blob: 754c2b7448b54709e3410b9c09007d266f79f6bd [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 Esfahbod26429342013-12-19 11:53:47 -0500274otTables.ScriptList.mergeMap = {
275 'ScriptCount': sum,
276 'ScriptRecord': sumLists,
277}
278
279otTables.FeatureList.mergeMap = {
280 'FeatureCount': sum,
281 'FeatureRecord': sumLists,
282}
283
284otTables.LookupList.mergeMap = {
285 'LookupCount': sum,
286 'Lookup': sumLists,
287}
288
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500289otTables.Coverage.mergeMap = {
290 'glyphs': sumLists,
291}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400292
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500293otTables.ClassDef.mergeMap = {
294 'classDefs': sumDicts,
295}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400296
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500297otTables.LigCaretList.mergeMap = {
298 'Coverage': mergeObjects,
299 'LigGlyphCount': sum,
300 'LigGlyph': sumLists,
301}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400302
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500303otTables.AttachList.mergeMap = {
304 'Coverage': mergeObjects,
305 'GlyphCount': sum,
306 'AttachPoint': sumLists,
307}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400308
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500309# XXX Renumber MarkFilterSets of lookups
310otTables.MarkGlyphSetsDef.mergeMap = {
311 'MarkSetTableFormat': equal,
312 'MarkSetCount': sum,
313 'Coverage': sumLists,
314}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400315
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500316otTables.GDEF.mergeMap = {
317 '*': mergeObjects,
318 'Version': max,
319}
320
Behdad Esfahbod26429342013-12-19 11:53:47 -0500321otTables.GSUB.mergeMap = otTables.GPOS.mergeMap = {
322 '*': mergeObjects,
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500323 'Version': max,
Behdad Esfahbod26429342013-12-19 11:53:47 -0500324}
325
326ttLib.getTableClass('GDEF').mergeMap = \
327ttLib.getTableClass('GSUB').mergeMap = \
328ttLib.getTableClass('GPOS').mergeMap = \
329ttLib.getTableClass('BASE').mergeMap = \
330ttLib.getTableClass('JSTF').mergeMap = \
331ttLib.getTableClass('MATH').mergeMap = \
332{
333 'tableTag': equal,
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500334 'table': mergeObjects,
335}
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400336
Behdad Esfahbod26429342013-12-19 11:53:47 -0500337
338@_add_method(otTables.Feature)
339def mapLookups(self, lookupMap):
340 self.LookupListIndex = [lookupMap[i] for i in self.LookupListIndex]
341
342@_add_method(otTables.FeatureList)
343def mapLookups(self, lookupMap):
344 for f in self.FeatureRecord:
345 if not f or not f.Feature: continue
346 f.Feature.mapLookups(lookupMap)
347
348@_add_method(otTables.DefaultLangSys,
349 otTables.LangSys)
350def mapFeatures(self, featureMap):
351 self.FeatureIndex = [featureMap[i] for i in self.FeatureIndex]
352 if self.ReqFeatureIndex != 65535:
353 self.ReqFeatureIndex = featureMap[self.ReqFeatureIndex]
354
355@_add_method(otTables.Script)
356def mapFeatures(self, featureMap):
357 if self.DefaultLangSys:
358 self.DefaultLangSys.mapFeatures(featureMap)
359 for l in self.LangSysRecord:
360 if not l or not l.LangSys: continue
361 l.LangSys.mapFeatures(featureMap)
362
363@_add_method(otTables.ScriptList)
364def mapFeatures(self, feature_indices):
365 for s in self.ScriptRecord:
366 if not s or not s.Script: continue
367 s.Script.mapFeatures(featureMap)
368
369
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400370class Options(object):
371
372 class UnknownOptionError(Exception):
373 pass
374
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400375 def __init__(self, **kwargs):
376
377 self.set(**kwargs)
378
379 def set(self, **kwargs):
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500380 for k,v in kwargs.items():
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400381 if not hasattr(self, k):
382 raise self.UnknownOptionError("Unknown option '%s'" % k)
383 setattr(self, k, v)
384
385 def parse_opts(self, argv, ignore_unknown=False):
386 ret = []
387 opts = {}
388 for a in argv:
389 orig_a = a
390 if not a.startswith('--'):
391 ret.append(a)
392 continue
393 a = a[2:]
394 i = a.find('=')
395 op = '='
396 if i == -1:
397 if a.startswith("no-"):
398 k = a[3:]
399 v = False
400 else:
401 k = a
402 v = True
403 else:
404 k = a[:i]
405 if k[-1] in "-+":
406 op = k[-1]+'=' # Ops is '-=' or '+=' now.
407 k = k[:-1]
408 v = a[i+1:]
409 k = k.replace('-', '_')
410 if not hasattr(self, k):
411 if ignore_unknown == True or k in ignore_unknown:
412 ret.append(orig_a)
413 continue
414 else:
415 raise self.UnknownOptionError("Unknown option '%s'" % a)
416
417 ov = getattr(self, k)
418 if isinstance(ov, bool):
419 v = bool(v)
420 elif isinstance(ov, int):
421 v = int(v)
422 elif isinstance(ov, list):
423 vv = v.split(',')
424 if vv == ['']:
425 vv = []
426 vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv]
427 if op == '=':
428 v = vv
429 elif op == '+=':
430 v = ov
431 v.extend(vv)
432 elif op == '-=':
433 v = ov
434 for x in vv:
435 if x in v:
436 v.remove(x)
437 else:
438 assert 0
439
440 opts[k] = v
441 self.set(**opts)
442
443 return ret
444
445
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500446class Merger(object):
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400447
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400448 def __init__(self, options=None, log=None):
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400449
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400450 if not log:
451 log = Logger()
452 if not options:
453 options = Options()
454
455 self.options = options
456 self.log = log
457
458 def merge(self, fontfiles):
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400459
460 mega = ttLib.TTFont()
461
462 #
463 # Settle on a mega glyph order.
464 #
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400465 fonts = [ttLib.TTFont(fontfile) for fontfile in fontfiles]
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400466 glyphOrders = [font.getGlyphOrder() for font in fonts]
467 megaGlyphOrder = self._mergeGlyphOrders(glyphOrders)
468 # Reload fonts and set new glyph names on them.
469 # TODO Is it necessary to reload font? I think it is. At least
470 # it's safer, in case tables were loaded to provide glyph names.
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400471 fonts = [ttLib.TTFont(fontfile) for fontfile in fontfiles]
Behdad Esfahbod3235a042013-09-19 20:57:33 -0400472 for font,glyphOrder in zip(fonts, glyphOrders):
473 font.setGlyphOrder(glyphOrder)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400474 mega.setGlyphOrder(megaGlyphOrder)
475
Behdad Esfahbod26429342013-12-19 11:53:47 -0500476 for font in fonts:
477 self._preMerge(font)
478
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500479 allTags = reduce(set.union, (list(font.keys()) for font in fonts), set())
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400480 allTags.remove('GlyphOrder')
481 for tag in allTags:
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400482
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400483 clazz = ttLib.getTableClass(tag)
484
Behdad Esfahbod26429342013-12-19 11:53:47 -0500485 tables = [font.get(tag, NotImplemented) for font in fonts]
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500486 table = clazz(tag).merge(self, tables)
487 if table is not NotImplemented and table is not False:
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400488 mega[tag] = table
Behdad Esfahbodb640f742013-09-19 20:12:56 -0400489 self.log("Merged '%s'." % tag)
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400490 else:
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500491 self.log("Dropped '%s'." % tag)
Behdad Esfahbodb640f742013-09-19 20:12:56 -0400492 self.log.lapse("merge '%s'" % tag)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400493
Behdad Esfahbod26429342013-12-19 11:53:47 -0500494 self._postMerge(mega)
495
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400496 return mega
497
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400498 def _mergeGlyphOrders(self, glyphOrders):
Behdad Esfahbodc2e27fd2013-09-20 16:25:48 -0400499 """Modifies passed-in glyphOrders to reflect new glyph names.
500 Returns glyphOrder for the merged font."""
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400501 # Simply append font index to the glyph name for now.
Behdad Esfahbodc2e27fd2013-09-20 16:25:48 -0400502 # TODO Even this simplistic numbering can result in conflicts.
503 # But then again, we have to improve this soon anyway.
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400504 mega = []
505 for n,glyphOrder in enumerate(glyphOrders):
506 for i,glyphName in enumerate(glyphOrder):
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500507 glyphName += "#" + repr(n)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400508 glyphOrder[i] = glyphName
509 mega.append(glyphName)
510 return mega
511
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500512 def mergeObjects(self, returnTable, logic, tables):
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500513 # Right now we don't use self at all. Will use in the future
514 # for options and logging.
515
516 if logic is NotImplemented:
517 return NotImplemented
518
519 allKeys = set.union(set(), *(vars(table).keys() for table in tables if table is not NotImplemented))
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -0800520 for key in allKeys:
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -0800521 try:
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500522 mergeLogic = logic[key]
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -0800523 except KeyError:
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500524 try:
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500525 mergeLogic = logic['*']
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500526 except KeyError:
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500527 raise Exception("Don't know how to merge key %s of class %s" %
528 (key, returnTable.__class__.__name__))
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500529 if mergeLogic is NotImplemented:
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -0800530 continue
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500531 value = mergeLogic(getattr(table, key, NotImplemented) for table in tables)
532 if value is not NotImplemented:
533 setattr(returnTable, key, value)
534
535 return returnTable
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -0800536
Behdad Esfahbod26429342013-12-19 11:53:47 -0500537 def _preMerge(self, font):
538
539 return
540 GDEF = font.get('GDEF')
541 GSUB = font.get('GSUB')
542 GPOS = font.get('GPOS')
543
544 for t in [GSUB, GPOS]:
545 if not t or not t.table.LookupList or not t.table.FeatureList: continue
546 lookupMap = dict(enumerate(t.table.LookupList.Lookup))
547 t.table.FeatureList.mapLookups(lookupMap)
548
549 # TODO FeatureParams nameIDs
550
551 def _postMerge(self, font):
552 pass
553
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400554
555class Logger(object):
556
557 def __init__(self, verbose=False, xml=False, timing=False):
558 self.verbose = verbose
559 self.xml = xml
560 self.timing = timing
561 self.last_time = self.start_time = time.time()
562
563 def parse_opts(self, argv):
564 argv = argv[:]
565 for v in ['verbose', 'xml', 'timing']:
566 if "--"+v in argv:
567 setattr(self, v, True)
568 argv.remove("--"+v)
569 return argv
570
571 def __call__(self, *things):
572 if not self.verbose:
573 return
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500574 print(' '.join(str(x) for x in things))
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400575
576 def lapse(self, *things):
577 if not self.timing:
578 return
579 new_time = time.time()
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500580 print("Took %0.3fs to %s" %(new_time - self.last_time,
581 ' '.join(str(x) for x in things)))
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400582 self.last_time = new_time
583
584 def font(self, font, file=sys.stdout):
585 if not self.xml:
586 return
587 from fontTools.misc import xmlWriter
588 writer = xmlWriter.XMLWriter(file)
589 font.disassembleInstructions = False # Work around ttLib bug
590 for tag in font.keys():
591 writer.begintag(tag)
592 writer.newline()
593 font[tag].toXML(writer, font)
594 writer.endtag(tag)
595 writer.newline()
596
597
598__all__ = [
599 'Options',
600 'Merger',
601 'Logger',
602 'main'
603]
604
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400605def main(args):
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400606
607 log = Logger()
608 args = log.parse_opts(args)
609
610 options = Options()
611 args = options.parse_opts(args)
612
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400613 if len(args) < 1:
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500614 print("usage: pyftmerge font...", file=sys.stderr)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400615 sys.exit(1)
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400616
617 merger = Merger(options=options, log=log)
618 font = merger.merge(args)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400619 outfile = 'merged.ttf'
620 font.save(outfile)
Behdad Esfahbodb640f742013-09-19 20:12:56 -0400621 log.lapse("compile and save font")
622
623 log.last_time = log.start_time
624 log.lapse("make one with everything(TOTAL TIME)")
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400625
626if __name__ == "__main__":
627 main(sys.argv[1:])