Files
rosetta/tools/fixtures/bitmapfonts.py
T

100 lines
6.4 KiB
Python

# Bitmap font fixtures (tools/fixtures.py) for font/bdf and font/pcf (and codecs/font/Bitmap): BDF fonts (Spleen 5x8,
# 12x24; BSD-2, nixpkgs#spleen), PCF fonts compiled from them by `bdftopcf` with every glyph pad / scan unit / bit and
# byte order (-p1/2/4/8, -u1/2/4, -m / -l) and with -t (terminal fonts), Tamzen PCFs (nixpkgs#tamzen) and X11
# misc-misc .pcf.gz fonts in ISO8859-1 and ISO8859-5, Windows .fnt / .fon (NE) made by FontForge from the Spleen BDFs;
# all read from the nix store at fixture time. Reference glyph
# bitmaps, offsets and advances come from FreeType (tools/fixtures/_bitmapfonts_ref.py); our BDF writer's output for
# each font (tools/fixtures/_bitmapfonts_ours.luau) is read back by FreeType and compared too.
# tests/gen/bitmapfonts.luau { fonts = { { name, format, data, gz?, ref = { glyphs = { { cp, width, height, left,
# top, advance, pixels } }, ascent, descent }, ours = { ok, detail } } } }
import gzip, importlib.util, json, os, shutil, subprocess
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
A = importlib.util.module_from_spec(_s)
_s.loader.exec_module(A)
INPUTS = ["tools/fixtures/_bitmapfonts_ref.py", "tools/fixtures/_bitmapfonts_ours.luau", "src/Rosetta/font/bdf", "src/Rosetta/font/pcf",
"src/Rosetta/font/fon"]
CHARS = [32, 33, 48, 64, 65, 87, 103, 106, 113, 126, 0xE9, 0xF1, 0x416, 0x2588, 0x2192]
def store(pkg):
return subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + pkg], capture_output=True, check=True, text=True).stdout.strip().split("\n")[-1]
def refs(ctx, paths):
code = open(os.path.join(ctx.root, "tools", "fixtures", "_bitmapfonts_ref.py")).read()
raw = ctx.python(["freetype-py"], code, input=json.dumps({"fonts": [{"path": p, "chars": CHARS} for p in paths]}).encode())
return json.loads(raw)
def generate(ctx):
spleen = os.path.join(store("spleen"), "share", "fonts", "misc")
tamzen = os.path.join(store("tamzen"), "share", "fonts", "misc")
misc = os.path.join(store("xorg.fontmiscmisc"), "share", "fonts", "X11", "misc")
tmp = A.tmpdir()
try:
items = [] # (name, format, path, gz)
for f in ("spleen-5x8.bdf", "spleen-12x24.bdf"):
items.append((f, "bdf", os.path.join(spleen, f), False))
src = os.path.join(spleen, "spleen-5x8.bdf")
for opts in (["-p1", "-u1", "-m"], ["-p2", "-u2", "-l"], ["-p4", "-u4", "-m"], ["-p8", "-u4", "-l"], ["-p4", "-u1", "-l", "-t"]):
out = os.path.join(tmp, "spleen-5x8" + "".join(opts) + ".pcf")
A.tool(["xorg.bdftopcf"], ["bdftopcf"] + opts + ["-o", out, src])
items.append(("spleen-5x8 bdftopcf " + " ".join(opts), "pcf", out, False))
out = os.path.join(tmp, "spleen-12x24.pcf")
A.tool(["xorg.bdftopcf"], ["bdftopcf", "-o", out, os.path.join(spleen, "spleen-12x24.bdf")])
items.append(("spleen-12x24 bdftopcf", "pcf", out, False))
for f in ("Tamzen7x13r.pcf", "Tamzen10x20b.pcf"):
items.append((f, "pcf", os.path.join(tamzen, f), False))
for f in ("6x13-ISO8859-1.pcf.gz", "9x18B-ISO8859-5.pcf.gz"):
items.append((f, "pcf", os.path.join(misc, f), True))
# Windows FNT / FON by FontForge from the Spleen BDFs (one strike, and a .fon with two)
for bdf, label in (("spleen-8x16.bdf", "8x16"), ("spleen-5x8.bdf", "5x8")):
fn = os.path.join(tmp, "spleen-%s.fnt" % label)
A.tool(["fontforge"], ["fontforge", "-lang=ff", "-c", 'Open($1); Generate($2, "fnt")', os.path.join(spleen, bdf), fn])
fnts = [f for f in os.listdir(tmp) if f.startswith("spleen-%s-" % label) and f.endswith(".fnt")]
items.append(("spleen-%s.fnt (fontforge)" % label, "fon", os.path.join(tmp, fnts[0]), False))
fon = os.path.join(tmp, "spleen-two.fon")
A.tool(["fontforge"], ["fontforge", "-lang=ff", "-c", 'Open($1); Import($2); Generate($3, "fon")',
os.path.join(spleen, "spleen-8x16.bdf"), os.path.join(spleen, "spleen-12x24.bdf"), fon])
items.append(("spleen 8x16 + 12x24 .fon (fontforge)", "fon", fon, False))
# FreeType reads .pcf.gz itself
rs = refs(ctx, [p for _, _, p, _ in items])
fonts = []
for (name, fmt, path, gz), ref in zip(items, rs):
for g in ref["glyphs"]:
g["pixels"] = bytes.fromhex(g["pixels"])
e = {"name": name, "format": fmt, "data": open(path, "rb").read(), "ref": ref}
if gz:
e["gz"] = True
fonts.append(e)
# our BDF writer, read back by FreeType
ctx.emit("bitmapfonts_src", {"fonts": [{k: v for k, v in f.items() if k != "ref"} for f in fonts]})
subprocess.run(["python3", "-I", os.path.join(ctx.root, "tools", "gen_registry.py")], check=True, capture_output=True)
exe = shutil.which("luau")
argv = ([exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]) + [os.path.join(ctx.root, "tools", "fixtures", "_bitmapfonts_ours.luau")]
r = subprocess.run(argv, capture_output=True, cwd=ctx.root)
ours = {}
for line in r.stdout.decode().splitlines():
n, h = line.rsplit(" ", 1)
p = os.path.join(tmp, "ours-%d.bdf" % len(ours))
open(p, "wb").write(bytes.fromhex(h))
ours[n] = p
names = list(ours)
back = refs(ctx, [ours[n] for n in names]) if names else []
for f in fonts:
if f["name"] in ours:
b = back[names.index(f["name"])]
want = {(g["cp"], g["width"], g["height"], g["left"], g["top"], g["advance"], g["pixels"].hex()) for g in f["ref"]["glyphs"]}
got = {(g["cp"], g["width"], g["height"], g["left"], g["top"], g["advance"], g["pixels"]) for g in b["glyphs"]}
diff = sorted(want ^ got)[:2]
f["ours"] = {"ok": want == got, "detail": "%d glyphs, %d differ %s" % (len(want), len(want ^ got), [d[:6] for d in diff])}
if not f["ref"]["unicode"]:
f["ours"] = {"ok": True, "detail": "not a Unicode font: FreeType maps byte codes, our BDF leaves them unmapped"}
else:
f["ours"] = {"ok": False, "detail": "no output: " + r.stderr.decode(errors="replace")[-300:]}
ctx.emit("bitmapfonts", {"fonts": fonts})
finally:
A.rmtree(tmp)