blob: aa8400e6b67cbbb35a6ed67efc7dd5f6486c96d8 [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
66 def __getitem__(self, key):
67 if not hasattr(self, "font"):
68 self.parse()
Just36183002000-03-28 10:38:43 +000069 return self.font[key]
Just7842e561999-12-16 21:34:53 +000070
71 def parse(self):
Just528614e2000-01-16 22:14:02 +000072 from fontTools.misc import psLib
73 from fontTools.misc import psCharStrings
Just7842e561999-12-16 21:34:53 +000074 self.font = psLib.suckfont(self.data)
75 charStrings = self.font["CharStrings"]
76 lenIV = self.font["Private"].get("lenIV", 4)
77 assert lenIV >= 0
78 for glyphName, charString in charStrings.items():
Justc2be3d92000-01-12 19:15:57 +000079 charString, R = eexec.decrypt(charString, 4330)
Just7842e561999-12-16 21:34:53 +000080 charStrings[glyphName] = psCharStrings.T1CharString(charString[lenIV:])
81 subrs = self.font["Private"]["Subrs"]
82 for i in range(len(subrs)):
Justc2be3d92000-01-12 19:15:57 +000083 charString, R = eexec.decrypt(subrs[i], 4330)
Just7842e561999-12-16 21:34:53 +000084 subrs[i] = psCharStrings.T1CharString(charString[lenIV:])
85 del self.data
86
87
88
Just36183002000-03-28 10:38:43 +000089# low level T1 data read and write functions
Just7842e561999-12-16 21:34:53 +000090
91def read(path):
92 """reads any Type 1 font file, returns raw data"""
93 normpath = string.lower(path)
jvr22433b12002-07-12 19:20:19 +000094 if haveMacSupport:
jvrb19141e2003-06-07 15:15:51 +000095 creator, type = MacOS.GetCreatorAndType(path)
Just7842e561999-12-16 21:34:53 +000096 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]:
jvrda0d8052002-07-29 21:33:46 +0000146 if onlyHeader and code == 2:
147 break
jvr05a16f22002-07-29 21:39:06 +0000148 data.append(res.data[2:])
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:
jvrb19141e2003-06-07 15:15:51 +0000245 MacOS.SetCreatorAndType(path, 'mdos', 'BINA')
Just7842e561999-12-16 21:34:53 +0000246
Just5810aa92001-06-24 15:12:48 +0000247def writeOther(path, data, dohex = 0):
248 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000249 f = open(path, "wb")
250 try:
251 hexlinelen = HEXLINELENGTH / 2
Just5810aa92001-06-24 15:12:48 +0000252 for isEncrypted, chunk in chunks:
253 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000254 code = 2
255 else:
256 code = 1
257 if code == 2 and dohex:
258 while chunk:
Justc2be3d92000-01-12 19:15:57 +0000259 f.write(eexec.hexString(chunk[:hexlinelen]))
Just7842e561999-12-16 21:34:53 +0000260 f.write('\r')
261 chunk = chunk[hexlinelen:]
262 else:
263 f.write(chunk)
264 finally:
265 f.close()
jvr22433b12002-07-12 19:20:19 +0000266 if haveMacSupport:
jvrb19141e2003-06-07 15:15:51 +0000267 MacOS.SetCreatorAndType(path, 'R*ch', 'TEXT') # BBEdit text file
Just7842e561999-12-16 21:34:53 +0000268
269
270# decryption tools
271
272EEXECBEGIN = "currentfile eexec"
273EEXECEND = '0' * 64
274EEXECINTERNALEND = "currentfile closefile"
275EEXECBEGINMARKER = "%-- eexec start\r"
276EEXECENDMARKER = "%-- eexec end\r"
277
278_ishexRE = re.compile('[0-9A-Fa-f]*$')
279
Just5810aa92001-06-24 15:12:48 +0000280def isHex(text):
Just7842e561999-12-16 21:34:53 +0000281 return _ishexRE.match(text) is not None
282
283
Just5810aa92001-06-24 15:12:48 +0000284def decryptType1(data):
285 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000286 data = []
Just5810aa92001-06-24 15:12:48 +0000287 for isEncrypted, chunk in chunks:
288 if isEncrypted:
289 if isHex(chunk[:4]):
290 chunk = deHexString(chunk)
Justc2be3d92000-01-12 19:15:57 +0000291 decrypted, R = eexec.decrypt(chunk, 55665)
Just7842e561999-12-16 21:34:53 +0000292 decrypted = decrypted[4:]
293 if decrypted[-len(EEXECINTERNALEND)-1:-1] <> EEXECINTERNALEND \
294 and decrypted[-len(EEXECINTERNALEND)-2:-2] <> EEXECINTERNALEND:
jvre568dc72002-07-23 09:25:42 +0000295 raise T1Error, "invalid end of eexec part"
Just7842e561999-12-16 21:34:53 +0000296 decrypted = decrypted[:-len(EEXECINTERNALEND)-2] + '\r'
297 data.append(EEXECBEGINMARKER + decrypted + EEXECENDMARKER)
298 else:
299 if chunk[-len(EEXECBEGIN)-1:-1] == EEXECBEGIN:
300 data.append(chunk[:-len(EEXECBEGIN)-1])
301 else:
302 data.append(chunk)
303 return string.join(data, '')
304
Just5810aa92001-06-24 15:12:48 +0000305def findEncryptedChunks(data):
Just7842e561999-12-16 21:34:53 +0000306 chunks = []
307 while 1:
Just5810aa92001-06-24 15:12:48 +0000308 eBegin = string.find(data, EEXECBEGIN)
309 if eBegin < 0:
Just7842e561999-12-16 21:34:53 +0000310 break
jvr90290b72001-11-28 12:22:15 +0000311 eBegin = eBegin + len(EEXECBEGIN) + 1
Just5810aa92001-06-24 15:12:48 +0000312 eEnd = string.find(data, EEXECEND, eBegin)
313 if eEnd < 0:
jvre568dc72002-07-23 09:25:42 +0000314 raise T1Error, "can't find end of eexec part"
jvrdb1f2802002-07-23 14:54:47 +0000315 cypherText = data[eBegin:eEnd + 2]
316 plainText, R = eexec.decrypt(cypherText, 55665)
317 eEndLocal = string.find(plainText, EEXECINTERNALEND)
318 if eEndLocal < 0:
319 raise T1Error, "can't find end of eexec part"
320 eEnd = eBegin + eEndLocal + len(EEXECINTERNALEND) + 1
jvr90290b72001-11-28 12:22:15 +0000321 chunks.append((0, data[:eBegin]))
322 chunks.append((1, data[eBegin:eEnd]))
Just5810aa92001-06-24 15:12:48 +0000323 data = data[eEnd:]
Just7842e561999-12-16 21:34:53 +0000324 chunks.append((0, data))
325 return chunks
326
Just5810aa92001-06-24 15:12:48 +0000327def deHexString(hexstring):
Justc2be3d92000-01-12 19:15:57 +0000328 return eexec.deHexString(string.join(string.split(hexstring), ""))
Just7842e561999-12-16 21:34:53 +0000329
330
331# Type 1 assertion
332
333_fontType1RE = re.compile(r"/FontType\s+1\s+def")
334
Just5810aa92001-06-24 15:12:48 +0000335def assertType1(data):
Just7842e561999-12-16 21:34:53 +0000336 for head in ['%!PS-AdobeFont', '%!FontType1-1.0']:
337 if data[:len(head)] == head:
338 break
339 else:
jvre568dc72002-07-23 09:25:42 +0000340 raise T1Error, "not a PostScript font"
Just7842e561999-12-16 21:34:53 +0000341 if not _fontType1RE.search(data):
jvre568dc72002-07-23 09:25:42 +0000342 raise T1Error, "not a Type 1 font"
Just7842e561999-12-16 21:34:53 +0000343 if string.find(data, "currentfile eexec") < 0:
jvre568dc72002-07-23 09:25:42 +0000344 raise T1Error, "not an encrypted Type 1 font"
Just7842e561999-12-16 21:34:53 +0000345 # XXX what else?
346 return data
347
348
349# pfb helpers
350
Just5810aa92001-06-24 15:12:48 +0000351def longToString(long):
Just7842e561999-12-16 21:34:53 +0000352 str = ""
353 for i in range(4):
354 str = str + chr((long & (0xff << (i * 8))) >> i * 8)
355 return str
356
Just5810aa92001-06-24 15:12:48 +0000357def stringToLong(str):
Just7842e561999-12-16 21:34:53 +0000358 if len(str) <> 4:
359 raise ValueError, 'string must be 4 bytes long'
360 long = 0
361 for i in range(4):
362 long = long + (ord(str[i]) << (i * 8))
363 return long
Just5810aa92001-06-24 15:12:48 +0000364