packages feed

nano-ui-ttf (empty) → 0.2.0.0

raw patch · 12 files changed

+2103/−0 lines, 12 filesdep +basedep +bytestringdep +containersbinary-added

Dependencies added: base, bytestring, containers, file-embed, nano-ui, primitive, text

Files

+ CHANGELOG.md view
@@ -0,0 +1,8 @@+# Changelog++## 0.2.0.0 -- 2026-12-02++Initial release.++- Extracted the shared SDL3_ttf text engine from `nano-ui-sdl` so `nano-ui-sdl` and `nano-ui-sdl-web` share line shaping, glyph atlas bookkeeping, shaped-line and font caches, and the bundled Inter font (SIL OFL 1.1 in `LICENSE-Inter`).+- Exposes internal modules (`NanoUI.Ttf.Internal.*`) for backend integration, including fallback font attachment (`attachFallback`, `openFontBytes`) and SDL error reporting.
+ LICENSE view
@@ -0,0 +1,20 @@+Copyright (c) 2026 goolord++Permission is hereby granted, free of charge, to any person obtaining+a copy of this software and associated documentation files (the+"Software"), to deal in the Software without restriction, including+without limitation the rights to use, copy, modify, merge, publish,+distribute, sublicense, and/or sell copies of the Software, and to+permit persons to whom the Software is furnished to do so, subject to+the following conditions:++The above copyright notice and this permission notice shall be included+in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ LICENSE-Inter view
@@ -0,0 +1,92 @@+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION AND CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.
+ README.md view
@@ -0,0 +1,9 @@+# nano-ui-ttf++Shared SDL3_ttf text rendering layer used internally by both [nano-ui-sdl](https://hackage.haskell.org/package/nano-ui-sdl) and [nano-ui-sdl-web](https://hackage.haskell.org/package/nano-ui-sdl-web). It handles HarfBuzz line shaping via SDL_ttf, glyph atlas packing, shaped-line and font handle caching, and embeds the default Inter font (`NanoUI.Ttf.Internal.Inter`).++Applications should not depend on `nano-ui-ttf` directly; depend on a backend package instead. All exposed modules are `Internal` and may change alongside the backends between minor releases.++Building requires SDL3, SDL3_ttf 3.2+, and `pkg-config`. The `sdl` Cabal flag is enabled by default; disabling it marks the library unbuildable so solver plans without SDL can still resolve.++Code is MIT-licensed (`LICENSE`); the bundled Inter font is under the SIL Open Font License 1.1 (`LICENSE-Inter`).
+ cbits/nano_ui_ttf.c view
@@ -0,0 +1,390 @@+#include <SDL3/SDL.h>+#include <SDL3_ttf/SDL_ttf.h>+#include <SDL3_ttf/SDL_textengine.h>+#include <stddef.h>+#include <stdbool.h>+#include <stdint.h>++#include "nano_ui_ttf_shared.h"++/* The header spells SDL_ttf's direction values out so it compiles without+ * SDL's flags; these keep them equal. */+_Static_assert(NANO_UI_DIRECTION_LTR == TTF_DIRECTION_LTR, "NANO_UI_DIRECTION_LTR is TTF_DIRECTION_LTR");+_Static_assert(NANO_UI_DIRECTION_RTL == TTF_DIRECTION_RTL, "NANO_UI_DIRECTION_RTL is TTF_DIRECTION_RTL");+_Static_assert(NANO_UI_DIRECTION_MASK == TTF_SUBSTRING_DIRECTION_MASK, "NANO_UI_DIRECTION_MASK is TTF_SUBSTRING_DIRECTION_MASK");++/* Kerning is on by default; pin it so shaping survives defaults changing.+ * Direction and script stay unset: shaping detects them per run, so+ * right-to-left and complex scripts shape as themselves. Light grid-fitting+ * snaps outlines to whole pixels only vertically and keeps each advance+ * fractional, which spaces proportional text as designed. Monospaced text+ * wants full hinting instead (nano_ui_ttf_hint_for_grid). */+static TTF_Font *pin_font_rendering(TTF_Font *font)+{+    if (font) {+        TTF_SetFontKerning(font, true);+        TTF_SetFontHinting(font, TTF_HINTING_LIGHT);+    }+    return font;+}++/* A monospaced font is set on a grid of whole-pixel cells. Full hinting runs+ * the font's own instructions and rounds each advance to a whole pixel, so+ * every glyph of a shaped run starts on a pixel and the cells are evenly+ * spaced. Light hinting keeps the fractional advance (8.25 px for Consolas at+ * 15 px), which spaces a run's glyphs 8, 8, 8, 9 apart and leaves its stems+ * between pixels. */+void nano_ui_ttf_hint_for_grid(TTF_Font *font)+{+    if (font) {+        TTF_SetFontHinting(font, TTF_HINTING_NORMAL);+    }+}++/* Half the font's line gap: how far below the top of its line box the+ * glyphs' own box starts. SDL_ttf puts the glyphs at the top of the line and+ * the whole gap under them; splitting it, as CSS does with leading, centres+ * the text in its line. */+int nano_ui_ttf_half_leading(TTF_Font *font)+{+    int gap = TTF_GetFontLineSkip(font) - TTF_GetFontHeight(font);+    return gap > 0 ? gap / 2 : 0;+}++/* Whether @face@ is a bold of @regular@'s family: the same family name, at+ * semibold or heavier, and heavier than @regular@. */+bool nano_ui_ttf_is_bold_of(TTF_Font *face, TTF_Font *regular)+{+    const char *family = TTF_GetFontFamilyName(face);+    const char *want = TTF_GetFontFamilyName(regular);+    int weight = TTF_GetFontWeight(face);+    return family && want && SDL_strcmp(family, want) == 0 &&+           weight >= TTF_FONT_WEIGHT_SEMI_BOLD && weight > TTF_GetFontWeight(regular);+}++TTF_Font *nano_ui_ttf_open_font(const char *path, float ptsize)+{+    return pin_font_rendering(TTF_OpenFont(path, ptsize));+}++/* A font at another size over the same source as @font@: the copy shares+ * its file or memory stream, so any number of sizes read one source. */+TTF_Font *nano_ui_ttf_copy_font(TTF_Font *font, float ptsize)+{+    TTF_Font *copy = font ? TTF_CopyFont(font) : NULL;+    if (copy) {+        TTF_SetFontSize(copy, ptsize);+    }+    return pin_font_rendering(copy);+}++TTF_Font *nano_ui_ttf_open_font_memory(const void *data, size_t size, float ptsize)+{+    /* The font reads this stream after the Haskell ByteString callback ends.+     * Give the stream its own storage, released by its autoclose lifetime. */+    SDL_IOStream *stream = SDL_IOFromDynamicMem();+    if (!stream) {+        return NULL;+    }+    if (SDL_WriteIO(stream, data, size) != size ||+        SDL_SeekIO(stream, 0, SDL_IO_SEEK_SET) < 0) {+        SDL_CloseIO(stream);+        return NULL;+    }+    return pin_font_rendering(TTF_OpenFontIO(stream, true, ptsize));+}++float nano_ui_ttf_space_advance(TTF_Font *font)+{+    int w = 0;+    int h = 0;+    if (TTF_GetStringSize(font, " ", 1, &w, &h) && w > 0) {+        return (float)w;+    }+    int advance = 0;+    if (TTF_GetGlyphMetrics(font, ' ', NULL, NULL, NULL, NULL, &advance) && advance > 0) {+        return (float)advance;+    }+    return 0.f;+}++static void force_white_rgb(SDL_Surface *surf)+{+    Uint8 *base = (Uint8 *)surf->pixels;+    int pitch = surf->pitch;+    for (int y = 0; y < surf->h; y++) {+#if SDL_BYTEORDER == SDL_LIL_ENDIAN+        Uint32 *row = (Uint32 *)(base + y * pitch);+        for (int x = 0; x < surf->w; x++) {+            row[x] |= 0x00FFFFFFu;+        }+#else+        Uint8 *row = base + y * pitch;+        for (int x = 0; x < surf->w; x++) {+            Uint8 *px = row + x * 4;+            px[0] = 255;+            px[1] = 255;+            px[2] = 255;+        }+#endif+    }+}++/* A glyph image as coverage: white, with the image's alpha. Text is drawn in+ * one colour, so a colour glyph (an emoji) keeps its silhouette, tinted like+ * the rest. Its alpha is zero outside the glyph, like any other image's. */+static SDL_Surface *glyph_image_to_rgba(SDL_Surface *raw)+{+    if (!raw) {+        return NULL;+    }++    SDL_Surface *out = SDL_ConvertSurface(raw, SDL_PIXELFORMAT_RGBA32);+    if (out) {+        force_white_rgb(out);+    }+    return out;+}++int nano_ui_ttf_get_kerning(TTF_Font *font, Uint32 prev_cp, Uint32 cp)+{+    if (!font) {+        return 0;+    }+    int k = 0;+    TTF_GetGlyphKerning(font, prev_cp, cp, &k);+    return k;+}++/* ------------------------------------------------------------------------ */+/* Shaping                                                                  */+/* ------------------------------------------------------------------------ */++/* One shaped line, copied out of SDL_ttf's text layout: per glyph+ * NANO_UI_SHAPED_GLYPH_INTS ints (text offset, glyph index, dst x y w h,+ * src x y w h) and its font; per cluster NANO_UI_SHAPED_CLUSTER_INTS ints+ * (byte offset, byte length, x, width, flags). Coordinates are pixels from+ * the top left of the line. nano_ui_ttf_shared.h names each int. */+typedef struct NanoUIShaped {+    int w;+    int h;+    int num_glyphs;+    int *glyphs;+    TTF_Font **glyph_fonts;+    int num_clusters;+    int *clusters;+    /* Bytes of the caller's text; anything after is the sentinel. */+    int text_len;+    /* The sentinel's character when it takes up width, else 0. */+    Uint32 sentinel_advance_cp;+} NanoUIShaped;++static bool SDLCALL nano_ui_capture_text(void *userdata, TTF_Text *text)+{+    NanoUIShaped *out = (NanoUIShaped *)userdata;+    TTF_TextData *d = text->internal;+    size_t op_cap = d->num_ops > 0 ? (size_t)d->num_ops : 1;+    size_t cluster_cap = d->num_clusters > 0 ? (size_t)d->num_clusters : 1;+    out->w = d->w;+    out->h = d->h;+    out->glyphs = (int *)SDL_malloc(op_cap * NANO_UI_SHAPED_GLYPH_INTS * sizeof(int));+    out->glyph_fonts = (TTF_Font **)SDL_malloc(op_cap * sizeof(TTF_Font *));+    out->clusters = (int *)SDL_malloc(cluster_cap * NANO_UI_SHAPED_CLUSTER_INTS * sizeof(int));+    if (!out->glyphs || !out->glyph_fonts || !out->clusters) {+        return false;+    }+    /* The sentinel ends a left-to-right line and starts a right-to-left+     * one, which then shifts back by its advance. */+    int shift = 0;+    for (int i = 0; i < d->num_clusters; i++) {+        TTF_SubString *c = &d->clusters[i];+        if (c->offset >= out->text_len && c->length > 0) {+            int advance = 0;+            if (out->sentinel_advance_cp != 0) {+                TTF_GetGlyphMetrics(d->font, out->sentinel_advance_cp, NULL, NULL, NULL, NULL, &advance);+            }+            out->w = d->w - advance;+            if ((c->flags & TTF_SUBSTRING_DIRECTION_MASK) == TTF_DIRECTION_RTL) {+                shift = advance;+            }+        }+    }+    int lead = nano_ui_ttf_half_leading(d->font);+    int g = 0;+    for (int i = 0; i < d->num_ops; i++) {+        TTF_DrawOperation *op = &d->ops[i];+        if (op->cmd != TTF_DRAW_COMMAND_COPY || op->copy.text_offset >= out->text_len) {+            continue;+        }+        int *slot = out->glyphs + g * NANO_UI_SHAPED_GLYPH_INTS;+        slot[NANO_UI_GLYPH_TEXT_OFFSET] = op->copy.text_offset;+        slot[NANO_UI_GLYPH_INDEX] = (int)op->copy.glyph_index;+        slot[NANO_UI_GLYPH_DST_X] = op->copy.dst.x - shift;+        /* SDL_ttf places a fallback font's glyphs from that font's own+         * ascent; align them to the line's font's baseline instead, which+         * sits half the line gap down. */+        slot[NANO_UI_GLYPH_DST_Y] = op->copy.dst.y - (TTF_GetFontAscent(op->copy.glyph_font) - TTF_GetFontAscent(d->font)) + lead;+        slot[NANO_UI_GLYPH_DST_W] = op->copy.dst.w;+        slot[NANO_UI_GLYPH_DST_H] = op->copy.dst.h;+        slot[NANO_UI_GLYPH_SRC_X] = op->copy.src.x;+        slot[NANO_UI_GLYPH_SRC_Y] = op->copy.src.y;+        slot[NANO_UI_GLYPH_SRC_W] = op->copy.src.w;+        slot[NANO_UI_GLYPH_SRC_H] = op->copy.src.h;+        out->glyph_fonts[g] = op->copy.glyph_font;+        g++;+    }+    out->num_glyphs = g;+    int k = 0;+    for (int i = 0; i < d->num_clusters; i++) {+        TTF_SubString *c = &d->clusters[i];+        if (c->offset >= out->text_len) {+            continue;+        }+        int *slot = out->clusters + k * NANO_UI_SHAPED_CLUSTER_INTS;+        slot[NANO_UI_CLUSTER_OFFSET] = c->offset;+        slot[NANO_UI_CLUSTER_LENGTH] = c->length;+        slot[NANO_UI_CLUSTER_X] = c->rect.x - shift;+        slot[NANO_UI_CLUSTER_WIDTH] = c->rect.w;+        slot[NANO_UI_CLUSTER_FLAGS] = (int)c->flags;+        k++;+    }+    out->num_clusters = k;+    d->engine_text = out;+    return true;+}++static void SDLCALL nano_ui_release_text(void *userdata, TTF_Text *text)+{+    (void)userdata;+    (void)text;+}++void nano_ui_ttf_shaped_free(NanoUIShaped *shaped);++/* Shape @len@ bytes of @text@ followed by @sentinel_len@ bytes of+ * @sentinel@, as 'nano_ui_ttf_shape' describes. */+static bool shape_with_sentinel(TTF_Font *font, const char *text, size_t len, const char *sentinel,+                                size_t sentinel_len, Uint32 advance_cp, int direction, NanoUIShaped *out)+{+    SDL_zerop(out);+    TTF_TextEngine engine;+    SDL_INIT_INTERFACE(&engine);+    engine.userdata = out;+    engine.CreateText = nano_ui_capture_text;+    engine.DestroyText = nano_ui_release_text;+    out->text_len = (int)len;+    out->sentinel_advance_cp = advance_cp;+    char stack_buf[256];+    const size_t padded_len = len + sentinel_len;+    char *padded = padded_len <= sizeof(stack_buf) ? stack_buf : (char *)SDL_malloc(padded_len);+    if (!padded) {+        return false;+    }+    SDL_memcpy(padded, text, len);+    SDL_memcpy(padded + len, sentinel, sentinel_len);+    TTF_Text *t = TTF_CreateText(&engine, font, padded, padded_len);+    if (padded != stack_buf) {+        SDL_free(padded);+    }+    if (!t) {+        return false;+    }+    if (direction != NANO_UI_DIRECTION_AUTO) {+        TTF_SetTextDirection(t, (TTF_Direction)direction);+    }+    /* Laying the text out hands it to the engine, which copies it. */+    int w = 0, h = 0;+    bool ok = TTF_GetTextSize(t, &w, &h);+    if (ok && out->glyphs == NULL) {+        ok = TTF_UpdateText(t) && out->glyphs != NULL;+    }+    TTF_DestroyText(t);+    return ok;+}++/* Shape one line with the font and its fallbacks, in a direction+ * (NANO_UI_DIRECTION_AUTO lets SDL_ttf pick, NANO_UI_DIRECTION_LTR or+ * NANO_UI_DIRECTION_RTL). The caller frees+ * the result with nano_ui_ttf_shaped_free.+ *+ * The line is shaped with a sentinel after it, whose glyph and cluster are+ * then dropped. SDL_ttf 3.2 cuts a fallback span that ends the text one+ * character past its last cluster, losing a vowel sign merged into that+ * cluster, and trims the width of trailing spaces. The sentinel is U+2060+ * WORD JOINER: HarfBuzz skips default-ignorable characters when it matches+ * a lookup's context, so the line shapes as though nothing followed it. A+ * visible sentinel would be context: Inter 4 turns up to five punctuation+ * marks before a '|' into their capital-height forms.+ *+ * SDL_ttf lays out nothing for a line with no visible glyph, such as one of+ * only spaces, so such a line takes a '|' instead: there is nothing in it for+ * the '|' to change. */+bool nano_ui_ttf_shape(TTF_Font *font, const char *text, size_t len, int direction, NanoUIShaped *out)+{+    if (!font || !text || len == 0) {+        SDL_zerop(out);+        return font != NULL;+    }+    if (shape_with_sentinel(font, text, len, "\xE2\x81\xA0", 3, 0, direction, out)) {+        return true;+    }+    nano_ui_ttf_shaped_free(out);+    bool bar = TTF_FontHasGlyph(font, '|');+    return shape_with_sentinel(font, text, len, "|", bar ? 1 : 0, bar ? '|' : 0, direction, out);+}++void nano_ui_ttf_shaped_free(NanoUIShaped *shaped)+{+    if (shaped) {+        SDL_free(shaped->glyphs);+        SDL_free(shaped->glyph_fonts);+        SDL_free(shaped->clusters);+        SDL_zerop(shaped);+    }+}++size_t nano_ui_ttf_shaped_size(void)+{+    return sizeof(NanoUIShaped);+}++/* Fields of a shaped line: width, height, glyph count, cluster count. */+int nano_ui_ttf_shaped_int(const NanoUIShaped *shaped, int field)+{+    switch (field) {+    case NANO_UI_SHAPED_WIDTH: return shaped->w;+    case NANO_UI_SHAPED_HEIGHT: return shaped->h;+    case NANO_UI_SHAPED_GLYPH_COUNT: return shaped->num_glyphs;+    case NANO_UI_SHAPED_CLUSTER_COUNT: return shaped->num_clusters;+    default: return 0;+    }+}++/* Arrays of a shaped line: glyphs, glyph fonts, clusters. */+void *nano_ui_ttf_shaped_ptr(const NanoUIShaped *shaped, int field)+{+    switch (field) {+    case NANO_UI_SHAPED_GLYPHS: return shaped->glyphs;+    case NANO_UI_SHAPED_GLYPH_FONTS: return (void *)shaped->glyph_fonts;+    case NANO_UI_SHAPED_CLUSTERS: return shaped->clusters;+    default: return NULL;+    }+}++bool nano_ui_ttf_render_glyph_index_surface(TTF_Font *font, Uint32 glyph_index, SDL_Surface **out_surface)+{+    if (!font || !out_surface) {+        return false;+    }+    SDL_Surface *raw = TTF_GetGlyphImageForIndex(font, glyph_index, NULL);+    if (!raw) {+        return false;+    }+    SDL_Surface *converted = glyph_image_to_rgba(raw);+    SDL_DestroySurface(raw);+    if (!converted) {+        return false;+    }+    *out_surface = converted;+    return true;+}
+ data/inter.ttf view

binary file changed (absent → 18884 bytes)

+ include/nano_ui_ttf_shared.h view
@@ -0,0 +1,184 @@+#ifndef NANO_UI_TTF_SHARED_H+#define NANO_UI_TTF_SHARED_H++/* Constants and glyph-atlas placement shared by nano-ui-ttf's shaping+ * (cbits/nano_ui_ttf.c), nano-ui-sdl's texture atlas and vertex batch+ * (nano_ui_text_atlas.c, nano_ui_render.c) and nano-ui-sdl-web's in-memory+ * atlas (nano_ui_web_atlas.c). The package installs this header, so the+ * other two include it through their dependency on nano-ui-ttf.+ *+ * NanoUI.Ttf.Internal.Header reads these values with hsc2hs. Two have a+ * Haskell twin in the core package, which cannot include C:+ * NANO_UI_VERTEX_BYTES is NanoUI.Internal.Draw.Types.vertexSize and+ * NANO_UI_GLYPH_ATLAS_PAGES is glyphAtlasPages. nano-ui-sdl-web-test checks+ * that each pair is equal.+ *+ * The header needs no SDL include, so hsc2hs compiles it without SDL's+ * flags. */++#include <stdbool.h>++/* Bytes in one vertex of the core's draw buffer: x, y, red, green, blue,+ * alpha, u, v, each a 32-bit float. SDL_Vertex has the same layout, which+ * nano_ui_render.c asserts. */+#define NANO_UI_VERTEX_BYTES 32++/* Width and height of a glyph atlas page in pixels. */+#define NANO_UI_GLYPH_ATLAS_SIZE 2048++/* Pages the atlas opens before it is out of space. */+#define NANO_UI_GLYPH_ATLAS_PAGES 4++/* Transparent pixels around each glyph, so bilinear sampling at a glyph's+ * edge reads nothing from its neighbour. */+#define NANO_UI_GLYPH_ATLAS_PAD 1++/* The opaque white square at the top left of every page, which untextured+ * shapes sample on page 0. The texel just right of it is padding, which+ * NanoUI.Ttf.Internal.Font samples for a glyph that has no slot. */+#define NANO_UI_WHITE_PATCH_SIZE 4++/* ------------------------------------------------------------------------ */+/* Shaped lines (nano_ui_ttf_shape)                                         */+/* ------------------------------------------------------------------------ */++/* The `field` argument of nano_ui_ttf_shaped_int. */+enum {+    NANO_UI_SHAPED_WIDTH = 0,+    NANO_UI_SHAPED_HEIGHT = 1,+    NANO_UI_SHAPED_GLYPH_COUNT = 2,+    NANO_UI_SHAPED_CLUSTER_COUNT = 3+};++/* The `field` argument of nano_ui_ttf_shaped_ptr. */+enum {+    NANO_UI_SHAPED_GLYPHS = 0,+    NANO_UI_SHAPED_GLYPH_FONTS = 1,+    NANO_UI_SHAPED_CLUSTERS = 2+};++/* The ints of one glyph in the NANO_UI_SHAPED_GLYPHS array, in order:+ * NANO_UI_SHAPED_GLYPH_INTS of them a glyph. dst is where the glyph image+ * lands on the line, in pixels from its top left; src is the part of the+ * glyph image to draw. */+enum {+    NANO_UI_GLYPH_TEXT_OFFSET = 0,+    NANO_UI_GLYPH_INDEX = 1,+    NANO_UI_GLYPH_DST_X = 2,+    NANO_UI_GLYPH_DST_Y = 3,+    NANO_UI_GLYPH_DST_W = 4,+    NANO_UI_GLYPH_DST_H = 5,+    NANO_UI_GLYPH_SRC_X = 6,+    NANO_UI_GLYPH_SRC_Y = 7,+    NANO_UI_GLYPH_SRC_W = 8,+    NANO_UI_GLYPH_SRC_H = 9,+    NANO_UI_SHAPED_GLYPH_INTS = 10+};++/* The ints of one cluster in the NANO_UI_SHAPED_CLUSTERS array, in order:+ * NANO_UI_SHAPED_CLUSTER_INTS of them a cluster. Offset and length are in+ * bytes of the shaped text; x and width in pixels. */+enum {+    NANO_UI_CLUSTER_OFFSET = 0,+    NANO_UI_CLUSTER_LENGTH = 1,+    NANO_UI_CLUSTER_X = 2,+    NANO_UI_CLUSTER_WIDTH = 3,+    NANO_UI_CLUSTER_FLAGS = 4,+    NANO_UI_SHAPED_CLUSTER_INTS = 5+};++/* The `direction` argument of nano_ui_ttf_shape, and a cluster's flags+ * masked with NANO_UI_DIRECTION_MASK: SDL_ttf's TTF_Direction values and+ * TTF_SUBSTRING_DIRECTION_MASK, which nano_ui_ttf.c asserts. */+enum {+    NANO_UI_DIRECTION_AUTO = 0,+    NANO_UI_DIRECTION_LTR = 4,+    NANO_UI_DIRECTION_RTL = 5+};+#define NANO_UI_DIRECTION_MASK 0xFF++/* ------------------------------------------------------------------------ */+/* Glyph atlas placement                                                    */+/* ------------------------------------------------------------------------ */++/* Where the next glyph goes. Glyphs fill page 0 in rows, then each later+ * page in turn; a glyph lands at the same UVs whichever backend stores the+ * pages. */+typedef struct NanoUiAtlasCursor {+    int pages; /* pages holding glyphs; the cursor is on the last */+    int x;+    int y;+    int row_h;+} NanoUiAtlasCursor;++/* Put the cursor on page `page`, after its white patch. */+static inline void nano_ui_atlas_cursor_open(NanoUiAtlasCursor *cur, int page)+{+    cur->pages = page + 1;+    cur->x = NANO_UI_WHITE_PATCH_SIZE + NANO_UI_GLYPH_ATLAS_PAD;+    cur->y = NANO_UI_GLYPH_ATLAS_PAD;+    cur->row_h = NANO_UI_WHITE_PATCH_SIZE;+}++/* A place for a gw by gh glyph on the current page, moving to a new row or+ * a new page when it does not fit. `open_page(atlas, page)` makes page+ * `page` ready for glyphs and calls nano_ui_atlas_cursor_open; it answers+ * false when it cannot. False when the glyph is larger than a page, or no+ * page is left with room. */+static inline bool nano_ui_atlas_slot_for(+    NanoUiAtlasCursor *cur,+    void *atlas,+    bool (*open_page)(void *atlas, int page),+    int gw,+    int gh,+    int *out_page,+    int *out_x,+    int *out_y)+{+    const int pad = NANO_UI_GLYPH_ATLAS_PAD;+    const int size = NANO_UI_GLYPH_ATLAS_SIZE;+    if (gw + 2 * pad > size || gh + 2 * pad > size) {+        return false;+    }+    if (cur->pages == 0 && !open_page(atlas, 0)) {+        return false;+    }+    for (;;) {+        if (cur->x + gw + pad <= size && cur->y + gh + pad <= size) {+            break;+        }+        int next_y = cur->y + (cur->row_h > 0 ? cur->row_h + pad : pad);+        if (next_y + gh + pad <= size) {+            cur->y = next_y;+            cur->x = pad;+            cur->row_h = 0;+            break;+        }+        if (cur->pages >= NANO_UI_GLYPH_ATLAS_PAGES || !open_page(atlas, cur->pages)) {+            return false;+        }+    }+    *out_page = cur->pages - 1;+    *out_x = cur->x;+    *out_y = cur->y;+    return true;+}++/* Move the cursor past a gw by gh glyph copied to (x, y) on page `page`,+ * and write its u0, v0, u1 and v1: normalised to [0,1] within the page,+ * plus the page's number in u. */+static inline void nano_ui_atlas_commit(+    NanoUiAtlasCursor *cur, int page, int x, int y, int gw, int gh, float uv[4])+{+    cur->x = x + gw + NANO_UI_GLYPH_ATLAS_PAD;+    if (gh > cur->row_h) {+        cur->row_h = gh;+    }+    float s = (float)NANO_UI_GLYPH_ATLAS_SIZE;+    uv[0] = (float)page + (float)x / s;+    uv[1] = (float)y / s;+    uv[2] = uv[0] + (float)gw / s;+    uv[3] = uv[1] + (float)gh / s;+}++#endif
+ lib/NanoUI/Ttf/Internal/Font.hs view
@@ -0,0 +1,1037 @@+{-# LANGUAGE CApiFFI #-}+{-# LANGUAGE RecordWildCards #-}++-- | Shared SDL3_ttf font handles, shaping, measurement snapshots, and glyph+-- atlas caching. Parameterized over backend-specific atlas operations+-- ('AtlasOps') and optional platform hooks ('FontHooks') so both desktop SDL+-- and browser WebGL backends share one implementation.+--+-- The names 'SdlFont', 'SdlFontCache' and the @sf@ and @sfc@ field prefixes+-- date from when this code lived in nano-ui-sdl. Nothing here depends on an+-- SDL window or renderer: "SDL" names SDL3_ttf, which both nano-ui-sdl and+-- nano-ui-sdl-web shape and rasterise text with. The names are public API+-- of both backends' internal modules, so they stay.+module NanoUI.Ttf.Internal.Font+  ( AtlasOps (..)+  , FontHooks (..)+  , defaultFontHooks+  , SdlFont (..)+  , FontSource (..)+  , fontSourceLabel+  , embeddedFontSource+  , GlyphSlot (..)+  , GlyphAtlas (..)+  , glyphAtlasSize+  , newGlyphAtlas+  , destroyGlyphAtlas+  , glyphAtlasFull+  , glyphAtlasHandle+  , SdlFontCache (..)+  , newSdlFontCache+  , destroySdlFontCache+  , reloadSdlFontCache+  , prepareGlyphAtlasForFrame+  , beginTtfFrame+  , ttfFrameDropped+  , closeEvictedFonts+  , sdlFontCacheSource+  , sdlFontCacheMonoSource+  , withSdlFontCache+  , withTtf+  , openFontPath+  , openFontBytes+  , readSdlFont+  , attachFallback+  , closeFont+  , ttfOpenFont+  , ttfCloseFont+  , ttfHasGlyph+  , ttfAddFallback+  , ttfRemoveFallback+  , ttfCopyFont+  , ttfIsBoldOf+  ) where++import Control.Exception (IOException, bracket_, catch, finally, onException, throwIO)+import Control.Monad (foldM_, forM_, unless, when, zipWithM_)+import Control.Monad.Primitive (RealWorld)+import Data.Bits ((.&.))+import Data.ByteString (ByteString)+import Data.ByteString.Unsafe (unsafeUseAsCStringLen)+import Data.Char (isSpace, ord)+import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef)+import Data.Int (Int32)+import Data.IntMap.Strict qualified as IM+import Data.IntSet qualified as IS+import Data.List (delete, elemIndex)+import Data.Maybe (isJust, mapMaybe)+import Data.Primitive.PrimArray+  ( MutablePrimArray+  , PrimArray+  , indexPrimArray+  , newPrimArray+  , primArrayFromList+  , readPrimArray+  , setPrimArray+  , sizeofPrimArray+  , unsafeFreezePrimArray+  , writePrimArray+  )+import Data.Primitive.PrimVar (PrimVar, newPrimVar, readPrimVar, writePrimVar)+import Data.Primitive.SmallArray (SmallArray, indexSmallArray, smallArrayFromList)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Foreign qualified as TF+import Data.Text.Internal.Encoding.Utf8 (utf8Length)+import Data.Text.Unsafe (lengthWord8)+import Data.Unique (hashUnique, newUnique)+import Foreign.C.String (CString)+import Foreign.C.Types (CBool (..), CFloat (..), CInt (..), CSize (..), CUInt (..))+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Marshal.Array (advancePtr, allocaArray)+import Foreign.Marshal.Utils (fillBytes, with)+import Foreign.Ptr (Ptr, castPtr, nullPtr, plusPtr)+import Foreign.Storable (peek, peekElemOff)+import GHC.Foreign qualified as GHC+import GHC.IO.Encoding (TextEncoding, utf8)+import NanoUI (FontStyle (..), FontVariant (..), FontWeight (..), unlessM, whenM)+import NanoUI.Backend+import NanoUI.Bidi (BidiRun (..), bidiRuns, needsBidi)+import NanoUI.Internal.Context.Types (GenCache, cachedGen, emptyGenCache)+import NanoUI.Ttf.Internal.Header+  ( clusterFlags+  , clusterLength+  , clusterOffset+  , clusterWidth+  , clusterX+  , directionAuto+  , directionLtr+  , directionMask+  , directionRtl+  , glyphAtlasPixels+  , glyphDstH+  , glyphDstW+  , glyphDstX+  , glyphDstY+  , glyphIndex+  , glyphSrcH+  , glyphSrcW+  , glyphSrcX+  , glyphSrcY+  , shapedClusterCount+  , shapedClusterInts+  , shapedClusters+  , shapedGlyphCount+  , shapedGlyphFonts+  , shapedGlyphInts+  , shapedGlyphs+  , shapedHeight+  , shapedWidth+  , whitePatchSize+  )+import NanoUI.Ttf.Internal.Inter (fontInterBytes, fontInterLabel)++-- | Native glyph-atlas operations supplied by the concrete backend (SDL+-- renderer textures on desktop, CPU pixel pages for WebGL upload on web).+data AtlasOps = AtlasOps+  { aoHandle :: !(Ptr ())+  , aoDestroy :: !(IO ())+  , aoReset :: !(IO ())+  , aoInsertSurface :: !(Ptr () -> Ptr CFloat -> IO CBool)+  }++-- | Optional platform hooks for desktop font discovery and path encoding.+data FontHooks = FontHooks+  { fhEnsureCoverage :: !(SdlFont -> Text -> IO ())+  -- ^ Attach fallback fonts covering missing glyphs before shaping.+  , fhBoldSource :: !(FontSource -> IO (Ptr ()) -> IO (Maybe FontSource))+  -- ^ Discover a native bold face beside a regular font file, if available.+  , fhPathEncoding :: !(IO TextEncoding)+  -- ^ Encoding used for font file paths passed to SDL_ttf.+  , fhOnTtfQuit :: !(IO ())+  -- ^ Cleanup action run before @TTF_Quit@ (e.g. closing coverage probes).+  }++-- | Hooks with no system font search, no bold-face lookup, and UTF-8 paths.+defaultFontHooks :: FontHooks+defaultFontHooks =+  FontHooks+    { fhEnsureCoverage = \_ _ -> pure ()+    , fhBoldSource = \_ _ -> pure Nothing+    , fhPathEncoding = pure utf8+    , fhOnTtfQuit = pure ()+    }++-- | An open SDL3_ttf font handle with its cached metrics and attached fallbacks.+data SdlFont = SdlFont+  { sfId :: !Int+  , sfFont :: !(Ptr ())+  , sfLineSkip :: !Float+  , sfAscent :: !Float+  , sfSpaceAdvance :: !Float+  , sfAlive :: !(IORef Bool)+  , sfPointSize :: !Float+  -- ^ The size the font was opened at, which its fallbacks open at too.+  , sfFallbacks :: !(IORef (IM.IntMap SdlFont))+  -- ^ Fallback fonts attached to this face, indexed by source slot.+  }++-- | Where a font face is loaded from.+data FontSource+  = FontFromPath !FilePath+  | FontFromMemory !ByteString !FilePath+  deriving (Eq, Show)++-- | Human-readable label for a 'FontSource'.+fontSourceLabel :: FontSource -> FilePath+fontSourceLabel (FontFromPath p) = p+fontSourceLabel (FontFromMemory _ label) = label++-- | Bundled Inter, which a font that will not open falls back to.+embeddedFontSource :: FontSource+embeddedFontSource = FontFromMemory fontInterBytes fontInterLabel++-- | Per-glyph atlas slot. UVs are normalised to [0,1] within the page, plus+-- the page's number in u, as 'ShapedGlyphs' carries them.+data GlyphSlot = GlyphSlot+  { gsU0 :: {-# UNPACK #-} !Float+  , gsV0 :: {-# UNPACK #-} !Float+  , gsU1 :: {-# UNPACK #-} !Float+  , gsV1 :: {-# UNPACK #-} !Float+  }++-- | Shared glyph atlas bookkeeping over backend 'AtlasOps'.+data GlyphAtlas = GlyphAtlas+  { gaOps :: !AtlasOps+  , gaEpoch :: !(IORef Int)+  , -- | An insertion failed (every page out of space) since the last reset.+    -- The atlas is reset at the next frame start, before any quad is recorded.+    gaFull :: !(IORef Bool)+  , -- | Glyph slots by font id, then glyph index: what shaped text draws.+    gaIndexEntries :: !(IORef (IM.IntMap (IM.IntMap (Maybe GlyphSlot))))+  , -- | Frames begun ('prepareGlyphAtlasForFrame'), by which the text caches+    -- count what a frame looks up ('RunCache').+    gaFrame :: !(IORef Int)+  }++-- | Wrap backend 'AtlasOps' in a 'GlyphAtlas'.+newGlyphAtlas :: AtlasOps -> IO GlyphAtlas+newGlyphAtlas ops =+  GlyphAtlas ops <$> newIORef 0 <*> newIORef False <*> newIORef IM.empty <*> newIORef 0++-- | Destroy the underlying native glyph atlas.+destroyGlyphAtlas :: GlyphAtlas -> IO ()+destroyGlyphAtlas = aoDestroy . gaOps++-- | Whether a glyph could not be placed since the atlas was last reset.+glyphAtlasFull :: SdlFontCache -> IO Bool+glyphAtlasFull = readIORef . gaFull . sfcGlyphAtlas++-- | The glyph atlas's native handle.+glyphAtlasHandle :: SdlFontCache -> Ptr ()+glyphAtlasHandle = aoHandle . gaOps . sfcGlyphAtlas++ensureAlive :: SdlFont -> IO ()+ensureAlive sf = unlessM (readIORef (sfAlive sf)) (fail "font backend used after closeFont")++runCacheCap :: Int+runCacheCap = 1024++data RunCache v = RunCache+  { rcGens :: !(IORef (GenCache Text v))+  , rcFrame :: !(PrimVar RealWorld Int)+  , rcLooked :: !(PrimVar RealWorld Int)+  , rcCap :: !(PrimVar RealWorld Int)+  }++newRunCache :: IO (RunCache v)+newRunCache = RunCache <$> newIORef emptyGenCache <*> newPrimVar 0 <*> newPrimVar 0 <*> newPrimVar runCacheCap++{-# INLINE cachedRun #-}+cachedRun :: GlyphAtlas -> RunCache v -> Text -> IO v -> IO v+cachedRun ga RunCache {..} txt make = do+  frame <- readIORef (gaFrame ga)+  counted <- readPrimVar rcFrame+  looked <- readPrimVar rcLooked+  let !w = textWeight txt+  if frame == counted+    then writePrimVar rcLooked (looked + w)+    else do+      writePrimVar rcFrame frame+      writePrimVar rcLooked w+      writePrimVar rcCap (max runCacheCap (2 * looked))+  cap <- readPrimVar rcCap+  cachedGen cap textWeight rcGens txt make++textWeight :: Text -> Int+textWeight txt = 1 + lengthWord8 txt `quot` 4096++-- | A glyph's native measurements in unscaled pixels: min x, max x, min y, max y, advance.+data GlyphMetrics = GlyphMetrics !Float !Float !Float !Float !Float++getGlyphMetrics :: SdlFont -> Int -> IO (Maybe GlyphMetrics)+getGlyphMetrics sf cp = allocaArray 5 $ \p -> do+  let at = advancePtr p+      metric i = fromIntegral <$> peekElemOff p i+  ok <- ttfGlyphMetrics (sfFont sf) (fromIntegral cp) p (at 1) (at 2) (at 3) (at 4)+  if ok+    then Just <$> (GlyphMetrics <$> metric 0 <*> metric 1 <*> metric 2 <*> metric 3 <*> metric 4)+    else pure Nothing++metricsGlyphQuad :: SdlFont -> Float -> GlyphMetrics -> GlyphQuad+metricsGlyphQuad sf inv (GlyphMetrics minX maxX minY maxY _) =+  GlyphQuad+    (minX / inv)+    ((sfAscent sf - maxY) / inv)+    ((maxX - minX) / inv)+    ((maxY - minY) / inv)+    0+    0+    0+    0++lookupOrInsertGlyph :: GlyphAtlas -> SdlFont -> Int -> IO (Maybe GlyphSlot)+lookupOrInsertGlyph ga font gi = do+  entries <- readIORef (gaIndexEntries ga)+  case IM.lookup (sfId font) entries >>= IM.lookup gi of+    Just mSlot -> pure mSlot+    Nothing -> do+      mSlot <- placeGlyphImage ga font gi+      modifyIORef' (gaIndexEntries ga) (IM.insertWith IM.union (sfId font) (IM.singleton gi mSlot))+      pure mSlot++placeGlyphImage :: GlyphAtlas -> SdlFont -> Int -> IO (Maybe GlyphSlot)+placeGlyphImage ga font gi = do+  surf <- with nullPtr $ \sp -> ttfRenderGlyphIndexSurface (sfFont font) (fromIntegral gi) sp >> peek sp+  if surf == nullPtr+    then pure Nothing+    else allocaArray 4 $ \uv -> do+      placed <- aoInsertSurface (gaOps ga) surf uv+      sdlDestroySurface surf+      if placed == 0+        then Nothing <$ writeIORef (gaFull ga) True+        else do+          u0 <- realToFrac <$> peekElemOff uv 0+          v0 <- realToFrac <$> peekElemOff uv 1+          u1 <- realToFrac <$> peekElemOff uv 2+          v1 <- realToFrac <$> peekElemOff uv 3+          pure (Just (GlyphSlot u0 v0 u1 v1))++-- | Width and height of the glyph atlas texture: NANO_UI_GLYPH_ATLAS_SIZE.+glyphAtlasSize :: Float+glyphAtlasSize = fromIntegral glyphAtlasPixels++-- | The UVs of a texel no glyph or shape covers, for a glyph with no slot:+-- the padding column just right of page 0's white patch, on its bottom row.+deadU, deadV :: Float+deadU = (fromIntegral whitePatchSize + 0.5) / glyphAtlasSize+deadV = (glyphAtlasSize - 0.5) / glyphAtlasSize++data Shaped = Shaped+  { shapedText :: !ShapedText+  , shapedSize :: !(Float, Float)+  , _shapedGlyphs :: !(PrimArray Int32)+  -- ^ 'glyphRecordInts' ints a glyph: the C side's glyph from 'glyphIndex'+  -- on, its x moved right by the pen of the piece it was shaped in.+  , _shapedFontIndices :: !(PrimArray Int32)+  , _shapedFonts :: !(SmallArray SdlFont)+  }++-- | Ints a glyph takes in '_shapedGlyphs': the C side's glyph without its+-- text offset, which nothing after shaping reads.+glyphRecordInts :: Int+glyphRecordInts = shapedGlyphInts - glyphIndex++-- | Where an int of the C side's glyph ('glyphDstX' and the rest) is in a+-- glyph record of '_shapedGlyphs'.+recordField :: Int -> Int+recordField k = k - glyphIndex++-- | The runs of a line to shape apart, as start and end characters and the+-- direction to shape in. Text that needs no bidi runs ('needsBidi') is one+-- run, whose direction SDL_ttf picks. A right-to-left run is shaped right+-- to left without its leading and trailing spaces, which shape left to+-- right.+shapingRuns :: Text -> [(Int, Int, CInt)]+shapingRuns txt+  | needsBidi txt = concatMap directed (bidiRuns txt)+  | otherwise = [(0, T.length txt, auto)]+  where+    auto = fromIntegral directionAuto+    ltr = fromIntegral directionLtr+    rtl = fromIntegral directionRtl+    directed r+      | not (runRightToLeft r) = [(runStart r, runEnd r, ltr)]+      | otherwise =+          let run = T.take (runEnd r - runStart r) (T.drop (runStart r) txt)+              lead = T.length (T.takeWhile isSpace run)+              trail = T.length (T.takeWhileEnd isSpace run)+              coreStart = runStart r + lead+              coreEnd = runEnd r - trail+           in if coreStart >= coreEnd+                then [(runStart r, runEnd r, ltr)]+                else+                  [(coreEnd, runEnd r, ltr) | trail > 0]+                    ++ [(coreStart, coreEnd, rtl)]+                    ++ [(runStart r, coreStart, ltr) | lead > 0]++-- | Shape a line run by run ('shapingRuns'), each run after the last, into+-- its glyphs ('copyShapedGlyphs'), the x of every caret position+-- ('placeClusters', 'fillCarets'), its size and the right edge of its ink.+-- Sizes are in layout units: device pixels divided by @inv@.+shapeLine :: SdlFont -> Float -> Text -> IO Shaped+shapeLine sf inv txt = do+  ensureAlive sf+  fallbacks <- IM.elems <$> readIORef (sfFallbacks sf)+  let fontList = sf : fallbacks+      fontPtrs = map sfFont fontList+      fontIndex ptr = maybe 0 fromIntegral (elemIndex ptr fontPtrs)+      n = T.length txt+      totalBytes = lengthWord8 txt+      runs = shapingRuns txt+      pieceCount = length runs+      ascii = totalBytes == n+  charOfByte <- newPrimArray (if ascii then 0 else totalBytes + 1)+  let charAt b = if ascii then pure (min n b) else readPrimArray charOfByte (min totalBytes b)+      indexChars !i !b t = case T.uncons t of+        Nothing -> pure ()+        Just (c, rest) -> do+          writePrimArray charOfByte b i+          indexChars (i + 1) (b + utf8Length c) rest+  unless ascii $ do+    setPrimArray charOfByte 0 (totalBytes + 1) n+    indexChars 0 0 txt+  size <- fromIntegral <$> ttfShapedSize+  let totalBuf = size * max 1 pieceCount+  allocaBytes totalBuf $ \outs -> do+    fillBytes outs 0 totalBuf+    let resultOf p = outs `plusPtr` (p * size)+        freeAll = forM_ [0 .. pieceCount - 1] (ttfShapedFree . resultOf)+    flip finally freeAll $ do+      forM_ (zip [0 ..] runs) $ \(p, (start, end, dir)) ->+        TF.useAsPtr (T.take (end - start) (T.drop start txt)) $ \ptr len -> do+          ok <- ttfShape (sfFont sf) (castPtr ptr) (fromIntegral len) dir (resultOf p)+          when (ok == 0) $ ttfShapedFree (resultOf p)+      glyphCount <- sum <$> mapM (\p -> shapedInt (resultOf p) shapedGlyphCount) [0 .. pieceCount - 1]+      glyphs <- newPrimArray (glyphCount * glyphRecordInts)+      fontIndices <- newPrimArray glyphCount+      stops <- newPrimArray n+      setPrimArray stops 0 n (0 / 0 :: Float)+      let fillPieces !p !pen !height !g0 !inkEnd !endStop pieces = case pieces of+            [] -> pure (pen, height, inkEnd, endStop)+            (start, _, _) : rest -> do+              let result = resultOf p+                  byteStart = if ascii then start else lengthWord8 (T.take start txt)+              w <- shapedInt result shapedWidth+              h <- shapedInt result shapedHeight+              nGlyphs <- shapedInt result shapedGlyphCount+              nClusters <- shapedInt result shapedClusterCount+              glyphPtr <- castPtr <$> ttfShapedPtr result (fromIntegral shapedGlyphs)+              fontPtr <- castPtr <$> ttfShapedPtr result (fromIntegral shapedGlyphFonts)+              clusterPtr <- castPtr <$> ttfShapedPtr result (fromIntegral shapedClusters)+              ink <-+                if glyphPtr == nullPtr+                  then pure inkEnd+                  else copyShapedGlyphs glyphs fontIndices fontIndex glyphPtr fontPtr nGlyphs g0 pen inkEnd+              end <-+                if clusterPtr == nullPtr+                  then pure endStop+                  else placeClusters stops charAt n clusterPtr nClusters byteStart pen endStop+              ttfShapedFree result+              fillPieces (p + 1) (pen + w) (max height h) (g0 + nGlyphs) ink end rest+      (total, height, inkEnd, endStop) <- fillPieces 0 0 (0 :: Int) 0 0 (0 / 0) runs+      caretArr <- fillCarets stops n inv (if isNaN endStop then fromIntegral total else endStop)+      glyphArr <- unsafeFreezePrimArray glyphs+      indexArr <- unsafeFreezePrimArray fontIndices+      let !width = fromIntegral total / inv+          !measured = (width, fromIntegral height / inv)+      pure (Shaped (ShapedText width (fromIntegral inkEnd / inv) caretArr) measured glyphArr indexArr (smallArrayFromList fontList))++-- | A field of a shaped line ('shapedWidth' and the rest).+{-# INLINE shapedInt #-}+shapedInt :: Ptr () -> Int -> IO Int+shapedInt result field = fromIntegral <$> ttfShapedInt result (fromIntegral field)++-- | Copy a shaped piece's @nGlyphs@ glyphs into the line's glyph records+-- from record @g0@ on, moving each right by the piece's @pen@, and note+-- each glyph's font as its index among the line's fonts. Answers the right+-- edge of the line's ink so far, from @ink0@.+{-# INLINE copyShapedGlyphs #-}+copyShapedGlyphs ::+  MutablePrimArray RealWorld Int32 ->+  MutablePrimArray RealWorld Int32 ->+  (Ptr () -> Int32) ->+  Ptr CInt ->+  Ptr (Ptr ()) ->+  Int ->+  Int ->+  Int ->+  Int ->+  IO Int+copyShapedGlyphs glyphs fontIndices fontIndex glyphPtr fontPtr nGlyphs g0 pen = go 0+  where+    go !i !ink+      | i >= nGlyphs = pure ink+      | otherwise = do+          let src = i * shapedGlyphInts+              dst = (g0 + i) * glyphRecordInts+          forM_ [glyphIndex .. shapedGlyphInts - 1] $ \k -> do+            v <- fromIntegral <$> peekElemOff glyphPtr (src + k)+            writePrimArray glyphs (dst + recordField k) (if k == glyphDstX then v + fromIntegral pen else v)+          x1 <- readPrimArray glyphs (dst + recordField glyphDstX)+          gw <- readPrimArray glyphs (dst + recordField glyphDstW)+          ptr <- peekElemOff fontPtr i+          writePrimArray fontIndices (g0 + i) (fontIndex ptr)+          go (i + 1) (max ink (fromIntegral (x1 + gw) :: Int))++-- | Write the caret x of each character a shaped piece's @nClusters@+-- clusters cover into @stops@, by character index: a cluster's width split+-- evenly between its characters, right to left in a right-to-left cluster.+-- @byteStart@ is the piece's first byte in the line, @pen@ its x, and+-- @charAt@ the character a byte of the line starts. Answers the x where the+-- line's last character ends once a cluster reaches it, else @end0@.+{-# INLINE placeClusters #-}+placeClusters ::+  MutablePrimArray RealWorld Float ->+  (Int -> IO Int) ->+  Int ->+  Ptr CInt ->+  Int ->+  Int ->+  Int ->+  Float ->+  IO Float+placeClusters stops charAt n clusterPtr nClusters byteStart pen = go 0+  where+    clusterInt :: Int -> Int -> IO Int+    clusterInt i k = fromIntegral <$> peekElemOff clusterPtr (i * shapedClusterInts + k)+    go !i !end+      | i >= nClusters = pure end+      | otherwise = do+          len <- clusterInt i clusterLength+          if len <= 0+            then go (i + 1) end+            else do+              off0 <- clusterInt i clusterOffset+              x0 <- clusterInt i clusterX+              cw <- clusterInt i clusterWidth+              flags <- clusterInt i clusterFlags+              let off = off0 + byteStart+                  x = fromIntegral (x0 + pen) :: Float+                  fw = fromIntegral cw+                  rtl = flags .&. directionMask == directionRtl+              c0 <- charAt off+              c1 <- charAt (off + len)+              let k = max 1 (c1 - c0)+                  stop j+                    | c0 + j >= n = pure ()+                    | rtl = writePrimArray stops (c0 + j) (x + fw - fw * fromIntegral j / fromIntegral k)+                    | otherwise = writePrimArray stops (c0 + j) (x + fw * fromIntegral j / fromIntegral k)+              forM_ [0 .. k - 1] stop+              let end'+                    | isNaN end && c1 == n = if rtl then x else x + fw+                    | otherwise = end+              go (i + 1) end'++-- | The caret x before each of the line's @n@ characters and after the last+-- (@endStop@), in layout units. A character no cluster placed (@NaN@ in+-- @stops@) takes the caret before it.+fillCarets :: MutablePrimArray RealWorld Float -> Int -> Float -> Float -> IO (PrimArray Float)+fillCarets stops n inv endStop = do+  carets <- newPrimArray (n + 1)+  let fillCaret prev i = do+        v <- readPrimArray stops i+        let v' = if isNaN v then prev else v / inv+        v' <$ writePrimArray carets i v'+  foldM_ fillCaret 0 [0 .. n - 1]+  writePrimArray carets n (endStop / inv)+  unsafeFreezePrimArray carets++placeShapedGlyphs :: GlyphAtlas -> Float -> Shaped -> IO ShapedGlyphs+placeShapedGlyphs ga inv (Shaped _ _ glyphs fontIndices fonts) = do+  let !count = sizeofPrimArray fontIndices+  out <- newPrimArray (count * 8)+  forM_ [0 .. count - 1] $ \i -> do+    let field k = indexPrimArray glyphs (i * glyphRecordInts + recordField k)+        g k = fromIntegral (field k) :: Float+        write k = writePrimArray out (i * 8 + k)+        font = indexSmallArray fonts (fromIntegral (indexPrimArray fontIndices i))+    mSlot <- lookupOrInsertGlyph ga font (fromIntegral (field glyphIndex))+    -- The quad: x, y, width and height, then u0, v0, u1 and v1.+    write 0 (g glyphDstX / inv)+    write 1 (g glyphDstY / inv)+    write 2 (g glyphDstW / inv)+    write 3 (g glyphDstH / inv)+    case mSlot of+      Just slot -> do+        let u0 = gsU0 slot + g glyphSrcX / glyphAtlasSize+            v0 = gsV0 slot + g glyphSrcY / glyphAtlasSize+        write 4 u0+        write 5 v0+        write 6 (if g glyphSrcW > 0 then u0 + g glyphSrcW / glyphAtlasSize else gsU1 slot)+        write 7 (if g glyphSrcH > 0 then v0 + g glyphSrcH / glyphAtlasSize else gsV1 slot)+      Nothing -> zipWithM_ write [4 ..] [deadU, deadV, deadU, deadV]+  ShapedGlyphs <$> unsafeFreezePrimArray out++{-# NOINLINE buildGlyphFontMetrics #-}+buildGlyphFontMetrics :: FontHooks -> GlyphAtlas -> SdlFont -> Float -> IO (FontMetrics, Text -> IO (Float, Float))+buildGlyphFontMetrics hooks ga sf scale = do+  let !inv = if scale > 0 then scale else 1+      !spaceAdvance = sfSpaceAdvance sf / inv+      advanceOf = maybe spaceAdvance (\(GlyphMetrics _ _ _ _ adv) -> adv / inv)++  asciiMetrics <- mapM (getGlyphMetrics sf) [0 .. 127]+  let !asciiGeometry = smallArrayFromList (map (fmap (metricsGlyphQuad sf inv)) asciiMetrics)+      !asciiAdvances = primArrayFromList (map advanceOf asciiMetrics)+  rawKernXM <- ttfGetKerning (sfFont sf) (fromIntegral (ord 'x')) (fromIntegral (ord 'M'))+  let !kernXM = fromIntegral rawKernXM / inv++  preparedRun <- newRunCache+  shapedRun <- newRunCache+  quadRun <- newRunCache+  quadEpochRef <- newIORef =<< readIORef (gaEpoch ga)++  let+    {-# NOINLINE shapedLookup #-}+    shapedLookup !txt+      | T.null txt = pure Nothing+      | otherwise = do+          ensureAlive sf+          ep <- readIORef (gaEpoch ga)+          quadEp <- readIORef quadEpochRef+          when (quadEp /= ep) $ do+            writeIORef quadEpochRef ep+            writeIORef (rcGens quadRun) emptyGenCache+          cachedRun ga quadRun txt $+            Just <$> (placeShapedGlyphs ga inv =<< shapeOf txt)++    shapeOf !txt =+      cachedRun ga shapedRun txt $ do+        fhEnsureCoverage hooks sf txt+        shapeLine sf inv txt++    measure !txt+      | T.null txt = pure emptySize+      | otherwise = shapedSize <$> shapeOf txt+    !emptySize = (0, sfLineSkip sf / inv)++    backend = FontBackend prepareText shapedLookup++    prepareText txt = do+      ensureAlive sf+      cachedRun ga preparedRun txt $ do+        advances <-+          if T.isAscii txt+            then pure IM.empty+            else do+              let insertNonAscii m c+                    | ord c < 128 = m+                    | otherwise = IM.insert (ord c) c m+                  others = T.foldl' insertNonAscii IM.empty txt+              IM.map advanceOf <$> traverse (getGlyphMetrics sf . ord) others+        shaped <- if T.null txt then pure Nothing else Just <$> shapeOf txt+        let !layout = fmap shapedText shaped+        pure $!+          (monospaceMetrics (sfLineSkip sf / inv))+            { fmAscent = sfAscent sf / inv+            , fmAdvance = \c ->+                let cp = ord c+                 in if cp < 128+                      then indexPrimArray asciiAdvances cp+                      else IM.findWithDefault spaceAdvance cp advances+            , fmKerning = \a b -> if a == 'x' && b == 'M' then kernXM else 0+            , fmGlyph = \c ->+                let cp = ord c+                 in if cp < 128 then indexSmallArray asciiGeometry cp else Nothing+            , fmShape = \t -> if t == txt then layout else Nothing+            , fmBackend = Just backend+            , fmSnapScale = inv+            }++  fm <- prepareText ""+  pure (fm, measure)++-- | Bracket an action with @TTF_Init@ and @TTF_Quit@, running 'fhOnTtfQuit'+-- before shutting down SDL_ttf.+withTtf :: FontHooks -> IO a -> IO a+withTtf hooks =+  bracket_+    (unlessM ttfInit (ttfFail "TTF_Init failed"))+    (fhOnTtfQuit hooks >> ttfQuit)++-- | Open a font at a point size, or bundled Inter when it will not open.+openFontSource :: FontHooks -> Bool -> FontSource -> Float -> IO (FontSource, SdlFont)+openFontSource hooks grid source ptsize =+  open source `catch` \(e :: IOException) ->+    if source == embeddedFontSource+      then throwIO e+      else open embeddedFontSource `catch` \(_ :: IOException) -> throwIO e+  where+    pt = realToFrac ptsize+    open src = do+      font <- case src of+        FontFromPath path -> openFontPath hooks path pt+        FontFromMemory bs _ ->+          unsafeUseAsCStringLen bs $ \(ptr, len) -> ttfOpenFontMemory (castPtr ptr) (fromIntegral len) pt+      when (font == nullPtr) $ ttfFail ("TTF_OpenFont failed for " ++ fontSourceLabel src)+      when grid (ttfHintForGrid font)+      (src,) <$> readSdlFont ptsize font++-- | Throw an 'IOError' for a failed SDL_ttf call, with SDL's last error+-- message appended when there is one.+ttfFail :: String -> IO a+ttfFail what = do+  p <- sdlGetError+  err <- if p == nullPtr then pure "" else GHC.peekCString utf8 p+  ioError (userError (if null err then what else what ++ ": " ++ err))++-- | Open a font file at a point size using the configured path encoding.+openFontPath :: FontHooks -> FilePath -> CFloat -> IO (Ptr ())+openFontPath hooks path pt = fhPathEncoding hooks >>= \enc -> GHC.withCString enc path (`ttfOpenFont` pt)++-- | Open a font file's bytes at a point size; null when they will not open.+-- SDL_ttf reads the bytes while the font is open, and from fonts copied+-- from it ('ttfCopyFont'), so the caller keeps the 'ByteString' alive as+-- long as any of them.+openFontBytes :: ByteString -> CFloat -> IO (Ptr ())+openFontBytes bs pt = unsafeUseAsCStringLen bs $ \(ptr, len) -> ttfOpenFontMemory (castPtr ptr) (fromIntegral len) pt++-- | Attach a fallback to a face for the characters it lacks: a copy of+-- @probe@ (an open font of the fallback, at any size) at the face's size,+-- keyed by @source@ so a source is attached once. SDL_ttf tries the+-- fallbacks in the order they were added, so all are re-added in source+-- order.+attachFallback :: SdlFont -> Int -> Ptr () -> IO ()+attachFallback sf source probe = do+  attached <- readIORef (sfFallbacks sf)+  unless (IM.member source attached) $ do+    copy <- ttfCopyFont probe (realToFrac (sfPointSize sf))+    unless (copy == nullPtr) $ do+      fallback <- readSdlFont (sfPointSize sf) copy+      let attached' = IM.insert source fallback attached+      forM_ attached $ \f -> ttfRemoveFallback (sfFont sf) (sfFont f)+      forM_ attached' $ \f -> ttfAddFallback (sfFont sf) (sfFont f)+      writeIORef (sfFallbacks sf) attached'++-- | Wrap an open TTF font handle.+readSdlFont :: Float -> Ptr () -> IO SdlFont+readSdlFont sfPointSize sfFont = do+  sfId <- hashUnique <$> newUnique+  sfAlive <- newIORef True+  sfFallbacks <- newIORef IM.empty+  sfLineSkip <- fromIntegral <$> ttfLineSkip sfFont+  sfAscent <- fromIntegral <$> ((+) <$> ttfAscent sfFont <*> ttfHalfLeading sfFont)+  sfSpaceAdvance <- realToFrac <$> ttfSpaceAdvance sfFont+  pure SdlFont {..}++-- | Close a font handle and all of its attached fallbacks.+closeFont :: SdlFont -> IO ()+closeFont sf = do+  whenM (atomicModifyIORef' (sfAlive sf) (False,)) $ do+    ttfCloseFont (sfFont sf)+    readIORef (sfFallbacks sf) >>= mapM_ closeFont++-- ---------------------------------------------------------------------------+-- Font cache++data CachedFontEntry = CachedFontEntry+  { cfeFont :: !SdlFont+  , cfeFm :: !FontMetrics+  , cfeMeasure :: !(Text -> IO (Float, Float))+  }++-- | Base sans and mono faces plus an LRU cache of dynamic sizes and bold faces.+data SdlFontCache = SdlFontCache+  { sfcHooks :: !FontHooks+  , sfcGlyphAtlas :: !GlyphAtlas+  -- ^ Glyph atlas shared by every font face in this cache.+  , sfcBasePt :: !Float+  , sfcScaleRef :: !(IORef Float)+  , sfcMonoSource :: !FontSource+  , sfcSansSourceRef :: !(IORef FontSource)+  , sfcBaseEntries :: !(IORef (CachedFontEntry, CachedFontEntry))+  , sfcDynamicCache :: !(IORef (IM.IntMap CachedFontEntry, [Int]))+  , sfcEvicted :: !(IORef [SdlFont])+  }++-- | Open the base sans and mono fonts at the pixel density and warm them.+newSdlFontCache :: FontHooks -> FontSource -> FontSource -> GlyphAtlas -> Float -> IORef Float -> IO SdlFontCache+newSdlFontCache hooks sans mono ga basePt scaleRef = do+  scale <- readIORef scaleRef+  (sans', sansEntry) <- openCachedFont hooks ga scale False sans basePt+  (mono', monoEntry) <- openCachedFont hooks ga scale True mono basePt+  cache <-+    SdlFontCache hooks ga basePt scaleRef mono'+      <$> newIORef sans'+      <*> newIORef (sansEntry, monoEntry)+      <*> newIORef (IM.empty, [])+      <*> newIORef []+  warmBaseFonts cache+  pure cache++openCachedFont :: FontHooks -> GlyphAtlas -> Float -> Bool -> FontSource -> Float -> IO (FontSource, CachedFontEntry)+openCachedFont hooks ga scale grid source pt = do+  (opened, font) <- openFontSource hooks grid source (pt * scale)+  (opened,) . uncurry (CachedFontEntry font) <$> buildGlyphFontMetrics hooks ga font scale++warmBaseFonts :: SdlFontCache -> IO ()+warmBaseFonts cache = do+  (sans, mono) <- readIORef (sfcBaseEntries cache)+  forM_ [sans, mono] $ \e -> drawShaped (cfeFm e) (T.pack [' ' .. '~'])++resetGlyphAtlas :: SdlFontCache -> IO ()+resetGlyphAtlas cache = do+  let ga = sfcGlyphAtlas cache+  modifyIORef' (gaEpoch ga) (+ 1)+  writeIORef (gaIndexEntries ga) IM.empty+  writeIORef (gaFull ga) False+  aoReset (gaOps ga)+  warmBaseFonts cache++-- | Frame-start atlas maintenance: count the frame, and reset the atlas if an+-- insertion failed since the last reset.+prepareGlyphAtlasForFrame :: SdlFontCache -> IO Bool+prepareGlyphAtlasForFrame cache = do+  modifyIORef' (gaFrame (sfcGlyphAtlas cache)) (+ 1)+  full <- glyphAtlasFull cache+  full <$ when full (resetGlyphAtlas cache)++-- | The font work a backend does before a frame's UI pass records any text,+-- answering whether the glyph atlas was reset ('prepareGlyphAtlasForFrame').+-- A reset emptied the glyph slots a kept draw's text points at, so the+-- frame repaints whole ('damageFull') rather than reuse one. Fonts the size+-- cache evicted close now, and the measure caches that can still hold their+-- metrics are dropped ('clearMeasureCache'), before the pass measures text.+beginTtfFrame :: SdlFontCache -> Context -> IO Bool+beginTtfFrame cache ctx = do+  fresh <- prepareGlyphAtlasForFrame cache+  when fresh (damageFull ctx)+  whenM (closeEvictedFonts cache) (clearMeasureCache ctx)+  pure fresh++-- | Whether to drop the frame just built instead of presenting it: its UI+-- pass ran out of glyph atlas room, so some of its text has no quads. A+-- dropped frame damages the whole window and marks the context dirty, so+-- the next frame, after 'beginTtfFrame' resets the atlas, repaints it all+-- and the screen keeps the last good frame meanwhile. @fresh@ is what+-- 'beginTtfFrame' answered for this frame: a frame that filled an atlas+-- reset at its own start (a glyph larger than a page, or more glyphs than+-- the pages hold) would fill it again after every reset, so it is presented+-- with those glyphs missing instead.+ttfFrameDropped :: SdlFontCache -> Context -> Bool -> IO Bool+ttfFrameDropped cache ctx fresh = do+  dropped <- (&& not fresh) <$> glyphAtlasFull cache+  when dropped $ do+    damageFull ctx+    markDirty ctx+  pure dropped++-- | The primary (sans) family's source, for the debug readout.+sdlFontCacheSource :: SdlFontCache -> IO FontSource+sdlFontCacheSource cache = readIORef (sfcSansSourceRef cache)++-- | The monospace family's source.+sdlFontCacheMonoSource :: SdlFontCache -> FontSource+sdlFontCacheMonoSource = sfcMonoSource++closeCachedFonts :: GlyphAtlas -> [SdlFont] -> IO ()+closeCachedFonts ga fonts = do+  fallbacks <- concat <$> mapM (fmap IM.elems . readIORef . sfFallbacks) fonts+  let handles = IS.fromList (map sfId (fonts ++ fallbacks))+  mapM_ closeFont fonts+  modifyIORef' (gaIndexEntries ga) (`IM.withoutKeys` handles)++-- | Close every open font, base, dynamic and evicted.+destroySdlFontCache :: SdlFontCache -> IO ()+destroySdlFontCache cache = do+  (dynamic, _) <- atomicModifyIORef' (sfcDynamicCache cache) ((IM.empty, []),)+  evicted <- atomicModifyIORef' (sfcEvicted cache) ([],)+  (sans, mono) <- readIORef (sfcBaseEntries cache)+  closeCachedFonts (sfcGlyphAtlas cache) (map cfeFont (sans : mono : IM.elems dynamic) ++ evicted)++-- | Close fonts evicted since the last call, answering whether there were any.+closeEvictedFonts :: SdlFontCache -> IO Bool+closeEvictedFonts cache = do+  evicted <- atomicModifyIORef' (sfcEvicted cache) ([],)+  not (null evicted) <$ closeCachedFonts (sfcGlyphAtlas cache) evicted++-- | Reopen base fonts at the current pixel density, closing old fonts only+-- after the replacements open cleanly.+reloadSdlFontCache :: SdlFontCache -> FontSource -> IO ()+reloadSdlFontCache cache source = do+  scale <- readIORef (sfcScaleRef cache)+  let open grid src = openCachedFont (sfcHooks cache) (sfcGlyphAtlas cache) scale grid src (sfcBasePt cache)+  (opened, sans) <- open False source+  mono <- snd <$> open True (sfcMonoSource cache) `onException` closeFont (cfeFont sans)+  (dynamic, _) <- atomicModifyIORef' (sfcDynamicCache cache) ((IM.empty, []),)+  evicted <- atomicModifyIORef' (sfcEvicted cache) ([],)+  (oldSans, oldMono) <- readIORef (sfcBaseEntries cache)+  writeIORef (sfcSansSourceRef cache) opened+  writeIORef (sfcBaseEntries cache) (sans, mono)+  closeCachedFonts (sfcGlyphAtlas cache) (map cfeFont (oldSans : oldMono : IM.elems dynamic) ++ evicted)+  resetGlyphAtlas cache++-- | Install the cache's base fonts and resolver on a 'Context'.+withSdlFontCache :: SdlFontCache -> Context -> IO Context+withSdlFontCache cache ctx = do+  scale <- readIORef (sfcScaleRef cache)+  (sans, mono) <- readIORef (sfcBaseEntries cache)+  let metrics = withFontSize (withMonoFontMetrics (withFontMetrics ctx (cfeFm sans)) (cfeFm mono)) (sfcBasePt cache)+  pure $+    withFontResolver+      (wrapMeasureCache scale metrics (cfeMeasure sans))+      (\sz weight style var -> (\(e, native) -> (cfeFm e, native)) <$> resolveCachedFont cache sz weight style var)+      (\sz weight style var txt -> resolveCachedFont cache sz weight style var >>= (`cfeMeasure` txt) . fst)++isBoldWeight :: FontWeight -> Bool+isBoldWeight = \case+  WeightSemiBold -> True+  WeightBold -> True+  WeightExtraBold -> True+  WeightBlack -> True+  _ -> False++elemFirstN :: Int -> Int -> [Int] -> Bool+elemFirstN !n !k = go n+  where+    go !remN (x : xs)+      | remN <= 0 = False+      | x == k = True+      | otherwise = go (remN - 1) xs+    go _ [] = False++resolveCachedFont :: SdlFontCache -> Float -> FontWeight -> FontStyle -> FontVariant -> IO (CachedFontEntry, Bool)+resolveCachedFont cache sz weight style var = do+  bold <-+    if style == FontStyleNormal && isBoldWeight weight+      then do+        src <- variantSource cache var+        fhBoldSource (sfcHooks cache) src (sfFont . cfeFont <$> baseEntry cache var)+      else pure Nothing+  (,isJust bold) <$> getOrLoadCachedFont cache sz var bold++variantSource :: SdlFontCache -> FontVariant -> IO FontSource+variantSource cache var+  | var == FontMono = pure (sfcMonoSource cache)+  | otherwise = readIORef (sfcSansSourceRef cache)++baseEntry :: SdlFontCache -> FontVariant -> IO CachedFontEntry+baseEntry cache var = (if var == FontMono then snd else fst) <$> readIORef (sfcBaseEntries cache)++getOrLoadCachedFont :: SdlFontCache -> Float -> FontVariant -> Maybe FontSource -> IO CachedFontEntry+getOrLoadCachedFont cache sz var bold+  | null bold && ptKey == round (sfcBasePt cache * 2) = baseEntry cache var+  | otherwise = do+      (entries, order) <- readIORef (sfcDynamicCache cache)+      case IM.lookup key entries of+        Just entry -> do+          unless (elemFirstN 24 key order) $ do+            let order' = key : delete key order+            length order' `seq` writeIORef (sfcDynamicCache cache) (entries, order')+          pure entry+        Nothing -> do+          scale <- readIORef (sfcScaleRef cache)+          source <- maybe (variantSource cache var) pure bold+          entry <- snd <$> openCachedFont (sfcHooks cache) (sfcGlyphAtlas cache) scale mono source (fromIntegral ptKey / 2)+          let opened = key : order+              (kept, evicted) = if length opened > 48 then splitAt 32 opened else (opened, [])+          writeIORef (sfcDynamicCache cache) (foldr IM.delete (IM.insert key entry entries) evicted, kept)+          modifyIORef' (sfcEvicted cache) (map cfeFont (mapMaybe (`IM.lookup` entries) evicted) ++)+          pure entry+  where+    mono = var == FontMono+    ptKey = round ((if sz > 0 then sz else sfcBasePt cache) * 2) :: Int+    key = ptKey * 4 + fromEnum (not (null bold)) * 2 + fromEnum mono++-- ---------------------------------------------------------------------------+-- SDL3_ttf FFI++foreign import capi unsafe "SDL3_ttf/SDL_ttf.h TTF_Init"+  ttfInit :: IO Bool++foreign import capi unsafe "SDL3_ttf/SDL_ttf.h TTF_Quit"+  ttfQuit :: IO ()++foreign import ccall unsafe "SDL_GetError"+  sdlGetError :: IO CString++foreign import capi unsafe "SDL3/SDL.h SDL_DestroySurface"+  sdlDestroySurface :: Ptr () -> IO ()++-- | Open a font file via the nano-ui C helper.+foreign import ccall unsafe "nano_ui_ttf_open_font"+  ttfOpenFont :: CString -> CFloat -> IO (Ptr ())++foreign import ccall unsafe "nano_ui_ttf_open_font_memory"+  ttfOpenFontMemory :: Ptr () -> CSize -> CFloat -> IO (Ptr ())++-- | Close a TTF_Font handle.+foreign import capi unsafe "SDL3_ttf/SDL_ttf.h TTF_CloseFont"+  ttfCloseFont :: Ptr () -> IO ()++foreign import capi unsafe "SDL3_ttf/SDL_ttf.h TTF_GetFontLineSkip"+  ttfLineSkip :: Ptr () -> IO CInt++foreign import capi unsafe "SDL3_ttf/SDL_ttf.h TTF_GetFontAscent"+  ttfAscent :: Ptr () -> IO CInt++foreign import ccall unsafe "nano_ui_ttf_half_leading"+  ttfHalfLeading :: Ptr () -> IO CInt++-- | Whether a font face is a native bold face of a regular face's family.+foreign import ccall unsafe "nano_ui_ttf_is_bold_of"+  ttfIsBoldOf :: Ptr () -> Ptr () -> IO CBool++foreign import ccall unsafe "nano_ui_ttf_hint_for_grid"+  ttfHintForGrid :: Ptr () -> IO ()++foreign import ccall unsafe "nano_ui_ttf_space_advance"+  ttfSpaceAdvance :: Ptr () -> IO CFloat++foreign import capi unsafe "SDL3_ttf/SDL_ttf.h TTF_GetGlyphMetrics"+  ttfGlyphMetrics ::+    Ptr () ->+    CUInt ->+    Ptr CInt ->+    Ptr CInt ->+    Ptr CInt ->+    Ptr CInt ->+    Ptr CInt ->+    IO Bool++foreign import ccall unsafe "nano_ui_ttf_shape"+  ttfShape :: Ptr () -> CString -> CSize -> CInt -> Ptr () -> IO CBool++foreign import ccall unsafe "nano_ui_ttf_shaped_free"+  ttfShapedFree :: Ptr () -> IO ()++foreign import ccall unsafe "nano_ui_ttf_shaped_size"+  ttfShapedSize :: IO CSize++foreign import ccall unsafe "nano_ui_ttf_shaped_int"+  ttfShapedInt :: Ptr () -> CInt -> IO CInt++foreign import ccall unsafe "nano_ui_ttf_shaped_ptr"+  ttfShapedPtr :: Ptr () -> CInt -> IO (Ptr ())++foreign import ccall unsafe "nano_ui_ttf_render_glyph_index_surface"+  ttfRenderGlyphIndexSurface :: Ptr () -> CUInt -> Ptr (Ptr ()) -> IO CBool++-- | Whether a font or its fallbacks have a glyph for a Unicode codepoint.+foreign import capi unsafe "SDL3_ttf/SDL_ttf.h TTF_FontHasGlyph"+  ttfHasGlyph :: Ptr () -> CUInt -> IO Bool++-- | Attach a fallback font to a primary font.+foreign import capi unsafe "SDL3_ttf/SDL_ttf.h TTF_AddFallbackFont"+  ttfAddFallback :: Ptr () -> Ptr () -> IO Bool++-- | Remove a fallback font from a primary font.+foreign import capi unsafe "SDL3_ttf/SDL_ttf.h TTF_RemoveFallbackFont"+  ttfRemoveFallback :: Ptr () -> Ptr () -> IO ()++-- | Clone a font handle at a new point size sharing its underlying stream.+foreign import ccall unsafe "nano_ui_ttf_copy_font"+  ttfCopyFont :: Ptr () -> CFloat -> IO (Ptr ())++foreign import ccall unsafe "nano_ui_ttf_get_kerning"+  ttfGetKerning :: Ptr () -> CUInt -> CUInt -> IO CInt
+ lib/NanoUI/Ttf/Internal/Header.hsc view
@@ -0,0 +1,112 @@+-- | The constants of @include/nano_ui_ttf_shared.h@, read by hsc2hs, so the+-- Haskell side of shaping and the glyph atlas uses the values the C side+-- was compiled with.+module NanoUI.Ttf.Internal.Header+  ( -- * Draw buffer and glyph atlas+    vertexBytes+  , glyphAtlasPixels+  , glyphAtlasPageCount+  , glyphAtlasPad+  , whitePatchSize+    -- * Shaped lines+  , shapedWidth+  , shapedHeight+  , shapedGlyphCount+  , shapedClusterCount+  , shapedGlyphs+  , shapedGlyphFonts+  , shapedClusters+  , glyphTextOffset+  , glyphIndex+  , glyphDstX+  , glyphDstY+  , glyphDstW+  , glyphDstH+  , glyphSrcX+  , glyphSrcY+  , glyphSrcW+  , glyphSrcH+  , shapedGlyphInts+  , clusterOffset+  , clusterLength+  , clusterX+  , clusterWidth+  , clusterFlags+  , shapedClusterInts+  , directionAuto+  , directionLtr+  , directionRtl+  , directionMask+  ) where++#include "nano_ui_ttf_shared.h"++-- | NANO_UI_VERTEX_BYTES: bytes in one vertex of the core's draw buffer.+-- Equal to the core's 'NanoUI.Internal.Draw.Types.vertexSize', which+-- nano-ui-sdl-web-test checks.+vertexBytes :: Int+vertexBytes = #const NANO_UI_VERTEX_BYTES++-- | NANO_UI_GLYPH_ATLAS_SIZE: width and height of a glyph atlas page.+glyphAtlasPixels :: Int+glyphAtlasPixels = #const NANO_UI_GLYPH_ATLAS_SIZE++-- | NANO_UI_GLYPH_ATLAS_PAGES. Equal to the core's+-- 'NanoUI.Internal.Draw.Types.glyphAtlasPages', which nano-ui-sdl-web-test+-- checks.+glyphAtlasPageCount :: Int+glyphAtlasPageCount = #const NANO_UI_GLYPH_ATLAS_PAGES++-- | NANO_UI_GLYPH_ATLAS_PAD: transparent pixels around each glyph.+glyphAtlasPad :: Int+glyphAtlasPad = #const NANO_UI_GLYPH_ATLAS_PAD++-- | NANO_UI_WHITE_PATCH_SIZE: the opaque square at each page's top left.+whitePatchSize :: Int+whitePatchSize = #const NANO_UI_WHITE_PATCH_SIZE++-- | The fields of @nano_ui_ttf_shaped_int@.+shapedWidth, shapedHeight, shapedGlyphCount, shapedClusterCount :: Int+shapedWidth = #const NANO_UI_SHAPED_WIDTH+shapedHeight = #const NANO_UI_SHAPED_HEIGHT+shapedGlyphCount = #const NANO_UI_SHAPED_GLYPH_COUNT+shapedClusterCount = #const NANO_UI_SHAPED_CLUSTER_COUNT++-- | The fields of @nano_ui_ttf_shaped_ptr@.+shapedGlyphs, shapedGlyphFonts, shapedClusters :: Int+shapedGlyphs = #const NANO_UI_SHAPED_GLYPHS+shapedGlyphFonts = #const NANO_UI_SHAPED_GLYPH_FONTS+shapedClusters = #const NANO_UI_SHAPED_CLUSTERS++-- | The ints of a shaped glyph, at these offsets from its first, and+-- 'shapedGlyphInts' of them a glyph.+glyphTextOffset, glyphIndex, glyphDstX, glyphDstY, glyphDstW, glyphDstH, glyphSrcX, glyphSrcY, glyphSrcW, glyphSrcH, shapedGlyphInts :: Int+glyphTextOffset = #const NANO_UI_GLYPH_TEXT_OFFSET+glyphIndex = #const NANO_UI_GLYPH_INDEX+glyphDstX = #const NANO_UI_GLYPH_DST_X+glyphDstY = #const NANO_UI_GLYPH_DST_Y+glyphDstW = #const NANO_UI_GLYPH_DST_W+glyphDstH = #const NANO_UI_GLYPH_DST_H+glyphSrcX = #const NANO_UI_GLYPH_SRC_X+glyphSrcY = #const NANO_UI_GLYPH_SRC_Y+glyphSrcW = #const NANO_UI_GLYPH_SRC_W+glyphSrcH = #const NANO_UI_GLYPH_SRC_H+shapedGlyphInts = #const NANO_UI_SHAPED_GLYPH_INTS++-- | The ints of a shaped cluster, at these offsets from its first, and+-- 'shapedClusterInts' of them a cluster.+clusterOffset, clusterLength, clusterX, clusterWidth, clusterFlags, shapedClusterInts :: Int+clusterOffset = #const NANO_UI_CLUSTER_OFFSET+clusterLength = #const NANO_UI_CLUSTER_LENGTH+clusterX = #const NANO_UI_CLUSTER_X+clusterWidth = #const NANO_UI_CLUSTER_WIDTH+clusterFlags = #const NANO_UI_CLUSTER_FLAGS+shapedClusterInts = #const NANO_UI_SHAPED_CLUSTER_INTS++-- | Shaping directions (SDL_ttf's @TTF_Direction@), and the mask that takes+-- a cluster's direction out of its flags.+directionAuto, directionLtr, directionRtl, directionMask :: Int+directionAuto = #const NANO_UI_DIRECTION_AUTO+directionLtr = #const NANO_UI_DIRECTION_LTR+directionRtl = #const NANO_UI_DIRECTION_RTL+directionMask = #const NANO_UI_DIRECTION_MASK
+ lib/NanoUI/Ttf/Internal/Inter.hs view
@@ -0,0 +1,19 @@+{-# LANGUAGE TemplateHaskell #-}++-- | Embedded default UI font. Import only from font bootstrap code.+module NanoUI.Ttf.Internal.Inter+  ( fontInterBytes+  , fontInterLabel+  ) where++import Data.ByteString (ByteString)+import Data.FileEmbed (embedFileRelative)++-- | Display label for the bundled Inter font.+fontInterLabel :: FilePath+fontInterLabel = "inter.ttf"++-- | Raw TTF bytes for the bundled Inter font.+{-# NOINLINE fontInterBytes #-}+fontInterBytes :: ByteString+fontInterBytes = $(embedFileRelative "data/inter.ttf")
+ lib/NanoUI/Ttf/Internal/Support.hs view
@@ -0,0 +1,147 @@+-- | Shared fallback-font coverage probing, generic CSS family expansion, and+-- font-cache reload synchronization for SDL3 and WebGL2 backends.+module NanoUI.Ttf.Internal.Support+  ( -- * Family normalization and generic expansion+    normalizeFamily+  , expandGenericFamily+    -- * Fallback glyph coverage+  , CoveragePool+  , newCoveragePool+  , ensurePoolCoverage+  , closeCoveragePool+    -- * Cache reload+  , syncSdlFontCache+  ) where++import Control.Monad (forM_, unless, when)+import Data.Char (isPrint, isSpace, ord, toLower)+import Data.Foldable (traverse_)+import Data.IORef (IORef, newIORef, readIORef, writeIORef)+import Data.IntMap.Strict qualified as IM+import Data.Primitive.SmallArray (SmallArray, indexSmallArray, sizeofSmallArray, smallArrayFromList)+import Data.Text (Text)+import Data.Text qualified as T+import Foreign.Ptr (Ptr, nullPtr)+import NanoUI.Backend (Context, clearMeasureCache, damageFull, markDirty)+import NanoUI.Ttf.Internal.Font+  ( FontSource+  , SdlFont (..)+  , SdlFontCache+  , attachFallback+  , reloadSdlFontCache+  , ttfCloseFont+  , ttfHasGlyph+  , withSdlFontCache+  )++-- | Fold case and drop whitespace, hyphens, and underscores so family and+-- file names can be matched loosely (@"DejaVu Sans Mono"@ vs @DejaVuSansMono@).+normalizeFamily :: String -> String+normalizeFamily =+  map toLower+    . filter (\c -> not (isSpace c) && c /= '-' && c /= '_')++-- | Expand a normalized generic CSS family (@sansserif@, @serif@, @monospace@)+-- into concrete families to search in preference order.+expandGenericFamily :: String -> Maybe [String]+expandGenericFamily = \case+  "monospace" ->+    Just+      [ "DejaVu Sans Mono"+      , "Liberation Mono"+      , "Ubuntu Mono"+      , "Noto Sans Mono"+      , "Consolas"+      , "Courier New"+      ]+  "sansserif" ->+    Just+      [ "DejaVu Sans"+      , "Liberation Sans"+      , "Noto Sans"+      , "Open Sans"+      , "Helvetica Neue"+      ]+  "serif" ->+    Just+      [ "DejaVu Serif"+      , "Liberation Serif"+      , "Noto Serif"+      , "Times New Roman"+      ]+  _ -> Nothing++data PoolState src = PoolState+  { psSources :: !(SmallArray src)+  , psProbes :: !(IM.IntMap (Ptr ()))+  , psChars :: !(IM.IntMap (Maybe Int))+  }++-- | Lazy fallback probe cache mapping non-ASCII codepoints to the first+-- fallback source carrying a glyph for them.+data CoveragePool src = CoveragePool+  { cpLoadSources :: !(IO [src])+  , cpOpenProbe :: !(src -> IO (Ptr ()))+  , cpState :: !(IORef (Maybe (PoolState src)))+  }++-- | Create a fallback coverage pool backed by a lazy source loader and an+-- opener returning a @TTF_Font*@ probe (or 'nullPtr' on failure).+newCoveragePool :: IO [src] -> (src -> IO (Ptr ())) -> IO (CoveragePool src)+newCoveragePool loadSources openProbe =+  CoveragePool loadSources openProbe <$> newIORef Nothing++-- | Attach fallback fonts from @pool@ to @sf@ for any printable non-ASCII+-- characters in @txt@ that @sf@ lacks.+ensurePoolCoverage :: CoveragePool src -> SdlFont -> Text -> IO ()+ensurePoolCoverage pool sf txt =+  unless (T.isAscii txt) $+    forM_ (T.unpack txt) $ \c ->+      when (ord c >= 128 && isPrint c) $ do+        has <- ttfHasGlyph (sfFont sf) (fromIntegral (ord c))+        unless has $ probeForCodepoint pool (ord c) >>= traverse_ (uncurry (attachFallback sf))++probeForCodepoint :: CoveragePool src -> Int -> IO (Maybe (Int, Ptr ()))+probeForCodepoint pool cp = do+  st <- readIORef (cpState pool) >>= maybe loadState pure+  let sources = psSources st+      n = sizeofSmallArray sources+      search probes i+        | i >= n = pure (Nothing, probes)+        | otherwise = do+            probe <- maybe (cpOpenProbe pool (indexSmallArray sources i)) pure (IM.lookup i probes)+            has <- if probe == nullPtr then pure False else ttfHasGlyph probe (fromIntegral cp)+            let probes' = IM.insert i probe probes+            if has then pure (Just i, probes') else search probes' (i + 1)+  (source, probes) <- case IM.lookup cp (psChars st) of+    Just known -> pure (known, psProbes st)+    Nothing -> do+      found@(first, opened) <- search (psProbes st) 0+      found <$ writeIORef (cpState pool) (Just st {psProbes = opened, psChars = IM.insert cp first (psChars st)})+  pure (source >>= \i -> (i,) <$> IM.lookup i probes)+  where+    loadState = do+      srcs <- cpLoadSources pool+      let st = PoolState (smallArrayFromList srcs) IM.empty IM.empty+      st <$ writeIORef (cpState pool) (Just st)++-- | Close all opened probe faces and clear the codepoint map (before @TTF_Quit@).+closeCoveragePool :: CoveragePool src -> IO ()+closeCoveragePool pool =+  readIORef (cpState pool) >>= \case+    Nothing -> pure ()+    Just st -> do+      forM_ (psProbes st) $ \probe -> unless (probe == nullPtr) (ttfCloseFont probe)+      writeIORef (cpState pool) (Just st {psProbes = IM.empty, psChars = IM.empty})++-- | Reload @cache@ with @source@, install the updated font resolver onto @ctx@+-- (passing it through @decorate@ for backend hooks such as clipboard), clear+-- measurement caches, and queue a full repaint.+syncSdlFontCache :: SdlFontCache -> Context -> FontSource -> (Context -> Context) -> IO Context+syncSdlFontCache cache ctx source decorate = do+  reloadSdlFontCache cache source+  ctx' <- decorate <$> withSdlFontCache cache ctx+  clearMeasureCache ctx+  damageFull ctx+  markDirty ctx+  pure ctx'
+ nano-ui-ttf.cabal view
@@ -0,0 +1,85 @@+cabal-version:      3.4+name:               nano-ui-ttf+version:            0.2.0.0+synopsis:           Shared SDL3_ttf shaping, glyph atlas, and font cache for nano-ui+description:+    Internal shared TrueType shaping, glyph atlas bookkeeping, font caching,+    and bundled Inter font used by nano-ui-sdl and nano-ui-sdl-web.+license:            MIT AND OFL-1.1+license-files:+    LICENSE+    LICENSE-Inter+author:             goolord+maintainer:         zacharyachurchill@gmail.com+homepage:           https://github.com/goolord/nano-ui+bug-reports:        https://github.com/goolord/nano-ui/issues+category:           Graphics+build-type:         Simple+tested-with:        GHC ==9.10.3 || ==9.14.1++extra-doc-files:+    CHANGELOG.md+    README.md++-- The header is listed so cabal rebuilds the C and hsc2hs sources when it+-- changes; install-includes alone is not tracked.+extra-source-files:+    data/inter.ttf+    include/nano_ui_ttf_shared.h++source-repository head+    type:     git+    location: https://github.com/goolord/nano-ui.git+    subdir:   packages/nano-ui-ttf++flag sdl+    description: Build the SDL3_ttf layer. Needs SDL3, SDL3_ttf, and pkg-config.+    manual: True+    default: True++common extensions+    default-language: GHC2024+    default-extensions:+        OverloadedStrings++common warnings+    ghc-options:+        -Wall+        -Wextra+        -Wcompat+        -Widentities+        -Wincomplete-record-updates+        -Wincomplete-uni-patterns+        -Wmissing-export-lists+        -Wmissing-home-modules+        -Wpartial-fields+        -Wredundant-constraints+        -Wunused-packages++library+    import:           extensions+    import:           warnings+    exposed-modules:+        NanoUI.Ttf.Internal.Font+        NanoUI.Ttf.Internal.Header+        NanoUI.Ttf.Internal.Inter+        NanoUI.Ttf.Internal.Support+    build-depends:+        base >=4.20 && <4.23,+        bytestring ^>=0.12,+        containers >=0.7 && <0.9,+        file-embed ^>=0.0.16,+        nano-ui ^>=0.2,+        primitive ^>=0.9,+        text >=2.1.2 && <2.2+    hs-source-dirs:   lib+    -- nano-ui-sdl and nano-ui-sdl-web include the installed header from+    -- their own C sources.+    include-dirs:     include+    install-includes: nano_ui_ttf_shared.h+    build-tool-depends: hsc2hs:hsc2hs+    if !flag(sdl)+        buildable: False+    if flag(sdl)+        c-sources:        cbits/nano_ui_ttf.c+        pkgconfig-depends: sdl3 >= 3.2, sdl3-ttf >= 3.2