summaryrefslogtreecommitdiff
path: root/src/host/control.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/host/control.zig')
-rw-r--r--src/host/control.zig339
1 files changed, 296 insertions, 43 deletions
diff --git a/src/host/control.zig b/src/host/control.zig
index 8cc8296..943316c 100644
--- a/src/host/control.zig
+++ b/src/host/control.zig
@@ -2,17 +2,45 @@
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 });
+const Server = fs.Server(Backend, .{ .fid_capacity = 32, .slot_capacity = 4, .name_capacity = 64 });
const msize = 16384;
-const names = [_][]const u8{ "/", "ctl", "status", "log", "screen.png", "profile", "profile-trace", "timing-trace", "presentation-trace" };
+/// 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,
@@ -38,6 +66,9 @@ 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,
@@ -60,6 +91,36 @@ pub const Control = struct {
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);
@@ -97,7 +158,8 @@ pub const Control = struct {
conn.used -= consumed;
progressed = consumed != 0;
}
- while (conn.server.next()) |req| self.answer(host, conn, req);
+ 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| {
@@ -117,42 +179,58 @@ pub const Control = struct {
}
}
- fn answer(self: *Control, host: *Host, conn: *Connection, req: fs.Req) void {
+ /// 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 = .{ .tag = req.tag, .status = .err, .errno = fs.E.INVAL, .ename = @errorName(err) };
+ 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 {
- if (req.node < 1 or req.node > names.len) return error.UnknownFile;
+ // 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, conn, 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 (req.node != 1) return error.NotDirectory;
- for (names[1..], 2..) |name, node| if (std.mem.eql(u8, name, req.data)) {
- reply.attr = self.attr(node);
- return &.{};
- };
- return error.UnknownFile;
+ 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 (req.node == 5 or req.node == 7 or req.node == 8 or req.node == 9) {
- if (req.node == 5) {
+ 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 (req.node) {
- 5 => try self.allocator.dupe(u8, self.png),
- 7 => try self.trace(host),
- 8 => try self.timingTrace(host),
- 9 => try self.presentationTrace(host),
- else => unreachable,
+ 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 &.{};
@@ -166,12 +244,14 @@ pub const Control = struct {
slot.* = null;
},
.readdir => {
- if (req.node != 1) return error.NotDirectory;
+ if (file == .sketch) return &.{};
+ if (file != .@"/") return error.NotDirectory;
var used: usize = 0;
- for (names[1..], 0..) |name, index| {
+ for (std.enums.values(File)[1..], 0..) |f, index| {
if (index < req.off) continue;
- std.mem.writeInt(u64, buffer[used..][0..8], index + 2, .little);
- buffer[used + 8] = 0;
+ 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;
@@ -180,21 +260,21 @@ pub const Control = struct {
},
.read => {
var writer: std.Io.Writer = .fixed(buffer);
- const bytes: []const u8 = switch (req.node) {
- 2 => "Write one console command per line. screenshot captures the next frame.\n",
- 3 => blk: {
+ 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();
},
- 4 => blk: {
+ .log => blk: {
for (host.console.lines) |line| {
try writer.writeAll(line.bytes[0..line.len]);
try writer.writeByte('\n');
}
break :blk writer.buffered();
},
- 5, 7, 8, 9 => if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle,
- 6 => blk: {
+ .@"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});
@@ -207,30 +287,41 @@ pub const Control = struct {
}
break :blk writer.buffered();
},
- else => return error.NotFile,
+ .@"/", .state, .sketch => return error.NotFile,
};
return window(bytes, req.off, req.size);
},
.write => {
- if (req.node != 2) return error.ReadOnly;
+ 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");
- if (std.mem.eql(u8, line, "screenshot")) {
- self.capture_pending = true;
- self.capture_error = null;
- } else if (std.mem.eql(u8, line, "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;
- } else try host.runLine(line, c.SDL_GetTicksNS());
+ 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 (req.node != 2 or !req.truncate) return error.ReadOnly;
+ if (file != .ctl or !req.truncate) return error.ReadOnly;
reply.attr = self.attr(req.node);
},
}
@@ -279,7 +370,8 @@ pub const Control = struct {
}
fn attr(self: *Control, node: u64) fs.Attr {
- return .{ .name = names[@intCast(node - 1)], .node = node, .dir = node == 1, .mode = if (node == 1) 0o700 else if (node == 2) 0o600 else 0o400, .size = if (node == 5) self.png.len else 0, .version = if (node == 5) @truncate(self.generation) else 0 };
+ 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 {
@@ -303,6 +395,111 @@ pub const Control = struct {
}
};
+/// 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, conn: *Connection, 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 };
+ },
+ // A value is read as it was at the open: it changes every frame,
+ // and its length with it.
+ .open => if (!dir) for (&conn.snapshots, 1..) |*slot, handle| if (slot.* == null) {
+ var text: std.Io.Writer.Allocating = .init(self.allocator);
+ defer text.deinit();
+ try state_files.read(layout, if (self.offline) |o| o.bytes else host.live(), node, &text.writer);
+ slot.* = try text.toOwnedSlice();
+ reply.handle = @intCast(handle);
+ break;
+ } else 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 (!dir) return error.NotDirectory;
+ return buffer[0..state_files.readdir(layout, node, req.off, buffer)];
+ },
+ .read => {
+ if (dir) return error.NotFile;
+ const bytes = if (req.handle > 0 and req.handle <= conn.snapshots.len) conn.snapshots[req.handle - 1] orelse return error.InvalidHandle else return error.InvalidHandle;
+ return window(bytes, 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);
@@ -452,3 +649,59 @@ test "control writes reject presentation trace mutations and opens own independe
_ = 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));
+}