blob: 6e9ab8b858e9ed9252935945f49c5bd5667f8809 [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
Just7842e561999-12-16 21:34:53 +000038 import macfs
39
jvre568dc72002-07-23 09:25:42 +000040class T1Error(Exception): pass
Just7842e561999-12-16 21:34:53 +000041
Just7842e561999-12-16 21:34:53 +000042
43class T1Font:
44
Just36183002000-03-28 10:38:43 +000045 """Type 1 font class.
46
47 Uses a minimal interpeter that supports just about enough PS to parse
48 Type 1 fonts.
Just7842e561999-12-16 21:34:53 +000049 """
50
51 def __init__(self, path=None):
52 if path is not None:
53 self.data, type = read(path)
54 else:
55 pass # XXX
56
57 def saveAs(self, path, type):
jvr8c74f462001-08-16 10:34:22 +000058 write(path, self.getData(), type)
Just7842e561999-12-16 21:34:53 +000059
60 def getData(self):
Just36183002000-03-28 10:38:43 +000061 # XXX Todo: if the data has been converted to Python object,
62 # recreate the PS stream
Just7842e561999-12-16 21:34:53 +000063 return self.data
64
65 def __getitem__(self, key):
66 if not hasattr(self, "font"):
67 self.parse()
Just36183002000-03-28 10:38:43 +000068 return self.font[key]
Just7842e561999-12-16 21:34:53 +000069
70 def parse(self):
Just528614e2000-01-16 22:14:02 +000071 from fontTools.misc import psLib
72 from fontTools.misc import psCharStrings
Just7842e561999-12-16 21:34:53 +000073 self.font = psLib.suckfont(self.data)
74 charStrings = self.font["CharStrings"]
75 lenIV = self.font["Private"].get("lenIV", 4)
76 assert lenIV >= 0
77 for glyphName, charString in charStrings.items():
Justc2be3d92000-01-12 19:15:57 +000078 charString, R = eexec.decrypt(charString, 4330)
Just7842e561999-12-16 21:34:53 +000079 charStrings[glyphName] = psCharStrings.T1CharString(charString[lenIV:])
80 subrs = self.font["Private"]["Subrs"]
81 for i in range(len(subrs)):
Justc2be3d92000-01-12 19:15:57 +000082 charString, R = eexec.decrypt(subrs[i], 4330)
Just7842e561999-12-16 21:34:53 +000083 subrs[i] = psCharStrings.T1CharString(charString[lenIV:])
84 del self.data
85
86
87
Just36183002000-03-28 10:38:43 +000088# low level T1 data read and write functions
Just7842e561999-12-16 21:34:53 +000089
90def read(path):
91 """reads any Type 1 font file, returns raw data"""
92 normpath = string.lower(path)
jvr22433b12002-07-12 19:20:19 +000093 if haveMacSupport:
Just7842e561999-12-16 21:34:53 +000094 fss = macfs.FSSpec(path)
95 creator, type = fss.GetCreatorType()
96 if type == 'LWFN':
Just5810aa92001-06-24 15:12:48 +000097 return readLWFN(path), 'LWFN'
Just7842e561999-12-16 21:34:53 +000098 if normpath[-4:] == '.pfb':
Just5810aa92001-06-24 15:12:48 +000099 return readPFB(path), 'PFB'
Just7842e561999-12-16 21:34:53 +0000100 else:
Just5810aa92001-06-24 15:12:48 +0000101 return readOther(path), 'OTHER'
Just7842e561999-12-16 21:34:53 +0000102
103def write(path, data, kind='OTHER', dohex=0):
Just5810aa92001-06-24 15:12:48 +0000104 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000105 kind = string.upper(kind)
106 try:
107 os.remove(path)
108 except os.error:
109 pass
110 err = 1
111 try:
112 if kind == 'LWFN':
Just5810aa92001-06-24 15:12:48 +0000113 writeLWFN(path, data)
Just7842e561999-12-16 21:34:53 +0000114 elif kind == 'PFB':
Just5810aa92001-06-24 15:12:48 +0000115 writePFB(path, data)
Just7842e561999-12-16 21:34:53 +0000116 else:
Just5810aa92001-06-24 15:12:48 +0000117 writeOther(path, data, dohex)
Just7842e561999-12-16 21:34:53 +0000118 err = 0
119 finally:
120 if err and not DEBUG:
121 try:
122 os.remove(path)
123 except os.error:
124 pass
125
126
127# -- internal --
128
129LWFNCHUNKSIZE = 2000
130HEXLINELENGTH = 80
131
132
jvrda0d8052002-07-29 21:33:46 +0000133def readLWFN(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000134 """reads an LWFN font file, returns raw data"""
Juste9601bf2001-07-30 19:04:40 +0000135 resRef = Res.FSpOpenResFile(path, 1) # read-only
Just7842e561999-12-16 21:34:53 +0000136 try:
Juste9601bf2001-07-30 19:04:40 +0000137 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000138 n = Res.Count1Resources('POST')
139 data = []
140 for i in range(501, 501 + n):
141 res = Res.Get1Resource('POST', i)
142 code = ord(res.data[0])
143 if ord(res.data[1]) <> 0:
jvre568dc72002-07-23 09:25:42 +0000144 raise T1Error, 'corrupt LWFN file'
Just7842e561999-12-16 21:34:53 +0000145 if code in [1, 2]:
146 data.append(res.data[2:])
jvrda0d8052002-07-29 21:33:46 +0000147 if onlyHeader and code == 2:
148 break
Just7842e561999-12-16 21:34:53 +0000149 elif code in [3, 5]:
150 break
151 elif code == 4:
152 f = open(path, "rb")
153 data.append(f.read())
154 f.close()
155 elif code == 0:
156 pass # comment, ignore
157 else:
jvre568dc72002-07-23 09:25:42 +0000158 raise T1Error, 'bad chunk code: ' + `code`
Just7842e561999-12-16 21:34:53 +0000159 finally:
Juste9601bf2001-07-30 19:04:40 +0000160 Res.CloseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000161 data = string.join(data, '')
Just5810aa92001-06-24 15:12:48 +0000162 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000163 return data
164
Just5810aa92001-06-24 15:12:48 +0000165def readPFB(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000166 """reads a PFB font file, returns raw data"""
167 f = open(path, "rb")
168 data = []
169 while 1:
170 if f.read(1) <> chr(128):
jvre568dc72002-07-23 09:25:42 +0000171 raise T1Error, 'corrupt PFB file'
Just7842e561999-12-16 21:34:53 +0000172 code = ord(f.read(1))
173 if code in [1, 2]:
Just5810aa92001-06-24 15:12:48 +0000174 chunklen = stringToLong(f.read(4))
Just36183002000-03-28 10:38:43 +0000175 chunk = f.read(chunklen)
176 assert len(chunk) == chunklen
177 data.append(chunk)
Just7842e561999-12-16 21:34:53 +0000178 elif code == 3:
179 break
180 else:
jvre568dc72002-07-23 09:25:42 +0000181 raise T1Error, 'bad chunk code: ' + `code`
Just5810aa92001-06-24 15:12:48 +0000182 if onlyHeader:
183 break
Just7842e561999-12-16 21:34:53 +0000184 f.close()
185 data = string.join(data, '')
Just5810aa92001-06-24 15:12:48 +0000186 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000187 return data
188
Just5810aa92001-06-24 15:12:48 +0000189def readOther(path):
Just7842e561999-12-16 21:34:53 +0000190 """reads any (font) file, returns raw data"""
191 f = open(path, "rb")
192 data = f.read()
193 f.close()
Just5810aa92001-06-24 15:12:48 +0000194 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000195
Just5810aa92001-06-24 15:12:48 +0000196 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000197 data = []
Just5810aa92001-06-24 15:12:48 +0000198 for isEncrypted, chunk in chunks:
199 if isEncrypted and isHex(chunk[:4]):
200 data.append(deHexString(chunk))
Just7842e561999-12-16 21:34:53 +0000201 else:
202 data.append(chunk)
203 return string.join(data, '')
204
205# file writing tools
206
Just5810aa92001-06-24 15:12:48 +0000207def writeLWFN(path, data):
Juste9601bf2001-07-30 19:04:40 +0000208 Res.FSpCreateResFile(path, "just", "LWFN", 0)
209 resRef = Res.FSpOpenResFile(path, 2) # write-only
Just7842e561999-12-16 21:34:53 +0000210 try:
Juste9601bf2001-07-30 19:04:40 +0000211 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000212 resID = 501
Just5810aa92001-06-24 15:12:48 +0000213 chunks = findEncryptedChunks(data)
214 for isEncrypted, chunk in chunks:
215 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000216 code = 2
217 else:
218 code = 1
219 while chunk:
220 res = Res.Resource(chr(code) + '\0' + chunk[:LWFNCHUNKSIZE - 2])
221 res.AddResource('POST', resID, '')
222 chunk = chunk[LWFNCHUNKSIZE - 2:]
223 resID = resID + 1
224 res = Res.Resource(chr(5) + '\0')
225 res.AddResource('POST', resID, '')
226 finally:
Juste9601bf2001-07-30 19:04:40 +0000227 Res.CloseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000228
Just5810aa92001-06-24 15:12:48 +0000229def writePFB(path, data):
230 chunks = findEncryptedChunks(data)
Just36183002000-03-28 10:38:43 +0000231 f = open(path, "wb")
Just7842e561999-12-16 21:34:53 +0000232 try:
Just5810aa92001-06-24 15:12:48 +0000233 for isEncrypted, chunk in chunks:
234 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000235 code = 2
236 else:
237 code = 1
238 f.write(chr(128) + chr(code))
Just5810aa92001-06-24 15:12:48 +0000239 f.write(longToString(len(chunk)))
Just7842e561999-12-16 21:34:53 +0000240 f.write(chunk)
241 f.write(chr(128) + chr(3))
242 finally:
243 f.close()
jvr22433b12002-07-12 19:20:19 +0000244 if haveMacSupport:
Just36183002000-03-28 10:38:43 +0000245 fss = macfs.FSSpec(path)
Just7842e561999-12-16 21:34:53 +0000246 fss.SetCreatorType('mdos', 'BINA')
247
Just5810aa92001-06-24 15:12:48 +0000248def writeOther(path, data, dohex = 0):
249 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000250 f = open(path, "wb")
251 try:
252 hexlinelen = HEXLINELENGTH / 2
Just5810aa92001-06-24 15:12:48 +0000253 for isEncrypted, chunk in chunks:
254 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000255 code = 2
256 else:
257 code = 1
258 if code == 2 and dohex:
259 while chunk:
Justc2be3d92000-01-12 19:15:57 +0000260 f.write(eexec.hexString(chunk[:hexlinelen]))
Just7842e561999-12-16 21:34:53 +0000261 f.write('\r')
262 chunk = chunk[hexlinelen:]
263 else:
264 f.write(chunk)
265 finally:
266 f.close()
jvr22433b12002-07-12 19:20:19 +0000267 if haveMacSupport:
Just7842e561999-12-16 21:34:53 +0000268 fss = macfs.FSSpec(path)
269 fss.SetCreatorType('R*ch', 'TEXT') # BBEdit text file
270
271
272# decryption tools
273
274EEXECBEGIN = "currentfile eexec"
275EEXECEND = '0' * 64
276EEXECINTERNALEND = "currentfile closefile"
277EEXECBEGINMARKER = "%-- eexec start\r"
278EEXECENDMARKER = "%-- eexec end\r"
279
280_ishexRE = re.compile('[0-9A-Fa-f]*$')
281
Just5810aa92001-06-24 15:12:48 +0000282def isHex(text):
Just7842e561999-12-16 21:34:53 +0000283 return _ishexRE.match(text) is not None
284
285
Just5810aa92001-06-24 15:12:48 +0000286def decryptType1(data):
287 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000288 data = []
Just5810aa92001-06-24 15:12:48 +0000289 for isEncrypted, chunk in chunks:
290 if isEncrypted:
291 if isHex(chunk[:4]):
292 chunk = deHexString(chunk)
Justc2be3d92000-01-12 19:15:57 +0000293 decrypted, R = eexec.decrypt(chunk, 55665)
Just7842e561999-12-16 21:34:53 +0000294 decrypted = decrypted[4:]
295 if decrypted[-len(EEXECINTERNALEND)-1:-1] <> EEXECINTERNALEND \
296 and decrypted[-len(EEXECINTERNALEND)-2:-2] <> EEXECINTERNALEND:
jvre568dc72002-07-23 09:25:42 +0000297 raise T1Error, "invalid end of eexec part"
Just7842e561999-12-16 21:34:53 +0000298 decrypted = decrypted[:-len(EEXECINTERNALEND)-2] + '\r'
299 data.append(EEXECBEGINMARKER + decrypted + EEXECENDMARKER)
300 else:
301 if chunk[-len(EEXECBEGIN)-1:-1] == EEXECBEGIN:
302 data.append(chunk[:-len(EEXECBEGIN)-1])
303 else:
304 data.append(chunk)
305 return string.join(data, '')
306
Just5810aa92001-06-24 15:12:48 +0000307def findEncryptedChunks(data):
Just7842e561999-12-16 21:34:53 +0000308 chunks = []
309 while 1:
Just5810aa92001-06-24 15:12:48 +0000310 eBegin = string.find(data, EEXECBEGIN)
311 if eBegin < 0:
Just7842e561999-12-16 21:34:53 +0000312 break
jvr90290b72001-11-28 12:22:15 +0000313 eBegin = eBegin + len(EEXECBEGIN) + 1
Just5810aa92001-06-24 15:12:48 +0000314 eEnd = string.find(data, EEXECEND, eBegin)
315 if eEnd < 0:
jvre568dc72002-07-23 09:25:42 +0000316 raise T1Error, "can't find end of eexec part"
jvrdb1f2802002-07-23 14:54:47 +0000317 cypherText = data[eBegin:eEnd + 2]
318 plainText, R = eexec.decrypt(cypherText, 55665)
319 eEndLocal = string.find(plainText, EEXECINTERNALEND)
320 if eEndLocal < 0:
321 raise T1Error, "can't find end of eexec part"
322 eEnd = eBegin + eEndLocal + len(EEXECINTERNALEND) + 1
jvr90290b72001-11-28 12:22:15 +0000323 chunks.append((0, data[:eBegin]))
324 chunks.append((1, data[eBegin:eEnd]))
Just5810aa92001-06-24 15:12:48 +0000325 data = data[eEnd:]
Just7842e561999-12-16 21:34:53 +0000326 chunks.append((0, data))
327 return chunks
328
Just5810aa92001-06-24 15:12:48 +0000329def deHexString(hexstring):
Justc2be3d92000-01-12 19:15:57 +0000330 return eexec.deHexString(string.join(string.split(hexstring), ""))
Just7842e561999-12-16 21:34:53 +0000331
332
333# Type 1 assertion
334
335_fontType1RE = re.compile(r"/FontType\s+1\s+def")
336
Just5810aa92001-06-24 15:12:48 +0000337def assertType1(data):
Just7842e561999-12-16 21:34:53 +0000338 for head in ['%!PS-AdobeFont', '%!FontType1-1.0']:
339 if data[:len(head)] == head:
340 break
341 else:
jvre568dc72002-07-23 09:25:42 +0000342 raise T1Error, "not a PostScript font"
Just7842e561999-12-16 21:34:53 +0000343 if not _fontType1RE.search(data):
jvre568dc72002-07-23 09:25:42 +0000344 raise T1Error, "not a Type 1 font"
Just7842e561999-12-16 21:34:53 +0000345 if string.find(data, "currentfile eexec") < 0:
jvre568dc72002-07-23 09:25:42 +0000346 raise T1Error, "not an encrypted Type 1 font"
Just7842e561999-12-16 21:34:53 +0000347 # XXX what else?
348 return data
349
350
351# pfb helpers
352
Just5810aa92001-06-24 15:12:48 +0000353def longToString(long):
Just7842e561999-12-16 21:34:53 +0000354 str = ""
355 for i in range(4):
356 str = str + chr((long & (0xff << (i * 8))) >> i * 8)
357 return str
358
Just5810aa92001-06-24 15:12:48 +0000359def stringToLong(str):
Just7842e561999-12-16 21:34:53 +0000360 if len(str) <> 4:
361 raise ValueError, 'string must be 4 bytes long'
362 long = 0
363 for i in range(4):
364 long = long + (ord(str[i]) << (i * 8))
365 return long
Just5810aa92001-06-24 15:12:48 +0000366