summaryrefslogtreecommitdiff
path: root/src/host/Console.zig
blob: 40845f7306ce3384c91dcfbd509a0a89a01586c7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
//! The developer console: a line editor, a short log, and the host commands
//! (snapshots, recordings, replay, field inspection). Lines the host does not
//! know go to the sketch's `command`.
const Console = @This();
const std = @import("std");
const abi = @import("abi");
const Host = @import("Host.zig");
const fields = @import("fields.zig");
const memory = @import("memory.zig");
const timeline = @import("timeline.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 host_commands = [_][]const u8{
    "help",   "overlay memory", "overlay sound", "get",   "set",  "reset",      "save",     "load", "snapshot", "recording",
    "record", "stop",           "play",          "pause", "step", "seek start", "seek end", "diff", "quit",     "exit",
};

visible: bool = false,
buffer: [96]u8 = @splat(0),
len: usize = 0,
cursor: usize = 0,
lines: [5]Line = @splat(.{}),
snapshot: usize = 1,
recording: usize = 0,
overlay_memory: bool = false,
overlay_sound: bool = false,

pub fn text(self: *const Console) []const u8 {
    return self.buffer[0..self.len];
}

pub fn insert(self: *Console, typed: []const u8) void {
    for (typed) |byte| {
        // Commands and the built-in font only need printable ASCII.
        if (byte < 32 or byte > 126 or byte == '`' or self.len == self.buffer.len) continue;
        std.mem.copyBackwards(u8, self.buffer[self.cursor + 1 .. self.len + 1], self.buffer[self.cursor..self.len]);
        self.buffer[self.cursor] = byte;
        self.cursor += 1;
        self.len += 1;
    }
}

/// Edits the line; `submit` returns it (valid until the next edit).
pub fn edit(self: *Console, key: Key, extra: []const []const u8) ?[]const u8 {
    switch (key) {
        .left => self.cursor -|= 1,
        .right => self.cursor = @min(self.len, self.cursor + 1),
        .home => self.cursor = 0,
        .end => self.cursor = self.len,
        .clear => {
            self.len = 0;
            self.cursor = 0;
        },
        .backspace => if (self.cursor > 0) {
            self.cursor -= 1;
            self.erase();
        },
        .delete => self.erase(),
        .tab => self.complete(extra),
        .submit => {
            const line = self.text();
            // The bytes stay put until the next edit; only the length resets.
            self.len = 0;
            self.cursor = 0;
            if (std.mem.trim(u8, line, " ").len == 0) return null;
            self.print("> {s}", .{line});
            return line;
        },
    }
    return null;
}

fn erase(self: *Console) void {
    if (self.cursor == self.len) return;
    std.mem.copyForwards(u8, self.buffer[self.cursor .. self.len - 1], self.buffer[self.cursor + 1 .. self.len]);
    self.len -= 1;
}

fn complete(self: *Console, extra: []const []const u8) void {
    var first: ?[]const u8 = null;
    var common: usize = 0;
    var matches: [256]u8 = undefined;
    var used: usize = 0;
    var count: usize = 0;
    for ([_][]const []const u8{ &host_commands, extra }) |list| for (list) |candidate| {
        if (!std.mem.startsWith(u8, candidate, self.text())) continue;
        if (first) |previous| {
            var i: usize = 0;
            while (i < common and i < candidate.len and previous[i] == candidate[i]) : (i += 1) {}
            common = i;
        } else {
            first = candidate;
            common = candidate.len;
        }
        const match = std.mem.print(matches[used..], "{s}  ", .{candidate}) catch continue;
        used += match.len;
        count += 1;
    };
    if (first) |candidate| {
        self.cursor = self.len;
        self.insert(candidate[self.len..common]);
        if (count > 1) self.log(matches[0..used]);
    } else self.log("No completion. Type help for commands.");
}

pub fn log(self: *Console, message: []const u8) void {
    var rest = message;
    while (true) {
        std.mem.copyForwards(Line, self.lines[0..4], self.lines[1..5]);
        const line = &self.lines[4];
        line.len = @min(rest.len, line.bytes.len);
        @memcpy(line.bytes[0..line.len], rest[0..line.len]);
        rest = rest[line.len..];
        if (rest.len == 0) break;
    }
}

pub fn print(self: *Console, comptime fmt: []const u8, args: anytype) void {
    var buf: [512]u8 = undefined;
    self.log(std.mem.print(&buf, fmt, args) catch "(message too long)");
}

/// Runs one line. Host commands first; anything else goes to the sketch.
/// Returns events to replay after a seek, already restored to the snapshot.
pub fn execute(self: *Console, host: *Host, line: []const u8, now: u64) ![]const abi.Event {
    const h = &host.timeline;
    var words = std.mem.tokenizeAny(u8, line, " \t");
    const command = words.next() orelse return &.{};
    const arg = words.next();
    const rest = words.rest();

    if (eq(command, "help")) {
        self.log("save|load [1..7] snapshot N | record|play [0..15] recording N | stop | pause | step N (frames) | seek start|end|<ms>");
        self.log("diff [N] | reset | get <field> | set <field> <value> | overlay memory|sound | quit");
        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;
        const flag = if (eq(name, "memory")) &self.overlay_memory else if (eq(name, "sound")) &self.overlay_sound else return error.UnknownOverlay;
        flag.* = !flag.*;
        self.print("{s} overlay: {s}", .{ name, if (flag.*) "on" else "off" });
    } 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;
        h.stop(now);
        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")) {
        h.stop(now);
        host.quit = true;
    } else if (eq(command, "reset")) {
        h.stop(now);
        host.resetState();
        self.log("Live state reset. Snapshots are kept.");
    } else if (eq(command, "snapshot")) {
        self.snapshot = try slot(arg orelse return error.ExpectedSlot, 1, memory.slot_count - 1);
    } else if (eq(command, "recording")) {
        self.recording = try slot(arg orelse return error.ExpectedSlot, 0, timeline.recording_count - 1);
    } else if (eq(command, "save") or eq(command, "load")) {
        const index = if (arg) |a| try slot(a, 1, memory.slot_count - 1) else self.snapshot;
        if (eq(command, "load") and !h.bank.hasSnapshot(index)) return error.EmptySnapshot;
        h.stop(now);
        if (eq(command, "save")) {
            h.bank.save(index);
            self.print("Saved snapshot {d}. Recordings from its old contents are invalidated.", .{index});
        } else {
            try h.restore(index);
            self.print("Loaded snapshot {d}.", .{index});
        }
    } else if (eq(command, "record") or eq(command, "play")) {
        const index = if (arg) |a| try slot(a, 0, timeline.recording_count - 1) else self.recording;
        if (eq(command, "play")) _ = try h.bank.get(index);
        h.stop(now);
        if (eq(command, "record")) try h.startRecording(index, self.snapshot, now, host.build) else try h.play(index, now);
        self.recording = index;
        self.print("{s} recording {d} from snapshot {d}.", .{ if (eq(command, "record")) "Started" else "Playing", index, h.bank.recording(index).snapshot });
        if (eq(command, "play")) self.warnBuild(host, h.bank.recording(index));
    } else if (eq(command, "stop")) {
        h.stop(now);
    } 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;
        _ = try h.bank.get(if (h.mode == .live or h.mode == .recording) self.recording else h.selected);
        if (h.mode == .recording) h.stop(now);
        if (h.mode == .live) try h.play(self.recording, now);
        const r = try h.bank.get(h.selected);
        if (h.mode == .playing and h.cursor == 0) self.warnBuild(host, r);
        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(r.count);
        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 index = if (arg) |a| try slot(a, 1, memory.slot_count - 1) else self.snapshot;
        if (!h.bank.hasSnapshot(index)) return error.EmptySnapshot;
        const diff = h.bank.compare(0, index);
        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 {d}: {d} differing values, first {s}", .{ index, diff.count, w.buffered() });
        } else self.print("Live vs snapshot {d}: same", .{index});
    } else {
        // Sketch commands edit state outside the recorded input.
        h.stop(now);
        switch (host.forward(self, line, now)) {
            .unknown => return error.UnknownCommand,
            .failed => return error.CommandFailed,
            .done => {},
        }
    }
    return &.{};
}

pub fn draw(self: *const Console, host: *Host, out: *std.ArrayList(abi.Command), arena: std.mem.Allocator) !void {
    const ink: abi.Color = .{ .r = 230, .g = 255, .b = 230 };
    const hint: abi.Color = .{ .r = 145, .g = 220, .b = 150 };
    const top = @as(f32, @floatFromInt(host.canvas[1])) - panel_height;
    const width: f32 = @floatFromInt(host.canvas[0]);
    const h = &host.timeline;
    try out.append(arena, .{ .rect = .{ .dst = .{ .x = 0, .y = top, .w = width, .h = panel_height }, .color = .{ .r = 24, .g = 28, .b = 28 } } });
    const status = try std.fmt.allocPrint(arena, "{s} | {t} | snapshot {d} | recording {d} (active {d}) | event {d} | {d}ms", .{
        host.name, h.mode, self.snapshot, self.recording, h.selected, h.cursor, h.position / std.time.ns_per_ms,
    });
    try out.append(arena, .{ .text = .{ .x = 12, .y = top + 8, .scale = 1, .color = hint, .bytes = status } });
    for (&self.lines, 0..) |*line, i| {
        try out.append(arena, .{ .text = .{ .x = 12, .y = top + 28 + @as(f32, @floatFromInt(i)) * 18, .scale = 1, .color = ink, .bytes = line.bytes[0..line.len] } });
    }
    try out.append(arena, .{ .text = .{ .x = 12, .y = top + 122, .scale = 1, .color = ink, .bytes = try std.fmt.allocPrint(arena, "> {s}", .{self.text()}) } });
    try out.append(arena, .{ .rect = .{ .dst = .{ .x = @floatFromInt(28 + self.cursor * 8), .y = top + 120, .w = 1, .h = 12 }, .color = hint } });
}

/// A replay of a recording made by other code may diverge: say so.
fn warnBuild(self: *Console, host: *const Host, r: *const timeline.Recording) void {
    if (r.build() != 0 and host.build != 0 and r.build() != host.build) self.log("Warning: recorded by another build of the sketch; the replay may differ.");
}

fn eq(a: []const u8, b: []const u8) bool {
    return std.mem.eql(u8, a, b);
}

fn slot(value: []const u8, min: usize, max: usize) !usize {
    const index = std.fmt.parseInt(usize, value, 10) catch return error.InvalidSlot;
    if (index < min or index > max) return error.InvalidSlot;
    return index;
}

test "line editing, completion and submission" {
    var c: Console = .{};
    c.insert("scen");
    _ = c.edit(.tab, &.{ "scene room", "scene gallery" });
    try std.testing.expectEqualStrings("scene ", c.text());
    c.insert("`room");
    try std.testing.expectEqualStrings("scene room", c.text());
    _ = c.edit(.home, &.{});
    _ = c.edit(.delete, &.{});
    try std.testing.expectEqualStrings("cene room", c.text());
    const line = c.edit(.submit, &.{}).?;
    try std.testing.expectEqualStrings("cene room", line);
    try std.testing.expectEqualStrings("", c.text());
    try std.testing.expect(c.edit(.submit, &.{}) == null);
}