removeOverlaps.py 12 KB

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