code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def writeLayerContents(self, layerOrder=None, validate=None): """ Write the layercontents.plist file. This method *must* be called after all glyph sets have been written. """ if validate is None: validate = self._validate if self._formatVersion < UFOFormatVer...
Write the layercontents.plist file. This method *must* be called after all glyph sets have been written.
writeLayerContents
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def getGlyphSet( self, layerName=None, defaultLayer=True, glyphNameToFileNameFunc=None, validateRead=None, validateWrite=None, expectContentsFile=False, ): """ Return the GlyphSet object associated with the appropriate glyph directory i...
Return the GlyphSet object associated with the appropriate glyph directory in the .ufo. If layerName is None, the default glyph set will be used. The defaultLayer flag indictes that the layer should be saved into the default glyphs directory. ``validateRead`` wi...
getGlyphSet
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def renameGlyphSet(self, layerName, newLayerName, defaultLayer=False): """ Rename a glyph set. Note: if a GlyphSet object has already been retrieved for layerName, it is up to the caller to inform that object that the directory it represents has changed. """ if s...
Rename a glyph set. Note: if a GlyphSet object has already been retrieved for layerName, it is up to the caller to inform that object that the directory it represents has changed.
renameGlyphSet
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def deleteGlyphSet(self, layerName): """ Remove the glyph set matching layerName. """ if self._formatVersion < UFOFormatVersion.FORMAT_3_0: # ignore deleting glyph sets for UFO1 UFO2 as there are no layers # just write the data from the default layer r...
Remove the glyph set matching layerName.
deleteGlyphSet
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def writeImage(self, fileName, data, validate=None): """ Write data to fileName in the images directory. The data must be a valid PNG. """ if validate is None: validate = self._validate if self._formatVersion < UFOFormatVersion.FORMAT_3_0: raise UF...
Write data to fileName in the images directory. The data must be a valid PNG.
writeImage
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def removeImage(self, fileName, validate=None): # XXX remove unused 'validate'? """ Remove the file named fileName from the images directory. """ if self._formatVersion < UFOFormatVersion.FORMAT_3_0: raise UFOLibError( f"Images are not allowed in UFO ...
Remove the file named fileName from the images directory.
removeImage
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def copyImageFromReader(self, reader, sourceFileName, destFileName, validate=None): """ Copy the sourceFileName in the provided UFOReader to destFileName in this writer. This uses the most memory efficient method possible for copying the data possible. """ if validate is ...
Copy the sourceFileName in the provided UFOReader to destFileName in this writer. This uses the most memory efficient method possible for copying the data possible.
copyImageFromReader
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def _sniffFileStructure(ufo_path): """Return UFOFileStructure.ZIP if the UFO at path 'ufo_path' (str) is a zip file, else return UFOFileStructure.PACKAGE if 'ufo_path' is a directory. Raise UFOLibError if it is a file with unknown structure, or if the path does not exist. """ if zipfile.is_z...
Return UFOFileStructure.ZIP if the UFO at path 'ufo_path' (str) is a zip file, else return UFOFileStructure.PACKAGE if 'ufo_path' is a directory. Raise UFOLibError if it is a file with unknown structure, or if the path does not exist.
_sniffFileStructure
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def makeUFOPath(path): """ Return a .ufo pathname. >>> makeUFOPath("directory/something.ext") == ( ... os.path.join('directory', 'something.ufo')) True >>> makeUFOPath("directory/something.another.thing.ext") == ( ... os.path.join('directory', 'something.another.thing.ufo')) True ...
Return a .ufo pathname. >>> makeUFOPath("directory/something.ext") == ( ... os.path.join('directory', 'something.ufo')) True >>> makeUFOPath("directory/something.another.thing.ext") == ( ... os.path.join('directory', 'something.another.thing.ufo')) True
makeUFOPath
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def validateFontInfoVersion2ValueForAttribute(attr, value): """ This performs very basic validation of the value for attribute following the UFO 2 fontinfo.plist specification. The results of this should not be interpretted as *correct* for the font that they are part of. This merely indicates that ...
This performs very basic validation of the value for attribute following the UFO 2 fontinfo.plist specification. The results of this should not be interpretted as *correct* for the font that they are part of. This merely indicates that the value is of the proper type and, where the specification de...
validateFontInfoVersion2ValueForAttribute
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def validateInfoVersion2Data(infoData): """ This performs very basic validation of the value for infoData following the UFO 2 fontinfo.plist specification. The results of this should not be interpretted as *correct* for the font that they are part of. This merely indicates that the values are of...
This performs very basic validation of the value for infoData following the UFO 2 fontinfo.plist specification. The results of this should not be interpretted as *correct* for the font that they are part of. This merely indicates that the values are of the proper type and, where the specification d...
validateInfoVersion2Data
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def validateFontInfoVersion3ValueForAttribute(attr, value): """ This performs very basic validation of the value for attribute following the UFO 3 fontinfo.plist specification. The results of this should not be interpretted as *correct* for the font that they are part of. This merely indicates that ...
This performs very basic validation of the value for attribute following the UFO 3 fontinfo.plist specification. The results of this should not be interpretted as *correct* for the font that they are part of. This merely indicates that the value is of the proper type and, where the specification de...
validateFontInfoVersion3ValueForAttribute
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def validateInfoVersion3Data(infoData): """ This performs very basic validation of the value for infoData following the UFO 3 fontinfo.plist specification. The results of this should not be interpretted as *correct* for the font that they are part of. This merely indicates that the values are of...
This performs very basic validation of the value for infoData following the UFO 3 fontinfo.plist specification. The results of this should not be interpretted as *correct* for the font that they are part of. This merely indicates that the values are of the proper type and, where the specification d...
validateInfoVersion3Data
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def convertFontInfoValueForAttributeFromVersion1ToVersion2(attr, value): """ Convert value from version 1 to version 2 format. Returns the new attribute name and the converted value. If the value is None, None will be returned for the new value. """ # convert floats to ints if possible if is...
Convert value from version 1 to version 2 format. Returns the new attribute name and the converted value. If the value is None, None will be returned for the new value.
convertFontInfoValueForAttributeFromVersion1ToVersion2
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def convertFontInfoValueForAttributeFromVersion2ToVersion1(attr, value): """ Convert value from version 2 to version 1 format. Returns the new attribute name and the converted value. If the value is None, None will be returned for the new value. """ if value is not None: if attr == "styl...
Convert value from version 2 to version 1 format. Returns the new attribute name and the converted value. If the value is None, None will be returned for the new value.
convertFontInfoValueForAttributeFromVersion2ToVersion1
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def convertFontInfoValueForAttributeFromVersion2ToVersion3(attr, value): """ Convert value from version 2 to version 3 format. Returns the new attribute name and the converted value. If the value is None, None will be returned for the new value. """ if attr in _ufo2To3FloatToInt: try: ...
Convert value from version 2 to version 3 format. Returns the new attribute name and the converted value. If the value is None, None will be returned for the new value.
convertFontInfoValueForAttributeFromVersion2ToVersion3
python
fonttools/fonttools
Lib/fontTools/ufoLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ufoLib/__init__.py
MIT
def script(char): """Return the four-letter script code assigned to the Unicode character 'char' as string. >>> script("a") 'Latn' >>> script(",") 'Zyyy' >>> script(chr(0x10FFFF)) 'Zzzz' """ code = byteord(char) # 'bisect_right(a, x, lo=0, hi=len(a))' returns an insertion po...
Return the four-letter script code assigned to the Unicode character 'char' as string. >>> script("a") 'Latn' >>> script(",") 'Zyyy' >>> script(chr(0x10FFFF)) 'Zzzz'
script
python
fonttools/fonttools
Lib/fontTools/unicodedata/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/unicodedata/__init__.py
MIT
def script_extension(char): """Return the script extension property assigned to the Unicode character 'char' as a set of string. >>> script_extension("a") == {'Latn'} True >>> script_extension(chr(0x060C)) == {'Nkoo', 'Arab', 'Rohg', 'Thaa', 'Syrc', 'Gara', 'Yezi'} True >>> script_extension...
Return the script extension property assigned to the Unicode character 'char' as a set of string. >>> script_extension("a") == {'Latn'} True >>> script_extension(chr(0x060C)) == {'Nkoo', 'Arab', 'Rohg', 'Thaa', 'Syrc', 'Gara', 'Yezi'} True >>> script_extension(chr(0x10FFFF)) == {'Zzzz'} Tru...
script_extension
python
fonttools/fonttools
Lib/fontTools/unicodedata/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/unicodedata/__init__.py
MIT
def script_name(code, default=KeyError): """Return the long, human-readable script name given a four-letter Unicode script code. If no matching name is found, a KeyError is raised by default. You can use the 'default' argument to return a fallback value (e.g. 'Unknown' or None) instead of throwing...
Return the long, human-readable script name given a four-letter Unicode script code. If no matching name is found, a KeyError is raised by default. You can use the 'default' argument to return a fallback value (e.g. 'Unknown' or None) instead of throwing an error.
script_name
python
fonttools/fonttools
Lib/fontTools/unicodedata/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/unicodedata/__init__.py
MIT
def script_code(script_name, default=KeyError): """Returns the four-letter Unicode script code from its long name If no matching script code is found, a KeyError is raised by default. You can use the 'default' argument to return a fallback string (e.g. 'Zzzz' or None) instead of throwing an error. ...
Returns the four-letter Unicode script code from its long name If no matching script code is found, a KeyError is raised by default. You can use the 'default' argument to return a fallback string (e.g. 'Zzzz' or None) instead of throwing an error.
script_code
python
fonttools/fonttools
Lib/fontTools/unicodedata/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/unicodedata/__init__.py
MIT
def script_horizontal_direction( script_code: str, default: T | type[KeyError] = KeyError ) -> HorizDirection | T: """Return "RTL" for scripts that contain right-to-left characters according to the Bidi_Class property. Otherwise return "LTR". """ if script_code not in Scripts.NAMES: if isins...
Return "RTL" for scripts that contain right-to-left characters according to the Bidi_Class property. Otherwise return "LTR".
script_horizontal_direction
python
fonttools/fonttools
Lib/fontTools/unicodedata/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/unicodedata/__init__.py
MIT
def block(char): """Return the block property assigned to the Unicode character 'char' as a string. >>> block("a") 'Basic Latin' >>> block(chr(0x060C)) 'Arabic' >>> block(chr(0xEFFFF)) 'No_Block' """ code = byteord(char) i = bisect_right(Blocks.RANGES, code) return Block...
Return the block property assigned to the Unicode character 'char' as a string. >>> block("a") 'Basic Latin' >>> block(chr(0x060C)) 'Arabic' >>> block(chr(0xEFFFF)) 'No_Block'
block
python
fonttools/fonttools
Lib/fontTools/unicodedata/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/unicodedata/__init__.py
MIT
def ot_tags_from_script(script_code): """Return a list of OpenType script tags associated with a given Unicode script code. Return ['DFLT'] script tag for invalid/unknown script codes. """ if script_code in OTTags.SCRIPT_EXCEPTIONS: return [OTTags.SCRIPT_EXCEPTIONS[script_code]] if scri...
Return a list of OpenType script tags associated with a given Unicode script code. Return ['DFLT'] script tag for invalid/unknown script codes.
ot_tags_from_script
python
fonttools/fonttools
Lib/fontTools/unicodedata/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/unicodedata/__init__.py
MIT
def ot_tag_to_script(tag): """Return the Unicode script code for the given OpenType script tag, or None for "DFLT" tag or if there is no Unicode script associated with it. Raises ValueError if the tag is invalid. """ tag = tostr(tag).strip() if not tag or " " in tag or len(tag) > 4: rais...
Return the Unicode script code for the given OpenType script tag, or None for "DFLT" tag or if there is no Unicode script associated with it. Raises ValueError if the tag is invalid.
ot_tag_to_script
python
fonttools/fonttools
Lib/fontTools/unicodedata/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/unicodedata/__init__.py
MIT
def main(args=None): """Add `avar` table from designspace file to variable font.""" if args is None: import sys args = sys.argv[1:] from fontTools import configLogger from fontTools.ttLib import TTFont from fontTools.designspaceLib import DesignSpaceDocument import argparse ...
Add `avar` table from designspace file to variable font.
main
python
fonttools/fonttools
Lib/fontTools/varLib/avar.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avar.py
MIT
def normalizeLog(value, rangeMin, rangeMax): """Logarithmically normalize value in [rangeMin, rangeMax] to [0, 1], with extrapolation.""" logMin = math.log(rangeMin) logMax = math.log(rangeMax) return (math.log(value) - logMin) / (logMax - logMin)
Logarithmically normalize value in [rangeMin, rangeMax] to [0, 1], with extrapolation.
normalizeLog
python
fonttools/fonttools
Lib/fontTools/varLib/avarPlanner.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avarPlanner.py
MIT
def interpolateLog(t, a, b): """Logarithmic interpolation between a and b, with t typically in [0, 1].""" logA = math.log(a) logB = math.log(b) return math.exp(logA + t * (logB - logA))
Logarithmic interpolation between a and b, with t typically in [0, 1].
interpolateLog
python
fonttools/fonttools
Lib/fontTools/varLib/avarPlanner.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avarPlanner.py
MIT
def normalizeDegrees(value, rangeMin, rangeMax): """Angularly normalize value in [rangeMin, rangeMax] to [0, 1], with extrapolation.""" tanMin = math.tan(math.radians(rangeMin)) tanMax = math.tan(math.radians(rangeMax)) return (math.tan(math.radians(value)) - tanMin) / (tanMax - tanMin)
Angularly normalize value in [rangeMin, rangeMax] to [0, 1], with extrapolation.
normalizeDegrees
python
fonttools/fonttools
Lib/fontTools/varLib/avarPlanner.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avarPlanner.py
MIT
def measureWeight(glyphset, glyphs=None): """Measure the perceptual average weight of the given glyphs.""" if isinstance(glyphs, dict): frequencies = glyphs else: frequencies = {g: 1 for g in glyphs} wght_sum = wdth_sum = 0 for glyph_name in glyphs: if frequencies is not Non...
Measure the perceptual average weight of the given glyphs.
measureWeight
python
fonttools/fonttools
Lib/fontTools/varLib/avarPlanner.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avarPlanner.py
MIT
def measureWidth(glyphset, glyphs=None): """Measure the average width of the given glyphs.""" if isinstance(glyphs, dict): frequencies = glyphs else: frequencies = {g: 1 for g in glyphs} wdth_sum = 0 freq_sum = 0 for glyph_name in glyphs: if frequencies is not None: ...
Measure the average width of the given glyphs.
measureWidth
python
fonttools/fonttools
Lib/fontTools/varLib/avarPlanner.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avarPlanner.py
MIT
def measureSlant(glyphset, glyphs=None): """Measure the perceptual average slant angle of the given glyphs.""" if isinstance(glyphs, dict): frequencies = glyphs else: frequencies = {g: 1 for g in glyphs} slnt_sum = 0 freq_sum = 0 for glyph_name in glyphs: if frequencies ...
Measure the perceptual average slant angle of the given glyphs.
measureSlant
python
fonttools/fonttools
Lib/fontTools/varLib/avarPlanner.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avarPlanner.py
MIT
def planWeightAxis( glyphSetFunc, axisLimits, weights=None, samples=None, glyphs=None, designLimits=None, pins=None, sanitize=False, ): """Plan a weight (`wght`) axis. weights: A list of weight values to plan for. If None, the default values are used. This function simp...
Plan a weight (`wght`) axis. weights: A list of weight values to plan for. If None, the default values are used. This function simply calls planAxis with values=weights, and the appropriate arguments. See documenation for planAxis for more information.
planWeightAxis
python
fonttools/fonttools
Lib/fontTools/varLib/avarPlanner.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avarPlanner.py
MIT
def planWidthAxis( glyphSetFunc, axisLimits, widths=None, samples=None, glyphs=None, designLimits=None, pins=None, sanitize=False, ): """Plan a width (`wdth`) axis. widths: A list of width values (percentages) to plan for. If None, the default values are used. This func...
Plan a width (`wdth`) axis. widths: A list of width values (percentages) to plan for. If None, the default values are used. This function simply calls planAxis with values=widths, and the appropriate arguments. See documenation for planAxis for more information.
planWidthAxis
python
fonttools/fonttools
Lib/fontTools/varLib/avarPlanner.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avarPlanner.py
MIT
def planSlantAxis( glyphSetFunc, axisLimits, slants=None, samples=None, glyphs=None, designLimits=None, pins=None, sanitize=False, ): """Plan a slant (`slnt`) axis. slants: A list slant angles to plan for. If None, the default values are used. This function simply calls...
Plan a slant (`slnt`) axis. slants: A list slant angles to plan for. If None, the default values are used. This function simply calls planAxis with values=slants, and the appropriate arguments. See documenation for planAxis for more information.
planSlantAxis
python
fonttools/fonttools
Lib/fontTools/varLib/avarPlanner.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avarPlanner.py
MIT
def planOpticalSizeAxis( glyphSetFunc, axisLimits, sizes=None, samples=None, glyphs=None, designLimits=None, pins=None, sanitize=False, ): """Plan a optical-size (`opsz`) axis. sizes: A list of optical size values to plan for. If None, the default values are used. This ...
Plan a optical-size (`opsz`) axis. sizes: A list of optical size values to plan for. If None, the default values are used. This function simply calls planAxis with values=sizes, and the appropriate arguments. See documenation for planAxis for more information.
planOpticalSizeAxis
python
fonttools/fonttools
Lib/fontTools/varLib/avarPlanner.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avarPlanner.py
MIT
def makeDesignspaceSnippet(axisTag, axisName, axisLimit, mapping): """Make a designspace snippet for a single axis.""" designspaceSnippet = ( ' <axis tag="%s" name="%s" minimum="%g" default="%g" maximum="%g"' % ((axisTag, axisName) + axisLimit) ) if mapping: designspaceSnippe...
Make a designspace snippet for a single axis.
makeDesignspaceSnippet
python
fonttools/fonttools
Lib/fontTools/varLib/avarPlanner.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avarPlanner.py
MIT
def addEmptyAvar(font): """Add an empty `avar` table to the font.""" font["avar"] = avar = newTable("avar") for axis in fvar.axes: avar.segments[axis.axisTag] = {}
Add an empty `avar` table to the font.
addEmptyAvar
python
fonttools/fonttools
Lib/fontTools/varLib/avarPlanner.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avarPlanner.py
MIT
def main(args=None): """Plan the standard axis mappings for a variable font""" if args is None: import sys args = sys.argv[1:] from fontTools import configLogger from fontTools.ttLib import TTFont import argparse parser = argparse.ArgumentParser( "fonttools varLib.ava...
Plan the standard axis mappings for a variable font
main
python
fonttools/fonttools
Lib/fontTools/varLib/avarPlanner.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/avarPlanner.py
MIT
def merge_PrivateDicts(top_dicts, vsindex_dict, var_model, fd_map): """ I step through the FontDicts in the FDArray of the varfont TopDict. For each varfont FontDict: * step through each key in FontDict.Private. * For each key, step through each relevant source font Private dict, and build a ...
I step through the FontDicts in the FDArray of the varfont TopDict. For each varfont FontDict: * step through each key in FontDict.Private. * For each key, step through each relevant source font Private dict, and build a list of values to blend. The 'relevant' source fonts are selected by f...
merge_PrivateDicts
python
fonttools/fonttools
Lib/fontTools/varLib/cff.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/cff.py
MIT
def getfd_map(varFont, fonts_list): """Since a subset source font may have fewer FontDicts in their FDArray than the default font, we have to match up the FontDicts in the different fonts . We do this with the FDSelect array, and by assuming that the same glyph will reference matching FontDicts in ...
Since a subset source font may have fewer FontDicts in their FDArray than the default font, we have to match up the FontDicts in the different fonts . We do this with the FDSelect array, and by assuming that the same glyph will reference matching FontDicts in each source font. We return a mapping from ...
getfd_map
python
fonttools/fonttools
Lib/fontTools/varLib/cff.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/cff.py
MIT
def reorder_blend_args(self, commands, get_delta_func): """ We first re-order the master coordinate values. For a moveto to lineto, the args are now arranged as:: [ [master_0 x,y], [master_1 x,y], [master_2 x,y] ] We re-arrange this to:: [ [master_0 x, ...
We first re-order the master coordinate values. For a moveto to lineto, the args are now arranged as:: [ [master_0 x,y], [master_1 x,y], [master_2 x,y] ] We re-arrange this to:: [ [master_0 x, master_1 x, master_2 x], [master_0 y, maste...
reorder_blend_args
python
fonttools/fonttools
Lib/fontTools/varLib/cff.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/cff.py
MIT
def overlayBox(top, bot): """Overlays ``top`` box on top of ``bot`` box. Returns two items: * Box for intersection of ``top`` and ``bot``, or None if they don't intersect. * Box for remainder of ``bot``. Remainder box might not be exact (since the remainder might not be a simple box), but is in...
Overlays ``top`` box on top of ``bot`` box. Returns two items: * Box for intersection of ``top`` and ``bot``, or None if they don't intersect. * Box for remainder of ``bot``. Remainder box might not be exact (since the remainder might not be a simple box), but is inclusive of the exact remain...
overlayBox
python
fonttools/fonttools
Lib/fontTools/varLib/featureVars.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/featureVars.py
MIT
def addFeatureVariationsRaw(font, table, conditionalSubstitutions, featureTag="rvrn"): """Low level implementation of addFeatureVariations that directly models the possibilities of the FeatureVariations table.""" featureTags = [featureTag] if isinstance(featureTag, str) else sorted(featureTag) processL...
Low level implementation of addFeatureVariations that directly models the possibilities of the FeatureVariations table.
addFeatureVariationsRaw
python
fonttools/fonttools
Lib/fontTools/varLib/featureVars.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/featureVars.py
MIT
def makeSubstitutionsHashable(conditionalSubstitutions): """Turn all the substitution dictionaries in sorted tuples of tuples so they are hashable, to detect duplicates so we don't write out redundant data.""" allSubstitutions = set() condSubst = [] for conditionSet, substitutionMaps in conditio...
Turn all the substitution dictionaries in sorted tuples of tuples so they are hashable, to detect duplicates so we don't write out redundant data.
makeSubstitutionsHashable
python
fonttools/fonttools
Lib/fontTools/varLib/featureVars.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/featureVars.py
MIT
def buildSubstitutionLookups(gsub, allSubstitutions, processLast=False): """Build the lookups for the glyph substitutions, return a dict mapping the substitution to lookup indices.""" # Insert lookups at the beginning of the lookup vector # https://github.com/googlefonts/fontmake/issues/950 firstI...
Build the lookups for the glyph substitutions, return a dict mapping the substitution to lookup indices.
buildSubstitutionLookups
python
fonttools/fonttools
Lib/fontTools/varLib/featureVars.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/featureVars.py
MIT
def findFeatureVariationRecord(featureVariations, conditionTable): """Find a FeatureVariationRecord that has the same conditionTable.""" if featureVariations.Version != 0x00010000: raise VarLibError( "Unsupported FeatureVariations table version: " f"0x{featureVariations.Version:0...
Find a FeatureVariationRecord that has the same conditionTable.
findFeatureVariationRecord
python
fonttools/fonttools
Lib/fontTools/varLib/featureVars.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/featureVars.py
MIT
def sortFeatureList(table): """Sort the feature list by feature tag, and remap the feature indices elsewhere. This is needed after the feature list has been modified. """ # decorate, sort, undecorate, because we need to make an index remapping table tagIndexFea = [ (fea.FeatureTag, index, fe...
Sort the feature list by feature tag, and remap the feature indices elsewhere. This is needed after the feature list has been modified.
sortFeatureList
python
fonttools/fonttools
Lib/fontTools/varLib/featureVars.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/featureVars.py
MIT
def remapFeatures(table, featureRemap): """Go through the scripts list, and remap feature indices.""" for scriptIndex, script in enumerate(table.ScriptList.ScriptRecord): defaultLangSys = script.Script.DefaultLangSys if defaultLangSys is not None: _remapLangSys(defaultLangSys, featur...
Go through the scripts list, and remap feature indices.
remapFeatures
python
fonttools/fonttools
Lib/fontTools/varLib/featureVars.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/featureVars.py
MIT
def main(args=None): """Add `HVAR` table to variable font.""" if args is None: import sys args = sys.argv[1:] from fontTools import configLogger from fontTools.designspaceLib import DesignSpaceDocument import argparse parser = argparse.ArgumentParser( "fonttools varLi...
Add `HVAR` table to variable font.
main
python
fonttools/fonttools
Lib/fontTools/varLib/hvar.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/hvar.py
MIT
def main(args=None): """Test for interpolatability issues between fonts""" import argparse import sys parser = argparse.ArgumentParser( "fonttools varLib.interpolatable", description=main.__doc__, ) parser.add_argument( "--glyphs", action="store", help="S...
Test for interpolatability issues between fonts
main
python
fonttools/fonttools
Lib/fontTools/varLib/interpolatable.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/interpolatable.py
MIT
def sort_problems(problems): """Sort problems by severity, then by glyph name, then by problem message.""" return dict( sorted( problems.items(), key=lambda _: -min( ( (InterpolatableProblem.severity[p["type"]] + p.get("tolerance", 0)) ...
Sort problems by severity, then by glyph name, then by problem message.
sort_problems
python
fonttools/fonttools
Lib/fontTools/varLib/interpolatableHelpers.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/interpolatableHelpers.py
MIT
def interpolate_layout(designspace, loc, master_finder=lambda s: s, mapped=False): """ Interpolate GPOS from a designspace file and location. If master_finder is set, it should be a callable that takes master filename as found in designspace file and map it to master font binary as to be opened (eg...
Interpolate GPOS from a designspace file and location. If master_finder is set, it should be a callable that takes master filename as found in designspace file and map it to master font binary as to be opened (eg. .ttf or .otf). If mapped is False (default), then location is mapped using the ...
interpolate_layout
python
fonttools/fonttools
Lib/fontTools/varLib/interpolate_layout.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/interpolate_layout.py
MIT
def main(args=None): """Interpolate GDEF/GPOS/GSUB tables for a point on a designspace""" from fontTools import configLogger import argparse import sys parser = argparse.ArgumentParser( "fonttools varLib.interpolate_layout", description=main.__doc__, ) parser.add_argument( ...
Interpolate GDEF/GPOS/GSUB tables for a point on a designspace
main
python
fonttools/fonttools
Lib/fontTools/varLib/interpolate_layout.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/interpolate_layout.py
MIT
def iup_segment( coords: _PointSegment, rc1: _Point, rd1: _Delta, rc2: _Point, rd2: _Delta ): # -> _DeltaSegment: """Given two reference coordinates `rc1` & `rc2` and their respective delta vectors `rd1` & `rd2`, returns interpolated deltas for the set of coordinates `coords`.""" # rc1 = reference...
Given two reference coordinates `rc1` & `rc2` and their respective delta vectors `rd1` & `rd2`, returns interpolated deltas for the set of coordinates `coords`.
iup_segment
python
fonttools/fonttools
Lib/fontTools/varLib/iup.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/iup.py
MIT
def iup_contour(deltas: _DeltaOrNoneSegment, coords: _PointSegment) -> _DeltaSegment: """For the contour given in `coords`, interpolate any missing delta values in delta vector `deltas`. Returns fully filled-out delta vector.""" assert len(deltas) == len(coords) if None not in deltas: retu...
For the contour given in `coords`, interpolate any missing delta values in delta vector `deltas`. Returns fully filled-out delta vector.
iup_contour
python
fonttools/fonttools
Lib/fontTools/varLib/iup.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/iup.py
MIT
def iup_delta( deltas: _DeltaOrNoneSegment, coords: _PointSegment, ends: _Endpoints ) -> _DeltaSegment: """For the outline given in `coords`, with contour endpoints given in sorted increasing order in `ends`, interpolate any missing delta values in delta vector `deltas`. Returns fully filled-out de...
For the outline given in `coords`, with contour endpoints given in sorted increasing order in `ends`, interpolate any missing delta values in delta vector `deltas`. Returns fully filled-out delta vector.
iup_delta
python
fonttools/fonttools
Lib/fontTools/varLib/iup.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/iup.py
MIT
def can_iup_in_between( deltas: _DeltaSegment, coords: _PointSegment, i: Integral, j: Integral, tolerance: Real, ): # -> bool: """Return true if the deltas for points at `i` and `j` (`i < j`) can be successfully used to interpolate deltas for points in between them within provided error...
Return true if the deltas for points at `i` and `j` (`i < j`) can be successfully used to interpolate deltas for points in between them within provided error tolerance.
can_iup_in_between
python
fonttools/fonttools
Lib/fontTools/varLib/iup.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/iup.py
MIT
def _iup_contour_bound_forced_set( deltas: _DeltaSegment, coords: _PointSegment, tolerance: Real = 0 ) -> set: """The forced set is a conservative set of points on the contour that must be encoded explicitly (ie. cannot be interpolated). Calculating this set allows for significantly speeding up the dyn...
The forced set is a conservative set of points on the contour that must be encoded explicitly (ie. cannot be interpolated). Calculating this set allows for significantly speeding up the dynamic-programming, as well as resolve circularity in DP. The set is precise; that is, if an index is in the returned s...
_iup_contour_bound_forced_set
python
fonttools/fonttools
Lib/fontTools/varLib/iup.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/iup.py
MIT
def _iup_contour_optimize_dp( deltas: _DeltaSegment, coords: _PointSegment, forced=set(), tolerance: Real = 0, lookback: Integral = None, ): """Straightforward Dynamic-Programming. For each index i, find least-costly encoding of points 0 to i where i is explicitly encoded. We find this by ...
Straightforward Dynamic-Programming. For each index i, find least-costly encoding of points 0 to i where i is explicitly encoded. We find this by considering all previous explicit points j and check whether interpolation can fill points between j and i. Note that solution always encodes last point explic...
_iup_contour_optimize_dp
python
fonttools/fonttools
Lib/fontTools/varLib/iup.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/iup.py
MIT
def _rot_list(l: list, k: int): """Rotate list by k items forward. Ie. item at position 0 will be at position k in returned list. Negative k is allowed.""" n = len(l) k %= n if not k: return l return l[n - k :] + l[: n - k]
Rotate list by k items forward. Ie. item at position 0 will be at position k in returned list. Negative k is allowed.
_rot_list
python
fonttools/fonttools
Lib/fontTools/varLib/iup.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/iup.py
MIT
def iup_contour_optimize( deltas: _DeltaSegment, coords: _PointSegment, tolerance: Real = 0.0 ) -> _DeltaOrNoneSegment: """For contour with coordinates `coords`, optimize a set of delta values `deltas` within error `tolerance`. Returns delta vector that has most number of None items instead of the ...
For contour with coordinates `coords`, optimize a set of delta values `deltas` within error `tolerance`. Returns delta vector that has most number of None items instead of the input delta.
iup_contour_optimize
python
fonttools/fonttools
Lib/fontTools/varLib/iup.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/iup.py
MIT
def iup_delta_optimize( deltas: _DeltaSegment, coords: _PointSegment, ends: _Endpoints, tolerance: Real = 0.0, ) -> _DeltaOrNoneSegment: """For the outline given in `coords`, with contour endpoints given in sorted increasing order in `ends`, optimize a set of delta values `deltas` within err...
For the outline given in `coords`, with contour endpoints given in sorted increasing order in `ends`, optimize a set of delta values `deltas` within error `tolerance`. Returns delta vector that has most number of None items instead of the input delta.
iup_delta_optimize
python
fonttools/fonttools
Lib/fontTools/varLib/iup.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/iup.py
MIT
def _merge_GlyphOrders(font, lst, values_lst=None, default=None): """Takes font and list of glyph lists (must be sorted by glyph id), and returns two things: - Combined glyph list, - If values_lst is None, return input glyph lists, but padded with None when a glyph was missing in a list. Otherwis...
Takes font and list of glyph lists (must be sorted by glyph id), and returns two things: - Combined glyph list, - If values_lst is None, return input glyph lists, but padded with None when a glyph was missing in a list. Otherwise, return values_lst list-of-list, padded with None to match combin...
_merge_GlyphOrders
python
fonttools/fonttools
Lib/fontTools/varLib/merger.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/merger.py
MIT
def _Lookup_PairPos_subtables_canonicalize(lst, font): """Merge multiple Format1 subtables at the beginning of lst, and merge multiple consecutive Format2 subtables that have the same Class2 (ie. were split because of offset overflows). Returns new list.""" lst = list(lst) l = len(lst) i = 0 ...
Merge multiple Format1 subtables at the beginning of lst, and merge multiple consecutive Format2 subtables that have the same Class2 (ie. were split because of offset overflows). Returns new list.
_Lookup_PairPos_subtables_canonicalize
python
fonttools/fonttools
Lib/fontTools/varLib/merger.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/merger.py
MIT
def expandPaintColrLayers(colr): """Rebuild LayerList without PaintColrLayers reuse. Each base paint graph is fully DFS-traversed (with exception of PaintColrGlyph which are irrelevant for this); any layers referenced via PaintColrLayers are collected into a new LayerList and duplicated...
Rebuild LayerList without PaintColrLayers reuse. Each base paint graph is fully DFS-traversed (with exception of PaintColrGlyph which are irrelevant for this); any layers referenced via PaintColrLayers are collected into a new LayerList and duplicated when reuse is detected, to ensure t...
expandPaintColrLayers
python
fonttools/fonttools
Lib/fontTools/varLib/merger.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/merger.py
MIT
def normalizeValue(v, triple, extrapolate=False): """Normalizes value based on a min/default/max triple. >>> normalizeValue(400, (100, 400, 900)) 0.0 >>> normalizeValue(100, (100, 400, 900)) -1.0 >>> normalizeValue(650, (100, 400, 900)) 0.5 """ lower, default, upper = triple if ...
Normalizes value based on a min/default/max triple. >>> normalizeValue(400, (100, 400, 900)) 0.0 >>> normalizeValue(100, (100, 400, 900)) -1.0 >>> normalizeValue(650, (100, 400, 900)) 0.5
normalizeValue
python
fonttools/fonttools
Lib/fontTools/varLib/models.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/models.py
MIT
def normalizeLocation(location, axes, extrapolate=False, *, validate=False): """Normalizes location based on axis min/default/max values from axes. >>> axes = {"wght": (100, 400, 900)} >>> normalizeLocation({"wght": 400}, axes) {'wght': 0.0} >>> normalizeLocation({"wght": 100}, axes) {'wght': -...
Normalizes location based on axis min/default/max values from axes. >>> axes = {"wght": (100, 400, 900)} >>> normalizeLocation({"wght": 400}, axes) {'wght': 0.0} >>> normalizeLocation({"wght": 100}, axes) {'wght': -1.0} >>> normalizeLocation({"wght": 900}, axes) {'wght': 1.0} >>> normal...
normalizeLocation
python
fonttools/fonttools
Lib/fontTools/varLib/models.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/models.py
MIT
def supportScalar(location, support, ot=True, extrapolate=False, axisRanges=None): """Returns the scalar multiplier at location, for a master with support. If ot is True, then a peak value of zero for support of an axis means "axis does not participate". That is how OpenType Variation Font technology ...
Returns the scalar multiplier at location, for a master with support. If ot is True, then a peak value of zero for support of an axis means "axis does not participate". That is how OpenType Variation Font technology works. If extrapolate is True, axisRanges must be a dict that maps axis names to ...
supportScalar
python
fonttools/fonttools
Lib/fontTools/varLib/models.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/models.py
MIT
def getSubModel(self, items): """Return a sub-model and the items that are not None. The sub-model is necessary for working with the subset of items when some are None. The sub-model is cached.""" if None not in items: return self, items key = tuple(v is not...
Return a sub-model and the items that are not None. The sub-model is necessary for working with the subset of items when some are None. The sub-model is cached.
getSubModel
python
fonttools/fonttools
Lib/fontTools/varLib/models.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/models.py
MIT
def getScalars(self, loc): """Return scalars for each delta, for the given location. If interpolating many master-values at the same location, this function allows speed up by fetching the scalars once and using them with interpolateFromMastersAndScalars().""" return [ ...
Return scalars for each delta, for the given location. If interpolating many master-values at the same location, this function allows speed up by fetching the scalars once and using them with interpolateFromMastersAndScalars().
getScalars
python
fonttools/fonttools
Lib/fontTools/varLib/models.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/models.py
MIT
def getMasterScalars(self, targetLocation): """Return multipliers for each master, for the given location. If interpolating many master-values at the same location, this function allows speed up by fetching the scalars once and using them with interpolateFromValuesAndScalars(). ...
Return multipliers for each master, for the given location. If interpolating many master-values at the same location, this function allows speed up by fetching the scalars once and using them with interpolateFromValuesAndScalars(). Note that the scalars used in interpolateFromMastersAnd...
getMasterScalars
python
fonttools/fonttools
Lib/fontTools/varLib/models.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/models.py
MIT
def interpolateFromValuesAndScalars(values, scalars): """Interpolate from values and scalars coefficients. If the values are master-values, then the scalars should be fetched from getMasterScalars(). If the values are deltas, then the scalars should be fetched from getScalars()...
Interpolate from values and scalars coefficients. If the values are master-values, then the scalars should be fetched from getMasterScalars(). If the values are deltas, then the scalars should be fetched from getScalars(); in which case this is the same as interpolateFromDeltas...
interpolateFromValuesAndScalars
python
fonttools/fonttools
Lib/fontTools/varLib/models.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/models.py
MIT
def interpolateFromDeltas(self, loc, deltas): """Interpolate from deltas, at location loc.""" scalars = self.getScalars(loc) return self.interpolateFromDeltasAndScalars(deltas, scalars)
Interpolate from deltas, at location loc.
interpolateFromDeltas
python
fonttools/fonttools
Lib/fontTools/varLib/models.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/models.py
MIT
def interpolateFromMasters(self, loc, masterValues, *, round=noRound): """Interpolate from master-values, at location loc.""" scalars = self.getMasterScalars(loc) return self.interpolateFromValuesAndScalars(masterValues, scalars)
Interpolate from master-values, at location loc.
interpolateFromMasters
python
fonttools/fonttools
Lib/fontTools/varLib/models.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/models.py
MIT
def interpolateFromMastersAndScalars(self, masterValues, scalars, *, round=noRound): """Interpolate from master-values, and scalars fetched from getScalars(), which is useful when you want to interpolate multiple master-values with the same location.""" deltas = self.getDeltas(masterValu...
Interpolate from master-values, and scalars fetched from getScalars(), which is useful when you want to interpolate multiple master-values with the same location.
interpolateFromMastersAndScalars
python
fonttools/fonttools
Lib/fontTools/varLib/models.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/models.py
MIT
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...
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 boun...
interpolate_cff2_metrics
python
fonttools/fonttools
Lib/fontTools/varLib/mutator.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/mutator.py
MIT
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.: .. code-block:: ...
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.: .. code-block:: {'wght': 400, 'wdth': 100} By default, a new TTFont object is returned. If ``...
instantiateVariableFont
python
fonttools/fonttools
Lib/fontTools/varLib/mutator.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/mutator.py
MIT
def plotModelFromMasters(model, masterValues, fig, **kwargs): """Plot a variation model and set of master values corresponding to the locations to the model into a pyplot figure. Variation model must have axisOrder of size 1 or 2.""" if len(model.axisOrder) == 1: _plotModelFromMasters2D(model, ...
Plot a variation model and set of master values corresponding to the locations to the model into a pyplot figure. Variation model must have axisOrder of size 1 or 2.
plotModelFromMasters
python
fonttools/fonttools
Lib/fontTools/varLib/plot.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/plot.py
MIT
def buildVFStatTable(ttFont: TTFont, doc: DesignSpaceDocument, vfName: str) -> None: """Build the STAT table for the variable font identified by its name in the given document. Knowing which variable we're building STAT data for is needed to subset the STAT locations to only include what the variable f...
Build the STAT table for the variable font identified by its name in the given document. Knowing which variable we're building STAT data for is needed to subset the STAT locations to only include what the variable font actually ships. .. versionadded:: 5.0 .. seealso:: - :func:`getStatAxe...
buildVFStatTable
python
fonttools/fonttools
Lib/fontTools/varLib/stat.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/stat.py
MIT
def getStatAxes(doc: DesignSpaceDocument, userRegion: Region) -> List[Dict]: """Return a list of axis dicts suitable for use as the ``axes`` argument to :func:`fontTools.otlLib.builder.buildStatTable()`. .. versionadded:: 5.0 """ # First, get the axis labels with explicit ordering # then append...
Return a list of axis dicts suitable for use as the ``axes`` argument to :func:`fontTools.otlLib.builder.buildStatTable()`. .. versionadded:: 5.0
getStatAxes
python
fonttools/fonttools
Lib/fontTools/varLib/stat.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/stat.py
MIT
def getStatLocations(doc: DesignSpaceDocument, userRegion: Region) -> List[Dict]: """Return a list of location dicts suitable for use as the ``locations`` argument to :func:`fontTools.otlLib.builder.buildStatTable()`. .. versionadded:: 5.0 """ axesByName = {axis.name: axis for axis in doc.axes} ...
Return a list of location dicts suitable for use as the ``locations`` argument to :func:`fontTools.otlLib.builder.buildStatTable()`. .. versionadded:: 5.0
getStatLocations
python
fonttools/fonttools
Lib/fontTools/varLib/stat.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/stat.py
MIT
def _visit(self, func): """Recurse down from self, if type of an object is ot.Device, call func() on it. Works on otData-style classes.""" if type(self) == ot.Device: func(self) elif isinstance(self, list): for that in self: _visit(that, func) elif hasattr(self, "getC...
Recurse down from self, if type of an object is ot.Device, call func() on it. Works on otData-style classes.
_visit
python
fonttools/fonttools
Lib/fontTools/varLib/varStore.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/varStore.py
MIT
def _Device_recordVarIdx(self, s): """Add VarIdx in this Device table (if any) to the set s.""" if self.DeltaFormat == 0x8000: s.add((self.StartSize << 16) + self.EndSize)
Add VarIdx in this Device table (if any) to the set s.
_Device_recordVarIdx
python
fonttools/fonttools
Lib/fontTools/varLib/varStore.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/varStore.py
MIT
def _Device_mapVarIdx(self, mapping, done): """Map VarIdx in this Device table (if any) through mapping.""" if id(self) in done: return done.add(id(self)) if self.DeltaFormat == 0x8000: varIdx = mapping[(self.StartSize << 16) + self.EndSize] self.StartSize = varIdx >> 16 ...
Map VarIdx in this Device table (if any) through mapping.
_Device_mapVarIdx
python
fonttools/fonttools
Lib/fontTools/varLib/varStore.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/varStore.py
MIT
def _characteristic_overhead(columns): """Returns overhead in bytes of encoding this characteristic as a VarData.""" c = 4 + 6 # 4 bytes for LOffset, 6 bytes for VarData header c += bit_count(columns) * 2 return c
Returns overhead in bytes of encoding this characteristic as a VarData.
_characteristic_overhead
python
fonttools/fonttools
Lib/fontTools/varLib/varStore.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/varStore.py
MIT
def VarStore_optimize(self, use_NO_VARIATION_INDEX=True, quantization=1): """Optimize storage. Returns mapping from old VarIdxes to new ones.""" # Overview: # # For each VarData row, we first extend it with zeroes to have # one column per region in VarRegionList. We then group the # rows into _...
Optimize storage. Returns mapping from old VarIdxes to new ones.
VarStore_optimize
python
fonttools/fonttools
Lib/fontTools/varLib/varStore.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/varStore.py
MIT
def _add_fvar(font, axes, instances: List[InstanceDescriptor]): """ Add 'fvar' table to font. axes is an ordered dictionary of DesignspaceAxis objects. instances is list of dictionary objects with 'location', 'stylename', and possibly 'postscriptfontname' entries. """ assert axes asse...
Add 'fvar' table to font. axes is an ordered dictionary of DesignspaceAxis objects. instances is list of dictionary objects with 'location', 'stylename', and possibly 'postscriptfontname' entries.
_add_fvar
python
fonttools/fonttools
Lib/fontTools/varLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/__init__.py
MIT
def _add_avar(font, axes, mappings, axisTags): """ Add 'avar' table to font. axes is an ordered dictionary of AxisDescriptor objects. """ assert axes assert isinstance(axes, OrderedDict) log.info("Generating avar") avar = newTable("avar") interesting = False vals_triples = {...
Add 'avar' table to font. axes is an ordered dictionary of AxisDescriptor objects.
_add_avar
python
fonttools/fonttools
Lib/fontTools/varLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/__init__.py
MIT
def drop_implied_oncurve_points(*masters: TTFont) -> int: """Drop impliable on-curve points from all the simple glyphs in masters. In TrueType glyf outlines, on-curve points can be implied when they are located exactly at the midpoint of the line connecting two consecutive off-curve points. The input ...
Drop impliable on-curve points from all the simple glyphs in masters. In TrueType glyf outlines, on-curve points can be implied when they are located exactly at the midpoint of the line connecting two consecutive off-curve points. The input masters' glyf tables are assumed to contain same-named glyphs tha...
drop_implied_oncurve_points
python
fonttools/fonttools
Lib/fontTools/varLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/__init__.py
MIT
def build_many( designspace: DesignSpaceDocument, master_finder=lambda s: s, exclude=[], optimize=True, skip_vf=lambda vf_name: False, colr_layer_reuse=True, drop_implied_oncurves=False, ): """ Build variable fonts from a designspace file, version 5 which can define several VFs, ...
Build variable fonts from a designspace file, version 5 which can define several VFs, or version 4 which has implicitly one VF covering the whole doc. If master_finder is set, it should be a callable that takes master filename as found in designspace file and map it to master font binary as to be ...
build_many
python
fonttools/fonttools
Lib/fontTools/varLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/__init__.py
MIT
def build( designspace, master_finder=lambda s: s, exclude=[], optimize=True, colr_layer_reuse=True, drop_implied_oncurves=False, ): """ Build variation font from a designspace file. If master_finder is set, it should be a callable that takes master filename as found in designsp...
Build variation font from a designspace file. If master_finder is set, it should be a callable that takes master filename as found in designspace file and map it to master font binary as to be opened (eg. .ttf or .otf).
build
python
fonttools/fonttools
Lib/fontTools/varLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/__init__.py
MIT
def load_masters(designspace, master_finder=lambda s: s): """Ensure that all SourceDescriptor.font attributes have an appropriate TTFont object loaded, or else open TTFont objects from the SourceDescriptor.path attributes. The paths can point to either an OpenType font, a TTX file, or a UFO. In the ...
Ensure that all SourceDescriptor.font attributes have an appropriate TTFont object loaded, or else open TTFont objects from the SourceDescriptor.path attributes. The paths can point to either an OpenType font, a TTX file, or a UFO. In the latter case, use the provided master_finder callable to map from...
load_masters
python
fonttools/fonttools
Lib/fontTools/varLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/__init__.py
MIT
def addGSUBFeatureVariations(vf, designspace, featureTags=(), *, log_enabled=False): """Add GSUB FeatureVariations table to variable font, based on DesignSpace rules. Args: vf: A TTFont object representing the variable font. designspace: A DesignSpaceDocument object. featureTags: Option...
Add GSUB FeatureVariations table to variable font, based on DesignSpace rules. Args: vf: A TTFont object representing the variable font. designspace: A DesignSpaceDocument object. featureTags: Optional feature tag(s) to use for the FeatureVariations records. If unset, the key 'c...
addGSUBFeatureVariations
python
fonttools/fonttools
Lib/fontTools/varLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/__init__.py
MIT
def main(args=None): """Build variable fonts from a designspace file and masters""" from argparse import ArgumentParser from fontTools import configLogger parser = ArgumentParser(prog="varLib", description=main.__doc__) parser.add_argument("designspace") output_group = parser.add_mutually_exclu...
Build variable fonts from a designspace file and masters
main
python
fonttools/fonttools
Lib/fontTools/varLib/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/__init__.py
MIT
def updateNameTable(varfont, axisLimits): """Update instatiated variable font's name table using STAT AxisValues. Raises ValueError if the STAT table is missing or an Axis Value table is missing for requested axis locations. First, collect all STAT AxisValues that match the new default axis locations ...
Update instatiated variable font's name table using STAT AxisValues. Raises ValueError if the STAT table is missing or an Axis Value table is missing for requested axis locations. First, collect all STAT AxisValues that match the new default axis locations (excluding "elided" ones); concatenate the st...
updateNameTable
python
fonttools/fonttools
Lib/fontTools/varLib/instancer/names.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/instancer/names.py
MIT
def expand( cls, v: Union[ "AxisTriple", float, # pin axis at single value, same as min==default==max Tuple[float, float], # (min, max), restrict axis and keep default Tuple[float, float, float], # (min, default, max) ], ) -> "AxisTriple": ...
Convert a single value or a tuple into an AxisTriple. If the input is a single value, it is interpreted as a pin at that value. If the input is a tuple, it is interpreted as (min, max) or (min, default, max).
expand
python
fonttools/fonttools
Lib/fontTools/varLib/instancer/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/instancer/__init__.py
MIT
def limitRangeAndPopulateDefaults(self, fvarTriple) -> "AxisTriple": """Return a new AxisTriple with the default value filled in. Set default to fvar axis default if the latter is within the min/max range, otherwise set default to the min or max value, whichever is closer to the fvar ax...
Return a new AxisTriple with the default value filled in. Set default to fvar axis default if the latter is within the min/max range, otherwise set default to the min or max value, whichever is closer to the fvar axis default. If the default value is already set, return self.
limitRangeAndPopulateDefaults
python
fonttools/fonttools
Lib/fontTools/varLib/instancer/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/instancer/__init__.py
MIT
def instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True): """Remove? https://github.com/fonttools/fonttools/pull/2266""" gvar = varfont["gvar"] glyf = varfont["glyf"] hMetrics = varfont["hmtx"].metrics vMetrics = getattr(varfont.get("vmtx"), "metrics", None) _instantiateGvarGl...
Remove? https://github.com/fonttools/fonttools/pull/2266
instantiateGvarGlyph
python
fonttools/fonttools
Lib/fontTools/varLib/instancer/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/instancer/__init__.py
MIT
def verticalMetricsKeptInSync(varfont): """Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing. When applying MVAR deltas to the OS/2 table, if the ascender, descender and line gap change but they were the same as the respective hhea metrics in the original font, this context mana...
Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing. When applying MVAR deltas to the OS/2 table, if the ascender, descender and line gap change but they were the same as the respective hhea metrics in the original font, this context manager ensures that hhea metrcs also get updated ...
verticalMetricsKeptInSync
python
fonttools/fonttools
Lib/fontTools/varLib/instancer/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/instancer/__init__.py
MIT
def setRibbiBits(font): """Set the `head.macStyle` and `OS/2.fsSelection` style bits appropriately.""" english_ribbi_style = font["name"].getName(names.NameID.SUBFAMILY_NAME, 3, 1, 0x409) if english_ribbi_style is None: return styleMapStyleName = english_ribbi_style.toStr().lower() if ...
Set the `head.macStyle` and `OS/2.fsSelection` style bits appropriately.
setRibbiBits
python
fonttools/fonttools
Lib/fontTools/varLib/instancer/__init__.py
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/varLib/instancer/__init__.py
MIT