code
stringlengths 66
870k
| docstring
stringlengths 19
26.7k
| func_name
stringlengths 1
138
| language
stringclasses 1
value | repo
stringlengths 7
68
| path
stringlengths 5
324
| url
stringlengths 46
389
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def 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.
"""
for cd in conditions:
value = location[cd["name"]]
if cd.get("minimum") is None:
if value > cd["maximum"]:
return False
elif cd.get("maximum") is None:
if cd["minimum"] > value:
return False
elif not cd["minimum"] <= value <= cd["maximum"]:
return False
return True
|
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.
|
evaluateConditions
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
def processRules(rules, location, glyphNames):
"""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:
if evaluateRule(rule, location):
for name in glyphNames:
swap = False
for a, b in rule.subs:
if name == a:
swap = True
break
if swap:
newNames.append(b)
else:
newNames.append(name)
glyphNames = newNames
newNames = []
return glyphNames
|
Apply these rules at this location to these glyphnames.
Return a new list of glyphNames with substitutions applied.
- rule order matters
|
processRules
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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]
|
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
|
clearLocation
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
|
Get the :class:`LocationLabelDescriptor` instance that matches
this instances's :attr:`locationLabel`.
Raises if the named label can't be found.
.. versionadded:: 5.0
|
getLocationLabelDescriptor
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
|
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
|
getFullDesignLocation
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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:
return v
return piecewiseLinearMap(v, {k: v for k, v in self.map})
|
Maps value from axis mapping's input (user) to output (design).
|
map_forward
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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})
|
Maps value from axis mapping's output (design) to input (user).
|
map_backward
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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)
|
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.
|
map_backward
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
}
|
Get the complete user location of this label, by combining data
from the explicit user location and default axis values.
.. versionadded:: 5.0
|
getFullUserLocation
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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(
hasattr(axis, "values")
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)
if self.documentObject.axisMappings:
if minVersion < (5, 1):
minVersion = (5, 1)
return minVersion
|
Try to use the version specified in the document, or a sufficiently
recent version to be able to encode what the document contains.
|
_getEffectiveFormatTuple
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
def locationFromElement(self, element):
"""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
|
Read a nested ``<location>`` element inside the given ``element``.
.. versionchanged:: 5.0
Return a tuple of (designLocation, userLocation)
|
locationFromElement
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
def readLocationElement(self, locationElement):
"""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")
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
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")
if xValue is not None:
xValue = float(xValue)
except ValueError:
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:
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:
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:
userLoc[dimName] = userValue
return designLoc, userLoc
|
Read a ``<location>`` element.
.. versionchanged:: 5.0
Return a tuple of (designLocation, userLocation)
|
readLocationElement
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
def readGlyphElement(self, glyphElement, instanceObject):
"""
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"/>
<note>
This is an instance from an anisotropic interpolation.
</note>
</glyph>
"""
glyphData = {}
glyphName = glyphElement.attrib.get("name")
if glyphName is None:
raise DesignSpaceDocumentError("Glyph object without name attribute")
mute = glyphElement.attrib.get("mute")
if mute == "1":
glyphData["mute"] = True
# unicode
unicodes = glyphElement.attrib.get("unicode")
if unicodes is not None:
try:
unicodes = [int(u, 16) for u in unicodes.split(" ")]
glyphData["unicodes"] = unicodes
except ValueError:
raise DesignSpaceDocumentError(
"unicode values %s are not integers" % unicodes
)
for noteElement in glyphElement.findall(".note"):
glyphData["note"] = noteElement.text
break
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")
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=designLocation, glyphName=masterGlyphName
)
if glyphSources is None:
glyphSources = []
glyphSources.append(d)
if glyphSources is not None:
glyphData["masters"] = glyphSources
instanceObject.glyphs[glyphName] = glyphData
|
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"/>
<note>
This is an instance from an anisotropic interpolation.
</note>
</glyph>
|
readGlyphElement
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
def readLib(self):
"""Read the lib element for the whole document."""
for libElement in self.root.findall(".lib"):
self.documentObject.lib = plistlib.fromtree(libElement[0])
|
Read the lib element for the whole document.
|
readLib
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
|
Read a designspace file from ``path`` and return a new instance of
:class:.
|
fromfile
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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"):
f = StringIO()
xml_declaration = False
elif encoding is None or encoding == "utf-8":
f = BytesIO()
encoding = "UTF-8"
xml_declaration = True
else:
raise ValueError("unsupported encoding: '%s'" % encoding)
writer = self.writerClass(f, self)
writer.write(encoding=encoding, xml_declaration=xml_declaration)
return f.getvalue()
|
Returns the designspace as a string. Default encoding ``utf-8``.
|
tostring
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
self.filename = os.path.basename(path)
reader = self.readerClass(path, self)
reader.read()
if self.sources:
self.findDefault()
|
Read a designspace file from ``path`` and populates the fields of
``self`` with the data.
|
read
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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.
::
case 1.
descriptor.filename == None
descriptor.path == None
-- action:
write as is, descriptors will not have a filename attr.
useless, but no reason to interfere.
case 2.
descriptor.filename == "../something"
descriptor.path == None
-- action:
write as is. The filename attr should not be touched.
case 3.
descriptor.filename == None
descriptor.path == "~/absolute/path/there"
-- action:
calculate the relative path for filename.
We're not overwriting some other value for filename, it should be fine
case 4.
descriptor.filename == '../somewhere'
descriptor.path == "~/absolute/path/there"
-- action:
there is a conflict between the given filename, and the path.
So we know where the file is relative to the document.
Can't guess why they're different, we just choose for path to be correct and update filename.
"""
assert self.path is not None
for descriptor in self.sources + self.instances:
if descriptor.path is not None:
# case 3 and 4: filename gets updated and relativized
descriptor.filename = self._posixRelativePath(descriptor.path)
|
Right before we save we need to identify and respond to the following situations:
In each descriptor, we have to do the right thing for the filename attribute.
::
case 1.
descriptor.filename == None
descriptor.path == None
-- action:
write as is, descriptors will not have a filename attr.
useless, but no reason to interfere.
case 2.
descriptor.filename == "../something"
descriptor.path == None
-- action:
write as is. The filename attr should not be touched.
case 3.
descriptor.filename == None
descriptor.path == "~/absolute/path/there"
-- action:
calculate the relative path for filename.
We're not overwriting some other value for filename, it should be fine
case 4.
descriptor.filename == '../somewhere'
descriptor.path == "~/absolute/path/there"
-- action:
there is a conflict between the given filename, and the path.
So we know where the file is relative to the document.
Can't guess why they're different, we just choose for path to be correct and update filename.
|
updatePaths
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
|
Instantiate a new :class:`SourceDescriptor` using the given
``kwargs`` and add it to ``doc.sources``.
|
addSourceDescriptor
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
|
Instantiate a new :class:`InstanceDescriptor` using the given
``kwargs`` and add it to :attr:`instances`.
|
addInstanceDescriptor
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
def addAxisDescriptor(self, **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
|
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.
|
addAxisDescriptor
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
def addAxisMappingDescriptor(self, **kwargs):
"""Instantiate a new :class:`AxisMappingDescriptor` using the given
``kwargs`` and add it to :attr:`rules`.
"""
axisMapping = self.writerClass.axisMappingDescriptorClass(**kwargs)
self.addAxisMapping(axisMapping)
return axisMapping
|
Instantiate a new :class:`AxisMappingDescriptor` using the given
``kwargs`` and add it to :attr:`rules`.
|
addAxisMappingDescriptor
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
|
Instantiate a new :class:`RuleDescriptor` using the given
``kwargs`` and add it to :attr:`rules`.
|
addRuleDescriptor
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
|
Instantiate a new :class:`VariableFontDescriptor` using the given
``kwargs`` and add it to :attr:`variableFonts`.
.. versionadded:: 5.0
|
addVariableFontDescriptor
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
|
Instantiate a new :class:`LocationLabelDescriptor` using the given
``kwargs`` and add it to :attr:`locationLabels`.
.. versionadded:: 5.0
|
addLocationLabelDescriptor
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
def newDefaultLocation(self):
"""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()
for axisDescriptor in self.axes:
loc[axisDescriptor.name] = axisDescriptor.map_forward(
axisDescriptor.default
)
return loc
|
Return a dict with the default location in design space coordinates.
|
newDefaultLocation
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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,
)
|
Return the :class:`LocationLabel` that matches the given
``userLocation``, or ``None`` if no such label exists.
.. versionadded:: 5.0
|
labelForUserLocation
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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.
"""
if masters:
for descriptor in self.sources:
if descriptor.filename is not None and not force:
continue
if self.path is not None:
descriptor.filename = self._posixRelativePath(descriptor.path)
if instances:
for descriptor in self.instances:
if descriptor.filename is not None and not force:
continue
if self.path is not None:
descriptor.filename = self._posixRelativePath(descriptor.path)
|
Set a descriptor filename attr from the path and this document path.
If the filename attribute is not None: skip it.
|
updateFilenameFromPath
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
|
Return a list of axis names, in the same order as defined in the document.
|
getAxisOrder
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
|
Return the top-level location label with the given ``name``, or
``None`` if no such label exists.
.. versionadded:: 5.0
|
getLocationLabel
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
}
|
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
|
map_forward
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
}
|
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
|
map_backward
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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).
defaultDesignLocation = self.newDefaultLocation()
for sourceDescriptor in self.sources:
if sourceDescriptor.getFullDesignLocation(self) == defaultDesignLocation:
self.default = sourceDescriptor
return sourceDescriptor
return None
|
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()`
|
findDefault
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
def normalizeLocation(self, location):
"""Return a dict with normalized axis values."""
from fontTools.varLib.models import normalizeValue
new = {}
for axis in self.axes:
if axis.name not in location:
# skipping this dimension it seems
continue
value = location[axis.name]
# 'anisotropic' location, take first coord only
if isinstance(value, tuple):
value = value[0]
triple = [
axis.map_forward(v) for v in (axis.minimum, axis.default, axis.maximum)
]
new[axis.name] = normalizeValue(value, triple)
return new
|
Return a dict with normalized axis values.
|
normalizeLocation
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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.
"""
# masters
for item in self.sources:
item.location = self.normalizeLocation(item.location)
# instances
for item in self.instances:
# glyph masters for this instance
for _, glyphData in item.glyphs.items():
glyphData["instanceLocation"] = self.normalizeLocation(
glyphData["instanceLocation"]
)
for glyphMaster in glyphData["masters"]:
glyphMaster["location"] = self.normalizeLocation(
glyphMaster["location"]
)
item.location = self.normalizeLocation(item.location)
# the axes
for axis in self.axes:
# scale the map first
newMap = []
for inputValue, outputValue in axis.map:
newOutputValue = self.normalizeLocation({axis.name: outputValue}).get(
axis.name
)
newMap.append((inputValue, newOutputValue))
if newMap:
axis.map = newMap
# finally the axis values
minimum = self.normalizeLocation({axis.name: axis.minimum}).get(axis.name)
maximum = self.normalizeLocation({axis.name: axis.maximum}).get(axis.name)
default = self.normalizeLocation({axis.name: axis.default}).get(axis.name)
# and set them in the axis.minimum
axis.minimum = minimum
axis.maximum = maximum
axis.default = default
# now the rules
for rule in self.rules:
newConditionSets = []
for conditions in rule.conditionSets:
newConditions = []
for cond in conditions:
if cond.get("minimum") is not None:
minimum = self.normalizeLocation(
{cond["name"]: cond["minimum"]}
).get(cond["name"])
else:
minimum = None
if cond.get("maximum") is not None:
maximum = self.normalizeLocation(
{cond["name"]: cond["maximum"]}
).get(cond["name"])
else:
maximum = None
newConditions.append(
dict(name=cond["name"], minimum=minimum, maximum=maximum)
)
newConditionSets.append(newConditions)
rule.conditionSets = newConditionSets
|
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.
|
normalize
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
def loadSourceFonts(self, opener, **kwargs):
"""Ensure SourceDescriptor.font attributes are loaded, and return list of fonts.
Takes a callable which initializes a new font object (e.g. TTFont, or
defcon.Font, etc.) from the SourceDescriptor.path, and sets the
SourceDescriptor.font attribute.
If the font attribute is already not None, it is not loaded again.
Fonts with the same path are only loaded once and shared among SourceDescriptors.
For example, to load UFO sources using defcon:
designspace = DesignSpaceDocument.fromfile("path/to/my.designspace")
designspace.loadSourceFonts(defcon.Font)
Or to load masters as FontTools binary fonts, including extra options:
designspace.loadSourceFonts(ttLib.TTFont, recalcBBoxes=False)
Args:
opener (Callable): takes one required positional argument, the source.path,
and an optional list of keyword arguments, and returns a new font object
loaded from the path.
**kwargs: extra options passed on to the opener function.
Returns:
List of font objects in the order they appear in the sources list.
"""
# we load fonts with the same source.path only once
loaded = {}
fonts = []
for source in self.sources:
if source.font is not None: # font already loaded
fonts.append(source.font)
continue
if source.path in loaded:
source.font = loaded[source.path]
else:
if source.path is None:
raise DesignSpaceDocumentError(
"Designspace source '%s' has no 'path' attribute"
% (source.name or "<Unknown>")
)
source.font = opener(source.path, **kwargs)
loaded[source.path] = source.font
fonts.append(source.font)
return fonts
|
Ensure SourceDescriptor.font attributes are loaded, and return list of fonts.
Takes a callable which initializes a new font object (e.g. TTFont, or
defcon.Font, etc.) from the SourceDescriptor.path, and sets the
SourceDescriptor.font attribute.
If the font attribute is already not None, it is not loaded again.
Fonts with the same path are only loaded once and shared among SourceDescriptors.
For example, to load UFO sources using defcon:
designspace = DesignSpaceDocument.fromfile("path/to/my.designspace")
designspace.loadSourceFonts(defcon.Font)
Or to load masters as FontTools binary fonts, including extra options:
designspace.loadSourceFonts(ttLib.TTFont, recalcBBoxes=False)
Args:
opener (Callable): takes one required positional argument, the source.path,
and an optional list of keyword arguments, and returns a new font object
loaded from the path.
**kwargs: extra options passed on to the opener function.
Returns:
List of font objects in the order they appear in the sources list.
|
loadSourceFonts
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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)
|
Return the formatVersion as a tuple of (major, minor).
.. versionadded:: 5.0
|
formatTuple
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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 hasattr(axis, "values"):
# Mypy doesn't support narrowing union types via hasattr()
# TODO(Python 3.10): use TypeGuard
# https://mypy.readthedocs.io/en/stable/type_narrowing.html
axis = cast(DiscreteAxisDescriptor, axis)
discreteAxes.append(axis) # type: ignore
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
|
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
|
getVariableFonts
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
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
|
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
|
deepcopyExceptFonts
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
def main(args=None):
"""Roundtrip .designspace file through the DesignSpaceDocument class"""
if args is None:
import sys
args = sys.argv[1:]
from argparse import ArgumentParser
parser = ArgumentParser(prog="designspaceLib", description=main.__doc__)
parser.add_argument("input")
parser.add_argument("output")
options = parser.parse_args(args)
ds = DesignSpaceDocument.fromfile(options.input)
ds.write(options.output)
|
Roundtrip .designspace file through the DesignSpaceDocument class
|
main
|
python
|
fonttools/fonttools
|
Lib/fontTools/designspaceLib/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/designspaceLib/__init__.py
|
MIT
|
def add_range(self, start, end, glyphs):
"""Add a range (e.g. ``A-Z``) to the class. ``start`` and ``end``
are either :class:`GlyphName` objects or strings representing the
start and end glyphs in the class, and ``glyphs`` is the full list of
:class:`GlyphName` objects in the range."""
if self.curr < len(self.glyphs):
self.original.extend(self.glyphs[self.curr :])
self.original.append((start, end))
self.glyphs.extend(glyphs)
self.curr = len(self.glyphs)
|
Add a range (e.g. ``A-Z``) to the class. ``start`` and ``end``
are either :class:`GlyphName` objects or strings representing the
start and end glyphs in the class, and ``glyphs`` is the full list of
:class:`GlyphName` objects in the range.
|
add_range
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/ast.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/ast.py
|
MIT
|
def add_cid_range(self, start, end, glyphs):
"""Add a range to the class by glyph ID. ``start`` and ``end`` are the
initial and final IDs, and ``glyphs`` is the full list of
:class:`GlyphName` objects in the range."""
if self.curr < len(self.glyphs):
self.original.extend(self.glyphs[self.curr :])
self.original.append(("\\{}".format(start), "\\{}".format(end)))
self.glyphs.extend(glyphs)
self.curr = len(self.glyphs)
|
Add a range to the class by glyph ID. ``start`` and ``end`` are the
initial and final IDs, and ``glyphs`` is the full list of
:class:`GlyphName` objects in the range.
|
add_cid_range
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/ast.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/ast.py
|
MIT
|
def add_class(self, gc):
"""Add glyphs from the given :class:`GlyphClassName` object to the
class."""
if self.curr < len(self.glyphs):
self.original.extend(self.glyphs[self.curr :])
self.original.append(gc)
self.glyphs.extend(gc.glyphSet())
self.curr = len(self.glyphs)
|
Add glyphs from the given :class:`GlyphClassName` object to the
class.
|
add_class
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/ast.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/ast.py
|
MIT
|
def build(self, builder):
"""Call the ``start_feature`` callback on the builder object, visit
all the statements in this feature, and then call ``end_feature``."""
builder.start_feature(self.location, self.name, self.use_extension)
# language exclude_dflt statements modify builder.features_
# limit them to this block with temporary builder.features_
features = builder.features_
builder.features_ = {}
Block.build(self, builder)
for key, value in builder.features_.items():
features.setdefault(key, []).extend(value)
builder.features_ = features
builder.end_feature()
|
Call the ``start_feature`` callback on the builder object, visit
all the statements in this feature, and then call ``end_feature``.
|
build
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/ast.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/ast.py
|
MIT
|
def addDefinition(self, definition):
"""Add a :class:`MarkClassDefinition` statement to this mark class."""
assert isinstance(definition, MarkClassDefinition)
self.definitions.append(definition)
for glyph in definition.glyphSet():
if glyph in self.glyphs:
otherLoc = self.glyphs[glyph].location
if otherLoc is None:
end = ""
else:
end = f" at {otherLoc}"
raise FeatureLibError(
"Glyph %s already defined%s" % (glyph, end), definition.location
)
self.glyphs[glyph] = definition
|
Add a :class:`MarkClassDefinition` statement to this mark class.
|
addDefinition
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/ast.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/ast.py
|
MIT
|
def build(self, builder):
"""Calls the builder object's ``add_chain_context_pos`` callback on each
rule context."""
for prefix, glyphs, suffix in self.chainContexts:
prefix = [p.glyphSet() for p in prefix]
glyphs = [g.glyphSet() for g in glyphs]
suffix = [s.glyphSet() for s in suffix]
builder.add_chain_context_pos(self.location, prefix, glyphs, suffix, [])
|
Calls the builder object's ``add_chain_context_pos`` callback on each
rule context.
|
build
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/ast.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/ast.py
|
MIT
|
def build(self, builder):
"""Calls the builder object's ``add_chain_context_subst`` callback on
each rule context."""
for prefix, glyphs, suffix in self.chainContexts:
prefix = [p.glyphSet() for p in prefix]
glyphs = [g.glyphSet() for g in glyphs]
suffix = [s.glyphSet() for s in suffix]
builder.add_chain_context_subst(self.location, prefix, glyphs, suffix, [])
|
Calls the builder object's ``add_chain_context_subst`` callback on
each rule context.
|
build
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/ast.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/ast.py
|
MIT
|
def build(self, builder):
"""Calls a callback on the builder object:
* If the rule is enumerated, calls ``add_specific_pair_pos`` on each
combination of first and second glyphs.
* If the glyphs are both single :class:`GlyphName` objects, calls
``add_specific_pair_pos``.
* Else, calls ``add_class_pair_pos``.
"""
if self.enumerated:
g = [self.glyphs1.glyphSet(), self.glyphs2.glyphSet()]
seen_pair = False
for glyph1, glyph2 in itertools.product(*g):
seen_pair = True
builder.add_specific_pair_pos(
self.location, glyph1, self.valuerecord1, glyph2, self.valuerecord2
)
if not seen_pair:
raise FeatureLibError(
"Empty glyph class in positioning rule", self.location
)
return
is_specific = isinstance(self.glyphs1, GlyphName) and isinstance(
self.glyphs2, GlyphName
)
if is_specific:
builder.add_specific_pair_pos(
self.location,
self.glyphs1.glyph,
self.valuerecord1,
self.glyphs2.glyph,
self.valuerecord2,
)
else:
builder.add_class_pair_pos(
self.location,
self.glyphs1.glyphSet(),
self.valuerecord1,
self.glyphs2.glyphSet(),
self.valuerecord2,
)
|
Calls a callback on the builder object:
* If the rule is enumerated, calls ``add_specific_pair_pos`` on each
combination of first and second glyphs.
* If the glyphs are both single :class:`GlyphName` objects, calls
``add_specific_pair_pos``.
* Else, calls ``add_class_pair_pos``.
|
build
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/ast.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/ast.py
|
MIT
|
def build(self, builder):
"""Call the ``start_feature`` callback on the builder object, visit
all the statements in this feature, and then call ``end_feature``."""
builder.start_feature(self.location, self.name, self.use_extension)
if (
self.conditionset != "NULL"
and self.conditionset not in builder.conditionsets_
):
raise FeatureLibError(
f"variation block used undefined conditionset {self.conditionset}",
self.location,
)
# language exclude_dflt statements modify builder.features_
# limit them to this block with temporary builder.features_
features = builder.features_
builder.features_ = {}
Block.build(self, builder)
for key, value in builder.features_.items():
items = builder.feature_variations_.setdefault(key, {}).setdefault(
self.conditionset, []
)
items.extend(value)
if key not in features:
features[key] = [] # Ensure we make a feature record
builder.features_ = features
builder.end_feature()
|
Call the ``start_feature`` callback on the builder object, visit
all the statements in this feature, and then call ``end_feature``.
|
build
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/ast.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/ast.py
|
MIT
|
def addOpenTypeFeaturesFromString(
font, features, filename=None, tables=None, debug=False
):
"""Add features from a string to a font. Note that this replaces any
features currently present.
Args:
font (feaLib.ttLib.TTFont): The font object.
features: A string containing feature code.
filename: The directory containing ``filename`` is used as the root of
relative ``include()`` paths; if ``None`` is provided, the current
directory is assumed.
tables: If passed, restrict the set of affected tables to those in the
list.
debug: Whether to add source debugging information to the font in the
``Debg`` table
"""
featurefile = StringIO(tostr(features))
if filename:
featurefile.name = filename
addOpenTypeFeatures(font, featurefile, tables=tables, debug=debug)
|
Add features from a string to a font. Note that this replaces any
features currently present.
Args:
font (feaLib.ttLib.TTFont): The font object.
features: A string containing feature code.
filename: The directory containing ``filename`` is used as the root of
relative ``include()`` paths; if ``None`` is provided, the current
directory is assumed.
tables: If passed, restrict the set of affected tables to those in the
list.
debug: Whether to add source debugging information to the font in the
``Debg`` table
|
addOpenTypeFeaturesFromString
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/builder.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/builder.py
|
MIT
|
def find_lookup_builders_(self, lookups):
"""Helper for building chain contextual substitutions
Given a list of lookup names, finds the LookupBuilder for each name.
If an input name is None, it gets mapped to a None LookupBuilder.
"""
lookup_builders = []
for lookuplist in lookups:
if lookuplist is not None:
lookup_builders.append(
[self.named_lookups_.get(l.name) for l in lookuplist]
)
else:
lookup_builders.append(None)
return lookup_builders
|
Helper for building chain contextual substitutions
Given a list of lookup names, finds the LookupBuilder for each name.
If an input name is None, it gets mapped to a None LookupBuilder.
|
find_lookup_builders_
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/builder.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/builder.py
|
MIT
|
def add_to_cv_num_named_params(self, tag):
"""Adds new items to ``self.cv_num_named_params_``
or increments the count of existing items."""
if tag in self.cv_num_named_params_:
self.cv_num_named_params_[tag] += 1
else:
self.cv_num_named_params_[tag] = 1
|
Adds new items to ``self.cv_num_named_params_``
or increments the count of existing items.
|
add_to_cv_num_named_params
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/builder.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/builder.py
|
MIT
|
def __init__(self, featurefile, *, includeDir=None):
"""Initializes an IncludingLexer.
Behavior:
If includeDir is passed, it will be used to determine the top-level
include directory to use for all encountered include statements. If it is
not passed, ``os.path.dirname(featurefile)`` will be considered the
include directory.
"""
self.lexers_ = [self.make_lexer_(featurefile)]
self.featurefilepath = self.lexers_[0].filename_
self.includeDir = includeDir
|
Initializes an IncludingLexer.
Behavior:
If includeDir is passed, it will be used to determine the top-level
include directory to use for all encountered include statements. If it is
not passed, ``os.path.dirname(featurefile)`` will be considered the
include directory.
|
__init__
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/lexer.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/lexer.py
|
MIT
|
def parse(self):
"""Parse the file, and return a :class:`fontTools.feaLib.ast.FeatureFile`
object representing the root of the abstract syntax tree containing the
parsed contents of the file."""
statements = self.doc_.statements
while self.next_token_type_ is not None or self.cur_comments_:
self.advance_lexer_(comments=True)
if self.cur_token_type_ is Lexer.COMMENT:
statements.append(
self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
)
elif self.is_cur_keyword_("include"):
statements.append(self.parse_include_())
elif self.cur_token_type_ is Lexer.GLYPHCLASS:
statements.append(self.parse_glyphclass_definition_())
elif self.is_cur_keyword_(("anon", "anonymous")):
statements.append(self.parse_anonymous_())
elif self.is_cur_keyword_("anchorDef"):
statements.append(self.parse_anchordef_())
elif self.is_cur_keyword_("languagesystem"):
statements.append(self.parse_languagesystem_())
elif self.is_cur_keyword_("lookup"):
statements.append(self.parse_lookup_(vertical=False))
elif self.is_cur_keyword_("markClass"):
statements.append(self.parse_markClass_())
elif self.is_cur_keyword_("feature"):
statements.append(self.parse_feature_block_())
elif self.is_cur_keyword_("conditionset"):
statements.append(self.parse_conditionset_())
elif self.is_cur_keyword_("variation"):
statements.append(self.parse_feature_block_(variation=True))
elif self.is_cur_keyword_("table"):
statements.append(self.parse_table_())
elif self.is_cur_keyword_("valueRecordDef"):
statements.append(self.parse_valuerecord_definition_(vertical=False))
elif (
self.cur_token_type_ is Lexer.NAME
and self.cur_token_ in self.extensions
):
statements.append(self.extensions[self.cur_token_](self))
elif self.cur_token_type_ is Lexer.SYMBOL and self.cur_token_ == ";":
continue
else:
raise FeatureLibError(
"Expected feature, languagesystem, lookup, markClass, "
'table, or glyph class definition, got {} "{}"'.format(
self.cur_token_type_, self.cur_token_
),
self.cur_token_location_,
)
# Report any missing glyphs at the end of parsing
if self.missing:
error = [
" %s (first found at %s)" % (name, loc)
for name, loc in self.missing.items()
]
raise FeatureLibError(
"The following glyph names are referenced but are missing from the "
"glyph set:\n" + ("\n".join(error)),
None,
)
return self.doc_
|
Parse the file, and return a :class:`fontTools.feaLib.ast.FeatureFile`
object representing the root of the abstract syntax tree containing the
parsed contents of the file.
|
parse
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/parser.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/parser.py
|
MIT
|
def parse_name_(self):
"""Parses a name record. See `section 9.e <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#9.e>`_."""
platEncID = None
langID = None
if self.next_token_type_ in Lexer.NUMBERS:
platformID = self.expect_any_number_()
location = self.cur_token_location_
if platformID not in (1, 3):
raise FeatureLibError("Expected platform id 1 or 3", location)
if self.next_token_type_ in Lexer.NUMBERS:
platEncID = self.expect_any_number_()
langID = self.expect_any_number_()
else:
platformID = 3
location = self.cur_token_location_
if platformID == 1: # Macintosh
platEncID = platEncID or 0 # Roman
langID = langID or 0 # English
else: # 3, Windows
platEncID = platEncID or 1 # Unicode
langID = langID or 0x0409 # English
string = self.expect_string_()
self.expect_symbol_(";")
encoding = getEncoding(platformID, platEncID, langID)
if encoding is None:
raise FeatureLibError("Unsupported encoding", location)
unescaped = self.unescape_string_(string, encoding)
return platformID, platEncID, langID, unescaped
|
Parses a name record. See `section 9.e <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#9.e>`_.
|
parse_name_
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/parser.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/parser.py
|
MIT
|
def parse_featureNames_(self, tag):
"""Parses a ``featureNames`` statement found in stylistic set features.
See section `8.c <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#8.c>`_.
"""
assert self.cur_token_ == "featureNames", self.cur_token_
block = self.ast.NestedBlock(
tag, self.cur_token_, location=self.cur_token_location_
)
self.expect_symbol_("{")
for symtab in self.symbol_tables_:
symtab.enter_scope()
while self.next_token_ != "}" or self.cur_comments_:
self.advance_lexer_(comments=True)
if self.cur_token_type_ is Lexer.COMMENT:
block.statements.append(
self.ast.Comment(self.cur_token_, location=self.cur_token_location_)
)
elif self.is_cur_keyword_("name"):
location = self.cur_token_location_
platformID, platEncID, langID, string = self.parse_name_()
block.statements.append(
self.ast.FeatureNameStatement(
tag, platformID, platEncID, langID, string, location=location
)
)
elif self.cur_token_ == ";":
continue
else:
raise FeatureLibError('Expected "name"', self.cur_token_location_)
self.expect_symbol_("}")
for symtab in self.symbol_tables_:
symtab.exit_scope()
self.expect_symbol_(";")
return block
|
Parses a ``featureNames`` statement found in stylistic set features.
See section `8.c <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#8.c>`_.
|
parse_featureNames_
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/parser.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/parser.py
|
MIT
|
def check_glyph_name_in_glyph_set(self, *names):
"""Adds a glyph name (just `start`) or glyph names of a
range (`start` and `end`) which are not in the glyph set
to the "missing list" for future error reporting.
If no glyph set is present, does nothing.
"""
if self.glyphNames_:
for name in names:
if name in self.glyphNames_:
continue
if name not in self.missing:
self.missing[name] = self.cur_token_location_
|
Adds a glyph name (just `start`) or glyph names of a
range (`start` and `end`) which are not in the glyph set
to the "missing list" for future error reporting.
If no glyph set is present, does nothing.
|
check_glyph_name_in_glyph_set
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/parser.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/parser.py
|
MIT
|
def make_glyph_range_(self, location, start, limit):
"""(location, "a.sc", "d.sc") --> ["a.sc", "b.sc", "c.sc", "d.sc"]"""
result = list()
if len(start) != len(limit):
raise FeatureLibError(
'Bad range: "%s" and "%s" should have the same length' % (start, limit),
location,
)
rev = self.reverse_string_
prefix = os.path.commonprefix([start, limit])
suffix = rev(os.path.commonprefix([rev(start), rev(limit)]))
if len(suffix) > 0:
start_range = start[len(prefix) : -len(suffix)]
limit_range = limit[len(prefix) : -len(suffix)]
else:
start_range = start[len(prefix) :]
limit_range = limit[len(prefix) :]
if start_range >= limit_range:
raise FeatureLibError(
"Start of range must be smaller than its end", location
)
uppercase = re.compile(r"^[A-Z]$")
if uppercase.match(start_range) and uppercase.match(limit_range):
for c in range(ord(start_range), ord(limit_range) + 1):
result.append("%s%c%s" % (prefix, c, suffix))
return result
lowercase = re.compile(r"^[a-z]$")
if lowercase.match(start_range) and lowercase.match(limit_range):
for c in range(ord(start_range), ord(limit_range) + 1):
result.append("%s%c%s" % (prefix, c, suffix))
return result
digits = re.compile(r"^[0-9]{1,3}$")
if digits.match(start_range) and digits.match(limit_range):
for i in range(int(start_range, 10), int(limit_range, 10) + 1):
number = ("000" + str(i))[-len(start_range) :]
result.append("%s%s%s" % (prefix, number, suffix))
return result
raise FeatureLibError('Bad range: "%s-%s"' % (start, limit), location)
|
(location, "a.sc", "d.sc") --> ["a.sc", "b.sc", "c.sc", "d.sc"]
|
make_glyph_range_
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/parser.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/parser.py
|
MIT
|
def main(args=None):
"""Add features from a feature file (.fea) into an OTF font"""
parser = argparse.ArgumentParser(
description="Use fontTools to compile OpenType feature files (*.fea)."
)
parser.add_argument(
"input_fea", metavar="FEATURES", help="Path to the feature file"
)
parser.add_argument(
"input_font", metavar="INPUT_FONT", help="Path to the input font"
)
parser.add_argument(
"-o",
"--output",
dest="output_font",
metavar="OUTPUT_FONT",
help="Path to the output font.",
)
parser.add_argument(
"-t",
"--tables",
metavar="TABLE_TAG",
choices=Builder.supportedTables,
nargs="+",
help="Specify the table(s) to be built.",
)
parser.add_argument(
"-d",
"--debug",
action="store_true",
help="Add source-level debugging information to font.",
)
parser.add_argument(
"-v",
"--verbose",
help="Increase the logger verbosity. Multiple -v " "options are allowed.",
action="count",
default=0,
)
parser.add_argument(
"--traceback", help="show traceback for exceptions.", action="store_true"
)
options = parser.parse_args(args)
levels = ["WARNING", "INFO", "DEBUG"]
configLogger(level=levels[min(len(levels) - 1, options.verbose)])
output_font = options.output_font or makeOutputFileName(options.input_font)
log.info("Compiling features to '%s'" % (output_font))
font = TTFont(options.input_font)
try:
addOpenTypeFeatures(
font, options.input_fea, tables=options.tables, debug=options.debug
)
except FeatureLibError as e:
if options.traceback:
raise
log.error(e)
sys.exit(1)
font.save(output_font)
|
Add features from a feature file (.fea) into an OTF font
|
main
|
python
|
fonttools/fonttools
|
Lib/fontTools/feaLib/__main__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/feaLib/__main__.py
|
MIT
|
def add_method(*clazzes, **kwargs):
"""Returns a decorator function that adds a new method to one or
more classes."""
allowDefault = kwargs.get("allowDefaultTable", False)
def wrapper(method):
done = []
for clazz in clazzes:
if clazz in done:
continue # Support multiple names of a clazz
done.append(clazz)
assert allowDefault or clazz != DefaultTable, "Oops, table class not found."
assert (
method.__name__ not in clazz.__dict__
), "Oops, class '%s' has method '%s'." % (clazz.__name__, method.__name__)
setattr(clazz, method.__name__, method)
return None
return wrapper
|
Returns a decorator function that adds a new method to one or
more classes.
|
add_method
|
python
|
fonttools/fonttools
|
Lib/fontTools/merge/base.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/merge/base.py
|
MIT
|
def computeMegaGlyphOrder(merger, glyphOrders):
"""Modifies passed-in glyphOrders to reflect new glyph names.
Stores merger.glyphOrder."""
megaOrder = {}
for glyphOrder in glyphOrders:
for i, glyphName in enumerate(glyphOrder):
if glyphName in megaOrder:
n = megaOrder[glyphName]
while (glyphName + "." + repr(n)) in megaOrder:
n += 1
megaOrder[glyphName] = n
glyphName += "." + repr(n)
glyphOrder[i] = glyphName
megaOrder[glyphName] = 1
merger.glyphOrder = megaOrder = list(megaOrder.keys())
|
Modifies passed-in glyphOrders to reflect new glyph names.
Stores merger.glyphOrder.
|
computeMegaGlyphOrder
|
python
|
fonttools/fonttools
|
Lib/fontTools/merge/cmap.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/merge/cmap.py
|
MIT
|
def computeMegaUvs(merger, uvsTables):
"""Returns merged UVS subtable (cmap format=14)."""
uvsDict = {}
cmap = merger.cmap
for table in uvsTables:
for variationSelector, uvsMapping in table.uvsDict.items():
if variationSelector not in uvsDict:
uvsDict[variationSelector] = {}
for unicodeValue, glyphName in uvsMapping:
if cmap.get(unicodeValue) == glyphName:
# this is a default variation
glyphName = None
# prefer previous glyph id if both fonts defined UVS
if unicodeValue not in uvsDict[variationSelector]:
uvsDict[variationSelector][unicodeValue] = glyphName
for variationSelector in uvsDict:
uvsDict[variationSelector] = [*uvsDict[variationSelector].items()]
return uvsDict
|
Returns merged UVS subtable (cmap format=14).
|
computeMegaUvs
|
python
|
fonttools/fonttools
|
Lib/fontTools/merge/cmap.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/merge/cmap.py
|
MIT
|
def computeMegaCmap(merger, cmapTables):
"""Sets merger.cmap and merger.uvsDict."""
# TODO Handle format=14.
# Only merge format 4 and 12 Unicode subtables, ignores all other subtables
# If there is a format 12 table for a font, ignore the format 4 table of it
chosenCmapTables = []
chosenUvsTables = []
for fontIdx, table in enumerate(cmapTables):
format4 = None
format12 = None
format14 = None
for subtable in table.tables:
properties = (subtable.format, subtable.platformID, subtable.platEncID)
if properties in _CmapUnicodePlatEncodings.BMP:
format4 = subtable
elif properties in _CmapUnicodePlatEncodings.FullRepertoire:
format12 = subtable
elif properties in _CmapUnicodePlatEncodings.UVS:
format14 = subtable
else:
log.warning(
"Dropped cmap subtable from font '%s':\t"
"format %2s, platformID %2s, platEncID %2s",
fontIdx,
subtable.format,
subtable.platformID,
subtable.platEncID,
)
if format12 is not None:
chosenCmapTables.append((format12, fontIdx))
elif format4 is not None:
chosenCmapTables.append((format4, fontIdx))
if format14 is not None:
chosenUvsTables.append(format14)
# Build the unicode mapping
merger.cmap = cmap = {}
fontIndexForGlyph = {}
glyphSets = [None for f in merger.fonts] if hasattr(merger, "fonts") else None
for table, fontIdx in chosenCmapTables:
# handle duplicates
for uni, gid in table.cmap.items():
oldgid = cmap.get(uni, None)
if oldgid is None:
cmap[uni] = gid
fontIndexForGlyph[gid] = fontIdx
elif is_Default_Ignorable(uni) or uni in (0x25CC,): # U+25CC DOTTED CIRCLE
continue
elif oldgid != gid:
# Char previously mapped to oldgid, now to gid.
# Record, to fix up in GSUB 'locl' later.
if merger.duplicateGlyphsPerFont[fontIdx].get(oldgid) is None:
if glyphSets is not None:
oldFontIdx = fontIndexForGlyph[oldgid]
for idx in (fontIdx, oldFontIdx):
if glyphSets[idx] is None:
glyphSets[idx] = merger.fonts[idx].getGlyphSet()
# if _glyphsAreSame(glyphSets[oldFontIdx], glyphSets[fontIdx], oldgid, gid):
# continue
merger.duplicateGlyphsPerFont[fontIdx][oldgid] = gid
elif merger.duplicateGlyphsPerFont[fontIdx][oldgid] != gid:
# Char previously mapped to oldgid but oldgid is already remapped to a different
# gid, because of another Unicode character.
# TODO: Try harder to do something about these.
log.warning(
"Dropped mapping from codepoint %#06X to glyphId '%s'", uni, gid
)
merger.uvsDict = computeMegaUvs(merger, chosenUvsTables)
|
Sets merger.cmap and merger.uvsDict.
|
computeMegaCmap
|
python
|
fonttools/fonttools
|
Lib/fontTools/merge/cmap.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/merge/cmap.py
|
MIT
|
def renameCFFCharStrings(merger, glyphOrder, cffTable):
"""Rename topDictIndex charStrings based on glyphOrder."""
td = cffTable.cff.topDictIndex[0]
charStrings = {}
for i, v in enumerate(td.CharStrings.charStrings.values()):
glyphName = glyphOrder[i]
charStrings[glyphName] = v
td.CharStrings.charStrings = charStrings
td.charset = list(glyphOrder)
|
Rename topDictIndex charStrings based on glyphOrder.
|
renameCFFCharStrings
|
python
|
fonttools/fonttools
|
Lib/fontTools/merge/cmap.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/merge/cmap.py
|
MIT
|
def onlyExisting(func):
"""Returns a filter func that when called with a list,
only calls func on the non-NotImplemented items of the list,
and only so if there's at least one item remaining.
Otherwise returns NotImplemented."""
def wrapper(lst):
items = [item for item in lst if item is not NotImplemented]
return func(items) if items else NotImplemented
return wrapper
|
Returns a filter func that when called with a list,
only calls func on the non-NotImplemented items of the list,
and only so if there's at least one item remaining.
Otherwise returns NotImplemented.
|
onlyExisting
|
python
|
fonttools/fonttools
|
Lib/fontTools/merge/util.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/merge/util.py
|
MIT
|
def merge(self, fontfiles):
"""Merges fonts together.
Args:
fontfiles: A list of file names to be merged
Returns:
A :class:`fontTools.ttLib.TTFont` object. Call the ``save`` method on
this to write it out to an OTF file.
"""
#
# Settle on a mega glyph order.
#
fonts = self._openFonts(fontfiles)
glyphOrders = [list(font.getGlyphOrder()) for font in fonts]
computeMegaGlyphOrder(self, glyphOrders)
# Take first input file sfntVersion
sfntVersion = fonts[0].sfntVersion
# Reload fonts and set new glyph names on them.
fonts = self._openFonts(fontfiles)
for font, glyphOrder in zip(fonts, glyphOrders):
font.setGlyphOrder(glyphOrder)
if "CFF " in font:
renameCFFCharStrings(self, glyphOrder, font["CFF "])
cmaps = [font["cmap"] for font in fonts]
self.duplicateGlyphsPerFont = [{} for _ in fonts]
computeMegaCmap(self, cmaps)
mega = ttLib.TTFont(sfntVersion=sfntVersion)
mega.setGlyphOrder(self.glyphOrder)
for font in fonts:
self._preMerge(font)
self.fonts = fonts
allTags = reduce(set.union, (list(font.keys()) for font in fonts), set())
allTags.remove("GlyphOrder")
for tag in sorted(allTags):
if tag in self.options.drop_tables:
continue
with timer("merge '%s'" % tag):
tables = [font.get(tag, NotImplemented) for font in fonts]
log.info("Merging '%s'.", tag)
clazz = ttLib.getTableClass(tag)
table = clazz(tag).merge(self, tables)
# XXX Clean this up and use: table = mergeObjects(tables)
if table is not NotImplemented and table is not False:
mega[tag] = table
log.info("Merged '%s'.", tag)
else:
log.info("Dropped '%s'.", tag)
del self.duplicateGlyphsPerFont
del self.fonts
self._postMerge(mega)
return mega
|
Merges fonts together.
Args:
fontfiles: A list of file names to be merged
Returns:
A :class:`fontTools.ttLib.TTFont` object. Call the ``save`` method on
this to write it out to an OTF file.
|
merge
|
python
|
fonttools/fonttools
|
Lib/fontTools/merge/__init__.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/merge/__init__.py
|
MIT
|
def calcBounds(array):
"""Calculate the bounding rectangle of a 2D points array.
Args:
array: A sequence of 2D tuples.
Returns:
A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
"""
if not array:
return 0, 0, 0, 0
xs = [x for x, y in array]
ys = [y for x, y in array]
return min(xs), min(ys), max(xs), max(ys)
|
Calculate the bounding rectangle of a 2D points array.
Args:
array: A sequence of 2D tuples.
Returns:
A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
|
calcBounds
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def updateBounds(bounds, p, min=min, max=max):
"""Add a point to a bounding rectangle.
Args:
bounds: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax), or None``.
p: A 2D tuple representing a point.
min,max: functions to compute the minimum and maximum.
Returns:
The updated bounding rectangle ``(xMin, yMin, xMax, yMax)``.
"""
(x, y) = p
if bounds is None:
return x, y, x, y
xMin, yMin, xMax, yMax = bounds
return min(xMin, x), min(yMin, y), max(xMax, x), max(yMax, y)
|
Add a point to a bounding rectangle.
Args:
bounds: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax), or None``.
p: A 2D tuple representing a point.
min,max: functions to compute the minimum and maximum.
Returns:
The updated bounding rectangle ``(xMin, yMin, xMax, yMax)``.
|
updateBounds
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def pointInRect(p, rect):
"""Test if a point is inside a bounding rectangle.
Args:
p: A 2D tuple representing a point.
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
Returns:
``True`` if the point is inside the rectangle, ``False`` otherwise.
"""
(x, y) = p
xMin, yMin, xMax, yMax = rect
return (xMin <= x <= xMax) and (yMin <= y <= yMax)
|
Test if a point is inside a bounding rectangle.
Args:
p: A 2D tuple representing a point.
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
Returns:
``True`` if the point is inside the rectangle, ``False`` otherwise.
|
pointInRect
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def pointsInRect(array, rect):
"""Determine which points are inside a bounding rectangle.
Args:
array: A sequence of 2D tuples.
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
Returns:
A list containing the points inside the rectangle.
"""
if len(array) < 1:
return []
xMin, yMin, xMax, yMax = rect
return [(xMin <= x <= xMax) and (yMin <= y <= yMax) for x, y in array]
|
Determine which points are inside a bounding rectangle.
Args:
array: A sequence of 2D tuples.
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
Returns:
A list containing the points inside the rectangle.
|
pointsInRect
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def vectorLength(vector):
"""Calculate the length of the given vector.
Args:
vector: A 2D tuple.
Returns:
The Euclidean length of the vector.
"""
x, y = vector
return math.sqrt(x**2 + y**2)
|
Calculate the length of the given vector.
Args:
vector: A 2D tuple.
Returns:
The Euclidean length of the vector.
|
vectorLength
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def normRect(rect):
"""Normalize a bounding box rectangle.
This function "turns the rectangle the right way up", so that the following
holds::
xMin <= xMax and yMin <= yMax
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
Returns:
A normalized bounding rectangle.
"""
(xMin, yMin, xMax, yMax) = rect
return min(xMin, xMax), min(yMin, yMax), max(xMin, xMax), max(yMin, yMax)
|
Normalize a bounding box rectangle.
This function "turns the rectangle the right way up", so that the following
holds::
xMin <= xMax and yMin <= yMax
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
Returns:
A normalized bounding rectangle.
|
normRect
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def scaleRect(rect, x, y):
"""Scale a bounding box rectangle.
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
x: Factor to scale the rectangle along the X axis.
Y: Factor to scale the rectangle along the Y axis.
Returns:
A scaled bounding rectangle.
"""
(xMin, yMin, xMax, yMax) = rect
return xMin * x, yMin * y, xMax * x, yMax * y
|
Scale a bounding box rectangle.
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
x: Factor to scale the rectangle along the X axis.
Y: Factor to scale the rectangle along the Y axis.
Returns:
A scaled bounding rectangle.
|
scaleRect
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def offsetRect(rect, dx, dy):
"""Offset a bounding box rectangle.
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
dx: Amount to offset the rectangle along the X axis.
dY: Amount to offset the rectangle along the Y axis.
Returns:
An offset bounding rectangle.
"""
(xMin, yMin, xMax, yMax) = rect
return xMin + dx, yMin + dy, xMax + dx, yMax + dy
|
Offset a bounding box rectangle.
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
dx: Amount to offset the rectangle along the X axis.
dY: Amount to offset the rectangle along the Y axis.
Returns:
An offset bounding rectangle.
|
offsetRect
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def insetRect(rect, dx, dy):
"""Inset a bounding box rectangle on all sides.
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
dx: Amount to inset the rectangle along the X axis.
dY: Amount to inset the rectangle along the Y axis.
Returns:
An inset bounding rectangle.
"""
(xMin, yMin, xMax, yMax) = rect
return xMin + dx, yMin + dy, xMax - dx, yMax - dy
|
Inset a bounding box rectangle on all sides.
Args:
rect: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
dx: Amount to inset the rectangle along the X axis.
dY: Amount to inset the rectangle along the Y axis.
Returns:
An inset bounding rectangle.
|
insetRect
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def sectRect(rect1, rect2):
"""Test for rectangle-rectangle intersection.
Args:
rect1: First bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
rect2: Second bounding rectangle.
Returns:
A boolean and a rectangle.
If the input rectangles intersect, returns ``True`` and the intersecting
rectangle. Returns ``False`` and ``(0, 0, 0, 0)`` if the input
rectangles don't intersect.
"""
(xMin1, yMin1, xMax1, yMax1) = rect1
(xMin2, yMin2, xMax2, yMax2) = rect2
xMin, yMin, xMax, yMax = (
max(xMin1, xMin2),
max(yMin1, yMin2),
min(xMax1, xMax2),
min(yMax1, yMax2),
)
if xMin >= xMax or yMin >= yMax:
return False, (0, 0, 0, 0)
return True, (xMin, yMin, xMax, yMax)
|
Test for rectangle-rectangle intersection.
Args:
rect1: First bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
rect2: Second bounding rectangle.
Returns:
A boolean and a rectangle.
If the input rectangles intersect, returns ``True`` and the intersecting
rectangle. Returns ``False`` and ``(0, 0, 0, 0)`` if the input
rectangles don't intersect.
|
sectRect
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def unionRect(rect1, rect2):
"""Determine union of bounding rectangles.
Args:
rect1: First bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
rect2: Second bounding rectangle.
Returns:
The smallest rectangle in which both input rectangles are fully
enclosed.
"""
(xMin1, yMin1, xMax1, yMax1) = rect1
(xMin2, yMin2, xMax2, yMax2) = rect2
xMin, yMin, xMax, yMax = (
min(xMin1, xMin2),
min(yMin1, yMin2),
max(xMax1, xMax2),
max(yMax1, yMax2),
)
return (xMin, yMin, xMax, yMax)
|
Determine union of bounding rectangles.
Args:
rect1: First bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
rect2: Second bounding rectangle.
Returns:
The smallest rectangle in which both input rectangles are fully
enclosed.
|
unionRect
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def rectCenter(rect):
"""Determine rectangle center.
Args:
rect: Bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
Returns:
A 2D tuple representing the point at the center of the rectangle.
"""
(xMin, yMin, xMax, yMax) = rect
return (xMin + xMax) / 2, (yMin + yMax) / 2
|
Determine rectangle center.
Args:
rect: Bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
Returns:
A 2D tuple representing the point at the center of the rectangle.
|
rectCenter
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def rectArea(rect):
"""Determine rectangle area.
Args:
rect: Bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
Returns:
The area of the rectangle.
"""
(xMin, yMin, xMax, yMax) = rect
return (yMax - yMin) * (xMax - xMin)
|
Determine rectangle area.
Args:
rect: Bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
Returns:
The area of the rectangle.
|
rectArea
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def intRect(rect):
"""Round a rectangle to integer values.
Guarantees that the resulting rectangle is NOT smaller than the original.
Args:
rect: Bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
Returns:
A rounded bounding rectangle.
"""
(xMin, yMin, xMax, yMax) = rect
xMin = int(math.floor(xMin))
yMin = int(math.floor(yMin))
xMax = int(math.ceil(xMax))
yMax = int(math.ceil(yMax))
return (xMin, yMin, xMax, yMax)
|
Round a rectangle to integer values.
Guarantees that the resulting rectangle is NOT smaller than the original.
Args:
rect: Bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
Returns:
A rounded bounding rectangle.
|
intRect
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def quantizeRect(rect, factor=1):
"""
>>> bounds = (72.3, -218.4, 1201.3, 919.1)
>>> quantizeRect(bounds)
(72, -219, 1202, 920)
>>> quantizeRect(bounds, factor=10)
(70, -220, 1210, 920)
>>> quantizeRect(bounds, factor=100)
(0, -300, 1300, 1000)
"""
if factor < 1:
raise ValueError(f"Expected quantization factor >= 1, found: {factor!r}")
xMin, yMin, xMax, yMax = normRect(rect)
return (
int(math.floor(xMin / factor) * factor),
int(math.floor(yMin / factor) * factor),
int(math.ceil(xMax / factor) * factor),
int(math.ceil(yMax / factor) * factor),
)
|
>>> bounds = (72.3, -218.4, 1201.3, 919.1)
>>> quantizeRect(bounds)
(72, -219, 1202, 920)
>>> quantizeRect(bounds, factor=10)
(70, -220, 1210, 920)
>>> quantizeRect(bounds, factor=100)
(0, -300, 1300, 1000)
|
quantizeRect
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def pairwise(iterable, reverse=False):
"""Iterate over current and next items in iterable.
Args:
iterable: An iterable
reverse: If true, iterate in reverse order.
Returns:
A iterable yielding two elements per iteration.
Example:
>>> tuple(pairwise([]))
()
>>> tuple(pairwise([], reverse=True))
()
>>> tuple(pairwise([0]))
((0, 0),)
>>> tuple(pairwise([0], reverse=True))
((0, 0),)
>>> tuple(pairwise([0, 1]))
((0, 1), (1, 0))
>>> tuple(pairwise([0, 1], reverse=True))
((1, 0), (0, 1))
>>> tuple(pairwise([0, 1, 2]))
((0, 1), (1, 2), (2, 0))
>>> tuple(pairwise([0, 1, 2], reverse=True))
((2, 1), (1, 0), (0, 2))
>>> tuple(pairwise(['a', 'b', 'c', 'd']))
(('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'))
>>> tuple(pairwise(['a', 'b', 'c', 'd'], reverse=True))
(('d', 'c'), ('c', 'b'), ('b', 'a'), ('a', 'd'))
"""
if not iterable:
return
if reverse:
it = reversed(iterable)
else:
it = iter(iterable)
first = next(it, None)
a = first
for b in it:
yield (a, b)
a = b
yield (a, first)
|
Iterate over current and next items in iterable.
Args:
iterable: An iterable
reverse: If true, iterate in reverse order.
Returns:
A iterable yielding two elements per iteration.
Example:
>>> tuple(pairwise([]))
()
>>> tuple(pairwise([], reverse=True))
()
>>> tuple(pairwise([0]))
((0, 0),)
>>> tuple(pairwise([0], reverse=True))
((0, 0),)
>>> tuple(pairwise([0, 1]))
((0, 1), (1, 0))
>>> tuple(pairwise([0, 1], reverse=True))
((1, 0), (0, 1))
>>> tuple(pairwise([0, 1, 2]))
((0, 1), (1, 2), (2, 0))
>>> tuple(pairwise([0, 1, 2], reverse=True))
((2, 1), (1, 0), (0, 2))
>>> tuple(pairwise(['a', 'b', 'c', 'd']))
(('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'))
>>> tuple(pairwise(['a', 'b', 'c', 'd'], reverse=True))
(('d', 'c'), ('c', 'b'), ('b', 'a'), ('a', 'd'))
|
pairwise
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def _test():
"""
>>> import math
>>> calcBounds([])
(0, 0, 0, 0)
>>> calcBounds([(0, 40), (0, 100), (50, 50), (80, 10)])
(0, 10, 80, 100)
>>> updateBounds((0, 0, 0, 0), (100, 100))
(0, 0, 100, 100)
>>> pointInRect((50, 50), (0, 0, 100, 100))
True
>>> pointInRect((0, 0), (0, 0, 100, 100))
True
>>> pointInRect((100, 100), (0, 0, 100, 100))
True
>>> not pointInRect((101, 100), (0, 0, 100, 100))
True
>>> list(pointsInRect([(50, 50), (0, 0), (100, 100), (101, 100)], (0, 0, 100, 100)))
[True, True, True, False]
>>> vectorLength((3, 4))
5.0
>>> vectorLength((1, 1)) == math.sqrt(2)
True
>>> list(asInt16([0, 0.1, 0.5, 0.9]))
[0, 0, 1, 1]
>>> normRect((0, 10, 100, 200))
(0, 10, 100, 200)
>>> normRect((100, 200, 0, 10))
(0, 10, 100, 200)
>>> scaleRect((10, 20, 50, 150), 1.5, 2)
(15.0, 40, 75.0, 300)
>>> offsetRect((10, 20, 30, 40), 5, 6)
(15, 26, 35, 46)
>>> insetRect((10, 20, 50, 60), 5, 10)
(15, 30, 45, 50)
>>> insetRect((10, 20, 50, 60), -5, -10)
(5, 10, 55, 70)
>>> intersects, rect = sectRect((0, 10, 20, 30), (0, 40, 20, 50))
>>> not intersects
True
>>> intersects, rect = sectRect((0, 10, 20, 30), (5, 20, 35, 50))
>>> intersects
1
>>> rect
(5, 20, 20, 30)
>>> unionRect((0, 10, 20, 30), (0, 40, 20, 50))
(0, 10, 20, 50)
>>> rectCenter((0, 0, 100, 200))
(50.0, 100.0)
>>> rectCenter((0, 0, 100, 199.0))
(50.0, 99.5)
>>> intRect((0.9, 2.9, 3.1, 4.1))
(0, 2, 4, 5)
"""
|
>>> import math
>>> calcBounds([])
(0, 0, 0, 0)
>>> calcBounds([(0, 40), (0, 100), (50, 50), (80, 10)])
(0, 10, 80, 100)
>>> updateBounds((0, 0, 0, 0), (100, 100))
(0, 0, 100, 100)
>>> pointInRect((50, 50), (0, 0, 100, 100))
True
>>> pointInRect((0, 0), (0, 0, 100, 100))
True
>>> pointInRect((100, 100), (0, 0, 100, 100))
True
>>> not pointInRect((101, 100), (0, 0, 100, 100))
True
>>> list(pointsInRect([(50, 50), (0, 0), (100, 100), (101, 100)], (0, 0, 100, 100)))
[True, True, True, False]
>>> vectorLength((3, 4))
5.0
>>> vectorLength((1, 1)) == math.sqrt(2)
True
>>> list(asInt16([0, 0.1, 0.5, 0.9]))
[0, 0, 1, 1]
>>> normRect((0, 10, 100, 200))
(0, 10, 100, 200)
>>> normRect((100, 200, 0, 10))
(0, 10, 100, 200)
>>> scaleRect((10, 20, 50, 150), 1.5, 2)
(15.0, 40, 75.0, 300)
>>> offsetRect((10, 20, 30, 40), 5, 6)
(15, 26, 35, 46)
>>> insetRect((10, 20, 50, 60), 5, 10)
(15, 30, 45, 50)
>>> insetRect((10, 20, 50, 60), -5, -10)
(5, 10, 55, 70)
>>> intersects, rect = sectRect((0, 10, 20, 30), (0, 40, 20, 50))
>>> not intersects
True
>>> intersects, rect = sectRect((0, 10, 20, 30), (5, 20, 35, 50))
>>> intersects
1
>>> rect
(5, 20, 20, 30)
>>> unionRect((0, 10, 20, 30), (0, 40, 20, 50))
(0, 10, 20, 50)
>>> rectCenter((0, 0, 100, 200))
(50.0, 100.0)
>>> rectCenter((0, 0, 100, 199.0))
(50.0, 99.5)
>>> intRect((0.9, 2.9, 3.1, 4.1))
(0, 2, 4, 5)
|
_test
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/arrayTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/arrayTools.py
|
MIT
|
def calcCubicArcLength(pt1, pt2, pt3, pt4, tolerance=0.005):
"""Calculates the arc length for a cubic Bezier segment.
Whereas :func:`approximateCubicArcLength` approximates the length, this
function calculates it by "measuring", recursively dividing the curve
until the divided segments are shorter than ``tolerance``.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
tolerance: Controls the precision of the calcuation.
Returns:
Arc length value.
"""
return calcCubicArcLengthC(
complex(*pt1), complex(*pt2), complex(*pt3), complex(*pt4), tolerance
)
|
Calculates the arc length for a cubic Bezier segment.
Whereas :func:`approximateCubicArcLength` approximates the length, this
function calculates it by "measuring", recursively dividing the curve
until the divided segments are shorter than ``tolerance``.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
tolerance: Controls the precision of the calcuation.
Returns:
Arc length value.
|
calcCubicArcLength
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def calcCubicArcLengthC(pt1, pt2, pt3, pt4, tolerance=0.005):
"""Calculates the arc length for a cubic Bezier segment.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.
tolerance: Controls the precision of the calcuation.
Returns:
Arc length value.
"""
mult = 1.0 + 1.5 * tolerance # The 1.5 is a empirical hack; no math
return _calcCubicArcLengthCRecurse(mult, pt1, pt2, pt3, pt4)
|
Calculates the arc length for a cubic Bezier segment.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.
tolerance: Controls the precision of the calcuation.
Returns:
Arc length value.
|
calcCubicArcLengthC
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def calcQuadraticArcLengthC(pt1, pt2, pt3):
"""Calculates the arc length for a quadratic Bezier segment.
Args:
pt1: Start point of the Bezier as a complex number.
pt2: Handle point of the Bezier as a complex number.
pt3: End point of the Bezier as a complex number.
Returns:
Arc length value.
"""
# Analytical solution to the length of a quadratic bezier.
# Documentation: https://github.com/fonttools/fonttools/issues/3055
d0 = pt2 - pt1
d1 = pt3 - pt2
d = d1 - d0
n = d * 1j
scale = abs(n)
if scale == 0.0:
return abs(pt3 - pt1)
origDist = _dot(n, d0)
if abs(origDist) < epsilon:
if _dot(d0, d1) >= 0:
return abs(pt3 - pt1)
a, b = abs(d0), abs(d1)
return (a * a + b * b) / (a + b)
x0 = _dot(d, d0) / origDist
x1 = _dot(d, d1) / origDist
Len = abs(2 * (_intSecAtan(x1) - _intSecAtan(x0)) * origDist / (scale * (x1 - x0)))
return Len
|
Calculates the arc length for a quadratic Bezier segment.
Args:
pt1: Start point of the Bezier as a complex number.
pt2: Handle point of the Bezier as a complex number.
pt3: End point of the Bezier as a complex number.
Returns:
Arc length value.
|
calcQuadraticArcLengthC
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def calcQuadraticBounds(pt1, pt2, pt3):
"""Calculates the bounding rectangle for a quadratic Bezier segment.
Args:
pt1: Start point of the Bezier as a 2D tuple.
pt2: Handle point of the Bezier as a 2D tuple.
pt3: End point of the Bezier as a 2D tuple.
Returns:
A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
Example::
>>> calcQuadraticBounds((0, 0), (50, 100), (100, 0))
(0, 0, 100, 50.0)
>>> calcQuadraticBounds((0, 0), (100, 0), (100, 100))
(0.0, 0.0, 100, 100)
"""
(ax, ay), (bx, by), (cx, cy) = calcQuadraticParameters(pt1, pt2, pt3)
ax2 = ax * 2.0
ay2 = ay * 2.0
roots = []
if ax2 != 0:
roots.append(-bx / ax2)
if ay2 != 0:
roots.append(-by / ay2)
points = [
(ax * t * t + bx * t + cx, ay * t * t + by * t + cy)
for t in roots
if 0 <= t < 1
] + [pt1, pt3]
return calcBounds(points)
|
Calculates the bounding rectangle for a quadratic Bezier segment.
Args:
pt1: Start point of the Bezier as a 2D tuple.
pt2: Handle point of the Bezier as a 2D tuple.
pt3: End point of the Bezier as a 2D tuple.
Returns:
A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
Example::
>>> calcQuadraticBounds((0, 0), (50, 100), (100, 0))
(0, 0, 100, 50.0)
>>> calcQuadraticBounds((0, 0), (100, 0), (100, 100))
(0.0, 0.0, 100, 100)
|
calcQuadraticBounds
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def approximateCubicArcLength(pt1, pt2, pt3, pt4):
"""Approximates the arc length for a cubic Bezier segment.
Uses Gauss-Lobatto quadrature with n=5 points to approximate arc length.
See :func:`calcCubicArcLength` for a slower but more accurate result.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
Returns:
Arc length value.
Example::
>>> approximateCubicArcLength((0, 0), (25, 100), (75, 100), (100, 0))
190.04332968932817
>>> approximateCubicArcLength((0, 0), (50, 0), (100, 50), (100, 100))
154.8852074945903
>>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (150, 0)) # line; exact result should be 150.
149.99999999999991
>>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (-50, 0)) # cusp; exact result should be 150.
136.9267662156362
>>> approximateCubicArcLength((0, 0), (50, 0), (100, -50), (-50, 0)) # cusp
154.80848416537057
"""
return approximateCubicArcLengthC(
complex(*pt1), complex(*pt2), complex(*pt3), complex(*pt4)
)
|
Approximates the arc length for a cubic Bezier segment.
Uses Gauss-Lobatto quadrature with n=5 points to approximate arc length.
See :func:`calcCubicArcLength` for a slower but more accurate result.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
Returns:
Arc length value.
Example::
>>> approximateCubicArcLength((0, 0), (25, 100), (75, 100), (100, 0))
190.04332968932817
>>> approximateCubicArcLength((0, 0), (50, 0), (100, 50), (100, 100))
154.8852074945903
>>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (150, 0)) # line; exact result should be 150.
149.99999999999991
>>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (-50, 0)) # cusp; exact result should be 150.
136.9267662156362
>>> approximateCubicArcLength((0, 0), (50, 0), (100, -50), (-50, 0)) # cusp
154.80848416537057
|
approximateCubicArcLength
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def calcCubicBounds(pt1, pt2, pt3, pt4):
"""Calculates the bounding rectangle for a quadratic Bezier segment.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
Returns:
A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
Example::
>>> calcCubicBounds((0, 0), (25, 100), (75, 100), (100, 0))
(0, 0, 100, 75.0)
>>> calcCubicBounds((0, 0), (50, 0), (100, 50), (100, 100))
(0.0, 0.0, 100, 100)
>>> print("%f %f %f %f" % calcCubicBounds((50, 0), (0, 100), (100, 100), (50, 0)))
35.566243 0.000000 64.433757 75.000000
"""
(ax, ay), (bx, by), (cx, cy), (dx, dy) = calcCubicParameters(pt1, pt2, pt3, pt4)
# calc first derivative
ax3 = ax * 3.0
ay3 = ay * 3.0
bx2 = bx * 2.0
by2 = by * 2.0
xRoots = [t for t in solveQuadratic(ax3, bx2, cx) if 0 <= t < 1]
yRoots = [t for t in solveQuadratic(ay3, by2, cy) if 0 <= t < 1]
roots = xRoots + yRoots
points = [
(
ax * t * t * t + bx * t * t + cx * t + dx,
ay * t * t * t + by * t * t + cy * t + dy,
)
for t in roots
] + [pt1, pt4]
return calcBounds(points)
|
Calculates the bounding rectangle for a quadratic Bezier segment.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
Returns:
A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
Example::
>>> calcCubicBounds((0, 0), (25, 100), (75, 100), (100, 0))
(0, 0, 100, 75.0)
>>> calcCubicBounds((0, 0), (50, 0), (100, 50), (100, 100))
(0.0, 0.0, 100, 100)
>>> print("%f %f %f %f" % calcCubicBounds((50, 0), (0, 100), (100, 100), (50, 0)))
35.566243 0.000000 64.433757 75.000000
|
calcCubicBounds
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def splitLine(pt1, pt2, where, isHorizontal):
"""Split a line at a given coordinate.
Args:
pt1: Start point of line as 2D tuple.
pt2: End point of line as 2D tuple.
where: Position at which to split the line.
isHorizontal: Direction of the ray splitting the line. If true,
``where`` is interpreted as a Y coordinate; if false, then
``where`` is interpreted as an X coordinate.
Returns:
A list of two line segments (each line segment being two 2D tuples)
if the line was successfully split, or a list containing the original
line.
Example::
>>> printSegments(splitLine((0, 0), (100, 100), 50, True))
((0, 0), (50, 50))
((50, 50), (100, 100))
>>> printSegments(splitLine((0, 0), (100, 100), 100, True))
((0, 0), (100, 100))
>>> printSegments(splitLine((0, 0), (100, 100), 0, True))
((0, 0), (0, 0))
((0, 0), (100, 100))
>>> printSegments(splitLine((0, 0), (100, 100), 0, False))
((0, 0), (0, 0))
((0, 0), (100, 100))
>>> printSegments(splitLine((100, 0), (0, 0), 50, False))
((100, 0), (50, 0))
((50, 0), (0, 0))
>>> printSegments(splitLine((0, 100), (0, 0), 50, True))
((0, 100), (0, 50))
((0, 50), (0, 0))
"""
pt1x, pt1y = pt1
pt2x, pt2y = pt2
ax = pt2x - pt1x
ay = pt2y - pt1y
bx = pt1x
by = pt1y
a = (ax, ay)[isHorizontal]
if a == 0:
return [(pt1, pt2)]
t = (where - (bx, by)[isHorizontal]) / a
if 0 <= t < 1:
midPt = ax * t + bx, ay * t + by
return [(pt1, midPt), (midPt, pt2)]
else:
return [(pt1, pt2)]
|
Split a line at a given coordinate.
Args:
pt1: Start point of line as 2D tuple.
pt2: End point of line as 2D tuple.
where: Position at which to split the line.
isHorizontal: Direction of the ray splitting the line. If true,
``where`` is interpreted as a Y coordinate; if false, then
``where`` is interpreted as an X coordinate.
Returns:
A list of two line segments (each line segment being two 2D tuples)
if the line was successfully split, or a list containing the original
line.
Example::
>>> printSegments(splitLine((0, 0), (100, 100), 50, True))
((0, 0), (50, 50))
((50, 50), (100, 100))
>>> printSegments(splitLine((0, 0), (100, 100), 100, True))
((0, 0), (100, 100))
>>> printSegments(splitLine((0, 0), (100, 100), 0, True))
((0, 0), (0, 0))
((0, 0), (100, 100))
>>> printSegments(splitLine((0, 0), (100, 100), 0, False))
((0, 0), (0, 0))
((0, 0), (100, 100))
>>> printSegments(splitLine((100, 0), (0, 0), 50, False))
((100, 0), (50, 0))
((50, 0), (0, 0))
>>> printSegments(splitLine((0, 100), (0, 0), 50, True))
((0, 100), (0, 50))
((0, 50), (0, 0))
|
splitLine
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def splitQuadratic(pt1, pt2, pt3, where, isHorizontal):
"""Split a quadratic Bezier curve at a given coordinate.
Args:
pt1,pt2,pt3: Control points of the Bezier as 2D tuples.
where: Position at which to split the curve.
isHorizontal: Direction of the ray splitting the curve. If true,
``where`` is interpreted as a Y coordinate; if false, then
``where`` is interpreted as an X coordinate.
Returns:
A list of two curve segments (each curve segment being three 2D tuples)
if the curve was successfully split, or a list containing the original
curve.
Example::
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 150, False))
((0, 0), (50, 100), (100, 0))
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, False))
((0, 0), (25, 50), (50, 50))
((50, 50), (75, 50), (100, 0))
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, False))
((0, 0), (12.5, 25), (25, 37.5))
((25, 37.5), (62.5, 75), (100, 0))
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, True))
((0, 0), (7.32233, 14.6447), (14.6447, 25))
((14.6447, 25), (50, 75), (85.3553, 25))
((85.3553, 25), (92.6777, 14.6447), (100, -7.10543e-15))
>>> # XXX I'm not at all sure if the following behavior is desirable:
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, True))
((0, 0), (25, 50), (50, 50))
((50, 50), (50, 50), (50, 50))
((50, 50), (75, 50), (100, 0))
"""
a, b, c = calcQuadraticParameters(pt1, pt2, pt3)
solutions = solveQuadratic(
a[isHorizontal], b[isHorizontal], c[isHorizontal] - where
)
solutions = sorted(t for t in solutions if 0 <= t < 1)
if not solutions:
return [(pt1, pt2, pt3)]
return _splitQuadraticAtT(a, b, c, *solutions)
|
Split a quadratic Bezier curve at a given coordinate.
Args:
pt1,pt2,pt3: Control points of the Bezier as 2D tuples.
where: Position at which to split the curve.
isHorizontal: Direction of the ray splitting the curve. If true,
``where`` is interpreted as a Y coordinate; if false, then
``where`` is interpreted as an X coordinate.
Returns:
A list of two curve segments (each curve segment being three 2D tuples)
if the curve was successfully split, or a list containing the original
curve.
Example::
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 150, False))
((0, 0), (50, 100), (100, 0))
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, False))
((0, 0), (25, 50), (50, 50))
((50, 50), (75, 50), (100, 0))
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, False))
((0, 0), (12.5, 25), (25, 37.5))
((25, 37.5), (62.5, 75), (100, 0))
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, True))
((0, 0), (7.32233, 14.6447), (14.6447, 25))
((14.6447, 25), (50, 75), (85.3553, 25))
((85.3553, 25), (92.6777, 14.6447), (100, -7.10543e-15))
>>> # XXX I'm not at all sure if the following behavior is desirable:
>>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, True))
((0, 0), (25, 50), (50, 50))
((50, 50), (50, 50), (50, 50))
((50, 50), (75, 50), (100, 0))
|
splitQuadratic
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def splitCubic(pt1, pt2, pt3, pt4, where, isHorizontal):
"""Split a cubic Bezier curve at a given coordinate.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
where: Position at which to split the curve.
isHorizontal: Direction of the ray splitting the curve. If true,
``where`` is interpreted as a Y coordinate; if false, then
``where`` is interpreted as an X coordinate.
Returns:
A list of two curve segments (each curve segment being four 2D tuples)
if the curve was successfully split, or a list containing the original
curve.
Example::
>>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 150, False))
((0, 0), (25, 100), (75, 100), (100, 0))
>>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 50, False))
((0, 0), (12.5, 50), (31.25, 75), (50, 75))
((50, 75), (68.75, 75), (87.5, 50), (100, 0))
>>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 25, True))
((0, 0), (2.29379, 9.17517), (4.79804, 17.5085), (7.47414, 25))
((7.47414, 25), (31.2886, 91.6667), (68.7114, 91.6667), (92.5259, 25))
((92.5259, 25), (95.202, 17.5085), (97.7062, 9.17517), (100, 1.77636e-15))
"""
a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4)
solutions = solveCubic(
a[isHorizontal], b[isHorizontal], c[isHorizontal], d[isHorizontal] - where
)
solutions = sorted(t for t in solutions if 0 <= t < 1)
if not solutions:
return [(pt1, pt2, pt3, pt4)]
return _splitCubicAtT(a, b, c, d, *solutions)
|
Split a cubic Bezier curve at a given coordinate.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
where: Position at which to split the curve.
isHorizontal: Direction of the ray splitting the curve. If true,
``where`` is interpreted as a Y coordinate; if false, then
``where`` is interpreted as an X coordinate.
Returns:
A list of two curve segments (each curve segment being four 2D tuples)
if the curve was successfully split, or a list containing the original
curve.
Example::
>>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 150, False))
((0, 0), (25, 100), (75, 100), (100, 0))
>>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 50, False))
((0, 0), (12.5, 50), (31.25, 75), (50, 75))
((50, 75), (68.75, 75), (87.5, 50), (100, 0))
>>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 25, True))
((0, 0), (2.29379, 9.17517), (4.79804, 17.5085), (7.47414, 25))
((7.47414, 25), (31.2886, 91.6667), (68.7114, 91.6667), (92.5259, 25))
((92.5259, 25), (95.202, 17.5085), (97.7062, 9.17517), (100, 1.77636e-15))
|
splitCubic
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def splitQuadraticAtT(pt1, pt2, pt3, *ts):
"""Split a quadratic Bezier curve at one or more values of t.
Args:
pt1,pt2,pt3: Control points of the Bezier as 2D tuples.
*ts: Positions at which to split the curve.
Returns:
A list of curve segments (each curve segment being three 2D tuples).
Examples::
>>> printSegments(splitQuadraticAtT((0, 0), (50, 100), (100, 0), 0.5))
((0, 0), (25, 50), (50, 50))
((50, 50), (75, 50), (100, 0))
>>> printSegments(splitQuadraticAtT((0, 0), (50, 100), (100, 0), 0.5, 0.75))
((0, 0), (25, 50), (50, 50))
((50, 50), (62.5, 50), (75, 37.5))
((75, 37.5), (87.5, 25), (100, 0))
"""
a, b, c = calcQuadraticParameters(pt1, pt2, pt3)
return _splitQuadraticAtT(a, b, c, *ts)
|
Split a quadratic Bezier curve at one or more values of t.
Args:
pt1,pt2,pt3: Control points of the Bezier as 2D tuples.
*ts: Positions at which to split the curve.
Returns:
A list of curve segments (each curve segment being three 2D tuples).
Examples::
>>> printSegments(splitQuadraticAtT((0, 0), (50, 100), (100, 0), 0.5))
((0, 0), (25, 50), (50, 50))
((50, 50), (75, 50), (100, 0))
>>> printSegments(splitQuadraticAtT((0, 0), (50, 100), (100, 0), 0.5, 0.75))
((0, 0), (25, 50), (50, 50))
((50, 50), (62.5, 50), (75, 37.5))
((75, 37.5), (87.5, 25), (100, 0))
|
splitQuadraticAtT
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def splitCubicAtT(pt1, pt2, pt3, pt4, *ts):
"""Split a cubic Bezier curve at one or more values of t.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
*ts: Positions at which to split the curve.
Returns:
A list of curve segments (each curve segment being four 2D tuples).
Examples::
>>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5))
((0, 0), (12.5, 50), (31.25, 75), (50, 75))
((50, 75), (68.75, 75), (87.5, 50), (100, 0))
>>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5, 0.75))
((0, 0), (12.5, 50), (31.25, 75), (50, 75))
((50, 75), (59.375, 75), (68.75, 68.75), (77.3438, 56.25))
((77.3438, 56.25), (85.9375, 43.75), (93.75, 25), (100, 0))
"""
a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4)
split = _splitCubicAtT(a, b, c, d, *ts)
# the split impl can introduce floating point errors; we know the first
# segment should always start at pt1 and the last segment should end at pt4,
# so we set those values directly before returning.
split[0] = (pt1, *split[0][1:])
split[-1] = (*split[-1][:-1], pt4)
return split
|
Split a cubic Bezier curve at one or more values of t.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
*ts: Positions at which to split the curve.
Returns:
A list of curve segments (each curve segment being four 2D tuples).
Examples::
>>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5))
((0, 0), (12.5, 50), (31.25, 75), (50, 75))
((50, 75), (68.75, 75), (87.5, 50), (100, 0))
>>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5, 0.75))
((0, 0), (12.5, 50), (31.25, 75), (50, 75))
((50, 75), (59.375, 75), (68.75, 68.75), (77.3438, 56.25))
((77.3438, 56.25), (85.9375, 43.75), (93.75, 25), (100, 0))
|
splitCubicAtT
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def splitCubicAtTC(pt1, pt2, pt3, pt4, *ts):
"""Split a cubic Bezier curve at one or more values of t.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers..
*ts: Positions at which to split the curve.
Yields:
Curve segments (each curve segment being four complex numbers).
"""
a, b, c, d = calcCubicParametersC(pt1, pt2, pt3, pt4)
yield from _splitCubicAtTC(a, b, c, d, *ts)
|
Split a cubic Bezier curve at one or more values of t.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers..
*ts: Positions at which to split the curve.
Yields:
Curve segments (each curve segment being four complex numbers).
|
splitCubicAtTC
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def splitCubicIntoTwoAtTC(pt1, pt2, pt3, pt4, t):
"""Split a cubic Bezier curve at t.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.
t: Position at which to split the curve.
Returns:
A tuple of two curve segments (each curve segment being four complex numbers).
"""
t2 = t * t
_1_t = 1 - t
_1_t_2 = _1_t * _1_t
_2_t_1_t = 2 * t * _1_t
pointAtT = (
_1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4
)
off1 = _1_t_2 * pt1 + _2_t_1_t * pt2 + t2 * pt3
off2 = _1_t_2 * pt2 + _2_t_1_t * pt3 + t2 * pt4
pt2 = pt1 + (pt2 - pt1) * t
pt3 = pt4 + (pt3 - pt4) * _1_t
return ((pt1, pt2, off1, pointAtT), (pointAtT, off2, pt3, pt4))
|
Split a cubic Bezier curve at t.
Args:
pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.
t: Position at which to split the curve.
Returns:
A tuple of two curve segments (each curve segment being four complex numbers).
|
splitCubicIntoTwoAtTC
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def quadraticPointAtT(pt1, pt2, pt3, t):
"""Finds the point at time `t` on a quadratic curve.
Args:
pt1, pt2, pt3: Coordinates of the curve as 2D tuples.
t: The time along the curve.
Returns:
A 2D tuple with the coordinates of the point.
"""
x = (1 - t) * (1 - t) * pt1[0] + 2 * (1 - t) * t * pt2[0] + t * t * pt3[0]
y = (1 - t) * (1 - t) * pt1[1] + 2 * (1 - t) * t * pt2[1] + t * t * pt3[1]
return (x, y)
|
Finds the point at time `t` on a quadratic curve.
Args:
pt1, pt2, pt3: Coordinates of the curve as 2D tuples.
t: The time along the curve.
Returns:
A 2D tuple with the coordinates of the point.
|
quadraticPointAtT
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def cubicPointAtT(pt1, pt2, pt3, pt4, t):
"""Finds the point at time `t` on a cubic curve.
Args:
pt1, pt2, pt3, pt4: Coordinates of the curve as 2D tuples.
t: The time along the curve.
Returns:
A 2D tuple with the coordinates of the point.
"""
t2 = t * t
_1_t = 1 - t
_1_t_2 = _1_t * _1_t
x = (
_1_t_2 * _1_t * pt1[0]
+ 3 * (_1_t_2 * t * pt2[0] + _1_t * t2 * pt3[0])
+ t2 * t * pt4[0]
)
y = (
_1_t_2 * _1_t * pt1[1]
+ 3 * (_1_t_2 * t * pt2[1] + _1_t * t2 * pt3[1])
+ t2 * t * pt4[1]
)
return (x, y)
|
Finds the point at time `t` on a cubic curve.
Args:
pt1, pt2, pt3, pt4: Coordinates of the curve as 2D tuples.
t: The time along the curve.
Returns:
A 2D tuple with the coordinates of the point.
|
cubicPointAtT
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def cubicPointAtTC(pt1, pt2, pt3, pt4, t):
"""Finds the point at time `t` on a cubic curve.
Args:
pt1, pt2, pt3, pt4: Coordinates of the curve as complex numbers.
t: The time along the curve.
Returns:
A complex number with the coordinates of the point.
"""
t2 = t * t
_1_t = 1 - t
_1_t_2 = _1_t * _1_t
return _1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4
|
Finds the point at time `t` on a cubic curve.
Args:
pt1, pt2, pt3, pt4: Coordinates of the curve as complex numbers.
t: The time along the curve.
Returns:
A complex number with the coordinates of the point.
|
cubicPointAtTC
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
def lineLineIntersections(s1, e1, s2, e2):
"""Finds intersections between two line segments.
Args:
s1, e1: Coordinates of the first line as 2D tuples.
s2, e2: Coordinates of the second line as 2D tuples.
Returns:
A list of ``Intersection`` objects, each object having ``pt``, ``t1``
and ``t2`` attributes containing the intersection point, time on first
segment and time on second segment respectively.
Examples::
>>> a = lineLineIntersections( (310,389), (453, 222), (289, 251), (447, 367))
>>> len(a)
1
>>> intersection = a[0]
>>> intersection.pt
(374.44882952482897, 313.73458370177315)
>>> (intersection.t1, intersection.t2)
(0.45069111555824465, 0.5408153767394238)
"""
s1x, s1y = s1
e1x, e1y = e1
s2x, s2y = s2
e2x, e2y = e2
if (
math.isclose(s2x, e2x) and math.isclose(s1x, e1x) and not math.isclose(s1x, s2x)
): # Parallel vertical
return []
if (
math.isclose(s2y, e2y) and math.isclose(s1y, e1y) and not math.isclose(s1y, s2y)
): # Parallel horizontal
return []
if math.isclose(s2x, e2x) and math.isclose(s2y, e2y): # Line segment is tiny
return []
if math.isclose(s1x, e1x) and math.isclose(s1y, e1y): # Line segment is tiny
return []
if math.isclose(e1x, s1x):
x = s1x
slope34 = (e2y - s2y) / (e2x - s2x)
y = slope34 * (x - s2x) + s2y
pt = (x, y)
return [
Intersection(
pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt)
)
]
if math.isclose(s2x, e2x):
x = s2x
slope12 = (e1y - s1y) / (e1x - s1x)
y = slope12 * (x - s1x) + s1y
pt = (x, y)
return [
Intersection(
pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt)
)
]
slope12 = (e1y - s1y) / (e1x - s1x)
slope34 = (e2y - s2y) / (e2x - s2x)
if math.isclose(slope12, slope34):
return []
x = (slope12 * s1x - s1y - slope34 * s2x + s2y) / (slope12 - slope34)
y = slope12 * (x - s1x) + s1y
pt = (x, y)
if _both_points_are_on_same_side_of_origin(
pt, e1, s1
) and _both_points_are_on_same_side_of_origin(pt, s2, e2):
return [
Intersection(
pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt)
)
]
return []
|
Finds intersections between two line segments.
Args:
s1, e1: Coordinates of the first line as 2D tuples.
s2, e2: Coordinates of the second line as 2D tuples.
Returns:
A list of ``Intersection`` objects, each object having ``pt``, ``t1``
and ``t2`` attributes containing the intersection point, time on first
segment and time on second segment respectively.
Examples::
>>> a = lineLineIntersections( (310,389), (453, 222), (289, 251), (447, 367))
>>> len(a)
1
>>> intersection = a[0]
>>> intersection.pt
(374.44882952482897, 313.73458370177315)
>>> (intersection.t1, intersection.t2)
(0.45069111555824465, 0.5408153767394238)
|
lineLineIntersections
|
python
|
fonttools/fonttools
|
Lib/fontTools/misc/bezierTools.py
|
https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/misc/bezierTools.py
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.