Skip to content

Instantly share code, notes, and snippets.

@anthrotype
Created March 31, 2015 18:29
Show Gist options
  • Select an option

  • Save anthrotype/98dfa654be415a7d0cfc to your computer and use it in GitHub Desktop.

Select an option

Save anthrotype/98dfa654be415a7d0cfc to your computer and use it in GitHub Desktop.
fontTools WOFF2 glyf table roundtrip test
#!/usr/bin/env python
"""
Test that reconstructed 'glyf' and 'loca' table data are bitwise identical to
the original, 'normalised' table data.
"""
from __future__ import print_function
import sys
import struct
from fontTools.misc.py23 import *
from fontTools.ttLib import TTFont
from fontTools.ttLib import woff2
from fontTools.ttLib.sfnt import calcChecksum
def pretty_print_tables(glyfData, locaData, indexFormat):
glyfCheckSum = "0x%08X" % calcChecksum(glyfData)
locaCheckSum = "0x%08X" % calcChecksum(locaData)
print(" glyf.length ", len(glyfData))
print(" glyf.checkSum ", glyfCheckSum)
print(" loca.length ", len(locaData))
print(" loca.checkSum ", locaCheckSum)
print(" indexFormat ", indexFormat)
def main():
if not sys.argv[1:]:
print("No input font")
sys.exit(1)
infile = sys.argv[1]
font = TTFont(infile, recalcTimestamp=False, checkChecksums=1)
if font.sfntVersion != "\000\001\000\000":
print("Not a TrueType font")
sys.exit(1)
print("Read original 'glyf' and 'loca' tables...")
glyfData = font.reader['glyf']
locaData = font.reader['loca']
indexFormat, = struct.unpack(">H", font.reader['head'][50:52])
pretty_print_tables(glyfData, locaData, indexFormat)
print("Normalise 'glyf' and 'loca' tables...")
font.flavor = "woff2"
font.recalcBBoxes = True
font.lazy = False # 'expand' glyph data on decompile
if not font.isLoaded('glyf'):
font['glyf']
glyfData = font.getTableData('glyf')
locaData = font.getTableData('loca')
indexFormat = font['head'].indexToLocFormat
pretty_print_tables(glyfData, locaData, indexFormat)
print("Transform 'glyf' and 'loca' tables...")
encoder = woff2.WOFF2GlyfTable()
encoder.setLocaData(locaData, indexFormat, font['maxp'].numGlyphs)
transformedGlyfData = encoder.transform(glyfData)
transformedLocaData = b""
pretty_print_tables(transformedGlyfData, transformedLocaData,
indexFormat)
print("Reconstruct 'glyf' and 'loca' tables...")
decoder = woff2.WOFF2GlyfTable()
reconstructedGlyfData = decoder.reconstruct(transformedGlyfData)
reconstructedLocaData = decoder.getLocaData()
pretty_print_tables(reconstructedGlyfData, reconstructedLocaData,
decoder.indexFormat)
if (glyfData != reconstructedGlyfData or
locaData != reconstructedLocaData):
print("FAILED: reconstructed tables are different from normalised ones")
else:
print("OK: reconstructed tables are identical to normalised ones")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment