1#! /usr/bin/env python 2 3from __future__ import print_function, division, absolute_import 4from fontTools.misc.py23 import * 5from fontTools.ttLib import TTFont 6import sys 7 8if len(sys.argv) < 2: 9 print("usage: subset-fpgm.py fontfile.ttf func-number...") 10 sys.exit(1) 11fontfile = sys.argv[1] 12func_nums = [int(x) for x in sys.argv[2:]] 13 14font = TTFont(fontfile) 15fpgm = font['fpgm'] 16 17# Parse fpgm 18asm = fpgm.program.getAssembly() 19funcs = {} 20stack = [] 21tokens = iter(asm) 22for token in tokens: 23 if token.startswith("PUSH") or token.startswith("NPUSH"): 24 for token in tokens: 25 try: 26 num = int(token) 27 stack.append(num) 28 except ValueError: 29 break 30 if token.startswith("FDEF"): 31 num = stack.pop() 32 body = [] 33 for token in tokens: 34 if token.startswith("ENDF"): 35 break 36 body.append(token) 37 funcs[num] = body 38 continue 39 assert 0, "Unexpected token in fpgm: %s" % token 40 41# Subset! 42funcs = {i:funcs[i] for i in func_nums} 43 44# Put it back together: 45asm = [] 46if funcs: 47 asm.append("PUSH[ ]") 48nums = sorted(funcs.keys()) 49asm.extend(str(i) for i in nums) 50for i in nums: 51 asm.append("FDEF[ ]") 52 asm.extend(funcs[i]) 53 asm.append("ENDF[ ]") 54 55import pprint 56pprint.pprint(asm) 57 58fpgm.program.fromAssembly(asm) 59# Make sure it compiles 60fpgm.program.getBytecode() 61