summaryrefslogtreecommitdiff
path: root/src/host/control.zig
blob: 75fb5245d6e60475ce1328a4cc78805f4c6d6e6b (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
//! Local 9P controls, serviced on the frame thread: no SDL or state races.
const std = @import("std");
const c9 = @import("cloud9");
const c = @import("c");
const abi = @import("abi");
const Host = @import("Host.zig");
const Presentation = @import("Presentation.zig");
const state_files = @import("state_files.zig");
const script = @import("script.zig");
const Console = @import("Console.zig");
const fs = c9.fs;
const transport = c9.transport;
const Backend = struct {
    pub const Req = fs.Req;
    pub const Reply = fs.Reply;
};
const Server = fs.Server(Backend, .{ .fid_capacity = 32, .slot_capacity = 4, .name_capacity = 64 });
const msize = 16384;
/// The files, a row each: what lookup, readdir and getattr answer. A
/// file's node is its number here.
const File = enum(u64) { @"/" = 1, ctl, status, log, @"screen.png", profile, @"profile-trace", @"timing-trace", @"presentation-trace", README, commands, sketch = 1 << 63, state = @bitCast(state_files.root) };
const files = std.enums.EnumArray(File, struct { mode: u16 = 0o400, doc: []const u8 }).init(.{
    .@"/" = .{ .mode = 0o700, .doc = "" },
    .ctl = .{ .mode = 0o600, .doc = "write a verb a line, of those below: ctl's own, the input a script plays (live, no frame of its own), the console's; any other line goes to the sketch (commands lists its words)" },
    .status = .{ .doc = "name, canvas size, playback mode, gpu, and the screenshot's state" },
    .log = .{ .doc = "the console's last five lines" },
    .@"screen.png" = .{ .doc = "the next frame, as PNG: an open waits for it to be drawn, and pins its own copy" },
    .profile = .{ .doc = "with --profile-gpu: label, count, mean, worst, p95 and p99 ms, tab-separated" },
    .@"profile-trace" = .{ .doc = "with --profile-gpu: label,sample,ns, the samples kept, as CSV" },
    .@"timing-trace" = .{ .doc = "index,frame_ns,work_ns,outside_work_ns, the frames kept, as CSV" },
    .@"presentation-trace" = .{ .doc = "on Wayland: presentation feedback per frame, as CSV" },
    .README = .{ .doc = "this: a line a file, ctl's verbs under it, a line a State file under state/" },
    .commands = .{ .doc = "every verb ctl takes, a line each, the sketch's words last" },
    .sketch = .{ .mode = 0o700, .doc = "the sketch's own files, which the host never serves: reserved, empty" },
    .state = .{ .mode = 0o700, .doc = "the sketch's State: a directory per struct and array, a file per value; a read is the value, a write what set does (a jump); an array of numbers is one file of its values, blank-separated" },
});

/// The verbs `ctl` takes beside the console's lines.
const Verb = enum { screenshot, @"profile-reset" };
const verbs = std.enums.EnumArray(Verb, []const u8).init(.{
    .screenshot = "captures the next frame (status says when); screen.png's open does it itself",
    .@"profile-reset" = "clears profile's counters and frame count, keeping its labels",
});

const Connection = struct {
    fd: c_int = -1,
    server: Server = undefined,
    input: [msize]u8 = undefined,
    output: [msize * 2]u8 = undefined,
    incoming: [msize]u8 = undefined,
    used: usize = 0,
    snapshots: [32]?[]u8 = @splat(null),

    fn close(self: *Connection, a: std.mem.Allocator) void {
        if (self.fd < 0) return;
        transport.close(self.fd);
        for (&self.snapshots) |*snapshot| if (snapshot.*) |bytes| {
            a.free(bytes);
            snapshot.* = null;
        };
        self.fd = -1;
    }
};

pub const Control = struct {
    allocator: std.mem.Allocator,
    path: [:0]u8,
    listener: c_int,
    /// Serving with no sketch running (`fs` with it closed): the State to
    /// show and where it came from; the host is not touched.
    offline: ?Offline = null,
    connections: [4]Connection = @splat(.{}),
    png: []u8 = &.{},
    capture_pending: bool = false,
    generation: u64 = 0,
    capture_error: ?anyerror = null,

    pub fn init(a: std.mem.Allocator, path: []const u8) !*Control {
        const self = try a.create(Control);
        errdefer a.destroy(self);
        const z = try a.dupeSentinel(u8, path, 0);
        errdefer a.free(z);
        // Refuse an existing path; never unlink another process's socket.
        const fd = try transport.listenFd(.{ .unix = z }, 4);
        errdefer {
            transport.close(fd);
            _ = std.c.unlink(z);
        }
        if (std.c.chmod(z, 0o600) != 0) return error.SocketPermissions;
        self.* = .{ .allocator = a, .path = z, .listener = fd };
        return self;
    }

    /// Listens at `where`: a socket path, or a name posted as
    /// `$XDG_RUNTIME_DIR/9p/sketchbook/<where>` (a stale entry replaced, a
    /// live one refused).
    pub fn open(a: std.mem.Allocator, environ: *const std.process.Environ.Map, where: []const u8) !*Control {
        if (std.mem.startsWith(u8, where, "/")) return init(a, where);
        var buf: [c9.post.sun_path_len]u8 = undefined;
        const path = try registered(environ, where, &buf);
        const dir = path[0..std.mem.lastIndexOfScalar(u8, path, '/').?];
        var dir_buf: [c9.post.sun_path_len]u8 = undefined;
        for ([_]usize{ dir.len - "/sketchbook".len, dir.len }) |n| _ = std.c.mkdir(std.fmt.bufPrintSentinel(&dir_buf, "{s}", .{dir[0..n]}, 0) catch unreachable, 0o700);
        switch (c9.post.probe(path)) {
            .live => return error.AlreadyPosted,
            .stale => _ = std.c.unlink(path),
            .none => {},
        }
        return init(a, path);
    }

    /// Serves one client on `fd` until it hangs up: `fs` with no sketch
    /// running, on a thread of its own.
    pub fn serveOffline(self: *Control, fd: c_int) void {
        const conn = self.allocator.create(Connection) catch return transport.close(fd);
        defer self.allocator.destroy(conn);
        conn.* = .{ .fd = fd };
        conn.server = .init(.{ .in = &conn.input, .out = &conn.output, .root = 1 });
        var host: Host = undefined; // Offline, nothing reads it.
        while (true) self.service(&host, conn) catch break;
        conn.close(self.allocator);
    }

    pub fn deinit(self: *Control) void {
        for (&self.connections) |*conn| conn.close(self.allocator);
        transport.close(self.listener);
        _ = std.c.unlink(self.path);
        self.allocator.free(self.path);
        self.allocator.free(self.png);
        self.allocator.destroy(self);
    }

    pub fn poll(self: *Control, host: *Host) void {
        if (transport.acceptFd(self.listener, false) catch null) |fd| {
            var accepted = false;
            for (&self.connections) |*conn| if (conn.fd < 0) {
                conn.fd = fd;
                conn.used = 0;
                conn.server = .init(.{ .in = &conn.input, .out = &conn.output, .root = 1 });
                accepted = true;
                break;
            };
            if (!accepted) transport.close(fd);
        }
        for (&self.connections) |*conn| {
            if (conn.fd < 0) continue;
            self.service(host, conn) catch conn.close(self.allocator);
        }
    }

    fn service(self: *Control, host: *Host, conn: *Connection) !void {
        // Bound work per frame, including clients which continually write.
        for (0..32) |_| {
            var progressed = false;
            if (conn.used != 0) {
                const consumed = conn.server.push(conn.incoming[0..conn.used]);
                std.mem.copyForwards(u8, &conn.incoming, conn.incoming[consumed..conn.used]);
                conn.used -= consumed;
                progressed = consumed != 0;
            }
            while (conn.server.retry()) |req| self.answer(host, conn, req, true);
            while (conn.server.next()) |req| self.answer(host, conn, req, false);
            if (conn.server.protocol.dead) return error.Closed;
            if (conn.server.output().len > 0) {
                if (try transport.write(conn.fd, conn.server.output())) |n| {
                    if (n == 0) return error.Closed;
                    conn.server.wrote(n);
                    progressed = true;
                }
            }
            if (conn.used < conn.incoming.len) {
                if (try transport.read(conn.fd, conn.incoming[conn.used..])) |n| {
                    if (n == 0) return error.Closed;
                    conn.used += n;
                    progressed = true;
                }
            }
            if (!progressed) break;
        }
    }

    /// Answers a request, or parks it: an open of screen.png asks for the
    /// next frame and waits for it, asked again (`retried`) each frame
    /// until the capture has landed.
    fn answer(self: *Control, host: *Host, conn: *Connection, req: fs.Req, retried: bool) void {
        var reply: fs.Reply = .{ .tag = req.tag };
        var buffer: [msize]u8 = undefined;
        if (!retried and req.op == .open and req.node == @backingInt(File.@"screen.png")) {
            self.capture_pending = true;
            self.capture_error = null;
        }
        const bytes = self.respond(host, conn, req, &reply, &buffer) catch |err| blk: {
            reply = if (err == error.CapturePending) .{ .tag = req.tag, .status = .again } else .{ .tag = req.tag, .status = .err, .errno = fs.E.INVAL, .ename = if (err == error.SketchNotRunning) self.offline.?.from else @errorName(err) };
            break :blk &.{};
        };
        conn.server.reply(&reply, bytes);
    }

    fn respond(self: *Control, host: *Host, conn: *Connection, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]const u8 {
        // Nodes from 2^63 are the sketch's: none is served but sketch/.
        if (req.node > @backingInt(File.sketch)) return error.UnknownFile;
        if (req.node & @as(u64, @bitCast(state_files.root)) != 0) return stateRespond(self, host, req, reply, buffer);
        const file = std.enums.fromInt(File, req.node) orelse return error.UnknownFile;
        if (self.offline != null and (req.op == .write or (req.op == .open or req.op == .read) and file != .README and file != .commands and file != .ctl and file != .@"/" and file != .sketch)) return error.SketchNotRunning;
        switch (req.op) {
            .lookup => {
                if (file == .sketch) return error.UnknownFile;
                if (file != .@"/") return error.NotDirectory;
                const found = std.meta.stringToEnum(File, req.data) orelse return error.UnknownFile;
                if (found == .@"/") return error.UnknownFile;
                reply.attr = self.attr(@backingInt(found));
            },
            .getattr => reply.attr = self.attr(req.node),
            .open => {
                if (file == .@"screen.png" or file == .@"profile-trace" or file == .@"timing-trace" or file == .@"presentation-trace" or file == .README or file == .commands) {
                    if (file == .@"screen.png") {
                        if (self.capture_pending) return error.CapturePending;
                        if (self.capture_error) |err| return err;
                        if (self.png.len == 0) return error.CaptureScreenshotFirst;
                    }
                    for (&conn.snapshots, 1..) |*slot, handle| if (slot.* == null) {
                        slot.* = switch (file) {
                            .@"screen.png" => try self.allocator.dupe(u8, self.png),
                            .@"profile-trace" => try self.trace(host),
                            .@"timing-trace" => try self.timingTrace(host),
                            .README, .commands => blk: {
                                var text: std.Io.Writer.Allocating = .init(self.allocator);
                                defer text.deinit();
                                const layout = if (self.offline) |o| o.layout else host.state.layout;
                                if (file == .README) try readme(layout, &text.writer) else try verbLines(&text.writer, "", if (self.offline) |o| o.completions else host.completions);
                                break :blk try text.toOwnedSlice();
                            },
                            else => try self.presentationTrace(host),
                        };
                        reply.handle = @intCast(handle);
                        return &.{};
                    };
                    return error.TooManySnapshots;
                }
            },
            .release => if (req.opened and req.handle > 0 and req.handle <= conn.snapshots.len) {
                const slot = &conn.snapshots[req.handle - 1];
                if (slot.*) |bytes| self.allocator.free(bytes);
                slot.* = null;
            },
            .readdir => {
                if (file == .sketch) return &.{};
                if (file != .@"/") return error.NotDirectory;
                var used: usize = 0;
                for (std.enums.values(File)[1..], 0..) |f, index| {
                    if (index < req.off) continue;
                    const name = @tagName(f);
                    std.mem.writeInt(u64, buffer[used..][0..8], @backingInt(f), .little);
                    buffer[used + 8] = @intFromBool(f == .state or f == .sketch);
                    buffer[used + 9] = @intCast(name.len);
                    @memcpy(buffer[used + 10 ..][0..name.len], name);
                    used += 10 + name.len;
                }
                return buffer[0..used];
            },
            .read => {
                var writer: std.Io.Writer = .fixed(buffer);
                const bytes: []const u8 = switch (file) {
                    .ctl => "Write a verb a line: commands lists them, README says what each does.\n",
                    .status => blk: {
                        try writer.print("name {s}\nsize {d} {d}\nmode {t}\ngpu {s}\nscreenshot_pending {}\nscreenshot_generation {d}\nscreenshot_error {s}\n", .{ host.name, host.canvas[0], host.canvas[1], host.timeline.mode, if (host.gpu != null) "yes" else "no", self.capture_pending, self.generation, if (self.capture_error) |err| @errorName(err) else "none" });
                        break :blk writer.buffered();
                    },
                    .log => blk: {
                        for (host.console.lines) |line| {
                            try writer.writeAll(line.bytes[0..line.len]);
                            try writer.writeByte('\n');
                        }
                        break :blk writer.buffered();
                    },
                    .@"screen.png", .@"profile-trace", .@"timing-trace", .@"presentation-trace", .README, .commands => if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle,
                    .profile => blk: {
                        const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled;
                        const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled;
                        try writer.print("# CPU wall milliseconds including GPU submission and fence wait; not hardware timestamps\n# frames {d}\nlabel\tcount\tmean_ms\tworst_ms\tp95_ms\tp99_ms\n", .{gpu.frame - profile.start_frame});
                        var entries = profile.entries.iterator();
                        while (entries.next()) |entry| {
                            const value = entry.value_ptr;
                            const percentiles = value.percentiles();
                            const count: f64 = @floatFromInt(@max(value.count, 1));
                            try writer.print("{s}\t{d}\t{d:.6}\t{d:.6}\t{d:.6}\t{d:.6}\n", .{ entry.key_ptr.*, value.count, @as(f64, @floatFromInt(value.total)) / count / std.time.ns_per_ms, @as(f64, @floatFromInt(value.worst)) / std.time.ns_per_ms, @as(f64, @floatFromInt(percentiles[0])) / std.time.ns_per_ms, @as(f64, @floatFromInt(percentiles[1])) / std.time.ns_per_ms });
                        }
                        break :blk writer.buffered();
                    },
                    .@"/", .state, .sketch => return error.NotFile,
                };
                return window(bytes, req.off, req.size);
            },
            .write => {
                if (file != .ctl) return error.ReadOnly;
                if (req.data.len > 4096 or std.mem.indexOfScalar(u8, req.data, 0) != null) return error.InvalidCommand;
                var lines = std.mem.tokenizeScalar(u8, req.data, '\n');
                while (lines.next()) |raw| {
                    const line = std.mem.trim(u8, raw, " \t\r");
                    const verb = std.meta.stringToEnum(Verb, line) orelse {
                        var words = std.mem.tokenizeAny(u8, line, " \t");
                        const input = std.meta.stringToEnum(script.Verb, words.next() orelse "");
                        if (input != null and script.verbs.get(input.?).input) {
                            try script.input(host, input.?, &words, c.SDL_GetTicksNS());
                        } else try host.runLine(line, c.SDL_GetTicksNS());
                        continue;
                    };
                    switch (verb) {
                        .screenshot => {
                            self.capture_pending = true;
                            self.capture_error = null;
                        },
                        .@"profile-reset" => {
                            const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled;
                            const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled;
                            for (profile.entries.values()) |*entry| entry.* = .{};
                            profile.start_frame = gpu.frame;
                        },
                    }
                }
                reply.written = @intCast(req.data.len);
            },
            .setattr => {
                if (file != .ctl or !req.truncate) return error.ReadOnly;
                reply.attr = self.attr(req.node);
            },
        }
        return &.{};
    }

    fn trace(self: *Control, host: *Host) ![]u8 {
        const gpu = if (host.passes) |*gpu| gpu else return error.ProfilingDisabled;
        const profile = if (gpu.profile) |*profile| profile else return error.ProfilingDisabled;
        const buffer = try self.allocator.alloc(u8, 256 << 10);
        defer self.allocator.free(buffer);
        var writer: std.Io.Writer = .fixed(buffer);
        try writer.writeAll("label,sample,ns\n");
        var entries = profile.entries.iterator();
        while (entries.next()) |entry| {
            const value = entry.value_ptr;
            for (0..value.retained()) |i| {
                try writer.writeByte('"');
                for (entry.key_ptr.*) |ch| {
                    if (ch == '"') try writer.writeByte('"');
                    try writer.writeByte(ch);
                }
                try writer.print("\",{d},{d}\n", .{ value.count - value.retained() + i + 1, value.sample(i) });
            }
        }
        return self.allocator.dupe(u8, writer.buffered());
    }

    fn timingTrace(self: *Control, host: *const Host) ![]u8 {
        var csv: std.ArrayList(u8) = .empty;
        errdefer csv.deinit(self.allocator);
        try csv.appendSlice(self.allocator, "index,frame_ns,work_ns,outside_work_ns\n");
        for (0..host.timing.count) |i| {
            const sample = host.timing.sampleAt(i);
            try csv.print(self.allocator, "{d},{d},{d},{d}\n", .{ i, sample.frame, sample.work, sample.frame -| sample.work });
        }
        return csv.toOwnedSlice(self.allocator);
    }

    fn presentationTrace(self: *Control, host: *const Host) ![]u8 {
        var csv: std.Io.Writer.Allocating = .init(self.allocator);
        defer csv.deinit();
        try Presentation.csv(host.presentation, &csv.writer);
        if (csv.written().len > 2 << 20) return error.TraceTooLarge;
        return csv.toOwnedSlice();
    }

    fn attr(self: *Control, node: u64) fs.Attr {
        const file: File = @fromBackingInt(@intCast(node));
        return .{ .name = @tagName(file), .node = node, .dir = file == .@"/" or file == .state or file == .sketch, .mode = files.get(file).mode, .size = if (file == .@"screen.png") self.png.len else 0, .version = if (file == .@"screen.png") @truncate(self.generation) else 0 };
    }

    pub fn capture(self: *Control, surface: *c.SDL_Surface) void {
        self.capture_pending = false;
        self.save(surface) catch |err| {
            self.capture_error = err;
        };
    }

    fn save(self: *Control, surface: *c.SDL_Surface) !void {
        const stream = c.SDL_IOFromDynamicMem() orelse return error.CaptureStream;
        defer _ = c.SDL_CloseIO(stream);
        if (!c.SDL_SavePNG_IO(surface, stream, false)) return error.EncodePng;
        const size = c.SDL_GetIOSize(stream);
        if (size <= 0) return error.EncodePng;
        const pointer = c.SDL_GetPointerProperty(c.SDL_GetIOProperties(stream), c.SDL_PROP_IOSTREAM_DYNAMIC_MEMORY_POINTER, null) orelse return error.EncodePng;
        const png = try self.allocator.dupe(u8, @as([*]const u8, @ptrCast(pointer))[0..@intCast(size)]);
        self.allocator.free(self.png);
        self.png = png;
        self.generation += 1;
    }
};

/// The README: a line a file, ctl's verbs indented under it and the
/// State's files under state/, in the shape cloud9's `help` reads.
fn readme(layout: @import("memory.zig").Layout, w: *std.Io.Writer) !void {
    for (std.enums.values(File)[1..]) |f| {
        const name = @tagName(f);
        const dir = f == .state or f == .sketch;
        try w.print("{s}{s}", .{ name, if (dir) "/" else "" });
        try w.splatByteAll(' ', @max(1, 41 -| (name.len + @intFromBool(dir))));
        try w.print("{s}\n", .{files.get(f).doc});
        if (f == .ctl) try verbLines(w, "    ", &.{});
        if (f == .state) try state_files.readme(layout, w);
    }
}

/// A line a verb ctl takes: ctl's own, the input verbs, the console's,
/// then `sketch`'s words.
fn verbLines(w: *std.Io.Writer, indent: []const u8, sketch: []const []const u8) !void {
    for (std.enums.values(Verb)) |v| try verbLine(w, indent, @tagName(v), "", verbs.get(v));
    for (std.enums.values(script.Verb)) |v| if (script.verbs.get(v).input) try verbLine(w, indent, @tagName(v), script.verbs.get(v).args, script.verbs.get(v).doc);
    for (std.enums.values(Console.Verb)) |v| try verbLine(w, indent, @tagName(v), Console.verbs.get(v).args, Console.verbs.get(v).doc);
    for (sketch) |word| try w.print("{s}{s}\n", .{ indent, word });
}

fn verbLine(w: *std.Io.Writer, indent: []const u8, name: []const u8, args: []const u8, doc: []const u8) !void {
    try w.print("{s}{s}{s}{s}", .{ indent, name, if (args.len > 0) " " else "", args });
    try w.splatByteAll(' ', @max(1, 37 -| (name.len + args.len + @intFromBool(args.len > 0))));
    try w.print("{s}\n", .{doc});
}

/// Under `state/`: the live State as files (state_files.zig), a write
/// run as the console's `set`.
fn stateRespond(self: *Control, host: *Host, req: fs.Req, reply: *fs.Reply, buffer: []u8) ![]const u8 {
    const layout = if (self.offline) |o| o.layout else host.state.layout;
    const node: state_files.Node = @bitCast(req.node);
    if (!state_files.valid(layout, node)) return error.StateLayoutChangedWalkAgain;
    const dir = state_files.isDir(layout, node);
    const mode: u16 = if (dir) 0o700 else if (state_files.writable(layout, node)) 0o600 else 0o400;
    switch (req.op) {
        .lookup => {
            if (!dir) return error.NotDirectory;
            const child = state_files.lookup(layout, node, req.data) orelse return error.UnknownField;
            const child_dir = state_files.isDir(layout, child);
            reply.attr = .{ .node = @bitCast(child), .dir = child_dir, .mode = if (child_dir) 0o700 else if (state_files.writable(layout, child)) 0o600 else 0o400 };
        },
        .getattr => reply.attr = .{ .node = req.node, .dir = dir, .mode = mode },
        .setattr => {
            if (mode != 0o600 or !req.truncate) return error.ReadOnly;
            reply.attr = .{ .node = req.node, .mode = mode };
        },
        .open, .release => {},
        .readdir => {
            if (!dir) return error.NotDirectory;
            return buffer[0..state_files.readdir(layout, node, req.off, buffer)];
        },
        .read => {
            if (dir) return error.NotFile;
            var w: std.Io.Writer = .fixed(buffer);
            state_files.read(layout, if (self.offline) |o| o.bytes else host.live(), node, &w) catch return error.ValueTooLong;
            return window(w.buffered(), req.off, req.size);
        },
        .write => {
            if (mode != 0o600) return error.ReadOnly;
            if (self.offline != null) return error.SketchNotRunning;
            var w: std.Io.Writer = .fixed(buffer);
            w.writeAll("set ") catch unreachable;
            state_files.path(layout, node, &w) catch return error.ValueTooLong;
            w.writeByte(' ') catch return error.ValueTooLong;
            for (std.mem.trim(u8, req.data, " \t\r\n")) |byte| w.writeByte(if (byte == '\n') ' ' else byte) catch return error.ValueTooLong;
            try host.runLine(w.buffered(), c.SDL_GetTicksNS());
            reply.written = @intCast(req.data.len);
        },
    }
    return &.{};
}

/// The State `fs` shows with no sketch running, and its words for what a
/// running one would answer.
pub const Offline = struct {
    layout: @import("memory.zig").Layout,
    bytes: []const u8,
    completions: []const []const u8,
    /// "drat-meout is not running: ..."
    from: []const u8,
};

/// `$XDG_RUNTIME_DIR/9p/sketchbook/<name>`, where a sketch posts its tree.
pub fn registered(environ: *const std.process.Environ.Map, name: []const u8, buf: []u8) ![:0]u8 {
    if (!c9.post.legalName(name)) return error.IllegalName;
    const runtime = environ.get("XDG_RUNTIME_DIR") orelse return error.NotRuntimeDir;
    return std.fmt.bufPrintSentinel(buf, "{s}/9p/sketchbook/{s}", .{ runtime, name }, 0) catch error.NameTooLong;
}

fn window(bytes: []const u8, offset: u64, count: u32) []const u8 {
    if (offset >= bytes.len) return &.{};
    const start: usize = @intCast(offset);
    return bytes[start..][0..@min(count, bytes.len - start)];
}

test "9P reads respect offsets, counts and EOF" {
    try std.testing.expectEqualStrings("cd", window("abcdef", 2, 2));
    try std.testing.expectEqualStrings("ef", window("abcdef", 4, 200));
    try std.testing.expectEqualStrings("", window("abcdef", std.math.maxInt(u64), 10));
}

test "control writes validate and screenshot opens pin an immutable snapshot" {
    const a = std.testing.allocator;
    var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 };
    var host: Host = undefined; // These backend operations do not access the host.
    var conn: Connection = .{};
    var reply: fs.Reply = .{ .tag = 1 };
    var buf: [256]u8 = undefined;
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .setattr, .node = 2, .truncate = true }, &reply, &buf);
    try std.testing.expectError(error.ReadOnly, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 3, .data = "screenshot" }, &reply, &buf));
    try std.testing.expectError(error.InvalidCommand, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "screenshot\x00" }, &reply, &buf));
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "screenshot\n" }, &reply, &buf);
    try std.testing.expect(control.capture_pending);
    try std.testing.expectError(error.CapturePending, control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 5 }, &reply, &buf));
    control.capture_pending = false;
    control.png = try a.dupe(u8, "first image");
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 5 }, &reply, &buf);
    const handle = reply.handle;
    a.free(control.png);
    control.png = try a.dupe(u8, "second image");
    defer a.free(control.png);
    const bytes = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 5, .handle = handle, .size = 100 }, &reply, &buf);
    try std.testing.expectEqualStrings("first image", bytes);
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 5, .handle = handle, .opened = true }, &reply, &buf);
    try std.testing.expect(conn.snapshots[handle - 1] == null);
}

test "control writes reset profiling counters while retaining labels" {
    const a = std.testing.allocator;
    var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 };
    var host: Host = undefined;
    host.passes = null;
    var conn: Connection = .{};
    var reply: fs.Reply = .{ .tag = 1 };
    var buf: [512]u8 = undefined;
    const reset: fs.Req = .{ .tag = 1, .op = .write, .node = 2, .data = "profile-reset\n" };
    try std.testing.expectError(error.ProfilingDisabled, control.respond(&host, &conn, reset, &reply, &buf));
    host.passes = @as(@import("gpu"), undefined);
    const gpu = &host.passes.?;
    gpu.profile = .init(a);
    defer gpu.profile.?.deinit();
    const profile = &gpu.profile.?;
    try profile.entries.put(profile.arena.allocator(), "scene", .{});
    profile.entries.values()[0].add(400_000);
    profile.entries.values()[0].add(600_000);
    gpu.frame = 420;
    const read: fs.Req = .{ .tag = 1, .op = .read, .node = 6, .size = buf.len };
    const before = try control.respond(&host, &conn, read, &reply, &buf);
    try std.testing.expect(std.mem.indexOf(u8, before, "scene\t2\t0.500000\t0.600000") != null);
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 7 }, &reply, &buf);
    const trace_handle = reply.handle;
    _ = try control.respond(&host, &conn, reset, &reply, &buf);
    const trace = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 7, .handle = trace_handle, .size = 100 }, &reply, &buf);
    try std.testing.expectEqualStrings("label,sample,ns\n\"scene\",1,400000\n\"scene\",2,600000\n", trace);
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 7, .handle = trace_handle, .opened = true }, &reply, &buf);
    try std.testing.expect(conn.snapshots[trace_handle - 1] == null);
    try std.testing.expectEqual(@as(usize, 1), profile.entries.count());
    try std.testing.expectEqual(@as(u64, 0), profile.entries.values()[0].total);
    try std.testing.expectEqual(@as(u64, 420), profile.start_frame);
    const after = try control.respond(&host, &conn, read, &reply, &buf);
    try std.testing.expect(std.mem.indexOf(u8, after, "# frames 0") != null);
    try std.testing.expect(std.mem.indexOf(u8, after, "scene\t0\t0.000000\t0.000000") != null);
}

test "control writes profiling ring retains latest samples and nearest rank percentiles" {
    var entry: @import("gpu").Profile.Entry = .{};
    for (1..4100) |ns| entry.add(ns);
    try std.testing.expectEqual(@as(u64, 4099), entry.count);
    try std.testing.expectEqual(@as(usize, 2048), entry.retained());
    try std.testing.expectEqual(@as(u64, 2052), entry.sample(0));
    try std.testing.expectEqual(@as(u64, 4099), entry.sample(2047));
    try std.testing.expectEqual([2]u64{ 3997, 4079 }, entry.percentiles());
    entry = .{};
    try std.testing.expectEqual(@as(usize, 0), entry.retained());
    try std.testing.expectEqual([2]u64{ 0, 0 }, entry.percentiles());
    entry.add(20);
    try std.testing.expectEqual([2]u64{ 20, 20 }, entry.percentiles());
}

test "control writes reject timing trace mutations and opens pin chronological samples" {
    const a = std.testing.allocator;
    var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 };
    var host: Host = undefined;
    host.timing = .{};
    for (0..@import("Timing.zig").capacity + 2) |i| host.timing.add(.{ .frame = i + 1, .work = i });
    var conn: Connection = .{};
    var reply: fs.Reply = .{ .tag = 1 };
    var buf: [256]u8 = undefined;
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .lookup, .node = 1, .data = "timing-trace" }, &reply, &buf);
    try std.testing.expectEqual(@as(u64, 8), reply.attr.node);
    try std.testing.expectEqual(@as(u16, 0o400), reply.attr.mode);
    try std.testing.expectError(error.ReadOnly, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 8, .data = "reset" }, &reply, &buf));
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 8 }, &reply, &buf);
    const first = reply.handle;
    host.timing = .{};
    host.timing.add(.{ .frame = 4, .work = 7 });
    const original = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 8, .handle = first, .size = 100 }, &reply, &buf);
    try std.testing.expect(std.mem.startsWith(u8, original, "index,frame_ns,work_ns,outside_work_ns\n0,3,2,1\n1,4,3,1\n"));
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 8 }, &reply, &buf);
    const second = reply.handle;
    const latest = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 8, .handle = second, .size = 100 }, &reply, &buf);
    try std.testing.expectEqualStrings("index,frame_ns,work_ns,outside_work_ns\n0,4,7,0\n", latest);
    for ([_]u32{ first, second }) |handle| {
        _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 8, .handle = handle, .opened = true }, &reply, &buf);
        try std.testing.expect(conn.snapshots[handle - 1] == null);
    }
}

test "control writes reject presentation trace mutations and opens own independent snapshots" {
    const a = std.testing.allocator;
    var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 };
    var host: Host = undefined;
    host.presentation = null;
    var conn: Connection = .{};
    var reply: fs.Reply = .{ .tag = 1 };
    var buf: [512]u8 = undefined;
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .lookup, .node = 1, .data = "presentation-trace" }, &reply, &buf);
    try std.testing.expectEqual(@as(u64, 9), reply.attr.node);
    try std.testing.expectEqual(@as(u16, 0o400), reply.attr.mode);
    try std.testing.expectError(error.ReadOnly, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 9, .data = "reset" }, &reply, &buf));
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 9 }, &reply, &buf);
    const first = reply.handle;
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = 9 }, &reply, &buf);
    const second = reply.handle;
    try std.testing.expect(conn.snapshots[first - 1].?.ptr != conn.snapshots[second - 1].?.ptr);
    const original = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 9, .handle = first, .size = 4096 }, &reply, &buf);
    try std.testing.expect(std.mem.startsWith(u8, original, "# status "));
    try std.testing.expect(std.mem.indexOf(u8, original, "disabled_or_allocation_failed") != null);
    try std.testing.expect(std.mem.endsWith(u8, original, "frame_id,sample_ms,commit_ns,result,presented_ns,refresh_ns,sequence,flags\n"));
    try std.testing.expect(std.mem.indexOfScalar(u8, original, 0) == null);
    const expected = try a.dupe(u8, original);
    defer a.free(expected);
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 9, .handle = first, .opened = true }, &reply, &buf);
    const retained = try control.respond(&host, &conn, .{ .tag = 1, .op = .read, .node = 9, .handle = second, .size = 4096 }, &reply, &buf);
    try std.testing.expectEqualStrings(expected, retained);
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = 9, .handle = second, .opened = true }, &reply, &buf);
    try std.testing.expect(conn.snapshots[first - 1] == null and conn.snapshots[second - 1] == null);
}

test "control writes take input verbs live, and the README and commands read the tables" {
    const a = std.testing.allocator;
    var control: Control = .{ .allocator = a, .path = undefined, .listener = -1 };
    var host: Host = undefined;
    host.gpa = a;
    host.console = .{};
    host.input = .{};
    host.pending = .empty;
    defer host.pending.deinit(a);
    const S = struct { scene: enum(u8) { room, street } = .room, talk: struct { text: [3]u8 = @splat(0) } = .{} };
    var arena: std.heap.ArenaAllocator = .init(a);
    defer arena.deinit();
    host.state.layout = try @import("memory.zig").Layout.copy(arena.allocator(), @import("abi").layout.of(S, .state));
    host.completions = &.{ "scene room", "scene street" };
    var conn: Connection = .{};
    var reply: fs.Reply = .{ .tag = 1 };
    var buf: [512]u8 = undefined;
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "click 10 20\nhold left_shift\n" }, &reply, &buf);
    try std.testing.expectEqual(@as(usize, 4), host.pending.items.len);
    try std.testing.expectEqual(abi.Event.Kind.mouse_up, host.pending.items[2].kind);
    try std.testing.expectEqual(@as(f32, 20), host.pending.items[2].y);
    try std.testing.expectEqual(abi.Event.Kind.key_down, host.pending.items[3].kind);
    try std.testing.expectError(error.ExpectedPoint, control.respond(&host, &conn, .{ .tag = 1, .op = .write, .node = 2, .data = "click 10" }, &reply, &buf));
    for ([_]File{ .README, .commands }) |f| {
        _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .open, .node = @backingInt(f) }, &reply, &buf);
        const handle = reply.handle;
        const text = conn.snapshots[handle - 1].?;
        if (f == .README) {
            try std.testing.expect(std.mem.startsWith(u8, text, "ctl                                      write a verb a line"));
            try std.testing.expect(std.mem.indexOf(u8, text, "\n    screenshot                           captures the next frame") != null);
            try std.testing.expect(std.mem.indexOf(u8, text, "\n    click X Y                            move there") != null);
            try std.testing.expect(std.mem.indexOf(u8, text, "\n    set FIELD VALUE...                   a field to a value") != null);
            try std.testing.expect(std.mem.indexOf(u8, text, "\nstate/                                   the sketch's State") != null);
            try std.testing.expect(std.mem.indexOf(u8, text, "\nsketch/                                  the sketch's own files") != null);
            try std.testing.expect(std.mem.endsWith(u8, text, "\nstate/scene                              .room .street\nstate/talk/text                          3 u8, blank-separated\n"));
        } else {
            try std.testing.expect(std.mem.startsWith(u8, text, "screenshot                           captures"));
            try std.testing.expect(std.mem.endsWith(u8, text, "\nscene room\nscene street\n"));
        }
        _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .release, .node = @backingInt(f), .handle = handle, .opened = true }, &reply, &buf);
    }
}

test "control writes leave the sketch's directory and nodes alone" {
    var control: Control = .{ .allocator = std.testing.allocator, .path = undefined, .listener = -1 };
    var host: Host = undefined;
    var conn: Connection = .{};
    var reply: fs.Reply = .{ .tag = 1 };
    var buf: [256]u8 = undefined;
    _ = try control.respond(&host, &conn, .{ .tag = 1, .op = .lookup, .node = 1, .data = "sketch" }, &reply, &buf);
    try std.testing.expect(reply.attr.dir and reply.attr.node == 1 << 63);
    try std.testing.expectEqual(@as(usize, 0), (try control.respond(&host, &conn, .{ .tag = 1, .op = .readdir, .node = 1 << 63 }, &reply, &buf)).len);
    try std.testing.expectError(error.UnknownFile, control.respond(&host, &conn, .{ .tag = 1, .op = .lookup, .node = 1 << 63, .data = "buffer" }, &reply, &buf));
    for ([_]u64{ (1 << 63) + 1, (1 << 63) | (1 << 62), std.math.maxInt(u64) }) |node| try std.testing.expectError(error.UnknownFile, control.respond(&host, &conn, .{ .tag = 1, .op = .getattr, .node = node }, &reply, &buf));
}