blob: 28195d1ffb061a91dd35ecfefa74f85227f31836 [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 Esfahbod1ae29592014-01-14 15:07:50 +08008from __future__ import print_function, division, absolute_import
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -05009from 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."""
Behdad Esfahbodc68c0ff2013-12-19 14:19:23 -050022 allowDefault = kwargs.get('allowDefaultTable', False)
Behdad Esfahbodc855f3a2013-09-19 20:09:23 -040023 def wrapper(method):
24 for clazz in clazzes:
Behdad Esfahbod35e3c722013-12-20 21:34:09 -050025 assert allowDefault or clazz != DefaultTable, 'Oops, table class not found.'
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -050026 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):
Behdad Esfahbod477dad12014-03-28 13:52:48 -070036 lst = list(lst)
Behdad Esfahbod49028b32013-12-18 17:34:17 -050037 t = iter(lst)
38 first = next(t)
Behdad Esfahbod477dad12014-03-28 13:52:48 -070039 assert all(item == first for item in t), "Expected all items to be equal: %s" % lst
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -080040 return first
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -080041
42def first(lst):
Behdad Esfahbod49028b32013-12-18 17:34:17 -050043 return next(iter(lst))
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -080044
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -080045def recalculate(lst):
Behdad Esfahbod92fd5662013-12-19 04:56:50 -050046 return NotImplemented
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -080047
48def current_time(lst):
Behdad Esfahbod49028b32013-12-18 17:34:17 -050049 return int(time.time() - _h_e_a_d.mac_epoch_diff)
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -080050
Roozbeh Pournader642eaf12013-12-21 01:04:18 -080051def bitwise_and(lst):
52 return reduce(operator.and_, lst)
53
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -080054def bitwise_or(lst):
Behdad Esfahbod49028b32013-12-18 17:34:17 -050055 return reduce(operator.or_, lst)
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -080056
Behdad Esfahbod92fd5662013-12-19 04:56:50 -050057def avg_int(lst):
58 lst = list(lst)
59 return sum(lst) // len(lst)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -040060
Behdad Esfahbod0d5fcf42014-03-28 14:37:32 -070061def onlyExisting(func):
Behdad Esfahbod92fd5662013-12-19 04:56:50 -050062 """Returns a filter func that when called with a list,
63 only calls func on the non-NotImplemented items of the list,
64 and only so if there's at least one item remaining.
65 Otherwise returns NotImplemented."""
66
67 def wrapper(lst):
68 items = [item for item in lst if item is not NotImplemented]
69 return func(items) if items else NotImplemented
70
71 return wrapper
72
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -050073def sumLists(lst):
74 l = []
75 for item in lst:
76 l.extend(item)
77 return l
78
79def sumDicts(lst):
80 d = {}
81 for item in lst:
82 d.update(item)
83 return d
84
Behdad Esfahbod12dd5472013-12-19 05:58:06 -050085def mergeObjects(lst):
86 lst = [item for item in lst if item is not None and item is not NotImplemented]
87 if not lst:
88 return None # Not all can be NotImplemented
89
90 clazz = lst[0].__class__
91 assert all(type(item) == clazz for item in lst), lst
92 logic = clazz.mergeMap
93 returnTable = clazz()
Behdad Esfahbod82c54632014-03-28 14:41:53 -070094 returnDict = {}
Behdad Esfahbod12dd5472013-12-19 05:58:06 -050095
96 allKeys = set.union(set(), *(vars(table).keys() for table in lst))
97 for key in allKeys:
98 try:
99 mergeLogic = logic[key]
100 except KeyError:
101 try:
102 mergeLogic = logic['*']
103 except KeyError:
104 raise Exception("Don't know how to merge key %s of class %s" %
105 (key, clazz.__name__))
106 if mergeLogic is NotImplemented:
107 continue
108 value = mergeLogic(getattr(table, key, NotImplemented) for table in lst)
109 if value is not NotImplemented:
Behdad Esfahbod82c54632014-03-28 14:41:53 -0700110 returnDict[key] = value
111
112 returnTable.__dict__ = returnDict
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500113
114 return returnTable
115
Behdad Esfahbod201a6812014-03-28 14:58:12 -0700116def mergeBits(bitmap):
117
118 def wrapper(lst):
119 lst = list(lst)
120 returnValue = 0
121 for bitNumber in range(bitmap['size']):
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800122 try:
Behdad Esfahbod201a6812014-03-28 14:58:12 -0700123 mergeLogic = bitmap[bitNumber]
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800124 except KeyError:
Behdad Esfahbod201a6812014-03-28 14:58:12 -0700125 try:
126 mergeLogic = bitmap['*']
127 except KeyError:
128 raise Exception("Don't know how to merge bit %s" % bitNumber)
129 shiftedBit = 1 << bitNumber
130 mergedValue = mergeLogic(bool(item & shiftedBit) for item in lst)
131 returnValue |= mergedValue << bitNumber
132 return returnValue
133
134 return wrapper
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800135
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500136
137@_add_method(DefaultTable, allowDefaultTable=True)
Behdad Esfahbod3b36f552013-12-19 04:45:17 -0500138def merge(self, m, tables):
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500139 if not hasattr(self, 'mergeMap'):
140 m.log("Don't know how to merge '%s'." % self.tableTag)
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500141 return NotImplemented
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500142
Behdad Esfahbod27c71f92014-01-27 21:01:45 -0500143 logic = self.mergeMap
144
145 if isinstance(logic, dict):
146 return m.mergeObjects(self, self.mergeMap, tables)
147 else:
148 return logic(tables)
149
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500150
151ttLib.getTableClass('maxp').mergeMap = {
152 '*': max,
153 'tableTag': equal,
154 'tableVersion': equal,
155 'numGlyphs': sum,
Behdad Esfahbod27c71f92014-01-27 21:01:45 -0500156 'maxStorage': first,
157 'maxFunctionDefs': first,
158 'maxInstructionDefs': first,
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400159 # TODO When we correctly merge hinting data, update these values:
160 # maxFunctionDefs, maxInstructionDefs, maxSizeOfInstructions
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500161}
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400162
Behdad Esfahbodb8039e22014-03-28 13:54:37 -0700163headFlagsMergeBitMap = {
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800164 'size': 16,
165 '*': bitwise_or,
166 1: bitwise_and, # Baseline at y = 0
167 2: bitwise_and, # lsb at x = 0
168 3: bitwise_and, # Force ppem to integer values. FIXME?
169 5: bitwise_and, # Font is vertical
170 6: lambda bit: 0, # Always set to zero
171 11: bitwise_and, # Font data is 'lossless'
172 13: bitwise_and, # Optimized for ClearType
173 14: bitwise_and, # Last resort font. FIXME? equal or first may be better
174 15: lambda bit: 0, # Always set to zero
175}
176
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500177ttLib.getTableClass('head').mergeMap = {
178 'tableTag': equal,
179 'tableVersion': max,
180 'fontRevision': max,
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500181 'checkSumAdjustment': lambda lst: 0, # We need *something* here
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500182 'magicNumber': equal,
Behdad Esfahbod201a6812014-03-28 14:58:12 -0700183 'flags': mergeBits(headFlagsMergeBitMap),
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500184 'unitsPerEm': equal,
185 'created': current_time,
186 'modified': current_time,
187 'xMin': min,
188 'yMin': min,
189 'xMax': max,
190 'yMax': max,
191 'macStyle': first,
192 'lowestRecPPEM': max,
193 'fontDirectionHint': lambda lst: 2,
194 'indexToLocFormat': recalculate,
195 'glyphDataFormat': equal,
196}
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400197
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500198ttLib.getTableClass('hhea').mergeMap = {
199 '*': equal,
200 'tableTag': equal,
201 'tableVersion': max,
202 'ascent': max,
203 'descent': min,
204 'lineGap': max,
205 'advanceWidthMax': max,
206 'minLeftSideBearing': min,
207 'minRightSideBearing': min,
208 'xMaxExtent': max,
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800209 'caretSlopeRise': first,
210 'caretSlopeRun': first,
211 'caretOffset': first,
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500212 'numberOfHMetrics': recalculate,
213}
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400214
Behdad Esfahbodb8039e22014-03-28 13:54:37 -0700215os2FsTypeMergeBitMap = {
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800216 'size': 16,
217 '*': lambda bit: 0,
218 1: bitwise_or, # no embedding permitted
219 2: bitwise_and, # allow previewing and printing documents
220 3: bitwise_and, # allow editing documents
221 8: bitwise_or, # no subsetting permitted
222 9: bitwise_or, # no embedding of outlines permitted
223}
224
225def mergeOs2FsType(lst):
226 lst = list(lst)
227 if all(item == 0 for item in lst):
228 return 0
229
230 # Compute least restrictive logic for each fsType value
231 for i in range(len(lst)):
232 # unset bit 1 (no embedding permitted) if either bit 2 or 3 is set
233 if lst[i] & 0x000C:
234 lst[i] &= ~0x0002
235 # set bit 2 (allow previewing) if bit 3 is set (allow editing)
236 elif lst[i] & 0x0008:
237 lst[i] |= 0x0004
238 # set bits 2 and 3 if everything is allowed
239 elif lst[i] == 0:
240 lst[i] = 0x000C
241
Behdad Esfahbod201a6812014-03-28 14:58:12 -0700242 fsType = mergeBits(os2FsTypeMergeBitMap)(lst)
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800243 # unset bits 2 and 3 if bit 1 is set (some font is "no embedding")
244 if fsType & 0x0002:
245 fsType &= ~0x000C
246 return fsType
247
248
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500249ttLib.getTableClass('OS/2').mergeMap = {
250 '*': first,
251 'tableTag': equal,
252 'version': max,
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500253 'xAvgCharWidth': avg_int, # Apparently fontTools doesn't recalc this
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800254 'fsType': mergeOs2FsType, # Will be overwritten
255 'panose': first, # FIXME: should really be the first Latin font
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500256 'ulUnicodeRange1': bitwise_or,
257 'ulUnicodeRange2': bitwise_or,
258 'ulUnicodeRange3': bitwise_or,
259 'ulUnicodeRange4': bitwise_or,
260 'fsFirstCharIndex': min,
261 'fsLastCharIndex': max,
262 'sTypoAscender': max,
263 'sTypoDescender': min,
264 'sTypoLineGap': max,
265 'usWinAscent': max,
266 'usWinDescent': max,
Behdad Esfahbod0e235be2014-03-28 14:56:27 -0700267 # Version 2,3,4
Behdad Esfahbod77654212014-03-28 14:48:09 -0700268 'ulCodePageRange1': onlyExisting(bitwise_or),
269 'ulCodePageRange2': onlyExisting(bitwise_or),
270 'usMaxContex': onlyExisting(max),
Behdad Esfahboddb2410a2013-12-19 03:30:29 -0500271 # TODO version 5
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500272}
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400273
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800274@_add_method(ttLib.getTableClass('OS/2'))
275def merge(self, m, tables):
276 DefaultTable.merge(self, m, tables)
277 if self.version < 2:
278 # bits 8 and 9 are reserved and should be set to zero
279 self.fsType &= ~0x0300
280 if self.version >= 3:
281 # Only one of bits 1, 2, and 3 may be set. We already take
282 # care of bit 1 implications in mergeOs2FsType. So unset
283 # bit 2 if bit 3 is already set.
284 if self.fsType & 0x0008:
285 self.fsType &= ~0x0004
286 return self
287
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500288ttLib.getTableClass('post').mergeMap = {
289 '*': first,
290 'tableTag': equal,
291 'formatType': max,
292 'isFixedPitch': min,
293 'minMemType42': max,
294 'maxMemType42': lambda lst: 0,
295 'minMemType1': max,
296 'maxMemType1': lambda lst: 0,
Behdad Esfahbod0d5fcf42014-03-28 14:37:32 -0700297 'mapping': onlyExisting(sumDicts),
Behdad Esfahbodc68c0ff2013-12-19 14:19:23 -0500298 'extraNames': lambda lst: [],
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500299}
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400300
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500301ttLib.getTableClass('vmtx').mergeMap = ttLib.getTableClass('hmtx').mergeMap = {
302 'tableTag': equal,
303 'metrics': sumDicts,
304}
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400305
Roozbeh Pournader7a272142013-12-19 15:46:05 -0800306ttLib.getTableClass('gasp').mergeMap = {
307 'tableTag': equal,
308 'version': max,
309 'gaspRange': first, # FIXME? Appears irreconcilable
310}
311
312ttLib.getTableClass('name').mergeMap = {
313 'tableTag': equal,
314 'names': first, # FIXME? Does mixing name records make sense?
315}
316
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500317ttLib.getTableClass('loca').mergeMap = {
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500318 '*': recalculate,
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500319 'tableTag': equal,
320}
321
322ttLib.getTableClass('glyf').mergeMap = {
323 'tableTag': equal,
324 'glyphs': sumDicts,
325 'glyphOrder': sumLists,
326}
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400327
Behdad Esfahbodbe4ecc72013-09-19 20:37:01 -0400328@_add_method(ttLib.getTableClass('glyf'))
Behdad Esfahbod3b36f552013-12-19 04:45:17 -0500329def merge(self, m, tables):
Behdad Esfahbod27c71f92014-01-27 21:01:45 -0500330 for i,table in enumerate(tables):
Behdad Esfahbod43650332013-09-20 16:33:33 -0400331 for g in table.glyphs.values():
Behdad Esfahbod27c71f92014-01-27 21:01:45 -0500332 if i:
333 # Drop hints for all but first font, since
334 # we don't map functions / CVT values.
335 g.removeHinting()
Behdad Esfahbod43650332013-09-20 16:33:33 -0400336 # Expand composite glyphs to load their
337 # composite glyph names.
338 if g.isComposite():
339 g.expand(table)
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500340 return DefaultTable.merge(self, m, tables)
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400341
Behdad Esfahbod27c71f92014-01-27 21:01:45 -0500342ttLib.getTableClass('prep').mergeMap = lambda self, lst: first(lst)
343ttLib.getTableClass('fpgm').mergeMap = lambda self, lst: first(lst)
344ttLib.getTableClass('cvt ').mergeMap = lambda self, lst: first(lst)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400345
Behdad Esfahbodbe4ecc72013-09-19 20:37:01 -0400346@_add_method(ttLib.getTableClass('cmap'))
Behdad Esfahbod3b36f552013-12-19 04:45:17 -0500347def merge(self, m, tables):
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400348 # TODO Handle format=14.
Behdad Esfahbod3b36f552013-12-19 04:45:17 -0500349 cmapTables = [t for table in tables for t in table.tables
Behdad Esfahbodf480c7c2014-03-12 12:18:47 -0700350 if t.isUnicode()]
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400351 # TODO Better handle format-4 and format-12 coexisting in same font.
352 # TODO Insert both a format-4 and format-12 if needed.
Behdad Esfahbodbe4ecc72013-09-19 20:37:01 -0400353 module = ttLib.getTableModule('cmap')
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400354 assert all(t.format in [4, 12] for t in cmapTables)
355 format = max(t.format for t in cmapTables)
356 cmapTable = module.cmap_classes[format](format)
357 cmapTable.cmap = {}
358 cmapTable.platformID = 3
359 cmapTable.platEncID = max(t.platEncID for t in cmapTables)
360 cmapTable.language = 0
361 for table in cmapTables:
362 # TODO handle duplicates.
363 cmapTable.cmap.update(table.cmap)
364 self.tableVersion = 0
365 self.tables = [cmapTable]
366 self.numSubTables = len(self.tables)
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500367 return self
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400368
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400369
Behdad Esfahbod26429342013-12-19 11:53:47 -0500370otTables.ScriptList.mergeMap = {
371 'ScriptCount': sum,
Behdad Esfahbod972af5a2013-12-31 18:16:36 +0800372 'ScriptRecord': lambda lst: sorted(sumLists(lst), key=lambda s: s.ScriptTag),
Behdad Esfahbod26429342013-12-19 11:53:47 -0500373}
374
375otTables.FeatureList.mergeMap = {
376 'FeatureCount': sum,
377 'FeatureRecord': sumLists,
378}
379
380otTables.LookupList.mergeMap = {
381 'LookupCount': sum,
382 'Lookup': sumLists,
383}
384
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500385otTables.Coverage.mergeMap = {
386 'glyphs': sumLists,
387}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400388
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500389otTables.ClassDef.mergeMap = {
390 'classDefs': sumDicts,
391}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400392
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500393otTables.LigCaretList.mergeMap = {
394 'Coverage': mergeObjects,
395 'LigGlyphCount': sum,
396 'LigGlyph': sumLists,
397}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400398
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500399otTables.AttachList.mergeMap = {
400 'Coverage': mergeObjects,
401 'GlyphCount': sum,
402 'AttachPoint': sumLists,
403}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400404
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500405# XXX Renumber MarkFilterSets of lookups
406otTables.MarkGlyphSetsDef.mergeMap = {
407 'MarkSetTableFormat': equal,
408 'MarkSetCount': sum,
409 'Coverage': sumLists,
410}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400411
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500412otTables.GDEF.mergeMap = {
413 '*': mergeObjects,
414 'Version': max,
415}
416
Behdad Esfahbod26429342013-12-19 11:53:47 -0500417otTables.GSUB.mergeMap = otTables.GPOS.mergeMap = {
418 '*': mergeObjects,
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500419 'Version': max,
Behdad Esfahbod26429342013-12-19 11:53:47 -0500420}
421
422ttLib.getTableClass('GDEF').mergeMap = \
423ttLib.getTableClass('GSUB').mergeMap = \
424ttLib.getTableClass('GPOS').mergeMap = \
425ttLib.getTableClass('BASE').mergeMap = \
426ttLib.getTableClass('JSTF').mergeMap = \
427ttLib.getTableClass('MATH').mergeMap = \
428{
Behdad Esfahbod0d5fcf42014-03-28 14:37:32 -0700429 'tableTag': onlyExisting(equal), # XXX clean me up
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500430 'table': mergeObjects,
431}
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400432
Behdad Esfahbod26429342013-12-19 11:53:47 -0500433
Behdad Esfahbod50803312014-02-10 18:14:37 -0500434@_add_method(otTables.SingleSubst,
435 otTables.MultipleSubst,
436 otTables.AlternateSubst,
437 otTables.LigatureSubst,
438 otTables.ReverseChainSingleSubst,
439 otTables.SinglePos,
440 otTables.PairPos,
441 otTables.CursivePos,
442 otTables.MarkBasePos,
443 otTables.MarkLigPos,
444 otTables.MarkMarkPos)
445def mapLookups(self, lookupMap):
446 pass
447
448# Copied and trimmed down from subset.py
449@_add_method(otTables.ContextSubst,
450 otTables.ChainContextSubst,
451 otTables.ContextPos,
452 otTables.ChainContextPos)
453def __classify_context(self):
454
455 class ContextHelper(object):
456 def __init__(self, klass, Format):
457 if klass.__name__.endswith('Subst'):
458 Typ = 'Sub'
459 Type = 'Subst'
460 else:
461 Typ = 'Pos'
462 Type = 'Pos'
463 if klass.__name__.startswith('Chain'):
464 Chain = 'Chain'
465 else:
466 Chain = ''
467 ChainTyp = Chain+Typ
468
469 self.Typ = Typ
470 self.Type = Type
471 self.Chain = Chain
472 self.ChainTyp = ChainTyp
473
474 self.LookupRecord = Type+'LookupRecord'
475
476 if Format == 1:
477 self.Rule = ChainTyp+'Rule'
478 self.RuleSet = ChainTyp+'RuleSet'
479 elif Format == 2:
480 self.Rule = ChainTyp+'ClassRule'
481 self.RuleSet = ChainTyp+'ClassSet'
482
483 if self.Format not in [1, 2, 3]:
484 return None # Don't shoot the messenger; let it go
485 if not hasattr(self.__class__, "__ContextHelpers"):
486 self.__class__.__ContextHelpers = {}
487 if self.Format not in self.__class__.__ContextHelpers:
488 helper = ContextHelper(self.__class__, self.Format)
489 self.__class__.__ContextHelpers[self.Format] = helper
490 return self.__class__.__ContextHelpers[self.Format]
491
492
493@_add_method(otTables.ContextSubst,
494 otTables.ChainContextSubst,
495 otTables.ContextPos,
496 otTables.ChainContextPos)
497def mapLookups(self, lookupMap):
498 c = self.__classify_context()
499
500 if self.Format in [1, 2]:
501 for rs in getattr(self, c.RuleSet):
502 if not rs: continue
503 for r in getattr(rs, c.Rule):
504 if not r: continue
505 for ll in getattr(r, c.LookupRecord):
506 if not ll: continue
507 ll.LookupListIndex = lookupMap[ll.LookupListIndex]
508 elif self.Format == 3:
509 for ll in getattr(self, c.LookupRecord):
510 if not ll: continue
511 ll.LookupListIndex = lookupMap[ll.LookupListIndex]
512 else:
513 assert 0, "unknown format: %s" % self.Format
514
515@_add_method(otTables.Lookup)
516def mapLookups(self, lookupMap):
517 for st in self.SubTable:
518 if not st: continue
519 st.mapLookups(lookupMap)
520
521@_add_method(otTables.LookupList)
522def mapLookups(self, lookupMap):
523 for l in self.Lookup:
524 if not l: continue
525 l.mapLookups(lookupMap)
526
Behdad Esfahbod26429342013-12-19 11:53:47 -0500527@_add_method(otTables.Feature)
528def mapLookups(self, lookupMap):
529 self.LookupListIndex = [lookupMap[i] for i in self.LookupListIndex]
530
531@_add_method(otTables.FeatureList)
532def mapLookups(self, lookupMap):
533 for f in self.FeatureRecord:
534 if not f or not f.Feature: continue
535 f.Feature.mapLookups(lookupMap)
536
537@_add_method(otTables.DefaultLangSys,
538 otTables.LangSys)
539def mapFeatures(self, featureMap):
540 self.FeatureIndex = [featureMap[i] for i in self.FeatureIndex]
541 if self.ReqFeatureIndex != 65535:
542 self.ReqFeatureIndex = featureMap[self.ReqFeatureIndex]
543
544@_add_method(otTables.Script)
545def mapFeatures(self, featureMap):
546 if self.DefaultLangSys:
547 self.DefaultLangSys.mapFeatures(featureMap)
548 for l in self.LangSysRecord:
549 if not l or not l.LangSys: continue
550 l.LangSys.mapFeatures(featureMap)
551
552@_add_method(otTables.ScriptList)
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500553def mapFeatures(self, featureMap):
Behdad Esfahbod26429342013-12-19 11:53:47 -0500554 for s in self.ScriptRecord:
555 if not s or not s.Script: continue
556 s.Script.mapFeatures(featureMap)
557
558
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400559class Options(object):
560
561 class UnknownOptionError(Exception):
562 pass
563
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400564 def __init__(self, **kwargs):
565
566 self.set(**kwargs)
567
568 def set(self, **kwargs):
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500569 for k,v in kwargs.items():
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400570 if not hasattr(self, k):
571 raise self.UnknownOptionError("Unknown option '%s'" % k)
572 setattr(self, k, v)
573
574 def parse_opts(self, argv, ignore_unknown=False):
575 ret = []
576 opts = {}
577 for a in argv:
578 orig_a = a
579 if not a.startswith('--'):
580 ret.append(a)
581 continue
582 a = a[2:]
583 i = a.find('=')
584 op = '='
585 if i == -1:
586 if a.startswith("no-"):
587 k = a[3:]
588 v = False
589 else:
590 k = a
591 v = True
592 else:
593 k = a[:i]
594 if k[-1] in "-+":
595 op = k[-1]+'=' # Ops is '-=' or '+=' now.
596 k = k[:-1]
597 v = a[i+1:]
598 k = k.replace('-', '_')
599 if not hasattr(self, k):
600 if ignore_unknown == True or k in ignore_unknown:
601 ret.append(orig_a)
602 continue
603 else:
604 raise self.UnknownOptionError("Unknown option '%s'" % a)
605
606 ov = getattr(self, k)
607 if isinstance(ov, bool):
608 v = bool(v)
609 elif isinstance(ov, int):
610 v = int(v)
611 elif isinstance(ov, list):
612 vv = v.split(',')
613 if vv == ['']:
614 vv = []
615 vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv]
616 if op == '=':
617 v = vv
618 elif op == '+=':
619 v = ov
620 v.extend(vv)
621 elif op == '-=':
622 v = ov
623 for x in vv:
624 if x in v:
625 v.remove(x)
626 else:
627 assert 0
628
629 opts[k] = v
630 self.set(**opts)
631
632 return ret
633
634
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500635class Merger(object):
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400636
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400637 def __init__(self, options=None, log=None):
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400638
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400639 if not log:
640 log = Logger()
641 if not options:
642 options = Options()
643
644 self.options = options
645 self.log = log
646
647 def merge(self, fontfiles):
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400648
649 mega = ttLib.TTFont()
650
651 #
652 # Settle on a mega glyph order.
653 #
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400654 fonts = [ttLib.TTFont(fontfile) for fontfile in fontfiles]
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400655 glyphOrders = [font.getGlyphOrder() for font in fonts]
656 megaGlyphOrder = self._mergeGlyphOrders(glyphOrders)
657 # Reload fonts and set new glyph names on them.
658 # TODO Is it necessary to reload font? I think it is. At least
659 # it's safer, in case tables were loaded to provide glyph names.
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400660 fonts = [ttLib.TTFont(fontfile) for fontfile in fontfiles]
Behdad Esfahbod3235a042013-09-19 20:57:33 -0400661 for font,glyphOrder in zip(fonts, glyphOrders):
662 font.setGlyphOrder(glyphOrder)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400663 mega.setGlyphOrder(megaGlyphOrder)
664
Behdad Esfahbod26429342013-12-19 11:53:47 -0500665 for font in fonts:
666 self._preMerge(font)
667
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500668 allTags = reduce(set.union, (list(font.keys()) for font in fonts), set())
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400669 allTags.remove('GlyphOrder')
670 for tag in allTags:
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400671
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400672 clazz = ttLib.getTableClass(tag)
673
Behdad Esfahbod26429342013-12-19 11:53:47 -0500674 tables = [font.get(tag, NotImplemented) for font in fonts]
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500675 table = clazz(tag).merge(self, tables)
676 if table is not NotImplemented and table is not False:
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400677 mega[tag] = table
Behdad Esfahbodb640f742013-09-19 20:12:56 -0400678 self.log("Merged '%s'." % tag)
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400679 else:
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500680 self.log("Dropped '%s'." % tag)
Behdad Esfahbodb640f742013-09-19 20:12:56 -0400681 self.log.lapse("merge '%s'" % tag)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400682
Behdad Esfahbod26429342013-12-19 11:53:47 -0500683 self._postMerge(mega)
684
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400685 return mega
686
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400687 def _mergeGlyphOrders(self, glyphOrders):
Behdad Esfahbodc2e27fd2013-09-20 16:25:48 -0400688 """Modifies passed-in glyphOrders to reflect new glyph names.
689 Returns glyphOrder for the merged font."""
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400690 # Simply append font index to the glyph name for now.
Behdad Esfahbodc2e27fd2013-09-20 16:25:48 -0400691 # TODO Even this simplistic numbering can result in conflicts.
692 # But then again, we have to improve this soon anyway.
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400693 mega = []
694 for n,glyphOrder in enumerate(glyphOrders):
695 for i,glyphName in enumerate(glyphOrder):
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500696 glyphName += "#" + repr(n)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400697 glyphOrder[i] = glyphName
698 mega.append(glyphName)
699 return mega
700
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500701 def mergeObjects(self, returnTable, logic, tables):
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500702 # Right now we don't use self at all. Will use in the future
703 # for options and logging.
704
705 if logic is NotImplemented:
706 return NotImplemented
707
708 allKeys = set.union(set(), *(vars(table).keys() for table in tables if table is not NotImplemented))
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -0800709 for key in allKeys:
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -0800710 try:
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500711 mergeLogic = logic[key]
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -0800712 except KeyError:
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500713 try:
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500714 mergeLogic = logic['*']
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500715 except KeyError:
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500716 raise Exception("Don't know how to merge key %s of class %s" %
717 (key, returnTable.__class__.__name__))
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500718 if mergeLogic is NotImplemented:
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -0800719 continue
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500720 value = mergeLogic(getattr(table, key, NotImplemented) for table in tables)
721 if value is not NotImplemented:
722 setattr(returnTable, key, value)
723
724 return returnTable
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -0800725
Behdad Esfahbod26429342013-12-19 11:53:47 -0500726 def _preMerge(self, font):
727
Behdad Esfahbod26429342013-12-19 11:53:47 -0500728 GDEF = font.get('GDEF')
729 GSUB = font.get('GSUB')
730 GPOS = font.get('GPOS')
731
732 for t in [GSUB, GPOS]:
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500733 if not t: continue
Behdad Esfahbod26429342013-12-19 11:53:47 -0500734
Behdad Esfahbod50803312014-02-10 18:14:37 -0500735 if t.table.LookupList:
Behdad Esfahbodb76d6ff2013-12-20 20:24:27 -0500736 lookupMap = {i:id(v) for i,v in enumerate(t.table.LookupList.Lookup)}
Behdad Esfahbod50803312014-02-10 18:14:37 -0500737 t.table.LookupList.mapLookups(lookupMap)
738 if t.table.FeatureList:
739 # XXX Handle present FeatureList but absent LookupList
740 t.table.FeatureList.mapLookups(lookupMap)
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500741
742 if t.table.FeatureList and t.table.ScriptList:
Behdad Esfahbodb76d6ff2013-12-20 20:24:27 -0500743 featureMap = {i:id(v) for i,v in enumerate(t.table.FeatureList.FeatureRecord)}
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500744 t.table.ScriptList.mapFeatures(featureMap)
745
746 # TODO GDEF/Lookup MarkFilteringSets
Behdad Esfahbod26429342013-12-19 11:53:47 -0500747 # TODO FeatureParams nameIDs
748
749 def _postMerge(self, font):
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500750
751 GDEF = font.get('GDEF')
752 GSUB = font.get('GSUB')
753 GPOS = font.get('GPOS')
754
755 for t in [GSUB, GPOS]:
756 if not t: continue
757
Behdad Esfahbod50803312014-02-10 18:14:37 -0500758 if t.table.LookupList:
Behdad Esfahbodb76d6ff2013-12-20 20:24:27 -0500759 lookupMap = {id(v):i for i,v in enumerate(t.table.LookupList.Lookup)}
Behdad Esfahbod50803312014-02-10 18:14:37 -0500760 t.table.LookupList.mapLookups(lookupMap)
761 if t.table.FeatureList:
762 # XXX Handle present FeatureList but absent LookupList
763 t.table.FeatureList.mapLookups(lookupMap)
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500764
765 if t.table.FeatureList and t.table.ScriptList:
Behdad Esfahbod50803312014-02-10 18:14:37 -0500766 # XXX Handle present ScriptList but absent FeatureList
Behdad Esfahbodb76d6ff2013-12-20 20:24:27 -0500767 featureMap = {id(v):i for i,v in enumerate(t.table.FeatureList.FeatureRecord)}
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500768 t.table.ScriptList.mapFeatures(featureMap)
769
770 # TODO GDEF/Lookup MarkFilteringSets
771 # TODO FeatureParams nameIDs
Behdad Esfahbod26429342013-12-19 11:53:47 -0500772
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400773
774class Logger(object):
775
776 def __init__(self, verbose=False, xml=False, timing=False):
777 self.verbose = verbose
778 self.xml = xml
779 self.timing = timing
780 self.last_time = self.start_time = time.time()
781
782 def parse_opts(self, argv):
783 argv = argv[:]
784 for v in ['verbose', 'xml', 'timing']:
785 if "--"+v in argv:
786 setattr(self, v, True)
787 argv.remove("--"+v)
788 return argv
789
790 def __call__(self, *things):
791 if not self.verbose:
792 return
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500793 print(' '.join(str(x) for x in things))
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400794
795 def lapse(self, *things):
796 if not self.timing:
797 return
798 new_time = time.time()
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500799 print("Took %0.3fs to %s" %(new_time - self.last_time,
800 ' '.join(str(x) for x in things)))
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400801 self.last_time = new_time
802
803 def font(self, font, file=sys.stdout):
804 if not self.xml:
805 return
806 from fontTools.misc import xmlWriter
807 writer = xmlWriter.XMLWriter(file)
808 font.disassembleInstructions = False # Work around ttLib bug
809 for tag in font.keys():
810 writer.begintag(tag)
811 writer.newline()
812 font[tag].toXML(writer, font)
813 writer.endtag(tag)
814 writer.newline()
815
816
817__all__ = [
818 'Options',
819 'Merger',
820 'Logger',
821 'main'
822]
823
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400824def main(args):
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400825
826 log = Logger()
827 args = log.parse_opts(args)
828
829 options = Options()
830 args = options.parse_opts(args)
831
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400832 if len(args) < 1:
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500833 print("usage: pyftmerge font...", file=sys.stderr)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400834 sys.exit(1)
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400835
836 merger = Merger(options=options, log=log)
837 font = merger.merge(args)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400838 outfile = 'merged.ttf'
839 font.save(outfile)
Behdad Esfahbodb640f742013-09-19 20:12:56 -0400840 log.lapse("compile and save font")
841
842 log.last_time = log.start_time
843 log.lapse("make one with everything(TOTAL TIME)")
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400844
845if __name__ == "__main__":
846 main(sys.argv[1:])