summaryrefslogtreecommitdiff
path: root/src/host/Console.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/host/Console.zig')
-rw-r--r--src/host/Console.zig403
1 files changed, 241 insertions, 162 deletions
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@<file>" },
+ .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|<ms> | sessions | play session S [at SECS] | export-session [S] FILE | import FILE");
- self.log("reset | get|set <field> [<value>] | 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");