Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/fontTools/__pycache__/__main__.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/__pycache__/afmLib.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/__pycache__/fontBuilder.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/__pycache__/help.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/__pycache__/tfmLib.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/__pycache__/ttx.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/__pycache__/unicode.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/cffLib/CFF2ToCFF.pyAdded+258
- lib/python3.12/site-packages/fontTools/cffLib/CFFToCFF2.pyAdded+305
- lib/python3.12/site-packages/fontTools/cffLib/__init__.pyAdded
- lib/python3.12/site-packages/fontTools/cffLib/__pycache__/CFF2ToCFF.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/cffLib/__pycache__/CFFToCFF2.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/cffLib/__pycache__/specializer.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/cffLib/__pycache__/transforms.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/cffLib/__pycache__/width.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/cffLib/specializer.pyAdded+927
- lib/python3.12/site-packages/fontTools/cffLib/transforms.pyAdded+495
- lib/python3.12/site-packages/fontTools/cffLib/width.pyAdded+210
- lib/python3.12/site-packages/fontTools/config/__init__.pyAdded+90
- lib/python3.12/site-packages/fontTools/config/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/merge/__init__.pyAdded+248
- lib/python3.12/site-packages/fontTools/merge/__main__.pyAdded+6
- lib/python3.12/site-packages/fontTools/merge/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/merge/__pycache__/__main__.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/merge/__pycache__/base.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/merge/__pycache__/cmap.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/merge/__pycache__/layout.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/merge/__pycache__/options.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/merge/__pycache__/tables.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/merge/__pycache__/unicode.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/merge/__pycache__/util.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/merge/base.pyAdded+81
- lib/python3.12/site-packages/fontTools/merge/cmap.pyAdded+173
- lib/python3.12/site-packages/fontTools/merge/layout.pyAdded+526
- lib/python3.12/site-packages/fontTools/merge/options.pyAdded+85
- lib/python3.12/site-packages/fontTools/merge/tables.pyAdded+352
- lib/python3.12/site-packages/fontTools/merge/unicode.pyAdded+78
- lib/python3.12/site-packages/fontTools/merge/util.pyAdded+143
- lib/python3.12/site-packages/fontTools/misc/__init__.pyAdded+1
- lib/python3.12/site-packages/fontTools/misc/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/misc/__pycache__/arrayTools.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/misc/__pycache__/bezierTools.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/misc/__pycache__/classifyTools.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/misc/__pycache__/cliTools.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/misc/__pycache__/configTools.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/misc/__pycache__/cython.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/misc/__pycache__/dictTools.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/misc/__pycache__/eexec.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/misc/__pycache__/encodingTools.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/misc/__pycache__/enumTools.cpython-312.pycAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258"""CFF2 to CFF converter."""
from fontTools.ttLib import TTFont, newTablefrom fontTools.misc.cliTools import makeOutputFileNamefrom fontTools.misc.psCharStrings import T2StackUseExtractorfrom fontTools.cffLib import ( TopDictIndex, buildOrder, buildDefaults, topDictOperators, privateDictOperators, FDSelect,)from .transforms import desubroutinizeCharStringfrom .specializer import specializeProgramfrom .width import optimizeWidthsfrom collections import defaultdictimport logging
__all__ = ["convertCFF2ToCFF", "main"]
log = logging.getLogger("fontTools.cffLib")
def _convertCFF2ToCFF(cff, otFont): """Converts this object from CFF2 format to CFF format. This conversion is done 'in-place'. The conversion cannot be reversed.
The CFF2 font cannot be variable. (TODO Accept those and convert to the default instance?)
This assumes a decompiled CFF2 table. (i.e. that the object has been filled via :meth:`decompile` and e.g. not loaded from XML.)"""
cff.major = 1
topDictData = TopDictIndex(None) for item in cff.topDictIndex: # Iterate over, such that all are decompiled item.cff2GetGlyphOrder = None topDictData.append(item) cff.topDictIndex = topDictData topDict = topDictData[0]
if hasattr(topDict, "VarStore"): raise ValueError("Variable CFF2 font cannot be converted to CFF format.")
opOrder = buildOrder(topDictOperators) topDict.order = opOrder for key in topDict.rawDict.keys(): if key not in opOrder: del topDict.rawDict[key] if hasattr(topDict, key): delattr(topDict, key)
charStrings = topDict.CharStrings
fdArray = topDict.FDArray if not hasattr(topDict, "FDSelect"): # FDSelect is optional in CFF2, but required in CFF. fdSelect = topDict.FDSelect = FDSelect() fdSelect.gidArray = [0] * len(charStrings.charStrings)
defaults = buildDefaults(privateDictOperators) order = buildOrder(privateDictOperators) for fd in fdArray: fd.setCFF2(False) privateDict = fd.Private privateDict.order = order for key in order: if key not in privateDict.rawDict and key in defaults: privateDict.rawDict[key] = defaults[key] for key in privateDict.rawDict.keys(): if key not in order: del privateDict.rawDict[key] if hasattr(privateDict, key): delattr(privateDict, key)
# Add ending operators for cs in charStrings.values(): cs.decompile() cs.program.append("endchar") for subrSets in [cff.GlobalSubrs] + [ getattr(fd.Private, "Subrs", []) for fd in fdArray ]: for cs in subrSets: cs.program.append("return")
# Add (optimal) width to CharStrings that need it. widths = defaultdict(list) metrics = otFont["hmtx"].metrics for glyphName in charStrings.keys(): cs, fdIndex = charStrings.getItemAndSelector(glyphName) if fdIndex == None: fdIndex = 0 widths[fdIndex].append(metrics[glyphName][0]) for fdIndex, widthList in widths.items(): bestDefault, bestNominal = optimizeWidths(widthList) private = fdArray[fdIndex].Private private.defaultWidthX = bestDefault private.nominalWidthX = bestNominal for glyphName in charStrings.keys(): cs, fdIndex = charStrings.getItemAndSelector(glyphName) if fdIndex == None: fdIndex = 0 private = fdArray[fdIndex].Private width = metrics[glyphName][0] if width != private.defaultWidthX: cs.program.insert(0, width - private.nominalWidthX)
# Handle stack use since stack-depth is lower in CFF than in CFF2. for glyphName in charStrings.keys(): cs, fdIndex = charStrings.getItemAndSelector(glyphName) if fdIndex is None: fdIndex = 0 private = fdArray[fdIndex].Private extractor = T2StackUseExtractor( getattr(private, "Subrs", []), cff.GlobalSubrs, private=private ) stackUse = extractor.execute(cs) if stackUse > 48: # CFF stack depth is 48 desubroutinizeCharString(cs) cs.program = specializeProgram(cs.program)
# Unused subroutines are still in CFF2 (ie. lacking 'return' operator) # because they were not decompiled when we added the 'return'. # Moreover, some used subroutines may have become unused after the # stack-use fixup. So we remove all unused subroutines now. cff.remove_unused_subroutines()
mapping = { name: ("cid" + str(n).zfill(5) if n else ".notdef") for n, name in enumerate(topDict.charset) } topDict.charset = [ "cid" + str(n).zfill(5) if n else ".notdef" for n in range(len(topDict.charset)) ] charStrings.charStrings = { mapping[name]: v for name, v in charStrings.charStrings.items() }
topDict.ROS = ("Adobe", "Identity", 0)
def convertCFF2ToCFF(font, *, updatePostTable=True): if "CFF2" not in font: raise ValueError("Input font does not contain a CFF2 table.") cff = font["CFF2"].cff _convertCFF2ToCFF(cff, font) del font["CFF2"] table = font["CFF "] = newTable("CFF ") table.cff = cff
if updatePostTable and "post" in font: # Only version supported for fonts with CFF table is 0x00030000 not 0x20000 post = font["post"] if post.formatType == 2.0: post.formatType = 3.0
def main(args=None): """Convert CFF2 OTF font to CFF OTF font""" if args is None: import sys
args = sys.argv[1:]
import argparse
parser = argparse.ArgumentParser( "fonttools cffLib.CFF2ToCFF", description="Convert a non-variable CFF2 font to CFF.", ) parser.add_argument( "input", metavar="INPUT.ttf", help="Input OTF file with CFF table." ) parser.add_argument( "-o", "--output", metavar="OUTPUT.ttf", default=None, help="Output instance OTF file (default: INPUT-CFF2.ttf).", ) parser.add_argument( "--no-recalc-timestamp", dest="recalc_timestamp", action="store_false", help="Don't set the output font's timestamp to the current time.", ) parser.add_argument( "--remove-overlaps", action="store_true", help="Merge overlapping contours and components. Requires skia-pathops", ) parser.add_argument( "--ignore-overlap-errors", action="store_true", help="Don't crash if the remove-overlaps operation fails for some glyphs.", ) loggingGroup = parser.add_mutually_exclusive_group(required=False) loggingGroup.add_argument( "-v", "--verbose", action="store_true", help="Run more verbosely." ) loggingGroup.add_argument( "-q", "--quiet", action="store_true", help="Turn verbosity off." ) options = parser.parse_args(args)
from fontTools import configLogger
configLogger( level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO") )
import os
infile = options.input if not os.path.isfile(infile): parser.error("No such file '{}'".format(infile))
outfile = ( makeOutputFileName(infile, overWrite=True, suffix="-CFF") if not options.output else options.output )
font = TTFont(infile, recalcTimestamp=options.recalc_timestamp, recalcBBoxes=False)
convertCFF2ToCFF(font)
if options.remove_overlaps: from fontTools.ttLib.removeOverlaps import removeOverlaps from io import BytesIO
log.debug("Removing overlaps")
stream = BytesIO() font.save(stream) stream.seek(0) font = TTFont(stream, recalcTimestamp=False, recalcBBoxes=False) removeOverlaps( font, ignoreErrors=options.ignore_overlap_errors, )
log.info( "Saving %s", outfile, ) font.save(outfile)
if __name__ == "__main__": import sys
sys.exit(main(sys.argv[1:]))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305"""CFF to CFF2 converter."""
from fontTools.ttLib import TTFont, newTablefrom fontTools.misc.cliTools import makeOutputFileNamefrom fontTools.misc.psCharStrings import T2WidthExtractorfrom fontTools.cffLib import ( TopDictIndex, FDArrayIndex, FontDict, buildOrder, topDictOperators, privateDictOperators, topDictOperators2, privateDictOperators2,)from io import BytesIOimport logging
__all__ = ["convertCFFToCFF2", "main"]
log = logging.getLogger("fontTools.cffLib")
class _NominalWidthUsedError(Exception): def __add__(self, other): raise self
def __radd__(self, other): raise self
def _convertCFFToCFF2(cff, otFont): """Converts this object from CFF format to CFF2 format. This conversion is done 'in-place'. The conversion cannot be reversed.
This assumes a decompiled CFF table. (i.e. that the object has been filled via :meth:`decompile` and e.g. not loaded from XML.)"""
# Clean up T2CharStrings
topDict = cff.topDictIndex[0] fdArray = topDict.FDArray if hasattr(topDict, "FDArray") else None charStrings = topDict.CharStrings globalSubrs = cff.GlobalSubrs localSubrs = ( [getattr(fd.Private, "Subrs", []) for fd in fdArray] if fdArray else ( [topDict.Private.Subrs] if hasattr(topDict, "Private") and hasattr(topDict.Private, "Subrs") else [] ) )
for glyphName in charStrings.keys(): cs, fdIndex = charStrings.getItemAndSelector(glyphName) cs.decompile()
# Clean up subroutines first for subrs in [globalSubrs] + localSubrs: for subr in subrs: program = subr.program i = j = len(program) try: i = program.index("return") except ValueError: pass try: j = program.index("endchar") except ValueError: pass program[min(i, j) :] = []
# Clean up glyph charstrings removeUnusedSubrs = False nominalWidthXError = _NominalWidthUsedError() for glyphName in charStrings.keys(): cs, fdIndex = charStrings.getItemAndSelector(glyphName) program = cs.program
thisLocalSubrs = ( localSubrs[fdIndex] if fdIndex is not None else ( getattr(topDict.Private, "Subrs", []) if hasattr(topDict, "Private") else [] ) )
# Intentionally use custom type for nominalWidthX, such that any # CharString that has an explicit width encoded will throw back to us. extractor = T2WidthExtractor( thisLocalSubrs, globalSubrs, nominalWidthXError, 0, ) try: extractor.execute(cs) except _NominalWidthUsedError: # Program has explicit width. We want to drop it, but can't # just pop the first number since it may be a subroutine call. # Instead, when seeing that, we embed the subroutine and recurse. # If this ever happened, we later prune unused subroutines. while len(program) >= 2 and program[1] in ["callsubr", "callgsubr"]: removeUnusedSubrs = True subrNumber = program.pop(0) assert isinstance(subrNumber, int), subrNumber op = program.pop(0) bias = extractor.localBias if op == "callsubr" else extractor.globalBias subrNumber += bias subrSet = thisLocalSubrs if op == "callsubr" else globalSubrs subrProgram = subrSet[subrNumber].program program[:0] = subrProgram # Now pop the actual width assert len(program) >= 1, program program.pop(0)
if program and program[-1] == "endchar": program.pop()
if removeUnusedSubrs: cff.remove_unused_subroutines()
# Upconvert TopDict
cff.major = 2 cff2GetGlyphOrder = cff.otFont.getGlyphOrder topDictData = TopDictIndex(None, cff2GetGlyphOrder) for item in cff.topDictIndex: # Iterate over, such that all are decompiled topDictData.append(item) cff.topDictIndex = topDictData topDict = topDictData[0] if hasattr(topDict, "Private"): privateDict = topDict.Private else: privateDict = None opOrder = buildOrder(topDictOperators2) topDict.order = opOrder topDict.cff2GetGlyphOrder = cff2GetGlyphOrder
if not hasattr(topDict, "FDArray"): fdArray = topDict.FDArray = FDArrayIndex() fdArray.strings = None fdArray.GlobalSubrs = topDict.GlobalSubrs topDict.GlobalSubrs.fdArray = fdArray charStrings = topDict.CharStrings if charStrings.charStringsAreIndexed: charStrings.charStringsIndex.fdArray = fdArray else: charStrings.fdArray = fdArray fontDict = FontDict() fontDict.setCFF2(True) fdArray.append(fontDict) fontDict.Private = privateDict privateOpOrder = buildOrder(privateDictOperators2) if privateDict is not None: for entry in privateDictOperators: key = entry[1] if key not in privateOpOrder: if key in privateDict.rawDict: # print "Removing private dict", key del privateDict.rawDict[key] if hasattr(privateDict, key): delattr(privateDict, key) # print "Removing privateDict attr", key else: # clean up the PrivateDicts in the fdArray fdArray = topDict.FDArray privateOpOrder = buildOrder(privateDictOperators2) for fontDict in fdArray: fontDict.setCFF2(True) for key in list(fontDict.rawDict.keys()): if key not in fontDict.order: del fontDict.rawDict[key] if hasattr(fontDict, key): delattr(fontDict, key)
privateDict = fontDict.Private for entry in privateDictOperators: key = entry[1] if key not in privateOpOrder: if key in list(privateDict.rawDict.keys()): # print "Removing private dict", key del privateDict.rawDict[key] if hasattr(privateDict, key): delattr(privateDict, key) # print "Removing privateDict attr", key
# Now delete up the deprecated topDict operators from CFF 1.0 for entry in topDictOperators: key = entry[1] # We seem to need to keep the charset operator for now, # or we fail to compile with some fonts, like AdditionFont.otf. # I don't know which kind of CFF font those are. But keeping # charset seems to work. It will be removed when we save and # read the font again. # # AdditionFont.otf has <Encoding name="StandardEncoding"/>. if key == "charset": continue if key not in opOrder: if key in topDict.rawDict: del topDict.rawDict[key] if hasattr(topDict, key): delattr(topDict, key)
# TODO(behdad): What does the following comment even mean? Both CFF and CFF2 # use the same T2Charstring class. I *think* what it means is that the CharStrings # were loaded for CFF1, and we need to reload them for CFF2 to set varstore, etc # on them. At least that's what I understand. It's probably safe to remove this # and just set vstore where needed. # # See comment above about charset as well.
# At this point, the Subrs and Charstrings are all still T2Charstring class # easiest to fix this by compiling, then decompiling again file = BytesIO() cff.compile(file, otFont, isCFF2=True) file.seek(0) cff.decompile(file, otFont, isCFF2=True)
def convertCFFToCFF2(font): cff = font["CFF "].cff del font["CFF "] _convertCFFToCFF2(cff, font) table = font["CFF2"] = newTable("CFF2") table.cff = cff
def main(args=None): """Convert CFF OTF font to CFF2 OTF font""" if args is None: import sys
args = sys.argv[1:]
import argparse
parser = argparse.ArgumentParser( "fonttools cffLib.CFFToCFF2", description="Upgrade a CFF font to CFF2.", ) parser.add_argument( "input", metavar="INPUT.ttf", help="Input OTF file with CFF table." ) parser.add_argument( "-o", "--output", metavar="OUTPUT.ttf", default=None, help="Output instance OTF file (default: INPUT-CFF2.ttf).", ) parser.add_argument( "--no-recalc-timestamp", dest="recalc_timestamp", action="store_false", help="Don't set the output font's timestamp to the current time.", ) loggingGroup = parser.add_mutually_exclusive_group(required=False) loggingGroup.add_argument( "-v", "--verbose", action="store_true", help="Run more verbosely." ) loggingGroup.add_argument( "-q", "--quiet", action="store_true", help="Turn verbosity off." ) options = parser.parse_args(args)
from fontTools import configLogger
configLogger( level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO") )
import os
infile = options.input if not os.path.isfile(infile): parser.error("No such file '{}'".format(infile))
outfile = ( makeOutputFileName(infile, overWrite=True, suffix="-CFF2") if not options.output else options.output )
font = TTFont(infile, recalcTimestamp=options.recalc_timestamp, recalcBBoxes=False)
convertCFFToCFF2(font)
log.info( "Saving %s", outfile, ) font.save(outfile)
if __name__ == "__main__": import sys
sys.exit(main(sys.argv[1:]))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927# -*- coding: utf-8 -*-
"""T2CharString operator specializer and generalizer.
PostScript glyph drawing operations can be expressed in multiple differentways. For example, as well as the ``lineto`` operator, there is also a``hlineto`` operator which draws a horizontal line, removing the need tospecify a ``dx`` coordinate, and a ``vlineto`` operator which draws avertical line, removing the need to specify a ``dy`` coordinate. As wellas decompiling :class:`fontTools.misc.psCharStrings.T2CharString` objectsinto lists of operations, this module allows for conversion between generaland specific forms of the operation.
"""
from fontTools.cffLib import maxStackLimit
def stringToProgram(string): if isinstance(string, str): string = string.split() program = [] for token in string: try: token = int(token) except ValueError: try: token = float(token) except ValueError: pass program.append(token) return program
def programToString(program): return " ".join(str(x) for x in program)
def programToCommands(program, getNumRegions=None): """Takes a T2CharString program list and returns list of commands. Each command is a two-tuple of commandname,arg-list. The commandname might be empty string if no commandname shall be emitted (used for glyph width, hintmask/cntrmask argument, as well as stray arguments at the end of the program (🤷). 'getNumRegions' may be None, or a callable object. It must return the number of regions. 'getNumRegions' takes a single argument, vsindex. It returns the numRegions for the vsindex. The Charstring may or may not start with a width value. If the first non-blend operator has an odd number of arguments, then the first argument is a width, and is popped off. This is complicated with blend operators, as there may be more than one before the first hint or moveto operator, and each one reduces several arguments to just one list argument. We have to sum the number of arguments that are not part of the blend arguments, and all the 'numBlends' values. We could instead have said that by definition, if there is a blend operator, there is no width value, since CFF2 Charstrings don't have width values. I discussed this with Behdad, and we are allowing for an initial width value in this case because developers may assemble a CFF2 charstring from CFF Charstrings, which could have width values. """
seenWidthOp = False vsIndex = 0 lenBlendStack = 0 lastBlendIndex = 0 commands = [] stack = [] it = iter(program)
for token in it: if not isinstance(token, str): stack.append(token) continue
if token == "blend": assert getNumRegions is not None numSourceFonts = 1 + getNumRegions(vsIndex) # replace the blend op args on the stack with a single list # containing all the blend op args. numBlends = stack[-1] numBlendArgs = numBlends * numSourceFonts + 1 # replace first blend op by a list of the blend ops. stack[-numBlendArgs:] = [stack[-numBlendArgs:]] lenStack = len(stack) lenBlendStack += numBlends + lenStack - 1 lastBlendIndex = lenStack # if a blend op exists, this is or will be a CFF2 charstring. continue
elif token == "vsindex": vsIndex = stack[-1] assert type(vsIndex) is int
elif (not seenWidthOp) and token in { "hstem", "hstemhm", "vstem", "vstemhm", "cntrmask", "hintmask", "hmoveto", "vmoveto", "rmoveto", "endchar", }: seenWidthOp = True parity = token in {"hmoveto", "vmoveto"} if lenBlendStack: # lenBlendStack has the number of args represented by the last blend # arg and all the preceding args. We need to now add the number of # args following the last blend arg. numArgs = lenBlendStack + len(stack[lastBlendIndex:]) else: numArgs = len(stack) if numArgs and (numArgs % 2) ^ parity: width = stack.pop(0) commands.append(("", [width]))
if token in {"hintmask", "cntrmask"}: if stack: commands.append(("", stack)) commands.append((token, [])) commands.append(("", [next(it)])) else: commands.append((token, stack)) stack = [] if stack: commands.append(("", stack)) return commands
def _flattenBlendArgs(args): token_list = [] for arg in args: if isinstance(arg, list): token_list.extend(arg) token_list.append("blend") else: token_list.append(arg) return token_list
def commandsToProgram(commands): """Takes a commands list as returned by programToCommands() and converts it back to a T2CharString program list.""" program = [] for op, args in commands: if any(isinstance(arg, list) for arg in args): args = _flattenBlendArgs(args) program.extend(args) if op: program.append(op) return program
def _everyN(el, n): """Group the list el into groups of size n""" l = len(el) if l % n != 0: raise ValueError(el) for i in range(0, l, n): yield el[i : i + n]
class _GeneralizerDecombinerCommandsMap(object): @staticmethod def rmoveto(args): if len(args) != 2: raise ValueError(args) yield ("rmoveto", args)
@staticmethod def hmoveto(args): if len(args) != 1: raise ValueError(args) yield ("rmoveto", [args[0], 0])
@staticmethod def vmoveto(args): if len(args) != 1: raise ValueError(args) yield ("rmoveto", [0, args[0]])
@staticmethod def rlineto(args): if not args: raise ValueError(args) for args in _everyN(args, 2): yield ("rlineto", args)
@staticmethod def hlineto(args): if not args: raise ValueError(args) it = iter(args) try: while True: yield ("rlineto", [next(it), 0]) yield ("rlineto", [0, next(it)]) except StopIteration: pass
@staticmethod def vlineto(args): if not args: raise ValueError(args) it = iter(args) try: while True: yield ("rlineto", [0, next(it)]) yield ("rlineto", [next(it), 0]) except StopIteration: pass
@staticmethod def rrcurveto(args): if not args: raise ValueError(args) for args in _everyN(args, 6): yield ("rrcurveto", args)
@staticmethod def hhcurveto(args): l = len(args) if l < 4 or l % 4 > 1: raise ValueError(args) if l % 2 == 1: yield ("rrcurveto", [args[1], args[0], args[2], args[3], args[4], 0]) args = args[5:] for args in _everyN(args, 4): yield ("rrcurveto", [args[0], 0, args[1], args[2], args[3], 0])
@staticmethod def vvcurveto(args): l = len(args) if l < 4 or l % 4 > 1: raise ValueError(args) if l % 2 == 1: yield ("rrcurveto", [args[0], args[1], args[2], args[3], 0, args[4]]) args = args[5:] for args in _everyN(args, 4): yield ("rrcurveto", [0, args[0], args[1], args[2], 0, args[3]])
@staticmethod def hvcurveto(args): l = len(args) if l < 4 or l % 8 not in {0, 1, 4, 5}: raise ValueError(args) last_args = None if l % 2 == 1: lastStraight = l % 8 == 5 args, last_args = args[:-5], args[-5:] it = _everyN(args, 4) try: while True: args = next(it) yield ("rrcurveto", [args[0], 0, args[1], args[2], 0, args[3]]) args = next(it) yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], 0]) except StopIteration: pass if last_args: args = last_args if lastStraight: yield ("rrcurveto", [args[0], 0, args[1], args[2], args[4], args[3]]) else: yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], args[4]])
@staticmethod def vhcurveto(args): l = len(args) if l < 4 or l % 8 not in {0, 1, 4, 5}: raise ValueError(args) last_args = None if l % 2 == 1: lastStraight = l % 8 == 5 args, last_args = args[:-5], args[-5:] it = _everyN(args, 4) try: while True: args = next(it) yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], 0]) args = next(it) yield ("rrcurveto", [args[0], 0, args[1], args[2], 0, args[3]]) except StopIteration: pass if last_args: args = last_args if lastStraight: yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], args[4]]) else: yield ("rrcurveto", [args[0], 0, args[1], args[2], args[4], args[3]])
@staticmethod def rcurveline(args): l = len(args) if l < 8 or l % 6 != 2: raise ValueError(args) args, last_args = args[:-2], args[-2:] for args in _everyN(args, 6): yield ("rrcurveto", args) yield ("rlineto", last_args)
@staticmethod def rlinecurve(args): l = len(args) if l < 8 or l % 2 != 0: raise ValueError(args) args, last_args = args[:-6], args[-6:] for args in _everyN(args, 2): yield ("rlineto", args) yield ("rrcurveto", last_args)
def _convertBlendOpToArgs(blendList): # args is list of blend op args. Since we are supporting # recursive blend op calls, some of these args may also # be a list of blend op args, and need to be converted before # we convert the current list. if any([isinstance(arg, list) for arg in blendList]): args = [ i for e in blendList for i in (_convertBlendOpToArgs(e) if isinstance(e, list) else [e]) ] else: args = blendList
# We now know that blendList contains a blend op argument list, even if # some of the args are lists that each contain a blend op argument list. # Convert from: # [default font arg sequence x0,...,xn] + [delta tuple for x0] + ... + [delta tuple for xn] # to: # [ [x0] + [delta tuple for x0], # ..., # [xn] + [delta tuple for xn] ] numBlends = args[-1] # Can't use args.pop() when the args are being used in a nested list # comprehension. See calling context args = args[:-1]
l = len(args) numRegions = l // numBlends - 1 if not (numBlends * (numRegions + 1) == l): raise ValueError(blendList)
defaultArgs = [[arg] for arg in args[:numBlends]] deltaArgs = args[numBlends:] numDeltaValues = len(deltaArgs) deltaList = [ deltaArgs[i : i + numRegions] for i in range(0, numDeltaValues, numRegions) ] blend_args = [a + b + [1] for a, b in zip(defaultArgs, deltaList)] return blend_args
def generalizeCommands(commands, ignoreErrors=False): result = [] mapping = _GeneralizerDecombinerCommandsMap for op, args in commands: # First, generalize any blend args in the arg list. if any([isinstance(arg, list) for arg in args]): try: args = [ n for arg in args for n in ( _convertBlendOpToArgs(arg) if isinstance(arg, list) else [arg] ) ] except ValueError: if ignoreErrors: # Store op as data, such that consumers of commands do not have to # deal with incorrect number of arguments. result.append(("", args)) result.append(("", [op])) else: raise
func = getattr(mapping, op, None) if func is None: result.append((op, args)) continue try: for command in func(args): result.append(command) except ValueError: if ignoreErrors: # Store op as data, such that consumers of commands do not have to # deal with incorrect number of arguments. result.append(("", args)) result.append(("", [op])) else: raise return result
def generalizeProgram(program, getNumRegions=None, **kwargs): return commandsToProgram( generalizeCommands(programToCommands(program, getNumRegions), **kwargs) )
def _categorizeVector(v): """ Takes X,Y vector v and returns one of r, h, v, or 0 depending on which of X and/or Y are zero, plus tuple of nonzero ones. If both are zero, it returns a single zero still.
>>> _categorizeVector((0,0)) ('0', (0,)) >>> _categorizeVector((1,0)) ('h', (1,)) >>> _categorizeVector((0,2)) ('v', (2,)) >>> _categorizeVector((1,2)) ('r', (1, 2)) """ if not v[0]: if not v[1]: return "0", v[:1] else: return "v", v[1:] else: if not v[1]: return "h", v[:1] else: return "r", v
def _mergeCategories(a, b): if a == "0": return b if b == "0": return a if a == b: return a return None
def _negateCategory(a): if a == "h": return "v" if a == "v": return "h" assert a in "0r" return a
def _convertToBlendCmds(args): # return a list of blend commands, and # the remaining non-blended args, if any. num_args = len(args) stack_use = 0 new_args = [] i = 0 while i < num_args: arg = args[i] i += 1 if not isinstance(arg, list): new_args.append(arg) stack_use += 1 else: prev_stack_use = stack_use # The arg is a tuple of blend values. # These are each (master 0,delta 1..delta n, 1) # Combine as many successive tuples as we can, # up to the max stack limit. num_sources = len(arg) - 1 blendlist = [arg] stack_use += 1 + num_sources # 1 for the num_blends arg
# if we are here, max stack is the CFF2 max stack. # I use the CFF2 max stack limit here rather than # the 'maxstack' chosen by the client, as the default # maxstack may have been used unintentionally. For all # the other operators, this just produces a little less # optimization, but here it puts a hard (and low) limit # on the number of source fonts that can be used. # # Make sure the stack depth does not exceed (maxstack - 1), so # that subroutinizer can insert subroutine calls at any point. while ( (i < num_args) and isinstance(args[i], list) and stack_use + num_sources < maxStackLimit ): blendlist.append(args[i]) i += 1 stack_use += num_sources # blendList now contains as many single blend tuples as can be # combined without exceeding the CFF2 stack limit. num_blends = len(blendlist) # append the 'num_blends' default font values blend_args = [] for arg in blendlist: blend_args.append(arg[0]) for arg in blendlist: assert arg[-1] == 1 blend_args.extend(arg[1:-1]) blend_args.append(num_blends) new_args.append(blend_args) stack_use = prev_stack_use + num_blends
return new_args
def _addArgs(a, b): if isinstance(b, list): if isinstance(a, list): if len(a) != len(b) or a[-1] != b[-1]: raise ValueError() return [_addArgs(va, vb) for va, vb in zip(a[:-1], b[:-1])] + [a[-1]] else: a, b = b, a if isinstance(a, list): assert a[-1] == 1 return [_addArgs(a[0], b)] + a[1:] return a + b
def _argsStackUse(args): stackLen = 0 maxLen = 0 for arg in args: if type(arg) is list: # Blended arg maxLen = max(maxLen, stackLen + _argsStackUse(arg)) stackLen += arg[-1] else: stackLen += 1 return max(stackLen, maxLen)
def specializeCommands( commands, ignoreErrors=False, generalizeFirst=True, preserveTopology=False, maxstack=48,): # We perform several rounds of optimizations. They are carefully ordered and are: # # 0. Generalize commands. # This ensures that they are in our expected simple form, with each line/curve only # having arguments for one segment, and using the generic form (rlineto/rrcurveto). # If caller is sure the input is in this form, they can turn off generalization to # save time. # # 1. Combine successive rmoveto operations. # # 2. Specialize rmoveto/rlineto/rrcurveto operators into horizontal/vertical variants. # We specialize into some, made-up, variants as well, which simplifies following # passes. # # 3. Merge or delete redundant operations, to the extent requested. # OpenType spec declares point numbers in CFF undefined. As such, we happily # change topology. If client relies on point numbers (in GPOS anchors, or for # hinting purposes(what?)) they can turn this off. # # 4. Peephole optimization to revert back some of the h/v variants back into their # original "relative" operator (rline/rrcurveto) if that saves a byte. # # 5. Combine adjacent operators when possible, minding not to go over max stack size. # # 6. Resolve any remaining made-up operators into real operators. # # I have convinced myself that this produces optimal bytecode (except for, possibly # one byte each time maxstack size prohibits combining.) YMMV, but you'd be wrong. :-) # A dynamic-programming approach can do the same but would be significantly slower. # # 7. For any args which are blend lists, convert them to a blend command.
# 0. Generalize commands. if generalizeFirst: commands = generalizeCommands(commands, ignoreErrors=ignoreErrors) else: commands = list(commands) # Make copy since we modify in-place later.
# 1. Combine successive rmoveto operations. for i in range(len(commands) - 1, 0, -1): if "rmoveto" == commands[i][0] == commands[i - 1][0]: v1, v2 = commands[i - 1][1], commands[i][1] commands[i - 1] = ( "rmoveto", [_addArgs(v1[0], v2[0]), _addArgs(v1[1], v2[1])], ) del commands[i]
# 2. Specialize rmoveto/rlineto/rrcurveto operators into horizontal/vertical variants. # # We, in fact, specialize into more, made-up, variants that special-case when both # X and Y components are zero. This simplifies the following optimization passes. # This case is rare, but OCD does not let me skip it. # # After this round, we will have four variants that use the following mnemonics: # # - 'r' for relative, ie. non-zero X and non-zero Y, # - 'h' for horizontal, ie. zero X and non-zero Y, # - 'v' for vertical, ie. non-zero X and zero Y, # - '0' for zeros, ie. zero X and zero Y. # # The '0' pseudo-operators are not part of the spec, but help simplify the following # optimization rounds. We resolve them at the end. So, after this, we will have four # moveto and four lineto variants: # # - 0moveto, 0lineto # - hmoveto, hlineto # - vmoveto, vlineto # - rmoveto, rlineto # # and sixteen curveto variants. For example, a '0hcurveto' operator means a curve # dx0,dy0,dx1,dy1,dx2,dy2,dx3,dy3 where dx0, dx1, and dy3 are zero but not dx3. # An 'rvcurveto' means dx3 is zero but not dx0,dy0,dy3. # # There are nine different variants of curves without the '0'. Those nine map exactly # to the existing curve variants in the spec: rrcurveto, and the four variants hhcurveto, # vvcurveto, hvcurveto, and vhcurveto each cover two cases, one with an odd number of # arguments and one without. Eg. an hhcurveto with an extra argument (odd number of # arguments) is in fact an rhcurveto. The operators in the spec are designed such that # all four of rhcurveto, rvcurveto, hrcurveto, and vrcurveto are encodable for one curve. # # Of the curve types with '0', the 00curveto is equivalent to a lineto variant. The rest # of the curve types with a 0 need to be encoded as a h or v variant. Ie. a '0' can be # thought of a "don't care" and can be used as either an 'h' or a 'v'. As such, we always # encode a number 0 as argument when we use a '0' variant. Later on, we can just substitute # the '0' with either 'h' or 'v' and it works. # # When we get to curve splines however, things become more complicated... XXX finish this. # There's one more complexity with splines. If one side of the spline is not horizontal or # vertical (or zero), ie. if it's 'r', then it limits which spline types we can encode. # Only hhcurveto and vvcurveto operators can encode a spline starting with 'r', and # only hvcurveto and vhcurveto operators can encode a spline ending with 'r'. # This limits our merge opportunities later. # for i in range(len(commands)): op, args = commands[i]
if op in {"rmoveto", "rlineto"}: c, args = _categorizeVector(args) commands[i] = c + op[1:], args continue
if op == "rrcurveto": c1, args1 = _categorizeVector(args[:2]) c2, args2 = _categorizeVector(args[-2:]) commands[i] = c1 + c2 + "curveto", args1 + args[2:4] + args2 continue
# 3. Merge or delete redundant operations, to the extent requested. # # TODO # A 0moveto that comes before all other path operations can be removed. # though I find conflicting evidence for this. # # TODO # "If hstem and vstem hints are both declared at the beginning of a # CharString, and this sequence is followed directly by the hintmask or # cntrmask operators, then the vstem hint operator (or, if applicable, # the vstemhm operator) need not be included." # # "The sequence and form of a CFF2 CharString program may be represented as: # {hs* vs* cm* hm* mt subpath}? {mt subpath}*" # # https://www.microsoft.com/typography/otspec/cff2charstr.htm#section3.1 # # For Type2 CharStrings the sequence is: # w? {hs* vs* cm* hm* mt subpath}? {mt subpath}* endchar"
# Some other redundancies change topology (point numbers). if not preserveTopology: for i in range(len(commands) - 1, -1, -1): op, args = commands[i]
# A 00curveto is demoted to a (specialized) lineto. if op == "00curveto": assert len(args) == 4 c, args = _categorizeVector(args[1:3]) op = c + "lineto" commands[i] = op, args # and then...
# A 0lineto can be deleted. if op == "0lineto": del commands[i] continue
# Merge adjacent hlineto's and vlineto's. # In CFF2 charstrings from variable fonts, each # arg item may be a list of blendable values, one from # each source font. if i and op in {"hlineto", "vlineto"} and (op == commands[i - 1][0]): _, other_args = commands[i - 1] assert len(args) == 1 and len(other_args) == 1 try: new_args = [_addArgs(args[0], other_args[0])] except ValueError: continue commands[i - 1] = (op, new_args) del commands[i] continue
# 4. Peephole optimization to revert back some of the h/v variants back into their # original "relative" operator (rline/rrcurveto) if that saves a byte. for i in range(1, len(commands) - 1): op, args = commands[i] prv, nxt = commands[i - 1][0], commands[i + 1][0]
if op in {"0lineto", "hlineto", "vlineto"} and prv == nxt == "rlineto": assert len(args) == 1 args = [0, args[0]] if op[0] == "v" else [args[0], 0] commands[i] = ("rlineto", args) continue
if op[2:] == "curveto" and len(args) == 5 and prv == nxt == "rrcurveto": assert (op[0] == "r") ^ (op[1] == "r") if op[0] == "v": pos = 0 elif op[0] != "r": pos = 1 elif op[1] == "v": pos = 4 else: pos = 5 # Insert, while maintaining the type of args (can be tuple or list). args = args[:pos] + type(args)((0,)) + args[pos:] commands[i] = ("rrcurveto", args) continue
# 5. Combine adjacent operators when possible, minding not to go over max stack size. stackUse = _argsStackUse(commands[-1][1]) if commands else 0 for i in range(len(commands) - 1, 0, -1): op1, args1 = commands[i - 1] op2, args2 = commands[i] new_op = None
# Merge logic... if {op1, op2} <= {"rlineto", "rrcurveto"}: if op1 == op2: new_op = op1 else: l = len(args2) if op2 == "rrcurveto" and l == 6: new_op = "rlinecurve" elif l == 2: new_op = "rcurveline"
elif (op1, op2) in {("rlineto", "rlinecurve"), ("rrcurveto", "rcurveline")}: new_op = op2
elif {op1, op2} == {"vlineto", "hlineto"}: new_op = op1
elif "curveto" == op1[2:] == op2[2:]: d0, d1 = op1[:2] d2, d3 = op2[:2]
if d1 == "r" or d2 == "r" or d0 == d3 == "r": continue
d = _mergeCategories(d1, d2) if d is None: continue if d0 == "r": d = _mergeCategories(d, d3) if d is None: continue new_op = "r" + d + "curveto" elif d3 == "r": d0 = _mergeCategories(d0, _negateCategory(d)) if d0 is None: continue new_op = d0 + "r" + "curveto" else: d0 = _mergeCategories(d0, d3) if d0 is None: continue new_op = d0 + d + "curveto"
# Make sure the stack depth does not exceed (maxstack - 1), so # that subroutinizer can insert subroutine calls at any point. args1StackUse = _argsStackUse(args1) combinedStackUse = max(args1StackUse, len(args1) + stackUse) if new_op and combinedStackUse < maxstack: commands[i - 1] = (new_op, args1 + args2) del commands[i] stackUse = combinedStackUse else: stackUse = args1StackUse
# 6. Resolve any remaining made-up operators into real operators. for i in range(len(commands)): op, args = commands[i]
if op in {"0moveto", "0lineto"}: commands[i] = "h" + op[1:], args continue
if op[2:] == "curveto" and op[:2] not in {"rr", "hh", "vv", "vh", "hv"}: l = len(args)
op0, op1 = op[:2] if (op0 == "r") ^ (op1 == "r"): assert l % 2 == 1 if op0 == "0": op0 = "h" if op1 == "0": op1 = "h" if op0 == "r": op0 = op1 if op1 == "r": op1 = _negateCategory(op0) assert {op0, op1} <= {"h", "v"}, (op0, op1)
if l % 2: if op0 != op1: # vhcurveto / hvcurveto if (op0 == "h") ^ (l % 8 == 1): # Swap last two args order args = args[:-2] + args[-1:] + args[-2:-1] else: # hhcurveto / vvcurveto if op0 == "h": # hhcurveto # Swap first two args order args = args[1:2] + args[:1] + args[2:]
commands[i] = op0 + op1 + "curveto", args continue
# 7. For any series of args which are blend lists, convert the series to a single blend arg. for i in range(len(commands)): op, args = commands[i] if any(isinstance(arg, list) for arg in args): commands[i] = op, _convertToBlendCmds(args)
return commands
def specializeProgram(program, getNumRegions=None, **kwargs): return commandsToProgram( specializeCommands(programToCommands(program, getNumRegions), **kwargs) )
if __name__ == "__main__": import sys
if len(sys.argv) == 1: import doctest
sys.exit(doctest.testmod().failed)
import argparse
parser = argparse.ArgumentParser( "fonttools cffLib.specializer", description="CFF CharString generalizer/specializer", ) parser.add_argument("program", metavar="command", nargs="*", help="Commands.") parser.add_argument( "--num-regions", metavar="NumRegions", nargs="*", default=None, help="Number of variable-font regions for blend opertaions.", ) parser.add_argument( "--font", metavar="FONTFILE", default=None, help="CFF2 font to specialize.", ) parser.add_argument( "-o", "--output-file", type=str, help="Output font file name.", )
options = parser.parse_args(sys.argv[1:])
if options.program: getNumRegions = ( None if options.num_regions is None else lambda vsIndex: int( options.num_regions[0 if vsIndex is None else vsIndex] ) )
program = stringToProgram(options.program) print("Program:") print(programToString(program)) commands = programToCommands(program, getNumRegions) print("Commands:") print(commands) program2 = commandsToProgram(commands) print("Program from commands:") print(programToString(program2)) assert program == program2 print("Generalized program:") print(programToString(generalizeProgram(program, getNumRegions))) print("Specialized program:") print(programToString(specializeProgram(program, getNumRegions)))
if options.font: from fontTools.ttLib import TTFont
font = TTFont(options.font) cff2 = font["CFF2"].cff.topDictIndex[0] charstrings = cff2.CharStrings for glyphName in charstrings.keys(): charstring = charstrings[glyphName] charstring.decompile() getNumRegions = charstring.private.getNumRegions charstring.program = specializeProgram( charstring.program, getNumRegions, maxstack=maxStackLimit )
if options.output_file is None: from fontTools.misc.cliTools import makeOutputFileName
outfile = makeOutputFileName( options.font, overWrite=True, suffix=".specialized" ) else: outfile = options.output_file if outfile: print("Saving", outfile) font.save(outfile)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495from fontTools.misc.psCharStrings import ( SimpleT2Decompiler, T2WidthExtractor, calcSubrBias,)
def _uniq_sort(l): return sorted(set(l))
class StopHintCountEvent(Exception): pass
class _DesubroutinizingT2Decompiler(SimpleT2Decompiler): stop_hintcount_ops = ( "op_hintmask", "op_cntrmask", "op_rmoveto", "op_hmoveto", "op_vmoveto", )
def __init__(self, localSubrs, globalSubrs, private=None): SimpleT2Decompiler.__init__(self, localSubrs, globalSubrs, private)
def execute(self, charString): self.need_hintcount = True # until proven otherwise for op_name in self.stop_hintcount_ops: setattr(self, op_name, self.stop_hint_count)
if hasattr(charString, "_desubroutinized"): # If a charstring has already been desubroutinized, we will still # need to execute it if we need to count hints in order to # compute the byte length for mask arguments, and haven't finished # counting hints pairs. if self.need_hintcount and self.callingStack: try: SimpleT2Decompiler.execute(self, charString) except StopHintCountEvent: del self.callingStack[-1] return
charString._patches = [] SimpleT2Decompiler.execute(self, charString) desubroutinized = charString.program[:] for idx, expansion in reversed(charString._patches): assert idx >= 2 assert desubroutinized[idx - 1] in [ "callsubr", "callgsubr", ], desubroutinized[idx - 1] assert type(desubroutinized[idx - 2]) == int if expansion[-1] == "return": expansion = expansion[:-1] desubroutinized[idx - 2 : idx] = expansion if not self.private.in_cff2: if "endchar" in desubroutinized: # Cut off after first endchar desubroutinized = desubroutinized[ : desubroutinized.index("endchar") + 1 ]
charString._desubroutinized = desubroutinized del charString._patches
def op_callsubr(self, index): subr = self.localSubrs[self.operandStack[-1] + self.localBias] SimpleT2Decompiler.op_callsubr(self, index) self.processSubr(index, subr)
def op_callgsubr(self, index): subr = self.globalSubrs[self.operandStack[-1] + self.globalBias] SimpleT2Decompiler.op_callgsubr(self, index) self.processSubr(index, subr)
def stop_hint_count(self, *args): self.need_hintcount = False for op_name in self.stop_hintcount_ops: setattr(self, op_name, None) cs = self.callingStack[-1] if hasattr(cs, "_desubroutinized"): raise StopHintCountEvent()
def op_hintmask(self, index): SimpleT2Decompiler.op_hintmask(self, index) if self.need_hintcount: self.stop_hint_count()
def processSubr(self, index, subr): cs = self.callingStack[-1] if not hasattr(cs, "_desubroutinized"): cs._patches.append((index, subr._desubroutinized))
def desubroutinizeCharString(cs): """Desubroutinize a charstring in-place.""" cs.decompile() subrs = getattr(cs.private, "Subrs", []) decompiler = _DesubroutinizingT2Decompiler(subrs, cs.globalSubrs, cs.private) decompiler.execute(cs) cs.program = cs._desubroutinized del cs._desubroutinized
def desubroutinize(cff): for fontName in cff.fontNames: font = cff[fontName] cs = font.CharStrings for c in cs.values(): desubroutinizeCharString(c) # Delete all the local subrs if hasattr(font, "FDArray"): for fd in font.FDArray: pd = fd.Private if hasattr(pd, "Subrs"): del pd.Subrs if "Subrs" in pd.rawDict: del pd.rawDict["Subrs"] else: pd = font.Private if hasattr(pd, "Subrs"): del pd.Subrs if "Subrs" in pd.rawDict: del pd.rawDict["Subrs"] # as well as the global subrs cff.GlobalSubrs.clear()
class _MarkingT2Decompiler(SimpleT2Decompiler): def __init__(self, localSubrs, globalSubrs, private): SimpleT2Decompiler.__init__(self, localSubrs, globalSubrs, private) for subrs in [localSubrs, globalSubrs]: if subrs and not hasattr(subrs, "_used"): subrs._used = set()
def op_callsubr(self, index): self.localSubrs._used.add(self.operandStack[-1] + self.localBias) SimpleT2Decompiler.op_callsubr(self, index)
def op_callgsubr(self, index): self.globalSubrs._used.add(self.operandStack[-1] + self.globalBias) SimpleT2Decompiler.op_callgsubr(self, index)
class _DehintingT2Decompiler(T2WidthExtractor): class Hints(object): def __init__(self): # Whether calling this charstring produces any hint stems # Note that if a charstring starts with hintmask, it will # have has_hint set to True, because it *might* produce an # implicit vstem if called under certain conditions. self.has_hint = False # Index to start at to drop all hints self.last_hint = 0 # Index up to which we know more hints are possible. # Only relevant if status is 0 or 1. self.last_checked = 0 # The status means: # 0: after dropping hints, this charstring is empty # 1: after dropping hints, there may be more hints # continuing after this, or there might be # other things. Not clear yet. # 2: no more hints possible after this charstring self.status = 0 # Has hintmask instructions; not recursive self.has_hintmask = False # List of indices of calls to empty subroutines to remove. self.deletions = []
pass
def __init__( self, css, localSubrs, globalSubrs, nominalWidthX, defaultWidthX, private=None ): self._css = css T2WidthExtractor.__init__( self, localSubrs, globalSubrs, nominalWidthX, defaultWidthX ) self.private = private
def execute(self, charString): old_hints = charString._hints if hasattr(charString, "_hints") else None charString._hints = self.Hints()
T2WidthExtractor.execute(self, charString)
hints = charString._hints
if hints.has_hint or hints.has_hintmask: self._css.add(charString)
if hints.status != 2: # Check from last_check, make sure we didn't have any operators. for i in range(hints.last_checked, len(charString.program) - 1): if isinstance(charString.program[i], str): hints.status = 2 break else: hints.status = 1 # There's *something* here hints.last_checked = len(charString.program)
if old_hints: assert hints.__dict__ == old_hints.__dict__
def op_callsubr(self, index): subr = self.localSubrs[self.operandStack[-1] + self.localBias] T2WidthExtractor.op_callsubr(self, index) self.processSubr(index, subr)
def op_callgsubr(self, index): subr = self.globalSubrs[self.operandStack[-1] + self.globalBias] T2WidthExtractor.op_callgsubr(self, index) self.processSubr(index, subr)
def op_hstem(self, index): T2WidthExtractor.op_hstem(self, index) self.processHint(index)
def op_vstem(self, index): T2WidthExtractor.op_vstem(self, index) self.processHint(index)
def op_hstemhm(self, index): T2WidthExtractor.op_hstemhm(self, index) self.processHint(index)
def op_vstemhm(self, index): T2WidthExtractor.op_vstemhm(self, index) self.processHint(index)
def op_hintmask(self, index): rv = T2WidthExtractor.op_hintmask(self, index) self.processHintmask(index) return rv
def op_cntrmask(self, index): rv = T2WidthExtractor.op_cntrmask(self, index) self.processHintmask(index) return rv
def processHintmask(self, index): cs = self.callingStack[-1] hints = cs._hints hints.has_hintmask = True if hints.status != 2: # Check from last_check, see if we may be an implicit vstem for i in range(hints.last_checked, index - 1): if isinstance(cs.program[i], str): hints.status = 2 break else: # We are an implicit vstem hints.has_hint = True hints.last_hint = index + 1 hints.status = 0 hints.last_checked = index + 1
def processHint(self, index): cs = self.callingStack[-1] hints = cs._hints hints.has_hint = True hints.last_hint = index hints.last_checked = index
def processSubr(self, index, subr): cs = self.callingStack[-1] hints = cs._hints subr_hints = subr._hints
# Check from last_check, make sure we didn't have # any operators. if hints.status != 2: for i in range(hints.last_checked, index - 1): if isinstance(cs.program[i], str): hints.status = 2 break hints.last_checked = index
if hints.status != 2: if subr_hints.has_hint: hints.has_hint = True
# Decide where to chop off from if subr_hints.status == 0: hints.last_hint = index else: hints.last_hint = index - 2 # Leave the subr call in
elif subr_hints.status == 0: hints.deletions.append(index)
hints.status = max(hints.status, subr_hints.status)
def _cs_subset_subroutines(charstring, subrs, gsubrs): p = charstring.program for i in range(1, len(p)): if p[i] == "callsubr": assert isinstance(p[i - 1], int) p[i - 1] = subrs._used.index(p[i - 1] + subrs._old_bias) - subrs._new_bias elif p[i] == "callgsubr": assert isinstance(p[i - 1], int) p[i - 1] = ( gsubrs._used.index(p[i - 1] + gsubrs._old_bias) - gsubrs._new_bias )
def _cs_drop_hints(charstring): hints = charstring._hints
if hints.deletions: p = charstring.program for idx in reversed(hints.deletions): del p[idx - 2 : idx]
if hints.has_hint: assert not hints.deletions or hints.last_hint <= hints.deletions[0] charstring.program = charstring.program[hints.last_hint :] if not charstring.program: # TODO CFF2 no need for endchar. charstring.program.append("endchar") if hasattr(charstring, "width"): # Insert width back if needed if charstring.width != charstring.private.defaultWidthX: # For CFF2 charstrings, this should never happen assert ( charstring.private.defaultWidthX is not None ), "CFF2 CharStrings must not have an initial width value" charstring.program.insert( 0, charstring.width - charstring.private.nominalWidthX )
if hints.has_hintmask: i = 0 p = charstring.program while i < len(p): if p[i] in ["hintmask", "cntrmask"]: assert i + 1 <= len(p) del p[i : i + 2] continue i += 1
assert len(charstring.program)
del charstring._hints
def remove_hints(cff, *, removeUnusedSubrs: bool = True): for fontname in cff.keys(): font = cff[fontname] cs = font.CharStrings # This can be tricky, but doesn't have to. What we do is: # # - Run all used glyph charstrings and recurse into subroutines, # - For each charstring (including subroutines), if it has any # of the hint stem operators, we mark it as such. # Upon returning, for each charstring we note all the # subroutine calls it makes that (recursively) contain a stem, # - Dropping hinting then consists of the following two ops: # * Drop the piece of the program in each charstring before the # last call to a stem op or a stem-calling subroutine, # * Drop all hintmask operations. # - It's trickier... A hintmask right after hints and a few numbers # will act as an implicit vstemhm. As such, we track whether # we have seen any non-hint operators so far and do the right # thing, recursively... Good luck understanding that :( css = set() for c in cs.values(): c.decompile() subrs = getattr(c.private, "Subrs", []) decompiler = _DehintingT2Decompiler( css, subrs, c.globalSubrs, c.private.nominalWidthX, c.private.defaultWidthX, c.private, ) decompiler.execute(c) c.width = decompiler.width for charstring in css: _cs_drop_hints(charstring) del css
# Drop font-wide hinting values all_privs = [] if hasattr(font, "FDArray"): all_privs.extend(fd.Private for fd in font.FDArray) else: all_privs.append(font.Private) for priv in all_privs: for k in [ "BlueValues", "OtherBlues", "FamilyBlues", "FamilyOtherBlues", "BlueScale", "BlueShift", "BlueFuzz", "StemSnapH", "StemSnapV", "StdHW", "StdVW", "ForceBold", "LanguageGroup", "ExpansionFactor", ]: if hasattr(priv, k): setattr(priv, k, None) if removeUnusedSubrs: remove_unused_subroutines(cff)
def _pd_delete_empty_subrs(private_dict): if hasattr(private_dict, "Subrs") and not private_dict.Subrs: if "Subrs" in private_dict.rawDict: del private_dict.rawDict["Subrs"] del private_dict.Subrs
def remove_unused_subroutines(cff): for fontname in cff.keys(): font = cff[fontname] cs = font.CharStrings # Renumber subroutines to remove unused ones
# Mark all used subroutines for c in cs.values(): subrs = getattr(c.private, "Subrs", []) decompiler = _MarkingT2Decompiler(subrs, c.globalSubrs, c.private) decompiler.execute(c)
all_subrs = [font.GlobalSubrs] if hasattr(font, "FDArray"): all_subrs.extend( fd.Private.Subrs for fd in font.FDArray if hasattr(fd.Private, "Subrs") and fd.Private.Subrs ) elif hasattr(font.Private, "Subrs") and font.Private.Subrs: all_subrs.append(font.Private.Subrs)
subrs = set(subrs) # Remove duplicates
# Prepare for subrs in all_subrs: if not hasattr(subrs, "_used"): subrs._used = set() subrs._used = _uniq_sort(subrs._used) subrs._old_bias = calcSubrBias(subrs) subrs._new_bias = calcSubrBias(subrs._used)
# Renumber glyph charstrings for c in cs.values(): subrs = getattr(c.private, "Subrs", None) _cs_subset_subroutines(c, subrs, font.GlobalSubrs)
# Renumber subroutines themselves for subrs in all_subrs: if subrs == font.GlobalSubrs: if not hasattr(font, "FDArray") and hasattr(font.Private, "Subrs"): local_subrs = font.Private.Subrs elif ( hasattr(font, "FDArray") and len(font.FDArray) == 1 and hasattr(font.FDArray[0].Private, "Subrs") ): # Technically we shouldn't do this. But I've run into fonts that do it. local_subrs = font.FDArray[0].Private.Subrs else: local_subrs = None else: local_subrs = subrs
subrs.items = [subrs.items[i] for i in subrs._used] if hasattr(subrs, "file"): del subrs.file if hasattr(subrs, "offsets"): del subrs.offsets
for subr in subrs.items: _cs_subset_subroutines(subr, local_subrs, font.GlobalSubrs)
# Delete local SubrsIndex if empty if hasattr(font, "FDArray"): for fd in font.FDArray: _pd_delete_empty_subrs(fd.Private) else: _pd_delete_empty_subrs(font.Private)
# Cleanup for subrs in all_subrs: del subrs._used, subrs._old_bias, subrs._new_bias123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210# -*- coding: utf-8 -*-
"""T2CharString glyph width optimizer.
CFF glyphs whose width equals the CFF Private dictionary's ``defaultWidthX``value do not need to specify their width in their charstring, saving bytes.This module determines the optimum ``defaultWidthX`` and ``nominalWidthX``values for a font, when provided with a list of glyph widths."""
from fontTools.ttLib import TTFontfrom collections import defaultdictfrom operator import addfrom functools import reduce
__all__ = ["optimizeWidths", "main"]
class missingdict(dict): def __init__(self, missing_func): self.missing_func = missing_func
def __missing__(self, v): return self.missing_func(v)
def cumSum(f, op=add, start=0, decreasing=False): keys = sorted(f.keys()) minx, maxx = keys[0], keys[-1]
total = reduce(op, f.values(), start)
if decreasing: missing = lambda x: start if x > maxx else total domain = range(maxx, minx - 1, -1) else: missing = lambda x: start if x < minx else total domain = range(minx, maxx + 1)
out = missingdict(missing)
v = start for x in domain: v = op(v, f[x]) out[x] = v
return out
def byteCost(widths, default, nominal): if not hasattr(widths, "items"): d = defaultdict(int) for w in widths: d[w] += 1 widths = d
cost = 0 for w, freq in widths.items(): if w == default: continue diff = abs(w - nominal) if diff <= 107: cost += freq elif diff <= 1131: cost += freq * 2 else: cost += freq * 5 return cost
def optimizeWidthsBruteforce(widths): """Bruteforce version. Veeeeeeeeeeeeeeeeery slow. Only works for smallests of fonts."""
d = defaultdict(int) for w in widths: d[w] += 1
# Maximum number of bytes using default can possibly save maxDefaultAdvantage = 5 * max(d.values())
minw, maxw = min(widths), max(widths) domain = list(range(minw, maxw + 1))
bestCostWithoutDefault = min(byteCost(widths, None, nominal) for nominal in domain)
bestCost = len(widths) * 5 + 1 for nominal in domain: if byteCost(widths, None, nominal) > bestCost + maxDefaultAdvantage: continue for default in domain: cost = byteCost(widths, default, nominal) if cost < bestCost: bestCost = cost bestDefault = default bestNominal = nominal
return bestDefault, bestNominal
def optimizeWidths(widths): """Given a list of glyph widths, or dictionary mapping glyph width to number of glyphs having that, returns a tuple of best CFF default and nominal glyph widths.
This algorithm is linear in UPEM+numGlyphs."""
if not hasattr(widths, "items"): d = defaultdict(int) for w in widths: d[w] += 1 widths = d
keys = sorted(widths.keys()) minw, maxw = keys[0], keys[-1] domain = list(range(minw, maxw + 1))
# Cumulative sum/max forward/backward. cumFrqU = cumSum(widths, op=add) cumMaxU = cumSum(widths, op=max) cumFrqD = cumSum(widths, op=add, decreasing=True) cumMaxD = cumSum(widths, op=max, decreasing=True)
# Cost per nominal choice, without default consideration. nomnCostU = missingdict( lambda x: cumFrqU[x] + cumFrqU[x - 108] + cumFrqU[x - 1132] * 3 ) nomnCostD = missingdict( lambda x: cumFrqD[x] + cumFrqD[x + 108] + cumFrqD[x + 1132] * 3 ) nomnCost = missingdict(lambda x: nomnCostU[x] + nomnCostD[x] - widths[x])
# Cost-saving per nominal choice, by best default choice. dfltCostU = missingdict( lambda x: max(cumMaxU[x], cumMaxU[x - 108] * 2, cumMaxU[x - 1132] * 5) ) dfltCostD = missingdict( lambda x: max(cumMaxD[x], cumMaxD[x + 108] * 2, cumMaxD[x + 1132] * 5) ) dfltCost = missingdict(lambda x: max(dfltCostU[x], dfltCostD[x]))
# Combined cost per nominal choice. bestCost = missingdict(lambda x: nomnCost[x] - dfltCost[x])
# Best nominal. nominal = min(domain, key=lambda x: bestCost[x])
# Work back the best default. bestC = bestCost[nominal] dfltC = nomnCost[nominal] - bestCost[nominal] ends = [] if dfltC == dfltCostU[nominal]: starts = [nominal, nominal - 108, nominal - 1132] for start in starts: while cumMaxU[start] and cumMaxU[start] == cumMaxU[start - 1]: start -= 1 ends.append(start) else: starts = [nominal, nominal + 108, nominal + 1132] for start in starts: while cumMaxD[start] and cumMaxD[start] == cumMaxD[start + 1]: start += 1 ends.append(start) default = min(ends, key=lambda default: byteCost(widths, default, nominal))
return default, nominal
def main(args=None): """Calculate optimum defaultWidthX/nominalWidthX values"""
import argparse
parser = argparse.ArgumentParser( "fonttools cffLib.width", description=main.__doc__, ) parser.add_argument( "inputs", metavar="FILE", type=str, nargs="+", help="Input TTF files" ) parser.add_argument( "-b", "--brute-force", dest="brute", action="store_true", help="Use brute-force approach (VERY slow)", )
args = parser.parse_args(args)
for fontfile in args.inputs: font = TTFont(fontfile) hmtx = font["hmtx"] widths = [m[0] for m in hmtx.metrics.values()] if args.brute: default, nominal = optimizeWidthsBruteforce(widths) else: default, nominal = optimizeWidths(widths) print( "glyphs=%d default=%d nominal=%d byteCost=%d" % (len(widths), default, nominal, byteCost(widths, default, nominal)) )
if __name__ == "__main__": import sys
if len(sys.argv) == 1: import doctest
sys.exit(doctest.testmod().failed) main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Define all configuration options that can affect the working of fontToolsmodules. E.g. optimization levels of varLib IUP, otlLib GPOS compression level,etc. If this file gets too big, split it into smaller files per-module.
An instance of the Config class can be attached to a TTFont object, so thatthe various modules can access their configuration options from it."""
from textwrap import dedent
from fontTools.misc.configTools import *
class Config(AbstractConfig): options = Options()
OPTIONS = Config.options
Config.register_option( name="fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL", help=dedent( """\ GPOS Lookup type 2 (PairPos) compression level: 0 = do not attempt to compact PairPos lookups; 1 to 8 = create at most 1 to 8 new subtables for each existing subtable, provided that it would yield a 50%% file size saving; 9 = create as many new subtables as needed to yield a file size saving. Default: 0.
This compaction aims to save file size, by splitting large class kerning subtables (Format 2) that contain many zero values into smaller and denser subtables. It's a trade-off between the overhead of several subtables versus the sparseness of one big subtable.
See the pull request: https://github.com/fonttools/fonttools/pull/2326 """ ), default=0, parse=int, validate=lambda v: v in range(10),)
Config.register_option( name="fontTools.ttLib.tables.otBase:USE_HARFBUZZ_REPACKER", help=dedent( """\ FontTools tries to use the HarfBuzz Repacker to serialize GPOS/GSUB tables if the uharfbuzz python bindings are importable, otherwise falls back to its slower, less efficient serializer. Set to False to always use the latter. Set to True to explicitly request the HarfBuzz Repacker (will raise an error if uharfbuzz cannot be imported). """ ), default=None, parse=Option.parse_optional_bool, validate=Option.validate_optional_bool,)
Config.register_option( name="fontTools.otlLib.builder:WRITE_GPOS7", help=dedent( """\ macOS before 13.2 didn’t support GPOS LookupType 7 (non-chaining ContextPos lookups), so FontTools.otlLib.builder disables a file size optimisation that would use LookupType 7 instead of 8 when there is no chaining (no prefix or suffix). Set to True to enable the optimization. """ ), default=False, parse=Option.parse_optional_bool, validate=Option.validate_optional_bool,)
Config.register_option( name="fontTools.ttLib:OPTIMIZE_FONT_SPEED", help=dedent( """\ Enable optimizations that prioritize speed over file size. This mainly affects how glyf table and gvar / VARC tables are compiled. The produced fonts will be larger, but rendering performance will be improved with HarfBuzz and other text layout engines. """ ), default=False, parse=Option.parse_optional_bool, validate=Option.validate_optional_bool,)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248# Copyright 2013 Google, Inc. All Rights Reserved.## Google Author(s): Behdad Esfahbod, Roozbeh Pournader
from fontTools import ttLibimport fontTools.merge.basefrom fontTools.merge.cmap import ( computeMegaGlyphOrder, computeMegaCmap, renameCFFCharStrings,)from fontTools.merge.layout import layoutPreMerge, layoutPostMergefrom fontTools.merge.options import Optionsimport fontTools.merge.tablesfrom fontTools.misc.loggingTools import Timerfrom functools import reduceimport sysimport logging
log = logging.getLogger("fontTools.merge")timer = Timer(logger=logging.getLogger(__name__ + ".timer"), level=logging.INFO)
class Merger(object): """Font merger.
This class merges multiple files into a single OpenType font, taking into account complexities such as OpenType layout (``GSUB``/``GPOS``) tables and cross-font metrics (for example ``hhea.ascent`` is set to the maximum value across all the fonts).
If multiple glyphs map to the same Unicode value, and the glyphs are considered sufficiently different (that is, they differ in any of paths, widths, or height), then subsequent glyphs are renamed and a lookup in the ``locl`` feature will be created to disambiguate them. For example, if the arguments are an Arabic font and a Latin font and both contain a set of parentheses, the Latin glyphs will be renamed to ``parenleft.1`` and ``parenright.1``, and a lookup will be inserted into the to ``locl`` feature (creating it if necessary) under the ``latn`` script to substitute ``parenleft`` with ``parenleft.1`` etc.
Restrictions:
- All fonts must have the same units per em. - If duplicate glyph disambiguation takes place as described above then the fonts must have a ``GSUB`` table.
Attributes: options: Currently unused. """
def __init__(self, options=None): if not options: options = Options()
self.options = options
def _openFonts(self, fontfiles): fonts = [ttLib.TTFont(fontfile) for fontfile in fontfiles] for font, fontfile in zip(fonts, fontfiles): font._merger__fontfile = fontfile font._merger__name = font["name"].getDebugName(4) return fonts
def merge(self, fontfiles): """Merges fonts together.
Args: fontfiles: A list of file names to be merged
Returns: A :class:`fontTools.ttLib.TTFont` object. Call the ``save`` method on this to write it out to an OTF file. """ # # Settle on a mega glyph order. # fonts = self._openFonts(fontfiles) glyphOrders = [list(font.getGlyphOrder()) for font in fonts] computeMegaGlyphOrder(self, glyphOrders)
# Take first input file sfntVersion sfntVersion = fonts[0].sfntVersion
# Reload fonts and set new glyph names on them. fonts = self._openFonts(fontfiles) for font, glyphOrder in zip(fonts, glyphOrders): font.setGlyphOrder(glyphOrder) if "CFF " in font: renameCFFCharStrings(self, glyphOrder, font["CFF "])
cmaps = [font["cmap"] for font in fonts] self.duplicateGlyphsPerFont = [{} for _ in fonts] computeMegaCmap(self, cmaps)
mega = ttLib.TTFont(sfntVersion=sfntVersion) mega.setGlyphOrder(self.glyphOrder)
for font in fonts: self._preMerge(font)
self.fonts = fonts
allTags = reduce(set.union, (list(font.keys()) for font in fonts), set()) allTags.remove("GlyphOrder")
for tag in sorted(allTags): if tag in self.options.drop_tables: continue
with timer("merge '%s'" % tag): tables = [font.get(tag, NotImplemented) for font in fonts]
log.info("Merging '%s'.", tag) clazz = ttLib.getTableClass(tag) table = clazz(tag).merge(self, tables) # XXX Clean this up and use: table = mergeObjects(tables)
if table is not NotImplemented and table is not False: mega[tag] = table log.info("Merged '%s'.", tag) else: log.info("Dropped '%s'.", tag)
del self.duplicateGlyphsPerFont del self.fonts
self._postMerge(mega)
return mega
def mergeObjects(self, returnTable, logic, tables): # Right now we don't use self at all. Will use in the future # for options and logging.
allKeys = set.union( set(), *(vars(table).keys() for table in tables if table is not NotImplemented), ) for key in allKeys: log.info(" %s", key) try: mergeLogic = logic[key] except KeyError: try: mergeLogic = logic["*"] except KeyError: raise Exception( "Don't know how to merge key %s of class %s" % (key, returnTable.__class__.__name__) ) if mergeLogic is NotImplemented: continue value = mergeLogic(getattr(table, key, NotImplemented) for table in tables) if value is not NotImplemented: setattr(returnTable, key, value)
return returnTable
def _preMerge(self, font): layoutPreMerge(font)
def _postMerge(self, font): layoutPostMerge(font)
if "OS/2" in font: # https://github.com/fonttools/fonttools/issues/2538 # TODO: Add an option to disable this? font["OS/2"].recalcAvgCharWidth(font)
__all__ = ["Options", "Merger", "main"]
@timer("make one with everything (TOTAL TIME)")def main(args=None): """Merge multiple fonts into one""" from fontTools import configLogger
if args is None: args = sys.argv[1:]
options = Options() args = options.parse_opts(args) fontfiles = [] if options.input_file: with open(options.input_file) as inputfile: fontfiles = [ line.strip() for line in inputfile.readlines() if not line.lstrip().startswith("#") ] for g in args: fontfiles.append(g)
if len(fontfiles) < 1: print( "usage: fonttools merge [font1 ... fontN] [--input-file=filelist.txt] [--output-file=merged.ttf] [--import-file=tables.ttx]", file=sys.stderr, ) print( " [--drop-tables=tags] [--verbose] [--timing]", file=sys.stderr, ) print("", file=sys.stderr) print(" font1 ... fontN Files to merge.", file=sys.stderr) print( " --input-file=<filename> Read files to merge from a text file, each path new line. # Comment lines allowed.", file=sys.stderr, ) print( " --output-file=<filename> Specify output file name (default: merged.ttf).", file=sys.stderr, ) print( " --import-file=<filename> TTX file to import after merging. This can be used to set metadata.", file=sys.stderr, ) print( " --drop-tables=<table tags> Comma separated list of table tags to skip, case sensitive.", file=sys.stderr, ) print( " --verbose Output progress information.", file=sys.stderr, ) print(" --timing Output progress timing.", file=sys.stderr) return 1
configLogger(level=logging.INFO if options.verbose else logging.WARNING) if options.timing: timer.logger.setLevel(logging.DEBUG) else: timer.logger.disabled = True
merger = Merger(options=options) font = merger.merge(fontfiles)
if options.import_file: font.importXML(options.import_file)
with timer("compile and save font"): font.save(options.output_file)
if __name__ == "__main__": sys.exit(main())123456import sysfrom fontTools.merge import main
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081# Copyright 2013 Google, Inc. All Rights Reserved.## Google Author(s): Behdad Esfahbod, Roozbeh Pournader
from fontTools.ttLib.tables.DefaultTable import DefaultTableimport logging
log = logging.getLogger("fontTools.merge")
def add_method(*clazzes, **kwargs): """Returns a decorator function that adds a new method to one or more classes.""" allowDefault = kwargs.get("allowDefaultTable", False)
def wrapper(method): done = [] for clazz in clazzes: if clazz in done: continue # Support multiple names of a clazz done.append(clazz) assert allowDefault or clazz != DefaultTable, "Oops, table class not found." assert ( method.__name__ not in clazz.__dict__ ), "Oops, class '%s' has method '%s'." % (clazz.__name__, method.__name__) setattr(clazz, method.__name__, method) return None
return wrapper
def mergeObjects(lst): lst = [item for item in lst if item is not NotImplemented] if not lst: return NotImplemented lst = [item for item in lst if item is not None] if not lst: return None
clazz = lst[0].__class__ assert all(type(item) == clazz for item in lst), lst
logic = clazz.mergeMap returnTable = clazz() returnDict = {}
allKeys = set.union(set(), *(vars(table).keys() for table in lst)) for key in allKeys: try: mergeLogic = logic[key] except KeyError: try: mergeLogic = logic["*"] except KeyError: raise Exception( "Don't know how to merge key %s of class %s" % (key, clazz.__name__) ) if mergeLogic is NotImplemented: continue value = mergeLogic(getattr(table, key, NotImplemented) for table in lst) if value is not NotImplemented: returnDict[key] = value
returnTable.__dict__ = returnDict
return returnTable
@add_method(DefaultTable, allowDefaultTable=True)def merge(self, m, tables): if not hasattr(self, "mergeMap"): log.info("Don't know how to merge '%s'.", self.tableTag) return NotImplemented
logic = self.mergeMap
if isinstance(logic, dict): return m.mergeObjects(self, self.mergeMap, tables) else: return logic(tables)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173# Copyright 2013 Google, Inc. All Rights Reserved.## Google Author(s): Behdad Esfahbod, Roozbeh Pournader
from fontTools.merge.unicode import is_Default_Ignorablefrom fontTools.pens.recordingPen import DecomposingRecordingPenimport logging
log = logging.getLogger("fontTools.merge")
def computeMegaGlyphOrder(merger, glyphOrders): """Modifies passed-in glyphOrders to reflect new glyph names. Stores merger.glyphOrder.""" megaOrder = {} for glyphOrder in glyphOrders: for i, glyphName in enumerate(glyphOrder): if glyphName in megaOrder: n = megaOrder[glyphName] while (glyphName + "." + repr(n)) in megaOrder: n += 1 megaOrder[glyphName] = n glyphName += "." + repr(n) glyphOrder[i] = glyphName megaOrder[glyphName] = 1 merger.glyphOrder = megaOrder = list(megaOrder.keys())
def _glyphsAreSame( glyphSet1, glyphSet2, glyph1, glyph2, advanceTolerance=0.05, advanceToleranceEmpty=0.20,): pen1 = DecomposingRecordingPen(glyphSet1) pen2 = DecomposingRecordingPen(glyphSet2) g1 = glyphSet1[glyph1] g2 = glyphSet2[glyph2] g1.draw(pen1) g2.draw(pen2) if pen1.value != pen2.value: return False # Allow more width tolerance for glyphs with no ink tolerance = advanceTolerance if pen1.value else advanceToleranceEmpty # TODO Warn if advances not the same but within tolerance. if abs(g1.width - g2.width) > g1.width * tolerance: return False if hasattr(g1, "height") and g1.height is not None: if abs(g1.height - g2.height) > g1.height * tolerance: return False return True
def computeMegaUvs(merger, uvsTables): """Returns merged UVS subtable (cmap format=14).""" uvsDict = {} cmap = merger.cmap for table in uvsTables: for variationSelector, uvsMapping in table.uvsDict.items(): if variationSelector not in uvsDict: uvsDict[variationSelector] = {} for unicodeValue, glyphName in uvsMapping: if cmap.get(unicodeValue) == glyphName: # this is a default variation glyphName = None # prefer previous glyph id if both fonts defined UVS if unicodeValue not in uvsDict[variationSelector]: uvsDict[variationSelector][unicodeValue] = glyphName
for variationSelector in uvsDict: uvsDict[variationSelector] = [*uvsDict[variationSelector].items()]
return uvsDict
# Valid (format, platformID, platEncID) triplets for cmap subtables containing# Unicode BMP-only and Unicode Full Repertoire semantics.# Cf. OpenType spec for "Platform specific encodings":# https://docs.microsoft.com/en-us/typography/opentype/spec/nameclass _CmapUnicodePlatEncodings: BMP = {(4, 3, 1), (4, 0, 3), (4, 0, 4), (4, 0, 6)} FullRepertoire = {(12, 3, 10), (12, 0, 4), (12, 0, 6)} UVS = {(14, 0, 5)}
def computeMegaCmap(merger, cmapTables): """Sets merger.cmap and merger.uvsDict."""
# TODO Handle format=14. # Only merge format 4 and 12 Unicode subtables, ignores all other subtables # If there is a format 12 table for a font, ignore the format 4 table of it chosenCmapTables = [] chosenUvsTables = [] for fontIdx, table in enumerate(cmapTables): format4 = None format12 = None format14 = None for subtable in table.tables: properties = (subtable.format, subtable.platformID, subtable.platEncID) if properties in _CmapUnicodePlatEncodings.BMP: format4 = subtable elif properties in _CmapUnicodePlatEncodings.FullRepertoire: format12 = subtable elif properties in _CmapUnicodePlatEncodings.UVS: format14 = subtable else: log.warning( "Dropped cmap subtable from font '%s':\t" "format %2s, platformID %2s, platEncID %2s", fontIdx, subtable.format, subtable.platformID, subtable.platEncID, ) if format12 is not None: chosenCmapTables.append((format12, fontIdx)) elif format4 is not None: chosenCmapTables.append((format4, fontIdx))
if format14 is not None: chosenUvsTables.append(format14)
# Build the unicode mapping merger.cmap = cmap = {} fontIndexForGlyph = {} glyphSets = [None for f in merger.fonts] if hasattr(merger, "fonts") else None
for table, fontIdx in chosenCmapTables: # handle duplicates for uni, gid in table.cmap.items(): oldgid = cmap.get(uni, None) if oldgid is None: cmap[uni] = gid fontIndexForGlyph[gid] = fontIdx elif is_Default_Ignorable(uni) or uni in (0x25CC,): # U+25CC DOTTED CIRCLE continue elif oldgid != gid: # Char previously mapped to oldgid, now to gid. # Record, to fix up in GSUB 'locl' later. if merger.duplicateGlyphsPerFont[fontIdx].get(oldgid) is None: if glyphSets is not None: oldFontIdx = fontIndexForGlyph[oldgid] for idx in (fontIdx, oldFontIdx): if glyphSets[idx] is None: glyphSets[idx] = merger.fonts[idx].getGlyphSet() # if _glyphsAreSame(glyphSets[oldFontIdx], glyphSets[fontIdx], oldgid, gid): # continue merger.duplicateGlyphsPerFont[fontIdx][oldgid] = gid elif merger.duplicateGlyphsPerFont[fontIdx][oldgid] != gid: # Char previously mapped to oldgid but oldgid is already remapped to a different # gid, because of another Unicode character. # TODO: Try harder to do something about these. log.warning( "Dropped mapping from codepoint %#06X to glyphId '%s'", uni, gid )
merger.uvsDict = computeMegaUvs(merger, chosenUvsTables)
def renameCFFCharStrings(merger, glyphOrder, cffTable): """Rename topDictIndex charStrings based on glyphOrder.""" td = cffTable.cff.topDictIndex[0]
charStrings = {} for i, v in enumerate(td.CharStrings.charStrings.values()): glyphName = glyphOrder[i] charStrings[glyphName] = v td.CharStrings.charStrings = charStrings
td.charset = list(glyphOrder)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526# Copyright 2013 Google, Inc. All Rights Reserved.## Google Author(s): Behdad Esfahbod, Roozbeh Pournader
from fontTools import ttLibfrom fontTools.ttLib.tables.DefaultTable import DefaultTablefrom fontTools.ttLib.tables import otTablesfrom fontTools.merge.base import add_method, mergeObjectsfrom fontTools.merge.util import *import logging
log = logging.getLogger("fontTools.merge")
def mergeLookupLists(lst): # TODO Do smarter merge. return sumLists(lst)
def mergeFeatures(lst): assert lst self = otTables.Feature() self.FeatureParams = None self.LookupListIndex = mergeLookupLists( [l.LookupListIndex for l in lst if l.LookupListIndex] ) self.LookupCount = len(self.LookupListIndex) return self
def mergeFeatureLists(lst): d = {} for l in lst: for f in l: tag = f.FeatureTag if tag not in d: d[tag] = [] d[tag].append(f.Feature) ret = [] for tag in sorted(d.keys()): rec = otTables.FeatureRecord() rec.FeatureTag = tag rec.Feature = mergeFeatures(d[tag]) ret.append(rec) return ret
def mergeLangSyses(lst): assert lst
# TODO Support merging ReqFeatureIndex assert all(l.ReqFeatureIndex == 0xFFFF for l in lst)
self = otTables.LangSys() self.LookupOrder = None self.ReqFeatureIndex = 0xFFFF self.FeatureIndex = mergeFeatureLists( [l.FeatureIndex for l in lst if l.FeatureIndex] ) self.FeatureCount = len(self.FeatureIndex) return self
def mergeScripts(lst): assert lst
if len(lst) == 1: return lst[0] langSyses = {} for sr in lst: for lsr in sr.LangSysRecord: if lsr.LangSysTag not in langSyses: langSyses[lsr.LangSysTag] = [] langSyses[lsr.LangSysTag].append(lsr.LangSys) lsrecords = [] for tag, langSys_list in sorted(langSyses.items()): lsr = otTables.LangSysRecord() lsr.LangSys = mergeLangSyses(langSys_list) lsr.LangSysTag = tag lsrecords.append(lsr)
self = otTables.Script() self.LangSysRecord = lsrecords self.LangSysCount = len(lsrecords) dfltLangSyses = [s.DefaultLangSys for s in lst if s.DefaultLangSys] if dfltLangSyses: self.DefaultLangSys = mergeLangSyses(dfltLangSyses) else: self.DefaultLangSys = None return self
def mergeScriptRecords(lst): d = {} for l in lst: for s in l: tag = s.ScriptTag if tag not in d: d[tag] = [] d[tag].append(s.Script) ret = [] for tag in sorted(d.keys()): rec = otTables.ScriptRecord() rec.ScriptTag = tag rec.Script = mergeScripts(d[tag]) ret.append(rec) return ret
otTables.ScriptList.mergeMap = { "ScriptCount": lambda lst: None, # TODO "ScriptRecord": mergeScriptRecords,}otTables.BaseScriptList.mergeMap = { "BaseScriptCount": lambda lst: None, # TODO # TODO: Merge duplicate entries "BaseScriptRecord": lambda lst: sorted( sumLists(lst), key=lambda s: s.BaseScriptTag ),}
otTables.FeatureList.mergeMap = { "FeatureCount": sum, "FeatureRecord": lambda lst: sorted(sumLists(lst), key=lambda s: s.FeatureTag),}
otTables.LookupList.mergeMap = { "LookupCount": sum, "Lookup": sumLists,}
otTables.Coverage.mergeMap = { "Format": min, "glyphs": sumLists,}
otTables.ClassDef.mergeMap = { "Format": min, "classDefs": sumDicts,}
otTables.LigCaretList.mergeMap = { "Coverage": mergeObjects, "LigGlyphCount": sum, "LigGlyph": sumLists,}
otTables.AttachList.mergeMap = { "Coverage": mergeObjects, "GlyphCount": sum, "AttachPoint": sumLists,}
# XXX Renumber MarkFilterSets of lookupsotTables.MarkGlyphSetsDef.mergeMap = { "MarkSetTableFormat": equal, "MarkSetCount": sum, "Coverage": sumLists,}
otTables.Axis.mergeMap = { "*": mergeObjects,}
# XXX Fix BASE table mergingotTables.BaseTagList.mergeMap = { "BaseTagCount": sum, "BaselineTag": sumLists,}
otTables.GDEF.mergeMap = otTables.GSUB.mergeMap = otTables.GPOS.mergeMap = ( otTables.BASE.mergeMap) = otTables.JSTF.mergeMap = otTables.MATH.mergeMap = { "*": mergeObjects, "Version": max,}
ttLib.getTableClass("GDEF").mergeMap = ttLib.getTableClass("GSUB").mergeMap = ( ttLib.getTableClass("GPOS").mergeMap) = ttLib.getTableClass("BASE").mergeMap = ttLib.getTableClass( "JSTF").mergeMap = ttLib.getTableClass( "MATH").mergeMap = { "tableTag": onlyExisting(equal), # XXX clean me up "table": mergeObjects,}
@add_method(ttLib.getTableClass("GSUB"))def merge(self, m, tables): assert len(tables) == len(m.duplicateGlyphsPerFont) for i, (table, dups) in enumerate(zip(tables, m.duplicateGlyphsPerFont)): if not dups: continue if table is None or table is NotImplemented: log.warning( "Have non-identical duplicates to resolve for '%s' but no GSUB. Are duplicates intended?: %s", m.fonts[i]._merger__name, dups, ) continue
synthFeature = None synthLookup = None for script in table.table.ScriptList.ScriptRecord: if script.ScriptTag == "DFLT": continue # XXX for langsys in [script.Script.DefaultLangSys] + [ l.LangSys for l in script.Script.LangSysRecord ]: if langsys is None: continue # XXX Create! feature = [v for v in langsys.FeatureIndex if v.FeatureTag == "locl"] assert len(feature) <= 1 if feature: feature = feature[0] else: if not synthFeature: synthFeature = otTables.FeatureRecord() synthFeature.FeatureTag = "locl" f = synthFeature.Feature = otTables.Feature() f.FeatureParams = None f.LookupCount = 0 f.LookupListIndex = [] table.table.FeatureList.FeatureRecord.append(synthFeature) table.table.FeatureList.FeatureCount += 1 feature = synthFeature langsys.FeatureIndex.append(feature) langsys.FeatureIndex.sort(key=lambda v: v.FeatureTag)
if not synthLookup: subtable = otTables.SingleSubst() subtable.mapping = dups synthLookup = otTables.Lookup() synthLookup.LookupFlag = 0 synthLookup.LookupType = 1 synthLookup.SubTableCount = 1 synthLookup.SubTable = [subtable] if table.table.LookupList is None: # mtiLib uses None as default value for LookupList, # while feaLib points to an empty array with count 0 # TODO: make them do the same table.table.LookupList = otTables.LookupList() table.table.LookupList.Lookup = [] table.table.LookupList.LookupCount = 0 table.table.LookupList.Lookup.append(synthLookup) table.table.LookupList.LookupCount += 1
if feature.Feature.LookupListIndex[:1] != [synthLookup]: feature.Feature.LookupListIndex[:0] = [synthLookup] feature.Feature.LookupCount += 1
DefaultTable.merge(self, m, tables) return self
@add_method( otTables.SingleSubst, otTables.MultipleSubst, otTables.AlternateSubst, otTables.LigatureSubst, otTables.ReverseChainSingleSubst, otTables.SinglePos, otTables.PairPos, otTables.CursivePos, otTables.MarkBasePos, otTables.MarkLigPos, otTables.MarkMarkPos,)def mapLookups(self, lookupMap): pass
# Copied and trimmed down from subset.py@add_method( otTables.ContextSubst, otTables.ChainContextSubst, otTables.ContextPos, otTables.ChainContextPos,)def __merge_classify_context(self): class ContextHelper(object): def __init__(self, klass, Format): if klass.__name__.endswith("Subst"): Typ = "Sub" Type = "Subst" else: Typ = "Pos" Type = "Pos" if klass.__name__.startswith("Chain"): Chain = "Chain" else: Chain = "" ChainTyp = Chain + Typ
self.Typ = Typ self.Type = Type self.Chain = Chain self.ChainTyp = ChainTyp
self.LookupRecord = Type + "LookupRecord"
if Format == 1: self.Rule = ChainTyp + "Rule" self.RuleSet = ChainTyp + "RuleSet" elif Format == 2: self.Rule = ChainTyp + "ClassRule" self.RuleSet = ChainTyp + "ClassSet"
if self.Format not in [1, 2, 3]: return None # Don't shoot the messenger; let it go if not hasattr(self.__class__, "_merge__ContextHelpers"): self.__class__._merge__ContextHelpers = {} if self.Format not in self.__class__._merge__ContextHelpers: helper = ContextHelper(self.__class__, self.Format) self.__class__._merge__ContextHelpers[self.Format] = helper return self.__class__._merge__ContextHelpers[self.Format]
@add_method( otTables.ContextSubst, otTables.ChainContextSubst, otTables.ContextPos, otTables.ChainContextPos,)def mapLookups(self, lookupMap): c = self.__merge_classify_context()
if self.Format in [1, 2]: for rs in getattr(self, c.RuleSet): if not rs: continue for r in getattr(rs, c.Rule): if not r: continue for ll in getattr(r, c.LookupRecord): if not ll: continue ll.LookupListIndex = lookupMap[ll.LookupListIndex] elif self.Format == 3: for ll in getattr(self, c.LookupRecord): if not ll: continue ll.LookupListIndex = lookupMap[ll.LookupListIndex] else: assert 0, "unknown format: %s" % self.Format
@add_method(otTables.ExtensionSubst, otTables.ExtensionPos)def mapLookups(self, lookupMap): if self.Format == 1: self.ExtSubTable.mapLookups(lookupMap) else: assert 0, "unknown format: %s" % self.Format
@add_method(otTables.Lookup)def mapLookups(self, lookupMap): for st in self.SubTable: if not st: continue st.mapLookups(lookupMap)
@add_method(otTables.LookupList)def mapLookups(self, lookupMap): for l in self.Lookup: if not l: continue l.mapLookups(lookupMap)
@add_method(otTables.Lookup)def mapMarkFilteringSets(self, markFilteringSetMap): if self.LookupFlag & 0x0010: self.MarkFilteringSet = markFilteringSetMap[self.MarkFilteringSet]
@add_method(otTables.LookupList)def mapMarkFilteringSets(self, markFilteringSetMap): for l in self.Lookup: if not l: continue l.mapMarkFilteringSets(markFilteringSetMap)
@add_method(otTables.Feature)def mapLookups(self, lookupMap): self.LookupListIndex = [lookupMap[i] for i in self.LookupListIndex]
@add_method(otTables.FeatureList)def mapLookups(self, lookupMap): for f in self.FeatureRecord: if not f or not f.Feature: continue f.Feature.mapLookups(lookupMap)
@add_method(otTables.DefaultLangSys, otTables.LangSys)def mapFeatures(self, featureMap): self.FeatureIndex = [featureMap[i] for i in self.FeatureIndex] if self.ReqFeatureIndex != 65535: self.ReqFeatureIndex = featureMap[self.ReqFeatureIndex]
@add_method(otTables.Script)def mapFeatures(self, featureMap): if self.DefaultLangSys: self.DefaultLangSys.mapFeatures(featureMap) for l in self.LangSysRecord: if not l or not l.LangSys: continue l.LangSys.mapFeatures(featureMap)
@add_method(otTables.ScriptList)def mapFeatures(self, featureMap): for s in self.ScriptRecord: if not s or not s.Script: continue s.Script.mapFeatures(featureMap)
def layoutPreMerge(font): # Map indices to references
GDEF = font.get("GDEF") GSUB = font.get("GSUB") GPOS = font.get("GPOS")
for t in [GSUB, GPOS]: if not t: continue
if t.table.LookupList: lookupMap = {i: v for i, v in enumerate(t.table.LookupList.Lookup)} t.table.LookupList.mapLookups(lookupMap) t.table.FeatureList.mapLookups(lookupMap)
if ( GDEF and GDEF.table.Version >= 0x00010002 and GDEF.table.MarkGlyphSetsDef ): markFilteringSetMap = { i: v for i, v in enumerate(GDEF.table.MarkGlyphSetsDef.Coverage) } t.table.LookupList.mapMarkFilteringSets(markFilteringSetMap)
if t.table.FeatureList and t.table.ScriptList: featureMap = {i: v for i, v in enumerate(t.table.FeatureList.FeatureRecord)} t.table.ScriptList.mapFeatures(featureMap)
# TODO FeatureParams nameIDs
def layoutPostMerge(font): # Map references back to indices
GDEF = font.get("GDEF") GSUB = font.get("GSUB") GPOS = font.get("GPOS")
for t in [GSUB, GPOS]: if not t: continue
if t.table.FeatureList and t.table.ScriptList: # Collect unregistered (new) features. featureMap = GregariousIdentityDict(t.table.FeatureList.FeatureRecord) t.table.ScriptList.mapFeatures(featureMap)
# Record used features. featureMap = AttendanceRecordingIdentityDict( t.table.FeatureList.FeatureRecord ) t.table.ScriptList.mapFeatures(featureMap) usedIndices = featureMap.s
# Remove unused features t.table.FeatureList.FeatureRecord = [ f for i, f in enumerate(t.table.FeatureList.FeatureRecord) if i in usedIndices ]
# Map back to indices. featureMap = NonhashableDict(t.table.FeatureList.FeatureRecord) t.table.ScriptList.mapFeatures(featureMap)
t.table.FeatureList.FeatureCount = len(t.table.FeatureList.FeatureRecord)
if t.table.LookupList: # Collect unregistered (new) lookups. lookupMap = GregariousIdentityDict(t.table.LookupList.Lookup) t.table.FeatureList.mapLookups(lookupMap) t.table.LookupList.mapLookups(lookupMap)
# Record used lookups. lookupMap = AttendanceRecordingIdentityDict(t.table.LookupList.Lookup) t.table.FeatureList.mapLookups(lookupMap) t.table.LookupList.mapLookups(lookupMap) usedIndices = lookupMap.s
# Remove unused lookups t.table.LookupList.Lookup = [ l for i, l in enumerate(t.table.LookupList.Lookup) if i in usedIndices ]
# Map back to indices. lookupMap = NonhashableDict(t.table.LookupList.Lookup) t.table.FeatureList.mapLookups(lookupMap) t.table.LookupList.mapLookups(lookupMap)
t.table.LookupList.LookupCount = len(t.table.LookupList.Lookup)
if GDEF and GDEF.table.Version >= 0x00010002: markFilteringSetMap = NonhashableDict( GDEF.table.MarkGlyphSetsDef.Coverage ) t.table.LookupList.mapMarkFilteringSets(markFilteringSetMap)
# TODO FeatureParams nameIDs12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485# Copyright 2013 Google, Inc. All Rights Reserved.## Google Author(s): Behdad Esfahbod, Roozbeh Pournader
class Options(object): class UnknownOptionError(Exception): pass
def __init__(self, **kwargs): self.verbose = False self.timing = False self.drop_tables = [] self.input_file = None self.output_file = "merged.ttf" self.import_file = None
self.set(**kwargs)
def set(self, **kwargs): for k, v in kwargs.items(): if not hasattr(self, k): raise self.UnknownOptionError("Unknown option '%s'" % k) setattr(self, k, v)
def parse_opts(self, argv, ignore_unknown=[]): ret = [] opts = {} for a in argv: orig_a = a if not a.startswith("--"): ret.append(a) continue a = a[2:] i = a.find("=") op = "=" if i == -1: if a.startswith("no-"): k = a[3:] v = False else: k = a v = True else: k = a[:i] if k[-1] in "-+": op = k[-1] + "=" # Ops is '-=' or '+=' now. k = k[:-1] v = a[i + 1 :] ok = k k = k.replace("-", "_") if not hasattr(self, k): if ignore_unknown is True or ok in ignore_unknown: ret.append(orig_a) continue else: raise self.UnknownOptionError("Unknown option '%s'" % a)
ov = getattr(self, k) if isinstance(ov, bool): v = bool(v) elif isinstance(ov, int): v = int(v) elif isinstance(ov, list): vv = v.split(",") if vv == [""]: vv = [] vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv] if op == "=": v = vv elif op == "+=": v = ov v.extend(vv) elif op == "-=": v = ov for x in vv: if x in v: v.remove(x) else: assert 0
opts[k] = v self.set(**opts)
return ret123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352# Copyright 2013 Google, Inc. All Rights Reserved.## Google Author(s): Behdad Esfahbod, Roozbeh Pournader
from fontTools import ttLib, cffLibfrom fontTools.misc.psCharStrings import T2WidthExtractorfrom fontTools.ttLib.tables.DefaultTable import DefaultTablefrom fontTools.merge.base import add_method, mergeObjectsfrom fontTools.merge.cmap import computeMegaCmapfrom fontTools.merge.util import *import logging
log = logging.getLogger("fontTools.merge")
ttLib.getTableClass("maxp").mergeMap = { "*": max, "tableTag": equal, "tableVersion": equal, "numGlyphs": sum, "maxStorage": first, "maxFunctionDefs": first, "maxInstructionDefs": first, # TODO When we correctly merge hinting data, update these values: # maxFunctionDefs, maxInstructionDefs, maxSizeOfInstructions}
headFlagsMergeBitMap = { "size": 16, "*": bitwise_or, 1: bitwise_and, # Baseline at y = 0 2: bitwise_and, # lsb at x = 0 3: bitwise_and, # Force ppem to integer values. FIXME? 5: bitwise_and, # Font is vertical 6: lambda bit: 0, # Always set to zero 11: bitwise_and, # Font data is 'lossless' 13: bitwise_and, # Optimized for ClearType 14: bitwise_and, # Last resort font. FIXME? equal or first may be better 15: lambda bit: 0, # Always set to zero}
ttLib.getTableClass("head").mergeMap = { "tableTag": equal, "tableVersion": max, "fontRevision": max, "checkSumAdjustment": lambda lst: 0, # We need *something* here "magicNumber": equal, "flags": mergeBits(headFlagsMergeBitMap), "unitsPerEm": equal, "created": current_time, "modified": current_time, "xMin": min, "yMin": min, "xMax": max, "yMax": max, "macStyle": first, "lowestRecPPEM": max, "fontDirectionHint": lambda lst: 2, "indexToLocFormat": first, "glyphDataFormat": equal,}
ttLib.getTableClass("hhea").mergeMap = { "*": equal, "tableTag": equal, "tableVersion": max, "ascent": max, "descent": min, "lineGap": max, "advanceWidthMax": max, "minLeftSideBearing": min, "minRightSideBearing": min, "xMaxExtent": max, "caretSlopeRise": first, "caretSlopeRun": first, "caretOffset": first, "numberOfHMetrics": recalculate,}
ttLib.getTableClass("vhea").mergeMap = { "*": equal, "tableTag": equal, "tableVersion": max, "ascent": max, "descent": min, "lineGap": max, "advanceHeightMax": max, "minTopSideBearing": min, "minBottomSideBearing": min, "yMaxExtent": max, "caretSlopeRise": first, "caretSlopeRun": first, "caretOffset": first, "numberOfVMetrics": recalculate,}
os2FsTypeMergeBitMap = { "size": 16, "*": lambda bit: 0, 1: bitwise_or, # no embedding permitted 2: bitwise_and, # allow previewing and printing documents 3: bitwise_and, # allow editing documents 8: bitwise_or, # no subsetting permitted 9: bitwise_or, # no embedding of outlines permitted}
def mergeOs2FsType(lst): lst = list(lst) if all(item == 0 for item in lst): return 0
# Compute least restrictive logic for each fsType value for i in range(len(lst)): # unset bit 1 (no embedding permitted) if either bit 2 or 3 is set if lst[i] & 0x000C: lst[i] &= ~0x0002 # set bit 2 (allow previewing) if bit 3 is set (allow editing) elif lst[i] & 0x0008: lst[i] |= 0x0004 # set bits 2 and 3 if everything is allowed elif lst[i] == 0: lst[i] = 0x000C
fsType = mergeBits(os2FsTypeMergeBitMap)(lst) # unset bits 2 and 3 if bit 1 is set (some font is "no embedding") if fsType & 0x0002: fsType &= ~0x000C return fsType
ttLib.getTableClass("OS/2").mergeMap = { "*": first, "tableTag": equal, "version": max, "xAvgCharWidth": first, # Will be recalculated at the end on the merged font "fsType": mergeOs2FsType, # Will be overwritten "panose": first, # FIXME: should really be the first Latin font "ulUnicodeRange1": bitwise_or, "ulUnicodeRange2": bitwise_or, "ulUnicodeRange3": bitwise_or, "ulUnicodeRange4": bitwise_or, "fsFirstCharIndex": min, "fsLastCharIndex": max, "sTypoAscender": max, "sTypoDescender": min, "sTypoLineGap": max, "usWinAscent": max, "usWinDescent": max, # Version 1 "ulCodePageRange1": onlyExisting(bitwise_or), "ulCodePageRange2": onlyExisting(bitwise_or), # Version 2, 3, 4 "sxHeight": onlyExisting(max), "sCapHeight": onlyExisting(max), "usDefaultChar": onlyExisting(first), "usBreakChar": onlyExisting(first), "usMaxContext": onlyExisting(max), # version 5 "usLowerOpticalPointSize": onlyExisting(min), "usUpperOpticalPointSize": onlyExisting(max),}
@add_method(ttLib.getTableClass("OS/2"))def merge(self, m, tables): DefaultTable.merge(self, m, tables) if self.version < 2: # bits 8 and 9 are reserved and should be set to zero self.fsType &= ~0x0300 if self.version >= 3: # Only one of bits 1, 2, and 3 may be set. We already take # care of bit 1 implications in mergeOs2FsType. So unset # bit 2 if bit 3 is already set. if self.fsType & 0x0008: self.fsType &= ~0x0004 return self
ttLib.getTableClass("post").mergeMap = { "*": first, "tableTag": equal, "formatType": max, "isFixedPitch": min, "minMemType42": max, "maxMemType42": lambda lst: 0, "minMemType1": max, "maxMemType1": lambda lst: 0, "mapping": onlyExisting(sumDicts), "extraNames": lambda lst: [],}
ttLib.getTableClass("vmtx").mergeMap = ttLib.getTableClass("hmtx").mergeMap = { "tableTag": equal, "metrics": sumDicts,}
ttLib.getTableClass("name").mergeMap = { "tableTag": equal, "names": first, # FIXME? Does mixing name records make sense?}
ttLib.getTableClass("loca").mergeMap = { "*": recalculate, "tableTag": equal,}
ttLib.getTableClass("glyf").mergeMap = { "tableTag": equal, "glyphs": sumDicts, "glyphOrder": sumLists, "_reverseGlyphOrder": recalculate, "axisTags": equal,}
@add_method(ttLib.getTableClass("glyf"))def merge(self, m, tables): for i, table in enumerate(tables): for g in table.glyphs.values(): if i: # Drop hints for all but first font, since # we don't map functions / CVT values. g.removeHinting() # Expand composite glyphs to load their # composite glyph names. if g.isComposite(): g.expand(table) return DefaultTable.merge(self, m, tables)
ttLib.getTableClass("prep").mergeMap = lambda self, lst: first(lst)ttLib.getTableClass("fpgm").mergeMap = lambda self, lst: first(lst)ttLib.getTableClass("cvt ").mergeMap = lambda self, lst: first(lst)ttLib.getTableClass("gasp").mergeMap = lambda self, lst: first( lst) # FIXME? Appears irreconcilable
@add_method(ttLib.getTableClass("CFF "))def merge(self, m, tables): if any(hasattr(table.cff[0], "FDSelect") for table in tables): raise NotImplementedError("Merging CID-keyed CFF tables is not supported yet")
for table in tables: table.cff.desubroutinize()
newcff = tables[0] newfont = newcff.cff[0] private = newfont.Private newDefaultWidthX, newNominalWidthX = private.defaultWidthX, private.nominalWidthX storedNamesStrings = [] glyphOrderStrings = [] glyphOrder = set(newfont.getGlyphOrder())
for name in newfont.strings.strings: if name not in glyphOrder: storedNamesStrings.append(name) else: glyphOrderStrings.append(name)
chrset = list(newfont.charset) newcs = newfont.CharStrings log.debug("FONT 0 CharStrings: %d.", len(newcs))
for i, table in enumerate(tables[1:], start=1): font = table.cff[0] defaultWidthX, nominalWidthX = ( font.Private.defaultWidthX, font.Private.nominalWidthX, ) widthsDiffer = ( defaultWidthX != newDefaultWidthX or nominalWidthX != newNominalWidthX ) font.Private = private fontGlyphOrder = set(font.getGlyphOrder()) for name in font.strings.strings: if name in fontGlyphOrder: glyphOrderStrings.append(name) cs = font.CharStrings gs = table.cff.GlobalSubrs log.debug("Font %d CharStrings: %d.", i, len(cs)) chrset.extend(font.charset) if newcs.charStringsAreIndexed: for i, name in enumerate(cs.charStrings, start=len(newcs)): newcs.charStrings[name] = i newcs.charStringsIndex.items.append(None) for name in cs.charStrings: if widthsDiffer: c = cs[name] defaultWidthXToken = object() extractor = T2WidthExtractor([], [], nominalWidthX, defaultWidthXToken) extractor.execute(c) width = extractor.width if width is not defaultWidthXToken: # The following will be wrong if the width is added # by a subroutine. Ouch! c.program.pop(0) else: width = defaultWidthX if width != newDefaultWidthX: c.program.insert(0, width - newNominalWidthX) newcs[name] = cs[name]
newfont.charset = chrset newfont.numGlyphs = len(chrset) newfont.strings.strings = glyphOrderStrings + storedNamesStrings
return newcff
@add_method(ttLib.getTableClass("cmap"))def merge(self, m, tables): if not hasattr(m, "cmap"): computeMegaCmap(m, tables) cmap = m.cmap
cmapBmpOnly = {uni: gid for uni, gid in cmap.items() if uni <= 0xFFFF} self.tables = [] module = ttLib.getTableModule("cmap") if len(cmapBmpOnly) != len(cmap): # format-12 required. cmapTable = module.cmap_classes[12](12) cmapTable.platformID = 3 cmapTable.platEncID = 10 cmapTable.language = 0 cmapTable.cmap = cmap self.tables.append(cmapTable) # always create format-4 cmapTable = module.cmap_classes[4](4) cmapTable.platformID = 3 cmapTable.platEncID = 1 cmapTable.language = 0 cmapTable.cmap = cmapBmpOnly # ordered by platform then encoding self.tables.insert(0, cmapTable)
uvsDict = m.uvsDict if uvsDict: # format-14 uvsTable = module.cmap_classes[14](14) uvsTable.platformID = 0 uvsTable.platEncID = 5 uvsTable.language = 0 uvsTable.cmap = {} uvsTable.uvsDict = uvsDict # ordered by platform then encoding self.tables.insert(0, uvsTable) self.tableVersion = 0 self.numSubTables = len(self.tables) return self123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778# Copyright 2021 Behdad Esfahbod. All Rights Reserved.
def is_Default_Ignorable(u): # http://www.unicode.org/reports/tr44/#Default_Ignorable_Code_Point # # TODO Move me to unicodedata module and autogenerate. # # Unicode 14.0: # $ grep '; Default_Ignorable_Code_Point ' DerivedCoreProperties.txt | sed 's/;.*#/#/' # 00AD # Cf SOFT HYPHEN # 034F # Mn COMBINING GRAPHEME JOINER # 061C # Cf ARABIC LETTER MARK # 115F..1160 # Lo [2] HANGUL CHOSEONG FILLER..HANGUL JUNGSEONG FILLER # 17B4..17B5 # Mn [2] KHMER VOWEL INHERENT AQ..KHMER VOWEL INHERENT AA # 180B..180D # Mn [3] MONGOLIAN FREE VARIATION SELECTOR ONE..MONGOLIAN FREE VARIATION SELECTOR THREE # 180E # Cf MONGOLIAN VOWEL SEPARATOR # 180F # Mn MONGOLIAN FREE VARIATION SELECTOR FOUR # 200B..200F # Cf [5] ZERO WIDTH SPACE..RIGHT-TO-LEFT MARK # 202A..202E # Cf [5] LEFT-TO-RIGHT EMBEDDING..RIGHT-TO-LEFT OVERRIDE # 2060..2064 # Cf [5] WORD JOINER..INVISIBLE PLUS # 2065 # Cn <reserved-2065> # 2066..206F # Cf [10] LEFT-TO-RIGHT ISOLATE..NOMINAL DIGIT SHAPES # 3164 # Lo HANGUL FILLER # FE00..FE0F # Mn [16] VARIATION SELECTOR-1..VARIATION SELECTOR-16 # FEFF # Cf ZERO WIDTH NO-BREAK SPACE # FFA0 # Lo HALFWIDTH HANGUL FILLER # FFF0..FFF8 # Cn [9] <reserved-FFF0>..<reserved-FFF8> # 1BCA0..1BCA3 # Cf [4] SHORTHAND FORMAT LETTER OVERLAP..SHORTHAND FORMAT UP STEP # 1D173..1D17A # Cf [8] MUSICAL SYMBOL BEGIN BEAM..MUSICAL SYMBOL END PHRASE # E0000 # Cn <reserved-E0000> # E0001 # Cf LANGUAGE TAG # E0002..E001F # Cn [30] <reserved-E0002>..<reserved-E001F> # E0020..E007F # Cf [96] TAG SPACE..CANCEL TAG # E0080..E00FF # Cn [128] <reserved-E0080>..<reserved-E00FF> # E0100..E01EF # Mn [240] VARIATION SELECTOR-17..VARIATION SELECTOR-256 # E01F0..E0FFF # Cn [3600] <reserved-E01F0>..<reserved-E0FFF> return ( u == 0x00AD or u == 0x034F # Cf SOFT HYPHEN or u == 0x061C # Mn COMBINING GRAPHEME JOINER or 0x115F <= u <= 0x1160 # Cf ARABIC LETTER MARK or 0x17B4 # Lo [2] HANGUL CHOSEONG FILLER..HANGUL JUNGSEONG FILLER <= u <= 0x17B5 or 0x180B # Mn [2] KHMER VOWEL INHERENT AQ..KHMER VOWEL INHERENT AA <= u <= 0x180D or u # Mn [3] MONGOLIAN FREE VARIATION SELECTOR ONE..MONGOLIAN FREE VARIATION SELECTOR THREE == 0x180E or u == 0x180F # Cf MONGOLIAN VOWEL SEPARATOR or 0x200B <= u <= 0x200F # Mn MONGOLIAN FREE VARIATION SELECTOR FOUR or 0x202A <= u <= 0x202E # Cf [5] ZERO WIDTH SPACE..RIGHT-TO-LEFT MARK or 0x2060 # Cf [5] LEFT-TO-RIGHT EMBEDDING..RIGHT-TO-LEFT OVERRIDE <= u <= 0x2064 or u == 0x2065 # Cf [5] WORD JOINER..INVISIBLE PLUS or 0x2066 <= u <= 0x206F # Cn <reserved-2065> or u == 0x3164 # Cf [10] LEFT-TO-RIGHT ISOLATE..NOMINAL DIGIT SHAPES or 0xFE00 <= u <= 0xFE0F # Lo HANGUL FILLER or u == 0xFEFF # Mn [16] VARIATION SELECTOR-1..VARIATION SELECTOR-16 or u == 0xFFA0 # Cf ZERO WIDTH NO-BREAK SPACE or 0xFFF0 <= u <= 0xFFF8 # Lo HALFWIDTH HANGUL FILLER or 0x1BCA0 <= u <= 0x1BCA3 # Cn [9] <reserved-FFF0>..<reserved-FFF8> or 0x1D173 # Cf [4] SHORTHAND FORMAT LETTER OVERLAP..SHORTHAND FORMAT UP STEP <= u <= 0x1D17A or u == 0xE0000 # Cf [8] MUSICAL SYMBOL BEGIN BEAM..MUSICAL SYMBOL END PHRASE or u == 0xE0001 # Cn <reserved-E0000> or 0xE0002 <= u <= 0xE001F # Cf LANGUAGE TAG or 0xE0020 <= u <= 0xE007F # Cn [30] <reserved-E0002>..<reserved-E001F> or 0xE0080 <= u <= 0xE00FF # Cf [96] TAG SPACE..CANCEL TAG or 0xE0100 <= u <= 0xE01EF # Cn [128] <reserved-E0080>..<reserved-E00FF> or 0xE01F0 # Mn [240] VARIATION SELECTOR-17..VARIATION SELECTOR-256 <= u <= 0xE0FFF or False # Cn [3600] <reserved-E01F0>..<reserved-E0FFF> )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143# Copyright 2013 Google, Inc. All Rights Reserved.## Google Author(s): Behdad Esfahbod, Roozbeh Pournader
from fontTools.misc.timeTools import timestampNowfrom fontTools.ttLib.tables.DefaultTable import DefaultTablefrom functools import reduceimport operatorimport logging
log = logging.getLogger("fontTools.merge")
# General utility functions for merging values from different fonts
def equal(lst): lst = list(lst) t = iter(lst) first = next(t) assert all(item == first for item in t), "Expected all items to be equal: %s" % lst return first
def first(lst): return next(iter(lst))
def recalculate(lst): return NotImplemented
def current_time(lst): return timestampNow()
def bitwise_and(lst): return reduce(operator.and_, lst)
def bitwise_or(lst): return reduce(operator.or_, lst)
def avg_int(lst): lst = list(lst) return sum(lst) // len(lst)
def onlyExisting(func): """Returns a filter func that when called with a list, only calls func on the non-NotImplemented items of the list, and only so if there's at least one item remaining. Otherwise returns NotImplemented."""
def wrapper(lst): items = [item for item in lst if item is not NotImplemented] return func(items) if items else NotImplemented
return wrapper
def sumLists(lst): l = [] for item in lst: l.extend(item) return l
def sumDicts(lst): d = {} for item in lst: d.update(item) return d
def mergeBits(bitmap): def wrapper(lst): lst = list(lst) returnValue = 0 for bitNumber in range(bitmap["size"]): try: mergeLogic = bitmap[bitNumber] except KeyError: try: mergeLogic = bitmap["*"] except KeyError: raise Exception("Don't know how to merge bit %s" % bitNumber) shiftedBit = 1 << bitNumber mergedValue = mergeLogic(bool(item & shiftedBit) for item in lst) returnValue |= mergedValue << bitNumber return returnValue
return wrapper
class AttendanceRecordingIdentityDict(object): """A dictionary-like object that records indices of items actually accessed from a list."""
def __init__(self, lst): self.l = lst self.d = {id(v): i for i, v in enumerate(lst)} self.s = set()
def __getitem__(self, v): self.s.add(self.d[id(v)]) return v
class GregariousIdentityDict(object): """A dictionary-like object that welcomes guests without reservations and adds them to the end of the guest list."""
def __init__(self, lst): self.l = lst self.s = set(id(v) for v in lst)
def __getitem__(self, v): if id(v) not in self.s: self.s.add(id(v)) self.l.append(v) return v
class NonhashableDict(object): """A dictionary-like object mapping objects to values."""
def __init__(self, keys, values=None): if values is None: self.d = {id(v): i for i, v in enumerate(keys)} else: self.d = {id(k): v for k, v in zip(keys, values)}
def __getitem__(self, k): return self.d[id(k)]
def __setitem__(self, k, v): self.d[id(k)] = v
def __delitem__(self, k): del self.d[id(k)]1"""Empty __init__.py file to signal Python this directory is a package."""lib/python3.12/site-packages/fontTools/__pycache__/__main__.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/__pycache__/afmLib.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/__pycache__/fontBuilder.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/__pycache__/help.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/__pycache__/tfmLib.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/__pycache__/ttx.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/__pycache__/unicode.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/cffLib/CFF2ToCFF.pyAdded+258
lib/python3.12/site-packages/fontTools/cffLib/CFFToCFF2.pyAdded+305
lib/python3.12/site-packages/fontTools/cffLib/__init__.pyAdded
lib/python3.12/site-packages/fontTools/cffLib/__pycache__/CFF2ToCFF.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/cffLib/__pycache__/CFFToCFF2.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/cffLib/__pycache__/specializer.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/cffLib/__pycache__/transforms.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/cffLib/__pycache__/width.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/cffLib/specializer.pyAdded+927
lib/python3.12/site-packages/fontTools/cffLib/transforms.pyAdded+495
lib/python3.12/site-packages/fontTools/cffLib/width.pyAdded+210
lib/python3.12/site-packages/fontTools/config/__init__.pyAdded+90
lib/python3.12/site-packages/fontTools/config/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/merge/__init__.pyAdded+248
lib/python3.12/site-packages/fontTools/merge/__main__.pyAdded+6
lib/python3.12/site-packages/fontTools/merge/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/merge/__pycache__/__main__.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/merge/__pycache__/base.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/merge/__pycache__/cmap.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/merge/__pycache__/layout.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/merge/__pycache__/options.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/merge/__pycache__/tables.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/merge/__pycache__/unicode.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/merge/__pycache__/util.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/merge/base.pyAdded+81
lib/python3.12/site-packages/fontTools/merge/cmap.pyAdded+173
lib/python3.12/site-packages/fontTools/merge/layout.pyAdded+526
lib/python3.12/site-packages/fontTools/merge/options.pyAdded+85
lib/python3.12/site-packages/fontTools/merge/tables.pyAdded+352
lib/python3.12/site-packages/fontTools/merge/unicode.pyAdded+78
lib/python3.12/site-packages/fontTools/merge/util.pyAdded+143
lib/python3.12/site-packages/fontTools/misc/__init__.pyAdded+1
lib/python3.12/site-packages/fontTools/misc/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/misc/__pycache__/arrayTools.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/misc/__pycache__/bezierTools.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/misc/__pycache__/classifyTools.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/misc/__pycache__/cliTools.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/misc/__pycache__/configTools.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/misc/__pycache__/cython.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/misc/__pycache__/dictTools.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/misc/__pycache__/eexec.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/misc/__pycache__/encodingTools.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/misc/__pycache__/enumTools.cpython-312.pycAdded