diff options
| -rw-r--r-- | build.zig | 49 | ||||
| -rw-r--r-- | build.zig.zon | 13 | ||||
| -rw-r--r-- | src/host/Glyphs.zig | 225 | ||||
| -rw-r--r-- | src/host/Host.zig | 5 | ||||
| -rw-r--r-- | src/host/TimingAtlas.zig | 2 | ||||
| -rw-r--r-- | src/host/gfx.zig | 75 | ||||
| -rw-r--r-- | test/fonts.c | 90 | ||||
| -rw-r--r-- | vendor/README.md | 4 | ||||
| -rw-r--r-- | vendor/fonts/README.md | 74 | ||||
| -rw-r--r-- | vendor/text.c | 411 | ||||
| -rw-r--r-- | vendor/text.h | 61 |
11 files changed, 502 insertions, 507 deletions
@@ -86,8 +86,14 @@ pub fn build(b: *Build) void { }); tracy.link_libcpp = true; } + const text_library = textLibrary(b, target, optimize) orelse return; + b.installArtifact(text_library); const c = cModule(b, target, optimize); + c.linkLibrary(text_library); gpu.addImport("c", c); + // pardes's glyph atlas, for its ink boxes (the host packs its own: see + // src/host/Glyphs.zig) and the comparison with pardes's raster. + const font_atlas = b.createModule(.{ .root_source_file = b.path("src/font/Atlas.zig"), .imports = &.{.{ .name = "c", .module = c }} }); // No optimize mode of its own: the host's Zig code builds in the mode // of the executable it is part of (`script_optimize` makes use of it). const cloud9 = b.dependency("cloud9", .{ .target = target, .optimize = optimize }).module("cloud9"); @@ -95,7 +101,7 @@ pub fn build(b: *Build) void { const host = b.addModule("host", .{ .root_source_file = b.path("src/host/root.zig"), .target = target, - .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 } }, + .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 } }, }); b.step("test-control", "Test 9P control validation and screenshot snapshots").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = host, .filters = &.{ "control writes", "9P reads", "the State as files", "a row of scalars" } })).step); @@ -181,7 +187,7 @@ pub fn build(b: *Build) void { 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 }), 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 } } }), + 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); // A State bigger than a save holds is a compile error that says what to do. const too_big = b.addObject(.{ .name = "too_big", .root_module = b.createModule(.{ @@ -657,13 +663,46 @@ fn cModule(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.Optimi source.addFileArg(protocol); translator.mod.addCSourceFile(.{ .file = source.addOutputFileArg("presentation-time-protocol.c"), .flags = &.{"-std=c99"} }); translator.mod.linkSystemLibrary("wayland-client", .{ .use_pkg_config = .force }); - translator.mod.addCSourceFile(.{ .file = b.path("vendor/text.c"), .flags = &.{"-std=c23"} }); - translator.mod.linkSystemLibrary("pangocairo-1.0", .{ .use_pkg_config = .force }); - translator.mod.linkSystemLibrary("pangoft2-1.0", .{ .use_pkg_config = .force }); } return translator.mod; } +/// `sketchbook-text`: vendor/text.c over pardes's vendor/font.c, FreeType +/// and HarfBuzz, the packages and flags pardes builds its window with. The +/// host links it, and so do a sketch's tests (`App.addTest`), which measure +/// text with no host; a sketch's library never does. Null until the lazy +/// packages are fetched. +fn textLibrary(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) ?*Build.Step.Compile { + const freetype = (b.lazyDependency("freetype", .{ .target = target, .optimize = optimize, .@"enable-libpng" = false }) orelse return null).artifact("freetype"); + const harfbuzz = b.lazyDependency("harfbuzz", .{}) orelse return null; + const lib = b.addLibrary(.{ .name = "sketchbook-text", .linkage = .static, .root_module = b.createModule(.{ + .target = target, + .optimize = optimize, + .link_libc = true, + .link_libcpp = true, + }) }); + lib.root_module.linkLibrary(freetype); + lib.root_module.addIncludePath(harfbuzz.path("src")); + lib.root_module.addCSourceFile(.{ .file = harfbuzz.path("src/harfbuzz.cc"), .flags = &.{ + "-DHAVE_STDBOOL_H", + "-DHAVE_UNISTD_H", + "-DHAVE_SYS_MMAN_H", + "-DHAVE_PTHREAD=1", + "-DHAVE_FREETYPE=1", + "-DHAVE_FT_GET_VAR_BLEND_COORDINATES=1", + "-DHAVE_FT_SET_VAR_BLEND_COORDINATES=1", + "-DHAVE_FT_DONE_MM_VAR=1", + "-DHAVE_FT_GET_TRANSFORM=1", + "-Dhb_malloc_impl=ui_malloc", + "-Dhb_calloc_impl=ui_calloc", + "-Dhb_realloc_impl=ui_realloc", + "-Dhb_free_impl=ui_free", + } }); + lib.root_module.addCSourceFile(.{ .file = b.path("vendor/font.c") }); + lib.root_module.addCSourceFile(.{ .file = b.path("vendor/text.c"), .flags = &.{"-std=c23"} }); + return lib; +} + /// SDL 3.4.14 gives its pthread TLS key no destructor, so threads SDL did not /// create (PipeWire's) leave error storage behind when they exit. Compile the /// original backend with an exit destructor; the pinned package is untouched. diff --git a/build.zig.zon b/build.zig.zon index 828a17e..141dc90 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -18,6 +18,19 @@ .hash = "xitdb-0.0.0-EEFkxhwmBwDz1N8H9oHhVhd1Al5YZp8iDhaMLm2_79pS", .lazy = true, }, + // Text (vendor/text.c over pardes's vendor/font.c): the FreeType + // and HarfBuzz pardes pins, compiled into the host. Lazy, like + // xitdb: a `gpu-only` embedder brings its own. + .freetype = .{ + .url = "git+https://github.com/allyourcodebase/freetype#884fd2235e6ae1ec4306eda30b3259f20930ed2e", + .hash = "freetype-2.14.3-C3-WdXSKAAB-kHs4qgRoeoFnRkNQn6M_SSlUGZ6ywgBQ", + .lazy = true, + }, + .harfbuzz = .{ + .url = "https://deps.files.ghostty.org/harfbuzz-11.0.0.tar.xz", + .hash = "N-V-__8AAG02ugUcWec-Ndp-i7JTsJ0dgF8nnJRUInkGLG7G", + .lazy = true, + }, }, .minimum_zig_version = "0.17.0", .paths = .{ "build.zig", "build.zig.zon", "src", "tools", "vendor", "web" }, diff --git a/src/host/Glyphs.zig b/src/host/Glyphs.zig new file mode 100644 index 0000000..8de40cf --- /dev/null +++ b/src/host/Glyphs.zig @@ -0,0 +1,225 @@ +//! The host's text. A `Command.text` is shaped by vendor/text.c at its +//! canvas size (what `textRun` measured), and each glyph is rasterized by +//! pardes's font.c at the size it lands on the device, kept in one +//! 2048x2048 coverage atlas: shelves of trimmed ink boxes, cleared and +//! refilled when full (pardes's policy: no eviction). The texture holds +//! white premultiplied by coverage, so a vertex colour is the ink and the +//! coverage is mixed once, with no gamma. The glyphs of consecutive text +//! commands are one geometry call (`flush`, which the Painter calls before +//! anything else it draws). Upright text lands on whole device pixels and +//! samples NEAREST; `textScaled` (and a glyph past 512 device pixels, +//! rastered at 512) is placed unsnapped and samples LINEAR. +const Glyphs = @This(); +const std = @import("std"); +const abi = @import("abi"); +const c = @import("c"); +const Atlas = @import("font_atlas"); + +const side = Atlas.atlas_w; +/// The largest raster, in device pixels: a bigger glyph is this one, stretched. +const max_px = 512; + +/// A glyph of a face at a device size, in 64ths of a pixel. +const Key = packed struct(u64) { face: u8, glyph: u32, px: u24 }; +/// Its ink box in the atlas, and where that box sits from the pen's origin +/// on the baseline (device pixels, y down). Empty: nothing to draw. +const Slot = struct { u: u16 = 0, v: u16 = 0, w: u16 = 0, h: u16 = 0, dx: i16 = 0, dy: i16 = 0 }; + +gpa: std.mem.Allocator, +/// Coverage, a byte a texel: `texture`'s contents to come. +stage: []u8 = &.{}, +texture: ?*c.SDL_Texture = null, +slots: std.AutoHashMapUnmanaged(Key, Slot) = .empty, +/// The shelf being filled: its top, its height so far, and the pen in it. +shelf: struct { x: u32 = 0, y: u32 = 0, h: u32 = 0 } = .{}, +/// What the stage changed since the last upload: x0, y0, x1, y1. +dirty: [4]u32 = .{ 0, 0, side, side }, +/// A glyph's raster before it is trimmed, and the shaped glyphs of a run. +raster: std.ArrayList(u8) = .empty, +shaped: std.ArrayList(c.SkGlyph) = .empty, +/// The pending geometry: six vertices a glyph, in logical units. +batch: std.ArrayList(c.SDL_Vertex) = .empty, +linear: bool = false, + +pub fn deinit(g: *Glyphs) void { + if (g.texture) |t| c.SDL_DestroyTexture(t); + g.gpa.free(g.stage); + g.slots.deinit(g.gpa); + g.raster.deinit(g.gpa); + g.shaped.deinit(g.gpa); + g.batch.deinit(g.gpa); + g.* = .{ .gpa = g.gpa }; +} + +/// The canvas size `scale` is, in pixels: scale 1 is 13. +pub fn pixels(scale: f32) f32 { + return 13 * scale; +} + +/// One `Command.text` into the batch. +pub fn draw(g: *Glyphs, renderer: *c.SDL_Renderer, t: @FieldType(abi.Command, "text")) void { + const raster = if (t.raster > 0) t.raster else t.scale; + if (t.bytes.len == 0 or t.color.a == 0 or !(t.scale > 0) or !std.math.isFinite(t.scale) or !std.math.isFinite(raster)) return; + if (g.texture == null and !g.start(renderer)) return; + // Shaped at the size it was measured at; `k` stretches that layout to + // the size drawn (textScaled), `dpi` to the device. + var advance: i32 = 0; + var ascent: i32 = 0; + var height: i32 = 0; + const face: c_int = @backingInt(t.face); + var n: usize = 0; + while (true) { + n = @intCast(c.sk_text_shape(face, pixels(raster), t.bytes.ptr, t.bytes.len, g.shaped.items.ptr, @intCast(g.shaped.items.len), &advance, &ascent, &height)); + if (n <= g.shaped.items.len) break; + g.shaped.resize(g.gpa, n) catch return; + } + const k = t.scale / raster; + const dpi = density(renderer); + const wanted = pixels(t.scale) * dpi; + const px = @min(wanted, max_px); + const stretch = wanted / px; + const snapped = k == 1 and stretch == 1; + if (g.linear != !snapped) { + g.flush(renderer); + g.linear = !snapped; + } + const ink: c.SDL_FColor = .{ + .r = @as(f32, @floatFromInt(t.color.r)) * @as(f32, @floatFromInt(t.color.a)) / (255 * 255), + .g = @as(f32, @floatFromInt(t.color.g)) * @as(f32, @floatFromInt(t.color.a)) / (255 * 255), + .b = @as(f32, @floatFromInt(t.color.b)) * @as(f32, @floatFromInt(t.color.a)) / (255 * 255), + .a = @as(f32, @floatFromInt(t.color.a)) / 255, + }; + const unit = k * dpi; // device pixels a layout pixel + const origin: [2]f32 = .{ t.x * dpi, (t.y + @as(f32, @floatFromInt(ascent)) * k) * dpi }; + for (g.shaped.items[0..n]) |glyph| { + const key: Key = .{ .face = glyph.face, .glyph = glyph.glyph, .px = @intFromFloat(@round(px * 64)) }; + const slot = g.slotFor(renderer, key) orelse continue; + if (slot.w == 0) continue; + var at: [2]f32 = .{ origin[0] + @as(f32, @floatFromInt(glyph.x)) * unit, origin[1] + @as(f32, @floatFromInt(glyph.y)) * unit }; + if (snapped) at = .{ @round(origin[0]) + @round(@as(f32, @floatFromInt(glyph.x)) * unit), @round(origin[1]) + @round(@as(f32, @floatFromInt(glyph.y)) * unit) }; + const x0 = (at[0] + @as(f32, @floatFromInt(slot.dx)) * stretch) / dpi; + const y0 = (at[1] + @as(f32, @floatFromInt(slot.dy)) * stretch) / dpi; + const x1 = x0 + @as(f32, @floatFromInt(slot.w)) * stretch / dpi; + const y1 = y0 + @as(f32, @floatFromInt(slot.h)) * stretch / dpi; + const s: f32 = 1.0 / @as(f32, side); + const s0 = @as(f32, @floatFromInt(slot.u)) * s; + const t0 = @as(f32, @floatFromInt(slot.v)) * s; + const s1 = @as(f32, @floatFromInt(slot.u + slot.w)) * s; + const t1 = @as(f32, @floatFromInt(slot.v + slot.h)) * s; + const quad = g.batch.addManyAsArray(g.gpa, 6) catch return; + const tl: c.SDL_Vertex = .{ .position = .{ .x = x0, .y = y0 }, .color = ink, .tex_coord = .{ .x = s0, .y = t0 } }; + const tr: c.SDL_Vertex = .{ .position = .{ .x = x1, .y = y0 }, .color = ink, .tex_coord = .{ .x = s1, .y = t0 } }; + const bl: c.SDL_Vertex = .{ .position = .{ .x = x0, .y = y1 }, .color = ink, .tex_coord = .{ .x = s0, .y = t1 } }; + const br: c.SDL_Vertex = .{ .position = .{ .x = x1, .y = y1 }, .color = ink, .tex_coord = .{ .x = s1, .y = t1 } }; + quad.* = .{ tl, tr, bl, tr, br, bl }; + } +} + +/// Draws the batch: the stage's new rows uploaded, then one geometry call. +pub fn flush(g: *Glyphs, renderer: *c.SDL_Renderer) void { + if (g.batch.items.len == 0) return; + defer g.batch.clearRetainingCapacity(); + const texture = g.texture orelse return; + g.upload(); + _ = c.SDL_SetTextureScaleMode(texture, if (g.linear) c.SDL_SCALEMODE_LINEAR else c.SDL_SCALEMODE_NEAREST); + _ = c.SDL_RenderGeometry(renderer, texture, g.batch.items.ptr, @intCast(g.batch.items.len), null, 0); +} + +fn start(g: *Glyphs, renderer: *c.SDL_Renderer) bool { + g.stage = g.gpa.alloc(u8, side * side) catch return false; + @memset(g.stage, 0); + const texture = c.SDL_CreateTexture(renderer, c.SDL_PIXELFORMAT_RGBA32, c.SDL_TEXTUREACCESS_STATIC, side, side) orelse { + g.gpa.free(g.stage); + g.stage = &.{}; + return false; + }; + _ = c.SDL_SetTextureBlendMode(texture, c.SDL_BLENDMODE_BLEND_PREMULTIPLIED); + g.texture = texture; + g.dirty = .{ 0, 0, side, side }; + return true; +} + +/// The stage's changed rectangle into the texture, coverage as white +/// premultiplied (r = g = b = a), 64 rows at a time. +fn upload(g: *Glyphs) void { + const d = g.dirty; + if (d[2] <= d[0] or d[3] <= d[1]) return; + const w = d[2] - d[0]; + const band = 64; + g.raster.resize(g.gpa, w * band * 4) catch return; + var top = d[1]; + while (top < d[3]) : (top += band) { + const h = @min(band, d[3] - top); + for (0..h) |y| for (0..w) |x| @memset(g.raster.items[(y * w + x) * 4 ..][0..4], g.stage[(top + y) * side + d[0] + x]); + const rect: c.SDL_Rect = .{ .x = @intCast(d[0]), .y = @intCast(top), .w = @intCast(w), .h = @intCast(h) }; + _ = c.SDL_UpdateTexture(g.texture, &rect, g.raster.items.ptr, @intCast(w * 4)); + } + g.dirty = .{ side, side, 0, 0 }; +} + +/// `key`'s slot, rasterized on first use; when the atlas is full, what is +/// pending is drawn and the atlas starts over. Null if it cannot hold it. +fn slotFor(g: *Glyphs, renderer: *c.SDL_Renderer, key: Key) ?Slot { + if (g.slots.get(key)) |s| return s; + return g.rasterize(key) orelse { + g.flush(renderer); + g.slots.clearRetainingCapacity(); + @memset(g.stage, 0); + g.shelf = .{}; + g.dirty = .{ 0, 0, side, side }; + return g.rasterize(key); + }; +} + +/// font.c's raster of `key`, its advance centred on the pen as pardes +/// centres a cell's, a margin of half its size around it; then trimmed to +/// its ink and shelved. Null when the atlas has no room. +fn rasterize(g: *Glyphs, key: Key) ?Slot { + const px = @as(f32, @floatFromInt(key.px)) / 64; + const font = c.sk_text_ui(key.face) orelse return null; + var cell_w: c_int = 0; + var height: c_int = 0; + var ascent: c_int = 0; + c.ui_font_cell_metrics(font, px, &cell_w, &height, &ascent); + const advance = @max(0, c.sk_text_advance(key.face, px, key.glyph)); + const pad: c_int = @intFromFloat(@ceil(px / 2) + 2); + const w: usize = @intCast(advance + 2 * pad); + const h: usize = @intCast(height + 2 * pad); + g.raster.resize(g.gpa, w * h) catch return null; + const blank = c.ui_font_raster(font, px, key.glyph, 0, g.raster.items.ptr, @intCast(w), @intCast(w), @intCast(h), pad, advance, ascent + pad) == 0; + const box = if (blank) null else Atlas.inkBounds(g.raster.items, w, w, h); + const b = box orelse { + g.slots.put(g.gpa, key, .{}) catch {}; + return .{}; + }; + const bw: u32 = @intCast(b.max_x - b.min_x + 1); + const bh: u32 = @intCast(b.max_y - b.min_y + 1); + // A new shelf when this one is full; a gap of a texel around each box, + // so LINEAR sampling at its edge reads nothing of a neighbour. + if (g.shelf.x + bw + 1 > side) g.shelf = .{ .y = g.shelf.y + g.shelf.h }; + if (g.shelf.y + bh + 1 > side or bw + 1 > side) return null; + const slot: Slot = .{ .u = @intCast(g.shelf.x), .v = @intCast(g.shelf.y), .w = @intCast(bw), .h = @intCast(bh), .dx = @intCast(@as(i64, @intCast(b.min_x)) - pad), .dy = @intCast(@as(i64, @intCast(b.min_y)) - pad - ascent) }; + g.slots.put(g.gpa, key, slot) catch return null; + for (0..bh) |y| @memcpy(g.stage[(slot.v + y) * side + slot.u ..][0..bw], g.raster.items[(b.min_y + y) * w + b.min_x ..][0..bw]); + g.dirty = .{ @min(g.dirty[0], slot.u), @min(g.dirty[1], slot.v), @max(g.dirty[2], slot.u + bw), @max(g.dirty[3], slot.v + bh) }; + g.shelf.x += bw + 1; + g.shelf.h = @max(g.shelf.h, bh + 1); + return slot; +} + +/// Device pixels a canvas unit: the render scale (a supersampled target's +/// 4) times the window's logical presentation, if it is drawing there. +fn density(renderer: *c.SDL_Renderer) f32 { + var sx: f32 = 1; + var sy: f32 = 1; + _ = c.SDL_GetRenderScale(renderer, &sx, &sy); + var w: c_int = 0; + var h: c_int = 0; + var mode: c.SDL_RendererLogicalPresentation = undefined; + var rect: c.SDL_FRect = undefined; + if (c.SDL_GetRenderLogicalPresentation(renderer, &w, &h, &mode) and mode != c.SDL_LOGICAL_PRESENTATION_DISABLED and w > 0 and h > 0 and c.SDL_GetRenderLogicalPresentationRect(renderer, &rect)) { + sx *= rect.w / @as(f32, @floatFromInt(w)); + sy *= rect.h / @as(f32, @floatFromInt(h)); + } + return @max(0.25, @max(sx, sy)); +} diff --git a/src/host/Host.zig b/src/host/Host.zig index 0a8eeee..ede02df 100644 --- a/src/host/Host.zig +++ b/src/host/Host.zig @@ -198,7 +198,7 @@ pub fn init(self: *Host, gpa: std.mem.Allocator, io: std.Io, environ: *const std .renderer = renderer.?, .gpu = gpu, .images = .{ .gpa = gpa, .renderer = renderer.? }, - .painter = .{ .renderer = renderer.?, .images = undefined, .smooth = gpu != null }, + .painter = .{ .renderer = renderer.?, .images = undefined, .smooth = gpu != null, .glyphs = .{ .gpa = gpa } }, .audio = .{ .gpa = gpa }, .state = .init(gpa), .session = .init(gpa), @@ -1128,7 +1128,8 @@ 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 { - return gfx.textSize(hostOf(ctx).renderer, scale, bytes, face); + _ = ctx; + return gfx.textSize(scale, bytes, 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 bde8a0a..4294b6a 100644 --- a/src/host/TimingAtlas.zig +++ b/src/host/TimingAtlas.zig @@ -19,7 +19,7 @@ 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(images.renderer, 1, "0", .mono); + const size = gfx.textSize(1, "0", .mono); 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 94e154f..f84568a 100644 --- a/src/host/gfx.zig +++ b/src/host/gfx.zig @@ -2,6 +2,7 @@ const std = @import("std"); const c = @import("c"); const abi = @import("abi"); +const Glyphs = @import("Glyphs.zig"); pub const Images = struct { gpa: std.mem.Allocator, @@ -172,6 +173,7 @@ pub const Painter = struct { backdrop_state: ?*c.SDL_GPURenderState = null, backdrop_shader: ?*c.SDL_GPUShader = null, backdrop_hash: u64 = 0, + glyphs: Glyphs, const Layer = struct { big: ?*c.SDL_Texture = null, @@ -199,6 +201,7 @@ pub const Painter = struct { } pub fn deinit(p: *Painter) void { + p.glyphs.deinit(); if (p.backdrop_texture) |t| c.SDL_DestroyTexture(t); if (p.backdrop_state) |state| c.SDL_DestroyGPURenderState(state); if (p.backdrop_shader) |shader| if (c.SDL_GetGPURendererDevice(p.renderer)) |device| c.SDL_ReleaseGPUShader(device, shader); @@ -220,6 +223,7 @@ pub const Painter = struct { /// Back to the canvas, blending alpha, unclipped: where overlays draw /// and screenshots read. pub fn end(p: *Painter) void { + p.glyphs.flush(p.renderer); p.flush(); if (p.target != .none) { p.target = .none; @@ -231,11 +235,11 @@ pub const Painter = struct { /// Draws one graphics command. Other commands are not graphics: ignored. pub fn draw(p: *Painter, command: abi.Command) void { + if (command != .text) p.glyphs.flush(p.renderer); if (command != .shape) p.flush(); const renderer = p.renderer; switch (command) { .clear => |color| { - if (@import("builtin").os.tag == .linux and p.target == .none) c.sk_text_begin_frame(renderer); // A target holds premultiplied colour, as a canvas cleared // to a translucent colour does. setColor(renderer, if (p.target == .none) color else premultiply(color)); @@ -249,10 +253,7 @@ pub const Painter = struct { .shape => |s| p.shape(s.color, s.points, s.ends, s.indices, s.colors), .image => |img| p.drawImage(img.image, img.dst, img.src, img.tint, img.corners), .backdrop => |b| p.backdrop(b.dst, b.fragment, b.uniforms), - .text => |text| { - _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND); - drawText(renderer, text.x, text.y, text.scale, text.bytes, text.color, text.face, if (text.raster > 0) text.raster else text.scale); - }, + .text => |text| p.glyphs.draw(renderer, text), .clip => |clip| { if (clip) |r| { const rect: c.SDL_Rect = .{ .x = @intFromFloat(r.x), .y = @intFromFloat(r.y), .w = @intFromFloat(r.w), .h = @intFromFloat(r.h) }; @@ -410,11 +411,19 @@ pub const Painter = struct { _ = c.SDL_SetGPURenderState(p.renderer, null); } + fn missing(p: *Painter, dst: abi.Rect) void { + _ = c.SDL_SetRenderDrawBlendMode(p.renderer, c.SDL_BLENDMODE_BLEND); + setColor(p.renderer, .{ .r = 110, .g = 30, .b = 70 }); + _ = c.SDL_RenderFillRect(p.renderer, &frect(dst)); + p.glyphs.draw(p.renderer, .{ .x = dst.x + 4, .y = dst.y + 4, .scale = 1, .bytes = "missing image", .color = .{ .r = 255, .g = 210, .b = 240 } }); + p.glyphs.flush(p.renderer); + } + fn drawImage(p: *Painter, handle: abi.Image, dst: abi.Rect, src_rect: abi.Rect, tint: abi.Color, corners: ?abi.Corners) void { const renderer = p.renderer; const entry = p.images.get(handle); const texture = if (entry) |e| e.texture else null; - const t = texture orelse return missing(renderer, dst); + const t = texture orelse return p.missing(dst); const e = entry.?; if (handle == p.target) return; // Drawing into itself: nothing. if (e.stale) p.resolve(e); @@ -604,45 +613,15 @@ fn fcolor(color: abi.Color) c.SDL_FColor { }; } -/// Native shaped text on Linux, using a 13px monospace face at scale 1. -/// Other targets retain SDL's built-in 8x8 fallback. Coordinates are line-box tops. -pub fn drawText(renderer: *c.SDL_Renderer, x: f32, y: f32, scale: f32, bytes: []const u8, color: abi.Color, face: abi.Face, raster: f32) void { - if (@import("builtin").os.tag == .linux and c.sk_text_draw_scaled(renderer, @backingInt(face), x, y, scale, raster, bytes.ptr, bytes.len, color.r, color.g, color.b, color.a)) return; - var buf: [1024]u8 = undefined; - const len = @min(std.mem.indexOfScalar(u8, bytes, 0) orelse bytes.len, buf.len - 1); - @memcpy(buf[0..len], bytes[0..len]); - buf[len] = 0; - setColor(renderer, color); - var sx: f32 = 1; - var sy: f32 = 1; - _ = c.SDL_GetRenderScale(renderer, &sx, &sy); - const s = @max(scale, 1); - // The clip rect scales with the renderer: shrink it to match, to the - // whole pixels around it (so it may let up to `s - 1` pixels more through). - var clip: c.SDL_Rect = undefined; - const clipped = c.SDL_RenderClipEnabled(renderer) and c.SDL_GetRenderClipRect(renderer, &clip); - _ = c.SDL_SetRenderScale(renderer, sx * s, sy * s); - if (clipped and s != 1) { - const x0 = @floor(@as(f32, @floatFromInt(clip.x)) / s); - const y0 = @floor(@as(f32, @floatFromInt(clip.y)) / s); - const x1 = @ceil(@as(f32, @floatFromInt(clip.x + clip.w)) / s); - const y1 = @ceil(@as(f32, @floatFromInt(clip.y + clip.h)) / s); - const scaled: c.SDL_Rect = .{ .x = @intFromFloat(x0), .y = @intFromFloat(y0), .w = @intFromFloat(x1 - x0), .h = @intFromFloat(y1 - y0) }; - _ = c.SDL_SetRenderClipRect(renderer, &scaled); - } - _ = c.SDL_RenderDebugText(renderer, x / s, y / s, &buf); - _ = c.SDL_SetRenderScale(renderer, sx, sy); - if (clipped and s != 1) _ = c.SDL_SetRenderClipRect(renderer, &clip); -} - -/// What `drawText` gives `bytes` at `scale`: its width and the height of -/// its line, in canvas units (`Host.textSize`). -pub fn textSize(renderer: *c.SDL_Renderer, scale: f32, bytes: []const u8, face: abi.Face) [2]f32 { - var size: [2]f32 = .{ 0, 0 }; - if (@import("builtin").os.tag == .linux and c.sk_text_measure_face(renderer, @backingInt(face), scale, bytes.ptr, bytes.len, &size[0], &size[1])) return size; - // The debug font's 8 px cells. - const s = @max(scale, 1); - return .{ @as(f32, @floatFromInt(bytes.len)) * 8 * s, 8 * s }; +/// 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; + 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) }; } fn premultiply(color: abi.Color) abi.Color { @@ -650,12 +629,6 @@ fn premultiply(color: abi.Color) abi.Color { return .{ .r = @intCast((color.r * a + 127) / 255), .g = @intCast((color.g * a + 127) / 255), .b = @intCast((color.b * a + 127) / 255), .a = color.a }; } -fn missing(renderer: *c.SDL_Renderer, dst: abi.Rect) void { - _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_BLEND); - setColor(renderer, .{ .r = 110, .g = 30, .b = 70 }); - _ = c.SDL_RenderFillRect(renderer, &frect(dst)); - drawText(renderer, dst.x + 4, dst.y + 4, 1, "missing image", .{ .r = 255, .g = 210, .b = 240 }, .mono, 1); -} fn setColor(renderer: *c.SDL_Renderer, color: abi.Color) void { _ = c.SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a); diff --git a/test/fonts.c b/test/fonts.c deleted file mode 100644 index cd3b9ff..0000000 --- a/test/fonts.c +++ /dev/null @@ -1,90 +0,0 @@ -/* Standalone Linux font regression/specimen. See vendor/fonts/README.md. */ -#include "../vendor/text.c" -#include <assert.h> -#include <stdio.h> - -static unsigned glyphs(PangoLayout *layout) { - unsigned count = 0; - PangoLayoutIter *it = pango_layout_get_iter(layout); - do { - PangoLayoutRun *run = pango_layout_iter_get_run_readonly(it); - if (run) count += run->glyphs->num_glyphs; - } while (pango_layout_iter_next_run(it)); - pango_layout_iter_free(it); - return count; -} -int main(int argc, char **argv) { - assert(SDL_Init(0)); - SDL_Surface *surface = SDL_CreateSurface(1440, 820, SDL_PIXELFORMAT_ARGB8888); - SDL_Renderer *r = SDL_CreateSoftwareRenderer(surface); - assert(r); - SDL_SetRenderDrawColor(r, 17, 21, 27, 255); SDL_RenderClear(r); - sk_text_begin_frame(r); - const char *samples[] = { - "Go Mono / native shaped text", - "Pardes / 46.8M accesses / 3.97M calls", - "0123456789 0x7ffed849acf0 () [] {} <> -> != ==", - "Latin: cafe\xcc\x81 / café / naïve / fi fl ffi", - "Greek / Cyrillic: λ → Ω Привет мир", - "Japanese fallback: 日本語 ひらがな カタカナ", - "Arabic shaping: العربية لا السلام عليكم", - "Hebrew bidi: שלום עולם | English 123", - "Symbols / emoji: ✓ ⌘ ⌥ ⌫ ⌜ ⌟ 😀 ★ ♥", - "draw.render → body_layer.renderBody → TerminalImages.draw" - }; - for (unsigned i=0; i<sizeof(samples)/sizeof(*samples); ++i) { - assert(sk_text_draw(r, 30, 25 + 53*i, i==0?2.2f:1.6f, samples[i], strlen(samples[i]), - i==0?228:165,i==0?234:178,i==0?242:195,255)); - TextCache *c=cache_for(r); - assert(pango_layout_get_unknown_glyphs_count(c->layout)==0); - } - TextCache *c=cache_for(r); - assert(sk_text_draw(r,30,575,1.0f,"e\xcc\x81",3,228,234,242,255)); - PangoRectangle combining, plain; - pango_layout_get_pixel_extents(c->layout,NULL,&combining); - assert(sk_text_draw(r,50,575,1.0f,"e",1,228,234,242,255)); - pango_layout_get_pixel_extents(c->layout,NULL,&plain); - assert(combining.width==plain.width); - assert(sk_text_draw(r,70,575,1.0f,"لا",strlen("لا"),228,234,242,255)); - assert(glyphs(c->layout)==1); - assert(sk_text_draw(r,120,575,1.0f,"0123456789",10,228,234,242,255)); - PangoRectangle bounds; pango_layout_get_pixel_extents(c->layout,NULL,&bounds); - assert(bounds.width>=75 && bounds.width<=85 && bounds.height>=13); - printf("scale 1: 10-digit advance %dpx, line box %dpx\n",bounds.width,bounds.height); - SDL_Rect clip={30,620,400,30}; SDL_SetRenderClipRect(r,&clip); - assert(sk_text_draw(r,30,617,1.6f,"Clipping preserves the baseline and glyph edges outside this box",strlen("Clipping preserves the baseline and glyph edges outside this box"),112,183,255,255)); - SDL_SetRenderClipRect(r,NULL); - assert(sk_text_draw(r,30,680,1.6f,"animated ink",12,240,20,40,255)); - const size_t cached_bytes = c->bytes; - assert(sk_text_draw(r,30,730,1.6f,"animated ink",12,40,20,240,128)); - assert(c->bytes == cached_bytes); /* Color and opacity reuse the coverage mask. */ - assert(SDL_RenderPresent(r)); - unsigned red_pixels = 0, blue_pixels = 0; - for (int y=680; y<780; ++y) for (int x=30; x<250; ++x) { - Uint8 red, green, blue, alpha; - assert(SDL_ReadSurfacePixel(surface,x,y,&red,&green,&blue,&alpha)); - if (y<710 && red>150 && blue<100) ++red_pixels; - if (y>=730 && blue>70 && red<70) ++blue_pixels; - } - assert(red_pixels>50 && blue_pixels>50); - if(argc>1) assert(SDL_SavePNG(surface,argv[1])); - assert(SDL_SetRenderLogicalPresentation(r,720,410,SDL_LOGICAL_PRESENTATION_LETTERBOX)); - assert(fabsf(density(r)-2)<0.01f); - assert(sk_text_draw(r,10,10,1.0f,"0123456789",10,228,234,242,255)); - pango_layout_get_pixel_extents(c->layout,NULL,&bounds); - assert(bounds.width>=150 && bounds.width<=170); - /* Eviction across frames and exhaustion inside one frame both stay bounded. */ - for(unsigned i=0;i<800;i++) { - if(i%100==0) sk_text_begin_frame(r); - char text[32]; int n=snprintf(text,sizeof(text),"cache %u",i); - assert(sk_text_draw(r,0,0,1,text,(size_t)n,255,255,255,255)); - assert(c->bytes<=CACHE_BYTES); - } - for(unsigned i=0;i<600;i++) { - char text[32]; int n=snprintf(text,sizeof(text),"transient %u",i); - assert(sk_text_draw(r,0,0,1,text,(size_t)n,255,255,255,255)); - assert(c->bytes<=CACHE_BYTES); - } - SDL_DestroyRenderer(r); SDL_DestroySurface(surface); SDL_Quit(); - puts("Go Mono, fallback, combining marks, Arabic shaping, 2x DPI, clipping and bounded cache passed"); -} diff --git a/vendor/README.md b/vendor/README.md index 1d3e42b..990dd0e 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -12,6 +12,10 @@ Single-file codecs, vendored unchanged; `codecs.c` compiles them for the host. `font.c` and `font.h` are pardes's FreeType and HarfBuzz shim, moved from its `src/gui/` unchanged, under `src/font/Atlas.zig`. The embedder compiles them against its own FreeType and HarfBuzz and exports `ui_malloc` and friends. +`text.c` and `text.h` are sketchbook's text over them: the faces in +`fonts/`, shaped by HarfBuzz, and `ui_malloc` over C's heap. `build.zig` +compiles the three, with FreeType and HarfBuzz (the packages and flags +pardes uses), into the static library `sketchbook-text`. `presentation-time/presentation-time.xml` is the Wayland presentation-time v3 protocol description (the client binds v1; its license is included in the XML). diff --git a/vendor/fonts/README.md b/vendor/fonts/README.md index b02fd51..e9ac1ec 100644 --- a/vendor/fonts/README.md +++ b/vendor/fonts/README.md @@ -1,72 +1,26 @@ -# Native text +# Native text's faces -Linux Sketchbook text uses bundled **Go Mono** through PangoCairo: HarfBuzz -shaping, Fontconfig fallback and FreeType/Cairo grayscale antialiasing with light -hinting. This follows the rendering quality choices in Pardes `src/gui/font.c`; -it does not copy Pardes's terminal-cell shaping, bold synthesis or glyph atlas. +Sketchbook's native text is shaped by HarfBuzz and rasterized by pardes's +`vendor/font.c` over FreeType (`vendor/text.c`, built into the host as the +static library `sketchbook-text`; see `docs/text.md`). These files are its +faces, embedded in the binary with C23 `#embed`, in `abi.Face`'s order. No +installed font is read: there is no fontconfig. `Go-Mono.ttf` is from the Go project's official `golang/image` repository: https://github.com/golang/image/tree/master/font/gofont/ttfs SHA-256: `8bc66a0154bbf69cd24e5bde41a12ec9495c8a242c5def2255e4a164900f1ed7`. The complete Bigelow & Holmes / Go font license is in `LICENSE`. -Five more faces of the same family are bundled the same way, for -`f.textIn(face, ...)` (`abi.Face`, in this order after Go Mono): -`Go-Mono-Bold.ttf`, `Go-Mono-Italic.ttf`, `Go-Regular.ttf`, `Go-Medium.ttf`, -`Go-Bold.ttf`, as the `ttf-go` package installs them (the same upstream). -Each is a font description of its own (`sk_text_draw_face`); the sans -faces fall back to installed sans families instead of mono ones. +Five more faces of the same family follow it: `Go-Mono-Bold.ttf`, +`Go-Mono-Italic.ttf`, `Go-Regular.ttf`, `Go-Medium.ttf`, `Go-Bold.ttf`, as +the `ttf-go` package installs them (the same upstream). Four faces of **JetBrains Mono NL** (the family without ligatures) follow them (`.code`, `.code_bold`, `.code_italic`, `.code_medium`): `JetBrainsMonoNL-Regular.ttf`, `-Bold.ttf`, `-Italic.ttf` and `-Medium.ttf` -as the `ttf-jetbrains-mono` package installs them, under the -SIL Open Font License in `LICENSE-JetBrainsMono`. They fall back as the -mono faces do. +as the `ttf-jetbrains-mono` package installs them, under the SIL Open Font +License in `LICENSE-JetBrainsMono`. -The fonts are embedded in the binary with C23 `#embed`. It is registered in a -private Fontconfig config through a Linux memfd, so moving the executable does -not require a font installation or the source checkout. Installed outline fonts -provide Unicode fallback, in the order listed in `vendor/text.c`; actual glyph -coverage and emoji color depend on those fonts. Color font paint is preserved. -No system Fontconfig settings are modified. - -The `f.text`/`f.print` API is unchanged. Their x/y positions mean line-box top. -Scale 1 uses a nominal 13px font: Go Mono measures 8px ASCII advance and 16px -line height on the tested stack. At other sizes advances may round to a physical -pixel. Applications should allow a 16×scale line box and avoid slicing UTF-8 at -arbitrary byte boundaries. Pango shapes each supplied string independently; -applications still perform wrapping and clipping. Explicit newlines are not a -layout API. Other platforms retain SDL's debug-font fallback for now. - -`sk_text_measure` lays a string out the same way and returns its advance -width and line height (`Host.textSize`). `SKETCHBOOK_FONT`, in the -environment, names an installed family to put before Go Mono. - -Text is rasterized at the renderer's physical pixel density (including logical -presentation scale), and texture origins snap to physical pixels. Whole-run -textures retain antialiasing and shaping; no scaled 8×8 bitmap text is involved. -The renderer-owned cache retains at most 4096 strings / 128 MiB of pixel data. -ASCII runs cache white coverage masks and tint at draw time, so animated ink -reuses the same pixels. Unicode retains painted glyphs, including color emoji. -Only prior-frame textures can be evicted; exceptionally dense frames flush and -release temporary textures rather than growing the cache. Renderer destruction -releases the font map, descriptors and keys after SDL releases its textures. - -Native Linux builds need `pkg-config`, `pangocairo`, and `pangoft2` development -packages, in addition to SDL. The resulting executable uses the system Pango, -Cairo, HarfBuzz, Fontconfig and FreeType libraries. - -Run the independent regression and specimen (with system SDL3): - -```sh -cc -std=c23 -Wall -Wextra -Werror -O2 test/fonts.c -o /tmp/sketchbook-fonts \ - $(pkg-config --cflags --libs sdl3 pangocairo pangoft2) -lm -/tmp/sketchbook-fonts /tmp/sketchbook-fonts.png -``` - -It checks the primary font's advance/line box, Unicode fallback, zero-advance -combining marks, Arabic lam-alef shaping, 2× rendering density, clipping, cache -eviction and renderer cleanup. The specimen includes Latin, Greek, Cyrillic, -Japanese, Arabic, Hebrew and symbols/emoji. Missing fallback fonts fail the -coverage assertion rather than silently claiming complete Unicode support. +A codepoint a face lacks comes from one fallback: JetBrains Mono NL for the +Go faces (and a sketch's own), Go Mono for JetBrains Mono's. Neither family +has CJK, Arabic, Hebrew or emoji: those draw as the missing-glyph box. diff --git a/vendor/text.c b/vendor/text.c index a453067..818597d 100644 --- a/vendor/text.c +++ b/vendor/text.c @@ -1,23 +1,20 @@ -/* Native text: Pardes's FreeType/HarfBuzz quality target, via Pango's complete - script itemization, shaping, bidi and Fontconfig fallback instead of its - terminal-cell-specific shaping layer. Grayscale coverage avoids color fringes. */ -#define _GNU_SOURCE +/* sketchbook's text (text.h): HarfBuzz shapes, pardes's font.c rasterizes + and gives the line box. The ten bundled faces are embedded with #embed; + each face is opened on first use, by FreeType (font.c) and HarfBuzz's + own OpenType functions over the same bytes, so glyph ids agree. */ #include "text.h" -#include <fontconfig/fontconfig.h> -#include <pango/pangofc-fontmap.h> -#include <sys/mman.h> -#include <unistd.h> -#include <errno.h> -#include <pango/pangocairo.h> +#include <hb.h> #include <math.h> -#include <stdint.h> #include <stdlib.h> #include <string.h> -#define CACHE_ENTRIES 4096 -#define CACHE_BYTES (128 * 1024 * 1024) -#define CACHE_PROPERTY "sketchbook.native-text" -/* The Go family, bundled: one file a face, in `SkTextFace` order. */ +/* font.h's allocator, for FreeType and HarfBuzz (built with + hb_malloc_impl=ui_malloc): C's heap. */ +void *ui_malloc(size_t size) { return malloc(size); } +void *ui_calloc(size_t count, size_t size) { return calloc(count, size); } +void *ui_realloc(void *block, size_t size) { return realloc(block, size); } +void ui_free(void *block) { free(block); } + static const unsigned char go_mono[] = { #embed "fonts/Go-Mono.ttf" }; @@ -36,8 +33,6 @@ static const unsigned char go_medium[] = { static const unsigned char go_bold[] = { #embed "fonts/Go-Bold.ttf" }; -/* JetBrains Mono NL, for code: the same 0.6 em advance as Go Mono, and no - ligatures (`->` stays two characters, as it is in the source). */ static const unsigned char jb_mono[] = { #embed "fonts/JetBrainsMonoNL-Regular.ttf" }; @@ -50,281 +45,143 @@ static const unsigned char jb_mono_italic[] = { static const unsigned char jb_mono_medium[] = { #embed "fonts/JetBrainsMonoNL-Medium.ttf" }; -static const struct { const unsigned char *bytes; size_t len; const char *family, *style; } faces[SK_TEXT_FACES] = { - {go_mono, sizeof(go_mono), "Go Mono", ""}, - {go_mono_bold, sizeof(go_mono_bold), "Go Mono", " Bold"}, - {go_mono_italic, sizeof(go_mono_italic), "Go Mono", " Italic"}, - {go_regular, sizeof(go_regular), "Go", ""}, - {go_medium, sizeof(go_medium), "Go Medium", ""}, - {go_bold, sizeof(go_bold), "Go", " Bold"}, - {jb_mono, sizeof(jb_mono), "JetBrains Mono NL", ""}, - {jb_mono_bold, sizeof(jb_mono_bold), "JetBrains Mono NL", " Bold"}, - {jb_mono_italic, sizeof(jb_mono_italic), "JetBrains Mono NL", " Italic"}, - {jb_mono_medium, sizeof(jb_mono_medium), "JetBrains Mono NL", " Medium"}, -}; -typedef struct { - SDL_Texture *texture; - char *text; - size_t len, bytes; - uint64_t hash, used; - int size, width, height, left, top, face; - Uint32 color; -} Text; -typedef struct { - PangoFontMap *map; - PangoContext *context; - PangoLayout *layout; - PangoFontDescription *font[SK_TEXT_FACES]; - FcConfig *config; - int font_fd[SK_TEXT_FACES]; - Text entries[CACHE_ENTRIES]; - size_t bytes; - uint64_t frame; -} TextCache; +/* ponytail: one thread. The host shapes on its main thread, a test binary + on the runner's; a second thread would need a lock here. */ +static struct { + const uint8_t *bytes; + size_t len; + UIFont *ui; + hb_font_t *hb; +} faces[SK_TEXT_MAX_FACES] = { + {go_mono, sizeof go_mono}, {go_mono_bold, sizeof go_mono_bold}, + {go_mono_italic, sizeof go_mono_italic}, {go_regular, sizeof go_regular}, + {go_medium, sizeof go_medium}, {go_bold, sizeof go_bold}, + {jb_mono, sizeof jb_mono}, {jb_mono_bold, sizeof jb_mono_bold}, + {jb_mono_italic, sizeof jb_mono_italic}, {jb_mono_medium, sizeof jb_mono_medium}, +}; +static int count = SK_TEXT_FACES; +static hb_buffer_t *buffer; -static void release_text(Text *t) { - if (t->texture) SDL_DestroyTexture(t->texture); - free(t->text); - memset(t, 0, sizeof(*t)); -} -static void SDLCALL release_cache(void *userdata, void *value) { - (void)userdata; - TextCache *c = value; - /* SDL destroys its owned textures before renderer property cleanup. */ - for (size_t i = 0; i < CACHE_ENTRIES; ++i) free(c->entries[i].text); - for (int i = 0; i < SK_TEXT_FACES; ++i) if (c->font[i]) pango_font_description_free(c->font[i]); - if (c->layout) g_object_unref(c->layout); - if (c->context) g_object_unref(c->context); - if (c->map) g_object_unref(c->map); - if (c->config) FcConfigDestroy(c->config); - for (int i = 0; i < SK_TEXT_FACES; ++i) if (c->font_fd[i] >= 0) close(c->font_fd[i]); - free(c); -} -static TextCache *cache_for(SDL_Renderer *renderer) { - SDL_PropertiesID props = SDL_GetRendererProperties(renderer); - TextCache *c = SDL_GetPointerProperty(props, CACHE_PROPERTY, NULL); - if (c) return c; - c = calloc(1, sizeof(*c)); - if (!c) return NULL; - for (int i = 0; i < SK_TEXT_FACES; ++i) c->font_fd[i] = -1; - c->config = FcInitLoadConfigAndFonts(); - if (!c->config) { release_cache(NULL, c); return NULL; } - for (int i = 0; i < SK_TEXT_FACES; ++i) { - c->font_fd[i] = memfd_create("sketchbook-go", MFD_CLOEXEC); - if (c->font_fd[i] < 0) { release_cache(NULL, c); return NULL; } - size_t offset = 0; - while (offset < faces[i].len) { - ssize_t n = write(c->font_fd[i], faces[i].bytes + offset, faces[i].len - offset); - if (n < 0 && errno == EINTR) continue; - if (n <= 0) { release_cache(NULL, c); return NULL; } - offset += (size_t)n; - } - char path[64]; - snprintf(path, sizeof(path), "/proc/self/fd/%d", c->font_fd[i]); - if (!FcConfigAppFontAddFile(c->config, (const FcChar8 *)path)) { - release_cache(NULL, c); - return NULL; - } - } - c->map = pango_cairo_font_map_new_for_font_type(CAIRO_FONT_TYPE_FT); - pango_fc_font_map_set_config(PANGO_FC_FONT_MAP(c->map), c->config); - c->context = pango_font_map_create_context(c->map); - c->layout = pango_layout_new(c->context); - /* SKETCHBOOK_FONT names an installed family to use before the built-in - mono one. The sans faces fall back the same way after their own. */ - const char *first = getenv("SKETCHBOOK_FONT"); - for (int i = 0; i < SK_TEXT_FACES; ++i) { - const bool mono = i <= SK_TEXT_MONO_ITALIC || i >= SK_TEXT_CODE; - char families[640]; - snprintf(families, sizeof(families), "%s%s%s, %sNoto Sans Arabic, Noto Sans Hebrew, IBM Plex Sans JP, Noto Color Emoji, Noto Sans Symbols 2, DejaVu Sans, %s%s", - mono && first ? first : "", mono && first ? ", " : "", faces[i].family, - mono ? "Noto Sans Mono, DejaVu Sans Mono, " : "Go, Noto Sans, ", mono ? "monospace" : "sans-serif", faces[i].style); - c->font[i] = pango_font_description_from_string(families); - } - cairo_font_options_t *options = cairo_font_options_create(); - cairo_font_options_set_antialias(options, CAIRO_ANTIALIAS_GRAY); - cairo_font_options_set_hint_style(options, CAIRO_HINT_STYLE_SLIGHT); - cairo_font_options_set_hint_metrics(options, CAIRO_HINT_METRICS_ON); - pango_cairo_context_set_font_options(c->context, options); - cairo_font_options_destroy(options); - pango_context_set_round_glyph_positions(c->context, TRUE); - pango_layout_set_single_paragraph_mode(c->layout, TRUE); - c->frame = 1; - if (!SDL_SetPointerPropertyWithCleanup(props, CACHE_PROPERTY, c, release_cache, NULL)) { - release_cache(NULL, c); - return NULL; - } - return c; +/* `face` opened, or the mono for an unknown one. */ +static int open_face(int face) { + if (face < 0 || face >= count) face = SK_TEXT_MONO; + if (!faces[face].ui) { + faces[face].ui = ui_font_new(faces[face].bytes, (int32_t)faces[face].len); + hb_blob_t *blob = hb_blob_create((const char *)faces[face].bytes, (unsigned)faces[face].len, + HB_MEMORY_MODE_READONLY, NULL, NULL); + hb_face_t *hb_face = hb_face_create(blob, 0); + faces[face].hb = hb_font_create(hb_face); + hb_face_destroy(hb_face); + hb_blob_destroy(blob); + } + return face; } -void sk_text_begin_frame(SDL_Renderer *renderer) { - TextCache *c = SDL_GetPointerProperty(SDL_GetRendererProperties(renderer), CACHE_PROPERTY, NULL); - /* A sketch may clear twice in a frame. Flush first so any eviction of a - previous epoch can never destroy a texture referenced by queued draws. */ - if (c) { - SDL_FlushRenderer(renderer); - ++c->frame; - } +UIFont *sk_text_ui(int face) { + if (face < 0 || face >= count) return NULL; + return faces[open_face(face)].ui; } -static float density(SDL_Renderer *renderer) { - float sx = 1, sy = 1; - SDL_GetRenderScale(renderer, &sx, &sy); - int w = 0, h = 0; - SDL_RendererLogicalPresentation mode; - SDL_FRect rect; - if (SDL_GetRenderLogicalPresentation(renderer, &w, &h, &mode) && - mode != SDL_LOGICAL_PRESENTATION_DISABLED && w > 0 && h > 0 && - SDL_GetRenderLogicalPresentationRect(renderer, &rect)) { - sx *= rect.w / w; - sy *= rect.h / h; - } - return fmaxf(0.25f, fmaxf(sx, sy)); -} -static uint64_t hash_text(const char *bytes, size_t len) { - uint64_t hash = UINT64_C(14695981039346656037); - for (size_t i = 0; i < len; ++i) hash = (hash ^ (unsigned char)bytes[i]) * UINT64_C(1099511628211); - return hash; -} -/* The font size, in 64ths of a physical pixel, that `scale` asks for. */ -static int font_size(float scale, float dpi) { - return (int)lroundf(fminf(512, 13.0f * scale * dpi) * 64); -} -/* Lays `bytes` out at `size`: its extents in physical pixels (`ink` may be NULL). */ -static bool lay_out(TextCache *c, const char *bytes, size_t len, int size, int face, - PangoRectangle *ink, PangoRectangle *logical) { - if (len > INT_MAX || !g_utf8_validate(bytes, (gssize)len, NULL)) return false; - pango_font_description_set_absolute_size(c->font[face], (double)size * PANGO_SCALE / 64.0); - pango_layout_set_font_description(c->layout, c->font[face]); - pango_layout_set_text(c->layout, bytes, (int)len); - pango_layout_get_pixel_extents(c->layout, ink, logical); - return true; -} -static bool rasterize(TextCache *c, SDL_Renderer *renderer, Text *out, - const char *bytes, size_t len, int size, int face, Uint32 color) { - PangoRectangle ink, logical; - if (!lay_out(c, bytes, len, size, face, &ink, &logical)) return false; - const int left = MIN(0, ink.x) - 1; - const int top = MIN(0, ink.y) - 1; - const int width = MAX(logical.x + logical.width, ink.x + ink.width) - left + 1; - const int height = MAX(logical.y + logical.height, ink.y + ink.height) - top + 1; - if (width <= 0 || height <= 0 || width > 16384 || height > 4096 || - (size_t)width * height * 4 > CACHE_BYTES) return false; - cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); - if (cairo_surface_status(surface) != CAIRO_STATUS_SUCCESS) { - cairo_surface_destroy(surface); - return false; - } - cairo_t *cr = cairo_create(surface); - cairo_set_source_rgb(cr, ((color >> 16) & 255) / 255.0, ((color >> 8) & 255) / 255.0, (color & 255) / 255.0); - cairo_move_to(cr, -left, -top); - pango_cairo_show_layout(cr, c->layout); - cairo_destroy(cr); - cairo_surface_flush(surface); - SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, - SDL_TEXTUREACCESS_STATIC, width, height); - const bool okay = texture && SDL_UpdateTexture(texture, NULL, cairo_image_surface_get_data(surface), - cairo_image_surface_get_stride(surface)); - cairo_surface_destroy(surface); - if (!okay) { if (texture) SDL_DestroyTexture(texture); return false; } - SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND_PREMULTIPLIED); - SDL_SetTextureScaleMode(texture, SDL_SCALEMODE_LINEAR); - char *key = malloc(len + 1); - if (!key) { SDL_DestroyTexture(texture); return false; } - memcpy(key, bytes, len); key[len] = 0; - *out = (Text){.texture=texture,.text=key,.len=len,.bytes=(size_t)width*height*4, - .hash=hash_text(bytes,len),.used=c->frame,.size=size,.width=width,.height=height, - .left=left,.top=top,.face=face,.color=color}; - return true; +int sk_text_font(const uint8_t *bytes, size_t len) { + if (!bytes || len == 0 || len > INT32_MAX) return -1; + for (int i = SK_TEXT_FACES; i < count; i++) + if (faces[i].len == len && memcmp(faces[i].bytes, bytes, len) == 0) return i; + if (count == SK_TEXT_MAX_FACES) return -1; + uint8_t *copy = malloc(len); + if (!copy) return -1; + memcpy(copy, bytes, len); + UIFont *ui = ui_font_new(copy, (int32_t)len); + if (!ui) { + free(copy); + return -1; + } + faces[count].bytes = copy; + faces[count].len = len; + faces[count].ui = ui; + open_face(count); /* its HarfBuzz font */ + return count++; } -bool sk_text_measure(SDL_Renderer *renderer, float scale, const char *utf8, size_t len, - float *width, float *height) { - return sk_text_measure_face(renderer, SK_TEXT_MONO, scale, utf8, len, width, height); +/* ponytail: one fallback face, no fontconfig. JetBrains Mono NL for the Go + faces and a sketch's own, Go Mono for JetBrains Mono's. */ +static int fallback(int face) { + return face >= SK_TEXT_CODE && face < SK_TEXT_FACES ? SK_TEXT_MONO : SK_TEXT_CODE; } -bool sk_text_measure_face(SDL_Renderer *renderer, int face, float scale, const char *utf8, size_t len, - float *width, float *height) { - if (!isfinite(scale) || scale <= 0 || face < 0 || face >= SK_TEXT_FACES) return false; - TextCache *c = cache_for(renderer); - if (!c) return false; - const float dpi = density(renderer); - PangoRectangle logical; - if (!lay_out(c, utf8, len, font_size(scale, dpi), face, NULL, &logical)) return false; - *width = logical.width / dpi; - *height = logical.height / dpi; - return true; +/* The codepoint at `s` and its length; an invalid byte is U+FFFD, one byte. */ +static size_t decode(const unsigned char *s, size_t n, uint32_t *cp) { + const unsigned lead = s[0]; + const size_t len = lead < 0x80 ? 1 : (lead >> 5) == 6 ? 2 : (lead >> 4) == 14 ? 3 : (lead >> 3) == 30 ? 4 : 0; + if (len == 0 || len > n) return *cp = 0xfffd, 1; + uint32_t v = len == 1 ? lead : lead & (0x7f >> len); + for (size_t i = 1; i < len; i++) { + if ((s[i] & 0xc0) != 0x80) return *cp = 0xfffd, 1; + v = v << 6 | (s[i] & 0x3f); + } + *cp = v; + return len; } -bool sk_text_draw(SDL_Renderer *renderer, float x, float y, float scale, - const char *utf8, size_t len, Uint8 r, Uint8 g, Uint8 b, Uint8 a) { - return sk_text_draw_face(renderer, SK_TEXT_MONO, x, y, scale, utf8, len, r, g, b, a); -} +static int32_t whole(hb_position_t v) { return (int32_t)lroundf((float)v / 64.0f); } -bool sk_text_draw_face(SDL_Renderer *renderer, int face, float x, float y, float scale, - const char *utf8, size_t len, Uint8 r, Uint8 g, Uint8 b, Uint8 a) { - return sk_text_draw_scaled(renderer, face, x, y, scale, scale, utf8, len, r, g, b, a); +static int scale_of(float px) { return (int)lroundf(fmaxf(px, 1.0f) * 64.0f); } + +int32_t sk_text_advance(int face, float px, uint32_t glyph) { + hb_font_t *hb = faces[open_face(face)].hb; + hb_font_set_scale(hb, scale_of(px), scale_of(px)); + return whole(hb_font_get_glyph_h_advance(hb, glyph)); } -bool sk_text_draw_scaled(SDL_Renderer *renderer, int face, float x, float y, float scale, float raster, - const char *utf8, size_t len, Uint8 r, Uint8 g, Uint8 b, Uint8 a) { - if (!len || !a) return true; - if (!isfinite(scale) || scale <= 0 || !isfinite(raster) || raster <= 0 || face < 0 || face >= SK_TEXT_FACES) return false; - TextCache *c = cache_for(renderer); - if (!c) return false; - const float dpi = density(renderer); - const int size = font_size(raster, dpi); - /* How much larger than rasterized it is drawn: 1 when it is drawn as it is. */ - const float k = scale / raster; - /* ASCII uses a reusable coverage mask; animated ink never rerasterizes it. - Keep the existing painted path for Unicode, including color emoji. */ - bool mask = true; - for (size_t i = 0; i < len; ++i) if ((unsigned char)utf8[i] >= 128) { mask = false; break; } - const Uint32 color = mask ? 0xffffff : ((Uint32)r << 16) | ((Uint32)g << 8) | b; - const uint64_t hash = hash_text(utf8, len); - Text *entry = NULL; - for (size_t i = 0; i < CACHE_ENTRIES; ++i) { - Text *t = &c->entries[i]; - if (t->texture && t->hash == hash && t->len == len && t->size == size && t->face == face && - t->color == color && !memcmp(t->text, utf8, len)) { entry = t; break; } - } - Text made = {0}; - if (!entry) { - if (!rasterize(c, renderer, &made, utf8, len, size, face, color)) return false; - /* Only evict textures unused this epoch. SDL can still have queued draws - referring to current-frame entries; those stay alive through present. */ - while (!entry) { - Text *oldest = NULL; - for (size_t i = 0; i < CACHE_ENTRIES; ++i) { - Text *t = &c->entries[i]; - if (!t->texture) { if (!entry) entry = t; } - else if (t->used < c->frame && (!oldest || t->used < oldest->used)) oldest = t; - } - if (entry && c->bytes + made.bytes <= CACHE_BYTES) break; - entry = NULL; - if (!oldest) break; - c->bytes -= oldest->bytes; - release_text(oldest); - } - if (entry) { *entry = made; c->bytes += made.bytes; } - else entry = &made; +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) { + face = open_face(face); + const int other = open_face(fallback(face)); + int32_t cell_w, cell_h, asc; + ui_font_cell_metrics(faces[face].ui, px, &cell_w, &cell_h, &asc); + *ascent = asc; + *height = cell_h; + *advance = 0; + if (!utf8 || len == 0 || len > INT32_MAX) return 0; + if (!buffer) buffer = hb_buffer_create(); + const int scale = scale_of(px); + int n = 0; + int32_t pen = 0; + size_t i = 0; + while (i < len) { + /* A segment: the codepoints one face draws. A codepoint goes to the + fallback only when the face lacks it and the fallback has it. */ + const size_t start = i; + int which = -1; + while (i < len) { + uint32_t cp; + const size_t step = decode((const unsigned char *)utf8 + i, len - i, &cp); + const int own = ui_font_glyph(faces[face].ui, (int32_t)cp) != 0 || + ui_font_glyph(faces[other].ui, (int32_t)cp) == 0; + const int here = own ? face : other; + if (which < 0) which = here; + else if (here != which) break; + i += step; } - entry->used = c->frame; - /* Cairo pixels are premultiplied; modulate RGB and alpha together. Color - glyphs retain their intrinsic paint, while ordinary text uses its ink. */ - SDL_SetTextureColorMod(entry->texture, mask ? r * a / 255 : a, mask ? g * a / 255 : a, mask ? b * a / 255 : a); - SDL_SetTextureAlphaMod(entry->texture, a); - SDL_FRect dest = {.x=(roundf(x*dpi)+entry->left)/dpi,.y=(roundf(y*dpi)+entry->top)/dpi, - .w=entry->width/dpi,.h=entry->height/dpi}; - if (k != 1) dest = (SDL_FRect){.x=x+entry->left*k/dpi,.y=y+entry->top*k/dpi, - .w=entry->width*k/dpi,.h=entry->height*k/dpi}; - const bool okay = SDL_RenderTexture(renderer, entry->texture, NULL, &dest); - if (entry == &made) { - /* Exceptional very dense frames remain bounded instead of retaining - every unique string. Flush before releasing this temporary texture. */ - SDL_FlushRenderer(renderer); - release_text(&made); + hb_font_t *hb = faces[which].hb; + hb_font_set_scale(hb, scale, scale); + hb_buffer_clear_contents(buffer); + /* The whole text as context, the segment as the item: clusters are + byte offsets into `utf8`. */ + hb_buffer_add_utf8(buffer, utf8, (int)len, (unsigned)start, (int)(i - start)); + hb_buffer_set_direction(buffer, HB_DIRECTION_LTR); /* ponytail: no bidi */ + hb_buffer_guess_segment_properties(buffer); + hb_shape(hb, buffer, NULL, 0); + unsigned glyphs = 0; + const hb_glyph_info_t *info = hb_buffer_get_glyph_infos(buffer, &glyphs); + const hb_glyph_position_t *pos = hb_buffer_get_glyph_positions(buffer, &glyphs); + for (unsigned k = 0; k < glyphs; k++, n++) { + if (out && n < max) + out[n] = (SkGlyph){info[k].codepoint, info[k].cluster, pen + whole(pos[k].x_offset), + -whole(pos[k].y_offset), (uint8_t)which}; + pen += whole(pos[k].x_advance); } - return okay; + } + *advance = pen; + return n; } diff --git a/vendor/text.h b/vendor/text.h index aa49db8..dd4eecf 100644 --- a/vendor/text.h +++ b/vendor/text.h @@ -1,26 +1,45 @@ +/* sketchbook's text: the faces (`abi.Face`'s ten, bundled, and a sketch's + own from bytes), shaped by HarfBuzz and rasterized by pardes's font.c. + One static library, `sketchbook-text`, linked by the host and by a + sketch's tests, so both measure with the same code. */ #ifndef SKETCHBOOK_TEXT_H #define SKETCHBOOK_TEXT_H -#include <SDL3/SDL.h> +#include "font.h" #include <stddef.h> -/* x/y are the logical line-box top. Scale 1 is 13 px Go Mono (roughly - eight-pixel ASCII advance and a 16-pixel line box); fallback uses Fontconfig. */ -bool sk_text_draw(SDL_Renderer *, float x, float y, float scale, - const char *utf8, size_t len, Uint8 r, Uint8 g, Uint8 b, Uint8 a); -/* What sk_text_draw gives the text at `scale`: its advance width and the - height of its line box, in logical units. False if it cannot be laid out. */ -bool sk_text_measure(SDL_Renderer *, float scale, const char *utf8, size_t len, - float *width, float *height); -/* The same in another face of the bundled Go family (`abi.Face`'s order). */ +#include <stdint.h> + enum { SK_TEXT_MONO, SK_TEXT_MONO_BOLD, SK_TEXT_MONO_ITALIC, SK_TEXT_SANS, SK_TEXT_SANS_MEDIUM, SK_TEXT_SANS_BOLD, SK_TEXT_CODE, SK_TEXT_CODE_BOLD, SK_TEXT_CODE_ITALIC, SK_TEXT_CODE_MEDIUM, SK_TEXT_FACES }; -bool sk_text_draw_face(SDL_Renderer *, int face, float x, float y, float scale, - const char *utf8, size_t len, Uint8 r, Uint8 g, Uint8 b, Uint8 a); -bool sk_text_measure_face(SDL_Renderer *, int face, float scale, const char *utf8, size_t len, - float *width, float *height); -/* The same, laid out and rasterized at `raster` and drawn at `scale`: the - glyphs keep their places against each other while the size changes (a - camera moving), and one texture serves every size on the way. Its - position is not snapped to a pixel. */ -bool sk_text_draw_scaled(SDL_Renderer *, int face, float x, float y, float scale, float raster, - const char *utf8, size_t len, Uint8 r, Uint8 g, Uint8 b, Uint8 a); -void sk_text_begin_frame(SDL_Renderer *); +#define SK_TEXT_MAX_FACES 64 + +/* One glyph of a shaped run: `face` draws it (the run's, or its fallback), + `cluster` is the byte it starts at, `x`/`y` its pen position in whole + pixels from the run's start (y down). */ +typedef struct { + uint32_t glyph; + uint32_t cluster; + int32_t x; + int32_t y; + uint8_t face; +} SkGlyph; + +/* `utf8` in `face` at `px` pixels, left to right: at most `max` glyphs into + `out` (NULL to measure only). Returns how many there are (more than `max` + when they did not fit), with the run's advance, its ascent and its line's + height, all in whole pixels: each glyph's advance is rounded, and the + line box is FreeType's at that size (font.h's cell metrics). Invalid + UTF-8 shapes as U+FFFD; an unknown face as the mono. */ +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); + +/* `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); + +/* A face for a sketch's own font, its bytes copied: the same id for the + same bytes. -1 when FreeType refuses them or every face is taken. */ +int sk_text_font(const uint8_t *bytes, size_t len); + +/* What rasterizes `face` (font.h's ui_font_raster), NULL if none. */ +UIFont *sk_text_ui(int face); + #endif |
