blob: 6255a8cc9247d984cc0986280401ea011072442b [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
jvr45d1f3b2008-03-01 11:34:54 +000024from fontTools.misc.macCreatorType import getMacCreatorAndType
Just7842e561999-12-16 21:34:53 +000025import 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
jvr7d4b6932003-08-25 17:53:29 +000066 def getGlyphSet(self):
67 """Return a generic GlyphSet, which is a dict-like object
68 mapping glyph names to glyph objects. The returned glyph objects
69 have a .draw() method that supports the Pen protocol, and will
70 have an attribute named 'width', but only *after* the .draw() method
71 has been called.
72
73 In the case of Type 1, the GlyphSet is simply the CharStrings dict.
74 """
75 return self["CharStrings"]
76
Just7842e561999-12-16 21:34:53 +000077 def __getitem__(self, key):
78 if not hasattr(self, "font"):
79 self.parse()
Just36183002000-03-28 10:38:43 +000080 return self.font[key]
Just7842e561999-12-16 21:34:53 +000081
82 def parse(self):
Just528614e2000-01-16 22:14:02 +000083 from fontTools.misc import psLib
84 from fontTools.misc import psCharStrings
Just7842e561999-12-16 21:34:53 +000085 self.font = psLib.suckfont(self.data)
86 charStrings = self.font["CharStrings"]
87 lenIV = self.font["Private"].get("lenIV", 4)
88 assert lenIV >= 0
jvr489d76a2003-08-24 19:56:16 +000089 subrs = self.font["Private"]["Subrs"]
Just7842e561999-12-16 21:34:53 +000090 for glyphName, charString in charStrings.items():
Justc2be3d92000-01-12 19:15:57 +000091 charString, R = eexec.decrypt(charString, 4330)
jvr489d76a2003-08-24 19:56:16 +000092 charStrings[glyphName] = psCharStrings.T1CharString(charString[lenIV:],
93 subrs=subrs)
Just7842e561999-12-16 21:34:53 +000094 for i in range(len(subrs)):
Justc2be3d92000-01-12 19:15:57 +000095 charString, R = eexec.decrypt(subrs[i], 4330)
jvr489d76a2003-08-24 19:56:16 +000096 subrs[i] = psCharStrings.T1CharString(charString[lenIV:], subrs=subrs)
Just7842e561999-12-16 21:34:53 +000097 del self.data
Just7842e561999-12-16 21:34:53 +000098
99
Just36183002000-03-28 10:38:43 +0000100# low level T1 data read and write functions
Just7842e561999-12-16 21:34:53 +0000101
jvr10fd22a2005-01-25 19:06:51 +0000102def read(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000103 """reads any Type 1 font file, returns raw data"""
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500104 normpath = path.lower()
jvr45d1f3b2008-03-01 11:34:54 +0000105 creator, type = getMacCreatorAndType(path)
106 if type == 'LWFN':
107 return readLWFN(path, onlyHeader), 'LWFN'
Just7842e561999-12-16 21:34:53 +0000108 if normpath[-4:] == '.pfb':
jvr10fd22a2005-01-25 19:06:51 +0000109 return readPFB(path, onlyHeader), 'PFB'
Just7842e561999-12-16 21:34:53 +0000110 else:
Just5810aa92001-06-24 15:12:48 +0000111 return readOther(path), 'OTHER'
Just7842e561999-12-16 21:34:53 +0000112
113def write(path, data, kind='OTHER', dohex=0):
Just5810aa92001-06-24 15:12:48 +0000114 assertType1(data)
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500115 kind = kind.upper()
Just7842e561999-12-16 21:34:53 +0000116 try:
117 os.remove(path)
118 except os.error:
119 pass
120 err = 1
121 try:
122 if kind == 'LWFN':
Just5810aa92001-06-24 15:12:48 +0000123 writeLWFN(path, data)
Just7842e561999-12-16 21:34:53 +0000124 elif kind == 'PFB':
Just5810aa92001-06-24 15:12:48 +0000125 writePFB(path, data)
Just7842e561999-12-16 21:34:53 +0000126 else:
Just5810aa92001-06-24 15:12:48 +0000127 writeOther(path, data, dohex)
Just7842e561999-12-16 21:34:53 +0000128 err = 0
129 finally:
130 if err and not DEBUG:
131 try:
132 os.remove(path)
133 except os.error:
134 pass
135
136
137# -- internal --
138
139LWFNCHUNKSIZE = 2000
140HEXLINELENGTH = 80
141
142
jvrda0d8052002-07-29 21:33:46 +0000143def readLWFN(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000144 """reads an LWFN font file, returns raw data"""
jvr91bca422012-10-18 12:49:22 +0000145 resRef = Res.FSOpenResFile(path, 1) # read-only
Just7842e561999-12-16 21:34:53 +0000146 try:
Juste9601bf2001-07-30 19:04:40 +0000147 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000148 n = Res.Count1Resources('POST')
149 data = []
150 for i in range(501, 501 + n):
151 res = Res.Get1Resource('POST', i)
152 code = ord(res.data[0])
Behdad Esfahbod180ace62013-11-27 02:40:30 -0500153 if ord(res.data[1]) != 0:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500154 raise T1Error('corrupt LWFN file')
Just7842e561999-12-16 21:34:53 +0000155 if code in [1, 2]:
jvrda0d8052002-07-29 21:33:46 +0000156 if onlyHeader and code == 2:
157 break
jvr05a16f22002-07-29 21:39:06 +0000158 data.append(res.data[2:])
Just7842e561999-12-16 21:34:53 +0000159 elif code in [3, 5]:
160 break
161 elif code == 4:
162 f = open(path, "rb")
163 data.append(f.read())
164 f.close()
165 elif code == 0:
166 pass # comment, ignore
167 else:
Behdad Esfahboddc7e6f32013-11-27 02:44:56 -0500168 raise T1Error('bad chunk code: ' + repr(code))
Just7842e561999-12-16 21:34:53 +0000169 finally:
Juste9601bf2001-07-30 19:04:40 +0000170 Res.CloseResFile(resRef)
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500171 data = ''.join(data)
Just5810aa92001-06-24 15:12:48 +0000172 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000173 return data
174
Just5810aa92001-06-24 15:12:48 +0000175def readPFB(path, onlyHeader=0):
Just7842e561999-12-16 21:34:53 +0000176 """reads a PFB font file, returns raw data"""
177 f = open(path, "rb")
178 data = []
Behdad Esfahbodac1b4352013-11-27 04:15:34 -0500179 while True:
Behdad Esfahbod180ace62013-11-27 02:40:30 -0500180 if f.read(1) != chr(128):
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500181 raise T1Error('corrupt PFB file')
Just7842e561999-12-16 21:34:53 +0000182 code = ord(f.read(1))
183 if code in [1, 2]:
Just5810aa92001-06-24 15:12:48 +0000184 chunklen = stringToLong(f.read(4))
Just36183002000-03-28 10:38:43 +0000185 chunk = f.read(chunklen)
186 assert len(chunk) == chunklen
187 data.append(chunk)
Just7842e561999-12-16 21:34:53 +0000188 elif code == 3:
189 break
190 else:
Behdad Esfahboddc7e6f32013-11-27 02:44:56 -0500191 raise T1Error('bad chunk code: ' + repr(code))
Just5810aa92001-06-24 15:12:48 +0000192 if onlyHeader:
193 break
Just7842e561999-12-16 21:34:53 +0000194 f.close()
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500195 data = ''.join(data)
Just5810aa92001-06-24 15:12:48 +0000196 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000197 return data
198
Just5810aa92001-06-24 15:12:48 +0000199def readOther(path):
Just7842e561999-12-16 21:34:53 +0000200 """reads any (font) file, returns raw data"""
201 f = open(path, "rb")
202 data = f.read()
203 f.close()
Just5810aa92001-06-24 15:12:48 +0000204 assertType1(data)
Just7842e561999-12-16 21:34:53 +0000205
Just5810aa92001-06-24 15:12:48 +0000206 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000207 data = []
Just5810aa92001-06-24 15:12:48 +0000208 for isEncrypted, chunk in chunks:
209 if isEncrypted and isHex(chunk[:4]):
210 data.append(deHexString(chunk))
Just7842e561999-12-16 21:34:53 +0000211 else:
212 data.append(chunk)
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500213 return ''.join(data)
Just7842e561999-12-16 21:34:53 +0000214
215# file writing tools
216
Just5810aa92001-06-24 15:12:48 +0000217def writeLWFN(path, data):
Juste9601bf2001-07-30 19:04:40 +0000218 Res.FSpCreateResFile(path, "just", "LWFN", 0)
jvr91bca422012-10-18 12:49:22 +0000219 resRef = Res.FSOpenResFile(path, 2) # write-only
Just7842e561999-12-16 21:34:53 +0000220 try:
Juste9601bf2001-07-30 19:04:40 +0000221 Res.UseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000222 resID = 501
Just5810aa92001-06-24 15:12:48 +0000223 chunks = findEncryptedChunks(data)
224 for isEncrypted, chunk in chunks:
225 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000226 code = 2
227 else:
228 code = 1
229 while chunk:
230 res = Res.Resource(chr(code) + '\0' + chunk[:LWFNCHUNKSIZE - 2])
231 res.AddResource('POST', resID, '')
232 chunk = chunk[LWFNCHUNKSIZE - 2:]
233 resID = resID + 1
234 res = Res.Resource(chr(5) + '\0')
235 res.AddResource('POST', resID, '')
236 finally:
Juste9601bf2001-07-30 19:04:40 +0000237 Res.CloseResFile(resRef)
Just7842e561999-12-16 21:34:53 +0000238
Just5810aa92001-06-24 15:12:48 +0000239def writePFB(path, data):
240 chunks = findEncryptedChunks(data)
Just36183002000-03-28 10:38:43 +0000241 f = open(path, "wb")
Just7842e561999-12-16 21:34:53 +0000242 try:
Just5810aa92001-06-24 15:12:48 +0000243 for isEncrypted, chunk in chunks:
244 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000245 code = 2
246 else:
247 code = 1
248 f.write(chr(128) + chr(code))
Just5810aa92001-06-24 15:12:48 +0000249 f.write(longToString(len(chunk)))
Just7842e561999-12-16 21:34:53 +0000250 f.write(chunk)
251 f.write(chr(128) + chr(3))
252 finally:
253 f.close()
Just7842e561999-12-16 21:34:53 +0000254
Just5810aa92001-06-24 15:12:48 +0000255def writeOther(path, data, dohex = 0):
256 chunks = findEncryptedChunks(data)
Just7842e561999-12-16 21:34:53 +0000257 f = open(path, "wb")
258 try:
259 hexlinelen = HEXLINELENGTH / 2
Just5810aa92001-06-24 15:12:48 +0000260 for isEncrypted, chunk in chunks:
261 if isEncrypted:
Just7842e561999-12-16 21:34:53 +0000262 code = 2
263 else:
264 code = 1
265 if code == 2 and dohex:
266 while chunk:
Justc2be3d92000-01-12 19:15:57 +0000267 f.write(eexec.hexString(chunk[:hexlinelen]))
Just7842e561999-12-16 21:34:53 +0000268 f.write('\r')
269 chunk = chunk[hexlinelen:]
270 else:
271 f.write(chunk)
272 finally:
273 f.close()
Just7842e561999-12-16 21:34:53 +0000274
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:]
Behdad Esfahbod180ace62013-11-27 02:40:30 -0500299 if decrypted[-len(EEXECINTERNALEND)-1:-1] != EEXECINTERNALEND \
300 and decrypted[-len(EEXECINTERNALEND)-2:-2] != EEXECINTERNALEND:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500301 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)
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500309 return ''.join(data)
Just7842e561999-12-16 21:34:53 +0000310
Just5810aa92001-06-24 15:12:48 +0000311def findEncryptedChunks(data):
Just7842e561999-12-16 21:34:53 +0000312 chunks = []
Behdad Esfahbodac1b4352013-11-27 04:15:34 -0500313 while True:
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500314 eBegin = data.find(EEXECBEGIN)
Just5810aa92001-06-24 15:12:48 +0000315 if eBegin < 0:
Just7842e561999-12-16 21:34:53 +0000316 break
jvr90290b72001-11-28 12:22:15 +0000317 eBegin = eBegin + len(EEXECBEGIN) + 1
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500318 eEnd = data.find(EEXECEND, eBegin)
Just5810aa92001-06-24 15:12:48 +0000319 if eEnd < 0:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500320 raise T1Error("can't find end of eexec part")
jvrdb1f2802002-07-23 14:54:47 +0000321 cypherText = data[eBegin:eEnd + 2]
jvre56bc902008-03-10 21:58:00 +0000322 if isHex(cypherText[:4]):
323 cypherText = deHexString(cypherText)
jvrdb1f2802002-07-23 14:54:47 +0000324 plainText, R = eexec.decrypt(cypherText, 55665)
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500325 eEndLocal = plainText.find(EEXECINTERNALEND)
jvrdb1f2802002-07-23 14:54:47 +0000326 if eEndLocal < 0:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500327 raise T1Error("can't find end of eexec part")
jvr90290b72001-11-28 12:22:15 +0000328 chunks.append((0, data[:eBegin]))
jvre56bc902008-03-10 21:58:00 +0000329 chunks.append((1, cypherText[:eEndLocal + len(EEXECINTERNALEND) + 1]))
Just5810aa92001-06-24 15:12:48 +0000330 data = data[eEnd:]
Just7842e561999-12-16 21:34:53 +0000331 chunks.append((0, data))
332 return chunks
333
Just5810aa92001-06-24 15:12:48 +0000334def deHexString(hexstring):
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500335 return eexec.deHexString(''.join(hexstring.split()))
Just7842e561999-12-16 21:34:53 +0000336
337
338# Type 1 assertion
339
340_fontType1RE = re.compile(r"/FontType\s+1\s+def")
341
Just5810aa92001-06-24 15:12:48 +0000342def assertType1(data):
jvre56bc902008-03-10 21:58:00 +0000343 for head in ['%!PS-AdobeFont', '%!FontType1']:
Just7842e561999-12-16 21:34:53 +0000344 if data[:len(head)] == head:
345 break
346 else:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500347 raise T1Error("not a PostScript font")
Just7842e561999-12-16 21:34:53 +0000348 if not _fontType1RE.search(data):
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500349 raise T1Error("not a Type 1 font")
Behdad Esfahbod14fb0312013-11-27 05:47:34 -0500350 if data.find("currentfile eexec") < 0:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500351 raise T1Error("not an encrypted Type 1 font")
Just7842e561999-12-16 21:34:53 +0000352 # XXX what else?
353 return data
354
355
356# pfb helpers
357
Just5810aa92001-06-24 15:12:48 +0000358def longToString(long):
Just7842e561999-12-16 21:34:53 +0000359 str = ""
360 for i in range(4):
361 str = str + chr((long & (0xff << (i * 8))) >> i * 8)
362 return str
363
Just5810aa92001-06-24 15:12:48 +0000364def stringToLong(str):
Behdad Esfahbod180ace62013-11-27 02:40:30 -0500365 if len(str) != 4:
Behdad Esfahbodcd5aad92013-11-27 02:42:28 -0500366 raise ValueError('string must be 4 bytes long')
Just7842e561999-12-16 21:34:53 +0000367 long = 0
368 for i in range(4):
369 long = long + (ord(str[i]) << (i * 8))
370 return long
Just5810aa92001-06-24 15:12:48 +0000371