aboutsummaryrefslogtreecommitdiff
path: root/Lib/fontTools
diff options
context:
space:
mode:
authorSadaf Ebrahimi <sadafebrahimi@google.com>2022-05-13 18:57:12 +0000
committerAutomerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>2022-05-13 18:57:12 +0000
commitdebb1cba85fe0ed630b67e5d4a6d0ec5d7ef0284 (patch)
tree1dff6c1c2a08ce8152e5b964fc0021acdf9696f1 /Lib/fontTools
parent29956f91d34a6e7e114e9e04c4c22296e20b80c8 (diff)
parent312bed341d812d31e893eb9ed2b4bc0dd4da7fff (diff)
downloadfonttools-debb1cba85fe0ed630b67e5d4a6d0ec5d7ef0284.tar.gz
Updating fonttools 4.31.2 to fonttools 4.33.3 am: fc762b5499 am: 4b0e404dd9 am: 2f76e5ea08 am: 312bed341d
Original change: https://android-review.googlesource.com/c/platform/external/fonttools/+/2097373 Change-Id: If8eeb77ee500ed12b637e04bc8cff7c085c139cb Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
Diffstat (limited to 'Lib/fontTools')
-rw-r--r--Lib/fontTools/__init__.py2
-rw-r--r--Lib/fontTools/cffLib/__init__.py9
-rw-r--r--Lib/fontTools/config/__init__.py59
-rw-r--r--Lib/fontTools/designspaceLib/__init__.py1826
-rw-r--r--Lib/fontTools/designspaceLib/split.py424
-rw-r--r--Lib/fontTools/designspaceLib/statNames.py224
-rw-r--r--Lib/fontTools/designspaceLib/types.py122
-rw-r--r--Lib/fontTools/fontBuilder.py13
-rw-r--r--Lib/fontTools/merge/__init__.py5
-rw-r--r--Lib/fontTools/merge/tables.py2
-rw-r--r--Lib/fontTools/misc/configTools.py348
-rw-r--r--Lib/fontTools/misc/psCharStrings.py16
-rw-r--r--Lib/fontTools/misc/testTools.py28
-rw-r--r--Lib/fontTools/otlLib/builder.py21
-rw-r--r--Lib/fontTools/otlLib/optimize/__init__.py39
-rw-r--r--Lib/fontTools/otlLib/optimize/gpos.py65
-rw-r--r--Lib/fontTools/subset/__init__.py22
-rw-r--r--Lib/fontTools/ttLib/tables/O_S_2f_2.py14
-rw-r--r--Lib/fontTools/ttLib/tables/_c_m_a_p.py17
-rw-r--r--Lib/fontTools/ttLib/tables/otBase.py157
-rw-r--r--Lib/fontTools/ttLib/ttFont.py40
-rwxr-xr-xLib/fontTools/ufoLib/glifLib.py4
-rw-r--r--Lib/fontTools/varLib/__init__.py78
-rw-r--r--Lib/fontTools/varLib/instancer/__init__.py7
-rw-r--r--Lib/fontTools/varLib/interpolatable.py125
-rw-r--r--Lib/fontTools/varLib/merger.py15
-rw-r--r--Lib/fontTools/varLib/stat.py142
27 files changed, 3510 insertions, 314 deletions
diff --git a/Lib/fontTools/__init__.py b/Lib/fontTools/__init__.py
index 7fa7b304..9a39ea0f 100644
--- a/Lib/fontTools/__init__.py
+++ b/Lib/fontTools/__init__.py
@@ -3,6 +3,6 @@ from fontTools.misc.loggingTools import configLogger
log = logging.getLogger(__name__)
-version = __version__ = "4.31.2"
+version = __version__ = "4.33.3"
__all__ = ["version", "log", "configLogger"]
diff --git a/Lib/fontTools/cffLib/__init__.py b/Lib/fontTools/cffLib/__init__.py
index 07d0d513..fc82bb27 100644
--- a/Lib/fontTools/cffLib/__init__.py
+++ b/Lib/fontTools/cffLib/__init__.py
@@ -337,7 +337,7 @@ class CFFFontSet(object):
topDict = TopDict(
GlobalSubrs=self.GlobalSubrs,
cff2GetGlyphOrder=cff2GetGlyphOrder)
- self.topDictIndex = TopDictIndex(None, cff2GetGlyphOrder, None)
+ self.topDictIndex = TopDictIndex(None, cff2GetGlyphOrder)
self.topDictIndex.append(topDict)
for element in content:
if isinstance(element, str):
@@ -375,7 +375,7 @@ class CFFFontSet(object):
filled via :meth:`decompile`.)"""
self.major = 2
cff2GetGlyphOrder = self.otFont.getGlyphOrder
- topDictData = TopDictIndex(None, cff2GetGlyphOrder, None)
+ topDictData = TopDictIndex(None, cff2GetGlyphOrder)
topDictData.items = self.topDictIndex.items
self.topDictIndex = topDictData
topDict = topDictData[0]
@@ -1004,11 +1004,6 @@ class VarStoreData(object):
def decompile(self):
if self.file:
- class GlobalState(object):
- def __init__(self, tableType, cachingStats):
- self.tableType = tableType
- self.cachingStats = cachingStats
- globalState = GlobalState(tableType="VarStore", cachingStats={})
# read data in from file. Assume position is correct.
length = readCard16(self.file)
self.data = self.file.read(length)
diff --git a/Lib/fontTools/config/__init__.py b/Lib/fontTools/config/__init__.py
new file mode 100644
index 00000000..f5a62eaf
--- /dev/null
+++ b/Lib/fontTools/config/__init__.py
@@ -0,0 +1,59 @@
+"""
+Define all configuration options that can affect the working of fontTools
+modules. E.g. optimization levels of varLib IUP, otlLib GPOS compression level,
+etc. If this file gets too big, split it into smaller files per-module.
+
+An instance of the Config class can be attached to a TTFont object, so that
+the various modules can access their configuration options from it.
+"""
+from textwrap import dedent
+
+from fontTools.misc.configTools import *
+
+
+class Config(AbstractConfig):
+ options = Options()
+
+
+OPTIONS = Config.options
+
+
+Config.register_option(
+ name="fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL",
+ help=dedent(
+ """\
+ GPOS Lookup type 2 (PairPos) compression level:
+ 0 = do not attempt to compact PairPos lookups;
+ 1 to 8 = create at most 1 to 8 new subtables for each existing
+ subtable, provided that it would yield a 50%% file size saving;
+ 9 = create as many new subtables as needed to yield a file size saving.
+ Default: 0.
+
+ This compaction aims to save file size, by splitting large class
+ kerning subtables (Format 2) that contain many zero values into
+ smaller and denser subtables. It's a trade-off between the overhead
+ of several subtables versus the sparseness of one big subtable.
+
+ See the pull request: https://github.com/fonttools/fonttools/pull/2326
+ """
+ ),
+ default=0,
+ parse=int,
+ validate=lambda v: v in range(10),
+)
+
+Config.register_option(
+ name="fontTools.ttLib.tables.otBase:USE_HARFBUZZ_REPACKER",
+ help=dedent(
+ """\
+ FontTools tries to use the HarfBuzz Repacker to serialize GPOS/GSUB tables
+ if the uharfbuzz python bindings are importable, otherwise falls back to its
+ slower, less efficient serializer. Set to False to always use the latter.
+ Set to True to explicitly request the HarfBuzz Repacker (will raise an
+ error if uharfbuzz cannot be imported).
+ """
+ ),
+ default=None,
+ parse=Option.parse_optional_bool,
+ validate=Option.validate_optional_bool,
+)
diff --git a/Lib/fontTools/designspaceLib/__init__.py b/Lib/fontTools/designspaceLib/__init__.py
index 4b706827..400e960e 100644
--- a/Lib/fontTools/designspaceLib/__init__.py
+++ b/Lib/fontTools/designspaceLib/__init__.py
@@ -1,13 +1,19 @@
-# -*- coding: utf-8 -*-
+from __future__ import annotations
-from fontTools.misc.loggingTools import LogMixin
-from fontTools.misc.textTools import tobytes, tostr
import collections
-from io import BytesIO, StringIO
+import copy
+import itertools
+import math
import os
import posixpath
+from io import BytesIO, StringIO
+from textwrap import indent
+from typing import Any, Dict, List, MutableMapping, Optional, Tuple, Union
+
from fontTools.misc import etree as ET
from fontTools.misc import plistlib
+from fontTools.misc.loggingTools import LogMixin
+from fontTools.misc.textTools import tobytes, tostr
"""
designSpaceDocument
@@ -40,6 +46,7 @@ def posix(path):
def posixpath_property(private_name):
+ """Generate a propery that holds a path always using forward slashes."""
def getter(self):
# Normal getter
return getattr(self, private_name)
@@ -93,16 +100,41 @@ class SimpleDescriptor(AsDictMixin):
except AssertionError:
print("failed attribute", attr, getattr(self, attr), "!=", getattr(other, attr))
+ def __repr__(self):
+ attrs = [f"{a}={repr(getattr(self, a))}," for a in self._attrs]
+ attrs = indent('\n'.join(attrs), ' ')
+ return f"{self.__class__.__name__}(\n{attrs}\n)"
+
class SourceDescriptor(SimpleDescriptor):
- """Simple container for data related to the source"""
+ """Simple container for data related to the source
+
+ .. code:: python
+
+ 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"
_attrs = ['filename', 'path', 'name', 'layerName',
'location', 'copyLib',
'copyGroups', 'copyFeatures',
'muteKerning', 'muteInfo',
'mutedGlyphNames',
- 'familyName', 'styleName']
+ 'familyName', 'styleName', 'localisedFamilyName']
+
+ filename = posixpath_property("_filename")
+ path = posixpath_property("_path")
def __init__(
self,
@@ -112,9 +144,11 @@ class SourceDescriptor(SimpleDescriptor):
font=None,
name=None,
location=None,
+ designLocation=None,
layerName=None,
familyName=None,
styleName=None,
+ localisedFamilyName=None,
copyLib=False,
copyInfo=False,
copyGroups=False,
@@ -124,8 +158,10 @@ class SourceDescriptor(SimpleDescriptor):
mutedGlyphNames=None,
):
self.filename = filename
- """The original path as found in the document."""
+ """string. A relative path to the source file, **as it is in the document**.
+ MutatorMath + VarLib.
+ """
self.path = path
"""The absolute path, calculated from filename."""
@@ -142,27 +178,158 @@ class SourceDescriptor(SimpleDescriptor):
"""
self.name = name
- self.location = location
+ """string. Optional. Unique identifier name for this source.
+
+ MutatorMath + Varlib.
+ """
+
+ self.designLocation = designLocation if designLocation is not None else location or {}
+ """dict. Axis values for this source, in design space coordinates.
+
+ MutatorMath + Varlib.
+
+ This may be only part of the full design location.
+ See :meth:`getFullDesignLocation()`
+
+ .. versionadded:: 5.0
+ """
+
self.layerName = layerName
+ """string. The name of the layer in the source to look for
+ outline data. Default ``None`` which means ``foreground``.
+ """
self.familyName = 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.
+ """
self.styleName = 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.
+ """
+ self.localisedFamilyName = localisedFamilyName or {}
+ """dict. A dictionary of localised family name strings, keyed by
+ language code.
+
+ If present, will be used to build localized names for all instances.
+
+ .. versionadded:: 5.0
+ """
self.copyLib = copyLib
+ """bool. Indicates if the contents of the font.lib need to
+ be copied to the instances.
+
+ MutatorMath.
+
+ .. deprecated:: 5.0
+ """
self.copyInfo = copyInfo
+ """bool. Indicates if the non-interpolating font.info needs
+ to be copied to the instances.
+
+ MutatorMath.
+
+ .. deprecated:: 5.0
+ """
self.copyGroups = copyGroups
+ """bool. Indicates if the groups need to be copied to the
+ instances.
+
+ MutatorMath.
+
+ .. deprecated:: 5.0
+ """
self.copyFeatures = copyFeatures
+ """bool. Indicates if the feature text needs to be
+ copied to the instances.
+
+ MutatorMath.
+
+ .. deprecated:: 5.0
+ """
self.muteKerning = muteKerning
+ """bool. Indicates if the kerning data from this source
+ needs to be muted (i.e. not be part of the calculations).
+
+ MutatorMath only.
+ """
self.muteInfo = muteInfo
+ """bool. Indicated if the interpolating font.info data for
+ this source needs to be muted.
+
+ MutatorMath only.
+ """
self.mutedGlyphNames = mutedGlyphNames or []
+ """list. Glyphnames that need to be muted in the
+ instances.
+
+ MutatorMath only.
+ """
+
+ @property
+ def location(self):
+ """dict. Axis values for this source, in design space coordinates.
+
+ MutatorMath + Varlib.
+
+ .. deprecated:: 5.0
+ Use the more explicit alias for this property :attr:`designLocation`.
+ """
+ return self.designLocation
+
+ @location.setter
+ def location(self, location: Optional[AnisotropicLocationDict]):
+ self.designLocation = location or {}
+
+ def setFamilyName(self, familyName, languageCode="en"):
+ """Setter for :attr:`localisedFamilyName`
+
+ .. versionadded:: 5.0
+ """
+ self.localisedFamilyName[languageCode] = tostr(familyName)
+
+ def getFamilyName(self, languageCode="en"):
+ """Getter for :attr:`localisedFamilyName`
+
+ .. versionadded:: 5.0
+ """
+ return self.localisedFamilyName.get(languageCode)
- path = posixpath_property("_path")
- filename = posixpath_property("_filename")
+
+ def getFullDesignLocation(self, doc: 'DesignSpaceDocument') -> AnisotropicLocationDict:
+ """Get the complete design location of this source, from its
+ :attr:`designLocation` and the document's axis defaults.
+
+ .. versionadded:: 5.0
+ """
+ result: AnisotropicLocationDict = {}
+ for axis in doc.axes:
+ if axis.name in self.designLocation:
+ result[axis.name] = self.designLocation[axis.name]
+ else:
+ result[axis.name] = axis.map_forward(axis.default)
+ return result
class RuleDescriptor(SimpleDescriptor):
- """Represents the rule descriptor element
+ """Represents the rule descriptor element: a set of glyph substitutions to
+ trigger conditionally in some parts of the designspace.
- .. code-block:: xml
+ .. code:: python
+
+ 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"))
+
+ .. code:: xml
<!-- optional: list of substitution rules -->
<rules>
@@ -181,21 +348,36 @@ class RuleDescriptor(SimpleDescriptor):
def __init__(self, *, name=None, conditionSets=None, subs=None):
self.name = name
+ """string. Unique name for this rule. Can be used to reference this rule data."""
# list of lists of dict(name='aaaa', minimum=0, maximum=1000)
self.conditionSets = conditionSets or []
+ """a list of conditionsets.
+
+ - Each conditionset is a list of conditions.
+ - Each condition is a dict with ``name``, ``minimum`` and ``maximum`` keys.
+ """
# list of substitutions stored as tuples of glyphnames ("a", "a.alt")
self.subs = subs or []
+ """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 <https://docs.microsoft.com/en-us/typography/opentype/spec/features_pt#-tag-rvrn>`_.
+ See ref:`rules-element` § Attributes.
+ """
def evaluateRule(rule, location):
- """ Return True if any of the rule's conditionsets matches the given location."""
+ """Return True if any of the rule's conditionsets matches the given location."""
return any(evaluateConditions(c, location) for c in rule.conditionSets)
def evaluateConditions(conditions, location):
- """ Return True if all the conditions matches the given location.
- If a condition has no minimum, check for < maximum.
- If a condition has no maximum, check for > minimum.
+ """Return True if all the conditions matches the given location.
+
+ - If a condition has no minimum, check for < maximum.
+ - If a condition has no maximum, check for > minimum.
"""
for cd in conditions:
value = location[cd['name']]
@@ -211,8 +393,11 @@ def evaluateConditions(conditions, location):
def processRules(rules, location, glyphNames):
- """ Apply these rules at this location to these glyphnames
- - rule order matters
+ """Apply these rules at this location to these glyphnames.
+
+ Return a new list of glyphNames with substitutions applied.
+
+ - rule order matters
"""
newNames = []
for rule in rules:
@@ -232,22 +417,54 @@ def processRules(rules, location, glyphNames):
return glyphNames
+AnisotropicLocationDict = Dict[str, Union[float, Tuple[float, float]]]
+SimpleLocationDict = Dict[str, float]
+
+
class InstanceDescriptor(SimpleDescriptor):
- """Simple container for data related to the instance"""
+ """Simple container for data related to the instance
+
+
+ .. code:: python
+
+ 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"
_defaultLanguageCode = "en"
- _attrs = ['path',
+ _attrs = ['filename',
+ 'path',
'name',
- 'location',
+ 'locationLabel',
+ 'designLocation',
+ 'userLocation',
'familyName',
'styleName',
'postScriptFontName',
'styleMapFamilyName',
'styleMapStyleName',
+ 'localisedFamilyName',
+ 'localisedStyleName',
+ 'localisedStyleMapFamilyName',
+ 'localisedStyleMapStyleName',
+ 'glyphs',
'kerning',
'info',
'lib']
+ filename = posixpath_property("_filename")
+ path = posixpath_property("_path")
+
def __init__(
self,
*,
@@ -256,6 +473,9 @@ class InstanceDescriptor(SimpleDescriptor):
font=None,
name=None,
location=None,
+ locationLabel=None,
+ designLocation=None,
+ userLocation=None,
familyName=None,
styleName=None,
postScriptFontName=None,
@@ -270,34 +490,148 @@ class InstanceDescriptor(SimpleDescriptor):
info=True,
lib=None,
):
- # the original path as found in the document
self.filename = filename
- # the absolute path, calculated from filename
+ """string. Relative path to the instance file, **as it is
+ in the document**. The file may or may not exist.
+
+ MutatorMath + VarLib.
+ """
self.path = path
- # Same as in SourceDescriptor.
+ """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.
+ """
self.font = font
+ """Same as :attr:`SourceDescriptor.font`
+
+ .. seealso:: :attr:`SourceDescriptor.font`
+ """
self.name = name
- self.location = location
+ """string. Unique identifier name of the instance, used to
+ identify it if it needs to be referenced from elsewhere in the
+ document.
+ """
+ self.locationLabel = locationLabel
+ """Name of a :class:`LocationLabelDescriptor`. If
+ provided, the instance should have the same location as the
+ LocationLabel.
+
+ .. seealso::
+ :meth:`getFullDesignLocation`
+ :meth:`getFullUserLocation`
+
+ .. versionadded:: 5.0
+ """
+ self.designLocation: AnisotropicLocationDict = designLocation if designLocation is not None else (location or {})
+ """dict. Axis values for this instance, in design space coordinates.
+
+ MutatorMath + Varlib.
+
+ .. seealso:: This may be only part of the full location. See:
+ :meth:`getFullDesignLocation`
+ :meth:`getFullUserLocation`
+
+ .. versionadded:: 5.0
+ """
+ self.userLocation: SimpleLocationDict = userLocation or {}
+ """dict. Axis values for this instance, in user space coordinates.
+
+ MutatorMath + Varlib.
+
+ .. seealso:: This may be only part of the full location. See:
+ :meth:`getFullDesignLocation`
+ :meth:`getFullUserLocation`
+
+ .. versionadded:: 5.0
+ """
self.familyName = familyName
+ """string. Family name of this instance.
+
+ MutatorMath + Varlib.
+ """
self.styleName = styleName
+ """string. Style name of this instance.
+
+ MutatorMath + Varlib.
+ """
self.postScriptFontName = postScriptFontName
+ """string. Postscript fontname for this instance.
+
+ MutatorMath + Varlib.
+ """
self.styleMapFamilyName = styleMapFamilyName
+ """string. StyleMap familyname for this instance.
+
+ MutatorMath + Varlib.
+ """
self.styleMapStyleName = styleMapStyleName
+ """string. StyleMap stylename for this instance.
+
+ MutatorMath + Varlib.
+ """
self.localisedFamilyName = localisedFamilyName or {}
+ """dict. A dictionary of localised family name
+ strings, keyed by language code.
+ """
self.localisedStyleName = localisedStyleName or {}
+ """dict. A dictionary of localised stylename
+ strings, keyed by language code.
+ """
self.localisedStyleMapFamilyName = localisedStyleMapFamilyName or {}
+ """A dictionary of localised style map
+ familyname strings, keyed by language code.
+ """
self.localisedStyleMapStyleName = localisedStyleMapStyleName or {}
+ """A dictionary of localised style map
+ stylename strings, keyed by language code.
+ """
self.glyphs = glyphs or {}
+ """dict for special master definitions for glyphs. If glyphs
+ need special masters (to record the results of executed rules for
+ example).
+
+ MutatorMath.
+
+ .. deprecated:: 5.0
+ Use rules or sparse sources instead.
+ """
self.kerning = kerning
+ """ bool. Indicates if this instance needs its kerning
+ calculated.
+
+ MutatorMath.
+
+ .. deprecated:: 5.0
+ """
self.info = info
+ """bool. Indicated if this instance needs the interpolating
+ font.info calculated.
+
+ .. deprecated:: 5.0
+ """
self.lib = lib or {}
"""Custom data associated with this instance."""
- path = posixpath_property("_path")
- filename = posixpath_property("_filename")
+ @property
+ def location(self):
+ """dict. Axis values for this instance.
+
+ MutatorMath + Varlib.
+
+ .. deprecated:: 5.0
+ Use the more explicit alias for this property :attr:`designLocation`.
+ """
+ return self.designLocation
+
+ @location.setter
+ def location(self, location: Optional[AnisotropicLocationDict]):
+ self.designLocation = location or {}
def setStyleName(self, styleName, languageCode="en"):
+ """These methods give easier access to the localised names."""
self.localisedStyleName[languageCode] = tostr(styleName)
def getStyleName(self, languageCode="en"):
@@ -321,6 +655,106 @@ class InstanceDescriptor(SimpleDescriptor):
def getStyleMapFamilyName(self, languageCode="en"):
return self.localisedStyleMapFamilyName.get(languageCode)
+ def clearLocation(self, axisName: Optional[str] = None):
+ """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.
+
+ .. code:: python
+
+ 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:
+
+ .. code:: python
+
+ instance.clearLocation('Weight')
+ instance.designLocation['Weight'] = (34, 36.5)
+
+ Args:
+ axisName: if provided, only clear the location for that axis.
+
+ .. versionadded:: 5.0
+ """
+ self.locationLabel = None
+ if axisName is None:
+ self.designLocation = {}
+ self.userLocation = {}
+ else:
+ if self.designLocation is None:
+ self.designLocation = {}
+ if axisName in self.designLocation:
+ del self.designLocation[axisName]
+ if self.userLocation is None:
+ self.userLocation = {}
+ if axisName in self.userLocation:
+ del self.userLocation[axisName]
+
+ def getLocationLabelDescriptor(self, doc: 'DesignSpaceDocument') -> Optional[LocationLabelDescriptor]:
+ """Get the :class:`LocationLabelDescriptor` instance that matches
+ this instances's :attr:`locationLabel`.
+
+ Raises if the named label can't be found.
+
+ .. versionadded:: 5.0
+ """
+ if self.locationLabel is None:
+ return None
+ label = doc.getLocationLabel(self.locationLabel)
+ if label is None:
+ raise DesignSpaceDocumentError(
+ 'InstanceDescriptor.getLocationLabelDescriptor(): '
+ f'unknown location label `{self.locationLabel}` in instance `{self.name}`.'
+ )
+ return label
+
+ def getFullDesignLocation(self, doc: 'DesignSpaceDocument') -> AnisotropicLocationDict:
+ """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.
+
+ .. versionadded:: 5.0
+ """
+ label = self.getLocationLabelDescriptor(doc)
+ if label is not None:
+ return doc.map_forward(label.userLocation) # type: ignore
+ result: AnisotropicLocationDict = {}
+ for axis in doc.axes:
+ if axis.name in self.designLocation:
+ result[axis.name] = self.designLocation[axis.name]
+ elif axis.name in self.userLocation:
+ result[axis.name] = axis.map_forward(self.userLocation[axis.name])
+ else:
+ result[axis.name] = axis.map_forward(axis.default)
+ return result
+
+ def getFullUserLocation(self, doc: 'DesignSpaceDocument') -> SimpleLocationDict:
+ """Get the complete user location for this instance.
+
+ .. seealso:: :meth:`getFullDesignLocation`
+
+ .. versionadded:: 5.0
+ """
+ return doc.map_backward(self.getFullDesignLocation(doc))
+
def tagForAxisName(name):
# try to find or make a tag name for this axis name
@@ -340,12 +774,8 @@ def tagForAxisName(name):
return tag, dict(en=name)
-class AxisDescriptor(SimpleDescriptor):
- """ Simple container for the axis data
- Add more localisations?
- """
+class AbstractAxisDescriptor(SimpleDescriptor):
flavor = "axis"
- _attrs = ['tag', 'name', 'maximum', 'minimum', 'default', 'map']
def __init__(
self,
@@ -353,23 +783,122 @@ class AxisDescriptor(SimpleDescriptor):
tag=None,
name=None,
labelNames=None,
- minimum=None,
- default=None,
- maximum=None,
hidden=False,
map=None,
+ axisOrdering=None,
+ axisLabels=None,
):
# opentype tag for this axis
self.tag = tag
+ """string. Four letter tag for this axis. Some might be
+ registered at the `OpenType
+ specification <https://www.microsoft.com/typography/otspec/fvar.htm#VAT>`__.
+ Privately-defined axis tags must begin with an uppercase letter and
+ use only uppercase letters or digits.
+ """
# name of the axis used in locations
self.name = name
+ """string. Name of the axis as it is used in the location dicts.
+
+ MutatorMath + Varlib.
+ """
# names for UI purposes, if this is not a standard axis,
self.labelNames = labelNames or {}
+ """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.
+ """
+ self.hidden = hidden
+ """bool. Whether this axis should be hidden in user interfaces.
+ """
+ self.map = map or []
+ """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.
+ """
+ self.axisOrdering = axisOrdering
+ """STAT table field ``axisOrdering``.
+
+ See: `OTSpec STAT Axis Record <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-records>`_
+
+ .. versionadded:: 5.0
+ """
+ self.axisLabels: List[AxisLabelDescriptor] = axisLabels or []
+ """STAT table entries for Axis Value Tables format 1, 2, 3.
+
+ See: `OTSpec STAT Axis Value Tables <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-value-tables>`_
+
+ .. versionadded:: 5.0
+ """
+
+
+class AxisDescriptor(AbstractAxisDescriptor):
+ """ Simple container for the axis data.
+
+ Add more localisations?
+
+ .. code:: python
+
+ 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)
+ """
+ _attrs = ['tag', 'name', 'maximum', 'minimum', 'default', 'map', 'axisOrdering', 'axisLabels']
+
+ def __init__(
+ self,
+ *,
+ tag=None,
+ name=None,
+ labelNames=None,
+ minimum=None,
+ default=None,
+ maximum=None,
+ hidden=False,
+ map=None,
+ axisOrdering=None,
+ axisLabels=None,
+ ):
+ super().__init__(
+ tag=tag,
+ name=name,
+ labelNames=labelNames,
+ hidden=hidden,
+ map=map,
+ axisOrdering=axisOrdering,
+ axisLabels=axisLabels,
+ )
self.minimum = minimum
+ """number. The minimum value for this axis in user space.
+
+ MutatorMath + Varlib.
+ """
self.maximum = maximum
+ """number. The maximum value for this axis in user space.
+
+ MutatorMath + Varlib.
+ """
self.default = default
- self.hidden = hidden
- self.map = map or []
+ """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.
+ """
def serialize(self):
# output to a dict, used in testing
@@ -382,9 +911,12 @@ class AxisDescriptor(SimpleDescriptor):
default=self.default,
hidden=self.hidden,
map=self.map,
+ axisOrdering=self.axisOrdering,
+ axisLabels=self.axisLabels,
)
def map_forward(self, v):
+ """Maps value from axis mapping's input (user) to output (design)."""
from fontTools.varLib.models import piecewiseLinearMap
if not self.map:
@@ -392,18 +924,349 @@ class AxisDescriptor(SimpleDescriptor):
return piecewiseLinearMap(v, {k: v for k, v in self.map})
def map_backward(self, v):
+ """Maps value from axis mapping's output (design) to input (user)."""
from fontTools.varLib.models import piecewiseLinearMap
+ if isinstance(v, tuple):
+ v = v[0]
if not self.map:
return v
return piecewiseLinearMap(v, {v: k for k, v in self.map})
+class DiscreteAxisDescriptor(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`` and ``maximum``,
+ while a discrete axis has a list of ``values``.
+
+ 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.
+
+ .. code:: python
+
+ a2 = DiscreteAxisDescriptor()
+ a2.values = [0, 1]
+ 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)
+
+ .. versionadded:: 5.0
+ """
+
+ flavor = "axis"
+ _attrs = ('tag', 'name', 'values', 'default', 'map', 'axisOrdering', 'axisLabels')
+
+ def __init__(
+ self,
+ *,
+ tag=None,
+ name=None,
+ labelNames=None,
+ values=None,
+ default=None,
+ hidden=False,
+ map=None,
+ axisOrdering=None,
+ axisLabels=None,
+ ):
+ super().__init__(
+ tag=tag,
+ name=name,
+ labelNames=labelNames,
+ hidden=hidden,
+ map=map,
+ axisOrdering=axisOrdering,
+ axisLabels=axisLabels,
+ )
+ self.default: float = default
+ """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.
+ """
+ self.values: List[float] = values or []
+ """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.
+ """
+
+ def map_forward(self, value):
+ """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.
+ """
+ return next((v for k, v in self.map if k == value), value)
+
+ def map_backward(self, value):
+ """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.
+ """
+ if isinstance(value, tuple):
+ value = value[0]
+ return next((k for k, v in self.map if v == value), value)
+
+
+class AxisLabelDescriptor(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 <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-value-table-format-1>`_
+
+ The STAT format of the Axis value depends on which field are filled-in,
+ see :meth:`getFormat`
+
+ .. versionadded:: 5.0
+ """
+
+ flavor = "label"
+ _attrs = ('userMinimum', 'userValue', 'userMaximum', 'name', 'elidable', 'olderSibling', 'linkedUserValue', 'labelNames')
+
+ def __init__(
+ self,
+ *,
+ name,
+ userValue,
+ userMinimum=None,
+ userMaximum=None,
+ elidable=False,
+ olderSibling=False,
+ linkedUserValue=None,
+ labelNames=None,
+ ):
+ self.userMinimum: Optional[float] = userMinimum
+ """STAT field ``rangeMinValue`` (format 2)."""
+ self.userValue: float = userValue
+ """STAT field ``value`` (format 1, 3) or ``nominalValue`` (format 2)."""
+ self.userMaximum: Optional[float] = userMaximum
+ """STAT field ``rangeMaxValue`` (format 2)."""
+ self.name: str = name
+ """Label for this axis location, STAT field ``valueNameID``."""
+ self.elidable: bool = elidable
+ """STAT flag ``ELIDABLE_AXIS_VALUE_NAME``.
+
+ See: `OTSpec STAT Flags <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#flags>`_
+ """
+ self.olderSibling: bool = olderSibling
+ """STAT flag ``OLDER_SIBLING_FONT_ATTRIBUTE``.
+
+ See: `OTSpec STAT Flags <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#flags>`_
+ """
+ self.linkedUserValue: Optional[float] = linkedUserValue
+ """STAT field ``linkedValue`` (format 3)."""
+ self.labelNames: MutableMapping[str, str] = labelNames or {}
+ """User-facing translations of this location's label. Keyed by
+ ``xml:lang`` code.
+ """
+
+ def getFormat(self) -> int:
+ """Determine which format of STAT Axis value to use to encode this label.
+
+ =========== ========= =========== =========== ===============
+ STAT Format userValue userMinimum userMaximum linkedUserValue
+ =========== ========= =========== =========== ===============
+ 1 ✅ ❌ ❌ ❌
+ 2 ✅ ✅ ✅ ❌
+ 3 ✅ ❌ ❌ ✅
+ =========== ========= =========== =========== ===============
+ """
+ if self.linkedUserValue is not None:
+ return 3
+ if self.userMinimum is not None or self.userMaximum is not None:
+ return 2
+ return 1
+
+ @property
+ def defaultName(self) -> str:
+ """Return the English name from :attr:`labelNames` or the :attr:`name`."""
+ return self.labelNames.get("en") or self.name
+
+
+class LocationLabelDescriptor(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 <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-value-table-format-4>`_
+
+ .. versionadded:: 5.0
+ """
+
+ flavor = "label"
+ _attrs = ('name', 'elidable', 'olderSibling', 'userLocation', 'labelNames')
+
+ def __init__(
+ self,
+ *,
+ name,
+ userLocation,
+ elidable=False,
+ olderSibling=False,
+ labelNames=None,
+ ):
+ self.name: str = name
+ """Label for this named location, STAT field ``valueNameID``."""
+ self.userLocation: SimpleLocationDict = userLocation or {}
+ """Location in user coordinates along each axis.
+
+ If an axis is not mentioned, it is assumed to be at its default location.
+
+ .. seealso:: This may be only part of the full location. See:
+ :meth:`getFullUserLocation`
+ """
+ self.elidable: bool = elidable
+ """STAT flag ``ELIDABLE_AXIS_VALUE_NAME``.
+
+ See: `OTSpec STAT Flags <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#flags>`_
+ """
+ self.olderSibling: bool = olderSibling
+ """STAT flag ``OLDER_SIBLING_FONT_ATTRIBUTE``.
+
+ See: `OTSpec STAT Flags <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#flags>`_
+ """
+ self.labelNames: Dict[str, str] = labelNames or {}
+ """User-facing translations of this location's label. Keyed by
+ xml:lang code.
+ """
+
+ @property
+ def defaultName(self) -> str:
+ """Return the English name from :attr:`labelNames` or the :attr:`name`."""
+ return self.labelNames.get("en") or self.name
+
+ def getFullUserLocation(self, doc: 'DesignSpaceDocument') -> SimpleLocationDict:
+ """Get the complete user location of this label, by combining data
+ from the explicit user location and default axis values.
+
+ .. versionadded:: 5.0
+ """
+ return {
+ axis.name: self.userLocation.get(axis.name, axis.default)
+ for axis in doc.axes
+ }
+
+
+class VariableFontDescriptor(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.
+
+ .. versionadded:: 5.0
+ """
+
+ flavor = "variable-font"
+ _attrs = ('filename', 'axisSubsets', 'lib')
+
+ filename = posixpath_property("_filename")
+
+ def __init__(self, *, name, filename=None, axisSubsets=None, lib=None):
+ self.name: str = name
+ """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.
+ """
+ self.filename: str = 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 :attr:`name` will be used as a basename for the file.
+ """
+ self.axisSubsets: List[Union[RangeAxisSubsetDescriptor, ValueAxisSubsetDescriptor]] = axisSubsets or []
+ """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 :class:`ValueAxisSubsetDescriptor`).
+ """
+ self.lib: MutableMapping[str, Any] = lib or {}
+ """Custom data associated with this variable font."""
+
+
+class RangeAxisSubsetDescriptor(SimpleDescriptor):
+ """Subset of a continuous axis to include in a variable font.
+
+ .. versionadded:: 5.0
+ """
+ flavor = "axis-subset"
+ _attrs = ('name', 'userMinimum', 'userDefault', 'userMaximum')
+
+ def __init__(self, *, name, userMinimum=-math.inf, userDefault=None, userMaximum=math.inf):
+ self.name: str = name
+ """Name of the :class:`AxisDescriptor` to subset."""
+ self.userMinimum: float = userMinimum
+ """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``)
+ """
+ self.userDefault: Optional[float] = userDefault
+ """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``)
+ """
+ self.userMaximum: float = userMaximum
+ """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``)
+ """
+
+
+class ValueAxisSubsetDescriptor(SimpleDescriptor):
+ """Single value of a discrete or continuous axis to use in a variable font.
+
+ .. versionadded:: 5.0
+ """
+ flavor = "axis-subset"
+ _attrs = ('name', 'userValue')
+
+ def __init__(self, *, name, userValue):
+ self.name: str = name
+ """Name of the :class:`AxisDescriptor` or :class:`DiscreteAxisDescriptor`
+ to "snapshot" or "freeze".
+ """
+ self.userValue: float = userValue
+ """Value in user coordinates at which to freeze the given axis."""
+
+
class BaseDocWriter(object):
_whiteSpace = " "
- ruleDescriptorClass = RuleDescriptor
axisDescriptorClass = AxisDescriptor
+ discreteAxisDescriptorClass = DiscreteAxisDescriptor
+ axisLabelDescriptorClass = AxisLabelDescriptor
+ locationLabelDescriptorClass = LocationLabelDescriptor
+ ruleDescriptorClass = RuleDescriptor
sourceDescriptorClass = SourceDescriptor
+ variableFontDescriptorClass = VariableFontDescriptor
+ valueAxisSubsetDescriptorClass = ValueAxisSubsetDescriptor
+ rangeAxisSubsetDescriptorClass = RangeAxisSubsetDescriptor
instanceDescriptorClass = InstanceDescriptor
@classmethod
@@ -422,21 +1285,29 @@ class BaseDocWriter(object):
def getRuleDescriptor(cls):
return cls.ruleDescriptorClass()
- def __init__(self, documentPath, documentObject):
+ def __init__(self, documentPath, documentObject: DesignSpaceDocument):
self.path = documentPath
self.documentObject = documentObject
- self.documentVersion = "4.1"
+ self.effectiveFormatTuple = self._getEffectiveFormatTuple()
self.root = ET.Element("designspace")
- self.root.attrib['format'] = self.documentVersion
- self._axes = [] # for use by the writer only
- self._rules = [] # for use by the writer only
def write(self, pretty=True, encoding="UTF-8", xml_declaration=True):
- if self.documentObject.axes:
- self.root.append(ET.Element("axes"))
+ self.root.attrib['format'] = ".".join(str(i) for i in self.effectiveFormatTuple)
+
+ if self.documentObject.axes or self.documentObject.elidedFallbackName is not None:
+ axesElement = ET.Element("axes")
+ if self.documentObject.elidedFallbackName is not None:
+ axesElement.attrib['elidedfallbackname'] = self.documentObject.elidedFallbackName
+ self.root.append(axesElement)
for axisObject in self.documentObject.axes:
self._addAxis(axisObject)
+ if self.documentObject.locationLabels:
+ labelsElement = ET.Element("labels")
+ for labelObject in self.documentObject.locationLabels:
+ self._addLocationLabel(labelsElement, labelObject)
+ self.root.append(labelsElement)
+
if self.documentObject.rules:
if getattr(self.documentObject, "rulesProcessingLast", False):
attributes = {"processing": "last"}
@@ -451,13 +1322,19 @@ class BaseDocWriter(object):
for sourceObject in self.documentObject.sources:
self._addSource(sourceObject)
+ if self.documentObject.variableFonts:
+ variableFontsElement = ET.Element("variable-fonts")
+ for variableFont in self.documentObject.variableFonts:
+ self._addVariableFont(variableFontsElement, variableFont)
+ self.root.append(variableFontsElement)
+
if self.documentObject.instances:
self.root.append(ET.Element("instances"))
for instanceObject in self.documentObject.instances:
self._addInstance(instanceObject)
if self.documentObject.lib:
- self._addLib(self.documentObject.lib)
+ self._addLib(self.root, self.documentObject.lib, 2)
tree = ET.ElementTree(self.root)
tree.write(
@@ -468,6 +1345,34 @@ class BaseDocWriter(object):
pretty_print=pretty,
)
+ def _getEffectiveFormatTuple(self):
+ """Try to use the version specified in the document, or a sufficiently
+ recent version to be able to encode what the document contains.
+ """
+ minVersion = self.documentObject.formatTuple
+ if (
+ any(
+ isinstance(axis, DiscreteAxisDescriptor) or
+ axis.axisOrdering is not None or
+ axis.axisLabels
+ for axis in self.documentObject.axes
+ ) or
+ self.documentObject.locationLabels or
+ any(
+ source.localisedFamilyName
+ for source in self.documentObject.sources
+ ) or
+ self.documentObject.variableFonts or
+ any(
+ instance.locationLabel or
+ instance.userLocation
+ for instance in self.documentObject.instances
+ )
+ ):
+ if minVersion < (5, 0):
+ minVersion = (5, 0)
+ return minVersion
+
def _makeLocationElement(self, locationObject, name=None):
""" Convert Location dict to a locationElement."""
locElement = ET.Element("location")
@@ -492,11 +1397,10 @@ class BaseDocWriter(object):
def intOrFloat(self, num):
if int(num) == num:
return "%d" % num
- return "%f" % num
+ return ("%f" % num).rstrip('0').rstrip('.')
def _addRule(self, ruleObject):
# if none of the conditions have minimum or maximum values, do not add the rule.
- self._rules.append(ruleObject)
ruleElement = ET.Element('rule')
if ruleObject.name is not None:
ruleElement.attrib['name'] = ruleObject.name
@@ -524,32 +1428,102 @@ class BaseDocWriter(object):
self.root.findall('.rules')[0].append(ruleElement)
def _addAxis(self, axisObject):
- self._axes.append(axisObject)
axisElement = ET.Element('axis')
axisElement.attrib['tag'] = axisObject.tag
axisElement.attrib['name'] = axisObject.name
- axisElement.attrib['minimum'] = self.intOrFloat(axisObject.minimum)
- axisElement.attrib['maximum'] = self.intOrFloat(axisObject.maximum)
- axisElement.attrib['default'] = self.intOrFloat(axisObject.default)
- if axisObject.hidden:
- axisElement.attrib['hidden'] = "1"
- for languageCode, labelName in sorted(axisObject.labelNames.items()):
- languageElement = ET.Element('labelname')
- languageElement.attrib[XML_LANG] = languageCode
- languageElement.text = labelName
- axisElement.append(languageElement)
+ self._addLabelNames(axisElement, axisObject.labelNames)
if axisObject.map:
for inputValue, outputValue in axisObject.map:
mapElement = ET.Element('map')
mapElement.attrib['input'] = self.intOrFloat(inputValue)
mapElement.attrib['output'] = self.intOrFloat(outputValue)
axisElement.append(mapElement)
+ if axisObject.axisOrdering or axisObject.axisLabels:
+ labelsElement = ET.Element('labels')
+ if axisObject.axisOrdering is not None:
+ labelsElement.attrib['ordering'] = str(axisObject.axisOrdering)
+ for label in axisObject.axisLabels:
+ self._addAxisLabel(labelsElement, label)
+ axisElement.append(labelsElement)
+ if isinstance(axisObject, AxisDescriptor):
+ axisElement.attrib['minimum'] = self.intOrFloat(axisObject.minimum)
+ axisElement.attrib['maximum'] = self.intOrFloat(axisObject.maximum)
+ elif isinstance(axisObject, DiscreteAxisDescriptor):
+ axisElement.attrib['values'] = " ".join(self.intOrFloat(v) for v in axisObject.values)
+ axisElement.attrib['default'] = self.intOrFloat(axisObject.default)
+ if axisObject.hidden:
+ axisElement.attrib['hidden'] = "1"
self.root.findall('.axes')[0].append(axisElement)
+ def _addAxisLabel(self, axisElement: ET.Element, label: AxisLabelDescriptor) -> None:
+ labelElement = ET.Element('label')
+ labelElement.attrib['uservalue'] = self.intOrFloat(label.userValue)
+ if label.userMinimum is not None:
+ labelElement.attrib['userminimum'] = self.intOrFloat(label.userMinimum)
+ if label.userMaximum is not None:
+ labelElement.attrib['usermaximum'] = self.intOrFloat(label.userMaximum)
+ labelElement.attrib['name'] = label.name
+ if label.elidable:
+ labelElement.attrib['elidable'] = "true"
+ if label.olderSibling:
+ labelElement.attrib['oldersibling'] = "true"
+ if label.linkedUserValue is not None:
+ labelElement.attrib['linkeduservalue'] = self.intOrFloat(label.linkedUserValue)
+ self._addLabelNames(labelElement, label.labelNames)
+ axisElement.append(labelElement)
+
+ def _addLabelNames(self, parentElement, labelNames):
+ for languageCode, labelName in sorted(labelNames.items()):
+ languageElement = ET.Element('labelname')
+ languageElement.attrib[XML_LANG] = languageCode
+ languageElement.text = labelName
+ parentElement.append(languageElement)
+
+ def _addLocationLabel(self, parentElement: ET.Element, label: LocationLabelDescriptor) -> None:
+ labelElement = ET.Element('label')
+ labelElement.attrib['name'] = label.name
+ if label.elidable:
+ labelElement.attrib['elidable'] = "true"
+ if label.olderSibling:
+ labelElement.attrib['oldersibling'] = "true"
+ self._addLabelNames(labelElement, label.labelNames)
+ self._addLocationElement(labelElement, userLocation=label.userLocation)
+ parentElement.append(labelElement)
+
+ def _addLocationElement(
+ self,
+ parentElement,
+ *,
+ designLocation: AnisotropicLocationDict = None,
+ userLocation: SimpleLocationDict = None
+ ):
+ locElement = ET.Element("location")
+ for axis in self.documentObject.axes:
+ if designLocation is not None and axis.name in designLocation:
+ dimElement = ET.Element('dimension')
+ dimElement.attrib['name'] = axis.name
+ value = designLocation[axis.name]
+ if isinstance(value, tuple):
+ dimElement.attrib['xvalue'] = self.intOrFloat(value[0])
+ dimElement.attrib['yvalue'] = self.intOrFloat(value[1])
+ else:
+ dimElement.attrib['xvalue'] = self.intOrFloat(value)
+ locElement.append(dimElement)
+ elif userLocation is not None and axis.name in userLocation:
+ dimElement = ET.Element('dimension')
+ dimElement.attrib['name'] = axis.name
+ value = userLocation[axis.name]
+ dimElement.attrib['uservalue'] = self.intOrFloat(value)
+ locElement.append(dimElement)
+ if len(locElement) > 0:
+ parentElement.append(locElement)
+
def _addInstance(self, instanceObject):
instanceElement = ET.Element('instance')
if instanceObject.name is not None:
instanceElement.attrib['name'] = instanceObject.name
+ if instanceObject.locationLabel is not None:
+ instanceElement.attrib['location'] = instanceObject.locationLabel
if instanceObject.familyName is not None:
instanceElement.attrib['familyname'] = instanceObject.familyName
if instanceObject.styleName is not None:
@@ -596,9 +1570,19 @@ class BaseDocWriter(object):
localisedStyleMapFamilyNameElement.text = instanceObject.getStyleMapFamilyName(code)
instanceElement.append(localisedStyleMapFamilyNameElement)
- if instanceObject.location is not None:
- locationElement, instanceObject.location = self._makeLocationElement(instanceObject.location)
- instanceElement.append(locationElement)
+ if self.effectiveFormatTuple >= (5, 0):
+ if instanceObject.locationLabel is None:
+ self._addLocationElement(
+ instanceElement,
+ designLocation=instanceObject.designLocation,
+ userLocation=instanceObject.userLocation
+ )
+ else:
+ # Pre-version 5.0 code was validating and filling in the location
+ # dict while writing it out, as preserved below.
+ if instanceObject.location is not None:
+ locationElement, instanceObject.location = self._makeLocationElement(instanceObject.location)
+ instanceElement.append(locationElement)
if instanceObject.filename is not None:
instanceElement.attrib['filename'] = instanceObject.filename
if instanceObject.postScriptFontName is not None:
@@ -607,24 +1591,23 @@ class BaseDocWriter(object):
instanceElement.attrib['stylemapfamilyname'] = instanceObject.styleMapFamilyName
if instanceObject.styleMapStyleName is not None:
instanceElement.attrib['stylemapstylename'] = instanceObject.styleMapStyleName
- if instanceObject.glyphs:
- if instanceElement.findall('.glyphs') == []:
- glyphsElement = ET.Element('glyphs')
- instanceElement.append(glyphsElement)
- glyphsElement = instanceElement.findall('.glyphs')[0]
- for glyphName, data in sorted(instanceObject.glyphs.items()):
- glyphElement = self._writeGlyphElement(instanceElement, instanceObject, glyphName, data)
- glyphsElement.append(glyphElement)
- if instanceObject.kerning:
- kerningElement = ET.Element('kerning')
- instanceElement.append(kerningElement)
- if instanceObject.info:
- infoElement = ET.Element('info')
- instanceElement.append(infoElement)
- if instanceObject.lib:
- libElement = ET.Element('lib')
- libElement.append(plistlib.totree(instanceObject.lib, indent_level=4))
- instanceElement.append(libElement)
+ if self.effectiveFormatTuple < (5, 0):
+ # Deprecated members as of version 5.0
+ if instanceObject.glyphs:
+ if instanceElement.findall('.glyphs') == []:
+ glyphsElement = ET.Element('glyphs')
+ instanceElement.append(glyphsElement)
+ glyphsElement = instanceElement.findall('.glyphs')[0]
+ for glyphName, data in sorted(instanceObject.glyphs.items()):
+ glyphElement = self._writeGlyphElement(instanceElement, instanceObject, glyphName, data)
+ glyphsElement.append(glyphElement)
+ if instanceObject.kerning:
+ kerningElement = ET.Element('kerning')
+ instanceElement.append(kerningElement)
+ if instanceObject.info:
+ infoElement = ET.Element('info')
+ instanceElement.append(infoElement)
+ self._addLib(instanceElement, instanceObject.lib, 4)
self.root.findall('.instances')[0].append(instanceElement)
def _addSource(self, sourceObject):
@@ -641,6 +1624,16 @@ class BaseDocWriter(object):
sourceElement.attrib['stylename'] = sourceObject.styleName
if sourceObject.layerName is not None:
sourceElement.attrib['layer'] = sourceObject.layerName
+ if sourceObject.localisedFamilyName:
+ languageCodes = list(sourceObject.localisedFamilyName.keys())
+ languageCodes.sort()
+ for code in languageCodes:
+ if code == "en":
+ continue # already stored in the element attribute
+ localisedFamilyNameElement = ET.Element('familyname')
+ localisedFamilyNameElement.attrib[XML_LANG] = code
+ localisedFamilyNameElement.text = sourceObject.getFamilyName(code)
+ sourceElement.append(localisedFamilyNameElement)
if sourceObject.copyLib:
libElement = ET.Element('lib')
libElement.attrib['copy'] = "1"
@@ -670,14 +1663,45 @@ class BaseDocWriter(object):
glyphElement.attrib["name"] = name
glyphElement.attrib["mute"] = '1'
sourceElement.append(glyphElement)
- locationElement, sourceObject.location = self._makeLocationElement(sourceObject.location)
- sourceElement.append(locationElement)
+ if self.effectiveFormatTuple >= (5, 0):
+ self._addLocationElement(sourceElement, designLocation=sourceObject.location)
+ else:
+ # Pre-version 5.0 code was validating and filling in the location
+ # dict while writing it out, as preserved below.
+ locationElement, sourceObject.location = self._makeLocationElement(sourceObject.location)
+ sourceElement.append(locationElement)
self.root.findall('.sources')[0].append(sourceElement)
- def _addLib(self, dict):
+ def _addVariableFont(self, parentElement: ET.Element, vf: VariableFontDescriptor) -> None:
+ vfElement = ET.Element('variable-font')
+ vfElement.attrib['name'] = vf.name
+ if vf.filename is not None:
+ vfElement.attrib['filename'] = vf.filename
+ if vf.axisSubsets:
+ subsetsElement = ET.Element('axis-subsets')
+ for subset in vf.axisSubsets:
+ subsetElement = ET.Element('axis-subset')
+ subsetElement.attrib['name'] = subset.name
+ if isinstance(subset, RangeAxisSubsetDescriptor):
+ if subset.userMinimum != -math.inf:
+ subsetElement.attrib['userminimum'] = self.intOrFloat(subset.userMinimum)
+ if subset.userMaximum != math.inf:
+ subsetElement.attrib['usermaximum'] = self.intOrFloat(subset.userMaximum)
+ if subset.userDefault is not None:
+ subsetElement.attrib['userdefault'] = self.intOrFloat(subset.userDefault)
+ elif isinstance(subset, ValueAxisSubsetDescriptor):
+ subsetElement.attrib['uservalue'] = self.intOrFloat(subset.userValue)
+ subsetsElement.append(subsetElement)
+ vfElement.append(subsetsElement)
+ self._addLib(vfElement, vf.lib, 4)
+ parentElement.append(vfElement)
+
+ def _addLib(self, parentElement: ET.Element, data: Any, indent_level: int) -> None:
+ if not data:
+ return
libElement = ET.Element('lib')
- libElement.append(plistlib.totree(dict, indent_level=2))
- self.root.append(libElement)
+ libElement.append(plistlib.totree(data, indent_level=indent_level))
+ parentElement.append(libElement)
def _writeGlyphElement(self, instanceElement, instanceObject, glyphName, data):
glyphElement = ET.Element('glyph')
@@ -711,9 +1735,15 @@ class BaseDocWriter(object):
class BaseDocReader(LogMixin):
- ruleDescriptorClass = RuleDescriptor
axisDescriptorClass = AxisDescriptor
+ discreteAxisDescriptorClass = DiscreteAxisDescriptor
+ axisLabelDescriptorClass = AxisLabelDescriptor
+ locationLabelDescriptorClass = LocationLabelDescriptor
+ ruleDescriptorClass = RuleDescriptor
sourceDescriptorClass = SourceDescriptor
+ variableFontsDescriptorClass = VariableFontDescriptor
+ valueAxisSubsetDescriptorClass = ValueAxisSubsetDescriptor
+ rangeAxisSubsetDescriptorClass = RangeAxisSubsetDescriptor
instanceDescriptorClass = InstanceDescriptor
def __init__(self, documentPath, documentObject):
@@ -738,7 +1768,9 @@ class BaseDocReader(LogMixin):
def read(self):
self.readAxes()
+ self.readLabels()
self.readRules()
+ self.readVariableFonts()
self.readSources()
self.readInstances()
self.readLib()
@@ -810,17 +1842,24 @@ class BaseDocReader(LogMixin):
def readAxes(self):
# read the axes elements, including the warp map.
+ axesElement = self.root.find(".axes")
+ if axesElement is not None and 'elidedfallbackname' in axesElement.attrib:
+ self.documentObject.elidedFallbackName = axesElement.attrib['elidedfallbackname']
axisElements = self.root.findall(".axes/axis")
if not axisElements:
return
for axisElement in axisElements:
- axisObject = self.axisDescriptorClass()
+ if self.documentObject.formatTuple >= (5, 0) and "values" in axisElement.attrib:
+ axisObject = self.discreteAxisDescriptorClass()
+ axisObject.values = [float(s) for s in axisElement.attrib["values"].split(" ")]
+ else:
+ axisObject = self.axisDescriptorClass()
+ axisObject.minimum = float(axisElement.attrib.get("minimum"))
+ axisObject.maximum = float(axisElement.attrib.get("maximum"))
+ axisObject.default = float(axisElement.attrib.get("default"))
axisObject.name = axisElement.attrib.get("name")
- axisObject.minimum = float(axisElement.attrib.get("minimum"))
- axisObject.maximum = float(axisElement.attrib.get("maximum"))
if axisElement.attrib.get('hidden', False):
axisObject.hidden = True
- axisObject.default = float(axisElement.attrib.get("default"))
axisObject.tag = axisElement.attrib.get("tag")
for mapElement in axisElement.findall('map'):
a = float(mapElement.attrib['input'])
@@ -832,9 +1871,172 @@ class BaseDocReader(LogMixin):
for key, lang in labelNameElement.items():
if key == XML_LANG:
axisObject.labelNames[lang] = tostr(labelNameElement.text)
+ labelElement = axisElement.find(".labels")
+ if labelElement is not None:
+ if "ordering" in labelElement.attrib:
+ axisObject.axisOrdering = int(labelElement.attrib["ordering"])
+ for label in labelElement.findall(".label"):
+ axisObject.axisLabels.append(self.readAxisLabel(label))
self.documentObject.axes.append(axisObject)
self.axisDefaults[axisObject.name] = axisObject.default
+ def readAxisLabel(self, element: ET.Element):
+ xml_attrs = {'userminimum', 'uservalue', 'usermaximum', 'name', 'elidable', 'oldersibling', 'linkeduservalue'}
+ unknown_attrs = set(element.attrib) - xml_attrs
+ if unknown_attrs:
+ raise DesignSpaceDocumentError(f"label element contains unknown attributes: {', '.join(unknown_attrs)}")
+
+ name = element.get("name")
+ if name is None:
+ raise DesignSpaceDocumentError("label element must have a name attribute.")
+ valueStr = element.get("uservalue")
+ if valueStr is None:
+ raise DesignSpaceDocumentError("label element must have a uservalue attribute.")
+ value = float(valueStr)
+ minimumStr = element.get("userminimum")
+ minimum = float(minimumStr) if minimumStr is not None else None
+ maximumStr = element.get("usermaximum")
+ maximum = float(maximumStr) if maximumStr is not None else None
+ linkedValueStr = element.get("linkeduservalue")
+ linkedValue = float(linkedValueStr) if linkedValueStr is not None else None
+ elidable = True if element.get("elidable") == "true" else False
+ olderSibling = True if element.get("oldersibling") == "true" else False
+ labelNames = {
+ lang: label_name.text or ""
+ for label_name in element.findall("labelname")
+ for attr, lang in label_name.items()
+ if attr == XML_LANG
+ # Note: elementtree reads the "xml:lang" attribute name as
+ # '{http://www.w3.org/XML/1998/namespace}lang'
+ }
+ return self.axisLabelDescriptorClass(
+ name=name,
+ userValue=value,
+ userMinimum=minimum,
+ userMaximum=maximum,
+ elidable=elidable,
+ olderSibling=olderSibling,
+ linkedUserValue=linkedValue,
+ labelNames=labelNames,
+ )
+
+ def readLabels(self):
+ if self.documentObject.formatTuple < (5, 0):
+ return
+
+ xml_attrs = {'name', 'elidable', 'oldersibling'}
+ for labelElement in self.root.findall(".labels/label"):
+ unknown_attrs = set(labelElement.attrib) - xml_attrs
+ if unknown_attrs:
+ raise DesignSpaceDocumentError(f"Label element contains unknown attributes: {', '.join(unknown_attrs)}")
+
+ name = labelElement.get("name")
+ if name is None:
+ raise DesignSpaceDocumentError("label element must have a name attribute.")
+ designLocation, userLocation = self.locationFromElement(labelElement)
+ if designLocation:
+ raise DesignSpaceDocumentError(f'<label> element "{name}" must only have user locations (using uservalue="").')
+ elidable = True if labelElement.get("elidable") == "true" else False
+ olderSibling = True if labelElement.get("oldersibling") == "true" else False
+ labelNames = {
+ lang: label_name.text or ""
+ for label_name in labelElement.findall("labelname")
+ for attr, lang in label_name.items()
+ if attr == XML_LANG
+ # Note: elementtree reads the "xml:lang" attribute name as
+ # '{http://www.w3.org/XML/1998/namespace}lang'
+ }
+ locationLabel = self.locationLabelDescriptorClass(
+ name=name,
+ userLocation=userLocation,
+ elidable=elidable,
+ olderSibling=olderSibling,
+ labelNames=labelNames,
+ )
+ self.documentObject.locationLabels.append(locationLabel)
+
+ def readVariableFonts(self):
+ if self.documentObject.formatTuple < (5, 0):
+ return
+
+ xml_attrs = {'name', 'filename'}
+ for variableFontElement in self.root.findall(".variable-fonts/variable-font"):
+ unknown_attrs = set(variableFontElement.attrib) - xml_attrs
+ if unknown_attrs:
+ raise DesignSpaceDocumentError(f"variable-font element contains unknown attributes: {', '.join(unknown_attrs)}")
+
+ name = variableFontElement.get("name")
+ if name is None:
+ raise DesignSpaceDocumentError("variable-font element must have a name attribute.")
+
+ filename = variableFontElement.get("filename")
+
+ axisSubsetsElement = variableFontElement.find(".axis-subsets")
+ if axisSubsetsElement is None:
+ raise DesignSpaceDocumentError("variable-font element must contain an axis-subsets element.")
+ axisSubsets = []
+ for axisSubset in axisSubsetsElement.iterfind(".axis-subset"):
+ axisSubsets.append(self.readAxisSubset(axisSubset))
+
+ lib = None
+ libElement = variableFontElement.find(".lib")
+ if libElement is not None:
+ lib = plistlib.fromtree(libElement[0])
+
+ variableFont = self.variableFontsDescriptorClass(
+ name=name,
+ filename=filename,
+ axisSubsets=axisSubsets,
+ lib=lib,
+ )
+ self.documentObject.variableFonts.append(variableFont)
+
+ def readAxisSubset(self, element: ET.Element):
+ if "uservalue" in element.attrib:
+ xml_attrs = {'name', 'uservalue'}
+ unknown_attrs = set(element.attrib) - xml_attrs
+ if unknown_attrs:
+ raise DesignSpaceDocumentError(f"axis-subset element contains unknown attributes: {', '.join(unknown_attrs)}")
+
+ name = element.get("name")
+ if name is None:
+ raise DesignSpaceDocumentError("axis-subset element must have a name attribute.")
+ userValueStr = element.get("uservalue")
+ if userValueStr is None:
+ raise DesignSpaceDocumentError(
+ "The axis-subset element for a discrete subset must have a uservalue attribute."
+ )
+ userValue = float(userValueStr)
+
+ return self.valueAxisSubsetDescriptorClass(name=name, userValue=userValue)
+ else:
+ xml_attrs = {'name', 'userminimum', 'userdefault', 'usermaximum'}
+ unknown_attrs = set(element.attrib) - xml_attrs
+ if unknown_attrs:
+ raise DesignSpaceDocumentError(f"axis-subset element contains unknown attributes: {', '.join(unknown_attrs)}")
+
+ name = element.get("name")
+ if name is None:
+ raise DesignSpaceDocumentError("axis-subset element must have a name attribute.")
+
+ userMinimum = element.get("userminimum")
+ userDefault = element.get("userdefault")
+ userMaximum = element.get("usermaximum")
+ if userMinimum is not None and userDefault is not None and userMaximum is not None:
+ return self.rangeAxisSubsetDescriptorClass(
+ name=name,
+ userMinimum=float(userMinimum),
+ userDefault=float(userDefault),
+ userMaximum=float(userMaximum),
+ )
+ if all(v is None for v in (userMinimum, userDefault, userMaximum)):
+ return self.rangeAxisSubsetDescriptorClass(name=name)
+
+ raise DesignSpaceDocumentError(
+ "axis-subset element must have min/max/default values or none at all."
+ )
+
+
def readSources(self):
for sourceCount, sourceElement in enumerate(self.root.findall(".sources/source")):
filename = sourceElement.attrib.get('filename')
@@ -856,7 +2058,15 @@ class BaseDocReader(LogMixin):
styleName = sourceElement.attrib.get("stylename")
if styleName is not None:
sourceObject.styleName = styleName
- sourceObject.location = self.locationFromElement(sourceElement)
+ for familyNameElement in sourceElement.findall('familyname'):
+ for key, lang in familyNameElement.items():
+ if key == XML_LANG:
+ familyName = familyNameElement.text
+ sourceObject.setFamilyName(familyName, lang)
+ designLocation, userLocation = self.locationFromElement(sourceElement)
+ if userLocation:
+ raise DesignSpaceDocumentError(f'<source> element "{sourceName}" must only have design locations (using xvalue="").')
+ sourceObject.location = designLocation
layerName = sourceElement.attrib.get('layer')
if layerName is not None:
sourceObject.layerName = layerName
@@ -886,40 +2096,63 @@ class BaseDocReader(LogMixin):
self.documentObject.sources.append(sourceObject)
def locationFromElement(self, element):
- elementLocation = None
+ """Read a nested ``<location>`` element inside the given ``element``.
+
+ .. versionchanged:: 5.0
+ Return a tuple of (designLocation, userLocation)
+ """
+ elementLocation = (None, None)
for locationElement in element.findall('.location'):
elementLocation = self.readLocationElement(locationElement)
break
return elementLocation
def readLocationElement(self, locationElement):
- """ Format 0 location reader """
+ """Read a ``<location>`` element.
+
+ .. versionchanged:: 5.0
+ Return a tuple of (designLocation, userLocation)
+ """
if self._strictAxisNames and not self.documentObject.axes:
raise DesignSpaceDocumentError("No axes defined")
- loc = {}
+ userLoc = {}
+ designLoc = {}
for dimensionElement in locationElement.findall(".dimension"):
dimName = dimensionElement.attrib.get("name")
if self._strictAxisNames and dimName not in self.axisDefaults:
# In case the document contains no axis definitions,
self.log.warning("Location with undefined axis: \"%s\".", dimName)
continue
- xValue = yValue = None
+ userValue = xValue = yValue = None
+ try:
+ userValue = dimensionElement.attrib.get('uservalue')
+ if userValue is not None:
+ userValue = float(userValue)
+ except ValueError:
+ self.log.warning("ValueError in readLocation userValue %3.3f", userValue)
try:
xValue = dimensionElement.attrib.get('xvalue')
- xValue = float(xValue)
+ if xValue is not None:
+ xValue = float(xValue)
except ValueError:
- self.log.warning("KeyError in readLocation xValue %3.3f", xValue)
+ self.log.warning("ValueError in readLocation xValue %3.3f", xValue)
try:
yValue = dimensionElement.attrib.get('yvalue')
if yValue is not None:
yValue = float(yValue)
except ValueError:
- pass
+ self.log.warning("ValueError in readLocation yValue %3.3f", yValue)
+ if userValue is None == xValue is None:
+ raise DesignSpaceDocumentError(f'Exactly one of uservalue="" or xvalue="" must be provided for location dimension "{dimName}"')
if yValue is not None:
- loc[dimName] = (xValue, yValue)
+ if xValue is None:
+ raise DesignSpaceDocumentError(f'Missing xvalue="" for the location dimension "{dimName}"" with yvalue="{yValue}"')
+ designLoc[dimName] = (xValue, yValue)
+ elif xValue is not None:
+ designLoc[dimName] = xValue
else:
- loc[dimName] = xValue
- return loc
+ userLoc[dimName] = userValue
+ return designLoc, userLoc
def readInstances(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
instanceElements = self.root.findall('.instances/instance')
@@ -974,9 +2207,13 @@ class BaseDocReader(LogMixin):
if key == XML_LANG:
styleMapFamilyName = styleMapFamilyNameElement.text
instanceObject.setStyleMapFamilyName(styleMapFamilyName, lang)
- instanceLocation = self.locationFromElement(instanceElement)
- if instanceLocation is not None:
- instanceObject.location = instanceLocation
+ designLocation, userLocation = self.locationFromElement(instanceElement)
+ locationLabel = instanceElement.attrib.get('location')
+ if (designLocation or userLocation) and locationLabel is not None:
+ raise DesignSpaceDocumentError('instance element must have at most one of the location="..." attribute or the nested location element')
+ instanceObject.locationLabel = locationLabel
+ instanceObject.userLocation = userLocation or {}
+ instanceObject.designLocation = designLocation or {}
for glyphElement in instanceElement.findall('.glyphs/glyph'):
self.readGlyphElement(glyphElement, instanceObject)
for infoElement in instanceElement.findall("info"):
@@ -993,19 +2230,16 @@ class BaseDocReader(LogMixin):
""" Read the info element."""
instanceObject.info = True
- def readKerningElement(self, kerningElement, instanceObject):
- """ Read the kerning element."""
- kerningLocation = self.locationFromElement(kerningElement)
- instanceObject.addKerning(kerningLocation)
-
def readGlyphElement(self, glyphElement, instanceObject):
"""
- Read the glyph element:
+ Read the glyph element, which could look like either one of these:
.. code-block:: xml
<glyph name="b" unicode="0x62"/>
+
<glyph name="b"/>
+
<glyph name="b">
<master location="location-token-bbb" source="master-token-aaa2"/>
<master glyphname="b.alt1" location="location-token-ccc" source="master-token-aaa3"/>
@@ -1033,19 +2267,23 @@ class BaseDocReader(LogMixin):
for noteElement in glyphElement.findall('.note'):
glyphData['note'] = noteElement.text
break
- instanceLocation = self.locationFromElement(glyphElement)
- if instanceLocation is not None:
- glyphData['instanceLocation'] = instanceLocation
+ designLocation, userLocation = self.locationFromElement(glyphElement)
+ if userLocation:
+ raise DesignSpaceDocumentError(f'<glyph> element "{glyphName}" must only have design locations (using xvalue="").')
+ if designLocation is not None:
+ glyphData['instanceLocation'] = designLocation
glyphSources = None
for masterElement in glyphElement.findall('.masters/master'):
fontSourceName = masterElement.attrib.get('source')
- sourceLocation = self.locationFromElement(masterElement)
+ designLocation, userLocation = self.locationFromElement(masterElement)
+ if userLocation:
+ raise DesignSpaceDocumentError(f'<master> element "{fontSourceName}" must only have design locations (using xvalue="").')
masterGlyphName = masterElement.attrib.get('glyphname')
if masterGlyphName is None:
# if we don't read a glyphname, use the one we have
masterGlyphName = glyphName
d = dict(font=fontSourceName,
- location=sourceLocation,
+ location=designLocation,
glyphName=masterGlyphName)
if glyphSources is None:
glyphSources = []
@@ -1061,9 +2299,43 @@ class BaseDocReader(LogMixin):
class DesignSpaceDocument(LogMixin, AsDictMixin):
- """ Read, write data from the designspace file"""
+ """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 <document-xml-structure>`_ attributes are usually
+ all lowercase.
+
+ .. code:: python
+
+ from fontTools.designspaceLib import DesignSpaceDocument
+ doc = DesignSpaceDocument.fromfile("some/path/to/my.designspace")
+ doc.formatVersion
+ doc.elidedFallbackName
+ doc.axes
+ doc.locationLabels
+ doc.rules
+ doc.rulesProcessingLast
+ doc.sources
+ doc.variableFonts
+ doc.instances
+ doc.lib
+
+ """
+
def __init__(self, readerClass=None, writerClass=None):
self.path = None
+ """String, optional. When the document is read from the disk, this is
+ the full path that was given to :meth:`read` or :meth:`fromfile`.
+ """
self.filename = None
"""String, optional. When the document is read from the disk, this is
its original file name, i.e. the last part of its path.
@@ -1073,18 +2345,70 @@ class DesignSpaceDocument(LogMixin, AsDictMixin):
possible "good" filename, in case one wants to save the file somewhere.
"""
- self.formatVersion = None
- self.sources = []
- self.instances = []
- self.axes = []
- self.rules = []
- self.rulesProcessingLast = False
- self.default = None # name of the default master
+ self.formatVersion: Optional[str] = None
+ """Format version for this document, as a string. E.g. "4.0" """
- self.lib = {}
- """Custom data associated with the whole document."""
+ self.elidedFallbackName: Optional[str] = None
+ """STAT Style Attributes Header field ``elidedFallbackNameID``.
+
+ See: `OTSpec STAT Style Attributes Header <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#style-attributes-header>`_
+
+ .. versionadded:: 5.0
+ """
+
+ self.axes: List[Union[AxisDescriptor, DiscreteAxisDescriptor]] = []
+ """List of this document's axes."""
+ self.locationLabels: List[LocationLabelDescriptor] = []
+ """List of this document's STAT format 4 labels.
+
+ .. versionadded:: 5.0"""
+ self.rules: List[RuleDescriptor] = []
+ """List of this document's rules."""
+ self.rulesProcessingLast: bool = False
+ """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 <https://github.com/fonttools/fonttools/issues/1371#issuecomment-590214572>`__
+ `fontTools#2050 <https://github.com/fonttools/fonttools/issues/2050#issuecomment-678691020>`__
+
+ If you want to use a different feature altogether, e.g. ``calt``,
+ use the lib key ``com.github.fonttools.varLib.featureVarsFeatureTag``
+
+ .. code:: xml
+
+ <lib>
+ <dict>
+ <key>com.github.fonttools.varLib.featureVarsFeatureTag</key>
+ <string>calt</string>
+ </dict>
+ </lib>
+ """
+ self.sources: List[SourceDescriptor] = []
+ """List of this document's sources."""
+ self.variableFonts: List[VariableFontDescriptor] = []
+ """List of this document's variable fonts.
+
+ .. versionadded:: 5.0"""
+ self.instances: List[InstanceDescriptor] = []
+ """List of this document's instances."""
+ self.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.
+ """
+
+ self.default: Optional[str] = None
+ """Name of the default master.
+
+ This attribute is updated by the :meth:`findDefault`
+ """
- #
if readerClass is not None:
self.readerClass = readerClass
else:
@@ -1096,6 +2420,9 @@ class DesignSpaceDocument(LogMixin, AsDictMixin):
@classmethod
def fromfile(cls, path, readerClass=None, writerClass=None):
+ """Read a designspace file from ``path`` and return a new instance of
+ :class:.
+ """
self = cls(readerClass=readerClass, writerClass=writerClass)
self.read(path)
return self
@@ -1110,6 +2437,7 @@ class DesignSpaceDocument(LogMixin, AsDictMixin):
return self
def tostring(self, encoding=None):
+ """Returns the designspace as a string. Default encoding ``utf-8``."""
if encoding is str or (
encoding is not None and encoding.lower() == "unicode"
):
@@ -1126,6 +2454,9 @@ class DesignSpaceDocument(LogMixin, AsDictMixin):
return f.getvalue()
def read(self, path):
+ """Read a designspace file from ``path`` and populates the fields of
+ ``self`` with the data.
+ """
if hasattr(path, "__fspath__"): # support os.PathLike objects
path = path.__fspath__()
self.path = path
@@ -1136,6 +2467,7 @@ class DesignSpaceDocument(LogMixin, AsDictMixin):
self.findDefault()
def write(self, path):
+ """Write this designspace to ``path``."""
if hasattr(path, "__fspath__"): # support os.PathLike objects
path = path.__fspath__()
self.path = path
@@ -1150,8 +2482,10 @@ class DesignSpaceDocument(LogMixin, AsDictMixin):
def updatePaths(self):
"""
- 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.
+ 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
@@ -1187,8 +2521,6 @@ class DesignSpaceDocument(LogMixin, AsDictMixin):
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.
-
-
"""
assert self.path is not None
for descriptor in self.sources + self.instances:
@@ -1196,40 +2528,96 @@ class DesignSpaceDocument(LogMixin, AsDictMixin):
# case 3 and 4: filename gets updated and relativized
descriptor.filename = self._posixRelativePath(descriptor.path)
- def addSource(self, sourceDescriptor):
+ def addSource(self, sourceDescriptor: SourceDescriptor):
+ """Add the given ``sourceDescriptor`` to ``doc.sources``."""
self.sources.append(sourceDescriptor)
def addSourceDescriptor(self, **kwargs):
+ """Instantiate a new :class:`SourceDescriptor` using the given
+ ``kwargs`` and add it to ``doc.sources``.
+ """
source = self.writerClass.sourceDescriptorClass(**kwargs)
self.addSource(source)
return source
- def addInstance(self, instanceDescriptor):
+ def addInstance(self, instanceDescriptor: InstanceDescriptor):
+ """Add the given ``instanceDescriptor`` to :attr:`instances`."""
self.instances.append(instanceDescriptor)
def addInstanceDescriptor(self, **kwargs):
+ """Instantiate a new :class:`InstanceDescriptor` using the given
+ ``kwargs`` and add it to :attr:`instances`.
+ """
instance = self.writerClass.instanceDescriptorClass(**kwargs)
self.addInstance(instance)
return instance
- def addAxis(self, axisDescriptor):
+ def addAxis(self, axisDescriptor: Union[AxisDescriptor, DiscreteAxisDescriptor]):
+ """Add the given ``axisDescriptor`` to :attr:`axes`."""
self.axes.append(axisDescriptor)
def addAxisDescriptor(self, **kwargs):
- axis = self.writerClass.axisDescriptorClass(**kwargs)
+ """Instantiate a new :class:`AxisDescriptor` using the given
+ ``kwargs`` and add it to :attr:`axes`.
+
+ The axis will be and instance of :class:`DiscreteAxisDescriptor` if
+ the ``kwargs`` provide a ``value``, or a :class:`AxisDescriptor` otherwise.
+ """
+ if "values" in kwargs:
+ axis = self.writerClass.discreteAxisDescriptorClass(**kwargs)
+ else:
+ axis = self.writerClass.axisDescriptorClass(**kwargs)
self.addAxis(axis)
return axis
- def addRule(self, ruleDescriptor):
+ def addRule(self, ruleDescriptor: RuleDescriptor):
+ """Add the given ``ruleDescriptor`` to :attr:`rules`."""
self.rules.append(ruleDescriptor)
def addRuleDescriptor(self, **kwargs):
+ """Instantiate a new :class:`RuleDescriptor` using the given
+ ``kwargs`` and add it to :attr:`rules`.
+ """
rule = self.writerClass.ruleDescriptorClass(**kwargs)
self.addRule(rule)
return rule
+ def addVariableFont(self, variableFontDescriptor: VariableFontDescriptor):
+ """Add the given ``variableFontDescriptor`` to :attr:`variableFonts`.
+
+ .. versionadded:: 5.0
+ """
+ self.variableFonts.append(variableFontDescriptor)
+
+ def addVariableFontDescriptor(self, **kwargs):
+ """Instantiate a new :class:`VariableFontDescriptor` using the given
+ ``kwargs`` and add it to :attr:`variableFonts`.
+
+ .. versionadded:: 5.0
+ """
+ variableFont = self.writerClass.variableFontDescriptorClass(**kwargs)
+ self.addVariableFont(variableFont)
+ return variableFont
+
+ def addLocationLabel(self, locationLabelDescriptor: LocationLabelDescriptor):
+ """Add the given ``locationLabelDescriptor`` to :attr:`locationLabels`.
+
+ .. versionadded:: 5.0
+ """
+ self.locationLabels.append(locationLabelDescriptor)
+
+ def addLocationLabelDescriptor(self, **kwargs):
+ """Instantiate a new :class:`LocationLabelDescriptor` using the given
+ ``kwargs`` and add it to :attr:`locationLabels`.
+
+ .. versionadded:: 5.0
+ """
+ locationLabel = self.writerClass.locationLabelDescriptorClass(**kwargs)
+ self.addLocationLabel(locationLabel)
+ return locationLabel
+
def newDefaultLocation(self):
- """Return default location in design space."""
+ """Return a dict with the default location in design space coordinates."""
# Without OrderedDict, output XML would be non-deterministic.
# https://github.com/LettError/designSpaceDocument/issues/10
loc = collections.OrderedDict()
@@ -1239,9 +2627,21 @@ class DesignSpaceDocument(LogMixin, AsDictMixin):
)
return loc
+ def labelForUserLocation(self, userLocation: SimpleLocationDict) -> Optional[LocationLabelDescriptor]:
+ """Return the :class:`LocationLabel` that matches the given
+ ``userLocation``, or ``None`` if no such label exists.
+
+ .. versionadded:: 5.0
+ """
+ return next(
+ (label for label in self.locationLabels if label.userLocation == userLocation), None
+ )
+
def updateFilenameFromPath(self, masters=True, instances=True, force=False):
- # set a descriptor filename attr from the path and this document path
- # if the filename attribute is not None: skip it.
+ """Set a descriptor filename attr from the path and this document path.
+
+ If the filename attribute is not None: skip it.
+ """
if masters:
for descriptor in self.sources:
if descriptor.filename is not None and not force:
@@ -1256,49 +2656,102 @@ class DesignSpaceDocument(LogMixin, AsDictMixin):
descriptor.filename = self._posixRelativePath(descriptor.path)
def newAxisDescriptor(self):
- # Ask the writer class to make us a new axisDescriptor
+ """Ask the writer class to make us a new axisDescriptor."""
return self.writerClass.getAxisDecriptor()
def newSourceDescriptor(self):
- # Ask the writer class to make us a new sourceDescriptor
+ """Ask the writer class to make us a new sourceDescriptor."""
return self.writerClass.getSourceDescriptor()
def newInstanceDescriptor(self):
- # Ask the writer class to make us a new instanceDescriptor
+ """Ask the writer class to make us a new instanceDescriptor."""
return self.writerClass.getInstanceDescriptor()
def getAxisOrder(self):
+ """Return a list of axis names, in the same order as defined in the document."""
names = []
for axisDescriptor in self.axes:
names.append(axisDescriptor.name)
return names
def getAxis(self, name):
+ """Return the axis with the given ``name``, or ``None`` if no such axis exists."""
for axisDescriptor in self.axes:
if axisDescriptor.name == name:
return axisDescriptor
return None
+ def getLocationLabel(self, name: str) -> Optional[LocationLabelDescriptor]:
+ """Return the top-level location label with the given ``name``, or
+ ``None`` if no such label exists.
+
+ .. versionadded:: 5.0
+ """
+ for label in self.locationLabels:
+ if label.name == name:
+ return label
+ return None
+
+ def map_forward(self, userLocation: SimpleLocationDict) -> SimpleLocationDict:
+ """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.
+
+ .. versionadded:: 5.0
+ """
+ return {
+ axis.name: axis.map_forward(userLocation.get(axis.name, axis.default))
+ for axis in self.axes
+ }
+
+ def map_backward(self, designLocation: AnisotropicLocationDict) -> SimpleLocationDict:
+ """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.
+
+ .. versionadded:: 5.0
+ """
+ return {
+ axis.name: (
+ axis.map_backward(designLocation[axis.name])
+ if axis.name in designLocation
+ else axis.default
+ )
+ for axis in self.axes
+ }
+
def findDefault(self):
"""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 :attr:`default` value.
+
+ .. versionchanged:: 5.0
+ Allow the default source to not specify some of the axis values, and
+ they are assumed to be the default.
+ See :meth:`SourceDescriptor.getFullDesignLocation()`
"""
self.default = None
# Convert the default location from user space to design space before comparing
# it against the SourceDescriptor locations (always in design space).
- default_location_design = self.newDefaultLocation()
+ defaultDesignLocation = self.newDefaultLocation()
for sourceDescriptor in self.sources:
- if sourceDescriptor.location == default_location_design:
+ if sourceDescriptor.getFullDesignLocation(self) == defaultDesignLocation:
self.default = sourceDescriptor
return sourceDescriptor
return None
def normalizeLocation(self, location):
+ """Return a dict with normalized axis values."""
from fontTools.varLib.models import normalizeValue
new = {}
@@ -1317,9 +2770,12 @@ class DesignSpaceDocument(LogMixin, AsDictMixin):
return new
def normalize(self):
- # 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.
+ """
+ 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.
+ """
# masters
for item in self.sources:
item.location = self.normalizeLocation(item.location)
@@ -1412,3 +2868,81 @@ class DesignSpaceDocument(LogMixin, AsDictMixin):
loaded[source.path] = source.font
fonts.append(source.font)
return fonts
+
+ @property
+ def formatTuple(self):
+ """Return the formatVersion as a tuple of (major, minor).
+
+ .. versionadded:: 5.0
+ """
+ if self.formatVersion is None:
+ return (5, 0)
+ numbers = (int(i) for i in self.formatVersion.split("."))
+ major = next(numbers)
+ minor = next(numbers, 0)
+ return (major, minor)
+
+ def getVariableFonts(self) -> List[VariableFontDescriptor]:
+ """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.
+
+ .. seealso:: :func:`splitInterpolable`
+
+ .. versionadded:: 5.0
+ """
+ if self.variableFonts:
+ return self.variableFonts
+
+ variableFonts = []
+ discreteAxes = []
+ rangeAxisSubsets: List[Union[RangeAxisSubsetDescriptor, ValueAxisSubsetDescriptor]] = []
+ for axis in self.axes:
+ if isinstance(axis, DiscreteAxisDescriptor):
+ discreteAxes.append(axis)
+ else:
+ rangeAxisSubsets.append(RangeAxisSubsetDescriptor(name=axis.name))
+ valueCombinations = itertools.product(*[axis.values for axis in discreteAxes])
+ for values in valueCombinations:
+ basename = None
+ if self.filename is not None:
+ basename = os.path.splitext(self.filename)[0] + "-VF"
+ if self.path is not None:
+ basename = os.path.splitext(os.path.basename(self.path))[0] + "-VF"
+ if basename is None:
+ basename = "VF"
+ axisNames = "".join([f"-{axis.tag}{value}" for axis, value in zip(discreteAxes, values)])
+ variableFonts.append(VariableFontDescriptor(
+ name=f"{basename}{axisNames}",
+ axisSubsets=rangeAxisSubsets + [
+ ValueAxisSubsetDescriptor(name=axis.name, userValue=value)
+ for axis, value in zip(discreteAxes, values)
+ ]
+ ))
+ return variableFonts
+
+ def deepcopyExceptFonts(self):
+ """Allow deep-copying a DesignSpace document without deep-copying
+ attached UFO fonts or TTFont objects. The :attr:`font` attribute
+ is shared by reference between the original and the copy.
+
+ .. versionadded:: 5.0
+ """
+ fonts = [source.font for source in self.sources]
+ try:
+ for source in self.sources:
+ source.font = None
+ res = copy.deepcopy(self)
+ for source, font in zip(res.sources, fonts):
+ source.font = font
+ return res
+ finally:
+ for source, font in zip(self.sources, fonts):
+ source.font = font
+
diff --git a/Lib/fontTools/designspaceLib/split.py b/Lib/fontTools/designspaceLib/split.py
new file mode 100644
index 00000000..2a09418c
--- /dev/null
+++ b/Lib/fontTools/designspaceLib/split.py
@@ -0,0 +1,424 @@
+"""Allows building all the variable fonts of a DesignSpace version 5 by
+splitting the document into interpolable sub-space, then into each VF.
+"""
+
+from __future__ import annotations
+
+import itertools
+import logging
+import math
+from typing import Any, Callable, Dict, Iterator, List, Tuple
+
+from fontTools.designspaceLib import (
+ AxisDescriptor,
+ DesignSpaceDocument,
+ DiscreteAxisDescriptor,
+ InstanceDescriptor,
+ RuleDescriptor,
+ SimpleLocationDict,
+ SourceDescriptor,
+ VariableFontDescriptor,
+)
+from fontTools.designspaceLib.statNames import StatNames, getStatNames
+from fontTools.designspaceLib.types import (
+ Range,
+ Region,
+ ConditionSet,
+ getVFUserRegion,
+ locationInRegion,
+ regionInRegion,
+ userRegionToDesignRegion,
+)
+
+LOGGER = logging.getLogger(__name__)
+
+MakeInstanceFilenameCallable = Callable[
+ [DesignSpaceDocument, InstanceDescriptor, StatNames], str
+]
+
+
+def defaultMakeInstanceFilename(
+ doc: DesignSpaceDocument, instance: InstanceDescriptor, statNames: StatNames
+) -> str:
+ """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.
+ """
+ familyName = instance.familyName or statNames.familyNames.get("en")
+ styleName = instance.styleName or statNames.styleNames.get("en")
+ return f"{familyName}-{styleName}.ttf"
+
+
+def splitInterpolable(
+ doc: DesignSpaceDocument,
+ makeNames: bool = True,
+ expandLocations: bool = True,
+ makeInstanceFilename: MakeInstanceFilenameCallable = defaultMakeInstanceFilename,
+) -> Iterator[Tuple[SimpleLocationDict, DesignSpaceDocument]]:
+ """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.
+
+ Args:
+ - ``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.
+
+ .. versionadded:: 5.0
+ """
+ discreteAxes = []
+ interpolableUserRegion: Region = {}
+ for axis in doc.axes:
+ if isinstance(axis, DiscreteAxisDescriptor):
+ discreteAxes.append(axis)
+ else:
+ interpolableUserRegion[axis.name] = Range(
+ axis.minimum, axis.maximum, axis.default
+ )
+ valueCombinations = itertools.product(*[axis.values for axis in discreteAxes])
+ for values in valueCombinations:
+ discreteUserLocation = {
+ discreteAxis.name: value
+ for discreteAxis, value in zip(discreteAxes, values)
+ }
+ subDoc = _extractSubSpace(
+ doc,
+ {**interpolableUserRegion, **discreteUserLocation},
+ keepVFs=True,
+ makeNames=makeNames,
+ expandLocations=expandLocations,
+ makeInstanceFilename=makeInstanceFilename,
+ )
+ yield discreteUserLocation, subDoc
+
+
+def splitVariableFonts(
+ doc: DesignSpaceDocument,
+ makeNames: bool = False,
+ expandLocations: bool = False,
+ makeInstanceFilename: MakeInstanceFilenameCallable = defaultMakeInstanceFilename,
+) -> Iterator[Tuple[str, DesignSpaceDocument]]:
+ """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.
+
+ Args:
+ - ``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.
+
+ .. versionadded:: 5.0
+ """
+ # Make one DesignspaceDoc v5 for each variable font
+ for vf in doc.getVariableFonts():
+ vfUserRegion = getVFUserRegion(doc, vf)
+ vfDoc = _extractSubSpace(
+ doc,
+ vfUserRegion,
+ keepVFs=False,
+ makeNames=makeNames,
+ expandLocations=expandLocations,
+ makeInstanceFilename=makeInstanceFilename,
+ )
+ vfDoc.lib = {**vfDoc.lib, **vf.lib}
+ yield vf.name, vfDoc
+
+
+def convert5to4(
+ doc: DesignSpaceDocument,
+) -> Dict[str, DesignSpaceDocument]:
+ """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.
+
+ .. versionadded:: 5.0
+ """
+ vfs = {}
+ for _location, subDoc in splitInterpolable(doc):
+ for vfName, vfDoc in splitVariableFonts(subDoc):
+ vfDoc.formatVersion = "4.1"
+ vfs[vfName] = vfDoc
+ return vfs
+
+
+def _extractSubSpace(
+ doc: DesignSpaceDocument,
+ userRegion: Region,
+ *,
+ keepVFs: bool,
+ makeNames: bool,
+ expandLocations: bool,
+ makeInstanceFilename: MakeInstanceFilenameCallable,
+) -> DesignSpaceDocument:
+ subDoc = DesignSpaceDocument()
+ # Don't include STAT info
+ # FIXME: (Jany) let's think about it. Not include = OK because the point of
+ # the splitting is to build VFs and we'll use the STAT data of the full
+ # document to generate the STAT of the VFs, so "no need" to have STAT data
+ # in sub-docs. Counterpoint: what if someone wants to split this DS for
+ # other purposes? Maybe for that it would be useful to also subset the STAT
+ # data?
+ # subDoc.elidedFallbackName = doc.elidedFallbackName
+
+ def maybeExpandDesignLocation(object):
+ if expandLocations:
+ return object.getFullDesignLocation(doc)
+ else:
+ return object.designLocation
+
+ for axis in doc.axes:
+ range = userRegion[axis.name]
+ if isinstance(range, Range) and isinstance(axis, AxisDescriptor):
+ subDoc.addAxis(
+ AxisDescriptor(
+ # Same info
+ tag=axis.tag,
+ name=axis.name,
+ labelNames=axis.labelNames,
+ hidden=axis.hidden,
+ # Subset range
+ minimum=max(range.minimum, axis.minimum),
+ default=range.default or axis.default,
+ maximum=min(range.maximum, axis.maximum),
+ map=[
+ (user, design)
+ for user, design in axis.map
+ if range.minimum <= user <= range.maximum
+ ],
+ # Don't include STAT info
+ axisOrdering=None,
+ axisLabels=None,
+ )
+ )
+
+ # Don't include STAT info
+ # subDoc.locationLabels = doc.locationLabels
+
+ # Rules: subset them based on conditions
+ designRegion = userRegionToDesignRegion(doc, userRegion)
+ subDoc.rules = _subsetRulesBasedOnConditions(doc.rules, designRegion)
+ subDoc.rulesProcessingLast = doc.rulesProcessingLast
+
+ # Sources: keep only the ones that fall within the kept axis ranges
+ for source in doc.sources:
+ if not locationInRegion(doc.map_backward(source.designLocation), userRegion):
+ continue
+
+ subDoc.addSource(
+ SourceDescriptor(
+ filename=source.filename,
+ path=source.path,
+ font=source.font,
+ name=source.name,
+ designLocation=_filterLocation(
+ userRegion, maybeExpandDesignLocation(source)
+ ),
+ layerName=source.layerName,
+ familyName=source.familyName,
+ styleName=source.styleName,
+ muteKerning=source.muteKerning,
+ muteInfo=source.muteInfo,
+ mutedGlyphNames=source.mutedGlyphNames,
+ )
+ )
+
+ # Copy family name translations from the old default source to the new default
+ vfDefault = subDoc.findDefault()
+ oldDefault = doc.findDefault()
+ if vfDefault is not None and oldDefault is not None:
+ vfDefault.localisedFamilyName = oldDefault.localisedFamilyName
+
+ # Variable fonts: keep only the ones that fall within the kept axis ranges
+ if keepVFs:
+ # Note: call getVariableFont() to make the implicit VFs explicit
+ for vf in doc.getVariableFonts():
+ vfUserRegion = getVFUserRegion(doc, vf)
+ if regionInRegion(vfUserRegion, userRegion):
+ subDoc.addVariableFont(
+ VariableFontDescriptor(
+ name=vf.name,
+ filename=vf.filename,
+ axisSubsets=[
+ axisSubset
+ for axisSubset in vf.axisSubsets
+ if isinstance(userRegion[axisSubset.name], Range)
+ ],
+ lib=vf.lib,
+ )
+ )
+
+ # Instances: same as Sources + compute missing names
+ for instance in doc.instances:
+ if not locationInRegion(instance.getFullUserLocation(doc), userRegion):
+ continue
+
+ if makeNames:
+ statNames = getStatNames(doc, instance.getFullUserLocation(doc))
+ familyName = instance.familyName or statNames.familyNames.get("en")
+ styleName = instance.styleName or statNames.styleNames.get("en")
+ subDoc.addInstance(
+ InstanceDescriptor(
+ filename=instance.filename
+ or makeInstanceFilename(doc, instance, statNames),
+ path=instance.path,
+ font=instance.font,
+ name=instance.name or f"{familyName} {styleName}",
+ userLocation={} if expandLocations else instance.userLocation,
+ designLocation=_filterLocation(
+ userRegion, maybeExpandDesignLocation(instance)
+ ),
+ familyName=familyName,
+ styleName=styleName,
+ postScriptFontName=instance.postScriptFontName
+ or statNames.postScriptFontName,
+ styleMapFamilyName=instance.styleMapFamilyName
+ or statNames.styleMapFamilyNames.get("en"),
+ styleMapStyleName=instance.styleMapStyleName
+ or statNames.styleMapStyleName,
+ localisedFamilyName=instance.localisedFamilyName
+ or statNames.familyNames,
+ localisedStyleName=instance.localisedStyleName
+ or statNames.styleNames,
+ localisedStyleMapFamilyName=instance.localisedStyleMapFamilyName
+ or statNames.styleMapFamilyNames,
+ localisedStyleMapStyleName=instance.localisedStyleMapStyleName
+ or {},
+ lib=instance.lib,
+ )
+ )
+ else:
+ subDoc.addInstance(
+ InstanceDescriptor(
+ filename=instance.filename,
+ path=instance.path,
+ font=instance.font,
+ name=instance.name,
+ userLocation={} if expandLocations else instance.userLocation,
+ designLocation=_filterLocation(
+ userRegion, maybeExpandDesignLocation(instance)
+ ),
+ familyName=instance.familyName,
+ styleName=instance.styleName,
+ postScriptFontName=instance.postScriptFontName,
+ styleMapFamilyName=instance.styleMapFamilyName,
+ styleMapStyleName=instance.styleMapStyleName,
+ localisedFamilyName=instance.localisedFamilyName,
+ localisedStyleName=instance.localisedStyleName,
+ localisedStyleMapFamilyName=instance.localisedStyleMapFamilyName,
+ localisedStyleMapStyleName=instance.localisedStyleMapStyleName,
+ lib=instance.lib,
+ )
+ )
+
+ subDoc.lib = doc.lib
+
+ return subDoc
+
+
+def _conditionSetFrom(conditionSet: List[Dict[str, Any]]) -> ConditionSet:
+ c: Dict[str, Range] = {}
+ for condition in conditionSet:
+ c[condition["name"]] = Range(
+ condition.get("minimum", -math.inf),
+ condition.get("maximum", math.inf),
+ )
+ return c
+
+
+def _subsetRulesBasedOnConditions(
+ rules: List[RuleDescriptor], designRegion: Region
+) -> List[RuleDescriptor]:
+ # What rules to keep:
+ # - Keep the rule if any conditionset is relevant.
+ # - A conditionset is relevant if all conditions are relevant or it is empty.
+ # - A condition is relevant if
+ # - axis is point (C-AP),
+ # - and point in condition's range (C-AP-in)
+ # (in this case remove the condition because it's always true)
+ # - else (C-AP-out) whole conditionset can be discarded (condition false
+ # => conditionset false)
+ # - axis is range (C-AR),
+ # - (C-AR-all) and axis range fully contained in condition range: we can
+ # scrap the condition because it's always true
+ # - (C-AR-inter) and intersection(axis range, condition range) not empty:
+ # keep the condition with the smaller range (= intersection)
+ # - (C-AR-none) else, whole conditionset can be discarded
+ newRules: List[RuleDescriptor] = []
+ for rule in rules:
+ newRule: RuleDescriptor = RuleDescriptor(
+ name=rule.name, conditionSets=[], subs=rule.subs
+ )
+ for conditionset in rule.conditionSets:
+ cs = _conditionSetFrom(conditionset)
+ newConditionset: List[Dict[str, Any]] = []
+ discardConditionset = False
+ for selectionName, selectionValue in designRegion.items():
+ # TODO: Ensure that all(key in conditionset for key in region.keys())?
+ if selectionName not in cs:
+ # raise Exception("Selection has different axes than the rules")
+ continue
+ if isinstance(selectionValue, (float, int)): # is point
+ # Case C-AP-in
+ if selectionValue in cs[selectionName]:
+ pass # always matches, conditionset can stay empty for this one.
+ # Case C-AP-out
+ else:
+ discardConditionset = True
+ else: # is range
+ # Case C-AR-all
+ if selectionValue in cs[selectionName]:
+ pass # always matches, conditionset can stay empty for this one.
+ else:
+ intersection = cs[selectionName].intersection(selectionValue)
+ # Case C-AR-inter
+ if intersection is not None:
+ newConditionset.append(
+ {
+ "name": selectionName,
+ "minimum": intersection.minimum,
+ "maximum": intersection.maximum,
+ }
+ )
+ # Case C-AR-none
+ else:
+ discardConditionset = True
+ if not discardConditionset:
+ newRule.conditionSets.append(newConditionset)
+ if newRule.conditionSets:
+ newRules.append(newRule)
+
+ return newRules
+
+
+def _filterLocation(
+ userRegion: Region,
+ location: Dict[str, float],
+) -> Dict[str, float]:
+ return {
+ name: value
+ for name, value in location.items()
+ if name in userRegion and isinstance(userRegion[name], Range)
+ }
diff --git a/Lib/fontTools/designspaceLib/statNames.py b/Lib/fontTools/designspaceLib/statNames.py
new file mode 100644
index 00000000..0a475c89
--- /dev/null
+++ b/Lib/fontTools/designspaceLib/statNames.py
@@ -0,0 +1,224 @@
+"""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:
+
+.. code:: python
+
+ instance = doc.instances[0]
+ names = getStatNames(doc, instance.getFullUserLocation(doc))
+ print(names.styleNames)
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Dict, Optional, Tuple, Union
+import logging
+
+from fontTools.designspaceLib import (
+ AxisDescriptor,
+ AxisLabelDescriptor,
+ DesignSpaceDocument,
+ DesignSpaceDocumentError,
+ DiscreteAxisDescriptor,
+ SimpleLocationDict,
+ SourceDescriptor,
+)
+
+LOGGER = logging.getLogger(__name__)
+
+# TODO(Python 3.8): use Literal
+# RibbiStyleName = Union[Literal["regular"], Literal["bold"], Literal["italic"], Literal["bold italic"]]
+RibbiStyle = str
+BOLD_ITALIC_TO_RIBBI_STYLE = {
+ (False, False): "regular",
+ (False, True): "italic",
+ (True, False): "bold",
+ (True, True): "bold italic",
+}
+
+
+@dataclass
+class StatNames:
+ """Name data generated from the STAT table information."""
+
+ familyNames: Dict[str, str]
+ styleNames: Dict[str, str]
+ postScriptFontName: Optional[str]
+ styleMapFamilyNames: Dict[str, str]
+ styleMapStyleName: Optional[RibbiStyle]
+
+
+
+def getStatNames(
+ doc: DesignSpaceDocument, userLocation: SimpleLocationDict
+) -> StatNames:
+ """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).
+
+ .. versionadded:: 5.0
+ """
+ familyNames: Dict[str, str] = {}
+ defaultSource: Optional[SourceDescriptor] = doc.findDefault()
+ if defaultSource is None:
+ LOGGER.warning("Cannot determine default source to look up family name.")
+ elif defaultSource.familyName is None:
+ LOGGER.warning(
+ "Cannot look up family name, assign the 'familyname' attribute to the default source."
+ )
+ else:
+ familyNames = {
+ "en": defaultSource.familyName,
+ **defaultSource.localisedFamilyName,
+ }
+
+ styleNames: Dict[str, str] = {}
+ # If a free-standing label matches the location, use it for name generation.
+ label = doc.labelForUserLocation(userLocation)
+ if label is not None:
+ styleNames = {"en": label.name, **label.labelNames}
+ # Otherwise, scour the axis labels for matches.
+ else:
+ # Gather all languages in which at least one translation is provided
+ # Then build names for all these languages, but fallback to English
+ # whenever a translation is missing.
+ labels = _getAxisLabelsForUserLocation(doc.axes, userLocation)
+ languages = set(language for label in labels for language in label.labelNames)
+ languages.add("en")
+ for language in languages:
+ styleName = " ".join(
+ label.labelNames.get(language, label.defaultName)
+ for label in labels
+ if not label.elidable
+ )
+ if not styleName and doc.elidedFallbackName is not None:
+ styleName = doc.elidedFallbackName
+ styleNames[language] = styleName
+
+ postScriptFontName = None
+ if "en" in familyNames and "en" in styleNames:
+ postScriptFontName = f"{familyNames['en']}-{styleNames['en']}".replace(" ", "")
+
+ styleMapStyleName, regularUserLocation = _getRibbiStyle(doc, userLocation)
+
+ styleNamesForStyleMap = styleNames
+ if regularUserLocation != userLocation:
+ regularStatNames = getStatNames(doc, regularUserLocation)
+ styleNamesForStyleMap = regularStatNames.styleNames
+
+ styleMapFamilyNames = {}
+ for language in set(familyNames).union(styleNames.keys()):
+ familyName = familyNames.get(language, familyNames["en"])
+ styleName = styleNamesForStyleMap.get(language, styleNamesForStyleMap["en"])
+ styleMapFamilyNames[language] = (familyName + " " + styleName).strip()
+
+ return StatNames(
+ familyNames=familyNames,
+ styleNames=styleNames,
+ postScriptFontName=postScriptFontName,
+ styleMapFamilyNames=styleMapFamilyNames,
+ styleMapStyleName=styleMapStyleName,
+ )
+
+
+def _getSortedAxisLabels(
+ axes: list[Union[AxisDescriptor, DiscreteAxisDescriptor]],
+) -> Dict[str, list[AxisLabelDescriptor]]:
+ """Returns axis labels sorted by their ordering, with unordered ones appended as
+ they are listed."""
+
+ # First, get the axis labels with explicit ordering...
+ sortedAxes = sorted(
+ (axis for axis in axes if axis.axisOrdering is not None),
+ key=lambda a: a.axisOrdering,
+ )
+ sortedLabels: Dict[str, list[AxisLabelDescriptor]] = {
+ axis.name: axis.axisLabels for axis in sortedAxes
+ }
+
+ # ... then append the others in the order they appear.
+ # NOTE: This relies on Python 3.7+ dict's preserved insertion order.
+ for axis in axes:
+ if axis.axisOrdering is None:
+ sortedLabels[axis.name] = axis.axisLabels
+
+ return sortedLabels
+
+
+def _getAxisLabelsForUserLocation(
+ axes: list[Union[AxisDescriptor, DiscreteAxisDescriptor]],
+ userLocation: SimpleLocationDict,
+) -> list[AxisLabelDescriptor]:
+ labels: list[AxisLabelDescriptor] = []
+
+ allAxisLabels = _getSortedAxisLabels(axes)
+ if allAxisLabels.keys() != userLocation.keys():
+ LOGGER.warning(
+ f"Mismatch between user location '{userLocation.keys()}' and available "
+ f"labels for '{allAxisLabels.keys()}'."
+ )
+
+ for axisName, axisLabels in allAxisLabels.items():
+ userValue = userLocation[axisName]
+ label: Optional[AxisLabelDescriptor] = next(
+ (
+ l
+ for l in axisLabels
+ if l.userValue == userValue
+ or (
+ l.userMinimum is not None
+ and l.userMaximum is not None
+ and l.userMinimum <= userValue <= l.userMaximum
+ )
+ ),
+ None,
+ )
+ if label is None:
+ LOGGER.debug(
+ f"Document needs a label for axis '{axisName}', user value '{userValue}'."
+ )
+ else:
+ labels.append(label)
+
+ return labels
+
+
+def _getRibbiStyle(
+ self: DesignSpaceDocument, userLocation: SimpleLocationDict
+) -> Tuple[RibbiStyle, SimpleLocationDict]:
+ """Compute the RIBBI style name of the given user location,
+ return the location of the matching Regular in the RIBBI group.
+
+ .. versionadded:: 5.0
+ """
+ regularUserLocation = {}
+ axes_by_tag = {axis.tag: axis for axis in self.axes}
+
+ bold: bool = False
+ italic: bool = False
+
+ axis = axes_by_tag.get("wght")
+ if axis is not None:
+ for regular_label in axis.axisLabels:
+ if regular_label.linkedUserValue == userLocation[axis.name]:
+ regularUserLocation[axis.name] = regular_label.userValue
+ bold = True
+ break
+
+ axis = axes_by_tag.get("ital") or axes_by_tag.get("slnt")
+ if axis is not None:
+ for urpright_label in axis.axisLabels:
+ if urpright_label.linkedUserValue == userLocation[axis.name]:
+ regularUserLocation[axis.name] = urpright_label.userValue
+ italic = True
+ break
+
+ return BOLD_ITALIC_TO_RIBBI_STYLE[bold, italic], {
+ **userLocation,
+ **regularUserLocation,
+ }
diff --git a/Lib/fontTools/designspaceLib/types.py b/Lib/fontTools/designspaceLib/types.py
new file mode 100644
index 00000000..8afea96c
--- /dev/null
+++ b/Lib/fontTools/designspaceLib/types.py
@@ -0,0 +1,122 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Dict, List, Optional, Union
+
+from fontTools.designspaceLib import (
+ DesignSpaceDocument,
+ RangeAxisSubsetDescriptor,
+ SimpleLocationDict,
+ VariableFontDescriptor,
+)
+
+
+def clamp(value, minimum, maximum):
+ return min(max(value, minimum), maximum)
+
+
+@dataclass
+class Range:
+ minimum: float
+ """Inclusive minimum of the range."""
+ maximum: float
+ """Inclusive maximum of the range."""
+ default: float = 0
+ """Default value"""
+
+ def __post_init__(self):
+ self.minimum, self.maximum = sorted((self.minimum, self.maximum))
+ self.default = clamp(self.default, self.minimum, self.maximum)
+
+ def __contains__(self, value: Union[float, Range]) -> bool:
+ if isinstance(value, Range):
+ return self.minimum <= value.minimum and value.maximum <= self.maximum
+ return self.minimum <= value <= self.maximum
+
+ def intersection(self, other: Range) -> Optional[Range]:
+ if self.maximum < other.minimum or self.minimum > other.maximum:
+ return None
+ else:
+ return Range(
+ max(self.minimum, other.minimum),
+ min(self.maximum, other.maximum),
+ self.default, # We don't care about the default in this use-case
+ )
+
+
+# A region selection is either a range or a single value, as a Designspace v5
+# axis-subset element only allows a single discrete value or a range for a
+# variable-font element.
+Region = Dict[str, Union[Range, float]]
+
+# A conditionset is a set of named ranges.
+ConditionSet = Dict[str, Range]
+
+# A rule is a list of conditionsets where any has to be relevant for the whole rule to be relevant.
+Rule = List[ConditionSet]
+Rules = Dict[str, Rule]
+
+
+def locationInRegion(location: SimpleLocationDict, region: Region) -> bool:
+ for name, value in location.items():
+ if name not in region:
+ return False
+ regionValue = region[name]
+ if isinstance(regionValue, (float, int)):
+ if value != regionValue:
+ return False
+ else:
+ if value not in regionValue:
+ return False
+ return True
+
+
+def regionInRegion(region: Region, superRegion: Region) -> bool:
+ for name, value in region.items():
+ if not name in superRegion:
+ return False
+ superValue = superRegion[name]
+ if isinstance(superValue, (float, int)):
+ if value != superValue:
+ return False
+ else:
+ if value not in superValue:
+ return False
+ return True
+
+
+def userRegionToDesignRegion(doc: DesignSpaceDocument, userRegion: Region) -> Region:
+ designRegion = {}
+ for name, value in userRegion.items():
+ axis = doc.getAxis(name)
+ if isinstance(value, (float, int)):
+ designRegion[name] = axis.map_forward(value)
+ else:
+ designRegion[name] = Range(
+ axis.map_forward(value.minimum),
+ axis.map_forward(value.maximum),
+ axis.map_forward(value.default),
+ )
+ return designRegion
+
+
+def getVFUserRegion(doc: DesignSpaceDocument, vf: VariableFontDescriptor) -> Region:
+ vfUserRegion: Region = {}
+ # For each axis, 2 cases:
+ # - it has a range = it's an axis in the VF DS
+ # - it's a single location = use it to know which rules should apply in the VF
+ for axisSubset in vf.axisSubsets:
+ axis = doc.getAxis(axisSubset.name)
+ if isinstance(axisSubset, RangeAxisSubsetDescriptor):
+ vfUserRegion[axis.name] = Range(
+ max(axisSubset.userMinimum, axis.minimum),
+ min(axisSubset.userMaximum, axis.maximum),
+ axisSubset.userDefault or axis.default,
+ )
+ else:
+ vfUserRegion[axis.name] = axisSubset.userValue
+ # Any axis not mentioned explicitly has a single location = default value
+ for axis in doc.axes:
+ if axis.name not in vfUserRegion:
+ vfUserRegion[axis.name] = axis.default
+ return vfUserRegion
diff --git a/Lib/fontTools/fontBuilder.py b/Lib/fontTools/fontBuilder.py
index bf3b31b7..ad7180cb 100644
--- a/Lib/fontTools/fontBuilder.py
+++ b/Lib/fontTools/fontBuilder.py
@@ -486,15 +486,12 @@ class FontBuilder(object):
"""Create a new `OS/2` table and initialize it with default values,
which can be overridden by keyword arguments.
"""
- if "xAvgCharWidth" not in values:
- gs = self.font.getGlyphSet()
- widths = [
- gs[glyphName].width
- for glyphName in gs.keys()
- if gs[glyphName].width > 0
- ]
- values["xAvgCharWidth"] = int(round(sum(widths) / float(len(widths))))
self._initTableWithValues("OS/2", _OS2Defaults, values)
+ if "xAvgCharWidth" not in values:
+ assert (
+ "hmtx" in self.font
+ ), "the 'hmtx' table must be setup before the 'OS/2' table"
+ self.font["OS/2"].recalcAvgCharWidth(self.font)
if not (
"ulUnicodeRange1" in values
or "ulUnicodeRange2" in values
diff --git a/Lib/fontTools/merge/__init__.py b/Lib/fontTools/merge/__init__.py
index 152bf079..97106489 100644
--- a/Lib/fontTools/merge/__init__.py
+++ b/Lib/fontTools/merge/__init__.py
@@ -155,6 +155,11 @@ class Merger(object):
def _postMerge(self, font):
layoutPostMerge(font)
+ if "OS/2" in font:
+ # https://github.com/fonttools/fonttools/issues/2538
+ # TODO: Add an option to disable this?
+ font["OS/2"].recalcAvgCharWidth(font)
+
__all__ = [
'Options',
diff --git a/Lib/fontTools/merge/tables.py b/Lib/fontTools/merge/tables.py
index b266f7a9..ac6d59b5 100644
--- a/Lib/fontTools/merge/tables.py
+++ b/Lib/fontTools/merge/tables.py
@@ -132,7 +132,7 @@ ttLib.getTableClass('OS/2').mergeMap = {
'*': first,
'tableTag': equal,
'version': max,
- 'xAvgCharWidth': avg_int, # Apparently fontTools doesn't recalc this
+ 'xAvgCharWidth': first, # Will be recalculated at the end on the merged font
'fsType': mergeOs2FsType, # Will be overwritten
'panose': first, # FIXME: should really be the first Latin font
'ulUnicodeRange1': bitwise_or,
diff --git a/Lib/fontTools/misc/configTools.py b/Lib/fontTools/misc/configTools.py
new file mode 100644
index 00000000..38bbada2
--- /dev/null
+++ b/Lib/fontTools/misc/configTools.py
@@ -0,0 +1,348 @@
+"""
+Code of the config system; not related to fontTools or fonts in particular.
+
+The options that are specific to fontTools are in :mod:`fontTools.config`.
+
+To create your own config system, you need to create an instance of
+:class:`Options`, and a subclass of :class:`AbstractConfig` with its
+``options`` class variable set to your instance of Options.
+
+"""
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from typing import (
+ Any,
+ Callable,
+ ClassVar,
+ Dict,
+ Iterable,
+ Mapping,
+ MutableMapping,
+ Optional,
+ Set,
+ Union,
+)
+
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "AbstractConfig",
+ "ConfigAlreadyRegisteredError",
+ "ConfigError",
+ "ConfigUnknownOptionError",
+ "ConfigValueParsingError",
+ "ConfigValueValidationError",
+ "Option",
+ "Options",
+]
+
+
+class ConfigError(Exception):
+ """Base exception for the config module."""
+
+
+class ConfigAlreadyRegisteredError(ConfigError):
+ """Raised when a module tries to register a configuration option that
+ already exists.
+
+ Should not be raised too much really, only when developing new fontTools
+ modules.
+ """
+
+ def __init__(self, name):
+ super().__init__(f"Config option {name} is already registered.")
+
+
+class ConfigValueParsingError(ConfigError):
+ """Raised when a configuration value cannot be parsed."""
+
+ def __init__(self, name, value):
+ super().__init__(
+ f"Config option {name}: value cannot be parsed (given {repr(value)})"
+ )
+
+
+class ConfigValueValidationError(ConfigError):
+ """Raised when a configuration value cannot be validated."""
+
+ def __init__(self, name, value):
+ super().__init__(
+ f"Config option {name}: value is invalid (given {repr(value)})"
+ )
+
+
+class ConfigUnknownOptionError(ConfigError):
+ """Raised when a configuration option is unknown."""
+
+ def __init__(self, option_or_name):
+ name = (
+ f"'{option_or_name.name}' (id={id(option_or_name)})>"
+ if isinstance(option_or_name, Option)
+ else f"'{option_or_name}'"
+ )
+ super().__init__(f"Config option {name} is unknown")
+
+
+# eq=False because Options are unique, not fungible objects
+@dataclass(frozen=True, eq=False)
+class Option:
+ name: str
+ """Unique name identifying the option (e.g. package.module:MY_OPTION)."""
+ help: str
+ """Help text for this option."""
+ default: Any
+ """Default value for this option."""
+ parse: Callable[[str], Any]
+ """Turn input (e.g. string) into proper type. Only when reading from file."""
+ validate: Optional[Callable[[Any], bool]] = None
+ """Return true if the given value is an acceptable value."""
+
+ @staticmethod
+ def parse_optional_bool(v: str) -> Optional[bool]:
+ s = str(v).lower()
+ if s in {"0", "no", "false"}:
+ return False
+ if s in {"1", "yes", "true"}:
+ return True
+ if s in {"auto", "none"}:
+ return None
+ raise ValueError("invalid optional bool: {v!r}")
+
+ @staticmethod
+ def validate_optional_bool(v: Any) -> bool:
+ return v is None or isinstance(v, bool)
+
+
+class Options(Mapping):
+ """Registry of available options for a given config system.
+
+ Define new options using the :meth:`register()` method.
+
+ Access existing options using the Mapping interface.
+ """
+
+ __options: Dict[str, Option]
+
+ def __init__(self, other: "Options" = None) -> None:
+ self.__options = {}
+ if other is not None:
+ for option in other.values():
+ self.register_option(option)
+
+ def register(
+ self,
+ name: str,
+ help: str,
+ default: Any,
+ parse: Callable[[str], Any],
+ validate: Optional[Callable[[Any], bool]] = None,
+ ) -> Option:
+ """Create and register a new option."""
+ return self.register_option(Option(name, help, default, parse, validate))
+
+ def register_option(self, option: Option) -> Option:
+ """Register a new option."""
+ name = option.name
+ if name in self.__options:
+ raise ConfigAlreadyRegisteredError(name)
+ self.__options[name] = option
+ return option
+
+ def is_registered(self, option: Option) -> bool:
+ """Return True if the same option object is already registered."""
+ return self.__options.get(option.name) is option
+
+ def __getitem__(self, key: str) -> Option:
+ return self.__options.__getitem__(key)
+
+ def __iter__(self) -> Iterator[str]:
+ return self.__options.__iter__()
+
+ def __len__(self) -> int:
+ return self.__options.__len__()
+
+ def __repr__(self) -> str:
+ return (
+ f"{self.__class__.__name__}({{\n"
+ + "".join(
+ f" {k!r}: Option(default={v.default!r}, ...),\n"
+ for k, v in self.__options.items()
+ )
+ + "})"
+ )
+
+
+_USE_GLOBAL_DEFAULT = object()
+
+
+class AbstractConfig(MutableMapping):
+ """
+ Create a set of config values, optionally pre-filled with values from
+ the given dictionary or pre-existing config object.
+
+ The class implements the MutableMapping protocol keyed by option name (`str`).
+ For convenience its methods accept either Option or str as the key parameter.
+
+ .. seealso:: :meth:`set()`
+
+ This config class is abstract because it needs its ``options`` class
+ var to be set to an instance of :class:`Options` before it can be
+ instanciated and used.
+
+ .. code:: python
+
+ class MyConfig(AbstractConfig):
+ options = Options()
+
+ MyConfig.register_option( "test:option_name", "This is an option", 0, int, lambda v: isinstance(v, int))
+
+ cfg = MyConfig({"test:option_name": 10})
+
+ """
+
+ options: ClassVar[Options]
+
+ @classmethod
+ def register_option(
+ cls,
+ name: str,
+ help: str,
+ default: Any,
+ parse: Callable[[str], Any],
+ validate: Optional[Callable[[Any], bool]] = None,
+ ) -> Option:
+ """Register an available option in this config system."""
+ return cls.options.register(
+ name, help=help, default=default, parse=parse, validate=validate
+ )
+
+ _values: Dict[str, Any]
+
+ def __init__(
+ self,
+ values: Union[AbstractConfig, Dict[Union[Option, str], Any]] = {},
+ parse_values: bool = False,
+ skip_unknown: bool = False,
+ ):
+ self._values = {}
+ values_dict = values._values if isinstance(values, AbstractConfig) else values
+ for name, value in values_dict.items():
+ self.set(name, value, parse_values, skip_unknown)
+
+ def _resolve_option(self, option_or_name: Union[Option, str]) -> Option:
+ if isinstance(option_or_name, Option):
+ option = option_or_name
+ if not self.options.is_registered(option):
+ raise ConfigUnknownOptionError(option)
+ return option
+ elif isinstance(option_or_name, str):
+ name = option_or_name
+ try:
+ return self.options[name]
+ except KeyError:
+ raise ConfigUnknownOptionError(name)
+ else:
+ raise TypeError(
+ "expected Option or str, found "
+ f"{type(option_or_name).__name__}: {option_or_name!r}"
+ )
+
+ def set(
+ self,
+ option_or_name: Union[Option, str],
+ value: Any,
+ parse_values: bool = False,
+ skip_unknown: bool = False,
+ ):
+ """Set the value of an option.
+
+ Args:
+ * `option_or_name`: an `Option` object or its name (`str`).
+ * `value`: the value to be assigned to given option.
+ * `parse_values`: parse the configuration value from a string into
+ its proper type, as per its `Option` object. The default
+ behavior is to raise `ConfigValueValidationError` when the value
+ is not of the right type. Useful when reading options from a
+ file type that doesn't support as many types as Python.
+ * `skip_unknown`: skip unknown configuration options. The default
+ behaviour is to raise `ConfigUnknownOptionError`. Useful when
+ reading options from a configuration file that has extra entries
+ (e.g. for a later version of fontTools)
+ """
+ try:
+ option = self._resolve_option(option_or_name)
+ except ConfigUnknownOptionError as e:
+ if skip_unknown:
+ log.debug(str(e))
+ return
+ raise
+
+ # Can be useful if the values come from a source that doesn't have
+ # strict typing (.ini file? Terminal input?)
+ if parse_values:
+ try:
+ value = option.parse(value)
+ except Exception as e:
+ raise ConfigValueParsingError(option.name, value) from e
+
+ if option.validate is not None and not option.validate(value):
+ raise ConfigValueValidationError(option.name, value)
+
+ self._values[option.name] = value
+
+ def get(
+ self, option_or_name: Union[Option, str], default: Any = _USE_GLOBAL_DEFAULT
+ ) -> Any:
+ """
+ Get the value of an option. The value which is returned is the first
+ provided among:
+
+ 1. a user-provided value in the options's ``self._values`` dict
+ 2. a caller-provided default value to this method call
+ 3. the global default for the option provided in ``fontTools.config``
+
+ This is to provide the ability to migrate progressively from config
+ options passed as arguments to fontTools APIs to config options read
+ from the current TTFont, e.g.
+
+ .. code:: python
+
+ def fontToolsAPI(font, some_option):
+ value = font.cfg.get("someLib.module:SOME_OPTION", some_option)
+ # use value
+
+ That way, the function will work the same for users of the API that
+ still pass the option to the function call, but will favour the new
+ config mechanism if the given font specifies a value for that option.
+ """
+ option = self._resolve_option(option_or_name)
+ if option.name in self._values:
+ return self._values[option.name]
+ if default is not _USE_GLOBAL_DEFAULT:
+ return default
+ return option.default
+
+ def copy(self):
+ return self.__class__(self._values)
+
+ def __getitem__(self, option_or_name: Union[Option, str]) -> Any:
+ return self.get(option_or_name)
+
+ def __setitem__(self, option_or_name: Union[Option, str], value: Any) -> None:
+ return self.set(option_or_name, value)
+
+ def __delitem__(self, option_or_name: Union[Option, str]) -> None:
+ option = self._resolve_option(option_or_name)
+ del self._values[option.name]
+
+ def __iter__(self) -> Iterable[str]:
+ return self._values.__iter__()
+
+ def __len__(self) -> int:
+ return len(self._values)
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}({repr(self._values)})"
diff --git a/Lib/fontTools/misc/psCharStrings.py b/Lib/fontTools/misc/psCharStrings.py
index 29c2d365..549dae25 100644
--- a/Lib/fontTools/misc/psCharStrings.py
+++ b/Lib/fontTools/misc/psCharStrings.py
@@ -502,11 +502,20 @@ class T2OutlineExtractor(T2WidthExtractor):
T2WidthExtractor.__init__(
self, localSubrs, globalSubrs, nominalWidthX, defaultWidthX, private)
self.pen = pen
+ self.subrLevel = 0
def reset(self):
T2WidthExtractor.reset(self)
self.currentPoint = (0, 0)
self.sawMoveTo = 0
+ self.subrLevel = 0
+
+ def execute(self, charString):
+ self.subrLevel += 1
+ super().execute(charString)
+ self.subrLevel -= 1
+ if self.subrLevel == 0:
+ self.endPath()
def _nextPoint(self, point):
x, y = self.currentPoint
@@ -536,8 +545,11 @@ class T2OutlineExtractor(T2WidthExtractor):
def endPath(self):
# In T2 there are no open paths, so always do a closePath when
- # finishing a sub path.
- self.closePath()
+ # finishing a sub path. We avoid spurious calls to closePath()
+ # because its a real T1 op we're emulating in T2 whereas
+ # endPath() is just a means to that emulation
+ if self.sawMoveTo:
+ self.closePath()
#
# hint operators
diff --git a/Lib/fontTools/misc/testTools.py b/Lib/fontTools/misc/testTools.py
index db316a82..871a9951 100644
--- a/Lib/fontTools/misc/testTools.py
+++ b/Lib/fontTools/misc/testTools.py
@@ -3,10 +3,12 @@
from collections.abc import Iterable
from io import BytesIO
import os
+import re
import shutil
import sys
import tempfile
from unittest import TestCase as _TestCase
+from fontTools.config import Config
from fontTools.misc.textTools import tobytes
from fontTools.misc.xmlWriter import XMLWriter
@@ -52,6 +54,7 @@ class FakeFont:
self.reverseGlyphOrderDict_ = {g: i for i, g in enumerate(glyphs)}
self.lazy = False
self.tables = {}
+ self.cfg = Config()
def __getitem__(self, tag):
return self.tables[tag]
@@ -133,6 +136,31 @@ def getXML(func, ttFont=None):
return xml.splitlines()
+def stripVariableItemsFromTTX(
+ string: str,
+ ttLibVersion: bool = True,
+ checkSumAdjustment: bool = True,
+ modified: bool = True,
+ created: bool = True,
+ sfntVersion: bool = False, # opt-in only
+) -> str:
+ """Strip stuff like ttLibVersion, checksums, timestamps, etc. from TTX dumps."""
+ # ttlib changes with the fontTools version
+ if ttLibVersion:
+ string = re.sub(' ttLibVersion="[^"]+"', "", string)
+ # sometimes (e.g. some subsetter tests) we don't care whether it's OTF or TTF
+ if sfntVersion:
+ string = re.sub(' sfntVersion="[^"]+"', "", string)
+ # head table checksum and creation and mod date changes with each save.
+ if checkSumAdjustment:
+ string = re.sub('<checkSumAdjustment value="[^"]+"/>', "", string)
+ if modified:
+ string = re.sub('<modified value="[^"]+"/>', "", string)
+ if created:
+ string = re.sub('<created value="[^"]+"/>', "", string)
+ return string
+
+
class MockFont(object):
"""A font-like object that automatically adds any looked up glyphname
to its glyphOrder."""
diff --git a/Lib/fontTools/otlLib/builder.py b/Lib/fontTools/otlLib/builder.py
index e3f33551..233edec2 100644
--- a/Lib/fontTools/otlLib/builder.py
+++ b/Lib/fontTools/otlLib/builder.py
@@ -12,8 +12,7 @@ from fontTools.ttLib.tables.otBase import (
from fontTools.ttLib.tables import otBase
from fontTools.feaLib.ast import STATNameStatement
from fontTools.otlLib.optimize.gpos import (
- GPOS_COMPACT_MODE_DEFAULT,
- GPOS_COMPACT_MODE_ENV_KEY,
+ _compression_level_from_env,
compact_lookup,
)
from fontTools.otlLib.error import OpenTypeLibError
@@ -367,9 +366,15 @@ class ChainContextualBuilder(LookupBuilder):
contextual positioning lookup.
"""
subtables = []
- chaining = False
+
rulesets = self.rulesets()
chaining = any(ruleset.hasPrefixOrSuffix for ruleset in rulesets)
+ # Unfortunately, as of 2022-03-07, Apple's CoreText renderer does not
+ # correctly process GPOS7 lookups, so for now we force contextual
+ # positioning lookups to be chaining (GPOS8).
+ if self.subtable_type == "Pos": # horrible separation of concerns breach
+ chaining = True
+
for ruleset in rulesets:
# Determine format strategy. We try to build formats 1, 2 and 3
# subtables and then work out which is best. candidates list holds
@@ -1408,10 +1413,14 @@ class PairPosBuilder(LookupBuilder):
# Compact the lookup
# This is a good moment to do it because the compaction should create
# smaller subtables, which may prevent overflows from happening.
- mode = os.environ.get(GPOS_COMPACT_MODE_ENV_KEY, GPOS_COMPACT_MODE_DEFAULT)
- if mode and mode != "0":
+ # Keep reading the value from the ENV until ufo2ft switches to the config system
+ level = self.font.cfg.get(
+ "fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL",
+ default=_compression_level_from_env(),
+ )
+ if level != 0:
log.info("Compacting GPOS...")
- compact_lookup(self.font, mode, lookup)
+ compact_lookup(self.font, level, lookup)
return lookup
diff --git a/Lib/fontTools/otlLib/optimize/__init__.py b/Lib/fontTools/otlLib/optimize/__init__.py
index 5c007e89..a9512fb0 100644
--- a/Lib/fontTools/otlLib/optimize/__init__.py
+++ b/Lib/fontTools/otlLib/optimize/__init__.py
@@ -1,39 +1,27 @@
from argparse import RawTextHelpFormatter
-from textwrap import dedent
-
+from fontTools.otlLib.optimize.gpos import COMPRESSION_LEVEL, compact
from fontTools.ttLib import TTFont
-from fontTools.otlLib.optimize.gpos import compact, GPOS_COMPACT_MODE_DEFAULT
+
def main(args=None):
"""Optimize the layout tables of an existing font."""
from argparse import ArgumentParser
+
from fontTools import configLogger
- parser = ArgumentParser(prog="otlLib.optimize", description=main.__doc__, formatter_class=RawTextHelpFormatter)
+ parser = ArgumentParser(
+ prog="otlLib.optimize",
+ description=main.__doc__,
+ formatter_class=RawTextHelpFormatter,
+ )
parser.add_argument("font")
parser.add_argument(
"-o", metavar="OUTPUTFILE", dest="outfile", default=None, help="output file"
)
parser.add_argument(
- "--gpos-compact-mode",
- help=dedent(
- f"""\
- GPOS Lookup type 2 (PairPos) compaction mode:
- 0 = do not attempt to compact PairPos lookups;
- 1 to 8 = create at most 1 to 8 new subtables for each existing
- subtable, provided that it would yield a 50%% file size saving;
- 9 = create as many new subtables as needed to yield a file size saving.
- Default: {GPOS_COMPACT_MODE_DEFAULT}.
-
- This compaction aims to save file size, by splitting large class
- kerning subtables (Format 2) that contain many zero values into
- smaller and denser subtables. It's a trade-off between the overhead
- of several subtables versus the sparseness of one big subtable.
-
- See the pull request: https://github.com/fonttools/fonttools/pull/2326
- """
- ),
- default=int(GPOS_COMPACT_MODE_DEFAULT),
+ "--gpos-compression-level",
+ help=COMPRESSION_LEVEL.help,
+ default=COMPRESSION_LEVEL.default,
choices=list(range(10)),
type=int,
)
@@ -51,12 +39,10 @@ def main(args=None):
)
font = TTFont(options.font)
- # TODO: switch everything to have type(mode) = int when using the Config class
- compact(font, str(options.gpos_compact_mode))
+ compact(font, options.gpos_compression_level)
font.save(options.outfile or options.font)
-
if __name__ == "__main__":
import sys
@@ -65,4 +51,3 @@ if __name__ == "__main__":
import doctest
sys.exit(doctest.testmod().failed)
-
diff --git a/Lib/fontTools/otlLib/optimize/gpos.py b/Lib/fontTools/otlLib/optimize/gpos.py
index 79873fad..0acd9ed0 100644
--- a/Lib/fontTools/otlLib/optimize/gpos.py
+++ b/Lib/fontTools/otlLib/optimize/gpos.py
@@ -1,24 +1,45 @@
import logging
+import os
from collections import defaultdict, namedtuple
from functools import reduce
from itertools import chain
from math import log2
from typing import DefaultDict, Dict, Iterable, List, Sequence, Tuple
+from fontTools.config import OPTIONS
from fontTools.misc.intTools import bit_count, bit_indices
from fontTools.ttLib import TTFont
from fontTools.ttLib.tables import otBase, otTables
-# NOTE: activating this optimization via the environment variable is
-# experimental and may not be supported once an alternative mechanism
-# is in place. See: https://github.com/fonttools/fonttools/issues/2349
+log = logging.getLogger(__name__)
+
+COMPRESSION_LEVEL = OPTIONS[f"{__name__}:COMPRESSION_LEVEL"]
+
+# Kept because ufo2ft depends on it, to be removed once ufo2ft uses the config instead
+# https://github.com/fonttools/fonttools/issues/2592
GPOS_COMPACT_MODE_ENV_KEY = "FONTTOOLS_GPOS_COMPACT_MODE"
-GPOS_COMPACT_MODE_DEFAULT = "0"
+GPOS_COMPACT_MODE_DEFAULT = str(COMPRESSION_LEVEL.default)
+
-log = logging.getLogger("fontTools.otlLib.optimize.gpos")
+def _compression_level_from_env() -> int:
+ env_level = GPOS_COMPACT_MODE_DEFAULT
+ if GPOS_COMPACT_MODE_ENV_KEY in os.environ:
+ import warnings
+
+ warnings.warn(
+ f"'{GPOS_COMPACT_MODE_ENV_KEY}' environment variable is deprecated. "
+ "Please set the 'fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL' option "
+ "in TTFont.cfg.",
+ DeprecationWarning,
+ )
+ env_level = os.environ[GPOS_COMPACT_MODE_ENV_KEY]
+ if len(env_level) == 1 and env_level in "0123456789":
+ return int(env_level)
+ raise ValueError(f"Bad {GPOS_COMPACT_MODE_ENV_KEY}={env_level}")
-def compact(font: TTFont, mode: str) -> TTFont:
+
+def compact(font: TTFont, level: int) -> TTFont:
# Ideal plan:
# 1. Find lookups of Lookup Type 2: Pair Adjustment Positioning Subtable
# https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-2-pair-adjustment-positioning-subtable
@@ -35,21 +56,21 @@ def compact(font: TTFont, mode: str) -> TTFont:
gpos = font["GPOS"]
for lookup in gpos.table.LookupList.Lookup:
if lookup.LookupType == 2:
- compact_lookup(font, mode, lookup)
+ compact_lookup(font, level, lookup)
elif lookup.LookupType == 9 and lookup.SubTable[0].ExtensionLookupType == 2:
- compact_ext_lookup(font, mode, lookup)
+ compact_ext_lookup(font, level, lookup)
return font
-def compact_lookup(font: TTFont, mode: str, lookup: otTables.Lookup) -> None:
- new_subtables = compact_pair_pos(font, mode, lookup.SubTable)
+def compact_lookup(font: TTFont, level: int, lookup: otTables.Lookup) -> None:
+ new_subtables = compact_pair_pos(font, level, lookup.SubTable)
lookup.SubTable = new_subtables
lookup.SubTableCount = len(new_subtables)
-def compact_ext_lookup(font: TTFont, mode: str, lookup: otTables.Lookup) -> None:
+def compact_ext_lookup(font: TTFont, level: int, lookup: otTables.Lookup) -> None:
new_subtables = compact_pair_pos(
- font, mode, [ext_subtable.ExtSubTable for ext_subtable in lookup.SubTable]
+ font, level, [ext_subtable.ExtSubTable for ext_subtable in lookup.SubTable]
)
new_ext_subtables = []
for subtable in new_subtables:
@@ -62,7 +83,7 @@ def compact_ext_lookup(font: TTFont, mode: str, lookup: otTables.Lookup) -> None
def compact_pair_pos(
- font: TTFont, mode: str, subtables: Sequence[otTables.PairPos]
+ font: TTFont, level: int, subtables: Sequence[otTables.PairPos]
) -> Sequence[otTables.PairPos]:
new_subtables = []
for subtable in subtables:
@@ -70,12 +91,12 @@ def compact_pair_pos(
# Not doing anything to Format 1 (yet?)
new_subtables.append(subtable)
elif subtable.Format == 2:
- new_subtables.extend(compact_class_pairs(font, mode, subtable))
+ new_subtables.extend(compact_class_pairs(font, level, subtable))
return new_subtables
def compact_class_pairs(
- font: TTFont, mode: str, subtable: otTables.PairPos
+ font: TTFont, level: int, subtable: otTables.PairPos
) -> List[otTables.PairPos]:
from fontTools.otlLib.builder import buildPairPosClassesSubtable
@@ -95,17 +116,9 @@ def compact_class_pairs(
getattr(class2, "Value1", None),
getattr(class2, "Value2", None),
)
-
- if len(mode) == 1 and mode in "123456789":
- grouped_pairs = cluster_pairs_by_class2_coverage_custom_cost(
- font, all_pairs, int(mode)
- )
- for pairs in grouped_pairs:
- subtables.append(
- buildPairPosClassesSubtable(pairs, font.getReverseGlyphMap())
- )
- else:
- raise ValueError(f"Bad {GPOS_COMPACT_MODE_ENV_KEY}={mode}")
+ grouped_pairs = cluster_pairs_by_class2_coverage_custom_cost(font, all_pairs, level)
+ for pairs in grouped_pairs:
+ subtables.append(buildPairPosClassesSubtable(pairs, font.getReverseGlyphMap()))
return subtables
diff --git a/Lib/fontTools/subset/__init__.py b/Lib/fontTools/subset/__init__.py
index 53b440da..56d9c0ef 100644
--- a/Lib/fontTools/subset/__init__.py
+++ b/Lib/fontTools/subset/__init__.py
@@ -2,9 +2,11 @@
#
# Google Author(s): Behdad Esfahbod
+from fontTools import config
from fontTools.misc.roundTools import otRound
from fontTools import ttLib
from fontTools.ttLib.tables import otTables
+from fontTools.ttLib.tables.otBase import USE_HARFBUZZ_REPACKER
from fontTools.otlLib.maxContextCalc import maxCtxFont
from fontTools.pens.basePen import NullPen
from fontTools.misc.loggingTools import Timer
@@ -144,6 +146,15 @@ Output options
The Zopfli Python bindings are available at:
https://pypi.python.org/pypi/zopfli
+--harfbuzz-repacker
+ By default, we serialize GPOS/GSUB using the HarfBuzz Repacker when
+ uharfbuzz can be imported and is successful, otherwise fall back to
+ the pure-python serializer. Set the option to force using the HarfBuzz
+ Repacker (raises an error if uharfbuzz can't be found or fails).
+
+--no-harfbuzz-repacker
+ Always use the pure-python serializer even if uharfbuzz is available.
+
Glyph set expansion
^^^^^^^^^^^^^^^^^^^
@@ -2642,6 +2653,7 @@ class Options(object):
self.flavor = None # May be 'woff' or 'woff2'
self.with_zopfli = False # use zopfli instead of zlib for WOFF 1.0
self.desubroutinize = False # Desubroutinize CFF CharStrings
+ self.harfbuzz_repacker = USE_HARFBUZZ_REPACKER.default
self.verbose = False
self.timing = False
self.xml = False
@@ -2964,11 +2976,10 @@ class Subsetter(object):
if old_uniranges != new_uniranges:
log.info("%s Unicode ranges pruned: %s", tag, sorted(new_uniranges))
if self.options.recalc_average_width:
- widths = [m[0] for m in font["hmtx"].metrics.values() if m[0] > 0]
- avg_width = otRound(sum(widths) / len(widths))
- if avg_width != font[tag].xAvgCharWidth:
- font[tag].xAvgCharWidth = avg_width
- log.info("%s xAvgCharWidth updated: %d", tag, avg_width)
+ old_avg_width = font[tag].xAvgCharWidth
+ new_avg_width = font[tag].recalcAvgCharWidth(font)
+ if old_avg_width != new_avg_width:
+ log.info("%s xAvgCharWidth updated: %d", tag, new_avg_width)
if self.options.recalc_max_context:
max_context = maxCtxFont(font)
if max_context != font[tag].usMaxContext:
@@ -3038,6 +3049,7 @@ def save_font(font, outfile, options):
from fontTools.ttLib import sfnt
sfnt.USE_ZOPFLI = True
font.flavor = options.flavor
+ font.cfg[USE_HARFBUZZ_REPACKER] = options.harfbuzz_repacker
font.save(outfile, reorderTables=options.canonical_order)
def parse_unicodes(s):
diff --git a/Lib/fontTools/ttLib/tables/O_S_2f_2.py b/Lib/fontTools/ttLib/tables/O_S_2f_2.py
index a5765224..ba2e3961 100644
--- a/Lib/fontTools/ttLib/tables/O_S_2f_2.py
+++ b/Lib/fontTools/ttLib/tables/O_S_2f_2.py
@@ -1,4 +1,5 @@
from fontTools.misc import sstruct
+from fontTools.misc.roundTools import otRound
from fontTools.misc.textTools import safeEval, num2binary, binary2num
from fontTools.ttLib.tables import DefaultTable
import bisect
@@ -299,6 +300,19 @@ class table_O_S_2f_2(DefaultTable.DefaultTable):
self.setUnicodeRanges(bits)
return bits
+ def recalcAvgCharWidth(self, ttFont):
+ """Recalculate xAvgCharWidth using metrics from ttFont's 'hmtx' table.
+
+ Set it to 0 if the unlikely event 'hmtx' table is not found.
+ """
+ avg_width = 0
+ hmtx = ttFont.get("hmtx")
+ if hmtx:
+ widths = [m[0] for m in hmtx.metrics.values() if m[0] > 0]
+ avg_width = otRound(sum(widths) / len(widths))
+ self.xAvgCharWidth = avg_width
+ return avg_width
+
# Unicode ranges data from the OpenType OS/2 table specification v1.7
diff --git a/Lib/fontTools/ttLib/tables/_c_m_a_p.py b/Lib/fontTools/ttLib/tables/_c_m_a_p.py
index a31b5059..9bd59a6b 100644
--- a/Lib/fontTools/ttLib/tables/_c_m_a_p.py
+++ b/Lib/fontTools/ttLib/tables/_c_m_a_p.py
@@ -91,6 +91,11 @@ class table__c_m_a_p(DefaultTable.DefaultTable):
(0, 1), # Unicode 1.1
(0, 0) # Unicode 1.0
+ This particular order matches what HarfBuzz uses to choose what
+ subtable to use by default. This order prefers the largest-repertoire
+ subtable, and among those, prefers the Windows-platform over the
+ Unicode-platform as the former has wider support.
+
This order can be customized via the ``cmapPreferences`` argument.
"""
for platformID, platEncID in cmapPreferences:
@@ -172,13 +177,11 @@ class table__c_m_a_p(DefaultTable.DefaultTable):
seen = {} # Some tables are the same object reference. Don't compile them twice.
done = {} # Some tables are different objects, but compile to the same data chunk
for table in self.tables:
- try:
- offset = seen[id(table.cmap)]
- except KeyError:
+ offset = seen.get(id(table.cmap))
+ if offset is None:
chunk = table.compile(ttFont)
- if chunk in done:
- offset = done[chunk]
- else:
+ offset = done.get(chunk)
+ if offset is None:
offset = seen[id(table.cmap)] = done[chunk] = totalOffset + len(tableData)
tableData = tableData + chunk
data = data + struct.pack(">HHl", table.platformID, table.platEncID, offset)
@@ -800,7 +803,6 @@ class cmap_format_4(CmapSubtable):
start = startCode[i]
delta = idDelta[i]
rangeOffset = idRangeOffset[i]
- # *someone* needs to get killed.
partial = rangeOffset // 2 - start + i - len(idRangeOffset)
rangeCharCodes = list(range(startCode[i], endCode[i] + 1))
@@ -891,7 +893,6 @@ class cmap_format_4(CmapSubtable):
idDelta.append((indices[0] - startCode[i]) % 0x10000)
idRangeOffset.append(0)
else:
- # someone *definitely* needs to get killed.
idDelta.append(0)
idRangeOffset.append(2 * (len(endCode) + len(glyphIndexArray) - i))
glyphIndexArray.extend(indices)
diff --git a/Lib/fontTools/ttLib/tables/otBase.py b/Lib/fontTools/ttLib/tables/otBase.py
index bc2c9fba..d30892f3 100644
--- a/Lib/fontTools/ttLib/tables/otBase.py
+++ b/Lib/fontTools/ttLib/tables/otBase.py
@@ -1,3 +1,4 @@
+from fontTools.config import OPTIONS
from fontTools.misc.textTools import Tag, bytesjoin
from .DefaultTable import DefaultTable
import sys
@@ -8,6 +9,15 @@ from typing import Iterator, NamedTuple, Optional
log = logging.getLogger(__name__)
+have_uharfbuzz = False
+try:
+ import uharfbuzz as hb
+ have_uharfbuzz = True
+except ImportError:
+ pass
+
+USE_HARFBUZZ_REPACKER = OPTIONS[f"{__name__}:USE_HARFBUZZ_REPACKER"]
+
class OverflowErrorRecord(object):
def __init__(self, overflowTuple):
self.tableType = overflowTuple[0]
@@ -66,11 +76,56 @@ class BaseTTXConverter(DefaultTable):
# If a lookup subtable overflows an offset, we have to start all over.
overflowRecord = None
+ # this is 3-state option: default (None) means automatically use hb.repack or
+ # silently fall back if it fails; True, use it and raise error if not possible
+ # or it errors out; False, don't use it, even if you can.
+ use_hb_repack = font.cfg[USE_HARFBUZZ_REPACKER]
+ if self.tableTag in ("GSUB", "GPOS"):
+ if use_hb_repack is False:
+ log.debug(
+ "hb.repack disabled, compiling '%s' with pure-python serializer",
+ self.tableTag,
+ )
+ elif not have_uharfbuzz:
+ if use_hb_repack is True:
+ raise ImportError("No module named 'uharfbuzz'")
+ else:
+ assert use_hb_repack is None
+ log.debug(
+ "uharfbuzz not found, compiling '%s' with pure-python serializer",
+ self.tableTag,
+ )
+ hb_first_error_logged = False
while True:
try:
writer = OTTableWriter(tableTag=self.tableTag)
self.table.compile(writer, font)
+ if (
+ use_hb_repack in (None, True)
+ and have_uharfbuzz
+ and self.tableTag in ("GSUB", "GPOS")
+ ):
+ try:
+ log.debug("serializing '%s' with hb.repack", self.tableTag)
+ return writer.getAllDataUsingHarfbuzz()
+ except (ValueError, MemoryError, hb.RepackerError) as e:
+ # Only log hb repacker errors the first time they occur in
+ # the offset-overflow resolution loop, they are just noisy.
+ # Maybe we can revisit this if/when uharfbuzz actually gives
+ # us more info as to why hb.repack failed...
+ if not hb_first_error_logged:
+ error_msg = f"{type(e).__name__}"
+ if str(e) != "":
+ error_msg += f": {e}"
+ log.warning(
+ "hb.repack failed to serialize '%s', reverting to "
+ "pure-python serializer; the error message was: %s",
+ self.tableTag,
+ error_msg,
+ )
+ hb_first_error_logged = True
+ return writer.getAllData(remove_duplicate=False)
return writer.getAllData()
except OTLOffsetOverflowError as e:
@@ -298,6 +353,20 @@ class OTTableWriter(object):
return bytesjoin(items)
+ def getDataForHarfbuzz(self):
+ """Assemble the data for this writer/table with all offset field set to 0"""
+ items = list(self.items)
+ packFuncs = {2: packUShort, 3: packUInt24, 4: packULong}
+ for i, item in enumerate(items):
+ if hasattr(item, "getData"):
+ # Offset value is not needed in harfbuzz repacker, so setting offset to 0 to avoid overflow here
+ if item.offsetSize in packFuncs:
+ items[i] = packFuncs[item.offsetSize](0)
+ else:
+ raise ValueError(item.offsetSize)
+
+ return bytesjoin(items)
+
def __hash__(self):
# only works after self._doneWriting() has been called
return hash(self.items)
@@ -402,11 +471,95 @@ class OTTableWriter(object):
selfTables.append(self)
- def getAllData(self):
- """Assemble all data, including all subtables."""
+ def _gatherGraphForHarfbuzz(self, tables, obj_list, done, objidx, virtual_edges):
+ real_links = []
+ virtual_links = []
+ item_idx = objidx
+
+ # Merge virtual_links from parent
+ for idx in virtual_edges:
+ virtual_links.append((0, 0, idx))
+
+ sortCoverageLast = False
+ coverage_idx = 0
+ if hasattr(self, "sortCoverageLast"):
+ # Find coverage table
+ for i, item in enumerate(self.items):
+ if getattr(item, 'name', None) == "Coverage":
+ sortCoverageLast = True
+ if id(item) not in done:
+ coverage_idx = item_idx = item._gatherGraphForHarfbuzz(tables, obj_list, done, item_idx, virtual_edges)
+ else:
+ coverage_idx = done[id(item)]
+ virtual_edges.append(coverage_idx)
+ break
+
+ child_idx = 0
+ offset_pos = 0
+ for i, item in enumerate(self.items):
+ if hasattr(item, "getData"):
+ pos = offset_pos
+ elif hasattr(item, "getCountData"):
+ offset_pos += item.size
+ continue
+ else:
+ offset_pos = offset_pos + len(item)
+ continue
+
+ if id(item) not in done:
+ child_idx = item_idx = item._gatherGraphForHarfbuzz(tables, obj_list, done, item_idx, virtual_edges)
+ else:
+ child_idx = done[id(item)]
+
+ real_edge = (pos, item.offsetSize, child_idx)
+ real_links.append(real_edge)
+ offset_pos += item.offsetSize
+
+ tables.append(self)
+ obj_list.append((real_links,virtual_links))
+ item_idx += 1
+ done[id(self)] = item_idx
+ if sortCoverageLast:
+ virtual_edges.pop()
+
+ return item_idx
+
+ def getAllDataUsingHarfbuzz(self):
+ """The Whole table is represented as a Graph.
+ Assemble graph data and call Harfbuzz repacker to pack the table.
+ Harfbuzz repacker is faster and retain as much sub-table sharing as possible, see also:
+ https://github.com/harfbuzz/harfbuzz/blob/main/docs/repacker.md
+ The input format for hb.repack() method is explained here:
+ https://github.com/harfbuzz/uharfbuzz/blob/main/src/uharfbuzz/_harfbuzz.pyx#L1149
+ """
internedTables = {}
self._doneWriting(internedTables)
tables = []
+ obj_list = []
+ done = {}
+ objidx = 0
+ virtual_edges = []
+ self._gatherGraphForHarfbuzz(tables, obj_list, done, objidx, virtual_edges)
+ # Gather all data in two passes: the absolute positions of all
+ # subtable are needed before the actual data can be assembled.
+ pos = 0
+ for table in tables:
+ table.pos = pos
+ pos = pos + table.getDataLength()
+
+ data = []
+ for table in tables:
+ tableData = table.getDataForHarfbuzz()
+ data.append(tableData)
+
+ return hb.repack(data, obj_list)
+
+ def getAllData(self, remove_duplicate=True):
+ """Assemble all data, including all subtables."""
+ if remove_duplicate:
+ internedTables = {}
+ self._doneWriting(internedTables)
+ tables = []
extTables = []
done = {}
self._gatherTables(tables, extTables, done)
diff --git a/Lib/fontTools/ttLib/ttFont.py b/Lib/fontTools/ttLib/ttFont.py
index 3929e2f3..d7f7ef83 100644
--- a/Lib/fontTools/ttLib/ttFont.py
+++ b/Lib/fontTools/ttLib/ttFont.py
@@ -1,4 +1,6 @@
+from fontTools.config import Config
from fontTools.misc import xmlWriter
+from fontTools.misc.configTools import AbstractConfig
from fontTools.misc.textTools import Tag, byteord, tostr
from fontTools.misc.loggingTools import deprecateArgument
from fontTools.ttLib import TTLibError
@@ -49,7 +51,7 @@ class TTFont(object):
>> tt2.importXML("afont.ttx")
>> tt2['maxp'].numGlyphs
242
-
+
The TTFont object may be used as a context manager; this will cause the file
reader to be closed after the context ``with`` block is exited::
@@ -89,7 +91,7 @@ class TTFont(object):
sfntVersion="\000\001\000\000", flavor=None, checkChecksums=0,
verbose=None, recalcBBoxes=True, allowVID=NotImplemented, ignoreDecompileErrors=False,
recalcTimestamp=True, fontNumber=-1, lazy=None, quiet=None,
- _tableCache=None):
+ _tableCache=None, cfg={}):
for name in ("verbose", "quiet"):
val = locals().get(name)
if val is not None:
@@ -101,6 +103,7 @@ class TTFont(object):
self.recalcTimestamp = recalcTimestamp
self.tables = {}
self.reader = None
+ self.cfg = cfg.copy() if isinstance(cfg, AbstractConfig) else Config(cfg)
self.ignoreDecompileErrors = ignoreDecompileErrors
if not file:
@@ -698,22 +701,27 @@ class TTFont(object):
return glyphs
def getBestCmap(self, cmapPreferences=((3, 10), (0, 6), (0, 4), (3, 1), (0, 3), (0, 2), (0, 1), (0, 0))):
- """Return the 'best' unicode cmap dictionary available in the font,
- or None, if no unicode cmap subtable is available.
+ """Returns the 'best' Unicode cmap dictionary available in the font
+ or ``None``, if no Unicode cmap subtable is available.
By default it will search for the following (platformID, platEncID)
- pairs::
-
- (3, 10),
- (0, 6),
- (0, 4),
- (3, 1),
- (0, 3),
- (0, 2),
- (0, 1),
- (0, 0)
-
- This can be customized via the ``cmapPreferences`` argument.
+ pairs in order::
+
+ (3, 10), # Windows Unicode full repertoire
+ (0, 6), # Unicode full repertoire (format 13 subtable)
+ (0, 4), # Unicode 2.0 full repertoire
+ (3, 1), # Windows Unicode BMP
+ (0, 3), # Unicode 2.0 BMP
+ (0, 2), # Unicode ISO/IEC 10646
+ (0, 1), # Unicode 1.1
+ (0, 0) # Unicode 1.0
+
+ This particular order matches what HarfBuzz uses to choose what
+ subtable to use by default. This order prefers the largest-repertoire
+ subtable, and among those, prefers the Windows-platform over the
+ Unicode-platform as the former has wider support.
+
+ This order can be customized via the ``cmapPreferences`` argument.
"""
return self["cmap"].getBestCmap(cmapPreferences=cmapPreferences)
diff --git a/Lib/fontTools/ufoLib/glifLib.py b/Lib/fontTools/ufoLib/glifLib.py
index 44622a14..89c9176a 100755
--- a/Lib/fontTools/ufoLib/glifLib.py
+++ b/Lib/fontTools/ufoLib/glifLib.py
@@ -95,11 +95,11 @@ class Glyph:
self.glyphName = glyphName
self.glyphSet = glyphSet
- def draw(self, pen):
+ def draw(self, pen, outputImpliedClosingLine=False):
"""
Draw this glyph onto a *FontTools* Pen.
"""
- pointPen = PointToSegmentPen(pen)
+ pointPen = PointToSegmentPen(pen, outputImpliedClosingLine=outputImpliedClosingLine)
self.drawPoints(pointPen)
def drawPoints(self, pointPen):
diff --git a/Lib/fontTools/varLib/__init__.py b/Lib/fontTools/varLib/__init__.py
index 15c2e700..4029a107 100644
--- a/Lib/fontTools/varLib/__init__.py
+++ b/Lib/fontTools/varLib/__init__.py
@@ -18,6 +18,7 @@ Then you can make a variable-font this way:
API *will* change in near future.
"""
+from typing import List
from fontTools.misc.vector import Vector
from fontTools.misc.roundTools import noRound, otRound
from fontTools.misc.textTools import Tag, tostr
@@ -33,7 +34,9 @@ from fontTools.varLib.merger import VariationMerger
from fontTools.varLib.mvar import MVAR_ENTRIES
from fontTools.varLib.iup import iup_delta_optimize
from fontTools.varLib.featureVars import addFeatureVariations
-from fontTools.designspaceLib import DesignSpaceDocument
+from fontTools.designspaceLib import DesignSpaceDocument, InstanceDescriptor
+from fontTools.designspaceLib.split import splitInterpolable, splitVariableFonts
+from fontTools.varLib.stat import buildVFStatTable
from functools import partial
from collections import OrderedDict, namedtuple
import os.path
@@ -53,7 +56,7 @@ FEAVAR_FEATURETAG_LIB_KEY = "com.github.fonttools.varLib.featureVarsFeatureTag"
# Creation routines
#
-def _add_fvar(font, axes, instances):
+def _add_fvar(font, axes, instances: List[InstanceDescriptor]):
"""
Add 'fvar' table to font.
@@ -81,7 +84,8 @@ def _add_fvar(font, axes, instances):
fvar.axes.append(axis)
for instance in instances:
- coordinates = instance.location
+ # Filter out discrete axis locations
+ coordinates = {name: value for name, value in instance.location.items() if name in axes}
if "en" not in instance.localisedStyleName:
if not instance.styleName:
@@ -198,11 +202,10 @@ def _add_avar(font, axes):
return avar
-def _add_stat(font, axes):
- # for now we just get the axis tags and nameIDs from the fvar,
- # so we can reuse the same nameIDs which were defined in there.
- # TODO make use of 'axes' once it adds style attributes info:
- # https://github.com/LettError/designSpaceDocument/issues/8
+def _add_stat(font):
+ # Note: this function only gets called by old code that calls `build()`
+ # directly. Newer code that wants to benefit from STAT data from the
+ # designspace should call `build_many()`
if "STAT" in font:
return
@@ -759,7 +762,8 @@ def load_designspace(designspace):
# Check all master and instance locations are valid and fill in defaults
for obj in masters+instances:
obj_name = obj.name or obj.styleName or ''
- loc = obj.location
+ loc = obj.getFullDesignLocation(ds)
+ obj.designLocation = loc
if loc is None:
raise VarLibValidationError(
f"Source or instance '{obj_name}' has no location."
@@ -770,22 +774,18 @@ def load_designspace(designspace):
f"Location axis '{axis_name}' unknown for '{obj_name}'."
)
for axis_name,axis in axes.items():
- if axis_name not in loc:
- # NOTE: `axis.default` is always user-space, but `obj.location` always design-space.
- loc[axis_name] = axis.map_forward(axis.default)
- else:
- v = axis.map_backward(loc[axis_name])
- if not (axis.minimum <= v <= axis.maximum):
- raise VarLibValidationError(
- f"Source or instance '{obj_name}' has out-of-range location "
- f"for axis '{axis_name}': is mapped to {v} but must be in "
- f"mapped range [{axis.minimum}..{axis.maximum}] (NOTE: all "
- "values are in user-space)."
- )
+ v = axis.map_backward(loc[axis_name])
+ if not (axis.minimum <= v <= axis.maximum):
+ raise VarLibValidationError(
+ f"Source or instance '{obj_name}' has out-of-range location "
+ f"for axis '{axis_name}': is mapped to {v} but must be in "
+ f"mapped range [{axis.minimum}..{axis.maximum}] (NOTE: all "
+ "values are in user-space)."
+ )
# Normalize master locations
- internal_master_locs = [o.location for o in masters]
+ internal_master_locs = [o.getFullDesignLocation(ds) for o in masters]
log.info("Internal master locations:\n%s", pformat(internal_master_locs))
# TODO This mapping should ideally be moved closer to logic in _add_fvar/avar
@@ -865,6 +865,38 @@ def set_default_weight_width_slant(font, location):
font["post"].italicAngle = italicAngle
+def build_many(designspace: DesignSpaceDocument, master_finder=lambda s:s, exclude=[], optimize=True, skip_vf=lambda vf_name: False):
+ """
+ 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 opened (eg. .ttf or .otf).
+
+ skip_vf can be used to skip building some of the variable fonts defined in
+ the input designspace. It's a predicate that takes as argument the name
+ of the variable font and returns `bool`.
+
+ Always returns a Dict[str, TTFont] keyed by VariableFontDescriptor.name
+ """
+ res = {}
+ for _location, subDoc in splitInterpolable(designspace):
+ for name, vfDoc in splitVariableFonts(subDoc):
+ if skip_vf(name):
+ log.debug(f"Skipping variable TTF font: {name}")
+ continue
+ vf = build(
+ vfDoc,
+ master_finder,
+ exclude=list(exclude) + ["STAT"],
+ optimize=optimize
+ )[0]
+ if "STAT" not in exclude:
+ buildVFStatTable(vf, designspace, name)
+ res[name] = vf
+ return res
+
def build(designspace, master_finder=lambda s:s, exclude=[], optimize=True):
"""
Build variation font from a designspace file.
@@ -898,7 +930,7 @@ def build(designspace, master_finder=lambda s:s, exclude=[], optimize=True):
# TODO append masters as named-instances as well; needs .designspace change.
fvar = _add_fvar(vf, ds.axes, ds.instances)
if 'STAT' not in exclude:
- _add_stat(vf, ds.axes)
+ _add_stat(vf)
if 'avar' not in exclude:
_add_avar(vf, ds.axes)
diff --git a/Lib/fontTools/varLib/instancer/__init__.py b/Lib/fontTools/varLib/instancer/__init__.py
index cec802f3..6dad393e 100644
--- a/Lib/fontTools/varLib/instancer/__init__.py
+++ b/Lib/fontTools/varLib/instancer/__init__.py
@@ -1024,8 +1024,11 @@ def instantiateSTAT(varfont, axisLimits):
log.info("Instantiating STAT table")
newAxisValueTables = axisValuesFromAxisLimits(stat, axisLimits)
- stat.AxisValueArray.AxisValue = newAxisValueTables
- stat.AxisValueCount = len(stat.AxisValueArray.AxisValue)
+ stat.AxisValueCount = len(newAxisValueTables)
+ if stat.AxisValueCount:
+ stat.AxisValueArray.AxisValue = newAxisValueTables
+ else:
+ stat.AxisValueArray = None
def axisValuesFromAxisLimits(stat, axisLimits):
diff --git a/Lib/fontTools/varLib/interpolatable.py b/Lib/fontTools/varLib/interpolatable.py
index cff76ece..a9583a18 100644
--- a/Lib/fontTools/varLib/interpolatable.py
+++ b/Lib/fontTools/varLib/interpolatable.py
@@ -7,6 +7,7 @@ $ fonttools varLib.interpolatable font1 font2 ...
"""
from fontTools.pens.basePen import AbstractPen, BasePen
+from fontTools.pens.pointPen import SegmentToPointPen
from fontTools.pens.recordingPen import RecordingPen
from fontTools.pens.statisticsPen import StatisticsPen
from fontTools.pens.momentsPen import OpenContourError
@@ -14,6 +15,14 @@ from collections import OrderedDict
import itertools
import sys
+def _rot_list(l, k):
+ """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]
+
class PerContourPen(BasePen):
def __init__(self, Pen, glyphset=None):
@@ -55,6 +64,21 @@ class PerContourOrComponentPen(PerContourPen):
self.value[-1].addComponent(glyphName, transformation)
+class RecordingPointPen(BasePen):
+
+ def __init__(self):
+ self.value = []
+
+ def beginPath(self, identifier = None, **kwargs):
+ pass
+
+ def endPath(self) -> None:
+ pass
+
+ def addPoint(self, pt, segmentType=None):
+ self.value.append((pt, False if segmentType is None else True))
+
+
def _vdiff(v0, v1):
return tuple(b - a for a, b in zip(v0, v1))
@@ -65,6 +89,12 @@ def _vlen(vec):
v += x * x
return v
+def _complex_vlen(vec):
+ v = 0
+ for x in vec:
+ v += abs(x) * abs(x)
+ return v
+
def _matching_cost(G, matching):
return sum(G[i][j] for i, j in enumerate(matching))
@@ -125,6 +155,7 @@ def test(glyphsets, glyphs=None, names=None):
try:
allVectors = []
allNodeTypes = []
+ allContourIsomorphisms = []
for glyphset, name in zip(glyphsets, names):
# print('.', end='')
if glyph_name not in glyphset:
@@ -135,18 +166,24 @@ def test(glyphsets, glyphs=None, names=None):
perContourPen = PerContourOrComponentPen(
RecordingPen, glyphset=glyphset
)
- glyph.draw(perContourPen)
+ try:
+ glyph.draw(perContourPen, outputImpliedClosingLine=True)
+ except TypeError:
+ glyph.draw(perContourPen)
contourPens = perContourPen.value
del perContourPen
contourVectors = []
+ contourIsomorphisms = []
nodeTypes = []
allNodeTypes.append(nodeTypes)
allVectors.append(contourVectors)
+ allContourIsomorphisms.append(contourIsomorphisms)
for ix, contour in enumerate(contourPens):
- nodeTypes.append(
- tuple(instruction[0] for instruction in contour.value)
- )
+
+ nodeVecs = tuple(instruction[0] for instruction in contour.value)
+ nodeTypes.append(nodeVecs)
+
stats = StatisticsPen(glyphset=glyphset)
try:
contour.replay(stats)
@@ -168,6 +205,38 @@ def test(glyphsets, glyphs=None, names=None):
contourVectors.append(vector)
# print(vector)
+ # Check starting point
+ if nodeVecs[0] == 'addComponent':
+ continue
+ assert nodeVecs[0] == 'moveTo'
+ assert nodeVecs[-1] in ('closePath', 'endPath')
+ points = RecordingPointPen()
+ converter = SegmentToPointPen(points, False)
+ contour.replay(converter)
+ # points.value is a list of pt,bool where bool is true if on-curve and false if off-curve;
+ # now check all rotations and mirror-rotations of the contour and build list of isomorphic
+ # possible starting points.
+ bits = 0
+ for pt,b in points.value:
+ bits = (bits << 1) | b
+ n = len(points.value)
+ mask = (1 << n ) - 1
+ isomorphisms = []
+ contourIsomorphisms.append(isomorphisms)
+ for i in range(n):
+ b = ((bits << i) & mask) | ((bits >> (n - i)))
+ if b == bits:
+ isomorphisms.append(_rot_list ([complex(*pt) for pt,bl in points.value], i))
+ # Add mirrored rotations
+ mirrored = list(reversed(points.value))
+ reversed_bits = 0
+ for pt,b in mirrored:
+ reversed_bits = (reversed_bits << 1) | b
+ for i in range(n):
+ b = ((reversed_bits << i) & mask) | ((reversed_bits >> (n - i)))
+ if b == bits:
+ isomorphisms.append(_rot_list ([complex(*pt) for pt,bl in mirrored], i))
+
# Check each master against the next one in the list.
for i, (m0, m1) in enumerate(zip(allNodeTypes[:-1], allNodeTypes[1:])):
if len(m0) != len(m1):
@@ -223,7 +292,9 @@ def test(glyphsets, glyphs=None, names=None):
continue
costs = [[_vlen(_vdiff(v0, v1)) for v1 in m1] for v0 in m0]
matching, matching_cost = min_cost_perfect_bipartite_matching(costs)
- if matching != list(range(len(m0))):
+ identity_matching = list(range(len(m0)))
+ identity_cost = sum(costs[i][i] for i in range(len(m0)))
+ if matching != identity_matching and matching_cost < identity_cost * .95:
add_problem(
glyph_name,
{
@@ -235,23 +306,27 @@ def test(glyphsets, glyphs=None, names=None):
},
)
break
- upem = 2048
- item_cost = round(
- (matching_cost / len(m0) / len(m0[0])) ** 0.5 / upem * 100
- )
- hist.append(item_cost)
- threshold = 7
- if item_cost >= threshold:
- add_problem(
- glyph_name,
- {
- "type": "high_cost",
- "master_1": names[i],
- "master_2": names[i + 1],
- "value_1": item_cost,
- "value_2": threshold,
- },
- )
+
+ for i, (m0, m1) in enumerate(zip(allContourIsomorphisms[:-1], allContourIsomorphisms[1:])):
+ if len(m0) != len(m1):
+ # We already reported this
+ continue
+ if not m0:
+ continue
+ for contour0,contour1 in zip(m0,m1):
+ c0 = contour0[0]
+ costs = [v for v in (_complex_vlen(_vdiff(c0, c1)) for c1 in contour1)]
+ min_cost = min(costs)
+ first_cost = costs[0]
+ if min_cost < first_cost * .95:
+ add_problem(
+ glyph_name,
+ {
+ "type": "wrong_start_point",
+ "master_1": names[i],
+ "master_2": names[i + 1],
+ },
+ )
except ValueError as e:
add_problem(
@@ -351,14 +426,12 @@ def main(args=None):
p["master_2"],
)
)
- if p["type"] == "high_cost":
+ if p["type"] == "wrong_start_point":
print(
- " Interpolation has high cost: cost of %s to %s = %i, threshold %i"
+ " Contour start point differs: %s, %s"
% (
p["master_1"],
p["master_2"],
- p["value_1"],
- p["value_2"],
)
)
if problems:
diff --git a/Lib/fontTools/varLib/merger.py b/Lib/fontTools/varLib/merger.py
index 5a3a4f34..3e5d2a9b 100644
--- a/Lib/fontTools/varLib/merger.py
+++ b/Lib/fontTools/varLib/merger.py
@@ -16,9 +16,8 @@ from fontTools.varLib.varStore import VarStoreInstancer
from functools import reduce
from fontTools.otlLib.builder import buildSinglePos
from fontTools.otlLib.optimize.gpos import (
- compact_pair_pos,
- GPOS_COMPACT_MODE_DEFAULT,
- GPOS_COMPACT_MODE_ENV_KEY,
+ _compression_level_from_env,
+ compact_pair_pos,
)
log = logging.getLogger("fontTools.varLib.merger")
@@ -850,10 +849,14 @@ def merge(merger, self, lst):
# Compact the merged subtables
# This is a good moment to do it because the compaction should create
# smaller subtables, which may prevent overflows from happening.
- mode = os.environ.get(GPOS_COMPACT_MODE_ENV_KEY, GPOS_COMPACT_MODE_DEFAULT)
- if mode and mode != "0":
+ # Keep reading the value from the ENV until ufo2ft switches to the config system
+ level = merger.font.cfg.get(
+ "fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL",
+ default=_compression_level_from_env(),
+ )
+ if level != 0:
log.info("Compacting GPOS...")
- self.SubTable = compact_pair_pos(merger.font, mode, self.SubTable)
+ self.SubTable = compact_pair_pos(merger.font, level, self.SubTable)
self.SubTableCount = len(self.SubTable)
elif isSinglePos and flattened:
diff --git a/Lib/fontTools/varLib/stat.py b/Lib/fontTools/varLib/stat.py
new file mode 100644
index 00000000..46c9498d
--- /dev/null
+++ b/Lib/fontTools/varLib/stat.py
@@ -0,0 +1,142 @@
+"""Extra methods for DesignSpaceDocument to generate its STAT table data."""
+
+from __future__ import annotations
+
+from typing import Dict, List, Union
+
+import fontTools.otlLib.builder
+from fontTools.designspaceLib import (
+ AxisLabelDescriptor,
+ DesignSpaceDocument,
+ DesignSpaceDocumentError,
+ LocationLabelDescriptor,
+)
+from fontTools.designspaceLib.types import Region, getVFUserRegion, locationInRegion
+from fontTools.ttLib import TTFont
+
+
+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 font actually ships.
+
+ .. versionadded:: 5.0
+
+ .. seealso::
+ - :func:`getStatAxes()`
+ - :func:`getStatLocations()`
+ - :func:`fontTools.otlLib.builder.buildStatTable()`
+ """
+ for vf in doc.getVariableFonts():
+ if vf.name == vfName:
+ break
+ else:
+ raise DesignSpaceDocumentError(
+ f"Cannot find the variable font by name {vfName}"
+ )
+
+ region = getVFUserRegion(doc, vf)
+
+ return fontTools.otlLib.builder.buildStatTable(
+ ttFont,
+ getStatAxes(doc, region),
+ getStatLocations(doc, region),
+ doc.elidedFallbackName if doc.elidedFallbackName is not None else 2,
+ )
+
+
+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 the others in the order they appear.
+ maxOrdering = max(
+ (axis.axisOrdering for axis in doc.axes if axis.axisOrdering is not None),
+ default=-1,
+ )
+ axisOrderings = []
+ for axis in doc.axes:
+ if axis.axisOrdering is not None:
+ axisOrderings.append(axis.axisOrdering)
+ else:
+ maxOrdering += 1
+ axisOrderings.append(maxOrdering)
+ return [
+ dict(
+ tag=axis.tag,
+ name={"en": axis.name, **axis.labelNames},
+ ordering=ordering,
+ values=[
+ _axisLabelToStatLocation(label)
+ for label in axis.axisLabels
+ if locationInRegion({axis.name: label.userValue}, userRegion)
+ ],
+ )
+ for axis, ordering in zip(doc.axes, axisOrderings)
+ ]
+
+
+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 [
+ dict(
+ name={"en": label.name, **label.labelNames},
+ # Location in the designspace is keyed by axis name
+ # Location in buildStatTable by axis tag
+ location={
+ axesByName[name].tag: value
+ for name, value in label.getFullUserLocation(doc).items()
+ },
+ flags=_labelToFlags(label),
+ )
+ for label in doc.locationLabels
+ if locationInRegion(label.getFullUserLocation(doc), userRegion)
+ ]
+
+
+def _labelToFlags(label: Union[AxisLabelDescriptor, LocationLabelDescriptor]) -> int:
+ flags = 0
+ if label.olderSibling:
+ flags |= 1
+ if label.elidable:
+ flags |= 2
+ return flags
+
+
+def _axisLabelToStatLocation(
+ label: AxisLabelDescriptor,
+) -> Dict:
+ label_format = label.getFormat()
+ name = {"en": label.name, **label.labelNames}
+ flags = _labelToFlags(label)
+ if label_format == 1:
+ return dict(name=name, value=label.userValue, flags=flags)
+ if label_format == 3:
+ return dict(
+ name=name,
+ value=label.userValue,
+ linkedValue=label.linkedUserValue,
+ flags=flags,
+ )
+ if label_format == 2:
+ res = dict(
+ name=name,
+ nominalValue=label.userValue,
+ flags=flags,
+ )
+ if label.userMinimum is not None:
+ res["rangeMinValue"] = label.userMinimum
+ if label.userMaximum is not None:
+ res["rangeMaxValue"] = label.userMaximum
+ return res
+ raise NotImplementedError("Unknown STAT label format")