blob: ee862f51d021e9910449af3d1206fcc4e8d61029 [file] [log] [blame]
Just7842e561999-12-16 21:34:53 +00001"""fontTools.t1Lib.py -- Tools for PostScript Type 1 fonts
2
3Functions for reading and writing raw Type 1 data:
4
5read(path)
6 reads any Type 1 font file, returns the raw data and a type indicator:
7 'LWFN', 'PFB' or 'OTHER', depending on the format of the file pointed
8 to by 'path'.
9 Raises an error when the file does not contain valid Type 1 data.
10
Just5810aa92001-06-24 15:12:48 +000011write(path, data, kind='OTHER', dohex=0)
Just7842e561999-12-16 21:34:53 +000012 writes raw Type 1 data to the file pointed to by 'path'.
13 'kind' can be one of 'LWFN', 'PFB' or 'OTHER'; it defaults to 'OTHER'.
14 'dohex' is a flag which determines whether the eexec encrypted
15 part should be written as hexadecimal or binary, but only if kind
16 is 'LWFN' or 'PFB'.
17"""
18
19__author__ = "jvr"
20__version__ = "1.0b2"
21DEBUG = 0
22
Justc2be3d92000-01-12 19:15:57 +000023from fontTools.misc import eexec
Just7842e561999-12-16 21:34:53 +000024import string
25import re
26import os
27
jvr22433b12002-07-12 19:20:19 +000028
29try:
30 import macfs
31except ImportError:
32 haveMacSupport = 0
33else:
34 haveMacSupport = 1
35
36if haveMacSupport:
jvr25ccb9c2002-05-03 19:38:07 +000037 try:
38 from Carbon import Res
39 except ImportError:
40 import Res # MacPython < 2.2
Just7842e561999-12-16 21:34:53 +000041 import macfs
42
43error = 't1Lib.error'
44
Just7842e561999-12-16 21:34:53 +000045
46class T1Font:
47
Just36183002000-03-28 10:38:43 +000048 """Type 1 font class.
49
50 Uses a minimal interpeter that supports just about enough PS to parse
51 Type 1 fonts.
Just7842e561999-12-16 21:34:53 +000052 """
53
54 def __init__(self, path=None):
55 if path is not None:
56 self.data, type = read(path)
57 else:
58 pass # XXX
59
60 def saveAs(self, path, type):
jvr8c74f462001-08-16 10:34:22 +000061 write(path, self.getData(), type)
Just7842e561999-12-16 21:34:53 +000062
63 def getData(self):
Just36183002000-03-28 10:38:43 +000064 # XXX Todo: if the data has been converted to Python object,
65 # recreate the PS stream
Just7842e561999-12-16 21:34:53 +000066 return self.data
67
68 def __getitem__(self, key):
69 if not hasattr(self, "font"):
70 self.parse()
Just36183002000-03-28 10:38:43 +000071 return self.font[key]
Just7842e561999-12-16 21:34:53 +000072
73 def parse(self):
Just528614e2000-01-16 22:14:02 +000074 from fontTools.misc import psLib
75 from fontTools.misc import psCharStrings
Just7842e561999-12-16 21:34:53 +000076 self.font = psLib.suckfont(self.data)
77 charStrings = self.font["CharStrings"]
78 lenIV = self.font["Private"].get("lenIV", 4)
79 assert lenIV >= 0
80 for glyphName, charString in charStrings.items():
Justc2be3d92000-01-12 19:15:57 +000081 charString, R = eexec.decrypt(charString, 4330)
Just7842e561999-12-16 21:34:53 +000082 charStrings[glyphName] = psCharStrings.T1CharString(charString[lenIV:])
83 subrs = self.font["Private"]["Subrs"]
84 for i in range(len(subrs)):
Justc2be3d92000-01-12 19:15:57 +000085 charString, R = eexec.decrypt(subrs[i], 4330)
Just7842e561999-12-16 21:34:53 +000086 subrs[i] = psCharStrings.T1CharString(charString[lenIV:])
87 del self.data
88
89
90
Just36183002000-03-28 10:38:43 +000091# low level T1 data read and write functions
Just7842e561999-12-16 21:34:53 +000092
93def read(path):
94 """reads any Type 1 font file, returns raw data"""
95 normpath = string.lower(path)
jvr22433b12002-07-12 19:20:19 +000096 if haveMacSupport:
Just7842e561999-12-16 21:34:53 +000097 fss = macfs.FSSpec(path)
98 creator, type = fss.GetCreatorType()
99 if type == 'LWFN':
Just5810aa92001-06-24 15:12:48 +0000100 return readLWFN(path), 'LWFN'
Just7842e561999-12-16 21:34:53 +0000101 if normpath[-4:] == '.pfb':
Just5810aa92001-06-24 15:12:48 +0000102 return readPFB(path), 'PFB'
Just7842e561999-12-16 21:34:53 +0000103 else:
Just5810aa92001-06-24 15:12:48 +0000104 return readOther(path), 'OTHER'
Just7842e561999-12-16 21:34:53 +0000105
106def write(path, data, kind='OTHER', dohex=0):
Just5810aa92001-06-24 15:12:48 +0000107 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000108 kind = string.upper(kind)
109 try:
110 os.remove(path)
111 except os.error:
112 pass
113 err = 1
114 try:
115 if kind == 'LWFN':
Just5810aa92001-06-24 15:12:48 +0000116 writeLWFN(path, data)
Just7842e561999-12-16 21:34:53 +0000117 elif kind == 'PFB':
Just5810aa92001-06-24 15:12:48 +0000118 writePFB(path, data)
Just7842e561999-12-16 21:34:53 +0000119 else:
Just5810aa92001-06-24 15:12:48 +0000120 writeOther(path, data, dohex)
Just7842e561999-12-16 21:34:53 +0000121 err = 0
122 finally:
123 if err and not DEBUG:
124 try:
125 os.remove(path)
126 except os.error:
127 pass
128
129
130# -- internal --
131
132LWFNCHUNKSIZE = 2000
133HEXLINELENGTH = 80
134
135
Just5810aa92001-06-24 15:12:48 +0000136def readLWFN(path):
Just7842e561999-12-16 21:34:53 +0000137 """reads an LWFN font file, returns raw data"""
Juste9601bf2001-07-30 19:04:40 +0000138 resRef = Res.FSpOpenResFile(path, 1) # read-only
Just7842e561999-12-16 21:34:53 +0000139 try:
Juste9601bf2001-07-30 19:04:40 +0000140 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000141 n = Res.Count1Resources('POST')
142 data = []
143 for i in range(501, 501 + n):
144 res = Res.Get1Resource('POST', i)
145 code = ord(res.data[0])
146 if ord(res.data[1]) <> 0:
147 raise error, 'corrupt LWFN file'
148 if code in [1, 2]:
149 data.append(res.data[2:])
150 elif code in [3, 5]:
151 break
152 elif code == 4:
153 f = open(path, "rb")
154 data.append(f.read())
155 f.close()
156 elif code == 0:
157 pass # comment, ignore
158 else:
159 raise error, 'bad chunk code: ' + `code`
160 finally:
Juste9601bf2001-07-30 19:04:40 +0000161 Res.CloseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000162 data = string.join(data, '')
Just5810aa92001-06-24 15:12:48 +0000163 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000164 return data
165
Just5810aa92001-06-24 15:12:48 +0000166def readPFB(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000167 """reads a PFB font file, returns raw data"""
168 f = open(path, "rb")
169 data = []
170 while 1:
171 if f.read(1) <> chr(128):
172 raise error, 'corrupt PFB file'
173 code = ord(f.read(1))
174 if code in [1, 2]:
Just5810aa92001-06-24 15:12:48 +0000175 chunklen = stringToLong(f.read(4))
Just36183002000-03-28 10:38:43 +0000176 chunk = f.read(chunklen)
177 assert len(chunk) == chunklen
178 data.append(chunk)
Just7842e561999-12-16 21:34:53 +0000179 elif code == 3:
180 break
181 else:
182 raise error, 'bad chunk code: ' + `code`
Just5810aa92001-06-24 15:12:48 +0000183 if onlyHeader:
184 break
Just7842e561999-12-16 21:34:53 +0000185 f.close()
186 data = string.join(data, '')
Just5810aa92001-06-24 15:12:48 +0000187 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000188 return data
189
Just5810aa92001-06-24 15:12:48 +0000190def readOther(path):
Just7842e561999-12-16 21:34:53 +0000191 """reads any (font) file, returns raw data"""
192 f = open(path, "rb")
193 data = f.read()
194 f.close()
Just5810aa92001-06-24 15:12:48 +0000195 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000196
Just5810aa92001-06-24 15:12:48 +0000197 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000198 data = []
Just5810aa92001-06-24 15:12:48 +0000199 for isEncrypted, chunk in chunks:
200 if isEncrypted and isHex(chunk[:4]):
201 data.append(deHexString(chunk))
Just7842e561999-12-16 21:34:53 +0000202 else:
203 data.append(chunk)
204 return string.join(data, '')
205
206# file writing tools
207
Just5810aa92001-06-24 15:12:48 +0000208def writeLWFN(path, data):
Juste9601bf2001-07-30 19:04:40 +0000209 Res.FSpCreateResFile(path, "just", "LWFN", 0)
210 resRef = Res.FSpOpenResFile(path, 2) # write-only
Just7842e561999-12-16 21:34:53 +0000211 try:
Juste9601bf2001-07-30 19:04:40 +0000212 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000213 resID = 501
Just5810aa92001-06-24 15:12:48 +0000214 chunks = findEncryptedChunks(data)
215 for isEncrypted, chunk in chunks:
216 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000217 code = 2
218 else:
219 code = 1
220 while chunk:
221 res = Res.Resource(chr(code) + '\0' + chunk[:LWFNCHUNKSIZE - 2])
222 res.AddResource('POST', resID, '')
223 chunk = chunk[LWFNCHUNKSIZE - 2:]
224 resID = resID + 1
225 res = Res.Resource(chr(5) + '\0')
226 res.AddResource('POST', resID, '')
227 finally:
Juste9601bf2001-07-30 19:04:40 +0000228 Res.CloseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000229
Just5810aa92001-06-24 15:12:48 +0000230def writePFB(path, data):
231 chunks = findEncryptedChunks(data)
Just36183002000-03-28 10:38:43 +0000232 f = open(path, "wb")
Just7842e561999-12-16 21:34:53 +0000233 try:
Just5810aa92001-06-24 15:12:48 +0000234 for isEncrypted, chunk in chunks:
235 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000236 code = 2
237 else:
238 code = 1
239 f.write(chr(128) + chr(code))
Just5810aa92001-06-24 15:12:48 +0000240 f.write(longToString(len(chunk)))
Just7842e561999-12-16 21:34:53 +0000241 f.write(chunk)
242 f.write(chr(128) + chr(3))
243 finally:
244 f.close()
jvr22433b12002-07-12 19:20:19 +0000245 if haveMacSupport:
Just36183002000-03-28 10:38:43 +0000246 fss = macfs.FSSpec(path)
Just7842e561999-12-16 21:34:53 +0000247 fss.SetCreatorType('mdos', 'BINA')
248
Just5810aa92001-06-24 15:12:48 +0000249def writeOther(path, data, dohex = 0):
250 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000251 f = open(path, "wb")
252 try:
253 hexlinelen = HEXLINELENGTH / 2
Just5810aa92001-06-24 15:12:48 +0000254 for isEncrypted, chunk in chunks:
255 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000256 code = 2
257 else:
258 code = 1
259 if code == 2 and dohex:
260 while chunk:
Justc2be3d92000-01-12 19:15:57 +0000261 f.write(eexec.hexString(chunk[:hexlinelen]))
Just7842e561999-12-16 21:34:53 +0000262 f.write('\r')
263 chunk = chunk[hexlinelen:]
264 else:
265 f.write(chunk)
266 finally:
267 f.close()
jvr22433b12002-07-12 19:20:19 +0000268 if haveMacSupport:
Just7842e561999-12-16 21:34:53 +0000269 fss = macfs.FSSpec(path)
270 fss.SetCreatorType('R*ch', 'TEXT') # BBEdit text file
271
272
273# decryption tools
274
275EEXECBEGIN = "currentfile eexec"
276EEXECEND = '0' * 64
277EEXECINTERNALEND = "currentfile closefile"
278EEXECBEGINMARKER = "%-- eexec start\r"
279EEXECENDMARKER = "%-- eexec end\r"
280
281_ishexRE = re.compile('[0-9A-Fa-f]*$')
282
Just5810aa92001-06-24 15:12:48 +0000283def isHex(text):
Just7842e561999-12-16 21:34:53 +0000284 return _ishexRE.match(text) is not None
285
286
Just5810aa92001-06-24 15:12:48 +0000287def decryptType1(data):
288 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000289 data = []
Just5810aa92001-06-24 15:12:48 +0000290 for isEncrypted, chunk in chunks:
291 if isEncrypted:
292 if isHex(chunk[:4]):
293 chunk = deHexString(chunk)
Justc2be3d92000-01-12 19:15:57 +0000294 decrypted, R = eexec.decrypt(chunk, 55665)
Just7842e561999-12-16 21:34:53 +0000295 decrypted = decrypted[4:]
296 if decrypted[-len(EEXECINTERNALEND)-1:-1] <> EEXECINTERNALEND \
297 and decrypted[-len(EEXECINTERNALEND)-2:-2] <> EEXECINTERNALEND:
298 raise error, "invalid end of eexec part"
299 decrypted = decrypted[:-len(EEXECINTERNALEND)-2] + '\r'
300 data.append(EEXECBEGINMARKER + decrypted + EEXECENDMARKER)
301 else:
302 if chunk[-len(EEXECBEGIN)-1:-1] == EEXECBEGIN:
303 data.append(chunk[:-len(EEXECBEGIN)-1])
304 else:
305 data.append(chunk)
306 return string.join(data, '')
307
Just5810aa92001-06-24 15:12:48 +0000308def findEncryptedChunks(data):
Just7842e561999-12-16 21:34:53 +0000309 chunks = []
310 while 1:
Just5810aa92001-06-24 15:12:48 +0000311 eBegin = string.find(data, EEXECBEGIN)
312 if eBegin < 0:
Just7842e561999-12-16 21:34:53 +0000313 break
jvr90290b72001-11-28 12:22:15 +0000314 eBegin = eBegin + len(EEXECBEGIN) + 1
Just5810aa92001-06-24 15:12:48 +0000315 eEnd = string.find(data, EEXECEND, eBegin)
316 if eEnd < 0:
Just7842e561999-12-16 21:34:53 +0000317 raise error, "can't find end of eexec part"
jvr90290b72001-11-28 12:22:15 +0000318 cypherText = data[eBegin:eEnd + 2]
319 plainText, R = eexec.decrypt(cypherText, 55665)
320 eEndLocal = string.find(plainText, EEXECINTERNALEND)
321 if eEndLocal < 0:
322 raise error, "can't find end of eexec part"
323 eEnd = eBegin + eEndLocal + len(EEXECINTERNALEND) + 1
324 chunks.append((0, data[:eBegin]))
325 chunks.append((1, data[eBegin:eEnd]))
Just5810aa92001-06-24 15:12:48 +0000326 data = data[eEnd:]
Just7842e561999-12-16 21:34:53 +0000327 chunks.append((0, data))
328 return chunks
329
Just5810aa92001-06-24 15:12:48 +0000330def deHexString(hexstring):
Justc2be3d92000-01-12 19:15:57 +0000331 return eexec.deHexString(string.join(string.split(hexstring), ""))
Just7842e561999-12-16 21:34:53 +0000332
333
334# Type 1 assertion
335
336_fontType1RE = re.compile(r"/FontType\s+1\s+def")
337
Just5810aa92001-06-24 15:12:48 +0000338def assertType1(data):
Just7842e561999-12-16 21:34:53 +0000339 for head in ['%!PS-AdobeFont', '%!FontType1-1.0']:
340 if data[:len(head)] == head:
341 break
342 else:
343 raise error, "not a PostScript font"
344 if not _fontType1RE.search(data):
345 raise error, "not a Type 1 font"
346 if string.find(data, "currentfile eexec") < 0:
347 raise error, "not an encrypted Type 1 font"
348 # XXX what else?
349 return data
350
351
352# pfb helpers
353
Just5810aa92001-06-24 15:12:48 +0000354def longToString(long):
Just7842e561999-12-16 21:34:53 +0000355 str = ""
356 for i in range(4):
357 str = str + chr((long & (0xff << (i * 8))) >> i * 8)
358 return str
359
Just5810aa92001-06-24 15:12:48 +0000360def stringToLong(str):
Just7842e561999-12-16 21:34:53 +0000361 if len(str) <> 4:
362 raise ValueError, 'string must be 4 bytes long'
363 long = 0
364 for i in range(4):
365 long = long + (ord(str[i]) << (i * 8))
366 return long
Just5810aa92001-06-24 15:12:48 +0000367