summaryrefslogtreecommitdiff
path: root/test/session.zig
blob: 16a131fd54feb0214d102dc0e3351b85da93654d (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
//! T1 of docs/next-tests.md: a session driven as a 9P client drives one,
//! in process. Each call walks a path from the root, opens, reads or writes,
//! and clunks, through `serveFs` alone. The core is opaque here, so a
//! behavioural test (test/behaviour/, whose module imports only this) has
//! no field to reach: what it can see is what a client can.
const std = @import("std");
const pardes = @import("pardes");

const Pardes = pardes.Pardes;
const Req = pardes.ctlfs.Req;
const Reply = pardes.ctlfs.Reply;

pub const Session = struct {
    core: *anyopaque,
    /// What the calls answered, kept until deinit.
    arena: std.heap.ArenaAllocator,
    /// Saves the core asked its host for (a host would perform them).
    saved: usize = 0,
    /// The words of the last refusal `refused` answered.
    said: []const u8 = "",
    tag: u64 = 0,

    /// A session showing one file pane holding `text`.
    pub fn initFile(gpa: std.mem.Allocator, text: []const u8) !Session {
        const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
        errdefer p.deinit();
        _ = try p.setTestFile(text);
        var s: Session = .{ .core = p, .arena = .init(gpa) };
        s.drain();
        return s;
    }

    /// A session showing its terminal pane, as `pardes` starts.
    pub fn initTerm(gpa: std.mem.Allocator) !Session {
        const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 });
        var s: Session = .{ .core = p, .arena = .init(gpa) };
        s.drain();
        return s;
    }

    pub fn deinit(s: *Session) void {
        pardesOf(s).deinit();
        s.arena.deinit();
    }

    /// The whole file at `path` (`/index`, `/pane/3/body`).
    pub fn read(s: *Session, path: []const u8) ![]const u8 {
        const node, const h = try s.open(path, 0);
        defer _ = s.serve(.{ .tag = 0, .op = .release, .node = node, .handle = h, .opened = true });
        var out: std.ArrayList(u8) = .empty;
        while (true) {
            const r = s.serve(.{ .tag = 0, .op = .read, .node = node, .handle = h, .off = out.items.len, .size = 1 << 16 });
            if (r.status != .ok) return refusal(path, r);
            const bytes = pardesOf(s).fsPayload(r);
            if (bytes.len == 0) break;
            try out.appendSlice(s.arena.allocator(), bytes);
        }
        return out.items;
    }

    /// `data` written to `path` in one write, the open clunked after.
    pub fn write(s: *Session, path: []const u8, data: []const u8) !void {
        const errno = try s.refused(path, data);
        if (errno != 0) return error.Refused;
    }

    /// Like `write`, answering the refusal's errno, 0 when it was taken.
    pub fn refused(s: *Session, path: []const u8, data: []const u8) !u16 {
        const node, const h = try s.open(path, 1);
        const w = s.serve(.{ .tag = 0, .op = .write, .node = node, .handle = h, .data = data });
        // The clunk can refuse too (an Edit block left open), as close(2) does.
        const c = s.serve(.{ .tag = 0, .op = .release, .node = node, .handle = h, .opened = true });
        const r = if (w.status != .ok) w else c;
        if (r.status == .ok) return 0;
        s.said = try s.arena.allocator().dupe(u8, r.ename);
        return r.errno;
    }

    /// A path built from `args` (`s.at("/pane/{d}/body", .{n})`), kept
    /// until deinit.
    pub fn at(s: *Session, comptime fmt: []const u8, args: anytype) []const u8 {
        return std.fmt.allocPrint(s.arena.allocator(), fmt, args) catch @panic("out of memory");
    }

    /// A new pane, made by opening /pane/new; its serial.
    pub fn newPane(s: *Session) !u32 {
        return std.fmt.parseInt(u32, std.mem.trim(u8, try s.read("/pane/new"), "\n"), 10);
    }

    pub fn expect(s: *Session, path: []const u8, want: []const u8) !void {
        try std.testing.expectEqualStrings(want, try s.read(path));
    }

    /// Keys typed at the pane with the keyboard (`/kbdin`'s runes).
    pub fn keys(s: *Session, runes: []const u8) !void {
        try s.write("/kbdin", runes);
    }

    /// A click (Plan 9's buttons: 1 left, 2 middle, 4 right) on the first
    /// place `text` is drawn, `into` cells into it, found as a user finds it.
    pub fn click(s: *Session, text: []const u8, into: usize, buttons: u8) !void {
        const col, const row = try s.find(text);
        var line: [64]u8 = undefined;
        const x = col + into;
        try s.write("/mousein", try std.fmt.bufPrint(&line, "m {d} {d} {d}\nm {d} {d} 0\n", .{ x, row, buttons, x, row }));
    }

    /// The screen a frame draws, a line a row.
    pub fn screen(s: *Session) ![]const u8 {
        const a = s.arena.allocator();
        const json = try std.json.parseFromSliceLeaky(std.json.Value, a, try s.read("/screen"), .{});
        const cols: usize = @intCast(json.object.get("cols").?.integer);
        const cells = json.object.get("cells").?.array.items;
        var out: std.ArrayList(u8) = .empty;
        for (cells, 0..) |cell, i| {
            if (i > 0 and i % cols == 0) try out.append(a, '\n');
            const g = cell.array.items[0].string;
            try out.appendSlice(a, if (g.len == 0) " " else g);
        }
        return out.items;
    }

    /// A range file (`dot`, `addr`, `limit`) as its two offsets.
    pub fn range(s: *Session, path: []const u8) !struct { u32, u32 } {
        var it = std.mem.tokenizeScalar(u8, try s.read(path), ' ');
        return .{ try std.fmt.parseInt(u32, it.next() orelse return error.NoRange, 10), try std.fmt.parseInt(u32, it.next() orelse return error.NoRange, 10) };
    }

    /// No frontend attached, as a detached session's daemon says.
    pub fn detach(s: *Session) void {
        pardesOf(s).unattended = true;
    }

    /// The serial of the pane with the keyboard.
    pub fn focused(s: *Session) !u32 {
        return std.fmt.parseInt(u32, std.mem.trim(u8, try s.read("/focus"), "\n"), 10);
    }

    // shortcut: a grapheme is taken as one cell wide, so text past a wide
    // character is found a column off; count widths when a test needs it.
    fn find(s: *Session, text: []const u8) !struct { usize, usize } {
        var rows = std.mem.splitScalar(u8, try s.screen(), '\n');
        var row: usize = 0;
        while (rows.next()) |line| : (row += 1) {
            if (std.mem.indexOf(u8, line, text)) |i| return .{ try std.unicode.utf8CountCodepoints(line[0..i]), row };
        }
        std.debug.print("not on the screen: {s}\n", .{text});
        return error.NotOnScreen;
    }

    fn open(s: *Session, path: []const u8, omode: u8) !struct { u64, u32 } {
        var node: u64 = pardes.ctlfs.root;
        var parts = std.mem.tokenizeScalar(u8, path, '/');
        while (parts.next()) |name| {
            const r = s.serve(.{ .tag = 0, .op = .lookup, .node = node, .data = name });
            if (r.status != .ok) return refusal(path, r);
            node = r.attr.node;
        }
        const r = s.serve(.{ .tag = 0, .op = .open, .node = node, .omode = omode });
        if (r.status != .ok) return refusal(path, r);
        return .{ node, r.handle };
    }

    fn serve(s: *Session, req: Req) Reply {
        var q = req;
        s.tag += 1;
        q.tag = s.tag;
        const r = pardesOf(s).serveFs(q);
        // As the server does (src/9p_io.zig): a clunk's held lines run then.
        if (q.op == .release) pardes.ctlfs.runClosedLines(pardesOf(s));
        s.drain();
        return r;
    }

    fn drain(s: *Session) void {
        while (pardesOf(s).nextEffect()) |e| switch (e) {
            .save_file, .save_text => s.saved += 1,
            else => {},
        };
    }

    fn pardesOf(s: *Session) *Pardes {
        return @ptrCast(@alignCast(s.core));
    }

    // ninep:

    /// An open kept until `clunk`, as an event reader or a lock holder
    /// keeps one.
    pub const Fid = struct { node: u64, handle: u32 };

    /// `path` opened (omode 0 read, 1 write, 2 both) and held.
    pub fn hold(s: *Session, path: []const u8, omode: u8) !Fid {
        const node, const h = try s.open(path, omode);
        return .{ .node = node, .handle = h };
    }

    /// One read on a held open (an event record, an answer).
    pub fn readFid(s: *Session, f: Fid) ![]const u8 {
        const r = s.serve(.{ .tag = 0, .op = .read, .node = f.node, .handle = f.handle, .size = 1 << 16 });
        if (r.status != .ok) return refusal("a held open", r);
        return s.arena.allocator().dupe(u8, pardesOf(s).fsPayload(r));
    }

    /// One write on a held open: 0 when taken, else its errno, its words in `said`.
    pub fn writeFid(s: *Session, f: Fid, data: []const u8) !u16 {
        const r = s.serve(.{ .tag = 0, .op = .write, .node = f.node, .handle = f.handle, .data = data });
        if (r.status == .ok) return 0;
        s.said = try s.arena.allocator().dupe(u8, r.ename);
        return r.errno;
    }

    pub fn clunk(s: *Session, f: Fid) void {
        _ = s.serve(.{ .tag = 0, .op = .release, .node = f.node, .handle = f.handle, .opened = true });
    }

    /// A held open's file truncated, as an OTRUNC open (`> data`) does.
    pub fn truncate(s: *Session, f: Fid) !void {
        const r = s.serve(.{ .tag = 0, .op = .setattr, .node = f.node, .truncate = true });
        if (r.status != .ok) return refusal("truncate", r);
    }

    /// One read of `size` bytes at `off`, on an open of its own.
    pub fn readAt(s: *Session, path: []const u8, off: u64, size: u32) ![]const u8 {
        const f = try s.hold(path, 0);
        defer s.clunk(f);
        const r = s.serve(.{ .tag = 0, .op = .read, .node = f.node, .handle = f.handle, .off = off, .size = size });
        if (r.status != .ok) return refusal(path, r);
        return s.arena.allocator().dupe(u8, pardesOf(s).fsPayload(r));
    }

    /// What a stat of `path` answers: its size, mode and qid version.
    pub fn stat(s: *Session, path: []const u8) !struct { size: u64, mode: u16, version: u32 } {
        const f = try s.hold(path, 0);
        defer s.clunk(f);
        const r = s.serve(.{ .tag = 0, .op = .getattr, .node = f.node });
        if (r.status != .ok) return refusal(path, r);
        return .{ .size = r.attr.size, .mode = r.attr.mode, .version = r.attr.version };
    }

    // panes:
    /// `data` written to `path` truncated first, as a shell's `>` does.
    pub fn replace(s: *Session, path: []const u8, data: []const u8) !void {
        const node, const h = try s.open(path, 1);
        defer _ = s.serve(.{ .tag = 0, .op = .release, .node = node, .handle = h, .opened = true });
        const t = s.serve(.{ .tag = 0, .op = .setattr, .node = node, .handle = h, .truncate = true });
        if (t.status != .ok) return refusal(path, t);
        const w = s.serve(.{ .tag = 0, .op = .write, .node = node, .handle = h, .data = data });
        if (w.status != .ok) return refusal(path, w);
    }

    // core:

    /// /layout as its columns, left to right, `column:pane,pane` each and
    /// a blank between (`1:2,5 3:`, column 3 empty).
    pub fn columns(s: *Session) ![]const u8 {
        const a = s.arena.allocator();
        var out: std.ArrayList(u8) = .empty;
        var lines = std.mem.tokenizeScalar(u8, try s.read("/layout"), '\n');
        while (lines.next()) |line| {
            if (std.mem.startsWith(u8, line, "active ")) continue;
            var words = std.mem.tokenizeScalar(u8, line, ' ');
            if (out.items.len > 0) try out.append(a, ' ');
            try out.print(a, "{s}:", .{words.next().?});
            for (0..5) |_| _ = words.next(); // index x width current empty|full
            var sep: []const u8 = "";
            while (words.next()) |pane| : (sep = ",") try out.print(a, "{s}{s}", .{ sep, pane });
        }
        return out.items;
    }

    /// The serial of the `i`th column from the left.
    pub fn column(s: *Session, i: usize) !u32 {
        var cols = std.mem.tokenizeScalar(u8, try s.columns(), ' ');
        for (0..i) |_| _ = cols.next();
        const col = cols.next() orelse return error.NoColumn;
        return std.fmt.parseInt(u32, col[0..std.mem.indexOfScalar(u8, col, ':').?], 10);
    }

    /// Where /screen draws the cursor, column and row; null when it draws none.
    pub fn cursor(s: *Session) !?struct { usize, usize } {
        const json = try std.json.parseFromSliceLeaky(std.json.Value, s.arena.allocator(), try s.read("/screen"), .{});
        const c = switch (json.object.get("cursor").?) {
            .object => |o| o,
            else => return null,
        };
        return .{ @intCast(c.get("x").?.integer), @intCast(c.get("y").?.integer) };
    }

    /// Where `text` is first drawn on /screen, column and row.
    pub fn where(s: *Session, text: []const u8) !struct { usize, usize } {
        return s.find(text);
    }

    // pdf:

    /// A Look of `path` at the root (one relative to the working directory
    /// made absolute first); the serial of the pane with the keyboard after.
    /// A PDF in a build without them (-Dmupdf=false: no PdfTint in
    /// /commands) skips the test.
    pub fn lookFile(s: *Session, path: []const u8) !u32 {
        if (std.mem.endsWith(u8, path, ".pdf") and std.mem.indexOf(u8, try s.read("/commands"), "PdfTint") == null) return error.SkipZigTest;
        var buf: [4096]u8 = undefined;
        const abs = if (std.fs.path.isAbsolute(path)) path else s.at("{s}/{s}", .{ buf[0..try std.Io.Dir.cwd().realPath(std.testing.io, &buf)], path });
        try s.write("/look", s.at("{s}\n", .{abs}));
        return s.focused();
    }

    /// The page a PDF pane shows and its pages, from its tag's `[page/pages]`.
    pub fn pdfPage(s: *Session, n: u32) !struct { u32, u32 } {
        const tag = try s.read(s.at("/pane/{d}/tag", .{n}));
        const lo = std.mem.indexOf(u8, tag, " [") orelse return error.NoPage;
        const close = std.mem.indexOfScalarPos(u8, tag, lo, ']') orelse return error.NoPage;
        var it = std.mem.splitScalar(u8, tag[lo + 2 .. close], '/');
        return .{ try std.fmt.parseInt(u32, it.next().?, 10), try std.fmt.parseInt(u32, it.next() orelse return error.NoPage, 10) };
    }
};

fn refusal(path: []const u8, r: Reply) error{Refused} {
    std.debug.print("{s}: refused, errno {d}: {s}\n", .{ path, r.errno, r.ename });
    return error.Refused;
}