diff options
Diffstat (limited to 'vendor/text.c')
| -rw-r--r-- | vendor/text.c | 432 |
1 files changed, 160 insertions, 272 deletions
diff --git a/vendor/text.c b/vendor/text.c index 8b2a54e..09e3902 100644 --- a/vendor/text.c +++ b/vendor/text.c @@ -1,23 +1,20 @@ -/* Native text: Pardes's FreeType/HarfBuzz quality target, via Pango's complete - script itemization, shaping, bidi and Fontconfig fallback instead of its - terminal-cell-specific shaping layer. Grayscale coverage avoids color fringes. */ -#define _GNU_SOURCE +/* sketchbook's text (text.h): HarfBuzz shapes, pardes's font.c rasterizes + and gives the line box. The ten bundled faces are embedded with #embed; + each face is opened on first use, by FreeType (font.c) and HarfBuzz's + own OpenType functions over the same bytes, so glyph ids agree. */ #include "text.h" -#include <fontconfig/fontconfig.h> -#include <pango/pangofc-fontmap.h> -#include <sys/mman.h> -#include <unistd.h> -#include <errno.h> -#include <pango/pangocairo.h> +#include <hb.h> #include <math.h> -#include <stdint.h> #include <stdlib.h> #include <string.h> -#define CACHE_ENTRIES 4096 -#define CACHE_BYTES (128 * 1024 * 1024) -#define CACHE_PROPERTY "sketchbook.native-text" -/* The Go family, bundled: one file a face, in `SkTextFace` order. */ +/* font.h's allocator, for FreeType and HarfBuzz (built with + hb_malloc_impl=ui_malloc): C's heap. */ +void *ui_malloc(size_t size) { return malloc(size); } +void *ui_calloc(size_t count, size_t size) { return calloc(count, size); } +void *ui_realloc(void *block, size_t size) { return realloc(block, size); } +void ui_free(void *block) { free(block); } + static const unsigned char go_mono[] = { #embed "fonts/Go-Mono.ttf" }; @@ -36,8 +33,6 @@ static const unsigned char go_medium[] = { static const unsigned char go_bold[] = { #embed "fonts/Go-Bold.ttf" }; -/* JetBrains Mono NL, for code: the same 0.6 em advance as Go Mono, and no - ligatures (`->` stays two characters, as it is in the source). */ static const unsigned char jb_mono[] = { #embed "fonts/JetBrainsMonoNL-Regular.ttf" }; @@ -50,277 +45,170 @@ static const unsigned char jb_mono_italic[] = { static const unsigned char jb_mono_medium[] = { #embed "fonts/JetBrainsMonoNL-Medium.ttf" }; -static const struct { const unsigned char *bytes; size_t len; const char *family, *style; } faces[SK_TEXT_FACES] = { - {go_mono, sizeof(go_mono), "Go Mono", ""}, - {go_mono_bold, sizeof(go_mono_bold), "Go Mono", " Bold"}, - {go_mono_italic, sizeof(go_mono_italic), "Go Mono", " Italic"}, - {go_regular, sizeof(go_regular), "Go", ""}, - {go_medium, sizeof(go_medium), "Go Medium", ""}, - {go_bold, sizeof(go_bold), "Go", " Bold"}, - {jb_mono, sizeof(jb_mono), "JetBrains Mono NL", ""}, - {jb_mono_bold, sizeof(jb_mono_bold), "JetBrains Mono NL", " Bold"}, - {jb_mono_italic, sizeof(jb_mono_italic), "JetBrains Mono NL", " Italic"}, - {jb_mono_medium, sizeof(jb_mono_medium), "JetBrains Mono NL", " Medium"}, -}; -typedef struct { - SDL_Texture *texture; - char *text; - size_t len, bytes; - uint64_t hash, used; - int size, width, height, left, top, face; - Uint32 color; -} Text; -typedef struct { - PangoFontMap *map; - PangoContext *context; - PangoLayout *layout; - PangoFontDescription *font[SK_TEXT_FACES]; - FcConfig *config; - int font_fd[SK_TEXT_FACES]; - Text entries[CACHE_ENTRIES]; - size_t bytes; - uint64_t frame; -} TextCache; +/* ponytail: one thread. The host shapes on its main thread, a test binary + on the runner's; a second thread would need a lock here. */ +static struct { + const uint8_t *bytes; + size_t len; + UIFont *ui; + hb_font_t *hb; +} faces[SK_TEXT_MAX_FACES] = { + {go_mono, sizeof go_mono}, {go_mono_bold, sizeof go_mono_bold}, + {go_mono_italic, sizeof go_mono_italic}, {go_regular, sizeof go_regular}, + {go_medium, sizeof go_medium}, {go_bold, sizeof go_bold}, + {jb_mono, sizeof jb_mono}, {jb_mono_bold, sizeof jb_mono_bold}, + {jb_mono_italic, sizeof jb_mono_italic}, {jb_mono_medium, sizeof jb_mono_medium}, +}; +static int count = SK_TEXT_FACES; +static hb_buffer_t *buffer; -static void release_text(Text *t) { - if (t->texture) SDL_DestroyTexture(t->texture); - free(t->text); - memset(t, 0, sizeof(*t)); -} -static void SDLCALL release_cache(void *userdata, void *value) { - (void)userdata; - TextCache *c = value; - /* SDL destroys its owned textures before renderer property cleanup. */ - for (size_t i = 0; i < CACHE_ENTRIES; ++i) free(c->entries[i].text); - for (int i = 0; i < SK_TEXT_FACES; ++i) if (c->font[i]) pango_font_description_free(c->font[i]); - if (c->layout) g_object_unref(c->layout); - if (c->context) g_object_unref(c->context); - if (c->map) g_object_unref(c->map); - if (c->config) FcConfigDestroy(c->config); - for (int i = 0; i < SK_TEXT_FACES; ++i) if (c->font_fd[i] >= 0) close(c->font_fd[i]); - free(c); -} -static TextCache *cache_for(SDL_Renderer *renderer) { - SDL_PropertiesID props = SDL_GetRendererProperties(renderer); - TextCache *c = SDL_GetPointerProperty(props, CACHE_PROPERTY, NULL); - if (c) return c; - c = calloc(1, sizeof(*c)); - if (!c) return NULL; - for (int i = 0; i < SK_TEXT_FACES; ++i) c->font_fd[i] = -1; - c->config = FcInitLoadConfigAndFonts(); - if (!c->config) { release_cache(NULL, c); return NULL; } - for (int i = 0; i < SK_TEXT_FACES; ++i) { - c->font_fd[i] = memfd_create("sketchbook-go", MFD_CLOEXEC); - if (c->font_fd[i] < 0) { release_cache(NULL, c); return NULL; } - size_t offset = 0; - while (offset < faces[i].len) { - ssize_t n = write(c->font_fd[i], faces[i].bytes + offset, faces[i].len - offset); - if (n < 0 && errno == EINTR) continue; - if (n <= 0) { release_cache(NULL, c); return NULL; } - offset += (size_t)n; - } - char path[64]; - snprintf(path, sizeof(path), "/proc/self/fd/%d", c->font_fd[i]); - if (!FcConfigAppFontAddFile(c->config, (const FcChar8 *)path)) { - release_cache(NULL, c); - return NULL; - } - } - c->map = pango_cairo_font_map_new_for_font_type(CAIRO_FONT_TYPE_FT); - pango_fc_font_map_set_config(PANGO_FC_FONT_MAP(c->map), c->config); - c->context = pango_font_map_create_context(c->map); - c->layout = pango_layout_new(c->context); - /* SKETCHBOOK_FONT names an installed family to use before the built-in - mono one. The sans faces fall back the same way after their own. */ - const char *first = getenv("SKETCHBOOK_FONT"); - for (int i = 0; i < SK_TEXT_FACES; ++i) { - const bool mono = i <= SK_TEXT_MONO_ITALIC || i >= SK_TEXT_CODE; - char families[640]; - snprintf(families, sizeof(families), "%s%s%s, %sNoto Sans Arabic, Noto Sans Hebrew, IBM Plex Sans JP, Noto Color Emoji, Noto Sans Symbols 2, DejaVu Sans, %s%s", - mono && first ? first : "", mono && first ? ", " : "", faces[i].family, - mono ? "Noto Sans Mono, DejaVu Sans Mono, " : "Go, Noto Sans, ", mono ? "monospace" : "sans-serif", faces[i].style); - c->font[i] = pango_font_description_from_string(families); - } - cairo_font_options_t *options = cairo_font_options_create(); - cairo_font_options_set_antialias(options, CAIRO_ANTIALIAS_GRAY); - cairo_font_options_set_hint_style(options, CAIRO_HINT_STYLE_SLIGHT); - cairo_font_options_set_hint_metrics(options, CAIRO_HINT_METRICS_ON); - pango_cairo_context_set_font_options(c->context, options); - cairo_font_options_destroy(options); - pango_context_set_round_glyph_positions(c->context, TRUE); - pango_layout_set_single_paragraph_mode(c->layout, TRUE); - c->frame = 1; - if (!SDL_SetPointerPropertyWithCleanup(props, CACHE_PROPERTY, c, release_cache, NULL)) { - release_cache(NULL, c); - return NULL; - } - return c; +/* `face` opened, or the mono for an unknown one. */ +static int open_face(int face) { + if (face < 0 || face >= count) face = SK_TEXT_MONO; + if (!faces[face].ui) { + faces[face].ui = ui_font_new(faces[face].bytes, (int32_t)faces[face].len); + hb_blob_t *blob = hb_blob_create((const char *)faces[face].bytes, (unsigned)faces[face].len, + HB_MEMORY_MODE_READONLY, NULL, NULL); + hb_face_t *hb_face = hb_face_create(blob, 0); + faces[face].hb = hb_font_create(hb_face); + hb_face_destroy(hb_face); + hb_blob_destroy(blob); + } + return face; } -void sk_text_begin_frame(SDL_Renderer *renderer) { - TextCache *c = SDL_GetPointerProperty(SDL_GetRendererProperties(renderer), CACHE_PROPERTY, NULL); - /* A sketch may clear twice in a frame. Flush first so any eviction of a - previous epoch can never destroy a texture referenced by queued draws. */ - if (c) { - SDL_FlushRenderer(renderer); - ++c->frame; - } +UIFont *sk_text_ui(int face) { + if (face < 0 || face >= count) return NULL; + return faces[open_face(face)].ui; } -static float density(SDL_Renderer *renderer) { - float sx = 1, sy = 1; - SDL_GetRenderScale(renderer, &sx, &sy); - int w = 0, h = 0; - SDL_RendererLogicalPresentation mode; - SDL_FRect rect; - if (SDL_GetRenderLogicalPresentation(renderer, &w, &h, &mode) && - mode != SDL_LOGICAL_PRESENTATION_DISABLED && w > 0 && h > 0 && - SDL_GetRenderLogicalPresentationRect(renderer, &rect)) { - sx *= rect.w / w; - sy *= rect.h / h; - } - return fmaxf(0.25f, fmaxf(sx, sy)); -} -static uint64_t hash_text(const char *bytes, size_t len) { - uint64_t hash = UINT64_C(14695981039346656037); - for (size_t i = 0; i < len; ++i) hash = (hash ^ (unsigned char)bytes[i]) * UINT64_C(1099511628211); - return hash; -} -/* The font size, in 64ths of a physical pixel, that `scale` asks for. */ -static int font_size(float scale, float dpi) { - return (int)lroundf(fminf(512, 13.0f * scale * dpi) * 64); -} -/* Lays `bytes` out at `size`: its extents in physical pixels (`ink` may be NULL). */ -static bool lay_out(TextCache *c, const char *bytes, size_t len, int size, int face, - PangoRectangle *ink, PangoRectangle *logical) { - if (len > INT_MAX || !g_utf8_validate(bytes, (gssize)len, NULL)) return false; - pango_font_description_set_absolute_size(c->font[face], (double)size * PANGO_SCALE / 64.0); - pango_layout_set_font_description(c->layout, c->font[face]); - pango_layout_set_text(c->layout, bytes, (int)len); - pango_layout_get_pixel_extents(c->layout, ink, logical); - return true; -} -static bool rasterize(TextCache *c, SDL_Renderer *renderer, Text *out, - const char *bytes, size_t len, int size, int face, Uint32 color) { - PangoRectangle ink, logical; - if (!lay_out(c, bytes, len, size, face, &ink, &logical)) return false; - const int left = MIN(0, ink.x) - 1; - const int top = MIN(0, ink.y) - 1; - const int width = MAX(logical.x + logical.width, ink.x + ink.width) - left + 1; - const int height = MAX(logical.y + logical.height, ink.y + ink.height) - top + 1; - if (width <= 0 || height <= 0 || width > 16384 || height > 4096 || - (size_t)width * height * 4 > CACHE_BYTES) return false; - cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); - if (cairo_surface_status(surface) != CAIRO_STATUS_SUCCESS) { - cairo_surface_destroy(surface); - return false; - } - cairo_t *cr = cairo_create(surface); - cairo_set_source_rgb(cr, ((color >> 16) & 255) / 255.0, ((color >> 8) & 255) / 255.0, (color & 255) / 255.0); - cairo_move_to(cr, -left, -top); - pango_cairo_show_layout(cr, c->layout); - cairo_destroy(cr); - cairo_surface_flush(surface); - SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, - SDL_TEXTUREACCESS_STATIC, width, height); - const bool okay = texture && SDL_UpdateTexture(texture, NULL, cairo_image_surface_get_data(surface), - cairo_image_surface_get_stride(surface)); - cairo_surface_destroy(surface); - if (!okay) { if (texture) SDL_DestroyTexture(texture); return false; } - SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND_PREMULTIPLIED); - SDL_SetTextureScaleMode(texture, SDL_SCALEMODE_LINEAR); - char *key = malloc(len + 1); - if (!key) { SDL_DestroyTexture(texture); return false; } - memcpy(key, bytes, len); key[len] = 0; - *out = (Text){.texture=texture,.text=key,.len=len,.bytes=(size_t)width*height*4, - .hash=hash_text(bytes,len),.used=c->frame,.size=size,.width=width,.height=height, - .left=left,.top=top,.face=face,.color=color}; - return true; +int sk_text_font(const uint8_t *bytes, size_t len) { + if (!bytes || len == 0 || len > INT32_MAX) return -1; + for (int i = SK_TEXT_FACES; i < count; i++) + if (faces[i].len == len && memcmp(faces[i].bytes, bytes, len) == 0) return i; + if (count == SK_TEXT_MAX_FACES) return -1; + uint8_t *copy = malloc(len); + if (!copy) return -1; + memcpy(copy, bytes, len); + UIFont *ui = ui_font_new(copy, (int32_t)len); + if (!ui) { + free(copy); + return -1; + } + faces[count].bytes = copy; + faces[count].len = len; + faces[count].ui = ui; + open_face(count); /* its HarfBuzz font */ + return count++; } -bool sk_text_measure(SDL_Renderer *renderer, float scale, const char *utf8, size_t len, - float *width, float *height) { - return sk_text_measure_face(renderer, SK_TEXT_MONO, scale, utf8, len, width, height); +/* ponytail: one fallback face, no fontconfig. JetBrains Mono NL for the Go + faces and a sketch's own, Go Mono for JetBrains Mono's. */ +static int fallback(int face) { + return face >= SK_TEXT_CODE && face < SK_TEXT_FACES ? SK_TEXT_MONO : SK_TEXT_CODE; } -bool sk_text_measure_face(SDL_Renderer *renderer, int face, float scale, const char *utf8, size_t len, - float *width, float *height) { - if (!isfinite(scale) || scale <= 0 || face < 0 || face >= SK_TEXT_FACES) return false; - TextCache *c = cache_for(renderer); - if (!c) return false; - const float dpi = density(renderer); - PangoRectangle logical; - if (!lay_out(c, utf8, len, font_size(scale, dpi), face, NULL, &logical)) return false; - *width = logical.width / dpi; - *height = logical.height / dpi; - return true; +/* The codepoint at `s` and its length; an invalid byte is U+FFFD, one byte. */ +static size_t decode(const unsigned char *s, size_t n, uint32_t *cp) { + const unsigned lead = s[0]; + const size_t len = lead < 0x80 ? 1 : (lead >> 5) == 6 ? 2 : (lead >> 4) == 14 ? 3 : (lead >> 3) == 30 ? 4 : 0; + if (len == 0 || len > n) return *cp = 0xfffd, 1; + uint32_t v = len == 1 ? lead : lead & (0x7f >> len); + for (size_t i = 1; i < len; i++) { + if ((s[i] & 0xc0) != 0x80) return *cp = 0xfffd, 1; + v = v << 6 | (s[i] & 0x3f); + } + *cp = v; + return len; } -bool sk_text_draw(SDL_Renderer *renderer, float x, float y, float scale, - const char *utf8, size_t len, Uint8 r, Uint8 g, Uint8 b, Uint8 a) { - return sk_text_draw_face(renderer, SK_TEXT_MONO, x, y, scale, utf8, len, r, g, b, a); -} +static int32_t whole(hb_position_t v) { return (int32_t)lroundf((float)v / 64.0f); } + +static int scale_of(float px) { return (int)lroundf(fmaxf(px, 1.0f) * 64.0f); } -bool sk_text_draw_face(SDL_Renderer *renderer, int face, float x, float y, float scale, - const char *utf8, size_t len, Uint8 r, Uint8 g, Uint8 b, Uint8 a) { - return sk_text_draw_scaled(renderer, face, x, y, scale, scale, utf8, len, r, g, b, a); +int32_t sk_text_advance(int face, float px, uint32_t glyph) { + hb_font_t *hb = faces[open_face(face)].hb; + hb_font_set_scale(hb, scale_of(px), scale_of(px)); + return whole(hb_font_get_glyph_h_advance(hb, glyph)); } -bool sk_text_draw_scaled(SDL_Renderer *renderer, int face, float x, float y, float scale, float raster, - const char *utf8, size_t len, Uint8 r, Uint8 g, Uint8 b, Uint8 a) { - if (!len || !a) return true; - if (!isfinite(scale) || scale <= 0 || !isfinite(raster) || raster <= 0 || face < 0 || face >= SK_TEXT_FACES) return false; - TextCache *c = cache_for(renderer); - if (!c) return false; - const float dpi = density(renderer); - const int size = font_size(raster, dpi); - /* How much larger than rasterized it is drawn: 1 when it is drawn as it is. */ - const float k = scale / raster; - const Uint32 color = ((Uint32)r << 16) | ((Uint32)g << 8) | b; - const uint64_t hash = hash_text(utf8, len); - Text *entry = NULL; - for (size_t i = 0; i < CACHE_ENTRIES; ++i) { - Text *t = &c->entries[i]; - if (t->texture && t->hash == hash && t->len == len && t->size == size && t->face == face && - t->color == color && !memcmp(t->text, utf8, len)) { entry = t; break; } +int sk_text_shape(int face, float px, const char *utf8, size_t len, SkGlyph *out, int max, + int32_t *advance, int32_t *ascent, int32_t *height) { + face = open_face(face); + const int other = open_face(fallback(face)); + int32_t cell_w, cell_h, asc; + ui_font_cell_metrics(faces[face].ui, px, &cell_w, &cell_h, &asc); + *ascent = asc; + *height = cell_h; + *advance = 0; + if (!utf8 || len == 0 || len > INT32_MAX) return 0; + if (!buffer) buffer = hb_buffer_create(); + const int scale = scale_of(px); + int n = 0; + int32_t pen = 0; + size_t i = 0; + while (i < len) { + /* A segment: the codepoints one face draws. A codepoint goes to the + fallback only when the face lacks it and the fallback has it. */ + const size_t start = i; + int which = -1; + while (i < len) { + uint32_t cp; + const size_t step = decode((const unsigned char *)utf8 + i, len - i, &cp); + const int own = ui_font_glyph(faces[face].ui, (int32_t)cp) != 0 || + ui_font_glyph(faces[other].ui, (int32_t)cp) == 0; + const int here = own ? face : other; + if (which < 0) which = here; + else if (here != which) break; + i += step; } - Text made = {0}; - if (!entry) { - if (!rasterize(c, renderer, &made, utf8, len, size, face, color)) return false; - /* Only evict textures unused this epoch. SDL can still have queued draws - referring to current-frame entries; those stay alive through present. */ - while (!entry) { - Text *oldest = NULL; - for (size_t i = 0; i < CACHE_ENTRIES; ++i) { - Text *t = &c->entries[i]; - if (!t->texture) { if (!entry) entry = t; } - else if (t->used < c->frame && (!oldest || t->used < oldest->used)) oldest = t; - } - if (entry && c->bytes + made.bytes <= CACHE_BYTES) break; - entry = NULL; - if (!oldest) break; - c->bytes -= oldest->bytes; - release_text(oldest); - } - if (entry) { *entry = made; c->bytes += made.bytes; } - else entry = &made; + hb_font_t *hb = faces[which].hb; + hb_font_set_scale(hb, scale, scale); + hb_buffer_clear_contents(buffer); + /* The whole text as context, the segment as the item: clusters are + byte offsets into `utf8`. */ + hb_buffer_add_utf8(buffer, utf8, (int)len, (unsigned)start, (int)(i - start)); + hb_buffer_set_direction(buffer, HB_DIRECTION_LTR); /* ponytail: no bidi */ + hb_buffer_guess_segment_properties(buffer); + hb_shape(hb, buffer, NULL, 0); + unsigned glyphs = 0; + const hb_glyph_info_t *info = hb_buffer_get_glyph_infos(buffer, &glyphs); + const hb_glyph_position_t *pos = hb_buffer_get_glyph_positions(buffer, &glyphs); + for (unsigned k = 0; k < glyphs; k++, n++) { + if (out && n < max) + out[n] = (SkGlyph){info[k].codepoint, info[k].cluster, pen + whole(pos[k].x_offset), + -whole(pos[k].y_offset), (uint8_t)which}; + pen += whole(pos[k].x_advance); } - entry->used = c->frame; - /* Cairo pixels are premultiplied; modulate RGB and alpha together. Color - glyphs retain their intrinsic paint, while ordinary text uses its ink. */ - SDL_SetTextureColorMod(entry->texture, a, a, a); - SDL_SetTextureAlphaMod(entry->texture, a); - SDL_FRect dest = {.x=(roundf(x*dpi)+entry->left)/dpi,.y=(roundf(y*dpi)+entry->top)/dpi, - .w=entry->width/dpi,.h=entry->height/dpi}; - if (k != 1) dest = (SDL_FRect){.x=x+entry->left*k/dpi,.y=y+entry->top*k/dpi, - .w=entry->width*k/dpi,.h=entry->height*k/dpi}; - const bool okay = SDL_RenderTexture(renderer, entry->texture, NULL, &dest); - if (entry == &made) { - /* Exceptional very dense frames remain bounded instead of retaining - every unique string. Flush before releasing this temporary texture. */ - SDL_FlushRenderer(renderer); - release_text(&made); + } + *advance = pen; + return n; +} + +int32_t sk_text_run(int face, float px, const char *utf8, size_t len, float *xs, + int32_t *ascent, int32_t *height) { + static SkGlyph *glyphs; + static int room; + int32_t advance = 0; + int n = sk_text_shape(face, px, utf8, len, glyphs, room, &advance, ascent, height); + if (!xs) return advance; + if (n > room) { + SkGlyph *more = realloc(glyphs, (size_t)n * sizeof *glyphs); + if (!more) n = room; + else { + glyphs = more; + room = n; + sk_text_shape(face, px, utf8, len, glyphs, room, &advance, ascent, height); } - return okay; + } + for (size_t i = 0; i < len; i++) xs[i] = -1; + for (int k = 0; k < n; k++) + if (glyphs[k].cluster < len && xs[glyphs[k].cluster] < 0) xs[glyphs[k].cluster] = glyphs[k].x > 0 ? (float)glyphs[k].x : 0; + float last = 0; + for (size_t i = 0; i < len; i++) { + if (xs[i] < 0) xs[i] = last; + last = xs[i]; + } + return advance; } |
