ttFont.py 40 KB

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