hashPointPen.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Modified from https://github.com/adobe-type-tools/psautohint/blob/08b346865710ed3c172f1eb581d6ef243b203f99/python/psautohint/ufoFont.py#L800-L838
  2. import hashlib
  3. from fontTools.pens.basePen import MissingComponentError
  4. from fontTools.pens.pointPen import AbstractPointPen
  5. class HashPointPen(AbstractPointPen):
  6. """
  7. This pen can be used to check if a glyph's contents (outlines plus
  8. components) have changed.
  9. Components are added as the original outline plus each composite's
  10. transformation.
  11. Example: You have some TrueType hinting code for a glyph which you want to
  12. compile. The hinting code specifies a hash value computed with HashPointPen
  13. that was valid for the glyph's outlines at the time the hinting code was
  14. written. Now you can calculate the hash for the glyph's current outlines to
  15. check if the outlines have changed, which would probably make the hinting
  16. code invalid.
  17. > glyph = ufo[name]
  18. > hash_pen = HashPointPen(glyph.width, ufo)
  19. > glyph.drawPoints(hash_pen)
  20. > ttdata = glyph.lib.get("public.truetype.instructions", None)
  21. > stored_hash = ttdata.get("id", None) # The hash is stored in the "id" key
  22. > if stored_hash is None or stored_hash != hash_pen.hash:
  23. > logger.error(f"Glyph hash mismatch, glyph '{name}' will have no instructions in font.")
  24. > else:
  25. > # The hash values are identical, the outline has not changed.
  26. > # Compile the hinting code ...
  27. > pass
  28. """
  29. def __init__(self, glyphWidth=0, glyphSet=None):
  30. self.glyphset = glyphSet
  31. self.data = ["w%s" % round(glyphWidth, 9)]
  32. @property
  33. def hash(self):
  34. data = "".join(self.data)
  35. if len(data) >= 128:
  36. data = hashlib.sha512(data.encode("ascii")).hexdigest()
  37. return data
  38. def beginPath(self, identifier=None, **kwargs):
  39. pass
  40. def endPath(self):
  41. self.data.append("|")
  42. def addPoint(
  43. self,
  44. pt,
  45. segmentType=None,
  46. smooth=False,
  47. name=None,
  48. identifier=None,
  49. **kwargs,
  50. ):
  51. if segmentType is None:
  52. pt_type = "o" # offcurve
  53. else:
  54. pt_type = segmentType[0]
  55. self.data.append(f"{pt_type}{pt[0]:g}{pt[1]:+g}")
  56. def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs):
  57. tr = "".join([f"{t:+}" for t in transformation])
  58. self.data.append("[")
  59. try:
  60. self.glyphset[baseGlyphName].drawPoints(self)
  61. except KeyError:
  62. raise MissingComponentError(baseGlyphName)
  63. self.data.append(f"({tr})]")