hmtx.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import struct
  2. from lxml.etree import Element
  3. from transform.bytes import outputTableBytes
  4. class hmtxMetric:
  5. """
  6. Class representing a single metric in an hmtx table.
  7. """
  8. def __init__(self, name, advanceWidth, lsb):
  9. self.name = name
  10. self.advanceWidth = advanceWidth
  11. self.lsb = lsb
  12. def toTTX(self):
  13. return Element("mtx", {"name": self.name
  14. ,"width": str(self.advanceWidth)
  15. ,"lsb": str(self.lsb)
  16. })
  17. def toBytes(self):
  18. return struct.pack(">Hh"
  19. , self.advanceWidth
  20. , self.lsb
  21. )
  22. class hmtx:
  23. """
  24. Class representing an hmtx table.
  25. """
  26. def __init__(self, m, glyphs):
  27. self.metrics = []
  28. for g in glyphs["img_empty"]:
  29. self.metrics.append(hmtxMetric(g.name(), m['metrics']['normalWidth'], m['metrics']['normalLSB']))
  30. def toTTX(self):
  31. hmtx = Element("hmtx")
  32. for m in self.metrics:
  33. hmtx.append(m.toTTX())
  34. return hmtx
  35. def toBytes(self):
  36. longHorMetric = b''
  37. for m in self.metrics:
  38. longHorMetric += m.toBytes()
  39. return outputTableBytes(longHorMetric)
  40. # TODO: work out how to calcuilate leftSideBearings[numGlyphs - numberOfHMetrics]
  41. # https://docs.microsoft.com/en-us/typography/opentype/spec/hmtx