diff options
Diffstat (limited to 'src/gui')
| -rw-r--r-- | src/gui/font.c | 471 | ||||
| -rw-r--r-- | src/gui/font.h | 98 | ||||
| -rw-r--r-- | src/gui/gui.zig | 735 |
3 files changed, 179 insertions, 1125 deletions
diff --git a/src/gui/font.c b/src/gui/font.c deleted file mode 100644 index aebe26e6..00000000 --- a/src/gui/font.c +++ /dev/null @@ -1,471 +0,0 @@ -// FreeType and HarfBuzz wrapper for gui.zig. The policy intentionally follows -// Ghostty's FreeType backend: native hinting enabled, the auto-hinter available -// as a fallback, and the light target for shape-preserving grayscale text. -// HarfBuzz only picks glyphs (liga, calt); the grid, not the font's advances, -// places them. -#include "font.h" -#include <freetype-zig.h> -#include <freetype/ftbitmap.h> -#include <freetype/ftmodapi.h> -#include <hb-ft.h> -#include <hb-ot.h> -#include <hb.h> - -#include <string.h> - -struct UIFont { - // FreeType allocates through ui_malloc and friends: the library holds a - // pointer to this for its lifetime, which the UIFont outlives. - struct FT_MemoryRec_ memory; - FT_Library library; - FT_Face face; - FT_F26Dot6 size; - // The charmap's answer for ASCII, which is most of every screen: a word the - // renderer has not seen before looks up each of its cells. - uint32_t ascii[128]; - // HarfBuzz state, made by the first ui_font_substitutes question (most - // fallback faces are never asked). - hb_font_t *hb; - hb_buffer_t *buffer; - FT_F26Dot6 hb_size; - // Every glyph a lookup of a ligature feature could replace. Nothing else - // can change a glyph, so a cell outside it is its nominal glyph without - // shaping: every cell, in a font without ligatures. - hb_set_t *substitutes; - // ui_font_shape's per-cell scratch, grown to the longest run seen - uint32_t *own; - uint8_t *state; - int32_t scratch; -}; - -static FT_F26Dot6 size_26_6(float px) { - if (px < 1.0f) - px = 1.0f; - return (FT_F26Dot6)(px * 64.0f + 0.5f); -} - -static int set_size(UIFont *f, float px) { - const FT_F26Dot6 size = size_26_6(px); - if (f->size == size) - return 1; - if (FT_Set_Char_Size(f->face, 0, size, 72, 72) != 0) - return 0; - f->size = size; - return 1; -} - -static int ceil_26_6(FT_Pos value) { return (int)((value + 63) >> 6); } - -static FT_Int32 load_flags(void) { - // Hinting is on because FT_LOAD_NO_HINTING is absent. Likewise, leaving - // FT_LOAD_NO_AUTOHINT absent lets FreeType fall back to its auto-hinter - // when the face has no native instructions. This is Ghostty's default. - return FT_LOAD_DEFAULT | FT_LOAD_TARGET_LIGHT; -} - -static void *ft_alloc(FT_Memory memory, long size) { - (void)memory; - return ui_malloc((size_t)size); -} - -static void ft_free(FT_Memory memory, void *block) { - (void)memory; - ui_free(block); -} - -static void *ft_realloc(FT_Memory memory, long cur_size, long new_size, - void *block) { - (void)memory; - (void)cur_size; - return ui_realloc(block, (size_t)new_size); -} - -UIFont *ui_font_new(const uint8_t *data, int32_t len) { - if (!data || len <= 0) - return NULL; - - UIFont *f = (UIFont *)ui_calloc(1, sizeof(UIFont)); - if (!f) - return NULL; - // FT_Init_FreeType is exactly FT_New_Library over FT_New_Memory's malloc - // manager, then the default modules and properties: the same, over ours. - f->memory = (struct FT_MemoryRec_){NULL, ft_alloc, ft_free, ft_realloc}; - if (FT_New_Library(&f->memory, &f->library) != 0) { - ui_free(f); - return NULL; - } - FT_Add_Default_Modules(f->library); - FT_Set_Default_Properties(f->library); - if (FT_New_Memory_Face(f->library, data, (FT_Long)len, 0, &f->face) != 0) { - FT_Done_Library(f->library); - ui_free(f); - return NULL; - } - // Some symbol fonts do not expose a Unicode charmap. FreeType already - // selects a usable default for those, so failure here is non-fatal. - (void)FT_Select_Charmap(f->face, FT_ENCODING_UNICODE); - for (uint32_t cp = 0; cp < 128; cp++) - f->ascii[cp] = FT_Get_Char_Index(f->face, cp); - return f; -} - -// HarfBuzz reads this same face (and its charmap) through FreeType, so shaping -// and rasterizing agree on glyph ids. None of these calls returns NULL: a -// failure is an inert empty object, and shaping then yields nominal glyphs. -static void start_harfbuzz(UIFont *f) { - f->hb = hb_ft_font_create_referenced(f->face); - f->buffer = hb_buffer_create(); - f->substitutes = hb_set_create(); - static const hb_tag_t features[] = { - HB_TAG('l', 'i', 'g', 'a'), HB_TAG('c', 'a', 'l', 't'), - HB_TAG('c', 'l', 'i', 'g'), HB_TAG('r', 'l', 'i', 'g'), - HB_TAG('r', 'c', 'l', 't'), HB_TAG_NONE}; - hb_face_t *face = hb_font_get_face(f->hb); - hb_set_t *lookups = hb_set_create(); - hb_ot_layout_collect_lookups(face, HB_OT_TAG_GSUB, NULL, NULL, features, - lookups); - hb_codepoint_t lookup = HB_SET_VALUE_INVALID; - while (hb_set_next(lookups, &lookup)) - hb_ot_layout_lookup_collect_glyphs(face, HB_OT_TAG_GSUB, lookup, NULL, - f->substitutes, NULL, NULL); - hb_set_destroy(lookups); -} - -const char *ui_font_name(UIFont *f) { - if (!f || !f->face) - return NULL; - const char *postscript = FT_Get_Postscript_Name(f->face); - if (postscript && postscript[0]) - return postscript; - if (f->face->family_name && f->face->family_name[0]) - return f->face->family_name; - return NULL; -} - -uint32_t ui_font_glyph(UIFont *f, int32_t cp) { - if (!f || cp < 0) - return 0; - if (cp < 128) - return f->ascii[cp]; - return FT_Get_Char_Index(f->face, (FT_ULong)(uint32_t)cp); -} - -void ui_font_free(UIFont *f) { - if (!f) - return; - // The HarfBuzz font holds a reference on the face: release it first. (All - // three accept NULL, a face that never shaped.) - hb_set_destroy(f->substitutes); - hb_buffer_destroy(f->buffer); - hb_font_destroy(f->hb); - if (f->face) - FT_Done_Face(f->face); - if (f->library) - FT_Done_Library(f->library); - ui_free(f->own); - ui_free(f->state); - ui_free(f); -} - -void ui_font_prime(UIFont *f) { - if (!f) - return; - hb_font_destroy(hb_ft_font_create_referenced(f->face)); - hb_buffer_t *buffer = hb_buffer_create(); - hb_buffer_add_utf8(buffer, "a", 1, 0, 1); - hb_buffer_guess_segment_properties(buffer); - hb_buffer_destroy(buffer); -} - -void ui_font_cell_metrics(UIFont *f, float px, int32_t *cell_w, int32_t *cell_h, - int32_t *ascent) { - if (!f || !cell_w || !cell_h || !ascent || !set_size(f, px)) { - if (cell_w) - *cell_w = 1; - if (cell_h) - *cell_h = 1; - if (ascent) - *ascent = 1; - return; - } - - const FT_Size_Metrics metrics = f->face->size->metrics; - const int asc = ceil_26_6(metrics.ascender); - const int desc = ceil_26_6(-metrics.descender); - int height = ceil_26_6(metrics.height); - if (height < asc + desc) - height = asc + desc; - - int width = ceil_26_6(metrics.max_advance); - const FT_UInt m = FT_Get_Char_Index(f->face, 'M'); - if (FT_Load_Glyph(f->face, m, load_flags()) == 0) { - const int advance = ceil_26_6(f->face->glyph->advance.x); - if (advance > 0) - width = advance; - } - - *cell_w = width > 0 ? width : 1; - *cell_h = height > 0 ? height : 1; - *ascent = asc > 0 ? asc : 1; -} - -static int raster(UIFont *f, float px, uint32_t glyph_index, int bold, - uint8_t *out, int32_t stride, int32_t width, int32_t height, - int32_t cell_x, int32_t cell_w, int32_t ascent, - int centered) { - if (!f || !out || stride < width || width <= 0 || height <= 0) - return 0; - for (int y = 0; y < height; y++) - memset(out + (size_t)y * (size_t)stride, 0, (size_t)width); - if (!set_size(f, px)) - return 0; - - if (FT_Load_Glyph(f->face, glyph_index, load_flags()) != 0) - return 0; - if (bold) { - // Synthetic bold thickens the hinted outline before it is rendered, so - // the wider stems are rasterized as one shape and keep hinted edges; the - // advance is untouched, as the cell grid requires. Strength is Ghostty's - // heuristic: 1/32 of the line height in 26.6, rounded up (one pixel at a - // 32 px line). A bitmap strike has no outline: widen it by one whole pixel, - // the classic overstrike, which keeps its pixels sharp. - FT_GlyphSlot slot = f->face->glyph; - if (slot->format == FT_GLYPH_FORMAT_OUTLINE) { - const FT_Pos height = f->face->size->metrics.height; - FT_Outline_Embolden(&slot->outline, (height + 31) / 32); - } else if (slot->format == FT_GLYPH_FORMAT_BITMAP && - FT_GlyphSlot_Own_Bitmap(slot) == 0) { - FT_Bitmap_Embolden(f->library, &slot->bitmap, 64, 0); - } - } - if (FT_Render_Glyph(f->face->glyph, FT_RENDER_MODE_NORMAL) != 0) - return 0; - - const FT_GlyphSlot glyph = f->face->glyph; - const FT_Bitmap *bitmap = &glyph->bitmap; - if (!bitmap->buffer || bitmap->width == 0 || bitmap->rows == 0) - return 0; - - const int advance = ceil_26_6(glyph->advance.x); - // Fallbacks may be proportional. Center their advance in the primary face's - // fixed cell, exactly as Ghostty centers a narrower fallback face. - const int gx = centered - ? (width - (int)bitmap->width) / 2 - : cell_x + glyph->bitmap_left + (cell_w - advance) / 2; - const int gy = - centered ? (height - (int)bitmap->rows) / 2 : ascent - glyph->bitmap_top; - const int pitch = bitmap->pitch; - const int row_bytes = pitch < 0 ? -pitch : pitch; - - for (unsigned int y = 0; y < bitmap->rows; y++) { - const int dy = gy + (int)y; - if (dy < 0 || dy >= height) - continue; - const unsigned int source_y = pitch < 0 ? bitmap->rows - 1 - y : y; - const uint8_t *src = bitmap->buffer + (size_t)source_y * (size_t)row_bytes; - - for (unsigned int x = 0; x < bitmap->width; x++) { - const int dx = gx + (int)x; - if (dx < 0 || dx >= width) - continue; - - uint8_t coverage; - if (bitmap->pixel_mode == FT_PIXEL_MODE_MONO) { - coverage = (src[x >> 3] & (0x80u >> (x & 7))) ? 255 : 0; - } else if (bitmap->pixel_mode == FT_PIXEL_MODE_GRAY) { - coverage = src[x]; - if (bitmap->num_grays > 1 && bitmap->num_grays != 256) - coverage = (uint8_t)((unsigned int)coverage * 255u / - (bitmap->num_grays - 1u)); - } else { - continue; - } - out[(size_t)dy * (size_t)stride + (size_t)dx] = coverage; - } - } - return 1; -} - -int ui_font_raster(UIFont *f, float px, uint32_t glyph, int bold, uint8_t *out, - int32_t stride, int32_t width, int32_t height, - int32_t cell_x, int32_t cell_w, int32_t ascent) { - return raster(f, px, glyph, bold, out, stride, width, height, cell_x, cell_w, - ascent, 0); -} - -int ui_font_raster_centered(UIFont *f, float px, uint32_t glyph, int bold, - uint8_t *out, int32_t stride, int32_t width, - int32_t height) { - return raster(f, px, glyph, bold, out, stride, width, height, 0, width, 0, 1); -} - -// The horizontal ink of `glyph` placed as ui_font_raster places it in a cell -// `cell` wide (26.6), relative to the cell's left edge. 0 when it has no ink. -static int ink(UIFont *f, uint32_t glyph, FT_Pos cell, FT_Pos *left, - FT_Pos *right) { - if (FT_Load_Glyph(f->face, glyph, load_flags()) != 0) - return 0; - const FT_GlyphSlot slot = f->face->glyph; - if (slot->metrics.width <= 0 || slot->metrics.height <= 0) - return 0; - const FT_Pos origin = - (FT_Pos)(((int)(cell >> 6) - ceil_26_6(slot->advance.x)) / 2) * 64; - *left = origin + slot->metrics.horiBearingX; - *right = *left + slot->metrics.width; - return 1; -} - -// ui_font_shape's per-cell marks: no glyph of its own, keep the nominal glyph, -// drawn as a slice of another cell's glyph. -#define NONE UINT32_MAX -#define PLAIN 1 -#define CLAIMED 2 - -int ui_font_substitutes(UIFont *f, uint32_t glyph) { - if (!f) - return 0; - if (!f->hb) - start_harfbuzz(f); - return hb_set_has(f->substitutes, glyph); -} - -// The GSUB features shaping leaves on are the ligature ones; the others -// HarfBuzz would apply (glyph composition, local forms, fractions around -// U+2044, ...) are off, so a cell is either its nominal glyph, as the renderer -// always drew it, or part of a ligature. Positioning is untouched: the grid -// ignores advances and keeps nominal glyphs where marks would move. -static const hb_feature_t shaping_features[] = { - {HB_TAG('c', 'c', 'm', 'p'), 0, 0, (unsigned int)-1}, - {HB_TAG('l', 'o', 'c', 'l'), 0, 0, (unsigned int)-1}, - {HB_TAG('r', 'v', 'r', 'n'), 0, 0, (unsigned int)-1}, - {HB_TAG('l', 't', 'r', 'a'), 0, 0, (unsigned int)-1}, - {HB_TAG('l', 't', 'r', 'm'), 0, 0, (unsigned int)-1}, - {HB_TAG('r', 'a', 'n', 'd'), 0, 0, (unsigned int)-1}, - {HB_TAG('f', 'r', 'a', 'c'), 0, 0, (unsigned int)-1}, - {HB_TAG('n', 'u', 'm', 'r'), 0, 0, (unsigned int)-1}, - {HB_TAG('d', 'n', 'o', 'm'), 0, 0, (unsigned int)-1}, -}; - -void ui_font_shape(UIFont *f, float px, int32_t cell_w, const uint32_t *cps, - int32_t n, UIShapedCell *out) { - if (!f || !cps || !out || n <= 0) - return; - for (int32_t i = 0; i < n; i++) - out[i] = (UIShapedCell){ui_font_glyph(f, (int32_t)cps[i]), 0, 1, 0}; - if (!f->hb) - start_harfbuzz(f); - int substitutable = 0; - for (int32_t i = 0; i < n && !substitutable; i++) - substitutable = hb_set_has(f->substitutes, out[i].glyph); - if (!substitutable || cell_w <= 0 || !set_size(f, px)) - return; - if (n > f->scratch) { - uint32_t *own = (uint32_t *)ui_realloc(f->own, (size_t)n * sizeof *own); - if (!own) - return; - f->own = own; - uint8_t *state = (uint8_t *)ui_realloc(f->state, (size_t)n); - if (!state) - return; - f->state = state; - f->scratch = n; - } - // hb-ft reads the FreeType size when told; positions are only consulted - // for being nonzero, but a zero scale would hide exactly that. - if (f->hb_size != f->size) { - hb_ft_font_changed(f->hb); - f->hb_size = f->size; - } - hb_buffer_clear_contents(f->buffer); - // One codepoint per cell, so a cluster value IS a cell index. - hb_buffer_add_codepoints(f->buffer, cps, n, 0, n); - hb_buffer_set_direction(f->buffer, HB_DIRECTION_LTR); - hb_buffer_guess_segment_properties(f->buffer); - hb_shape(f->hb, f->buffer, shaping_features, - sizeof shaping_features / sizeof shaping_features[0]); - unsigned int count = 0; - const hb_glyph_info_t *info = hb_buffer_get_glyph_infos(f->buffer, &count); - const hb_glyph_position_t *pos = - hb_buffer_get_glyph_positions(f->buffer, &count); - - // Each cell's own glyph is the one HarfBuzz left in its cluster. A cell a - // ligature merged into an earlier cluster has NONE. A cluster the grid - // cannot place (several glyphs, a positioned mark) is PLAIN, and so are the - // cells merged into it: they keep their nominal glyphs. - uint32_t *own = f->own; - uint8_t *state = f->state; - for (int32_t i = 0; i < n; i++) { - own[i] = NONE; - state[i] = 0; - } - for (unsigned int k = 0; k < count; k++) { - const uint32_t cluster = info[k].cluster; - if (cluster >= (uint32_t)n) - continue; - if (own[cluster] != NONE || pos[k].x_offset != 0 || pos[k].y_offset != 0) - state[cluster] = PLAIN; - else - own[cluster] = info[k].codepoint; - } - for (int32_t i = 1; i < n; i++) - if (own[i] == NONE && (state[i - 1] & PLAIN)) - state[i] = PLAIN; - - // A substituted glyph (or one whose cluster swallowed cells) may reach over - // its neighbours: it claims those that draw nothing of their own, nearest - // first, and each draws its slice of the one strip. Ink past a cell edge by - // half a pixel or less is noise. - const FT_Pos cell = (FT_Pos)cell_w * 64; - for (int32_t i = 0; i < n; i++) { - if ((state[i] & (PLAIN | CLAIMED)) || own[i] == NONE) - continue; - int32_t merged = 0; - while (i + 1 + merged < n && own[i + 1 + merged] == NONE && - !(state[i + 1 + merged] & PLAIN)) - merged++; - if (own[i] == out[i].glyph && merged == 0) - continue; - FT_Pos left = 0, right = 0; - if (!ink(f, own[i], cell, &left, &right)) - continue; // a spacer: claimed, never claiming - int32_t want_left = - left < -32 ? (int32_t)((-left - 32 + cell - 1) / cell) : 0; - int32_t want_right = right > cell + 32 - ? (int32_t)((right - cell - 32 + cell - 1) / cell) - : 0; - if (want_right < merged) - want_right = merged; - int32_t lead = 0, trail = 0; - while (lead < want_left && 1 + lead + trail < UI_MAX_SPAN) { - const int32_t j = i - lead - 1; - FT_Pos l, r; - if (j < 0 || (state[j] & (PLAIN | CLAIMED)) || - (own[j] != NONE && - (own[j] == out[j].glyph || ink(f, own[j], cell, &l, &r)))) - break; - lead++; - } - while (trail < want_right && 1 + lead + trail < UI_MAX_SPAN) { - const int32_t j = i + trail + 1; - FT_Pos l, r; - if (j >= n || (state[j] & (PLAIN | CLAIMED)) || - (own[j] != NONE && - (own[j] == out[j].glyph || ink(f, own[j], cell, &l, &r)))) - break; - trail++; - } - for (int32_t j = i - lead; j <= i + trail; j++) { - out[j] = - (UIShapedCell){own[i], (uint8_t)lead, (uint8_t)(1 + lead + trail), - (uint8_t)(j - (i - lead))}; - state[j] |= CLAIMED; - } - } - // The rest draw their own glyph; a merged cell nothing claimed draws blank. - const uint32_t space = f->ascii[' ']; - for (int32_t i = 0; i < n; i++) { - if (state[i] & (PLAIN | CLAIMED)) - continue; - out[i].glyph = own[i] == NONE ? space : own[i]; - } -} diff --git a/src/gui/font.h b/src/gui/font.h deleted file mode 100644 index db964fb0..00000000 --- a/src/gui/font.h +++ /dev/null @@ -1,98 +0,0 @@ -// Tiny C shim over FreeType and HarfBuzz, so gui.zig only imports the stable -// renderer API. The implementation owns FreeType's library and face objects -// and HarfBuzz's font and buffer, and keeps the caller's font bytes borrowed -// for the face lifetime. -#ifndef UI_FONT_H -#define UI_FONT_H -#include <stddef.h> -#include <stdint.h> - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct UIFont UIFont; - -// Every allocation FreeType, HarfBuzz and this shim make: C's malloc, calloc, -// realloc and free, implemented by gui.zig over a Zig allocator. HarfBuzz is -// compiled to call them (hb_malloc_impl and friends); FreeType gets them as -// each library's memory manager. -void *ui_malloc(size_t size); -void *ui_calloc(size_t count, size_t size); -void *ui_realloc(void *block, size_t size); -void ui_free(void *block); - -// Parse the first face in an in-memory font. `data` must stay alive for the -// lifetime of the font. Returns NULL on failure. -UIFont *ui_font_new(const uint8_t *data, int32_t len); - -// The face FreeType actually accepted. Prefer its PostScript name (the same -// identity the macOS shell reports); fall back to the family name when the -// font has no PostScript table. Borrowed for the UIFont lifetime. -const char *ui_font_name(UIFont *f); - -// The glyph the selected Unicode charmap maps `cp` to. Glyph zero is the -// face's .notdef box: the codepoint is missing, which is what fallback choice -// asks. -uint32_t ui_font_glyph(UIFont *f, int32_t cp); - -// `px` is the pixel height. Metrics and rasterization both configure FreeType -// at that size, so hinted advances, baseline and bitmaps stay in step. -void ui_font_cell_metrics(UIFont *f, float px, int32_t *cell_w, int32_t *cell_h, - int32_t *ascent); - -// What one grid cell draws: `slice` of the glyph `glyph` rasterized across -// `span` cells with its own cell `lead` cells from the left. A plain cell is -// its own glyph, lead 0, span 1, slice 0. -typedef struct { - uint32_t glyph; - uint8_t lead; - uint8_t span; - uint8_t slice; -} UIShapedCell; - -// The longest glyph strip a ligature may claim, in cells. -#define UI_MAX_SPAN 8 - -// Whether a lookup of the font's ligature features (liga, calt, clig, rlig, -// rclt) could replace `glyph`. When it cannot, shaping leaves the glyph alone -// and its cell needs no shaping at all. -int ui_font_substitutes(UIFont *f, uint32_t glyph); - -// One cell per codepoint of `cps`, all in this face, shaped by HarfBuzz with -// the font's ligature features (a run with no glyph ui_font_substitutes -// reports comes back nominal without it). A substituted glyph whose ink -// reaches over neighbouring cells that draw nothing of their own (a -// ligature's spacers, or the cells a merged cluster swallowed) claims them as -// a strip. Otherwise, and for anything the grid cannot place (several glyphs -// in one cell, positioned marks), each cell is its nominal glyph. -void ui_font_shape(UIFont *f, float px, int32_t cell_w, const uint32_t *cps, - int32_t n, UIShapedCell *out); - -// Rasterize `glyph` into `out` as a hinted grayscale mask of `width` x -// `height` (`stride` bytes per row). The glyph's advance is centered in the -// `cell_w` pixels that start at `cell_x`, and its baseline is `ascent` pixels -// from the top; ink outside the mask is clipped. `bold` emboldens the outline -// before rendering (synthetic bold, same advance). Returns 1 when the glyph -// produced coverage, 0 for blank/error. -int ui_font_raster(UIFont *f, float px, uint32_t glyph, int bold, uint8_t *out, - int32_t stride, int32_t width, int32_t height, - int32_t cell_x, int32_t cell_w, int32_t ascent); - -// Center bitmap ink bounds, independent of advance and baseline bearings. -int ui_font_raster_centered(UIFont *f, float px, uint32_t glyph, int bold, - uint8_t *out, int32_t stride, int32_t width, - int32_t height); - -void ui_font_free(UIFont *f); - -// HarfBuzz makes a few process-wide objects on first use and keeps them for -// the life of the process (the default Unicode functions, the locale's -// language, hb-ft's font functions). Making them here, with `f`'s face, lets -// the caller hand them an allocator that does not count them as leaks. -void ui_font_prime(UIFont *f); - -#ifdef __cplusplus -} -#endif -#endif 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 { |
