Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/__init__.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/__main__.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/macUtils.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/removeOverlaps.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/reorderGlyphs.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/scaleUpem.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/sfnt.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/standardGlyphOrder.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/ttCollection.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/ttFont.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/ttGlyphSet.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/ttVisitor.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/woff2.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/BitmapGlyphMetrics.pyAdded+64
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/C_F_F_.pyAdded+61
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/C_F_F__2.pyAdded+26
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/C_O_L_R_.pyAdded+165
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/C_P_A_L_.pyAdded+305
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/D__e_b_g.pyAdded+35
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/DefaultTable.pyAdded+63
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/G_D_E_F_.pyAdded+13
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/G_V_A_R_.pyAdded+5
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/G__l_o_c.pyAdded+85
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/H_V_A_R_.pyAdded+13
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/J_S_T_F_.pyAdded+13
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/L_T_S_H_.pyAdded+58
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/M_V_A_R_.pyAdded+13
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/O_S_2f_2.pyAdded+752
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/S_T_A_T_.pyAdded+15
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/S__i_l_l.pyAdded+92
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I_C_.pyAdded+14
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I_S_.pyAdded+13
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I__0.pyAdded+70
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I__1.pyAdded+163
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I__2.pyAdded+17
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I__3.pyAdded+22
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I__5.pyAdded+60
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/V_A_R_C_.pyAdded+12
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/V_O_R_G_.pyAdded+165
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__init__.pyAdded+94
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/B_A_S_E_.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F_.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F__2.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/C_P_A_L_.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/E_B_D_T_.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/E_B_L_C_.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/F_F_T_M_.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/F__e_a_t.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/G__l_a_t.cpython-311.pycAdded
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/H_V_A_R_.cpython-311.pycAdded
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# Since bitmap glyph metrics are shared between EBLC and EBDT# this class gets its own python file.from fontTools.misc import sstructfrom fontTools.misc.textTools import safeEvalimport logging
log = logging.getLogger(__name__)
bigGlyphMetricsFormat = """ > # big endian height: B width: B horiBearingX: b horiBearingY: b horiAdvance: B vertBearingX: b vertBearingY: b vertAdvance: B"""
smallGlyphMetricsFormat = """ > # big endian height: B width: B BearingX: b BearingY: b Advance: B"""
class BitmapGlyphMetrics(object): def toXML(self, writer, ttFont): writer.begintag(self.__class__.__name__) writer.newline() for metricName in sstruct.getformat(self.__class__.binaryFormat)[1]: writer.simpletag(metricName, value=getattr(self, metricName)) writer.newline() writer.endtag(self.__class__.__name__) writer.newline()
def fromXML(self, name, attrs, content, ttFont): metricNames = set(sstruct.getformat(self.__class__.binaryFormat)[1]) for element in content: if not isinstance(element, tuple): continue name, attrs, content = element # Make sure this is a metric that is needed by GlyphMetrics. if name in metricNames: vars(self)[name] = safeEval(attrs["value"]) else: log.warning( "unknown name '%s' being ignored in %s.", name, self.__class__.__name__, )
class BigGlyphMetrics(BitmapGlyphMetrics): binaryFormat = bigGlyphMetricsFormat
class SmallGlyphMetrics(BitmapGlyphMetrics): binaryFormat = smallGlyphMetricsFormat12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061from io import BytesIOfrom fontTools import cffLibfrom . import DefaultTable
class table_C_F_F_(DefaultTable.DefaultTable): """Compact Font Format table (version 1)
The ``CFF`` table embeds a CFF-formatted font. The CFF font format predates OpenType and could be used as a standalone font file, but the ``CFF`` table is also used to package CFF fonts into an OpenType container.
.. note:: ``CFF`` has been succeeded by ``CFF2``, which eliminates much of the redundancy incurred by embedding CFF version 1 in an OpenType font.
See also https://learn.microsoft.com/en-us/typography/opentype/spec/cff """
def __init__(self, tag=None): DefaultTable.DefaultTable.__init__(self, tag) self.cff = cffLib.CFFFontSet() self._gaveGlyphOrder = False
def decompile(self, data, otFont): self.cff.decompile(BytesIO(data), otFont, isCFF2=False) assert len(self.cff) == 1, "can't deal with multi-font CFF tables."
def compile(self, otFont): f = BytesIO() self.cff.compile(f, otFont, isCFF2=False) return f.getvalue()
def haveGlyphNames(self): if hasattr(self.cff[self.cff.fontNames[0]], "ROS"): return False # CID-keyed font else: return True
def getGlyphOrder(self): if self._gaveGlyphOrder: from fontTools import ttLib
raise ttLib.TTLibError("illegal use of getGlyphOrder()") self._gaveGlyphOrder = True return self.cff[self.cff.fontNames[0]].getGlyphOrder()
def setGlyphOrder(self, glyphOrder): pass # XXX # self.cff[self.cff.fontNames[0]].setGlyphOrder(glyphOrder)
def toXML(self, writer, otFont): self.cff.toXML(writer)
def fromXML(self, name, attrs, content, otFont): if not hasattr(self, "cff"): self.cff = cffLib.CFFFontSet() self.cff.fromXML(name, attrs, content, otFont)1234567891011121314151617181920212223242526from io import BytesIOfrom fontTools.ttLib.tables.C_F_F_ import table_C_F_F_
class table_C_F_F__2(table_C_F_F_): """Compact Font Format version 2 table
The ``CFF2`` table contains glyph data for a CFF2-flavored OpenType font.
.. note:: ``CFF2`` is the successor to ``CFF``, and eliminates much of the redundancy incurred by embedding CFF version 1 in an OpenType font.
See also https://learn.microsoft.com/en-us/typography/opentype/spec/cff2 """
def decompile(self, data, otFont): self.cff.decompile(BytesIO(data), otFont, isCFF2=True) assert len(self.cff) == 1, "can't deal with multi-font CFF tables."
def compile(self, otFont): f = BytesIO() self.cff.compile(f, otFont, isCFF2=True) return f.getvalue()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165# Copyright 2013 Google, Inc. All Rights Reserved.## Google Author(s): Behdad Esfahbod
from fontTools.misc.textTools import safeEvalfrom . import DefaultTable
class table_C_O_L_R_(DefaultTable.DefaultTable): """Color table
The ``COLR`` table defines color presentation of outline glyphs. It must be used in concert with the ``CPAL`` table, which contains the color descriptors used.
This table is structured so that you can treat it like a dictionary keyed by glyph name.
``ttFont['COLR'][<glyphName>]`` will return the color layers for any glyph.
``ttFont['COLR'][<glyphName>] = <value>`` will set the color layers for any glyph.
See also https://learn.microsoft.com/en-us/typography/opentype/spec/colr """
@staticmethod def _decompileColorLayersV0(table): if not table.LayerRecordArray: return {} colorLayerLists = {} layerRecords = table.LayerRecordArray.LayerRecord numLayerRecords = len(layerRecords) for baseRec in table.BaseGlyphRecordArray.BaseGlyphRecord: baseGlyph = baseRec.BaseGlyph firstLayerIndex = baseRec.FirstLayerIndex numLayers = baseRec.NumLayers assert firstLayerIndex + numLayers <= numLayerRecords layers = [] for i in range(firstLayerIndex, firstLayerIndex + numLayers): layerRec = layerRecords[i] layers.append(LayerRecord(layerRec.LayerGlyph, layerRec.PaletteIndex)) colorLayerLists[baseGlyph] = layers return colorLayerLists
def _toOTTable(self, ttFont): from . import otTables from fontTools.colorLib.builder import populateCOLRv0
tableClass = getattr(otTables, self.tableTag) table = tableClass() table.Version = self.version
populateCOLRv0( table, { baseGlyph: [(layer.name, layer.colorID) for layer in layers] for baseGlyph, layers in self.ColorLayers.items() }, glyphMap=ttFont.getReverseGlyphMap(rebuild=True), ) return table
def decompile(self, data, ttFont): from .otBase import OTTableReader from . import otTables
# We use otData to decompile, but we adapt the decompiled otTables to the # existing COLR v0 API for backward compatibility. reader = OTTableReader(data, tableTag=self.tableTag) tableClass = getattr(otTables, self.tableTag) table = tableClass() table.decompile(reader, ttFont)
self.version = table.Version if self.version == 0: self.ColorLayers = self._decompileColorLayersV0(table) else: # for new versions, keep the raw otTables around self.table = table
def compile(self, ttFont): from .otBase import OTTableWriter
if hasattr(self, "table"): table = self.table else: table = self._toOTTable(ttFont)
writer = OTTableWriter(tableTag=self.tableTag) table.compile(writer, ttFont) return writer.getAllData()
def toXML(self, writer, ttFont): if hasattr(self, "table"): self.table.toXML2(writer, ttFont) else: writer.simpletag("version", value=self.version) writer.newline() for baseGlyph in sorted(self.ColorLayers.keys(), key=ttFont.getGlyphID): writer.begintag("ColorGlyph", name=baseGlyph) writer.newline() for layer in self.ColorLayers[baseGlyph]: layer.toXML(writer, ttFont) writer.endtag("ColorGlyph") writer.newline()
def fromXML(self, name, attrs, content, ttFont): if name == "version": # old COLR v0 API setattr(self, name, safeEval(attrs["value"])) elif name == "ColorGlyph": if not hasattr(self, "ColorLayers"): self.ColorLayers = {} glyphName = attrs["name"] for element in content: if isinstance(element, str): continue layers = [] for element in content: if isinstance(element, str): continue layer = LayerRecord() layer.fromXML(element[0], element[1], element[2], ttFont) layers.append(layer) self.ColorLayers[glyphName] = layers else: # new COLR v1 API from . import otTables
if not hasattr(self, "table"): tableClass = getattr(otTables, self.tableTag) self.table = tableClass() self.table.fromXML(name, attrs, content, ttFont) self.table.populateDefaults() self.version = self.table.Version
def __getitem__(self, glyphName): if not isinstance(glyphName, str): raise TypeError(f"expected str, found {type(glyphName).__name__}") return self.ColorLayers[glyphName]
def __setitem__(self, glyphName, value): if not isinstance(glyphName, str): raise TypeError(f"expected str, found {type(glyphName).__name__}") if value is not None: self.ColorLayers[glyphName] = value elif glyphName in self.ColorLayers: del self.ColorLayers[glyphName]
def __delitem__(self, glyphName): del self.ColorLayers[glyphName]
class LayerRecord(object): def __init__(self, name=None, colorID=None): self.name = name self.colorID = colorID
def toXML(self, writer, ttFont): writer.simpletag("layer", name=self.name, colorID=self.colorID) writer.newline()
def fromXML(self, eltname, attrs, content, ttFont): for name, value in attrs.items(): if name == "name": setattr(self, name, value) else: setattr(self, name, safeEval(value))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305# Copyright 2013 Google, Inc. All Rights Reserved.## Google Author(s): Behdad Esfahbod
from fontTools.misc.textTools import bytesjoin, safeEvalfrom . import DefaultTableimport arrayfrom collections import namedtupleimport structimport sys
class table_C_P_A_L_(DefaultTable.DefaultTable): """Color Palette table
The ``CPAL`` table contains a set of one or more color palettes. The color records in each palette can be referenced by the ``COLR`` table to specify the colors used in a color glyph.
See also https://learn.microsoft.com/en-us/typography/opentype/spec/cpal """
NO_NAME_ID = 0xFFFF DEFAULT_PALETTE_TYPE = 0
def __init__(self, tag=None): DefaultTable.DefaultTable.__init__(self, tag) self.palettes = [] self.paletteTypes = [] self.paletteLabels = [] self.paletteEntryLabels = []
def decompile(self, data, ttFont): ( self.version, self.numPaletteEntries, numPalettes, numColorRecords, goffsetFirstColorRecord, ) = struct.unpack(">HHHHL", data[:12]) assert ( self.version <= 1 ), "Version of CPAL table is higher than I know how to handle" self.palettes = [] pos = 12 for i in range(numPalettes): startIndex = struct.unpack(">H", data[pos : pos + 2])[0] assert startIndex + self.numPaletteEntries <= numColorRecords pos += 2 palette = [] ppos = goffsetFirstColorRecord + startIndex * 4 for j in range(self.numPaletteEntries): palette.append(Color(*struct.unpack(">BBBB", data[ppos : ppos + 4]))) ppos += 4 self.palettes.append(palette) if self.version == 0: offsetToPaletteTypeArray = 0 offsetToPaletteLabelArray = 0 offsetToPaletteEntryLabelArray = 0 else: pos = 12 + numPalettes * 2 ( offsetToPaletteTypeArray, offsetToPaletteLabelArray, offsetToPaletteEntryLabelArray, ) = struct.unpack(">LLL", data[pos : pos + 12]) self.paletteTypes = self._decompileUInt32Array( data, offsetToPaletteTypeArray, numPalettes, default=self.DEFAULT_PALETTE_TYPE, ) self.paletteLabels = self._decompileUInt16Array( data, offsetToPaletteLabelArray, numPalettes, default=self.NO_NAME_ID ) self.paletteEntryLabels = self._decompileUInt16Array( data, offsetToPaletteEntryLabelArray, self.numPaletteEntries, default=self.NO_NAME_ID, )
def _decompileUInt16Array(self, data, offset, numElements, default=0): if offset == 0: return [default] * numElements result = array.array("H", data[offset : offset + 2 * numElements]) if sys.byteorder != "big": result.byteswap() assert len(result) == numElements, result return result.tolist()
def _decompileUInt32Array(self, data, offset, numElements, default=0): if offset == 0: return [default] * numElements result = array.array("I", data[offset : offset + 4 * numElements]) if sys.byteorder != "big": result.byteswap() assert len(result) == numElements, result return result.tolist()
def compile(self, ttFont): colorRecordIndices, colorRecords = self._compileColorRecords() paletteTypes = self._compilePaletteTypes() paletteLabels = self._compilePaletteLabels() paletteEntryLabels = self._compilePaletteEntryLabels() numColorRecords = len(colorRecords) // 4 offsetToFirstColorRecord = 12 + len(colorRecordIndices) if self.version >= 1: offsetToFirstColorRecord += 12 header = struct.pack( ">HHHHL", self.version, self.numPaletteEntries, len(self.palettes), numColorRecords, offsetToFirstColorRecord, ) if self.version == 0: dataList = [header, colorRecordIndices, colorRecords] else: pos = offsetToFirstColorRecord + len(colorRecords) if len(paletteTypes) == 0: offsetToPaletteTypeArray = 0 else: offsetToPaletteTypeArray = pos pos += len(paletteTypes) if len(paletteLabels) == 0: offsetToPaletteLabelArray = 0 else: offsetToPaletteLabelArray = pos pos += len(paletteLabels) if len(paletteEntryLabels) == 0: offsetToPaletteEntryLabelArray = 0 else: offsetToPaletteEntryLabelArray = pos pos += len(paletteLabels) header1 = struct.pack( ">LLL", offsetToPaletteTypeArray, offsetToPaletteLabelArray, offsetToPaletteEntryLabelArray, ) dataList = [ header, colorRecordIndices, header1, colorRecords, paletteTypes, paletteLabels, paletteEntryLabels, ] return bytesjoin(dataList)
def _compilePalette(self, palette): assert len(palette) == self.numPaletteEntries pack = lambda c: struct.pack(">BBBB", c.blue, c.green, c.red, c.alpha) return bytesjoin([pack(color) for color in palette])
def _compileColorRecords(self): colorRecords, colorRecordIndices, pool = [], [], {} for palette in self.palettes: packedPalette = self._compilePalette(palette) if packedPalette in pool: index = pool[packedPalette] else: index = len(colorRecords) colorRecords.append(packedPalette) pool[packedPalette] = index colorRecordIndices.append(struct.pack(">H", index * self.numPaletteEntries)) return bytesjoin(colorRecordIndices), bytesjoin(colorRecords)
def _compilePaletteTypes(self): if self.version == 0 or not any(self.paletteTypes): return b"" assert len(self.paletteTypes) == len(self.palettes) result = bytesjoin([struct.pack(">I", ptype) for ptype in self.paletteTypes]) assert len(result) == 4 * len(self.palettes) return result
def _compilePaletteLabels(self): if self.version == 0 or all(l == self.NO_NAME_ID for l in self.paletteLabels): return b"" assert len(self.paletteLabels) == len(self.palettes) result = bytesjoin([struct.pack(">H", label) for label in self.paletteLabels]) assert len(result) == 2 * len(self.palettes) return result
def _compilePaletteEntryLabels(self): if self.version == 0 or all( l == self.NO_NAME_ID for l in self.paletteEntryLabels ): return b"" assert len(self.paletteEntryLabels) == self.numPaletteEntries result = bytesjoin( [struct.pack(">H", label) for label in self.paletteEntryLabels] ) assert len(result) == 2 * self.numPaletteEntries return result
def toXML(self, writer, ttFont): numPalettes = len(self.palettes) paletteLabels = {i: nameID for (i, nameID) in enumerate(self.paletteLabels)} paletteTypes = {i: typ for (i, typ) in enumerate(self.paletteTypes)} writer.simpletag("version", value=self.version) writer.newline() writer.simpletag("numPaletteEntries", value=self.numPaletteEntries) writer.newline() for index, palette in enumerate(self.palettes): attrs = {"index": index} paletteType = paletteTypes.get(index, self.DEFAULT_PALETTE_TYPE) paletteLabel = paletteLabels.get(index, self.NO_NAME_ID) if self.version > 0 and paletteLabel != self.NO_NAME_ID: attrs["label"] = paletteLabel if self.version > 0 and paletteType != self.DEFAULT_PALETTE_TYPE: attrs["type"] = paletteType writer.begintag("palette", **attrs) writer.newline() if ( self.version > 0 and paletteLabel != self.NO_NAME_ID and ttFont and "name" in ttFont ): name = ttFont["name"].getDebugName(paletteLabel) if name is not None: writer.comment(name) writer.newline() assert len(palette) == self.numPaletteEntries for cindex, color in enumerate(palette): color.toXML(writer, ttFont, cindex) writer.endtag("palette") writer.newline() if self.version > 0 and not all( l == self.NO_NAME_ID for l in self.paletteEntryLabels ): writer.begintag("paletteEntryLabels") writer.newline() for index, label in enumerate(self.paletteEntryLabels): if label != self.NO_NAME_ID: writer.simpletag("label", index=index, value=label) if self.version > 0 and label and ttFont and "name" in ttFont: name = ttFont["name"].getDebugName(label) if name is not None: writer.comment(name) writer.newline() writer.endtag("paletteEntryLabels") writer.newline()
def fromXML(self, name, attrs, content, ttFont): if name == "palette": self.paletteLabels.append(int(attrs.get("label", self.NO_NAME_ID))) self.paletteTypes.append(int(attrs.get("type", self.DEFAULT_PALETTE_TYPE))) palette = [] for element in content: if isinstance(element, str): continue attrs = element[1] color = Color.fromHex(attrs["value"]) palette.append(color) self.palettes.append(palette) elif name == "paletteEntryLabels": colorLabels = {} for element in content: if isinstance(element, str): continue elementName, elementAttr, _ = element if elementName == "label": labelIndex = safeEval(elementAttr["index"]) nameID = safeEval(elementAttr["value"]) colorLabels[labelIndex] = nameID self.paletteEntryLabels = [ colorLabels.get(i, self.NO_NAME_ID) for i in range(self.numPaletteEntries) ] elif "value" in attrs: value = safeEval(attrs["value"]) setattr(self, name, value) if name == "numPaletteEntries": self.paletteEntryLabels = [self.NO_NAME_ID] * self.numPaletteEntries
class Color(namedtuple("Color", "blue green red alpha")): def hex(self): return "#%02X%02X%02X%02X" % (self.red, self.green, self.blue, self.alpha)
def __repr__(self): return self.hex()
def toXML(self, writer, ttFont, index=None): writer.simpletag("color", value=self.hex(), index=index) writer.newline()
@classmethod def fromHex(cls, value): if value[0] == "#": value = value[1:] red = int(value[0:2], 16) green = int(value[2:4], 16) blue = int(value[4:6], 16) alpha = int(value[6:8], 16) if len(value) >= 8 else 0xFF return cls(red=red, green=green, blue=blue, alpha=alpha)
@classmethod def fromRGBA(cls, red, green, blue, alpha): return cls(red=red, green=green, blue=blue, alpha=alpha)1234567891011121314151617181920212223242526272829303132333435import jsonfrom textwrap import indent
from . import DefaultTablefrom fontTools.misc.textTools import tostr
class table_D__e_b_g(DefaultTable.DefaultTable): def __init__(self, tag=None): DefaultTable.DefaultTable.__init__(self, tag) self.data = {}
def decompile(self, data, ttFont): self.data = json.loads(data)
def compile(self, ttFont): return json.dumps(self.data).encode("utf-8")
def toXML(self, writer, ttFont): # make sure json indentation inside CDATA block matches XMLWriter's data = json.dumps(self.data, indent=len(writer.indentwhite)) prefix = tostr(writer.indentwhite) * (writer.indentlevel + 1) # but don't indent the first json line so it's adjacent to `<![CDATA[{` cdata = indent(data, prefix, lambda ln: ln != "{\n")
writer.begintag("json") writer.newline() writer.writecdata(cdata) writer.newline() writer.endtag("json") writer.newline()
def fromXML(self, name, attrs, content, ttFont): if name == "json": self.data = json.loads("".join(content))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263from __future__ import annotations
from typing import TYPE_CHECKING
from fontTools.misc.textTools import Tagfrom fontTools.ttLib import getClassTag
if TYPE_CHECKING: from typing import Any
from fontTools.misc.xmlWriter import XMLWriter from fontTools.ttLib import TTFont
class DefaultTable: dependencies: list[str] = []
def __init__(self, tag: str | bytes | None = None) -> None: if tag is None: tag = getClassTag(self.__class__) self.tableTag = Tag(tag)
def decompile(self, data: bytes, ttFont: TTFont) -> None: self.data = data
def compile(self, ttFont: TTFont) -> bytes: return self.data
def toXML( self, writer: XMLWriter, ttFont: TTFont, **kwargs: dict[str, Any] ) -> None: if hasattr(self, "ERROR"): writer.comment("An error occurred during the decompilation of this table") writer.newline() writer.comment(self.ERROR) writer.newline() writer.begintag("hexdata") writer.newline() writer.dumphex(self.compile(ttFont)) writer.endtag("hexdata") writer.newline()
def fromXML( self, name: str, attrs: dict[str, str], content: str, ttFont: TTFont ) -> None: from fontTools import ttLib from fontTools.misc.textTools import readHex
if name != "hexdata": raise ttLib.TTLibError("can't handle '%s' element" % name) self.decompile(readHex(content), ttFont)
def __repr__(self) -> str: return "<'%s' table at %x>" % (self.tableTag, id(self))
def __eq__(self, other: Any) -> bool: if type(self) != type(other): return NotImplemented return self.__dict__ == other.__dict__
def __ne__(self, other: Any) -> bool: result = self.__eq__(other) return result if result is NotImplemented else not result12345678910111213from .otBase import BaseTTXConverter
class table_G_D_E_F_(BaseTTXConverter): """Glyph Definition table
The ``GDEF`` table stores various glyph properties that are used by OpenType Layout.
See also https://learn.microsoft.com/en-us/typography/opentype/spec/gdef """
pass12345from ._g_v_a_r import table__g_v_a_r
class table_G_V_A_R_(table__g_v_a_r): gid_size = 312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485from fontTools.misc import sstructfrom fontTools.misc.textTools import safeEvalfrom . import DefaultTableimport arrayimport sys
Gloc_header = """ > # big endian version: 16.16F # Table version flags: H # bit 0: 1=long format, 0=short format # bit 1: 1=attribute names, 0=no names numAttribs: H # NUmber of attributes"""
class table_G__l_o_c(DefaultTable.DefaultTable): """Graphite Index to Glyph Atttributes table
See also https://graphite.sil.org/graphite_techAbout#graphite-font-tables """
dependencies = ["Glat"]
def __init__(self, tag=None): DefaultTable.DefaultTable.__init__(self, tag) self.attribIds = None self.numAttribs = 0
def decompile(self, data, ttFont): _, data = sstruct.unpack2(Gloc_header, data, self) flags = self.flags del self.flags self.locations = array.array("I" if flags & 1 else "H") self.locations.frombytes(data[: len(data) - self.numAttribs * (flags & 2)]) if sys.byteorder != "big": self.locations.byteswap() self.attribIds = array.array("H") if flags & 2: self.attribIds.frombytes(data[-self.numAttribs * 2 :]) if sys.byteorder != "big": self.attribIds.byteswap()
def compile(self, ttFont): data = sstruct.pack( Gloc_header, dict( version=1.0, flags=(bool(self.attribIds) << 1) + (self.locations.typecode == "I"), numAttribs=self.numAttribs, ), ) if sys.byteorder != "big": self.locations.byteswap() data += self.locations.tobytes() if sys.byteorder != "big": self.locations.byteswap() if self.attribIds: if sys.byteorder != "big": self.attribIds.byteswap() data += self.attribIds.tobytes() if sys.byteorder != "big": self.attribIds.byteswap() return data
def set(self, locations): long_format = max(locations) >= 65536 self.locations = array.array("I" if long_format else "H", locations)
def toXML(self, writer, ttFont): writer.simpletag("attributes", number=self.numAttribs) writer.newline()
def fromXML(self, name, attrs, content, ttFont): if name == "attributes": self.numAttribs = int(safeEval(attrs["number"]))
def __getitem__(self, index): return self.locations[index]
def __len__(self): return len(self.locations)
def __iter__(self): return iter(self.locations)12345678910111213from .otBase import BaseTTXConverter
class table_H_V_A_R_(BaseTTXConverter): """Horizontal Metrics Variations table
The ``HVAR`` table contains variations in horizontal glyph metrics in variable fonts.
See also https://learn.microsoft.com/en-us/typography/opentype/spec/hvar """
pass12345678910111213from .otBase import BaseTTXConverter
class table_J_S_T_F_(BaseTTXConverter): """Justification table
The ``JSTF`` table contains glyph substitution and positioning data used to perform text justification.
See also https://learn.microsoft.com/en-us/typography/opentype/spec/jstf """
pass12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758from fontTools.misc.textTools import safeEvalfrom . import DefaultTableimport structimport array
# XXX I've lowered the strictness, to make sure Apple's own Chicago# XXX gets through. They're looking into it, I hope to raise the standards# XXX back to normal eventually.
class table_L_T_S_H_(DefaultTable.DefaultTable): """Linear Threshold table
The ``LTSH`` table contains per-glyph settings indicating the ppem sizes at which the advance width metric should be scaled linearly, despite the effects of any TrueType instructions that might otherwise alter the advance width.
See also https://learn.microsoft.com/en-us/typography/opentype/spec/ltsh """
def decompile(self, data, ttFont): version, numGlyphs = struct.unpack(">HH", data[:4]) data = data[4:] assert version == 0, "unknown version: %s" % version assert (len(data) % numGlyphs) < 4, "numGlyphs doesn't match data length" # ouch: the assertion is not true in Chicago! # assert numGlyphs == ttFont['maxp'].numGlyphs yPels = array.array("B") yPels.frombytes(data) self.yPels = {} for i in range(numGlyphs): self.yPels[ttFont.getGlyphName(i)] = yPels[i]
def compile(self, ttFont): version = 0 names = list(self.yPels.keys()) numGlyphs = len(names) yPels = [0] * numGlyphs # ouch: the assertion is not true in Chicago! # assert len(self.yPels) == ttFont['maxp'].numGlyphs == numGlyphs for name in names: yPels[ttFont.getGlyphID(name)] = self.yPels[name] yPels = array.array("B", yPels) return struct.pack(">HH", version, numGlyphs) + yPels.tobytes()
def toXML(self, writer, ttFont): names = sorted(self.yPels.keys()) for name in names: writer.simpletag("yPel", name=name, value=self.yPels[name]) writer.newline()
def fromXML(self, name, attrs, content, ttFont): if not hasattr(self, "yPels"): self.yPels = {} if name != "yPel": return # ignore unknown tags self.yPels[attrs["name"]] = safeEval(attrs["value"])12345678910111213from .otBase import BaseTTXConverter
class table_M_V_A_R_(BaseTTXConverter): """Metrics Variations table
The ``MVAR`` table contains variation information for font-wide metrics in a variable font.
See also https://learn.microsoft.com/en-us/typography/opentype/spec/mvar """
pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752from fontTools.misc import sstructfrom fontTools.misc.roundTools import otRoundfrom fontTools.misc.textTools import safeEval, num2binary, binary2numfrom fontTools.ttLib.tables import DefaultTableimport bisectimport logging
log = logging.getLogger(__name__)
# panose classification
panoseFormat = """ bFamilyType: B bSerifStyle: B bWeight: B bProportion: B bContrast: B bStrokeVariation: B bArmStyle: B bLetterForm: B bMidline: B bXHeight: B"""
class Panose(object): def __init__(self, **kwargs): _, names, _ = sstruct.getformat(panoseFormat) for name in names: setattr(self, name, kwargs.pop(name, 0)) for k in kwargs: raise TypeError(f"Panose() got an unexpected keyword argument {k!r}")
def toXML(self, writer, ttFont): formatstring, names, fixes = sstruct.getformat(panoseFormat) for name in names: writer.simpletag(name, value=getattr(self, name)) writer.newline()
def fromXML(self, name, attrs, content, ttFont): setattr(self, name, safeEval(attrs["value"]))
# 'sfnt' OS/2 and Windows Metrics table - 'OS/2'
OS2_format_0 = """ > # big endian version: H # version xAvgCharWidth: h # average character width usWeightClass: H # degree of thickness of strokes usWidthClass: H # aspect ratio fsType: H # type flags ySubscriptXSize: h # subscript horizontal font size ySubscriptYSize: h # subscript vertical font size ySubscriptXOffset: h # subscript x offset ySubscriptYOffset: h # subscript y offset ySuperscriptXSize: h # superscript horizontal font size ySuperscriptYSize: h # superscript vertical font size ySuperscriptXOffset: h # superscript x offset ySuperscriptYOffset: h # superscript y offset yStrikeoutSize: h # strikeout size yStrikeoutPosition: h # strikeout position sFamilyClass: h # font family class and subclass panose: 10s # panose classification number ulUnicodeRange1: L # character range ulUnicodeRange2: L # character range ulUnicodeRange3: L # character range ulUnicodeRange4: L # character range achVendID: 4s # font vendor identification fsSelection: H # font selection flags usFirstCharIndex: H # first unicode character index usLastCharIndex: H # last unicode character index sTypoAscender: h # typographic ascender sTypoDescender: h # typographic descender sTypoLineGap: h # typographic line gap usWinAscent: H # Windows ascender usWinDescent: H # Windows descender"""
OS2_format_1_addition = """ ulCodePageRange1: L ulCodePageRange2: L"""
OS2_format_2_addition = ( OS2_format_1_addition + """ sxHeight: h sCapHeight: h usDefaultChar: H usBreakChar: H usMaxContext: H""")
OS2_format_5_addition = ( OS2_format_2_addition + """ usLowerOpticalPointSize: H usUpperOpticalPointSize: H""")
bigendian = " > # big endian\n"
OS2_format_1 = OS2_format_0 + OS2_format_1_additionOS2_format_2 = OS2_format_0 + OS2_format_2_additionOS2_format_5 = OS2_format_0 + OS2_format_5_additionOS2_format_1_addition = bigendian + OS2_format_1_additionOS2_format_2_addition = bigendian + OS2_format_2_additionOS2_format_5_addition = bigendian + OS2_format_5_addition
class table_O_S_2f_2(DefaultTable.DefaultTable): """OS/2 and Windows Metrics table
The ``OS/2`` table contains a variety of font-wide metrics and parameters that may be useful to an operating system or other software for system-integration purposes.
See also https://learn.microsoft.com/en-us/typography/opentype/spec/os2 """
dependencies = ["head"]
def decompile(self, data, ttFont): dummy, data = sstruct.unpack2(OS2_format_0, data, self)
if self.version == 1: dummy, data = sstruct.unpack2(OS2_format_1_addition, data, self) elif self.version in (2, 3, 4): dummy, data = sstruct.unpack2(OS2_format_2_addition, data, self) elif self.version == 5: dummy, data = sstruct.unpack2(OS2_format_5_addition, data, self) self.usLowerOpticalPointSize /= 20 self.usUpperOpticalPointSize /= 20 elif self.version != 0: from fontTools import ttLib
raise ttLib.TTLibError( "unknown format for OS/2 table: version %s" % self.version ) if len(data): log.warning("too much 'OS/2' table data")
self.panose = sstruct.unpack(panoseFormat, self.panose, Panose())
def compile(self, ttFont): self.updateFirstAndLastCharIndex(ttFont) panose = self.panose head = ttFont["head"] if (self.fsSelection & 1) and not (head.macStyle & 1 << 1): log.warning( "fsSelection bit 0 (italic) and " "head table macStyle bit 1 (italic) should match" ) if (self.fsSelection & 1 << 5) and not (head.macStyle & 1): log.warning( "fsSelection bit 5 (bold) and " "head table macStyle bit 0 (bold) should match" ) if (self.fsSelection & 1 << 6) and (self.fsSelection & 1 + (1 << 5)): log.warning( "fsSelection bit 6 (regular) is set, " "bits 0 (italic) and 5 (bold) must be clear" ) if self.version < 4 and self.fsSelection & 0b1110000000: log.warning( "fsSelection bits 7, 8 and 9 are only defined in " "OS/2 table version 4 and up: version %s", self.version, ) self.panose = sstruct.pack(panoseFormat, self.panose) if self.version == 0: data = sstruct.pack(OS2_format_0, self) elif self.version == 1: data = sstruct.pack(OS2_format_1, self) elif self.version in (2, 3, 4): data = sstruct.pack(OS2_format_2, self) elif self.version == 5: d = self.__dict__.copy() d["usLowerOpticalPointSize"] = round(self.usLowerOpticalPointSize * 20) d["usUpperOpticalPointSize"] = round(self.usUpperOpticalPointSize * 20) data = sstruct.pack(OS2_format_5, d) else: from fontTools import ttLib
raise ttLib.TTLibError( "unknown format for OS/2 table: version %s" % self.version ) self.panose = panose return data
def toXML(self, writer, ttFont): writer.comment( "The fields 'usFirstCharIndex' and 'usLastCharIndex'\n" "will be recalculated by the compiler" ) writer.newline() if self.version == 1: format = OS2_format_1 elif self.version in (2, 3, 4): format = OS2_format_2 elif self.version == 5: format = OS2_format_5 else: format = OS2_format_0 formatstring, names, fixes = sstruct.getformat(format) for name in names: value = getattr(self, name) if name == "panose": writer.begintag("panose") writer.newline() value.toXML(writer, ttFont) writer.endtag("panose") elif name in ( "ulUnicodeRange1", "ulUnicodeRange2", "ulUnicodeRange3", "ulUnicodeRange4", "ulCodePageRange1", "ulCodePageRange2", ): writer.simpletag(name, value=num2binary(value)) elif name in ("fsType", "fsSelection"): writer.simpletag(name, value=num2binary(value, 16)) elif name == "achVendID": writer.simpletag(name, value=repr(value)[1:-1]) else: writer.simpletag(name, value=value) writer.newline()
def fromXML(self, name, attrs, content, ttFont): if name == "panose": self.panose = panose = Panose() for element in content: if isinstance(element, tuple): name, attrs, content = element panose.fromXML(name, attrs, content, ttFont) elif name in ( "ulUnicodeRange1", "ulUnicodeRange2", "ulUnicodeRange3", "ulUnicodeRange4", "ulCodePageRange1", "ulCodePageRange2", "fsType", "fsSelection", ): setattr(self, name, binary2num(attrs["value"])) elif name == "achVendID": setattr(self, name, safeEval("'''" + attrs["value"] + "'''")) else: setattr(self, name, safeEval(attrs["value"]))
def updateFirstAndLastCharIndex(self, ttFont): if "cmap" not in ttFont: return codes = set() for table in getattr(ttFont["cmap"], "tables", []): if table.isUnicode(): codes.update(table.cmap.keys()) if codes: minCode = min(codes) maxCode = max(codes) # USHORT cannot hold codepoints greater than 0xFFFF self.usFirstCharIndex = min(0xFFFF, minCode) self.usLastCharIndex = min(0xFFFF, maxCode)
# misspelled attributes kept for legacy reasons
@property def usMaxContex(self): return self.usMaxContext
@usMaxContex.setter def usMaxContex(self, value): self.usMaxContext = value
@property def fsFirstCharIndex(self): return self.usFirstCharIndex
@fsFirstCharIndex.setter def fsFirstCharIndex(self, value): self.usFirstCharIndex = value
@property def fsLastCharIndex(self): return self.usLastCharIndex
@fsLastCharIndex.setter def fsLastCharIndex(self, value): self.usLastCharIndex = value
def getUnicodeRanges(self): """Return the set of 'ulUnicodeRange*' bits currently enabled.""" bits = set() ul1, ul2 = self.ulUnicodeRange1, self.ulUnicodeRange2 ul3, ul4 = self.ulUnicodeRange3, self.ulUnicodeRange4 for i in range(32): if ul1 & (1 << i): bits.add(i) if ul2 & (1 << i): bits.add(i + 32) if ul3 & (1 << i): bits.add(i + 64) if ul4 & (1 << i): bits.add(i + 96) return bits
def setUnicodeRanges(self, bits): """Set the 'ulUnicodeRange*' fields to the specified 'bits'.""" ul1, ul2, ul3, ul4 = 0, 0, 0, 0 for bit in bits: if 0 <= bit < 32: ul1 |= 1 << bit elif 32 <= bit < 64: ul2 |= 1 << (bit - 32) elif 64 <= bit < 96: ul3 |= 1 << (bit - 64) elif 96 <= bit < 123: ul4 |= 1 << (bit - 96) else: raise ValueError("expected 0 <= int <= 122, found: %r" % bit) self.ulUnicodeRange1, self.ulUnicodeRange2 = ul1, ul2 self.ulUnicodeRange3, self.ulUnicodeRange4 = ul3, ul4
def recalcUnicodeRanges(self, ttFont, pruneOnly=False): """Intersect the codepoints in the font's Unicode cmap subtables with the Unicode block ranges defined in the OpenType specification (v1.7), and set the respective 'ulUnicodeRange*' bits if there is at least ONE intersection. If 'pruneOnly' is True, only clear unused bits with NO intersection. """ unicodes = set() for table in ttFont["cmap"].tables: if table.isUnicode(): unicodes.update(table.cmap.keys()) if pruneOnly: empty = intersectUnicodeRanges(unicodes, inverse=True) bits = self.getUnicodeRanges() - empty else: bits = intersectUnicodeRanges(unicodes) self.setUnicodeRanges(bits) return bits
def getCodePageRanges(self): """Return the set of 'ulCodePageRange*' bits currently enabled.""" bits = set() if self.version < 1: return bits ul1, ul2 = self.ulCodePageRange1, self.ulCodePageRange2 for i in range(32): if ul1 & (1 << i): bits.add(i) if ul2 & (1 << i): bits.add(i + 32) return bits
def setCodePageRanges(self, bits): """Set the 'ulCodePageRange*' fields to the specified 'bits'.""" ul1, ul2 = 0, 0 for bit in bits: if 0 <= bit < 32: ul1 |= 1 << bit elif 32 <= bit < 64: ul2 |= 1 << (bit - 32) else: raise ValueError(f"expected 0 <= int <= 63, found: {bit:r}") if self.version < 1: self.version = 1 self.ulCodePageRange1, self.ulCodePageRange2 = ul1, ul2
def recalcCodePageRanges(self, ttFont, pruneOnly=False): unicodes = set() for table in ttFont["cmap"].tables: if table.isUnicode(): unicodes.update(table.cmap.keys()) bits = calcCodePageRanges(unicodes) if pruneOnly: bits &= self.getCodePageRanges() # when no codepage ranges can be enabled, fall back to enabling bit 0 # (Latin 1) so that the font works in MS Word: # https://github.com/googlei18n/fontmake/issues/468 if not bits: bits = {0} self.setCodePageRanges(bits) return bits
def recalcAvgCharWidth(self, ttFont): """Recalculate xAvgCharWidth using metrics from ttFont's 'hmtx' table.
Set it to 0 if the unlikely event 'hmtx' table is not found. """ avg_width = 0 hmtx = ttFont.get("hmtx") if hmtx is not None: widths = [width for width, _ in hmtx.metrics.values() if width > 0] if widths: avg_width = otRound(sum(widths) / len(widths)) self.xAvgCharWidth = avg_width return avg_width
# Unicode ranges data from the OpenType OS/2 table specification v1.7
OS2_UNICODE_RANGES = ( (("Basic Latin", (0x0000, 0x007F)),), (("Latin-1 Supplement", (0x0080, 0x00FF)),), (("Latin Extended-A", (0x0100, 0x017F)),), (("Latin Extended-B", (0x0180, 0x024F)),), ( ("IPA Extensions", (0x0250, 0x02AF)), ("Phonetic Extensions", (0x1D00, 0x1D7F)), ("Phonetic Extensions Supplement", (0x1D80, 0x1DBF)), ), ( ("Spacing Modifier Letters", (0x02B0, 0x02FF)), ("Modifier Tone Letters", (0xA700, 0xA71F)), ), ( ("Combining Diacritical Marks", (0x0300, 0x036F)), ("Combining Diacritical Marks Supplement", (0x1DC0, 0x1DFF)), ), (("Greek and Coptic", (0x0370, 0x03FF)),), (("Coptic", (0x2C80, 0x2CFF)),), ( ("Cyrillic", (0x0400, 0x04FF)), ("Cyrillic Supplement", (0x0500, 0x052F)), ("Cyrillic Extended-A", (0x2DE0, 0x2DFF)), ("Cyrillic Extended-B", (0xA640, 0xA69F)), ), (("Armenian", (0x0530, 0x058F)),), (("Hebrew", (0x0590, 0x05FF)),), (("Vai", (0xA500, 0xA63F)),), (("Arabic", (0x0600, 0x06FF)), ("Arabic Supplement", (0x0750, 0x077F))), (("NKo", (0x07C0, 0x07FF)),), (("Devanagari", (0x0900, 0x097F)),), (("Bengali", (0x0980, 0x09FF)),), (("Gurmukhi", (0x0A00, 0x0A7F)),), (("Gujarati", (0x0A80, 0x0AFF)),), (("Oriya", (0x0B00, 0x0B7F)),), (("Tamil", (0x0B80, 0x0BFF)),), (("Telugu", (0x0C00, 0x0C7F)),), (("Kannada", (0x0C80, 0x0CFF)),), (("Malayalam", (0x0D00, 0x0D7F)),), (("Thai", (0x0E00, 0x0E7F)),), (("Lao", (0x0E80, 0x0EFF)),), (("Georgian", (0x10A0, 0x10FF)), ("Georgian Supplement", (0x2D00, 0x2D2F))), (("Balinese", (0x1B00, 0x1B7F)),), (("Hangul Jamo", (0x1100, 0x11FF)),), ( ("Latin Extended Additional", (0x1E00, 0x1EFF)), ("Latin Extended-C", (0x2C60, 0x2C7F)), ("Latin Extended-D", (0xA720, 0xA7FF)), ), (("Greek Extended", (0x1F00, 0x1FFF)),), ( ("General Punctuation", (0x2000, 0x206F)), ("Supplemental Punctuation", (0x2E00, 0x2E7F)), ), (("Superscripts And Subscripts", (0x2070, 0x209F)),), (("Currency Symbols", (0x20A0, 0x20CF)),), (("Combining Diacritical Marks For Symbols", (0x20D0, 0x20FF)),), (("Letterlike Symbols", (0x2100, 0x214F)),), (("Number Forms", (0x2150, 0x218F)),), ( ("Arrows", (0x2190, 0x21FF)), ("Supplemental Arrows-A", (0x27F0, 0x27FF)), ("Supplemental Arrows-B", (0x2900, 0x297F)), ("Miscellaneous Symbols and Arrows", (0x2B00, 0x2BFF)), ), ( ("Mathematical Operators", (0x2200, 0x22FF)), ("Supplemental Mathematical Operators", (0x2A00, 0x2AFF)), ("Miscellaneous Mathematical Symbols-A", (0x27C0, 0x27EF)), ("Miscellaneous Mathematical Symbols-B", (0x2980, 0x29FF)), ), (("Miscellaneous Technical", (0x2300, 0x23FF)),), (("Control Pictures", (0x2400, 0x243F)),), (("Optical Character Recognition", (0x2440, 0x245F)),), (("Enclosed Alphanumerics", (0x2460, 0x24FF)),), (("Box Drawing", (0x2500, 0x257F)),), (("Block Elements", (0x2580, 0x259F)),), (("Geometric Shapes", (0x25A0, 0x25FF)),), (("Miscellaneous Symbols", (0x2600, 0x26FF)),), (("Dingbats", (0x2700, 0x27BF)),), (("CJK Symbols And Punctuation", (0x3000, 0x303F)),), (("Hiragana", (0x3040, 0x309F)),), ( ("Katakana", (0x30A0, 0x30FF)), ("Katakana Phonetic Extensions", (0x31F0, 0x31FF)), ), (("Bopomofo", (0x3100, 0x312F)), ("Bopomofo Extended", (0x31A0, 0x31BF))), (("Hangul Compatibility Jamo", (0x3130, 0x318F)),), (("Phags-pa", (0xA840, 0xA87F)),), (("Enclosed CJK Letters And Months", (0x3200, 0x32FF)),), (("CJK Compatibility", (0x3300, 0x33FF)),), (("Hangul Syllables", (0xAC00, 0xD7AF)),), (("Non-Plane 0 *", (0xD800, 0xDFFF)),), (("Phoenician", (0x10900, 0x1091F)),), ( ("CJK Unified Ideographs", (0x4E00, 0x9FFF)), ("CJK Radicals Supplement", (0x2E80, 0x2EFF)), ("Kangxi Radicals", (0x2F00, 0x2FDF)), ("Ideographic Description Characters", (0x2FF0, 0x2FFF)), ("CJK Unified Ideographs Extension A", (0x3400, 0x4DBF)), ("CJK Unified Ideographs Extension B", (0x20000, 0x2A6DF)), ("Kanbun", (0x3190, 0x319F)), ), (("Private Use Area (plane 0)", (0xE000, 0xF8FF)),), ( ("CJK Strokes", (0x31C0, 0x31EF)), ("CJK Compatibility Ideographs", (0xF900, 0xFAFF)), ("CJK Compatibility Ideographs Supplement", (0x2F800, 0x2FA1F)), ), (("Alphabetic Presentation Forms", (0xFB00, 0xFB4F)),), (("Arabic Presentation Forms-A", (0xFB50, 0xFDFF)),), (("Combining Half Marks", (0xFE20, 0xFE2F)),), ( ("Vertical Forms", (0xFE10, 0xFE1F)), ("CJK Compatibility Forms", (0xFE30, 0xFE4F)), ), (("Small Form Variants", (0xFE50, 0xFE6F)),), (("Arabic Presentation Forms-B", (0xFE70, 0xFEFF)),), (("Halfwidth And Fullwidth Forms", (0xFF00, 0xFFEF)),), (("Specials", (0xFFF0, 0xFFFF)),), (("Tibetan", (0x0F00, 0x0FFF)),), (("Syriac", (0x0700, 0x074F)),), (("Thaana", (0x0780, 0x07BF)),), (("Sinhala", (0x0D80, 0x0DFF)),), (("Myanmar", (0x1000, 0x109F)),), ( ("Ethiopic", (0x1200, 0x137F)), ("Ethiopic Supplement", (0x1380, 0x139F)), ("Ethiopic Extended", (0x2D80, 0x2DDF)), ), (("Cherokee", (0x13A0, 0x13FF)),), (("Unified Canadian Aboriginal Syllabics", (0x1400, 0x167F)),), (("Ogham", (0x1680, 0x169F)),), (("Runic", (0x16A0, 0x16FF)),), (("Khmer", (0x1780, 0x17FF)), ("Khmer Symbols", (0x19E0, 0x19FF))), (("Mongolian", (0x1800, 0x18AF)),), (("Braille Patterns", (0x2800, 0x28FF)),), (("Yi Syllables", (0xA000, 0xA48F)), ("Yi Radicals", (0xA490, 0xA4CF))), ( ("Tagalog", (0x1700, 0x171F)), ("Hanunoo", (0x1720, 0x173F)), ("Buhid", (0x1740, 0x175F)), ("Tagbanwa", (0x1760, 0x177F)), ), (("Old Italic", (0x10300, 0x1032F)),), (("Gothic", (0x10330, 0x1034F)),), (("Deseret", (0x10400, 0x1044F)),), ( ("Byzantine Musical Symbols", (0x1D000, 0x1D0FF)), ("Musical Symbols", (0x1D100, 0x1D1FF)), ("Ancient Greek Musical Notation", (0x1D200, 0x1D24F)), ), (("Mathematical Alphanumeric Symbols", (0x1D400, 0x1D7FF)),), ( ("Private Use (plane 15)", (0xF0000, 0xFFFFD)), ("Private Use (plane 16)", (0x100000, 0x10FFFD)), ), ( ("Variation Selectors", (0xFE00, 0xFE0F)), ("Variation Selectors Supplement", (0xE0100, 0xE01EF)), ), (("Tags", (0xE0000, 0xE007F)),), (("Limbu", (0x1900, 0x194F)),), (("Tai Le", (0x1950, 0x197F)),), (("New Tai Lue", (0x1980, 0x19DF)),), (("Buginese", (0x1A00, 0x1A1F)),), (("Glagolitic", (0x2C00, 0x2C5F)),), (("Tifinagh", (0x2D30, 0x2D7F)),), (("Yijing Hexagram Symbols", (0x4DC0, 0x4DFF)),), (("Syloti Nagri", (0xA800, 0xA82F)),), ( ("Linear B Syllabary", (0x10000, 0x1007F)), ("Linear B Ideograms", (0x10080, 0x100FF)), ("Aegean Numbers", (0x10100, 0x1013F)), ), (("Ancient Greek Numbers", (0x10140, 0x1018F)),), (("Ugaritic", (0x10380, 0x1039F)),), (("Old Persian", (0x103A0, 0x103DF)),), (("Shavian", (0x10450, 0x1047F)),), (("Osmanya", (0x10480, 0x104AF)),), (("Cypriot Syllabary", (0x10800, 0x1083F)),), (("Kharoshthi", (0x10A00, 0x10A5F)),), (("Tai Xuan Jing Symbols", (0x1D300, 0x1D35F)),), ( ("Cuneiform", (0x12000, 0x123FF)), ("Cuneiform Numbers and Punctuation", (0x12400, 0x1247F)), ), (("Counting Rod Numerals", (0x1D360, 0x1D37F)),), (("Sundanese", (0x1B80, 0x1BBF)),), (("Lepcha", (0x1C00, 0x1C4F)),), (("Ol Chiki", (0x1C50, 0x1C7F)),), (("Saurashtra", (0xA880, 0xA8DF)),), (("Kayah Li", (0xA900, 0xA92F)),), (("Rejang", (0xA930, 0xA95F)),), (("Cham", (0xAA00, 0xAA5F)),), (("Ancient Symbols", (0x10190, 0x101CF)),), (("Phaistos Disc", (0x101D0, 0x101FF)),), ( ("Carian", (0x102A0, 0x102DF)), ("Lycian", (0x10280, 0x1029F)), ("Lydian", (0x10920, 0x1093F)), ), (("Domino Tiles", (0x1F030, 0x1F09F)), ("Mahjong Tiles", (0x1F000, 0x1F02F))),)
_unicodeStarts = []_unicodeValues = [None]
def _getUnicodeRanges(): # build the ranges of codepoints for each unicode range bit, and cache result if not _unicodeStarts: unicodeRanges = [ (start, (stop, bit)) for bit, blocks in enumerate(OS2_UNICODE_RANGES) for _, (start, stop) in blocks ] for start, (stop, bit) in sorted(unicodeRanges): _unicodeStarts.append(start) _unicodeValues.append((stop, bit)) return _unicodeStarts, _unicodeValues
def intersectUnicodeRanges(unicodes, inverse=False): """Intersect a sequence of (int) Unicode codepoints with the Unicode block ranges defined in the OpenType specification v1.7, and return the set of 'ulUnicodeRanges' bits for which there is at least ONE intersection. If 'inverse' is True, return the the bits for which there is NO intersection.
>>> intersectUnicodeRanges([0x0410]) == {9} True >>> intersectUnicodeRanges([0x0410, 0x1F000]) == {9, 57, 122} True >>> intersectUnicodeRanges([0x0410, 0x1F000], inverse=True) == ( ... set(range(len(OS2_UNICODE_RANGES))) - {9, 57, 122}) True """ unicodes = set(unicodes) unicodestarts, unicodevalues = _getUnicodeRanges() bits = set() for code in unicodes: stop, bit = unicodevalues[bisect.bisect(unicodestarts, code)] if code <= stop: bits.add(bit) # The spec says that bit 57 ("Non Plane 0") implies that there's # at least one codepoint beyond the BMP; so I also include all # the non-BMP codepoints here if any(0x10000 <= code < 0x110000 for code in unicodes): bits.add(57) return set(range(len(OS2_UNICODE_RANGES))) - bits if inverse else bits
def calcCodePageRanges(unicodes): """Given a set of Unicode codepoints (integers), calculate the corresponding OS/2 CodePage range bits. This is a direct translation of FontForge implementation: https://github.com/fontforge/fontforge/blob/7b2c074/fontforge/tottf.c#L3158 """ bits = set() hasAscii = set(range(0x20, 0x7E)).issubset(unicodes) hasLineart = ord("┤") in unicodes
for uni in unicodes: if uni == ord("Þ") and hasAscii: bits.add(0) # Latin 1 elif uni == ord("Ľ") and hasAscii: bits.add(1) # Latin 2: Eastern Europe if hasLineart: bits.add(58) # Latin 2 elif uni == ord("Б"): bits.add(2) # Cyrillic if ord("Ѕ") in unicodes and hasLineart: bits.add(57) # IBM Cyrillic if ord("╜") in unicodes and hasLineart: bits.add(49) # MS-DOS Russian elif uni == ord("Ά"): bits.add(3) # Greek if hasLineart and ord("½") in unicodes: bits.add(48) # IBM Greek if hasLineart and ord("√") in unicodes: bits.add(60) # Greek, former 437 G elif uni == ord("İ") and hasAscii: bits.add(4) # Turkish if hasLineart: bits.add(56) # IBM turkish elif uni == ord("א"): bits.add(5) # Hebrew if hasLineart and ord("√") in unicodes: bits.add(53) # Hebrew elif uni == ord("ر"): bits.add(6) # Arabic if ord("√") in unicodes: bits.add(51) # Arabic if hasLineart: bits.add(61) # Arabic; ASMO 708 elif uni == ord("ŗ") and hasAscii: bits.add(7) # Windows Baltic if hasLineart: bits.add(59) # MS-DOS Baltic elif uni == ord("₫") and hasAscii: bits.add(8) # Vietnamese elif uni == ord("ๅ"): bits.add(16) # Thai elif uni == ord("エ"): bits.add(17) # JIS/Japan elif uni == ord("ㄅ"): bits.add(18) # Chinese: Simplified elif uni == ord("ㄱ"): bits.add(19) # Korean wansung elif uni == ord("央"): bits.add(20) # Chinese: Traditional elif uni == ord("곴"): bits.add(21) # Korean Johab elif uni == ord("♥") and hasAscii: bits.add(30) # OEM Character Set # TODO: Symbol bit has a special meaning (check the spec), we need # to confirm if this is wanted by default. # elif chr(0xF000) <= char <= chr(0xF0FF): # codepageRanges.add(31) # Symbol Character Set elif uni == ord("þ") and hasAscii and hasLineart: bits.add(54) # MS-DOS Icelandic elif uni == ord("╚") and hasAscii: bits.add(62) # WE/Latin 1 bits.add(63) # US elif hasAscii and hasLineart and ord("√") in unicodes: if uni == ord("Å"): bits.add(50) # MS-DOS Nordic elif uni == ord("é"): bits.add(52) # MS-DOS Canadian French elif uni == ord("õ"): bits.add(55) # MS-DOS Portuguese
if hasAscii and ord("‰") in unicodes and ord("∑") in unicodes: bits.add(29) # Macintosh Character Set (US Roman)
return bits
if __name__ == "__main__": import doctest, sys
sys.exit(doctest.testmod().failed)123456789101112131415from .otBase import BaseTTXConverter
class table_S_T_A_T_(BaseTTXConverter): """Style Attributes table
The ``STAT`` table records stylistic or typeface-design attributes that differentiate the individual fonts within a font family from one another. Those attributes can be used to assist users when navigating the style variations of a variable font or a family of static fonts.
See also https://learn.microsoft.com/en-us/typography/opentype/spec/stat """
pass1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192from fontTools.misc import sstructfrom fontTools.misc.fixedTools import floatToFixedToStrfrom fontTools.misc.textTools import safeEvalfrom . import DefaultTablefrom . import grUtilsimport struct
Sill_hdr = """ > version: 16.16F"""
class table_S__i_l_l(DefaultTable.DefaultTable): """Graphite Languages table
See also https://graphite.sil.org/graphite_techAbout#graphite-font-tables """
def __init__(self, tag=None): DefaultTable.DefaultTable.__init__(self, tag) self.langs = {}
def decompile(self, data, ttFont): (_, data) = sstruct.unpack2(Sill_hdr, data, self) self.version = float(floatToFixedToStr(self.version, precisionBits=16)) (numLangs,) = struct.unpack(">H", data[:2]) data = data[8:] maxsetting = 0 langinfo = [] for i in range(numLangs): (langcode, numsettings, offset) = struct.unpack( ">4sHH", data[i * 8 : (i + 1) * 8] ) offset = int(offset / 8) - (numLangs + 1) langcode = langcode.replace(b"\000", b"") langinfo.append((langcode.decode("utf-8"), numsettings, offset)) maxsetting = max(maxsetting, offset + numsettings) data = data[numLangs * 8 :] finfo = [] for i in range(maxsetting): (fid, val, _) = struct.unpack(">LHH", data[i * 8 : (i + 1) * 8]) finfo.append((fid, val)) self.langs = {} for c, n, o in langinfo: self.langs[c] = [] for i in range(o, o + n): self.langs[c].append(finfo[i])
def compile(self, ttFont): ldat = b"" fdat = b"" offset = len(self.langs) for c, inf in sorted(self.langs.items()): ldat += struct.pack(">4sHH", c.encode("utf8"), len(inf), 8 * offset + 20) for fid, val in inf: fdat += struct.pack(">LHH", fid, val, 0) offset += len(inf) ldat += struct.pack(">LHH", 0x80808080, 0, 8 * offset + 20) return ( sstruct.pack(Sill_hdr, self) + grUtils.bininfo(len(self.langs)) + ldat + fdat )
def toXML(self, writer, ttFont): writer.simpletag("version", version=self.version) writer.newline() for c, inf in sorted(self.langs.items()): writer.begintag("lang", name=c) writer.newline() for fid, val in inf: writer.simpletag("feature", fid=grUtils.num2tag(fid), val=val) writer.newline() writer.endtag("lang") writer.newline()
def fromXML(self, name, attrs, content, ttFont): if name == "version": self.version = float(safeEval(attrs["version"])) elif name == "lang": c = attrs["name"] self.langs[c] = [] for element in content: if not isinstance(element, tuple): continue tag, a, subcontent = element if tag == "feature": self.langs[c].append( (grUtils.tag2num(a["fid"]), int(safeEval(a["val"]))) )1234567891011121314""" TSI{B,C,D,J,P,S,V} are private tables used by Microsoft Visual TrueType (VTT)tool to store its table source data.
TSIC contains the source text for the Variation CVT window and data forthe ``cvar`` table.
See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables"""
from .otBase import BaseTTXConverter
class table_T_S_I_C_(BaseTTXConverter): pass12345678910111213""" TSI{B,C,D,J,P,S,V} are private tables used by Microsoft Visual TrueType (VTT)tool to store its table source data.
TSIS contains the source text for the ``GSUB`` table.
See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables"""
from .T_S_I_V_ import table_T_S_I_V_
class table_T_S_I_S_(table_T_S_I_V_): pass12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT)tool to store its hinting source data.
TSI0 is the index table containing the lengths and offsets for the glyphprograms and 'extra' programs ('fpgm', 'prep', and 'cvt') that are containedin the TSI1 table.
See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables"""
import loggingimport struct
from . import DefaultTable
log = logging.getLogger(__name__)
tsi0Format = ">HHL"
def fixlongs(glyphID, textLength, textOffset): return int(glyphID), int(textLength), textOffset
class table_T_S_I__0(DefaultTable.DefaultTable): dependencies = ["TSI1"]
def decompile(self, data, ttFont): numGlyphs = ttFont["maxp"].numGlyphs indices = [] size = struct.calcsize(tsi0Format) numEntries = len(data) // size if numEntries != numGlyphs + 5: diff = numEntries - numGlyphs - 5 log.warning( "Number of glyphPrograms differs from the number of glyphs in the font " f"by {abs(diff)} ({numEntries - 5} programs vs. {numGlyphs} glyphs)." ) for _ in range(numEntries): glyphID, textLength, textOffset = fixlongs( *struct.unpack(tsi0Format, data[:size]) ) indices.append((glyphID, textLength, textOffset)) data = data[size:] assert len(data) == 0 assert indices[-5] == (0xFFFE, 0, 0xABFC1F34), "bad magic number" self.indices = indices[:-5] self.extra_indices = indices[-4:]
def compile(self, ttFont): if not hasattr(self, "indices"): # We have no corresponding table (TSI1 or TSI3); let's return # no data, which effectively means "ignore us". return b"" data = b"" for index, textLength, textOffset in self.indices: data = data + struct.pack(tsi0Format, index, textLength, textOffset) data = data + struct.pack(tsi0Format, 0xFFFE, 0, 0xABFC1F34) for index, textLength, textOffset in self.extra_indices: data = data + struct.pack(tsi0Format, index, textLength, textOffset) return data
def set(self, indices, extra_indices): # gets called by 'TSI1' or 'TSI3' self.indices = indices self.extra_indices = extra_indices
def toXML(self, writer, ttFont): writer.comment("This table will be calculated by the compiler") writer.newline()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163""" TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT)tool to store its hinting source data.
TSI1 contains the text of the glyph programs in the form of low-level assemblycode, as well as the 'extra' programs 'fpgm', 'ppgm' (i.e. 'prep'), and 'cvt'.
See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables"""
from . import DefaultTablefrom fontTools.misc.loggingTools import LogMixinfrom fontTools.misc.textTools import strjoin, tobytes, tostr
class table_T_S_I__1(LogMixin, DefaultTable.DefaultTable): extras = {0xFFFA: "ppgm", 0xFFFB: "cvt", 0xFFFC: "reserved", 0xFFFD: "fpgm"}
indextable = "TSI0"
def decompile(self, data, ttFont): totalLength = len(data) indextable = ttFont[self.indextable] for indices, isExtra in zip( (indextable.indices, indextable.extra_indices), (False, True) ): programs = {} for i, (glyphID, textLength, textOffset) in enumerate(indices): if isExtra: name = self.extras[glyphID] else: name = ttFont.getGlyphName(glyphID) if textOffset > totalLength: self.log.warning("textOffset > totalLength; %r skipped" % name) continue if textLength < 0x8000: # If the length stored in the record is less than 32768, then use # that as the length of the record. pass elif textLength == 0x8000: # If the length is 32768, compute the actual length as follows: isLast = i == (len(indices) - 1) if isLast: if isExtra: # For the last "extra" record (the very last record of the # table), the length is the difference between the total # length of the TSI1 table and the textOffset of the final # record. nextTextOffset = totalLength else: # For the last "normal" record (the last record just prior # to the record containing the "magic number"), the length # is the difference between the textOffset of the record # following the "magic number" (0xFFFE) record (i.e. the # first "extra" record), and the textOffset of the last # "normal" record. nextTextOffset = indextable.extra_indices[0][2] else: # For all other records with a length of 0x8000, the length is # the difference between the textOffset of the record in # question and the textOffset of the next record. nextTextOffset = indices[i + 1][2] assert nextTextOffset >= textOffset, "entries not sorted by offset" if nextTextOffset > totalLength: self.log.warning( "nextTextOffset > totalLength; %r truncated" % name ) nextTextOffset = totalLength textLength = nextTextOffset - textOffset else: from fontTools import ttLib
raise ttLib.TTLibError( "%r textLength (%d) must not be > 32768" % (name, textLength) ) text = data[textOffset : textOffset + textLength] assert len(text) == textLength text = tostr(text, encoding="utf-8") if text: programs[name] = text if isExtra: self.extraPrograms = programs else: self.glyphPrograms = programs
def compile(self, ttFont): if not hasattr(self, "glyphPrograms"): self.glyphPrograms = {} self.extraPrograms = {} data = b"" indextable = ttFont[self.indextable] glyphNames = ttFont.getGlyphOrder()
indices = [] for i, name in enumerate(glyphNames): if len(data) % 2: data = ( data + b"\015" ) # align on 2-byte boundaries, fill with return chars. Yum. if name in self.glyphPrograms: text = tobytes(self.glyphPrograms[name], encoding="utf-8") else: text = b"" textLength = len(text) if textLength >= 0x8000: textLength = 0x8000 indices.append((i, textLength, len(data))) data = data + text
extra_indices = [] for code, name in sorted(self.extras.items()): if len(data) % 2: data = ( data + b"\015" ) # align on 2-byte boundaries, fill with return chars. if name in self.extraPrograms: text = tobytes(self.extraPrograms[name], encoding="utf-8") else: text = b"" textLength = len(text) if textLength >= 0x8000: textLength = 0x8000 extra_indices.append((code, textLength, len(data))) data = data + text indextable.set(indices, extra_indices) return data
def toXML(self, writer, ttFont): names = sorted(self.glyphPrograms.keys()) writer.newline() for name in names: text = self.glyphPrograms[name] if not text: continue writer.begintag("glyphProgram", name=name) writer.newline() writer.write_noindent(text.replace("\r", "\n")) writer.newline() writer.endtag("glyphProgram") writer.newline() writer.newline() extra_names = sorted(self.extraPrograms.keys()) for name in extra_names: text = self.extraPrograms[name] if not text: continue writer.begintag("extraProgram", name=name) writer.newline() writer.write_noindent(text.replace("\r", "\n")) writer.newline() writer.endtag("extraProgram") writer.newline() writer.newline()
def fromXML(self, name, attrs, content, ttFont): if not hasattr(self, "glyphPrograms"): self.glyphPrograms = {} self.extraPrograms = {} lines = strjoin(content).replace("\r", "\n").split("\n") text = "\r".join(lines[1:-1]) if name == "glyphProgram": self.glyphPrograms[attrs["name"]] = text elif name == "extraProgram": self.extraPrograms[attrs["name"]] = text1234567891011121314151617""" TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT)tool to store its hinting source data.
TSI2 is the index table containing the lengths and offsets for the glyphprograms that are contained in the TSI3 table. It uses the same format asthe TSI0 table.
See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables"""
from fontTools import ttLib
superclass = ttLib.getTableClass("TSI0")
class table_T_S_I__2(superclass): dependencies = ["TSI3"]12345678910111213141516171819202122""" TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT)tool to store its hinting source data.
TSI3 contains the text of the glyph programs in the form of 'VTTTalk' code.
See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables"""
from fontTools import ttLib
superclass = ttLib.getTableClass("TSI1")
class table_T_S_I__3(superclass): extras = { 0xFFFA: "reserved0", 0xFFFB: "reserved1", 0xFFFC: "reserved2", 0xFFFD: "reserved3", }
indextable = "TSI2"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT)tool to store its hinting source data.
TSI5 contains the VTT character groups.
See also https://learn.microsoft.com/en-us/typography/tools/vtt/tsi-tables"""
import arrayimport loggingimport sys
from fontTools.misc.textTools import safeEval
from . import DefaultTable
log = logging.getLogger(__name__)
class table_T_S_I__5(DefaultTable.DefaultTable): def decompile(self, data, ttFont): numGlyphs = ttFont["maxp"].numGlyphs a = array.array("H") a.frombytes(data) if sys.byteorder != "big": a.byteswap() self.glyphGrouping = {} numEntries = len(data) // 2 if numEntries != numGlyphs: diff = numEntries - numGlyphs log.warning( "Number of entries differs from the number of glyphs in the font " f"by {abs(diff)} ({numEntries} entries vs. {numGlyphs} glyphs)." ) for i in range(numEntries): self.glyphGrouping[ttFont.getGlyphName(i)] = a[i]
def compile(self, ttFont): glyphNames = ttFont.getGlyphOrder() a = array.array("H") for glyphName in glyphNames: a.append(self.glyphGrouping.get(glyphName, 0)) if sys.byteorder != "big": a.byteswap() return a.tobytes()
def toXML(self, writer, ttFont): names = sorted(self.glyphGrouping.keys()) for glyphName in names: writer.simpletag( "glyphgroup", name=glyphName, value=self.glyphGrouping[glyphName] ) writer.newline()
def fromXML(self, name, attrs, content, ttFont): if not hasattr(self, "glyphGrouping"): self.glyphGrouping = {} if name != "glyphgroup": return self.glyphGrouping[attrs["name"]] = safeEval(attrs["value"])123456789101112from .otBase import BaseTTXConverter
class table_V_A_R_C_(BaseTTXConverter): """Variable Components table
The ``VARC`` table contains variation information for composite glyphs.
See also https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md """
pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165from fontTools.misc.textTools import bytesjoin, safeEvalfrom . import DefaultTableimport struct
class table_V_O_R_G_(DefaultTable.DefaultTable): """Vertical Origin table
The ``VORG`` table contains the vertical origin of each glyph in a `CFF` or `CFF2` font.
This table is structured so that you can treat it like a dictionary keyed by glyph name.
``ttFont['VORG'][<glyphName>]`` will return the vertical origin for any glyph.
``ttFont['VORG'][<glyphName>] = <value>`` will set the vertical origin for any glyph.
See also https://learn.microsoft.com/en-us/typography/opentype/spec/vorg """
def decompile(self, data, ttFont): self.getGlyphName = ( ttFont.getGlyphName ) # for use in get/set item functions, for access by GID ( self.majorVersion, self.minorVersion, self.defaultVertOriginY, self.numVertOriginYMetrics, ) = struct.unpack(">HHhH", data[:8]) assert ( self.majorVersion <= 1 ), "Major version of VORG table is higher than I know how to handle" data = data[8:] vids = [] gids = [] pos = 0 for i in range(self.numVertOriginYMetrics): gid, vOrigin = struct.unpack(">Hh", data[pos : pos + 4]) pos += 4 gids.append(gid) vids.append(vOrigin)
self.VOriginRecords = vOrig = {} glyphOrder = ttFont.getGlyphOrder() try: names = [glyphOrder[gid] for gid in gids] except IndexError: getGlyphName = self.getGlyphName names = map(getGlyphName, gids)
for name, vid in zip(names, vids): vOrig[name] = vid
def compile(self, ttFont): vorgs = list(self.VOriginRecords.values()) names = list(self.VOriginRecords.keys()) nameMap = ttFont.getReverseGlyphMap() try: gids = [nameMap[name] for name in names] except KeyError: nameMap = ttFont.getReverseGlyphMap(rebuild=True) gids = [nameMap[name] for name in names] vOriginTable = list(zip(gids, vorgs)) self.numVertOriginYMetrics = len(vorgs) vOriginTable.sort() # must be in ascending GID order dataList = [struct.pack(">Hh", rec[0], rec[1]) for rec in vOriginTable] header = struct.pack( ">HHhH", self.majorVersion, self.minorVersion, self.defaultVertOriginY, self.numVertOriginYMetrics, ) dataList.insert(0, header) data = bytesjoin(dataList) return data
def toXML(self, writer, ttFont): writer.simpletag("majorVersion", value=self.majorVersion) writer.newline() writer.simpletag("minorVersion", value=self.minorVersion) writer.newline() writer.simpletag("defaultVertOriginY", value=self.defaultVertOriginY) writer.newline() writer.simpletag("numVertOriginYMetrics", value=self.numVertOriginYMetrics) writer.newline() vOriginTable = [] glyphNames = self.VOriginRecords.keys() for glyphName in glyphNames: try: gid = ttFont.getGlyphID(glyphName) except: assert 0, ( "VORG table contains a glyph name not in ttFont.getGlyphNames(): " + str(glyphName) ) vOriginTable.append([gid, glyphName, self.VOriginRecords[glyphName]]) vOriginTable.sort() for entry in vOriginTable: vOriginRec = VOriginRecord(entry[1], entry[2]) vOriginRec.toXML(writer, ttFont)
def fromXML(self, name, attrs, content, ttFont): if not hasattr(self, "VOriginRecords"): self.VOriginRecords = {} self.getGlyphName = ( ttFont.getGlyphName ) # for use in get/set item functions, for access by GID if name == "VOriginRecord": vOriginRec = VOriginRecord() for element in content: if isinstance(element, str): continue name, attrs, content = element vOriginRec.fromXML(name, attrs, content, ttFont) self.VOriginRecords[vOriginRec.glyphName] = vOriginRec.vOrigin elif "value" in attrs: setattr(self, name, safeEval(attrs["value"]))
def __getitem__(self, glyphSelector): if isinstance(glyphSelector, int): # its a gid, convert to glyph name glyphSelector = self.getGlyphName(glyphSelector)
if glyphSelector not in self.VOriginRecords: return self.defaultVertOriginY
return self.VOriginRecords[glyphSelector]
def __setitem__(self, glyphSelector, value): if isinstance(glyphSelector, int): # its a gid, convert to glyph name glyphSelector = self.getGlyphName(glyphSelector)
if value != self.defaultVertOriginY: self.VOriginRecords[glyphSelector] = value elif glyphSelector in self.VOriginRecords: del self.VOriginRecords[glyphSelector]
def __delitem__(self, glyphSelector): del self.VOriginRecords[glyphSelector]
class VOriginRecord(object): def __init__(self, name=None, vOrigin=None): self.glyphName = name self.vOrigin = vOrigin
def toXML(self, writer, ttFont): writer.begintag("VOriginRecord") writer.newline() writer.simpletag("glyphName", value=self.glyphName) writer.newline() writer.simpletag("vOrigin", value=self.vOrigin) writer.newline() writer.endtag("VOriginRecord") writer.newline()
def fromXML(self, name, attrs, content, ttFont): value = attrs["value"] if name == "glyphName": setattr(self, name, value) else: setattr(self, name, safeEval(value))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# DON'T EDIT! This file is generated by MetaTools/buildTableList.py.def _moduleFinderHint(): """Dummy function to let modulefinder know what tables may be dynamically imported. Generated by MetaTools/buildTableList.py.
>>> _moduleFinderHint() """ from . import B_A_S_E_ from . import C_B_D_T_ from . import C_B_L_C_ from . import C_F_F_ from . import C_F_F__2 from . import C_O_L_R_ from . import C_P_A_L_ from . import D_S_I_G_ from . import D__e_b_g from . import E_B_D_T_ from . import E_B_L_C_ from . import F_F_T_M_ from . import F__e_a_t from . import G_D_E_F_ from . import G_P_O_S_ from . import G_S_U_B_ from . import G_V_A_R_ from . import G__l_a_t from . import G__l_o_c from . import H_V_A_R_ from . import J_S_T_F_ from . import L_T_S_H_ from . import M_A_T_H_ from . import M_V_A_R_ from . import O_S_2f_2 from . import S_T_A_T_ from . import S_V_G_ from . import S__i_l_f from . import S__i_l_l from . import T_S_I_B_ from . import T_S_I_C_ from . import T_S_I_D_ from . import T_S_I_J_ from . import T_S_I_P_ from . import T_S_I_S_ from . import T_S_I_V_ from . import T_S_I__0 from . import T_S_I__1 from . import T_S_I__2 from . import T_S_I__3 from . import T_S_I__5 from . import T_T_F_A_ from . import V_A_R_C_ from . import V_D_M_X_ from . import V_O_R_G_ from . import V_V_A_R_ from . import _a_n_k_r from . import _a_v_a_r from . import _b_s_l_n from . import _c_i_d_g from . import _c_m_a_p from . import _c_v_a_r from . import _c_v_t from . import _f_e_a_t from . import _f_p_g_m from . import _f_v_a_r from . import _g_a_s_p from . import _g_c_i_d from . import _g_l_y_f from . import _g_v_a_r from . import _h_d_m_x from . import _h_e_a_d from . import _h_h_e_a from . import _h_m_t_x from . import _k_e_r_n from . import _l_c_a_r from . import _l_o_c_a from . import _l_t_a_g from . import _m_a_x_p from . import _m_e_t_a from . import _m_o_r_t from . import _m_o_r_x from . import _n_a_m_e from . import _o_p_b_d from . import _p_o_s_t from . import _p_r_e_p from . import _p_r_o_p from . import _s_b_i_x from . import _t_r_a_k from . import _v_h_e_a from . import _v_m_t_x
if __name__ == "__main__": import doctest, sys
sys.exit(doctest.testmod().failed)data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/__init__.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/__main__.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/macUtils.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/removeOverlaps.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/reorderGlyphs.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/scaleUpem.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/sfnt.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/standardGlyphOrder.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/ttCollection.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/ttFont.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/ttGlyphSet.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/ttVisitor.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/__pycache__/woff2.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/BitmapGlyphMetrics.pyAdded+64
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/C_F_F_.pyAdded+61
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/C_F_F__2.pyAdded+26
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/C_O_L_R_.pyAdded+165
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/C_P_A_L_.pyAdded+305
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/D__e_b_g.pyAdded+35
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/DefaultTable.pyAdded+63
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/G_D_E_F_.pyAdded+13
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/G_V_A_R_.pyAdded+5
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/G__l_o_c.pyAdded+85
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/H_V_A_R_.pyAdded+13
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/J_S_T_F_.pyAdded+13
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/L_T_S_H_.pyAdded+58
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/M_V_A_R_.pyAdded+13
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/O_S_2f_2.pyAdded+752
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/S_T_A_T_.pyAdded+15
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/S__i_l_l.pyAdded+92
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I_C_.pyAdded+14
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I_S_.pyAdded+13
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I__0.pyAdded+70
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I__1.pyAdded+163
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I__2.pyAdded+17
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I__3.pyAdded+22
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/T_S_I__5.pyAdded+60
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/V_A_R_C_.pyAdded+12
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/V_O_R_G_.pyAdded+165
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__init__.pyAdded+94
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/B_A_S_E_.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F_.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F__2.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/C_P_A_L_.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/E_B_D_T_.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/E_B_L_C_.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/F_F_T_M_.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/F__e_a_t.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/G__l_a_t.cpython-311.pycAdded
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/fontTools/ttLib/tables/__pycache__/H_V_A_R_.cpython-311.pycAdded