systemless 0.70.1

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
//! Native macOS framebuffer presentation.
//!
//! `softbuffer`'s AppKit backend creates a new `CGImage` for every present.
//! Core Animation then copies and color-converts that image on the CPU.  A
//! continuously animating 800x600 game can spend most of a host core in that
//! conversion path. This presenter keeps a `CAMetalLayer`, command queue,
//! render pipeline, and two upload textures alive for the window lifetime.
//! Native guest and high-resolution raster frames share a latest-frame mailbox to a Metal
//! worker paced by drawable availability. Thus a full drawable queue never
//! blocks AppKit input handling or 68k execution. Retained high-resolution
//! text arrives as a compact cell/detail image that the GPU resolves directly
//! at the drawable size, like the Windows D3D11 and browser presenters.

use std::ffi::c_void;
use std::ptr::NonNull;
use std::rc::Rc;
use std::sync::{Arc, Condvar, Mutex};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use objc2::rc::{autoreleasepool, Retained};
use objc2::runtime::{NSObject, ProtocolObject};
use objc2::{msg_send, msg_send_id};
use objc2_foundation::{ns_string, CGRect, MainThreadMarker};
use objc2_metal::{
    MTLBuffer, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLCreateSystemDefaultDevice,
    MTLDevice, MTLDrawable, MTLLibrary, MTLLoadAction, MTLPixelFormat, MTLPrimitiveType, MTLRegion,
    MTLRenderCommandEncoder, MTLRenderPassDescriptor, MTLRenderPipelineDescriptor,
    MTLRenderPipelineState, MTLResourceOptions, MTLStorageMode, MTLStoreAction, MTLTexture,
    MTLTextureDescriptor, MTLTextureUsage, MTLViewport,
};
use objc2_quartz_core::{
    kCAGravityBottom, CAAutoresizingMask, CALayer, CAMetalDrawable, CAMetalLayer,
};
use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle};
use winit::window::Window;

use systemless::display::CursorImage;
use systemless::memory::CompactPresentation;

// Double buffering prevents the CPU from overwriting the texture used by the
// in-flight GPU frame without allowing a third drawable to queue and add input
// latency. The 800x600 upload is far below the GPU throughput limit.
const FRAME_RESOURCE_COUNT: usize = 2;

#[repr(C)]
#[derive(Clone, Copy, Default, Eq, PartialEq)]
struct GuestFrameUniforms {
    row_bytes: u32,
    width: u32,
    height: u32,
    pixel_size: u32,
    content_left: u32,
    content_top: u32,
    cursor_kind: u32,
    cursor_width: u32,
    cursor_height: u32,
    cursor_left: i32,
    cursor_top: i32,
}

/// Must match `CompactFrameUniforms` in metal_present.metal. Crop values are
/// logical guest pixels; the viewport (`ox`, `oy`, `dw`, `dh`) is drawable
/// pixels, so the shader's coverage arithmetic stays exact integers.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
struct CompactFrameUniforms {
    width: u32,
    height: u32,
    scale: u32,
    crop_left: u32,
    crop_top: u32,
    crop_width: u32,
    crop_height: u32,
    dw: u32,
    dh: u32,
    ox: u32,
    oy: u32,
}

#[repr(C)]
#[derive(Clone, Eq, PartialEq)]
struct GuestCursorData {
    data_rows: [u32; 16],
    mask_rows: [u32; 16],
    color_pixels: [u32; 256],
}

#[derive(Clone, Eq, PartialEq)]
struct GuestFrameMetadata {
    screen_layout: (u32, u16, u16, u16),
    content_rect: (u32, u32, u32, u32),
    palette: [u32; 256],
    uniforms: GuestFrameUniforms,
    cursor: GuestCursorData,
    drawable_size: (u32, u32),
}

#[derive(Default)]
struct GuestFrameProfile {
    attempts: u64,
    unchanged: u64,
    forced: u64,
    comparison_time: Duration,
    presentation_time: Duration,
}

#[derive(Clone, PartialEq, Eq)]
enum FrameMetadata {
    Guest(GuestFrameMetadata),
    Raster {
        layout: RasterLayout,
        drawable_size: (u32, u32),
    },
    Compact(CompactFrameUniforms),
}

/// Which pixels the presenter must show, and where they sit in the frame buffer
/// that carries them.
///
/// The raster path hands its caller's whole frame buffer to the mailbox without
/// cropping it, so the worker uploads `left`/`top`/`width`/`height` in place
/// using `buffer_width` as the row stride. A cropped presentation therefore
/// never materialises a cropped copy of the frame.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RasterLayout {
    pub left: u32,
    pub top: u32,
    pub width: u32,
    pub height: u32,
    pub buffer_width: u32,
}

impl RasterLayout {
    /// The rectangle covering all of `size`, for a frame presented uncropped.
    fn whole(size: (u32, u32)) -> Self {
        Self {
            left: 0,
            top: 0,
            width: size.0,
            height: size.1,
            buffer_width: size.0,
        }
    }

    /// Byte offset of the rectangle's first texel inside a buffer of `byte_len`
    /// bytes, or `None` when the rectangle reaches past the buffer.
    fn texel_byte_offset(&self, byte_len: usize) -> Option<usize> {
        if self.width == 0 || self.height == 0 {
            return None;
        }
        if self.left.checked_add(self.width)? > self.buffer_width {
            return None;
        }
        let last_row = u64::from(self.top).checked_add(u64::from(self.height) - 1)?;
        let last_texel = last_row
            .checked_mul(u64::from(self.buffer_width))?
            .checked_add(u64::from(self.left))?
            .checked_add(u64::from(self.width))?;
        if last_texel.checked_mul(size_of::<u32>() as u64)? > u64::try_from(byte_len).ok()? {
            return None;
        }
        let first_texel = u64::from(self.top)
            .checked_mul(u64::from(self.buffer_width))?
            .checked_add(u64::from(self.left))?;
        usize::try_from(first_texel.checked_mul(size_of::<u32>() as u64)?).ok()
    }
}

/// The storage one queued frame carries.
///
/// Guest frames are packed indexed bytes the shader decodes; raster frames are
/// ARGB words. Keeping the two apart lets the raster path lend its caller's
/// allocation to the mailbox — the caller receives a spare buffer in exchange —
/// instead of copying the frame into storage the mailbox owns.
/// Compact frames share the owner's immutable snapshot; the worker copies its
/// cells and detail straight into Metal buffers.
enum FramePixels {
    Indexed(Vec<u8>),
    Argb(Vec<u32>),
    Compact(Arc<CompactPresentation>),
}

impl FramePixels {
    /// The frame as bytes, borrowing raster ARGB in place. Compact frames
    /// carry two arrays and are uploaded separately.
    fn as_bytes(&self) -> &[u8] {
        match self {
            Self::Indexed(bytes) => bytes,
            Self::Argb(pixels) => argb_bytes(pixels),
            Self::Compact(_) => &[],
        }
    }
}

struct GuestFrameSubmission {
    pixels: FramePixels,
    metadata: FrameMetadata,
}

#[derive(Default)]
struct GuestFrameMailboxState {
    pending: Option<GuestFrameSubmission>,
    recycled: Vec<Vec<u8>>,
    recycled_argb: Vec<Vec<u32>>,
    paused: bool,
    active: bool,
    drawable_in_use: bool,
    shutdown: bool,
    error: Option<String>,
    submitted: u64,
    coalesced: u64,
    drawable_wait_time: Duration,
    render_time: Duration,
}

impl GuestFrameMailboxState {
    /// Return a submission's storage to the pool its format came from.
    fn recycle(&mut self, pixels: FramePixels) {
        match pixels {
            FramePixels::Indexed(bytes) => self.recycled.push(bytes),
            FramePixels::Argb(pixels) => self.recycled_argb.push(pixels),
            FramePixels::Compact(_) => {}
        }
    }
}

#[derive(Default)]
struct GuestFrameMailbox {
    state: Mutex<GuestFrameMailboxState>,
    changed: Condvar,
}

struct GuestRenderWorker {
    layer: Retained<CAMetalLayer>,
    device: Retained<ProtocolObject<dyn MTLDevice>>,
    command_queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
    pipeline: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
    guest_buffers: Vec<Retained<ProtocolObject<dyn MTLBuffer>>>,
    guest_buffer_size: usize,
    next_guest_buffer: usize,
    raster_pipeline: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
    upload_textures: Vec<Retained<ProtocolObject<dyn MTLTexture>>>,
    upload_size: (u32, u32),
    next_upload_texture: usize,
    compact_pipeline: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
    compact_buffers: CompactBuffers,
}

/// Double-buffered shared storage for compact cells and detail. Callers
/// acquire the drawable first: with two drawables, that guarantees the GPU has
/// finished reading the slot about to be overwritten.
#[derive(Default)]
struct CompactBuffers {
    slots: Vec<[(Retained<ProtocolObject<dyn MTLBuffer>>, usize); 2]>,
    next: usize,
}

impl CompactBuffers {
    fn upload(
        &mut self,
        device: &ProtocolObject<dyn MTLDevice>,
        frame: &CompactPresentation,
    ) -> Result<
        (
            &ProtocolObject<dyn MTLBuffer>,
            &ProtocolObject<dyn MTLBuffer>,
        ),
        String,
    > {
        let allocate = |words: usize| {
            // Grow geometrically so a dialog's extra detail does not
            // reallocate every frame. Metal rejects zero-length buffers.
            let capacity = words.max(1).next_power_of_two();
            device
                .newBufferWithLength_options(
                    capacity * size_of::<u32>(),
                    MTLResourceOptions::MTLResourceStorageModeShared,
                )
                .map(|buffer| (buffer, capacity))
                .ok_or_else(|| "Metal failed to allocate a compact frame buffer".to_string())
        };
        if self.slots.len() != FRAME_RESOURCE_COUNT {
            self.slots.clear();
            for _ in 0..FRAME_RESOURCE_COUNT {
                self.slots.push([
                    allocate(frame.cells.len())?,
                    allocate(frame.detail.len())?,
                ]);
            }
            self.next = 0;
        }
        let index = self.next;
        self.next = (index + 1) % self.slots.len();
        let slot = &mut self.slots[index];
        for ((buffer, capacity), data) in slot
            .iter_mut()
            .zip([frame.cells.as_slice(), frame.detail.as_slice()])
        {
            if *capacity < data.len() {
                (*buffer, *capacity) = allocate(data.len())?;
            }
            // The buffer holds at least data.len() words, and no GPU command
            // still reads this slot (see the type's documentation).
            unsafe {
                std::ptr::copy_nonoverlapping(
                    data.as_ptr(),
                    buffer.contents().as_ptr().cast::<u32>(),
                    data.len(),
                );
            }
        }
        let [(cells, _), (detail, _)] = &self.slots[index];
        Ok((cells, detail))
    }
}

// Metal devices, queues, immutable pipeline states, and CAMetalLayer drawable
// acquisition are explicitly usable from background rendering threads. Layer
// geometry is still changed only by `MetalPresenter` on AppKit's main thread;
// the worker only calls `nextDrawable` and encodes commands for that drawable.
// objc2 0.5 predates the framework sendability annotations, so it cannot infer
// those guarantees for the retained Objective-C objects.
unsafe impl Send for GuestRenderWorker {}

struct AsyncGuestPresenter {
    mailbox: Arc<GuestFrameMailbox>,
    thread: Option<JoinHandle<()>>,
}

impl Default for GuestCursorData {
    fn default() -> Self {
        Self {
            data_rows: [0; 16],
            mask_rows: [0; 16],
            color_pixels: [0; 256],
        }
    }
}

/// Take back the storage of a superseded pending frame, or `None` when nothing
/// was pending. A superseded frame has never been handed to the worker.
fn take_superseded_pending(state: &mut GuestFrameMailboxState) -> Option<FramePixels> {
    let previous = state.pending.take()?;
    state.coalesced = state.coalesced.saturating_add(1);
    Some(previous.pixels)
}

/// The staging buffer an indexed frame should be copied into: the superseded
/// frame's storage when it already held indexed bytes, otherwise a pooled one.
fn indexed_staging_buffer(state: &mut GuestFrameMailboxState) -> Vec<u8> {
    match take_superseded_pending(state) {
        Some(FramePixels::Indexed(bytes)) => bytes,
        Some(other) => {
            state.recycle(other);
            state.recycled.pop().unwrap_or_default()
        }
        None => state.recycled.pop().unwrap_or_default(),
    }
}

fn replace_pending_guest_frame(
    state: &mut GuestFrameMailboxState,
    framebuffer: &[u8],
    layout: GuestVisibleByteLayout,
    metadata: FrameMetadata,
) {
    let mut pixels = indexed_staging_buffer(state);
    copy_guest_visible_pixels(&mut pixels, framebuffer, layout);
    state.pending = Some(GuestFrameSubmission {
        pixels: FramePixels::Indexed(pixels),
        metadata,
    });
}

/// Queue a raster frame by taking ownership of its buffer, and hand a spare
/// buffer back for the caller's next frame.
///
/// The frame is copied nowhere: the mailbox owns `pixels` until the worker has
/// uploaded `layout` out of it, then recycles it. The returned buffer is the
/// superseded pending frame's storage when one was queued, otherwise a pooled
/// spare, so the caller never has to allocate a replacement.
fn replace_pending_raster_frame(
    state: &mut GuestFrameMailboxState,
    pixels: Vec<u32>,
    layout: RasterLayout,
    drawable_size: (u32, u32),
) -> Vec<u32> {
    let spare = match take_superseded_pending(state) {
        Some(FramePixels::Argb(superseded)) => Some(superseded),
        Some(other) => {
            state.recycle(other);
            None
        }
        None => None,
    };
    let spare = spare
        .or_else(|| state.recycled_argb.pop())
        .unwrap_or_default();
    state.pending = Some(GuestFrameSubmission {
        pixels: FramePixels::Argb(pixels),
        metadata: FrameMetadata::Raster {
            layout,
            drawable_size,
        },
    });
    spare
}

impl AsyncGuestPresenter {
    fn new(worker: GuestRenderWorker) -> Result<Self, String> {
        let mailbox = Arc::new(GuestFrameMailbox::default());
        let worker_mailbox = Arc::clone(&mailbox);
        let thread = std::thread::Builder::new()
            .name("systemless-metal-present".to_string())
            .spawn(move || worker.run(worker_mailbox))
            .map_err(|error| format!("failed to start Metal presenter thread: {error}"))?;
        Ok(Self {
            mailbox,
            thread: Some(thread),
        })
    }

    fn enqueue(
        &self,
        framebuffer: &[u8],
        layout: GuestVisibleByteLayout,
        metadata: GuestFrameMetadata,
    ) -> Result<(), String> {
        self.enqueue_frame(framebuffer, layout, FrameMetadata::Guest(metadata))
    }

    /// Queue a borrowed raster frame, copying it into a pooled buffer.
    ///
    /// A caller that owns its frame should use [`Self::enqueue_raster_owned`]
    /// instead: this path can only borrow the pixels, so it must stage them.
    fn enqueue_raster(
        &self,
        pixels: &[u32],
        source_size: (u32, u32),
        drawable_size: (u32, u32),
    ) -> Result<(), String> {
        let mut state = self
            .mailbox
            .state
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        if let Some(error) = state.error.as_ref() {
            return Err(error.clone());
        }
        state.paused = false;
        let mut staged = state.recycled_argb.pop().unwrap_or_default();
        staged.clear();
        staged.extend_from_slice(pixels);
        let spare = replace_pending_raster_frame(
            &mut state,
            staged,
            RasterLayout::whole(source_size),
            drawable_size,
        );
        state.recycled_argb.push(spare);
        self.mailbox.changed.notify_one();
        Ok(())
    }

    /// Queue a raster frame the caller hands over, returning the buffer the
    /// caller should reuse for its next frame. No pixel is copied.
    fn enqueue_raster_owned(
        &self,
        pixels: Vec<u32>,
        layout: RasterLayout,
        drawable_size: (u32, u32),
    ) -> Result<Vec<u32>, String> {
        let mut state = self
            .mailbox
            .state
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        if let Some(error) = state.error.as_ref() {
            return Err(error.clone());
        }
        state.paused = false;
        let spare = replace_pending_raster_frame(&mut state, pixels, layout, drawable_size);
        self.mailbox.changed.notify_one();
        Ok(spare)
    }

    /// Queue a shared compact snapshot. Only the Arc changes hands; the worker
    /// copies cells and detail into Metal storage after acquiring a drawable.
    fn enqueue_compact(
        &self,
        frame: Arc<CompactPresentation>,
        uniforms: CompactFrameUniforms,
    ) -> Result<(), String> {
        let mut state = self
            .mailbox
            .state
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        if let Some(error) = state.error.as_ref() {
            return Err(error.clone());
        }
        state.paused = false;
        if let Some(superseded) = take_superseded_pending(&mut state) {
            state.recycle(superseded);
        }
        state.pending = Some(GuestFrameSubmission {
            pixels: FramePixels::Compact(frame),
            metadata: FrameMetadata::Compact(uniforms),
        });
        self.mailbox.changed.notify_one();
        Ok(())
    }

    fn enqueue_frame(
        &self,
        framebuffer: &[u8],
        layout: GuestVisibleByteLayout,
        metadata: FrameMetadata,
    ) -> Result<(), String> {
        let mut state = self
            .mailbox
            .state
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        if let Some(error) = state.error.as_ref() {
            return Err(error.clone());
        }

        state.paused = false;
        replace_pending_guest_frame(&mut state, framebuffer, layout, metadata);
        self.mailbox.changed.notify_one();
        Ok(())
    }

    /// Stop accepting asynchronous work and wait until no command is being
    /// encoded. Pending work is discarded so a later mode switch cannot flash
    /// a stale guest frame over the synchronous fallback presentation.
    fn pause_and_wait(&self) {
        let mut state = self
            .mailbox
            .state
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        state.paused = true;
        if let Some(pending) = state.pending.take() {
            state.recycle(pending.pixels);
        }
        self.mailbox.changed.notify_all();
        while state.active || state.drawable_in_use {
            state = self
                .mailbox
                .changed
                .wait(state)
                .unwrap_or_else(|error| error.into_inner());
        }
    }

    fn snapshot(&self) -> (u64, u64, Duration, Duration) {
        let state = self
            .mailbox
            .state
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        (
            state.submitted,
            state.coalesced,
            state.drawable_wait_time,
            state.render_time,
        )
    }
}

impl Drop for AsyncGuestPresenter {
    fn drop(&mut self) {
        {
            let mut state = self
                .mailbox
                .state
                .lock()
                .unwrap_or_else(|error| error.into_inner());
            state.shutdown = true;
            state.pending = None;
            self.mailbox.changed.notify_all();
        }
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}

impl GuestRenderWorker {
    fn run(mut self, mailbox: Arc<GuestFrameMailbox>) {
        loop {
            let mut state = mailbox
                .state
                .lock()
                .unwrap_or_else(|error| error.into_inner());
            while !state.shutdown && (state.paused || state.pending.is_none()) {
                state = mailbox
                    .changed
                    .wait(state)
                    .unwrap_or_else(|error| error.into_inner());
            }
            if state.shutdown {
                break;
            }
            state.drawable_in_use = true;
            drop(state);

            let wait_start = Instant::now();
            // This is a raw Rust worker rather than an AppKit-created thread,
            // so it has no ambient Objective-C autorelease pool. Drain the
            // temporary QuartzCore objects created while acquiring a drawable.
            let drawable = {
                let _timing = crate::FramePhaseTimer::new("Metal drawable wait (worker)");
                autoreleasepool(|_| unsafe { self.layer.nextDrawable() })
            };
            let drawable_wait = wait_start.elapsed();

            let mut state = mailbox
                .state
                .lock()
                .unwrap_or_else(|error| error.into_inner());
            state.drawable_wait_time += drawable_wait;
            if state.shutdown {
                state.drawable_in_use = false;
                mailbox.changed.notify_all();
                break;
            }
            if state.paused {
                state.drawable_in_use = false;
                mailbox.changed.notify_all();
                drop(state);
                drop(drawable);
                continue;
            }
            let Some(submission) = state.pending.take() else {
                state.drawable_in_use = false;
                mailbox.changed.notify_all();
                drop(state);
                drop(drawable);
                continue;
            };
            state.active = true;
            drop(state);

            let render_start = Instant::now();
            // Command buffers, pass descriptors, and driver bookkeeping may
            // also autorelease objects while encoding the frame.
            let result = autoreleasepool(|_| match drawable {
                Some(drawable) => self.submit(&submission, &drawable),
                None => Ok(()),
            });
            let render_time = render_start.elapsed();

            let mut state = mailbox
                .state
                .lock()
                .unwrap_or_else(|error| error.into_inner());
            state.active = false;
            state.drawable_in_use = false;
            state.render_time += render_time;
            if result.is_ok() {
                state.submitted = state.submitted.saturating_add(1);
            } else if state.error.is_none() {
                state.error = result.err();
            }
            state.recycle(submission.pixels);
            mailbox.changed.notify_all();
        }
    }

    fn submit(
        &mut self,
        submission: &GuestFrameSubmission,
        drawable: &ProtocolObject<dyn CAMetalDrawable>,
    ) -> Result<(), String> {
        let framebuffer = submission.pixels.as_bytes();
        let metadata = match &submission.metadata {
            FrameMetadata::Guest(metadata) => metadata,
            FrameMetadata::Raster {
                layout,
                drawable_size,
            } => {
                let source_size = (layout.width, layout.height);
                if self.upload_size != source_size {
                    self.upload_textures =
                        upload_textures(&self.device, source_size.0, source_size.1)?;
                    self.upload_size = source_size;
                    self.next_upload_texture = 0;
                }
                let index = self.next_upload_texture;
                self.next_upload_texture = (index + 1) % self.upload_textures.len();
                return encode_raster_frame(
                    &self.command_queue,
                    &self.raster_pipeline,
                    &self.upload_textures[index],
                    drawable,
                    framebuffer,
                    *layout,
                    *drawable_size,
                    false,
                );
            }
            FrameMetadata::Compact(uniforms) => {
                let FramePixels::Compact(frame) = &submission.pixels else {
                    return Err("compact metadata without a compact frame".to_string());
                };
                let buffers = self.compact_buffers.upload(&self.device, frame)?;
                return encode_compact_frame(
                    &self.command_queue,
                    &self.compact_pipeline,
                    buffers,
                    drawable,
                    uniforms,
                    false,
                );
            }
        };
        self.ensure_guest_buffers(framebuffer.len())?;

        let buffer_index = self.next_guest_buffer;
        self.next_guest_buffer = (buffer_index + 1) % self.guest_buffers.len();
        let guest_buffer = &self.guest_buffers[buffer_index];
        unsafe {
            std::ptr::copy_nonoverlapping(
                framebuffer.as_ptr(),
                guest_buffer.contents().as_ptr().cast::<u8>(),
                framebuffer.len(),
            );
        }

        encode_guest_frame(
            &self.command_queue,
            &self.pipeline,
            guest_buffer,
            drawable,
            metadata,
            false,
        )
    }

    fn ensure_guest_buffers(&mut self, frame_bytes: usize) -> Result<(), String> {
        if self.guest_buffer_size == frame_bytes {
            return Ok(());
        }
        let mut buffers = Vec::with_capacity(FRAME_RESOURCE_COUNT);
        for _ in 0..FRAME_RESOURCE_COUNT {
            buffers.push(
                self.device
                    .newBufferWithLength_options(
                        frame_bytes,
                        MTLResourceOptions::MTLResourceStorageModeShared,
                    )
                    .ok_or_else(|| "Metal failed to allocate a guest framebuffer".to_string())?,
            );
        }
        self.guest_buffers = buffers;
        self.guest_buffer_size = frame_bytes;
        self.next_guest_buffer = 0;
        Ok(())
    }
}

pub struct MetalPresenter {
    _window: Rc<Window>,
    root_layer: Retained<CALayer>,
    layer: Retained<CAMetalLayer>,
    device: Retained<ProtocolObject<dyn MTLDevice>>,
    command_queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
    pipeline: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
    guest_pipeline: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
    guest_buffers: Vec<Retained<ProtocolObject<dyn MTLBuffer>>>,
    guest_buffer_size: usize,
    next_guest_buffer: usize,
    upload_textures: Vec<Retained<ProtocolObject<dyn MTLTexture>>>,
    upload_size: (u32, u32),
    drawable_size: (u32, u32),
    next_upload_texture: usize,
    last_guest_metadata: Option<GuestFrameMetadata>,
    last_guest_visible_pixels: Vec<u8>,
    skip_unchanged_guest_frames: bool,
    profile_guest_frames: bool,
    guest_frame_profile: GuestFrameProfile,
    compact_pipeline: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
    compact_buffers: CompactBuffers,
    compact_enabled: bool,
    /// The compact snapshot and placement most recently presented, so an
    /// unchanged owner frame is not uploaded again.
    last_compact: Option<(Arc<CompactPresentation>, CompactFrameUniforms)>,
    async_guest_presenter: AsyncGuestPresenter,
}

/// The GPU that scans out the main display. Rendering there avoids copying every
/// presented frame across GPUs on dual-GPU Macs when the window is scanned out
/// directly (fullscreen); windowed presentation is unaffected either way.
/// `SYSTEMLESS_METAL_DEVICE=default` keeps the system default device.
fn display_metal_device() -> Option<Retained<ProtocolObject<dyn MTLDevice>>> {
    #[link(name = "CoreGraphics", kind = "framework")]
    extern "C" {
        fn CGMainDisplayID() -> u32;
        fn CGDirectDisplayCopyCurrentMetalDevice(
            display: u32,
        ) -> *mut ProtocolObject<dyn MTLDevice>;
    }
    if std::env::var("SYSTEMLESS_METAL_DEVICE")
        .map(|v| v == "default")
        .unwrap_or(false)
    {
        return None;
    }
    // Returns a +1 reference (Copy rule); null when the display has no Metal device.
    unsafe { Retained::from_raw(CGDirectDisplayCopyCurrentMetalDevice(CGMainDisplayID())) }
}

impl MetalPresenter {
    pub fn new(window: Rc<Window>) -> Result<Self, String> {
        MainThreadMarker::new()
            .ok_or_else(|| "Metal presenter must be created on the main thread".to_string())?;

        let handle = window
            .window_handle()
            .map_err(|error| format!("failed to get AppKit window handle: {error}"))?;
        let RawWindowHandle::AppKit(handle) = handle.as_raw() else {
            return Err("Metal presenter requires an AppKit window".to_string());
        };

        // SAFETY: winit owns this NSView for at least as long as `window`,
        // which the presenter retains in `_window`. AppKit view/layer access
        // occurs on the main thread.
        let view: &NSObject = unsafe { handle.ns_view.cast().as_ref() };
        let _: () = unsafe { msg_send![view, setWantsLayer: true] };
        let root_layer: Option<Retained<CALayer>> = unsafe { msg_send_id![view, layer] };
        let root_layer =
            root_layer.ok_or_else(|| "AppKit did not create a root layer".to_string())?;

        // SAFETY: Metal returns a retained Objective-C protocol object or nil.
        let device = display_metal_device()
            .or_else(|| unsafe { Retained::retain(MTLCreateSystemDefaultDevice()) })
            .ok_or_else(|| "this Mac has no Metal device".to_string())?;
        let command_queue = device
            .newCommandQueue()
            .ok_or_else(|| "Metal failed to create a command queue".to_string())?;

        let layer = unsafe { CAMetalLayer::new() };
        unsafe {
            layer.setDevice(Some(&device));
            layer.setPixelFormat(MTLPixelFormat::BGRA8Unorm);
            layer.setFramebufferOnly(true);
            layer.setMaximumDrawableCount(FRAME_RESOURCE_COUNT);
            layer.setPresentsWithTransaction(false);
            layer.setDisplaySyncEnabled(true);
        }
        layer.setOpaque(true);
        // If AppKit changes the view bounds before the replacement Metal
        // drawable is committed, preserve the previous drawable's pixel size
        // instead of stretching it to the transient layer bounds.
        // Automatic dialog crops grow the native window upward while keeping
        // its bottom edge fixed. Pin the retained drawable to that edge so the
        // complete pre-dialog frame remains stationary until the resize
        // callback submits its replacement.
        layer.setContentsGravity(unsafe { kCAGravityBottom });
        layer.setFrame(root_layer.bounds());
        layer.setAutoresizingMask(
            CAAutoresizingMask::kCALayerWidthSizable | CAAutoresizingMask::kCALayerHeightSizable,
        );
        layer.setContentsScale(root_layer.contentsScale());
        root_layer.addSublayer(&layer);

        let library = device
            .newLibraryWithSource_options_error(
                ns_string!(include_str!("metal_present.metal")),
                None,
            )
            .map_err(|error| format!("Metal shader compilation failed: {error}"))?;
        let vertex = library
            .newFunctionWithName(ns_string!("raster_vertex"))
            .ok_or_else(|| "Metal vertex function was not found".to_string())?;
        let fragment = library
            .newFunctionWithName(ns_string!("raster_fragment"))
            .ok_or_else(|| "Metal fragment function was not found".to_string())?;
        let guest_fragment = library
            .newFunctionWithName(ns_string!("guest_raster_fragment"))
            .ok_or_else(|| "Metal guest framebuffer function was not found".to_string())?;
        let compact_fragment = library
            .newFunctionWithName(ns_string!("compact_fragment"))
            .ok_or_else(|| "Metal compact coverage function was not found".to_string())?;

        let descriptor = MTLRenderPipelineDescriptor::new();
        descriptor.setVertexFunction(Some(&vertex));
        descriptor.setFragmentFunction(Some(&fragment));
        unsafe {
            descriptor
                .colorAttachments()
                .objectAtIndexedSubscript(0)
                .setPixelFormat(MTLPixelFormat::BGRA8Unorm);
        }
        let pipeline = device
            .newRenderPipelineStateWithDescriptor_error(&descriptor)
            .map_err(|error| format!("Metal pipeline creation failed: {error}"))?;

        descriptor.setFragmentFunction(Some(&guest_fragment));
        let guest_pipeline = device
            .newRenderPipelineStateWithDescriptor_error(&descriptor)
            .map_err(|error| format!("Metal guest pipeline creation failed: {error}"))?;

        descriptor.setFragmentFunction(Some(&compact_fragment));
        let compact_pipeline = device
            .newRenderPipelineStateWithDescriptor_error(&descriptor)
            .map_err(|error| format!("Metal compact pipeline creation failed: {error}"))?;

        let async_command_queue = device
            .newCommandQueue()
            .ok_or_else(|| "Metal failed to create the presenter command queue".to_string())?;
        let async_guest_presenter = AsyncGuestPresenter::new(GuestRenderWorker {
            layer: layer.clone(),
            device: device.clone(),
            command_queue: async_command_queue,
            pipeline: guest_pipeline.clone(),
            guest_buffers: Vec::new(),
            guest_buffer_size: 0,
            next_guest_buffer: 0,
            raster_pipeline: pipeline.clone(),
            upload_textures: Vec::new(),
            upload_size: (0, 0),
            next_upload_texture: 0,
            compact_pipeline: compact_pipeline.clone(),
            compact_buffers: CompactBuffers::default(),
        })?;

        Ok(Self {
            _window: window,
            root_layer,
            layer,
            device,
            command_queue,
            pipeline,
            guest_pipeline,
            guest_buffers: Vec::new(),
            guest_buffer_size: 0,
            next_guest_buffer: 0,
            upload_textures: Vec::new(),
            upload_size: (0, 0),
            drawable_size: (0, 0),
            next_upload_texture: 0,
            last_guest_metadata: None,
            last_guest_visible_pixels: Vec::new(),
            skip_unchanged_guest_frames: std::env::var_os(
                "SYSTEMLESS_DISABLE_UNCHANGED_FRAME_SKIP",
            )
            .is_none(),
            profile_guest_frames: std::env::var_os("SYSTEMLESS_PROFILE_METAL_FRAMES").is_some(),
            guest_frame_profile: GuestFrameProfile::default(),
            compact_pipeline,
            compact_buffers: CompactBuffers::default(),
            compact_enabled: std::env::var_os("SYSTEMLESS_METAL_COMPACT")
                .is_none_or(|value| value != "0"),
            last_compact: None,
            async_guest_presenter,
        })
    }

    /// Couple the next drawable presentation to the current Core Animation
    /// transaction. This is used only while an AppKit window-frame mutation
    /// is in flight; normal gameplay keeps the lower-latency asynchronous
    /// Metal presentation path.
    pub fn set_transactional_presentation(&self, enabled: bool) {
        if enabled {
            self.async_guest_presenter.pause_and_wait();
        }
        unsafe { self.layer.setPresentsWithTransaction(enabled) };
    }

    /// Present a raster frame supplied as a borrowed slice.
    ///
    /// The mailbox must own the pixels it queues, so this path stages them into
    /// a pool buffer. Callers that own their frame should use
    /// [`Self::present_owned`], which hands the frame over instead of copying
    /// it.
    pub fn present(
        &mut self,
        pixels: &[u32],
        source_width: u32,
        source_height: u32,
        drawable_width: u32,
        drawable_height: u32,
    ) -> Result<(), String> {
        let expected_pixels = source_width as usize * source_height as usize;
        if pixels.len() < expected_pixels || expected_pixels == 0 {
            return Err("framebuffer dimensions do not match its pixel data".to_string());
        }
        if drawable_width == 0 || drawable_height == 0 {
            return Ok(());
        }

        self.resize_drawable(drawable_width, drawable_height);
        self.last_guest_metadata = None;
        self.last_compact = None;
        if !unsafe { self.layer.presentsWithTransaction() } {
            return self.async_guest_presenter.enqueue_raster(
                &pixels[..expected_pixels],
                (source_width, source_height),
                (drawable_width, drawable_height),
            );
        }
        self.async_guest_presenter.pause_and_wait();
        self.ensure_upload_textures(source_width, source_height)?;

        // Acquire the drawable before recycling the corresponding upload
        // texture. With a two-drawable layer, nextDrawable blocks until the
        // oldest in-flight frame is complete, making the matching texture safe
        // for the CPU to overwrite without adding a third queued frame.
        let Some(drawable) = (unsafe { self.layer.nextDrawable() }) else {
            return Ok(());
        };
        let upload_index = self.next_upload_texture;
        self.next_upload_texture = (upload_index + 1) % self.upload_textures.len();
        let upload = &self.upload_textures[upload_index];
        encode_raster_frame(
            &self.command_queue,
            &self.pipeline,
            upload,
            &drawable,
            argb_bytes(pixels),
            RasterLayout::whole((source_width, source_height)),
            (drawable_width, drawable_height),
            true,
        )?;
        Ok(())
    }

    /// Present a raster frame the caller hands over, returning the buffer the
    /// caller should reuse for its next frame.
    ///
    /// `frame` is the whole frame buffer and `layout` selects the pixels to
    /// show, so a cropped presentation needs neither a cropped copy nor a
    /// staging copy: the presenter worker uploads the rectangle in place and
    /// recycles the buffer once the driver has read it.
    pub fn present_owned(
        &mut self,
        frame: Vec<u32>,
        layout: RasterLayout,
        drawable_width: u32,
        drawable_height: u32,
    ) -> Result<Vec<u32>, String> {
        let byte_len = frame.len().saturating_mul(size_of::<u32>());
        if layout.texel_byte_offset(byte_len).is_none() {
            return Err("framebuffer dimensions do not match its pixel data".to_string());
        }
        if drawable_width == 0 || drawable_height == 0 {
            return Ok(frame);
        }

        self.resize_drawable(drawable_width, drawable_height);
        self.last_guest_metadata = None;
        self.last_compact = None;
        if !unsafe { self.layer.presentsWithTransaction() } {
            return self.async_guest_presenter.enqueue_raster_owned(
                frame,
                layout,
                (drawable_width, drawable_height),
            );
        }
        self.async_guest_presenter.pause_and_wait();
        self.ensure_upload_textures(layout.width, layout.height)?;

        // Acquire the drawable before recycling the corresponding upload
        // texture. With a two-drawable layer, nextDrawable blocks until the
        // oldest in-flight frame is complete, making the matching texture safe
        // for the CPU to overwrite without adding a third queued frame.
        let Some(drawable) = (unsafe { self.layer.nextDrawable() }) else {
            return Ok(frame);
        };
        let upload_index = self.next_upload_texture;
        self.next_upload_texture = (upload_index + 1) % self.upload_textures.len();
        let upload = &self.upload_textures[upload_index];
        encode_raster_frame(
            &self.command_queue,
            &self.pipeline,
            upload,
            &drawable,
            argb_bytes(&frame),
            layout,
            (drawable_width, drawable_height),
            true,
        )?;
        Ok(frame)
    }

    /// Snapshot and present a native Classic Macintosh framebuffer. The GPU
    /// expands indexed/monochrome pixels and composites the guest cursor, so
    /// the CPU copies only the packed source bytes. Two staging buffers keep
    /// each submitted frame immutable until Metal has consumed it.
    pub fn present_guest_frame(
        &mut self,
        framebuffer: &[u8],
        screen_mode: (u32, u32, u16, u16, u16),
        content_rect: (u32, u32, u32, u32),
        palette: &[u32; 256],
        cursor: Option<(&CursorImage, (i16, i16))>,
        drawable_size: (u32, u32),
        force_present: bool,
    ) -> Result<bool, String> {
        let (_, row_bytes, width, height, pixel_size) = screen_mode;
        let screen_width = u32::from(width);
        let screen_height = u32::from(height);
        let (content_left, content_top, width, height) = content_rect;
        let (drawable_width, drawable_height) = drawable_size;
        let Some(packed_content_left) = guest_packed_content_left(pixel_size, content_left) else {
            return Ok(false);
        };
        if content_left.saturating_add(width) > screen_width
            || content_top.saturating_add(height) > screen_height
        {
            return Err("detected content rectangle lies outside the guest screen".to_string());
        }
        if width == 0 || height == 0 || drawable_width == 0 || drawable_height == 0 {
            return Ok(true);
        }
        let frame_bytes = guest_frame_byte_len(row_bytes, screen_height)
            .ok_or_else(|| "guest framebuffer dimensions overflow host size".to_string())?;
        if framebuffer.len() < frame_bytes {
            return Err("guest framebuffer dimensions do not match its pixel data".to_string());
        }

        let visible_layout = guest_visible_byte_layout(
            row_bytes,
            pixel_size,
            content_left,
            content_top,
            width,
            height,
        )
        .ok_or_else(|| "visible guest framebuffer rows are invalid".to_string())?;
        let (mut uniforms, cursor_data) = cursor
            .map(|(image, position)| guest_cursor_data(Some(image), position))
            .unwrap_or_else(|| guest_cursor_data(None, (0, 0)));
        let packed_origin_left = content_left - packed_content_left;
        uniforms.row_bytes = u32::try_from(visible_layout.visible_row_bytes)
            .map_err(|_| "visible guest row stride exceeds Metal's limit".to_string())?;
        uniforms.width = width;
        uniforms.height = height;
        uniforms.pixel_size = u32::from(pixel_size);
        uniforms.content_left = packed_content_left;
        uniforms.content_top = 0;
        uniforms.cursor_left -= i32::try_from(packed_origin_left)
            .map_err(|_| "guest crop origin exceeds Metal's limit".to_string())?;
        uniforms.cursor_top -= i32::try_from(content_top)
            .map_err(|_| "guest crop origin exceeds Metal's limit".to_string())?;
        let metadata = GuestFrameMetadata {
            screen_layout: (row_bytes, screen_mode.2, screen_mode.3, pixel_size),
            content_rect,
            palette: *palette,
            uniforms,
            cursor: cursor_data,
            drawable_size,
        };

        let presentation_start = Instant::now();
        self.guest_frame_profile.attempts += 1;
        if force_present {
            self.guest_frame_profile.forced += 1;
        }
        let compare_start = Instant::now();
        let unchanged = self.skip_unchanged_guest_frames
            && self.last_guest_metadata.as_ref() == Some(&metadata)
            && guest_visible_pixels_equal(
                &self.last_guest_visible_pixels,
                framebuffer,
                visible_layout,
            );
        if self.skip_unchanged_guest_frames {
            self.guest_frame_profile.comparison_time += compare_start.elapsed();
        }
        if unchanged && !force_present {
            self.guest_frame_profile.unchanged += 1;
            self.guest_frame_profile.presentation_time += presentation_start.elapsed();
            self.maybe_log_guest_frame_profile();
            return Ok(true);
        }

        self.resize_drawable(drawable_width, drawable_height);
        self.last_compact = None;
        if unsafe { self.layer.presentsWithTransaction() } {
            let visible_bytes = visible_layout
                .visible_row_bytes
                .checked_mul(visible_layout.row_count)
                .ok_or_else(|| {
                    "visible guest framebuffer dimensions overflow host size".to_string()
                })?;
            self.ensure_guest_buffers(visible_bytes)?;
            let Some(drawable) = (unsafe { self.layer.nextDrawable() }) else {
                return Ok(true);
            };
            let buffer_index = self.next_guest_buffer;
            self.next_guest_buffer = (buffer_index + 1) % self.guest_buffers.len();
            let guest_buffer = &self.guest_buffers[buffer_index];
            copy_guest_visible_pixels_to_ptr(
                guest_buffer.contents().as_ptr().cast::<u8>(),
                framebuffer,
                visible_layout,
            );
            encode_guest_frame(
                &self.command_queue,
                &self.guest_pipeline,
                guest_buffer,
                &drawable,
                &metadata,
                true,
            )?;
        } else {
            self.async_guest_presenter
                .enqueue(framebuffer, visible_layout, metadata.clone())?;
        }
        if self.skip_unchanged_guest_frames {
            copy_guest_visible_pixels(
                &mut self.last_guest_visible_pixels,
                framebuffer,
                visible_layout,
            );
            self.last_guest_metadata = Some(metadata);
        }
        self.guest_frame_profile.presentation_time += presentation_start.elapsed();
        self.maybe_log_guest_frame_profile();
        Ok(true)
    }

    /// Whether retained text frames may be resolved by
    /// [`Self::present_compact`]. `SYSTEMLESS_METAL_COMPACT=0` keeps the CPU
    /// resampler for comparison.
    pub fn supports_compact(&self) -> bool {
        self.compact_enabled
    }

    /// Present `crop` (logical guest pixels) of a compact retained image,
    /// resolving its coverage on the GPU at the drawable size. Returns false,
    /// presenting nothing, when the frame exceeds the shader's exact integer
    /// range; the caller then resolves it on the CPU.
    pub fn present_compact(
        &mut self,
        frame: &Arc<CompactPresentation>,
        crop: (u32, u32, u32, u32),
        drawable_size: (u32, u32),
        force_present: bool,
    ) -> Result<bool, String> {
        let Some(uniforms) = compact_frame_uniforms(frame, crop, drawable_size) else {
            return Ok(false);
        };
        let unchanged = self
            .last_compact
            .as_ref()
            .is_some_and(|(last, last_uniforms)| {
                Arc::ptr_eq(last, frame) && *last_uniforms == uniforms
            });
        if unchanged && !force_present && self.drawable_size == drawable_size {
            return Ok(true);
        }
        self.resize_drawable(drawable_size.0, drawable_size.1);
        self.last_guest_metadata = None;
        if unsafe { self.layer.presentsWithTransaction() } {
            self.async_guest_presenter.pause_and_wait();
            // Acquire the drawable before overwriting a buffer slot; see
            // `CompactBuffers`.
            let Some(drawable) = (unsafe { self.layer.nextDrawable() }) else {
                return Ok(true);
            };
            let buffers = self.compact_buffers.upload(&self.device, frame)?;
            encode_compact_frame(
                &self.command_queue,
                &self.compact_pipeline,
                buffers,
                &drawable,
                &uniforms,
                true,
            )?;
        } else {
            self.async_guest_presenter
                .enqueue_compact(frame.clone(), uniforms)?;
        }
        self.last_compact = Some((frame.clone(), uniforms));
        Ok(true)
    }

    fn maybe_log_guest_frame_profile(&self) {
        let profile = &self.guest_frame_profile;
        if !self.profile_guest_frames
            || profile.attempts == 0
            || !profile.attempts.is_multiple_of(600)
        {
            return;
        }
        let skipped_percent = profile.unchanged as f64 * 100.0 / profile.attempts as f64;
        let compare_us =
            profile.comparison_time.as_secs_f64() * 1_000_000.0 / profile.attempts as f64;
        let presentation_us =
            profile.presentation_time.as_secs_f64() * 1_000_000.0 / profile.attempts as f64;
        let (async_submitted, coalesced, drawable_wait, render_time) =
            self.async_guest_presenter.snapshot();
        let submitted = async_submitted;
        let drawable_wait_us = if async_submitted == 0 {
            0.0
        } else {
            drawable_wait.as_secs_f64() * 1_000_000.0 / async_submitted as f64
        };
        let render_us = if async_submitted == 0 {
            0.0
        } else {
            render_time.as_secs_f64() * 1_000_000.0 / async_submitted as f64
        };
        eprintln!(
            "[METAL-PROFILE] attempts={} submitted={} coalesced={} unchanged_skipped={} forced={} skipped={:.1}% compare={:.1}us/frame enqueue={:.1}us/frame drawable_wait={:.1}us/submission render={:.1}us/submission",
            profile.attempts,
            submitted,
            coalesced,
            profile.unchanged,
            profile.forced,
            skipped_percent,
            compare_us,
            presentation_us,
            drawable_wait_us,
            render_us,
        );
    }

    fn ensure_upload_textures(&mut self, width: u32, height: u32) -> Result<(), String> {
        if self.upload_size == (width, height) {
            return Ok(());
        }

        let textures = upload_textures(&self.device, width, height)?;
        self.upload_textures = textures;
        self.upload_size = (width, height);
        self.next_upload_texture = 0;
        Ok(())
    }

    fn ensure_guest_buffers(&mut self, frame_bytes: usize) -> Result<(), String> {
        if self.guest_buffer_size == frame_bytes {
            return Ok(());
        }
        let mut buffers = Vec::with_capacity(FRAME_RESOURCE_COUNT);
        for _ in 0..FRAME_RESOURCE_COUNT {
            buffers.push(
                self.device
                    .newBufferWithLength_options(
                        frame_bytes,
                        MTLResourceOptions::MTLResourceStorageModeShared,
                    )
                    .ok_or_else(|| "Metal failed to allocate a guest framebuffer".to_string())?,
            );
        }
        self.guest_buffers = buffers;
        self.guest_buffer_size = frame_bytes;
        self.next_guest_buffer = 0;
        Ok(())
    }

    fn resize_drawable(&mut self, width: u32, height: u32) {
        if self.drawable_size != (width, height) {
            // CALayer property assignments participate in Core Animation
            // transactions even when the value is unchanged. Reasserting
            // frame and scale at the guest VBL rate can make an otherwise
            // trivial Metal layer miss physical-display deadlines.
            self.layer.setFrame(self.root_layer.bounds());
            self.layer.setContentsScale(self.root_layer.contentsScale());
            unsafe {
                self.layer.setDrawableSize(
                    CGRect::new(
                        objc2_foundation::CGPoint::new(0.0, 0.0),
                        objc2_foundation::CGSize::new(width as f64, height as f64),
                    )
                    .size,
                );
            }
            self.drawable_size = (width, height);
        }
    }
}

fn argb_bytes(pixels: &[u32]) -> &[u8] {
    // All byte patterns of u32 are valid and the returned borrow cannot outlive
    // the source pixels. BGRA8Unorm consumes their native little-endian bytes.
    unsafe { std::slice::from_raw_parts(pixels.as_ptr().cast(), std::mem::size_of_val(pixels)) }
}

fn upload_textures(
    device: &ProtocolObject<dyn MTLDevice>,
    width: u32,
    height: u32,
) -> Result<Vec<Retained<ProtocolObject<dyn MTLTexture>>>, String> {
    let descriptor = unsafe {
        MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
            MTLPixelFormat::BGRA8Unorm,
            width as usize,
            height as usize,
            false,
        )
    };
    descriptor.setStorageMode(MTLStorageMode::Shared);
    descriptor.setUsage(MTLTextureUsage::ShaderRead);

    let mut textures = Vec::with_capacity(FRAME_RESOURCE_COUNT);
    for _ in 0..FRAME_RESOURCE_COUNT {
        textures.push(
            device
                .newTextureWithDescriptor(&descriptor)
                .ok_or_else(|| "Metal failed to allocate an upload texture".to_string())?,
        );
    }
    Ok(textures)
}

fn finish_presentation(
    command_buffer: &ProtocolObject<dyn MTLCommandBuffer>,
    drawable: &ProtocolObject<dyn CAMetalDrawable>,
    transactional: bool,
) {
    if transactional {
        // Apple requires the render work to be scheduled before the
        // drawable itself is presented into the current CA transaction.
        // Using commandBuffer.presentDrawable here would bypass that
        // transaction and recreate the one-frame resize bounce.
        command_buffer.commit();
        command_buffer.waitUntilScheduled();
        let drawable: &ProtocolObject<dyn objc2_metal::MTLDrawable> =
            ProtocolObject::from_ref(drawable);
        drawable.present();
    } else {
        command_buffer.presentDrawable(ProtocolObject::from_ref(drawable));
        command_buffer.commit();
    }
}

/// Upload the rectangle a raster frame presents into its upload texture.
///
/// The frame buffer arrives whole: `layout` selects the presented pixels and
/// supplies the row stride of the buffer that carries them, so the driver reads
/// the rectangle in place and the CPU never materialises a cropped copy.
fn upload_raster_region(
    upload: &ProtocolObject<dyn MTLTexture>,
    pixels: &[u8],
    layout: RasterLayout,
) -> Result<(), String> {
    let offset = layout
        .texel_byte_offset(pixels.len())
        .ok_or_else(|| "presented rectangle does not fit its framebuffer".to_string())?;
    let region = MTLRegion {
        origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
        size: objc2_metal::MTLSize {
            width: layout.width as usize,
            height: layout.height as usize,
            depth: 1,
        },
    };
    let first_texel = pixels
        .get(offset..)
        .ok_or_else(|| "presented rectangle starts past its framebuffer".to_string())?;
    let source = NonNull::new(first_texel.as_ptr().cast_mut().cast::<c_void>())
        .ok_or_else(|| "a non-empty framebuffer has a non-null pointer".to_string())?;
    unsafe {
        upload.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
            region,
            0,
            source,
            layout.buffer_width as usize * size_of::<u32>(),
        );
    }
    Ok(())
}

fn encode_raster_frame(
    command_queue: &ProtocolObject<dyn MTLCommandQueue>,
    pipeline: &ProtocolObject<dyn MTLRenderPipelineState>,
    upload: &ProtocolObject<dyn MTLTexture>,
    drawable: &ProtocolObject<dyn CAMetalDrawable>,
    pixels: &[u8],
    layout: RasterLayout,
    drawable_size: (u32, u32),
    transactional: bool,
) -> Result<(), String> {
    let (source_width, source_height) = (layout.width, layout.height);
    let (drawable_width, drawable_height) = drawable_size;
    upload_raster_region(upload, pixels, layout)?;

    let drawable_texture = unsafe { drawable.texture() };
    let pass = unsafe { MTLRenderPassDescriptor::new() };
    let color = unsafe { pass.colorAttachments().objectAtIndexedSubscript(0) };
    color.setTexture(Some(&drawable_texture));
    color.setLoadAction(MTLLoadAction::Clear);
    color.setStoreAction(MTLStoreAction::Store);
    color.setClearColor(objc2_metal::MTLClearColor {
        red: 0.0,
        green: 0.0,
        blue: 0.0,
        alpha: 1.0,
    });

    let command_buffer = command_queue
        .commandBuffer()
        .ok_or_else(|| "Metal failed to create a command buffer".to_string())?;
    let encoder = command_buffer
        .renderCommandEncoderWithDescriptor(&pass)
        .ok_or_else(|| "Metal failed to create a render encoder".to_string())?;
    encoder.setRenderPipelineState(pipeline);
    unsafe { encoder.setFragmentTexture_atIndex(Some(upload), 0) };

    let viewport =
        aspect_fit_viewport(source_width, source_height, drawable_width, drawable_height);
    encoder.setViewport(MTLViewport {
        originX: viewport.0,
        originY: viewport.1,
        width: viewport.2,
        height: viewport.3,
        znear: 0.0,
        zfar: 1.0,
    });
    unsafe {
        encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::TriangleStrip, 0, 4)
    };
    encoder.endEncoding();

    finish_presentation(&command_buffer, drawable, transactional);
    Ok(())
}

fn encode_compact_frame(
    command_queue: &ProtocolObject<dyn MTLCommandQueue>,
    pipeline: &ProtocolObject<dyn MTLRenderPipelineState>,
    (cells, detail): (&ProtocolObject<dyn MTLBuffer>, &ProtocolObject<dyn MTLBuffer>),
    drawable: &ProtocolObject<dyn CAMetalDrawable>,
    uniforms: &CompactFrameUniforms,
    transactional: bool,
) -> Result<(), String> {
    let texture = unsafe { drawable.texture() };
    let pass = unsafe { MTLRenderPassDescriptor::new() };
    let color = unsafe { pass.colorAttachments().objectAtIndexedSubscript(0) };
    color.setTexture(Some(&texture));
    color.setLoadAction(MTLLoadAction::Clear);
    color.setStoreAction(MTLStoreAction::Store);
    color.setClearColor(objc2_metal::MTLClearColor {
        red: 0.0,
        green: 0.0,
        blue: 0.0,
        alpha: 1.0,
    });

    let command_buffer = command_queue
        .commandBuffer()
        .ok_or_else(|| "Metal failed to create a command buffer".to_string())?;
    let encoder = command_buffer
        .renderCommandEncoderWithDescriptor(&pass)
        .ok_or_else(|| "Metal failed to create a render encoder".to_string())?;
    encoder.setRenderPipelineState(pipeline);
    unsafe {
        encoder.setFragmentBuffer_offset_atIndex(Some(cells), 0, 0);
        encoder.setFragmentBuffer_offset_atIndex(Some(detail), 0, 1);
        encoder.setFragmentBytes_length_atIndex(
            non_null_bytes(uniforms),
            size_of::<CompactFrameUniforms>(),
            2,
        );
    }
    encoder.setViewport(MTLViewport {
        originX: uniforms.ox.into(),
        originY: uniforms.oy.into(),
        width: uniforms.dw.into(),
        height: uniforms.dh.into(),
        znear: 0.0,
        zfar: 1.0,
    });
    unsafe {
        encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::TriangleStrip, 0, 4)
    };
    encoder.endEncoding();

    finish_presentation(&command_buffer, drawable, transactional);
    Ok(())
}

/// The integer aspect-fit rectangle `(left, top, width, height)` of `source`
/// in `drawable`. Integer bounds keep every fragment's coverage footprint an
/// exact rational of the source size, as in the CPU resampler.
fn integer_aspect_fit(source: (u32, u32), drawable: (u32, u32)) -> (u32, u32, u32, u32) {
    let (sw, sh) = (u64::from(source.0), u64::from(source.1));
    let (dw, dh) = (u64::from(drawable.0), u64::from(drawable.1));
    let (width, height) = if dw * sh <= dh * sw {
        (dw, dw * sh / sw)
    } else {
        (dh * sw / sh, dh)
    };
    (
        ((dw - width) / 2) as u32,
        ((dh - height) / 2) as u32,
        width as u32,
        height as u32,
    )
}

/// Uniforms for presenting `crop` (logical guest pixels) of `frame` into a
/// drawable, or `None` when the shader's 32-bit coverage arithmetic could
/// overflow or the inputs are inconsistent; callers then resolve on the CPU.
fn compact_frame_uniforms(
    frame: &CompactPresentation,
    crop: (u32, u32, u32, u32),
    drawable_size: (u32, u32),
) -> Option<CompactFrameUniforms> {
    let (crop_left, crop_top, crop_width, crop_height) = crop;
    if !(1..=4).contains(&frame.scale)
        || frame.cells.len() != (frame.width as usize).checked_mul(frame.height as usize)?
        || crop_width == 0
        || crop_height == 0
        || crop_left.checked_add(crop_width)? > frame.width
        || crop_top.checked_add(crop_height)? > frame.height
        || drawable_size.0 == 0
        || drawable_size.1 == 0
    {
        return None;
    }
    let (ox, oy, dw, dh) = integer_aspect_fit((crop_width, crop_height), drawable_size);
    let sw = u64::from(crop_width) * u64::from(frame.scale);
    let sh = u64::from(crop_height) * u64::from(frame.scale);
    let total =
        (if sw > u64::from(dw) { sw } else { 1 }) * (if sh > u64::from(dh) { sh } else { 1 });
    if [sw, sh, u64::from(dw), u64::from(dh)]
        .iter()
        .any(|&n| n == 0 || n > 16384)
        || total * 255 + total / 2 > u64::from(u32::MAX)
    {
        return None;
    }
    debug_assert!(frame.cells.iter().all(|&cell| {
        cell >> 31 == 0
            || (cell & 0x7fffffff) as usize + (frame.scale * frame.scale) as usize
                <= frame.detail.len()
    }));
    Some(CompactFrameUniforms {
        width: frame.width,
        height: frame.height,
        scale: frame.scale,
        crop_left,
        crop_top,
        crop_width,
        crop_height,
        dw,
        dh,
        ox,
        oy,
    })
}

fn encode_guest_frame(
    command_queue: &ProtocolObject<dyn MTLCommandQueue>,
    pipeline: &ProtocolObject<dyn MTLRenderPipelineState>,
    guest_buffer: &ProtocolObject<dyn MTLBuffer>,
    drawable: &ProtocolObject<dyn CAMetalDrawable>,
    metadata: &GuestFrameMetadata,
    transactional: bool,
) -> Result<(), String> {
    let drawable_texture = unsafe { drawable.texture() };
    let pass = unsafe { MTLRenderPassDescriptor::new() };
    let color = unsafe { pass.colorAttachments().objectAtIndexedSubscript(0) };
    color.setTexture(Some(&drawable_texture));
    color.setLoadAction(MTLLoadAction::Clear);
    color.setStoreAction(MTLStoreAction::Store);
    color.setClearColor(objc2_metal::MTLClearColor {
        red: 0.0,
        green: 0.0,
        blue: 0.0,
        alpha: 1.0,
    });

    let command_buffer = command_queue
        .commandBuffer()
        .ok_or_else(|| "Metal failed to create a command buffer".to_string())?;
    let encoder = command_buffer
        .renderCommandEncoderWithDescriptor(&pass)
        .ok_or_else(|| "Metal failed to create a render encoder".to_string())?;
    encoder.setRenderPipelineState(pipeline);
    unsafe {
        encoder.setFragmentBuffer_offset_atIndex(Some(guest_buffer), 0, 0);
        encoder.setFragmentBytes_length_atIndex(
            non_null_bytes(&metadata.palette),
            size_of::<[u32; 256]>(),
            1,
        );
        encoder.setFragmentBytes_length_atIndex(
            non_null_bytes(&metadata.uniforms),
            size_of::<GuestFrameUniforms>(),
            2,
        );
        encoder.setFragmentBytes_length_atIndex(
            non_null_bytes(&metadata.cursor),
            size_of::<GuestCursorData>(),
            3,
        );
    }

    let (_, _, width, height) = metadata.content_rect;
    let (drawable_width, drawable_height) = metadata.drawable_size;
    let viewport = aspect_fit_viewport(width, height, drawable_width, drawable_height);
    encoder.setViewport(MTLViewport {
        originX: viewport.0,
        originY: viewport.1,
        width: viewport.2,
        height: viewport.3,
        znear: 0.0,
        zfar: 1.0,
    });
    unsafe {
        encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::TriangleStrip, 0, 4)
    };
    encoder.endEncoding();

    if transactional {
        command_buffer.commit();
        command_buffer.waitUntilScheduled();
        let drawable: &ProtocolObject<dyn objc2_metal::MTLDrawable> =
            ProtocolObject::from_ref(drawable);
        drawable.present();
    } else {
        command_buffer.presentDrawable(ProtocolObject::from_ref(drawable));
        command_buffer.commit();
    }
    Ok(())
}

fn non_null_bytes<T>(value: &T) -> NonNull<c_void> {
    NonNull::from(value).cast::<c_void>()
}

fn guest_cursor_data(
    cursor: Option<&CursorImage>,
    mouse_pos: (i16, i16),
) -> (GuestFrameUniforms, GuestCursorData) {
    let mut uniforms = GuestFrameUniforms::default();
    let mut gpu = GuestCursorData::default();
    let Some(cursor) = cursor else {
        return (uniforms, gpu);
    };

    let (mouse_v, mouse_h) = mouse_pos;
    match cursor {
        CursorImage::Mono {
            data,
            mask,
            hot_v,
            hot_h,
        } => {
            uniforms.cursor_kind = 1;
            uniforms.cursor_width = 16;
            uniforms.cursor_height = 16;
            uniforms.cursor_left = i32::from(mouse_h) - i32::from(*hot_h);
            uniforms.cursor_top = i32::from(mouse_v) - i32::from(*hot_v);
            for row in 0..16 {
                gpu.data_rows[row] =
                    u32::from(u16::from_be_bytes([data[row * 2], data[row * 2 + 1]]));
                gpu.mask_rows[row] =
                    u32::from(u16::from_be_bytes([mask[row * 2], mask[row * 2 + 1]]));
            }
        }
        CursorImage::Color {
            width,
            height,
            pixels_argb,
            mask,
            hot_v,
            hot_h,
            ..
        } => {
            let source_width = *width;
            let width = source_width.min(16);
            let height = (*height).min(16);
            uniforms.cursor_kind = 2;
            uniforms.cursor_width = u32::from(width);
            uniforms.cursor_height = u32::from(height);
            uniforms.cursor_left = i32::from(mouse_h) - i32::from(*hot_h);
            uniforms.cursor_top = i32::from(mouse_v) - i32::from(*hot_v);
            for row in 0..16 {
                gpu.mask_rows[row] =
                    u32::from(u16::from_be_bytes([mask[row * 2], mask[row * 2 + 1]]));
            }
            for row in 0..usize::from(height) {
                let source_start = row * usize::from(source_width);
                let source_end = source_start + usize::from(width);
                let destination_start = row * usize::from(width);
                if source_end <= pixels_argb.len() {
                    gpu.color_pixels[destination_start..destination_start + usize::from(width)]
                        .copy_from_slice(&pixels_argb[source_start..source_end]);
                }
            }
        }
    }
    (uniforms, gpu)
}

fn aspect_fit_viewport(
    source_width: u32,
    source_height: u32,
    drawable_width: u32,
    drawable_height: u32,
) -> (f64, f64, f64, f64) {
    let scale = (drawable_width as f64 / source_width as f64)
        .min(drawable_height as f64 / source_height as f64);
    let width = source_width as f64 * scale;
    let height = source_height as f64 * scale;
    (
        (drawable_width as f64 - width) * 0.5,
        (drawable_height as f64 - height) * 0.5,
        width,
        height,
    )
}

fn guest_frame_byte_len(row_bytes: u32, screen_height: u32) -> Option<usize> {
    usize::try_from(row_bytes)
        .ok()?
        .checked_mul(screen_height as usize)
}

fn guest_packed_content_left(pixel_size: u16, content_left: u32) -> Option<u32> {
    match pixel_size {
        1 => Some(content_left & 7),
        2 => Some(content_left & 3),
        4 => Some(content_left & 1),
        8 => Some(0),
        _ => None,
    }
}

#[derive(Clone, Copy)]
struct GuestVisibleByteLayout {
    first_row_offset: usize,
    row_stride: usize,
    visible_row_bytes: usize,
    row_count: usize,
}

fn guest_visible_byte_layout(
    row_bytes: u32,
    pixel_size: u16,
    left: u32,
    top: u32,
    width: u32,
    height: u32,
) -> Option<GuestVisibleByteLayout> {
    let row_stride = usize::try_from(row_bytes).ok()?;
    let (first_byte, byte_end) = match pixel_size {
        1 | 2 | 4 => {
            let pixels_per_byte = 8 / u32::from(pixel_size);
            (
                usize::try_from(left / pixels_per_byte).ok()?,
                usize::try_from(
                    left.checked_add(width)?.checked_add(pixels_per_byte - 1)? / pixels_per_byte,
                )
                .ok()?,
            )
        }
        8 => (
            usize::try_from(left).ok()?,
            usize::try_from(left.checked_add(width)?).ok()?,
        ),
        _ => return None,
    };
    if byte_end > row_stride || byte_end <= first_byte || height == 0 {
        return None;
    }
    Some(GuestVisibleByteLayout {
        first_row_offset: usize::try_from(top)
            .ok()?
            .checked_mul(row_stride)?
            .checked_add(first_byte)?,
        row_stride,
        visible_row_bytes: byte_end - first_byte,
        row_count: usize::try_from(height).ok()?,
    })
}

fn guest_visible_pixels_equal(
    snapshot: &[u8],
    framebuffer: &[u8],
    layout: GuestVisibleByteLayout,
) -> bool {
    let Some(snapshot_len) = layout.visible_row_bytes.checked_mul(layout.row_count) else {
        return false;
    };
    if snapshot.len() != snapshot_len {
        return false;
    }
    for row in 0..layout.row_count {
        let Some(source_start) = row
            .checked_mul(layout.row_stride)
            .and_then(|offset| layout.first_row_offset.checked_add(offset))
        else {
            return false;
        };
        let Some(source_end) = source_start.checked_add(layout.visible_row_bytes) else {
            return false;
        };
        let snapshot_start = row * layout.visible_row_bytes;
        if framebuffer.get(source_start..source_end)
            != snapshot.get(snapshot_start..snapshot_start + layout.visible_row_bytes)
        {
            return false;
        }
    }
    true
}

fn copy_guest_visible_pixels(
    snapshot: &mut Vec<u8>,
    framebuffer: &[u8],
    layout: GuestVisibleByteLayout,
) {
    snapshot.clear();
    let capacity = layout
        .visible_row_bytes
        .checked_mul(layout.row_count)
        .unwrap_or(0);
    snapshot.reserve(capacity);
    for row in 0..layout.row_count {
        let source_start = layout.first_row_offset + row * layout.row_stride;
        let source_end = source_start + layout.visible_row_bytes;
        snapshot.extend_from_slice(&framebuffer[source_start..source_end]);
    }
}

fn copy_guest_visible_pixels_to_ptr(
    destination: *mut u8,
    framebuffer: &[u8],
    layout: GuestVisibleByteLayout,
) {
    for row in 0..layout.row_count {
        let source_start = layout.first_row_offset + row * layout.row_stride;
        let destination_start = row * layout.visible_row_bytes;
        // SAFETY: `guest_visible_byte_layout` validated every source row,
        // while the caller allocated visible_row_bytes * row_count bytes.
        unsafe {
            std::ptr::copy_nonoverlapping(
                framebuffer.as_ptr().add(source_start),
                destination.add(destination_start),
                layout.visible_row_bytes,
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        argb_bytes, aspect_fit_viewport, copy_guest_visible_pixels, guest_cursor_data,
        guest_packed_content_left, guest_visible_byte_layout, guest_visible_pixels_equal,
        replace_pending_guest_frame, FrameMetadata, FramePixels, GuestCursorData,
        GuestFrameMailboxState, GuestFrameMetadata, GuestFrameUniforms, RasterLayout,
    };
    use systemless::display::CursorImage;

    /// Exercise the production shader on the GPU, including its final reduction
    /// to drawable pixels. No AppKit window or unlocked desktop is required.
    fn render_rgba(source: &image::RgbaImage, width: u32, height: u32) -> image::RgbaImage {
        use super::*;
        autoreleasepool(|_| {
            let device = unsafe { Retained::retain(MTLCreateSystemDefaultDevice()) }
                .expect("Metal device required");
            let library = device
                .newLibraryWithSource_options_error(
                    ns_string!(include_str!("metal_present.metal")),
                    None,
                )
                .expect("compile presentation shader");
            let descriptor = MTLRenderPipelineDescriptor::new();
            descriptor.setVertexFunction(
                library
                    .newFunctionWithName(ns_string!("raster_vertex"))
                    .as_deref(),
            );
            descriptor.setFragmentFunction(
                library
                    .newFunctionWithName(ns_string!("raster_fragment"))
                    .as_deref(),
            );
            unsafe {
                descriptor
                    .colorAttachments()
                    .objectAtIndexedSubscript(0)
                    .setPixelFormat(MTLPixelFormat::RGBA8Unorm);
            }
            let pipeline = device
                .newRenderPipelineStateWithDescriptor_error(&descriptor)
                .unwrap();
            let texture = |w, h, usage| {
                let desc = unsafe {
                    MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
                        MTLPixelFormat::RGBA8Unorm,
                        w as usize,
                        h as usize,
                        false,
                    )
                };
                desc.setStorageMode(MTLStorageMode::Shared);
                desc.setUsage(usage);
                device.newTextureWithDescriptor(&desc).unwrap()
            };
            let input = texture(source.width(), source.height(), MTLTextureUsage::ShaderRead);
            let output = texture(width, height, MTLTextureUsage::RenderTarget);
            let region = |w, h| MTLRegion {
                origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
                size: objc2_metal::MTLSize {
                    width: w as usize,
                    height: h as usize,
                    depth: 1,
                },
            };
            unsafe {
                input.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
                    region(source.width(), source.height()),
                    0,
                    NonNull::new(source.as_ptr().cast_mut().cast()).unwrap(),
                    source.width() as usize * 4,
                );
            }
            let pass = unsafe { MTLRenderPassDescriptor::new() };
            let color = unsafe { pass.colorAttachments().objectAtIndexedSubscript(0) };
            color.setTexture(Some(&output));
            color.setLoadAction(MTLLoadAction::Clear);
            color.setStoreAction(MTLStoreAction::Store);
            let queue = device.newCommandQueue().unwrap();
            let command = queue.commandBuffer().unwrap();
            let encoder = command.renderCommandEncoderWithDescriptor(&pass).unwrap();
            encoder.setRenderPipelineState(&pipeline);
            encoder.setViewport(MTLViewport {
                originX: 0.0,
                originY: 0.0,
                width: width as f64,
                height: height as f64,
                znear: 0.0,
                zfar: 1.0,
            });
            unsafe {
                encoder.setFragmentTexture_atIndex(Some(&input), 0);
                encoder.drawPrimitives_vertexStart_vertexCount(
                    MTLPrimitiveType::TriangleStrip,
                    0,
                    4,
                );
            }
            encoder.endEncoding();
            command.commit();
            unsafe {
                command.waitUntilCompleted();
            }
            let mut result = image::RgbaImage::new(width, height);
            unsafe {
                output.getBytes_bytesPerRow_fromRegion_mipmapLevel(
                    NonNull::new(result.as_mut_ptr().cast()).unwrap(),
                    width as usize * 4,
                    region(width, height),
                    0,
                );
            }
            result
        })
    }

    /// Run `compact_fragment` for `crop` of `frame` into a BGRA drawable, as
    /// the presenter does, and read the drawable back as ARGB words.
    fn render_compact(
        frame: &systemless::memory::CompactPresentation,
        crop: (u32, u32, u32, u32),
        drawable: (u32, u32),
    ) -> Vec<u32> {
        use super::*;
        let uniforms = compact_frame_uniforms(frame, crop, drawable).expect("supported frame");
        autoreleasepool(|_| {
            let device = unsafe { Retained::retain(MTLCreateSystemDefaultDevice()) }
                .expect("Metal device required");
            let library = device
                .newLibraryWithSource_options_error(
                    ns_string!(include_str!("metal_present.metal")),
                    None,
                )
                .expect("compile presentation shader");
            let descriptor = MTLRenderPipelineDescriptor::new();
            descriptor.setVertexFunction(
                library
                    .newFunctionWithName(ns_string!("raster_vertex"))
                    .as_deref(),
            );
            descriptor.setFragmentFunction(
                library
                    .newFunctionWithName(ns_string!("compact_fragment"))
                    .as_deref(),
            );
            unsafe {
                descriptor
                    .colorAttachments()
                    .objectAtIndexedSubscript(0)
                    .setPixelFormat(MTLPixelFormat::BGRA8Unorm);
            }
            let pipeline = device
                .newRenderPipelineStateWithDescriptor_error(&descriptor)
                .unwrap();
            let desc = unsafe {
                MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
                    MTLPixelFormat::BGRA8Unorm,
                    drawable.0 as usize,
                    drawable.1 as usize,
                    false,
                )
            };
            desc.setStorageMode(MTLStorageMode::Shared);
            desc.setUsage(MTLTextureUsage::RenderTarget);
            let output = device.newTextureWithDescriptor(&desc).unwrap();
            let mut buffers = CompactBuffers::default();
            let (cells, detail) = buffers.upload(&device, frame).unwrap();
            let pass = unsafe { MTLRenderPassDescriptor::new() };
            let color = unsafe { pass.colorAttachments().objectAtIndexedSubscript(0) };
            color.setTexture(Some(&output));
            color.setLoadAction(MTLLoadAction::Clear);
            color.setStoreAction(MTLStoreAction::Store);
            color.setClearColor(objc2_metal::MTLClearColor {
                red: 0.0,
                green: 0.0,
                blue: 0.0,
                alpha: 1.0,
            });
            let queue = device.newCommandQueue().unwrap();
            let command = queue.commandBuffer().unwrap();
            let encoder = command.renderCommandEncoderWithDescriptor(&pass).unwrap();
            encoder.setRenderPipelineState(&pipeline);
            unsafe {
                encoder.setFragmentBuffer_offset_atIndex(Some(cells), 0, 0);
                encoder.setFragmentBuffer_offset_atIndex(Some(detail), 0, 1);
                encoder.setFragmentBytes_length_atIndex(
                    non_null_bytes(&uniforms),
                    size_of::<CompactFrameUniforms>(),
                    2,
                );
            }
            encoder.setViewport(MTLViewport {
                originX: uniforms.ox.into(),
                originY: uniforms.oy.into(),
                width: uniforms.dw.into(),
                height: uniforms.dh.into(),
                znear: 0.0,
                zfar: 1.0,
            });
            unsafe {
                encoder.drawPrimitives_vertexStart_vertexCount(
                    MTLPrimitiveType::TriangleStrip,
                    0,
                    4,
                );
            }
            encoder.endEncoding();
            command.commit();
            unsafe {
                command.waitUntilCompleted();
            }
            let mut result = vec![0u32; (drawable.0 * drawable.1) as usize];
            unsafe {
                output.getBytes_bytesPerRow_fromRegion_mipmapLevel(
                    NonNull::new(result.as_mut_ptr().cast()).unwrap(),
                    drawable.0 as usize * 4,
                    MTLRegion {
                        origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
                        size: objc2_metal::MTLSize {
                            width: drawable.0 as usize,
                            height: drawable.1 as usize,
                            depth: 1,
                        },
                    },
                    0,
                );
            }
            result
        })
    }

    #[test]
    fn compact_shader_matches_cpu_coverage_for_crops_and_drawables() {
        use systemless::memory::CompactPresentation;
        let mut seed = 0x2545_f491u32;
        let mut next = || {
            seed ^= seed << 13;
            seed ^= seed >> 17;
            seed ^= seed << 5;
            seed
        };
        for scale in [2u32, 3, 4] {
            let (width, height) = (13u32, 9u32);
            let mut frame = CompactPresentation {
                width,
                height,
                scale,
                ..Default::default()
            };
            for _ in 0..width * height {
                if next() % 4 == 0 {
                    frame.cells.push(0x80000000 | frame.detail.len() as u32);
                    for _ in 0..scale * scale {
                        frame.detail.push(next() & 0xffffff);
                    }
                } else {
                    frame.cells.push(next() & 0xffffff);
                }
            }
            let sw = width * scale;
            let full: Vec<u32> = (0..height * scale)
                .flat_map(|y| (0..sw).map(move |x| (x, y)))
                .map(|(x, y)| {
                    let cell = frame.cells[((y / scale) * width + x / scale) as usize];
                    0xff000000
                        | if cell >> 31 == 0 {
                            cell
                        } else {
                            frame.detail[(cell & 0x7fffffff) as usize
                                + ((y % scale) * scale + x % scale) as usize]
                        }
                })
                .collect();
            for crop in [(0, 0, width, height), (2, 1, 9, 7), (12, 8, 1, 1)] {
                for drawable in [
                    (crop.2 * scale, crop.3 * scale),
                    (crop.2 * scale + 7, crop.3 * scale + 3),
                    (crop.2, crop.3 + 5),
                    (crop.2 * 5 + 1, crop.3 * 2),
                    (31, 17),
                ] {
                    let (cl, ct, cw, ch) = crop;
                    let cropped: Vec<u32> = (ct * scale..(ct + ch) * scale)
                        .flat_map(|y| {
                            full[(y * sw + cl * scale) as usize..(y * sw + (cl + cw) * scale) as usize]
                                .iter()
                                .copied()
                        })
                        .collect();
                    let (ox, oy, dw, dh) =
                        super::integer_aspect_fit((cw, ch), drawable);
                    let mut scaled = Vec::new();
                    systemless::display::resize_argb_coverage(
                        &cropped,
                        (cw * scale, ch * scale),
                        (dw, dh),
                        &mut scaled,
                    );
                    let actual = render_compact(&frame, crop, drawable);
                    for y in 0..drawable.1 {
                        for x in 0..drawable.0 {
                            let expected = if x >= ox && x < ox + dw && y >= oy && y < oy + dh {
                                scaled[((y - oy) * dw + x - ox) as usize]
                            } else {
                                0xff000000
                            };
                            assert_eq!(
                                actual[(y * drawable.0 + x) as usize],
                                expected,
                                "scale={scale} crop={crop:?} drawable={drawable:?} at ({x},{y})"
                            );
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn compact_uniforms_reject_crops_outside_the_frame_and_inexact_totals() {
        use systemless::memory::CompactPresentation;
        let frame = CompactPresentation {
            width: 4,
            height: 3,
            scale: 2,
            cells: vec![0; 12],
            detail: Vec::new(),
        };
        assert!(super::compact_frame_uniforms(&frame, (0, 0, 4, 3), (8, 6)).is_some());
        assert!(super::compact_frame_uniforms(&frame, (1, 0, 4, 3), (8, 6)).is_none());
        assert!(super::compact_frame_uniforms(&frame, (0, 0, 0, 3), (8, 6)).is_none());
        assert!(super::compact_frame_uniforms(&frame, (0, 0, 4, 3), (0, 6)).is_none());
        let large = CompactPresentation {
            width: 4096,
            height: 4096,
            scale: 4,
            cells: vec![0; 4096 * 4096],
            detail: Vec::new(),
        };
        assert!(super::compact_frame_uniforms(&large, (0, 0, 4096, 4096), (100, 100)).is_none());
    }

    #[test]
    fn minification_retains_thin_strokes_between_sample_centers() {
        let source = image::RgbaImage::from_fn(8, 8, |x, _| {
            let shade = if x % 2 == 0 { 0 } else { 255 };
            image::Rgba([shade, shade, shade, 255])
        });
        for (width, expected) in [
            (2, vec![128, 128]),
            (3, vec![96, 128, 159]),
            (5, vec![96, 96, 128, 159, 159]),
        ] {
            let result = render_rgba(&source, width, 3);
            let packed: Vec<u32> = source
                .pixels()
                .map(|p| u32::from_be_bytes([p[3], p[0], p[1], p[2]]))
                .collect();
            let mut software = Vec::new();
            systemless::display::resize_argb_coverage(&packed, (8, 8), (width, 3), &mut software);
            for (gpu, cpu) in result.pixels().zip(software) {
                let [a, r, g, b] = cpu.to_be_bytes();
                for (actual, expected) in gpu.0.into_iter().zip([r, g, b, a]) {
                    assert!(actual.abs_diff(expected) <= 1);
                }
            }
            // Exact area averages retain alternating one-pixel strokes at
            // integral and fractional reductions; allow UNorm rounding error.
            for (x, _, pixel) in result.enumerate_pixels() {
                assert!(
                    pixel[0].abs_diff(expected[x as usize]) <= 1,
                    "lost coverage at width {width}, column {x}"
                );
                assert_eq!(pixel[3], 255);
            }
        }
        let enlarged = render_rgba(&source, 16, 16);
        for (x, y, pixel) in enlarged.enumerate_pixels() {
            assert_eq!(pixel, source.get_pixel(x / 2, y / 2));
        }
    }

    #[test]
    #[ignore = "writes actual Metal output; set SYSTEMLESS_METAL_FONT_CAPTURE"]
    fn capture_showcase_at_mac_window_size() {
        let path = std::env::var_os("SYSTEMLESS_METAL_FONT_CAPTURE").expect("capture output path");
        let source = image::load_from_memory(include_bytes!(
            "../../../tests/toolbox-showcase/outline-fonts/first-paint/textedit-fresh.png"
        ))
        .unwrap()
        .into_rgba8();
        // Native menus hide the guest's 20-row menu bar. The reported window
        // displays the remaining 800x580 guest area at 960x696 physical pixels.
        let scale = systemless::display::outline_output_scale((800, 580), (960, 696));
        let pixels = source
            .pixels()
            .map(|p| u32::from_be_bytes([p[3], p[0], p[1], p[2]]))
            .collect::<Vec<_>>();
        let mut resolved = Vec::new();
        systemless::display::resize_argb_coverage(
            &pixels,
            source.dimensions(),
            (800 * scale, 600 * scale),
            &mut resolved,
        );
        let bytes = resolved
            .into_iter()
            .flat_map(|p| [(p >> 16) as u8, (p >> 8) as u8, p as u8, (p >> 24) as u8])
            .collect();
        let source = image::RgbaImage::from_raw(800 * scale, 600 * scale, bytes).unwrap();
        let source =
            image::imageops::crop_imm(&source, 0, 20 * scale, 800 * scale, 580 * scale).to_image();
        render_rgba(&source, 960, 696).save(path).unwrap();
    }

    #[test]
    fn viewport_scales_continuously_and_centers_letterboxing() {
        assert_eq!(
            aspect_fit_viewport(800, 600, 1920, 1080),
            (240.0, 0.0, 1440.0, 1080.0)
        );
        assert_eq!(
            aspect_fit_viewport(800, 600, 1200, 900),
            (0.0, 0.0, 1200.0, 900.0)
        );
    }

    #[test]
    fn cropped_presentation_packs_only_visible_guest_rows() {
        let layout = guest_visible_byte_layout(800, 8, 80, 104, 640, 392).unwrap();
        assert_eq!(layout.visible_row_bytes * layout.row_count, 250_880);
    }

    #[test]
    fn cropped_four_bit_presentation_keeps_nibble_aligned_rows() {
        let layout = guest_visible_byte_layout(400, 4, 81, 10, 319, 20).unwrap();
        assert_eq!(layout.first_row_offset, 4_040);
        assert_eq!(layout.row_stride, 400);
        assert_eq!(layout.visible_row_bytes, 160);
        assert_eq!(layout.row_count, 20);
    }

    #[test]
    fn cropped_two_bit_presentation_keeps_msb_aligned_metadata_and_rows() {
        let layout = guest_visible_byte_layout(200, 2, 5, 10, 319, 20).unwrap();
        assert_eq!(guest_packed_content_left(2, 5), Some(1));
        assert_eq!(layout.first_row_offset, 2_001);
        assert_eq!(layout.row_stride, 200);
        assert_eq!(layout.visible_row_bytes, 80);
        assert_eq!(layout.row_count, 20);
    }

    #[test]
    fn guest_shader_decodes_two_bit_and_monochrome_pixels_through_the_palette() {
        let shader = include_str!("metal_present.metal");
        let (_, after_two_bit_header) = shader
            .split_once("} else if (frame.pixel_size == 2) {")
            .expect("guest shader must have an explicit 2bpp branch");
        let (two_bit_branch, monochrome_branch) = after_two_bit_header
            .split_once("} else {")
            .expect("guest shader must retain a final 1bpp branch");

        assert!(two_bit_branch.contains("x / 4"));
        assert!(two_bit_branch.contains("6 - 2 * (x & 3)"));
        assert!(two_bit_branch.contains("& 0x03"));
        assert!(two_bit_branch.contains("argb = palette[index]"));
        assert!(monochrome_branch.contains("x / 8"));
        assert!(monochrome_branch.contains("7 - (x & 7)"));
        assert!(monochrome_branch.contains("argb = palette[index]"));
    }

    #[test]
    fn raster_frames_enqueue_while_drawable_is_blocked_and_keep_latest_pixels() {
        use super::{argb_bytes, AsyncGuestPresenter, GuestFrameMailbox};
        use std::{sync::Arc, time::Duration};
        let mailbox = Arc::new(GuestFrameMailbox::default());
        {
            let mut state = mailbox.state.lock().unwrap();
            state.drawable_in_use = true;
            state.active = true;
        }
        let producer_mailbox = Arc::clone(&mailbox);
        let (sent, received) = std::sync::mpsc::channel();
        let producer = std::thread::spawn(move || {
            let presenter = AsyncGuestPresenter {
                mailbox: producer_mailbox,
                thread: None,
            };
            let mut pixels = vec![0xff123456; 16];
            for color in [0xff123456, 0xffabcdef] {
                pixels.fill(color);
                presenter.enqueue_raster(&pixels, (4, 4), (8, 8)).unwrap();
            }
            pixels.fill(0); // queued pixels must own their storage
            sent.send(presenter).unwrap();
        });
        let presenter = received
            .recv_timeout(Duration::from_secs(2))
            .expect("raster enqueue must not wait for a drawable or an active frame");
        producer.join().unwrap();
        {
            let state = mailbox.state.lock().unwrap();
            assert!(state.drawable_in_use && state.active);
            assert_eq!(state.coalesced, 1);
            let frame = state.pending.as_ref().unwrap();
            assert_eq!(frame.pixels.as_bytes(), argb_bytes(&[0xffabcdef; 16]));
            assert!(
                frame.metadata
                    == FrameMetadata::Raster {
                        layout: RasterLayout::whole((4, 4)),
                        drawable_size: (8, 8),
                    }
            );
        }
        // A mode switch replaces pending raster work in the same mailbox.
        let metadata = GuestFrameMetadata {
            screen_layout: (2, 2, 1, 8),
            content_rect: (0, 0, 2, 1),
            palette: [0; 256],
            uniforms: GuestFrameUniforms::default(),
            cursor: GuestCursorData::default(),
            drawable_size: (8, 8),
        };
        presenter
            .enqueue(
                &[7, 8],
                guest_visible_byte_layout(2, 8, 0, 0, 2, 1).unwrap(),
                metadata,
            )
            .unwrap();
        let state = mailbox.state.lock().unwrap();
        assert_eq!(state.coalesced, 2);
        assert_eq!(state.pending.as_ref().unwrap().pixels.as_bytes(), &[7u8, 8]);
    }

    #[test]
    fn busy_presenter_mailbox_keeps_only_the_latest_complete_frame() {
        let metadata = GuestFrameMetadata {
            screen_layout: (4, 4, 2, 8),
            content_rect: (0, 0, 4, 2),
            palette: [0; 256],
            uniforms: GuestFrameUniforms::default(),
            cursor: GuestCursorData::default(),
            drawable_size: (8, 4),
        };
        let mut state = GuestFrameMailboxState::default();

        let layout = guest_visible_byte_layout(4, 8, 0, 0, 4, 1).unwrap();
        replace_pending_guest_frame(
            &mut state,
            &[1, 2, 3, 4],
            layout,
            FrameMetadata::Guest(metadata.clone()),
        );
        replace_pending_guest_frame(
            &mut state,
            &[5, 6, 7, 8],
            layout,
            FrameMetadata::Guest(metadata.clone()),
        );

        assert_eq!(state.coalesced, 1);
        let pending = state.pending.as_ref().unwrap();
        assert_eq!(pending.pixels.as_bytes(), &[5u8, 6, 7, 8]);
        assert!(pending.metadata == FrameMetadata::Guest(metadata));
    }

    /// The raster present path reinterprets the caller's pixels instead of
    /// copying them, leaving the mailbox staging copy as the frame's only copy.
    #[test]
    fn raster_present_bytes_borrow_the_caller_pixels() {
        let pixels = vec![0xff00_0000u32, 0x0012_3456];
        let bytes = argb_bytes(&pixels);
        assert_eq!(bytes.as_ptr(), pixels.as_ptr().cast());
        assert_eq!(bytes.len(), pixels.len() * std::mem::size_of::<u32>());
    }

    #[test]
    fn presenter_mailbox_packs_cropped_rows_without_surrounding_pixels() {
        let metadata = GuestFrameMetadata {
            screen_layout: (6, 6, 3, 8),
            content_rect: (2, 1, 3, 2),
            palette: [0; 256],
            uniforms: GuestFrameUniforms::default(),
            cursor: GuestCursorData::default(),
            drawable_size: (6, 4),
        };
        let framebuffer = [
            0, 1, 2, 3, 4, 5, // outside the crop
            6, 7, 8, 9, 10, 11, // visible bytes 8..=10
            12, 13, 14, 15, 16, 17, // visible bytes 14..=16
        ];
        let layout = guest_visible_byte_layout(6, 8, 2, 1, 3, 2).unwrap();
        let mut state = GuestFrameMailboxState::default();

        replace_pending_guest_frame(
            &mut state,
            &framebuffer,
            layout,
            FrameMetadata::Guest(metadata),
        );

        assert_eq!(
            state.pending.unwrap().pixels.as_bytes(),
            &[8u8, 9, 10, 14, 15, 16]
        );
    }

    #[test]
    fn unchanged_detection_compares_only_cropped_visible_rows() {
        let mut framebuffer = vec![0u8; 8 * 6];
        let layout = guest_visible_byte_layout(8, 8, 2, 1, 4, 3).unwrap();
        let mut snapshot = Vec::new();
        copy_guest_visible_pixels(&mut snapshot, &framebuffer, layout);
        assert!(guest_visible_pixels_equal(&snapshot, &framebuffer, layout));

        framebuffer[0] = 1;
        assert!(
            guest_visible_pixels_equal(&snapshot, &framebuffer, layout),
            "pixels outside the crop must not trigger a GPU submission"
        );
        framebuffer[2 * 8 + 4] = 1;
        assert!(!guest_visible_pixels_equal(&snapshot, &framebuffer, layout));
    }

    #[test]
    fn monochrome_visible_comparison_includes_boundary_bytes() {
        let mut framebuffer = vec![0u8; 4 * 3];
        let layout = guest_visible_byte_layout(4, 1, 7, 1, 10, 1).unwrap();
        let mut snapshot = Vec::new();
        copy_guest_visible_pixels(&mut snapshot, &framebuffer, layout);
        assert_eq!(snapshot.len(), 3);

        framebuffer[4 + 2] = 0x80;
        assert!(!guest_visible_pixels_equal(&snapshot, &framebuffer, layout));
    }

    /// Opt-in measurement of the raster frame path into the present mailbox.
    ///
    /// A borrowed raster frame (`MetalPresenter::present`, used when the
    /// resolved outline image is presented from the bus cache) is staged into a
    /// pool buffer. An owned frame (`MetalPresenter::present_owned`, used by the
    /// cropped software path) is handed to the mailbox with the rectangle to
    /// upload, so the caller copies nothing — not even the crop, which the
    /// worker now reads in place out of the whole frame. This harness times all
    /// three at the geometry the EV Nova capture presents.
    ///
    /// ```sh
    /// cargo test --profile fast --bin systemless mailbox_raster_copy_microbench -- --ignored --nocapture
    /// ```
    #[test]
    #[ignore = "measurement harness; prints raster mailbox path timings"]
    fn mailbox_raster_copy_microbench() {
        use super::{AsyncGuestPresenter, GuestFrameMailbox};
        use std::sync::Arc;
        use std::time::{Duration, Instant};
        const WIDTH: u32 = 800;
        const HEIGHT: u32 = 600;
        // The capture presented a letterboxed rectangle inside the guest screen.
        const CROP: (u32, u32, u32, u32) = (0, 40, 800, 520);
        const FRAMES: usize = 600;

        let (crop_left, crop_top, crop_width, crop_height) = CROP;
        let crop_texels = (crop_width * crop_height) as usize;
        let full = vec![0u32; (WIDTH * HEIGHT) as usize];
        let presenter = AsyncGuestPresenter {
            mailbox: Arc::new(GuestFrameMailbox::default()),
            thread: None,
        };

        // Borrowed frame: staged into a pool buffer, one copy on this thread.
        let mut staged_borrowed = Vec::new();
        for _ in 0..FRAMES {
            let start = Instant::now();
            presenter
                .enqueue_raster(&full, (WIDTH, HEIGHT), (WIDTH, HEIGHT))
                .unwrap();
            staged_borrowed.push(start.elapsed());
        }

        // Owned frame: the whole buffer is lent to the mailbox and a spare comes
        // back, so the caller copies nothing.
        let layout = RasterLayout {
            left: crop_left,
            top: crop_top,
            width: crop_width,
            height: crop_height,
            buffer_width: WIDTH,
        };
        let mut handoff_owned = Vec::new();
        let mut scratch = full.clone();
        for _ in 0..FRAMES {
            let start = Instant::now();
            scratch = presenter
                .enqueue_raster_owned(scratch, layout, (WIDTH, HEIGHT))
                .unwrap();
            handoff_owned.push(start.elapsed());
            std::hint::black_box(&scratch);
        }
        drop(presenter);

        // The crop `crop_argb_frame` used to compact in place, as a per-row
        // `copy_within` over the full-size buffer, timed on the same buffer the
        // caller no longer walks.
        let mut crop_move = Vec::new();
        let mut frame = full.clone();
        for _ in 0..FRAMES {
            frame.extend_from_slice(&full[..(WIDTH * HEIGHT) as usize - frame.len()]);
            let start = Instant::now();
            for row in 0..crop_height as usize {
                let source = (crop_top as usize + row) * WIDTH as usize + crop_left as usize;
                frame.copy_within(
                    source..source + crop_width as usize,
                    row * crop_width as usize,
                );
            }
            frame.truncate(crop_texels);
            crop_move.push(start.elapsed());
            std::hint::black_box(&frame);
        }

        let full_bytes_per_frame = (WIDTH * HEIGHT) as usize * size_of::<u32>();
        let crop_bytes_per_frame = crop_texels * size_of::<u32>();
        eprintln!(
            "frame={WIDTH}x{HEIGHT} crop={crop_width}x{crop_height}@{crop_left},{crop_top} \
             full_bytes={full_bytes_per_frame} crop_bytes={crop_bytes_per_frame}"
        );
        summarise("staged_borrowed_frame", staged_borrowed);
        summarise("handoff_owned_frame", handoff_owned);
        summarise("materialised_crop", crop_move);
        eprintln!(
            "main-thread bytes/frame: cropped software frame before={} after={}",
            crop_bytes_per_frame * 2,
            0
        );

        fn summarise(name: &str, mut samples: Vec<Duration>) {
            samples.sort();
            let total: Duration = samples.iter().copied().sum();
            eprintln!(
                "{name}: mean={:?} p50={:?} p95={:?}",
                total / samples.len() as u32,
                samples[samples.len() / 2],
                samples[samples.len() * 95 / 100]
            );
        }
    }

    /// The raster handoff lends the caller's frame to the mailbox instead of
    /// copying it, and coalescing hands the superseded frame straight back as
    /// the caller's next scratch buffer — so no pixel moves.
    #[test]
    fn raster_handoff_lends_the_frame_and_recycles_it_through_the_mailbox() {
        use super::{AsyncGuestPresenter, GuestFrameMailbox};
        let presenter = AsyncGuestPresenter {
            mailbox: std::sync::Arc::new(GuestFrameMailbox::default()),
            thread: None,
        };
        let layout = RasterLayout {
            left: 1,
            top: 2,
            width: 2,
            height: 2,
            buffer_width: 4,
        };

        let first: Vec<u32> = (0..16).collect();
        let first_pixels = first.as_ptr();
        let spare = presenter
            .enqueue_raster_owned(first, layout, (8, 8))
            .unwrap();
        assert!(
            spare.is_empty(),
            "nothing has been presented yet, so there is no spare to hand back"
        );
        {
            let state = presenter.mailbox.state.lock().unwrap();
            let pending = state.pending.as_ref().unwrap();
            match &pending.pixels {
                FramePixels::Argb(pixels) => assert_eq!(
                    pixels.as_ptr(),
                    first_pixels,
                    "the queued frame is the caller's own allocation"
                ),
                FramePixels::Indexed(_) | FramePixels::Compact(_) => {
                    panic!("raster frames queue ARGB words")
                }
            }
            assert!(
                pending.metadata
                    == FrameMetadata::Raster {
                        layout,
                        drawable_size: (8, 8),
                    }
            );
        }

        // A second frame supersedes the first before the worker takes it.
        let second: Vec<u32> = (100..116).collect();
        let second_pixels = second.as_ptr();
        let spare = presenter
            .enqueue_raster_owned(second, layout, (8, 8))
            .unwrap();
        assert_eq!(
            spare.as_ptr(),
            first_pixels,
            "the superseded frame becomes the caller's next scratch buffer"
        );
        assert_eq!(spare, (0..16).collect::<Vec<u32>>());
        let state = presenter.mailbox.state.lock().unwrap();
        assert_eq!(state.coalesced, 1);
        match &state.pending.as_ref().unwrap().pixels {
            FramePixels::Argb(pixels) => assert_eq!(pixels.as_ptr(), second_pixels),
            FramePixels::Indexed(_) | FramePixels::Compact(_) => {
                panic!("raster frames queue ARGB words")
            }
        }
    }

    /// A presented rectangle must lie inside the buffer it is read from, and
    /// the stride must reach every row it names.
    #[test]
    fn raster_layout_rejects_rectangles_past_the_buffer() {
        let inside = RasterLayout {
            left: 2,
            top: 3,
            width: 2,
            height: 1,
            buffer_width: 4,
        };
        let buffer_bytes = 4 * 4 * size_of::<u32>();
        assert_eq!(
            inside.texel_byte_offset(buffer_bytes),
            Some((3 * 4 + 2) * size_of::<u32>())
        );
        assert_eq!(inside.texel_byte_offset(buffer_bytes - 1), None);

        let past_the_row = RasterLayout {
            left: 3,
            width: 2,
            ..inside
        };
        assert_eq!(past_the_row.texel_byte_offset(buffer_bytes), None);
        assert_eq!(
            RasterLayout::whole((0, 4)).texel_byte_offset(buffer_bytes),
            None
        );
        assert_eq!(
            RasterLayout::whole((4, 0)).texel_byte_offset(buffer_bytes),
            None
        );
        assert_eq!(
            RasterLayout::whole((4, 4)).texel_byte_offset(buffer_bytes),
            Some(0)
        );
    }

    /// The cropped handoff must upload exactly the pixels a materialised crop
    /// would have: the same rectangle, read out of the whole frame with the
    /// frame's own row stride.
    #[test]
    fn cropped_upload_matches_a_materialised_crop() {
        use super::*;
        const WIDTH: u32 = 6;
        const HEIGHT: u32 = 4;
        let frame: Vec<u32> = (0..WIDTH * HEIGHT).map(|i| 0xff00_0000 | i).collect();
        let layout = RasterLayout {
            left: 1,
            top: 1,
            width: 3,
            height: 2,
            buffer_width: WIDTH,
        };
        // What `crop_argb_frame` used to materialise for the same rectangle.
        let mut materialised = Vec::new();
        for row in 0..layout.height as usize {
            let start = (layout.top as usize + row) * WIDTH as usize + layout.left as usize;
            materialised.extend_from_slice(&frame[start..start + layout.width as usize]);
        }
        assert_eq!(materialised.len(), 6);

        autoreleasepool(|_| {
            let device = unsafe { Retained::retain(MTLCreateSystemDefaultDevice()) }
                .expect("Metal device required");
            let texture = |width: u32, height: u32| {
                let descriptor = unsafe {
                    MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
                        MTLPixelFormat::RGBA8Unorm,
                        width as usize,
                        height as usize,
                        false,
                    )
                };
                descriptor.setStorageMode(MTLStorageMode::Shared);
                descriptor.setUsage(MTLTextureUsage::ShaderRead);
                device.newTextureWithDescriptor(&descriptor).unwrap()
            };
            let read = |texture: &ProtocolObject<dyn MTLTexture>| {
                let mut bytes = vec![0u8; (layout.width * layout.height) as usize * 4];
                let region = MTLRegion {
                    origin: objc2_metal::MTLOrigin { x: 0, y: 0, z: 0 },
                    size: objc2_metal::MTLSize {
                        width: layout.width as usize,
                        height: layout.height as usize,
                        depth: 1,
                    },
                };
                unsafe {
                    texture.getBytes_bytesPerRow_fromRegion_mipmapLevel(
                        NonNull::new(bytes.as_mut_ptr().cast()).unwrap(),
                        layout.width as usize * 4,
                        region,
                        0,
                    );
                }
                bytes
            };
            let size = (layout.width, layout.height);
            let strided = texture(size.0, size.1);
            upload_raster_region(&strided, argb_bytes(&frame), layout).unwrap();
            let packed = texture(size.0, size.1);
            upload_raster_region(
                &packed,
                argb_bytes(&materialised),
                RasterLayout::whole(size),
            )
            .unwrap();

            let strided = read(&strided);
            assert_eq!(strided, read(&packed));
            let mut expected = Vec::new();
            for pixel in &materialised {
                expected.extend_from_slice(&pixel.to_ne_bytes());
            }
            assert_eq!(strided, expected);
        });
    }

    #[test]
    fn monochrome_cursor_is_packed_for_metal_without_bit_reversal() {
        let mut data = [0u8; 32];
        let mut mask = [0u8; 32];
        data[0..2].copy_from_slice(&0x8001u16.to_be_bytes());
        mask[0..2].copy_from_slice(&0xC003u16.to_be_bytes());
        let cursor = CursorImage::Mono {
            data,
            mask,
            hot_v: 3,
            hot_h: 4,
        };

        let (uniforms, gpu) = guest_cursor_data(Some(&cursor), (20, 30));

        assert_eq!(uniforms.cursor_kind, 1);
        assert_eq!((uniforms.cursor_left, uniforms.cursor_top), (26, 17));
        assert_eq!(gpu.data_rows[0], 0x8001);
        assert_eq!(gpu.mask_rows[0], 0xC003);
    }
}