summaryrefslogtreecommitdiff
path: root/test/kitty.zig
blob: f222f9cfb064e2e5f1e3ed81e78fcbe263b0876e (plain) (blame)
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
//! Kitty graphics protocol conformance for terminal panes, at the core.
//!
//!   zig build kitty-test -Dplatform=tui|gui   these cases alone
//!   zig build unit-test                       they run with the rest
//!
//! ghostty-vt implements the protocol; what pardes owns is the proxy around
//! it: a program's APC reaches the emulator whole however the pty splits it,
//! the emulator's replies go back to that program's pty (and nowhere else),
//! and what the emulator stores is drawn where the program put it. Each case
//! feeds a pane's output the way a pty read does and checks all three: the
//! bytes the program would read back, ghostty's image storage, and the
//! placements a frame hands the shell (which a tty re-emits to the outer
//! terminal and the GUI draws; test/kitty_harness.zig follows them there).
//!
//! A case pardes does not pass yet is a `knownGap`: its check runs, the test
//! is skipped with the reason while it fails, and fails once it passes, so
//! the marker goes when the gap closes.
const std = @import("std");
const pardes = @import("pardes");
const Pardes = pardes.Pardes;
const config = pardes.config;
const terminal = pardes.panes.terminal;

const gpa = std.testing.allocator;

// 4x2 pixels, the left half red and the right half blue, in every encoding
// the protocol has (generated with Python's zlib and a hand-built PNG).
const rgb_b64 = "/wAA/wAAAAD/AAD//wAA/wAAAAD/AAD/";
const rgba_b64 = "/wAA//8AAP8AAP//AAD///8AAP//AAD/AAD//wAA//8=";
const rgb_zlib_b64 = "eJz7z8Dwn4EBTPz/j8QGAGO0B/k=";
const png_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAQAAAACCAIAAADwyuo0AAAAE0lEQVR4nGP4z8AARGDiPwMyBwBnsgf5Q2OaZwAAAABJRU5ErkJggg==";
const rgb_raw = [_]u8{ 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255, 255, 0, 0, 255, 0, 0, 0, 0, 255, 0, 0, 255 };
// 256x256 transparent RGBA, zlib: 256 KiB stored per copy for 373 bytes sent.
const blank_256_zlib_b64 = "eNrtwTEBAAAAwqD1T+1tB6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN4AADwAAQ==";

const red = [4]u8{ 255, 0, 0, 255 };
const blue = [4]u8{ 0, 0, 255, 255 };

/// `ESC _ G <control> ; <payload> ESC \`
inline fn apc(comptime control: []const u8, comptime payload: []const u8) []const u8 {
    return comptime "\x1b_G" ++ control ++ ";" ++ payload ++ "\x1b\\";
}

/// What the protocol answers: `ESC _ G <keys> ; <message> ESC \`
inline fn reply(comptime keys: []const u8, comptime message: []const u8) []const u8 {
    return comptime "\x1b_G" ++ keys ++ ";" ++ message ++ "\x1b\\";
}

fn knownGap(comptime reason: []const u8, passes: bool) !void {
    if (passes) {
        std.debug.print("kitty: a known gap passes now, drop its marker: {s}\n", .{reason});
        return error.KnownGapNowPasses;
    }
    std.debug.print("kitty: known gap: {s}\n", .{reason});
    return error.SkipZigTest;
}

/// A session of `shells` (1, or up to 3) terminal panes with 10x20 pixel cells, under a
/// shell that draws pixels, every pane's keyboard at its pty.
const Rig = struct {
    p: *Pardes,
    frame: std.heap.ArenaAllocator,
    /// What each pane's program has read back since `take`.
    read: [pardes.MAX_PANES]std.ArrayList(u8) = @splat(.empty),

    fn init(shells: u8) !Rig {
        // f=100 decodes through pardes's own decoder (stb_image), which the
        // shells start at launch.
        pardes.image.start(std.testing.io, gpa);
        // ghostty warns of every refused command; the refusals are the point.
        std.testing.log_level = .err;
        // A core boots one shell or the classic three.
        const p = try Pardes.init(gpa, .{ .cols = 120, .rows = 40, .shells = if (shells > 1) 3 else 1 });
        p.frontend.native_images = true;
        p.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 10, .h = 20 } } });
        for (p.panes) |slot| if (slot) |each| {
            each.body.mode = .tty;
        };
        var r: Rig = .{ .p = p, .frame = .init(gpa) };
        r.drain();
        for (&r.read) |*b| b.clearRetainingCapacity();
        return r;
    }

    fn deinit(r: *Rig) void {
        for (&r.read) |*b| b.deinit(gpa);
        r.frame.deinit();
        r.p.deinit();
        pardes.image.stop();
    }

    fn drain(r: *Rig) void {
        while (r.p.nextEffect()) |effect| {
            if (effect == .write) r.read[effect.write.pane].appendSlice(gpa, effect.write.bytes.slice()) catch @panic("OOM");
        }
    }

    /// One pty read of pane `id`'s output.
    fn feed(r: *Rig, id: u8, bytes: []const u8) void {
        r.p.update(.{ .output = .{ .pane = id, .bytes = bytes } });
        r.drain();
    }

    /// The same output, as reads of `step` bytes.
    fn feedSplit(r: *Rig, id: u8, bytes: []const u8, step: usize) void {
        var at: usize = 0;
        while (at < bytes.len) : (at += step) r.feed(id, bytes[at..@min(bytes.len, at + step)]);
    }

    /// What pane `id`'s program read back, since the last take.
    fn take(r: *Rig, id: u8) ![]u8 {
        defer r.read[id].clearRetainingCapacity();
        return r.frame.allocator().dupe(u8, r.read[id].items);
    }

    fn pane(r: *Rig, id: u8) *pardes.Pane {
        return r.p.panes[id].?;
    }

    fn vt(r: *Rig, id: u8) @TypeOf(&r.pane(id).terminal.?.vt) {
        return &r.pane(id).terminal.?.vt;
    }

    fn storage(r: *Rig, id: u8) @TypeOf(&r.vt(id).screens.active.kitty_images) {
        return &r.vt(id).screens.active.kitty_images;
    }

    fn places(r: *Rig) ![]const pardes.Placement {
        _ = r.frame.reset(.retain_capacity);
        const s = try r.p.render(r.frame.allocator());
        return s.placements.items;
    }

    /// The id its program gave the image a place draws.
    fn idOf(r: *Rig, place: pardes.Placement) ?u32 {
        const shown = r.p.panes[place.pane] orelse return null;
        var it = shown.terminal.?.vt.screens.active.kitty_images.images.iterator();
        while (it.next()) |e| if (pardes.Placement.keyOf(shown.serial, e.key_ptr.*, @truncate(e.value_ptr.generation)) == place.key) return e.key_ptr.*;
        return null;
    }

    /// The top-left cell of pane `id`'s body, in screen cells.
    fn origin(r: *Rig, id: u8) struct { x: u16, y: u16 } {
        const rect = r.p.rects[id];
        return .{ .x = rect.x + config.GUTTER, .y = r.p.bodyTop(r.pane(id), rect) };
    }

    /// The places drawn for the image a program called `image_id`.
    fn placesOf(r: *Rig, image_id: u32) ![]const pardes.Placement {
        var out: std.ArrayList(pardes.Placement) = .empty;
        for (try r.places()) |place| if (r.idOf(place) == image_id)
            try out.append(r.frame.allocator(), place);
        return out.items;
    }

    fn placementCount(r: *Rig, id: u8) usize {
        return r.storage(id).placements.count();
    }

    fn hasImage(r: *Rig, id: u8, image_id: u32) bool {
        return r.storage(id).imageById(image_id) != null;
    }
};

/// The pixel at `(x, y)` of a drawn place's whole image, as RGBA.
fn pixel(place: pardes.Placement, x: usize, y: usize) [4]u8 {
    return place.raster.bytes()[y * place.raster.stride + x * 4 ..][0..4].*;
}

test "kitty: a support query is answered on the asking pane's pty and stores nothing" {
    var r = try Rig.init(2);
    defer r.deinit();
    r.feed(1, apc("i=31,s=1,v=1,a=q,t=d,f=24", "AAAA"));
    try std.testing.expectEqualStrings(reply("i=31", "OK"), try r.take(1));
    try std.testing.expectEqualStrings("", try r.take(0));
    try std.testing.expect(!r.hasImage(1, 31));
    try std.testing.expectEqual(@as(usize, 0), (try r.places()).len);
}

test "kitty: a query that cannot load says why, with its keys" {
    var r = try Rig.init(1);
    defer r.deinit();
    // Too little data for a 2x2 RGB image.
    r.feed(0, apc("i=32,s=2,v=2,a=q,t=d,f=24", "AAAA"));
    const got = try r.take(0);
    try std.testing.expect(std.mem.startsWith(u8, got, "\x1b_Gi=32;E"));
    try std.testing.expect(std.mem.endsWith(u8, got, "\x1b\\"));
    try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, got, "\x1b_G"));
}

test "kitty: quiet levels: q=1 drops the OK, q=2 the errors too" {
    const Case = struct { control: []const u8, payload: []const u8, answered: bool };
    const cases = [_]Case{
        .{ .control = "i=33,s=1,v=1,a=q,f=24,q=0", .payload = "AAAA", .answered = true },
        .{ .control = "i=33,s=1,v=1,a=q,f=24,q=1", .payload = "AAAA", .answered = false },
        .{ .control = "i=33,s=2,v=2,a=q,f=24,q=1", .payload = "AAAA", .answered = true },
        .{ .control = "i=33,s=2,v=2,a=q,f=24,q=2", .payload = "AAAA", .answered = false },
        .{ .control = "i=33,s=4,v=2,a=t,f=24,q=1", .payload = rgb_b64, .answered = false },
        .{ .control = "i=33,a=p,q=2", .payload = "", .answered = false },
    };
    for (cases) |c| {
        var r = try Rig.init(1);
        defer r.deinit();
        const bytes = try std.fmt.allocPrint(r.frame.allocator(), "\x1b_G{s};{s}\x1b\\", .{ c.control, c.payload });
        r.feed(0, bytes);
        const got = try r.take(0);
        std.testing.expectEqual(c.answered, got.len > 0) catch |err| {
            std.debug.print("q case {s}: read back {f}\n", .{ c.control, std.ascii.hexEscape(got, .lower) });
            return err;
        };
    }
}

test "kitty: RGB, RGBA, PNG and zlib-compressed RGB all draw the same pixels" {
    const Case = struct { control: []const u8, payload: []const u8 };
    const cases = [_]Case{
        .{ .control = "a=T,i=1,f=24,s=4,v=2,c=2,r=1", .payload = rgb_b64 },
        .{ .control = "a=T,i=1,f=32,s=4,v=2,c=2,r=1", .payload = rgba_b64 },
        .{ .control = "a=T,i=1,f=100,c=2,r=1", .payload = png_b64 },
        .{ .control = "a=T,i=1,f=24,o=z,s=4,v=2,c=2,r=1", .payload = rgb_zlib_b64 },
    };
    for (cases) |c| {
        var r = try Rig.init(1);
        defer r.deinit();
        r.feed(0, try std.fmt.allocPrint(r.frame.allocator(), "\x1b_G{s};{s}\x1b\\", .{ c.control, c.payload }));
        try std.testing.expectEqualStrings(reply("i=1", "OK"), try r.take(0));
        const img = r.storage(0).imageById(1) orelse return error.NotStored;
        try std.testing.expectEqual(@as(u32, 4), img.width);
        try std.testing.expectEqual(@as(u32, 2), img.height);
        const drawn = try r.placesOf(1);
        try std.testing.expectEqual(@as(usize, 1), drawn.len);
        try std.testing.expectEqual(@as(usize, 4), drawn[0].raster.w);
        for ([_][2]usize{ .{ 0, 0 }, .{ 1, 1 } }) |at| try std.testing.expectEqual(red, pixel(drawn[0], at[0], at[1]));
        for ([_][2]usize{ .{ 2, 0 }, .{ 3, 1 } }) |at| try std.testing.expectEqual(blue, pixel(drawn[0], at[0], at[1]));
    }
}

test "kitty: a chunked transmission arrives whole however the pty splits it, answered once" {
    // Three chunks of base64 (each a multiple of four), the keys on the first.
    const chunked = apc("a=T,i=2,f=24,s=4,v=2,c=2,r=1,m=1", rgb_b64[0..8]) ++
        apc("m=1", rgb_b64[8..20]) ++ apc("m=0", rgb_b64[20..]);
    for ([_]usize{ 1, 2, 3, 5, 7, 16, 64, chunked.len }) |step| {
        var r = try Rig.init(1);
        defer r.deinit();
        r.feedSplit(0, chunked, step);
        try std.testing.expectEqualStrings(reply("i=2", "OK"), try r.take(0));
        const img = r.storage(0).imageById(2) orelse return error.NotStored;
        try std.testing.expectEqualSlices(u8, &rgb_raw, img.data.bytes().?);
        try std.testing.expectEqual(@as(usize, 1), (try r.placesOf(2)).len);
    }
}

test "kitty: text around an APC prints, in the same read and split across reads" {
    for ([_]usize{ 1, 4, 1024 }) |step| {
        var r = try Rig.init(1);
        defer r.deinit();
        r.feedSplit(0, "before" ++ apc("a=t,i=3,f=24,s=4,v=2,q=2", rgb_b64) ++ "after", step);
        const text = try terminal.screenTextAlloc(r.pane(0), r.frame.allocator());
        try std.testing.expect(std.mem.indexOf(u8, text, "beforeafter") != null);
        try std.testing.expect(r.hasImage(0, 3));
    }
}

const shm = struct {
    extern "c" fn shm_open(name: [*:0]const u8, flag: c_int, mode: std.c.mode_t) c_int;
    extern "c" fn shm_unlink(name: [*:0]const u8) c_int;
};

fn writeTemp(path: [:0]const u8, bytes: []const u8) !void {
    const fd = std.c.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(std.c.mode_t, 0o600));
    if (fd < 0) return error.OpenFailed;
    defer _ = std.c.close(fd);
    if (std.c.write(fd, bytes.ptr, bytes.len) != @as(isize, @intCast(bytes.len))) return error.WriteFailed;
}

fn exists(path: [:0]const u8) bool {
    return std.c.access(path, std.c.F_OK) == 0;
}

fn b64(arena: std.mem.Allocator, bytes: []const u8) ![]const u8 {
    const enc = std.base64.standard.Encoder;
    const out = try arena.alloc(u8, enc.calcSize(bytes.len));
    return enc.encode(out, bytes);
}

test "kitty: file, temporary-file and shared-memory media load, and the terminal removes what it should" {
    var r = try Rig.init(1);
    defer r.deinit();
    const arena = r.frame.allocator();
    const pid = std.c.getpid();

    // t=f: a file the program keeps.
    const file = try std.fmt.allocPrintSentinel(arena, "/tmp/pardes-kitty-{d}-file.rgb", .{pid}, 0);
    try writeTemp(file, &rgb_raw);
    defer _ = std.c.unlink(file);
    r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=f,i=41,f=24,s=4,v=2;{s}\x1b\\", .{try b64(arena, file)}));
    const file_reply = try r.take(0);
    // t=t: a temporary file, which the terminal deletes once read; its name
    // must say it is one.
    const temp = try std.fmt.allocPrintSentinel(arena, "/tmp/tty-graphics-protocol-pardes-{d}.rgb", .{pid}, 0);
    try writeTemp(temp, &rgb_raw);
    defer _ = std.c.unlink(temp);
    r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=t,i=42,f=24,s=4,v=2;{s}\x1b\\", .{try b64(arena, temp)}));
    const temp_reply = try r.take(0);
    // t=s: a POSIX shared memory object, which the terminal unlinks.
    const name = try std.fmt.allocPrintSentinel(arena, "/pardes-kitty-{d}", .{pid}, 0);
    const fd = shm.shm_open(name, @bitCast(std.c.O{ .ACCMODE = .RDWR, .CREAT = true, .TRUNC = true }), 0o600);
    if (fd < 0) return error.ShmOpenFailed;
    defer _ = shm.shm_unlink(name);
    // Sized first: FreeBSD's write does not grow a shared memory object.
    if (ftruncate(fd, rgb_raw.len) != 0) return error.WriteFailed;
    if (std.c.write(fd, &rgb_raw, rgb_raw.len) != rgb_raw.len) return error.WriteFailed;
    _ = std.c.close(fd);
    r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=s,i=43,f=24,s=4,v=2,S={d};{s}\x1b\\", .{ rgb_raw.len, try b64(arena, name) }));
    const shm_reply = try r.take(0);

    const passes = std.mem.eql(u8, file_reply, reply("i=41", "OK")) and
        std.mem.eql(u8, temp_reply, reply("i=42", "OK")) and
        std.mem.eql(u8, shm_reply, reply("i=43", "OK"));
    if (!passes) {
        std.debug.print("media replies: f {f} | t {f} | s {f}\n", .{
            std.ascii.hexEscape(file_reply, .lower),
            std.ascii.hexEscape(temp_reply, .lower),
            std.ascii.hexEscape(shm_reply, .lower),
        });
        return error.MediumRefused;
    }
    for ([_]u32{ 41, 42, 43 }) |id| {
        const img = r.storage(0).imageById(id) orelse return error.NotStored;
        try std.testing.expectEqualSlices(u8, &rgb_raw, img.data.bytes().?);
    }
    try std.testing.expect(exists(file));
    try std.testing.expect(!exists(temp));
}

test "kitty: a temporary file outside the temp directory, or not named as one, is refused" {
    var r = try Rig.init(1);
    defer r.deinit();
    const arena = r.frame.allocator();
    const file = try std.fmt.allocPrintSentinel(arena, "/tmp/pardes-kitty-{d}-notemp.rgb", .{std.c.getpid()}, 0);
    try writeTemp(file, &rgb_raw);
    defer _ = std.c.unlink(file);
    r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=t,i=44,f=24,s=4,v=2;{s}\x1b\\", .{try b64(arena, file)}));
    const got = try r.take(0);
    try std.testing.expect(std.mem.startsWith(u8, got, "\x1b_Gi=44;E"));
    try std.testing.expect(!r.hasImage(0, 44));
    // Refused, it is left where it was.
    try std.testing.expect(exists(file));
}

test "kitty: a=T draws at the cursor and moves the cursor past the image; C=1 leaves it" {
    for ([_]bool{ false, true }) |still| {
        var r = try Rig.init(1);
        defer r.deinit();
        if (still)
            r.feed(0, "\x1b[3;5H" ++ apc("a=T,i=4,f=24,s=4,v=2,c=2,r=2,C=1,q=2", rgb_b64))
        else
            r.feed(0, "\x1b[3;5H" ++ apc("a=T,i=4,f=24,s=4,v=2,c=2,r=2,q=2", rgb_b64));
        const cursor = r.vt(0).screens.active.cursor;
        if (still) {
            try std.testing.expectEqual(@as(usize, 4), cursor.x);
            try std.testing.expectEqual(@as(usize, 2), cursor.y);
        } else {
            // Kitty: one cell past the image's right edge, on its last row.
            try std.testing.expectEqual(@as(usize, 6), cursor.x);
            try std.testing.expectEqual(@as(usize, 3), cursor.y);
        }
        const drawn = try r.placesOf(4);
        // A cell row at a time: two rows.
        try std.testing.expectEqual(@as(usize, 2), drawn.len);
        const o = r.origin(0);
        try std.testing.expectEqual(o.x + 4, drawn[0].dst.x);
        try std.testing.expectEqual(o.y + 2, drawn[0].dst.y);
        try std.testing.expectEqual(o.y + 3, drawn[1].dst.y);
        for (drawn) |place| try std.testing.expectEqual(@as(u16, 2), place.dst.w);
    }
}

test "kitty: a=p places one image twice by placement id, a source rect crops it, and a re-put moves it" {
    var r = try Rig.init(1);
    defer r.deinit();
    r.feed(0, apc("a=t,i=7,f=24,s=4,v=2", rgb_b64));
    try std.testing.expectEqualStrings(reply("i=7", "OK"), try r.take(0));
    try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(7)).len);
    r.feed(0, "\x1b[1;1H" ++ apc("a=p,i=7,p=1,c=2,r=1", ""));
    try std.testing.expectEqualStrings(reply("i=7,p=1", "OK"), try r.take(0));
    // The right half only (x=2, w=2): blue, in one cell.
    r.feed(0, "\x1b[6;10H" ++ apc("a=p,i=7,p=2,x=2,y=0,w=2,h=2,c=1,r=1", ""));
    try std.testing.expectEqualStrings(reply("i=7,p=2", "OK"), try r.take(0));
    try std.testing.expectEqual(@as(usize, 2), r.placementCount(0));
    const o = r.origin(0);
    var drawn = try r.placesOf(7);
    try std.testing.expectEqual(@as(usize, 2), drawn.len);
    var cropped: ?pardes.Placement = null;
    for (drawn) |place| if (place.dst.y == o.y + 5) {
        cropped = place;
    };
    const crop = cropped orelse return error.CroppedPlacementMissing;
    try std.testing.expectEqual(o.x + 9, crop.dst.x);
    try std.testing.expectEqual(@as(u16, 1), crop.dst.w);
    const g: pardes.image.NativeGeometry = .{ .src = crop.src, .dst = crop.at.? };
    try std.testing.expectEqual(@as(u32, 2), g.src.x);
    try std.testing.expectEqual(@as(u32, 2), g.src.w);
    // Put again under the same id, placement 1 moves; it is not doubled.
    r.feed(0, "\x1b[10;1H" ++ apc("a=p,i=7,p=1,c=2,r=1,q=1", ""));
    try std.testing.expectEqual(@as(usize, 2), r.placementCount(0));
    drawn = try r.placesOf(7);
    var at_ten = false;
    var at_one = false;
    for (drawn) |place| {
        if (place.dst.y == o.y + 9) at_ten = true;
        if (place.dst.y == o.y) at_one = true;
    }
    try std.testing.expect(at_ten and !at_one);
}

test "kitty: a=p of an image that is not there answers ENOENT" {
    var r = try Rig.init(1);
    defer r.deinit();
    r.feed(0, apc("a=p,i=99", ""));
    const got = try r.take(0);
    try std.testing.expect(std.mem.startsWith(u8, got, "\x1b_Gi=99;ENOENT"));
}

test "kitty: an image number gets an id, which the reply carries" {
    var r = try Rig.init(1);
    defer r.deinit();
    r.feed(0, apc("a=t,I=5,f=24,s=4,v=2", rgb_b64));
    const got = try r.take(0);
    // `i=<assigned>,I=5;OK`
    try std.testing.expect(std.mem.startsWith(u8, got, "\x1b_Gi="));
    try std.testing.expect(std.mem.endsWith(u8, got, ",I=5;OK\x1b\\"));
    try std.testing.expect(r.storage(0).imageByNumber(5) != null);
}

test "kitty: z-index travels with the image, and images are handed on lowest z first" {
    var r = try Rig.init(1);
    defer r.deinit();
    // Three overlapping at (0,0), given out of order; the virtual one's z
    // is its placement's.
    r.feed(0, "\x1b[1;1H" ++ apc("a=T,i=8,f=24,s=4,v=2,c=2,r=1,z=5,C=1,q=2", rgb_b64) ++
        apc("a=T,i=9,f=24,s=4,v=2,c=2,r=1,z=-7,C=1,q=2", rgb_b64) ++
        apc("a=T,i=10,f=24,s=4,v=2,c=2,r=1,C=1,q=2", rgb_b64) ++
        apc("a=T,U=1,i=11,f=24,s=4,v=2,c=1,r=1,z=3,q=2", rgb_b64) ++
        "\x1b[1;1H\x1b[38;2;0;0;11m\u{10EEEE}\u{0305}\u{0305}\x1b[39m");
    const drawn = try r.places();
    try std.testing.expectEqual(@as(usize, 4), drawn.len);
    var zs: [4]i32 = undefined;
    var ids: [4]u32 = undefined;
    for (drawn, 0..) |place, i| {
        zs[i] = place.z;
        ids[i] = r.idOf(place).?;
    }
    try std.testing.expectEqualSlices(i32, &.{ -7, 0, 3, 5 }, &zs);
    try std.testing.expectEqualSlices(u32, &.{ 9, 10, 11, 8 }, &ids);
}

/// A screen with two images in known places, for the deletes:
///   image 1: placement 1 at (0,0) 2x1, placement 2 at (10,5) 2x1, z=5
///   image 2:             placement 1 at (20,8) 2x2, z=-3
/// and the cursor parked at (20,8), on image 2.
fn deleteScene(r: *Rig) void {
    r.feed(0, apc("a=t,i=1,f=24,s=4,v=2,q=2", rgb_b64) ++ apc("a=t,i=2,f=24,s=4,v=2,q=2", rgb_b64));
    r.feed(0, "\x1b[1;1H" ++ apc("a=p,i=1,p=1,c=2,r=1,C=1,q=2", "") ++
        "\x1b[6;11H" ++ apc("a=p,i=1,p=2,c=2,r=1,z=5,C=1,q=2", "") ++
        "\x1b[9;21H" ++ apc("a=p,i=2,p=1,c=2,r=2,z=-3,C=1,q=2", ""));
}

test "kitty: every delete takes the placements it names, and the uppercase ones free the image" {
    const Case = struct {
        control: []const u8,
        /// Placements left, and whether images 1 and 2 are still stored.
        left: usize,
        one: bool,
        two: bool,
    };
    const cases = [_]Case{
        .{ .control = "a=d", .left = 0, .one = true, .two = true }, // d=a is the default
        .{ .control = "a=d,d=a", .left = 0, .one = true, .two = true },
        .{ .control = "a=d,d=A", .left = 0, .one = false, .two = false },
        .{ .control = "a=d,d=i,i=1", .left = 1, .one = true, .two = true },
        .{ .control = "a=d,d=I,i=1", .left = 1, .one = false, .two = true },
        .{ .control = "a=d,d=i,i=1,p=2", .left = 2, .one = true, .two = true },
        .{ .control = "a=d,d=c", .left = 2, .one = true, .two = true },
        .{ .control = "a=d,d=C", .left = 2, .one = true, .two = false },
        .{ .control = "a=d,d=p,x=11,y=6", .left = 2, .one = true, .two = true },
        .{ .control = "a=d,d=P,x=21,y=10", .left = 2, .one = true, .two = false },
        .{ .control = "a=d,d=q,x=11,y=6,z=5", .left = 2, .one = true, .two = true },
        .{ .control = "a=d,d=q,x=11,y=6,z=4", .left = 3, .one = true, .two = true },
        .{ .control = "a=d,d=x,x=2", .left = 2, .one = true, .two = true },
        .{ .control = "a=d,d=X,x=22", .left = 2, .one = true, .two = false },
        .{ .control = "a=d,d=y,y=6", .left = 2, .one = true, .two = true },
        .{ .control = "a=d,d=Y,y=10", .left = 2, .one = true, .two = false },
        .{ .control = "a=d,d=z,z=-3", .left = 2, .one = true, .two = true },
        .{ .control = "a=d,d=Z,z=-3", .left = 2, .one = true, .two = false },
        .{ .control = "a=d,d=r,x=1,y=1", .left = 1, .one = true, .two = true },
        .{ .control = "a=d,d=R,x=1,y=2", .left = 0, .one = false, .two = false },
    };
    for (cases) |c| {
        var r = try Rig.init(1);
        defer r.deinit();
        deleteScene(&r);
        try std.testing.expectEqual(@as(usize, 3), r.placementCount(0));
        try std.testing.expectEqual(@as(usize, 4), (try r.places()).len);
        r.feed(0, try std.fmt.allocPrint(r.frame.allocator(), "\x1b_G{s}\x1b\\", .{c.control}));
        const drawn = (try r.places()).len;
        const got = .{ r.placementCount(0), r.hasImage(0, 1), r.hasImage(0, 2) };
        std.testing.expectEqual(.{ c.left, c.one, c.two }, got) catch |err| {
            std.debug.print("delete {s}: left {d}, image 1 {}, image 2 {}\n", .{ c.control, got[0], got[1], got[2] });
            return err;
        };
        // Deletes never answer, and the frame draws what is left: a 2x1
        // placement is one place, the 2x2 one two.
        try std.testing.expectEqualStrings("", try r.take(0));
        var rows: usize = 0;
        var it = r.storage(0).placements.iterator();
        while (it.next()) |entry| rows += if (entry.key_ptr.image_id == 2) 2 else 1;
        try std.testing.expectEqual(rows, drawn);
    }
}

test "kitty: deletes by image number take that image's placements, and N frees it" {
    for ([_]bool{ false, true }) |free| {
        var r = try Rig.init(1);
        defer r.deinit();
        r.feed(0, "\x1b[1;1H" ++ apc("a=T,I=11,f=24,s=4,v=2,c=2,r=1,C=1,q=2", rgb_b64) ++
            "\x1b[5;1H" ++ apc("a=T,i=2,f=24,s=4,v=2,c=2,r=1,C=1,q=2", rgb_b64));
        try std.testing.expectEqual(@as(usize, 2), r.placementCount(0));
        if (free) r.feed(0, apc("a=d,d=N,I=11", "")) else r.feed(0, apc("a=d,d=n,I=11", ""));
        try std.testing.expectEqual(@as(usize, 1), r.placementCount(0));
        try std.testing.expectEqual(!free, r.storage(0).imageByNumber(11) != null);
        try std.testing.expect(r.hasImage(0, 2));
        try std.testing.expectEqual(@as(usize, 1), (try r.places()).len);
    }
}

test "kitty: a delete abandons a chunked load in progress" {
    var r = try Rig.init(1);
    defer r.deinit();
    r.feed(0, apc("a=t,i=9,f=24,s=4,v=2,m=1", rgb_b64[0..8]));
    r.feed(0, apc("a=d,d=A", ""));
    r.feed(0, apc("m=0", rgb_b64[8..]));
    try std.testing.expect(!r.hasImage(0, 9));
}

test "kitty: Unicode placeholders draw a virtual placement over two rows, with implicit columns" {
    var r = try Rig.init(1);
    defer r.deinit();
    // Image 7 in the placeholders' foreground; row diacritics U+0305 (0)
    // and U+030D (1); the first cell of each row names its column (U+0305 =
    // 0) and the next one carries on from it with no diacritic of its own.
    r.feed(0, apc("a=T,U=1,i=7,f=24,s=4,v=2,c=2,r=2,q=2", rgb_b64) ++
        "\x1b[2;3H\x1b[38;2;0;0;7m\u{10EEEE}\u{0305}\u{0305}\u{10EEEE}" ++
        "\x1b[3;3H\u{10EEEE}\u{030D}\u{0305}\u{10EEEE}\x1b[39mX");
    const drawn = try r.placesOf(7);
    const o = r.origin(0);
    try std.testing.expectEqual(@as(usize, 2), drawn.len);
    try std.testing.expectEqual(o.x + 2, drawn[0].dst.x);
    try std.testing.expectEqual(o.y + 1, drawn[0].dst.y);
    try std.testing.expectEqual(o.y + 2, drawn[1].dst.y);
    for (drawn) |place| try std.testing.expectEqual(@as(u16, 2), place.dst.w);
    // The top row shows the image's top half, the bottom its bottom half.
    try std.testing.expectEqual(@as(u32, 0), drawn[0].src.y);
    try std.testing.expectEqual(@as(u32, 1), drawn[1].src.y);
}

test "kitty: a placeholder naming its placement in the underline colour picks that placement" {
    var r = try Rig.init(1);
    defer r.deinit();
    // Two virtual placements of image 7: p=1 one cell, p=2 two cells wide.
    r.feed(0, apc("a=t,i=7,f=24,s=4,v=2,q=2", rgb_b64) ++
        apc("a=p,U=1,i=7,p=1,c=1,r=1,q=2", "") ++ apc("a=p,U=1,i=7,p=2,c=2,r=1,q=2", "") ++
        "\x1b[1;1H\x1b[38;2;0;0;7m\x1b[58;2;0;0;2m\u{10EEEE}\u{0305}\u{0305}\u{10EEEE}\x1b[39;59m");
    const drawn = try r.placesOf(7);
    try std.testing.expectEqual(@as(usize, 1), drawn.len);
    // Placement 2 spans two cells, so each cell is half the image.
    try std.testing.expectEqual(@as(u16, 2), drawn[0].dst.w);
}

test "kitty: an image follows its text when the shell scrolls, resizes and reflows" {
    var r = try Rig.init(1);
    defer r.deinit();
    r.feed(0, "\x1b[5;1Hmarker" ++ apc("a=T,i=10,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64));
    const o = r.origin(0);
    try std.testing.expectEqual(o.y + 4, (try r.placesOf(10))[0].dst.y);
    // Two lines of output at the bottom scroll it up two rows.
    r.feed(0, "\x1b[40;1H\n\n");
    try std.testing.expectEqual(o.y + 2, (try r.placesOf(10))[0].dst.y);
    // A narrower pane reflows the text; the image stays on its row.
    const pane = r.pane(0);
    terminal.resizeGrid(pane, 40, pane.rows);
    const text = try terminal.screenTextAlloc(pane, r.frame.allocator());
    var row: usize = 0;
    var lines = std.mem.splitScalar(u8, text, '\n');
    while (lines.next()) |line| : (row += 1) if (std.mem.startsWith(u8, line, "marker")) break;
    const drawn = try r.placesOf(10);
    try std.testing.expectEqual(@as(usize, 1), drawn.len);
    const viewport_top: usize = @intCast(terminal.gridOffset(pane));
    try std.testing.expectEqual(o.y + @as(u16, @intCast(row - viewport_top)), drawn[0].dst.y);
}

test "kitty: the alternate screen has its own images, and the primary's come back after it" {
    var r = try Rig.init(1);
    defer r.deinit();
    r.feed(0, "\x1b[1;1H" ++ apc("a=T,i=11,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64));
    r.feed(0, "\x1b[?1049h");
    try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(11)).len);
    // yazi's way in: the image goes on the alternate screen.
    r.feed(0, "\x1b[3;3H" ++ apc("a=T,i=12,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64));
    try std.testing.expectEqual(@as(usize, 1), (try r.placesOf(12)).len);
    try std.testing.expect(!r.hasImage(0, 11)); // per screen
    r.feed(0, "\x1b[?1049l");
    try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(12)).len);
    try std.testing.expectEqual(@as(usize, 1), (try r.placesOf(11)).len);
}

test "kitty: clear (ED 2 + ED 3) takes the images away, and they stay away" {
    var r = try Rig.init(1);
    defer r.deinit();
    r.feed(0, "\x1b[1;1H" ++ apc("a=T,i=13,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64));
    var nl: [2 * 60]u8 = undefined;
    for (0..60) |i| nl[2 * i ..][0..2].* = "\r\n".*;
    r.feed(0, &nl);
    r.feed(0, "\x1b[H\x1b[2J\x1b[3J");
    try std.testing.expectEqual(@as(usize, 0), r.placementCount(0));
    try std.testing.expectEqual(@as(usize, 0), (try r.places()).len);
    r.feed(0, "after clear\r\n");
    try std.testing.expectEqual(@as(usize, 0), (try r.places()).len);
}

test "kitty: replies go to the pane that asked, never another, and never into the drawn cells" {
    var r = try Rig.init(3);
    defer r.deinit();
    r.feed(1, apc("i=51,s=1,v=1,a=q,f=24", "AAAA"));
    r.feed(2, apc("i=52,s=1,v=1,a=q,f=24", "AAAA"));
    r.feed(1, apc("a=t,i=53,f=24,s=4,v=2", rgb_b64));
    r.feed(2, apc("a=p,i=53", ""));
    try std.testing.expectEqualStrings(reply("i=51", "OK") ++ reply("i=53", "OK"), try r.take(1));
    try std.testing.expect(std.mem.startsWith(u8, try r.take(2), reply("i=52", "OK") ++ "\x1b_Gi=53;ENOENT"));
    try std.testing.expectEqualStrings("", try r.take(0));
    // Images are per pane: pane 2 never sees pane 1's.
    try std.testing.expect(r.hasImage(1, 53) and !r.hasImage(2, 53));
    _ = try r.places();
    const s = &r.p.surface;
    for (0..s.rows) |y| for (0..s.cols) |x| {
        const g = s.at(@intCast(x), @intCast(y)).grapheme();
        try std.testing.expect(std.mem.indexOfScalar(u8, g, 0x1b) == null);
        try std.testing.expect(!std.mem.eql(u8, g, "_"));
    };
}

test "kitty: many replies from one read all arrive, each whole, in order" {
    var r = try Rig.init(1);
    defer r.deinit();
    var batch: std.ArrayList(u8) = .empty;
    defer batch.deinit(gpa);
    var want: std.ArrayList(u8) = .empty;
    defer want.deinit(gpa);
    for (100..164) |id| {
        try batch.print(gpa, "\x1b_Gi={d},s=1,v=1,a=q,f=24;AAAA\x1b\\", .{id});
        try want.print(gpa, "\x1b_Gi={d};OK\x1b\\", .{id});
    }
    r.feed(0, batch.items);
    try std.testing.expectEqualStrings(want.items, try r.take(0));
}

test "kitty: answers past what one read may hold are dropped whole, never cut" {
    var r = try Rig.init(1);
    defer r.deinit();
    var batch: std.ArrayList(u8) = .empty;
    defer batch.deinit(gpa);
    // Each fails with a long EINVAL: far more answer than the pane holds.
    for (1..1001) |id| try batch.print(gpa, "\x1b_Gi={d},s=2,v=2,a=q,f=24;AAAA\x1b\\", .{id});
    r.feed(0, batch.items);
    const got = try r.take(0);
    try std.testing.expect(got.len > 0);
    try std.testing.expect(r.pane(0).terminal.?.reply_dropped > 0);
    // Whole sequences only, each its own `ESC _ G ... ESC \`.
    var rest = got;
    while (rest.len > 0) {
        try std.testing.expect(std.mem.startsWith(u8, rest, "\x1b_Gi="));
        const end = std.mem.indexOf(u8, rest, "\x1b\\") orelse return error.CutAnswer;
        try std.testing.expect(std.mem.indexOf(u8, rest[3..end], "\x1b") == null);
        rest = rest[end + 2 ..];
    }
    // The next read is answered again.
    r.feed(0, apc("i=31,s=1,v=1,a=q,f=24", "AAAA"));
    try std.testing.expectEqualStrings(reply("i=31", "OK"), try r.take(0));
}

test "kitty: the graphics answer comes before DA's, as a probe expects" {
    var r = try Rig.init(1);
    defer r.deinit();
    // yazi, chafa and kitten icat probe this way and wait for DA to end it.
    r.feed(0, apc("i=31,s=1,v=1,a=q,t=d,f=24", "AAAA") ++ "\x1b[c");
    const got = try r.take(0);
    const kitty = std.mem.indexOf(u8, got, reply("i=31", "OK")) orelse return error.NoKittyReply;
    const da = std.mem.indexOf(u8, got, "\x1b[?") orelse return error.NoDaReply;
    try std.testing.expect(kitty < da);
}

test "kitty: a cancelled (CAN, SUB) APC runs nothing, answers nothing, and the text goes on" {
    for ([_][]const u8{ "\x18", "\x1a" }) |cancel| {
        var r = try Rig.init(1);
        defer r.deinit();
        r.feed(0, "\x1b_Ga=T,i=60,f=24,s=4,v=2;" ++ rgb_b64);
        r.feed(0, cancel);
        r.feed(0, "after");
        try std.testing.expect(!r.hasImage(0, 60));
        try std.testing.expectEqualStrings("", try r.take(0));
        const text = try terminal.screenTextAlloc(r.pane(0), r.frame.allocator());
        try std.testing.expect(std.mem.indexOf(u8, text, "after") != null);
    }
}

test "kitty: an image too large to hold is refused with an error" {
    var r = try Rig.init(1);
    defer r.deinit();
    // Past ghostty's 10000-pixel side.
    r.feed(0, apc("a=t,i=61,f=32,s=20000,v=2,o=z", blank_256_zlib_b64));
    const got = try r.take(0);
    try std.testing.expect(std.mem.startsWith(u8, got, "\x1b_Gi=61;E"));
    try std.testing.expect(!r.hasImage(0, 61));
}

test "kitty: many images stay inside the pane's storage limit, oldest out first, and go with the pane" {
    var r = try Rig.init(1);
    defer r.deinit();
    const storage = r.storage(0);
    var buf: [600]u8 = undefined;
    // 256 KiB each: 300 of them is past the 64 MiB a screen may hold.
    for (1..301) |id| r.feed(0, try std.fmt.bufPrint(&buf, "\x1b_Ga=t,i={d},f=32,s=256,v=256,o=z,q=2;{s}\x1b\\", .{ id, blank_256_zlib_b64 }));
    try std.testing.expect(storage.total_bytes <= storage.total_limit);
    try std.testing.expect(storage.images.count() < 300);
    try std.testing.expect(r.hasImage(0, 300));
    try std.testing.expect(!r.hasImage(0, 1));
    try std.testing.expectEqualStrings("", try r.take(0));
    // The testing allocator checks the pane gives all of it back (deinit).
}

test "kitty: an animation's frames play" {
    var r = try Rig.init(1);
    defer r.deinit();
    // Root frame red, frame 2 blue (a whole-frame RGB replacement), then
    // run it: s=3, looping.
    const blue_frame = "AAD/AAD/AAD/AAD/AAD/AAD/AAD/AAD/";
    r.feed(0, "\x1b[1;1H" ++ apc("a=T,i=70,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64) ++
        apc("a=f,i=70,f=24,s=4,v=2,z=40,q=2", blue_frame) ++
        // The root frame's gap is 0 (gapless, skipped) until it is given one.
        apc("a=a,i=70,r=1,z=40,q=2", "") ++
        apc("a=a,i=70,s=3,v=1,q=2", ""));
    const img = r.storage(0).imageById(70) orelse return error.NotStored;
    try std.testing.expect(img.animation != null);
    // On the core's clock: the first frame drawn starts it (red), the core
    // asks to wake for the next, and a frame drawn after 40 ms shows blue.
    const base: u64 = 10 * std.time.ns_per_s;
    r.p.advance(base);
    const first = try r.placesOf(70);
    try std.testing.expectEqual(red, pixel(first[0], 0, 0));
    try std.testing.expect(r.p.nextWake() != null);
    var shows_blue = false;
    for (1..20) |k| {
        r.p.advance(base + k * 50 * std.time.ns_per_ms);
        const drawn = try r.placesOf(70);
        if (drawn.len == 1 and std.mem.eql(u8, &pixel(drawn[0], 0, 0), &blue)) shows_blue = true;
    }
    try std.testing.expect(shows_blue);
    // Stopped (s=1), nothing more to wake for.
    r.feed(0, apc("a=a,i=70,s=1,q=2", ""));
    _ = try r.places();
    try std.testing.expectEqual(@as(?u64, null), terminal.animationDueMs(r.pane(0)));
}

test "kitty: a placement relative to another (P=, Q=) is drawn at its parent's cell plus H/V" {
    var r = try Rig.init(1);
    defer r.deinit();
    r.feed(0, apc("a=t,i=80,f=24,s=4,v=2,q=2", rgb_b64) ++ "\x1b[2;2H" ++
        apc("a=p,i=80,p=1,c=2,r=1,q=2", "") ++
        // Three cells right of placement 1, one row down; then one relative
        // to that, a chain two deep.
        apc("a=p,i=80,p=2,P=80,Q=1,H=3,V=1,c=2,r=1,q=2", "") ++
        apc("a=p,i=80,p=3,P=80,Q=2,H=3,c=2,r=1,q=2", ""));
    try std.testing.expectEqual(@as(usize, 3), r.placementCount(0));
    const drawn = try r.placesOf(80);
    try std.testing.expectEqual(@as(usize, 3), drawn.len);
    const o = r.origin(0);
    var cells: [3][2]u16 = undefined;
    for (drawn, 0..) |place, i| cells[i] = .{ place.dst.x - o.x, place.dst.y - o.y };
    std.mem.sort([2]u16, &cells, {}, struct {
        fn lt(_: void, a: [2]u16, b: [2]u16) bool {
            return a[0] < b[0];
        }
    }.lt);
    try std.testing.expectEqual([2]u16{ 1, 1 }, cells[0]);
    try std.testing.expectEqual([2]u16{ 4, 2 }, cells[1]);
    try std.testing.expectEqual([2]u16{ 7, 2 }, cells[2]);
    // Its parent deleted, a relative placement goes with it.
    r.feed(0, apc("a=d,d=i,i=80,p=1", ""));
    try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(80)).len);
}

// ---- What t=f, t=t and t=s may make pardes open ----
//
// A program in a pane names paths on pardes's machine. Which paths ghostty's
// loader accepts is its policy (kitty's, which the user accepts); what pardes
// owns is that none of them hangs or crashes it or blows its memory: a FIFO
// (an open for reading waits for a writer), a device (an open may do
// something), a file no screen could hold. And t=t deletes temporary files
// only.

extern "c" fn mkfifo(path: [*:0]const u8, mode: std.c.mode_t) c_int;
extern "c" fn symlink(target: [*:0]const u8, link: [*:0]const u8) c_int;
extern "c" fn usleep(us: c_uint) c_int;
extern "c" fn ftruncate(fd: c_int, len: i64) c_int;
extern "c" fn getcwd(buf: [*]u8, size: usize) ?[*:0]u8;

const Guard = struct {
    path: [:0]const u8,
    done: std.atomic.Value(bool) = .init(false),
    blocked: std.atomic.Value(bool) = .init(false),

    /// After 1.5 s still running, the feed is stuck in an open of the FIFO:
    /// open it for writing, which lets that open return.
    fn run(g: *Guard) void {
        for (0..150) |_| {
            if (g.done.load(.acquire)) return;
            _ = usleep(10_000);
        }
        g.blocked.store(true, .release);
        const fd = std.c.open(g.path, .{ .ACCMODE = .WRONLY }, @as(std.c.mode_t, 0));
        if (fd >= 0) _ = std.c.close(fd);
    }
};

/// Feeds `bytes`; whether the feed blocked opening `fifo`.
fn feedBlocks(r: *Rig, bytes: []const u8, fifo: [:0]const u8) !bool {
    var g: Guard = .{ .path = fifo };
    const t = try std.Thread.spawn(.{}, Guard.run, .{&g});
    r.feed(0, bytes);
    g.done.store(true, .release);
    t.join();
    return g.blocked.load(.acquire);
}

test "kitty: a FIFO named by t=f, t=t or t=s never blocks pardes" {
    var r = try Rig.init(1);
    defer r.deinit();
    const arena = r.frame.allocator();
    const pid = std.c.getpid();
    const Case = struct { medium: u8, fifo: [:0]const u8, name: []const u8 };
    const file = try std.fmt.allocPrintSentinel(arena, "/tmp/pardes-kitty-{d}-fifo", .{pid}, 0);
    const temp = try std.fmt.allocPrintSentinel(arena, "/tmp/tty-graphics-protocol-pardes-{d}-fifo", .{pid}, 0);
    const shm_path = try std.fmt.allocPrintSentinel(arena, "/dev/shm/pardes-kitty-{d}-fifo", .{pid}, 0);
    const cases = [_]Case{
        .{ .medium = 'f', .fifo = file, .name = file },
        .{ .medium = 't', .fifo = temp, .name = temp },
        .{ .medium = 's', .fifo = shm_path, .name = shm_path["/dev/shm".len..] },
    };
    for (cases) |c| {
        // Shared memory is a directory only on Linux (/dev/shm).
        if (c.medium == 's' and comptime @import("builtin").os.tag != .linux) continue;
        _ = std.c.unlink(c.fifo);
        if (mkfifo(c.fifo, 0o600) != 0) return error.MkfifoFailed;
        defer _ = std.c.unlink(c.fifo);
        const cmd = try std.fmt.allocPrint(arena, "\x1b_Ga=t,t={c},i=90,f=24,s=1,v=1;{s}\x1b\\", .{ c.medium, try b64(arena, c.name) });
        const blocked = try feedBlocks(&r, cmd, c.fifo);
        if (blocked) std.debug.print("t={c}: pardes blocked opening the FIFO {s}\n", .{ c.medium, c.fifo });
        try std.testing.expect(!blocked);
        try std.testing.expect(std.mem.startsWith(u8, try r.take(0), "\x1b_Gi=90;E"));
        try std.testing.expect(!r.hasImage(0, 90));
    }
}

test "kitty: t=s through a /dev/shm symlink to a FIFO does not block pardes either" {
    var r = try Rig.init(1);
    defer r.deinit();
    const arena = r.frame.allocator();
    const pid = std.c.getpid();
    const fifo = try std.fmt.allocPrintSentinel(arena, "/tmp/pardes-kitty-{d}-shmfifo", .{pid}, 0);
    _ = std.c.unlink(fifo);
    if (mkfifo(fifo, 0o600) != 0) return error.MkfifoFailed;
    defer _ = std.c.unlink(fifo);
    const link = try std.fmt.allocPrintSentinel(arena, "/dev/shm/pardes-kitty-{d}-link", .{pid}, 0);
    _ = std.c.unlink(link);
    if (symlink(fifo, link) != 0) return error.SymlinkFailed;
    defer _ = std.c.unlink(link);
    const cmd = try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=s,i=91,f=24,s=1,v=1;{s}\x1b\\", .{try b64(arena, link["/dev/shm".len..])});
    try std.testing.expect(!try feedBlocks(&r, cmd, fifo));
    try std.testing.expect(std.mem.startsWith(u8, try r.take(0), "\x1b_Gi=91;E"));
}

test "kitty: t=f and t=t refuse /proc, /sys, devices and directories" {
    var r = try Rig.init(1);
    defer r.deinit();
    const arena = r.frame.allocator();
    const refused = [_][]const u8{ "/proc/self/status", "/sys/devices/system/cpu/online", "/dev/null", "/dev/zero", "/dev/urandom", "/tmp", "/" };
    for ([_]u8{ 'f', 't' }) |medium| for (refused) |path| {
        // A raw 1x1 pixel needs 3 bytes (S=3): any readable file would do.
        r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t={c},i=92,f=24,s=1,v=1,S=3;{s}\x1b\\", .{ medium, try b64(arena, path) }));
        try std.testing.expect(std.mem.startsWith(u8, try r.take(0), "\x1b_Gi=92;E"));
        try std.testing.expect(!r.hasImage(0, 92));
    };
}

test "kitty: t=t deletes only a temporary file: one outside the temp directory, or behind a symlink, stays" {
    var r = try Rig.init(1);
    defer r.deinit();
    const arena = r.frame.allocator();
    const pid = std.c.getpid();
    var cwd_buf: [4096]u8 = undefined;
    const cwd = std.mem.span(getcwd(&cwd_buf, cwd_buf.len) orelse return error.NoCwd);
    // Outside /tmp, /dev/shm and $TMPDIR: the build's own cache.
    const dir = try std.fmt.allocPrintSentinel(arena, "{s}/.zig-cache/tmp/pardes-kitty-{d}", .{ cwd, pid }, 0);
    _ = std.c.mkdir(dir, 0o700);
    defer _ = std.c.rmdir(dir);
    const kept = try std.fmt.allocPrintSentinel(arena, "{s}/tty-graphics-protocol-kept.rgb", .{dir}, 0);
    try writeTemp(kept, &rgb_raw);
    defer _ = std.c.unlink(kept);
    const link = try std.fmt.allocPrintSentinel(arena, "/tmp/tty-graphics-protocol-pardes-{d}-link", .{pid}, 0);
    _ = std.c.unlink(link);
    if (symlink(kept, link) != 0) return error.SymlinkFailed;
    defer _ = std.c.unlink(link);
    for ([_][:0]const u8{ kept, link }) |path| {
        r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=t,i=93,f=24,s=4,v=2;{s}\x1b\\", .{try b64(arena, path)}));
        try std.testing.expect(std.mem.startsWith(u8, try r.take(0), "\x1b_Gi=93;E"));
        try std.testing.expect(!r.hasImage(0, 93));
        try std.testing.expect(exists(kept));
    }
}

test "kitty: a file bigger than a screen may hold is refused, not read whole" {
    var r = try Rig.init(1);
    defer r.deinit();
    const arena = r.frame.allocator();
    // 100 MiB, sparse: 5120x5120 RGBA, past the 64 MiB a screen holds.
    const big = try std.fmt.allocPrintSentinel(arena, "/tmp/pardes-kitty-{d}-big.rgba", .{std.c.getpid()}, 0);
    const fd = std.c.open(big, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(std.c.mode_t, 0o600));
    if (fd < 0) return error.OpenFailed;
    _ = ftruncate(fd, 5120 * 5120 * 4);
    _ = std.c.close(fd);
    defer _ = std.c.unlink(big);
    r.feed(0, try std.fmt.allocPrint(arena, "\x1b_Ga=t,t=f,i=94,f=32,s=5120,v=5120;{s}\x1b\\", .{try b64(arena, big)}));
    const got = try r.take(0);
    try std.testing.expect(std.mem.startsWith(u8, got, "\x1b_Gi=94;E"));
    try std.testing.expect(!r.hasImage(0, 94));
}

// ---- Fuzz ----
//
// Seeded random kitty traffic, the way a confused or hostile program sends
// it: commands with any keys and values, payloads valid and broken, CAN and
// SUB mid-command, placeholders with any diacritics, cursor moves, ED 2/3,
// the alternate screen, window and cell-size resizes and frames between,
// split into reads anywhere. Each seed checks that pardes neither crashes
// nor leaks (the testing allocator) and that every answer parses.
//
//   PARDES_KITTY_FUZZ=<seeds>         more seeds (default 24)
//   PARDES_KITTY_FUZZ_SEED=<seed>     one seed, printing each step
//   PARDES_KITTY_FUZZ_STEPS=<n>       steps per seed (default 400)
//
// A crash prints `seed S step N`: rerun that seed with fewer steps to
// shrink it. A bad answer shrinks itself to the shortest failing prefix.

fn envNumber(name: [*:0]const u8, default: u64) u64 {
    const v = std.c.getenv(name) orelse return default;
    return std.fmt.parseInt(u64, std.mem.span(v), 10) catch default;
}

const fuzz_keys = "aiIpfsvxywhcrXYzCUPQHVmoqtSOd";
const fuzz_actions = "tTpdqfac";
const fuzz_deletes = "aAiInNcCpPqQxXyYzZrRfF";

fn fuzzValue(rng: std.Random, out: *std.ArrayList(u8), arena: std.mem.Allocator) !void {
    switch (rng.uintLessThan(u8, 10)) {
        0 => try out.appendSlice(arena, "0"),
        1 => try out.print(arena, "{d}", .{rng.int(u32)}),
        2 => try out.print(arena, "-{d}", .{rng.uintLessThan(u32, 1 << 31)}),
        3 => try out.appendSlice(arena, "4294967295"),
        4 => try out.appendSlice(arena, "99999999999999999999"),
        5 => try out.appendSlice(arena, "x"),
        else => try out.print(arena, "{d}", .{rng.uintLessThan(u32, 12)}),
    }
}

/// A command that loads, or places what is loaded, with any geometry: it
/// gets past the parser to the storage and the drawing.
fn fuzzPlacement(rng: std.Random, arena: std.mem.Allocator) ![]const u8 {
    var out: std.ArrayList(u8) = .empty;
    const id = 1 + rng.uintLessThan(u32, 4);
    switch (rng.uintLessThan(u8, 3)) {
        0 => try out.print(arena, "\x1b_Ga=T,f=24,s=4,v=2,i={d},q=2", .{id}),
        1 => try out.print(arena, "\x1b_Ga=p,i={d},q=2", .{id}),
        else => try out.print(arena, "\x1b_Ga=T,f=100,i={d},q=2", .{id}),
    }
    const keys = "crxywhXYzCUpPQHV";
    for (0..rng.uintLessThan(usize, 6)) |_| {
        try out.print(arena, ",{c}=", .{keys[rng.uintLessThan(usize, keys.len)]});
        try fuzzValue(rng, &out, arena);
    }
    try out.append(arena, ';');
    if (std.mem.startsWith(u8, out.items, "\x1b_Ga=T,f=24")) try out.appendSlice(arena, rgb_b64);
    if (std.mem.startsWith(u8, out.items, "\x1b_Ga=T,f=100")) try out.appendSlice(arena, png_b64);
    try out.appendSlice(arena, "\x1b\\");
    return out.items;
}

fn fuzzCommand(rng: std.Random, arena: std.mem.Allocator) ![]const u8 {
    if (rng.boolean()) return fuzzPlacement(rng, arena);
    var out: std.ArrayList(u8) = .empty;
    try out.appendSlice(arena, "\x1b_G");
    const action = fuzz_actions[rng.uintLessThan(usize, fuzz_actions.len)];
    try out.print(arena, "a={c}", .{action});
    if (action == 'd') try out.print(arena, ",d={c}", .{fuzz_deletes[rng.uintLessThan(usize, fuzz_deletes.len)]});
    for (0..rng.uintLessThan(usize, 7)) |_| {
        const key = fuzz_keys[rng.uintLessThan(usize, fuzz_keys.len)];
        try out.print(arena, ",{c}=", .{key});
        switch (key) {
            'f' => try out.appendSlice(arena, ([_][]const u8{ "24", "32", "100", "7" })[rng.uintLessThan(usize, 4)]),
            't' => try out.appendSlice(arena, ([_][]const u8{ "d", "f", "t", "s", "q" })[rng.uintLessThan(usize, 5)]),
            'o' => try out.appendSlice(arena, if (rng.boolean()) "z" else "y"),
            else => try fuzzValue(rng, &out, arena),
        }
    }
    // Mostly the small ids the rest reuse, so commands meet each other.
    if (rng.uintLessThan(u8, 4) != 0) try out.print(arena, ",i={d}", .{1 + rng.uintLessThan(u32, 4)});
    if (rng.boolean()) try out.print(arena, ",s={d},v={d}", .{ rng.uintLessThan(u32, 6), rng.uintLessThan(u32, 6) });
    try out.append(arena, ';');
    switch (rng.uintLessThan(u8, 8)) {
        0 => try out.appendSlice(arena, rgb_b64),
        1 => try out.appendSlice(arena, rgba_b64),
        2 => try out.appendSlice(arena, png_b64),
        3 => try out.appendSlice(arena, rgb_zlib_b64),
        4 => {}, // nothing
        5 => {
            // base64, broken: random characters, wrong padding.
            for (0..rng.uintLessThan(usize, 40)) |_| try out.append(arena, "AB/+=x!Z09"[rng.uintLessThan(usize, 10)]);
        },
        6 => try out.appendSlice(arena, png_b64[0..rng.uintLessThan(usize, png_b64.len)]),
        else => try out.appendSlice(arena, "AAAA"),
    }
    switch (rng.uintLessThan(u8, 12)) {
        0 => try out.append(arena, 0x18), // CAN
        1 => try out.append(arena, 0x1a), // SUB
        2 => try out.appendSlice(arena, "\x1b[m"), // ESC aborting it
        else => try out.appendSlice(arena, "\x1b\\"),
    }
    return out.items;
}

fn fuzzOutput(rng: std.Random, arena: std.mem.Allocator) ![]const u8 {
    return switch (rng.uintLessThan(u8, 9)) {
        0 => try std.fmt.allocPrint(arena, "\x1b[{d};{d}H", .{ 1 + rng.uintLessThan(u32, 50), 1 + rng.uintLessThan(u32, 150) }),
        1 => "line\r\n",
        2 => "\x1b[H\x1b[2J\x1b[3J",
        3 => if (rng.boolean()) "\x1b[?1049h" else "\x1b[?1049l",
        4 => blk: {
            // Placeholders: an image id in the colour (24-bit or 256), any
            // diacritics, up to three per cell.
            var out: std.ArrayList(u8) = .empty;
            if (rng.boolean())
                try out.print(arena, "\x1b[38;2;{d};{d};{d}m", .{ rng.int(u8), rng.int(u8), rng.uintLessThan(u8, 5) })
            else
                try out.print(arena, "\x1b[38;5;{d}m", .{rng.uintLessThan(u8, 5)});
            if (rng.boolean()) try out.print(arena, "\x1b[58;5;{d}m", .{rng.uintLessThan(u8, 4)});
            for (0..1 + rng.uintLessThan(usize, 6)) |_| {
                try out.appendSlice(arena, "\u{10EEEE}");
                const marks = [_][]const u8{ "\u{0305}", "\u{030D}", "\u{030E}", "\u{0310}", "\u{0312}", "\u{033D}", "\u{0346}", "\u{1D242}" };
                for (0..rng.uintLessThan(usize, 4)) |_| try out.appendSlice(arena, marks[rng.uintLessThan(usize, marks.len)]);
            }
            try out.appendSlice(arena, "\x1b[39;59m");
            break :blk out.items;
        },
        5 => "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
        6 => "\x1b[2;8r\x1b[S\x1b[T\x1b[r",
        7 => "\x1b[3L\x1b[2M\x1b[4@\x1b[2P",
        else => "text",
    };
}

/// Every answer whole: kitty's `ESC _ G ... ESC \`, or a CSI.
fn answersParse(got: []const u8) bool {
    var rest = got;
    while (rest.len > 0) {
        if (std.mem.startsWith(u8, rest, "\x1b_G")) {
            const end = std.mem.indexOf(u8, rest, "\x1b\\") orelse return false;
            if (std.mem.indexOfScalar(u8, rest[3..end], 0x1b) != null) return false;
            rest = rest[end + 2 ..];
        } else if (std.mem.startsWith(u8, rest, "\x1b[")) {
            var i: usize = 2;
            while (i < rest.len and !(rest[i] >= 0x40 and rest[i] <= 0x7e)) i += 1;
            if (i == rest.len) return false;
            rest = rest[i + 1 ..];
        } else return false;
    }
    return true;
}

/// One seed's run, `steps` long; false on a bad answer.
fn fuzzRun(seed: u64, steps: usize, trace: bool) !bool {
    var prng: std.Random.DefaultPrng = .init(seed);
    const rng = prng.random();
    var r = try Rig.init(1);
    defer r.deinit();
    var arena_state: std.heap.ArenaAllocator = .init(gpa);
    defer arena_state.deinit();
    for (0..steps) |step| {
        _ = arena_state.reset(.retain_capacity);
        const arena = arena_state.allocator();
        if (trace) std.debug.print("seed {d} step {d}\n", .{ seed, step });
        switch (rng.uintLessThan(u8, 20)) {
            0 => {
                const cols = 20 + rng.uintLessThan(u16, 140);
                const rows = 6 + rng.uintLessThan(u16, 50);
                r.p.update(.{ .resize = .{ .cols = cols, .rows = rows, .cell_pixels = .{ .w = 1 + rng.uintLessThan(u16, 30), .h = 1 + rng.uintLessThan(u16, 60) } } });
                r.drain();
            },
            1 => terminal.resizeGrid(r.pane(0), 1 + rng.uintLessThan(u16, 120), 1 + rng.uintLessThan(u16, 40)),
            2, 3 => {
                const drawn = try r.places();
                if (trace) std.debug.print("  {d} places, {d} placements, {d} images\n", .{ drawn.len, r.placementCount(0), r.storage(0).images.count() });
            },
            4, 5, 6, 7 => r.feedSplit(0, try fuzzOutput(rng, arena), 1 + rng.uintLessThan(usize, 64)),
            else => {
                var batch: std.ArrayList(u8) = .empty;
                for (0..1 + rng.uintLessThan(usize, 4)) |_| try batch.appendSlice(arena, try fuzzCommand(rng, arena));
                r.feedSplit(0, batch.items, 1 + rng.uintLessThan(usize, 200));
            },
        }
        const got = try r.take(0);
        if (!answersParse(got)) {
            if (trace) std.debug.print("seed {d} step {d}: unparsable answer {f}\n", .{ seed, step, std.ascii.hexEscape(got, .lower) });
            return false;
        }
    }
    _ = try r.places();
    return true;
}

test "kitty: fuzzed traffic neither crashes nor leaks, and every answer parses" {
    const steps: usize = @intCast(envNumber("PARDES_KITTY_FUZZ_STEPS", 400));
    if (std.c.getenv("PARDES_KITTY_FUZZ_SEED")) |one| {
        const seed = try std.fmt.parseInt(u64, std.mem.span(one), 10);
        try std.testing.expect(try fuzzRun(seed, steps, true));
        return;
    }
    const seeds = envNumber("PARDES_KITTY_FUZZ", 24);
    for (0..seeds) |seed| {
        if (try fuzzRun(seed, steps, false)) continue;
        // Shrink to the shortest failing prefix.
        var lo: usize = 1;
        var hi: usize = steps;
        while (lo < hi) {
            const mid = lo + (hi - lo) / 2;
            if (try fuzzRun(seed, mid, false)) lo = mid + 1 else hi = mid;
        }
        std.debug.print("kitty fuzz: seed {d} fails in {d} steps; PARDES_KITTY_FUZZ_SEED={d} PARDES_KITTY_FUZZ_STEPS={d} traces it\n", .{ seed, lo, seed, lo });
        return error.FuzzFailed;
    }
    if (seeds != 24) std.debug.print("kitty fuzz: {d} seeds of {d} steps ok\n", .{ seeds, steps });
}

// ---- An image's pane, as it lives ----

test "kitty: scrolled back by pardes, an image shows on its row; scrolled forward, it goes" {
    var r = try Rig.init(1);
    defer r.deinit();
    const pane = r.pane(0);
    r.feed(0, "\x1b[1;1Hmarker" ++ apc("a=T,i=20,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64));
    var nl: [2 * 60]u8 = undefined;
    for (0..60) |i| nl[2 * i ..][0..2].* = "\r\n".*;
    r.feed(0, &nl);
    try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(20)).len);
    // Back to the top of the history: the marker row is the body's first.
    terminal.scrollGrid(pane, -1000);
    const o = r.origin(0);
    const drawn = try r.placesOf(20);
    try std.testing.expectEqual(@as(usize, 1), drawn.len);
    try std.testing.expectEqual(o.y, drawn[0].dst.y);
    try std.testing.expectEqual(o.x + 6, drawn[0].dst.x);
    terminal.followOutput(pane);
    try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(20)).len);
}

test "kitty: an edited copy taller than the rows it covers pushes the images below it down" {
    var r = try Rig.init(1);
    defer r.deinit();
    const pane = r.pane(0);
    r.feed(0, "\x1b[1;1Hone\r\ntwo\r\n\x1b[6;1H" ++ apc("a=T,i=21,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64));
    const o = r.origin(0);
    try std.testing.expectEqual(o.y + 5, (try r.placesOf(21))[0].dst.y);
    // Row 1 ("two") edited into three lines.
    pane.body.mode = .normal;
    pane.ovl = .{ .row = 1, .rows = 1, .text = try gpa.dupe(u8, "two\nthree\nfour") };
    const drawn = try r.placesOf(21);
    try std.testing.expectEqual(@as(usize, 1), drawn.len);
    try std.testing.expectEqual(o.y + 7, drawn[0].dst.y);
}

test "kitty: an image wider than its pane is cut at the pane's edge, never drawn over the next one" {
    var r = try Rig.init(3);
    defer r.deinit();
    // The classic boot: two columns. Pane 0 is in the left one.
    const rect = r.p.rects[0];
    const o = r.origin(0);
    const right = rect.x + rect.w;
    // 2x1 cells at its last-but-one column: one cell is the pane's.
    const at = try std.fmt.allocPrint(r.frame.allocator(), "\x1b[1;{d}H", .{r.pane(0).cols});
    r.feed(0, at);
    r.feed(0, apc("a=T,i=22,f=24,s=4,v=2,c=4,r=1,q=2", rgb_b64));
    const drawn = try r.placesOf(22);
    try std.testing.expectEqual(@as(usize, 1), drawn.len);
    try std.testing.expect(drawn[0].dst.x + drawn[0].dst.w <= o.x + r.pane(0).cols);
    try std.testing.expect(drawn[0].dst.x + drawn[0].dst.w <= right);
    // And the pixels it takes are only that cell's.
    const g: pardes.image.NativeGeometry = .{ .src = drawn[0].src, .dst = drawn[0].at.? };
    try std.testing.expect(g.dst.w <= @as(u32, drawn[0].dst.w) * 10);
}

test "kitty: a collapsed pane draws no image" {
    var r = try Rig.init(3);
    defer r.deinit();
    r.feed(1, "\x1b[1;1H" ++ apc("a=T,i=23,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64));
    try std.testing.expectEqual(@as(usize, 1), (try r.placesOf(23)).len);
    try std.testing.expect(r.p.executeBuiltinLine(1, "Collapse"));
    try std.testing.expectEqual(@as(usize, 0), (try r.placesOf(23)).len);
    try std.testing.expect(r.p.executeBuiltinLine(1, "Collapse"));
    try std.testing.expectEqual(@as(usize, 1), (try r.placesOf(23)).len);
}

test "kitty: a new cell size (font zoom) redraws an image at the same cells, scaled to the new size" {
    var r = try Rig.init(1);
    defer r.deinit();
    r.feed(0, "\x1b[2;3H" ++ apc("a=T,i=24,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64));
    var drawn = try r.placesOf(24);
    try std.testing.expectEqual(@as(u32, 20), drawn[0].at.?.w);
    r.p.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 15, .h = 30 } } });
    r.drain();
    drawn = try r.placesOf(24);
    const o = r.origin(0);
    try std.testing.expectEqual(@as(usize, 1), drawn.len);
    try std.testing.expectEqual(o.x + 2, drawn[0].dst.x);
    try std.testing.expectEqual(o.y + 1, drawn[0].dst.y);
    try std.testing.expectEqual(@as(u32, 30), drawn[0].at.?.w);
    try std.testing.expectEqual(@as(u32, 30), drawn[0].at.?.h);
}

test "kitty: a dumped and restored terminal keeps its images" {
    var r = try Rig.init(1);
    defer r.deinit();
    r.feed(0, "\x1b[1;1Hpicture" ++ apc("a=T,i=25,f=24,s=4,v=2,c=2,r=1,q=2", rgb_b64));
    try pardes.dump.dumpState(r.p);
    const restored = try pardes.dump.restore(r.p, r.p.dump_out.?, "/tmp/pardes-kitty.dump");
    defer restored.deinit();
    const pane = restored.panes[0].?;
    // ghostty's snapshot of the emulator (src/terminal.zig) carries them.
    try std.testing.expect(pane.terminal.?.vt.screens.active.kitty_images.placements.count() > 0);
}

// ---- Real clients' traffic ----
//
// What kitten icat 0.49.2 and chafa 1.18.3 wrote to a pardes pane, recorded
// with script(1) between them and the pane (`PARDES_KITTY_EXPLORE` in
// test/kitty_harness.zig), a 64x64 PNG on a 118-column pane with 8x16 cells:
// their probes, then the image streamed. Replayed in 4 KiB reads, each must
// answer whole and draw its first row where it drew live.

const Recorded = struct {
    name: []const u8,
    bytes: []const u8,
    /// The pane cell its top-left landed on, live; null: draws nothing.
    at: ?[2]u16,
};

const recorded = [_]Recorded{
    .{ .name = "icat --align=left", .bytes = @embedFile("kitty-fixtures/icat-left.vt"), .at = .{ 0, 0 } },
    .{ .name = "icat --align=center", .bytes = @embedFile("kitty-fixtures/icat-center.vt"), .at = .{ 55, 0 } },
    .{ .name = "icat --align=right", .bytes = @embedFile("kitty-fixtures/icat-right.vt"), .at = .{ 110, 0 } },
    .{ .name = "icat --place 10x5@20x3", .bytes = @embedFile("kitty-fixtures/icat-place.vt"), .at = .{ 21, 3 } },
    .{ .name = "icat --unicode-placeholder", .bytes = @embedFile("kitty-fixtures/icat-placeholder.vt"), .at = .{ 0, 0 } },
    .{ .name = "chafa -f kitty -s 8x4", .bytes = @embedFile("kitty-fixtures/chafa.vt"), .at = .{ 0, 0 } },
    .{ .name = "icat --clear", .bytes = @embedFile("kitty-fixtures/icat-clear.vt"), .at = null },
};

test "kitty: recorded kitten icat and chafa traffic replays: answers whole, images where they were drawn" {
    for (recorded) |rec| {
        var r = try Rig.init(1);
        defer r.deinit();
        r.p.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 8, .h = 16 } } });
        r.drain();
        _ = try r.take(0);
        r.feedSplit(0, rec.bytes, 4096);
        const got = try r.take(0);
        std.testing.expect(answersParse(got)) catch |err| {
            std.debug.print("{s}: unparsable answer {f}\n", .{ rec.name, std.ascii.hexEscape(got, .lower) });
            return err;
        };
        const drawn = try r.places();
        const want = rec.at orelse {
            try std.testing.expectEqual(@as(usize, 0), drawn.len);
            continue;
        };
        const o = r.origin(0);
        var top: ?pardes.Placement = null;
        for (drawn) |place| {
            if (top == null or place.dst.y < top.?.dst.y or (place.dst.y == top.?.dst.y and place.dst.x < top.?.dst.x)) top = place;
        }
        const first = top orelse {
            std.debug.print("{s}: nothing drawn\n", .{rec.name});
            return error.NothingDrawn;
        };
        std.testing.expectEqual([2]u16{ o.x + want[0], o.y + want[1] }, [2]u16{ first.dst.x, first.dst.y }) catch |err| {
            std.debug.print("{s}: drawn at {d},{d}, live at {d},{d}\n", .{ rec.name, first.dst.x - o.x, first.dst.y - o.y, want[0], want[1] });
            return err;
        };
    }
}

test "kitty: under a shell that draws no pixels, a 64x64 image over 8x4 cells is still handed on over those cells, its cells left to the shell" {
    // The glyph art a tty draws there is the tty's test (tui.zig).
    var r = try Rig.init(1);
    defer r.deinit();
    r.p.frontend.native_images = false;
    r.p.update(.{ .resize = .{ .cols = 120, .rows = 40, .cell_pixels = .{ .w = 8, .h = 16 } } });
    r.drain();
    // Not the frame's arena: each frame resets that.
    var data: std.heap.ArenaAllocator = .init(gpa);
    defer data.deinit();
    const arena = data.allocator();
    const px = try arena.alloc(u8, 64 * 64 * 3);
    for (0..64 * 64) |i| px[i * 3 ..][0..3].* = .{ 13, 77, 231 };
    const enc = try b64(arena, px);
    for ([_]bool{ false, true }) |helix| {
        if (helix) try std.testing.expect(r.p.executeBuiltinLine(0, "Theme helix"));
        // As test/kitty_client.zig's `place` sends it: after text, in
        // 1 KiB chunks.
        var cmds: std.ArrayList(u8) = .empty;
        try cmds.appendSlice(arena, "\x1b[H\x1b[2J\r\nANCHOR>");
        var at: usize = 0;
        while (at < enc.len) : (at += 1024) {
            const end = @min(enc.len, at + 1024);
            const more: u8 = if (end < enc.len) '1' else '0';
            if (at == 0)
                try cmds.print(arena, "\x1b_Ga=T,i=42,f=24,s=64,v=64,c=8,r=4,m={c};{s}\x1b\\", .{ more, enc[at..end] })
            else
                try cmds.print(arena, "\x1b_Gm={c};{s}\x1b\\", .{ more, enc[at..end] });
        }
        try cmds.appendSlice(arena, "\r\n");
        r.feed(0, cmds.items);
        const drawn = try r.places();
        const o = r.origin(0);
        try std.testing.expectEqual(@as(usize, 4), drawn.len);
        for (drawn, 0..) |place, dy| {
            try std.testing.expectEqual(pardes.RectCell{ .x = o.x + 7, .y = o.y + 1 + @as(u16, @intCast(dy)), .w = 8, .h = 1 }, place.dst);
            try std.testing.expect(!place.art.glyph);
            try std.testing.expectEqualStrings(" ", r.p.surface.at(o.x + 7, place.dst.y).grapheme());
        }
    }
}