summaryrefslogtreecommitdiff
path: root/src/host/script.zig
blob: 38954f3cbf1eb296877a2171295b7cc0cac6fd6a (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
//! 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 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
//!     frames N               advance N frames without input
//!     expect FIELD VALUE     compare a state field (enums by name or number)
//!     await FIELD VALUE      run frames until it holds (a minute at most)
//!     expect-audio KEY       stream KEY has received samples
//!     screenshot FILE        save the next frame as PNG
//!     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
//!
//! `{name}` is replaced by `--define name=value` from the command line.
const std = @import("std");
const abi = @import("abi");
const Host = @import("Host.zig");
const fields = @import("fields.zig");

pub const frame_ns: u64 = std.time.ns_per_s / 60;
/// The most frames `await` plays: a minute.
const await_limit = 60 * 60;

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();
    var now: u64 = std.time.ns_per_s;
    var failures: usize = 0;
    var lines = std.mem.splitScalar(u8, source, '\n');
    var number: usize = 0;
    while (lines.next()) |raw| {
        number += 1;
        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 rest = std.mem.trim(u8, words.rest(), " \t");
        step(host, arena.allocator(), command, rest, &words, &now) catch |err| {
            failures += 1;
            std.debug.print("script:{d}: {s}: {t}\n", .{ number, line, err });
            if (err != error.ExpectationFailed) break;
        };
        if (host.quit) break;
    }
    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 });
        try host.route(.{ .kind = .mouse_down, .time = now.*, .x = x, .y = y, .code = 1 });
        try host.route(.{ .kind = .mouse_up, .time = now.*, .x = x, .y = y, .code = 1 });
    } 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 });
    } else if (eq(u8, command, "wheel")) {
        const x, const y = try point(words);
        const delta = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedDelta);
        try host.route(.{ .kind = .wheel, .time = now.*, .x = x, .y = y, .value = @bitCast(delta) });
    } 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 = @intFromEnum(key) });
        try host.route(.{ .kind = .key_up, .time = now.*, .code = @intFromEnum(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;
        };
    } 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 = std.mem.trim(u8, words.rest(), " \t");
        const leaf = 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 (!fields.matches(leaf, host.live(), want) and waited < await_limit) : (waited += 1) try advance(host, now);
        }
        if (!fields.matches(leaf, host.live(), want)) {
            var buf: [128]u8 = undefined;
            var w: std.Io.Writer = .fixed(&buf);
            fields.format(leaf, host.live(), &w) catch {};
            std.debug.print("  {s}: expected {s}, found {s}\n", .{ path, want, w.buffered() });
            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) 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.dupeZ(u8, rest);
    } 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, "quit")) {
        host.quit = true;
        return;
    } else return error.UnknownScriptCommand;
    try advance(host, now);
}

fn advance(host: *Host, now: *u64) !void {
    try host.frame(now.*);
    now.* += frame_ns;
}

fn point(words: anytype) !struct { f32, f32 } {
    const x = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedPoint);
    const y = try std.fmt.parseFloat(f32, words.next() orelse return error.ExpectedPoint);
    return .{ x, y };
}

fn substitute(arena: std.mem.Allocator, line: []const u8, defines: []const [2][]const u8) ![]const u8 {
    var out = line;
    for (defines) |pair| {
        const pattern = try std.fmt.allocPrint(arena, "{{{s}}}", .{pair[0]});
        out = try std.mem.replaceOwned(u8, arena, out, pattern, pair[1]);
    }
    return out;
}