//! The sketchbook host: runs a sketch linked in, or loaded from a library //! 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"); pub const Host = @import("Host.zig"); 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. pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void { const gpa = init.gpa; var options: Host.Options = .{}; var script_path: ?[]const u8 = null; var defines: std.ArrayList([2][]const u8) = .empty; defer defines.deinit(gpa); var lines: std.ArrayList([]const u8) = .empty; defer lines.deinit(gpa); var args = init.minimal.args.iterate(); _ = args.skip(); while (args.next()) |arg| { 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 (options.export_to) |to| { 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", .{}); } 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(); { var host: Host = undefined; try host.init(gpa, init.io, init.environ_map, options, linked); defer host.deinit(); for (lines.items) |line| host.runLine(line, c.SDL_GetTicksNS()) catch {}; if (script_path) |path| { const source = try std.Io.Dir.cwd().readFileAlloc(init.io, path, gpa, .limited(1 << 20)); defer gpa.free(source); try script.run(&host, source, defines.items); } else try host.run(); } if (sdl_heap.leaked()) return error.LeakedSdlMemory; } /// 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//.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/ (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 (`.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(comptime fmt: []const u8, args: anytype) noreturn { std.debug.print("sketchbook: " ++ fmt ++ "\n", args); std.process.exit(2); } /// SDL's allocations go through a leak-checking allocator of their own, so a /// session that leaks SDL memory fails loudly at exit. const sdl_heap = struct { var debug: std.heap.DebugAllocator(.{ .backing_allocator_zeroes = false }) = .{}; const alignment: std.mem.Alignment = .of(std.c.max_align_t); const header = alignment.forward(@sizeOf(usize)); fn install() void { _ = c.SDL_SetMemoryFunctions(malloc, calloc, realloc, free); } fn leaked() bool { return debug.deinit() == .leak; } fn block(size: usize) ?[*]u8 { const total = std.math.add(usize, header, size) catch return null; const base = debug.allocator().rawAlloc(total, alignment, @returnAddress()) orelse return null; @as(*usize, @ptrCast(@alignCast(base))).* = total; return base + header; } fn whole(mem: *anyopaque) []u8 { const base: [*]u8 = @as([*]u8, @ptrCast(mem)) - header; return base[0..@as(*const usize, @ptrCast(@alignCast(base))).*]; } fn malloc(size: usize) callconv(.c) ?*anyopaque { return block(size); } fn calloc(n: usize, size: usize) callconv(.c) ?*anyopaque { const bytes = std.math.mul(usize, n, size) catch return null; const mem = block(bytes) orelse return null; @memset(mem[0..bytes], 0); return mem; } fn realloc(maybe: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque { const old = whole(maybe orelse return malloc(size)); const total = std.math.add(usize, header, size) catch return null; if (debug.allocator().rawRemap(old, alignment, total, @returnAddress())) |base| { @as(*usize, @ptrCast(@alignCast(base))).* = total; return base + header; } const new = block(size) orelse return null; @memcpy(new[0..@min(size, old.len - header)], old[header..][0..@min(size, old.len - header)]); debug.allocator().rawFree(old, alignment, @returnAddress()); return new; } fn free(maybe: ?*anyopaque) callconv(.c) void { debug.allocator().rawFree(whole(maybe orelse return), alignment, @returnAddress()); } }; test { _ = Host; _ = memory; _ = fields; _ = timeline; _ = @import("Sessions.zig"); _ = @import("audio.zig"); _ = @import("Console.zig"); _ = @import("control.zig"); _ = @import("state_files.zig"); _ = @import("timing_marker.zig"); }