blob: 14cc90464bd66eb82adae1699704b84bc62af801 [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
Behdad Esfahboddc873722013-12-04 21:28:50 -050011write(path, data, kind='OTHER', dohex=False)
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"""
Behdad Esfahbod1ae29592014-01-14 15:07:50 +080018from __future__ import print_function, division, absolute_import
Behdad Esfahbod30e691e2013-11-27 17:27:45 -050019from fontTools.misc.py23 import *
Justc2be3d92000-01-12 19:15:57 +000020from fontTools.misc import eexec
jvr45d1f3b2008-03-01 11:34:54 +000021from fontTools.misc.macCreatorType import getMacCreatorAndType
Just7842e561999-12-16 21:34:53 +000022import os
Behdad Esfahbod30e691e2013-11-27 17:27:45 -050023import re
Just7842e561999-12-16 21:34:53 +000024
Denis Jacqueryeaf1c9962013-11-29 21:51:15 +010025__author__ = "jvr"
26__version__ = "1.0b2"
27DEBUG = 0
28
jvr22433b12002-07-12 19:20:19 +000029
30try:
jvr25ccb9c2002-05-03 19:38:07 +000031 try:
32 from Carbon import Res
33 except ImportError:
34 import Res # MacPython < 2.2
jvre568dc72002-07-23 09:25:42 +000035except ImportError:
36 haveMacSupport = 0
37else:
38 haveMacSupport = 1
jvrb19141e2003-06-07 15:15:51 +000039 import MacOS
jvr59afba72003-05-24 12:34:11 +000040
Just7842e561999-12-16 21:34:53 +000041
jvre568dc72002-07-23 09:25:42 +000042class T1Error(Exception): pass
Just7842e561999-12-16 21:34:53 +000043
Just7842e561999-12-16 21:34:53 +000044
Behdad Esfahbode388db52013-11-28 14:26:58 -050045class T1Font(object):
Just7842e561999-12-16 21:34:53 +000046
Just36183002000-03-28 10:38:43 +000047 """Type 1 font class.
48
49 Uses a minimal interpeter that supports just about enough PS to parse
50 Type 1 fonts.
Just7842e561999-12-16 21:34:53 +000051 """
52
53 def __init__(self, path=None):
54 if path is not None:
55 self.data, type = read(path)
56 else:
57 pass # XXX
58
59 def saveAs(self, path, type):
jvr8c74f462001-08-16 10:34:22 +000060 write(path, self.getData(), type)
Just7842e561999-12-16 21:34:53 +000061
62 def getData(self):
Just36183002000-03-28 10:38:43 +000063 # XXX Todo: if the data has been converted to Python object,
64 # recreate the PS stream
Just7842e561999-12-16 21:34:53 +000065 return self.data
66
jvr7d4b6932003-08-25 17:53:29 +000067 def getGlyphSet(self):
68 """Return a generic GlyphSet, which is a dict-like object
69 mapping glyph names to glyph objects. The returned glyph objects
70 have a .draw() method that supports the Pen protocol, and will
71 have an attribute named 'width', but only *after* the .draw() method
72 has been called.
73
74 In the case of Type 1, the GlyphSet is simply the CharStrings dict.
75 """
76 return self["CharStrings"]
77
Just7842e561999-12-16 21:34:53 +000078 def __getitem__(self, key):
79 if not hasattr(self, "font"):
80 self.parse()
Just36183002000-03-28 10:38:43 +000081 return self.font[key]
Just7842e561999-12-16 21:34:53 +000082
83 def parse(self):
Just528614e2000-01-16 22:14:02 +000084 from fontTools.misc import psLib
85 from fontTools.misc import psCharStrings
Just7842e561999-12-16 21:34:53 +000086 self.font = psLib.suckfont(self.data)
87 charStrings = self.font["CharStrings"]
88 lenIV = self.font["Private"].get("lenIV", 4)
89 assert lenIV >= 0
jvr489d76a2003-08-24 19:56:16 +000090 subrs = self.font["Private"]["Subrs"]
Just7842e561999-12-16 21:34:53 +000091 for glyphName, charString in charStrings.items():
Justc2be3d92000-01-12 19:15:57 +000092 charString, R = eexec.decrypt(charString, 4330)
jvr489d76a2003-08-24 19:56:16 +000093 charStrings[glyphName] = psCharStrings.T1CharString(charString[lenIV:],
94 subrs=subrs)
Just7842e561999-12-16 21:34:53 +000095 for i in range(len(subrs)):
Justc2be3d92000-01-12 19:15:57 +000096 charString, R = eexec.decrypt(subrs[i], 4330)
jvr489d76a2003-08-24 19:56:16 +000097 subrs[i] = psCharStrings.T1CharString(charString[lenIV:], subrs=subrs)
Just7842e561999-12-16 21:34:53 +000098 del self.data
Just7842e561999-12-16 21:34:53 +000099
100
Just36183002000-03-28 10:38:43 +0000101# low level T1 data read and write functions
Just7842e561999-12-16 21:34:53 +0000102
Behdad Esfahboddc873722013-12-04 21:28:50 -0500103def read(path, onlyHeader=False):
Just7842e561999-12-16 21:34:53 +0000104 """reads any Type 1 font file, returns raw data"""
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500105 normpath = path.lower()
Behdad Esfahbod153ec402013-12-04 01:15:46 -0500106 creator, typ = getMacCreatorAndType(path)
107 if typ == 'LWFN':
jvr45d1f3b2008-03-01 11:34:54 +0000108 return readLWFN(path, onlyHeader), 'LWFN'
Just7842e561999-12-16 21:34:53 +0000109 if normpath[-4:] == '.pfb':
jvr10fd22a2005-01-25 19:06:51 +0000110 return readPFB(path, onlyHeader), 'PFB'
Just7842e561999-12-16 21:34:53 +0000111 else:
Just5810aa92001-06-24 15:12:48 +0000112 return readOther(path), 'OTHER'
Just7842e561999-12-16 21:34:53 +0000113
Behdad Esfahboddc873722013-12-04 21:28:50 -0500114def write(path, data, kind='OTHER', dohex=False):
Just5810aa92001-06-24 15:12:48 +0000115 assertType1(data)
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500116 kind = kind.upper()
Just7842e561999-12-16 21:34:53 +0000117 try:
118 os.remove(path)
119 except os.error:
120 pass
121 err = 1
122 try:
123 if kind == 'LWFN':
Just5810aa92001-06-24 15:12:48 +0000124 writeLWFN(path, data)
Just7842e561999-12-16 21:34:53 +0000125 elif kind == 'PFB':
Just5810aa92001-06-24 15:12:48 +0000126 writePFB(path, data)
Just7842e561999-12-16 21:34:53 +0000127 else:
Just5810aa92001-06-24 15:12:48 +0000128 writeOther(path, data, dohex)
Just7842e561999-12-16 21:34:53 +0000129 err = 0
130 finally:
131 if err and not DEBUG:
132 try:
133 os.remove(path)
134 except os.error:
135 pass
136
137
138# -- internal --
139
140LWFNCHUNKSIZE = 2000
141HEXLINELENGTH = 80
142
143
Behdad Esfahboddc873722013-12-04 21:28:50 -0500144def readLWFN(path, onlyHeader=False):
Just7842e561999-12-16 21:34:53 +0000145 """reads an LWFN font file, returns raw data"""
jvr91bca422012-10-18 12:49:22 +0000146 resRef = Res.FSOpenResFile(path, 1) # read-only
Just7842e561999-12-16 21:34:53 +0000147 try:
Juste9601bf2001-07-30 19:04:40 +0000148 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000149 n = Res.Count1Resources('POST')
150 data = []
151 for i in range(501, 501 + n):
152 res = Res.Get1Resource('POST', i)
Behdad Esfahbod319c5fd2013-11-27 18:13:48 -0500153 code = byteord(res.data[0])
154 if byteord(res.data[1]) != 0:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500155 raise T1Error('corrupt LWFN file')
Just7842e561999-12-16 21:34:53 +0000156 if code in [1, 2]:
jvrda0d8052002-07-29 21:33:46 +0000157 if onlyHeader and code == 2:
158 break
jvr05a16f22002-07-29 21:39:06 +0000159 data.append(res.data[2:])
Just7842e561999-12-16 21:34:53 +0000160 elif code in [3, 5]:
161 break
162 elif code == 4:
163 f = open(path, "rb")
164 data.append(f.read())
165 f.close()
166 elif code == 0:
167 pass # comment, ignore
168 else:
Behdad Esfahboddc7e6f32013-11-27 02:44:56 -0500169 raise T1Error('bad chunk code: ' + repr(code))
Just7842e561999-12-16 21:34:53 +0000170 finally:
Juste9601bf2001-07-30 19:04:40 +0000171 Res.CloseResFile(resRef)
Behdad Esfahbod18316aa2013-11-27 21:17:35 -0500172 data = bytesjoin(data)
Just5810aa92001-06-24 15:12:48 +0000173 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000174 return data
175
Behdad Esfahboddc873722013-12-04 21:28:50 -0500176def readPFB(path, onlyHeader=False):
Just7842e561999-12-16 21:34:53 +0000177 """reads a PFB font file, returns raw data"""
178 f = open(path, "rb")
179 data = []
Behdad Esfahbodac1b4352013-11-27 04:15:34 -0500180 while True:
Behdad Esfahbodb7a2d792013-11-27 15:19:40 -0500181 if f.read(1) != bytechr(128):
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500182 raise T1Error('corrupt PFB file')
Behdad Esfahbod319c5fd2013-11-27 18:13:48 -0500183 code = byteord(f.read(1))
Just7842e561999-12-16 21:34:53 +0000184 if code in [1, 2]:
Just5810aa92001-06-24 15:12:48 +0000185 chunklen = stringToLong(f.read(4))
Just36183002000-03-28 10:38:43 +0000186 chunk = f.read(chunklen)
187 assert len(chunk) == chunklen
188 data.append(chunk)
Just7842e561999-12-16 21:34:53 +0000189 elif code == 3:
190 break
191 else:
Behdad Esfahboddc7e6f32013-11-27 02:44:56 -0500192 raise T1Error('bad chunk code: ' + repr(code))
Just5810aa92001-06-24 15:12:48 +0000193 if onlyHeader:
194 break
Just7842e561999-12-16 21:34:53 +0000195 f.close()
Behdad Esfahbod18316aa2013-11-27 21:17:35 -0500196 data = bytesjoin(data)
Just5810aa92001-06-24 15:12:48 +0000197 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000198 return data
199
Just5810aa92001-06-24 15:12:48 +0000200def readOther(path):
Just7842e561999-12-16 21:34:53 +0000201 """reads any (font) file, returns raw data"""
202 f = open(path, "rb")
203 data = f.read()
204 f.close()
Just5810aa92001-06-24 15:12:48 +0000205 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000206
Just5810aa92001-06-24 15:12:48 +0000207 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000208 data = []
Just5810aa92001-06-24 15:12:48 +0000209 for isEncrypted, chunk in chunks:
210 if isEncrypted and isHex(chunk[:4]):
211 data.append(deHexString(chunk))
Just7842e561999-12-16 21:34:53 +0000212 else:
213 data.append(chunk)
Behdad Esfahbod18316aa2013-11-27 21:17:35 -0500214 return bytesjoin(data)
Just7842e561999-12-16 21:34:53 +0000215
216# file writing tools
217
Just5810aa92001-06-24 15:12:48 +0000218def writeLWFN(path, data):
Juste9601bf2001-07-30 19:04:40 +0000219 Res.FSpCreateResFile(path, "just", "LWFN", 0)
jvr91bca422012-10-18 12:49:22 +0000220 resRef = Res.FSOpenResFile(path, 2) # write-only
Just7842e561999-12-16 21:34:53 +0000221 try:
Juste9601bf2001-07-30 19:04:40 +0000222 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000223 resID = 501
Just5810aa92001-06-24 15:12:48 +0000224 chunks = findEncryptedChunks(data)
225 for isEncrypted, chunk in chunks:
226 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000227 code = 2
228 else:
229 code = 1
230 while chunk:
Behdad Esfahbodb7a2d792013-11-27 15:19:40 -0500231 res = Res.Resource(bytechr(code) + '\0' + chunk[:LWFNCHUNKSIZE - 2])
Just7842e561999-12-16 21:34:53 +0000232 res.AddResource('POST', resID, '')
233 chunk = chunk[LWFNCHUNKSIZE - 2:]
234 resID = resID + 1
Behdad Esfahbodb7a2d792013-11-27 15:19:40 -0500235 res = Res.Resource(bytechr(5) + '\0')
Just7842e561999-12-16 21:34:53 +0000236 res.AddResource('POST', resID, '')
237 finally:
Juste9601bf2001-07-30 19:04:40 +0000238 Res.CloseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000239
Just5810aa92001-06-24 15:12:48 +0000240def writePFB(path, data):
241 chunks = findEncryptedChunks(data)
Just36183002000-03-28 10:38:43 +0000242 f = open(path, "wb")
Just7842e561999-12-16 21:34:53 +0000243 try:
Just5810aa92001-06-24 15:12:48 +0000244 for isEncrypted, chunk in chunks:
245 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000246 code = 2
247 else:
248 code = 1
Behdad Esfahbodb7a2d792013-11-27 15:19:40 -0500249 f.write(bytechr(128) + bytechr(code))
Just5810aa92001-06-24 15:12:48 +0000250 f.write(longToString(len(chunk)))
Just7842e561999-12-16 21:34:53 +0000251 f.write(chunk)
Behdad Esfahbodb7a2d792013-11-27 15:19:40 -0500252 f.write(bytechr(128) + bytechr(3))
Just7842e561999-12-16 21:34:53 +0000253 finally:
254 f.close()
Just7842e561999-12-16 21:34:53 +0000255
Behdad Esfahboddc873722013-12-04 21:28:50 -0500256def writeOther(path, data, dohex=False):
Just5810aa92001-06-24 15:12:48 +0000257 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000258 f = open(path, "wb")
259 try:
Behdad Esfahbod32c10ee2013-11-27 17:46:17 -0500260 hexlinelen = HEXLINELENGTH // 2
Just5810aa92001-06-24 15:12:48 +0000261 for isEncrypted, chunk in chunks:
262 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000263 code = 2
264 else:
265 code = 1
266 if code == 2 and dohex:
267 while chunk:
Justc2be3d92000-01-12 19:15:57 +0000268 f.write(eexec.hexString(chunk[:hexlinelen]))
Just7842e561999-12-16 21:34:53 +0000269 f.write('\r')
270 chunk = chunk[hexlinelen:]
271 else:
272 f.write(chunk)
273 finally:
274 f.close()
Just7842e561999-12-16 21:34:53 +0000275
276
277# decryption tools
278
279EEXECBEGIN = "currentfile eexec"
280EEXECEND = '0' * 64
281EEXECINTERNALEND = "currentfile closefile"
282EEXECBEGINMARKER = "%-- eexec start\r"
283EEXECENDMARKER = "%-- eexec end\r"
284
285_ishexRE = re.compile('[0-9A-Fa-f]*$')
286
Just5810aa92001-06-24 15:12:48 +0000287def isHex(text):
Just7842e561999-12-16 21:34:53 +0000288 return _ishexRE.match(text) is not None
289
290
Just5810aa92001-06-24 15:12:48 +0000291def decryptType1(data):
292 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000293 data = []
Just5810aa92001-06-24 15:12:48 +0000294 for isEncrypted, chunk in chunks:
295 if isEncrypted:
296 if isHex(chunk[:4]):
297 chunk = deHexString(chunk)
Justc2be3d92000-01-12 19:15:57 +0000298 decrypted, R = eexec.decrypt(chunk, 55665)
Just7842e561999-12-16 21:34:53 +0000299 decrypted = decrypted[4:]
Behdad Esfahbod180ace62013-11-27 02:40:30 -0500300 if decrypted[-len(EEXECINTERNALEND)-1:-1] != EEXECINTERNALEND \
301 and decrypted[-len(EEXECINTERNALEND)-2:-2] != EEXECINTERNALEND:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500302 raise T1Error("invalid end of eexec part")
Just7842e561999-12-16 21:34:53 +0000303 decrypted = decrypted[:-len(EEXECINTERNALEND)-2] + '\r'
304 data.append(EEXECBEGINMARKER + decrypted + EEXECENDMARKER)
305 else:
306 if chunk[-len(EEXECBEGIN)-1:-1] == EEXECBEGIN:
307 data.append(chunk[:-len(EEXECBEGIN)-1])
308 else:
309 data.append(chunk)
Behdad Esfahbod18316aa2013-11-27 21:17:35 -0500310 return bytesjoin(data)
Just7842e561999-12-16 21:34:53 +0000311
Just5810aa92001-06-24 15:12:48 +0000312def findEncryptedChunks(data):
Just7842e561999-12-16 21:34:53 +0000313 chunks = []
Behdad Esfahbodac1b4352013-11-27 04:15:34 -0500314 while True:
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500315 eBegin = data.find(EEXECBEGIN)
Just5810aa92001-06-24 15:12:48 +0000316 if eBegin < 0:
Just7842e561999-12-16 21:34:53 +0000317 break
jvr90290b72001-11-28 12:22:15 +0000318 eBegin = eBegin + len(EEXECBEGIN) + 1
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500319 eEnd = data.find(EEXECEND, eBegin)
Just5810aa92001-06-24 15:12:48 +0000320 if eEnd < 0:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500321 raise T1Error("can't find end of eexec part")
jvrdb1f2802002-07-23 14:54:47 +0000322 cypherText = data[eBegin:eEnd + 2]
jvre56bc902008-03-10 21:58:00 +0000323 if isHex(cypherText[:4]):
324 cypherText = deHexString(cypherText)
jvrdb1f2802002-07-23 14:54:47 +0000325 plainText, R = eexec.decrypt(cypherText, 55665)
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500326 eEndLocal = plainText.find(EEXECINTERNALEND)
jvrdb1f2802002-07-23 14:54:47 +0000327 if eEndLocal < 0:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500328 raise T1Error("can't find end of eexec part")
jvr90290b72001-11-28 12:22:15 +0000329 chunks.append((0, data[:eBegin]))
jvre56bc902008-03-10 21:58:00 +0000330 chunks.append((1, cypherText[:eEndLocal + len(EEXECINTERNALEND) + 1]))
Just5810aa92001-06-24 15:12:48 +0000331 data = data[eEnd:]
Just7842e561999-12-16 21:34:53 +0000332 chunks.append((0, data))
333 return chunks
334
Just5810aa92001-06-24 15:12:48 +0000335def deHexString(hexstring):
Behdad Esfahbod18316aa2013-11-27 21:17:35 -0500336 return eexec.deHexString(strjoin(hexstring.split()))
Just7842e561999-12-16 21:34:53 +0000337
338
339# Type 1 assertion
340
Behdad Esfahboddc0ce0b2013-12-07 12:04:23 -0500341_fontType1RE = re.compile(br"/FontType\s+1\s+def")
Just7842e561999-12-16 21:34:53 +0000342
Just5810aa92001-06-24 15:12:48 +0000343def assertType1(data):
Behdad Esfahboddc0ce0b2013-12-07 12:04:23 -0500344 for head in [b'%!PS-AdobeFont', b'%!FontType1']:
Just7842e561999-12-16 21:34:53 +0000345 if data[:len(head)] == head:
346 break
347 else:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500348 raise T1Error("not a PostScript font")
Just7842e561999-12-16 21:34:53 +0000349 if not _fontType1RE.search(data):
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500350 raise T1Error("not a Type 1 font")
Behdad Esfahboddc0ce0b2013-12-07 12:04:23 -0500351 if data.find(b"currentfile eexec") < 0:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500352 raise T1Error("not an encrypted Type 1 font")
Just7842e561999-12-16 21:34:53 +0000353 # XXX what else?
354 return data
355
356
357# pfb helpers
358
Just5810aa92001-06-24 15:12:48 +0000359def longToString(long):
Behdad Esfahbod153ec402013-12-04 01:15:46 -0500360 s = ""
Just7842e561999-12-16 21:34:53 +0000361 for i in range(4):
Behdad Esfahbod153ec402013-12-04 01:15:46 -0500362 s += bytechr((long & (0xff << (i * 8))) >> i * 8)
363 return s
Just7842e561999-12-16 21:34:53 +0000364
Behdad Esfahbod153ec402013-12-04 01:15:46 -0500365def stringToLong(s):
366 if len(s) != 4:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500367 raise ValueError('string must be 4 bytes long')
Behdad Esfahbod153ec402013-12-04 01:15:46 -0500368 l = 0
Just7842e561999-12-16 21:34:53 +0000369 for i in range(4):
Behdad Esfahbod153ec402013-12-04 01:15:46 -0500370 l += byteord(s[i]) << (i * 8)
371 return l
Just5810aa92001-06-24 15:12:48 +0000372