summaryrefslogtreecommitdiff
path: root/test/kitty_client.zig
blob: 03ad629edd42aae3de92c6fbe712a449ea48bf13 (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
//! A kitty graphics client for test/kitty_harness.zig: run in a pardes
//! terminal pane, it plays one case of the protocol the way yazi or
//! `kitten icat` do (raw mode, a batch of commands, then reads what comes
//! back) and records every byte its pty gave it.
//!
//!   pardes-kitty-client <case> <out>
//!
//! After the case's commands it sends a sync query (`i=999`); replies come
//! in order, so all the case's are in before the sync's. `<out>` gets the
//! bytes read, and `<out>.done` is made last, which the harness waits for.
const std = @import("std");
const c = std.c;

// 64x64 RGB, one colour: the harness looks for it in the outer terminal's
// image store and in the GUI's capture.
pub const side = 64;
pub const colour = [3]u8{ 13, 77, 231 };
const sync = "\x1b_Gi=999,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\";

// The kernel's ioctls on Linux: glibc's tcgetattr writes its 60-byte
// termios into Zig's 44-byte kernel one, and std.posix's calls glibc's in a
// program linking libc (src/main.zig exports kernel ones; this has none).
const linux = @import("builtin").os.tag == .linux;

fn getTermios() !std.posix.termios {
    if (!linux) return std.posix.tcgetattr(0) catch error.NotATerminal;
    var t: std.os.linux.termios = undefined;
    if (std.os.linux.errno(std.os.linux.tcgetattr(0, &t)) != .SUCCESS) return error.NotATerminal;
    return t;
}

fn setTermios(t: std.posix.termios) void {
    if (!linux) return std.posix.tcsetattr(0, .NOW, t) catch {};
    _ = std.os.linux.tcsetattr(0, .NOW, &t);
}

pub fn main(init: std.process.Init) !void {
    var arena_state: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
    defer arena_state.deinit();
    const arena = arena_state.allocator();
    const args = try init.minimal.args.toSlice(arena);
    if (args.len != 3) return error.BadArgs;
    const case = args[1];
    const out = try arena.dupeSentinel(u8, args[2], 0);

    const saved = try getTermios();
    var raw = saved;
    raw.lflag.ICANON = false;
    raw.lflag.ECHO = false;
    raw.cc[@backingInt(std.posix.V.MIN)] = 0;
    raw.cc[@backingInt(std.posix.V.TIME)] = 1;
    setTermios(raw);
    defer setTermios(saved);

    var cmds: std.ArrayList(u8) = .empty;
    try play(arena, case, &cmds);
    try cmds.appendSlice(arena, sync);
    try writeAll(cmds.items);

    // Read until the sync's answer, or 5 s.
    var got: std.ArrayList(u8) = .empty;
    var buf: [4096]u8 = undefined;
    var waited: usize = 0;
    while (waited < 50 and std.mem.indexOf(u8, got.items, "\x1b_Gi=999;") == null) {
        const n = c.read(0, &buf, buf.len);
        if (n > 0) try got.appendSlice(arena, buf[0..@intCast(n)]) else waited += 1;
    }
    // A little longer, for anything that should not have come.
    for (0..3) |_| {
        const n = c.read(0, &buf, buf.len);
        if (n > 0) try got.appendSlice(arena, buf[0..@intCast(n)]);
    }
    // t=f's file stays the client's to remove (a terminal deletes only t=t's).
    _ = c.unlink(try std.fmt.allocPrintSentinel(arena, "/tmp/kc-{d}.rgb", .{c.getpid()}, 0));
    try writeFile(out, got.items);
    try writeFile(try std.fmt.allocPrintSentinel(arena, "{s}.done", .{out}, 0), "");
}

fn play(arena: std.mem.Allocator, case: []const u8, cmds: *std.ArrayList(u8)) !void {
    const pixels = try solid(arena);
    const enc = std.base64.standard.Encoder;
    const b64 = try arena.alloc(u8, enc.calcSize(pixels.len));
    _ = enc.encode(b64, pixels);
    const pid = c.getpid();

    if (std.mem.eql(u8, case, "query")) {
        // yazi's and chafa's probe: a graphics query, then DA to end it.
        try cmds.appendSlice(arena, "\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\\x1b[c");
    } else if (std.mem.eql(u8, case, "place")) {
        // A line to find, then the image right after it: chunked in 1 KiB
        // pieces, as kitten icat sends a big one, 8x4 cells.
        try cmds.appendSlice(arena, "\r\nANCHOR>");
        var at: usize = 0;
        var first = true;
        while (at < b64.len) : (at += 1024) {
            const end = @min(b64.len, at + 1024);
            const more: u8 = if (end < b64.len) '1' else '0';
            if (first)
                try cmds.print(arena, "\x1b_Ga=T,i=42,f=24,s={d},v={d},c=8,r=4,m={c};{s}\x1b\\", .{ side, side, more, b64[at..end] })
            else
                try cmds.print(arena, "\x1b_Gm={c};{s}\x1b\\", .{ more, b64[at..end] });
            first = false;
        }
        try cmds.appendSlice(arena, "\r\n");
    } else if (std.mem.eql(u8, case, "media")) {
        const file = try std.fmt.allocPrintSentinel(arena, "/tmp/kc-{d}.rgb", .{pid}, 0);
        const temp = try std.fmt.allocPrintSentinel(arena, "/tmp/tty-graphics-protocol-kc-{d}.rgb", .{pid}, 0);
        const shm_name = try std.fmt.allocPrintSentinel(arena, "/kc-{d}", .{pid}, 0);
        try writeFile(file, pixels);
        try writeFile(temp, pixels);
        const fd = shm_open(shm_name, @bitCast(c.O{ .ACCMODE = .RDWR, .CREAT = true, .TRUNC = true }), 0o600);
        if (fd < 0) return error.ShmOpenFailed;
        if (c.write(fd, pixels.ptr, pixels.len) != @as(isize, @intCast(pixels.len))) return error.WriteFailed;
        _ = c.close(fd);
        for ([_]struct { u8, u32, []const u8 }{ .{ 'f', 51, file }, .{ 't', 52, temp }, .{ 's', 53, shm_name } }) |m| {
            const path = try arena.alloc(u8, enc.calcSize(m[2].len));
            _ = enc.encode(path, m[2]);
            try cmds.print(arena, "\x1b_Ga=t,t={c},i={d},f=24,s={d},v={d};{s}\x1b\\", .{ m[0], m[1], side, side, path });
        }
    } else if (std.mem.eql(u8, case, "quiet")) {
        // q=1 hides the OK, q=2 the error; q=0's error is heard.
        try cmds.print(arena, "\x1b_Ga=t,i=61,f=24,s={d},v={d},q=1;{s}\x1b\\", .{ side, side, b64 });
        try cmds.appendSlice(arena, "\x1b_Ga=t,i=62,f=24,s=2,v=2,q=2;AAAA\x1b\\");
        try cmds.appendSlice(arena, "\x1b_Ga=t,i=63,f=24,s=2,v=2,q=0;AAAA\x1b\\");
    } else if (std.mem.eql(u8, case, "cancel")) {
        // CAN in the middle of the payload: nothing runs, the text goes on.
        try cmds.print(arena, "\x1b_Ga=T,i=64,f=24,s={d},v={d};{s}\x18CANCELLED-OK\r\n", .{ side, side, b64[0..512] });
    } else if (std.mem.eql(u8, case, "under")) {
        // Under the text (z < 0), as a background picture is put.
        try cmds.print(arena, "\x1b_Ga=T,i=66,f=24,s={d},v={d},c=8,r=4,z=-1,q=2;{s}\x1b\\\r\n", .{ side, side, b64 });
    } else if (std.mem.eql(u8, case, "show")) {
        try cmds.print(arena, "\x1b_Ga=T,i=65,f=24,s={d},v={d},c=8,r=4,q=2;{s}\x1b\\\r\n", .{ side, side, b64 });
    } else if (std.mem.eql(u8, case, "delete")) {
        // Run after `show`, in the same pane: image 65 is still stored.
        try cmds.appendSlice(arena, "\x1b_Ga=d,d=I,i=65\x1b\\");
    } else return error.UnknownCase;
}

extern "c" fn shm_open(name: [*:0]const u8, flag: c_int, mode: c.mode_t) c_int;

fn solid(arena: std.mem.Allocator) ![]u8 {
    const px = try arena.alloc(u8, side * side * 3);
    for (0..side * side) |i| px[i * 3 ..][0..3].* = colour;
    return px;
}

fn writeAll(bytes: []const u8) !void {
    var at: usize = 0;
    while (at < bytes.len) {
        const n = c.write(1, bytes[at..].ptr, bytes.len - at);
        if (n < 0) {
            if (c.errno(n) == .INTR or c.errno(n) == .AGAIN) continue;
            return error.WriteFailed;
        }
        at += @intCast(n);
    }
}

fn writeFile(path: [:0]const u8, bytes: []const u8) !void {
    const fd = c.open(path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(c.mode_t, 0o644));
    if (fd < 0) return error.OpenFailed;
    defer _ = c.close(fd);
    var at: usize = 0;
    while (at < bytes.len) {
        const n = c.write(fd, bytes[at..].ptr, bytes.len - at);
        if (n <= 0) return error.WriteFailed;
        at += @intCast(n);
    }
}