From 303478956e0086467a9073d7f6fa67b51b6580ad Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 09:06:20 -0300 Subject: 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 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- src/abi.zig | 40 ++++--- src/host/Host.zig | 12 +- src/host/TimingAtlas.zig | 3 +- src/host/gfx.zig | 13 +-- src/sketch/root.zig | 26 ++++- src/sketch/text.zig | 281 +++++++++++++++++++++++++++++++++++++++++++++++ src/sketch/web.zig | 25 +++-- 7 files changed, 363 insertions(+), 37 deletions(-) create mode 100644 src/sketch/text.zig (limited to 'src') 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. -- cgit v1.3