File size: 8,579 Bytes
b72ab63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
from io import BytesIO
import struct
from fontTools.misc import sstruct
from fontTools.misc.textTools import bytesjoin, tostr
from collections import OrderedDict
from collections.abc import MutableMapping


class ResourceError(Exception):
    pass


class ResourceReader(MutableMapping):
    """Reader for Mac OS resource forks.

    Parses a resource fork and returns resources according to their type.
    If run on OS X, this will open the resource fork in the filesystem.
    Otherwise, it will open the file itself and attempt to read it as
    though it were a resource fork.

    The returned object can be indexed by type and iterated over,
    returning in each case a list of py:class:`Resource` objects
    representing all the resources of a certain type.

    """

    def __init__(self, fileOrPath):
        """Open a file

        Args:
                fileOrPath: Either an object supporting a ``read`` method, an
                        ``os.PathLike`` object, or a string.
        """
        self._resources = OrderedDict()
        if hasattr(fileOrPath, "read"):
            self.file = fileOrPath
        else:
            try:
                # try reading from the resource fork (only works on OS X)
                self.file = self.openResourceFork(fileOrPath)
                self._readFile()
                return
            except (ResourceError, IOError):
                # if it fails, use the data fork
                self.file = self.openDataFork(fileOrPath)
        self._readFile()

    @staticmethod
    def openResourceFork(path):
        if hasattr(path, "__fspath__"):  # support os.PathLike objects
            path = path.__fspath__()
        with open(path + "/..namedfork/rsrc", "rb") as resfork:
            data = resfork.read()
        infile = BytesIO(data)
        infile.name = path
        return infile

    @staticmethod
    def openDataFork(path):
        with open(path, "rb") as datafork:
            data = datafork.read()
        infile = BytesIO(data)
        infile.name = path
        return infile

    def _readFile(self):
        self._readHeaderAndMap()
        self._readTypeList()

    def _read(self, numBytes, offset=None):
        if offset is not None:
            try:
                self.file.seek(offset)
            except OverflowError:
                raise ResourceError("Failed to seek offset ('offset' is too large)")
            if self.file.tell() != offset:
                raise ResourceError("Failed to seek offset (reached EOF)")
        try:
            data = self.file.read(numBytes)
        except OverflowError:
            raise ResourceError("Cannot read resource ('numBytes' is too large)")
        if len(data) != numBytes:
            raise ResourceError("Cannot read resource (not enough data)")
        return data

    def _readHeaderAndMap(self):
        self.file.seek(0)
        headerData = self._read(ResourceForkHeaderSize)
        sstruct.unpack(ResourceForkHeader, headerData, self)
        # seek to resource map, skip reserved
        mapOffset = self.mapOffset + 22
        resourceMapData = self._read(ResourceMapHeaderSize, mapOffset)
        sstruct.unpack(ResourceMapHeader, resourceMapData, self)
        self.absTypeListOffset = self.mapOffset + self.typeListOffset
        self.absNameListOffset = self.mapOffset + self.nameListOffset

    def _readTypeList(self):
        absTypeListOffset = self.absTypeListOffset
        numTypesData = self._read(2, absTypeListOffset)
        (self.numTypes,) = struct.unpack(">H", numTypesData)
        absTypeListOffset2 = absTypeListOffset + 2
        for i in range(self.numTypes + 1):
            resTypeItemOffset = absTypeListOffset2 + ResourceTypeItemSize * i
            resTypeItemData = self._read(ResourceTypeItemSize, resTypeItemOffset)
            item = sstruct.unpack(ResourceTypeItem, resTypeItemData)
            resType = tostr(item["type"], encoding="mac-roman")
            refListOffset = absTypeListOffset + item["refListOffset"]
            numRes = item["numRes"] + 1
            resources = self._readReferenceList(resType, refListOffset, numRes)
            self._resources[resType] = resources

    def _readReferenceList(self, resType, refListOffset, numRes):
        resources = []
        for i in range(numRes):
            refOffset = refListOffset + ResourceRefItemSize * i
            refData = self._read(ResourceRefItemSize, refOffset)
            res = Resource(resType)
            res.decompile(refData, self)
            resources.append(res)
        return resources

    def __getitem__(self, resType):
        return self._resources[resType]

    def __delitem__(self, resType):
        del self._resources[resType]

    def __setitem__(self, resType, resources):
        self._resources[resType] = resources

    def __len__(self):
        return len(self._resources)

    def __iter__(self):
        return iter(self._resources)

    def keys(self):
        return self._resources.keys()

    @property
    def types(self):
        """A list of the types of resources in the resource fork."""
        return list(self._resources.keys())

    def countResources(self, resType):
        """Return the number of resources of a given type."""
        try:
            return len(self[resType])
        except KeyError:
            return 0

    def getIndices(self, resType):
        """Returns a list of indices of resources of a given type."""
        numRes = self.countResources(resType)
        if numRes:
            return list(range(1, numRes + 1))
        else:
            return []

    def getNames(self, resType):
        """Return list of names of all resources of a given type."""
        return [res.name for res in self.get(resType, []) if res.name is not None]

    def getIndResource(self, resType, index):
        """Return resource of given type located at an index ranging from 1
        to the number of resources for that type, or None if not found.
        """
        if index < 1:
            return None
        try:
            res = self[resType][index - 1]
        except (KeyError, IndexError):
            return None
        return res

    def getNamedResource(self, resType, name):
        """Return the named resource of given type, else return None."""
        name = tostr(name, encoding="mac-roman")
        for res in self.get(resType, []):
            if res.name == name:
                return res
        return None

    def close(self):
        if not self.file.closed:
            self.file.close()


class Resource(object):
    """Represents a resource stored within a resource fork.

    Attributes:
            type: resource type.
            data: resource data.
            id: ID.
            name: resource name.
            attr: attributes.
    """

    def __init__(
        self, resType=None, resData=None, resID=None, resName=None, resAttr=None
    ):
        self.type = resType
        self.data = resData
        self.id = resID
        self.name = resName
        self.attr = resAttr

    def decompile(self, refData, reader):
        sstruct.unpack(ResourceRefItem, refData, self)
        # interpret 3-byte dataOffset as (padded) ULONG to unpack it with struct
        (self.dataOffset,) = struct.unpack(">L", bytesjoin([b"\0", self.dataOffset]))
        absDataOffset = reader.dataOffset + self.dataOffset
        (dataLength,) = struct.unpack(">L", reader._read(4, absDataOffset))
        self.data = reader._read(dataLength)
        if self.nameOffset == -1:
            return
        absNameOffset = reader.absNameListOffset + self.nameOffset
        (nameLength,) = struct.unpack("B", reader._read(1, absNameOffset))
        (name,) = struct.unpack(">%ss" % nameLength, reader._read(nameLength))
        self.name = tostr(name, encoding="mac-roman")


ResourceForkHeader = """
		> # big endian
		dataOffset:     L
		mapOffset:      L
		dataLen:        L
		mapLen:         L
"""

ResourceForkHeaderSize = sstruct.calcsize(ResourceForkHeader)

ResourceMapHeader = """
		> # big endian
		attr:              H
		typeListOffset:    H
		nameListOffset:    H
"""

ResourceMapHeaderSize = sstruct.calcsize(ResourceMapHeader)

ResourceTypeItem = """
		> # big endian
		type:              4s
		numRes:            H
		refListOffset:     H
"""

ResourceTypeItemSize = sstruct.calcsize(ResourceTypeItem)

ResourceRefItem = """
		> # big endian
		id:                h
		nameOffset:        h
		attr:              B
		dataOffset:        3s
		reserved:          L
"""

ResourceRefItemSize = sstruct.calcsize(ResourceRefItem)