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/__init__.pyAdded+8
- lib/python3.12/site-packages/fontTools/__main__.pyAdded+35
- lib/python3.12/site-packages/fontTools/afmLib.pyAdded+439
- lib/python3.12/site-packages/fontTools/agl.pyAdded
- lib/python3.12/site-packages/fontTools/annotations.pyAdded+30
- lib/python3.12/site-packages/fontTools/colorLib/__init__.pyAdded
- lib/python3.12/site-packages/fontTools/colorLib/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/colorLib/__pycache__/builder.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/colorLib/__pycache__/errors.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/colorLib/__pycache__/geometry.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/colorLib/__pycache__/table_builder.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/colorLib/__pycache__/unbuilder.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/colorLib/builder.pyAdded+664
- lib/python3.12/site-packages/fontTools/colorLib/errors.pyAdded+2
- lib/python3.12/site-packages/fontTools/colorLib/geometry.pyAdded+143
- lib/python3.12/site-packages/fontTools/colorLib/table_builder.pyAdded+223
- lib/python3.12/site-packages/fontTools/colorLib/unbuilder.pyAdded+81
- lib/python3.12/site-packages/fontTools/designspaceLib/__init__.pyAdded
- lib/python3.12/site-packages/fontTools/designspaceLib/__main__.pyAdded+6
- lib/python3.12/site-packages/fontTools/designspaceLib/__pycache__/__main__.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/designspaceLib/__pycache__/split.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/designspaceLib/__pycache__/statNames.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/designspaceLib/__pycache__/types.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/designspaceLib/split.pyAdded+475
- lib/python3.12/site-packages/fontTools/designspaceLib/statNames.pyAdded+260
- lib/python3.12/site-packages/fontTools/designspaceLib/types.pyAdded+147
- lib/python3.12/site-packages/fontTools/encodings/MacRoman.pyAdded+258
- lib/python3.12/site-packages/fontTools/encodings/StandardEncoding.pyAdded+258
- lib/python3.12/site-packages/fontTools/encodings/__init__.pyAdded+1
- lib/python3.12/site-packages/fontTools/encodings/__pycache__/MacRoman.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/encodings/__pycache__/StandardEncoding.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/encodings/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/encodings/__pycache__/codecs.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/encodings/codecs.pyAdded+135
- lib/python3.12/site-packages/fontTools/fontBuilder.pyAdded+1014
- lib/python3.12/site-packages/fontTools/help.pyAdded+36
- lib/python3.12/site-packages/fontTools/mtiLib/__init__.pyAdded+1400
- lib/python3.12/site-packages/fontTools/mtiLib/__main__.pyAdded+5
- lib/python3.12/site-packages/fontTools/mtiLib/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/mtiLib/__pycache__/__main__.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/otlLib/__init__.pyAdded+1
- lib/python3.12/site-packages/fontTools/otlLib/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/otlLib/__pycache__/error.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/otlLib/__pycache__/maxContextCalc.cpython-312.pycAdded
- lib/python3.12/site-packages/fontTools/otlLib/builder.pyAdded
- lib/python3.12/site-packages/fontTools/otlLib/error.pyAdded+11
- lib/python3.12/site-packages/fontTools/otlLib/maxContextCalc.pyAdded+96
- lib/python3.12/site-packages/fontTools/otlLib/optimize/__init__.pyAdded+53
- lib/python3.12/site-packages/fontTools/otlLib/optimize/__main__.pyAdded+6
- lib/python3.12/site-packages/fontTools/otlLib/optimize/__pycache__/__init__.cpython-312.pycAdded
12345678import loggingfrom fontTools.misc.loggingTools import configLogger
log = logging.getLogger(__name__)
version = __version__ = "4.61.1"
__all__ = ["version", "log", "configLogger"]1234567891011121314151617181920212223242526272829303132333435import sys
def main(args=None): if args is None: args = sys.argv[1:]
# TODO Handle library-wide options. Eg.: # --unicodedata # --verbose / other logging stuff
# TODO Allow a way to run arbitrary modules? Useful for setting # library-wide options and calling another library. Eg.: # # $ fonttools --unicodedata=... fontmake ... # # This allows for a git-like command where thirdparty commands # can be added. Should we just try importing the fonttools # module first and try without if it fails?
if len(sys.argv) < 2: sys.argv.append("help") if sys.argv[1] == "-h" or sys.argv[1] == "--help": sys.argv[1] = "help" mod = "fontTools." + sys.argv[1] sys.argv[1] = sys.argv[0] + " " + sys.argv[1] del sys.argv[0]
import runpy
runpy.run_module(mod, run_name="__main__")
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439"""Module for reading and writing AFM (Adobe Font Metrics) files.
Note that this has been designed to read in AFM files generated by Fontographerand has not been tested on many other files. In particular, it does notimplement the whole Adobe AFM specification [#f1]_ but, it should read most"common" AFM files.
Here is an example of using `afmLib` to read, modify and write an AFM file:
>>> from fontTools.afmLib import AFM >>> f = AFM("Tests/afmLib/data/TestAFM.afm") >>> >>> # Accessing a pair gets you the kern value >>> f[("V","A")] -60 >>> >>> # Accessing a glyph name gets you metrics >>> f["A"] (65, 668, (8, -25, 660, 666)) >>> # (charnum, width, bounding box) >>> >>> # Accessing an attribute gets you metadata >>> f.FontName 'TestFont-Regular' >>> f.FamilyName 'TestFont' >>> f.Weight 'Regular' >>> f.XHeight 500 >>> f.Ascender 750 >>> >>> # Attributes and items can also be set >>> f[("A","V")] = -150 # Tighten kerning >>> f.FontName = "TestFont Squished" >>> >>> # And the font written out again (remove the # in front) >>> #f.write("testfont-squished.afm")
.. rubric:: Footnotes
.. [#f1] `Adobe Technote 5004 <https://www.adobe.com/content/dam/acom/en/devnet/font/pdfs/5004.AFM_Spec.pdf>`_, Adobe Font Metrics File Format Specification.
"""
import re
# every single line starts with a "word"identifierRE = re.compile(r"^([A-Za-z]+).*")
# regular expression to parse char linescharRE = re.compile( r"(-?\d+)" # charnum r"\s*;\s*WX\s+" # ; WX r"(-?\d+)" # width r"\s*;\s*N\s+" # ; N r"([.A-Za-z0-9_]+)" # charname r"\s*;\s*B\s+" # ; B r"(-?\d+)" # left r"\s+" r"(-?\d+)" # bottom r"\s+" r"(-?\d+)" # right r"\s+" r"(-?\d+)" # top r"\s*;\s*" # ;)
# regular expression to parse kerning lineskernRE = re.compile( r"([.A-Za-z0-9_]+)" # leftchar r"\s+" r"([.A-Za-z0-9_]+)" # rightchar r"\s+" r"(-?\d+)" # value r"\s*")
# regular expressions to parse composite info lines of the form:# Aacute 2 ; PCC A 0 0 ; PCC acute 182 211 ;compositeRE = re.compile( r"([.A-Za-z0-9_]+)" # char name r"\s+" r"(\d+)" # number of parts r"\s*;\s*")componentRE = re.compile( r"PCC\s+" # PPC r"([.A-Za-z0-9_]+)" # base char name r"\s+" r"(-?\d+)" # x offset r"\s+" r"(-?\d+)" # y offset r"\s*;\s*")
preferredAttributeOrder = [ "FontName", "FullName", "FamilyName", "Weight", "ItalicAngle", "IsFixedPitch", "FontBBox", "UnderlinePosition", "UnderlineThickness", "Version", "Notice", "EncodingScheme", "CapHeight", "XHeight", "Ascender", "Descender",]
class error(Exception): pass
class AFM(object): _attrs = None
_keywords = [ "StartFontMetrics", "EndFontMetrics", "StartCharMetrics", "EndCharMetrics", "StartKernData", "StartKernPairs", "EndKernPairs", "EndKernData", "StartComposites", "EndComposites", ]
def __init__(self, path=None): """AFM file reader.
Instantiating an object with a path name will cause the file to be opened, read, and parsed. Alternatively the path can be left unspecified, and a file can be parsed later with the :meth:`read` method.""" self._attrs = {} self._chars = {} self._kerning = {} self._index = {} self._comments = [] self._composites = {} if path is not None: self.read(path)
def read(self, path): """Opens, reads and parses a file.""" lines = readlines(path) for line in lines: if not line.strip(): continue m = identifierRE.match(line) if m is None: raise error("syntax error in AFM file: " + repr(line))
pos = m.regs[1][1] word = line[:pos] rest = line[pos:].strip() if word in self._keywords: continue if word == "C": self.parsechar(rest) elif word == "KPX": self.parsekernpair(rest) elif word == "CC": self.parsecomposite(rest) else: self.parseattr(word, rest)
def parsechar(self, rest): m = charRE.match(rest) if m is None: raise error("syntax error in AFM file: " + repr(rest)) things = [] for fr, to in m.regs[1:]: things.append(rest[fr:to]) charname = things[2] del things[2] charnum, width, l, b, r, t = (int(thing) for thing in things) self._chars[charname] = charnum, width, (l, b, r, t)
def parsekernpair(self, rest): m = kernRE.match(rest) if m is None: raise error("syntax error in AFM file: " + repr(rest)) things = [] for fr, to in m.regs[1:]: things.append(rest[fr:to]) leftchar, rightchar, value = things value = int(value) self._kerning[(leftchar, rightchar)] = value
def parseattr(self, word, rest): if word == "FontBBox": l, b, r, t = [int(thing) for thing in rest.split()] self._attrs[word] = l, b, r, t elif word == "Comment": self._comments.append(rest) else: try: value = int(rest) except (ValueError, OverflowError): self._attrs[word] = rest else: self._attrs[word] = value
def parsecomposite(self, rest): m = compositeRE.match(rest) if m is None: raise error("syntax error in AFM file: " + repr(rest)) charname = m.group(1) ncomponents = int(m.group(2)) rest = rest[m.regs[0][1] :] components = [] while True: m = componentRE.match(rest) if m is None: raise error("syntax error in AFM file: " + repr(rest)) basechar = m.group(1) xoffset = int(m.group(2)) yoffset = int(m.group(3)) components.append((basechar, xoffset, yoffset)) rest = rest[m.regs[0][1] :] if not rest: break assert len(components) == ncomponents self._composites[charname] = components
def write(self, path, sep="\r"): """Writes out an AFM font to the given path.""" import time
lines = [ "StartFontMetrics 2.0", "Comment Generated by afmLib; at %s" % (time.strftime("%m/%d/%Y %H:%M:%S", time.localtime(time.time()))), ]
# write comments, assuming (possibly wrongly!) they should # all appear at the top for comment in self._comments: lines.append("Comment " + comment)
# write attributes, first the ones we know about, in # a preferred order attrs = self._attrs for attr in preferredAttributeOrder: if attr in attrs: value = attrs[attr] if attr == "FontBBox": value = "%s %s %s %s" % value lines.append(attr + " " + str(value)) # then write the attributes we don't know about, # in alphabetical order items = sorted(attrs.items()) for attr, value in items: if attr in preferredAttributeOrder: continue lines.append(attr + " " + str(value))
# write char metrics lines.append("StartCharMetrics " + repr(len(self._chars))) items = [ (charnum, (charname, width, box)) for charname, (charnum, width, box) in self._chars.items() ]
def myKey(a): """Custom key function to make sure unencoded chars (-1) end up at the end of the list after sorting.""" if a[0] == -1: a = (0xFFFF,) + a[1:] # 0xffff is an arbitrary large number return a
items.sort(key=myKey)
for charnum, (charname, width, (l, b, r, t)) in items: lines.append( "C %d ; WX %d ; N %s ; B %d %d %d %d ;" % (charnum, width, charname, l, b, r, t) ) lines.append("EndCharMetrics")
# write kerning info lines.append("StartKernData") lines.append("StartKernPairs " + repr(len(self._kerning))) items = sorted(self._kerning.items()) for (leftchar, rightchar), value in items: lines.append("KPX %s %s %d" % (leftchar, rightchar, value)) lines.append("EndKernPairs") lines.append("EndKernData")
if self._composites: composites = sorted(self._composites.items()) lines.append("StartComposites %s" % len(self._composites)) for charname, components in composites: line = "CC %s %s ;" % (charname, len(components)) for basechar, xoffset, yoffset in components: line = line + " PCC %s %s %s ;" % (basechar, xoffset, yoffset) lines.append(line) lines.append("EndComposites")
lines.append("EndFontMetrics")
writelines(path, lines, sep)
def has_kernpair(self, pair): """Returns `True` if the given glyph pair (specified as a tuple) exists in the kerning dictionary.""" return pair in self._kerning
def kernpairs(self): """Returns a list of all kern pairs in the kerning dictionary.""" return list(self._kerning.keys())
def has_char(self, char): """Returns `True` if the given glyph exists in the font.""" return char in self._chars
def chars(self): """Returns a list of all glyph names in the font.""" return list(self._chars.keys())
def comments(self): """Returns all comments from the file.""" return self._comments
def addComment(self, comment): """Adds a new comment to the file.""" self._comments.append(comment)
def addComposite(self, glyphName, components): """Specifies that the glyph `glyphName` is made up of the given components. The components list should be of the following form::
[ (glyphname, xOffset, yOffset), ... ]
""" self._composites[glyphName] = components
def __getattr__(self, attr): if attr in self._attrs: return self._attrs[attr] else: raise AttributeError(attr)
def __setattr__(self, attr, value): # all attrs *not* starting with "_" are consider to be AFM keywords if attr[:1] == "_": self.__dict__[attr] = value else: self._attrs[attr] = value
def __delattr__(self, attr): # all attrs *not* starting with "_" are consider to be AFM keywords if attr[:1] == "_": try: del self.__dict__[attr] except KeyError: raise AttributeError(attr) else: try: del self._attrs[attr] except KeyError: raise AttributeError(attr)
def __getitem__(self, key): if isinstance(key, tuple): # key is a tuple, return the kernpair return self._kerning[key] else: # return the metrics instead return self._chars[key]
def __setitem__(self, key, value): if isinstance(key, tuple): # key is a tuple, set kernpair self._kerning[key] = value else: # set char metrics self._chars[key] = value
def __delitem__(self, key): if isinstance(key, tuple): # key is a tuple, del kernpair del self._kerning[key] else: # del char metrics del self._chars[key]
def __repr__(self): if hasattr(self, "FullName"): return "<AFM object for %s>" % self.FullName else: return "<AFM object at %x>" % id(self)
def readlines(path): with open(path, "r", encoding="ascii") as f: data = f.read() return data.splitlines()
def writelines(path, lines, sep="\r"): with open(path, "w", encoding="ascii", newline=sep) as f: f.write("\n".join(lines) + "\n")
if __name__ == "__main__": import EasyDialogs
path = EasyDialogs.AskFileForOpen() if path: afm = AFM(path) char = "A" if afm.has_char(char): print(afm[char]) # print charnum, width and boundingbox pair = ("A", "V") if afm.has_kernpair(pair): print(afm[pair]) # print kerning value for pair print(afm.Version) # various other afm entries have become attributes print(afm.Weight) # afm.comments() returns a list of all Comment lines found in the AFM print(afm.comments()) # print afm.chars() # print afm.kernpairs() print(afm) afm.write(path + ".muck")123456789101112131415161718192021222324252627282930from __future__ import annotationsfrom typing import TYPE_CHECKING, Iterable, Optional, TypeVar, Unionfrom collections.abc import Callable, Sequencefrom fontTools.misc.filesystem._base import FSfrom os import PathLikefrom xml.etree.ElementTree import Element as ElementTreeElement
if TYPE_CHECKING: from fontTools.ufoLib import UFOFormatVersion from fontTools.ufoLib.glifLib import GLIFFormatVersion from lxml.etree import _Element as LxmlElement
T = TypeVar("T") # Generic typeK = TypeVar("K") # Generic dict key typeV = TypeVar("V") # Generic dict value type
GlyphNameToFileNameFunc = Optional[Callable[[str, set[str]], str]]ElementType = Union[ElementTreeElement, "LxmlElement"]FormatVersion = Union[int, tuple[int, int]]FormatVersions = Optional[Iterable[FormatVersion]]GLIFFormatVersionInput = Optional[Union[int, tuple[int, int], "GLIFFormatVersion"]]UFOFormatVersionInput = Optional[Union[int, tuple[int, int], "UFOFormatVersion"]]IntFloat = Union[int, float]KerningPair = tuple[str, str]KerningDict = dict[KerningPair, IntFloat]KerningGroups = dict[str, Sequence[str]]KerningNested = dict[str, dict[str, IntFloat]]PathStr = Union[str, PathLike[str]]PathOrFS = Union[PathStr, FS]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664"""colorLib.builder: Build COLR/CPAL tables from scratch
"""
import collectionsimport copyimport enumfrom functools import partialfrom math import ceil, logfrom typing import ( Any, Dict, Generator, Iterable, List, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union,)from fontTools.misc.arrayTools import intRectfrom fontTools.misc.fixedTools import fixedToFloatfrom fontTools.misc.treeTools import build_n_ary_treefrom fontTools.ttLib.tables import C_O_L_R_from fontTools.ttLib.tables import C_P_A_L_from fontTools.ttLib.tables import _n_a_m_efrom fontTools.ttLib.tables import otTables as otfrom fontTools.ttLib.tables.otTables import ExtendMode, CompositeModefrom .errors import ColorLibErrorfrom .geometry import round_start_circle_stable_containmentfrom .table_builder import BuildCallback, TableBuilder
# TODO move type aliases to colorLib.types?T = TypeVar("T")_Kwargs = Mapping[str, Any]_PaintInput = Union[int, _Kwargs, ot.Paint, Tuple[str, "_PaintInput"]]_PaintInputList = Sequence[_PaintInput]_ColorGlyphsDict = Dict[str, Union[_PaintInputList, _PaintInput]]_ColorGlyphsV0Dict = Dict[str, Sequence[Tuple[str, int]]]_ClipBoxInput = Union[ Tuple[int, int, int, int, int], # format 1, variable Tuple[int, int, int, int], # format 0, non-variable ot.ClipBox,]
MAX_PAINT_COLR_LAYER_COUNT = 255_DEFAULT_ALPHA = 1.0_MAX_REUSE_LEN = 32
def _beforeBuildPaintRadialGradient(paint, source): x0 = source["x0"] y0 = source["y0"] r0 = source["r0"] x1 = source["x1"] y1 = source["y1"] r1 = source["r1"]
# TODO apparently no builder_test confirms this works (?)
# avoid abrupt change after rounding when c0 is near c1's perimeter c = round_start_circle_stable_containment((x0, y0), r0, (x1, y1), r1) x0, y0 = c.centre r0 = c.radius
# update source to ensure paint is built with corrected values source["x0"] = x0 source["y0"] = y0 source["r0"] = r0 source["x1"] = x1 source["y1"] = y1 source["r1"] = r1
return paint, source
def _defaultColorStop(): colorStop = ot.ColorStop() colorStop.Alpha = _DEFAULT_ALPHA return colorStop
def _defaultVarColorStop(): colorStop = ot.VarColorStop() colorStop.Alpha = _DEFAULT_ALPHA return colorStop
def _defaultColorLine(): colorLine = ot.ColorLine() colorLine.Extend = ExtendMode.PAD return colorLine
def _defaultVarColorLine(): colorLine = ot.VarColorLine() colorLine.Extend = ExtendMode.PAD return colorLine
def _defaultPaintSolid(): paint = ot.Paint() paint.Alpha = _DEFAULT_ALPHA return paint
def _buildPaintCallbacks(): return { ( BuildCallback.BEFORE_BUILD, ot.Paint, ot.PaintFormat.PaintRadialGradient, ): _beforeBuildPaintRadialGradient, ( BuildCallback.BEFORE_BUILD, ot.Paint, ot.PaintFormat.PaintVarRadialGradient, ): _beforeBuildPaintRadialGradient, (BuildCallback.CREATE_DEFAULT, ot.ColorStop): _defaultColorStop, (BuildCallback.CREATE_DEFAULT, ot.VarColorStop): _defaultVarColorStop, (BuildCallback.CREATE_DEFAULT, ot.ColorLine): _defaultColorLine, (BuildCallback.CREATE_DEFAULT, ot.VarColorLine): _defaultVarColorLine, ( BuildCallback.CREATE_DEFAULT, ot.Paint, ot.PaintFormat.PaintSolid, ): _defaultPaintSolid, ( BuildCallback.CREATE_DEFAULT, ot.Paint, ot.PaintFormat.PaintVarSolid, ): _defaultPaintSolid, }
def populateCOLRv0( table: ot.COLR, colorGlyphsV0: _ColorGlyphsV0Dict, glyphMap: Optional[Mapping[str, int]] = None,): """Build v0 color layers and add to existing COLR table.
Args: table: a raw ``otTables.COLR()`` object (not ttLib's ``table_C_O_L_R_``). colorGlyphsV0: map of base glyph names to lists of (layer glyph names, color palette index) tuples. Can be empty. glyphMap: a map from glyph names to glyph indices, as returned from ``TTFont.getReverseGlyphMap()``, to optionally sort base records by GID. """ if glyphMap is not None: colorGlyphItems = sorted( colorGlyphsV0.items(), key=lambda item: glyphMap[item[0]] ) else: colorGlyphItems = colorGlyphsV0.items() baseGlyphRecords = [] layerRecords = [] for baseGlyph, layers in colorGlyphItems: baseRec = ot.BaseGlyphRecord() baseRec.BaseGlyph = baseGlyph baseRec.FirstLayerIndex = len(layerRecords) baseRec.NumLayers = len(layers) baseGlyphRecords.append(baseRec)
for layerGlyph, paletteIndex in layers: layerRec = ot.LayerRecord() layerRec.LayerGlyph = layerGlyph layerRec.PaletteIndex = paletteIndex layerRecords.append(layerRec)
table.BaseGlyphRecordArray = table.LayerRecordArray = None if baseGlyphRecords: table.BaseGlyphRecordArray = ot.BaseGlyphRecordArray() table.BaseGlyphRecordArray.BaseGlyphRecord = baseGlyphRecords if layerRecords: table.LayerRecordArray = ot.LayerRecordArray() table.LayerRecordArray.LayerRecord = layerRecords table.BaseGlyphRecordCount = len(baseGlyphRecords) table.LayerRecordCount = len(layerRecords)
def buildCOLR( colorGlyphs: _ColorGlyphsDict, version: Optional[int] = None, *, glyphMap: Optional[Mapping[str, int]] = None, varStore: Optional[ot.VarStore] = None, varIndexMap: Optional[ot.DeltaSetIndexMap] = None, clipBoxes: Optional[Dict[str, _ClipBoxInput]] = None, allowLayerReuse: bool = True,) -> C_O_L_R_.table_C_O_L_R_: """Build COLR table from color layers mapping.
Args:
colorGlyphs: map of base glyph name to, either list of (layer glyph name, color palette index) tuples for COLRv0; or a single ``Paint`` (dict) or list of ``Paint`` for COLRv1. version: the version of COLR table. If None, the version is determined by the presence of COLRv1 paints or variation data (varStore), which require version 1; otherwise, if all base glyphs use only simple color layers, version 0 is used. glyphMap: a map from glyph names to glyph indices, as returned from TTFont.getReverseGlyphMap(), to optionally sort base records by GID. varStore: Optional ItemVarationStore for deltas associated with v1 layer. varIndexMap: Optional DeltaSetIndexMap for deltas associated with v1 layer. clipBoxes: Optional map of base glyph name to clip box 4- or 5-tuples: (xMin, yMin, xMax, yMax) or (xMin, yMin, xMax, yMax, varIndexBase).
Returns: A new COLR table. """ self = C_O_L_R_.table_C_O_L_R_()
if varStore is not None and version == 0: raise ValueError("Can't add VarStore to COLRv0")
if version in (None, 0) and not varStore: # split color glyphs into v0 and v1 and encode separately colorGlyphsV0, colorGlyphsV1 = _split_color_glyphs_by_version(colorGlyphs) if version == 0 and colorGlyphsV1: raise ValueError("Can't encode COLRv1 glyphs in COLRv0") else: # unless explicitly requested for v1 or have variations, in which case # we encode all color glyph as v1 colorGlyphsV0, colorGlyphsV1 = {}, colorGlyphs
colr = ot.COLR()
populateCOLRv0(colr, colorGlyphsV0, glyphMap)
colr.LayerList, colr.BaseGlyphList = buildColrV1( colorGlyphsV1, glyphMap, allowLayerReuse=allowLayerReuse, )
if version is None: version = 1 if (varStore or colorGlyphsV1) else 0 elif version not in (0, 1): raise NotImplementedError(version) self.version = colr.Version = version
if version == 0: self.ColorLayers = self._decompileColorLayersV0(colr) else: colr.ClipList = buildClipList(clipBoxes) if clipBoxes else None colr.VarIndexMap = varIndexMap colr.VarStore = varStore self.table = colr
return self
def buildClipList(clipBoxes: Dict[str, _ClipBoxInput]) -> ot.ClipList: clipList = ot.ClipList() clipList.Format = 1 clipList.clips = {name: buildClipBox(box) for name, box in clipBoxes.items()} return clipList
def buildClipBox(clipBox: _ClipBoxInput) -> ot.ClipBox: if isinstance(clipBox, ot.ClipBox): return clipBox n = len(clipBox) clip = ot.ClipBox() if n not in (4, 5): raise ValueError(f"Invalid ClipBox: expected 4 or 5 values, found {n}") clip.xMin, clip.yMin, clip.xMax, clip.yMax = intRect(clipBox[:4]) clip.Format = int(n == 5) + 1 if n == 5: clip.VarIndexBase = int(clipBox[4]) return clip
class ColorPaletteType(enum.IntFlag): USABLE_WITH_LIGHT_BACKGROUND = 0x0001 USABLE_WITH_DARK_BACKGROUND = 0x0002
@classmethod def _missing_(cls, value): # enforce reserved bits if isinstance(value, int) and (value < 0 or value & 0xFFFC != 0): raise ValueError(f"{value} is not a valid {cls.__name__}") return super()._missing_(value)
# None, 'abc' or {'en': 'abc', 'de': 'xyz'}_OptionalLocalizedString = Union[None, str, Dict[str, str]]
def buildPaletteLabels( labels: Iterable[_OptionalLocalizedString], nameTable: _n_a_m_e.table__n_a_m_e) -> List[Optional[int]]: return [ ( nameTable.addMultilingualName(l, mac=False) if isinstance(l, dict) else ( C_P_A_L_.table_C_P_A_L_.NO_NAME_ID if l is None else nameTable.addMultilingualName({"en": l}, mac=False) ) ) for l in labels ]
def buildCPAL( palettes: Sequence[Sequence[Tuple[float, float, float, float]]], paletteTypes: Optional[Sequence[ColorPaletteType]] = None, paletteLabels: Optional[Sequence[_OptionalLocalizedString]] = None, paletteEntryLabels: Optional[Sequence[_OptionalLocalizedString]] = None, nameTable: Optional[_n_a_m_e.table__n_a_m_e] = None,) -> C_P_A_L_.table_C_P_A_L_: """Build CPAL table from list of color palettes.
Args: palettes: list of lists of colors encoded as tuples of (R, G, B, A) floats in the range [0..1]. paletteTypes: optional list of ColorPaletteType, one for each palette. paletteLabels: optional list of palette labels. Each lable can be either: None (no label), a string (for for default English labels), or a localized string (as a dict keyed with BCP47 language codes). paletteEntryLabels: optional list of palette entry labels, one for each palette entry (see paletteLabels). nameTable: optional name table where to store palette and palette entry labels. Required if either paletteLabels or paletteEntryLabels is set.
Return: A new CPAL v0 or v1 table, if custom palette types or labels are specified. """ if len({len(p) for p in palettes}) != 1: raise ColorLibError("color palettes have different lengths")
if (paletteLabels or paletteEntryLabels) and not nameTable: raise TypeError( "nameTable is required if palette or palette entries have labels" )
cpal = C_P_A_L_.table_C_P_A_L_() cpal.numPaletteEntries = len(palettes[0])
cpal.palettes = [] for i, palette in enumerate(palettes): colors = [] for j, color in enumerate(palette): if not isinstance(color, tuple) or len(color) != 4: raise ColorLibError( f"In palette[{i}][{j}]: expected (R, G, B, A) tuple, got {color!r}" ) if any(v > 1 or v < 0 for v in color): raise ColorLibError( f"palette[{i}][{j}] has invalid out-of-range [0..1] color: {color!r}" ) # input colors are RGBA, CPAL encodes them as BGRA red, green, blue, alpha = color colors.append( C_P_A_L_.Color(*(round(v * 255) for v in (blue, green, red, alpha))) ) cpal.palettes.append(colors)
if any(v is not None for v in (paletteTypes, paletteLabels, paletteEntryLabels)): cpal.version = 1
if paletteTypes is not None: if len(paletteTypes) != len(palettes): raise ColorLibError( f"Expected {len(palettes)} paletteTypes, got {len(paletteTypes)}" ) cpal.paletteTypes = [ColorPaletteType(t).value for t in paletteTypes] else: cpal.paletteTypes = [C_P_A_L_.table_C_P_A_L_.DEFAULT_PALETTE_TYPE] * len( palettes )
if paletteLabels is not None: if len(paletteLabels) != len(palettes): raise ColorLibError( f"Expected {len(palettes)} paletteLabels, got {len(paletteLabels)}" ) cpal.paletteLabels = buildPaletteLabels(paletteLabels, nameTable) else: cpal.paletteLabels = [C_P_A_L_.table_C_P_A_L_.NO_NAME_ID] * len(palettes)
if paletteEntryLabels is not None: if len(paletteEntryLabels) != cpal.numPaletteEntries: raise ColorLibError( f"Expected {cpal.numPaletteEntries} paletteEntryLabels, " f"got {len(paletteEntryLabels)}" ) cpal.paletteEntryLabels = buildPaletteLabels(paletteEntryLabels, nameTable) else: cpal.paletteEntryLabels = [ C_P_A_L_.table_C_P_A_L_.NO_NAME_ID ] * cpal.numPaletteEntries else: cpal.version = 0
return cpal
# COLR v1 tables# See draft proposal at: https://github.com/googlefonts/colr-gradients-spec
def _is_colrv0_layer(layer: Any) -> bool: # Consider as COLRv0 layer any sequence of length 2 (be it tuple or list) in which # the first element is a str (the layerGlyph) and the second element is an int # (CPAL paletteIndex). # https://github.com/googlefonts/ufo2ft/issues/426 try: layerGlyph, paletteIndex = layer except (TypeError, ValueError): return False else: return isinstance(layerGlyph, str) and isinstance(paletteIndex, int)
def _split_color_glyphs_by_version( colorGlyphs: _ColorGlyphsDict,) -> Tuple[_ColorGlyphsV0Dict, _ColorGlyphsDict]: colorGlyphsV0 = {} colorGlyphsV1 = {} for baseGlyph, layers in colorGlyphs.items(): if all(_is_colrv0_layer(l) for l in layers): colorGlyphsV0[baseGlyph] = layers else: colorGlyphsV1[baseGlyph] = layers
# sanity check assert set(colorGlyphs) == (set(colorGlyphsV0) | set(colorGlyphsV1))
return colorGlyphsV0, colorGlyphsV1
def _reuse_ranges(num_layers: int) -> Generator[Tuple[int, int], None, None]: # TODO feels like something itertools might have already for lbound in range(num_layers): # Reuse of very large #s of layers is relatively unlikely # +2: we want sequences of at least 2 # otData handles single-record duplication for ubound in range( lbound + 2, min(num_layers + 1, lbound + 2 + _MAX_REUSE_LEN) ): yield (lbound, ubound)
class LayerReuseCache: reusePool: Mapping[Tuple[Any, ...], int] tuples: Mapping[int, Tuple[Any, ...]] keepAlive: List[ot.Paint] # we need id to remain valid
def __init__(self): self.reusePool = {} self.tuples = {} self.keepAlive = []
def _paint_tuple(self, paint: ot.Paint): # start simple, who even cares about cyclic graphs or interesting field types def _tuple_safe(value): if isinstance(value, enum.Enum): return value elif hasattr(value, "__dict__"): return tuple( (k, _tuple_safe(v)) for k, v in sorted(value.__dict__.items()) ) elif isinstance(value, collections.abc.MutableSequence): return tuple(_tuple_safe(e) for e in value) return value
# Cache the tuples for individual Paint instead of the whole sequence # because the seq could be a transient slice result = self.tuples.get(id(paint), None) if result is None: result = _tuple_safe(paint) self.tuples[id(paint)] = result self.keepAlive.append(paint) return result
def _as_tuple(self, paints: Sequence[ot.Paint]) -> Tuple[Any, ...]: return tuple(self._paint_tuple(p) for p in paints)
def try_reuse(self, layers: List[ot.Paint]) -> List[ot.Paint]: found_reuse = True while found_reuse: found_reuse = False
ranges = sorted( _reuse_ranges(len(layers)), key=lambda t: (t[1] - t[0], t[1], t[0]), reverse=True, ) for lbound, ubound in ranges: reuse_lbound = self.reusePool.get( self._as_tuple(layers[lbound:ubound]), -1 ) if reuse_lbound == -1: continue new_slice = ot.Paint() new_slice.Format = int(ot.PaintFormat.PaintColrLayers) new_slice.NumLayers = ubound - lbound new_slice.FirstLayerIndex = reuse_lbound layers = layers[:lbound] + [new_slice] + layers[ubound:] found_reuse = True break return layers
def add(self, layers: List[ot.Paint], first_layer_index: int): for lbound, ubound in _reuse_ranges(len(layers)): self.reusePool[self._as_tuple(layers[lbound:ubound])] = ( lbound + first_layer_index )
class LayerListBuilder: layers: List[ot.Paint] cache: LayerReuseCache allowLayerReuse: bool
def __init__(self, *, allowLayerReuse=True): self.layers = [] if allowLayerReuse: self.cache = LayerReuseCache() else: self.cache = None
# We need to intercept construction of PaintColrLayers callbacks = _buildPaintCallbacks() callbacks[ ( BuildCallback.BEFORE_BUILD, ot.Paint, ot.PaintFormat.PaintColrLayers, ) ] = self._beforeBuildPaintColrLayers self.tableBuilder = TableBuilder(callbacks)
# COLR layers is unusual in that it modifies shared state # so we need a callback into an object def _beforeBuildPaintColrLayers(self, dest, source): # Sketchy gymnastics: a sequence input will have dropped it's layers # into NumLayers; get it back if isinstance(source.get("NumLayers", None), collections.abc.Sequence): layers = source["NumLayers"] else: layers = source["Layers"]
# Convert maps seqs or whatever into typed objects layers = [self.buildPaint(l) for l in layers]
# No reason to have a colr layers with just one entry if len(layers) == 1: return layers[0], {}
if self.cache is not None: # Look for reuse, with preference to longer sequences # This may make the layer list smaller layers = self.cache.try_reuse(layers)
# The layer list is now final; if it's too big we need to tree it is_tree = len(layers) > MAX_PAINT_COLR_LAYER_COUNT layers = build_n_ary_tree(layers, n=MAX_PAINT_COLR_LAYER_COUNT)
# We now have a tree of sequences with Paint leaves. # Convert the sequences into PaintColrLayers. def listToColrLayers(layer): if isinstance(layer, collections.abc.Sequence): return self.buildPaint( { "Format": ot.PaintFormat.PaintColrLayers, "Layers": [listToColrLayers(l) for l in layer], } ) return layer
layers = [listToColrLayers(l) for l in layers]
# No reason to have a colr layers with just one entry if len(layers) == 1: return layers[0], {}
paint = ot.Paint() paint.Format = int(ot.PaintFormat.PaintColrLayers) paint.NumLayers = len(layers) paint.FirstLayerIndex = len(self.layers) self.layers.extend(layers)
# Register our parts for reuse provided we aren't a tree # If we are a tree the leaves registered for reuse and that will suffice if self.cache is not None and not is_tree: self.cache.add(layers, paint.FirstLayerIndex)
# we've fully built dest; empty source prevents generalized build from kicking in return paint, {}
def buildPaint(self, paint: _PaintInput) -> ot.Paint: return self.tableBuilder.build(ot.Paint, paint)
def build(self) -> Optional[ot.LayerList]: if not self.layers: return None layers = ot.LayerList() layers.LayerCount = len(self.layers) layers.Paint = self.layers return layers
def buildBaseGlyphPaintRecord( baseGlyph: str, layerBuilder: LayerListBuilder, paint: _PaintInput) -> ot.BaseGlyphList: self = ot.BaseGlyphPaintRecord() self.BaseGlyph = baseGlyph self.Paint = layerBuilder.buildPaint(paint) return self
def _format_glyph_errors(errors: Mapping[str, Exception]) -> str: lines = [] for baseGlyph, error in sorted(errors.items()): lines.append(f" {baseGlyph} => {type(error).__name__}: {error}") return "\n".join(lines)
def buildColrV1( colorGlyphs: _ColorGlyphsDict, glyphMap: Optional[Mapping[str, int]] = None, *, allowLayerReuse: bool = True,) -> Tuple[Optional[ot.LayerList], ot.BaseGlyphList]: if glyphMap is not None: colorGlyphItems = sorted( colorGlyphs.items(), key=lambda item: glyphMap[item[0]] ) else: colorGlyphItems = colorGlyphs.items()
errors = {} baseGlyphs = [] layerBuilder = LayerListBuilder(allowLayerReuse=allowLayerReuse) for baseGlyph, paint in colorGlyphItems: try: baseGlyphs.append(buildBaseGlyphPaintRecord(baseGlyph, layerBuilder, paint))
except (ColorLibError, OverflowError, ValueError, TypeError) as e: errors[baseGlyph] = e
if errors: failed_glyphs = _format_glyph_errors(errors) exc = ColorLibError(f"Failed to build BaseGlyphList:\n{failed_glyphs}") exc.errors = errors raise exc from next(iter(errors.values()))
layers = layerBuilder.build() glyphs = ot.BaseGlyphList() glyphs.BaseGlyphCount = len(baseGlyphs) glyphs.BaseGlyphPaintRecord = baseGlyphs return (layers, glyphs)12class ColorLibError(Exception): pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143"""Helpers for manipulating 2D points and vectors in COLR table."""
from math import copysign, cos, hypot, isclose, pifrom fontTools.misc.roundTools import otRound
def _vector_between(origin, target): return (target[0] - origin[0], target[1] - origin[1])
def _round_point(pt): return (otRound(pt[0]), otRound(pt[1]))
def _unit_vector(vec): length = hypot(*vec) if length == 0: return None return (vec[0] / length, vec[1] / length)
_CIRCLE_INSIDE_TOLERANCE = 1e-4
# The unit vector's X and Y components are respectively# U = (cos(α), sin(α))# where α is the angle between the unit vector and the positive x axis._UNIT_VECTOR_THRESHOLD = cos(3 / 8 * pi) # == sin(1/8 * pi) == 0.38268343236508984
def _rounding_offset(direction): # Return 2-tuple of -/+ 1.0 or 0.0 approximately based on the direction vector. # We divide the unit circle in 8 equal slices oriented towards the cardinal # (N, E, S, W) and intermediate (NE, SE, SW, NW) directions. To each slice we # map one of the possible cases: -1, 0, +1 for either X and Y coordinate. # E.g. Return (+1.0, -1.0) if unit vector is oriented towards SE, or # (-1.0, 0.0) if it's pointing West, etc. uv = _unit_vector(direction) if not uv: return (0, 0)
result = [] for uv_component in uv: if -_UNIT_VECTOR_THRESHOLD <= uv_component < _UNIT_VECTOR_THRESHOLD: # unit vector component near 0: direction almost orthogonal to the # direction of the current axis, thus keep coordinate unchanged result.append(0) else: # nudge coord by +/- 1.0 in direction of unit vector result.append(copysign(1.0, uv_component)) return tuple(result)
class Circle: def __init__(self, centre, radius): self.centre = centre self.radius = radius
def __repr__(self): return f"Circle(centre={self.centre}, radius={self.radius})"
def round(self): return Circle(_round_point(self.centre), otRound(self.radius))
def inside(self, outer_circle, tolerance=_CIRCLE_INSIDE_TOLERANCE): dist = self.radius + hypot(*_vector_between(self.centre, outer_circle.centre)) return ( isclose(outer_circle.radius, dist, rel_tol=_CIRCLE_INSIDE_TOLERANCE) or outer_circle.radius > dist )
def concentric(self, other): return self.centre == other.centre
def move(self, dx, dy): self.centre = (self.centre[0] + dx, self.centre[1] + dy)
def round_start_circle_stable_containment(c0, r0, c1, r1): """Round start circle so that it stays inside/outside end circle after rounding.
The rounding of circle coordinates to integers may cause an abrupt change if the start circle c0 is so close to the end circle c1's perimiter that it ends up falling outside (or inside) as a result of the rounding. To keep the gradient unchanged, we nudge it in the right direction.
See: https://github.com/googlefonts/colr-gradients-spec/issues/204 https://github.com/googlefonts/picosvg/issues/158 """ start, end = Circle(c0, r0), Circle(c1, r1)
inside_before_round = start.inside(end)
round_start = start.round() round_end = end.round() inside_after_round = round_start.inside(round_end)
if inside_before_round == inside_after_round: return round_start elif inside_after_round: # start was outside before rounding: we need to push start away from end direction = _vector_between(round_end.centre, round_start.centre) radius_delta = +1.0 else: # start was inside before rounding: we need to push start towards end direction = _vector_between(round_start.centre, round_end.centre) radius_delta = -1.0 dx, dy = _rounding_offset(direction)
# At most 2 iterations ought to be enough to converge. Before the loop, we # know the start circle didn't keep containment after normal rounding; thus # we continue adjusting by -/+ 1.0 until containment is restored. # Normal rounding can at most move each coordinates -/+0.5; in the worst case # both the start and end circle's centres and radii will be rounded in opposite # directions, e.g. when they move along a 45 degree diagonal: # c0 = (1.5, 1.5) ===> (2.0, 2.0) # r0 = 0.5 ===> 1.0 # c1 = (0.499, 0.499) ===> (0.0, 0.0) # r1 = 2.499 ===> 2.0 # In this example, the relative distance between the circles, calculated # as r1 - (r0 + distance(c0, c1)) is initially 0.57437 (c0 is inside c1), and # -1.82842 after rounding (c0 is now outside c1). Nudging c0 by -1.0 on both # x and y axes moves it towards c1 by hypot(-1.0, -1.0) = 1.41421. Two of these # moves cover twice that distance, which is enough to restore containment. max_attempts = 2 for _ in range(max_attempts): if round_start.concentric(round_end): # can't move c0 towards c1 (they are the same), so we change the radius round_start.radius += radius_delta assert round_start.radius >= 0 else: round_start.move(dx, dy) if inside_before_round == round_start.inside(round_end): break else: # likely a bug raise AssertionError( f"Rounding circle {start} " f"{'inside' if inside_before_round else 'outside'} " f"{end} failed after {max_attempts} attempts!" )
return round_start123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""colorLib.table_builder: Generic helper for filling in BaseTable derivatives from tuples and maps and such.
"""
import collectionsimport enumfrom fontTools.ttLib.tables.otBase import ( BaseTable, FormatSwitchingBaseTable, UInt8FormatSwitchingBaseTable,)from fontTools.ttLib.tables.otConverters import ( ComputedInt, SimpleValue, Struct, Short, UInt8, UShort, IntValue, FloatValue, OptionalValue,)from fontTools.misc.roundTools import otRound
class BuildCallback(enum.Enum): """Keyed on (BEFORE_BUILD, class[, Format if available]). Receives (dest, source). Should return (dest, source), which can be new objects. """
BEFORE_BUILD = enum.auto()
"""Keyed on (AFTER_BUILD, class[, Format if available]). Receives (dest). Should return dest, which can be a new object. """ AFTER_BUILD = enum.auto()
"""Keyed on (CREATE_DEFAULT, class[, Format if available]). Receives no arguments. Should return a new instance of class. """ CREATE_DEFAULT = enum.auto()
def _assignable(convertersByName): return {k: v for k, v in convertersByName.items() if not isinstance(v, ComputedInt)}
def _isNonStrSequence(value): return isinstance(value, collections.abc.Sequence) and not isinstance(value, str)
def _split_format(cls, source): if _isNonStrSequence(source): assert len(source) > 0, f"{cls} needs at least format from {source}" fmt, remainder = source[0], source[1:] elif isinstance(source, collections.abc.Mapping): assert "Format" in source, f"{cls} needs at least Format from {source}" remainder = source.copy() fmt = remainder.pop("Format") else: raise ValueError(f"Not sure how to populate {cls} from {source}")
assert isinstance( fmt, collections.abc.Hashable ), f"{cls} Format is not hashable: {fmt!r}" assert fmt in cls.convertersByName, f"{cls} invalid Format: {fmt!r}"
return fmt, remainder
class TableBuilder: """ Helps to populate things derived from BaseTable from maps, tuples, etc.
A table of lifecycle callbacks may be provided to add logic beyond what is possible based on otData info for the target class. See BuildCallbacks. """
def __init__(self, callbackTable=None): if callbackTable is None: callbackTable = {} self._callbackTable = callbackTable
def _convert(self, dest, field, converter, value): enumClass = getattr(converter, "enumClass", None)
if enumClass: if isinstance(value, enumClass): pass elif isinstance(value, str): try: value = getattr(enumClass, value.upper()) except AttributeError: raise ValueError(f"{value} is not a valid {enumClass}") else: value = enumClass(value)
elif isinstance(converter, IntValue): value = otRound(value) elif isinstance(converter, FloatValue): value = float(value)
elif isinstance(converter, Struct): if converter.repeat: if _isNonStrSequence(value): value = [self.build(converter.tableClass, v) for v in value] else: value = [self.build(converter.tableClass, value)] setattr(dest, converter.repeat, len(value)) else: value = self.build(converter.tableClass, value) elif callable(converter): value = converter(value)
setattr(dest, field, value)
def build(self, cls, source): assert issubclass(cls, BaseTable)
if isinstance(source, cls): return source
callbackKey = (cls,) fmt = None if issubclass(cls, FormatSwitchingBaseTable): fmt, source = _split_format(cls, source) callbackKey = (cls, fmt)
dest = self._callbackTable.get( (BuildCallback.CREATE_DEFAULT,) + callbackKey, lambda: cls() )() assert isinstance(dest, cls)
convByName = _assignable(cls.convertersByName) skippedFields = set()
# For format switchers we need to resolve converters based on format if issubclass(cls, FormatSwitchingBaseTable): dest.Format = fmt convByName = _assignable(convByName[dest.Format]) skippedFields.add("Format")
# Convert sequence => mapping so before thunk only has to handle one format if _isNonStrSequence(source): # Sequence (typically list or tuple) assumed to match fields in declaration order assert len(source) <= len( convByName ), f"Sequence of {len(source)} too long for {cls}; expected <= {len(convByName)} values" source = dict(zip(convByName.keys(), source))
dest, source = self._callbackTable.get( (BuildCallback.BEFORE_BUILD,) + callbackKey, lambda d, s: (d, s) )(dest, source)
if isinstance(source, collections.abc.Mapping): for field, value in source.items(): if field in skippedFields: continue converter = convByName.get(field, None) if not converter: raise ValueError( f"Unrecognized field {field} for {cls}; expected one of {sorted(convByName.keys())}" ) self._convert(dest, field, converter, value) else: # let's try as a 1-tuple dest = self.build(cls, (source,))
for field, conv in convByName.items(): if not hasattr(dest, field) and isinstance(conv, OptionalValue): setattr(dest, field, conv.DEFAULT)
dest = self._callbackTable.get( (BuildCallback.AFTER_BUILD,) + callbackKey, lambda d: d )(dest)
return dest
class TableUnbuilder: def __init__(self, callbackTable=None): if callbackTable is None: callbackTable = {} self._callbackTable = callbackTable
def unbuild(self, table): assert isinstance(table, BaseTable)
source = {}
callbackKey = (type(table),) if isinstance(table, FormatSwitchingBaseTable): source["Format"] = int(table.Format) callbackKey += (table.Format,)
for converter in table.getConverters(): if isinstance(converter, ComputedInt): continue value = getattr(table, converter.name)
enumClass = getattr(converter, "enumClass", None) if enumClass: source[converter.name] = value.name.lower() elif isinstance(converter, Struct): if converter.repeat: source[converter.name] = [self.unbuild(v) for v in value] else: source[converter.name] = self.unbuild(value) elif isinstance(converter, SimpleValue): # "simple" values (e.g. int, float, str) need no further un-building source[converter.name] = value else: raise NotImplementedError( "Don't know how unbuild {value!r} with {converter!r}" )
source = self._callbackTable.get(callbackKey, lambda s: s)(source)
return source123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081from fontTools.ttLib.tables import otTables as otfrom .table_builder import TableUnbuilder
def unbuildColrV1(layerList, baseGlyphList): layers = [] if layerList: layers = layerList.Paint unbuilder = LayerListUnbuilder(layers) return { rec.BaseGlyph: unbuilder.unbuildPaint(rec.Paint) for rec in baseGlyphList.BaseGlyphPaintRecord }
def _flatten_layers(lst): for paint in lst: if paint["Format"] == ot.PaintFormat.PaintColrLayers: yield from _flatten_layers(paint["Layers"]) else: yield paint
class LayerListUnbuilder: def __init__(self, layers): self.layers = layers
callbacks = { ( ot.Paint, ot.PaintFormat.PaintColrLayers, ): self._unbuildPaintColrLayers, } self.tableUnbuilder = TableUnbuilder(callbacks)
def unbuildPaint(self, paint): assert isinstance(paint, ot.Paint) return self.tableUnbuilder.unbuild(paint)
def _unbuildPaintColrLayers(self, source): assert source["Format"] == ot.PaintFormat.PaintColrLayers
layers = list( _flatten_layers( [ self.unbuildPaint(childPaint) for childPaint in self.layers[ source["FirstLayerIndex"] : source["FirstLayerIndex"] + source["NumLayers"] ] ] ) )
if len(layers) == 1: return layers[0]
return {"Format": source["Format"], "Layers": layers}
if __name__ == "__main__": from pprint import pprint import sys from fontTools.ttLib import TTFont
try: fontfile = sys.argv[1] except IndexError: sys.exit("usage: fonttools colorLib.unbuilder FONTFILE")
font = TTFont(fontfile) colr = font["COLR"] if colr.version < 1: sys.exit(f"error: No COLR table version=1 found in {fontfile}")
colorGlyphs = unbuildColrV1( colr.table.LayerList, colr.table.BaseGlyphList, )
pprint(colorGlyphs)123456import sysfrom fontTools.designspaceLib import main
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475"""Allows building all the variable fonts of a DesignSpace version 5 bysplitting the document into interpolable sub-space, then into each VF."""
from __future__ import annotations
import itertoolsimport loggingimport mathfrom typing import Any, Callable, Dict, Iterator, List, Tuple, cast
from fontTools.designspaceLib import ( AxisDescriptor, AxisMappingDescriptor, DesignSpaceDocument, DiscreteAxisDescriptor, InstanceDescriptor, RuleDescriptor, SimpleLocationDict, SourceDescriptor, VariableFontDescriptor,)from fontTools.designspaceLib.statNames import StatNames, getStatNamesfrom fontTools.designspaceLib.types import ( ConditionSet, Range, Region, getVFUserRegion, locationInRegion, regionInRegion, userRegionToDesignRegion,)
LOGGER = logging.getLogger(__name__)
MakeInstanceFilenameCallable = Callable[ [DesignSpaceDocument, InstanceDescriptor, StatNames], str]
def defaultMakeInstanceFilename( doc: DesignSpaceDocument, instance: InstanceDescriptor, statNames: StatNames) -> str: """Default callable to synthesize an instance filename when makeNames=True, for instances that don't specify an instance name in the designspace. This part of the name generation can be overriden because it's not specified by the STAT table. """ familyName = instance.familyName or statNames.familyNames.get("en") styleName = instance.styleName or statNames.styleNames.get("en") return f"{familyName}-{styleName}.ttf"
def splitInterpolable( doc: DesignSpaceDocument, makeNames: bool = True, expandLocations: bool = True, makeInstanceFilename: MakeInstanceFilenameCallable = defaultMakeInstanceFilename,) -> Iterator[Tuple[SimpleLocationDict, DesignSpaceDocument]]: """Split the given DS5 into several interpolable sub-designspaces. There are as many interpolable sub-spaces as there are combinations of discrete axis values.
E.g. with axes: - italic (discrete) Upright or Italic - style (discrete) Sans or Serif - weight (continuous) 100 to 900
There are 4 sub-spaces in which the Weight axis should interpolate: (Upright, Sans), (Upright, Serif), (Italic, Sans) and (Italic, Serif).
The sub-designspaces still include the full axis definitions and STAT data, but the rules, sources, variable fonts, instances are trimmed down to only keep what falls within the interpolable sub-space.
Args: - ``makeNames``: Whether to compute the instance family and style names using the STAT data. - ``expandLocations``: Whether to turn all locations into "full" locations, including implicit default axis values where missing. - ``makeInstanceFilename``: Callable to synthesize an instance filename when makeNames=True, for instances that don't specify an instance name in the designspace. This part of the name generation can be overridden because it's not specified by the STAT table.
.. versionadded:: 5.0 """ discreteAxes = [] interpolableUserRegion: Region = {} for axis in doc.axes: if hasattr(axis, "values"): # Mypy doesn't support narrowing union types via hasattr() # TODO(Python 3.10): use TypeGuard # https://mypy.readthedocs.io/en/stable/type_narrowing.html axis = cast(DiscreteAxisDescriptor, axis) discreteAxes.append(axis) else: axis = cast(AxisDescriptor, axis) interpolableUserRegion[axis.name] = Range( axis.minimum, axis.maximum, axis.default, ) valueCombinations = itertools.product(*[axis.values for axis in discreteAxes]) for values in valueCombinations: discreteUserLocation = { discreteAxis.name: value for discreteAxis, value in zip(discreteAxes, values) } subDoc = _extractSubSpace( doc, {**interpolableUserRegion, **discreteUserLocation}, keepVFs=True, makeNames=makeNames, expandLocations=expandLocations, makeInstanceFilename=makeInstanceFilename, ) yield discreteUserLocation, subDoc
def splitVariableFonts( doc: DesignSpaceDocument, makeNames: bool = False, expandLocations: bool = False, makeInstanceFilename: MakeInstanceFilenameCallable = defaultMakeInstanceFilename,) -> Iterator[Tuple[str, DesignSpaceDocument]]: """Convert each variable font listed in this document into a standalone designspace. This can be used to compile all the variable fonts from a format 5 designspace using tools that can only deal with 1 VF at a time.
Args: - ``makeNames``: Whether to compute the instance family and style names using the STAT data. - ``expandLocations``: Whether to turn all locations into "full" locations, including implicit default axis values where missing. - ``makeInstanceFilename``: Callable to synthesize an instance filename when makeNames=True, for instances that don't specify an instance name in the designspace. This part of the name generation can be overridden because it's not specified by the STAT table.
.. versionadded:: 5.0 """ # Make one DesignspaceDoc v5 for each variable font for vf in doc.getVariableFonts(): vfUserRegion = getVFUserRegion(doc, vf) vfDoc = _extractSubSpace( doc, vfUserRegion, keepVFs=False, makeNames=makeNames, expandLocations=expandLocations, makeInstanceFilename=makeInstanceFilename, ) vfDoc.lib = {**vfDoc.lib, **vf.lib} yield vf.name, vfDoc
def convert5to4( doc: DesignSpaceDocument,) -> Dict[str, DesignSpaceDocument]: """Convert each variable font listed in this document into a standalone format 4 designspace. This can be used to compile all the variable fonts from a format 5 designspace using tools that only know about format 4.
.. versionadded:: 5.0 """ vfs = {} for _location, subDoc in splitInterpolable(doc): for vfName, vfDoc in splitVariableFonts(subDoc): vfDoc.formatVersion = "4.1" vfs[vfName] = vfDoc return vfs
def _extractSubSpace( doc: DesignSpaceDocument, userRegion: Region, *, keepVFs: bool, makeNames: bool, expandLocations: bool, makeInstanceFilename: MakeInstanceFilenameCallable,) -> DesignSpaceDocument: subDoc = DesignSpaceDocument() # Don't include STAT info # FIXME: (Jany) let's think about it. Not include = OK because the point of # the splitting is to build VFs and we'll use the STAT data of the full # document to generate the STAT of the VFs, so "no need" to have STAT data # in sub-docs. Counterpoint: what if someone wants to split this DS for # other purposes? Maybe for that it would be useful to also subset the STAT # data? # subDoc.elidedFallbackName = doc.elidedFallbackName
def maybeExpandDesignLocation(object): if expandLocations: return object.getFullDesignLocation(doc) else: return object.designLocation
for axis in doc.axes: range = userRegion[axis.name] if isinstance(range, Range) and hasattr(axis, "minimum"): # Mypy doesn't support narrowing union types via hasattr() # TODO(Python 3.10): use TypeGuard # https://mypy.readthedocs.io/en/stable/type_narrowing.html axis = cast(AxisDescriptor, axis) subDoc.addAxis( AxisDescriptor( # Same info tag=axis.tag, name=axis.name, labelNames=axis.labelNames, hidden=axis.hidden, # Subset range minimum=max(range.minimum, axis.minimum), default=range.default or axis.default, maximum=min(range.maximum, axis.maximum), map=[ (user, design) for user, design in axis.map if range.minimum <= user <= range.maximum ], # Don't include STAT info axisOrdering=None, axisLabels=None, ) )
subDoc.axisMappings = mappings = [] subDocAxes = {axis.name for axis in subDoc.axes} for mapping in doc.axisMappings: if not all(axis in subDocAxes for axis in mapping.inputLocation.keys()): continue if not all(axis in subDocAxes for axis in mapping.outputLocation.keys()): LOGGER.error( "In axis mapping from input %s, some output axes are not in the variable-font: %s", mapping.inputLocation, mapping.outputLocation, ) continue
mappingAxes = set() mappingAxes.update(mapping.inputLocation.keys()) mappingAxes.update(mapping.outputLocation.keys()) for axis in doc.axes: if axis.name not in mappingAxes: continue range = userRegion[axis.name] if ( range.minimum != axis.minimum or (range.default is not None and range.default != axis.default) or range.maximum != axis.maximum ): LOGGER.error( "Limiting axis ranges used in <mapping> elements not supported: %s", axis.name, ) continue
mappings.append( AxisMappingDescriptor( inputLocation=mapping.inputLocation, outputLocation=mapping.outputLocation, ) )
# Don't include STAT info # subDoc.locationLabels = doc.locationLabels
# Rules: subset them based on conditions designRegion = userRegionToDesignRegion(doc, userRegion) subDoc.rules = _subsetRulesBasedOnConditions(doc.rules, designRegion) subDoc.rulesProcessingLast = doc.rulesProcessingLast
# Sources: keep only the ones that fall within the kept axis ranges for source in doc.sources: if not locationInRegion(doc.map_backward(source.designLocation), userRegion): continue
subDoc.addSource( SourceDescriptor( filename=source.filename, path=source.path, font=source.font, name=source.name, designLocation=_filterLocation( userRegion, maybeExpandDesignLocation(source) ), layerName=source.layerName, familyName=source.familyName, styleName=source.styleName, muteKerning=source.muteKerning, muteInfo=source.muteInfo, mutedGlyphNames=source.mutedGlyphNames, ) )
# Copy family name translations from the old default source to the new default vfDefault = subDoc.findDefault() oldDefault = doc.findDefault() if vfDefault is not None and oldDefault is not None: vfDefault.localisedFamilyName = oldDefault.localisedFamilyName
# Variable fonts: keep only the ones that fall within the kept axis ranges if keepVFs: # Note: call getVariableFont() to make the implicit VFs explicit for vf in doc.getVariableFonts(): vfUserRegion = getVFUserRegion(doc, vf) if regionInRegion(vfUserRegion, userRegion): subDoc.addVariableFont( VariableFontDescriptor( name=vf.name, filename=vf.filename, axisSubsets=[ axisSubset for axisSubset in vf.axisSubsets if isinstance(userRegion[axisSubset.name], Range) ], lib=vf.lib, ) )
# Instances: same as Sources + compute missing names for instance in doc.instances: if not locationInRegion(instance.getFullUserLocation(doc), userRegion): continue
if makeNames: statNames = getStatNames(doc, instance.getFullUserLocation(doc)) familyName = instance.familyName or statNames.familyNames.get("en") styleName = instance.styleName or statNames.styleNames.get("en") subDoc.addInstance( InstanceDescriptor( filename=instance.filename or makeInstanceFilename(doc, instance, statNames), path=instance.path, font=instance.font, name=instance.name or f"{familyName} {styleName}", userLocation={} if expandLocations else instance.userLocation, designLocation=_filterLocation( userRegion, maybeExpandDesignLocation(instance) ), familyName=familyName, styleName=styleName, postScriptFontName=instance.postScriptFontName or statNames.postScriptFontName, styleMapFamilyName=instance.styleMapFamilyName or statNames.styleMapFamilyNames.get("en"), styleMapStyleName=instance.styleMapStyleName or statNames.styleMapStyleName, localisedFamilyName=instance.localisedFamilyName or statNames.familyNames, localisedStyleName=instance.localisedStyleName or statNames.styleNames, localisedStyleMapFamilyName=instance.localisedStyleMapFamilyName or statNames.styleMapFamilyNames, localisedStyleMapStyleName=instance.localisedStyleMapStyleName or {}, lib=instance.lib, ) ) else: subDoc.addInstance( InstanceDescriptor( filename=instance.filename, path=instance.path, font=instance.font, name=instance.name, userLocation={} if expandLocations else instance.userLocation, designLocation=_filterLocation( userRegion, maybeExpandDesignLocation(instance) ), familyName=instance.familyName, styleName=instance.styleName, postScriptFontName=instance.postScriptFontName, styleMapFamilyName=instance.styleMapFamilyName, styleMapStyleName=instance.styleMapStyleName, localisedFamilyName=instance.localisedFamilyName, localisedStyleName=instance.localisedStyleName, localisedStyleMapFamilyName=instance.localisedStyleMapFamilyName, localisedStyleMapStyleName=instance.localisedStyleMapStyleName, lib=instance.lib, ) )
subDoc.lib = doc.lib
return subDoc
def _conditionSetFrom(conditionSet: List[Dict[str, Any]]) -> ConditionSet: c: Dict[str, Range] = {} for condition in conditionSet: minimum, maximum = condition.get("minimum"), condition.get("maximum") c[condition["name"]] = Range( minimum if minimum is not None else -math.inf, maximum if maximum is not None else math.inf, ) return c
def _subsetRulesBasedOnConditions( rules: List[RuleDescriptor], designRegion: Region) -> List[RuleDescriptor]: # What rules to keep: # - Keep the rule if any conditionset is relevant. # - A conditionset is relevant if all conditions are relevant or it is empty. # - A condition is relevant if # - axis is point (C-AP), # - and point in condition's range (C-AP-in) # (in this case remove the condition because it's always true) # - else (C-AP-out) whole conditionset can be discarded (condition false # => conditionset false) # - axis is range (C-AR), # - (C-AR-all) and axis range fully contained in condition range: we can # scrap the condition because it's always true # - (C-AR-inter) and intersection(axis range, condition range) not empty: # keep the condition with the smaller range (= intersection) # - (C-AR-none) else, whole conditionset can be discarded newRules: List[RuleDescriptor] = [] for rule in rules: newRule: RuleDescriptor = RuleDescriptor( name=rule.name, conditionSets=[], subs=rule.subs ) for conditionset in rule.conditionSets: cs = _conditionSetFrom(conditionset) newConditionset: List[Dict[str, Any]] = [] discardConditionset = False for selectionName, selectionValue in designRegion.items(): # TODO: Ensure that all(key in conditionset for key in region.keys())? if selectionName not in cs: # raise Exception("Selection has different axes than the rules") continue if isinstance(selectionValue, (float, int)): # is point # Case C-AP-in if selectionValue in cs[selectionName]: pass # always matches, conditionset can stay empty for this one. # Case C-AP-out else: discardConditionset = True else: # is range # Case C-AR-all if selectionValue in cs[selectionName]: pass # always matches, conditionset can stay empty for this one. else: intersection = cs[selectionName].intersection(selectionValue) # Case C-AR-inter if intersection is not None: newConditionset.append( { "name": selectionName, "minimum": intersection.minimum, "maximum": intersection.maximum, } ) # Case C-AR-none else: discardConditionset = True if not discardConditionset: newRule.conditionSets.append(newConditionset) if newRule.conditionSets: newRules.append(newRule)
return newRules
def _filterLocation( userRegion: Region, location: Dict[str, float],) -> Dict[str, float]: return { name: value for name, value in location.items() if name in userRegion and isinstance(userRegion[name], Range) }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260"""Compute name information for a given location in user-space coordinatesusing STAT data. This can be used to fill-in automatically the names of aninstance:
.. code:: python
instance = doc.instances[0] names = getStatNames(doc, instance.getFullUserLocation(doc)) print(names.styleNames)"""
from __future__ import annotations
from dataclasses import dataclassfrom typing import Dict, Literal, Optional, Tuple, Unionimport logging
from fontTools.designspaceLib import ( AxisDescriptor, AxisLabelDescriptor, DesignSpaceDocument, DiscreteAxisDescriptor, SimpleLocationDict, SourceDescriptor,)
LOGGER = logging.getLogger(__name__)
RibbiStyleName = Union[ Literal["regular"], Literal["bold"], Literal["italic"], Literal["bold italic"],]
BOLD_ITALIC_TO_RIBBI_STYLE = { (False, False): "regular", (False, True): "italic", (True, False): "bold", (True, True): "bold italic",}
@dataclassclass StatNames: """Name data generated from the STAT table information."""
familyNames: Dict[str, str] styleNames: Dict[str, str] postScriptFontName: Optional[str] styleMapFamilyNames: Dict[str, str] styleMapStyleName: Optional[RibbiStyleName]
def getStatNames( doc: DesignSpaceDocument, userLocation: SimpleLocationDict) -> StatNames: """Compute the family, style, PostScript names of the given ``userLocation`` using the document's STAT information.
Also computes localizations.
If not enough STAT data is available for a given name, either its dict of localized names will be empty (family and style names), or the name will be None (PostScript name).
Note: this method does not consider info attached to the instance, like family name. The user needs to override all names on an instance that STAT information would compute differently than desired.
.. versionadded:: 5.0 """ familyNames: Dict[str, str] = {} defaultSource: Optional[SourceDescriptor] = doc.findDefault() if defaultSource is None: LOGGER.warning("Cannot determine default source to look up family name.") elif defaultSource.familyName is None: LOGGER.warning( "Cannot look up family name, assign the 'familyname' attribute to the default source." ) else: familyNames = { "en": defaultSource.familyName, **defaultSource.localisedFamilyName, }
styleNames: Dict[str, str] = {} # If a free-standing label matches the location, use it for name generation. label = doc.labelForUserLocation(userLocation) if label is not None: styleNames = {"en": label.name, **label.labelNames} # Otherwise, scour the axis labels for matches. else: # Gather all languages in which at least one translation is provided # Then build names for all these languages, but fallback to English # whenever a translation is missing. labels = _getAxisLabelsForUserLocation(doc.axes, userLocation) if labels: languages = set( language for label in labels for language in label.labelNames ) languages.add("en") for language in languages: styleName = " ".join( label.labelNames.get(language, label.defaultName) for label in labels if not label.elidable ) if not styleName and doc.elidedFallbackName is not None: styleName = doc.elidedFallbackName styleNames[language] = styleName
if "en" not in familyNames or "en" not in styleNames: # Not enough information to compute PS names of styleMap names return StatNames( familyNames=familyNames, styleNames=styleNames, postScriptFontName=None, styleMapFamilyNames={}, styleMapStyleName=None, )
postScriptFontName = f"{familyNames['en']}-{styleNames['en']}".replace(" ", "")
styleMapStyleName, regularUserLocation = _getRibbiStyle(doc, userLocation)
styleNamesForStyleMap = styleNames if regularUserLocation != userLocation: regularStatNames = getStatNames(doc, regularUserLocation) styleNamesForStyleMap = regularStatNames.styleNames
styleMapFamilyNames = {} for language in set(familyNames).union(styleNames.keys()): familyName = familyNames.get(language, familyNames["en"]) styleName = styleNamesForStyleMap.get(language, styleNamesForStyleMap["en"]) styleMapFamilyNames[language] = (familyName + " " + styleName).strip()
return StatNames( familyNames=familyNames, styleNames=styleNames, postScriptFontName=postScriptFontName, styleMapFamilyNames=styleMapFamilyNames, styleMapStyleName=styleMapStyleName, )
def _getSortedAxisLabels( axes: list[Union[AxisDescriptor, DiscreteAxisDescriptor]],) -> Dict[str, list[AxisLabelDescriptor]]: """Returns axis labels sorted by their ordering, with unordered ones appended as they are listed."""
# First, get the axis labels with explicit ordering... sortedAxes = sorted( (axis for axis in axes if axis.axisOrdering is not None), key=lambda a: a.axisOrdering, ) sortedLabels: Dict[str, list[AxisLabelDescriptor]] = { axis.name: axis.axisLabels for axis in sortedAxes }
# ... then append the others in the order they appear. # NOTE: This relies on Python 3.7+ dict's preserved insertion order. for axis in axes: if axis.axisOrdering is None: sortedLabels[axis.name] = axis.axisLabels
return sortedLabels
def _getAxisLabelsForUserLocation( axes: list[Union[AxisDescriptor, DiscreteAxisDescriptor]], userLocation: SimpleLocationDict,) -> list[AxisLabelDescriptor]: labels: list[AxisLabelDescriptor] = []
allAxisLabels = _getSortedAxisLabels(axes) if allAxisLabels.keys() != userLocation.keys(): LOGGER.warning( f"Mismatch between user location '{userLocation.keys()}' and available " f"labels for '{allAxisLabels.keys()}'." )
for axisName, axisLabels in allAxisLabels.items(): userValue = userLocation[axisName] label: Optional[AxisLabelDescriptor] = next( ( l for l in axisLabels if l.userValue == userValue or ( l.userMinimum is not None and l.userMaximum is not None and l.userMinimum <= userValue <= l.userMaximum ) ), None, ) if label is None: LOGGER.debug( f"Document needs a label for axis '{axisName}', user value '{userValue}'." ) else: labels.append(label)
return labels
def _getRibbiStyle( self: DesignSpaceDocument, userLocation: SimpleLocationDict) -> Tuple[RibbiStyleName, SimpleLocationDict]: """Compute the RIBBI style name of the given user location, return the location of the matching Regular in the RIBBI group.
.. versionadded:: 5.0 """ regularUserLocation = {} axes_by_tag = {axis.tag: axis for axis in self.axes}
bold: bool = False italic: bool = False
axis = axes_by_tag.get("wght") if axis is not None: for regular_label in axis.axisLabels: if ( regular_label.linkedUserValue == userLocation[axis.name] # In the "recursive" case where both the Regular has # linkedUserValue pointing the Bold, and the Bold has # linkedUserValue pointing to the Regular, only consider the # first case: Regular (e.g. 400) has linkedUserValue pointing to # Bold (e.g. 700, higher than Regular) and regular_label.userValue < regular_label.linkedUserValue ): regularUserLocation[axis.name] = regular_label.userValue bold = True break
axis = axes_by_tag.get("ital") or axes_by_tag.get("slnt") if axis is not None: for upright_label in axis.axisLabels: if ( upright_label.linkedUserValue == userLocation[axis.name] # In the "recursive" case where both the Upright has # linkedUserValue pointing the Italic, and the Italic has # linkedUserValue pointing to the Upright, only consider the # first case: Upright (e.g. ital=0, slant=0) has # linkedUserValue pointing to Italic (e.g ital=1, slant=-12 or # slant=12 for backwards italics, in any case higher than # Upright in absolute value, hence the abs() below. and abs(upright_label.userValue) < abs(upright_label.linkedUserValue) ): regularUserLocation[axis.name] = upright_label.userValue italic = True break
return BOLD_ITALIC_TO_RIBBI_STYLE[bold, italic], { **userLocation, **regularUserLocation, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147from __future__ import annotations
from dataclasses import dataclassfrom typing import Dict, List, Optional, Union, cast
from fontTools.designspaceLib import ( AxisDescriptor, DesignSpaceDocument, DesignSpaceDocumentError, RangeAxisSubsetDescriptor, SimpleLocationDict, ValueAxisSubsetDescriptor, VariableFontDescriptor,)
def clamp(value, minimum, maximum): return min(max(value, minimum), maximum)
@dataclassclass Range: minimum: float """Inclusive minimum of the range.""" maximum: float """Inclusive maximum of the range.""" default: float = 0 """Default value"""
def __post_init__(self): self.minimum, self.maximum = sorted((self.minimum, self.maximum)) self.default = clamp(self.default, self.minimum, self.maximum)
def __contains__(self, value: Union[float, Range]) -> bool: if isinstance(value, Range): return self.minimum <= value.minimum and value.maximum <= self.maximum return self.minimum <= value <= self.maximum
def intersection(self, other: Range) -> Optional[Range]: if self.maximum < other.minimum or self.minimum > other.maximum: return None else: return Range( max(self.minimum, other.minimum), min(self.maximum, other.maximum), self.default, # We don't care about the default in this use-case )
# A region selection is either a range or a single value, as a Designspace v5# axis-subset element only allows a single discrete value or a range for a# variable-font element.Region = Dict[str, Union[Range, float]]
# A conditionset is a set of named ranges.ConditionSet = Dict[str, Range]
# A rule is a list of conditionsets where any has to be relevant for the whole rule to be relevant.Rule = List[ConditionSet]Rules = Dict[str, Rule]
def locationInRegion(location: SimpleLocationDict, region: Region) -> bool: for name, value in location.items(): if name not in region: return False regionValue = region[name] if isinstance(regionValue, (float, int)): if value != regionValue: return False else: if value not in regionValue: return False return True
def regionInRegion(region: Region, superRegion: Region) -> bool: for name, value in region.items(): if not name in superRegion: return False superValue = superRegion[name] if isinstance(superValue, (float, int)): if value != superValue: return False else: if value not in superValue: return False return True
def userRegionToDesignRegion(doc: DesignSpaceDocument, userRegion: Region) -> Region: designRegion = {} for name, value in userRegion.items(): axis = doc.getAxis(name) if axis is None: raise DesignSpaceDocumentError( f"Cannot find axis named '{name}' for region." ) if isinstance(value, (float, int)): designRegion[name] = axis.map_forward(value) else: designRegion[name] = Range( axis.map_forward(value.minimum), axis.map_forward(value.maximum), axis.map_forward(value.default), ) return designRegion
def getVFUserRegion(doc: DesignSpaceDocument, vf: VariableFontDescriptor) -> Region: vfUserRegion: Region = {} # For each axis, 2 cases: # - it has a range = it's an axis in the VF DS # - it's a single location = use it to know which rules should apply in the VF for axisSubset in vf.axisSubsets: axis = doc.getAxis(axisSubset.name) if axis is None: raise DesignSpaceDocumentError( f"Cannot find axis named '{axisSubset.name}' for variable font '{vf.name}'." ) if hasattr(axisSubset, "userMinimum"): # Mypy doesn't support narrowing union types via hasattr() # TODO(Python 3.10): use TypeGuard # https://mypy.readthedocs.io/en/stable/type_narrowing.html axisSubset = cast(RangeAxisSubsetDescriptor, axisSubset) if not hasattr(axis, "minimum"): raise DesignSpaceDocumentError( f"Cannot select a range over '{axis.name}' for variable font '{vf.name}' " "because it's a discrete axis, use only 'userValue' instead." ) axis = cast(AxisDescriptor, axis) vfUserRegion[axis.name] = Range( max(axisSubset.userMinimum, axis.minimum), min(axisSubset.userMaximum, axis.maximum), axisSubset.userDefault or axis.default, ) else: axisSubset = cast(ValueAxisSubsetDescriptor, axisSubset) vfUserRegion[axis.name] = axisSubset.userValue # Any axis not mentioned explicitly has a single location = default value for axis in doc.axes: if axis.name not in vfUserRegion: assert isinstance( axis.default, (int, float) ), f"Axis '{axis.name}' has no valid default value." vfUserRegion[axis.name] = axis.default return vfUserRegion123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258MacRoman = [ "NUL", "Eth", "eth", "Lslash", "lslash", "Scaron", "scaron", "Yacute", "yacute", "HT", "LF", "Thorn", "thorn", "CR", "Zcaron", "zcaron", "DLE", "DC1", "DC2", "DC3", "DC4", "onehalf", "onequarter", "onesuperior", "threequarters", "threesuperior", "twosuperior", "brokenbar", "minus", "multiply", "RS", "US", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quotesingle", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "grave", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", "DEL", "Adieresis", "Aring", "Ccedilla", "Eacute", "Ntilde", "Odieresis", "Udieresis", "aacute", "agrave", "acircumflex", "adieresis", "atilde", "aring", "ccedilla", "eacute", "egrave", "ecircumflex", "edieresis", "iacute", "igrave", "icircumflex", "idieresis", "ntilde", "oacute", "ograve", "ocircumflex", "odieresis", "otilde", "uacute", "ugrave", "ucircumflex", "udieresis", "dagger", "degree", "cent", "sterling", "section", "bullet", "paragraph", "germandbls", "registered", "copyright", "trademark", "acute", "dieresis", "notequal", "AE", "Oslash", "infinity", "plusminus", "lessequal", "greaterequal", "yen", "mu", "partialdiff", "summation", "product", "pi", "integral", "ordfeminine", "ordmasculine", "Omega", "ae", "oslash", "questiondown", "exclamdown", "logicalnot", "radical", "florin", "approxequal", "Delta", "guillemotleft", "guillemotright", "ellipsis", "nbspace", "Agrave", "Atilde", "Otilde", "OE", "oe", "endash", "emdash", "quotedblleft", "quotedblright", "quoteleft", "quoteright", "divide", "lozenge", "ydieresis", "Ydieresis", "fraction", "currency", "guilsinglleft", "guilsinglright", "fi", "fl", "daggerdbl", "periodcentered", "quotesinglbase", "quotedblbase", "perthousand", "Acircumflex", "Ecircumflex", "Aacute", "Edieresis", "Egrave", "Iacute", "Icircumflex", "Idieresis", "Igrave", "Oacute", "Ocircumflex", "apple", "Ograve", "Uacute", "Ucircumflex", "Ugrave", "dotlessi", "circumflex", "tilde", "macron", "breve", "dotaccent", "ring", "cedilla", "hungarumlaut", "ogonek", "caron",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258StandardEncoding = [ ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", "space", "exclam", "quotedbl", "numbersign", "dollar", "percent", "ampersand", "quoteright", "parenleft", "parenright", "asterisk", "plus", "comma", "hyphen", "period", "slash", "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "colon", "semicolon", "less", "equal", "greater", "question", "at", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "bracketleft", "backslash", "bracketright", "asciicircum", "underscore", "quoteleft", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "braceleft", "bar", "braceright", "asciitilde", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", "exclamdown", "cent", "sterling", "fraction", "yen", "florin", "section", "currency", "quotesingle", "quotedblleft", "guillemotleft", "guilsinglleft", "guilsinglright", "fi", "fl", ".notdef", "endash", "dagger", "daggerdbl", "periodcentered", ".notdef", "paragraph", "bullet", "quotesinglbase", "quotedblbase", "quotedblright", "guillemotright", "ellipsis", "perthousand", ".notdef", "questiondown", ".notdef", "grave", "acute", "circumflex", "tilde", "macron", "breve", "dotaccent", "dieresis", ".notdef", "ring", "cedilla", ".notdef", "hungarumlaut", "ogonek", "caron", "emdash", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", "AE", ".notdef", "ordfeminine", ".notdef", ".notdef", ".notdef", ".notdef", "Lslash", "Oslash", "OE", "ordmasculine", ".notdef", ".notdef", ".notdef", ".notdef", ".notdef", "ae", ".notdef", ".notdef", ".notdef", "dotlessi", ".notdef", ".notdef", "lslash", "oslash", "oe", "germandbls", ".notdef", ".notdef", ".notdef", ".notdef",]1"""Empty __init__.py file to signal Python this directory is a package."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""Extend the Python codecs module with a few encodings that are used in OpenType (name table)but missing from Python. See https://github.com/fonttools/fonttools/issues/236 for details."""
import codecsimport encodings
class ExtendCodec(codecs.Codec): def __init__(self, name, base_encoding, mapping): self.name = name self.base_encoding = base_encoding self.mapping = mapping self.reverse = {v: k for k, v in mapping.items()} self.max_len = max(len(v) for v in mapping.values()) self.info = codecs.CodecInfo( name=self.name, encode=self.encode, decode=self.decode ) codecs.register_error(name, self.error)
def _map(self, mapper, output_type, exc_type, input, errors): base_error_handler = codecs.lookup_error(errors) length = len(input) out = output_type() while input: # first try to use self.error as the error handler try: part = mapper(input, self.base_encoding, errors=self.name) out += part break # All converted except exc_type as e: # else convert the correct part, handle error as requested and continue out += mapper(input[: e.start], self.base_encoding, self.name) replacement, pos = base_error_handler(e) out += replacement input = input[pos:] return out, length
def encode(self, input, errors="strict"): return self._map(codecs.encode, bytes, UnicodeEncodeError, input, errors)
def decode(self, input, errors="strict"): return self._map(codecs.decode, str, UnicodeDecodeError, input, errors)
def error(self, e): if isinstance(e, UnicodeDecodeError): for end in range(e.start + 1, e.end + 1): s = e.object[e.start : end] if s in self.mapping: return self.mapping[s], end elif isinstance(e, UnicodeEncodeError): for end in range(e.start + 1, e.start + self.max_len + 1): s = e.object[e.start : end] if s in self.reverse: return self.reverse[s], end e.encoding = self.name raise e
_extended_encodings = { "x_mac_japanese_ttx": ( "shift_jis", { b"\xFC": chr(0x007C), b"\x7E": chr(0x007E), b"\x80": chr(0x005C), b"\xA0": chr(0x00A0), b"\xFD": chr(0x00A9), b"\xFE": chr(0x2122), b"\xFF": chr(0x2026), }, ), "x_mac_trad_chinese_ttx": ( "big5", { b"\x80": chr(0x005C), b"\xA0": chr(0x00A0), b"\xFD": chr(0x00A9), b"\xFE": chr(0x2122), b"\xFF": chr(0x2026), }, ), "x_mac_korean_ttx": ( "euc_kr", { b"\x80": chr(0x00A0), b"\x81": chr(0x20A9), b"\x82": chr(0x2014), b"\x83": chr(0x00A9), b"\xFE": chr(0x2122), b"\xFF": chr(0x2026), }, ), "x_mac_simp_chinese_ttx": ( "gb2312", { b"\x80": chr(0x00FC), b"\xA0": chr(0x00A0), b"\xFD": chr(0x00A9), b"\xFE": chr(0x2122), b"\xFF": chr(0x2026), }, ),}
_cache = {}
def search_function(name): name = encodings.normalize_encoding(name) # Rather undocumented... if name in _extended_encodings: if name not in _cache: base_encoding, mapping = _extended_encodings[name] assert name[-4:] == "_ttx" # Python 2 didn't have any of the encodings that we are implementing # in this file. Python 3 added aliases for the East Asian ones, mapping # them "temporarily" to the same base encoding as us, with a comment # suggesting that full implementation will appear some time later. # As such, try the Python version of the x_mac_... first, if that is found, # use *that* as our base encoding. This would make our encoding upgrade # to the full encoding when and if Python finally implements that. # http://bugs.python.org/issue24041 base_encodings = [name[:-4], base_encoding] for base_encoding in base_encodings: try: codecs.lookup(base_encoding) except LookupError: continue _cache[name] = ExtendCodec(name, base_encoding, mapping) break return _cache[name].info
return None
codecs.register(search_function)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014__all__ = ["FontBuilder"]
"""This module is *experimental*, meaning it still may evolve and change.
The `FontBuilder` class is a convenient helper to construct working TTF orOTF fonts from scratch.
Note that the various setup methods cannot be called in arbitrary order,due to various interdependencies between OpenType tables. Here is an orderthat works:
fb = FontBuilder(...) fb.setupGlyphOrder(...) fb.setupCharacterMap(...) fb.setupGlyf(...) --or-- fb.setupCFF(...) fb.setupHorizontalMetrics(...) fb.setupHorizontalHeader() fb.setupNameTable(...) fb.setupOS2() fb.addOpenTypeFeatures(...) fb.setupPost() fb.save(...)
Here is how to build a minimal TTF:
```pythonfrom fontTools.fontBuilder import FontBuilderfrom fontTools.pens.ttGlyphPen import TTGlyphPen
def drawTestGlyph(pen): pen.moveTo((100, 100)) pen.lineTo((100, 1000)) pen.qCurveTo((200, 900), (400, 900), (500, 1000)) pen.lineTo((500, 100)) pen.closePath()
fb = FontBuilder(1024, isTTF=True)fb.setupGlyphOrder([".notdef", ".null", "space", "A", "a"])fb.setupCharacterMap({32: "space", 65: "A", 97: "a"})advanceWidths = {".notdef": 600, "space": 500, "A": 600, "a": 600, ".null": 0}
familyName = "HelloTestFont"styleName = "TotallyNormal"version = "0.1"
nameStrings = dict( familyName=dict(en=familyName, nl="HalloTestFont"), styleName=dict(en=styleName, nl="TotaalNormaal"), uniqueFontIdentifier="fontBuilder: " + familyName + "." + styleName, fullName=familyName + "-" + styleName, psName=familyName + "-" + styleName, version="Version " + version,)
pen = TTGlyphPen(None)drawTestGlyph(pen)glyph = pen.glyph()glyphs = {".notdef": glyph, "space": glyph, "A": glyph, "a": glyph, ".null": glyph}fb.setupGlyf(glyphs)metrics = {}glyphTable = fb.font["glyf"]for gn, advanceWidth in advanceWidths.items(): metrics[gn] = (advanceWidth, glyphTable[gn].xMin)fb.setupHorizontalMetrics(metrics)fb.setupHorizontalHeader(ascent=824, descent=-200)fb.setupNameTable(nameStrings)fb.setupOS2(sTypoAscender=824, usWinAscent=824, usWinDescent=200)fb.setupPost()fb.save("test.ttf")```
And here's how to build a minimal OTF:
```pythonfrom fontTools.fontBuilder import FontBuilderfrom fontTools.pens.t2CharStringPen import T2CharStringPen
def drawTestGlyph(pen): pen.moveTo((100, 100)) pen.lineTo((100, 1000)) pen.curveTo((200, 900), (400, 900), (500, 1000)) pen.lineTo((500, 100)) pen.closePath()
fb = FontBuilder(1024, isTTF=False)fb.setupGlyphOrder([".notdef", ".null", "space", "A", "a"])fb.setupCharacterMap({32: "space", 65: "A", 97: "a"})advanceWidths = {".notdef": 600, "space": 500, "A": 600, "a": 600, ".null": 0}
familyName = "HelloTestFont"styleName = "TotallyNormal"version = "0.1"
nameStrings = dict( familyName=dict(en=familyName, nl="HalloTestFont"), styleName=dict(en=styleName, nl="TotaalNormaal"), uniqueFontIdentifier="fontBuilder: " + familyName + "." + styleName, fullName=familyName + "-" + styleName, psName=familyName + "-" + styleName, version="Version " + version,)
pen = T2CharStringPen(600, None)drawTestGlyph(pen)charString = pen.getCharString()charStrings = { ".notdef": charString, "space": charString, "A": charString, "a": charString, ".null": charString,}fb.setupCFF(nameStrings["psName"], {"FullName": nameStrings["psName"]}, charStrings, {})lsb = {gn: cs.calcBounds(None)[0] for gn, cs in charStrings.items()}metrics = {}for gn, advanceWidth in advanceWidths.items(): metrics[gn] = (advanceWidth, lsb[gn])fb.setupHorizontalMetrics(metrics)fb.setupHorizontalHeader(ascent=824, descent=200)fb.setupNameTable(nameStrings)fb.setupOS2(sTypoAscender=824, usWinAscent=824, usWinDescent=200)fb.setupPost()fb.save("test.otf")```"""
from .ttLib import TTFont, newTablefrom .ttLib.tables._c_m_a_p import cmap_classesfrom .ttLib.tables._g_l_y_f import flagCubicfrom .ttLib.tables.O_S_2f_2 import Panosefrom .misc.timeTools import timestampNowimport structfrom collections import OrderedDict
_headDefaults = dict( tableVersion=1.0, fontRevision=1.0, checkSumAdjustment=0, magicNumber=0x5F0F3CF5, flags=0x0003, unitsPerEm=1000, created=0, modified=0, xMin=0, yMin=0, xMax=0, yMax=0, macStyle=0, lowestRecPPEM=3, fontDirectionHint=2, indexToLocFormat=0, glyphDataFormat=0,)
_maxpDefaultsTTF = dict( tableVersion=0x00010000, numGlyphs=0, maxPoints=0, maxContours=0, maxCompositePoints=0, maxCompositeContours=0, maxZones=2, maxTwilightPoints=0, maxStorage=0, maxFunctionDefs=0, maxInstructionDefs=0, maxStackElements=0, maxSizeOfInstructions=0, maxComponentElements=0, maxComponentDepth=0,)_maxpDefaultsOTF = dict( tableVersion=0x00005000, numGlyphs=0,)
_postDefaults = dict( formatType=3.0, italicAngle=0, underlinePosition=0, underlineThickness=0, isFixedPitch=0, minMemType42=0, maxMemType42=0, minMemType1=0, maxMemType1=0,)
_hheaDefaults = dict( tableVersion=0x00010000, ascent=0, descent=0, lineGap=0, advanceWidthMax=0, minLeftSideBearing=0, minRightSideBearing=0, xMaxExtent=0, caretSlopeRise=1, caretSlopeRun=0, caretOffset=0, reserved0=0, reserved1=0, reserved2=0, reserved3=0, metricDataFormat=0, numberOfHMetrics=0,)
_vheaDefaults = dict( tableVersion=0x00010000, ascent=0, descent=0, lineGap=0, advanceHeightMax=0, minTopSideBearing=0, minBottomSideBearing=0, yMaxExtent=0, caretSlopeRise=0, caretSlopeRun=0, reserved0=0, reserved1=0, reserved2=0, reserved3=0, reserved4=0, metricDataFormat=0, numberOfVMetrics=0,)
_nameIDs = dict( copyright=0, familyName=1, styleName=2, uniqueFontIdentifier=3, fullName=4, version=5, psName=6, trademark=7, manufacturer=8, designer=9, description=10, vendorURL=11, designerURL=12, licenseDescription=13, licenseInfoURL=14, # reserved = 15, typographicFamily=16, typographicSubfamily=17, compatibleFullName=18, sampleText=19, postScriptCIDFindfontName=20, wwsFamilyName=21, wwsSubfamilyName=22, lightBackgroundPalette=23, darkBackgroundPalette=24, variationsPostScriptNamePrefix=25,)
# to insert in setupNameTable doc string:# print("\n".join(("%s (nameID %s)" % (k, v)) for k, v in sorted(_nameIDs.items(), key=lambda x: x[1])))
def _getOS2Defaults(): return dict( version=3, xAvgCharWidth=0, usWeightClass=400, usWidthClass=5, fsType=0x0004, # default: Preview & Print embedding ySubscriptXSize=0, ySubscriptYSize=0, ySubscriptXOffset=0, ySubscriptYOffset=0, ySuperscriptXSize=0, ySuperscriptYSize=0, ySuperscriptXOffset=0, ySuperscriptYOffset=0, yStrikeoutSize=0, yStrikeoutPosition=0, sFamilyClass=0, panose=Panose(), ulUnicodeRange1=0, ulUnicodeRange2=0, ulUnicodeRange3=0, ulUnicodeRange4=0, achVendID="????", fsSelection=0, usFirstCharIndex=0, usLastCharIndex=0, sTypoAscender=0, sTypoDescender=0, sTypoLineGap=0, usWinAscent=0, usWinDescent=0, ulCodePageRange1=0, ulCodePageRange2=0, sxHeight=0, sCapHeight=0, usDefaultChar=0, # .notdef usBreakChar=32, # space usMaxContext=0, usLowerOpticalPointSize=0, usUpperOpticalPointSize=0, )
class FontBuilder(object): def __init__(self, unitsPerEm=None, font=None, isTTF=True, glyphDataFormat=0): """Initialize a FontBuilder instance.
If the `font` argument is not given, a new `TTFont` will be constructed, and `unitsPerEm` must be given. If `isTTF` is True, the font will be a glyf-based TTF; if `isTTF` is False it will be a CFF-based OTF.
The `glyphDataFormat` argument corresponds to the `head` table field that defines the format of the TrueType `glyf` table (default=0). TrueType glyphs historically can only contain quadratic splines and static components, but there's a proposal to add support for cubic Bezier curves as well as variable composites/components at https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1.md You can experiment with the new features by setting `glyphDataFormat` to 1. A ValueError is raised if `glyphDataFormat` is left at 0 but glyphs are added that contain cubic splines or varcomposites. This is to prevent accidentally creating fonts that are incompatible with existing TrueType implementations.
If `font` is given, it must be a `TTFont` instance and `unitsPerEm` must _not_ be given. The `isTTF` and `glyphDataFormat` arguments will be ignored. """ if font is None: self.font = TTFont(recalcTimestamp=False) self.isTTF = isTTF now = timestampNow() assert unitsPerEm is not None self.setupHead( unitsPerEm=unitsPerEm, created=now, modified=now, glyphDataFormat=glyphDataFormat, ) self.setupMaxp() else: assert unitsPerEm is None self.font = font self.isTTF = "glyf" in font
def save(self, file): """Save the font. The 'file' argument can be either a pathname or a writable file object. """ self.font.save(file)
def _initTableWithValues(self, tableTag, defaults, values): table = self.font[tableTag] = newTable(tableTag) for k, v in defaults.items(): setattr(table, k, v) for k, v in values.items(): setattr(table, k, v) return table
def _updateTableWithValues(self, tableTag, values): table = self.font[tableTag] for k, v in values.items(): setattr(table, k, v)
def setupHead(self, **values): """Create a new `head` table and initialize it with default values, which can be overridden by keyword arguments. """ self._initTableWithValues("head", _headDefaults, values)
def updateHead(self, **values): """Update the head table with the fields and values passed as keyword arguments. """ self._updateTableWithValues("head", values)
def setupGlyphOrder(self, glyphOrder): """Set the glyph order for the font.""" self.font.setGlyphOrder(glyphOrder)
def setupCharacterMap(self, cmapping, uvs=None, allowFallback=False): """Build the `cmap` table for the font. The `cmapping` argument should be a dict mapping unicode code points as integers to glyph names.
The `uvs` argument, when passed, must be a list of tuples, describing Unicode Variation Sequences. These tuples have three elements: (unicodeValue, variationSelector, glyphName) `unicodeValue` and `variationSelector` are integer code points. `glyphName` may be None, to indicate this is the default variation. Text processors will then use the cmap to find the glyph name. Each Unicode Variation Sequence should be an officially supported sequence, but this is not policed. """ subTables = [] highestUnicode = max(cmapping) if cmapping else 0 if highestUnicode > 0xFFFF: cmapping_3_1 = dict((k, v) for k, v in cmapping.items() if k < 0x10000) subTable_3_10 = buildCmapSubTable(cmapping, 12, 3, 10) subTables.append(subTable_3_10) else: cmapping_3_1 = cmapping format = 4 subTable_3_1 = buildCmapSubTable(cmapping_3_1, format, 3, 1) try: subTable_3_1.compile(self.font) except struct.error: # format 4 overflowed, fall back to format 12 if not allowFallback: raise ValueError( "cmap format 4 subtable overflowed; sort glyph order by unicode to fix." ) format = 12 subTable_3_1 = buildCmapSubTable(cmapping_3_1, format, 3, 1) subTables.append(subTable_3_1) subTable_0_3 = buildCmapSubTable(cmapping_3_1, format, 0, 3) subTables.append(subTable_0_3)
if uvs is not None: uvsDict = {} for unicodeValue, variationSelector, glyphName in uvs: if cmapping.get(unicodeValue) == glyphName: # this is a default variation glyphName = None if variationSelector not in uvsDict: uvsDict[variationSelector] = [] uvsDict[variationSelector].append((unicodeValue, glyphName)) uvsSubTable = buildCmapSubTable({}, 14, 0, 5) uvsSubTable.uvsDict = uvsDict subTables.append(uvsSubTable)
self.font["cmap"] = newTable("cmap") self.font["cmap"].tableVersion = 0 self.font["cmap"].tables = subTables
def setupNameTable(self, nameStrings, windows=True, mac=True): """Create the `name` table for the font. The `nameStrings` argument must be a dict, mapping nameIDs or descriptive names for the nameIDs to name record values. A value is either a string, or a dict, mapping language codes to strings, to allow localized name table entries.
By default, both Windows (platformID=3) and Macintosh (platformID=1) name records are added, unless any of `windows` or `mac` arguments is False.
The following descriptive names are available for nameIDs:
copyright (nameID 0) familyName (nameID 1) styleName (nameID 2) uniqueFontIdentifier (nameID 3) fullName (nameID 4) version (nameID 5) psName (nameID 6) trademark (nameID 7) manufacturer (nameID 8) designer (nameID 9) description (nameID 10) vendorURL (nameID 11) designerURL (nameID 12) licenseDescription (nameID 13) licenseInfoURL (nameID 14) typographicFamily (nameID 16) typographicSubfamily (nameID 17) compatibleFullName (nameID 18) sampleText (nameID 19) postScriptCIDFindfontName (nameID 20) wwsFamilyName (nameID 21) wwsSubfamilyName (nameID 22) lightBackgroundPalette (nameID 23) darkBackgroundPalette (nameID 24) variationsPostScriptNamePrefix (nameID 25) """ nameTable = self.font["name"] = newTable("name") nameTable.names = []
for nameName, nameValue in nameStrings.items(): if isinstance(nameName, int): nameID = nameName else: nameID = _nameIDs[nameName] if isinstance(nameValue, str): nameValue = dict(en=nameValue) nameTable.addMultilingualName( nameValue, ttFont=self.font, nameID=nameID, windows=windows, mac=mac )
def setupOS2(self, **values): """Create a new `OS/2` table and initialize it with default values, which can be overridden by keyword arguments. """ self._initTableWithValues("OS/2", _getOS2Defaults(), values) if "xAvgCharWidth" not in values: assert ( "hmtx" in self.font ), "the 'hmtx' table must be setup before the 'OS/2' table" self.font["OS/2"].recalcAvgCharWidth(self.font) if not ( "ulUnicodeRange1" in values or "ulUnicodeRange2" in values or "ulUnicodeRange3" in values or "ulUnicodeRange3" in values ): assert ( "cmap" in self.font ), "the 'cmap' table must be setup before the 'OS/2' table" self.font["OS/2"].recalcUnicodeRanges(self.font)
def setupCFF(self, psName, fontInfo, charStringsDict, privateDict): from .cffLib import ( CFFFontSet, TopDictIndex, TopDict, CharStrings, GlobalSubrsIndex, PrivateDict, )
assert not self.isTTF self.font.sfntVersion = "OTTO" fontSet = CFFFontSet() fontSet.major = 1 fontSet.minor = 0 fontSet.otFont = self.font fontSet.fontNames = [psName] fontSet.topDictIndex = TopDictIndex()
globalSubrs = GlobalSubrsIndex() fontSet.GlobalSubrs = globalSubrs private = PrivateDict() for key, value in privateDict.items(): setattr(private, key, value) fdSelect = None fdArray = None
topDict = TopDict() topDict.charset = self.font.getGlyphOrder() topDict.Private = private topDict.GlobalSubrs = fontSet.GlobalSubrs for key, value in fontInfo.items(): setattr(topDict, key, value) if "FontMatrix" not in fontInfo: scale = 1 / self.font["head"].unitsPerEm topDict.FontMatrix = [scale, 0, 0, scale, 0, 0]
charStrings = CharStrings( None, topDict.charset, globalSubrs, private, fdSelect, fdArray ) for glyphName, charString in charStringsDict.items(): charString.private = private charString.globalSubrs = globalSubrs charStrings[glyphName] = charString topDict.CharStrings = charStrings
fontSet.topDictIndex.append(topDict)
self.font["CFF "] = newTable("CFF ") self.font["CFF "].cff = fontSet
def setupCFF2(self, charStringsDict, fdArrayList=None, regions=None): from .cffLib import ( CFFFontSet, TopDictIndex, TopDict, CharStrings, GlobalSubrsIndex, PrivateDict, FDArrayIndex, FontDict, )
assert not self.isTTF self.font.sfntVersion = "OTTO" fontSet = CFFFontSet() fontSet.major = 2 fontSet.minor = 0
cff2GetGlyphOrder = self.font.getGlyphOrder fontSet.topDictIndex = TopDictIndex(None, cff2GetGlyphOrder, None)
globalSubrs = GlobalSubrsIndex() fontSet.GlobalSubrs = globalSubrs
if fdArrayList is None: fdArrayList = [{}] fdSelect = None fdArray = FDArrayIndex() fdArray.strings = None fdArray.GlobalSubrs = globalSubrs for privateDict in fdArrayList: fontDict = FontDict() fontDict.setCFF2(True) private = PrivateDict() for key, value in privateDict.items(): setattr(private, key, value) fontDict.Private = private fdArray.append(fontDict)
topDict = TopDict() topDict.cff2GetGlyphOrder = cff2GetGlyphOrder topDict.FDArray = fdArray scale = 1 / self.font["head"].unitsPerEm topDict.FontMatrix = [scale, 0, 0, scale, 0, 0]
private = fdArray[0].Private charStrings = CharStrings(None, None, globalSubrs, private, fdSelect, fdArray) for glyphName, charString in charStringsDict.items(): charString.private = private charString.globalSubrs = globalSubrs charStrings[glyphName] = charString topDict.CharStrings = charStrings
fontSet.topDictIndex.append(topDict)
self.font["CFF2"] = newTable("CFF2") self.font["CFF2"].cff = fontSet
if regions: self.setupCFF2Regions(regions)
def setupCFF2Regions(self, regions): from .varLib.builder import buildVarRegionList, buildVarData, buildVarStore from .cffLib import VarStoreData
assert "fvar" in self.font, "fvar must to be set up first" assert "CFF2" in self.font, "CFF2 must to be set up first" axisTags = [a.axisTag for a in self.font["fvar"].axes] varRegionList = buildVarRegionList(regions, axisTags) varData = buildVarData(list(range(len(regions))), None, optimize=False) varStore = buildVarStore(varRegionList, [varData]) vstore = VarStoreData(otVarStore=varStore) topDict = self.font["CFF2"].cff.topDictIndex[0] topDict.VarStore = vstore for fontDict in topDict.FDArray: fontDict.Private.vstore = vstore
def setupGlyf(self, glyphs, calcGlyphBounds=True, validateGlyphFormat=True): """Create the `glyf` table from a dict, that maps glyph names to `fontTools.ttLib.tables._g_l_y_f.Glyph` objects, for example as made by `fontTools.pens.ttGlyphPen.TTGlyphPen`.
If `calcGlyphBounds` is True, the bounds of all glyphs will be calculated. Only pass False if your glyph objects already have their bounding box values set.
If `validateGlyphFormat` is True, raise ValueError if any of the glyphs contains cubic curves or is a variable composite but head.glyphDataFormat=0. Set it to False to skip the check if you know in advance all the glyphs are compatible with the specified glyphDataFormat. """ assert self.isTTF
if validateGlyphFormat and self.font["head"].glyphDataFormat == 0: for name, g in glyphs.items(): if g.numberOfContours > 0 and any(f & flagCubic for f in g.flags): raise ValueError( f"Glyph {name!r} has cubic Bezier outlines, but glyphDataFormat=0; " "either convert to quadratics with cu2qu or set glyphDataFormat=1." )
self.font["loca"] = newTable("loca") self.font["glyf"] = newTable("glyf") self.font["glyf"].glyphs = glyphs if hasattr(self.font, "glyphOrder"): self.font["glyf"].glyphOrder = self.font.glyphOrder if calcGlyphBounds: self.calcGlyphBounds()
def setupFvar(self, axes, instances): """Adds an font variations table to the font.
Args: axes (list): See below. instances (list): See below.
``axes`` should be a list of axes, with each axis either supplied as a py:class:`.designspaceLib.AxisDescriptor` object, or a tuple in the format ```tupletag, minValue, defaultValue, maxValue, name``. The ``name`` is either a string, or a dict, mapping language codes to strings, to allow localized name table entries.
```instances`` should be a list of instances, with each instance either supplied as a py:class:`.designspaceLib.InstanceDescriptor` object, or a dict with keys ``location`` (mapping of axis tags to float values), ``stylename`` and (optionally) ``postscriptfontname``. The ``stylename`` is either a string, or a dict, mapping language codes to strings, to allow localized name table entries. """
addFvar(self.font, axes, instances)
def setupAvar(self, axes, mappings=None): """Adds an axis variations table to the font.
Args: axes (list): A list of py:class:`.designspaceLib.AxisDescriptor` objects. """ from .varLib import _add_avar
if "fvar" not in self.font: raise KeyError("'fvar' table is missing; can't add 'avar'.")
axisTags = [axis.axisTag for axis in self.font["fvar"].axes] axes = OrderedDict(enumerate(axes)) # Only values are used _add_avar(self.font, axes, mappings, axisTags)
def setupGvar(self, variations): gvar = self.font["gvar"] = newTable("gvar") gvar.version = 1 gvar.reserved = 0 gvar.variations = variations
def setupGVAR(self, variations): gvar = self.font["GVAR"] = newTable("GVAR") gvar.version = 1 gvar.reserved = 0 gvar.variations = variations
def calcGlyphBounds(self): """Calculate the bounding boxes of all glyphs in the `glyf` table. This is usually not called explicitly by client code. """ glyphTable = self.font["glyf"] for glyph in glyphTable.glyphs.values(): glyph.recalcBounds(glyphTable)
def setupHorizontalMetrics(self, metrics): """Create a new `hmtx` table, for horizontal metrics.
The `metrics` argument must be a dict, mapping glyph names to `(width, leftSidebearing)` tuples. """ self.setupMetrics("hmtx", metrics)
def setupVerticalMetrics(self, metrics): """Create a new `vmtx` table, for horizontal metrics.
The `metrics` argument must be a dict, mapping glyph names to `(height, topSidebearing)` tuples. """ self.setupMetrics("vmtx", metrics)
def setupMetrics(self, tableTag, metrics): """See `setupHorizontalMetrics()` and `setupVerticalMetrics()`.""" assert tableTag in ("hmtx", "vmtx") mtxTable = self.font[tableTag] = newTable(tableTag) roundedMetrics = {} for gn in metrics: w, lsb = metrics[gn] roundedMetrics[gn] = int(round(w)), int(round(lsb)) mtxTable.metrics = roundedMetrics
def setupHorizontalHeader(self, **values): """Create a new `hhea` table initialize it with default values, which can be overridden by keyword arguments. """ self._initTableWithValues("hhea", _hheaDefaults, values)
def setupVerticalHeader(self, **values): """Create a new `vhea` table initialize it with default values, which can be overridden by keyword arguments. """ self._initTableWithValues("vhea", _vheaDefaults, values)
def setupVerticalOrigins(self, verticalOrigins, defaultVerticalOrigin=None): """Create a new `VORG` table. The `verticalOrigins` argument must be a dict, mapping glyph names to vertical origin values.
The `defaultVerticalOrigin` argument should be the most common vertical origin value. If omitted, this value will be derived from the actual values in the `verticalOrigins` argument. """ if defaultVerticalOrigin is None: # find the most frequent vorg value bag = {} for gn in verticalOrigins: vorg = verticalOrigins[gn] if vorg not in bag: bag[vorg] = 1 else: bag[vorg] += 1 defaultVerticalOrigin = sorted( bag, key=lambda vorg: bag[vorg], reverse=True )[0] self._initTableWithValues( "VORG", {}, dict(VOriginRecords={}, defaultVertOriginY=defaultVerticalOrigin), ) vorgTable = self.font["VORG"] vorgTable.majorVersion = 1 vorgTable.minorVersion = 0 for gn in verticalOrigins: vorgTable[gn] = verticalOrigins[gn]
def setupPost(self, keepGlyphNames=True, **values): """Create a new `post` table and initialize it with default values, which can be overridden by keyword arguments. """ isCFF2 = "CFF2" in self.font postTable = self._initTableWithValues("post", _postDefaults, values) if (self.isTTF or isCFF2) and keepGlyphNames: postTable.formatType = 2.0 postTable.extraNames = [] postTable.mapping = {} else: postTable.formatType = 3.0
def setupMaxp(self): """Create a new `maxp` table. This is called implicitly by FontBuilder itself and is usually not called by client code. """ if self.isTTF: defaults = _maxpDefaultsTTF else: defaults = _maxpDefaultsOTF self._initTableWithValues("maxp", defaults, {})
def setupDummyDSIG(self): """This adds an empty DSIG table to the font to make some MS applications happy. This does not properly sign the font. """ values = dict( ulVersion=1, usFlag=0, usNumSigs=0, signatureRecords=[], ) self._initTableWithValues("DSIG", {}, values)
def addOpenTypeFeatures(self, features, filename=None, tables=None, debug=False): """Add OpenType features to the font from a string containing Feature File syntax.
The `filename` argument is used in error messages and to determine where to look for "include" files.
The optional `tables` argument can be a list of OTL tables tags to build, allowing the caller to only build selected OTL tables. See `fontTools.feaLib` for details.
The optional `debug` argument controls whether to add source debugging information to the font in the `Debg` table. """ from .feaLib.builder import addOpenTypeFeaturesFromString
addOpenTypeFeaturesFromString( self.font, features, filename=filename, tables=tables, debug=debug )
def addFeatureVariations(self, conditionalSubstitutions, featureTag="rvrn"): """Add conditional substitutions to a Variable Font.
See `fontTools.varLib.featureVars.addFeatureVariations`. """ from .varLib import featureVars
if "fvar" not in self.font: raise KeyError("'fvar' table is missing; can't add FeatureVariations.")
featureVars.addFeatureVariations( self.font, conditionalSubstitutions, featureTag=featureTag )
def setupCOLR( self, colorLayers, version=None, varStore=None, varIndexMap=None, clipBoxes=None, allowLayerReuse=True, ): """Build new COLR table using color layers dictionary.
Cf. `fontTools.colorLib.builder.buildCOLR`. """ from fontTools.colorLib.builder import buildCOLR
glyphMap = self.font.getReverseGlyphMap() self.font["COLR"] = buildCOLR( colorLayers, version=version, glyphMap=glyphMap, varStore=varStore, varIndexMap=varIndexMap, clipBoxes=clipBoxes, allowLayerReuse=allowLayerReuse, )
def setupCPAL( self, palettes, paletteTypes=None, paletteLabels=None, paletteEntryLabels=None, ): """Build new CPAL table using list of palettes.
Optionally build CPAL v1 table using paletteTypes, paletteLabels and paletteEntryLabels.
Cf. `fontTools.colorLib.builder.buildCPAL`. """ from fontTools.colorLib.builder import buildCPAL
self.font["CPAL"] = buildCPAL( palettes, paletteTypes=paletteTypes, paletteLabels=paletteLabels, paletteEntryLabels=paletteEntryLabels, nameTable=self.font.get("name"), )
def setupStat(self, axes, locations=None, elidedFallbackName=2): """Build a new 'STAT' table.
See `fontTools.otlLib.builder.buildStatTable` for details about the arguments. """ from .otlLib.builder import buildStatTable
assert "name" in self.font, "name must to be set up first"
buildStatTable( self.font, axes, locations, elidedFallbackName, macNames=any(nr.platformID == 1 for nr in self.font["name"].names), )
def buildCmapSubTable(cmapping, format, platformID, platEncID): subTable = cmap_classes[format](format) subTable.cmap = cmapping subTable.platformID = platformID subTable.platEncID = platEncID subTable.language = 0 return subTable
def addFvar(font, axes, instances): from .ttLib.tables._f_v_a_r import Axis, NamedInstance
assert axes
fvar = newTable("fvar") nameTable = font["name"]
# if there are not currently any mac names don't add them here, that's inconsistent # https://github.com/fonttools/fonttools/issues/683 macNames = any(nr.platformID == 1 for nr in getattr(nameTable, "names", ()))
# we have all the best ways to express mac names platforms = ((3, 1, 0x409),) if macNames: platforms = ((1, 0, 0),) + platforms
for axis_def in axes: axis = Axis()
if isinstance(axis_def, tuple): ( axis.axisTag, axis.minValue, axis.defaultValue, axis.maxValue, name, ) = axis_def else: (axis.axisTag, axis.minValue, axis.defaultValue, axis.maxValue, name) = ( axis_def.tag, axis_def.minimum, axis_def.default, axis_def.maximum, axis_def.name, ) if axis_def.hidden: axis.flags = 0x0001 # HIDDEN_AXIS
if isinstance(name, str): name = dict(en=name)
axis.axisNameID = nameTable.addMultilingualName(name, ttFont=font, mac=macNames) fvar.axes.append(axis)
for instance in instances: if isinstance(instance, dict): coordinates = instance["location"] name = instance["stylename"] psname = instance.get("postscriptfontname") else: coordinates = instance.location name = instance.localisedStyleName or instance.styleName psname = instance.postScriptFontName
if isinstance(name, str): name = dict(en=name)
inst = NamedInstance() inst.subfamilyNameID = nameTable.addMultilingualName( name, ttFont=font, mac=macNames ) if psname is not None: inst.postscriptNameID = nameTable.addName(psname, platforms=platforms) inst.coordinates = coordinates fvar.instances.append(inst)
font["fvar"] = fvar123456789101112131415161718192021222324252627282930313233343536import pkgutilimport sysimport fontToolsimport importlibimport osfrom pathlib import Path
def main(): """Show this help""" path = fontTools.__path__ descriptions = {} for pkg in sorted( mod.name for mod in pkgutil.walk_packages([fontTools.__path__[0]], prefix="fontTools.") ): try: imports = __import__(pkg, globals(), locals(), ["main"]) except ImportError as e: continue try: description = imports.main.__doc__ # Cython modules seem to return "main()" as the docstring if description and description != "main()": pkg = pkg.replace("fontTools.", "").replace(".__main__", "") # show the docstring's first line only descriptions[pkg] = description.splitlines()[0] except AttributeError as e: pass for pkg, description in descriptions.items(): print("fonttools %-25s %s" % (pkg, description), file=sys.stderr)
if __name__ == "__main__": print("fonttools v%s\n" % fontTools.__version__, file=sys.stderr) main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400# FontDame-to-FontTools for OpenType Layout tables## Source language spec is available at:# http://monotype.github.io/OpenType_Table_Source/otl_source.html# https://github.com/Monotype/OpenType_Table_Source/
from fontTools import ttLibfrom fontTools.ttLib.tables._c_m_a_p import cmap_classesfrom fontTools.ttLib.tables import otTables as otfrom fontTools.ttLib.tables.otBase import ValueRecord, valueRecordFormatDictfrom fontTools.otlLib import builder as otlfrom contextlib import contextmanagerfrom fontTools.ttLib import newTablefrom fontTools.feaLib.lookupDebugInfo import LOOKUP_DEBUG_ENV_VAR, LOOKUP_DEBUG_INFO_KEYfrom operator import setitemimport osimport logging
class MtiLibError(Exception): pass
class ReferenceNotFoundError(MtiLibError): pass
class FeatureNotFoundError(ReferenceNotFoundError): pass
class LookupNotFoundError(ReferenceNotFoundError): pass
log = logging.getLogger("fontTools.mtiLib")
def makeGlyph(s): if s[:2] in ["U ", "u "]: return ttLib.TTFont._makeGlyphName(int(s[2:], 16)) elif s[:2] == "# ": return "glyph%.5d" % int(s[2:]) assert s.find(" ") < 0, "Space found in glyph name: %s" % s assert s, "Glyph name is empty" return s
def makeGlyphs(l): return [makeGlyph(g) for g in l]
def mapLookup(sym, mapping): # Lookups are addressed by name. So resolved them using a map if available. # Fallback to parsing as lookup index if a map isn't provided. if mapping is not None: try: idx = mapping[sym] except KeyError: raise LookupNotFoundError(sym) else: idx = int(sym) return idx
def mapFeature(sym, mapping): # Features are referenced by index according the spec. So, if symbol is an # integer, use it directly. Otherwise look up in the map if provided. try: idx = int(sym) except ValueError: try: idx = mapping[sym] except KeyError: raise FeatureNotFoundError(sym) return idx
def setReference(mapper, mapping, sym, setter, collection, key): try: mapped = mapper(sym, mapping) except ReferenceNotFoundError as e: try: if mapping is not None: mapping.addDeferredMapping( lambda ref: setter(collection, key, ref), sym, e ) return except AttributeError: pass raise setter(collection, key, mapped)
class DeferredMapping(dict): def __init__(self): self._deferredMappings = []
def addDeferredMapping(self, setter, sym, e): log.debug("Adding deferred mapping for symbol '%s' %s", sym, type(e).__name__) self._deferredMappings.append((setter, sym, e))
def applyDeferredMappings(self): for setter, sym, e in self._deferredMappings: log.debug( "Applying deferred mapping for symbol '%s' %s", sym, type(e).__name__ ) try: mapped = self[sym] except KeyError: raise e setter(mapped) log.debug("Set to %s", mapped) self._deferredMappings = []
def parseScriptList(lines, featureMap=None): self = ot.ScriptList() records = [] with lines.between("script table"): for line in lines: while len(line) < 4: line.append("") scriptTag, langSysTag, defaultFeature, features = line log.debug("Adding script %s language-system %s", scriptTag, langSysTag)
langSys = ot.LangSys() langSys.LookupOrder = None if defaultFeature: setReference( mapFeature, featureMap, defaultFeature, setattr, langSys, "ReqFeatureIndex", ) else: langSys.ReqFeatureIndex = 0xFFFF syms = stripSplitComma(features) langSys.FeatureIndex = theList = [3] * len(syms) for i, sym in enumerate(syms): setReference(mapFeature, featureMap, sym, setitem, theList, i) langSys.FeatureCount = len(langSys.FeatureIndex)
script = [s for s in records if s.ScriptTag == scriptTag] if script: script = script[0].Script else: scriptRec = ot.ScriptRecord() scriptRec.ScriptTag = scriptTag + " " * (4 - len(scriptTag)) scriptRec.Script = ot.Script() records.append(scriptRec) script = scriptRec.Script script.DefaultLangSys = None script.LangSysRecord = [] script.LangSysCount = 0
if langSysTag == "default": script.DefaultLangSys = langSys else: langSysRec = ot.LangSysRecord() langSysRec.LangSysTag = langSysTag + " " * (4 - len(langSysTag)) langSysRec.LangSys = langSys script.LangSysRecord.append(langSysRec) script.LangSysCount = len(script.LangSysRecord)
for script in records: script.Script.LangSysRecord = sorted( script.Script.LangSysRecord, key=lambda rec: rec.LangSysTag ) self.ScriptRecord = sorted(records, key=lambda rec: rec.ScriptTag) self.ScriptCount = len(self.ScriptRecord) return self
def parseFeatureList(lines, lookupMap=None, featureMap=None): self = ot.FeatureList() self.FeatureRecord = [] with lines.between("feature table"): for line in lines: name, featureTag, lookups = line if featureMap is not None: assert name not in featureMap, "Duplicate feature name: %s" % name featureMap[name] = len(self.FeatureRecord) # If feature name is integer, make sure it matches its index. try: assert int(name) == len(self.FeatureRecord), "%d %d" % ( name, len(self.FeatureRecord), ) except ValueError: pass featureRec = ot.FeatureRecord() featureRec.FeatureTag = featureTag featureRec.Feature = ot.Feature() self.FeatureRecord.append(featureRec) feature = featureRec.Feature feature.FeatureParams = None syms = stripSplitComma(lookups) feature.LookupListIndex = theList = [None] * len(syms) for i, sym in enumerate(syms): setReference(mapLookup, lookupMap, sym, setitem, theList, i) feature.LookupCount = len(feature.LookupListIndex)
self.FeatureCount = len(self.FeatureRecord) return self
def parseLookupFlags(lines): flags = 0 filterset = None allFlags = [ "righttoleft", "ignorebaseglyphs", "ignoreligatures", "ignoremarks", "markattachmenttype", "markfiltertype", ] while lines.peeks()[0].lower() in allFlags: line = next(lines) flag = { "righttoleft": 0x0001, "ignorebaseglyphs": 0x0002, "ignoreligatures": 0x0004, "ignoremarks": 0x0008, }.get(line[0].lower()) if flag: assert line[1].lower() in ["yes", "no"], line[1] if line[1].lower() == "yes": flags |= flag continue if line[0].lower() == "markattachmenttype": flags |= int(line[1]) << 8 continue if line[0].lower() == "markfiltertype": flags |= 0x10 filterset = int(line[1]) return flags, filterset
def parseSingleSubst(lines, font, _lookupMap=None): mapping = {} for line in lines: assert len(line) == 2, line line = makeGlyphs(line) mapping[line[0]] = line[1] return otl.buildSingleSubstSubtable(mapping)
def parseMultiple(lines, font, _lookupMap=None): mapping = {} for line in lines: line = makeGlyphs(line) mapping[line[0]] = line[1:] return otl.buildMultipleSubstSubtable(mapping)
def parseAlternate(lines, font, _lookupMap=None): mapping = {} for line in lines: line = makeGlyphs(line) mapping[line[0]] = line[1:] return otl.buildAlternateSubstSubtable(mapping)
def parseLigature(lines, font, _lookupMap=None): mapping = {} for line in lines: assert len(line) >= 2, line line = makeGlyphs(line) mapping[tuple(line[1:])] = line[0] return otl.buildLigatureSubstSubtable(mapping)
def parseSinglePos(lines, font, _lookupMap=None): values = {} for line in lines: assert len(line) == 3, line w = line[0].title().replace(" ", "") assert w in valueRecordFormatDict g = makeGlyph(line[1]) v = int(line[2]) if g not in values: values[g] = ValueRecord() assert not hasattr(values[g], w), (g, w) setattr(values[g], w, v) return otl.buildSinglePosSubtable(values, font.getReverseGlyphMap())
def parsePair(lines, font, _lookupMap=None): self = ot.PairPos() self.ValueFormat1 = self.ValueFormat2 = 0 typ = lines.peeks()[0].split()[0].lower() if typ in ("left", "right"): self.Format = 1 values = {} for line in lines: assert len(line) == 4, line side = line[0].split()[0].lower() assert side in ("left", "right"), side what = line[0][len(side) :].title().replace(" ", "") mask = valueRecordFormatDict[what][0] glyph1, glyph2 = makeGlyphs(line[1:3]) value = int(line[3]) if not glyph1 in values: values[glyph1] = {} if not glyph2 in values[glyph1]: values[glyph1][glyph2] = (ValueRecord(), ValueRecord()) rec2 = values[glyph1][glyph2] if side == "left": self.ValueFormat1 |= mask vr = rec2[0] else: self.ValueFormat2 |= mask vr = rec2[1] assert not hasattr(vr, what), (vr, what) setattr(vr, what, value) self.Coverage = makeCoverage(set(values.keys()), font) self.PairSet = [] for glyph1 in self.Coverage.glyphs: values1 = values[glyph1] pairset = ot.PairSet() records = pairset.PairValueRecord = [] for glyph2 in sorted(values1.keys(), key=font.getGlyphID): values2 = values1[glyph2] pair = ot.PairValueRecord() pair.SecondGlyph = glyph2 pair.Value1 = values2[0] pair.Value2 = values2[1] if self.ValueFormat2 else None records.append(pair) pairset.PairValueCount = len(pairset.PairValueRecord) self.PairSet.append(pairset) self.PairSetCount = len(self.PairSet) elif typ.endswith("class"): self.Format = 2 classDefs = [None, None] while lines.peeks()[0].endswith("class definition begin"): typ = lines.peek()[0][: -len("class definition begin")].lower() idx, klass = { "first": (0, ot.ClassDef1), "second": (1, ot.ClassDef2), }[typ] assert classDefs[idx] is None classDefs[idx] = parseClassDef(lines, font, klass=klass) self.ClassDef1, self.ClassDef2 = classDefs self.Class1Count, self.Class2Count = ( 1 + max(c.classDefs.values()) for c in classDefs ) self.Class1Record = [ot.Class1Record() for i in range(self.Class1Count)] for rec1 in self.Class1Record: rec1.Class2Record = [ot.Class2Record() for j in range(self.Class2Count)] for rec2 in rec1.Class2Record: rec2.Value1 = ValueRecord() rec2.Value2 = ValueRecord() for line in lines: assert len(line) == 4, line side = line[0].split()[0].lower() assert side in ("left", "right"), side what = line[0][len(side) :].title().replace(" ", "") mask = valueRecordFormatDict[what][0] class1, class2, value = (int(x) for x in line[1:4]) rec2 = self.Class1Record[class1].Class2Record[class2] if side == "left": self.ValueFormat1 |= mask vr = rec2.Value1 else: self.ValueFormat2 |= mask vr = rec2.Value2 assert not hasattr(vr, what), (vr, what) setattr(vr, what, value) for rec1 in self.Class1Record: for rec2 in rec1.Class2Record: rec2.Value1 = ValueRecord(self.ValueFormat1, rec2.Value1) rec2.Value2 = ( ValueRecord(self.ValueFormat2, rec2.Value2) if self.ValueFormat2 else None )
self.Coverage = makeCoverage(set(self.ClassDef1.classDefs.keys()), font) else: assert 0, typ return self
def parseKernset(lines, font, _lookupMap=None): typ = lines.peeks()[0].split()[0].lower() if typ in ("left", "right"): with lines.until( ("firstclass definition begin", "secondclass definition begin") ): return parsePair(lines, font) return parsePair(lines, font)
def makeAnchor(data, klass=ot.Anchor): assert len(data) <= 2 anchor = klass() anchor.Format = 1 anchor.XCoordinate, anchor.YCoordinate = intSplitComma(data[0]) if len(data) > 1 and data[1] != "": anchor.Format = 2 anchor.AnchorPoint = int(data[1]) return anchor
def parseCursive(lines, font, _lookupMap=None): records = {} for line in lines: assert len(line) in [3, 4], line idx, klass = { "entry": (0, ot.EntryAnchor), "exit": (1, ot.ExitAnchor), }[line[0]] glyph = makeGlyph(line[1]) if glyph not in records: records[glyph] = [None, None] assert records[glyph][idx] is None, (glyph, idx) records[glyph][idx] = makeAnchor(line[2:], klass) return otl.buildCursivePosSubtable(records, font.getReverseGlyphMap())
def makeMarkRecords(data, coverage, c): records = [] for glyph in coverage.glyphs: klass, anchor = data[glyph] record = c.MarkRecordClass() record.Class = klass setattr(record, c.MarkAnchor, anchor) records.append(record) return records
def makeBaseRecords(data, coverage, c, classCount): records = [] idx = {} for glyph in coverage.glyphs: idx[glyph] = len(records) record = c.BaseRecordClass() anchors = [None] * classCount setattr(record, c.BaseAnchor, anchors) records.append(record) for (glyph, klass), anchor in data.items(): record = records[idx[glyph]] anchors = getattr(record, c.BaseAnchor) assert anchors[klass] is None, (glyph, klass) anchors[klass] = anchor return records
def makeLigatureRecords(data, coverage, c, classCount): records = [None] * len(coverage.glyphs) idx = {g: i for i, g in enumerate(coverage.glyphs)}
for (glyph, klass, compIdx, compCount), anchor in data.items(): record = records[idx[glyph]] if record is None: record = records[idx[glyph]] = ot.LigatureAttach() record.ComponentCount = compCount record.ComponentRecord = [ot.ComponentRecord() for i in range(compCount)] for compRec in record.ComponentRecord: compRec.LigatureAnchor = [None] * classCount assert record.ComponentCount == compCount, ( glyph, record.ComponentCount, compCount, )
anchors = record.ComponentRecord[compIdx - 1].LigatureAnchor assert anchors[klass] is None, (glyph, compIdx, klass) anchors[klass] = anchor return records
def parseMarkToSomething(lines, font, c): self = c.Type() self.Format = 1 markData = {} baseData = {} Data = { "mark": (markData, c.MarkAnchorClass), "base": (baseData, c.BaseAnchorClass), "ligature": (baseData, c.BaseAnchorClass), } maxKlass = 0 for line in lines: typ = line[0] assert typ in ("mark", "base", "ligature") glyph = makeGlyph(line[1]) data, anchorClass = Data[typ] extraItems = 2 if typ == "ligature" else 0 extras = tuple(int(i) for i in line[2 : 2 + extraItems]) klass = int(line[2 + extraItems]) anchor = makeAnchor(line[3 + extraItems :], anchorClass) if typ == "mark": key, value = glyph, (klass, anchor) else: key, value = ((glyph, klass) + extras), anchor assert key not in data, key data[key] = value maxKlass = max(maxKlass, klass)
# Mark markCoverage = makeCoverage(set(markData.keys()), font, c.MarkCoverageClass) markArray = c.MarkArrayClass() markRecords = makeMarkRecords(markData, markCoverage, c) setattr(markArray, c.MarkRecord, markRecords) setattr(markArray, c.MarkCount, len(markRecords)) setattr(self, c.MarkCoverage, markCoverage) setattr(self, c.MarkArray, markArray) self.ClassCount = maxKlass + 1
# Base self.classCount = 0 if not baseData else 1 + max(k[1] for k, v in baseData.items()) baseCoverage = makeCoverage( set([k[0] for k in baseData.keys()]), font, c.BaseCoverageClass ) baseArray = c.BaseArrayClass() if c.Base == "Ligature": baseRecords = makeLigatureRecords(baseData, baseCoverage, c, self.classCount) else: baseRecords = makeBaseRecords(baseData, baseCoverage, c, self.classCount) setattr(baseArray, c.BaseRecord, baseRecords) setattr(baseArray, c.BaseCount, len(baseRecords)) setattr(self, c.BaseCoverage, baseCoverage) setattr(self, c.BaseArray, baseArray)
return self
class MarkHelper(object): def __init__(self): for Which in ("Mark", "Base"): for What in ("Coverage", "Array", "Count", "Record", "Anchor"): key = Which + What if Which == "Mark" and What in ("Count", "Record", "Anchor"): value = key else: value = getattr(self, Which) + What if value == "LigatureRecord": value = "LigatureAttach" setattr(self, key, value) if What != "Count": klass = getattr(ot, value) setattr(self, key + "Class", klass)
class MarkToBaseHelper(MarkHelper): Mark = "Mark" Base = "Base" Type = ot.MarkBasePos
class MarkToMarkHelper(MarkHelper): Mark = "Mark1" Base = "Mark2" Type = ot.MarkMarkPos
class MarkToLigatureHelper(MarkHelper): Mark = "Mark" Base = "Ligature" Type = ot.MarkLigPos
def parseMarkToBase(lines, font, _lookupMap=None): return parseMarkToSomething(lines, font, MarkToBaseHelper())
def parseMarkToMark(lines, font, _lookupMap=None): return parseMarkToSomething(lines, font, MarkToMarkHelper())
def parseMarkToLigature(lines, font, _lookupMap=None): return parseMarkToSomething(lines, font, MarkToLigatureHelper())
def stripSplitComma(line): return [s.strip() for s in line.split(",")] if line else []
def intSplitComma(line): return [int(i) for i in line.split(",")] if line else []
# Copied from fontTools.subsetclass ContextHelper(object): def __init__(self, klassName, Format): if klassName.endswith("Subst"): Typ = "Sub" Type = "Subst" else: Typ = "Pos" Type = "Pos" if klassName.startswith("Chain"): Chain = "Chain" InputIdx = 1 DataLen = 3 else: Chain = "" InputIdx = 0 DataLen = 1 ChainTyp = Chain + Typ
self.Typ = Typ self.Type = Type self.Chain = Chain self.ChainTyp = ChainTyp self.InputIdx = InputIdx self.DataLen = DataLen
self.LookupRecord = Type + "LookupRecord"
if Format == 1: Coverage = lambda r: r.Coverage ChainCoverage = lambda r: r.Coverage ContextData = lambda r: (None,) ChainContextData = lambda r: (None, None, None) SetContextData = None SetChainContextData = None RuleData = lambda r: (r.Input,) ChainRuleData = lambda r: (r.Backtrack, r.Input, r.LookAhead)
def SetRuleData(r, d): (r.Input,) = d (r.GlyphCount,) = (len(x) + 1 for x in d)
def ChainSetRuleData(r, d): (r.Backtrack, r.Input, r.LookAhead) = d ( r.BacktrackGlyphCount, r.InputGlyphCount, r.LookAheadGlyphCount, ) = (len(d[0]), len(d[1]) + 1, len(d[2]))
elif Format == 2: Coverage = lambda r: r.Coverage ChainCoverage = lambda r: r.Coverage ContextData = lambda r: (r.ClassDef,) ChainContextData = lambda r: ( r.BacktrackClassDef, r.InputClassDef, r.LookAheadClassDef, )
def SetContextData(r, d): (r.ClassDef,) = d
def SetChainContextData(r, d): (r.BacktrackClassDef, r.InputClassDef, r.LookAheadClassDef) = d
RuleData = lambda r: (r.Class,) ChainRuleData = lambda r: (r.Backtrack, r.Input, r.LookAhead)
def SetRuleData(r, d): (r.Class,) = d (r.GlyphCount,) = (len(x) + 1 for x in d)
def ChainSetRuleData(r, d): (r.Backtrack, r.Input, r.LookAhead) = d ( r.BacktrackGlyphCount, r.InputGlyphCount, r.LookAheadGlyphCount, ) = (len(d[0]), len(d[1]) + 1, len(d[2]))
elif Format == 3: Coverage = lambda r: r.Coverage[0] ChainCoverage = lambda r: r.InputCoverage[0] ContextData = None ChainContextData = None SetContextData = None SetChainContextData = None RuleData = lambda r: r.Coverage ChainRuleData = lambda r: ( r.BacktrackCoverage + r.InputCoverage + r.LookAheadCoverage )
def SetRuleData(r, d): (r.Coverage,) = d (r.GlyphCount,) = (len(x) for x in d)
def ChainSetRuleData(r, d): (r.BacktrackCoverage, r.InputCoverage, r.LookAheadCoverage) = d ( r.BacktrackGlyphCount, r.InputGlyphCount, r.LookAheadGlyphCount, ) = (len(x) for x in d)
else: assert 0, "unknown format: %s" % Format
if Chain: self.Coverage = ChainCoverage self.ContextData = ChainContextData self.SetContextData = SetChainContextData self.RuleData = ChainRuleData self.SetRuleData = ChainSetRuleData else: self.Coverage = Coverage self.ContextData = ContextData self.SetContextData = SetContextData self.RuleData = RuleData self.SetRuleData = SetRuleData
if Format == 1: self.Rule = ChainTyp + "Rule" self.RuleCount = ChainTyp + "RuleCount" self.RuleSet = ChainTyp + "RuleSet" self.RuleSetCount = ChainTyp + "RuleSetCount" self.Intersect = lambda glyphs, c, r: [r] if r in glyphs else [] elif Format == 2: self.Rule = ChainTyp + "ClassRule" self.RuleCount = ChainTyp + "ClassRuleCount" self.RuleSet = ChainTyp + "ClassSet" self.RuleSetCount = ChainTyp + "ClassSetCount" self.Intersect = lambda glyphs, c, r: ( c.intersect_class(glyphs, r) if c else (set(glyphs) if r == 0 else set()) )
self.ClassDef = "InputClassDef" if Chain else "ClassDef" self.ClassDefIndex = 1 if Chain else 0 self.Input = "Input" if Chain else "Class"
def parseLookupRecords(items, klassName, lookupMap=None): klass = getattr(ot, klassName) lst = [] for item in items: rec = klass() item = stripSplitComma(item) assert len(item) == 2, item idx = int(item[0]) assert idx > 0, idx rec.SequenceIndex = idx - 1 setReference(mapLookup, lookupMap, item[1], setattr, rec, "LookupListIndex") lst.append(rec) return lst
def makeClassDef(classDefs, font, klass=ot.Coverage): if not classDefs: return None self = klass() self.classDefs = dict(classDefs) return self
def parseClassDef(lines, font, klass=ot.ClassDef): classDefs = {} with lines.between("class definition"): for line in lines: glyph = makeGlyph(line[0]) assert glyph not in classDefs, glyph classDefs[glyph] = int(line[1]) return makeClassDef(classDefs, font, klass)
def makeCoverage(glyphs, font, klass=ot.Coverage): if not glyphs: return None if isinstance(glyphs, set): glyphs = sorted(glyphs) coverage = klass() coverage.glyphs = sorted(set(glyphs), key=font.getGlyphID) return coverage
def parseCoverage(lines, font, klass=ot.Coverage): glyphs = [] with lines.between("coverage definition"): for line in lines: glyphs.append(makeGlyph(line[0])) return makeCoverage(glyphs, font, klass)
def bucketizeRules(self, c, rules, bucketKeys): buckets = {} for seq, recs in rules: buckets.setdefault(seq[c.InputIdx][0], []).append( (tuple(s[1 if i == c.InputIdx else 0 :] for i, s in enumerate(seq)), recs) )
rulesets = [] for firstGlyph in bucketKeys: if firstGlyph not in buckets: rulesets.append(None) continue thisRules = [] for seq, recs in buckets[firstGlyph]: rule = getattr(ot, c.Rule)() c.SetRuleData(rule, seq) setattr(rule, c.Type + "Count", len(recs)) setattr(rule, c.LookupRecord, recs) thisRules.append(rule)
ruleset = getattr(ot, c.RuleSet)() setattr(ruleset, c.Rule, thisRules) setattr(ruleset, c.RuleCount, len(thisRules)) rulesets.append(ruleset)
setattr(self, c.RuleSet, rulesets) setattr(self, c.RuleSetCount, len(rulesets))
def parseContext(lines, font, Type, lookupMap=None): self = getattr(ot, Type)() typ = lines.peeks()[0].split()[0].lower() if typ == "glyph": self.Format = 1 log.debug("Parsing %s format %s", Type, self.Format) c = ContextHelper(Type, self.Format) rules = [] for line in lines: assert line[0].lower() == "glyph", line[0] while len(line) < 1 + c.DataLen: line.append("") seq = tuple(makeGlyphs(stripSplitComma(i)) for i in line[1 : 1 + c.DataLen]) recs = parseLookupRecords(line[1 + c.DataLen :], c.LookupRecord, lookupMap) rules.append((seq, recs))
firstGlyphs = set(seq[c.InputIdx][0] for seq, recs in rules) self.Coverage = makeCoverage(firstGlyphs, font) bucketizeRules(self, c, rules, self.Coverage.glyphs) elif typ.endswith("class"): self.Format = 2 log.debug("Parsing %s format %s", Type, self.Format) c = ContextHelper(Type, self.Format) classDefs = [None] * c.DataLen while lines.peeks()[0].endswith("class definition begin"): typ = lines.peek()[0][: -len("class definition begin")].lower() idx, klass = { 1: { "": (0, ot.ClassDef), }, 3: { "backtrack": (0, ot.BacktrackClassDef), "": (1, ot.InputClassDef), "lookahead": (2, ot.LookAheadClassDef), }, }[c.DataLen][typ] assert classDefs[idx] is None, idx classDefs[idx] = parseClassDef(lines, font, klass=klass) c.SetContextData(self, classDefs) rules = [] for line in lines: assert line[0].lower().startswith("class"), line[0] while len(line) < 1 + c.DataLen: line.append("") seq = tuple(intSplitComma(i) for i in line[1 : 1 + c.DataLen]) recs = parseLookupRecords(line[1 + c.DataLen :], c.LookupRecord, lookupMap) rules.append((seq, recs)) firstClasses = set(seq[c.InputIdx][0] for seq, recs in rules) firstGlyphs = set( g for g, c in classDefs[c.InputIdx].classDefs.items() if c in firstClasses ) self.Coverage = makeCoverage(firstGlyphs, font) bucketizeRules(self, c, rules, range(max(firstClasses) + 1)) elif typ.endswith("coverage"): self.Format = 3 log.debug("Parsing %s format %s", Type, self.Format) c = ContextHelper(Type, self.Format) coverages = tuple([] for i in range(c.DataLen)) while lines.peeks()[0].endswith("coverage definition begin"): typ = lines.peek()[0][: -len("coverage definition begin")].lower() idx, klass = { 1: { "": (0, ot.Coverage), }, 3: { "backtrack": (0, ot.BacktrackCoverage), "input": (1, ot.InputCoverage), "lookahead": (2, ot.LookAheadCoverage), }, }[c.DataLen][typ] coverages[idx].append(parseCoverage(lines, font, klass=klass)) c.SetRuleData(self, coverages) lines = list(lines) assert len(lines) == 1 line = lines[0] assert line[0].lower() == "coverage", line[0] recs = parseLookupRecords(line[1:], c.LookupRecord, lookupMap) setattr(self, c.Type + "Count", len(recs)) setattr(self, c.LookupRecord, recs) else: assert 0, typ return self
def parseContextSubst(lines, font, lookupMap=None): return parseContext(lines, font, "ContextSubst", lookupMap=lookupMap)
def parseContextPos(lines, font, lookupMap=None): return parseContext(lines, font, "ContextPos", lookupMap=lookupMap)
def parseChainedSubst(lines, font, lookupMap=None): return parseContext(lines, font, "ChainContextSubst", lookupMap=lookupMap)
def parseChainedPos(lines, font, lookupMap=None): return parseContext(lines, font, "ChainContextPos", lookupMap=lookupMap)
def parseReverseChainedSubst(lines, font, _lookupMap=None): self = ot.ReverseChainSingleSubst() self.Format = 1 coverages = ([], []) while lines.peeks()[0].endswith("coverage definition begin"): typ = lines.peek()[0][: -len("coverage definition begin")].lower() idx, klass = { "backtrack": (0, ot.BacktrackCoverage), "lookahead": (1, ot.LookAheadCoverage), }[typ] coverages[idx].append(parseCoverage(lines, font, klass=klass)) self.BacktrackCoverage = coverages[0] self.BacktrackGlyphCount = len(self.BacktrackCoverage) self.LookAheadCoverage = coverages[1] self.LookAheadGlyphCount = len(self.LookAheadCoverage) mapping = {} for line in lines: assert len(line) == 2, line line = makeGlyphs(line) mapping[line[0]] = line[1] self.Coverage = makeCoverage(set(mapping.keys()), font) self.Substitute = [mapping[k] for k in self.Coverage.glyphs] self.GlyphCount = len(self.Substitute) return self
def parseLookup(lines, tableTag, font, lookupMap=None): line = lines.expect("lookup") _, name, typ = line log.debug("Parsing lookup type %s %s", typ, name) lookup = ot.Lookup() lookup.LookupFlag, filterset = parseLookupFlags(lines) if filterset is not None: lookup.MarkFilteringSet = filterset lookup.LookupType, parseLookupSubTable = { "GSUB": { "single": (1, parseSingleSubst), "multiple": (2, parseMultiple), "alternate": (3, parseAlternate), "ligature": (4, parseLigature), "context": (5, parseContextSubst), "chained": (6, parseChainedSubst), "reversechained": (8, parseReverseChainedSubst), }, "GPOS": { "single": (1, parseSinglePos), "pair": (2, parsePair), "kernset": (2, parseKernset), "cursive": (3, parseCursive), "mark to base": (4, parseMarkToBase), "mark to ligature": (5, parseMarkToLigature), "mark to mark": (6, parseMarkToMark), "context": (7, parseContextPos), "chained": (8, parseChainedPos), }, }[tableTag][typ]
with lines.until("lookup end"): subtables = []
while lines.peek(): with lines.until(("% subtable", "subtable end")): while lines.peek(): subtable = parseLookupSubTable(lines, font, lookupMap) assert lookup.LookupType == subtable.LookupType subtables.append(subtable) if lines.peeks()[0] in ("% subtable", "subtable end"): next(lines) lines.expect("lookup end")
lookup.SubTable = subtables lookup.SubTableCount = len(lookup.SubTable) if lookup.SubTableCount == 0: # Remove this return when following is fixed: # https://github.com/fonttools/fonttools/issues/789 return None return lookup
def parseGSUBGPOS(lines, font, tableTag): container = ttLib.getTableClass(tableTag)() lookupMap = DeferredMapping() featureMap = DeferredMapping() assert tableTag in ("GSUB", "GPOS") log.debug("Parsing %s", tableTag) self = getattr(ot, tableTag)() self.Version = 0x00010000 fields = { "script table begin": ( "ScriptList", lambda lines: parseScriptList(lines, featureMap), ), "feature table begin": ( "FeatureList", lambda lines: parseFeatureList(lines, lookupMap, featureMap), ), "lookup": ("LookupList", None), } for attr, parser in fields.values(): setattr(self, attr, None) while lines.peek() is not None: typ = lines.peek()[0].lower() if typ not in fields: log.debug("Skipping %s", lines.peek()) next(lines) continue attr, parser = fields[typ] if typ == "lookup": if self.LookupList is None: self.LookupList = ot.LookupList() self.LookupList.Lookup = [] _, name, _ = lines.peek() lookup = parseLookup(lines, tableTag, font, lookupMap) if lookupMap is not None: assert name not in lookupMap, "Duplicate lookup name: %s" % name lookupMap[name] = len(self.LookupList.Lookup) else: assert int(name) == len(self.LookupList.Lookup), "%d %d" % ( name, len(self.Lookup), ) self.LookupList.Lookup.append(lookup) else: assert getattr(self, attr) is None, attr setattr(self, attr, parser(lines)) if self.LookupList: self.LookupList.LookupCount = len(self.LookupList.Lookup) if lookupMap is not None: lookupMap.applyDeferredMappings() if os.environ.get(LOOKUP_DEBUG_ENV_VAR): if "Debg" not in font: font["Debg"] = newTable("Debg") font["Debg"].data = {} debug = ( font["Debg"] .data.setdefault(LOOKUP_DEBUG_INFO_KEY, {}) .setdefault(tableTag, {}) ) for name, lookup in lookupMap.items(): debug[str(lookup)] = ["", name, ""]
featureMap.applyDeferredMappings() container.table = self return container
def parseGSUB(lines, font): return parseGSUBGPOS(lines, font, "GSUB")
def parseGPOS(lines, font): return parseGSUBGPOS(lines, font, "GPOS")
def parseAttachList(lines, font): points = {} with lines.between("attachment list"): for line in lines: glyph = makeGlyph(line[0]) assert glyph not in points, glyph points[glyph] = [int(i) for i in line[1:]] return otl.buildAttachList(points, font.getReverseGlyphMap())
def parseCaretList(lines, font): carets = {} with lines.between("carets"): for line in lines: glyph = makeGlyph(line[0]) assert glyph not in carets, glyph num = int(line[1]) thisCarets = [int(i) for i in line[2:]] assert num == len(thisCarets), line carets[glyph] = thisCarets return otl.buildLigCaretList(carets, {}, font.getReverseGlyphMap())
def makeMarkFilteringSets(sets, font): self = ot.MarkGlyphSetsDef() self.MarkSetTableFormat = 1 self.MarkSetCount = 1 + max(sets.keys()) self.Coverage = [None] * self.MarkSetCount for k, v in sorted(sets.items()): self.Coverage[k] = makeCoverage(set(v), font) return self
def parseMarkFilteringSets(lines, font): sets = {} with lines.between("set definition"): for line in lines: assert len(line) == 2, line glyph = makeGlyph(line[0]) # TODO accept set names st = int(line[1]) if st not in sets: sets[st] = [] sets[st].append(glyph) return makeMarkFilteringSets(sets, font)
def parseGDEF(lines, font): container = ttLib.getTableClass("GDEF")() log.debug("Parsing GDEF") self = ot.GDEF() fields = { "class definition begin": ( "GlyphClassDef", lambda lines, font: parseClassDef(lines, font, klass=ot.GlyphClassDef), ), "attachment list begin": ("AttachList", parseAttachList), "carets begin": ("LigCaretList", parseCaretList), "mark attachment class definition begin": ( "MarkAttachClassDef", lambda lines, font: parseClassDef(lines, font, klass=ot.MarkAttachClassDef), ), "markfilter set definition begin": ("MarkGlyphSetsDef", parseMarkFilteringSets), } for attr, parser in fields.values(): setattr(self, attr, None) while lines.peek() is not None: typ = lines.peek()[0].lower() if typ not in fields: log.debug("Skipping %s", typ) next(lines) continue attr, parser = fields[typ] assert getattr(self, attr) is None, attr setattr(self, attr, parser(lines, font)) self.Version = 0x00010000 if self.MarkGlyphSetsDef is None else 0x00010002 container.table = self return container
def parseCmap(lines, font): container = ttLib.getTableClass("cmap")() log.debug("Parsing cmap") tables = [] while lines.peek() is not None: lines.expect("cmap subtable %d" % len(tables)) platId, encId, fmt, lang = [ parseCmapId(lines, field) for field in ("platformID", "encodingID", "format", "language") ] table = cmap_classes[fmt](fmt) table.platformID = platId table.platEncID = encId table.language = lang table.cmap = {} line = next(lines) while line[0] != "end subtable": table.cmap[int(line[0], 16)] = line[1] line = next(lines) tables.append(table) container.tableVersion = 0 container.tables = tables return container
def parseCmapId(lines, field): line = next(lines) assert field == line[0] return int(line[1])
def parseTable(lines, font, tableTag=None): log.debug("Parsing table") line = lines.peeks() tag = None if line[0].split()[0] == "FontDame": tag = line[0].split()[1] elif " ".join(line[0].split()[:3]) == "Font Chef Table": tag = line[0].split()[3] if tag is not None: next(lines) tag = tag.ljust(4) if tableTag is None: tableTag = tag else: assert tableTag == tag, (tableTag, tag)
assert ( tableTag is not None ), "Don't know what table to parse and data doesn't specify"
return { "GSUB": parseGSUB, "GPOS": parseGPOS, "GDEF": parseGDEF, "cmap": parseCmap, }[tableTag](lines, font)
class Tokenizer(object): def __init__(self, f): # TODO BytesIO / StringIO as needed? also, figure out whether we work on bytes or unicode lines = iter(f) try: self.filename = f.name except: self.filename = None self.lines = iter(lines) self.line = "" self.lineno = 0 self.stoppers = [] self.buffer = None
def __iter__(self): return self
def _next_line(self): self.lineno += 1 line = self.line = next(self.lines) line = [s.strip() for s in line.split("\t")] if len(line) == 1 and not line[0]: del line[0] if line and not line[-1]: log.warning("trailing tab found on line %d: %s" % (self.lineno, self.line)) while line and not line[-1]: del line[-1] return line
def _next_nonempty(self): while True: line = self._next_line() # Skip comments and empty lines if line and line[0] and (line[0][0] != "%" or line[0] == "% subtable"): return line
def _next_buffered(self): if self.buffer: ret = self.buffer self.buffer = None return ret else: return self._next_nonempty()
def __next__(self): line = self._next_buffered() if line[0].lower() in self.stoppers: self.buffer = line raise StopIteration return line
def next(self): return self.__next__()
def peek(self): if not self.buffer: try: self.buffer = self._next_nonempty() except StopIteration: return None if self.buffer[0].lower() in self.stoppers: return None return self.buffer
def peeks(self): ret = self.peek() return ret if ret is not None else ("",)
@contextmanager def between(self, tag): start = tag + " begin" end = tag + " end" self.expectendswith(start) self.stoppers.append(end) yield del self.stoppers[-1] self.expect(tag + " end")
@contextmanager def until(self, tags): if type(tags) is not tuple: tags = (tags,) self.stoppers.extend(tags) yield del self.stoppers[-len(tags) :]
def expect(self, s): line = next(self) tag = line[0].lower() assert tag == s, "Expected '%s', got '%s'" % (s, tag) return line
def expectendswith(self, s): line = next(self) tag = line[0].lower() assert tag.endswith(s), "Expected '*%s', got '%s'" % (s, tag) return line
def build(f, font, tableTag=None): """Convert a Monotype font layout file to an OpenType layout object
A font object must be passed, but this may be a "dummy" font; it is only used for sorting glyph sets when making coverage tables and to hold the OpenType layout table while it is being built.
Args: f: A file object. font (TTFont): A font object. tableTag (string): If provided, asserts that the file contains data for the given OpenType table.
Returns: An object representing the table. (e.g. ``table_G_S_U_B_``) """ lines = Tokenizer(f) return parseTable(lines, font, tableTag=tableTag)
def main(args=None, font=None): """Convert a FontDame OTL file to TTX XML
Writes XML output to stdout.
Args: args: Command line arguments (``--font``, ``--table``, input files). """ import sys from fontTools import configLogger from fontTools.misc.testTools import MockFont
if args is None: args = sys.argv[1:]
# configure the library logger (for >= WARNING) configLogger() # comment this out to enable debug messages from mtiLib's logger # log.setLevel(logging.DEBUG)
import argparse
parser = argparse.ArgumentParser( "fonttools mtiLib", description=main.__doc__, )
parser.add_argument( "--font", "-f", metavar="FILE", dest="font", help="Input TTF files (used for glyph classes and sorting coverage tables)", ) parser.add_argument( "--table", "-t", metavar="TABLE", dest="tableTag", help="Table to fill (sniffed from input file if not provided)", ) parser.add_argument( "inputs", metavar="FILE", type=str, nargs="+", help="Input FontDame .txt files" )
args = parser.parse_args(args)
if font is None: if args.font: font = ttLib.TTFont(args.font) else: font = MockFont()
for f in args.inputs: log.debug("Processing %s", f) with open(f, "rt", encoding="utf-8-sig") as f: table = build(f, font, tableTag=args.tableTag) blob = table.compile(font) # Make sure it compiles decompiled = table.__class__() decompiled.decompile(blob, font) # Make sure it decompiles!
# continue from fontTools.misc import xmlWriter
tag = table.tableTag writer = xmlWriter.XMLWriter(sys.stdout) writer.begintag(tag) writer.newline() # table.toXML(writer, font) decompiled.toXML(writer, font) writer.endtag(tag) writer.newline()
if __name__ == "__main__": import sys
sys.exit(main())12345import sysfrom fontTools.mtiLib import main
if __name__ == "__main__": sys.exit(main())1"""OpenType Layout-related functionality."""1234567891011class OpenTypeLibError(Exception): def __init__(self, message, location): Exception.__init__(self, message) self.location = location
def __str__(self): message = Exception.__str__(self) if self.location: return f"{self.location}: {message}" else: return message123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596__all__ = ["maxCtxFont"]
def maxCtxFont(font): """Calculate the usMaxContext value for an entire font."""
maxCtx = 0 for tag in ("GSUB", "GPOS"): if tag not in font: continue table = font[tag].table if not table.LookupList: continue for lookup in table.LookupList.Lookup: for st in lookup.SubTable: maxCtx = maxCtxSubtable(maxCtx, tag, lookup.LookupType, st) return maxCtx
def maxCtxSubtable(maxCtx, tag, lookupType, st): """Calculate usMaxContext based on a single lookup table (and an existing max value). """
# single positioning, single / multiple substitution if (tag == "GPOS" and lookupType == 1) or ( tag == "GSUB" and lookupType in (1, 2, 3) ): maxCtx = max(maxCtx, 1)
# pair positioning elif tag == "GPOS" and lookupType == 2: maxCtx = max(maxCtx, 2)
# ligatures elif tag == "GSUB" and lookupType == 4: for ligatures in st.ligatures.values(): for ligature in ligatures: maxCtx = max(maxCtx, ligature.CompCount)
# context elif (tag == "GPOS" and lookupType == 7) or (tag == "GSUB" and lookupType == 5): maxCtx = maxCtxContextualSubtable(maxCtx, st, "Pos" if tag == "GPOS" else "Sub")
# chained context elif (tag == "GPOS" and lookupType == 8) or (tag == "GSUB" and lookupType == 6): maxCtx = maxCtxContextualSubtable( maxCtx, st, "Pos" if tag == "GPOS" else "Sub", "Chain" )
# extensions elif (tag == "GPOS" and lookupType == 9) or (tag == "GSUB" and lookupType == 7): maxCtx = maxCtxSubtable(maxCtx, tag, st.ExtensionLookupType, st.ExtSubTable)
# reverse-chained context elif tag == "GSUB" and lookupType == 8: maxCtx = maxCtxContextualRule(maxCtx, st, "Reverse")
return maxCtx
def maxCtxContextualSubtable(maxCtx, st, ruleType, chain=""): """Calculate usMaxContext based on a contextual feature subtable."""
if st.Format == 1: for ruleset in getattr(st, "%s%sRuleSet" % (chain, ruleType)): if ruleset is None: continue for rule in getattr(ruleset, "%s%sRule" % (chain, ruleType)): if rule is None: continue maxCtx = maxCtxContextualRule(maxCtx, rule, chain)
elif st.Format == 2: for ruleset in getattr(st, "%s%sClassSet" % (chain, ruleType)): if ruleset is None: continue for rule in getattr(ruleset, "%s%sClassRule" % (chain, ruleType)): if rule is None: continue maxCtx = maxCtxContextualRule(maxCtx, rule, chain)
elif st.Format == 3: maxCtx = maxCtxContextualRule(maxCtx, st, chain)
return maxCtx
def maxCtxContextualRule(maxCtx, st, chain): """Calculate usMaxContext based on a contextual feature rule."""
if not chain: return max(maxCtx, st.GlyphCount) elif chain == "Reverse": return max(maxCtx, 1 + st.LookAheadGlyphCount) return max(maxCtx, st.InputGlyphCount + st.LookAheadGlyphCount)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253from argparse import RawTextHelpFormatterfrom fontTools.otlLib.optimize.gpos import COMPRESSION_LEVEL, compactfrom fontTools.ttLib import TTFont
def main(args=None): """Optimize the layout tables of an existing font""" from argparse import ArgumentParser
from fontTools import configLogger
parser = ArgumentParser( prog="otlLib.optimize", description=main.__doc__, formatter_class=RawTextHelpFormatter, ) parser.add_argument("font") parser.add_argument( "-o", metavar="OUTPUTFILE", dest="outfile", default=None, help="output file" ) parser.add_argument( "--gpos-compression-level", help=COMPRESSION_LEVEL.help, default=COMPRESSION_LEVEL.default, choices=list(range(10)), type=int, ) logging_group = parser.add_mutually_exclusive_group(required=False) logging_group.add_argument( "-v", "--verbose", action="store_true", help="Run more verbosely." ) logging_group.add_argument( "-q", "--quiet", action="store_true", help="Turn verbosity off." ) options = parser.parse_args(args)
configLogger( level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO") )
font = TTFont(options.font) compact(font, options.gpos_compression_level) font.save(options.outfile or options.font)
if __name__ == "__main__": import sys
if len(sys.argv) > 1: sys.exit(main()) import doctest
sys.exit(doctest.testmod().failed)123456import sysfrom fontTools.otlLib.optimize import main
if __name__ == "__main__": sys.exit(main())lib/python3.12/site-packages/fontTools/__init__.pyAdded+8
lib/python3.12/site-packages/fontTools/__main__.pyAdded+35
lib/python3.12/site-packages/fontTools/afmLib.pyAdded+439
lib/python3.12/site-packages/fontTools/agl.pyAdded
lib/python3.12/site-packages/fontTools/annotations.pyAdded+30
lib/python3.12/site-packages/fontTools/colorLib/__init__.pyAdded
lib/python3.12/site-packages/fontTools/colorLib/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/colorLib/__pycache__/builder.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/colorLib/__pycache__/errors.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/colorLib/__pycache__/geometry.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/colorLib/__pycache__/table_builder.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/colorLib/__pycache__/unbuilder.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/colorLib/builder.pyAdded+664
lib/python3.12/site-packages/fontTools/colorLib/errors.pyAdded+2
lib/python3.12/site-packages/fontTools/colorLib/geometry.pyAdded+143
lib/python3.12/site-packages/fontTools/colorLib/table_builder.pyAdded+223
lib/python3.12/site-packages/fontTools/colorLib/unbuilder.pyAdded+81
lib/python3.12/site-packages/fontTools/designspaceLib/__init__.pyAdded
lib/python3.12/site-packages/fontTools/designspaceLib/__main__.pyAdded+6
lib/python3.12/site-packages/fontTools/designspaceLib/__pycache__/__main__.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/designspaceLib/__pycache__/split.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/designspaceLib/__pycache__/statNames.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/designspaceLib/__pycache__/types.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/designspaceLib/split.pyAdded+475
lib/python3.12/site-packages/fontTools/designspaceLib/statNames.pyAdded+260
lib/python3.12/site-packages/fontTools/designspaceLib/types.pyAdded+147
lib/python3.12/site-packages/fontTools/encodings/MacRoman.pyAdded+258
lib/python3.12/site-packages/fontTools/encodings/StandardEncoding.pyAdded+258
lib/python3.12/site-packages/fontTools/encodings/__init__.pyAdded+1
lib/python3.12/site-packages/fontTools/encodings/__pycache__/MacRoman.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/encodings/__pycache__/StandardEncoding.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/encodings/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/encodings/__pycache__/codecs.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/encodings/codecs.pyAdded+135
lib/python3.12/site-packages/fontTools/fontBuilder.pyAdded+1014
lib/python3.12/site-packages/fontTools/help.pyAdded+36
lib/python3.12/site-packages/fontTools/mtiLib/__init__.pyAdded+1400
lib/python3.12/site-packages/fontTools/mtiLib/__main__.pyAdded+5
lib/python3.12/site-packages/fontTools/mtiLib/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/mtiLib/__pycache__/__main__.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/otlLib/__init__.pyAdded+1
lib/python3.12/site-packages/fontTools/otlLib/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/otlLib/__pycache__/error.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/otlLib/__pycache__/maxContextCalc.cpython-312.pycAdded
lib/python3.12/site-packages/fontTools/otlLib/builder.pyAdded
lib/python3.12/site-packages/fontTools/otlLib/error.pyAdded+11
lib/python3.12/site-packages/fontTools/otlLib/maxContextCalc.pyAdded+96
lib/python3.12/site-packages/fontTools/otlLib/optimize/__init__.pyAdded+53
lib/python3.12/site-packages/fontTools/otlLib/optimize/__main__.pyAdded+6
lib/python3.12/site-packages/fontTools/otlLib/optimize/__pycache__/__init__.cpython-312.pycAdded