summaryrefslogtreecommitdiff
path: root/src/anim/typst.zig
blob: 05a0d4e8a2482dec49da5aeec21c08a9a349bb51 (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
//! Build-time Typst for a scene file. `sb.addTypst` builds a small generator
//! around this file that imports the scene, whose `construct` has already
//! run at comptime and listed its Typst objects (`scene.typst_sources`),
//! compiles each with the `typst` CLI after the scene's `typst_preamble`,
//! and writes a module the player uses to find the SVGs by source:
//!
//!     typst.find(source) ?[]const u8
const std = @import("std");

/// Used when the scene declares no `typst_preamble`.
pub const default_preamble =
    \\#set page(width: auto, height: auto, margin: 3pt, fill: none)
;

pub fn generate(comptime SceneFile: type, comptime sources: []const []const u8, gpa: std.mem.Allocator, io: std.Io, out_path: []const u8, cache_path: []const u8) !void {
    const preamble: []const u8 = if (@hasDecl(SceneFile, "typst_preamble")) SceneFile.typst_preamble else default_preamble;
    const cwd = std.Io.Dir.cwd();
    var out = try cwd.createDirPathOpen(io, out_path, .{});
    defer out.close(io);
    var cache = try cwd.createDirPathOpen(io, cache_path, .{});
    defer cache.close(io);

    var table: std.ArrayList(u8) = .empty;
    var seen: std.AutoHashMapUnmanaged(u64, void) = .empty;
    for (sources) |source| {
        const key = std.hash.Wyhash.hash(0, source);
        if ((try seen.getOrPut(gpa, key)).found_existing) continue;
        const name = try std.fmt.allocPrint(gpa, "{x:0>16}.svg", .{key});
        // Cached by preamble and source together.
        const cache_name = try std.fmt.allocPrint(gpa, "{x:0>16}-{s}", .{ std.hash.Wyhash.hash(0, preamble), name });
        const svg = cache.readFileAlloc(io, cache_name, gpa, .limited(64 << 20)) catch try compile(gpa, io, cache, cache_name, preamble, source);
        try out.writeFile(io, .{ .sub_path = name, .data = svg });
        try table.print(gpa, "    .{{ 0x{x:0>16}, @embedFile(\"{s}\") }},\n", .{ key, name });
    }
    const module = try std.fmt.allocPrint(gpa,
        \\//! Generated by sketchbook's src/anim/typst.zig: the scene's Typst objects, as SVG.
        \\const std = @import("std");
        \\
        \\const table = [_]struct {{ u64, []const u8 }}{{
        \\{s}}};
        \\
        \\/// The SVG compiled from Typst `source`, if the scene declared it.
        \\pub fn find(source: []const u8) ?[]const u8 {{
        \\    const key = std.hash.Wyhash.hash(0, source);
        \\    for (table) |entry| if (entry[0] == key) return entry[1];
        \\    return null;
        \\}}
        \\
    , .{table.items});
    try out.writeFile(io, .{ .sub_path = "typst.zig", .data = module });
}

/// Runs `typst compile` on `preamble ++ source` and caches the SVG. The
/// root is `/`, so an absolute path in a source is the file's own path
/// (`#image("/home/me/manual.pdf", page: 31)`) and a relative one is
/// in the cache. Typst only reads what a source names, and a scene's
/// sources are its author's code, built by a build that can already read
/// anything. A file named this way is not part of the cache key: changed
/// in place, it keeps its old SVG until its entry in the cache goes.
fn compile(gpa: std.mem.Allocator, io: std.Io, cache: std.Io.Dir, name: []const u8, preamble: []const u8, source: []const u8) ![]const u8 {
    const typ = try std.fmt.allocPrint(gpa, "{s}.typ", .{name});
    try cache.writeFile(io, .{ .sub_path = typ, .data = try std.mem.concat(gpa, u8, &.{ preamble, "\n", source, "\n" }) });
    const result = try std.process.run(gpa, io, .{
        .argv = &.{ "typst", "compile", "--root", "/", "--format", "svg", typ, name },
        .cwd = .{ .dir = cache },
    });
    if (result.term != .exited or result.term.exited != 0) {
        std.debug.print("typst failed on:\n{s}\n{s}\n", .{ source, result.stderr });
        return error.TypstFailed;
    }
    return cache.readFileAlloc(io, name, gpa, .limited(64 << 20));
}