blob: 8e212ec1c844477ed2373105e22a4dd0bf694408 [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 Esfahbodb8039e22014-03-28 13:54:37 -0700116def mergeBits(bitmap, lst):
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800117 lst = list(lst)
118 returnValue = 0
Behdad Esfahbodb8039e22014-03-28 13:54:37 -0700119 for bitNumber in range(bitmap['size']):
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800120 try:
Behdad Esfahbodb8039e22014-03-28 13:54:37 -0700121 mergeLogic = bitmap[bitNumber]
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800122 except KeyError:
123 try:
Behdad Esfahbodb8039e22014-03-28 13:54:37 -0700124 mergeLogic = bitmap['*']
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800125 except KeyError:
126 raise Exception("Don't know how to merge bit %s" % bitNumber)
127 shiftedBit = 1 << bitNumber
128 mergedValue = mergeLogic(bool(item & shiftedBit) for item in lst)
129 returnValue |= mergedValue << bitNumber
130 return returnValue
131
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500132
133@_add_method(DefaultTable, allowDefaultTable=True)
Behdad Esfahbod3b36f552013-12-19 04:45:17 -0500134def merge(self, m, tables):
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500135 if not hasattr(self, 'mergeMap'):
136 m.log("Don't know how to merge '%s'." % self.tableTag)
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500137 return NotImplemented
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500138
Behdad Esfahbod27c71f92014-01-27 21:01:45 -0500139 logic = self.mergeMap
140
141 if isinstance(logic, dict):
142 return m.mergeObjects(self, self.mergeMap, tables)
143 else:
144 return logic(tables)
145
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500146
147ttLib.getTableClass('maxp').mergeMap = {
148 '*': max,
149 'tableTag': equal,
150 'tableVersion': equal,
151 'numGlyphs': sum,
Behdad Esfahbod27c71f92014-01-27 21:01:45 -0500152 'maxStorage': first,
153 'maxFunctionDefs': first,
154 'maxInstructionDefs': first,
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400155 # TODO When we correctly merge hinting data, update these values:
156 # maxFunctionDefs, maxInstructionDefs, maxSizeOfInstructions
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500157}
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400158
Behdad Esfahbodb8039e22014-03-28 13:54:37 -0700159headFlagsMergeBitMap = {
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800160 'size': 16,
161 '*': bitwise_or,
162 1: bitwise_and, # Baseline at y = 0
163 2: bitwise_and, # lsb at x = 0
164 3: bitwise_and, # Force ppem to integer values. FIXME?
165 5: bitwise_and, # Font is vertical
166 6: lambda bit: 0, # Always set to zero
167 11: bitwise_and, # Font data is 'lossless'
168 13: bitwise_and, # Optimized for ClearType
169 14: bitwise_and, # Last resort font. FIXME? equal or first may be better
170 15: lambda bit: 0, # Always set to zero
171}
172
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500173ttLib.getTableClass('head').mergeMap = {
174 'tableTag': equal,
175 'tableVersion': max,
176 'fontRevision': max,
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500177 'checkSumAdjustment': lambda lst: 0, # We need *something* here
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500178 'magicNumber': equal,
Behdad Esfahbodb8039e22014-03-28 13:54:37 -0700179 'flags': lambda lst: mergeBits(headFlagsMergeBitMap, lst),
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500180 'unitsPerEm': equal,
181 'created': current_time,
182 'modified': current_time,
183 'xMin': min,
184 'yMin': min,
185 'xMax': max,
186 'yMax': max,
187 'macStyle': first,
188 'lowestRecPPEM': max,
189 'fontDirectionHint': lambda lst: 2,
190 'indexToLocFormat': recalculate,
191 'glyphDataFormat': equal,
192}
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400193
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500194ttLib.getTableClass('hhea').mergeMap = {
195 '*': equal,
196 'tableTag': equal,
197 'tableVersion': max,
198 'ascent': max,
199 'descent': min,
200 'lineGap': max,
201 'advanceWidthMax': max,
202 'minLeftSideBearing': min,
203 'minRightSideBearing': min,
204 'xMaxExtent': max,
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800205 'caretSlopeRise': first,
206 'caretSlopeRun': first,
207 'caretOffset': first,
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500208 'numberOfHMetrics': recalculate,
209}
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400210
Behdad Esfahbodb8039e22014-03-28 13:54:37 -0700211os2FsTypeMergeBitMap = {
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800212 'size': 16,
213 '*': lambda bit: 0,
214 1: bitwise_or, # no embedding permitted
215 2: bitwise_and, # allow previewing and printing documents
216 3: bitwise_and, # allow editing documents
217 8: bitwise_or, # no subsetting permitted
218 9: bitwise_or, # no embedding of outlines permitted
219}
220
221def mergeOs2FsType(lst):
222 lst = list(lst)
223 if all(item == 0 for item in lst):
224 return 0
225
226 # Compute least restrictive logic for each fsType value
227 for i in range(len(lst)):
228 # unset bit 1 (no embedding permitted) if either bit 2 or 3 is set
229 if lst[i] & 0x000C:
230 lst[i] &= ~0x0002
231 # set bit 2 (allow previewing) if bit 3 is set (allow editing)
232 elif lst[i] & 0x0008:
233 lst[i] |= 0x0004
234 # set bits 2 and 3 if everything is allowed
235 elif lst[i] == 0:
236 lst[i] = 0x000C
237
Behdad Esfahbodb8039e22014-03-28 13:54:37 -0700238 fsType = mergeBits(os2FsTypeMergeBitMap, lst)
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800239 # unset bits 2 and 3 if bit 1 is set (some font is "no embedding")
240 if fsType & 0x0002:
241 fsType &= ~0x000C
242 return fsType
243
244
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500245ttLib.getTableClass('OS/2').mergeMap = {
246 '*': first,
247 'tableTag': equal,
248 'version': max,
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500249 'xAvgCharWidth': avg_int, # Apparently fontTools doesn't recalc this
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800250 'fsType': mergeOs2FsType, # Will be overwritten
251 'panose': first, # FIXME: should really be the first Latin font
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500252 'ulUnicodeRange1': bitwise_or,
253 'ulUnicodeRange2': bitwise_or,
254 'ulUnicodeRange3': bitwise_or,
255 'ulUnicodeRange4': bitwise_or,
256 'fsFirstCharIndex': min,
257 'fsLastCharIndex': max,
258 'sTypoAscender': max,
259 'sTypoDescender': min,
260 'sTypoLineGap': max,
261 'usWinAscent': max,
262 'usWinDescent': max,
263 'ulCodePageRange1': bitwise_or,
264 'ulCodePageRange2': bitwise_or,
265 'usMaxContex': max,
Behdad Esfahboddb2410a2013-12-19 03:30:29 -0500266 # TODO version 5
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500267}
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400268
Roozbeh Pournader642eaf12013-12-21 01:04:18 -0800269@_add_method(ttLib.getTableClass('OS/2'))
270def merge(self, m, tables):
271 DefaultTable.merge(self, m, tables)
272 if self.version < 2:
273 # bits 8 and 9 are reserved and should be set to zero
274 self.fsType &= ~0x0300
275 if self.version >= 3:
276 # Only one of bits 1, 2, and 3 may be set. We already take
277 # care of bit 1 implications in mergeOs2FsType. So unset
278 # bit 2 if bit 3 is already set.
279 if self.fsType & 0x0008:
280 self.fsType &= ~0x0004
281 return self
282
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500283ttLib.getTableClass('post').mergeMap = {
284 '*': first,
285 'tableTag': equal,
286 'formatType': max,
287 'isFixedPitch': min,
288 'minMemType42': max,
289 'maxMemType42': lambda lst: 0,
290 'minMemType1': max,
291 'maxMemType1': lambda lst: 0,
Behdad Esfahbod0d5fcf42014-03-28 14:37:32 -0700292 'mapping': onlyExisting(sumDicts),
Behdad Esfahbodc68c0ff2013-12-19 14:19:23 -0500293 'extraNames': lambda lst: [],
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500294}
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400295
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500296ttLib.getTableClass('vmtx').mergeMap = ttLib.getTableClass('hmtx').mergeMap = {
297 'tableTag': equal,
298 'metrics': sumDicts,
299}
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400300
Roozbeh Pournader7a272142013-12-19 15:46:05 -0800301ttLib.getTableClass('gasp').mergeMap = {
302 'tableTag': equal,
303 'version': max,
304 'gaspRange': first, # FIXME? Appears irreconcilable
305}
306
307ttLib.getTableClass('name').mergeMap = {
308 'tableTag': equal,
309 'names': first, # FIXME? Does mixing name records make sense?
310}
311
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500312ttLib.getTableClass('loca').mergeMap = {
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500313 '*': recalculate,
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500314 'tableTag': equal,
315}
316
317ttLib.getTableClass('glyf').mergeMap = {
318 'tableTag': equal,
319 'glyphs': sumDicts,
320 'glyphOrder': sumLists,
321}
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400322
Behdad Esfahbodbe4ecc72013-09-19 20:37:01 -0400323@_add_method(ttLib.getTableClass('glyf'))
Behdad Esfahbod3b36f552013-12-19 04:45:17 -0500324def merge(self, m, tables):
Behdad Esfahbod27c71f92014-01-27 21:01:45 -0500325 for i,table in enumerate(tables):
Behdad Esfahbod43650332013-09-20 16:33:33 -0400326 for g in table.glyphs.values():
Behdad Esfahbod27c71f92014-01-27 21:01:45 -0500327 if i:
328 # Drop hints for all but first font, since
329 # we don't map functions / CVT values.
330 g.removeHinting()
Behdad Esfahbod43650332013-09-20 16:33:33 -0400331 # Expand composite glyphs to load their
332 # composite glyph names.
333 if g.isComposite():
334 g.expand(table)
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500335 return DefaultTable.merge(self, m, tables)
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400336
Behdad Esfahbod27c71f92014-01-27 21:01:45 -0500337ttLib.getTableClass('prep').mergeMap = lambda self, lst: first(lst)
338ttLib.getTableClass('fpgm').mergeMap = lambda self, lst: first(lst)
339ttLib.getTableClass('cvt ').mergeMap = lambda self, lst: first(lst)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400340
Behdad Esfahbodbe4ecc72013-09-19 20:37:01 -0400341@_add_method(ttLib.getTableClass('cmap'))
Behdad Esfahbod3b36f552013-12-19 04:45:17 -0500342def merge(self, m, tables):
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400343 # TODO Handle format=14.
Behdad Esfahbod3b36f552013-12-19 04:45:17 -0500344 cmapTables = [t for table in tables for t in table.tables
Behdad Esfahbodf480c7c2014-03-12 12:18:47 -0700345 if t.isUnicode()]
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400346 # TODO Better handle format-4 and format-12 coexisting in same font.
347 # TODO Insert both a format-4 and format-12 if needed.
Behdad Esfahbodbe4ecc72013-09-19 20:37:01 -0400348 module = ttLib.getTableModule('cmap')
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400349 assert all(t.format in [4, 12] for t in cmapTables)
350 format = max(t.format for t in cmapTables)
351 cmapTable = module.cmap_classes[format](format)
352 cmapTable.cmap = {}
353 cmapTable.platformID = 3
354 cmapTable.platEncID = max(t.platEncID for t in cmapTables)
355 cmapTable.language = 0
356 for table in cmapTables:
357 # TODO handle duplicates.
358 cmapTable.cmap.update(table.cmap)
359 self.tableVersion = 0
360 self.tables = [cmapTable]
361 self.numSubTables = len(self.tables)
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500362 return self
Behdad Esfahbod71294de2013-09-19 19:43:17 -0400363
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400364
Behdad Esfahbod26429342013-12-19 11:53:47 -0500365otTables.ScriptList.mergeMap = {
366 'ScriptCount': sum,
Behdad Esfahbod972af5a2013-12-31 18:16:36 +0800367 'ScriptRecord': lambda lst: sorted(sumLists(lst), key=lambda s: s.ScriptTag),
Behdad Esfahbod26429342013-12-19 11:53:47 -0500368}
369
370otTables.FeatureList.mergeMap = {
371 'FeatureCount': sum,
372 'FeatureRecord': sumLists,
373}
374
375otTables.LookupList.mergeMap = {
376 'LookupCount': sum,
377 'Lookup': sumLists,
378}
379
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500380otTables.Coverage.mergeMap = {
381 'glyphs': sumLists,
382}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400383
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500384otTables.ClassDef.mergeMap = {
385 'classDefs': sumDicts,
386}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400387
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500388otTables.LigCaretList.mergeMap = {
389 'Coverage': mergeObjects,
390 'LigGlyphCount': sum,
391 'LigGlyph': sumLists,
392}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400393
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500394otTables.AttachList.mergeMap = {
395 'Coverage': mergeObjects,
396 'GlyphCount': sum,
397 'AttachPoint': sumLists,
398}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400399
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500400# XXX Renumber MarkFilterSets of lookups
401otTables.MarkGlyphSetsDef.mergeMap = {
402 'MarkSetTableFormat': equal,
403 'MarkSetCount': sum,
404 'Coverage': sumLists,
405}
Behdad Esfahbodc14ab482013-09-19 21:22:54 -0400406
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500407otTables.GDEF.mergeMap = {
408 '*': mergeObjects,
409 'Version': max,
410}
411
Behdad Esfahbod26429342013-12-19 11:53:47 -0500412otTables.GSUB.mergeMap = otTables.GPOS.mergeMap = {
413 '*': mergeObjects,
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500414 'Version': max,
Behdad Esfahbod26429342013-12-19 11:53:47 -0500415}
416
417ttLib.getTableClass('GDEF').mergeMap = \
418ttLib.getTableClass('GSUB').mergeMap = \
419ttLib.getTableClass('GPOS').mergeMap = \
420ttLib.getTableClass('BASE').mergeMap = \
421ttLib.getTableClass('JSTF').mergeMap = \
422ttLib.getTableClass('MATH').mergeMap = \
423{
Behdad Esfahbod0d5fcf42014-03-28 14:37:32 -0700424 'tableTag': onlyExisting(equal), # XXX clean me up
Behdad Esfahbod12dd5472013-12-19 05:58:06 -0500425 'table': mergeObjects,
426}
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400427
Behdad Esfahbod26429342013-12-19 11:53:47 -0500428
Behdad Esfahbod50803312014-02-10 18:14:37 -0500429@_add_method(otTables.SingleSubst,
430 otTables.MultipleSubst,
431 otTables.AlternateSubst,
432 otTables.LigatureSubst,
433 otTables.ReverseChainSingleSubst,
434 otTables.SinglePos,
435 otTables.PairPos,
436 otTables.CursivePos,
437 otTables.MarkBasePos,
438 otTables.MarkLigPos,
439 otTables.MarkMarkPos)
440def mapLookups(self, lookupMap):
441 pass
442
443# Copied and trimmed down from subset.py
444@_add_method(otTables.ContextSubst,
445 otTables.ChainContextSubst,
446 otTables.ContextPos,
447 otTables.ChainContextPos)
448def __classify_context(self):
449
450 class ContextHelper(object):
451 def __init__(self, klass, Format):
452 if klass.__name__.endswith('Subst'):
453 Typ = 'Sub'
454 Type = 'Subst'
455 else:
456 Typ = 'Pos'
457 Type = 'Pos'
458 if klass.__name__.startswith('Chain'):
459 Chain = 'Chain'
460 else:
461 Chain = ''
462 ChainTyp = Chain+Typ
463
464 self.Typ = Typ
465 self.Type = Type
466 self.Chain = Chain
467 self.ChainTyp = ChainTyp
468
469 self.LookupRecord = Type+'LookupRecord'
470
471 if Format == 1:
472 self.Rule = ChainTyp+'Rule'
473 self.RuleSet = ChainTyp+'RuleSet'
474 elif Format == 2:
475 self.Rule = ChainTyp+'ClassRule'
476 self.RuleSet = ChainTyp+'ClassSet'
477
478 if self.Format not in [1, 2, 3]:
479 return None # Don't shoot the messenger; let it go
480 if not hasattr(self.__class__, "__ContextHelpers"):
481 self.__class__.__ContextHelpers = {}
482 if self.Format not in self.__class__.__ContextHelpers:
483 helper = ContextHelper(self.__class__, self.Format)
484 self.__class__.__ContextHelpers[self.Format] = helper
485 return self.__class__.__ContextHelpers[self.Format]
486
487
488@_add_method(otTables.ContextSubst,
489 otTables.ChainContextSubst,
490 otTables.ContextPos,
491 otTables.ChainContextPos)
492def mapLookups(self, lookupMap):
493 c = self.__classify_context()
494
495 if self.Format in [1, 2]:
496 for rs in getattr(self, c.RuleSet):
497 if not rs: continue
498 for r in getattr(rs, c.Rule):
499 if not r: continue
500 for ll in getattr(r, c.LookupRecord):
501 if not ll: continue
502 ll.LookupListIndex = lookupMap[ll.LookupListIndex]
503 elif self.Format == 3:
504 for ll in getattr(self, c.LookupRecord):
505 if not ll: continue
506 ll.LookupListIndex = lookupMap[ll.LookupListIndex]
507 else:
508 assert 0, "unknown format: %s" % self.Format
509
510@_add_method(otTables.Lookup)
511def mapLookups(self, lookupMap):
512 for st in self.SubTable:
513 if not st: continue
514 st.mapLookups(lookupMap)
515
516@_add_method(otTables.LookupList)
517def mapLookups(self, lookupMap):
518 for l in self.Lookup:
519 if not l: continue
520 l.mapLookups(lookupMap)
521
Behdad Esfahbod26429342013-12-19 11:53:47 -0500522@_add_method(otTables.Feature)
523def mapLookups(self, lookupMap):
524 self.LookupListIndex = [lookupMap[i] for i in self.LookupListIndex]
525
526@_add_method(otTables.FeatureList)
527def mapLookups(self, lookupMap):
528 for f in self.FeatureRecord:
529 if not f or not f.Feature: continue
530 f.Feature.mapLookups(lookupMap)
531
532@_add_method(otTables.DefaultLangSys,
533 otTables.LangSys)
534def mapFeatures(self, featureMap):
535 self.FeatureIndex = [featureMap[i] for i in self.FeatureIndex]
536 if self.ReqFeatureIndex != 65535:
537 self.ReqFeatureIndex = featureMap[self.ReqFeatureIndex]
538
539@_add_method(otTables.Script)
540def mapFeatures(self, featureMap):
541 if self.DefaultLangSys:
542 self.DefaultLangSys.mapFeatures(featureMap)
543 for l in self.LangSysRecord:
544 if not l or not l.LangSys: continue
545 l.LangSys.mapFeatures(featureMap)
546
547@_add_method(otTables.ScriptList)
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500548def mapFeatures(self, featureMap):
Behdad Esfahbod26429342013-12-19 11:53:47 -0500549 for s in self.ScriptRecord:
550 if not s or not s.Script: continue
551 s.Script.mapFeatures(featureMap)
552
553
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400554class Options(object):
555
556 class UnknownOptionError(Exception):
557 pass
558
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400559 def __init__(self, **kwargs):
560
561 self.set(**kwargs)
562
563 def set(self, **kwargs):
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500564 for k,v in kwargs.items():
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400565 if not hasattr(self, k):
566 raise self.UnknownOptionError("Unknown option '%s'" % k)
567 setattr(self, k, v)
568
569 def parse_opts(self, argv, ignore_unknown=False):
570 ret = []
571 opts = {}
572 for a in argv:
573 orig_a = a
574 if not a.startswith('--'):
575 ret.append(a)
576 continue
577 a = a[2:]
578 i = a.find('=')
579 op = '='
580 if i == -1:
581 if a.startswith("no-"):
582 k = a[3:]
583 v = False
584 else:
585 k = a
586 v = True
587 else:
588 k = a[:i]
589 if k[-1] in "-+":
590 op = k[-1]+'=' # Ops is '-=' or '+=' now.
591 k = k[:-1]
592 v = a[i+1:]
593 k = k.replace('-', '_')
594 if not hasattr(self, k):
595 if ignore_unknown == True or k in ignore_unknown:
596 ret.append(orig_a)
597 continue
598 else:
599 raise self.UnknownOptionError("Unknown option '%s'" % a)
600
601 ov = getattr(self, k)
602 if isinstance(ov, bool):
603 v = bool(v)
604 elif isinstance(ov, int):
605 v = int(v)
606 elif isinstance(ov, list):
607 vv = v.split(',')
608 if vv == ['']:
609 vv = []
610 vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv]
611 if op == '=':
612 v = vv
613 elif op == '+=':
614 v = ov
615 v.extend(vv)
616 elif op == '-=':
617 v = ov
618 for x in vv:
619 if x in v:
620 v.remove(x)
621 else:
622 assert 0
623
624 opts[k] = v
625 self.set(**opts)
626
627 return ret
628
629
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500630class Merger(object):
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400631
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400632 def __init__(self, options=None, log=None):
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400633
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400634 if not log:
635 log = Logger()
636 if not options:
637 options = Options()
638
639 self.options = options
640 self.log = log
641
642 def merge(self, fontfiles):
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400643
644 mega = ttLib.TTFont()
645
646 #
647 # Settle on a mega glyph order.
648 #
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400649 fonts = [ttLib.TTFont(fontfile) for fontfile in fontfiles]
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400650 glyphOrders = [font.getGlyphOrder() for font in fonts]
651 megaGlyphOrder = self._mergeGlyphOrders(glyphOrders)
652 # Reload fonts and set new glyph names on them.
653 # TODO Is it necessary to reload font? I think it is. At least
654 # it's safer, in case tables were loaded to provide glyph names.
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400655 fonts = [ttLib.TTFont(fontfile) for fontfile in fontfiles]
Behdad Esfahbod3235a042013-09-19 20:57:33 -0400656 for font,glyphOrder in zip(fonts, glyphOrders):
657 font.setGlyphOrder(glyphOrder)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400658 mega.setGlyphOrder(megaGlyphOrder)
659
Behdad Esfahbod26429342013-12-19 11:53:47 -0500660 for font in fonts:
661 self._preMerge(font)
662
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500663 allTags = reduce(set.union, (list(font.keys()) for font in fonts), set())
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400664 allTags.remove('GlyphOrder')
665 for tag in allTags:
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400666
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400667 clazz = ttLib.getTableClass(tag)
668
Behdad Esfahbod26429342013-12-19 11:53:47 -0500669 tables = [font.get(tag, NotImplemented) for font in fonts]
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500670 table = clazz(tag).merge(self, tables)
671 if table is not NotImplemented and table is not False:
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400672 mega[tag] = table
Behdad Esfahbodb640f742013-09-19 20:12:56 -0400673 self.log("Merged '%s'." % tag)
Behdad Esfahbod65f19d82013-09-18 21:02:41 -0400674 else:
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500675 self.log("Dropped '%s'." % tag)
Behdad Esfahbodb640f742013-09-19 20:12:56 -0400676 self.log.lapse("merge '%s'" % tag)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400677
Behdad Esfahbod26429342013-12-19 11:53:47 -0500678 self._postMerge(mega)
679
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400680 return mega
681
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400682 def _mergeGlyphOrders(self, glyphOrders):
Behdad Esfahbodc2e27fd2013-09-20 16:25:48 -0400683 """Modifies passed-in glyphOrders to reflect new glyph names.
684 Returns glyphOrder for the merged font."""
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400685 # Simply append font index to the glyph name for now.
Behdad Esfahbodc2e27fd2013-09-20 16:25:48 -0400686 # TODO Even this simplistic numbering can result in conflicts.
687 # But then again, we have to improve this soon anyway.
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400688 mega = []
689 for n,glyphOrder in enumerate(glyphOrders):
690 for i,glyphName in enumerate(glyphOrder):
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500691 glyphName += "#" + repr(n)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400692 glyphOrder[i] = glyphName
693 mega.append(glyphName)
694 return mega
695
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500696 def mergeObjects(self, returnTable, logic, tables):
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500697 # Right now we don't use self at all. Will use in the future
698 # for options and logging.
699
700 if logic is NotImplemented:
701 return NotImplemented
702
703 allKeys = set.union(set(), *(vars(table).keys() for table in tables if table is not NotImplemented))
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -0800704 for key in allKeys:
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -0800705 try:
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500706 mergeLogic = logic[key]
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -0800707 except KeyError:
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500708 try:
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500709 mergeLogic = logic['*']
Behdad Esfahbod9e6adb62013-12-19 04:20:26 -0500710 except KeyError:
Behdad Esfahbod6baf26e2013-12-19 04:47:34 -0500711 raise Exception("Don't know how to merge key %s of class %s" %
712 (key, returnTable.__class__.__name__))
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500713 if mergeLogic is NotImplemented:
Roozbeh Pournadere219c6c2013-12-18 12:15:46 -0800714 continue
Behdad Esfahbod92fd5662013-12-19 04:56:50 -0500715 value = mergeLogic(getattr(table, key, NotImplemented) for table in tables)
716 if value is not NotImplemented:
717 setattr(returnTable, key, value)
718
719 return returnTable
Roozbeh Pournader47bee9c2013-12-18 00:45:12 -0800720
Behdad Esfahbod26429342013-12-19 11:53:47 -0500721 def _preMerge(self, font):
722
Behdad Esfahbod26429342013-12-19 11:53:47 -0500723 GDEF = font.get('GDEF')
724 GSUB = font.get('GSUB')
725 GPOS = font.get('GPOS')
726
727 for t in [GSUB, GPOS]:
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500728 if not t: continue
Behdad Esfahbod26429342013-12-19 11:53:47 -0500729
Behdad Esfahbod50803312014-02-10 18:14:37 -0500730 if t.table.LookupList:
Behdad Esfahbodb76d6ff2013-12-20 20:24:27 -0500731 lookupMap = {i:id(v) for i,v in enumerate(t.table.LookupList.Lookup)}
Behdad Esfahbod50803312014-02-10 18:14:37 -0500732 t.table.LookupList.mapLookups(lookupMap)
733 if t.table.FeatureList:
734 # XXX Handle present FeatureList but absent LookupList
735 t.table.FeatureList.mapLookups(lookupMap)
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500736
737 if t.table.FeatureList and t.table.ScriptList:
Behdad Esfahbodb76d6ff2013-12-20 20:24:27 -0500738 featureMap = {i:id(v) for i,v in enumerate(t.table.FeatureList.FeatureRecord)}
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500739 t.table.ScriptList.mapFeatures(featureMap)
740
741 # TODO GDEF/Lookup MarkFilteringSets
Behdad Esfahbod26429342013-12-19 11:53:47 -0500742 # TODO FeatureParams nameIDs
743
744 def _postMerge(self, font):
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500745
746 GDEF = font.get('GDEF')
747 GSUB = font.get('GSUB')
748 GPOS = font.get('GPOS')
749
750 for t in [GSUB, GPOS]:
751 if not t: continue
752
Behdad Esfahbod50803312014-02-10 18:14:37 -0500753 if t.table.LookupList:
Behdad Esfahbodb76d6ff2013-12-20 20:24:27 -0500754 lookupMap = {id(v):i for i,v in enumerate(t.table.LookupList.Lookup)}
Behdad Esfahbod50803312014-02-10 18:14:37 -0500755 t.table.LookupList.mapLookups(lookupMap)
756 if t.table.FeatureList:
757 # XXX Handle present FeatureList but absent LookupList
758 t.table.FeatureList.mapLookups(lookupMap)
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500759
760 if t.table.FeatureList and t.table.ScriptList:
Behdad Esfahbod50803312014-02-10 18:14:37 -0500761 # XXX Handle present ScriptList but absent FeatureList
Behdad Esfahbodb76d6ff2013-12-20 20:24:27 -0500762 featureMap = {id(v):i for i,v in enumerate(t.table.FeatureList.FeatureRecord)}
Behdad Esfahbod398770d2013-12-19 15:30:24 -0500763 t.table.ScriptList.mapFeatures(featureMap)
764
765 # TODO GDEF/Lookup MarkFilteringSets
766 # TODO FeatureParams nameIDs
Behdad Esfahbod26429342013-12-19 11:53:47 -0500767
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400768
769class Logger(object):
770
771 def __init__(self, verbose=False, xml=False, timing=False):
772 self.verbose = verbose
773 self.xml = xml
774 self.timing = timing
775 self.last_time = self.start_time = time.time()
776
777 def parse_opts(self, argv):
778 argv = argv[:]
779 for v in ['verbose', 'xml', 'timing']:
780 if "--"+v in argv:
781 setattr(self, v, True)
782 argv.remove("--"+v)
783 return argv
784
785 def __call__(self, *things):
786 if not self.verbose:
787 return
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500788 print(' '.join(str(x) for x in things))
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400789
790 def lapse(self, *things):
791 if not self.timing:
792 return
793 new_time = time.time()
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500794 print("Took %0.3fs to %s" %(new_time - self.last_time,
795 ' '.join(str(x) for x in things)))
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400796 self.last_time = new_time
797
798 def font(self, font, file=sys.stdout):
799 if not self.xml:
800 return
801 from fontTools.misc import xmlWriter
802 writer = xmlWriter.XMLWriter(file)
803 font.disassembleInstructions = False # Work around ttLib bug
804 for tag in font.keys():
805 writer.begintag(tag)
806 writer.newline()
807 font[tag].toXML(writer, font)
808 writer.endtag(tag)
809 writer.newline()
810
811
812__all__ = [
813 'Options',
814 'Merger',
815 'Logger',
816 'main'
817]
818
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400819def main(args):
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400820
821 log = Logger()
822 args = log.parse_opts(args)
823
824 options = Options()
825 args = options.parse_opts(args)
826
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400827 if len(args) < 1:
Behdad Esfahbodf63e80e2013-12-18 17:14:26 -0500828 print("usage: pyftmerge font...", file=sys.stderr)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400829 sys.exit(1)
Behdad Esfahbodf2d59822013-09-19 16:16:39 -0400830
831 merger = Merger(options=options, log=log)
832 font = merger.merge(args)
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400833 outfile = 'merged.ttf'
834 font.save(outfile)
Behdad Esfahbodb640f742013-09-19 20:12:56 -0400835 log.lapse("compile and save font")
836
837 log.last_time = log.start_time
838 log.lapse("make one with everything(TOTAL TIME)")
Behdad Esfahbod45d2f382013-09-18 20:47:53 -0400839
840if __name__ == "__main__":
841 main(sys.argv[1:])