removeOverlaps.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. """ Simplify TrueType glyphs by merging overlapping contours/components.
  2. Requires https://github.com/fonttools/skia-pathops
  3. """
  4. import itertools
  5. import logging
  6. from typing import Callable, Iterable, Optional, Mapping
  7. from fontTools.cffLib import CFFFontSet
  8. from fontTools.ttLib import ttFont
  9. from fontTools.ttLib.tables import _g_l_y_f
  10. from fontTools.ttLib.tables import _h_m_t_x
  11. from fontTools.misc.psCharStrings import T2CharString
  12. from fontTools.misc.roundTools import otRound, noRound
  13. from fontTools.pens.ttGlyphPen import TTGlyphPen
  14. from fontTools.pens.t2CharStringPen import T2CharStringPen
  15. import pathops
  16. __all__ = ["removeOverlaps"]
  17. class RemoveOverlapsError(Exception):
  18. pass
  19. log = logging.getLogger("fontTools.ttLib.removeOverlaps")
  20. _TTGlyphMapping = Mapping[str, ttFont._TTGlyph]
  21. def skPathFromGlyph(glyphName: str, glyphSet: _TTGlyphMapping) -> pathops.Path:
  22. path = pathops.Path()
  23. pathPen = path.getPen(glyphSet=glyphSet)
  24. glyphSet[glyphName].draw(pathPen)
  25. return path
  26. def skPathFromGlyphComponent(
  27. component: _g_l_y_f.GlyphComponent, glyphSet: _TTGlyphMapping
  28. ):
  29. baseGlyphName, transformation = component.getComponentInfo()
  30. path = skPathFromGlyph(baseGlyphName, glyphSet)
  31. return path.transform(*transformation)
  32. def componentsOverlap(glyph: _g_l_y_f.Glyph, glyphSet: _TTGlyphMapping) -> bool:
  33. if not glyph.isComposite():
  34. raise ValueError("This method only works with TrueType composite glyphs")
  35. if len(glyph.components) < 2:
  36. return False # single component, no overlaps
  37. component_paths = {}
  38. def _get_nth_component_path(index: int) -> pathops.Path:
  39. if index not in component_paths:
  40. component_paths[index] = skPathFromGlyphComponent(
  41. glyph.components[index], glyphSet
  42. )
  43. return component_paths[index]
  44. return any(
  45. pathops.op(
  46. _get_nth_component_path(i),
  47. _get_nth_component_path(j),
  48. pathops.PathOp.INTERSECTION,
  49. fix_winding=False,
  50. keep_starting_points=False,
  51. )
  52. for i, j in itertools.combinations(range(len(glyph.components)), 2)
  53. )
  54. def ttfGlyphFromSkPath(path: pathops.Path) -> _g_l_y_f.Glyph:
  55. # Skia paths have no 'components', no need for glyphSet
  56. ttPen = TTGlyphPen(glyphSet=None)
  57. path.draw(ttPen)
  58. glyph = ttPen.glyph()
  59. assert not glyph.isComposite()
  60. # compute glyph.xMin (glyfTable parameter unused for non composites)
  61. glyph.recalcBounds(glyfTable=None)
  62. return glyph
  63. def _charString_from_SkPath(
  64. path: pathops.Path, charString: T2CharString
  65. ) -> T2CharString:
  66. if charString.width == charString.private.defaultWidthX:
  67. width = None
  68. else:
  69. width = charString.width - charString.private.nominalWidthX
  70. t2Pen = T2CharStringPen(width=width, glyphSet=None)
  71. path.draw(t2Pen)
  72. return t2Pen.getCharString(charString.private, charString.globalSubrs)
  73. def _round_path(
  74. path: pathops.Path, round: Callable[[float], float] = otRound
  75. ) -> pathops.Path:
  76. rounded_path = pathops.Path()
  77. for verb, points in path:
  78. rounded_path.add(verb, *((round(p[0]), round(p[1])) for p in points))
  79. return rounded_path
  80. def _simplify(
  81. path: pathops.Path,
  82. debugGlyphName: str,
  83. *,
  84. round: Callable[[float], float] = otRound,
  85. ) -> pathops.Path:
  86. # skia-pathops has a bug where it sometimes fails to simplify paths when there
  87. # are float coordinates and control points are very close to one another.
  88. # Rounding coordinates to integers works around the bug.
  89. # Since we are going to round glyf coordinates later on anyway, here it is
  90. # ok(-ish) to also round before simplify. Better than failing the whole process
  91. # for the entire font.
  92. # https://bugs.chromium.org/p/skia/issues/detail?id=11958
  93. # https://github.com/google/fonts/issues/3365
  94. # TODO(anthrotype): remove once this Skia bug is fixed
  95. try:
  96. return pathops.simplify(path, clockwise=path.clockwise)
  97. except pathops.PathOpsError:
  98. pass
  99. path = _round_path(path, round=round)
  100. try:
  101. path = pathops.simplify(path, clockwise=path.clockwise)
  102. log.debug(
  103. "skia-pathops failed to simplify '%s' with float coordinates, "
  104. "but succeded using rounded integer coordinates",
  105. debugGlyphName,
  106. )
  107. return path
  108. except pathops.PathOpsError as e:
  109. if log.isEnabledFor(logging.DEBUG):
  110. path.dump()
  111. raise RemoveOverlapsError(
  112. f"Failed to remove overlaps from glyph {debugGlyphName!r}"
  113. ) from e
  114. raise AssertionError("Unreachable")
  115. def _same_path(path1: pathops.Path, path2: pathops.Path) -> bool:
  116. return {tuple(c) for c in path1.contours} == {tuple(c) for c in path2.contours}
  117. def removeTTGlyphOverlaps(
  118. glyphName: str,
  119. glyphSet: _TTGlyphMapping,
  120. glyfTable: _g_l_y_f.table__g_l_y_f,
  121. hmtxTable: _h_m_t_x.table__h_m_t_x,
  122. removeHinting: bool = True,
  123. ) -> bool:
  124. glyph = glyfTable[glyphName]
  125. # decompose composite glyphs only if components overlap each other
  126. if (
  127. glyph.numberOfContours > 0
  128. or glyph.isComposite()
  129. and componentsOverlap(glyph, glyphSet)
  130. ):
  131. path = skPathFromGlyph(glyphName, glyphSet)
  132. # remove overlaps
  133. path2 = _simplify(path, glyphName)
  134. # replace TTGlyph if simplified path is different (ignoring contour order)
  135. if not _same_path(path, path2):
  136. glyfTable[glyphName] = glyph = ttfGlyphFromSkPath(path2)
  137. # simplified glyph is always unhinted
  138. assert not glyph.program
  139. # also ensure hmtx LSB == glyph.xMin so glyph origin is at x=0
  140. width, lsb = hmtxTable[glyphName]
  141. if lsb != glyph.xMin:
  142. hmtxTable[glyphName] = (width, glyph.xMin)
  143. return True
  144. if removeHinting:
  145. glyph.removeHinting()
  146. return False
  147. def _remove_glyf_overlaps(
  148. *,
  149. font: ttFont.TTFont,
  150. glyphNames: Iterable[str],
  151. glyphSet: _TTGlyphMapping,
  152. removeHinting: bool,
  153. ignoreErrors: bool,
  154. ) -> None:
  155. glyfTable = font["glyf"]
  156. hmtxTable = font["hmtx"]
  157. # process all simple glyphs first, then composites with increasing component depth,
  158. # so that by the time we test for component intersections the respective base glyphs
  159. # have already been simplified
  160. glyphNames = sorted(
  161. glyphNames,
  162. key=lambda name: (
  163. (
  164. glyfTable[name].getCompositeMaxpValues(glyfTable).maxComponentDepth
  165. if glyfTable[name].isComposite()
  166. else 0
  167. ),
  168. name,
  169. ),
  170. )
  171. modified = set()
  172. for glyphName in glyphNames:
  173. try:
  174. if removeTTGlyphOverlaps(
  175. glyphName, glyphSet, glyfTable, hmtxTable, removeHinting
  176. ):
  177. modified.add(glyphName)
  178. except RemoveOverlapsError:
  179. if not ignoreErrors:
  180. raise
  181. log.error("Failed to remove overlaps for '%s'", glyphName)
  182. log.debug("Removed overlaps for %s glyphs:\n%s", len(modified), " ".join(modified))
  183. def _remove_charstring_overlaps(
  184. *,
  185. glyphName: str,
  186. glyphSet: _TTGlyphMapping,
  187. cffFontSet: CFFFontSet,
  188. ) -> bool:
  189. path = skPathFromGlyph(glyphName, glyphSet)
  190. # remove overlaps
  191. path2 = _simplify(path, glyphName, round=noRound)
  192. # replace TTGlyph if simplified path is different (ignoring contour order)
  193. if not _same_path(path, path2):
  194. charStrings = cffFontSet[0].CharStrings
  195. charStrings[glyphName] = _charString_from_SkPath(path2, charStrings[glyphName])
  196. return True
  197. return False
  198. def _remove_cff_overlaps(
  199. *,
  200. font: ttFont.TTFont,
  201. glyphNames: Iterable[str],
  202. glyphSet: _TTGlyphMapping,
  203. removeHinting: bool,
  204. ignoreErrors: bool,
  205. removeUnusedSubroutines: bool = True,
  206. ) -> None:
  207. cffFontSet = font["CFF "].cff
  208. modified = set()
  209. for glyphName in glyphNames:
  210. try:
  211. if _remove_charstring_overlaps(
  212. glyphName=glyphName,
  213. glyphSet=glyphSet,
  214. cffFontSet=cffFontSet,
  215. ):
  216. modified.add(glyphName)
  217. except RemoveOverlapsError:
  218. if not ignoreErrors:
  219. raise
  220. log.error("Failed to remove overlaps for '%s'", glyphName)
  221. if not modified:
  222. log.debug("No overlaps found in the specified CFF glyphs")
  223. return
  224. if removeHinting:
  225. cffFontSet.remove_hints()
  226. if removeUnusedSubroutines:
  227. cffFontSet.remove_unused_subroutines()
  228. log.debug("Removed overlaps for %s glyphs:\n%s", len(modified), " ".join(modified))
  229. def removeOverlaps(
  230. font: ttFont.TTFont,
  231. glyphNames: Optional[Iterable[str]] = None,
  232. removeHinting: bool = True,
  233. ignoreErrors: bool = False,
  234. *,
  235. removeUnusedSubroutines: bool = True,
  236. ) -> None:
  237. """Simplify glyphs in TTFont by merging overlapping contours.
  238. Overlapping components are first decomposed to simple contours, then merged.
  239. Currently this only works for fonts with 'glyf' or 'CFF ' tables.
  240. Raises NotImplementedError if 'glyf' or 'CFF ' tables are absent.
  241. Note that removing overlaps invalidates the hinting. By default we drop hinting
  242. from all glyphs whether or not overlaps are removed from a given one, as it would
  243. look weird if only some glyphs are left (un)hinted.
  244. Args:
  245. font: input TTFont object, modified in place.
  246. glyphNames: optional iterable of glyph names (str) to remove overlaps from.
  247. By default, all glyphs in the font are processed.
  248. removeHinting (bool): set to False to keep hinting for unmodified glyphs.
  249. ignoreErrors (bool): set to True to ignore errors while removing overlaps,
  250. thus keeping the tricky glyphs unchanged (fonttools/fonttools#2363).
  251. removeUnusedSubroutines (bool): set to False to keep unused subroutines
  252. in CFF table after removing overlaps. Default is to remove them if
  253. any glyphs are modified.
  254. """
  255. if "glyf" not in font and "CFF " not in font:
  256. raise NotImplementedError(
  257. "No outline data found in the font: missing 'glyf' or 'CFF ' table"
  258. )
  259. if glyphNames is None:
  260. glyphNames = font.getGlyphOrder()
  261. # Wraps the underlying glyphs, takes care of interfacing with drawing pens
  262. glyphSet = font.getGlyphSet()
  263. if "glyf" in font:
  264. _remove_glyf_overlaps(
  265. font=font,
  266. glyphNames=glyphNames,
  267. glyphSet=glyphSet,
  268. removeHinting=removeHinting,
  269. ignoreErrors=ignoreErrors,
  270. )
  271. if "CFF " in font:
  272. _remove_cff_overlaps(
  273. font=font,
  274. glyphNames=glyphNames,
  275. glyphSet=glyphSet,
  276. removeHinting=removeHinting,
  277. ignoreErrors=ignoreErrors,
  278. removeUnusedSubroutines=removeUnusedSubroutines,
  279. )
  280. def main(args=None):
  281. """Simplify glyphs in TTFont by merging overlapping contours."""
  282. import argparse
  283. parser = argparse.ArgumentParser(
  284. "fonttools ttLib.removeOverlaps", description=__doc__
  285. )
  286. parser.add_argument("input", metavar="INPUT.ttf", help="Input font file")
  287. parser.add_argument("output", metavar="OUTPUT.ttf", help="Output font file")
  288. parser.add_argument(
  289. "glyphs",
  290. metavar="GLYPHS",
  291. nargs="*",
  292. help="Optional list of glyph names to remove overlaps from",
  293. )
  294. parser.add_argument(
  295. "--keep-hinting",
  296. action="store_true",
  297. help="Keep hinting for unmodified glyphs, default is to drop hinting",
  298. )
  299. parser.add_argument(
  300. "--ignore-errors",
  301. action="store_true",
  302. help="ignore errors while removing overlaps, "
  303. "thus keeping the tricky glyphs unchanged",
  304. )
  305. parser.add_argument(
  306. "--keep-unused-subroutines",
  307. action="store_true",
  308. help="Keep unused subroutines in CFF table after removing overlaps, "
  309. "default is to remove them if any glyphs are modified",
  310. )
  311. args = parser.parse_args(args)
  312. with ttFont.TTFont(args.input) as font:
  313. removeOverlaps(
  314. font=font,
  315. glyphNames=args.glyphs or None,
  316. removeHinting=not args.keep_hinting,
  317. ignoreErrors=args.ignore_errors,
  318. removeUnusedSubroutines=not args.keep_unused_subroutines,
  319. )
  320. font.save(args.output)
  321. if __name__ == "__main__":
  322. main()