summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/abi.zig14
-rw-r--r--src/host/Host.zig60
-rw-r--r--src/host/root.zig24
-rw-r--r--src/sketch/web.zig5
4 files changed, 93 insertions, 10 deletions
diff --git a/src/abi.zig b/src/abi.zig
index 35c399b..f88fca5 100644
--- a/src/abi.zig
+++ b/src/abi.zig
@@ -647,7 +647,9 @@ pub const Host = struct {
samples: *const fn (*anyopaque, Audio) []const f32,
/// The whole file, mapped for the life of the host; empty if missing.
readFile: *const fn (*anyopaque, []const u8) []const u8,
- env: *const fn (*anyopaque, []const u8) ?[]const u8,
+ /// See `Host.appendFile`: name, then bytes.
+ appendFile: *const fn (*anyopaque, [*]const u8, usize, [*]const u8, usize) callconv(.c) [*:0]const u8,
+ env:*const fn (*anyopaque, []const u8) ?[]const u8,
/// A monotonic clock in nanoseconds, for measuring, not for state:
/// `update` must use `Input` time to stay replayable.
clock: *const fn (*anyopaque) u64,
@@ -720,6 +722,16 @@ pub const Host = struct {
pub fn readFile(h: Host, path: []const u8) []const u8 {
return h.vtable.readFile(h.ctx, path);
}
+ /// Appends `bytes` to the sketch's file `name` (no `/` in it),
+ /// creating it: `<state>.<name>`, beside the state file (in
+ /// `.sketchbook/` under `zig build run`). Returns the file's path, for
+ /// `readFile`, or "" when nothing was written, which on the web is
+ /// always. Only `draw` and `command` can write, and a write is not
+ /// replayed, like sound. `readFile` maps a file once: what is appended
+ /// to it afterwards is not in what it returned.
+ pub fn appendFile(h: Host, name: []const u8, bytes: []const u8) []const u8 {
+ return std.mem.span(h.vtable.appendFile(h.ctx, name.ptr, name.len, bytes.ptr, bytes.len));
+ }
pub fn env(h: Host, name: []const u8) ?[]const u8 {
return h.vtable.env(h.ctx, name);
}
diff --git a/src/host/Host.zig b/src/host/Host.zig
index 4f1214a..05d08f7 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -107,6 +107,9 @@ commands: std.ArrayList(abi.Command) = .empty,
pending: std.ArrayList(abi.Event) = .empty,
input: abi.Input = .{},
files: std.StringHashMapUnmanaged([]align(memory.page) const u8) = .empty,
+/// The paths `appendFile` wrote, each once, 0-terminated: the sketch keeps
+/// them.
+written: std.StringHashMapUnmanaged(void) = .empty,
canvas: [2]u32 = .{ 0, 0 },
cursor: abi.Cursor = .arrow,
quit: bool = false,
@@ -259,6 +262,9 @@ pub fn deinit(self: *Host) void {
std.posix.munmap(entry.value_ptr.*);
}
self.files.deinit(self.gpa);
+ var written = self.written.keyIterator();
+ while (written.next()) |path| self.gpa.free(path.ptr[0 .. path.len + 1]);
+ self.written.deinit(self.gpa);
self.timeline.deinit();
self.session.deinit(self.gpa);
self.store.close();
@@ -1014,6 +1020,7 @@ const api: abi.Host.VTable = .{
.newSound = apiNewSound,
.samples = apiSamples,
.readFile = apiReadFile,
+ .appendFile = apiAppendFile,
.env = apiEnv,
.clock = apiClock,
};
@@ -1090,6 +1097,35 @@ fn apiReadFile(ctx: *anyopaque, path: []const u8) []const u8 {
self.files.put(self.gpa, key, bytes) catch self.gpa.free(key);
return bytes;
}
+fn apiAppendFile(ctx: *anyopaque, name_ptr: [*]const u8, name_len: usize, bytes: [*]const u8, len: usize) callconv(.c) [*:0]const u8 {
+ const self = hostOf(ctx);
+ const name = name_ptr[0..name_len];
+ if (name.len == 0 or std.mem.indexOfScalar(u8, name, '/') != null) {
+ self.print("appendFile: {s}: a name, not a path", .{name});
+ return "";
+ }
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const path = std.mem.print(&buf, "{s}.{s}", .{ self.options.state, name }) catch return "";
+ const file = std.Io.Dir.cwd().createFile(self.io, path, .{ .truncate = false }) catch |err| {
+ self.print("appendFile: {s}: {t}", .{ path, err });
+ return "";
+ };
+ defer file.close(self.io);
+ const end = file.length(self.io) catch return "";
+ file.writePositionalAll(self.io, bytes[0..len], end) catch |err| {
+ self.print("appendFile: {s}: {t}", .{ path, err });
+ return "";
+ };
+ const kept = self.written.getOrPut(self.gpa, path) catch return "";
+ if (!kept.found_existing) {
+ const copy = self.gpa.dupeSentinel(u8, path, 0) catch {
+ self.written.removeByPtr(kept.key_ptr);
+ return "";
+ };
+ kept.key_ptr.* = copy;
+ }
+ return @ptrCast(kept.key_ptr.*.ptr);
+}
fn apiClock(_: *anyopaque) u64 {
return c.SDL_GetTicksNS();
}
@@ -1295,3 +1331,27 @@ test "a state file's snapshots from before sessions become marks, and the file o
try std.testing.expectEqual(@as(usize, 1), again.slots);
try std.testing.expectEqual(@as(u32, 5), std.mem.readInt(u32, again.slot(0)[0..4], .little));
}
+
+test "appendFile appends to a file beside the state and names it for readFile" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ var host: Host = undefined;
+ host.gpa = std.testing.allocator;
+ host.io = io;
+ host.written = .empty;
+ host.options = .{ .state = try std.mem.print(&buf, ".zig-cache/tmp/{s}/t.state", .{&tmp.sub_path}) };
+ defer {
+ var written = host.written.keyIterator();
+ while (written.next()) |path| host.gpa.free(path.ptr[0 .. path.len + 1]);
+ host.written.deinit(host.gpa);
+ }
+ const name = "take-1.f32";
+ const path = std.mem.span(apiAppendFile(&host, name, name.len, "ab", 2));
+ try std.testing.expect(std.mem.endsWith(u8, path, "/t.state.take-1.f32"));
+ try std.testing.expectEqual(path.ptr, apiAppendFile(&host, name, name.len, "cd", 2));
+ const bytes = try tmp.dir.readFileAlloc(io, "t.state.take-1.f32", host.gpa, .unlimited);
+ defer host.gpa.free(bytes);
+ try std.testing.expectEqualStrings("abcd", bytes);
+}
diff --git a/src/host/root.zig b/src/host/root.zig
index 5889b42..c64af92 100644
--- a/src/host/root.zig
+++ b/src/host/root.zig
@@ -96,21 +96,27 @@ pub fn main(init: std.process.Init, linked: ?abi.Sketch) !void {
// 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 or store file,
- // nor fail on the store's lock (its sessions are in memory). An export's are
- // removed instead: nothing reads them, and a player may have the given
- // ones open.
+ // nor the files the sketch appends to, nor fail on the store's lock
+ // (its sessions are in memory). 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;
if (options.state.len == 0 and (script_path != null or options.export_to != null)) options.state = "sketch.state";
const given = options.state;
const private = (script_path != null or options.export_to != null) and options.fresh;
if (!private) sketchbookDir(init.io, given);
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{ "", ".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);
+ // Its files are `<private>` and `<private>.<name>`, beside the given one.
+ defer if (private) moved: {
+ const dir = std.Io.Dir.cwd().openDir(init.io, std.fs.path.dirname(given) orelse ".", .{ .iterate = true }) catch break :moved;
+ defer dir.close(init.io);
+ const from = std.fs.path.basename(options.state);
+ var it = dir.iterate();
+ while (it.next(init.io) catch null) |entry| {
+ if (!std.mem.startsWith(u8, entry.name, from) or (entry.name.len > from.len and entry.name[from.len] != '.')) continue;
+ var to: [std.fs.max_path_bytes]u8 = undefined;
+ const name = std.mem.print(&to, "{s}{s}", .{ std.fs.path.basename(given), entry.name[from.len..] }) catch continue;
+ if (options.export_to != null) dir.deleteFile(init.io, entry.name) catch {} else dir.rename(entry.name, dir, name, init.io) catch {};
+ }
};
sdl_heap.install();
diff --git a/src/sketch/web.zig b/src/sketch/web.zig
index 62a173a..fd8d7bb 100644
--- a/src/sketch/web.zig
+++ b/src/sketch/web.zig
@@ -414,6 +414,7 @@ fn Driver(comptime App: type) type {
.newSound = newSound,
.samples = samples,
.readFile = readFile,
+ .appendFile = appendFile,
.env = env,
.clock = clock,
};
@@ -478,6 +479,10 @@ fn Driver(comptime App: type) type {
fn readFile(_: *anyopaque, _: []const u8) []const u8 {
return &.{};
}
+ /// No files on the web: nothing is written, and the path is "".
+ fn appendFile(_: *anyopaque, _: [*]const u8, _: usize, _: [*]const u8, _: usize) callconv(.c) [*:0]const u8 {
+ return "";
+ }
fn env(_: *anyopaque, _: []const u8) ?[]const u8 {
return null;
}