CFFToCFF2.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. """CFF to CFF2 converter."""
  2. from fontTools.ttLib import TTFont, newTable
  3. from fontTools.misc.cliTools import makeOutputFileName
  4. from fontTools.misc.psCharStrings import T2WidthExtractor
  5. from fontTools.cffLib import (
  6. TopDictIndex,
  7. FDArrayIndex,
  8. FontDict,
  9. buildOrder,
  10. topDictOperators,
  11. privateDictOperators,
  12. topDictOperators2,
  13. privateDictOperators2,
  14. )
  15. from io import BytesIO
  16. import logging
  17. __all__ = ["convertCFFToCFF2", "main"]
  18. log = logging.getLogger("fontTools.cffLib")
  19. class _NominalWidthUsedError(Exception):
  20. def __add__(self, other):
  21. raise self
  22. def __radd__(self, other):
  23. raise self
  24. def _convertCFFToCFF2(cff, otFont):
  25. """Converts this object from CFF format to CFF2 format. This conversion
  26. is done 'in-place'. The conversion cannot be reversed.
  27. This assumes a decompiled CFF table. (i.e. that the object has been
  28. filled via :meth:`decompile` and e.g. not loaded from XML.)"""
  29. # Clean up T2CharStrings
  30. topDict = cff.topDictIndex[0]
  31. fdArray = topDict.FDArray if hasattr(topDict, "FDArray") else None
  32. charStrings = topDict.CharStrings
  33. globalSubrs = cff.GlobalSubrs
  34. localSubrs = (
  35. [getattr(fd.Private, "Subrs", []) for fd in fdArray]
  36. if fdArray
  37. else (
  38. [topDict.Private.Subrs]
  39. if hasattr(topDict, "Private") and hasattr(topDict.Private, "Subrs")
  40. else []
  41. )
  42. )
  43. for glyphName in charStrings.keys():
  44. cs, fdIndex = charStrings.getItemAndSelector(glyphName)
  45. cs.decompile()
  46. # Clean up subroutines first
  47. for subrs in [globalSubrs] + localSubrs:
  48. for subr in subrs:
  49. program = subr.program
  50. i = j = len(program)
  51. try:
  52. i = program.index("return")
  53. except ValueError:
  54. pass
  55. try:
  56. j = program.index("endchar")
  57. except ValueError:
  58. pass
  59. program[min(i, j) :] = []
  60. # Clean up glyph charstrings
  61. removeUnusedSubrs = False
  62. nominalWidthXError = _NominalWidthUsedError()
  63. for glyphName in charStrings.keys():
  64. cs, fdIndex = charStrings.getItemAndSelector(glyphName)
  65. program = cs.program
  66. thisLocalSubrs = (
  67. localSubrs[fdIndex]
  68. if fdIndex
  69. else (
  70. getattr(topDict.Private, "Subrs", [])
  71. if hasattr(topDict, "Private")
  72. else []
  73. )
  74. )
  75. # Intentionally use custom type for nominalWidthX, such that any
  76. # CharString that has an explicit width encoded will throw back to us.
  77. extractor = T2WidthExtractor(
  78. thisLocalSubrs,
  79. globalSubrs,
  80. nominalWidthXError,
  81. 0,
  82. )
  83. try:
  84. extractor.execute(cs)
  85. except _NominalWidthUsedError:
  86. # Program has explicit width. We want to drop it, but can't
  87. # just pop the first number since it may be a subroutine call.
  88. # Instead, when seeing that, we embed the subroutine and recurse.
  89. # If this ever happened, we later prune unused subroutines.
  90. while program[1] in ["callsubr", "callgsubr"]:
  91. removeUnusedSubrs = True
  92. subrNumber = program.pop(0)
  93. op = program.pop(0)
  94. bias = extractor.localBias if op == "callsubr" else extractor.globalBias
  95. subrNumber += bias
  96. subrSet = thisLocalSubrs if op == "callsubr" else globalSubrs
  97. subrProgram = subrSet[subrNumber].program
  98. program[:0] = subrProgram
  99. # Now pop the actual width
  100. program.pop(0)
  101. if program and program[-1] == "endchar":
  102. program.pop()
  103. if removeUnusedSubrs:
  104. cff.remove_unused_subroutines()
  105. # Upconvert TopDict
  106. cff.major = 2
  107. cff2GetGlyphOrder = cff.otFont.getGlyphOrder
  108. topDictData = TopDictIndex(None, cff2GetGlyphOrder)
  109. for item in cff.topDictIndex:
  110. # Iterate over, such that all are decompiled
  111. topDictData.append(item)
  112. cff.topDictIndex = topDictData
  113. topDict = topDictData[0]
  114. if hasattr(topDict, "Private"):
  115. privateDict = topDict.Private
  116. else:
  117. privateDict = None
  118. opOrder = buildOrder(topDictOperators2)
  119. topDict.order = opOrder
  120. topDict.cff2GetGlyphOrder = cff2GetGlyphOrder
  121. if not hasattr(topDict, "FDArray"):
  122. fdArray = topDict.FDArray = FDArrayIndex()
  123. fdArray.strings = None
  124. fdArray.GlobalSubrs = topDict.GlobalSubrs
  125. topDict.GlobalSubrs.fdArray = fdArray
  126. charStrings = topDict.CharStrings
  127. if charStrings.charStringsAreIndexed:
  128. charStrings.charStringsIndex.fdArray = fdArray
  129. else:
  130. charStrings.fdArray = fdArray
  131. fontDict = FontDict()
  132. fontDict.setCFF2(True)
  133. fdArray.append(fontDict)
  134. fontDict.Private = privateDict
  135. privateOpOrder = buildOrder(privateDictOperators2)
  136. if privateDict is not None:
  137. for entry in privateDictOperators:
  138. key = entry[1]
  139. if key not in privateOpOrder:
  140. if key in privateDict.rawDict:
  141. # print "Removing private dict", key
  142. del privateDict.rawDict[key]
  143. if hasattr(privateDict, key):
  144. delattr(privateDict, key)
  145. # print "Removing privateDict attr", key
  146. else:
  147. # clean up the PrivateDicts in the fdArray
  148. fdArray = topDict.FDArray
  149. privateOpOrder = buildOrder(privateDictOperators2)
  150. for fontDict in fdArray:
  151. fontDict.setCFF2(True)
  152. for key in list(fontDict.rawDict.keys()):
  153. if key not in fontDict.order:
  154. del fontDict.rawDict[key]
  155. if hasattr(fontDict, key):
  156. delattr(fontDict, key)
  157. privateDict = fontDict.Private
  158. for entry in privateDictOperators:
  159. key = entry[1]
  160. if key not in privateOpOrder:
  161. if key in list(privateDict.rawDict.keys()):
  162. # print "Removing private dict", key
  163. del privateDict.rawDict[key]
  164. if hasattr(privateDict, key):
  165. delattr(privateDict, key)
  166. # print "Removing privateDict attr", key
  167. # Now delete up the deprecated topDict operators from CFF 1.0
  168. for entry in topDictOperators:
  169. key = entry[1]
  170. # We seem to need to keep the charset operator for now,
  171. # or we fail to compile with some fonts, like AdditionFont.otf.
  172. # I don't know which kind of CFF font those are. But keeping
  173. # charset seems to work. It will be removed when we save and
  174. # read the font again.
  175. #
  176. # AdditionFont.otf has <Encoding name="StandardEncoding"/>.
  177. if key == "charset":
  178. continue
  179. if key not in opOrder:
  180. if key in topDict.rawDict:
  181. del topDict.rawDict[key]
  182. if hasattr(topDict, key):
  183. delattr(topDict, key)
  184. # TODO(behdad): What does the following comment even mean? Both CFF and CFF2
  185. # use the same T2Charstring class. I *think* what it means is that the CharStrings
  186. # were loaded for CFF1, and we need to reload them for CFF2 to set varstore, etc
  187. # on them. At least that's what I understand. It's probably safe to remove this
  188. # and just set vstore where needed.
  189. #
  190. # See comment above about charset as well.
  191. # At this point, the Subrs and Charstrings are all still T2Charstring class
  192. # easiest to fix this by compiling, then decompiling again
  193. file = BytesIO()
  194. cff.compile(file, otFont, isCFF2=True)
  195. file.seek(0)
  196. cff.decompile(file, otFont, isCFF2=True)
  197. def convertCFFToCFF2(font):
  198. cff = font["CFF "].cff
  199. del font["CFF "]
  200. _convertCFFToCFF2(cff, font)
  201. table = font["CFF2"] = newTable("CFF2")
  202. table.cff = cff
  203. def main(args=None):
  204. """Convert CFF OTF font to CFF2 OTF font"""
  205. if args is None:
  206. import sys
  207. args = sys.argv[1:]
  208. import argparse
  209. parser = argparse.ArgumentParser(
  210. "fonttools cffLib.CFFToCFF2",
  211. description="Upgrade a CFF font to CFF2.",
  212. )
  213. parser.add_argument(
  214. "input", metavar="INPUT.ttf", help="Input OTF file with CFF table."
  215. )
  216. parser.add_argument(
  217. "-o",
  218. "--output",
  219. metavar="OUTPUT.ttf",
  220. default=None,
  221. help="Output instance OTF file (default: INPUT-CFF2.ttf).",
  222. )
  223. parser.add_argument(
  224. "--no-recalc-timestamp",
  225. dest="recalc_timestamp",
  226. action="store_false",
  227. help="Don't set the output font's timestamp to the current time.",
  228. )
  229. loggingGroup = parser.add_mutually_exclusive_group(required=False)
  230. loggingGroup.add_argument(
  231. "-v", "--verbose", action="store_true", help="Run more verbosely."
  232. )
  233. loggingGroup.add_argument(
  234. "-q", "--quiet", action="store_true", help="Turn verbosity off."
  235. )
  236. options = parser.parse_args(args)
  237. from fontTools import configLogger
  238. configLogger(
  239. level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
  240. )
  241. import os
  242. infile = options.input
  243. if not os.path.isfile(infile):
  244. parser.error("No such file '{}'".format(infile))
  245. outfile = (
  246. makeOutputFileName(infile, overWrite=True, suffix="-CFF2")
  247. if not options.output
  248. else options.output
  249. )
  250. font = TTFont(infile, recalcTimestamp=options.recalc_timestamp, recalcBBoxes=False)
  251. convertCFFToCFF2(font)
  252. log.info(
  253. "Saving %s",
  254. outfile,
  255. )
  256. font.save(outfile)
  257. if __name__ == "__main__":
  258. import sys
  259. sys.exit(main(sys.argv[1:]))