def _tableToXML(self, writer, tag, progress, splitGlyphs=False, quiet=None): if quiet is not None: deprecateArgument("quiet", "configure logging instead") if tag in self: table = self[tag] report = "Dumping '%s' table..." % tag else: report = "No '%s' table found." % tag if progress: progress.setLabel(report) log.info(report) if tag not in self: return xmlTag = tagToXML(tag) attrs = dict() if hasattr(table, "ERROR"): attrs['ERROR'] = "decompilation error" from .tables.DefaultTable import DefaultTable if table.__class__ == DefaultTable: attrs['raw'] = True writer.begintag(xmlTag, **attrs) writer.newline() if tag == "glyf": table.toXML(writer, self, progress, splitGlyphs) elif tag == "CFF ": table.toXML(writer, self, progress) else: table.toXML(writer, self) writer.endtag(xmlTag) writer.newline() writer.newline()
def _tableToXML(self, writer, tag, progress, quiet=None): if quiet is not None: deprecateArgument("quiet", "configure logging instead") if tag in self: table = self[tag] report = "Dumping '%s' table..." % tag else: report = "No '%s' table found." % tag if progress: progress.setLabel(report) log.info(report) if tag not in self: return xmlTag = tagToXML(tag) attrs = dict() if hasattr(table, "ERROR"): attrs['ERROR'] = "decompilation error" from .tables.DefaultTable import DefaultTable if table.__class__ == DefaultTable: attrs['raw'] = True writer.begintag(xmlTag, **attrs) writer.newline() if tag in ("glyf", "CFF "): table.toXML(writer, self, progress) else: table.toXML(writer, self) writer.endtag(xmlTag) writer.newline() writer.newline()
def __init__(self, fileOrPath, ttFont, progress=None, quiet=None, contentOnly=False): if fileOrPath == '-': fileOrPath = sys.stdin if not hasattr(fileOrPath, "read"): self.file = open(fileOrPath, "rb") self._closeStream = True else: # assume readable file object self.file = fileOrPath self._closeStream = False self.ttFont = ttFont self.progress = progress if quiet is not None: from fontTools.misc.loggingTools import deprecateArgument deprecateArgument("quiet", "configure logging instead") self.quiet = quiet self.root = None self.contentStack = [] self.contentOnly = contentOnly self.stackSize = 0
def _saveXML(self, writer, writeVersion=True, quiet=None, tables=None, skipTables=None, splitTables=False, splitGlyphs=False, disassembleInstructions=True, bitmapGlyphDataFormat='raw'): if quiet is not None: deprecateArgument("quiet", "configure logging instead") self.disassembleInstructions = disassembleInstructions self.bitmapGlyphDataFormat = bitmapGlyphDataFormat if not tables: tables = list(self.keys()) if "GlyphOrder" not in tables: tables = ["GlyphOrder"] + tables if skipTables: for tag in skipTables: if tag in tables: tables.remove(tag) numTables = len(tables) if writeVersion: from fontTools import version version = ".".join(version.split('.')[:2]) writer.begintag("ttFont", sfntVersion=repr(tostr(self.sfntVersion))[1:-1], ttLibVersion=version) else: writer.begintag("ttFont", sfntVersion=repr(tostr(self.sfntVersion))[1:-1]) writer.newline() # always splitTables if splitGlyphs is enabled splitTables = splitTables or splitGlyphs if not splitTables: writer.newline() else: path, ext = os.path.splitext(writer.filename) fileNameTemplate = path + ".%s" + ext for i in range(numTables): tag = tables[i] if splitTables: tablePath = fileNameTemplate % tagToIdentifier(tag) tableWriter = xmlWriter.XMLWriter(tablePath, newlinestr=writer.newlinestr) tableWriter.begintag("ttFont", ttLibVersion=version) tableWriter.newline() tableWriter.newline() writer.simpletag(tagToXML(tag), src=os.path.basename(tablePath)) writer.newline() else: tableWriter = writer self._tableToXML(tableWriter, tag, splitGlyphs=splitGlyphs) if splitTables: tableWriter.endtag("ttFont") tableWriter.newline() tableWriter.close() writer.endtag("ttFont") writer.newline()
def importXML(self, fileOrPath, progress=None, quiet=None): """Import a TTX file (an XML-based text format), so as to recreate a font object. """ if quiet is not None: deprecateArgument("quiet", "configure logging instead") if "maxp" in self and "post" in self: # Make sure the glyph order is loaded, as it otherwise gets # lost if the XML doesn't contain the glyph order, yet does # contain the table which was originally used to extract the # glyph names from (ie. 'post', 'cmap' or 'CFF '). self.getGlyphOrder() from fontTools.misc import xmlReader reader = xmlReader.XMLReader(fileOrPath, self, progress) reader.read()
def __init__(self, fileOrPath, ttFont, progress=None, quiet=None): if fileOrPath == '-': fileOrPath = sys.stdin if not hasattr(fileOrPath, "read"): self.file = open(fileOrPath, "rb") self._closeStream = True else: # assume readable file object self.file = fileOrPath self._closeStream = False self.ttFont = ttFont self.progress = progress if quiet is not None: from fontTools.misc.loggingTools import deprecateArgument deprecateArgument("quiet", "configure logging instead") self.quiet = quiet self.root = None self.contentStack = [] self.stackSize = 0
def __init__(self, file=None, res_name_or_index=None, sfntVersion="\000\001\000\000", flavor=None, checkChecksums=False, verbose=None, recalcBBoxes=True, allowVID=False, ignoreDecompileErrors=False, recalcTimestamp=True, fontNumber=-1, lazy=None, quiet=None): """The constructor can be called with a few different arguments. When reading a font from disk, 'file' should be either a pathname pointing to a file, or a readable file object. It we're running on a Macintosh, 'res_name_or_index' maybe an sfnt resource name or an sfnt resource index number or zero. The latter case will cause TTLib to autodetect whether the file is a flat file or a suitcase. (If it's a suitcase, only the first 'sfnt' resource will be read!) The 'checkChecksums' argument is used to specify how sfnt checksums are treated upon reading a file from disk: 0: don't check (default) 1: check, print warnings if a wrong checksum is found 2: check, raise an exception if a wrong checksum is found. The TTFont constructor can also be called without a 'file' argument: this is the way to create a new empty font. In this case you can optionally supply the 'sfntVersion' argument, and a 'flavor' which can be None, 'woff', or 'woff2'. If the recalcBBoxes argument is false, a number of things will *not* be recalculated upon save/compile: 1) 'glyf' glyph bounding boxes 2) 'CFF ' font bounding box 3) 'head' font bounding box 4) 'hhea' min/max values 5) 'vhea' min/max values (1) is needed for certain kinds of CJK fonts (ask Werner Lemberg ;-). Additionally, upon importing an TTX file, this option cause glyphs to be compiled right away. This should reduce memory consumption greatly, and therefore should have some impact on the time needed to parse/compile large fonts. If the recalcTimestamp argument is false, the modified timestamp in the 'head' table will *not* be recalculated upon save/compile. If the allowVID argument is set to true, then virtual GID's are supported. Asking for a glyph ID with a glyph name or GID that is not in the font will return a virtual GID. This is valid for GSUB and cmap tables. For SING glyphlets, the cmap table is used to specify Unicode values for virtual GI's used in GSUB/GPOS rules. If the gid N is requested and does not exist in the font, or the glyphname has the form glyphN and does not exist in the font, then N is used as the virtual GID. Else, the first virtual GID is assigned as 0x1000 -1; for subsequent new virtual GIDs, the next is one less than the previous. If ignoreDecompileErrors is set to True, exceptions raised in individual tables during decompilation will be ignored, falling back to the DefaultTable implementation, which simply keeps the binary data. If lazy is set to True, many data structures are loaded lazily, upon access only. If it is set to False, many data structures are loaded immediately. The default is lazy=None which is somewhere in between. """ from fontTools.ttLib import sfnt for name in ("verbose", "quiet"): val = locals().get(name) if val is not None: deprecateArgument(name, "configure logging instead") setattr(self, name, val) self.lazy = lazy self.recalcBBoxes = recalcBBoxes self.recalcTimestamp = recalcTimestamp self.tables = {} self.reader = None # Permit the user to reference glyphs that are not int the font. self.last_vid = 0xFFFE # Can't make it be 0xFFFF, as the world is full unsigned short integer counters that get incremented after the last seen GID value. self.reverseVIDDict = {} self.VIDDict = {} self.allowVID = allowVID self.ignoreDecompileErrors = ignoreDecompileErrors if not file: self.sfntVersion = sfntVersion self.flavor = flavor self.flavorData = None return if not hasattr(file, "read"): closeStream = True # assume file is a string if res_name_or_index is not None: # see if it contains 'sfnt' resources in the resource or data fork from . import macUtils if res_name_or_index == 0: if macUtils.getSFNTResIndices(file): # get the first available sfnt font. file = macUtils.SFNTResourceReader(file, 1) else: file = open(file, "rb") else: file = macUtils.SFNTResourceReader(file, res_name_or_index) else: file = open(file, "rb") else: # assume "file" is a readable file object closeStream = False if not self.lazy: # read input file in memory and wrap a stream around it to allow overwriting tmp = BytesIO(file.read()) if hasattr(file, 'name'): # save reference to input file name tmp.name = file.name if closeStream: file.close() file = tmp self.reader = sfnt.SFNTReader(file, checkChecksums, fontNumber=fontNumber) self.sfntVersion = self.reader.sfntVersion self.flavor = self.reader.flavor self.flavorData = self.reader.flavorData
def saveXML(self, fileOrPath, progress=None, quiet=None, tables=None, skipTables=None, splitTables=False, disassembleInstructions=True, splitGlyphs=False, bitmapGlyphDataFormat='raw', newlinestr=None): """Export the font as TTX (an XML-based text file), or as a series of text files when splitTables is true. In the latter case, the 'fileOrPath' argument should be a path to a directory. The 'tables' argument must either be false (dump all tables) or a list of tables to dump. The 'skipTables' argument may be a list of tables to skip, but only when the 'tables' argument is false. """ from fontTools import version from fontTools.misc import xmlWriter # only write the MAJOR.MINOR version in the 'ttLibVersion' attribute of # TTX files' root element (without PATCH or .dev suffixes) version = ".".join(version.split('.')[:2]) if quiet is not None: deprecateArgument("quiet", "configure logging instead") self.disassembleInstructions = disassembleInstructions self.bitmapGlyphDataFormat = bitmapGlyphDataFormat if not tables: tables = list(self.keys()) if "GlyphOrder" not in tables: tables = ["GlyphOrder"] + tables if skipTables: for tag in skipTables: if tag in tables: tables.remove(tag) numTables = len(tables) if progress: progress.set(0, numTables) idlefunc = getattr(progress, "idle", None) else: idlefunc = None writer = xmlWriter.XMLWriter(fileOrPath, idlefunc=idlefunc, newlinestr=newlinestr) writer.begintag("ttFont", sfntVersion=repr(tostr(self.sfntVersion))[1:-1], ttLibVersion=version) writer.newline() if not splitTables: writer.newline() if splitTables or splitGlyphs: # 'fileOrPath' must now be a path path, ext = os.path.splitext(fileOrPath) fileNameTemplate = path + ".%s" + ext for i in range(numTables): if progress: progress.set(i) tag = tables[i] if splitTables or (splitGlyphs and tag == 'glyf'): tablePath = fileNameTemplate % tagToIdentifier(tag) else: tablePath = None if splitTables: tableWriter = xmlWriter.XMLWriter(tablePath, idlefunc=idlefunc, newlinestr=newlinestr) tableWriter.begintag("ttFont", ttLibVersion=version) tableWriter.newline() tableWriter.newline() writer.simpletag(tagToXML(tag), src=os.path.basename(tablePath)) writer.newline() else: tableWriter = writer self._tableToXML(tableWriter, tag, progress, splitGlyphs=splitGlyphs) if splitTables: tableWriter.endtag("ttFont") tableWriter.newline() tableWriter.close() if progress: progress.set((i + 1)) writer.endtag("ttFont") writer.newline() # close if 'fileOrPath' is a path; leave it open if it's a file. # The special string "-" means standard output so leave that open too if not hasattr(fileOrPath, "write") and fileOrPath != "-": writer.close()
def __init__(self, file=None, res_name_or_index=None, sfntVersion="\000\001\000\000", flavor=None, checkChecksums=False, verbose=None, recalcBBoxes=True, allowVID=False, ignoreDecompileErrors=False, recalcTimestamp=True, fontNumber=-1, lazy=None, quiet=None): """The constructor can be called with a few different arguments. When reading a font from disk, 'file' should be either a pathname pointing to a file, or a readable file object. It we're running on a Macintosh, 'res_name_or_index' maybe an sfnt resource name or an sfnt resource index number or zero. The latter case will cause TTLib to autodetect whether the file is a flat file or a suitcase. (If it's a suitcase, only the first 'sfnt' resource will be read!) The 'checkChecksums' argument is used to specify how sfnt checksums are treated upon reading a file from disk: 0: don't check (default) 1: check, print warnings if a wrong checksum is found 2: check, raise an exception if a wrong checksum is found. The TTFont constructor can also be called without a 'file' argument: this is the way to create a new empty font. In this case you can optionally supply the 'sfntVersion' argument, and a 'flavor' which can be None, 'woff', or 'woff2'. If the recalcBBoxes argument is false, a number of things will *not* be recalculated upon save/compile: 1) glyph bounding boxes 2) maxp font bounding box 3) hhea min/max values (1) is needed for certain kinds of CJK fonts (ask Werner Lemberg ;-). Additionally, upon importing an TTX file, this option cause glyphs to be compiled right away. This should reduce memory consumption greatly, and therefore should have some impact on the time needed to parse/compile large fonts. If the recalcTimestamp argument is false, the modified timestamp in the 'head' table will *not* be recalculated upon save/compile. If the allowVID argument is set to true, then virtual GID's are supported. Asking for a glyph ID with a glyph name or GID that is not in the font will return a virtual GID. This is valid for GSUB and cmap tables. For SING glyphlets, the cmap table is used to specify Unicode values for virtual GI's used in GSUB/GPOS rules. If the gid N is requested and does not exist in the font, or the glyphname has the form glyphN and does not exist in the font, then N is used as the virtual GID. Else, the first virtual GID is assigned as 0x1000 -1; for subsequent new virtual GIDs, the next is one less than the previous. If ignoreDecompileErrors is set to True, exceptions raised in individual tables during decompilation will be ignored, falling back to the DefaultTable implementation, which simply keeps the binary data. If lazy is set to True, many data structures are loaded lazily, upon access only. If it is set to False, many data structures are loaded immediately. The default is lazy=None which is somewhere in between. """ from fontTools.ttLib import sfnt for name in ("verbose", "quiet"): val = locals().get(name) if val is not None: deprecateArgument(name, "configure logging instead") setattr(self, name, val) self.lazy = lazy self.recalcBBoxes = recalcBBoxes self.recalcTimestamp = recalcTimestamp self.tables = {} self.reader = None # Permit the user to reference glyphs that are not in the font. self.last_vid = 0xFFFE # Can't make it be 0xFFFF, as the world is full unsigned short integer counters that get incremented after the last seen GID value. self.reverseVIDDict = {} self.VIDDict = {} self.allowVID = allowVID self.ignoreDecompileErrors = ignoreDecompileErrors if not file: self.sfntVersion = sfntVersion self.flavor = flavor self.flavorData = None return if not hasattr(file, "read"): closeStream = True # assume file is a string if res_name_or_index is not None: # see if it contains 'sfnt' resources in the resource or data fork from . import macUtils if res_name_or_index == 0: if macUtils.getSFNTResIndices(file): # get the first available sfnt font. file = macUtils.SFNTResourceReader(file, 1) else: file = open(file, "rb") else: file = macUtils.SFNTResourceReader(file, res_name_or_index) else: file = open(file, "rb") else: # assume "file" is a readable file object closeStream = False if not self.lazy: # read input file in memory and wrap a stream around it to allow overwriting tmp = BytesIO(file.read()) if hasattr(file, 'name'): # save reference to input file name tmp.name = file.name if closeStream: file.close() file = tmp self.reader = sfnt.SFNTReader(file, checkChecksums, fontNumber=fontNumber) self.sfntVersion = self.reader.sfntVersion self.flavor = self.reader.flavor self.flavorData = self.reader.flavorData
def saveXML(self, fileOrPath, progress=None, quiet=None, tables=None, skipTables=None, splitTables=False, disassembleInstructions=True, bitmapGlyphDataFormat='raw'): """Export the font as TTX (an XML-based text file), or as a series of text files when splitTables is true. In the latter case, the 'fileOrPath' argument should be a path to a directory. The 'tables' argument must either be false (dump all tables) or a list of tables to dump. The 'skipTables' argument may be a list of tables to skip, but only when the 'tables' argument is false. """ from fontTools import version from fontTools.misc import xmlWriter if quiet is not None: deprecateArgument("quiet", "configure logging instead") self.disassembleInstructions = disassembleInstructions self.bitmapGlyphDataFormat = bitmapGlyphDataFormat if not tables: tables = list(self.keys()) if "GlyphOrder" not in tables: tables = ["GlyphOrder"] + tables if skipTables: for tag in skipTables: if tag in tables: tables.remove(tag) numTables = len(tables) if progress: progress.set(0, numTables) idlefunc = getattr(progress, "idle", None) else: idlefunc = None writer = xmlWriter.XMLWriter(fileOrPath, idlefunc=idlefunc) writer.begintag("ttFont", sfntVersion=repr(self.sfntVersion)[1:-1], ttLibVersion=version) writer.newline() if not splitTables: writer.newline() else: # 'fileOrPath' must now be a path path, ext = os.path.splitext(fileOrPath) fileNameTemplate = path + ".%s" + ext for i in range(numTables): if progress: progress.set(i) tag = tables[i] if splitTables: tablePath = fileNameTemplate % tagToIdentifier(tag) tableWriter = xmlWriter.XMLWriter(tablePath, idlefunc=idlefunc) tableWriter.begintag("ttFont", ttLibVersion=version) tableWriter.newline() tableWriter.newline() writer.simpletag(tagToXML(tag), src=os.path.basename(tablePath)) writer.newline() else: tableWriter = writer self._tableToXML(tableWriter, tag, progress) if splitTables: tableWriter.endtag("ttFont") tableWriter.newline() tableWriter.close() if progress: progress.set((i + 1)) writer.endtag("ttFont") writer.newline() # close if 'fileOrPath' is a path; leave it open if it's a file if not hasattr(fileOrPath, "write"): writer.close()
def __init__(self, file=None, res_name_or_index=None, sfntVersion="\000\001\000\000", flavor=None, checkChecksums=0, verbose=None, recalcBBoxes=True, allowVID=NotImplemented, ignoreDecompileErrors=False, recalcTimestamp=True, fontNumber=-1, lazy=None, quiet=None, _tableCache=None): for name in ("verbose", "quiet"): val = locals().get(name) if val is not None: deprecateArgument(name, "configure logging instead") setattr(self, name, val) self.lazy = lazy self.recalcBBoxes = recalcBBoxes self.recalcTimestamp = recalcTimestamp self.tables = {} self.reader = None self.ignoreDecompileErrors = ignoreDecompileErrors if not file: self.sfntVersion = sfntVersion self.flavor = flavor self.flavorData = None return if not hasattr(file, "read"): closeStream = True # assume file is a string if res_name_or_index is not None: # see if it contains 'sfnt' resources in the resource or data fork from . import macUtils if res_name_or_index == 0: if macUtils.getSFNTResIndices(file): # get the first available sfnt font. file = macUtils.SFNTResourceReader(file, 1) else: file = open(file, "rb") else: file = macUtils.SFNTResourceReader(file, res_name_or_index) else: file = open(file, "rb") else: # assume "file" is a readable file object closeStream = False file.seek(0) if not self.lazy: # read input file in memory and wrap a stream around it to allow overwriting file.seek(0) tmp = BytesIO(file.read()) if hasattr(file, 'name'): # save reference to input file name tmp.name = file.name if closeStream: file.close() file = tmp self._tableCache = _tableCache self.reader = SFNTReader(file, checkChecksums, fontNumber=fontNumber) self.sfntVersion = self.reader.sfntVersion self.flavor = self.reader.flavor self.flavorData = self.reader.flavorData