aboutsummaryrefslogtreecommitdiff
path: root/vendor/libghostty-vt/src/terminal/kitty/graphics_exec.zig
blob: b1b968b283d513e78ac4cfac52909824df63695d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
const std = @import("std");
const assert = @import("../../quirks.zig").inlineAssert;
const Allocator = std.mem.Allocator;

const Terminal = @import("../Terminal.zig");
const command = @import("graphics_command.zig");
const image = @import("graphics_image.zig");
const animation = @import("graphics_animation.zig");
const pixel = @import("graphics_pixel.zig");
const Command = command.Command;
const Response = command.Response;
const LoadingImage = image.LoadingImage;
const Image = image.Image;
const ImageStorage = @import("graphics_storage.zig").ImageStorage;

const log = std.log.scoped(.kitty_gfx);

/// Execute a Kitty graphics command against the given terminal. This
/// will never fail, but the response may indicate an error and the
/// terminal state may not be updated to reflect the command. This will
/// never put the terminal in an unrecoverable state, however.
///
/// The allocator must be the same allocator that was used to build
/// the command.
pub fn execute(
    io: std.Io,
    alloc: Allocator,
    terminal: *Terminal,
    cmd: *const Command,
) ?Response {
    // If storage is disabled then we disable the full protocol. This means
    // we don't even respond to queries so the terminal completely acts as
    // if this feature is not supported.
    if (!terminal.screens.active.kitty_images.enabled()) {
        log.debug("kitty graphics requested but disabled", .{});
        return null;
    }

    log.debug("executing kitty graphics command: quiet={} control={}", .{
        cmd.quiet,
        cmd.control,
    });

    // The quiet settings used to control the response. We have to make this
    // a var because in certain special cases (namely chunked transmissions)
    // this can change.
    var quiet = cmd.quiet;

    // The protocol makes i and I mutually exclusive for every action, so this
    // must happen before dispatch and before an action can mutate storage.
    // https://sw.kovidgoyal.net/kitty/graphics-protocol/#requesting-image-ids-from-the-terminal
    const identifiers = cmd.control.identifiers();
    if (identifiers.image_id > 0 and identifiers.image_number > 0) {
        const resp: Response = .{
            .id = identifiers.image_id,
            .image_number = identifiers.image_number,
            .placement_id = identifiers.placement_id,
            .message = "EINVAL: image ID and number are mutually exclusive",
        };
        log.warn("erroneous kitty graphics response: {s}", .{resp.message});

        return switch (quiet) {
            .no => resp,
            .ok => resp,
            .failures => null,
        };
    }

    const resp_: ?Response = switch (cmd.control) {
        .query => query(io, alloc, terminal, cmd),
        .display => display(io, alloc, terminal, cmd),
        .delete => delete(io, alloc, terminal, cmd),

        .transmit, .transmit_and_display, .transmit_animation_frame => resp: {
            // If we're transmitting, then our `q` setting value is complicated.
            // The `q` setting inherits the value from the starting command
            // unless `q` is set >= 1 on this command. If it is, then we save
            // that as the new `q` setting.
            const storage = &terminal.screens.active.kitty_images;
            if (storage.loading) |loading| switch (cmd.quiet) {
                // q=0 we use whatever the start command value is
                .no => quiet = loading.quiet,

                // q>=1 we use the new value, but we should already be set to it
                inline .ok, .failures => |tag| {
                    assert(quiet == tag);
                    loading.quiet = tag;
                },
            };

            break :resp switch (cmd.control) {
                .transmit_animation_frame => transmitAnimationFrame(
                    io,
                    alloc,
                    terminal,
                    cmd,
                ),
                else => transmit(
                    io,
                    alloc,
                    terminal,
                    cmd,
                ),
            };
        },

        .control_animation => controlAnimation(
            io,
            alloc,
            terminal,
            cmd,
        ),

        .compose_animation => composeAnimation(
            io,
            alloc,
            terminal,
            cmd,
        ),
    };

    // Handle the quiet settings
    if (resp_) |resp| {
        if (!resp.ok()) {
            log.warn("erroneous kitty graphics response: {s}", .{resp.message});
        }

        return switch (quiet) {
            .no => if (resp.empty()) null else resp,
            .ok => if (resp.ok()) null else resp,
            .failures => null,
        };
    }

    return null;
}

/// Execute a "query" command.
///
/// This command is used to attempt to load an image and respond with
/// success/error but does not persist any of the command to the terminal
/// state.
fn query(
    io: std.Io,
    alloc: Allocator,
    terminal: *const Terminal,
    cmd: *const Command,
) Response {
    const t = cmd.control.query;

    // Query requires image ID. We can't actually send a response without
    // an image ID either but we return an error and this will be logged
    // downstream.
    if (t.image_id == 0) {
        return .{ .message = "EINVAL: image ID required" };
    }

    // Build a partial response to start
    var result: Response = .{
        .id = t.image_id,
        .image_number = t.image_number,
        .placement_id = t.placement_id,
    };

    // A query must attempt a complete load, then discard the result without
    // changing image storage.
    // https://sw.kovidgoyal.net/kitty/graphics-protocol/#querying-support-and-available-transmission-mediums
    const storage = &terminal.screens.active.kitty_images;
    var loading = LoadingImage.init(io, alloc, cmd, storage.image_limits) catch |err| {
        encodeError(&result, err);
        return result;
    };
    defer loading.deinit(alloc);

    var img = loading.complete(alloc) catch |err| {
        encodeError(&result, err);
        return result;
    };
    img.deinit(alloc);

    return result;
}

/// Transmit image data.
///
/// This loads the image, validates it, and puts it into the terminal
/// screen storage. It does not display the image.
fn transmit(
    io: std.Io,
    alloc: Allocator,
    terminal: *Terminal,
    cmd: *const Command,
) Response {
    const t = cmd.transmission().?;
    const storage = &terminal.screens.active.kitty_images;

    var result: Response = if (storage.loading) |loading| loading: {
        // Any transmit-like command received while a load is in progress
        // is a continuation chunk of that load, and the load completes
        // according to how it started. If an animation frame load (a=f)
        // is in progress, this chunk belongs to it even when the client
        // didn't repeat a=f on the chunk.
        if (loading.frame != null) return transmitAnimationFrame(
            io,
            alloc,
            terminal,
            cmd,
        );

        break :loading loading.response;
    } else .{
        .id = t.image_id,
        .image_number = t.image_number,
        .placement_id = t.placement_id,
    };

    const load = loadAndAddImage(io, alloc, terminal, cmd) catch |err| {
        encodeError(&result, err);
        return result;
    };
    errdefer load.image.deinit(alloc);

    // If we're also displaying, then do that now. This function does
    // both transmit and transmit and display. The display might also be
    // deferred if it is multi-chunk.
    if (load.display) |d| {
        assert(!load.more);
        var d_copy = d;
        d_copy.image_id = load.image.id;
        result = display(io, alloc, terminal, &.{
            .control = .{ .display = d_copy },
            .quiet = cmd.quiet,
        });
    }

    // If there are more chunks expected we do not respond.
    if (load.more) return .{};

    // If the loaded image was assigned its ID automatically, not based
    // on a number or explicitly specified ID, then we don't respond.
    if (load.image.metadata.implicit_id) return .{};

    // After the image is added, set the ID in case it changed.
    // The resulting image number and placement ID never change.
    result.id = load.image.id;

    return result;
}

/// Display a previously transmitted image.
fn display(
    io: std.Io,
    alloc: Allocator,
    terminal: *Terminal,
    cmd: *const Command,
) Response {
    const d = cmd.display().?;

    // Display requires image ID or number.
    if (d.image_id == 0 and d.image_number == 0) {
        return .{ .message = "EINVAL: image ID or number required" };
    }

    // Build up our response
    var result: Response = .{
        .id = d.image_id,
        .image_number = d.image_number,
        .placement_id = d.placement_id,
    };

    // A virtual placement (U=1) cannot also be a relative placement.
    // Kitty checks this before even looking up the image.
    if (d.virtual_placement and d.parent_id > 0) {
        result.message = "EINVAL: virtual placement cannot refer to a parent";
        return result;
    }

    // Verify the requested image exists if we have an ID
    const storage = &terminal.screens.active.kitty_images;
    const img_: ?Image = if (d.image_id != 0)
        storage.imageById(d.image_id)
    else
        storage.imageByNumber(d.image_number);
    const img = img_ orelse {
        result.message = "ENOENT: image not found";
        return result;
    };

    // Make sure our response has the image id in case we looked up by number
    result.id = img.id;

    // Location where the placement will go.
    const location: ImageStorage.Placement.Location = location: {
        // Virtual placements are not tracked
        if (d.virtual_placement) break :location .virtual;

        // No parent reference (P=): the placement is pinned to the
        // cursor. The cursor is always tracked but we don't want
        // this pin to move with the cursor.
        if (d.parent_id == 0) {
            const pin = terminal.screens.active.pages.trackPin(
                terminal.screens.active.cursor.page_pin.*,
            ) catch |err| {
                log.warn("failed to create pin for Kitty graphics err={}", .{err});
                result.message = "EINVAL: failed to prepare terminal state";
                return result;
            };
            break :location .{ .pin = pin };
        }

        // A parent reference makes this a relative placement: it is
        // positioned relative to the parent placement instead of the
        // cursor.

        // The key of the placement being created, when it is
        // addressable (an explicit placement ID). Needed for
        // self-parent and cycle detection.
        const child: ?ImageStorage.PlacementKey = if (d.placement_id > 0) .{
            .image_id = img.id,
            .placement_id = .{ .tag = .external, .id = d.placement_id },
        } else null;

        const parent = storage.resolveParent(
            io,
            terminal.screens.active,
            child,
            d.parent_id,
            d.parent_placement_id,
        ) catch |err| {
            result.message = switch (err) {
                error.ParentImageNotFound => "ENOPARENT: parent image not found",
                error.ParentPlacementNotFound => "ENOPARENT: parent placement not found",
                error.SelfParent => "EINVAL: placement cannot be its own parent",
                error.Cycle => "ECYCLE: parent chain creates a cycle",
                error.TooDeep => "ETOODEEP: parent chain too deep",
                error.AncestorNotFound => "ENOENT: parent chain ancestor not found",
            };
            return result;
        };

        break :location .{ .relative = .{
            .parent = parent,
            .horizontal_offset = d.horizontal_offset,
            .vertical_offset = d.vertical_offset,
        } };
    };

    // Add the placement
    const p: ImageStorage.Placement = placement: {
        var p: ImageStorage.Placement = .{
            .location = location,
            .x_offset = d.x_offset,
            .y_offset = d.y_offset,
            .source_x = d.x,
            .source_y = d.y,
            .source_width = d.width,
            .source_height = d.height,
            .columns = d.columns,
            .rows = d.rows,
            .z = d.z,
        };

        const cell_offset = p.cellOffset(terminal);
        if (terminal.width_px / terminal.cols > 0) p.x_offset = cell_offset.x;
        if (terminal.height_px / terminal.rows > 0) p.y_offset = cell_offset.y;

        break :placement p;
    };
    storage.addPlacement(
        io,
        alloc,
        terminal.screens.active,
        img.id,
        result.placement_id,
        p,
    ) catch |err| {
        p.deinit(terminal.screens.active);
        encodeError(&result, err);
        return result;
    };

    // Apply cursor movement setting. This only applies to pin placements:
    // relative placements never move the cursor regardless of C=, just
    // like kitty.
    switch (p.location) {
        .virtual, .relative => {},
        .pin => |pin| switch (d.cursor_movement) {
            .none => {},
            .after => {
                // We use terminal.index to properly handle scroll regions.
                const screen = terminal.screens.active;
                const size = p.gridSize(img, terminal);
                const target_x = @as(usize, pin.x) +| @as(usize, size.cols);
                const wraps = target_x >= @as(usize, terminal.cols);
                const requested_rows =
                    (@as(usize, size.rows) -| 1) +| @intFromBool(wraps);

                // The requested row count comes from the application and can
                // be as large as u32. Calling terminal.index once for every
                // row could therefore leave the terminal unresponsive for a
                // very long time.
                //
                // First allow enough calls to reach the bottom of the scroll
                // region. Each call after that scrolls the region by one row,
                // so limit those extra calls to one screen. This follows
                // Kitty's behavior while keeping the amount of work bounded.
                const region = terminal.scrolling_region;
                const rows_before_scroll: usize = if (screen.cursor.y >= region.top and
                    screen.cursor.y <= region.bottom and
                    screen.cursor.x >= region.left and
                    screen.cursor.x <= region.right)
                    @as(usize, region.bottom - screen.cursor.y)
                else
                    0;
                const rows_to_move: usize = @min(
                    requested_rows,
                    rows_before_scroll +| @as(usize, terminal.rows),
                );
                for (0..rows_to_move) |_| terminal.index() catch |err| {
                    log.warn("failed to move cursor: {}", .{err});
                    break;
                };

                // Kitty wraps once when the movement reaches the right edge;
                // otherwise it leaves the cursor immediately to the right of
                // the placement.
                screen.cursor.pending_wrap = false;
                screen.cursorHorizontalAbsolute(
                    if (wraps) 0 else @intCast(target_x),
                );
            },
        },
    }

    return result;
}

/// Transmit animation frame data (a=f).
///
/// Frame data is loaded exactly like image data, including chunking
/// and every transmission medium, and once complete it is composed
/// into a frame of an existing image's animation.
fn transmitAnimationFrame(
    io: std.Io,
    alloc: Allocator,
    terminal: *Terminal,
    cmd: *const Command,
) Response {
    const storage = &terminal.screens.active.kitty_images;

    // A chunk arriving while a load is in progress continues that load.
    if (storage.loading) |loading| {
        // If this is the first frame, then we treat it like a normal image
        // because the first frame is just the image.
        if (loading.frame == null) return transmit(
            io,
            alloc,
            terminal,
            cmd,
        );

        // Not the first frame, so continue loading similar to transmit
        // but this is for a subsequent frame.
        var result = loading.response;
        loading.addData(alloc, cmd.data) catch |err| {
            encodeError(&result, err);
            return result;
        };

        // If more chunks are expected we don't respond yet.
        const t = cmd.transmission().?;
        if (t.more_chunks) return .{};

        // Final chunk: copy the loading state out and free the
        // pointer, mirroring loadAndAddImage.
        var loading_copy = loading.*;
        alloc.destroy(loading);
        storage.loading = null;
        defer loading_copy.deinit(alloc);
        return completeAnimationFrame(
            io,
            alloc,
            terminal,
            &loading_copy,
        );
    }

    // We are starting our load, either the first frame or a subsequent frame.
    const f = cmd.control.transmit_animation_frame;
    const t = f.transmission;
    var result: Response = .{
        .id = t.image_id,
        .image_number = t.image_number,
        .placement_id = t.placement_id,
        // Errors echo the client's frame number; on success this is
        // replaced with the resolved (possibly newly assigned) one.
        .frame = f.edit_frame,
    };

    // A frame can only be added to an existing image.
    if (t.image_id == 0 and t.image_number == 0) {
        result.message = "EINVAL: image ID or number required";
        return result;
    }
    const img = storage.imagePtrByIdOrNumber(
        t.image_id,
        t.image_number,
    ) orelse {
        result.message = "ENOENT: image not found";
        return result;
    };
    result.id = img.id;

    var loading = LoadingImage.init(
        io,
        alloc,
        cmd,
        storage.image_limits,
    ) catch |err| {
        encodeError(&result, err);
        return result;
    };
    loading.frame = .{
        .cmd = f,
        .image_generation = img.generation,
    };
    loading.response.id = img.id;

    // Chunked: store the loading state and wait for the rest. The
    // frame parameters above are saved with it; continuation chunks
    // contribute only payload bytes.
    if (t.more_chunks) {
        const loading_ptr = alloc.create(LoadingImage) catch |err| {
            loading.deinit(alloc);
            encodeError(&result, err);
            return result;
        };
        loading_ptr.* = loading;
        storage.loading = loading_ptr;
        return .{};
    }

    defer loading.deinit(alloc);
    return completeAnimationFrame(
        io,
        alloc,
        terminal,
        &loading,
    );
}

/// Complete a fully loaded animation frame: validate it against its
/// image and compose it into the image's animation.
fn completeAnimationFrame(
    io: std.Io,
    alloc: Allocator,
    terminal: *Terminal,
    loading: *LoadingImage,
) Response {
    const storage = &terminal.screens.active.kitty_images;
    var result = loading.response;
    const f = loading.frame.?.cmd;

    // Re-resolve the image: it may have been deleted, evicted, or
    // replaced while the frame data was being transmitted. The saved
    // generation pins the exact image the load started against.
    var img = storage.imagePtrByIdOrNumber(
        loading.image.id,
        loading.image.number,
    ) orelse {
        result.message = "ENOENT: image not found";
        return result;
    };
    if (img.generation != loading.frame.?.image_generation) {
        result.message = "ENOENT: image not found";
        return result;
    }
    if (img.data.bytes() == null) {
        result.message = "EINVAL: image data incomplete";
        return result;
    }

    // Finish decoding the frame data: decompression, PNG decoding,
    // and length validation all match image loading.
    var frame_img = loading.complete(alloc) catch |err| {
        encodeError(&result, err);
        return result;
    };
    defer frame_img.deinit(alloc);

    // The frame rectangle may not exceed the image's size. The x/y
    // offsets are deliberately not validated: composition clips,
    // matching Kitty.
    if (frame_img.width > img.width or frame_img.height > img.height) {
        result.message = "EINVAL: frame dimensions exceed image";
        return result;
    }

    // All composition happens in RGBA; convert both sides as needed.
    if (frame_img.format != .rgba) {
        const rgba = pixel.rgbaFromFormat(
            alloc,
            frame_img.format,
            frame_img.data.bytes().?,
        ) catch |err| {
            encodeError(&result, err);
            return result;
        };
        frame_img.data.deinit(alloc);
        frame_img.data = .{ .complete = rgba };
        frame_img.format = .rgba;
    }
    storage.convertImageToRgba(io, alloc, img) catch |err| {
        encodeError(&result, err);
        return result;
    };

    const anim = ensureAnimation(alloc, img) catch |err| {
        encodeError(&result, err);
        return result;
    };

    // Resolve the frame number: r in 1..count edits that existing
    // frame, anything else (including omitted) creates a new frame
    // appended at count+1. The resolved number is echoed in the
    // response so clients can learn assigned frame numbers.
    const count: u32 = anim.frameCount();
    const number: u32 = number: {
        const r = f.edit_frame;
        if (r == 0 or r > count + 1) break :number count + 1;
        break :number r;
    };
    result.frame = number;

    const src = frame_img.data.bytes().?;
    if (number == count + 1) {
        // Creating a new frame. The gap defaults to 40ms when omitted
        // and a negative gap creates a gapless (never shown) frame.
        const gap: u32 = if (f.gap_ms > 0)
            @intCast(f.gap_ms)
        else if (f.gap_ms < 0)
            0
        else
            animation.default_gap_ms;

        // The base canvas frame must exist before we reserve space.
        if (f.create_frame > 0 and img.frameData(f.create_frame) == null) {
            result.message = "EINVAL: base frame not found";
            return result;
        }

        // Reserve room for the new frame, evicting other images if
        // needed. Eviction can remove images (never this one), so we
        // re-resolve our pointer afterwards to be safe.
        const frame_len: usize = @as(usize, img.width) * img.height * 4;
        const image_id = img.id;
        storage.reserveAnimationBytes(
            io,
            alloc,
            terminal.screens.active,
            image_id,
            frame_len,
        ) catch {
            result.message = "ENOSPC: animation frame storage full";
            return result;
        };
        img = storage.imagePtrByIdOrNumber(image_id, 0).?;

        const canvas = alloc.alloc(u8, frame_len) catch {
            storage.releaseAnimationBytes(frame_len);
            result.message = "ENOMEM: out of memory";
            return result;
        };
        if (f.create_frame > 0) {
            @memcpy(canvas, img.frameData(f.create_frame).?);
        } else {
            pixel.fillBackground(canvas, f.background);
        }
        pixel.composeRect(
            canvas,
            img.width,
            img.height,
            src,
            frame_img.width,
            frame_img.height,
            f.x,
            f.y,
            f.composition_mode,
        );

        anim.frames.append(alloc, .{
            .data = canvas,
            .gap_ms = gap,
        }) catch {
            alloc.free(canvas);
            storage.releaseAnimationBytes(frame_len);
            result.message = "ENOMEM: out of memory";
            return result;
        };

        // A new frame never changes the displayed frame (playback
        // reaches it later), but the storage content changed.
        storage.markMutated(io);
    } else {
        // Editing an existing frame. A nonzero gap also updates the
        // frame's gap; the 40ms default doesn't apply to edits.
        //
        // Unlike frame creation there is no byte reservation here:
        // frames are always stored at full image size, so the edit
        // composes into the existing buffer in place and storage
        // usage cannot change. Kitty likewise exempts frame edits
        // from its quota check.
        if (f.gap_ms != 0) anim.setGapAt(
            number - 1,
            if (f.gap_ms > 0) @intCast(f.gap_ms) else 0,
        );

        // The frame data is owned by this storage, so the const cast
        // is safe (same reasoning as the renderer's image uploads).
        const dst = @constCast(img.frameData(number).?);
        pixel.composeRect(
            dst,
            img.width,
            img.height,
            src,
            frame_img.width,
            frame_img.height,
            f.x,
            f.y,
            f.composition_mode,
        );

        if (number - 1 == anim.current_index) {
            // The displayed pixels changed; restart the frame's gap
            // timer like Kitty's re-upload does.
            anim.frame_shown_at_ms = null;
            storage.markImageContentChanged(io, img);
        } else {
            storage.markMutated(io);
        }
    }

    return result;
}

/// Control animation playback (a=a).
///
/// Successful commands never respond. The only possible responses are
/// for a missing image or identifier. Invalid key values are silently
/// ignored, matching Kitty.
fn controlAnimation(
    io: std.Io,
    alloc: Allocator,
    terminal: *Terminal,
    cmd: *const Command,
) Response {
    const a = cmd.control.control_animation;
    const storage = &terminal.screens.active.kitty_images;

    var result: Response = .{
        .id = a.image_id,
        .image_number = a.image_number,
        .placement_id = a.placement_id,
    };
    if (a.image_id == 0 and a.image_number == 0) {
        result.message = "EINVAL: image ID or number required";
        return result;
    }
    const img = storage.imagePtrByIdOrNumber(
        a.image_id,
        a.image_number,
    ) orelse {
        result.message = "ENOENT: image not found";
        return result;
    };

    const anim = ensureAnimation(alloc, img) catch |err| {
        encodeError(&result, err);
        return result;
    };

    // The keys below are applied independently and in the same order as Kitty.

    // Set a frame's gap (r= together with z=). This is the only way
    // to give the root frame a gap, since it is created gapless.
    if (a.frame != 0 and a.frame <= anim.frameCount() and a.gap_ms != 0) {
        anim.setGapAt(
            a.frame - 1,
            if (a.gap_ms > 0) @intCast(a.gap_ms) else 0,
        );
        storage.markMutated(io);
    }

    // Set the current frame (c=), the client-driven animation
    // primitive.
    if (a.current_frame != 0 and a.current_frame <= anim.frameCount() and
        a.current_frame - 1 != anim.current_index)
    {
        anim.current_index = a.current_frame - 1;
        anim.frame_shown_at_ms = null;
        storage.markImageContentChanged(io, img);
    }

    // Set the playback state (s=). Any state change resets the loop
    // counter; leaving the stopped state restarts the gap timer.
    if (a.action != .invalid) {
        const old = anim.state;
        anim.state = switch (a.action) {
            .invalid => unreachable,
            .stop => .stopped,
            .run_wait => .loading,
            .run => .running,
        };
        if (old == .stopped and anim.state != .stopped) {
            anim.frame_shown_at_ms = null;
        }
        anim.current_loop = 0;
        storage.markMutated(io);
    }

    // Set the loop count (v=), stored off by one per the protocol:
    // v=1 loops forever, v=n plays n-1 loops.
    if (a.loops != 0) {
        anim.max_loops = a.loops - 1;
        storage.markMutated(io);
    }

    // Successful animation control commands never respond.
    return .{};
}

/// Compose a rectangle of pixels from one animation frame onto
/// another (a=c). Frame 1 (the root frame) always exists, so this also works
/// on images without any animation state.
fn composeAnimation(
    io: std.Io,
    alloc: Allocator,
    terminal: *Terminal,
    cmd: *const Command,
) Response {
    const c = cmd.control.compose_animation;
    const storage = &terminal.screens.active.kitty_images;

    var result: Response = .{
        .id = c.image_id,
        .image_number = c.image_number,
        .placement_id = c.placement_id,
    };
    if (c.image_id == 0 and c.image_number == 0) {
        result.message = "EINVAL: image ID or number required";
        return result;
    }
    const img = storage.imagePtrByIdOrNumber(
        c.image_id,
        c.image_number,
    ) orelse {
        result.message = "ENOENT: image not found";
        return result;
    };
    result.id = img.id;
    if (img.data.bytes() == null) {
        result.message = "EINVAL: image data incomplete";
        return result;
    }

    // Both frames must exist. Note that r is the source frame and c
    // the destination; the spec's reference table describes these
    // backwards (see AnimationFrameComposition).
    if (img.frameData(c.source_frame) == null) {
        result.message = "ENOENT: source frame not found";
        return result;
    }
    if (img.frameData(c.dest_frame) == null) {
        result.message = "ENOENT: destination frame not found";
        return result;
    }

    // Rectangle validation is done in u64 so untrusted 32-bit values
    // can't overflow. Out-of-bounds rectangles are errors here,
    // unlike a=f which clips.
    const width: u64 = if (c.width > 0) c.width else img.width;
    const height: u64 = if (c.height > 0) c.height else img.height;
    if (@as(u64, c.x) + width > img.width or
        @as(u64, c.y) + height > img.height)
    {
        result.message = "EINVAL: destination rectangle out of bounds";
        return result;
    }
    if (@as(u64, c.left_edge) + width > img.width or
        @as(u64, c.top_edge) + height > img.height)
    {
        result.message = "EINVAL: source rectangle out of bounds";
        return result;
    }

    // Composing a frame onto itself requires non-overlapping
    // rectangles.
    if (c.source_frame == c.dest_frame) {
        const x_overlaps = @max(c.left_edge, c.x) < @min(c.left_edge, c.x) + width;
        const y_overlaps = @max(c.top_edge, c.y) < @min(c.top_edge, c.y) + height;
        if (x_overlaps and y_overlaps) {
            result.message = "EINVAL: source and destination rectangles overlap";
            return result;
        }
    }

    // All composition happens in RGBA.
    storage.convertImageToRgba(
        io,
        alloc,
        img,
    ) catch |err| {
        encodeError(&result, err);
        return result;
    };

    // The frame data is owned by this storage, so the const cast is
    // safe. The rectangles were validated disjoint above, so in-place
    // composition within one frame is well-defined.
    const src = img.frameData(c.source_frame).?;
    const dst = @constCast(img.frameData(c.dest_frame).?);
    pixel.composeCanvasRect(
        dst,
        src,
        img.width,
        @intCast(width),
        @intCast(height),
        c.left_edge,
        c.top_edge,
        c.x,
        c.y,
        c.composition_mode,
    );

    // If the destination is the displayed frame then the on-screen
    // content changed.
    const current: u32 = if (img.animation) |anim| anim.current_index else 0;
    if (c.dest_frame - 1 == current) {
        storage.markImageContentChanged(io, img);
    } else {
        storage.markMutated(io);
    }

    return result;
}

/// Get or lazily create the animation state for an image.
fn ensureAnimation(
    alloc: Allocator,
    img: *Image,
) Allocator.Error!*animation.Animation {
    if (img.animation) |anim| return anim;
    const anim = try alloc.create(animation.Animation);
    anim.* = .{};
    img.animation = anim;
    return anim;
}

/// Display a previously transmitted image.
fn delete(
    io: std.Io,
    alloc: Allocator,
    terminal: *Terminal,
    cmd: *const Command,
) Response {
    const storage = &terminal.screens.active.kitty_images;

    // Every delete command aborts an incomplete chunked upload.
    if (storage.loading) |loading| {
        loading.destroy(alloc);
        storage.loading = null;
    }

    // Then perform the actual deletion request, too.
    storage.delete(
        io,
        alloc,
        terminal,
        cmd.control.delete.action,
    );

    // Delete never responds on success
    return .{};
}

fn loadAndAddImage(
    io: std.Io,
    alloc: Allocator,
    terminal: *Terminal,
    cmd: *const Command,
) !struct {
    image: Image,
    more: bool = false,
    display: ?command.Display = null,
} {
    const t = cmd.transmission().?;
    const storage = &terminal.screens.active.kitty_images;

    // Determine our image. This also handles chunking and early exit.
    var loading: LoadingImage = if (storage.loading) |loading| loading: {
        // Note: we do NOT want to call "cmd.toOwnedData" here because
        // we're _copying_ the data. We want the command data to be freed.
        try loading.addData(alloc, cmd.data);

        // If we have more then we're done
        if (t.more_chunks) return .{ .image = loading.image, .more = true };

        // We have no more chunks. We're going to be completing the
        // image so we want to destroy the pointer to the loading
        // image and copy it out.
        defer {
            alloc.destroy(loading);
            storage.loading = null;
        }

        break :loading loading.*;
    } else loading: {
        // Reusing a specific image ID deletes the old image and all of its
        // placements when the new transmission begins, not when it completes.
        if (t.image_id > 0) {
            storage.delete(io, alloc, terminal, .{ .id = .{
                .image_id = t.image_id,
                .delete = true,
            } });
        }

        break :loading try .init(io, alloc, cmd, storage.image_limits);
    };

    // We only want to deinit on error. If we're chunking, then we don't
    // want to deinit at all. If we're not chunking, then we'll deinit
    // after we've copied the image out.
    errdefer loading.deinit(alloc);

    // If the image has no ID, we assign one
    if (loading.image.id == 0) {
        if (loading.image.number > 0) {
            loading.image.id = storage.nextImageId(.explicit);
        } else {
            loading.image.id = storage.nextImageId(.implicit);
            loading.image.metadata.implicit_id = true;
        }
    }

    // If this is chunked, this is the beginning of a new chunked transmission.
    // (We checked for an in-progress chunk above.)
    if (t.more_chunks) {
        // We allocate the pointer on the heap because its rare and we
        // don't want to always pay the memory cost to keep it around.
        const loading_ptr = try alloc.create(LoadingImage);
        errdefer alloc.destroy(loading_ptr);
        loading_ptr.* = loading;
        storage.loading = loading_ptr;
        return .{ .image = loading.image, .more = true };
    }

    // Dump the image data before it is decompressed
    // loading.debugDump() catch unreachable;

    // Validate and store our image
    var img = try loading.complete(alloc);
    errdefer img.deinit(alloc);
    try storage.addImage(io, alloc, terminal.screens.active, img);

    // Get our display settings
    const display_ = loading.display;

    // Ensure we deinit the loading state because we're done. The image
    // won't be deinit because of "complete" above.
    loading.deinit(alloc);

    return .{ .image = img, .display = display_ };
}

const EncodeableError = Image.Error || Allocator.Error;

/// Encode an error code into a message for a response.
fn encodeError(r: *Response, err: EncodeableError) void {
    switch (err) {
        error.OutOfMemory => r.message = "ENOMEM: out of memory",
        error.InsufficientData => r.message = "ENODATA: insufficient data",
        error.InvalidData => r.message = "EINVAL: invalid data",
        error.DecompressionFailed => r.message = "EINVAL: decompression failed",
        error.FilePathTooLong => r.message = "EINVAL: file path too long",
        error.TemporaryFileNotInTempDir => r.message = "EINVAL: temporary file not in temp dir",
        error.TemporaryFileNotNamedCorrectly => r.message = "EINVAL: temporary file not named correctly",
        error.UnsupportedFormat => r.message = "EINVAL: unsupported format",
        error.UnsupportedMedium => r.message = "EINVAL: unsupported medium",
        error.UnsupportedDepth => r.message = "EINVAL: unsupported pixel depth",
        error.DimensionsRequired => r.message = "EINVAL: dimensions required",
        error.DimensionsTooLarge => r.message = "EINVAL: dimensions too large",
    }
}

test "kittygfx query validates image data" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var terminal = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer terminal.deinit(alloc);

    var cmd: Command = .{
        .control = .{ .query = .{
            .format = .rgb,
            .width = 1,
            .height = 1,
            .image_id = 31,
        } },
        // A 1x1 RGB image requires three bytes.
        .data = try alloc.dupe(u8, &.{ 0, 0 }),
    };
    defer cmd.deinit(alloc);

    const resp = execute(io, alloc, &terminal, &cmd).?;
    try testing.expect(!resp.ok());
    try testing.expectEqual(@as(u32, 31), resp.id);
    try testing.expectEqualStrings("EINVAL: invalid data", resp.message);
    try testing.expectEqual(
        @as(usize, 0),
        terminal.screens.active.kitty_images.images.count(),
    );
}

test "kittygfx valid query does not replace or store image" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var terminal = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer terminal.deinit(alloc);
    const storage = &terminal.screens.active.kitty_images;

    // Store a red pixel under the same ID used by the query.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=31;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &terminal, &cmd).?.ok());
    }

    // Successfully validate a black pixel without replacing the red one.
    var cmd: Command = .{
        .control = .{ .query = .{
            .format = .rgb,
            .width = 1,
            .height = 1,
            .image_id = 31,
        } },
        .data = try alloc.dupe(u8, &.{ 0, 0, 0 }),
    };
    defer cmd.deinit(alloc);

    const resp = execute(io, alloc, &terminal, &cmd).?;
    try testing.expect(resp.ok());
    try testing.expectEqual(@as(usize, 1), storage.images.count());
    try testing.expectEqualSlices(
        u8,
        &.{ 255, 0, 0 },
        storage.imageById(31).?.data.bytes().?,
    );
}

test "kittygfx image id and number are mutually exclusive for every action" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    const inputs = [_][]const u8{
        "a=q,f=24,s=1,v=1,i=1,I=2,p=3;AAAA",
        "a=t,f=24,s=1,v=1,i=1,I=2,p=3;AAAA",
        "a=T,f=24,s=1,v=1,i=1,I=2,p=3;AAAA",
        "a=p,i=1,I=2,p=3",
        "a=d,d=a,i=1,I=2,p=3",
        "a=f,i=1,I=2,p=3;AAAA",
        "a=a,i=1,I=2,p=3",
        "a=c,i=1,I=2,p=3",
    };

    for (inputs) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);

        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(!resp.ok());
        try testing.expectEqual(@as(u32, 1), resp.id);
        try testing.expectEqual(@as(u32, 2), resp.image_number);
        try testing.expectEqual(@as(u32, 3), resp.placement_id);
        try testing.expectEqualStrings(
            "EINVAL: image ID and number are mutually exclusive",
            resp.message,
        );

        var buf: [128]u8 = undefined;
        var writer: std.Io.Writer = .fixed(&buf);
        try resp.encode(&writer);
        try testing.expectEqualStrings(
            "\x1b_Gi=1,I=2,p=3;EINVAL: image ID and number are mutually exclusive\x1b\\",
            writer.buffered(),
        );
    }

    try testing.expectEqual(@as(usize, 0), t.screens.active.kitty_images.images.count());
    try testing.expectEqual(@as(usize, 0), t.screens.active.kitty_images.placements.count());
}

test "kittygfx conflicting identifiers are rejected before mutation" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // Store an image so a buggy put would succeed and mutate placement state.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Directly constructed commands must receive the same validation as
    // commands produced by the parser.
    {
        const cmd: Command = .{ .control = .{ .display = .{
            .image_id = 1,
            .image_number = 2,
            .placement_id = 7,
            .cursor_movement = .none,
        } } };
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(!resp.ok());
        try testing.expectEqual(@as(u32, 1), resp.id);
        try testing.expectEqual(@as(u32, 2), resp.image_number);
        try testing.expectEqual(@as(u32, 7), resp.placement_id);
        try testing.expectEqual(@as(usize, 0), storage.placements.count());
    }

    // Add a real placement so a buggy delete would remove it.
    {
        const cmd = try command.Parser.parseString(alloc, "a=p,i=1,p=7,C=1");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
        try testing.expectEqual(@as(usize, 1), storage.placements.count());
    }

    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=d,d=i,i=1,I=2,p=7",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(!resp.ok());
        try testing.expectEqual(@as(usize, 1), storage.placements.count());
    }

    // q=2 suppresses the required error response but not the validation.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=d,d=i,i=1,I=2,p=7,q=2",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
        try testing.expectEqual(@as(usize, 1), storage.placements.count());
    }
}

test "kittygfx chunked success response uses initial identifiers" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=2,I=93,p=7,m=1;AAAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }

    {
        const cmd = try command.Parser.parseString(alloc, "m=0;AAAA");
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;

        try testing.expect(resp.ok());
        try testing.expectEqual(@as(u32, 1), resp.id);
        try testing.expectEqual(@as(u32, 93), resp.image_number);
        try testing.expectEqual(@as(u32, 7), resp.placement_id);

        var buf: [128]u8 = undefined;
        var writer: std.Io.Writer = .fixed(&buf);
        try resp.encode(&writer);
        try testing.expectEqualStrings(
            "\x1b_Gi=1,I=93,p=7;OK\x1b\\",
            writer.buffered(),
        );
    }
}

test "kittygfx chunked error response uses initial identifiers" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=41,p=7,m=1;AA==",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }

    {
        const cmd = try command.Parser.parseString(alloc, "m=0;AA==");
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;

        try testing.expect(!resp.ok());
        try testing.expectEqual(@as(u32, 41), resp.id);
        try testing.expectEqual(@as(u32, 7), resp.placement_id);
        try testing.expectEqualStrings("EINVAL: invalid data", resp.message);
    }
}

test "kittygfx more chunks with q=1" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    // Initial chunk has q=1
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=T,f=24,t=d,i=1,s=1,v=2,c=10,r=1,m=1,q=1;////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd);
        try testing.expect(resp == null);
    }

    // Subsequent chunk has no q but should respect initial
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "m=0;////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd);
        try testing.expect(resp == null);
    }
}

test "kittygfx more chunks with q=0" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    // Initial chunk has q=0
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,t=d,s=1,v=2,c=10,r=1,m=1,i=1,q=0;////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd);
        try testing.expect(resp == null);
    }

    // Subsequent chunk has no q so should respond OK
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "m=0;////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }
}

test "kittygfx more chunks with chunk increasing q" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    // Initial chunk has q=0
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,t=d,s=1,v=2,c=10,r=1,m=1,i=1,q=0;////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd);
        try testing.expect(resp == null);
    }

    // Subsequent chunk sets q=1 so should not respond
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "m=0,q=1;////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd);
        try testing.expect(resp == null);
    }
}

test "kittygfx delete aborts chunked image load" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // Begin a two-chunk RGB image, then interrupt it with a delete.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=2,i=1,m=1;AAAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    try testing.expect(storage.loading != null);

    {
        const cmd = try command.Parser.parseString(alloc, "a=d");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    try testing.expect(storage.loading == null);

    // A fresh chunked upload must start from empty state after the delete.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=2,i=1,m=1;AAAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    {
        const cmd = try command.Parser.parseString(alloc, "m=0;AAAA");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    try testing.expectEqual(@as(usize, 6), storage.imageById(1).?.data.len());
}

test "kittygfx uppercase id delete preserves image when placement does not match" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // Store an unplaced 1x1 RGB image.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;AAAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Uppercase deletion may free data only if the named placement matched.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=d,d=I,i=1,p=7",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }

    try testing.expect(storage.imageById(1) != null);
}

test "kittygfx default format is rgba" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    const cmd = try command.Parser.parseString(
        alloc,
        "a=t,t=d,i=1,s=1,v=2,c=10,r=1;///////////",
    );
    defer cmd.deinit(alloc);
    const resp = execute(io, alloc, &t, &cmd).?;
    try testing.expect(resp.ok());

    const storage = &t.screens.active.kitty_images;
    const img = storage.imageById(1).?;
    try testing.expectEqual(command.Transmission.Format.rgba, img.format);
}

test "kittygfx test valid u32 (expect invalid image ID)" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    const cmd = try command.Parser.parseString(
        alloc,
        "a=p,i=4294967295",
    );
    defer cmd.deinit(alloc);
    const resp = execute(io, alloc, &t, &cmd).?;
    try testing.expect(!resp.ok());
    try testing.expectEqual(resp.message, "ENOENT: image not found");
}

test "kittygfx test valid i32 (expect invalid image ID)" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    const cmd = try command.Parser.parseString(
        alloc,
        "a=p,i=1,z=-2147483648",
    );
    defer cmd.deinit(alloc);
    const resp = execute(io, alloc, &t, &cmd).?;
    try testing.expect(!resp.ok());
    try testing.expectEqual(resp.message, "ENOENT: image not found");
}

test "kittygfx no response with no image ID or number" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,t=d,s=1,v=2,c=10,r=1,i=0,I=0;////////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd);
        try testing.expect(resp == null);
    }
}

test "kittygfx no response with no image ID or number load and display" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=T,f=24,t=d,s=1,v=2,c=10,r=1,i=0,I=0;////////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd);
        try testing.expect(resp == null);
    }
}

test "kittygfx retransmit same id gets fresh image generation" {
    const testing = std.testing;
    const io = testing.io;
    const alloc = testing.allocator;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // Transmit a 1x2 RGB image with id=1.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,t=d,f=24,i=1,s=1,v=2;////////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }
    const gen1 = storage.imageById(1).?.generation;
    try testing.expect(gen1 > 0);
    try testing.expectEqual(gen1, storage.generation);

    // Retransmit the same id with identical dimensions/length. The
    // (width, height, format, len) tuple is identical, so only the
    // generation can reveal that the contents were replaced.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,t=d,f=24,i=1,s=1,v=2;AAAAAAAA",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }
    const gen2 = storage.imageById(1).?.generation;
    try testing.expect(gen2 > gen1);
    try testing.expectEqual(gen2, storage.generation);
}

test "kittygfx retransmit same id removes existing placements" {
    const testing = std.testing;
    const io = testing.io;
    const alloc = testing.allocator;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    const tracked = t.screens.active.pages.countTrackedPins();

    // Transmit and display an image, then add anonymous and named placements.
    // Multiple anonymous a=p placements for one image are explicitly valid.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=T,t=d,f=24,i=1,s=1,v=2,C=1;////////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }
    {
        const cmd = try command.Parser.parseString(alloc, "a=p,i=1,C=1");
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }
    {
        const cmd = try command.Parser.parseString(alloc, "a=p,i=1,p=7,C=1");
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }
    try testing.expectEqual(@as(usize, 3), storage.placements.count());
    try testing.expectEqual(
        tracked + 3,
        t.screens.active.pages.countTrackedPins(),
    );

    // Retransmitting replaces the image and must delete every old placement.
    // Plain a=t creates no replacement placement of its own.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,t=d,f=24,i=1,s=1,v=2;AAAAAAAA",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }
    try testing.expectEqual(@as(usize, 0), storage.placements.count());
    try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins());

    // a=T creates one new placement after deleting the previous image and
    // placements, so repeated redraws remain bounded at one placement.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=T,t=d,f=24,i=1,s=1,v=2,C=1;////////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=T,t=d,f=24,i=1,s=1,v=2,C=1;AAAAAAAA",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }
    try testing.expectEqual(@as(usize, 1), storage.placements.count());
    try testing.expectEqual(
        tracked + 1,
        t.screens.active.pages.countTrackedPins(),
    );
}

test "kittygfx retransmit same id removes image on first chunk" {
    const testing = std.testing;
    const io = testing.io;
    const alloc = testing.allocator;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    const tracked = t.screens.active.pages.countTrackedPins();

    // Store and display the old image.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=T,t=d,f=24,i=1,s=1,v=2,C=1;////////",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    try testing.expect(storage.imageById(1) != null);
    try testing.expectEqual(@as(usize, 1), storage.placements.count());
    try testing.expectEqual(
        tracked + 1,
        t.screens.active.pages.countTrackedPins(),
    );

    // Starting a replacement for the same explicit ID removes the old image
    // and placements before the replacement's final chunk arrives.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,t=d,f=24,i=1,s=1,v=2,m=1;AAAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    try testing.expect(storage.loading != null);
    try testing.expect(storage.imageById(1) == null);
    try testing.expectEqual(@as(usize, 0), storage.placements.count());
    try testing.expectEqual(tracked, t.screens.active.pages.countTrackedPins());
}

test "kittygfx delete then retransmit same id gets fresh generation" {
    const testing = std.testing;
    const io = testing.io;
    const alloc = testing.allocator;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // Transmit and display, then delete everything (including image
    // data), then retransmit the same ID.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=T,t=d,f=24,i=1,s=1,v=2,c=1,r=1;////////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }
    const gen1 = storage.imageById(1).?.generation;

    {
        const cmd = try command.Parser.parseString(alloc, "a=d,d=A");
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd);
        try testing.expect(resp == null);
    }
    try testing.expect(storage.imageById(1) == null);
    const gen_delete = storage.generation;
    try testing.expect(gen_delete > gen1);

    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,t=d,f=24,i=1,s=1,v=2;////////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }
    const gen2 = storage.imageById(1).?.generation;
    try testing.expect(gen2 > gen1);
    try testing.expect(gen2 > gen_delete);
}

test "kittygfx display clamps cell offsets" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    t.width_px = 50; // 10 px per col
    t.height_px = 100; // 20 px per row

    const cmd = try command.Parser.parseString(
        alloc,
        "a=T,t=d,f=24,i=1,s=1,v=1,c=2,r=1,X=99,Y=99,C=1;AAAA",
    );
    defer cmd.deinit(alloc);

    const resp = execute(io, alloc, &t, &cmd).?;
    try testing.expect(resp.ok());

    const storage = &t.screens.active.kitty_images;
    var it = storage.placements.iterator();
    const placement = it.next().?.value_ptr;
    try testing.expectEqual(@as(u32, 9), placement.x_offset);
    try testing.expectEqual(@as(u32, 19), placement.y_offset);

    const actual = placement.pixelSize(storage.imageById(1).?, &t);
    try testing.expectEqual(@as(u32, 11), actual.width);
    try testing.expectEqual(@as(u32, 1), actual.height);
}

test "kittygfx placement bounds cursor movement for untrusted dimensions" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    const cmd = try command.Parser.parseString(
        alloc,
        "a=T,t=d,f=24,i=1,s=1,v=1,c=4294967295,r=4294967295;////",
    );
    defer cmd.deinit(alloc);

    const resp = execute(io, alloc, &t, &cmd).?;
    try testing.expect(resp.ok());
    try testing.expectEqual(@as(usize, 1), t.screens.active.kitty_images.placements.count());
    // Reaching the bottom takes four rows, then scrolling is capped to one
    // screen (five rows), matching Kitty's bounded screen-scroll behavior.
    try testing.expectEqual(@as(usize, 10), t.screens.active.pages.scrollbar().total);
}

test "kittygfx placement moves cursor past a tall image" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    // Load a one-pixel RGB image, then place it over the full width and eight
    // rows. Eight rows are taller than the screen but still within Kitty's
    // scroll budget.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,t=d,f=24,i=1,s=1,v=1;////",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=p,i=1,p=1,c=5,r=8",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }

    // A subsequent placement begins immediately after the first one instead
    // of overlapping it at the old one-screen movement cap.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=p,i=1,p=2,C=1",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }

    const storage = &t.screens.active.kitty_images;
    const first = storage.placements.get(.{
        .image_id = 1,
        .placement_id = .{ .tag = .external, .id = 1 },
    }).?;
    const second = storage.placements.get(.{
        .image_id = 1,
        .placement_id = .{ .tag = .external, .id = 2 },
    }).?;
    const first_pin = switch (first.location) {
        .pin => |pin| pin,
        .virtual, .relative => unreachable,
    };
    const second_pin = switch (second.location) {
        .pin => |pin| pin,
        .virtual, .relative => unreachable,
    };
    const first_y = t.screens.active.pages.pointFromPin(
        .screen,
        first_pin.*,
    ).?.screen.y;
    const second_y = t.screens.active.pages.pointFromPin(
        .screen,
        second_pin.*,
    ).?.screen.y;
    try testing.expectEqual(first_y + 8, second_y);
}

test "kittygfx unknown format responds with EINVAL" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    const cmd = try command.Parser.parseString(
        alloc,
        "a=t,f=42,t=d,i=31,s=1,v=1;AAAA",
    );
    defer cmd.deinit(alloc);

    const resp = execute(io, alloc, &t, &cmd).?;
    try testing.expect(!resp.ok());
    try testing.expectEqual(@as(u32, 31), resp.id);
    try testing.expectEqualStrings("EINVAL: unsupported format", resp.message);
    try testing.expectEqual(
        @as(usize, 0),
        t.screens.active.kitty_images.images.count(),
    );
}

test "kittygfx unknown format on query responds with EINVAL" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    const cmd = try command.Parser.parseString(
        alloc,
        "a=q,f=42,t=d,i=31,s=1,v=1;AAAA",
    );
    defer cmd.deinit(alloc);

    const resp = execute(io, alloc, &t, &cmd).?;
    try testing.expect(!resp.ok());
    try testing.expectEqual(@as(u32, 31), resp.id);
    try testing.expectEqualStrings("EINVAL: unsupported format", resp.message);
}

test "kittygfx zero format is rgba" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    // Kitty treats f=0 as an absent f, i.e. RGBA.
    const cmd = try command.Parser.parseString(
        alloc,
        "a=t,f=0,t=d,i=1,s=1,v=2,c=10,r=1;///////////",
    );
    defer cmd.deinit(alloc);

    const resp = execute(io, alloc, &t, &cmd).?;
    try testing.expect(resp.ok());

    const img = t.screens.active.kitty_images.imageById(1).?;
    try testing.expectEqual(command.Transmission.Format.rgba, img.format);
}

test "kittygfx unknown format with q=3 has no response" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    // q above 2 is out of range in the spec but Kitty suppresses
    // everything for anything above 1, so we must still parse it.
    const cmd = try command.Parser.parseString(
        alloc,
        "a=t,f=42,t=d,i=31,q=3,s=1,v=1;AAAA",
    );
    defer cmd.deinit(alloc);

    try testing.expect(execute(io, alloc, &t, &cmd) == null);
}

test "kittygfx out of range display keys are tolerated" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=T,f=24,t=d,i=31,s=1,v=1,C=2,U=2;AAAA",
        );
        defer cmd.deinit(alloc);

        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
        try testing.expectEqual(@as(u32, 31), resp.id);
    }

    // U=2 must behave like U=1, so the placement is virtual.
    const storage = &t.screens.active.kitty_images;
    var it = storage.placements.iterator();
    const entry = it.next().?;
    try testing.expect(entry.value_ptr.location == .virtual);
}

test "kittygfx number-based transmission assigns smallest free id" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // Empty storage: the first free ID is 1, as in Kitty.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,I=42;/wAA",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
        try testing.expectEqual(@as(u32, 1), resp.id);
        try testing.expectEqual(@as(u32, 42), resp.image_number);
    }

    // Occupy ID 2 explicitly; the next number gets 3.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=2;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,I=43;/wAA",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
        try testing.expectEqual(@as(u32, 3), resp.id);
    }

    // Deleting ID 1 opens a gap that the next number fills.
    {
        const cmd = try command.Parser.parseString(alloc, "a=d,d=I,i=1");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,I=44;/wAA",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
        try testing.expectEqual(@as(u32, 1), resp.id);
    }

    try testing.expectEqual(@as(usize, 3), storage.images.count());
    try testing.expectEqual(@as(u32, 44), storage.imageById(1).?.number);
    try testing.expectEqual(@as(u32, 0), storage.imageById(2).?.number);
    try testing.expectEqual(@as(u32, 43), storage.imageById(3).?.number);
}

test "kittygfx number-based id assignment does not replace client image" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // A client stores and places a red pixel on the ID the old wrapping
    // counter would assign first.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=2147483647;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    {
        const cmd = try command.Parser.parseString(alloc, "a=p,i=2147483647,C=1");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // A number-based transmission must not collide with it.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,I=42;AAD/",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
        try testing.expectEqual(@as(u32, 1), resp.id);
    }

    // The client's image and placement are untouched.
    try testing.expectEqual(@as(usize, 2), storage.images.count());
    try testing.expectEqual(@as(usize, 1), storage.placements.count());
    try testing.expectEqualSlices(
        u8,
        &.{ 255, 0, 0 },
        storage.imageById(2147483647).?.data.bytes().?,
    );
}

test "kittygfx implicit id assignment does not replace client image" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // A client stores and places a red pixel on the ID the implicit
    // counter assigns first.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=2147483647;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    {
        const cmd = try command.Parser.parseString(alloc, "a=p,i=2147483647,C=1");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Transmit without an ID or number: no response, and the counter
    // skips over the in-use ID instead of replacing that image.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1;AAD/",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }

    try testing.expectEqual(@as(usize, 2), storage.images.count());
    try testing.expectEqual(@as(usize, 1), storage.placements.count());
    try testing.expectEqualSlices(
        u8,
        &.{ 255, 0, 0 },
        storage.imageById(2147483647).?.data.bytes().?,
    );
    const implicit = storage.imageById(2147483648).?;
    try testing.expect(implicit.metadata.implicit_id);
    try testing.expectEqualSlices(u8, &.{ 0, 0, 255 }, implicit.data.bytes().?);
}

test "kittygfx relative placement with missing parent image" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;AAAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // The parent image does not exist: the placement must be rejected
    // with ENOPARENT, nothing may be created, and the cursor must not
    // move (a relative placement never moves the cursor, and a failed
    // one certainly must not).
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=p,i=1,p=1,P=42,Q=1,H=2,V=2",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(!resp.ok());
        try testing.expectEqualStrings(
            "ENOPARENT: parent image not found",
            resp.message,
        );
    }

    try testing.expectEqual(@as(usize, 0), storage.placements.count());
    try testing.expectEqual(0, t.screens.active.cursor.x);
    try testing.expectEqual(0, t.screens.active.cursor.y);
}

test "kittygfx relative placement with missing parent placement" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    for ([_][]const u8{
        "a=t,f=24,s=1,v=1,i=1;AAAA",
        "a=t,f=24,s=1,v=1,i=2;AAAA",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // The parent image exists but has no placements at all.
    {
        const cmd = try command.Parser.parseString(alloc, "a=p,i=1,P=2");
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(!resp.ok());
        try testing.expectEqualStrings(
            "ENOPARENT: parent placement not found",
            resp.message,
        );
    }

    // The parent image has a placement, but not the requested one.
    {
        const cmd = try command.Parser.parseString(alloc, "a=p,i=2,p=1,C=1");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    {
        const cmd = try command.Parser.parseString(alloc, "a=p,i=1,P=2,Q=9");
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(!resp.ok());
        try testing.expectEqualStrings(
            "ENOPARENT: parent placement not found",
            resp.message,
        );
    }

    try testing.expectEqual(@as(usize, 1), storage.placements.count());
}

test "kittygfx relative placement cannot parent itself" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    for ([_][]const u8{
        "a=t,f=24,s=1,v=1,i=1;AAAA",
        "a=p,i=1,p=1,C=1",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Explicitly via Q, and implicitly when the Q=0 fallback selects
    // the placement being replaced.
    for ([_][]const u8{
        "a=p,i=1,p=1,P=1,Q=1",
        "a=p,i=1,p=1,P=1",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(!resp.ok());
        try testing.expectEqualStrings(
            "EINVAL: placement cannot be its own parent",
            resp.message,
        );
    }

    // The original placement must be untouched.
    const storage = &t.screens.active.kitty_images;
    const p = storage.placements.get(.{
        .image_id = 1,
        .placement_id = .{ .tag = .external, .id = 1 },
    }).?;
    try testing.expect(p.location == .pin);
}

test "kittygfx relative placement cycle" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    for ([_][]const u8{
        "a=t,f=24,s=1,v=1,i=1;AAAA",
        "a=p,i=1,p=1,C=1",
        "a=p,i=1,p=2,P=1,Q=1",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Replacing placement 1 with a parent of placement 2 would create
    // the cycle 1 -> 2 -> 1.
    {
        const cmd = try command.Parser.parseString(alloc, "a=p,i=1,p=1,P=1,Q=2");
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(!resp.ok());
        try testing.expectEqualStrings(
            "ECYCLE: parent chain creates a cycle",
            resp.message,
        );
    }

    // The original placement must be untouched, keeping the stored
    // chains acyclic.
    const storage = &t.screens.active.kitty_images;
    const p = storage.placements.get(.{
        .image_id = 1,
        .placement_id = .{ .tag = .external, .id = 1 },
    }).?;
    try testing.expect(p.location == .pin);
}

test "kittygfx relative placement chain depth limit" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    for ([_][]const u8{
        "a=t,f=24,s=1,v=1,i=1;AAAA",
        "a=p,i=1,p=1,C=1",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Chains of up to parent_chain_limit (8) links must work: these
    // placements form the chain 9 -> 8 -> ... -> 2 -> 1.
    for (2..10) |id| {
        var buf: [64]u8 = undefined;
        const cmd = try command.Parser.parseString(
            alloc,
            try std.fmt.bufPrint(&buf, "a=p,i=1,p={},P=1,Q={}", .{ id, id - 1 }),
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // One more link exceeds the limit.
    {
        const cmd = try command.Parser.parseString(alloc, "a=p,i=1,p=10,P=1,Q=9");
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(!resp.ok());
        try testing.expectEqualStrings(
            "ETOODEEP: parent chain too deep",
            resp.message,
        );
    }

    const storage = &t.screens.active.kitty_images;
    try testing.expectEqual(@as(usize, 9), storage.placements.count());
}

test "kittygfx relative placement does not move cursor" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // C is left at its default (move after) on the relative placement
    // but it must never move the cursor.
    for ([_][]const u8{
        "a=t,f=24,s=1,v=1,i=1;AAAA",
        "a=p,i=1,p=1,C=1",
        "a=p,i=1,p=2,P=1,Q=1,H=3,V=2,c=2,r=2",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    try testing.expectEqual(0, t.screens.active.cursor.x);
    try testing.expectEqual(0, t.screens.active.cursor.y);

    // The stored placement carries the parent link and offsets.
    const p = storage.placements.get(.{
        .image_id = 1,
        .placement_id = .{ .tag = .external, .id = 2 },
    }).?;
    const rel = p.location.relative;
    try testing.expect(rel.parent.eql(.{
        .image_id = 1,
        .placement_id = .{ .tag = .external, .id = 1 },
    }));
    try testing.expectEqual(@as(i32, 3), rel.horizontal_offset);
    try testing.expectEqual(@as(i32, 2), rel.vertical_offset);
}

test "kittygfx virtual placement with parent rejected before image lookup" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    // Kitty rejects U=1 + P= before checking that the image exists,
    // so this must not be ENOENT.
    const cmd = try command.Parser.parseString(alloc, "a=p,i=42,U=1,P=1");
    defer cmd.deinit(alloc);
    const resp = execute(io, alloc, &t, &cmd).?;
    try testing.expect(!resp.ok());
    try testing.expectEqualStrings(
        "EINVAL: virtual placement cannot refer to a parent",
        resp.message,
    );
}

test "kittygfx deleting a parent deletes relative placements transitively" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // Root (pin) <- child <- grandchild
    for ([_][]const u8{
        "a=t,f=24,s=1,v=1,i=1;AAAA",
        "a=p,i=1,p=1,C=1",
        "a=p,i=1,p=2,P=1,Q=1",
        "a=p,i=1,p=3,P=1,Q=2",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    try testing.expectEqual(@as(usize, 3), storage.placements.count());

    // Deleting the middle placement takes the grandchild with it but
    // leaves the root.
    {
        const cmd = try command.Parser.parseString(alloc, "a=d,d=i,i=1,p=2");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    try testing.expectEqual(@as(usize, 1), storage.placements.count());
    try testing.expect(storage.placements.contains(.{
        .image_id = 1,
        .placement_id = .{ .tag = .external, .id = 1 },
    }));

    // Deleting the root removes the remaining placement, and the
    // image itself is retained (lowercase delete).
    {
        const cmd = try command.Parser.parseString(alloc, "a=d,d=i,i=1,p=1");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    try testing.expectEqual(@as(usize, 0), storage.placements.count());
    try testing.expect(storage.imageById(1) != null);
}

test "kittygfx retransmitting parent image deletes relative placements" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // Image 2's placement is relative to image 1's placement.
    for ([_][]const u8{
        "a=t,f=24,s=1,v=1,i=1;AAAA",
        "a=t,f=24,s=1,v=1,i=2;AAAA",
        "a=p,i=1,p=1,C=1",
        "a=p,i=2,p=1,P=1,Q=1",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    try testing.expectEqual(@as(usize, 2), storage.placements.count());

    // Retransmitting image 1 removes its placements, which orphans
    // and removes image 2's placement too. Image 2 is left without
    // any placement so it is freed as well: retransmission deletes
    // with uppercase semantics, and kitty also removes an image whose
    // last placement died from a broken parent chain.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;AAAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    try testing.expectEqual(@as(usize, 0), storage.placements.count());
    try testing.expect(storage.imageById(2) == null);
}

test "kittygfx relative placement parent fallback picks lowest external id" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    for ([_][]const u8{
        "a=t,f=24,s=1,v=1,i=1;AAAA",
        "a=t,f=24,s=1,v=1,i=2;AAAA",
        "a=p,i=1,p=7,C=1",
        "a=p,i=1,p=3,C=1",
        "a=p,i=2,P=1",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    var it = storage.placements.iterator();
    const rel = while (it.next()) |entry| {
        if (entry.key_ptr.image_id == 2) break entry.value_ptr.location.relative;
    } else return error.PlacementNotFound;
    try testing.expect(rel.parent.eql(.{
        .image_id = 1,
        .placement_id = .{ .tag = .external, .id = 3 },
    }));
}

test "kittygfx placements created after a full reset are retained" {
    // Regression test: Screen.reset reuses the cursor's tracked pin
    // but PageList.reset marked it garbage. Placements copy the cursor
    // pin, so every placement created after a reset was born garbage
    // and silently swept by the next placement command.
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 24, .cols = 80 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    t.fullReset();

    for ([_][]const u8{
        "a=t,f=24,s=1,v=1,i=1;AAAA",
        "a=p,i=1,p=1,C=1",
        "a=p,i=1,p=2,C=1",
        "a=p,i=1,p=3,P=1,Q=2",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    try testing.expectEqual(@as(usize, 3), storage.placements.count());
}

test "kittygfx relative placement with pruned parent is ENOPARENT" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    for ([_][]const u8{
        "a=t,f=24,s=1,v=1,i=1;AAAA",
        "a=p,i=1,p=1,C=1",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // The parent's tracked content is pruned from history but the
    // placement hasn't been swept yet. The put must reap it and answer
    // ENOPARENT rather than storing an orphan against it.
    const parent = storage.placements.getPtr(.{
        .image_id = 1,
        .placement_id = .{ .tag = .external, .id = 1 },
    }).?;
    parent.location.pin.garbage = true;

    {
        const cmd = try command.Parser.parseString(alloc, "a=p,i=1,p=2,P=1,Q=1");
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(!resp.ok());
        try testing.expectEqualStrings(
            "ENOPARENT: parent placement not found",
            resp.message,
        );
    }
    try testing.expectEqual(@as(usize, 0), storage.placements.count());
}

test "kittygfx uppercase delete frees image of cascaded placements" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    for ([_][]const u8{
        "a=t,f=24,s=1,v=1,i=1;AAAA",
        "a=p,i=1,p=1,C=1",
        "a=p,i=1,p=2,P=1,Q=1",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // The uppercase delete only matches placement 1. The cascade
    // removes placement 2, leaving the image without placements, so
    // the image must be freed too.
    {
        const cmd = try command.Parser.parseString(alloc, "a=d,d=I,i=1,p=1");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    try testing.expectEqual(@as(usize, 0), storage.placements.count());
    try testing.expect(storage.imageById(1) == null);
}

// Animation tests frequently start from a 1x1 RGB red image with
// id=1 ("/wAA" is FF0000). Composition converts images to RGBA, so
// after the first frame command the base data is FF0000FF.

test "kittygfx animation: new frame with default gap responds with frame number" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Transmit a 1x1 RGB blue frame ("AAD/" is 0000FF).
    const cmd = try command.Parser.parseString(
        alloc,
        "a=f,i=1,f=24,s=1,v=1;AAD/",
    );
    defer cmd.deinit(alloc);
    const resp = execute(io, alloc, &t, &cmd).?;
    try testing.expect(resp.ok());
    try testing.expectEqual(@as(u32, 1), resp.id);
    try testing.expectEqual(@as(u32, 2), resp.frame);

    var buf: [128]u8 = undefined;
    var writer: std.Io.Writer = .fixed(&buf);
    try resp.encode(&writer);
    try testing.expectEqualStrings("\x1b_Gi=1,r=2;OK\x1b\\", writer.buffered());

    const img = storage.imagePtrByIdOrNumber(1, 0).?;
    try testing.expectEqual(command.Transmission.Format.rgba, img.format);
    try testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, img.data.bytes().?);

    const anim = img.animation.?;
    try testing.expectEqual(@as(u32, 2), anim.frameCount());
    try testing.expectEqual(@as(u32, 0), anim.root_gap_ms);
    try testing.expectEqual(@as(u32, 40), anim.frames.items[0].gap_ms);
    try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, anim.frames.items[0].data);

    // The displayed frame is still the root: renderData is the base.
    try testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, img.renderData().bytes().?);

    // Frame bytes count against the storage total.
    try testing.expectEqual(@as(usize, 8), storage.total_bytes);
}

test "kittygfx animation: frame gap normalization on create" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    for ([_][]const u8{
        "a=f,i=1,f=24,s=1,v=1,z=100;AAD/",
        "a=f,i=1,f=24,s=1,v=1,z=-5;AAD/",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?;
    try testing.expectEqual(@as(u32, 100), anim.frames.items[0].gap_ms);
    try testing.expectEqual(@as(u32, 0), anim.frames.items[1].gap_ms);
}

test "kittygfx animation: background fill and offset composition" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // 2x1 RGB white image ("////////" is FFFFFF FFFFFF).
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=2,v=1,i=1;////////",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // New frame: 1x1 RGB white transmitted at x=1 over an opaque red
    // background (Y=4278190335 is 0xff0000ff, R in the MSB).
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=f,i=1,f=24,s=1,v=1,x=1,Y=4278190335;////",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?;
    try testing.expectEqualSlices(
        u8,
        &.{ 255, 0, 0, 255, 255, 255, 255, 255 },
        anim.frames.items[0].data,
    );
}

test "kittygfx animation: create from base frame with overwrite" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Frame 2 based on the root (c=1) with a semi-transparent blue
    // pixel ("AAD/gA==" is 0000FF80) in overwrite mode: the source
    // replaces the canvas including alpha.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=f,i=1,f=32,s=1,v=1,c=1,X=1;AAD/gA==",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
    }

    const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?;
    try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 128 }, anim.frames.items[0].data);
}

test "kittygfx animation: alpha blend composes over base frame" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Blend a fully opaque blue pixel over the root: alpha blending
    // an opaque source is equivalent to a copy.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=f,i=1,f=32,s=1,v=1,c=1;AAD//w==",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Blend a fully transparent pixel over the root: the canvas is
    // unchanged (still the red base).
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=f,i=1,f=32,s=1,v=1,c=1;AAD/AA==",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?;
    try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, anim.frames.items[0].data);
    try testing.expectEqualSlices(u8, &.{ 255, 0, 0, 255 }, anim.frames.items[1].data);
}

test "kittygfx animation: edit root frame bumps generation" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    const gen1 = storage.imagePtrByIdOrNumber(1, 0).?.generation;

    // r=1 edits the root frame in place. The root is the displayed
    // frame so the image generation must change.
    const cmd = try command.Parser.parseString(
        alloc,
        "a=f,i=1,f=24,s=1,v=1,r=1;AAD/",
    );
    defer cmd.deinit(alloc);
    const resp = execute(io, alloc, &t, &cmd).?;
    try testing.expect(resp.ok());
    try testing.expectEqual(@as(u32, 1), resp.frame);

    const img = storage.imagePtrByIdOrNumber(1, 0).?;
    try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, img.data.bytes().?);
    try testing.expect(img.generation > gen1);
}

test "kittygfx animation: edit frame gap without data change" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Create frame 2, then edit it with z=-1: gap becomes gapless.
    // Editing with z=0 leaves the gap unchanged (no 40ms default).
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=f,i=1,f=24,s=1,v=1,z=77;AAD/",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=f,i=1,f=24,s=1,v=1,r=2;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?;
    try testing.expectEqual(@as(u32, 77), anim.frames.items[0].gap_ms);

    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=f,i=1,f=24,s=1,v=1,r=2,z=-1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    try testing.expectEqual(@as(u32, 0), anim.frames.items[0].gap_ms);
}

test "kittygfx animation: frame errors" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    const cases = [_]struct {
        input: []const u8,
        message: []const u8,
    }{
        // Unknown image.
        .{
            .input = "a=f,i=9,f=24,s=1,v=1;AAD/",
            .message = "ENOENT: image not found",
        },
        // Frame bigger than the image.
        .{
            .input = "a=f,i=1,f=24,s=2,v=1;////////",
            .message = "EINVAL: frame dimensions exceed image",
        },
        // Nonexistent base frame.
        .{
            .input = "a=f,i=1,f=24,s=1,v=1,c=5;AAD/",
            .message = "EINVAL: base frame not found",
        },
        // Insufficient data for the declared rectangle.
        .{
            .input = "a=f,i=1,f=24,s=1,v=1;AA==",
            .message = "ENODATA: insufficient data",
        },
    };
    for (cases) |case| {
        const cmd = try command.Parser.parseString(alloc, case.input);
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(!resp.ok());
        try testing.expectEqualStrings(case.message, resp.message);
    }

    // None of the failures may have created a frame.
    const storage = &t.screens.active.kitty_images;
    const img = storage.imagePtrByIdOrNumber(1, 0).?;
    if (img.animation) |anim| {
        try testing.expectEqual(@as(usize, 0), anim.frames.items.len);
    }
}

test "kittygfx animation: excess frame data is truncated" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Six bytes for a 1x1 RGB frame: Kitty tolerates the excess.
    const cmd = try command.Parser.parseString(
        alloc,
        "a=f,i=1,f=24,s=1,v=1;AAD/////",
    );
    defer cmd.deinit(alloc);
    try testing.expect(execute(io, alloc, &t, &cmd).?.ok());

    const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?;
    try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, anim.frames.items[0].data);
}

test "kittygfx animation: chunked frame transmission" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // 2x1 RGB white image.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=2,v=1,i=1;////////",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Transmit a 2x1 frame in two chunks of one pixel each. The
    // chunks repeat a=f per the protocol. No response until the
    // final chunk.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=f,i=1,f=24,s=2,v=1,z=60,m=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    try testing.expect(storage.loading != null);
    {
        const cmd = try command.Parser.parseString(alloc, "a=f,m=0;AAD/");
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
        try testing.expectEqual(@as(u32, 1), resp.id);
        try testing.expectEqual(@as(u32, 2), resp.frame);
    }
    try testing.expect(storage.loading == null);

    const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?;
    try testing.expectEqual(@as(u32, 60), anim.frames.items[0].gap_ms);
    try testing.expectEqualSlices(
        u8,
        &.{ 255, 0, 0, 255, 0, 0, 255, 255 },
        anim.frames.items[0].data,
    );
}

test "kittygfx animation: chunked frame continuation without a=f" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=2,v=1,i=1;////////",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // The spec requires chunks to repeat a=f, but a bare continuation
    // (which parses as a transmit action) must still continue the
    // frame load rather than turn into an image transmission.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=f,i=1,f=24,s=2,v=1,m=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    {
        const cmd = try command.Parser.parseString(alloc, "m=0;AAD/");
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
        try testing.expectEqual(@as(u32, 2), resp.frame);
    }

    const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?;
    try testing.expectEqual(@as(usize, 1), anim.frames.items.len);
}

test "kittygfx animation: control command sets gap current state and loops" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=f,i=1,f=24,s=1,v=1;AAD/",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    const img = storage.imagePtrByIdOrNumber(1, 0).?;
    const gen1 = img.generation;

    // One command can set several things: the root frame's gap
    // (r=1,z=50), the current frame (c=2), the state (s=3, running),
    // and the loop count (v=3, meaning two loops). Successful a=a
    // commands never respond.
    const cmd = try command.Parser.parseString(
        alloc,
        "a=a,i=1,r=1,z=50,c=2,s=3,v=3",
    );
    defer cmd.deinit(alloc);
    try testing.expect(execute(io, alloc, &t, &cmd) == null);

    const anim = img.animation.?;
    try testing.expectEqual(@as(u32, 50), anim.root_gap_ms);
    try testing.expectEqual(@as(u32, 1), anim.current_index);
    try testing.expectEqual(animation.Animation.State.running, anim.state);
    try testing.expectEqual(@as(u32, 2), anim.max_loops);

    // Changing the current frame changes the displayed content.
    try testing.expect(img.generation > gen1);
    try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, img.renderData().bytes().?);
}

test "kittygfx animation: control command ignores invalid values" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Out-of-range frame numbers and s values are silently ignored.
    const cmd = try command.Parser.parseString(
        alloc,
        "a=a,i=1,r=9,z=50,c=9,s=7",
    );
    defer cmd.deinit(alloc);
    try testing.expect(execute(io, alloc, &t, &cmd) == null);

    const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?;
    try testing.expectEqual(@as(u32, 0), anim.root_gap_ms);
    try testing.expectEqual(@as(u32, 0), anim.current_index);
    try testing.expectEqual(animation.Animation.State.stopped, anim.state);
}

test "kittygfx animation: control command missing image responds ENOENT" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);

    const cmd = try command.Parser.parseString(alloc, "a=a,i=9,s=3");
    defer cmd.deinit(alloc);
    const resp = execute(io, alloc, &t, &cmd).?;
    try testing.expect(!resp.ok());
    try testing.expectEqualStrings("ENOENT: image not found", resp.message);
}

test "kittygfx animation: compose frames" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // 2x1 RGB image: red then blue ("/wAAAAD/" is FF0000 0000FF).
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=2,v=1,i=1;/wAAAAD/",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    // Frame 2 starts as a transparent canvas with a white pixel at
    // x=0 ("////" is FFFFFF).
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=f,i=1,f=24,s=1,v=1;////",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Compose the root's pixel at (1,0) onto frame 2 at (0,0):
    // r=1 is the source frame, c=2 the destination, X/Y the source
    // offsets, x/y the destination offsets.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=c,i=1,r=1,c=2,w=1,h=1,X=1,x=0",
        );
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(resp.ok());
        try testing.expectEqual(@as(u32, 0), resp.frame);
    }

    const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?;
    try testing.expectEqualSlices(
        u8,
        &.{ 0, 0, 255, 255, 0, 0, 0, 0 },
        anim.frames.items[0].data,
    );
}

test "kittygfx animation: compose current frame bumps generation" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // 2x1 RGB white image; the root frame is the displayed frame.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=2,v=1,i=1;////////",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    const img = storage.imagePtrByIdOrNumber(1, 0).?;
    const gen1 = img.generation;

    // a=c works on images without animation state: both frames are
    // the root. Copy pixel 0 onto pixel 1.
    const cmd = try command.Parser.parseString(
        alloc,
        "a=c,i=1,r=1,c=1,w=1,h=1,x=1",
    );
    defer cmd.deinit(alloc);
    try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    try testing.expect(img.generation > gen1);
}

test "kittygfx animation: compose errors" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    const cases = [_]struct {
        input: []const u8,
        message: []const u8,
    }{
        .{
            .input = "a=c,i=9,r=1,c=1",
            .message = "ENOENT: image not found",
        },
        .{
            .input = "a=c,i=1,r=2,c=1",
            .message = "ENOENT: source frame not found",
        },
        .{
            .input = "a=c,i=1,r=1,c=2",
            .message = "ENOENT: destination frame not found",
        },
        // 1x1 image: any offset pushes the rect out of bounds.
        .{
            .input = "a=c,i=1,r=1,c=1,x=1",
            .message = "EINVAL: destination rectangle out of bounds",
        },
        .{
            .input = "a=c,i=1,r=1,c=1,X=1",
            .message = "EINVAL: source rectangle out of bounds",
        },
        // Same frame, same (whole-image) rect: overlap.
        .{
            .input = "a=c,i=1,r=1,c=1",
            .message = "EINVAL: source and destination rectangles overlap",
        },
    };
    for (cases) |case| {
        const cmd = try command.Parser.parseString(alloc, case.input);
        defer cmd.deinit(alloc);
        const resp = execute(io, alloc, &t, &cmd).?;
        try testing.expect(!resp.ok());
        try testing.expectEqualStrings(case.message, resp.message);
    }
}

test "kittygfx animation: delete frame promotes root and fixes current" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    // Frames 2 and 3: blue and white.
    for ([_][]const u8{
        "a=f,i=1,f=24,s=1,v=1,z=10;AAD/",
        "a=f,i=1,f=24,s=1,v=1,z=20;////",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    const total_before = storage.total_bytes;

    // Delete the root frame (r omitted selects it): frame 2 becomes
    // the new root, including its gap. Deletes never respond.
    {
        const cmd = try command.Parser.parseString(alloc, "a=d,d=f,i=1");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    const img = storage.imagePtrByIdOrNumber(1, 0).?;
    const anim = img.animation.?;
    try testing.expectEqual(@as(u32, 2), anim.frameCount());
    try testing.expectEqual(@as(u32, 10), anim.root_gap_ms);
    try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, img.data.bytes().?);
    try testing.expectEqual(total_before - 4, storage.total_bytes);

    // Delete a frame number past the end: clamps to the last frame.
    {
        const cmd = try command.Parser.parseString(alloc, "a=d,d=f,i=1,r=9");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    try testing.expectEqual(@as(u32, 1), anim.frameCount());
    try testing.expectEqual(total_before - 8, storage.total_bytes);

    // Down to one frame: d=f is now a no-op and the image survives.
    {
        const cmd = try command.Parser.parseString(alloc, "a=d,d=f,i=1");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    try testing.expect(storage.imageById(1) != null);
}

test "kittygfx animation: uppercase frame delete removes non-animated image" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;

    // Transmit and place: unlike d=I, an uppercase frame delete on a
    // non-animated image removes it even though it is placed.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=T,f=24,s=1,v=1,i=1,C=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    try testing.expectEqual(@as(usize, 1), storage.placements.count());

    {
        const cmd = try command.Parser.parseString(alloc, "a=d,d=F,i=1");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    try testing.expect(storage.imageById(1) == null);
    try testing.expectEqual(@as(usize, 0), storage.placements.count());
    try testing.expectEqual(@as(usize, 0), storage.total_bytes);
}

test "kittygfx animation: deleting current frame refreshes display" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    for ([_][]const u8{
        "a=f,i=1,f=24,s=1,v=1;AAD/",
        "a=f,i=1,f=24,s=1,v=1;////",
        "a=a,i=1,c=3",
    }) |input| {
        const cmd = try command.Parser.parseString(alloc, input);
        defer cmd.deinit(alloc);
        _ = execute(io, alloc, &t, &cmd);
    }

    const img = storage.imagePtrByIdOrNumber(1, 0).?;
    const anim = img.animation.?;
    try testing.expectEqual(@as(u32, 2), anim.current_index);
    const gen1 = img.generation;

    // Deleting the last frame (the current one) clamps the index and
    // refreshes the display.
    {
        const cmd = try command.Parser.parseString(alloc, "a=d,d=f,i=1,r=3");
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd) == null);
    }
    try testing.expectEqual(@as(u32, 1), anim.current_index);
    try testing.expect(img.generation > gen1);
    try testing.expectEqualSlices(u8, &.{ 0, 0, 255, 255 }, img.renderData().bytes().?);
}

test "kittygfx animation: retransmitting base image resets animation" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=f,i=1,f=24,s=1,v=1;AAD/",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    try testing.expectEqual(@as(usize, 8), storage.total_bytes);

    // Retransmit the base image: the animation is dropped and the
    // frame bytes are credited back.
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    const img = storage.imagePtrByIdOrNumber(1, 0).?;
    try testing.expect(img.animation == null);
    try testing.expectEqual(@as(usize, 3), storage.total_bytes);
}

test "kittygfx animation: control negative gap makes frame gapless" {
    const testing = std.testing;
    const alloc = testing.allocator;
    const io = testing.io;

    var t = try Terminal.init(io, alloc, .{ .rows = 5, .cols = 5 });
    defer t.deinit(alloc);
    const storage = &t.screens.active.kitty_images;
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=t,f=24,s=1,v=1,i=1;/wAA",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }
    {
        const cmd = try command.Parser.parseString(
            alloc,
            "a=f,i=1,f=24,s=1,v=1;AAD/",
        );
        defer cmd.deinit(alloc);
        try testing.expect(execute(io, alloc, &t, &cmd).?.ok());
    }

    const cmd = try command.Parser.parseString(alloc, "a=a,i=1,r=2,z=-1");
    defer cmd.deinit(alloc);
    try testing.expect(execute(io, alloc, &t, &cmd) == null);

    const anim = storage.imagePtrByIdOrNumber(1, 0).?.animation.?;
    try testing.expectEqual(@as(u32, 0), anim.frames.items[0].gap_ms);
}