blob: 2dcd0538182667132928feb9410302a022ac85c2 [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
jvr59afba72003-05-24 12:34:11 +000038 try:
39 from Carbon.File import FSSpec
40 except ImportError:
41 from macfs import FSSpec # MacPython < 2.2
42
Just7842e561999-12-16 21:34:53 +000043
jvre568dc72002-07-23 09:25:42 +000044class T1Error(Exception): pass
Just7842e561999-12-16 21:34:53 +000045
Just7842e561999-12-16 21:34:53 +000046
47class T1Font:
48
Just36183002000-03-28 10:38:43 +000049 """Type 1 font class.
50
51 Uses a minimal interpeter that supports just about enough PS to parse
52 Type 1 fonts.
Just7842e561999-12-16 21:34:53 +000053 """
54
55 def __init__(self, path=None):
56 if path is not None:
57 self.data, type = read(path)
58 else:
59 pass # XXX
60
61 def saveAs(self, path, type):
jvr8c74f462001-08-16 10:34:22 +000062 write(path, self.getData(), type)
Just7842e561999-12-16 21:34:53 +000063
64 def getData(self):
Just36183002000-03-28 10:38:43 +000065 # XXX Todo: if the data has been converted to Python object,
66 # recreate the PS stream
Just7842e561999-12-16 21:34:53 +000067 return self.data
68
69 def __getitem__(self, key):
70 if not hasattr(self, "font"):
71 self.parse()
Just36183002000-03-28 10:38:43 +000072 return self.font[key]
Just7842e561999-12-16 21:34:53 +000073
74 def parse(self):
Just528614e2000-01-16 22:14:02 +000075 from fontTools.misc import psLib
76 from fontTools.misc import psCharStrings
Just7842e561999-12-16 21:34:53 +000077 self.font = psLib.suckfont(self.data)
78 charStrings = self.font["CharStrings"]
79 lenIV = self.font["Private"].get("lenIV", 4)
80 assert lenIV >= 0
81 for glyphName, charString in charStrings.items():
Justc2be3d92000-01-12 19:15:57 +000082 charString, R = eexec.decrypt(charString, 4330)
Just7842e561999-12-16 21:34:53 +000083 charStrings[glyphName] = psCharStrings.T1CharString(charString[lenIV:])
84 subrs = self.font["Private"]["Subrs"]
85 for i in range(len(subrs)):
Justc2be3d92000-01-12 19:15:57 +000086 charString, R = eexec.decrypt(subrs[i], 4330)
Just7842e561999-12-16 21:34:53 +000087 subrs[i] = psCharStrings.T1CharString(charString[lenIV:])
88 del self.data
89
90
91
Just36183002000-03-28 10:38:43 +000092# low level T1 data read and write functions
Just7842e561999-12-16 21:34:53 +000093
94def read(path):
95 """reads any Type 1 font file, returns raw data"""
96 normpath = string.lower(path)
jvr22433b12002-07-12 19:20:19 +000097 if haveMacSupport:
jvr59afba72003-05-24 12:34:11 +000098 fss = FSSpec(path)
Just7842e561999-12-16 21:34:53 +000099 creator, type = fss.GetCreatorType()
100 if type == 'LWFN':
Just5810aa92001-06-24 15:12:48 +0000101 return readLWFN(path), 'LWFN'
Just7842e561999-12-16 21:34:53 +0000102 if normpath[-4:] == '.pfb':
Just5810aa92001-06-24 15:12:48 +0000103 return readPFB(path), 'PFB'
Just7842e561999-12-16 21:34:53 +0000104 else:
Just5810aa92001-06-24 15:12:48 +0000105 return readOther(path), 'OTHER'
Just7842e561999-12-16 21:34:53 +0000106
107def write(path, data, kind='OTHER', dohex=0):
Just5810aa92001-06-24 15:12:48 +0000108 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000109 kind = string.upper(kind)
110 try:
111 os.remove(path)
112 except os.error:
113 pass
114 err = 1
115 try:
116 if kind == 'LWFN':
Just5810aa92001-06-24 15:12:48 +0000117 writeLWFN(path, data)
Just7842e561999-12-16 21:34:53 +0000118 elif kind == 'PFB':
Just5810aa92001-06-24 15:12:48 +0000119 writePFB(path, data)
Just7842e561999-12-16 21:34:53 +0000120 else:
Just5810aa92001-06-24 15:12:48 +0000121 writeOther(path, data, dohex)
Just7842e561999-12-16 21:34:53 +0000122 err = 0
123 finally:
124 if err and not DEBUG:
125 try:
126 os.remove(path)
127 except os.error:
128 pass
129
130
131# -- internal --
132
133LWFNCHUNKSIZE = 2000
134HEXLINELENGTH = 80
135
136
jvrda0d8052002-07-29 21:33:46 +0000137def readLWFN(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000138 """reads an LWFN font file, returns raw data"""
Juste9601bf2001-07-30 19:04:40 +0000139 resRef = Res.FSpOpenResFile(path, 1) # read-only
Just7842e561999-12-16 21:34:53 +0000140 try:
Juste9601bf2001-07-30 19:04:40 +0000141 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000142 n = Res.Count1Resources('POST')
143 data = []
144 for i in range(501, 501 + n):
145 res = Res.Get1Resource('POST', i)
146 code = ord(res.data[0])
147 if ord(res.data[1]) <> 0:
jvre568dc72002-07-23 09:25:42 +0000148 raise T1Error, 'corrupt LWFN file'
Just7842e561999-12-16 21:34:53 +0000149 if code in [1, 2]:
jvrda0d8052002-07-29 21:33:46 +0000150 if onlyHeader and code == 2:
151 break
jvr05a16f22002-07-29 21:39:06 +0000152 data.append(res.data[2:])
Just7842e561999-12-16 21:34:53 +0000153 elif code in [3, 5]:
154 break
155 elif code == 4:
156 f = open(path, "rb")
157 data.append(f.read())
158 f.close()
159 elif code == 0:
160 pass # comment, ignore
161 else:
jvre568dc72002-07-23 09:25:42 +0000162 raise T1Error, 'bad chunk code: ' + `code`
Just7842e561999-12-16 21:34:53 +0000163 finally:
Juste9601bf2001-07-30 19:04:40 +0000164 Res.CloseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000165 data = string.join(data, '')
Just5810aa92001-06-24 15:12:48 +0000166 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000167 return data
168
Just5810aa92001-06-24 15:12:48 +0000169def readPFB(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000170 """reads a PFB font file, returns raw data"""
171 f = open(path, "rb")
172 data = []
173 while 1:
174 if f.read(1) <> chr(128):
jvre568dc72002-07-23 09:25:42 +0000175 raise T1Error, 'corrupt PFB file'
Just7842e561999-12-16 21:34:53 +0000176 code = ord(f.read(1))
177 if code in [1, 2]:
Just5810aa92001-06-24 15:12:48 +0000178 chunklen = stringToLong(f.read(4))
Just36183002000-03-28 10:38:43 +0000179 chunk = f.read(chunklen)
180 assert len(chunk) == chunklen
181 data.append(chunk)
Just7842e561999-12-16 21:34:53 +0000182 elif code == 3:
183 break
184 else:
jvre568dc72002-07-23 09:25:42 +0000185 raise T1Error, 'bad chunk code: ' + `code`
Just5810aa92001-06-24 15:12:48 +0000186 if onlyHeader:
187 break
Just7842e561999-12-16 21:34:53 +0000188 f.close()
189 data = string.join(data, '')
Just5810aa92001-06-24 15:12:48 +0000190 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000191 return data
192
Just5810aa92001-06-24 15:12:48 +0000193def readOther(path):
Just7842e561999-12-16 21:34:53 +0000194 """reads any (font) file, returns raw data"""
195 f = open(path, "rb")
196 data = f.read()
197 f.close()
Just5810aa92001-06-24 15:12:48 +0000198 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000199
Just5810aa92001-06-24 15:12:48 +0000200 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000201 data = []
Just5810aa92001-06-24 15:12:48 +0000202 for isEncrypted, chunk in chunks:
203 if isEncrypted and isHex(chunk[:4]):
204 data.append(deHexString(chunk))
Just7842e561999-12-16 21:34:53 +0000205 else:
206 data.append(chunk)
207 return string.join(data, '')
208
209# file writing tools
210
Just5810aa92001-06-24 15:12:48 +0000211def writeLWFN(path, data):
Juste9601bf2001-07-30 19:04:40 +0000212 Res.FSpCreateResFile(path, "just", "LWFN", 0)
213 resRef = Res.FSpOpenResFile(path, 2) # write-only
Just7842e561999-12-16 21:34:53 +0000214 try:
Juste9601bf2001-07-30 19:04:40 +0000215 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000216 resID = 501
Just5810aa92001-06-24 15:12:48 +0000217 chunks = findEncryptedChunks(data)
218 for isEncrypted, chunk in chunks:
219 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000220 code = 2
221 else:
222 code = 1
223 while chunk:
224 res = Res.Resource(chr(code) + '\0' + chunk[:LWFNCHUNKSIZE - 2])
225 res.AddResource('POST', resID, '')
226 chunk = chunk[LWFNCHUNKSIZE - 2:]
227 resID = resID + 1
228 res = Res.Resource(chr(5) + '\0')
229 res.AddResource('POST', resID, '')
230 finally:
Juste9601bf2001-07-30 19:04:40 +0000231 Res.CloseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000232
Just5810aa92001-06-24 15:12:48 +0000233def writePFB(path, data):
234 chunks = findEncryptedChunks(data)
Just36183002000-03-28 10:38:43 +0000235 f = open(path, "wb")
Just7842e561999-12-16 21:34:53 +0000236 try:
Just5810aa92001-06-24 15:12:48 +0000237 for isEncrypted, chunk in chunks:
238 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000239 code = 2
240 else:
241 code = 1
242 f.write(chr(128) + chr(code))
Just5810aa92001-06-24 15:12:48 +0000243 f.write(longToString(len(chunk)))
Just7842e561999-12-16 21:34:53 +0000244 f.write(chunk)
245 f.write(chr(128) + chr(3))
246 finally:
247 f.close()
jvr22433b12002-07-12 19:20:19 +0000248 if haveMacSupport:
jvr59afba72003-05-24 12:34:11 +0000249 fss = FSSpec(path)
Just7842e561999-12-16 21:34:53 +0000250 fss.SetCreatorType('mdos', 'BINA')
251
Just5810aa92001-06-24 15:12:48 +0000252def writeOther(path, data, dohex = 0):
253 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000254 f = open(path, "wb")
255 try:
256 hexlinelen = HEXLINELENGTH / 2
Just5810aa92001-06-24 15:12:48 +0000257 for isEncrypted, chunk in chunks:
258 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000259 code = 2
260 else:
261 code = 1
262 if code == 2 and dohex:
263 while chunk:
Justc2be3d92000-01-12 19:15:57 +0000264 f.write(eexec.hexString(chunk[:hexlinelen]))
Just7842e561999-12-16 21:34:53 +0000265 f.write('\r')
266 chunk = chunk[hexlinelen:]
267 else:
268 f.write(chunk)
269 finally:
270 f.close()
jvr22433b12002-07-12 19:20:19 +0000271 if haveMacSupport:
jvr59afba72003-05-24 12:34:11 +0000272 fss = FSSpec(path)
Just7842e561999-12-16 21:34:53 +0000273 fss.SetCreatorType('R*ch', 'TEXT') # BBEdit text file
274
275
276# decryption tools
277
278EEXECBEGIN = "currentfile eexec"
279EEXECEND = '0' * 64
280EEXECINTERNALEND = "currentfile closefile"
281EEXECBEGINMARKER = "%-- eexec start\r"
282EEXECENDMARKER = "%-- eexec end\r"
283
284_ishexRE = re.compile('[0-9A-Fa-f]*$')
285
Just5810aa92001-06-24 15:12:48 +0000286def isHex(text):
Just7842e561999-12-16 21:34:53 +0000287 return _ishexRE.match(text) is not None
288
289
Just5810aa92001-06-24 15:12:48 +0000290def decryptType1(data):
291 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000292 data = []
Just5810aa92001-06-24 15:12:48 +0000293 for isEncrypted, chunk in chunks:
294 if isEncrypted:
295 if isHex(chunk[:4]):
296 chunk = deHexString(chunk)
Justc2be3d92000-01-12 19:15:57 +0000297 decrypted, R = eexec.decrypt(chunk, 55665)
Just7842e561999-12-16 21:34:53 +0000298 decrypted = decrypted[4:]
299 if decrypted[-len(EEXECINTERNALEND)-1:-1] <> EEXECINTERNALEND \
300 and decrypted[-len(EEXECINTERNALEND)-2:-2] <> EEXECINTERNALEND:
jvre568dc72002-07-23 09:25:42 +0000301 raise T1Error, "invalid end of eexec part"
Just7842e561999-12-16 21:34:53 +0000302 decrypted = decrypted[:-len(EEXECINTERNALEND)-2] + '\r'
303 data.append(EEXECBEGINMARKER + decrypted + EEXECENDMARKER)
304 else:
305 if chunk[-len(EEXECBEGIN)-1:-1] == EEXECBEGIN:
306 data.append(chunk[:-len(EEXECBEGIN)-1])
307 else:
308 data.append(chunk)
309 return string.join(data, '')
310
Just5810aa92001-06-24 15:12:48 +0000311def findEncryptedChunks(data):
Just7842e561999-12-16 21:34:53 +0000312 chunks = []
313 while 1:
Just5810aa92001-06-24 15:12:48 +0000314 eBegin = string.find(data, EEXECBEGIN)
315 if eBegin < 0:
Just7842e561999-12-16 21:34:53 +0000316 break
jvr90290b72001-11-28 12:22:15 +0000317 eBegin = eBegin + len(EEXECBEGIN) + 1
Just5810aa92001-06-24 15:12:48 +0000318 eEnd = string.find(data, EEXECEND, eBegin)
319 if eEnd < 0:
jvre568dc72002-07-23 09:25:42 +0000320 raise T1Error, "can't find end of eexec part"
jvrdb1f2802002-07-23 14:54:47 +0000321 cypherText = data[eBegin:eEnd + 2]
322 plainText, R = eexec.decrypt(cypherText, 55665)
323 eEndLocal = string.find(plainText, EEXECINTERNALEND)
324 if eEndLocal < 0:
325 raise T1Error, "can't find end of eexec part"
326 eEnd = eBegin + eEndLocal + len(EEXECINTERNALEND) + 1
jvr90290b72001-11-28 12:22:15 +0000327 chunks.append((0, data[:eBegin]))
328 chunks.append((1, data[eBegin:eEnd]))
Just5810aa92001-06-24 15:12:48 +0000329 data = data[eEnd:]
Just7842e561999-12-16 21:34:53 +0000330 chunks.append((0, data))
331 return chunks
332
Just5810aa92001-06-24 15:12:48 +0000333def deHexString(hexstring):
Justc2be3d92000-01-12 19:15:57 +0000334 return eexec.deHexString(string.join(string.split(hexstring), ""))
Just7842e561999-12-16 21:34:53 +0000335
336
337# Type 1 assertion
338
339_fontType1RE = re.compile(r"/FontType\s+1\s+def")
340
Just5810aa92001-06-24 15:12:48 +0000341def assertType1(data):
Just7842e561999-12-16 21:34:53 +0000342 for head in ['%!PS-AdobeFont', '%!FontType1-1.0']:
343 if data[:len(head)] == head:
344 break
345 else:
jvre568dc72002-07-23 09:25:42 +0000346 raise T1Error, "not a PostScript font"
Just7842e561999-12-16 21:34:53 +0000347 if not _fontType1RE.search(data):
jvre568dc72002-07-23 09:25:42 +0000348 raise T1Error, "not a Type 1 font"
Just7842e561999-12-16 21:34:53 +0000349 if string.find(data, "currentfile eexec") < 0:
jvre568dc72002-07-23 09:25:42 +0000350 raise T1Error, "not an encrypted Type 1 font"
Just7842e561999-12-16 21:34:53 +0000351 # XXX what else?
352 return data
353
354
355# pfb helpers
356
Just5810aa92001-06-24 15:12:48 +0000357def longToString(long):
Just7842e561999-12-16 21:34:53 +0000358 str = ""
359 for i in range(4):
360 str = str + chr((long & (0xff << (i * 8))) >> i * 8)
361 return str
362
Just5810aa92001-06-24 15:12:48 +0000363def stringToLong(str):
Just7842e561999-12-16 21:34:53 +0000364 if len(str) <> 4:
365 raise ValueError, 'string must be 4 bytes long'
366 long = 0
367 for i in range(4):
368 long = long + (ord(str[i]) << (i * 8))
369 return long
Just5810aa92001-06-24 15:12:48 +0000370