systemless 0.68.0

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
//! Architecture-neutral Dialog Manager records, DITL parsing, and geometry.
//!
//! Inside Macintosh Volume I (1985), pp. I-399--I-434, and
//! Inside Macintosh: Macintosh Toolbox Essentials (1992), pp. 6-1--6-179.
use std::borrow::Cow;

use crate::trap::types::decode_mac_roman;

/// Canonical guest DialogRecord byte size.
pub const DIALOG_RECORD_SIZE: u32 = 256;

/// Canonical DialogRecord guest field offsets.
pub const DIALOG_WINDOW_KIND_OFFSET: u32 = 108;
pub const DIALOG_GO_AWAY_FLAG_OFFSET: u32 = 112;
pub const DIALOG_ITEMS_OFFSET: u32 = 156;
pub const DIALOG_TEXT_HANDLE_OFFSET: u32 = 160;
pub const DIALOG_EDIT_FIELD_OFFSET: u32 = 164;
pub const DIALOG_EDIT_OPEN_OFFSET: u32 = 166;
pub const DIALOG_DEFAULT_ITEM_OFFSET: u32 = 168;
pub const DIALOG_RESOURCE_ID_OFFSET: u32 = 170;

/// Canonical initial value for `editField` in a newly created DialogRecord (-1 = no edit field active).
/// Inside Macintosh Volume I, p. I-411.
pub const DIALOG_INITIAL_EDIT_FIELD: i16 = -1;

/// Canonical initial value for `editOpen` in a newly created DialogRecord (0 = closed).
/// Inside Macintosh Volume I, p. I-411.
pub const DIALOG_INITIAL_EDIT_OPEN: i16 = 0;

/// Canonical initial value for `aDefItem` in a newly created DialogRecord (1 = item 1 is default button).
/// Inside Macintosh Volume I, p. I-411.
pub const DIALOG_INITIAL_DEFAULT_ITEM: i16 = 1;

/// Host-private Dialog Manager state offsets following the documented DialogRecord.
pub const DIALOG_CANCEL_ITEM_OFFSET: u32 = 172;
pub const DIALOG_ALERT_HIT_OFFSET: u32 = 174;
pub const DIALOG_STANDARD_ALERT_OUTPUT_OFFSET: u32 = 176;
pub const DIALOG_STANDARD_ALERT_STACK_OFFSET: u32 = 180;

/// Canonical Dialog window kind. Inside Macintosh Volume I, p. I-273.
pub const DIALOG_WINDOW_KIND: u16 = 2;

/// Canonical DialogDispatch ($AA68) routine selectors.
/// Macintosh Toolbox Essentials (1992), pp. 6-162--6-167.
#[allow(dead_code)]
pub const DIALOG_DISPATCH_NEW_COLOR_DIALOG: u16 = 0x0000;
pub const DIALOG_DISPATCH_GET_STD_FILTER_PROC: u16 = 0x0003;
pub const DIALOG_DISPATCH_SET_DIALOG_DEFAULT_ITEM: u16 = 0x0004;
pub const DIALOG_DISPATCH_SET_DIALOG_CANCEL_ITEM: u16 = 0x0005;
pub const DIALOG_DISPATCH_SET_DIALOG_TRACKS_CURSOR: u16 = 0x0006;
pub const DIALOG_DISPATCH_NEW_FEATURES_DIALOG: u16 = 0x000C;

/// Standard default button outline thickness in pixels.
/// Macintosh Toolbox Essentials (1992), Listing 6-17.
pub const DEFAULT_BUTTON_OUTLINE_THICKNESS: i16 = 3;

/// Standard default button outline outset padding in pixels.
/// Macintosh Toolbox Essentials (1992), Listing 6-17.
pub const DEFAULT_BUTTON_OUTLINE_INSET: i16 = 4;

/// Standard margin around dialog content for a modal dialog box (`dBoxProc`).
/// Inside Macintosh Volume I, p. I-273.
pub const DIALOG_DBOX_FRAME_MARGIN: i16 = 8;

/// Standard outset around an active edit-text field for focus/border frame rendering.
/// Inside Macintosh Volume I, p. I-414; Macintosh Human Interface Guidelines (1992), p. 184.
pub const EDIT_TEXT_FRAME_OUTSET: i16 = 3;

/// Standard flush-left text glyph inset from destination rectangle leading edge.
/// Inside Macintosh Volume I, pp. I-373--I-374.
pub const DIALOG_TEXT_LEFT_INSET: i16 = 1;

/// Canonical AppendDITL placement methods.
/// Macintosh Toolbox Essentials (1992), pp. 6-108, 6-153.
pub const APPEND_DITL_OVERLAY: i16 = 0;
pub const APPEND_DITL_RIGHT: i16 = 1;
pub const APPEND_DITL_BOTTOM: i16 = 2;

/// Item disable bit in the DITL item type byte.
pub const DIALOG_ITEM_DISABLED_FLAG: u8 = 0x80;

/// Canonical Dialog item type codes. Inside Macintosh Volume I, p. I-427.
pub const DIALOG_ITEM_USER_ITEM: u8 = 0;
pub const DIALOG_ITEM_BUTTON: u8 = 4;
pub const DIALOG_ITEM_CHECKBOX: u8 = 5;
pub const DIALOG_ITEM_RADIO: u8 = 6;
pub const DIALOG_ITEM_RESOURCE_CONTROL: u8 = 7;
pub const DIALOG_ITEM_STATIC_TEXT: u8 = 8;
pub const DIALOG_ITEM_EDIT_TEXT: u8 = 16;
pub const DIALOG_ITEM_ICON: u8 = 32;
pub const DIALOG_ITEM_PICTURE: u8 = 64;

/// Canonical Alert types. Inside Macintosh Volume I, p. I-417, and Appearance.h.
pub const ALERT_TYPE_STOP: u16 = 0;
pub const ALERT_TYPE_NOTE: u16 = 1;
pub const ALERT_TYPE_CAUTION: u16 = 2;
#[allow(dead_code)]
pub const ALERT_TYPE_PLAIN: u16 = 3;

/// Canonical Standard Alert button IDs. Inside Macintosh: Macintosh Toolbox Essentials (1992), p. 6-110.
#[allow(dead_code)]
pub const ALERT_BUTTON_OK: i16 = 1;
#[allow(dead_code)]
pub const ALERT_BUTTON_CANCEL: i16 = 2;
#[allow(dead_code)]
pub const ALERT_BUTTON_OTHER: i16 = 3;
#[allow(dead_code)]
pub const ALERT_BUTTON_HELP: i16 = 4;

/// Strongly typed Dialog Manager item kind.
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DialogItemKind {
    UserItem,
    Button,
    Checkbox,
    RadioButton,
    ResourceControl,
    StaticText,
    EditText,
    Icon,
    Picture,
    Unknown(u8),
}

#[allow(dead_code)]
impl DialogItemKind {
    /// Decode the base item kind, masking out the disabled flag bit (0x80).
    pub const fn from_raw_type(raw: u8) -> Self {
        match raw & 0x7F {
            DIALOG_ITEM_USER_ITEM => Self::UserItem,
            DIALOG_ITEM_BUTTON => Self::Button,
            DIALOG_ITEM_CHECKBOX => Self::Checkbox,
            DIALOG_ITEM_RADIO => Self::RadioButton,
            DIALOG_ITEM_RESOURCE_CONTROL => Self::ResourceControl,
            DIALOG_ITEM_STATIC_TEXT => Self::StaticText,
            DIALOG_ITEM_EDIT_TEXT => Self::EditText,
            DIALOG_ITEM_ICON => Self::Icon,
            DIALOG_ITEM_PICTURE => Self::Picture,
            other => Self::Unknown(other),
        }
    }

    /// Return the raw integer code for this item kind.
    pub const fn raw_base_type(self) -> u8 {
        match self {
            Self::UserItem => DIALOG_ITEM_USER_ITEM,
            Self::Button => DIALOG_ITEM_BUTTON,
            Self::Checkbox => DIALOG_ITEM_CHECKBOX,
            Self::RadioButton => DIALOG_ITEM_RADIO,
            Self::ResourceControl => DIALOG_ITEM_RESOURCE_CONTROL,
            Self::StaticText => DIALOG_ITEM_STATIC_TEXT,
            Self::EditText => DIALOG_ITEM_EDIT_TEXT,
            Self::Icon => DIALOG_ITEM_ICON,
            Self::Picture => DIALOG_ITEM_PICTURE,
            Self::Unknown(raw) => raw,
        }
    }

    /// Whether this item represents a clickable button or standard control.
    pub const fn is_control(self) -> bool {
        matches!(
            self,
            Self::Button | Self::Checkbox | Self::RadioButton | Self::ResourceControl
        )
    }

    /// Whether this item represents an application user item (`userItem`, 0).
    pub const fn is_user_item(self) -> bool {
        matches!(self, Self::UserItem)
    }

    /// Whether this item represents a standard pushbutton (`ctrlItem + btnCtrl`, 4).
    pub const fn is_button(self) -> bool {
        matches!(self, Self::Button)
    }

    /// Whether this item represents a checkbox control (`ctrlItem + chkCtrl`, 5).
    pub const fn is_checkbox(self) -> bool {
        matches!(self, Self::Checkbox)
    }

    /// Whether this item represents a radio button control (`ctrlItem + radCtrl`, 6).
    pub const fn is_radio(self) -> bool {
        matches!(self, Self::RadioButton)
    }

    /// Whether this item represents a resource-defined control (`ctrlItem + resCtrl`, 7).
    pub const fn is_resource_control(self) -> bool {
        matches!(self, Self::ResourceControl)
    }

    /// Whether this item represents non-editable static text (`statText`, 8).
    pub const fn is_static_text(self) -> bool {
        matches!(self, Self::StaticText)
    }

    /// Whether this item represents editable text (`editText`, 16).
    pub const fn is_edit_text(self) -> bool {
        matches!(self, Self::EditText)
    }

    /// Whether this item represents a standard icon (`iconItem`, 32).
    pub const fn is_icon(self) -> bool {
        matches!(self, Self::Icon)
    }

    /// Whether this item represents a QuickDraw picture (`picItem`, 64).
    pub const fn is_picture(self) -> bool {
        matches!(self, Self::Picture)
    }

    /// Whether this item contains text payload (static or editable).
    pub const fn is_text(self) -> bool {
        matches!(self, Self::StaticText | Self::EditText)
    }

    /// Whether this item represents static or editable text, or a control with a title string.
    pub const fn has_text_or_title(self) -> bool {
        matches!(
            self,
            Self::StaticText
                | Self::EditText
                | Self::Button
                | Self::Checkbox
                | Self::RadioButton
        )
    }

    /// Whether this item references an external resource (resource control, icon, or picture).
    pub const fn is_resource(self) -> bool {
        matches!(self, Self::ResourceControl | Self::Icon | Self::Picture)
    }

    /// The 4-byte Mac OS resource type associated with this dialog item kind (`b"CNTL"`, `b"ICON"`, or `b"PICT"`).
    pub const fn resource_type(self) -> Option<[u8; 4]> {
        match self {
            Self::ResourceControl => Some(*b"CNTL"),
            Self::Icon => Some(*b"ICON"),
            Self::Picture => Some(*b"PICT"),
            _ => None,
        }
    }

    /// The 4-byte Mac OS resource type associated with this dialog item kind as a big-endian `u32`.
    pub const fn resource_type_u32(self) -> Option<u32> {
        match self.resource_type() {
            Some(bytes) => Some(u32::from_be_bytes(bytes)),
            None => None,
        }
    }
}

/// Parsed Dialog Item List (DITL) entry.
///
/// Inside Macintosh: Macintosh Toolbox Essentials (1992), pp. 6-120--6-121.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DialogItemRecord {
    /// Byte offset of the item entry within the source DITL data.
    pub item_offset: usize,
    /// Raw item type byte (including `DIALOG_ITEM_DISABLED_FLAG`).
    pub item_type: u8,
    /// Display rectangle in dialog-local coordinates (top, left, bottom, right).
    pub rect: (i16, i16, i16, i16),
    /// Handle or procedure pointer from the item header (0 in resource data).
    pub handle: u32,
    /// Raw item payload bytes (Pascal string, resource ID, or application data).
    pub payload: Vec<u8>,
}

#[allow(dead_code)]
impl DialogItemRecord {
    /// Whether the item is enabled for user interaction.
    pub fn is_enabled(&self) -> bool {
        is_dialog_item_enabled(self.item_type)
    }

    /// Whether the item is disabled for user interaction.
    pub fn is_disabled(&self) -> bool {
        is_dialog_item_disabled(self.item_type)
    }

    /// Strongly typed item kind.
    pub fn kind(&self) -> DialogItemKind {
        DialogItemKind::from_raw_type(self.item_type)
    }

    /// Whether the item represents a button, checkbox, or radio control.
    pub fn is_control(&self) -> bool {
        is_dialog_item_control(self.item_type)
    }

    /// Whether the item represents an application user item (`userItem`, 0).
    pub fn is_user_item(&self) -> bool {
        is_dialog_item_user_item(self.item_type)
    }

    /// Whether the item represents a standard pushbutton (`ctrlItem + btnCtrl`, 4).
    pub fn is_button(&self) -> bool {
        is_dialog_item_button(self.item_type)
    }

    /// Whether the item represents a checkbox control (`ctrlItem + chkCtrl`, 5).
    pub fn is_checkbox(&self) -> bool {
        is_dialog_item_checkbox(self.item_type)
    }

    /// Whether the item represents a radio button control (`ctrlItem + radCtrl`, 6).
    pub fn is_radio(&self) -> bool {
        is_dialog_item_radio(self.item_type)
    }

    /// Whether the item represents a resource-defined control (`ctrlItem + resCtrl`, 7).
    pub fn is_resource_control(&self) -> bool {
        is_dialog_item_resource_control(self.item_type)
    }

    /// Whether the item represents non-editable static text (`statText`, 8).
    pub fn is_static_text(&self) -> bool {
        is_dialog_item_static_text(self.item_type)
    }

    /// Whether the item represents editable text (`editText`, 16).
    pub fn is_edit_text(&self) -> bool {
        is_dialog_item_edit_text(self.item_type)
    }

    /// Whether the item represents a standard icon (`iconItem`, 32).
    pub fn is_icon(&self) -> bool {
        is_dialog_item_icon(self.item_type)
    }

    /// Whether the item represents a QuickDraw picture (`picItem`, 64).
    pub fn is_picture(&self) -> bool {
        is_dialog_item_picture(self.item_type)
    }

    /// Whether the item represents static or editable text.
    pub fn is_text(&self) -> bool {
        is_dialog_item_text(self.item_type)
    }

    /// Whether the item represents text or a control with a title string.
    pub fn has_text_or_title(&self) -> bool {
        is_dialog_item_text_or_title(self.item_type)
    }

    /// Returns the raw payload bytes if the item represents text or a title string.
    pub fn text_payload(&self) -> Option<&[u8]> {
        if self.has_text_or_title() {
            Some(&self.payload)
        } else {
            None
        }
    }

    /// Decoded Mac Roman text if the payload represents a text or title string; otherwise empty.
    pub fn text(&self) -> String {
        self.text_payload()
            .map(decode_mac_roman)
            .unwrap_or_default()
    }

    /// Whether the item references an external resource (resource control, icon, or picture).
    pub fn is_resource(&self) -> bool {
        is_dialog_item_resource(self.item_type)
    }

    /// 4-byte Mac OS resource type if the item references a resource (`b"CNTL"`, `b"ICON"`, or `b"PICT"`).
    pub fn resource_type(&self) -> Option<[u8; 4]> {
        dialog_item_resource_type(self.item_type)
    }

    /// 4-byte Mac OS resource type as `u32` if the item references a resource.
    pub fn resource_type_u32(&self) -> Option<u32> {
        dialog_item_resource_type_u32(self.item_type)
    }

    /// 16-bit resource ID if the item references a resource (CNTL, ICON, PICT).
    pub fn resource_id(&self) -> Option<i16> {
        if self.is_resource() && self.payload.len() >= 2 {
            Some(i16::from_be_bytes([self.payload[0], self.payload[1]]))
        } else {
            None
        }
    }

    /// Whether the item rectangle is moved off-screen via `HideDialogItem`.
    pub fn is_hidden(&self) -> bool {
        is_dialog_item_rect_hidden(self.rect)
    }

    /// Offset the item display rectangle by `(v_delta, h_delta)`.
    pub fn offset_rect(&mut self, v_delta: i16, h_delta: i16) {
        self.rect = offset_rect(self.rect, v_delta, h_delta);
    }

    /// Calculate the enclosing rectangle for invalidation and redrawing.
    pub fn enclosing_rect(&self) -> (i16, i16, i16, i16) {
        dialog_item_enclosing_rect(self.item_type, self.rect)
    }
}

#[inline]
fn read_be_i16(bytes: &[u8], offset: usize) -> Option<i16> {
    let slice = bytes.get(offset..offset.checked_add(2)?)?;
    Some(i16::from_be_bytes([slice[0], slice[1]]))
}

#[inline]
fn read_be_u32(bytes: &[u8], offset: usize) -> Option<u32> {
    let slice = bytes.get(offset..offset.checked_add(4)?)?;
    Some(u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]))
}

/// Calculate the payload length for a DITL item.
///
/// Inside Macintosh Volume I, pp. I-404--I-405, I-427;
/// Macintosh Toolbox Essentials (1992), p. 6-153.
pub fn ditl_item_payload_len(base_type: u8, data_len_byte: u8, remaining: usize) -> Option<usize> {
    if is_dialog_item_resource(base_type) {
        // icon (32), picture (64), resCtrl (7): 2-byte resource ID.
        // IM:I I-427 describes the byte after itmtype as length=2; MTE 1992
        // p. 6-153 documents the same compiled records as a reserved byte plus
        // the two-byte resource ID. Accept both conventions.
        if remaining < 2 {
            return None;
        }
        if data_len_byte >= 2 {
            Some(usize::from(data_len_byte))
        } else {
            Some(2)
        }
    } else {
        Some(usize::from(data_len_byte))
    }
}

/// Calculate the total byte length of a compiled DITL item record at `record_offset`,
/// including its 14-byte header and padded payload.
pub fn ditl_item_record_len_at(bytes: &[u8], record_offset: usize) -> Option<usize> {
    if record_offset.checked_add(14)? > bytes.len() {
        return None;
    }
    let item_type = *bytes.get(record_offset.checked_add(12)?)?;
    let data_len_byte = *bytes.get(record_offset.checked_add(13)?)?;
    let base_type = dialog_item_base_type(item_type);
    let payload_offset = record_offset.checked_add(14)?;
    let remaining = bytes.len().saturating_sub(payload_offset);
    let payload_len = ditl_item_payload_len(base_type, data_len_byte, remaining)?;
    let padded = (payload_len + 1) & !1;
    if padded > remaining {
        return None;
    }
    Some(14 + padded)
}

/// Calculate the total used bytes of compiled DITL data up to the last item.
pub fn ditl_total_used_len(bytes: &[u8]) -> usize {
    if bytes.len() < 2 {
        return bytes.len();
    }
    let Some(count_minus_one) = read_be_i16(bytes, 0) else {
        return bytes.len();
    };
    let count = if count_minus_one < 0 {
        0
    } else {
        match usize::try_from(count_minus_one)
            .ok()
            .and_then(|c| c.checked_add(1))
        {
            Some(c) => c,
            None => return bytes.len(),
        }
    };
    let mut offset = 2usize;
    for _ in 0..count {
        let Some(record_len) = ditl_item_record_len_at(bytes, offset) else {
            break;
        };
        offset = offset.saturating_add(record_len);
    }
    offset
}

/// Parse raw DITL resource bytes into a list of parsed dialog item records.
///
/// Macintosh Toolbox Essentials (1992), pp. 6-120--6-121.
pub fn parse_ditl_items(bytes: &[u8]) -> Option<Vec<DialogItemRecord>> {
    let count_minus_one = read_be_i16(bytes, 0)?;
    let count = if count_minus_one < 0 {
        0
    } else {
        match usize::try_from(count_minus_one)
            .ok()
            .and_then(|c| c.checked_add(1))
        {
            Some(c) => c,
            None => return None,
        }
    };

    let mut offset = 2usize;
    let mut items = Vec::with_capacity(count);

    for _ in 0..count {
        if offset + 14 > bytes.len() {
            break;
        }
        let Some(handle) = read_be_u32(bytes, offset) else {
            break;
        };
        let Some(top) = read_be_i16(bytes, offset + 4) else {
            break;
        };
        let Some(left) = read_be_i16(bytes, offset + 6) else {
            break;
        };
        let Some(bottom) = read_be_i16(bytes, offset + 8) else {
            break;
        };
        let Some(right) = read_be_i16(bytes, offset + 10) else {
            break;
        };
        let item_type = bytes[offset + 12];
        let data_len_byte = bytes[offset + 13];
        let base_type = dialog_item_base_type(item_type);
        let payload_start = offset + 14;
        let remaining = bytes.len().saturating_sub(payload_start);
        let Some(payload_len) = ditl_item_payload_len(base_type, data_len_byte, remaining) else {
            break;
        };
        let padded = (payload_len + 1) & !1;
        if padded > remaining {
            break;
        }
        let payload = bytes[payload_start..payload_start + payload_len].to_vec();

        items.push(DialogItemRecord {
            item_offset: offset,
            item_type,
            rect: (top, left, bottom, right),
            handle,
            payload,
        });

        offset = payload_start + padded;
    }

    Some(items)
}

/// Adjust dialog window bounds according to System 7 AutoPositioning flags.
pub fn position_dialog_bounds(
    bounds: (i16, i16, i16, i16),
    position: u16,
    screen_width: i32,
    screen_height: i32,
) -> (i16, i16, i16, i16) {
    let centered = matches!(
        position,
        0x280a | 0x300a | 0x380a | 0xa80a | 0xb00a | 0xb80a
    );
    if !centered {
        return bounds;
    }

    let height = i32::from(bounds.2) - i32::from(bounds.0);
    let width = i32::from(bounds.3) - i32::from(bounds.1);
    let top = (screen_height - height).max(0) / 2;
    let left = (screen_width - width).max(0) / 2;

    (
        top.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
        left.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
        (top + height).clamp(i16::MIN as i32, i16::MAX as i32) as i16,
        (left + width).clamp(i16::MIN as i32, i16::MAX as i32) as i16,
    )
}

/// Standard coordinate offset applied to move a dialog item off-screen when hidden.
///
/// Inside Macintosh Volume IV, p. IV-59;
/// Macintosh Toolbox Essentials (1992), pp. 6-123--6-124.
pub const DIALOG_ITEM_HIDDEN_OFFSET: i16 = 16384;

/// Horizontal threshold coordinate distinguishing on-screen dialog items from hidden ones.
///
/// Macintosh Toolbox Essentials (1992), pp. 6-123--6-124.
pub const DIALOG_ITEM_HIDDEN_THRESHOLD: i16 = 8192;

/// Offset a rectangle by `(v_delta, h_delta)` using saturating arithmetic.
pub fn offset_rect(rect: (i16, i16, i16, i16), v_delta: i16, h_delta: i16) -> (i16, i16, i16, i16) {
    (
        rect.0.saturating_add(v_delta),
        rect.1.saturating_add(h_delta),
        rect.2.saturating_add(v_delta),
        rect.3.saturating_add(h_delta),
    )
}

/// Convert a dialog-local rectangle into global/screen coordinates based on dialog bounds.
pub fn dialog_rect_to_global(
    bounds: (i16, i16, i16, i16),
    rect: (i16, i16, i16, i16),
) -> (i16, i16, i16, i16) {
    (
        bounds.0.saturating_add(rect.0),
        bounds.1.saturating_add(rect.1),
        bounds.0.saturating_add(rect.2),
        bounds.1.saturating_add(rect.3),
    )
}

/// Convert a global/screen rectangle into dialog-local coordinates based on dialog bounds.
#[allow(dead_code)]
pub fn dialog_rect_to_local(
    bounds: (i16, i16, i16, i16),
    rect: (i16, i16, i16, i16),
) -> (i16, i16, i16, i16) {
    (
        rect.0.saturating_sub(bounds.0),
        rect.1.saturating_sub(bounds.1),
        rect.2.saturating_sub(bounds.0),
        rect.3.saturating_sub(bounds.1),
    )
}

/// Convert a global/screen point into dialog-local coordinates based on dialog bounds.
#[inline]
pub const fn global_to_dialog_local_point(
    bounds: (i16, i16, i16, i16),
    screen_v: i16,
    screen_h: i16,
) -> (i16, i16) {
    (
        screen_v.saturating_sub(bounds.0),
        screen_h.saturating_sub(bounds.1),
    )
}

/// Convert a dialog-local point into global/screen coordinates based on dialog bounds.
#[allow(dead_code)]
#[inline]
pub const fn dialog_local_to_global_point(
    bounds: (i16, i16, i16, i16),
    local_v: i16,
    local_h: i16,
) -> (i16, i16) {
    (
        bounds.0.saturating_add(local_v),
        bounds.1.saturating_add(local_h),
    )
}

/// Whether a rectangle contains a point `(v, h)` (with half-open interval `top <= v < bottom` and `left <= h < right`).
pub fn rect_contains_point(rect: (i16, i16, i16, i16), v: i16, h: i16) -> bool {
    v >= rect.0 && v < rect.2 && h >= rect.1 && h < rect.3
}

/// Inset a rectangle by `(v_delta, h_delta)` using saturating arithmetic.
#[allow(dead_code)]
pub fn inset_rect(rect: (i16, i16, i16, i16), v_delta: i16, h_delta: i16) -> (i16, i16, i16, i16) {
    (
        rect.0.saturating_add(v_delta),
        rect.1.saturating_add(h_delta),
        rect.2.saturating_sub(v_delta),
        rect.3.saturating_sub(h_delta),
    )
}

/// Outset a rectangle by `(v_delta, h_delta)` using saturating arithmetic.
pub fn outset_rect(rect: (i16, i16, i16, i16), v_delta: i16, h_delta: i16) -> (i16, i16, i16, i16) {
    (
        rect.0.saturating_sub(v_delta),
        rect.1.saturating_sub(h_delta),
        rect.2.saturating_add(v_delta),
        rect.3.saturating_add(h_delta),
    )
}

/// Calculate the outer boundary rectangle for a modal dialog box (`dBoxProc`)
/// structure frame including its standard 8-pixel margin.
///
/// Inside Macintosh Volume I, p. I-273.
pub fn dialog_dbox_frame_rect(content_bounds: (i16, i16, i16, i16)) -> (i16, i16, i16, i16) {
    outset_rect(
        content_bounds,
        DIALOG_DBOX_FRAME_MARGIN,
        DIALOG_DBOX_FRAME_MARGIN,
    )
}

/// Calculate the outer border frame rectangle for an edit-text dialog item.
///
/// Inside Macintosh Volume I, p. I-414;
/// Macintosh Human Interface Guidelines (1992), p. 184.
pub fn edit_text_frame_rect(item_rect: (i16, i16, i16, i16)) -> (i16, i16, i16, i16) {
    outset_rect(item_rect, EDIT_TEXT_FRAME_OUTSET, EDIT_TEXT_FRAME_OUTSET)
}

/// Calculate the text rendering rectangle for a static or editable text dialog item,
/// applying the standard 1-pixel flush-left glyph inset.
///
/// Inside Macintosh Volume I, pp. I-373--I-374.
pub fn dialog_text_rect(item_rect: (i16, i16, i16, i16)) -> (i16, i16, i16, i16) {
    (
        item_rect.0,
        item_rect.1.saturating_add(DIALOG_TEXT_LEFT_INSET),
        item_rect.2,
        item_rect.3,
    )
}

/// Extract the base dialog item type code, stripping the disabled bit flag (`0x80`).
pub const fn dialog_item_base_type(raw_type: u8) -> u8 {
    raw_type & !DIALOG_ITEM_DISABLED_FLAG
}

/// Returns whether the dialog item has the disabled bit flag (`0x80`) set.
///
/// Inside Macintosh Volume I, p. I-427;
/// Macintosh Toolbox Essentials (1992), p. 6-152.
#[inline]
pub const fn is_dialog_item_disabled(raw_type: u8) -> bool {
    (raw_type & DIALOG_ITEM_DISABLED_FLAG) != 0
}

/// Returns whether the dialog item is enabled (disabled bit flag `0x80` not set).
///
/// Inside Macintosh Volume I, p. I-427;
/// Macintosh Toolbox Essentials (1992), p. 6-152.
#[inline]
pub const fn is_dialog_item_enabled(raw_type: u8) -> bool {
    (raw_type & DIALOG_ITEM_DISABLED_FLAG) == 0
}

/// Resolve the target dialog pointer for a Toolbox event.
///
/// Inside Macintosh Volume I, pp. I-416--I-417:
/// Update and activate events name their target window in `message`; if that
/// window is a dialog box, the event routes to it (and if not, no dialog is targeted).
/// All other events are routed to the frontmost active dialog.
pub fn dialog_target_for_event<F>(
    what: u16,
    message: u32,
    is_dialog: F,
    front_dialog: Option<u32>,
) -> Option<u32>
where
    F: FnOnce(u32) -> bool,
{
    match what {
        EVENT_UPDATE | EVENT_ACTIVATE => {
            if is_dialog(message) {
                Some(message)
            } else {
                None
            }
        }
        _ => front_dialog,
    }
}

/// Determine whether a dialog item rectangle is hidden off-screen.
///
/// Macintosh Toolbox Essentials (1992), pp. 6-123--6-124.
pub fn is_dialog_item_rect_hidden(rect: (i16, i16, i16, i16)) -> bool {
    rect.1 > DIALOG_ITEM_HIDDEN_THRESHOLD
}

/// Calculate the hidden offscreen rectangle for a dialog item (+16384 on left and right).
pub fn hide_dialog_item_rect(rect: (i16, i16, i16, i16)) -> (i16, i16, i16, i16) {
    (
        rect.0,
        rect.1.wrapping_add(DIALOG_ITEM_HIDDEN_OFFSET),
        rect.2,
        rect.3.wrapping_add(DIALOG_ITEM_HIDDEN_OFFSET),
    )
}

/// Calculate the restored onscreen rectangle for a hidden dialog item (-16384 on left and right).
pub fn show_dialog_item_rect(rect: (i16, i16, i16, i16)) -> (i16, i16, i16, i16) {
    (
        rect.0,
        rect.1.wrapping_sub(DIALOG_ITEM_HIDDEN_OFFSET),
        rect.2,
        rect.3.wrapping_sub(DIALOG_ITEM_HIDDEN_OFFSET),
    )
}

/// Calculate the enclosing rectangle for a dialog item for erasure and invalidation.
///
/// Inside Macintosh Volume IV, p. IV-59 notes that Dialog Manager drawing can extend
/// outside an editText item's display rectangle by 3 pixels.
pub fn dialog_item_enclosing_rect(
    item_type: u8,
    rect: (i16, i16, i16, i16),
) -> (i16, i16, i16, i16) {
    if is_dialog_item_edit_text(item_type) {
        (
            rect.0.saturating_sub(3),
            rect.1.saturating_sub(3),
            rect.2.saturating_add(3),
            rect.3.saturating_add(3),
        )
    } else {
        rect
    }
}

/// Find the 0-based index of the first item whose rectangle contains the dialog-local point.
///
/// Inside Macintosh Volume IV, p. IV-60;
/// Macintosh Toolbox Essentials (1992), p. 6-125.
pub fn find_dialog_item_at_local_point<'a>(
    rects: impl IntoIterator<Item = &'a (i16, i16, i16, i16)>,
    pt_v: i16,
    pt_h: i16,
) -> Option<usize> {
    for (idx, &rect) in rects.into_iter().enumerate() {
        if rect_contains_point(rect, pt_v, pt_h) {
            return Some(idx);
        }
    }
    None
}

/// Hit-tests a dialog-local point against dialog items, returning the 0-based index of the first matching item.
///
/// If `enabled_only` is true, disabled items (`is_dialog_item_disabled`) are skipped.
/// For each item whose bounding rectangle contains `(local_v, local_h)`, `control_part_hit` is called
/// if the item is a control (`is_dialog_item_control`). If `control_part_hit` returns `false`, the item
/// is skipped (allowing clicks on inactive controls or transparent group box bodies to fall through).
///
/// Inside Macintosh Volume I, pp. I-416--I-418;
/// Macintosh Toolbox Essentials (1992), pp. 6-125, 6-138--6-139.
pub fn find_dialog_item_hit<I, F>(
    items: I,
    local_v: i16,
    local_h: i16,
    enabled_only: bool,
    mut control_part_hit: F,
) -> Option<usize>
where
    I: IntoIterator<Item = ((i16, i16, i16, i16), u8)>,
    F: FnMut(usize) -> bool,
{
    for (idx, (rect, raw_type)) in items.into_iter().enumerate() {
        if enabled_only && is_dialog_item_disabled(raw_type) {
            continue;
        }
        if !rect_contains_point(rect, local_v, local_h) {
            continue;
        }
        if is_dialog_item_control(raw_type) && !control_part_hit(idx) {
            continue;
        }
        return Some(idx);
    }
    None
}

/// Hit-tests a global screen point against dialog items given the dialog window bounds.
#[allow(dead_code)]
pub fn find_dialog_item_at_global_point<I, F>(
    bounds: (i16, i16, i16, i16),
    screen_v: i16,
    screen_h: i16,
    items: I,
    enabled_only: bool,
    control_part_hit: F,
) -> Option<usize>
where
    I: IntoIterator<Item = ((i16, i16, i16, i16), u8)>,
    F: FnMut(usize) -> bool,
{
    let (local_v, local_h) = global_to_dialog_local_point(bounds, screen_v, screen_h);
    find_dialog_item_hit(items, local_v, local_h, enabled_only, control_part_hit)
}

/// Offset the bounding rectangles of compiled DITL items directly within the raw binary buffer.
pub fn offset_ditl_bytes(
    bytes: &mut [u8],
    item_offsets: impl IntoIterator<Item = usize>,
    dv: i16,
    dh: i16,
) {
    if dv == 0 && dh == 0 {
        return;
    }
    for item_offset in item_offsets {
        for (coordinate_offset, delta) in [(4usize, dv), (6, dh), (8, dv), (10, dh)] {
            let Some(start) = item_offset.checked_add(coordinate_offset) else {
                continue;
            };
            let Some(pair) = bytes.get(start..start.saturating_add(2)) else {
                continue;
            };
            let value = i16::from_be_bytes([pair[0], pair[1]]).saturating_add(delta);
            if let Some(destination) = bytes.get_mut(start..start.saturating_add(2)) {
                destination.copy_from_slice(&value.to_be_bytes());
            }
        }
    }
}

/// Parsed representation of a Macintosh dialog template (`DLOG` resource).
///
/// Inside Macintosh Volume I, pp. I-437--I-438;
/// Macintosh Toolbox Essentials (1992), pp. 6-113--6-114, 6-148.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DialogTemplate {
    pub bounds: (i16, i16, i16, i16),
    pub proc_id: i16,
    pub visible: bool,
    pub go_away: bool,
    pub ref_con: u32,
    pub items_id: i16,
    pub title: Vec<u8>,
    pub position: u16,
}

impl DialogTemplate {
    /// Decode the Pascal title bytes as a Mac Roman string.
    pub fn title_string(&self) -> String {
        decode_mac_roman(&self.title)
    }
}

/// Parse a dialog template (`DLOG` resource) from compiled binary bytes.
///
/// Inside Macintosh Volume I, pp. I-437--I-438;
/// Macintosh Toolbox Essentials (1992), pp. 6-113--6-114, 6-148.
pub fn parse_dialog_template(bytes: &[u8]) -> Option<DialogTemplate> {
    if bytes.len() < 20 {
        return None;
    }
    let bounds = (
        i16::from_be_bytes(bytes.get(0..2)?.try_into().ok()?),
        i16::from_be_bytes(bytes.get(2..4)?.try_into().ok()?),
        i16::from_be_bytes(bytes.get(4..6)?.try_into().ok()?),
        i16::from_be_bytes(bytes.get(6..8)?.try_into().ok()?),
    );
    let proc_id = i16::from_be_bytes(bytes.get(8..10)?.try_into().ok()?);
    let visible = *bytes.get(10)? != 0;
    let go_away = bytes.get(12).copied().unwrap_or(0) != 0;
    let ref_con = bytes
        .get(14..18)
        .and_then(|slice| slice.try_into().ok())
        .map(u32::from_be_bytes)
        .unwrap_or(0);
    let items_id = i16::from_be_bytes(bytes.get(18..20)?.try_into().ok()?);
    let title_len = usize::from(bytes.get(20).copied().unwrap_or(0));
    let title_start = 21.min(bytes.len());
    let title_end = 21usize.saturating_add(title_len).min(bytes.len());
    let title = bytes.get(title_start..title_end).unwrap_or(&[]).to_vec();
    let nominal_title_end = 21usize.saturating_add(title_len);
    let position_offset = (nominal_title_end + 1) & !1;
    let position = bytes
        .get(position_offset..position_offset.saturating_add(2))
        .and_then(|value| value.try_into().ok())
        .map(u16::from_be_bytes)
        .unwrap_or(0);

    Some(DialogTemplate {
        bounds,
        proc_id,
        visible,
        go_away,
        ref_con,
        items_id,
        title,
        position,
    })
}

/// Parsed representation of a Macintosh alert template (`ALRT` resource).
///
/// Inside Macintosh Volume I, pp. I-425--I-426;
/// Macintosh Toolbox Essentials (1992), p. 6-150.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AlertTemplate {
    pub bounds: (i16, i16, i16, i16),
    pub items_id: i16,
    pub stages: u16,
    pub position: u16,
}

/// Parse an alert template (`ALRT` resource) from compiled binary bytes.
///
/// Inside Macintosh Volume I, pp. I-425--I-426;
/// Macintosh Toolbox Essentials (1992), p. 6-150.
pub fn parse_alert_template(bytes: &[u8]) -> Option<AlertTemplate> {
    if bytes.len() < 8 {
        return None;
    }
    let bounds = (
        i16::from_be_bytes(bytes.get(0..2)?.try_into().ok()?),
        i16::from_be_bytes(bytes.get(2..4)?.try_into().ok()?),
        i16::from_be_bytes(bytes.get(4..6)?.try_into().ok()?),
        i16::from_be_bytes(bytes.get(6..8)?.try_into().ok()?),
    );
    let items_id = bytes
        .get(8..10)
        .and_then(|slice| slice.try_into().ok())
        .map(i16::from_be_bytes)
        .unwrap_or(0);
    let stages = bytes
        .get(10..12)
        .and_then(|slice| slice.try_into().ok())
        .map(u16::from_be_bytes)
        .unwrap_or(0);
    let position = bytes
        .get(12..14)
        .and_then(|slice| slice.try_into().ok())
        .map(u16::from_be_bytes)
        .unwrap_or(0);

    Some(AlertTemplate {
        bounds,
        items_id,
        stages,
        position,
    })
}

/// Information about an alert stage extracted from an `ALRT` resource's stage word.
///
/// Inside Macintosh Volume I, pp. I-422--I-424;
/// Macintosh Toolbox Essentials (1992), pp. 6-106, 6-150.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AlertStageInfo {
    /// Zero-based stage index (0..=3), clamped from guest stage counter.
    pub stage_index: u16,
    /// The 4-bit nibble for this stage.
    pub stage_nibble: u8,
    /// Whether the alert window is drawn (bit 2 / 0x04 of the nibble).
    pub box_drawn: bool,
    /// The default button item index: 1 (OK) if bit 3 is 0, or 2 (Cancel) if bit 3 is 1.
    pub default_item: i16,
    /// Sound number (0..=3) from bits 0..=1.
    pub sound_number: u8,
}

/// Decode alert stage parameters for the specified stage counter (0..=3).
pub fn alert_stage_info(stages: u16, stage_counter: u16) -> AlertStageInfo {
    let stage_index = stage_counter.min(3);
    let stage_nibble = ((stages >> (stage_index * 4)) & 0x0F) as u8;
    let box_drawn = (stage_nibble & 0x04) != 0;
    let default_item = if (stage_nibble & 0x08) == 0 { 1 } else { 2 };
    let sound_number = stage_nibble & 0x03;
    AlertStageInfo {
        stage_index,
        stage_nibble,
        box_drawn,
        default_item,
        sound_number,
    }
}

/// Replace `^0`..`^3` placeholders in dialog text bytes with the corresponding ParamText slot contents.
///
/// Returns `Cow::Borrowed` when no `^` character is present, avoiding allocations.
/// Inside Macintosh Volume I, p. I-422;
/// Macintosh Toolbox Essentials (1992), pp. 6-129--6-130.
pub fn apply_param_text<'a>(text: &'a [u8], slots: &[impl AsRef<[u8]>]) -> Cow<'a, [u8]> {
    if !text.contains(&b'^') {
        return Cow::Borrowed(text);
    }
    let mut expanded = Vec::with_capacity(text.len());
    let mut offset = 0;
    while offset < text.len() {
        if text[offset] == b'^' {
            if let Some(index) = text
                .get(offset + 1)
                .copied()
                .filter(u8::is_ascii_digit)
                .map(|b| usize::from(b - b'0'))
                .filter(|&idx| idx < slots.len())
            {
                expanded.extend_from_slice(slots[index].as_ref());
                offset += 2;
                continue;
            }
        }
        expanded.push(text[offset]);
        offset += 1;
    }
    Cow::Owned(expanded)
}

/// String-oriented wrapper for `apply_param_text` operating on Mac Roman text strings.
pub fn apply_param_text_str<'a, S: AsRef<[u8]>>(text: &'a str, slots: &[S]) -> Cow<'a, str> {
    if !text.contains('^') {
        return Cow::Borrowed(text);
    }
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == '^' {
            if let Some(&next) = chars.peek() {
                if let Some(digit) = next.to_digit(10) {
                    let idx = digit as usize;
                    if idx < slots.len() {
                        chars.next();
                        out.push_str(&decode_mac_roman(slots[idx].as_ref()));
                        continue;
                    }
                }
            }
        }
        out.push(ch);
    }
    Cow::Owned(out)
}

/// Canonical Macintosh key codes for modal dialog navigation.
pub const KEY_RETURN: u8 = 0x24;
pub const KEY_NUMPAD_ENTER: u8 = 0x4C;
pub const KEY_ESCAPE: u8 = 0x35;
pub const KEY_TAB: u8 = 0x30;
pub const KEY_PERIOD: u8 = 0x2F;

/// Canonical Macintosh ASCII character codes for modal dialog navigation.
pub const CHAR_RETURN: u8 = 0x0D;
pub const CHAR_ENTER: u8 = 0x03;
pub const CHAR_ESCAPE: u8 = 0x1B;
pub const CHAR_TAB: u8 = 0x09;
pub const CHAR_PERIOD: u8 = b'.';

/// Event modifier bit for Command key (`cmdKey`).
pub const MODIFIER_CMD_KEY: u16 = 0x0100;

/// Event `what` codes for Toolbox events.
///
/// Inside Macintosh Volume I (1985), pp. I-249--I-250;
/// Macintosh Toolbox Essentials (1992), pp. 2-83--2-84.
pub const EVENT_NULL: u16 = 0;
pub const EVENT_MOUSE_DOWN: u16 = 1;
#[allow(dead_code)]
pub const EVENT_MOUSE_UP: u16 = 2;
pub const EVENT_KEY_DOWN: u16 = 3;
#[allow(dead_code)]
pub const EVENT_KEY_UP: u16 = 4;
pub const EVENT_AUTO_KEY: u16 = 5;
pub const EVENT_UPDATE: u16 = 6;
#[allow(dead_code)]
pub const EVENT_DISK: u16 = 7;
pub const EVENT_ACTIVATE: u16 = 8;

/// Decision produced by standard modal dialog keyboard filtering.
///
/// Inside Macintosh Volume I (1985), pp. I-415--I-416;
/// Macintosh Toolbox Essentials (1992), pp. 6-86--6-90, 6-138.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DialogFilterDecision {
    /// Return or Enter key activated: triggers the dialog's default button.
    TriggerDefaultButton,
    /// Escape or Command-Period key activated: triggers the dialog's cancel button.
    TriggerCancelButton,
    /// Tab key activated: advances focus to the next `editText` item.
    AdvanceEditTextFocus,
    /// Key event not handled by standard dialog filter.
    Unhandled,
}

/// Determine whether the specified character and key code correspond to the default button activation key (Return or Enter).
pub const fn is_dialog_default_key(char_code: u8, key_code: u8) -> bool {
    matches!(char_code, CHAR_RETURN | CHAR_ENTER)
        || matches!(key_code, KEY_RETURN | KEY_NUMPAD_ENTER)
}

/// Determine whether the specified character, key code, and modifier word correspond to the cancel button activation key (Escape or Command-Period).
pub const fn is_dialog_cancel_key(char_code: u8, key_code: u8, modifiers: u16) -> bool {
    char_code == CHAR_ESCAPE
        || key_code == KEY_ESCAPE
        || ((modifiers & MODIFIER_CMD_KEY) != 0
            && (char_code == CHAR_PERIOD || key_code == KEY_PERIOD))
}

/// Determine whether the specified character and key code correspond to the Tab key.
pub const fn is_dialog_tab_key(char_code: u8, key_code: u8) -> bool {
    char_code == CHAR_TAB || key_code == KEY_TAB
}

/// Evaluate a keyboard event for standard modal dialog filtering.
///
/// Inside Macintosh Volume I, pp. I-415--I-416;
/// Macintosh Toolbox Essentials (1992), pp. 6-86--6-90, 6-138.
pub fn evaluate_modal_dialog_key(
    event_what: u16,
    message: u32,
    modifiers: u16,
) -> DialogFilterDecision {
    if !matches!(event_what, EVENT_KEY_DOWN | EVENT_AUTO_KEY) {
        return DialogFilterDecision::Unhandled;
    }
    let char_code = (message & 0xFF) as u8;
    let key_code = ((message >> 8) & 0xFF) as u8;

    if is_dialog_default_key(char_code, key_code) {
        DialogFilterDecision::TriggerDefaultButton
    } else if is_dialog_cancel_key(char_code, key_code, modifiers) {
        DialogFilterDecision::TriggerCancelButton
    } else if is_dialog_tab_key(char_code, key_code) {
        DialogFilterDecision::AdvanceEditTextFocus
    } else {
        DialogFilterDecision::Unhandled
    }
}

/// Find the next `editText` item in item-list order, wrapping cyclically.
///
/// Takes an iterator of item types (raw `u8`) and the current 1-indexed
/// edit item number (0 if no edit item is active). Returns the 1-indexed item
/// number of the next `editText` item, or `None` if the dialog has no `editText` items.
///
/// Inside Macintosh Volume I, p. I-416;
/// Macintosh Toolbox Essentials (1992), p. 6-88.
pub fn find_next_edit_text_item(
    item_types: impl IntoIterator<Item = u8>,
    current_edit_item_1_indexed: usize,
) -> Option<usize> {
    let types: Vec<u8> = item_types.into_iter().collect();
    if types.is_empty() {
        return None;
    }
    let start = current_edit_item_1_indexed;
    for offset in 0..types.len() {
        let idx = (start + offset) % types.len();
        let base_type = dialog_item_base_type(types[idx]);
        if base_type == DIALOG_ITEM_EDIT_TEXT {
            return Some(idx + 1);
        }
    }
    None
}

/// Helper to find the next `editText` item directly from a slice of `DialogItemRecord`s.
#[allow(dead_code)]
pub fn find_next_edit_text_in_items(
    items: &[DialogItemRecord],
    current_edit_item_1_indexed: usize,
) -> Option<usize> {
    find_next_edit_text_item(
        items.iter().map(|item| item.item_type),
        current_edit_item_1_indexed,
    )
}

/// Clamps a text length to 255 bytes (Pascal string maximum payload).
#[allow(dead_code)]
pub fn clamp_dialog_item_text_len(len: usize) -> u8 {
    len.min(255) as u8
}

/// Clamps a byte slice to at most 255 bytes (Pascal string maximum payload).
pub fn clamp_dialog_item_text_bytes(text_bytes: &[u8]) -> &[u8] {
    let len = text_bytes.len().min(255);
    &text_bytes[..len]
}

/// Clamps a UTF-8 string so its byte length does not exceed 255 bytes,
/// ensuring character boundary safety.
#[allow(dead_code)]
pub fn clamp_dialog_item_text_str(text: &str) -> &str {
    if text.len() <= 255 {
        return text;
    }
    let mut boundary = 255;
    while boundary > 0 && !text.is_char_boundary(boundary) {
        boundary -= 1;
    }
    &text[..boundary]
}

/// Encodes raw text bytes into Pascal string format: `(length_byte, clamped_payload)`.
pub fn encode_dialog_item_pstring(text_bytes: &[u8]) -> (u8, &[u8]) {
    let clamped = clamp_dialog_item_text_bytes(text_bytes);
    (clamped.len() as u8, clamped)
}

/// Formats text bytes into a Pascal string byte vector with length prefix: `[len, byte0, byte1, ...]`.
#[allow(dead_code)]
pub fn format_dialog_item_pstring(text_bytes: &[u8]) -> Vec<u8> {
    let clamped = clamp_dialog_item_text_bytes(text_bytes);
    let mut result = Vec::with_capacity(1 + clamped.len());
    result.push(clamped.len() as u8);
    result.extend_from_slice(clamped);
    result
}

/// Decodes a Pascal string slice (where the first byte is length) into payload bytes.
#[allow(dead_code)]
pub fn decode_dialog_item_pstring(bytes: &[u8]) -> Option<&[u8]> {
    let &len = bytes.first()?;
    let end = 1 + len as usize;
    if bytes.len() >= end {
        Some(&bytes[1..end])
    } else {
        None
    }
}

/// Decodes a Pascal string slice (where the first byte is length) into a Mac Roman string.
#[allow(dead_code)]
pub fn decode_dialog_item_pstring_to_string(bytes: &[u8]) -> Option<String> {
    decode_dialog_item_pstring(bytes).map(decode_mac_roman)
}

/// Prepares input text bytes for `SetDialogItemText`, clamping to at most 255 bytes
/// and returning both the clamped byte slice and the decoded Mac Roman string.
#[allow(dead_code)]
pub fn prepare_set_dialog_item_text(text_bytes: &[u8]) -> (&[u8], String) {
    let clamped = clamp_dialog_item_text_bytes(text_bytes);
    let decoded = decode_mac_roman(clamped);
    (clamped, decoded)
}

/// Encodes raw text bytes into Pascal string format for `GetDialogItemText`: `(length_byte, clamped_payload)`.
#[allow(dead_code)]
pub fn prepare_get_dialog_item_text(text_bytes: &[u8]) -> (u8, &[u8]) {
    encode_dialog_item_pstring(text_bytes)
}

/// Resolves the active dialog item text bytes from an optional handle buffer and fallback DITL payload.
///
/// If `handle_bytes` is provided, it takes precedence. Otherwise, falls back to `fallback_payload`
/// if the item type represents text or a titled control. Returns an empty slice for other item types.
pub fn extract_dialog_item_text_bytes<'a>(
    base_type: u8,
    handle_bytes: Option<&'a [u8]>,
    fallback_payload: &'a [u8],
) -> &'a [u8] {
    if let Some(bytes) = handle_bytes {
        bytes
    } else if is_dialog_item_text_or_title(base_type) {
        fallback_payload
    } else {
        &[]
    }
}

/// Resolves the active dialog item text string from an optional handle buffer and fallback DITL payload.
#[allow(dead_code)]
pub fn extract_dialog_item_text_string(
    base_type: u8,
    handle_bytes: Option<&[u8]>,
    fallback_payload: &[u8],
) -> String {
    decode_mac_roman(extract_dialog_item_text_bytes(
        base_type,
        handle_bytes,
        fallback_payload,
    ))
}

/// Retrieves a reference to an item from a 1-indexed slice (returns `None` if `item_number == 0` or out of bounds).
pub fn get_item_at_1_indexed<T>(items: &[T], item_number_1_indexed: usize) -> Option<&T> {
    item_number_1_indexed
        .checked_sub(1)
        .and_then(|idx| items.get(idx))
}

/// Retrieves a mutable reference to an item from a 1-indexed slice (returns `None` if `item_number == 0` or out of bounds).
#[allow(dead_code)]
pub fn get_item_at_1_indexed_mut<T>(
    items: &mut [T],
    item_number_1_indexed: usize,
) -> Option<&mut T> {
    item_number_1_indexed
        .checked_sub(1)
        .and_then(|idx| items.get_mut(idx))
}

/// Returns true if the raw item type represents a button, checkbox, radio button, or resource control.
pub const fn is_dialog_item_control(raw_type: u8) -> bool {
    DialogItemKind::from_raw_type(raw_type).is_control()
}

/// Returns true if the raw item type represents an application user item (`userItem`, 0).
pub const fn is_dialog_item_user_item(raw_type: u8) -> bool {
    DialogItemKind::from_raw_type(raw_type).is_user_item()
}

/// Returns true if the raw item type represents a standard pushbutton (`ctrlItem + btnCtrl`, 4).
pub const fn is_dialog_item_button(raw_type: u8) -> bool {
    DialogItemKind::from_raw_type(raw_type).is_button()
}

/// Returns true if the raw item type represents a checkbox control (`ctrlItem + chkCtrl`, 5).
pub const fn is_dialog_item_checkbox(raw_type: u8) -> bool {
    DialogItemKind::from_raw_type(raw_type).is_checkbox()
}

/// Returns true if the raw item type represents a radio button control (`ctrlItem + radCtrl`, 6).
pub const fn is_dialog_item_radio(raw_type: u8) -> bool {
    DialogItemKind::from_raw_type(raw_type).is_radio()
}

/// Returns true if the raw item type represents a resource-defined control (`ctrlItem + resCtrl`, 7).
pub const fn is_dialog_item_resource_control(raw_type: u8) -> bool {
    DialogItemKind::from_raw_type(raw_type).is_resource_control()
}

/// Returns true if the raw item type represents non-editable static text (`statText`, 8).
pub const fn is_dialog_item_static_text(raw_type: u8) -> bool {
    DialogItemKind::from_raw_type(raw_type).is_static_text()
}

/// Returns true if the raw item type represents editable text (`editText`, 16).
pub const fn is_dialog_item_edit_text(raw_type: u8) -> bool {
    DialogItemKind::from_raw_type(raw_type).is_edit_text()
}

/// Returns true if the raw item type represents a standard icon (`iconItem`, 32).
pub const fn is_dialog_item_icon(raw_type: u8) -> bool {
    DialogItemKind::from_raw_type(raw_type).is_icon()
}

/// Returns true if the raw item type represents a QuickDraw picture (`picItem`, 64).
pub const fn is_dialog_item_picture(raw_type: u8) -> bool {
    DialogItemKind::from_raw_type(raw_type).is_picture()
}

/// Returns true if the raw item type represents static text or edit text.
pub const fn is_dialog_item_text(raw_type: u8) -> bool {
    DialogItemKind::from_raw_type(raw_type).is_text()
}

/// Returns true if the raw item type represents static text, edit text, or a titled control.
pub const fn is_dialog_item_text_or_title(raw_type: u8) -> bool {
    DialogItemKind::from_raw_type(raw_type).has_text_or_title()
}

/// Returns true if the raw item type references an external resource (resource control, icon, or picture).
pub const fn is_dialog_item_resource(raw_type: u8) -> bool {
    DialogItemKind::from_raw_type(raw_type).is_resource()
}

/// Returns the 4-byte Mac OS resource type associated with a dialog item (`b"CNTL"`, `b"ICON"`, or `b"PICT"`).
pub const fn dialog_item_resource_type(raw_type: u8) -> Option<[u8; 4]> {
    DialogItemKind::from_raw_type(raw_type).resource_type()
}

/// Returns the 4-byte Mac OS resource type associated with a dialog item as a big-endian `u32`.
pub const fn dialog_item_resource_type_u32(raw_type: u8) -> Option<u32> {
    DialogItemKind::from_raw_type(raw_type).resource_type_u32()
}

/// Standard Macintosh Dialog icon size (32x32 pixels, `ICON` / `cicn`).
pub const DIALOG_ICON_SIZE: i16 = 32;

/// Small Macintosh Dialog icon size (16x16 pixels, `SICN`).
#[allow(dead_code)]
pub const DIALOG_SMALL_ICON_SIZE: i16 = 16;

/// Centers an icon of dimensions `(icon_width, icon_height)` within `item_rect` `(top, left, bottom, right)`.
///
/// If `item_rect` is larger than the icon, the icon is centered horizontally and vertically.
/// If `item_rect` is identical in size, `item_rect` is returned.
#[allow(dead_code)]
#[inline]
pub const fn dialog_icon_rect(
    item_rect: (i16, i16, i16, i16),
    icon_width: i16,
    icon_height: i16,
) -> (i16, i16, i16, i16) {
    let (top, left, bottom, right) = item_rect;
    let rect_w = right - left;
    let rect_h = bottom - top;
    let offset_x = (rect_w - icon_width) / 2;
    let offset_y = (rect_h - icon_height) / 2;
    let start_x = left + offset_x;
    let start_y = top + offset_y;
    (start_y, start_x, start_y + icon_height, start_x + icon_width)
}

/// Centers a standard 32x32 icon (`DIALOG_ICON_SIZE`) within `item_rect`.
#[allow(dead_code)]
#[inline]
pub const fn dialog_standard_icon_rect(item_rect: (i16, i16, i16, i16)) -> (i16, i16, i16, i16) {
    dialog_icon_rect(item_rect, DIALOG_ICON_SIZE, DIALOG_ICON_SIZE)
}

/// Returns true if the raw item type represents static or editable text requiring handle disposal.
pub const fn is_dialog_item_disposable_text(raw_type: u8) -> bool {
    is_dialog_item_text(raw_type)
}

/// Returns true if the raw item type represents a button, checkbox, radio, or resource control requiring control record disposal.
pub const fn is_dialog_item_disposable_control(raw_type: u8) -> bool {
    is_dialog_item_control(raw_type)
}

/// Maps a dialog item type (with or without disabled bit) to its standard Control Manager procID.
///
/// Inside Macintosh Volume I, pp. I-410, I-421:
/// - Button (4) -> 0 (`pushButProc`)
/// - Checkbox (5) -> 1 (`checkBoxProc`)
/// - Radio (6) -> 2 (`radioButProc`)
pub fn dialog_item_control_proc_id(item_type: u8) -> Option<i16> {
    match dialog_item_base_type(item_type) {
        DIALOG_ITEM_BUTTON => Some(0),
        DIALOG_ITEM_CHECKBOX => Some(1),
        DIALOG_ITEM_RADIO => Some(2),
        _ => None,
    }
}

/// Maps an alert type (Stop, Note, Caution, Plain) to standard icon resource ID (Stop=0, Note=1, Caution=2, Plain=None).
#[allow(dead_code)]
pub fn alert_icon_id(alert_type: u16) -> Option<i16> {
    match alert_type {
        ALERT_TYPE_STOP => Some(0),
        ALERT_TYPE_NOTE => Some(1),
        ALERT_TYPE_CAUTION => Some(2),
        _ => None,
    }
}

/// Computes the next AlertStage counter capped at 3, per Inside Macintosh Volume I, p. I-423.
pub fn next_alert_stage(current_stage: u16) -> u16 {
    ((current_stage as u32) + 1).min(3) as u16
}

/// Normalizes an arbitrary text selection range `(start, end)` within `0..=max_len`.
///
/// Clamps both bounds to `max_len` and ensures `start <= end`.
#[inline]
pub fn normalize_selection_bounds(start: usize, end: usize, max_len: usize) -> (usize, usize) {
    let s = start.min(max_len);
    let e = end.min(max_len);
    if s <= e {
        (s, e)
    } else {
        (e, s)
    }
}

/// Normalizes an edit text item selection range `(start_sel, end_sel)` against a given text length.
///
/// Inside Macintosh Volume I, p. I-414, and Macintosh Toolbox Essentials (1992), p. 6-132:
/// - Special case: `(0, -1)` or `(0, 32767)` indicates "select all" (`0..text_len`).
/// - Clamps start and end bounds to `0..=text_len`.
/// - Normalizes reversed bounds (`start > end` -> swapped to `end..start`).
pub fn normalize_dialog_item_selection(
    start_sel: i16,
    end_sel: i16,
    text_len: usize,
) -> (u16, u16) {
    let text_len = text_len.min(i16::MAX as usize);
    if start_sel == 0 && (end_sel == -1 || end_sel == i16::MAX) {
        (0, text_len as u16)
    } else {
        let (s, e) = normalize_selection_bounds(
            start_sel.max(0) as usize,
            end_sel.max(0) as usize,
            text_len,
        );
        (s as u16, e as u16)
    }
}

/// Computes the outer bounding rectangle and corner oval radius for drawing the standard 3px bold
/// default button ring around a push button rectangle.
///
/// Macintosh Toolbox Essentials (1992), Listing 6-17:
/// Outer rect is outset by 4 pixels in all dimensions; corner oval diameter is `max(4, height / 2 - 4)`.
pub fn default_button_outline_geometry(
    button_rect: (i16, i16, i16, i16),
) -> ((i16, i16, i16, i16), i16) {
    let outer = (
        button_rect.0.saturating_sub(DEFAULT_BUTTON_OUTLINE_INSET),
        button_rect.1.saturating_sub(DEFAULT_BUTTON_OUTLINE_INSET),
        button_rect.2.saturating_add(DEFAULT_BUTTON_OUTLINE_INSET),
        button_rect.3.saturating_add(DEFAULT_BUTTON_OUTLINE_INSET),
    );
    let height = outer.2.saturating_sub(outer.0);
    let oval = (height / 2 - 4).max(4);
    (outer, oval)
}

/// Returns true if the title matches "Cancel" (case-insensitive ASCII), which identifies
/// the standard Cancel button in dialog boxes per Macintosh Toolbox Essentials (1992), p. 6-51.
pub fn is_dialog_cancel_button_title(title: &[u8]) -> bool {
    title.eq_ignore_ascii_case(b"cancel")
}

/// Returns true if the string title matches "Cancel" (case-insensitive ASCII).
#[allow(dead_code)]
pub fn is_dialog_cancel_button_title_str(title: &str) -> bool {
    title.eq_ignore_ascii_case("cancel")
}

/// Finds the 1-indexed item number of an enabled PushButton with title "Cancel" (case-insensitive).
pub fn find_dialog_cancel_item_index<I, T>(items: I) -> Option<u16>
where
    I: IntoIterator<Item = (u8, T)>,
    T: AsRef<[u8]>,
{
    items
        .into_iter()
        .enumerate()
        .find_map(|(idx, (raw_type, title))| {
            let is_enabled_button =
                is_dialog_item_enabled(raw_type) && is_dialog_item_button(raw_type);
            if is_enabled_button && is_dialog_cancel_button_title(title.as_ref()) {
                u16::try_from(idx + 1).ok()
            } else {
                None
            }
        })
}

/// Resolves the 1-indexed cancel item number for a dialog.
///
/// Priority:
/// 1. An explicitly configured cancel item (`configured_cancel > 0`).
/// 2. An enabled PushButton with title "Cancel" (case-insensitive ASCII) found via `find_dialog_cancel_item_index`.
/// 3. Returns 0 if no cancel item is configured or found.
///
/// Inside Macintosh: Macintosh Toolbox Essentials (1992), pp. 6-51, 6-86--6-90, 6-163.
pub fn resolve_dialog_cancel_item<I, T>(configured_cancel: Option<i16>, items: I) -> i16
where
    I: IntoIterator<Item = (u8, T)>,
    T: AsRef<[u8]>,
{
    if let Some(item) = configured_cancel {
        if item > 0 {
            return item;
        }
    }
    find_dialog_cancel_item_index(items)
        .map(|idx| idx as i16)
        .unwrap_or(0)
}

/// Resolves the 1-indexed cancel item number for a modal dialog, falling back to
/// `ALERT_BUTTON_CANCEL` (2) if no explicit or titled cancel item is found, per classic Mac OS convention.
pub fn resolve_modal_dialog_cancel_item<I, T>(configured_cancel: Option<i16>, items: I) -> i16
where
    I: IntoIterator<Item = (u8, T)>,
    T: AsRef<[u8]>,
{
    let item = resolve_dialog_cancel_item(configured_cancel, items);
    if item > 0 {
        item
    } else {
        ALERT_BUTTON_CANCEL
    }
}

/// Resolves the 1-indexed default item number for a dialog.
///
/// If `configured_default` is `Some(item)` with `item > 0`, it is returned directly.
/// Otherwise, defaults to `ALERT_BUTTON_OK` (1) if `item_count >= 1`, or 0 if empty.
///
/// Inside Macintosh Volume I, p. I-415; Macintosh Toolbox Essentials (1992), pp. 6-86--6-90, 6-163.
pub fn resolve_dialog_default_item(configured_default: Option<i16>, item_count: usize) -> i16 {
    if let Some(item) = configured_default {
        if item > 0 {
            return item;
        }
    }
    if item_count >= 1 {
        ALERT_BUTTON_OK
    } else {
        0
    }
}

/// Returns true if `item_no` matches the active default item (`item_no == default_item && default_item > 0`).
#[allow(dead_code)]
#[inline]
pub const fn is_dialog_default_button(item_no: i16, default_item: i16) -> bool {
    item_no > 0 && item_no == default_item
}

/// Returns true if `item_no` matches the active cancel item (`item_no == cancel_item && cancel_item > 0`).
#[allow(dead_code)]
#[inline]
pub const fn is_dialog_cancel_button(item_no: i16, cancel_item: i16) -> bool {
    item_no > 0 && item_no == cancel_item
}

/// Computes the `(dv, dh)` translation offset for items being appended to a dialog via `AppendDITL`.
///
/// Macintosh Toolbox Essentials (1992), pp. 6-108, 6-153:
/// - `overlayDITL` (0): (0, 0)
/// - `appendDITLRight` (1): (0, dialog_width)
/// - `appendDITLBottom` (2): (dialog_height, 0)
/// - negative `item_no` (< 0): offset relative to the upper-left of item `-method` (1-indexed).
pub fn append_ditl_offset_delta<F>(
    method: i16,
    dialog_height: i16,
    dialog_width: i16,
    item_origin_lookup: F,
) -> (i16, i16)
where
    F: FnOnce(usize) -> Option<(i16, i16)>,
{
    match method {
        APPEND_DITL_OVERLAY => (0, 0),
        APPEND_DITL_RIGHT => (0, dialog_width),
        APPEND_DITL_BOTTOM => (dialog_height, 0),
        relative_item if relative_item < 0 => {
            let item_no = usize::from(relative_item.unsigned_abs());
            item_origin_lookup(item_no).unwrap_or((0, 0))
        }
        _ => (0, 0),
    }
}

/// Calculates the number of retained items and the new DITL count-minus-one header word
/// after removing `remove_count` items from a dialog with `current_count` items.
///
/// Macintosh Toolbox Essentials (1992), p. 6-154:
/// - If `remove_count >= current_count`, all items are removed (0 retained, header word is -1 / 0xFFFF).
/// - Otherwise, `retained = current_count - remove_count`, and header word is `(retained - 1) as i16`.
pub fn shorten_ditl_counts(current_count: usize, remove_count: usize) -> (usize, i16) {
    let remove = remove_count.min(current_count);
    let retained = current_count.saturating_sub(remove);
    let count_minus_one = if retained == 0 {
        -1
    } else {
        retained.saturating_sub(1).min(i16::MAX as usize) as i16
    };
    (retained, count_minus_one)
}

/// Returns true if two rectangles intersect.
pub fn rects_intersect(a: (i16, i16, i16, i16), b: (i16, i16, i16, i16)) -> bool {
    a.0 < b.2 && a.2 > b.0 && a.1 < b.3 && a.3 > b.1
}

/// Returns true if a dialog item's local rectangle intersects the dialog global bounds.
pub fn dialog_item_intersects_bounds(
    bounds: (i16, i16, i16, i16),
    item_rect: (i16, i16, i16, i16),
) -> bool {
    rects_intersect(dialog_rect_to_global(bounds, item_rect), bounds)
}

/// Checks whether an in-bounds dialog is game-managed (all items intersecting bounds are user items).
pub fn is_dialog_game_managed<I>(bounds: (i16, i16, i16, i16), items: I) -> bool
where
    I: IntoIterator<Item = (u8, (i16, i16, i16, i16))>,
{
    let mut has_visible_item = false;
    for (item_type, item_rect) in items {
        if !dialog_item_intersects_bounds(bounds, item_rect) {
            continue;
        }
        has_visible_item = true;
        if !is_dialog_item_user_item(item_type) {
            return false;
        }
    }
    has_visible_item
}

/// Tests whether an event should be handled as part of an active modeless or movable modal dialog.
///
/// Inside Macintosh Volume I (1985), p. I-416;
/// Macintosh Toolbox Essentials (1992), p. 6-138:
/// - If there is no target dialog corresponding to the event, returns `false`.
/// - For `updateEvt` (6) and `activateEvt` (8), returns `true` if `message == dialog_ptr`.
/// - For `mouseDown` (1), returns `true` if the mouse point `(where_v, where_h)` falls within the dialog window bounds.
/// - For all other event types directed to the dialog, returns `true`.
pub fn is_dialog_event(
    what: u16,
    message: u32,
    where_v: i16,
    where_h: i16,
    target_dialog: Option<u32>,
    dialog_bounds: Option<(i16, i16, i16, i16)>,
) -> bool {
    let Some(dialog_ptr) = target_dialog else {
        return false;
    };
    match what {
        EVENT_UPDATE | EVENT_ACTIVATE => message == dialog_ptr,
        EVENT_MOUSE_DOWN => {
            dialog_bounds.is_some_and(|bounds| rect_contains_point(bounds, where_v, where_h))
        }
        _ => true,
    }
}

/// Validates whether a character is an editable character accepted by dialog edit fields.
///
/// Macintosh Toolbox Essentials (1992), p. 6-139:
/// Accepts backspace (0x08) and printable ASCII / Mac Roman characters (0x20..=0x7E).
pub fn is_dialog_edit_text_character(character: u8) -> bool {
    matches!(character, 0x08 | 0x20..=0x7E)
}

/// Describes the action that the host environment must take in response to a `DialogSelect` event.
///
/// Inside Macintosh Volume I, pp. I-417--I-418;
/// Macintosh Toolbox Essentials (1992), pp. 6-139--6-141.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DialogSelectAction {
    /// The event is not targeted at an active dialog, fell outside the dialog window,
    /// or was otherwise ignored by the Dialog Manager.
    ///
    /// Corresponds to `DialogSelect` returning `FALSE` (0).
    NoAction,

    /// An update event (`updateEvt`) targeted at `dialog`.
    ///
    /// The caller must redraw the dialog window contents.
    /// `theDialog` out-pointer is written with `dialog`.
    /// Returns `FALSE` (0).
    Update { dialog: u32 },

    /// An activate event (`activateEvt`) targeted at `dialog`.
    ///
    /// `theDialog` out-pointer is written with `dialog`.
    /// Returns `FALSE` (0).
    Activate { dialog: u32 },

    /// A null event (`nullEvent`) targeted at `dialog` while an editable text item is active.
    ///
    /// The caller must call `TEIdle` on the dialog's TextEdit record to blink the insertion caret.
    /// Returns `FALSE` (0).
    Idle { dialog: u32, edit_item: i16 },

    /// A mouse-down event (`mouseDown`) hit an enabled dialog item.
    ///
    /// The caller must:
    /// - If `is_edit_text`: activate or focus the edit field (e.g. `TEClick`).
    /// - If `is_resource_control`: track the control (e.g. scroll bar tracking).
    /// - Write `theDialog = dialog` and `itemHit = item_no`.
    /// Returns `TRUE` (1).
    ItemHit {
        dialog: u32,
        item_no: i16,
        is_edit_text: bool,
        is_resource_control: bool,
    },

    /// A mouse-down event (`mouseDown`) hit a disabled dialog item.
    ///
    /// Does not activate or return the item.
    /// Returns `FALSE` (0).
    DisabledItemHit { dialog: u32, item_no: i16 },

    /// A key-down or auto-key event directed to an active enabled editable text field.
    ///
    /// The caller must process the character via TextEdit (e.g. `TEKey`) and write:
    /// - `theDialog = dialog` and `itemHit = edit_item`.
    /// Returns `TRUE` (1).
    KeyStroke {
        dialog: u32,
        edit_item: i16,
        character: u8,
    },
}

#[allow(dead_code)]
impl DialogSelectAction {
    /// Whether this action represents a handled event that causes `DialogSelect` to return `TRUE` (1).
    #[inline]
    pub const fn is_handled(self) -> bool {
        matches!(self, Self::ItemHit { .. } | Self::KeyStroke { .. })
    }

    /// Whether this action sets `theDialog` output pointer if one was provided.
    #[inline]
    pub const fn should_set_dialog_ptr(self) -> bool {
        matches!(
            self,
            Self::Update { .. }
                | Self::Activate { .. }
                | Self::ItemHit { .. }
                | Self::KeyStroke { .. }
        )
    }

    /// The target dialog pointer if this action affects a dialog box.
    #[inline]
    pub const fn target_dialog(self) -> Option<u32> {
        match self {
            Self::NoAction => None,
            Self::Update { dialog }
            | Self::Activate { dialog }
            | Self::Idle { dialog, .. }
            | Self::ItemHit { dialog, .. }
            | Self::DisabledItemHit { dialog, .. }
            | Self::KeyStroke { dialog, .. } => Some(dialog),
        }
    }

    /// The affected 1-indexed item number if this action reports an item hit (`ItemHit` or `KeyStroke`).
    #[inline]
    pub const fn item_hit(self) -> Option<i16> {
        match self {
            Self::ItemHit { item_no, .. } => Some(item_no),
            Self::KeyStroke { edit_item, .. } => Some(edit_item),
            _ => None,
        }
    }
}

/// Evaluates an event record within the context of `DialogSelect`.
///
/// Macintosh Toolbox Essentials (1992), pp. 6-139--6-141:
/// - Update and activate events route to the named window (if it is a dialog).
/// - Null events advance the insertion-caret blink in active editable text fields via `Idle`.
/// - Mouse-down events inside the dialog bounds are hit-tested against dialog items.
/// - Key-down and auto-key events are forwarded to the active editable text field.
pub fn evaluate_dialog_select<F>(
    what: u16,
    message: u32,
    where_v: i16,
    where_h: i16,
    target_dialog: Option<u32>,
    dialog_bounds: Option<(i16, i16, i16, i16)>,
    active_edit_item: Option<(i16, u8)>,
    hit_test: F,
) -> DialogSelectAction
where
    F: FnOnce(i16, i16) -> Option<(i16, u8)>,
{
    let Some(dialog) = target_dialog else {
        return DialogSelectAction::NoAction;
    };

    match what {
        EVENT_UPDATE if message == dialog => DialogSelectAction::Update { dialog },
        EVENT_ACTIVATE if message == dialog => DialogSelectAction::Activate { dialog },
        EVENT_NULL => {
            if let Some((edit_item, raw_type)) = active_edit_item {
                if edit_item > 0
                    && is_dialog_item_enabled(raw_type)
                    && is_dialog_item_edit_text(raw_type)
                {
                    return DialogSelectAction::Idle { dialog, edit_item };
                }
            }
            DialogSelectAction::NoAction
        }
        EVENT_MOUSE_DOWN => {
            let Some(bounds) = dialog_bounds else {
                return DialogSelectAction::NoAction;
            };
            if !rect_contains_point(bounds, where_v, where_h) {
                return DialogSelectAction::NoAction;
            }
            if let Some((item_no, raw_type)) = hit_test(where_v, where_h) {
                if item_no > 0 {
                    if is_dialog_item_enabled(raw_type) {
                        return DialogSelectAction::ItemHit {
                            dialog,
                            item_no,
                            is_edit_text: is_dialog_item_edit_text(raw_type),
                            is_resource_control: is_dialog_item_resource_control(raw_type),
                        };
                    } else {
                        return DialogSelectAction::DisabledItemHit { dialog, item_no };
                    }
                }
            }
            DialogSelectAction::NoAction
        }
        EVENT_KEY_DOWN | EVENT_AUTO_KEY => {
            if let Some((edit_item, raw_type)) = active_edit_item {
                if edit_item > 0
                    && is_dialog_item_enabled(raw_type)
                    && is_dialog_item_edit_text(raw_type)
                {
                    let character = (message & 0xFF) as u8;
                    if is_dialog_edit_text_character(character) {
                        return DialogSelectAction::KeyStroke {
                            dialog,
                            edit_item,
                            character,
                        };
                    }
                }
            }
            DialogSelectAction::NoAction
        }
        _ => DialogSelectAction::NoAction,
    }
}

/// Calculates the updated text bytes and new insertion caret offset after processing a key press
/// (such as backspace or printable character) against an existing text buffer and selection range.
///
/// Macintosh Toolbox Essentials (1992), pp. 2-83--2-88, 6-139.
pub fn textedit_key_result(
    existing: &[u8],
    sel_start: usize,
    sel_end: usize,
    key: u8,
) -> (Vec<u8>, usize) {
    let text_len = existing.len();
    let s = sel_start.min(text_len);
    let e = sel_end.min(text_len);
    let (s, e) = if s > e { (e, s) } else { (s, e) };

    if key == 0x08 {
        if s != e {
            let mut merged = Vec::with_capacity(text_len - (e - s));
            merged.extend_from_slice(&existing[..s]);
            merged.extend_from_slice(&existing[e..]);
            return (merged, s);
        }
        if s > 0 {
            let mut merged = Vec::with_capacity(text_len - 1);
            merged.extend_from_slice(&existing[..s - 1]);
            merged.extend_from_slice(&existing[s..]);
            return (merged, s - 1);
        }
        return (existing.to_vec(), s);
    }

    let mut merged = Vec::with_capacity(s + 1 + text_len.saturating_sub(e));
    merged.extend_from_slice(&existing[..s]);
    merged.push(key);
    merged.extend_from_slice(&existing[e..]);
    (merged, s + 1)
}

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

    #[test]
    fn item_kind_decoding_and_properties() {
        assert_eq!(DialogItemKind::from_raw_type(4), DialogItemKind::Button);
        assert_eq!(
            DialogItemKind::from_raw_type(4 | DIALOG_ITEM_DISABLED_FLAG),
            DialogItemKind::Button
        );
        assert!(DialogItemKind::Button.is_control());
        assert!(!DialogItemKind::Button.is_text());

        assert_eq!(DialogItemKind::from_raw_type(8), DialogItemKind::StaticText);
        assert!(DialogItemKind::StaticText.is_text());
        assert!(!DialogItemKind::StaticText.is_control());

        assert_eq!(DialogItemKind::from_raw_type(16), DialogItemKind::EditText);
        assert_eq!(DialogItemKind::from_raw_type(32), DialogItemKind::Icon);
        assert_eq!(DialogItemKind::from_raw_type(64), DialogItemKind::Picture);
        assert_eq!(DialogItemKind::from_raw_type(0), DialogItemKind::UserItem);
        assert_eq!(
            DialogItemKind::from_raw_type(99),
            DialogItemKind::Unknown(99)
        );
    }

    #[test]
    fn parse_ditl_items_round_trip() {
        let mut data = Vec::new();
        // Item count minus 1: 1 item (0x0000)
        data.extend_from_slice(&0i16.to_be_bytes());
        // Handle: 0
        data.extend_from_slice(&0u32.to_be_bytes());
        // Rect: (10, 20, 30, 40)
        data.extend_from_slice(&10i16.to_be_bytes());
        data.extend_from_slice(&20i16.to_be_bytes());
        data.extend_from_slice(&30i16.to_be_bytes());
        data.extend_from_slice(&40i16.to_be_bytes());
        // Type: Button (4), Length: 2, Payload: "OK"
        data.push(DIALOG_ITEM_BUTTON);
        data.push(2);
        data.extend_from_slice(b"OK");

        let items = parse_ditl_items(&data).expect("valid DITL");
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].rect, (10, 20, 30, 40));
        assert_eq!(items[0].kind(), DialogItemKind::Button);
        assert!(items[0].is_enabled());
        assert_eq!(items[0].text(), "OK");
    }

    #[test]
    fn position_dialog_centering() {
        let bounds = (0, 0, 100, 200);
        // Centered position flag 0x280a
        let centered = position_dialog_bounds(bounds, 0x280a, 640, 480);
        assert_eq!(centered, (190, 220, 290, 420));

        // Non-centered flag leaves bounds unchanged
        let uncentered = position_dialog_bounds(bounds, 0x0000, 640, 480);
        assert_eq!(uncentered, bounds);
    }

    #[test]
    fn parse_ditl_items_empty_and_truncated() {
        let mut empty_data = Vec::new();
        empty_data.extend_from_slice(&(-1i16).to_be_bytes());
        let empty_items = parse_ditl_items(&empty_data).expect("valid empty DITL");
        assert!(empty_items.is_empty());
        assert_eq!(ditl_total_used_len(&empty_data), 2);

        // Truncated item: count 2, first valid button, second item truncated
        let mut data = Vec::new();
        data.extend_from_slice(&1i16.to_be_bytes()); // count-1 = 1 (2 items)
                                                     // Item 1: Button "OK"
        data.extend_from_slice(&0u32.to_be_bytes());
        data.extend_from_slice(&[0, 1, 0, 2, 0, 11, 0, 42]);
        data.push(DIALOG_ITEM_BUTTON);
        data.push(2);
        data.extend_from_slice(b"OK");
        // Item 2: StatText declaring 6 bytes, but only 3 provided
        data.extend_from_slice(&0u32.to_be_bytes());
        data.extend_from_slice(&[0, 12, 0, 2, 0, 22, 0, 72]);
        data.push(DIALOG_ITEM_STATIC_TEXT);
        data.push(6);
        data.extend_from_slice(b"Bad");

        let items = parse_ditl_items(&data).expect("parses valid items before truncated one");
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].text(), "OK");
    }

    #[test]
    fn parse_ditl_items_resource_ids_and_record_lengths() {
        let mut data = Vec::new();
        data.extend_from_slice(&1i16.to_be_bytes()); // 2 items
                                                     // Item 1: resCtrl (7) with reserved byte 0 followed by 128
        data.extend_from_slice(&0u32.to_be_bytes());
        data.extend_from_slice(&[0, 1, 0, 2, 0, 11, 0, 42]);
        data.push(DIALOG_ITEM_RESOURCE_CONTROL);
        data.push(0); // reserved byte per MTE
        data.extend_from_slice(&128i16.to_be_bytes());

        // Item 2: icon (32) with length byte 2 followed by -42
        data.extend_from_slice(&0u32.to_be_bytes());
        data.extend_from_slice(&[0, 12, 0, 2, 0, 28, 0, 34]);
        data.push(DIALOG_ITEM_ICON);
        data.push(2); // length byte 2 per IM:I
        data.extend_from_slice(&(-42i16).to_be_bytes());

        let len1 = ditl_item_record_len_at(&data, 2).expect("record 1 len");
        assert_eq!(len1, 16);
        let len2 = ditl_item_record_len_at(&data, 2 + len1).expect("record 2 len");
        assert_eq!(len2, 16);
        assert_eq!(ditl_total_used_len(&data), 2 + len1 + len2);

        let items = parse_ditl_items(&data).expect("valid items");
        assert_eq!(items.len(), 2);
        assert_eq!(items[0].kind(), DialogItemKind::ResourceControl);
        assert_eq!(items[0].resource_id(), Some(128));
        assert_eq!(items[1].kind(), DialogItemKind::Icon);
        assert_eq!(items[1].resource_id(), Some(-42));
    }

    #[test]
    fn dialog_item_rect_geometry_and_visibility() {
        let initial_rect = (10, 20, 30, 80);
        let offset = offset_rect(initial_rect, 5, -10);
        assert_eq!(offset, (15, 10, 35, 70));

        let bounds = (100, 200, 300, 500);
        let global = dialog_rect_to_global(bounds, initial_rect);
        assert_eq!(global, (110, 220, 130, 280));
        let local = dialog_rect_to_local(bounds, global);
        assert_eq!(local, initial_rect);

        assert!(!is_dialog_item_rect_hidden(initial_rect));
        let hidden = hide_dialog_item_rect(initial_rect);
        assert_eq!(hidden, (10, 16404, 30, 16464));
        assert!(is_dialog_item_rect_hidden(hidden));
        let shown = show_dialog_item_rect(hidden);
        assert_eq!(shown, initial_rect);

        // Enclosing rect: standard controls match exactly; editText extends 3px on all sides
        assert_eq!(
            dialog_item_enclosing_rect(DIALOG_ITEM_BUTTON, initial_rect),
            initial_rect
        );
        assert_eq!(
            dialog_item_enclosing_rect(DIALOG_ITEM_EDIT_TEXT, initial_rect),
            (7, 17, 33, 83)
        );

        // DialogItemRecord helpers
        let mut record = DialogItemRecord {
            item_offset: 2,
            item_type: DIALOG_ITEM_EDIT_TEXT,
            rect: initial_rect,
            handle: 0,
            payload: vec![],
        };
        assert!(!record.is_hidden());
        assert_eq!(record.enclosing_rect(), (7, 17, 33, 83));
        record.offset_rect(10, 20);
        assert_eq!(record.rect, (20, 40, 40, 100));
    }

    #[test]
    fn dialog_item_point_hit_testing_and_ditl_byte_offsetting() {
        let rect1 = (10, 20, 30, 50);
        let rect2 = (30, 20, 50, 50);
        let rects = [rect1, rect2];

        // rect_contains_point is half-open: [top, bottom) and [left, right)
        assert!(rect_contains_point(rect1, 10, 20));
        assert!(rect_contains_point(rect1, 29, 49));
        assert!(!rect_contains_point(rect1, 30, 20));
        assert!(!rect_contains_point(rect1, 10, 50));

        // find_dialog_item_at_local_point
        assert_eq!(find_dialog_item_at_local_point(&rects, 15, 25), Some(0));
        assert_eq!(find_dialog_item_at_local_point(&rects, 35, 25), Some(1));
        assert_eq!(find_dialog_item_at_local_point(&rects, 5, 5), None);

        // offset_ditl_bytes
        let mut data = Vec::new();
        data.extend_from_slice(&0i16.to_be_bytes()); // 1 item
        data.extend_from_slice(&0u32.to_be_bytes()); // handle at 2
        data.extend_from_slice(&10i16.to_be_bytes()); // top at 6
        data.extend_from_slice(&20i16.to_be_bytes()); // left at 8
        data.extend_from_slice(&30i16.to_be_bytes()); // bottom at 10
        data.extend_from_slice(&40i16.to_be_bytes()); // right at 12
        data.push(DIALOG_ITEM_BUTTON);
        data.push(0);

        offset_ditl_bytes(&mut data, [2], 5, 10);
        assert_eq!(i16::from_be_bytes([data[6], data[7]]), 15);
        assert_eq!(i16::from_be_bytes([data[8], data[9]]), 30);
        assert_eq!(i16::from_be_bytes([data[10], data[11]]), 35);
        assert_eq!(i16::from_be_bytes([data[12], data[13]]), 50);
    }

    #[test]
    fn dialog_template_parsing_and_positioning() {
        // Classic 22-byte DLOG (empty title, no position word)
        let mut dlog22 = Vec::new();
        dlog22.extend_from_slice(&228i16.to_be_bytes()); // top
        dlog22.extend_from_slice(&198i16.to_be_bytes()); // left
        dlog22.extend_from_slice(&372i16.to_be_bytes()); // bottom
        dlog22.extend_from_slice(&455i16.to_be_bytes()); // right
        dlog22.extend_from_slice(&2i16.to_be_bytes()); // proc_id
        dlog22.push(1); // visible
        dlog22.push(0); // filler
        dlog22.push(0); // go_away
        dlog22.push(0); // filler
        dlog22.extend_from_slice(&0u32.to_be_bytes()); // ref_con
        dlog22.extend_from_slice(&1013i16.to_be_bytes()); // items_id
        dlog22.push(0); // empty title length
        dlog22.push(0); // padding

        let template = parse_dialog_template(&dlog22).expect("valid 22-byte dlog");
        assert_eq!(template.bounds, (228, 198, 372, 455));
        assert_eq!(template.proc_id, 2);
        assert!(template.visible);
        assert!(!template.go_away);
        assert_eq!(template.ref_con, 0);
        assert_eq!(template.items_id, 1013);
        assert_eq!(template.title, b"");
        assert_eq!(template.title_string(), "");
        assert_eq!(template.position, 0);

        // 24-byte DLOG with position word 0x280A
        let mut dlog24 = dlog22.clone();
        dlog24.extend_from_slice(&0x280Au16.to_be_bytes());
        let template = parse_dialog_template(&dlog24).expect("valid 24-byte dlog");
        assert_eq!(template.position, 0x280A);

        // DLOG with odd title ("Odd" -> 3 bytes, padded to 24, position at 24..26)
        let mut dlog_odd = Vec::new();
        dlog_odd.extend_from_slice(&10i16.to_be_bytes());
        dlog_odd.extend_from_slice(&20i16.to_be_bytes());
        dlog_odd.extend_from_slice(&110i16.to_be_bytes());
        dlog_odd.extend_from_slice(&220i16.to_be_bytes());
        dlog_odd.extend_from_slice(&1i16.to_be_bytes());
        dlog_odd.push(1); // visible
        dlog_odd.push(0);
        dlog_odd.push(1); // go_away
        dlog_odd.push(0);
        dlog_odd.extend_from_slice(&42u32.to_be_bytes());
        dlog_odd.extend_from_slice(&701i16.to_be_bytes());
        dlog_odd.push(3); // title len
        dlog_odd.extend_from_slice(b"Odd");
        // title_end = 21 + 3 = 24 (even boundary), so position is at offset 24..26
        dlog_odd.extend_from_slice(&0x300Au16.to_be_bytes());
        let template = parse_dialog_template(&dlog_odd).expect("valid odd title dlog");
        assert_eq!(template.title_string(), "Odd");
        assert_eq!(template.items_id, 701);
        assert_eq!(template.position, 0x300A);
        assert!(template.go_away);

        // DLOG with even title ("Even" -> 4 bytes, padded to 26, position at 26..28)
        let mut dlog_even = Vec::new();
        dlog_even.extend_from_slice(&11i16.to_be_bytes());
        dlog_even.extend_from_slice(&21i16.to_be_bytes());
        dlog_even.extend_from_slice(&111i16.to_be_bytes());
        dlog_even.extend_from_slice(&221i16.to_be_bytes());
        dlog_even.extend_from_slice(&1i16.to_be_bytes());
        dlog_even.push(1);
        dlog_even.push(0);
        dlog_even.push(0);
        dlog_even.push(0);
        dlog_even.extend_from_slice(&0u32.to_be_bytes());
        dlog_even.extend_from_slice(&702i16.to_be_bytes());
        dlog_even.push(4); // title len
        dlog_even.extend_from_slice(b"Even");
        dlog_even.push(0); // alignment pad
        dlog_even.extend_from_slice(&0x700Au16.to_be_bytes());
        let template = parse_dialog_template(&dlog_even).expect("valid even title dlog");
        assert_eq!(template.title_string(), "Even");
        assert_eq!(template.items_id, 702);
        assert_eq!(template.position, 0x700A);

        // Truncated DLOG (< 20 bytes) returns None
        assert!(parse_dialog_template(&[0u8; 19]).is_none());
    }

    #[test]
    fn alert_template_parsing_and_stages() {
        // Classic 12-byte ALRT
        let mut alrt12 = Vec::new();
        alrt12.extend_from_slice(&10i16.to_be_bytes());
        alrt12.extend_from_slice(&20i16.to_be_bytes());
        alrt12.extend_from_slice(&90i16.to_be_bytes());
        alrt12.extend_from_slice(&220i16.to_be_bytes());
        alrt12.extend_from_slice(&123i16.to_be_bytes()); // items_id
        alrt12.extend_from_slice(&0x0008u16.to_be_bytes()); // stages

        let alert = parse_alert_template(&alrt12).expect("valid 12-byte alrt");
        assert_eq!(alert.bounds, (10, 20, 90, 220));
        assert_eq!(alert.items_id, 123);
        assert_eq!(alert.stages, 0x0008);
        assert_eq!(alert.position, 0);

        // 14-byte System 7 ALRT with position word 0xB00A
        let mut alrt14 = Vec::new();
        alrt14.extend_from_slice(&0i16.to_be_bytes());
        alrt14.extend_from_slice(&0i16.to_be_bytes());
        alrt14.extend_from_slice(&80i16.to_be_bytes());
        alrt14.extend_from_slice(&200i16.to_be_bytes());
        alrt14.extend_from_slice(&(-321i16).to_be_bytes()); // items_id
        alrt14.extend_from_slice(&0xF721u16.to_be_bytes()); // stages
        alrt14.extend_from_slice(&0xB00Au16.to_be_bytes()); // position

        let alert = parse_alert_template(&alrt14).expect("valid 14-byte alrt");
        assert_eq!(alert.items_id, -321);
        assert_eq!(alert.stages, 0xF721);
        assert_eq!(alert.position, 0xB00A);

        // Alert stages evaluation: 0xF721
        // Stage 0 (counter 0): nibble 1 (0b0001) -> box_drawn: false, default_item: 1, sound: 1
        let s0 = alert_stage_info(0xF721, 0);
        assert_eq!(s0.stage_index, 0);
        assert_eq!(s0.stage_nibble, 1);
        assert!(!s0.box_drawn);
        assert_eq!(s0.default_item, 1);
        assert_eq!(s0.sound_number, 1);

        // Stage 1 (counter 1): nibble 2 (0b0010) -> box_drawn: false, default_item: 1, sound: 2
        let s1 = alert_stage_info(0xF721, 1);
        assert_eq!(s1.stage_index, 1);
        assert_eq!(s1.stage_nibble, 2);
        assert!(!s1.box_drawn);
        assert_eq!(s1.default_item, 1);
        assert_eq!(s1.sound_number, 2);

        // Stage 2 (counter 2): nibble 7 (0b0111) -> box_drawn: true, default_item: 1, sound: 3
        let s2 = alert_stage_info(0xF721, 2);
        assert_eq!(s2.stage_index, 2);
        assert_eq!(s2.stage_nibble, 7);
        assert!(s2.box_drawn);
        assert_eq!(s2.default_item, 1);
        assert_eq!(s2.sound_number, 3);

        // Stage 3 (counter 3): nibble 0xF (0b1111) -> box_drawn: true, default_item: 2 (boldItm set), sound: 3
        let s3 = alert_stage_info(0xF721, 3);
        assert_eq!(s3.stage_index, 3);
        assert_eq!(s3.stage_nibble, 0xF);
        assert!(s3.box_drawn);
        assert_eq!(s3.default_item, 2);
        assert_eq!(s3.sound_number, 3);

        // Counter > 3 clamps to stage 3
        let s_clamped = alert_stage_info(0xF721, 10);
        assert_eq!(s_clamped, s3);

        // Truncated ALRT (< 8 bytes) returns None
        assert!(parse_alert_template(&[0u8; 7]).is_none());
    }

    #[test]
    fn param_text_byte_and_str_substitution() {
        let params: [Vec<u8>; 4] = [
            b"first".to_vec(),
            Vec::new(),
            b"third".to_vec(),
            b"fourth".to_vec(),
        ];

        // Byte substitution
        assert_eq!(
            apply_param_text(b"^0/^1/^2/^3", &params).as_ref(),
            b"first//third/fourth"
        );
        assert_eq!(
            apply_param_text(b"^^0 ^9 trailing^", &params).as_ref(),
            b"^first ^9 trailing^"
        );
        assert!(matches!(
            apply_param_text(b"plain", &params),
            Cow::Borrowed(_)
        ));

        // String substitution
        let str_params: [Vec<u8>; 4] = [
            b"MS UserKey".to_vec(),
            b"42".to_vec(),
            Vec::new(),
            Vec::new(),
        ];

        assert_eq!(
            apply_param_text_str("Unable to open the \"^0\" file.", &str_params),
            "Unable to open the \"MS UserKey\" file."
        );
        assert_eq!(apply_param_text_str("count: ^1", &str_params), "count: 42");
        assert_eq!(
            apply_param_text_str("plain text without placeholders", &str_params),
            "plain text without placeholders"
        );
        assert_eq!(
            apply_param_text_str("^0 ^1 ^2 ^3", &str_params),
            "MS UserKey 42  "
        );
        assert_eq!(
            apply_param_text_str("^A literal caret", &str_params),
            "^A literal caret"
        );
        assert_eq!(apply_param_text_str("trailing^", &str_params), "trailing^");
        assert_eq!(apply_param_text_str("^^0", &str_params), "^MS UserKey");
        assert_eq!(apply_param_text_str("", &str_params), "");
    }

    #[test]
    fn modal_dialog_keyboard_navigation_and_filter_evaluation() {
        // Return key: char 0x0D, keycode 0x24
        assert!(is_dialog_default_key(CHAR_RETURN, 0));
        assert!(is_dialog_default_key(0, KEY_RETURN));
        // Enter key: char 0x03, keycode 0x4C
        assert!(is_dialog_default_key(CHAR_ENTER, 0));
        assert!(is_dialog_default_key(0, KEY_NUMPAD_ENTER));
        assert!(!is_dialog_default_key(b'a', 0));

        // Escape: char 0x1B, keycode 0x35
        assert!(is_dialog_cancel_key(CHAR_ESCAPE, 0, 0));
        assert!(is_dialog_cancel_key(0, KEY_ESCAPE, 0));
        // Command-period: char '.' with MODIFIER_CMD_KEY
        assert!(is_dialog_cancel_key(CHAR_PERIOD, 0, MODIFIER_CMD_KEY));
        assert!(is_dialog_cancel_key(0, KEY_PERIOD, MODIFIER_CMD_KEY));
        // Period without Cmd is not cancel
        assert!(!is_dialog_cancel_key(CHAR_PERIOD, 0, 0));

        // Tab: char 0x09, keycode 0x30
        assert!(is_dialog_tab_key(CHAR_TAB, 0));
        assert!(is_dialog_tab_key(0, KEY_TAB));
        assert!(!is_dialog_tab_key(b' ', 0));

        // evaluate_modal_dialog_key
        let return_msg = (u32::from(KEY_RETURN) << 8) | u32::from(CHAR_RETURN);
        assert_eq!(
            evaluate_modal_dialog_key(EVENT_KEY_DOWN, return_msg, 0),
            DialogFilterDecision::TriggerDefaultButton
        );
        assert_eq!(
            evaluate_modal_dialog_key(EVENT_AUTO_KEY, return_msg, 0),
            DialogFilterDecision::TriggerDefaultButton
        );

        let esc_msg = (u32::from(KEY_ESCAPE) << 8) | u32::from(CHAR_ESCAPE);
        assert_eq!(
            evaluate_modal_dialog_key(EVENT_KEY_DOWN, esc_msg, 0),
            DialogFilterDecision::TriggerCancelButton
        );

        let cmd_period_msg = (u32::from(KEY_PERIOD) << 8) | u32::from(CHAR_PERIOD);
        assert_eq!(
            evaluate_modal_dialog_key(EVENT_KEY_DOWN, cmd_period_msg, MODIFIER_CMD_KEY),
            DialogFilterDecision::TriggerCancelButton
        );
        assert_eq!(
            evaluate_modal_dialog_key(EVENT_KEY_DOWN, cmd_period_msg, 0),
            DialogFilterDecision::Unhandled
        );

        let tab_msg = (u32::from(KEY_TAB) << 8) | u32::from(CHAR_TAB);
        assert_eq!(
            evaluate_modal_dialog_key(EVENT_KEY_DOWN, tab_msg, 0),
            DialogFilterDecision::AdvanceEditTextFocus
        );

        // Non-keyboard events (e.g. mouseDown = 1) are Unhandled
        assert_eq!(
            evaluate_modal_dialog_key(1, return_msg, 0),
            DialogFilterDecision::Unhandled
        );
    }

    #[test]
    fn find_next_edit_text_item_cycling() {
        assert_eq!(find_next_edit_text_item([], 0), None);
        assert_eq!(
            find_next_edit_text_item([DIALOG_ITEM_BUTTON, DIALOG_ITEM_STATIC_TEXT], 0),
            None
        );

        // Single editText at index 1 (item 2)
        let single = [
            DIALOG_ITEM_BUTTON,
            DIALOG_ITEM_EDIT_TEXT,
            DIALOG_ITEM_STATIC_TEXT,
        ];
        assert_eq!(find_next_edit_text_item(single, 0), Some(2));
        assert_eq!(find_next_edit_text_item(single, 1), Some(2));
        assert_eq!(find_next_edit_text_item(single, 2), Some(2));
        assert_eq!(find_next_edit_text_item(single, 3), Some(2));

        // Multiple editText items at item 2 and item 4
        let multiple = [
            DIALOG_ITEM_BUTTON,      // 1
            DIALOG_ITEM_EDIT_TEXT,   // 2
            DIALOG_ITEM_STATIC_TEXT, // 3
            DIALOG_ITEM_EDIT_TEXT,   // 4
        ];
        assert_eq!(find_next_edit_text_item(multiple, 0), Some(2));
        assert_eq!(find_next_edit_text_item(multiple, 1), Some(2));
        assert_eq!(find_next_edit_text_item(multiple, 2), Some(4));
        assert_eq!(find_next_edit_text_item(multiple, 3), Some(4));
        assert_eq!(find_next_edit_text_item(multiple, 4), Some(2)); // wraps!

        // Handles disabled flag (0x80)
        let disabled_edit = [
            DIALOG_ITEM_BUTTON,
            DIALOG_ITEM_EDIT_TEXT | DIALOG_ITEM_DISABLED_FLAG,
        ];
        assert_eq!(find_next_edit_text_item(disabled_edit, 0), Some(2));

        // find_next_edit_text_in_items helper
        let item_records = [
            DialogItemRecord {
                item_offset: 0,
                item_type: DIALOG_ITEM_BUTTON,
                rect: (0, 0, 0, 0),
                handle: 0,
                payload: vec![],
            },
            DialogItemRecord {
                item_offset: 0,
                item_type: DIALOG_ITEM_EDIT_TEXT,
                rect: (0, 0, 0, 0),
                handle: 0,
                payload: vec![],
            },
        ];
        assert_eq!(find_next_edit_text_in_items(&item_records, 0), Some(2));
        assert_eq!(find_next_edit_text_in_items(&item_records, 2), Some(2));
    }

    #[test]
    fn dialog_item_text_and_query_operations() {
        // Clamping length and bytes
        assert_eq!(clamp_dialog_item_text_len(10), 10);
        assert_eq!(clamp_dialog_item_text_len(300), 255);

        let short_bytes = b"Hello world";
        assert_eq!(clamp_dialog_item_text_bytes(short_bytes), short_bytes);
        let long_bytes = vec![b'A'; 300];
        let clamped = clamp_dialog_item_text_bytes(&long_bytes);
        assert_eq!(clamped.len(), 255);
        assert_eq!(clamped, &long_bytes[..255]);

        // Pascal string encode & decode
        let (len, text) = encode_dialog_item_pstring(b"Test");
        assert_eq!(len, 4);
        assert_eq!(text, b"Test");

        let mut pstr = vec![4];
        pstr.extend_from_slice(b"Test");
        assert_eq!(decode_dialog_item_pstring(&pstr), Some(&b"Test"[..]));
        assert_eq!(decode_dialog_item_pstring(&[]), None);
        assert_eq!(decode_dialog_item_pstring(&[10, 1, 2]), None); // truncated

        // 1-indexed lookups
        let mut items = vec!["First", "Second", "Third"];
        assert_eq!(get_item_at_1_indexed(&items, 0), None);
        assert_eq!(get_item_at_1_indexed(&items, 1), Some(&"First"));
        assert_eq!(get_item_at_1_indexed(&items, 2), Some(&"Second"));
        assert_eq!(get_item_at_1_indexed(&items, 3), Some(&"Third"));
        assert_eq!(get_item_at_1_indexed(&items, 4), None);

        *get_item_at_1_indexed_mut(&mut items, 2).unwrap() = "Modified";
        assert_eq!(items[1], "Modified");
        assert_eq!(get_item_at_1_indexed_mut(&mut items, 0), None);
        assert_eq!(get_item_at_1_indexed_mut(&mut items, 99), None);

        // Control and text predicates
        assert!(is_dialog_item_control(DIALOG_ITEM_BUTTON));
        assert!(is_dialog_item_control(
            DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG
        ));
        assert!(is_dialog_item_control(DIALOG_ITEM_CHECKBOX));
        assert!(is_dialog_item_control(DIALOG_ITEM_RADIO));
        assert!(is_dialog_item_control(DIALOG_ITEM_RESOURCE_CONTROL));
        assert!(!is_dialog_item_control(DIALOG_ITEM_STATIC_TEXT));
        assert!(!is_dialog_item_control(DIALOG_ITEM_EDIT_TEXT));
        assert!(!is_dialog_item_control(DIALOG_ITEM_ICON));

        assert!(is_dialog_item_text(DIALOG_ITEM_STATIC_TEXT));
        assert!(is_dialog_item_text(DIALOG_ITEM_EDIT_TEXT));
        assert!(is_dialog_item_text(
            DIALOG_ITEM_EDIT_TEXT | DIALOG_ITEM_DISABLED_FLAG
        ));
        assert!(!is_dialog_item_text(DIALOG_ITEM_BUTTON));
        assert!(!is_dialog_item_text(DIALOG_ITEM_ICON));

        assert!(is_dialog_item_text_or_title(DIALOG_ITEM_STATIC_TEXT));
        assert!(is_dialog_item_text_or_title(DIALOG_ITEM_EDIT_TEXT));
        assert!(is_dialog_item_text_or_title(DIALOG_ITEM_BUTTON));
        assert!(is_dialog_item_text_or_title(DIALOG_ITEM_CHECKBOX));
        assert!(is_dialog_item_text_or_title(DIALOG_ITEM_RADIO));
        assert!(!is_dialog_item_text_or_title(DIALOG_ITEM_RESOURCE_CONTROL));
        assert!(!is_dialog_item_text_or_title(DIALOG_ITEM_ICON));
        assert!(!is_dialog_item_text_or_title(DIALOG_ITEM_PICTURE));
        assert!(!is_dialog_item_text_or_title(DIALOG_ITEM_USER_ITEM));

        // String clamping and formatting
        let short_str = "Dialog item text";
        assert_eq!(clamp_dialog_item_text_str(short_str), short_str);
        let long_str = "a".repeat(300);
        let clamped_str = clamp_dialog_item_text_str(&long_str);
        assert_eq!(clamped_str.len(), 255);

        let pstr_formatted = format_dialog_item_pstring(b"Sample");
        assert_eq!(pstr_formatted[0], 6);
        assert_eq!(&pstr_formatted[1..], b"Sample");
        assert_eq!(
            decode_dialog_item_pstring_to_string(&pstr_formatted),
            Some("Sample".to_string())
        );

        let (set_bytes, set_string) = prepare_set_dialog_item_text(b"Config");
        assert_eq!(set_bytes, b"Config");
        assert_eq!(set_string, "Config");

        let (get_len, get_bytes) = prepare_get_dialog_item_text(b"Result");
        assert_eq!(get_len, 6);
        assert_eq!(get_bytes, b"Result");

        // Active text resolution from handle vs fallback payload
        let payload = b"Default text";
        let handle_override = b"Active handle text";
        assert_eq!(
            extract_dialog_item_text_bytes(DIALOG_ITEM_EDIT_TEXT, Some(handle_override), payload),
            handle_override
        );
        assert_eq!(
            extract_dialog_item_text_bytes(DIALOG_ITEM_EDIT_TEXT, None, payload),
            payload
        );
        assert_eq!(
            extract_dialog_item_text_bytes(DIALOG_ITEM_BUTTON, None, b"Cancel"),
            b"Cancel"
        );
        assert_eq!(
            extract_dialog_item_text_bytes(DIALOG_ITEM_ICON, None, &[0x00, 0x80]),
            b""
        );
        assert_eq!(
            extract_dialog_item_text_string(DIALOG_ITEM_STATIC_TEXT, None, b"Info"),
            "Info"
        );

        // DialogItemRecord text queries and payload isolation
        let text_record = DialogItemRecord {
            item_offset: 0,
            item_type: DIALOG_ITEM_STATIC_TEXT,
            rect: (0, 0, 10, 50),
            handle: 0,
            payload: b"Hello".to_vec(),
        };
        assert!(text_record.has_text_or_title());
        assert_eq!(text_record.text_payload(), Some(&b"Hello"[..]));
        assert_eq!(text_record.text(), "Hello");

        let icon_record = DialogItemRecord {
            item_offset: 0,
            item_type: DIALOG_ITEM_ICON,
            rect: (0, 0, 32, 32),
            handle: 0,
            payload: vec![0x00, 0x80],
        };
        assert!(!icon_record.has_text_or_title());
        assert_eq!(icon_record.text_payload(), None);
        assert_eq!(icon_record.text(), "");

        // Control procIDs
        assert_eq!(dialog_item_control_proc_id(DIALOG_ITEM_BUTTON), Some(0));
        assert_eq!(
            dialog_item_control_proc_id(DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG),
            Some(0)
        );
        assert_eq!(dialog_item_control_proc_id(DIALOG_ITEM_CHECKBOX), Some(1));
        assert_eq!(dialog_item_control_proc_id(DIALOG_ITEM_RADIO), Some(2));
        assert_eq!(dialog_item_control_proc_id(DIALOG_ITEM_STATIC_TEXT), None);
        assert_eq!(dialog_item_control_proc_id(DIALOG_ITEM_ICON), None);
    }

    #[test]
    fn dialog_item_resource_mapping_and_geometry() {
        // Classification
        assert!(is_dialog_item_resource(DIALOG_ITEM_RESOURCE_CONTROL));
        assert!(is_dialog_item_resource(DIALOG_ITEM_ICON));
        assert!(is_dialog_item_resource(DIALOG_ITEM_PICTURE));
        assert!(is_dialog_item_resource(
            DIALOG_ITEM_RESOURCE_CONTROL | DIALOG_ITEM_DISABLED_FLAG
        ));
        assert!(is_dialog_item_resource(
            DIALOG_ITEM_ICON | DIALOG_ITEM_DISABLED_FLAG
        ));
        assert!(is_dialog_item_resource(
            DIALOG_ITEM_PICTURE | DIALOG_ITEM_DISABLED_FLAG
        ));

        assert!(!is_dialog_item_resource(DIALOG_ITEM_USER_ITEM));
        assert!(!is_dialog_item_resource(DIALOG_ITEM_BUTTON));
        assert!(!is_dialog_item_resource(DIALOG_ITEM_CHECKBOX));
        assert!(!is_dialog_item_resource(DIALOG_ITEM_RADIO));
        assert!(!is_dialog_item_resource(DIALOG_ITEM_STATIC_TEXT));
        assert!(!is_dialog_item_resource(DIALOG_ITEM_EDIT_TEXT));
        assert!(!is_dialog_item_resource(99));

        // Resource type 4-character codes
        assert_eq!(
            dialog_item_resource_type(DIALOG_ITEM_RESOURCE_CONTROL),
            Some(*b"CNTL")
        );
        assert_eq!(
            dialog_item_resource_type(DIALOG_ITEM_RESOURCE_CONTROL | DIALOG_ITEM_DISABLED_FLAG),
            Some(*b"CNTL")
        );
        assert_eq!(dialog_item_resource_type(DIALOG_ITEM_ICON), Some(*b"ICON"));
        assert_eq!(
            dialog_item_resource_type(DIALOG_ITEM_ICON | DIALOG_ITEM_DISABLED_FLAG),
            Some(*b"ICON")
        );
        assert_eq!(
            dialog_item_resource_type(DIALOG_ITEM_PICTURE),
            Some(*b"PICT")
        );
        assert_eq!(
            dialog_item_resource_type(DIALOG_ITEM_PICTURE | DIALOG_ITEM_DISABLED_FLAG),
            Some(*b"PICT")
        );
        assert_eq!(dialog_item_resource_type(DIALOG_ITEM_STATIC_TEXT), None);
        assert_eq!(dialog_item_resource_type(DIALOG_ITEM_BUTTON), None);

        // Resource type as u32
        assert_eq!(
            dialog_item_resource_type_u32(DIALOG_ITEM_RESOURCE_CONTROL),
            Some(u32::from_be_bytes(*b"CNTL"))
        );
        assert_eq!(
            dialog_item_resource_type_u32(DIALOG_ITEM_ICON),
            Some(u32::from_be_bytes(*b"ICON"))
        );
        assert_eq!(
            dialog_item_resource_type_u32(DIALOG_ITEM_PICTURE),
            Some(u32::from_be_bytes(*b"PICT"))
        );
        assert_eq!(
            dialog_item_resource_type_u32(DIALOG_ITEM_STATIC_TEXT),
            None
        );

        // DialogItemRecord resource queries and guarded ID decoding
        let res_control_record = DialogItemRecord {
            item_offset: 0,
            item_type: DIALOG_ITEM_RESOURCE_CONTROL,
            rect: (10, 10, 30, 80),
            handle: 0,
            payload: 128i16.to_be_bytes().to_vec(),
        };
        assert!(res_control_record.is_resource());
        assert_eq!(res_control_record.resource_type(), Some(*b"CNTL"));
        assert_eq!(
            res_control_record.resource_type_u32(),
            Some(u32::from_be_bytes(*b"CNTL"))
        );
        assert_eq!(res_control_record.resource_id(), Some(128));

        let icon_record = DialogItemRecord {
            item_offset: 16,
            item_type: DIALOG_ITEM_ICON | DIALOG_ITEM_DISABLED_FLAG,
            rect: (20, 20, 52, 52),
            handle: 0,
            payload: (-42i16).to_be_bytes().to_vec(),
        };
        assert!(icon_record.is_resource());
        assert_eq!(icon_record.resource_type(), Some(*b"ICON"));
        assert_eq!(
            icon_record.resource_type_u32(),
            Some(u32::from_be_bytes(*b"ICON"))
        );
        assert_eq!(icon_record.resource_id(), Some(-42));

        let pict_record = DialogItemRecord {
            item_offset: 32,
            item_type: DIALOG_ITEM_PICTURE,
            rect: (0, 0, 100, 100),
            handle: 0,
            payload: 1024i16.to_be_bytes().to_vec(),
        };
        assert!(pict_record.is_resource());
        assert_eq!(pict_record.resource_type(), Some(*b"PICT"));
        assert_eq!(
            pict_record.resource_type_u32(),
            Some(u32::from_be_bytes(*b"PICT"))
        );
        assert_eq!(pict_record.resource_id(), Some(1024));

        // Short payload on resource item returns None
        let short_icon_record = DialogItemRecord {
            item_offset: 48,
            item_type: DIALOG_ITEM_ICON,
            rect: (0, 0, 32, 32),
            handle: 0,
            payload: vec![1],
        };
        assert!(short_icon_record.is_resource());
        assert_eq!(short_icon_record.resource_id(), None);

        // Text item with 2+ bytes must NOT return a resource ID
        let text_record = DialogItemRecord {
            item_offset: 64,
            item_type: DIALOG_ITEM_STATIC_TEXT,
            rect: (0, 0, 16, 100),
            handle: 0,
            payload: b"OK".to_vec(),
        };
        assert!(!text_record.is_resource());
        assert_eq!(text_record.resource_type(), None);
        assert_eq!(text_record.resource_type_u32(), None);
        assert_eq!(text_record.resource_id(), None);

        // Icon geometry and centering
        assert_eq!(DIALOG_ICON_SIZE, 32);
        assert_eq!(DIALOG_SMALL_ICON_SIZE, 16);

        // Standard 32x32 in exactly 32x32 rect -> unchanged
        assert_eq!(
            dialog_standard_icon_rect((10, 20, 42, 52)),
            (10, 20, 42, 52)
        );
        // Centered within larger rect (40x50)
        assert_eq!(
            dialog_standard_icon_rect((0, 0, 40, 50)),
            (4, 9, 36, 41)
        );
        // Small icon (16x16) centered within 20x20 rect
        assert_eq!(
            dialog_icon_rect(
                (10, 10, 30, 30),
                DIALOG_SMALL_ICON_SIZE,
                DIALOG_SMALL_ICON_SIZE
            ),
            (12, 12, 28, 28)
        );
    }

    #[test]
    fn dialog_selection_normalization_and_alert_helpers() {
        // Select all special cases: (0, -1) and (0, 32767)
        assert_eq!(normalize_dialog_item_selection(0, -1, 10), (0, 10));
        assert_eq!(normalize_dialog_item_selection(0, i16::MAX, 10), (0, 10));
        assert_eq!(normalize_dialog_item_selection(0, -1, 0), (0, 0));

        // Normal in-bounds range
        assert_eq!(normalize_dialog_item_selection(2, 5, 10), (2, 5));
        assert_eq!(normalize_dialog_item_selection(0, 0, 10), (0, 0));
        assert_eq!(normalize_dialog_item_selection(10, 10, 10), (10, 10));

        // Clamping out-of-bounds
        assert_eq!(normalize_dialog_item_selection(-5, 20, 10), (0, 10));
        assert_eq!(normalize_dialog_item_selection(15, 20, 10), (10, 10));

        // Reversed bounds swapping
        assert_eq!(normalize_dialog_item_selection(7, 3, 10), (3, 7));
        assert_eq!(normalize_dialog_item_selection(12, -2, 10), (0, 10));

        // Alert icon IDs
        assert_eq!(alert_icon_id(ALERT_TYPE_STOP), Some(0));
        assert_eq!(alert_icon_id(ALERT_TYPE_NOTE), Some(1));
        assert_eq!(alert_icon_id(ALERT_TYPE_CAUTION), Some(2));
        assert_eq!(alert_icon_id(ALERT_TYPE_PLAIN), None);
        assert_eq!(alert_icon_id(999), None);

        // Standard alert buttons
        assert_eq!(ALERT_BUTTON_OK, 1);
        assert_eq!(ALERT_BUTTON_CANCEL, 2);
        assert_eq!(ALERT_BUTTON_OTHER, 3);
        assert_eq!(ALERT_BUTTON_HELP, 4);

        // Next alert stage capped at 3
        assert_eq!(next_alert_stage(0), 1);
        assert_eq!(next_alert_stage(1), 2);
        assert_eq!(next_alert_stage(2), 3);
        assert_eq!(next_alert_stage(3), 3);
        assert_eq!(next_alert_stage(10), 3);

        // Disposal classification predicates
        assert!(is_dialog_item_disposable_text(DIALOG_ITEM_STATIC_TEXT));
        assert!(is_dialog_item_disposable_text(DIALOG_ITEM_EDIT_TEXT));
        assert!(is_dialog_item_disposable_text(
            DIALOG_ITEM_EDIT_TEXT | DIALOG_ITEM_DISABLED_FLAG
        ));
        assert!(!is_dialog_item_disposable_text(DIALOG_ITEM_BUTTON));
        assert!(!is_dialog_item_disposable_text(DIALOG_ITEM_ICON));

        assert!(is_dialog_item_disposable_control(DIALOG_ITEM_BUTTON));
        assert!(is_dialog_item_disposable_control(DIALOG_ITEM_CHECKBOX));
        assert!(is_dialog_item_disposable_control(DIALOG_ITEM_RADIO));
        assert!(is_dialog_item_disposable_control(
            DIALOG_ITEM_RESOURCE_CONTROL
        ));
        assert!(is_dialog_item_disposable_control(
            DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG
        ));
        assert!(!is_dialog_item_disposable_control(DIALOG_ITEM_STATIC_TEXT));
        assert!(!is_dialog_item_disposable_control(DIALOG_ITEM_ICON));
    }

    #[test]
    fn dialog_dispatch_button_geometry_and_cancel_detection() {
        // DialogRecord chrome and window kind
        assert_eq!(DIALOG_WINDOW_KIND_OFFSET, 108);
        assert_eq!(DIALOG_WINDOW_KIND, 2);
        assert_eq!(DIALOG_GO_AWAY_FLAG_OFFSET, 112);

        // DialogDispatch selectors
        assert_eq!(DIALOG_DISPATCH_NEW_COLOR_DIALOG, 0x0000);
        assert_eq!(DIALOG_DISPATCH_GET_STD_FILTER_PROC, 0x0003);
        assert_eq!(DIALOG_DISPATCH_SET_DIALOG_DEFAULT_ITEM, 0x0004);
        assert_eq!(DIALOG_DISPATCH_SET_DIALOG_CANCEL_ITEM, 0x0005);
        assert_eq!(DIALOG_DISPATCH_SET_DIALOG_TRACKS_CURSOR, 0x0006);
        assert_eq!(DIALOG_DISPATCH_NEW_FEATURES_DIALOG, 0x000C);

        // Default button outline geometry
        assert_eq!(DEFAULT_BUTTON_OUTLINE_THICKNESS, 3);
        assert_eq!(DEFAULT_BUTTON_OUTLINE_INSET, 4);

        let button_rect = (50, 100, 70, 160);
        let (outer, oval) = default_button_outline_geometry(button_rect);
        assert_eq!(outer, (46, 96, 74, 164));
        // height = 74 - 46 = 28; oval = max(4, 28/2 - 4) = 10
        assert_eq!(oval, 10);

        // Cancel button title predicates
        assert!(is_dialog_cancel_button_title(b"Cancel"));
        assert!(is_dialog_cancel_button_title(b"cancel"));
        assert!(is_dialog_cancel_button_title(b"CANCEL"));
        assert!(!is_dialog_cancel_button_title(b"OK"));
        assert!(!is_dialog_cancel_button_title(b""));

        assert!(is_dialog_cancel_button_title_str("Cancel"));
        assert!(is_dialog_cancel_button_title_str("cancel"));
        assert!(!is_dialog_cancel_button_title_str("Dismiss"));

        // Cancel item search across items
        let items: Vec<(u8, &str)> = vec![
            (DIALOG_ITEM_BUTTON, "OK"),
            (DIALOG_ITEM_BUTTON, "Cancel"),
            (DIALOG_ITEM_STATIC_TEXT, "Cancel"),
        ];
        assert_eq!(
            find_dialog_cancel_item_index(items.iter().copied()),
            Some(2)
        );

        // Disabled cancel button is ignored
        let items_disabled: Vec<(u8, &str)> = vec![
            (DIALOG_ITEM_BUTTON, "OK"),
            (DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG, "Cancel"),
        ];
        assert_eq!(
            find_dialog_cancel_item_index(items_disabled.iter().copied()),
            None
        );

        // No cancel button present
        let items_no_cancel: Vec<(u8, &str)> =
            vec![(DIALOG_ITEM_BUTTON, "OK"), (DIALOG_ITEM_BUTTON, "Help")];
        assert_eq!(
            find_dialog_cancel_item_index(items_no_cancel.iter().copied()),
            None
        );

        // resolve_dialog_cancel_item
        assert_eq!(
            resolve_dialog_cancel_item(Some(3), items.iter().copied()),
            3
        );
        assert_eq!(
            resolve_dialog_cancel_item(Some(0), items.iter().copied()),
            2
        );
        assert_eq!(
            resolve_dialog_cancel_item(None, items.iter().copied()),
            2
        );
        assert_eq!(
            resolve_dialog_cancel_item(None, items_no_cancel.iter().copied()),
            0
        );

        // resolve_modal_dialog_cancel_item
        assert_eq!(
            resolve_modal_dialog_cancel_item(Some(4), items.iter().copied()),
            4
        );
        assert_eq!(
            resolve_modal_dialog_cancel_item(None, items.iter().copied()),
            2
        );
        assert_eq!(
            resolve_modal_dialog_cancel_item(None, items_no_cancel.iter().copied()),
            ALERT_BUTTON_CANCEL
        );

        // resolve_dialog_default_item
        assert_eq!(resolve_dialog_default_item(Some(3), 5), 3);
        assert_eq!(resolve_dialog_default_item(Some(0), 5), 1);
        assert_eq!(resolve_dialog_default_item(None, 5), 1);
        assert_eq!(resolve_dialog_default_item(None, 0), 0);

        // is_dialog_default_button & is_dialog_cancel_button
        assert!(is_dialog_default_button(1, 1));
        assert!(!is_dialog_default_button(2, 1));
        assert!(!is_dialog_default_button(0, 0));
        assert!(!is_dialog_default_button(-1, -1));

        assert!(is_dialog_cancel_button(2, 2));
        assert!(!is_dialog_cancel_button(1, 2));
        assert!(!is_dialog_cancel_button(0, 0));
        assert!(!is_dialog_cancel_button(-1, -1));
    }

    #[test]
    fn append_and_shorten_ditl_operations_and_game_managed_check() {
        // AppendDITL constants
        assert_eq!(APPEND_DITL_OVERLAY, 0);
        assert_eq!(APPEND_DITL_RIGHT, 1);
        assert_eq!(APPEND_DITL_BOTTOM, 2);

        // append_ditl_offset_delta tests
        let height = 200;
        let width = 300;
        let item_origins = [(20, 30), (50, 60)];

        assert_eq!(
            append_ditl_offset_delta(APPEND_DITL_OVERLAY, height, width, |_| None),
            (0, 0)
        );
        assert_eq!(
            append_ditl_offset_delta(APPEND_DITL_RIGHT, height, width, |_| None),
            (0, 300)
        );
        assert_eq!(
            append_ditl_offset_delta(APPEND_DITL_BOTTOM, height, width, |_| None),
            (200, 0)
        );
        assert_eq!(
            append_ditl_offset_delta(-1, height, width, |idx| item_origins.get(idx - 1).copied()),
            (20, 30)
        );
        assert_eq!(
            append_ditl_offset_delta(-2, height, width, |idx| item_origins.get(idx - 1).copied()),
            (50, 60)
        );
        assert_eq!(
            append_ditl_offset_delta(-3, height, width, |idx| item_origins.get(idx - 1).copied()),
            (0, 0)
        );

        // shorten_ditl_counts tests
        assert_eq!(shorten_ditl_counts(10, 3), (7, 6));
        assert_eq!(shorten_ditl_counts(5, 5), (0, -1));
        assert_eq!(shorten_ditl_counts(5, 10), (0, -1));
        assert_eq!(shorten_ditl_counts(0, 2), (0, -1));

        // rects_intersect tests
        let r1 = (10, 10, 50, 50);
        let r2 = (20, 20, 60, 60);
        let r3 = (60, 60, 100, 100);
        let r4 = (50, 50, 100, 100);
        assert!(rects_intersect(r1, r2));
        assert!(!rects_intersect(r1, r3));
        assert!(!rects_intersect(r1, r4)); // Touching edge only

        // dialog_item_intersects_bounds tests
        let bounds = (100, 100, 300, 400);
        assert!(dialog_item_intersects_bounds(bounds, (10, 10, 50, 50)));
        assert!(!dialog_item_intersects_bounds(bounds, (300, 10, 350, 50)));

        // is_dialog_game_managed tests
        let all_user = vec![
            (DIALOG_ITEM_USER_ITEM, (10, 10, 50, 50)),
            (DIALOG_ITEM_USER_ITEM, (60, 60, 100, 100)),
        ];
        assert!(is_dialog_game_managed(bounds, all_user));

        let with_button = vec![
            (DIALOG_ITEM_USER_ITEM, (10, 10, 50, 50)),
            (DIALOG_ITEM_BUTTON, (60, 60, 100, 100)),
        ];
        assert!(!is_dialog_game_managed(bounds, with_button));

        let button_offscreen = vec![
            (DIALOG_ITEM_USER_ITEM, (10, 10, 50, 50)),
            (DIALOG_ITEM_BUTTON, (300, 300, 350, 350)),
        ];
        assert!(is_dialog_game_managed(bounds, button_offscreen));

        let empty: Vec<(u8, (i16, i16, i16, i16))> = vec![];
        assert!(!is_dialog_game_managed(bounds, empty));
    }

    #[test]
    fn dialog_event_classification_and_textedit_key_processing() {
        let dialog = 0x2000;
        let bounds = (50, 50, 200, 300);

        // is_dialog_event tests
        // None target dialog -> always false
        assert!(!is_dialog_event(
            EVENT_UPDATE,
            dialog,
            0,
            0,
            None,
            Some(bounds)
        ));
        assert!(!is_dialog_event(
            EVENT_MOUSE_DOWN,
            0,
            100,
            100,
            None,
            Some(bounds)
        ));

        // updateEvt (6) & activateEvt (8) -> match message == dialog
        assert!(is_dialog_event(
            EVENT_UPDATE,
            dialog,
            0,
            0,
            Some(dialog),
            Some(bounds)
        ));
        assert!(!is_dialog_event(
            EVENT_UPDATE,
            0x9999,
            0,
            0,
            Some(dialog),
            Some(bounds)
        ));
        assert!(is_dialog_event(
            EVENT_ACTIVATE,
            dialog,
            0,
            0,
            Some(dialog),
            Some(bounds)
        ));
        assert!(!is_dialog_event(
            EVENT_ACTIVATE,
            0x1111,
            0,
            0,
            Some(dialog),
            Some(bounds)
        ));

        // mouseDown (1) -> within bounds
        assert!(is_dialog_event(
            EVENT_MOUSE_DOWN,
            0,
            100,
            100,
            Some(dialog),
            Some(bounds)
        ));
        assert!(!is_dialog_event(
            EVENT_MOUSE_DOWN,
            0,
            10,
            10,
            Some(dialog),
            Some(bounds)
        ));
        assert!(!is_dialog_event(
            EVENT_MOUSE_DOWN,
            0,
            100,
            100,
            Some(dialog),
            None
        ));

        // other events (keyDown, autoKey, null, etc.) -> true if target dialog present
        assert!(is_dialog_event(
            EVENT_KEY_DOWN,
            b'a' as u32,
            0,
            0,
            Some(dialog),
            Some(bounds)
        ));
        assert!(is_dialog_event(
            EVENT_AUTO_KEY,
            b'a' as u32,
            0,
            0,
            Some(dialog),
            Some(bounds)
        ));
        assert!(is_dialog_event(
            EVENT_NULL,
            0,
            0,
            0,
            Some(dialog),
            Some(bounds)
        ));

        // is_dialog_edit_text_character tests
        assert!(is_dialog_edit_text_character(0x08)); // backspace
        assert!(is_dialog_edit_text_character(b' ')); // space (0x20)
        assert!(is_dialog_edit_text_character(b'A'));
        assert!(is_dialog_edit_text_character(b'~')); // 0x7E
        assert!(!is_dialog_edit_text_character(0x00)); // null
        assert!(!is_dialog_edit_text_character(0x0D)); // CR
        assert!(!is_dialog_edit_text_character(0x1B)); // ESC
        assert!(!is_dialog_edit_text_character(0x7F)); // DEL
        assert!(!is_dialog_edit_text_character(0x80));

        // textedit_key_result tests
        let initial = b"Hello World";
        // Insertion at caret (index 5)
        let (res, caret) = textedit_key_result(initial, 5, 5, b',');
        assert_eq!(res, b"Hello, World");
        assert_eq!(caret, 6);

        // Insertion replacing range [5, 11) (" World")
        let (res, caret) = textedit_key_result(initial, 5, 11, b'!');
        assert_eq!(res, b"Hello!");
        assert_eq!(caret, 6);

        // Insertion with reversed endpoints [11, 5)
        let (res, caret) = textedit_key_result(initial, 11, 5, b'!');
        assert_eq!(res, b"Hello!");
        assert_eq!(caret, 6);

        // Backspace at caret > 0
        let (res, caret) = textedit_key_result(initial, 5, 5, 0x08);
        assert_eq!(res, b"Hell World");
        assert_eq!(caret, 4);

        // Backspace deleting selection range [0, 5) ("Hello")
        let (res, caret) = textedit_key_result(initial, 0, 5, 0x08);
        assert_eq!(res, b" World");
        assert_eq!(caret, 0);

        // Backspace at caret 0 (noop)
        let (res, caret) = textedit_key_result(initial, 0, 0, 0x08);
        assert_eq!(res, b"Hello World");
        assert_eq!(caret, 0);
    }

    #[test]
    fn dialog_target_routing_and_frame_geometry() {
        // Target resolution for events
        let front = Some(0x1000);
        let dialog_window = 0x2000;
        let other_window = 0x3000;
        let is_dialog = |ptr| ptr == dialog_window;

        // Update events route to message only if it is a dialog
        assert_eq!(
            dialog_target_for_event(EVENT_UPDATE, dialog_window, is_dialog, front),
            Some(dialog_window)
        );
        assert_eq!(
            dialog_target_for_event(EVENT_UPDATE, other_window, is_dialog, front),
            None
        );

        // Activate events route to message only if it is a dialog
        assert_eq!(
            dialog_target_for_event(EVENT_ACTIVATE, dialog_window, is_dialog, front),
            Some(dialog_window)
        );
        assert_eq!(
            dialog_target_for_event(EVENT_ACTIVATE, other_window, is_dialog, front),
            None
        );

        // Mouse, key, and other events route to front dialog regardless of message
        assert_eq!(
            dialog_target_for_event(EVENT_MOUSE_DOWN, other_window, is_dialog, front),
            front
        );
        assert_eq!(
            dialog_target_for_event(EVENT_KEY_DOWN, other_window, is_dialog, front),
            front
        );
        assert_eq!(
            dialog_target_for_event(EVENT_AUTO_KEY, other_window, is_dialog, front),
            front
        );
        assert_eq!(
            dialog_target_for_event(EVENT_NULL, other_window, is_dialog, front),
            front
        );

        // Inset and outset math
        let base = (10, 20, 100, 200);
        assert_eq!(inset_rect(base, 2, 5), (12, 25, 98, 195));
        assert_eq!(outset_rect(base, 3, 4), (7, 16, 103, 204));

        // Modal dialog dBoxProc frame rect: 8px margin
        assert_eq!(
            dialog_dbox_frame_rect((50, 60, 150, 260)),
            (42, 52, 158, 268)
        );

        // Edit text frame rect: 3px outset
        assert_eq!(edit_text_frame_rect((10, 20, 30, 80)), (7, 17, 33, 83));

        // Dialog text rect: 1px left inset
        assert_eq!(dialog_text_rect((10, 20, 30, 80)), (10, 21, 30, 80));

        // Dialog item base type stripping 0x80
        assert_eq!(
            dialog_item_base_type(DIALOG_ITEM_USER_ITEM),
            DIALOG_ITEM_USER_ITEM
        );
        assert_eq!(
            dialog_item_base_type(DIALOG_ITEM_BUTTON),
            DIALOG_ITEM_BUTTON
        );
        assert_eq!(
            dialog_item_base_type(DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG),
            DIALOG_ITEM_BUTTON
        );
        assert_eq!(
            dialog_item_base_type(DIALOG_ITEM_EDIT_TEXT | DIALOG_ITEM_DISABLED_FLAG),
            DIALOG_ITEM_EDIT_TEXT
        );
        assert_eq!(
            dialog_item_base_type(DIALOG_ITEM_PICTURE | DIALOG_ITEM_DISABLED_FLAG),
            DIALOG_ITEM_PICTURE
        );
    }

    #[test]
    fn dialog_record_initial_state_and_offsets() {
        assert_eq!(DIALOG_INITIAL_EDIT_FIELD, -1);
        assert_eq!(DIALOG_INITIAL_EDIT_FIELD as u16, 0xFFFF);
        assert_eq!(DIALOG_INITIAL_EDIT_OPEN, 0);
        assert_eq!(DIALOG_INITIAL_DEFAULT_ITEM, 1);
        assert_eq!(DIALOG_ITEMS_OFFSET, 156);
        assert_eq!(DIALOG_TEXT_HANDLE_OFFSET, 160);
        assert_eq!(DIALOG_EDIT_FIELD_OFFSET, 164);
        assert_eq!(DIALOG_EDIT_OPEN_OFFSET, 166);
        assert_eq!(DIALOG_DEFAULT_ITEM_OFFSET, 168);
        assert_eq!(DIALOG_RESOURCE_ID_OFFSET, 170);
        assert_eq!(DIALOG_CANCEL_ITEM_OFFSET, 172);
        assert_eq!(DIALOG_ALERT_HIT_OFFSET, 174);
        assert_eq!(DIALOG_STANDARD_ALERT_OUTPUT_OFFSET, 176);
        assert_eq!(DIALOG_STANDARD_ALERT_STACK_OFFSET, 180);
        assert_eq!(DIALOG_RECORD_SIZE, 256);
    }

    #[test]
    fn dialog_item_disabled_and_enabled_predicates() {
        assert!(is_dialog_item_enabled(DIALOG_ITEM_BUTTON));
        assert!(is_dialog_item_enabled(DIALOG_ITEM_EDIT_TEXT));
        assert!(is_dialog_item_enabled(DIALOG_ITEM_USER_ITEM));
        assert!(!is_dialog_item_disabled(DIALOG_ITEM_BUTTON));
        assert!(!is_dialog_item_disabled(DIALOG_ITEM_EDIT_TEXT));

        let disabled_btn = DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG;
        assert!(is_dialog_item_disabled(disabled_btn));
        assert!(!is_dialog_item_enabled(disabled_btn));

        let disabled_text = DIALOG_ITEM_STATIC_TEXT | DIALOG_ITEM_DISABLED_FLAG;
        assert!(is_dialog_item_disabled(disabled_text));
        assert!(!is_dialog_item_enabled(disabled_text));

        let record_enabled = DialogItemRecord {
            item_offset: 0,
            item_type: DIALOG_ITEM_BUTTON,
            rect: (10, 10, 30, 80),
            handle: 0,
            payload: vec![],
        };
        assert!(record_enabled.is_enabled());
        assert!(!record_enabled.is_disabled());

        let record_disabled = DialogItemRecord {
            item_offset: 0,
            item_type: disabled_btn,
            rect: (10, 10, 30, 80),
            handle: 0,
            payload: vec![],
        };
        assert!(record_disabled.is_disabled());
        assert!(!record_disabled.is_enabled());
    }

    #[test]
    fn dialog_point_conversions_and_bounds() {
        let bounds = (50, 100, 250, 300);
        let screen_pt = (75, 160);
        let local_pt = global_to_dialog_local_point(bounds, screen_pt.0, screen_pt.1);
        assert_eq!(local_pt, (25, 60));

        let converted_back = dialog_local_to_global_point(bounds, local_pt.0, local_pt.1);
        assert_eq!(converted_back, screen_pt);

        assert_eq!(
            global_to_dialog_local_point((100, 100, 200, 200), i16::MIN, i16::MIN),
            (i16::MIN, i16::MIN)
        );
        assert_eq!(
            dialog_local_to_global_point((100, 100, 200, 200), i16::MAX, i16::MAX),
            (i16::MAX, i16::MAX)
        );
    }

    #[test]
    fn dialog_item_hit_testing() {
        assert_eq!(find_dialog_item_hit([], 10, 10, false, |_| true), None);

        let items = [
            // Item 0: disabled static text at (10, 10, 50, 100)
            (
                (10, 10, 50, 100),
                DIALOG_ITEM_STATIC_TEXT | DIALOG_ITEM_DISABLED_FLAG,
            ),
            // Item 1: enabled button at (20, 20, 40, 80)
            ((20, 20, 40, 80), DIALOG_ITEM_BUTTON),
            // Item 2: enabled resource control at (60, 10, 90, 100)
            ((60, 10, 90, 100), DIALOG_ITEM_RESOURCE_CONTROL),
        ];

        // Unfiltered (FindDItem semantics): disabled item 0 wins at (25, 25)
        assert_eq!(
            find_dialog_item_hit(items, 25, 25, false, |_| true),
            Some(0)
        );

        // Filtered enabled-only (DialogSelect / mouse tracking semantics):
        // disabled item 0 is skipped, hitting enabled button item 1!
        assert_eq!(find_dialog_item_hit(items, 25, 25, true, |_| true), Some(1));

        // Point outside all items
        assert_eq!(find_dialog_item_hit(items, 5, 5, true, |_| true), None);

        // Control part filtering: control at index 2 queried
        assert_eq!(
            find_dialog_item_hit(items, 70, 50, true, |_idx| false),
            None
        );
        assert_eq!(
            find_dialog_item_hit(items, 70, 50, true, |idx| idx == 2),
            Some(2)
        );

        // find_dialog_item_at_global_point coordinates test
        let dialog_bounds = (100, 200, 300, 400);
        assert_eq!(
            find_dialog_item_at_global_point(dialog_bounds, 125, 225, items, true, |_| true,),
            Some(1)
        );
    }

    #[test]
    fn normalize_selection_bounds_behavior() {
        assert_eq!(normalize_selection_bounds(2, 5, 10), (2, 5));
        assert_eq!(normalize_selection_bounds(5, 2, 10), (2, 5));
        assert_eq!(normalize_selection_bounds(0, 0, 10), (0, 0));
        assert_eq!(normalize_selection_bounds(10, 10, 10), (10, 10));
        assert_eq!(normalize_selection_bounds(5, 20, 10), (5, 10));
        assert_eq!(normalize_selection_bounds(25, 30, 10), (10, 10));
        assert_eq!(normalize_selection_bounds(30, 5, 10), (5, 10));
    }

    #[test]
    fn item_kind_predicates_and_record_methods() {
        let test_cases: [(
            u8,
            DialogItemKind,
            bool,
            bool,
            bool,
            bool,
            bool,
            bool,
            bool,
            bool,
            bool,
            bool,
            bool,
        ); 9] = [
            // (raw, kind, is_user, is_btn, is_chk, is_rad, is_res_ctrl, is_ctrl, is_stat, is_edit, is_text, is_icon, is_pict)
            (
                DIALOG_ITEM_USER_ITEM,
                DialogItemKind::UserItem,
                true,
                false,
                false,
                false,
                false,
                false,
                false,
                false,
                false,
                false,
                false,
            ),
            (
                DIALOG_ITEM_BUTTON,
                DialogItemKind::Button,
                false,
                true,
                false,
                false,
                false,
                true,
                false,
                false,
                false,
                false,
                false,
            ),
            (
                DIALOG_ITEM_CHECKBOX,
                DialogItemKind::Checkbox,
                false,
                false,
                true,
                false,
                false,
                true,
                false,
                false,
                false,
                false,
                false,
            ),
            (
                DIALOG_ITEM_RADIO,
                DialogItemKind::RadioButton,
                false,
                false,
                false,
                true,
                false,
                true,
                false,
                false,
                false,
                false,
                false,
            ),
            (
                DIALOG_ITEM_RESOURCE_CONTROL,
                DialogItemKind::ResourceControl,
                false,
                false,
                false,
                false,
                true,
                true,
                false,
                false,
                false,
                false,
                false,
            ),
            (
                DIALOG_ITEM_STATIC_TEXT,
                DialogItemKind::StaticText,
                false,
                false,
                false,
                false,
                false,
                false,
                true,
                false,
                true,
                false,
                false,
            ),
            (
                DIALOG_ITEM_EDIT_TEXT,
                DialogItemKind::EditText,
                false,
                false,
                false,
                false,
                false,
                false,
                false,
                true,
                true,
                false,
                false,
            ),
            (
                DIALOG_ITEM_ICON,
                DialogItemKind::Icon,
                false,
                false,
                false,
                false,
                false,
                false,
                false,
                false,
                false,
                true,
                false,
            ),
            (
                DIALOG_ITEM_PICTURE,
                DialogItemKind::Picture,
                false,
                false,
                false,
                false,
                false,
                false,
                false,
                false,
                false,
                false,
                true,
            ),
        ];

        for (
            raw,
            kind,
            is_user,
            is_btn,
            is_chk,
            is_rad,
            is_res_ctrl,
            is_ctrl,
            is_stat,
            is_edit,
            is_text,
            is_icon,
            is_pict,
        ) in test_cases
        {
            for flag in [0, DIALOG_ITEM_DISABLED_FLAG] {
                let r = raw | flag;
                assert_eq!(is_dialog_item_user_item(r), is_user);
                assert_eq!(is_dialog_item_button(r), is_btn);
                assert_eq!(is_dialog_item_checkbox(r), is_chk);
                assert_eq!(is_dialog_item_radio(r), is_rad);
                assert_eq!(is_dialog_item_resource_control(r), is_res_ctrl);
                assert_eq!(is_dialog_item_control(r), is_ctrl);
                assert_eq!(is_dialog_item_static_text(r), is_stat);
                assert_eq!(is_dialog_item_edit_text(r), is_edit);
                assert_eq!(is_dialog_item_text(r), is_text);
                assert_eq!(is_dialog_item_icon(r), is_icon);
                assert_eq!(is_dialog_item_picture(r), is_pict);

                let record = DialogItemRecord {
                    item_offset: 0,
                    item_type: r,
                    rect: (0, 0, 10, 10),
                    handle: 0,
                    payload: Vec::new(),
                };
                assert_eq!(record.is_user_item(), is_user);
                assert_eq!(record.is_button(), is_btn);
                assert_eq!(record.is_checkbox(), is_chk);
                assert_eq!(record.is_radio(), is_rad);
                assert_eq!(record.is_resource_control(), is_res_ctrl);
                assert_eq!(record.is_control(), is_ctrl);
                assert_eq!(record.is_static_text(), is_stat);
                assert_eq!(record.is_edit_text(), is_edit);
                assert_eq!(record.is_text(), is_text);
                assert_eq!(record.is_icon(), is_icon);
                assert_eq!(record.is_picture(), is_pict);
            }

            assert_eq!(kind.is_user_item(), is_user);
            assert_eq!(kind.is_button(), is_btn);
            assert_eq!(kind.is_checkbox(), is_chk);
            assert_eq!(kind.is_radio(), is_rad);
            assert_eq!(kind.is_resource_control(), is_res_ctrl);
            assert_eq!(kind.is_control(), is_ctrl);
            assert_eq!(kind.is_static_text(), is_stat);
            assert_eq!(kind.is_edit_text(), is_edit);
            assert_eq!(kind.is_text(), is_text);
            assert_eq!(kind.is_icon(), is_icon);
            assert_eq!(kind.is_picture(), is_pict);
        }
    }

    #[test]
    fn dialog_select_action_and_evaluation() {
        let dialog = 0x2000;
        let bounds = (10, 20, 110, 120);

        // Action properties
        let no_act = DialogSelectAction::NoAction;
        assert!(!no_act.is_handled());
        assert!(!no_act.should_set_dialog_ptr());
        assert_eq!(no_act.target_dialog(), None);
        assert_eq!(no_act.item_hit(), None);

        let update_act = DialogSelectAction::Update { dialog };
        assert!(!update_act.is_handled());
        assert!(update_act.should_set_dialog_ptr());
        assert_eq!(update_act.target_dialog(), Some(dialog));
        assert_eq!(update_act.item_hit(), None);

        let activate_act = DialogSelectAction::Activate { dialog };
        assert!(!activate_act.is_handled());
        assert!(activate_act.should_set_dialog_ptr());
        assert_eq!(activate_act.target_dialog(), Some(dialog));
        assert_eq!(activate_act.item_hit(), None);

        let idle_act = DialogSelectAction::Idle {
            dialog,
            edit_item: 1,
        };
        assert!(!idle_act.is_handled());
        assert!(!idle_act.should_set_dialog_ptr());
        assert_eq!(idle_act.target_dialog(), Some(dialog));
        assert_eq!(idle_act.item_hit(), None);

        let hit_act = DialogSelectAction::ItemHit {
            dialog,
            item_no: 3,
            is_edit_text: false,
            is_resource_control: false,
        };
        assert!(hit_act.is_handled());
        assert!(hit_act.should_set_dialog_ptr());
        assert_eq!(hit_act.target_dialog(), Some(dialog));
        assert_eq!(hit_act.item_hit(), Some(3));

        let dis_act = DialogSelectAction::DisabledItemHit {
            dialog,
            item_no: 4,
        };
        assert!(!dis_act.is_handled());
        assert!(!dis_act.should_set_dialog_ptr());
        assert_eq!(dis_act.target_dialog(), Some(dialog));
        assert_eq!(dis_act.item_hit(), None);

        let key_act = DialogSelectAction::KeyStroke {
            dialog,
            edit_item: 2,
            character: b'Z',
        };
        assert!(key_act.is_handled());
        assert!(key_act.should_set_dialog_ptr());
        assert_eq!(key_act.target_dialog(), Some(dialog));
        assert_eq!(key_act.item_hit(), Some(2));

        // evaluate_dialog_select: No target dialog
        assert_eq!(
            evaluate_dialog_select(
                EVENT_NULL,
                0,
                0,
                0,
                None,
                Some(bounds),
                None,
                |_, _| None,
            ),
            DialogSelectAction::NoAction
        );

        // evaluate_dialog_select: Update event
        assert_eq!(
            evaluate_dialog_select(
                EVENT_UPDATE,
                dialog,
                0,
                0,
                Some(dialog),
                Some(bounds),
                None,
                |_, _| None,
            ),
            DialogSelectAction::Update { dialog }
        );
        // Update for different window
        assert_eq!(
            evaluate_dialog_select(
                EVENT_UPDATE,
                0x9999,
                0,
                0,
                Some(dialog),
                Some(bounds),
                None,
                |_, _| None,
            ),
            DialogSelectAction::NoAction
        );

        // evaluate_dialog_select: Activate event
        assert_eq!(
            evaluate_dialog_select(
                EVENT_ACTIVATE,
                dialog,
                0,
                0,
                Some(dialog),
                Some(bounds),
                None,
                |_, _| None,
            ),
            DialogSelectAction::Activate { dialog }
        );

        // evaluate_dialog_select: Null event with active edit text
        assert_eq!(
            evaluate_dialog_select(
                EVENT_NULL,
                0,
                0,
                0,
                Some(dialog),
                Some(bounds),
                Some((2, DIALOG_ITEM_EDIT_TEXT)),
                |_, _| None,
            ),
            DialogSelectAction::Idle {
                dialog,
                edit_item: 2
            }
        );
        // Null event with active edit text disabled
        assert_eq!(
            evaluate_dialog_select(
                EVENT_NULL,
                0,
                0,
                0,
                Some(dialog),
                Some(bounds),
                Some((2, DIALOG_ITEM_EDIT_TEXT | DIALOG_ITEM_DISABLED_FLAG)),
                |_, _| None,
            ),
            DialogSelectAction::NoAction
        );
        // Null event with active non-edit text (e.g. button)
        assert_eq!(
            evaluate_dialog_select(
                EVENT_NULL,
                0,
                0,
                0,
                Some(dialog),
                Some(bounds),
                Some((1, DIALOG_ITEM_BUTTON)),
                |_, _| None,
            ),
            DialogSelectAction::NoAction
        );

        // evaluate_dialog_select: Mouse down
        // Mouse down outside bounds
        assert_eq!(
            evaluate_dialog_select(
                EVENT_MOUSE_DOWN,
                0,
                5,
                5,
                Some(dialog),
                Some(bounds),
                None,
                |_, _| Some((1, DIALOG_ITEM_BUTTON)),
            ),
            DialogSelectAction::NoAction
        );
        // Mouse down inside bounds, hitting enabled button
        assert_eq!(
            evaluate_dialog_select(
                EVENT_MOUSE_DOWN,
                0,
                50,
                50,
                Some(dialog),
                Some(bounds),
                None,
                |_, _| Some((1, DIALOG_ITEM_BUTTON)),
            ),
            DialogSelectAction::ItemHit {
                dialog,
                item_no: 1,
                is_edit_text: false,
                is_resource_control: false,
            }
        );
        // Mouse down inside bounds, hitting enabled edit text
        assert_eq!(
            evaluate_dialog_select(
                EVENT_MOUSE_DOWN,
                0,
                50,
                50,
                Some(dialog),
                Some(bounds),
                None,
                |_, _| Some((2, DIALOG_ITEM_EDIT_TEXT)),
            ),
            DialogSelectAction::ItemHit {
                dialog,
                item_no: 2,
                is_edit_text: true,
                is_resource_control: false,
            }
        );
        // Mouse down inside bounds, hitting enabled res control
        assert_eq!(
            evaluate_dialog_select(
                EVENT_MOUSE_DOWN,
                0,
                50,
                50,
                Some(dialog),
                Some(bounds),
                None,
                |_, _| Some((3, DIALOG_ITEM_RESOURCE_CONTROL)),
            ),
            DialogSelectAction::ItemHit {
                dialog,
                item_no: 3,
                is_edit_text: false,
                is_resource_control: true,
            }
        );
        // Mouse down inside bounds, hitting disabled item
        assert_eq!(
            evaluate_dialog_select(
                EVENT_MOUSE_DOWN,
                0,
                50,
                50,
                Some(dialog),
                Some(bounds),
                None,
                |_, _| Some((4, DIALOG_ITEM_BUTTON | DIALOG_ITEM_DISABLED_FLAG)),
            ),
            DialogSelectAction::DisabledItemHit { dialog, item_no: 4 }
        );
        // Mouse down inside bounds, no item hit
        assert_eq!(
            evaluate_dialog_select(
                EVENT_MOUSE_DOWN,
                0,
                50,
                50,
                Some(dialog),
                Some(bounds),
                None,
                |_, _| None,
            ),
            DialogSelectAction::NoAction
        );

        // evaluate_dialog_select: KeyDown / AutoKey
        assert_eq!(
            evaluate_dialog_select(
                EVENT_KEY_DOWN,
                b'A' as u32,
                0,
                0,
                Some(dialog),
                Some(bounds),
                Some((2, DIALOG_ITEM_EDIT_TEXT)),
                |_, _| None,
            ),
            DialogSelectAction::KeyStroke {
                dialog,
                edit_item: 2,
                character: b'A',
            }
        );
        assert_eq!(
            evaluate_dialog_select(
                EVENT_AUTO_KEY,
                0x08,
                0,
                0,
                Some(dialog),
                Some(bounds),
                Some((2, DIALOG_ITEM_EDIT_TEXT)),
                |_, _| None,
            ),
            DialogSelectAction::KeyStroke {
                dialog,
                edit_item: 2,
                character: 0x08,
            }
        );
        // KeyDown when no active edit text
        assert_eq!(
            evaluate_dialog_select(
                EVENT_KEY_DOWN,
                b'A' as u32,
                0,
                0,
                Some(dialog),
                Some(bounds),
                None,
                |_, _| None,
            ),
            DialogSelectAction::NoAction
        );
    }
}