blob: 610c4be5eef124b8610bfe87b5084b3727c56545 [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
Behdad Esfahbod32c10ee2013-11-27 17:46:17 -050023from __future__ import print_function, division
Behdad Esfahbod30e691e2013-11-27 17:27:45 -050024from fontTools.misc.py23 import *
Justc2be3d92000-01-12 19:15:57 +000025from fontTools.misc import eexec
jvr45d1f3b2008-03-01 11:34:54 +000026from fontTools.misc.macCreatorType import getMacCreatorAndType
Just7842e561999-12-16 21:34:53 +000027import os
Behdad Esfahbod30e691e2013-11-27 17:27:45 -050028import re
Just7842e561999-12-16 21:34:53 +000029
jvr22433b12002-07-12 19:20:19 +000030
31try:
jvr25ccb9c2002-05-03 19:38:07 +000032 try:
33 from Carbon import Res
34 except ImportError:
35 import Res # MacPython < 2.2
jvre568dc72002-07-23 09:25:42 +000036except ImportError:
37 haveMacSupport = 0
38else:
39 haveMacSupport = 1
jvrb19141e2003-06-07 15:15:51 +000040 import MacOS
jvr59afba72003-05-24 12:34:11 +000041
Just7842e561999-12-16 21:34:53 +000042
jvre568dc72002-07-23 09:25:42 +000043class T1Error(Exception): pass
Just7842e561999-12-16 21:34:53 +000044
Just7842e561999-12-16 21:34:53 +000045
Behdad Esfahbode388db52013-11-28 14:26:58 -050046class T1Font(object):
Just7842e561999-12-16 21:34:53 +000047
Just36183002000-03-28 10:38:43 +000048 """Type 1 font class.
49
50 Uses a minimal interpeter that supports just about enough PS to parse
51 Type 1 fonts.
Just7842e561999-12-16 21:34:53 +000052 """
53
54 def __init__(self, path=None):
55 if path is not None:
56 self.data, type = read(path)
57 else:
58 pass # XXX
59
60 def saveAs(self, path, type):
jvr8c74f462001-08-16 10:34:22 +000061 write(path, self.getData(), type)
Just7842e561999-12-16 21:34:53 +000062
63 def getData(self):
Just36183002000-03-28 10:38:43 +000064 # XXX Todo: if the data has been converted to Python object,
65 # recreate the PS stream
Just7842e561999-12-16 21:34:53 +000066 return self.data
67
jvr7d4b6932003-08-25 17:53:29 +000068 def getGlyphSet(self):
69 """Return a generic GlyphSet, which is a dict-like object
70 mapping glyph names to glyph objects. The returned glyph objects
71 have a .draw() method that supports the Pen protocol, and will
72 have an attribute named 'width', but only *after* the .draw() method
73 has been called.
74
75 In the case of Type 1, the GlyphSet is simply the CharStrings dict.
76 """
77 return self["CharStrings"]
78
Just7842e561999-12-16 21:34:53 +000079 def __getitem__(self, key):
80 if not hasattr(self, "font"):
81 self.parse()
Just36183002000-03-28 10:38:43 +000082 return self.font[key]
Just7842e561999-12-16 21:34:53 +000083
84 def parse(self):
Just528614e2000-01-16 22:14:02 +000085 from fontTools.misc import psLib
86 from fontTools.misc import psCharStrings
Just7842e561999-12-16 21:34:53 +000087 self.font = psLib.suckfont(self.data)
88 charStrings = self.font["CharStrings"]
89 lenIV = self.font["Private"].get("lenIV", 4)
90 assert lenIV >= 0
jvr489d76a2003-08-24 19:56:16 +000091 subrs = self.font["Private"]["Subrs"]
Just7842e561999-12-16 21:34:53 +000092 for glyphName, charString in charStrings.items():
Justc2be3d92000-01-12 19:15:57 +000093 charString, R = eexec.decrypt(charString, 4330)
jvr489d76a2003-08-24 19:56:16 +000094 charStrings[glyphName] = psCharStrings.T1CharString(charString[lenIV:],
95 subrs=subrs)
Just7842e561999-12-16 21:34:53 +000096 for i in range(len(subrs)):
Justc2be3d92000-01-12 19:15:57 +000097 charString, R = eexec.decrypt(subrs[i], 4330)
jvr489d76a2003-08-24 19:56:16 +000098 subrs[i] = psCharStrings.T1CharString(charString[lenIV:], subrs=subrs)
Just7842e561999-12-16 21:34:53 +000099 del self.data
Just7842e561999-12-16 21:34:53 +0000100
101
Just36183002000-03-28 10:38:43 +0000102# low level T1 data read and write functions
Just7842e561999-12-16 21:34:53 +0000103
jvr10fd22a2005-01-25 19:06:51 +0000104def read(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000105 """reads any Type 1 font file, returns raw data"""
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500106 normpath = path.lower()
jvr45d1f3b2008-03-01 11:34:54 +0000107 creator, type = getMacCreatorAndType(path)
108 if type == 'LWFN':
109 return readLWFN(path, onlyHeader), 'LWFN'
Just7842e561999-12-16 21:34:53 +0000110 if normpath[-4:] == '.pfb':
jvr10fd22a2005-01-25 19:06:51 +0000111 return readPFB(path, onlyHeader), 'PFB'
Just7842e561999-12-16 21:34:53 +0000112 else:
Just5810aa92001-06-24 15:12:48 +0000113 return readOther(path), 'OTHER'
Just7842e561999-12-16 21:34:53 +0000114
115def write(path, data, kind='OTHER', dohex=0):
Just5810aa92001-06-24 15:12:48 +0000116 assertType1(data)
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500117 kind = kind.upper()
Just7842e561999-12-16 21:34:53 +0000118 try:
119 os.remove(path)
120 except os.error:
121 pass
122 err = 1
123 try:
124 if kind == 'LWFN':
Just5810aa92001-06-24 15:12:48 +0000125 writeLWFN(path, data)
Just7842e561999-12-16 21:34:53 +0000126 elif kind == 'PFB':
Just5810aa92001-06-24 15:12:48 +0000127 writePFB(path, data)
Just7842e561999-12-16 21:34:53 +0000128 else:
Just5810aa92001-06-24 15:12:48 +0000129 writeOther(path, data, dohex)
Just7842e561999-12-16 21:34:53 +0000130 err = 0
131 finally:
132 if err and not DEBUG:
133 try:
134 os.remove(path)
135 except os.error:
136 pass
137
138
139# -- internal --
140
141LWFNCHUNKSIZE = 2000
142HEXLINELENGTH = 80
143
144
jvrda0d8052002-07-29 21:33:46 +0000145def readLWFN(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000146 """reads an LWFN font file, returns raw data"""
jvr91bca422012-10-18 12:49:22 +0000147 resRef = Res.FSOpenResFile(path, 1) # read-only
Just7842e561999-12-16 21:34:53 +0000148 try:
Juste9601bf2001-07-30 19:04:40 +0000149 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000150 n = Res.Count1Resources('POST')
151 data = []
152 for i in range(501, 501 + n):
153 res = Res.Get1Resource('POST', i)
Behdad Esfahbod319c5fd2013-11-27 18:13:48 -0500154 code = byteord(res.data[0])
155 if byteord(res.data[1]) != 0:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500156 raise T1Error('corrupt LWFN file')
Just7842e561999-12-16 21:34:53 +0000157 if code in [1, 2]:
jvrda0d8052002-07-29 21:33:46 +0000158 if onlyHeader and code == 2:
159 break
jvr05a16f22002-07-29 21:39:06 +0000160 data.append(res.data[2:])
Just7842e561999-12-16 21:34:53 +0000161 elif code in [3, 5]:
162 break
163 elif code == 4:
164 f = open(path, "rb")
165 data.append(f.read())
166 f.close()
167 elif code == 0:
168 pass # comment, ignore
169 else:
Behdad Esfahboddc7e6f32013-11-27 02:44:56 -0500170 raise T1Error('bad chunk code: ' + repr(code))
Just7842e561999-12-16 21:34:53 +0000171 finally:
Juste9601bf2001-07-30 19:04:40 +0000172 Res.CloseResFile(resRef)
Behdad Esfahbod18316aa2013-11-27 21:17:35 -0500173 data = bytesjoin(data)
Just5810aa92001-06-24 15:12:48 +0000174 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000175 return data
176
Just5810aa92001-06-24 15:12:48 +0000177def readPFB(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000178 """reads a PFB font file, returns raw data"""
179 f = open(path, "rb")
180 data = []
Behdad Esfahbodac1b4352013-11-27 04:15:34 -0500181 while True:
Behdad Esfahbodb7a2d792013-11-27 15:19:40 -0500182 if f.read(1) != bytechr(128):
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500183 raise T1Error('corrupt PFB file')
Behdad Esfahbod319c5fd2013-11-27 18:13:48 -0500184 code = byteord(f.read(1))
Just7842e561999-12-16 21:34:53 +0000185 if code in [1, 2]:
Just5810aa92001-06-24 15:12:48 +0000186 chunklen = stringToLong(f.read(4))
Just36183002000-03-28 10:38:43 +0000187 chunk = f.read(chunklen)
188 assert len(chunk) == chunklen
189 data.append(chunk)
Just7842e561999-12-16 21:34:53 +0000190 elif code == 3:
191 break
192 else:
Behdad Esfahboddc7e6f32013-11-27 02:44:56 -0500193 raise T1Error('bad chunk code: ' + repr(code))
Just5810aa92001-06-24 15:12:48 +0000194 if onlyHeader:
195 break
Just7842e561999-12-16 21:34:53 +0000196 f.close()
Behdad Esfahbod18316aa2013-11-27 21:17:35 -0500197 data = bytesjoin(data)
Just5810aa92001-06-24 15:12:48 +0000198 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000199 return data
200
Just5810aa92001-06-24 15:12:48 +0000201def readOther(path):
Just7842e561999-12-16 21:34:53 +0000202 """reads any (font) file, returns raw data"""
203 f = open(path, "rb")
204 data = f.read()
205 f.close()
Just5810aa92001-06-24 15:12:48 +0000206 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000207
Just5810aa92001-06-24 15:12:48 +0000208 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000209 data = []
Just5810aa92001-06-24 15:12:48 +0000210 for isEncrypted, chunk in chunks:
211 if isEncrypted and isHex(chunk[:4]):
212 data.append(deHexString(chunk))
Just7842e561999-12-16 21:34:53 +0000213 else:
214 data.append(chunk)
Behdad Esfahbod18316aa2013-11-27 21:17:35 -0500215 return bytesjoin(data)
Just7842e561999-12-16 21:34:53 +0000216
217# file writing tools
218
Just5810aa92001-06-24 15:12:48 +0000219def writeLWFN(path, data):
Juste9601bf2001-07-30 19:04:40 +0000220 Res.FSpCreateResFile(path, "just", "LWFN", 0)
jvr91bca422012-10-18 12:49:22 +0000221 resRef = Res.FSOpenResFile(path, 2) # write-only
Just7842e561999-12-16 21:34:53 +0000222 try:
Juste9601bf2001-07-30 19:04:40 +0000223 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000224 resID = 501
Just5810aa92001-06-24 15:12:48 +0000225 chunks = findEncryptedChunks(data)
226 for isEncrypted, chunk in chunks:
227 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000228 code = 2
229 else:
230 code = 1
231 while chunk:
Behdad Esfahbodb7a2d792013-11-27 15:19:40 -0500232 res = Res.Resource(bytechr(code) + '\0' + chunk[:LWFNCHUNKSIZE - 2])
Just7842e561999-12-16 21:34:53 +0000233 res.AddResource('POST', resID, '')
234 chunk = chunk[LWFNCHUNKSIZE - 2:]
235 resID = resID + 1
Behdad Esfahbodb7a2d792013-11-27 15:19:40 -0500236 res = Res.Resource(bytechr(5) + '\0')
Just7842e561999-12-16 21:34:53 +0000237 res.AddResource('POST', resID, '')
238 finally:
Juste9601bf2001-07-30 19:04:40 +0000239 Res.CloseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000240
Just5810aa92001-06-24 15:12:48 +0000241def writePFB(path, data):
242 chunks = findEncryptedChunks(data)
Just36183002000-03-28 10:38:43 +0000243 f = open(path, "wb")
Just7842e561999-12-16 21:34:53 +0000244 try:
Just5810aa92001-06-24 15:12:48 +0000245 for isEncrypted, chunk in chunks:
246 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000247 code = 2
248 else:
249 code = 1
Behdad Esfahbodb7a2d792013-11-27 15:19:40 -0500250 f.write(bytechr(128) + bytechr(code))
Just5810aa92001-06-24 15:12:48 +0000251 f.write(longToString(len(chunk)))
Just7842e561999-12-16 21:34:53 +0000252 f.write(chunk)
Behdad Esfahbodb7a2d792013-11-27 15:19:40 -0500253 f.write(bytechr(128) + bytechr(3))
Just7842e561999-12-16 21:34:53 +0000254 finally:
255 f.close()
Just7842e561999-12-16 21:34:53 +0000256
Just5810aa92001-06-24 15:12:48 +0000257def writeOther(path, data, dohex = 0):
258 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000259 f = open(path, "wb")
260 try:
Behdad Esfahbod32c10ee2013-11-27 17:46:17 -0500261 hexlinelen = HEXLINELENGTH // 2
Just5810aa92001-06-24 15:12:48 +0000262 for isEncrypted, chunk in chunks:
263 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000264 code = 2
265 else:
266 code = 1
267 if code == 2 and dohex:
268 while chunk:
Justc2be3d92000-01-12 19:15:57 +0000269 f.write(eexec.hexString(chunk[:hexlinelen]))
Just7842e561999-12-16 21:34:53 +0000270 f.write('\r')
271 chunk = chunk[hexlinelen:]
272 else:
273 f.write(chunk)
274 finally:
275 f.close()
Just7842e561999-12-16 21:34:53 +0000276
277
278# decryption tools
279
280EEXECBEGIN = "currentfile eexec"
281EEXECEND = '0' * 64
282EEXECINTERNALEND = "currentfile closefile"
283EEXECBEGINMARKER = "%-- eexec start\r"
284EEXECENDMARKER = "%-- eexec end\r"
285
286_ishexRE = re.compile('[0-9A-Fa-f]*$')
287
Just5810aa92001-06-24 15:12:48 +0000288def isHex(text):
Just7842e561999-12-16 21:34:53 +0000289 return _ishexRE.match(text) is not None
290
291
Just5810aa92001-06-24 15:12:48 +0000292def decryptType1(data):
293 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000294 data = []
Just5810aa92001-06-24 15:12:48 +0000295 for isEncrypted, chunk in chunks:
296 if isEncrypted:
297 if isHex(chunk[:4]):
298 chunk = deHexString(chunk)
Justc2be3d92000-01-12 19:15:57 +0000299 decrypted, R = eexec.decrypt(chunk, 55665)
Just7842e561999-12-16 21:34:53 +0000300 decrypted = decrypted[4:]
Behdad Esfahbod180ace62013-11-27 02:40:30 -0500301 if decrypted[-len(EEXECINTERNALEND)-1:-1] != EEXECINTERNALEND \
302 and decrypted[-len(EEXECINTERNALEND)-2:-2] != EEXECINTERNALEND:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500303 raise T1Error("invalid end of eexec part")
Just7842e561999-12-16 21:34:53 +0000304 decrypted = decrypted[:-len(EEXECINTERNALEND)-2] + '\r'
305 data.append(EEXECBEGINMARKER + decrypted + EEXECENDMARKER)
306 else:
307 if chunk[-len(EEXECBEGIN)-1:-1] == EEXECBEGIN:
308 data.append(chunk[:-len(EEXECBEGIN)-1])
309 else:
310 data.append(chunk)
Behdad Esfahbod18316aa2013-11-27 21:17:35 -0500311 return bytesjoin(data)
Just7842e561999-12-16 21:34:53 +0000312
Just5810aa92001-06-24 15:12:48 +0000313def findEncryptedChunks(data):
Just7842e561999-12-16 21:34:53 +0000314 chunks = []
Behdad Esfahbodac1b4352013-11-27 04:15:34 -0500315 while True:
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500316 eBegin = data.find(EEXECBEGIN)
Just5810aa92001-06-24 15:12:48 +0000317 if eBegin < 0:
Just7842e561999-12-16 21:34:53 +0000318 break
jvr90290b72001-11-28 12:22:15 +0000319 eBegin = eBegin + len(EEXECBEGIN) + 1
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500320 eEnd = data.find(EEXECEND, eBegin)
Just5810aa92001-06-24 15:12:48 +0000321 if eEnd < 0:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500322 raise T1Error("can't find end of eexec part")
jvrdb1f2802002-07-23 14:54:47 +0000323 cypherText = data[eBegin:eEnd + 2]
jvre56bc902008-03-10 21:58:00 +0000324 if isHex(cypherText[:4]):
325 cypherText = deHexString(cypherText)
jvrdb1f2802002-07-23 14:54:47 +0000326 plainText, R = eexec.decrypt(cypherText, 55665)
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500327 eEndLocal = plainText.find(EEXECINTERNALEND)
jvrdb1f2802002-07-23 14:54:47 +0000328 if eEndLocal < 0:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500329 raise T1Error("can't find end of eexec part")
jvr90290b72001-11-28 12:22:15 +0000330 chunks.append((0, data[:eBegin]))
jvre56bc902008-03-10 21:58:00 +0000331 chunks.append((1, cypherText[:eEndLocal + len(EEXECINTERNALEND) + 1]))
Just5810aa92001-06-24 15:12:48 +0000332 data = data[eEnd:]
Just7842e561999-12-16 21:34:53 +0000333 chunks.append((0, data))
334 return chunks
335
Just5810aa92001-06-24 15:12:48 +0000336def deHexString(hexstring):
Behdad Esfahbod18316aa2013-11-27 21:17:35 -0500337 return eexec.deHexString(strjoin(hexstring.split()))
Just7842e561999-12-16 21:34:53 +0000338
339
340# Type 1 assertion
341
342_fontType1RE = re.compile(r"/FontType\s+1\s+def")
343
Just5810aa92001-06-24 15:12:48 +0000344def assertType1(data):
jvre56bc902008-03-10 21:58:00 +0000345 for head in ['%!PS-AdobeFont', '%!FontType1']:
Just7842e561999-12-16 21:34:53 +0000346 if data[:len(head)] == head:
347 break
348 else:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500349 raise T1Error("not a PostScript font")
Just7842e561999-12-16 21:34:53 +0000350 if not _fontType1RE.search(data):
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500351 raise T1Error("not a Type 1 font")
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500352 if data.find("currentfile eexec") < 0:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500353 raise T1Error("not an encrypted Type 1 font")
Just7842e561999-12-16 21:34:53 +0000354 # XXX what else?
355 return data
356
357
358# pfb helpers
359
Just5810aa92001-06-24 15:12:48 +0000360def longToString(long):
Just7842e561999-12-16 21:34:53 +0000361 str = ""
362 for i in range(4):
Behdad Esfahbodb7a2d792013-11-27 15:19:40 -0500363 str = str + bytechr((long & (0xff << (i * 8))) >> i * 8)
Just7842e561999-12-16 21:34:53 +0000364 return str
365
Just5810aa92001-06-24 15:12:48 +0000366def stringToLong(str):
Behdad Esfahbod180ace62013-11-27 02:40:30 -0500367 if len(str) != 4:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500368 raise ValueError('string must be 4 bytes long')
Just7842e561999-12-16 21:34:53 +0000369 long = 0
370 for i in range(4):
Behdad Esfahbod319c5fd2013-11-27 18:13:48 -0500371 long = long + (byteord(str[i]) << (i * 8))
Just7842e561999-12-16 21:34:53 +0000372 return long
Just5810aa92001-06-24 15:12:48 +0000373