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