diff --git a/Lib/fontTools/ttLib/tables/TupleVariation.py b/Lib/fontTools/ttLib/tables/TupleVariation.py
index e2ceba4d1..fb2131b2b 100644
--- a/Lib/fontTools/ttLib/tables/TupleVariation.py
+++ b/Lib/fontTools/ttLib/tables/TupleVariation.py
@@ -30,6 +30,7 @@ log = logging.getLogger(__name__)
class TupleVariation(object):
+
def __init__(self, axes, coordinates):
self.axes = axes.copy()
self.coordinates = coordinates[:]
@@ -54,10 +55,7 @@ class TupleVariation(object):
If the result is False, the TupleVariation can be omitted from the font
without making any visible difference.
"""
- for c in self.coordinates:
- if c is not None:
- return True
- return False
+ return any(c is not None for c in self.coordinates)
def toXML(self, writer, axisTags):
writer.begintag("tuple")
@@ -306,7 +304,7 @@ class TupleVariation(object):
elif type(c) is int:
deltaX.append(c)
elif c is not None:
- raise ValueError("invalid type of delta: %s" % type(c))
+ raise TypeError("invalid type of delta: %s" % type(c))
return self.compileDeltaValues_(deltaX) + self.compileDeltaValues_(deltaY)
@staticmethod
@@ -446,6 +444,125 @@ class TupleVariation(object):
size += axisCount * 4
return size
+ def getCoordWidth(self):
+ """ Return 2 if coordinates are (x, y) as in gvar, 1 if single values
+ as in cvar, or 0 if empty.
+ """
+ firstDelta = next((c for c in self.coordinates if c is not None), None)
+ if firstDelta is None:
+ return 0 # empty or has no impact
+ if type(firstDelta) in (int, float):
+ return 1
+ if type(firstDelta) is tuple and len(firstDelta) == 2:
+ return 2
+ raise TypeError(
+ "invalid type of delta; expected (int or float) number, or "
+ "Tuple[number, number]: %r" % firstDelta
+ )
+
+ def scaleDeltas(self, scalar):
+ if scalar == 1.0:
+ return # no change
+ coordWidth = self.getCoordWidth()
+ self.coordinates = [
+ None
+ if d is None
+ else d * scalar
+ if coordWidth == 1
+ else (d[0] * scalar, d[1] * scalar)
+ for d in self.coordinates
+ ]
+
+ def roundDeltas(self):
+ coordWidth = self.getCoordWidth()
+ self.coordinates = [
+ None
+ if d is None
+ else otRound(d)
+ if coordWidth == 1
+ else (otRound(d[0]), otRound(d[1]))
+ for d in self.coordinates
+ ]
+
+ def calcInferredDeltas(self, origCoords, endPts):
+ from fontTools.varLib.iup import iup_delta
+
+ if self.getCoordWidth() == 1:
+ raise TypeError(
+ "Only 'gvar' TupleVariation can have inferred deltas"
+ )
+ if None in self.coordinates:
+ if len(self.coordinates) != len(origCoords):
+ raise ValueError(
+ "Expected len(origCoords) == %d; found %d"
+ % (len(self.coordinates), len(origCoords))
+ )
+ self.coordinates = iup_delta(self.coordinates, origCoords, endPts)
+
+ def optimize(self, origCoords, endPts, tolerance=0.5, isComposite=False):
+ from fontTools.varLib.iup import iup_delta_optimize
+
+ if None in self.coordinates:
+ return # already optimized
+
+ deltaOpt = iup_delta_optimize(
+ self.coordinates, origCoords, endPts, tolerance=tolerance
+ )
+ if None in deltaOpt:
+ if isComposite and all(d is None for d in deltaOpt):
+ # Fix for macOS composites
+ # https://github.com/fonttools/fonttools/issues/1381
+ deltaOpt = [(0, 0)] + [None] * (len(deltaOpt) - 1)
+ # Use "optimized" version only if smaller...
+ varOpt = TupleVariation(self.axes, deltaOpt)
+
+ # Shouldn't matter that this is different from fvar...?
+ axisTags = sorted(self.axes.keys())
+ tupleData, auxData, _ = self.compile(axisTags, [], None)
+ unoptimizedLength = len(tupleData) + len(auxData)
+ tupleData, auxData, _ = varOpt.compile(axisTags, [], None)
+ optimizedLength = len(tupleData) + len(auxData)
+
+ if optimizedLength < unoptimizedLength:
+ self.coordinates = varOpt.coordinates
+
+ def __iadd__(self, other):
+ if not isinstance(other, TupleVariation):
+ return NotImplemented
+ deltas1 = self.coordinates
+ length = len(deltas1)
+ deltas2 = other.coordinates
+ if len(deltas2) != length:
+ raise ValueError(
+ "cannot sum TupleVariation deltas with different lengths"
+ )
+ # 'None' values have different meanings in gvar vs cvar TupleVariations:
+ # within the gvar, when deltas are not provided explicitly for some points,
+ # they need to be inferred; whereas for the 'cvar' table, if deltas are not
+ # provided for some CVT values, then no adjustments are made (i.e. None == 0).
+ # Thus, we cannot sum deltas for gvar TupleVariations if they contain
+ # inferred inferred deltas (the latter need to be computed first using
+ # 'calcInferredDeltas' method), but we can treat 'None' values in cvar
+ # deltas as if they are zeros.
+ if self.getCoordWidth() == 2:
+ for i, d2 in zip(range(length), deltas2):
+ d1 = deltas1[i]
+ try:
+ deltas1[i] = (d1[0] + d2[0], d1[1] + d2[1])
+ except TypeError:
+ raise ValueError(
+ "cannot sum gvar deltas with inferred points"
+ )
+ else:
+ for i, d2 in zip(range(length), deltas2):
+ d1 = deltas1[i]
+ if d1 is not None and d2 is not None:
+ deltas1[i] = d1 + d2
+ elif d1 is None and d2 is not None:
+ deltas1[i] = d2
+ # elif d2 is None do nothing
+ return self
+
def decompileSharedTuples(axisTags, sharedTupleCount, data, offset):
result = []
diff --git a/Lib/fontTools/ttLib/tables/_g_l_y_f.py b/Lib/fontTools/ttLib/tables/_g_l_y_f.py
index 83d5315bb..7d2c16e6d 100644
--- a/Lib/fontTools/ttLib/tables/_g_l_y_f.py
+++ b/Lib/fontTools/ttLib/tables/_g_l_y_f.py
@@ -243,6 +243,162 @@ class table__g_l_y_f(DefaultTable.DefaultTable):
assert len(self.glyphOrder) == len(self.glyphs)
return len(self.glyphs)
+ def getPhantomPoints(self, glyphName, ttFont, defaultVerticalOrigin=None):
+ """Compute the four "phantom points" for the given glyph from its bounding box
+ and the horizontal and vertical advance widths and sidebearings stored in the
+ ttFont's "hmtx" and "vmtx" tables.
+
+ If the ttFont doesn't contain a "vmtx" table, the hhea.ascent is used as the
+ vertical origin, and the head.unitsPerEm as the vertical advance.
+
+ The "defaultVerticalOrigin" (Optional[int]) is needed when the ttFont contains
+ neither a "vmtx" nor an "hhea" table, as may happen with 'sparse' masters.
+ The value should be the hhea.ascent of the default master.
+
+ https://docs.microsoft.com/en-us/typography/opentype/spec/tt_instructing_glyphs#phantoms
+ """
+ glyph = self[glyphName]
+ assert glyphName in ttFont["hmtx"].metrics, ttFont["hmtx"].metrics
+ horizontalAdvanceWidth, leftSideBearing = ttFont["hmtx"].metrics[glyphName]
+ if not hasattr(glyph, 'xMin'):
+ glyph.recalcBounds(self)
+ leftSideX = glyph.xMin - leftSideBearing
+ rightSideX = leftSideX + horizontalAdvanceWidth
+ if "vmtx" in ttFont:
+ verticalAdvanceWidth, topSideBearing = ttFont["vmtx"].metrics[glyphName]
+ topSideY = topSideBearing + glyph.yMax
+ else:
+ # without vmtx, use ascent as vertical origin and UPEM as vertical advance
+ # like HarfBuzz does
+ verticalAdvanceWidth = ttFont["head"].unitsPerEm
+ if "hhea" in ttFont:
+ topSideY = ttFont["hhea"].ascent
+ else:
+ # sparse masters may not contain an hhea table; use the ascent
+ # of the default master as the vertical origin
+ if defaultVerticalOrigin is not None:
+ topSideY = defaultVerticalOrigin
+ else:
+ log.warning(
+ "font is missing both 'vmtx' and 'hhea' tables, "
+ "and no 'defaultVerticalOrigin' was provided; "
+ "the vertical phantom points may be incorrect."
+ )
+ topSideY = verticalAdvanceWidth
+ bottomSideY = topSideY - verticalAdvanceWidth
+ return [
+ (leftSideX, 0),
+ (rightSideX, 0),
+ (0, topSideY),
+ (0, bottomSideY),
+ ]
+
+ def getCoordinatesAndControls(self, glyphName, ttFont, defaultVerticalOrigin=None):
+ """Return glyph coordinates and controls as expected by "gvar" table.
+
+ The coordinates includes four "phantom points" for the glyph metrics,
+ as mandated by the "gvar" spec.
+
+ The glyph controls is a namedtuple with the following attributes:
+ - numberOfContours: -1 for composite glyphs.
+ - endPts: list of indices of end points for each contour in simple
+ glyphs, or component indices in composite glyphs (used for IUP
+ optimization).
+ - flags: array of contour point flags for simple glyphs (None for
+ composite glyphs).
+ - components: list of base glyph names (str) for each component in
+ composite glyphs (None for simple glyphs).
+
+ The "ttFont" and "defaultVerticalOrigin" args are used to compute the
+ "phantom points" (see "getPhantomPoints" method).
+
+ Return None if the requested glyphName is not present.
+ """
+ if glyphName not in self.glyphs:
+ return None
+ glyph = self[glyphName]
+ if glyph.isComposite():
+ coords = GlyphCoordinates(
+ [(getattr(c, 'x', 0), getattr(c, 'y', 0)) for c in glyph.components]
+ )
+ controls = _GlyphControls(
+ numberOfContours=glyph.numberOfContours,
+ endPts=list(range(len(glyph.components))),
+ flags=None,
+ components=[c.glyphName for c in glyph.components],
+ )
+ else:
+ coords, endPts, flags = glyph.getCoordinates(self)
+ coords = coords.copy()
+ controls = _GlyphControls(
+ numberOfContours=glyph.numberOfContours,
+ endPts=endPts,
+ flags=flags,
+ components=None,
+ )
+ # Add phantom points for (left, right, top, bottom) positions.
+ phantomPoints = self.getPhantomPoints(
+ glyphName, ttFont, defaultVerticalOrigin=defaultVerticalOrigin
+ )
+ coords.extend(phantomPoints)
+ return coords, controls
+
+ def setCoordinates(self, glyphName, coord, ttFont):
+ """Set coordinates and metrics for the given glyph.
+
+ "coord" is an array of GlyphCoordinates which must include the "phantom
+ points" as the last four coordinates.
+
+ Both the horizontal/vertical advances and left/top sidebearings in "hmtx"
+ and "vmtx" tables (if any) are updated from four phantom points and
+ the glyph's bounding boxes.
+ """
+ # TODO: Create new glyph if not already present
+ assert glyphName in self.glyphs
+ glyph = self[glyphName]
+
+ # Handle phantom points for (left, right, top, bottom) positions.
+ assert len(coord) >= 4
+ leftSideX = coord[-4][0]
+ rightSideX = coord[-3][0]
+ topSideY = coord[-2][1]
+ bottomSideY = coord[-1][1]
+
+ coord = coord[:-4]
+
+ if glyph.isComposite():
+ assert len(coord) == len(glyph.components)
+ for p, comp in zip(coord, glyph.components):
+ if hasattr(comp, 'x'):
+ comp.x, comp.y = p
+ elif glyph.numberOfContours == 0:
+ assert len(coord) == 0
+ else:
+ assert len(coord) == len(glyph.coordinates)
+ glyph.coordinates = GlyphCoordinates(coord)
+
+ glyph.recalcBounds(self)
+
+ horizontalAdvanceWidth = otRound(rightSideX - leftSideX)
+ if horizontalAdvanceWidth < 0:
+ # unlikely, but it can happen, see:
+ # https://github.com/fonttools/fonttools/pull/1198
+ horizontalAdvanceWidth = 0
+ leftSideBearing = otRound(glyph.xMin - leftSideX)
+ ttFont["hmtx"].metrics[glyphName] = horizontalAdvanceWidth, leftSideBearing
+
+ if "vmtx" in ttFont:
+ verticalAdvanceWidth = otRound(topSideY - bottomSideY)
+ if verticalAdvanceWidth < 0: # unlikely but do the same as horizontal
+ verticalAdvanceWidth = 0
+ topSideBearing = otRound(topSideY - glyph.yMax)
+ ttFont["vmtx"].metrics[glyphName] = verticalAdvanceWidth, topSideBearing
+
+
+_GlyphControls = namedtuple(
+ "_GlyphControls", "numberOfContours endPts flags components"
+)
+
glyphHeaderFormat = """
> # big endian
diff --git a/Lib/fontTools/ttLib/tables/_g_v_a_r.py b/Lib/fontTools/ttLib/tables/_g_v_a_r.py
index f9c9e5286..7a02f8f5b 100644
--- a/Lib/fontTools/ttLib/tables/_g_v_a_r.py
+++ b/Lib/fontTools/ttLib/tables/_g_v_a_r.py
@@ -217,8 +217,9 @@ def compileGlyph_(variations, pointCount, axisTags, sharedCoordIndices):
variations, pointCount, axisTags, sharedCoordIndices)
if tupleVariationCount == 0:
return b""
- result = (struct.pack(">HH", tupleVariationCount, 4 + len(tuples)) +
- tuples + data)
+ result = (
+ struct.pack(">HH", tupleVariationCount, 4 + len(tuples)) + tuples + data
+ )
if len(result) % 2 != 0:
result = result + b"\0" # padding
return result
@@ -229,6 +230,8 @@ def decompileGlyph_(pointCount, sharedTuples, axisTags, data):
return []
tupleVariationCount, offsetToData = struct.unpack(">HH", data[:4])
dataPos = offsetToData
- return tv.decompileTupleVariationStore("gvar", axisTags,
- tupleVariationCount, pointCount,
- sharedTuples, data, 4, offsetToData)
+ return tv.decompileTupleVariationStore(
+ "gvar", axisTags,
+ tupleVariationCount, pointCount,
+ sharedTuples, data, 4, offsetToData
+ )
diff --git a/Lib/fontTools/varLib/__init__.py b/Lib/fontTools/varLib/__init__.py
index b428aeb15..5a881495f 100644
--- a/Lib/fontTools/varLib/__init__.py
+++ b/Lib/fontTools/varLib/__init__.py
@@ -209,102 +209,6 @@ def _add_stat(font, axes):
stat.ElidedFallbackNameID = 2
-def _get_phantom_points(font, glyphName, defaultVerticalOrigin=None):
- glyf = font["glyf"]
- glyph = glyf[glyphName]
- horizontalAdvanceWidth, leftSideBearing = font["hmtx"].metrics[glyphName]
- if not hasattr(glyph, 'xMin'):
- glyph.recalcBounds(glyf)
- leftSideX = glyph.xMin - leftSideBearing
- rightSideX = leftSideX + horizontalAdvanceWidth
- if "vmtx" in font:
- verticalAdvanceWidth, topSideBearing = font["vmtx"].metrics[glyphName]
- topSideY = topSideBearing + glyph.yMax
- else:
- # without vmtx, use ascent as vertical origin and UPEM as vertical advance
- # like HarfBuzz does
- verticalAdvanceWidth = font["head"].unitsPerEm
- try:
- topSideY = font["hhea"].ascent
- except KeyError:
- # sparse masters may not contain an hhea table; use the ascent
- # of the default master as the vertical origin
- assert defaultVerticalOrigin is not None
- topSideY = defaultVerticalOrigin
- bottomSideY = topSideY - verticalAdvanceWidth
- return [
- (leftSideX, 0),
- (rightSideX, 0),
- (0, topSideY),
- (0, bottomSideY),
- ]
-
-
-# TODO Move to glyf or gvar table proper
-def _GetCoordinates(font, glyphName, defaultVerticalOrigin=None):
- """font, glyphName --> glyph coordinates as expected by "gvar" table
-
- The result includes four "phantom points" for the glyph metrics,
- as mandated by the "gvar" spec.
- """
- glyf = font["glyf"]
- if glyphName not in glyf.glyphs: return None
- glyph = glyf[glyphName]
- if glyph.isComposite():
- coord = GlyphCoordinates([(getattr(c, 'x', 0),getattr(c, 'y', 0)) for c in glyph.components])
- control = (glyph.numberOfContours,[c.glyphName for c in glyph.components])
- else:
- allData = glyph.getCoordinates(glyf)
- coord = allData[0]
- control = (glyph.numberOfContours,)+allData[1:]
-
- # Add phantom points for (left, right, top, bottom) positions.
- phantomPoints = _get_phantom_points(font, glyphName, defaultVerticalOrigin)
- coord = coord.copy()
- coord.extend(phantomPoints)
-
- return coord, control
-
-# TODO Move to glyf or gvar table proper
-def _SetCoordinates(font, glyphName, coord):
- glyf = font["glyf"]
- assert glyphName in glyf.glyphs
- glyph = glyf[glyphName]
-
- # Handle phantom points for (left, right, top, bottom) positions.
- assert len(coord) >= 4
- if not hasattr(glyph, 'xMin'):
- glyph.recalcBounds(glyf)
- leftSideX = coord[-4][0]
- rightSideX = coord[-3][0]
- topSideY = coord[-2][1]
- bottomSideY = coord[-1][1]
-
- for _ in range(4):
- del coord[-1]
-
- if glyph.isComposite():
- assert len(coord) == len(glyph.components)
- for p,comp in zip(coord, glyph.components):
- if hasattr(comp, 'x'):
- comp.x,comp.y = p
- elif glyph.numberOfContours is 0:
- assert len(coord) == 0
- else:
- assert len(coord) == len(glyph.coordinates)
- glyph.coordinates = coord
-
- glyph.recalcBounds(glyf)
-
- horizontalAdvanceWidth = otRound(rightSideX - leftSideX)
- if horizontalAdvanceWidth < 0:
- # unlikely, but it can happen, see:
- # https://github.com/fonttools/fonttools/pull/1198
- horizontalAdvanceWidth = 0
- leftSideBearing = otRound(glyph.xMin - leftSideX)
- # XXX Handle vertical
- font["hmtx"].metrics[glyphName] = horizontalAdvanceWidth, leftSideBearing
-
def _add_gvar(font, masterModel, master_ttfs, tolerance=0.5, optimize=True):
assert tolerance >= 0
@@ -319,13 +223,13 @@ def _add_gvar(font, masterModel, master_ttfs, tolerance=0.5, optimize=True):
glyf = font['glyf']
# use hhea.ascent of base master as default vertical origin when vmtx is missing
- defaultVerticalOrigin = font['hhea'].ascent
+ baseAscent = font['hhea'].ascent
for glyph in font.getGlyphOrder():
isComposite = glyf[glyph].isComposite()
allData = [
- _GetCoordinates(m, glyph, defaultVerticalOrigin=defaultVerticalOrigin)
+ m["glyf"].getCoordinatesAndControls(glyph, m, defaultVerticalOrigin=baseAscent)
for m in master_ttfs
]
model, allData = masterModel.getSubModel(allData)
@@ -346,7 +250,7 @@ def _add_gvar(font, masterModel, master_ttfs, tolerance=0.5, optimize=True):
# Prepare for IUP optimization
origCoords = deltas[0]
- endPts = control[1] if control[0] >= 1 else list(range(len(control[1])))
+ endPts = control.endPts
for i,(delta,support) in enumerate(zip(deltas[1:], supports[1:])):
if all(abs(v) <= tolerance for v in delta.array) and not isComposite:
@@ -462,20 +366,20 @@ def _merge_TTHinting(font, masterModel, master_ttfs, tolerance=0.5):
var = TupleVariation(support, delta)
cvar.variations.append(var)
-MetricsFields = namedtuple('MetricsFields',
+_MetricsFields = namedtuple('_MetricsFields',
['tableTag', 'metricsTag', 'sb1', 'sb2', 'advMapping', 'vOrigMapping'])
-hvarFields = MetricsFields(tableTag='HVAR', metricsTag='hmtx', sb1='LsbMap',
+HVAR_FIELDS = _MetricsFields(tableTag='HVAR', metricsTag='hmtx', sb1='LsbMap',
sb2='RsbMap', advMapping='AdvWidthMap', vOrigMapping=None)
-vvarFields = MetricsFields(tableTag='VVAR', metricsTag='vmtx', sb1='TsbMap',
+VVAR_FIELDS = _MetricsFields(tableTag='VVAR', metricsTag='vmtx', sb1='TsbMap',
sb2='BsbMap', advMapping='AdvHeightMap', vOrigMapping='VOrgMap')
def _add_HVAR(font, masterModel, master_ttfs, axisTags):
- _add_VHVAR(font, masterModel, master_ttfs, axisTags, hvarFields)
+ _add_VHVAR(font, masterModel, master_ttfs, axisTags, HVAR_FIELDS)
def _add_VVAR(font, masterModel, master_ttfs, axisTags):
- _add_VHVAR(font, masterModel, master_ttfs, axisTags, vvarFields)
+ _add_VHVAR(font, masterModel, master_ttfs, axisTags, VVAR_FIELDS)
def _add_VHVAR(font, masterModel, master_ttfs, axisTags, tableFields):
@@ -692,9 +596,15 @@ def _merge_OTL(font, model, master_fonts, axisTags):
GDEF = font['GDEF'].table
assert GDEF.Version <= 0x00010002
except KeyError:
- font['GDEF']= newTable('GDEF')
+ font['GDEF'] = newTable('GDEF')
GDEFTable = font["GDEF"] = newTable('GDEF')
GDEF = GDEFTable.table = ot.GDEF()
+ GDEF.GlyphClassDef = None
+ GDEF.AttachList = None
+ GDEF.LigCaretList = None
+ GDEF.MarkAttachClassDef = None
+ GDEF.MarkGlyphSetsDef = None
+
GDEF.Version = 0x00010003
GDEF.VarStore = store
diff --git a/Lib/fontTools/varLib/featureVars.py b/Lib/fontTools/varLib/featureVars.py
index e3aa6b6e7..0c6913d31 100644
--- a/Lib/fontTools/varLib/featureVars.py
+++ b/Lib/fontTools/varLib/featureVars.py
@@ -285,6 +285,7 @@ def addFeatureVariationsRaw(font, conditionalSubstitutions):
rvrnFeature = buildFeatureRecord('rvrn', [])
gsub.FeatureList.FeatureRecord.append(rvrnFeature)
+ gsub.FeatureList.FeatureCount = len(gsub.FeatureList.FeatureRecord)
sortFeatureList(gsub)
rvrnFeatureIndex = gsub.FeatureList.FeatureRecord.index(rvrnFeature)
@@ -348,6 +349,7 @@ def buildGSUB():
srec.Script.DefaultLangSys = langrec.LangSys
gsub.ScriptList.ScriptRecord.append(srec)
+ gsub.ScriptList.ScriptCount = 1
gsub.FeatureVariations = None
return fontTable
@@ -382,6 +384,7 @@ def buildSubstitutionLookups(gsub, allSubstitutions):
lookup = buildLookup([buildSingleSubstSubtable(substMap)])
gsub.LookupList.Lookup.append(lookup)
assert gsub.LookupList.Lookup[lookupMap[subst]] is lookup
+ gsub.LookupList.LookupCount = len(gsub.LookupList.Lookup)
return lookupMap
@@ -399,6 +402,7 @@ def buildFeatureRecord(featureTag, lookupListIndices):
fr.FeatureTag = featureTag
fr.Feature = ot.Feature()
fr.Feature.LookupListIndex = lookupListIndices
+ fr.Feature.populateDefaults()
return fr
diff --git a/Lib/fontTools/varLib/instancer.py b/Lib/fontTools/varLib/instancer.py
new file mode 100644
index 000000000..52d62c998
--- /dev/null
+++ b/Lib/fontTools/varLib/instancer.py
@@ -0,0 +1,1037 @@
+""" Partially instantiate a variable font.
+
+The module exports an `instantiateVariableFont` function and CLI that allow to
+create full instances (i.e. static fonts) from variable fonts, as well as "partial"
+variable fonts that only contain a subset of the original variation space.
+
+For example, if you wish to pin the width axis to a given location while keeping
+the rest of the axes, you can do:
+
+$ fonttools varLib.instancer ./NotoSans-VF.ttf wdth=85
+
+See `fonttools varLib.instancer --help` for more info on the CLI options.
+
+The module's entry point is the `instantiateVariableFont` function, which takes
+a TTFont object and a dict specifying a location along either some or all the axes,
+and returns a new TTFont representing respectively a partial or a full instance.
+
+E.g. here's how to pin the wght axis at a given location in a wght+wdth variable
+font, keeping only the deltas associated with the wdth axis:
+
+| >>> from fontTools import ttLib
+| >>> from fontTools.varLib import instancer
+| >>> varfont = ttLib.TTFont("path/to/MyVariableFont.ttf")
+| >>> [a.axisTag for a in partial["fvar"].axes] # the varfont's current axes
+| ['wght', 'wdth']
+| >>> partial = instancer.instantiateVariableFont(varfont, {"wght": 300})
+| >>> [a.axisTag for a in partial["fvar"].axes] # axes left after pinning 'wght'
+| ['wdth']
+
+If the input location specifies all the axes, the resulting instance is no longer
+'variable' (same as using fontools varLib.mutator):
+
+| >>> instance = instancer.instantiateVariableFont(
+| ... varfont, {"wght": 700, "wdth": 67.5}
+| ... )
+| >>> "fvar" not in instance
+| True
+
+If one just want to drop an axis at the default location, without knowing in
+advance what the default value for that axis is, one can pass a `None` value:
+
+| >>> instance = instancer.instantiateVariableFont(varfont, {"wght": None})
+| >>> len(varfont["fvar"].axes)
+| 1
+
+From the console script, this is equivalent to passing `wght=drop` as input.
+
+This module is similar to fontTools.varLib.mutator, which it's intended to supersede.
+Note that, unlike varLib.mutator, when an axis is not mentioned in the input
+location, the varLib.instancer will keep the axis and the corresponding deltas,
+whereas mutator implicitly drops the axis at its default coordinate.
+
+The module currently supports only the first two "levels" of partial instancing,
+with the rest planned to be implemented in the future, namely:
+L1) dropping one or more axes while leaving the default tables unmodified;
+L2) dropping one or more axes while pinning them at non-default locations;
+L3) restricting the range of variation of one or more axes, by setting either
+ a new minimum or maximum, potentially -- though not necessarily -- dropping
+ entire regions of variations that fall completely outside this new range.
+L4) moving the default location of an axis.
+
+Currently only TrueType-flavored variable fonts (i.e. containing 'glyf' table)
+are supported, but support for CFF2 variable fonts will be added soon.
+
+The discussion and implementation of these features are tracked at
+https://github.com/fonttools/fonttools/issues/1537
+"""
+from __future__ import print_function, division, absolute_import
+from fontTools.misc.py23 import *
+from fontTools.misc.fixedTools import floatToFixedToFloat, otRound
+from fontTools.varLib.models import supportScalar, normalizeValue, piecewiseLinearMap
+from fontTools.ttLib import TTFont
+from fontTools.ttLib.tables.TupleVariation import TupleVariation
+from fontTools.ttLib.tables import _g_l_y_f
+from fontTools import varLib
+
+# we import the `subset` module because we use the `prune_lookups` method on the GSUB
+# table class, and that method is only defined dynamically upon importing `subset`
+from fontTools import subset # noqa: F401
+from fontTools.varLib import builder
+from fontTools.varLib.mvar import MVAR_ENTRIES
+from fontTools.varLib.merger import MutatorMerger
+from contextlib import contextmanager
+import collections
+from copy import deepcopy
+import logging
+from itertools import islice
+import os
+import re
+
+
+log = logging.getLogger("fontTools.varLib.instancer")
+
+
+def instantiateTupleVariationStore(variations, location, origCoords=None, endPts=None):
+ """Instantiate TupleVariation list at the given location.
+
+ The 'variations' list of TupleVariation objects is modified in-place.
+ The input location can describe either a full instance (all the axes are assigned an
+ explicit coordinate) or partial (some of the axes are omitted).
+ Tuples that do not participate are kept as they are. Those that have 0 influence
+ at the given location are removed from the variation store.
+ Those that are fully instantiated (i.e. all their axes are being pinned) are also
+ removed from the variation store, their scaled deltas accummulated and returned, so
+ that they can be added by the caller to the default instance's coordinates.
+ Tuples that are only partially instantiated (i.e. not all the axes that they
+ participate in are being pinned) are kept in the store, and their deltas multiplied
+ by the scalar support of the axes to be pinned at the desired location.
+
+ Args:
+ variations: List[TupleVariation] from either 'gvar' or 'cvar'.
+ location: Dict[str, float]: axes coordinates for the full or partial instance.
+ origCoords: GlyphCoordinates: default instance's coordinates for computing 'gvar'
+ inferred points (cf. table__g_l_y_f.getCoordinatesAndControls).
+ endPts: List[int]: indices of contour end points, for inferring 'gvar' deltas.
+
+ Returns:
+ List[float]: the overall delta adjustment after applicable deltas were summed.
+ """
+ newVariations = collections.OrderedDict()
+ for var in variations:
+ # Compute the scalar support of the axes to be pinned at the desired location,
+ # excluding any axes that we are not pinning.
+ # If a TupleVariation doesn't mention an axis, it implies that the axis peak
+ # is 0 (i.e. the axis does not participate).
+ support = {axis: var.axes.pop(axis, (-1, 0, +1)) for axis in location}
+ scalar = supportScalar(location, support)
+ if scalar == 0.0:
+ # no influence, drop the TupleVariation
+ continue
+
+ # compute inferred deltas only for gvar ('origCoords' is None for cvar)
+ if origCoords is not None:
+ var.calcInferredDeltas(origCoords, endPts)
+
+ var.scaleDeltas(scalar)
+
+ # merge TupleVariations with overlapping "tents"
+ axes = tuple(var.axes.items())
+ if axes in newVariations:
+ newVariations[axes] += var
+ else:
+ newVariations[axes] = var
+
+ # drop TupleVariation if all axes have been pinned (var.axes.items() is empty);
+ # its deltas will be added to the default instance's coordinates
+ defaultVar = newVariations.pop(tuple(), None)
+
+ for var in newVariations.values():
+ var.roundDeltas()
+ variations[:] = list(newVariations.values())
+
+ return defaultVar.coordinates if defaultVar is not None else []
+
+
+def instantiateGvarGlyph(varfont, glyphname, location, optimize=True):
+ glyf = varfont["glyf"]
+ coordinates, ctrl = glyf.getCoordinatesAndControls(glyphname, varfont)
+ endPts = ctrl.endPts
+
+ gvar = varfont["gvar"]
+ # when exporting to TTX, a glyph with no variations is omitted; thus when loading
+ # a TTFont from TTX, a glyph that's present in glyf table may be missing from gvar.
+ tupleVarStore = gvar.variations.get(glyphname)
+
+ if tupleVarStore:
+ defaultDeltas = instantiateTupleVariationStore(
+ tupleVarStore, location, coordinates, endPts
+ )
+
+ if defaultDeltas:
+ coordinates += _g_l_y_f.GlyphCoordinates(defaultDeltas)
+
+ # setCoordinates also sets the hmtx/vmtx advance widths and sidebearings from
+ # the four phantom points and glyph bounding boxes.
+ # We call it unconditionally even if a glyph has no variations or no deltas are
+ # applied at this location, in case the glyph's xMin and in turn its sidebearing
+ # have changed. E.g. a composite glyph has no deltas for the component's (x, y)
+ # offset nor for the 4 phantom points (e.g. it's monospaced). Thus its entry in
+ # gvar table is empty; however, the composite's base glyph may have deltas
+ # applied, hence the composite's bbox and left/top sidebearings may need updating
+ # in the instanced font.
+ glyf.setCoordinates(glyphname, coordinates, varfont)
+
+ if not tupleVarStore:
+ if glyphname in gvar.variations:
+ del gvar.variations[glyphname]
+ return
+
+ if optimize:
+ isComposite = glyf[glyphname].isComposite()
+ for var in tupleVarStore:
+ var.optimize(coordinates, endPts, isComposite)
+
+
+def instantiateGvar(varfont, location, optimize=True):
+ log.info("Instantiating glyf/gvar tables")
+
+ gvar = varfont["gvar"]
+ glyf = varfont["glyf"]
+ # Get list of glyph names sorted by component depth.
+ # If a composite glyph is processed before its base glyph, the bounds may
+ # be calculated incorrectly because deltas haven't been applied to the
+ # base glyph yet.
+ glyphnames = sorted(
+ glyf.glyphOrder,
+ key=lambda name: (
+ glyf[name].getCompositeMaxpValues(glyf).maxComponentDepth
+ if glyf[name].isComposite()
+ else 0,
+ name,
+ ),
+ )
+ for glyphname in glyphnames:
+ instantiateGvarGlyph(varfont, glyphname, location, optimize=optimize)
+
+ if not gvar.variations:
+ del varfont["gvar"]
+
+
+def setCvarDeltas(cvt, deltas):
+ for i, delta in enumerate(deltas):
+ if delta:
+ cvt[i] += otRound(delta)
+
+
+def instantiateCvar(varfont, location):
+ log.info("Instantiating cvt/cvar tables")
+
+ cvar = varfont["cvar"]
+
+ defaultDeltas = instantiateTupleVariationStore(cvar.variations, location)
+
+ if defaultDeltas:
+ setCvarDeltas(varfont["cvt "], defaultDeltas)
+
+ if not cvar.variations:
+ del varfont["cvar"]
+
+
+def setMvarDeltas(varfont, deltas):
+ mvar = varfont["MVAR"].table
+ records = mvar.ValueRecord
+ for rec in records:
+ mvarTag = rec.ValueTag
+ if mvarTag not in MVAR_ENTRIES:
+ continue
+ tableTag, itemName = MVAR_ENTRIES[mvarTag]
+ delta = deltas[rec.VarIdx]
+ if delta != 0:
+ setattr(
+ varfont[tableTag],
+ itemName,
+ getattr(varfont[tableTag], itemName) + otRound(delta),
+ )
+
+
+def instantiateMVAR(varfont, location):
+ log.info("Instantiating MVAR table")
+
+ mvar = varfont["MVAR"].table
+ fvarAxes = varfont["fvar"].axes
+ varStore = mvar.VarStore
+ defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, location)
+ setMvarDeltas(varfont, defaultDeltas)
+
+ if varStore.VarRegionList.Region:
+ varIndexMapping = varStore.optimize()
+ for rec in mvar.ValueRecord:
+ rec.VarIdx = varIndexMapping[rec.VarIdx]
+ else:
+ del varfont["MVAR"]
+
+
+def _remapVarIdxMap(table, attrName, varIndexMapping, glyphOrder):
+ oldMapping = getattr(table, attrName).mapping
+ newMapping = [varIndexMapping[oldMapping[glyphName]] for glyphName in glyphOrder]
+ setattr(table, attrName, builder.buildVarIdxMap(newMapping, glyphOrder))
+
+
+# TODO(anthrotype) Add support for HVAR/VVAR in CFF2
+def _instantiateVHVAR(varfont, location, tableFields):
+ tableTag = tableFields.tableTag
+ fvarAxes = varfont["fvar"].axes
+ # Deltas from gvar table have already been applied to the hmtx/vmtx. For full
+ # instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return
+ if set(location).issuperset(axis.axisTag for axis in fvarAxes):
+ log.info("Dropping %s table", tableTag)
+ del varfont[tableTag]
+ return
+
+ log.info("Instantiating %s table", tableTag)
+ vhvar = varfont[tableTag].table
+ varStore = vhvar.VarStore
+ # since deltas were already applied, the return value here is ignored
+ instantiateItemVariationStore(varStore, fvarAxes, location)
+
+ if varStore.VarRegionList.Region:
+ # Only re-optimize VarStore if the HVAR/VVAR already uses indirect AdvWidthMap
+ # or AdvHeightMap. If a direct, implicit glyphID->VariationIndex mapping is
+ # used for advances, skip re-optimizing and maintain original VariationIndex.
+ if getattr(vhvar, tableFields.advMapping):
+ varIndexMapping = varStore.optimize()
+ glyphOrder = varfont.getGlyphOrder()
+ _remapVarIdxMap(vhvar, tableFields.advMapping, varIndexMapping, glyphOrder)
+ if getattr(vhvar, tableFields.sb1): # left or top sidebearings
+ _remapVarIdxMap(vhvar, tableFields.sb1, varIndexMapping, glyphOrder)
+ if getattr(vhvar, tableFields.sb2): # right or bottom sidebearings
+ _remapVarIdxMap(vhvar, tableFields.sb2, varIndexMapping, glyphOrder)
+ if tableTag == "VVAR" and getattr(vhvar, tableFields.vOrigMapping):
+ _remapVarIdxMap(
+ vhvar, tableFields.vOrigMapping, varIndexMapping, glyphOrder
+ )
+ else:
+ del varfont[tableTag]
+
+
+def instantiateHVAR(varfont, location):
+ return _instantiateVHVAR(varfont, location, varLib.HVAR_FIELDS)
+
+
+def instantiateVVAR(varfont, location):
+ return _instantiateVHVAR(varfont, location, varLib.VVAR_FIELDS)
+
+
+class _TupleVarStoreAdapter(object):
+ def __init__(self, regions, axisOrder, tupleVarData, itemCounts):
+ self.regions = regions
+ self.axisOrder = axisOrder
+ self.tupleVarData = tupleVarData
+ self.itemCounts = itemCounts
+
+ @classmethod
+ def fromItemVarStore(cls, itemVarStore, fvarAxes):
+ axisOrder = [axis.axisTag for axis in fvarAxes]
+ regions = [
+ region.get_support(fvarAxes) for region in itemVarStore.VarRegionList.Region
+ ]
+ tupleVarData = []
+ itemCounts = []
+ for varData in itemVarStore.VarData:
+ variations = []
+ varDataRegions = (regions[i] for i in varData.VarRegionIndex)
+ for axes, coordinates in zip(varDataRegions, zip(*varData.Item)):
+ variations.append(TupleVariation(axes, list(coordinates)))
+ tupleVarData.append(variations)
+ itemCounts.append(varData.ItemCount)
+ return cls(regions, axisOrder, tupleVarData, itemCounts)
+
+ def dropAxes(self, axes):
+ prunedRegions = (
+ frozenset(
+ (axisTag, support)
+ for axisTag, support in region.items()
+ if axisTag not in axes
+ )
+ for region in self.regions
+ )
+ # dedup regions while keeping original order
+ uniqueRegions = collections.OrderedDict.fromkeys(prunedRegions)
+ self.regions = [dict(items) for items in uniqueRegions if items]
+ self.axisOrder = [axisTag for axisTag in self.axisOrder if axisTag not in axes]
+
+ def instantiate(self, location):
+ defaultDeltaArray = []
+ for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
+ defaultDeltas = instantiateTupleVariationStore(variations, location)
+ if not defaultDeltas:
+ defaultDeltas = [0] * itemCount
+ defaultDeltaArray.append(defaultDeltas)
+
+ # remove pinned axes from all the regions
+ self.dropAxes(location.keys())
+
+ return defaultDeltaArray
+
+ def asItemVarStore(self):
+ regionOrder = [frozenset(axes.items()) for axes in self.regions]
+ varDatas = []
+ for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
+ if variations:
+ assert len(variations[0].coordinates) == itemCount
+ varRegionIndices = [
+ regionOrder.index(frozenset(var.axes.items())) for var in variations
+ ]
+ varDataItems = list(zip(*(var.coordinates for var in variations)))
+ varDatas.append(
+ builder.buildVarData(varRegionIndices, varDataItems, optimize=False)
+ )
+ else:
+ varDatas.append(
+ builder.buildVarData([], [[] for _ in range(itemCount)])
+ )
+ regionList = builder.buildVarRegionList(self.regions, self.axisOrder)
+ itemVarStore = builder.buildVarStore(regionList, varDatas)
+ # remove unused regions from VarRegionList
+ itemVarStore.prune_regions()
+ return itemVarStore
+
+
+def instantiateItemVariationStore(itemVarStore, fvarAxes, location):
+ """ Compute deltas at partial location, and update varStore in-place.
+
+ Remove regions in which all axes were instanced, and scale the deltas of
+ the remaining regions where only some of the axes were instanced.
+
+ The number of VarData subtables, and the number of items within each, are
+ not modified, in order to keep the existing VariationIndex valid.
+ One may call VarStore.optimize() method after this to further optimize those.
+
+ Args:
+ varStore: An otTables.VarStore object (Item Variation Store)
+ fvarAxes: list of fvar's Axis objects
+ location: Dict[str, float] mapping axis tags to normalized axis coordinates.
+ May not specify coordinates for all the fvar axes.
+
+ Returns:
+ defaultDeltas: to be added to the default instance, of type dict of floats
+ keyed by VariationIndex compound values: i.e. (outer << 16) + inner.
+ """
+ tupleVarStore = _TupleVarStoreAdapter.fromItemVarStore(itemVarStore, fvarAxes)
+ defaultDeltaArray = tupleVarStore.instantiate(location)
+ newItemVarStore = tupleVarStore.asItemVarStore()
+
+ itemVarStore.VarRegionList = newItemVarStore.VarRegionList
+ assert itemVarStore.VarDataCount == newItemVarStore.VarDataCount
+ itemVarStore.VarData = newItemVarStore.VarData
+
+ defaultDeltas = {
+ ((major << 16) + minor): delta
+ for major, deltas in enumerate(defaultDeltaArray)
+ for minor, delta in enumerate(deltas)
+ }
+ return defaultDeltas
+
+
+def instantiateOTL(varfont, location):
+ # TODO(anthrotype) Support partial instancing of JSTF and BASE tables
+
+ if (
+ "GDEF" not in varfont
+ or varfont["GDEF"].table.Version < 0x00010003
+ or not varfont["GDEF"].table.VarStore
+ ):
+ return
+
+ if "GPOS" in varfont:
+ msg = "Instantiating GDEF and GPOS tables"
+ else:
+ msg = "Instantiating GDEF table"
+ log.info(msg)
+
+ gdef = varfont["GDEF"].table
+ varStore = gdef.VarStore
+ fvarAxes = varfont["fvar"].axes
+
+ defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, location)
+
+ # When VF are built, big lookups may overflow and be broken into multiple
+ # subtables. MutatorMerger (which inherits from AligningMerger) reattaches
+ # them upon instancing, in case they can now fit a single subtable (if not,
+ # they will be split again upon compilation).
+ # This 'merger' also works as a 'visitor' that traverses the OTL tables and
+ # calls specific methods when instances of a given type are found.
+ # Specifically, it adds default deltas to GPOS Anchors/ValueRecords and GDEF
+ # LigatureCarets, and optionally deletes all VariationIndex tables if the
+ # VarStore is fully instanced.
+ merger = MutatorMerger(
+ varfont, defaultDeltas, deleteVariations=(not varStore.VarRegionList.Region)
+ )
+ merger.mergeTables(varfont, [varfont], ["GDEF", "GPOS"])
+
+ if varStore.VarRegionList.Region:
+ varIndexMapping = varStore.optimize()
+ gdef.remap_device_varidxes(varIndexMapping)
+ if "GPOS" in varfont:
+ varfont["GPOS"].table.remap_device_varidxes(varIndexMapping)
+ else:
+ # Downgrade GDEF.
+ del gdef.VarStore
+ gdef.Version = 0x00010002
+ if gdef.MarkGlyphSetsDef is None:
+ del gdef.MarkGlyphSetsDef
+ gdef.Version = 0x00010000
+
+ if not (
+ gdef.LigCaretList
+ or gdef.MarkAttachClassDef
+ or gdef.GlyphClassDef
+ or gdef.AttachList
+ or (gdef.Version >= 0x00010002 and gdef.MarkGlyphSetsDef)
+ ):
+ del varfont["GDEF"]
+
+
+def instantiateFeatureVariations(varfont, location):
+ for tableTag in ("GPOS", "GSUB"):
+ if tableTag not in varfont or not hasattr(
+ varfont[tableTag].table, "FeatureVariations"
+ ):
+ continue
+ log.info("Instantiating FeatureVariations of %s table", tableTag)
+ _instantiateFeatureVariations(
+ varfont[tableTag].table, varfont["fvar"].axes, location
+ )
+ # remove unreferenced lookups
+ varfont[tableTag].prune_lookups()
+
+
+def _featureVariationRecordIsUnique(rec, seen):
+ conditionSet = []
+ for cond in rec.ConditionSet.ConditionTable:
+ if cond.Format != 1:
+ # can't tell whether this is duplicate, assume is unique
+ return True
+ conditionSet.append(
+ (cond.AxisIndex, cond.FilterRangeMinValue, cond.FilterRangeMaxValue)
+ )
+ # besides the set of conditions, we also include the FeatureTableSubstitution
+ # version to identify unique FeatureVariationRecords, even though only one
+ # version is currently defined. It's theoretically possible that multiple
+ # records with same conditions but different substitution table version be
+ # present in the same font for backward compatibility.
+ recordKey = frozenset([rec.FeatureTableSubstitution.Version] + conditionSet)
+ if recordKey in seen:
+ return False
+ else:
+ seen.add(recordKey) # side effect
+ return True
+
+
+def _instantiateFeatureVariationRecord(
+ record, recIdx, location, fvarAxes, axisIndexMap
+):
+ shouldKeep = False
+ applies = True
+ newConditions = []
+ for i, condition in enumerate(record.ConditionSet.ConditionTable):
+ if condition.Format == 1:
+ axisIdx = condition.AxisIndex
+ axisTag = fvarAxes[axisIdx].axisTag
+ if axisTag in location:
+ minValue = condition.FilterRangeMinValue
+ maxValue = condition.FilterRangeMaxValue
+ v = location[axisTag]
+ if not (minValue <= v <= maxValue):
+ # condition not met so remove entire record
+ applies = False
+ newConditions = None
+ break
+ else:
+ # axis not pinned, keep condition with remapped axis index
+ applies = False
+ condition.AxisIndex = axisIndexMap[axisTag]
+ newConditions.append(condition)
+ else:
+ log.warning(
+ "Condition table {0} of FeatureVariationRecord {1} has "
+ "unsupported format ({2}); ignored".format(i, recIdx, condition.Format)
+ )
+ applies = False
+ newConditions.append(condition)
+
+ if newConditions:
+ record.ConditionSet.ConditionTable = newConditions
+ shouldKeep = True
+
+ return applies, shouldKeep
+
+
+def _instantiateFeatureVariations(table, fvarAxes, location):
+ pinnedAxes = set(location.keys())
+ axisOrder = [axis.axisTag for axis in fvarAxes if axis.axisTag not in pinnedAxes]
+ axisIndexMap = {axisTag: axisOrder.index(axisTag) for axisTag in axisOrder}
+
+ featureVariationApplied = False
+ uniqueRecords = set()
+ newRecords = []
+
+ for i, record in enumerate(table.FeatureVariations.FeatureVariationRecord):
+ applies, shouldKeep = _instantiateFeatureVariationRecord(
+ record, i, location, fvarAxes, axisIndexMap
+ )
+ if shouldKeep:
+ if _featureVariationRecordIsUnique(record, uniqueRecords):
+ newRecords.append(record)
+
+ if applies and not featureVariationApplied:
+ assert record.FeatureTableSubstitution.Version == 0x00010000
+ for rec in record.FeatureTableSubstitution.SubstitutionRecord:
+ table.FeatureList.FeatureRecord[rec.FeatureIndex].Feature = rec.Feature
+ # Set variations only once
+ featureVariationApplied = True
+
+ if newRecords:
+ table.FeatureVariations.FeatureVariationRecord = newRecords
+ table.FeatureVariations.FeatureVariationCount = len(newRecords)
+ else:
+ del table.FeatureVariations
+
+
+def instantiateAvar(varfont, location):
+ segments = varfont["avar"].segments
+
+ # drop table if we instantiate all the axes
+ if set(location).issuperset(segments):
+ log.info("Dropping avar table")
+ del varfont["avar"]
+ return
+
+ log.info("Instantiating avar table")
+ for axis in location:
+ if axis in segments:
+ del segments[axis]
+
+
+def instantiateFvar(varfont, location):
+ # 'location' dict must contain user-space (non-normalized) coordinates
+
+ fvar = varfont["fvar"]
+
+ # drop table if we instantiate all the axes
+ if set(location).issuperset(axis.axisTag for axis in fvar.axes):
+ log.info("Dropping fvar table")
+ del varfont["fvar"]
+ return
+
+ log.info("Instantiating fvar table")
+
+ fvar.axes = [axis for axis in fvar.axes if axis.axisTag not in location]
+
+ # only keep NamedInstances whose coordinates == pinned axis location
+ instances = []
+ for instance in fvar.instances:
+ if any(instance.coordinates[axis] != value for axis, value in location.items()):
+ continue
+ for axis in location:
+ del instance.coordinates[axis]
+ instances.append(instance)
+ fvar.instances = instances
+
+
+def instantiateSTAT(varfont, location):
+ pinnedAxes = set(location.keys())
+
+ stat = varfont["STAT"].table
+ if not stat.DesignAxisRecord:
+ return # skip empty STAT table
+
+ designAxes = stat.DesignAxisRecord.Axis
+ pinnedAxisIndices = {
+ i for i, axis in enumerate(designAxes) if axis.AxisTag in pinnedAxes
+ }
+
+ if len(pinnedAxisIndices) == len(designAxes):
+ log.info("Dropping STAT table")
+ del varfont["STAT"]
+ return
+
+ log.info("Instantiating STAT table")
+
+ # only keep DesignAxis that were not instanced, and build a mapping from old
+ # to new axis indices
+ newDesignAxes = []
+ axisIndexMap = {}
+ for i, axis in enumerate(designAxes):
+ if i not in pinnedAxisIndices:
+ axisIndexMap[i] = len(newDesignAxes)
+ newDesignAxes.append(axis)
+
+ if stat.AxisValueArray and stat.AxisValueArray.AxisValue:
+ # drop all AxisValue tables that reference any of the pinned axes
+ newAxisValueTables = []
+ for axisValueTable in stat.AxisValueArray.AxisValue:
+ if axisValueTable.Format in (1, 2, 3):
+ if axisValueTable.AxisIndex in pinnedAxisIndices:
+ continue
+ axisValueTable.AxisIndex = axisIndexMap[axisValueTable.AxisIndex]
+ newAxisValueTables.append(axisValueTable)
+ elif axisValueTable.Format == 4:
+ if any(
+ rec.AxisIndex in pinnedAxisIndices
+ for rec in axisValueTable.AxisValueRecord
+ ):
+ continue
+ for rec in axisValueTable.AxisValueRecord:
+ rec.AxisIndex = axisIndexMap[rec.AxisIndex]
+ newAxisValueTables.append(axisValueTable)
+ else:
+ raise NotImplementedError(axisValueTable.Format)
+ stat.AxisValueArray.AxisValue = newAxisValueTables
+ stat.AxisValueCount = len(stat.AxisValueArray.AxisValue)
+
+ stat.DesignAxisRecord.Axis[:] = newDesignAxes
+ stat.DesignAxisCount = len(stat.DesignAxisRecord.Axis)
+
+
+def getVariationNameIDs(varfont):
+ used = []
+ if "fvar" in varfont:
+ fvar = varfont["fvar"]
+ for axis in fvar.axes:
+ used.append(axis.axisNameID)
+ for instance in fvar.instances:
+ used.append(instance.subfamilyNameID)
+ if instance.postscriptNameID != 0xFFFF:
+ used.append(instance.postscriptNameID)
+ if "STAT" in varfont:
+ stat = varfont["STAT"].table
+ for axis in stat.DesignAxisRecord.Axis if stat.DesignAxisRecord else ():
+ used.append(axis.AxisNameID)
+ for value in stat.AxisValueArray.AxisValue if stat.AxisValueArray else ():
+ used.append(value.ValueNameID)
+ # nameIDs <= 255 are reserved by OT spec so we don't touch them
+ return {nameID for nameID in used if nameID > 255}
+
+
+@contextmanager
+def pruningUnusedNames(varfont):
+ origNameIDs = getVariationNameIDs(varfont)
+
+ yield
+
+ log.info("Pruning name table")
+ exclude = origNameIDs - getVariationNameIDs(varfont)
+ varfont["name"].names[:] = [
+ record for record in varfont["name"].names if record.nameID not in exclude
+ ]
+ if "ltag" in varfont:
+ # Drop the whole 'ltag' table if all the language-dependent Unicode name
+ # records that reference it have been dropped.
+ # TODO: Only prune unused ltag tags, renumerating langIDs accordingly.
+ # Note ltag can also be used by feat or morx tables, so check those too.
+ if not any(
+ record
+ for record in varfont["name"].names
+ if record.platformID == 0 and record.langID != 0xFFFF
+ ):
+ del varfont["ltag"]
+
+
+def setMacOverlapFlags(glyfTable):
+ flagOverlapCompound = _g_l_y_f.OVERLAP_COMPOUND
+ flagOverlapSimple = _g_l_y_f.flagOverlapSimple
+ for glyphName in glyfTable.keys():
+ glyph = glyfTable[glyphName]
+ # Set OVERLAP_COMPOUND bit for compound glyphs
+ if glyph.isComposite():
+ glyph.components[0].flags |= flagOverlapCompound
+ # Set OVERLAP_SIMPLE bit for simple glyphs
+ elif glyph.numberOfContours > 0:
+ glyph.flags[0] |= flagOverlapSimple
+
+
+def normalize(value, triple, avarMapping):
+ value = normalizeValue(value, triple)
+ if avarMapping:
+ value = piecewiseLinearMap(value, avarMapping)
+ # Quantize to F2Dot14, to avoid surprise interpolations.
+ return floatToFixedToFloat(value, 14)
+
+
+def normalizeAxisLimits(varfont, axisLimits):
+ fvar = varfont["fvar"]
+ badLimits = set(axisLimits.keys()).difference(a.axisTag for a in fvar.axes)
+ if badLimits:
+ raise ValueError("Cannot limit: {} not present in fvar".format(badLimits))
+
+ axes = {
+ a.axisTag: (a.minValue, a.defaultValue, a.maxValue)
+ for a in fvar.axes
+ if a.axisTag in axisLimits
+ }
+
+ avarSegments = {}
+ if "avar" in varfont:
+ avarSegments = varfont["avar"].segments
+ normalizedLimits = {}
+ for axis_tag, triple in axes.items():
+ avarMapping = avarSegments.get(axis_tag, None)
+ value = axisLimits[axis_tag]
+ if isinstance(value, tuple):
+ normalizedLimits[axis_tag] = tuple(
+ normalize(v, triple, avarMapping) for v in axisLimits[axis_tag]
+ )
+ else:
+ normalizedLimits[axis_tag] = normalize(value, triple, avarMapping)
+ return normalizedLimits
+
+
+def sanityCheckVariableTables(varfont):
+ if "fvar" not in varfont:
+ raise ValueError("Missing required table fvar")
+ if "gvar" in varfont:
+ if "glyf" not in varfont:
+ raise ValueError("Can't have gvar without glyf")
+ # TODO(anthrotype) Remove once we do support partial instancing CFF2
+ if "CFF2" in varfont:
+ raise NotImplementedError("Instancing CFF2 variable fonts is not supported yet")
+
+
+def populateAxisDefaults(varfont, axisLimits):
+ if any(value is None for value in axisLimits.values()):
+ fvar = varfont["fvar"]
+ defaultValues = {a.axisTag: a.defaultValue for a in fvar.axes}
+ return {
+ axisTag: defaultValues[axisTag] if value is None else value
+ for axisTag, value in axisLimits.items()
+ }
+ return axisLimits
+
+
+def instantiateVariableFont(
+ varfont, axisLimits, inplace=False, optimize=True, overlap=True
+):
+ """ Instantiate variable font, either fully or partially.
+
+ Depending on whether the `axisLimits` dictionary references all or some of the
+ input varfont's axes, the output font will either be a full instance (static
+ font) or a variable font with possibly less variation data.
+
+ Args:
+ varfont: a TTFont instance, which must contain at least an 'fvar' table.
+ Note that variable fonts with 'CFF2' table are not supported yet.
+ axisLimits: a dict keyed by axis tags (str) containing the coordinates (float)
+ along one or more axes where the desired instance will be located.
+ If the value is `None`, the default coordinate as per 'fvar' table for
+ that axis is used.
+ The limit values can also be (min, max) tuples for restricting an
+ axis's variation range, but this is not implemented yet.
+ inplace (bool): whether to modify input TTFont object in-place instead of
+ returning a distinct object.
+ optimize (bool): if False, do not perform IUP-delta optimization on the
+ remaining 'gvar' table's deltas. Possibly faster, and might work around
+ rendering issues in some buggy environments, at the cost of a slightly
+ larger file size.
+ overlap (bool): variable fonts usually contain overlapping contours, and some
+ font rendering engines on Apple platforms require that the `OVERLAP_SIMPLE`
+ and `OVERLAP_COMPOUND` flags in the 'glyf' table be set to force rendering
+ using a non-zero fill rule. Thus we always set these flags on all glyphs
+ to maximise cross-compatibility of the generated instance. You can disable
+ this by setting `overalap` to False.
+ """
+ sanityCheckVariableTables(varfont)
+
+ if not inplace:
+ varfont = deepcopy(varfont)
+
+ axisLimits = populateAxisDefaults(varfont, axisLimits)
+
+ normalizedLimits = normalizeAxisLimits(varfont, axisLimits)
+
+ log.info("Normalized limits: %s", normalizedLimits)
+
+ # TODO Remove this check once ranges are supported
+ if any(isinstance(v, tuple) for v in axisLimits.values()):
+ raise NotImplementedError("Axes range limits are not supported yet")
+
+ if "gvar" in varfont:
+ instantiateGvar(varfont, normalizedLimits, optimize=optimize)
+
+ if "cvar" in varfont:
+ instantiateCvar(varfont, normalizedLimits)
+
+ if "MVAR" in varfont:
+ instantiateMVAR(varfont, normalizedLimits)
+
+ if "HVAR" in varfont:
+ instantiateHVAR(varfont, normalizedLimits)
+
+ if "VVAR" in varfont:
+ instantiateVVAR(varfont, normalizedLimits)
+
+ instantiateOTL(varfont, normalizedLimits)
+
+ instantiateFeatureVariations(varfont, normalizedLimits)
+
+ if "avar" in varfont:
+ instantiateAvar(varfont, normalizedLimits)
+
+ with pruningUnusedNames(varfont):
+ if "STAT" in varfont:
+ instantiateSTAT(varfont, axisLimits)
+
+ instantiateFvar(varfont, axisLimits)
+
+ if "fvar" not in varfont:
+ if "glyf" in varfont and overlap:
+ setMacOverlapFlags(varfont["glyf"])
+
+ varLib.set_default_weight_width_slant(
+ varfont,
+ location={
+ axisTag: limit
+ for axisTag, limit in axisLimits.items()
+ if not isinstance(limit, tuple)
+ },
+ )
+
+ return varfont
+
+
+def parseLimits(limits):
+ result = {}
+ for limitString in limits:
+ match = re.match(r"^(\w{1,4})=(?:(drop)|(?:([^:]+)(?:[:](.+))?))$", limitString)
+ if not match:
+ raise ValueError("invalid location format: %r" % limitString)
+ tag = match.group(1).ljust(4)
+ if match.group(2): # 'drop'
+ lbound = None
+ else:
+ lbound = float(match.group(3))
+ ubound = lbound
+ if match.group(4):
+ ubound = float(match.group(4))
+ if lbound != ubound:
+ result[tag] = (lbound, ubound)
+ else:
+ result[tag] = lbound
+ return result
+
+
+def parseArgs(args):
+ """Parse argv.
+
+ Returns:
+ 3-tuple (infile, axisLimits, options)
+ axisLimits is either a Dict[str, Optional[float]], for pinning variation axes
+ to specific coordinates along those axes (with `None` as a placeholder for an
+ axis' default value); or a Dict[str, Tuple(float, float)], meaning limit this
+ axis to min/max range.
+ Axes locations are in user-space coordinates, as defined in the "fvar" table.
+ """
+ from fontTools import configLogger
+ import argparse
+
+ parser = argparse.ArgumentParser(
+ "fonttools varLib.instancer",
+ description="Partially instantiate a variable font",
+ )
+ parser.add_argument("input", metavar="INPUT.ttf", help="Input variable TTF file.")
+ parser.add_argument(
+ "locargs",
+ metavar="AXIS=LOC",
+ nargs="*",
+ help="List of space separated locations. A location consist in "
+ "the tag of a variation axis, followed by '=' and one of number, "
+ "number:number or the literal string 'drop'. "
+ "E.g.: wdth=100 or wght=75.0:125.0 or wght=drop",
+ )
+ parser.add_argument(
+ "-o",
+ "--output",
+ metavar="OUTPUT.ttf",
+ default=None,
+ help="Output instance TTF file (default: INPUT-instance.ttf).",
+ )
+ parser.add_argument(
+ "--no-optimize",
+ dest="optimize",
+ action="store_false",
+ help="Don't perform IUP optimization on the remaining gvar TupleVariations",
+ )
+ parser.add_argument(
+ "--no-overlap-flag",
+ dest="overlap",
+ action="store_false",
+ help="Don't set OVERLAP_SIMPLE/OVERLAP_COMPOUND glyf flags (only applicable "
+ "when generating a full instance)",
+ )
+ loggingGroup = parser.add_mutually_exclusive_group(required=False)
+ loggingGroup.add_argument(
+ "-v", "--verbose", action="store_true", help="Run more verbosely."
+ )
+ loggingGroup.add_argument(
+ "-q", "--quiet", action="store_true", help="Turn verbosity off."
+ )
+ options = parser.parse_args(args)
+
+ infile = options.input
+ if not os.path.isfile(infile):
+ parser.error("No such file '{}'".format(infile))
+
+ configLogger(
+ level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
+ )
+
+ try:
+ axisLimits = parseLimits(options.locargs)
+ except ValueError as e:
+ parser.error(e)
+
+ if len(axisLimits) != len(options.locargs):
+ parser.error("Specified multiple limits for the same axis")
+
+ return (infile, axisLimits, options)
+
+
+def main(args=None):
+ infile, axisLimits, options = parseArgs(args)
+ log.info("Restricting axes: %s", axisLimits)
+
+ log.info("Loading variable font")
+ varfont = TTFont(infile)
+
+ isFullInstance = {
+ axisTag for axisTag, limit in axisLimits.items() if not isinstance(limit, tuple)
+ }.issuperset(axis.axisTag for axis in varfont["fvar"].axes)
+
+ instantiateVariableFont(
+ varfont,
+ axisLimits,
+ inplace=True,
+ optimize=options.optimize,
+ overlap=options.overlap,
+ )
+
+ outfile = (
+ os.path.splitext(infile)[0]
+ + "-{}.ttf".format("instance" if isFullInstance else "partial")
+ if not options.output
+ else options.output
+ )
+
+ log.info(
+ "Saving %s font %s",
+ "instance" if isFullInstance else "partial variable",
+ outfile,
+ )
+ varfont.save(outfile)
+
+
+if __name__ == "__main__":
+ import sys
+
+ sys.exit(main())
diff --git a/Lib/fontTools/varLib/merger.py b/Lib/fontTools/varLib/merger.py
index cd16ace45..9b5af5cad 100644
--- a/Lib/fontTools/varLib/merger.py
+++ b/Lib/fontTools/varLib/merger.py
@@ -292,7 +292,8 @@ def merge(merger, self, lst):
if vpair is None:
v1, v2 = None, None
else:
- v1, v2 = vpair.Value1, vpair.Value2
+ v1 = getattr(vpair, "Value1", None)
+ v2 = getattr(vpair, "Value2", None)
v.Value1 = otBase.ValueRecord(merger.valueFormat1, src=v1) if merger.valueFormat1 else None
v.Value2 = otBase.ValueRecord(merger.valueFormat2, src=v2) if merger.valueFormat2 else None
values[j] = v
@@ -518,19 +519,19 @@ def merge(merger, self, lst):
if self.Format == 1:
for pairSet in self.PairSet:
for pairValueRecord in pairSet.PairValueRecord:
- pv1 = pairValueRecord.Value1
+ pv1 = getattr(pairValueRecord, "Value1", None)
if pv1 is not None:
vf1 |= pv1.getFormat()
- pv2 = pairValueRecord.Value2
+ pv2 = getattr(pairValueRecord, "Value2", None)
if pv2 is not None:
vf2 |= pv2.getFormat()
elif self.Format == 2:
for class1Record in self.Class1Record:
for class2Record in class1Record.Class2Record:
- pv1 = class2Record.Value1
+ pv1 = getattr(class2Record, "Value1", None)
if pv1 is not None:
vf1 |= pv1.getFormat()
- pv2 = class2Record.Value2
+ pv2 = getattr(class2Record, "Value2", None)
if pv2 is not None:
vf2 |= pv2.getFormat()
self.ValueFormat1 = vf1
@@ -886,17 +887,10 @@ class MutatorMerger(AligningMerger):
the operation can benefit from many operations that the
aligning merger does."""
- def __init__(self, font, location):
+ def __init__(self, font, instancer, deleteVariations=True):
Merger.__init__(self, font)
- self.location = location
-
- store = None
- if 'GDEF' in font:
- gdef = font['GDEF'].table
- if gdef.Version >= 0x00010003:
- store = gdef.VarStore
-
- self.instancer = VarStoreInstancer(store, font['fvar'].axes, location)
+ self.instancer = instancer
+ self.deleteVariations = deleteVariations
@MutatorMerger.merger(ot.CaretValue)
def merge(merger, self, lst):
@@ -909,14 +903,16 @@ def merge(merger, self, lst):
instancer = merger.instancer
dev = self.DeviceTable
- del self.DeviceTable
+ if merger.deleteVariations:
+ del self.DeviceTable
if dev:
assert dev.DeltaFormat == 0x8000
varidx = (dev.StartSize << 16) + dev.EndSize
delta = otRound(instancer[varidx])
- self.Coordinate += delta
+ self.Coordinate += delta
- self.Format = 1
+ if merger.deleteVariations:
+ self.Format = 1
@MutatorMerger.merger(ot.Anchor)
def merge(merger, self, lst):
@@ -933,7 +929,8 @@ def merge(merger, self, lst):
if not hasattr(self, tableName):
continue
dev = getattr(self, tableName)
- delattr(self, tableName)
+ if merger.deleteVariations:
+ delattr(self, tableName)
if dev is None:
continue
@@ -944,7 +941,8 @@ def merge(merger, self, lst):
attr = v+'Coordinate'
setattr(self, attr, getattr(self, attr) + delta)
- self.Format = 1
+ if merger.deleteVariations:
+ self.Format = 1
@MutatorMerger.merger(otBase.ValueRecord)
def merge(merger, self, lst):
@@ -953,7 +951,6 @@ def merge(merger, self, lst):
self.__dict__ = lst[0].__dict__.copy()
instancer = merger.instancer
- # TODO Handle differing valueformats
for name, tableName in [('XAdvance','XAdvDevice'),
('YAdvance','YAdvDevice'),
('XPlacement','XPlaDevice'),
@@ -962,7 +959,8 @@ def merge(merger, self, lst):
if not hasattr(self, tableName):
continue
dev = getattr(self, tableName)
- delattr(self, tableName)
+ if merger.deleteVariations:
+ delattr(self, tableName)
if dev is None:
continue
diff --git a/Lib/fontTools/varLib/mutator.py b/Lib/fontTools/varLib/mutator.py
index 04ab35778..aba327167 100644
--- a/Lib/fontTools/varLib/mutator.py
+++ b/Lib/fontTools/varLib/mutator.py
@@ -10,7 +10,6 @@ from fontTools.pens.boundsPen import BoundsPen
from fontTools.ttLib import TTFont, newTable
from fontTools.ttLib.tables import ttProgram
from fontTools.ttLib.tables._g_l_y_f import GlyphCoordinates, flagOverlapSimple, OVERLAP_COMPOUND
-from fontTools.varLib import _GetCoordinates, _SetCoordinates
from fontTools.varLib.models import (
supportScalar,
normalizeLocation,
@@ -195,7 +194,7 @@ def instantiateVariableFont(varfont, location, inplace=False, overlap=True):
name))
for glyphname in glyphnames:
variations = gvar.variations[glyphname]
- coordinates,_ = _GetCoordinates(varfont, glyphname)
+ coordinates, _ = glyf.getCoordinatesAndControls(glyphname, varfont)
origCoords, endPts = None, None
for var in variations:
scalar = supportScalar(loc, var.axes)
@@ -203,11 +202,10 @@ def instantiateVariableFont(varfont, location, inplace=False, overlap=True):
delta = var.coordinates
if None in delta:
if origCoords is None:
- origCoords,control = _GetCoordinates(varfont, glyphname)
- endPts = control[1] if control[0] >= 1 else list(range(len(control[1])))
- delta = iup_delta(delta, origCoords, endPts)
+ origCoords, g = glyf.getCoordinatesAndControls(glyphname, varfont)
+ delta = iup_delta(delta, origCoords, g.endPts)
coordinates += GlyphCoordinates(delta) * scalar
- _SetCoordinates(varfont, glyphname, coordinates)
+ glyf.setCoordinates(glyphname, coordinates, varfont)
else:
glyf = None
@@ -291,7 +289,7 @@ def instantiateVariableFont(varfont, location, inplace=False, overlap=True):
gdef = varfont['GDEF'].table
instancer = VarStoreInstancer(gdef.VarStore, fvar.axes, loc)
- merger = MutatorMerger(varfont, loc)
+ merger = MutatorMerger(varfont, instancer)
merger.mergeTables(varfont, [varfont], ['GDEF', 'GPOS'])
# Downgrade GDEF.
diff --git a/Lib/fontTools/varLib/varStore.py b/Lib/fontTools/varLib/varStore.py
index f8ce81996..d9d48a513 100644
--- a/Lib/fontTools/varLib/varStore.py
+++ b/Lib/fontTools/varLib/varStore.py
@@ -133,8 +133,11 @@ def VarData_addItem(self, deltas):
ot.VarData.addItem = VarData_addItem
def VarRegion_get_support(self, fvar_axes):
- return {fvar_axes[i].axisTag: (reg.StartCoord,reg.PeakCoord,reg.EndCoord)
- for i,reg in enumerate(self.VarRegionAxis)}
+ return {
+ fvar_axes[i].axisTag: (reg.StartCoord,reg.PeakCoord,reg.EndCoord)
+ for i, reg in enumerate(self.VarRegionAxis)
+ if reg.PeakCoord != 0
+ }
ot.VarRegion.get_support = VarRegion_get_support
diff --git a/Tests/conftest.py b/Tests/conftest.py
new file mode 100644
index 000000000..492861420
--- /dev/null
+++ b/Tests/conftest.py
@@ -0,0 +1,28 @@
+import fontTools
+import pytest
+
+
+@pytest.fixture(autouse=True, scope="session")
+def disableConfigLogger():
+ """Session-scoped fixture to make fontTools.configLogger function no-op.
+
+ Logging in python maintains a global state. When in the tests we call a main()
+ function from modules subset or ttx, a call to configLogger is made that modifies
+ this global state (to configures a handler for the fontTools logger).
+ To prevent that, we monkey-patch the `configLogger` attribute of the `fontTools`
+ module (the one used in the scripts main() functions) so that it does nothing,
+ to avoid any side effects.
+
+ NOTE: `fontTools.configLogger` is only an alias for the configLogger function in
+ `fontTools.misc.loggingTools` module; the original function is not modified.
+ """
+
+ def noop(*args, **kwargs):
+ return
+
+ originalConfigLogger = fontTools.configLogger
+ fontTools.configLogger = noop
+ try:
+ yield
+ finally:
+ fontTools.configLogger = originalConfigLogger
diff --git a/Tests/ttLib/tables/TupleVariation_test.py b/Tests/ttLib/tables/TupleVariation_test.py
index aab4cba0b..d78810a9c 100644
--- a/Tests/ttLib/tables/TupleVariation_test.py
+++ b/Tests/ttLib/tables/TupleVariation_test.py
@@ -69,6 +69,13 @@ SKIA_GVAR_I_DATA = deHexStr(
class TupleVariationTest(unittest.TestCase):
+ def __init__(self, methodName):
+ unittest.TestCase.__init__(self, methodName)
+ # Python 3 renamed assertRaisesRegexp to assertRaisesRegex,
+ # and fires deprecation warnings if a program uses the old name.
+ if not hasattr(self, "assertRaisesRegex"):
+ self.assertRaisesRegex = self.assertRaisesRegexp
+
def test_equal(self):
var1 = TupleVariation({"wght":(0.0, 1.0, 1.0)}, [(0,0), (9,8), (7,6)])
var2 = TupleVariation({"wght":(0.0, 1.0, 1.0)}, [(0,0), (9,8), (7,6)])
@@ -681,6 +688,167 @@ class TupleVariationTest(unittest.TestCase):
content = writer.file.getvalue().decode("utf-8")
return [line.strip() for line in content.splitlines()][1:]
+ def test_getCoordWidth(self):
+ empty = TupleVariation({}, [])
+ self.assertEqual(empty.getCoordWidth(), 0)
+
+ empty = TupleVariation({}, [None])
+ self.assertEqual(empty.getCoordWidth(), 0)
+
+ gvarTuple = TupleVariation({}, [None, (0, 0)])
+ self.assertEqual(gvarTuple.getCoordWidth(), 2)
+
+ cvarTuple = TupleVariation({}, [None, 0])
+ self.assertEqual(cvarTuple.getCoordWidth(), 1)
+
+ cvarTuple.coordinates[1] *= 1.0
+ self.assertEqual(cvarTuple.getCoordWidth(), 1)
+
+ with self.assertRaises(TypeError):
+ TupleVariation({}, [None, "a"]).getCoordWidth()
+
+ def test_scaleDeltas_cvar(self):
+ var = TupleVariation({}, [100, None])
+
+ var.scaleDeltas(1.0)
+ self.assertEqual(var.coordinates, [100, None])
+
+ var.scaleDeltas(0.333)
+ self.assertAlmostEqual(var.coordinates[0], 33.3)
+ self.assertIsNone(var.coordinates[1])
+
+ var.scaleDeltas(0.0)
+ self.assertEqual(var.coordinates, [0, None])
+
+ def test_scaleDeltas_gvar(self):
+ var = TupleVariation({}, [(100, 200), None])
+
+ var.scaleDeltas(1.0)
+ self.assertEqual(var.coordinates, [(100, 200), None])
+
+ var.scaleDeltas(0.333)
+ self.assertAlmostEqual(var.coordinates[0][0], 33.3)
+ self.assertAlmostEqual(var.coordinates[0][1], 66.6)
+ self.assertIsNone(var.coordinates[1])
+
+ var.scaleDeltas(0.0)
+ self.assertEqual(var.coordinates, [(0, 0), None])
+
+ def test_roundDeltas_cvar(self):
+ var = TupleVariation({}, [55.5, None, 99.9])
+ var.roundDeltas()
+ self.assertEqual(var.coordinates, [56, None, 100])
+
+ def test_roundDeltas_gvar(self):
+ var = TupleVariation({}, [(55.5, 100.0), None, (99.9, 100.0)])
+ var.roundDeltas()
+ self.assertEqual(var.coordinates, [(56, 100), None, (100, 100)])
+
+ def test_calcInferredDeltas(self):
+ var = TupleVariation({}, [(0, 0), None, None, None])
+ coords = [(1, 1), (1, 1), (1, 1), (1, 1)]
+
+ var.calcInferredDeltas(coords, [])
+
+ self.assertEqual(
+ var.coordinates,
+ [(0, 0), (0, 0), (0, 0), (0, 0)]
+ )
+
+ def test_calcInferredDeltas_invalid(self):
+ # cvar tuples can't have inferred deltas
+ with self.assertRaises(TypeError):
+ TupleVariation({}, [0]).calcInferredDeltas([], [])
+
+ # origCoords must have same length as self.coordinates
+ with self.assertRaises(ValueError):
+ TupleVariation({}, [(0, 0), None]).calcInferredDeltas([], [])
+
+ # at least 4 phantom points required
+ with self.assertRaises(AssertionError):
+ TupleVariation({}, [(0, 0), None]).calcInferredDeltas([(0, 0), (0, 0)], [])
+
+ with self.assertRaises(AssertionError):
+ TupleVariation({}, [(0, 0)] + [None]*5).calcInferredDeltas(
+ [(0, 0)]*6,
+ [1, 0] # endPts not in increasing order
+ )
+
+ def test_optimize(self):
+ var = TupleVariation({"wght": (0.0, 1.0, 1.0)}, [(0, 0)]*5)
+
+ var.optimize([(0, 0)]*5, [0])
+
+ self.assertEqual(var.coordinates, [None, None, None, None, None])
+
+ def test_optimize_isComposite(self):
+ # when a composite glyph's deltas are all (0, 0), we still want
+ # to write out an entry in gvar, else macOS doesn't apply any
+ # variations to the composite glyph (even if its individual components
+ # do vary).
+ # https://github.com/fonttools/fonttools/issues/1381
+ var = TupleVariation({"wght": (0.0, 1.0, 1.0)}, [(0, 0)]*5)
+ var.optimize([(0, 0)]*5, [0], isComposite=True)
+ self.assertEqual(var.coordinates, [(0, 0)]*5)
+
+ # it takes more than 128 (0, 0) deltas before the optimized tuple with
+ # (None) inferred deltas (except for the first) becomes smaller than
+ # the un-optimized one that has all deltas explicitly set to (0, 0).
+ var = TupleVariation({"wght": (0.0, 1.0, 1.0)}, [(0, 0)]*129)
+ var.optimize([(0, 0)]*129, list(range(129-4)), isComposite=True)
+ self.assertEqual(var.coordinates, [(0, 0)] + [None]*128)
+
+ def test_sum_deltas_gvar(self):
+ var1 = TupleVariation(
+ {},
+ [
+ (-20, 0), (-20, 0), (20, 0), (20, 0),
+ (0, 0), (0, 0), (0, 0), (0, 0),
+ ]
+ )
+ var2 = TupleVariation(
+ {},
+ [
+ (-10, 0), (-10, 0), (10, 0), (10, 0),
+ (0, 0), (20, 0), (0, 0), (0, 0),
+ ]
+ )
+
+ var1 += var2
+
+ self.assertEqual(
+ var1.coordinates,
+ [
+ (-30, 0), (-30, 0), (30, 0), (30, 0),
+ (0, 0), (20, 0), (0, 0), (0, 0),
+ ]
+ )
+
+ def test_sum_deltas_gvar_invalid_length(self):
+ var1 = TupleVariation({}, [(1, 2)])
+ var2 = TupleVariation({}, [(1, 2), (3, 4)])
+
+ with self.assertRaisesRegex(ValueError, "deltas with different lengths"):
+ var1 += var2
+
+ def test_sum_deltas_gvar_with_inferred_points(self):
+ var1 = TupleVariation({}, [(1, 2), None])
+ var2 = TupleVariation({}, [(2, 3), None])
+
+ with self.assertRaisesRegex(ValueError, "deltas with inferred points"):
+ var1 += var2
+
+ def test_sum_deltas_cvar(self):
+ axes = {"wght": (0.0, 1.0, 1.0)}
+ var1 = TupleVariation(axes, [0, 1, None, None])
+ var2 = TupleVariation(axes, [None, 2, None, 3])
+ var3 = TupleVariation(axes, [None, None, None, 4])
+
+ var1 += var2
+ var1 += var3
+
+ self.assertEqual(var1.coordinates, [0, 3, None, 7])
+
if __name__ == "__main__":
import sys
diff --git a/Tests/ttx/ttx_test.py b/Tests/ttx/ttx_test.py
index eb5816ba8..97307fb7a 100644
--- a/Tests/ttx/ttx_test.py
+++ b/Tests/ttx/ttx_test.py
@@ -953,7 +953,7 @@ def test_main_getopterror_missing_directory():
ttx.main(args)
-def test_main_keyboard_interrupt(tmpdir, monkeypatch, capsys):
+def test_main_keyboard_interrupt(tmpdir, monkeypatch, caplog):
with pytest.raises(SystemExit):
inpath = os.path.join("Tests", "ttx", "data", "TestTTF.ttx")
outpath = tmpdir.join("TestTTF.ttf")
@@ -963,8 +963,7 @@ def test_main_keyboard_interrupt(tmpdir, monkeypatch, capsys):
)
ttx.main(args)
- out, err = capsys.readouterr()
- assert "(Cancelled.)" in err
+ assert "(Cancelled.)" in caplog.text
@pytest.mark.skipif(
@@ -982,7 +981,7 @@ def test_main_system_exit(tmpdir, monkeypatch):
ttx.main(args)
-def test_main_ttlib_error(tmpdir, monkeypatch, capsys):
+def test_main_ttlib_error(tmpdir, monkeypatch, caplog):
with pytest.raises(SystemExit):
inpath = os.path.join("Tests", "ttx", "data", "TestTTF.ttx")
outpath = tmpdir.join("TestTTF.ttf")
@@ -994,15 +993,14 @@ def test_main_ttlib_error(tmpdir, monkeypatch, capsys):
)
ttx.main(args)
- out, err = capsys.readouterr()
- assert "Test error" in err
+ assert "Test error" in caplog.text
@pytest.mark.skipif(
sys.platform == "win32",
reason="waitForKeyPress function causes test to hang on Windows platform",
)
-def test_main_base_exception(tmpdir, monkeypatch, capsys):
+def test_main_base_exception(tmpdir, monkeypatch, caplog):
with pytest.raises(SystemExit):
inpath = os.path.join("Tests", "ttx", "data", "TestTTF.ttx")
outpath = tmpdir.join("TestTTF.ttf")
@@ -1014,8 +1012,7 @@ def test_main_base_exception(tmpdir, monkeypatch, capsys):
)
ttx.main(args)
- out, err = capsys.readouterr()
- assert "Unhandled exception has occurred" in err
+ assert "Unhandled exception has occurred" in caplog.text
# ---------------------------
diff --git a/Tests/varLib/data/PartialInstancerTest-VF.ttx b/Tests/varLib/data/PartialInstancerTest-VF.ttx
new file mode 100644
index 000000000..92540e03e
--- /dev/null
+++ b/Tests/varLib/data/PartialInstancerTest-VF.ttx
@@ -0,0 +1,1131 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Bräiti
+
+
+ Weight
+
+
+ Width
+
+
+ Thin
+
+
+ ExtraLight
+
+
+ Light
+
+
+ Regular
+
+
+ Medium
+
+
+ SemiBold
+
+
+ Bold
+
+
+ ExtraBold
+
+
+ Black
+
+
+ SemiCondensed Thin
+
+
+ SemiCondensed ExtraLight
+
+
+ SemiCondensed Light
+
+
+ SemiCondensed
+
+
+ SemiCondensed Medium
+
+
+ SemiCondensed SemiBold
+
+
+ SemiCondensed Bold
+
+
+ SemiCondensed ExtraBold
+
+
+ SemiCondensed Black
+
+
+ Condensed Thin
+
+
+ Condensed ExtraLight
+
+
+ Condensed Light
+
+
+ Condensed
+
+
+ Condensed Medium
+
+
+ Condensed SemiBold
+
+
+ Condensed Bold
+
+
+ Condensed ExtraBold
+
+
+ Condensed Black
+
+
+ ExtraCondensed Thin
+
+
+ ExtraCondensed ExtraLight
+
+
+ ExtraCondensed Light
+
+
+ ExtraCondensed
+
+
+ ExtraCondensed Medium
+
+
+ ExtraCondensed SemiBold
+
+
+ ExtraCondensed Bold
+
+
+ ExtraCondensed ExtraBold
+
+
+ ExtraCondensed Black
+
+
+ Italic
+
+
+ Upright
+
+
+ TestVariableFont-XCdBd
+
+
+ Copyright 2015 Google Inc. All Rights Reserved.
+
+
+ Test Variable Font
+
+
+ Regular
+
+
+ 2.001;GOOG;TestVariableFont-Regular
+
+
+ Test Variable Font Regular
+
+
+ Version 2.001
+
+
+ TestVariableFont-Regular
+
+
+ Noto is a trademark of Google Inc.
+
+
+ Monotype Imaging Inc.
+
+
+ Monotype Design Team
+
+
+ http://www.google.com/get/noto/
+
+
+ http://www.monotype.com/studio
+
+
+ Weight
+
+
+ Width
+
+
+ Thin
+
+
+ ExtraLight
+
+
+ Light
+
+
+ Regular
+
+
+ Medium
+
+
+ SemiBold
+
+
+ Bold
+
+
+ ExtraBold
+
+
+ Black
+
+
+ SemiCondensed Thin
+
+
+ SemiCondensed ExtraLight
+
+
+ SemiCondensed Light
+
+
+ SemiCondensed
+
+
+ SemiCondensed Medium
+
+
+ SemiCondensed SemiBold
+
+
+ SemiCondensed Bold
+
+
+ SemiCondensed ExtraBold
+
+
+ SemiCondensed Black
+
+
+ Condensed Thin
+
+
+ Condensed ExtraLight
+
+
+ Condensed Light
+
+
+ Condensed
+
+
+ Condensed Medium
+
+
+ Condensed SemiBold
+
+
+ Condensed Bold
+
+
+ Condensed ExtraBold
+
+
+ Condensed Black
+
+
+ ExtraCondensed Thin
+
+
+ ExtraCondensed ExtraLight
+
+
+ ExtraCondensed Light
+
+
+ ExtraCondensed
+
+
+ ExtraCondensed Medium
+
+
+ ExtraCondensed SemiBold
+
+
+ ExtraCondensed Bold
+
+
+ ExtraCondensed ExtraBold
+
+
+ ExtraCondensed Black
+
+
+ Italic
+
+
+ Upright
+
+
+ TestVariableFont-XCdBd
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ wght
+ 0x0
+ 100.0
+ 400.0
+ 900.0
+ 256
+
+
+
+
+ wdth
+ 0x0
+ 70.0
+ 100.0
+ 100.0
+ 257
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Tests/varLib/data/PartialInstancerTest2-VF.ttx b/Tests/varLib/data/PartialInstancerTest2-VF.ttx
new file mode 100644
index 000000000..0f19bde35
--- /dev/null
+++ b/Tests/varLib/data/PartialInstancerTest2-VF.ttx
@@ -0,0 +1,1803 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Weight
+
+
+ Width
+
+
+ Thin
+
+
+ ExtraLight
+
+
+ Light
+
+
+ Regular
+
+
+ Medium
+
+
+ SemiBold
+
+
+ Bold
+
+
+ ExtraBold
+
+
+ Black
+
+
+ SemiCondensed Thin
+
+
+ SemiCondensed ExtraLight
+
+
+ SemiCondensed Light
+
+
+ SemiCondensed
+
+
+ SemiCondensed Medium
+
+
+ SemiCondensed SemiBold
+
+
+ SemiCondensed Bold
+
+
+ SemiCondensed ExtraBold
+
+
+ SemiCondensed Black
+
+
+ Condensed Thin
+
+
+ Condensed ExtraLight
+
+
+ Condensed Light
+
+
+ Condensed
+
+
+ Condensed Medium
+
+
+ Condensed SemiBold
+
+
+ Condensed Bold
+
+
+ Condensed ExtraBold
+
+
+ Condensed Black
+
+
+ ExtraCondensed Thin
+
+
+ ExtraCondensed ExtraLight
+
+
+ ExtraCondensed Light
+
+
+ ExtraCondensed
+
+
+ ExtraCondensed Medium
+
+
+ ExtraCondensed SemiBold
+
+
+ ExtraCondensed Bold
+
+
+ ExtraCondensed ExtraBold
+
+
+ ExtraCondensed Black
+
+
+ Copyright 2015 Google Inc. All Rights Reserved.
+
+
+ Noto Sans
+
+
+ Regular
+
+
+ 2.001;GOOG;NotoSans-Regular
+
+
+ Noto Sans Regular
+
+
+ Version 2.001
+
+
+ NotoSans-Regular
+
+
+ Noto is a trademark of Google Inc.
+
+
+ Monotype Imaging Inc.
+
+
+ Monotype Design Team
+
+
+ Designed by Monotype design team.
+
+
+ http://www.google.com/get/noto/
+
+
+ http://www.monotype.com/studio
+
+
+ This Font Software is licensed under the SIL Open Font License, Version 1.1. This Font Software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the SIL Open Font License for the specific language, permissions and limitations governing your use of this Font Software.
+
+
+ http://scripts.sil.org/OFL
+
+
+ Weight
+
+
+ Width
+
+
+ Thin
+
+
+ ExtraLight
+
+
+ Light
+
+
+ Regular
+
+
+ Medium
+
+
+ SemiBold
+
+
+ Bold
+
+
+ ExtraBold
+
+
+ Black
+
+
+ SemiCondensed Thin
+
+
+ SemiCondensed ExtraLight
+
+
+ SemiCondensed Light
+
+
+ SemiCondensed
+
+
+ SemiCondensed Medium
+
+
+ SemiCondensed SemiBold
+
+
+ SemiCondensed Bold
+
+
+ SemiCondensed ExtraBold
+
+
+ SemiCondensed Black
+
+
+ Condensed Thin
+
+
+ Condensed ExtraLight
+
+
+ Condensed Light
+
+
+ Condensed
+
+
+ Condensed Medium
+
+
+ Condensed SemiBold
+
+
+ Condensed Bold
+
+
+ Condensed ExtraBold
+
+
+ Condensed Black
+
+
+ ExtraCondensed Thin
+
+
+ ExtraCondensed ExtraLight
+
+
+ ExtraCondensed Light
+
+
+ ExtraCondensed
+
+
+ ExtraCondensed Medium
+
+
+ ExtraCondensed SemiBold
+
+
+ ExtraCondensed Bold
+
+
+ ExtraCondensed ExtraBold
+
+
+ ExtraCondensed Black
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ wght
+ 0x0
+ 100.0
+ 400.0
+ 900.0
+ 256
+
+
+
+
+ wdth
+ 0x0
+ 62.5
+ 100.0
+ 100.0
+ 257
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-100,100.ttx b/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-100,100.ttx
new file mode 100644
index 000000000..c64049fed
--- /dev/null
+++ b/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-100,100.ttx
@@ -0,0 +1,484 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Copyright 2015 Google Inc. All Rights Reserved.
+
+
+ Noto Sans
+
+
+ Regular
+
+
+ 2.001;GOOG;NotoSans-Regular
+
+
+ Noto Sans Regular
+
+
+ Version 2.001
+
+
+ NotoSans-Regular
+
+
+ Noto is a trademark of Google Inc.
+
+
+ Monotype Imaging Inc.
+
+
+ Monotype Design Team
+
+
+ Designed by Monotype design team.
+
+
+ http://www.google.com/get/noto/
+
+
+ http://www.monotype.com/studio
+
+
+ This Font Software is licensed under the SIL Open Font License, Version 1.1. This Font Software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the SIL Open Font License for the specific language, permissions and limitations governing your use of this Font Software.
+
+
+ http://scripts.sil.org/OFL
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-100,62.5.ttx b/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-100,62.5.ttx
new file mode 100644
index 000000000..87d0c65c7
--- /dev/null
+++ b/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-100,62.5.ttx
@@ -0,0 +1,484 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Copyright 2015 Google Inc. All Rights Reserved.
+
+
+ Noto Sans
+
+
+ Regular
+
+
+ 2.001;GOOG;NotoSans-Regular
+
+
+ Noto Sans Regular
+
+
+ Version 2.001
+
+
+ NotoSans-Regular
+
+
+ Noto is a trademark of Google Inc.
+
+
+ Monotype Imaging Inc.
+
+
+ Monotype Design Team
+
+
+ Designed by Monotype design team.
+
+
+ http://www.google.com/get/noto/
+
+
+ http://www.monotype.com/studio
+
+
+ This Font Software is licensed under the SIL Open Font License, Version 1.1. This Font Software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the SIL Open Font License for the specific language, permissions and limitations governing your use of this Font Software.
+
+
+ http://scripts.sil.org/OFL
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-400,100.ttx b/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-400,100.ttx
new file mode 100644
index 000000000..fc64365eb
--- /dev/null
+++ b/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-400,100.ttx
@@ -0,0 +1,484 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Copyright 2015 Google Inc. All Rights Reserved.
+
+
+ Noto Sans
+
+
+ Regular
+
+
+ 2.001;GOOG;NotoSans-Regular
+
+
+ Noto Sans Regular
+
+
+ Version 2.001
+
+
+ NotoSans-Regular
+
+
+ Noto is a trademark of Google Inc.
+
+
+ Monotype Imaging Inc.
+
+
+ Monotype Design Team
+
+
+ Designed by Monotype design team.
+
+
+ http://www.google.com/get/noto/
+
+
+ http://www.monotype.com/studio
+
+
+ This Font Software is licensed under the SIL Open Font License, Version 1.1. This Font Software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the SIL Open Font License for the specific language, permissions and limitations governing your use of this Font Software.
+
+
+ http://scripts.sil.org/OFL
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-400,62.5.ttx b/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-400,62.5.ttx
new file mode 100644
index 000000000..9b40106fe
--- /dev/null
+++ b/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-400,62.5.ttx
@@ -0,0 +1,484 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Copyright 2015 Google Inc. All Rights Reserved.
+
+
+ Noto Sans
+
+
+ Regular
+
+
+ 2.001;GOOG;NotoSans-Regular
+
+
+ Noto Sans Regular
+
+
+ Version 2.001
+
+
+ NotoSans-Regular
+
+
+ Noto is a trademark of Google Inc.
+
+
+ Monotype Imaging Inc.
+
+
+ Monotype Design Team
+
+
+ Designed by Monotype design team.
+
+
+ http://www.google.com/get/noto/
+
+
+ http://www.monotype.com/studio
+
+
+ This Font Software is licensed under the SIL Open Font License, Version 1.1. This Font Software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the SIL Open Font License for the specific language, permissions and limitations governing your use of this Font Software.
+
+
+ http://scripts.sil.org/OFL
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-900,100.ttx b/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-900,100.ttx
new file mode 100644
index 000000000..8f8517960
--- /dev/null
+++ b/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-900,100.ttx
@@ -0,0 +1,484 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Copyright 2015 Google Inc. All Rights Reserved.
+
+
+ Noto Sans
+
+
+ Regular
+
+
+ 2.001;GOOG;NotoSans-Regular
+
+
+ Noto Sans Regular
+
+
+ Version 2.001
+
+
+ NotoSans-Regular
+
+
+ Noto is a trademark of Google Inc.
+
+
+ Monotype Imaging Inc.
+
+
+ Monotype Design Team
+
+
+ Designed by Monotype design team.
+
+
+ http://www.google.com/get/noto/
+
+
+ http://www.monotype.com/studio
+
+
+ This Font Software is licensed under the SIL Open Font License, Version 1.1. This Font Software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the SIL Open Font License for the specific language, permissions and limitations governing your use of this Font Software.
+
+
+ http://scripts.sil.org/OFL
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-900,62.5.ttx b/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-900,62.5.ttx
new file mode 100644
index 000000000..bc8c7e9a6
--- /dev/null
+++ b/Tests/varLib/data/test_results/PartialInstancerTest2-VF-instance-900,62.5.ttx
@@ -0,0 +1,484 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Copyright 2015 Google Inc. All Rights Reserved.
+
+
+ Noto Sans
+
+
+ Regular
+
+
+ 2.001;GOOG;NotoSans-Regular
+
+
+ Noto Sans Regular
+
+
+ Version 2.001
+
+
+ NotoSans-Regular
+
+
+ Noto is a trademark of Google Inc.
+
+
+ Monotype Imaging Inc.
+
+
+ Monotype Design Team
+
+
+ Designed by Monotype design team.
+
+
+ http://www.google.com/get/noto/
+
+
+ http://www.monotype.com/studio
+
+
+ This Font Software is licensed under the SIL Open Font License, Version 1.1. This Font Software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the SIL Open Font License for the specific language, permissions and limitations governing your use of this Font Software.
+
+
+ http://scripts.sil.org/OFL
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Tests/varLib/instancer_test.py b/Tests/varLib/instancer_test.py
new file mode 100644
index 000000000..7c587b595
--- /dev/null
+++ b/Tests/varLib/instancer_test.py
@@ -0,0 +1,1406 @@
+from __future__ import print_function, division, absolute_import
+from fontTools.misc.py23 import *
+from fontTools import ttLib
+from fontTools import designspaceLib
+from fontTools.feaLib.builder import addOpenTypeFeaturesFromString
+from fontTools.ttLib.tables import _f_v_a_r, _g_l_y_f
+from fontTools.ttLib.tables import otTables
+from fontTools.ttLib.tables.TupleVariation import TupleVariation
+from fontTools import varLib
+from fontTools.varLib import instancer
+from fontTools.varLib.mvar import MVAR_ENTRIES
+from fontTools.varLib import builder
+from fontTools.varLib import featureVars
+from fontTools.varLib import models
+import collections
+from copy import deepcopy
+import logging
+import os
+import re
+import pytest
+
+
+TESTDATA = os.path.join(os.path.dirname(__file__), "data")
+
+
+@pytest.fixture
+def varfont():
+ f = ttLib.TTFont()
+ f.importXML(os.path.join(TESTDATA, "PartialInstancerTest-VF.ttx"))
+ return f
+
+
+@pytest.fixture(params=[True, False], ids=["optimize", "no-optimize"])
+def optimize(request):
+ return request.param
+
+
+@pytest.fixture
+def fvarAxes():
+ wght = _f_v_a_r.Axis()
+ wght.axisTag = Tag("wght")
+ wght.minValue = 100
+ wght.defaultValue = 400
+ wght.maxValue = 900
+ wdth = _f_v_a_r.Axis()
+ wdth.axisTag = Tag("wdth")
+ wdth.minValue = 70
+ wdth.defaultValue = 100
+ wdth.maxValue = 100
+ return [wght, wdth]
+
+
+def _get_coordinates(varfont, glyphname):
+ # converts GlyphCoordinates to a list of (x, y) tuples, so that pytest's
+ # assert will give us a nicer diff
+ return list(varfont["glyf"].getCoordinatesAndControls(glyphname, varfont)[0])
+
+
+class InstantiateGvarTest(object):
+ @pytest.mark.parametrize("glyph_name", ["hyphen"])
+ @pytest.mark.parametrize(
+ "location, expected",
+ [
+ pytest.param(
+ {"wdth": -1.0},
+ {
+ "hyphen": [
+ (27, 229),
+ (27, 310),
+ (247, 310),
+ (247, 229),
+ (0, 0),
+ (274, 0),
+ (0, 536),
+ (0, 0),
+ ]
+ },
+ id="wdth=-1.0",
+ ),
+ pytest.param(
+ {"wdth": -0.5},
+ {
+ "hyphen": [
+ (33.5, 229),
+ (33.5, 308.5),
+ (264.5, 308.5),
+ (264.5, 229),
+ (0, 0),
+ (298, 0),
+ (0, 536),
+ (0, 0),
+ ]
+ },
+ id="wdth=-0.5",
+ ),
+ # an axis pinned at the default normalized location (0.0) means
+ # the default glyf outline stays the same
+ pytest.param(
+ {"wdth": 0.0},
+ {
+ "hyphen": [
+ (40, 229),
+ (40, 307),
+ (282, 307),
+ (282, 229),
+ (0, 0),
+ (322, 0),
+ (0, 536),
+ (0, 0),
+ ]
+ },
+ id="wdth=0.0",
+ ),
+ ],
+ )
+ def test_pin_and_drop_axis(self, varfont, glyph_name, location, expected, optimize):
+ instancer.instantiateGvar(varfont, location, optimize=optimize)
+
+ assert _get_coordinates(varfont, glyph_name) == expected[glyph_name]
+
+ # check that the pinned axis has been dropped from gvar
+ assert not any(
+ "wdth" in t.axes
+ for tuples in varfont["gvar"].variations.values()
+ for t in tuples
+ )
+
+ def test_full_instance(self, varfont, optimize):
+ instancer.instantiateGvar(
+ varfont, {"wght": 0.0, "wdth": -0.5}, optimize=optimize
+ )
+
+ assert _get_coordinates(varfont, "hyphen") == [
+ (33.5, 229),
+ (33.5, 308.5),
+ (264.5, 308.5),
+ (264.5, 229),
+ (0, 0),
+ (298, 0),
+ (0, 536),
+ (0, 0),
+ ]
+
+ assert "gvar" not in varfont
+
+ def test_composite_glyph_not_in_gvar(self, varfont):
+ """ The 'minus' glyph is a composite glyph, which references 'hyphen' as a
+ component, but has no tuple variations in gvar table, so the component offset
+ and the phantom points do not change; however the sidebearings and bounding box
+ do change as a result of the parent glyph 'hyphen' changing.
+ """
+ hmtx = varfont["hmtx"]
+ vmtx = varfont["vmtx"]
+
+ hyphenCoords = _get_coordinates(varfont, "hyphen")
+ assert hyphenCoords == [
+ (40, 229),
+ (40, 307),
+ (282, 307),
+ (282, 229),
+ (0, 0),
+ (322, 0),
+ (0, 536),
+ (0, 0),
+ ]
+ assert hmtx["hyphen"] == (322, 40)
+ assert vmtx["hyphen"] == (536, 229)
+
+ minusCoords = _get_coordinates(varfont, "minus")
+ assert minusCoords == [(0, 0), (0, 0), (422, 0), (0, 536), (0, 0)]
+ assert hmtx["minus"] == (422, 40)
+ assert vmtx["minus"] == (536, 229)
+
+ location = {"wght": -1.0, "wdth": -1.0}
+
+ instancer.instantiateGvar(varfont, location)
+
+ # check 'hyphen' coordinates changed
+ assert _get_coordinates(varfont, "hyphen") == [
+ (26, 259),
+ (26, 286),
+ (237, 286),
+ (237, 259),
+ (0, 0),
+ (263, 0),
+ (0, 536),
+ (0, 0),
+ ]
+ # check 'minus' coordinates (i.e. component offset and phantom points)
+ # did _not_ change
+ assert _get_coordinates(varfont, "minus") == minusCoords
+
+ assert hmtx["hyphen"] == (263, 26)
+ assert vmtx["hyphen"] == (536, 250)
+
+ assert hmtx["minus"] == (422, 26) # 'minus' left sidebearing changed
+ assert vmtx["minus"] == (536, 250) # 'minus' top sidebearing too
+
+
+class InstantiateCvarTest(object):
+ @pytest.mark.parametrize(
+ "location, expected",
+ [
+ pytest.param({"wght": -1.0}, [500, -400, 150, 250], id="wght=-1.0"),
+ pytest.param({"wdth": -1.0}, [500, -400, 180, 200], id="wdth=-1.0"),
+ pytest.param({"wght": -0.5}, [500, -400, 165, 250], id="wght=-0.5"),
+ pytest.param({"wdth": -0.3}, [500, -400, 180, 235], id="wdth=-0.3"),
+ ],
+ )
+ def test_pin_and_drop_axis(self, varfont, location, expected):
+ instancer.instantiateCvar(varfont, location)
+
+ assert list(varfont["cvt "].values) == expected
+
+ # check that the pinned axis has been dropped from cvar
+ pinned_axes = location.keys()
+ assert not any(
+ axis in t.axes for t in varfont["cvar"].variations for axis in pinned_axes
+ )
+
+ def test_full_instance(self, varfont):
+ instancer.instantiateCvar(varfont, {"wght": -0.5, "wdth": -0.5})
+
+ assert list(varfont["cvt "].values) == [500, -400, 165, 225]
+
+ assert "cvar" not in varfont
+
+
+class InstantiateMVARTest(object):
+ @pytest.mark.parametrize(
+ "location, expected",
+ [
+ pytest.param(
+ {"wght": 1.0},
+ {"strs": 100, "undo": -200, "unds": 150, "xhgt": 530},
+ id="wght=1.0",
+ ),
+ pytest.param(
+ {"wght": 0.5},
+ {"strs": 75, "undo": -150, "unds": 100, "xhgt": 515},
+ id="wght=0.5",
+ ),
+ pytest.param(
+ {"wght": 0.0},
+ {"strs": 50, "undo": -100, "unds": 50, "xhgt": 500},
+ id="wght=0.0",
+ ),
+ pytest.param(
+ {"wdth": -1.0},
+ {"strs": 20, "undo": -100, "unds": 50, "xhgt": 500},
+ id="wdth=-1.0",
+ ),
+ pytest.param(
+ {"wdth": -0.5},
+ {"strs": 35, "undo": -100, "unds": 50, "xhgt": 500},
+ id="wdth=-0.5",
+ ),
+ pytest.param(
+ {"wdth": 0.0},
+ {"strs": 50, "undo": -100, "unds": 50, "xhgt": 500},
+ id="wdth=0.0",
+ ),
+ ],
+ )
+ def test_pin_and_drop_axis(self, varfont, location, expected):
+ mvar = varfont["MVAR"].table
+ # initially we have two VarData: the first contains deltas associated with 3
+ # regions: 1 with only wght, 1 with only wdth, and 1 with both wght and wdth
+ assert len(mvar.VarStore.VarData) == 2
+ assert mvar.VarStore.VarRegionList.RegionCount == 3
+ assert mvar.VarStore.VarData[0].VarRegionCount == 3
+ assert all(len(item) == 3 for item in mvar.VarStore.VarData[0].Item)
+ # The second VarData has deltas associated only with 1 region (wght only).
+ assert mvar.VarStore.VarData[1].VarRegionCount == 1
+ assert all(len(item) == 1 for item in mvar.VarStore.VarData[1].Item)
+
+ instancer.instantiateMVAR(varfont, location)
+
+ for mvar_tag, expected_value in expected.items():
+ table_tag, item_name = MVAR_ENTRIES[mvar_tag]
+ assert getattr(varfont[table_tag], item_name) == expected_value
+
+ # check that regions and accompanying deltas have been dropped
+ num_regions_left = len(mvar.VarStore.VarRegionList.Region)
+ assert num_regions_left < 3
+ assert mvar.VarStore.VarRegionList.RegionCount == num_regions_left
+ assert mvar.VarStore.VarData[0].VarRegionCount == num_regions_left
+ # VarData subtables have been merged
+ assert len(mvar.VarStore.VarData) == 1
+
+ @pytest.mark.parametrize(
+ "location, expected",
+ [
+ pytest.param(
+ {"wght": 1.0, "wdth": 0.0},
+ {"strs": 100, "undo": -200, "unds": 150},
+ id="wght=1.0,wdth=0.0",
+ ),
+ pytest.param(
+ {"wght": 0.0, "wdth": -1.0},
+ {"strs": 20, "undo": -100, "unds": 50},
+ id="wght=0.0,wdth=-1.0",
+ ),
+ pytest.param(
+ {"wght": 0.5, "wdth": -0.5},
+ {"strs": 55, "undo": -145, "unds": 95},
+ id="wght=0.5,wdth=-0.5",
+ ),
+ pytest.param(
+ {"wght": 1.0, "wdth": -1.0},
+ {"strs": 50, "undo": -180, "unds": 130},
+ id="wght=0.5,wdth=-0.5",
+ ),
+ ],
+ )
+ def test_full_instance(self, varfont, location, expected):
+ instancer.instantiateMVAR(varfont, location)
+
+ for mvar_tag, expected_value in expected.items():
+ table_tag, item_name = MVAR_ENTRIES[mvar_tag]
+ assert getattr(varfont[table_tag], item_name) == expected_value
+
+ assert "MVAR" not in varfont
+
+
+class InstantiateHVARTest(object):
+ # the 'expectedDeltas' below refer to the VarData item deltas for the "hyphen"
+ # glyph in the PartialInstancerTest-VF.ttx test font, that are left after
+ # partial instancing
+ @pytest.mark.parametrize(
+ "location, expectedRegions, expectedDeltas",
+ [
+ ({"wght": -1.0}, [{"wdth": (-1.0, -1.0, 0)}], [-59]),
+ ({"wght": 0}, [{"wdth": (-1.0, -1.0, 0)}], [-48]),
+ ({"wght": 1.0}, [{"wdth": (-1.0, -1.0, 0)}], [7]),
+ (
+ {"wdth": -1.0},
+ [
+ {"wght": (-1.0, -1.0, 0.0)},
+ {"wght": (0.0, 0.61, 1.0)},
+ {"wght": (0.61, 1.0, 1.0)},
+ ],
+ [-11, 31, 51],
+ ),
+ ({"wdth": 0}, [{"wght": (0.61, 1.0, 1.0)}], [-4]),
+ ],
+ )
+ def test_partial_instance(self, varfont, location, expectedRegions, expectedDeltas):
+ instancer.instantiateHVAR(varfont, location)
+
+ assert "HVAR" in varfont
+ hvar = varfont["HVAR"].table
+ varStore = hvar.VarStore
+
+ regions = varStore.VarRegionList.Region
+ fvarAxes = [a for a in varfont["fvar"].axes if a.axisTag not in location]
+ assert [reg.get_support(fvarAxes) for reg in regions] == expectedRegions
+
+ assert len(varStore.VarData) == 1
+ assert varStore.VarData[0].ItemCount == 2
+
+ assert hvar.AdvWidthMap is not None
+ advWithMap = hvar.AdvWidthMap.mapping
+
+ assert advWithMap[".notdef"] == advWithMap["space"]
+ varIdx = advWithMap[".notdef"]
+ # these glyphs have no metrics variations in the test font
+ assert varStore.VarData[varIdx >> 16].Item[varIdx & 0xFFFF] == (
+ [0] * varStore.VarData[0].VarRegionCount
+ )
+
+ varIdx = advWithMap["hyphen"]
+ assert varStore.VarData[varIdx >> 16].Item[varIdx & 0xFFFF] == expectedDeltas
+
+ def test_full_instance(self, varfont):
+ instancer.instantiateHVAR(varfont, {"wght": 0, "wdth": 0})
+
+ assert "HVAR" not in varfont
+
+
+class InstantiateItemVariationStoreTest(object):
+ def test_VarRegion_get_support(self):
+ axisOrder = ["wght", "wdth", "opsz"]
+ regionAxes = {"wdth": (-1.0, -1.0, 0.0), "wght": (0.0, 1.0, 1.0)}
+ region = builder.buildVarRegion(regionAxes, axisOrder)
+
+ assert len(region.VarRegionAxis) == 3
+ assert region.VarRegionAxis[2].PeakCoord == 0
+
+ fvarAxes = [SimpleNamespace(axisTag=axisTag) for axisTag in axisOrder]
+
+ assert region.get_support(fvarAxes) == regionAxes
+
+ @pytest.fixture
+ def varStore(self):
+ return builder.buildVarStore(
+ builder.buildVarRegionList(
+ [
+ {"wght": (-1.0, -1.0, 0)},
+ {"wght": (0, 0.5, 1.0)},
+ {"wght": (0.5, 1.0, 1.0)},
+ {"wdth": (-1.0, -1.0, 0)},
+ {"wght": (-1.0, -1.0, 0), "wdth": (-1.0, -1.0, 0)},
+ {"wght": (0, 0.5, 1.0), "wdth": (-1.0, -1.0, 0)},
+ {"wght": (0.5, 1.0, 1.0), "wdth": (-1.0, -1.0, 0)},
+ ],
+ ["wght", "wdth"],
+ ),
+ [
+ builder.buildVarData([0, 1, 2], [[100, 100, 100], [100, 100, 100]]),
+ builder.buildVarData(
+ [3, 4, 5, 6], [[100, 100, 100, 100], [100, 100, 100, 100]]
+ ),
+ ],
+ )
+
+ @pytest.mark.parametrize(
+ "location, expected_deltas, num_regions",
+ [
+ ({"wght": 0}, [[0, 0], [0, 0]], 1),
+ ({"wght": 0.25}, [[50, 50], [0, 0]], 1),
+ ({"wdth": 0}, [[0, 0], [0, 0]], 3),
+ ({"wdth": -0.75}, [[0, 0], [75, 75]], 3),
+ ({"wght": 0, "wdth": 0}, [[0, 0], [0, 0]], 0),
+ ({"wght": 0.25, "wdth": 0}, [[50, 50], [0, 0]], 0),
+ ({"wght": 0, "wdth": -0.75}, [[0, 0], [75, 75]], 0),
+ ],
+ )
+ def test_instantiate_default_deltas(
+ self, varStore, fvarAxes, location, expected_deltas, num_regions
+ ):
+ defaultDeltas = instancer.instantiateItemVariationStore(
+ varStore, fvarAxes, location
+ )
+
+ defaultDeltaArray = []
+ for varidx, delta in sorted(defaultDeltas.items()):
+ major, minor = varidx >> 16, varidx & 0xFFFF
+ if major == len(defaultDeltaArray):
+ defaultDeltaArray.append([])
+ assert len(defaultDeltaArray[major]) == minor
+ defaultDeltaArray[major].append(delta)
+
+ assert defaultDeltaArray == expected_deltas
+ assert varStore.VarRegionList.RegionCount == num_regions
+
+
+class TupleVarStoreAdapterTest(object):
+ def test_instantiate(self):
+ regions = [
+ {"wght": (-1.0, -1.0, 0)},
+ {"wght": (0.0, 1.0, 1.0)},
+ {"wdth": (-1.0, -1.0, 0)},
+ {"wght": (-1.0, -1.0, 0), "wdth": (-1.0, -1.0, 0)},
+ {"wght": (0, 1.0, 1.0), "wdth": (-1.0, -1.0, 0)},
+ ]
+ axisOrder = ["wght", "wdth"]
+ tupleVarData = [
+ [
+ TupleVariation({"wght": (-1.0, -1.0, 0)}, [10, 70]),
+ TupleVariation({"wght": (0.0, 1.0, 1.0)}, [30, 90]),
+ TupleVariation(
+ {"wght": (-1.0, -1.0, 0), "wdth": (-1.0, -1.0, 0)}, [-40, -100]
+ ),
+ TupleVariation(
+ {"wght": (0, 1.0, 1.0), "wdth": (-1.0, -1.0, 0)}, [-60, -120]
+ ),
+ ],
+ [
+ TupleVariation({"wdth": (-1.0, -1.0, 0)}, [5, 45]),
+ TupleVariation(
+ {"wght": (-1.0, -1.0, 0), "wdth": (-1.0, -1.0, 0)}, [-15, -55]
+ ),
+ TupleVariation(
+ {"wght": (0, 1.0, 1.0), "wdth": (-1.0, -1.0, 0)}, [-35, -75]
+ ),
+ ],
+ ]
+ adapter = instancer._TupleVarStoreAdapter(
+ regions, axisOrder, tupleVarData, itemCounts=[2, 2]
+ )
+
+ defaultDeltaArray = adapter.instantiate({"wght": 0.5})
+
+ assert defaultDeltaArray == [[15, 45], [0, 0]]
+ assert adapter.regions == [{"wdth": (-1.0, -1.0, 0)}]
+ assert adapter.tupleVarData == [
+ [TupleVariation({"wdth": (-1.0, -1.0, 0)}, [-30, -60])],
+ [TupleVariation({"wdth": (-1.0, -1.0, 0)}, [-12, 8])],
+ ]
+
+ def test_dropAxes(self):
+ regions = [
+ {"wght": (-1.0, -1.0, 0)},
+ {"wght": (0.0, 1.0, 1.0)},
+ {"wdth": (-1.0, -1.0, 0)},
+ {"opsz": (0.0, 1.0, 1.0)},
+ {"wght": (-1.0, -1.0, 0), "wdth": (-1.0, -1.0, 0)},
+ {"wght": (0, 0.5, 1.0), "wdth": (-1.0, -1.0, 0)},
+ {"wght": (0.5, 1.0, 1.0), "wdth": (-1.0, -1.0, 0)},
+ ]
+ axisOrder = ["wght", "wdth", "opsz"]
+ adapter = instancer._TupleVarStoreAdapter(regions, axisOrder, [], itemCounts=[])
+
+ adapter.dropAxes({"wdth"})
+
+ assert adapter.regions == [
+ {"wght": (-1.0, -1.0, 0)},
+ {"wght": (0.0, 1.0, 1.0)},
+ {"opsz": (0.0, 1.0, 1.0)},
+ {"wght": (0.0, 0.5, 1.0)},
+ {"wght": (0.5, 1.0, 1.0)},
+ ]
+
+ adapter.dropAxes({"wght", "opsz"})
+
+ assert adapter.regions == []
+
+ def test_roundtrip(self, fvarAxes):
+ regions = [
+ {"wght": (-1.0, -1.0, 0)},
+ {"wght": (0, 0.5, 1.0)},
+ {"wght": (0.5, 1.0, 1.0)},
+ {"wdth": (-1.0, -1.0, 0)},
+ {"wght": (-1.0, -1.0, 0), "wdth": (-1.0, -1.0, 0)},
+ {"wght": (0, 0.5, 1.0), "wdth": (-1.0, -1.0, 0)},
+ {"wght": (0.5, 1.0, 1.0), "wdth": (-1.0, -1.0, 0)},
+ ]
+ axisOrder = [axis.axisTag for axis in fvarAxes]
+
+ itemVarStore = builder.buildVarStore(
+ builder.buildVarRegionList(regions, axisOrder),
+ [
+ builder.buildVarData(
+ [0, 1, 2, 4, 5, 6],
+ [[10, -20, 30, -40, 50, -60], [70, -80, 90, -100, 110, -120]],
+ ),
+ builder.buildVarData(
+ [3, 4, 5, 6], [[5, -15, 25, -35], [45, -55, 65, -75]]
+ ),
+ ],
+ )
+
+ adapter = instancer._TupleVarStoreAdapter.fromItemVarStore(
+ itemVarStore, fvarAxes
+ )
+
+ assert adapter.tupleVarData == [
+ [
+ TupleVariation({"wght": (-1.0, -1.0, 0)}, [10, 70]),
+ TupleVariation({"wght": (0, 0.5, 1.0)}, [-20, -80]),
+ TupleVariation({"wght": (0.5, 1.0, 1.0)}, [30, 90]),
+ TupleVariation(
+ {"wght": (-1.0, -1.0, 0), "wdth": (-1.0, -1.0, 0)}, [-40, -100]
+ ),
+ TupleVariation(
+ {"wght": (0, 0.5, 1.0), "wdth": (-1.0, -1.0, 0)}, [50, 110]
+ ),
+ TupleVariation(
+ {"wght": (0.5, 1.0, 1.0), "wdth": (-1.0, -1.0, 0)}, [-60, -120]
+ ),
+ ],
+ [
+ TupleVariation({"wdth": (-1.0, -1.0, 0)}, [5, 45]),
+ TupleVariation(
+ {"wght": (-1.0, -1.0, 0), "wdth": (-1.0, -1.0, 0)}, [-15, -55]
+ ),
+ TupleVariation(
+ {"wght": (0, 0.5, 1.0), "wdth": (-1.0, -1.0, 0)}, [25, 65]
+ ),
+ TupleVariation(
+ {"wght": (0.5, 1.0, 1.0), "wdth": (-1.0, -1.0, 0)}, [-35, -75]
+ ),
+ ],
+ ]
+ assert adapter.itemCounts == [data.ItemCount for data in itemVarStore.VarData]
+ assert adapter.regions == regions
+ assert adapter.axisOrder == axisOrder
+
+ itemVarStore2 = adapter.asItemVarStore()
+
+ assert [
+ reg.get_support(fvarAxes) for reg in itemVarStore2.VarRegionList.Region
+ ] == regions
+
+ assert itemVarStore2.VarDataCount == 2
+ assert itemVarStore2.VarData[0].VarRegionIndex == [0, 1, 2, 4, 5, 6]
+ assert itemVarStore2.VarData[0].Item == [
+ [10, -20, 30, -40, 50, -60],
+ [70, -80, 90, -100, 110, -120],
+ ]
+ assert itemVarStore2.VarData[1].VarRegionIndex == [3, 4, 5, 6]
+ assert itemVarStore2.VarData[1].Item == [[5, -15, 25, -35], [45, -55, 65, -75]]
+
+
+def makeTTFont(glyphOrder, features):
+ font = ttLib.TTFont()
+ font.setGlyphOrder(glyphOrder)
+ addOpenTypeFeaturesFromString(font, features)
+ font["name"] = ttLib.newTable("name")
+ return font
+
+
+def _makeDSAxesDict(axes):
+ dsAxes = collections.OrderedDict()
+ for axisTag, axisValues in axes:
+ axis = designspaceLib.AxisDescriptor()
+ axis.name = axis.tag = axis.labelNames["en"] = axisTag
+ axis.minimum, axis.default, axis.maximum = axisValues
+ dsAxes[axis.tag] = axis
+ return dsAxes
+
+
+def makeVariableFont(masters, baseIndex, axes, masterLocations):
+ vf = deepcopy(masters[baseIndex])
+ dsAxes = _makeDSAxesDict(axes)
+ fvar = varLib._add_fvar(vf, dsAxes, instances=())
+ axisTags = [axis.axisTag for axis in fvar.axes]
+ normalizedLocs = [models.normalizeLocation(m, dict(axes)) for m in masterLocations]
+ model = models.VariationModel(normalizedLocs, axisOrder=axisTags)
+ varLib._merge_OTL(vf, model, masters, axisTags)
+ return vf
+
+
+def makeParametrizedVF(glyphOrder, features, values, increments):
+ # Create a test VF with given glyphs and parametrized OTL features.
+ # The VF is built from 9 masters (3 x 3 along wght and wdth), with
+ # locations hard-coded and base master at wght=400 and wdth=100.
+ # 'values' is a list of initial values that are interpolated in the
+ # 'features' string, and incremented for each subsequent master by the
+ # given 'increments' (list of 2-tuple) along the two axes.
+ assert values and len(values) == len(increments)
+ assert all(len(i) == 2 for i in increments)
+ masterLocations = [
+ {"wght": 100, "wdth": 50},
+ {"wght": 100, "wdth": 100},
+ {"wght": 100, "wdth": 150},
+ {"wght": 400, "wdth": 50},
+ {"wght": 400, "wdth": 100}, # base master
+ {"wght": 400, "wdth": 150},
+ {"wght": 700, "wdth": 50},
+ {"wght": 700, "wdth": 100},
+ {"wght": 700, "wdth": 150},
+ ]
+ n = len(values)
+ values = list(values)
+ masters = []
+ for _ in range(3):
+ for _ in range(3):
+ master = makeTTFont(glyphOrder, features=features % tuple(values))
+ masters.append(master)
+ for i in range(n):
+ values[i] += increments[i][1]
+ for i in range(n):
+ values[i] += increments[i][0]
+ baseIndex = 4
+ axes = [("wght", (100, 400, 700)), ("wdth", (50, 100, 150))]
+ vf = makeVariableFont(masters, baseIndex, axes, masterLocations)
+ return vf
+
+
+@pytest.fixture
+def varfontGDEF():
+ glyphOrder = [".notdef", "f", "i", "f_i"]
+ features = (
+ "feature liga { sub f i by f_i;} liga;"
+ "table GDEF { LigatureCaretByPos f_i %d; } GDEF;"
+ )
+ values = [100]
+ increments = [(+30, +10)]
+ return makeParametrizedVF(glyphOrder, features, values, increments)
+
+
+@pytest.fixture
+def varfontGPOS():
+ glyphOrder = [".notdef", "V", "A"]
+ features = "feature kern { pos V A %d; } kern;"
+ values = [-80]
+ increments = [(-10, -5)]
+ return makeParametrizedVF(glyphOrder, features, values, increments)
+
+
+@pytest.fixture
+def varfontGPOS2():
+ glyphOrder = [".notdef", "V", "A", "acutecomb"]
+ features = (
+ "markClass [acutecomb] @TOP_MARKS;"
+ "feature mark {"
+ " pos base A mark @TOP_MARKS;"
+ "} mark;"
+ "feature kern {"
+ " pos V A %d;"
+ "} kern;"
+ )
+ values = [200, -80]
+ increments = [(+30, +10), (-10, -5)]
+ return makeParametrizedVF(glyphOrder, features, values, increments)
+
+
+class InstantiateOTLTest(object):
+ @pytest.mark.parametrize(
+ "location, expected",
+ [
+ ({"wght": -1.0}, 110), # -60
+ ({"wght": 0}, 170),
+ ({"wght": 0.5}, 200), # +30
+ ({"wght": 1.0}, 230), # +60
+ ({"wdth": -1.0}, 160), # -10
+ ({"wdth": -0.3}, 167), # -3
+ ({"wdth": 0}, 170),
+ ({"wdth": 1.0}, 180), # +10
+ ],
+ )
+ def test_pin_and_drop_axis_GDEF(self, varfontGDEF, location, expected):
+ vf = varfontGDEF
+ assert "GDEF" in vf
+
+ instancer.instantiateOTL(vf, location)
+
+ assert "GDEF" in vf
+ gdef = vf["GDEF"].table
+ assert gdef.Version == 0x00010003
+ assert gdef.VarStore
+ assert gdef.LigCaretList
+ caretValue = gdef.LigCaretList.LigGlyph[0].CaretValue[0]
+ assert caretValue.Format == 3
+ assert hasattr(caretValue, "DeviceTable")
+ assert caretValue.DeviceTable.DeltaFormat == 0x8000
+ assert caretValue.Coordinate == expected
+
+ @pytest.mark.parametrize(
+ "location, expected",
+ [
+ ({"wght": -1.0, "wdth": -1.0}, 100), # -60 - 10
+ ({"wght": -1.0, "wdth": 0.0}, 110), # -60
+ ({"wght": -1.0, "wdth": 1.0}, 120), # -60 + 10
+ ({"wght": 0.0, "wdth": -1.0}, 160), # -10
+ ({"wght": 0.0, "wdth": 0.0}, 170),
+ ({"wght": 0.0, "wdth": 1.0}, 180), # +10
+ ({"wght": 1.0, "wdth": -1.0}, 220), # +60 - 10
+ ({"wght": 1.0, "wdth": 0.0}, 230), # +60
+ ({"wght": 1.0, "wdth": 1.0}, 240), # +60 + 10
+ ],
+ )
+ def test_full_instance_GDEF(self, varfontGDEF, location, expected):
+ vf = varfontGDEF
+ assert "GDEF" in vf
+
+ instancer.instantiateOTL(vf, location)
+
+ assert "GDEF" in vf
+ gdef = vf["GDEF"].table
+ assert gdef.Version == 0x00010000
+ assert not hasattr(gdef, "VarStore")
+ assert gdef.LigCaretList
+ caretValue = gdef.LigCaretList.LigGlyph[0].CaretValue[0]
+ assert caretValue.Format == 1
+ assert not hasattr(caretValue, "DeviceTable")
+ assert caretValue.Coordinate == expected
+
+ @pytest.mark.parametrize(
+ "location, expected",
+ [
+ ({"wght": -1.0}, -85), # +25
+ ({"wght": 0}, -110),
+ ({"wght": 1.0}, -135), # -25
+ ({"wdth": -1.0}, -105), # +5
+ ({"wdth": 0}, -110),
+ ({"wdth": 1.0}, -115), # -5
+ ],
+ )
+ def test_pin_and_drop_axis_GPOS_kern(self, varfontGPOS, location, expected):
+ vf = varfontGPOS
+ assert "GDEF" in vf
+ assert "GPOS" in vf
+
+ instancer.instantiateOTL(vf, location)
+
+ gdef = vf["GDEF"].table
+ gpos = vf["GPOS"].table
+ assert gdef.Version == 0x00010003
+ assert gdef.VarStore
+
+ assert gpos.LookupList.Lookup[0].LookupType == 2 # PairPos
+ pairPos = gpos.LookupList.Lookup[0].SubTable[0]
+ valueRec1 = pairPos.PairSet[0].PairValueRecord[0].Value1
+ assert valueRec1.XAdvDevice
+ assert valueRec1.XAdvDevice.DeltaFormat == 0x8000
+ assert valueRec1.XAdvance == expected
+
+ @pytest.mark.parametrize(
+ "location, expected",
+ [
+ ({"wght": -1.0, "wdth": -1.0}, -80), # +25 + 5
+ ({"wght": -1.0, "wdth": 0.0}, -85), # +25
+ ({"wght": -1.0, "wdth": 1.0}, -90), # +25 - 5
+ ({"wght": 0.0, "wdth": -1.0}, -105), # +5
+ ({"wght": 0.0, "wdth": 0.0}, -110),
+ ({"wght": 0.0, "wdth": 1.0}, -115), # -5
+ ({"wght": 1.0, "wdth": -1.0}, -130), # -25 + 5
+ ({"wght": 1.0, "wdth": 0.0}, -135), # -25
+ ({"wght": 1.0, "wdth": 1.0}, -140), # -25 - 5
+ ],
+ )
+ def test_full_instance_GPOS_kern(self, varfontGPOS, location, expected):
+ vf = varfontGPOS
+ assert "GDEF" in vf
+ assert "GPOS" in vf
+
+ instancer.instantiateOTL(vf, location)
+
+ assert "GDEF" not in vf
+ gpos = vf["GPOS"].table
+
+ assert gpos.LookupList.Lookup[0].LookupType == 2 # PairPos
+ pairPos = gpos.LookupList.Lookup[0].SubTable[0]
+ valueRec1 = pairPos.PairSet[0].PairValueRecord[0].Value1
+ assert not hasattr(valueRec1, "XAdvDevice")
+ assert valueRec1.XAdvance == expected
+
+ @pytest.mark.parametrize(
+ "location, expected",
+ [
+ ({"wght": -1.0}, (210, -85)), # -60, +25
+ ({"wght": 0}, (270, -110)),
+ ({"wght": 0.5}, (300, -122)), # +30, -12
+ ({"wght": 1.0}, (330, -135)), # +60, -25
+ ({"wdth": -1.0}, (260, -105)), # -10, +5
+ ({"wdth": -0.3}, (267, -108)), # -3, +2
+ ({"wdth": 0}, (270, -110)),
+ ({"wdth": 1.0}, (280, -115)), # +10, -5
+ ],
+ )
+ def test_pin_and_drop_axis_GPOS_mark_and_kern(
+ self, varfontGPOS2, location, expected
+ ):
+ vf = varfontGPOS2
+ assert "GDEF" in vf
+ assert "GPOS" in vf
+
+ instancer.instantiateOTL(vf, location)
+
+ v1, v2 = expected
+ gdef = vf["GDEF"].table
+ gpos = vf["GPOS"].table
+ assert gdef.Version == 0x00010003
+ assert gdef.VarStore
+ assert gdef.GlyphClassDef
+
+ assert gpos.LookupList.Lookup[0].LookupType == 4 # MarkBasePos
+ markBasePos = gpos.LookupList.Lookup[0].SubTable[0]
+ baseAnchor = markBasePos.BaseArray.BaseRecord[0].BaseAnchor[0]
+ assert baseAnchor.Format == 3
+ assert baseAnchor.XDeviceTable
+ assert baseAnchor.XDeviceTable.DeltaFormat == 0x8000
+ assert not baseAnchor.YDeviceTable
+ assert baseAnchor.XCoordinate == v1
+ assert baseAnchor.YCoordinate == 450
+
+ assert gpos.LookupList.Lookup[1].LookupType == 2 # PairPos
+ pairPos = gpos.LookupList.Lookup[1].SubTable[0]
+ valueRec1 = pairPos.PairSet[0].PairValueRecord[0].Value1
+ assert valueRec1.XAdvDevice
+ assert valueRec1.XAdvDevice.DeltaFormat == 0x8000
+ assert valueRec1.XAdvance == v2
+
+ @pytest.mark.parametrize(
+ "location, expected",
+ [
+ ({"wght": -1.0, "wdth": -1.0}, (200, -80)), # -60 - 10, +25 + 5
+ ({"wght": -1.0, "wdth": 0.0}, (210, -85)), # -60, +25
+ ({"wght": -1.0, "wdth": 1.0}, (220, -90)), # -60 + 10, +25 - 5
+ ({"wght": 0.0, "wdth": -1.0}, (260, -105)), # -10, +5
+ ({"wght": 0.0, "wdth": 0.0}, (270, -110)),
+ ({"wght": 0.0, "wdth": 1.0}, (280, -115)), # +10, -5
+ ({"wght": 1.0, "wdth": -1.0}, (320, -130)), # +60 - 10, -25 + 5
+ ({"wght": 1.0, "wdth": 0.0}, (330, -135)), # +60, -25
+ ({"wght": 1.0, "wdth": 1.0}, (340, -140)), # +60 + 10, -25 - 5
+ ],
+ )
+ def test_full_instance_GPOS_mark_and_kern(self, varfontGPOS2, location, expected):
+ vf = varfontGPOS2
+ assert "GDEF" in vf
+ assert "GPOS" in vf
+
+ instancer.instantiateOTL(vf, location)
+
+ v1, v2 = expected
+ gdef = vf["GDEF"].table
+ gpos = vf["GPOS"].table
+ assert gdef.Version == 0x00010000
+ assert not hasattr(gdef, "VarStore")
+ assert gdef.GlyphClassDef
+
+ assert gpos.LookupList.Lookup[0].LookupType == 4 # MarkBasePos
+ markBasePos = gpos.LookupList.Lookup[0].SubTable[0]
+ baseAnchor = markBasePos.BaseArray.BaseRecord[0].BaseAnchor[0]
+ assert baseAnchor.Format == 1
+ assert not hasattr(baseAnchor, "XDeviceTable")
+ assert not hasattr(baseAnchor, "YDeviceTable")
+ assert baseAnchor.XCoordinate == v1
+ assert baseAnchor.YCoordinate == 450
+
+ assert gpos.LookupList.Lookup[1].LookupType == 2 # PairPos
+ pairPos = gpos.LookupList.Lookup[1].SubTable[0]
+ valueRec1 = pairPos.PairSet[0].PairValueRecord[0].Value1
+ assert not hasattr(valueRec1, "XAdvDevice")
+ assert valueRec1.XAdvance == v2
+
+
+class InstantiateAvarTest(object):
+ @pytest.mark.parametrize("location", [{"wght": 0.0}, {"wdth": 0.0}])
+ def test_pin_and_drop_axis(self, varfont, location):
+ instancer.instantiateAvar(varfont, location)
+
+ assert set(varfont["avar"].segments).isdisjoint(location)
+
+ def test_full_instance(self, varfont):
+ instancer.instantiateAvar(varfont, {"wght": 0.0, "wdth": 0.0})
+
+ assert "avar" not in varfont
+
+
+class InstantiateFvarTest(object):
+ @pytest.mark.parametrize(
+ "location, instancesLeft",
+ [
+ (
+ {"wght": 400.0},
+ ["Regular", "SemiCondensed", "Condensed", "ExtraCondensed"],
+ ),
+ (
+ {"wght": 100.0},
+ ["Thin", "SemiCondensed Thin", "Condensed Thin", "ExtraCondensed Thin"],
+ ),
+ (
+ {"wdth": 100.0},
+ [
+ "Thin",
+ "ExtraLight",
+ "Light",
+ "Regular",
+ "Medium",
+ "SemiBold",
+ "Bold",
+ "ExtraBold",
+ "Black",
+ ],
+ ),
+ # no named instance at pinned location
+ ({"wdth": 90.0}, []),
+ ],
+ )
+ def test_pin_and_drop_axis(self, varfont, location, instancesLeft):
+ instancer.instantiateFvar(varfont, location)
+
+ fvar = varfont["fvar"]
+ assert {a.axisTag for a in fvar.axes}.isdisjoint(location)
+
+ for instance in fvar.instances:
+ assert set(instance.coordinates).isdisjoint(location)
+
+ name = varfont["name"]
+ assert [
+ name.getDebugName(instance.subfamilyNameID) for instance in fvar.instances
+ ] == instancesLeft
+
+ def test_full_instance(self, varfont):
+ instancer.instantiateFvar(varfont, {"wght": 0.0, "wdth": 0.0})
+
+ assert "fvar" not in varfont
+
+
+class InstantiateSTATTest(object):
+ @pytest.mark.parametrize(
+ "location, expected",
+ [
+ ({"wght": 400}, ["Condensed", "Upright"]),
+ ({"wdth": 100}, ["Thin", "Regular", "Black", "Upright"]),
+ ],
+ )
+ def test_pin_and_drop_axis(self, varfont, location, expected):
+ instancer.instantiateSTAT(varfont, location)
+
+ stat = varfont["STAT"].table
+ designAxes = {a.AxisTag for a in stat.DesignAxisRecord.Axis}
+
+ assert designAxes == {"wght", "wdth", "ital"}.difference(location)
+
+ name = varfont["name"]
+ valueNames = []
+ for axisValueTable in stat.AxisValueArray.AxisValue:
+ valueName = name.getDebugName(axisValueTable.ValueNameID)
+ valueNames.append(valueName)
+
+ assert valueNames == expected
+
+ def test_skip_empty_table(self, varfont):
+ stat = otTables.STAT()
+ stat.Version = 0x00010001
+ stat.populateDefaults()
+ assert not stat.DesignAxisRecord
+ assert not stat.AxisValueArray
+ varfont["STAT"].table = stat
+
+ instancer.instantiateSTAT(varfont, {"wght": 100})
+
+ assert not varfont["STAT"].table.DesignAxisRecord
+
+ def test_drop_table(self, varfont):
+ stat = otTables.STAT()
+ stat.Version = 0x00010001
+ stat.populateDefaults()
+ stat.DesignAxisRecord = otTables.AxisRecordArray()
+ axis = otTables.AxisRecord()
+ axis.AxisTag = "wght"
+ axis.AxisNameID = 0
+ axis.AxisOrdering = 0
+ stat.DesignAxisRecord.Axis = [axis]
+ varfont["STAT"].table = stat
+
+ instancer.instantiateSTAT(varfont, {"wght": 100})
+
+ assert "STAT" not in varfont
+
+
+def test_pruningUnusedNames(varfont):
+ varNameIDs = instancer.getVariationNameIDs(varfont)
+
+ assert varNameIDs == set(range(256, 296 + 1))
+
+ fvar = varfont["fvar"]
+ stat = varfont["STAT"].table
+
+ with instancer.pruningUnusedNames(varfont):
+ del fvar.axes[0] # Weight (nameID=256)
+ del fvar.instances[0] # Thin (nameID=258)
+ del stat.DesignAxisRecord.Axis[0] # Weight (nameID=256)
+ del stat.AxisValueArray.AxisValue[0] # Thin (nameID=258)
+
+ assert not any(n for n in varfont["name"].names if n.nameID in {256, 258})
+
+ with instancer.pruningUnusedNames(varfont):
+ del varfont["fvar"]
+ del varfont["STAT"]
+
+ assert not any(n for n in varfont["name"].names if n.nameID in varNameIDs)
+ assert "ltag" not in varfont
+
+
+def test_setMacOverlapFlags():
+ flagOverlapCompound = _g_l_y_f.OVERLAP_COMPOUND
+ flagOverlapSimple = _g_l_y_f.flagOverlapSimple
+
+ glyf = ttLib.newTable("glyf")
+ glyf.glyphOrder = ["a", "b", "c"]
+ a = _g_l_y_f.Glyph()
+ a.numberOfContours = 1
+ a.flags = [0]
+ b = _g_l_y_f.Glyph()
+ b.numberOfContours = -1
+ comp = _g_l_y_f.GlyphComponent()
+ comp.flags = 0
+ b.components = [comp]
+ c = _g_l_y_f.Glyph()
+ c.numberOfContours = 0
+ glyf.glyphs = {"a": a, "b": b, "c": c}
+
+ instancer.setMacOverlapFlags(glyf)
+
+ assert a.flags[0] & flagOverlapSimple != 0
+ assert b.components[0].flags & flagOverlapCompound != 0
+
+
+def _strip_ttLibVersion(string):
+ return re.sub(' ttLibVersion=".*"', "", string)
+
+
+@pytest.fixture
+def varfont2():
+ f = ttLib.TTFont(recalcTimestamp=False)
+ f.importXML(os.path.join(TESTDATA, "PartialInstancerTest2-VF.ttx"))
+ return f
+
+
+def _dump_ttx(ttFont):
+ # compile to temporary bytes stream, reload and dump to XML
+ tmp = BytesIO()
+ ttFont.save(tmp)
+ tmp.seek(0)
+ ttFont2 = ttLib.TTFont(tmp, recalcBBoxes=False, recalcTimestamp=False)
+ s = StringIO()
+ ttFont2.saveXML(s, newlinestr="\n")
+ return _strip_ttLibVersion(s.getvalue())
+
+
+def _get_expected_instance_ttx(wght, wdth):
+ with open(
+ os.path.join(
+ TESTDATA,
+ "test_results",
+ "PartialInstancerTest2-VF-instance-{0},{1}.ttx".format(wght, wdth),
+ ),
+ "r",
+ encoding="utf-8",
+ ) as fp:
+ return _strip_ttLibVersion(fp.read())
+
+
+class InstantiateVariableFontTest(object):
+ @pytest.mark.parametrize(
+ "wght, wdth",
+ [(100, 100), (400, 100), (900, 100), (100, 62.5), (400, 62.5), (900, 62.5)],
+ )
+ def test_multiple_instancing(self, varfont2, wght, wdth):
+ partial = instancer.instantiateVariableFont(varfont2, {"wght": wght})
+ instance = instancer.instantiateVariableFont(partial, {"wdth": wdth})
+
+ expected = _get_expected_instance_ttx(wght, wdth)
+
+ assert _dump_ttx(instance) == expected
+
+ def test_default_instance(self, varfont2):
+ instance = instancer.instantiateVariableFont(
+ varfont2, {"wght": None, "wdth": None}
+ )
+
+ expected = _get_expected_instance_ttx(400, 100)
+
+ assert _dump_ttx(instance) == expected
+
+
+def _conditionSetAsDict(conditionSet, axisOrder):
+ result = {}
+ for cond in conditionSet.ConditionTable:
+ assert cond.Format == 1
+ axisTag = axisOrder[cond.AxisIndex]
+ result[axisTag] = (cond.FilterRangeMinValue, cond.FilterRangeMaxValue)
+ return result
+
+
+def _getSubstitutions(gsub, lookupIndices):
+ subs = {}
+ for index, lookup in enumerate(gsub.LookupList.Lookup):
+ if index in lookupIndices:
+ for subtable in lookup.SubTable:
+ subs.update(subtable.mapping)
+ return subs
+
+
+def makeFeatureVarsFont(conditionalSubstitutions):
+ axes = set()
+ glyphs = set()
+ for region, substitutions in conditionalSubstitutions:
+ for box in region:
+ axes.update(box.keys())
+ glyphs.update(*substitutions.items())
+
+ varfont = ttLib.TTFont()
+ varfont.setGlyphOrder(sorted(glyphs))
+
+ fvar = varfont["fvar"] = ttLib.newTable("fvar")
+ fvar.axes = []
+ for axisTag in sorted(axes):
+ axis = _f_v_a_r.Axis()
+ axis.axisTag = Tag(axisTag)
+ fvar.axes.append(axis)
+
+ featureVars.addFeatureVariations(varfont, conditionalSubstitutions)
+
+ return varfont
+
+
+class InstantiateFeatureVariationsTest(object):
+ @pytest.mark.parametrize(
+ "location, appliedSubs, expectedRecords",
+ [
+ ({"wght": 0}, {}, [({"cntr": (0.75, 1.0)}, {"uni0041": "uni0061"})]),
+ (
+ {"wght": -1.0},
+ {},
+ [
+ ({"cntr": (0, 0.25)}, {"uni0061": "uni0041"}),
+ ({"cntr": (0.75, 1.0)}, {"uni0041": "uni0061"}),
+ ],
+ ),
+ (
+ {"wght": 1.0},
+ {"uni0024": "uni0024.nostroke"},
+ [
+ (
+ {"cntr": (0.75, 1.0)},
+ {"uni0024": "uni0024.nostroke", "uni0041": "uni0061"},
+ )
+ ],
+ ),
+ (
+ {"cntr": 0},
+ {},
+ [
+ ({"wght": (-1.0, -0.45654)}, {"uni0061": "uni0041"}),
+ ({"wght": (0.20886, 1.0)}, {"uni0024": "uni0024.nostroke"}),
+ ],
+ ),
+ (
+ {"cntr": 1.0},
+ {"uni0041": "uni0061"},
+ [
+ (
+ {"wght": (0.20886, 1.0)},
+ {"uni0024": "uni0024.nostroke", "uni0041": "uni0061"},
+ )
+ ],
+ ),
+ ],
+ )
+ def test_partial_instance(self, location, appliedSubs, expectedRecords):
+ font = makeFeatureVarsFont(
+ [
+ ([{"wght": (0.20886, 1.0)}], {"uni0024": "uni0024.nostroke"}),
+ ([{"cntr": (0.75, 1.0)}], {"uni0041": "uni0061"}),
+ (
+ [{"wght": (-1.0, -0.45654), "cntr": (0, 0.25)}],
+ {"uni0061": "uni0041"},
+ ),
+ ]
+ )
+
+ instancer.instantiateFeatureVariations(font, location)
+
+ gsub = font["GSUB"].table
+ featureVariations = gsub.FeatureVariations
+
+ assert featureVariations.FeatureVariationCount == len(expectedRecords)
+
+ axisOrder = [a.axisTag for a in font["fvar"].axes if a.axisTag not in location]
+ for i, (expectedConditionSet, expectedSubs) in enumerate(expectedRecords):
+ rec = featureVariations.FeatureVariationRecord[i]
+ conditionSet = _conditionSetAsDict(rec.ConditionSet, axisOrder)
+
+ assert conditionSet == expectedConditionSet
+
+ subsRecord = rec.FeatureTableSubstitution.SubstitutionRecord[0]
+ lookupIndices = subsRecord.Feature.LookupListIndex
+ substitutions = _getSubstitutions(gsub, lookupIndices)
+
+ assert substitutions == expectedSubs
+
+ appliedLookupIndices = gsub.FeatureList.FeatureRecord[0].Feature.LookupListIndex
+
+ assert _getSubstitutions(gsub, appliedLookupIndices) == appliedSubs
+
+ @pytest.mark.parametrize(
+ "location, appliedSubs",
+ [
+ ({"wght": 0, "cntr": 0}, None),
+ ({"wght": -1.0, "cntr": 0}, {"uni0061": "uni0041"}),
+ ({"wght": 1.0, "cntr": 0}, {"uni0024": "uni0024.nostroke"}),
+ ({"wght": 0.0, "cntr": 1.0}, {"uni0041": "uni0061"}),
+ (
+ {"wght": 1.0, "cntr": 1.0},
+ {"uni0041": "uni0061", "uni0024": "uni0024.nostroke"},
+ ),
+ ({"wght": -1.0, "cntr": 0.3}, None),
+ ],
+ )
+ def test_full_instance(self, location, appliedSubs):
+ font = makeFeatureVarsFont(
+ [
+ ([{"wght": (0.20886, 1.0)}], {"uni0024": "uni0024.nostroke"}),
+ ([{"cntr": (0.75, 1.0)}], {"uni0041": "uni0061"}),
+ (
+ [{"wght": (-1.0, -0.45654), "cntr": (0, 0.25)}],
+ {"uni0061": "uni0041"},
+ ),
+ ]
+ )
+
+ instancer.instantiateFeatureVariations(font, location)
+
+ gsub = font["GSUB"].table
+ assert not hasattr(gsub, "FeatureVariations")
+
+ if appliedSubs:
+ lookupIndices = gsub.FeatureList.FeatureRecord[0].Feature.LookupListIndex
+ assert _getSubstitutions(gsub, lookupIndices) == appliedSubs
+ else:
+ assert not gsub.FeatureList.FeatureRecord
+
+ def test_unsupported_condition_format(self, caplog):
+ font = makeFeatureVarsFont(
+ [
+ (
+ [{"wdth": (-1.0, -0.5), "wght": (0.5, 1.0)}],
+ {"dollar": "dollar.nostroke"},
+ )
+ ]
+ )
+ featureVariations = font["GSUB"].table.FeatureVariations
+ rec1 = featureVariations.FeatureVariationRecord[0]
+ assert len(rec1.ConditionSet.ConditionTable) == 2
+ rec1.ConditionSet.ConditionTable[0].Format = 2
+
+ with caplog.at_level(logging.WARNING, logger="fontTools.varLib.instancer"):
+ instancer.instantiateFeatureVariations(font, {"wdth": 0})
+
+ assert (
+ "Condition table 0 of FeatureVariationRecord 0 "
+ "has unsupported format (2); ignored"
+ ) in caplog.text
+
+ # check that record with unsupported condition format (but whose other
+ # conditions do not reference pinned axes) is kept as is
+ featureVariations = font["GSUB"].table.FeatureVariations
+ assert featureVariations.FeatureVariationRecord[0] is rec1
+ assert len(rec1.ConditionSet.ConditionTable) == 2
+ assert rec1.ConditionSet.ConditionTable[0].Format == 2
+
+
+@pytest.mark.parametrize(
+ "limits, expected",
+ [
+ (["wght=400", "wdth=100"], {"wght": 400, "wdth": 100}),
+ (["wght=400:900"], {"wght": (400, 900)}),
+ (["slnt=11.4"], {"slnt": 11.4}),
+ (["ABCD=drop"], {"ABCD": None}),
+ ],
+)
+def test_parseLimits(limits, expected):
+ assert instancer.parseLimits(limits) == expected
+
+
+@pytest.mark.parametrize(
+ "limits", [["abcde=123", "=0", "wght=:", "wght=1:", "wght=abcd", "wght=x:y"]]
+)
+def test_parseLimits_invalid(limits):
+ with pytest.raises(ValueError, match="invalid location format"):
+ instancer.parseLimits(limits)
+
+
+def test_normalizeAxisLimits_tuple(varfont):
+ normalized = instancer.normalizeAxisLimits(varfont, {"wght": (100, 400)})
+ assert normalized == {"wght": (-1.0, 0)}
+
+
+def test_normalizeAxisLimits_no_avar(varfont):
+ del varfont["avar"]
+
+ normalized = instancer.normalizeAxisLimits(varfont, {"wght": (500, 600)})
+
+ assert normalized["wght"] == pytest.approx((0.2, 0.4), 1e-4)
+
+
+def test_normalizeAxisLimits_missing_from_fvar(varfont):
+ with pytest.raises(ValueError, match="not present in fvar"):
+ instancer.normalizeAxisLimits(varfont, {"ZZZZ": 1000})
+
+
+def test_sanityCheckVariableTables(varfont):
+ font = ttLib.TTFont()
+ with pytest.raises(ValueError, match="Missing required table fvar"):
+ instancer.sanityCheckVariableTables(font)
+
+ del varfont["glyf"]
+
+ with pytest.raises(ValueError, match="Can't have gvar without glyf"):
+ instancer.sanityCheckVariableTables(varfont)
+
+
+def test_main(varfont, tmpdir):
+ fontfile = str(tmpdir / "PartialInstancerTest-VF.ttf")
+ varfont.save(fontfile)
+ args = [fontfile, "wght=400"]
+
+ # exits without errors
+ assert instancer.main(args) is None
+
+
+def test_main_exit_nonexistent_file(capsys):
+ with pytest.raises(SystemExit):
+ instancer.main([""])
+ captured = capsys.readouterr()
+
+ assert "No such file ''" in captured.err
+
+
+def test_main_exit_invalid_location(varfont, tmpdir, capsys):
+ fontfile = str(tmpdir / "PartialInstancerTest-VF.ttf")
+ varfont.save(fontfile)
+
+ with pytest.raises(SystemExit):
+ instancer.main([fontfile, "wght:100"])
+ captured = capsys.readouterr()
+
+ assert "invalid location format" in captured.err
+
+
+def test_main_exit_multiple_limits(varfont, tmpdir, capsys):
+ fontfile = str(tmpdir / "PartialInstancerTest-VF.ttf")
+ varfont.save(fontfile)
+
+ with pytest.raises(SystemExit):
+ instancer.main([fontfile, "wght=400", "wght=90"])
+ captured = capsys.readouterr()
+
+ assert "Specified multiple limits for the same axis" in captured.err