blob: b0d17ff72b5b132a46e585021c517510a43737de [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
Just5810aa92001-06-24 15:12:48 +0000133def readLWFN(path):
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:])
147 elif code in [3, 5]:
148 break
149 elif code == 4:
150 f = open(path, "rb")
151 data.append(f.read())
152 f.close()
153 elif code == 0:
154 pass # comment, ignore
155 else:
jvre568dc72002-07-23 09:25:42 +0000156 raise T1Error, 'bad chunk code: ' + `code`
Just7842e561999-12-16 21:34:53 +0000157 finally:
Juste9601bf2001-07-30 19:04:40 +0000158 Res.CloseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000159 data = string.join(data, '')
Just5810aa92001-06-24 15:12:48 +0000160 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000161 return data
162
Just5810aa92001-06-24 15:12:48 +0000163def readPFB(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000164 """reads a PFB font file, returns raw data"""
165 f = open(path, "rb")
166 data = []
167 while 1:
168 if f.read(1) <> chr(128):
jvre568dc72002-07-23 09:25:42 +0000169 raise T1Error, 'corrupt PFB file'
Just7842e561999-12-16 21:34:53 +0000170 code = ord(f.read(1))
171 if code in [1, 2]:
Just5810aa92001-06-24 15:12:48 +0000172 chunklen = stringToLong(f.read(4))
Just36183002000-03-28 10:38:43 +0000173 chunk = f.read(chunklen)
174 assert len(chunk) == chunklen
175 data.append(chunk)
Just7842e561999-12-16 21:34:53 +0000176 elif code == 3:
177 break
178 else:
jvre568dc72002-07-23 09:25:42 +0000179 raise T1Error, 'bad chunk code: ' + `code`
Just5810aa92001-06-24 15:12:48 +0000180 if onlyHeader:
181 break
Just7842e561999-12-16 21:34:53 +0000182 f.close()
183 data = string.join(data, '')
Just5810aa92001-06-24 15:12:48 +0000184 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000185 return data
186
Just5810aa92001-06-24 15:12:48 +0000187def readOther(path):
Just7842e561999-12-16 21:34:53 +0000188 """reads any (font) file, returns raw data"""
189 f = open(path, "rb")
190 data = f.read()
191 f.close()
Just5810aa92001-06-24 15:12:48 +0000192 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000193
Just5810aa92001-06-24 15:12:48 +0000194 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000195 data = []
Just5810aa92001-06-24 15:12:48 +0000196 for isEncrypted, chunk in chunks:
197 if isEncrypted and isHex(chunk[:4]):
198 data.append(deHexString(chunk))
Just7842e561999-12-16 21:34:53 +0000199 else:
200 data.append(chunk)
201 return string.join(data, '')
202
203# file writing tools
204
Just5810aa92001-06-24 15:12:48 +0000205def writeLWFN(path, data):
Juste9601bf2001-07-30 19:04:40 +0000206 Res.FSpCreateResFile(path, "just", "LWFN", 0)
207 resRef = Res.FSpOpenResFile(path, 2) # write-only
Just7842e561999-12-16 21:34:53 +0000208 try:
Juste9601bf2001-07-30 19:04:40 +0000209 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000210 resID = 501
Just5810aa92001-06-24 15:12:48 +0000211 chunks = findEncryptedChunks(data)
212 for isEncrypted, chunk in chunks:
213 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000214 code = 2
215 else:
216 code = 1
217 while chunk:
218 res = Res.Resource(chr(code) + '\0' + chunk[:LWFNCHUNKSIZE - 2])
219 res.AddResource('POST', resID, '')
220 chunk = chunk[LWFNCHUNKSIZE - 2:]
221 resID = resID + 1
222 res = Res.Resource(chr(5) + '\0')
223 res.AddResource('POST', resID, '')
224 finally:
Juste9601bf2001-07-30 19:04:40 +0000225 Res.CloseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000226
Just5810aa92001-06-24 15:12:48 +0000227def writePFB(path, data):
228 chunks = findEncryptedChunks(data)
Just36183002000-03-28 10:38:43 +0000229 f = open(path, "wb")
Just7842e561999-12-16 21:34:53 +0000230 try:
Just5810aa92001-06-24 15:12:48 +0000231 for isEncrypted, chunk in chunks:
232 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000233 code = 2
234 else:
235 code = 1
236 f.write(chr(128) + chr(code))
Just5810aa92001-06-24 15:12:48 +0000237 f.write(longToString(len(chunk)))
Just7842e561999-12-16 21:34:53 +0000238 f.write(chunk)
239 f.write(chr(128) + chr(3))
240 finally:
241 f.close()
jvr22433b12002-07-12 19:20:19 +0000242 if haveMacSupport:
Just36183002000-03-28 10:38:43 +0000243 fss = macfs.FSSpec(path)
Just7842e561999-12-16 21:34:53 +0000244 fss.SetCreatorType('mdos', 'BINA')
245
Just5810aa92001-06-24 15:12:48 +0000246def writeOther(path, data, dohex = 0):
247 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000248 f = open(path, "wb")
249 try:
250 hexlinelen = HEXLINELENGTH / 2
Just5810aa92001-06-24 15:12:48 +0000251 for isEncrypted, chunk in chunks:
252 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000253 code = 2
254 else:
255 code = 1
256 if code == 2 and dohex:
257 while chunk:
Justc2be3d92000-01-12 19:15:57 +0000258 f.write(eexec.hexString(chunk[:hexlinelen]))
Just7842e561999-12-16 21:34:53 +0000259 f.write('\r')
260 chunk = chunk[hexlinelen:]
261 else:
262 f.write(chunk)
263 finally:
264 f.close()
jvr22433b12002-07-12 19:20:19 +0000265 if haveMacSupport:
Just7842e561999-12-16 21:34:53 +0000266 fss = macfs.FSSpec(path)
267 fss.SetCreatorType('R*ch', 'TEXT') # BBEdit text file
268
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