systemless 0.1.126

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
//! Control Manager trap handlers.

use super::dispatch::{ControlAuxRecordState, ControlTrackingState};
use super::types::{decode_mac_roman_for_render, Rect, ShapeOp};
use crate::cpu::{CpuOps, Register};
use crate::memory::{globals::addr, MacMemoryBus, MemoryBus};
use crate::quickdraw::text::get_font_metrics;
use crate::ui_theme::ControlKind;
use crate::Result;

use std::sync::OnceLock;
static TRACE_CONTROLS: OnceLock<bool> = OnceLock::new();
fn trace_controls_enabled() -> bool {
    *TRACE_CONTROLS.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_CONTROLS").is_some())
}

impl super::TrapDispatcher {
    const LOWMEM_AUX_CTL_HEAD: u32 = 0x0CD4;
    const AUX_CTL_NEXT_OFFSET: u32 = 0;
    const AUX_CTL_OWNER_OFFSET: u32 = 4;
    const AUX_CTL_CTABLE_OFFSET: u32 = 8;
    const AUX_CTL_FLAGS_OFFSET: u32 = 12;
    const AUX_CTL_RESERVED_OFFSET: u32 = 14;
    const AUX_CTL_REFCON_OFFSET: u32 = 18;
    const AUX_CTL_RECORD_SIZE: u32 = 22;
    const INACTIVE_CONTROL_TITLE_RGB: [u16; 3] = [0xA1A1, 0xA1A1, 0xA1A1];

    fn control_trace_nonzero(value: u32) -> String {
        if value == 0 {
            "$00000000".to_string()
        } else {
            "$NONZERO".to_string()
        }
    }

    fn control_trace_control_fields(&self, bus: &MacMemoryBus, ctrl_handle: u32) -> String {
        let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);
        if ctrl_ptr == 0 {
            return "control_handle=$00000000 control_ptr=$00000000 rect=none visible=false hilite=none proc_id=none".to_string();
        }
        let top = bus.read_word(ctrl_ptr + 8) as i16;
        let left = bus.read_word(ctrl_ptr + 10) as i16;
        let bottom = bus.read_word(ctrl_ptr + 12) as i16;
        let right = bus.read_word(ctrl_ptr + 14) as i16;
        let vis = bus.read_byte(ctrl_ptr + 16);
        let hilite = bus.read_byte(ctrl_ptr + 17);
        let proc_id = self.control_proc_ids.get(&ctrl_ptr).copied().unwrap_or(0);
        format!(
            "control_handle={} control_ptr={} rect=({top},{left},{bottom},{right}) visible={} hilite={} proc_id={proc_id}",
            Self::control_trace_nonzero(ctrl_handle),
            Self::control_trace_nonzero(ctrl_ptr),
            vis == 255,
            hilite,
        )
    }

    fn record_trackcontrol_input_trace(
        &mut self,
        bus: &MacMemoryBus,
        action: &str,
        ctrl_handle: u32,
        start_pt: Option<(i16, i16)>,
        action_proc: u32,
        part: Option<u16>,
        highlighted_item: Option<i16>,
        outcome: &str,
    ) {
        if !self.input_trace_enabled {
            return;
        }
        let start = start_pt
            .map(|(v, h)| format!("({v},{h})"))
            .unwrap_or_else(|| "none".to_string());
        let part = part
            .map(|value| value.to_string())
            .unwrap_or_else(|| "pending".to_string());
        let highlighted = highlighted_item
            .map(|value| value.to_string())
            .unwrap_or_else(|| "none".to_string());
        // IM:I I-323 / MTE 1992 5-89..5-90: TrackControl takes the
        // mouse-down point in the control window's local coordinates and
        // returns the release part code, or 0 when no control part remains hit.
        self.record_input_trace_line(format!(
            "A968 action={} start={} action_proc={} live_mouse=({},{}) {} {} part={} highlighted_item={} outcome={}",
            action,
            start,
            Self::control_trace_nonzero(action_proc),
            self.mouse_pos.0,
            self.mouse_pos.1,
            self.input_trace_state_fields(),
            self.control_trace_control_fields(bus, ctrl_handle),
            part,
            highlighted,
            outcome,
        ));
    }

    fn control_tracking_button_down(&self, bus: &MacMemoryBus) -> bool {
        // TrackControl follows the mouse until button release (IM:I I-323).
        // MBState ($0172) is the classic low-memory button mirror (0=down,
        // $80=up), so guest callbacks/VBL tasks can hold or release tracking
        // between trap re-fires. Inside Macintosh Volume II, p. II-371.
        self.mouse_button || bus.read_byte(addr::MB_STATE) == 0x00
    }

    fn control_tracking_mouse_pos(&self, bus: &MacMemoryBus) -> (i16, i16) {
        // Mouse ($0830) is the current low-memory mouse Point. Prefer it when
        // a guest callback updates classic globals directly during tracking;
        // otherwise keep dispatcher-driven tests and host input authoritative.
        // Inside Macintosh Volume II, p. II-371; Volume III, p. III-446.
        let v = bus.read_word(addr::MOUSE_LOC2) as i16;
        let h = bus.read_word(addr::MOUSE_LOC2 + 2) as i16;
        if v != 0 || h != 0 {
            (v, h)
        } else {
            self.mouse_pos
        }
    }

    fn control_record_ptr(bus: &MacMemoryBus, ctrl_handle: u32) -> u32 {
        if ctrl_handle == 0 {
            0
        } else {
            bus.read_long(ctrl_handle)
        }
    }

    fn read_pascal_string(bus: &MacMemoryBus, str_ptr: u32) -> Vec<u8> {
        if str_ptr == 0 {
            return Vec::new();
        }

        let len = bus.read_byte(str_ptr) as usize;
        (0..len)
            .map(|i| bus.read_byte(str_ptr + 1 + i as u32))
            .collect()
    }

    fn write_pascal_string(bus: &mut MacMemoryBus, str_ptr: u32, bytes: &[u8]) {
        if str_ptr == 0 {
            return;
        }

        let len = bytes.len().min(255);
        bus.write_byte(str_ptr, len as u8);
        for (index, &byte) in bytes.iter().take(len).enumerate() {
            bus.write_byte(str_ptr + 1 + index as u32, byte);
        }
    }

    pub(crate) fn control_title_bytes(bus: &MacMemoryBus, ctrl_ptr: u32) -> Vec<u8> {
        Self::read_pascal_string(bus, ctrl_ptr + 40)
    }

    fn set_control_title_bytes(bus: &mut MacMemoryBus, ctrl_ptr: u32, bytes: &[u8]) {
        Self::write_pascal_string(bus, ctrl_ptr + 40, bytes);
    }

    fn control_def_proc_handle(&mut self, bus: &mut MacMemoryBus, proc_id: i16) -> u32 {
        if proc_id <= 0 {
            return 0;
        }

        let cdef_id = proc_id >> 4;
        self.find_resource_any(*b"CDEF", cdef_id)
            .map(|(_, ptr)| ptr)
            .map(|ptr| self.get_or_create_resource_handle(bus, *b"CDEF", cdef_id, ptr))
            .unwrap_or(0)
    }

    fn control_aux_reserved_value(&self, bus: &MacMemoryBus, ctrl_handle: u32) -> u32 {
        let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);
        let proc_id = self.control_proc_ids.get(&ctrl_ptr).copied().unwrap_or(0);
        u32::from((proc_id & 0xF) as u16) << 24
    }

    fn standard_testcontrol_part_code(&self, ctrl_ptr: u32) -> u16 {
        match self.control_proc_ids.get(&ctrl_ptr).copied().unwrap_or(0) {
            1 | 2 => 11, // inCheckBox for checkbox and radio-button variants
            _ => 10,     // inButton for push buttons and the current fallback path
        }
    }

    pub(crate) fn write_control_value(
        &mut self,
        bus: &mut MacMemoryBus,
        ctrl_handle: u32,
        value: i16,
    ) {
        let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);
        if ctrl_ptr == 0 {
            return;
        }
        if let Some((dlg_ptr, item_no)) = self.dialog_control_handles.get(&ctrl_handle).copied() {
            self.dialog_control_values.insert((dlg_ptr, item_no), value);
        }
        bus.write_word(ctrl_ptr + 18, value as u16);
    }

    fn sync_dialog_item_rect_for_control(&mut self, bus: &MacMemoryBus, ctrl_handle: u32) {
        let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);
        if ctrl_ptr == 0 {
            return;
        }
        let Some((dialog_ptr, item_no)) = self.dialog_control_handles.get(&ctrl_handle).copied()
        else {
            return;
        };
        let rect = (
            bus.read_word(ctrl_ptr + 8) as i16,
            bus.read_word(ctrl_ptr + 10) as i16,
            bus.read_word(ctrl_ptr + 12) as i16,
            bus.read_word(ctrl_ptr + 14) as i16,
        );
        let idx = (item_no as usize).wrapping_sub(1);
        if let Some(items) = self.dialog_items.get_mut(&dialog_ptr) {
            if idx < items.len() {
                items[idx].rect = rect;
            }
        }
        if let Some(tracking) = self.dialog_tracking.as_mut() {
            if tracking.dialog_ptr == dialog_ptr && idx < tracking.items.len() {
                tracking.items[idx].rect = rect;
            }
        }
    }

    pub(crate) fn popup_control_dropdown_rect(
        &self,
        bus: &MacMemoryBus,
        ctrl_ptr: u32,
        menu_idx: usize,
    ) -> (i16, i16, i16, i16) {
        let (_, _, screen_width, screen_height, _) = self.get_screen_params();
        let owner = bus.read_long(ctrl_ptr + 4);
        let (owner_top, owner_left, _, _) = if owner != 0 {
            Self::dialog_screen_bounds(bus, owner)
        } else {
            (0, 0, 0, 0)
        };
        let r_top = bus.read_word(ctrl_ptr + 8) as i16;
        let r_left = bus.read_word(ctrl_ptr + 10) as i16;
        let r_right = bus.read_word(ctrl_ptr + 14) as i16;
        let selected_value = bus.read_word(ctrl_ptr + 18) as i16;
        let selected_index = selected_value.max(0) as usize;
        let abs_top = owner_top + r_top;
        let abs_left = owner_left + r_left;

        let mut width = (r_right - r_left).max(80);
        if let Some(menu) = self.menus.get(menu_idx) {
            for item in &menu.items {
                let w = Self::fb_measure_string(&item.text, 0, 12)
                    + self.menu_item_width_extra(bus, item)
                    + 24;
                width = width.max(w);
            }
            let selected_item_offset = if selected_index >= 1 && selected_index <= menu.items.len()
            {
                menu.items
                    .iter()
                    .take(selected_index - 1)
                    .map(|item| self.menu_item_height(bus, item))
                    .sum::<i16>()
            } else {
                0
            };
            // The standard popup CDEF opens the live menu with the current
            // value's item aligned to the popup box, matching the Menu
            // Manager's PopUpMenuSelect(top, left, popUpItem) convention.
            let desired_top = abs_top - 1 - selected_item_offset;
            let height = (self.menu_items_height(bus, &menu.items) + 2).max(1);
            let clamped_top = if screen_height <= 0 {
                desired_top
            } else if height >= screen_height {
                0
            } else {
                desired_top.clamp(0, screen_height - height)
            };
            let bottom = if screen_height > 0 {
                (clamped_top + height).min(screen_height)
            } else {
                clamped_top + height
            };
            return (
                clamped_top,
                abs_left,
                bottom,
                (abs_left + width).min(screen_width),
            );
        }

        let desired_top = abs_top - 1;
        let height = 2;
        let clamped_top = if screen_height <= 0 {
            desired_top
        } else if height >= screen_height {
            0
        } else {
            desired_top.clamp(0, screen_height - height)
        };
        (
            clamped_top,
            abs_left,
            clamped_top + height,
            (abs_left + width).min(screen_width),
        )
    }

    fn control_tracking_item_at_point(
        &self,
        bus: &MacMemoryBus,
        mouse_x: i16,
        mouse_y: i16,
    ) -> i16 {
        let Some(tracking) = self.control_tracking.as_ref() else {
            return 0;
        };
        let (top, left, bottom, right) = tracking.dropdown_rect;
        if mouse_x < left || mouse_x >= right || mouse_y < top || mouse_y >= bottom {
            return 0;
        }
        let Some(menu) = self.menus.get(tracking.active_menu) else {
            return 0;
        };
        let mut item_top = top + 1;
        for (item_idx, item) in menu.items.iter().enumerate() {
            let item_bottom = item_top + self.menu_item_height(bus, item);
            if mouse_y >= item_top && mouse_y < item_bottom {
                if item.text == "-" || !item.enabled {
                    return 0;
                }
                return item_idx as i16 + 1;
            }
            item_top = item_bottom;
        }
        0
    }

    fn invert_control_tracking_item(&self, bus: &mut MacMemoryBus, item: i16) {
        let Some(tracking) = self.control_tracking.as_ref() else {
            return;
        };
        self.invert_dropdown_item_rect(bus, tracking.active_menu, tracking.dropdown_rect, item);
    }

    fn set_control_tracking_highlight(&mut self, bus: &mut MacMemoryBus, item: i16) {
        let Some(old_item) = self
            .control_tracking
            .as_ref()
            .map(|tracking| tracking.highlighted_item)
        else {
            return;
        };
        if old_item == item {
            return;
        }

        if self.ui_theme_id() == crate::ui_theme::UiThemeId::ClassicSystem7 {
            if old_item > 0 {
                self.invert_control_tracking_item(bus, old_item);
            }
            if let Some(tracking) = self.control_tracking.as_mut() {
                tracking.highlighted_item = item;
            }
            if item > 0 {
                self.invert_control_tracking_item(bus, item);
            }
            return;
        }

        let Some((active_menu, dropdown_rect)) = self.control_tracking.as_mut().map(|tracking| {
            tracking.highlighted_item = item;
            (tracking.active_menu, tracking.dropdown_rect)
        }) else {
            return;
        };
        self.draw_menu_dropdown(bus, active_menu, dropdown_rect);
    }

    fn finish_popup_control_tracking<C: CpuOps>(
        &mut self,
        cpu: &mut C,
        bus: &mut MacMemoryBus,
        selected_item: i16,
    ) {
        let Some(tracking) = self.control_tracking.take() else {
            return;
        };
        self.restore_dropdown_pixels(bus, tracking.dropdown_rect, &tracking.saved_pixels);

        let part = if selected_item > 0 {
            self.write_control_value(bus, tracking.ctrl_handle, selected_item);
            self.draw_control(cpu, bus, tracking.ctrl_ptr);
            10u16
        } else {
            0u16
        };
        self.record_trackcontrol_input_trace(
            bus,
            "tracking_finish",
            tracking.ctrl_handle,
            None,
            0,
            Some(part),
            Some(selected_item),
            if selected_item > 0 {
                "popup_item_selected"
            } else {
                "popup_no_selection"
            },
        );
        bus.write_word(tracking.stack_ptr + 12, part);
        cpu.write_reg(Register::A7, tracking.stack_ptr + 12);
    }

    fn simple_control_tracking_inside(&self, bus: &MacMemoryBus) -> bool {
        let Some(tracking) = self.control_tracking.as_ref() else {
            return false;
        };
        let (top, left, bottom, right) = tracking.simple_screen_rect;
        let (mouse_v, mouse_h) = self.control_tracking_mouse_pos(bus);
        mouse_v >= top && mouse_v < bottom && mouse_h >= left && mouse_h < right
    }

    fn redraw_simple_control_tracking_state<C: CpuOps>(
        &mut self,
        cpu: &mut C,
        bus: &mut MacMemoryBus,
        highlighted: bool,
    ) {
        let Some((ctrl_ptr, saved_hilite)) = self
            .control_tracking
            .as_ref()
            .map(|tracking| (tracking.ctrl_ptr, tracking.saved_hilite))
        else {
            return;
        };
        bus.write_byte(ctrl_ptr + 17, if highlighted { 1 } else { saved_hilite });
        self.draw_control(cpu, bus, ctrl_ptr);
        if let Some(tracking) = self.control_tracking.as_mut() {
            tracking.simple_highlighted = highlighted;
        }
    }

    fn finish_simple_control_tracking<C: CpuOps>(
        &mut self,
        cpu: &mut C,
        bus: &mut MacMemoryBus,
        inside: bool,
    ) {
        let Some(tracking) = self.control_tracking.take() else {
            return;
        };
        bus.write_byte(tracking.ctrl_ptr + 17, tracking.saved_hilite);
        self.draw_control(cpu, bus, tracking.ctrl_ptr);

        let part = if inside { tracking.simple_part } else { 0 };
        self.record_trackcontrol_input_trace(
            bus,
            "tracking_finish",
            tracking.ctrl_handle,
            None,
            0,
            Some(part),
            None,
            if inside {
                "simple_part_selected"
            } else {
                "simple_no_selection"
            },
        );
        bus.write_word(tracking.stack_ptr + 12, part);
        cpu.write_reg(Register::A7, tracking.stack_ptr + 12);
    }

    fn standard_scrollbar_testcontrol_part_code(
        &self,
        bus: &MacMemoryBus,
        ctrl_ptr: u32,
        pt_v: i16,
        pt_h: i16,
    ) -> u16 {
        let top = bus.read_word(ctrl_ptr + 8) as i16;
        let left = bus.read_word(ctrl_ptr + 10) as i16;
        let bottom = bus.read_word(ctrl_ptr + 12) as i16;
        let right = bus.read_word(ctrl_ptr + 14) as i16;
        let value = bus.read_word(ctrl_ptr + 18) as i16;
        let min = bus.read_word(ctrl_ptr + 20) as i16;
        let max = bus.read_word(ctrl_ptr + 22) as i16;

        if min >= max {
            return 0;
        }

        let is_vertical = (bottom - top) > (right - left);
        let arrow_len = 16i16.min(if is_vertical {
            bottom - top
        } else {
            right - left
        });
        let range = i32::from(max) - i32::from(min);
        if range <= 0 {
            return 0;
        }
        let value_clamped = (i32::from(value) - i32::from(min)).clamp(0, range);
        let thumb_len = 16i16.min(if is_vertical {
            (bottom - top) - arrow_len * 2
        } else {
            (right - left) - arrow_len * 2
        });
        if thumb_len <= 0 {
            return 0;
        }

        if is_vertical {
            let track_top = top + arrow_len;
            let track_bottom = bottom - arrow_len;
            let track_len = track_bottom - track_top;
            let travel = i32::from(track_len - thumb_len);
            if travel < 0 {
                return 0;
            }
            let thumb_top = track_top + ((value_clamped * travel) / range) as i16;
            let thumb_bottom = thumb_top + thumb_len;
            if pt_v < track_top {
                20
            } else if pt_v >= track_bottom {
                21
            } else if pt_v < thumb_top {
                22
            } else if pt_v < thumb_bottom {
                129
            } else {
                23
            }
        } else {
            let track_left = left + arrow_len;
            let track_right = right - arrow_len;
            let track_len = track_right - track_left;
            let travel = i32::from(track_len - thumb_len);
            if travel < 0 {
                return 0;
            }
            let thumb_left = track_left + ((value_clamped * travel) / range) as i16;
            let thumb_right = thumb_left + thumb_len;
            if pt_h < track_left {
                20
            } else if pt_h >= track_right {
                21
            } else if pt_h < thumb_left {
                22
            } else if pt_h < thumb_right {
                129
            } else {
                23
            }
        }
    }

    fn sync_control_aux_head_lowmem(&self, bus: &mut MacMemoryBus) {
        bus.write_long(Self::LOWMEM_AUX_CTL_HEAD, self.control_aux_head);
    }

    fn default_control_color_table_handle(&mut self, bus: &mut MacMemoryBus) -> u32 {
        let gd_handle = self.ensure_main_gdevice(bus);
        let gd_ptr = bus.read_long(gd_handle);
        let gd_pixmap_handle = bus.read_long(gd_ptr + 22);
        let gd_pixmap_ptr = bus.read_long(gd_pixmap_handle);
        bus.read_long(gd_pixmap_ptr + 42)
    }

    pub(crate) fn ensure_control_aux_record(
        &mut self,
        bus: &mut MacMemoryBus,
        ctrl_handle: u32,
    ) -> u32 {
        if ctrl_handle == 0 {
            return 0;
        }

        let default_ctab = self.default_control_color_table_handle(bus);
        if let Some(state) = self.control_aux_records.get(&ctrl_handle).copied() {
            let aux_ptr = bus.read_long(state.handle);
            if aux_ptr != 0 {
                bus.write_long(aux_ptr + Self::AUX_CTL_OWNER_OFFSET, ctrl_handle);
                if bus.read_long(aux_ptr + Self::AUX_CTL_CTABLE_OFFSET) == 0 {
                    bus.write_long(aux_ptr + Self::AUX_CTL_CTABLE_OFFSET, default_ctab);
                }
                bus.write_word(aux_ptr + Self::AUX_CTL_FLAGS_OFFSET, 0);
                bus.write_long(
                    aux_ptr + Self::AUX_CTL_RESERVED_OFFSET,
                    self.control_aux_reserved_value(bus, ctrl_handle),
                );
            }
            return state.handle;
        }

        let aux_ptr = bus.alloc(Self::AUX_CTL_RECORD_SIZE);
        let aux_handle = bus.alloc(4);
        bus.write_long(aux_handle, aux_ptr);
        bus.write_long(aux_ptr + Self::AUX_CTL_NEXT_OFFSET, self.control_aux_head);
        bus.write_long(aux_ptr + Self::AUX_CTL_OWNER_OFFSET, ctrl_handle);
        bus.write_long(aux_ptr + Self::AUX_CTL_CTABLE_OFFSET, default_ctab);
        bus.write_word(aux_ptr + Self::AUX_CTL_FLAGS_OFFSET, 0);
        bus.write_long(
            aux_ptr + Self::AUX_CTL_RESERVED_OFFSET,
            self.control_aux_reserved_value(bus, ctrl_handle),
        );
        bus.write_long(aux_ptr + Self::AUX_CTL_REFCON_OFFSET, 0);
        self.control_aux_head = aux_handle;
        self.sync_control_aux_head_lowmem(bus);
        self.control_aux_records
            .insert(ctrl_handle, ControlAuxRecordState { handle: aux_handle });
        aux_handle
    }

    pub(crate) fn release_control_aux_record(&mut self, bus: &mut MacMemoryBus, ctrl_handle: u32) {
        let Some(state) = self.control_aux_records.remove(&ctrl_handle) else {
            return;
        };

        let mut prev_handle = 0u32;
        let mut cur_handle = self.control_aux_head;
        while cur_handle != 0 {
            let cur_ptr = bus.read_long(cur_handle);
            if cur_ptr == 0 {
                break;
            }
            let next_handle = bus.read_long(cur_ptr + Self::AUX_CTL_NEXT_OFFSET);
            if cur_handle == state.handle {
                if prev_handle == 0 {
                    self.control_aux_head = next_handle;
                } else {
                    let prev_ptr = bus.read_long(prev_handle);
                    if prev_ptr != 0 {
                        bus.write_long(prev_ptr + Self::AUX_CTL_NEXT_OFFSET, next_handle);
                    }
                }
                break;
            }
            prev_handle = cur_handle;
            cur_handle = next_handle;
        }
        self.sync_control_aux_head_lowmem(bus);

        let aux_ptr = bus.read_long(state.handle);
        if aux_ptr != 0 {
            bus.free(aux_ptr);
        }
        bus.free(state.handle);
    }

    pub(crate) fn control_aux_state(&self, ctrl_handle: u32) -> Option<ControlAuxRecordState> {
        self.control_aux_records.get(&ctrl_handle).copied()
    }

    pub(crate) fn initialize_control_record(
        &mut self,
        bus: &mut MacMemoryBus,
        ctrl_ptr: u32,
        window_ptr: u32,
        bounds: (i16, i16, i16, i16),
        title: &[u8],
        visible: bool,
        value: i16,
        min: i16,
        max: i16,
        proc_id: i16,
        ref_con: u32,
    ) {
        bus.write_long(ctrl_ptr, 0); // nextControl
        bus.write_long(ctrl_ptr + 4, window_ptr); // contrlOwner
        bus.write_word(ctrl_ptr + 8, bounds.0 as u16);
        bus.write_word(ctrl_ptr + 10, bounds.1 as u16);
        bus.write_word(ctrl_ptr + 12, bounds.2 as u16);
        bus.write_word(ctrl_ptr + 14, bounds.3 as u16);
        bus.write_byte(ctrl_ptr + 16, if visible { 255 } else { 0 });
        bus.write_byte(ctrl_ptr + 17, 0); // contrlHilite
        bus.write_word(ctrl_ptr + 18, value as u16);
        bus.write_word(ctrl_ptr + 20, min as u16);
        bus.write_word(ctrl_ptr + 22, max as u16);
        let def_proc_handle = self.control_def_proc_handle(bus, proc_id);
        bus.write_long(ctrl_ptr + 24, def_proc_handle);
        let contrl_data = if Self::is_popup_menu_proc_id(proc_id) {
            self.create_popup_control_private_data(bus, min)
        } else {
            0
        };
        bus.write_long(ctrl_ptr + 28, contrl_data);
        bus.write_long(ctrl_ptr + 32, 0); // contrlAction
        bus.write_long(ctrl_ptr + 36, ref_con);
        Self::set_control_title_bytes(bus, ctrl_ptr, title);
        self.control_proc_ids.insert(ctrl_ptr, proc_id);
    }

    fn create_popup_control_private_data(&mut self, bus: &mut MacMemoryBus, menu_id: i16) -> u32 {
        let menu_handle = self.create_popup_menu_handle(bus, menu_id);
        if menu_handle == 0 {
            return 0;
        }

        let data_ptr = bus.alloc(8);
        let data_handle = bus.alloc(4);
        if data_ptr == 0 || data_handle == 0 {
            return 0;
        }

        // IM:VI 1991 pp. 3-18..3-19: popup control contrlData is a
        // handle to popupPrivateData { mHandle: MenuHandle, mID: Integer,
        // mPrivate: reserved bytes }.
        bus.write_long(data_handle, data_ptr);
        bus.write_long(data_ptr, menu_handle);
        bus.write_word(data_ptr + 4, menu_id as u16);
        bus.write_word(data_ptr + 6, 0);
        self.ptr_to_handle.insert(data_ptr, data_handle);
        data_handle
    }

    pub(crate) fn popup_control_menu_id(
        &self,
        bus: &MacMemoryBus,
        ctrl_ptr: u32,
        fallback_menu_id: i16,
    ) -> i16 {
        let data_handle = bus.read_long(ctrl_ptr + 28);
        if data_handle != 0 {
            let data_ptr = bus.read_long(data_handle);
            if data_ptr != 0 && bus.get_alloc_size(data_ptr).unwrap_or(0) >= 6 {
                let menu_handle = bus.read_long(data_ptr);
                let menu_id = bus.read_word(data_ptr + 4) as i16;
                if menu_id != 0
                    && self
                        .menus
                        .iter()
                        .any(|menu| menu.id == menu_id && menu.handle == menu_handle)
                {
                    return menu_id;
                }
            }
        }
        fallback_menu_id
    }

    /// Draw a single control based on its procID, using QuickDraw primitives
    /// so the output matches real Mac CDEF rendering.
    /// Coordinates in the control record are local to the owning window.
    /// QuickDraw shape methods handle the local→screen conversion via the port.
    pub(crate) fn draw_control<C: CpuOps>(
        &mut self,
        cpu: &mut C,
        bus: &mut MacMemoryBus,
        ctrl_ptr: u32,
    ) {
        if ctrl_ptr == 0 {
            return;
        }
        let vis = bus.read_byte(ctrl_ptr + 16);
        if vis != 255 {
            return;
        }

        let r_top = bus.read_word(ctrl_ptr + 8) as i16;
        let r_left = bus.read_word(ctrl_ptr + 10) as i16;
        let r_bottom = bus.read_word(ctrl_ptr + 12) as i16;
        let r_right = bus.read_word(ctrl_ptr + 14) as i16;
        let hilite = bus.read_byte(ctrl_ptr + 17);
        let value = bus.read_word(ctrl_ptr + 18) as i16;
        let min = bus.read_word(ctrl_ptr + 20) as i16;
        let max = bus.read_word(ctrl_ptr + 22) as i16;
        let title_bytes = Self::control_title_bytes(bus, ctrl_ptr);
        let title = decode_mac_roman_for_render(&title_bytes);

        let proc_id = self.control_proc_ids.get(&ctrl_ptr).copied().unwrap_or(0);

        // Save pen state, set to defaults (PenNormal)
        let saved_pn_size = self.pn_size;
        let saved_pn_mode = self.pn_mode;
        let saved_pn_pat = self.pn_pat;
        self.pn_size = (1, 1);
        self.pn_mode = 8; // patCopy
        self.pn_pat = [0xFF; 8]; // solid black

        // Local rect for QuickDraw primitives
        let r = Rect {
            top: r_top,
            left: r_left,
            bottom: r_bottom,
            right: r_right,
        };

        // Screen coordinates for fb_draw_string (text rendering)
        let window_ptr = bus.read_long(ctrl_ptr + 4);
        let (scr_top, scr_left, _, _) = Self::dialog_screen_bounds(bus, window_ptr);
        let abs_top = scr_top + r_top;
        let abs_left = scr_left + r_left;
        let abs_bottom = scr_top + r_bottom;
        let abs_right = scr_left + r_right;

        match proc_id {
            0 => {
                // pushButProc — push button
                self.draw_push_button_control(
                    cpu, bus, &r, abs_top, abs_left, abs_bottom, abs_right, hilite, &title,
                );
            }
            1 => {
                // checkBoxProc — checkbox
                let checked = value != 0;
                let height = r_bottom - r_top;
                let box_size = 12i16;
                let box_top = r_top + (height - box_size) / 2;
                let box_left = r_left + 2;
                let box_r = Rect {
                    top: box_top,
                    left: box_left,
                    bottom: box_top + box_size,
                    right: box_left + box_size,
                };

                if !self.draw_theme_control_chrome(
                    bus,
                    ControlKind::Checkbox,
                    scr_top + box_top,
                    scr_left + box_left,
                    scr_top + box_top + box_size,
                    scr_left + box_left + box_size,
                    hilite != 255,
                    hilite == 1,
                    checked,
                    false,
                ) {
                    // Erase checkbox area
                    self.draw_rect(cpu, bus, &box_r, ShapeOp::Erase);
                    // Frame checkbox border
                    self.draw_rect(cpu, bus, &box_r, ShapeOp::Frame);

                    if checked {
                        // Draw X inside the checkbox
                        self.draw_checkbox_x(bus, scr_top + box_top, scr_left + box_left, box_size);
                    }
                }

                // Draw label text to the right of the checkbox
                let font_id = 0i16;
                let font_size = 12i16;
                let metrics = get_font_metrics(font_id, font_size);
                let text_x = scr_left + box_left + box_size + 4;
                let text_y = scr_top + r_top + (height + metrics.ascent - metrics.descent) / 2;
                self.draw_control_label_text(
                    bus,
                    abs_top,
                    scr_left + box_left + box_size + 1,
                    abs_bottom,
                    abs_right,
                    text_x,
                    text_y,
                    &title,
                    font_id,
                    font_size,
                    hilite == 255,
                );

                if self.ui_theme_id() == crate::ui_theme::UiThemeId::ClassicSystem7 && hilite == 1 {
                    // Pressed: invert the checkbox box area
                    self.draw_rect(cpu, bus, &box_r, ShapeOp::Invert);
                }
            }
            2 => {
                // radioButProc — radio button
                let selected = value != 0;
                let height = r_bottom - r_top;
                let circle_size = 12i16;
                let circle_top = r_top + (height - circle_size) / 2;
                let circle_left = r_left + 2;
                let circle_r = Rect {
                    top: circle_top,
                    left: circle_left,
                    bottom: circle_top + circle_size,
                    right: circle_left + circle_size,
                };

                if !self.draw_theme_control_chrome(
                    bus,
                    ControlKind::RadioButton,
                    scr_top + circle_top,
                    scr_left + circle_left,
                    scr_top + circle_top + circle_size,
                    scr_left + circle_left + circle_size,
                    hilite != 255,
                    hilite == 1,
                    selected,
                    false,
                ) {
                    // Erase circle area
                    self.draw_oval(cpu, bus, &circle_r, ShapeOp::Erase);
                    // Frame circle
                    self.draw_oval(cpu, bus, &circle_r, ShapeOp::Frame);

                    if selected {
                        // Fill inner circle (smaller by 3px on each side)
                        let inner_r = Rect {
                            top: circle_top + 3,
                            left: circle_left + 3,
                            bottom: circle_top + circle_size - 3,
                            right: circle_left + circle_size - 3,
                        };
                        self.draw_oval(cpu, bus, &inner_r, ShapeOp::Paint);
                    }
                }

                // Draw label text to the right of the circle
                let font_id = 0i16;
                let font_size = 12i16;
                let metrics = get_font_metrics(font_id, font_size);
                let text_x = scr_left + circle_left + circle_size + 4;
                let text_y = scr_top + r_top + (height + metrics.ascent - metrics.descent) / 2;
                self.draw_control_label_text(
                    bus,
                    abs_top,
                    scr_left + circle_left + circle_size + 1,
                    abs_bottom,
                    abs_right,
                    text_x,
                    text_y,
                    &title,
                    font_id,
                    font_size,
                    hilite == 255,
                );

                if self.ui_theme_id() == crate::ui_theme::UiThemeId::ClassicSystem7 && hilite == 1 {
                    // Pressed: invert the circle area
                    self.draw_oval(cpu, bus, &circle_r, ShapeOp::Invert);
                }
            }
            16 => {
                // scrollBarProc — scroll bar (uses fb_* functions with screen coords)
                self.draw_scroll_bar(
                    bus, abs_top, abs_left, abs_bottom, abs_right, value, min, max, hilite,
                );
            }
            proc_id if Self::is_popup_menu_proc_id(proc_id) => {
                // popupMenuProc — draw the CNTL-backed popup button using
                // the selected MENU resource item.
                let menu_id = self.popup_control_menu_id(bus, ctrl_ptr, min);
                let selected = value.max(1) as usize;
                let item_title = self.popup_menu_item_title(bus, menu_id, selected);
                let (draw_top, draw_left, draw_bottom, draw_right) = self.popup_control_box_rect(
                    bus, abs_top, abs_left, abs_bottom, abs_right, menu_id, max, proc_id,
                );
                self.draw_popup_control_label(
                    bus,
                    abs_top,
                    abs_left,
                    abs_bottom,
                    draw_left,
                    &title,
                    hilite != 255,
                );
                // HIG 1992 p. 87 describes the closed pop-up menu as the
                // rectangle/triangle control; MTE 1992 p. 6-98 says
                // HiliteControl dims inactive pop-up menus. Keep part-code
                // and menu tracking behavior unchanged while routing that
                // semantic state to non-classic theme chrome.
                self.draw_popup_control_with_state(
                    bus,
                    draw_top,
                    draw_left,
                    draw_bottom,
                    draw_right,
                    &item_title.unwrap_or_default(),
                    hilite != 255,
                    hilite == 1,
                );
            }
            _ => {
                if trace_controls_enabled() {
                    eprintln!(
                        "[CONTROL] Unknown procID {} for control at ${:08X}",
                        proc_id, ctrl_ptr
                    );
                }
                // IM:I I-328..I-331 defines custom controls as CDEF-backed
                // drawCntl/testCntl implementations selected by procID. Systemless
                // cannot execute arbitrary guest CDEFs here, so preserve the
                // ControlRecord title and rectangle as a generic button fallback.
                if !self.draw_picture_title_control(
                    bus,
                    abs_top,
                    abs_left,
                    abs_bottom,
                    abs_right,
                    hilite,
                    value,
                    &title_bytes,
                ) {
                    self.draw_push_button_control(
                        cpu, bus, &r, abs_top, abs_left, abs_bottom, abs_right, hilite, &title,
                    );
                }
            }
        }

        // Restore pen state
        self.pn_size = saved_pn_size;
        self.pn_mode = saved_pn_mode;
        self.pn_pat = saved_pn_pat;
    }

    fn draw_picture_title_control(
        &mut self,
        bus: &mut MacMemoryBus,
        abs_top: i16,
        abs_left: i16,
        abs_bottom: i16,
        abs_right: i16,
        hilite: u8,
        value: i16,
        title_bytes: &[u8],
    ) -> bool {
        let Some((off_id, on_id)) = Self::picture_ids_from_control_title(title_bytes) else {
            return false;
        };
        let Some((_, off_pic_ptr)) = self.find_resource_any(*b"PICT", off_id) else {
            return false;
        };
        let Some((_, on_pic_ptr)) = self.find_resource_any(*b"PICT", on_id) else {
            return false;
        };

        // IM:I I-317..I-331 says custom CDEFs interpret ControlRecord
        // fields, and IM:I I-369 says DrawPicture scales a Picture into a
        // destination Rect. If a custom control's title bytes are exactly two
        // valid PICT resource IDs, use those resources as a generic CDEF
        // fallback and leave all other custom controls on the text/button path.
        let pic_ptr = if hilite == 1 || value != 0 {
            on_pic_ptr
        } else {
            off_pic_ptr
        };
        let device_ct_seed =
            Self::ctab_seed(bus, self.current_gdevice_ctab_handle(bus)).unwrap_or(0);
        let (drawn, _) = super::pict::draw_picture(
            bus,
            pic_ptr,
            abs_top,
            abs_left,
            abs_bottom,
            abs_right,
            self.screen_mode,
            &self.device_clut,
            device_ct_seed,
            None,
        );
        if drawn && hilite == 255 {
            self.dim_rect(bus, abs_top, abs_left, abs_bottom, abs_right);
        }
        drawn
    }

    fn picture_ids_from_control_title(title_bytes: &[u8]) -> Option<(i16, i16)> {
        (title_bytes.len() == 4).then(|| {
            (
                i16::from_be_bytes([title_bytes[0], title_bytes[1]]),
                i16::from_be_bytes([title_bytes[2], title_bytes[3]]),
            )
        })
    }

    fn draw_push_button_control<C: CpuOps>(
        &mut self,
        cpu: &mut C,
        bus: &mut MacMemoryBus,
        r: &Rect,
        abs_top: i16,
        abs_left: i16,
        abs_bottom: i16,
        abs_right: i16,
        hilite: u8,
        title: &str,
    ) {
        if self.draw_theme_push_button_chrome(
            bus,
            abs_top,
            abs_left,
            abs_bottom,
            abs_right,
            hilite != 255,
            hilite == 1,
            false,
        ) {
            self.draw_control_text(bus, abs_top, abs_left, abs_bottom, abs_right, title);
            if hilite == 255 {
                self.dim_rect(bus, abs_top, abs_left, abs_bottom, abs_right);
            }
            return;
        }

        // Standard CDEF uses FrameRoundRect with oval 10x10.
        // Macintosh Revealed Volume One, p. 412.
        let oval: i16 = 10;

        // Erase first so a re-draw (e.g. from SetCTitle) overwrites the old title
        // instead of overlapping the new one. Checkbox / radio CDEFs already do this.
        self.draw_round_rect(cpu, bus, r, oval, oval, ShapeOp::Erase);
        self.draw_round_rect(cpu, bus, r, oval, oval, ShapeOp::Frame);

        self.draw_control_text(bus, abs_top, abs_left, abs_bottom, abs_right, title);

        if hilite == 1 {
            // Pressed: invert the interior.
            let inv = Rect {
                top: r.top + 1,
                left: r.left + 1,
                bottom: r.bottom - 1,
                right: r.right - 1,
            };
            let inv_oval = (oval - 2).max(0);
            self.draw_round_rect(cpu, bus, &inv, inv_oval, inv_oval, ShapeOp::Invert);
        } else if hilite == 255 {
            // Inactive: dim by clearing every other pixel to white.
            self.dim_rect(bus, abs_top, abs_left, abs_bottom, abs_right);
        }
    }

    /// Draw centered text for a push button control using fb_draw_string.
    fn draw_control_text(
        &self,
        bus: &mut MacMemoryBus,
        abs_top: i16,
        abs_left: i16,
        abs_bottom: i16,
        abs_right: i16,
        title: &str,
    ) {
        let (screen_base, row_bytes, screen_width, screen_height, pixel_size) =
            self.get_screen_params();
        let font_id = 0i16; // Chicago (system font)
        let font_size = 12i16;
        let metrics = get_font_metrics(font_id, font_size);
        let text_w = Self::fb_measure_string(title, font_id, font_size);
        let text_x = abs_left + (abs_right - abs_left - text_w) / 2;
        let text_y = abs_top
            + (abs_bottom - abs_top - (metrics.ascent + metrics.descent)) / 2
            + metrics.ascent;
        Self::fb_draw_string(
            bus,
            screen_base,
            row_bytes,
            pixel_size,
            screen_width,
            screen_height,
            text_x,
            text_y,
            title,
            font_id,
            font_size,
        );
    }

    fn draw_control_label_text(
        &self,
        bus: &mut MacMemoryBus,
        label_top: i16,
        label_left: i16,
        label_bottom: i16,
        label_right: i16,
        text_x: i16,
        text_y: i16,
        title: &str,
        font_id: i16,
        font_size: i16,
        inactive: bool,
    ) {
        let (screen_base, row_bytes, screen_width, screen_height, pixel_size) =
            self.get_screen_params();
        if inactive && pixel_size == 8 {
            // Control drawing writes directly to the screen framebuffer, so
            // resolve against the same live device CLUT used by screenshots
            // instead of TheGDevice, which games may leave on an offscreen
            // palette while redrawing dialogs.
            let [r, g, b] = Self::INACTIVE_CONTROL_TITLE_RGB;
            let gray_index = super::pict::closest_clut_index(r, g, b, &self.device_clut);
            Self::fb_draw_string_styled_index(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                text_x,
                text_y,
                title,
                font_id,
                font_size,
                0,
                gray_index,
            );
            return;
        }

        Self::fb_draw_string(
            bus,
            screen_base,
            row_bytes,
            pixel_size,
            screen_width,
            screen_height,
            text_x,
            text_y,
            title,
            font_id,
            font_size,
        );
        if inactive {
            // MTE 1992 p. 5-13 describes inactive controls as dimmed; when
            // no indexed-gray device color is available, preserve the older
            // monochrome CDEF fallback by pattern-dimming only the title.
            self.dim_rect(bus, label_top, label_left, label_bottom, label_right);
        }
    }

    /// Draw the X mark inside a checkbox at screen coordinates.
    /// System 7.5.3 checkbox X spans the full interior diagonal (i=1..size-1),
    /// starting one pixel inside the box border on each side.
    /// Inside Macintosh Volume I, I-322 figure 27.
    fn draw_checkbox_x(
        &self,
        bus: &mut MacMemoryBus,
        box_top_screen: i16,
        box_left_screen: i16,
        box_size: i16,
    ) {
        let (screen_base, row_bytes, screen_width, screen_height, pixel_size) =
            self.get_screen_params();
        for i in 1..box_size - 1 {
            Self::fb_set_pixel(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                box_left_screen + i,
                box_top_screen + i,
                true,
            );
            Self::fb_set_pixel(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                box_left_screen + box_size - 1 - i,
                box_top_screen + i,
                true,
            );
        }
    }

    /// Dim a rectangular area with a 50% gray pattern (checkerboard).
    /// Used for inactive (hilite=255) controls.
    pub(crate) fn dim_rect(
        &self,
        bus: &mut MacMemoryBus,
        top: i16,
        left: i16,
        bottom: i16,
        right: i16,
    ) {
        let (screen_base, row_bytes, screen_width, screen_height, pixel_size) =
            self.get_screen_params();
        for y in top..bottom {
            if y < 0 || y >= screen_height {
                continue;
            }
            for x in left..right {
                if x < 0 || x >= screen_width {
                    continue;
                }
                // Checkerboard pattern: clear every other pixel to white
                if (x + y) & 1 == 0 {
                    Self::fb_set_pixel(
                        bus,
                        screen_base,
                        row_bytes,
                        pixel_size,
                        screen_width,
                        screen_height,
                        x,
                        y,
                        false,
                    );
                }
            }
        }
    }

    /// Draw a scroll bar control.
    /// Inside Macintosh Volume I, I-332 (scroll bar CDEF)
    pub(crate) fn draw_scroll_bar(
        &self,
        bus: &mut MacMemoryBus,
        top: i16,
        left: i16,
        bottom: i16,
        right: i16,
        value: i16,
        min: i16,
        max: i16,
        hilite: u8,
    ) {
        // IM:I I-332 / MTE 1992 5-58..5-61 define scroll-bar CDEF state in
        // terms of orientation, value range, arrows, page regions, and the
        // scroll box. Theme providers can own those pixels without changing
        // ControlRecord fields, hit testing, or guest-visible part codes.
        if self.draw_theme_scrollbar_chrome(bus, top, left, bottom, right, value, min, max, hilite)
        {
            return;
        }

        let (screen_base, row_bytes, screen_width, screen_height, pixel_size) =
            self.get_screen_params();
        let is_vertical = (bottom - top) > (right - left);
        let is_inactive = hilite == 255 || min >= max;

        // Draw outer frame
        self.draw_rect_border(bus, top, left, bottom, right);

        if is_inactive {
            // Inactive: white fill, arrow box dividers, arrow shapes (no shadow/track/thumb)
            Self::fb_fill_rect(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                top + 1,
                left + 1,
                bottom - 1,
                right - 1,
                false,
            );
            if is_vertical {
                let arrow_h = 16i16.min(bottom - top);
                // Divider lines
                self.draw_hline(bus, top + arrow_h - 1, left, right);
                self.draw_hline(bus, bottom - arrow_h, left, right);
                // Arrow shapes (14x14 content, no inner shadow)
                self.draw_scroll_arrow_inactive(bus, top + 1, left + 1, 0); // up
                self.draw_scroll_arrow_inactive(bus, bottom - arrow_h + 1, left + 1, 1);
            // down
            } else {
                let arrow_w = 16i16.min(right - left);
                // Divider lines
                self.draw_vline(bus, left + arrow_w - 1, top, bottom);
                self.draw_vline(bus, right - arrow_w, top, bottom);
                // Arrow shapes
                self.draw_scroll_arrow_inactive(bus, top + 1, left + 1, 2); // left
                self.draw_scroll_arrow_inactive(bus, top + 1, right - arrow_w + 1, 3);
                // right
            }
            return;
        }

        if is_vertical {
            let arrow_h = 16i16.min(bottom - top);

            // Up arrow box
            self.draw_rect_border(bus, top, left, top + arrow_h, right);
            // White fill inside arrow box
            Self::fb_fill_rect(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                top + 1,
                left + 1,
                top + arrow_h - 1,
                right - 1,
                false,
            );
            // Inner shadow: right line at right-2, bottom line at top+arrow_h-2
            Self::fb_fill_rect(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                top + 1,
                right - 2,
                top + arrow_h - 1,
                right - 1,
                true,
            );
            Self::fb_fill_rect(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                top + arrow_h - 2,
                left + 1,
                top + arrow_h - 1,
                right - 1,
                true,
            );
            // Up arrow glyph
            self.draw_scroll_arrow(bus, top + 1, left + 1, 0); // up

            // Down arrow box
            let da_top = bottom - arrow_h;
            self.draw_rect_border(bus, da_top, left, bottom, right);
            Self::fb_fill_rect(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                da_top + 1,
                left + 1,
                bottom - 1,
                right - 1,
                false,
            );
            // Inner shadow
            Self::fb_fill_rect(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                da_top + 1,
                right - 2,
                bottom - 1,
                right - 1,
                true,
            );
            Self::fb_fill_rect(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                bottom - 2,
                left + 1,
                bottom - 1,
                right - 1,
                true,
            );
            // Down arrow glyph
            self.draw_scroll_arrow(bus, da_top + 1, left + 1, 1); // down

            // Track area between arrows
            let track_top = top + arrow_h;
            let track_bottom = bottom - arrow_h;
            if track_top < track_bottom {
                // Fill track with ltGray pattern
                self.fill_scroll_track(bus, track_top, left + 1, track_bottom, right - 1);

                // Draw thumb (fixed 16px height)
                let track_len = track_bottom - track_top;
                let thumb_h = 16i16.min(track_len);
                let range = (max - min).max(1) as i32;
                let val_clamped = (value - min).max(0).min(max - min) as i32;
                let travel = (track_len - thumb_h) as i32;
                let thumb_top = track_top + ((val_clamped * travel) / range) as i16;
                let thumb_bottom = thumb_top + thumb_h;

                // White fill for thumb
                Self::fb_fill_rect(
                    bus,
                    screen_base,
                    row_bytes,
                    pixel_size,
                    screen_width,
                    screen_height,
                    thumb_top,
                    left + 1,
                    thumb_bottom,
                    right - 1,
                    false,
                );
                // Thumb border
                self.draw_rect_border(bus, thumb_top, left, thumb_bottom, right);
                // Thumb inner right shadow
                Self::fb_fill_rect(
                    bus,
                    screen_base,
                    row_bytes,
                    pixel_size,
                    screen_width,
                    screen_height,
                    thumb_top + 1,
                    right - 2,
                    thumb_bottom - 1,
                    right - 1,
                    true,
                );
                // Thumb grip lines (4 horizontal lines, 6px wide, centered)
                self.draw_thumb_grip_lines_v(bus, thumb_top, left, right);
            }
        } else {
            // Horizontal scroll bar
            let arrow_w = 16i16.min(right - left);

            // Left arrow box
            self.draw_rect_border(bus, top, left, bottom, left + arrow_w);
            Self::fb_fill_rect(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                top + 1,
                left + 1,
                bottom - 1,
                left + arrow_w - 1,
                false,
            );
            // Inner shadow
            Self::fb_fill_rect(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                top + 1,
                left + arrow_w - 2,
                bottom - 1,
                left + arrow_w - 1,
                true,
            );
            Self::fb_fill_rect(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                bottom - 2,
                left + 1,
                bottom - 1,
                left + arrow_w - 1,
                true,
            );
            // Left arrow glyph
            self.draw_scroll_arrow(bus, top + 1, left + 1, 2); // left

            // Right arrow box
            let ra_left = right - arrow_w;
            self.draw_rect_border(bus, top, ra_left, bottom, right);
            Self::fb_fill_rect(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                top + 1,
                ra_left + 1,
                bottom - 1,
                right - 1,
                false,
            );
            // Inner shadow
            Self::fb_fill_rect(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                top + 1,
                right - 2,
                bottom - 1,
                right - 1,
                true,
            );
            Self::fb_fill_rect(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                bottom - 2,
                ra_left + 1,
                bottom - 1,
                right - 1,
                true,
            );
            // Right arrow glyph
            self.draw_scroll_arrow(bus, top + 1, ra_left + 1, 3); // right

            // Track area between arrows
            let track_left = left + arrow_w;
            let track_right = right - arrow_w;
            if track_left < track_right {
                self.fill_scroll_track(bus, top + 1, track_left, bottom - 1, track_right);

                // Draw thumb (fixed 16px width)
                let track_len = track_right - track_left;
                let thumb_w = 16i16.min(track_len);
                let range = (max - min).max(1) as i32;
                let val_clamped = (value - min).max(0).min(max - min) as i32;
                let travel = (track_len - thumb_w) as i32;
                let thumb_left = track_left + ((val_clamped * travel) / range) as i16;
                let thumb_right = thumb_left + thumb_w;

                // White fill for thumb
                Self::fb_fill_rect(
                    bus,
                    screen_base,
                    row_bytes,
                    pixel_size,
                    screen_width,
                    screen_height,
                    top + 1,
                    thumb_left,
                    bottom - 1,
                    thumb_right,
                    false,
                );
                // Thumb border
                self.draw_rect_border(bus, top, thumb_left, bottom, thumb_right);
                // Thumb inner bottom shadow only (no right shadow for horizontal)
                Self::fb_fill_rect(
                    bus,
                    screen_base,
                    row_bytes,
                    pixel_size,
                    screen_width,
                    screen_height,
                    bottom - 2,
                    thumb_left + 1,
                    bottom - 1,
                    thumb_right - 1,
                    true,
                );
                // Thumb grip lines (4 vertical lines, 6px tall, centered)
                self.draw_thumb_grip_lines_h(bus, thumb_left, top, bottom);
            }
        }
    }

    /// Fill a scroll bar track area with the ltGray pattern ($88/$22).
    fn fill_scroll_track(
        &self,
        bus: &mut MacMemoryBus,
        top: i16,
        left: i16,
        bottom: i16,
        right: i16,
    ) {
        // ltGray pattern: $88 $22 $88 $22 $88 $22 $88 $22
        const LT_GRAY: [u8; 8] = [0x88, 0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x22];
        let (screen_base, row_bytes, screen_width, screen_height, pixel_size) =
            self.get_screen_params();
        for y in top..bottom {
            if y < 0 || y >= screen_height {
                continue;
            }
            let pat_row = LT_GRAY[(y as u16 % 8) as usize];
            for x in left..right {
                if x < 0 || x >= screen_width {
                    continue;
                }
                let bit = 7 - (x as u16 % 8);
                let on = (pat_row >> bit) & 1 != 0;
                Self::fb_set_pixel(
                    bus,
                    screen_base,
                    row_bytes,
                    pixel_size,
                    screen_width,
                    screen_height,
                    x,
                    y,
                    on,
                );
            }
        }
    }

    /// Draw a scroll bar arrow glyph (outlined arrow with shaft).
    /// Direction: 0=up, 1=down, 2=left, 3=right
    /// content_top/content_left: top-left of the 13x13 content area inside the arrow box.
    fn draw_scroll_arrow(
        &self,
        bus: &mut MacMemoryBus,
        content_top: i16,
        content_left: i16,
        direction: u8,
    ) {
        // Up arrow pattern in a 13x13 content area
        // Each entry: (row, &[cols])
        const UP_ARROW: [(i16, &[i16]); 10] = [
            (2, &[6]),    // tip
            (3, &[5, 7]), // outline
            (4, &[4, 8]),
            (5, &[3, 9]),
            (6, &[2, 10]),
            (7, &[1, 2, 3, 4, 8, 9, 10, 11]), // arms
            (8, &[4, 8]),                     // shaft sides
            (9, &[4, 8]),
            (10, &[4, 8]),
            (11, &[4, 5, 6, 7, 8]), // shaft bottom
        ];

        let (screen_base, row_bytes, screen_width, screen_height, pixel_size) =
            self.get_screen_params();

        for &(row, cols) in &UP_ARROW {
            for &col in cols {
                // Transform coordinates based on direction
                let (py, px) = match direction {
                    0 => (row, col),      // up: as-is
                    1 => (13 - row, col), // down: vertical flip
                    2 => (12 - col, row), // left: rotate CW
                    3 => (col, 13 - row), // right: rotate CCW + shift
                    _ => continue,
                };
                let sy = content_top + py;
                let sx = content_left + px;
                Self::fb_set_pixel(
                    bus,
                    screen_base,
                    row_bytes,
                    pixel_size,
                    screen_width,
                    screen_height,
                    sx,
                    sy,
                    true,
                );
            }
        }
    }

    /// Draw 4 horizontal grip lines on a vertical scroll bar thumb.
    fn draw_thumb_grip_lines_v(
        &self,
        bus: &mut MacMemoryBus,
        thumb_top: i16,
        box_left: i16,
        _box_right: i16,
    ) {
        let (screen_base, row_bytes, screen_width, screen_height, pixel_size) =
            self.get_screen_params();
        // Grip lines at thumb_top + 5, 7, 9, 11
        // Each line: 6px wide, starting at box_left + 5
        let grip_left = box_left + 5;
        let grip_right = box_left + 11; // exclusive
        for &offset in &[5i16, 7, 9, 11] {
            let y = thumb_top + offset;
            for x in grip_left..grip_right {
                Self::fb_set_pixel(
                    bus,
                    screen_base,
                    row_bytes,
                    pixel_size,
                    screen_width,
                    screen_height,
                    x,
                    y,
                    true,
                );
            }
        }
    }

    /// Draw 4 vertical grip lines on a horizontal scroll bar thumb.
    fn draw_thumb_grip_lines_h(
        &self,
        bus: &mut MacMemoryBus,
        thumb_left: i16,
        box_top: i16,
        _box_bottom: i16,
    ) {
        let (screen_base, row_bytes, screen_width, screen_height, pixel_size) =
            self.get_screen_params();
        // Grip lines at thumb_left + 5, 7, 9, 11
        // Each line: 6px tall, starting at box_top + 5
        let grip_top = box_top + 5;
        let grip_bottom = box_top + 11; // exclusive
        for &offset in &[5i16, 7, 9, 11] {
            let x = thumb_left + offset;
            for y in grip_top..grip_bottom {
                Self::fb_set_pixel(
                    bus,
                    screen_base,
                    row_bytes,
                    pixel_size,
                    screen_width,
                    screen_height,
                    x,
                    y,
                    true,
                );
            }
        }
    }

    /// Draw a horizontal line at the given y, from left to right-1 (screen coords).
    fn draw_hline(&self, bus: &mut MacMemoryBus, y: i16, left: i16, right: i16) {
        let (screen_base, row_bytes, screen_width, screen_height, pixel_size) =
            self.get_screen_params();
        for x in left..right {
            Self::fb_set_pixel(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                x,
                y,
                true,
            );
        }
    }

    /// Draw a vertical line at the given x, from top to bottom-1 (screen coords).
    fn draw_vline(&self, bus: &mut MacMemoryBus, x: i16, top: i16, bottom: i16) {
        let (screen_base, row_bytes, screen_width, screen_height, pixel_size) =
            self.get_screen_params();
        for y in top..bottom {
            Self::fb_set_pixel(
                bus,
                screen_base,
                row_bytes,
                pixel_size,
                screen_width,
                screen_height,
                x,
                y,
                true,
            );
        }
    }

    /// Draw an inactive scroll bar arrow glyph (14x14 content area, no inner shadow).
    /// Direction: 0=up, 1=down, 2=left, 3=right
    fn draw_scroll_arrow_inactive(
        &self,
        bus: &mut MacMemoryBus,
        content_top: i16,
        content_left: i16,
        direction: u8,
    ) {
        // Up/Down arrow pattern in a 14x14 content area
        const UP_ARROW_14: [(i16, &[i16]); 10] = [
            (2, &[6, 7]), // tip (2px wide)
            (3, &[5, 8]),
            (4, &[4, 9]),
            (5, &[3, 10]),
            (6, &[2, 11]),
            (7, &[1, 2, 3, 4, 9, 10, 11, 12]), // arms
            (8, &[4, 9]),                      // shaft sides
            (9, &[4, 9]),
            (10, &[4, 9]),
            (11, &[4, 5, 6, 7, 8, 9]), // shaft bottom
        ];

        // Left arrow pattern in 14x14 (derived from expected reference)
        const LEFT_ARROW_14: [(i16, &[i16]); 12] = [
            (1, &[6]),
            (2, &[5, 6]),
            (3, &[4, 6]),
            (4, &[3, 6, 7, 8, 9, 10]), // arrowhead + shaft top
            (5, &[2, 10]),
            (6, &[1, 10]), // tip
            (7, &[1, 10]),
            (8, &[2, 10]),
            (9, &[3, 6, 7, 8, 9, 10]), // arrowhead + shaft bottom
            (10, &[4, 6]),
            (11, &[5, 6]),
            (12, &[6]),
        ];

        // Right arrow = left arrow mirrored: col → 13-col
        const RIGHT_ARROW_14: [(i16, &[i16]); 12] = [
            (1, &[7]),
            (2, &[7, 8]),
            (3, &[7, 9]),
            (4, &[3, 4, 5, 6, 7, 10]),
            (5, &[3, 11]),
            (6, &[3, 12]), // tip
            (7, &[3, 12]),
            (8, &[3, 11]),
            (9, &[3, 4, 5, 6, 7, 10]),
            (10, &[7, 9]),
            (11, &[7, 8]),
            (12, &[7]),
        ];

        let (screen_base, row_bytes, screen_width, screen_height, pixel_size) =
            self.get_screen_params();

        match direction {
            0 | 1 => {
                for &(row, cols) in &UP_ARROW_14 {
                    for &col in cols {
                        let (py, px) = if direction == 0 {
                            (row, col)
                        } else {
                            (13 - row, col)
                        };
                        let sy = content_top + py;
                        let sx = content_left + px;
                        Self::fb_set_pixel(
                            bus,
                            screen_base,
                            row_bytes,
                            pixel_size,
                            screen_width,
                            screen_height,
                            sx,
                            sy,
                            true,
                        );
                    }
                }
            }
            2 => {
                for &(row, cols) in &LEFT_ARROW_14 {
                    for &col in cols {
                        let sy = content_top + row;
                        let sx = content_left + col;
                        Self::fb_set_pixel(
                            bus,
                            screen_base,
                            row_bytes,
                            pixel_size,
                            screen_width,
                            screen_height,
                            sx,
                            sy,
                            true,
                        );
                    }
                }
            }
            3 => {
                for &(row, cols) in &RIGHT_ARROW_14 {
                    for &col in cols {
                        let sy = content_top + row;
                        let sx = content_left + col;
                        Self::fb_set_pixel(
                            bus,
                            screen_base,
                            row_bytes,
                            pixel_size,
                            screen_width,
                            screen_height,
                            sx,
                            sy,
                            true,
                        );
                    }
                }
            }
            _ => {}
        }
    }

    pub(crate) fn dispatch_control<C: CpuOps>(
        &mut self,
        is_tool: bool,
        trap_num: u16,
        cpu: &mut C,
        bus: &mut MacMemoryBus,
    ) -> Option<Result<()>> {
        Some(match (is_tool, trap_num) {
            // NewControl ($A954)
            // Allocates a new control and adds it to the specified window.
            // FUNCTION NewControl(theWindow: WindowPtr; boundsRect: Rect; title: Str255;
            //   visible: BOOLEAN; value: INTEGER; min, max: INTEGER; procID: INTEGER;
            //   refCon: LONGINT): ControlHandle;
            // Inside Macintosh Volume I, I-331
            // NewControl ($A954): Initializes ControlRecord fields from stack parameters, stores title/refCon/default CDEF handle, prepends handle into window's wControlList per IM:I I-317/I-331
            (true, 0x154) => {
                let sp = cpu.read_reg(Register::A7);
                let window_ptr = bus.read_long(sp + 22);
                let bounds_ptr = bus.read_long(sp + 18);
                let title_ptr = bus.read_long(sp + 14);
                // Read Pascal BOOLEAN as the HIGH byte of its 2-byte stack slot
                // (MPW C convention).
                let visible = bus.read_byte(sp + 12) != 0;
                let value = bus.read_word(sp + 10) as i16;
                let min = bus.read_word(sp + 8) as i16;
                let max = bus.read_word(sp + 6) as i16;
                let proc_id = bus.read_word(sp + 4) as i16;
                let ref_con = bus.read_long(sp);

                let bounds = if bounds_ptr != 0 {
                    (
                        bus.read_word(bounds_ptr) as i16,
                        bus.read_word(bounds_ptr + 2) as i16,
                        bus.read_word(bounds_ptr + 4) as i16,
                        bus.read_word(bounds_ptr + 6) as i16,
                    )
                } else {
                    (0, 0, 0, 0)
                };
                let title = Self::read_pascal_string(bus, title_ptr);

                let ctrl_ptr = bus.alloc(296);
                let handle = bus.alloc(4);
                bus.write_long(handle, ctrl_ptr);

                self.initialize_control_record(
                    bus, ctrl_ptr, window_ptr, bounds, &title, visible, value, min, max, proc_id,
                    ref_con,
                );
                self.ensure_control_aux_record(bus, handle);

                if window_ptr != 0 {
                    let old_head = bus.read_long(window_ptr + 140);
                    bus.write_long(ctrl_ptr, old_head);
                    bus.write_long(window_ptr + 140, handle);
                }

                // On a real Mac, NewControl with visible=true draws the control
                // immediately via the CDEF's drawCntl message.
                // Inside Macintosh Volume I, I-331
                if visible {
                    self.draw_control(cpu, bus, ctrl_ptr);
                }

                bus.write_long(sp + 26, handle);
                cpu.write_reg(Register::A7, sp + 26);
                Ok(())
            }

            // DisposeControl ($A955)
            // Removes a control from its window's control list and
            // releases the memory it occupies.
            // PROCEDURE DisposeControl(theControl: ControlHandle);
            // Inside Macintosh Volume I, I-332
            //
            // DisposeControl ($A955): Reads contrlOwner at offset 4, unlinks handle from window chain, frees memory per IM:I I-332
            (true, 0x155) => {
                let sp = cpu.read_reg(Register::A7);
                let ctrl_handle = bus.read_long(sp);
                cpu.write_reg(Register::A7, sp + 4);
                if ctrl_handle != 0 {
                    let ctrl_ptr = bus.read_long(ctrl_handle);
                    if ctrl_ptr != 0 {
                        // Remove from window's control list by reading
                        // contrlOwner (offset 4) to find the parent window,
                        // then unlinking this control from the chain.
                        // Inside Macintosh Volume I, I-316.
                        let owner = bus.read_long(ctrl_ptr + 4);
                        if owner != 0 {
                            // Window's controlList handle is at offset 140
                            let mut prev_handle = 0u32;
                            let mut cur_handle = bus.read_long(owner + 140);
                            while cur_handle != 0 {
                                let cur_ptr = bus.read_long(cur_handle);
                                if cur_ptr == 0 {
                                    break;
                                }
                                if cur_handle == ctrl_handle {
                                    // Unlink: next = contrlData.nextControl at offset 0
                                    let next = bus.read_long(cur_ptr);
                                    if prev_handle == 0 {
                                        bus.write_long(owner + 140, next);
                                    } else {
                                        let prev_ptr = bus.read_long(prev_handle);
                                        bus.write_long(prev_ptr, next);
                                    }
                                    break;
                                }
                                prev_handle = cur_handle;
                                cur_handle = bus.read_long(cur_ptr);
                            }
                        }
                        self.release_control_aux_record(bus, ctrl_handle);
                        self.control_proc_ids.remove(&ctrl_ptr);
                        bus.free(ctrl_ptr);
                    }
                    bus.free(ctrl_handle);
                }
                Ok(())
            }

            // KillControls ($A956)
            // Disposes of all controls belonging to the specified window.
            // Walks the window's control chain and frees each handle.
            // PROCEDURE KillControls(theWindow: WindowPtr);
            // Inside Macintosh Volume I, I-332
            // KillControls ($A956): Walks + frees all controls in window per IM:I I-332
            (true, 0x156) => {
                let sp = cpu.read_reg(Register::A7);
                let window_ptr = bus.read_long(sp);
                cpu.write_reg(Register::A7, sp + 4);
                if window_ptr != 0 {
                    // Walk the control list starting at window+140
                    let mut ctrl_handle = bus.read_long(window_ptr + 140);
                    while ctrl_handle != 0 {
                        let ctrl_ptr = bus.read_long(ctrl_handle);
                        if ctrl_ptr == 0 {
                            bus.free(ctrl_handle);
                            break;
                        }
                        let next = bus.read_long(ctrl_ptr);
                        self.release_control_aux_record(bus, ctrl_handle);
                        self.control_proc_ids.remove(&ctrl_ptr);
                        bus.free(ctrl_ptr);
                        bus.free(ctrl_handle);
                        ctrl_handle = next;
                    }
                    // Nil out the window's control list head
                    bus.write_long(window_ptr + 140, 0);
                }
                Ok(())
            }

            // ShowControl ($A957)
            // Makes the given control visible by setting contrlVis to 255.
            // PROCEDURE ShowControl(theControl: ControlHandle);
            // Inside Macintosh Volume I, I-328
            // ShowControl ($A957): Sets contrlVis byte to 255 (visible)
            (true, 0x157) => {
                let sp = cpu.read_reg(Register::A7);
                let ctrl_handle = bus.read_long(sp);
                if ctrl_handle != 0 {
                    let ctrl_ptr = bus.read_long(ctrl_handle);
                    if ctrl_ptr != 0 {
                        bus.write_byte(ctrl_ptr + 16, 255); // contrlVis = visible
                    }
                }
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // HideControl ($A958)
            // Makes the given control invisible by setting contrlVis to 0.
            // PROCEDURE HideControl(theControl: ControlHandle);
            // Inside Macintosh Volume I, I-328
            // HideControl ($A958): Sets contrlVis byte to 0 (invisible)
            (true, 0x158) => {
                let sp = cpu.read_reg(Register::A7);
                let ctrl_handle = bus.read_long(sp);
                if ctrl_handle != 0 {
                    let ctrl_ptr = bus.read_long(ctrl_handle);
                    if ctrl_ptr != 0 {
                        bus.write_byte(ctrl_ptr + 16, 0); // contrlVis = invisible
                    }
                }
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // MoveControl ($A959)
            // Moves a control to the specified position in local coordinates.
            // The top left corner of contrlRect moves to (h, v); the size
            // is preserved.
            // PROCEDURE MoveControl(theControl: ControlHandle; h, v: INTEGER);
            // Inside Macintosh Volume I, I-329
            //
            // Pascal pushes theControl first, then h, then v — so v is at SP+0,
            // h at SP+2, theControl at SP+4.
            // MoveControl ($A959): Moves contrlRect to (h,v) preserving size per IM:I I-329
            (true, 0x159) => {
                let sp = cpu.read_reg(Register::A7);
                let v = bus.read_word(sp) as i16;
                let h = bus.read_word(sp + 2) as i16;
                let ctrl_handle = bus.read_long(sp + 4);
                cpu.write_reg(Register::A7, sp + 8);
                if ctrl_handle != 0 {
                    let ctrl_ptr = bus.read_long(ctrl_handle);
                    if ctrl_ptr != 0 {
                        // contrlRect is at offset 8: top(2), left(2), bottom(2), right(2)
                        let old_top = bus.read_word(ctrl_ptr + 8) as i16;
                        let old_left = bus.read_word(ctrl_ptr + 10) as i16;
                        let old_bottom = bus.read_word(ctrl_ptr + 12) as i16;
                        let old_right = bus.read_word(ctrl_ptr + 14) as i16;
                        let width = old_right - old_left;
                        let height = old_bottom - old_top;

                        // Erase the control's CURRENT screen rect before moving it. Per
                        // IM:I I-329 (and ROM _MoveControl source) this is implemented as
                        // HideControl + update contrlRect + ShowControl; HideControl
                        // invalidates and erases the old location.
                        let owner_window = bus.read_long(ctrl_ptr + 4);
                        if owner_window != 0 {
                            let (scr_top, scr_left, _, _) =
                                Self::dialog_screen_bounds(bus, owner_window);
                            let (screen_base, row_bytes, screen_width, screen_height, pixel_size) =
                                self.get_screen_params();
                            Self::fb_fill_rect(
                                bus,
                                screen_base,
                                row_bytes,
                                pixel_size,
                                screen_width,
                                screen_height,
                                scr_top + old_top,
                                scr_left + old_left,
                                scr_top + old_bottom,
                                scr_left + old_right,
                                false, // erase to white
                            );
                        }

                        bus.write_word(ctrl_ptr + 8, v as u16);
                        bus.write_word(ctrl_ptr + 10, h as u16);
                        bus.write_word(ctrl_ptr + 12, (v + height) as u16);
                        bus.write_word(ctrl_ptr + 14, (h + width) as u16);
                        self.sync_dialog_item_rect_for_control(bus, ctrl_handle);
                    }
                }
                Ok(())
            }

            // GetCRefCon ($A95A)
            // Returns the reference constant for the given control.
            // FUNCTION GetCRefCon(theControl: ControlHandle): LONGINT;
            // Inside Macintosh Volume I, I-330
            // GetCRefCon ($A95A): Returns ControlRecord `contrlRfCon`
            (true, 0x15A) => {
                let sp = cpu.read_reg(Register::A7);
                let ctrl_handle = bus.read_long(sp);
                let ref_con = Self::control_record_ptr(bus, ctrl_handle)
                    .checked_add(36)
                    .map(|addr| bus.read_long(addr))
                    .unwrap_or(0);
                bus.write_long(sp + 4, ref_con);
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // SetCRefCon ($A95B)
            // Sets the reference constant for the given control.
            // PROCEDURE SetCRefCon(theControl: ControlHandle; data: LONGINT);
            // Inside Macintosh Volume I, I-330
            // SetCRefCon ($A95B): Stores ControlRecord `contrlRfCon`
            (true, 0x15B) => {
                let sp = cpu.read_reg(Register::A7);
                let ref_con = bus.read_long(sp);
                let ctrl_handle = bus.read_long(sp + 4);
                let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);
                if ctrl_ptr != 0 {
                    bus.write_long(ctrl_ptr + 36, ref_con);
                }
                cpu.write_reg(Register::A7, sp + 8);
                Ok(())
            }

            // SizeControl ($A95C)
            // Changes the size of a control.
            // PROCEDURE SizeControl(theControl: ControlHandle; w, h: INTEGER);
            // Inside Macintosh Volume I, I-329
            // SizeControl ($A95C): Updates control rect width/height in place; does not redraw
            (true, 0x15C) => {
                let sp = cpu.read_reg(Register::A7);
                let height = bus.read_word(sp) as i16;
                let width = bus.read_word(sp + 2) as i16;
                let ctrl_handle = bus.read_long(sp + 4);
                let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);
                if ctrl_ptr != 0 {
                    let top = bus.read_word(ctrl_ptr + 8) as i16;
                    let left = bus.read_word(ctrl_ptr + 10) as i16;
                    bus.write_word(ctrl_ptr + 12, top.wrapping_add(height) as u16);
                    bus.write_word(ctrl_ptr + 14, left.wrapping_add(width) as u16);
                    self.sync_dialog_item_rect_for_control(bus, ctrl_handle);
                }
                cpu.write_reg(Register::A7, sp + 8);
                Ok(())
            }

            // HiliteControl ($A95D)
            // Highlights a control as specified by hiliteState.
            // PROCEDURE HiliteControl(theControl: ControlHandle; hiliteState: INTEGER);
            // Macintosh Toolbox Essentials 1992, p. 5-98
            // HiliteControl ($A95D): Updates ControlRecord `contrlHilite`
            // and redraws through the control definition path.
            (true, 0x15D) => {
                let sp = cpu.read_reg(Register::A7);
                let hilite_state = bus.read_word(sp) as u8;
                let ctrl_handle = bus.read_long(sp + 2);
                let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);
                if ctrl_ptr != 0 {
                    bus.write_byte(ctrl_ptr + 17, hilite_state);
                    if trace_controls_enabled() {
                        let dialog_item = self
                            .dialog_control_handles
                            .get(&ctrl_handle)
                            .map(|(dlg, item)| format!(" dialog=${dlg:08X} item={item}"))
                            .unwrap_or_default();
                        eprintln!(
                            "[CONTROL] HiliteControl state={}{} {}",
                            hilite_state,
                            dialog_item,
                            self.control_trace_control_fields(bus, ctrl_handle),
                        );
                    }
                    self.draw_control(cpu, bus, ctrl_ptr);
                } else if trace_controls_enabled() {
                    eprintln!(
                        "[CONTROL] HiliteControl state={} {}",
                        hilite_state,
                        self.control_trace_control_fields(bus, ctrl_handle),
                    );
                }
                cpu.write_reg(Register::A7, sp + 6);
                Ok(())
            }

            // GetCTitle ($A95E)
            // Returns the title of the given control.
            // PROCEDURE GetCTitle(theControl: ControlHandle; VAR title: Str255);
            // Inside Macintosh Volume I, I-327
            // GetCTitle ($A95E): Copies Pascal title from ControlRecord
            (true, 0x15E) => {
                let sp = cpu.read_reg(Register::A7);
                let title_ptr = bus.read_long(sp);
                let ctrl_handle = bus.read_long(sp + 4);
                let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);
                let title = if ctrl_ptr != 0 {
                    Self::control_title_bytes(bus, ctrl_ptr)
                } else {
                    Vec::new()
                };
                Self::write_pascal_string(bus, title_ptr, &title);
                cpu.write_reg(Register::A7, sp + 8);
                Ok(())
            }

            // SetCTitle ($A95F)
            // Sets the title of the given control and redraws it.
            // PROCEDURE SetCTitle(theControl: ControlHandle; title: Str255);
            // Inside Macintosh Volume I, I-327
            // SetCTitle ($A95F): Stores Pascal title in ControlRecord and redraws control
            (true, 0x15F) => {
                let sp = cpu.read_reg(Register::A7);
                let title_ptr = bus.read_long(sp);
                let ctrl_handle = bus.read_long(sp + 4);
                cpu.write_reg(Register::A7, sp + 8);
                let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);
                if ctrl_ptr != 0 {
                    let title = Self::read_pascal_string(bus, title_ptr);
                    Self::set_control_title_bytes(bus, ctrl_ptr, &title);
                    self.draw_control(cpu, bus, ctrl_ptr);
                }
                Ok(())
            }

            // GetCtlValue ($A960)
            // Returns the current value of a control.
            // FUNCTION GetCtlValue(theControl: ControlHandle): INTEGER;
            // Inside Macintosh Volume I, I-327
            // GetCtlValue ($A960): Routes through dialog control handles; falls back to ControlRecord offset 18
            (true, 0x160) => {
                let sp = cpu.read_reg(Register::A7);
                let ctrl_handle = bus.read_long(sp);
                let value = if let Some((dlg_ptr, item_no)) =
                    self.dialog_control_handles.get(&ctrl_handle).copied()
                {
                    self.dialog_control_values
                        .get(&(dlg_ptr, item_no))
                        .copied()
                        .unwrap_or(0)
                } else if ctrl_handle != 0 {
                    let ctrl_ptr = bus.read_long(ctrl_handle);
                    if ctrl_ptr != 0 {
                        bus.read_word(ctrl_ptr + 18) as i16
                    } else {
                        0
                    }
                } else {
                    0
                };
                bus.write_word(sp + 4, value as u16);
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // SetCtlValue ($A963)
            // Sets the current value of a control, clamped to
            // [contrlMin, contrlMax].
            // PROCEDURE SetCtlValue(theControl: ControlHandle; theValue: INTEGER);
            // Inside Macintosh Volume I, I-328
            // SetCtlValue ($A963): Routes through dialog control handles; writes to ControlRecord offset 18
            (true, 0x163) => {
                let sp = cpu.read_reg(Register::A7);
                let requested = bus.read_word(sp) as i16;
                let ctrl_handle = bus.read_long(sp + 2);
                cpu.write_reg(Register::A7, sp + 6);

                if ctrl_handle == 0 {
                    return Some(Ok(()));
                }
                let ctrl_ptr = bus.read_long(ctrl_handle);
                if ctrl_ptr == 0 {
                    return Some(Ok(()));
                }
                let min = bus.read_word(ctrl_ptr + 20) as i16;
                let max = bus.read_word(ctrl_ptr + 22) as i16;
                let proc_id = self.control_proc_ids.get(&ctrl_ptr).copied().unwrap_or(0);
                // If min > max the control is degenerate — IM doesn't
                // define the behaviour. Be conservative: take the
                // requested value unchanged in that case.
                let value = if Self::is_popup_menu_proc_id(proc_id) {
                    requested
                } else if min <= max {
                    requested.clamp(min, max)
                } else {
                    requested
                };
                if let Some((dlg_ptr, item_no)) =
                    self.dialog_control_handles.get(&ctrl_handle).copied()
                {
                    self.dialog_control_values.insert((dlg_ptr, item_no), value);
                }
                bus.write_word(ctrl_ptr + 18, value as u16);
                if trace_controls_enabled() {
                    let dialog_item = self
                        .dialog_control_handles
                        .get(&ctrl_handle)
                        .map(|(dlg, item)| format!(" dialog=${dlg:08X} item={item}"))
                        .unwrap_or_default();
                    eprintln!(
                        "[CONTROL] SetCtlValue requested={} value={}{} {}",
                        requested,
                        value,
                        dialog_item,
                        self.control_trace_control_fields(bus, ctrl_handle),
                    );
                }
                self.draw_control(cpu, bus, ctrl_ptr);
                Ok(())
            }

            // GetCtlMin ($A961)
            // Returns the minimum setting of a control.
            // FUNCTION GetCtlMin(theControl: ControlHandle): INTEGER;
            // Inside Macintosh Volume I, I-327
            // GetCtlMin ($A961): Returns ControlRecord `contrlMin`
            (true, 0x161) => {
                let sp = cpu.read_reg(Register::A7);
                let ctrl_handle = bus.read_long(sp);
                let min = Self::control_record_ptr(bus, ctrl_handle)
                    .checked_add(20)
                    .map(|addr| bus.read_word(addr))
                    .unwrap_or(0);
                bus.write_word(sp + 4, min);
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // SetCtlMin ($A964)
            // Sets the minimum setting of a control. If the current
            // value is less than the new minimum, it's bumped up per
            // IM:I I-328 ("SetCtlValue is called to set the current
            // value to the new minimum").
            // PROCEDURE SetCtlMin(theControl: ControlHandle; minValue: INTEGER);
            // Inside Macintosh Volume I, I-328
            // SetCtlMin ($A964): Stores ControlRecord `contrlMin`
            (true, 0x164) => {
                let sp = cpu.read_reg(Register::A7);
                let min = bus.read_word(sp) as i16;
                let ctrl_handle = bus.read_long(sp + 2);
                cpu.write_reg(Register::A7, sp + 6);
                let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);
                if ctrl_ptr != 0 {
                    bus.write_word(ctrl_ptr + 20, min as u16);
                    let proc_id = self.control_proc_ids.get(&ctrl_ptr).copied().unwrap_or(0);
                    let value = bus.read_word(ctrl_ptr + 18) as i16;
                    if !Self::is_popup_menu_proc_id(proc_id) && value < min {
                        bus.write_word(ctrl_ptr + 18, min as u16);
                        if let Some((dlg_ptr, item_no)) =
                            self.dialog_control_handles.get(&ctrl_handle).copied()
                        {
                            self.dialog_control_values.insert((dlg_ptr, item_no), min);
                        }
                        self.draw_control(cpu, bus, ctrl_ptr);
                    }
                }
                Ok(())
            }

            // GetCtlMax ($A962)
            // Returns the maximum setting of a control.
            // FUNCTION GetCtlMax(theControl: ControlHandle): INTEGER;
            // Inside Macintosh Volume I, I-327
            // GetCtlMax ($A962): Returns ControlRecord `contrlMax`
            (true, 0x162) => {
                let sp = cpu.read_reg(Register::A7);
                let ctrl_handle = bus.read_long(sp);
                let max = Self::control_record_ptr(bus, ctrl_handle)
                    .checked_add(22)
                    .map(|addr| bus.read_word(addr))
                    .unwrap_or(0);
                bus.write_word(sp + 4, max);
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // SetCtlMax ($A965)
            // Sets the maximum setting of a control. If the current
            // value is greater than the new maximum, it's pulled
            // down per IM:I I-328 (symmetric to SetCtlMin).
            // PROCEDURE SetCtlMax(theControl: ControlHandle; maxValue: INTEGER);
            // Inside Macintosh Volume I, I-328
            // SetCtlMax ($A965): Stores ControlRecord `contrlMax`
            (true, 0x165) => {
                let sp = cpu.read_reg(Register::A7);
                let max = bus.read_word(sp) as i16;
                let ctrl_handle = bus.read_long(sp + 2);
                cpu.write_reg(Register::A7, sp + 6);
                let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);
                if ctrl_ptr != 0 {
                    bus.write_word(ctrl_ptr + 22, max as u16);
                    let proc_id = self.control_proc_ids.get(&ctrl_ptr).copied().unwrap_or(0);
                    let value = bus.read_word(ctrl_ptr + 18) as i16;
                    if !Self::is_popup_menu_proc_id(proc_id) && value > max {
                        bus.write_word(ctrl_ptr + 18, max as u16);
                        if let Some((dlg_ptr, item_no)) =
                            self.dialog_control_handles.get(&ctrl_handle).copied()
                        {
                            self.dialog_control_values.insert((dlg_ptr, item_no), max);
                        }
                        self.draw_control(cpu, bus, ctrl_ptr);
                    }
                }
                Ok(())
            }

            // TestControl ($A966)
            // Tests which part of a control the given point is in.
            // FUNCTION TestControl(theControl: ControlHandle; thePt: Point): INTEGER;
            // Inside Macintosh Volume I, I-325; Macintosh Toolbox Essentials
            // (1992), p. 5-93
            // TestControl ($A966): For the standard button-family controls
            // Systemless currently models, visible active push buttons return
            // inButton (10) while checkboxes/radio buttons return inCheckBox
            // (11). Invisible, inactive, or missed controls return 0.
            (true, 0x166) => {
                let sp = cpu.read_reg(Register::A7);
                let pt_v = bus.read_word(sp) as i16;
                let pt_h = bus.read_word(sp + 2) as i16;
                let ctrl_handle = bus.read_long(sp + 4);
                let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);

                let mut part: u16 = 0;
                if ctrl_ptr != 0 {
                    let vis = bus.read_byte(ctrl_ptr + 16);
                    let hilite = bus.read_byte(ctrl_ptr + 17);
                    if vis == 255 && hilite != 255 {
                        let r_top = bus.read_word(ctrl_ptr + 8) as i16;
                        let r_left = bus.read_word(ctrl_ptr + 10) as i16;
                        let r_bottom = bus.read_word(ctrl_ptr + 12) as i16;
                        let r_right = bus.read_word(ctrl_ptr + 14) as i16;
                        if pt_v >= r_top && pt_v < r_bottom && pt_h >= r_left && pt_h < r_right {
                            part = match self.control_proc_ids.get(&ctrl_ptr).copied().unwrap_or(0)
                            {
                                16 => self.standard_scrollbar_testcontrol_part_code(
                                    bus, ctrl_ptr, pt_v, pt_h,
                                ),
                                _ => self.standard_testcontrol_part_code(ctrl_ptr),
                            };
                        }
                    }
                }

                bus.write_word(sp + 8, part);
                cpu.write_reg(Register::A7, sp + 8);
                Ok(())
            }

            // TrackControl ($A968)
            // Tracks the mouse and returns the part code where it was released.
            // FUNCTION TrackControl(theControl: ControlHandle; startPt: Point;
            //   actionProc: ProcPtr): INTEGER;
            // Macintosh Toolbox Essentials 1992, pp. 5-89 to 5-90
            // Stack: SP+0=actionProc(4), SP+4=startPt(4), SP+8=theControl(4), SP+12=result(2)
            // TrackControl ($A968): tracks popup controls and held-mouse
            // simple push/checkbox/radio controls across refires; preserves
            // the old immediate hit-test path when the mouse is already up.
            (true, 0x168) => {
                if self.control_tracking.is_some() {
                    let popup_tracking = self
                        .control_tracking
                        .as_ref()
                        .map(|tracking| tracking.popup_tracking)
                        .unwrap_or(false);
                    if popup_tracking {
                        if self.control_tracking_button_down(bus) {
                            let ctrl_handle = self
                                .control_tracking
                                .as_ref()
                                .map(|tracking| tracking.ctrl_handle)
                                .unwrap_or(0);
                            let (mv, mh) = self.control_tracking_mouse_pos(bus);
                            let new_item = self.control_tracking_item_at_point(bus, mh, mv);
                            let old_item = self
                                .control_tracking
                                .as_ref()
                                .map(|tracking| tracking.highlighted_item)
                                .unwrap_or(0);
                            if new_item != old_item {
                                self.set_control_tracking_highlight(bus, new_item);
                            }
                            self.record_trackcontrol_input_trace(
                                bus,
                                "tracking_update",
                                ctrl_handle,
                                None,
                                0,
                                None,
                                Some(new_item),
                                if new_item > 0 {
                                    "popup_item_highlighted"
                                } else {
                                    "popup_no_item"
                                },
                            );
                        } else {
                            let selected_item = self
                                .control_tracking
                                .as_ref()
                                .map(|tracking| tracking.highlighted_item)
                                .unwrap_or(0);
                            self.finish_popup_control_tracking(cpu, bus, selected_item);
                        }
                    } else {
                        let ctrl_handle = self
                            .control_tracking
                            .as_ref()
                            .map(|tracking| tracking.ctrl_handle)
                            .unwrap_or(0);
                        let inside = self.simple_control_tracking_inside(bus);
                        if self.control_tracking_button_down(bus) {
                            let highlighted = self
                                .control_tracking
                                .as_ref()
                                .map(|tracking| tracking.simple_highlighted)
                                .unwrap_or(false);
                            if inside != highlighted {
                                self.redraw_simple_control_tracking_state(cpu, bus, inside);
                            }
                            self.record_trackcontrol_input_trace(
                                bus,
                                "tracking_update",
                                ctrl_handle,
                                None,
                                0,
                                self.control_tracking.as_ref().map(|tracking| {
                                    if inside {
                                        tracking.simple_part
                                    } else {
                                        0
                                    }
                                }),
                                None,
                                if inside {
                                    "simple_part_highlighted"
                                } else {
                                    "simple_no_part"
                                },
                            );
                        } else {
                            self.finish_simple_control_tracking(cpu, bus, inside);
                        }
                    }
                    return Some(Ok(()));
                }

                let sp = cpu.read_reg(Register::A7);
                let action_proc = bus.read_long(sp);
                let ctrl_handle = bus.read_long(sp + 8);
                let pt_v = bus.read_word(sp + 4) as i16;
                let pt_h = bus.read_word(sp + 6) as i16;

                let mut part: u16 = 0;
                let mut outcome = "no_control";
                if ctrl_handle != 0 {
                    let ctrl_ptr = bus.read_long(ctrl_handle);
                    if ctrl_ptr != 0 {
                        let vis = bus.read_byte(ctrl_ptr + 16);
                        let hilite = bus.read_byte(ctrl_ptr + 17);
                        outcome = "inactive_or_invisible";
                        if vis == 255 && hilite != 255 {
                            let r_top = bus.read_word(ctrl_ptr + 8) as i16;
                            let r_left = bus.read_word(ctrl_ptr + 10) as i16;
                            let r_bottom = bus.read_word(ctrl_ptr + 12) as i16;
                            let r_right = bus.read_word(ctrl_ptr + 14) as i16;
                            outcome = "outside_control";
                            if pt_v >= r_top && pt_v < r_bottom && pt_h >= r_left && pt_h < r_right
                            {
                                let proc_id =
                                    self.control_proc_ids.get(&ctrl_ptr).copied().unwrap_or(0);
                                if Self::is_popup_menu_proc_id(proc_id) {
                                    let menu_id = self.popup_control_menu_id(
                                        bus,
                                        ctrl_ptr,
                                        bus.read_word(ctrl_ptr + 20) as i16,
                                    );
                                    if let Some(menu_idx) =
                                        self.menus.iter().rposition(|menu| menu.id == menu_id)
                                    {
                                        let dropdown_rect = self
                                            .popup_control_dropdown_rect(bus, ctrl_ptr, menu_idx);
                                        let saved = self.save_dropdown_pixels(bus, dropdown_rect);
                                        self.draw_menu_dropdown(bus, menu_idx, dropdown_rect);
                                        self.control_tracking = Some(ControlTrackingState {
                                            ctrl_handle,
                                            ctrl_ptr,
                                            popup_tracking: true,
                                            active_menu: menu_idx,
                                            highlighted_item: 0,
                                            saved_pixels: saved,
                                            dropdown_rect,
                                            simple_part: 0,
                                            simple_screen_rect: (0, 0, 0, 0),
                                            simple_highlighted: false,
                                            saved_hilite: hilite,
                                            stack_ptr: sp,
                                        });
                                        self.record_trackcontrol_input_trace(
                                            bus,
                                            "start",
                                            ctrl_handle,
                                            Some((pt_v, pt_h)),
                                            action_proc,
                                            None,
                                            Some(0),
                                            "open_popup_tracking",
                                        );
                                        return Some(Ok(()));
                                    }
                                }

                                // IM:I I-323: TrackControl follows mouse
                                // movement, highlights simple controls, and
                                // returns the part code only after mouse-up.
                                // Preserve the old immediate path when the
                                // mouse is already up; scripted callers that
                                // model a real mouse-down take the refire path.
                                if self.mouse_button
                                    && action_proc == 0
                                    && matches!(proc_id, 0 | 1 | 2)
                                {
                                    let part = self.standard_testcontrol_part_code(ctrl_ptr);
                                    let window_ptr = bus.read_long(ctrl_ptr + 4);
                                    let (scr_top, scr_left, _, _) =
                                        Self::dialog_screen_bounds(bus, window_ptr);
                                    let screen_rect = (
                                        scr_top + r_top,
                                        scr_left + r_left,
                                        scr_top + r_bottom,
                                        scr_left + r_right,
                                    );
                                    self.control_tracking = Some(ControlTrackingState {
                                        ctrl_handle,
                                        ctrl_ptr,
                                        popup_tracking: false,
                                        active_menu: 0,
                                        highlighted_item: 0,
                                        saved_pixels: Vec::new(),
                                        dropdown_rect: (0, 0, 0, 0),
                                        simple_part: part,
                                        simple_screen_rect: screen_rect,
                                        simple_highlighted: false,
                                        saved_hilite: hilite,
                                        stack_ptr: sp,
                                    });
                                    self.redraw_simple_control_tracking_state(cpu, bus, true);
                                    self.record_trackcontrol_input_trace(
                                        bus,
                                        "start",
                                        ctrl_handle,
                                        Some((pt_v, pt_h)),
                                        action_proc,
                                        None,
                                        None,
                                        "simple_tracking_started",
                                    );
                                    return Some(Ok(()));
                                }

                                // Return inButton (10) for simple controls.
                                // Inside Macintosh Volume I, I-316
                                part = 10;
                                outcome = "visible_active_hit";
                            }
                        }
                    }
                }

                self.record_trackcontrol_input_trace(
                    bus,
                    "start",
                    ctrl_handle,
                    Some((pt_v, pt_h)),
                    action_proc,
                    Some(part),
                    None,
                    outcome,
                );
                bus.write_word(sp + 12, part);
                cpu.write_reg(Register::A7, sp + 12);
                Ok(())
            }

            // DrawControls ($A969)
            // Draws all the controls belonging to the specified window.
            // PROCEDURE DrawControls(theWindow: WindowPtr);
            // Inside Macintosh Volume I, I-333
            // DrawControls ($A969): Draws all controls in window's control list per IM:I I-333
            (true, 0x169) => {
                let sp = cpu.read_reg(Register::A7);
                let window_ptr = bus.read_long(sp);

                if window_ptr != 0 {
                    // Collect ctrl_ptrs first to avoid borrow conflicts
                    let mut ctrl_handle = bus.read_long(window_ptr + 140);
                    let mut ctrl_ptrs: Vec<u32> = Vec::new();
                    while ctrl_handle != 0 {
                        let ctrl_ptr = bus.read_long(ctrl_handle);
                        if ctrl_ptr == 0 {
                            break;
                        }
                        ctrl_ptrs.push(ctrl_ptr);
                        ctrl_handle = bus.read_long(ctrl_ptr);
                    }

                    // Draw controls in reverse order (last added = bottom of list = drawn first)
                    for &ctrl_ptr in ctrl_ptrs.iter().rev() {
                        let proc_id = self.control_proc_ids.get(&ctrl_ptr).copied().unwrap_or(0);
                        if Self::is_popup_menu_proc_id(proc_id) {
                            // popupMenuProc needs special MENU resource lookup
                            let vis = bus.read_byte(ctrl_ptr + 16);
                            let hilite = bus.read_byte(ctrl_ptr + 17);
                            if vis == 255 {
                                let r_top = bus.read_word(ctrl_ptr + 8) as i16;
                                let r_left = bus.read_word(ctrl_ptr + 10) as i16;
                                let r_bottom = bus.read_word(ctrl_ptr + 12) as i16;
                                let r_right = bus.read_word(ctrl_ptr + 14) as i16;
                                let ctrl_value = bus.read_word(ctrl_ptr + 18) as i16;
                                let menu_id = self.popup_control_menu_id(
                                    bus,
                                    ctrl_ptr,
                                    bus.read_word(ctrl_ptr + 20) as i16,
                                );
                                let (scr_top, scr_left, _, _) =
                                    Self::dialog_screen_bounds(bus, window_ptr);
                                let abs_top = scr_top + r_top;
                                let abs_left = scr_left + r_left;
                                let abs_bottom = scr_top + r_bottom;
                                let abs_right = scr_left + r_right;
                                let selected = ctrl_value.max(1) as usize;
                                let item_title = self.popup_menu_item_title(bus, menu_id, selected);
                                self.draw_popup_control_with_state(
                                    bus,
                                    abs_top,
                                    abs_left,
                                    abs_bottom,
                                    abs_right,
                                    &item_title.unwrap_or_default(),
                                    hilite != 255,
                                    hilite == 1,
                                );
                            }
                        } else {
                            self.draw_control(cpu, bus, ctrl_ptr);
                        }
                    }
                }

                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // UpdtControl ($A953)
            // Redraws the window's controls whose rect intersects the
            // given update region.
            // PROCEDURE UpdtControl(theWindow: WindowPtr; updateRgn: RgnHandle);
            // Inside Macintosh Volume V, V-222
            //
            // Uses bbox-approx region semantics. A nil update region is a no-op;
            // a non-empty update region redraws only the intersecting visible controls.
            // UpdtControl ($A953): Walks the window's wControlList at +140, hit-tests each control's contrlRect against the bbox of the update region, invokes draw_control on each survivor; pops 8 bytes (updateRgn + theWindow). Region semantics are bbox-approximated since Systemless does not model arbitrary RgnHandle scanlines.
            (true, 0x153) => {
                let sp = cpu.read_reg(Register::A7);
                let update_rgn = bus.read_long(sp);
                let window_ptr = bus.read_long(sp + 4);
                cpu.write_reg(Register::A7, sp + 8);
                if trace_controls_enabled() {
                    eprintln!(
                        "[CONTROL] UpdtControl window=${:08X} updateRgn=${:08X}",
                        window_ptr, update_rgn
                    );
                }
                let window_limit = bus.ram_size().saturating_sub(140);
                // Treat stale or out-of-range window pointers as inert rather
                // than dereferencing arbitrary guest memory.
                if window_ptr == 0 || window_ptr > window_limit {
                    return Some(Ok(()));
                }
                if update_rgn == 0 {
                    return Some(Ok(()));
                }
                let update_rect = match Self::region_handle_rect(bus, update_rgn) {
                    Some(rect) => rect,
                    None => return Some(Ok(())),
                };
                let mut ctrl_handle = bus.read_long(window_ptr + 140);
                let mut ctrl_ptrs: Vec<u32> = Vec::new();
                while ctrl_handle != 0 {
                    let ctrl_ptr = bus.read_long(ctrl_handle);
                    if ctrl_ptr == 0 {
                        break;
                    }
                    ctrl_ptrs.push(ctrl_ptr);
                    ctrl_handle = bus.read_long(ctrl_ptr);
                }
                let (ut, ul, ub, ur) = update_rect;
                for ctrl_ptr in ctrl_ptrs.iter().rev() {
                    let ctrl_ptr = *ctrl_ptr;
                    let ct = bus.read_word(ctrl_ptr + 8) as i16;
                    let cl = bus.read_word(ctrl_ptr + 10) as i16;
                    let cb = bus.read_word(ctrl_ptr + 12) as i16;
                    let cr = bus.read_word(ctrl_ptr + 14) as i16;
                    // Skip controls fully outside the update bbox.
                    if cb <= ut || cr <= ul || ct >= ub || cl >= ur {
                        continue;
                    }
                    self.draw_control(cpu, bus, ctrl_ptr);
                }
                Ok(())
            }

            // FindControl ($A96C)
            // Determines which control, if any, the given point is in.
            // FUNCTION FindControl(thePoint: Point; theWindow: WindowPtr;
            //   VAR whichControl: ControlHandle): INTEGER;
            // Inside Macintosh Volume I, I-334
            // Stack: SP+0=whichControl(4), SP+4=theWindow(4), SP+8=thePt(4), SP+12=result(2)
            // FindControl ($A96C): Walks window's control list, checks visibility and hilite, hit-tests point against contrlRect, returns part code and control handle
            (true, 0x16C) => {
                let sp = cpu.read_reg(Register::A7);
                let which_ctrl_ptr = bus.read_long(sp);
                let window_ptr = bus.read_long(sp + 4);
                let pt_v = bus.read_word(sp + 8) as i16;
                let pt_h = bus.read_word(sp + 10) as i16;

                let mut found_handle: u32 = 0;
                let mut found_part: u16 = 0;

                // Walk the control list starting at window+140 (wControlList)
                // Macintosh TB Essentials 1992, 4-67
                if window_ptr != 0 {
                    let mut ctrl_handle = bus.read_long(window_ptr + 140);
                    while ctrl_handle != 0 {
                        let ctrl_ptr = bus.read_long(ctrl_handle);
                        if ctrl_ptr == 0 {
                            break;
                        }

                        // Check visibility (offset 16, 255 = visible)
                        let vis = bus.read_byte(ctrl_ptr + 16);
                        // Check hilite (offset 17, 255 = inactive/disabled)
                        let hilite = bus.read_byte(ctrl_ptr + 17);

                        if vis == 255 && hilite != 255 {
                            // Check contrlRect (offset 8): top, left, bottom, right
                            let r_top = bus.read_word(ctrl_ptr + 8) as i16;
                            let r_left = bus.read_word(ctrl_ptr + 10) as i16;
                            let r_bottom = bus.read_word(ctrl_ptr + 12) as i16;
                            let r_right = bus.read_word(ctrl_ptr + 14) as i16;

                            if pt_v >= r_top && pt_v < r_bottom && pt_h >= r_left && pt_h < r_right
                            {
                                found_handle = ctrl_handle;
                                // Return part code 10 (kControlButtonPart) for
                                // simple button controls. The proper approach
                                // would call the CDEF's testCntl, but for HLE
                                // we return a generic hit indicator.
                                found_part = 10;
                                break;
                            }
                        }

                        // Follow the linked list: nextControl at offset 0
                        ctrl_handle = bus.read_long(ctrl_ptr);
                    }
                }

                if which_ctrl_ptr != 0 {
                    bus.write_long(which_ctrl_ptr, found_handle);
                }
                bus.write_word(sp + 12, found_part);
                cpu.write_reg(Register::A7, sp + 12);

                Ok(())
            }

            // GetNewControl ($A9BE)
            // Creates a control from a 'CNTL' resource.
            // FUNCTION GetNewControl(controlID: INTEGER; theWindow: WindowPtr): ControlHandle;
            // Inside Macintosh Volume I, I-332
            // Stack: SP+0=theWindow(4), SP+4=controlID(2), SP+6=result(4)
            // GetNewControl ($A9BE): Loads CNTL resource, parses all fields (bounds, value, vis, min, max, procID, refCon, title), allocates ControlRecord, links into window's control list
            (true, 0x1BE) => {
                let sp = cpu.read_reg(Register::A7);
                let window_ptr = bus.read_long(sp);
                let ctrl_id = bus.read_word(sp + 4) as i16;

                // IM:I I-321: if the CNTL template cannot be read, return NIL.
                let cntl_data = self
                    .find_resource_any(*b"CNTL", ctrl_id)
                    .map(|(_, ptr)| ptr);

                let Some(rsrc_addr) = cntl_data else {
                    bus.write_long(sp + 6, 0);
                    cpu.write_reg(Register::A7, sp + 6);
                    return Some(Ok(()));
                };

                // Allocate ControlRecord (296 bytes: 40 fixed + 256 title)
                let ctrl_ptr = bus.alloc(296);
                let handle = bus.alloc(4);
                bus.write_long(handle, ctrl_ptr);

                // CNTL resource format (Macintosh TB Essentials 1992, 5-118):
                //   0: boundsRect (8 bytes: top, left, bottom, right)
                //   8: value (2 bytes)
                //  10: visibility (1 byte)
                //  11: fill (1 byte)
                //  12: max (2 bytes)
                //  14: min (2 bytes)
                //  16: procID (2 bytes)
                //  18: refCon (4 bytes)
                //  22: title (Pascal string)
                let r_top = bus.read_word(rsrc_addr);
                let r_left = bus.read_word(rsrc_addr + 2);
                let r_bottom = bus.read_word(rsrc_addr + 4);
                let r_right = bus.read_word(rsrc_addr + 6);
                let value = bus.read_word(rsrc_addr + 8);
                // CNTL visibility is stored as a BOOLEAN word (2 bytes),
                // not a single byte. $FFFF or $0100 = visible, $0000 = invisible.
                // Inside Macintosh Volume I, I-333
                let vis_word = bus.read_word(rsrc_addr + 10);
                let visibility: u8 = if vis_word != 0 { 255 } else { 0 };
                let max = bus.read_word(rsrc_addr + 12);
                let min = bus.read_word(rsrc_addr + 14);
                let proc_id = bus.read_word(rsrc_addr + 16) as i16;
                let ref_con = bus.read_long(rsrc_addr + 18);
                let title = Self::read_pascal_string(bus, rsrc_addr + 22);

                self.initialize_control_record(
                    bus,
                    ctrl_ptr,
                    window_ptr,
                    (r_top as i16, r_left as i16, r_bottom as i16, r_right as i16),
                    &title,
                    visibility == 255,
                    value as i16,
                    min as i16,
                    max as i16,
                    proc_id,
                    ref_con,
                );
                self.ensure_control_aux_record(bus, handle);
                if trace_controls_enabled() {
                    eprintln!(
                        "[CONTROL] GetNewControl id={} proc_id={} cdef_id={} title=\"{}\" rect=({},{}..{},{} ) window=${:08X}",
                        ctrl_id,
                        proc_id,
                        proc_id >> 4,
                        decode_mac_roman_for_render(&title),
                        r_top as i16,
                        r_left as i16,
                        r_bottom as i16,
                        r_right as i16,
                        window_ptr
                    );
                }

                // Link into window's control list at offset 140 (wControlList)
                // New controls go at the beginning of the list.
                // Inside Macintosh Volume I, I-331
                if window_ptr != 0 {
                    let old_head = bus.read_long(window_ptr + 140);
                    bus.write_long(ctrl_ptr, old_head); // nextControl = old head
                    bus.write_long(window_ptr + 140, handle); // window's controlList = new handle
                }

                bus.write_long(sp + 6, handle);
                cpu.write_reg(Register::A7, sp + 6);
                Ok(())
            }

            // SetCtlAction ($A96B)
            // Sets the action procedure for the given control.
            // PROCEDURE SetCtlAction(theControl: ControlHandle; actionProc: ProcPtr);
            // Inside Macintosh Volume I, I-336
            // SetCtlAction ($A96B): Stores ControlRecord `contrlAction`
            (true, 0x16B) => {
                let sp = cpu.read_reg(Register::A7);
                let action_proc = bus.read_long(sp);
                let ctrl_handle = bus.read_long(sp + 4);
                let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);
                if ctrl_ptr != 0 {
                    bus.write_long(ctrl_ptr + 32, action_proc);
                }
                cpu.write_reg(Register::A7, sp + 8);
                Ok(())
            }

            // GetCtlAction ($A96A)
            // Returns the action procedure for the given control.
            // FUNCTION GetCtlAction(theControl: ControlHandle): ProcPtr;
            // Inside Macintosh Volume I, I-336
            // GetCtlAction ($A96A): Returns ControlRecord `contrlAction`
            (true, 0x16A) => {
                let sp = cpu.read_reg(Register::A7);
                let ctrl_handle = bus.read_long(sp);
                let action_proc = Self::control_record_ptr(bus, ctrl_handle)
                    .checked_add(32)
                    .map(|addr| bus.read_long(addr))
                    .unwrap_or(0);
                bus.write_long(sp + 4, action_proc);
                cpu.write_reg(Register::A7, sp + 4);
                Ok(())
            }

            // DragControl ($A967)
            // Drags a control, following the mouse until the button is released.
            // PROCEDURE DragControl(theControl: ControlHandle; startPt: Point;
            //   limitRect: Rect; slopRect: Rect; axis: INTEGER);
            // Inside Macintosh Volume I, I-335
            //
            // Pascal frame (Rect args by VALUE — pinned by the existing
            // inline contract test dragcontrol_does_not_mutate_control_record):
            //   sp+0   axis: INTEGER         (2)
            //   sp+2   slopRect: Rect        (8)
            //   sp+10  limitRect: Rect       (8)
            //   sp+18  startPt: Point        (4)
            //   sp+22  theControl: Handle    (4)
            // Total pop = 26 bytes.
            //
            // CONVENTION DIVERGENCE WARNING: IM:I-91
            // explicit PEA-sizeRect example documents Window-Manager Rect
            // args BY POINTER (4 bytes). The Window Manager interactive-
            // tracking family at src/trap/window.rs ($A925 DragWindow,
            // $A92B GrowWindow, $A926 DragTheRgn) AND $A905 DragGrayRgn
            // at src/trap/toolbox.rs all follow that convention (Rect by
            // ptr, 4 bytes per Rect). DragControl here is the ONLY
            // remaining "drag" trap that pops by-VALUE (8 bytes per
            // Rect). The 26-byte pop is pinned by an existing contract
            // test but is not backed by an IM citation — the IM:I I-432
            // "assembly summary" reference is to the Dialog Mgr Summary,
            // not a DragControl-specific assembly block. Cross-checking
            // against MPW Pascal compiler output for a real corpus
            // binary is the right way to resolve this. For now, the
            // 26-byte pop is preserved as the established behavior.
            //
            // HLE compromise: Systemless does not model interactive mouse
            // dragging — there is no `WaitMouseUp` event loop synthesizing
            // mouse-moved events that would feed back into a control-
            // tracking redraw cycle. The trap therefore returns without
            // moving the control or triggering any redraws. Apps that
            // call DragControl during user interaction (typically from
            // a TrackControl callback) will see the control unchanged.
            // The scripted corpus exercises controls via
            // direct CtlValue manipulation rather than drag flows, so
            // this no-op is appropriate.
            //
            // Regression coverage:
            //   tests::dragcontrol_pops_18_bytes_and_leaves_contrlrect_unchanged_on_no_drag_path
            // DragControl ($A967): The public MPW C declaration uses
            // pointer rect parameters, so the C ABI consumes 18 bytes
            // (theControl 4 + startPt 4 + limitRect* 4 + slopRect* 4
            // + axis 2). HLE has no interactive mouse drag loop so the
            // control is left in place.
            (true, 0x167) => {
                let sp = cpu.read_reg(Register::A7);
                cpu.write_reg(Register::A7, sp + 18);
                Ok(())
            }

            // SetCtlColor ($AA43)
            // PROCEDURE SetCtlColor(theControl: ControlHandle; newColorTable: CCTabHandle);
            // Macintosh Toolbox Essentials (1992), pp. 5-101 and 5-107.
            // Stack: SP+0: newColorTable(4), SP+4: theControl(4). Pop 8.
            // SetCtlColor ($AA43): Rewrites the tracked AuxCtlRec's acCTable
            // field in place. Fresh BasiliskII/System 7.5.3 controls already
            // carry AuxCtlRecs, but Systemless still allocates one on demand if a
            // control somehow reaches SetCtlColor without tracked aux state.
            (true, 0x243) => {
                let sp = cpu.read_reg(Register::A7);
                let color_table = bus.read_long(sp);
                let ctrl_handle = bus.read_long(sp + 4);
                if ctrl_handle != 0 {
                    let default_ctab = self.default_control_color_table_handle(bus);
                    let effective_ctab = if color_table != 0 {
                        color_table
                    } else {
                        default_ctab
                    };
                    let aux_handle = self.ensure_control_aux_record(bus, ctrl_handle);
                    let aux_ptr = bus.read_long(aux_handle);
                    if aux_ptr != 0 {
                        bus.write_long(aux_ptr + Self::AUX_CTL_OWNER_OFFSET, ctrl_handle);
                        bus.write_long(aux_ptr + Self::AUX_CTL_CTABLE_OFFSET, effective_ctab);
                        bus.write_word(aux_ptr + Self::AUX_CTL_FLAGS_OFFSET, 0);
                        bus.write_long(
                            aux_ptr + Self::AUX_CTL_RESERVED_OFFSET,
                            self.control_aux_reserved_value(bus, ctrl_handle),
                        );
                    }

                    let ctrl_ptr = Self::control_record_ptr(bus, ctrl_handle);
                    if ctrl_ptr != 0 && bus.read_byte(ctrl_ptr + 16) == 255 {
                        self.draw_control(cpu, bus, ctrl_ptr);
                    }
                }
                cpu.write_reg(Register::A7, sp + 8);
                Ok(())
            }

            // Draw1Control ($A96D)
            // Draws a single control.
            // PROCEDURE Draw1Control(theControl: ControlHandle);
            // Inside Macintosh Volume I, I-326
            // Draw1Control ($A96D): Pops 4-byte handle (theControl), dereferences via *handle to ControlPtr, invokes draw_control on it (same code path DrawControls walks per-element). NIL handle is a graceful no-op. Per IM:I I-326. Popup buttons (procID 1008) use the popup-control renderer instead of falling through as a no-op, and the current GDevice is preserved across the redraw.
            (true, 0x16D) => {
                let sp = cpu.read_reg(Register::A7);
                let ctrl_handle = bus.read_long(sp);
                cpu.write_reg(Register::A7, sp + 4);
                let saved_gdevice = self.current_gdevice;
                // Treat stale or out-of-range handles as inert rather than
                // dereferencing arbitrary guest memory. The control record's
                // Pascal title begins at offset 40, so we also reject handles
                // whose title byte or declared title payload would run off the
                // end of RAM before handing the record to draw_control.
                let ram_limit = bus.ram_size().saturating_sub(4);
                if ctrl_handle != 0 && ctrl_handle <= ram_limit {
                    let ctrl_ptr = bus.read_long(ctrl_handle);
                    let title_off = ctrl_ptr.saturating_add(40);
                    if ctrl_ptr != 0 && title_off < bus.ram_size() && title_off <= ram_limit {
                        let title_len = bus.read_byte(title_off) as u32;
                        let title_end = title_off.saturating_add(1).saturating_add(title_len);
                        if title_end <= bus.ram_size() {
                            // popupMenuProc (1008) already has a direct
                            // renderer in draw_control, so Draw1Control can
                            // reuse the same control path as DrawControls.
                            self.draw_control(cpu, bus, ctrl_ptr);
                            debug_assert_eq!(self.current_gdevice, saved_gdevice);
                        }
                    }
                }
                Ok(())
            }

            // GetCVariant ($A809)
            // Returns the variation code of a control.
            // FUNCTION GetCVariant(theControl: ControlHandle): INTEGER;
            // Inside Macintosh Volume V, V-222 (Macintosh Plus, SE, and II).
            //
            // The control definition ID is `16 * resourceID + variation_code`
            // (Inside Macintosh Volume I 1985, p. I-323 "Defining Your Own
            // Controls"): the upper 12 bits select the CDEF resource, the low
            // 4 bits select the variant. NewControl stores both into the
            // ControlRecord — the resolved CDEF handle into contrlDefProc
            // (offset 24) and historically the variation code into the
            // high-order byte of that field. Per IM:V V-222: "This value was
            // formerly stored in the high four bits of the control defproc
            // handle; for future compatibility, use the GetCVariant routine
            // to access this value."
            //
            // Systemless's NewControl / GetNewControl (toolbox.rs:1144 and
            // :1972) record the original procID in the side-table
            // `control_proc_ids: HashMap<ctrl_ptr, i16>`, indexed by the
            // dereferenced ControlPtr (i.e. *theControl). GetCVariant
            // recovers the variation code by reading procID from that side
            // table and masking the low 4 bits — the canonical IM:I I-323
            // definition. Same formula independent of CDEF resource ID:
            //   pushButProc=0   → variant 0
            //   checkBoxProc=1  → variant 1
            //   radioButProc=2  → variant 2
            //   scrollBarProc=16 → variant 0
            //   popupMenuProc=1008 + popupFixedWidth=1 → variant 1
            //
            // Stack layout (Pascal FUNCTION): caller pre-allocates 2-byte
            // INTEGER result slot at sp+4, pushes 4-byte ControlHandle arg at
            // sp+0. Trap reads arg, advances A7 by 4, writes INTEGER result
            // at the former sp+4. NIL theControl returns 0.
            //
            // MPW Universal Headers `Controls.h`:
            //   EXTERN_API(SInt16) GetControlVariant(ControlRef) ONEWORDINLINE(0xA809);
            //   #define GetCVariant(theControl) GetControlVariant(theControl)
            (true, 0x009) => {
                let sp = cpu.read_reg(Register::A7);
                let ctrl_handle = bus.read_long(sp);
                let variant: i16 = if ctrl_handle != 0 {
                    let ctrl_ptr = bus.read_long(ctrl_handle);
                    let proc_id = self.control_proc_ids.get(&ctrl_ptr).copied().unwrap_or(0);
                    proc_id & 0xF
                } else {
                    0
                };
                cpu.write_reg(Register::A7, sp + 4);
                bus.write_word(sp + 4, variant as u16);
                Ok(())
            }

            _ => return None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::super::test_helpers::{setup, setup_with_port};
    use crate::cpu::{CpuOps, Register};
    use crate::memory::{MacMemoryBus, MemoryBus};
    use crate::trap::menu::{Menu, MenuItem};
    use crate::trap::TrapDispatcher;
    use crate::ui_theme::UiThemeId;

    fn build_cntl_resource(
        rect: (i16, i16, i16, i16),
        value: i16,
        visible: bool,
        min: i16,
        max: i16,
        proc_id: i16,
        ref_con: u32,
        title: &[u8],
    ) -> Vec<u8> {
        let mut data = Vec::with_capacity(23 + title.len());
        data.extend_from_slice(&(rect.0 as u16).to_be_bytes());
        data.extend_from_slice(&(rect.1 as u16).to_be_bytes());
        data.extend_from_slice(&(rect.2 as u16).to_be_bytes());
        data.extend_from_slice(&(rect.3 as u16).to_be_bytes());
        data.extend_from_slice(&(value as u16).to_be_bytes());
        data.extend_from_slice(&(if visible { 0xFFFFu16 } else { 0 }).to_be_bytes());
        data.extend_from_slice(&(max as u16).to_be_bytes());
        data.extend_from_slice(&(min as u16).to_be_bytes());
        data.extend_from_slice(&(proc_id as u16).to_be_bytes());
        data.extend_from_slice(&ref_con.to_be_bytes());
        let len = title.len().min(255);
        data.push(len as u8);
        data.extend_from_slice(&title[..len]);
        data
    }

    fn fill_rect_pict_resource(
        frame: (i16, i16, i16, i16),
        fill_rect: (i16, i16, i16, i16),
    ) -> Vec<u8> {
        let mut data = Vec::new();
        data.extend_from_slice(&0u16.to_be_bytes()); // picSize placeholder
        for value in [frame.0, frame.1, frame.2, frame.3] {
            data.extend_from_slice(&(value as u16).to_be_bytes());
        }
        data.push(0x11); // versionOp
        data.push(0x01); // PICT v1
        data.push(0x0A); // FillPat
        data.extend_from_slice(&[0xFF; 8]);
        data.push(0x34); // fillRect
        for value in [fill_rect.0, fill_rect.1, fill_rect.2, fill_rect.3] {
            data.extend_from_slice(&(value as u16).to_be_bytes());
        }
        data.push(0xFF); // EndOfPicture
        let size = data.len() as u16;
        data[0..2].copy_from_slice(&size.to_be_bytes());
        data
    }

    fn alloc_control_handle(
        bus: &mut MacMemoryBus,
        rect: (i16, i16, i16, i16),
        vis: u8,
        hilite: u8,
    ) -> (u32, u32) {
        let ctrl_ptr = bus.alloc(40);
        let ctrl_handle = bus.alloc(4);
        bus.write_long(ctrl_handle, ctrl_ptr);
        bus.write_word(ctrl_ptr + 8, rect.0 as u16);
        bus.write_word(ctrl_ptr + 10, rect.1 as u16);
        bus.write_word(ctrl_ptr + 12, rect.2 as u16);
        bus.write_word(ctrl_ptr + 14, rect.3 as u16);
        bus.write_byte(ctrl_ptr + 16, vis);
        bus.write_byte(ctrl_ptr + 17, hilite);
        (ctrl_handle, ctrl_ptr)
    }

    fn alloc_scrollbar_control(
        disp: &mut super::super::TrapDispatcher,
        bus: &mut MacMemoryBus,
        rect: (i16, i16, i16, i16),
        vis: u8,
        hilite: u8,
        value: i16,
        min: i16,
        max: i16,
    ) -> (u32, u32) {
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(bus, rect, vis, hilite);
        bus.write_word(ctrl_ptr + 18, value as u16);
        bus.write_word(ctrl_ptr + 20, min as u16);
        bus.write_word(ctrl_ptr + 22, max as u16);
        disp.control_proc_ids.insert(ctrl_ptr, 16);
        (ctrl_handle, ctrl_ptr)
    }

    fn new_control_handle<C: CpuOps>(
        disp: &mut TrapDispatcher,
        cpu: &mut C,
        bus: &mut MacMemoryBus,
        window_ptr: u32,
        visible: bool,
        proc_id: i16,
    ) -> u32 {
        let sp = 0x300000;
        let bounds_ptr = bus.alloc(8);
        let title_ptr = bus.alloc(16);

        bus.write_word(bounds_ptr, 10);
        bus.write_word(bounds_ptr + 2, 20);
        bus.write_word(bounds_ptr + 4, 30);
        bus.write_word(bounds_ptr + 6, 80);
        bus.write_byte(title_ptr, 4);
        bus.write_bytes(title_ptr + 1, b"Aux!");

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0x1234_5678);
        bus.write_word(sp + 4, proc_id as u16);
        bus.write_word(sp + 6, 99);
        bus.write_word(sp + 8, 1);
        bus.write_word(sp + 10, 7);
        bus.write_byte(sp + 12, if visible { 1 } else { 0 });
        bus.write_long(sp + 14, title_ptr);
        bus.write_long(sp + 18, bounds_ptr);
        bus.write_long(sp + 22, window_ptr);

        let result = disp.dispatch_control(true, 0x154, cpu, bus);
        assert!(result.unwrap().is_ok());
        bus.read_long(cpu.read_reg(Register::A7))
    }

    fn make_control_ctab_handle(bus: &mut MacMemoryBus) -> u32 {
        let ctab_ptr = bus.alloc(8 + 4 * 8);
        let ctab_handle = bus.alloc(4);
        bus.write_long(ctab_handle, ctab_ptr);
        bus.write_long(ctab_ptr, 0); // ccSeed
        bus.write_word(ctab_ptr + 4, 0); // ccRider
        bus.write_word(ctab_ptr + 6, 3); // ctSize (4 ColorSpec entries)
        for (index, part_id) in [0u16, 1, 2, 3].iter().enumerate() {
            let entry = ctab_ptr + 8 + index as u32 * 8;
            bus.write_word(entry, *part_id);
            bus.write_word(entry + 2, 0x1111u16.wrapping_mul(index as u16 + 1));
            bus.write_word(entry + 4, 0x0101u16.wrapping_mul(index as u16 + 2));
            bus.write_word(entry + 6, 0x0202u16.wrapping_mul(index as u16 + 3));
        }
        ctab_handle
    }

    #[test]
    fn new_control_initializes_record_and_links_window() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000;
        let window_ptr = bus.alloc(200);
        let bounds_ptr = bus.alloc(8);
        let title_ptr = bus.alloc(16);

        bus.write_word(bounds_ptr, 10);
        bus.write_word(bounds_ptr + 2, 20);
        bus.write_word(bounds_ptr + 4, 30);
        bus.write_word(bounds_ptr + 6, 80);
        bus.write_byte(title_ptr, 4);
        bus.write_bytes(title_ptr + 1, b"Test");

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0x1234_5678);
        bus.write_word(sp + 4, 0);
        bus.write_word(sp + 6, 99);
        bus.write_word(sp + 8, 1);
        bus.write_word(sp + 10, 7);
        // Pascal BOOLEAN at SP+12 — value goes in HIGH byte (MPW C convention).
        bus.write_byte(sp + 12, 1);
        bus.write_long(sp + 14, title_ptr);
        bus.write_long(sp + 18, bounds_ptr);
        bus.write_long(sp + 22, window_ptr);

        let result = disp.dispatch_control(true, 0x154, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());

        let handle = bus.read_long(sp + 26);
        let ctrl_ptr = bus.read_long(handle);
        assert_ne!(handle, 0);
        assert_ne!(ctrl_ptr, 0);
        assert_eq!(bus.read_long(window_ptr + 140), handle);
        assert_eq!(bus.read_long(ctrl_ptr + 4), window_ptr);
        assert_eq!(bus.read_word(ctrl_ptr + 8), 10);
        assert_eq!(bus.read_word(ctrl_ptr + 10), 20);
        assert_eq!(bus.read_word(ctrl_ptr + 12), 30);
        assert_eq!(bus.read_word(ctrl_ptr + 14), 80);
        assert_eq!(bus.read_byte(ctrl_ptr + 16), 255);
        assert_eq!(bus.read_word(ctrl_ptr + 18), 7);
        assert_eq!(bus.read_word(ctrl_ptr + 20), 1);
        assert_eq!(bus.read_word(ctrl_ptr + 22), 99);
        assert_eq!(bus.read_long(ctrl_ptr + 36), 0x1234_5678);
        assert_eq!(bus.read_byte(ctrl_ptr + 40), 4);
        assert_eq!(bus.read_bytes(ctrl_ptr + 41, 4), b"Test");
        assert_eq!(cpu.read_reg(Register::A7), sp + 26);
    }

    #[test]
    fn newcontrol_creates_aux_record_and_getauxctl_returns_true() {
        let (mut disp, mut cpu, mut bus) = setup();
        let window_ptr = bus.alloc(200);
        let ctrl_handle = new_control_handle(&mut disp, &mut cpu, &mut bus, window_ptr, false, 0);

        let aux_state = disp
            .control_aux_state(ctrl_handle)
            .expect("fresh control should have an AuxCtlRec on BasiliskII System 7.5.3");
        let aux_ptr = bus.read_long(aux_state.handle);
        assert_ne!(aux_ptr, 0, "AuxCtlHandle must master a live AuxCtlRec");
        assert_eq!(
            bus.read_long(aux_ptr + 4),
            ctrl_handle,
            "acOwner must point back to the control handle"
        );
        assert_ne!(
            bus.read_long(aux_ptr + 8),
            0,
            "fresh controls should already carry a non-NIL acCTable"
        );
        assert_eq!(
            bus.read_long(0x0CD4),
            aux_state.handle,
            "AuxCtlHead low-memory global should point at the fresh control's aux record"
        );

        let aux_out = bus.alloc(4);
        let sp = 0x300100;
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, aux_out);
        bus.write_long(sp + 4, ctrl_handle);
        bus.write_word(sp + 8, 0xFFFF);

        let result = disp.dispatch_quickdraw(true, 0x244, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);
        assert_eq!(
            bus.read_long(aux_out),
            aux_state.handle,
            "GetAuxCtl should write the tracked AuxCtlHandle for fresh controls"
        );
        assert_eq!(
            bus.read_word(sp + 8),
            0x0100,
            "GetAuxCtl should return TRUE for fresh tracked controls"
        );
    }

    #[test]
    fn setctlcolor_reuses_aux_record_and_getauxctl_reports_custom_colors() {
        let (mut disp, mut cpu, mut bus) = setup();
        let window_ptr = bus.alloc(200);
        let ctrl_handle = new_control_handle(&mut disp, &mut cpu, &mut bus, window_ptr, false, 0);
        let aux_before = disp
            .control_aux_state(ctrl_handle)
            .expect("fresh control should already have an AuxCtlRec");
        let custom_ctab = make_control_ctab_handle(&mut bus);

        let sp = 0x300140;
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, custom_ctab);
        bus.write_long(sp + 4, ctrl_handle);

        let result = disp.dispatch_control(true, 0x243, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);

        let aux_after = disp
            .control_aux_state(ctrl_handle)
            .expect("SetCtlColor should keep the AuxCtlRec alive");
        assert_eq!(
            aux_after.handle, aux_before.handle,
            "SetCtlColor should rewrite the existing AuxCtlRec instead of allocating a new one"
        );
        let aux_ptr = bus.read_long(aux_after.handle);
        assert_eq!(
            bus.read_long(aux_ptr + 8),
            custom_ctab,
            "SetCtlColor should rewrite acCTable to the caller-supplied CCTabHandle"
        );

        let aux_out = bus.alloc(4);
        let get_sp = 0x300180;
        cpu.write_reg(Register::A7, get_sp);
        bus.write_long(get_sp, aux_out);
        bus.write_long(get_sp + 4, ctrl_handle);
        bus.write_word(get_sp + 8, 0);

        let get_result = disp.dispatch_quickdraw(true, 0x244, &mut cpu, &mut bus);
        assert!(get_result.unwrap().is_ok());
        assert_eq!(cpu.read_reg(Register::A7), get_sp + 8);
        assert_eq!(bus.read_long(aux_out), aux_after.handle);
        assert_eq!(
            bus.read_word(get_sp + 8),
            0x0100,
            "GetAuxCtl should return TRUE after SetCtlColor installs custom colors"
        );
    }

    #[test]
    fn disposecontrol_releases_aux_record_and_repairs_auxctl_chain() {
        let (mut disp, mut cpu, mut bus) = setup();
        let window_ptr = bus.alloc(200);
        let first = new_control_handle(&mut disp, &mut cpu, &mut bus, window_ptr, false, 0);
        let second = new_control_handle(&mut disp, &mut cpu, &mut bus, window_ptr, false, 1);
        let first_ctab = make_control_ctab_handle(&mut bus);
        let second_ctab = make_control_ctab_handle(&mut bus);

        for (ctrl_handle, ctab_handle) in [(first, first_ctab), (second, second_ctab)] {
            let sp = if ctrl_handle == first {
                0x300180
            } else {
                0x3001A0
            };
            cpu.write_reg(Register::A7, sp);
            bus.write_long(sp, ctab_handle);
            bus.write_long(sp + 4, ctrl_handle);
            let result = disp.dispatch_control(true, 0x243, &mut cpu, &mut bus);
            assert!(result.unwrap().is_ok());
        }

        let first_state = disp
            .control_aux_state(first)
            .expect("first control aux record");
        let second_state = disp
            .control_aux_state(second)
            .expect("second control aux record");
        let first_aux_ptr = bus.read_long(first_state.handle);
        let second_aux_ptr = bus.read_long(second_state.handle);
        assert_eq!(
            bus.read_long(second_aux_ptr),
            first_state.handle,
            "second AuxCtlRec should link to the first via acNext"
        );

        let sp = 0x3001C0;
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, first);

        let result = disp.dispatch_control(true, 0x155, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
        assert!(
            disp.control_aux_state(first).is_none(),
            "DisposeControl should drop the released control from the aux-state map"
        );
        assert_eq!(
            bus.read_long(0x0CD4),
            second_state.handle,
            "AuxCtlHead should remain pointed at the surviving control's aux record"
        );
        assert_eq!(
            bus.read_long(second_aux_ptr),
            0,
            "DisposeControl should repair the acNext chain when unlinking a non-head aux record"
        );
        assert_eq!(
            bus.get_alloc_size(first_state.handle),
            None,
            "DisposeControl should free the released AuxCtlHandle"
        );
        assert_eq!(
            bus.get_alloc_size(first_aux_ptr),
            None,
            "DisposeControl should free the released AuxCtlRec"
        );
    }

    // IM:I I-331: NewControl takes nine arguments and returns a ControlHandle.
    #[test]
    fn newcontrol_consumes_arguments_and_writes_result_slot() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let window_ptr = bus.alloc(200);
        let bounds_ptr = bus.alloc(8);
        let title_ptr = bus.alloc(16);

        bus.write_word(bounds_ptr, 12);
        bus.write_word(bounds_ptr + 2, 18);
        bus.write_word(bounds_ptr + 4, 40);
        bus.write_word(bounds_ptr + 6, 90);
        bus.write_byte(title_ptr, 4);
        bus.write_bytes(title_ptr + 1, b"Play");

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0x1020_3040);
        bus.write_word(sp + 4, 0);
        bus.write_word(sp + 6, 99);
        bus.write_word(sp + 8, 0);
        bus.write_word(sp + 10, 1);
        // Pascal BOOLEAN high byte convention for visible = TRUE.
        bus.write_byte(sp + 12, 1);
        bus.write_long(sp + 14, title_ptr);
        bus.write_long(sp + 18, bounds_ptr);
        bus.write_long(sp + 22, window_ptr);

        disp.dispatch_control(true, 0x154, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 26);
        assert_ne!(bus.read_long(sp + 26), 0);
    }

    // IM:I I-331: NewControl adds the allocated control to the window's
    // control list.
    #[test]
    fn newcontrol_prepends_new_handle_into_window_control_list() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let window_ptr = bus.alloc(200);
        let bounds_ptr = bus.alloc(8);
        let title_ptr = bus.alloc(16);
        let (old_head, old_ptr) = alloc_control_handle(&mut bus, (5, 5, 15, 50), 255, 0);
        bus.write_long(old_ptr + 4, window_ptr);
        bus.write_long(old_ptr, 0);
        bus.write_long(window_ptr + 140, old_head);

        bus.write_word(bounds_ptr, 20);
        bus.write_word(bounds_ptr + 2, 24);
        bus.write_word(bounds_ptr + 4, 60);
        bus.write_word(bounds_ptr + 6, 120);
        bus.write_byte(title_ptr, 3);
        bus.write_bytes(title_ptr + 1, b"New");

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0xA0B0_C0D0);
        bus.write_word(sp + 4, 0);
        bus.write_word(sp + 6, 100);
        bus.write_word(sp + 8, 0);
        bus.write_word(sp + 10, 10);
        bus.write_byte(sp + 12, 1);
        bus.write_long(sp + 14, title_ptr);
        bus.write_long(sp + 18, bounds_ptr);
        bus.write_long(sp + 22, window_ptr);

        disp.dispatch_control(true, 0x154, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        let new_head = bus.read_long(sp + 26);
        let new_ptr = bus.read_long(new_head);
        assert_eq!(bus.read_long(window_ptr + 140), new_head);
        assert_eq!(bus.read_long(new_ptr), old_head);
        assert_eq!(bus.read_long(new_ptr + 4), window_ptr);
    }

    // IM:I I-332: DisposeControl takes one ControlHandle argument.
    #[test]
    fn disposecontrol_consumes_control_handle_argument() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (ctrl_handle, _) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, ctrl_handle);
        disp.dispatch_control(true, 0x155, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
    }

    // IM:I I-332: DisposeControl removes the control from the window's
    // control list.
    #[test]
    fn disposecontrol_unlinks_control_from_owner_window_list() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let window_ptr = bus.alloc(200);
        let (tail_handle, tail_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);
        let (head_handle, head_ptr) = alloc_control_handle(&mut bus, (12, 24, 36, 72), 255, 0);
        bus.write_long(tail_ptr + 4, window_ptr);
        bus.write_long(head_ptr + 4, window_ptr);
        bus.write_long(tail_ptr, 0);
        bus.write_long(head_ptr, tail_handle);
        bus.write_long(window_ptr + 140, head_handle);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, head_handle);
        disp.dispatch_control(true, 0x155, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_long(window_ptr + 140), tail_handle);
        assert_eq!(bus.read_long(tail_ptr), 0);
    }

    // IM:I I-332: KillControls takes one WindowPtr argument.
    #[test]
    fn killcontrols_consumes_window_argument() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let window_ptr = bus.alloc(200);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, window_ptr);
        disp.dispatch_control(true, 0x156, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
    }

    // IM:I I-332: KillControls disposes every control owned by the window.
    #[test]
    fn killcontrols_clears_window_control_list_head() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let window_ptr = bus.alloc(200);
        let (tail_handle, tail_ptr) = alloc_control_handle(&mut bus, (8, 12, 24, 80), 255, 0);
        let (head_handle, head_ptr) = alloc_control_handle(&mut bus, (16, 20, 36, 100), 255, 0);
        bus.write_long(tail_ptr + 4, window_ptr);
        bus.write_long(head_ptr + 4, window_ptr);
        bus.write_long(tail_ptr, 0);
        bus.write_long(head_ptr, tail_handle);
        bus.write_long(window_ptr + 140, head_handle);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, window_ptr);
        disp.dispatch_control(true, 0x156, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_long(window_ptr + 140), 0);
    }

    // IM:I I-336: SetCtlAction takes actionProc and control-handle arguments.
    #[test]
    fn setctlaction_consumes_control_and_action_arguments() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (ctrl_handle, _) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0x00AA_BBCC);
        bus.write_long(sp + 4, ctrl_handle);
        disp.dispatch_control(true, 0x16B, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 8);
    }

    // IM:I I-336: SetCtlAction stores the control's action procedure pointer.
    #[test]
    fn setctlaction_updates_control_action_procptr() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0x0012_3456);
        bus.write_long(sp + 4, ctrl_handle);
        disp.dispatch_control(true, 0x16B, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_long(ctrl_ptr + 32), 0x0012_3456);
    }

    // IM:I I-336: GetCtlAction takes one ControlHandle argument and returns
    // the action ProcPtr.
    #[test]
    fn getctlaction_consumes_control_argument_and_writes_result_slot() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);
        bus.write_long(ctrl_ptr + 32, 0x00AB_CDEF);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, ctrl_handle);
        disp.dispatch_control(true, 0x16A, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
        assert_eq!(bus.read_long(sp + 4), 0x00AB_CDEF);
    }

    // IM:I I-336: GetCtlAction returns the action procedure currently stored
    // in the control record.
    #[test]
    fn getctlaction_returns_control_action_procptr() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);
        bus.write_long(ctrl_ptr + 32, 0x00FE_DCBA);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, ctrl_handle);
        disp.dispatch_control(true, 0x16A, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_long(sp + 4), 0x00FE_DCBA);
    }

    #[test]
    fn getnewcontrol_parses_cntl_resource_and_links_at_window_head() {
        // IM:I (1985) pp. I-321 and I-333: GetNewControl copies CNTL fields
        // into a control record and links it into the window's control list.
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let window_ptr = bus.alloc(200);
        let old_ctrl_ptr = bus.alloc(40);
        let old_ctrl_handle = bus.alloc(4);
        bus.write_long(old_ctrl_handle, old_ctrl_ptr);
        bus.write_long(window_ptr + 140, old_ctrl_handle);

        let cntl = build_cntl_resource((10, 20, 40, 100), 7, true, 2, 99, 0, 0x1234_5678, b"Play");
        disp.install_test_resource(&mut bus, *b"CNTL", 128, &cntl);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, window_ptr);
        bus.write_word(sp + 4, 128);
        bus.write_long(sp + 6, 0xDEAD_BEEF);
        disp.dispatch_control(true, 0x1BE, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        let handle = bus.read_long(sp + 6);
        let ctrl_ptr = bus.read_long(handle);
        assert_ne!(handle, 0);
        assert_ne!(ctrl_ptr, 0);
        assert_eq!(cpu.read_reg(Register::A7), sp + 6);
        assert_eq!(bus.read_long(window_ptr + 140), handle);
        assert_eq!(bus.read_long(ctrl_ptr), old_ctrl_handle);
        assert_eq!(bus.read_long(ctrl_ptr + 4), window_ptr);
        assert_eq!(bus.read_word(ctrl_ptr + 8) as i16, 10);
        assert_eq!(bus.read_word(ctrl_ptr + 10) as i16, 20);
        assert_eq!(bus.read_word(ctrl_ptr + 12) as i16, 40);
        assert_eq!(bus.read_word(ctrl_ptr + 14) as i16, 100);
        assert_eq!(bus.read_byte(ctrl_ptr + 16), 255);
        assert_eq!(bus.read_word(ctrl_ptr + 18) as i16, 7);
        assert_eq!(bus.read_word(ctrl_ptr + 20) as i16, 2);
        assert_eq!(bus.read_word(ctrl_ptr + 22) as i16, 99);
        assert_eq!(bus.read_long(ctrl_ptr + 36), 0x1234_5678);
        assert_eq!(bus.read_byte(ctrl_ptr + 40), 4);
        assert_eq!(bus.read_bytes(ctrl_ptr + 41, 4), b"Play");
    }

    #[test]
    fn getnewcontrol_missing_cntl_returns_nil_and_preserves_window_list() {
        // IM:I (1985) p. I-321: if the control template can't be read,
        // GetNewControl returns NIL.
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let window_ptr = bus.alloc(200);
        let old_ctrl_ptr = bus.alloc(40);
        let old_ctrl_handle = bus.alloc(4);
        bus.write_long(old_ctrl_handle, old_ctrl_ptr);
        bus.write_long(window_ptr + 140, old_ctrl_handle);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, window_ptr);
        bus.write_word(sp + 4, 999);
        bus.write_long(sp + 6, 0xDEAD_BEEF);
        disp.dispatch_control(true, 0x1BE, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 6);
        assert_eq!(bus.read_long(sp + 6), 0);
        assert_eq!(bus.read_long(window_ptr + 140), old_ctrl_handle);
    }

    #[test]
    fn control_accessors_round_trip_action_refcon_title_and_bounds() {
        let (mut disp, mut cpu, mut bus) = setup();
        let ctrl_ptr = bus.alloc(296);
        let ctrl_handle = bus.alloc(4);
        let title_ptr = bus.alloc(16);
        let out_title_ptr = bus.alloc(16);
        let sp = 0x300000;

        bus.write_long(ctrl_handle, ctrl_ptr);
        bus.write_long(ctrl_ptr + 36, 0xCAFE_BABE);
        bus.write_long(ctrl_ptr + 32, 0x0012_3456);
        bus.write_word(ctrl_ptr + 8, 10);
        bus.write_word(ctrl_ptr + 10, 20);
        bus.write_word(ctrl_ptr + 12, 30);
        bus.write_word(ctrl_ptr + 14, 60);
        bus.write_byte(ctrl_ptr + 16, 255);
        bus.write_word(ctrl_ptr + 20, 3);
        bus.write_word(ctrl_ptr + 22, 11);
        bus.write_byte(title_ptr, 3);
        bus.write_bytes(title_ptr + 1, b"EV!");

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, title_ptr);
        bus.write_long(sp + 4, ctrl_handle);
        let result = disp.dispatch_control(true, 0x15F, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        assert_eq!(bus.read_byte(ctrl_ptr + 40), 3);
        assert_eq!(bus.read_bytes(ctrl_ptr + 41, 3), b"EV!");

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, out_title_ptr);
        bus.write_long(sp + 4, ctrl_handle);
        let result = disp.dispatch_control(true, 0x15E, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        assert_eq!(bus.read_byte(out_title_ptr), 3);
        assert_eq!(bus.read_bytes(out_title_ptr + 1, 3), b"EV!");

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, ctrl_handle);
        let result = disp.dispatch_control(true, 0x15A, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        assert_eq!(bus.read_long(sp + 4), 0xCAFE_BABE);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, ctrl_handle);
        let result = disp.dispatch_control(true, 0x16A, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        assert_eq!(bus.read_long(sp + 4), 0x0012_3456);

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 10);
        bus.write_long(sp + 2, ctrl_handle);
        let result = disp.dispatch_control(true, 0x164, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 21);
        bus.write_long(sp + 2, ctrl_handle);
        let result = disp.dispatch_control(true, 0x165, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, ctrl_handle);
        let result = disp.dispatch_control(true, 0x161, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        assert_eq!(bus.read_word(sp + 4), 10);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, ctrl_handle);
        let result = disp.dispatch_control(true, 0x162, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        assert_eq!(bus.read_word(sp + 4), 21);

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 15);
        bus.write_word(sp + 2, 25);
        bus.write_long(sp + 4, ctrl_handle);
        let result = disp.dispatch_control(true, 0x166, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        assert_eq!(bus.read_word(sp + 8), 10);

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 0);
        bus.write_word(sp + 2, 0);
        bus.write_long(sp + 4, ctrl_handle);
        let result = disp.dispatch_control(true, 0x166, &mut cpu, &mut bus);
        assert!(result.unwrap().is_ok());
        assert_eq!(bus.read_word(sp + 8), 0);
    }

    // SizeControl/GetCTitle/SetCTitle semantics per Inside Macintosh
    // Volume I (1985), pp. I-321 and I-325.
    #[test]
    fn sizecontrol_sets_bottom_right_from_requested_width_height_and_pops_args() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 40, 70), 255, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 18); // h
        bus.write_word(sp + 2, 44); // w
        bus.write_long(sp + 4, ctrl_handle);
        disp.dispatch_control(true, 0x15C, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_word(ctrl_ptr + 8) as i16, 10);
        assert_eq!(bus.read_word(ctrl_ptr + 10) as i16, 20);
        assert_eq!(bus.read_word(ctrl_ptr + 12) as i16, 28);
        assert_eq!(bus.read_word(ctrl_ptr + 14) as i16, 64);
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);
    }

    #[test]
    fn getctitle_copies_control_title_to_output_str255_and_pops_args() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let ctrl_ptr = bus.alloc(296);
        let ctrl_handle = bus.alloc(4);
        bus.write_long(ctrl_handle, ctrl_ptr);
        let out_title = bus.alloc(16);

        bus.write_byte(ctrl_ptr + 40, 5);
        bus.write_bytes(ctrl_ptr + 41, b"Hello");

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, out_title);
        bus.write_long(sp + 4, ctrl_handle);
        disp.dispatch_control(true, 0x15E, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_byte(out_title), 5);
        assert_eq!(bus.read_bytes(out_title + 1, 5), b"Hello");
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);
    }

    #[test]
    fn setctitle_updates_control_title_from_input_str255_and_pops_args() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let ctrl_ptr = bus.alloc(296);
        let ctrl_handle = bus.alloc(4);
        bus.write_long(ctrl_handle, ctrl_ptr);
        let in_title = bus.alloc(16);

        bus.write_word(ctrl_ptr + 8, 10);
        bus.write_word(ctrl_ptr + 10, 20);
        bus.write_word(ctrl_ptr + 12, 40);
        bus.write_word(ctrl_ptr + 14, 70);
        bus.write_byte(ctrl_ptr + 16, 255);
        bus.write_byte(ctrl_ptr + 40, 3);
        bus.write_bytes(ctrl_ptr + 41, b"Old");
        bus.write_byte(in_title, 7);
        bus.write_bytes(in_title + 1, b"Options");

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, in_title);
        bus.write_long(sp + 4, ctrl_handle);
        disp.dispatch_control(true, 0x15F, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_byte(ctrl_ptr + 40), 7);
        assert_eq!(bus.read_bytes(ctrl_ptr + 41, 7), b"Options");
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);
    }

    // SetCtlValue clamps to [contrlMin, contrlMax] per IM:I I-328.

    #[test]
    fn setctlvalue_clamps_above_max() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        cpu.write_reg(Register::A7, sp);
        let ctrl_ptr = bus.alloc(40);
        bus.write_word(ctrl_ptr + 20, 0);
        bus.write_word(ctrl_ptr + 22, 100);
        let handle = bus.alloc(4);
        bus.write_long(handle, ctrl_ptr);
        bus.write_word(sp, 500);
        bus.write_long(sp + 2, handle);
        disp.dispatch_control(true, 0x163, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(ctrl_ptr + 18) as i16, 100);
    }

    #[test]
    fn setctlvalue_clamps_below_min() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        cpu.write_reg(Register::A7, sp);
        let ctrl_ptr = bus.alloc(40);
        bus.write_word(ctrl_ptr + 20, 50);
        bus.write_word(ctrl_ptr + 22, 100);
        let handle = bus.alloc(4);
        bus.write_long(handle, ctrl_ptr);
        bus.write_word(sp, 10);
        bus.write_long(sp + 2, handle);
        disp.dispatch_control(true, 0x163, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(ctrl_ptr + 18) as i16, 50);
    }

    #[test]
    fn setctlvalue_passes_through_inrange() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        cpu.write_reg(Register::A7, sp);
        let ctrl_ptr = bus.alloc(40);
        bus.write_word(ctrl_ptr + 20, 0);
        bus.write_word(ctrl_ptr + 22, 100);
        let handle = bus.alloc(4);
        bus.write_long(handle, ctrl_ptr);
        bus.write_word(sp, 42);
        bus.write_long(sp + 2, handle);
        disp.dispatch_control(true, 0x163, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(ctrl_ptr + 18) as i16, 42);
    }

    #[test]
    fn setctlvalue_popupmenuproc_variant_does_not_clamp_to_menu_id_min() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        cpu.write_reg(Register::A7, sp);
        let ctrl_ptr = bus.alloc(40);
        bus.write_word(ctrl_ptr + 20, 1300); // popupMenuProc stores MENU id in min
        bus.write_word(ctrl_ptr + 22, 0);
        let handle = bus.alloc(4);
        bus.write_long(handle, ctrl_ptr);
        disp.control_proc_ids.insert(ctrl_ptr, 1009);
        bus.write_word(sp, 3);
        bus.write_long(sp + 2, handle);

        disp.dispatch_control(true, 0x163, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_word(ctrl_ptr + 18) as i16, 3);
    }

    // SetCtlMin / SetCtlMax must bump the current value into the new range if it's outside.
    #[test]
    fn setctlmin_bumps_below_value_up() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        cpu.write_reg(Register::A7, sp);
        let ctrl_ptr = bus.alloc(40);
        bus.write_word(ctrl_ptr + 18, 5); // current value
        bus.write_word(ctrl_ptr + 20, 0); // min
        bus.write_word(ctrl_ptr + 22, 100); // max
        let handle = bus.alloc(4);
        bus.write_long(handle, ctrl_ptr);
        bus.write_word(sp, 20); // new min
        bus.write_long(sp + 2, handle);
        disp.dispatch_control(true, 0x164, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(ctrl_ptr + 20) as i16, 20);
        assert_eq!(
            bus.read_word(ctrl_ptr + 18) as i16,
            20,
            "current value must be bumped up to the new minimum"
        );
    }

    #[test]
    fn setctlmax_pulls_above_value_down() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        cpu.write_reg(Register::A7, sp);
        let ctrl_ptr = bus.alloc(40);
        bus.write_word(ctrl_ptr + 18, 80); // current value
        bus.write_word(ctrl_ptr + 20, 0); // min
        bus.write_word(ctrl_ptr + 22, 100); // max
        let handle = bus.alloc(4);
        bus.write_long(handle, ctrl_ptr);
        bus.write_word(sp, 50); // new max
        bus.write_long(sp + 2, handle);
        disp.dispatch_control(true, 0x165, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(ctrl_ptr + 22) as i16, 50);
        assert_eq!(
            bus.read_word(ctrl_ptr + 18) as i16,
            50,
            "current value must be pulled down to the new maximum"
        );
    }

    #[test]
    fn setctlmin_inrange_value_untouched() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        cpu.write_reg(Register::A7, sp);
        let ctrl_ptr = bus.alloc(40);
        bus.write_word(ctrl_ptr + 18, 50); // current value
        bus.write_word(ctrl_ptr + 20, 0);
        bus.write_word(ctrl_ptr + 22, 100);
        let handle = bus.alloc(4);
        bus.write_long(handle, ctrl_ptr);
        bus.write_word(sp, 10); // new min, still below value
        bus.write_long(sp + 2, handle);
        disp.dispatch_control(true, 0x164, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(ctrl_ptr + 20) as i16, 10);
        assert_eq!(
            bus.read_word(ctrl_ptr + 18) as i16,
            50,
            "current value in range must stay unchanged"
        );
    }

    // ShowControl/HideControl/MoveControl semantics per Inside Macintosh
    // Volume I (1985), pp. I-328 to I-329.
    #[test]
    fn showcontrol_sets_contrlvis_visible_and_pops_handle_arg() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 0, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, ctrl_handle);
        disp.dispatch_control(true, 0x157, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_byte(ctrl_ptr + 16), 255);
        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
    }

    #[test]
    fn hidecontrol_clears_contrlvis_and_pops_handle_arg() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, ctrl_handle);
        disp.dispatch_control(true, 0x158, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_byte(ctrl_ptr + 16), 0);
        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
    }

    #[test]
    fn movecontrol_repositions_rect_preserves_size_and_pops_args() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 40, 70), 255, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 35); // v
        bus.write_word(sp + 2, 90); // h
        bus.write_long(sp + 4, ctrl_handle);
        disp.dispatch_control(true, 0x159, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_word(ctrl_ptr + 8) as i16, 35);
        assert_eq!(bus.read_word(ctrl_ptr + 10) as i16, 90);
        assert_eq!(bus.read_word(ctrl_ptr + 12) as i16, 65);
        assert_eq!(bus.read_word(ctrl_ptr + 14) as i16, 140);
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);
    }

    // HiliteControl semantics per Macintosh Toolbox Essentials 1992, p. 5-98.
    #[test]
    fn hilite_control_writes_contrlhilite_and_pops_stack() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 1);
        bus.write_long(sp + 2, ctrl_handle);
        disp.dispatch_control(true, 0x15D, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_byte(ctrl_ptr + 17), 1);
        assert_eq!(cpu.read_reg(Register::A7), sp + 6);
    }

    #[test]
    fn hilite_control_255_marks_control_inactive() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 255);
        bus.write_long(sp + 2, ctrl_handle);
        disp.dispatch_control(true, 0x15D, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_byte(ctrl_ptr + 17), 255);
        assert_eq!(cpu.read_reg(Register::A7), sp + 6);
    }

    #[test]
    fn inactive_checkbox_and_radio_titles_use_gray_device_index() {
        let (mut disp, mut cpu, mut bus) = setup_with_port();
        let screen_base = bus.alloc(128 * 128);
        let row_bytes = 128u32;
        disp.set_screen_mode_for_test(screen_base, row_bytes, 128, 128, 8);
        disp.device_clut = [[0x2020, 0x4040, 0x6060]; 256];
        disp.device_clut[0] = [0xFFFF, 0xFFFF, 0xFFFF];
        disp.device_clut[42] = [0xA1A1, 0xA1A1, 0xA1A1];
        disp.device_clut[255] = [0, 0, 0];
        bus.write_long(0x0824, screen_base);
        bus.write_word(0x0828, row_bytes as u16);

        let gdevice_handle = disp.ensure_main_gdevice(&mut bus);
        bus.write_long(0x08A4, gdevice_handle);
        bus.write_long(0x0CC8, gdevice_handle);
        let gdevice = bus.read_long(gdevice_handle);
        let pixmap_handle = bus.read_long(gdevice + 22);
        let pixmap = bus.read_long(pixmap_handle);
        let ctab_handle = bus.read_long(pixmap + 42);
        let ctab = bus.read_long(ctab_handle);
        for index in 0u32..256 {
            let entry = ctab + 8 + index * 8;
            bus.write_word(entry, index as u16);
            bus.write_word(entry + 2, 0x2020);
            bus.write_word(entry + 4, 0x4040);
            bus.write_word(entry + 6, 0x6060);
        }
        let white_entry = ctab + 8;
        bus.write_word(white_entry, 0);
        bus.write_word(white_entry + 2, 0xFFFF);
        bus.write_word(white_entry + 4, 0xFFFF);
        bus.write_word(white_entry + 6, 0xFFFF);
        // Deliberately put the exact gray at a different GDevice-table index.
        // The inactive title draw path should resolve against device_clut,
        // matching screen export, not this current-GDevice table.
        let gray_entry = ctab + 8 + 17 * 8;
        bus.write_word(gray_entry, 17);
        bus.write_word(gray_entry + 2, 0xA1A1);
        bus.write_word(gray_entry + 4, 0xA1A1);
        bus.write_word(gray_entry + 6, 0xA1A1);
        let black_entry = ctab + 8 + 255 * 8;
        bus.write_word(black_entry, 255);
        bus.write_word(black_entry + 2, 0);
        bus.write_word(black_entry + 4, 0);
        bus.write_word(black_entry + 6, 0);

        for offset in 0..(row_bytes * 128) {
            bus.write_byte(screen_base + offset, 0);
        }
        let window_ptr = disp.current_port;
        bus.write_word(window_ptr + 8, 0);
        bus.write_word(window_ptr + 10, 0);
        bus.write_word(window_ptr + 16, 0);
        bus.write_word(window_ptr + 18, 0);
        bus.write_word(window_ptr + 20, 128);
        bus.write_word(window_ptr + 22, 128);

        for (proc_id, rect, value) in [(1, (20, 20, 40, 118), 1), (2, (52, 20, 72, 118), 1)] {
            let ctrl_ptr = bus.alloc(296);
            disp.initialize_control_record(
                &mut bus, ctrl_ptr, window_ptr, rect, b"Sound", true, value, 0, 1, proc_id, 0,
            );
            bus.write_byte(ctrl_ptr + 17, 255);
            disp.draw_control(&mut cpu, &mut bus, ctrl_ptr);
        }

        let checkbox_gray = count_pixel_index(&bus, screen_base, row_bytes, 20, 35, 40, 118, 42);
        let checkbox_black = count_pixel_index(&bus, screen_base, row_bytes, 20, 35, 40, 118, 255);
        let radio_gray = count_pixel_index(&bus, screen_base, row_bytes, 52, 35, 72, 118, 42);
        let radio_black = count_pixel_index(&bus, screen_base, row_bytes, 52, 35, 72, 118, 255);

        assert!(
            checkbox_gray > 12,
            "inactive checkbox title should draw with the device gray index"
        );
        assert_eq!(
            checkbox_black, 0,
            "inactive checkbox title must not leave black glyph pixels"
        );
        assert!(
            radio_gray > 12,
            "inactive radio title should draw with the device gray index"
        );
        assert_eq!(
            radio_black, 0,
            "inactive radio title must not leave black glyph pixels"
        );
    }

    // TrackControl semantics per Macintosh Toolbox Essentials 1992, pp. 5-89 to 5-90.
    #[test]
    fn track_control_visible_active_button_hit_returns_inbutton() {
        let (mut disp, mut cpu, mut bus) = setup();
        disp.enable_input_trace_capture();
        let sp = 0x300000u32;
        let (ctrl_handle, _) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0);
        bus.write_word(sp + 4, 15);
        bus.write_word(sp + 6, 25);
        bus.write_long(sp + 8, ctrl_handle);
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_word(sp + 12), 10);
        assert_eq!(cpu.read_reg(Register::A7), sp + 12);
        let trace = disp.input_trace_text();
        assert!(trace.contains("A968 action=start start=(15,25)"));
        assert!(trace.contains("part=10 highlighted_item=none outcome=visible_active_hit"));
    }

    #[test]
    fn track_control_button_systemless_theme_tracks_pressed_state_until_release() {
        let (mut disp, mut cpu, mut bus) = setup_with_port();
        disp.set_ui_theme_id(UiThemeId::SystemlessDefault);
        disp.enable_input_trace_capture();
        let sp = 0x300000u32;
        let window = disp.current_port;
        let row_bytes = 64u32;
        let base = bus.alloc(row_bytes * 342);
        disp.set_screen_mode_for_test(base, row_bytes, 512, 342, 1);
        clear_1bpp_screen(&mut bus, base, row_bytes, 342);
        let (ctrl_handle, ctrl_ptr) =
            alloc_button_control(&mut disp, &mut bus, window, (20, 20, 40, 80));
        let probe_x = 30;
        let probe_y = 30;

        disp.mouse_button = true;
        disp.mouse_pos = (probe_y, probe_x);
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0);
        bus.write_word(sp + 4, probe_y as u16);
        bus.write_word(sp + 6, probe_x as u16);
        bus.write_long(sp + 8, ctrl_handle);
        bus.write_word(sp + 12, 0xBEEF);

        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp,
            "simple TrackControl should defer the stack pop until mouse-up"
        );
        assert!(disp.control_tracking.is_some());
        assert_eq!(bus.read_word(sp + 12), 0xBEEF);
        assert_eq!(bus.read_byte(ctrl_ptr + 17), 1);
        assert!(
            screen_pixel_is_set(&bus, base, row_bytes, probe_x, probe_y),
            "held simple TrackControl should route pressed button chrome through the provider"
        );

        disp.mouse_pos = (10, 10);
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_byte(ctrl_ptr + 17), 0);
        assert!(
            !screen_pixel_is_set(&bus, base, row_bytes, probe_x, probe_y),
            "dragging outside should redraw unpressed provider chrome"
        );

        disp.mouse_pos = (probe_y, probe_x);
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_byte(ctrl_ptr + 17), 1);
        assert!(
            screen_pixel_is_set(&bus, base, row_bytes, probe_x, probe_y),
            "dragging back inside should restore provider pressed chrome"
        );

        disp.mouse_button = false;
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 12);
        assert_eq!(bus.read_word(sp + 12), 10);
        assert_eq!(bus.read_byte(ctrl_ptr + 17), 0);
        assert!(disp.control_tracking.is_none());
        assert!(
            !screen_pixel_is_set(&bus, base, row_bytes, probe_x, probe_y),
            "release should restore unpressed provider chrome before returning"
        );
        let trace = disp.input_trace_text();
        assert!(trace.contains("outcome=simple_tracking_started"));
        assert!(trace.contains("outcome=simple_no_part"));
        assert!(trace.contains("outcome=simple_part_highlighted"));
        assert!(trace.contains("part=10 highlighted_item=none outcome=simple_part_selected"));
    }

    fn trackcontrol_button_release_result_for_theme(
        theme_id: UiThemeId,
        release_inside: bool,
    ) -> (u16, u32, u8, bool) {
        let (mut disp, mut cpu, mut bus) = setup_with_port();
        disp.set_ui_theme_id(theme_id);
        let sp = 0x300000u32;
        let window = disp.current_port;
        let screen_base = bus.read_long(window + 2);
        let row_bytes = (bus.read_word(window + 6) & 0x3FFF) as u32;
        disp.set_screen_mode_for_test(screen_base, row_bytes, 512, 342, 1);
        let (ctrl_handle, ctrl_ptr) =
            alloc_button_control(&mut disp, &mut bus, window, (20, 20, 40, 80));

        disp.mouse_button = true;
        disp.mouse_pos = (30, 30);
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0);
        bus.write_word(sp + 4, 30);
        bus.write_word(sp + 6, 30);
        bus.write_long(sp + 8, ctrl_handle);
        bus.write_word(sp + 12, 0xBEEF);
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        if !release_inside {
            disp.mouse_pos = (10, 10);
            disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
                .unwrap()
                .unwrap();
        }
        disp.mouse_button = false;
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        (
            bus.read_word(sp + 12),
            cpu.read_reg(Register::A7),
            bus.read_byte(ctrl_ptr + 17),
            disp.control_tracking.is_some(),
        )
    }

    #[test]
    fn systemless_theme_does_not_change_trackcontrol_part_codes() {
        // IM:I I-323: TrackControl returns the same part code on inside
        // release and 0 on outside release. Theme chrome must not alter those
        // guest-visible Control Manager results.
        let classic_inside =
            trackcontrol_button_release_result_for_theme(UiThemeId::ClassicSystem7, true);
        let themed_inside =
            trackcontrol_button_release_result_for_theme(UiThemeId::SystemlessDefault, true);
        let classic_outside =
            trackcontrol_button_release_result_for_theme(UiThemeId::ClassicSystem7, false);
        let themed_outside =
            trackcontrol_button_release_result_for_theme(UiThemeId::SystemlessDefault, false);

        assert_eq!(classic_inside, (10, 0x30000C, 0, false));
        assert_eq!(classic_outside, (0, 0x30000C, 0, false));
        assert_eq!(
            themed_inside, classic_inside,
            "systemless-default must not change TrackControl inside-release part codes"
        );
        assert_eq!(
            themed_outside, classic_outside,
            "systemless-default must not change TrackControl outside-release part codes"
        );
    }

    fn trackcontrol_popup_value_result_for_theme(
        theme_id: UiThemeId,
        select_second_item: bool,
    ) -> (u16, u32, i16, bool) {
        let (mut disp, mut cpu, mut bus) = setup_with_port();
        disp.set_ui_theme_id(theme_id);
        let sp = 0x300000u32;
        let window = disp.current_port;
        let screen_base = bus.read_long(window + 2);
        let row_bytes = (bus.read_word(window + 6) & 0x3FFF) as u32;
        disp.set_screen_mode_for_test(screen_base, row_bytes, 512, 342, 1);
        clear_1bpp_screen(&mut bus, screen_base, row_bytes, 342);

        let owner = bus.read_long(bus.read_long(cpu.read_reg(Register::A5)));
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 130), 255, 0);
        bus.write_long(ctrl_ptr + 4, owner);
        bus.write_word(ctrl_ptr + 18, 1);
        bus.write_word(ctrl_ptr + 20, 902);
        bus.write_word(ctrl_ptr + 22, 0);
        disp.control_proc_ids.insert(ctrl_ptr, 1009);
        disp.menus.push(Menu {
            id: 902,
            title: "Mode".to_string(),
            items: vec![
                MenuItem {
                    text: "First".to_string(),
                    icon: 0,
                    key_equiv: 0,
                    mark: 0,
                    style: 0,
                    enabled: true,
                },
                MenuItem {
                    text: "Second".to_string(),
                    icon: 0,
                    key_equiv: 0,
                    mark: 0,
                    style: 0,
                    enabled: true,
                },
            ],
            enabled: true,
            handle: 0,
            in_menu_bar: false,
            visible_in_menu_bar: false,
            hierarchical: false,
        });

        disp.mouse_button = true;
        disp.mouse_pos = (15, 25);
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0xFFFF_FFFF);
        bus.write_word(sp + 4, 15);
        bus.write_word(sp + 6, 25);
        bus.write_long(sp + 8, ctrl_handle);
        bus.write_word(sp + 12, 0xBEEF);
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(cpu.read_reg(Register::A7), sp);

        let (dropdown_top, dropdown_left, dropdown_bottom, _) = disp
            .control_tracking
            .as_ref()
            .map(|tracking| tracking.dropdown_rect)
            .expect("popup tracking should open a dropdown");
        if select_second_item {
            disp.mouse_pos = (dropdown_top + 1 + 16 + 1, dropdown_left + 5);
        } else {
            disp.mouse_pos = (dropdown_bottom + 8, dropdown_left + 5);
        }
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        disp.mouse_button = false;
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        (
            bus.read_word(sp + 12),
            cpu.read_reg(Register::A7),
            bus.read_word(ctrl_ptr + 18) as i16,
            disp.control_tracking.is_some(),
        )
    }

    #[test]
    fn systemless_theme_does_not_change_popup_trackcontrol_value_results() {
        // MTE 1992 describes popup contrlValue as the chosen menu item
        // number, and TrackControl as returning the release part code.
        // Theme chrome must not alter either guest-visible result.
        let classic_select =
            trackcontrol_popup_value_result_for_theme(UiThemeId::ClassicSystem7, true);
        let themed_select =
            trackcontrol_popup_value_result_for_theme(UiThemeId::SystemlessDefault, true);
        let classic_no_selection =
            trackcontrol_popup_value_result_for_theme(UiThemeId::ClassicSystem7, false);
        let themed_no_selection =
            trackcontrol_popup_value_result_for_theme(UiThemeId::SystemlessDefault, false);

        assert_eq!(classic_select, (10, 0x30000C, 2, false));
        assert_eq!(classic_no_selection, (0, 0x30000C, 1, false));
        assert_eq!(
            themed_select, classic_select,
            "systemless-default must not change popup TrackControl selected values"
        );
        assert_eq!(
            themed_no_selection, classic_no_selection,
            "systemless-default must not change popup TrackControl no-selection values"
        );
    }

    #[test]
    fn track_control_popup_menu_tracks_and_updates_value_on_release() {
        let (mut disp, mut cpu, mut bus) = setup_with_port();
        disp.enable_input_trace_capture();
        let sp = 0x300000u32;
        let owner = bus.read_long(bus.read_long(cpu.read_reg(Register::A5)));
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 130), 255, 0);
        bus.write_long(ctrl_ptr + 4, owner);
        bus.write_word(ctrl_ptr + 18, 1);
        bus.write_word(ctrl_ptr + 20, 900); // popupMenuProc stores MENU id in min
        bus.write_word(ctrl_ptr + 22, 0);
        disp.control_proc_ids.insert(ctrl_ptr, 1009);
        disp.menus.push(Menu {
            id: 900,
            title: "Squadies".to_string(),
            items: vec![
                MenuItem {
                    text: "Duke".to_string(),
                    icon: 0,
                    key_equiv: 0,
                    mark: 0,
                    style: 0,
                    enabled: true,
                },
                MenuItem {
                    text: "Carnage".to_string(),
                    icon: 0,
                    key_equiv: 0,
                    mark: 0,
                    style: 0,
                    enabled: true,
                },
            ],
            enabled: true,
            handle: 0,
            in_menu_bar: false,
            hierarchical: false,
            visible_in_menu_bar: false,
        });

        disp.mouse_button = true;
        disp.mouse_pos = (15, 25);
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0);
        bus.write_word(sp + 4, 15);
        bus.write_word(sp + 6, 25);
        bus.write_long(sp + 8, ctrl_handle);
        bus.write_word(sp + 12, 0xBEEF);

        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(
            cpu.read_reg(Register::A7),
            sp,
            "popup tracking should defer the TrackControl stack pop"
        );
        let dropdown_rect = disp
            .control_tracking
            .as_ref()
            .map(|tracking| tracking.dropdown_rect)
            .expect("popup tracking should open a dropdown");
        let (dropdown_top, dropdown_left, dropdown_bottom, _) = dropdown_rect;
        assert_eq!(
            (dropdown_top, dropdown_left, dropdown_bottom),
            (9, 20, 43),
            "popup tracking should align selected item 1 with the control box, \
             not open below the control bottom"
        );
        assert_eq!(bus.read_word(sp + 12), 0xBEEF);

        disp.mouse_pos = (dropdown_top + 1 + 16 + 1, dropdown_left + 5);
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(
            disp.control_tracking
                .as_ref()
                .map(|tracking| tracking.highlighted_item),
            Some(2)
        );

        disp.mouse_button = false;
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 12);
        assert_eq!(bus.read_word(sp + 12), 10);
        assert_eq!(bus.read_word(ctrl_ptr + 18) as i16, 2);
        assert!(disp.control_tracking.is_none());
        let trace = disp.input_trace_text();
        assert!(trace.contains("A968 action=start start=(15,25)"));
        assert!(trace.contains("outcome=open_popup_tracking"));
        assert!(trace.contains("A968 action=tracking_update"));
        assert!(trace.contains("tracking=menu:idle dialog:idle control:active"));
        assert!(trace.contains("highlighted_item=2 outcome=popup_item_highlighted"));
        assert!(trace.contains("A968 action=tracking_finish"));
        assert!(trace.contains("part=10 highlighted_item=2 outcome=popup_item_selected"));
    }

    #[test]
    fn track_control_popup_systemless_theme_routes_highlight_through_menu_provider() {
        let (mut disp, mut cpu, mut bus) = setup_with_port();
        disp.set_ui_theme_id(UiThemeId::SystemlessDefault);
        disp.enable_input_trace_capture();
        let sp = 0x300000u32;
        let window = disp.current_port;
        let screen_base = bus.read_long(window + 2);
        let row_bytes = (bus.read_word(window + 6) & 0x3FFF) as u32;
        disp.set_screen_mode_for_test(screen_base, row_bytes, 512, 342, 1);
        clear_1bpp_screen(&mut bus, screen_base, row_bytes, 342);

        let owner = bus.read_long(bus.read_long(cpu.read_reg(Register::A5)));
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 130), 255, 0);
        bus.write_long(ctrl_ptr + 4, owner);
        bus.write_word(ctrl_ptr + 18, 1);
        bus.write_word(ctrl_ptr + 20, 901);
        bus.write_word(ctrl_ptr + 22, 0);
        disp.control_proc_ids.insert(ctrl_ptr, 1009);
        disp.menus.push(Menu {
            id: 901,
            title: "Formation".to_string(),
            items: vec![
                MenuItem {
                    text: "Duke".to_string(),
                    icon: 0,
                    key_equiv: 0,
                    mark: 0,
                    style: 0,
                    enabled: true,
                },
                MenuItem {
                    text: "Carnage".to_string(),
                    icon: 0,
                    key_equiv: 0,
                    mark: 0,
                    style: 0,
                    enabled: true,
                },
            ],
            enabled: true,
            handle: 0,
            in_menu_bar: false,
            visible_in_menu_bar: false,
            hierarchical: false,
        });

        disp.mouse_button = true;
        disp.mouse_pos = (15, 25);
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0);
        bus.write_word(sp + 4, 15);
        bus.write_word(sp + 6, 25);
        bus.write_long(sp + 8, ctrl_handle);
        bus.write_word(sp + 12, 0xBEEF);

        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        let (dropdown_top, dropdown_left, _dropdown_bottom, dropdown_right) = disp
            .control_tracking
            .as_ref()
            .map(|tracking| tracking.dropdown_rect)
            .expect("popup tracking should open a dropdown");
        let item_two_top = dropdown_top + 1 + 16;
        let raw_inversion_probe_x = dropdown_right - 10;
        let raw_inversion_probe_y = item_two_top + 5;
        assert!(
            !screen_pixel_is_set(
                &bus,
                screen_base,
                row_bytes,
                raw_inversion_probe_x,
                raw_inversion_probe_y
            ),
            "unhighlighted popup item row should leave blank row space clear"
        );

        disp.mouse_pos = (item_two_top + 1, dropdown_left + 5);
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(
            disp.control_tracking
                .as_ref()
                .map(|tracking| tracking.highlighted_item),
            Some(2)
        );
        let provider_rail_pixels = count_set_pixels(
            &bus,
            screen_base,
            row_bytes,
            item_two_top,
            dropdown_left,
            item_two_top + 16,
            dropdown_left + 12,
        );
        assert!(
            provider_rail_pixels > 0,
            "systemless-default popup tracking should redraw provider-owned item rail chrome"
        );
        assert!(
            !screen_pixel_is_set(
                &bus,
                screen_base,
                row_bytes,
                raw_inversion_probe_x,
                raw_inversion_probe_y
            ),
            "systemless-default popup tracking must not use raw full-row inversion"
        );

        disp.mouse_button = false;
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 12);
        assert_eq!(bus.read_word(sp + 12), 10);
        assert_eq!(bus.read_word(ctrl_ptr + 18) as i16, 2);
        assert!(disp.control_tracking.is_none());
        let trace = disp.input_trace_text();
        assert!(trace.contains("A968 action=tracking_update"));
        assert!(trace.contains("highlighted_item=2 outcome=popup_item_highlighted"));
        assert!(trace.contains("part=10 highlighted_item=2 outcome=popup_item_selected"));
    }

    #[test]
    fn track_control_point_outside_returns_zero() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (ctrl_handle, _) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0);
        bus.write_word(sp + 4, 5);
        bus.write_word(sp + 6, 5);
        bus.write_long(sp + 8, ctrl_handle);
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_word(sp + 12), 0);
        assert_eq!(cpu.read_reg(Register::A7), sp + 12);
    }

    #[test]
    fn track_control_inactive_or_invisible_control_returns_zero() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (inactive_handle, _) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 255);
        let (invisible_handle, _) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 0, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0);
        bus.write_word(sp + 4, 15);
        bus.write_word(sp + 6, 25);
        bus.write_long(sp + 8, inactive_handle);
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(sp + 12), 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0);
        bus.write_word(sp + 4, 15);
        bus.write_word(sp + 6, 25);
        bus.write_long(sp + 8, invisible_handle);
        disp.dispatch_control(true, 0x168, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(sp + 12), 0);
        assert_eq!(cpu.read_reg(Register::A7), sp + 12);
    }

    // DrawControls semantics per IM:I (1985) I-322 and MTE (1992) 5-87..5-88.
    #[test]
    fn drawcontrols_pops_window_arg_and_preserves_control_list_links() {
        let (mut disp, mut cpu, mut bus) = setup_with_port();
        let sp = 0x300000u32;
        let a5 = cpu.read_reg(Register::A5);
        let qd_globals = bus.read_long(a5);
        let window_ptr = bus.read_long(qd_globals);

        let (first_handle, first_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);
        let (second_handle, second_ptr) = alloc_control_handle(&mut bus, (18, 28, 38, 68), 255, 0);
        bus.write_long(first_ptr + 4, window_ptr);
        bus.write_long(second_ptr + 4, window_ptr);
        bus.write_long(first_ptr, 0);
        bus.write_long(second_ptr, first_handle);
        bus.write_long(window_ptr + 140, second_handle);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, window_ptr);
        disp.dispatch_control(true, 0x169, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
        assert_eq!(bus.read_long(window_ptr + 140), second_handle);
        assert_eq!(bus.read_long(second_ptr), first_handle);
        assert_eq!(bus.read_long(first_ptr), 0);
    }

    // FindControl semantics per IM:I (1985) I-323 and MTE (1992) 5-89.
    #[test]
    fn findcontrol_visible_active_hit_returns_inbutton_and_control_handle() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let window_ptr = bus.alloc(200);
        let which_ctrl_out = bus.alloc(4);
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);
        bus.write_long(ctrl_ptr, 0);
        bus.write_long(window_ptr + 140, ctrl_handle);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, which_ctrl_out);
        bus.write_long(sp + 4, window_ptr);
        bus.write_word(sp + 8, 15);
        bus.write_word(sp + 10, 25);
        disp.dispatch_control(true, 0x16C, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(bus.read_long(which_ctrl_out), ctrl_handle);
        assert_eq!(bus.read_word(sp + 12), 10);
        assert_eq!(cpu.read_reg(Register::A7), sp + 12);
    }

    #[test]
    fn findcontrol_inactive_invisible_or_miss_returns_zero_and_nil() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let window_ptr = bus.alloc(200);
        let which_ctrl_out = bus.alloc(4);

        let (inactive_handle, inactive_ptr) =
            alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 255);
        bus.write_long(inactive_ptr, 0);
        bus.write_long(window_ptr + 140, inactive_handle);
        cpu.write_reg(Register::A7, sp);
        bus.write_long(which_ctrl_out, 0xDEAD_BEEF);
        bus.write_long(sp, which_ctrl_out);
        bus.write_long(sp + 4, window_ptr);
        bus.write_word(sp + 8, 15);
        bus.write_word(sp + 10, 25);
        disp.dispatch_control(true, 0x16C, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_long(which_ctrl_out), 0);
        assert_eq!(bus.read_word(sp + 12), 0);
        assert_eq!(cpu.read_reg(Register::A7), sp + 12);

        let (invisible_handle, invisible_ptr) =
            alloc_control_handle(&mut bus, (10, 20, 30, 60), 0, 0);
        bus.write_long(invisible_ptr, 0);
        bus.write_long(window_ptr + 140, invisible_handle);
        cpu.write_reg(Register::A7, sp);
        bus.write_long(which_ctrl_out, 0xDEAD_BEEF);
        bus.write_long(sp, which_ctrl_out);
        bus.write_long(sp + 4, window_ptr);
        bus.write_word(sp + 8, 15);
        bus.write_word(sp + 10, 25);
        disp.dispatch_control(true, 0x16C, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_long(which_ctrl_out), 0);
        assert_eq!(bus.read_word(sp + 12), 0);
        assert_eq!(cpu.read_reg(Register::A7), sp + 12);

        let (visible_handle, visible_ptr) =
            alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);
        bus.write_long(visible_ptr, 0);
        bus.write_long(window_ptr + 140, visible_handle);
        cpu.write_reg(Register::A7, sp);
        bus.write_long(which_ctrl_out, 0xDEAD_BEEF);
        bus.write_long(sp, which_ctrl_out);
        bus.write_long(sp + 4, window_ptr);
        bus.write_word(sp + 8, 5);
        bus.write_word(sp + 10, 5);
        disp.dispatch_control(true, 0x16C, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_long(which_ctrl_out), 0);
        assert_eq!(bus.read_word(sp + 12), 0);
        assert_eq!(cpu.read_reg(Register::A7), sp + 12);
    }

    #[test]
    fn testcontrol_returns_inbutton_for_push_buttons_and_incheckbox_for_check_family() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;

        let (button_handle, button_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);
        disp.control_proc_ids.insert(button_ptr, 0);
        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 15);
        bus.write_word(sp + 2, 25);
        bus.write_long(sp + 4, button_handle);
        bus.write_word(sp + 8, 0xDEAD);
        disp.dispatch_control(true, 0x166, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(sp + 8), 10);
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);

        let (checkbox_handle, checkbox_ptr) =
            alloc_control_handle(&mut bus, (40, 50, 80, 120), 255, 0);
        disp.control_proc_ids.insert(checkbox_ptr, 1);
        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 60);
        bus.write_word(sp + 2, 70);
        bus.write_long(sp + 4, checkbox_handle);
        bus.write_word(sp + 8, 0xBEEF);
        disp.dispatch_control(true, 0x166, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(sp + 8), 11);
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);

        let (radio_handle, radio_ptr) = alloc_control_handle(&mut bus, (90, 30, 120, 100), 255, 0);
        disp.control_proc_ids.insert(radio_ptr, 2);
        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 100);
        bus.write_word(sp + 2, 40);
        bus.write_long(sp + 4, radio_handle);
        bus.write_word(sp + 8, 0xCAFE);
        disp.dispatch_control(true, 0x166, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(sp + 8), 11);
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);
    }

    #[test]
    fn testcontrol_returns_zero_for_inactive_invisible_or_miss() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;

        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);
        disp.control_proc_ids.insert(ctrl_ptr, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 5);
        bus.write_word(sp + 2, 5);
        bus.write_long(sp + 4, ctrl_handle);
        bus.write_word(sp + 8, 0xDEAD);
        disp.dispatch_control(true, 0x166, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(sp + 8), 0);

        bus.write_byte(ctrl_ptr + 17, 255);
        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 15);
        bus.write_word(sp + 2, 25);
        bus.write_long(sp + 4, ctrl_handle);
        bus.write_word(sp + 8, 0xBEEF);
        disp.dispatch_control(true, 0x166, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(sp + 8), 0);

        bus.write_byte(ctrl_ptr + 17, 0);
        bus.write_byte(ctrl_ptr + 16, 0);
        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 15);
        bus.write_word(sp + 2, 25);
        bus.write_long(sp + 4, ctrl_handle);
        bus.write_word(sp + 8, 0xCAFE);
        disp.dispatch_control(true, 0x166, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(sp + 8), 0);
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);
    }

    #[test]
    fn testcontrol_function_protocol_consumes_controlhandle_and_point_and_writes_integer_result() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);
        disp.control_proc_ids.insert(ctrl_ptr, 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 15);
        bus.write_word(sp + 2, 25);
        bus.write_long(sp + 4, ctrl_handle);
        bus.write_word(sp + 8, 0xCAFE);
        bus.write_word(sp + 10, 0xBEEF);

        disp.dispatch_control(true, 0x166, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 8);
        assert_eq!(bus.read_word(sp + 8), 10);
        assert_eq!(
            bus.read_word(sp + 10),
            0xBEEF,
            "TestControl must only overwrite the INTEGER result slot"
        );
    }

    #[test]
    fn testcontrol_returns_standard_scrollbar_part_codes_for_vertical_scrollbar() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let (scroll_handle, _) =
            alloc_scrollbar_control(&mut disp, &mut bus, (60, 240, 220, 256), 255, 0, 40, 0, 100);

        for (pt_v, pt_h, expected) in [
            (70i16, 248i16, 20u16),
            (95, 248, 22),
            (126, 248, 129),
            (150, 248, 23),
            (210, 248, 21),
        ] {
            cpu.write_reg(Register::A7, sp);
            bus.write_word(sp, pt_v as u16);
            bus.write_word(sp + 2, pt_h as u16);
            bus.write_long(sp + 4, scroll_handle);
            bus.write_word(sp + 8, 0xBEEF);
            bus.write_word(sp + 10, 0xCAFE);

            disp.dispatch_control(true, 0x166, &mut cpu, &mut bus)
                .unwrap()
                .unwrap();

            assert_eq!(cpu.read_reg(Register::A7), sp + 8);
            assert_eq!(bus.read_word(sp + 8), expected);
            assert_eq!(bus.read_word(sp + 10), 0xCAFE);
        }
    }

    fn dispatch_testcontrol_part<C: CpuOps>(
        disp: &mut TrapDispatcher,
        cpu: &mut C,
        bus: &mut MacMemoryBus,
        sp: u32,
        ctrl_handle: u32,
        point: (i16, i16),
    ) -> (u16, u32, u16) {
        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, point.0 as u16);
        bus.write_word(sp + 2, point.1 as u16);
        bus.write_long(sp + 4, ctrl_handle);
        bus.write_word(sp + 8, 0xBEEF);
        bus.write_word(sp + 10, 0xCAFE);

        disp.dispatch_control(true, 0x166, cpu, bus)
            .unwrap()
            .unwrap();

        (
            bus.read_word(sp + 8),
            cpu.read_reg(Register::A7),
            bus.read_word(sp + 10),
        )
    }

    fn testcontrol_results_for_theme(theme_id: UiThemeId) -> Vec<(&'static str, u16, u32, u16)> {
        let (mut disp, mut cpu, mut bus) = setup();
        disp.set_ui_theme_id(theme_id);
        let sp = 0x300000u32;
        let mut results = Vec::new();

        let (button_handle, button_ptr) = alloc_control_handle(&mut bus, (10, 20, 30, 60), 255, 0);
        disp.control_proc_ids.insert(button_ptr, 0);
        let (part, stack, tail) =
            dispatch_testcontrol_part(&mut disp, &mut cpu, &mut bus, sp, button_handle, (15, 25));
        results.push(("button", part, stack, tail));

        let (checkbox_handle, checkbox_ptr) =
            alloc_control_handle(&mut bus, (40, 50, 80, 120), 255, 0);
        disp.control_proc_ids.insert(checkbox_ptr, 1);
        let (part, stack, tail) =
            dispatch_testcontrol_part(&mut disp, &mut cpu, &mut bus, sp, checkbox_handle, (60, 70));
        results.push(("checkbox", part, stack, tail));

        let (radio_handle, radio_ptr) = alloc_control_handle(&mut bus, (90, 30, 120, 100), 255, 0);
        disp.control_proc_ids.insert(radio_ptr, 2);
        let (part, stack, tail) =
            dispatch_testcontrol_part(&mut disp, &mut cpu, &mut bus, sp, radio_handle, (100, 40));
        results.push(("radio", part, stack, tail));

        let (scroll_handle, _) =
            alloc_scrollbar_control(&mut disp, &mut bus, (60, 240, 220, 256), 255, 0, 40, 0, 100);
        for (name, point) in [
            ("scroll_up_arrow", (70i16, 248i16)),
            ("scroll_page_up", (95, 248)),
            ("scroll_thumb", (126, 248)),
            ("scroll_page_down", (150, 248)),
            ("scroll_down_arrow", (210, 248)),
        ] {
            let (part, stack, tail) =
                dispatch_testcontrol_part(&mut disp, &mut cpu, &mut bus, sp, scroll_handle, point);
            results.push((name, part, stack, tail));
        }

        let (outside_handle, outside_ptr) =
            alloc_control_handle(&mut bus, (130, 20, 160, 80), 255, 0);
        disp.control_proc_ids.insert(outside_ptr, 0);
        let (part, stack, tail) =
            dispatch_testcontrol_part(&mut disp, &mut cpu, &mut bus, sp, outside_handle, (120, 15));
        results.push(("outside", part, stack, tail));

        let (inactive_handle, inactive_ptr) =
            alloc_control_handle(&mut bus, (170, 20, 200, 80), 255, 255);
        disp.control_proc_ids.insert(inactive_ptr, 0);
        let (part, stack, tail) = dispatch_testcontrol_part(
            &mut disp,
            &mut cpu,
            &mut bus,
            sp,
            inactive_handle,
            (180, 30),
        );
        results.push(("inactive", part, stack, tail));

        let (invisible_handle, invisible_ptr) =
            alloc_control_handle(&mut bus, (210, 20, 240, 80), 0, 0);
        disp.control_proc_ids.insert(invisible_ptr, 0);
        let (part, stack, tail) = dispatch_testcontrol_part(
            &mut disp,
            &mut cpu,
            &mut bus,
            sp,
            invisible_handle,
            (220, 30),
        );
        results.push(("invisible", part, stack, tail));

        results
    }

    #[test]
    fn systemless_theme_does_not_change_testcontrol_part_codes() {
        // IM:I I-315 defines standard Control Manager part codes. IM:I I-325
        // specifies that TestControl returns those codes for visible active
        // controls, or 0 for misses, invisible controls, and inactive controls.
        // Theme chrome must not alter those guest-visible hit-test results.
        let classic = testcontrol_results_for_theme(UiThemeId::ClassicSystem7);
        let themed = testcontrol_results_for_theme(UiThemeId::SystemlessDefault);
        let expected_stack = 0x300008u32;
        let expected_tail = 0xCAFEu16;

        assert_eq!(
            classic,
            vec![
                ("button", 10, expected_stack, expected_tail),
                ("checkbox", 11, expected_stack, expected_tail),
                ("radio", 11, expected_stack, expected_tail),
                ("scroll_up_arrow", 20, expected_stack, expected_tail),
                ("scroll_page_up", 22, expected_stack, expected_tail),
                ("scroll_thumb", 129, expected_stack, expected_tail),
                ("scroll_page_down", 23, expected_stack, expected_tail),
                ("scroll_down_arrow", 21, expected_stack, expected_tail),
                ("outside", 0, expected_stack, expected_tail),
                ("inactive", 0, expected_stack, expected_tail),
                ("invisible", 0, expected_stack, expected_tail),
            ]
        );
        assert_eq!(
            themed, classic,
            "systemless-default must not change TestControl part codes or stack protocol"
        );
    }

    // Draw1Control signature/no-op baseline per MTE (1992) 5-88.
    #[test]
    fn draw1control_nil_handle_is_noop_and_pops_arg() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0);

        disp.dispatch_control(true, 0x16D, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
    }

    #[test]
    fn draw1control_unknown_cdef_pict_title_draws_resource_pair() {
        let (mut disp, mut cpu, mut bus) = setup_with_port();
        let sp = 0x300000u32;
        let window = 0x181000u32;
        disp.set_current_port_for_test(window);
        let base = bus.read_long(window + 2);
        let row_bytes = (bus.read_word(window + 6) & 0x3FFF) as u32;
        disp.set_screen_mode_for_test(base, row_bytes, 512, 342, 1);

        disp.install_test_resource(
            &mut bus,
            *b"PICT",
            4096,
            &fill_rect_pict_resource((0, 0, 8, 8), (0, 0, 8, 4)),
        );
        disp.install_test_resource(
            &mut bus,
            *b"PICT",
            4097,
            &fill_rect_pict_resource((0, 0, 8, 8), (0, 4, 8, 8)),
        );

        let (ctrl_handle, ctrl_ptr) =
            alloc_button_control(&mut disp, &mut bus, window, (20, 20, 40, 100));
        disp.control_proc_ids.insert(ctrl_ptr, 3216);
        bus.write_byte(ctrl_ptr + 40, 4);
        bus.write_word(ctrl_ptr + 41, 4096);
        bus.write_word(ctrl_ptr + 43, 4097);

        clear_1bpp_screen(&mut bus, base, row_bytes, 342);
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, ctrl_handle);
        disp.dispatch_control(true, 0x16D, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
        assert!(
            screen_pixel_is_set(&bus, base, row_bytes, 35, 30),
            "normal unknown CDEF with a PICT-pair title should draw the first PICT"
        );
        assert!(
            !screen_pixel_is_set(&bus, base, row_bytes, 85, 30),
            "normal state should not draw the highlighted PICT"
        );

        clear_1bpp_screen(&mut bus, base, row_bytes, 342);
        bus.write_byte(ctrl_ptr + 17, 1);
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, ctrl_handle);
        disp.dispatch_control(true, 0x16D, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
        assert!(
            !screen_pixel_is_set(&bus, base, row_bytes, 35, 30),
            "highlighted state should not draw the normal PICT"
        );
        assert!(
            screen_pixel_is_set(&bus, base, row_bytes, 85, 30),
            "highlighted unknown CDEF with a PICT-pair title should draw the second PICT"
        );
    }

    #[test]
    fn draw1control_unknown_cdef_falls_back_to_button_title_chrome() {
        let (mut disp, mut cpu, mut bus) = setup_with_port();
        let sp = 0x300000u32;
        let window = 0x181000u32;
        disp.set_current_port_for_test(window);
        let base = bus.read_long(window + 2);
        let row_bytes = (bus.read_word(window + 6) & 0x3FFF) as u32;
        disp.set_screen_mode_for_test(base, row_bytes, 512, 342, 1);
        clear_1bpp_screen(&mut bus, base, row_bytes, 342);

        let (blank_handle, blank_ptr) =
            alloc_button_control(&mut disp, &mut bus, window, (20, 20, 40, 140));
        let (titled_handle, titled_ptr) =
            alloc_button_control(&mut disp, &mut bus, window, (60, 20, 80, 140));
        for ptr in [blank_ptr, titled_ptr] {
            disp.control_proc_ids.insert(ptr, 3216);
        }
        bus.write_byte(titled_ptr + 40, 4);
        bus.write_bytes(titled_ptr + 41, b"PLAY");

        for handle in [blank_handle, titled_handle] {
            cpu.write_reg(Register::A7, sp);
            bus.write_long(sp, handle);
            disp.dispatch_control(true, 0x16D, &mut cpu, &mut bus)
                .unwrap()
                .unwrap();
            assert_eq!(cpu.read_reg(Register::A7), sp + 4);
        }

        let blank_chrome = count_set_pixels(&bus, base, row_bytes, 20, 20, 40, 140);
        assert!(
            blank_chrome > 0,
            "unknown CDEF fallback should draw visible control chrome"
        );

        let mut title_differences = 0;
        for dy in 0..20 {
            for dx in 0..120 {
                let blank_pixel = screen_pixel_is_set(&bus, base, row_bytes, 20 + dx, 20 + dy);
                let titled_pixel = screen_pixel_is_set(&bus, base, row_bytes, 20 + dx, 60 + dy);
                if blank_pixel != titled_pixel {
                    title_differences += 1;
                }
            }
        }
        assert!(
            title_differences > 8,
            "unknown CDEF fallback should draw the ControlRecord title"
        );

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 65);
        bus.write_word(sp + 2, 30);
        bus.write_long(sp + 4, titled_handle);
        bus.write_word(sp + 8, 0xDEAD);
        disp.dispatch_control(true, 0x166, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(sp + 8), 10);
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);
    }

    #[test]
    fn draw1control_popup_control_preserves_current_gdevice_and_pops_arg() {
        let (mut disp, mut cpu, mut bus) = setup_with_port();
        let sp = 0x300000u32;
        let window_ptr = disp.current_port;
        let gdevice_before = disp.current_gdevice;
        let (ctrl_handle, ctrl_ptr) =
            alloc_button_control(&mut disp, &mut bus, window_ptr, (20, 20, 260, 60));
        disp.control_proc_ids.insert(ctrl_ptr, 1008);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, ctrl_handle);

        disp.dispatch_control(true, 0x16D, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
        assert_eq!(disp.current_gdevice, gdevice_before);
    }

    #[test]
    fn draw1control_systemless_theme_routes_popup_control_chrome_through_provider() {
        let sp = 0x300000u32;
        let bounds = (20, 20, 40, 120);

        let (mut classic, mut classic_cpu, mut classic_bus) = setup_with_port();
        let classic_window = classic.current_port;
        let classic_base = classic_bus.read_long(classic_window + 2);
        let classic_row_bytes = (classic_bus.read_word(classic_window + 6) & 0x3FFF) as u32;
        classic.set_screen_mode_for_test(classic_base, classic_row_bytes, 512, 342, 1);
        clear_1bpp_screen(&mut classic_bus, classic_base, classic_row_bytes, 342);
        let (classic_handle, classic_ptr) =
            alloc_button_control(&mut classic, &mut classic_bus, classic_window, bounds);
        classic.control_proc_ids.insert(classic_ptr, 1008);
        classic_cpu.write_reg(Register::A7, sp);
        classic_bus.write_long(sp, classic_handle);
        classic
            .dispatch_control(true, 0x16D, &mut classic_cpu, &mut classic_bus)
            .unwrap()
            .unwrap();

        let (mut themed, mut themed_cpu, mut themed_bus) = setup_with_port();
        themed.set_ui_theme_id(UiThemeId::SystemlessDefault);
        let themed_window = themed.current_port;
        let themed_base = themed_bus.read_long(themed_window + 2);
        let themed_row_bytes = (themed_bus.read_word(themed_window + 6) & 0x3FFF) as u32;
        themed.set_screen_mode_for_test(themed_base, themed_row_bytes, 512, 342, 1);
        clear_1bpp_screen(&mut themed_bus, themed_base, themed_row_bytes, 342);
        let (themed_handle, themed_ptr) =
            alloc_button_control(&mut themed, &mut themed_bus, themed_window, bounds);
        themed.control_proc_ids.insert(themed_ptr, 1008);
        themed_cpu.write_reg(Register::A7, sp);
        themed_bus.write_long(sp, themed_handle);
        themed
            .dispatch_control(true, 0x16D, &mut themed_cpu, &mut themed_bus)
            .unwrap()
            .unwrap();

        assert!(
            screen_pixel_is_set(&classic_bus, classic_base, classic_row_bytes, 100, 37),
            "classic popup CDEF should draw its resolved auto-width offset shadow"
        );
        assert!(
            screen_pixel_is_set(&classic_bus, classic_base, classic_row_bytes, 101, 37),
            "classic popup CDEF should extend the resolved shadow one pixel past the provider frame"
        );
        assert!(
            !screen_pixel_is_set(&themed_bus, themed_base, themed_row_bytes, 101, 37),
            "systemless-default popup provider should not draw the classic resolved shadow extension"
        );

        themed_cpu.write_reg(Register::A7, sp);
        themed_bus.write_word(sp, 25);
        themed_bus.write_word(sp + 2, 25);
        themed_bus.write_long(sp + 4, themed_handle);
        themed_bus.write_word(sp + 8, 0xDEAD);
        themed
            .dispatch_control(true, 0x166, &mut themed_cpu, &mut themed_bus)
            .unwrap()
            .unwrap();
        assert_eq!(themed_bus.read_word(sp + 8), 10);
        assert_eq!(themed_cpu.read_reg(Register::A7), sp + 8);
    }

    #[test]
    fn draw1control_systemless_theme_routes_popup_control_hilite_states_through_provider() {
        let sp = 0x300000u32;
        let (mut themed, mut themed_cpu, mut themed_bus) = setup_with_port();
        themed.set_ui_theme_id(UiThemeId::SystemlessDefault);
        let themed_window = themed.current_port;
        let row_bytes = 64u32;
        let base = themed_bus.alloc(row_bytes * 342);
        themed.set_screen_mode_for_test(base, row_bytes, 512, 342, 1);
        clear_1bpp_screen(&mut themed_bus, base, row_bytes, 342);

        let (normal_handle, normal_ptr) = alloc_button_control(
            &mut themed,
            &mut themed_bus,
            themed_window,
            (20, 20, 40, 120),
        );
        let (pressed_handle, pressed_ptr) = alloc_button_control(
            &mut themed,
            &mut themed_bus,
            themed_window,
            (52, 20, 72, 120),
        );
        let (inactive_handle, inactive_ptr) = alloc_button_control(
            &mut themed,
            &mut themed_bus,
            themed_window,
            (84, 20, 104, 120),
        );
        for ptr in [normal_ptr, pressed_ptr, inactive_ptr] {
            themed.control_proc_ids.insert(ptr, 1008);
        }
        themed_bus.write_byte(pressed_ptr + 17, 1);
        themed_bus.write_byte(inactive_ptr + 17, 255);

        for handle in [normal_handle, pressed_handle, inactive_handle] {
            themed_cpu.write_reg(Register::A7, sp);
            themed_bus.write_long(sp, handle);
            themed
                .dispatch_control(true, 0x16D, &mut themed_cpu, &mut themed_bus)
                .unwrap()
                .unwrap();
        }

        assert!(
            !screen_pixel_is_set(&themed_bus, base, row_bytes, 22, 30),
            "normal systemless-default popup should keep the state inset clear"
        );
        assert!(
            screen_pixel_is_set(&themed_bus, base, row_bytes, 30, 57),
            "pressed systemless-default popup should route hilite state to provider fill"
        );
        let normal_chrome = count_set_pixels(&themed_bus, base, row_bytes, 21, 20, 38, 100);
        let inactive_chrome = count_set_pixels(&themed_bus, base, row_bytes, 85, 20, 102, 100);
        assert!(
            inactive_chrome > normal_chrome,
            "inactive systemless-default popup should route HiliteControl state to provider chrome ({inactive_chrome} <= {normal_chrome})"
        );
    }

    #[test]
    fn draw1control_systemless_theme_routes_push_button_chrome_through_provider() {
        let sp = 0x300000u32;
        let bounds = (20, 20, 40, 80);

        let (mut classic, mut classic_cpu, mut classic_bus) = setup_with_port();
        let classic_window = classic.current_port;
        let classic_base = classic_bus.read_long(classic_window + 2);
        let classic_row_bytes = (classic_bus.read_word(classic_window + 6) & 0x3FFF) as u32;
        classic.set_screen_mode_for_test(classic_base, classic_row_bytes, 512, 342, 1);
        let (classic_handle, _) =
            alloc_button_control(&mut classic, &mut classic_bus, classic_window, bounds);
        classic_cpu.write_reg(Register::A7, sp);
        classic_bus.write_long(sp, classic_handle);
        classic
            .dispatch_control(true, 0x16D, &mut classic_cpu, &mut classic_bus)
            .unwrap()
            .unwrap();

        let (mut themed, mut themed_cpu, mut themed_bus) = setup_with_port();
        themed.set_ui_theme_id(UiThemeId::SystemlessDefault);
        let themed_window = themed.current_port;
        let themed_base = themed_bus.read_long(themed_window + 2);
        let themed_row_bytes = (themed_bus.read_word(themed_window + 6) & 0x3FFF) as u32;
        themed.set_screen_mode_for_test(themed_base, themed_row_bytes, 512, 342, 1);
        let (themed_handle, _) =
            alloc_button_control(&mut themed, &mut themed_bus, themed_window, bounds);
        themed_cpu.write_reg(Register::A7, sp);
        themed_bus.write_long(sp, themed_handle);
        themed
            .dispatch_control(true, 0x16D, &mut themed_cpu, &mut themed_bus)
            .unwrap()
            .unwrap();

        assert!(
            !screen_pixel_is_set(&classic_bus, classic_base, classic_row_bytes, 20, 20),
            "classic round-rect CDEF should leave the outer corner as background"
        );
        assert!(
            screen_pixel_is_set(&themed_bus, themed_base, themed_row_bytes, 20, 20),
            "systemless-default provider chrome should own the HLE control corner pixel"
        );

        themed_cpu.write_reg(Register::A7, sp);
        themed_bus.write_word(sp, 25);
        themed_bus.write_word(sp + 2, 25);
        themed_bus.write_long(sp + 4, themed_handle);
        themed_bus.write_word(sp + 8, 0xDEAD);
        themed
            .dispatch_control(true, 0x166, &mut themed_cpu, &mut themed_bus)
            .unwrap()
            .unwrap();
        assert_eq!(themed_bus.read_word(sp + 8), 10);
        assert_eq!(themed_cpu.read_reg(Register::A7), sp + 8);
    }

    #[test]
    fn draw1control_systemless_theme_routes_button_hilite_states_through_provider() {
        let sp = 0x300000u32;
        let (mut themed, mut cpu, mut bus) = setup_with_port();
        themed.set_ui_theme_id(UiThemeId::SystemlessDefault);
        let window = themed.current_port;
        let row_bytes = 64u32;
        let base = bus.alloc(row_bytes * 342);
        themed.set_screen_mode_for_test(base, row_bytes, 512, 342, 1);
        clear_1bpp_screen(&mut bus, base, row_bytes, 342);

        let (enabled_handle, _enabled_ptr) =
            alloc_button_control(&mut themed, &mut bus, window, (20, 20, 40, 80));
        let (pressed_handle, pressed_ptr) =
            alloc_button_control(&mut themed, &mut bus, window, (60, 20, 80, 80));
        let (inactive_handle, inactive_ptr) =
            alloc_button_control(&mut themed, &mut bus, window, (100, 20, 120, 80));
        bus.write_byte(pressed_ptr + 17, 1);
        bus.write_byte(inactive_ptr + 17, 255);

        for handle in [enabled_handle, pressed_handle, inactive_handle] {
            cpu.write_reg(Register::A7, sp);
            bus.write_long(sp, handle);
            themed
                .dispatch_control(true, 0x16D, &mut cpu, &mut bus)
                .unwrap()
                .unwrap();
            assert_eq!(cpu.read_reg(Register::A7), sp + 4);
        }

        let enabled_body = count_set_pixels(&bus, base, row_bytes, 23, 23, 37, 77);
        let pressed_body = count_set_pixels(&bus, base, row_bytes, 63, 23, 77, 77);
        assert!(
            pressed_body > enabled_body,
            "systemless-default should route contrlHilite=1 into the provider pressed state ({pressed_body} <= {enabled_body})"
        );

        // MTE 1992 glossary, "inactive control": inactive controls are
        // visually indicated and do not respond as active controls.
        let inactive_body = count_set_pixels(&bus, base, row_bytes, 103, 23, 117, 77);
        assert!(
            pressed_body > inactive_body,
            "systemless-default should keep inactive button chrome distinct from pressed chrome"
        );

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 65);
        bus.write_word(sp + 2, 25);
        bus.write_long(sp + 4, pressed_handle);
        bus.write_word(sp + 8, 0xDEAD);
        themed
            .dispatch_control(true, 0x166, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(sp + 8), 10);
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 105);
        bus.write_word(sp + 2, 25);
        bus.write_long(sp + 4, inactive_handle);
        bus.write_word(sp + 8, 0xDEAD);
        themed
            .dispatch_control(true, 0x166, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(sp + 8), 0);
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);
    }

    #[test]
    fn draw1control_systemless_theme_routes_checkbox_and_radio_chrome_through_provider() {
        let sp = 0x300000u32;

        let (mut classic, mut classic_cpu, mut classic_bus) = setup_with_port();
        let classic_window = classic.current_port;
        let classic_base = classic_bus.read_long(classic_window + 2);
        let classic_row_bytes = (classic_bus.read_word(classic_window + 6) & 0x3FFF) as u32;
        classic.set_screen_mode_for_test(classic_base, classic_row_bytes, 512, 342, 1);
        let (classic_checkbox_handle, classic_checkbox_ptr) = alloc_button_control(
            &mut classic,
            &mut classic_bus,
            classic_window,
            (20, 20, 40, 120),
        );
        classic.control_proc_ids.insert(classic_checkbox_ptr, 1);
        classic_bus.write_word(classic_checkbox_ptr + 18, 1);
        let (classic_radio_handle, classic_radio_ptr) = alloc_button_control(
            &mut classic,
            &mut classic_bus,
            classic_window,
            (50, 20, 70, 120),
        );
        classic.control_proc_ids.insert(classic_radio_ptr, 2);
        classic_bus.write_word(classic_radio_ptr + 18, 1);
        for handle in [classic_checkbox_handle, classic_radio_handle] {
            classic_cpu.write_reg(Register::A7, sp);
            classic_bus.write_long(sp, handle);
            classic
                .dispatch_control(true, 0x16D, &mut classic_cpu, &mut classic_bus)
                .unwrap()
                .unwrap();
        }

        let (mut themed, mut themed_cpu, mut themed_bus) = setup_with_port();
        themed.set_ui_theme_id(UiThemeId::SystemlessDefault);
        let themed_window = themed.current_port;
        let themed_base = themed_bus.read_long(themed_window + 2);
        let themed_row_bytes = (themed_bus.read_word(themed_window + 6) & 0x3FFF) as u32;
        themed.set_screen_mode_for_test(themed_base, themed_row_bytes, 512, 342, 1);
        let (themed_checkbox_handle, themed_checkbox_ptr) = alloc_button_control(
            &mut themed,
            &mut themed_bus,
            themed_window,
            (20, 20, 40, 120),
        );
        themed.control_proc_ids.insert(themed_checkbox_ptr, 1);
        themed_bus.write_word(themed_checkbox_ptr + 18, 1);
        let (themed_radio_handle, themed_radio_ptr) = alloc_button_control(
            &mut themed,
            &mut themed_bus,
            themed_window,
            (50, 20, 70, 120),
        );
        themed.control_proc_ids.insert(themed_radio_ptr, 2);
        themed_bus.write_word(themed_radio_ptr + 18, 1);
        for handle in [themed_checkbox_handle, themed_radio_handle] {
            themed_cpu.write_reg(Register::A7, sp);
            themed_bus.write_long(sp, handle);
            themed
                .dispatch_control(true, 0x16D, &mut themed_cpu, &mut themed_bus)
                .unwrap()
                .unwrap();
        }

        let classic_checkbox_pixels = count_set_pixels(
            &classic_bus,
            classic_base,
            classic_row_bytes,
            24,
            22,
            36,
            34,
        );
        let themed_checkbox_pixels =
            count_set_pixels(&themed_bus, themed_base, themed_row_bytes, 24, 22, 36, 34);
        assert!(
            themed_checkbox_pixels > classic_checkbox_pixels,
            "systemless-default checkbox provider should draw a denser selected mark ({themed_checkbox_pixels} <= {classic_checkbox_pixels})"
        );
        let classic_radio_pixels = count_set_pixels(
            &classic_bus,
            classic_base,
            classic_row_bytes,
            54,
            22,
            66,
            34,
        );
        let themed_radio_pixels =
            count_set_pixels(&themed_bus, themed_base, themed_row_bytes, 54, 22, 66, 34);
        assert!(
            themed_radio_pixels > classic_radio_pixels,
            "systemless-default radio provider should draw a denser selected mark ({themed_radio_pixels} <= {classic_radio_pixels})"
        );

        themed_cpu.write_reg(Register::A7, sp);
        themed_bus.write_word(sp, 25);
        themed_bus.write_word(sp + 2, 25);
        themed_bus.write_long(sp + 4, themed_checkbox_handle);
        themed_bus.write_word(sp + 8, 0xDEAD);
        themed
            .dispatch_control(true, 0x166, &mut themed_cpu, &mut themed_bus)
            .unwrap()
            .unwrap();
        assert_eq!(themed_bus.read_word(sp + 8), 11);
        assert_eq!(themed_cpu.read_reg(Register::A7), sp + 8);
    }

    #[test]
    fn draw1control_systemless_theme_routes_checkbox_radio_hilite_states_through_provider() {
        let sp = 0x300000u32;
        let (mut themed, mut cpu, mut bus) = setup_with_port();
        themed.set_ui_theme_id(UiThemeId::SystemlessDefault);
        let window = themed.current_port;
        let row_bytes = 64u32;
        let base = bus.alloc(row_bytes * 342);
        themed.set_screen_mode_for_test(base, row_bytes, 512, 342, 1);
        clear_1bpp_screen(&mut bus, base, row_bytes, 342);

        let (checkbox_enabled_handle, checkbox_enabled_ptr) =
            alloc_button_control(&mut themed, &mut bus, window, (20, 20, 40, 100));
        let (checkbox_pressed_handle, checkbox_pressed_ptr) =
            alloc_button_control(&mut themed, &mut bus, window, (52, 20, 72, 100));
        let (checkbox_inactive_handle, checkbox_inactive_ptr) =
            alloc_button_control(&mut themed, &mut bus, window, (84, 20, 104, 100));
        for ptr in [
            checkbox_enabled_ptr,
            checkbox_pressed_ptr,
            checkbox_inactive_ptr,
        ] {
            themed.control_proc_ids.insert(ptr, 1);
        }
        bus.write_byte(checkbox_pressed_ptr + 17, 1);
        bus.write_byte(checkbox_inactive_ptr + 17, 255);

        let (radio_enabled_handle, radio_enabled_ptr) =
            alloc_button_control(&mut themed, &mut bus, window, (20, 140, 40, 220));
        let (radio_pressed_handle, radio_pressed_ptr) =
            alloc_button_control(&mut themed, &mut bus, window, (52, 140, 72, 220));
        let (radio_inactive_handle, radio_inactive_ptr) =
            alloc_button_control(&mut themed, &mut bus, window, (84, 140, 104, 220));
        for ptr in [radio_enabled_ptr, radio_pressed_ptr, radio_inactive_ptr] {
            themed.control_proc_ids.insert(ptr, 2);
        }
        bus.write_byte(radio_pressed_ptr + 17, 1);
        bus.write_byte(radio_inactive_ptr + 17, 255);

        for handle in [
            checkbox_enabled_handle,
            checkbox_pressed_handle,
            checkbox_inactive_handle,
            radio_enabled_handle,
            radio_pressed_handle,
            radio_inactive_handle,
        ] {
            cpu.write_reg(Register::A7, sp);
            bus.write_long(sp, handle);
            themed
                .dispatch_control(true, 0x16D, &mut cpu, &mut bus)
                .unwrap()
                .unwrap();
            assert_eq!(cpu.read_reg(Register::A7), sp + 4);
        }

        let checkbox_enabled_body = count_set_pixels(&bus, base, row_bytes, 24, 22, 36, 34);
        let checkbox_pressed_body = count_set_pixels(&bus, base, row_bytes, 56, 22, 68, 34);
        let checkbox_inactive_body = count_set_pixels(&bus, base, row_bytes, 88, 22, 100, 34);
        assert!(
            checkbox_pressed_body > checkbox_enabled_body,
            "systemless-default should route checkbox contrlHilite=1 to provider pressed fill ({checkbox_pressed_body} <= {checkbox_enabled_body})"
        );
        assert!(
            checkbox_pressed_body > checkbox_inactive_body,
            "systemless-default should keep inactive checkbox chrome distinct from pressed chrome"
        );

        let radio_enabled_body = count_set_pixels(&bus, base, row_bytes, 24, 142, 36, 154);
        let radio_pressed_body = count_set_pixels(&bus, base, row_bytes, 56, 142, 68, 154);
        let radio_inactive_body = count_set_pixels(&bus, base, row_bytes, 88, 142, 100, 154);
        assert!(
            radio_pressed_body > radio_enabled_body,
            "systemless-default should route radio contrlHilite=1 to provider pressed fill ({radio_pressed_body} <= {radio_enabled_body})"
        );
        assert!(
            radio_pressed_body > radio_inactive_body,
            "systemless-default should keep inactive radio chrome distinct from pressed chrome"
        );

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 57);
        bus.write_word(sp + 2, 145);
        bus.write_long(sp + 4, radio_pressed_handle);
        bus.write_word(sp + 8, 0xDEAD);
        themed
            .dispatch_control(true, 0x166, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_word(sp + 8), 11);
        assert_eq!(cpu.read_reg(Register::A7), sp + 8);
    }

    #[test]
    fn scrollbar_systemless_theme_routes_chrome_through_provider_and_keeps_part_codes() {
        let sp = 0x300000u32;
        let bounds = (20, 20, 180, 36);

        let (mut classic, _classic_cpu, mut classic_bus) = setup_with_port();
        let classic_window = classic.current_port;
        let classic_base = classic_bus.read_long(classic_window + 2);
        let classic_row_bytes = (classic_bus.read_word(classic_window + 6) & 0x3FFF) as u32;
        classic.set_screen_mode_for_test(classic_base, classic_row_bytes, 512, 342, 1);
        clear_1bpp_screen(&mut classic_bus, classic_base, classic_row_bytes, 342);
        let (_classic_handle, classic_ptr) =
            alloc_button_control(&mut classic, &mut classic_bus, classic_window, bounds);
        classic.control_proc_ids.insert(classic_ptr, 16);
        classic_bus.write_word(classic_ptr + 18, 40);
        classic_bus.write_word(classic_ptr + 20, 0);
        classic_bus.write_word(classic_ptr + 22, 100);
        assert!(
            !classic.draw_theme_scrollbar_chrome(
                &mut classic_bus,
                bounds.0,
                bounds.1,
                bounds.2,
                bounds.3,
                40,
                0,
                100,
                0,
            ),
            "classic-system7 keeps the existing scrollBarProc renderer"
        );

        let (mut themed, mut themed_cpu, mut themed_bus) = setup_with_port();
        themed.set_ui_theme_id(UiThemeId::SystemlessDefault);
        let themed_window = themed.current_port;
        let themed_base = themed_bus.read_long(themed_window + 2);
        let themed_row_bytes = (themed_bus.read_word(themed_window + 6) & 0x3FFF) as u32;
        themed.set_screen_mode_for_test(themed_base, themed_row_bytes, 512, 342, 1);
        clear_1bpp_screen(&mut themed_bus, themed_base, themed_row_bytes, 342);
        let (themed_handle, themed_ptr) =
            alloc_button_control(&mut themed, &mut themed_bus, themed_window, bounds);
        themed.control_proc_ids.insert(themed_ptr, 16);
        themed_bus.write_word(themed_ptr + 18, 40);
        themed_bus.write_word(themed_ptr + 20, 0);
        themed_bus.write_word(themed_ptr + 22, 100);
        assert!(
            themed.draw_theme_scrollbar_chrome(
                &mut themed_bus,
                bounds.0,
                bounds.1,
                bounds.2,
                bounds.3,
                40,
                0,
                100,
                0,
            ),
            "systemless-default routes scrollBarProc chrome through the theme provider"
        );

        themed_cpu.write_reg(Register::A7, sp);
        themed_bus.write_word(sp, 85);
        themed_bus.write_word(sp + 2, 28);
        themed_bus.write_long(sp + 4, themed_handle);
        themed_bus.write_word(sp + 8, 0xDEAD);
        themed
            .dispatch_control(true, 0x166, &mut themed_cpu, &mut themed_bus)
            .unwrap()
            .unwrap();
        assert_eq!(themed_bus.read_word(sp + 8), 129);
        assert_eq!(themed_cpu.read_reg(Register::A7), sp + 8);
    }

    #[test]
    fn draw1control_systemless_theme_routes_scrollbar_hilite_states_through_provider() {
        let sp = 0x300000u32;
        let (mut themed, mut cpu, mut bus) = setup_with_port();
        themed.set_ui_theme_id(UiThemeId::SystemlessDefault);
        let row_bytes = 64u32;
        let base = bus.alloc(row_bytes * 342);
        themed.set_screen_mode_for_test(base, row_bytes, 512, 342, 1);
        clear_1bpp_screen(&mut bus, base, row_bytes, 342);

        let (normal_handle, normal_ptr) =
            alloc_scrollbar_control(&mut themed, &mut bus, (20, 20, 100, 36), 255, 0, 40, 0, 100);
        let (arrow_handle, _) = alloc_scrollbar_control(
            &mut themed,
            &mut bus,
            (20, 52, 100, 68),
            255,
            20,
            40,
            0,
            100,
        );
        let (page_handle, _) = alloc_scrollbar_control(
            &mut themed,
            &mut bus,
            (20, 84, 100, 100),
            255,
            22,
            40,
            0,
            100,
        );
        let (inactive_handle, inactive_ptr) = alloc_scrollbar_control(
            &mut themed,
            &mut bus,
            (20, 116, 100, 132),
            255,
            255,
            40,
            0,
            100,
        );

        for handle in [normal_handle, arrow_handle, page_handle, inactive_handle] {
            cpu.write_reg(Register::A7, sp);
            bus.write_long(sp, handle);
            themed
                .dispatch_control(true, 0x16D, &mut cpu, &mut bus)
                .unwrap()
                .unwrap();
            assert_eq!(cpu.read_reg(Register::A7), sp + 4);
        }

        let normal_arrow_fill = count_set_pixels(&bus, base, row_bytes, 21, 21, 35, 35);
        let pressed_arrow_fill = count_set_pixels(&bus, base, row_bytes, 21, 53, 35, 67);
        assert!(
            pressed_arrow_fill > normal_arrow_fill,
            "systemless-default should route scrollbar arrow part hilite through provider fill ({pressed_arrow_fill} <= {normal_arrow_fill})"
        );

        let normal_page_before_fill = count_set_pixels(&bus, base, row_bytes, 37, 22, 47, 34);
        let pressed_page_before_fill = count_set_pixels(&bus, base, row_bytes, 37, 86, 47, 98);
        assert!(
            pressed_page_before_fill > normal_page_before_fill,
            "systemless-default should route scrollbar page-region hilite through provider fill ({pressed_page_before_fill} <= {normal_page_before_fill})"
        );

        assert!(
            screen_pixel_is_set(&bus, base, row_bytes, 28, 56),
            "enabled scrollbar should draw its provider thumb"
        );
        assert!(
            !screen_pixel_is_set(&bus, base, row_bytes, 124, 56),
            "inactive scrollbar should suppress the provider thumb"
        );

        // IM:I I-313 / I-323: hilite values 1..253 name active parts,
        // while 255 makes the control inactive and hit testing returns no part.
        for (handle, pt_v, pt_h, expected) in [
            (arrow_handle, 24i16, 60i16, 20u16),
            (page_handle, 40, 92, 22),
            (normal_handle, 56, 28, 129),
            (inactive_handle, 56, 124, 0),
        ] {
            cpu.write_reg(Register::A7, sp);
            bus.write_word(sp, pt_v as u16);
            bus.write_word(sp + 2, pt_h as u16);
            bus.write_long(sp + 4, handle);
            bus.write_word(sp + 8, 0xDEAD);
            themed
                .dispatch_control(true, 0x166, &mut cpu, &mut bus)
                .unwrap()
                .unwrap();
            assert_eq!(bus.read_word(sp + 8), expected);
            assert_eq!(cpu.read_reg(Register::A7), sp + 8);
        }

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 20);
        bus.write_long(sp + 2, normal_handle);
        themed
            .dispatch_control(true, 0x15D, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_byte(normal_ptr + 17), 20);
        assert_eq!(cpu.read_reg(Register::A7), sp + 6);
        assert!(
            count_set_pixels(&bus, base, row_bytes, 21, 21, 35, 35) > normal_arrow_fill,
            "HiliteControl should redraw scroll-bar part hilites through the provider"
        );

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 255);
        bus.write_long(sp + 2, normal_handle);
        themed
            .dispatch_control(true, 0x15D, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(bus.read_byte(normal_ptr + 17), 255);
        assert_eq!(cpu.read_reg(Register::A7), sp + 6);
        assert!(
            !screen_pixel_is_set(&bus, base, row_bytes, 28, 56),
            "HiliteControl(255) should redraw the inactive provider state"
        );
        assert_eq!(bus.read_byte(inactive_ptr + 17), 255);
    }

    #[test]
    fn draw1control_out_of_range_handle_is_noop_and_pops_arg() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, bus.ram_size() + 4);

        disp.dispatch_control(true, 0x16D, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
    }

    #[test]
    fn draw1control_handle_pointing_at_out_of_range_control_ptr_is_noop_and_pops_arg() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let handle = bus.alloc(4);
        assert_ne!(handle, 0);
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, handle);
        bus.write_long(handle, bus.ram_size() + 0x1000);

        disp.dispatch_control(true, 0x16D, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
    }

    #[test]
    fn draw1control_handle_pointing_to_truncated_control_record_is_noop_and_pops_arg() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let handle = bus.alloc(4);
        let ctrl_ptr = bus.ram_size().saturating_sub(41);
        assert_ne!(handle, 0);
        assert!(ctrl_ptr > 0);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, handle);
        bus.write_long(handle, ctrl_ptr);
        bus.write_byte(ctrl_ptr + 40, 16);

        disp.dispatch_control(true, 0x16D, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
    }

    #[test]
    fn dragcontrol_pops_18_bytes_and_leaves_contrlrect_unchanged_on_no_drag_path() {
        let (mut disp, mut cpu, mut bus) = setup_with_port();
        let sp = 0x300000u32;
        let window_ptr = disp.current_port;
        let (ctrl_handle, ctrl_ptr) = alloc_control_handle(&mut bus, (88, 96, 132, 220), 0, 0);
        let limit_rect_ptr = bus.alloc(8);
        let slop_rect_ptr = bus.alloc(8);
        let top_before = bus.read_word(ctrl_ptr + 8);
        let left_before = bus.read_word(ctrl_ptr + 10);
        let bottom_before = bus.read_word(ctrl_ptr + 12);
        let right_before = bus.read_word(ctrl_ptr + 14);

        bus.write_long(ctrl_ptr + 4, window_ptr);
        bus.write_long(window_ptr + 140, ctrl_handle);

        bus.write_word(limit_rect_ptr, 0);
        bus.write_word(limit_rect_ptr + 2, 0);
        bus.write_word(limit_rect_ptr + 4, 400);
        bus.write_word(limit_rect_ptr + 6, 640);
        bus.write_word(slop_rect_ptr, (-40i16) as u16);
        bus.write_word(slop_rect_ptr + 2, (-40i16) as u16);
        bus.write_word(slop_rect_ptr + 4, (-20i16) as u16);
        bus.write_word(slop_rect_ptr + 6, (-20i16) as u16);

        cpu.write_reg(Register::A7, sp);
        bus.write_word(sp, 0); // axis
        bus.write_long(sp + 2, slop_rect_ptr);
        bus.write_long(sp + 6, limit_rect_ptr);
        bus.write_word(sp + 10, 12); // startPt.v
        bus.write_word(sp + 12, 18); // startPt.h
        bus.write_long(sp + 14, ctrl_handle);

        disp.dispatch_control(true, 0x167, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 18);
        assert_eq!(bus.read_word(ctrl_ptr + 8), top_before);
        assert_eq!(bus.read_word(ctrl_ptr + 10), left_before);
        assert_eq!(bus.read_word(ctrl_ptr + 12), bottom_before);
        assert_eq!(bus.read_word(ctrl_ptr + 14), right_before);
    }

    fn alloc_button_control(
        disp: &mut super::super::TrapDispatcher,
        bus: &mut MacMemoryBus,
        window_ptr: u32,
        bounds: (i16, i16, i16, i16),
    ) -> (u32, u32) {
        let ctrl_ptr = bus.alloc(48);
        let ctrl_handle = bus.alloc(4);
        bus.write_long(ctrl_handle, ctrl_ptr);
        bus.write_long(ctrl_ptr, 0);
        bus.write_long(ctrl_ptr + 4, window_ptr);
        bus.write_word(ctrl_ptr + 8, bounds.0 as u16);
        bus.write_word(ctrl_ptr + 10, bounds.1 as u16);
        bus.write_word(ctrl_ptr + 12, bounds.2 as u16);
        bus.write_word(ctrl_ptr + 14, bounds.3 as u16);
        bus.write_byte(ctrl_ptr + 16, 255);
        bus.write_byte(ctrl_ptr + 17, 0);
        bus.write_word(ctrl_ptr + 18, 0);
        bus.write_word(ctrl_ptr + 20, 0);
        bus.write_word(ctrl_ptr + 22, 1);
        bus.write_long(ctrl_ptr + 24, 0);
        bus.write_long(ctrl_ptr + 28, 0);
        bus.write_long(ctrl_ptr + 32, 0);
        bus.write_long(ctrl_ptr + 36, 0);
        bus.write_byte(ctrl_ptr + 40, 0);
        disp.control_proc_ids.insert(ctrl_ptr, 0);
        (ctrl_handle, ctrl_ptr)
    }

    fn screen_pixel_is_set(bus: &MacMemoryBus, base: u32, row_bytes: u32, x: i16, y: i16) -> bool {
        let byte = bus.read_byte(base + (y as u32 * row_bytes) + ((x as u32) / 8));
        byte & (0x80u8 >> ((x as u8) & 7)) != 0
    }

    fn count_set_pixels(
        bus: &MacMemoryBus,
        base: u32,
        row_bytes: u32,
        top: i16,
        left: i16,
        bottom: i16,
        right: i16,
    ) -> u32 {
        let mut count = 0;
        for y in top..bottom {
            for x in left..right {
                if screen_pixel_is_set(bus, base, row_bytes, x, y) {
                    count += 1;
                }
            }
        }
        count
    }

    fn count_pixel_index(
        bus: &MacMemoryBus,
        base: u32,
        row_bytes: u32,
        top: i16,
        left: i16,
        bottom: i16,
        right: i16,
        pixel_index: u8,
    ) -> u32 {
        let mut count = 0;
        for y in top..bottom {
            for x in left..right {
                if bus.read_byte(base + y as u32 * row_bytes + x as u32) == pixel_index {
                    count += 1;
                }
            }
        }
        count
    }

    fn clear_1bpp_screen(bus: &mut MacMemoryBus, base: u32, row_bytes: u32, height: u32) {
        for y in 0..height {
            for x in 0..row_bytes {
                bus.write_byte(base + y * row_bytes + x, 0);
            }
        }
    }

    #[test]
    fn updtcontrol_repaints_intersecting_controls_and_empty_regions() {
        let (mut disp, mut cpu, mut bus) = setup_with_port();
        let window_ptr = 0x181000u32;
        let screen_base = bus.read_long(window_ptr + 2);
        let row_bytes = (bus.read_word(window_ptr + 6) & 0x3FFF) as u32;

        let (left_handle, left_ptr) =
            alloc_button_control(&mut disp, &mut bus, window_ptr, (20, 20, 60, 120));
        let (right_handle, right_ptr) =
            alloc_button_control(&mut disp, &mut bus, window_ptr, (20, 150, 60, 250));

        bus.write_long(window_ptr + 140, right_handle);
        bus.write_long(right_ptr, left_handle);
        bus.write_long(left_ptr, 0);
        bus.write_long(left_ptr + 4, window_ptr);
        bus.write_long(right_ptr + 4, window_ptr);

        let sp = 0x300000u32;
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, window_ptr);
        disp.dispatch_control(true, 0x169, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        let left_probe = (70, 40);
        let right_probe = (200, 40);
        assert!(!screen_pixel_is_set(
            &bus,
            screen_base,
            row_bytes,
            left_probe.0,
            left_probe.1
        ));
        assert!(!screen_pixel_is_set(
            &bus,
            screen_base,
            row_bytes,
            right_probe.0,
            right_probe.1
        ));

        bus.write_byte(left_ptr + 17, 1);
        let narrow_rgn = bus.alloc(10);
        bus.write_word(narrow_rgn, 10);
        bus.write_word(narrow_rgn + 2, 20);
        bus.write_word(narrow_rgn + 4, 20);
        bus.write_word(narrow_rgn + 6, 60);
        bus.write_word(narrow_rgn + 8, 120);
        let narrow_handle = bus.alloc(4);
        bus.write_long(narrow_handle, narrow_rgn);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, narrow_handle);
        bus.write_long(sp + 4, window_ptr);
        let sp_before = cpu.read_reg(Register::A7);
        disp.dispatch_control(true, 0x153, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(cpu.read_reg(Register::A7), sp_before + 8);
        assert!(
            screen_pixel_is_set(&bus, screen_base, row_bytes, left_probe.0, left_probe.1),
            "left control should redraw when its rect intersects the update region"
        );
        assert!(
            !screen_pixel_is_set(&bus, screen_base, row_bytes, right_probe.0, right_probe.1),
            "right control should remain unchanged when it does not intersect the update region"
        );

        bus.write_byte(right_ptr + 17, 1);
        let empty_rgn = bus.alloc(10);
        bus.write_word(empty_rgn, 10);
        bus.write_word(empty_rgn + 2, 0);
        bus.write_word(empty_rgn + 4, 0);
        bus.write_word(empty_rgn + 6, 0);
        bus.write_word(empty_rgn + 8, 0);
        let empty_handle = bus.alloc(4);
        bus.write_long(empty_handle, empty_rgn);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, empty_handle);
        bus.write_long(sp + 4, window_ptr);
        let sp_before = cpu.read_reg(Register::A7);
        disp.dispatch_control(true, 0x153, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();
        assert_eq!(cpu.read_reg(Register::A7), sp_before + 8);
        assert!(
            screen_pixel_is_set(&bus, screen_base, row_bytes, left_probe.0, left_probe.1),
            "empty update regions should leave previously repainted controls unchanged"
        );
        assert!(
            !screen_pixel_is_set(&bus, screen_base, row_bytes, right_probe.0, right_probe.1),
            "empty update regions should not repaint controls outside the update region"
        );
    }

    #[test]
    fn updtcontrol_out_of_range_window_pointer_is_noop_and_pops_args() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0);
        bus.write_long(sp + 4, bus.ram_size() + 0x1000);

        let sp_before = cpu.read_reg(Register::A7);
        disp.dispatch_control(true, 0x153, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(
            cpu.read_reg(Register::A7),
            sp_before + 8,
            "UpdtControl should still consume its Pascal frame"
        );
    }

    // GetCVariant per Inside Macintosh Volume V (1986), p. V-222: returns the
    // variation code packed in the low 4 bits of the control's procID (Inside
    // Macintosh Volume I 1985, p. I-323: control definition ID = 16 *
    // resourceID + variation_code).
    fn install_control_for_variant_test(
        disp: &mut crate::trap::TrapDispatcher,
        bus: &mut MacMemoryBus,
        proc_id: i16,
    ) -> u32 {
        let ctrl_ptr = bus.alloc(296);
        let ctrl_handle = bus.alloc(4);
        bus.write_long(ctrl_handle, ctrl_ptr);
        disp.control_proc_ids.insert(ctrl_ptr, proc_id);
        ctrl_handle
    }

    #[test]
    fn getcvariant_returns_variation_code_from_low_four_bits_of_proc_id() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;

        // pushButProc = 0 → variant 0
        let h_button = install_control_for_variant_test(&mut disp, &mut bus, 0);
        // checkBoxProc = 1 → variant 1
        let h_check = install_control_for_variant_test(&mut disp, &mut bus, 1);
        // radioButProc = 2 → variant 2
        let h_radio = install_control_for_variant_test(&mut disp, &mut bus, 2);
        // scrollBarProc = 16 → variant 0 (CDEF resource 1, variant 0)
        let h_scroll = install_control_for_variant_test(&mut disp, &mut bus, 16);
        // popupMenuProc + popupFixedWidth = 1008 + 1 = 1009 → variant 1
        let h_popup_fixed = install_control_for_variant_test(&mut disp, &mut bus, 1009);

        for (handle, expected) in [
            (h_button, 0i16),
            (h_check, 1),
            (h_radio, 2),
            (h_scroll, 0),
            (h_popup_fixed, 1),
        ] {
            cpu.write_reg(Register::A7, sp);
            bus.write_long(sp, handle);
            bus.write_word(sp + 4, 0xDEAD);
            disp.dispatch_control(true, 0x009, &mut cpu, &mut bus)
                .unwrap()
                .unwrap();
            assert_eq!(cpu.read_reg(Register::A7), sp + 4);
            assert_eq!(
                bus.read_word(sp + 4) as i16,
                expected,
                "GetCVariant must return low 4 bits of procID; got wrong value"
            );
        }
    }

    #[test]
    fn getcvariant_returns_zero_for_nil_control_handle() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, 0);
        bus.write_word(sp + 4, 0xBEEF);

        disp.dispatch_control(true, 0x009, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
        assert_eq!(
            bus.read_word(sp + 4) as i16,
            0,
            "NIL theControl must return 0 (no variant) without crashing"
        );
    }

    #[test]
    fn getcvariant_function_protocol_pops_handle_and_writes_integer_result() {
        let (mut disp, mut cpu, mut bus) = setup();
        let sp = 0x300000u32;
        let handle = install_control_for_variant_test(&mut disp, &mut bus, 2);

        cpu.write_reg(Register::A7, sp);
        bus.write_long(sp, handle);
        bus.write_word(sp + 4, 0xCAFE);
        bus.write_word(sp + 6, 0xBABE);

        disp.dispatch_control(true, 0x009, &mut cpu, &mut bus)
            .unwrap()
            .unwrap();

        // A7 advances exactly 4 bytes (handle popped); INTEGER result at SP+4.
        assert_eq!(cpu.read_reg(Register::A7), sp + 4);
        assert_eq!(bus.read_word(sp + 4) as i16, 2);
        // Sentinel just past the 2-byte result slot survives.
        assert_eq!(
            bus.read_word(sp + 6),
            0xBABE,
            "trap must not write past the 2-byte INTEGER result slot"
        );
    }
}