macUtils.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. """ttLib.macUtils.py -- Various Mac-specific stuff."""
  2. from io import BytesIO
  3. from fontTools.misc.macRes import ResourceReader, ResourceError
  4. def getSFNTResIndices(path):
  5. """Determine whether a file has a 'sfnt' resource fork or not."""
  6. try:
  7. reader = ResourceReader(path)
  8. indices = reader.getIndices("sfnt")
  9. reader.close()
  10. return indices
  11. except ResourceError:
  12. return []
  13. def openTTFonts(path):
  14. """Given a pathname, return a list of TTFont objects. In the case
  15. of a flat TTF/OTF file, the list will contain just one font object;
  16. but in the case of a Mac font suitcase it will contain as many
  17. font objects as there are sfnt resources in the file.
  18. """
  19. from fontTools import ttLib
  20. fonts = []
  21. sfnts = getSFNTResIndices(path)
  22. if not sfnts:
  23. fonts.append(ttLib.TTFont(path))
  24. else:
  25. for index in sfnts:
  26. fonts.append(ttLib.TTFont(path, index))
  27. if not fonts:
  28. raise ttLib.TTLibError("no fonts found in file '%s'" % path)
  29. return fonts
  30. class SFNTResourceReader(BytesIO):
  31. """Simple read-only file wrapper for 'sfnt' resources."""
  32. def __init__(self, path, res_name_or_index):
  33. from fontTools import ttLib
  34. reader = ResourceReader(path)
  35. if isinstance(res_name_or_index, str):
  36. rsrc = reader.getNamedResource("sfnt", res_name_or_index)
  37. else:
  38. rsrc = reader.getIndResource("sfnt", res_name_or_index)
  39. if rsrc is None:
  40. raise ttLib.TTLibError("sfnt resource not found: %s" % res_name_or_index)
  41. reader.close()
  42. self.rsrc = rsrc
  43. super(SFNTResourceReader, self).__init__(rsrc.data)
  44. self.name = path