diff options
Diffstat (limited to 'vendor/text.c')
| -rw-r--r-- | vendor/text.c | 228 |
1 files changed, 228 insertions, 0 deletions
diff --git a/vendor/text.c b/vendor/text.c new file mode 100644 index 0000000..9a81558 --- /dev/null +++ b/vendor/text.c @@ -0,0 +1,228 @@ +/* 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 +#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 <math.h> +#include <stdint.h> +#include <stdlib.h> +#include <string.h> + +#define CACHE_ENTRIES 512 +#define CACHE_BYTES (16 * 1024 * 1024) +#define CACHE_PROPERTY "sketchbook.native-text" +static const unsigned char go_mono[] = { +#embed "fonts/Go-Mono.ttf" +}; + +typedef struct { + SDL_Texture *texture; + char *text; + size_t len, bytes; + uint64_t hash, used; + int size, width, height, left, top; + Uint32 color; +} Text; +typedef struct { + PangoFontMap *map; + PangoContext *context; + PangoLayout *layout; + PangoFontDescription *font; + FcConfig *config; + int font_fd; + Text entries[CACHE_ENTRIES]; + size_t bytes; + uint64_t frame; +} TextCache; + +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); + if (c->font) pango_font_description_free(c->font); + 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); + if (c->font_fd >= 0) close(c->font_fd); + 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; + c->font_fd = memfd_create("sketchbook-go-mono", MFD_CLOEXEC); + if (c->font_fd < 0) { free(c); return NULL; } + size_t offset = 0; + while (offset < sizeof(go_mono)) { + ssize_t n = write(c->font_fd, go_mono + offset, sizeof(go_mono) - 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); + c->config = FcInitLoadConfigAndFonts(); + if (!c->config || !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); + c->font = pango_font_description_from_string("Go Mono, Noto Sans Mono, DejaVu Sans Mono, Noto Sans Arabic, Noto Sans Hebrew, IBM Plex Sans JP, Noto Color Emoji, Noto Sans Symbols 2, DejaVu Sans, monospace"); + 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; +} + +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; + } +} + +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; +} +static bool rasterize(TextCache *c, SDL_Renderer *renderer, Text *out, + const char *bytes, size_t len, int size, Uint32 color) { + if (len > INT_MAX || !g_utf8_validate(bytes, (gssize)len, NULL)) return false; + pango_font_description_set_absolute_size(c->font, (double)size * PANGO_SCALE / 64.0); + pango_layout_set_font_description(c->layout, c->font); + pango_layout_set_text(c->layout, bytes, (int)len); + PangoRectangle ink, logical; + pango_layout_get_pixel_extents(c->layout, &ink, &logical); + 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,.color=color}; + return true; +} + +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) { + if (!len || !a) return true; + if (!isfinite(scale) || scale <= 0) return false; + TextCache *c = cache_for(renderer); + if (!c) return false; + const float dpi = density(renderer); + const int size = (int)lroundf(fminf(512, 13.0f * scale * dpi) * 64); + 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->color == color && !memcmp(t->text, utf8, len)) { entry = t; break; } + } + Text made = {0}; + if (!entry) { + if (!rasterize(c, renderer, &made, utf8, len, size, 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; + } + 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}; + 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); + } + return okay; +} |
