blob: 9e1c6d8dc7aff81052d93b022d3158ce0b54ff7b [file] [log] [blame]
Behdad Esfahbod45d2f382013-09-18 20:47:53 -04001# Copyright 2013 Google, Inc. All Rights Reserved.
2#
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -08003# Google Author(s): Behdad Esfahbod, Roozbeh Pournader
Behdad Esfahbod45d2f382013-09-18 20:47:53 -04004
5"""Font merger.
6"""
7
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -05008from __future__ import print_function, division
9from fontTools.misc.py23 import *
10from fontTools import ttLib, cffLib
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -080011from fontTools.ttLib.tables import otTables, _h_e_a_d
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -050012from fontTools.ttLib.tables.DefaultTable import DefaultTable
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -050013from functools import reduce
Behdad Esfahbod45d2f382013-09-18 20:47:53 -040014import sys
Behdad Esfahbodf2d59822013-09-19 16:16:39 -040015import time
Behdad Esfahbod49028b32013-12-18 17:34:17 -050016import operator
Behdad Esfahbod45d2f382013-09-18 20:47:53 -040017
Behdad Esfahbod45d2f382013-09-18 20:47:53 -040018
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -050019def _add_method(*clazzes, **kwargs):
Behdad Esfahbodc855f3a2013-09-19 20:09:23 -040020 """Returns a decorator function that adds a new method to one or
21 more classes."""
22 def wrapper(method):
23 for clazz in clazzes:
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -050024 if not kwargs.get('allowDefaultTable', False):
25 assert clazz != DefaultTable, 'Oops, table class not found.'
26 assert method.__name__ not in clazz.__dict__, \
Behdad Esfahbodc855f3a2013-09-19 20:09:23 -040027 "Oops, class '%s' has method '%s'." % (clazz.__name__,
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -050028 method.__name__)
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -050029 setattr(clazz, method.__name__, method)
Behdad Esfahbodc855f3a2013-09-19 20:09:23 -040030 return None
31 return wrapper
Behdad Esfahbod45d2f382013-09-18 20:47:53 -040032
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -080033# General utility functions for merging values from different fonts
Behdad Esfahbod92fd5662013-12-19 04:56:50 -050034
Behdad Esfahbod49028b32013-12-18 17:34:17 -050035def equal(lst):
36 t = iter(lst)
37 first = next(t)
38 assert all(item == first for item in t)
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -080039 return first
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -080040
41def first(lst):
Behdad Esfahbod49028b32013-12-18 17:34:17 -050042 return next(iter(lst))
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -080043
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -080044def recalculate(lst):
Behdad Esfahbod92fd5662013-12-19 04:56:50 -050045 return NotImplemented
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -080046
47def current_time(lst):
Behdad Esfahbod49028b32013-12-18 17:34:17 -050048 return int(time.time() - _h_e_a_d.mac_epoch_diff)
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -080049
50def bitwise_or(lst):
Behdad Esfahbod49028b32013-12-18 17:34:17 -050051 return reduce(operator.or_, lst)
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -080052
Behdad Esfahbod92fd5662013-12-19 04:56:50 -050053def avg_int(lst):
54 lst = list(lst)
55 return sum(lst) // len(lst)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -040056
Behdad Esfahbod92fd5662013-12-19 04:56:50 -050057def nonnone(func):
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -050058 """Returns a filter func that when called with a list,
59 only calls func on the non-None items of the list, and
60 only so if there's at least one non-None item in the
Behdad Esfahbod92fd5662013-12-19 04:56:50 -050061 list. Otherwise returns None."""
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -050062
63 def wrapper(lst):
64 items = [item for item in lst if item is not None]
65 return func(items) if items else None
66
67 return wrapper
68
Behdad Esfahbod92fd5662013-12-19 04:56:50 -050069def implemented(func):
70 """Returns a filter func that when called with a list,
71 only calls func on the non-NotImplemented items of the list,
72 and only so if there's at least one item remaining.
73 Otherwise returns NotImplemented."""
74
75 def wrapper(lst):
76 items = [item for item in lst if item is not NotImplemented]
77 return func(items) if items else NotImplemented
78
79 return wrapper
80
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -050081def sumLists(lst):
82 l = []
83 for item in lst:
84 l.extend(item)
85 return l
86
87def sumDicts(lst):
88 d = {}
89 for item in lst:
90 d.update(item)
91 return d
92
Behdad Esfahbod12dd5472013-12-19 05:58:06 -050093def mergeObjects(lst):
94 lst = [item for item in lst if item is not None and item is not NotImplemented]
95 if not lst:
96 return None # Not all can be NotImplemented
97
98 clazz = lst[0].__class__
99 assert all(type(item) == clazz for item in lst), lst
100 logic = clazz.mergeMap
101 returnTable = clazz()
102
103 allKeys = set.union(set(), *(vars(table).keys() for table in lst))
104 for key in allKeys:
105 try:
106 mergeLogic = logic[key]
107 except KeyError:
108 try:
109 mergeLogic = logic['*']
110 except KeyError:
111 raise Exception("Don't know how to merge key %s of class %s" %
112 (key, clazz.__name__))
113 if mergeLogic is NotImplemented:
114 continue
115 value = mergeLogic(getattr(table, key, NotImplemented) for table in lst)
116 if value is not NotImplemented:
117 setattr(returnTable, key, value)
118
119 return returnTable
120
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500121
122@_add_method(DefaultTable, allowDefaultTable=True)
Behdad Esfahbod3b36f552013-12-19 04:45:17 -0500123def merge(self, m, tables):
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500124 if not hasattr(self, 'mergeMap'):
125 m.log("Don't know how to merge '%s'." % self.tableTag)
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500126 return NotImplemented
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500127
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500128 return m.mergeObjects(self, self.mergeMap, tables)
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500129
130ttLib.getTableClass('maxp').mergeMap = {
131 '*': max,
132 'tableTag': equal,
133 'tableVersion': equal,
134 'numGlyphs': sum,
135 'maxStorage': max, # FIXME: may need to be changed to sum
136 'maxFunctionDefs': sum,
137 'maxInstructionDefs': sum,
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400138 # TODO When we correctly merge hinting data, update these values:
139 # maxFunctionDefs, maxInstructionDefs, maxSizeOfInstructions
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500140}
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400141
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500142ttLib.getTableClass('head').mergeMap = {
143 'tableTag': equal,
144 'tableVersion': max,
145 'fontRevision': max,
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500146 'checkSumAdjustment': lambda lst: 0, # We need *something* here
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500147 'magicNumber': equal,
148 'flags': first, # FIXME: replace with bit-sensitive code
149 'unitsPerEm': equal,
150 'created': current_time,
151 'modified': current_time,
152 'xMin': min,
153 'yMin': min,
154 'xMax': max,
155 'yMax': max,
156 'macStyle': first,
157 'lowestRecPPEM': max,
158 'fontDirectionHint': lambda lst: 2,
159 'indexToLocFormat': recalculate,
160 'glyphDataFormat': equal,
161}
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400162
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500163ttLib.getTableClass('hhea').mergeMap = {
164 '*': equal,
165 'tableTag': equal,
166 'tableVersion': max,
167 'ascent': max,
168 'descent': min,
169 'lineGap': max,
170 'advanceWidthMax': max,
171 'minLeftSideBearing': min,
172 'minRightSideBearing': min,
173 'xMaxExtent': max,
174 'caretSlopeRise': first, # FIXME
175 'caretSlopeRun': first, # FIXME
176 'caretOffset': first, # FIXME
177 'numberOfHMetrics': recalculate,
178}
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400179
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500180ttLib.getTableClass('OS/2').mergeMap = {
181 '*': first,
182 'tableTag': equal,
183 'version': max,
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500184 'xAvgCharWidth': avg_int, # Apparently fontTools doesn't recalc this
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500185 'fsType': first, # FIXME
186 'panose': first, # FIXME?
187 'ulUnicodeRange1': bitwise_or,
188 'ulUnicodeRange2': bitwise_or,
189 'ulUnicodeRange3': bitwise_or,
190 'ulUnicodeRange4': bitwise_or,
191 'fsFirstCharIndex': min,
192 'fsLastCharIndex': max,
193 'sTypoAscender': max,
194 'sTypoDescender': min,
195 'sTypoLineGap': max,
196 'usWinAscent': max,
197 'usWinDescent': max,
198 'ulCodePageRange1': bitwise_or,
199 'ulCodePageRange2': bitwise_or,
200 'usMaxContex': max,
Behdad Esfahboddb2410a2013-12-19 03:30:29 -0500201 # TODO version 5
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500202}
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400203
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500204ttLib.getTableClass('post').mergeMap = {
205 '*': first,
206 'tableTag': equal,
207 'formatType': max,
208 'isFixedPitch': min,
209 'minMemType42': max,
210 'maxMemType42': lambda lst: 0,
211 'minMemType1': max,
212 'maxMemType1': lambda lst: 0,
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500213 'mapping': implemented(sumDicts),
214 'extraNames': lambda lst: [][:],
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500215}
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400216
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500217ttLib.getTableClass('vmtx').mergeMap = ttLib.getTableClass('hmtx').mergeMap = {
218 'tableTag': equal,
219 'metrics': sumDicts,
220}
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400221
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500222ttLib.getTableClass('loca').mergeMap = {
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500223 '*': recalculate,
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500224 'tableTag': equal,
225}
226
227ttLib.getTableClass('glyf').mergeMap = {
228 'tableTag': equal,
229 'glyphs': sumDicts,
230 'glyphOrder': sumLists,
231}
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400232
Behdad Esfahbodbe4ecc72013-09-19 20:37:01 -0400233@_add_method(ttLib.getTableClass('glyf'))
Behdad Esfahbod3b36f552013-12-19 04:45:17 -0500234def merge(self, m, tables):
235 for table in tables:
Behdad Esfahbod43650332013-09-20 16:33:33 -0400236 for g in table.glyphs.values():
237 # Drop hints for now, since we don't remap
238 # functions / CVT values.
239 g.removeHinting()
240 # Expand composite glyphs to load their
241 # composite glyph names.
242 if g.isComposite():
243 g.expand(table)
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500244 return DefaultTable.merge(self, m, tables)
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400245
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500246ttLib.getTableClass('prep').mergeMap = NotImplemented
247ttLib.getTableClass('fpgm').mergeMap = NotImplemented
248ttLib.getTableClass('cvt ').mergeMap = NotImplemented
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400249
Behdad Esfahbodbe4ecc72013-09-19 20:37:01 -0400250@_add_method(ttLib.getTableClass('cmap'))
Behdad Esfahbod3b36f552013-12-19 04:45:17 -0500251def merge(self, m, tables):
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400252 # TODO Handle format=14.
Behdad Esfahbod3b36f552013-12-19 04:45:17 -0500253 cmapTables = [t for table in tables for t in table.tables
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400254 if t.platformID == 3 and t.platEncID in [1, 10]]
255 # TODO Better handle format-4 and format-12 coexisting in same font.
256 # TODO Insert both a format-4 and format-12 if needed.
Behdad Esfahbodbe4ecc72013-09-19 20:37:01 -0400257 module = ttLib.getTableModule('cmap')
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400258 assert all(t.format in [4, 12] for t in cmapTables)
259 format = max(t.format for t in cmapTables)
260 cmapTable = module.cmap_classes[format](format)
261 cmapTable.cmap = {}
262 cmapTable.platformID = 3
263 cmapTable.platEncID = max(t.platEncID for t in cmapTables)
264 cmapTable.language = 0
265 for table in cmapTables:
266 # TODO handle duplicates.
267 cmapTable.cmap.update(table.cmap)
268 self.tableVersion = 0
269 self.tables = [cmapTable]
270 self.numSubTables = len(self.tables)
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500271 return self
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400272
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400273
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500274otTables.Coverage.mergeMap = {
275 'glyphs': sumLists,
276}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400277
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500278otTables.ClassDef.mergeMap = {
279 'classDefs': sumDicts,
280}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400281
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500282otTables.LigCaretList.mergeMap = {
283 'Coverage': mergeObjects,
284 'LigGlyphCount': sum,
285 'LigGlyph': sumLists,
286}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400287
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500288otTables.AttachList.mergeMap = {
289 'Coverage': mergeObjects,
290 'GlyphCount': sum,
291 'AttachPoint': sumLists,
292}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400293
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500294# XXX Renumber MarkFilterSets of lookups
295otTables.MarkGlyphSetsDef.mergeMap = {
296 'MarkSetTableFormat': equal,
297 'MarkSetCount': sum,
298 'Coverage': sumLists,
299}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400300
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500301otTables.GDEF.mergeMap = {
302 '*': mergeObjects,
303 'Version': max,
304}
305
306ttLib.getTableClass('GDEF').mergeMap = {
307 'tableTag': equal,
308 'Version': max,
309 'table': mergeObjects,
310}
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400311
312class Options(object):
313
314 class UnknownOptionError(Exception):
315 pass
316
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400317 def __init__(self, **kwargs):
318
319 self.set(**kwargs)
320
321 def set(self, **kwargs):
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500322 for k,v in kwargs.items():
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400323 if not hasattr(self, k):
324 raise self.UnknownOptionError("Unknown option '%s'" % k)
325 setattr(self, k, v)
326
327 def parse_opts(self, argv, ignore_unknown=False):
328 ret = []
329 opts = {}
330 for a in argv:
331 orig_a = a
332 if not a.startswith('--'):
333 ret.append(a)
334 continue
335 a = a[2:]
336 i = a.find('=')
337 op = '='
338 if i == -1:
339 if a.startswith("no-"):
340 k = a[3:]
341 v = False
342 else:
343 k = a
344 v = True
345 else:
346 k = a[:i]
347 if k[-1] in "-+":
348 op = k[-1]+'=' # Ops is '-=' or '+=' now.
349 k = k[:-1]
350 v = a[i+1:]
351 k = k.replace('-', '_')
352 if not hasattr(self, k):
353 if ignore_unknown == True or k in ignore_unknown:
354 ret.append(orig_a)
355 continue
356 else:
357 raise self.UnknownOptionError("Unknown option '%s'" % a)
358
359 ov = getattr(self, k)
360 if isinstance(ov, bool):
361 v = bool(v)
362 elif isinstance(ov, int):
363 v = int(v)
364 elif isinstance(ov, list):
365 vv = v.split(',')
366 if vv == ['']:
367 vv = []
368 vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv]
369 if op == '=':
370 v = vv
371 elif op == '+=':
372 v = ov
373 v.extend(vv)
374 elif op == '-=':
375 v = ov
376 for x in vv:
377 if x in v:
378 v.remove(x)
379 else:
380 assert 0
381
382 opts[k] = v
383 self.set(**opts)
384
385 return ret
386
387
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500388class Merger(object):
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400389
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400390 def __init__(self, options=None, log=None):
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400391
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400392 if not log:
393 log = Logger()
394 if not options:
395 options = Options()
396
397 self.options = options
398 self.log = log
399
400 def merge(self, fontfiles):
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400401
402 mega = ttLib.TTFont()
403
404 #
405 # Settle on a mega glyph order.
406 #
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400407 fonts = [ttLib.TTFont(fontfile) for fontfile in fontfiles]
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400408 glyphOrders = [font.getGlyphOrder() for font in fonts]
409 megaGlyphOrder = self._mergeGlyphOrders(glyphOrders)
410 # Reload fonts and set new glyph names on them.
411 # TODO Is it necessary to reload font? I think it is. At least
412 # it's safer, in case tables were loaded to provide glyph names.
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400413 fonts = [ttLib.TTFont(fontfile) for fontfile in fontfiles]
Behdad Esfahbod3235a042013-09-19 20:57:33 -0400414 for font,glyphOrder in zip(fonts, glyphOrders):
415 font.setGlyphOrder(glyphOrder)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400416 mega.setGlyphOrder(megaGlyphOrder)
417
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500418 allTags = reduce(set.union, (list(font.keys()) for font in fonts), set())
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400419 allTags.remove('GlyphOrder')
420 for tag in allTags:
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400421
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400422 clazz = ttLib.getTableClass(tag)
423
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500424 tables = [font[tag] if font.has_key(tag) else NotImplemented for font in fonts]
425 table = clazz(tag).merge(self, tables)
426 if table is not NotImplemented and table is not False:
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400427 mega[tag] = table
Behdad Esfahbodb640f742013-09-19 20:12:56 -0400428 self.log("Merged '%s'." % tag)
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400429 else:
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500430 self.log("Dropped '%s'." % tag)
Behdad Esfahbodb640f742013-09-19 20:12:56 -0400431 self.log.lapse("merge '%s'" % tag)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400432
433 return mega
434
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400435 def _mergeGlyphOrders(self, glyphOrders):
Behdad Esfahbodc2e27fd2013-09-20 16:25:48 -0400436 """Modifies passed-in glyphOrders to reflect new glyph names.
437 Returns glyphOrder for the merged font."""
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400438 # Simply append font index to the glyph name for now.
Behdad Esfahbodc2e27fd2013-09-20 16:25:48 -0400439 # TODO Even this simplistic numbering can result in conflicts.
440 # But then again, we have to improve this soon anyway.
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400441 mega = []
442 for n,glyphOrder in enumerate(glyphOrders):
443 for i,glyphName in enumerate(glyphOrder):
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500444 glyphName += "#" + repr(n)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400445 glyphOrder[i] = glyphName
446 mega.append(glyphName)
447 return mega
448
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500449 def mergeObjects(self, returnTable, logic, tables):
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500450 # Right now we don't use self at all. Will use in the future
451 # for options and logging.
452
453 if logic is NotImplemented:
454 return NotImplemented
455
456 allKeys = set.union(set(), *(vars(table).keys() for table in tables if table is not NotImplemented))
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -0800457 for key in allKeys:
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -0800458 try:
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500459 mergeLogic = logic[key]
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -0800460 except KeyError:
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500461 try:
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500462 mergeLogic = logic['*']
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500463 except KeyError:
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500464 raise Exception("Don't know how to merge key %s of class %s" %
465 (key, returnTable.__class__.__name__))
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500466 if mergeLogic is NotImplemented:
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -0800467 continue
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500468 value = mergeLogic(getattr(table, key, NotImplemented) for table in tables)
469 if value is not NotImplemented:
470 setattr(returnTable, key, value)
471
472 return returnTable
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -0800473
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400474
475class Logger(object):
476
477 def __init__(self, verbose=False, xml=False, timing=False):
478 self.verbose = verbose
479 self.xml = xml
480 self.timing = timing
481 self.last_time = self.start_time = time.time()
482
483 def parse_opts(self, argv):
484 argv = argv[:]
485 for v in ['verbose', 'xml', 'timing']:
486 if "--"+v in argv:
487 setattr(self, v, True)
488 argv.remove("--"+v)
489 return argv
490
491 def __call__(self, *things):
492 if not self.verbose:
493 return
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500494 print(' '.join(str(x) for x in things))
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400495
496 def lapse(self, *things):
497 if not self.timing:
498 return
499 new_time = time.time()
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500500 print("Took %0.3fs to %s" %(new_time - self.last_time,
501 ' '.join(str(x) for x in things)))
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400502 self.last_time = new_time
503
504 def font(self, font, file=sys.stdout):
505 if not self.xml:
506 return
507 from fontTools.misc import xmlWriter
508 writer = xmlWriter.XMLWriter(file)
509 font.disassembleInstructions = False # Work around ttLib bug
510 for tag in font.keys():
511 writer.begintag(tag)
512 writer.newline()
513 font[tag].toXML(writer, font)
514 writer.endtag(tag)
515 writer.newline()
516
517
518__all__ = [
519 'Options',
520 'Merger',
521 'Logger',
522 'main'
523]
524
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400525def main(args):
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400526
527 log = Logger()
528 args = log.parse_opts(args)
529
530 options = Options()
531 args = options.parse_opts(args)
532
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400533 if len(args) < 1:
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500534 print("usage: pyftmerge font...", file=sys.stderr)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400535 sys.exit(1)
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400536
537 merger = Merger(options=options, log=log)
538 font = merger.merge(args)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400539 outfile = 'merged.ttf'
540 font.save(outfile)
Behdad Esfahbodb640f742013-09-19 20:12:56 -0400541 log.lapse("compile and save font")
542
543 log.last_time = log.start_time
544 log.lapse("make one with everything(TOTAL TIME)")
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400545
546if __name__ == "__main__":
547 main(sys.argv[1:])