//! 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, &.{}); } /// `p`'s layout of `bytes`, and in `out` the place of every byte: where a /// caret before it sits (`layout` with `.caret = i`), `out[bytes.len]` the /// end's. An editor draws ranges and hit-tests with it: the byte at a point /// is the last whose line holds the point's y and whose x is at or left of /// it. `out` has a place a byte and one more. pub fn places(bytes: []const u8, p: Paragraph, out: []Caret) Layout { std.debug.assert(out.len > bytes.len); return lay(bytes, p, 0, 0, null, out); } /// 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; with `out`, each byte's place (`places`). pub fn lay(bytes: []const u8, p: Paragraph, x: f32, y: f32, frame: anytype, out_places: []Caret) 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); }; if (out_places.len > 0) for (at..end) |i| { out_places[i] = .{ .x = pen + xs[i - at], .y = top, .h = line.height }; }; 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; } // A `\n` or the spaces a line wraps at, and the end, sit at its end. const after = if (line.next == bytes.len) line.next + 1 else line.next; if (out_places.len > 0) for (line.end..after) |i| { out_places[i] = .{ .x = pen, .y = top, .h = line.height }; }; 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]); } test "a paragraph's places are where its caret sits, byte by byte" { const t = std.testing; // Wrapped at a space, a `\n`, a span twice the size on the first line, // a two-byte codepoint and a last empty line. const text = "ab cd efgh\nij é\n"; const p: Paragraph = .{ .width = 80, .spans = &.{ .{ .start = 3, .scale = 2 }, .{ .start = 5, .scale = 1 } } }; var out: [text.len + 1]Caret = undefined; try t.expectEqual(layout(text, p), places(text, p, &out)); for (0..text.len + 1) |i| { var at = p; at.caret = @intCast(i); try t.expectEqual(layout(text, at).caret, out[i]); } // The big span's line is taller; the byte after its line, on the next. try t.expect(out[0].h > 16); try t.expectEqual(@as(f32, 3 * 8 + 2 * 8 * 2), out[5].x); try t.expectEqual(out[6].y, out[7].y); try t.expect(out[6].y > out[5].y); }