blob: bb8c9bd80348cc8062fabed1ddf65a0b165e798b [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:
jvr25ccb9c2002-05-03 19:38:07 +000030 try:
31 from Carbon import Res
32 except ImportError:
33 import Res # MacPython < 2.2
jvre568dc72002-07-23 09:25:42 +000034except ImportError:
35 haveMacSupport = 0
36else:
37 haveMacSupport = 1
jvrb19141e2003-06-07 15:15:51 +000038 import MacOS
jvr59afba72003-05-24 12:34:11 +000039
Just7842e561999-12-16 21:34:53 +000040
jvre568dc72002-07-23 09:25:42 +000041class T1Error(Exception): pass
Just7842e561999-12-16 21:34:53 +000042
Just7842e561999-12-16 21:34:53 +000043
44class T1Font:
45
Just36183002000-03-28 10:38:43 +000046 """Type 1 font class.
47
48 Uses a minimal interpeter that supports just about enough PS to parse
49 Type 1 fonts.
Just7842e561999-12-16 21:34:53 +000050 """
51
52 def __init__(self, path=None):
53 if path is not None:
54 self.data, type = read(path)
55 else:
56 pass # XXX
57
58 def saveAs(self, path, type):
jvr8c74f462001-08-16 10:34:22 +000059 write(path, self.getData(), type)
Just7842e561999-12-16 21:34:53 +000060
61 def getData(self):
Just36183002000-03-28 10:38:43 +000062 # XXX Todo: if the data has been converted to Python object,
63 # recreate the PS stream
Just7842e561999-12-16 21:34:53 +000064 return self.data
65
jvr7d4b6932003-08-25 17:53:29 +000066 def getGlyphSet(self):
67 """Return a generic GlyphSet, which is a dict-like object
68 mapping glyph names to glyph objects. The returned glyph objects
69 have a .draw() method that supports the Pen protocol, and will
70 have an attribute named 'width', but only *after* the .draw() method
71 has been called.
72
73 In the case of Type 1, the GlyphSet is simply the CharStrings dict.
74 """
75 return self["CharStrings"]
76
Just7842e561999-12-16 21:34:53 +000077 def __getitem__(self, key):
78 if not hasattr(self, "font"):
79 self.parse()
Just36183002000-03-28 10:38:43 +000080 return self.font[key]
Just7842e561999-12-16 21:34:53 +000081
82 def parse(self):
Just528614e2000-01-16 22:14:02 +000083 from fontTools.misc import psLib
84 from fontTools.misc import psCharStrings
Just7842e561999-12-16 21:34:53 +000085 self.font = psLib.suckfont(self.data)
86 charStrings = self.font["CharStrings"]
87 lenIV = self.font["Private"].get("lenIV", 4)
88 assert lenIV >= 0
jvr489d76a2003-08-24 19:56:16 +000089 subrs = self.font["Private"]["Subrs"]
Just7842e561999-12-16 21:34:53 +000090 for glyphName, charString in charStrings.items():
Justc2be3d92000-01-12 19:15:57 +000091 charString, R = eexec.decrypt(charString, 4330)
jvr489d76a2003-08-24 19:56:16 +000092 charStrings[glyphName] = psCharStrings.T1CharString(charString[lenIV:],
93 subrs=subrs)
Just7842e561999-12-16 21:34:53 +000094 for i in range(len(subrs)):
Justc2be3d92000-01-12 19:15:57 +000095 charString, R = eexec.decrypt(subrs[i], 4330)
jvr489d76a2003-08-24 19:56:16 +000096 subrs[i] = psCharStrings.T1CharString(charString[lenIV:], subrs=subrs)
Just7842e561999-12-16 21:34:53 +000097 del self.data
Just7842e561999-12-16 21:34:53 +000098
99
Just36183002000-03-28 10:38:43 +0000100# low level T1 data read and write functions
Just7842e561999-12-16 21:34:53 +0000101
102def read(path):
103 """reads any Type 1 font file, returns raw data"""
104 normpath = string.lower(path)
jvr22433b12002-07-12 19:20:19 +0000105 if haveMacSupport:
jvrb19141e2003-06-07 15:15:51 +0000106 creator, type = MacOS.GetCreatorAndType(path)
Just7842e561999-12-16 21:34:53 +0000107 if type == 'LWFN':
Just5810aa92001-06-24 15:12:48 +0000108 return readLWFN(path), 'LWFN'
Just7842e561999-12-16 21:34:53 +0000109 if normpath[-4:] == '.pfb':
Just5810aa92001-06-24 15:12:48 +0000110 return readPFB(path), 'PFB'
Just7842e561999-12-16 21:34:53 +0000111 else:
Just5810aa92001-06-24 15:12:48 +0000112 return readOther(path), 'OTHER'
Just7842e561999-12-16 21:34:53 +0000113
114def write(path, data, kind='OTHER', dohex=0):
Just5810aa92001-06-24 15:12:48 +0000115 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000116 kind = string.upper(kind)
117 try:
118 os.remove(path)
119 except os.error:
120 pass
121 err = 1
122 try:
123 if kind == 'LWFN':
Just5810aa92001-06-24 15:12:48 +0000124 writeLWFN(path, data)
Just7842e561999-12-16 21:34:53 +0000125 elif kind == 'PFB':
Just5810aa92001-06-24 15:12:48 +0000126 writePFB(path, data)
Just7842e561999-12-16 21:34:53 +0000127 else:
Just5810aa92001-06-24 15:12:48 +0000128 writeOther(path, data, dohex)
Just7842e561999-12-16 21:34:53 +0000129 err = 0
130 finally:
131 if err and not DEBUG:
132 try:
133 os.remove(path)
134 except os.error:
135 pass
136
137
138# -- internal --
139
140LWFNCHUNKSIZE = 2000
141HEXLINELENGTH = 80
142
143
jvrda0d8052002-07-29 21:33:46 +0000144def readLWFN(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000145 """reads an LWFN font file, returns raw data"""
Juste9601bf2001-07-30 19:04:40 +0000146 resRef = Res.FSpOpenResFile(path, 1) # read-only
Just7842e561999-12-16 21:34:53 +0000147 try:
Juste9601bf2001-07-30 19:04:40 +0000148 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000149 n = Res.Count1Resources('POST')
150 data = []
151 for i in range(501, 501 + n):
152 res = Res.Get1Resource('POST', i)
153 code = ord(res.data[0])
154 if ord(res.data[1]) <> 0:
jvre568dc72002-07-23 09:25:42 +0000155 raise T1Error, 'corrupt LWFN file'
Just7842e561999-12-16 21:34:53 +0000156 if code in [1, 2]:
jvrda0d8052002-07-29 21:33:46 +0000157 if onlyHeader and code == 2:
158 break
jvr05a16f22002-07-29 21:39:06 +0000159 data.append(res.data[2:])
Just7842e561999-12-16 21:34:53 +0000160 elif code in [3, 5]:
161 break
162 elif code == 4:
163 f = open(path, "rb")
164 data.append(f.read())
165 f.close()
166 elif code == 0:
167 pass # comment, ignore
168 else:
jvre568dc72002-07-23 09:25:42 +0000169 raise T1Error, 'bad chunk code: ' + `code`
Just7842e561999-12-16 21:34:53 +0000170 finally:
Juste9601bf2001-07-30 19:04:40 +0000171 Res.CloseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000172 data = string.join(data, '')
Just5810aa92001-06-24 15:12:48 +0000173 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000174 return data
175
Just5810aa92001-06-24 15:12:48 +0000176def readPFB(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000177 """reads a PFB font file, returns raw data"""
178 f = open(path, "rb")
179 data = []
180 while 1:
181 if f.read(1) <> chr(128):
jvre568dc72002-07-23 09:25:42 +0000182 raise T1Error, 'corrupt PFB file'
Just7842e561999-12-16 21:34:53 +0000183 code = ord(f.read(1))
184 if code in [1, 2]:
Just5810aa92001-06-24 15:12:48 +0000185 chunklen = stringToLong(f.read(4))
Just36183002000-03-28 10:38:43 +0000186 chunk = f.read(chunklen)
187 assert len(chunk) == chunklen
188 data.append(chunk)
Just7842e561999-12-16 21:34:53 +0000189 elif code == 3:
190 break
191 else:
jvre568dc72002-07-23 09:25:42 +0000192 raise T1Error, 'bad chunk code: ' + `code`
Just5810aa92001-06-24 15:12:48 +0000193 if onlyHeader:
194 break
Just7842e561999-12-16 21:34:53 +0000195 f.close()
196 data = string.join(data, '')
Just5810aa92001-06-24 15:12:48 +0000197 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000198 return data
199
Just5810aa92001-06-24 15:12:48 +0000200def readOther(path):
Just7842e561999-12-16 21:34:53 +0000201 """reads any (font) file, returns raw data"""
202 f = open(path, "rb")
203 data = f.read()
204 f.close()
Just5810aa92001-06-24 15:12:48 +0000205 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000206
Just5810aa92001-06-24 15:12:48 +0000207 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000208 data = []
Just5810aa92001-06-24 15:12:48 +0000209 for isEncrypted, chunk in chunks:
210 if isEncrypted and isHex(chunk[:4]):
211 data.append(deHexString(chunk))
Just7842e561999-12-16 21:34:53 +0000212 else:
213 data.append(chunk)
214 return string.join(data, '')
215
216# file writing tools
217
Just5810aa92001-06-24 15:12:48 +0000218def writeLWFN(path, data):
Juste9601bf2001-07-30 19:04:40 +0000219 Res.FSpCreateResFile(path, "just", "LWFN", 0)
220 resRef = Res.FSpOpenResFile(path, 2) # write-only
Just7842e561999-12-16 21:34:53 +0000221 try:
Juste9601bf2001-07-30 19:04:40 +0000222 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000223 resID = 501
Just5810aa92001-06-24 15:12:48 +0000224 chunks = findEncryptedChunks(data)
225 for isEncrypted, chunk in chunks:
226 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000227 code = 2
228 else:
229 code = 1
230 while chunk:
231 res = Res.Resource(chr(code) + '\0' + chunk[:LWFNCHUNKSIZE - 2])
232 res.AddResource('POST', resID, '')
233 chunk = chunk[LWFNCHUNKSIZE - 2:]
234 resID = resID + 1
235 res = Res.Resource(chr(5) + '\0')
236 res.AddResource('POST', resID, '')
237 finally:
Juste9601bf2001-07-30 19:04:40 +0000238 Res.CloseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000239
Just5810aa92001-06-24 15:12:48 +0000240def writePFB(path, data):
241 chunks = findEncryptedChunks(data)
Just36183002000-03-28 10:38:43 +0000242 f = open(path, "wb")
Just7842e561999-12-16 21:34:53 +0000243 try:
Just5810aa92001-06-24 15:12:48 +0000244 for isEncrypted, chunk in chunks:
245 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000246 code = 2
247 else:
248 code = 1
249 f.write(chr(128) + chr(code))
Just5810aa92001-06-24 15:12:48 +0000250 f.write(longToString(len(chunk)))
Just7842e561999-12-16 21:34:53 +0000251 f.write(chunk)
252 f.write(chr(128) + chr(3))
253 finally:
254 f.close()
jvr22433b12002-07-12 19:20:19 +0000255 if haveMacSupport:
jvrb19141e2003-06-07 15:15:51 +0000256 MacOS.SetCreatorAndType(path, 'mdos', 'BINA')
Just7842e561999-12-16 21:34:53 +0000257
Just5810aa92001-06-24 15:12:48 +0000258def writeOther(path, data, dohex = 0):
259 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000260 f = open(path, "wb")
261 try:
262 hexlinelen = HEXLINELENGTH / 2
Just5810aa92001-06-24 15:12:48 +0000263 for isEncrypted, chunk in chunks:
264 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000265 code = 2
266 else:
267 code = 1
268 if code == 2 and dohex:
269 while chunk:
Justc2be3d92000-01-12 19:15:57 +0000270 f.write(eexec.hexString(chunk[:hexlinelen]))
Just7842e561999-12-16 21:34:53 +0000271 f.write('\r')
272 chunk = chunk[hexlinelen:]
273 else:
274 f.write(chunk)
275 finally:
276 f.close()
jvr22433b12002-07-12 19:20:19 +0000277 if haveMacSupport:
jvrb19141e2003-06-07 15:15:51 +0000278 MacOS.SetCreatorAndType(path, 'R*ch', 'TEXT') # BBEdit text file
Just7842e561999-12-16 21:34:53 +0000279
280
281# decryption tools
282
283EEXECBEGIN = "currentfile eexec"
284EEXECEND = '0' * 64
285EEXECINTERNALEND = "currentfile closefile"
286EEXECBEGINMARKER = "%-- eexec start\r"
287EEXECENDMARKER = "%-- eexec end\r"
288
289_ishexRE = re.compile('[0-9A-Fa-f]*$')
290
Just5810aa92001-06-24 15:12:48 +0000291def isHex(text):
Just7842e561999-12-16 21:34:53 +0000292 return _ishexRE.match(text) is not None
293
294
Just5810aa92001-06-24 15:12:48 +0000295def decryptType1(data):
296 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000297 data = []
Just5810aa92001-06-24 15:12:48 +0000298 for isEncrypted, chunk in chunks:
299 if isEncrypted:
300 if isHex(chunk[:4]):
301 chunk = deHexString(chunk)
Justc2be3d92000-01-12 19:15:57 +0000302 decrypted, R = eexec.decrypt(chunk, 55665)
Just7842e561999-12-16 21:34:53 +0000303 decrypted = decrypted[4:]
304 if decrypted[-len(EEXECINTERNALEND)-1:-1] <> EEXECINTERNALEND \
305 and decrypted[-len(EEXECINTERNALEND)-2:-2] <> EEXECINTERNALEND:
jvre568dc72002-07-23 09:25:42 +0000306 raise T1Error, "invalid end of eexec part"
Just7842e561999-12-16 21:34:53 +0000307 decrypted = decrypted[:-len(EEXECINTERNALEND)-2] + '\r'
308 data.append(EEXECBEGINMARKER + decrypted + EEXECENDMARKER)
309 else:
310 if chunk[-len(EEXECBEGIN)-1:-1] == EEXECBEGIN:
311 data.append(chunk[:-len(EEXECBEGIN)-1])
312 else:
313 data.append(chunk)
314 return string.join(data, '')
315
Just5810aa92001-06-24 15:12:48 +0000316def findEncryptedChunks(data):
Just7842e561999-12-16 21:34:53 +0000317 chunks = []
318 while 1:
Just5810aa92001-06-24 15:12:48 +0000319 eBegin = string.find(data, EEXECBEGIN)
320 if eBegin < 0:
Just7842e561999-12-16 21:34:53 +0000321 break
jvr90290b72001-11-28 12:22:15 +0000322 eBegin = eBegin + len(EEXECBEGIN) + 1
Just5810aa92001-06-24 15:12:48 +0000323 eEnd = string.find(data, EEXECEND, eBegin)
324 if eEnd < 0:
jvre568dc72002-07-23 09:25:42 +0000325 raise T1Error, "can't find end of eexec part"
jvrdb1f2802002-07-23 14:54:47 +0000326 cypherText = data[eBegin:eEnd + 2]
327 plainText, R = eexec.decrypt(cypherText, 55665)
328 eEndLocal = string.find(plainText, EEXECINTERNALEND)
329 if eEndLocal < 0:
330 raise T1Error, "can't find end of eexec part"
331 eEnd = eBegin + eEndLocal + len(EEXECINTERNALEND) + 1
jvr90290b72001-11-28 12:22:15 +0000332 chunks.append((0, data[:eBegin]))
333 chunks.append((1, data[eBegin:eEnd]))
Just5810aa92001-06-24 15:12:48 +0000334 data = data[eEnd:]
Just7842e561999-12-16 21:34:53 +0000335 chunks.append((0, data))
336 return chunks
337
Just5810aa92001-06-24 15:12:48 +0000338def deHexString(hexstring):
Justc2be3d92000-01-12 19:15:57 +0000339 return eexec.deHexString(string.join(string.split(hexstring), ""))
Just7842e561999-12-16 21:34:53 +0000340
341
342# Type 1 assertion
343
344_fontType1RE = re.compile(r"/FontType\s+1\s+def")
345
Just5810aa92001-06-24 15:12:48 +0000346def assertType1(data):
Just7842e561999-12-16 21:34:53 +0000347 for head in ['%!PS-AdobeFont', '%!FontType1-1.0']:
348 if data[:len(head)] == head:
349 break
350 else:
jvre568dc72002-07-23 09:25:42 +0000351 raise T1Error, "not a PostScript font"
Just7842e561999-12-16 21:34:53 +0000352 if not _fontType1RE.search(data):
jvre568dc72002-07-23 09:25:42 +0000353 raise T1Error, "not a Type 1 font"
Just7842e561999-12-16 21:34:53 +0000354 if string.find(data, "currentfile eexec") < 0:
jvre568dc72002-07-23 09:25:42 +0000355 raise T1Error, "not an encrypted Type 1 font"
Just7842e561999-12-16 21:34:53 +0000356 # XXX what else?
357 return data
358
359
360# pfb helpers
361
Just5810aa92001-06-24 15:12:48 +0000362def longToString(long):
Just7842e561999-12-16 21:34:53 +0000363 str = ""
364 for i in range(4):
365 str = str + chr((long & (0xff << (i * 8))) >> i * 8)
366 return str
367
Just5810aa92001-06-24 15:12:48 +0000368def stringToLong(str):
Just7842e561999-12-16 21:34:53 +0000369 if len(str) <> 4:
370 raise ValueError, 'string must be 4 bytes long'
371 long = 0
372 for i in range(4):
373 long = long + (ord(str[i]) << (i * 8))
374 return long
Just5810aa92001-06-24 15:12:48 +0000375