diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-17 03:00:00 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 12:15:01 -0300 |
| commit | 1d4015b1b9740a894bea288dadb11d212eceff73 (patch) | |
| tree | afbe13324d480e0c758ebd228c8dc37c67ac20f5 /src/gui/gui.zig | |
| parent | e8662178dba9d779cbfaa290154ae78c61402d30 (diff) | |
| download | pardes-1d4015b1b9740a894bea288dadb11d212eceff73.tar.gz pardes-1d4015b1b9740a894bea288dadb11d212eceff73.zip | |
gui: the font shim and the glyph atlas are sketchbook's (vendor/font.{c,h}, src/font/Atlas.zig), moved as they were, the second step of the GPU move: font.c and font.h leave src/gui/ byte for byte, and the atlas leaves gui.zig, its faces (the primary, its bytes, the fallbacks), its stage, slots, pen and dirty rows, GlyphKey (Atlas.Key, the same bits: a FontRole and a GlyphDecoration go in as its Role and Decoration, checked at compile time), ruleArms, drawRule, inkBounds, glyphForCodepoint, cachedGlyph, centerGlyphInk and decorateLine; gui.zig holds an Atlas and asks it for what it asked the shim (a face, a fallback, the name, the cell, a substitution, a run shaped), so it calls no ui_font_ function; cachedGlyph stays as the window's: it hands the atlas the body's and the tagline's sizes, GUTTER and dp(1) on every miss (a window reopened on another display draws its rules at that display's dp(1) without a reset, as before) and keeps the frame probe's raster zone; the Atlas module is built from the sketchbook checkout over gui.zig's own `c` as Cells is, font.c compiled from there against pardes's FreeType and HarfBuzz; its tests (the raster, the box rules, the decorations, the dirty rows) are Atlas.zig's and run with unit-test, the tests of pardes's use of it (shaping, taglines, grips, the allocator, the atlas's bytes, whose hashes are unchanged) stay here over the Atlas
Diffstat (limited to 'src/gui/gui.zig')
| -rw-r--r-- | src/gui/gui.zig | 735 |
1 files changed, 179 insertions, 556 deletions
diff --git a/src/gui/gui.zig b/src/gui/gui.zig index d0d46f44..14194122 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1,5 +1,6 @@ const SketchGpu = @import("sketch_gpu"); const Cells = @import("gpu_cells"); // sketchbook's src/gpu/Cells.zig +const Atlas = @import("font_atlas"); // sketchbook's src/font/Atlas.zig const GpuScene = @import("gpu_scene"); const filesystem = @import("../fs.zig"); const std = @import("std"); @@ -87,66 +88,11 @@ const p9_arrow_mask = blk: { break :blk m; }; -const atlas_w: u32 = 2048; -const atlas_h: u32 = 2048; -const Slot = struct { u: u32, v: u32 }; -/// An atlas entry is a glyph of a face (0 the primary font, i the fallback -/// i - 1) at a role's size, drawn `span` cells wide with its own cell `lead` -/// cells in: a ligature is one strip whose cells sample their own slices. -/// Packed, so the atlas map hashes one word instead of walking fields. -const GlyphKey = packed struct(u64) { - face: u8, - glyph: u32, - role: pardes.FontRole, - decoration: GlyphDecoration = .{}, - centered: bool = false, - lead: u4 = 0, - span: u4 = 1, - /// A light box-drawing rule (`ruleArms`), drawn edge to edge rather - /// than from the font; `glyph` is its codepoint. - rule: bool = false, - _: u1 = 0, -}; - -/// The light box-drawing rules drawn by hand, as Ghostty and kitty draw -/// them: a logical pixel thick through the cell's middle, out to its edges, -/// so a markdown table's `|` (Tables.zig) joins the rows above and below it -/// and its delimiter row is one line across, at any line height a font's -/// own glyph would leave gaps in. The arms each one has: left, right, up, down. -fn ruleArms(cp: u32) ?[4]bool { - return switch (cp) { - 0x2500 => .{ true, true, false, false }, // ─ - 0x2502 => .{ false, false, true, true }, // │ - 0x250c => .{ false, true, false, true }, // ┌ - 0x2510 => .{ true, false, false, true }, // ┐ - 0x2514 => .{ false, true, true, false }, // └ - 0x2518 => .{ true, false, true, false }, // ┘ - 0x251c => .{ false, true, true, true }, // ├ - 0x2524 => .{ true, false, true, true }, // ┤ - 0x252c => .{ true, true, false, true }, // ┬ - 0x2534 => .{ true, true, true, false }, // ┴ - 0x253c => .{ true, true, true, true }, // ┼ - else => null, - }; -} - -fn drawRule(out: [*]u8, stride: usize, width: usize, height: usize, arms: [4]bool) void { - if (width == 0 or height == 0) return; - const t: usize = @min(@max(1, @as(usize, @intFromFloat(dp(1)))), @min(width, height)); - const mx = (width - t) / 2; - const my = (height - t) / 2; - for (0..height) |y| @memset(out[y * stride ..][0..width], 0); - if (arms[0] or arms[1]) for (0..t) |k| { - const from: usize = if (arms[0]) 0 else mx; - const to: usize = if (arms[1]) width else mx + t; - @memset(out[(my + k) * stride + from ..][0 .. to - from], 255); - }; - if (arms[2] or arms[3]) { - const from: usize = if (arms[2]) 0 else my; - const to: usize = if (arms[3]) height else my + t; - for (from..to) |y| @memset(out[y * stride + mx ..][0..t], 255); - } -} +const atlas_w = Atlas.atlas_w; +const atlas_h = Atlas.atlas_h; +const Slot = Atlas.Slot; +const GlyphKey = Atlas.Key; +const ruleArms = Atlas.ruleArms; const GlyphDecoration = packed struct(u5) { bold: bool = false, @@ -163,6 +109,19 @@ const GlyphDecoration = packed struct(u5) { } }; +// The atlas's Key holds a GlyphDecoration and a FontRole as its own +// Decoration and Role (@bitCast, @enumFromInt): the same bits, so the same +// slots. +comptime { + std.debug.assert(@bitSizeOf(GlyphDecoration) == @bitSizeOf(Atlas.Decoration)); + for (.{ .{ @FieldType(pardes.CellStyle, "ul"), Atlas.Underline }, .{ pardes.FontRole, Atlas.Role } }) |pair| { + const ours = @typeInfo(pair[0]).@"enum"; + const its = @typeInfo(pair[1]).@"enum"; + std.debug.assert(ours.tag_type == its.tag_type and ours.field_names.len == its.field_names.len); + for (ours.field_names, its.field_names, ours.field_values, its.field_values) |a, b, x, y| std.debug.assert(std.mem.eql(u8, a, b) and x == y); + } +} + const TaglineRaster = struct { px: f32, width: u32, @@ -170,12 +129,12 @@ const TaglineRaster = struct { height: u32, }; -fn taglineRaster(font: *c.UIFont, body_px: f32, body_cell_w: u32, body_cell_h: u32, percent: u8) TaglineRaster { +fn taglineRaster(atlas: *const Atlas, body_px: f32, body_cell_w: u32, body_cell_h: u32, percent: u8) TaglineRaster { const px = body_px * @as(f32, @floatFromInt(percent)) / 100.0; var own_w: c_int = 1; var own_h: c_int = 1; var own_ascent: c_int = 1; - c.ui_font_cell_metrics(font, px, &own_w, &own_h, &own_ascent); + atlas.cellMetrics(px, &own_w, &own_h, &own_ascent); const fixed_w: c_int = @intCast(body_cell_w); const fixed_h: c_int = @intCast(body_cell_h); const band_h = std.math.clamp(own_h, 1, fixed_h); @@ -209,10 +168,9 @@ var sdl_allocator: std.mem.Allocator = undefined; const sdl_heap = c_heap.Heap(&sdl_allocator); const max_fallback_fonts = 1 + fonts.fallback_names.len; -const LoadedFallback = struct { - face: *c.UIFont, - bytes: []u8 = &.{}, -}; +comptime { + std.debug.assert(max_fallback_fonts <= Atlas.max_fallbacks); +} const max_touch_points: usize = 16; const touch_scroll_tick: f32 = 0.02; @@ -225,22 +183,6 @@ const font_px_step: f32 = 2.0; const font_px_min: f32 = 8.0; const font_px_max: f32 = 72.0; -const InkBounds = struct { min_x: usize, min_y: usize, max_x: usize, max_y: usize }; - -fn inkBounds(bitmap: []const u8, stride: usize, w: usize, h: usize) ?InkBounds { - var bounds: ?InkBounds = null; - for (0..h) |y| for (0..w) |x| { - if (bitmap[y * stride + x] == 0) continue; - if (bounds) |*b| { - b.min_x = @min(b.min_x, x); - b.min_y = @min(b.min_y, y); - b.max_x = @max(b.max_x, x); - b.max_y = @max(b.max_y, y); - } else bounds = .{ .min_x = x, .min_y = y, .max_x = x, .max_y = y }; - }; - return bounds; -} - const CellInstance = Cells.CellInstance; const OverlayVertex = Cells.OverlayVertex; const ImageInstance = Cells.ImageInstance; @@ -519,15 +461,13 @@ const Gui = struct { /// renderFrame's decor instances, group by group (buildDecor). decor: std.ArrayListUnmanaged(CellInstance) = .empty, - font: *c.UIFont, - font_bytes: []u8 = &.{}, + /// The faces and the glyphs drawn from them. + atlas: Atlas, font_name: [255]u8 = @splat(0), font_name_len: u8 = 0, /// A replica client's: the session's font request it last followed /// (syncReplicaFont), as a hash of the request. remote_font_request: ?u64 = null, - fallbacks: [max_fallback_fonts]?LoadedFallback = @splat(null), - fallback_count: usize = 0, px: f32, tagline_px: f32, tagline_percent: u8, @@ -538,15 +478,6 @@ const Gui = struct { ascent: i32, tagline_baseline: i32, - atlas_stage: []u8, - glyphs: std.AutoHashMap(GlyphKey, Slot), - pen_x: u32 = 0, - pen_y: u32 = 0, - /// The atlas rows drawn into since the last upload, [top, bottom): the - /// whole atlas at first, since the texture starts undefined. - atlas_dirty_top: u32 = 0, - atlas_dirty_bottom: u32 = atlas_h, - space_slot: Slot = .{ .u = 0, .v = 0 }, words: Words = .{}, touch: Touch = .{}, @@ -666,7 +597,7 @@ fn releaseWindowParts(g: *Gui, gpa: std.mem.Allocator) void { } fn setGuiFontName(g: *Gui, fallback: []const u8) void { - const name = if (c.ui_font_name(g.font)) |name_z| std.mem.span(name_z) else fallback; + const name = if (g.atlas.fontName()) |name_z| std.mem.span(name_z) else fallback; const len = @min(name.len, g.font_name.len); @memcpy(g.font_name[0..len], name[0..len]); g.font_name_len = @intCast(len); @@ -704,14 +635,7 @@ fn syncReplicaFont(g: *Gui, core: *const pardes.Pardes, gpa: std.mem.Allocator) return false; }; const bytes = filesystem.readFile(gpa, face.path) catch return false; - const font = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse { - gpa.free(bytes); - return false; - }; - c.ui_font_free(g.font); - if (g.font_bytes.len != 0) gpa.free(g.font_bytes); - g.font = font; - g.font_bytes = bytes; // FreeType borrows them for the face lifetime + if (!g.atlas.setFont(gpa, bytes)) return false; if (f.requested_size_hundredths != 0) g.px = @as(f32, @floatFromInt(f.requested_size_hundredths)) / 100; setGuiFontName(g, face.name); @@ -720,50 +644,15 @@ fn syncReplicaFont(g: *Gui, core: *const pardes.Pardes, gpa: std.mem.Allocator) } fn loadFallbackFonts(g: *Gui, gpa: std.mem.Allocator) void { - if (c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len))) |face| { - g.fallbacks[0] = .{ .face = face }; - g.fallback_count = 1; - } + _ = g.atlas.addFallback(gpa, font_ttf, false); var arena_state = std.heap.ArenaAllocator.init(gpa); defer arena_state.deinit(); for (fonts.fallbacks(arena_state.allocator())) |candidate| { - if (g.fallback_count == g.fallbacks.len) break; + if (g.atlas.fallback_count == max_fallback_fonts) break; const bytes = filesystem.readFile(gpa, candidate.path) catch continue; - const len = std.math.cast(c_int, bytes.len) orelse { - gpa.free(bytes); - continue; - }; - const face = c.ui_font_new(bytes.ptr, len) orelse { - gpa.free(bytes); - continue; - }; - g.fallbacks[g.fallback_count] = .{ .face = face, .bytes = bytes }; - g.fallback_count += 1; - } -} - -fn deinitFallbackFonts(g: *Gui, gpa: std.mem.Allocator) void { - for (g.fallbacks[0..g.fallback_count]) |loaded| { - const fallback = loaded.?; - c.ui_font_free(fallback.face); - if (fallback.bytes.len != 0) gpa.free(fallback.bytes); - } -} - -const FaceGlyph = struct { face: u8, glyph: u32 }; - -/// The face and glyph that draw `cp`, the face as a GlyphKey face: 0 is the -/// primary font and i the fallback i - 1. A codepoint no face has draws the -/// primary's .notdef. -fn glyphForCodepoint(g: *const Gui, cp: u32) FaceGlyph { - const primary = c.ui_font_glyph(g.font, @intCast(cp)); - if (primary != 0) return .{ .face = 0, .glyph = primary }; - for (g.fallbacks[0..g.fallback_count], 1..) |loaded, face| { - const glyph = c.ui_font_glyph(loaded.?.face, @intCast(cp)); - if (glyph != 0) return .{ .face = @intCast(face), .glyph = glyph }; + _ = g.atlas.addFallback(gpa, bytes, true); } - return .{ .face = 0, .glyph = 0 }; } const CellLayout = struct { w: f32, h: f32, x_off: f32, y_off: f32 }; @@ -1064,14 +953,14 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di c.SDL_GetGPUSwapchainTextureFormat(device, window); font_allocator = gpa; - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)) orelse { - log.err("ui_font_new failed", .{}); - return error.FontInit; + var atlas = Atlas.init(gpa, font_ttf) catch |err| { + log.err("the font atlas: {t}", .{err}); + return err; }; // HarfBuzz's process-wide objects are made once and never freed: made // from the default heap, they stay out of a Debug build's leak report. font_allocator = std.heap.smp_allocator; - c.ui_font_prime(font); + atlas.prime(); font_allocator = gpa; // A harness forcing a density (PARDES_TEST_SCALE) draws the text as a // person on that display would size it, so its chrome is seen at the @@ -1080,10 +969,10 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di var cw: c_int = 10; var chh: c_int = 20; var asc: c_int = 16; - c.ui_font_cell_metrics(font, px, &cw, &chh, &asc); + atlas.cellMetrics(px, &cw, &chh, &asc); const cell_w: u32 = @intCast(@max(cw, 1)); const cell_h: u32 = @intCast(@max(chh, 1)); - const tagline = taglineRaster(font, px, cell_w, cell_h, config.gui_tagline_font_percent); + const tagline = taglineRaster(&atlas, px, cell_w, cell_h, config.gui_tagline_font_percent); if (test_mode) { const cols = envU16(env, "PARDES_TEST_COLS") orelse 80; const rows = envU16(env, "PARDES_TEST_ROWS") orelse 24; @@ -1122,9 +1011,6 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di var ovx_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, .size = overlay_buffer_size, .props = 0 }; const overlay_vxfer = c.SDL_CreateGPUTransferBuffer(device, &ovx_info) orelse return error.GpuCreate; - const atlas_stage = try gpa.alloc(u8, atlas_w * atlas_h); - defer gpa.free(atlas_stage); - @memset(atlas_stage, 0); const overlay_vertices = try gpa.alloc(OverlayVertex, max_overlay_vertices); defer gpa.free(overlay_vertices); @@ -1146,7 +1032,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di .overlay_vbuf = overlay_vbuf, .overlay_vxfer = overlay_vxfer, .overlay_vertices = overlay_vertices, - .font = font, + .atlas = atlas, .px = px, .tagline_px = tagline.px, .tagline_percent = config.gui_tagline_font_percent, @@ -1156,8 +1042,6 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di .cell_h = cell_h, .ascent = asc, .tagline_baseline = tagline.baseline, - .atlas_stage = atlas_stage, - .glyphs = std.AutoHashMap(GlyphKey, Slot).init(gpa), .capture = test_mode, .capture_pad = if (test_mode) envU16(env, "PARDES_TEST_PAD") orelse 0 else 0, .capture_series = test_mode and env.get("PARDES_TEST_SERIES") != null, @@ -1195,8 +1079,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di } setGuiFontName(&g, "Adwaita Mono"); loadFallbackFonts(&g, gpa); - defer deinitFallbackFonts(&g, gpa); - defer g.glyphs.deinit(); + defer g.atlas.deinit(gpa); defer g.words.deinit(gpa); defer { if (g.addon_gpu) |*gpu| gpu.deinit(); @@ -1210,8 +1093,6 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, headless: bool, di g.decor.deinit(gpa); } defer c.SDL_ReleaseGPUGraphicsPipeline(device, image_pipeline); - defer if (g.font_bytes.len != 0) gpa.free(g.font_bytes); // set by Font, if it ran - defer c.ui_font_free(g.font); defer gpa.free(g.scroll_edge); // grown on demand by stepScroll defer g.glide.deinit(gpa); resetGlyphAtlas(&g); @@ -3254,16 +3135,11 @@ fn pollFrame(ctx: ?*anyopaque) void { core.rejectFont(); break :blk; }; - const nf = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse { + if (!g.atlas.setFont(s.gpa, bytes)) { log.err("ui_font_new failed: {s}", .{path}); - s.gpa.free(bytes); core.rejectFont(); break :blk; - }; - c.ui_font_free(g.font); - if (g.font_bytes.len != 0) s.gpa.free(g.font_bytes); - g.font = nf; - g.font_bytes = bytes; // FreeType borrows them for the face lifetime + } if (core.settings.font.requested_size_hundredths != 0) g.px = @as(f32, @floatFromInt(core.settings.font.requested_size_hundredths)) / 100; setGuiFontName(g, core.settings.font.requested_name.get()); @@ -4612,7 +4488,7 @@ fn renderFrame( @memcpy(instances[cell_total + shifted ..][0..decor_len], g.decor.items); c.SDL_UnmapGPUTransferBuffer(g.device, g.vxfer.?); - if (g.atlas_dirty_top < g.atlas_dirty_bottom) uploadAtlas(g, cmd); + if (g.atlas.atlas_dirty_top < g.atlas.atlas_dirty_bottom) uploadAtlas(g, cmd); const copy = c.SDL_BeginGPUCopyPass(cmd); const src = c.SDL_GPUTransferBufferLocation{ .transfer_buffer = g.vxfer.?, .offset = 0 }; @@ -4978,9 +4854,9 @@ fn emitSurfaceCell( if (grip) { // A grip is one glyph centered across the gutter, not text: it is // looked up by its codepoint's glyph, never shaped. - const drawn = glyphForCodepoint(g, cellCodepoint(glyph)); - const cached = cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = GlyphDecoration.fromCell(glyph), .centered = true }); - const slot = cached orelse g.space_slot; + const drawn = g.atlas.glyphForCodepoint(cellCodepoint(glyph)); + const cached = cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = @bitCast(GlyphDecoration.fromCell(glyph)), .centered = true }); + const slot = cached orelse g.atlas.space_slot; const b = button.?; const center = (b[0] + b[2]) / 2 - @as(f32, @floatFromInt(col - offset)) * body_layout.w; const shift: f32 = if (cached != null) @as(f32, @floatFromInt(@as(u32, offset) * g.cell_w)) + @as(f32, @floatFromInt(config.GUTTER * g.cell_w)) / 2 - center else 0; @@ -5015,10 +4891,10 @@ fn emitSurfaceCell( // Over it, only its own glyph; the band round it and the ring // are decor (gripDecor). if (here.pane_grip and !grip) { - instances[next.*].u0 = @as(f32, @floatFromInt(g.space_slot.u)) / atlas_w; + instances[next.*].u0 = @as(f32, @floatFromInt(g.atlas.space_slot.u)) / atlas_w; instances[next.*].u1 = instances[next.*].u0 + @as(f32, @floatFromInt(g.cell_w)) / atlas_w; - instances[next.*].v0 = @as(f32, @floatFromInt(g.space_slot.v)) / atlas_h; - instances[next.*].v1 = @as(f32, @floatFromInt(g.space_slot.v + g.tagline_height)) / atlas_h; + instances[next.*].v0 = @as(f32, @floatFromInt(g.atlas.space_slot.v)) / atlas_h; + instances[next.*].v1 = @as(f32, @floatFromInt(g.atlas.space_slot.v + g.tagline_height)) / atlas_h; } // Its ground is the fill again. instances[next.*].br = base.br; @@ -5117,11 +4993,11 @@ fn refitFont(g: *Gui, core: ?*pardes.Pardes) void { var cw: c_int = 10; var chh: c_int = 20; var asc: c_int = 16; - c.ui_font_cell_metrics(g.font, g.px, &cw, &chh, &asc); + g.atlas.cellMetrics(g.px, &cw, &chh, &asc); g.cell_w = @intCast(@max(cw, 1)); g.cell_h = @intCast(@max(chh, 1)); g.ascent = @intCast(@max(asc, 1)); - const tagline = taglineRaster(g.font, g.px, g.cell_w, g.cell_h, g.tagline_percent); + const tagline = taglineRaster(&g.atlas, g.px, g.cell_w, g.cell_h, g.tagline_percent); g.tagline_px = tagline.px; g.tagline_width = tagline.width; g.tagline_baseline = tagline.baseline; @@ -5139,14 +5015,8 @@ fn refitFont(g: *Gui, core: ?*pardes.Pardes) void { // The first cell of the cleared atlas stays blank: the space slot. fn resetGlyphAtlas(g: *Gui) void { - g.glyphs.clearRetainingCapacity(); + g.atlas.reset(g.cell_w); g.words.clear(); - @memset(g.atlas_stage, 0); - g.space_slot = .{ .u = 0, .v = 0 }; - g.pen_x = g.cell_w; - g.pen_y = 0; - g.atlas_dirty_top = 0; - g.atlas_dirty_bottom = atlas_h; } fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void { @@ -5159,7 +5029,7 @@ fn syncTaglineFont(g: *Gui, core: *pardes.Pardes) void { fn fitTaglineFont(g: *Gui, percent: u8) bool { if (percent == g.tagline_percent) return false; g.tagline_percent = percent; - const tagline = taglineRaster(g.font, g.px, g.cell_w, g.cell_h, percent); + const tagline = taglineRaster(&g.atlas, g.px, g.cell_w, g.cell_h, percent); g.tagline_px = tagline.px; g.tagline_width = tagline.width; g.tagline_baseline = tagline.baseline; @@ -5256,19 +5126,18 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: return words.slots.items[memo.slots + at - memo.start]; var here = wordCell(&line[at]); // An underlined or struck-out space is a glyph of its own: it draws its line. - if (here.cp == ' ' and !here.decoration.drawsBlank()) return g.space_slot; + if (here.cp == ' ' and !here.decoration.drawsBlank()) return g.atlas.space_slot; if (ruleArms(here.cp) != null) - return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = role, .rule = true }) orelse g.space_slot; - const gpa = g.glyphs.allocator; + return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = @enumFromInt(@intFromEnum(role)), .rule = true }) orelse g.atlas.space_slot; + const gpa = g.atlas.glyphs.allocator; const cell_key: Words.CellKey = .{ .cp = @intCast(here.cp), .role = role, .decoration = here.decoration }; - const known = words.cells.getOrPut(gpa, cell_key) catch return g.space_slot; + const known = words.cells.getOrPut(gpa, cell_key) catch return g.atlas.space_slot; if (!known.found_existing) { - const drawn = glyphForCodepoint(g, here.cp); - const font = if (drawn.face == 0) g.font else g.fallbacks[drawn.face - 1].?.face; - known.value_ptr.* = if (role == .body and c.ui_font_substitutes(font, drawn.glyph) != 0) + const drawn = g.atlas.glyphForCodepoint(here.cp); + known.value_ptr.* = if (role == .body and g.atlas.substitutes(drawn.face, drawn.glyph)) Words.shape_slot else - cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = role, .decoration = here.decoration }) orelse g.space_slot; + cachedGlyph(g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = @enumFromInt(@intFromEnum(role)), .decoration = @bitCast(here.decoration) }) orelse g.atlas.space_slot; } const plain = known.value_ptr.*; if (!std.meta.eql(plain, Words.shape_slot)) return plain; @@ -5286,7 +5155,7 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: const text_start = words.text.items.len; var end = start; while (true) { - words.text.append(gpa, here.cp) catch return g.space_slot; + words.text.append(gpa, here.cp) catch return g.atlas.space_slot; end += 1; if (end == line.len) break; const next = wordCell(&line[end]); @@ -5316,27 +5185,26 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: const n = text.len; words.slots.ensureUnusedCapacity(gpa, n) catch { words.text.shrinkRetainingCapacity(text_start); - return g.space_slot; + return g.atlas.space_slot; }; words.shaped.resize(gpa, n) catch { words.text.shrinkRetainingCapacity(text_start); - return g.space_slot; + return g.atlas.space_slot; }; const shaped = words.shaped.items; var run_start: usize = 0; - var face = glyphForCodepoint(g, text[0]).face; + var face = g.atlas.glyphForCodepoint(text[0]).face; while (run_start < n) { var run_end = run_start + 1; var next_face = face; while (run_end < n) : (run_end += 1) { - next_face = glyphForCodepoint(g, text[run_end]).face; + next_face = g.atlas.glyphForCodepoint(text[run_end]).face; if (next_face != face) break; } - const run_font = if (face == 0) g.font else g.fallbacks[face - 1].?.face; - c.ui_font_shape(run_font, g.px, @intCast(g.cell_w), text[run_start..].ptr, @intCast(run_end - run_start), shaped[run_start..].ptr); + g.atlas.shape(face, g.px, g.cell_w, text[run_start..run_end], shaped[run_start..]); for (shaped[run_start..run_end]) |cell| { - const key: GlyphKey = .{ .face = face, .glyph = cell.glyph, .role = .body, .decoration = decoration, .lead = @intCast(cell.lead), .span = @intCast(cell.span) }; - const slot: Slot = if (cachedGlyph(g, key)) |strip| .{ .u = strip.u + g.cell_w * cell.slice, .v = strip.v } else g.space_slot; + const key: GlyphKey = .{ .face = face, .glyph = cell.glyph, .role = .body, .decoration = @bitCast(decoration), .lead = @intCast(cell.lead), .span = @intCast(cell.span) }; + const slot: Slot = if (cachedGlyph(g, key)) |strip| .{ .u = strip.u + g.cell_w * cell.slice, .v = strip.v } else g.atlas.space_slot; words.slots.appendAssumeCapacity(slot); } run_start = run_end; @@ -5366,7 +5234,7 @@ fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gu .overlay_vbuf = undefined, .overlay_vxfer = undefined, .overlay_vertices = &.{}, - .font = undefined, + .atlas = .{ .font = undefined, .atlas_stage = &.{}, .glyphs = undefined }, .px = 0, .tagline_px = 0, .tagline_percent = 0, @@ -5376,123 +5244,37 @@ fn testGui(cell_w: u32, cell_h: u32, tagline_width: u32, tagline_height: u32) Gu .cell_h = cell_h, .ascent = 0, .tagline_baseline = 0, - .atlas_stage = &.{}, - .glyphs = undefined, }; } -/// The atlas slot of `key`, rasterized on first use. A strip is `span` cells -/// wide (a grip glyph GUTTER cells, centered); a cell samples its slice of it. +/// The atlas slot of `key` (Atlas.cachedGlyph), rasterized on first use at +/// the window's sizes, a grip glyph GUTTER cells wide, its rules and +/// decorations a logical pixel thick (dp): a raster is the frame probe's. /// Null when the atlas is full. fn cachedGlyph(g: *Gui, key: GlyphKey) ?Slot { - if (g.glyphs.get(key)) |s| return s; - const slot_w = g.cell_w * @as(u32, if (key.centered) config.GUTTER else key.span); - if (g.pen_x + slot_w > atlas_w) { - g.pen_x = 0; - g.pen_y += g.cell_h; - } - if (g.pen_y + g.cell_h > atlas_h) return null; // atlas full: fall back + if (g.atlas.glyphs.get(key)) |s| return s; const probe_raster = monoNs(); - defer if (frame_probe) |probe| { + const body: Atlas.Size = .{ .px = g.px, .cell_w = g.cell_w, .height = g.cell_h, .baseline = g.ascent }; + const tagline: Atlas.Size = .{ .px = g.tagline_px, .cell_w = g.tagline_width, .height = g.tagline_height, .baseline = g.tagline_baseline }; + const s = g.atlas.cachedGlyph(key, body, tagline, config.GUTTER, @intFromFloat(dp(1))) orelse return null; + if (frame_probe) |probe| { probe.zone(.gui_raster, probe_raster); probe.rastered +|= 1; - }; - const s = Slot{ .u = g.pen_x, .v = g.pen_y }; - const out = g.atlas_stage.ptr + @as(usize, s.v) * atlas_w + s.u; - const face = if (key.face == 0) g.font else g.fallbacks[key.face - 1].?.face; - const px = if (key.role == .tagline) g.tagline_px else g.px; - const baseline = if (key.role == .tagline) g.tagline_baseline else g.ascent; - const cell_w = if (key.role == .tagline) g.tagline_width else g.cell_w; - const raster_w = if (key.centered) slot_w else cell_w * key.span; - const raster_h = if (key.role == .tagline) g.tagline_height else g.cell_h; - const bold = @intFromBool(key.decoration.bold); - if (key.rule) { - drawRule(out, atlas_w, raster_w, raster_h, ruleArms(key.glyph).?); - } else if (key.centered) { - _ = c.ui_font_raster_centered(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h)); - } else { - _ = c.ui_font_raster(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h), @intCast(cell_w * key.lead), @intCast(cell_w), baseline); } - decorateLine(out, atlas_w, raster_w, raster_h, baseline, key.decoration); - if (key.centered) centerGlyphInk(out, raster_w, raster_h); - g.atlas_dirty_top = @min(g.atlas_dirty_top, s.v); - g.atlas_dirty_bottom = @max(g.atlas_dirty_bottom, s.v + raster_h); - g.glyphs.put(key, s) catch return null; - g.pen_x += slot_w; return s; } -// Run once when a grip glyph enters the atlas, after decorations. Copy only -// visible ink so bearings, empty bitmap margins and bold all share one center. -fn centerGlyphInk(out: [*]u8, width: usize, height: usize) void { - const b = inkBounds(out[0 .. (height - 1) * atlas_w + width], atlas_w, width, height) orelse return; - const w = b.max_x - b.min_x + 1; - const h = b.max_y - b.min_y + 1; - const left = (width - w) / 2; - const top = (height - h) / 2; - var scratch: [atlas_w]u8 = undefined; - for (0..h) |step| { - const row = if (top > b.min_y) h - 1 - step else step; - const source = (b.min_y + row) * atlas_w + b.min_x; - const target = (top + row) * atlas_w; - @memcpy(scratch[0..w], out[source..][0..w]); - @memset(out[target..][0..width], 0); - @memcpy(out[target + left ..][0..w], scratch[0..w]); - } - for (0..height) |row| { - if (row < top or row >= top + h) @memset(out[row * atlas_w ..][0..width], 0); - } -} - -// Underline and strikethrough stay inside the existing atlas slot, so text -// advance, caret and selection geometry are identical to the regular glyph. -// The cached mask keeps this work out of steady-state rendering and also -// decorates terminal spaces. Bold is not drawn here: the rasterizer emboldens -// the outline. -fn decorateLine(out: [*]u8, stride: usize, width: usize, height: usize, baseline: i32, decoration: GlyphDecoration) void { - if (width == 0 or height == 0) return; - // A line is a logical pixel thick, its dots and waves as long: the same - // weight at any density (dp). - const t: usize = @intFromFloat(dp(1)); - if (decoration.underline != .off) { - const base: usize = @intCast(@max(0, baseline)); - const row = @min(base + 1, height -| t); - for (0..width) |x| { - const top = switch (decoration.underline) { - .off => unreachable, - .single => row, - .double => { - const upper = @min(base + 1, height -| 3 * t); - for (0..t) |k| { - out[@min(upper + k, height - 1) * stride + x] = 255; - out[@min(upper + 2 * t + k, height - 1) * stride + x] = 255; - } - continue; - }, - .curly => row -| @as(usize, if (x % (4 * t) < 2 * t) t else 0), - .dotted => if (x % (3 * t) < t) row else continue, - .dashed => if (x % (6 * t) < 4 * t) row else continue, - }; - for (0..t) |k| out[@min(top + k, height - 1) * stride + x] = 255; - } - } - if (decoration.strikethrough) { - const row = @min(height -| t, @as(usize, @intCast(@max(0, baseline))) * 2 / 3); - for (0..t) |k| @memset(out[@min(row + k, height - 1) * stride ..][0..width], 255); - } -} - /// Uploads only the atlas rows drawn into since the last upload. Glyphs fill /// the atlas pen-style, a band of rows at a time, so new glyphs are a band a /// cell or two tall, not the whole 4 MB texture. The band sits at the same /// offset in the transfer buffer as in the stage, and the texture keeps the /// rows outside it. fn uploadAtlas(g: *Gui, cmd: *c.SDL_GPUCommandBuffer) void { - const top = g.atlas_dirty_top; - const rows = g.atlas_dirty_bottom - top; + const top = g.atlas.atlas_dirty_top; + const rows = g.atlas.atlas_dirty_bottom - top; const ptr = c.SDL_MapGPUTransferBuffer(g.device, g.atlas_xfer, false) orelse return; const dst: [*]u8 = @ptrCast(ptr); - @memcpy(dst[top * atlas_w ..][0 .. rows * atlas_w], g.atlas_stage[top * atlas_w ..][0 .. rows * atlas_w]); + @memcpy(dst[top * atlas_w ..][0 .. rows * atlas_w], g.atlas.atlas_stage[top * atlas_w ..][0 .. rows * atlas_w]); c.SDL_UnmapGPUTransferBuffer(g.device, g.atlas_xfer); const copy = c.SDL_BeginGPUCopyPass(cmd); @@ -5500,8 +5282,8 @@ fn uploadAtlas(g: *Gui, cmd: *c.SDL_GPUCommandBuffer) void { const dstregion = c.SDL_GPUTextureRegion{ .texture = g.atlas_tex, .mip_level = 0, .layer = 0, .x = 0, .y = top, .z = 0, .w = atlas_w, .h = rows, .d = 1 }; c.SDL_UploadToGPUTexture(copy, &src, &dstregion, false); c.SDL_EndGPUCopyPass(copy); - g.atlas_dirty_top = atlas_h; - g.atlas_dirty_bottom = 0; + g.atlas.atlas_dirty_top = atlas_h; + g.atlas.atlas_dirty_bottom = 0; } fn ensureCaptureTexture(g: *Gui, width: u32, height: u32) !void { @@ -6690,25 +6472,24 @@ fn expectCoverIsScan(cover: []const Cover, cols: u16, rows: u16, body_layers: [] }; } -/// A Gui that can shape and rasterize `font` at `px`, and nothing else. From -/// here on the fonts allocate from std.testing.allocator (the caller puts -/// font_allocator back), so the test counts what they leak. -fn textTestGui(font: *c.UIFont, px: f32) !Gui { - c.ui_font_prime(font); +/// A Gui that can shape and rasterize the face in `bytes` at `px`, and +/// nothing else. From here on the fonts allocate from std.testing.allocator +/// (the caller puts font_allocator back), so the test counts what they leak. +fn textTestGui(bytes: []const u8, px: f32) !Gui { + var atlas = try Atlas.init(std.testing.allocator, bytes); + atlas.prime(); font_allocator = std.testing.allocator; var cw: c_int = 0; var ch: c_int = 0; var ascent: c_int = 0; - c.ui_font_cell_metrics(font, px, &cw, &ch, &ascent); - const tag = taglineRaster(font, px, @intCast(cw), @intCast(ch), 82); + atlas.cellMetrics(px, &cw, &ch, &ascent); + const tag = taglineRaster(&atlas, px, @intCast(cw), @intCast(ch), 82); var g = testGui(@intCast(cw), @intCast(ch), tag.width, tag.height); - g.font = font; + g.atlas = atlas; g.px = px; g.ascent = ascent; g.tagline_px = tag.px; g.tagline_baseline = tag.baseline; - g.atlas_stage = try std.testing.allocator.alloc(u8, atlas_w * atlas_h); - g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator); resetGlyphAtlas(&g); return g; } @@ -6720,7 +6501,7 @@ fn textTestLine(comptime text: []const u8) [text.len]pardes.Cell { } fn glyphKeyAt(g: *Gui, slot: Slot) !GlyphKey { - var it = g.glyphs.iterator(); + var it = g.atlas.glyphs.iterator(); while (it.next()) |entry| if (std.meta.eql(entry.value_ptr.*, slot)) return entry.key_ptr.*; return error.NoGlyph; } @@ -6782,37 +6563,39 @@ fn cursorColor(chrome: *const pardes.Chrome, cell: *const pardes.Cell, role: par test "FreeType and HarfBuzz allocate from the gui allocator and give it all back" { // HarfBuzz's process-wide objects come from the default heap, as in runNative. - const primer = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - c.ui_font_prime(primer); - c.ui_font_free(primer); + var primer = try Atlas.init(std.testing.allocator, font_ttf); + primer.prime(); + primer.deinit(std.testing.allocator); font_allocator = std.testing.allocator; defer font_allocator = std.heap.smp_allocator; - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - var mask: [64 * 64]u8 = undefined; - try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, 27, c.ui_font_glyph(font, 'g'), 1, &mask, 64, 32, 48, 0, 32, 30)); - try std.testing.expectEqual(@as(c_int, 0), c.ui_font_substitutes(font, c.ui_font_glyph(font, '-'))); + var atlas = try Atlas.init(std.testing.allocator, font_ttf); + defer atlas.deinit(std.testing.allocator); + atlas.reset(32); + const size: Atlas.Size = .{ .px = 27, .cell_w = 32, .height = 48, .baseline = 30 }; + const g_slot = atlas.cachedGlyph(.{ .face = 0, .glyph = atlas.glyphForCodepoint('g').glyph, .role = .body, .decoration = .{ .bold = true } }, size, size, config.GUTTER, 1).?; + try std.testing.expect(Atlas.inkBounds(atlas.atlas_stage[@as(usize, g_slot.v) * atlas_w + g_slot.u ..], atlas_w, 32, 48) != null); + try std.testing.expect(!atlas.substitutes(0, atlas.glyphForCodepoint('-').glyph)); // A font with ligatures runs the whole HarfBuzz pass. const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); defer std.testing.allocator.free(bytes); - const maple = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit; - defer c.ui_font_free(maple); + var maple = try Atlas.init(std.testing.allocator, bytes); + defer maple.deinit(std.testing.allocator); var cell_w: c_int = 0; var cell_h: c_int = 0; var ascent: c_int = 0; - c.ui_font_cell_metrics(maple, 27, &cell_w, &cell_h, &ascent); + maple.cellMetrics(27, &cell_w, &cell_h, &ascent); const text = [_]u32{ 'a', '-', '>', 'b', '=', '=' }; var shaped: [text.len]c.UIShapedCell = undefined; - c.ui_font_shape(maple, 27, cell_w, &text, text.len, &shaped); + maple.shape(0, 27, @intCast(cell_w), &text, &shaped); try std.testing.expectEqual(@as(u8, 2), shaped[1].span); try std.testing.expectEqual(@as(u8, 2), shaped[4].span); } test "every font size step moves the cell, and the ends are reachable exactly" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); + var atlas = try Atlas.init(std.testing.allocator, font_ttf); + defer atlas.deinit(std.testing.allocator); var px = font_px_min + font_px_step; while (px <= font_px_max) : (px += 1.0) { var cw: c_int = 0; @@ -6820,95 +6603,33 @@ test "every font size step moves the cell, and the ends are reachable exactly" { var asc: c_int = 0; var pw: c_int = 0; var ph: c_int = 0; - c.ui_font_cell_metrics(font, px, &cw, &ch, &asc); - c.ui_font_cell_metrics(font, px - font_px_step, &pw, &ph, &asc); + atlas.cellMetrics(px, &cw, &ch, &asc); + atlas.cellMetrics(px - font_px_step, &pw, &ph, &asc); try std.testing.expect(cw > pw and ch > ph); } try std.testing.expectEqual(font_px_max, std.math.clamp(font_px_max + font_px_step, font_px_min, font_px_max)); try std.testing.expectEqual(font_px_min, std.math.clamp(font_px_min - font_px_step, font_px_min, font_px_max)); } -test "FreeType atlas raster is grayscale, bounded, and clears blank cells" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - const h = c.ui_font_glyph(font, 'H'); - try std.testing.expect(h != 0); - try std.testing.expectEqual(@as(u32, 0), c.ui_font_glyph(font, 0x10ffff)); - - const size: f32 = 13.0; - var cell_w: c_int = 0; - var cell_h: c_int = 0; - var ascent: c_int = 0; - c.ui_font_cell_metrics(font, size, &cell_w, &cell_h, &ascent); - try std.testing.expect(cell_w > 0 and cell_w <= 128); - try std.testing.expect(cell_h > 0 and cell_h <= 128); - - const stride: c_int = 128; - var bitmap: [128 * 128]u8 = @splat(0xaa); - try std.testing.expectEqual( - @as(c_int, 1), - c.ui_font_raster(font, size, h, 0, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), - ); - - var ink: usize = 0; - var soft: usize = 0; - var regular_coverage: usize = 0; - for (0..@intCast(cell_h)) |y| { - for (0..@intCast(cell_w)) |x| { - const coverage = bitmap[y * @as(usize, @intCast(stride)) + x]; - if (coverage > 0) ink += 1; - if (coverage > 0 and coverage < 255) soft += 1; - regular_coverage += coverage; - } - } - try std.testing.expect(ink > 0); - try std.testing.expect(soft > 0); - // Synthetic bold thickens the outline inside the same cell. - try std.testing.expectEqual( - @as(c_int, 1), - c.ui_font_raster(font, size, h, 1, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), - ); - var bold_coverage: usize = 0; - for (0..@intCast(cell_h)) |y| { - for (0..@intCast(cell_w)) |x| bold_coverage += bitmap[y * @as(usize, @intCast(stride)) + x]; - for (bitmap[y * @as(usize, @intCast(stride)) + @as(usize, @intCast(cell_w)) ..][0..@intCast(stride - cell_w)]) |guard| - try std.testing.expectEqual(@as(u8, 0xaa), guard); - } - try std.testing.expect(bold_coverage > regular_coverage); - - try std.testing.expectEqual( - @as(c_int, 0), - c.ui_font_raster(font, size, c.ui_font_glyph(font, ' '), 0, &bitmap, stride, cell_w, cell_h, 0, cell_w, ascent), - ); - for (0..@intCast(cell_h)) |y| - for (0..@intCast(cell_w)) |x| - try std.testing.expectEqual( - @as(u8, 0), - bitmap[y * @as(usize, @intCast(stride)) + x], - ); -} - test "tagline glyph shrinks into its own cell and stays vertically centered" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - const body_px: f32 = 27.0; - var cell_w: c_int = 1; - var cell_h: c_int = 1; - var body_ascent: c_int = 1; - c.ui_font_cell_metrics(font, body_px, &cell_w, &cell_h, &body_ascent); - const tag = taglineRaster(font, body_px, @intCast(cell_w), @intCast(cell_h), config.gui_tagline_font_percent); + var g = try textTestGui(font_ttf, body_px); + defer font_allocator = std.heap.smp_allocator; + defer g.atlas.deinit(std.testing.allocator); + defer g.words.deinit(std.testing.allocator); + _ = fitTaglineFont(&g, config.gui_tagline_font_percent); + const cell_w: c_int = @intCast(g.cell_w); + const cell_h: c_int = @intCast(g.cell_h); + const tag = taglineRaster(&g.atlas, body_px, @intCast(cell_w), @intCast(cell_h), config.gui_tagline_font_percent); try std.testing.expect(tag.px < body_px); try std.testing.expect(tag.width < @as(u32, @intCast(cell_w))); - const stride: c_int = 128; - var body: [128 * 128]u8 = @splat(0); - var tagline: [128 * 128]u8 = @splat(0); - const h = c.ui_font_glyph(font, 'H'); - try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, body_px, h, 0, &body, stride, cell_w, cell_h, 0, cell_w, body_ascent)); - try std.testing.expectEqual(@as(c_int, 1), c.ui_font_raster(font, tag.px, h, 0, &tagline, stride, @intCast(tag.width), @intCast(tag.height), 0, @intCast(tag.width), tag.baseline)); - const b = inkBounds(&body, @intCast(stride), @intCast(cell_w), @intCast(cell_h)).?; - const t = inkBounds(&tagline, @intCast(stride), @intCast(tag.width), @intCast(tag.height)).?; + // Each at its role's size, as a frame draws it. + const h = g.atlas.glyphForCodepoint('H').glyph; + const body = cachedGlyph(&g, .{ .face = 0, .glyph = h, .role = .body }).?; + const tagline = cachedGlyph(&g, .{ .face = 0, .glyph = h, .role = .tagline }).?; + const b = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, body.v) * atlas_w + body.u ..], atlas_w, @intCast(cell_w), @intCast(cell_h)).?; + const t = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, tagline.v) * atlas_w + tagline.u ..], atlas_w, @intCast(tag.width), @intCast(tag.height)).?; try std.testing.expect(t.max_x - t.min_x < b.max_x - b.min_x); try std.testing.expect(t.max_y - t.min_y < b.max_y - b.min_y); const body_center_x: isize = @intCast(b.min_x + b.max_x); @@ -6924,15 +6645,15 @@ test "tagline glyph shrinks into its own cell and stays vertically centered" { } test "tagline percentage changes measured band height without body metrics" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); + var atlas = try Atlas.init(std.testing.allocator, font_ttf); + defer atlas.deinit(std.testing.allocator); var cell_w: c_int = 1; var cell_h: c_int = 1; var ascent: c_int = 1; - c.ui_font_cell_metrics(font, 27.0, &cell_w, &cell_h, &ascent); - const small = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 40); - const configured = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 82); - const full = taglineRaster(font, 27.0, @intCast(cell_w), @intCast(cell_h), 100); + atlas.cellMetrics(27.0, &cell_w, &cell_h, &ascent); + const small = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 40); + const configured = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 82); + const full = taglineRaster(&atlas, 27.0, @intCast(cell_w), @intCast(cell_h), 100); try std.testing.expect(small.width < configured.width); try std.testing.expect(configured.width <= full.width); try std.testing.expectEqual(@as(u32, @intCast(cell_w)), full.width); @@ -6952,9 +6673,9 @@ test "installed Nerd Symbols fallback covers Yazi directory icons" { const bytes = try filesystem.readFile(std.testing.allocator, candidate.path); defer std.testing.allocator.free(bytes); - const face = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit; - defer c.ui_font_free(face); - try std.testing.expect(c.ui_font_glyph(face, 0xe5ff) != 0); + var atlas = try Atlas.init(std.testing.allocator, bytes); + defer atlas.deinit(std.testing.allocator); + try std.testing.expect(atlas.glyphForCodepoint(0xe5ff).glyph != 0); } @@ -7933,7 +7654,7 @@ test "concealed terminal text emits no ink on its ground" { var cell: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; cell.text[0] = 'X'; const resolved = resolveCell(&g, (&cell)[0..1], 0, null, .body, false, bg_default); - try std.testing.expectEqualDeep(g.space_slot, resolved.slot); + try std.testing.expectEqualDeep(g.atlas.space_slot, resolved.slot); try std.testing.expectEqual(bg_default, resolved.bg); } @@ -8175,12 +7896,9 @@ test "insert cursor overlays without replacing the character beneath it" { test "a ligature draws across its cells, one slice each, and comes apart under the cursor" { const bytes = try filesystem.readFile(std.testing.allocator, "assets/MapleMono-NF-Regular.ttf"); defer std.testing.allocator.free(bytes); - const font = c.ui_font_new(bytes.ptr, @intCast(bytes.len)) orelse return error.FontInit; - defer c.ui_font_free(font); - var g = try textTestGui(font, 27); + var g = try textTestGui(bytes, 27); defer font_allocator = std.heap.smp_allocator; - defer std.testing.allocator.free(g.atlas_stage); - defer g.glyphs.deinit(); + defer g.atlas.deinit(std.testing.allocator); defer g.words.deinit(std.testing.allocator); const line = textTestLine("a->b"); @@ -8190,7 +7908,7 @@ test "a ligature draws across its cells, one slice each, and comes apart under t try std.testing.expectEqual(slots[1].v, slots[2].v); try std.testing.expectEqual(slots[1].u + g.cell_w, slots[2].u); var strips: usize = 0; - var it = g.glyphs.iterator(); + var it = g.atlas.glyphs.iterator(); while (it.next()) |entry| if (entry.key_ptr.span == 2) { strips += 1; try std.testing.expectEqual(@as(u4, 1), entry.key_ptr.lead); @@ -8198,7 +7916,7 @@ test "a ligature draws across its cells, one slice each, and comes apart under t }; try std.testing.expectEqual(@as(usize, 1), strips); // The arrow runs through the seam: both halves carry ink at it. - const seam = g.atlas_stage[@as(usize, slots[2].v) * atlas_w ..]; + const seam = g.atlas.atlas_stage[@as(usize, slots[2].v) * atlas_w ..]; var left_ink: usize = 0; var right_ink: usize = 0; for (0..g.cell_h) |y| { @@ -8207,8 +7925,8 @@ test "a ligature draws across its cells, one slice each, and comes apart under t } try std.testing.expect(left_ink > 0 and right_ink > 0); // `a` and `b` are their plain glyphs. - try std.testing.expectEqual(g.glyphs.get(.{ .face = 0, .glyph = c.ui_font_glyph(font, 'a'), .role = .body }).?, slots[0]); - try std.testing.expectEqual(g.glyphs.get(.{ .face = 0, .glyph = c.ui_font_glyph(font, 'b'), .role = .body }).?, slots[3]); + try std.testing.expectEqual(g.atlas.glyphs.get(.{ .face = 0, .glyph = g.atlas.glyphForCodepoint('a').glyph, .role = .body }).?, slots[0]); + try std.testing.expectEqual(g.atlas.glyphs.get(.{ .face = 0, .glyph = g.atlas.glyphForCodepoint('b').glyph, .role = .body }).?, slots[3]); // A second line with the same word reuses the shaped slots. const again = textTestLine("a->b"); @@ -8217,83 +7935,78 @@ test "a ligature draws across its cells, one slice each, and comes apart under t try std.testing.expectEqual(text_len, g.words.text.items.len); // The cursor on either half shows plain `-` and `>`. - const plain_minus = cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '-'), .role = .body }).?; - const plain_greater = cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '>'), .role = .body }).?; + const plain_minus = cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('-').glyph, .role = .body }).?; + const plain_greater = cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('>').glyph, .role = .body }).?; for ([_]usize{ 1, 2 }) |cursor| { try std.testing.expectEqual(plain_minus, cellSlot(&g, &line, 1, cursor, .body)); try std.testing.expectEqual(plain_greater, cellSlot(&g, &line, 2, cursor, .body)); } // A tagline is never shaped. - try std.testing.expectEqual(c.ui_font_glyph(font, '-'), (try glyphKeyAt(&g, cellSlot(&g, &line, 1, null, .tagline))).glyph); + try std.testing.expectEqual(g.atlas.glyphForCodepoint('-').glyph, (try glyphKeyAt(&g, cellSlot(&g, &line, 1, null, .tagline))).glyph); } test "a font without ligatures draws every cell as its own glyph, exactly as before shaping" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - var g = try textTestGui(font, 18); + var g = try textTestGui(font_ttf, 18); defer font_allocator = std.heap.smp_allocator; - defer std.testing.allocator.free(g.atlas_stage); - defer g.glyphs.deinit(); + defer g.atlas.deinit(std.testing.allocator); defer g.words.deinit(std.testing.allocator); + // Each glyph as it is drawn unshaped, in an atlas of its own. + var plain = try textTestGui(font_ttf, 18); + defer plain.atlas.deinit(std.testing.allocator); + defer plain.words.deinit(std.testing.allocator); const text = "a->b != c => d <= e |> www == :: 0x1F"; var line = textTestLine(text); line[3].style.bold = true; // a style change inside a word - var expected: [64 * 64]u8 = undefined; for (line, 0..) |cell, i| { if (text[i] == ' ') continue; const slot = cellSlot(&g, &line, i, null, .body); const key = try glyphKeyAt(&g, slot); - try std.testing.expectEqual(c.ui_font_glyph(font, text[i]), key.glyph); + try std.testing.expectEqual(g.atlas.glyphForCodepoint(text[i]).glyph, key.glyph); try std.testing.expectEqual(@as(u4, 1), key.span); - _ = c.ui_font_raster(font, 18, key.glyph, @intFromBool(cell.style.bold), &expected, 64, @intCast(g.cell_w), @intCast(g.cell_h), 0, @intCast(g.cell_w), g.ascent); + const expected = cachedGlyph(&plain, .{ .face = 0, .glyph = key.glyph, .role = .body, .decoration = .{ .bold = cell.style.bold } }).?; for (0..g.cell_h) |y| - try std.testing.expectEqualSlices(u8, expected[y * 64 ..][0..g.cell_w], g.atlas_stage[(slot.v + y) * atlas_w + slot.u ..][0..g.cell_w]); + try std.testing.expectEqualSlices(u8, plain.atlas.atlas_stage[(expected.v + y) * atlas_w + expected.u ..][0..g.cell_w], g.atlas.atlas_stage[(slot.v + y) * atlas_w + slot.u ..][0..g.cell_w]); } } test "pane indicator cached ink centers bearings styles and sizes" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); var g = testGui(10, 20, 6, 12); - g.font = font; - g.atlas_stage = try std.testing.allocator.alloc(u8, atlas_w * atlas_h); - defer std.testing.allocator.free(g.atlas_stage); - g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator); - defer g.glyphs.deinit(); + g.atlas = try Atlas.init(std.testing.allocator, font_ttf); + defer g.atlas.deinit(std.testing.allocator); for ([_]f32{ 13, 27, 40 }) |px| { g.px = px; var cw: c_int = 0; var ch: c_int = 0; - c.ui_font_cell_metrics(font, px, &cw, &ch, &g.ascent); + g.atlas.cellMetrics(px, &cw, &ch, &g.ascent); g.cell_w = @intCast(cw); g.cell_h = @intCast(ch); for ([_]u8{ 40, 82, 100 }) |percent| { - const tag = taglineRaster(font, px, g.cell_w, g.cell_h, percent); + const tag = taglineRaster(&g.atlas, px, g.cell_w, g.cell_h, percent); g.tagline_width = tag.width; g.tagline_height = tag.height; g.tagline_px = tag.px; g.tagline_baseline = tag.baseline; resetGlyphAtlas(&g); - try std.testing.expectEqual(@as(usize, 0), g.glyphs.count()); + try std.testing.expectEqual(@as(usize, 0), g.atlas.glyphs.count()); for ([_]u32{ '^', '$', 'j' }) |cp| for ([_]bool{ false, true }) |bold| { - const key: GlyphKey = .{ .face = 0, .glyph = c.ui_font_glyph(font, @intCast(cp)), .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }; + const key: GlyphKey = .{ .face = 0, .glyph = g.atlas.glyphForCodepoint(cp).glyph, .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }; const slot = cachedGlyph(&g, key).?; - const bounds = inkBounds(g.atlas_stage[@as(usize, slot.v) * atlas_w + slot.u ..], atlas_w, g.cell_w * config.GUTTER, tag.height).?; + const bounds = Atlas.inkBounds(g.atlas.atlas_stage[@as(usize, slot.v) * atlas_w + slot.u ..], atlas_w, g.cell_w * config.GUTTER, tag.height).?; const center_x: isize = @intCast(bounds.min_x + bounds.max_x); const center_y: isize = @intCast(bounds.min_y + bounds.max_y); try std.testing.expect(@abs(center_x - @as(isize, @intCast(g.cell_w * config.GUTTER - 1))) <= 1); try std.testing.expect(@abs(center_y - @as(isize, @intCast(tag.height - 1))) <= 1); - const count = g.glyphs.count(); - const pen = g.pen_x; + const count = g.atlas.glyphs.count(); + const pen = g.atlas.pen_x; try std.testing.expectEqualDeep(slot, cachedGlyph(&g, key).?); - try std.testing.expectEqual(count, g.glyphs.count()); - try std.testing.expectEqual(pen, g.pen_x); + try std.testing.expectEqual(count, g.atlas.glyphs.count()); + try std.testing.expectEqual(pen, g.atlas.pen_x); }; } } resetGlyphAtlas(&g); - g.pen_y = atlas_h; - try std.testing.expectEqual(@as(?Slot, null), cachedGlyph(&g, .{ .face = 0, .glyph = c.ui_font_glyph(font, '^'), .role = .tagline, .centered = true })); + g.atlas.pen_y = atlas_h; + try std.testing.expectEqual(@as(?Slot, null), cachedGlyph(&g, .{ .face = 0, .glyph = g.atlas.glyphForCodepoint('^').glyph, .role = .tagline, .centered = true })); } test "pane indicator halves are safe on an exhausted atlas" { @@ -8310,15 +8023,12 @@ test "pane indicator halves are safe on an exhausted atlas" { coverFrame(&cover, 6, 2, &.{}, &.{}, &grip); const chrome: pardes.Chrome = .{}; - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); var g = testGui(10, 20, 8, 16); - g.font = font; + g.atlas = try Atlas.init(std.testing.allocator, font_ttf); + defer g.atlas.deinit(std.testing.allocator); g.px = 20; g.tagline_px = 16; - g.pen_y = atlas_h; - g.glyphs = std.AutoHashMap(GlyphKey, Slot).init(std.testing.allocator); - defer g.glyphs.deinit(); + g.atlas.pen_y = atlas_h; defer g.words.deinit(std.testing.allocator); var instances: [4]CellInstance = undefined; var next: u32 = 0; @@ -8329,92 +8039,11 @@ test "pane indicator halves are safe on an exhausted atlas" { try std.testing.expectEqual(@as(u32, 4), next); } -test "a box-drawing rule reaches its cell's edges, and only its arms do" { - const stride = 12; - const width = 9; - const height = 15; - var mask: [stride * height]u8 = @splat(0xa5); - drawRule(&mask, stride, width, height, ruleArms(0x253c).?); - // ┼: ink on all four edges, none in the corners, nothing past the slot. - try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]); - try std.testing.expectEqual(@as(u8, 255), mask[(height - 1) * stride + width / 2]); - try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride]); - try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride + width - 1]); - try std.testing.expectEqual(@as(u8, 0), mask[0]); - for (0..height) |y| for (mask[y * stride + width ..][0 .. stride - width]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard); - drawRule(&mask, stride, width, height, ruleArms(0x2502).?); - try std.testing.expectEqual(@as(u8, 0), mask[(height / 2) * stride]); - try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]); - try std.testing.expect(ruleArms('|') == null); -} - -test "glyph decorations render spaces and stay inside their atlas slot" { - const stride = 9; - const width = 5; - const height = 7; - for ([_]GlyphDecoration{ - .{ .underline = .single }, - .{ .underline = .double }, - .{ .underline = .curly }, - .{ .underline = .dotted }, - .{ .underline = .dashed }, - .{ .strikethrough = true }, - }) |decoration| { - var mask: [stride * (height + 1)]u8 = @splat(0xa5); - for (0..height) |y| @memset(mask[y * stride ..][0..width], 0); - decorateLine(&mask, stride, width, height, 5, decoration); - try std.testing.expect(inkBounds(&mask, stride, width, height) != null); - for (0..height) |y| for (mask[y * stride + width ..][0 .. stride - width]) |guard| - try std.testing.expectEqual(@as(u8, 0xa5), guard); - for (mask[stride * height ..]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard); - } +test "a concealed cell's underline draws nothing of its own" { const hidden: pardes.Cell = .{ .default = false, .style = .{ .invisible = true, .ul = .single } }; try std.testing.expect(!GlyphDecoration.fromCell(&hidden).drawsBlank()); } -test "the atlas's dirty rows hold every row a new glyph draws into, and a reset dirties them all" { - const font = c.ui_font_new(font_ttf.ptr, @intCast(font_ttf.len)).?; - defer c.ui_font_free(font); - var g = try textTestGui(font, 18); - defer font_allocator = std.heap.smp_allocator; - defer std.testing.allocator.free(g.atlas_stage); - defer g.glyphs.deinit(); - defer g.words.deinit(std.testing.allocator); - // The texture as uploadAtlas leaves it, which starts undefined. - const texture = try std.testing.allocator.alloc(u8, atlas_w * atlas_h); - defer std.testing.allocator.free(texture); - @memset(texture, 0xa5); - var glyph: u32 = 0; - for (0..40) |frame| { - if (frame == 30) resetGlyphAtlas(&g); // a font change - // Plain glyphs, strips, taglines, grip glyphs and decorations. - for (0..25) |_| { - glyph += 1; - const span: u4 = @intCast(1 + glyph % 3); - _ = cachedGlyph(&g, .{ - .face = 0, - .glyph = glyph, - .role = if (glyph % 4 == 0) .tagline else .body, - .decoration = .{ .bold = glyph % 2 == 0, .underline = if (glyph % 5 == 0) .curly else .off, .strikethrough = glyph % 11 == 0 }, - .centered = glyph % 13 == 0, - .lead = @intCast(glyph % span), - .span = span, - }) orelse return error.AtlasFull; - } - for (0..atlas_h) |row| { - const stage = g.atlas_stage[row * atlas_w ..][0..atlas_w]; - const uploaded = texture[row * atlas_w ..][0..atlas_w]; - if (row >= g.atlas_dirty_top and row < g.atlas_dirty_bottom) - @memcpy(uploaded, stage) - else - try std.testing.expect(std.mem.eql(u8, stage, uploaded)); - } - g.atlas_dirty_top = atlas_h; - g.atlas_dirty_bottom = 0; - } - try std.testing.expect(g.pen_y >= 2 * g.cell_h); -} - test "overlapping background layers keep one uniform opacity" { const blend = Cells.backgroundLayerBlend(); try std.testing.expectEqual(@as(c.SDL_GPUBlendFactor, c.SDL_GPU_BLENDFACTOR_CONSTANT_COLOR), blend.src_alpha_blendfactor); @@ -9070,19 +8699,13 @@ test "the atlas's bytes: a fixed key list at 27 px and at 54 px (2x) rasterizes var slots_hash = std.hash.Wyhash.init(0); // 0: Adwaita Mono, Maple its fallback; 1: Maple, whose ligatures shape. for ([_][]const u8{ font_ttf, maple }) |primary| { - const font = c.ui_font_new(primary.ptr, @intCast(primary.len)) orelse return error.FontInit; - defer c.ui_font_free(font); - const fallback = c.ui_font_new(maple.ptr, @intCast(maple.len)) orelse return error.FontInit; - defer c.ui_font_free(fallback); - var g = try textTestGui(font, px); + var g = try textTestGui(primary, px); defer font_allocator = std.heap.smp_allocator; - defer std.testing.allocator.free(g.atlas_stage); - defer g.glyphs.deinit(); + defer g.atlas.deinit(std.testing.allocator); defer g.words.deinit(std.testing.allocator); - g.fallbacks[0] = .{ .face = fallback }; - g.fallback_count = 1; + try std.testing.expect(g.atlas.addFallback(std.testing.allocator, maple, false)); try std.testing.expect(fitTaglineFont(&g, 80)); - const decorations = [_]GlyphDecoration{ + const decorations = [_]Atlas.Decoration{ .{}, .{ .bold = true }, .{ .underline = .single }, @@ -9093,34 +8716,34 @@ test "the atlas's bytes: a fixed key list at 27 px and at 54 px (2x) rasterizes .{ .strikethrough = true }, }; for (0x21..0x7f) |cp| { - const drawn = glyphForCodepoint(&g, @intCast(cp)); + const drawn = g.atlas.glyphForCodepoint(@intCast(cp)); for (decorations) |decoration| _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .body, .decoration = decoration }) orelse return error.AtlasFull; for (decorations[0..2]) |decoration| _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = decoration }) orelse return error.AtlasFull; } - const space = glyphForCodepoint(&g, ' '); + const space = g.atlas.glyphForCodepoint(' '); _ = cachedGlyph(&g, .{ .face = space.face, .glyph = space.glyph, .role = .body, .decoration = .{ .underline = .single } }) orelse return error.AtlasFull; - for ([_]u32{ 0x2500, 0x2502, 0x250c, 0x2510, 0x2514, 0x2518, 0x251c, 0x2524, 0x252c, 0x2534, 0x253c }) |cp| for ([_]pardes.FontRole{ .body, .tagline }) |role| { + for ([_]u32{ 0x2500, 0x2502, 0x250c, 0x2510, 0x2514, 0x2518, 0x251c, 0x2524, 0x252c, 0x2534, 0x253c }) |cp| for ([_]Atlas.Role{ .body, .tagline }) |role| { _ = cachedGlyph(&g, .{ .face = 0, .glyph = cp, .role = role, .rule = true }) orelse return error.AtlasFull; }; for ([_]u32{ '$', '^', 'j' }) |cp| for ([_]bool{ false, true }) |bold| { - const drawn = glyphForCodepoint(&g, cp); + const drawn = g.atlas.glyphForCodepoint(cp); _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .tagline, .decoration = .{ .bold = bold }, .centered = true }) orelse return error.AtlasFull; }; // Nerd icons (Yazi's folder, a file, powerline's arrow): Maple's, // the primary's or the fallback's. for ([_]u32{ 0xe5ff, 0xf07b, 0xe0b0 }) |cp| { - const drawn = glyphForCodepoint(&g, cp); + const drawn = g.atlas.glyphForCodepoint(cp); try std.testing.expect(drawn.glyph != 0); _ = cachedGlyph(&g, .{ .face = drawn.face, .glyph = drawn.glyph, .role = .body }) orelse return error.AtlasFull; } // Ligature strips, shaped by the words' cache as a frame shapes them. const line = textTestLine("a->b => != <= >= == === !== |> <| :: ++ -- www office"); for (0..line.len) |i| _ = cellSlot(&g, &line, i, null, .body); - stage_hash.update(g.atlas_stage); + stage_hash.update(g.atlas.atlas_stage); const Entry = struct { key: u64, u: u32, v: u32 }; var entries: std.ArrayList(Entry) = .empty; defer entries.deinit(std.testing.allocator); - var it = g.glyphs.iterator(); + var it = g.atlas.glyphs.iterator(); while (it.next()) |e| try entries.append(std.testing.allocator, .{ .key = @bitCast(e.key_ptr.*), .u = e.value_ptr.u, .v = e.value_ptr.v }); std.mem.sort(Entry, entries.items, {}, struct { fn less(_: void, x: Entry, y: Entry) bool { |
