From cf347f91ee838759dc44ed34ec6ff320186e90ce Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 01:44:36 -0300 Subject: One verb table: the flags, the console's, the script's and ctl's words are rows Six hand-kept lists said one vocabulary: root.zig's parser, its usage and its header; the console's completion list, its help strings and the execute chain; Host.zig's list of lines that do not move State; the script's header comment and its step chain; control.zig's names and its magic node numbers. Now each is a table, and the parser, the help, the completion and the dispatch read it. - root.zig: `Flag`, an enum, and `flags`, a row each (arg, doc): the loop looks the word up, takes its argument when the row names one, and a switch sets what it means; `usage` is made from the rows at compile time (the same text, and a line for --help). Errors say the flag and what it needs. - Console.zig: `Verb` and `verbs`, a row each (args, doc, moves_state): execute is a switch on the verb, a line whose first word is none goes to the sketch as before; Tab completes from the rows (a verb, and with each lowercase word its first argument may be: `seek start`); `help` prints the rows wrapped to the log's width, `help VERB` its line. - Host.zig: movesState asks the row; a sketch's command moves State. - script.zig: `Verb` and `verbs` (args, doc, frame, input): step is a switch, a row with `frame` is followed by one; the input verbs are `input`, which a 9P ctl will call live. - control.zig: `File` and `files` (mode, doc), a node being its number (the same numbers); `Verb` and `verbs` for ctl's own two words. Behaviour is unchanged but for help's text, completion's list (the same words, and `timing`, `play`, `seek`... alone) and errors' words. The diff adds more than it deletes (+630 -521): the rows carry a line of doc for every verb, which nothing had before. Tests: test-control, test-timing, test-setup, test-same, test-kill, test-past, test-import, test-paths: 70/70 steps, 29/29 tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- src/host/Console.zig | 403 +++++++++++++++++++++++++------------------ src/host/Host.zig | 9 +- src/host/control.zig | 100 +++++++---- src/host/root.zig | 164 +++++++++--------- src/host/script.zig | 474 ++++++++++++++++++++++++++------------------------- 5 files changed, 631 insertions(+), 519 deletions(-) (limited to 'src') diff --git a/src/host/Console.zig b/src/host/Console.zig index 0d4cda0..3046132 100644 --- a/src/host/Console.zig +++ b/src/host/Console.zig @@ -11,13 +11,63 @@ const Sessions = @import("Sessions.zig"); pub const panel_height = 144; pub const Key = enum { left, right, home, end, backspace, delete, clear, tab, submit }; -const Line = struct { bytes: [118]u8 = @splat(0), len: usize = 0 }; +const Line = struct { + bytes: [width]u8 = @splat(0), + len: usize = 0, + const width = 118; +}; -const host_commands = [_][]const u8{ - "help", "overlay memory", "overlay sound", "get", "set", "reset", "save", "load", "snapshot", "recording", "marks", "clips", "play session", - "record", "stop", "play", "pause", "step", "seek start", "seek end", "diff", "quit", "exit", - "overlay timing", "sessions", "timing on", "timing off", "timing frame", "timing work", "timing reset", "timing stats", - "export-session", "import", +/// The console's words, a row each: what `help` prints, Tab completes, +/// `execute` runs (its switch) and `Host.runLine` asks `moves_state` of. +/// A line whose first word is none of them goes to the sketch. +pub const Verb = enum { help, get, set, reset, save, load, diff, snapshot, marks, record, recording, clips, play, stop, pause, step, seek, sessions, @"export-session", import, overlay, timing, quit, exit }; +pub const Row = struct { + args: []const u8 = "", + doc: []const u8, + /// May change State other than through `update`: a jump. + moves_state: bool = false, +}; +pub const verbs = std.enums.EnumArray(Verb, Row).init(.{ + .help = .{ .args = "[VERB]", .doc = "the verbs, or what one does; then the sketch's help" }, + .get = .{ .args = "FIELD", .doc = "a State field's value (`pos[0]`, `boids.buffer[3]`); a vector, array or struct shows every value in it, in memory order" }, + .set = .{ .args = "FIELD VALUE...", .doc = "a field to a value (enums by name or number), or an array of numbers to all its values, in memory order", .moves_state = true }, + .reset = .{ .doc = "State to its defaults, then the sketch's init; marks are kept", .moves_state = true }, + .save = .{ .args = "[MARK]", .doc = "marks the State now, MARK or the snapshot one" }, + .load = .{ .args = "[MARK|#K]", .doc = "brings a mark back (#K: the K-th in marks), migrated to today's layout", .moves_state = true }, + .diff = .{ .args = "[MARK]", .doc = "live State against a mark, leaf by leaf" }, + .snapshot = .{ .args = "MARK", .doc = "the mark save, load, diff and record use when given none" }, + .marks = .{ .doc = "the last marks" }, + .record = .{ .args = "[CLIP]", .doc = "starts a clip from the snapshot mark (saved first if new, else restored)", .moves_state = true }, + .recording = .{ .args = "CLIP", .doc = "the clip record, play, seek and step use when given none" }, + .clips = .{ .doc = "the last clips" }, + .play = .{ .args = "session S [at SECONDS] | [CLIP]", .doc = "replays a past session (paused at SECONDS), or a clip", .moves_state = true }, + .stop = .{ .doc = "ends the clip being recorded or played: live from here" }, + .pause = .{ .doc = "pauses or resumes a replay" }, + .step = .{ .args = "N", .doc = "N frames on (or back) in the replay", .moves_state = true }, + .seek = .{ .args = "start|end|MS", .doc = "to a place in the replay", .moves_state = true }, + .sessions = .{ .doc = "where this run records, and the last sessions" }, + .@"export-session" = .{ .args = "[S] FILE", .doc = "session S (this run's) with its marks and clips, to a database of its own" }, + .import = .{ .args = "FILE", .doc = "the sessions of such a file, its marks and clips as NAME@" }, + .overlay = .{ .args = "memory|sound|timing", .doc = "shows or hides an overlay" }, + .timing = .{ .args = "[on|off|frame|work|reset|stats]", .doc = "the frame timing graph: shown, its metric, cleared, or its numbers" }, + .quit = .{ .doc = "ends the run" }, + .exit = .{ .doc = "ends the run" }, +}); + +/// What Tab completes from: every verb, and with each of the words its +/// first argument may be (`seek start`). +const completions = blk: { + @setEvalBranchQuota(100_000); + var list: []const []const u8 = &.{}; + for (std.enums.values(Verb)) |v| { + list = list ++ .{@tagName(v)}; + const args = verbs.get(v).args; + var words = std.mem.tokenizeScalar(u8, std.mem.trim(u8, args[0 .. std.mem.indexOfScalar(u8, args, ' ') orelse args.len], "[]"), '|'); + while (words.next()) |word| if (std.ascii.isLower(word[0])) { + list = list ++ .{@tagName(v) ++ " " ++ word}; + }; + } + break :blk list; }; visible: bool = false, @@ -110,7 +160,7 @@ fn complete(self: *Console, extra: []const []const u8) void { var matches: [256]u8 = undefined; var used: usize = 0; var count: usize = 0; - for ([_][]const []const u8{ &host_commands, extra }) |list| for (list) |candidate| { + for ([_][]const []const u8{ completions, extra }) |list| for (list) |candidate| { if (!std.mem.startsWith(u8, candidate, self.text())) continue; if (first) |previous| { var i: usize = 0; @@ -156,160 +206,7 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const const command = words.next() orelse return &.{}; const arg = words.next(); const rest = words.rest(); - - if (eq(command, "help")) { - self.log("save|load|diff [MARK] snapshot MARK marks | record|play [CLIP] recording CLIP clips | stop | pause"); - self.log("step N (frames) | seek start|end| | sessions | play session S [at SECS] | export-session [S] FILE | import FILE"); - self.log("reset | get|set [] | overlay memory|sound | quit"); - self.log("timing [on|off|frame|work|reset|stats] | overlay timing"); - if (host.forward(self, line, now) == .unknown) self.log("Backtick hides the console. Tab completes."); - return &.{}; - } - if (eq(command, "overlay")) { - const name = arg orelse return error.ExpectedOverlay; - if (rest.len != 0) return error.UnexpectedArgument; - const flag = if (eq(name, "memory")) &self.overlay_memory else if (eq(name, "sound")) &self.overlay_sound else if (eq(name, "timing")) &host.timing.visible else return error.UnknownOverlay; - flag.* = !flag.*; - host.timing.dirty = true; - self.print("{s} overlay: {s}", .{ name, if (flag.*) "on" else "off" }); - } else if (eq(command, "timing")) { - if (rest.len != 0) return error.UnexpectedArgument; - if (eq(arg orelse "", "stats")) { - self.print("Timing: last {d}/240 frames; frame includes present, work excludes present (wall clock).", .{host.timing.count}); - inline for (.{ .frame, .work }) |metric| { - const s = host.timing.stats(metric); - self.print("{s}: avg {d:.3} ms | p90 {d:.3} ms | p99 {d:.3} ms | max {d:.3} ms", .{ @tagName(metric), s.mean, s.p90, s.p99, s.max }); - } - } else { - try host.timing.command(arg); - self.print("Timing overlay: {s}, graph: {t}, samples: {d}", .{ if (host.timing.visible) "on" else "off", host.timing.metric, host.timing.count }); - } - } else if (eq(command, "get")) { - const path = arg orelse return error.ExpectedField; - var buf: [160]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) { - error.UnknownField => return error.UnknownField, - error.WriteFailed => {}, // shown cut off - }; - self.print("{s} = {s}", .{ path, w.buffered() }); - } else if (eq(command, "set")) { - const path = arg orelse return error.ExpectedField; - const leaf = host.state.layout.find(path) orelse return error.UnknownField; - if (rest.len == 0) return error.ExpectedValue; - try stop(host); - try fields.set(leaf, host.live(), std.mem.trim(u8, rest, " ")); - self.print("{s} = {s}", .{ path, std.mem.trim(u8, rest, " ") }); - } else if (eq(command, "quit") or eq(command, "exit")) { - try stop(host); - host.quit = true; - } else if (eq(command, "reset")) { - try stop(host); - host.resetState(); - self.log("Live state reset. Snapshots are kept."); - } else if (eq(command, "snapshot") or eq(command, "recording")) { - const n = try nameOr(arg orelse return error.ExpectedName, &self.snapshot); - (if (eq(command, "snapshot")) &self.snapshot else &self.recording).* = .of(n); - } else if (eq(command, "save")) { - const n = try nameOr(arg, &self.snapshot); - try stop(host); - _ = try host.sessions.mark(n, .mark, host.live()); - self.print("Saved snapshot {s}.", .{n}); - } else if (eq(command, "load")) { - const n = try nameOr(arg, &self.snapshot); - const key = try loadMark(host, n); - defer key.free(host.gpa); - try stop(host); - try h.restore(key); - self.print("Loaded snapshot {s}.", .{n}); - } else if (eq(command, "record")) { - const n = try nameOr(arg, &self.recording); - const from = self.snapshot.get(); - try stop(host); - // An unused mark captures the current state; an existing one is - // restored, so several clips can branch from exactly those bytes. - const k = if (try host.sessions.findMark(from) == null) try host.sessions.mark(from, .mark, host.live()) else blk: { - const key = try loadMark(host, from); - defer key.free(host.gpa); - try h.restore(key); - break :blk try host.sessions.keyframe(.jump, host.live()); - }; - // The input held now is restored first in the clip (Host.restoredInput). - h.restored = true; - try host.sessions.startClip(n, k); - h.startRecording(); - self.recording = .of(n); - self.print("Started recording {s} from snapshot {s}.", .{ n, from }); - } else if (eq(command, "play") and arg != null and eq(arg.?, "session")) { - var more = std.mem.tokenizeAny(u8, rest, " \t"); - const index = std.fmt.parseInt(u64, more.next() orelse return error.ExpectedSession, 10) catch return error.InvalidSession; - var at: ?u64 = null; - if (more.next()) |word| { - if (!eq(word, "at")) return error.UnexpectedArgument; - const seconds = std.fmt.parseFloat(f64, more.next() orelse return error.ExpectedPosition) catch return error.InvalidPosition; - at = @intFromFloat(@max(0, seconds) * std.time.ns_per_s); - } - try stop(host); - return self.playSession(host, index, at, now); - } else if (eq(command, "play")) { - const n = try nameOr(arg, &self.recording); - try stop(host); - try loadClip(host, n); - try h.play(now); - self.recording = .of(n); - self.print("Playing recording {s}.", .{n}); - self.warnBuild(host); - } else if (eq(command, "stop")) { - try stop(host); - } else if (eq(command, "pause")) { - if (h.mode != .playing and h.mode != .paused) return error.NotReplaying; - h.pause(now); - } else if (eq(command, "step") or eq(command, "seek")) { - const value = arg orelse return error.ExpectedPosition; - if (h.mode == .live or h.mode == .recording) { - try stop(host); - try loadClip(host, self.recording.get()); - try h.play(now); - self.warnBuild(host); - } - if (eq(command, "step")) return h.step(std.fmt.parseInt(i64, value, 10) catch return error.InvalidPosition); - if (eq(value, "start")) return h.seekCount(0); - if (eq(value, "end")) return h.seekCount(h.events.items.len); - const ms = std.fmt.parseInt(u64, value, 10) catch return error.InvalidPosition; - return h.seekTime(ms *| std.time.ns_per_ms); - } else if (eq(command, "diff")) { - const n = try nameOr(arg, &self.snapshot); - var arena: std.heap.ArenaAllocator = .init(host.gpa); - defer arena.deinit(); - const saved = try markState(host, arena.allocator(), n); - const diff = memory.compareKept(saved.layout, host.state.layout, host.live(), saved.bytes); - if (diff.first) |first| { - var buf: [96]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - first.leaf.name(first.offset, &w) catch {}; - self.print("Live vs snapshot {s}: {d} differing values, first {s}", .{ n, diff.count, w.buffered() }); - } else self.print("Live vs snapshot {s}: same", .{n}); - } else if (eq(command, "sessions")) { - if (arg != null) return error.UnexpectedArgument; - try self.listSessions(host); - } else if (eq(command, "export-session")) { - const s = &host.sessions; - const first = arg orelse return error.ExpectedFile; - const index = if (rest.len == 0) s.session else std.fmt.parseInt(u64, first, 10) catch return error.InvalidSession; - const path = if (rest.len == 0) first else std.mem.trim(u8, rest, " \t"); - try s.exportSession(index, path); - self.print("Exported session {d} to {s}.", .{ index, path }); - } else if (eq(command, "import")) { - const path = arg orelse return error.ExpectedFile; - if (rest.len != 0) return error.UnexpectedArgument; - const s = &host.sessions; - const first = try s.import(path); - const n = try s.count(.sessions); - self.print("Imported {s} as session {d}..{d}; marks and clips are NAME@{s}.", .{ path, first, n - 1, std.fs.path.basename(path) }); - } else if (eq(command, "marks") or eq(command, "clips")) { - if (arg != null) return error.UnexpectedArgument; - try self.listNamed(host, eq(command, "marks")); - } else { + const verb = std.meta.stringToEnum(Verb, command) orelse { // Sketch commands edit state outside the recorded input. try stop(host); switch (host.forward(self, line, now)) { @@ -317,6 +214,189 @@ pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const .failed => return error.CommandFailed, .done => {}, } + return &.{}; + }; + switch (verb) { + .help => { + if (std.meta.stringToEnum(Verb, arg orelse "")) |v| { + self.print("{t} {s}: {s}", .{ v, verbs.get(v).args, verbs.get(v).doc }); + return &.{}; + } + var buf: [Line.width + 3]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + for (std.enums.values(Verb)) |v| { + if (w.end + @tagName(v).len + verbs.get(v).args.len + 3 > Line.width) { + self.log(w.buffered()); + w.end = 0; + } + w.print("{s}{t}{s}{s}", .{ if (w.end == 0) "" else " | ", v, if (verbs.get(v).args.len == 0) "" else " ", verbs.get(v).args }) catch {}; + } + self.log(w.buffered()); + if (host.forward(self, line, now) == .unknown) self.log("help VERB says what one does. Backtick hides the console. Tab completes."); + }, + .overlay => { + const name = arg orelse return error.ExpectedOverlay; + if (rest.len != 0) return error.UnexpectedArgument; + const flag = if (eq(name, "memory")) &self.overlay_memory else if (eq(name, "sound")) &self.overlay_sound else if (eq(name, "timing")) &host.timing.visible else return error.UnknownOverlay; + flag.* = !flag.*; + host.timing.dirty = true; + self.print("{s} overlay: {s}", .{ name, if (flag.*) "on" else "off" }); + }, + .timing => { + if (rest.len != 0) return error.UnexpectedArgument; + if (eq(arg orelse "", "stats")) { + self.print("Timing: last {d}/240 frames; frame includes present, work excludes present (wall clock).", .{host.timing.count}); + inline for (.{ .frame, .work }) |metric| { + const s = host.timing.stats(metric); + self.print("{s}: avg {d:.3} ms | p90 {d:.3} ms | p99 {d:.3} ms | max {d:.3} ms", .{ @tagName(metric), s.mean, s.p90, s.p99, s.max }); + } + } else { + try host.timing.command(arg); + self.print("Timing overlay: {s}, graph: {t}, samples: {d}", .{ if (host.timing.visible) "on" else "off", host.timing.metric, host.timing.count }); + } + }, + .get => { + const path = arg orelse return error.ExpectedField; + var buf: [160]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) { + error.UnknownField => return error.UnknownField, + error.WriteFailed => {}, // shown cut off + }; + self.print("{s} = {s}", .{ path, w.buffered() }); + }, + .set => { + const path = arg orelse return error.ExpectedField; + const leaf = host.state.layout.find(path) orelse return error.UnknownField; + if (rest.len == 0) return error.ExpectedValue; + try stop(host); + try fields.set(leaf, host.live(), std.mem.trim(u8, rest, " ")); + self.print("{s} = {s}", .{ path, std.mem.trim(u8, rest, " ") }); + }, + .quit, .exit => { + try stop(host); + host.quit = true; + }, + .reset => { + try stop(host); + host.resetState(); + self.log("Live state reset. Snapshots are kept."); + }, + .snapshot, .recording => { + const n = try nameOr(arg orelse return error.ExpectedName, &self.snapshot); + (if (verb == .snapshot) &self.snapshot else &self.recording).* = .of(n); + }, + .save => { + const n = try nameOr(arg, &self.snapshot); + try stop(host); + _ = try host.sessions.mark(n, .mark, host.live()); + self.print("Saved snapshot {s}.", .{n}); + }, + .load => { + const n = try nameOr(arg, &self.snapshot); + const key = try loadMark(host, n); + defer key.free(host.gpa); + try stop(host); + try h.restore(key); + self.print("Loaded snapshot {s}.", .{n}); + }, + .record => { + const n = try nameOr(arg, &self.recording); + const from = self.snapshot.get(); + try stop(host); + // An unused mark captures the current state; an existing one is + // restored, so several clips can branch from exactly those bytes. + const k = if (try host.sessions.findMark(from) == null) try host.sessions.mark(from, .mark, host.live()) else blk: { + const key = try loadMark(host, from); + defer key.free(host.gpa); + try h.restore(key); + break :blk try host.sessions.keyframe(.jump, host.live()); + }; + // The input held now is restored first in the clip (Host.restoredInput). + h.restored = true; + try host.sessions.startClip(n, k); + h.startRecording(); + self.recording = .of(n); + self.print("Started recording {s} from snapshot {s}.", .{ n, from }); + }, + .play => if (arg != null and eq(arg.?, "session")) { + var more = std.mem.tokenizeAny(u8, rest, " \t"); + const index = std.fmt.parseInt(u64, more.next() orelse return error.ExpectedSession, 10) catch return error.InvalidSession; + var at: ?u64 = null; + if (more.next()) |word| { + if (!eq(word, "at")) return error.UnexpectedArgument; + const seconds = std.fmt.parseFloat(f64, more.next() orelse return error.ExpectedPosition) catch return error.InvalidPosition; + at = @intFromFloat(@max(0, seconds) * std.time.ns_per_s); + } + try stop(host); + return self.playSession(host, index, at, now); + } else { + const n = try nameOr(arg, &self.recording); + try stop(host); + try loadClip(host, n); + try h.play(now); + self.recording = .of(n); + self.print("Playing recording {s}.", .{n}); + self.warnBuild(host); + }, + .stop => { + try stop(host); + }, + .pause => { + if (h.mode != .playing and h.mode != .paused) return error.NotReplaying; + h.pause(now); + }, + .step, .seek => { + const value = arg orelse return error.ExpectedPosition; + if (h.mode == .live or h.mode == .recording) { + try stop(host); + try loadClip(host, self.recording.get()); + try h.play(now); + self.warnBuild(host); + } + if (verb == .step) return h.step(std.fmt.parseInt(i64, value, 10) catch return error.InvalidPosition); + if (eq(value, "start")) return h.seekCount(0); + if (eq(value, "end")) return h.seekCount(h.events.items.len); + const ms = std.fmt.parseInt(u64, value, 10) catch return error.InvalidPosition; + return h.seekTime(ms *| std.time.ns_per_ms); + }, + .diff => { + const n = try nameOr(arg, &self.snapshot); + var arena: std.heap.ArenaAllocator = .init(host.gpa); + defer arena.deinit(); + const saved = try markState(host, arena.allocator(), n); + const diff = memory.compareKept(saved.layout, host.state.layout, host.live(), saved.bytes); + if (diff.first) |first| { + var buf: [96]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + first.leaf.name(first.offset, &w) catch {}; + self.print("Live vs snapshot {s}: {d} differing values, first {s}", .{ n, diff.count, w.buffered() }); + } else self.print("Live vs snapshot {s}: same", .{n}); + }, + .sessions => { + if (arg != null) return error.UnexpectedArgument; + try self.listSessions(host); + }, + .@"export-session" => { + const s = &host.sessions; + const first = arg orelse return error.ExpectedFile; + const index = if (rest.len == 0) s.session else std.fmt.parseInt(u64, first, 10) catch return error.InvalidSession; + const path = if (rest.len == 0) first else std.mem.trim(u8, rest, " \t"); + try s.exportSession(index, path); + self.print("Exported session {d} to {s}.", .{ index, path }); + }, + .import => { + const path = arg orelse return error.ExpectedFile; + if (rest.len != 0) return error.UnexpectedArgument; + const s = &host.sessions; + const first = try s.import(path); + const n = try s.count(.sessions); + self.print("Imported {s} as session {d}..{d}; marks and clips are NAME@{s}.", .{ path, first, n - 1, std.fs.path.basename(path) }); + }, + .marks, .clips => { + if (arg != null) return error.UnexpectedArgument; + try self.listNamed(host, verb == .marks); + }, } return &.{}; } @@ -473,7 +553,6 @@ fn eq(a: []const u8, b: []const u8) bool { return std.mem.eql(u8, a, b); } - test "line editing, completion and submission" { var c: Console = .{}; c.insert("scen"); diff --git a/src/host/Host.zig b/src/host/Host.zig index 002c704..93c47c1 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -727,13 +727,12 @@ pub fn runLine(self: *Host, line: []const u8, now: u64) !void { } /// Whether a console line that succeeded may have changed State other than -/// through `update` (restoring a snapshot is caught apart from this). +/// through `update` (restoring a snapshot is caught apart from this): a +/// sketch's command may. fn movesState(line: []const u8) bool { var words = std.mem.tokenizeAny(u8, line, " \t"); - const verb = words.next() orelse return false; - const still = [_][]const u8{ "help", "overlay", "timing", "get", "snapshot", "recording", "diff", "stop", "pause", "save", "quit", "exit", "sessions", "marks", "clips", "export-session", "import" }; - for (still) |w| if (std.mem.eql(u8, verb, w)) return false; - return true; + const verb = std.meta.stringToEnum(Console.Verb, words.next() orelse return false) orelse return true; + return Console.verbs.get(verb).moves_state; } /// Offers a line to the sketch. diff --git a/src/host/control.zig b/src/host/control.zig index 8cc8296..33b186b 100644 --- a/src/host/control.zig +++ b/src/host/control.zig @@ -12,7 +12,27 @@ const Backend = struct { }; const Server = fs.Server(Backend, .{ .fid_capacity = 32, .slot_capacity = 4 }); 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" }; +const files = std.enums.EnumArray(File, struct { mode: u16 = 0o400, doc: []const u8 }).init(.{ + .@"/" = .{ .mode = 0o700, .doc = "" }, + .ctl = .{ .mode = 0o600, .doc = "write console lines, a line each; screenshot captures the next frame, profile-reset clears profile" }, + .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 frame screenshot captured, as PNG; each open 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" }, +}); + +/// 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 for screen.png", + .@"profile-reset" = "clears profile's counters and frame count, keeping its labels", +}); const Connection = struct { fd: c_int = -1, @@ -128,31 +148,28 @@ pub const Control = struct { } 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; + const file = std.enums.fromInt(File, req.node) orelse return error.UnknownFile; 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 != .@"/") 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") { + 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), + else => try self.presentationTrace(host), }; reply.handle = @intCast(handle); return &.{}; @@ -166,10 +183,11 @@ pub const Control = struct { slot.* = null; }, .readdir => { - if (req.node != 1) return error.NotDirectory; + 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; + const name = @tagName(f); std.mem.writeInt(u64, buffer[used..][0..8], index + 2, .little); buffer[used + 8] = 0; buffer[used + 9] = @intCast(name.len); @@ -180,21 +198,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 one console command per line. screenshot captures the next frame.\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" => 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 +225,37 @@ pub const Control = struct { } break :blk writer.buffered(); }, - else => return error.NotFile, + .@"/" => 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 { + 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 +304,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 == .@"/", .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 { diff --git a/src/host/root.zig b/src/host/root.zig index 9c7ad77..42362d3 100644 --- a/src/host/root.zig +++ b/src/host/root.zig @@ -1,21 +1,6 @@ //! The sketchbook host: runs a sketch linked in, or loaded from a library -//! that it hot-reloads whenever a build replaces it. -//! -//! sketchbook [options] [LIBRARY] -//! --state FILE the save (default: $XDG_DATA_HOME//.xitdb; -//! sketch.xitdb for a script or an export) -//! --headless offscreen video, silent audio -//! --script FILE play a script instead of reading devices -//! --fresh start from default state (the save's history is kept) -//! --timing-marker encode frame ID and draw sample time for video analysis -//! --profile-gpu time each GPU command alone, print the times at exit -//! --console LINE run a console line once the sketch is loaded (repeatable) -//! --define NAME=VALUE substitute {NAME} in the script -//! --export DIR|- headless, from fresh state: every frame as DIR/000000.png, ... -//! or for - as raw RGBA on stdout, until the sketch quits -//! --fps N export: frames a second (60); each tick is exactly 1/N s -//! --frames N export: stop after N frames -//! --size WxH the first canvas and, headless, the room for it +//! that it hot-reloads whenever a build replaces it. Its options are +//! `flags`, which parse the command line and print `--help`. const std = @import("std"); const c = @import("c"); const abi = @import("abi"); @@ -39,58 +24,52 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { var args = init.minimal.args.iterate(); _ = args.skip(); while (args.next()) |arg| { - if (std.mem.eql(u8, arg, "--state")) { - options.state = args.next() orelse fatal("--state needs a file"); - } else if (std.mem.eql(u8, arg, "--9p")) { - options.ninep = args.next() orelse fatal("--9p needs a socket path"); - } else if (std.mem.eql(u8, arg, "--fresh")) { - options.fresh = true; - } else if (std.mem.eql(u8, arg, "--headless")) { - options.headless = true; - } else if (std.mem.eql(u8, arg, "--timing-marker")) { - options.timing_marker = true; - } else if (std.mem.eql(u8, arg, "--profile-gpu")) { - options.profile_gpu = true; - } else if (std.mem.eql(u8, arg, "--console")) { - try lines.append(gpa, args.next() orelse fatal("--console needs a line")); - } else if (std.mem.eql(u8, arg, "--script")) { - script_path = args.next() orelse fatal("--script needs a file"); - options.script = true; - } else if (std.mem.eql(u8, arg, "--define")) { - const pair = args.next() orelse fatal("--define needs NAME=VALUE"); - const eq = std.mem.indexOfScalar(u8, pair, '=') orelse fatal("--define needs NAME=VALUE"); - try defines.append(gpa, .{ pair[0..eq], pair[eq + 1 ..] }); - } else if (std.mem.eql(u8, arg, "--export")) { - options.export_to = args.next() orelse fatal("--export needs a directory, or - for stdout"); - options.headless = true; - options.fresh = true; - } else if (std.mem.eql(u8, arg, "--fps")) { - options.fps = std.fmt.parseInt(u32, args.next() orelse "", 10) catch 0; - if (options.fps == 0) fatal("--fps needs a whole number of frames a second"); - } else if (std.mem.eql(u8, arg, "--frames")) { - options.frames = std.fmt.parseInt(u64, args.next() orelse "", 10) catch fatal("--frames needs a number"); - } else if (std.mem.eql(u8, arg, "--size")) { - const size = args.next() orelse ""; - const x = std.mem.indexOfScalar(u8, size, 'x') orelse fatal("--size needs WxH"); - const w = std.fmt.parseInt(u32, size[0..x], 10) catch 0; - const h = std.fmt.parseInt(u32, size[x + 1 ..], 10) catch 0; - if (w == 0 or h == 0) fatal("--size needs WxH"); - options.size = .{ w, h }; - } else if (std.mem.eql(u8, arg, "-h") or std.mem.eql(u8, arg, "--help")) { - std.debug.print("{s}", .{usage}); - return; - } else if (std.mem.startsWith(u8, arg, "-")) { - fatal("unknown option (see --help)"); - } else { + if (!std.mem.startsWith(u8, arg, "-")) { options.library = arg; + continue; } + const flag: Flag = if (std.mem.eql(u8, arg, "-h")) .help else (if (std.mem.startsWith(u8, arg, "--")) std.meta.stringToEnum(Flag, arg[2..]) else null) orelse fatal("{s} is no option (see --help)", .{arg}); + const v = if (flags.get(flag).arg.len == 0) "" else args.next() orelse fatal("{s} needs {s}", .{ arg, flags.get(flag).arg }); + switch (flag) { + .@"9p" => options.ninep = v, + .state => options.state = v, + .headless => options.headless = true, + .script => { + script_path = v; + options.script = true; + }, + .fresh => options.fresh = true, + .@"timing-marker" => options.timing_marker = true, + .@"profile-gpu" => options.profile_gpu = true, + .console => try lines.append(gpa, v), + .define => { + const eq = std.mem.indexOfScalar(u8, v, '=') orelse fatal("{s} needs {s}", .{ arg, "NAME=VALUE" }); + try defines.append(gpa, .{ v[0..eq], v[eq + 1 ..] }); + }, + .@"export" => { + options.export_to = v; + options.headless = true; + options.fresh = true; + }, + .fps => options.fps = std.fmt.parseInt(u32, v, 10) catch 0, + .frames => options.frames = std.fmt.parseInt(u64, v, 10) catch fatal("{s} needs {s}", .{ arg, "a number" }), + .size => { + const x = std.mem.indexOfScalar(u8, v, 'x') orelse 0; + const w = std.fmt.parseInt(u32, v[0..x], 10) catch 0; + const h = std.fmt.parseInt(u32, v[x + 1 ..], 10) catch 0; + if (w == 0 or h == 0) fatal("{s} needs {s}", .{ arg, "WxH" }); + options.size = .{ w, h }; + }, + .help => return std.debug.print("{s}", .{usage}), + } + if (options.fps == 0) fatal("{s} needs {s}", .{ arg, "a whole number of frames a second" }); } - if (linked == null and options.library == null) fatal("no sketch library given (see --help)"); + if (linked == null and options.library == null) fatal("no sketch library given (see --help)", .{}); if (options.export_to) |to| { - if (script_path != null) fatal("--export plays no script: it runs the sketch on its own"); + if (script_path != null) fatal("--export plays no script: it runs the sketch on its own", .{}); if (!std.mem.eql(u8, to, "-")) { try std.Io.Dir.cwd().createDirPath(init.io, to); - } else if (try std.Io.File.stdout().isTty(init.io)) fatal("--export -: stdout is a terminal; pipe it to ffmpeg"); + } else if (try std.Io.File.stdout().isTty(init.io)) fatal("--export -: stdout is a terminal; pipe it to ffmpeg", .{}); } if (options.state.len == 0 and (script_path != null or options.export_to != null)) options.state = "sketch.xitdb"; @@ -112,26 +91,41 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { if (sdl_heap.leaked()) return error.LeakedSdlMemory; } -const usage = - \\usage: sketchbook [options] [LIBRARY] - \\ --9p SOCKET local 9P controls: ctl, status, log, screen.png - \\ --state FILE the save, one file: FILE, or FILE.xitdb for a FILE.state (where a - \\ state file from before is imported from, once); default: - \\ $XDG_DATA_HOME//.xitdb, sketch.xitdb for --script, --export - \\ --headless offscreen video, silent audio, no vsync - \\ --script FILE play a script instead of reading devices - \\ --fresh start from default state (the save's history is kept) - \\ --timing-marker encode frame ID and draw sample time for video analysis - \\ --profile-gpu time each GPU command alone, print the times at exit - \\ --console LINE run a console line once the sketch is loaded (repeatable) - \\ --define NAME=VALUE substitute {NAME} in the script - \\ --export DIR|- headless, from fresh state: every frame as DIR/000000.png, ... - \\ or for - as raw RGBA on stdout, until the sketch quits - \\ --fps N export: frames a second (60); each tick is exactly 1/N s - \\ --frames N export: stop after N frames - \\ --size WxH the first canvas and, headless, the room for it - \\ -; +/// The options: a row each, what parses the command line (the switch in +/// `main` sets what each one means) and prints `--help`. +const Flag = enum { @"9p", state, headless, script, fresh, @"timing-marker", @"profile-gpu", console, define, @"export", fps, frames, size, help }; +const flags = std.enums.EnumArray(Flag, struct { arg: []const u8 = "", doc: []const u8 }).init(.{ + .@"9p" = .{ .arg = "SOCKET", .doc = "local 9P controls: ctl, status, log, screen.png" }, + .state = .{ .arg = "FILE", .doc = "the save, one file: FILE, or FILE.xitdb for a FILE.state (where a\nstate file from before is imported from, once); default:\n$XDG_DATA_HOME//.xitdb, sketch.xitdb for --script, --export" }, + .headless = .{ .doc = "offscreen video, silent audio, no vsync" }, + .script = .{ .arg = "FILE", .doc = "play a script instead of reading devices" }, + .fresh = .{ .doc = "start from default state (the save's history is kept)" }, + .@"timing-marker" = .{ .doc = "encode frame ID and draw sample time for video analysis" }, + .@"profile-gpu" = .{ .doc = "time each GPU command alone, print the times at exit" }, + .console = .{ .arg = "LINE", .doc = "run a console line once the sketch is loaded (repeatable)" }, + .define = .{ .arg = "NAME=VALUE", .doc = "substitute {NAME} in the script" }, + .@"export" = .{ .arg = "DIR|-", .doc = "headless, from fresh state: every frame as DIR/000000.png, ...\nor for - as raw RGBA on stdout, until the sketch quits" }, + .fps = .{ .arg = "N", .doc = "export: frames a second (60); each tick is exactly 1/N s" }, + .frames = .{ .arg = "N", .doc = "export: stop after N frames" }, + .size = .{ .arg = "WxH", .doc = "the first canvas and, headless, the room for it" }, + .help = .{ .doc = "this, also -h" }, +}); + +/// `--help`: a line per flag, its doc's lines under one another. +const usage = blk: { + @setEvalBranchQuota(100_000); + const pad: [23]u8 = @splat(' '); + var text: []const u8 = "usage: sketchbook [options] [LIBRARY]\n"; + for (std.enums.values(Flag)) |flag| { + const f = flags.get(flag); + const head = " --" ++ @tagName(flag) ++ (if (f.arg.len > 0) " " ++ f.arg else ""); + text = text ++ head ++ pad[head.len..]; + var lines = std.mem.splitScalar(u8, f.doc, '\n'); + text = text ++ lines.first() ++ "\n"; + while (lines.next()) |more| text = text ++ pad ++ more ++ "\n"; + } + break :blk text; +}; /// A save in a directory named `.sketchbook` (`zig build run`'s): the /// directory is made, with a `.gitignore` of `*` (the save grows, and a jj @@ -159,8 +153,8 @@ fn sketchbookDir(io: std.Io, state: []const u8) void { } } -fn fatal(message: []const u8) noreturn { - std.debug.print("sketchbook: {s}\n", .{message}); +fn fatal(comptime fmt: []const u8, args: anytype) noreturn { + std.debug.print("sketchbook: " ++ fmt ++ "\n", args); std.process.exit(2); } diff --git a/src/host/script.zig b/src/host/script.zig index a559d76..e3976e0 100644 --- a/src/host/script.zig +++ b/src/host/script.zig @@ -1,55 +1,9 @@ //! End-to-end scripts: plain text that plays a sketch like a person would, -//! through the same routing and frames, on a fixed 60 Hz clock. -//! -//! # comment -//! click 710 320 move there, press and release the left button -//! move|down|up X Y one pointer event, then a frame -//! wheel|wheel-x X Y DELTA -//! cancel what losing focus sends -//! key NAME press and release a key (`sketch.Key` names) -//! type TEXT text input, as typed into a focused field -//! console LINE run a console command (`console get` -//! takes no frame: it only reads) -//! frames N advance N frames without input -//! expect FIELD VALUE compare a state field (enums by name or number); -//! FIELD may index arrays and vector lanes, -//! `boids.buffer[3].pos[0]` -//! expect FIELD VALUE ~T numbers within T of VALUE -//! await FIELD VALUE [~T] run frames until it holds (a minute at most) -//! print FIELD write a field's value to stderr (a vector, -//! array or struct: every value in it), no frame -//! expect-snapshot NAME live state equals the newest mark NAME, leaf -//! by leaf (padding ignored, and leaves a layout -//! change reset), exactly -//! expect-key WHY FIELD VALUE -//! the newest keyframe of this session taken for -//! WHY (`Sessions.Why`: before_reload, mark...) -//! holds VALUE, read in its own layout -//! expect-log TEXT a recent console line contains TEXT -//! expect-no-log TEXT no recent console line does -//! expect-audio KEY stream KEY has received samples, or voice -//! KEY sounded since the last check of it -//! expect-no-audio KEY voice KEY did not sound since the last check -//! screenshot FILE save the next frame as PNG -//! expect-same-screenshot A B [MAX [X Y W H]] -//! two saved PNGs match, every channel within MAX -//! (default 0), in the rect if given (pixels) -//! expect-different-screenshot A B [X Y W H] -//! two saved PNGs differ somewhere (in the rect) -//! expect-pixel FILE X Y R G B A [TOL] -//! a saved PNG's pixel, every channel within TOL -//! load LIBRARY swap in another build of the sketch -//! reload load the watched library again -//! await-reload SECONDS run frames until a build replaces the library -//! kill die by SIGKILL, as a crash would -//! -//! `{name}` is replaced by `--define name=value` from the command line. -//! -//! Each line but `frames`, `print`, `console get`, the expectations and -//! `await-reload` is followed by one frame; `update` gets one call per -//! frame, live or replayed, so -//! `console play` then `frames N` replays N recorded frames at the -//! script's 60 Hz. +//! through the same routing and frames, on a fixed 60 Hz clock. A line is +//! a verb of `verbs` and its words; `# comment`; `{name}` is replaced by +//! `--define name=value` from the command line. `update` gets one call per +//! frame, live or replayed, so `console play` then `frames N` replays N +//! recorded frames at the script's 60 Hz. const std = @import("std"); const c = @import("c"); const abi = @import("abi"); @@ -63,6 +17,44 @@ pub const frame_ns: u64 = std.time.ns_per_s / 60; /// The most frames `await` plays: a minute. const await_limit = 60 * 60; +/// The script's verbs, a row each. A verb with `frame` is followed by one +/// frame; the `input` verbs are also what a 9P `ctl` takes live (`input`). +pub const Verb = enum { click, move, down, up, wheel, @"wheel-x", cancel, key, hold, release, type, console, frames, expect, await, print, @"expect-snapshot", @"expect-key", @"expect-log", @"expect-no-log", @"expect-audio", @"expect-no-audio", screenshot, @"expect-same-screenshot", @"expect-different-screenshot", @"expect-pixel", load, reload, @"await-reload", kill, quit }; +pub const Row = struct { args: []const u8 = "", doc: []const u8, frame: bool = false, input: bool = false }; +pub const verbs = std.enums.EnumArray(Verb, Row).init(.{ + .click = .{ .args = "X Y", .doc = "move there, press and release the left button", .frame = true, .input = true }, + .move = .{ .args = "X Y", .doc = "a pointer move", .frame = true, .input = true }, + .down = .{ .args = "X Y", .doc = "the left button down there", .frame = true, .input = true }, + .up = .{ .args = "X Y", .doc = "the left button up there", .frame = true, .input = true }, + .wheel = .{ .args = "X Y DELTA", .doc = "a wheel turn", .frame = true, .input = true }, + .@"wheel-x" = .{ .args = "X Y DELTA", .doc = "a sideways wheel turn", .frame = true, .input = true }, + .cancel = .{ .doc = "what losing focus sends", .frame = true, .input = true }, + .key = .{ .args = "NAME", .doc = "press and release a key (`sketch.Key` names)", .frame = true, .input = true }, + .hold = .{ .args = "NAME", .doc = "a key down until released, for modifiers", .frame = true, .input = true }, + .release = .{ .args = "NAME", .doc = "a held key up", .frame = true, .input = true }, + .type = .{ .args = "TEXT", .doc = "text input, as typed into a focused field", .frame = true, .input = true }, + .console = .{ .args = "LINE", .doc = "a console line (`console get` takes no frame: it only reads); one that fails fails the script", .frame = true }, + .frames = .{ .args = "N", .doc = "N frames without input" }, + .expect = .{ .args = "FIELD VALUE [~T]", .doc = "a State field holds VALUE (enums by name or number; numbers within T); FIELD may index arrays and vector lanes, `boids.buffer[3].pos[0]`" }, + .await = .{ .args = "FIELD VALUE [~T]", .doc = "frames until expect holds, a minute at most" }, + .print = .{ .args = "FIELD", .doc = "a field's value to stderr (a vector, array or struct: every value in it)" }, + .@"expect-snapshot" = .{ .args = "NAME", .doc = "live State equals the newest mark NAME, leaf by leaf (padding, and leaves a layout change reset, ignored)" }, + .@"expect-key" = .{ .args = "WHY FIELD VALUE", .doc = "the newest keyframe of this session taken for WHY (`Sessions.Why`: before_reload, mark...) holds VALUE, read in its own layout" }, + .@"expect-log" = .{ .args = "TEXT", .doc = "a recent console line contains TEXT" }, + .@"expect-no-log" = .{ .args = "TEXT", .doc = "no recent console line does" }, + .@"expect-audio" = .{ .args = "KEY", .doc = "stream KEY has received samples, or voice KEY sounded since the last check of it" }, + .@"expect-no-audio" = .{ .args = "KEY", .doc = "voice KEY did not sound since the last check" }, + .screenshot = .{ .args = "FILE", .doc = "save the next frame as PNG", .frame = true }, + .@"expect-same-screenshot" = .{ .args = "A B [MAX [X Y W H]]", .doc = "two saved PNGs match, every channel within MAX (0), in the rect if given (pixels)" }, + .@"expect-different-screenshot" = .{ .args = "A B [X Y W H]", .doc = "two saved PNGs differ somewhere (in the rect)" }, + .@"expect-pixel" = .{ .args = "FILE X Y R G B A [TOL]", .doc = "a saved PNG's pixel, every channel within TOL" }, + .load = .{ .args = "LIBRARY", .doc = "swap in another build of the sketch", .frame = true }, + .reload = .{ .doc = "load the watched library again", .frame = true }, + .@"await-reload" = .{ .args = "SECONDS", .doc = "frames until a build replaces the library" }, + .kill = .{ .doc = "die by SIGKILL, as a crash would" }, + .quit = .{ .doc = "end the run" }, +}); + pub fn run(host: *Host, source: []const u8, defines: []const [2][]const u8) !void { var arena: std.heap.ArenaAllocator = .init(host.gpa); defer arena.deinit(); @@ -75,9 +67,9 @@ pub fn run(host: *Host, source: []const u8, defines: []const [2][]const u8) !voi const line = try substitute(arena.allocator(), std.mem.trim(u8, raw, " \t\r"), defines); if (line.len == 0 or line[0] == '#') continue; var words = std.mem.tokenizeAny(u8, line, " \t"); - const command = words.next().?; + const verb = std.meta.stringToEnum(Verb, words.next().?); const rest = std.mem.trim(u8, words.rest(), " \t"); - step(host, arena.allocator(), command, rest, &words, &now) catch |err| { + (if (verb) |v| step(host, arena.allocator(), v, rest, &words, &now) else error.UnknownScriptCommand) catch |err| { failures += 1; std.debug.print("script:{d}: {s}: {t}\n", .{ number, line, err }); if (err != error.ExpectationFailed) break; @@ -87,188 +79,210 @@ pub fn run(host: *Host, source: []const u8, defines: []const [2][]const u8) !voi if (failures > 0) return error.ScriptFailed; } -fn step(host: *Host, arena: std.mem.Allocator, command: []const u8, rest: []const u8, words: anytype, now: *u64) !void { - const eq = std.mem.eql; - if (eq(u8, command, "click")) { - const x, const y = try point(words); - try host.route(.{ .kind = .mouse_move, .time = now.*, .x = x, .y = y, .flags = held(host) }); - try host.route(.{ .kind = .mouse_down, .time = now.*, .x = x, .y = y, .code = 1, .flags = held(host) }); - try host.route(.{ .kind = .mouse_up, .time = now.*, .x = x, .y = y, .code = 1, .flags = held(host) }); - } else if (eq(u8, command, "move") or eq(u8, command, "down") or eq(u8, command, "up")) { - const x, const y = try point(words); - const kind: abi.Event.Kind = if (eq(u8, command, "move")) .mouse_move else if (eq(u8, command, "down")) .mouse_down else .mouse_up; - try host.route(.{ .kind = kind, .time = now.*, .x = x, .y = y, .code = if (kind == .mouse_move) 0 else 1, .flags = held(host) }); - } else if (eq(u8, command, "wheel") or eq(u8, command, "wheel-x")) { - const x, const y = try point(words); - const delta = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedDelta); - try host.route(.{ .kind = if (eq(u8, command, "wheel-x")) .wheel_horizontal else .wheel, .time = now.*, .x = x, .y = y, .value = @bitCast(delta), .flags = held(host) }); - } else if (eq(u8, command, "cancel")) { - try host.route(.{ .kind = .cancel, .time = now.* }); - } else if (eq(u8, command, "key")) { - const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey; - try host.route(.{ .kind = .key_down, .time = now.*, .code = @backingInt(key) }); - try host.route(.{ .kind = .key_up, .time = now.*, .code = @backingInt(key) }); - } else if (eq(u8, command, "hold") or eq(u8, command, "release")) { - const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey; - try host.route(.{ .kind = if (eq(u8, command, "hold")) .key_down else .key_up, .time = now.*, .code = @backingInt(key) }); - } else if (eq(u8, command, "type")) { - for (rest) |byte| try host.route(.{ .kind = .text, .time = now.*, .value = byte }); - } else if (eq(u8, command, "console")) { - // A failing console line fails the script, like a failed expect. - host.runLine(rest, now.*) catch |err| { - std.debug.print(" console {s}: {t}\n", .{ rest, err }); - return err; - }; - if (std.mem.startsWith(u8, rest, "get ")) return; - } else if (eq(u8, command, "print")) { - const path = words.next() orelse return error.ExpectedField; - var buf: [4096]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) { - error.UnknownField => return error.UnknownField, - error.WriteFailed => {}, - }; - std.debug.print("{s} = {s}\n", .{ path, w.buffered() }); - return; - } else if (eq(u8, command, "frames")) { - const count = try std.fmt.parseInt(usize, rest, 10); - for (0..count) |_| try advance(host, now); - return; - } else if (eq(u8, command, "expect") or eq(u8, command, "await")) { - const path = words.next() orelse return error.ExpectedField; - const want, const tolerance = try expected(std.mem.trim(u8, words.rest(), " \t")); - // Looked up again after each frame: a reload may move the field. - _ = host.state.layout.find(path) orelse return error.UnknownField; - // `await` plays frames until the field holds the value, for up to a - // minute: for waits whose length is the sketch's business. - if (eq(u8, command, "await")) { - var waited: usize = 0; - while (!holds(host, path, want, tolerance) and waited < await_limit) : (waited += 1) try advance(host, now); - } - if (!holds(host, path, want, tolerance)) { - var buf: [128]u8 = undefined; +/// Routes an input verb's events at `now`, no frame after: a script's +/// line, or a 9P `ctl` line live. +pub fn input(host: *Host, verb: Verb, words: *std.mem.TokenIterator(u8, .any), now: u64) !void { + const rest = std.mem.trim(u8, words.rest(), " \t"); + switch (verb) { + .click => { + const x, const y = try point(words); + try host.route(.{ .kind = .mouse_move, .time = now, .x = x, .y = y, .flags = held(host) }); + try host.route(.{ .kind = .mouse_down, .time = now, .x = x, .y = y, .code = 1, .flags = held(host) }); + try host.route(.{ .kind = .mouse_up, .time = now, .x = x, .y = y, .code = 1, .flags = held(host) }); + }, + .move, .down, .up => { + const x, const y = try point(words); + const kind: abi.Event.Kind = switch (verb) { + .move => .mouse_move, + .down => .mouse_down, + else => .mouse_up, + }; + try host.route(.{ .kind = kind, .time = now, .x = x, .y = y, .code = if (kind == .mouse_move) 0 else 1, .flags = held(host) }); + }, + .wheel, .@"wheel-x" => { + const x, const y = try point(words); + const delta = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedDelta); + try host.route(.{ .kind = if (verb == .@"wheel-x") .wheel_horizontal else .wheel, .time = now, .x = x, .y = y, .value = @bitCast(delta), .flags = held(host) }); + }, + .cancel => try host.route(.{ .kind = .cancel, .time = now }), + .key => { + const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey; + try host.route(.{ .kind = .key_down, .time = now, .code = @backingInt(key) }); + try host.route(.{ .kind = .key_up, .time = now, .code = @backingInt(key) }); + }, + .hold, .release => { + const key = std.meta.stringToEnum(abi.Key, rest) orelse return error.UnknownKey; + try host.route(.{ .kind = if (verb == .hold) .key_down else .key_up, .time = now, .code = @backingInt(key) }); + }, + .type => for (rest) |byte| try host.route(.{ .kind = .text, .time = now, .value = byte }), + else => return error.NotInput, + } +} + +fn step(host: *Host, arena: std.mem.Allocator, verb: Verb, rest: []const u8, words: *std.mem.TokenIterator(u8, .any), now: *u64) !void { + switch (verb) { + .click, .move, .down, .up, .wheel, .@"wheel-x", .cancel, .key, .hold, .release, .type => try input(host, verb, words, now.*), + .console => { + // A failing console line fails the script, like a failed expect. + host.runLine(rest, now.*) catch |err| { + std.debug.print(" console {s}: {t}\n", .{ rest, err }); + return err; + }; + if (std.mem.startsWith(u8, rest, "get ")) return; + }, + .print => { + const path = words.next() orelse return error.ExpectedField; + var buf: [4096]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) { - error.UnknownField => w.writeAll("no such field") catch {}, + error.UnknownField => return error.UnknownField, error.WriteFailed => {}, }; - if (tolerance) |t| { - std.debug.print(" {s}: expected {s} ~{d}, found {s}\n", .{ path, want, t, w.buffered() }); - } else std.debug.print(" {s}: expected {s}, found {s}\n", .{ path, want, w.buffered() }); - return error.ExpectationFailed; - } - return; - } else if (eq(u8, command, "expect-snapshot")) { - const saved = try Console.markState(host, arena, rest); - if (!same(host, saved.layout, saved.bytes, rest)) return error.ExpectationFailed; - return; - } else if (eq(u8, command, "expect-key")) { - const why = std.meta.stringToEnum(Sessions.Why, words.next() orelse "") orelse return error.UnknownWhy; - const path = words.next() orelse return error.ExpectedField; - const want = std.mem.trim(u8, words.rest(), " \t"); - const s = &host.sessions; - try s.commit(.none); - var k = s.keys; - while (k > 0) { - k -= 1; - const key = try s.load(s.session, k); - defer key.free(host.gpa); - if (key.why != why) continue; - const leaf = (try memory.layoutOf(arena, key.layout)).find(path) orelse return error.UnknownField; - if (fields.matches(leaf, key.state, want)) return; - var buf: [128]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - fields.format(leaf, key.state, &w) catch {}; - std.debug.print(" {s} keyframe {d}: {s} expected {s}, found {s}\n", .{ @tagName(why), k, path, want, w.buffered() }); + std.debug.print("{s} = {s}\n", .{ path, w.buffered() }); + }, + .frames => { + const count = try std.fmt.parseInt(usize, rest, 10); + for (0..count) |_| try advance(host, now); + }, + .expect, .await => { + const path = words.next() orelse return error.ExpectedField; + const want, const tolerance = try expected(std.mem.trim(u8, words.rest(), " \t")); + // Looked up again after each frame: a reload may move the field. + _ = host.state.layout.find(path) orelse return error.UnknownField; + // `await` plays frames until the field holds the value, for up to a + // minute: for waits whose length is the sketch's business. + if (verb == .await) { + var waited: usize = 0; + while (!holds(host, path, want, tolerance) and waited < await_limit) : (waited += 1) try advance(host, now); + } + if (!holds(host, path, want, tolerance)) { + var buf: [128]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + fields.formatPath(host.state.layout, host.live(), path, &w) catch |err| switch (err) { + error.UnknownField => w.writeAll("no such field") catch {}, + error.WriteFailed => {}, + }; + if (tolerance) |t| { + std.debug.print(" {s}: expected {s} ~{d}, found {s}\n", .{ path, want, t, w.buffered() }); + } else std.debug.print(" {s}: expected {s}, found {s}\n", .{ path, want, w.buffered() }); + return error.ExpectationFailed; + } + }, + .@"expect-snapshot" => { + const saved = try Console.markState(host, arena, rest); + if (!same(host, saved.layout, saved.bytes, rest)) return error.ExpectationFailed; + }, + .@"expect-key" => { + const why = std.meta.stringToEnum(Sessions.Why, words.next() orelse "") orelse return error.UnknownWhy; + const path = words.next() orelse return error.ExpectedField; + const want = std.mem.trim(u8, words.rest(), " \t"); + const s = &host.sessions; + try s.commit(.none); + var k = s.keys; + while (k > 0) { + k -= 1; + const key = try s.load(s.session, k); + defer key.free(host.gpa); + if (key.why != why) continue; + const leaf = (try memory.layoutOf(arena, key.layout)).find(path) orelse return error.UnknownField; + if (fields.matches(leaf, key.state, want)) return; + var buf: [128]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + fields.format(leaf, key.state, &w) catch {}; + std.debug.print(" {s} keyframe {d}: {s} expected {s}, found {s}\n", .{ @tagName(why), k, path, want, w.buffered() }); + return error.ExpectationFailed; + } + std.debug.print(" no {s} keyframe in this session\n", .{@tagName(why)}); return error.ExpectationFailed; - } - std.debug.print(" no {s} keyframe in this session\n", .{@tagName(why)}); - return error.ExpectationFailed; - } else if (eq(u8, command, "expect-log") or eq(u8, command, "expect-no-log")) { - var found = false; - for (&host.console.lines) |*l| { - if (std.mem.indexOf(u8, l.bytes[0..l.len], rest) != null) found = true; - } - if (found != eq(u8, command, "expect-log")) { - std.debug.print(" console log:\n", .{}); - for (&host.console.lines) |*l| std.debug.print(" {s}\n", .{l.bytes[0..l.len]}); - return error.ExpectationFailed; - } - return; - } else if (eq(u8, command, "expect-same-screenshot") or eq(u8, command, "expect-different-screenshot")) { - const a = words.next() orelse return error.ExpectedFile; - const b = words.next() orelse return error.ExpectedFile; - const want_same = eq(u8, command, "expect-same-screenshot"); - const max: u8 = if (!want_same) 0 else if (words.next()) |m| std.fmt.parseInt(u8, m, 10) catch return error.InvalidValue else 0; - var rect: ?[4]usize = null; - if (words.next()) |x| { - var r: [4]usize = undefined; - r[0] = std.fmt.parseInt(usize, x, 10) catch return error.InvalidRect; - for (r[1..]) |*v| v.* = std.fmt.parseInt(usize, words.next() orelse return error.InvalidRect, 10) catch return error.InvalidRect; - rect = r; - } - const diff = try comparePng(arena, a, b, max, rect); - if ((diff.count == 0) != want_same) { - if (want_same) { - std.debug.print(" {s} vs {s}: {d} pixels differ by more than {d}, first at {d},{d}\n", .{ a, b, diff.count, max, diff.first[0], diff.first[1] }); - } else std.debug.print(" {s} and {s} are the same\n", .{ a, b }); - return error.ExpectationFailed; - } - return; - } else if (eq(u8, command, "expect-pixel")) { - const file = words.next() orelse return error.ExpectedFile; - var n: [7]u8 = .{ 0, 0, 0, 0, 0, 0, 0 }; - var x: usize = 0; - var y: usize = 0; - for (0..7) |i| { - const word = words.next() orelse if (i == 6) break else return error.ExpectedPixel; - if (i < 2) { - (if (i == 0) &x else &y).* = std.fmt.parseInt(usize, word, 10) catch return error.ExpectedPixel; - } else n[i - 2] = std.fmt.parseInt(u8, word, 0) catch return error.ExpectedPixel; - } - const tol = n[4]; - const surface = try loadPng(arena, file); - defer c.SDL_DestroySurface(surface); - if (x >= surface.*.w or y >= surface.*.h) return error.OutsideScreenshot; - const p = (@as([*]const u8, @ptrCast(surface.*.pixels.?)) + y * @as(usize, @intCast(surface.*.pitch)) + x * 4)[0..4]; - for (p, n[0..4]) |got, want| if (@max(got, want) - @min(got, want) > tol) { - std.debug.print(" {s} at {d},{d}: expected {d} {d} {d} {d}, found {d} {d} {d} {d}\n", .{ file, x, y, n[0], n[1], n[2], n[3], p[0], p[1], p[2], p[3] }); - return error.ExpectationFailed; - }; - return; - } else if (eq(u8, command, "expect-audio")) { - const key = try std.fmt.parseInt(u32, rest, 10); - if (host.input.stream(key).pushed == 0 and !host.audio.sounded(key)) return error.ExpectationFailed; - return; - } else if (eq(u8, command, "expect-no-audio")) { - if (host.audio.sounded(try std.fmt.parseInt(u32, rest, 10))) return error.ExpectationFailed; - return; - } else if (eq(u8, command, "screenshot")) { - if (std.fs.path.dirname(rest)) |dir| try std.Io.Dir.cwd().createDirPath(host.io, dir); - host.screenshot = try arena.dupeSentinel(u8, rest, 0); - } else if (eq(u8, command, "load")) { - try host.load(rest); - } else if (eq(u8, command, "reload")) { - try host.reload(); - } else if (eq(u8, command, "await-reload")) { - const seconds = try std.fmt.parseInt(u64, rest, 10); - const start = host.reloads; - const deadline = std.Io.Timestamp.now(host.io, .awake).nanoseconds + @as(i96, seconds) * std.time.ns_per_s; - while (host.reloads == start) { - if (std.Io.Timestamp.now(host.io, .awake).nanoseconds > deadline) return error.NoReload; - try advance(host, now); - try std.Io.sleep(host.io, .fromMilliseconds(10), .awake); - } - return; - } else if (eq(u8, command, "kill")) { - // A crash, for tests of what survives one: SIGKILL, no cleanup. - _ = std.os.linux.kill(std.os.linux.getpid(), .KILL); - return; - } else if (eq(u8, command, "quit")) { - host.quit = true; - return; - } else return error.UnknownScriptCommand; - try advance(host, now); + }, + .@"expect-log", .@"expect-no-log" => { + var found = false; + for (&host.console.lines) |*l| { + if (std.mem.indexOf(u8, l.bytes[0..l.len], rest) != null) found = true; + } + if (found != (verb == .@"expect-log")) { + std.debug.print(" console log:\n", .{}); + for (&host.console.lines) |*l| std.debug.print(" {s}\n", .{l.bytes[0..l.len]}); + return error.ExpectationFailed; + } + }, + .@"expect-same-screenshot", .@"expect-different-screenshot" => { + const a = words.next() orelse return error.ExpectedFile; + const b = words.next() orelse return error.ExpectedFile; + const want_same = verb == .@"expect-same-screenshot"; + const max: u8 = if (!want_same) 0 else if (words.next()) |m| std.fmt.parseInt(u8, m, 10) catch return error.InvalidValue else 0; + var rect: ?[4]usize = null; + if (words.next()) |x| { + var r: [4]usize = undefined; + r[0] = std.fmt.parseInt(usize, x, 10) catch return error.InvalidRect; + for (r[1..]) |*v| v.* = std.fmt.parseInt(usize, words.next() orelse return error.InvalidRect, 10) catch return error.InvalidRect; + rect = r; + } + const diff = try comparePng(arena, a, b, max, rect); + if ((diff.count == 0) != want_same) { + if (want_same) { + std.debug.print(" {s} vs {s}: {d} pixels differ by more than {d}, first at {d},{d}\n", .{ a, b, diff.count, max, diff.first[0], diff.first[1] }); + } else std.debug.print(" {s} and {s} are the same\n", .{ a, b }); + return error.ExpectationFailed; + } + }, + .@"expect-pixel" => { + const file = words.next() orelse return error.ExpectedFile; + var n: [7]u8 = .{ 0, 0, 0, 0, 0, 0, 0 }; + var x: usize = 0; + var y: usize = 0; + for (0..7) |i| { + const word = words.next() orelse if (i == 6) break else return error.ExpectedPixel; + if (i < 2) { + (if (i == 0) &x else &y).* = std.fmt.parseInt(usize, word, 10) catch return error.ExpectedPixel; + } else n[i - 2] = std.fmt.parseInt(u8, word, 0) catch return error.ExpectedPixel; + } + const tol = n[4]; + const surface = try loadPng(arena, file); + defer c.SDL_DestroySurface(surface); + if (x >= surface.*.w or y >= surface.*.h) return error.OutsideScreenshot; + const p = (@as([*]const u8, @ptrCast(surface.*.pixels.?)) + y * @as(usize, @intCast(surface.*.pitch)) + x * 4)[0..4]; + for (p, n[0..4]) |got, want| if (@max(got, want) - @min(got, want) > tol) { + std.debug.print(" {s} at {d},{d}: expected {d} {d} {d} {d}, found {d} {d} {d} {d}\n", .{ file, x, y, n[0], n[1], n[2], n[3], p[0], p[1], p[2], p[3] }); + return error.ExpectationFailed; + }; + }, + .@"expect-audio" => { + const key = try std.fmt.parseInt(u32, rest, 10); + if (host.input.stream(key).pushed == 0 and !host.audio.sounded(key)) return error.ExpectationFailed; + }, + .@"expect-no-audio" => { + if (host.audio.sounded(try std.fmt.parseInt(u32, rest, 10))) return error.ExpectationFailed; + }, + .screenshot => { + if (std.fs.path.dirname(rest)) |dir| try std.Io.Dir.cwd().createDirPath(host.io, dir); + host.screenshot = try arena.dupeSentinel(u8, rest, 0); + }, + .load => { + try host.load(rest); + }, + .reload => { + try host.reload(); + }, + .@"await-reload" => { + const seconds = try std.fmt.parseInt(u64, rest, 10); + const start = host.reloads; + const deadline = std.Io.Timestamp.now(host.io, .awake).nanoseconds + @as(i96, seconds) * std.time.ns_per_s; + while (host.reloads == start) { + if (std.Io.Timestamp.now(host.io, .awake).nanoseconds > deadline) return error.NoReload; + try advance(host, now); + try std.Io.sleep(host.io, .fromMilliseconds(10), .awake); + } + }, + .kill => { + // A crash, for tests of what survives one: SIGKILL, no cleanup. + _ = std.os.linux.kill(std.os.linux.getpid(), .KILL); + }, + .quit => { + host.quit = true; + }, + } + if (verbs.get(verb).frame) try advance(host, now); } /// The modifiers `hold` has down, for a pointer event's `flags`. -- cgit v1.3