Exemple #1
0
def reorderFontTables(inFile, outFile, tableOrder=None, checkChecksums=False):
	"""Rewrite a font file, ordering the tables as recommended by the
	OpenType specification 1.4.
	"""
	from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter
	reader = SFNTReader(inFile, checkChecksums=checkChecksums)
	writer = SFNTWriter(outFile, len(reader.tables), reader.sfntVersion, reader.flavor, reader.flavorData)
	tables = list(reader.keys())
	for tag in sortedTagList(tables, tableOrder):
		writer[tag] = reader[tag]
	writer.close()
Exemple #2
0
def reorderFontTables(inFile, outFile, tableOrder=None, checkChecksums=False):
	"""Rewrite a font file, ordering the tables as recommended by the
	OpenType specification 1.4.
	"""
	from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter
	reader = SFNTReader(inFile, checkChecksums=checkChecksums)
	writer = SFNTWriter(outFile, len(reader.tables), reader.sfntVersion, reader.flavor, reader.flavorData)
	tables = list(reader.keys())
	for tag in sortedTagList(tables, tableOrder):
		writer[tag] = reader[tag]
	writer.close()
 def __init__(self,
              file_content,
              checkChecksums=0,
              fontNumber=-1,
              _tableCache=None):
     from fontTools.ttLib.sfnt import SFNTReader
     from io import BytesIO
     # 用content数据代替原码的open()
     file = BytesIO(file_content)
     super().__init__()
     # 继承父类的初始化,但是没有传值会影响后续赋值,
     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
Exemple #4
0
    def test_pickle_protocol_BytesIO(self, deepcopy, tmp_path):
        buf = io.BytesIO(EMPTY_SFNT)
        reader = SFNTReader(buf)

        reader2 = deepcopy(reader)

        assert reader2 is not reader
        assert reader2.file is not reader.file

        assert isinstance(reader2.file, io.BytesIO)
        assert reader2.file.tell() == reader.file.tell()
        assert reader2.file.getvalue() == reader.file.getvalue()

        for k, v in reader.__dict__.items():
            if k == "file":
                continue
            assert getattr(reader2, k) == v
Exemple #5
0
    def test_pickle_protocol_FileIO(self, deepcopy, tmp_path):
        fontfile = tmp_path / "test.ttf"
        fontfile.write_bytes(EMPTY_SFNT)
        reader = SFNTReader(fontfile.open("rb"))

        reader2 = deepcopy(reader)

        assert reader2 is not reader
        assert reader2.file is not reader.file

        assert isinstance(reader2.file, io.BufferedReader)
        assert isinstance(reader2.file.raw, io.FileIO)
        assert reader2.file.name == reader.file.name
        assert reader2.file.tell() == reader.file.tell()

        for k, v in reader.__dict__.items():
            if k == "file":
                continue
            assert getattr(reader2, k) == v
Exemple #6
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,
			_tableCache=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.
		"""

		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
			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
Exemple #7
0
class TTFont(object):

	"""The main font object. It manages file input and output, and offers
	a convenient way of accessing tables.
	Tables will be only decompiled when necessary, ie. when they're actually
	accessed. This means that simple operations can be extremely fast.
	"""

	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,
			_tableCache=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.
		"""

		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
			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

	def __enter__(self):
		return self

	def __exit__(self, type, value, traceback):
		self.close()

	def close(self):
		"""If we still have a reader object, close it."""
		if self.reader is not None:
			self.reader.close()

	def save(self, file, reorderTables=True):
		"""Save the font to disk. Similarly to the constructor,
		the 'file' argument can be either a pathname or a writable
		file object.
		"""
		if not hasattr(file, "write"):
			if self.lazy and self.reader.file.name == file:
				raise TTLibError(
					"Can't overwrite TTFont when 'lazy' attribute is True")
			closeStream = True
			file = open(file, "wb")
		else:
			# assume "file" is a writable file object
			closeStream = False

		tmp = BytesIO()

		writer_reordersTables = self._save(tmp)

		if (reorderTables is None or writer_reordersTables or
				(reorderTables is False and self.reader is None)):
			# don't reorder tables and save as is
			file.write(tmp.getvalue())
			tmp.close()
		else:
			if reorderTables is False:
				# sort tables using the original font's order
				tableOrder = list(self.reader.keys())
			else:
				# use the recommended order from the OpenType specification
				tableOrder = None
			tmp.flush()
			tmp2 = BytesIO()
			reorderFontTables(tmp, tmp2, tableOrder)
			file.write(tmp2.getvalue())
			tmp.close()
			tmp2.close()

		if closeStream:
			file.close()

	def _save(self, file, tableCache=None):
		"""Internal function, to be shared by save() and TTCollection.save()"""

		if self.recalcTimestamp and 'head' in self:
			self['head']  # make sure 'head' is loaded so the recalculation is actually done

		tags = list(self.keys())
		if "GlyphOrder" in tags:
			tags.remove("GlyphOrder")
		numTables = len(tags)
		# write to a temporary stream to allow saving to unseekable streams
		writer = SFNTWriter(file, numTables, self.sfntVersion, self.flavor, self.flavorData)

		done = []
		for tag in tags:
			self._writeTable(tag, writer, done, tableCache)

		writer.close()

		return writer.reordersTables()

	def saveXML(self, fileOrPath, newlinestr=None, **kwargs):
		"""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.
		"""

		writer = xmlWriter.XMLWriter(fileOrPath, newlinestr=newlinestr)
		self._saveXML(writer, **kwargs)
		writer.close()

	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 _tableToXML(self, writer, tag, quiet=None, splitGlyphs=False):
		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
		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, splitGlyphs=splitGlyphs)
		else:
			table.toXML(writer, self)
		writer.endtag(xmlTag)
		writer.newline()
		writer.newline()

	def importXML(self, fileOrPath, 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)
		reader.read()

	def isLoaded(self, tag):
		"""Return true if the table identified by 'tag' has been
		decompiled and loaded into memory."""
		return tag in self.tables

	def has_key(self, tag):
		if self.isLoaded(tag):
			return True
		elif self.reader and tag in self.reader:
			return True
		elif tag == "GlyphOrder":
			return True
		else:
			return False

	__contains__ = has_key

	def keys(self):
		keys = list(self.tables.keys())
		if self.reader:
			for key in list(self.reader.keys()):
				if key not in keys:
					keys.append(key)

		if "GlyphOrder" in keys:
			keys.remove("GlyphOrder")
		keys = sortedTagList(keys)
		return ["GlyphOrder"] + keys

	def __len__(self):
		return len(list(self.keys()))

	def __getitem__(self, tag):
		tag = Tag(tag)
		try:
			return self.tables[tag]
		except KeyError:
			if tag == "GlyphOrder":
				table = GlyphOrder(tag)
				self.tables[tag] = table
				return table
			if self.reader is not None:
				import traceback
				log.debug("Reading '%s' table from disk", tag)
				data = self.reader[tag]
				if self._tableCache is not None:
					table = self._tableCache.get((Tag(tag), data))
					if table is not None:
						return table
				tableClass = getTableClass(tag)
				table = tableClass(tag)
				self.tables[tag] = table
				log.debug("Decompiling '%s' table", tag)
				try:
					table.decompile(data, self)
				except:
					if not self.ignoreDecompileErrors:
						raise
					# fall back to DefaultTable, retaining the binary table data
					log.exception(
						"An exception occurred during the decompilation of the '%s' table", tag)
					from .tables.DefaultTable import DefaultTable
					file = StringIO()
					traceback.print_exc(file=file)
					table = DefaultTable(tag)
					table.ERROR = file.getvalue()
					self.tables[tag] = table
					table.decompile(data, self)
				if self._tableCache is not None:
					self._tableCache[(Tag(tag), data)] = table
				return table
			else:
				raise KeyError("'%s' table not found" % tag)

	def __setitem__(self, tag, table):
		self.tables[Tag(tag)] = table

	def __delitem__(self, tag):
		if tag not in self:
			raise KeyError("'%s' table not found" % tag)
		if tag in self.tables:
			del self.tables[tag]
		if self.reader and tag in self.reader:
			del self.reader[tag]

	def get(self, tag, default=None):
		try:
			return self[tag]
		except KeyError:
			return default

	def setGlyphOrder(self, glyphOrder):
		self.glyphOrder = glyphOrder

	def getGlyphOrder(self):
		try:
			return self.glyphOrder
		except AttributeError:
			pass
		if 'CFF ' in self:
			cff = self['CFF ']
			self.glyphOrder = cff.getGlyphOrder()
		elif 'post' in self:
			# TrueType font
			glyphOrder = self['post'].getGlyphOrder()
			if glyphOrder is None:
				#
				# No names found in the 'post' table.
				# Try to create glyph names from the unicode cmap (if available)
				# in combination with the Adobe Glyph List (AGL).
				#
				self._getGlyphNamesFromCmap()
			else:
				self.glyphOrder = glyphOrder
		else:
			self._getGlyphNamesFromCmap()
		return self.glyphOrder

	def _getGlyphNamesFromCmap(self):
		#
		# This is rather convoluted, but then again, it's an interesting problem:
		# - we need to use the unicode values found in the cmap table to
		#   build glyph names (eg. because there is only a minimal post table,
		#   or none at all).
		# - but the cmap parser also needs glyph names to work with...
		# So here's what we do:
		# - make up glyph names based on glyphID
		# - load a temporary cmap table based on those names
		# - extract the unicode values, build the "real" glyph names
		# - unload the temporary cmap table
		#
		if self.isLoaded("cmap"):
			# Bootstrapping: we're getting called by the cmap parser
			# itself. This means self.tables['cmap'] contains a partially
			# loaded cmap, making it impossible to get at a unicode
			# subtable here. We remove the partially loaded cmap and
			# restore it later.
			# This only happens if the cmap table is loaded before any
			# other table that does f.getGlyphOrder()  or f.getGlyphName().
			cmapLoading = self.tables['cmap']
			del self.tables['cmap']
		else:
			cmapLoading = None
		# Make up glyph names based on glyphID, which will be used by the
		# temporary cmap and by the real cmap in case we don't find a unicode
		# cmap.
		numGlyphs = int(self['maxp'].numGlyphs)
		glyphOrder = [None] * numGlyphs
		glyphOrder[0] = ".notdef"
		for i in range(1, numGlyphs):
			glyphOrder[i] = "glyph%.5d" % i
		# Set the glyph order, so the cmap parser has something
		# to work with (so we don't get called recursively).
		self.glyphOrder = glyphOrder

		# Make up glyph names based on the reversed cmap table. Because some
		# glyphs (eg. ligatures or alternates) may not be reachable via cmap,
		# this naming table will usually not cover all glyphs in the font.
		# If the font has no Unicode cmap table, reversecmap will be empty.
		if 'cmap' in self:
			reversecmap = self['cmap'].buildReversed()
		else:
			reversecmap = {}
		useCount = {}
		for i in range(numGlyphs):
			tempName = glyphOrder[i]
			if tempName in reversecmap:
				# If a font maps both U+0041 LATIN CAPITAL LETTER A and
				# U+0391 GREEK CAPITAL LETTER ALPHA to the same glyph,
				# we prefer naming the glyph as "A".
				glyphName = self._makeGlyphName(min(reversecmap[tempName]))
				numUses = useCount[glyphName] = useCount.get(glyphName, 0) + 1
				if numUses > 1:
					glyphName = "%s.alt%d" % (glyphName, numUses - 1)
				glyphOrder[i] = glyphName

		if 'cmap' in self:
			# Delete the temporary cmap table from the cache, so it can
			# be parsed again with the right names.
			del self.tables['cmap']
			self.glyphOrder = glyphOrder
			if cmapLoading:
				# restore partially loaded cmap, so it can continue loading
				# using the proper names.
				self.tables['cmap'] = cmapLoading

	@staticmethod
	def _makeGlyphName(codepoint):
		from fontTools import agl  # Adobe Glyph List
		if codepoint in agl.UV2AGL:
			return agl.UV2AGL[codepoint]
		elif codepoint <= 0xFFFF:
			return "uni%04X" % codepoint
		else:
			return "u%X" % codepoint

	def getGlyphNames(self):
		"""Get a list of glyph names, sorted alphabetically."""
		glyphNames = sorted(self.getGlyphOrder())
		return glyphNames

	def getGlyphNames2(self):
		"""Get a list of glyph names, sorted alphabetically,
		but not case sensitive.
		"""
		from fontTools.misc import textTools
		return textTools.caselessSort(self.getGlyphOrder())

	def getGlyphName(self, glyphID, requireReal=False):
		try:
			return self.getGlyphOrder()[glyphID]
		except IndexError:
			if requireReal or not self.allowVID:
				# XXX The ??.W8.otf font that ships with OSX uses higher glyphIDs in
				# the cmap table than there are glyphs. I don't think it's legal...
				return "glyph%.5d" % glyphID
			else:
				# user intends virtual GID support
				try:
					glyphName = self.VIDDict[glyphID]
				except KeyError:
					glyphName  ="glyph%.5d" % glyphID
					self.last_vid = min(glyphID, self.last_vid )
					self.reverseVIDDict[glyphName] = glyphID
					self.VIDDict[glyphID] = glyphName
				return glyphName

	def getGlyphID(self, glyphName, requireReal=False):
		if not hasattr(self, "_reverseGlyphOrderDict"):
			self._buildReverseGlyphOrderDict()
		glyphOrder = self.getGlyphOrder()
		d = self._reverseGlyphOrderDict
		if glyphName not in d:
			if glyphName in glyphOrder:
				self._buildReverseGlyphOrderDict()
				return self.getGlyphID(glyphName)
			else:
				if requireReal:
					raise KeyError(glyphName)
				elif not self.allowVID:
					# Handle glyphXXX only
					if glyphName[:5] == "glyph":
						try:
							return int(glyphName[5:])
						except (NameError, ValueError):
							raise KeyError(glyphName)
				else:
					# user intends virtual GID support
					try:
						glyphID = self.reverseVIDDict[glyphName]
					except KeyError:
						# if name is in glyphXXX format, use the specified name.
						if glyphName[:5] == "glyph":
							try:
								glyphID = int(glyphName[5:])
							except (NameError, ValueError):
								glyphID = None
						if glyphID is None:
							glyphID = self.last_vid -1
							self.last_vid = glyphID
						self.reverseVIDDict[glyphName] = glyphID
						self.VIDDict[glyphID] = glyphName
					return glyphID

		glyphID = d[glyphName]
		if glyphName != glyphOrder[glyphID]:
			self._buildReverseGlyphOrderDict()
			return self.getGlyphID(glyphName)
		return glyphID

	def getReverseGlyphMap(self, rebuild=False):
		if rebuild or not hasattr(self, "_reverseGlyphOrderDict"):
			self._buildReverseGlyphOrderDict()
		return self._reverseGlyphOrderDict

	def _buildReverseGlyphOrderDict(self):
		self._reverseGlyphOrderDict = d = {}
		glyphOrder = self.getGlyphOrder()
		for glyphID in range(len(glyphOrder)):
			d[glyphOrder[glyphID]] = glyphID

	def _writeTable(self, tag, writer, done, tableCache=None):
		"""Internal helper function for self.save(). Keeps track of
		inter-table dependencies.
		"""
		if tag in done:
			return
		tableClass = getTableClass(tag)
		for masterTable in tableClass.dependencies:
			if masterTable not in done:
				if masterTable in self:
					self._writeTable(masterTable, writer, done, tableCache)
				else:
					done.append(masterTable)
		done.append(tag)
		tabledata = self.getTableData(tag)
		if tableCache is not None:
			entry = tableCache.get((Tag(tag), tabledata))
			if entry is not None:
				log.debug("reusing '%s' table", tag)
				writer.setEntry(tag, entry)
				return
		log.debug("writing '%s' table to disk", tag)
		writer[tag] = tabledata
		if tableCache is not None:
			tableCache[(Tag(tag), tabledata)] = writer[tag]

	def getTableData(self, tag):
		"""Returns raw table data, whether compiled or directly read from disk.
		"""
		tag = Tag(tag)
		if self.isLoaded(tag):
			log.debug("compiling '%s' table", tag)
			return self.tables[tag].compile(self)
		elif self.reader and tag in self.reader:
			log.debug("Reading '%s' table from disk", tag)
			return self.reader[tag]
		else:
			raise KeyError(tag)

	def getGlyphSet(self, preferCFF=True):
		"""Return a generic GlyphSet, which is a dict-like object
		mapping glyph names to glyph objects. The returned glyph objects
		have a .draw() method that supports the Pen protocol, and will
		have an attribute named 'width'.

		If the font is CFF-based, the outlines will be taken from the 'CFF ' or
		'CFF2' tables. Otherwise the outlines will be taken from the 'glyf' table.
		If the font contains both a 'CFF '/'CFF2' and a 'glyf' table, you can use
		the 'preferCFF' argument to specify which one should be taken. If the
		font contains both a 'CFF ' and a 'CFF2' table, the latter is taken.
		"""
		glyphs = None
		if (preferCFF and any(tb in self for tb in ["CFF ", "CFF2"]) or
		   ("glyf" not in self and any(tb in self for tb in ["CFF ", "CFF2"]))):
			table_tag = "CFF2" if "CFF2" in self else "CFF "
			glyphs = _TTGlyphSet(self,
			    list(self[table_tag].cff.values())[0].CharStrings, _TTGlyphCFF)

		if glyphs is None and "glyf" in self:
			glyphs = _TTGlyphSet(self, self["glyf"], _TTGlyphGlyf)

		if glyphs is None:
			raise TTLibError("Font contains no outlines")

		return glyphs

	def getBestCmap(self, cmapPreferences=((3, 10), (0, 6), (0, 4), (3, 1), (0, 3), (0, 2), (0, 1), (0, 0))):
		"""Return the 'best' unicode cmap dictionary available in the font,
		or None, if no unicode cmap subtable is available.

		By default it will search for the following (platformID, platEncID)
		pairs:
			(3, 10), (0, 6), (0, 4), (3, 1), (0, 3), (0, 2), (0, 1), (0, 0)
		This can be customized via the cmapPreferences argument.
		"""
		return self["cmap"].getBestCmap(cmapPreferences=cmapPreferences)
Exemple #8
0
    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
Exemple #9
0
class TTFont(object):
    """Represents a TrueType font.

	The object manages file input and output, and offers a convenient way of
	accessing tables. Tables will be only decompiled when necessary, ie. when
	they're actually accessed. This means that simple operations can be extremely fast.

	Example usage::

		>> from fontTools import ttLib
		>> tt = ttLib.TTFont("afont.ttf") # Load an existing font file
		>> tt['maxp'].numGlyphs
		242
		>> tt['OS/2'].achVendID
		'B&H\000'
		>> tt['head'].unitsPerEm
		2048

	For details of the objects returned when accessing each table, see :ref:`tables`.
	To add a table to the font, use the :py:func:`newTable` function::

		>> os2 = newTable("OS/2")
		>> os2.version = 4
		>> # set other attributes
		>> font["OS/2"] = os2

	TrueType fonts can also be serialized to and from XML format (see also the
	:ref:`ttx` binary)::

		>> tt.saveXML("afont.ttx")
		Dumping 'LTSH' table...
		Dumping 'OS/2' table...
		[...]

		>> tt2 = ttLib.TTFont() # Create a new font object
		>> tt2.importXML("afont.ttx")
		>> tt2['maxp'].numGlyphs
		242
	
	The TTFont object may be used as a context manager; this will cause the file
	reader to be closed after the context ``with`` block is exited::

		with TTFont(filename) as f:
			# Do stuff

	Args:
		file: When reading a font from disk, either a pathname pointing to a file,
			or a readable file object.
		res_name_or_index: If running on a Macintosh, either a sfnt resource name or
			an sfnt resource index number. If the index number is zero, TTLib will
			autodetect whether the file is a flat file or a suitcase. (If it is a suitcase,
			only the first 'sfnt' resource will be read.)
		sfntVersion (str): When constructing a font object from scratch, sets the four-byte
			sfnt magic number to be used. Defaults to ``\0\1\0\0`` (TrueType). To create
			an OpenType file, use ``OTTO``.
		flavor (str): Set this to ``woff`` when creating a WOFF file or ``woff2`` for a WOFF2
			file.
		checkChecksums (int): How checksum data should be treated. Default is 0
			(no checking). Set to 1 to check and warn on wrong checksums; set to 2 to
			raise an exception if any wrong checksums are found.
		recalcBBoxes (bool): If true (the default), recalculates ``glyf``, ``CFF ``,
			``head`` bounding box values and ``hhea``/``vhea`` min/max values on save.
			Also compiles the glyphs on importing, which saves memory consumption and
			time.
		ignoreDecompileErrors (bool): If true, exceptions raised during table decompilation
			will be ignored, and the binary data will be returned for those tables instead.
		recalcTimestamp (bool): If true (the default), sets the ``modified`` timestamp in
			the ``head`` table on save.
		fontNumber (int): The index of the font in a TrueType Collection file.
		lazy (bool): 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.
	"""
    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

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def close(self):
        """If we still have a reader object, close it."""
        if self.reader is not None:
            self.reader.close()

    def save(self, file, reorderTables=True):
        """Save the font to disk.

		Args:
			file: Similarly to the constructor, can be either a pathname or a writable
				file object.
			reorderTables (Option[bool]): If true (the default), reorder the tables,
				sorting them by tag (recommended by the OpenType specification). If
				false, retain the original font order. If None, reorder by table
				dependency (fastest).
		"""
        if not hasattr(file, "write"):
            if self.lazy and self.reader.file.name == file:
                raise TTLibError(
                    "Can't overwrite TTFont when 'lazy' attribute is True")
            createStream = True
        else:
            # assume "file" is a writable file object
            createStream = False

        tmp = BytesIO()

        writer_reordersTables = self._save(tmp)

        if not (reorderTables is None or writer_reordersTables or
                (reorderTables is False and self.reader is None)):
            if reorderTables is False:
                # sort tables using the original font's order
                tableOrder = list(self.reader.keys())
            else:
                # use the recommended order from the OpenType specification
                tableOrder = None
            tmp.flush()
            tmp2 = BytesIO()
            reorderFontTables(tmp, tmp2, tableOrder)
            tmp.close()
            tmp = tmp2

        if createStream:
            # "file" is a path
            with open(file, "wb") as file:
                file.write(tmp.getvalue())
        else:
            file.write(tmp.getvalue())

        tmp.close()

    def _save(self, file, tableCache=None):
        """Internal function, to be shared by save() and TTCollection.save()"""

        if self.recalcTimestamp and 'head' in self:
            self[
                'head']  # make sure 'head' is loaded so the recalculation is actually done

        tags = list(self.keys())
        if "GlyphOrder" in tags:
            tags.remove("GlyphOrder")
        numTables = len(tags)
        # write to a temporary stream to allow saving to unseekable streams
        writer = SFNTWriter(file, numTables, self.sfntVersion, self.flavor,
                            self.flavorData)

        done = []
        for tag in tags:
            self._writeTable(tag, writer, done, tableCache)

        writer.close()

        return writer.reordersTables()

    def saveXML(self, fileOrPath, newlinestr="\n", **kwargs):
        """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.
		"""

        writer = xmlWriter.XMLWriter(fileOrPath, newlinestr=newlinestr)
        self._saveXML(writer, **kwargs)
        writer.close()

    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 _tableToXML(self, writer, tag, quiet=None, splitGlyphs=False):
        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
        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, splitGlyphs=splitGlyphs)
        else:
            table.toXML(writer, self)
        writer.endtag(xmlTag)
        writer.newline()
        writer.newline()

    def importXML(self, fileOrPath, 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)
        reader.read()

    def isLoaded(self, tag):
        """Return true if the table identified by ``tag`` has been
		decompiled and loaded into memory."""
        return tag in self.tables

    def has_key(self, tag):
        """Test if the table identified by ``tag`` is present in the font.

		As well as this method, ``tag in font`` can also be used to determine the
		presence of the table."""
        if self.isLoaded(tag):
            return True
        elif self.reader and tag in self.reader:
            return True
        elif tag == "GlyphOrder":
            return True
        else:
            return False

    __contains__ = has_key

    def keys(self):
        """Returns the list of tables in the font, along with the ``GlyphOrder`` pseudo-table."""
        keys = list(self.tables.keys())
        if self.reader:
            for key in list(self.reader.keys()):
                if key not in keys:
                    keys.append(key)

        if "GlyphOrder" in keys:
            keys.remove("GlyphOrder")
        keys = sortedTagList(keys)
        return ["GlyphOrder"] + keys

    def __len__(self):
        return len(list(self.keys()))

    def __getitem__(self, tag):
        tag = Tag(tag)
        table = self.tables.get(tag)
        if table is None:
            if tag == "GlyphOrder":
                table = GlyphOrder(tag)
                self.tables[tag] = table
            elif self.reader is not None:
                table = self._readTable(tag)
            else:
                raise KeyError("'%s' table not found" % tag)
        return table

    def _readTable(self, tag):
        log.debug("Reading '%s' table from disk", tag)
        data = self.reader[tag]
        if self._tableCache is not None:
            table = self._tableCache.get((tag, data))
            if table is not None:
                return table
        tableClass = getTableClass(tag)
        table = tableClass(tag)
        self.tables[tag] = table
        log.debug("Decompiling '%s' table", tag)
        try:
            table.decompile(data, self)
        except Exception:
            if not self.ignoreDecompileErrors:
                raise
            # fall back to DefaultTable, retaining the binary table data
            log.exception(
                "An exception occurred during the decompilation of the '%s' table",
                tag)
            from .tables.DefaultTable import DefaultTable
            file = StringIO()
            traceback.print_exc(file=file)
            table = DefaultTable(tag)
            table.ERROR = file.getvalue()
            self.tables[tag] = table
            table.decompile(data, self)
        if self._tableCache is not None:
            self._tableCache[(tag, data)] = table
        return table

    def __setitem__(self, tag, table):
        self.tables[Tag(tag)] = table

    def __delitem__(self, tag):
        if tag not in self:
            raise KeyError("'%s' table not found" % tag)
        if tag in self.tables:
            del self.tables[tag]
        if self.reader and tag in self.reader:
            del self.reader[tag]

    def get(self, tag, default=None):
        """Returns the table if it exists or (optionally) a default if it doesn't."""
        try:
            return self[tag]
        except KeyError:
            return default

    def setGlyphOrder(self, glyphOrder):
        """Set the glyph order

		Args:
			glyphOrder ([str]): List of glyph names in order.
		"""
        self.glyphOrder = glyphOrder
        if hasattr(self, '_reverseGlyphOrderDict'):
            del self._reverseGlyphOrderDict

    def getGlyphOrder(self):
        """Returns a list of glyph names ordered by their position in the font."""
        try:
            return self.glyphOrder
        except AttributeError:
            pass
        if 'CFF ' in self:
            cff = self['CFF ']
            self.glyphOrder = cff.getGlyphOrder()
        elif 'post' in self:
            # TrueType font
            glyphOrder = self['post'].getGlyphOrder()
            if glyphOrder is None:
                #
                # No names found in the 'post' table.
                # Try to create glyph names from the unicode cmap (if available)
                # in combination with the Adobe Glyph List (AGL).
                #
                self._getGlyphNamesFromCmap()
            else:
                self.glyphOrder = glyphOrder
        else:
            self._getGlyphNamesFromCmap()
        return self.glyphOrder

    def _getGlyphNamesFromCmap(self):
        #
        # This is rather convoluted, but then again, it's an interesting problem:
        # - we need to use the unicode values found in the cmap table to
        #   build glyph names (eg. because there is only a minimal post table,
        #   or none at all).
        # - but the cmap parser also needs glyph names to work with...
        # So here's what we do:
        # - make up glyph names based on glyphID
        # - load a temporary cmap table based on those names
        # - extract the unicode values, build the "real" glyph names
        # - unload the temporary cmap table
        #
        if self.isLoaded("cmap"):
            # Bootstrapping: we're getting called by the cmap parser
            # itself. This means self.tables['cmap'] contains a partially
            # loaded cmap, making it impossible to get at a unicode
            # subtable here. We remove the partially loaded cmap and
            # restore it later.
            # This only happens if the cmap table is loaded before any
            # other table that does f.getGlyphOrder()  or f.getGlyphName().
            cmapLoading = self.tables['cmap']
            del self.tables['cmap']
        else:
            cmapLoading = None
        # Make up glyph names based on glyphID, which will be used by the
        # temporary cmap and by the real cmap in case we don't find a unicode
        # cmap.
        numGlyphs = int(self['maxp'].numGlyphs)
        glyphOrder = [None] * numGlyphs
        glyphOrder[0] = ".notdef"
        for i in range(1, numGlyphs):
            glyphOrder[i] = "glyph%.5d" % i
        # Set the glyph order, so the cmap parser has something
        # to work with (so we don't get called recursively).
        self.glyphOrder = glyphOrder

        # Make up glyph names based on the reversed cmap table. Because some
        # glyphs (eg. ligatures or alternates) may not be reachable via cmap,
        # this naming table will usually not cover all glyphs in the font.
        # If the font has no Unicode cmap table, reversecmap will be empty.
        if 'cmap' in self:
            reversecmap = self['cmap'].buildReversed()
        else:
            reversecmap = {}
        useCount = {}
        for i in range(numGlyphs):
            tempName = glyphOrder[i]
            if tempName in reversecmap:
                # If a font maps both U+0041 LATIN CAPITAL LETTER A and
                # U+0391 GREEK CAPITAL LETTER ALPHA to the same glyph,
                # we prefer naming the glyph as "A".
                glyphName = self._makeGlyphName(min(reversecmap[tempName]))
                numUses = useCount[glyphName] = useCount.get(glyphName, 0) + 1
                if numUses > 1:
                    glyphName = "%s.alt%d" % (glyphName, numUses - 1)
                glyphOrder[i] = glyphName

        if 'cmap' in self:
            # Delete the temporary cmap table from the cache, so it can
            # be parsed again with the right names.
            del self.tables['cmap']
            self.glyphOrder = glyphOrder
            if cmapLoading:
                # restore partially loaded cmap, so it can continue loading
                # using the proper names.
                self.tables['cmap'] = cmapLoading

    @staticmethod
    def _makeGlyphName(codepoint):
        from fontTools import agl  # Adobe Glyph List
        if codepoint in agl.UV2AGL:
            return agl.UV2AGL[codepoint]
        elif codepoint <= 0xFFFF:
            return "uni%04X" % codepoint
        else:
            return "u%X" % codepoint

    def getGlyphNames(self):
        """Get a list of glyph names, sorted alphabetically."""
        glyphNames = sorted(self.getGlyphOrder())
        return glyphNames

    def getGlyphNames2(self):
        """Get a list of glyph names, sorted alphabetically,
		but not case sensitive.
		"""
        from fontTools.misc import textTools
        return textTools.caselessSort(self.getGlyphOrder())

    def getGlyphName(self, glyphID):
        """Returns the name for the glyph with the given ID.

		If no name is available, synthesises one with the form ``glyphXXXXX``` where
		```XXXXX`` is the zero-padded glyph ID.
		"""
        try:
            return self.getGlyphOrder()[glyphID]
        except IndexError:
            return "glyph%.5d" % glyphID

    def getGlyphNameMany(self, lst):
        """Converts a list of glyph IDs into a list of glyph names."""
        glyphOrder = self.getGlyphOrder()
        cnt = len(glyphOrder)
        return [
            glyphOrder[gid] if gid < cnt else "glyph%.5d" % gid for gid in lst
        ]

    def getGlyphID(self, glyphName):
        """Returns the ID of the glyph with the given name."""
        try:
            return self.getReverseGlyphMap()[glyphName]
        except KeyError:
            if glyphName[:5] == "glyph":
                try:
                    return int(glyphName[5:])
                except (NameError, ValueError):
                    raise KeyError(glyphName)

    def getGlyphIDMany(self, lst):
        """Converts a list of glyph names into a list of glyph IDs."""
        d = self.getReverseGlyphMap()
        try:
            return [d[glyphName] for glyphName in lst]
        except KeyError:
            getGlyphID = self.getGlyphID
            return [getGlyphID(glyphName) for glyphName in lst]

    def getReverseGlyphMap(self, rebuild=False):
        """Returns a mapping of glyph names to glyph IDs."""
        if rebuild or not hasattr(self, "_reverseGlyphOrderDict"):
            self._buildReverseGlyphOrderDict()
        return self._reverseGlyphOrderDict

    def _buildReverseGlyphOrderDict(self):
        self._reverseGlyphOrderDict = d = {}
        for glyphID, glyphName in enumerate(self.getGlyphOrder()):
            d[glyphName] = glyphID
        return d

    def _writeTable(self, tag, writer, done, tableCache=None):
        """Internal helper function for self.save(). Keeps track of
		inter-table dependencies.
		"""
        if tag in done:
            return
        tableClass = getTableClass(tag)
        for masterTable in tableClass.dependencies:
            if masterTable not in done:
                if masterTable in self:
                    self._writeTable(masterTable, writer, done, tableCache)
                else:
                    done.append(masterTable)
        done.append(tag)
        tabledata = self.getTableData(tag)
        if tableCache is not None:
            entry = tableCache.get((Tag(tag), tabledata))
            if entry is not None:
                log.debug("reusing '%s' table", tag)
                writer.setEntry(tag, entry)
                return
        log.debug("Writing '%s' table to disk", tag)
        writer[tag] = tabledata
        if tableCache is not None:
            tableCache[(Tag(tag), tabledata)] = writer[tag]

    def getTableData(self, tag):
        """Returns the binary representation of a table.

		If the table is currently loaded and in memory, the data is compiled to
		binary and returned; if it is not currently loaded, the binary data is
		read from the font file and returned.
		"""
        tag = Tag(tag)
        if self.isLoaded(tag):
            log.debug("Compiling '%s' table", tag)
            return self.tables[tag].compile(self)
        elif self.reader and tag in self.reader:
            log.debug("Reading '%s' table from disk", tag)
            return self.reader[tag]
        else:
            raise KeyError(tag)

    def getGlyphSet(self, preferCFF=True):
        """Return a generic GlyphSet, which is a dict-like object
		mapping glyph names to glyph objects. The returned glyph objects
		have a .draw() method that supports the Pen protocol, and will
		have an attribute named 'width'.

		If the font is CFF-based, the outlines will be taken from the 'CFF ' or
		'CFF2' tables. Otherwise the outlines will be taken from the 'glyf' table.
		If the font contains both a 'CFF '/'CFF2' and a 'glyf' table, you can use
		the 'preferCFF' argument to specify which one should be taken. If the
		font contains both a 'CFF ' and a 'CFF2' table, the latter is taken.
		"""
        glyphs = None
        if (preferCFF and any(tb in self for tb in ["CFF ", "CFF2"])
                or ("glyf" not in self and any(tb in self
                                               for tb in ["CFF ", "CFF2"]))):
            table_tag = "CFF2" if "CFF2" in self else "CFF "
            glyphs = _TTGlyphSet(
                self,
                list(self[table_tag].cff.values())[0].CharStrings, _TTGlyphCFF)

        if glyphs is None and "glyf" in self:
            glyphs = _TTGlyphSet(self, self["glyf"], _TTGlyphGlyf)

        if glyphs is None:
            raise TTLibError("Font contains no outlines")

        return glyphs

    def getBestCmap(self,
                    cmapPreferences=((3, 10), (0, 6), (0, 4), (3, 1), (0, 3),
                                     (0, 2), (0, 1), (0, 0))):
        """Return the 'best' unicode cmap dictionary available in the font,
		or None, if no unicode cmap subtable is available.

		By default it will search for the following (platformID, platEncID)
		pairs::

			(3, 10),
			(0, 6),
			(0, 4),
			(3, 1),
			(0, 3),
			(0, 2),
			(0, 1),
			(0, 0)

		This can be customized via the ``cmapPreferences`` argument.
		"""
        return self["cmap"].getBestCmap(cmapPreferences=cmapPreferences)
Exemple #10
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,
                 _tableCache=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.
		"""

        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
            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
Exemple #11
0
class TTFont(object):
    """The main font object. It manages file input and output, and offers
	a convenient way of accessing tables.
	Tables will be only decompiled when necessary, ie. when they're actually
	accessed. This means that simple operations can be extremely fast.
	"""
    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,
                 _tableCache=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.
		"""

        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
            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

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        self.close()

    def close(self):
        """If we still have a reader object, close it."""
        if self.reader is not None:
            self.reader.close()

    def save(self, file, reorderTables=True):
        """Save the font to disk. Similarly to the constructor,
		the 'file' argument can be either a pathname or a writable
		file object.
		"""
        if not hasattr(file, "write"):
            if self.lazy and self.reader.file.name == file:
                raise TTLibError(
                    "Can't overwrite TTFont when 'lazy' attribute is True")
            closeStream = True
            file = open(file, "wb")
        else:
            # assume "file" is a writable file object
            closeStream = False

        tmp = BytesIO()

        writer_reordersTables = self._save(tmp)

        if (reorderTables is None or writer_reordersTables
                or (reorderTables is False and self.reader is None)):
            # don't reorder tables and save as is
            file.write(tmp.getvalue())
            tmp.close()
        else:
            if reorderTables is False:
                # sort tables using the original font's order
                tableOrder = list(self.reader.keys())
            else:
                # use the recommended order from the OpenType specification
                tableOrder = None
            tmp.flush()
            tmp2 = BytesIO()
            reorderFontTables(tmp, tmp2, tableOrder)
            file.write(tmp2.getvalue())
            tmp.close()
            tmp2.close()

        if closeStream:
            file.close()

    def _save(self, file, tableCache=None):
        """Internal function, to be shared by save() and TTCollection.save()"""

        if self.recalcTimestamp and 'head' in self:
            self[
                'head']  # make sure 'head' is loaded so the recalculation is actually done

        tags = list(self.keys())
        if "GlyphOrder" in tags:
            tags.remove("GlyphOrder")
        numTables = len(tags)
        # write to a temporary stream to allow saving to unseekable streams
        writer = SFNTWriter(file, numTables, self.sfntVersion, self.flavor,
                            self.flavorData)

        done = []
        for tag in tags:
            self._writeTable(tag, writer, done, tableCache)

        writer.close()

        return writer.reordersTables()

    def saveXML(self, fileOrPath, newlinestr=None, **kwargs):
        """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.
		"""

        writer = xmlWriter.XMLWriter(fileOrPath, newlinestr=newlinestr)
        self._saveXML(writer, **kwargs)
        writer.close()

    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 _tableToXML(self, writer, tag, quiet=None, splitGlyphs=False):
        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
        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, splitGlyphs=splitGlyphs)
        else:
            table.toXML(writer, self)
        writer.endtag(xmlTag)
        writer.newline()
        writer.newline()

    def importXML(self, fileOrPath, 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)
        reader.read()

    def isLoaded(self, tag):
        """Return true if the table identified by 'tag' has been
		decompiled and loaded into memory."""
        return tag in self.tables

    def has_key(self, tag):
        if self.isLoaded(tag):
            return True
        elif self.reader and tag in self.reader:
            return True
        elif tag == "GlyphOrder":
            return True
        else:
            return False

    __contains__ = has_key

    def keys(self):
        keys = list(self.tables.keys())
        if self.reader:
            for key in list(self.reader.keys()):
                if key not in keys:
                    keys.append(key)

        if "GlyphOrder" in keys:
            keys.remove("GlyphOrder")
        keys = sortedTagList(keys)
        return ["GlyphOrder"] + keys

    def __len__(self):
        return len(list(self.keys()))

    def __getitem__(self, tag):
        tag = Tag(tag)
        try:
            return self.tables[tag]
        except KeyError:
            if tag == "GlyphOrder":
                table = GlyphOrder(tag)
                self.tables[tag] = table
                return table
            if self.reader is not None:
                import traceback
                log.debug("Reading '%s' table from disk", tag)
                data = self.reader[tag]
                if self._tableCache is not None:
                    table = self._tableCache.get((Tag(tag), data))
                    if table is not None:
                        return table
                tableClass = getTableClass(tag)
                table = tableClass(tag)
                self.tables[tag] = table
                log.debug("Decompiling '%s' table", tag)
                try:
                    table.decompile(data, self)
                except:
                    if not self.ignoreDecompileErrors:
                        raise
                    # fall back to DefaultTable, retaining the binary table data
                    log.exception(
                        "An exception occurred during the decompilation of the '%s' table",
                        tag)
                    from .tables.DefaultTable import DefaultTable
                    file = StringIO()
                    traceback.print_exc(file=file)
                    table = DefaultTable(tag)
                    table.ERROR = file.getvalue()
                    self.tables[tag] = table
                    table.decompile(data, self)
                if self._tableCache is not None:
                    self._tableCache[(Tag(tag), data)] = table
                return table
            else:
                raise KeyError("'%s' table not found" % tag)

    def __setitem__(self, tag, table):
        self.tables[Tag(tag)] = table

    def __delitem__(self, tag):
        if tag not in self:
            raise KeyError("'%s' table not found" % tag)
        if tag in self.tables:
            del self.tables[tag]
        if self.reader and tag in self.reader:
            del self.reader[tag]

    def get(self, tag, default=None):
        try:
            return self[tag]
        except KeyError:
            return default

    def setGlyphOrder(self, glyphOrder):
        self.glyphOrder = glyphOrder

    def getGlyphOrder(self):
        try:
            return self.glyphOrder
        except AttributeError:
            pass
        if 'CFF ' in self:
            cff = self['CFF ']
            self.glyphOrder = cff.getGlyphOrder()
        elif 'post' in self:
            # TrueType font
            glyphOrder = self['post'].getGlyphOrder()
            if glyphOrder is None:
                #
                # No names found in the 'post' table.
                # Try to create glyph names from the unicode cmap (if available)
                # in combination with the Adobe Glyph List (AGL).
                #
                self._getGlyphNamesFromCmap()
            else:
                self.glyphOrder = glyphOrder
        else:
            self._getGlyphNamesFromCmap()
        return self.glyphOrder

    def _getGlyphNamesFromCmap(self):
        #
        # This is rather convoluted, but then again, it's an interesting problem:
        # - we need to use the unicode values found in the cmap table to
        #   build glyph names (eg. because there is only a minimal post table,
        #   or none at all).
        # - but the cmap parser also needs glyph names to work with...
        # So here's what we do:
        # - make up glyph names based on glyphID
        # - load a temporary cmap table based on those names
        # - extract the unicode values, build the "real" glyph names
        # - unload the temporary cmap table
        #
        if self.isLoaded("cmap"):
            # Bootstrapping: we're getting called by the cmap parser
            # itself. This means self.tables['cmap'] contains a partially
            # loaded cmap, making it impossible to get at a unicode
            # subtable here. We remove the partially loaded cmap and
            # restore it later.
            # This only happens if the cmap table is loaded before any
            # other table that does f.getGlyphOrder()  or f.getGlyphName().
            cmapLoading = self.tables['cmap']
            del self.tables['cmap']
        else:
            cmapLoading = None
        # Make up glyph names based on glyphID, which will be used by the
        # temporary cmap and by the real cmap in case we don't find a unicode
        # cmap.
        numGlyphs = int(self['maxp'].numGlyphs)
        glyphOrder = [None] * numGlyphs
        glyphOrder[0] = ".notdef"
        for i in range(1, numGlyphs):
            glyphOrder[i] = "glyph%.5d" % i
        # Set the glyph order, so the cmap parser has something
        # to work with (so we don't get called recursively).
        self.glyphOrder = glyphOrder

        # Make up glyph names based on the reversed cmap table. Because some
        # glyphs (eg. ligatures or alternates) may not be reachable via cmap,
        # this naming table will usually not cover all glyphs in the font.
        # If the font has no Unicode cmap table, reversecmap will be empty.
        if 'cmap' in self:
            reversecmap = self['cmap'].buildReversed()
        else:
            reversecmap = {}
        useCount = {}
        for i in range(numGlyphs):
            tempName = glyphOrder[i]
            if tempName in reversecmap:
                # If a font maps both U+0041 LATIN CAPITAL LETTER A and
                # U+0391 GREEK CAPITAL LETTER ALPHA to the same glyph,
                # we prefer naming the glyph as "A".
                glyphName = self._makeGlyphName(min(reversecmap[tempName]))
                numUses = useCount[glyphName] = useCount.get(glyphName, 0) + 1
                if numUses > 1:
                    glyphName = "%s.alt%d" % (glyphName, numUses - 1)
                glyphOrder[i] = glyphName

        if 'cmap' in self:
            # Delete the temporary cmap table from the cache, so it can
            # be parsed again with the right names.
            del self.tables['cmap']
            self.glyphOrder = glyphOrder
            if cmapLoading:
                # restore partially loaded cmap, so it can continue loading
                # using the proper names.
                self.tables['cmap'] = cmapLoading

    @staticmethod
    def _makeGlyphName(codepoint):
        from fontTools import agl  # Adobe Glyph List
        if codepoint in agl.UV2AGL:
            return agl.UV2AGL[codepoint]
        elif codepoint <= 0xFFFF:
            return "uni%04X" % codepoint
        else:
            return "u%X" % codepoint

    def getGlyphNames(self):
        """Get a list of glyph names, sorted alphabetically."""
        glyphNames = sorted(self.getGlyphOrder())
        return glyphNames

    def getGlyphNames2(self):
        """Get a list of glyph names, sorted alphabetically,
		but not case sensitive.
		"""
        from fontTools.misc import textTools
        return textTools.caselessSort(self.getGlyphOrder())

    def getGlyphName(self, glyphID, requireReal=False):
        try:
            return self.getGlyphOrder()[glyphID]
        except IndexError:
            if requireReal or not self.allowVID:
                # XXX The ??.W8.otf font that ships with OSX uses higher glyphIDs in
                # the cmap table than there are glyphs. I don't think it's legal...
                return "glyph%.5d" % glyphID
            else:
                # user intends virtual GID support
                try:
                    glyphName = self.VIDDict[glyphID]
                except KeyError:
                    glyphName = "glyph%.5d" % glyphID
                    self.last_vid = min(glyphID, self.last_vid)
                    self.reverseVIDDict[glyphName] = glyphID
                    self.VIDDict[glyphID] = glyphName
                return glyphName

    def getGlyphID(self, glyphName, requireReal=False):
        if not hasattr(self, "_reverseGlyphOrderDict"):
            self._buildReverseGlyphOrderDict()
        glyphOrder = self.getGlyphOrder()
        d = self._reverseGlyphOrderDict
        if glyphName not in d:
            if glyphName in glyphOrder:
                self._buildReverseGlyphOrderDict()
                return self.getGlyphID(glyphName)
            else:
                if requireReal:
                    raise KeyError(glyphName)
                elif not self.allowVID:
                    # Handle glyphXXX only
                    if glyphName[:5] == "glyph":
                        try:
                            return int(glyphName[5:])
                        except (NameError, ValueError):
                            raise KeyError(glyphName)
                else:
                    # user intends virtual GID support
                    try:
                        glyphID = self.reverseVIDDict[glyphName]
                    except KeyError:
                        # if name is in glyphXXX format, use the specified name.
                        if glyphName[:5] == "glyph":
                            try:
                                glyphID = int(glyphName[5:])
                            except (NameError, ValueError):
                                glyphID = None
                        if glyphID is None:
                            glyphID = self.last_vid - 1
                            self.last_vid = glyphID
                        self.reverseVIDDict[glyphName] = glyphID
                        self.VIDDict[glyphID] = glyphName
                    return glyphID

        glyphID = d[glyphName]
        if glyphName != glyphOrder[glyphID]:
            self._buildReverseGlyphOrderDict()
            return self.getGlyphID(glyphName)
        return glyphID

    def getReverseGlyphMap(self, rebuild=False):
        if rebuild or not hasattr(self, "_reverseGlyphOrderDict"):
            self._buildReverseGlyphOrderDict()
        return self._reverseGlyphOrderDict

    def _buildReverseGlyphOrderDict(self):
        self._reverseGlyphOrderDict = d = {}
        glyphOrder = self.getGlyphOrder()
        for glyphID in range(len(glyphOrder)):
            d[glyphOrder[glyphID]] = glyphID

    def _writeTable(self, tag, writer, done, tableCache=None):
        """Internal helper function for self.save(). Keeps track of
		inter-table dependencies.
		"""
        if tag in done:
            return
        tableClass = getTableClass(tag)
        for masterTable in tableClass.dependencies:
            if masterTable not in done:
                if masterTable in self:
                    self._writeTable(masterTable, writer, done, tableCache)
                else:
                    done.append(masterTable)
        done.append(tag)
        tabledata = self.getTableData(tag)
        if tableCache is not None:
            entry = tableCache.get((Tag(tag), tabledata))
            if entry is not None:
                log.debug("reusing '%s' table", tag)
                writer.setEntry(tag, entry)
                return
        log.debug("writing '%s' table to disk", tag)
        writer[tag] = tabledata
        if tableCache is not None:
            tableCache[(Tag(tag), tabledata)] = writer[tag]

    def getTableData(self, tag):
        """Returns raw table data, whether compiled or directly read from disk.
		"""
        tag = Tag(tag)
        if self.isLoaded(tag):
            log.debug("compiling '%s' table", tag)
            return self.tables[tag].compile(self)
        elif self.reader and tag in self.reader:
            log.debug("Reading '%s' table from disk", tag)
            return self.reader[tag]
        else:
            raise KeyError(tag)

    def getGlyphSet(self, preferCFF=True):
        """Return a generic GlyphSet, which is a dict-like object
		mapping glyph names to glyph objects. The returned glyph objects
		have a .draw() method that supports the Pen protocol, and will
		have an attribute named 'width'.

		If the font is CFF-based, the outlines will be taken from the 'CFF ' or
		'CFF2' tables. Otherwise the outlines will be taken from the 'glyf' table.
		If the font contains both a 'CFF '/'CFF2' and a 'glyf' table, you can use
		the 'preferCFF' argument to specify which one should be taken. If the
		font contains both a 'CFF ' and a 'CFF2' table, the latter is taken.
		"""
        glyphs = None
        if (preferCFF and any(tb in self for tb in ["CFF ", "CFF2"])
                or ("glyf" not in self and any(tb in self
                                               for tb in ["CFF ", "CFF2"]))):
            table_tag = "CFF2" if "CFF2" in self else "CFF "
            glyphs = _TTGlyphSet(
                self,
                list(self[table_tag].cff.values())[0].CharStrings, _TTGlyphCFF)

        if glyphs is None and "glyf" in self:
            glyphs = _TTGlyphSet(self, self["glyf"], _TTGlyphGlyf)

        if glyphs is None:
            raise TTLibError("Font contains no outlines")

        return glyphs

    def getBestCmap(self,
                    cmapPreferences=((3, 10), (0, 6), (0, 4), (3, 1), (0, 3),
                                     (0, 2), (0, 1), (0, 0))):
        """Return the 'best' unicode cmap dictionary available in the font,
		or None, if no unicode cmap subtable is available.

		By default it will search for the following (platformID, platEncID)
		pairs:
			(3, 10), (0, 6), (0, 4), (3, 1), (0, 3), (0, 2), (0, 1), (0, 0)
		This can be customized via the cmapPreferences argument.
		"""
        return self["cmap"].getBestCmap(cmapPreferences=cmapPreferences)