code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def build(self): """Build the lookup. Returns: An ``otTables.Lookup`` object representing the pair positioning lookup. """ builders = {} builder = ClassPairPosSubtableBuilder(self) for glyphclass1, value1, glyphclass2, value2 in self.pairs: if glyphclass1 is self.SUBTABLE_BREAK_: builder.addSubtableBreak() continue builder.addPair(glyphclass1, value1, glyphclass2, value2) subtables = [] if self.glyphPairs: subtables.extend(buildPairPosGlyphs(self.glyphPairs, self.glyphMap)) subtables.extend(builder.subtables()) lookup = self.buildLookup_(subtables) # Compact the lookup # This is a good moment to do it because the compaction should create # smaller subtables, which may prevent overflows from happening. # Keep reading the value from the ENV until ufo2ft switches to the config system level = self.font.cfg.get( "fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL", default=_compression_level_from_env(), ) if level != 0: log.info("Compacting GPOS...") compact_lookup(self.font, level, lookup) return lookup
Build the lookup. Returns: An ``otTables.Lookup`` object representing the pair positioning lookup.
build
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def add_pos(self, location, glyph, otValueRecord): """Add a single positioning rule. Args: location: A string or tuple representing the location in the original source which produced this lookup. glyph: A glyph name. otValueRection: A ``otTables.ValueRecord`` used to position the glyph. """ if otValueRecord is None: otValueRecord = ValueRecord() if not self.can_add(glyph, otValueRecord): otherLoc = self.locations[glyph] raise OpenTypeLibError( 'Already defined different position for glyph "%s" at %s' % (glyph, otherLoc), location, ) if otValueRecord: self.mapping[glyph] = otValueRecord self.locations[glyph] = location
Add a single positioning rule. Args: location: A string or tuple representing the location in the original source which produced this lookup. glyph: A glyph name. otValueRection: A ``otTables.ValueRecord`` used to position the glyph.
add_pos
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildSingleSubstSubtable(mapping): """Builds a single substitution (GSUB1) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.SingleSubstBuilder` instead. Args: mapping: A dictionary mapping input glyph names to output glyph names. Returns: An ``otTables.SingleSubst`` object, or ``None`` if the mapping dictionary is empty. """ if not mapping: return None self = ot.SingleSubst() self.mapping = dict(mapping) return self
Builds a single substitution (GSUB1) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.SingleSubstBuilder` instead. Args: mapping: A dictionary mapping input glyph names to output glyph names. Returns: An ``otTables.SingleSubst`` object, or ``None`` if the mapping dictionary is empty.
buildSingleSubstSubtable
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildMultipleSubstSubtable(mapping): """Builds a multiple substitution (GSUB2) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.MultipleSubstBuilder` instead. Example:: # sub uni06C0 by uni06D5.fina hamza.above # sub uni06C2 by uni06C1.fina hamza.above; subtable = buildMultipleSubstSubtable({ "uni06C0": [ "uni06D5.fina", "hamza.above"], "uni06C2": [ "uni06D1.fina", "hamza.above"] }) Args: mapping: A dictionary mapping input glyph names to a list of output glyph names. Returns: An ``otTables.MultipleSubst`` object or ``None`` if the mapping dictionary is empty. """ if not mapping: return None self = ot.MultipleSubst() self.mapping = dict(mapping) return self
Builds a multiple substitution (GSUB2) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.MultipleSubstBuilder` instead. Example:: # sub uni06C0 by uni06D5.fina hamza.above # sub uni06C2 by uni06C1.fina hamza.above; subtable = buildMultipleSubstSubtable({ "uni06C0": [ "uni06D5.fina", "hamza.above"], "uni06C2": [ "uni06D1.fina", "hamza.above"] }) Args: mapping: A dictionary mapping input glyph names to a list of output glyph names. Returns: An ``otTables.MultipleSubst`` object or ``None`` if the mapping dictionary is empty.
buildMultipleSubstSubtable
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildAlternateSubstSubtable(mapping): """Builds an alternate substitution (GSUB3) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.AlternateSubstBuilder` instead. Args: mapping: A dictionary mapping input glyph names to a list of output glyph names. Returns: An ``otTables.AlternateSubst`` object or ``None`` if the mapping dictionary is empty. """ if not mapping: return None self = ot.AlternateSubst() self.alternates = dict(mapping) return self
Builds an alternate substitution (GSUB3) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.AlternateSubstBuilder` instead. Args: mapping: A dictionary mapping input glyph names to a list of output glyph names. Returns: An ``otTables.AlternateSubst`` object or ``None`` if the mapping dictionary is empty.
buildAlternateSubstSubtable
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildLigatureSubstSubtable(mapping): """Builds a ligature substitution (GSUB4) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.LigatureSubstBuilder` instead. Example:: # sub f f i by f_f_i; # sub f i by f_i; subtable = buildLigatureSubstSubtable({ ("f", "f", "i"): "f_f_i", ("f", "i"): "f_i", }) Args: mapping: A dictionary mapping tuples of glyph names to output glyph names. Returns: An ``otTables.LigatureSubst`` object or ``None`` if the mapping dictionary is empty. """ if not mapping: return None self = ot.LigatureSubst() # The following single line can replace the rest of this function # with fontTools >= 3.1: # self.ligatures = dict(mapping) self.ligatures = {} for components in sorted(mapping.keys(), key=self._getLigatureSortKey): ligature = ot.Ligature() ligature.Component = components[1:] ligature.CompCount = len(ligature.Component) + 1 ligature.LigGlyph = mapping[components] firstGlyph = components[0] self.ligatures.setdefault(firstGlyph, []).append(ligature) return self
Builds a ligature substitution (GSUB4) subtable. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.LigatureSubstBuilder` instead. Example:: # sub f f i by f_f_i; # sub f i by f_i; subtable = buildLigatureSubstSubtable({ ("f", "f", "i"): "f_f_i", ("f", "i"): "f_i", }) Args: mapping: A dictionary mapping tuples of glyph names to output glyph names. Returns: An ``otTables.LigatureSubst`` object or ``None`` if the mapping dictionary is empty.
buildLigatureSubstSubtable
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildAnchor(x, y, point=None, deviceX=None, deviceY=None): """Builds an Anchor table. This determines the appropriate anchor format based on the passed parameters. Args: x (int): X coordinate. y (int): Y coordinate. point (int): Index of glyph contour point, if provided. deviceX (``otTables.Device``): X coordinate device table, if provided. deviceY (``otTables.Device``): Y coordinate device table, if provided. Returns: An ``otTables.Anchor`` object. """ self = ot.Anchor() self.XCoordinate, self.YCoordinate = x, y self.Format = 1 if point is not None: self.AnchorPoint = point self.Format = 2 if deviceX is not None or deviceY is not None: assert ( self.Format == 1 ), "Either point, or both of deviceX/deviceY, must be None." self.XDeviceTable = deviceX self.YDeviceTable = deviceY self.Format = 3 return self
Builds an Anchor table. This determines the appropriate anchor format based on the passed parameters. Args: x (int): X coordinate. y (int): Y coordinate. point (int): Index of glyph contour point, if provided. deviceX (``otTables.Device``): X coordinate device table, if provided. deviceY (``otTables.Device``): Y coordinate device table, if provided. Returns: An ``otTables.Anchor`` object.
buildAnchor
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildBaseArray(bases, numMarkClasses, glyphMap): """Builds a base array record. As part of building mark-to-base positioning rules, you will need to define a ``BaseArray`` record, which "defines for each base glyph an array of anchors, one for each mark class." This function builds the base array subtable. Example:: bases = {"a": {0: a3, 1: a5}, "b": {0: a4, 1: a5}} basearray = buildBaseArray(bases, 2, font.getReverseGlyphMap()) Args: bases (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being dictionaries mapping mark class ID to the appropriate ``otTables.Anchor`` object used for attaching marks of that class. numMarkClasses (int): The total number of mark classes for which anchors are defined. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.BaseArray`` object. """ self = ot.BaseArray() self.BaseRecord = [] for base in sorted(bases, key=glyphMap.__getitem__): b = bases[base] anchors = [b.get(markClass) for markClass in range(numMarkClasses)] self.BaseRecord.append(buildBaseRecord(anchors)) self.BaseCount = len(self.BaseRecord) return self
Builds a base array record. As part of building mark-to-base positioning rules, you will need to define a ``BaseArray`` record, which "defines for each base glyph an array of anchors, one for each mark class." This function builds the base array subtable. Example:: bases = {"a": {0: a3, 1: a5}, "b": {0: a4, 1: a5}} basearray = buildBaseArray(bases, 2, font.getReverseGlyphMap()) Args: bases (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being dictionaries mapping mark class ID to the appropriate ``otTables.Anchor`` object used for attaching marks of that class. numMarkClasses (int): The total number of mark classes for which anchors are defined. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.BaseArray`` object.
buildBaseArray
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildComponentRecord(anchors): """Builds a component record. As part of building mark-to-ligature positioning rules, you will need to define ``ComponentRecord`` objects, which contain "an array of offsets... to the Anchor tables that define all the attachment points used to attach marks to the component." This function builds the component record. Args: anchors: A list of ``otTables.Anchor`` objects or ``None``. Returns: A ``otTables.ComponentRecord`` object or ``None`` if no anchors are supplied. """ if not anchors: return None self = ot.ComponentRecord() self.LigatureAnchor = anchors return self
Builds a component record. As part of building mark-to-ligature positioning rules, you will need to define ``ComponentRecord`` objects, which contain "an array of offsets... to the Anchor tables that define all the attachment points used to attach marks to the component." This function builds the component record. Args: anchors: A list of ``otTables.Anchor`` objects or ``None``. Returns: A ``otTables.ComponentRecord`` object or ``None`` if no anchors are supplied.
buildComponentRecord
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildCursivePosSubtable(attach, glyphMap): """Builds a cursive positioning (GPOS3) subtable. Cursive positioning lookups are made up of a coverage table of glyphs, and a set of ``EntryExitRecord`` records containing the anchors for each glyph. This function builds the cursive positioning subtable. Example:: subtable = buildCursivePosSubtable({ "AlifIni": (None, buildAnchor(0, 50)), "BehMed": (buildAnchor(500,250), buildAnchor(0,50)), # ... }, font.getReverseGlyphMap()) Args: attach (dict): A mapping between glyph names and a tuple of two ``otTables.Anchor`` objects representing entry and exit anchors. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.CursivePos`` object, or ``None`` if the attachment dictionary was empty. """ if not attach: return None self = ot.CursivePos() self.Format = 1 self.Coverage = buildCoverage(attach.keys(), glyphMap) self.EntryExitRecord = [] for glyph in self.Coverage.glyphs: entryAnchor, exitAnchor = attach[glyph] rec = ot.EntryExitRecord() rec.EntryAnchor = entryAnchor rec.ExitAnchor = exitAnchor self.EntryExitRecord.append(rec) self.EntryExitCount = len(self.EntryExitRecord) return self
Builds a cursive positioning (GPOS3) subtable. Cursive positioning lookups are made up of a coverage table of glyphs, and a set of ``EntryExitRecord`` records containing the anchors for each glyph. This function builds the cursive positioning subtable. Example:: subtable = buildCursivePosSubtable({ "AlifIni": (None, buildAnchor(0, 50)), "BehMed": (buildAnchor(500,250), buildAnchor(0,50)), # ... }, font.getReverseGlyphMap()) Args: attach (dict): A mapping between glyph names and a tuple of two ``otTables.Anchor`` objects representing entry and exit anchors. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.CursivePos`` object, or ``None`` if the attachment dictionary was empty.
buildCursivePosSubtable
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildDevice(deltas): """Builds a Device record as part of a ValueRecord or Anchor. Device tables specify size-specific adjustments to value records and anchors to reflect changes based on the resolution of the output. For example, one could specify that an anchor's Y position should be increased by 1 pixel when displayed at 8 pixels per em. This routine builds device records. Args: deltas: A dictionary mapping pixels-per-em sizes to the delta adjustment in pixels when the font is displayed at that size. Returns: An ``otTables.Device`` object if any deltas were supplied, or ``None`` otherwise. """ if not deltas: return None self = ot.Device() keys = deltas.keys() self.StartSize = startSize = min(keys) self.EndSize = endSize = max(keys) assert 0 <= startSize <= endSize self.DeltaValue = deltaValues = [ deltas.get(size, 0) for size in range(startSize, endSize + 1) ] maxDelta = max(deltaValues) minDelta = min(deltaValues) assert minDelta > -129 and maxDelta < 128 if minDelta > -3 and maxDelta < 2: self.DeltaFormat = 1 elif minDelta > -9 and maxDelta < 8: self.DeltaFormat = 2 else: self.DeltaFormat = 3 return self
Builds a Device record as part of a ValueRecord or Anchor. Device tables specify size-specific adjustments to value records and anchors to reflect changes based on the resolution of the output. For example, one could specify that an anchor's Y position should be increased by 1 pixel when displayed at 8 pixels per em. This routine builds device records. Args: deltas: A dictionary mapping pixels-per-em sizes to the delta adjustment in pixels when the font is displayed at that size. Returns: An ``otTables.Device`` object if any deltas were supplied, or ``None`` otherwise.
buildDevice
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildLigatureArray(ligs, numMarkClasses, glyphMap): """Builds a LigatureArray subtable. As part of building a mark-to-ligature lookup, you will need to define the set of anchors (for each mark class) on each component of the ligature where marks can be attached. For example, for an Arabic divine name ligature (lam lam heh), you may want to specify mark attachment positioning for superior marks (fatha, etc.) and inferior marks (kasra, etc.) on each glyph of the ligature. This routine builds the ligature array record. Example:: buildLigatureArray({ "lam-lam-heh": [ { 0: superiorAnchor1, 1: inferiorAnchor1 }, # attach points for lam1 { 0: superiorAnchor2, 1: inferiorAnchor2 }, # attach points for lam2 { 0: superiorAnchor3, 1: inferiorAnchor3 }, # attach points for heh ] }, 2, font.getReverseGlyphMap()) Args: ligs (dict): A mapping of ligature names to an array of dictionaries: for each component glyph in the ligature, an dictionary mapping mark class IDs to anchors. numMarkClasses (int): The number of mark classes. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.LigatureArray`` object if deltas were supplied. """ self = ot.LigatureArray() self.LigatureAttach = [] for lig in sorted(ligs, key=glyphMap.__getitem__): anchors = [] for component in ligs[lig]: anchors.append([component.get(mc) for mc in range(numMarkClasses)]) self.LigatureAttach.append(buildLigatureAttach(anchors)) self.LigatureCount = len(self.LigatureAttach) return self
Builds a LigatureArray subtable. As part of building a mark-to-ligature lookup, you will need to define the set of anchors (for each mark class) on each component of the ligature where marks can be attached. For example, for an Arabic divine name ligature (lam lam heh), you may want to specify mark attachment positioning for superior marks (fatha, etc.) and inferior marks (kasra, etc.) on each glyph of the ligature. This routine builds the ligature array record. Example:: buildLigatureArray({ "lam-lam-heh": [ { 0: superiorAnchor1, 1: inferiorAnchor1 }, # attach points for lam1 { 0: superiorAnchor2, 1: inferiorAnchor2 }, # attach points for lam2 { 0: superiorAnchor3, 1: inferiorAnchor3 }, # attach points for heh ] }, 2, font.getReverseGlyphMap()) Args: ligs (dict): A mapping of ligature names to an array of dictionaries: for each component glyph in the ligature, an dictionary mapping mark class IDs to anchors. numMarkClasses (int): The number of mark classes. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.LigatureArray`` object if deltas were supplied.
buildLigatureArray
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildMarkArray(marks, glyphMap): """Builds a mark array subtable. As part of building mark-to-* positioning rules, you will need to define a MarkArray subtable, which "defines the class and the anchor point for a mark glyph." This function builds the mark array subtable. Example:: mark = { "acute": (0, buildAnchor(300,712)), # ... } markarray = buildMarkArray(marks, font.getReverseGlyphMap()) Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.MarkArray`` object. """ self = ot.MarkArray() self.MarkRecord = [] for mark in sorted(marks.keys(), key=glyphMap.__getitem__): markClass, anchor = marks[mark] markrec = buildMarkRecord(markClass, anchor) self.MarkRecord.append(markrec) self.MarkCount = len(self.MarkRecord) return self
Builds a mark array subtable. As part of building mark-to-* positioning rules, you will need to define a MarkArray subtable, which "defines the class and the anchor point for a mark glyph." This function builds the mark array subtable. Example:: mark = { "acute": (0, buildAnchor(300,712)), # ... } markarray = buildMarkArray(marks, font.getReverseGlyphMap()) Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: An ``otTables.MarkArray`` object.
buildMarkArray
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildMarkBasePosSubtable(marks, bases, glyphMap): """Build a single MarkBasePos (GPOS4) subtable. This builds a mark-to-base lookup subtable containing all of the referenced marks and bases. Example:: # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ... marks = {"acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2)} bases = {"a": {0: a3, 1: a5}, "b": {0: a4, 1: a5}} markbaseposes = [buildMarkBasePosSubtable(marks, bases, font.getReverseGlyphMap())] Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. (See :func:`buildMarkArray`.) bases (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being dictionaries mapping mark class ID to the appropriate ``otTables.Anchor`` object used for attaching marks of that class. (See :func:`buildBaseArray`.) glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A ``otTables.MarkBasePos`` object. """ self = ot.MarkBasePos() self.Format = 1 self.MarkCoverage = buildCoverage(marks, glyphMap) self.MarkArray = buildMarkArray(marks, glyphMap) self.ClassCount = max([mc for mc, _ in marks.values()]) + 1 self.BaseCoverage = buildCoverage(bases, glyphMap) self.BaseArray = buildBaseArray(bases, self.ClassCount, glyphMap) return self
Build a single MarkBasePos (GPOS4) subtable. This builds a mark-to-base lookup subtable containing all of the referenced marks and bases. Example:: # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ... marks = {"acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2)} bases = {"a": {0: a3, 1: a5}, "b": {0: a4, 1: a5}} markbaseposes = [buildMarkBasePosSubtable(marks, bases, font.getReverseGlyphMap())] Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. (See :func:`buildMarkArray`.) bases (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being dictionaries mapping mark class ID to the appropriate ``otTables.Anchor`` object used for attaching marks of that class. (See :func:`buildBaseArray`.) glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A ``otTables.MarkBasePos`` object.
buildMarkBasePosSubtable
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildMarkLigPosSubtable(marks, ligs, glyphMap): """Build a single MarkLigPos (GPOS5) subtable. This builds a mark-to-base lookup subtable containing all of the referenced marks and bases. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.MarkLigPosBuilder` instead. Example:: # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ... marks = { "acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2) } ligs = { "f_i": [ { 0: a3, 1: a5 }, # f { 0: a4, 1: a5 } # i ], # "c_t": [{...}, {...}] } markligpose = buildMarkLigPosSubtable(marks, ligs, font.getReverseGlyphMap()) Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. (See :func:`buildMarkArray`.) ligs (dict): A mapping of ligature names to an array of dictionaries: for each component glyph in the ligature, an dictionary mapping mark class IDs to anchors. (See :func:`buildLigatureArray`.) glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A ``otTables.MarkLigPos`` object. """ self = ot.MarkLigPos() self.Format = 1 self.MarkCoverage = buildCoverage(marks, glyphMap) self.MarkArray = buildMarkArray(marks, glyphMap) self.ClassCount = max([mc for mc, _ in marks.values()]) + 1 self.LigatureCoverage = buildCoverage(ligs, glyphMap) self.LigatureArray = buildLigatureArray(ligs, self.ClassCount, glyphMap) return self
Build a single MarkLigPos (GPOS5) subtable. This builds a mark-to-base lookup subtable containing all of the referenced marks and bases. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.MarkLigPosBuilder` instead. Example:: # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ... marks = { "acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2) } ligs = { "f_i": [ { 0: a3, 1: a5 }, # f { 0: a4, 1: a5 } # i ], # "c_t": [{...}, {...}] } markligpose = buildMarkLigPosSubtable(marks, ligs, font.getReverseGlyphMap()) Args: marks (dict): A dictionary mapping anchors to glyphs; the keys being glyph names, and the values being a tuple of mark class number and an ``otTables.Anchor`` object representing the mark's attachment point. (See :func:`buildMarkArray`.) ligs (dict): A mapping of ligature names to an array of dictionaries: for each component glyph in the ligature, an dictionary mapping mark class IDs to anchors. (See :func:`buildLigatureArray`.) glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A ``otTables.MarkLigPos`` object.
buildMarkLigPosSubtable
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildPairPosGlyphs(pairs, glyphMap): """Builds a list of glyph-based pair adjustment (GPOS2 format 1) subtables. This organises a list of pair positioning adjustments into subtables based on common value record formats. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder` instead. Example:: pairs = { ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ), ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ), # ... } subtables = buildPairPosGlyphs(pairs, font.getReverseGlyphMap()) Args: pairs (dict): Pair positioning data; the keys being a two-element tuple of glyphnames, and the values being a two-element tuple of ``otTables.ValueRecord`` objects. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.PairPos`` objects. """ p = {} # (formatA, formatB) --> {(glyphA, glyphB): (valA, valB)} for (glyphA, glyphB), (valA, valB) in pairs.items(): formatA = valA.getFormat() if valA is not None else 0 formatB = valB.getFormat() if valB is not None else 0 pos = p.setdefault((formatA, formatB), {}) pos[(glyphA, glyphB)] = (valA, valB) return [ buildPairPosGlyphsSubtable(pos, glyphMap, formatA, formatB) for ((formatA, formatB), pos) in sorted(p.items()) ]
Builds a list of glyph-based pair adjustment (GPOS2 format 1) subtables. This organises a list of pair positioning adjustments into subtables based on common value record formats. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder` instead. Example:: pairs = { ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ), ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ), # ... } subtables = buildPairPosGlyphs(pairs, font.getReverseGlyphMap()) Args: pairs (dict): Pair positioning data; the keys being a two-element tuple of glyphnames, and the values being a two-element tuple of ``otTables.ValueRecord`` objects. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.PairPos`` objects.
buildPairPosGlyphs
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildPairPosGlyphsSubtable(pairs, glyphMap, valueFormat1=None, valueFormat2=None): """Builds a single glyph-based pair adjustment (GPOS2 format 1) subtable. This builds a PairPos subtable from a dictionary of glyph pairs and their positioning adjustments. See also :func:`buildPairPosGlyphs`. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder` instead. Example:: pairs = { ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ), ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ), # ... } pairpos = buildPairPosGlyphsSubtable(pairs, font.getReverseGlyphMap()) Args: pairs (dict): Pair positioning data; the keys being a two-element tuple of glyphnames, and the values being a two-element tuple of ``otTables.ValueRecord`` objects. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. valueFormat1: Force the "left" value records to the given format. valueFormat2: Force the "right" value records to the given format. Returns: A ``otTables.PairPos`` object. """ self = ot.PairPos() self.Format = 1 valueFormat1 = self.ValueFormat1 = _getValueFormat(valueFormat1, pairs.values(), 0) valueFormat2 = self.ValueFormat2 = _getValueFormat(valueFormat2, pairs.values(), 1) p = {} for (glyphA, glyphB), (valA, valB) in pairs.items(): p.setdefault(glyphA, []).append((glyphB, valA, valB)) self.Coverage = buildCoverage({g for g, _ in pairs.keys()}, glyphMap) self.PairSet = [] for glyph in self.Coverage.glyphs: ps = ot.PairSet() ps.PairValueRecord = [] self.PairSet.append(ps) for glyph2, val1, val2 in sorted(p[glyph], key=lambda x: glyphMap[x[0]]): pvr = ot.PairValueRecord() pvr.SecondGlyph = glyph2 pvr.Value1 = ( ValueRecord(src=val1, valueFormat=valueFormat1) if valueFormat1 else None ) pvr.Value2 = ( ValueRecord(src=val2, valueFormat=valueFormat2) if valueFormat2 else None ) ps.PairValueRecord.append(pvr) ps.PairValueCount = len(ps.PairValueRecord) self.PairSetCount = len(self.PairSet) return self
Builds a single glyph-based pair adjustment (GPOS2 format 1) subtable. This builds a PairPos subtable from a dictionary of glyph pairs and their positioning adjustments. See also :func:`buildPairPosGlyphs`. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder` instead. Example:: pairs = { ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ), ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ), # ... } pairpos = buildPairPosGlyphsSubtable(pairs, font.getReverseGlyphMap()) Args: pairs (dict): Pair positioning data; the keys being a two-element tuple of glyphnames, and the values being a two-element tuple of ``otTables.ValueRecord`` objects. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. valueFormat1: Force the "left" value records to the given format. valueFormat2: Force the "right" value records to the given format. Returns: A ``otTables.PairPos`` object.
buildPairPosGlyphsSubtable
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildSinglePos(mapping, glyphMap): """Builds a list of single adjustment (GPOS1) subtables. This builds a list of SinglePos subtables from a dictionary of glyph names and their positioning adjustments. The format of the subtables are determined to optimize the size of the resulting subtables. See also :func:`buildSinglePosSubtable`. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.SinglePosBuilder` instead. Example:: mapping = { "V": buildValue({ "xAdvance" : +5 }), # ... } subtables = buildSinglePos(pairs, font.getReverseGlyphMap()) Args: mapping (dict): A mapping between glyphnames and ``otTables.ValueRecord`` objects. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.SinglePos`` objects. """ result, handled = [], set() # In SinglePos format 1, the covered glyphs all share the same ValueRecord. # In format 2, each glyph has its own ValueRecord, but these records # all have the same properties (eg., all have an X but no Y placement). coverages, masks, values = {}, {}, {} for glyph, value in mapping.items(): key = _getSinglePosValueKey(value) coverages.setdefault(key, []).append(glyph) masks.setdefault(key[0], []).append(key) values[key] = value # If a ValueRecord is shared between multiple glyphs, we generate # a SinglePos format 1 subtable; that is the most compact form. for key, glyphs in coverages.items(): # 5 ushorts is the length of introducing another sublookup if len(glyphs) * _getSinglePosValueSize(key) > 5: format1Mapping = {g: values[key] for g in glyphs} result.append(buildSinglePosSubtable(format1Mapping, glyphMap)) handled.add(key) # In the remaining ValueRecords, look for those whose valueFormat # (the set of used properties) is shared between multiple records. # These will get encoded in format 2. for valueFormat, keys in masks.items(): f2 = [k for k in keys if k not in handled] if len(f2) > 1: format2Mapping = {} for k in f2: format2Mapping.update((g, values[k]) for g in coverages[k]) result.append(buildSinglePosSubtable(format2Mapping, glyphMap)) handled.update(f2) # The remaining ValueRecords are only used by a few glyphs, normally # one. We encode these in format 1 again. for key, glyphs in coverages.items(): if key not in handled: for g in glyphs: st = buildSinglePosSubtable({g: values[key]}, glyphMap) result.append(st) # When the OpenType layout engine traverses the subtables, it will # stop after the first matching subtable. Therefore, we sort the # resulting subtables by decreasing coverage size; this increases # the chance that the layout engine can do an early exit. (Of course, # this would only be true if all glyphs were equally frequent, which # is not really the case; but we do not know their distribution). # If two subtables cover the same number of glyphs, we sort them # by glyph ID so that our output is deterministic. result.sort(key=lambda t: _getSinglePosTableKey(t, glyphMap)) return result
Builds a list of single adjustment (GPOS1) subtables. This builds a list of SinglePos subtables from a dictionary of glyph names and their positioning adjustments. The format of the subtables are determined to optimize the size of the resulting subtables. See also :func:`buildSinglePosSubtable`. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.SinglePosBuilder` instead. Example:: mapping = { "V": buildValue({ "xAdvance" : +5 }), # ... } subtables = buildSinglePos(pairs, font.getReverseGlyphMap()) Args: mapping (dict): A mapping between glyphnames and ``otTables.ValueRecord`` objects. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A list of ``otTables.SinglePos`` objects.
buildSinglePos
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildSinglePosSubtable(values, glyphMap): """Builds a single adjustment (GPOS1) subtable. This builds a list of SinglePos subtables from a dictionary of glyph names and their positioning adjustments. The format of the subtable is determined to optimize the size of the output. See also :func:`buildSinglePos`. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.SinglePosBuilder` instead. Example:: mapping = { "V": buildValue({ "xAdvance" : +5 }), # ... } subtable = buildSinglePos(pairs, font.getReverseGlyphMap()) Args: mapping (dict): A mapping between glyphnames and ``otTables.ValueRecord`` objects. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A ``otTables.SinglePos`` object. """ self = ot.SinglePos() self.Coverage = buildCoverage(values.keys(), glyphMap) valueFormat = self.ValueFormat = reduce( int.__or__, [v.getFormat() for v in values.values()], 0 ) valueRecords = [ ValueRecord(src=values[g], valueFormat=valueFormat) for g in self.Coverage.glyphs ] if all(v == valueRecords[0] for v in valueRecords): self.Format = 1 if self.ValueFormat != 0: self.Value = valueRecords[0] else: self.Value = None else: self.Format = 2 self.Value = valueRecords self.ValueCount = len(self.Value) return self
Builds a single adjustment (GPOS1) subtable. This builds a list of SinglePos subtables from a dictionary of glyph names and their positioning adjustments. The format of the subtable is determined to optimize the size of the output. See also :func:`buildSinglePos`. Note that if you are implementing a layout compiler, you may find it more flexible to use :py:class:`fontTools.otlLib.lookupBuilders.SinglePosBuilder` instead. Example:: mapping = { "V": buildValue({ "xAdvance" : +5 }), # ... } subtable = buildSinglePos(pairs, font.getReverseGlyphMap()) Args: mapping (dict): A mapping between glyphnames and ``otTables.ValueRecord`` objects. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A ``otTables.SinglePos`` object.
buildSinglePosSubtable
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildValue(value): """Builds a positioning value record. Value records are used to specify coordinates and adjustments for positioning and attaching glyphs. Many of the positioning functions in this library take ``otTables.ValueRecord`` objects as arguments. This function builds value records from dictionaries. Args: value (dict): A dictionary with zero or more of the following keys: - ``xPlacement`` - ``yPlacement`` - ``xAdvance`` - ``yAdvance`` - ``xPlaDevice`` - ``yPlaDevice`` - ``xAdvDevice`` - ``yAdvDevice`` Returns: An ``otTables.ValueRecord`` object. """ self = ValueRecord() for k, v in value.items(): setattr(self, k, v) return self
Builds a positioning value record. Value records are used to specify coordinates and adjustments for positioning and attaching glyphs. Many of the positioning functions in this library take ``otTables.ValueRecord`` objects as arguments. This function builds value records from dictionaries. Args: value (dict): A dictionary with zero or more of the following keys: - ``xPlacement`` - ``yPlacement`` - ``xAdvance`` - ``yAdvance`` - ``xPlaDevice`` - ``yPlaDevice`` - ``xAdvDevice`` - ``yAdvDevice`` Returns: An ``otTables.ValueRecord`` object.
buildValue
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildAttachList(attachPoints, glyphMap): """Builds an AttachList subtable. A GDEF table may contain an Attachment Point List table (AttachList) which stores the contour indices of attachment points for glyphs with attachment points. This routine builds AttachList subtables. Args: attachPoints (dict): A mapping between glyph names and a list of contour indices. Returns: An ``otTables.AttachList`` object if attachment points are supplied, or ``None`` otherwise. """ if not attachPoints: return None self = ot.AttachList() self.Coverage = buildCoverage(attachPoints.keys(), glyphMap) self.AttachPoint = [buildAttachPoint(attachPoints[g]) for g in self.Coverage.glyphs] self.GlyphCount = len(self.AttachPoint) return self
Builds an AttachList subtable. A GDEF table may contain an Attachment Point List table (AttachList) which stores the contour indices of attachment points for glyphs with attachment points. This routine builds AttachList subtables. Args: attachPoints (dict): A mapping between glyph names and a list of contour indices. Returns: An ``otTables.AttachList`` object if attachment points are supplied, or ``None`` otherwise.
buildAttachList
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildLigCaretList(coords, points, glyphMap): """Builds a ligature caret list table. Ligatures appear as a single glyph representing multiple characters; however when, for example, editing text containing a ``f_i`` ligature, the user may want to place the cursor between the ``f`` and the ``i``. The ligature caret list in the GDEF table specifies the position to display the "caret" (the character insertion indicator, typically a flashing vertical bar) "inside" the ligature to represent an insertion point. The insertion positions may be specified either by coordinate or by contour point. Example:: coords = { "f_f_i": [300, 600] # f|fi cursor at 300 units, ff|i cursor at 600. } points = { "c_t": [28] # c|t cursor appears at coordinate of contour point 28. } ligcaretlist = buildLigCaretList(coords, points, font.getReverseGlyphMap()) Args: coords: A mapping between glyph names and a list of coordinates for the insertion point of each ligature component after the first one. points: A mapping between glyph names and a list of contour points for the insertion point of each ligature component after the first one. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A ``otTables.LigCaretList`` object if any carets are present, or ``None`` otherwise.""" glyphs = set(coords.keys()) if coords else set() if points: glyphs.update(points.keys()) carets = {g: buildLigGlyph(coords.get(g), points.get(g)) for g in glyphs} carets = {g: c for g, c in carets.items() if c is not None} if not carets: return None self = ot.LigCaretList() self.Coverage = buildCoverage(carets.keys(), glyphMap) self.LigGlyph = [carets[g] for g in self.Coverage.glyphs] self.LigGlyphCount = len(self.LigGlyph) return self
Builds a ligature caret list table. Ligatures appear as a single glyph representing multiple characters; however when, for example, editing text containing a ``f_i`` ligature, the user may want to place the cursor between the ``f`` and the ``i``. The ligature caret list in the GDEF table specifies the position to display the "caret" (the character insertion indicator, typically a flashing vertical bar) "inside" the ligature to represent an insertion point. The insertion positions may be specified either by coordinate or by contour point. Example:: coords = { "f_f_i": [300, 600] # f|fi cursor at 300 units, ff|i cursor at 600. } points = { "c_t": [28] # c|t cursor appears at coordinate of contour point 28. } ligcaretlist = buildLigCaretList(coords, points, font.getReverseGlyphMap()) Args: coords: A mapping between glyph names and a list of coordinates for the insertion point of each ligature component after the first one. points: A mapping between glyph names and a list of contour points for the insertion point of each ligature component after the first one. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns: A ``otTables.LigCaretList`` object if any carets are present, or ``None`` otherwise.
buildLigCaretList
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
def buildMarkGlyphSetsDef(markSets, glyphMap): """Builds a mark glyph sets definition table. OpenType Layout lookups may choose to use mark filtering sets to consider or ignore particular combinations of marks. These sets are specified by setting a flag on the lookup, but the mark filtering sets are defined in the ``GDEF`` table. This routine builds the subtable containing the mark glyph set definitions. Example:: set0 = set("acute", "grave") set1 = set("caron", "grave") markglyphsets = buildMarkGlyphSetsDef([set0, set1], font.getReverseGlyphMap()) Args: markSets: A list of sets of glyphnames. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns An ``otTables.MarkGlyphSetsDef`` object. """ if not markSets: return None self = ot.MarkGlyphSetsDef() self.MarkSetTableFormat = 1 self.Coverage = [buildCoverage(m, glyphMap) for m in markSets] self.MarkSetCount = len(self.Coverage) return self
Builds a mark glyph sets definition table. OpenType Layout lookups may choose to use mark filtering sets to consider or ignore particular combinations of marks. These sets are specified by setting a flag on the lookup, but the mark filtering sets are defined in the ``GDEF`` table. This routine builds the subtable containing the mark glyph set definitions. Example:: set0 = set("acute", "grave") set1 = set("caron", "grave") markglyphsets = buildMarkGlyphSetsDef([set0, set1], font.getReverseGlyphMap()) Args: markSets: A list of sets of glyphnames. glyphMap: a glyph name to ID map, typically returned from ``font.getReverseGlyphMap()``. Returns An ``otTables.MarkGlyphSetsDef`` object.
buildMarkGlyphSetsDef
python
fonttools/fonttools
Lib/fontTools/otlLib/builder.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py
MIT
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
Calculate the usMaxContext value for an entire font.
maxCtxFont
python
fonttools/fonttools
Lib/fontTools/otlLib/maxContextCalc.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/maxContextCalc.py
MIT
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
Calculate usMaxContext based on a single lookup table (and an existing max value).
maxCtxSubtable
python
fonttools/fonttools
Lib/fontTools/otlLib/maxContextCalc.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/maxContextCalc.py
MIT
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
Calculate usMaxContext based on a contextual feature subtable.
maxCtxContextualSubtable
python
fonttools/fonttools
Lib/fontTools/otlLib/maxContextCalc.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/maxContextCalc.py
MIT
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)
Calculate usMaxContext based on a contextual feature rule.
maxCtxContextualRule
python
fonttools/fonttools
Lib/fontTools/otlLib/maxContextCalc.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/maxContextCalc.py
MIT
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)
Optimize the layout tables of an existing font
main
python
fonttools/fonttools
Lib/fontTools/otlLib/optimize/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/optimize/__init__.py
MIT
def addComponent( self, glyphName: str, transformation: Tuple[float, float, float, float, float, float], ) -> None: """Add a sub glyph. The 'transformation' argument must be a 6-tuple containing an affine transformation, or a Transform object from the fontTools.misc.transform module. More precisely: it should be a sequence containing 6 numbers. """ raise NotImplementedError
Add a sub glyph. The 'transformation' argument must be a 6-tuple containing an affine transformation, or a Transform object from the fontTools.misc.transform module. More precisely: it should be a sequence containing 6 numbers.
addComponent
python
fonttools/fonttools
Lib/fontTools/pens/basePen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py
MIT
def addVarComponent( self, glyphName: str, transformation: DecomposedTransform, location: Dict[str, float], ) -> None: """Add a VarComponent sub glyph. The 'transformation' argument must be a DecomposedTransform from the fontTools.misc.transform module, and the 'location' argument must be a dictionary mapping axis tags to their locations. """ # GlyphSet decomposes for us raise AttributeError
Add a VarComponent sub glyph. The 'transformation' argument must be a DecomposedTransform from the fontTools.misc.transform module, and the 'location' argument must be a dictionary mapping axis tags to their locations.
addVarComponent
python
fonttools/fonttools
Lib/fontTools/pens/basePen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py
MIT
def __init__( self, glyphSet, *args, skipMissingComponents=None, reverseFlipped=False, **kwargs, ): """Takes a 'glyphSet' argument (dict), in which the glyphs that are referenced as components are looked up by their name. If the optional 'reverseFlipped' argument is True, components whose transformation matrix has a negative determinant will be decomposed with a reversed path direction to compensate for the flip. The optional 'skipMissingComponents' argument can be set to True/False to override the homonymous class attribute for a given pen instance. """ super(DecomposingPen, self).__init__(*args, **kwargs) self.glyphSet = glyphSet self.skipMissingComponents = ( self.__class__.skipMissingComponents if skipMissingComponents is None else skipMissingComponents ) self.reverseFlipped = reverseFlipped
Takes a 'glyphSet' argument (dict), in which the glyphs that are referenced as components are looked up by their name. If the optional 'reverseFlipped' argument is True, components whose transformation matrix has a negative determinant will be decomposed with a reversed path direction to compensate for the flip. The optional 'skipMissingComponents' argument can be set to True/False to override the homonymous class attribute for a given pen instance.
__init__
python
fonttools/fonttools
Lib/fontTools/pens/basePen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py
MIT
def addComponent(self, glyphName, transformation): """Transform the points of the base glyph and draw it onto self.""" from fontTools.pens.transformPen import TransformPen try: glyph = self.glyphSet[glyphName] except KeyError: if not self.skipMissingComponents: raise MissingComponentError(glyphName) self.log.warning("glyph '%s' is missing from glyphSet; skipped" % glyphName) else: pen = self if transformation != Identity: pen = TransformPen(pen, transformation) if self.reverseFlipped: # if the transformation has a negative determinant, it will # reverse the contour direction of the component a, b, c, d = transformation[:4] det = a * d - b * c if det < 0: from fontTools.pens.reverseContourPen import ReverseContourPen pen = ReverseContourPen(pen) glyph.draw(pen)
Transform the points of the base glyph and draw it onto self.
addComponent
python
fonttools/fonttools
Lib/fontTools/pens/basePen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py
MIT
def _qCurveToOne(self, pt1, pt2): """This method implements the basic quadratic curve type. The default implementation delegates the work to the cubic curve function. Optionally override with a native implementation. """ pt0x, pt0y = self.__currentPoint pt1x, pt1y = pt1 pt2x, pt2y = pt2 mid1x = pt0x + 0.66666666666666667 * (pt1x - pt0x) mid1y = pt0y + 0.66666666666666667 * (pt1y - pt0y) mid2x = pt2x + 0.66666666666666667 * (pt1x - pt2x) mid2y = pt2y + 0.66666666666666667 * (pt1y - pt2y) self._curveToOne((mid1x, mid1y), (mid2x, mid2y), pt2)
This method implements the basic quadratic curve type. The default implementation delegates the work to the cubic curve function. Optionally override with a native implementation.
_qCurveToOne
python
fonttools/fonttools
Lib/fontTools/pens/basePen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py
MIT
def decomposeSuperBezierSegment(points): """Split the SuperBezier described by 'points' into a list of regular bezier segments. The 'points' argument must be a sequence with length 3 or greater, containing (x, y) coordinates. The last point is the destination on-curve point, the rest of the points are off-curve points. The start point should not be supplied. This function returns a list of (pt1, pt2, pt3) tuples, which each specify a regular curveto-style bezier segment. """ n = len(points) - 1 assert n > 1 bezierSegments = [] pt1, pt2, pt3 = points[0], None, None for i in range(2, n + 1): # calculate points in between control points. nDivisions = min(i, 3, n - i + 2) for j in range(1, nDivisions): factor = j / nDivisions temp1 = points[i - 1] temp2 = points[i - 2] temp = ( temp2[0] + factor * (temp1[0] - temp2[0]), temp2[1] + factor * (temp1[1] - temp2[1]), ) if pt2 is None: pt2 = temp else: pt3 = (0.5 * (pt2[0] + temp[0]), 0.5 * (pt2[1] + temp[1])) bezierSegments.append((pt1, pt2, pt3)) pt1, pt2, pt3 = temp, None, None bezierSegments.append((pt1, points[-2], points[-1])) return bezierSegments
Split the SuperBezier described by 'points' into a list of regular bezier segments. The 'points' argument must be a sequence with length 3 or greater, containing (x, y) coordinates. The last point is the destination on-curve point, the rest of the points are off-curve points. The start point should not be supplied. This function returns a list of (pt1, pt2, pt3) tuples, which each specify a regular curveto-style bezier segment.
decomposeSuperBezierSegment
python
fonttools/fonttools
Lib/fontTools/pens/basePen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py
MIT
def decomposeQuadraticSegment(points): """Split the quadratic curve segment described by 'points' into a list of "atomic" quadratic segments. The 'points' argument must be a sequence with length 2 or greater, containing (x, y) coordinates. The last point is the destination on-curve point, the rest of the points are off-curve points. The start point should not be supplied. This function returns a list of (pt1, pt2) tuples, which each specify a plain quadratic bezier segment. """ n = len(points) - 1 assert n > 0 quadSegments = [] for i in range(n - 1): x, y = points[i] nx, ny = points[i + 1] impliedPt = (0.5 * (x + nx), 0.5 * (y + ny)) quadSegments.append((points[i], impliedPt)) quadSegments.append((points[-2], points[-1])) return quadSegments
Split the quadratic curve segment described by 'points' into a list of "atomic" quadratic segments. The 'points' argument must be a sequence with length 2 or greater, containing (x, y) coordinates. The last point is the destination on-curve point, the rest of the points are off-curve points. The start point should not be supplied. This function returns a list of (pt1, pt2) tuples, which each specify a plain quadratic bezier segment.
decomposeQuadraticSegment
python
fonttools/fonttools
Lib/fontTools/pens/basePen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py
MIT
def outline(self, transform=None, evenOdd=False): """Converts the current contours to ``FT_Outline``. Args: transform: An optional 6-tuple containing an affine transformation, or a ``Transform`` object from the ``fontTools.misc.transform`` module. evenOdd: Pass ``True`` for even-odd fill instead of non-zero. """ transform = transform or Transform() if not hasattr(transform, "transformPoint"): transform = Transform(*transform) n_contours = len(self.contours) n_points = sum((len(contour.points) for contour in self.contours)) points = [] for contour in self.contours: for point in contour.points: point = transform.transformPoint(point) points.append( FT_Vector( FT_Pos(otRound(point[0] * 64)), FT_Pos(otRound(point[1] * 64)) ) ) tags = [] for contour in self.contours: for tag in contour.tags: tags.append(tag) contours = [] contours_sum = 0 for contour in self.contours: contours_sum += len(contour.points) contours.append(contours_sum - 1) flags = FT_OUTLINE_EVEN_ODD_FILL if evenOdd else FT_OUTLINE_NONE return FT_Outline( (ctypes.c_short)(n_contours), (ctypes.c_short)(n_points), (FT_Vector * n_points)(*points), (ctypes.c_ubyte * n_points)(*tags), (ctypes.c_short * n_contours)(*contours), (ctypes.c_int)(flags), )
Converts the current contours to ``FT_Outline``. Args: transform: An optional 6-tuple containing an affine transformation, or a ``Transform`` object from the ``fontTools.misc.transform`` module. evenOdd: Pass ``True`` for even-odd fill instead of non-zero.
outline
python
fonttools/fonttools
Lib/fontTools/pens/freetypePen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/freetypePen.py
MIT
def bbox(self): """Computes the exact bounding box of an outline. Returns: A tuple of ``(xMin, yMin, xMax, yMax)``. """ bbox = FT_BBox() outline = self.outline() FT_Outline_Get_BBox(ctypes.byref(outline), ctypes.byref(bbox)) return (bbox.xMin / 64.0, bbox.yMin / 64.0, bbox.xMax / 64.0, bbox.yMax / 64.0)
Computes the exact bounding box of an outline. Returns: A tuple of ``(xMin, yMin, xMax, yMax)``.
bbox
python
fonttools/fonttools
Lib/fontTools/pens/freetypePen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/freetypePen.py
MIT
def setTestPoint(self, testPoint, evenOdd=False): """Set the point to test. Call this _before_ the outline gets drawn.""" self.testPoint = testPoint self.evenOdd = evenOdd self.firstPoint = None self.intersectionCount = 0
Set the point to test. Call this _before_ the outline gets drawn.
setTestPoint
python
fonttools/fonttools
Lib/fontTools/pens/pointInsidePen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/pointInsidePen.py
MIT
def getResult(self): """After the shape has been drawn, getResult() returns True if the test point lies within the (black) shape, and False if it doesn't. """ winding = self.getWinding() if self.evenOdd: result = winding % 2 else: # non-zero result = self.intersectionCount != 0 return not not result
After the shape has been drawn, getResult() returns True if the test point lies within the (black) shape, and False if it doesn't.
getResult
python
fonttools/fonttools
Lib/fontTools/pens/pointInsidePen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/pointInsidePen.py
MIT
def addPoint( self, pt: Tuple[float, float], segmentType: Optional[str] = None, smooth: bool = False, name: Optional[str] = None, identifier: Optional[str] = None, **kwargs: Any, ) -> None: """Add a point to the current sub path.""" raise NotImplementedError
Add a point to the current sub path.
addPoint
python
fonttools/fonttools
Lib/fontTools/pens/pointPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/pointPen.py
MIT
def addVarComponent( self, glyphName: str, transformation: DecomposedTransform, location: Dict[str, float], identifier: Optional[str] = None, **kwargs: Any, ) -> None: """Add a VarComponent sub glyph. The 'transformation' argument must be a DecomposedTransform from the fontTools.misc.transform module, and the 'location' argument must be a dictionary mapping axis tags to their locations. """ # ttGlyphSet decomposes for us raise AttributeError
Add a VarComponent sub glyph. The 'transformation' argument must be a DecomposedTransform from the fontTools.misc.transform module, and the 'location' argument must be a dictionary mapping axis tags to their locations.
addVarComponent
python
fonttools/fonttools
Lib/fontTools/pens/pointPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/pointPen.py
MIT
def __init__( self, glyphSet, *args, skipMissingComponents=None, reverseFlipped=False, **kwargs, ): """Takes a 'glyphSet' argument (dict), in which the glyphs that are referenced as components are looked up by their name. If the optional 'reverseFlipped' argument is True, components whose transformation matrix has a negative determinant will be decomposed with a reversed path direction to compensate for the flip. The optional 'skipMissingComponents' argument can be set to True/False to override the homonymous class attribute for a given pen instance. """ super().__init__(*args, **kwargs) self.glyphSet = glyphSet self.skipMissingComponents = ( self.__class__.skipMissingComponents if skipMissingComponents is None else skipMissingComponents ) self.reverseFlipped = reverseFlipped
Takes a 'glyphSet' argument (dict), in which the glyphs that are referenced as components are looked up by their name. If the optional 'reverseFlipped' argument is True, components whose transformation matrix has a negative determinant will be decomposed with a reversed path direction to compensate for the flip. The optional 'skipMissingComponents' argument can be set to True/False to override the homonymous class attribute for a given pen instance.
__init__
python
fonttools/fonttools
Lib/fontTools/pens/pointPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/pointPen.py
MIT
def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs): """Transform the points of the base glyph and draw it onto self. The `identifier` parameter and any extra kwargs are ignored. """ from fontTools.pens.transformPen import TransformPointPen try: glyph = self.glyphSet[baseGlyphName] except KeyError: if not self.skipMissingComponents: raise MissingComponentError(baseGlyphName) self.log.warning( "glyph '%s' is missing from glyphSet; skipped" % baseGlyphName ) else: pen = self if transformation != Identity: pen = TransformPointPen(pen, transformation) if self.reverseFlipped: # if the transformation has a negative determinant, it will # reverse the contour direction of the component a, b, c, d = transformation[:4] if a * d - b * c < 0: pen = ReverseContourPointPen(pen) glyph.drawPoints(pen)
Transform the points of the base glyph and draw it onto self. The `identifier` parameter and any extra kwargs are ignored.
addComponent
python
fonttools/fonttools
Lib/fontTools/pens/pointPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/pointPen.py
MIT
def lerpRecordings(recording1, recording2, factor=0.5): """Linearly interpolate between two recordings. The recordings must be decomposed, i.e. they must not contain any components. Factor is typically between 0 and 1. 0 means the first recording, 1 means the second recording, and 0.5 means the average of the two recordings. Other values are possible, and can be useful to extrapolate. Defaults to 0.5. Returns a generator with the new recording. """ if len(recording1) != len(recording2): raise ValueError( "Mismatched lengths: %d and %d" % (len(recording1), len(recording2)) ) for (op1, args1), (op2, args2) in zip(recording1, recording2): if op1 != op2: raise ValueError("Mismatched operations: %s, %s" % (op1, op2)) if op1 == "addComponent": raise ValueError("Cannot interpolate components") else: mid_args = [ (x1 + (x2 - x1) * factor, y1 + (y2 - y1) * factor) for (x1, y1), (x2, y2) in zip(args1, args2) ] yield (op1, mid_args)
Linearly interpolate between two recordings. The recordings must be decomposed, i.e. they must not contain any components. Factor is typically between 0 and 1. 0 means the first recording, 1 means the second recording, and 0.5 means the average of the two recordings. Other values are possible, and can be useful to extrapolate. Defaults to 0.5. Returns a generator with the new recording.
lerpRecordings
python
fonttools/fonttools
Lib/fontTools/pens/recordingPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/recordingPen.py
MIT
def reversedContour(contour, outputImpliedClosingLine=False): """Generator that takes a list of pen's (operator, operands) tuples, and yields them with the winding direction reversed. """ if not contour: return # nothing to do, stop iteration # valid contours must have at least a starting and ending command, # can't have one without the other assert len(contour) > 1, "invalid contour" # the type of the last command determines if the contour is closed contourType = contour.pop()[0] assert contourType in ("endPath", "closePath") closed = contourType == "closePath" firstType, firstPts = contour.pop(0) assert firstType in ("moveTo", "qCurveTo"), ( "invalid initial segment type: %r" % firstType ) firstOnCurve = firstPts[-1] if firstType == "qCurveTo": # special case for TrueType paths contaning only off-curve points assert firstOnCurve is None, "off-curve only paths must end with 'None'" assert not contour, "only one qCurveTo allowed per off-curve path" firstPts = (firstPts[0],) + tuple(reversed(firstPts[1:-1])) + (None,) if not contour: # contour contains only one segment, nothing to reverse if firstType == "moveTo": closed = False # single-point paths can't be closed else: closed = True # off-curve paths are closed by definition yield firstType, firstPts else: lastType, lastPts = contour[-1] lastOnCurve = lastPts[-1] if closed: # for closed paths, we keep the starting point yield firstType, firstPts if firstOnCurve != lastOnCurve: # emit an implied line between the last and first points yield "lineTo", (lastOnCurve,) contour[-1] = (lastType, tuple(lastPts[:-1]) + (firstOnCurve,)) if len(contour) > 1: secondType, secondPts = contour[0] else: # contour has only two points, the second and last are the same secondType, secondPts = lastType, lastPts if not outputImpliedClosingLine: # if a lineTo follows the initial moveTo, after reversing it # will be implied by the closePath, so we don't emit one; # unless the lineTo and moveTo overlap, in which case we keep the # duplicate points if secondType == "lineTo" and firstPts != secondPts: del contour[0] if contour: contour[-1] = (lastType, tuple(lastPts[:-1]) + secondPts) else: # for open paths, the last point will become the first yield firstType, (lastOnCurve,) contour[-1] = (lastType, tuple(lastPts[:-1]) + (firstOnCurve,)) # we iterate over all segment pairs in reverse order, and yield # each one with the off-curve points reversed (if any), and # with the on-curve point of the following segment for (curType, curPts), (_, nextPts) in pairwise(contour, reverse=True): yield curType, tuple(reversed(curPts[:-1])) + (nextPts[-1],) yield "closePath" if closed else "endPath", ()
Generator that takes a list of pen's (operator, operands) tuples, and yields them with the winding direction reversed.
reversedContour
python
fonttools/fonttools
Lib/fontTools/pens/reverseContourPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/reverseContourPen.py
MIT
def main(args): """Report font glyph shape geometricsl statistics""" if args is None: import sys args = sys.argv[1:] import argparse parser = argparse.ArgumentParser( "fonttools pens.statisticsPen", description="Report font glyph shape geometricsl statistics", ) parser.add_argument("font", metavar="font.ttf", help="Font file.") parser.add_argument("glyphs", metavar="glyph-name", help="Glyph names.", nargs="*") parser.add_argument( "-y", metavar="<number>", help="Face index into a collection to open. Zero based.", ) parser.add_argument( "-c", "--control", action="store_true", help="Use the control-box pen instead of the Green therem.", ) parser.add_argument( "-q", "--quiet", action="store_true", help="Only report font-wide statistics." ) parser.add_argument( "--variations", metavar="AXIS=LOC", default="", help="List of space separated locations. A location consist in " "the name of a variation axis, followed by '=' and a number. E.g.: " "wght=700 wdth=80. The default is the location of the base master.", ) options = parser.parse_args(args) glyphs = options.glyphs fontNumber = int(options.y) if options.y is not None else 0 location = {} for tag_v in options.variations.split(): fields = tag_v.split("=") tag = fields[0].strip() v = int(fields[1]) location[tag] = v from fontTools.ttLib import TTFont font = TTFont(options.font, fontNumber=fontNumber) if not glyphs: glyphs = font.getGlyphOrder() _test( font.getGlyphSet(location=location), font["head"].unitsPerEm, glyphs, quiet=options.quiet, control=options.control, )
Report font glyph shape geometricsl statistics
main
python
fonttools/fonttools
Lib/fontTools/pens/statisticsPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/statisticsPen.py
MIT
def _moveTo(self, pt): """ >>> pen = SVGPathPen(None) >>> pen.moveTo((0, 0)) >>> pen._commands ['M0 0'] >>> pen = SVGPathPen(None) >>> pen.moveTo((10, 0)) >>> pen._commands ['M10 0'] >>> pen = SVGPathPen(None) >>> pen.moveTo((0, 10)) >>> pen._commands ['M0 10'] """ self._handleAnchor() t = "M%s" % (pointToString(pt, self._ntos)) self._commands.append(t) self._lastCommand = "M" self._lastX, self._lastY = pt
>>> pen = SVGPathPen(None) >>> pen.moveTo((0, 0)) >>> pen._commands ['M0 0'] >>> pen = SVGPathPen(None) >>> pen.moveTo((10, 0)) >>> pen._commands ['M10 0'] >>> pen = SVGPathPen(None) >>> pen.moveTo((0, 10)) >>> pen._commands ['M0 10']
_moveTo
python
fonttools/fonttools
Lib/fontTools/pens/svgPathPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py
MIT
def _lineTo(self, pt): """ # duplicate point >>> pen = SVGPathPen(None) >>> pen.moveTo((10, 10)) >>> pen.lineTo((10, 10)) >>> pen._commands ['M10 10'] # vertical line >>> pen = SVGPathPen(None) >>> pen.moveTo((10, 10)) >>> pen.lineTo((10, 0)) >>> pen._commands ['M10 10', 'V0'] # horizontal line >>> pen = SVGPathPen(None) >>> pen.moveTo((10, 10)) >>> pen.lineTo((0, 10)) >>> pen._commands ['M10 10', 'H0'] # basic >>> pen = SVGPathPen(None) >>> pen.lineTo((70, 80)) >>> pen._commands ['L70 80'] # basic following a moveto >>> pen = SVGPathPen(None) >>> pen.moveTo((0, 0)) >>> pen.lineTo((10, 10)) >>> pen._commands ['M0 0', ' 10 10'] """ x, y = pt # duplicate point if x == self._lastX and y == self._lastY: return # vertical line elif x == self._lastX: cmd = "V" pts = self._ntos(y) # horizontal line elif y == self._lastY: cmd = "H" pts = self._ntos(x) # previous was a moveto elif self._lastCommand == "M": cmd = None pts = " " + pointToString(pt, self._ntos) # basic else: cmd = "L" pts = pointToString(pt, self._ntos) # write the string t = "" if cmd: t += cmd self._lastCommand = cmd t += pts self._commands.append(t) # store for future reference self._lastX, self._lastY = pt
# duplicate point >>> pen = SVGPathPen(None) >>> pen.moveTo((10, 10)) >>> pen.lineTo((10, 10)) >>> pen._commands ['M10 10'] # vertical line >>> pen = SVGPathPen(None) >>> pen.moveTo((10, 10)) >>> pen.lineTo((10, 0)) >>> pen._commands ['M10 10', 'V0'] # horizontal line >>> pen = SVGPathPen(None) >>> pen.moveTo((10, 10)) >>> pen.lineTo((0, 10)) >>> pen._commands ['M10 10', 'H0'] # basic >>> pen = SVGPathPen(None) >>> pen.lineTo((70, 80)) >>> pen._commands ['L70 80'] # basic following a moveto >>> pen = SVGPathPen(None) >>> pen.moveTo((0, 0)) >>> pen.lineTo((10, 10)) >>> pen._commands ['M0 0', ' 10 10']
_lineTo
python
fonttools/fonttools
Lib/fontTools/pens/svgPathPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py
MIT
def _curveToOne(self, pt1, pt2, pt3): """ >>> pen = SVGPathPen(None) >>> pen.curveTo((10, 20), (30, 40), (50, 60)) >>> pen._commands ['C10 20 30 40 50 60'] """ t = "C" t += pointToString(pt1, self._ntos) + " " t += pointToString(pt2, self._ntos) + " " t += pointToString(pt3, self._ntos) self._commands.append(t) self._lastCommand = "C" self._lastX, self._lastY = pt3
>>> pen = SVGPathPen(None) >>> pen.curveTo((10, 20), (30, 40), (50, 60)) >>> pen._commands ['C10 20 30 40 50 60']
_curveToOne
python
fonttools/fonttools
Lib/fontTools/pens/svgPathPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py
MIT
def _qCurveToOne(self, pt1, pt2): """ >>> pen = SVGPathPen(None) >>> pen.qCurveTo((10, 20), (30, 40)) >>> pen._commands ['Q10 20 30 40'] >>> from fontTools.misc.roundTools import otRound >>> pen = SVGPathPen(None, ntos=lambda v: str(otRound(v))) >>> pen.qCurveTo((3, 3), (7, 5), (11, 4)) >>> pen._commands ['Q3 3 5 4', 'Q7 5 11 4'] """ assert pt2 is not None t = "Q" t += pointToString(pt1, self._ntos) + " " t += pointToString(pt2, self._ntos) self._commands.append(t) self._lastCommand = "Q" self._lastX, self._lastY = pt2
>>> pen = SVGPathPen(None) >>> pen.qCurveTo((10, 20), (30, 40)) >>> pen._commands ['Q10 20 30 40'] >>> from fontTools.misc.roundTools import otRound >>> pen = SVGPathPen(None, ntos=lambda v: str(otRound(v))) >>> pen.qCurveTo((3, 3), (7, 5), (11, 4)) >>> pen._commands ['Q3 3 5 4', 'Q7 5 11 4']
_qCurveToOne
python
fonttools/fonttools
Lib/fontTools/pens/svgPathPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py
MIT
def _closePath(self): """ >>> pen = SVGPathPen(None) >>> pen.closePath() >>> pen._commands ['Z'] """ self._commands.append("Z") self._lastCommand = "Z" self._lastX = self._lastY = None
>>> pen = SVGPathPen(None) >>> pen.closePath() >>> pen._commands ['Z']
_closePath
python
fonttools/fonttools
Lib/fontTools/pens/svgPathPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py
MIT
def _endPath(self): """ >>> pen = SVGPathPen(None) >>> pen.endPath() >>> pen._commands [] """ self._lastCommand = None self._lastX = self._lastY = None
>>> pen = SVGPathPen(None) >>> pen.endPath() >>> pen._commands []
_endPath
python
fonttools/fonttools
Lib/fontTools/pens/svgPathPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py
MIT
def main(args=None): """Generate per-character SVG from font and text""" if args is None: import sys args = sys.argv[1:] from fontTools.ttLib import TTFont import argparse parser = argparse.ArgumentParser( "fonttools pens.svgPathPen", description="Generate SVG from text" ) parser.add_argument("font", metavar="font.ttf", help="Font file.") parser.add_argument("text", metavar="text", nargs="?", help="Text string.") parser.add_argument( "-y", metavar="<number>", help="Face index into a collection to open. Zero based.", ) parser.add_argument( "--glyphs", metavar="whitespace-separated list of glyph names", type=str, help="Glyphs to show. Exclusive with text option", ) parser.add_argument( "--variations", metavar="AXIS=LOC", default="", help="List of space separated locations. A location consist in " "the name of a variation axis, followed by '=' and a number. E.g.: " "wght=700 wdth=80. The default is the location of the base master.", ) options = parser.parse_args(args) fontNumber = int(options.y) if options.y is not None else 0 font = TTFont(options.font, fontNumber=fontNumber) text = options.text glyphs = options.glyphs location = {} for tag_v in options.variations.split(): fields = tag_v.split("=") tag = fields[0].strip() v = float(fields[1]) location[tag] = v hhea = font["hhea"] ascent, descent = hhea.ascent, hhea.descent glyphset = font.getGlyphSet(location=location) cmap = font["cmap"].getBestCmap() if glyphs is not None and text is not None: raise ValueError("Options --glyphs and --text are exclusive") if glyphs is None: glyphs = " ".join(cmap[ord(u)] for u in text) glyphs = glyphs.split() s = "" width = 0 for g in glyphs: glyph = glyphset[g] pen = SVGPathPen(glyphset) glyph.draw(pen) commands = pen.getCommands() s += '<g transform="translate(%d %d) scale(1 -1)"><path d="%s"/></g>\n' % ( width, ascent, commands, ) width += glyph.width print('<?xml version="1.0" encoding="UTF-8"?>') print( '<svg width="%d" height="%d" xmlns="http://www.w3.org/2000/svg">' % (width, ascent - descent) ) print(s, end="") print("</svg>")
Generate per-character SVG from font and text
main
python
fonttools/fonttools
Lib/fontTools/pens/svgPathPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py
MIT
def __init__(self, outPen, transformation): """The 'outPen' argument is another pen object. It will receive the transformed coordinates. The 'transformation' argument can either be a six-tuple, or a fontTools.misc.transform.Transform object. """ super(TransformPen, self).__init__(outPen) if not hasattr(transformation, "transformPoint"): from fontTools.misc.transform import Transform transformation = Transform(*transformation) self._transformation = transformation self._transformPoint = transformation.transformPoint self._stack = []
The 'outPen' argument is another pen object. It will receive the transformed coordinates. The 'transformation' argument can either be a six-tuple, or a fontTools.misc.transform.Transform object.
__init__
python
fonttools/fonttools
Lib/fontTools/pens/transformPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/transformPen.py
MIT
def __init__(self, outPointPen, transformation): """The 'outPointPen' argument is another point pen object. It will receive the transformed coordinates. The 'transformation' argument can either be a six-tuple, or a fontTools.misc.transform.Transform object. """ super().__init__(outPointPen) if not hasattr(transformation, "transformPoint"): from fontTools.misc.transform import Transform transformation = Transform(*transformation) self._transformation = transformation self._transformPoint = transformation.transformPoint
The 'outPointPen' argument is another point pen object. It will receive the transformed coordinates. The 'transformation' argument can either be a six-tuple, or a fontTools.misc.transform.Transform object.
__init__
python
fonttools/fonttools
Lib/fontTools/pens/transformPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/transformPen.py
MIT
def glyph( self, componentFlags: int = 0x04, dropImpliedOnCurves: bool = False, *, round: Callable[[float], int] = otRound, ) -> Glyph: """ Returns a :py:class:`~._g_l_y_f.Glyph` object representing the glyph. Args: componentFlags: Flags to use for component glyphs. (default: 0x04) dropImpliedOnCurves: Whether to remove implied-oncurve points. (default: False) """ if not self._isClosed(): raise PenError("Didn't close last contour.") components = self._buildComponents(componentFlags) glyph = Glyph() glyph.coordinates = GlyphCoordinates(self.points) glyph.endPtsOfContours = self.endPts glyph.flags = array("B", self.types) self.init() if components: # If both components and contours were present, they have by now # been decomposed by _buildComponents. glyph.components = components glyph.numberOfContours = -1 else: glyph.numberOfContours = len(glyph.endPtsOfContours) glyph.program = ttProgram.Program() glyph.program.fromBytecode(b"") if dropImpliedOnCurves: dropImpliedOnCurvePoints(glyph) glyph.coordinates.toInt(round=round) return glyph
Returns a :py:class:`~._g_l_y_f.Glyph` object representing the glyph. Args: componentFlags: Flags to use for component glyphs. (default: 0x04) dropImpliedOnCurves: Whether to remove implied-oncurve points. (default: False)
glyph
python
fonttools/fonttools
Lib/fontTools/pens/ttGlyphPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/ttGlyphPen.py
MIT
def addPoint( self, pt: Tuple[float, float], segmentType: Optional[str] = None, smooth: bool = False, name: Optional[str] = None, identifier: Optional[str] = None, **kwargs: Any, ) -> None: """ Add a point to the current sub path. """ if self._isClosed(): raise PenError("Can't add a point to a closed contour.") if segmentType is None: self.types.append(0) elif segmentType in ("line", "move"): self.types.append(flagOnCurve) elif segmentType == "qcurve": self.types.append(flagOnCurve) elif segmentType == "curve": self.types.append("curve") else: raise AssertionError(segmentType) self.points.append(pt)
Add a point to the current sub path.
addPoint
python
fonttools/fonttools
Lib/fontTools/pens/ttGlyphPen.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/ttGlyphPen.py
MIT
def _main(args=None): """Convert an OpenType font from quadratic to cubic curves""" parser = argparse.ArgumentParser(prog="qu2cu") parser.add_argument("--version", action="version", version=fontTools.__version__) parser.add_argument( "infiles", nargs="+", metavar="INPUT", help="one or more input TTF source file(s).", ) parser.add_argument("-v", "--verbose", action="count", default=0) parser.add_argument( "-e", "--conversion-error", type=float, metavar="ERROR", default=0.001, help="maxiumum approximation error measured in EM (default: 0.001)", ) parser.add_argument( "-c", "--all-cubic", default=False, action="store_true", help="whether to only use cubic curves", ) output_parser = parser.add_mutually_exclusive_group() output_parser.add_argument( "-o", "--output-file", default=None, metavar="OUTPUT", help=("output filename for the converted TTF."), ) output_parser.add_argument( "-d", "--output-dir", default=None, metavar="DIRECTORY", help="output directory where to save converted TTFs", ) options = parser.parse_args(args) if not options.verbose: level = "WARNING" elif options.verbose == 1: level = "INFO" else: level = "DEBUG" logging.basicConfig(level=level) if len(options.infiles) > 1 and options.output_file: parser.error("-o/--output-file can't be used with multile inputs") if options.output_dir: output_dir = options.output_dir if not os.path.exists(output_dir): os.mkdir(output_dir) elif not os.path.isdir(output_dir): parser.error("'%s' is not a directory" % output_dir) output_paths = [ os.path.join(output_dir, os.path.basename(p)) for p in options.infiles ] elif options.output_file: output_paths = [options.output_file] else: output_paths = [ makeOutputFileName(p, overWrite=True, suffix=".cubic") for p in options.infiles ] kwargs = dict( dump_stats=options.verbose > 0, max_err_em=options.conversion_error, all_cubic=options.all_cubic, ) for input_path, output_path in zip(options.infiles, output_paths): _font_to_cubic(input_path, output_path, **kwargs)
Convert an OpenType font from quadratic to cubic curves
_main
python
fonttools/fonttools
Lib/fontTools/qu2cu/cli.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/qu2cu/cli.py
MIT
def cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance): """Check if a cubic Bezier lies within a given distance of the origin. "Origin" means *the* origin (0,0), not the start of the curve. Note that no checks are made on the start and end positions of the curve; this function only checks the inside of the curve. Args: p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. p3 (complex): End point of curve. tolerance (double): Distance from origin. Returns: bool: True if the cubic Bezier ``p`` entirely lies within a distance ``tolerance`` of the origin, False otherwise. """ # First check p2 then p1, as p2 has higher error early on. if abs(p2) <= tolerance and abs(p1) <= tolerance: return True # Split. mid = (p0 + 3 * (p1 + p2) + p3) * 0.125 if abs(mid) > tolerance: return False deriv3 = (p3 + p2 - p1 - p0) * 0.125 return cubic_farthest_fit_inside( p0, (p0 + p1) * 0.5, mid - deriv3, mid, tolerance ) and cubic_farthest_fit_inside(mid, mid + deriv3, (p2 + p3) * 0.5, p3, tolerance)
Check if a cubic Bezier lies within a given distance of the origin. "Origin" means *the* origin (0,0), not the start of the curve. Note that no checks are made on the start and end positions of the curve; this function only checks the inside of the curve. Args: p0 (complex): Start point of curve. p1 (complex): First handle of curve. p2 (complex): Second handle of curve. p3 (complex): End point of curve. tolerance (double): Distance from origin. Returns: bool: True if the cubic Bezier ``p`` entirely lies within a distance ``tolerance`` of the origin, False otherwise.
cubic_farthest_fit_inside
python
fonttools/fonttools
Lib/fontTools/qu2cu/qu2cu.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/qu2cu/qu2cu.py
MIT
def elevate_quadratic(p0, p1, p2): """Given a quadratic bezier curve, return its degree-elevated cubic.""" # https://pomax.github.io/bezierinfo/#reordering p1_2_3 = p1 * (2 / 3) return ( p0, (p0 * (1 / 3) + p1_2_3), (p2 * (1 / 3) + p1_2_3), p2, )
Given a quadratic bezier curve, return its degree-elevated cubic.
elevate_quadratic
python
fonttools/fonttools
Lib/fontTools/qu2cu/qu2cu.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/qu2cu/qu2cu.py
MIT
def merge_curves(curves, start, n): """Give a cubic-Bezier spline, reconstruct one cubic-Bezier that has the same endpoints and tangents and approxmates the spline.""" # Reconstruct the t values of the cut segments prod_ratio = 1.0 sum_ratio = 1.0 ts = [1] for k in range(1, n): ck = curves[start + k] c_before = curves[start + k - 1] # |t_(k+1) - t_k| / |t_k - t_(k - 1)| = ratio assert ck[0] == c_before[3] ratio = abs(ck[1] - ck[0]) / abs(c_before[3] - c_before[2]) prod_ratio *= ratio sum_ratio += prod_ratio ts.append(sum_ratio) # (t(n) - t(n - 1)) / (t_(1) - t(0)) = prod_ratio ts = [t / sum_ratio for t in ts[:-1]] p0 = curves[start][0] p1 = curves[start][1] p2 = curves[start + n - 1][2] p3 = curves[start + n - 1][3] # Build the curve by scaling the control-points. p1 = p0 + (p1 - p0) / (ts[0] if ts else 1) p2 = p3 + (p2 - p3) / ((1 - ts[-1]) if ts else 1) curve = (p0, p1, p2, p3) return curve, ts
Give a cubic-Bezier spline, reconstruct one cubic-Bezier that has the same endpoints and tangents and approxmates the spline.
merge_curves
python
fonttools/fonttools
Lib/fontTools/qu2cu/qu2cu.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/qu2cu/qu2cu.py
MIT
def quadratic_to_curves( quads: List[List[Point]], max_err: float = 0.5, all_cubic: bool = False, ) -> List[Tuple[Point, ...]]: """Converts a connecting list of quadratic splines to a list of quadratic and cubic curves. A quadratic spline is specified as a list of points. Either each point is a 2-tuple of X,Y coordinates, or each point is a complex number with real/imaginary components representing X,Y coordinates. The first and last points are on-curve points and the rest are off-curve points, with an implied on-curve point in the middle between every two consequtive off-curve points. Returns: The output is a list of tuples of points. Points are represented in the same format as the input, either as 2-tuples or complex numbers. Each tuple is either of length three, for a quadratic curve, or four, for a cubic curve. Each curve's last point is the same as the next curve's first point. Args: quads: quadratic splines max_err: absolute error tolerance; defaults to 0.5 all_cubic: if True, only cubic curves are generated; defaults to False """ is_complex = type(quads[0][0]) is complex if not is_complex: quads = [[complex(x, y) for (x, y) in p] for p in quads] q = [quads[0][0]] costs = [1] cost = 1 for p in quads: assert q[-1] == p[0] for i in range(len(p) - 2): cost += 1 costs.append(cost) costs.append(cost) qq = add_implicit_on_curves(p)[1:] costs.pop() q.extend(qq) cost += 1 costs.append(cost) curves = spline_to_curves(q, costs, max_err, all_cubic) if not is_complex: curves = [tuple((c.real, c.imag) for c in curve) for curve in curves] return curves
Converts a connecting list of quadratic splines to a list of quadratic and cubic curves. A quadratic spline is specified as a list of points. Either each point is a 2-tuple of X,Y coordinates, or each point is a complex number with real/imaginary components representing X,Y coordinates. The first and last points are on-curve points and the rest are off-curve points, with an implied on-curve point in the middle between every two consequtive off-curve points. Returns: The output is a list of tuples of points. Points are represented in the same format as the input, either as 2-tuples or complex numbers. Each tuple is either of length three, for a quadratic curve, or four, for a cubic curve. Each curve's last point is the same as the next curve's first point. Args: quads: quadratic splines max_err: absolute error tolerance; defaults to 0.5 all_cubic: if True, only cubic curves are generated; defaults to False
quadratic_to_curves
python
fonttools/fonttools
Lib/fontTools/qu2cu/qu2cu.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/qu2cu/qu2cu.py
MIT
def spline_to_curves(q, costs, tolerance=0.5, all_cubic=False): """ q: quadratic spline with alternating on-curve / off-curve points. costs: cumulative list of encoding cost of q in terms of number of points that need to be encoded. Implied on-curve points do not contribute to the cost. If all points need to be encoded, then costs will be range(1, len(q)+1). """ assert len(q) >= 3, "quadratic spline requires at least 3 points" # Elevate quadratic segments to cubic elevated_quadratics = [ elevate_quadratic(*q[i : i + 3]) for i in range(0, len(q) - 2, 2) ] # Find sharp corners; they have to be oncurves for sure. forced = set() for i in range(1, len(elevated_quadratics)): p0 = elevated_quadratics[i - 1][2] p1 = elevated_quadratics[i][0] p2 = elevated_quadratics[i][1] if abs(p1 - p0) + abs(p2 - p1) > tolerance + abs(p2 - p0): forced.add(i) # Dynamic-Programming to find the solution with fewest number of # cubic curves, and within those the one with smallest error. sols = [Solution(0, 0, 0, False)] impossible = Solution(len(elevated_quadratics) * 3 + 1, 0, 1, False) start = 0 for i in range(1, len(elevated_quadratics) + 1): best_sol = impossible for j in range(start, i): j_sol_count, j_sol_error = sols[j].num_points, sols[j].error if not all_cubic: # Solution with quadratics between j:i this_count = costs[2 * i - 1] - costs[2 * j] + 1 i_sol_count = j_sol_count + this_count i_sol_error = j_sol_error i_sol = Solution(i_sol_count, i_sol_error, i - j, False) if i_sol < best_sol: best_sol = i_sol if this_count <= 3: # Can't get any better than this in the path below continue # Fit elevated_quadratics[j:i] into one cubic try: curve, ts = merge_curves(elevated_quadratics, j, i - j) except ZeroDivisionError: continue # Now reconstruct the segments from the fitted curve reconstructed_iter = splitCubicAtTC(*curve, *ts) reconstructed = [] # Knot errors error = 0 for k, reconst in enumerate(reconstructed_iter): orig = elevated_quadratics[j + k] err = abs(reconst[3] - orig[3]) error = max(error, err) if error > tolerance: break reconstructed.append(reconst) if error > tolerance: # Not feasible continue # Interior errors for k, reconst in enumerate(reconstructed): orig = elevated_quadratics[j + k] p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig)) if not cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance): error = tolerance + 1 break if error > tolerance: # Not feasible continue # Save best solution i_sol_count = j_sol_count + 3 i_sol_error = max(j_sol_error, error) i_sol = Solution(i_sol_count, i_sol_error, i - j, True) if i_sol < best_sol: best_sol = i_sol if i_sol_count == 3: # Can't get any better than this break sols.append(best_sol) if i in forced: start = i # Reconstruct solution splits = [] cubic = [] i = len(sols) - 1 while i: count, is_cubic = sols[i].start_index, sols[i].is_cubic splits.append(i) cubic.append(is_cubic) i -= count curves = [] j = 0 for i, is_cubic in reversed(list(zip(splits, cubic))): if is_cubic: curves.append(merge_curves(elevated_quadratics, j, i - j)[0]) else: for k in range(j, i): curves.append(q[k * 2 : k * 2 + 3]) j = i return curves
q: quadratic spline with alternating on-curve / off-curve points. costs: cumulative list of encoding cost of q in terms of number of points that need to be encoded. Implied on-curve points do not contribute to the cost. If all points need to be encoded, then costs will be range(1, len(q)+1).
spline_to_curves
python
fonttools/fonttools
Lib/fontTools/qu2cu/qu2cu.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/qu2cu/qu2cu.py
MIT
def _add_method(*clazzes): """Returns a decorator function that adds a new method to one or more classes.""" def wrapper(method): done = [] for clazz in clazzes: if clazz in done: continue # Support multiple names of a clazz done.append(clazz) assert clazz.__name__ != "DefaultTable", "Oops, table class not found." assert not hasattr( clazz, method.__name__ ), "Oops, class '%s' has method '%s'." % (clazz.__name__, method.__name__) setattr(clazz, method.__name__, method) return None return wrapper
Returns a decorator function that adds a new method to one or more classes.
_add_method
python
fonttools/fonttools
Lib/fontTools/subset/util.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/util.py
MIT
def subset(self, glyphs): """Returns ascending list of remaining coverage values.""" indices = self.intersect(glyphs) self.glyphs = [g for g in self.glyphs if g in glyphs] return indices
Returns ascending list of remaining coverage values.
subset
python
fonttools/fonttools
Lib/fontTools/subset/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py
MIT
def intersect(self, glyphs): """Returns ascending list of matching class values.""" return _uniq_sort( ([0] if any(g not in self.classDefs for g in glyphs) else []) + [v for g, v in self.classDefs.items() if g in glyphs] )
Returns ascending list of matching class values.
intersect
python
fonttools/fonttools
Lib/fontTools/subset/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py
MIT
def intersect_class(self, glyphs, klass): """Returns set of glyphs matching class.""" if klass == 0: return set(g for g in glyphs if g not in self.classDefs) return set(g for g, v in self.classDefs.items() if v == klass and g in glyphs)
Returns set of glyphs matching class.
intersect_class
python
fonttools/fonttools
Lib/fontTools/subset/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py
MIT
def subset(self, glyphs, remap=False, useClass0=True): """Returns ascending list of remaining classes.""" self.classDefs = {g: v for g, v in self.classDefs.items() if g in glyphs} # Note: while class 0 has the special meaning of "not matched", # if no glyph will ever /not match/, we can optimize class 0 out too. # Only do this if allowed. indices = _uniq_sort( ( [0] if ((not useClass0) or any(g not in self.classDefs for g in glyphs)) else [] ) + list(self.classDefs.values()) ) if remap: self.remap(indices) return indices
Returns ascending list of remaining classes.
subset
python
fonttools/fonttools
Lib/fontTools/subset/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py
MIT
def neuter_lookups(self, lookup_indices): """Sets lookups not in lookup_indices to None.""" self.ensureDecompiled() self.Lookup = [ l if i in lookup_indices else None for i, l in enumerate(self.Lookup) ]
Sets lookups not in lookup_indices to None.
neuter_lookups
python
fonttools/fonttools
Lib/fontTools/subset/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py
MIT
def closure_lookups(self, lookup_indices): """Returns sorted index of all lookups reachable from lookup_indices.""" lookup_indices = _uniq_sort(lookup_indices) recurse = lookup_indices while True: recurse_lookups = sum( (self.Lookup[i].collect_lookups() for i in recurse if i < self.LookupCount), [], ) recurse_lookups = [ l for l in recurse_lookups if l not in lookup_indices and l < self.LookupCount ] if not recurse_lookups: return _uniq_sort(lookup_indices) recurse_lookups = _uniq_sort(recurse_lookups) lookup_indices.extend(recurse_lookups) recurse = recurse_lookups
Returns sorted index of all lookups reachable from lookup_indices.
closure_lookups
python
fonttools/fonttools
Lib/fontTools/subset/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py
MIT
def subset_lookups(self, lookup_indices): """ "Returns True if feature is non-empty afterwards.""" self.LookupListIndex = [l for l in self.LookupListIndex if l in lookup_indices] # Now map them. self.LookupListIndex = [lookup_indices.index(l) for l in self.LookupListIndex] self.LookupCount = len(self.LookupListIndex) # keep 'size' feature even if it contains no lookups; but drop any other # empty feature (e.g. FeatureParams for stylistic set names) # https://github.com/fonttools/fonttools/issues/2324 return self.LookupCount or isinstance( self.FeatureParams, otTables.FeatureParamsSize )
"Returns True if feature is non-empty afterwards.
subset_lookups
python
fonttools/fonttools
Lib/fontTools/subset/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py
MIT
def subset_lookups(self, lookup_indices): """Returns the indices of nonempty features.""" # Note: Never ever drop feature 'pref', even if it's empty. # HarfBuzz chooses shaper for Khmer based on presence of this # feature. See thread at: # http://lists.freedesktop.org/archives/harfbuzz/2012-November/002660.html return [ i for i, f in enumerate(self.FeatureRecord) if (f.Feature.subset_lookups(lookup_indices) or f.FeatureTag == "pref") ]
Returns the indices of nonempty features.
subset_lookups
python
fonttools/fonttools
Lib/fontTools/subset/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py
MIT
def subset_lookups(self, lookup_indices): """Returns the indices of nonempty features.""" return [ r.FeatureIndex for r in self.SubstitutionRecord if r.Feature.subset_lookups(lookup_indices) ]
Returns the indices of nonempty features.
subset_lookups
python
fonttools/fonttools
Lib/fontTools/subset/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py
MIT
def subset_lookups(self, lookup_indices): """Returns the indices of nonempty features.""" return sum( ( f.FeatureTableSubstitution.subset_lookups(lookup_indices) for f in self.FeatureVariationRecord ), [], )
Returns the indices of nonempty features.
subset_lookups
python
fonttools/fonttools
Lib/fontTools/subset/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py
MIT
def subset_lookups(self, lookup_indices): """Retains specified lookups, then removes empty features, language systems, and scripts.""" if self.table.LookupList: self.table.LookupList.subset_lookups(lookup_indices) if self.table.FeatureList: feature_indices = self.table.FeatureList.subset_lookups(lookup_indices) else: feature_indices = [] if getattr(self.table, "FeatureVariations", None): feature_indices += self.table.FeatureVariations.subset_lookups(lookup_indices) feature_indices = _uniq_sort(feature_indices) if self.table.FeatureList: self.table.FeatureList.subset_features(feature_indices) if getattr(self.table, "FeatureVariations", None): self.table.FeatureVariations.subset_features(feature_indices) if self.table.ScriptList: self.table.ScriptList.subset_features( feature_indices, self.retain_empty_scripts() )
Retains specified lookups, then removes empty features, language systems, and scripts.
subset_lookups
python
fonttools/fonttools
Lib/fontTools/subset/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py
MIT
def prune_lookups(self, remap=True): """Remove (default) or neuter unreferenced lookups""" if self.table.ScriptList: feature_indices = self.table.ScriptList.collect_features() else: feature_indices = [] if self.table.FeatureList: lookup_indices = self.table.FeatureList.collect_lookups(feature_indices) else: lookup_indices = [] if getattr(self.table, "FeatureVariations", None): lookup_indices += self.table.FeatureVariations.collect_lookups(feature_indices) lookup_indices = _uniq_sort(lookup_indices) if self.table.LookupList: lookup_indices = self.table.LookupList.closure_lookups(lookup_indices) else: lookup_indices = [] if remap: self.subset_lookups(lookup_indices) else: self.neuter_lookups(lookup_indices)
Remove (default) or neuter unreferenced lookups
prune_lookups
python
fonttools/fonttools
Lib/fontTools/subset/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py
MIT
def _remap_select_name_ids(font: ttLib.TTFont, needRemapping: set[int]) -> None: """Remap a set of IDs so that the originals can be safely scrambled or dropped. For each name record whose name id is in the `needRemapping` set, make a copy and allocate a new unused name id in the font-specific range (> 255). Finally update references to these in the `fvar` and `STAT` tables. """ if "fvar" not in font and "STAT" not in font: return name = font["name"] # 1. Assign new IDs for names to be preserved. existingIds = {record.nameID for record in name.names} remapping = {} nextId = name._findUnusedNameID() - 1 # Should skip gaps in name IDs. for nameId in needRemapping: nextId += 1 # We should have complete freedom until 32767. assert nextId not in existingIds, "_findUnusedNameID did not skip gaps" if nextId > 32767: raise ValueError("Ran out of name IDs while trying to remap existing ones.") remapping[nameId] = nextId # 2. Copy records to use the new ID. We can't rewrite them in place, because # that could make IDs 1 to 6 "disappear" from code that follows. Some # tools that produce EOT fonts expect them to exist, even when they're # scrambled. See https://github.com/fonttools/fonttools/issues/165. copiedRecords = [] for record in name.names: if record.nameID not in needRemapping: continue recordCopy = makeName( record.string, remapping[record.nameID], record.platformID, record.platEncID, record.langID, ) copiedRecords.append(recordCopy) name.names.extend(copiedRecords) # 3. Rewrite the corresponding IDs in other tables. For now, care only about # STAT and fvar. If more tables need to be changed, consider adapting # NameRecordVisitor to rewrite IDs wherever it finds them. fvar = font.get("fvar") if fvar is not None: for axis in fvar.axes: axis.axisNameID = remapping.get(axis.axisNameID, axis.axisNameID) for instance in fvar.instances: nameID = instance.subfamilyNameID instance.subfamilyNameID = remapping.get(nameID, nameID) nameID = instance.postscriptNameID instance.postscriptNameID = remapping.get(nameID, nameID) stat = font.get("STAT") if stat is None: return elidedNameID = stat.table.ElidedFallbackNameID stat.table.ElidedFallbackNameID = remapping.get(elidedNameID, elidedNameID) if stat.table.DesignAxisRecord: for axis in stat.table.DesignAxisRecord.Axis: axis.AxisNameID = remapping.get(axis.AxisNameID, axis.AxisNameID) if stat.table.AxisValueArray: for value in stat.table.AxisValueArray.AxisValue: value.ValueNameID = remapping.get(value.ValueNameID, value.ValueNameID)
Remap a set of IDs so that the originals can be safely scrambled or dropped. For each name record whose name id is in the `needRemapping` set, make a copy and allocate a new unused name id in the font-specific range (> 255). Finally update references to these in the `fvar` and `STAT` tables.
_remap_select_name_ids
python
fonttools/fonttools
Lib/fontTools/subset/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py
MIT
def parse_path(pathdef, pen, current_pos=(0, 0), arc_class=EllipticalArc): """Parse SVG path definition (i.e. "d" attribute of <path> elements) and call a 'pen' object's moveTo, lineTo, curveTo, qCurveTo and closePath methods. If 'current_pos' (2-float tuple) is provided, the initial moveTo will be relative to that instead being absolute. If the pen has an "arcTo" method, it is called with the original values of the elliptical arc curve commands: .. code-block:: pen.arcTo(rx, ry, rotation, arc_large, arc_sweep, (x, y)) Otherwise, the arcs are approximated by series of cubic Bezier segments ("curveTo"), one every 90 degrees. """ # In the SVG specs, initial movetos are absolute, even if # specified as 'm'. This is the default behavior here as well. # But if you pass in a current_pos variable, the initial moveto # will be relative to that current_pos. This is useful. current_pos = complex(*current_pos) elements = list(_tokenize_path(pathdef)) # Reverse for easy use of .pop() elements.reverse() start_pos = None command = None last_control = None have_arcTo = hasattr(pen, "arcTo") while elements: if elements[-1] in COMMANDS: # New command. last_command = command # Used by S and T command = elements.pop() absolute = command in UPPERCASE command = command.upper() else: # If this element starts with numbers, it is an implicit command # and we don't change the command. Check that it's allowed: if command is None: raise ValueError( "Unallowed implicit command in %s, position %s" % (pathdef, len(pathdef.split()) - len(elements)) ) last_command = command # Used by S and T if command == "M": # Moveto command. x = elements.pop() y = elements.pop() pos = float(x) + float(y) * 1j if absolute: current_pos = pos else: current_pos += pos # M is not preceded by Z; it's an open subpath if start_pos is not None: pen.endPath() pen.moveTo((current_pos.real, current_pos.imag)) # when M is called, reset start_pos # This behavior of Z is defined in svg spec: # http://www.w3.org/TR/SVG/paths.html#PathDataClosePathCommand start_pos = current_pos # Implicit moveto commands are treated as lineto commands. # So we set command to lineto here, in case there are # further implicit commands after this moveto. command = "L" elif command == "Z": # Close path if current_pos != start_pos: pen.lineTo((start_pos.real, start_pos.imag)) pen.closePath() current_pos = start_pos start_pos = None command = None # You can't have implicit commands after closing. elif command == "L": x = elements.pop() y = elements.pop() pos = float(x) + float(y) * 1j if not absolute: pos += current_pos pen.lineTo((pos.real, pos.imag)) current_pos = pos elif command == "H": x = elements.pop() pos = float(x) + current_pos.imag * 1j if not absolute: pos += current_pos.real pen.lineTo((pos.real, pos.imag)) current_pos = pos elif command == "V": y = elements.pop() pos = current_pos.real + float(y) * 1j if not absolute: pos += current_pos.imag * 1j pen.lineTo((pos.real, pos.imag)) current_pos = pos elif command == "C": control1 = float(elements.pop()) + float(elements.pop()) * 1j control2 = float(elements.pop()) + float(elements.pop()) * 1j end = float(elements.pop()) + float(elements.pop()) * 1j if not absolute: control1 += current_pos control2 += current_pos end += current_pos pen.curveTo( (control1.real, control1.imag), (control2.real, control2.imag), (end.real, end.imag), ) current_pos = end last_control = control2 elif command == "S": # Smooth curve. First control point is the "reflection" of # the second control point in the previous path. if last_command not in "CS": # If there is no previous command or if the previous command # was not an C, c, S or s, assume the first control point is # coincident with the current point. control1 = current_pos else: # The first control point is assumed to be the reflection of # the second control point on the previous command relative # to the current point. control1 = current_pos + current_pos - last_control control2 = float(elements.pop()) + float(elements.pop()) * 1j end = float(elements.pop()) + float(elements.pop()) * 1j if not absolute: control2 += current_pos end += current_pos pen.curveTo( (control1.real, control1.imag), (control2.real, control2.imag), (end.real, end.imag), ) current_pos = end last_control = control2 elif command == "Q": control = float(elements.pop()) + float(elements.pop()) * 1j end = float(elements.pop()) + float(elements.pop()) * 1j if not absolute: control += current_pos end += current_pos pen.qCurveTo((control.real, control.imag), (end.real, end.imag)) current_pos = end last_control = control elif command == "T": # Smooth curve. Control point is the "reflection" of # the second control point in the previous path. if last_command not in "QT": # If there is no previous command or if the previous command # was not an Q, q, T or t, assume the first control point is # coincident with the current point. control = current_pos else: # The control point is assumed to be the reflection of # the control point on the previous command relative # to the current point. control = current_pos + current_pos - last_control end = float(elements.pop()) + float(elements.pop()) * 1j if not absolute: end += current_pos pen.qCurveTo((control.real, control.imag), (end.real, end.imag)) current_pos = end last_control = control elif command == "A": rx = abs(float(elements.pop())) ry = abs(float(elements.pop())) rotation = float(elements.pop()) arc_large = bool(int(elements.pop())) arc_sweep = bool(int(elements.pop())) end = float(elements.pop()) + float(elements.pop()) * 1j if not absolute: end += current_pos # if the pen supports arcs, pass the values unchanged, otherwise # approximate the arc with a series of cubic bezier curves if have_arcTo: pen.arcTo( rx, ry, rotation, arc_large, arc_sweep, (end.real, end.imag), ) else: arc = arc_class( current_pos, rx, ry, rotation, arc_large, arc_sweep, end ) arc.draw(pen) current_pos = end # no final Z command, it's an open path if start_pos is not None: pen.endPath()
Parse SVG path definition (i.e. "d" attribute of <path> elements) and call a 'pen' object's moveTo, lineTo, curveTo, qCurveTo and closePath methods. If 'current_pos' (2-float tuple) is provided, the initial moveTo will be relative to that instead being absolute. If the pen has an "arcTo" method, it is called with the original values of the elliptical arc curve commands: .. code-block:: pen.arcTo(rx, ry, rotation, arc_large, arc_sweep, (x, y)) Otherwise, the arcs are approximated by series of cubic Bezier segments ("curveTo"), one every 90 degrees.
parse_path
python
fonttools/fonttools
Lib/fontTools/svgLib/path/parser.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/svgLib/path/parser.py
MIT
def read(path, onlyHeader=False): """reads any Type 1 font file, returns raw data""" _, ext = os.path.splitext(path) ext = ext.lower() creator, typ = getMacCreatorAndType(path) if typ == "LWFN": return readLWFN(path, onlyHeader), "LWFN" if ext == ".pfb": return readPFB(path, onlyHeader), "PFB" else: return readOther(path), "OTHER"
reads any Type 1 font file, returns raw data
read
python
fonttools/fonttools
Lib/fontTools/t1Lib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/t1Lib/__init__.py
MIT
def readLWFN(path, onlyHeader=False): """reads an LWFN font file, returns raw data""" from fontTools.misc.macRes import ResourceReader reader = ResourceReader(path) try: data = [] for res in reader.get("POST", []): code = byteord(res.data[0]) if byteord(res.data[1]) != 0: raise T1Error("corrupt LWFN file") if code in [1, 2]: if onlyHeader and code == 2: break data.append(res.data[2:]) elif code in [3, 5]: break elif code == 4: with open(path, "rb") as f: data.append(f.read()) elif code == 0: pass # comment, ignore else: raise T1Error("bad chunk code: " + repr(code)) finally: reader.close() data = bytesjoin(data) assertType1(data) return data
reads an LWFN font file, returns raw data
readLWFN
python
fonttools/fonttools
Lib/fontTools/t1Lib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/t1Lib/__init__.py
MIT
def readPFB(path, onlyHeader=False): """reads a PFB font file, returns raw data""" data = [] with open(path, "rb") as f: while True: if f.read(1) != bytechr(128): raise T1Error("corrupt PFB file") code = byteord(f.read(1)) if code in [1, 2]: chunklen = stringToLong(f.read(4)) chunk = f.read(chunklen) assert len(chunk) == chunklen data.append(chunk) elif code == 3: break else: raise T1Error("bad chunk code: " + repr(code)) if onlyHeader: break data = bytesjoin(data) assertType1(data) return data
reads a PFB font file, returns raw data
readPFB
python
fonttools/fonttools
Lib/fontTools/t1Lib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/t1Lib/__init__.py
MIT
def readOther(path): """reads any (font) file, returns raw data""" with open(path, "rb") as f: data = f.read() assertType1(data) chunks = findEncryptedChunks(data) data = [] for isEncrypted, chunk in chunks: if isEncrypted and isHex(chunk[:4]): data.append(deHexString(chunk)) else: data.append(chunk) return bytesjoin(data)
reads any (font) file, returns raw data
readOther
python
fonttools/fonttools
Lib/fontTools/t1Lib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/t1Lib/__init__.py
MIT
def getSFNTResIndices(path): """Determine whether a file has a 'sfnt' resource fork or not.""" try: reader = ResourceReader(path) indices = reader.getIndices("sfnt") reader.close() return indices except ResourceError: return []
Determine whether a file has a 'sfnt' resource fork or not.
getSFNTResIndices
python
fonttools/fonttools
Lib/fontTools/ttLib/macUtils.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/macUtils.py
MIT
def openTTFonts(path): """Given a pathname, return a list of TTFont objects. In the case of a flat TTF/OTF file, the list will contain just one font object; but in the case of a Mac font suitcase it will contain as many font objects as there are sfnt resources in the file. """ from fontTools import ttLib fonts = [] sfnts = getSFNTResIndices(path) if not sfnts: fonts.append(ttLib.TTFont(path)) else: for index in sfnts: fonts.append(ttLib.TTFont(path, index)) if not fonts: raise ttLib.TTLibError("no fonts found in file '%s'" % path) return fonts
Given a pathname, return a list of TTFont objects. In the case of a flat TTF/OTF file, the list will contain just one font object; but in the case of a Mac font suitcase it will contain as many font objects as there are sfnt resources in the file.
openTTFonts
python
fonttools/fonttools
Lib/fontTools/ttLib/macUtils.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/macUtils.py
MIT
def removeOverlaps( font: ttFont.TTFont, glyphNames: Optional[Iterable[str]] = None, removeHinting: bool = True, ignoreErrors: bool = False, *, removeUnusedSubroutines: bool = True, ) -> None: """Simplify glyphs in TTFont by merging overlapping contours. Overlapping components are first decomposed to simple contours, then merged. Currently this only works for fonts with 'glyf' or 'CFF ' tables. Raises NotImplementedError if 'glyf' or 'CFF ' tables are absent. Note that removing overlaps invalidates the hinting. By default we drop hinting from all glyphs whether or not overlaps are removed from a given one, as it would look weird if only some glyphs are left (un)hinted. Args: font: input TTFont object, modified in place. glyphNames: optional iterable of glyph names (str) to remove overlaps from. By default, all glyphs in the font are processed. removeHinting (bool): set to False to keep hinting for unmodified glyphs. ignoreErrors (bool): set to True to ignore errors while removing overlaps, thus keeping the tricky glyphs unchanged (fonttools/fonttools#2363). removeUnusedSubroutines (bool): set to False to keep unused subroutines in CFF table after removing overlaps. Default is to remove them if any glyphs are modified. """ if "glyf" not in font and "CFF " not in font: raise NotImplementedError( "No outline data found in the font: missing 'glyf' or 'CFF ' table" ) if glyphNames is None: glyphNames = font.getGlyphOrder() # Wraps the underlying glyphs, takes care of interfacing with drawing pens glyphSet = font.getGlyphSet() if "glyf" in font: _remove_glyf_overlaps( font=font, glyphNames=glyphNames, glyphSet=glyphSet, removeHinting=removeHinting, ignoreErrors=ignoreErrors, ) if "CFF " in font: _remove_cff_overlaps( font=font, glyphNames=glyphNames, glyphSet=glyphSet, removeHinting=removeHinting, ignoreErrors=ignoreErrors, removeUnusedSubroutines=removeUnusedSubroutines, )
Simplify glyphs in TTFont by merging overlapping contours. Overlapping components are first decomposed to simple contours, then merged. Currently this only works for fonts with 'glyf' or 'CFF ' tables. Raises NotImplementedError if 'glyf' or 'CFF ' tables are absent. Note that removing overlaps invalidates the hinting. By default we drop hinting from all glyphs whether or not overlaps are removed from a given one, as it would look weird if only some glyphs are left (un)hinted. Args: font: input TTFont object, modified in place. glyphNames: optional iterable of glyph names (str) to remove overlaps from. By default, all glyphs in the font are processed. removeHinting (bool): set to False to keep hinting for unmodified glyphs. ignoreErrors (bool): set to True to ignore errors while removing overlaps, thus keeping the tricky glyphs unchanged (fonttools/fonttools#2363). removeUnusedSubroutines (bool): set to False to keep unused subroutines in CFF table after removing overlaps. Default is to remove them if any glyphs are modified.
removeOverlaps
python
fonttools/fonttools
Lib/fontTools/ttLib/removeOverlaps.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/removeOverlaps.py
MIT
def main(args=None): """Simplify glyphs in TTFont by merging overlapping contours.""" import argparse parser = argparse.ArgumentParser( "fonttools ttLib.removeOverlaps", description=__doc__ ) parser.add_argument("input", metavar="INPUT.ttf", help="Input font file") parser.add_argument("output", metavar="OUTPUT.ttf", help="Output font file") parser.add_argument( "glyphs", metavar="GLYPHS", nargs="*", help="Optional list of glyph names to remove overlaps from", ) parser.add_argument( "--keep-hinting", action="store_true", help="Keep hinting for unmodified glyphs, default is to drop hinting", ) parser.add_argument( "--ignore-errors", action="store_true", help="ignore errors while removing overlaps, " "thus keeping the tricky glyphs unchanged", ) parser.add_argument( "--keep-unused-subroutines", action="store_true", help="Keep unused subroutines in CFF table after removing overlaps, " "default is to remove them if any glyphs are modified", ) args = parser.parse_args(args) with ttFont.TTFont(args.input) as font: removeOverlaps( font=font, glyphNames=args.glyphs or None, removeHinting=not args.keep_hinting, ignoreErrors=args.ignore_errors, removeUnusedSubroutines=not args.keep_unused_subroutines, ) font.save(args.output)
Simplify glyphs in TTFont by merging overlapping contours.
main
python
fonttools/fonttools
Lib/fontTools/ttLib/removeOverlaps.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/removeOverlaps.py
MIT
def scale_upem(font, new_upem): """Change the units-per-EM of font to the new value.""" upem = font["head"].unitsPerEm visitor = ScalerVisitor(new_upem / upem) visitor.visit(font)
Change the units-per-EM of font to the new value.
scale_upem
python
fonttools/fonttools
Lib/fontTools/ttLib/scaleUpem.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/scaleUpem.py
MIT
def main(args=None): """Change the units-per-EM of fonts""" if args is None: import sys args = sys.argv[1:] from fontTools.ttLib import TTFont from fontTools.misc.cliTools import makeOutputFileName import argparse parser = argparse.ArgumentParser( "fonttools ttLib.scaleUpem", description="Change the units-per-EM of fonts" ) parser.add_argument("font", metavar="font", help="Font file.") parser.add_argument( "new_upem", metavar="new-upem", help="New units-per-EM integer value." ) parser.add_argument( "--output-file", metavar="path", default=None, help="Output file." ) options = parser.parse_args(args) font = TTFont(options.font) new_upem = int(options.new_upem) output_file = ( options.output_file if options.output_file is not None else makeOutputFileName(options.font, overWrite=True, suffix="-scaled") ) scale_upem(font, new_upem) print("Writing %s" % output_file) font.save(output_file)
Change the units-per-EM of fonts
main
python
fonttools/fonttools
Lib/fontTools/ttLib/scaleUpem.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/scaleUpem.py
MIT
def __new__(cls, *args, **kwargs): """Return an instance of the SFNTReader sub-class which is compatible with the input file type. """ if args and cls is SFNTReader: infile = args[0] infile.seek(0) sfntVersion = Tag(infile.read(4)) infile.seek(0) if sfntVersion == "wOF2": # return new WOFF2Reader object from fontTools.ttLib.woff2 import WOFF2Reader return object.__new__(WOFF2Reader) # return default object return object.__new__(cls)
Return an instance of the SFNTReader sub-class which is compatible with the input file type.
__new__
python
fonttools/fonttools
Lib/fontTools/ttLib/sfnt.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/sfnt.py
MIT
def compress(data, level=ZLIB_COMPRESSION_LEVEL): """Compress 'data' to Zlib format. If 'USE_ZOPFLI' variable is True, zopfli is used instead of the zlib module. The compression 'level' must be between 0 and 9. 1 gives best speed, 9 gives best compression (0 gives no compression at all). The default value is a compromise between speed and compression (6). """ if not (0 <= level <= 9): raise ValueError("Bad compression level: %s" % level) if not USE_ZOPFLI or level == 0: from zlib import compress return compress(data, level) else: from zopfli.zlib import compress return compress(data, numiterations=ZOPFLI_LEVELS[level])
Compress 'data' to Zlib format. If 'USE_ZOPFLI' variable is True, zopfli is used instead of the zlib module. The compression 'level' must be between 0 and 9. 1 gives best speed, 9 gives best compression (0 gives no compression at all). The default value is a compromise between speed and compression (6).
compress
python
fonttools/fonttools
Lib/fontTools/ttLib/sfnt.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/sfnt.py
MIT
def __new__(cls, *args, **kwargs): """Return an instance of the SFNTWriter sub-class which is compatible with the specified 'flavor'. """ flavor = None if kwargs and "flavor" in kwargs: flavor = kwargs["flavor"] elif args and len(args) > 3: flavor = args[3] if cls is SFNTWriter: if flavor == "woff2": # return new WOFF2Writer object from fontTools.ttLib.woff2 import WOFF2Writer return object.__new__(WOFF2Writer) # return default object return object.__new__(cls)
Return an instance of the SFNTWriter sub-class which is compatible with the specified 'flavor'.
__new__
python
fonttools/fonttools
Lib/fontTools/ttLib/sfnt.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/sfnt.py
MIT
def __setitem__(self, tag, data): """Write raw table data to disk.""" if tag in self.tables: raise TTLibError("cannot rewrite '%s' table" % tag) entry = self.DirectoryEntry() entry.tag = tag entry.offset = self.nextTableOffset if tag == "head": entry.checkSum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:]) self.headTable = data entry.uncompressed = True else: entry.checkSum = calcChecksum(data) entry.saveData(self.file, data) if self.flavor == "woff": entry.origOffset = self.origNextTableOffset self.origNextTableOffset += (entry.origLength + 3) & ~3 self.nextTableOffset = self.nextTableOffset + ((entry.length + 3) & ~3) # Add NUL bytes to pad the table data to a 4-byte boundary. # Don't depend on f.seek() as we need to add the padding even if no # subsequent write follows (seek is lazy), ie. after the final table # in the font. self.file.write(b"\0" * (self.nextTableOffset - self.file.tell())) assert self.nextTableOffset == self.file.tell() self.setEntry(tag, entry)
Write raw table data to disk.
__setitem__
python
fonttools/fonttools
Lib/fontTools/ttLib/sfnt.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/sfnt.py
MIT
def close(self): """All tables must have been written to disk. Now write the directory. """ tables = sorted(self.tables.items()) if len(tables) != self.numTables: raise TTLibError( "wrong number of tables; expected %d, found %d" % (self.numTables, len(tables)) ) if self.flavor == "woff": self.signature = b"wOFF" self.reserved = 0 self.totalSfntSize = 12 self.totalSfntSize += 16 * len(tables) for tag, entry in tables: self.totalSfntSize += (entry.origLength + 3) & ~3 data = self.flavorData if self.flavorData else WOFFFlavorData() if data.majorVersion is not None and data.minorVersion is not None: self.majorVersion = data.majorVersion self.minorVersion = data.minorVersion else: if hasattr(self, "headTable"): self.majorVersion, self.minorVersion = struct.unpack( ">HH", self.headTable[4:8] ) else: self.majorVersion = self.minorVersion = 0 if data.metaData: self.metaOrigLength = len(data.metaData) self.file.seek(0, 2) self.metaOffset = self.file.tell() compressedMetaData = compress(data.metaData) self.metaLength = len(compressedMetaData) self.file.write(compressedMetaData) else: self.metaOffset = self.metaLength = self.metaOrigLength = 0 if data.privData: self.file.seek(0, 2) off = self.file.tell() paddedOff = (off + 3) & ~3 self.file.write(b"\0" * (paddedOff - off)) self.privOffset = self.file.tell() self.privLength = len(data.privData) self.file.write(data.privData) else: self.privOffset = self.privLength = 0 self.file.seek(0, 2) self.length = self.file.tell() else: assert not self.flavor, "Unknown flavor '%s'" % self.flavor pass directory = sstruct.pack(self.directoryFormat, self) self.file.seek(self.directoryOffset + self.directorySize) seenHead = 0 for tag, entry in tables: if tag == "head": seenHead = 1 directory = directory + entry.toString() if seenHead: self.writeMasterChecksum(directory) self.file.seek(self.directoryOffset) self.file.write(directory)
All tables must have been written to disk. Now write the directory.
close
python
fonttools/fonttools
Lib/fontTools/ttLib/sfnt.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/sfnt.py
MIT
def calcChecksum(data): """Calculate the checksum for an arbitrary block of data. If the data length is not a multiple of four, it assumes it is to be padded with null byte. >>> print(calcChecksum(b"abcd")) 1633837924 >>> print(calcChecksum(b"abcdxyz")) 3655064932 """ remainder = len(data) % 4 if remainder: data += b"\0" * (4 - remainder) value = 0 blockSize = 4096 assert blockSize % 4 == 0 for i in range(0, len(data), blockSize): block = data[i : i + blockSize] longs = struct.unpack(">%dL" % (len(block) // 4), block) value = (value + sum(longs)) & 0xFFFFFFFF return value
Calculate the checksum for an arbitrary block of data. If the data length is not a multiple of four, it assumes it is to be padded with null byte. >>> print(calcChecksum(b"abcd")) 1633837924 >>> print(calcChecksum(b"abcdxyz")) 3655064932
calcChecksum
python
fonttools/fonttools
Lib/fontTools/ttLib/sfnt.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/sfnt.py
MIT
def save(self, file, shareTables=True): """Save the font to disk. Similarly to the constructor, the 'file' argument can be either a pathname or a writable file object. """ if not hasattr(file, "write"): final = None file = open(file, "wb") else: # assume "file" is a writable file object # write to a temporary stream to allow saving to unseekable streams final = file file = BytesIO() tableCache = {} if shareTables else None offsets_offset = writeTTCHeader(file, len(self.fonts)) offsets = [] for font in self.fonts: offsets.append(file.tell()) font._save(file, tableCache=tableCache) file.seek(0, 2) file.seek(offsets_offset) file.write(struct.pack(">%dL" % len(self.fonts), *offsets)) if final: final.write(file.getvalue()) file.close()
Save the font to disk. Similarly to the constructor, the 'file' argument can be either a pathname or a writable file object.
save
python
fonttools/fonttools
Lib/fontTools/ttLib/ttCollection.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttCollection.py
MIT
def save(self, file, reorderTables=True): """Save the font to disk. Args: file: Similarly to the constructor, can be either a pathname or a writable file object. reorderTables (Option[bool]): If true (the default), reorder the tables, sorting them by tag (recommended by the OpenType specification). If false, retain the original font order. If None, reorder by table dependency (fastest). """ if not hasattr(file, "write"): if self.lazy and self.reader.file.name == file: raise TTLibError("Can't overwrite TTFont when 'lazy' attribute is True") createStream = True else: # assume "file" is a writable file object createStream = False tmp = BytesIO() writer_reordersTables = self._save(tmp) if not ( reorderTables is None or writer_reordersTables or (reorderTables is False and self.reader is None) ): if reorderTables is False: # sort tables using the original font's order tableOrder = list(self.reader.keys()) else: # use the recommended order from the OpenType specification tableOrder = None tmp.flush() tmp2 = BytesIO() reorderFontTables(tmp, tmp2, tableOrder) tmp.close() tmp = tmp2 if createStream: # "file" is a path with open(file, "wb") as file: file.write(tmp.getvalue()) else: file.write(tmp.getvalue()) tmp.close()
Save the font to disk. Args: file: Similarly to the constructor, can be either a pathname or a writable file object. reorderTables (Option[bool]): If true (the default), reorder the tables, sorting them by tag (recommended by the OpenType specification). If false, retain the original font order. If None, reorder by table dependency (fastest).
save
python
fonttools/fonttools
Lib/fontTools/ttLib/ttFont.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py
MIT
def _save(self, file, tableCache=None): """Internal function, to be shared by save() and TTCollection.save()""" if self.recalcTimestamp and "head" in self: self[ "head" ] # make sure 'head' is loaded so the recalculation is actually done tags = list(self.keys()) if "GlyphOrder" in tags: tags.remove("GlyphOrder") numTables = len(tags) # write to a temporary stream to allow saving to unseekable streams writer = SFNTWriter( file, numTables, self.sfntVersion, self.flavor, self.flavorData ) done = [] for tag in tags: self._writeTable(tag, writer, done, tableCache) writer.close() return writer.reordersTables()
Internal function, to be shared by save() and TTCollection.save()
_save
python
fonttools/fonttools
Lib/fontTools/ttLib/ttFont.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py
MIT
def saveXML(self, fileOrPath, newlinestr="\n", **kwargs): """Export the font as TTX (an XML-based text file), or as a series of text files when splitTables is true. In the latter case, the 'fileOrPath' argument should be a path to a directory. The 'tables' argument must either be false (dump all tables) or a list of tables to dump. The 'skipTables' argument may be a list of tables to skip, but only when the 'tables' argument is false. """ writer = xmlWriter.XMLWriter(fileOrPath, newlinestr=newlinestr) self._saveXML(writer, **kwargs) writer.close()
Export the font as TTX (an XML-based text file), or as a series of text files when splitTables is true. In the latter case, the 'fileOrPath' argument should be a path to a directory. The 'tables' argument must either be false (dump all tables) or a list of tables to dump. The 'skipTables' argument may be a list of tables to skip, but only when the 'tables' argument is false.
saveXML
python
fonttools/fonttools
Lib/fontTools/ttLib/ttFont.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py
MIT
def importXML(self, fileOrPath, quiet=None): """Import a TTX file (an XML-based text format), so as to recreate a font object. """ if quiet is not None: deprecateArgument("quiet", "configure logging instead") if "maxp" in self and "post" in self: # Make sure the glyph order is loaded, as it otherwise gets # lost if the XML doesn't contain the glyph order, yet does # contain the table which was originally used to extract the # glyph names from (ie. 'post', 'cmap' or 'CFF '). self.getGlyphOrder() from fontTools.misc import xmlReader reader = xmlReader.XMLReader(fileOrPath, self) reader.read()
Import a TTX file (an XML-based text format), so as to recreate a font object.
importXML
python
fonttools/fonttools
Lib/fontTools/ttLib/ttFont.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py
MIT
def has_key(self, tag): """Test if the table identified by ``tag`` is present in the font. As well as this method, ``tag in font`` can also be used to determine the presence of the table.""" if self.isLoaded(tag): return True elif self.reader and tag in self.reader: return True elif tag == "GlyphOrder": return True else: return False
Test if the table identified by ``tag`` is present in the font. As well as this method, ``tag in font`` can also be used to determine the presence of the table.
has_key
python
fonttools/fonttools
Lib/fontTools/ttLib/ttFont.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py
MIT