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
|
//! Kitty graphics protocol conformance for terminal panes, at the core.
//!
//! zig build kitty-test -Dplatform=tty|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
//! `ImagePlace`s 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.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.ImagePlace {
_ = r.frame.reset(.retain_capacity);
const s = try r.p.render(r.frame.allocator());
return s.images[0..s.nimages];
}
/// 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.ImagePlace {
var out: std.ArrayList(pardes.ImagePlace) = .empty;
for (try r.places()) |maybe| if (maybe) |place| if (place.native.page == 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.ImagePlace, x: usize, y: usize) [4]u8 {
return place.rgba[(y * place.iw + 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].iw);
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);
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].x);
try std.testing.expectEqual(o.y + 2, drawn[0].y);
try std.testing.expectEqual(o.y + 3, drawn[1].y);
for (drawn) |place| try std.testing.expectEqual(@as(u16, 2), place.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.ImagePlace = null;
for (drawn) |place| if (place.y == o.y + 5) {
cropped = place;
};
const crop = cropped orelse return error.CroppedPlacementMissing;
try std.testing.expectEqual(o.x + 9, crop.x);
try std.testing.expectEqual(@as(u16, 1), crop.w);
const g = crop.native.geometry.?;
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.y == o.y + 9) at_ten = true;
if (place.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 orders images, and a negative one goes under the text" {
var r = try Rig.init(1);
defer r.deinit();
r.feed(0, "\x1b[1;1H" ++ apc("a=T,i=8,f=24,s=4,v=2,c=2,r=1,z=-1,q=2", rgb_b64) ++ "\x1b[1;1Htext");
try std.testing.expectEqual(@as(usize, 1), r.placementCount(0));
var it = r.storage(0).placements.iterator();
try std.testing.expectEqual(@as(i32, -1), it.next().?.value_ptr.z);
try knownGap("pardes draws every terminal image over the cells, in storage order: an ImagePlace has no z-index, so z<0 (under the text) and the order between overlapping images are lost", @hasField(pardes.ImagePlace, "z"));
}
/// 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].x);
try std.testing.expectEqual(o.y + 1, drawn[0].y);
try std.testing.expectEqual(o.y + 2, drawn[1].y);
for (drawn) |place| try std.testing.expectEqual(@as(u16, 2), place.w);
// The top row shows the image's top half, the bottom its bottom half.
try std.testing.expectEqual(@as(u32, 0), drawn[0].native.geometry.?.src.y);
try std.testing.expectEqual(@as(u32, 1), drawn[1].native.geometry.?.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].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].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].y);
// A narrower pane reflows the text; the image stays on its row.
const pane = r.pane(0);
terminal.resizeGrid(pane, gpa, 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].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.x - o.x, place.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| {
_ = 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));
}
|