merge.py revision 0884507c0eedb210bbe691393064083dfc1aa291
1# Copyright 2013 Google, Inc. All Rights Reserved. 2# 3# Google Author(s): Behdad Esfahbod, Roozbeh Pournader 4 5"""Font merger. 6""" 7 8from __future__ import print_function, division, absolute_import 9from fontTools.misc.py23 import * 10from fontTools import ttLib, cffLib 11from fontTools.ttLib.tables import otTables, _h_e_a_d 12from fontTools.ttLib.tables.DefaultTable import DefaultTable 13from functools import reduce 14import sys 15import time 16import operator 17 18 19def _add_method(*clazzes, **kwargs): 20 """Returns a decorator function that adds a new method to one or 21 more classes.""" 22 allowDefault = kwargs.get('allowDefaultTable', False) 23 def wrapper(method): 24 for clazz in clazzes: 25 assert allowDefault or clazz != DefaultTable, 'Oops, table class not found.' 26 assert method.__name__ not in clazz.__dict__, \ 27 "Oops, class '%s' has method '%s'." % (clazz.__name__, 28 method.__name__) 29 setattr(clazz, method.__name__, method) 30 return None 31 return wrapper 32 33# General utility functions for merging values from different fonts 34 35def equal(lst): 36 lst = list(lst) 37 t = iter(lst) 38 first = next(t) 39 assert all(item == first for item in t), "Expected all items to be equal: %s" % lst 40 return first 41 42def first(lst): 43 return next(iter(lst)) 44 45def recalculate(lst): 46 return NotImplemented 47 48def current_time(lst): 49 return int(time.time() - _h_e_a_d.mac_epoch_diff) 50 51def bitwise_and(lst): 52 return reduce(operator.and_, lst) 53 54def bitwise_or(lst): 55 return reduce(operator.or_, lst) 56 57def avg_int(lst): 58 lst = list(lst) 59 return sum(lst) // len(lst) 60 61def onlyExisting(func): 62 """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 73def 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 85def mergeObjects(lst): 86 lst = [item for item in lst if item is not NotImplemented] 87 if not lst: 88 return NotImplemented 89 lst = [item for item in lst if item is not None] 90 if not lst: 91 return None 92 93 clazz = lst[0].__class__ 94 assert all(type(item) == clazz for item in lst), lst 95 96 logic = clazz.mergeMap 97 returnTable = clazz() 98 returnDict = {} 99 100 allKeys = set.union(set(), *(vars(table).keys() for table in lst)) 101 for key in allKeys: 102 try: 103 mergeLogic = logic[key] 104 except KeyError: 105 try: 106 mergeLogic = logic['*'] 107 except KeyError: 108 raise Exception("Don't know how to merge key %s of class %s" % 109 (key, clazz.__name__)) 110 if mergeLogic is NotImplemented: 111 continue 112 value = mergeLogic(getattr(table, key, NotImplemented) for table in lst) 113 if value is not NotImplemented: 114 returnDict[key] = value 115 116 returnTable.__dict__ = returnDict 117 118 return returnTable 119 120def mergeBits(bitmap): 121 122 def wrapper(lst): 123 lst = list(lst) 124 returnValue = 0 125 for bitNumber in range(bitmap['size']): 126 try: 127 mergeLogic = bitmap[bitNumber] 128 except KeyError: 129 try: 130 mergeLogic = bitmap['*'] 131 except KeyError: 132 raise Exception("Don't know how to merge bit %s" % bitNumber) 133 shiftedBit = 1 << bitNumber 134 mergedValue = mergeLogic(bool(item & shiftedBit) for item in lst) 135 returnValue |= mergedValue << bitNumber 136 return returnValue 137 138 return wrapper 139 140 141@_add_method(DefaultTable, allowDefaultTable=True) 142def merge(self, m, tables): 143 if not hasattr(self, 'mergeMap'): 144 m.log("Don't know how to merge '%s'." % self.tableTag) 145 return NotImplemented 146 147 logic = self.mergeMap 148 149 if isinstance(logic, dict): 150 return m.mergeObjects(self, self.mergeMap, tables) 151 else: 152 return logic(tables) 153 154 155ttLib.getTableClass('maxp').mergeMap = { 156 '*': max, 157 'tableTag': equal, 158 'tableVersion': equal, 159 'numGlyphs': sum, 160 'maxStorage': first, 161 'maxFunctionDefs': first, 162 'maxInstructionDefs': first, 163 # TODO When we correctly merge hinting data, update these values: 164 # maxFunctionDefs, maxInstructionDefs, maxSizeOfInstructions 165} 166 167headFlagsMergeBitMap = { 168 'size': 16, 169 '*': bitwise_or, 170 1: bitwise_and, # Baseline at y = 0 171 2: bitwise_and, # lsb at x = 0 172 3: bitwise_and, # Force ppem to integer values. FIXME? 173 5: bitwise_and, # Font is vertical 174 6: lambda bit: 0, # Always set to zero 175 11: bitwise_and, # Font data is 'lossless' 176 13: bitwise_and, # Optimized for ClearType 177 14: bitwise_and, # Last resort font. FIXME? equal or first may be better 178 15: lambda bit: 0, # Always set to zero 179} 180 181ttLib.getTableClass('head').mergeMap = { 182 'tableTag': equal, 183 'tableVersion': max, 184 'fontRevision': max, 185 'checkSumAdjustment': lambda lst: 0, # We need *something* here 186 'magicNumber': equal, 187 'flags': mergeBits(headFlagsMergeBitMap), 188 'unitsPerEm': equal, 189 'created': current_time, 190 'modified': current_time, 191 'xMin': min, 192 'yMin': min, 193 'xMax': max, 194 'yMax': max, 195 'macStyle': first, 196 'lowestRecPPEM': max, 197 'fontDirectionHint': lambda lst: 2, 198 'indexToLocFormat': recalculate, 199 'glyphDataFormat': equal, 200} 201 202ttLib.getTableClass('hhea').mergeMap = { 203 '*': equal, 204 'tableTag': equal, 205 'tableVersion': max, 206 'ascent': max, 207 'descent': min, 208 'lineGap': max, 209 'advanceWidthMax': max, 210 'minLeftSideBearing': min, 211 'minRightSideBearing': min, 212 'xMaxExtent': max, 213 'caretSlopeRise': first, 214 'caretSlopeRun': first, 215 'caretOffset': first, 216 'numberOfHMetrics': recalculate, 217} 218 219os2FsTypeMergeBitMap = { 220 'size': 16, 221 '*': lambda bit: 0, 222 1: bitwise_or, # no embedding permitted 223 2: bitwise_and, # allow previewing and printing documents 224 3: bitwise_and, # allow editing documents 225 8: bitwise_or, # no subsetting permitted 226 9: bitwise_or, # no embedding of outlines permitted 227} 228 229def mergeOs2FsType(lst): 230 lst = list(lst) 231 if all(item == 0 for item in lst): 232 return 0 233 234 # Compute least restrictive logic for each fsType value 235 for i in range(len(lst)): 236 # unset bit 1 (no embedding permitted) if either bit 2 or 3 is set 237 if lst[i] & 0x000C: 238 lst[i] &= ~0x0002 239 # set bit 2 (allow previewing) if bit 3 is set (allow editing) 240 elif lst[i] & 0x0008: 241 lst[i] |= 0x0004 242 # set bits 2 and 3 if everything is allowed 243 elif lst[i] == 0: 244 lst[i] = 0x000C 245 246 fsType = mergeBits(os2FsTypeMergeBitMap)(lst) 247 # unset bits 2 and 3 if bit 1 is set (some font is "no embedding") 248 if fsType & 0x0002: 249 fsType &= ~0x000C 250 return fsType 251 252 253ttLib.getTableClass('OS/2').mergeMap = { 254 '*': first, 255 'tableTag': equal, 256 'version': max, 257 'xAvgCharWidth': avg_int, # Apparently fontTools doesn't recalc this 258 'fsType': mergeOs2FsType, # Will be overwritten 259 'panose': first, # FIXME: should really be the first Latin font 260 'ulUnicodeRange1': bitwise_or, 261 'ulUnicodeRange2': bitwise_or, 262 'ulUnicodeRange3': bitwise_or, 263 'ulUnicodeRange4': bitwise_or, 264 'fsFirstCharIndex': min, 265 'fsLastCharIndex': max, 266 'sTypoAscender': max, 267 'sTypoDescender': min, 268 'sTypoLineGap': max, 269 'usWinAscent': max, 270 'usWinDescent': max, 271 # Version 2,3,4 272 'ulCodePageRange1': onlyExisting(bitwise_or), 273 'ulCodePageRange2': onlyExisting(bitwise_or), 274 'usMaxContex': onlyExisting(max), 275 # TODO version 5 276} 277 278@_add_method(ttLib.getTableClass('OS/2')) 279def merge(self, m, tables): 280 DefaultTable.merge(self, m, tables) 281 if self.version < 2: 282 # bits 8 and 9 are reserved and should be set to zero 283 self.fsType &= ~0x0300 284 if self.version >= 3: 285 # Only one of bits 1, 2, and 3 may be set. We already take 286 # care of bit 1 implications in mergeOs2FsType. So unset 287 # bit 2 if bit 3 is already set. 288 if self.fsType & 0x0008: 289 self.fsType &= ~0x0004 290 return self 291 292ttLib.getTableClass('post').mergeMap = { 293 '*': first, 294 'tableTag': equal, 295 'formatType': max, 296 'isFixedPitch': min, 297 'minMemType42': max, 298 'maxMemType42': lambda lst: 0, 299 'minMemType1': max, 300 'maxMemType1': lambda lst: 0, 301 'mapping': onlyExisting(sumDicts), 302 'extraNames': lambda lst: [], 303} 304 305ttLib.getTableClass('vmtx').mergeMap = ttLib.getTableClass('hmtx').mergeMap = { 306 'tableTag': equal, 307 'metrics': sumDicts, 308} 309 310ttLib.getTableClass('gasp').mergeMap = { 311 'tableTag': equal, 312 'version': max, 313 'gaspRange': first, # FIXME? Appears irreconcilable 314} 315 316ttLib.getTableClass('name').mergeMap = { 317 'tableTag': equal, 318 'names': first, # FIXME? Does mixing name records make sense? 319} 320 321ttLib.getTableClass('loca').mergeMap = { 322 '*': recalculate, 323 'tableTag': equal, 324} 325 326ttLib.getTableClass('glyf').mergeMap = { 327 'tableTag': equal, 328 'glyphs': sumDicts, 329 'glyphOrder': sumLists, 330} 331 332@_add_method(ttLib.getTableClass('glyf')) 333def merge(self, m, tables): 334 for i,table in enumerate(tables): 335 for g in table.glyphs.values(): 336 if i: 337 # Drop hints for all but first font, since 338 # we don't map functions / CVT values. 339 g.removeHinting() 340 # Expand composite glyphs to load their 341 # composite glyph names. 342 if g.isComposite(): 343 g.expand(table) 344 return DefaultTable.merge(self, m, tables) 345 346ttLib.getTableClass('prep').mergeMap = lambda self, lst: first(lst) 347ttLib.getTableClass('fpgm').mergeMap = lambda self, lst: first(lst) 348ttLib.getTableClass('cvt ').mergeMap = lambda self, lst: first(lst) 349 350@_add_method(ttLib.getTableClass('cmap')) 351def merge(self, m, tables): 352 # TODO Handle format=14. 353 cmapTables = [t for table in tables for t in table.tables 354 if t.isUnicode()] 355 # TODO Better handle format-4 and format-12 coexisting in same font. 356 # TODO Insert both a format-4 and format-12 if needed. 357 module = ttLib.getTableModule('cmap') 358 assert all(t.format in [4, 12] for t in cmapTables) 359 format = max(t.format for t in cmapTables) 360 cmapTable = module.cmap_classes[format](format) 361 cmapTable.cmap = {} 362 cmapTable.platformID = 3 363 cmapTable.platEncID = max(t.platEncID for t in cmapTables) 364 cmapTable.language = 0 365 for table in cmapTables: 366 # TODO handle duplicates. 367 cmapTable.cmap.update(table.cmap) 368 self.tableVersion = 0 369 self.tables = [cmapTable] 370 self.numSubTables = len(self.tables) 371 return self 372 373 374otTables.ScriptList.mergeMap = { 375 'ScriptCount': sum, 376 'ScriptRecord': lambda lst: sorted(sumLists(lst), key=lambda s: s.ScriptTag), 377} 378 379otTables.FeatureList.mergeMap = { 380 'FeatureCount': sum, 381 'FeatureRecord': sumLists, 382} 383 384otTables.LookupList.mergeMap = { 385 'LookupCount': sum, 386 'Lookup': sumLists, 387} 388 389otTables.Coverage.mergeMap = { 390 'glyphs': sumLists, 391} 392 393otTables.ClassDef.mergeMap = { 394 'classDefs': sumDicts, 395} 396 397otTables.LigCaretList.mergeMap = { 398 'Coverage': mergeObjects, 399 'LigGlyphCount': sum, 400 'LigGlyph': sumLists, 401} 402 403otTables.AttachList.mergeMap = { 404 'Coverage': mergeObjects, 405 'GlyphCount': sum, 406 'AttachPoint': sumLists, 407} 408 409# XXX Renumber MarkFilterSets of lookups 410otTables.MarkGlyphSetsDef.mergeMap = { 411 'MarkSetTableFormat': equal, 412 'MarkSetCount': sum, 413 'Coverage': sumLists, 414} 415 416otTables.GDEF.mergeMap = { 417 '*': mergeObjects, 418 'Version': max, 419} 420 421otTables.GSUB.mergeMap = otTables.GPOS.mergeMap = { 422 '*': mergeObjects, 423 'Version': max, 424} 425 426ttLib.getTableClass('GDEF').mergeMap = \ 427ttLib.getTableClass('GSUB').mergeMap = \ 428ttLib.getTableClass('GPOS').mergeMap = \ 429ttLib.getTableClass('BASE').mergeMap = \ 430ttLib.getTableClass('JSTF').mergeMap = \ 431ttLib.getTableClass('MATH').mergeMap = \ 432{ 433 'tableTag': onlyExisting(equal), # XXX clean me up 434 'table': mergeObjects, 435} 436 437 438@_add_method(otTables.SingleSubst, 439 otTables.MultipleSubst, 440 otTables.AlternateSubst, 441 otTables.LigatureSubst, 442 otTables.ReverseChainSingleSubst, 443 otTables.SinglePos, 444 otTables.PairPos, 445 otTables.CursivePos, 446 otTables.MarkBasePos, 447 otTables.MarkLigPos, 448 otTables.MarkMarkPos) 449def mapLookups(self, lookupMap): 450 pass 451 452# Copied and trimmed down from subset.py 453@_add_method(otTables.ContextSubst, 454 otTables.ChainContextSubst, 455 otTables.ContextPos, 456 otTables.ChainContextPos) 457def __classify_context(self): 458 459 class ContextHelper(object): 460 def __init__(self, klass, Format): 461 if klass.__name__.endswith('Subst'): 462 Typ = 'Sub' 463 Type = 'Subst' 464 else: 465 Typ = 'Pos' 466 Type = 'Pos' 467 if klass.__name__.startswith('Chain'): 468 Chain = 'Chain' 469 else: 470 Chain = '' 471 ChainTyp = Chain+Typ 472 473 self.Typ = Typ 474 self.Type = Type 475 self.Chain = Chain 476 self.ChainTyp = ChainTyp 477 478 self.LookupRecord = Type+'LookupRecord' 479 480 if Format == 1: 481 self.Rule = ChainTyp+'Rule' 482 self.RuleSet = ChainTyp+'RuleSet' 483 elif Format == 2: 484 self.Rule = ChainTyp+'ClassRule' 485 self.RuleSet = ChainTyp+'ClassSet' 486 487 if self.Format not in [1, 2, 3]: 488 return None # Don't shoot the messenger; let it go 489 if not hasattr(self.__class__, "__ContextHelpers"): 490 self.__class__.__ContextHelpers = {} 491 if self.Format not in self.__class__.__ContextHelpers: 492 helper = ContextHelper(self.__class__, self.Format) 493 self.__class__.__ContextHelpers[self.Format] = helper 494 return self.__class__.__ContextHelpers[self.Format] 495 496 497@_add_method(otTables.ContextSubst, 498 otTables.ChainContextSubst, 499 otTables.ContextPos, 500 otTables.ChainContextPos) 501def mapLookups(self, lookupMap): 502 c = self.__classify_context() 503 504 if self.Format in [1, 2]: 505 for rs in getattr(self, c.RuleSet): 506 if not rs: continue 507 for r in getattr(rs, c.Rule): 508 if not r: continue 509 for ll in getattr(r, c.LookupRecord): 510 if not ll: continue 511 ll.LookupListIndex = lookupMap[ll.LookupListIndex] 512 elif self.Format == 3: 513 for ll in getattr(self, c.LookupRecord): 514 if not ll: continue 515 ll.LookupListIndex = lookupMap[ll.LookupListIndex] 516 else: 517 assert 0, "unknown format: %s" % self.Format 518 519@_add_method(otTables.Lookup) 520def mapLookups(self, lookupMap): 521 for st in self.SubTable: 522 if not st: continue 523 st.mapLookups(lookupMap) 524 525@_add_method(otTables.LookupList) 526def mapLookups(self, lookupMap): 527 for l in self.Lookup: 528 if not l: continue 529 l.mapLookups(lookupMap) 530 531@_add_method(otTables.Feature) 532def mapLookups(self, lookupMap): 533 self.LookupListIndex = [lookupMap[i] for i in self.LookupListIndex] 534 535@_add_method(otTables.FeatureList) 536def mapLookups(self, lookupMap): 537 for f in self.FeatureRecord: 538 if not f or not f.Feature: continue 539 f.Feature.mapLookups(lookupMap) 540 541@_add_method(otTables.DefaultLangSys, 542 otTables.LangSys) 543def mapFeatures(self, featureMap): 544 self.FeatureIndex = [featureMap[i] for i in self.FeatureIndex] 545 if self.ReqFeatureIndex != 65535: 546 self.ReqFeatureIndex = featureMap[self.ReqFeatureIndex] 547 548@_add_method(otTables.Script) 549def mapFeatures(self, featureMap): 550 if self.DefaultLangSys: 551 self.DefaultLangSys.mapFeatures(featureMap) 552 for l in self.LangSysRecord: 553 if not l or not l.LangSys: continue 554 l.LangSys.mapFeatures(featureMap) 555 556@_add_method(otTables.ScriptList) 557def mapFeatures(self, featureMap): 558 for s in self.ScriptRecord: 559 if not s or not s.Script: continue 560 s.Script.mapFeatures(featureMap) 561 562 563class Options(object): 564 565 class UnknownOptionError(Exception): 566 pass 567 568 def __init__(self, **kwargs): 569 570 self.set(**kwargs) 571 572 def set(self, **kwargs): 573 for k,v in kwargs.items(): 574 if not hasattr(self, k): 575 raise self.UnknownOptionError("Unknown option '%s'" % k) 576 setattr(self, k, v) 577 578 def parse_opts(self, argv, ignore_unknown=False): 579 ret = [] 580 opts = {} 581 for a in argv: 582 orig_a = a 583 if not a.startswith('--'): 584 ret.append(a) 585 continue 586 a = a[2:] 587 i = a.find('=') 588 op = '=' 589 if i == -1: 590 if a.startswith("no-"): 591 k = a[3:] 592 v = False 593 else: 594 k = a 595 v = True 596 else: 597 k = a[:i] 598 if k[-1] in "-+": 599 op = k[-1]+'=' # Ops is '-=' or '+=' now. 600 k = k[:-1] 601 v = a[i+1:] 602 k = k.replace('-', '_') 603 if not hasattr(self, k): 604 if ignore_unknown == True or k in ignore_unknown: 605 ret.append(orig_a) 606 continue 607 else: 608 raise self.UnknownOptionError("Unknown option '%s'" % a) 609 610 ov = getattr(self, k) 611 if isinstance(ov, bool): 612 v = bool(v) 613 elif isinstance(ov, int): 614 v = int(v) 615 elif isinstance(ov, list): 616 vv = v.split(',') 617 if vv == ['']: 618 vv = [] 619 vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv] 620 if op == '=': 621 v = vv 622 elif op == '+=': 623 v = ov 624 v.extend(vv) 625 elif op == '-=': 626 v = ov 627 for x in vv: 628 if x in v: 629 v.remove(x) 630 else: 631 assert 0 632 633 opts[k] = v 634 self.set(**opts) 635 636 return ret 637 638 639class Merger(object): 640 641 def __init__(self, options=None, log=None): 642 643 if not log: 644 log = Logger() 645 if not options: 646 options = Options() 647 648 self.options = options 649 self.log = log 650 651 def merge(self, fontfiles): 652 653 mega = ttLib.TTFont() 654 655 # 656 # Settle on a mega glyph order. 657 # 658 fonts = [ttLib.TTFont(fontfile) for fontfile in fontfiles] 659 glyphOrders = [font.getGlyphOrder() for font in fonts] 660 megaGlyphOrder = self._mergeGlyphOrders(glyphOrders) 661 # Reload fonts and set new glyph names on them. 662 # TODO Is it necessary to reload font? I think it is. At least 663 # it's safer, in case tables were loaded to provide glyph names. 664 fonts = [ttLib.TTFont(fontfile) for fontfile in fontfiles] 665 for font,glyphOrder in zip(fonts, glyphOrders): 666 font.setGlyphOrder(glyphOrder) 667 mega.setGlyphOrder(megaGlyphOrder) 668 669 for font in fonts: 670 self._preMerge(font) 671 672 allTags = reduce(set.union, (list(font.keys()) for font in fonts), set()) 673 allTags.remove('GlyphOrder') 674 for tag in allTags: 675 676 clazz = ttLib.getTableClass(tag) 677 678 tables = [font.get(tag, NotImplemented) for font in fonts] 679 table = clazz(tag).merge(self, tables) 680 if table is not NotImplemented and table is not False: 681 mega[tag] = table 682 self.log("Merged '%s'." % tag) 683 else: 684 self.log("Dropped '%s'." % tag) 685 self.log.lapse("merge '%s'" % tag) 686 687 self._postMerge(mega) 688 689 return mega 690 691 def _mergeGlyphOrders(self, glyphOrders): 692 """Modifies passed-in glyphOrders to reflect new glyph names. 693 Returns glyphOrder for the merged font.""" 694 # Simply append font index to the glyph name for now. 695 # TODO Even this simplistic numbering can result in conflicts. 696 # But then again, we have to improve this soon anyway. 697 mega = [] 698 for n,glyphOrder in enumerate(glyphOrders): 699 for i,glyphName in enumerate(glyphOrder): 700 glyphName += "#" + repr(n) 701 glyphOrder[i] = glyphName 702 mega.append(glyphName) 703 return mega 704 705 def mergeObjects(self, returnTable, logic, tables): 706 # Right now we don't use self at all. Will use in the future 707 # for options and logging. 708 709 if logic is NotImplemented: 710 return NotImplemented 711 712 allKeys = set.union(set(), *(vars(table).keys() for table in tables if table is not NotImplemented)) 713 for key in allKeys: 714 try: 715 mergeLogic = logic[key] 716 except KeyError: 717 try: 718 mergeLogic = logic['*'] 719 except KeyError: 720 raise Exception("Don't know how to merge key %s of class %s" % 721 (key, returnTable.__class__.__name__)) 722 if mergeLogic is NotImplemented: 723 continue 724 value = mergeLogic(getattr(table, key, NotImplemented) for table in tables) 725 if value is not NotImplemented: 726 setattr(returnTable, key, value) 727 728 return returnTable 729 730 def _preMerge(self, font): 731 732 GDEF = font.get('GDEF') 733 GSUB = font.get('GSUB') 734 GPOS = font.get('GPOS') 735 736 for t in [GSUB, GPOS]: 737 if not t: continue 738 739 if t.table.LookupList: 740 lookupMap = {i:id(v) for i,v in enumerate(t.table.LookupList.Lookup)} 741 t.table.LookupList.mapLookups(lookupMap) 742 if t.table.FeatureList: 743 # XXX Handle present FeatureList but absent LookupList 744 t.table.FeatureList.mapLookups(lookupMap) 745 746 if t.table.FeatureList and t.table.ScriptList: 747 featureMap = {i:id(v) for i,v in enumerate(t.table.FeatureList.FeatureRecord)} 748 t.table.ScriptList.mapFeatures(featureMap) 749 750 # TODO GDEF/Lookup MarkFilteringSets 751 # TODO FeatureParams nameIDs 752 753 def _postMerge(self, font): 754 755 GDEF = font.get('GDEF') 756 GSUB = font.get('GSUB') 757 GPOS = font.get('GPOS') 758 759 for t in [GSUB, GPOS]: 760 if not t: continue 761 762 if t.table.LookupList: 763 lookupMap = {id(v):i for i,v in enumerate(t.table.LookupList.Lookup)} 764 t.table.LookupList.mapLookups(lookupMap) 765 if t.table.FeatureList: 766 # XXX Handle present FeatureList but absent LookupList 767 t.table.FeatureList.mapLookups(lookupMap) 768 769 if t.table.FeatureList and t.table.ScriptList: 770 # XXX Handle present ScriptList but absent FeatureList 771 featureMap = {id(v):i for i,v in enumerate(t.table.FeatureList.FeatureRecord)} 772 t.table.ScriptList.mapFeatures(featureMap) 773 774 # TODO GDEF/Lookup MarkFilteringSets 775 # TODO FeatureParams nameIDs 776 777 778class Logger(object): 779 780 def __init__(self, verbose=False, xml=False, timing=False): 781 self.verbose = verbose 782 self.xml = xml 783 self.timing = timing 784 self.last_time = self.start_time = time.time() 785 786 def parse_opts(self, argv): 787 argv = argv[:] 788 for v in ['verbose', 'xml', 'timing']: 789 if "--"+v in argv: 790 setattr(self, v, True) 791 argv.remove("--"+v) 792 return argv 793 794 def __call__(self, *things): 795 if not self.verbose: 796 return 797 print(' '.join(str(x) for x in things)) 798 799 def lapse(self, *things): 800 if not self.timing: 801 return 802 new_time = time.time() 803 print("Took %0.3fs to %s" %(new_time - self.last_time, 804 ' '.join(str(x) for x in things))) 805 self.last_time = new_time 806 807 def font(self, font, file=sys.stdout): 808 if not self.xml: 809 return 810 from fontTools.misc import xmlWriter 811 writer = xmlWriter.XMLWriter(file) 812 font.disassembleInstructions = False # Work around ttLib bug 813 for tag in font.keys(): 814 writer.begintag(tag) 815 writer.newline() 816 font[tag].toXML(writer, font) 817 writer.endtag(tag) 818 writer.newline() 819 820 821__all__ = [ 822 'Options', 823 'Merger', 824 'Logger', 825 'main' 826] 827 828def main(args): 829 830 log = Logger() 831 args = log.parse_opts(args) 832 833 options = Options() 834 args = options.parse_opts(args) 835 836 if len(args) < 1: 837 print("usage: pyftmerge font...", file=sys.stderr) 838 sys.exit(1) 839 840 merger = Merger(options=options, log=log) 841 font = merger.merge(args) 842 outfile = 'merged.ttf' 843 font.save(outfile) 844 log.lapse("compile and save font") 845 846 log.last_time = log.start_time 847 log.lapse("make one with everything(TOTAL TIME)") 848 849if __name__ == "__main__": 850 main(sys.argv[1:]) 851