diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-17 09:06:20 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 12:15:01 -0300 |
| commit | 303478956e0086467a9073d7f6fa67b51b6580ad (patch) | |
| tree | 6c69e13eef575b514433373893e1f14c435b4f1a /src/sketch/text.zig | |
| parent | c94455e1a8d2a430d8dcd74603bcd0d7b27aeb68 (diff) | |
| download | sketchbook-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
Diffstat (limited to 'src/sketch/text.zig')
| -rw-r--r-- | src/sketch/text.zig | 281 |
1 files changed, 281 insertions, 0 deletions
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]); +} |
