#!/usr/bin/env python3 """Exact text width from a GRUB pf2 font (what GRUB itself uses).""" import struct def load_pf2(path): data = open(path, 'rb').read() if data[:4] != b'FILE': raise ValueError('not a pf2 file') pos = 12 sec = {} while pos + 8 <= len(data): name = data[pos:pos + 4] length = struct.unpack('>I', data[pos + 4:pos + 8])[0] sec[name] = data[pos + 8:pos + 8 + length] pos += 8 + length chix = sec.get(b'CHIX', b'') dat = sec.get(b'DATA', b'') widths = {} for i in range(len(chix) // 8): code, off = struct.unpack('>II', chix[i * 8:(i + 1) * 8]) rec = dat[off:off + 16] if len(rec) < 16: continue _w, _h, _xo, _yo, dw, _dh, _dxo, _dyo = struct.unpack('>HHhhhhhh', rec) widths[chr(code)] = dw return widths if __name__ == '__main__': import sys w = load_pf2(sys.argv[1]) for ch in ' Aa1(9)': print(repr(ch), w.get(ch)) print('space width:', w.get(' '), '| glyphs:', len(w)) print('thin spaces:', w.get('\u2009'), w.get('\u200a'), w.get('\u00a0'))