#!/usr/bin/env python3 """Convert a Linux console PSF font (8x16) into a CP437-ordered font ROM. Output is a $readmemh file with 4096 lines: byte (code*16 + row), MSB = leftmost pixel. usage: psf2mem.py [font.psf.gz[,fallback.psf.gz...]] [out.mem] [preview.png] Glyphs missing from the first font are taken from the fallbacks in order. """ import gzip import struct import sys CP437_LOW = ("\u0000☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼") DEFAULT_FONTS = ",".join("/usr/share/consolefonts/%s.psf.gz" % f for f in ("Uni2-VGA16", "FullGreek-VGA16", "Vietnamese-TerminusBoldVGA16")) # Fonts often carry the triangle pointers under their newer code points. CP437_ALT = {"►": "▶", "◄": "◀"} def cp437(code): if code < 0x20: return CP437_LOW[code] if code == 0x7F: return "⌂" return bytes([code]).decode("cp437") def load_psf(path): raw = gzip.open(path).read() if path.endswith(".gz") else open(path, "rb").read() if raw[:2] == b"\x36\x04": mode, charsize = raw[2], raw[3] count = 512 if mode & 1 else 256 width, height, hdr = 8, charsize, 4 has_table = bool(mode & 6) glyphs = [raw[hdr + i * charsize: hdr + (i + 1) * charsize] for i in range(count)] table = {} if has_table: pos, g = hdr + count * charsize, 0 while g < count and pos + 1 < len(raw): (u,) = struct.unpack_from(" 1 and sys.argv[1] else DEFAULT_FONTS out = sys.argv[2] if len(sys.argv) > 2 else "font.mem" fonts = [] for path in src.split(","): glyphs, table, width, height = load_psf(path) if width != 8 or height != 16: raise SystemExit(f"{path}: need an 8x16 font, got {width}x{height}") fonts.append((glyphs, table)) missing = [] rom = [] for code in range(256): ch = cp437(code) glyph = None if code not in (0, 0x20): for glyphs, table in fonts: g = table.get(ch, code if not table else None) if g is None and ch in CP437_ALT: g = table.get(CP437_ALT[ch]) if g is not None: glyph = glyphs[g][:16] break if glyph is None: missing.append(f"{code:02X}") rom.extend(glyph or [0] * 16) with open(out, "w") as f: f.write("// CP437 order, 256 glyphs x 16 rows, from: %s\n" % ", ".join(p.split("/")[-1] for p in src.split(","))) for b in rom: f.write(f"{b:02x}\n") print(f"wrote {out}; glyphs missing: {' '.join(missing) or 'none'}") if len(sys.argv) > 3: from PIL import Image img = Image.new("1", (32 * 9, 8 * 17), 0) for code in range(256): ox, oy = (code % 32) * 9, (code // 32) * 17 for r in range(16): for c in range(8): if rom[code * 16 + r] & (0x80 >> c): img.putpixel((ox + c, oy + r), 1) img.save(sys.argv[3]) if __name__ == "__main__": main()