summaryrefslogtreecommitdiff
path: root/src/host/root.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/host/root.zig')
-rw-r--r--src/host/root.zig292
1 files changed, 194 insertions, 98 deletions
diff --git a/src/host/root.zig b/src/host/root.zig
index 158f894..f15493b 100644
--- a/src/host/root.zig
+++ b/src/host/root.zig
@@ -1,20 +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 persistent state (default: <name>.state)
-//! --headless offscreen video, silent audio
-//! --script FILE play a script instead of reading devices
-//! --fresh start from default state: no snapshots or recordings
-//! --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");
@@ -23,6 +9,10 @@ pub const memory = @import("memory.zig");
pub const fields = @import("fields.zig");
pub const script = @import("script.zig");
pub const timeline = @import("timeline.zig");
+const c9 = @import("cloud9");
+const control = @import("control.zig");
+const Sessions = @import("Sessions.zig");
+const Library = @import("library.zig").Library;
/// Entry point for both the generic host (`linked == null`) and apps that
/// link their sketch in.
@@ -38,76 +28,63 @@ 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");
- } 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.eql(u8, arg, "fs")) {
+ var words: std.ArrayList([]const u8) = .empty;
+ defer words.deinit(gpa);
+ while (args.next()) |word| try words.append(gpa, word);
+ std.process.exit(try fs(init, linked, options, words.items));
+ }
+ 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", .{});
}
- // A scripted run from fresh state works on files of its own, moved to
- // the given path at exit: two runs of one build step (two `zig build`s
- // at once share its output path) never share a state, store or
- // recordings file, nor fail on the store's lock. An export's are
- // removed instead: nothing reads them, and a player may have the given
- // ones open.
- var private_buf: [std.fs.max_path_bytes]u8 = undefined;
- const given = options.state;
- const private = (script_path != null or options.export_to != null) and options.fresh;
- if (private) options.state = std.mem.print(&private_buf, "{s}.{d}", .{ given, std.os.linux.getpid() }) catch fatal("--state path too long");
- defer if (private) for ([_][]const u8{ "", ".inputs", ".store" }) |suffix| {
- var from: [std.fs.max_path_bytes + 16]u8 = undefined;
- var to: [std.fs.max_path_bytes + 16]u8 = undefined;
- const a = std.mem.printSentinel(&from, "{s}{s}", .{ options.state, suffix }, 0) catch continue;
- const b = std.mem.printSentinel(&to, "{s}{s}", .{ given, suffix }, 0) catch continue;
- _ = if (options.export_to != null) std.os.linux.unlink(a.ptr) else std.os.linux.rename(a.ptr, b.ptr);
- };
+ if (options.state.len == 0 and (script_path != null or options.export_to != null)) options.state = "sketch.xitdb";
+ // A scripted run from fresh state, or an export, touches no save.
+ if (!((script_path != null or options.export_to != null) and options.fresh)) sketchbookDir(init.io, options.state);
sdl_heap.install();
{
@@ -124,27 +101,144 @@ 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 persistent state (default: sketch.state)
- \\ --headless offscreen video, silent audio, no vsync
- \\ --script FILE play a script instead of reading devices
- \\ --fresh start from default state: no snapshots or recordings
- \\ --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 = "NAME|/SOCKET", .doc = "the 9P tree (README, ctl, state/, screen.png...), posted as sketchbook/NAME\n(a run in a window posts its own name), or at a socket path" },
+ .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/<name>/<name>.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] [fs VERB [PATH [WORDS...]]]\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[@min(head.len, pad.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;
+};
+
+/// `fs VERB [PATH [WORDS]]`: cloud9's verbs on the sketch's tree. The
+/// running sketch's, posted as sketchbook/<name> (or at --9p); with none,
+/// the same tree served here from the save's newest State (--state's, or
+/// the default save), else from the State's defaults: README, commands,
+/// state/ answer, and the rest say the sketch is not running. No window.
+fn fs(init: std.process.Init, linked: ?abi.Sketch, options: Host.Options, words: []const []const u8) !u8 {
+ const gpa = init.gpa;
+ const io = init.io;
+ const env = init.environ_map;
+ var in_buf: [4096]u8 = undefined;
+ var out_buf: [4096]u8 = undefined;
+ var err_buf: [1024]u8 = undefined;
+ var in = std.Io.File.stdin().reader(io, &in_buf);
+ var out = std.Io.File.stdout().writer(io, &out_buf);
+ var err = std.Io.File.stderr().writer(io, &err_buf);
+ const user = env.get("USER") orelse "sketchbook";
+ var library: ?Library = null;
+ defer if (library) |*l| l.close();
+ const sketch = linked orelse blk: {
+ library = try Library.openFresh(io, options.library orelse fatal("fs needs the sketch library first: sketchbook LIBRARY fs ...", .{}), Host.scratchDir(env), 0);
+ break :blk library.?.sketch;
+ };
+ const info = sketch.info();
+ const no_env = [_:null]?[*:0]const u8{};
+ var f: c9.Fsys = undefined;
+ var path_buf: [c9.post.sun_path_len]u8 = undefined;
+ const where = options.ninep orelse info.name;
+ const path = if (std.mem.startsWith(u8, where, "/")) where else control.registered(env, where, &path_buf) catch "";
+ if (f.dial(io, &no_env, path, user)) |_| {
+ defer f.close();
+ return c9.verbs.run(&f, words, &in.interface, &out.interface, &err.interface);
+ } else |_| {}
+
+ var arena: std.heap.ArenaAllocator = .init(gpa);
+ defer arena.deinit();
+ const layout = try memory.Layout.copy(arena.allocator(), info.state);
+ const bytes = try arena.allocator().alignedAlloc(u8, .fromByteUnits(memory.page), layout.size);
+ @memset(bytes, 0);
+ sketch.defaults(.state, bytes.ptr);
+ var from = try std.fmt.allocPrint(arena.allocator(), "{s} is not running: this is its State's defaults (no save)", .{info.name});
+ var data_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const save = if (options.state.len > 0)
+ try std.fmt.allocPrint(arena.allocator(), "{s}.xitdb", .{Host.stemOf(options.state)})
+ else
+ try std.fmt.allocPrint(arena.allocator(), "{s}/{s}/{s}.xitdb", .{ env.get("XDG_DATA_HOME") orelse try std.fmt.bufPrint(&data_buf, "{s}/.local/share", .{env.get("HOME") orelse "."}), info.name, info.name });
+ if (Sessions.openRead(gpa, io, save)) |opened| {
+ var s = opened;
+ defer s.deinit();
+ var events: std.ArrayList(abi.Event) = .empty;
+ defer events.deinit(gpa);
+ if (try s.present(&events)) |key| {
+ defer key.free(gpa);
+ _ = try memory.restore(arena.allocator(), key.layout, key.state, layout, bytes, sketch.defaults);
+ from = try std.fmt.allocPrint(arena.allocator(), "{s} is not running: this is its save's newest State, frame {d} of {s}", .{ info.name, key.frame, save });
+ }
+ } else |_| {}
+ const commands = try arena.allocator().alloc([]const u8, info.commands.len);
+ for (commands, info.commands) |*to, word| to.* = word;
+ var server: control.Control = .{ .allocator = gpa, .path = undefined, .listener = -1, .offline = .{ .layout = layout, .bytes = bytes, .completions = commands, .from = from } };
+ var fds: [2]i32 = undefined;
+ if (std.c.socketpair(std.c.AF.UNIX, std.c.SOCK.STREAM | std.c.SOCK.CLOEXEC, 0, &fds) != 0) return error.SocketPair;
+ const thread = try std.Thread.spawn(.{}, control.Control.serveOffline, .{ &server, fds[0] });
+ defer thread.join();
+ try f.init(io, .{ .socket = .{ .handle = fds[1], .address = undefined } }, user);
+ defer f.close();
+ // A read answered here is not the running sketch's: said on stderr, so
+ // a script that reads before the sketch is up does not take it for one.
+ if (words.len > 0 and std.mem.eql(u8, words[0], "read")) {
+ try err.interface.print("{s}\n", .{from});
+ try err.interface.flush();
+ }
+ return c9.verbs.run(&f, words, &in.interface, &out.interface, &err.interface);
+}
+
+/// 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
+/// snapshot would commit it), and the state file an older build kept beside
+/// it (`<stem>.state`) is moved in, once, to be imported. A file is never
+/// replaced: when both exist, nothing moves.
+fn sketchbookDir(io: std.Io, state: []const u8) void {
+ const dir = std.fs.path.dirname(state) orelse return;
+ if (!std.mem.eql(u8, std.fs.path.basename(dir), ".sketchbook")) return;
+ const cwd = std.Io.Dir.cwd();
+ cwd.createDirPath(io, dir) catch return;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const ignore = std.fmt.bufPrint(&buf, "{s}/.gitignore", .{dir}) catch return;
+ cwd.writeFile(io, .{ .sub_path = ignore, .data = "*\n", .flags = .{ .exclusive = true } }) catch {};
+ var from_buf: [std.fs.max_path_bytes]u8 = undefined;
+ var to_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const parent = std.fs.path.dirname(dir) orelse ".";
+ const stem = Host.stemOf(std.fs.path.basename(state));
+ const from = std.fmt.bufPrintSentinel(&from_buf, "{s}/{s}.state", .{ parent, stem }, 0) catch return;
+ const to = std.fmt.bufPrintSentinel(&to_buf, "{s}/{s}.state", .{ dir, stem }, 0) catch return;
+ switch (std.os.linux.errno(std.os.linux.renameat2(std.os.linux.AT.FDCWD, from.ptr, std.os.linux.AT.FDCWD, to.ptr, .{ .NOREPLACE = true }))) {
+ .SUCCESS => std.debug.print("sketchbook: moved {s} to {s}\n", .{ from, to }),
+ .EXIST => std.debug.print("sketchbook: {s} and {s} both exist: nothing moved, {s} is used\n", .{ from, to, to }),
+ else => {},
+ }
+}
-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);
}
@@ -202,8 +296,10 @@ test {
_ = memory;
_ = fields;
_ = timeline;
+ _ = @import("Sessions.zig");
_ = @import("audio.zig");
_ = @import("Console.zig");
_ = @import("control.zig");
+ _ = @import("state_files.zig");
_ = @import("timing_marker.zig");
}