summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-17 09:06:20 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commit303478956e0086467a9073d7f6fa67b51b6580ad (patch)
tree6c69e13eef575b514433373893e1f14c435b4f1a
parentc94455e1a8d2a430d8dcd74603bcd0d7b27aeb68 (diff)
downloadsketchbook-303478956e0086467a9073d7f6fa67b51b6580ad.tar.gz
sketchbook-303478956e0086467a9073d7f6fa67b51b6580ad.zip
text: sk.text measures anywhere, Frame.paragraph wraps, aligns, spans, reveals and finds a caret
The ABI's one text entry is textRun (Host.VTable.textSize goes): a run in a face at a scale, as data, its advance and line box and each byte's x, a pure function of the font, the scale and the bytes, never of the display; and font, a face for a sketch's own TTF/OTF bytes (abi.Face is non-exhaustive: faces past the ten are a sketch's). The native host serves them from vendor/text.c (sk_text_run, sk_text_font), the web host from canvas measureText and FontFace (web/host.js), and the web draws each run in the page's monospace or sans-serif in the face's weight and style instead of 8 px a character. src/sketch/text.zig (sk.text) does the rest in plain Zig, the same on every host: size, layout and font anywhere, update included (the glue sets the host before each call into the sketch; a test binary has none and calls sketchbook-text directly, which App.addTest now links); a Paragraph is a face, scale and colour, a width to wrap at spaces, an alignment, spans (from a byte on: a colour, a face, a scale), reveal (the first N glyphs drawn, the layout the whole text's) and a caret byte, and its Layout the size, lines, glyphs and the caret's place. f.paragraph draws one, a Command.text a piece. f.text, f.textIn and f.print are a paragraph with no width when the bytes hold a \n, else the one command they were; host.textSize and textSizeIn stay, one line through textRun. Test: sk.text's own tests (a wrap, the space not counted, centred and right, a caret at a line's start and end and after a \n, a span twice the size, a word wider than the width, an empty text; reveal drawing the first glyphs of the same layout), run through sketchbook-text; and test/text.zig draws a centred paragraph with a red and a double-size span and a caret from its Layout, which test/text.script pins. zig build test-text runs these and the atlas's comparison with pardes's raster. Every other pinned pixel of test/text.script holds: the lines it pins are the same pixels Pango drew. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
-rw-r--r--build.zig24
-rw-r--r--src/abi.zig40
-rw-r--r--src/host/Host.zig12
-rw-r--r--src/host/TimingAtlas.zig3
-rw-r--r--src/host/gfx.zig13
-rw-r--r--src/sketch/root.zig26
-rw-r--r--src/sketch/text.zig281
-rw-r--r--src/sketch/web.zig25
-rw-r--r--test/text.script8
-rw-r--r--test/text.zig9
-rw-r--r--vendor/text.c27
-rw-r--r--vendor/text.h6
-rw-r--r--web/host.js53
13 files changed, 479 insertions, 48 deletions
diff --git a/build.zig b/build.zig
index eaa4454..ccec959 100644
--- a/build.zig
+++ b/build.zig
@@ -109,12 +109,16 @@ pub fn build(b: *Build) void {
b.step("test-sessions", "Test the sessions database: frames, keyframes, marks, clips").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{"session"} })).step);
b.step("test-presentation", "Test presentation feedback, pacing and trace snapshots").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{"presentation"} })).step);
+ // The sketch library's tests measure text with no host: through
+ // sketchbook-text, as an app's tests do (`App.addTest`).
+ const sketch_tests = b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = sketch_imports });
+ sketch_tests.linkLibrary(text_library);
const test_audio = b.step("test-audio", "Test sound: the voice mixer (reconciling, limiting, pitch, groups), sfxr, and a made sound played as a voice");
test_audio.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "voice", "mixer" } })).step);
- test_audio.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = sketch_imports }), .filters = &.{"sfxr"} })).step);
+ test_audio.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = sketch_tests, .filters = &.{"sfxr"} })).step);
const setup_tests = b.step("test-setup", "Test resource setup lifecycle and arguments");
- for ([_]*Build.Module{ host, b.createModule(.{ .root_source_file = b.path("src/sketch/root.zig"), .target = target, .optimize = optimize, .imports = sketch_imports }) }) |module| setup_tests.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module, .filters = &.{"setup"} })).step);
+ for ([_]*Build.Module{ host, sketch_tests }) |module| setup_tests.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module, .filters = &.{"setup"} })).step);
const host_exe = b.addExecutable(.{
.name = "sketchbook",
@@ -127,7 +131,7 @@ pub fn build(b: *Build) void {
});
b.installArtifact(host_exe);
- var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .tracy = tracy, .vector = undefined, .scope = undefined, .anim = undefined, .gltf = gltf, .cloud9 = cloud9 }, .host_exe = host_exe, .gltf_generator = gltf_generator, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .anim_dir = b.path("src/anim"), .gltf_render_dir = b.path("src/gltf_render"), .script_optimize = optimize, .shared = .create(b) };
+ var sb: Sketchbook = .{ .b = b, .target = target, .optimize = optimize, .modules = .{ .abi = abi, .sketch = sketch, .host = host, .tracy = tracy, .vector = undefined, .scope = undefined, .anim = undefined, .gltf = gltf, .cloud9 = cloud9 }, .host_exe = host_exe, .text = text_library, .gltf_generator = gltf_generator, .web = b.path("web"), .glsl = b.path("src/glsl.zig"), .tools = b.path("tools"), .anim_dir = b.path("src/anim"), .gltf_render_dir = b.path("src/gltf_render"), .script_optimize = optimize, .shared = .create(b) };
// 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.
@@ -185,7 +189,7 @@ pub fn build(b: *Build) void {
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 = sketch_imports }),
+ sketch_tests,
b.createModule(.{ .root_source_file = b.path("src/math/root.zig"), .target = target, .optimize = optimize }),
b.createModule(.{ .root_source_file = b.path("src/host/root.zig"), .target = target, .optimize = optimize, .imports = &.{ .{ .name = "abi", .module = abi }, .{ .name = "c", .module = c }, .{ .name = "gpu", .module = gpu }, .{ .name = "tracy", .module = tracy }, .{ .name = "cloud9", .module = cloud9 }, .{ .name = "xitdb", .module = xitdb }, .{ .name = "font_atlas", .module = font_atlas } } }),
}) |module| test_step.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = module })).step);
@@ -264,7 +268,12 @@ pub fn build(b: *Build) void {
test_web.dependOn(&render_web.step);
// `Host.textSize` against the text drawn (test/text.zig).
const text = sb.app(.{ .name = "text", .root_source_file = b.path("test/text.zig") });
- test_step.dependOn(&text.addScript(text.addExecutable(), b.path("test/text.script"), .{}).step);
+ const text_script = text.addScript(text.addExecutable(), b.path("test/text.script"), .{});
+ test_step.dependOn(&text_script.step);
+ const test_text = b.step("test-text", "Test text: layout (sketch.text), the atlas's rasters against pardes's, and test/text.script");
+ test_text.dependOn(&text_script.step);
+ test_text.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = sketch_tests, .filters = &.{"paragraph"} })).step);
+ test_text.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{"pardes's"} })).step);
// A sound the sketch made, as a voice: once per serial, not again on a
// replay (test/voices.zig).
const voices = sb.app(.{ .name = "voices", .root_source_file = b.path("test/voices.zig") });
@@ -831,6 +840,7 @@ pub fn init(b: *Build, options: Options) Sketchbook {
.optimize = options.optimize,
.modules = .{ .abi = dep.module("abi"), .sketch = dep.module("sketch"), .host = dep.module("host"), .tracy = dep.module("tracy"), .vector = dep.module("vector"), .scope = dep.module("scope"), .anim = dep.module("anim"), .gltf = dep.module("gltf"), .cloud9 = dep.module("cloud9") },
.host_exe = dep.artifact("sketchbook"),
+ .text = dep.artifact("sketchbook-text"),
.gltf_generator = dep.artifact("gltf-bindings"),
.web = dep.path("web"),
.glsl = dep.path("src/glsl.zig"),
@@ -884,6 +894,9 @@ pub const Sketchbook = struct {
modules: struct { abi: *Build.Module, sketch: *Build.Module, host: *Build.Module, tracy: *Build.Module, vector: *Build.Module, scope: *Build.Module, anim: *Build.Module, gltf: *Build.Module, cloud9: *Build.Module },
/// The generic host: loads and hot-reloads a sketch library.
host_exe: *Build.Step.Compile,
+ /// FreeType, HarfBuzz and vendor/text.c: what the host measures text
+ /// with, linked into an app's tests (`App.addTest`) so they measure too.
+ text: *Build.Step.Compile,
/// `host.js` and the `index.html` template.
web: Build.LazyPath,
/// The GLSL declaration generator (see `addGlslLayouts`).
@@ -1636,6 +1649,7 @@ pub const App = struct {
.imports = app.imports,
});
if (options.root_source_file != null) module.addImport("app", app.module);
+ module.linkLibrary(app.sb.text);
return b.addTest(.{ .root_module = module });
}
diff --git a/src/abi.zig b/src/abi.zig
index 6411b0d..e5fe372 100644
--- a/src/abi.zig
+++ b/src/abi.zig
@@ -62,9 +62,15 @@ pub const Color = extern struct {
/// The face a text is set in: the Go family, and JetBrains Mono NL (`code`,
/// without ligatures; its medium weight for small sizes on a dark ground)
/// for programs, all bundled with the native host. Mono is for data, sans
-/// for what is said about it. The web host has one face, the page's
-/// `monospace`.
-pub const Face = enum(u8) { mono, mono_bold, mono_italic, sans, sans_medium, sans_bold, code, code_bold, code_italic, code_medium };
+/// for what is said about it. Past these ten, a sketch's own fonts
+/// (`Host.VTable.font`). The web host draws them in the page's
+/// `monospace` and `sans-serif`.
+pub const Face = enum(u8) { mono, mono_bold, mono_italic, sans, sans_medium, sans_bold, code, code_bold, code_italic, code_medium, _ };
+
+/// A run of text in one face at one scale, measured (`Host.VTable.textRun`):
+/// its advance, and its line box (the ascent, the baseline from the top, and
+/// the height), in canvas units.
+pub const TextRun = struct { width: f32 = 0, ascent: f32 = 0, height: f32 = 0 };
/// How 2D drawing combines with what is already there (`Command.blend`).
/// Both are fixed-function on both hosts and match: `alpha` is source
@@ -646,9 +652,15 @@ pub const Host = struct {
writeBuffer: *const fn (*anyopaque, Buffer, u32, []const u8) anyerror!void,
/// Zero while unknown.
imageSize: *const fn (*anyopaque, Image) [2]u32,
- /// What `Command.text` gives the bytes at a scale: the width they
- /// advance and the height of their line, in canvas units.
- textSize: *const fn (*anyopaque, f32, []const u8, Face) [2]f32,
+ /// What `Command.text` gives the bytes in a face at a scale, as data:
+ /// a pure function of the font, the scale and the bytes, never of the
+ /// display. With the last slice (empty, or one a byte), each byte's x
+ /// from the run's start; a byte inside a cluster has its cluster's.
+ /// `sketch.text` lays paragraphs out over it.
+ textRun: *const fn (*anyopaque, Face, f32, []const u8, []f32) TextRun,
+ /// A face for TTF or OTF bytes, copied: the same face for the same
+ /// bytes. Null when they are not a font.
+ font: *const fn (*anyopaque, []const u8) ?Face,
/// `.none` if the file does not load.
loadSound: *const fn (*anyopaque, []const u8) Audio,
/// WAV, FLAC or Ogg Vorbis bytes in memory. Not cached. `.none` if
@@ -705,16 +717,18 @@ pub const Host = struct {
return h.vtable.imageSize(h.ctx, image);
}
/// The size `f.text(x, y, scale, bytes, ...)` covers from `x, y`: width
- /// and line height in canvas units, for laying text out (in `draw`:
- /// `update` gets no host). Native text is shaped and hinted at the size
- /// it is drawn, so a width is not a multiple of the scale: measure at
- /// the scale drawn.
+ /// and line height in canvas units, of one line (`sketch.text.size`
+ /// measures lines, anywhere, `update` too). Advances are whole pixels
+ /// at the size drawn, so a width is not a multiple of the scale: measure
+ /// at the scale drawn.
pub fn textSize(h: Host, scale: f32, bytes: []const u8) [2]f32 {
- return h.vtable.textSize(h.ctx, scale, bytes, .mono);
+ const run = h.vtable.textRun(h.ctx, .mono, scale, bytes, &.{});
+ return .{ run.width, run.height };
}
/// `textSize` for `f.textIn(face, ...)`.
pub fn textSizeIn(h: Host, face: Face, scale: f32, bytes: []const u8) [2]f32 {
- return h.vtable.textSize(h.ctx, scale, bytes, face);
+ const run = h.vtable.textRun(h.ctx, face, scale, bytes, &.{});
+ return .{ run.width, run.height };
}
pub fn loadSound(h: Host, path: []const u8) Audio {
return h.vtable.loadSound(h.ctx, path);
@@ -886,7 +900,7 @@ pub const hash: u64 = std.hash.Wyhash.hash(@import("abi_hash").layout, build);
pub const layout_hash: u64 = blk: {
@setEvalBranchQuota(1_000_000);
var h: u64 = 0;
- for (.{ Rect, Color, BlendMode, Corners, Event, Mode, Stream, Input, Image, Audio, Cursor, Voice, Command, gpu.Pass, gpu.Pipeline, gpu.Draw, gpu.Dispatch, gpu.PostProcess, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| {
+ for (.{ Rect, Color, Face, TextRun, BlendMode, Corners, Event, Mode, Stream, Input, Image, Audio, Cursor, Voice, Command, gpu.Pass, gpu.Pipeline, gpu.Draw, gpu.Dispatch, gpu.PostProcess, Host, Host.VTable, Context, Field, Layout, Info, Memory, Sketch }) |T| {
h = std.hash.Wyhash.hash(h, @typeName(T) ++ layout.signature(T));
}
break :blk h;
diff --git a/src/host/Host.zig b/src/host/Host.zig
index ede02df..9a2c0fa 100644
--- a/src/host/Host.zig
+++ b/src/host/Host.zig
@@ -1065,7 +1065,8 @@ const api: abi.Host.VTable = .{
.freeBuffer = apiFreeBuffer,
.writeBuffer = apiWriteBuffer,
.imageSize = apiImageSize,
- .textSize = apiTextSize,
+ .textRun = apiTextRun,
+ .font = apiFont,
.loadSound = apiLoadSound,
.decodeSound = apiDecodeSound,
.newSound = apiNewSound,
@@ -1127,9 +1128,12 @@ fn apiSamples(ctx: *anyopaque, audio: abi.Audio) []const f32 {
fn apiImageSize(ctx: *anyopaque, image: abi.Image) [2]u32 {
return hostOf(ctx).images.size(image);
}
-fn apiTextSize(ctx: *anyopaque, scale: f32, bytes: []const u8, face: abi.Face) [2]f32 {
- _ = ctx;
- return gfx.textSize(scale, bytes, face);
+fn apiTextRun(_: *anyopaque, face: abi.Face, scale: f32, bytes: []const u8, xs: []f32) abi.TextRun {
+ return gfx.textRun(face, scale, bytes, xs);
+}
+fn apiFont(_: *anyopaque, bytes: []const u8) ?abi.Face {
+ const face = c.sk_text_font(bytes.ptr, bytes.len);
+ return if (face < 0) null else @enumFromInt(face);
}
fn apiLoadSound(ctx: *anyopaque, path: []const u8) abi.Audio {
return hostOf(ctx).audio.load(path);
diff --git a/src/host/TimingAtlas.zig b/src/host/TimingAtlas.zig
index 4294b6a..a00a87e 100644
--- a/src/host/TimingAtlas.zig
+++ b/src/host/TimingAtlas.zig
@@ -19,7 +19,8 @@ const glyphs = blk: {
/// Called once with Painter on its canvas. Images owns the texture until shutdown.
pub fn init(images: *gfx.Images, painter: *gfx.Painter) !Atlas {
- const size = gfx.textSize(1, "0", .mono);
+ const run = gfx.textRun(.mono, 1, "0", &.{});
+ const size: [2]f32 = .{ run.width, run.height };
var atlas: Atlas = .{
.advance = size[0],
.cell_width = @ceil(size[0]) + padding * 2,
diff --git a/src/host/gfx.zig b/src/host/gfx.zig
index f84568a..d679067 100644
--- a/src/host/gfx.zig
+++ b/src/host/gfx.zig
@@ -613,15 +613,14 @@ fn fcolor(color: abi.Color) c.SDL_FColor {
};
}
-/// What `Command.text` covers at `scale`: the width of `bytes` and the
-/// height of its line, in canvas units (`Host.textSize`, `textRun`).
-pub fn textSize(scale: f32, bytes: []const u8, face: abi.Face) [2]f32 {
- if (!(scale > 0) or !std.math.isFinite(scale)) return .{ 0, 0 };
- var advance: i32 = 0;
+/// What `Command.text` gives `bytes` in `face` at `scale`, in canvas units:
+/// `Host.VTable.textRun`. `xs` is empty, or a byte each.
+pub fn textRun(face: abi.Face, scale: f32, bytes: []const u8, xs: []f32) abi.TextRun {
+ if (!(scale > 0) or !std.math.isFinite(scale) or (xs.len != 0 and xs.len != bytes.len)) return .{};
var ascent: i32 = 0;
var height: i32 = 0;
- _ = c.sk_text_shape(@backingInt(face), Glyphs.pixels(scale), bytes.ptr, bytes.len, null, 0, &advance, &ascent, &height);
- return .{ @floatFromInt(advance), @floatFromInt(height) };
+ const advance = c.sk_text_run(@backingInt(face), Glyphs.pixels(scale), bytes.ptr, bytes.len, if (xs.len == 0) null else xs.ptr, &ascent, &height);
+ return .{ .width = @floatFromInt(advance), .ascent = @floatFromInt(ascent), .height = @floatFromInt(height) };
}
fn premultiply(color: abi.Color) abi.Color {
diff --git a/src/sketch/root.zig b/src/sketch/root.zig
index 755e446..8a24417 100644
--- a/src/sketch/root.zig
+++ b/src/sketch/root.zig
@@ -40,9 +40,13 @@ pub const List = @import("list.zig").List;
/// Data computed in draw from a few State fields, kept in Session and rebuilt when they change (or after a reload).
pub const Derived = @import("derived.zig").Derived;
pub const web = @import("web.zig");
+/// Text measured and laid out anywhere (`update` too): `size`, `layout`,
+/// `font`, and the `Paragraph` `Frame.paragraph` draws.
+pub const text = @import("text.zig");
/// sfxr's sound effects, rendered to samples for `host.newSound`.
pub const sfxr = @import("sfxr.zig");
const request = @import("request.zig");
+const text_module = text;
pub const Request = request.Request;
pub const Handled = request.Handled;
@@ -157,13 +161,23 @@ pub const Frame = struct {
pub fn blend(f: *Frame, mode: BlendMode) void {
f.emit(.{ .blend = mode });
}
+ /// Text from its top left corner, scale 1 a 13 px face; a `\n` starts
+ /// a line. `sk.text.size(.mono, scale, bytes)` is what it covers.
pub fn text(f: *Frame, x: f32, y: f32, scale: f32, bytes: []const u8, color: anytype) void {
- f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes) } });
+ f.textIn(.mono, x, y, scale, bytes, color);
}
- /// `text` in another face of the built-in family: bold or italic mono,
- /// or the sans (`host.textSizeIn` measures it).
+ /// `text` in another face: bold or italic mono, the sans, JetBrains
+ /// Mono NL, or a sketch's own (`sk.text.font`).
pub fn textIn(f: *Frame, face: Face, x: f32, y: f32, scale: f32, bytes: []const u8, color: anytype) void {
- f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes), .face = face } });
+ if (std.mem.indexOfScalar(u8, bytes, '\n') != null) {
+ _ = f.paragraph(x, y, bytes, .{ .face = face, .scale = scale, .color = paint(color) });
+ } else f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes), .face = face } });
+ }
+ /// A paragraph from its top left corner (`sk.text.Paragraph`: a width
+ /// to wrap at, alignment, spans, the glyphs revealed, a caret), drawn;
+ /// its `Layout` returned, as `sk.text.layout` gives it, from `x`, `y`.
+ pub fn paragraph(f: *Frame, x: f32, y: f32, bytes: []const u8, p: text_module.Paragraph) text_module.Layout {
+ return text_module.lay(f.keep(u8, bytes), p, x, y, f);
}
/// `textIn` laid out and rasterized at `raster` and drawn at `scale`,
/// its position not snapped to a pixel: for text under a moving
@@ -174,7 +188,7 @@ pub const Frame = struct {
f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.keep(u8, bytes), .face = face, .raster = raster } });
}
pub fn print(f: *Frame, x: f32, y: f32, scale: f32, color: anytype, comptime fmt: []const u8, args: anytype) void {
- f.emit(.{ .text = .{ .x = x, .y = y, .scale = scale, .color = paint(color), .bytes = f.format(fmt, args) } });
+ f.textIn(.mono, x, y, scale, f.format(fmt, args), color);
}
/// Formats into scratch memory.
pub fn format(f: *Frame, comptime fmt: []const u8, args: anytype) []const u8 {
@@ -369,6 +383,7 @@ pub fn Glue(comptime App: type, comptime made: Build) type {
/// Calls `func` with the arguments its parameter types ask for.
fn call(comptime func: anytype, comptime name: []const u8, offer: Offer) @typeInfo(@TypeOf(func)).@"fn".return_type.? {
+ text_module.host = offer.ctx.host;
const F = @TypeOf(func);
var args: std.meta.ArgsTuple(F) = undefined;
inline for (@typeInfo(F).@"fn".param_types, 0..) |P, i| {
@@ -461,6 +476,7 @@ test {
_ = @import("list.zig");
_ = @import("derived.zig");
_ = sfxr;
+ _ = text;
}
test "setup receives session resources without a Frame and reports errors" {
diff --git a/src/sketch/text.zig b/src/sketch/text.zig
new file mode 100644
index 0000000..e4543b0
--- /dev/null
+++ b/src/sketch/text.zig
@@ -0,0 +1,281 @@
+//! Text as a sketch measures and lays it out, anywhere: `update` (pure: the
+//! same bytes give the same numbers), `draw` and tests. One host entry,
+//! `textRun` (a run in one face at one scale: its advance, its line box,
+//! each byte's x), and the rest here, in plain Zig, the same on every host:
+//! lines at `\n`, wrapping at spaces to a width, alignment, spans of
+//! another colour, face or scale, the first N glyphs revealed, a caret.
+//! A glyph, for `reveal` and `Layout.glyphs`, is a codepoint.
+//!
+//! The glue sets `host` before each call into the sketch. A test binary has
+//! no host: it calls vendor/text.c, which `App.addTest` links (the static
+//! library the native host is built with), so a test measures as the host.
+const std = @import("std");
+const builtin = @import("builtin");
+const abi = @import("abi");
+const Face = abi.Face;
+const Color = abi.Color;
+
+/// Who measures: set by the glue before each call into the sketch.
+pub var host: ?abi.Host = null;
+
+extern fn sk_text_run(face: c_int, px: f32, utf8: [*]const u8, len: usize, xs: ?[*]f32, ascent: *i32, height: *i32) i32;
+extern fn sk_text_font(bytes: [*]const u8, len: usize) c_int;
+
+/// From its `start` byte to the next span's: another colour, face or
+/// scale (null: the paragraph's). Spans are in order of `start`.
+pub const Span = struct { start: u32, color: ?Color = null, face: ?Face = null, scale: ?f32 = null };
+pub const Align = enum { left, center, right };
+
+pub const Paragraph = struct {
+ face: Face = .mono,
+ /// 1 is a 13 px face.
+ scale: f32 = 1,
+ color: Color = .white,
+ /// Lines wrap at spaces to this width; 0: lines end only at `\n`.
+ width: f32 = 0,
+ /// Within `width`, or within the widest line when it is 0.
+ @"align": Align = .left,
+ spans: []const Span = &.{},
+ /// Draw only the first `reveal` glyphs; the layout is the whole text's.
+ reveal: u32 = std.math.maxInt(u32),
+ /// A byte index whose place `Layout.caret` gives (`bytes.len`: the end).
+ caret: ?u32 = null,
+};
+
+/// A paragraph's extent and lines, its glyph count, and where `caret`
+/// sits: the left of its glyph, the top of its line and that line's height.
+/// Positions are the paragraph's (from its `x`, `y`; `layout` lays it out
+/// at 0, 0).
+pub const Layout = struct { w: f32 = 0, h: f32 = 0, lines: u32 = 0, glyphs: u32 = 0, caret: Caret = .{} };
+pub const Caret = struct { x: f32 = 0, y: f32 = 0, h: f32 = 0 };
+
+/// One run measured: its advance and line box, each byte's x into `xs`
+/// (empty, or one a byte).
+pub fn run(face: Face, scale: f32, bytes: []const u8, xs: []f32) abi.TextRun {
+ if (builtin.is_test) {
+ var ascent: i32 = 0;
+ var height: i32 = 0;
+ const advance = sk_text_run(@backingInt(face), 13 * scale, bytes.ptr, bytes.len, if (xs.len == 0) null else xs.ptr, &ascent, &height);
+ return .{ .width = @floatFromInt(advance), .ascent = @floatFromInt(ascent), .height = @floatFromInt(height) };
+ }
+ const h = host.?;
+ return h.vtable.textRun(h.ctx, face, scale, bytes, xs);
+}
+
+/// A face for a sketch's own TTF or OTF bytes (copied; the same bytes give
+/// the same face). Null when they are not a font. Its missing glyphs come
+/// from JetBrains Mono NL.
+pub fn font(bytes: []const u8) ?Face {
+ if (builtin.is_test) {
+ const face = sk_text_font(bytes.ptr, bytes.len);
+ return if (face < 0) null else @enumFromInt(face);
+ }
+ const h = host.?;
+ return h.vtable.font(h.ctx, bytes);
+}
+
+/// The width and height `bytes` covers in `face` at `scale`: its widest
+/// line and its lines' heights.
+pub fn size(face: Face, scale: f32, bytes: []const u8) [2]f32 {
+ const l = layout(bytes, .{ .face = face, .scale = scale });
+ return .{ l.w, l.h };
+}
+
+/// `p`'s layout of `bytes`, nothing drawn.
+pub fn layout(bytes: []const u8, p: Paragraph) Layout {
+ return lay(bytes, p, 0, 0, null);
+}
+
+/// The longest run measured at once; longer stretches are measured in
+/// pieces, at codepoint boundaries.
+const piece = 256;
+
+const Style = struct { face: Face, scale: f32, color: Color };
+
+/// The style at byte `i`, and the byte its span ends at.
+fn styleAt(bytes: []const u8, p: Paragraph, i: usize) struct { Style, usize } {
+ var s: Style = .{ .face = p.face, .scale = p.scale, .color = p.color };
+ var end = bytes.len;
+ for (p.spans) |span| {
+ if (span.start > i) {
+ end = @min(end, span.start);
+ break;
+ }
+ s = .{ .face = span.face orelse p.face, .scale = span.scale orelse p.scale, .color = span.color orelse p.color };
+ }
+ return .{ s, end };
+}
+
+/// Where the piece of one style from `at` ends: its span's end, a `\n`,
+/// `limit`, or `piece` bytes on (backed off to a codepoint's start).
+fn pieceEnd(bytes: []const u8, span_end: usize, at: usize, limit: usize) usize {
+ var end = @min(span_end, limit, at + piece);
+ if (std.mem.indexOfScalarPos(u8, bytes[0..end], at, '\n')) |nl| end = nl;
+ if (end < @min(span_end, limit) and end > at + 4) while (end > at and bytes[end] & 0xc0 == 0x80) {
+ end -= 1;
+ };
+ return end;
+}
+
+/// A line: bytes `[start, end)` drawn, the next line from `next`; its
+/// width and line box.
+const Line = struct { end: usize, next: usize, w: f32, ascent: f32, height: f32 };
+
+/// The line from `start`: to its `\n` or the end, or wrapped at the last
+/// space before the first glyph past `width`. A word wider than `width`
+/// stays whole. Spaces where it wraps are not part of its width.
+fn fit(bytes: []const u8, p: Paragraph, start: usize) Line {
+ var xs: [piece]f32 = undefined;
+ var at = start;
+ var w: f32 = 0;
+ var ascent: f32 = 0;
+ var descent: f32 = 0;
+ var wrap: ?Line = null;
+ // The first of the spaces before a break: the line's end if it wraps there.
+ var spaces: ?struct { at: usize, x: f32 } = null;
+ while (true) {
+ const style, const span_end = styleAt(bytes, p, at);
+ const end = pieceEnd(bytes, span_end, at, bytes.len);
+ const r = run(style.face, style.scale, bytes[at..end], xs[0 .. end - at]);
+ // A line wrapped where this piece starts has the line box before it.
+ const before: [2]f32 = .{ ascent, descent };
+ ascent = @max(ascent, r.ascent);
+ descent = @max(descent, r.height - r.ascent);
+ for (at..end) |i| {
+ const x = w + xs[i - at];
+ if (bytes[i] == ' ') {
+ if (spaces == null and i > start and bytes[i - 1] != ' ') spaces = .{ .at = i, .x = x };
+ continue;
+ }
+ if (spaces) |s| {
+ const box: [2]f32 = if (i == at) before else .{ ascent, descent };
+ wrap = .{ .end = s.at, .next = i, .w = s.x, .ascent = box[0], .height = box[0] + box[1] };
+ spaces = null;
+ }
+ const right = w + (if (i + 1 < end) xs[i + 1 - at] else r.width);
+ if (p.width > 0 and right > p.width) if (wrap) |l| return l;
+ }
+ w += r.width;
+ at = end;
+ // An empty line has its style's line box: an empty run's.
+ if (at == bytes.len or bytes[at] == '\n') return .{ .end = at, .next = @min(at + 1, bytes.len), .w = w, .ascent = ascent, .height = ascent + descent };
+ }
+}
+
+/// Lays `bytes` out from `x`, `y`, and with a frame, draws it: a
+/// `Command.text` a piece.
+pub fn lay(bytes: []const u8, p: Paragraph, x: f32, y: f32, frame: anytype) Layout {
+ const box = if (p.width > 0) p.width else if (p.@"align" != .left) blk: {
+ var left = p;
+ left.@"align" = .left;
+ left.caret = null;
+ break :blk layout(bytes, left).w;
+ } else 0;
+ var out: Layout = .{};
+ var xs: [piece]f32 = undefined;
+ var top = y;
+ var start: usize = 0;
+ var shown: u32 = 0;
+ while (true) {
+ const line = fit(bytes, p, start);
+ const offset: f32 = switch (p.@"align") {
+ .left => 0,
+ .center => @round((box - line.w) / 2),
+ .right => box - line.w,
+ };
+ var at = start;
+ var pen = x + offset;
+ if (p.caret) |caret| if (caret >= start and (caret < line.next or line.next == bytes.len)) {
+ out.caret = .{ .x = if (caret >= line.end) pen + line.w else pen, .y = top, .h = line.height };
+ };
+ while (at < line.end) {
+ const style, const span_end = styleAt(bytes, p, at);
+ const end = pieceEnd(bytes, span_end, at, line.end);
+ const r = run(style.face, style.scale, bytes[at..end], xs[0 .. end - at]);
+ if (p.caret) |caret| if (caret >= at and caret <= end and caret <= line.end) {
+ out.caret.x = pen + (if (caret < end) xs[caret - at] else r.width);
+ };
+ const count: u32 = @intCast(std.unicode.utf8CountCodepoints(bytes[at..end]) catch end - at);
+ if (@TypeOf(frame) != @TypeOf(null) and shown < p.reveal) {
+ var cut = end;
+ if (shown + count > p.reveal) {
+ var left = p.reveal - shown;
+ cut = at;
+ while (left > 0 and cut < end) : (left -= 1) cut += std.unicode.utf8ByteSequenceLength(bytes[cut]) catch 1;
+ }
+ frame.emit(.{ .text = .{ .x = pen, .y = top + line.ascent - r.ascent, .scale = style.scale, .color = style.color, .bytes = bytes[at..cut], .face = style.face } });
+ }
+ shown += count;
+ pen += r.width;
+ at = end;
+ }
+ out.w = @max(out.w, line.w);
+ out.lines += 1;
+ top += line.height;
+ // Spaces where a line wraps count too, so reveal walks the text; a
+ // `\n` is no glyph. After a last `\n` comes an empty line.
+ const newline = line.end < bytes.len and bytes[line.end] == '\n';
+ if (!newline) shown += @intCast(std.unicode.utf8CountCodepoints(bytes[line.end..line.next]) catch 0);
+ if (line.next == bytes.len and !newline) break;
+ start = line.next;
+ }
+ out.h = top - y;
+ out.glyphs = shown;
+ return out;
+}
+
+test "a paragraph wraps at spaces, aligns, reveals and finds its caret" {
+ const t = std.testing;
+ // Go Mono at 13 px: 8 px a glyph, a 16 px line (vendor/text.c).
+ const one = run(.mono, 1, "0123456789", &.{});
+ try t.expectEqual(@as(f32, 80), one.width);
+ try t.expectEqual(@as(f32, 16), one.height);
+ try t.expectEqual([2]f32{ 80, 16 }, size(.mono, 1, "0123456789"));
+ try t.expectEqual([2]f32{ 80, 32 }, size(.mono, 1, "01234\n0123456789"));
+ // 10 glyphs wide: "aaaa bbbb" fits, "cccc" wraps; the space is not width.
+ const l = layout("aaaa bbbb cccc", .{ .width = 80 });
+ try t.expectEqual(@as(u32, 2), l.lines);
+ try t.expectEqual(@as(f32, 72), l.w);
+ try t.expectEqual(@as(f32, 32), l.h);
+ try t.expectEqual(@as(u32, 14), l.glyphs);
+ // The caret before "cccc" is at the second line's start; at the end, after it.
+ try t.expectEqual(Caret{ .x = 0, .y = 16, .h = 16 }, layout("aaaa bbbb cccc", .{ .width = 80, .caret = 10 }).caret);
+ try t.expectEqual(Caret{ .x = 32, .y = 16, .h = 16 }, layout("aaaa bbbb cccc", .{ .width = 80, .caret = 14 }).caret);
+ try t.expectEqual(Caret{ .x = 16, .y = 0, .h = 16 }, layout("ab\ncd", .{ .caret = 2 }).caret);
+ try t.expectEqual(Caret{ .x = 8, .y = 16, .h = 16 }, layout("ab\ncd", .{ .caret = 4 }).caret);
+ // Centred in 100: a line of 4 starts at 34.
+ try t.expectEqual(Caret{ .x = 34, .y = 0, .h = 16 }, layout("abcd", .{ .width = 100, .@"align" = .center, .caret = 0 }).caret);
+ try t.expectEqual(Caret{ .x = 68, .y = 0, .h = 16 }, layout("abcd", .{ .width = 100, .@"align" = .right, .caret = 0 }).caret);
+ // A span twice the size makes its line taller, and wider.
+ const big = layout("ab cd", .{ .spans = &.{.{ .start = 3, .scale = 2 }} });
+ try t.expectEqual(@as(f32, 24 + 2 * 8 * 2), big.w);
+ try t.expect(big.h >= 31);
+ // A word wider than the width stays whole on its own line.
+ try t.expectEqual(@as(u32, 2), layout("abcdefghijkl x", .{ .width = 40 }).lines);
+ // An empty text is one empty line.
+ try t.expectEqual(Layout{ .w = 0, .h = 16, .lines = 1 }, layout("", .{}));
+}
+
+test "reveal draws the first glyphs of the same layout" {
+ const t = std.testing;
+ const Frame = struct {
+ drawn: [8][]const u8 = undefined,
+ n: usize = 0,
+ fn emit(f: *@This(), c: abi.Command) void {
+ f.drawn[f.n] = c.text.bytes;
+ f.n += 1;
+ }
+ };
+ var f: Frame = .{};
+ const whole = lay("ab cd\nef", .{ .width = 32 }, 0, 0, &f);
+ try t.expectEqual(@as(usize, 3), f.n);
+ try t.expectEqualStrings("ab", f.drawn[0]);
+ try t.expectEqualStrings("cd", f.drawn[1]);
+ try t.expectEqualStrings("ef", f.drawn[2]);
+ f = .{};
+ const part = lay("ab cd\nef", .{ .width = 32, .reveal = 4 }, 0, 0, &f);
+ try t.expectEqual(whole, part);
+ try t.expectEqual(@as(u32, 7), whole.glyphs);
+ try t.expectEqual(@as(usize, 2), f.n);
+ try t.expectEqualStrings("c", f.drawn[1]);
+}
diff --git a/src/sketch/web.zig b/src/sketch/web.zig
index 804a4df..e12acb3 100644
--- a/src/sketch/web.zig
+++ b/src/sketch/web.zig
@@ -15,6 +15,11 @@ const js = struct {
extern "host" fn newImage(w: u32, h: u32) u32;
extern "host" fn freeImage(image: u32) void;
extern "host" fn clock() f64;
+ /// canvas measureText: the run's width, ascent and height into `out`,
+ /// and with `xs_len` (the run's length) each byte's x.
+ extern "host" fn textRun(face: u32, scale: f32, ptr: [*]const u8, len: usize, xs: [*]f32, xs_len: usize, out: *[3]f32) void;
+ /// A FontFace from the bytes: its face, or -1.
+ extern "host" fn font(ptr: [*]const u8, len: usize) i32;
extern "host" fn openFile(command: [*]const u8, command_len: usize, pattern: [*]const u8, pattern_len: usize) void;
extern "canvas" fn clear(r: u32, g: u32, b: u32, a: u32) void;
extern "canvas" fn fill(x: f32, y: f32, w: f32, h: f32, r: u32, g: u32, b: u32, a: u32) void;
@@ -30,7 +35,7 @@ const js = struct {
extern "canvas" fn target(id: u32) void;
/// `abi.BlendMode` by value.
extern "canvas" fn blend(mode: u32) void;
- extern "canvas" fn text(x: f32, y: f32, scale: f32, ptr: [*]const u8, len: usize, r: u32, g: u32, b: u32, a: u32) void;
+ extern "canvas" fn text(x: f32, y: f32, scale: f32, face: u32, ptr: [*]const u8, len: usize, r: u32, g: u32, b: u32, a: u32) void;
extern "canvas" fn clip(enabled: u32, x: f32, y: f32, w: f32, h: f32) void;
extern "canvas" fn canvas(w: u32, h: u32) void;
extern "canvas" fn cursor(kind: u32) void;
@@ -207,7 +212,7 @@ fn Driver(comptime App: type) type {
.shape => |v| js.shape(v.points.ptr, v.points.len, v.ends.ptr, v.ends.len, v.colors.ptr, v.colors.len, v.color.r, v.color.g, v.color.b, v.color.a),
.target => |v| js.target(@backingInt(v)),
.blend => |v| js.blend(@backingInt(v)),
- .text => |v| js.text(v.x, v.y, v.scale, v.bytes.ptr, v.bytes.len, v.color.r, v.color.g, v.color.b, v.color.a),
+ .text => |v| js.text(v.x, v.y, v.scale, @backingInt(v.face), v.bytes.ptr, v.bytes.len, v.color.r, v.color.g, v.color.b, v.color.a),
.clip => |v| if (v) |r| js.clip(1, r.x, r.y, r.w, r.h) else js.clip(0, 0, 0, 0, 0),
.canvas => |v| {
input.width = @floatFromInt(v.w);
@@ -409,7 +414,8 @@ fn Driver(comptime App: type) type {
.freeBuffer = freeBuffer,
.writeBuffer = writeBuffer,
.imageSize = imageSize,
- .textSize = textSize,
+ .textRun = textRun,
+ .font = font,
.loadSound = loadSound,
.decodeSound = unsupportedSound,
.newSound = newSound,
@@ -449,10 +455,15 @@ fn Driver(comptime App: type) type {
fn imageSize(_: *anyopaque, img: abi.Image) [2]u32 {
return .{ js.imageWidth(@backingInt(img)), js.imageHeight(@backingInt(img)) };
}
- /// As host.js draws text: 8 px a character and a 16 px line at scale 1.
- fn textSize(_: *anyopaque, scale: f32, bytes: []const u8, _: abi.Face) [2]f32 {
- const count = std.unicode.utf8CountCodepoints(bytes) catch bytes.len;
- return .{ @as(f32, @floatFromInt(count)) * 8 * scale, 16 * scale };
+ /// As host.js draws text: canvas measureText, in the page's fonts.
+ fn textRun(_: *anyopaque, face: abi.Face, scale: f32, bytes: []const u8, xs: []f32) abi.TextRun {
+ var out: [3]f32 = .{ 0, 0, 0 };
+ js.textRun(@backingInt(face), scale, bytes.ptr, bytes.len, xs.ptr, xs.len, &out);
+ return .{ .width = out[0], .ascent = out[1], .height = out[2] };
+ }
+ fn font(_: *anyopaque, bytes: []const u8) ?abi.Face {
+ const face = js.font(bytes.ptr, bytes.len);
+ return if (face < 0) null else @enumFromInt(face);
}
/// Only sounds the page has decoded (opened or dropped files): the
/// browser decodes asynchronously, so there is no reading on demand.
diff --git a/test/text.script b/test/text.script
index 776cc41..2ed0b29 100644
--- a/test/text.script
+++ b/test/text.script
@@ -19,3 +19,11 @@ expect-pixel .zig-cache/text/native.png 127 256 16 16 16 255
# ligatures: twelve characters at scale 2 are 192 px, on its own taller line.
expect-pixel .zig-cache/text/native.png 200 275 32 64 96 255
expect-pixel .zig-cache/text/native.png 206 290 16 16 16 255
+# A paragraph (sk.text) wrapped at 200 and centred: three lines, the last
+# with "twice" at twice the size, 16 + 16 + 31 px tall from y 175; the caret
+# its Layout gives before "twice" is that line's height, at x 440.
+expect-pixel .zig-cache/text/native.png 425 237 32 64 96 255
+expect-pixel .zig-cache/text/native.png 425 238 16 16 16 255
+expect-pixel .zig-cache/text/native.png 440 207 255 255 0 255
+expect-pixel .zig-cache/text/native.png 440 237 255 255 0 255
+expect-pixel .zig-cache/text/native.png 440 206 32 64 96 255
diff --git a/test/text.zig b/test/text.zig
index d0e0eea..f60f13a 100644
--- a/test/text.zig
+++ b/test/text.zig
@@ -36,4 +36,13 @@ pub fn draw(f: *sk.Frame) void {
if (line.raster > 0) f.textScaled(line.face, 10 * k, y, line.scale * k, line.raster * k, line.text, 0xffffff) else f.textIn(line.face, 10 * k, y, line.scale * k, line.text, 0xffffff);
y += size[1] + 6 * k;
}
+ // A paragraph (sk.text): wrapped at 200, centred, a span in red and
+ // one twice the size, its box from sk.text.layout and a caret drawn
+ // before "twice" from the Layout it returns.
+ const words = "Centred, wrapped at spaces, in red and twice the size.";
+ const p: sk.text.Paragraph = .{ .width = 200 * k, .@"align" = .center, .scale = k, .spans = &.{ .{ .start = 31, .color = .{ .r = 255, .g = 80, .b = 80 } }, .{ .start = 35 }, .{ .start = 39, .scale = 2 * k }, .{ .start = 44 } }, .caret = 39 };
+ const l = sk.text.layout(words, p);
+ f.fill(sk.Rect{ .x = 420 * k, .y = 175 * k, .w = 200 * k, .h = l.h }, 0x204060);
+ const drawn = f.paragraph(420 * k, 175 * k, words, p);
+ f.fill(sk.Rect{ .x = drawn.caret.x, .y = drawn.caret.y, .w = k, .h = drawn.caret.h }, 0xffff00);
}
diff --git a/vendor/text.c b/vendor/text.c
index 818597d..09e3902 100644
--- a/vendor/text.c
+++ b/vendor/text.c
@@ -185,3 +185,30 @@ int sk_text_shape(int face, float px, const char *utf8, size_t len, SkGlyph *out
*advance = pen;
return n;
}
+
+int32_t sk_text_run(int face, float px, const char *utf8, size_t len, float *xs,
+ int32_t *ascent, int32_t *height) {
+ static SkGlyph *glyphs;
+ static int room;
+ int32_t advance = 0;
+ int n = sk_text_shape(face, px, utf8, len, glyphs, room, &advance, ascent, height);
+ if (!xs) return advance;
+ if (n > room) {
+ SkGlyph *more = realloc(glyphs, (size_t)n * sizeof *glyphs);
+ if (!more) n = room;
+ else {
+ glyphs = more;
+ room = n;
+ sk_text_shape(face, px, utf8, len, glyphs, room, &advance, ascent, height);
+ }
+ }
+ for (size_t i = 0; i < len; i++) xs[i] = -1;
+ for (int k = 0; k < n; k++)
+ if (glyphs[k].cluster < len && xs[glyphs[k].cluster] < 0) xs[glyphs[k].cluster] = glyphs[k].x > 0 ? (float)glyphs[k].x : 0;
+ float last = 0;
+ for (size_t i = 0; i < len; i++) {
+ if (xs[i] < 0) xs[i] = last;
+ last = xs[i];
+ }
+ return advance;
+}
diff --git a/vendor/text.h b/vendor/text.h
index dd4eecf..355ad90 100644
--- a/vendor/text.h
+++ b/vendor/text.h
@@ -31,6 +31,12 @@ typedef struct {
int sk_text_shape(int face, float px, const char *utf8, size_t len, SkGlyph *out, int max,
int32_t *advance, int32_t *ascent, int32_t *height);
+/* `sk_text_shape` measured: the run's advance, with `xs` (when not NULL,
+ `len` of them) the x of each byte from the run's start, a byte inside a
+ cluster at its cluster's. What `abi.Host.VTable.textRun` serves. */
+int32_t sk_text_run(int face, float px, const char *utf8, size_t len, float *xs,
+ int32_t *ascent, int32_t *height);
+
/* `glyph`'s own advance in `face` at `px`, in whole pixels (what the
renderer centres font.c's raster in, so the glyph lands on its origin). */
int32_t sk_text_advance(int face, float px, uint32_t glyph);
diff --git a/web/host.js b/web/host.js
index 32bdbfb..8213dbd 100644
--- a/web/host.js
+++ b/web/host.js
@@ -519,8 +519,49 @@ function drawImage(id, x, y, w, h, sx, sy, sw, sh, r, g, b, a, place) {
ctx.restore();
}
+// Text (docs/text.md): sketchbook's faces in the page's fonts, in their
+// weight and style, and a sketch's own font a FontFace (`fonts`, its bytes
+// kept to give the same face for the same bytes). 13 px at scale 1.
+const faceFonts = [['', 'monospace'], ['bold', 'monospace'], ['italic', 'monospace'], ['', 'sans-serif'], ['500', 'sans-serif'], ['bold', 'sans-serif'], ['', 'monospace'], ['bold', 'monospace'], ['italic', 'monospace'], ['500', 'monospace']];
+const fonts = [];
+const fontOf = (face, scale) => {
+ const [style, family] = face < 10 ? faceFonts[face] : ['', fonts[face - 10]?.family ?? 'monospace'];
+ return `${style} ${13 * scale}px ${family}`.trim();
+};
+const measurer = document.createElement('canvas').getContext('2d');
+
const imports = {
host: {
+ // A run's width, ascent and line height, and each byte's x (a byte inside
+ // a codepoint at its codepoint's): the prefixes measured, so drawn is
+ // measured, kerning included.
+ textRun(face, scale, ptr, len, xsPtr, xsLen, outPtr) {
+ measurer.font = fontOf(face, scale);
+ const all = bytes(ptr, len).slice();
+ const m = measurer.measureText(decoder.decode(all));
+ new Float32Array(wasm.memory.buffer, outPtr, 3).set([m.width, m.fontBoundingBoxAscent, m.fontBoundingBoxAscent + m.fontBoundingBoxDescent]);
+ if (!xsLen) return;
+ const xs = new Float32Array(wasm.memory.buffer, xsPtr, xsLen);
+ let x = 0;
+ for (let i = 0; i < len; i++) {
+ if ((all[i] & 0xc0) !== 0x80) x = i ? measurer.measureText(decoder.decode(all.subarray(0, i))).width : 0;
+ xs[i] = x;
+ }
+ },
+ font(ptr, len) {
+ const data = bytes(ptr, len).slice();
+ const known = fonts.findIndex(f => f.data.length === data.length && f.data.every((b, i) => b === data[i]));
+ if (known >= 0) return 10 + known;
+ if (fonts.length === 54) return -1;
+ const family = `sketchbook-font-${fonts.length}`;
+ try {
+ const face = new FontFace(family, data);
+ document.fonts.add(face);
+ face.load().catch(err => console.warn(`font ${family}: ${err}`));
+ } catch { return -1; }
+ fonts.push({family, data});
+ return 10 + fonts.length - 1;
+ },
log(ptr, len) { console.log(string(ptr, len)); },
loadImage(ptr, len) {
const path = string(ptr, len);
@@ -615,15 +656,15 @@ const imports = {
if (open) ctx.fill('nonzero');
},
// Always blended alpha, as native text is.
- text(x, y, scale, ptr, len, r, g, b, a) {
+ // A run from its line box's top left, in the face textRun measures it in.
+ text(x, y, scale, face, ptr, len, r, g, b, a) {
ctx.save();
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle = rgba(r, g, b, a);
- // The native font is a fixed 8px cell: the same advance, and a size
- // whose capitals fill the cell as native ones do.
- ctx.font = `${10 * scale}px monospace`;
- ctx.textBaseline = 'top';
- for (const [i, ch] of Array.from(string(ptr, len)).entries()) ctx.fillText(ch, x + i * 8 * scale, y);
+ ctx.font = fontOf(face, scale);
+ ctx.textBaseline = 'alphabetic';
+ const s = string(ptr, len);
+ ctx.fillText(s, x, y + ctx.measureText(s).fontBoundingBoxAscent);
ctx.restore();
},
clip(enabled, x, y, w, h) {