ttFont.py 40 KB

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