summaryrefslogtreecommitdiff
path: root/build.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-10-28 21:07:13 -0300
committerGabriel Schneider <[email protected]>2026-11-12 13:22:02 -0300
commit590ba7b9b579b97e34b51ab7e3460ebc85713343 (patch)
tree6a73a7570ff4f79f41deff078455877b9bc6571b /build.zig
parentbc8e6eb1bfef0c5e9b3c40fc1e4fd5a1659e2b03 (diff)
downloadsketchbook-590ba7b9b579b97e34b51ab7e3460ebc85713343.tar.gz
sketchbook-590ba7b9b579b97e34b51ab7e3460ebc85713343.zip
sketchbook: Zig 0.17, a Store on disk, requests, a scope (waveform, spectrum, spectrogram), audio codecs and fonts, web host
Diffstat (limited to 'build.zig')
-rw-r--r--build.zig385
1 files changed, 343 insertions, 42 deletions
diff --git a/build.zig b/build.zig
index 8de7f01..40cb49e 100644
--- a/build.zig
+++ b/build.zig
@@ -6,14 +6,21 @@
//!
//! const sb = sketchbook.init(b, .{ .target = target, .optimize = optimize });
//! const app = sb.app(.{ .name = "demo", .root_source_file = b.path("src/main.zig") });
-//! _ = app.addSteps(.{}); // run, lib, web, probe, e2e, test, install
+//! _ = app.addSteps(.{}); // run, lib, probe, e2e, test, install;
+//! // web and serve with `.web = .{}`
//!
//! or pick the pieces: `app.addLibrary()`, `app.addExecutable()`,
//! `app.addWeb(...)`, `app.addRun(...)`, `app.addScript(...)`,
-//! `app.addProbe(...)`, `app.addTest(...)`. For GPU shaders:
-//! `sb.addGlslLayouts(...)`, `sb.addGlslc(...)`, `sb.addSpirvModule(...)`.
-//! Each returns the ordinary `std.Build` objects, so anything can be
-//! extended or rewired.
+//! `app.addProbe(...)`, `app.addTest(...)`. GPU shaders are GLSL, built by
+//! `sb.addShaders(...)` into SPIR-V for native hosts and WGSL for the web;
+//! `sb.addGlslLayouts(...)` and `sb.addGlslc(...)` are its pieces. Each
+//! returns the ordinary `std.Build` objects, so anything can be extended or
+//! rewired.
+//!
+//! Tools, found on PATH when a step needs them: `glslc` (shaderc or the
+//! Vulkan SDK) for any shader, `naga` (`cargo install naga-cli`) only for
+//! the web build of a sketch with shaders, and `miniserve` and `openssl`
+//! only for `serve`.
const std = @import("std");
const Build = std.Build;
const translate_c = @import("translate_c");
@@ -59,26 +66,52 @@ pub fn build(b: *Build) void {
});
b.installArtifact(probe);
- var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .vector = undefined }, .host_exe = host_exe, .probe_exe = probe, .web = b.path("web"), .glsl = b.path("src/glsl.zig") };
+ var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .vector = undefined, .scope = undefined }, .host_exe = host_exe, .probe_exe = probe, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .shared = .create(b) };
- // Vector graphics: built with the same shader step apps use.
+ // Vector graphics: built with the same shader step apps use. Both forms
+ // of its shaders are exported, so apps' web builds can swap them too.
const vector_layouts = b.createModule(.{ .root_source_file = b.path("src/vector/layouts.zig") });
- const glsl = sb.addGlslLayouts(.{ .module = vector_layouts, .types = &.{ "Vertex", "Viewport", "Paint" } });
- const vector_shaders = sb.addSpirvModule(&.{
- .{ .name = "path_vert", .spirv = sb.addGlslc(.{ .source = b.path("src/vector/shaders/path.vert"), .include_dirs = &.{glsl.dir} }).spirv },
- .{ .name = "stencil_frag", .spirv = sb.addGlslc(.{ .source = b.path("src/vector/shaders/stencil.frag") }).spirv },
- .{ .name = "cover_frag", .spirv = sb.addGlslc(.{ .source = b.path("src/vector/shaders/cover.frag"), .include_dirs = &.{glsl.dir} }).spirv },
+ const vector_shaders = sb.addShaders(.{
+ .layouts = .{ .module = vector_layouts, .types = &.{ "Vertex", "Viewport", "Paint" } },
+ .sources = &.{ b.path("src/vector/shaders/path.vert"), b.path("src/vector/shaders/stencil.frag"), b.path("src/vector/shaders/cover.frag") },
});
+ b.modules.put(b.graph.arena, "vector_shaders", vector_shaders.module) catch @panic("OOM");
+ b.modules.put(b.graph.arena, "vector_shaders_web", vector_shaders.web) catch @panic("OOM");
const vector_imports: []const Build.Module.Import = &.{
.{ .name = "abi", .module = abi },
.{ .name = "vector_layouts", .module = vector_layouts },
- .{ .name = "vector_shaders", .module = vector_shaders },
+ .{ .name = "vector_shaders", .module = vector_shaders.module },
};
sb.modules.vector = b.addModule("vector", .{ .root_source_file = b.path("src/vector/root.zig"), .imports = vector_imports });
+ // Sound scopes: waveform, spectrogram, spectrum and oscilloscope of a
+ // stream of samples, analysed and drawn on the GPU.
+ const scope_layouts = b.createModule(.{ .root_source_file = b.path("src/scope/layouts.zig") });
+ const scope_shaders = sb.addShaders(.{
+ .layouts = .{ .module = scope_layouts, .types = &.{ "SpectrumParams", "WaveParams", "WaveView", "SpectrumView", "SpectrogramParams", "SpectrogramView" } },
+ .sources = &.{
+ b.path("src/scope/shaders/view.vert"),
+ b.path("src/scope/shaders/waveform.comp"),
+ b.path("src/scope/shaders/waveform.frag"),
+ b.path("src/scope/shaders/spectrogram.comp"),
+ b.path("src/scope/shaders/spectrogram.frag"),
+ b.path("src/scope/shaders/spectrum.comp"),
+ b.path("src/scope/shaders/spectrum.frag"),
+ },
+ });
+ b.modules.put(b.graph.arena, "scope_shaders", scope_shaders.module) catch @panic("OOM");
+ b.modules.put(b.graph.arena, "scope_shaders_web", scope_shaders.web) catch @panic("OOM");
+ const scope_imports: []const Build.Module.Import = &.{
+ .{ .name = "sketch", .module = sketch },
+ .{ .name = "scope_layouts", .module = scope_layouts },
+ .{ .name = "scope_shaders", .module = scope_shaders.module },
+ };
+ sb.modules.scope = b.addModule("scope", .{ .root_source_file = b.path("src/scope/root.zig"), .imports = scope_imports });
+
const test_step = b.step("test", "Run unit tests and the reload end-to-end test");
for ([_]*Build.Module{
b.createModule(.{ .root_source_file = b.path("src/vector/root.zig"), .target = target, .optimize = optimize, .imports = vector_imports }),
+ b.createModule(.{ .root_source_file = b.path("src/scope/root.zig"), .target = target, .optimize = optimize, .imports = scope_imports }),
b.createModule(.{ .root_source_file = b.path("src/glsl.zig"), .target = target, .optimize = optimize }),
b.createModule(.{ .root_source_file = b.path("src/abi.zig"), .target = target, .optimize = optimize }),
b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = &.{.{ .name = "abi", .module = abi }} }),
@@ -112,13 +145,20 @@ fn cModule(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.Optimi
.c_source_file = b.addWriteFiles().add("c.h",
\\#define SDL_DISABLE_OLD_NAMES
\\#include <SDL3/SDL.h>
- \\#include <sndfile.h>
+ \\#include "codecs.h"
+ \\#include "text.h"
),
.target = target,
.optimize = optimize,
});
translator.linkLibrary(sdl);
- translator.linkSystemLibrary("sndfile", .{});
+ translator.addIncludePath(b.path("vendor"));
+ translator.mod.addCSourceFile(.{ .file = b.path("vendor/codecs.c"), .flags = &.{"-fno-sanitize=undefined"} });
+ if (target.result.os.tag == .linux) {
+ translator.mod.addCSourceFile(.{ .file = b.path("vendor/text.c"), .flags = &.{"-std=c23"} });
+ translator.mod.linkSystemLibrary("pangocairo-1.0", .{ .use_pkg_config = .force });
+ translator.mod.linkSystemLibrary("pangoft2-1.0", .{ .use_pkg_config = .force });
+ }
return translator.mod;
}
@@ -168,24 +208,51 @@ pub const Options = struct {
pub fn init(b: *Build, options: Options) Sketchbook {
const dep = b.dependency(options.dependency, .{ .target = options.target, .optimize = options.optimize });
+ const shared: *Shared = .create(b);
+ for ([_][]const u8{ "vector_shaders", "scope_shaders" }) |name| {
+ shared.web_twins.put(b.graph.arena, dep.module(name), dep.module(b.fmt("{s}_web", .{name}))) catch @panic("OOM");
+ }
return .{
.b = b,
.target = options.target,
.optimize = options.optimize,
- .modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .vector = dep.module("vector") },
+ .modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .vector = dep.module("vector"), .scope = dep.module("scope") },
.host_exe = dep.artifact("sketchbook"),
.probe_exe = dep.artifact("sketchbook-probe"),
.web = dep.path("web"),
.glsl = dep.path("src/glsl.zig"),
+ .shared = shared,
};
}
+/// What every copy of a `Sketchbook` value shares.
+const Shared = struct {
+ /// SPIR-V shader modules and their WGSL twins (see `addShaders`).
+ web_twins: std.AutoArrayHashMapUnmanaged(*Build.Module, *Build.Module) = .empty,
+ /// Lookups of external tools, made once, run when a step needs them.
+ glslc: ?Build.LazyPath = null,
+ naga: ?Build.LazyPath = null,
+ miniserve: ?Build.LazyPath = null,
+ openssl: ?Build.LazyPath = null,
+ /// A self-signed certificate and its key, for `addServe`.
+ certificate: ?Certificate = null,
+
+ const Certificate = struct { cert: Build.LazyPath, key: Build.LazyPath };
+
+ fn create(b: *Build) *Shared {
+ const shared = b.graph.arena.create(Shared) catch @panic("OOM");
+ shared.* = .{};
+ return shared;
+ }
+};
+
pub const Sketchbook = struct {
b: *Build,
target: Build.ResolvedTarget,
optimize: std.builtin.OptimizeMode,
- /// `vector`: SVG, cubic geometry, and CPU and GPU renderers.
- modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, vector: *Build.Module },
+ /// `vector`: SVG, cubic geometry, and CPU and GPU renderers. `scope`:
+ /// waveform, spectrogram, spectrum and oscilloscope views of a sound.
+ modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, vector: *Build.Module, scope: *Build.Module },
/// The generic host: loads and hot-reloads a sketch library.
host_exe: *Build.Step.Compile,
/// Prints any sketch's state file.
@@ -194,6 +261,7 @@ pub const Sketchbook = struct {
web: Build.LazyPath,
/// The GLSL declaration generator (see `addGlslLayouts`).
glsl: Build.LazyPath,
+ shared: *Shared,
pub const GlslLayouts = struct {
run: *Build.Step.Run,
@@ -238,36 +306,160 @@ pub const Sketchbook = struct {
spirv: Build.LazyPath,
};
- /// One GLSL file compiled to SPIR-V by `glslc` (from the Vulkan SDK or
- /// shaderc, on PATH).
+ /// One GLSL file compiled to SPIR-V by `glslc`.
pub fn addGlslc(sb: Sketchbook, options: struct {
source: Build.LazyPath,
include_dirs: []const Build.LazyPath = &.{},
+ /// Macros defined for the source, as `NAME` or `NAME=VALUE`.
+ defines: []const []const u8 = &.{},
target_env: []const u8 = "vulkan1.1",
optimize: bool = true,
}) Glslc {
const b = sb.b;
- const run = b.addSystemCommand(&.{ "glslc", b.fmt("--target-env={s}", .{options.target_env}) });
+ const name = std.fs.path.basename(options.source.getDisplayName());
+ const run = Build.Step.Run.create(b, b.fmt("glslc {s}", .{name}));
+ run.addFileArg(sb.glslc());
+ run.addArg(b.fmt("--target-env={s}", .{options.target_env}));
if (options.optimize) run.addArg("-O");
+ for (options.defines) |define| run.addArg(b.fmt("-D{s}", .{define}));
for (options.include_dirs) |dir| run.addPrefixedDirectoryArg("-I", dir);
+ // The files the source #includes, for the cache: editing one
+ // recompiles every shader that includes it.
+ run.addArgs(&.{ "-MD", "-MF" });
+ _ = run.addDepFileOutputArg(b.fmt("{s}.d", .{name}));
run.addArg("-o");
- const spirv = run.addOutputFileArg(b.fmt("{s}.spv", .{std.fs.path.basename(options.source.getDisplayName())}));
+ const spirv = run.addOutputFileArg(b.fmt("{s}.spv", .{name}));
run.addFileArg(options.source);
return .{ .run = run, .spirv = spirv };
}
- /// A module declaring each SPIR-V file as `pub const <name>: []const u8`,
- /// 4-byte aligned as Vulkan reads it.
- pub fn addSpirvModule(sb: Sketchbook, shaders: []const struct { name: []const u8, spirv: Build.LazyPath }) *Build.Module {
+ pub const Shaders = struct {
+ /// SPIR-V, one `pub const <name>: []const u8` per shader, 4-byte
+ /// aligned as Vulkan reads it: the module to import.
+ module: *Build.Module,
+ /// The same declarations in WGSL, translated from the SPIR-V by
+ /// `naga`. The web build puts it in place of `module` wherever
+ /// `module` is imported (see `addWeb`), so sketches import one
+ /// module and never choose.
+ web: *Build.Module,
+ };
+
+ /// GLSL shaders for every host: compiled to SPIR-V, and for the web
+ /// compiled again with `SKETCHBOOK_WEB` defined and translated to WGSL,
+ /// which only the web build waits for. Each source is declared under its
+ /// file name with dots as underscores: `tuner.comp` is `tuner_comp`.
+ ///
+ /// WGSL lacks a little GLSL has: no write-only storage buffers (declare
+ /// them `buffer`), and no `coherent` (WGSL's barriers make storage
+ /// writes visible to the workgroup anyway, so leave it out under
+ /// `#ifdef SKETCHBOOK_WEB`).
+ pub fn addShaders(sb: Sketchbook, options: struct {
+ sources: []const Build.LazyPath,
+ /// Uniform and vertex layouts generated from Zig types, which the
+ /// sources `#include` as `<Type>.glsl` (see `addGlslLayouts`).
+ layouts: ?struct { module: *Build.Module, types: []const []const u8 } = null,
+ /// More `#include` directories.
+ include_dirs: []const Build.LazyPath = &.{},
+ }) Shaders {
const b = sb.b;
- const files = b.addWriteFiles();
- var source: std.ArrayList(u8) = .empty;
- for (shaders) |shader| {
- const file = b.fmt("{s}.spv", .{shader.name});
- _ = files.addCopyFile(shader.spirv, file);
- source.print(b.allocator, "const {s}_words align(4) = @embedFile(\"{s}\").*;\npub const {s}: []const u8 = &{s}_words;\n", .{ shader.name, file, shader.name, shader.name }) catch @panic("OOM");
+ const include_dirs = b.graph.arena.alloc(Build.LazyPath, options.include_dirs.len + 1) catch @panic("OOM");
+ @memcpy(include_dirs[0..options.include_dirs.len], options.include_dirs);
+ var dirs: []const Build.LazyPath = include_dirs[0..options.include_dirs.len];
+ if (options.layouts) |layouts| {
+ include_dirs[options.include_dirs.len] = sb.addGlslLayouts(.{ .module = layouts.module, .types = layouts.types }).dir;
+ dirs = include_dirs;
+ }
+
+ const native = b.addWriteFiles();
+ const web = b.addWriteFiles();
+ var native_source: std.ArrayList(u8) = .empty;
+ var web_source: std.ArrayList(u8) = .empty;
+ for (options.sources) |source| {
+ const file = std.fs.path.basename(source.getDisplayName());
+ const name = std.mem.replaceOwned(u8, b.graph.arena, file, ".", "_") catch @panic("OOM");
+ const spirv = sb.addGlslc(.{ .source = source, .include_dirs = dirs }).spirv;
+ _ = native.addCopyFile(spirv, b.fmt("{s}.spv", .{name}));
+ native_source.print(b.graph.arena, "const {s}_words align(4) = @embedFile(\"{s}.spv\").*;\npub const {s}: []const u8 = &{s}_words;\n", .{ name, name, name, name }) catch @panic("OOM");
+
+ const translate = Build.Step.Run.create(b, b.fmt("naga {s}", .{file}));
+ translate.addFileArg(sb.naga());
+ // SDL_GPU flips Vulkan's viewport, so the SPIR-V's clip space is
+ // already WebGPU's (y up): naga must not flip it again.
+ translate.addArg("--keep-coordinate-space");
+ translate.addFileArg(sb.addGlslc(.{ .source = source, .include_dirs = dirs, .defines = &.{"SKETCHBOOK_WEB"} }).spirv);
+ _ = web.addCopyFile(translate.addOutputFileArg(b.fmt("{s}.wgsl", .{name})), b.fmt("{s}.wgsl", .{name}));
+ web_source.print(b.graph.arena, "pub const {s}: []const u8 = @embedFile(\"{s}.wgsl\");\n", .{ name, name }) catch @panic("OOM");
+ }
+ const shaders: Shaders = .{
+ .module = b.createModule(.{ .root_source_file = native.add("spirv.zig", native_source.items) }),
+ .web = b.createModule(.{ .root_source_file = web.add("wgsl.zig", web_source.items) }),
+ };
+ sb.shared.web_twins.put(b.graph.arena, shaders.module, shaders.web) catch @panic("OOM");
+ return shaders;
+ }
+
+ /// `glslc`, from shaderc or the Vulkan SDK.
+ fn glslc(sb: Sketchbook) Build.LazyPath {
+ const sdk = if (sb.b.graph.environ_map.get("VULKAN_SDK")) |dir| sb.b.pathJoin(&.{ dir, "bin", "glslc" }) else "glslc";
+ return sb.program(&sb.shared.glslc, &.{ "glslc", sdk });
+ }
+
+ /// `naga`, from `cargo install naga-cli`: on PATH, or where cargo puts it.
+ fn naga(sb: Sketchbook) Build.LazyPath {
+ const env = &sb.b.graph.environ_map;
+ const cargo = if (env.get("CARGO_HOME")) |home| sb.b.pathJoin(&.{ home, "bin", "naga" }) else if (env.get("HOME")) |home| sb.b.pathJoin(&.{ home, ".cargo", "bin", "naga" }) else "naga";
+ return sb.program(&sb.shared.naga, &.{ "naga", cargo });
+ }
+
+ /// A tool found on PATH when a step needs it, looked up once.
+ fn program(sb: Sketchbook, slot: *?Build.LazyPath, names: []const []const u8) Build.LazyPath {
+ if (slot.* == null) slot.* = sb.b.findProgramLazy(.{ .names = names });
+ return slot.*.?;
+ }
+
+ /// A self-signed certificate for serving over https, made once by
+ /// `openssl` and kept in the cache: browsers ask to trust it once.
+ fn certificate(sb: Sketchbook) Shared.Certificate {
+ if (sb.shared.certificate == null) {
+ const b = sb.b;
+ const run = Build.Step.Run.create(b, "self-signed certificate");
+ run.addFileArg(sb.program(&sb.shared.openssl, &.{"openssl"}));
+ run.addArgs(&.{ "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", "-days", "3650", "-subj", "/CN=sketchbook" });
+ run.addArg("-keyout");
+ const key = run.addOutputFileArg("key.pem");
+ run.addArg("-out");
+ // Its progress on stderr is not a warning.
+ _ = run.captureStdErr(.{});
+ sb.shared.certificate = .{ .cert = run.addOutputFileArg("cert.pem"), .key = key };
+ }
+ return sb.shared.certificate.?;
+ }
+
+ /// `module` as the web build compiles it: each shader module in its
+ /// imports, however deep, replaced by its WGSL twin, and each module on
+ /// the way copied to import the copy. Modules nothing swaps below are
+ /// shared as they are.
+ fn webModule(sb: Sketchbook, module: *Build.Module, copies: *std.AutoArrayHashMapUnmanaged(*Build.Module, *Build.Module)) *Build.Module {
+ const arena = sb.b.graph.arena;
+ if (sb.shared.web_twins.get(module)) |twin| return twin;
+ if (copies.get(module)) |done| return done;
+ // An import cycle comes back here as itself: unchanged, which is
+ // right unless a shader module hides inside the cycle.
+ copies.put(arena, module, module) catch @panic("OOM");
+ var swapped = false;
+ const imports = arena.alloc(*Build.Module, module.import_table.count()) catch @panic("OOM");
+ for (module.import_table.values(), imports) |imported, *web| {
+ web.* = sb.webModule(imported, copies);
+ swapped = swapped or web.* != imported;
}
- return b.createModule(.{ .root_source_file = files.add("spirv.zig", source.items) });
+ if (!swapped) return module;
+ const copy = arena.create(Build.Module) catch @panic("OOM");
+ copy.init(module.owner, .{ .existing = module });
+ copy.import_table = .empty;
+ copy.cached_graph = .{ .modules = &.{}, .names = &.{} };
+ for (module.import_table.keys(), imports) |name, web| copy.addImport(name, web);
+ copies.put(arena, module, copy) catch @panic("OOM");
+ return copy;
}
pub fn app(sb: Sketchbook, options: App.Options) App {
@@ -340,11 +532,35 @@ pub const App = struct {
pub const WebOptions = struct {
/// Directories copied next to the page, under their own `dest`.
assets: []const Asset = &.{},
- /// Replaces the generic page; `{title}` is substituted either way.
+ /// Replaces the generic page; `{title}` is substituted either way,
+ /// and `{head}` with the links an installable app needs.
index_html: ?Build.LazyPath = null,
optimize: std.builtin.OptimizeMode = .ReleaseSafe,
+ /// Makes the page an installable app that opens offline.
+ pwa: ?Pwa = null,
pub const Asset = struct { source: Build.LazyPath, dest: []const u8 };
+
+ /// A progressive web app: a manifest naming it, icons, and a
+ /// service worker (`web/sw.js`) that keeps a copy of everything the
+ /// page fetches, network first, so it opens offline and still shows
+ /// each new build at once. Browsers allow service workers only in
+ /// secure contexts (https, or localhost).
+ pub const Pwa = struct {
+ /// The app's name by default.
+ name: ?[]const u8 = null,
+ short_name: ?[]const u8 = null,
+ description: []const u8 = "",
+ /// CSS colours: behind the page while it starts, and the
+ /// browser's chrome around it.
+ background: []const u8 = "#000000",
+ theme: []const u8 = "#000000",
+ /// Square PNGs, served as `icon-<size>.png`. Browsers want 192
+ /// and 512 pixels to offer installing.
+ icons: []const Icon = &.{},
+
+ pub const Icon = struct { source: Build.LazyPath, size: u32 };
+ };
};
pub const Web = struct {
@@ -356,9 +572,12 @@ pub const App = struct {
/// The browser build, as one directory ready to serve.
pub fn addWeb(app: App, options: WebOptions) Web {
const b = app.sb.b;
+ var copies: std.AutoArrayHashMapUnmanaged(*Build.Module, *Build.Module) = .empty;
+ var web_app = app;
+ web_app.module = app.sb.webModule(app.module, &copies);
const wasm = b.addExecutable(.{
.name = "sketch",
- .root_module = app.wrap("comptime { @import(\"sketch\").web.exportWeb(@import(\"app\")); }", b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .freestanding }), options.optimize),
+ .root_module = web_app.wrap("comptime { @import(\"sketch\").web.exportWeb(@import(\"app\")); }", b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .freestanding }), options.optimize),
});
wasm.entry = .disabled;
wasm.rdynamic = true;
@@ -373,11 +592,87 @@ pub const App = struct {
}));
page.addFileArg(options.index_html orelse app.sb.web.path(b, "index.html"));
page.addArg(app.name);
+ page.addArg(if (options.pwa) |pwa| app.addPwa(files, pwa) else "");
_ = files.addCopyFile(page.addOutputFileArg("index.html"), "index.html");
for (options.assets) |asset| _ = files.addCopyDirectory(asset.source, asset.dest, .{});
return .{ .wasm = wasm, .dir = files.getDirectory() };
}
+ /// Writes the manifest, icons and service worker into `files`, and
+ /// returns what the page's `<head>` needs for them.
+ fn addPwa(app: App, files: *Build.Step.WriteFile, pwa: WebOptions.Pwa) []const u8 {
+ const b = app.sb.b;
+ const arena = b.graph.arena;
+ const Icon = struct { src: []const u8, sizes: []const u8, type: []const u8 = "image/png", purpose: []const u8 = "any" };
+ const icons = arena.alloc(Icon, pwa.icons.len) catch @panic("OOM");
+ var touch: ?[]const u8 = null;
+ for (pwa.icons, icons) |icon, *entry| {
+ const name = b.fmt("icon-{d}.png", .{icon.size});
+ _ = files.addCopyFile(icon.source, name);
+ entry.* = .{ .src = name, .sizes = b.fmt("{d}x{d}", .{ icon.size, icon.size }) };
+ // iOS takes its home-screen icon from the page, not the manifest.
+ if (icon.size >= 180 and (touch == null or icon.size < 512)) touch = name;
+ }
+ const name = pwa.name orelse app.name;
+ const manifest = std.json.Stringify.valueAlloc(arena, .{
+ .name = name,
+ .short_name = pwa.short_name orelse name,
+ .description = pwa.description,
+ // Relative: the app works under any path it is served from.
+ .start_url = ".",
+ .scope = ".",
+ .display = "standalone",
+ .background_color = pwa.background,
+ .theme_color = pwa.theme,
+ .icons = icons,
+ }, .{ .whitespace = .indent_2 }) catch @panic("OOM");
+ _ = files.add("manifest.webmanifest", manifest);
+ _ = files.addCopyFile(app.sb.web.path(b, "sw.js"), "sw.js");
+ return b.fmt(
+ \\<link rel="manifest" href="manifest.webmanifest">
+ \\<meta name="theme-color" content="{s}">{s}
+ , .{ pwa.theme, if (touch) |icon| b.fmt("\n<link rel=\"apple-touch-icon\" href=\"{s}\">", .{icon}) else "" });
+ }
+
+ /// Serves an installed web build (`install`, under the prefix) with
+ /// `miniserve`, over https on port 8042 of every interface, until
+ /// stopped. Browsers give WebGPU and the microphone only to secure
+ /// contexts, and https makes the page one from any device on the
+ /// network, once the self-signed certificate is accepted; miniserve
+ /// prints the addresses as QR codes, for phones. It serves the installed
+ /// files, so `zig build web --watch` alongside shows each rebuild on
+ /// reload. Its defaults are environment variables, so miniserve's
+ /// options after `--` replace them (`-p 9000`).
+ pub fn addServe(app: App, install: *Build.Step.InstallDir) *Build.Step.Run {
+ const sb = app.sb;
+ const b = sb.b;
+ const prefix_relative = switch (install.options.install_dir) {
+ .prefix => install.options.install_subdir,
+ .custom => |dir| b.pathJoin(&.{ dir, install.options.install_subdir }),
+ else => @panic("addServe: install the web build under the prefix"),
+ };
+ const certificate = sb.certificate();
+ const run = Build.Step.Run.create(b, "miniserve");
+ run.addFileArg(sb.program(&sb.shared.miniserve, &.{"miniserve"}));
+ run.addPrefixedFileArg("--tls-cert=", certificate.cert);
+ run.addPrefixedFileArg("--tls-key=", certificate.key);
+ for ([_][2][]const u8{
+ .{ "MINISERVE_PORT", "8042" },
+ .{ "MINISERVE_INTERFACE", "0.0.0.0" },
+ .{ "MINISERVE_INDEX", "index.html" },
+ .{ "MINISERVE_DISABLE_INDEXING", "true" },
+ .{ "MINISERVE_QRCODE", "true" },
+ // A rebuilt sketch shows on reload.
+ .{ "MINISERVE_HEADER", "Cache-Control:no-cache" },
+ }) |env| run.setEnvironmentVariable(env[0], env[1]);
+ run.addPassthruArgs();
+ run.addDirectoryArg(b.graph.path(.install_prefix, prefix_relative));
+ run.step.dependOn(&install.step);
+ run.stdio = .inherit;
+ run.has_side_effects = true;
+ return run;
+ }
+
pub const RunOptions = struct {
/// State file, relative to the working directory.
state: ?[]const u8 = null,
@@ -393,10 +688,10 @@ pub const App = struct {
const run = b.addRunArtifact(app.sb.host_exe);
run.step.dependOn(&install.step);
run.addArgs(&.{ "--state", options.state orelse b.fmt("{s}.state", .{app.name}) });
- run.addArg(b.getInstallPath(.lib, library.out_filename));
+ run.addFileArg(b.graph.path(.install_lib, library.out_filename));
run.setCwd(options.cwd orelse b.path("."));
run.stdio = .inherit;
- if (b.args) |args| run.addArgs(args);
+ run.addPassthruArgs();
return run;
}
@@ -417,7 +712,8 @@ pub const App = struct {
run.addArgs(&.{ "--headless", "--fresh", "--script" });
run.addFileArg(script);
run.addArg("--state");
- _ = run.addOutputFileArg(b.fmt("{s}.state", .{app.name}));
+ // Named per script: runs of one app may share an output directory.
+ _ = run.addOutputFileArg(b.fmt("{s}-{s}.state", .{ app.name, std.fs.path.stem(script.getDisplayName()) }));
for (options.defines) |pair| run.addArgs(&.{ "--define", b.fmt("{s}={s}", .{ pair[0], pair[1] }) });
if (library) run.addArtifactArg(artifact);
run.setCwd(options.cwd orelse b.path("."));
@@ -433,7 +729,7 @@ pub const App = struct {
run.addArg(state orelse b.fmt("{s}.state", .{app.name}));
run.setCwd(b.path("."));
run.stdio = .inherit;
- if (b.args) |args| run.addArgs(args);
+ run.addPassthruArgs();
return run;
}
@@ -470,7 +766,8 @@ pub const App = struct {
/// The conventional wiring. Installs the executable, and adds:
/// `run` (host + hot reload), `lib` (rebuild the library; use `--watch`),
- /// `web`, `probe`, `e2e` (scripts) and `test`.
+ /// `web` and `serve` (with `web` options), `probe`, `e2e` (scripts) and
+ /// `test`.
pub fn addSteps(app: App, options: StepsOptions) Steps {
const b = app.sb.b;
const library = app.addLibrary();
@@ -484,7 +781,9 @@ pub const App = struct {
const web = if (options.web) |web_options| blk: {
const web = app.addWeb(web_options);
- b.step("web", "Build the browser version into zig-out/web").dependOn(&b.addInstallDirectory(.{ .source_dir = web.dir, .install_dir = .prefix, .install_subdir = "web" }).step);
+ const install = b.addInstallDirectory(.{ .source_dir = web.dir, .install_dir = .prefix, .install_subdir = "web" });
+ b.step("web", "Build the browser version into zig-out/web").dependOn(&install.step);
+ b.step("serve", "Serve zig-out/web over https on port 8042, to the local network too (-- -p PORT for another)").dependOn(&app.addServe(install).step);
break :blk web;
} else null;
@@ -499,7 +798,7 @@ pub const App = struct {
}
};
-/// Fills `{title}` in the page template.
+/// Fills `{title}` and `{head}` in the page template.
const page_tool =
\\const std = @import("std");
\\pub fn main(init: std.process.Init) !void {
@@ -507,11 +806,13 @@ const page_tool =
\\ _ = args.skip();
\\ const template = args.next().?;
\\ const title = args.next().?;
+ \\ const head = args.next().?;
\\ const out = args.next().?;
\\ const cwd = std.Io.Dir.cwd();
\\ const arena = init.arena.allocator();
\\ const source = try cwd.readFileAlloc(init.io, template, arena, .limited(1 << 20));
- \\ const page = try std.mem.replaceOwned(u8, arena, source, "{title}", title);
+ \\ const titled = try std.mem.replaceOwned(u8, arena, source, "{title}", title);
+ \\ const page = try std.mem.replaceOwned(u8, arena, titled, "{head}", head);
\\ try cwd.writeFile(init.io, .{ .sub_path = out, .data = page });
\\}
;