#!/usr/bin/env python3
"""gen_font.py - builds font_dejavu.h, the viewer's built-in text (v0.5 menu).

The viewer draws its menu with SDL2 alone (no SDL_ttf, no font file to ship):
printable ASCII from DejaVu Sans and DejaVu Sans Bold, rendered once here,
stored as 4-bit alpha, one atlas row per style. DejaVu's licence
(Bitstream Vera, with the DejaVu changes public domain) allows this; its text
ships in the Windows zip's licenses folder.

    python3 tools/raw-recv/gen_font.py      # rewrites tools/raw-recv/font_dejavu.h
"""
import os
from PIL import Image, ImageDraw, ImageFont

# regular for body text (drawn at 18-24 px), bold for titles and key caps
# (22-56 px): each rendered at the largest size it is drawn at, so text is
# only ever scaled down
FONTS = [
    ("regular", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 32),
    ("bold", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 56),
]
FIRST, LAST = 32, 126
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "font_dejavu.h")


def render(path, size):
    font = ImageFont.truetype(path, size)
    ascent, descent = font.getmetrics()
    h = ascent + descent
    glyphs = []
    for c in range(FIRST, LAST + 1):
        ch = chr(c)
        adv = int(round(font.getlength(ch)))
        l, t, r, b = font.getbbox(ch)
        w = max(r, adv, 1)
        im = Image.new("L", (w, h), 0)
        ImageDraw.Draw(im).text((0, 0), ch, font=font, fill=255)
        glyphs.append((im, adv))
    return glyphs, h


def main():
    parts = []
    metrics = []   # per style: list of (x, w, adv)
    heights = []
    for name, path, size in FONTS:
        glyphs, h = render(path, size)
        heights.append(h)
        x = 0
        m = []
        for im, adv in glyphs:
            m.append((x, im.width, adv))
            x += im.width + 1
        parts.append((glyphs, x))
        metrics.append(m)
    atlas_w = max(w for _, w in parts)
    atlas_w += atlas_w & 1
    tops = [sum(heights[:i]) for i in range(len(heights))]
    atlas = Image.new("L", (atlas_w, sum(heights)), 0)
    for row, (glyphs, _) in enumerate(parts):
        for (im, _), (x, _, _) in zip(glyphs, metrics[row]):
            atlas.paste(im, (x, tops[row]))
    px = atlas.tobytes()
    packed = bytes(((px[i] >> 4) << 4) | (px[i + 1] >> 4) for i in range(0, len(px), 2))

    with open(OUT, "w") as f:
        f.write("/* font_dejavu.h - generated by gen_font.py, do not edit.\n")
        f.write(" * DejaVu Sans / DejaVu Sans Bold (Bitstream Vera licence; DejaVu changes\n")
        f.write(" * public domain), ASCII %d-%d: regular at %d px, bold at %d px, 4-bit alpha,\n * two nibbles a byte. */\n" % (FIRST, LAST, FONTS[0][2], FONTS[1][2]))
        f.write("#define FONT_FIRST %d\n#define FONT_LAST %d\n" % (FIRST, LAST))
        f.write("static const int font_px[2] = { %d, %d };      /* the size each style was rendered at */\n" % (FONTS[0][2], FONTS[1][2]))
        f.write("static const int font_h[2] = { %d, %d };       /* its line height */\n" % tuple(heights))
        f.write("static const int font_top[2] = { %d, %d };     /* its row in the atlas */\n" % tuple(tops))
        f.write("#define FONT_ATLAS_W %d\n#define FONT_ATLAS_H %d\n" % (atlas_w, sum(heights)))
        f.write("/* per style (0 regular, 1 bold), per glyph: x in the atlas row, width, advance */\n")
        f.write("static const unsigned short font_glyphs[2][%d][3] = {\n" % (LAST - FIRST + 1))
        for m in metrics:
            f.write("  {" + ",".join("{%d,%d,%d}" % g for g in m) + "},\n")
        f.write("};\n")
        f.write("static const unsigned char font_atlas[%d] = {\n" % len(packed))
        for i in range(0, len(packed), 40):
            f.write("".join("%d," % b for b in packed[i:i + 40]) + "\n")
        f.write("};\n")
    print("%s: %dx%d atlas, %d bytes" % (OUT, atlas_w, sum(heights), len(packed)))


if __name__ == "__main__":
    main()
