예제 #1
0
def merge(merger, self, lst):
	assert self.Format == 1
	XCoords = [a.XCoordinate for a in lst]
	YCoords = [a.YCoordinate for a in lst]
	model = merger.model
	scalars = merger.scalars
	self.XCoordinate = otRound(model.interpolateFromMastersAndScalars(XCoords, scalars))
	self.YCoordinate = otRound(model.interpolateFromMastersAndScalars(YCoords, scalars))
예제 #2
0
	def compile(self, ttFont):
		metrics = []
		hasNegativeAdvances = False
		for glyphName in ttFont.getGlyphOrder():
			advanceWidth, sideBearing = self.metrics[glyphName]
			if advanceWidth < 0:
				log.error("Glyph %r has negative advance %s" % (
					glyphName, self.advanceName))
				hasNegativeAdvances = True
			metrics.append([advanceWidth, sideBearing])

		headerTable = ttFont.get(self.headerTag)
		if headerTable is not None:
			lastAdvance = metrics[-1][0]
			lastIndex = len(metrics)
			while metrics[lastIndex-2][0] == lastAdvance:
				lastIndex -= 1
				if lastIndex <= 1:
					# all advances are equal
					lastIndex = 1
					break
			additionalMetrics = metrics[lastIndex:]
			additionalMetrics = [otRound(sb) for _, sb in additionalMetrics]
			metrics = metrics[:lastIndex]
			numberOfMetrics = len(metrics)
			setattr(headerTable, self.numberOfMetricsName, numberOfMetrics)
		else:
			# no hhea/vhea, can't store numberOfMetrics; assume == numGlyphs
			numberOfMetrics = ttFont["maxp"].numGlyphs
			additionalMetrics = []

		allMetrics = []
		for advance, sb in metrics:
			allMetrics.extend([otRound(advance), otRound(sb)])
		metricsFmt = ">" + self.longMetricFormat * numberOfMetrics
		try:
			data = struct.pack(metricsFmt, *allMetrics)
		except struct.error as e:
			if "out of range" in str(e) and hasNegativeAdvances:
				raise ttLib.TTLibError(
					"'%s' table can't contain negative advance %ss"
					% (self.tableTag, self.advanceName))
			else:
				raise
		additionalMetrics = array.array("h", additionalMetrics)
		if sys.byteorder != "big": additionalMetrics.byteswap()
		data = data + additionalMetrics.tobytes()
		return data
    def _convert(self, dest, field, converter, value):
        enumClass = getattr(converter, "enumClass", None)

        if enumClass:
            if isinstance(value, enumClass):
                pass
            elif isinstance(value, str):
                try:
                    value = getattr(enumClass, value.upper())
                except AttributeError:
                    raise ValueError(f"{value} is not a valid {enumClass}")
            else:
                value = enumClass(value)

        elif isinstance(converter, IntValue):
            value = otRound(value)
        elif isinstance(converter, FloatValue):
            value = float(value)

        elif isinstance(converter, Struct):
            if converter.repeat:
                if _isNonStrSequence(value):
                    value = [
                        self.build(converter.tableClass, v) for v in value
                    ]
                else:
                    value = [self.build(converter.tableClass, value)]
                setattr(dest, converter.repeat, len(value))
            else:
                value = self.build(converter.tableClass, value)
        elif callable(converter):
            value = converter(value)

        setattr(dest, field, value)
예제 #4
0
def merge(merger, self, lst):

    # Hack till we become selfless.
    self.__dict__ = lst[0].__dict__.copy()

    if self.Format != 3:
        return

    instancer = merger.instancer
    for v in "XY":
        tableName = v + 'DeviceTable'
        if not hasattr(self, tableName):
            continue
        dev = getattr(self, tableName)
        if merger.deleteVariations:
            delattr(self, tableName)
        if dev is None:
            continue

        assert dev.DeltaFormat == 0x8000
        varidx = (dev.StartSize << 16) + dev.EndSize
        delta = otRound(instancer[varidx])

        attr = v + 'Coordinate'
        setattr(self, attr, getattr(self, attr) + delta)

    if merger.deleteVariations:
        self.Format = 1
예제 #5
0
def _bounds(color_glyph: ColorGlyph,
            quantize_factor: int = 1) -> Optional[Tuple[int, int, int, int]]:
    bounds = None
    for root in color_glyph.painted_layers:
        for context in root.breadth_first():
            if not isinstance(context.paint, PaintGlyph):
                continue
            paint_glyph: PaintGlyph = cast(PaintGlyph, context.paint)
            glyph_bbox = _transformed_glyph_bounds(color_glyph.ufo,
                                                   paint_glyph.glyph,
                                                   context.transform)
            if glyph_bbox is None:
                continue
            if bounds is None:
                bounds = glyph_bbox
            else:
                bounds = unionRect(bounds, glyph_bbox)
    if bounds is None:
        return
    # before quantizing to integer values > 1, we must first round floats to
    # int using the same rounding function (i.e. otRound) that fontTools
    # glyf table's compile method will use to round any float coordinates.
    bounds = tuple(otRound(v) for v in bounds)
    if quantize_factor > 1:
        return _quantize_bounding_rect(*bounds, factor=quantize_factor)
    return bounds
예제 #6
0
def interpolate_cff2_metrics(varfont, topDict, glyphOrder, loc):
    """Unlike TrueType glyphs, neither advance width nor bounding box
	info is stored in a CFF2 charstring. The width data exists only in
	the hmtx and HVAR tables. Since LSB data cannot be interpolated
	reliably from the master LSB values in the hmtx table, we traverse
	the charstring to determine the actual bound box. """

    charstrings = topDict.CharStrings
    boundsPen = BoundsPen(glyphOrder)
    hmtx = varfont['hmtx']
    hvar_table = None
    if 'HVAR' in varfont:
        hvar_table = varfont['HVAR'].table
        fvar = varfont['fvar']
        varStoreInstancer = VarStoreInstancer(hvar_table.VarStore, fvar.axes,
                                              loc)

    for gid, gname in enumerate(glyphOrder):
        entry = list(hmtx[gname])
        # get width delta.
        if hvar_table:
            if hvar_table.AdvWidthMap:
                width_idx = hvar_table.AdvWidthMap.mapping[gname]
            else:
                width_idx = gid
            width_delta = otRound(varStoreInstancer[width_idx])
        else:
            width_delta = 0

        # get LSB.
        boundsPen.init()
        charstring = charstrings[gname]
        charstring.draw(boundsPen)
        if boundsPen.bounds is None:
            # Happens with non-marking glyphs
            lsb_delta = 0
        else:
            lsb = otRound(boundsPen.bounds[0])
            lsb_delta = entry[1] - lsb

        if lsb_delta or width_delta:
            if width_delta:
                entry[0] += width_delta
            if lsb_delta:
                entry[1] = lsb
            hmtx[gname] = tuple(entry)
예제 #7
0
    def recalcAvgCharWidth(self, ttFont):
        """Recalculate xAvgCharWidth using metrics from ttFont's 'hmtx' table.

		Set it to 0 if the unlikely event 'hmtx' table is not found.
		"""
        avg_width = 0
        hmtx = ttFont.get("hmtx")
        if hmtx:
            widths = [m[0] for m in hmtx.metrics.values() if m[0] > 0]
            avg_width = otRound(sum(widths) / len(widths))
        self.xAvgCharWidth = avg_width
        return avg_width
예제 #8
0
    def outline(self, transform=None, evenOdd=False):
        """Converts the current contours to ``FT_Outline``.

        Args:
            transform: An optional 6-tuple containing an affine transformation,
                or a ``Transform`` object from the ``fontTools.misc.transform``
                module.
            evenOdd: Pass ``True`` for even-odd fill instead of non-zero.
        """
        transform = transform or Transform()
        if not hasattr(transform, "transformPoint"):
            transform = Transform(*transform)
        n_contours = len(self.contours)
        n_points = sum((len(contour.points) for contour in self.contours))
        points = []
        for contour in self.contours:
            for point in contour.points:
                point = transform.transformPoint(point)
                points.append(
                    FT_Vector(FT_Pos(otRound(point[0] * 64)),
                              FT_Pos(otRound(point[1] * 64))))
        tags = []
        for contour in self.contours:
            for tag in contour.tags:
                tags.append(tag)
        contours = []
        contours_sum = 0
        for contour in self.contours:
            contours_sum += len(contour.points)
            contours.append(contours_sum - 1)
        flags = FT_OUTLINE_EVEN_ODD_FILL if evenOdd else FT_OUTLINE_NONE
        return FT_Outline(
            (ctypes.c_short)(n_contours),
            (ctypes.c_short)(n_points),
            (FT_Vector * n_points)(*points),
            (ctypes.c_ubyte * n_points)(*tags),
            (ctypes.c_short * n_contours)(*contours),
            (ctypes.c_int)(flags),
        )
예제 #9
0
def interpolate_cff2_PrivateDict(topDict, interpolateFromDeltas):
    pd_blend_lists = ("BlueValues", "OtherBlues", "FamilyBlues",
                      "FamilyOtherBlues", "StemSnapH", "StemSnapV")
    pd_blend_values = ("BlueScale", "BlueShift", "BlueFuzz", "StdHW", "StdVW")
    for fontDict in topDict.FDArray:
        pd = fontDict.Private
        vsindex = pd.vsindex if (hasattr(pd, 'vsindex')) else 0
        for key, value in pd.rawDict.items():
            if (key in pd_blend_values) and isinstance(value, list):
                delta = interpolateFromDeltas(vsindex, value[1:])
                pd.rawDict[key] = otRound(value[0] + delta)
            elif (key in pd_blend_lists) and isinstance(value[0], list):
                """If any argument in a BlueValues list is a blend list,
				then they all are. The first value of each list is an
				absolute value. The delta tuples are calculated from
				relative master values, hence we need to append all the
				deltas to date to each successive absolute value."""
                delta = 0
                for i, val_list in enumerate(value):
                    delta += otRound(
                        interpolateFromDeltas(vsindex, val_list[1:]))
                    value[i] = val_list[0] + delta
예제 #10
0
def set_default_weight_width_slant(font, location):
    if "OS/2" in font:
        if "wght" in location:
            weight_class = otRound(max(1, min(location["wght"], 1000)))
            if font["OS/2"].usWeightClass != weight_class:
                log.info("Setting OS/2.usWeightClass = %s", weight_class)
                font["OS/2"].usWeightClass = weight_class

        if "wdth" in location:
            # map 'wdth' axis (50..200) to OS/2.usWidthClass (1..9), rounding to closest
            widthValue = min(max(location["wdth"], 50), 200)
            widthClass = otRound(
                models.piecewiseLinearMap(widthValue,
                                          WDTH_VALUE_TO_OS2_WIDTH_CLASS))
            if font["OS/2"].usWidthClass != widthClass:
                log.info("Setting OS/2.usWidthClass = %s", widthClass)
                font["OS/2"].usWidthClass = widthClass

    if "slnt" in location and "post" in font:
        italicAngle = max(-90, min(location["slnt"], 90))
        if font["post"].italicAngle != italicAngle:
            log.info("Setting post.italicAngle = %s", italicAngle)
            font["post"].italicAngle = italicAngle
예제 #11
0
def merge(merger, self, lst):
	model = merger.model
	scalars = merger.scalars
	# TODO Handle differing valueformats
	for name, tableName in [('XAdvance','XAdvDevice'),
				('YAdvance','YAdvDevice'),
				('XPlacement','XPlaDevice'),
				('YPlacement','YPlaDevice')]:

		assert not hasattr(self, tableName)

		if hasattr(self, name):
			values = [getattr(a, name, 0) for a in lst]
			value = otRound(model.interpolateFromMastersAndScalars(values, scalars))
			setattr(self, name, value)
예제 #12
0
 def getCharString(self, private=None, globalSubrs=None, optimize=True):
     commands = self._commands
     if optimize:
         maxstack = 48 if not self._CFF2 else 513
         commands = specializeCommands(commands,
                                       generalizeFirst=False,
                                       maxstack=maxstack)
     program = commandsToProgram(commands)
     if self._width is not None:
         assert not self._CFF2, "CFF2 does not allow encoding glyph width in CharString."
         program.insert(0, otRound(self._width))
     if not self._CFF2:
         program.append('endchar')
     charString = T2CharString(
         program=program, private=private, globalSubrs=globalSubrs)
     return charString
예제 #13
0
def merge(merger, self, lst):

    # Hack till we become selfless.
    self.__dict__ = lst[0].__dict__.copy()

    if self.Format != 3:
        return

    instancer = merger.instancer
    dev = 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

    if merger.deleteVariations:
        self.Format = 1
예제 #14
0
def interpolate_cff2_charstrings(topDict, interpolateFromDeltas, glyphOrder):
    charstrings = topDict.CharStrings
    for gname in glyphOrder:
        # Interpolate charstring
        # e.g replace blend op args with regular args,
        # and use and discard vsindex op.
        charstring = charstrings[gname]
        new_program = []
        vsindex = 0
        last_i = 0
        for i, token in enumerate(charstring.program):
            if token == 'vsindex':
                vsindex = charstring.program[i - 1]
                if last_i != 0:
                    new_program.extend(charstring.program[last_i:i - 1])
                last_i = i + 1
            elif token == 'blend':
                num_regions = charstring.getNumRegions(vsindex)
                numMasters = 1 + num_regions
                num_args = charstring.program[i - 1]
                # The program list starting at program[i] is now:
                # ..args for following operations
                # num_args values  from the default font
                # num_args tuples, each with numMasters-1 delta values
                # num_blend_args
                # 'blend'
                argi = i - (num_args * numMasters + 1)
                end_args = tuplei = argi + num_args
                while argi < end_args:
                    next_ti = tuplei + num_regions
                    deltas = charstring.program[tuplei:next_ti]
                    delta = interpolateFromDeltas(vsindex, deltas)
                    charstring.program[argi] += otRound(delta)
                    tuplei = next_ti
                    argi += 1
                new_program.extend(charstring.program[last_i:end_args])
                last_i = i + 1
        if last_i != 0:
            new_program.extend(charstring.program[last_i:])
            charstring.program = new_program
예제 #15
0
    def _buildComponents(self, componentFlags):
        if self.handleOverflowingTransforms:
            # we can't encode transform values > 2 or < -2 in F2Dot14,
            # so we must decompose the glyph if any transform exceeds these
            overflowing = any(s > 2 or s < -2
                              for (glyphName,
                                   transformation) in self.components
                              for s in transformation[:4])
        components = []
        for glyphName, transformation in self.components:
            if glyphName not in self.glyphSet:
                self.log.warning(
                    f"skipped non-existing component '{glyphName}'")
                continue
            if self.points or (self.handleOverflowingTransforms
                               and overflowing):
                # can't have both coordinates and components, so decompose
                self._decompose(glyphName, transformation)
                continue

            component = GlyphComponent()
            component.glyphName = glyphName
            component.x, component.y = (otRound(v) for v in transformation[4:])
            # quantize floats to F2Dot14 so we get same values as when decompiled
            # from a binary glyf table
            transformation = tuple(
                floatToFixedToFloat(v, 14) for v in transformation[:4])
            if transformation != (1, 0, 0, 1):
                if self.handleOverflowingTransforms and any(
                        MAX_F2DOT14 < s <= 2 for s in transformation):
                    # clamp values ~= +2.0 so we can keep the component
                    transformation = tuple(
                        MAX_F2DOT14 if MAX_F2DOT14 < s <= 2 else s
                        for s in transformation)
                component.transform = (transformation[:2], transformation[2:])
            component.flags = componentFlags
            components.append(component)
        return components
예제 #16
0
def merge(merger, self, lst):

    # Hack till we become selfless.
    self.__dict__ = lst[0].__dict__.copy()

    instancer = merger.instancer
    for name, tableName in [('XAdvance', 'XAdvDevice'),
                            ('YAdvance', 'YAdvDevice'),
                            ('XPlacement', 'XPlaDevice'),
                            ('YPlacement', 'YPlaDevice')]:

        if not hasattr(self, tableName):
            continue
        dev = getattr(self, tableName)
        if merger.deleteVariations:
            delattr(self, tableName)
        if dev is None:
            continue

        assert dev.DeltaFormat == 0x8000
        varidx = (dev.StartSize << 16) + dev.EndSize
        delta = otRound(instancer[varidx])

        setattr(self, name, getattr(self, name) + delta)
예제 #17
0
def _round_point(pt):
    return (otRound(pt[0]), otRound(pt[1]))
예제 #18
0
 def round(self):
     return Circle(_round_point(self.centre), otRound(self.radius))
예제 #19
0
def instantiateVariableFont(varfont, location, inplace=False, overlap=True):
    """ Generate a static instance from a variable TTFont and a dictionary
	defining the desired location along the variable font's axes.
	The location values must be specified as user-space coordinates, e.g.:

		{'wght': 400, 'wdth': 100}

	By default, a new TTFont object is returned. If ``inplace`` is True, the
	input varfont is modified and reduced to a static font.

	When the overlap parameter is defined as True,
	OVERLAP_SIMPLE and OVERLAP_COMPOUND bits are set to 1.  See
	https://docs.microsoft.com/en-us/typography/opentype/spec/glyf
	"""
    if not inplace:
        # make a copy to leave input varfont unmodified
        stream = BytesIO()
        varfont.save(stream)
        stream.seek(0)
        varfont = TTFont(stream)

    fvar = varfont['fvar']
    axes = {
        a.axisTag: (a.minValue, a.defaultValue, a.maxValue)
        for a in fvar.axes
    }
    loc = normalizeLocation(location, axes)
    if 'avar' in varfont:
        maps = varfont['avar'].segments
        loc = {k: piecewiseLinearMap(v, maps[k]) for k, v in loc.items()}
    # Quantize to F2Dot14, to avoid surprise interpolations.
    loc = {k: floatToFixedToFloat(v, 14) for k, v in loc.items()}
    # Location is normalized now
    log.info("Normalized location: %s", loc)

    if 'gvar' in varfont:
        log.info("Mutating glyf/gvar tables")
        gvar = varfont['gvar']
        glyf = varfont['glyf']
        hMetrics = varfont['hmtx'].metrics
        vMetrics = getattr(varfont.get('vmtx'), 'metrics', None)
        # get list of glyph names in gvar sorted by component depth
        glyphnames = sorted(
            gvar.variations.keys(),
            key=lambda name:
            (glyf[name].getCompositeMaxpValues(glyf).maxComponentDepth
             if glyf[name].isComposite() else 0, name))
        for glyphname in glyphnames:
            variations = gvar.variations[glyphname]
            coordinates, _ = glyf._getCoordinatesAndControls(
                glyphname, hMetrics, vMetrics)
            origCoords, endPts = None, None
            for var in variations:
                scalar = supportScalar(loc, var.axes)
                if not scalar: continue
                delta = var.coordinates
                if None in delta:
                    if origCoords is None:
                        origCoords, g = glyf._getCoordinatesAndControls(
                            glyphname, hMetrics, vMetrics)
                    delta = iup_delta(delta, origCoords, g.endPts)
                coordinates += GlyphCoordinates(delta) * scalar
            glyf._setCoordinates(glyphname, coordinates, hMetrics, vMetrics)
    else:
        glyf = None

    if 'cvar' in varfont:
        log.info("Mutating cvt/cvar tables")
        cvar = varfont['cvar']
        cvt = varfont['cvt ']
        deltas = {}
        for var in cvar.variations:
            scalar = supportScalar(loc, var.axes)
            if not scalar: continue
            for i, c in enumerate(var.coordinates):
                if c is not None:
                    deltas[i] = deltas.get(i, 0) + scalar * c
        for i, delta in deltas.items():
            cvt[i] += otRound(delta)

    if 'CFF2' in varfont:
        log.info("Mutating CFF2 table")
        glyphOrder = varfont.getGlyphOrder()
        CFF2 = varfont['CFF2']
        topDict = CFF2.cff.topDictIndex[0]
        vsInstancer = VarStoreInstancer(topDict.VarStore.otVarStore, fvar.axes,
                                        loc)
        interpolateFromDeltas = vsInstancer.interpolateFromDeltas
        interpolate_cff2_PrivateDict(topDict, interpolateFromDeltas)
        CFF2.desubroutinize()
        interpolate_cff2_charstrings(topDict, interpolateFromDeltas,
                                     glyphOrder)
        interpolate_cff2_metrics(varfont, topDict, glyphOrder, loc)
        del topDict.rawDict['VarStore']
        del topDict.VarStore

    if 'MVAR' in varfont:
        log.info("Mutating MVAR table")
        mvar = varfont['MVAR'].table
        varStoreInstancer = VarStoreInstancer(mvar.VarStore, fvar.axes, loc)
        records = mvar.ValueRecord
        for rec in records:
            mvarTag = rec.ValueTag
            if mvarTag not in MVAR_ENTRIES:
                continue
            tableTag, itemName = MVAR_ENTRIES[mvarTag]
            delta = otRound(varStoreInstancer[rec.VarIdx])
            if not delta:
                continue
            setattr(varfont[tableTag], itemName,
                    getattr(varfont[tableTag], itemName) + delta)

    log.info("Mutating FeatureVariations")
    for tableTag in 'GSUB', 'GPOS':
        if not tableTag in varfont:
            continue
        table = varfont[tableTag].table
        if not getattr(table, 'FeatureVariations', None):
            continue
        variations = table.FeatureVariations
        for record in variations.FeatureVariationRecord:
            applies = True
            for condition in record.ConditionSet.ConditionTable:
                if condition.Format == 1:
                    axisIdx = condition.AxisIndex
                    axisTag = fvar.axes[axisIdx].axisTag
                    Min = condition.FilterRangeMinValue
                    Max = condition.FilterRangeMaxValue
                    v = loc[axisTag]
                    if not (Min <= v <= Max):
                        applies = False
                else:
                    applies = False
                if not applies:
                    break

            if applies:
                assert record.FeatureTableSubstitution.Version == 0x00010000
                for rec in record.FeatureTableSubstitution.SubstitutionRecord:
                    table.FeatureList.FeatureRecord[
                        rec.FeatureIndex].Feature = rec.Feature
                break
        del table.FeatureVariations

    if 'GDEF' in varfont and varfont['GDEF'].table.Version >= 0x00010003:
        log.info("Mutating GDEF/GPOS/GSUB tables")
        gdef = varfont['GDEF'].table
        instancer = VarStoreInstancer(gdef.VarStore, fvar.axes, loc)

        merger = MutatorMerger(varfont, instancer)
        merger.mergeTables(varfont, [varfont], ['GDEF', 'GPOS'])

        # 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']

    addidef = False
    if glyf:
        for glyph in glyf.glyphs.values():
            if hasattr(glyph, "program"):
                instructions = glyph.program.getAssembly()
                # If GETVARIATION opcode is used in bytecode of any glyph add IDEF
                addidef = any(
                    op.startswith("GETVARIATION") for op in instructions)
                if addidef:
                    break
        if overlap:
            for glyph_name in glyf.keys():
                glyph = glyf[glyph_name]
                # Set OVERLAP_COMPOUND bit for compound glyphs
                if glyph.isComposite():
                    glyph.components[0].flags |= OVERLAP_COMPOUND
                # Set OVERLAP_SIMPLE bit for simple glyphs
                elif glyph.numberOfContours > 0:
                    glyph.flags[0] |= flagOverlapSimple
    if addidef:
        log.info("Adding IDEF to fpgm table for GETVARIATION opcode")
        asm = []
        if 'fpgm' in varfont:
            fpgm = varfont['fpgm']
            asm = fpgm.program.getAssembly()
        else:
            fpgm = newTable('fpgm')
            fpgm.program = ttProgram.Program()
            varfont['fpgm'] = fpgm
        asm.append("PUSHB[000] 145")
        asm.append("IDEF[ ]")
        args = [str(len(loc))]
        for a in fvar.axes:
            args.append(str(floatToFixed(loc[a.axisTag], 14)))
        asm.append("NPUSHW[ ] " + ' '.join(args))
        asm.append("ENDF[ ]")
        fpgm.program.fromAssembly(asm)

        # Change maxp attributes as IDEF is added
        if 'maxp' in varfont:
            maxp = varfont['maxp']
            setattr(maxp, "maxInstructionDefs",
                    1 + getattr(maxp, "maxInstructionDefs", 0))
            setattr(maxp, "maxStackElements",
                    max(len(loc), getattr(maxp, "maxStackElements", 0)))

    if 'name' in varfont:
        log.info("Pruning name table")
        exclude = {a.axisNameID for a in fvar.axes}
        for i in fvar.instances:
            exclude.add(i.subfamilyNameID)
            exclude.add(i.postscriptNameID)
        if 'ltag' in varfont:
            # Drop the whole 'ltag' table if all its language tags are referenced by
            # name records to be pruned.
            # TODO: prune unused ltag tags and re-enumerate langIDs accordingly
            excludedUnicodeLangIDs = [
                n.langID for n in varfont['name'].names if n.nameID in exclude
                and n.platformID == 0 and n.langID != 0xFFFF
            ]
            if set(excludedUnicodeLangIDs) == set(
                    range(len((varfont['ltag'].tags)))):
                del varfont['ltag']
        varfont['name'].names[:] = [
            n for n in varfont['name'].names if n.nameID not in exclude
        ]

    if "wght" in location and "OS/2" in varfont:
        varfont["OS/2"].usWeightClass = otRound(
            max(1, min(location["wght"], 1000)))
    if "wdth" in location:
        wdth = location["wdth"]
        for percent, widthClass in sorted(OS2_WIDTH_CLASS_VALUES.items()):
            if wdth < percent:
                varfont["OS/2"].usWidthClass = widthClass
                break
        else:
            varfont["OS/2"].usWidthClass = 9
    if "slnt" in location and "post" in varfont:
        varfont["post"].italicAngle = max(-90, min(location["slnt"], 90))

    log.info("Removing variable tables")
    for tag in ('avar', 'cvar', 'fvar', 'gvar', 'HVAR', 'MVAR', 'VVAR',
                'STAT'):
        if tag in varfont:
            del varfont[tag]

    return varfont