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
|
//! 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;
extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
pub const Session = struct {
/// The image addon (addons/image/image.c), as the build installs it.
pub const image_addon = @import("session_options").image_addon;
/// The fake addon, and its copies built wrong (build.zig).
pub const fake_addons = struct {
const o = @import("session_options");
pub const ok = o.fake_addon;
pub const abi = o.fake_addon_abi;
pub const no_export = o.fake_addon_no_export;
pub const core_word = o.fake_addon_core_word;
pub const no_dump = o.fake_addon_no_dump;
};
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,
/// What the language words' questions are asked of their servers
/// through (initLanguage); none, and they go unanswered.
languages: ?std.Io = null,
/// Kinds' jobs taken as a host's worker takes them and held, not run,
/// until `releaseJobs`: a job under way across what a test does
/// meanwhile (a reload).
hold_jobs: bool = false,
held: std.ArrayList(*pardes.host_io.KindJob) = .empty,
/// A session showing one file pane holding `text`, keeping what outlives
/// it in a database in memory (src/Db.zig).
pub fn initFile(gpa: std.mem.Allocator, text: []const u8) !Session {
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory });
errdefer p.deinit();
_ = try p.setTestFile(text);
var s: Session = .{ .core = p, .arena = .init(gpa) };
s.drain();
return s;
}
/// A session showing one scratch pane that asks language servers as a
/// host does, a `.rs` file's the scripted one (test/lspmock.zig, which
/// answers over a main.rs and the lib.rs beside it).
pub fn initLanguage(gpa: std.mem.Allocator) !Session {
var s = try initFile(gpa, "x\n");
const mock = try std.Io.Dir.cwd().realPathFileAlloc(std.testing.io, @import("session_options").lspmock, s.arena.allocator());
_ = setenv("PARDES_LSP_RS", mock, 1);
s.languages = std.testing.io;
return s;
}
/// A session showing one file pane, its startup file `init` (as
/// `~/.config/pardes/init` is read) applied first.
pub fn initStartup(gpa: std.mem.Allocator, init: []const u8) !Session {
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .startup_config = init });
errdefer p.deinit();
_ = try p.setTestFile("x\n");
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, .state = .memory });
var s: Session = .{ .core = p, .arena = .init(gpa) };
s.drain();
return s;
}
/// A session showing a scratch pane, keeping its state in the state
/// file in `dir` (its DumpDir), as every session of a user shares one.
pub fn initShared(gpa: std.mem.Allocator, dir: []const u8) !Session {
var config: [4200]u8 = undefined;
const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .disk, .startup_config = try std.fmt.bufPrint(&config, "DumpDir {s}\n", .{dir}) });
var s: Session = .{ .core = p, .arena = .init(gpa) };
s.drain();
return s;
}
pub fn deinit(s: *Session) void {
s.held.deinit(pardesOf(s).gpa);
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();
// A Restore asked for is performed once its write is answered (the
// write's reply holds nothing of the core it replaces).
s.restoreIfAsked();
return r;
}
fn drain(s: *Session) void {
while (pardesOf(s).nextEffect()) |e| switch (e) {
.save_file, .save_text => s.saved += 1,
// Into the session's state (a database in memory, or its file).
.write_dump => pardes.host_io.writeDump(pardesOf(s), pardesOf(s).dump_out.?),
.addon => pardesOf(s).perform(e),
// A kind's job, here and at once, as the host's worker would;
// held while a test holds them (`hold_jobs`).
.job => |j| if (!s.hold_jobs) pardesOf(s).perform(e) else if (pardes.host_io.KindJob.take(pardesOf(s), j.pane, j.serial, j.token)) |taken| s.held.append(pardesOf(s).gpa, taken) catch taken.drop(),
.lsp => |q| if (s.languages) |io| s.askServer(io, .{ .id = q.id, .kind = q.kind, .pane = q.pane, .offset = q.offset, .arg = q.arg.slice() }),
else => {},
};
}
/// The jobs held, run now and answered as the host's workers would.
pub fn releaseJobs(s: *Session) void {
s.hold_jobs = false;
for (s.held.items) |j| {
j.run();
j.land(pardesOf(s));
}
s.held.clearRetainingCapacity();
s.drain();
}
/// A language word's question asked of its server as a host asks it
/// (host_io.Lsp), here and at once: its answer the core's next event.
fn askServer(s: *Session, io: std.Io, req: pardes.host_io.Lsp.Request) void {
const p = pardesOf(s);
const Lsp = pardes.host_io.Lsp;
const job = Lsp.snapshot(p.gpa, p, req) catch return p.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } });
var rows: ?[]u8 = null;
Lsp.work(io, p.gpa, job, &rows, struct {
fn keep(ctx: ?*anyopaque, _: u32, answer: ?[]u8) void {
const into: *?[]u8 = @ptrCast(@alignCast(ctx.?));
into.* = answer;
}
}.keep);
defer if (rows) |owned| p.gpa.free(owned);
p.update(.{ .lsp_resp = .{ .id = req.id, .rows = rows } });
}
/// A Restore the write asked for, performed as a host performs it after
/// the write is answered (host_io.restoreCore): the dump read, and the
/// new core in the old one's place.
fn restoreIfAsked(s: *Session) void {
const p = pardesOf(s);
const gpa = p.gpa;
const name = p.takeRestore() orelse return;
const bytes = pardes.dump.restoreBytes(p, gpa, name) catch |err| return p.reportError(p.view().active, "Restore", err);
defer gpa.free(bytes);
const nc = pardes.dump.restore(p, bytes, name) catch |err| return p.reportError(p.view().active, "Restore", err);
p.deinit();
s.core = nc;
s.drain();
}
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) };
}
// pane2:
/// Each cell's style as /screen draws it, as JSON text (compare two
/// cells by it), row-major as `screen` draws the cells: row `y`'s cell
/// `x` is `[y * cols + x]`.
pub fn styles(s: *Session) ![]const []const u8 {
const a = s.arena.allocator();
const json = try std.json.parseFromSliceLeaky(std.json.Value, a, try s.read("/screen"), .{});
const kinds = json.object.get("styles").?.array.items;
const named = try a.alloc([]const u8, kinds.len);
for (kinds, named) |style, *text| text.* = try std.json.Stringify.valueAlloc(a, style, .{});
const cells = json.object.get("cells").?.array.items;
const out = try a.alloc([]const u8, cells.len);
for (cells, out) |cell, *style| style.* = named[@intCast(cell.array.items[1].integer)];
return out;
}
// core2:
/// The background /screen draws at a cell, as its JSON (`{"rgb":[255,255,255]}`).
pub fn bg(s: *Session, col: usize, row: usize) ![]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 cell = json.object.get("cells").?.array.items[row * cols + col];
const style = json.object.get("styles").?.array.items[@intCast(cell.array.items[1].integer)];
return std.json.Stringify.valueAlloc(a, style.object.get("bg").?, .{});
}
// mky: the 9P monkey's raw requests (test/monkey9p.zig). Quiet, and
// answering what came back rather than failing; the server engine's
// own checks (a write on a read-only open, OTRUNC's truncation first)
// are the monkey's to make.
/// A walked fid: its node, its open (`opened`, `fid.handle`), and what
/// the walk's last step said of it.
pub const Walked = struct { fid: Fid, dir: bool, mode: u16, opened: bool = false };
/// `held`: parked (`.again`), as a read with nothing yet is. `bytes`, a
/// read's (a readdir's names, a line each), last until the next request.
pub const Answer = struct { errno: u16 = 0, held: bool = false, bytes: []const u8 = "" };
pub const Ask = enum { open, create, read, readdir, write, clunk, remove, stat, truncate };
/// `path` walked from the root, not opened; null, its words in `said`,
/// when a step is refused.
pub fn walk(s: *Session, path: []const u8) !?Walked {
var r = s.serve(.{ .tag = 0, .op = .getattr, .node = pardes.ctlfs.root });
var node: u64 = pardes.ctlfs.root;
var parts = std.mem.tokenizeScalar(u8, path, '/');
while (parts.next()) |name| {
r = s.serve(.{ .tag = 0, .op = .lookup, .node = node, .data = name });
if (r.status != .ok) {
s.said = try s.arena.allocator().dupe(u8, r.ename);
return null;
}
node = r.attr.node;
}
return .{ .fid = .{ .node = node, .handle = 0 }, .dir = r.attr.dir, .mode = r.attr.mode };
}
/// One request on `w` as the engine passes it on (a clunk of an open,
/// a remove as a release that removes); `off` is a readdir's entry index.
pub fn ask(s: *Session, w: *Walked, what: Ask, a: struct { off: u64 = 0, size: u32 = 0, data: []const u8 = "", omode: u8 = 0, perm: u32 = 0 }) Answer {
const f = w.fid;
const r = s.serve(switch (what) {
.open => .{ .tag = 0, .op = .open, .node = f.node, .omode = a.omode },
.create => .{ .tag = 0, .op = .open, .node = f.node, .create = true, .data = a.data, .perm = a.perm, .omode = a.omode },
.read => .{ .tag = 0, .op = .read, .node = f.node, .handle = f.handle, .off = a.off, .size = a.size },
.readdir => .{ .tag = 0, .op = .readdir, .node = f.node, .handle = f.handle, .off = a.off, .size = a.size },
.write => .{ .tag = 0, .op = .write, .node = f.node, .handle = f.handle, .off = a.off, .data = a.data },
.clunk, .remove => .{ .tag = 0, .op = .release, .node = f.node, .handle = f.handle, .opened = w.opened, .remove = what == .remove },
.stat => .{ .tag = 0, .op = .getattr, .node = f.node, .handle = f.handle },
.truncate => .{ .tag = 0, .op = .setattr, .node = f.node, .truncate = true },
});
if (r.status == .again) return .{ .held = true };
if (r.status != .ok) {
s.said = s.arena.allocator().dupe(u8, r.ename) catch "";
return .{ .errno = if (r.errno == 0) 5 else r.errno };
}
if (what == .open or what == .create) {
w.fid.handle = r.handle;
w.opened = true;
}
if (what == .clunk or what == .remove) w.opened = false;
if (what != .readdir) return .{ .bytes = pardesOf(s).fsPayload(r) };
// A dirent: node (8), dir (1), name length (1), name.
const raw = pardesOf(s).fsPayload(r);
var names: std.ArrayList(u8) = .empty;
var i: usize = 0;
while (i + 10 <= raw.len) : (i += 10 + raw[i + 9]) {
names.appendSlice(s.arena.allocator(), raw[i + 10 ..][0..raw[i + 9]]) catch break;
names.append(s.arena.allocator(), '\n') catch break;
}
return .{ .bytes = names.items };
}
/// Whether the session has quit, as closing its last pane quits it.
pub fn ended(s: *Session) bool {
return pardesOf(s).quit;
}
};
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;
}
|