ttFont.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  1. from fontTools.config import Config
  2. from fontTools.misc import xmlWriter
  3. from fontTools.misc.configTools import AbstractConfig
  4. from fontTools.misc.textTools import Tag, byteord, tostr
  5. from fontTools.misc.loggingTools import deprecateArgument
  6. from fontTools.ttLib import TTLibError
  7. from fontTools.ttLib.ttGlyphSet import (
  8. _TTGlyph,
  9. _TTGlyphSetCFF,
  10. _TTGlyphSetGlyf,
  11. _TTGlyphSetVARC,
  12. )
  13. from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter
  14. from io import BytesIO, StringIO, UnsupportedOperation
  15. import os
  16. import logging
  17. import traceback
  18. log = logging.getLogger(__name__)
  19. class TTFont(object):
  20. """Represents a TrueType font.
  21. The object manages file input and output, and offers a convenient way of
  22. accessing tables. Tables will be only decompiled when necessary, ie. when
  23. they're actually accessed. This means that simple operations can be extremely fast.
  24. Example usage::
  25. >> from fontTools import ttLib
  26. >> tt = ttLib.TTFont("afont.ttf") # Load an existing font file
  27. >> tt['maxp'].numGlyphs
  28. 242
  29. >> tt['OS/2'].achVendID
  30. 'B&H\000'
  31. >> tt['head'].unitsPerEm
  32. 2048
  33. For details of the objects returned when accessing each table, see :ref:`tables`.
  34. To add a table to the font, use the :py:func:`newTable` function::
  35. >> os2 = newTable("OS/2")
  36. >> os2.version = 4
  37. >> # set other attributes
  38. >> font["OS/2"] = os2
  39. TrueType fonts can also be serialized to and from XML format (see also the
  40. :ref:`ttx` binary)::
  41. >> tt.saveXML("afont.ttx")
  42. Dumping 'LTSH' table...
  43. Dumping 'OS/2' table...
  44. [...]
  45. >> tt2 = ttLib.TTFont() # Create a new font object
  46. >> tt2.importXML("afont.ttx")
  47. >> tt2['maxp'].numGlyphs
  48. 242
  49. The TTFont object may be used as a context manager; this will cause the file
  50. reader to be closed after the context ``with`` block is exited::
  51. with TTFont(filename) as f:
  52. # Do stuff
  53. Args:
  54. file: When reading a font from disk, either a pathname pointing to a file,
  55. or a readable file object.
  56. res_name_or_index: If running on a Macintosh, either a sfnt resource name or
  57. an sfnt resource index number. If the index number is zero, TTLib will
  58. autodetect whether the file is a flat file or a suitcase. (If it is a suitcase,
  59. only the first 'sfnt' resource will be read.)
  60. sfntVersion (str): When constructing a font object from scratch, sets the four-byte
  61. sfnt magic number to be used. Defaults to ``\0\1\0\0`` (TrueType). To create
  62. an OpenType file, use ``OTTO``.
  63. flavor (str): Set this to ``woff`` when creating a WOFF file or ``woff2`` for a WOFF2
  64. file.
  65. checkChecksums (int): How checksum data should be treated. Default is 0
  66. (no checking). Set to 1 to check and warn on wrong checksums; set to 2 to
  67. raise an exception if any wrong checksums are found.
  68. recalcBBoxes (bool): If true (the default), recalculates ``glyf``, ``CFF ``,
  69. ``head`` bounding box values and ``hhea``/``vhea`` min/max values on save.
  70. Also compiles the glyphs on importing, which saves memory consumption and
  71. time.
  72. ignoreDecompileErrors (bool): If true, exceptions raised during table decompilation
  73. will be ignored, and the binary data will be returned for those tables instead.
  74. recalcTimestamp (bool): If true (the default), sets the ``modified`` timestamp in
  75. the ``head`` table on save.
  76. fontNumber (int): The index of the font in a TrueType Collection file.
  77. lazy (bool): If lazy is set to True, many data structures are loaded lazily, upon
  78. access only. If it is set to False, many data structures are loaded immediately.
  79. The default is ``lazy=None`` which is somewhere in between.
  80. """
  81. def __init__(
  82. self,
  83. file=None,
  84. res_name_or_index=None,
  85. sfntVersion="\000\001\000\000",
  86. flavor=None,
  87. checkChecksums=0,
  88. verbose=None,
  89. recalcBBoxes=True,
  90. allowVID=NotImplemented,
  91. ignoreDecompileErrors=False,
  92. recalcTimestamp=True,
  93. fontNumber=-1,
  94. lazy=None,
  95. quiet=None,
  96. _tableCache=None,
  97. cfg={},
  98. ):
  99. for name in ("verbose", "quiet"):
  100. val = locals().get(name)
  101. if val is not None:
  102. deprecateArgument(name, "configure logging instead")
  103. setattr(self, name, val)
  104. self.lazy = lazy
  105. self.recalcBBoxes = recalcBBoxes
  106. self.recalcTimestamp = recalcTimestamp
  107. self.tables = {}
  108. self.reader = None
  109. self.cfg = cfg.copy() if isinstance(cfg, AbstractConfig) else Config(cfg)
  110. self.ignoreDecompileErrors = ignoreDecompileErrors
  111. if not file:
  112. self.sfntVersion = sfntVersion
  113. self.flavor = flavor
  114. self.flavorData = None
  115. return
  116. seekable = True
  117. if not hasattr(file, "read"):
  118. closeStream = True
  119. # assume file is a string
  120. if res_name_or_index is not None:
  121. # see if it contains 'sfnt' resources in the resource or data fork
  122. from . import macUtils
  123. if res_name_or_index == 0:
  124. if macUtils.getSFNTResIndices(file):
  125. # get the first available sfnt font.
  126. file = macUtils.SFNTResourceReader(file, 1)
  127. else:
  128. file = open(file, "rb")
  129. else:
  130. file = macUtils.SFNTResourceReader(file, res_name_or_index)
  131. else:
  132. file = open(file, "rb")
  133. else:
  134. # assume "file" is a readable file object
  135. closeStream = False
  136. # SFNTReader wants the input file to be seekable.
  137. # SpooledTemporaryFile has no seekable() on < 3.11, but still can seek:
  138. # https://github.com/fonttools/fonttools/issues/3052
  139. if hasattr(file, "seekable"):
  140. seekable = file.seekable()
  141. elif hasattr(file, "seek"):
  142. try:
  143. file.seek(0)
  144. except UnsupportedOperation:
  145. seekable = False
  146. if not self.lazy:
  147. # read input file in memory and wrap a stream around it to allow overwriting
  148. if seekable:
  149. file.seek(0)
  150. tmp = BytesIO(file.read())
  151. if hasattr(file, "name"):
  152. # save reference to input file name
  153. tmp.name = file.name
  154. if closeStream:
  155. file.close()
  156. file = tmp
  157. elif not seekable:
  158. raise TTLibError("Input file must be seekable when lazy=True")
  159. self._tableCache = _tableCache
  160. self.reader = SFNTReader(file, checkChecksums, fontNumber=fontNumber)
  161. self.sfntVersion = self.reader.sfntVersion
  162. self.flavor = self.reader.flavor
  163. self.flavorData = self.reader.flavorData
  164. def __enter__(self):
  165. return self
  166. def __exit__(self, type, value, traceback):
  167. self.close()
  168. def close(self):
  169. """If we still have a reader object, close it."""
  170. if self.reader is not None:
  171. self.reader.close()
  172. def save(self, file, reorderTables=True):
  173. """Save the font to disk.
  174. Args:
  175. file: Similarly to the constructor, can be either a pathname or a writable
  176. file object.
  177. reorderTables (Option[bool]): If true (the default), reorder the tables,
  178. sorting them by tag (recommended by the OpenType specification). If
  179. false, retain the original font order. If None, reorder by table
  180. dependency (fastest).
  181. """
  182. if not hasattr(file, "write"):
  183. if self.lazy and self.reader.file.name == file:
  184. raise TTLibError("Can't overwrite TTFont when 'lazy' attribute is True")
  185. createStream = True
  186. else:
  187. # assume "file" is a writable file object
  188. createStream = False
  189. tmp = BytesIO()
  190. writer_reordersTables = self._save(tmp)
  191. if not (
  192. reorderTables is None
  193. or writer_reordersTables
  194. or (reorderTables is False and self.reader is None)
  195. ):
  196. if reorderTables is False:
  197. # sort tables using the original font's order
  198. tableOrder = list(self.reader.keys())
  199. else:
  200. # use the recommended order from the OpenType specification
  201. tableOrder = None
  202. tmp.flush()
  203. tmp2 = BytesIO()
  204. reorderFontTables(tmp, tmp2, tableOrder)
  205. tmp.close()
  206. tmp = tmp2
  207. if createStream:
  208. # "file" is a path
  209. with open(file, "wb") as file:
  210. file.write(tmp.getvalue())
  211. else:
  212. file.write(tmp.getvalue())
  213. tmp.close()
  214. def _save(self, file, tableCache=None):
  215. """Internal function, to be shared by save() and TTCollection.save()"""
  216. if self.recalcTimestamp and "head" in self:
  217. self[
  218. "head"
  219. ] # make sure 'head' is loaded so the recalculation is actually done
  220. tags = list(self.keys())
  221. if "GlyphOrder" in tags:
  222. tags.remove("GlyphOrder")
  223. numTables = len(tags)
  224. # write to a temporary stream to allow saving to unseekable streams
  225. writer = SFNTWriter(
  226. file, numTables, self.sfntVersion, self.flavor, self.flavorData
  227. )
  228. done = []
  229. for tag in tags:
  230. self._writeTable(tag, writer, done, tableCache)
  231. writer.close()
  232. return writer.reordersTables()
  233. def saveXML(self, fileOrPath, newlinestr="\n", **kwargs):
  234. """Export the font as TTX (an XML-based text file), or as a series of text
  235. files when splitTables is true. In the latter case, the 'fileOrPath'
  236. argument should be a path to a directory.
  237. The 'tables' argument must either be false (dump all tables) or a
  238. list of tables to dump. The 'skipTables' argument may be a list of tables
  239. to skip, but only when the 'tables' argument is false.
  240. """
  241. writer = xmlWriter.XMLWriter(fileOrPath, newlinestr=newlinestr)
  242. self._saveXML(writer, **kwargs)
  243. writer.close()
  244. def _saveXML(
  245. self,
  246. writer,
  247. writeVersion=True,
  248. quiet=None,
  249. tables=None,
  250. skipTables=None,
  251. splitTables=False,
  252. splitGlyphs=False,
  253. disassembleInstructions=True,
  254. bitmapGlyphDataFormat="raw",
  255. ):
  256. if quiet is not None:
  257. deprecateArgument("quiet", "configure logging instead")
  258. self.disassembleInstructions = disassembleInstructions
  259. self.bitmapGlyphDataFormat = bitmapGlyphDataFormat
  260. if not tables:
  261. tables = list(self.keys())
  262. if "GlyphOrder" not in tables:
  263. tables = ["GlyphOrder"] + tables
  264. if skipTables:
  265. for tag in skipTables:
  266. if tag in tables:
  267. tables.remove(tag)
  268. numTables = len(tables)
  269. if writeVersion:
  270. from fontTools import version
  271. version = ".".join(version.split(".")[:2])
  272. writer.begintag(
  273. "ttFont",
  274. sfntVersion=repr(tostr(self.sfntVersion))[1:-1],
  275. ttLibVersion=version,
  276. )
  277. else:
  278. writer.begintag("ttFont", sfntVersion=repr(tostr(self.sfntVersion))[1:-1])
  279. writer.newline()
  280. # always splitTables if splitGlyphs is enabled
  281. splitTables = splitTables or splitGlyphs
  282. if not splitTables:
  283. writer.newline()
  284. else:
  285. path, ext = os.path.splitext(writer.filename)
  286. for i in range(numTables):
  287. tag = tables[i]
  288. if splitTables:
  289. tablePath = path + "." + tagToIdentifier(tag) + ext
  290. tableWriter = xmlWriter.XMLWriter(
  291. tablePath, newlinestr=writer.newlinestr
  292. )
  293. tableWriter.begintag("ttFont", ttLibVersion=version)
  294. tableWriter.newline()
  295. tableWriter.newline()
  296. writer.simpletag(tagToXML(tag), src=os.path.basename(tablePath))
  297. writer.newline()
  298. else:
  299. tableWriter = writer
  300. self._tableToXML(tableWriter, tag, splitGlyphs=splitGlyphs)
  301. if splitTables:
  302. tableWriter.endtag("ttFont")
  303. tableWriter.newline()
  304. tableWriter.close()
  305. writer.endtag("ttFont")
  306. writer.newline()
  307. def _tableToXML(self, writer, tag, quiet=None, splitGlyphs=False):
  308. if quiet is not None:
  309. deprecateArgument("quiet", "configure logging instead")
  310. if tag in self:
  311. table = self[tag]
  312. report = "Dumping '%s' table..." % tag
  313. else:
  314. report = "No '%s' table found." % tag
  315. log.info(report)
  316. if tag not in self:
  317. return
  318. xmlTag = tagToXML(tag)
  319. attrs = dict()
  320. if hasattr(table, "ERROR"):
  321. attrs["ERROR"] = "decompilation error"
  322. from .tables.DefaultTable import DefaultTable
  323. if table.__class__ == DefaultTable:
  324. attrs["raw"] = True
  325. writer.begintag(xmlTag, **attrs)
  326. writer.newline()
  327. if tag == "glyf":
  328. table.toXML(writer, self, splitGlyphs=splitGlyphs)
  329. else:
  330. table.toXML(writer, self)
  331. writer.endtag(xmlTag)
  332. writer.newline()
  333. writer.newline()
  334. def importXML(self, fileOrPath, quiet=None):
  335. """Import a TTX file (an XML-based text format), so as to recreate
  336. a font object.
  337. """
  338. if quiet is not None:
  339. deprecateArgument("quiet", "configure logging instead")
  340. if "maxp" in self and "post" in self:
  341. # Make sure the glyph order is loaded, as it otherwise gets
  342. # lost if the XML doesn't contain the glyph order, yet does
  343. # contain the table which was originally used to extract the
  344. # glyph names from (ie. 'post', 'cmap' or 'CFF ').
  345. self.getGlyphOrder()
  346. from fontTools.misc import xmlReader
  347. reader = xmlReader.XMLReader(fileOrPath, self)
  348. reader.read()
  349. def isLoaded(self, tag):
  350. """Return true if the table identified by ``tag`` has been
  351. decompiled and loaded into memory."""
  352. return tag in self.tables
  353. def has_key(self, tag):
  354. """Test if the table identified by ``tag`` is present in the font.
  355. As well as this method, ``tag in font`` can also be used to determine the
  356. presence of the table."""
  357. if self.isLoaded(tag):
  358. return True
  359. elif self.reader and tag in self.reader:
  360. return True
  361. elif tag == "GlyphOrder":
  362. return True
  363. else:
  364. return False
  365. __contains__ = has_key
  366. def keys(self):
  367. """Returns the list of tables in the font, along with the ``GlyphOrder`` pseudo-table."""
  368. keys = list(self.tables.keys())
  369. if self.reader:
  370. for key in list(self.reader.keys()):
  371. if key not in keys:
  372. keys.append(key)
  373. if "GlyphOrder" in keys:
  374. keys.remove("GlyphOrder")
  375. keys = sortedTagList(keys)
  376. return ["GlyphOrder"] + keys
  377. def ensureDecompiled(self, recurse=None):
  378. """Decompile all the tables, even if a TTFont was opened in 'lazy' mode."""
  379. for tag in self.keys():
  380. table = self[tag]
  381. if recurse is None:
  382. recurse = self.lazy is not False
  383. if recurse and hasattr(table, "ensureDecompiled"):
  384. table.ensureDecompiled(recurse=recurse)
  385. self.lazy = False
  386. def __len__(self):
  387. return len(list(self.keys()))
  388. def __getitem__(self, tag):
  389. tag = Tag(tag)
  390. table = self.tables.get(tag)
  391. if table is None:
  392. if tag == "GlyphOrder":
  393. table = GlyphOrder(tag)
  394. self.tables[tag] = table
  395. elif self.reader is not None:
  396. table = self._readTable(tag)
  397. else:
  398. raise KeyError("'%s' table not found" % tag)
  399. return table
  400. def _readTable(self, tag):
  401. log.debug("Reading '%s' table from disk", tag)
  402. data = self.reader[tag]
  403. if self._tableCache is not None:
  404. table = self._tableCache.get((tag, data))
  405. if table is not None:
  406. return table
  407. tableClass = getTableClass(tag)
  408. table = tableClass(tag)
  409. self.tables[tag] = table
  410. log.debug("Decompiling '%s' table", tag)
  411. try:
  412. table.decompile(data, self)
  413. except Exception:
  414. if not self.ignoreDecompileErrors:
  415. raise
  416. # fall back to DefaultTable, retaining the binary table data
  417. log.exception(
  418. "An exception occurred during the decompilation of the '%s' table", tag
  419. )
  420. from .tables.DefaultTable import DefaultTable
  421. file = StringIO()
  422. traceback.print_exc(file=file)
  423. table = DefaultTable(tag)
  424. table.ERROR = file.getvalue()
  425. self.tables[tag] = table
  426. table.decompile(data, self)
  427. if self._tableCache is not None:
  428. self._tableCache[(tag, data)] = table
  429. return table
  430. def __setitem__(self, tag, table):
  431. self.tables[Tag(tag)] = table
  432. def __delitem__(self, tag):
  433. if tag not in self:
  434. raise KeyError("'%s' table not found" % tag)
  435. if tag in self.tables:
  436. del self.tables[tag]
  437. if self.reader and tag in self.reader:
  438. del self.reader[tag]
  439. def get(self, tag, default=None):
  440. """Returns the table if it exists or (optionally) a default if it doesn't."""
  441. try:
  442. return self[tag]
  443. except KeyError:
  444. return default
  445. def setGlyphOrder(self, glyphOrder):
  446. """Set the glyph order
  447. Args:
  448. glyphOrder ([str]): List of glyph names in order.
  449. """
  450. self.glyphOrder = glyphOrder
  451. if hasattr(self, "_reverseGlyphOrderDict"):
  452. del self._reverseGlyphOrderDict
  453. if self.isLoaded("glyf"):
  454. self["glyf"].setGlyphOrder(glyphOrder)
  455. def getGlyphOrder(self):
  456. """Returns a list of glyph names ordered by their position in the font."""
  457. try:
  458. return self.glyphOrder
  459. except AttributeError:
  460. pass
  461. if "CFF " in self:
  462. cff = self["CFF "]
  463. self.glyphOrder = cff.getGlyphOrder()
  464. elif "post" in self:
  465. # TrueType font
  466. glyphOrder = self["post"].getGlyphOrder()
  467. if glyphOrder is None:
  468. #
  469. # No names found in the 'post' table.
  470. # Try to create glyph names from the unicode cmap (if available)
  471. # in combination with the Adobe Glyph List (AGL).
  472. #
  473. self._getGlyphNamesFromCmap()
  474. elif len(glyphOrder) < self["maxp"].numGlyphs:
  475. #
  476. # Not enough names found in the 'post' table.
  477. # Can happen when 'post' format 1 is improperly used on a font that
  478. # has more than 258 glyphs (the length of 'standardGlyphOrder').
  479. #
  480. log.warning(
  481. "Not enough names found in the 'post' table, generating them from cmap instead"
  482. )
  483. self._getGlyphNamesFromCmap()
  484. else:
  485. self.glyphOrder = glyphOrder
  486. else:
  487. self._getGlyphNamesFromCmap()
  488. return self.glyphOrder
  489. def _getGlyphNamesFromCmap(self):
  490. #
  491. # This is rather convoluted, but then again, it's an interesting problem:
  492. # - we need to use the unicode values found in the cmap table to
  493. # build glyph names (eg. because there is only a minimal post table,
  494. # or none at all).
  495. # - but the cmap parser also needs glyph names to work with...
  496. # So here's what we do:
  497. # - make up glyph names based on glyphID
  498. # - load a temporary cmap table based on those names
  499. # - extract the unicode values, build the "real" glyph names
  500. # - unload the temporary cmap table
  501. #
  502. if self.isLoaded("cmap"):
  503. # Bootstrapping: we're getting called by the cmap parser
  504. # itself. This means self.tables['cmap'] contains a partially
  505. # loaded cmap, making it impossible to get at a unicode
  506. # subtable here. We remove the partially loaded cmap and
  507. # restore it later.
  508. # This only happens if the cmap table is loaded before any
  509. # other table that does f.getGlyphOrder() or f.getGlyphName().
  510. cmapLoading = self.tables["cmap"]
  511. del self.tables["cmap"]
  512. else:
  513. cmapLoading = None
  514. # Make up glyph names based on glyphID, which will be used by the
  515. # temporary cmap and by the real cmap in case we don't find a unicode
  516. # cmap.
  517. numGlyphs = int(self["maxp"].numGlyphs)
  518. glyphOrder = [None] * numGlyphs
  519. glyphOrder[0] = ".notdef"
  520. for i in range(1, numGlyphs):
  521. glyphOrder[i] = "glyph%.5d" % i
  522. # Set the glyph order, so the cmap parser has something
  523. # to work with (so we don't get called recursively).
  524. self.glyphOrder = glyphOrder
  525. # Make up glyph names based on the reversed cmap table. Because some
  526. # glyphs (eg. ligatures or alternates) may not be reachable via cmap,
  527. # this naming table will usually not cover all glyphs in the font.
  528. # If the font has no Unicode cmap table, reversecmap will be empty.
  529. if "cmap" in self:
  530. reversecmap = self["cmap"].buildReversed()
  531. else:
  532. reversecmap = {}
  533. useCount = {}
  534. for i in range(numGlyphs):
  535. tempName = glyphOrder[i]
  536. if tempName in reversecmap:
  537. # If a font maps both U+0041 LATIN CAPITAL LETTER A and
  538. # U+0391 GREEK CAPITAL LETTER ALPHA to the same glyph,
  539. # we prefer naming the glyph as "A".
  540. glyphName = self._makeGlyphName(min(reversecmap[tempName]))
  541. numUses = useCount[glyphName] = useCount.get(glyphName, 0) + 1
  542. if numUses > 1:
  543. glyphName = "%s.alt%d" % (glyphName, numUses - 1)
  544. glyphOrder[i] = glyphName
  545. if "cmap" in self:
  546. # Delete the temporary cmap table from the cache, so it can
  547. # be parsed again with the right names.
  548. del self.tables["cmap"]
  549. self.glyphOrder = glyphOrder
  550. if cmapLoading:
  551. # restore partially loaded cmap, so it can continue loading
  552. # using the proper names.
  553. self.tables["cmap"] = cmapLoading
  554. @staticmethod
  555. def _makeGlyphName(codepoint):
  556. from fontTools import agl # Adobe Glyph List
  557. if codepoint in agl.UV2AGL:
  558. return agl.UV2AGL[codepoint]
  559. elif codepoint <= 0xFFFF:
  560. return "uni%04X" % codepoint
  561. else:
  562. return "u%X" % codepoint
  563. def getGlyphNames(self):
  564. """Get a list of glyph names, sorted alphabetically."""
  565. glyphNames = sorted(self.getGlyphOrder())
  566. return glyphNames
  567. def getGlyphNames2(self):
  568. """Get a list of glyph names, sorted alphabetically,
  569. but not case sensitive.
  570. """
  571. from fontTools.misc import textTools
  572. return textTools.caselessSort(self.getGlyphOrder())
  573. def getGlyphName(self, glyphID):
  574. """Returns the name for the glyph with the given ID.
  575. If no name is available, synthesises one with the form ``glyphXXXXX``` where
  576. ```XXXXX`` is the zero-padded glyph ID.
  577. """
  578. try:
  579. return self.getGlyphOrder()[glyphID]
  580. except IndexError:
  581. return "glyph%.5d" % glyphID
  582. def getGlyphNameMany(self, lst):
  583. """Converts a list of glyph IDs into a list of glyph names."""
  584. glyphOrder = self.getGlyphOrder()
  585. cnt = len(glyphOrder)
  586. return [glyphOrder[gid] if gid < cnt else "glyph%.5d" % gid for gid in lst]
  587. def getGlyphID(self, glyphName):
  588. """Returns the ID of the glyph with the given name."""
  589. try:
  590. return self.getReverseGlyphMap()[glyphName]
  591. except KeyError:
  592. if glyphName[:5] == "glyph":
  593. try:
  594. return int(glyphName[5:])
  595. except (NameError, ValueError):
  596. raise KeyError(glyphName)
  597. raise
  598. def getGlyphIDMany(self, lst):
  599. """Converts a list of glyph names into a list of glyph IDs."""
  600. d = self.getReverseGlyphMap()
  601. try:
  602. return [d[glyphName] for glyphName in lst]
  603. except KeyError:
  604. getGlyphID = self.getGlyphID
  605. return [getGlyphID(glyphName) for glyphName in lst]
  606. def getReverseGlyphMap(self, rebuild=False):
  607. """Returns a mapping of glyph names to glyph IDs."""
  608. if rebuild or not hasattr(self, "_reverseGlyphOrderDict"):
  609. self._buildReverseGlyphOrderDict()
  610. return self._reverseGlyphOrderDict
  611. def _buildReverseGlyphOrderDict(self):
  612. self._reverseGlyphOrderDict = d = {}
  613. for glyphID, glyphName in enumerate(self.getGlyphOrder()):
  614. d[glyphName] = glyphID
  615. return d
  616. def _writeTable(self, tag, writer, done, tableCache=None):
  617. """Internal helper function for self.save(). Keeps track of
  618. inter-table dependencies.
  619. """
  620. if tag in done:
  621. return
  622. tableClass = getTableClass(tag)
  623. for masterTable in tableClass.dependencies:
  624. if masterTable not in done:
  625. if masterTable in self:
  626. self._writeTable(masterTable, writer, done, tableCache)
  627. else:
  628. done.append(masterTable)
  629. done.append(tag)
  630. tabledata = self.getTableData(tag)
  631. if tableCache is not None:
  632. entry = tableCache.get((Tag(tag), tabledata))
  633. if entry is not None:
  634. log.debug("reusing '%s' table", tag)
  635. writer.setEntry(tag, entry)
  636. return
  637. log.debug("Writing '%s' table to disk", tag)
  638. writer[tag] = tabledata
  639. if tableCache is not None:
  640. tableCache[(Tag(tag), tabledata)] = writer[tag]
  641. def getTableData(self, tag):
  642. """Returns the binary representation of a table.
  643. If the table is currently loaded and in memory, the data is compiled to
  644. binary and returned; if it is not currently loaded, the binary data is
  645. read from the font file and returned.
  646. """
  647. tag = Tag(tag)
  648. if self.isLoaded(tag):
  649. log.debug("Compiling '%s' table", tag)
  650. return self.tables[tag].compile(self)
  651. elif self.reader and tag in self.reader:
  652. log.debug("Reading '%s' table from disk", tag)
  653. return self.reader[tag]
  654. else:
  655. raise KeyError(tag)
  656. def getGlyphSet(
  657. self, preferCFF=True, location=None, normalized=False, recalcBounds=True
  658. ):
  659. """Return a generic GlyphSet, which is a dict-like object
  660. mapping glyph names to glyph objects. The returned glyph objects
  661. have a ``.draw()`` method that supports the Pen protocol, and will
  662. have an attribute named 'width'.
  663. If the font is CFF-based, the outlines will be taken from the ``CFF ``
  664. or ``CFF2`` tables. Otherwise the outlines will be taken from the
  665. ``glyf`` table.
  666. If the font contains both a ``CFF ``/``CFF2`` and a ``glyf`` table, you
  667. can use the ``preferCFF`` argument to specify which one should be taken.
  668. If the font contains both a ``CFF `` and a ``CFF2`` table, the latter is
  669. taken.
  670. If the ``location`` parameter is set, it should be a dictionary mapping
  671. four-letter variation tags to their float values, and the returned
  672. glyph-set will represent an instance of a variable font at that
  673. location.
  674. If the ``normalized`` variable is set to True, that location is
  675. interpreted as in the normalized (-1..+1) space, otherwise it is in the
  676. font's defined axes space.
  677. """
  678. if location and "fvar" not in self:
  679. location = None
  680. if location and not normalized:
  681. location = self.normalizeLocation(location)
  682. glyphSet = None
  683. if ("CFF " in self or "CFF2" in self) and (preferCFF or "glyf" not in self):
  684. glyphSet = _TTGlyphSetCFF(self, location)
  685. elif "glyf" in self:
  686. glyphSet = _TTGlyphSetGlyf(self, location, recalcBounds=recalcBounds)
  687. else:
  688. raise TTLibError("Font contains no outlines")
  689. if "VARC" in self:
  690. glyphSet = _TTGlyphSetVARC(self, location, glyphSet)
  691. return glyphSet
  692. def normalizeLocation(self, location):
  693. """Normalize a ``location`` from the font's defined axes space (also
  694. known as user space) into the normalized (-1..+1) space. It applies
  695. ``avar`` mapping if the font contains an ``avar`` table.
  696. The ``location`` parameter should be a dictionary mapping four-letter
  697. variation tags to their float values.
  698. Raises ``TTLibError`` if the font is not a variable font.
  699. """
  700. from fontTools.varLib.models import normalizeLocation
  701. if "fvar" not in self:
  702. raise TTLibError("Not a variable font")
  703. axes = self["fvar"].getAxes()
  704. location = normalizeLocation(location, axes)
  705. if "avar" in self:
  706. location = self["avar"].renormalizeLocation(location, self)
  707. return location
  708. def getBestCmap(
  709. self,
  710. cmapPreferences=(
  711. (3, 10),
  712. (0, 6),
  713. (0, 4),
  714. (3, 1),
  715. (0, 3),
  716. (0, 2),
  717. (0, 1),
  718. (0, 0),
  719. ),
  720. ):
  721. """Returns the 'best' Unicode cmap dictionary available in the font
  722. or ``None``, if no Unicode cmap subtable is available.
  723. By default it will search for the following (platformID, platEncID)
  724. pairs in order::
  725. (3, 10), # Windows Unicode full repertoire
  726. (0, 6), # Unicode full repertoire (format 13 subtable)
  727. (0, 4), # Unicode 2.0 full repertoire
  728. (3, 1), # Windows Unicode BMP
  729. (0, 3), # Unicode 2.0 BMP
  730. (0, 2), # Unicode ISO/IEC 10646
  731. (0, 1), # Unicode 1.1
  732. (0, 0) # Unicode 1.0
  733. This particular order matches what HarfBuzz uses to choose what
  734. subtable to use by default. This order prefers the largest-repertoire
  735. subtable, and among those, prefers the Windows-platform over the
  736. Unicode-platform as the former has wider support.
  737. This order can be customized via the ``cmapPreferences`` argument.
  738. """
  739. return self["cmap"].getBestCmap(cmapPreferences=cmapPreferences)
  740. def reorderGlyphs(self, new_glyph_order):
  741. from .reorderGlyphs import reorderGlyphs
  742. reorderGlyphs(self, new_glyph_order)
  743. class GlyphOrder(object):
  744. """A pseudo table. The glyph order isn't in the font as a separate
  745. table, but it's nice to present it as such in the TTX format.
  746. """
  747. def __init__(self, tag=None):
  748. pass
  749. def toXML(self, writer, ttFont):
  750. glyphOrder = ttFont.getGlyphOrder()
  751. writer.comment(
  752. "The 'id' attribute is only for humans; " "it is ignored when parsed."
  753. )
  754. writer.newline()
  755. for i in range(len(glyphOrder)):
  756. glyphName = glyphOrder[i]
  757. writer.simpletag("GlyphID", id=i, name=glyphName)
  758. writer.newline()
  759. def fromXML(self, name, attrs, content, ttFont):
  760. if not hasattr(self, "glyphOrder"):
  761. self.glyphOrder = []
  762. if name == "GlyphID":
  763. self.glyphOrder.append(attrs["name"])
  764. ttFont.setGlyphOrder(self.glyphOrder)
  765. def getTableModule(tag):
  766. """Fetch the packer/unpacker module for a table.
  767. Return None when no module is found.
  768. """
  769. from . import tables
  770. pyTag = tagToIdentifier(tag)
  771. try:
  772. __import__("fontTools.ttLib.tables." + pyTag)
  773. except ImportError as err:
  774. # If pyTag is found in the ImportError message,
  775. # means table is not implemented. If it's not
  776. # there, then some other module is missing, don't
  777. # suppress the error.
  778. if str(err).find(pyTag) >= 0:
  779. return None
  780. else:
  781. raise err
  782. else:
  783. return getattr(tables, pyTag)
  784. # Registry for custom table packer/unpacker classes. Keys are table
  785. # tags, values are (moduleName, className) tuples.
  786. # See registerCustomTableClass() and getCustomTableClass()
  787. _customTableRegistry = {}
  788. def registerCustomTableClass(tag, moduleName, className=None):
  789. """Register a custom packer/unpacker class for a table.
  790. The 'moduleName' must be an importable module. If no 'className'
  791. is given, it is derived from the tag, for example it will be
  792. ``table_C_U_S_T_`` for a 'CUST' tag.
  793. The registered table class should be a subclass of
  794. :py:class:`fontTools.ttLib.tables.DefaultTable.DefaultTable`
  795. """
  796. if className is None:
  797. className = "table_" + tagToIdentifier(tag)
  798. _customTableRegistry[tag] = (moduleName, className)
  799. def unregisterCustomTableClass(tag):
  800. """Unregister the custom packer/unpacker class for a table."""
  801. del _customTableRegistry[tag]
  802. def getCustomTableClass(tag):
  803. """Return the custom table class for tag, if one has been registered
  804. with 'registerCustomTableClass()'. Else return None.
  805. """
  806. if tag not in _customTableRegistry:
  807. return None
  808. import importlib
  809. moduleName, className = _customTableRegistry[tag]
  810. module = importlib.import_module(moduleName)
  811. return getattr(module, className)
  812. def getTableClass(tag):
  813. """Fetch the packer/unpacker class for a table."""
  814. tableClass = getCustomTableClass(tag)
  815. if tableClass is not None:
  816. return tableClass
  817. module = getTableModule(tag)
  818. if module is None:
  819. from .tables.DefaultTable import DefaultTable
  820. return DefaultTable
  821. pyTag = tagToIdentifier(tag)
  822. tableClass = getattr(module, "table_" + pyTag)
  823. return tableClass
  824. def getClassTag(klass):
  825. """Fetch the table tag for a class object."""
  826. name = klass.__name__
  827. assert name[:6] == "table_"
  828. name = name[6:] # Chop 'table_'
  829. return identifierToTag(name)
  830. def newTable(tag):
  831. """Return a new instance of a table."""
  832. tableClass = getTableClass(tag)
  833. return tableClass(tag)
  834. def _escapechar(c):
  835. """Helper function for tagToIdentifier()"""
  836. import re
  837. if re.match("[a-z0-9]", c):
  838. return "_" + c
  839. elif re.match("[A-Z]", c):
  840. return c + "_"
  841. else:
  842. return hex(byteord(c))[2:]
  843. def tagToIdentifier(tag):
  844. """Convert a table tag to a valid (but UGLY) python identifier,
  845. as well as a filename that's guaranteed to be unique even on a
  846. caseless file system. Each character is mapped to two characters.
  847. Lowercase letters get an underscore before the letter, uppercase
  848. letters get an underscore after the letter. Trailing spaces are
  849. trimmed. Illegal characters are escaped as two hex bytes. If the
  850. result starts with a number (as the result of a hex escape), an
  851. extra underscore is prepended. Examples::
  852. >>> tagToIdentifier('glyf')
  853. '_g_l_y_f'
  854. >>> tagToIdentifier('cvt ')
  855. '_c_v_t'
  856. >>> tagToIdentifier('OS/2')
  857. 'O_S_2f_2'
  858. """
  859. import re
  860. tag = Tag(tag)
  861. if tag == "GlyphOrder":
  862. return tag
  863. assert len(tag) == 4, "tag should be 4 characters long"
  864. while len(tag) > 1 and tag[-1] == " ":
  865. tag = tag[:-1]
  866. ident = ""
  867. for c in tag:
  868. ident = ident + _escapechar(c)
  869. if re.match("[0-9]", ident):
  870. ident = "_" + ident
  871. return ident
  872. def identifierToTag(ident):
  873. """the opposite of tagToIdentifier()"""
  874. if ident == "GlyphOrder":
  875. return ident
  876. if len(ident) % 2 and ident[0] == "_":
  877. ident = ident[1:]
  878. assert not (len(ident) % 2)
  879. tag = ""
  880. for i in range(0, len(ident), 2):
  881. if ident[i] == "_":
  882. tag = tag + ident[i + 1]
  883. elif ident[i + 1] == "_":
  884. tag = tag + ident[i]
  885. else:
  886. # assume hex
  887. tag = tag + chr(int(ident[i : i + 2], 16))
  888. # append trailing spaces
  889. tag = tag + (4 - len(tag)) * " "
  890. return Tag(tag)
  891. def tagToXML(tag):
  892. """Similarly to tagToIdentifier(), this converts a TT tag
  893. to a valid XML element name. Since XML element names are
  894. case sensitive, this is a fairly simple/readable translation.
  895. """
  896. import re
  897. tag = Tag(tag)
  898. if tag == "OS/2":
  899. return "OS_2"
  900. elif tag == "GlyphOrder":
  901. return tag
  902. if re.match("[A-Za-z_][A-Za-z_0-9]* *$", tag):
  903. return tag.strip()
  904. else:
  905. return tagToIdentifier(tag)
  906. def xmlToTag(tag):
  907. """The opposite of tagToXML()"""
  908. if tag == "OS_2":
  909. return Tag("OS/2")
  910. if len(tag) == 8:
  911. return identifierToTag(tag)
  912. else:
  913. return Tag(tag + " " * (4 - len(tag)))
  914. # Table order as recommended in the OpenType specification 1.4
  915. TTFTableOrder = [
  916. "head",
  917. "hhea",
  918. "maxp",
  919. "OS/2",
  920. "hmtx",
  921. "LTSH",
  922. "VDMX",
  923. "hdmx",
  924. "cmap",
  925. "fpgm",
  926. "prep",
  927. "cvt ",
  928. "loca",
  929. "glyf",
  930. "kern",
  931. "name",
  932. "post",
  933. "gasp",
  934. "PCLT",
  935. ]
  936. OTFTableOrder = ["head", "hhea", "maxp", "OS/2", "name", "cmap", "post", "CFF "]
  937. def sortedTagList(tagList, tableOrder=None):
  938. """Return a sorted copy of tagList, sorted according to the OpenType
  939. specification, or according to a custom tableOrder. If given and not
  940. None, tableOrder needs to be a list of tag names.
  941. """
  942. tagList = sorted(tagList)
  943. if tableOrder is None:
  944. if "DSIG" in tagList:
  945. # DSIG should be last (XXX spec reference?)
  946. tagList.remove("DSIG")
  947. tagList.append("DSIG")
  948. if "CFF " in tagList:
  949. tableOrder = OTFTableOrder
  950. else:
  951. tableOrder = TTFTableOrder
  952. orderedTables = []
  953. for tag in tableOrder:
  954. if tag in tagList:
  955. orderedTables.append(tag)
  956. tagList.remove(tag)
  957. orderedTables.extend(tagList)
  958. return orderedTables
  959. def reorderFontTables(inFile, outFile, tableOrder=None, checkChecksums=False):
  960. """Rewrite a font file, ordering the tables as recommended by the
  961. OpenType specification 1.4.
  962. """
  963. inFile.seek(0)
  964. outFile.seek(0)
  965. reader = SFNTReader(inFile, checkChecksums=checkChecksums)
  966. writer = SFNTWriter(
  967. outFile,
  968. len(reader.tables),
  969. reader.sfntVersion,
  970. reader.flavor,
  971. reader.flavorData,
  972. )
  973. tables = list(reader.keys())
  974. for tag in sortedTagList(tables, tableOrder):
  975. writer[tag] = reader[tag]
  976. writer.close()
  977. def maxPowerOfTwo(x):
  978. """Return the highest exponent of two, so that
  979. (2 ** exponent) <= x. Return 0 if x is 0.
  980. """
  981. exponent = 0
  982. while x:
  983. x = x >> 1
  984. exponent = exponent + 1
  985. return max(exponent - 1, 0)
  986. def getSearchRange(n, itemSize=16):
  987. """Calculate searchRange, entrySelector, rangeShift."""
  988. # itemSize defaults to 16, for backward compatibility
  989. # with upstream fonttools.
  990. exponent = maxPowerOfTwo(n)
  991. searchRange = (2**exponent) * itemSize
  992. entrySelector = exponent
  993. rangeShift = max(0, n * itemSize - searchRange)
  994. return searchRange, entrySelector, rangeShift