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