1 DesignSpaceDocument Python API
An object to read, write and edit interpolation systems for typefaces. Define sources, axes, rules, variable fonts and instances.
Get an overview of the available classes in the Class Diagram below:
DesignSpaceDocument
- class fontTools.designspaceLib.DesignSpaceDocument(readerClass=None, writerClass=None)[source]
Bases:
LogMixin
,AsDictMixin
The DesignSpaceDocument object can read and write
.designspace
data. It imports the axes, sources, variable fonts and instances to very basic descriptor objects that store the data in attributes. Data is added to the document by creating such descriptor objects, filling them with data and then adding them to the document. This makes it easy to integrate this object in different contexts.The DesignSpaceDocument object can be subclassed to work with different objects, as long as they have the same attributes. Reader and Writer objects can be subclassed as well.
Note: Python attribute names are usually camelCased, the corresponding XML attributes are usually all lowercase.
from fontTools.designspaceLib import DesignSpaceDocument doc = DesignSpaceDocument.fromfile("some/path/to/my.designspace") doc.formatVersion doc.elidedFallbackName doc.axes doc.axisMappings doc.locationLabels doc.rules doc.rulesProcessingLast doc.sources doc.variableFonts doc.instances doc.lib
- asdict()
- property log
- path
String, optional. When the document is read from the disk, this is the full path that was given to
read()
orfromfile()
.
- filename
String, optional. When the document is read from the disk, this is its original file name, i.e. the last part of its path.
When the document is produced by a Python script and still only exists in memory, the producing script can write here an indication of a possible “good” filename, in case one wants to save the file somewhere.
- formatVersion: str | None
Format version for this document, as a string. E.g. “4.0”
- elidedFallbackName: str | None
STAT Style Attributes Header field
elidedFallbackNameID
.See: OTSpec STAT Style Attributes Header
Added in version 5.0.
- axes: List[AxisDescriptor | DiscreteAxisDescriptor]
List of this document’s axes.
- axisMappings: List[AxisMappingDescriptor]
List of this document’s axis mappings.
- locationLabels: List[LocationLabelDescriptor]
List of this document’s STAT format 4 labels.
Added in version 5.0.
- rules: List[RuleDescriptor]
List of this document’s rules.
- rulesProcessingLast: bool
This flag indicates whether the substitution rules should be applied before or after other glyph substitution features.
False: before
True: after.
Default is False. For new projects, you probably want True. See the following issues for more information: fontTools#1371 fontTools#2050
If you want to use a different feature altogether, e.g.
calt
, use the lib keycom.github.fonttools.varLib.featureVarsFeatureTag
<lib> <dict> <key>com.github.fonttools.varLib.featureVarsFeatureTag</key> <string>calt</string> </dict> </lib>
- sources: List[SourceDescriptor]
List of this document’s sources.
- variableFonts: List[VariableFontDescriptor]
List of this document’s variable fonts.
Added in version 5.0.
- instances: List[InstanceDescriptor]
List of this document’s instances.
- lib: Dict
User defined, custom data associated with the whole document.
Use reverse-DNS notation to identify your own data. Respect the data stored by others.
- default: str | None
Name of the default master.
This attribute is updated by the
findDefault()
- classmethod fromfile(path, readerClass=None, writerClass=None)[source]
Read a designspace file from
path
and return a new instance of :class:.
- read(path)[source]
Read a designspace file from
path
and populates the fields ofself
with the data.
- updatePaths()[source]
Right before we save we need to identify and respond to the following situations: In each descriptor, we have to do the right thing for the filename attribute.
case 1. descriptor.filename == None descriptor.path == None -- action: write as is, descriptors will not have a filename attr. useless, but no reason to interfere. case 2. descriptor.filename == "../something" descriptor.path == None -- action: write as is. The filename attr should not be touched. case 3. descriptor.filename == None descriptor.path == "~/absolute/path/there" -- action: calculate the relative path for filename. We're not overwriting some other value for filename, it should be fine case 4. descriptor.filename == '../somewhere' descriptor.path == "~/absolute/path/there" -- action: there is a conflict between the given filename, and the path. So we know where the file is relative to the document. Can't guess why they're different, we just choose for path to be correct and update filename.
- addSource(sourceDescriptor: SourceDescriptor)[source]
Add the given
sourceDescriptor
todoc.sources
.
- addSourceDescriptor(**kwargs)[source]
Instantiate a new
SourceDescriptor
using the givenkwargs
and add it todoc.sources
.
- addInstance(instanceDescriptor: InstanceDescriptor)[source]
Add the given
instanceDescriptor
toinstances
.
- addInstanceDescriptor(**kwargs)[source]
Instantiate a new
InstanceDescriptor
using the givenkwargs
and add it toinstances
.
- addAxis(axisDescriptor: AxisDescriptor | DiscreteAxisDescriptor)[source]
Add the given
axisDescriptor
toaxes
.
- addAxisDescriptor(**kwargs)[source]
Instantiate a new
AxisDescriptor
using the givenkwargs
and add it toaxes
.The axis will be and instance of
DiscreteAxisDescriptor
if thekwargs
provide avalue
, or aAxisDescriptor
otherwise.
- addAxisMapping(axisMappingDescriptor: AxisMappingDescriptor)[source]
Add the given
axisMappingDescriptor
toaxisMappings
.
- addAxisMappingDescriptor(**kwargs)[source]
Instantiate a new
AxisMappingDescriptor
using the givenkwargs
and add it torules
.
- addRule(ruleDescriptor: RuleDescriptor)[source]
Add the given
ruleDescriptor
torules
.
- addRuleDescriptor(**kwargs)[source]
Instantiate a new
RuleDescriptor
using the givenkwargs
and add it torules
.
- addVariableFont(variableFontDescriptor: VariableFontDescriptor)[source]
Add the given
variableFontDescriptor
tovariableFonts
.Added in version 5.0.
- addVariableFontDescriptor(**kwargs)[source]
Instantiate a new
VariableFontDescriptor
using the givenkwargs
and add it tovariableFonts
.Added in version 5.0.
- addLocationLabel(locationLabelDescriptor: LocationLabelDescriptor)[source]
Add the given
locationLabelDescriptor
tolocationLabels
.Added in version 5.0.
- addLocationLabelDescriptor(**kwargs)[source]
Instantiate a new
LocationLabelDescriptor
using the givenkwargs
and add it tolocationLabels
.Added in version 5.0.
- labelForUserLocation(userLocation: Dict[str, float]) LocationLabelDescriptor | None [source]
Return the
LocationLabel
that matches the givenuserLocation
, orNone
if no such label exists.Added in version 5.0.
- updateFilenameFromPath(masters=True, instances=True, force=False)[source]
Set a descriptor filename attr from the path and this document path.
If the filename attribute is not None: skip it.
- getAxis(name: str) AxisDescriptor | DiscreteAxisDescriptor | None [source]
Return the axis with the given
name
, orNone
if no such axis exists.
- getAxisByTag(tag: str) AxisDescriptor | DiscreteAxisDescriptor | None [source]
Return the axis with the given
tag
, orNone
if no such axis exists.
- getLocationLabel(name: str) LocationLabelDescriptor | None [source]
Return the top-level location label with the given
name
, orNone
if no such label exists.Added in version 5.0.
- map_forward(userLocation: Dict[str, float]) Dict[str, float] [source]
Map a user location to a design location.
Assume that missing coordinates are at the default location for that axis.
Note: the output won’t be anisotropic, only the xvalue is set.
Added in version 5.0.
- map_backward(designLocation: Dict[str, float | Tuple[float, float]]) Dict[str, float] [source]
Map a design location to a user location.
Assume that missing coordinates are at the default location for that axis.
When the input has anisotropic locations, only the xvalue is used.
Added in version 5.0.
- findDefault()[source]
Set and return SourceDescriptor at the default location or None.
The default location is the set of all default values in user space of all axes.
This function updates the document’s
default
value.Changed in version 5.0: Allow the default source to not specify some of the axis values, and they are assumed to be the default. See
SourceDescriptor.getFullDesignLocation()
- normalize()[source]
Normalise the geometry of this designspace:
scale all the locations of all masters and instances to the -1 - 0 - 1 value.
we need the axis data to do the scaling, so we do those last.
- loadSourceFonts(opener, **kwargs)[source]
Ensure SourceDescriptor.font attributes are loaded, and return list of fonts.
Takes a callable which initializes a new font object (e.g. TTFont, or defcon.Font, etc.) from the SourceDescriptor.path, and sets the SourceDescriptor.font attribute. If the font attribute is already not None, it is not loaded again. Fonts with the same path are only loaded once and shared among SourceDescriptors.
For example, to load UFO sources using defcon:
designspace = DesignSpaceDocument.fromfile(“path/to/my.designspace”) designspace.loadSourceFonts(defcon.Font)
Or to load masters as FontTools binary fonts, including extra options:
designspace.loadSourceFonts(ttLib.TTFont, recalcBBoxes=False)
- Parameters:
opener (Callable) – takes one required positional argument, the source.path, and an optional list of keyword arguments, and returns a new font object loaded from the path.
**kwargs – extra options passed on to the opener function.
- Returns:
List of font objects in the order they appear in the sources list.
- property formatTuple
Return the formatVersion as a tuple of (major, minor).
Added in version 5.0.
- getVariableFonts() List[VariableFontDescriptor] [source]
Return all variable fonts defined in this document, or implicit variable fonts that can be built from the document’s continuous axes.
In the case of Designspace documents before version 5, the whole document was implicitly describing a variable font that covers the whole space.
In version 5 and above documents, there can be as many variable fonts as there are locations on discrete axes.
See also
splitInterpolable()
Added in version 5.0.
AxisDescriptor
- class fontTools.designspaceLib.AxisDescriptor(*, tag=None, name=None, labelNames=None, minimum=None, default=None, maximum=None, hidden=False, map=None, axisOrdering=None, axisLabels=None)[source]
Bases:
AbstractAxisDescriptor
Simple container for the axis data.
Add more localisations?
a1 = AxisDescriptor() a1.minimum = 1 a1.maximum = 1000 a1.default = 400 a1.name = "weight" a1.tag = "wght" a1.labelNames['fa-IR'] = "قطر" a1.labelNames['en'] = "Wéíght" a1.map = [(1.0, 10.0), (400.0, 66.0), (1000.0, 990.0)] a1.axisOrdering = 1 a1.axisLabels = [ AxisLabelDescriptor(name="Regular", userValue=400, elidable=True) ] doc.addAxis(a1)
- minimum
number. The minimum value for this axis in user space.
MutatorMath + varLib.
- maximum
number. The maximum value for this axis in user space.
MutatorMath + varLib.
- default
number. The default value for this axis, i.e. when a new location is created, this is the value this axis will get in user space.
MutatorMath + varLib.
- asdict()
- compare(other)
- flavor = 'axis'
- tag
string. Four letter tag for this axis. Some might be registered at the OpenType specification. Privately-defined axis tags must begin with an uppercase letter and use only uppercase letters or digits.
- name
string. Name of the axis as it is used in the location dicts.
MutatorMath + varLib.
- labelNames
dict. When defining a non-registered axis, it will be necessary to define user-facing readable names for the axis. Keyed by xml:lang code. Values are required to be
unicode
strings, even if they only contain ASCII characters.
bool. Whether this axis should be hidden in user interfaces.
- map
list of input / output values that can describe a warp of user space to design space coordinates. If no map values are present, it is assumed user space is the same as design space, as in [(minimum, minimum), (maximum, maximum)].
varLib.
- axisOrdering
STAT table field
axisOrdering
.Added in version 5.0.
- axisLabels: List[AxisLabelDescriptor]
STAT table entries for Axis Value Tables format 1, 2, 3.
See: OTSpec STAT Axis Value Tables
Added in version 5.0.
DiscreteAxisDescriptor
- class fontTools.designspaceLib.DiscreteAxisDescriptor(*, tag=None, name=None, labelNames=None, values=None, default=None, hidden=False, map=None, axisOrdering=None, axisLabels=None)[source]
Bases:
AbstractAxisDescriptor
Container for discrete axis data.
Use this for axes that do not interpolate. The main difference from a continuous axis is that a continuous axis has a
minimum
andmaximum
, while a discrete axis has a list ofvalues
.Example: an Italic axis with 2 stops, Roman and Italic, that are not compatible. The axis still allows to bind together the full font family, which is useful for the STAT table, however it can’t become a variation axis in a VF.
a2 = DiscreteAxisDescriptor() a2.values = [0, 1] a2.default = 0 a2.name = "Italic" a2.tag = "ITAL" a2.labelNames['fr'] = "Italique" a2.map = [(0, 0), (1, -11)] a2.axisOrdering = 2 a2.axisLabels = [ AxisLabelDescriptor(name="Roman", userValue=0, elidable=True) ] doc.addAxis(a2)
Added in version 5.0.
- flavor = 'axis'
- default: float
The default value for this axis, i.e. when a new location is created, this is the value this axis will get in user space.
However, this default value is less important than in continuous axes:
it doesn’t define the “neutral” version of outlines from which deltas would apply, as this axis does not interpolate.
it doesn’t provide the reference glyph set for the designspace, as fonts at each value can have different glyph sets.
- values: List[float]
List of possible values for this axis. Contrary to continuous axes, only the values in this list can be taken by the axis, nothing in-between.
- map_forward(value)[source]
Maps value from axis mapping’s input to output.
Returns value unchanged if no mapping entry is found.
Note: for discrete axes, each value must have its mapping entry, if you intend that value to be mapped.
- map_backward(value)[source]
Maps value from axis mapping’s output to input.
Returns value unchanged if no mapping entry is found.
Note: for discrete axes, each value must have its mapping entry, if you intend that value to be mapped.
- asdict()
- compare(other)
- tag
string. Four letter tag for this axis. Some might be registered at the OpenType specification. Privately-defined axis tags must begin with an uppercase letter and use only uppercase letters or digits.
- name
string. Name of the axis as it is used in the location dicts.
MutatorMath + varLib.
- labelNames
dict. When defining a non-registered axis, it will be necessary to define user-facing readable names for the axis. Keyed by xml:lang code. Values are required to be
unicode
strings, even if they only contain ASCII characters.
bool. Whether this axis should be hidden in user interfaces.
- map
list of input / output values that can describe a warp of user space to design space coordinates. If no map values are present, it is assumed user space is the same as design space, as in [(minimum, minimum), (maximum, maximum)].
varLib.
- axisOrdering
STAT table field
axisOrdering
.Added in version 5.0.
- axisLabels: List[AxisLabelDescriptor]
STAT table entries for Axis Value Tables format 1, 2, 3.
See: OTSpec STAT Axis Value Tables
Added in version 5.0.
AxisLabelDescriptor
- class fontTools.designspaceLib.AxisLabelDescriptor(*, name, userValue, userMinimum=None, userMaximum=None, elidable=False, olderSibling=False, linkedUserValue=None, labelNames=None)[source]
Bases:
SimpleDescriptor
Container for axis label data.
Analogue of OpenType’s STAT data for a single axis (formats 1, 2 and 3). All values are user values. See: OTSpec STAT Axis value table, format 1, 2, 3
The STAT format of the Axis value depends on which field are filled-in, see
getFormat()
Added in version 5.0.
- flavor = 'label'
- userMinimum: float | None
STAT field
rangeMinValue
(format 2).
- userValue: float
STAT field
value
(format 1, 3) ornominalValue
(format 2).
- userMaximum: float | None
STAT field
rangeMaxValue
(format 2).
- name: str
Label for this axis location, STAT field
valueNameID
.
- elidable: bool
STAT flag
ELIDABLE_AXIS_VALUE_NAME
.See: OTSpec STAT Flags
- olderSibling: bool
STAT flag
OLDER_SIBLING_FONT_ATTRIBUTE
.See: OTSpec STAT Flags
- linkedUserValue: float | None
STAT field
linkedValue
(format 3).
- labelNames: MutableMapping[str, str]
User-facing translations of this location’s label. Keyed by
xml:lang
code.
- getFormat() int [source]
Determine which format of STAT Axis value to use to encode this label.
STAT Format
userValue
userMinimum
userMaximum
linkedUserValue
1
✅
❌
❌
❌
2
✅
✅
✅
❌
3
✅
❌
❌
✅
- property defaultName: str
Return the English name from
labelNames
or thename
.
- asdict()
- compare(other)
LocationLabelDescriptor
- class fontTools.designspaceLib.LocationLabelDescriptor(*, name, userLocation, elidable=False, olderSibling=False, labelNames=None)[source]
Bases:
SimpleDescriptor
Container for location label data.
Analogue of OpenType’s STAT data for a free-floating location (format 4). All values are user values.
See: OTSpec STAT Axis value table, format 4
Added in version 5.0.
- flavor = 'label'
- name: str
Label for this named location, STAT field
valueNameID
.
- userLocation: Dict[str, float]
Location in user coordinates along each axis.
If an axis is not mentioned, it is assumed to be at its default location.
See also
This may be only part of the full location. See:
getFullUserLocation()
- elidable: bool
STAT flag
ELIDABLE_AXIS_VALUE_NAME
.See: OTSpec STAT Flags
- olderSibling: bool
STAT flag
OLDER_SIBLING_FONT_ATTRIBUTE
.See: OTSpec STAT Flags
- labelNames: Dict[str, str]
User-facing translations of this location’s label. Keyed by xml:lang code.
- property defaultName: str
Return the English name from
labelNames
or thename
.
- getFullUserLocation(doc: DesignSpaceDocument) Dict[str, float] [source]
Get the complete user location of this label, by combining data from the explicit user location and default axis values.
Added in version 5.0.
- asdict()
- compare(other)
RuleDescriptor
- class fontTools.designspaceLib.RuleDescriptor(*, name=None, conditionSets=None, subs=None)[source]
Bases:
SimpleDescriptor
Represents the rule descriptor element: a set of glyph substitutions to trigger conditionally in some parts of the designspace.
r1 = RuleDescriptor() r1.name = "unique.rule.name" r1.conditionSets.append([dict(name="weight", minimum=-10, maximum=10), dict(...)]) r1.conditionSets.append([dict(...), dict(...)]) r1.subs.append(("a", "a.alt"))
<!-- optional: list of substitution rules --> <rules> <rule name="vertical.bars"> <conditionset> <condition minimum="250.000000" maximum="750.000000" name="weight"/> <condition minimum="100" name="width"/> <condition minimum="10" maximum="40" name="optical"/> </conditionset> <sub name="cent" with="cent.alt"/> <sub name="dollar" with="dollar.alt"/> </rule> </rules>
- name
string. Unique name for this rule. Can be used to reference this rule data.
- conditionSets
a list of conditionsets.
Each conditionset is a list of conditions.
Each condition is a dict with
name
,minimum
andmaximum
keys.
- subs
list of substitutions.
Each substitution is stored as tuples of glyphnames, e.g. (“a”, “a.alt”).
Note: By default, rules are applied first, before other text shaping/OpenType layout, as they are part of the Required Variation Alternates OpenType feature. See ref:rules-element § Attributes.
- asdict()
- compare(other)
Evaluating rules
- fontTools.designspaceLib.evaluateRule(rule, location)[source]
Return True if any of the rule’s conditionsets matches the given location.
SourceDescriptor
- class fontTools.designspaceLib.SourceDescriptor(*, filename=None, path=None, font=None, name=None, location=None, designLocation=None, layerName=None, familyName=None, styleName=None, localisedFamilyName=None, copyLib=False, copyInfo=False, copyGroups=False, copyFeatures=False, muteKerning=False, muteInfo=False, mutedGlyphNames=None)[source]
Bases:
SimpleDescriptor
Simple container for data related to the source
doc = DesignSpaceDocument() s1 = SourceDescriptor() s1.path = masterPath1 s1.name = "master.ufo1" s1.font = defcon.Font("master.ufo1") s1.location = dict(weight=0) s1.familyName = "MasterFamilyName" s1.styleName = "MasterStyleNameOne" s1.localisedFamilyName = dict(fr="Caractère") s1.mutedGlyphNames.append("A") s1.mutedGlyphNames.append("Z") doc.addSource(s1)
- flavor = 'source'
- property filename
string. A relative path to the source file, as it is in the document.
MutatorMath + VarLib.
- property path
The absolute path, calculated from filename.
- font
Any Python object. Optional. Points to a representation of this source font that is loaded in memory, as a Python object (e.g. a
defcon.Font
or afontTools.ttFont.TTFont
).The default document reader will not fill-in this attribute, and the default writer will not use this attribute. It is up to the user of
designspaceLib
to either load the resource identified byfilename
and store it in this field, or write the contents of this field to the disk and make`filename
point to that.
- name
string. Optional. Unique identifier name for this source.
MutatorMath + varLib.
- designLocation
dict. Axis values for this source, in design space coordinates.
MutatorMath + varLib.
This may be only part of the full design location. See
getFullDesignLocation()
Added in version 5.0.
- layerName
string. The name of the layer in the source to look for outline data. Default
None
which meansforeground
.
- familyName
string. Family name of this source. Though this data can be extracted from the font, it can be efficient to have it right here.
varLib.
- styleName
string. Style name of this source. Though this data can be extracted from the font, it can be efficient to have it right here.
varLib.
- localisedFamilyName
dict. A dictionary of localised family name strings, keyed by language code.
If present, will be used to build localized names for all instances.
Added in version 5.0.
- copyLib
bool. Indicates if the contents of the font.lib need to be copied to the instances.
MutatorMath.
Deprecated since version 5.0.
- copyInfo
bool. Indicates if the non-interpolating font.info needs to be copied to the instances.
MutatorMath.
Deprecated since version 5.0.
- copyGroups
bool. Indicates if the groups need to be copied to the instances.
MutatorMath.
Deprecated since version 5.0.
- copyFeatures
bool. Indicates if the feature text needs to be copied to the instances.
MutatorMath.
Deprecated since version 5.0.
- muteKerning
bool. Indicates if the kerning data from this source needs to be muted (i.e. not be part of the calculations).
MutatorMath only.
- muteInfo
bool. Indicated if the interpolating font.info data for this source needs to be muted.
MutatorMath only.
- mutedGlyphNames
list. Glyphnames that need to be muted in the instances.
MutatorMath only.
- property location
dict. Axis values for this source, in design space coordinates.
MutatorMath + varLib.
Deprecated since version 5.0: Use the more explicit alias for this property
designLocation
.
- setFamilyName(familyName, languageCode='en')[source]
Setter for
localisedFamilyName
Added in version 5.0.
- getFamilyName(languageCode='en')[source]
Getter for
localisedFamilyName
Added in version 5.0.
- getFullDesignLocation(doc: DesignSpaceDocument) Dict[str, float] [source]
Get the complete design location of this source, from its
designLocation
and the document’s axis defaults.Added in version 5.0.
- asdict()
- compare(other)
VariableFontDescriptor
- class fontTools.designspaceLib.VariableFontDescriptor(*, name, filename=None, axisSubsets=None, lib=None)[source]
Bases:
SimpleDescriptor
Container for variable fonts, sub-spaces of the Designspace.
Use-cases:
From a single DesignSpace with discrete axes, define 1 variable font per value on the discrete axes. Before version 5, you would have needed 1 DesignSpace per such variable font, and a lot of data duplication.
From a big variable font with many axes, define subsets of that variable font that only include some axes and freeze other axes at a given location.
Added in version 5.0.
- flavor = 'variable-font'
- name: str
string, required. Name of this variable to identify it during the build process and from other parts of the document, and also as a filename in case the filename property is empty.
VarLib.
- property filename
string, optional. Relative path to the variable font file, as it is in the document. The file may or may not exist.
If not specified, the
name
will be used as a basename for the file.
- axisSubsets: List[RangeAxisSubsetDescriptor | ValueAxisSubsetDescriptor]
Axis subsets to include in this variable font.
If an axis is not mentioned, assume that we only want the default location of that axis (same as a
ValueAxisSubsetDescriptor
).
- lib: MutableMapping[str, Any]
Custom data associated with this variable font.
- asdict()
- compare(other)
RangeAxisSubsetDescriptor
- class fontTools.designspaceLib.RangeAxisSubsetDescriptor(*, name, userMinimum=-inf, userDefault=None, userMaximum=inf)[source]
Bases:
SimpleDescriptor
Subset of a continuous axis to include in a variable font.
Added in version 5.0.
- flavor = 'axis-subset'
- name: str
Name of the
AxisDescriptor
to subset.
- userMinimum: float
New minimum value of the axis in the target variable font. If not specified, assume the same minimum value as the full axis. (default =
-math.inf
)
- userDefault: float | None
New default value of the axis in the target variable font. If not specified, assume the same default value as the full axis. (default =
None
)
- userMaximum: float
New maximum value of the axis in the target variable font. If not specified, assume the same maximum value as the full axis. (default =
math.inf
)
- asdict()
- compare(other)
ValueAxisSubsetDescriptor
- class fontTools.designspaceLib.ValueAxisSubsetDescriptor(*, name, userValue)[source]
Bases:
SimpleDescriptor
Single value of a discrete or continuous axis to use in a variable font.
Added in version 5.0.
- flavor = 'axis-subset'
- name: str
Name of the
AxisDescriptor
orDiscreteAxisDescriptor
to “snapshot” or “freeze”.
- userValue: float
Value in user coordinates at which to freeze the given axis.
- asdict()
- compare(other)
InstanceDescriptor
- class fontTools.designspaceLib.InstanceDescriptor(*, filename=None, path=None, font=None, name=None, location=None, locationLabel=None, designLocation=None, userLocation=None, familyName=None, styleName=None, postScriptFontName=None, styleMapFamilyName=None, styleMapStyleName=None, localisedFamilyName=None, localisedStyleName=None, localisedStyleMapFamilyName=None, localisedStyleMapStyleName=None, glyphs=None, kerning=True, info=True, lib=None)[source]
Bases:
SimpleDescriptor
Simple container for data related to the instance
i2 = InstanceDescriptor() i2.path = instancePath2 i2.familyName = "InstanceFamilyName" i2.styleName = "InstanceStyleName" i2.name = "instance.ufo2" # anisotropic location i2.designLocation = dict(weight=500, width=(400,300)) i2.postScriptFontName = "InstancePostscriptName" i2.styleMapFamilyName = "InstanceStyleMapFamilyName" i2.styleMapStyleName = "InstanceStyleMapStyleName" i2.lib['com.coolDesignspaceApp.specimenText'] = 'Hamburgerwhatever' doc.addInstance(i2)
- flavor = 'instance'
- property filename
string. Relative path to the instance file, as it is in the document. The file may or may not exist.
MutatorMath + VarLib.
- property path
string. Absolute path to the instance file, calculated from the document path and the string in the filename attr. The file may or may not exist.
MutatorMath.
- font
Same as
SourceDescriptor.font
See also
- name
string. Unique identifier name of the instance, used to identify it if it needs to be referenced from elsewhere in the document.
- locationLabel
Name of a
LocationLabelDescriptor
. If provided, the instance should have the same location as the LocationLabel.Added in version 5.0.
- designLocation: Dict[str, float | Tuple[float, float]]
dict. Axis values for this instance, in design space coordinates.
MutatorMath + varLib.
See also
This may be only part of the full location. See:
getFullDesignLocation()
getFullUserLocation()
Added in version 5.0.
- userLocation: Dict[str, float]
dict. Axis values for this instance, in user space coordinates.
MutatorMath + varLib.
See also
This may be only part of the full location. See:
getFullDesignLocation()
getFullUserLocation()
Added in version 5.0.
- familyName
string. Family name of this instance.
MutatorMath + varLib.
- styleName
string. Style name of this instance.
MutatorMath + varLib.
- postScriptFontName
string. Postscript fontname for this instance.
MutatorMath + varLib.
- styleMapFamilyName
string. StyleMap familyname for this instance.
MutatorMath + varLib.
- styleMapStyleName
string. StyleMap stylename for this instance.
MutatorMath + varLib.
- localisedFamilyName
dict. A dictionary of localised family name strings, keyed by language code.
- localisedStyleName
dict. A dictionary of localised stylename strings, keyed by language code.
- localisedStyleMapFamilyName
A dictionary of localised style map familyname strings, keyed by language code.
- localisedStyleMapStyleName
A dictionary of localised style map stylename strings, keyed by language code.
- glyphs
dict for special master definitions for glyphs. If glyphs need special masters (to record the results of executed rules for example).
MutatorMath.
Deprecated since version 5.0: Use rules or sparse sources instead.
- kerning
bool. Indicates if this instance needs its kerning calculated.
MutatorMath.
Deprecated since version 5.0.
- info
bool. Indicated if this instance needs the interpolating font.info calculated.
Deprecated since version 5.0.
- lib
Custom data associated with this instance.
- property location
dict. Axis values for this instance.
MutatorMath + varLib.
Deprecated since version 5.0: Use the more explicit alias for this property
designLocation
.
- setStyleName(styleName, languageCode='en')[source]
These methods give easier access to the localised names.
- clearLocation(axisName: str | None = None)[source]
Clear all location-related fields. Ensures that :attr:
designLocation
and :attr:userLocation
are dictionaries (possibly empty if clearing everything).In order to update the location of this instance wholesale, a user should first clear all the fields, then change the field(s) for which they have data.
instance.clearLocation() instance.designLocation = {'Weight': (34, 36.5), 'Width': 100} instance.userLocation = {'Opsz': 16}
In order to update a single axis location, the user should only clear that axis, then edit the values:
instance.clearLocation('Weight') instance.designLocation['Weight'] = (34, 36.5)
- Parameters:
axisName – if provided, only clear the location for that axis.
Added in version 5.0.
- getLocationLabelDescriptor(doc: DesignSpaceDocument) LocationLabelDescriptor | None [source]
Get the
LocationLabelDescriptor
instance that matches this instances’slocationLabel
.Raises if the named label can’t be found.
Added in version 5.0.
- getFullDesignLocation(doc: DesignSpaceDocument) Dict[str, float | Tuple[float, float]] [source]
Get the complete design location of this instance, by combining data from the various location fields, default axis values and mappings, and top-level location labels.
The source of truth for this instance’s location is determined for each axis independently by taking the first not-None field in this list:
locationLabel
: the location along this axis is the same as the matching STAT format 4 label. No anisotropy.designLocation[axisName]
: the explicit design location along this axis, possibly anisotropic.userLocation[axisName]
: the explicit user location along this axis. No anisotropy.axis.default
: default axis value. No anisotropy.
Added in version 5.0.
- getFullUserLocation(doc: DesignSpaceDocument) Dict[str, float] [source]
Get the complete user location for this instance.
See also
Added in version 5.0.
- asdict()
- compare(other)
Subclassing descriptors
The DesignSpaceDocument can take subclassed Reader and Writer objects. This allows you to work with your own descriptors. You could subclass the descriptors. But as long as they have the basic attributes the descriptor does not need to be a subclass.
class MyDocReader(BaseDocReader):
axisDescriptorClass = MyAxisDescriptor
discreteAxisDescriptorClass = MyDiscreteAxisDescriptor
axisLabelDescriptorClass = MyAxisLabelDescriptor
locationLabelDescriptorClass = MyLocationLabelDescriptor
ruleDescriptorClass = MyRuleDescriptor
sourceDescriptorClass = MySourceDescriptor
variableFontsDescriptorClass = MyVariableFontDescriptor
valueAxisSubsetDescriptorClass = MyValueAxisSubsetDescriptor
rangeAxisSubsetDescriptorClass = MyRangeAxisSubsetDescriptor
instanceDescriptorClass = MyInstanceDescriptor
class MyDocWriter(BaseDocWriter):
axisDescriptorClass = MyAxisDescriptor
discreteAxisDescriptorClass = MyDiscreteAxisDescriptor
axisLabelDescriptorClass = MyAxisLabelDescriptor
locationLabelDescriptorClass = MyLocationLabelDescriptor
ruleDescriptorClass = MyRuleDescriptor
sourceDescriptorClass = MySourceDescriptor
variableFontsDescriptorClass = MyVariableFontDescriptor
valueAxisSubsetDescriptorClass = MyValueAxisSubsetDescriptor
rangeAxisSubsetDescriptorClass = MyRangeAxisSubsetDescriptor
instanceDescriptorClass = MyInstanceDescriptor
myDoc = DesignSpaceDocument(MyDocReader, MyDocWriter)
Helper modules
fontTools.designspaceLib.split
See Scripting > Working with DesignSpace version 5 for more information.
Allows building all the variable fonts of a DesignSpace version 5 by splitting the document into interpolable sub-space, then into each VF.
- fontTools.designspaceLib.split.convert5to4(doc: DesignSpaceDocument) Dict[str, DesignSpaceDocument] [source]
Convert each variable font listed in this document into a standalone format 4 designspace. This can be used to compile all the variable fonts from a format 5 designspace using tools that only know about format 4.
Added in version 5.0.
- fontTools.designspaceLib.split.defaultMakeInstanceFilename(doc: DesignSpaceDocument, instance: InstanceDescriptor, statNames: StatNames) str [source]
Default callable to synthesize an instance filename when makeNames=True, for instances that don’t specify an instance name in the designspace. This part of the name generation can be overriden because it’s not specified by the STAT table.
- fontTools.designspaceLib.split.splitInterpolable(doc: ~fontTools.designspaceLib.DesignSpaceDocument, makeNames: bool = True, expandLocations: bool = True, makeInstanceFilename: ~typing.Callable[[~fontTools.designspaceLib.DesignSpaceDocument, ~fontTools.designspaceLib.InstanceDescriptor, ~fontTools.designspaceLib.statNames.StatNames], str] = <function defaultMakeInstanceFilename>) Iterator[Tuple[Dict[str, float], DesignSpaceDocument]] [source]
Split the given DS5 into several interpolable sub-designspaces. There are as many interpolable sub-spaces as there are combinations of discrete axis values.
- E.g. with axes:
italic (discrete) Upright or Italic
style (discrete) Sans or Serif
weight (continuous) 100 to 900
There are 4 sub-spaces in which the Weight axis should interpolate: (Upright, Sans), (Upright, Serif), (Italic, Sans) and (Italic, Serif).
The sub-designspaces still include the full axis definitions and STAT data, but the rules, sources, variable fonts, instances are trimmed down to only keep what falls within the interpolable sub-space.
- Parameters:
makeNames (-) – Whether to compute the instance family and style names using the STAT data.
expandLocations (-) – Whether to turn all locations into “full” locations, including implicit default axis values where missing.
makeInstanceFilename (-) – Callable to synthesize an instance filename when makeNames=True, for instances that don’t specify an instance name in the designspace. This part of the name generation can be overridden because it’s not specified by the STAT table.
Added in version 5.0.
- fontTools.designspaceLib.split.splitVariableFonts(doc: ~fontTools.designspaceLib.DesignSpaceDocument, makeNames: bool = False, expandLocations: bool = False, makeInstanceFilename: ~typing.Callable[[~fontTools.designspaceLib.DesignSpaceDocument, ~fontTools.designspaceLib.InstanceDescriptor, ~fontTools.designspaceLib.statNames.StatNames], str] = <function defaultMakeInstanceFilename>) Iterator[Tuple[str, DesignSpaceDocument]] [source]
Convert each variable font listed in this document into a standalone designspace. This can be used to compile all the variable fonts from a format 5 designspace using tools that can only deal with 1 VF at a time.
- Parameters:
makeNames (-) – Whether to compute the instance family and style names using the STAT data.
expandLocations (-) – Whether to turn all locations into “full” locations, including implicit default axis values where missing.
makeInstanceFilename (-) – Callable to synthesize an instance filename when makeNames=True, for instances that don’t specify an instance name in the designspace. This part of the name generation can be overridden because it’s not specified by the STAT table.
Added in version 5.0.
fontTools.varLib.stat
Extra methods for DesignSpaceDocument to generate its STAT table data.
- fontTools.varLib.stat.buildVFStatTable(ttFont: TTFont, doc: DesignSpaceDocument, vfName: str) None [source]
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.
Added in version 5.0.
- fontTools.varLib.stat.getStatAxes(doc: DesignSpaceDocument, userRegion: Dict[str, Range | float]) List[Dict] [source]
Return a list of axis dicts suitable for use as the
axes
argument tofontTools.otlLib.builder.buildStatTable()
.Added in version 5.0.
- fontTools.varLib.stat.getStatLocations(doc: DesignSpaceDocument, userRegion: Dict[str, Range | float]) List[Dict] [source]
Return a list of location dicts suitable for use as the
locations
argument tofontTools.otlLib.builder.buildStatTable()
.Added in version 5.0.
fontTools.designspaceLib.statNames
Compute name information for a given location in user-space coordinates using STAT data. This can be used to fill-in automatically the names of an instance:
instance = doc.instances[0]
names = getStatNames(doc, instance.getFullUserLocation(doc))
print(names.styleNames)
- class fontTools.designspaceLib.statNames.StatNames(familyNames: Dict[str, str], styleNames: Dict[str, str], postScriptFontName: str | None, styleMapFamilyNames: Dict[str, str], styleMapStyleName: str | None)[source]
Bases:
object
Name data generated from the STAT table information.
- fontTools.designspaceLib.statNames.getStatNames(doc: DesignSpaceDocument, userLocation: Dict[str, float]) StatNames [source]
Compute the family, style, PostScript names of the given
userLocation
using the document’s STAT information.Also computes localizations.
If not enough STAT data is available for a given name, either its dict of localized names will be empty (family and style names), or the name will be None (PostScript name).
Added in version 5.0.