systemless 0.30.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
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
/*
 * Toolbox Showcase: Classic Macintosh Fat-App Fixture.
 * Compiled unchanged for 68K and native PowerPC.
 *
 * Exercises standard Macintosh Toolbox subsystems:
 * - Window Manager & Event Manager (Macintosh Toolbox Essentials ch 2, 4)
 * - Menu Manager & Hierarchical Submenus (Macintosh Toolbox Essentials ch 3)
 * - List Manager, default text lists, selection, scrolling, and resizing
 *   (More Macintosh Toolbox ch 4)
 * - Resource Manager enumeration, named lookup, deferred loading, release,
 *   and reload behavior
 *   (Inside Macintosh: More Macintosh Toolbox ch 1)
 * - Styled TextEdit runs, Font Manager lookup, and text measurement
 *   (Inside Macintosh: Text ch 2, 3, and 4)
 * - Standard File Open/Save dialogs, file-type filtering, navigation,
 *   cancellation, editable names, and returned FSSpec/SFReply records
 *   (Inside Macintosh: Files ch 3)
 * - Control Manager & Standard CDEFs (Macintosh Toolbox Essentials ch 5)
 * - Dialog Manager & Alerts (Macintosh Toolbox Essentials ch 6)
 * - Sound Manager channels, sampled playback & command queues
 *   (Inside Macintosh: Sound ch 2)
 * - Palette Manager activation, indexed drawing & animation
 *   (Inside Macintosh Volume VI ch 20)
 * - QuickDraw Geometry, Arcs, Polygons, Regions, PICT, Icons & 3D Bevels
 *   (Imaging With QuickDraw ch 3, 4, 7, 8)
 */

#include <Controls.h>
#include <ControlDefinitions.h>
#include <Dialogs.h>
#include <Events.h>
#include <Files.h>
#include <Fonts.h>
#include <Memory.h>
#include <Menus.h>
#include <Lists.h>
#include <OSUtils.h>
#include <Palettes.h>
#include <QDOffscreen.h>
#include <Quickdraw.h>
#include <Resources.h>
#include <Sound.h>
#include <StandardFile.h>
#include <TextEdit.h>
#include <ToolUtils.h>
#include <Windows.h>

#if defined(__POWERPC__) || defined(powerc) || defined(PowerPC) || defined(__powerc)
#define SHOWCASE_TARGET_PPC 1
#endif

#ifdef SHOWCASE_TARGET_PPC
#include <QD3D.h>
#include <QD3DCamera.h>
#include <QD3DDrawContext.h>
#include <QD3DGeometry.h>
#include <QD3DGroup.h>
#include <QD3DLight.h>
#include <QD3DRenderer.h>
#include <QD3DShader.h>
#include <QD3DStyle.h>
#include <QD3DTransform.h>
#include <QD3DSet.h>
#endif

#define rMenuBar 128
#define rMainWindow 128
#define rPrefDialog 129
#define rAboutAlert 130
#define rShowcaseIcon 128
#define rShowcasePalette 150
#define rShowcaseSound 151

#define mApple 128
#define mPages 129
#define mState 130
#define mFile 131
#define mOptions 132

#define mDifficulty 140
#define mSoundMenu 141
#define mRendererMenu 142

/* Pages menu items */
#define iGraphics 1
#define iControls 2
#define iWindows 3
#define iDrawing 4
#define iPreferences 5
#define iDialogs 6
#define iTextEdit 7
#define iPalettes 8
#define iLists 9
#define iSound 10
#define iStyledText 11
#define iStandardFile 12
#define iResources 13
#define iSprites 14

/* State menu items */
#define iButtonState 1
#define iCheckboxState 2
#define iScrollbarState 3
#define iWindowState 4
#define iSoundState 5

/* Options menu items */
#define iOptDifficulty 1
#define iOptSound 2
#define iOptRenderer 3
#define iOptResetPrefs 5
#define iOptLaunchDialog 6

/* Difficulty submenu items */
#define iDiffEasy 1
#define iDiffNormal 2
#define iDiffHard 3

/* Sound submenu items */
#define iSndMute 1
#define iSndFXOnly 2
#define iSndMusicOnly 3
#define iSndFull 4

/* Renderer submenu items */
#define iRendFlat 1
#define iRendBevel 2
#define iRendContrast 3

/* File menu items */
#define iFilePrefs 1
#define iQuit 4

/* Apple menu items */
#define iAbout 1

/* Page indices */
#define pageGraphics 1
#define pageControls 2
#define pageWindows 3
#define pageDrawing 4
#define pagePreferences 5
#define pageDialogs 6
#define pageTextEdit 7
#define pagePalettes 8
#define pageLists 9
#define pageSound 10
#define pageStyledText 11
#define pageStandardFile 12
#define pageResources 13
#define pageSprites 14

#define kResourceBrowserRows 3
#define resourceStatusEnumerated 1
#define resourceStatusLoaded 2
#define resourceStatusReleased 3
#define resourceStatusError 4

#define kInventoryRowCount 12
#define listStatusNone 0
#define listStatusSelected 1
#define listStatusMutated 2
#define listStatusScrolled 3
#define listStatusResized 4
#define listStatusInactive 5
#define listStatusActivated 6

static QDGlobals qd;
static WindowPtr gMainWindow;
static WindowPtr gAuxWindow;

/* Page 2: Controls */
static ControlHandle gButton;
static ControlHandle gCheckbox;
static ControlHandle gScrollbar;

/* Page 5: Game Preferences Controls */
static ControlHandle gPrefSndFX;
static ControlHandle gPrefMusic;
static ControlHandle gPrefVolume;
static ControlHandle gPrefDiffEasy;
static ControlHandle gPrefDiffNormal;
static ControlHandle gPrefDiffHard;
static ControlHandle gPrefRendFlat;
static ControlHandle gPrefRendBevel;
static ControlHandle gPrefRendContrast;
static ControlHandle gPrefBtnApply;
static ControlHandle gPrefBtnReset;
static ControlHandle gPrefBtnModal;

/* Page 6: Dialogs Controls */
static ControlHandle gDlgBtnOpenPrefs;
static ControlHandle gDlgBtnOpenAlert;

/* Page 7: Palette Manager */
static ControlHandle gPaletteAnimate;
static PaletteHandle gShowcasePalette;
static PaletteHandle gOriginalPalette;
static Boolean gPaletteAnimated = false;

/* Page 8: TextEdit */
static TEHandle gTE;
static Rect gTERect;
static short gTEJust = teJustLeft;
static ControlHandle gTEJustLeft;
static ControlHandle gTEJustCenter;
static ControlHandle gTEJustRight;
static ControlHandle gTEBtnCut;
static ControlHandle gTEBtnCopy;
static ControlHandle gTEBtnPaste;
static ControlHandle gTEBtnReset;

/* Page 9: Lists & Inventory */
static ListHandle gInventoryList;
static Rect gInventoryView;
static ControlHandle gListInspect;
static ControlHandle gListMutate;
static ControlHandle gListScroll;
static ControlHandle gListResize;
static ControlHandle gListActivate;
static short gListStatus;
static short gListSelectedRow = -1;
static short gListSelectedLength;
static Boolean gListActive = true;
static Boolean gListResized = false;

/* Page 10: Sound Manager */
static SndChannelPtr gShowcaseSoundChannel;
static Handle gShowcaseSound;
static SndCallBackUPP gShowcaseSoundCallbackUPP;
static SCStatus gShowcaseSoundStatus;
static ControlHandle gSoundBtnBeep;
static ControlHandle gSoundBtnPlay;
static ControlHandle gSoundBtnQueue;
static ControlHandle gSoundBtnFlush;
static ControlHandle gSoundBtnQuiet;
static ControlHandle gSoundBtnComplete;
static ControlHandle gSoundBtnDispose;
static Boolean gSoundBeeped = false;
static Boolean gSoundStarted = false;
static Boolean gSoundQueued = false;
static Boolean gSoundFlushed = false;
static Boolean gSoundQuieted = false;
static volatile Boolean gSoundCompleted = false;
static Boolean gSoundCompletionPresented = false;
static Boolean gSoundDisposed = true;
static Boolean gSoundResourceLocked = false;
static OSErr gSoundLastError = noErr;
static OSErr gSoundStatusError = noErr;

static void SyncMenuState(void);
static MenuHandle StateMenu(void);
static void DrawMainWindow(void);

/*
 * Sound Manager callbacks run at interrupt time. Store the completion flag
 * address in the channel's application-owned userInfo field so the callback
 * does not need to dereference the application's A5 world. Sound (1994),
 * pp. 2-46--2-48 and 2-151--2-152.
 */
static pascal void ShowcaseSoundCallback(SndChannelPtr chan, SndCommand *cmd)
{
    (void)cmd;
    if (chan != nil && chan->userInfo != 0) {
        *((volatile Boolean *)chan->userInfo) = true;
    }
}

static void MakeShowcaseSoundCommand(SndCommand *cmd, short command, long param2)
{
    cmd->cmd = command;
    cmd->param1 = 0;
    cmd->param2 = param2;
}

static void EnsureShowcaseSoundChannel(void)
{
    if (gShowcaseSoundChannel != nil) return;
    if (gShowcaseSound == nil) {
        gShowcaseSound = GetResource('snd ', rShowcaseSound);
    }
    if (gShowcaseSound == nil) {
        gSoundLastError = resNotFound;
        return;
    }

    if (gShowcaseSoundCallbackUPP == nil) {
        gShowcaseSoundCallbackUPP = NewSndCallBackUPP(ShowcaseSoundCallback);
    }
    gSoundLastError = SndNewChannel(&gShowcaseSoundChannel, sampledSynth,
                                    initMono, gShowcaseSoundCallbackUPP);
    if (gSoundLastError == noErr && gShowcaseSoundChannel != nil) {
        gShowcaseSoundChannel->userInfo = (long)&gSoundCompleted;
        gSoundDisposed = false;
    } else if (gShowcaseSoundCallbackUPP != nil) {
        DisposeSndCallBackUPP(gShowcaseSoundCallbackUPP);
        gShowcaseSoundCallbackUPP = nil;
    }
}

static void ResetShowcaseSoundChannel(void)
{
    SndCommand cmd;

    if (gShowcaseSoundChannel == nil) return;
    MakeShowcaseSoundCommand(&cmd, quietCmd, 0);
    SndDoImmediate(gShowcaseSoundChannel, &cmd);
    MakeShowcaseSoundCommand(&cmd, flushCmd, 0);
    SndDoImmediate(gShowcaseSoundChannel, &cmd);
}

static void PlayShowcaseSound(Boolean queueCompletion)
{
    SndCommand cmd;
    Boolean lockedHere;

    EnsureShowcaseSoundChannel();
    if (gShowcaseSoundChannel == nil || gShowcaseSound == nil) return;

    ResetShowcaseSoundChannel();
    gSoundStarted = false;
    gSoundQueued = false;
    gSoundFlushed = false;
    gSoundQuieted = false;
    gSoundCompleted = false;
    gSoundCompletionPresented = false;
    gSoundDisposed = false;
    SyncMenuState();

    lockedHere = false;
    if (!gSoundResourceLocked) {
        HLock(gShowcaseSound);
        gSoundResourceLocked = true;
        lockedHere = true;
    }
    gSoundLastError = SndPlay(gShowcaseSoundChannel,
                               (SndListHandle)gShowcaseSound, true);
    if (gSoundLastError != noErr) {
        if (lockedHere) {
            HUnlock(gShowcaseSound);
            gSoundResourceLocked = false;
        }
        return;
    }
    gSoundStarted = true;

    if (queueCompletion) {
        MakeShowcaseSoundCommand(&cmd, volumeCmd, 0x00c000c0);
        gSoundLastError = SndDoCommand(gShowcaseSoundChannel, &cmd, true);
        if (gSoundLastError == noErr) {
            MakeShowcaseSoundCommand(&cmd, callBackCmd, 0);
            gSoundLastError = SndDoCommand(gShowcaseSoundChannel, &cmd, true);
            gSoundQueued = gSoundLastError == noErr;
        }
    }
}

static void QueueShowcaseSoundCommands(void)
{
    SndCommand cmd;

    if (gShowcaseSoundChannel == nil) return;
    MakeShowcaseSoundCommand(&cmd, volumeCmd, 0x00800080);
    gSoundLastError = SndDoCommand(gShowcaseSoundChannel, &cmd, true);
    if (gSoundLastError == noErr) {
        MakeShowcaseSoundCommand(&cmd, callBackCmd, 0);
        gSoundLastError = SndDoCommand(gShowcaseSoundChannel, &cmd, true);
        gSoundQueued = gSoundLastError == noErr;
    }
}

static void FlushShowcaseSound(void)
{
    SndCommand cmd;

    if (gShowcaseSoundChannel == nil) return;
    MakeShowcaseSoundCommand(&cmd, flushCmd, 0);
    gSoundLastError = SndDoImmediate(gShowcaseSoundChannel, &cmd);
    gSoundFlushed = gSoundLastError == noErr;
}

static void QuietShowcaseSound(void)
{
    SndCommand cmd;

    if (gShowcaseSoundChannel == nil) return;
    MakeShowcaseSoundCommand(&cmd, quietCmd, 0);
    gSoundLastError = SndDoImmediate(gShowcaseSoundChannel, &cmd);
    gSoundQuieted = gSoundLastError == noErr;
}

static void DisposeShowcaseSoundChannel(void)
{
    if (gShowcaseSoundChannel == nil) {
        gSoundDisposed = true;
        if (gShowcaseSoundCallbackUPP != nil) {
            DisposeSndCallBackUPP(gShowcaseSoundCallbackUPP);
            gShowcaseSoundCallbackUPP = nil;
        }
        if (gSoundResourceLocked && gShowcaseSound != nil) {
            HUnlock(gShowcaseSound);
            gSoundResourceLocked = false;
        }
        SyncMenuState();
        return;
    }

    ResetShowcaseSoundChannel();
    gSoundLastError = SndDisposeChannel(gShowcaseSoundChannel, true);
    gShowcaseSoundChannel = nil;
    gSoundDisposed = true;
    if (gShowcaseSoundCallbackUPP != nil) {
        DisposeSndCallBackUPP(gShowcaseSoundCallbackUPP);
        gShowcaseSoundCallbackUPP = nil;
    }
    if (gSoundResourceLocked && gShowcaseSound != nil) {
        HUnlock(gShowcaseSound);
        gSoundResourceLocked = false;
    }
    SyncMenuState();
}

static void RefreshShowcaseSoundStatus(void)
{
    if (gShowcaseSoundChannel == nil) {
        gSoundStatusError = noErr;
        gShowcaseSoundStatus.scChannelBusy = false;
        gShowcaseSoundStatus.scChannelPaused = false;
        return;
    }
    gSoundStatusError = SndChannelStatus(gShowcaseSoundChannel,
                                         sizeof(SCStatus),
                                         &gShowcaseSoundStatus);
}

static void PollShowcaseSound(void)
{
    RefreshShowcaseSoundStatus();
    CheckItem(StateMenu(), iSoundState, gSoundCompleted);
    if (gSoundCompleted && !gSoundCompletionPresented) {
        gSoundCompletionPresented = true;
        DrawMainWindow();
    }
}

/* Page 11: Styled TextEdit & Font Manager */
static TEHandle gStyledTE;
static Rect gStyledTERect;
static short gStyledGenevaFont;
static short gStyledMonacoFont;
static Boolean gStyledGenevaReal;
static Boolean gStyledMonacoReal;
static short gStyledInspectMode;
static Boolean gStyledInspectResult;
static TextStyle gStyledInspectStyle;
static short gStyledRunMode;
static Boolean gStyledRunResult;
static TextStyle gStyledRunStyle;
static short gStyledCharWidth;
static short gStyledTextWidth;
static short gStyledMeasureWidth;

/* Page 12: Standard File */
#define fileStatusNone 0
#define fileStatusAccepted 1
#define fileStatusCancelled 2
#define fileStatusError 3

static ControlHandle gFileOpen;
static ControlHandle gFileLegacyOpen;
static ControlHandle gFileSave;
static ControlHandle gFileLegacySave;
static StandardFileReply gFileOpenReply;
static StandardFileReply gFileSaveReply;
static SFReply gFileLegacyOpenReply;
static SFReply gFileLegacySaveReply;
static short gFileOpenStatus;
static short gFileLegacyOpenStatus;
static short gFileSaveStatus;
static short gFileLegacySaveStatus;
static SFTypeList gFileTypeList;

/* Page 13: Resource Browser */
typedef struct {
    Handle handle;
    short id;
    ResType type;
    Str255 name;
    short attrs;
    long size;
    Boolean loaded;
    Boolean present;
} ResourceBrowserEntry;

static ControlHandle gResourceRefresh;
static ControlHandle gResourceLoad;
static ControlHandle gResourceRelease;
static ResourceBrowserEntry gResourceEntries[kResourceBrowserRows];
static short gResourceCount;
static short gResourceMenuCount;
static short gResourceWindowCount;
static Handle gResourceEditHandle;
static short gResourceStatus;
static short gResourceError;
static Boolean gResourceBrowserReady = false;

/* Page 14: Sprites, Masks & Scrolling */
#define kSpriteWorldWidth 320
#define kSpriteWorldHeight 128
#define kSpriteSize 48
static GWorldPtr gSpriteWorld;
static GWorldPtr gSpriteSource;
static GWorldPtr gSpriteMask;
static GWorldPtr gSpriteDeepMask;
static RgnHandle gSpriteRegion;
static RgnHandle gSpriteUpdateRegion;
static ControlHandle gSpriteAnimate;
static ControlHandle gSpriteScroll;
static ControlHandle gSpriteReset;
static Boolean gSpriteReady = false;
static Boolean gSpriteAnimated = false;
static Boolean gSpriteScrolled = false;
static Boolean gSpritePixelVerified = false;
static Boolean gSpriteRegionVerified = false;
static Boolean gSpriteUpdateRegionVerified = false;
static OSErr gSpriteRegionError = noErr;
static short gSpriteScrollDelta;

static const char kTESampleText[] =
    "TextEdit manages styled and plain text formatting, automatic word wrapping, "
    "selection highlighting, and clipboard scrap operations.\r\r"
    "Click to move the insertion point or drag across characters to select text.";

static const char kTECalloutText[] =
    "TETextBox renders transient wrapped paragraphs with specified justification.";

static const char kStyledSampleText[] =
    "Plain  Bold  Color  Size  Font";

static const char *kInventoryItems[kInventoryRowCount] = {
    "Phase Shifter       01  equipped",
    "Medkit              03  ready",
    "Plasma Cartridge    12  ready",
    "Shield Cell         04  reserve",
    "Navigation Chip     01  installed",
    "Repair Nanobots     06  reserve",
    "Fuel Rod            02  reserve",
    "Signal Beacon       01  ready",
    "Star Map             02  archive",
    "Alien Artifact      01  sealed",
    "Quantum Key         01  secured",
    "Mission Log          04  archive"
};

/*
 * Record an indexed PixMap into a PICT, replay it through a canonical
 * offscreen GWorld, then copy those pixels into the active screen palette.
 * The picture's 64 populated colors deliberately do not share device indexes
 * with the destination. DrawPicture must color-match them instead of treating
 * the PICT's raw indexes as screen indexes. Imaging With QuickDraw (1994),
 * pp. 4-13 and 7-14; CopyBits palette translation, pp. 7-24..7-28.
 */
static void DrawIndexedPictureTransfer(void)
{
    GWorldPtr sourceWorld;
    GWorldPtr replayWorld;
    GWorldPtr savedWorld;
    GDHandle savedDevice;
    PixMapHandle sourcePixels;
    PixMapHandle replayPixels;
    PixMapHandle windowPixels;
    CTabHandle sourceColors;
    PicHandle picture;
    Rect localRect;
    Rect displayRect;
    Ptr base;
    long rowBytes;
    short x;
    short y;
    short i;
    sourceWorld = nil;
    replayWorld = nil;
    picture = nil;
    sourceColors = nil;
    SetRect(&localRect, 0, 0, 192, 18);

    GetGWorld(&savedWorld, &savedDevice);
    if (NewGWorld(&sourceWorld, 8, &localRect, nil, nil, 0) != noErr) goto cleanup;
    if (NewGWorld(&replayWorld, 8, &localRect, nil, nil, 0) != noErr) goto cleanup;

    sourcePixels = GetGWorldPixMap(sourceWorld);
    replayPixels = GetGWorldPixMap(replayWorld);
    windowPixels = GetGWorldPixMap((GWorldPtr)gMainWindow);
    if (windowPixels == nil) goto cleanup;
    sourceColors = (**sourcePixels).pmTable;
    if (sourceColors == nil) goto cleanup;
    for (i = 0; i < 64; i++) {
        (**sourceColors).ctTable[i].value = i;
        (**sourceColors).ctTable[i].rgb.red = (unsigned short)(0x2200 + i * 0x02c0);
        (**sourceColors).ctTable[i].rgb.green = (unsigned short)(0xee00 - i * 0x0240);
        (**sourceColors).ctTable[i].rgb.blue = (unsigned short)(0x3300 + i * 0x0180);
    }
    CTabChanged(sourceColors);
    if (!LockPixels(sourcePixels) || !LockPixels(replayPixels)) goto cleanup;

    base = GetPixBaseAddr(sourcePixels);
    rowBytes = (**sourcePixels).rowBytes & 0x3fff;
    for (y = 0; y < 18; y++) {
        for (x = 0; x < 192; x++) {
            base[y * rowBytes + x] = (char)(1 + (x / 3));
        }
    }

    SetGWorld(replayWorld, nil);
    picture = OpenPicture(&localRect);
    CopyBits((BitMap *)*sourcePixels, (BitMap *)*replayPixels,
             &localRect, &localRect, srcCopy, nil);
    ClosePicture();

    DrawPicture(picture, &localRect);

    SetGWorld((GWorldPtr)gMainWindow, savedDevice);
    SetRect(&displayRect, 330, 272, 522, 290);
    CopyBits((BitMap *)*replayPixels, (BitMap *)*windowPixels,
             &localRect, &displayRect, srcCopy, nil);
    FrameRect(&displayRect);

cleanup:
    SetGWorld(savedWorld, savedDevice);
    if (picture != nil) KillPicture(picture);
    if (sourceWorld != nil) DisposeGWorld(sourceWorld);
    if (replayWorld != nil) DisposeGWorld(replayWorld);
}

/*
 * Copy already-authored indexes from an offscreen GDevice whose ColorTable
 * identifies the destination device, but whose RGB entries have been
 * transiently cleared without changing the table seed. Device ColorTables
 * assign colors by position, so CopyBits must preserve these indexes instead
 * of matching their temporary black RGB values into the screen table. Inside
 * Macintosh Volume V (1986), pp. V-57..V-58 and V-138..V-145; Imaging With
 * QuickDraw (1994), pp. 6-16..6-21 and 7-24..7-28.
 */
static void DrawSameDeviceIndexedTransfer(void)
{
    GWorldPtr sourceWorld;
    GDHandle screenDevice;
    PixMapHandle sourcePixels;
    PixMapHandle windowPixels;
    CTabHandle screenColors;
    CTabHandle sourceColors;
    Rect localRect;
    Rect displayRect;
    Ptr base;
    long rowBytes;
    RGBColor color;
    short x;
    short y;

    sourceWorld = nil;
    screenDevice = GetGDevice();
    if (screenDevice == nil) return;
    if ((**(**screenDevice).gdPMap).pixelSize != 8) {
        for (x = 0; x < 3; x++) {
            if (x == 0) {
                color.red = 0xffff; color.green = 0xffff; color.blue = 0;
            } else if (x == 1) {
                color.red = 0xffff; color.green = 0x6666; color.blue = 0;
            } else {
                color.red = 0; color.green = 0xcccc; color.blue = 0xaaaa;
            }
            RGBForeColor(&color);
            SetRect(&displayRect, 330 + x * 64, 302,
                    394 + x * 64, 320);
            PaintRect(&displayRect);
        }
        color.red = color.green = color.blue = 0;
        RGBForeColor(&color);
        SetRect(&displayRect, 330, 302, 522, 320);
        FrameRect(&displayRect);
        return;
    }
    screenColors = (**(**screenDevice).gdPMap).pmTable;
    if (screenColors == nil) return;

    SetRect(&localRect, 0, 0, 192, 18);
    if (NewGWorld(&sourceWorld, 8, &localRect, nil, nil, 0) != noErr) return;

    sourcePixels = GetGWorldPixMap(sourceWorld);
    windowPixels = GetGWorldPixMap((GWorldPtr)gMainWindow);
    if (sourcePixels == nil || windowPixels == nil) goto cleanup;
    sourceColors = (**sourcePixels).pmTable;
    if (sourceColors == nil || !LockPixels(sourcePixels)) goto cleanup;

    base = GetPixBaseAddr(sourcePixels);
    rowBytes = (**sourcePixels).rowBytes & 0x3fff;
    for (y = 0; y < 18; y++) {
        for (x = 0; x < 192; x++) {
            base[y * rowBytes + x] = (char)(2 + (x / 64));
        }
    }

    (**sourceColors).ctSeed = (**screenColors).ctSeed;
    (**sourceColors).ctFlags |= 0x8000;
    for (x = 2; x <= 4; x++) {
        (**sourceColors).ctTable[x].rgb.red = 0;
        (**sourceColors).ctTable[x].rgb.green = 0;
        (**sourceColors).ctTable[x].rgb.blue = 0;
    }

    SetRect(&displayRect, 330, 302, 522, 320);
    CopyBits((BitMap *)*sourcePixels, (BitMap *)*windowPixels,
             &localRect, &displayRect, srcCopy, nil);
    FrameRect(&displayRect);

cleanup:
    if (sourceWorld != nil) DisposeGWorld(sourceWorld);
}

/* State variables */
static short gPage = pageGraphics;
static Boolean gQuit = false;
static Boolean gButtonActivated = false;

/* Preferences state */
static short gDifficulty = iDiffNormal;
static Boolean gSoundFX = true;
static Boolean gMusic = true;
static short gVolume = 75;
static short gRenderer = iRendBevel;
static Boolean gModalDialogCompleted = false;

static MenuHandle StateMenu(void)
{
    return GetMenuHandle(mState);
}

static void DrawHeading(ConstStr255Param heading)
{
    TextFont(systemFont);
    TextSize(12);
    TextFace(bold);
    MoveTo(24, 34);
    DrawString(heading);
    TextFace(0);
}

/*
 * QuickDraw 3D-style Beveled Treatment (Emulated QuickDraw)
 * Renders raised 3D panels and sunken wells using dual-tone light/shadow borders.
 */
static void DrawBeveledBox(const Rect *r, Boolean sunken)
{
    RGBColor white;
    RGBColor lightGray;
    RGBColor midGray;
    RGBColor darkGray;
    RGBColor black;
    Rect inner;

    white.red = 0xffff; white.green = 0xffff; white.blue = 0xffff;
    lightGray.red = 0xeeee; lightGray.green = 0xeeee; lightGray.blue = 0xeeee;
    midGray.red = 0xcccc; midGray.green = 0xcccc; midGray.blue = 0xcccc;
    darkGray.red = 0x6666; darkGray.green = 0x6666; darkGray.blue = 0x6666;
    black.red = 0x0000; black.green = 0x0000; black.blue = 0x0000;

    RGBForeColor(&black);
    FrameRect(r);

    inner = *r;
    InsetRect(&inner, 1, 1);

    if (!sunken) {
        /* Raised 3D Panel: White top/left, Dark bottom/right */
        RGBForeColor(&white);
        MoveTo(inner.left, inner.bottom - 1);
        LineTo(inner.left, inner.top);
        LineTo(inner.right - 1, inner.top);

        RGBForeColor(&darkGray);
        MoveTo(inner.right - 1, inner.top + 1);
        LineTo(inner.right - 1, inner.bottom - 1);
        LineTo(inner.left + 1, inner.bottom - 1);

        InsetRect(&inner, 1, 1);
        RGBForeColor(&lightGray);
        PaintRect(&inner);
    } else {
        /* Sunken 3D Well: Dark top/left, White bottom/right */
        RGBForeColor(&darkGray);
        MoveTo(inner.left, inner.bottom - 1);
        LineTo(inner.left, inner.top);
        LineTo(inner.right - 1, inner.top);

        RGBForeColor(&white);
        MoveTo(inner.right - 1, inner.top + 1);
        LineTo(inner.right - 1, inner.bottom - 1);
        LineTo(inner.left + 1, inner.bottom - 1);

        InsetRect(&inner, 1, 1);
        RGBForeColor(&midGray);
        PaintRect(&inner);
    }
    RGBForeColor(&black);
}

static void DrawGraphicsPage(void)
{
    Rect r;
    Rect clip;
    RgnHandle savedClip;
    RGBColor red;
    RGBColor blue;
    RGBColor black;

    DrawHeading("\pGraphics, patterns, clipping, color, and text");

    SetRect(&r, 24, 55, 174, 135);
    PenPat(&qd.gray);
    PaintRect(&r);
    PenNormal();
    FrameRect(&r);

    red.red = 0xffff;
    red.green = 0x2222;
    red.blue = 0x2222;
    blue.red = 0x2222;
    blue.green = 0x4444;
    blue.blue = 0xffff;
    black.red = black.green = black.blue = 0;

    RGBForeColor(&red);
    SetRect(&r, 205, 55, 325, 135);
    PaintOval(&r);

    savedClip = NewRgn();
    GetClip(savedClip);
    SetRect(&clip, 405, 35, 486, 156);
    ClipRect(&clip);
    RGBForeColor(&blue);
    SetRect(&r, 330, 35, 485, 155);
    FrameRoundRect(&r, 24, 24);
    SetClip(savedClip);
    DisposeRgn(savedClip);

    RGBForeColor(&black);
    MoveTo(24, 175);
    LineTo(505, 175);
    TextFont(3);
    TextSize(10);
    MoveTo(24, 205);
    DrawString("\pThe same source and resources drive both CPU slices.");
}

static void DrawControlsPage(void)
{
    DrawHeading("\pControls and scroll bars");
    MoveTo(24, 70);
    DrawString("\pClick each control; the State menu records the result.");
    DrawControls(gMainWindow);
}

static void DrawWindowsPage(void)
{
    DrawHeading("\pWindow lifecycle and update events");
    MoveTo(24, 70);
    DrawString("\pThis page opens a second document window.");
    MoveTo(24, 92);
    DrawString("\pChoose another page to dispose it again.");
}

#ifdef SHOWCASE_TARGET_PPC
/*
 * Native PowerPC QuickDraw 3D Rendering Pipeline.
 * Exercises real QuickDraw3DLib lifecycle:
 * - Initialization & Teardown (Q3Initialize, Q3Exit)
 * - Macintosh Draw Context with Pane Viewport (Q3MacDrawContext_New)
 * - View Angle Aspect Perspective Camera (Q3ViewAngleAspectCamera_New)
 * - Interactive Renderer (Q3Renderer_NewFromType)
 * - Multi-source Lighting: Ambient & Directional (Q3LightGroup_New, Q3AmbientLight_New, Q3DirectionalLight_New)
 * - Material Attribute Set with Diffuse Color (Q3AttributeSet_New, Q3AttributeSet_Add)
 * - 3D Geometry: TriMesh model with vertex points & triangle indexing (Q3TriMesh_New)
 * - Phong Illumination Shader (Q3PhongIllumination_New)
 * - Rendering traversal loop (Q3View_StartRendering, Q3InterpolationStyle_Submit, Q3BackfacingStyle_Submit, Q3FillStyle_Submit, Q3Shader_Submit, Q3TriMesh_Submit, Q3View_EndRendering)
 * - Comprehensive resource disposal (Q3Object_Dispose)
 */
static void RenderQD3DScene(WindowPtr window)
{
    TQ3DrawContextObject drawContext = nil;
    TQ3CameraObject camera = nil;
    TQ3RendererObject renderer = nil;
    TQ3GroupObject lightGroup = nil;
    TQ3LightObject ambientLight = nil;
    TQ3LightObject dirLight = nil;
    TQ3ViewObject view = nil;
    TQ3ShaderObject shader = nil;
    TQ3AttributeSet attrSet = nil;
    TQ3GeometryObject geom = nil;
    TQ3MacDrawContextData macDCData;
    TQ3ViewAngleAspectCameraData cameraData;
    TQ3LightData ambData;
    TQ3DirectionalLightData dirData;
    TQ3ColorRGB diffColor;
    TQ3TriMeshData triMeshData;
    TQ3Point3D points[4];
    TQ3TriMeshTriangleData triangles[4];
    TQ3ViewStatus viewStatus;

    if (Q3Initialize() != kQ3Success) {
        return;
    }

    /* Bounded 3D Viewport Pane within Section 1 of Drawing Page: local (30, 80, 125, 130) */
    macDCData.drawContextData.clearImageMethod = kQ3ClearMethodWithColor;
    macDCData.drawContextData.clearImageColor.a = 1.0f;
    macDCData.drawContextData.clearImageColor.r = 0.12f;
    macDCData.drawContextData.clearImageColor.g = 0.16f;
    macDCData.drawContextData.clearImageColor.b = 0.28f;
    macDCData.drawContextData.pane.min.x = 30.0f;
    macDCData.drawContextData.pane.min.y = 80.0f;
    macDCData.drawContextData.pane.max.x = 125.0f;
    macDCData.drawContextData.pane.max.y = 130.0f;
    macDCData.drawContextData.paneState = kQ3True;
    macDCData.drawContextData.mask.image = nil;
    macDCData.drawContextData.mask.width = 0;
    macDCData.drawContextData.mask.height = 0;
    macDCData.drawContextData.mask.rowBytes = 0;
    macDCData.drawContextData.mask.bitOrder = kQ3EndianBig;
    macDCData.drawContextData.maskState = kQ3False;
    macDCData.drawContextData.doubleBufferState = kQ3False;
    macDCData.window = (CWindowPtr)window;
    macDCData.library = kQ3Mac2DLibraryNone;
    macDCData.viewPort = nil;
    macDCData.grafPort = (CGrafPtr)window;

    drawContext = Q3MacDrawContext_New(&macDCData);

    cameraData.cameraData.placement.cameraLocation.x = 0.0f;
    cameraData.cameraData.placement.cameraLocation.y = 0.35f;
    cameraData.cameraData.placement.cameraLocation.z = 2.4f;
    cameraData.cameraData.placement.pointOfInterest.x = 0.0f;
    cameraData.cameraData.placement.pointOfInterest.y = 0.0f;
    cameraData.cameraData.placement.pointOfInterest.z = 0.0f;
    cameraData.cameraData.placement.upVector.x = 0.0f;
    cameraData.cameraData.placement.upVector.y = 1.0f;
    cameraData.cameraData.placement.upVector.z = 0.0f;
    cameraData.cameraData.range.hither = 0.1f;
    cameraData.cameraData.range.yon = 100.0f;
    cameraData.cameraData.viewPort.origin.x = -1.0f;
    cameraData.cameraData.viewPort.origin.y = 1.0f;
    cameraData.cameraData.viewPort.width = 2.0f;
    cameraData.cameraData.viewPort.height = 2.0f;
    cameraData.fov = 0.85f;
    cameraData.aspectRatioXToY = 1.0f;

    camera = Q3ViewAngleAspectCamera_New(&cameraData);

    renderer = Q3Renderer_NewFromType(kQ3RendererTypeInteractive);

    lightGroup = Q3LightGroup_New();
    if (lightGroup != nil) {
        ambData.isOn = kQ3True;
        ambData.brightness = 0.35f;
        ambData.color.r = 1.0f;
        ambData.color.g = 1.0f;
        ambData.color.b = 1.0f;
        ambientLight = Q3AmbientLight_New(&ambData);
        if (ambientLight != nil) {
            Q3Group_AddObject(lightGroup, ambientLight);
            Q3Object_Dispose(ambientLight);
        }

        dirData.lightData.isOn = kQ3True;
        dirData.lightData.brightness = 0.85f;
        dirData.lightData.color.r = 1.0f;
        dirData.lightData.color.g = 1.0f;
        dirData.lightData.color.b = 1.0f;
        dirData.castsShadows = kQ3False;
        dirData.direction.x = 1.0f;
        dirData.direction.y = -1.0f;
        dirData.direction.z = -1.0f;
        dirLight = Q3DirectionalLight_New(&dirData);
        if (dirLight != nil) {
            Q3Group_AddObject(lightGroup, dirLight);
            Q3Object_Dispose(dirLight);
        }
    }

    view = Q3View_New();
    if (view != nil) {
        if (drawContext != nil) Q3View_SetDrawContext(view, drawContext);
        if (camera != nil) Q3View_SetCamera(view, camera);
        if (renderer != nil) Q3View_SetRenderer(view, renderer);
        if (lightGroup != nil) Q3View_SetLightGroup(view, lightGroup);
    }

    /* 3D Tetrahedron / Pyramid Model */
    points[0].x =  0.0f; points[0].y =  0.55f; points[0].z =  0.0f;
    points[1].x = -0.5f; points[1].y = -0.35f; points[1].z =  0.5f;
    points[2].x =  0.5f; points[2].y = -0.35f; points[2].z =  0.5f;
    points[3].x =  0.0f; points[3].y = -0.35f; points[3].z = -0.5f;

    triangles[0].pointIndices[0] = 0;
    triangles[0].pointIndices[1] = 1;
    triangles[0].pointIndices[2] = 2;

    triangles[1].pointIndices[0] = 0;
    triangles[1].pointIndices[1] = 2;
    triangles[1].pointIndices[2] = 3;

    triangles[2].pointIndices[0] = 0;
    triangles[2].pointIndices[1] = 3;
    triangles[2].pointIndices[2] = 1;

    triangles[3].pointIndices[0] = 1;
    triangles[3].pointIndices[1] = 3;
    triangles[3].pointIndices[2] = 2;

    attrSet = Q3AttributeSet_New();
    if (attrSet != nil) {
        diffColor.r = 0.2f;
        diffColor.g = 0.65f;
        diffColor.b = 0.95f;
        Q3AttributeSet_Add(attrSet, kQ3AttributeTypeDiffuseColor, &diffColor);
    }

    triMeshData.triMeshAttributeSet = attrSet;
    triMeshData.numTriangles = 4;
    triMeshData.triangles = triangles;
    triMeshData.numTriangleAttributeTypes = 0;
    triMeshData.triangleAttributeTypes = nil;
    triMeshData.numEdges = 0;
    triMeshData.edges = nil;
    triMeshData.numEdgeAttributeTypes = 0;
    triMeshData.edgeAttributeTypes = nil;
    triMeshData.numPoints = 4;
    triMeshData.points = points;
    triMeshData.numVertexAttributeTypes = 0;
    triMeshData.vertexAttributeTypes = nil;
    triMeshData.bBox.isEmpty = kQ3False;
    triMeshData.bBox.min.x = -0.5f;
    triMeshData.bBox.min.y = -0.35f;
    triMeshData.bBox.min.z = -0.5f;
    triMeshData.bBox.max.x =  0.5f;
    triMeshData.bBox.max.y =  0.55f;
    triMeshData.bBox.max.z =  0.5f;

    geom = Q3TriMesh_New(&triMeshData);
    shader = Q3PhongIllumination_New();

    if (view != nil && Q3View_StartRendering(view) == kQ3Success) {
        do {
            Q3InterpolationStyle_Submit(kQ3InterpolationStyleVertex, view);
            Q3BackfacingStyle_Submit(kQ3BackfacingStyleBoth, view);
            Q3FillStyle_Submit(kQ3FillStyleFilled, view);
            if (shader != nil) {
                Q3Shader_Submit(shader, view);
            }
            Q3TriMesh_Submit(&triMeshData, view);
            viewStatus = Q3View_EndRendering(view);
        } while (viewStatus == kQ3ViewStatusRetraverse);
    }

    if (geom != nil) Q3Object_Dispose(geom);
    if (shader != nil) Q3Object_Dispose(shader);
    if (attrSet != nil) Q3Object_Dispose(attrSet);
    if (view != nil) Q3Object_Dispose(view);
    if (lightGroup != nil) Q3Object_Dispose(lightGroup);
    if (renderer != nil) Q3Object_Dispose(renderer);
    if (camera != nil) Q3Object_Dispose(camera);
    if (drawContext != nil) Q3Object_Dispose(drawContext);

    Q3Exit();
}
#endif

/*
 * Page 4: Broader Drawing, QuickDraw 3D, Polygons, Arcs, Regions, PICT & Text
 */
static void DrawDrawingPage(void)
{
    Rect r;
    Rect arcRect;
    Rect subRect;
    Rect picFrame;
    Rect dstRect;
    PolyHandle poly;
    RgnHandle rgnA;
    RgnHandle rgnB;
    RgnHandle rgnCombined;
    PicHandle pic;
    Handle iconH;
    RGBColor color;
    RGBColor white;
    RGBColor darkGray;
    RGBColor black;
    FontInfo fInfo;
    short strW;
    Str255 strBuf;

    white.red = white.green = white.blue = 0xffff;
    darkGray.red = darkGray.green = darkGray.blue = 0x5555;
    black.red = black.green = black.blue = 0x0000;

    /* Section 1: architecture-neutral result after the native QD3D submission. */
    SetRect(&r, 20, 48, 270, 165);
    DrawBeveledBox(&r, false);

#ifdef SHOWCASE_TARGET_PPC
    /* Exercise the native pipeline before painting the shared visible result. */
    RenderQD3DScene(gMainWindow);
    DrawBeveledBox(&r, false);
#endif

    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(28, 62);
    DrawString("\pQuickDraw 3D-style Beveled Treatment");
    TextFace(0);
    MoveTo(28, 74);
    DrawString("\p(68K 2D Fallback Representation)");

    /* Metallic horizontal ridges */
    RGBForeColor(&white);
    MoveTo(28, 80); LineTo(262, 80);
    MoveTo(28, 84); LineTo(262, 84);
    RGBForeColor(&darkGray);
    MoveTo(28, 81); LineTo(262, 81);
    MoveTo(28, 85); LineTo(262, 85);

    /* Raised 3D Button */
    SetRect(&subRect, 30, 95, 125, 125);
    DrawBeveledBox(&subRect, false);
    TextFont(applFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(44, 113);
    DrawString("\pEmbossed");
    TextFace(0);

    /* Sunken 3D Gauge Well */
    SetRect(&subRect, 135, 95, 260, 125);
    DrawBeveledBox(&subRect, true);
    color.red = 0x2222; color.green = 0x8888; color.blue = 0x3333;
    RGBForeColor(&color);
    SetRect(&arcRect, 138, 98, 215, 122);
    PaintRect(&arcRect);
    RGBForeColor(&black);
    TextFont(applFont);
    TextSize(9);
    MoveTo(145, 113);
    DrawString("\pGauge: 65%");

    /* Inset chamfer status bar */
    SetRect(&subRect, 30, 134, 260, 155);
    DrawBeveledBox(&subRect, true);
    TextFont(3);
    TextSize(9);
    MoveTo(38, 148);
    DrawString("\pBeveled Facet Lighting (White / Gray)");

    /* Section 2: Polygons & Arcs */
    SetRect(&r, 280, 48, 535, 165);
    DrawBeveledBox(&r, false);

    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(288, 62);
    DrawString("\pPolygons and Arcs (QuickDraw Geometry)");
    TextFace(0);

    /* Star Polygon */
    poly = OpenPoly();
    MoveTo(345, 75);
    LineTo(356, 102); LineTo(385, 102); LineTo(362, 118);
    LineTo(371, 148); LineTo(345, 130); LineTo(319, 148);
    LineTo(328, 118); LineTo(305, 102); LineTo(334, 102);
    LineTo(345, 75);
    ClosePoly();

    color.red = 0xeeee; color.green = 0x9999; color.blue = 0x1111;
    RGBForeColor(&color);
    PaintPoly(poly);
    RGBForeColor(&black);
    FramePoly(poly);
    KillPoly(poly);

    /* 3-Sector Pie Chart with Arcs */
    SetRect(&arcRect, 415, 78, 495, 158);
    color.red = 0xdddd; color.green = 0x2222; color.blue = 0x3333;
    RGBForeColor(&color);
    PaintArc(&arcRect, 0, 120);

    color.red = 0x2222; color.green = 0x9999; color.blue = 0x4444;
    RGBForeColor(&color);
    PaintArc(&arcRect, 120, 110);

    color.red = 0x2222; color.green = 0x4444; color.blue = 0xdddd;
    RGBForeColor(&color);
    PaintArc(&arcRect, 230, 130);

    RGBForeColor(&black);
    FrameOval(&arcRect);

    /* Section 3: QuickDraw Regions */
    SetRect(&r, 20, 175, 185, 320);
    DrawBeveledBox(&r, false);

    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(28, 190);
    DrawString("\pQuickDraw Regions");
    TextFace(0);

    rgnA = NewRgn();
    rgnB = NewRgn();
    rgnCombined = NewRgn();

    SetRect(&subRect, 30, 205, 105, 275);
    OpenRgn();
    FrameOval(&subRect);
    CloseRgn(rgnA);

    SetRect(&subRect, 65, 225, 140, 290);
    OpenRgn();
    FrameRoundRect(&subRect, 16, 16);
    CloseRgn(rgnB);

    XorRgn(rgnA, rgnB, rgnCombined);
    color.red = 0x3333; color.green = 0x6666; color.blue = 0xbbbb;
    RGBForeColor(&color);
    PaintRgn(rgnCombined);
    RGBForeColor(&black);
    FrameRgn(rgnCombined);

    DisposeRgn(rgnA);
    DisposeRgn(rgnB);
    DisposeRgn(rgnCombined);

    TextFont(3);
    TextSize(9);
    MoveTo(28, 308);
    DrawString("\pXorRgn Oval + RoundRect");

    /* Section 4: Icons & Picture (PICT) Recording */
    SetRect(&r, 195, 175, 360, 320);
    DrawBeveledBox(&r, false);

    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(203, 190);
    DrawString("\pIcons & Pictures (PICT)");
    TextFace(0);

    /* Plot standard icon resource */
    SetRect(&subRect, 205, 205, 237, 237);
    iconH = GetIcon(rShowcaseIcon);
    if (iconH != nil) {
        PlotIcon(&subRect, iconH);
        ReleaseResource(iconH);
    }

    /* Dynamic PICT Recording & Playback */
    SetRect(&picFrame, 0, 0, 40, 40);
    pic = OpenPicture(&picFrame);
    color.red = 0xeeee; color.green = 0x7777; color.blue = 0x1111;
    RGBForeColor(&color);
    PaintRoundRect(&picFrame, 10, 10);
    RGBForeColor(&black);
    FrameRoundRect(&picFrame, 10, 10);
    TextFont(applFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(6, 25);
    DrawString("\pPICT");
    TextFace(0);
    ClosePicture();

    /* Draw picture 1:1 and scaled */
    SetRect(&dstRect, 250, 205, 290, 245);
    DrawPicture(pic, &dstRect);
    SetRect(&dstRect, 300, 205, 350, 255);
    DrawPicture(pic, &dstRect);
    KillPicture(pic);

    TextFont(3);
    TextSize(9);
    MoveTo(203, 280);
    DrawString("\pPlotIcon (32x32 bitmap)");
    MoveTo(203, 295);
    DrawString("\pOpenPicture/DrawPicture");

    /* Section 5: Typography & Measurements */
    SetRect(&r, 370, 175, 535, 320);
    DrawBeveledBox(&r, false);

    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(378, 190);
    DrawString("\pTypography & Metrics");
    TextFace(0);

    TextFont(systemFont);
    TextSize(12);
    TextFace(bold);
    MoveTo(378, 212);
    DrawString("\pSystem 12pt Bold");

    TextFont(applFont);
    TextSize(9);
    TextFace(0);
    MoveTo(378, 228);
    DrawString("\pGeneva 9pt Plain Text");

    TextFont(4); /* Monaco */
    TextSize(9);
    MoveTo(378, 244);
    DrawString("\pMonaco 9pt Code Font");

    TextFont(applFont);
    TextSize(9);
    TextFace(italic | underline | shadow);
    MoveTo(378, 262);
    DrawString("\pItalic Underline Shadow");
    TextFace(0);

    /* Text measurement */
    GetFontInfo(&fInfo);
    strBuf[0] = 0;
    MoveTo(378, 282);
    TextFont(3);
    TextSize(9);
    DrawString("\pMeasureText: ");
    strW = StringWidth("\pToolbox Showcase");
    NumToString(strW, strBuf);
    DrawString(strBuf);
    DrawString("\ppx");

    /* Ruler line */
    MoveTo(378, 295);
    LineTo(378 + (strW > 140 ? 140 : strW), 295);

    /* Footer note */
    MoveTo(20, 345);
    TextFont(applFont);
    TextSize(9);
    DrawString("\pAll operations executed through standard QuickDraw traps on 68K and PowerPC.");

    /* Draw this last because QuickDraw 3D flushes its pane asynchronously. */
    TextFont(systemFont);
    TextSize(12);
    TextFace(bold);
    MoveTo(70, 34);
    DrawString("\pDrawing: QuickDraw 3D, Polygons, Arcs, Regions, Pictures & Text");
    TextFace(0);
}

/*
 * Page 5: Game Preferences & Settings Panel
 */
static void DrawPreferencesPage(void)
{
    Rect r;
    Rect well;
    Str255 volStr;

    DrawHeading("\pGame Preferences & Configuration Panel");

    /* Audio Settings Group Box */
    SetRect(&r, 20, 48, 230, 160);
    DrawBeveledBox(&r, false);
    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(28, 62);
    DrawString("\pAudio & Sound FX");
    TextFace(0);

    /* Difficulty Group Box */
    SetRect(&r, 240, 48, 535, 160);
    DrawBeveledBox(&r, false);
    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(248, 62);
    DrawString("\pGameplay Difficulty");
    TextFace(0);

    /* Volume Slider Box */
    SetRect(&r, 20, 170, 230, 255);
    DrawBeveledBox(&r, false);
    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(28, 184);
    DrawString("\pMaster Volume: ");
    NumToString(gVolume, volStr);
    DrawString(volStr);
    DrawString("\p%");
    TextFace(0);

    /* Renderer Group Box */
    SetRect(&r, 240, 170, 535, 255);
    DrawBeveledBox(&r, false);
    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(248, 184);
    DrawString("\pGraphics Pipeline / Shading Style");
    TextFace(0);

    /* Status Readout Sunken Well */
    SetRect(&well, 20, 265, 535, 305);
    DrawBeveledBox(&well, true);
    TextFont(applFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(28, 282);
    DrawString("\pActive Profile: ");
    TextFace(0);
    if (gDifficulty == iDiffEasy) {
        DrawString("\pRecruit (Easy)");
    } else if (gDifficulty == iDiffHard) {
        DrawString("\pNightmare (Hard)");
    } else {
        DrawString("\pVeteran (Normal)");
    }
    DrawString("\p | Audio: ");
    if (!gSoundFX && !gMusic) {
        DrawString("\pMuted");
    } else if (gSoundFX && !gMusic) {
        DrawString("\pFX Only");
    } else if (!gSoundFX && gMusic) {
        DrawString("\pMusic Only");
    } else {
        DrawString("\pFull (FX+Music)");
    }
    DrawString("\p | Volume: ");
    DrawString(volStr);
    DrawString("\p% | Pipeline: ");
    if (gRenderer == iRendFlat) {
        DrawString("\pFlat 2D");
    } else if (gRenderer == iRendContrast) {
        DrawString("\pHigh Contrast");
    } else {
        DrawString("\pQD3D Bevels");
    }

    MoveTo(28, 297);
    TextFont(3);
    TextSize(9);
    DrawString("\pSettings synchronize bidirectionally with the Options hierarchical menus.");

    DrawControls(gMainWindow);
}

/*
 * Page 6: Dialog Manager, Modal Dialogs & System Alerts
 */
static void DrawDialogsPage(void)
{
    Rect r;
    Rect btnRect;
    Rect editRect;
    RGBColor black;

    black.red = black.green = black.blue = 0x0000;

    DrawHeading("\pDialog Manager: Modal Dialogs & System Alerts");

    TextFont(applFont);
    TextSize(9);
    MoveTo(24, 52);
    DrawString("\pThe Dialog Manager provides standardized modal and modeless user interaction.");
    MoveTo(24, 66);
    DrawString("\pClick the action buttons below or use the Options menu to trigger live sessions.");

    /* Embedded Dialog Simulation Preview */
    SetRect(&r, 20, 80, 535, 290);
    DrawBeveledBox(&r, false);

    TextFont(systemFont);
    TextSize(12);
    TextFace(bold);
    MoveTo(35, 105);
    DrawString("\pSimulated Modal Dialog Structure (DLOG / DITL)");
    TextFace(0);

    /* Default Button 3px Bold Outline Ring */
    SetRect(&btnRect, 410, 235, 510, 265);
    PenSize(3, 3);
    FrameRoundRect(&btnRect, 16, 16);
    PenNormal();
    TextFont(systemFont);
    TextSize(12);
    MoveTo(445, 255);
    DrawString("\pOK");

    /* Cancel Button */
    SetRect(&btnRect, 295, 238, 385, 262);
    FrameRoundRect(&btnRect, 8, 8);
    MoveTo(320, 255);
    DrawString("\pCancel");

    /* Dialog Item Types showcase */
    TextFont(applFont);
    TextSize(9);
    MoveTo(35, 130);
    DrawString("\p* Item Type 1 (btnCtrl): Standard & Default Action Push Buttons (3px ring)");
    MoveTo(35, 150);
    DrawString("\p* Item Type 2 (chkCtrl / radCtrl): Checkboxes & Mutual Exclusion Radio Buttons");
    MoveTo(35, 170);
    DrawString("\p* Item Type 3 (statText): Non-editable Information & Prompt Strings");
    MoveTo(35, 190);
    DrawString("\p* Item Type 4 (editText): TextEdit Buffer with Keyboard Focus & Selection:");

    /* Sample EditText Field */
    SetRect(&editRect, 170, 202, 380, 222);
    RGBForeColor(&black);
    FrameRect(&editRect);
    TextFont(4); /* Monaco */
    TextSize(9);
    MoveTo(176, 216);
    DrawString("\pAce Pilot |");

    /* Status of last modal session */
    TextFont(applFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(35, 282);
    DrawString("\pModal Dialog Status: ");
    TextFace(0);
    if (gModalDialogCompleted) {
        DrawString("\pLast session confirmed with OK.");
    } else {
        DrawString("\pNo modal dialog session completed yet.");
    }

    DrawControls(gMainWindow);
}

/*
 * Palette Manager page. Animated + explicit entries deliberately occupy
 * stable device indexes so AnimateEntry recolors already-drawn pixels without
 * touching the window bitmap. Inside Macintosh Volume VI (1991), pp. 20-10
 * through 20-15 and 20-19 through 20-22.
 */
static void DrawPalettesPage(void)
{
    Rect r;
    RGBColor black;
    RGBColor white;

    black.red = black.green = black.blue = 0;
    white.red = white.green = white.blue = 0xffff;

    RGBForeColor(&black);
    RGBBackColor(&white);
    DrawHeading("\pPalette activation, indexed drawing, and animation");
    MoveTo(24, 58);
    DrawString("\pThe swatches use PmForeColor; the lower well uses PmBackColor.");
    MoveTo(24, 76);
    DrawString("\pAnimated + explicit colors stay at known CLUT indexes.");

    PmForeColor(2);
    SetRect(&r, 30, 96, 180, 166);
    PaintRect(&r);
    PmForeColor(3);
    SetRect(&r, 205, 96, 355, 166);
    PaintOval(&r);
    PmForeColor(4);
    SetRect(&r, 380, 96, 530, 166);
    PaintRect(&r);

    RGBForeColor(&black);
    SetRect(&r, 30, 96, 180, 166); FrameRect(&r);
    SetRect(&r, 205, 96, 355, 166); FrameOval(&r);
    SetRect(&r, 380, 96, 530, 166); FrameRoundRect(&r, 18, 18);
    MoveTo(62, 186); DrawString("\pEntry 2");
    MoveTo(246, 186); DrawString("\pEntry 3");
    MoveTo(422, 186); DrawString("\pEntry 4");

    SetRect(&r, 30, 205, 530, 254);
    FrameRect(&r);
    InsetRect(&r, 2, 2);
    PmBackColor(5);
    EraseRect(&r);
    RGBBackColor(&white);
    RGBForeColor(&black);
    MoveTo(48, 235);
    DrawString("\pTolerant background entry allocated by the Palette Manager");

    RGBBackColor(&white);
    RGBForeColor(&black);
    MoveTo(30, 284);
    DrawString("\pIndexed PICT -> GWorld -> screen");
    MoveTo(30, 314);
    DrawString("\pDevice indexes survive black CLUT");
    DrawSameDeviceIndexedTransfer();
    DrawIndexedPictureTransfer();

    /*
     * A screen GDevice keeps the inverse table used for RGBForeColor
     * separate from the GDevice ColorTable used to build that lookup. Put an
     * exact requested color at hardware index 117 and a visibly different
     * color at the standard inverse-table result (213), then restore those
     * two logical ColorTable entries without touching the hardware. On an
     * 8-bit screen the band must display index 213, even though a direct
     * nearest-color scan would select 117. This is the small, app-independent
     * form of the loading-bar regression that exposed the distinction.
     * Inside Macintosh Volume V (1986), pp. V-137 through V-143.
     */
    {
        GDHandle screenDevice;
        CTabHandle screenColors;
        CTabHandle standardColors;
        ColorSpec colors[2];
        RGBColor requested;

        screenDevice = GetMainDevice();
        screenColors = (**(**screenDevice).gdPMap).pmTable;
        standardColors = GetCTable(8);
        colors[0].value = 117;
        colors[0].rgb.red = 0x1010;
        colors[0].rgb.green = 0x0a0a;
        colors[0].rgb.blue = 0x6969;
        colors[1].value = 213;
        colors[1].rgb.red = 0x7b7b;
        colors[1].rgb.green = 0x7373;
        colors[1].rgb.blue = 0x8484;
        SetEntries(-1, 1, colors);
        if (standardColors != nil) {
            (**screenColors).ctTable[117] = (**standardColors).ctTable[117];
            (**screenColors).ctTable[213] = (**standardColors).ctTable[213];
            CTabChanged(screenColors);
            DisposeCTable(standardColors);
        }

        requested.red = 0;
        requested.green = 0;
        requested.blue = 0x6666;
        RGBForeColor(&requested);
        SetRect(&r, 370, 322, 562, 340);
        PaintRect(&r);
        RGBForeColor(&black);
        FrameRect(&r);
    }
    MoveTo(30, 334);
    DrawString("\pRGBForeColor uses device inverse table");

    MoveTo(245, 361);
    DrawString(gPaletteAnimated ? "\pAnimated CLUT values" : "\pInitial CLUT values");
    DrawControls(gMainWindow);
}

static void AnimateShowcasePalette(void)
{
    RGBColor color;

    gPaletteAnimated = !gPaletteAnimated;
    color.red = 0xffff;
    color.green = gPaletteAnimated ? 0x1111 : 0xffff;
    color.blue = gPaletteAnimated ? 0x9999 : 0x0000;
    AnimateEntry(gMainWindow, 2, &color);

    color.red = gPaletteAnimated ? 0x1111 : 0xffff;
    color.green = gPaletteAnimated ? 0xdddd : 0x6666;
    color.blue = gPaletteAnimated ? 0x5555 : 0x0000;
    AnimateEntry(gMainWindow, 3, &color);

    color.red = gPaletteAnimated ? 0x2222 : 0x0000;
    color.green = gPaletteAnimated ? 0x5555 : 0xcccc;
    color.blue = gPaletteAnimated ? 0xffff : 0xaaaa;
    AnimateEntry(gMainWindow, 4, &color);
}

/*
 * Page 10: Sound Manager channels, sampled playback, command queues, and
 * callbacks. The controls deliberately separate queued commands from
 * immediate quiet/flush commands so their different lifecycles are visible.
 * Sound (1994), pp. 2-19--2-29, 2-92--2-101, and 2-151--2-152.
 */
static void DrawSoundPage(void)
{
    Rect r;
    Boolean busy;

    RefreshShowcaseSoundStatus();
    busy = gShowcaseSoundStatus.scChannelBusy;

    DrawHeading("\pSound Manager: Channels & Sampled Playback");
    MoveTo(24, 56);
    DrawString("\pSysBeep, SndPlay, FIFO commands, immediate control, and callbacks.");
    MoveTo(24, 70);
    DrawString("\pThe small resource-backed sample is mixed into the deterministic audio stream.");

    SetRect(&r, 20, 82, 290, 238);
    DrawBeveledBox(&r, false);
    SetRect(&r, 305, 82, 535, 238);
    DrawBeveledBox(&r, false);

    TextFont(systemFont);
    TextSize(10);
    TextFace(bold);
    MoveTo(32, 101);
    DrawString("\pChannel & status");
    MoveTo(317, 101);
    DrawString("\pCommand lifecycle");
    TextFace(0);

    TextFont(applFont);
    TextSize(9);
    MoveTo(32, 122);
    DrawString("\pSndNewChannel: ");
    DrawString(gShowcaseSoundChannel != nil ? "\pallocated" : "\pdisposed");
    MoveTo(32, 140);
    DrawString("\pSndChannelStatus: ");
    DrawString(busy ? "\pbusy" : "\pidle");
    MoveTo(32, 158);
    DrawString("\pSndPlay resource: ");
    DrawString(gSoundStarted ? "\pstarted" : "\pidle");
    MoveTo(32, 176);
    DrawString("\pSysBeep(30): ");
    DrawString(gSoundBeeped ? "\prequested" : "\pnot requested");
    MoveTo(32, 194);
    DrawString("\pCompletion: ");
    DrawString(gSoundCompleted ? "\preceived" : "\pwaiting");
    MoveTo(32, 212);
    DrawString("\pStatus error: ");
    DrawString(gSoundStatusError == noErr ? "\pnoErr" : "\perror");

    MoveTo(317, 122);
    DrawString("\pSndDoCommand FIFO: ");
    DrawString(gSoundQueued ? "\psent" : "\pidle");
    MoveTo(317, 140);
    DrawString("\pSndDoImmediate flush: ");
    DrawString(gSoundFlushed ? "\pissued" : "\pidle");
    MoveTo(317, 158);
    DrawString("\pSndDoImmediate quiet: ");
    DrawString(gSoundQuieted ? "\pissued" : "\pidle");
    MoveTo(317, 176);
    DrawString("\pCallback command: ");
    DrawString(gSoundQueued ? "\pqueued" : "\pnot queued");
    MoveTo(317, 194);
    DrawString("\pResource: ");
    DrawString(gShowcaseSound != nil ? "\ploaded" : "\pmissing");
    MoveTo(317, 212);
    DrawString("\pDispose: ");
    DrawString(gSoundDisposed ? "\pcomplete" : "\pavailable");

    DrawControls(gMainWindow);
}

/*
 * Page 8: TextEdit: Multiline Buffer, Justification, Scrap & Selection
 */
static void DrawTextEditPage(void)
{
    Rect r;
    Rect well;
    Rect calloutRect;
    Str255 numStr;
    RGBColor white;
    RGBColor black;

    white.red = white.green = white.blue = 0xffff;
    black.red = black.green = black.blue = 0x0000;

    DrawHeading("\pTextEdit: Multiline Buffer, Justification, Scrap & Selection");

    /* Section 1: Interactive TextEdit View */
    SetRect(&r, 20, 48, 340, 225);
    DrawBeveledBox(&r, false);

    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(28, 62);
    DrawString("\pInteractive TERec Buffer (Geneva 9pt)");
    TextFace(0);

    /* Sunken Well around live TextEdit field */
    SetRect(&well, 28, 70, 332, 217);
    DrawBeveledBox(&well, true);

    /* Erase TextEdit content rect and draw updated text */
    if (gTE != nil) {
        RGBBackColor(&white);
        RGBForeColor(&black);
        EraseRect(&gTERect);
        TEUpdate(&gTERect, gTE);
    }

    /* Section 2: Static TETextBox Callout */
    SetRect(&r, 350, 48, 535, 140);
    DrawBeveledBox(&r, false);

    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(358, 62);
    DrawString("\pTETextBox Callout (Centered)");
    TextFace(0);

    SetRect(&well, 358, 70, 527, 132);
    DrawBeveledBox(&well, true);

    SetRect(&calloutRect, 362, 74, 523, 128);
    TextFont(applFont);
    TextSize(9);
    RGBBackColor(&white);
    RGBForeColor(&black);
    EraseRect(&calloutRect);
    TETextBox((const void *)kTECalloutText, sizeof(kTECalloutText) - 1, &calloutRect, teJustCenter);

    /* Section 3: Alignment Controls */
    SetRect(&r, 350, 146, 535, 225);
    DrawBeveledBox(&r, false);

    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(358, 160);
    DrawString("\pParagraph Alignment (TESetJust)");
    TextFace(0);

    TextFont(applFont);
    TextSize(9);
    MoveTo(358, 206);
    DrawString("\pMode: ");
    if (gTEJust == teJustLeft) {
        DrawString("\pteJustLeft (0 - flush left)");
    } else if (gTEJust == teJustCenter) {
        DrawString("\pteJustCenter (1 - centered)");
    } else if (gTEJust == teJustRight) {
        DrawString("\pteJustRight (-1 - flush right)");
    }

    /* Section 4: Scrap Operations */
    SetRect(&r, 20, 233, 340, 310);
    DrawBeveledBox(&r, false);

    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(28, 247);
    DrawString("\pClipboard Scrap (TECut / TECopy / TEPaste)");
    TextFace(0);

    TextFont(3);
    TextSize(9);
    MoveTo(28, 300);
    DrawString("\pInteracts with internal TextEdit scrap buffer.");

    /* Section 5: TERec Live Metrics Inspector */
    SetRect(&r, 350, 233, 535, 310);
    DrawBeveledBox(&r, false);

    TextFont(applFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(358, 248);
    DrawString("\pTERec Inspector:");
    TextFace(0);

    if (gTE != nil) {
        MoveTo(358, 264);
        DrawString("\pLength: ");
        NumToString((**gTE).teLength, numStr);
        DrawString(numStr);
        DrawString("\p bytes | Lines: ");
        NumToString((**gTE).nLines, numStr);
        DrawString(numStr);

        MoveTo(358, 280);
        DrawString("\pSelection: [");
        NumToString((**gTE).selStart, numStr);
        DrawString(numStr);
        DrawString("\p..");
        NumToString((**gTE).selEnd, numStr);
        DrawString(numStr);
        DrawString("\p]");

        MoveTo(358, 296);
        DrawString("\pFont: Geneva | Size: 9pt | Active: Yes");
    }

    /* Footer Note */
    RGBBackColor(&white);
    RGBForeColor(&black);
    MoveTo(20, 335);
    TextFont(applFont);
    TextSize(9);
    DrawString("\pClick to position caret; drag to select. Type text or use buttons to edit.");

    DrawControls(gMainWindow);
}

/*
 * Page 9: Lists & Inventory.
 *
 * The default text list definition (theProc = 0) owns the cell drawing. The
 * page intentionally keeps the list in one column so every operation is
 * visible in the same deterministic row geometry on both CPU slices.
 * More Macintosh Toolbox (1993), pp. 4-70--4-76, 4-81--4-84, and 4-90--4-95.
 */
static short InventoryTextLength(const char *text)
{
    short length;

    length = 0;
    while (text[length] != 0) length++;
    return length;
}

static void UpdateInventoryList(void)
{
    RgnHandle updateRegion;

    if (gInventoryList == nil) return;
    updateRegion = NewRgn();
    if (updateRegion != nil) {
        RectRgn(updateRegion, &gInventoryView);
        LUpdate(updateRegion, gInventoryList);
        DisposeRgn(updateRegion);
    } else {
        LUpdate(nil, gInventoryList);
    }
}

static void PopulateInventoryList(void)
{
    Cell cell;
    short row;

    if (gInventoryList == nil) return;

    /* Batch structural and cell writes with automatic drawing disabled. */
    LSetDrawingMode(false, gInventoryList);
    LAddRow(kInventoryRowCount - 1, 1, gInventoryList);
    for (row = 0; row < kInventoryRowCount; row++) {
        cell.v = row;
        cell.h = 0;
        LSetCell((Ptr)kInventoryItems[row], InventoryTextLength(kInventoryItems[row]),
                 cell, gInventoryList);
    }
    LSetDrawingMode(true, gInventoryList);
    UpdateInventoryList();
}

static Boolean InspectInventorySelection(void)
{
    Cell cell;
    char cellData[96];
    short dataLength;

    cell.v = 0;
    cell.h = 0;
    gListSelectedRow = -1;
    gListSelectedLength = 0;
    if (gInventoryList == nil || !LGetSelect(true, &cell, gInventoryList)) {
        gListStatus = listStatusNone;
        return false;
    }

    /* LGetCell is the inspection path; the buffer is intentionally bounded. */
    dataLength = sizeof(cellData);
    LGetCell(cellData, &dataLength, cell, gInventoryList);
    gListSelectedRow = cell.v;
    gListSelectedLength = dataLength;
    gListStatus = listStatusSelected;
    return true;
}

static void MutateInventorySelection(void)
{
    Cell cell;
    char cellData[96];
    short dataLength;
    short suffixLength;
    short i;
    static const char suffix[] = "  * updated";

    cell.v = 0;
    cell.h = 0;
    if (gInventoryList == nil || !LGetSelect(true, &cell, gInventoryList)) {
        gListStatus = listStatusNone;
        gListSelectedRow = -1;
        gListSelectedLength = 0;
        return;
    }

    dataLength = sizeof(cellData);
    LGetCell(cellData, &dataLength, cell, gInventoryList);
    suffixLength = InventoryTextLength(suffix);
    if (dataLength > sizeof(cellData) - suffixLength) {
        dataLength = sizeof(cellData) - suffixLength;
    }
    for (i = 0; i < suffixLength; i++) {
        cellData[dataLength + i] = suffix[i];
    }
    dataLength += suffixLength;
    LSetCell(cellData, dataLength, cell, gInventoryList);
    gListSelectedRow = cell.v;
    gListSelectedLength = dataLength;
    gListStatus = listStatusMutated;
    UpdateInventoryList();
}

static void ScrollInventoryList(void)
{
    if (gInventoryList == nil) return;
    LScroll(0, 4, gInventoryList);
    gListStatus = listStatusScrolled;
    UpdateInventoryList();
}

static void ResizeInventoryList(void)
{
    if (gInventoryList == nil) return;
    if (gListResized) {
        LSize(504, 150, gInventoryList);
        SetRect(&gInventoryView, 24, 78, 528, 228);
        gListResized = false;
    } else {
        LSize(450, 114, gInventoryList);
        SetRect(&gInventoryView, 24, 78, 474, 192);
        gListResized = true;
    }
    gListStatus = listStatusResized;
    UpdateInventoryList();
}

static void ToggleInventoryActivation(void)
{
    if (gInventoryList == nil) return;
    gListActive = !gListActive;
    LActivate(gListActive, gInventoryList);
    gListStatus = gListActive ? listStatusActivated : listStatusInactive;
    UpdateInventoryList();
}

static void DrawListsPage(void)
{
    Rect frame;
    Str255 number;

    DrawHeading("\pLists & Inventory: List Manager operations");
    TextFont(applFont);
    TextSize(9);
    MoveTo(24, 54);
    DrawString("\pLNew + LAddRow + LSetCell populate a default text LDEF.");
    MoveTo(24, 66);
    DrawString("\pClick a row, inspect it, mutate it, scroll, resize, or toggle activation.");

    frame = gInventoryView;
    UpdateInventoryList();
    FrameRect(&frame);

    MoveTo(24, 316);
    TextFace(bold);
    DrawString("\pList Manager status: ");
    TextFace(0);
    if (gInventoryList == nil) {
        DrawString("\pLNew failed");
    } else if (gListStatus == listStatusNone) {
        DrawString("\pno cell selected");
    } else if (gListStatus == listStatusSelected) {
        DrawString("\pselected row ");
        NumToString(gListSelectedRow + 1, number);
        DrawString(number);
        DrawString("\p (LGetSelect/LGetCell)");
    } else if (gListStatus == listStatusMutated) {
        DrawString("\prow ");
        NumToString(gListSelectedRow + 1, number);
        DrawString(number);
        DrawString("\p updated with LSetCell");
    } else if (gListStatus == listStatusScrolled) {
        DrawString("\pscrolled with LScroll (four-row request)");
    } else if (gListStatus == listStatusResized) {
        DrawString(gListResized ? "\presized to compact view with LSize"
                               : "\prestored full view with LSize");
    } else if (gListStatus == listStatusInactive) {
        DrawString("\pinactive with LActivate(FALSE)");
    } else {
        DrawString("\pactive with LActivate(TRUE)");
    }

    MoveTo(24, 336);
    DrawString("\pSelected cell bytes: ");
    NumToString(gListSelectedLength, number);
    DrawString(number);
    DrawString(gListActive ? "\p | list active" : "\p | list inactive");

    DrawControls(gMainWindow);
}

/*
 * Page 13: Resource Browser. The map is inspected with loading disabled so
 * the table can show the difference between a resource reference and its
 * resident data. The selected named resource then follows the ordinary
 * SetResLoad(FALSE) -> GetNamedResource -> LoadResource -> ReleaseResource
 * path, including a subsequent reload of the same map reference.
 * Inside Macintosh: More Macintosh Toolbox (1993), pp. 1-75--1-82 and
 * 1-92--1-93; Inside Macintosh Volume I (1985), pp. I-118--I-125.
 */
static Boolean ResourceBrowserHandleLoaded(Handle handle)
{
    return handle != nil && *handle != nil;
}

static void ResourceBrowserTypeString(ResType type, Str255 string)
{
    string[0] = 4;
    string[1] = (char)(type >> 24);
    string[2] = (char)(type >> 16);
    string[3] = (char)(type >> 8);
    string[4] = (char)type;
}

static Boolean ResourceBrowserCheckError(void)
{
    gResourceError = ResError();
    if (gResourceError != noErr) {
        gResourceStatus = resourceStatusError;
        return false;
    }
    return true;
}

static void ResourceBrowserRestoreAutomaticLoading(void)
{
    short error;

    SetResLoad(true);
    error = ResError();
    if (gResourceError == noErr && error != noErr) gResourceError = error;
    if (gResourceError != noErr) gResourceStatus = resourceStatusError;
}

static void ResourceBrowserClearEntry(short index)
{
    gResourceEntries[index].handle = nil;
    gResourceEntries[index].id = 0;
    gResourceEntries[index].type = 0;
    gResourceEntries[index].name[0] = 0;
    gResourceEntries[index].attrs = 0;
    gResourceEntries[index].size = 0;
    gResourceEntries[index].loaded = false;
    gResourceEntries[index].present = false;
}

static Boolean ReadResourceBrowserEntries(void)
{
    short i;
    short visibleCount;
    Handle handle;
    ResType resourceType;
    long resourceSize;
    Boolean ok;
    Boolean resLoadDisabled;

    gResourceError = noErr;
    gResourceCount = 0;
    gResourceMenuCount = 0;
    gResourceWindowCount = 0;
    for (i = 0; i < kResourceBrowserRows; i++) ResourceBrowserClearEntry(i);

    ok = true;
    resLoadDisabled = false;
    /* Count1Resources is map-only, so it is safe while automatic loading is
     * disabled. Keep three counts visible to make the selected map scope
     * explicit and to compare the custom DATA records with existing UI data.
     */
    gResourceCount = Count1Resources('DATA');
    if (!ResourceBrowserCheckError()) ok = false;
    if (ok) {
        gResourceMenuCount = Count1Resources('MENU');
        if (!ResourceBrowserCheckError()) ok = false;
    }
    if (ok) {
        gResourceWindowCount = Count1Resources('WIND');
        if (!ResourceBrowserCheckError()) ok = false;
    }

    if (ok) {
        SetResLoad(false);
        resLoadDisabled = true;
        if (!ResourceBrowserCheckError()) ok = false;
    }
    visibleCount = ok ? gResourceCount : 0;
    if (visibleCount > kResourceBrowserRows) visibleCount = kResourceBrowserRows;
    for (i = 0; ok && i < visibleCount; i++) {
        handle = Get1IndResource('DATA', i + 1);
        if (!ResourceBrowserCheckError()) {
            ok = false;
            break;
        }
        if (handle == nil) {
            gResourceError = -192;
            gResourceStatus = resourceStatusError;
            ok = false;
            break;
        }

        gResourceEntries[i].handle = handle;
        GetResInfo(handle, &gResourceEntries[i].id, &resourceType,
                   gResourceEntries[i].name);
        if (!ResourceBrowserCheckError()) {
            ok = false;
            break;
        }
        gResourceEntries[i].type = resourceType;
        gResourceEntries[i].attrs = GetResAttrs(handle);
        if (!ResourceBrowserCheckError()) {
            ok = false;
            break;
        }
        gResourceEntries[i].loaded = ResourceBrowserHandleLoaded(handle);
        gResourceEntries[i].present = true;
        /* GetResourceSizeOnDisk (also exported as SizeResource) reports the
         * exact map-backed byte size without materializing an empty handle.
         * This preserves the deferred state while remaining valid on classic
         * Resource Manager implementations that invalidate released handles. */
        resourceSize = GetResourceSizeOnDisk(handle);
        if (!ResourceBrowserCheckError() || resourceSize < 0) {
            if (gResourceError == noErr) gResourceError = -192;
            gResourceStatus = resourceStatusError;
            ok = false;
            break;
        }
        gResourceEntries[i].size = resourceSize;
    }

    for (i = visibleCount; i < kResourceBrowserRows; i++) ResourceBrowserClearEntry(i);
    /* More Macintosh Toolbox warns that callers must restore automatic
     * loading promptly because other Toolbox managers rely on the default. */
    if (resLoadDisabled) ResourceBrowserRestoreAutomaticLoading();
    return ok && gResourceError == noErr;
}

static Boolean PrepareResourceBrowser(void)
{
    if (!gResourceBrowserReady) {
        if (!ReadResourceBrowserEntries()) return false;
        gResourceStatus = resourceStatusEnumerated;
        gResourceBrowserReady = true;
    }
    return true;
}

static void RefreshResourceBrowser(void)
{
    if (!PrepareResourceBrowser()) return;
    if (!ReadResourceBrowserEntries()) return;
    gResourceStatus = resourceStatusEnumerated;
}

static void LoadNamedResourceBrowserEntry(void)
{
    Handle handle;

    if (!PrepareResourceBrowser()) return;
    /* First obtain the named reference without reading its data, then restore
     * the normal policy and explicitly materialize it through LoadResource. */
    SetResLoad(false);
    if (!ResourceBrowserCheckError()) {
        ResourceBrowserRestoreAutomaticLoading();
        return;
    }
    handle = GetNamedResource('DATA', "\pMutable Record");
    if (!ResourceBrowserCheckError()) {
        ResourceBrowserRestoreAutomaticLoading();
        return;
    }
    ResourceBrowserRestoreAutomaticLoading();
    if (gResourceError != noErr) return;
    if (handle == nil) {
        gResourceError = -192;
        gResourceStatus = resourceStatusError;
        gResourceEditHandle = nil;
        return;
    }

    gResourceEditHandle = handle;
    LoadResource(gResourceEditHandle);
    if (!ResourceBrowserCheckError() || !ResourceBrowserHandleLoaded(gResourceEditHandle)) {
        if (gResourceError == noErr) gResourceError = -192;
        gResourceStatus = resourceStatusError;
        return;
    }
    if (!ReadResourceBrowserEntries()) return;
    gResourceStatus = resourceStatusLoaded;
}

static void ReleaseNamedResourceBrowserEntry(void)
{
    if (!PrepareResourceBrowser()) return;
    if (gResourceEditHandle == nil) {
        gResourceError = -192;
        gResourceStatus = resourceStatusError;
        return;
    }

    ReleaseResource(gResourceEditHandle);
    if (!ResourceBrowserCheckError()) {
        if (gResourceError == noErr) gResourceError = -192;
        gResourceStatus = resourceStatusError;
        return;
    }
    gResourceEditHandle = nil;
    if (!ReadResourceBrowserEntries()) return;
    gResourceStatus = resourceStatusReleased;
}

static void DrawResourceLifecycleStatus(void)
{
    Str255 number;

    if (gResourceStatus == resourceStatusLoaded) {
        DrawString("\ploaded via GetNamedResource + LoadResource");
    } else if (gResourceStatus == resourceStatusReleased) {
        DrawString("\preleased; map reference is empty");
    } else if (gResourceStatus == resourceStatusError) {
        DrawString("\pResource Manager error ");
        NumToString(gResourceError, number);
        DrawString(number);
    } else {
        DrawString("\penumerated with SetResLoad(FALSE)");
    }
}

static void DrawResourceBrowserPage(void)
{
    Rect table;
    Str255 number;
    Str255 typeName;
    short i;
    short rowTop;

    DrawHeading("\pResource Browser: Resource Manager map and lifecycle");
    TextFont(applFont);
    TextSize(9);
    MoveTo(24, 54);
    DrawString("\pCount1Resources: DATA ");
    NumToString(gResourceCount, number);
    DrawString(number);
    MoveTo(180, 54);
    DrawString("\pMENU ");
    NumToString(gResourceMenuCount, number);
    DrawString(number);
    MoveTo(310, 54);
    DrawString("\pWIND ");
    NumToString(gResourceWindowCount, number);
    DrawString(number);

    MoveTo(24, 68);
    DrawString("\pGet1IndResource + GetResInfo + GetResAttrs + GetResourceSizeOnDisk");
    table.top = 78;
    table.left = 20;
    table.bottom = 170;
    table.right = 540;
    DrawBeveledBox(&table, true);

    MoveTo(28, 91);
    TextFace(bold);
    DrawString("\pType");
    MoveTo(76, 91);
    DrawString("\pID");
    MoveTo(122, 91);
    DrawString("\pName");
    MoveTo(318, 91);
    DrawString("\pAttrs");
    MoveTo(374, 91);
    DrawString("\pSize");
    MoveTo(430, 91);
    DrawString("\pState");
    TextFace(0);

    for (i = 0; i < kResourceBrowserRows; i++) {
        rowTop = 108 + i * 19;
        MoveTo(28, rowTop);
        if (gResourceEntries[i].present) {
            ResourceBrowserTypeString(gResourceEntries[i].type, typeName);
            DrawString(typeName);
        } else {
            DrawString("\p--");
        }
        MoveTo(76, rowTop);
        if (gResourceEntries[i].present) {
            NumToString(gResourceEntries[i].id, number);
            DrawString(number);
        } else {
            DrawString("\p--");
        }
        MoveTo(122, rowTop);
        if (gResourceEntries[i].present) {
            DrawString(gResourceEntries[i].name);
        } else {
            DrawString("\p(no resource)");
        }
        MoveTo(318, rowTop);
        if ((gResourceEntries[i].attrs & 0x0002) != 0) {
            DrawString("\p02 changed");
        } else {
            DrawString("\p00 clean");
        }
        MoveTo(374, rowTop);
        NumToString((short)gResourceEntries[i].size, number);
        DrawString(number);
        MoveTo(430, rowTop);
        DrawString(gResourceEntries[i].loaded ? "\ploaded" : "\pempty");
    }

    MoveTo(24, 192);
    TextFace(bold);
    DrawString("\pSelected: ");
    TextFace(0);
    DrawString("\pDATA 203 \267 Mutable Record");
    MoveTo(24, 210);
    TextFace(bold);
    DrawString("\pLifecycle: ");
    TextFace(0);
    DrawResourceLifecycleStatus();
    MoveTo(24, 228);
    DrawString("\pThe table stays map-backed while resource data moves in and out of memory.");
    MoveTo(24, 338);
    DrawString("\pRefresh re-enumerates deferred references; Load and Release reuse one named record.");

    DrawControls(gMainWindow);
}

/*
 * Page 11: Styled TextEdit and Font Manager measurements.
 * The upper well is the rendered TextEdit record itself. The lower panels
 * report values returned by the same style and measurement APIs that created
 * that record; no parallel swatch model is used. Inside Macintosh: Text
 * (1993), pp. 2-78, 2-98..2-102, and 3-81..3-82.
 */
static void SetStyledStyle(TextStyle *style, short font, Style face,
                           short size, const RGBColor *color)
{
    style->tsFont = font;
    style->tsFace = face;
    style->tsSize = size;
    style->tsColor = *color;
}

static void ApplyStyledStyle(short start, short end, TextStyle *style)
{
    TESetSelect(start, end, gStyledTE);
    TESetStyle(doAll, style, true, gStyledTE);
}

static void InspectStyledText(void)
{
    short textLength;

    if (gStyledTE == nil) return;
    textLength = sizeof(kStyledSampleText) - 1;
    TESetSelect(0, textLength, gStyledTE);
    gStyledInspectMode = doAll;
    gStyledInspectResult = TEContinuousStyle(&gStyledInspectMode,
                                             &gStyledInspectStyle, gStyledTE);

    TESetSelect(7, 11, gStyledTE);
    gStyledRunMode = doAll;
    gStyledRunResult = TEContinuousStyle(&gStyledRunMode,
                                         &gStyledRunStyle, gStyledTE);
    TESetSelect(0, 0, gStyledTE);
}

static void MeasureStyledText(void)
{
    static const char measureText[] = "Styled";
    short charLocations[sizeof(measureText)];
    short count;

    count = sizeof(measureText) - 1;
    TextFont(gStyledGenevaFont);
    TextFace(0);
    TextSize(10);
    gStyledCharWidth = CharWidth('A');
    gStyledTextWidth = TextWidth((Ptr)measureText, 0, count);
    MeasureText(count, (Ptr)measureText, (Ptr)charLocations);
    gStyledMeasureWidth = charLocations[count];
}

static void InitializeStyledText(void)
{
    TextStyle style;
    RGBColor black;
    RGBColor blue;
    RGBColor red;
    RGBColor green;
    RGBColor purple;
    short textLength;

    black.red = black.green = black.blue = 0x0000;
    blue.red = 0x1111; blue.green = 0x2222; blue.blue = 0xdddd;
    red.red = 0xffff; red.green = 0x2222; red.blue = 0x2222;
    green.red = 0x1111; green.green = 0x9999; green.blue = 0x2222;
    purple.red = 0x8888; purple.green = 0x2222; purple.blue = 0x9999;

    /* Text 1993, pp. 4-52..4-53: resolve family names through Font Manager. */
    gStyledGenevaFont = 0;
    gStyledMonacoFont = 0;
    GetFNum("\pGeneva", &gStyledGenevaFont);
    GetFNum("\pMonaco", &gStyledMonacoFont);
    gStyledGenevaReal = gStyledGenevaFont != 0 && RealFont(gStyledGenevaFont, 9);
    gStyledMonacoReal = gStyledMonacoFont != 0 && RealFont(gStyledMonacoFont, 9);

    SetRect(&gStyledTERect, 34, 76, 521, 114);
    TextFont(gStyledGenevaFont);
    TextFace(0);
    TextSize(10);
    RGBForeColor(&black);
    gStyledTE = TEStyleNew(&gStyledTERect, &gStyledTERect);
    if (gStyledTE == nil) return;
    textLength = sizeof(kStyledSampleText) - 1;
    TESetText((const void *)kStyledSampleText, textLength, gStyledTE);

    SetStyledStyle(&style, gStyledGenevaFont, 0, 10, &black);
    ApplyStyledStyle(0, 5, &style);
    SetStyledStyle(&style, gStyledGenevaFont, bold, 12, &blue);
    ApplyStyledStyle(7, 11, &style);
    SetStyledStyle(&style, gStyledMonacoFont, 0, 10, &red);
    ApplyStyledStyle(13, 18, &style);
    SetStyledStyle(&style, gStyledMonacoFont, italic, 14, &green);
    ApplyStyledStyle(20, 24, &style);
    SetStyledStyle(&style, gStyledGenevaFont, underline, 10, &purple);
    ApplyStyledStyle(26, 30, &style);

    InspectStyledText();
    MeasureStyledText();
}

static void DrawStyledTextPage(void)
{
    Rect r;
    Rect well;
    Rect bar;
    Str255 numStr;
    RGBColor white;
    RGBColor black;
    RGBColor blue;
    RGBColor green;
    RGBColor purple;

    white.red = white.green = white.blue = 0xffff;
    black.red = black.green = black.blue = 0x0000;
    blue.red = 0x1111; blue.green = 0x2222; blue.blue = 0xdddd;
    green.red = 0x1111; green.green = 0x9999; green.blue = 0x2222;
    purple.red = 0x8888; purple.green = 0x2222; purple.blue = 0x9999;

    DrawHeading("\pStyled Text & Fonts");
    SetRect(&r, 20, 48, 535, 128);
    DrawBeveledBox(&r, false);
    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(28, 62);
    DrawString("\pTEStyleNew live multistyled record");
    TextFace(0);
    SetRect(&well, 28, 70, 527, 120);
    DrawBeveledBox(&well, true);
    if (gStyledTE != nil) {
        RGBBackColor(&white);
        RGBForeColor(&black);
        EraseRect(&gStyledTERect);
        TEUpdate(&gStyledTERect, gStyledTE);
    }

    SetRect(&r, 20, 138, 300, 310);
    DrawBeveledBox(&r, false);
    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(28, 153);
    DrawString("\pTESetStyle runs (doAll)");
    TextFace(0);
    TextFont(applFont);
    TextSize(9);
    MoveTo(28, 174); DrawString("\pPlain: Geneva 10pt / black");
    MoveTo(28, 189); DrawString("\pBold: Geneva 12pt / blue");
    MoveTo(28, 204); DrawString("\pColor: Monaco 10pt / red");
    MoveTo(28, 219); DrawString("\pSize: Monaco 14pt / italic green");
    MoveTo(28, 234); DrawString("\pFont: Geneva 10pt / underline purple");
    MoveTo(28, 260); DrawString("\pRun boundaries and colors are stored");
    MoveTo(28, 275); DrawString("\pin the live TEStyleHandle.");
    RGBForeColor(&purple);
    MoveTo(28, 294); DrawString("\pThe upper text is the assertion surface.");

    SetRect(&r, 310, 138, 535, 310);
    DrawBeveledBox(&r, false);
    RGBForeColor(&black);
    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(318, 153); DrawString("\pTEContinuousStyle + Font Manager");
    TextFace(0);
    TextFont(applFont);
    TextSize(9);
    MoveTo(318, 172); DrawString("\pAll runs: ");
    DrawString(gStyledInspectResult ? "\pcontinuous" : "\pmixed");
    MoveTo(318, 187); DrawString("\pMode mask: ");
    NumToString(gStyledInspectMode, numStr); DrawString(numStr);
    MoveTo(318, 202); DrawString("\pBold run: ");
    DrawString(gStyledRunResult ? "\pcontinuous" : "\pmixed");
    MoveTo(318, 217); DrawString("\pRun font/size: ");
    NumToString(gStyledRunStyle.tsFont, numStr); DrawString(numStr);
    DrawString("\p / ");
    NumToString(gStyledRunStyle.tsSize, numStr); DrawString(numStr);
    DrawString("\ppt");
    MoveTo(318, 232); DrawString("\pGetFNum: ");
    NumToString(gStyledGenevaFont, numStr); DrawString(numStr);
    DrawString("\p Geneva / ");
    NumToString(gStyledMonacoFont, numStr); DrawString(numStr);
    DrawString("\p Monaco");
    MoveTo(318, 247); DrawString("\pRealFont 9pt: ");
    DrawString(gStyledGenevaReal ? "\pGeneva yes / " : "\pGeneva no / ");
    DrawString(gStyledMonacoReal ? "\pMonaco yes" : "\pMonaco no");

    /* These bars are lengths returned by CharWidth, TextWidth, and MeasureText. */
    MoveTo(318, 263); DrawString("\pMeasured widths");
    SetRect(&r, 395, 257, 520, 305); FrameRect(&r);
    RGBForeColor(&blue);
    SetRect(&bar, 398, 263, 398 + gStyledCharWidth * 5, 270); PaintRect(&bar);
    RGBForeColor(&green);
    SetRect(&bar, 398, 278, 398 + gStyledTextWidth * 2, 285); PaintRect(&bar);
    RGBForeColor(&purple);
    SetRect(&bar, 398, 293, 398 + gStyledMeasureWidth * 2, 300); PaintRect(&bar);
    RGBForeColor(&black);
    MoveTo(318, 270); DrawString("\pChar");
    MoveTo(318, 285); DrawString("\pText");
    MoveTo(318, 300); DrawString("\pCumulative");

    RGBBackColor(&white);
    RGBForeColor(&black);
    MoveTo(20, 335);
    TextFont(applFont);
    TextSize(9);
    DrawString("\pActual TEStyle runs drive the rendered colors, fonts, faces, and measured widths.");
}

/*
 * Page 12: Standard File. Each button deliberately calls a different public
 * entry point. The Open path enters the fixture folder and accepts the sole
 * TEXT item; the legacy Open and Save paths are canceled; both Save paths
 * begin with an editable default name. Inside Macintosh: Files (1992),
 * pp. 3-42--3-54.
 */
static void DrawFileStatus(short status)
{
    if (status == fileStatusAccepted) {
        DrawString("\paccepted");
    } else if (status == fileStatusCancelled) {
        DrawString("\pcancelled");
    } else if (status == fileStatusError) {
        DrawString("\perror");
    } else {
        DrawString("\pnot exercised");
    }
}

static void DrawFileStatusLine(short top, ConstStr255Param label, short status)
{
    MoveTo(32, top);
    DrawString(label);
    DrawFileStatus(status);
}

static void DoStandardFileOpen(void)
{
    StandardGetFile(nil, 1, gFileTypeList, &gFileOpenReply);
    gFileOpenStatus = gFileOpenReply.sfGood ? fileStatusAccepted : fileStatusCancelled;
}

static void DoLegacyFileOpen(void)
{
    Point where;

    where.v = 0;
    where.h = 0;
    SFGetFile(where, "\pCancel this filtered legacy Open", nil, 1,
              gFileTypeList, nil, &gFileLegacyOpenReply);
    gFileLegacyOpenStatus = gFileLegacyOpenReply.good ? fileStatusAccepted : fileStatusCancelled;
}

static void DoStandardFileSave(void)
{
    OSErr err;

    StandardPutFile("\pSave a named fixture", "\pUntitled", &gFileSaveReply);
    if (!gFileSaveReply.sfGood) {
        gFileSaveStatus = fileStatusCancelled;
        return;
    }

    /* The returned FSSpec is consumed by File Manager, then removed so the
     * next Open dialog sees only the immutable fixture entries. */
    err = FSpCreate(&gFileSaveReply.sfFile, 'SHWC', 'TEXT', smSystemScript);
    if (err == noErr) {
        err = FSpDelete(&gFileSaveReply.sfFile);
    }
    gFileSaveStatus = err == noErr ? fileStatusAccepted : fileStatusError;
}

static void DoLegacyFileSave(void)
{
    Point where;

    where.v = 0;
    where.h = 0;
    SFPutFile(where, "\pCancel this legacy Save", "\pUntitled", nil,
              &gFileLegacySaveReply);
    gFileLegacySaveStatus = gFileLegacySaveReply.good ? fileStatusAccepted : fileStatusCancelled;
}

static void DrawStandardFilePage(void)
{
    Rect frame;

    DrawHeading("\pStandard File: Open, Save As, filtering & cancellation");
    TextFont(applFont);
    TextSize(9);
    MoveTo(24, 54);
    DrawString("\pThe fixture folder contains a TEXT document and a DATA file.");
    MoveTo(24, 68);
    DrawString("\pOpen TEXT navigates into it; the other controls exercise legacy APIs.");

    SetRect(&frame, 20, 84, 535, 216);
    DrawBeveledBox(&frame, false);
    TextFace(bold);
    MoveTo(32, 106);
    DrawString("\pReturned record checkpoints");
    TextFace(0);
    MoveTo(32, 126);
    DrawString("\pModern Open: sfGood + sfType + sfFile FSSpec");
    MoveTo(32, 142);
    DrawString("\pLegacy Open: good + fType + vRefNum + fName");
    MoveTo(32, 158);
    DrawString("\pModern Save: editable sfFile name, then FSpCreate/FSpDelete");
    MoveTo(32, 174);
    DrawString("\pLegacy Save: editable fName and SFReply cancellation");

    TextFace(bold);
    DrawFileStatusLine(236, "\pModern Open: ", gFileOpenStatus);
    DrawFileStatusLine(254, "\pLegacy Open: ", gFileLegacyOpenStatus);
    DrawFileStatusLine(272, "\pModern Save: ", gFileSaveStatus);
    DrawFileStatusLine(290, "\pLegacy Save: ", gFileLegacySaveStatus);
    TextFace(0);
    MoveTo(32, 316);
    DrawString("\pAccepted Open returns TEXT; Cancel leaves sfGood/good false.");
    MoveTo(32, 332);
    DrawString("\pNames are MacRoman PStrings and FSSpec directory IDs are checked.");
    DrawControls(gMainWindow);
}

/*
 * Page 14: Sprites, Masks & Scrolling.
 *
 * The scene is deliberately rendered into an 8-bit offscreen GWorld before
 * one CopyBits call presents it in the window. This keeps the source pixels
 * and the 1-bit matte stable while the destination exercises both the 8-bit
 * indexed 68K screen and the direct-color PowerPC screen. CopyMask is the
 * classic sprite operation; CopyDeepMask applies the same source through an
 * 8-bit deep mask and a BitMapToRegion-derived clip. ScrollRect then moves
 * the existing offscreen raster and reports its vacated strip through an
 * update region. Imaging With QuickDraw (1994), pp. 2-20--2-24,
 * 2-43--2-50, 3-119--3-122, and 6-22--6-46.
 */
static void BuildSpriteSource(void)
{
    GWorldPtr savedWorld;
    GDHandle savedDevice;
    Rect full;
    Rect body;
    Rect visor;
    RGBColor background;
    RGBColor bodyColor;
    RGBColor highlight;
    RGBColor black;
    RGBColor white;

    background.red = 0x1111; background.green = 0x2222; background.blue = 0x5555;
    bodyColor.red = gSpriteAnimated ? 0x22ff : 0xff22;
    bodyColor.green = gSpriteAnimated ? 0xdddd : 0x3333;
    bodyColor.blue = gSpriteAnimated ? 0xffff : 0x2222;
    highlight.red = gSpriteAnimated ? 0xffff : 0xffaa;
    highlight.green = gSpriteAnimated ? 0xffff : 0xaa22;
    highlight.blue = gSpriteAnimated ? 0x3333 : 0x1111;
    black.red = black.green = black.blue = 0;
    white.red = white.green = white.blue = 0xffff;

    GetGWorld(&savedWorld, &savedDevice);
    SetGWorld(gSpriteSource, nil);
    SetRect(&full, 0, 0, kSpriteSize, kSpriteSize);
    RGBBackColor(&background);
    EraseRect(&full);

    SetRect(&body, 4, 5, 44, 44);
    RGBForeColor(&bodyColor);
    PaintOval(&body);
    RGBForeColor(&black);
    FrameOval(&body);

    SetRect(&visor, 11, 14, 37, 25);
    RGBForeColor(&highlight);
    PaintRoundRect(&visor, 5, 5);
    RGBForeColor(&black);
    FrameRoundRect(&visor, 5, 5);

    /* A pair of white engine lights makes frame changes obvious. */
    SetRect(&body, 14, 31, 21, 37);
    RGBForeColor(&white);
    PaintOval(&body);
    SetRect(&body, 27, 31, 34, 37);
    PaintOval(&body);
    RGBForeColor(&black);
    SetGWorld(savedWorld, savedDevice);
}

static void BuildSpriteMask(void)
{
    GWorldPtr savedWorld;
    GDHandle savedDevice;
    Rect full;
    Rect body;
    RGBColor black;
    RGBColor white;

    black.red = black.green = black.blue = 0;
    white.red = white.green = white.blue = 0xffff;

    GetGWorld(&savedWorld, &savedDevice);
    SetGWorld(gSpriteMask, nil);
    SetRect(&full, 0, 0, kSpriteSize, kSpriteSize);
    RGBBackColor(&white);
    EraseRect(&full);
    SetRect(&body, 4, 5, 44, 44);
    RGBForeColor(&black);
    PaintOval(&body);
    SetGWorld(savedWorld, savedDevice);
}

static void BuildSpriteDeepMask(void)
{
    GWorldPtr savedWorld;
    GDHandle savedDevice;
    Rect full;
    Rect inner;
    RGBColor black;
    RGBColor white;

    black.red = black.green = black.blue = 0;
    white.red = white.green = white.blue = 0xffff;

    GetGWorld(&savedWorld, &savedDevice);
    SetGWorld(gSpriteDeepMask, nil);
    SetRect(&full, 0, 0, kSpriteSize, kSpriteSize);
    /* The canonical 8-bit GWorld palette maps white to index 0. Keep
       transparent pixels at zero and paint the opaque deep-mask oval black,
       whose nonzero index is accepted by CopyDeepMask. */
    RGBBackColor(&white);
    EraseRect(&full);
    SetRect(&inner, 8, 8, 40, 40);
    RGBForeColor(&black);
    PaintOval(&inner);
    SetGWorld(savedWorld, savedDevice);
}

static void PrepareSpriteScene(void)
{
    GWorldPtr savedWorld;
    GDHandle savedDevice;
    PixMapHandle sourcePixels;
    PixMapHandle maskPixels;
    PixMapHandle deepMaskPixels;
    PixMapHandle worldPixels;
    Rect worldRect;
    Rect sourceRect;
    Rect firstSpriteRect;
    Rect secondSpriteRect;
    Rect stripe;
    RGBColor background;
    RGBColor stripeColor;
    RGBColor accent;
    RGBColor probe;
    RGBColor observed;
    Point regionProbe;
    short x;
    short y;

    gSpritePixelVerified = false;
    gSpriteRegionVerified = false;
    gSpriteUpdateRegionVerified = false;
    gSpriteRegionError = noErr;
    gSpriteScrollDelta = 0;
    gSpriteScrolled = false;
    if (!gSpriteReady) return;

    background.red = 0x1111; background.green = 0x2222; background.blue = 0x5555;
    stripeColor.red = 0x2222; stripeColor.green = 0x5555; stripeColor.blue = 0x8888;
    accent.red = gSpriteAnimated ? 0xeeee : 0x6666;
    accent.green = gSpriteAnimated ? 0xeeee : 0x2222;
    accent.blue = gSpriteAnimated ? 0x3333 : 0xdddd;
    probe.red = 0xffff; probe.green = 0x4444; probe.blue = 0x1111;

    BuildSpriteSource();
    BuildSpriteMask();
    BuildSpriteDeepMask();

    GetGWorld(&savedWorld, &savedDevice);
    SetGWorld(gSpriteWorld, nil);
    SetRect(&worldRect, 0, 0, kSpriteWorldWidth, kSpriteWorldHeight);
    RGBBackColor(&background);
    EraseRect(&worldRect);

    /* Layered bands provide landmarks before and after ScrollRect. */
    RGBForeColor(&stripeColor);
    SetRect(&stripe, 0, 24, kSpriteWorldWidth, 28);
    PaintRect(&stripe);
    SetRect(&stripe, 0, 96, kSpriteWorldWidth, 100);
    PaintRect(&stripe);
    RGBForeColor(&accent);
    for (x = 0; x < kSpriteWorldWidth; x += 32) {
        MoveTo(x, 105);
        LineTo(x + 16, 105);
    }

    /* SetCPixel/GetCPixel are intentionally performed in the offscreen port. */
    SetCPixel(15, 12, &probe);
    GetCPixel(15, 12, &observed);
    gSpritePixelVerified = observed.red > 0x8000 && observed.green < 0x8000;
    for (y = 0; y < 5; y++) {
        SetCPixel(24 + y * 7, 14 + y * 3, &probe);
    }

    SetRect(&sourceRect, 0, 0, kSpriteSize, kSpriteSize);
    SetRect(&firstSpriteRect, 38, 38, 38 + kSpriteSize, 38 + kSpriteSize);
    SetRect(&secondSpriteRect, 214, 38, 214 + kSpriteSize, 38 + kSpriteSize);
    sourcePixels = GetGWorldPixMap(gSpriteSource);
    maskPixels = GetGWorldPixMap(gSpriteMask);
    deepMaskPixels = GetGWorldPixMap(gSpriteDeepMask);
    worldPixels = GetGWorldPixMap(gSpriteWorld);
    if (sourcePixels == nil || maskPixels == nil || deepMaskPixels == nil || worldPixels == nil) {
        SetGWorld(savedWorld, savedDevice);
        return;
    }

    /* CopyMask is a transparent, unscaled sprite transfer. */
    CopyMask((BitMap *)*sourcePixels, (BitMap *)*maskPixels, (BitMap *)*worldPixels,
             &sourceRect, &sourceRect, &firstSpriteRect);

    /* Rebuild the region from the 1-bit matte, then move it to the second sprite. */
    gSpriteRegionError = BitMapToRegion(gSpriteRegion, (BitMap *)*maskPixels);
    OffsetRgn(gSpriteRegion, secondSpriteRect.left, secondSpriteRect.top);
    regionProbe.v = secondSpriteRect.top + 24;
    regionProbe.h = secondSpriteRect.left + 24;
    gSpriteRegionVerified = gSpriteRegionError == noErr
        && !EmptyRgn(gSpriteRegion)
        && PtInRgn(regionProbe, gSpriteRegion);

    /* CopyDeepMask adds a second frame through an 8-bit mask and region clip. */
    CopyDeepMask((BitMap *)*sourcePixels, (BitMap *)*deepMaskPixels, (BitMap *)*worldPixels,
                 &sourceRect, &sourceRect, &secondSpriteRect, srcCopy, gSpriteRegion);

    SetGWorld(savedWorld, savedDevice);
}

static void ScrollSpriteScene(void)
{
    GWorldPtr savedWorld;
    GDHandle savedDevice;
    Rect scrollRect;
    Rect exposed;
    RGBColor background;
    RGBColor accent;
    Point updateProbe;

    if (!gSpriteReady) return;
    background.red = 0x1111; background.green = 0x2222; background.blue = 0x5555;
    accent.red = 0xeeee; accent.green = 0xeeee; accent.blue = 0x3333;

    GetGWorld(&savedWorld, &savedDevice);
    SetGWorld(gSpriteWorld, nil);
    SetRect(&scrollRect, 0, 0, kSpriteWorldWidth, kSpriteWorldHeight);
    SetEmptyRgn(gSpriteUpdateRegion);
    ScrollRect(&scrollRect, gSpriteScrolled ? 24 : -24, 0, gSpriteUpdateRegion);

    /* Repaint the vacated strip with a deterministic landmark after scrolling. */
    if (gSpriteScrolled) {
        SetRect(&exposed, 0, 0, 24, kSpriteWorldHeight);
    } else {
        SetRect(&exposed, kSpriteWorldWidth - 24, 0,
                kSpriteWorldWidth, kSpriteWorldHeight);
    }
    RGBForeColor(&background);
    PaintRect(&exposed);
    RGBForeColor(&accent);
    MoveTo(exposed.left + 4, 18);
    LineTo(exposed.right - 4, 18);
    MoveTo(exposed.left + 4, 110);
    LineTo(exposed.right - 4, 110);

    updateProbe.v = kSpriteWorldHeight / 2;
    updateProbe.h = gSpriteScrolled ? 12 : kSpriteWorldWidth - 12;
    gSpriteUpdateRegionVerified = PtInRgn(updateProbe, gSpriteUpdateRegion);
    gSpriteScrollDelta = gSpriteScrolled ? 24 : -24;
    gSpriteScrolled = !gSpriteScrolled;
    SetGWorld(savedWorld, savedDevice);
}

static void DrawSpritesPage(void)
{
    GWorldPtr savedWorld;
    GDHandle savedDevice;
    PixMapHandle worldPixels;
    PixMapHandle windowPixels;
    Rect worldRect;
    Rect displayRect;
    Rect panel;
    RGBColor black;
    Str255 number;

    black.red = black.green = black.blue = 0;
    DrawHeading("\pSprites, masks, and scrolling");

    SetRect(&panel, 20, 48, 360, 260);
    DrawBeveledBox(&panel, false);
    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(28, 62);
    DrawString("\pOffscreen indexed sprite scene");
    TextFace(0);

    SetRect(&displayRect, 24, 80, 344, 208);
    if (gSpriteReady) {
        GetGWorld(&savedWorld, &savedDevice);
        SetGWorld((GWorldPtr)gMainWindow, nil);
        worldPixels = GetGWorldPixMap(gSpriteWorld);
        windowPixels = GetGWorldPixMap((GWorldPtr)gMainWindow);
        SetRect(&worldRect, 0, 0, kSpriteWorldWidth, kSpriteWorldHeight);
        if (worldPixels != nil && windowPixels != nil) {
            CopyBits((BitMap *)*worldPixels, (BitMap *)*windowPixels,
                     &worldRect, &displayRect, srcCopy, nil);
        }
        RGBForeColor(&black);
        FrameRect(&displayRect);
        SetGWorld(savedWorld, savedDevice);
    } else {
        DrawBeveledBox(&displayRect, true);
    }

    SetRect(&panel, 370, 48, 535, 260);
    DrawBeveledBox(&panel, false);
    TextFont(systemFont);
    TextSize(9);
    TextFace(bold);
    MoveTo(378, 62);
    DrawString("\pQuickDraw pipeline");
    TextFace(0);
    MoveTo(378, 82);
    DrawString("\pCopyMask: 1-bit matte");
    MoveTo(378, 98);
    DrawString("\pCopyDeepMask: deep mask");
    MoveTo(378, 114);
    DrawString("\pBitMapToRegion: shape clip");
    MoveTo(378, 130);
    DrawString("\pSetCPixel/GetCPixel: sample");
    MoveTo(378, 154);
    DrawString("\pPixel round-trip: ");
    DrawString(gSpritePixelVerified ? "\pverified" : "\pnot verified");
    MoveTo(378, 170);
    DrawString("\pRegion round-trip: ");
    DrawString(gSpriteRegionVerified ? "\pverified" : "\pnot verified");
    MoveTo(378, 178);
    DrawString("\pUpdate region: ");
    DrawString(gSpriteUpdateRegionVerified ? "\pverified" : "\pnot verified");
    MoveTo(378, 194);
    DrawString("\pScrollRect delta: ");
    NumToString(gSpriteScrollDelta, number);
    DrawString(number);
    DrawString("\p px");
    MoveTo(378, 210);
    DrawString("\pUpdate strip: ");
    DrawString(gSpriteScrolled ? "\pright" : "\pleft");
    MoveTo(378, 234);
    DrawString(gSpriteRegionError == noErr ? "\pAll mask operations returned noErr."
                                           : "\pBitMapToRegion returned an error.");

    TextFont(applFont);
    TextSize(9);
    MoveTo(24, 280);
    DrawString("\pCopyMask preserves the scene behind the sprite; CopyDeepMask clips a second frame.");
    MoveTo(24, 294);
    DrawString("\pScroll the existing raster to expose a deterministic update region.");
    MoveTo(24, 344);
    DrawString("\pThe same source runs through the 68K indexed and PowerPC direct-color paths.");
    DrawControls(gMainWindow);
}

static void DrawMainWindow(void)
{
    RGBColor white;
    RGBColor black;

    white.red = white.green = white.blue = 0xffff;
    black.red = black.green = black.blue = 0x0000;

    SetPort(gMainWindow);
    RGBBackColor(&white);
    RGBForeColor(&black);
    EraseRect(&gMainWindow->portRect);
    switch (gPage) {
        case pageGraphics:
            DrawGraphicsPage();
            break;
        case pageControls:
            DrawControlsPage();
            break;
        case pageWindows:
            DrawWindowsPage();
            break;
        case pageDrawing:
            DrawDrawingPage();
            break;
        case pagePreferences:
            DrawPreferencesPage();
            break;
        case pageDialogs:
            DrawDialogsPage();
            break;
        case pagePalettes:
            DrawPalettesPage();
            break;
        case pageTextEdit:
            DrawTextEditPage();
            break;
        case pageLists:
            DrawListsPage();
            break;
        case pageSound:
            DrawSoundPage();
            break;
        case pageStyledText:
            DrawStyledTextPage();
            break;
        case pageStandardFile:
            DrawStandardFilePage();
            break;
        case pageResources:
            DrawResourceBrowserPage();
            break;
        case pageSprites:
            DrawSpritesPage();
            break;
    }
}

static void DrawAuxWindow(void)
{
    Str255 sizeStr;
    short width, height;
    if (gAuxWindow == nil) {
        return;
    }
    SetPort(gAuxWindow);
    EraseRect(&gAuxWindow->portRect);
    DrawHeading("\pAuxiliary window");
    MoveTo(24, 68);
    DrawString("\pCreated and destroyed through ordinary Window Manager calls.");
    width = gAuxWindow->portRect.right - gAuxWindow->portRect.left;
    height = gAuxWindow->portRect.bottom - gAuxWindow->portRect.top;
    MoveTo(24, 92);
    DrawString("\pWindow dimensions: ");
    NumToString(width, sizeStr);
    DrawString(sizeStr);
    DrawString("\p x ");
    NumToString(height, sizeStr);
    DrawString(sizeStr);
    DrawGrowIcon(gAuxWindow);
}

static void ShowAllControls(short page)
{
    Boolean isControls = (page == pageControls);
    Boolean isPrefs = (page == pagePreferences);
    Boolean isDialogs = (page == pageDialogs);
    Boolean isPalettes = (page == pagePalettes);
    Boolean isTextEdit = (page == pageTextEdit);
    Boolean isLists = (page == pageLists);
    Boolean isSound = (page == pageSound);
    Boolean isStandardFile = (page == pageStandardFile);
    Boolean isResources = (page == pageResources);
    Boolean isSprites = (page == pageSprites);

    /* Page 2: Controls */
    if (isControls) {
        ShowControl(gButton);
        ShowControl(gCheckbox);
        ShowControl(gScrollbar);
    } else {
        HideControl(gButton);
        HideControl(gCheckbox);
        HideControl(gScrollbar);
    }

    /* Page 5: Game Preferences */
    if (isPrefs) {
        ShowControl(gPrefSndFX);
        ShowControl(gPrefMusic);
        ShowControl(gPrefVolume);
        ShowControl(gPrefDiffEasy);
        ShowControl(gPrefDiffNormal);
        ShowControl(gPrefDiffHard);
        ShowControl(gPrefRendFlat);
        ShowControl(gPrefRendBevel);
        ShowControl(gPrefRendContrast);
        ShowControl(gPrefBtnApply);
        ShowControl(gPrefBtnReset);
        ShowControl(gPrefBtnModal);
    } else {
        HideControl(gPrefSndFX);
        HideControl(gPrefMusic);
        HideControl(gPrefVolume);
        HideControl(gPrefDiffEasy);
        HideControl(gPrefDiffNormal);
        HideControl(gPrefDiffHard);
        HideControl(gPrefRendFlat);
        HideControl(gPrefRendBevel);
        HideControl(gPrefRendContrast);
        HideControl(gPrefBtnApply);
        HideControl(gPrefBtnReset);
        HideControl(gPrefBtnModal);
    }

    /* Page 6: Dialogs */
    if (isDialogs) {
        ShowControl(gDlgBtnOpenPrefs);
        ShowControl(gDlgBtnOpenAlert);
    } else {
        HideControl(gDlgBtnOpenPrefs);
        HideControl(gDlgBtnOpenAlert);
    }

    /* Page 7: Palette Manager */
    if (isPalettes) {
        ShowControl(gPaletteAnimate);
    } else {
        HideControl(gPaletteAnimate);
    }

    /* Page 8: TextEdit */
    if (isTextEdit) {
        ShowControl(gTEJustLeft);
        ShowControl(gTEJustCenter);
        ShowControl(gTEJustRight);
        ShowControl(gTEBtnCut);
        ShowControl(gTEBtnCopy);
        ShowControl(gTEBtnPaste);
        ShowControl(gTEBtnReset);
    } else {
        HideControl(gTEJustLeft);
        HideControl(gTEJustCenter);
        HideControl(gTEJustRight);
        HideControl(gTEBtnCut);
        HideControl(gTEBtnCopy);
        HideControl(gTEBtnPaste);
        HideControl(gTEBtnReset);
    }

    /* Page 9: Lists & Inventory */
    if (isLists) {
        ShowControl(gListInspect);
        ShowControl(gListMutate);
        ShowControl(gListScroll);
        ShowControl(gListResize);
        ShowControl(gListActivate);
    } else {
        HideControl(gListInspect);
        HideControl(gListMutate);
        HideControl(gListScroll);
        HideControl(gListResize);
        HideControl(gListActivate);
    }

    /* Page 10: Sound Manager */
    if (isSound) {
        ShowControl(gSoundBtnBeep);
        ShowControl(gSoundBtnPlay);
        ShowControl(gSoundBtnQueue);
        ShowControl(gSoundBtnFlush);
        ShowControl(gSoundBtnQuiet);
        ShowControl(gSoundBtnComplete);
        ShowControl(gSoundBtnDispose);
    } else {
        HideControl(gSoundBtnBeep);
        HideControl(gSoundBtnPlay);
        HideControl(gSoundBtnQueue);
        HideControl(gSoundBtnFlush);
        HideControl(gSoundBtnQuiet);
        HideControl(gSoundBtnComplete);
        HideControl(gSoundBtnDispose);
    }

    /* Page 12: Standard File */
    if (isStandardFile) {
        ShowControl(gFileOpen);
        ShowControl(gFileLegacyOpen);
        ShowControl(gFileSave);
        ShowControl(gFileLegacySave);
    } else {
        HideControl(gFileOpen);
        HideControl(gFileLegacyOpen);
        HideControl(gFileSave);
        HideControl(gFileLegacySave);
    }

    /* Page 13: Resource Browser */
    if (isResources) {
        ShowControl(gResourceRefresh);
        ShowControl(gResourceLoad);
        ShowControl(gResourceRelease);
    } else {
        HideControl(gResourceRefresh);
        HideControl(gResourceLoad);
        HideControl(gResourceRelease);
    }

    /* Page 14: Sprites, Masks & Scrolling */
    if (isSprites) {
        ShowControl(gSpriteAnimate);
        ShowControl(gSpriteScroll);
        ShowControl(gSpriteReset);
    } else {
        HideControl(gSpriteAnimate);
        HideControl(gSpriteScroll);
        HideControl(gSpriteReset);
    }
}

static void SyncMenuState(void)
{
    MenuHandle pages;
    MenuHandle hDiff;
    MenuHandle hSound;
    MenuHandle hRend;
    short i;

    pages = GetMenuHandle(mPages);
    if (pages != nil) {
        for (i = 1; i <= 14; i++) {
            CheckItem(pages, i, gPage == i);
        }
    }

    hDiff = GetMenuHandle(mDifficulty);
    if (hDiff != nil) {
        CheckItem(hDiff, iDiffEasy, gDifficulty == iDiffEasy);
        CheckItem(hDiff, iDiffNormal, gDifficulty == iDiffNormal);
        CheckItem(hDiff, iDiffHard, gDifficulty == iDiffHard);
    }

    hSound = GetMenuHandle(mSoundMenu);
    if (hSound != nil) {
        CheckItem(hSound, iSndMute, !gSoundFX && !gMusic);
        CheckItem(hSound, iSndFXOnly, gSoundFX && !gMusic);
        CheckItem(hSound, iSndMusicOnly, !gSoundFX && gMusic);
        CheckItem(hSound, iSndFull, gSoundFX && gMusic);
    }

    hRend = GetMenuHandle(mRendererMenu);
    if (hRend != nil) {
        CheckItem(hRend, iRendFlat, gRenderer == iRendFlat);
        CheckItem(hRend, iRendBevel, gRenderer == iRendBevel);
        CheckItem(hRend, iRendContrast, gRenderer == iRendContrast);
    }

    /* Update control handles if created */
    if (gPrefSndFX != nil) {
        SetControlValue(gPrefSndFX, gSoundFX ? 1 : 0);
        SetControlValue(gPrefMusic, gMusic ? 1 : 0);
        SetControlValue(gPrefVolume, gVolume);
        SetControlValue(gPrefDiffEasy, gDifficulty == iDiffEasy ? 1 : 0);
        SetControlValue(gPrefDiffNormal, gDifficulty == iDiffNormal ? 1 : 0);
        SetControlValue(gPrefDiffHard, gDifficulty == iDiffHard ? 1 : 0);
        SetControlValue(gPrefRendFlat, gRenderer == iRendFlat ? 1 : 0);
        SetControlValue(gPrefRendBevel, gRenderer == iRendBevel ? 1 : 0);
        SetControlValue(gPrefRendContrast, gRenderer == iRendContrast ? 1 : 0);
    }

    if (gTEJustLeft != nil) {
        SetControlValue(gTEJustLeft, gTEJust == teJustLeft ? 1 : 0);
        SetControlValue(gTEJustCenter, gTEJust == teJustCenter ? 1 : 0);
        SetControlValue(gTEJustRight, gTEJust == teJustRight ? 1 : 0);
    }

    CheckItem(StateMenu(), iSoundState, gSoundCompleted);
}

static void DoModalPrefsDialog(void)
{
    DialogPtr theDialog;
    short itemHit;
    short itemType;
    Handle itemHandle;
    Rect itemRect;

    theDialog = GetNewDialog(rPrefDialog, nil, (WindowPtr)-1);
    if (theDialog == nil) {
        return;
    }
    SetPort(theDialog);
    ShowWindow(theDialog);

    do {
        ModalDialog(nil, &itemHit);
        if (itemHit == 4 || itemHit == 5) {
            GetDialogItem(theDialog, itemHit, &itemType, &itemHandle, &itemRect);
            SetControlValue((ControlHandle)itemHandle,
                            GetControlValue((ControlHandle)itemHandle) == 0 ? 1 : 0);
        }
    } while (itemHit != 1 && itemHit != 2);

    if (itemHit == 1) {
        gModalDialogCompleted = true;
    }

    DisposeDialog(theDialog);
    SetPort(gMainWindow);
    DrawMainWindow();
}

static void DoAboutAlert(void)
{
    Alert(rAboutAlert, nil);
    SetPort(gMainWindow);
    DrawMainWindow();
}

static void SetPage(short page)
{
    Rect bounds;

    if (gPage == pageSound && page != pageSound) {
        DisposeShowcaseSoundChannel();
    }
    if (gPage == pageTextEdit && page != pageTextEdit) {
        if (gTE != nil) TEDeactivate(gTE);
    }
    if (gPage == pagePalettes && page != pagePalettes) {
        SetPalette(gMainWindow, gOriginalPalette, true);
        ActivatePalette(gMainWindow);
    }
    if (gPage == pageLists && page != pageLists && gInventoryList != nil) {
        LActivate(false, gInventoryList);
        LSetDrawingMode(false, gInventoryList);
    }
    gPage = page;
    if (page == pagePalettes) {
        SetPalette(gMainWindow, gShowcasePalette, true);
        ActivatePalette(gMainWindow);
    }
    if (page == pageTextEdit) {
        if (gTE != nil) TEActivate(gTE);
    }
    if (page == pageLists && gInventoryList != nil) {
        gListActive = true;
        LSetDrawingMode(true, gInventoryList);
        LActivate(true, gInventoryList);
    }
    if (page == pageSound) {
        EnsureShowcaseSoundChannel();
    }
    if (page == pageResources) {
        PrepareResourceBrowser();
    }
    if (page == pageSprites) {
        PrepareSpriteScene();
    }
    ShowAllControls(page);
    SyncMenuState();

    if (page == pageWindows && gAuxWindow == nil) {
        SetRect(&bounds, 180, 155, 570, 300);
        gAuxWindow = NewCWindow(nil, &bounds, "\pAuxiliary Window", true,
                                zoomDocProc, (WindowPtr)-1, true, 0);
        CheckItem(StateMenu(), iWindowState, gAuxWindow != nil);
        DrawAuxWindow();
    } else if (page != pageWindows && gAuxWindow != nil) {
        DisposeWindow(gAuxWindow);
        gAuxWindow = nil;
        CheckItem(StateMenu(), iWindowState, false);
    }

    DrawMainWindow();
}

static void Initialize(void)
{
    Handle menuBar;
    MenuHandle hMenu;
    Rect r;
    Rect dataBounds;
    Rect sourceRect;
    Point cellSize;

    InitGraf(&qd.thePort);
    InitFonts();
    InitWindows();
    InitMenus();
    TEInit();
    InitDialogs(nil);
    InitCursor();

    menuBar = GetNewMBar(rMenuBar);
    if (menuBar == nil) {
        ExitToShell();
    }
    SetMenuBar(menuBar);
    DisposeHandle(menuBar);

    /* Insert hierarchical submenus into the hierarchical partition (-1) */
    hMenu = GetMenu(mOptions);
    if (hMenu != nil) InsertMenu(hMenu, -1);
    hMenu = GetMenu(mDifficulty);
    if (hMenu != nil) InsertMenu(hMenu, -1);
    hMenu = GetMenu(mSoundMenu);
    if (hMenu != nil) InsertMenu(hMenu, -1);
    hMenu = GetMenu(mRendererMenu);
    if (hMenu != nil) InsertMenu(hMenu, -1);

    DrawMenuBar();

    gMainWindow = GetNewCWindow(rMainWindow, nil, (WindowPtr)-1);
    if (gMainWindow == nil) {
        ExitToShell();
    }
    SetPort(gMainWindow);
    TextFont(applFont);
    TextSize(9);
    ShowWindow(gMainWindow);

    gOriginalPalette = GetPalette(gMainWindow);
    if (gOriginalPalette == nil) {
        gOriginalPalette = GetNewPalette(0);
    }
    gShowcasePalette = GetNewPalette(rShowcasePalette);
    SetPalette(gMainWindow, gOriginalPalette, true);
    ActivatePalette(gMainWindow);

    /* Page 2: Controls */
    SetRect(&r, 40, 255, 150, 279);
    gButton = NewControl(gMainWindow, &r, "\pActivate", false, 0, 0, 1,
                         pushButProc, 0);
    SetRect(&r, 185, 255, 315, 279);
    gCheckbox = NewControl(gMainWindow, &r, "\pCheckbox", false, 0, 0, 1,
                           checkBoxProc, 0);
    SetRect(&r, 40, 310, 500, 326);
    gScrollbar = NewControl(gMainWindow, &r, "\p", false, 0, 0, 10,
                            scrollBarProc, 0);

    /* Page 5: Game Preferences Controls */
    SetRect(&r, 35, 70, 210, 90);
    gPrefSndFX = NewControl(gMainWindow, &r, "\pSound Effects (SFX)", false, 1, 0, 1,
                            checkBoxProc, 0);
    SetRect(&r, 35, 95, 210, 115);
    gPrefMusic = NewControl(gMainWindow, &r, "\pBackground Music", false, 1, 0, 1,
                            checkBoxProc, 0);
    SetRect(&r, 35, 195, 215, 211);
    gPrefVolume = NewControl(gMainWindow, &r, "\p", false, 75, 0, 100,
                             scrollBarProc, 0);

    SetRect(&r, 250, 70, 390, 90);
    gPrefDiffEasy = NewControl(gMainWindow, &r, "\pRecruit (Easy)", false, 0, 0, 1,
                               radioButProc, 0);
    SetRect(&r, 250, 95, 390, 115);
    gPrefDiffNormal = NewControl(gMainWindow, &r, "\pVeteran (Normal)", false, 1, 0, 1,
                                 radioButProc, 0);
    SetRect(&r, 250, 120, 390, 140);
    gPrefDiffHard = NewControl(gMainWindow, &r, "\pNightmare (Hard)", false, 0, 0, 1,
                               radioButProc, 0);

    SetRect(&r, 250, 195, 420, 215);
    gPrefRendFlat = NewControl(gMainWindow, &r, "\pClassic 2D Flat", false, 0, 0, 1,
                               radioButProc, 0);
    SetRect(&r, 250, 215, 420, 235);
    gPrefRendBevel = NewControl(gMainWindow, &r, "\pQD3D Bevels (Emul.)", false, 1, 0, 1,
                                radioButProc, 0);
    SetRect(&r, 250, 235, 420, 255);
    gPrefRendContrast = NewControl(gMainWindow, &r, "\pHigh Contrast", false, 0, 0, 1,
                                   radioButProc, 0);

    SetRect(&r, 35, 315, 145, 339);
    gPrefBtnApply = NewControl(gMainWindow, &r, "\pSave & Apply", false, 0, 0, 1,
                               pushButProc, 0);
    SetRect(&r, 160, 315, 270, 339);
    gPrefBtnReset = NewControl(gMainWindow, &r, "\pReset Defaults", false, 0, 0, 1,
                               pushButProc, 0);
    SetRect(&r, 285, 315, 425, 339);
    gPrefBtnModal = NewControl(gMainWindow, &r, "\pModal Dialog\311", false, 0, 0, 1,
                               pushButProc, 0);

    /* Page 6: Dialogs Controls */
    SetRect(&r, 40, 305, 220, 329);
    gDlgBtnOpenPrefs = NewControl(gMainWindow, &r, "\pOpen Modal Dialog\311", false, 0, 0, 1,
                                  pushButProc, 0);
    SetRect(&r, 240, 305, 410, 329);
    gDlgBtnOpenAlert = NewControl(gMainWindow, &r, "\pDisplay About Alert…", false, 0, 0, 1,
                                  pushButProc, 0);

    /* Page 7: Palette Manager Control */
    SetRect(&r, 40, 342, 230, 366);
    gPaletteAnimate = NewControl(gMainWindow, &r, "\pAnimate Palette", false, 0, 0, 1,
                                 pushButProc, 0);

    /* Page 8: TextEdit Controls */
    SetRect(&gTERect, 34, 76, 326, 211);
    gTE = TENew(&gTERect, &gTERect);
    if (gTE != nil) {
        TESetText((const void *)kTESampleText, sizeof(kTESampleText) - 1, gTE);
        TESetSelect(0, 0, gTE);
    }

    SetRect(&r, 360, 168, 412, 188);
    gTEJustLeft = NewControl(gMainWindow, &r, "\pLeft", false, 1, 0, 1,
                             radioButProc, 0);
    SetRect(&r, 416, 168, 474, 188);
    gTEJustCenter = NewControl(gMainWindow, &r, "\pCenter", false, 0, 0, 1,
                               radioButProc, 0);
    SetRect(&r, 478, 168, 530, 188);
    gTEJustRight = NewControl(gMainWindow, &r, "\pRight", false, 0, 0, 1,
                              radioButProc, 0);

    SetRect(&r, 28, 256, 100, 280);
    gTEBtnCut = NewControl(gMainWindow, &r, "\pCut", false, 0, 0, 1,
                           pushButProc, 0);
    SetRect(&r, 106, 256, 178, 280);
    gTEBtnCopy = NewControl(gMainWindow, &r, "\pCopy", false, 0, 0, 1,
                            pushButProc, 0);
    SetRect(&r, 184, 256, 256, 280);
    gTEBtnPaste = NewControl(gMainWindow, &r, "\pPaste", false, 0, 0, 1,
                             pushButProc, 0);
    SetRect(&r, 262, 256, 332, 280);
    gTEBtnReset = NewControl(gMainWindow, &r, "\pReset", false, 0, 0, 1,
                             pushButProc, 0);

    /* Page 9: Lists & Inventory */
    SetRect(&gInventoryView, 24, 78, 528, 228);
    SetRect(&dataBounds, 0, 0, 1, 1);
    cellSize.v = 18;
    cellSize.h = 504;
    gInventoryList = LNew(&gInventoryView, &dataBounds, cellSize, 0,
                          gMainWindow, false, true, false, true);
    PopulateInventoryList();
    if (gInventoryList != nil) LSetDrawingMode(false, gInventoryList);

    SetRect(&r, 24, 242, 135, 266);
    gListInspect = NewControl(gMainWindow, &r, "\pInspect Selection", false, 0, 0, 1,
                              pushButProc, 0);
    SetRect(&r, 143, 242, 270, 266);
    gListMutate = NewControl(gMainWindow, &r, "\pUpdate Selected Row", false, 0, 0, 1,
                             pushButProc, 0);
    SetRect(&r, 278, 242, 390, 266);
    gListScroll = NewControl(gMainWindow, &r, "\pScroll Four Rows", false, 0, 0, 1,
                             pushButProc, 0);
    SetRect(&r, 398, 242, 514, 266);
    gListResize = NewControl(gMainWindow, &r, "\pResize List", false, 0, 0, 1,
                             pushButProc, 0);
    SetRect(&r, 24, 274, 170, 298);
    gListActivate = NewControl(gMainWindow, &r, "\pToggle Activation", false, 0, 0, 1,
                               pushButProc, 0);

    /* Page 10: Sound Manager Controls */
    SetRect(&r, 20, 255, 105, 279);
    gSoundBtnBeep = NewControl(gMainWindow, &r, "\pSysBeep", false, 0, 0, 1,
                               pushButProc, 0);
    SetRect(&r, 110, 255, 205, 279);
    gSoundBtnPlay = NewControl(gMainWindow, &r, "\pPlay snd", false, 0, 0, 1,
                               pushButProc, 0);
    SetRect(&r, 210, 255, 315, 279);
    gSoundBtnQueue = NewControl(gMainWindow, &r, "\pQueue cmds", false, 0, 0, 1,
                                pushButProc, 0);
    SetRect(&r, 320, 255, 385, 279);
    gSoundBtnFlush = NewControl(gMainWindow, &r, "\pFlush", false, 0, 0, 1,
                                pushButProc, 0);
    SetRect(&r, 390, 255, 455, 279);
    gSoundBtnQuiet = NewControl(gMainWindow, &r, "\pQuiet", false, 0, 0, 1,
                                pushButProc, 0);
    SetRect(&r, 20, 290, 145, 314);
    gSoundBtnComplete = NewControl(gMainWindow, &r, "\pPlay to complete", false, 0, 0, 1,
                                   pushButProc, 0);
    SetRect(&r, 150, 290, 250, 314);
    gSoundBtnDispose = NewControl(gMainWindow, &r, "\pDispose", false, 0, 0, 1,
                                  pushButProc, 0);

    /* Page 11: Styled TextEdit & Font Manager */
    InitializeStyledText();

    /* Page 12: Standard File */
    gFileTypeList[0] = 'TEXT';
    gFileTypeList[1] = 0;
    gFileTypeList[2] = 0;
    gFileTypeList[3] = 0;
    SetRect(&r, 24, 204, 148, 228);
    gFileOpen = NewControl(gMainWindow, &r, "\pOpen TEXT", false, 0, 0, 1,
                           pushButProc, 0);
    SetRect(&r, 158, 204, 294, 228);
    gFileLegacyOpen = NewControl(gMainWindow, &r, "\pLegacy Open", false, 0, 0, 1,
                                 pushButProc, 0);
    SetRect(&r, 304, 204, 416, 228);
    gFileSave = NewControl(gMainWindow, &r, "\pSave As", false, 0, 0, 1,
                           pushButProc, 0);
    SetRect(&r, 426, 204, 535, 228);
    gFileLegacySave = NewControl(gMainWindow, &r, "\pLegacy Save", false, 0, 0, 1,
                                 pushButProc, 0);

    /* Page 13: Resource Browser */
    SetRect(&r, 24, 252, 132, 276);
    gResourceRefresh = NewControl(gMainWindow, &r, "\pRefresh Map", false, 0, 0, 1,
                                  pushButProc, 0);
    SetRect(&r, 140, 252, 260, 276);
    gResourceLoad = NewControl(gMainWindow, &r, "\pLoad Named", false, 0, 0, 1,
                               pushButProc, 0);
    SetRect(&r, 268, 252, 388, 276);
    gResourceRelease = NewControl(gMainWindow, &r, "\pRelease Handle", false, 0, 0, 1,
                                  pushButProc, 0);

    /* Page 14: Sprites, Masks & Scrolling */
    SetRect(&dataBounds, 0, 0, kSpriteWorldWidth, kSpriteWorldHeight);
    SetRect(&sourceRect, 0, 0, kSpriteSize, kSpriteSize);
    gSpriteWorld = nil;
    gSpriteSource = nil;
    gSpriteMask = nil;
    gSpriteDeepMask = nil;
    gSpriteRegion = NewRgn();
    gSpriteUpdateRegion = NewRgn();
    if (NewGWorld(&gSpriteWorld, 8, &dataBounds, nil, nil, 0) == noErr
        && NewGWorld(&gSpriteSource, 8, &sourceRect, nil, nil, 0) == noErr
        && NewGWorld(&gSpriteMask, 1, &sourceRect, nil, nil, 0) == noErr
        && NewGWorld(&gSpriteDeepMask, 8, &sourceRect, nil, nil, 0) == noErr
        && gSpriteRegion != nil && gSpriteUpdateRegion != nil) {
        gSpriteReady = true;
    }
    SetRect(&r, 35, 304, 145, 328);
    gSpriteAnimate = NewControl(gMainWindow, &r, "\pAnimate Sprite", false, 0, 0, 1,
                                pushButProc, 0);
    SetRect(&r, 153, 304, 263, 328);
    gSpriteScroll = NewControl(gMainWindow, &r, "\pScroll Scene", false, 0, 0, 1,
                               pushButProc, 0);
    SetRect(&r, 271, 304, 365, 328);
    gSpriteReset = NewControl(gMainWindow, &r, "\pReset Scene", false, 0, 0, 1,
                              pushButProc, 0);

    SetPage(pageGraphics);
}

static void DoMenuChoice(long choice)
{
    short menuID;
    short item;

    menuID = HiWord(choice);
    item = LoWord(choice);

    if (menuID == mPages && item >= iGraphics && item <= iSprites) {
        SetPage(item);
    } else if (menuID == mDifficulty) {
        gDifficulty = item;
        SyncMenuState();
        DrawMainWindow();
    } else if (menuID == mSoundMenu) {
        if (item == iSndMute) {
            gSoundFX = false;
            gMusic = false;
        } else if (item == iSndFXOnly) {
            gSoundFX = true;
            gMusic = false;
        } else if (item == iSndMusicOnly) {
            gSoundFX = false;
            gMusic = true;
        } else if (item == iSndFull) {
            gSoundFX = true;
            gMusic = true;
        }
        SyncMenuState();
        DrawMainWindow();
    } else if (menuID == mRendererMenu) {
        gRenderer = item;
        SyncMenuState();
        DrawMainWindow();
    } else if (menuID == mOptions) {
        if (item == iOptResetPrefs) {
            gDifficulty = iDiffNormal;
            gSoundFX = true;
            gMusic = true;
            gVolume = 75;
            gRenderer = iRendBevel;
            SyncMenuState();
            DrawMainWindow();
        } else if (item == iOptLaunchDialog) {
            DoModalPrefsDialog();
        }
    } else if (menuID == mFile) {
        if (item == iFilePrefs) {
            SetPage(pagePreferences);
        } else if (item == iQuit) {
            gQuit = true;
        }
    } else if (menuID == mApple) {
        if (item == iAbout) {
            DoAboutAlert();
        }
    }
    HiliteMenu(0);
}

static void DoContentClick(WindowPtr window, EventRecord *event)
{
    ControlHandle control;
    short part;
    short trackedPart;
    short value;
    Point where;
    Rect listHit;

    if (window != gMainWindow) {
        return;
    }
    SetPort(window);
    where = event->where;
    GlobalToLocal(&where);

    if (gPage == pageTextEdit && gTE != nil && PtInRect(where, &gTERect)) {
        Boolean shift = (event->modifiers & shiftKey) != 0;
        TEClick(where, shift, gTE);
        DrawMainWindow();
        return;
    }

    if (gPage == pageLists && gInventoryList != nil && gListActive) {
        /* LClick also accepts the List Manager scroll-bar strip. */
        listHit = gInventoryView;
        listHit.top -= 1;
        listHit.bottom += 1;
        listHit.right += 16;
        if (PtInRect(where, &listHit)) {
            LClick(where, event->modifiers, gInventoryList);
            InspectInventorySelection();
            DrawMainWindow();
            return;
        }
    }

    part = FindControl(where, window, &control);
    if (part == 0) {
        return;
    }
    trackedPart = TrackControl(control, where, nil);
    if (trackedPart == 0) {
        return;
    }
    part = trackedPart;

    if (control == gButton) {
        gButtonActivated = !gButtonActivated;
        CheckItem(StateMenu(), iButtonState, gButtonActivated);
    } else if (control == gCheckbox) {
        value = GetControlValue(gCheckbox) == 0 ? 1 : 0;
        SetControlValue(gCheckbox, value);
        CheckItem(StateMenu(), iCheckboxState, value != 0);
    } else if (control == gScrollbar) {
        value = GetControlValue(gScrollbar);
        if (part == kControlUpButtonPart || part == kControlPageUpPart) {
            value -= part == kControlPageUpPart ? 3 : 1;
        } else if (part == kControlDownButtonPart || part == kControlPageDownPart) {
            value += part == kControlPageDownPart ? 3 : 1;
        }
        if (value < 0) value = 0;
        if (value > 10) value = 10;
        SetControlValue(gScrollbar, value);
        CheckItem(StateMenu(), iScrollbarState,
                  GetControlValue(gScrollbar) != 0);
    } else if (control == gPrefSndFX) {
        gSoundFX = !gSoundFX;
        SyncMenuState();
    } else if (control == gPrefMusic) {
        gMusic = !gMusic;
        SyncMenuState();
    } else if (control == gPrefVolume) {
        value = GetControlValue(gPrefVolume);
        if (part == kControlUpButtonPart || part == kControlPageUpPart) {
            value -= part == kControlPageUpPart ? 15 : 5;
        } else if (part == kControlDownButtonPart || part == kControlPageDownPart) {
            value += part == kControlPageDownPart ? 15 : 5;
        }
        if (value < 0) value = 0;
        if (value > 100) value = 100;
        gVolume = value;
        SetControlValue(gPrefVolume, gVolume);
    } else if (control == gPrefDiffEasy) {
        gDifficulty = iDiffEasy;
        SyncMenuState();
    } else if (control == gPrefDiffNormal) {
        gDifficulty = iDiffNormal;
        SyncMenuState();
    } else if (control == gPrefDiffHard) {
        gDifficulty = iDiffHard;
        SyncMenuState();
    } else if (control == gPrefRendFlat) {
        gRenderer = iRendFlat;
        SyncMenuState();
    } else if (control == gPrefRendBevel) {
        gRenderer = iRendBevel;
        SyncMenuState();
    } else if (control == gPrefRendContrast) {
        gRenderer = iRendContrast;
        SyncMenuState();
    } else if (control == gPrefBtnApply) {
        /* Save / Apply feedback */
        SyncMenuState();
    } else if (control == gPrefBtnReset) {
        gDifficulty = iDiffNormal;
        gSoundFX = true;
        gMusic = true;
        gVolume = 75;
        gRenderer = iRendBevel;
        SyncMenuState();
    } else if (control == gPrefBtnModal || control == gDlgBtnOpenPrefs) {
        DoModalPrefsDialog();
        return;
    } else if (control == gDlgBtnOpenAlert) {
        DoAboutAlert();
        return;
    } else if (control == gPaletteAnimate) {
        AnimateShowcasePalette();
        return;
    } else if (control == gSoundBtnBeep) {
        SysBeep(30);
        gSoundBeeped = true;
    } else if (control == gSoundBtnPlay) {
        PlayShowcaseSound(false);
    } else if (control == gSoundBtnQueue) {
        QueueShowcaseSoundCommands();
    } else if (control == gSoundBtnFlush) {
        FlushShowcaseSound();
    } else if (control == gSoundBtnQuiet) {
        QuietShowcaseSound();
    } else if (control == gSoundBtnComplete) {
        PlayShowcaseSound(true);
    } else if (control == gSoundBtnDispose) {
        DisposeShowcaseSoundChannel();
    } else if (control == gTEJustLeft) {
        gTEJust = teJustLeft;
        TESetAlignment(teJustLeft, gTE);
        SyncMenuState();
    } else if (control == gTEJustCenter) {
        gTEJust = teJustCenter;
        TESetAlignment(teJustCenter, gTE);
        SyncMenuState();
    } else if (control == gTEJustRight) {
        gTEJust = teJustRight;
        TESetAlignment(teJustRight, gTE);
        SyncMenuState();
    } else if (control == gTEBtnCut) {
        TECut(gTE);
    } else if (control == gTEBtnCopy) {
        TECopy(gTE);
    } else if (control == gTEBtnPaste) {
        TEPaste(gTE);
    } else if (control == gTEBtnReset) {
        TESetText((const void *)kTESampleText, sizeof(kTESampleText) - 1, gTE);
        TESetSelect(0, 14, gTE);
    } else if (control == gListInspect) {
        InspectInventorySelection();
    } else if (control == gListMutate) {
        MutateInventorySelection();
    } else if (control == gListScroll) {
        ScrollInventoryList();
    } else if (control == gListResize) {
        ResizeInventoryList();
    } else if (control == gListActivate) {
        ToggleInventoryActivation();
    } else if (control == gFileOpen) {
        DoStandardFileOpen();
        DrawMainWindow();
        return;
    } else if (control == gFileLegacyOpen) {
        DoLegacyFileOpen();
        DrawMainWindow();
        return;
    } else if (control == gFileSave) {
        DoStandardFileSave();
        DrawMainWindow();
        return;
    } else if (control == gFileLegacySave) {
        DoLegacyFileSave();
        DrawMainWindow();
        return;
    } else if (control == gResourceRefresh) {
        RefreshResourceBrowser();
    } else if (control == gResourceLoad) {
        LoadNamedResourceBrowserEntry();
    } else if (control == gResourceRelease) {
        ReleaseNamedResourceBrowserEntry();
    } else if (control == gSpriteAnimate) {
        gSpriteAnimated = !gSpriteAnimated;
        PrepareSpriteScene();
    } else if (control == gSpriteScroll) {
        ScrollSpriteScene();
    } else if (control == gSpriteReset) {
        gSpriteAnimated = false;
        PrepareSpriteScene();
    }
    DrawMainWindow();
}

static void DoEvent(EventRecord *event)
{
    WindowPtr window;
    short part;
    char key;

    switch (event->what) {
        case mouseDown:
            part = FindWindow(event->where, &window);
            if (part == inMenuBar) {
                DoMenuChoice(MenuSelect(event->where));
            } else if (part == inContent) {
                if (window != FrontWindow()) {
                    SelectWindow(window);
                } else {
                    DoContentClick(window, event);
                }
            } else if (part == inDrag) {
                DragWindow(window, event->where, &qd.screenBits.bounds);
            } else if (part == inGrow) {
                Rect sizeRect;
                long growResult;
                SetRect(&sizeRect, 180, 100, 520, 350);
                growResult = GrowWindow(window, event->where, &sizeRect);
                if (growResult != 0) {
                    SizeWindow(window, LoWord(growResult), HiWord(growResult), true);
                    SetPort(window);
                    InvalRect(&window->portRect);
                }
            } else if ((part == inZoomIn || part == inZoomOut) && TrackBox(window, event->where, part)) {
                ZoomWindow(window, part, window == FrontWindow());
                SetPort(window);
                InvalRect(&window->portRect);
            } else if (part == inGoAway && TrackGoAway(window, event->where)) {
                if (window == gAuxWindow) {
                    DisposeWindow(gAuxWindow);
                    gAuxWindow = nil;
                    CheckItem(StateMenu(), iWindowState, false);
                } else {
                    gQuit = true;
                }
            }
            break;

        case activateEvt:
            window = (WindowPtr)event->message;
            if (window == gMainWindow && gInventoryList != nil) {
                gListActive = (event->modifiers & activeFlag) != 0;
                LActivate(gListActive, gInventoryList);
                if (gPage == pageLists) DrawMainWindow();
            }
            break;

        case keyDown:
        case autoKey:
            key = (char)(event->message & charCodeMask);
            if ((event->modifiers & cmdKey) != 0) {
                DoMenuChoice(MenuKey(key));
            } else if (gPage == pageTextEdit && gTE != nil) {
                TEKey(key, gTE);
                DrawMainWindow();
            }
            break;

        case updateEvt:
            window = (WindowPtr)event->message;
            BeginUpdate(window);
            if (window == gMainWindow) {
                DrawMainWindow();
            } else if (window == gAuxWindow) {
                DrawAuxWindow();
            }
            EndUpdate(window);
            break;
    }
}

void main(void)
{
    EventRecord event;

    Initialize();
    while (!gQuit) {
        if (WaitNextEvent(everyEvent, &event, 1, nil)) {
            DoEvent(&event);
        } else if (gPage == pageTextEdit && gTE != nil) {
            TEIdle(gTE);
        } else if (gPage == pageSound) {
            PollShowcaseSound();
        }
    }
    DisposeShowcaseSoundChannel();
    SetPalette(gMainWindow, nil, true);
    if (gShowcasePalette != nil) DisposePalette(gShowcasePalette);
    if (gOriginalPalette != nil) DisposePalette(gOriginalPalette);
    if (gTE != nil) TEDispose(gTE);
    if (gStyledTE != nil) TEDispose(gStyledTE);
    if (gInventoryList != nil) {
        LActivate(false, gInventoryList);
        LDispose(gInventoryList);
    }
    ExitToShell();
}