1from fontTools.ttLib.tables import otTables as ot 2from .table_builder import TableUnbuilder 3 4 5def unbuildColrV1(layerV1List, baseGlyphV1List): 6 unbuilder = LayerV1ListUnbuilder(layerV1List.Paint) 7 return { 8 rec.BaseGlyph: unbuilder.unbuildPaint(rec.Paint) 9 for rec in baseGlyphV1List.BaseGlyphV1Record 10 } 11 12 13def _flatten(lst): 14 for el in lst: 15 if isinstance(el, list): 16 yield from _flatten(el) 17 else: 18 yield el 19 20 21class LayerV1ListUnbuilder: 22 def __init__(self, layers): 23 self.layers = layers 24 25 callbacks = { 26 ( 27 ot.Paint, 28 ot.PaintFormat.PaintColrLayers, 29 ): self._unbuildPaintColrLayers, 30 } 31 self.tableUnbuilder = TableUnbuilder(callbacks) 32 33 def unbuildPaint(self, paint): 34 assert isinstance(paint, ot.Paint) 35 return self.tableUnbuilder.unbuild(paint) 36 37 def _unbuildPaintColrLayers(self, source): 38 assert source["Format"] == ot.PaintFormat.PaintColrLayers 39 40 layers = list( 41 _flatten( 42 [ 43 self.unbuildPaint(childPaint) 44 for childPaint in self.layers[ 45 source["FirstLayerIndex"] : source["FirstLayerIndex"] 46 + source["NumLayers"] 47 ] 48 ] 49 ) 50 ) 51 52 if len(layers) == 1: 53 return layers[0] 54 55 return {"Format": source["Format"], "Layers": layers} 56 57 58if __name__ == "__main__": 59 from pprint import pprint 60 import sys 61 from fontTools.ttLib import TTFont 62 63 try: 64 fontfile = sys.argv[1] 65 except IndexError: 66 sys.exit("usage: fonttools colorLib.unbuilder FONTFILE") 67 68 font = TTFont(fontfile) 69 colr = font["COLR"] 70 if colr.version < 1: 71 sys.exit(f"error: No COLR table version=1 found in {fontfile}") 72 73 colorGlyphs = unbuildColrV1( 74 colr.table.LayerV1List, 75 colr.table.BaseGlyphV1List, 76 ignoreVarIdx=not colr.table.VarStore, 77 ) 78 79 pprint(colorGlyphs) 80