blob: 18b05f14ee6a3a6e2684763e23daac1742afa281 [file] [log] [blame]
jvr1c803b62002-09-12 17:33:12 +00001"""\
2usage: ttx [options] inputfile1 [... inputfileN]
3
4 TTX %s -- From OpenType To XML And Back
5
6 If an input file is a TrueType or OpenType font file, it will be
7 dumped to an TTX file (an XML-based text format).
8 If an input file is a TTX file, it will be compiled to a TrueType
9 or OpenType font file.
10
11 Output files are created so they are unique: an existing file is
pabs3ca75e432011-10-30 12:26:09 +000012 never overwritten.
jvr1c803b62002-09-12 17:33:12 +000013
14 General options:
15 -h Help: print this message
16 -d <outputfolder> Specify a directory where the output files are
17 to be created.
pabs35f419332013-06-22 06:47:34 +000018 -o <outputfile> Specify a file to write the output to.
jvr1c803b62002-09-12 17:33:12 +000019 -v Verbose: more messages will be written to stdout about what
20 is being done.
Dave Crosslandb1585972013-09-04 13:16:39 +010021 -q Quiet: No messages will be written to stdout about what
22 is being done.
jvr823f8cd2006-10-21 14:12:38 +000023 -a allow virtual glyphs ID's on compile or decompile.
jvr1c803b62002-09-12 17:33:12 +000024
25 Dump options:
26 -l List table info: instead of dumping to a TTX file, list some
27 minimal info about each table.
28 -t <table> Specify a table to dump. Multiple -t options
29 are allowed. When no -t option is specified, all tables
30 will be dumped.
31 -x <table> Specify a table to exclude from the dump. Multiple
32 -x options are allowed. -t and -x are mutually exclusive.
33 -s Split tables: save the TTX data into separate TTX files per
34 table and write one small TTX file that contains references
35 to the individual table dumps. This file can be used as
36 input to ttx, as long as the table files are in the
37 same directory.
38 -i Do NOT disassemble TT instructions: when this option is given,
39 all TrueType programs (glyph programs, the font program and the
40 pre-program) will be written to the TTX file as hex data
41 instead of assembly. This saves some time and makes the TTX
42 file smaller.
Matt Fontaine7baa1362013-08-09 13:25:15 -070043 -z <format> Specify a bitmap data export option for EBDT:
44 {'raw', 'row', 'bitwise', 'extfile'} or for the CBDT:
45 {'raw', 'extfile'} Each option does one of the following:
46 -z raw
47 * export the bitmap data as a hex dump
48 -z row
49 * export each row as hex data
50 -z bitwise
51 * export each row as binary in an ASCII art style
52 -z extfile
53 * export the data as external files with XML refences
54 If no export format is specified 'raw' format is used.
jvr1bcc11d2008-03-01 09:42:58 +000055 -e Don't ignore decompilation errors, but show a full traceback
56 and abort.
pabs30a6dea02009-11-08 15:53:24 +000057 -y <number> Select font number for TrueType Collection,
pabs37e91e772009-02-22 08:55:00 +000058 starting from 0.
jvr1c803b62002-09-12 17:33:12 +000059
60 Compile options:
61 -m Merge with TrueType-input-file: specify a TrueType or OpenType
62 font file to be merged with the TTX file. This option is only
63 valid when at most one TTX file is specified.
pabs3ca75e432011-10-30 12:26:09 +000064 -b Don't recalc glyph bounding boxes: use the values in the TTX
jvr1c803b62002-09-12 17:33:12 +000065 file as-is.
66"""
67
68
69import sys
70import os
71import getopt
72import re
73from fontTools.ttLib import TTFont
jvr823f8cd2006-10-21 14:12:38 +000074from fontTools.ttLib.tables.otBase import OTLOffsetOverflowError
75from fontTools.ttLib.tables.otTables import fixLookupOverFlows, fixSubTableOverFlows
jvr45d1f3b2008-03-01 11:34:54 +000076from fontTools.misc.macCreatorType import getMacCreatorAndType
jvr1c803b62002-09-12 17:33:12 +000077from fontTools import version
78
79def usage():
80 print __doc__ % version
81 sys.exit(2)
82
jvr2e838ce2003-08-22 18:50:44 +000083
jvr1c803b62002-09-12 17:33:12 +000084numberAddedRE = re.compile("(.*)#\d+$")
pabs3278d4d82013-06-22 08:16:33 +000085opentypeheaderRE = re.compile('''sfntVersion=['"]OTTO["']''')
jvr1c803b62002-09-12 17:33:12 +000086
87def makeOutputFileName(input, outputDir, extension):
88 dir, file = os.path.split(input)
89 file, ext = os.path.splitext(file)
90 if outputDir:
91 dir = outputDir
92 output = os.path.join(dir, file + extension)
93 m = numberAddedRE.match(file)
94 if m:
95 file = m.group(1)
96 n = 1
97 while os.path.exists(output):
98 output = os.path.join(dir, file + "#" + repr(n) + extension)
99 n = n + 1
100 return output
101
102
103class Options:
104
105 listTables = 0
106 outputDir = None
pabs3fb37a242013-06-22 06:43:01 +0000107 outputFile = None
jvr1c803b62002-09-12 17:33:12 +0000108 verbose = 0
Dave Crosslandb1585972013-09-04 13:16:39 +0100109 quiet = 0
jvr1c803b62002-09-12 17:33:12 +0000110 splitTables = 0
111 disassembleInstructions = 1
112 mergeFile = None
113 recalcBBoxes = 1
jvr823f8cd2006-10-21 14:12:38 +0000114 allowVID = 0
jvr1bcc11d2008-03-01 09:42:58 +0000115 ignoreDecompileErrors = True
Matt Fontaine7baa1362013-08-09 13:25:15 -0700116 bitmapGlyphDataFormat = 'raw'
jvr1bcc11d2008-03-01 09:42:58 +0000117
jvr1c803b62002-09-12 17:33:12 +0000118 def __init__(self, rawOptions, numFiles):
119 self.onlyTables = []
120 self.skipTables = []
pabs37e91e772009-02-22 08:55:00 +0000121 self.fontNumber = -1
jvr1c803b62002-09-12 17:33:12 +0000122 for option, value in rawOptions:
123 # general options
124 if option == "-h":
125 print __doc__ % version
126 sys.exit(0)
127 elif option == "-d":
128 if not os.path.isdir(value):
129 print "The -d option value must be an existing directory"
130 sys.exit(2)
131 self.outputDir = value
pabs3fb37a242013-06-22 06:43:01 +0000132 elif option == "-o":
133 self.outputFile = value
jvr1c803b62002-09-12 17:33:12 +0000134 elif option == "-v":
135 self.verbose = 1
Dave Crosslandb1585972013-09-04 13:16:39 +0100136 elif option == "-q":
137 self.quiet = 1
jvr1c803b62002-09-12 17:33:12 +0000138 # dump options
139 elif option == "-l":
140 self.listTables = 1
141 elif option == "-t":
142 self.onlyTables.append(value)
143 elif option == "-x":
144 self.skipTables.append(value)
145 elif option == "-s":
146 self.splitTables = 1
147 elif option == "-i":
148 self.disassembleInstructions = 0
Matt Fontaine7baa1362013-08-09 13:25:15 -0700149 elif option == "-z":
150 validOptions = ('raw', 'row', 'bitwise', 'extfile')
151 if value not in validOptions:
152 print "-z does not allow %s as a format. Use %s" % (option, validOptions)
153 sys.exit(2)
154 self.bitmapGlyphDataFormat = value
pabs37e91e772009-02-22 08:55:00 +0000155 elif option == "-y":
156 self.fontNumber = int(value)
jvr1c803b62002-09-12 17:33:12 +0000157 # compile options
158 elif option == "-m":
159 self.mergeFile = value
160 elif option == "-b":
161 self.recalcBBoxes = 0
jvr823f8cd2006-10-21 14:12:38 +0000162 elif option == "-a":
163 self.allowVID = 1
jvr1bcc11d2008-03-01 09:42:58 +0000164 elif option == "-e":
165 self.ignoreDecompileErrors = False
jvr1c803b62002-09-12 17:33:12 +0000166 if self.onlyTables and self.skipTables:
jvr6588c4e2004-09-25 07:35:05 +0000167 print "-t and -x options are mutually exclusive"
jvr1c803b62002-09-12 17:33:12 +0000168 sys.exit(2)
169 if self.mergeFile and numFiles > 1:
jvr6588c4e2004-09-25 07:35:05 +0000170 print "Must specify exactly one TTX source file when using -m"
jvr1c803b62002-09-12 17:33:12 +0000171 sys.exit(2)
172
173
174def ttList(input, output, options):
jvrf7f0f742002-09-14 15:31:26 +0000175 import string
pabs37e91e772009-02-22 08:55:00 +0000176 ttf = TTFont(input, fontNumber=options.fontNumber)
jvr1c803b62002-09-12 17:33:12 +0000177 reader = ttf.reader
178 tags = reader.keys()
179 tags.sort()
180 print 'Listing table info for "%s":' % input
181 format = " %4s %10s %7s %7s"
182 print format % ("tag ", " checksum", " length", " offset")
183 print format % ("----", "----------", "-------", "-------")
184 for tag in tags:
185 entry = reader.tables[tag]
jvre0912bb2004-12-24 15:59:35 +0000186 checkSum = long(entry.checkSum)
187 if checkSum < 0:
188 checkSum = checkSum + 0x100000000L
189 checksum = "0x" + string.zfill(hex(checkSum)[2:-1], 8)
jvr1c803b62002-09-12 17:33:12 +0000190 print format % (tag, checksum, entry.length, entry.offset)
191 print
192 ttf.close()
193
194
195def ttDump(input, output, options):
Dave Crosslandb1585972013-09-04 13:16:39 +0100196 if not options.quiet:
197 print 'Dumping "%s" to "%s"...' % (input, output)
jvr1bcc11d2008-03-01 09:42:58 +0000198 ttf = TTFont(input, 0, verbose=options.verbose, allowVID=options.allowVID,
pabs37e91e772009-02-22 08:55:00 +0000199 ignoreDecompileErrors=options.ignoreDecompileErrors,
200 fontNumber=options.fontNumber)
jvr1c803b62002-09-12 17:33:12 +0000201 ttf.saveXML(output,
202 tables=options.onlyTables,
203 skipTables=options.skipTables,
204 splitTables=options.splitTables,
Matt Fontaine7baa1362013-08-09 13:25:15 -0700205 disassembleInstructions=options.disassembleInstructions,
206 bitmapGlyphDataFormat=options.bitmapGlyphDataFormat)
jvr1c803b62002-09-12 17:33:12 +0000207 ttf.close()
208
209
210def ttCompile(input, output, options):
Dave Crossland85af40e2013-09-04 13:30:21 +0100211 if not options.quiet:
212 print 'Compiling "%s" to "%s"...' % (input, output)
jvr1c803b62002-09-12 17:33:12 +0000213 ttf = TTFont(options.mergeFile,
214 recalcBBoxes=options.recalcBBoxes,
jvr823f8cd2006-10-21 14:12:38 +0000215 verbose=options.verbose, allowVID=options.allowVID)
Dave Crossland85af40e2013-09-04 13:30:21 +0100216 ttf.importXML(input, quiet=options.quiet)
jvr823f8cd2006-10-21 14:12:38 +0000217 try:
218 ttf.save(output)
219 except OTLOffsetOverflowError, e:
jvr142506b2008-03-09 20:39:38 +0000220 # XXX This shouldn't be here at all, it should be as close to the
221 # OTL code as possible.
jvr823f8cd2006-10-21 14:12:38 +0000222 overflowRecord = e.value
223 print "Attempting to fix OTLOffsetOverflowError", e
224 lastItem = overflowRecord
225 while 1:
226 ok = 0
227 if overflowRecord.itemName == None:
228 ok = fixLookupOverFlows(ttf, overflowRecord)
229 else:
230 ok = fixSubTableOverFlows(ttf, overflowRecord)
231 if not ok:
232 raise
233
234 try:
235 ttf.save(output)
236 break
237 except OTLOffsetOverflowError, e:
238 print "Attempting to fix OTLOffsetOverflowError", e
239 overflowRecord = e.value
240 if overflowRecord == lastItem:
241 raise
jvr1c803b62002-09-12 17:33:12 +0000242
243 if options.verbose:
244 import time
245 print "finished at", time.strftime("%H:%M:%S", time.localtime(time.time()))
246
247
248def guessFileType(fileName):
jvr2e838ce2003-08-22 18:50:44 +0000249 base, ext = os.path.splitext(fileName)
jvr1c803b62002-09-12 17:33:12 +0000250 try:
251 f = open(fileName, "rb")
252 except IOError:
253 return None
jvr45d1f3b2008-03-01 11:34:54 +0000254 cr, tp = getMacCreatorAndType(fileName)
255 if tp in ("sfnt", "FFIL"):
256 return "TTF"
257 if ext == ".dfont":
258 return "TTF"
jvr1c803b62002-09-12 17:33:12 +0000259 header = f.read(256)
260 head = header[:4]
261 if head == "OTTO":
262 return "OTF"
pabs37e91e772009-02-22 08:55:00 +0000263 elif head == "ttcf":
264 return "TTC"
jvr1c803b62002-09-12 17:33:12 +0000265 elif head in ("\0\1\0\0", "true"):
266 return "TTF"
267 elif head.lower() == "<?xm":
pabs3e83b4c42013-06-22 08:13:22 +0000268 if opentypeheaderRE.match(header):
jvr1c803b62002-09-12 17:33:12 +0000269 return "OTX"
270 else:
271 return "TTX"
jvr1c803b62002-09-12 17:33:12 +0000272 return None
273
274
275def parseOptions(args):
276 try:
Matt Fontaine7baa1362013-08-09 13:25:15 -0700277 rawOptions, files = getopt.getopt(args, "ld:o:vht:x:sim:z:baey:")
jvr1c803b62002-09-12 17:33:12 +0000278 except getopt.GetoptError:
279 usage()
280
281 if not files:
282 usage()
283
284 options = Options(rawOptions, len(files))
285 jobs = []
286
287 for input in files:
288 tp = guessFileType(input)
pabs37e91e772009-02-22 08:55:00 +0000289 if tp in ("OTF", "TTF", "TTC"):
jvr1c803b62002-09-12 17:33:12 +0000290 extension = ".ttx"
291 if options.listTables:
292 action = ttList
293 else:
294 action = ttDump
295 elif tp == "TTX":
296 extension = ".ttf"
297 action = ttCompile
298 elif tp == "OTX":
299 extension = ".otf"
300 action = ttCompile
301 else:
302 print 'Unknown file type: "%s"' % input
303 continue
304
pabs3fb37a242013-06-22 06:43:01 +0000305 if options.outputFile:
306 output = options.outputFile
307 else:
308 output = makeOutputFileName(input, options.outputDir, extension)
jvr1c803b62002-09-12 17:33:12 +0000309 jobs.append((action, input, output))
jvr2921bb22002-09-12 20:05:23 +0000310 return jobs, options
jvr1c803b62002-09-12 17:33:12 +0000311
312
313def process(jobs, options):
314 for action, input, output in jobs:
315 action(input, output, options)
316
317
318def waitForKeyPress():
319 """Force the DOS Prompt window to stay open so the user gets
320 a chance to see what's wrong."""
321 import msvcrt
322 print '(Hit any key to exit)'
323 while not msvcrt.kbhit():
324 pass
325
326
327def main(args):
328 jobs, options = parseOptions(args)
329 try:
330 process(jobs, options)
331 except KeyboardInterrupt:
332 print "(Cancelled.)"
333 except SystemExit:
334 if sys.platform == "win32":
335 waitForKeyPress()
336 else:
337 raise
338 except:
339 if sys.platform == "win32":
340 import traceback
341 traceback.print_exc()
342 waitForKeyPress()
343 else:
344 raise
345
346
347if __name__ == "__main__":
348 main(sys.argv[1:])