diff --git a/build.zig b/build.zig index 25df881bf..fadf1539b 100644 --- a/build.zig +++ b/build.zig @@ -137,6 +137,7 @@ pub fn build(b: *std.build.Builder) !void { const main_test = b.addTest("src/main_wasm.zig"); main_test.setTarget(.{ .cpu_arch = .wasm32, .os_tag = .wasi }); main_test.addOptions("build_options", exe_options); + main_test.addPackage(js.pkg); test_step.dependOn(&main_test.step); } diff --git a/src/font/Atlas.zig b/src/font/Atlas.zig index 4259d5dda..a48edb966 100644 --- a/src/font/Atlas.zig +++ b/src/font/Atlas.zig @@ -307,7 +307,7 @@ pub fn clear(self: *Atlas) void { pub const Wasm = struct { // If you're copying this file (Atlas.zig) out to a separate project, // just replace this with the allocator you want to use. - const wasm = @import("../wasm.zig"); + const wasm = @import("../os/wasm.zig"); const alloc = wasm.alloc; export fn atlas_new(size: u32, format: u8) ?*Atlas { diff --git a/src/font/face/web_canvas.zig b/src/font/face/web_canvas.zig index 9710c810e..13d0252e8 100644 --- a/src/font/face/web_canvas.zig +++ b/src/font/face/web_canvas.zig @@ -73,7 +73,7 @@ pub const Face = struct { /// The wasm-compatible API. pub const Wasm = struct { - const wasm = @import("../../wasm.zig"); + const wasm = @import("../../os/wasm.zig"); const alloc = wasm.alloc; export fn face_new(ptr: [*]const u8, len: usize, pts: u16) ?*Face { diff --git a/src/main_wasm.zig b/src/main_wasm.zig index 5c4bdbf45..81f8265d8 100644 --- a/src/main_wasm.zig +++ b/src/main_wasm.zig @@ -1,5 +1,6 @@ // This is the main file for the WASM module. The WASM module has to // export a C ABI compatible API. -pub usingnamespace @import("wasm.zig"); +pub usingnamespace @import("os/wasm.zig"); +pub usingnamespace @import("os/wasm/log.zig"); pub usingnamespace @import("font/main.zig"); diff --git a/src/wasm.zig b/src/os/wasm.zig similarity index 100% rename from src/wasm.zig rename to src/os/wasm.zig diff --git a/src/os/wasm/log.zig b/src/os/wasm/log.zig new file mode 100644 index 000000000..b1957d05a --- /dev/null +++ b/src/os/wasm/log.zig @@ -0,0 +1,27 @@ +const std = @import("std"); +const builtin = @import("builtin"); +const wasm = @import("../wasm.zig"); + +// The function std.log will call. +pub fn log( + comptime level: std.log.Level, + comptime scope: @TypeOf(.EnumLiteral), + comptime format: []const u8, + args: anytype, +) void { + // Build the string + const level_txt = comptime level.asText(); + const prefix = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): "; + const txt = level_txt ++ prefix ++ format; + const str = nosuspend std.fmt.allocPrint(wasm.alloc, txt, args) catch return; + defer wasm.alloc.free(str); + + // Send it over to the JS side + JS.log(str.ptr, str.len); +} + +// We wrap our externs in this namespace so we can reuse symbols, otherwise +// "log" would collide. +const JS = struct { + extern "env" fn log(ptr: [*]const u8, len: usize) void; +};