Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- evalkit_tf437/lib/python3.10/site-packages/fontTools/__pycache__/__main__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/__pycache__/afmLib.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/__pycache__/fontBuilder.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/__pycache__/help.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/__pycache__/ttx.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/__pycache__/unicode.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/cu2qu/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/designspaceLib/statNames.py +253 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/designspaceLib/types.py +147 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/feaLib/location.py +12 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/feaLib/lookupDebugInfo.py +12 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/merge/__main__.py +6 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/merge/__pycache__/options.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/merge/__pycache__/util.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/merge/layout.py +526 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/merge/options.py +85 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/arrayTools.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/cliTools.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/eexec.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/filenames.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/iterTools.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/loggingTools.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/macRes.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/psLib.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/psOperators.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/roundTools.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/textTools.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/timeTools.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/transform.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/treeTools.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/vector.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/visitor.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/arrayTools.py +424 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/cliTools.py +53 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/cython.py +27 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/dictTools.py +83 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/fixedTools.py +253 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/iterTools.py +12 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/loggingTools.py +543 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/macRes.py +261 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/plistlib/py.typed +0 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/psCharStrings.py +1496 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/psLib.py +398 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/py23.py +96 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/roundTools.py +110 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/symfont.py +247 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/textTools.py +154 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/timeTools.py +88 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/treeTools.py +45 -0
- evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/vector.py +147 -0
evalkit_tf437/lib/python3.10/site-packages/fontTools/__pycache__/__main__.cpython-310.pyc
ADDED
|
Binary file (641 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/__pycache__/afmLib.cpython-310.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/__pycache__/fontBuilder.cpython-310.pyc
ADDED
|
Binary file (26.4 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/__pycache__/help.cpython-310.pyc
ADDED
|
Binary file (1.24 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/__pycache__/ttx.cpython-310.pyc
ADDED
|
Binary file (12.9 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/__pycache__/unicode.cpython-310.pyc
ADDED
|
Binary file (1.67 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/cu2qu/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (196 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compute name information for a given location in user-space coordinates
|
| 2 |
+
using STAT data. This can be used to fill-in automatically the names of an
|
| 3 |
+
instance:
|
| 4 |
+
|
| 5 |
+
.. code:: python
|
| 6 |
+
|
| 7 |
+
instance = doc.instances[0]
|
| 8 |
+
names = getStatNames(doc, instance.getFullUserLocation(doc))
|
| 9 |
+
print(names.styleNames)
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
from typing import Dict, Optional, Tuple, Union
|
| 16 |
+
import logging
|
| 17 |
+
|
| 18 |
+
from fontTools.designspaceLib import (
|
| 19 |
+
AxisDescriptor,
|
| 20 |
+
AxisLabelDescriptor,
|
| 21 |
+
DesignSpaceDocument,
|
| 22 |
+
DesignSpaceDocumentError,
|
| 23 |
+
DiscreteAxisDescriptor,
|
| 24 |
+
SimpleLocationDict,
|
| 25 |
+
SourceDescriptor,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
LOGGER = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
# TODO(Python 3.8): use Literal
|
| 31 |
+
# RibbiStyleName = Union[Literal["regular"], Literal["bold"], Literal["italic"], Literal["bold italic"]]
|
| 32 |
+
RibbiStyle = str
|
| 33 |
+
BOLD_ITALIC_TO_RIBBI_STYLE = {
|
| 34 |
+
(False, False): "regular",
|
| 35 |
+
(False, True): "italic",
|
| 36 |
+
(True, False): "bold",
|
| 37 |
+
(True, True): "bold italic",
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass
|
| 42 |
+
class StatNames:
|
| 43 |
+
"""Name data generated from the STAT table information."""
|
| 44 |
+
|
| 45 |
+
familyNames: Dict[str, str]
|
| 46 |
+
styleNames: Dict[str, str]
|
| 47 |
+
postScriptFontName: Optional[str]
|
| 48 |
+
styleMapFamilyNames: Dict[str, str]
|
| 49 |
+
styleMapStyleName: Optional[RibbiStyle]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def getStatNames(
|
| 53 |
+
doc: DesignSpaceDocument, userLocation: SimpleLocationDict
|
| 54 |
+
) -> StatNames:
|
| 55 |
+
"""Compute the family, style, PostScript names of the given ``userLocation``
|
| 56 |
+
using the document's STAT information.
|
| 57 |
+
|
| 58 |
+
Also computes localizations.
|
| 59 |
+
|
| 60 |
+
If not enough STAT data is available for a given name, either its dict of
|
| 61 |
+
localized names will be empty (family and style names), or the name will be
|
| 62 |
+
None (PostScript name).
|
| 63 |
+
|
| 64 |
+
.. versionadded:: 5.0
|
| 65 |
+
"""
|
| 66 |
+
familyNames: Dict[str, str] = {}
|
| 67 |
+
defaultSource: Optional[SourceDescriptor] = doc.findDefault()
|
| 68 |
+
if defaultSource is None:
|
| 69 |
+
LOGGER.warning("Cannot determine default source to look up family name.")
|
| 70 |
+
elif defaultSource.familyName is None:
|
| 71 |
+
LOGGER.warning(
|
| 72 |
+
"Cannot look up family name, assign the 'familyname' attribute to the default source."
|
| 73 |
+
)
|
| 74 |
+
else:
|
| 75 |
+
familyNames = {
|
| 76 |
+
"en": defaultSource.familyName,
|
| 77 |
+
**defaultSource.localisedFamilyName,
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
styleNames: Dict[str, str] = {}
|
| 81 |
+
# If a free-standing label matches the location, use it for name generation.
|
| 82 |
+
label = doc.labelForUserLocation(userLocation)
|
| 83 |
+
if label is not None:
|
| 84 |
+
styleNames = {"en": label.name, **label.labelNames}
|
| 85 |
+
# Otherwise, scour the axis labels for matches.
|
| 86 |
+
else:
|
| 87 |
+
# Gather all languages in which at least one translation is provided
|
| 88 |
+
# Then build names for all these languages, but fallback to English
|
| 89 |
+
# whenever a translation is missing.
|
| 90 |
+
labels = _getAxisLabelsForUserLocation(doc.axes, userLocation)
|
| 91 |
+
if labels:
|
| 92 |
+
languages = set(
|
| 93 |
+
language for label in labels for language in label.labelNames
|
| 94 |
+
)
|
| 95 |
+
languages.add("en")
|
| 96 |
+
for language in languages:
|
| 97 |
+
styleName = " ".join(
|
| 98 |
+
label.labelNames.get(language, label.defaultName)
|
| 99 |
+
for label in labels
|
| 100 |
+
if not label.elidable
|
| 101 |
+
)
|
| 102 |
+
if not styleName and doc.elidedFallbackName is not None:
|
| 103 |
+
styleName = doc.elidedFallbackName
|
| 104 |
+
styleNames[language] = styleName
|
| 105 |
+
|
| 106 |
+
if "en" not in familyNames or "en" not in styleNames:
|
| 107 |
+
# Not enough information to compute PS names of styleMap names
|
| 108 |
+
return StatNames(
|
| 109 |
+
familyNames=familyNames,
|
| 110 |
+
styleNames=styleNames,
|
| 111 |
+
postScriptFontName=None,
|
| 112 |
+
styleMapFamilyNames={},
|
| 113 |
+
styleMapStyleName=None,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
postScriptFontName = f"{familyNames['en']}-{styleNames['en']}".replace(" ", "")
|
| 117 |
+
|
| 118 |
+
styleMapStyleName, regularUserLocation = _getRibbiStyle(doc, userLocation)
|
| 119 |
+
|
| 120 |
+
styleNamesForStyleMap = styleNames
|
| 121 |
+
if regularUserLocation != userLocation:
|
| 122 |
+
regularStatNames = getStatNames(doc, regularUserLocation)
|
| 123 |
+
styleNamesForStyleMap = regularStatNames.styleNames
|
| 124 |
+
|
| 125 |
+
styleMapFamilyNames = {}
|
| 126 |
+
for language in set(familyNames).union(styleNames.keys()):
|
| 127 |
+
familyName = familyNames.get(language, familyNames["en"])
|
| 128 |
+
styleName = styleNamesForStyleMap.get(language, styleNamesForStyleMap["en"])
|
| 129 |
+
styleMapFamilyNames[language] = (familyName + " " + styleName).strip()
|
| 130 |
+
|
| 131 |
+
return StatNames(
|
| 132 |
+
familyNames=familyNames,
|
| 133 |
+
styleNames=styleNames,
|
| 134 |
+
postScriptFontName=postScriptFontName,
|
| 135 |
+
styleMapFamilyNames=styleMapFamilyNames,
|
| 136 |
+
styleMapStyleName=styleMapStyleName,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _getSortedAxisLabels(
|
| 141 |
+
axes: list[Union[AxisDescriptor, DiscreteAxisDescriptor]],
|
| 142 |
+
) -> Dict[str, list[AxisLabelDescriptor]]:
|
| 143 |
+
"""Returns axis labels sorted by their ordering, with unordered ones appended as
|
| 144 |
+
they are listed."""
|
| 145 |
+
|
| 146 |
+
# First, get the axis labels with explicit ordering...
|
| 147 |
+
sortedAxes = sorted(
|
| 148 |
+
(axis for axis in axes if axis.axisOrdering is not None),
|
| 149 |
+
key=lambda a: a.axisOrdering,
|
| 150 |
+
)
|
| 151 |
+
sortedLabels: Dict[str, list[AxisLabelDescriptor]] = {
|
| 152 |
+
axis.name: axis.axisLabels for axis in sortedAxes
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
# ... then append the others in the order they appear.
|
| 156 |
+
# NOTE: This relies on Python 3.7+ dict's preserved insertion order.
|
| 157 |
+
for axis in axes:
|
| 158 |
+
if axis.axisOrdering is None:
|
| 159 |
+
sortedLabels[axis.name] = axis.axisLabels
|
| 160 |
+
|
| 161 |
+
return sortedLabels
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _getAxisLabelsForUserLocation(
|
| 165 |
+
axes: list[Union[AxisDescriptor, DiscreteAxisDescriptor]],
|
| 166 |
+
userLocation: SimpleLocationDict,
|
| 167 |
+
) -> list[AxisLabelDescriptor]:
|
| 168 |
+
labels: list[AxisLabelDescriptor] = []
|
| 169 |
+
|
| 170 |
+
allAxisLabels = _getSortedAxisLabels(axes)
|
| 171 |
+
if allAxisLabels.keys() != userLocation.keys():
|
| 172 |
+
LOGGER.warning(
|
| 173 |
+
f"Mismatch between user location '{userLocation.keys()}' and available "
|
| 174 |
+
f"labels for '{allAxisLabels.keys()}'."
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
for axisName, axisLabels in allAxisLabels.items():
|
| 178 |
+
userValue = userLocation[axisName]
|
| 179 |
+
label: Optional[AxisLabelDescriptor] = next(
|
| 180 |
+
(
|
| 181 |
+
l
|
| 182 |
+
for l in axisLabels
|
| 183 |
+
if l.userValue == userValue
|
| 184 |
+
or (
|
| 185 |
+
l.userMinimum is not None
|
| 186 |
+
and l.userMaximum is not None
|
| 187 |
+
and l.userMinimum <= userValue <= l.userMaximum
|
| 188 |
+
)
|
| 189 |
+
),
|
| 190 |
+
None,
|
| 191 |
+
)
|
| 192 |
+
if label is None:
|
| 193 |
+
LOGGER.debug(
|
| 194 |
+
f"Document needs a label for axis '{axisName}', user value '{userValue}'."
|
| 195 |
+
)
|
| 196 |
+
else:
|
| 197 |
+
labels.append(label)
|
| 198 |
+
|
| 199 |
+
return labels
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _getRibbiStyle(
|
| 203 |
+
self: DesignSpaceDocument, userLocation: SimpleLocationDict
|
| 204 |
+
) -> Tuple[RibbiStyle, SimpleLocationDict]:
|
| 205 |
+
"""Compute the RIBBI style name of the given user location,
|
| 206 |
+
return the location of the matching Regular in the RIBBI group.
|
| 207 |
+
|
| 208 |
+
.. versionadded:: 5.0
|
| 209 |
+
"""
|
| 210 |
+
regularUserLocation = {}
|
| 211 |
+
axes_by_tag = {axis.tag: axis for axis in self.axes}
|
| 212 |
+
|
| 213 |
+
bold: bool = False
|
| 214 |
+
italic: bool = False
|
| 215 |
+
|
| 216 |
+
axis = axes_by_tag.get("wght")
|
| 217 |
+
if axis is not None:
|
| 218 |
+
for regular_label in axis.axisLabels:
|
| 219 |
+
if (
|
| 220 |
+
regular_label.linkedUserValue == userLocation[axis.name]
|
| 221 |
+
# In the "recursive" case where both the Regular has
|
| 222 |
+
# linkedUserValue pointing the Bold, and the Bold has
|
| 223 |
+
# linkedUserValue pointing to the Regular, only consider the
|
| 224 |
+
# first case: Regular (e.g. 400) has linkedUserValue pointing to
|
| 225 |
+
# Bold (e.g. 700, higher than Regular)
|
| 226 |
+
and regular_label.userValue < regular_label.linkedUserValue
|
| 227 |
+
):
|
| 228 |
+
regularUserLocation[axis.name] = regular_label.userValue
|
| 229 |
+
bold = True
|
| 230 |
+
break
|
| 231 |
+
|
| 232 |
+
axis = axes_by_tag.get("ital") or axes_by_tag.get("slnt")
|
| 233 |
+
if axis is not None:
|
| 234 |
+
for upright_label in axis.axisLabels:
|
| 235 |
+
if (
|
| 236 |
+
upright_label.linkedUserValue == userLocation[axis.name]
|
| 237 |
+
# In the "recursive" case where both the Upright has
|
| 238 |
+
# linkedUserValue pointing the Italic, and the Italic has
|
| 239 |
+
# linkedUserValue pointing to the Upright, only consider the
|
| 240 |
+
# first case: Upright (e.g. ital=0, slant=0) has
|
| 241 |
+
# linkedUserValue pointing to Italic (e.g ital=1, slant=-12 or
|
| 242 |
+
# slant=12 for backwards italics, in any case higher than
|
| 243 |
+
# Upright in absolute value, hence the abs() below.
|
| 244 |
+
and abs(upright_label.userValue) < abs(upright_label.linkedUserValue)
|
| 245 |
+
):
|
| 246 |
+
regularUserLocation[axis.name] = upright_label.userValue
|
| 247 |
+
italic = True
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Dict, List, Optional, Union, cast
|
| 5 |
+
|
| 6 |
+
from fontTools.designspaceLib import (
|
| 7 |
+
AxisDescriptor,
|
| 8 |
+
DesignSpaceDocument,
|
| 9 |
+
DesignSpaceDocumentError,
|
| 10 |
+
RangeAxisSubsetDescriptor,
|
| 11 |
+
SimpleLocationDict,
|
| 12 |
+
ValueAxisSubsetDescriptor,
|
| 13 |
+
VariableFontDescriptor,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def clamp(value, minimum, maximum):
|
| 18 |
+
return min(max(value, minimum), maximum)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class Range:
|
| 23 |
+
minimum: float
|
| 24 |
+
"""Inclusive minimum of the range."""
|
| 25 |
+
maximum: float
|
| 26 |
+
"""Inclusive maximum of the range."""
|
| 27 |
+
default: float = 0
|
| 28 |
+
"""Default value"""
|
| 29 |
+
|
| 30 |
+
def __post_init__(self):
|
| 31 |
+
self.minimum, self.maximum = sorted((self.minimum, self.maximum))
|
| 32 |
+
self.default = clamp(self.default, self.minimum, self.maximum)
|
| 33 |
+
|
| 34 |
+
def __contains__(self, value: Union[float, Range]) -> bool:
|
| 35 |
+
if isinstance(value, Range):
|
| 36 |
+
return self.minimum <= value.minimum and value.maximum <= self.maximum
|
| 37 |
+
return self.minimum <= value <= self.maximum
|
| 38 |
+
|
| 39 |
+
def intersection(self, other: Range) -> Optional[Range]:
|
| 40 |
+
if self.maximum < other.minimum or self.minimum > other.maximum:
|
| 41 |
+
return None
|
| 42 |
+
else:
|
| 43 |
+
return Range(
|
| 44 |
+
max(self.minimum, other.minimum),
|
| 45 |
+
min(self.maximum, other.maximum),
|
| 46 |
+
self.default, # We don't care about the default in this use-case
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# A region selection is either a range or a single value, as a Designspace v5
|
| 51 |
+
# axis-subset element only allows a single discrete value or a range for a
|
| 52 |
+
# variable-font element.
|
| 53 |
+
Region = Dict[str, Union[Range, float]]
|
| 54 |
+
|
| 55 |
+
# A conditionset is a set of named ranges.
|
| 56 |
+
ConditionSet = Dict[str, Range]
|
| 57 |
+
|
| 58 |
+
# A rule is a list of conditionsets where any has to be relevant for the whole rule to be relevant.
|
| 59 |
+
Rule = List[ConditionSet]
|
| 60 |
+
Rules = Dict[str, Rule]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def locationInRegion(location: SimpleLocationDict, region: Region) -> bool:
|
| 64 |
+
for name, value in location.items():
|
| 65 |
+
if name not in region:
|
| 66 |
+
return False
|
| 67 |
+
regionValue = region[name]
|
| 68 |
+
if isinstance(regionValue, (float, int)):
|
| 69 |
+
if value != regionValue:
|
| 70 |
+
return False
|
| 71 |
+
else:
|
| 72 |
+
if value not in regionValue:
|
| 73 |
+
return False
|
| 74 |
+
return True
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def regionInRegion(region: Region, superRegion: Region) -> bool:
|
| 78 |
+
for name, value in region.items():
|
| 79 |
+
if not name in superRegion:
|
| 80 |
+
return False
|
| 81 |
+
superValue = superRegion[name]
|
| 82 |
+
if isinstance(superValue, (float, int)):
|
| 83 |
+
if value != superValue:
|
| 84 |
+
return False
|
| 85 |
+
else:
|
| 86 |
+
if value not in superValue:
|
| 87 |
+
return False
|
| 88 |
+
return True
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def userRegionToDesignRegion(doc: DesignSpaceDocument, userRegion: Region) -> Region:
|
| 92 |
+
designRegion = {}
|
| 93 |
+
for name, value in userRegion.items():
|
| 94 |
+
axis = doc.getAxis(name)
|
| 95 |
+
if axis is None:
|
| 96 |
+
raise DesignSpaceDocumentError(
|
| 97 |
+
f"Cannot find axis named '{name}' for region."
|
| 98 |
+
)
|
| 99 |
+
if isinstance(value, (float, int)):
|
| 100 |
+
designRegion[name] = axis.map_forward(value)
|
| 101 |
+
else:
|
| 102 |
+
designRegion[name] = Range(
|
| 103 |
+
axis.map_forward(value.minimum),
|
| 104 |
+
axis.map_forward(value.maximum),
|
| 105 |
+
axis.map_forward(value.default),
|
| 106 |
+
)
|
| 107 |
+
return designRegion
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def getVFUserRegion(doc: DesignSpaceDocument, vf: VariableFontDescriptor) -> Region:
|
| 111 |
+
vfUserRegion: Region = {}
|
| 112 |
+
# For each axis, 2 cases:
|
| 113 |
+
# - it has a range = it's an axis in the VF DS
|
| 114 |
+
# - it's a single location = use it to know which rules should apply in the VF
|
| 115 |
+
for axisSubset in vf.axisSubsets:
|
| 116 |
+
axis = doc.getAxis(axisSubset.name)
|
| 117 |
+
if axis is None:
|
| 118 |
+
raise DesignSpaceDocumentError(
|
| 119 |
+
f"Cannot find axis named '{axisSubset.name}' for variable font '{vf.name}'."
|
| 120 |
+
)
|
| 121 |
+
if hasattr(axisSubset, "userMinimum"):
|
| 122 |
+
# Mypy doesn't support narrowing union types via hasattr()
|
| 123 |
+
# TODO(Python 3.10): use TypeGuard
|
| 124 |
+
# https://mypy.readthedocs.io/en/stable/type_narrowing.html
|
| 125 |
+
axisSubset = cast(RangeAxisSubsetDescriptor, axisSubset)
|
| 126 |
+
if not hasattr(axis, "minimum"):
|
| 127 |
+
raise DesignSpaceDocumentError(
|
| 128 |
+
f"Cannot select a range over '{axis.name}' for variable font '{vf.name}' "
|
| 129 |
+
"because it's a discrete axis, use only 'userValue' instead."
|
| 130 |
+
)
|
| 131 |
+
axis = cast(AxisDescriptor, axis)
|
| 132 |
+
vfUserRegion[axis.name] = Range(
|
| 133 |
+
max(axisSubset.userMinimum, axis.minimum),
|
| 134 |
+
min(axisSubset.userMaximum, axis.maximum),
|
| 135 |
+
axisSubset.userDefault or axis.default,
|
| 136 |
+
)
|
| 137 |
+
else:
|
| 138 |
+
axisSubset = cast(ValueAxisSubsetDescriptor, axisSubset)
|
| 139 |
+
vfUserRegion[axis.name] = axisSubset.userValue
|
| 140 |
+
# Any axis not mentioned explicitly has a single location = default value
|
| 141 |
+
for axis in doc.axes:
|
| 142 |
+
if axis.name not in vfUserRegion:
|
| 143 |
+
assert isinstance(
|
| 144 |
+
axis.default, (int, float)
|
| 145 |
+
), f"Axis '{axis.name}' has no valid default value."
|
| 146 |
+
vfUserRegion[axis.name] = axis.default
|
| 147 |
+
return vfUserRegion
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/feaLib/location.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import NamedTuple
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class FeatureLibLocation(NamedTuple):
|
| 5 |
+
"""A location in a feature file"""
|
| 6 |
+
|
| 7 |
+
file: str
|
| 8 |
+
line: int
|
| 9 |
+
column: int
|
| 10 |
+
|
| 11 |
+
def __str__(self):
|
| 12 |
+
return f"{self.file}:{self.line}:{self.column}"
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/feaLib/lookupDebugInfo.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import NamedTuple
|
| 2 |
+
|
| 3 |
+
LOOKUP_DEBUG_INFO_KEY = "com.github.fonttools.feaLib"
|
| 4 |
+
LOOKUP_DEBUG_ENV_VAR = "FONTTOOLS_LOOKUP_DEBUGGING"
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class LookupDebugInfo(NamedTuple):
|
| 8 |
+
"""Information about where a lookup came from, to be embedded in a font"""
|
| 9 |
+
|
| 10 |
+
location: str
|
| 11 |
+
name: str
|
| 12 |
+
feature: list
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/merge/__main__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from fontTools.merge import main
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
if __name__ == "__main__":
|
| 6 |
+
sys.exit(main())
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/merge/__pycache__/options.cpython-310.pyc
ADDED
|
Binary file (2.16 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/merge/__pycache__/util.cpython-310.pyc
ADDED
|
Binary file (5.89 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/merge/layout.py
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2013 Google, Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Google Author(s): Behdad Esfahbod, Roozbeh Pournader
|
| 4 |
+
|
| 5 |
+
from fontTools import ttLib
|
| 6 |
+
from fontTools.ttLib.tables.DefaultTable import DefaultTable
|
| 7 |
+
from fontTools.ttLib.tables import otTables
|
| 8 |
+
from fontTools.merge.base import add_method, mergeObjects
|
| 9 |
+
from fontTools.merge.util import *
|
| 10 |
+
import logging
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
log = logging.getLogger("fontTools.merge")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def mergeLookupLists(lst):
|
| 17 |
+
# TODO Do smarter merge.
|
| 18 |
+
return sumLists(lst)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def mergeFeatures(lst):
|
| 22 |
+
assert lst
|
| 23 |
+
self = otTables.Feature()
|
| 24 |
+
self.FeatureParams = None
|
| 25 |
+
self.LookupListIndex = mergeLookupLists(
|
| 26 |
+
[l.LookupListIndex for l in lst if l.LookupListIndex]
|
| 27 |
+
)
|
| 28 |
+
self.LookupCount = len(self.LookupListIndex)
|
| 29 |
+
return self
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def mergeFeatureLists(lst):
|
| 33 |
+
d = {}
|
| 34 |
+
for l in lst:
|
| 35 |
+
for f in l:
|
| 36 |
+
tag = f.FeatureTag
|
| 37 |
+
if tag not in d:
|
| 38 |
+
d[tag] = []
|
| 39 |
+
d[tag].append(f.Feature)
|
| 40 |
+
ret = []
|
| 41 |
+
for tag in sorted(d.keys()):
|
| 42 |
+
rec = otTables.FeatureRecord()
|
| 43 |
+
rec.FeatureTag = tag
|
| 44 |
+
rec.Feature = mergeFeatures(d[tag])
|
| 45 |
+
ret.append(rec)
|
| 46 |
+
return ret
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def mergeLangSyses(lst):
|
| 50 |
+
assert lst
|
| 51 |
+
|
| 52 |
+
# TODO Support merging ReqFeatureIndex
|
| 53 |
+
assert all(l.ReqFeatureIndex == 0xFFFF for l in lst)
|
| 54 |
+
|
| 55 |
+
self = otTables.LangSys()
|
| 56 |
+
self.LookupOrder = None
|
| 57 |
+
self.ReqFeatureIndex = 0xFFFF
|
| 58 |
+
self.FeatureIndex = mergeFeatureLists(
|
| 59 |
+
[l.FeatureIndex for l in lst if l.FeatureIndex]
|
| 60 |
+
)
|
| 61 |
+
self.FeatureCount = len(self.FeatureIndex)
|
| 62 |
+
return self
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def mergeScripts(lst):
|
| 66 |
+
assert lst
|
| 67 |
+
|
| 68 |
+
if len(lst) == 1:
|
| 69 |
+
return lst[0]
|
| 70 |
+
langSyses = {}
|
| 71 |
+
for sr in lst:
|
| 72 |
+
for lsr in sr.LangSysRecord:
|
| 73 |
+
if lsr.LangSysTag not in langSyses:
|
| 74 |
+
langSyses[lsr.LangSysTag] = []
|
| 75 |
+
langSyses[lsr.LangSysTag].append(lsr.LangSys)
|
| 76 |
+
lsrecords = []
|
| 77 |
+
for tag, langSys_list in sorted(langSyses.items()):
|
| 78 |
+
lsr = otTables.LangSysRecord()
|
| 79 |
+
lsr.LangSys = mergeLangSyses(langSys_list)
|
| 80 |
+
lsr.LangSysTag = tag
|
| 81 |
+
lsrecords.append(lsr)
|
| 82 |
+
|
| 83 |
+
self = otTables.Script()
|
| 84 |
+
self.LangSysRecord = lsrecords
|
| 85 |
+
self.LangSysCount = len(lsrecords)
|
| 86 |
+
dfltLangSyses = [s.DefaultLangSys for s in lst if s.DefaultLangSys]
|
| 87 |
+
if dfltLangSyses:
|
| 88 |
+
self.DefaultLangSys = mergeLangSyses(dfltLangSyses)
|
| 89 |
+
else:
|
| 90 |
+
self.DefaultLangSys = None
|
| 91 |
+
return self
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def mergeScriptRecords(lst):
|
| 95 |
+
d = {}
|
| 96 |
+
for l in lst:
|
| 97 |
+
for s in l:
|
| 98 |
+
tag = s.ScriptTag
|
| 99 |
+
if tag not in d:
|
| 100 |
+
d[tag] = []
|
| 101 |
+
d[tag].append(s.Script)
|
| 102 |
+
ret = []
|
| 103 |
+
for tag in sorted(d.keys()):
|
| 104 |
+
rec = otTables.ScriptRecord()
|
| 105 |
+
rec.ScriptTag = tag
|
| 106 |
+
rec.Script = mergeScripts(d[tag])
|
| 107 |
+
ret.append(rec)
|
| 108 |
+
return ret
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
otTables.ScriptList.mergeMap = {
|
| 112 |
+
"ScriptCount": lambda lst: None, # TODO
|
| 113 |
+
"ScriptRecord": mergeScriptRecords,
|
| 114 |
+
}
|
| 115 |
+
otTables.BaseScriptList.mergeMap = {
|
| 116 |
+
"BaseScriptCount": lambda lst: None, # TODO
|
| 117 |
+
# TODO: Merge duplicate entries
|
| 118 |
+
"BaseScriptRecord": lambda lst: sorted(
|
| 119 |
+
sumLists(lst), key=lambda s: s.BaseScriptTag
|
| 120 |
+
),
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
otTables.FeatureList.mergeMap = {
|
| 124 |
+
"FeatureCount": sum,
|
| 125 |
+
"FeatureRecord": lambda lst: sorted(sumLists(lst), key=lambda s: s.FeatureTag),
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
otTables.LookupList.mergeMap = {
|
| 129 |
+
"LookupCount": sum,
|
| 130 |
+
"Lookup": sumLists,
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
otTables.Coverage.mergeMap = {
|
| 134 |
+
"Format": min,
|
| 135 |
+
"glyphs": sumLists,
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
otTables.ClassDef.mergeMap = {
|
| 139 |
+
"Format": min,
|
| 140 |
+
"classDefs": sumDicts,
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
otTables.LigCaretList.mergeMap = {
|
| 144 |
+
"Coverage": mergeObjects,
|
| 145 |
+
"LigGlyphCount": sum,
|
| 146 |
+
"LigGlyph": sumLists,
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
otTables.AttachList.mergeMap = {
|
| 150 |
+
"Coverage": mergeObjects,
|
| 151 |
+
"GlyphCount": sum,
|
| 152 |
+
"AttachPoint": sumLists,
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
# XXX Renumber MarkFilterSets of lookups
|
| 156 |
+
otTables.MarkGlyphSetsDef.mergeMap = {
|
| 157 |
+
"MarkSetTableFormat": equal,
|
| 158 |
+
"MarkSetCount": sum,
|
| 159 |
+
"Coverage": sumLists,
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
otTables.Axis.mergeMap = {
|
| 163 |
+
"*": mergeObjects,
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
# XXX Fix BASE table merging
|
| 167 |
+
otTables.BaseTagList.mergeMap = {
|
| 168 |
+
"BaseTagCount": sum,
|
| 169 |
+
"BaselineTag": sumLists,
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
otTables.GDEF.mergeMap = otTables.GSUB.mergeMap = otTables.GPOS.mergeMap = (
|
| 173 |
+
otTables.BASE.mergeMap
|
| 174 |
+
) = otTables.JSTF.mergeMap = otTables.MATH.mergeMap = {
|
| 175 |
+
"*": mergeObjects,
|
| 176 |
+
"Version": max,
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
ttLib.getTableClass("GDEF").mergeMap = ttLib.getTableClass("GSUB").mergeMap = (
|
| 180 |
+
ttLib.getTableClass("GPOS").mergeMap
|
| 181 |
+
) = ttLib.getTableClass("BASE").mergeMap = ttLib.getTableClass(
|
| 182 |
+
"JSTF"
|
| 183 |
+
).mergeMap = ttLib.getTableClass(
|
| 184 |
+
"MATH"
|
| 185 |
+
).mergeMap = {
|
| 186 |
+
"tableTag": onlyExisting(equal), # XXX clean me up
|
| 187 |
+
"table": mergeObjects,
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
@add_method(ttLib.getTableClass("GSUB"))
|
| 192 |
+
def merge(self, m, tables):
|
| 193 |
+
assert len(tables) == len(m.duplicateGlyphsPerFont)
|
| 194 |
+
for i, (table, dups) in enumerate(zip(tables, m.duplicateGlyphsPerFont)):
|
| 195 |
+
if not dups:
|
| 196 |
+
continue
|
| 197 |
+
if table is None or table is NotImplemented:
|
| 198 |
+
log.warning(
|
| 199 |
+
"Have non-identical duplicates to resolve for '%s' but no GSUB. Are duplicates intended?: %s",
|
| 200 |
+
m.fonts[i]._merger__name,
|
| 201 |
+
dups,
|
| 202 |
+
)
|
| 203 |
+
continue
|
| 204 |
+
|
| 205 |
+
synthFeature = None
|
| 206 |
+
synthLookup = None
|
| 207 |
+
for script in table.table.ScriptList.ScriptRecord:
|
| 208 |
+
if script.ScriptTag == "DFLT":
|
| 209 |
+
continue # XXX
|
| 210 |
+
for langsys in [script.Script.DefaultLangSys] + [
|
| 211 |
+
l.LangSys for l in script.Script.LangSysRecord
|
| 212 |
+
]:
|
| 213 |
+
if langsys is None:
|
| 214 |
+
continue # XXX Create!
|
| 215 |
+
feature = [v for v in langsys.FeatureIndex if v.FeatureTag == "locl"]
|
| 216 |
+
assert len(feature) <= 1
|
| 217 |
+
if feature:
|
| 218 |
+
feature = feature[0]
|
| 219 |
+
else:
|
| 220 |
+
if not synthFeature:
|
| 221 |
+
synthFeature = otTables.FeatureRecord()
|
| 222 |
+
synthFeature.FeatureTag = "locl"
|
| 223 |
+
f = synthFeature.Feature = otTables.Feature()
|
| 224 |
+
f.FeatureParams = None
|
| 225 |
+
f.LookupCount = 0
|
| 226 |
+
f.LookupListIndex = []
|
| 227 |
+
table.table.FeatureList.FeatureRecord.append(synthFeature)
|
| 228 |
+
table.table.FeatureList.FeatureCount += 1
|
| 229 |
+
feature = synthFeature
|
| 230 |
+
langsys.FeatureIndex.append(feature)
|
| 231 |
+
langsys.FeatureIndex.sort(key=lambda v: v.FeatureTag)
|
| 232 |
+
|
| 233 |
+
if not synthLookup:
|
| 234 |
+
subtable = otTables.SingleSubst()
|
| 235 |
+
subtable.mapping = dups
|
| 236 |
+
synthLookup = otTables.Lookup()
|
| 237 |
+
synthLookup.LookupFlag = 0
|
| 238 |
+
synthLookup.LookupType = 1
|
| 239 |
+
synthLookup.SubTableCount = 1
|
| 240 |
+
synthLookup.SubTable = [subtable]
|
| 241 |
+
if table.table.LookupList is None:
|
| 242 |
+
# mtiLib uses None as default value for LookupList,
|
| 243 |
+
# while feaLib points to an empty array with count 0
|
| 244 |
+
# TODO: make them do the same
|
| 245 |
+
table.table.LookupList = otTables.LookupList()
|
| 246 |
+
table.table.LookupList.Lookup = []
|
| 247 |
+
table.table.LookupList.LookupCount = 0
|
| 248 |
+
table.table.LookupList.Lookup.append(synthLookup)
|
| 249 |
+
table.table.LookupList.LookupCount += 1
|
| 250 |
+
|
| 251 |
+
if feature.Feature.LookupListIndex[:1] != [synthLookup]:
|
| 252 |
+
feature.Feature.LookupListIndex[:0] = [synthLookup]
|
| 253 |
+
feature.Feature.LookupCount += 1
|
| 254 |
+
|
| 255 |
+
DefaultTable.merge(self, m, tables)
|
| 256 |
+
return self
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@add_method(
|
| 260 |
+
otTables.SingleSubst,
|
| 261 |
+
otTables.MultipleSubst,
|
| 262 |
+
otTables.AlternateSubst,
|
| 263 |
+
otTables.LigatureSubst,
|
| 264 |
+
otTables.ReverseChainSingleSubst,
|
| 265 |
+
otTables.SinglePos,
|
| 266 |
+
otTables.PairPos,
|
| 267 |
+
otTables.CursivePos,
|
| 268 |
+
otTables.MarkBasePos,
|
| 269 |
+
otTables.MarkLigPos,
|
| 270 |
+
otTables.MarkMarkPos,
|
| 271 |
+
)
|
| 272 |
+
def mapLookups(self, lookupMap):
|
| 273 |
+
pass
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
# Copied and trimmed down from subset.py
|
| 277 |
+
@add_method(
|
| 278 |
+
otTables.ContextSubst,
|
| 279 |
+
otTables.ChainContextSubst,
|
| 280 |
+
otTables.ContextPos,
|
| 281 |
+
otTables.ChainContextPos,
|
| 282 |
+
)
|
| 283 |
+
def __merge_classify_context(self):
|
| 284 |
+
class ContextHelper(object):
|
| 285 |
+
def __init__(self, klass, Format):
|
| 286 |
+
if klass.__name__.endswith("Subst"):
|
| 287 |
+
Typ = "Sub"
|
| 288 |
+
Type = "Subst"
|
| 289 |
+
else:
|
| 290 |
+
Typ = "Pos"
|
| 291 |
+
Type = "Pos"
|
| 292 |
+
if klass.__name__.startswith("Chain"):
|
| 293 |
+
Chain = "Chain"
|
| 294 |
+
else:
|
| 295 |
+
Chain = ""
|
| 296 |
+
ChainTyp = Chain + Typ
|
| 297 |
+
|
| 298 |
+
self.Typ = Typ
|
| 299 |
+
self.Type = Type
|
| 300 |
+
self.Chain = Chain
|
| 301 |
+
self.ChainTyp = ChainTyp
|
| 302 |
+
|
| 303 |
+
self.LookupRecord = Type + "LookupRecord"
|
| 304 |
+
|
| 305 |
+
if Format == 1:
|
| 306 |
+
self.Rule = ChainTyp + "Rule"
|
| 307 |
+
self.RuleSet = ChainTyp + "RuleSet"
|
| 308 |
+
elif Format == 2:
|
| 309 |
+
self.Rule = ChainTyp + "ClassRule"
|
| 310 |
+
self.RuleSet = ChainTyp + "ClassSet"
|
| 311 |
+
|
| 312 |
+
if self.Format not in [1, 2, 3]:
|
| 313 |
+
return None # Don't shoot the messenger; let it go
|
| 314 |
+
if not hasattr(self.__class__, "_merge__ContextHelpers"):
|
| 315 |
+
self.__class__._merge__ContextHelpers = {}
|
| 316 |
+
if self.Format not in self.__class__._merge__ContextHelpers:
|
| 317 |
+
helper = ContextHelper(self.__class__, self.Format)
|
| 318 |
+
self.__class__._merge__ContextHelpers[self.Format] = helper
|
| 319 |
+
return self.__class__._merge__ContextHelpers[self.Format]
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
@add_method(
|
| 323 |
+
otTables.ContextSubst,
|
| 324 |
+
otTables.ChainContextSubst,
|
| 325 |
+
otTables.ContextPos,
|
| 326 |
+
otTables.ChainContextPos,
|
| 327 |
+
)
|
| 328 |
+
def mapLookups(self, lookupMap):
|
| 329 |
+
c = self.__merge_classify_context()
|
| 330 |
+
|
| 331 |
+
if self.Format in [1, 2]:
|
| 332 |
+
for rs in getattr(self, c.RuleSet):
|
| 333 |
+
if not rs:
|
| 334 |
+
continue
|
| 335 |
+
for r in getattr(rs, c.Rule):
|
| 336 |
+
if not r:
|
| 337 |
+
continue
|
| 338 |
+
for ll in getattr(r, c.LookupRecord):
|
| 339 |
+
if not ll:
|
| 340 |
+
continue
|
| 341 |
+
ll.LookupListIndex = lookupMap[ll.LookupListIndex]
|
| 342 |
+
elif self.Format == 3:
|
| 343 |
+
for ll in getattr(self, c.LookupRecord):
|
| 344 |
+
if not ll:
|
| 345 |
+
continue
|
| 346 |
+
ll.LookupListIndex = lookupMap[ll.LookupListIndex]
|
| 347 |
+
else:
|
| 348 |
+
assert 0, "unknown format: %s" % self.Format
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
@add_method(otTables.ExtensionSubst, otTables.ExtensionPos)
|
| 352 |
+
def mapLookups(self, lookupMap):
|
| 353 |
+
if self.Format == 1:
|
| 354 |
+
self.ExtSubTable.mapLookups(lookupMap)
|
| 355 |
+
else:
|
| 356 |
+
assert 0, "unknown format: %s" % self.Format
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
@add_method(otTables.Lookup)
|
| 360 |
+
def mapLookups(self, lookupMap):
|
| 361 |
+
for st in self.SubTable:
|
| 362 |
+
if not st:
|
| 363 |
+
continue
|
| 364 |
+
st.mapLookups(lookupMap)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
@add_method(otTables.LookupList)
|
| 368 |
+
def mapLookups(self, lookupMap):
|
| 369 |
+
for l in self.Lookup:
|
| 370 |
+
if not l:
|
| 371 |
+
continue
|
| 372 |
+
l.mapLookups(lookupMap)
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
@add_method(otTables.Lookup)
|
| 376 |
+
def mapMarkFilteringSets(self, markFilteringSetMap):
|
| 377 |
+
if self.LookupFlag & 0x0010:
|
| 378 |
+
self.MarkFilteringSet = markFilteringSetMap[self.MarkFilteringSet]
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
@add_method(otTables.LookupList)
|
| 382 |
+
def mapMarkFilteringSets(self, markFilteringSetMap):
|
| 383 |
+
for l in self.Lookup:
|
| 384 |
+
if not l:
|
| 385 |
+
continue
|
| 386 |
+
l.mapMarkFilteringSets(markFilteringSetMap)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
@add_method(otTables.Feature)
|
| 390 |
+
def mapLookups(self, lookupMap):
|
| 391 |
+
self.LookupListIndex = [lookupMap[i] for i in self.LookupListIndex]
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
@add_method(otTables.FeatureList)
|
| 395 |
+
def mapLookups(self, lookupMap):
|
| 396 |
+
for f in self.FeatureRecord:
|
| 397 |
+
if not f or not f.Feature:
|
| 398 |
+
continue
|
| 399 |
+
f.Feature.mapLookups(lookupMap)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
@add_method(otTables.DefaultLangSys, otTables.LangSys)
|
| 403 |
+
def mapFeatures(self, featureMap):
|
| 404 |
+
self.FeatureIndex = [featureMap[i] for i in self.FeatureIndex]
|
| 405 |
+
if self.ReqFeatureIndex != 65535:
|
| 406 |
+
self.ReqFeatureIndex = featureMap[self.ReqFeatureIndex]
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@add_method(otTables.Script)
|
| 410 |
+
def mapFeatures(self, featureMap):
|
| 411 |
+
if self.DefaultLangSys:
|
| 412 |
+
self.DefaultLangSys.mapFeatures(featureMap)
|
| 413 |
+
for l in self.LangSysRecord:
|
| 414 |
+
if not l or not l.LangSys:
|
| 415 |
+
continue
|
| 416 |
+
l.LangSys.mapFeatures(featureMap)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
@add_method(otTables.ScriptList)
|
| 420 |
+
def mapFeatures(self, featureMap):
|
| 421 |
+
for s in self.ScriptRecord:
|
| 422 |
+
if not s or not s.Script:
|
| 423 |
+
continue
|
| 424 |
+
s.Script.mapFeatures(featureMap)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def layoutPreMerge(font):
|
| 428 |
+
# Map indices to references
|
| 429 |
+
|
| 430 |
+
GDEF = font.get("GDEF")
|
| 431 |
+
GSUB = font.get("GSUB")
|
| 432 |
+
GPOS = font.get("GPOS")
|
| 433 |
+
|
| 434 |
+
for t in [GSUB, GPOS]:
|
| 435 |
+
if not t:
|
| 436 |
+
continue
|
| 437 |
+
|
| 438 |
+
if t.table.LookupList:
|
| 439 |
+
lookupMap = {i: v for i, v in enumerate(t.table.LookupList.Lookup)}
|
| 440 |
+
t.table.LookupList.mapLookups(lookupMap)
|
| 441 |
+
t.table.FeatureList.mapLookups(lookupMap)
|
| 442 |
+
|
| 443 |
+
if (
|
| 444 |
+
GDEF
|
| 445 |
+
and GDEF.table.Version >= 0x00010002
|
| 446 |
+
and GDEF.table.MarkGlyphSetsDef
|
| 447 |
+
):
|
| 448 |
+
markFilteringSetMap = {
|
| 449 |
+
i: v for i, v in enumerate(GDEF.table.MarkGlyphSetsDef.Coverage)
|
| 450 |
+
}
|
| 451 |
+
t.table.LookupList.mapMarkFilteringSets(markFilteringSetMap)
|
| 452 |
+
|
| 453 |
+
if t.table.FeatureList and t.table.ScriptList:
|
| 454 |
+
featureMap = {i: v for i, v in enumerate(t.table.FeatureList.FeatureRecord)}
|
| 455 |
+
t.table.ScriptList.mapFeatures(featureMap)
|
| 456 |
+
|
| 457 |
+
# TODO FeatureParams nameIDs
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def layoutPostMerge(font):
|
| 461 |
+
# Map references back to indices
|
| 462 |
+
|
| 463 |
+
GDEF = font.get("GDEF")
|
| 464 |
+
GSUB = font.get("GSUB")
|
| 465 |
+
GPOS = font.get("GPOS")
|
| 466 |
+
|
| 467 |
+
for t in [GSUB, GPOS]:
|
| 468 |
+
if not t:
|
| 469 |
+
continue
|
| 470 |
+
|
| 471 |
+
if t.table.FeatureList and t.table.ScriptList:
|
| 472 |
+
# Collect unregistered (new) features.
|
| 473 |
+
featureMap = GregariousIdentityDict(t.table.FeatureList.FeatureRecord)
|
| 474 |
+
t.table.ScriptList.mapFeatures(featureMap)
|
| 475 |
+
|
| 476 |
+
# Record used features.
|
| 477 |
+
featureMap = AttendanceRecordingIdentityDict(
|
| 478 |
+
t.table.FeatureList.FeatureRecord
|
| 479 |
+
)
|
| 480 |
+
t.table.ScriptList.mapFeatures(featureMap)
|
| 481 |
+
usedIndices = featureMap.s
|
| 482 |
+
|
| 483 |
+
# Remove unused features
|
| 484 |
+
t.table.FeatureList.FeatureRecord = [
|
| 485 |
+
f
|
| 486 |
+
for i, f in enumerate(t.table.FeatureList.FeatureRecord)
|
| 487 |
+
if i in usedIndices
|
| 488 |
+
]
|
| 489 |
+
|
| 490 |
+
# Map back to indices.
|
| 491 |
+
featureMap = NonhashableDict(t.table.FeatureList.FeatureRecord)
|
| 492 |
+
t.table.ScriptList.mapFeatures(featureMap)
|
| 493 |
+
|
| 494 |
+
t.table.FeatureList.FeatureCount = len(t.table.FeatureList.FeatureRecord)
|
| 495 |
+
|
| 496 |
+
if t.table.LookupList:
|
| 497 |
+
# Collect unregistered (new) lookups.
|
| 498 |
+
lookupMap = GregariousIdentityDict(t.table.LookupList.Lookup)
|
| 499 |
+
t.table.FeatureList.mapLookups(lookupMap)
|
| 500 |
+
t.table.LookupList.mapLookups(lookupMap)
|
| 501 |
+
|
| 502 |
+
# Record used lookups.
|
| 503 |
+
lookupMap = AttendanceRecordingIdentityDict(t.table.LookupList.Lookup)
|
| 504 |
+
t.table.FeatureList.mapLookups(lookupMap)
|
| 505 |
+
t.table.LookupList.mapLookups(lookupMap)
|
| 506 |
+
usedIndices = lookupMap.s
|
| 507 |
+
|
| 508 |
+
# Remove unused lookups
|
| 509 |
+
t.table.LookupList.Lookup = [
|
| 510 |
+
l for i, l in enumerate(t.table.LookupList.Lookup) if i in usedIndices
|
| 511 |
+
]
|
| 512 |
+
|
| 513 |
+
# Map back to indices.
|
| 514 |
+
lookupMap = NonhashableDict(t.table.LookupList.Lookup)
|
| 515 |
+
t.table.FeatureList.mapLookups(lookupMap)
|
| 516 |
+
t.table.LookupList.mapLookups(lookupMap)
|
| 517 |
+
|
| 518 |
+
t.table.LookupList.LookupCount = len(t.table.LookupList.Lookup)
|
| 519 |
+
|
| 520 |
+
if GDEF and GDEF.table.Version >= 0x00010002:
|
| 521 |
+
markFilteringSetMap = NonhashableDict(
|
| 522 |
+
GDEF.table.MarkGlyphSetsDef.Coverage
|
| 523 |
+
)
|
| 524 |
+
t.table.LookupList.mapMarkFilteringSets(markFilteringSetMap)
|
| 525 |
+
|
| 526 |
+
# TODO FeatureParams nameIDs
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/merge/options.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2013 Google, Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Google Author(s): Behdad Esfahbod, Roozbeh Pournader
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Options(object):
|
| 7 |
+
class UnknownOptionError(Exception):
|
| 8 |
+
pass
|
| 9 |
+
|
| 10 |
+
def __init__(self, **kwargs):
|
| 11 |
+
self.verbose = False
|
| 12 |
+
self.timing = False
|
| 13 |
+
self.drop_tables = []
|
| 14 |
+
self.input_file = None
|
| 15 |
+
self.output_file = "merged.ttf"
|
| 16 |
+
self.import_file = None
|
| 17 |
+
|
| 18 |
+
self.set(**kwargs)
|
| 19 |
+
|
| 20 |
+
def set(self, **kwargs):
|
| 21 |
+
for k, v in kwargs.items():
|
| 22 |
+
if not hasattr(self, k):
|
| 23 |
+
raise self.UnknownOptionError("Unknown option '%s'" % k)
|
| 24 |
+
setattr(self, k, v)
|
| 25 |
+
|
| 26 |
+
def parse_opts(self, argv, ignore_unknown=[]):
|
| 27 |
+
ret = []
|
| 28 |
+
opts = {}
|
| 29 |
+
for a in argv:
|
| 30 |
+
orig_a = a
|
| 31 |
+
if not a.startswith("--"):
|
| 32 |
+
ret.append(a)
|
| 33 |
+
continue
|
| 34 |
+
a = a[2:]
|
| 35 |
+
i = a.find("=")
|
| 36 |
+
op = "="
|
| 37 |
+
if i == -1:
|
| 38 |
+
if a.startswith("no-"):
|
| 39 |
+
k = a[3:]
|
| 40 |
+
v = False
|
| 41 |
+
else:
|
| 42 |
+
k = a
|
| 43 |
+
v = True
|
| 44 |
+
else:
|
| 45 |
+
k = a[:i]
|
| 46 |
+
if k[-1] in "-+":
|
| 47 |
+
op = k[-1] + "=" # Ops is '-=' or '+=' now.
|
| 48 |
+
k = k[:-1]
|
| 49 |
+
v = a[i + 1 :]
|
| 50 |
+
ok = k
|
| 51 |
+
k = k.replace("-", "_")
|
| 52 |
+
if not hasattr(self, k):
|
| 53 |
+
if ignore_unknown is True or ok in ignore_unknown:
|
| 54 |
+
ret.append(orig_a)
|
| 55 |
+
continue
|
| 56 |
+
else:
|
| 57 |
+
raise self.UnknownOptionError("Unknown option '%s'" % a)
|
| 58 |
+
|
| 59 |
+
ov = getattr(self, k)
|
| 60 |
+
if isinstance(ov, bool):
|
| 61 |
+
v = bool(v)
|
| 62 |
+
elif isinstance(ov, int):
|
| 63 |
+
v = int(v)
|
| 64 |
+
elif isinstance(ov, list):
|
| 65 |
+
vv = v.split(",")
|
| 66 |
+
if vv == [""]:
|
| 67 |
+
vv = []
|
| 68 |
+
vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv]
|
| 69 |
+
if op == "=":
|
| 70 |
+
v = vv
|
| 71 |
+
elif op == "+=":
|
| 72 |
+
v = ov
|
| 73 |
+
v.extend(vv)
|
| 74 |
+
elif op == "-=":
|
| 75 |
+
v = ov
|
| 76 |
+
for x in vv:
|
| 77 |
+
if x in v:
|
| 78 |
+
v.remove(x)
|
| 79 |
+
else:
|
| 80 |
+
assert 0
|
| 81 |
+
|
| 82 |
+
opts[k] = v
|
| 83 |
+
self.set(**opts)
|
| 84 |
+
|
| 85 |
+
return ret
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/arrayTools.cpython-310.pyc
ADDED
|
Binary file (12.9 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/cliTools.cpython-310.pyc
ADDED
|
Binary file (1.88 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/eexec.cpython-310.pyc
ADDED
|
Binary file (3.64 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/filenames.cpython-310.pyc
ADDED
|
Binary file (6.96 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/iterTools.cpython-310.pyc
ADDED
|
Binary file (493 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/loggingTools.cpython-310.pyc
ADDED
|
Binary file (18.4 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/macRes.cpython-310.pyc
ADDED
|
Binary file (8.85 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/psLib.cpython-310.pyc
ADDED
|
Binary file (10.2 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/psOperators.cpython-310.pyc
ADDED
|
Binary file (18.7 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/roundTools.cpython-310.pyc
ADDED
|
Binary file (3.17 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/textTools.cpython-310.pyc
ADDED
|
Binary file (4.81 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/timeTools.cpython-310.pyc
ADDED
|
Binary file (2.56 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/transform.cpython-310.pyc
ADDED
|
Binary file (15.5 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/treeTools.cpython-310.pyc
ADDED
|
Binary file (1.11 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/vector.cpython-310.pyc
ADDED
|
Binary file (6.32 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/__pycache__/visitor.cpython-310.pyc
ADDED
|
Binary file (5.07 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/arrayTools.py
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Routines for calculating bounding boxes, point in rectangle calculations and
|
| 2 |
+
so on.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from fontTools.misc.roundTools import otRound
|
| 6 |
+
from fontTools.misc.vector import Vector as _Vector
|
| 7 |
+
import math
|
| 8 |
+
import warnings
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def calcBounds(array):
|
| 12 |
+
"""Calculate the bounding rectangle of a 2D points array.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
array: A sequence of 2D tuples.
|
| 16 |
+
|
| 17 |
+
Returns:
|
| 18 |
+
A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
|
| 19 |
+
"""
|
| 20 |
+
if not array:
|
| 21 |
+
return 0, 0, 0, 0
|
| 22 |
+
xs = [x for x, y in array]
|
| 23 |
+
ys = [y for x, y in array]
|
| 24 |
+
return min(xs), min(ys), max(xs), max(ys)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def calcIntBounds(array, round=otRound):
|
| 28 |
+
"""Calculate the integer bounding rectangle of a 2D points array.
|
| 29 |
+
|
| 30 |
+
Values are rounded to closest integer towards ``+Infinity`` using the
|
| 31 |
+
:func:`fontTools.misc.fixedTools.otRound` function by default, unless
|
| 32 |
+
an optional ``round`` function is passed.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
array: A sequence of 2D tuples.
|
| 36 |
+
round: A rounding function of type ``f(x: float) -> int``.
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
A four-item tuple of integers representing the bounding rectangle:
|
| 40 |
+
``(xMin, yMin, xMax, yMax)``.
|
| 41 |
+
"""
|
| 42 |
+
return tuple(round(v) for v in calcBounds(array))
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def updateBounds(bounds, p, min=min, max=max):
|
| 46 |
+
"""Add a point to a bounding rectangle.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
bounds: A bounding rectangle expressed as a tuple
|
| 50 |
+
``(xMin, yMin, xMax, yMax), or None``.
|
| 51 |
+
p: A 2D tuple representing a point.
|
| 52 |
+
min,max: functions to compute the minimum and maximum.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
The updated bounding rectangle ``(xMin, yMin, xMax, yMax)``.
|
| 56 |
+
"""
|
| 57 |
+
(x, y) = p
|
| 58 |
+
if bounds is None:
|
| 59 |
+
return x, y, x, y
|
| 60 |
+
xMin, yMin, xMax, yMax = bounds
|
| 61 |
+
return min(xMin, x), min(yMin, y), max(xMax, x), max(yMax, y)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def pointInRect(p, rect):
|
| 65 |
+
"""Test if a point is inside a bounding rectangle.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
p: A 2D tuple representing a point.
|
| 69 |
+
rect: A bounding rectangle expressed as a tuple
|
| 70 |
+
``(xMin, yMin, xMax, yMax)``.
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
``True`` if the point is inside the rectangle, ``False`` otherwise.
|
| 74 |
+
"""
|
| 75 |
+
(x, y) = p
|
| 76 |
+
xMin, yMin, xMax, yMax = rect
|
| 77 |
+
return (xMin <= x <= xMax) and (yMin <= y <= yMax)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def pointsInRect(array, rect):
|
| 81 |
+
"""Determine which points are inside a bounding rectangle.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
array: A sequence of 2D tuples.
|
| 85 |
+
rect: A bounding rectangle expressed as a tuple
|
| 86 |
+
``(xMin, yMin, xMax, yMax)``.
|
| 87 |
+
|
| 88 |
+
Returns:
|
| 89 |
+
A list containing the points inside the rectangle.
|
| 90 |
+
"""
|
| 91 |
+
if len(array) < 1:
|
| 92 |
+
return []
|
| 93 |
+
xMin, yMin, xMax, yMax = rect
|
| 94 |
+
return [(xMin <= x <= xMax) and (yMin <= y <= yMax) for x, y in array]
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def vectorLength(vector):
|
| 98 |
+
"""Calculate the length of the given vector.
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
vector: A 2D tuple.
|
| 102 |
+
|
| 103 |
+
Returns:
|
| 104 |
+
The Euclidean length of the vector.
|
| 105 |
+
"""
|
| 106 |
+
x, y = vector
|
| 107 |
+
return math.sqrt(x**2 + y**2)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def asInt16(array):
|
| 111 |
+
"""Round a list of floats to 16-bit signed integers.
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
array: List of float values.
|
| 115 |
+
|
| 116 |
+
Returns:
|
| 117 |
+
A list of rounded integers.
|
| 118 |
+
"""
|
| 119 |
+
return [int(math.floor(i + 0.5)) for i in array]
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def normRect(rect):
|
| 123 |
+
"""Normalize a bounding box rectangle.
|
| 124 |
+
|
| 125 |
+
This function "turns the rectangle the right way up", so that the following
|
| 126 |
+
holds::
|
| 127 |
+
|
| 128 |
+
xMin <= xMax and yMin <= yMax
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
rect: A bounding rectangle expressed as a tuple
|
| 132 |
+
``(xMin, yMin, xMax, yMax)``.
|
| 133 |
+
|
| 134 |
+
Returns:
|
| 135 |
+
A normalized bounding rectangle.
|
| 136 |
+
"""
|
| 137 |
+
(xMin, yMin, xMax, yMax) = rect
|
| 138 |
+
return min(xMin, xMax), min(yMin, yMax), max(xMin, xMax), max(yMin, yMax)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def scaleRect(rect, x, y):
|
| 142 |
+
"""Scale a bounding box rectangle.
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
rect: A bounding rectangle expressed as a tuple
|
| 146 |
+
``(xMin, yMin, xMax, yMax)``.
|
| 147 |
+
x: Factor to scale the rectangle along the X axis.
|
| 148 |
+
Y: Factor to scale the rectangle along the Y axis.
|
| 149 |
+
|
| 150 |
+
Returns:
|
| 151 |
+
A scaled bounding rectangle.
|
| 152 |
+
"""
|
| 153 |
+
(xMin, yMin, xMax, yMax) = rect
|
| 154 |
+
return xMin * x, yMin * y, xMax * x, yMax * y
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def offsetRect(rect, dx, dy):
|
| 158 |
+
"""Offset a bounding box rectangle.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
rect: A bounding rectangle expressed as a tuple
|
| 162 |
+
``(xMin, yMin, xMax, yMax)``.
|
| 163 |
+
dx: Amount to offset the rectangle along the X axis.
|
| 164 |
+
dY: Amount to offset the rectangle along the Y axis.
|
| 165 |
+
|
| 166 |
+
Returns:
|
| 167 |
+
An offset bounding rectangle.
|
| 168 |
+
"""
|
| 169 |
+
(xMin, yMin, xMax, yMax) = rect
|
| 170 |
+
return xMin + dx, yMin + dy, xMax + dx, yMax + dy
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def insetRect(rect, dx, dy):
|
| 174 |
+
"""Inset a bounding box rectangle on all sides.
|
| 175 |
+
|
| 176 |
+
Args:
|
| 177 |
+
rect: A bounding rectangle expressed as a tuple
|
| 178 |
+
``(xMin, yMin, xMax, yMax)``.
|
| 179 |
+
dx: Amount to inset the rectangle along the X axis.
|
| 180 |
+
dY: Amount to inset the rectangle along the Y axis.
|
| 181 |
+
|
| 182 |
+
Returns:
|
| 183 |
+
An inset bounding rectangle.
|
| 184 |
+
"""
|
| 185 |
+
(xMin, yMin, xMax, yMax) = rect
|
| 186 |
+
return xMin + dx, yMin + dy, xMax - dx, yMax - dy
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def sectRect(rect1, rect2):
|
| 190 |
+
"""Test for rectangle-rectangle intersection.
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
rect1: First bounding rectangle, expressed as tuples
|
| 194 |
+
``(xMin, yMin, xMax, yMax)``.
|
| 195 |
+
rect2: Second bounding rectangle.
|
| 196 |
+
|
| 197 |
+
Returns:
|
| 198 |
+
A boolean and a rectangle.
|
| 199 |
+
If the input rectangles intersect, returns ``True`` and the intersecting
|
| 200 |
+
rectangle. Returns ``False`` and ``(0, 0, 0, 0)`` if the input
|
| 201 |
+
rectangles don't intersect.
|
| 202 |
+
"""
|
| 203 |
+
(xMin1, yMin1, xMax1, yMax1) = rect1
|
| 204 |
+
(xMin2, yMin2, xMax2, yMax2) = rect2
|
| 205 |
+
xMin, yMin, xMax, yMax = (
|
| 206 |
+
max(xMin1, xMin2),
|
| 207 |
+
max(yMin1, yMin2),
|
| 208 |
+
min(xMax1, xMax2),
|
| 209 |
+
min(yMax1, yMax2),
|
| 210 |
+
)
|
| 211 |
+
if xMin >= xMax or yMin >= yMax:
|
| 212 |
+
return False, (0, 0, 0, 0)
|
| 213 |
+
return True, (xMin, yMin, xMax, yMax)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def unionRect(rect1, rect2):
|
| 217 |
+
"""Determine union of bounding rectangles.
|
| 218 |
+
|
| 219 |
+
Args:
|
| 220 |
+
rect1: First bounding rectangle, expressed as tuples
|
| 221 |
+
``(xMin, yMin, xMax, yMax)``.
|
| 222 |
+
rect2: Second bounding rectangle.
|
| 223 |
+
|
| 224 |
+
Returns:
|
| 225 |
+
The smallest rectangle in which both input rectangles are fully
|
| 226 |
+
enclosed.
|
| 227 |
+
"""
|
| 228 |
+
(xMin1, yMin1, xMax1, yMax1) = rect1
|
| 229 |
+
(xMin2, yMin2, xMax2, yMax2) = rect2
|
| 230 |
+
xMin, yMin, xMax, yMax = (
|
| 231 |
+
min(xMin1, xMin2),
|
| 232 |
+
min(yMin1, yMin2),
|
| 233 |
+
max(xMax1, xMax2),
|
| 234 |
+
max(yMax1, yMax2),
|
| 235 |
+
)
|
| 236 |
+
return (xMin, yMin, xMax, yMax)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def rectCenter(rect):
|
| 240 |
+
"""Determine rectangle center.
|
| 241 |
+
|
| 242 |
+
Args:
|
| 243 |
+
rect: Bounding rectangle, expressed as tuples
|
| 244 |
+
``(xMin, yMin, xMax, yMax)``.
|
| 245 |
+
|
| 246 |
+
Returns:
|
| 247 |
+
A 2D tuple representing the point at the center of the rectangle.
|
| 248 |
+
"""
|
| 249 |
+
(xMin, yMin, xMax, yMax) = rect
|
| 250 |
+
return (xMin + xMax) / 2, (yMin + yMax) / 2
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def rectArea(rect):
|
| 254 |
+
"""Determine rectangle area.
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
rect: Bounding rectangle, expressed as tuples
|
| 258 |
+
``(xMin, yMin, xMax, yMax)``.
|
| 259 |
+
|
| 260 |
+
Returns:
|
| 261 |
+
The area of the rectangle.
|
| 262 |
+
"""
|
| 263 |
+
(xMin, yMin, xMax, yMax) = rect
|
| 264 |
+
return (yMax - yMin) * (xMax - xMin)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def intRect(rect):
|
| 268 |
+
"""Round a rectangle to integer values.
|
| 269 |
+
|
| 270 |
+
Guarantees that the resulting rectangle is NOT smaller than the original.
|
| 271 |
+
|
| 272 |
+
Args:
|
| 273 |
+
rect: Bounding rectangle, expressed as tuples
|
| 274 |
+
``(xMin, yMin, xMax, yMax)``.
|
| 275 |
+
|
| 276 |
+
Returns:
|
| 277 |
+
A rounded bounding rectangle.
|
| 278 |
+
"""
|
| 279 |
+
(xMin, yMin, xMax, yMax) = rect
|
| 280 |
+
xMin = int(math.floor(xMin))
|
| 281 |
+
yMin = int(math.floor(yMin))
|
| 282 |
+
xMax = int(math.ceil(xMax))
|
| 283 |
+
yMax = int(math.ceil(yMax))
|
| 284 |
+
return (xMin, yMin, xMax, yMax)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def quantizeRect(rect, factor=1):
|
| 288 |
+
"""
|
| 289 |
+
>>> bounds = (72.3, -218.4, 1201.3, 919.1)
|
| 290 |
+
>>> quantizeRect(bounds)
|
| 291 |
+
(72, -219, 1202, 920)
|
| 292 |
+
>>> quantizeRect(bounds, factor=10)
|
| 293 |
+
(70, -220, 1210, 920)
|
| 294 |
+
>>> quantizeRect(bounds, factor=100)
|
| 295 |
+
(0, -300, 1300, 1000)
|
| 296 |
+
"""
|
| 297 |
+
if factor < 1:
|
| 298 |
+
raise ValueError(f"Expected quantization factor >= 1, found: {factor!r}")
|
| 299 |
+
xMin, yMin, xMax, yMax = normRect(rect)
|
| 300 |
+
return (
|
| 301 |
+
int(math.floor(xMin / factor) * factor),
|
| 302 |
+
int(math.floor(yMin / factor) * factor),
|
| 303 |
+
int(math.ceil(xMax / factor) * factor),
|
| 304 |
+
int(math.ceil(yMax / factor) * factor),
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
class Vector(_Vector):
|
| 309 |
+
def __init__(self, *args, **kwargs):
|
| 310 |
+
warnings.warn(
|
| 311 |
+
"fontTools.misc.arrayTools.Vector has been deprecated, please use "
|
| 312 |
+
"fontTools.misc.vector.Vector instead.",
|
| 313 |
+
DeprecationWarning,
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def pairwise(iterable, reverse=False):
|
| 318 |
+
"""Iterate over current and next items in iterable.
|
| 319 |
+
|
| 320 |
+
Args:
|
| 321 |
+
iterable: An iterable
|
| 322 |
+
reverse: If true, iterate in reverse order.
|
| 323 |
+
|
| 324 |
+
Returns:
|
| 325 |
+
A iterable yielding two elements per iteration.
|
| 326 |
+
|
| 327 |
+
Example:
|
| 328 |
+
|
| 329 |
+
>>> tuple(pairwise([]))
|
| 330 |
+
()
|
| 331 |
+
>>> tuple(pairwise([], reverse=True))
|
| 332 |
+
()
|
| 333 |
+
>>> tuple(pairwise([0]))
|
| 334 |
+
((0, 0),)
|
| 335 |
+
>>> tuple(pairwise([0], reverse=True))
|
| 336 |
+
((0, 0),)
|
| 337 |
+
>>> tuple(pairwise([0, 1]))
|
| 338 |
+
((0, 1), (1, 0))
|
| 339 |
+
>>> tuple(pairwise([0, 1], reverse=True))
|
| 340 |
+
((1, 0), (0, 1))
|
| 341 |
+
>>> tuple(pairwise([0, 1, 2]))
|
| 342 |
+
((0, 1), (1, 2), (2, 0))
|
| 343 |
+
>>> tuple(pairwise([0, 1, 2], reverse=True))
|
| 344 |
+
((2, 1), (1, 0), (0, 2))
|
| 345 |
+
>>> tuple(pairwise(['a', 'b', 'c', 'd']))
|
| 346 |
+
(('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'))
|
| 347 |
+
>>> tuple(pairwise(['a', 'b', 'c', 'd'], reverse=True))
|
| 348 |
+
(('d', 'c'), ('c', 'b'), ('b', 'a'), ('a', 'd'))
|
| 349 |
+
"""
|
| 350 |
+
if not iterable:
|
| 351 |
+
return
|
| 352 |
+
if reverse:
|
| 353 |
+
it = reversed(iterable)
|
| 354 |
+
else:
|
| 355 |
+
it = iter(iterable)
|
| 356 |
+
first = next(it, None)
|
| 357 |
+
a = first
|
| 358 |
+
for b in it:
|
| 359 |
+
yield (a, b)
|
| 360 |
+
a = b
|
| 361 |
+
yield (a, first)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def _test():
|
| 365 |
+
"""
|
| 366 |
+
>>> import math
|
| 367 |
+
>>> calcBounds([])
|
| 368 |
+
(0, 0, 0, 0)
|
| 369 |
+
>>> calcBounds([(0, 40), (0, 100), (50, 50), (80, 10)])
|
| 370 |
+
(0, 10, 80, 100)
|
| 371 |
+
>>> updateBounds((0, 0, 0, 0), (100, 100))
|
| 372 |
+
(0, 0, 100, 100)
|
| 373 |
+
>>> pointInRect((50, 50), (0, 0, 100, 100))
|
| 374 |
+
True
|
| 375 |
+
>>> pointInRect((0, 0), (0, 0, 100, 100))
|
| 376 |
+
True
|
| 377 |
+
>>> pointInRect((100, 100), (0, 0, 100, 100))
|
| 378 |
+
True
|
| 379 |
+
>>> not pointInRect((101, 100), (0, 0, 100, 100))
|
| 380 |
+
True
|
| 381 |
+
>>> list(pointsInRect([(50, 50), (0, 0), (100, 100), (101, 100)], (0, 0, 100, 100)))
|
| 382 |
+
[True, True, True, False]
|
| 383 |
+
>>> vectorLength((3, 4))
|
| 384 |
+
5.0
|
| 385 |
+
>>> vectorLength((1, 1)) == math.sqrt(2)
|
| 386 |
+
True
|
| 387 |
+
>>> list(asInt16([0, 0.1, 0.5, 0.9]))
|
| 388 |
+
[0, 0, 1, 1]
|
| 389 |
+
>>> normRect((0, 10, 100, 200))
|
| 390 |
+
(0, 10, 100, 200)
|
| 391 |
+
>>> normRect((100, 200, 0, 10))
|
| 392 |
+
(0, 10, 100, 200)
|
| 393 |
+
>>> scaleRect((10, 20, 50, 150), 1.5, 2)
|
| 394 |
+
(15.0, 40, 75.0, 300)
|
| 395 |
+
>>> offsetRect((10, 20, 30, 40), 5, 6)
|
| 396 |
+
(15, 26, 35, 46)
|
| 397 |
+
>>> insetRect((10, 20, 50, 60), 5, 10)
|
| 398 |
+
(15, 30, 45, 50)
|
| 399 |
+
>>> insetRect((10, 20, 50, 60), -5, -10)
|
| 400 |
+
(5, 10, 55, 70)
|
| 401 |
+
>>> intersects, rect = sectRect((0, 10, 20, 30), (0, 40, 20, 50))
|
| 402 |
+
>>> not intersects
|
| 403 |
+
True
|
| 404 |
+
>>> intersects, rect = sectRect((0, 10, 20, 30), (5, 20, 35, 50))
|
| 405 |
+
>>> intersects
|
| 406 |
+
1
|
| 407 |
+
>>> rect
|
| 408 |
+
(5, 20, 20, 30)
|
| 409 |
+
>>> unionRect((0, 10, 20, 30), (0, 40, 20, 50))
|
| 410 |
+
(0, 10, 20, 50)
|
| 411 |
+
>>> rectCenter((0, 0, 100, 200))
|
| 412 |
+
(50.0, 100.0)
|
| 413 |
+
>>> rectCenter((0, 0, 100, 199.0))
|
| 414 |
+
(50.0, 99.5)
|
| 415 |
+
>>> intRect((0.9, 2.9, 3.1, 4.1))
|
| 416 |
+
(0, 2, 4, 5)
|
| 417 |
+
"""
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
if __name__ == "__main__":
|
| 421 |
+
import sys
|
| 422 |
+
import doctest
|
| 423 |
+
|
| 424 |
+
sys.exit(doctest.testmod().failed)
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/cliTools.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Collection of utilities for command-line interfaces and console scripts."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
numberAddedRE = re.compile(r"#\d+$")
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def makeOutputFileName(
|
| 11 |
+
input, outputDir=None, extension=None, overWrite=False, suffix=""
|
| 12 |
+
):
|
| 13 |
+
"""Generates a suitable file name for writing output.
|
| 14 |
+
|
| 15 |
+
Often tools will want to take a file, do some kind of transformation to it,
|
| 16 |
+
and write it out again. This function determines an appropriate name for the
|
| 17 |
+
output file, through one or more of the following steps:
|
| 18 |
+
|
| 19 |
+
- changing the output directory
|
| 20 |
+
- appending suffix before file extension
|
| 21 |
+
- replacing the file extension
|
| 22 |
+
- suffixing the filename with a number (``#1``, ``#2``, etc.) to avoid
|
| 23 |
+
overwriting an existing file.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
input: Name of input file.
|
| 27 |
+
outputDir: Optionally, a new directory to write the file into.
|
| 28 |
+
suffix: Optionally, a string suffix is appended to file name before
|
| 29 |
+
the extension.
|
| 30 |
+
extension: Optionally, a replacement for the current file extension.
|
| 31 |
+
overWrite: Overwriting an existing file is permitted if true; if false
|
| 32 |
+
and the proposed filename exists, a new name will be generated by
|
| 33 |
+
adding an appropriate number suffix.
|
| 34 |
+
|
| 35 |
+
Returns:
|
| 36 |
+
str: Suitable output filename
|
| 37 |
+
"""
|
| 38 |
+
dirName, fileName = os.path.split(input)
|
| 39 |
+
fileName, ext = os.path.splitext(fileName)
|
| 40 |
+
if outputDir:
|
| 41 |
+
dirName = outputDir
|
| 42 |
+
fileName = numberAddedRE.split(fileName)[0]
|
| 43 |
+
if extension is None:
|
| 44 |
+
extension = os.path.splitext(input)[1]
|
| 45 |
+
output = os.path.join(dirName, fileName + suffix + extension)
|
| 46 |
+
n = 1
|
| 47 |
+
if not overWrite:
|
| 48 |
+
while os.path.exists(output):
|
| 49 |
+
output = os.path.join(
|
| 50 |
+
dirName, fileName + suffix + "#" + repr(n) + extension
|
| 51 |
+
)
|
| 52 |
+
n += 1
|
| 53 |
+
return output
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/cython.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Exports a no-op 'cython' namespace similar to
|
| 2 |
+
https://github.com/cython/cython/blob/master/Cython/Shadow.py
|
| 3 |
+
|
| 4 |
+
This allows to optionally compile @cython decorated functions
|
| 5 |
+
(when cython is available at built time), or run the same code
|
| 6 |
+
as pure-python, without runtime dependency on cython module.
|
| 7 |
+
|
| 8 |
+
We only define the symbols that we use. E.g. see fontTools.cu2qu
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from types import SimpleNamespace
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _empty_decorator(x):
|
| 15 |
+
return x
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
compiled = False
|
| 19 |
+
|
| 20 |
+
for name in ("double", "complex", "int"):
|
| 21 |
+
globals()[name] = None
|
| 22 |
+
|
| 23 |
+
for name in ("cfunc", "inline"):
|
| 24 |
+
globals()[name] = _empty_decorator
|
| 25 |
+
|
| 26 |
+
locals = lambda **_: _empty_decorator
|
| 27 |
+
returns = lambda _: _empty_decorator
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/dictTools.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Misc dict tools."""
|
| 2 |
+
|
| 3 |
+
__all__ = ["hashdict"]
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# https://stackoverflow.com/questions/1151658/python-hashable-dicts
|
| 7 |
+
class hashdict(dict):
|
| 8 |
+
"""
|
| 9 |
+
hashable dict implementation, suitable for use as a key into
|
| 10 |
+
other dicts.
|
| 11 |
+
|
| 12 |
+
>>> h1 = hashdict({"apples": 1, "bananas":2})
|
| 13 |
+
>>> h2 = hashdict({"bananas": 3, "mangoes": 5})
|
| 14 |
+
>>> h1+h2
|
| 15 |
+
hashdict(apples=1, bananas=3, mangoes=5)
|
| 16 |
+
>>> d1 = {}
|
| 17 |
+
>>> d1[h1] = "salad"
|
| 18 |
+
>>> d1[h1]
|
| 19 |
+
'salad'
|
| 20 |
+
>>> d1[h2]
|
| 21 |
+
Traceback (most recent call last):
|
| 22 |
+
...
|
| 23 |
+
KeyError: hashdict(bananas=3, mangoes=5)
|
| 24 |
+
|
| 25 |
+
based on answers from
|
| 26 |
+
http://stackoverflow.com/questions/1151658/python-hashable-dicts
|
| 27 |
+
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __key(self):
|
| 31 |
+
return tuple(sorted(self.items()))
|
| 32 |
+
|
| 33 |
+
def __repr__(self):
|
| 34 |
+
return "{0}({1})".format(
|
| 35 |
+
self.__class__.__name__,
|
| 36 |
+
", ".join("{0}={1}".format(str(i[0]), repr(i[1])) for i in self.__key()),
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
def __hash__(self):
|
| 40 |
+
return hash(self.__key())
|
| 41 |
+
|
| 42 |
+
def __setitem__(self, key, value):
|
| 43 |
+
raise TypeError(
|
| 44 |
+
"{0} does not support item assignment".format(self.__class__.__name__)
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
def __delitem__(self, key):
|
| 48 |
+
raise TypeError(
|
| 49 |
+
"{0} does not support item assignment".format(self.__class__.__name__)
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
def clear(self):
|
| 53 |
+
raise TypeError(
|
| 54 |
+
"{0} does not support item assignment".format(self.__class__.__name__)
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
def pop(self, *args, **kwargs):
|
| 58 |
+
raise TypeError(
|
| 59 |
+
"{0} does not support item assignment".format(self.__class__.__name__)
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
def popitem(self, *args, **kwargs):
|
| 63 |
+
raise TypeError(
|
| 64 |
+
"{0} does not support item assignment".format(self.__class__.__name__)
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
def setdefault(self, *args, **kwargs):
|
| 68 |
+
raise TypeError(
|
| 69 |
+
"{0} does not support item assignment".format(self.__class__.__name__)
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
def update(self, *args, **kwargs):
|
| 73 |
+
raise TypeError(
|
| 74 |
+
"{0} does not support item assignment".format(self.__class__.__name__)
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
# update is not ok because it mutates the object
|
| 78 |
+
# __add__ is ok because it creates a new object
|
| 79 |
+
# while the new object is under construction, it's ok to mutate it
|
| 80 |
+
def __add__(self, right):
|
| 81 |
+
result = hashdict(self)
|
| 82 |
+
dict.update(result, right)
|
| 83 |
+
return result
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/fixedTools.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
The `OpenType specification <https://docs.microsoft.com/en-us/typography/opentype/spec/otff#data-types>`_
|
| 3 |
+
defines two fixed-point data types:
|
| 4 |
+
|
| 5 |
+
``Fixed``
|
| 6 |
+
A 32-bit signed fixed-point number with a 16 bit twos-complement
|
| 7 |
+
magnitude component and 16 fractional bits.
|
| 8 |
+
``F2DOT14``
|
| 9 |
+
A 16-bit signed fixed-point number with a 2 bit twos-complement
|
| 10 |
+
magnitude component and 14 fractional bits.
|
| 11 |
+
|
| 12 |
+
To support reading and writing data with these data types, this module provides
|
| 13 |
+
functions for converting between fixed-point, float and string representations.
|
| 14 |
+
|
| 15 |
+
.. data:: MAX_F2DOT14
|
| 16 |
+
|
| 17 |
+
The maximum value that can still fit in an F2Dot14. (1.99993896484375)
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from .roundTools import otRound, nearestMultipleShortestRepr
|
| 21 |
+
import logging
|
| 22 |
+
|
| 23 |
+
log = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
__all__ = [
|
| 26 |
+
"MAX_F2DOT14",
|
| 27 |
+
"fixedToFloat",
|
| 28 |
+
"floatToFixed",
|
| 29 |
+
"floatToFixedToFloat",
|
| 30 |
+
"floatToFixedToStr",
|
| 31 |
+
"fixedToStr",
|
| 32 |
+
"strToFixed",
|
| 33 |
+
"strToFixedToFloat",
|
| 34 |
+
"ensureVersionIsLong",
|
| 35 |
+
"versionToFixed",
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
MAX_F2DOT14 = 0x7FFF / (1 << 14)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def fixedToFloat(value, precisionBits):
|
| 43 |
+
"""Converts a fixed-point number to a float given the number of
|
| 44 |
+
precision bits.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
value (int): Number in fixed-point format.
|
| 48 |
+
precisionBits (int): Number of precision bits.
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
Floating point value.
|
| 52 |
+
|
| 53 |
+
Examples::
|
| 54 |
+
|
| 55 |
+
>>> import math
|
| 56 |
+
>>> f = fixedToFloat(-10139, precisionBits=14)
|
| 57 |
+
>>> math.isclose(f, -0.61883544921875)
|
| 58 |
+
True
|
| 59 |
+
"""
|
| 60 |
+
return value / (1 << precisionBits)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def floatToFixed(value, precisionBits):
|
| 64 |
+
"""Converts a float to a fixed-point number given the number of
|
| 65 |
+
precision bits.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
value (float): Floating point value.
|
| 69 |
+
precisionBits (int): Number of precision bits.
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
int: Fixed-point representation.
|
| 73 |
+
|
| 74 |
+
Examples::
|
| 75 |
+
|
| 76 |
+
>>> floatToFixed(-0.61883544921875, precisionBits=14)
|
| 77 |
+
-10139
|
| 78 |
+
>>> floatToFixed(-0.61884, precisionBits=14)
|
| 79 |
+
-10139
|
| 80 |
+
"""
|
| 81 |
+
return otRound(value * (1 << precisionBits))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def floatToFixedToFloat(value, precisionBits):
|
| 85 |
+
"""Converts a float to a fixed-point number and back again.
|
| 86 |
+
|
| 87 |
+
By converting the float to fixed, rounding it, and converting it back
|
| 88 |
+
to float again, this returns a floating point values which is exactly
|
| 89 |
+
representable in fixed-point format.
|
| 90 |
+
|
| 91 |
+
Note: this **is** equivalent to ``fixedToFloat(floatToFixed(value))``.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
value (float): The input floating point value.
|
| 95 |
+
precisionBits (int): Number of precision bits.
|
| 96 |
+
|
| 97 |
+
Returns:
|
| 98 |
+
float: The transformed and rounded value.
|
| 99 |
+
|
| 100 |
+
Examples::
|
| 101 |
+
>>> import math
|
| 102 |
+
>>> f1 = -0.61884
|
| 103 |
+
>>> f2 = floatToFixedToFloat(-0.61884, precisionBits=14)
|
| 104 |
+
>>> f1 != f2
|
| 105 |
+
True
|
| 106 |
+
>>> math.isclose(f2, -0.61883544921875)
|
| 107 |
+
True
|
| 108 |
+
"""
|
| 109 |
+
scale = 1 << precisionBits
|
| 110 |
+
return otRound(value * scale) / scale
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def fixedToStr(value, precisionBits):
|
| 114 |
+
"""Converts a fixed-point number to a string representing a decimal float.
|
| 115 |
+
|
| 116 |
+
This chooses the float that has the shortest decimal representation (the least
|
| 117 |
+
number of fractional decimal digits).
|
| 118 |
+
|
| 119 |
+
For example, to convert a fixed-point number in a 2.14 format, use
|
| 120 |
+
``precisionBits=14``::
|
| 121 |
+
|
| 122 |
+
>>> fixedToStr(-10139, precisionBits=14)
|
| 123 |
+
'-0.61884'
|
| 124 |
+
|
| 125 |
+
This is pretty slow compared to the simple division used in ``fixedToFloat``.
|
| 126 |
+
Use sporadically when you need to serialize or print the fixed-point number in
|
| 127 |
+
a human-readable form.
|
| 128 |
+
It uses nearestMultipleShortestRepr under the hood.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
value (int): The fixed-point value to convert.
|
| 132 |
+
precisionBits (int): Number of precision bits, *up to a maximum of 16*.
|
| 133 |
+
|
| 134 |
+
Returns:
|
| 135 |
+
str: A string representation of the value.
|
| 136 |
+
"""
|
| 137 |
+
scale = 1 << precisionBits
|
| 138 |
+
return nearestMultipleShortestRepr(value / scale, factor=1.0 / scale)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def strToFixed(string, precisionBits):
|
| 142 |
+
"""Converts a string representing a decimal float to a fixed-point number.
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
string (str): A string representing a decimal float.
|
| 146 |
+
precisionBits (int): Number of precision bits, *up to a maximum of 16*.
|
| 147 |
+
|
| 148 |
+
Returns:
|
| 149 |
+
int: Fixed-point representation.
|
| 150 |
+
|
| 151 |
+
Examples::
|
| 152 |
+
|
| 153 |
+
>>> ## to convert a float string to a 2.14 fixed-point number:
|
| 154 |
+
>>> strToFixed('-0.61884', precisionBits=14)
|
| 155 |
+
-10139
|
| 156 |
+
"""
|
| 157 |
+
value = float(string)
|
| 158 |
+
return otRound(value * (1 << precisionBits))
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def strToFixedToFloat(string, precisionBits):
|
| 162 |
+
"""Convert a string to a decimal float with fixed-point rounding.
|
| 163 |
+
|
| 164 |
+
This first converts string to a float, then turns it into a fixed-point
|
| 165 |
+
number with ``precisionBits`` fractional binary digits, then back to a
|
| 166 |
+
float again.
|
| 167 |
+
|
| 168 |
+
This is simply a shorthand for fixedToFloat(floatToFixed(float(s))).
|
| 169 |
+
|
| 170 |
+
Args:
|
| 171 |
+
string (str): A string representing a decimal float.
|
| 172 |
+
precisionBits (int): Number of precision bits.
|
| 173 |
+
|
| 174 |
+
Returns:
|
| 175 |
+
float: The transformed and rounded value.
|
| 176 |
+
|
| 177 |
+
Examples::
|
| 178 |
+
|
| 179 |
+
>>> import math
|
| 180 |
+
>>> s = '-0.61884'
|
| 181 |
+
>>> bits = 14
|
| 182 |
+
>>> f = strToFixedToFloat(s, precisionBits=bits)
|
| 183 |
+
>>> math.isclose(f, -0.61883544921875)
|
| 184 |
+
True
|
| 185 |
+
>>> f == fixedToFloat(floatToFixed(float(s), precisionBits=bits), precisionBits=bits)
|
| 186 |
+
True
|
| 187 |
+
"""
|
| 188 |
+
value = float(string)
|
| 189 |
+
scale = 1 << precisionBits
|
| 190 |
+
return otRound(value * scale) / scale
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def floatToFixedToStr(value, precisionBits):
|
| 194 |
+
"""Convert float to string with fixed-point rounding.
|
| 195 |
+
|
| 196 |
+
This uses the shortest decimal representation (ie. the least
|
| 197 |
+
number of fractional decimal digits) to represent the equivalent
|
| 198 |
+
fixed-point number with ``precisionBits`` fractional binary digits.
|
| 199 |
+
It uses nearestMultipleShortestRepr under the hood.
|
| 200 |
+
|
| 201 |
+
>>> floatToFixedToStr(-0.61883544921875, precisionBits=14)
|
| 202 |
+
'-0.61884'
|
| 203 |
+
|
| 204 |
+
Args:
|
| 205 |
+
value (float): The float value to convert.
|
| 206 |
+
precisionBits (int): Number of precision bits, *up to a maximum of 16*.
|
| 207 |
+
|
| 208 |
+
Returns:
|
| 209 |
+
str: A string representation of the value.
|
| 210 |
+
|
| 211 |
+
"""
|
| 212 |
+
scale = 1 << precisionBits
|
| 213 |
+
return nearestMultipleShortestRepr(value, factor=1.0 / scale)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def ensureVersionIsLong(value):
|
| 217 |
+
"""Ensure a table version is an unsigned long.
|
| 218 |
+
|
| 219 |
+
OpenType table version numbers are expressed as a single unsigned long
|
| 220 |
+
comprising of an unsigned short major version and unsigned short minor
|
| 221 |
+
version. This function detects if the value to be used as a version number
|
| 222 |
+
looks too small (i.e. is less than ``0x10000``), and converts it to
|
| 223 |
+
fixed-point using :func:`floatToFixed` if so.
|
| 224 |
+
|
| 225 |
+
Args:
|
| 226 |
+
value (Number): a candidate table version number.
|
| 227 |
+
|
| 228 |
+
Returns:
|
| 229 |
+
int: A table version number, possibly corrected to fixed-point.
|
| 230 |
+
"""
|
| 231 |
+
if value < 0x10000:
|
| 232 |
+
newValue = floatToFixed(value, 16)
|
| 233 |
+
log.warning(
|
| 234 |
+
"Table version value is a float: %.4f; " "fix to use hex instead: 0x%08x",
|
| 235 |
+
value,
|
| 236 |
+
newValue,
|
| 237 |
+
)
|
| 238 |
+
value = newValue
|
| 239 |
+
return value
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def versionToFixed(value):
|
| 243 |
+
"""Ensure a table version number is fixed-point.
|
| 244 |
+
|
| 245 |
+
Args:
|
| 246 |
+
value (str): a candidate table version number.
|
| 247 |
+
|
| 248 |
+
Returns:
|
| 249 |
+
int: A table version number, possibly corrected to fixed-point.
|
| 250 |
+
"""
|
| 251 |
+
value = int(value, 0) if value.startswith("0") else float(value)
|
| 252 |
+
value = ensureVersionIsLong(value)
|
| 253 |
+
return value
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/iterTools.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import *
|
| 2 |
+
|
| 3 |
+
# Python 3.12:
|
| 4 |
+
if "batched" not in globals():
|
| 5 |
+
# https://docs.python.org/3/library/itertools.html#itertools.batched
|
| 6 |
+
def batched(iterable, n):
|
| 7 |
+
# batched('ABCDEFG', 3) --> ABC DEF G
|
| 8 |
+
if n < 1:
|
| 9 |
+
raise ValueError("n must be at least one")
|
| 10 |
+
it = iter(iterable)
|
| 11 |
+
while batch := tuple(islice(it, n)):
|
| 12 |
+
yield batch
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/loggingTools.py
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import logging
|
| 3 |
+
import timeit
|
| 4 |
+
from functools import wraps
|
| 5 |
+
from collections.abc import Mapping, Callable
|
| 6 |
+
import warnings
|
| 7 |
+
from logging import PercentStyle
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# default logging level used by Timer class
|
| 11 |
+
TIME_LEVEL = logging.DEBUG
|
| 12 |
+
|
| 13 |
+
# per-level format strings used by the default formatter
|
| 14 |
+
# (the level name is not printed for INFO and DEBUG messages)
|
| 15 |
+
DEFAULT_FORMATS = {
|
| 16 |
+
"*": "%(levelname)s: %(message)s",
|
| 17 |
+
"INFO": "%(message)s",
|
| 18 |
+
"DEBUG": "%(message)s",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class LevelFormatter(logging.Formatter):
|
| 23 |
+
"""Log formatter with level-specific formatting.
|
| 24 |
+
|
| 25 |
+
Formatter class which optionally takes a dict of logging levels to
|
| 26 |
+
format strings, allowing to customise the log records appearance for
|
| 27 |
+
specific levels.
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
Attributes:
|
| 31 |
+
fmt: A dictionary mapping logging levels to format strings.
|
| 32 |
+
The ``*`` key identifies the default format string.
|
| 33 |
+
datefmt: As per py:class:`logging.Formatter`
|
| 34 |
+
style: As per py:class:`logging.Formatter`
|
| 35 |
+
|
| 36 |
+
>>> import sys
|
| 37 |
+
>>> handler = logging.StreamHandler(sys.stdout)
|
| 38 |
+
>>> formatter = LevelFormatter(
|
| 39 |
+
... fmt={
|
| 40 |
+
... '*': '[%(levelname)s] %(message)s',
|
| 41 |
+
... 'DEBUG': '%(name)s [%(levelname)s] %(message)s',
|
| 42 |
+
... 'INFO': '%(message)s',
|
| 43 |
+
... })
|
| 44 |
+
>>> handler.setFormatter(formatter)
|
| 45 |
+
>>> log = logging.getLogger('test')
|
| 46 |
+
>>> log.setLevel(logging.DEBUG)
|
| 47 |
+
>>> log.addHandler(handler)
|
| 48 |
+
>>> log.debug('this uses a custom format string')
|
| 49 |
+
test [DEBUG] this uses a custom format string
|
| 50 |
+
>>> log.info('this also uses a custom format string')
|
| 51 |
+
this also uses a custom format string
|
| 52 |
+
>>> log.warning("this one uses the default format string")
|
| 53 |
+
[WARNING] this one uses the default format string
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
def __init__(self, fmt=None, datefmt=None, style="%"):
|
| 57 |
+
if style != "%":
|
| 58 |
+
raise ValueError(
|
| 59 |
+
"only '%' percent style is supported in both python 2 and 3"
|
| 60 |
+
)
|
| 61 |
+
if fmt is None:
|
| 62 |
+
fmt = DEFAULT_FORMATS
|
| 63 |
+
if isinstance(fmt, str):
|
| 64 |
+
default_format = fmt
|
| 65 |
+
custom_formats = {}
|
| 66 |
+
elif isinstance(fmt, Mapping):
|
| 67 |
+
custom_formats = dict(fmt)
|
| 68 |
+
default_format = custom_formats.pop("*", None)
|
| 69 |
+
else:
|
| 70 |
+
raise TypeError("fmt must be a str or a dict of str: %r" % fmt)
|
| 71 |
+
super(LevelFormatter, self).__init__(default_format, datefmt)
|
| 72 |
+
self.default_format = self._fmt
|
| 73 |
+
self.custom_formats = {}
|
| 74 |
+
for level, fmt in custom_formats.items():
|
| 75 |
+
level = logging._checkLevel(level)
|
| 76 |
+
self.custom_formats[level] = fmt
|
| 77 |
+
|
| 78 |
+
def format(self, record):
|
| 79 |
+
if self.custom_formats:
|
| 80 |
+
fmt = self.custom_formats.get(record.levelno, self.default_format)
|
| 81 |
+
if self._fmt != fmt:
|
| 82 |
+
self._fmt = fmt
|
| 83 |
+
# for python >= 3.2, _style needs to be set if _fmt changes
|
| 84 |
+
if PercentStyle:
|
| 85 |
+
self._style = PercentStyle(fmt)
|
| 86 |
+
return super(LevelFormatter, self).format(record)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def configLogger(**kwargs):
|
| 90 |
+
"""A more sophisticated logging system configuation manager.
|
| 91 |
+
|
| 92 |
+
This is more or less the same as :py:func:`logging.basicConfig`,
|
| 93 |
+
with some additional options and defaults.
|
| 94 |
+
|
| 95 |
+
The default behaviour is to create a ``StreamHandler`` which writes to
|
| 96 |
+
sys.stderr, set a formatter using the ``DEFAULT_FORMATS`` strings, and add
|
| 97 |
+
the handler to the top-level library logger ("fontTools").
|
| 98 |
+
|
| 99 |
+
A number of optional keyword arguments may be specified, which can alter
|
| 100 |
+
the default behaviour.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
|
| 104 |
+
logger: Specifies the logger name or a Logger instance to be
|
| 105 |
+
configured. (Defaults to "fontTools" logger). Unlike ``basicConfig``,
|
| 106 |
+
this function can be called multiple times to reconfigure a logger.
|
| 107 |
+
If the logger or any of its children already exists before the call is
|
| 108 |
+
made, they will be reset before the new configuration is applied.
|
| 109 |
+
filename: Specifies that a ``FileHandler`` be created, using the
|
| 110 |
+
specified filename, rather than a ``StreamHandler``.
|
| 111 |
+
filemode: Specifies the mode to open the file, if filename is
|
| 112 |
+
specified. (If filemode is unspecified, it defaults to ``a``).
|
| 113 |
+
format: Use the specified format string for the handler. This
|
| 114 |
+
argument also accepts a dictionary of format strings keyed by
|
| 115 |
+
level name, to allow customising the records appearance for
|
| 116 |
+
specific levels. The special ``'*'`` key is for 'any other' level.
|
| 117 |
+
datefmt: Use the specified date/time format.
|
| 118 |
+
level: Set the logger level to the specified level.
|
| 119 |
+
stream: Use the specified stream to initialize the StreamHandler. Note
|
| 120 |
+
that this argument is incompatible with ``filename`` - if both
|
| 121 |
+
are present, ``stream`` is ignored.
|
| 122 |
+
handlers: If specified, this should be an iterable of already created
|
| 123 |
+
handlers, which will be added to the logger. Any handler in the
|
| 124 |
+
list which does not have a formatter assigned will be assigned the
|
| 125 |
+
formatter created in this function.
|
| 126 |
+
filters: If specified, this should be an iterable of already created
|
| 127 |
+
filters. If the ``handlers`` do not already have filters assigned,
|
| 128 |
+
these filters will be added to them.
|
| 129 |
+
propagate: All loggers have a ``propagate`` attribute which determines
|
| 130 |
+
whether to continue searching for handlers up the logging hierarchy.
|
| 131 |
+
If not provided, the "propagate" attribute will be set to ``False``.
|
| 132 |
+
"""
|
| 133 |
+
# using kwargs to enforce keyword-only arguments in py2.
|
| 134 |
+
handlers = kwargs.pop("handlers", None)
|
| 135 |
+
if handlers is None:
|
| 136 |
+
if "stream" in kwargs and "filename" in kwargs:
|
| 137 |
+
raise ValueError(
|
| 138 |
+
"'stream' and 'filename' should not be " "specified together"
|
| 139 |
+
)
|
| 140 |
+
else:
|
| 141 |
+
if "stream" in kwargs or "filename" in kwargs:
|
| 142 |
+
raise ValueError(
|
| 143 |
+
"'stream' or 'filename' should not be "
|
| 144 |
+
"specified together with 'handlers'"
|
| 145 |
+
)
|
| 146 |
+
if handlers is None:
|
| 147 |
+
filename = kwargs.pop("filename", None)
|
| 148 |
+
mode = kwargs.pop("filemode", "a")
|
| 149 |
+
if filename:
|
| 150 |
+
h = logging.FileHandler(filename, mode)
|
| 151 |
+
else:
|
| 152 |
+
stream = kwargs.pop("stream", None)
|
| 153 |
+
h = logging.StreamHandler(stream)
|
| 154 |
+
handlers = [h]
|
| 155 |
+
# By default, the top-level library logger is configured.
|
| 156 |
+
logger = kwargs.pop("logger", "fontTools")
|
| 157 |
+
if not logger or isinstance(logger, str):
|
| 158 |
+
# empty "" or None means the 'root' logger
|
| 159 |
+
logger = logging.getLogger(logger)
|
| 160 |
+
# before (re)configuring, reset named logger and its children (if exist)
|
| 161 |
+
_resetExistingLoggers(parent=logger.name)
|
| 162 |
+
# use DEFAULT_FORMATS if 'format' is None
|
| 163 |
+
fs = kwargs.pop("format", None)
|
| 164 |
+
dfs = kwargs.pop("datefmt", None)
|
| 165 |
+
# XXX: '%' is the only format style supported on both py2 and 3
|
| 166 |
+
style = kwargs.pop("style", "%")
|
| 167 |
+
fmt = LevelFormatter(fs, dfs, style)
|
| 168 |
+
filters = kwargs.pop("filters", [])
|
| 169 |
+
for h in handlers:
|
| 170 |
+
if h.formatter is None:
|
| 171 |
+
h.setFormatter(fmt)
|
| 172 |
+
if not h.filters:
|
| 173 |
+
for f in filters:
|
| 174 |
+
h.addFilter(f)
|
| 175 |
+
logger.addHandler(h)
|
| 176 |
+
if logger.name != "root":
|
| 177 |
+
# stop searching up the hierarchy for handlers
|
| 178 |
+
logger.propagate = kwargs.pop("propagate", False)
|
| 179 |
+
# set a custom severity level
|
| 180 |
+
level = kwargs.pop("level", None)
|
| 181 |
+
if level is not None:
|
| 182 |
+
logger.setLevel(level)
|
| 183 |
+
if kwargs:
|
| 184 |
+
keys = ", ".join(kwargs.keys())
|
| 185 |
+
raise ValueError("Unrecognised argument(s): %s" % keys)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _resetExistingLoggers(parent="root"):
|
| 189 |
+
"""Reset the logger named 'parent' and all its children to their initial
|
| 190 |
+
state, if they already exist in the current configuration.
|
| 191 |
+
"""
|
| 192 |
+
root = logging.root
|
| 193 |
+
# get sorted list of all existing loggers
|
| 194 |
+
existing = sorted(root.manager.loggerDict.keys())
|
| 195 |
+
if parent == "root":
|
| 196 |
+
# all the existing loggers are children of 'root'
|
| 197 |
+
loggers_to_reset = [parent] + existing
|
| 198 |
+
elif parent not in existing:
|
| 199 |
+
# nothing to do
|
| 200 |
+
return
|
| 201 |
+
elif parent in existing:
|
| 202 |
+
loggers_to_reset = [parent]
|
| 203 |
+
# collect children, starting with the entry after parent name
|
| 204 |
+
i = existing.index(parent) + 1
|
| 205 |
+
prefixed = parent + "."
|
| 206 |
+
pflen = len(prefixed)
|
| 207 |
+
num_existing = len(existing)
|
| 208 |
+
while i < num_existing:
|
| 209 |
+
if existing[i][:pflen] == prefixed:
|
| 210 |
+
loggers_to_reset.append(existing[i])
|
| 211 |
+
i += 1
|
| 212 |
+
for name in loggers_to_reset:
|
| 213 |
+
if name == "root":
|
| 214 |
+
root.setLevel(logging.WARNING)
|
| 215 |
+
for h in root.handlers[:]:
|
| 216 |
+
root.removeHandler(h)
|
| 217 |
+
for f in root.filters[:]:
|
| 218 |
+
root.removeFilters(f)
|
| 219 |
+
root.disabled = False
|
| 220 |
+
else:
|
| 221 |
+
logger = root.manager.loggerDict[name]
|
| 222 |
+
logger.level = logging.NOTSET
|
| 223 |
+
logger.handlers = []
|
| 224 |
+
logger.filters = []
|
| 225 |
+
logger.propagate = True
|
| 226 |
+
logger.disabled = False
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class Timer(object):
|
| 230 |
+
"""Keeps track of overall time and split/lap times.
|
| 231 |
+
|
| 232 |
+
>>> import time
|
| 233 |
+
>>> timer = Timer()
|
| 234 |
+
>>> time.sleep(0.01)
|
| 235 |
+
>>> print("First lap:", timer.split())
|
| 236 |
+
First lap: ...
|
| 237 |
+
>>> time.sleep(0.02)
|
| 238 |
+
>>> print("Second lap:", timer.split())
|
| 239 |
+
Second lap: ...
|
| 240 |
+
>>> print("Overall time:", timer.time())
|
| 241 |
+
Overall time: ...
|
| 242 |
+
|
| 243 |
+
Can be used as a context manager inside with-statements.
|
| 244 |
+
|
| 245 |
+
>>> with Timer() as t:
|
| 246 |
+
... time.sleep(0.01)
|
| 247 |
+
>>> print("%0.3f seconds" % t.elapsed)
|
| 248 |
+
0... seconds
|
| 249 |
+
|
| 250 |
+
If initialised with a logger, it can log the elapsed time automatically
|
| 251 |
+
upon exiting the with-statement.
|
| 252 |
+
|
| 253 |
+
>>> import logging
|
| 254 |
+
>>> log = logging.getLogger("my-fancy-timer-logger")
|
| 255 |
+
>>> configLogger(logger=log, level="DEBUG", format="%(message)s", stream=sys.stdout)
|
| 256 |
+
>>> with Timer(log, 'do something'):
|
| 257 |
+
... time.sleep(0.01)
|
| 258 |
+
Took ... to do something
|
| 259 |
+
|
| 260 |
+
The same Timer instance, holding a reference to a logger, can be reused
|
| 261 |
+
in multiple with-statements, optionally with different messages or levels.
|
| 262 |
+
|
| 263 |
+
>>> timer = Timer(log)
|
| 264 |
+
>>> with timer():
|
| 265 |
+
... time.sleep(0.01)
|
| 266 |
+
elapsed time: ...s
|
| 267 |
+
>>> with timer('redo it', level=logging.INFO):
|
| 268 |
+
... time.sleep(0.02)
|
| 269 |
+
Took ... to redo it
|
| 270 |
+
|
| 271 |
+
It can also be used as a function decorator to log the time elapsed to run
|
| 272 |
+
the decorated function.
|
| 273 |
+
|
| 274 |
+
>>> @timer()
|
| 275 |
+
... def test1():
|
| 276 |
+
... time.sleep(0.01)
|
| 277 |
+
>>> @timer('run test 2', level=logging.INFO)
|
| 278 |
+
... def test2():
|
| 279 |
+
... time.sleep(0.02)
|
| 280 |
+
>>> test1()
|
| 281 |
+
Took ... to run 'test1'
|
| 282 |
+
>>> test2()
|
| 283 |
+
Took ... to run test 2
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
# timeit.default_timer choses the most accurate clock for each platform
|
| 287 |
+
_time = timeit.default_timer
|
| 288 |
+
default_msg = "elapsed time: %(time).3fs"
|
| 289 |
+
default_format = "Took %(time).3fs to %(msg)s"
|
| 290 |
+
|
| 291 |
+
def __init__(self, logger=None, msg=None, level=None, start=None):
|
| 292 |
+
self.reset(start)
|
| 293 |
+
if logger is None:
|
| 294 |
+
for arg in ("msg", "level"):
|
| 295 |
+
if locals().get(arg) is not None:
|
| 296 |
+
raise ValueError("'%s' can't be specified without a 'logger'" % arg)
|
| 297 |
+
self.logger = logger
|
| 298 |
+
self.level = level if level is not None else TIME_LEVEL
|
| 299 |
+
self.msg = msg
|
| 300 |
+
|
| 301 |
+
def reset(self, start=None):
|
| 302 |
+
"""Reset timer to 'start_time' or the current time."""
|
| 303 |
+
if start is None:
|
| 304 |
+
self.start = self._time()
|
| 305 |
+
else:
|
| 306 |
+
self.start = start
|
| 307 |
+
self.last = self.start
|
| 308 |
+
self.elapsed = 0.0
|
| 309 |
+
|
| 310 |
+
def time(self):
|
| 311 |
+
"""Return the overall time (in seconds) since the timer started."""
|
| 312 |
+
return self._time() - self.start
|
| 313 |
+
|
| 314 |
+
def split(self):
|
| 315 |
+
"""Split and return the lap time (in seconds) in between splits."""
|
| 316 |
+
current = self._time()
|
| 317 |
+
self.elapsed = current - self.last
|
| 318 |
+
self.last = current
|
| 319 |
+
return self.elapsed
|
| 320 |
+
|
| 321 |
+
def formatTime(self, msg, time):
|
| 322 |
+
"""Format 'time' value in 'msg' and return formatted string.
|
| 323 |
+
If 'msg' contains a '%(time)' format string, try to use that.
|
| 324 |
+
Otherwise, use the predefined 'default_format'.
|
| 325 |
+
If 'msg' is empty or None, fall back to 'default_msg'.
|
| 326 |
+
"""
|
| 327 |
+
if not msg:
|
| 328 |
+
msg = self.default_msg
|
| 329 |
+
if msg.find("%(time)") < 0:
|
| 330 |
+
msg = self.default_format % {"msg": msg, "time": time}
|
| 331 |
+
else:
|
| 332 |
+
try:
|
| 333 |
+
msg = msg % {"time": time}
|
| 334 |
+
except (KeyError, ValueError):
|
| 335 |
+
pass # skip if the format string is malformed
|
| 336 |
+
return msg
|
| 337 |
+
|
| 338 |
+
def __enter__(self):
|
| 339 |
+
"""Start a new lap"""
|
| 340 |
+
self.last = self._time()
|
| 341 |
+
self.elapsed = 0.0
|
| 342 |
+
return self
|
| 343 |
+
|
| 344 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 345 |
+
"""End the current lap. If timer has a logger, log the time elapsed,
|
| 346 |
+
using the format string in self.msg (or the default one).
|
| 347 |
+
"""
|
| 348 |
+
time = self.split()
|
| 349 |
+
if self.logger is None or exc_type:
|
| 350 |
+
# if there's no logger attached, or if any exception occurred in
|
| 351 |
+
# the with-statement, exit without logging the time
|
| 352 |
+
return
|
| 353 |
+
message = self.formatTime(self.msg, time)
|
| 354 |
+
# Allow log handlers to see the individual parts to facilitate things
|
| 355 |
+
# like a server accumulating aggregate stats.
|
| 356 |
+
msg_parts = {"msg": self.msg, "time": time}
|
| 357 |
+
self.logger.log(self.level, message, msg_parts)
|
| 358 |
+
|
| 359 |
+
def __call__(self, func_or_msg=None, **kwargs):
|
| 360 |
+
"""If the first argument is a function, return a decorator which runs
|
| 361 |
+
the wrapped function inside Timer's context manager.
|
| 362 |
+
Otherwise, treat the first argument as a 'msg' string and return an updated
|
| 363 |
+
Timer instance, referencing the same logger.
|
| 364 |
+
A 'level' keyword can also be passed to override self.level.
|
| 365 |
+
"""
|
| 366 |
+
if isinstance(func_or_msg, Callable):
|
| 367 |
+
func = func_or_msg
|
| 368 |
+
# use the function name when no explicit 'msg' is provided
|
| 369 |
+
if not self.msg:
|
| 370 |
+
self.msg = "run '%s'" % func.__name__
|
| 371 |
+
|
| 372 |
+
@wraps(func)
|
| 373 |
+
def wrapper(*args, **kwds):
|
| 374 |
+
with self:
|
| 375 |
+
return func(*args, **kwds)
|
| 376 |
+
|
| 377 |
+
return wrapper
|
| 378 |
+
else:
|
| 379 |
+
msg = func_or_msg or kwargs.get("msg")
|
| 380 |
+
level = kwargs.get("level", self.level)
|
| 381 |
+
return self.__class__(self.logger, msg, level)
|
| 382 |
+
|
| 383 |
+
def __float__(self):
|
| 384 |
+
return self.elapsed
|
| 385 |
+
|
| 386 |
+
def __int__(self):
|
| 387 |
+
return int(self.elapsed)
|
| 388 |
+
|
| 389 |
+
def __str__(self):
|
| 390 |
+
return "%.3f" % self.elapsed
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class ChannelsFilter(logging.Filter):
|
| 394 |
+
"""Provides a hierarchical filter for log entries based on channel names.
|
| 395 |
+
|
| 396 |
+
Filters out records emitted from a list of enabled channel names,
|
| 397 |
+
including their children. It works the same as the ``logging.Filter``
|
| 398 |
+
class, but allows the user to specify multiple channel names.
|
| 399 |
+
|
| 400 |
+
>>> import sys
|
| 401 |
+
>>> handler = logging.StreamHandler(sys.stdout)
|
| 402 |
+
>>> handler.setFormatter(logging.Formatter("%(message)s"))
|
| 403 |
+
>>> filter = ChannelsFilter("A.B", "C.D")
|
| 404 |
+
>>> handler.addFilter(filter)
|
| 405 |
+
>>> root = logging.getLogger()
|
| 406 |
+
>>> root.addHandler(handler)
|
| 407 |
+
>>> root.setLevel(level=logging.DEBUG)
|
| 408 |
+
>>> logging.getLogger('A.B').debug('this record passes through')
|
| 409 |
+
this record passes through
|
| 410 |
+
>>> logging.getLogger('A.B.C').debug('records from children also pass')
|
| 411 |
+
records from children also pass
|
| 412 |
+
>>> logging.getLogger('C.D').debug('this one as well')
|
| 413 |
+
this one as well
|
| 414 |
+
>>> logging.getLogger('A.B.').debug('also this one')
|
| 415 |
+
also this one
|
| 416 |
+
>>> logging.getLogger('A.F').debug('but this one does not!')
|
| 417 |
+
>>> logging.getLogger('C.DE').debug('neither this one!')
|
| 418 |
+
"""
|
| 419 |
+
|
| 420 |
+
def __init__(self, *names):
|
| 421 |
+
self.names = names
|
| 422 |
+
self.num = len(names)
|
| 423 |
+
self.lengths = {n: len(n) for n in names}
|
| 424 |
+
|
| 425 |
+
def filter(self, record):
|
| 426 |
+
if self.num == 0:
|
| 427 |
+
return True
|
| 428 |
+
for name in self.names:
|
| 429 |
+
nlen = self.lengths[name]
|
| 430 |
+
if name == record.name:
|
| 431 |
+
return True
|
| 432 |
+
elif record.name.find(name, 0, nlen) == 0 and record.name[nlen] == ".":
|
| 433 |
+
return True
|
| 434 |
+
return False
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
class CapturingLogHandler(logging.Handler):
|
| 438 |
+
def __init__(self, logger, level):
|
| 439 |
+
super(CapturingLogHandler, self).__init__(level=level)
|
| 440 |
+
self.records = []
|
| 441 |
+
if isinstance(logger, str):
|
| 442 |
+
self.logger = logging.getLogger(logger)
|
| 443 |
+
else:
|
| 444 |
+
self.logger = logger
|
| 445 |
+
|
| 446 |
+
def __enter__(self):
|
| 447 |
+
self.original_disabled = self.logger.disabled
|
| 448 |
+
self.original_level = self.logger.level
|
| 449 |
+
self.original_propagate = self.logger.propagate
|
| 450 |
+
|
| 451 |
+
self.logger.addHandler(self)
|
| 452 |
+
self.logger.setLevel(self.level)
|
| 453 |
+
self.logger.disabled = False
|
| 454 |
+
self.logger.propagate = False
|
| 455 |
+
|
| 456 |
+
return self
|
| 457 |
+
|
| 458 |
+
def __exit__(self, type, value, traceback):
|
| 459 |
+
self.logger.removeHandler(self)
|
| 460 |
+
self.logger.setLevel(self.original_level)
|
| 461 |
+
self.logger.disabled = self.original_disabled
|
| 462 |
+
self.logger.propagate = self.original_propagate
|
| 463 |
+
|
| 464 |
+
return self
|
| 465 |
+
|
| 466 |
+
def emit(self, record):
|
| 467 |
+
self.records.append(record)
|
| 468 |
+
|
| 469 |
+
def assertRegex(self, regexp, msg=None):
|
| 470 |
+
import re
|
| 471 |
+
|
| 472 |
+
pattern = re.compile(regexp)
|
| 473 |
+
for r in self.records:
|
| 474 |
+
if pattern.search(r.getMessage()):
|
| 475 |
+
return True
|
| 476 |
+
if msg is None:
|
| 477 |
+
msg = "Pattern '%s' not found in logger records" % regexp
|
| 478 |
+
assert 0, msg
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
class LogMixin(object):
|
| 482 |
+
"""Mixin class that adds logging functionality to another class.
|
| 483 |
+
|
| 484 |
+
You can define a new class that subclasses from ``LogMixin`` as well as
|
| 485 |
+
other base classes through multiple inheritance.
|
| 486 |
+
All instances of that class will have a ``log`` property that returns
|
| 487 |
+
a ``logging.Logger`` named after their respective ``<module>.<class>``.
|
| 488 |
+
|
| 489 |
+
For example:
|
| 490 |
+
|
| 491 |
+
>>> class BaseClass(object):
|
| 492 |
+
... pass
|
| 493 |
+
>>> class MyClass(LogMixin, BaseClass):
|
| 494 |
+
... pass
|
| 495 |
+
>>> a = MyClass()
|
| 496 |
+
>>> isinstance(a.log, logging.Logger)
|
| 497 |
+
True
|
| 498 |
+
>>> print(a.log.name)
|
| 499 |
+
fontTools.misc.loggingTools.MyClass
|
| 500 |
+
>>> class AnotherClass(MyClass):
|
| 501 |
+
... pass
|
| 502 |
+
>>> b = AnotherClass()
|
| 503 |
+
>>> isinstance(b.log, logging.Logger)
|
| 504 |
+
True
|
| 505 |
+
>>> print(b.log.name)
|
| 506 |
+
fontTools.misc.loggingTools.AnotherClass
|
| 507 |
+
"""
|
| 508 |
+
|
| 509 |
+
@property
|
| 510 |
+
def log(self):
|
| 511 |
+
if not hasattr(self, "_log"):
|
| 512 |
+
name = ".".join((self.__class__.__module__, self.__class__.__name__))
|
| 513 |
+
self._log = logging.getLogger(name)
|
| 514 |
+
return self._log
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def deprecateArgument(name, msg, category=UserWarning):
|
| 518 |
+
"""Raise a warning about deprecated function argument 'name'."""
|
| 519 |
+
warnings.warn("%r is deprecated; %s" % (name, msg), category=category, stacklevel=3)
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def deprecateFunction(msg, category=UserWarning):
|
| 523 |
+
"""Decorator to raise a warning when a deprecated function is called."""
|
| 524 |
+
|
| 525 |
+
def decorator(func):
|
| 526 |
+
@wraps(func)
|
| 527 |
+
def wrapper(*args, **kwargs):
|
| 528 |
+
warnings.warn(
|
| 529 |
+
"%r is deprecated; %s" % (func.__name__, msg),
|
| 530 |
+
category=category,
|
| 531 |
+
stacklevel=2,
|
| 532 |
+
)
|
| 533 |
+
return func(*args, **kwargs)
|
| 534 |
+
|
| 535 |
+
return wrapper
|
| 536 |
+
|
| 537 |
+
return decorator
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
if __name__ == "__main__":
|
| 541 |
+
import doctest
|
| 542 |
+
|
| 543 |
+
sys.exit(doctest.testmod(optionflags=doctest.ELLIPSIS).failed)
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/macRes.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from io import BytesIO
|
| 2 |
+
import struct
|
| 3 |
+
from fontTools.misc import sstruct
|
| 4 |
+
from fontTools.misc.textTools import bytesjoin, tostr
|
| 5 |
+
from collections import OrderedDict
|
| 6 |
+
from collections.abc import MutableMapping
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ResourceError(Exception):
|
| 10 |
+
pass
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ResourceReader(MutableMapping):
|
| 14 |
+
"""Reader for Mac OS resource forks.
|
| 15 |
+
|
| 16 |
+
Parses a resource fork and returns resources according to their type.
|
| 17 |
+
If run on OS X, this will open the resource fork in the filesystem.
|
| 18 |
+
Otherwise, it will open the file itself and attempt to read it as
|
| 19 |
+
though it were a resource fork.
|
| 20 |
+
|
| 21 |
+
The returned object can be indexed by type and iterated over,
|
| 22 |
+
returning in each case a list of py:class:`Resource` objects
|
| 23 |
+
representing all the resources of a certain type.
|
| 24 |
+
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, fileOrPath):
|
| 28 |
+
"""Open a file
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
fileOrPath: Either an object supporting a ``read`` method, an
|
| 32 |
+
``os.PathLike`` object, or a string.
|
| 33 |
+
"""
|
| 34 |
+
self._resources = OrderedDict()
|
| 35 |
+
if hasattr(fileOrPath, "read"):
|
| 36 |
+
self.file = fileOrPath
|
| 37 |
+
else:
|
| 38 |
+
try:
|
| 39 |
+
# try reading from the resource fork (only works on OS X)
|
| 40 |
+
self.file = self.openResourceFork(fileOrPath)
|
| 41 |
+
self._readFile()
|
| 42 |
+
return
|
| 43 |
+
except (ResourceError, IOError):
|
| 44 |
+
# if it fails, use the data fork
|
| 45 |
+
self.file = self.openDataFork(fileOrPath)
|
| 46 |
+
self._readFile()
|
| 47 |
+
|
| 48 |
+
@staticmethod
|
| 49 |
+
def openResourceFork(path):
|
| 50 |
+
if hasattr(path, "__fspath__"): # support os.PathLike objects
|
| 51 |
+
path = path.__fspath__()
|
| 52 |
+
with open(path + "/..namedfork/rsrc", "rb") as resfork:
|
| 53 |
+
data = resfork.read()
|
| 54 |
+
infile = BytesIO(data)
|
| 55 |
+
infile.name = path
|
| 56 |
+
return infile
|
| 57 |
+
|
| 58 |
+
@staticmethod
|
| 59 |
+
def openDataFork(path):
|
| 60 |
+
with open(path, "rb") as datafork:
|
| 61 |
+
data = datafork.read()
|
| 62 |
+
infile = BytesIO(data)
|
| 63 |
+
infile.name = path
|
| 64 |
+
return infile
|
| 65 |
+
|
| 66 |
+
def _readFile(self):
|
| 67 |
+
self._readHeaderAndMap()
|
| 68 |
+
self._readTypeList()
|
| 69 |
+
|
| 70 |
+
def _read(self, numBytes, offset=None):
|
| 71 |
+
if offset is not None:
|
| 72 |
+
try:
|
| 73 |
+
self.file.seek(offset)
|
| 74 |
+
except OverflowError:
|
| 75 |
+
raise ResourceError("Failed to seek offset ('offset' is too large)")
|
| 76 |
+
if self.file.tell() != offset:
|
| 77 |
+
raise ResourceError("Failed to seek offset (reached EOF)")
|
| 78 |
+
try:
|
| 79 |
+
data = self.file.read(numBytes)
|
| 80 |
+
except OverflowError:
|
| 81 |
+
raise ResourceError("Cannot read resource ('numBytes' is too large)")
|
| 82 |
+
if len(data) != numBytes:
|
| 83 |
+
raise ResourceError("Cannot read resource (not enough data)")
|
| 84 |
+
return data
|
| 85 |
+
|
| 86 |
+
def _readHeaderAndMap(self):
|
| 87 |
+
self.file.seek(0)
|
| 88 |
+
headerData = self._read(ResourceForkHeaderSize)
|
| 89 |
+
sstruct.unpack(ResourceForkHeader, headerData, self)
|
| 90 |
+
# seek to resource map, skip reserved
|
| 91 |
+
mapOffset = self.mapOffset + 22
|
| 92 |
+
resourceMapData = self._read(ResourceMapHeaderSize, mapOffset)
|
| 93 |
+
sstruct.unpack(ResourceMapHeader, resourceMapData, self)
|
| 94 |
+
self.absTypeListOffset = self.mapOffset + self.typeListOffset
|
| 95 |
+
self.absNameListOffset = self.mapOffset + self.nameListOffset
|
| 96 |
+
|
| 97 |
+
def _readTypeList(self):
|
| 98 |
+
absTypeListOffset = self.absTypeListOffset
|
| 99 |
+
numTypesData = self._read(2, absTypeListOffset)
|
| 100 |
+
(self.numTypes,) = struct.unpack(">H", numTypesData)
|
| 101 |
+
absTypeListOffset2 = absTypeListOffset + 2
|
| 102 |
+
for i in range(self.numTypes + 1):
|
| 103 |
+
resTypeItemOffset = absTypeListOffset2 + ResourceTypeItemSize * i
|
| 104 |
+
resTypeItemData = self._read(ResourceTypeItemSize, resTypeItemOffset)
|
| 105 |
+
item = sstruct.unpack(ResourceTypeItem, resTypeItemData)
|
| 106 |
+
resType = tostr(item["type"], encoding="mac-roman")
|
| 107 |
+
refListOffset = absTypeListOffset + item["refListOffset"]
|
| 108 |
+
numRes = item["numRes"] + 1
|
| 109 |
+
resources = self._readReferenceList(resType, refListOffset, numRes)
|
| 110 |
+
self._resources[resType] = resources
|
| 111 |
+
|
| 112 |
+
def _readReferenceList(self, resType, refListOffset, numRes):
|
| 113 |
+
resources = []
|
| 114 |
+
for i in range(numRes):
|
| 115 |
+
refOffset = refListOffset + ResourceRefItemSize * i
|
| 116 |
+
refData = self._read(ResourceRefItemSize, refOffset)
|
| 117 |
+
res = Resource(resType)
|
| 118 |
+
res.decompile(refData, self)
|
| 119 |
+
resources.append(res)
|
| 120 |
+
return resources
|
| 121 |
+
|
| 122 |
+
def __getitem__(self, resType):
|
| 123 |
+
return self._resources[resType]
|
| 124 |
+
|
| 125 |
+
def __delitem__(self, resType):
|
| 126 |
+
del self._resources[resType]
|
| 127 |
+
|
| 128 |
+
def __setitem__(self, resType, resources):
|
| 129 |
+
self._resources[resType] = resources
|
| 130 |
+
|
| 131 |
+
def __len__(self):
|
| 132 |
+
return len(self._resources)
|
| 133 |
+
|
| 134 |
+
def __iter__(self):
|
| 135 |
+
return iter(self._resources)
|
| 136 |
+
|
| 137 |
+
def keys(self):
|
| 138 |
+
return self._resources.keys()
|
| 139 |
+
|
| 140 |
+
@property
|
| 141 |
+
def types(self):
|
| 142 |
+
"""A list of the types of resources in the resource fork."""
|
| 143 |
+
return list(self._resources.keys())
|
| 144 |
+
|
| 145 |
+
def countResources(self, resType):
|
| 146 |
+
"""Return the number of resources of a given type."""
|
| 147 |
+
try:
|
| 148 |
+
return len(self[resType])
|
| 149 |
+
except KeyError:
|
| 150 |
+
return 0
|
| 151 |
+
|
| 152 |
+
def getIndices(self, resType):
|
| 153 |
+
"""Returns a list of indices of resources of a given type."""
|
| 154 |
+
numRes = self.countResources(resType)
|
| 155 |
+
if numRes:
|
| 156 |
+
return list(range(1, numRes + 1))
|
| 157 |
+
else:
|
| 158 |
+
return []
|
| 159 |
+
|
| 160 |
+
def getNames(self, resType):
|
| 161 |
+
"""Return list of names of all resources of a given type."""
|
| 162 |
+
return [res.name for res in self.get(resType, []) if res.name is not None]
|
| 163 |
+
|
| 164 |
+
def getIndResource(self, resType, index):
|
| 165 |
+
"""Return resource of given type located at an index ranging from 1
|
| 166 |
+
to the number of resources for that type, or None if not found.
|
| 167 |
+
"""
|
| 168 |
+
if index < 1:
|
| 169 |
+
return None
|
| 170 |
+
try:
|
| 171 |
+
res = self[resType][index - 1]
|
| 172 |
+
except (KeyError, IndexError):
|
| 173 |
+
return None
|
| 174 |
+
return res
|
| 175 |
+
|
| 176 |
+
def getNamedResource(self, resType, name):
|
| 177 |
+
"""Return the named resource of given type, else return None."""
|
| 178 |
+
name = tostr(name, encoding="mac-roman")
|
| 179 |
+
for res in self.get(resType, []):
|
| 180 |
+
if res.name == name:
|
| 181 |
+
return res
|
| 182 |
+
return None
|
| 183 |
+
|
| 184 |
+
def close(self):
|
| 185 |
+
if not self.file.closed:
|
| 186 |
+
self.file.close()
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class Resource(object):
|
| 190 |
+
"""Represents a resource stored within a resource fork.
|
| 191 |
+
|
| 192 |
+
Attributes:
|
| 193 |
+
type: resource type.
|
| 194 |
+
data: resource data.
|
| 195 |
+
id: ID.
|
| 196 |
+
name: resource name.
|
| 197 |
+
attr: attributes.
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
def __init__(
|
| 201 |
+
self, resType=None, resData=None, resID=None, resName=None, resAttr=None
|
| 202 |
+
):
|
| 203 |
+
self.type = resType
|
| 204 |
+
self.data = resData
|
| 205 |
+
self.id = resID
|
| 206 |
+
self.name = resName
|
| 207 |
+
self.attr = resAttr
|
| 208 |
+
|
| 209 |
+
def decompile(self, refData, reader):
|
| 210 |
+
sstruct.unpack(ResourceRefItem, refData, self)
|
| 211 |
+
# interpret 3-byte dataOffset as (padded) ULONG to unpack it with struct
|
| 212 |
+
(self.dataOffset,) = struct.unpack(">L", bytesjoin([b"\0", self.dataOffset]))
|
| 213 |
+
absDataOffset = reader.dataOffset + self.dataOffset
|
| 214 |
+
(dataLength,) = struct.unpack(">L", reader._read(4, absDataOffset))
|
| 215 |
+
self.data = reader._read(dataLength)
|
| 216 |
+
if self.nameOffset == -1:
|
| 217 |
+
return
|
| 218 |
+
absNameOffset = reader.absNameListOffset + self.nameOffset
|
| 219 |
+
(nameLength,) = struct.unpack("B", reader._read(1, absNameOffset))
|
| 220 |
+
(name,) = struct.unpack(">%ss" % nameLength, reader._read(nameLength))
|
| 221 |
+
self.name = tostr(name, encoding="mac-roman")
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
ResourceForkHeader = """
|
| 225 |
+
> # big endian
|
| 226 |
+
dataOffset: L
|
| 227 |
+
mapOffset: L
|
| 228 |
+
dataLen: L
|
| 229 |
+
mapLen: L
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
ResourceForkHeaderSize = sstruct.calcsize(ResourceForkHeader)
|
| 233 |
+
|
| 234 |
+
ResourceMapHeader = """
|
| 235 |
+
> # big endian
|
| 236 |
+
attr: H
|
| 237 |
+
typeListOffset: H
|
| 238 |
+
nameListOffset: H
|
| 239 |
+
"""
|
| 240 |
+
|
| 241 |
+
ResourceMapHeaderSize = sstruct.calcsize(ResourceMapHeader)
|
| 242 |
+
|
| 243 |
+
ResourceTypeItem = """
|
| 244 |
+
> # big endian
|
| 245 |
+
type: 4s
|
| 246 |
+
numRes: H
|
| 247 |
+
refListOffset: H
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
ResourceTypeItemSize = sstruct.calcsize(ResourceTypeItem)
|
| 251 |
+
|
| 252 |
+
ResourceRefItem = """
|
| 253 |
+
> # big endian
|
| 254 |
+
id: h
|
| 255 |
+
nameOffset: h
|
| 256 |
+
attr: B
|
| 257 |
+
dataOffset: 3s
|
| 258 |
+
reserved: L
|
| 259 |
+
"""
|
| 260 |
+
|
| 261 |
+
ResourceRefItemSize = sstruct.calcsize(ResourceRefItem)
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/plistlib/py.typed
ADDED
|
File without changes
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/psCharStrings.py
ADDED
|
@@ -0,0 +1,1496 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ings:
|
| 2 |
+
CFF dictionary data and Type1/Type2 CharStrings.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from fontTools.misc.fixedTools import (
|
| 6 |
+
fixedToFloat,
|
| 7 |
+
floatToFixed,
|
| 8 |
+
floatToFixedToStr,
|
| 9 |
+
strToFixedToFloat,
|
| 10 |
+
)
|
| 11 |
+
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
|
| 12 |
+
from fontTools.pens.boundsPen import BoundsPen
|
| 13 |
+
import struct
|
| 14 |
+
import logging
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
log = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def read_operator(self, b0, data, index):
|
| 21 |
+
if b0 == 12:
|
| 22 |
+
op = (b0, byteord(data[index]))
|
| 23 |
+
index = index + 1
|
| 24 |
+
else:
|
| 25 |
+
op = b0
|
| 26 |
+
try:
|
| 27 |
+
operator = self.operators[op]
|
| 28 |
+
except KeyError:
|
| 29 |
+
return None, index
|
| 30 |
+
value = self.handle_operator(operator)
|
| 31 |
+
return value, index
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def read_byte(self, b0, data, index):
|
| 35 |
+
return b0 - 139, index
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def read_smallInt1(self, b0, data, index):
|
| 39 |
+
b1 = byteord(data[index])
|
| 40 |
+
return (b0 - 247) * 256 + b1 + 108, index + 1
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def read_smallInt2(self, b0, data, index):
|
| 44 |
+
b1 = byteord(data[index])
|
| 45 |
+
return -(b0 - 251) * 256 - b1 - 108, index + 1
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def read_shortInt(self, b0, data, index):
|
| 49 |
+
(value,) = struct.unpack(">h", data[index : index + 2])
|
| 50 |
+
return value, index + 2
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def read_longInt(self, b0, data, index):
|
| 54 |
+
(value,) = struct.unpack(">l", data[index : index + 4])
|
| 55 |
+
return value, index + 4
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def read_fixed1616(self, b0, data, index):
|
| 59 |
+
(value,) = struct.unpack(">l", data[index : index + 4])
|
| 60 |
+
return fixedToFloat(value, precisionBits=16), index + 4
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def read_reserved(self, b0, data, index):
|
| 64 |
+
assert NotImplementedError
|
| 65 |
+
return NotImplemented, index
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def read_realNumber(self, b0, data, index):
|
| 69 |
+
number = ""
|
| 70 |
+
while True:
|
| 71 |
+
b = byteord(data[index])
|
| 72 |
+
index = index + 1
|
| 73 |
+
nibble0 = (b & 0xF0) >> 4
|
| 74 |
+
nibble1 = b & 0x0F
|
| 75 |
+
if nibble0 == 0xF:
|
| 76 |
+
break
|
| 77 |
+
number = number + realNibbles[nibble0]
|
| 78 |
+
if nibble1 == 0xF:
|
| 79 |
+
break
|
| 80 |
+
number = number + realNibbles[nibble1]
|
| 81 |
+
return float(number), index
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
t1OperandEncoding = [None] * 256
|
| 85 |
+
t1OperandEncoding[0:32] = (32) * [read_operator]
|
| 86 |
+
t1OperandEncoding[32:247] = (247 - 32) * [read_byte]
|
| 87 |
+
t1OperandEncoding[247:251] = (251 - 247) * [read_smallInt1]
|
| 88 |
+
t1OperandEncoding[251:255] = (255 - 251) * [read_smallInt2]
|
| 89 |
+
t1OperandEncoding[255] = read_longInt
|
| 90 |
+
assert len(t1OperandEncoding) == 256
|
| 91 |
+
|
| 92 |
+
t2OperandEncoding = t1OperandEncoding[:]
|
| 93 |
+
t2OperandEncoding[28] = read_shortInt
|
| 94 |
+
t2OperandEncoding[255] = read_fixed1616
|
| 95 |
+
|
| 96 |
+
cffDictOperandEncoding = t2OperandEncoding[:]
|
| 97 |
+
cffDictOperandEncoding[29] = read_longInt
|
| 98 |
+
cffDictOperandEncoding[30] = read_realNumber
|
| 99 |
+
cffDictOperandEncoding[255] = read_reserved
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
realNibbles = [
|
| 103 |
+
"0",
|
| 104 |
+
"1",
|
| 105 |
+
"2",
|
| 106 |
+
"3",
|
| 107 |
+
"4",
|
| 108 |
+
"5",
|
| 109 |
+
"6",
|
| 110 |
+
"7",
|
| 111 |
+
"8",
|
| 112 |
+
"9",
|
| 113 |
+
".",
|
| 114 |
+
"E",
|
| 115 |
+
"E-",
|
| 116 |
+
None,
|
| 117 |
+
"-",
|
| 118 |
+
]
|
| 119 |
+
realNibblesDict = {v: i for i, v in enumerate(realNibbles)}
|
| 120 |
+
|
| 121 |
+
maxOpStack = 193
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def buildOperatorDict(operatorList):
|
| 125 |
+
oper = {}
|
| 126 |
+
opc = {}
|
| 127 |
+
for item in operatorList:
|
| 128 |
+
if len(item) == 2:
|
| 129 |
+
oper[item[0]] = item[1]
|
| 130 |
+
else:
|
| 131 |
+
oper[item[0]] = item[1:]
|
| 132 |
+
if isinstance(item[0], tuple):
|
| 133 |
+
opc[item[1]] = item[0]
|
| 134 |
+
else:
|
| 135 |
+
opc[item[1]] = (item[0],)
|
| 136 |
+
return oper, opc
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
t2Operators = [
|
| 140 |
+
# opcode name
|
| 141 |
+
(1, "hstem"),
|
| 142 |
+
(3, "vstem"),
|
| 143 |
+
(4, "vmoveto"),
|
| 144 |
+
(5, "rlineto"),
|
| 145 |
+
(6, "hlineto"),
|
| 146 |
+
(7, "vlineto"),
|
| 147 |
+
(8, "rrcurveto"),
|
| 148 |
+
(10, "callsubr"),
|
| 149 |
+
(11, "return"),
|
| 150 |
+
(14, "endchar"),
|
| 151 |
+
(15, "vsindex"),
|
| 152 |
+
(16, "blend"),
|
| 153 |
+
(18, "hstemhm"),
|
| 154 |
+
(19, "hintmask"),
|
| 155 |
+
(20, "cntrmask"),
|
| 156 |
+
(21, "rmoveto"),
|
| 157 |
+
(22, "hmoveto"),
|
| 158 |
+
(23, "vstemhm"),
|
| 159 |
+
(24, "rcurveline"),
|
| 160 |
+
(25, "rlinecurve"),
|
| 161 |
+
(26, "vvcurveto"),
|
| 162 |
+
(27, "hhcurveto"),
|
| 163 |
+
# (28, 'shortint'), # not really an operator
|
| 164 |
+
(29, "callgsubr"),
|
| 165 |
+
(30, "vhcurveto"),
|
| 166 |
+
(31, "hvcurveto"),
|
| 167 |
+
((12, 0), "ignore"), # dotsection. Yes, there a few very early OTF/CFF
|
| 168 |
+
# fonts with this deprecated operator. Just ignore it.
|
| 169 |
+
((12, 3), "and"),
|
| 170 |
+
((12, 4), "or"),
|
| 171 |
+
((12, 5), "not"),
|
| 172 |
+
((12, 8), "store"),
|
| 173 |
+
((12, 9), "abs"),
|
| 174 |
+
((12, 10), "add"),
|
| 175 |
+
((12, 11), "sub"),
|
| 176 |
+
((12, 12), "div"),
|
| 177 |
+
((12, 13), "load"),
|
| 178 |
+
((12, 14), "neg"),
|
| 179 |
+
((12, 15), "eq"),
|
| 180 |
+
((12, 18), "drop"),
|
| 181 |
+
((12, 20), "put"),
|
| 182 |
+
((12, 21), "get"),
|
| 183 |
+
((12, 22), "ifelse"),
|
| 184 |
+
((12, 23), "random"),
|
| 185 |
+
((12, 24), "mul"),
|
| 186 |
+
((12, 26), "sqrt"),
|
| 187 |
+
((12, 27), "dup"),
|
| 188 |
+
((12, 28), "exch"),
|
| 189 |
+
((12, 29), "index"),
|
| 190 |
+
((12, 30), "roll"),
|
| 191 |
+
((12, 34), "hflex"),
|
| 192 |
+
((12, 35), "flex"),
|
| 193 |
+
((12, 36), "hflex1"),
|
| 194 |
+
((12, 37), "flex1"),
|
| 195 |
+
]
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def getIntEncoder(format):
|
| 199 |
+
if format == "cff":
|
| 200 |
+
twoByteOp = bytechr(28)
|
| 201 |
+
fourByteOp = bytechr(29)
|
| 202 |
+
elif format == "t1":
|
| 203 |
+
twoByteOp = None
|
| 204 |
+
fourByteOp = bytechr(255)
|
| 205 |
+
else:
|
| 206 |
+
assert format == "t2"
|
| 207 |
+
twoByteOp = bytechr(28)
|
| 208 |
+
fourByteOp = None
|
| 209 |
+
|
| 210 |
+
def encodeInt(
|
| 211 |
+
value,
|
| 212 |
+
fourByteOp=fourByteOp,
|
| 213 |
+
bytechr=bytechr,
|
| 214 |
+
pack=struct.pack,
|
| 215 |
+
unpack=struct.unpack,
|
| 216 |
+
twoByteOp=twoByteOp,
|
| 217 |
+
):
|
| 218 |
+
if -107 <= value <= 107:
|
| 219 |
+
code = bytechr(value + 139)
|
| 220 |
+
elif 108 <= value <= 1131:
|
| 221 |
+
value = value - 108
|
| 222 |
+
code = bytechr((value >> 8) + 247) + bytechr(value & 0xFF)
|
| 223 |
+
elif -1131 <= value <= -108:
|
| 224 |
+
value = -value - 108
|
| 225 |
+
code = bytechr((value >> 8) + 251) + bytechr(value & 0xFF)
|
| 226 |
+
elif twoByteOp is not None and -32768 <= value <= 32767:
|
| 227 |
+
code = twoByteOp + pack(">h", value)
|
| 228 |
+
elif fourByteOp is None:
|
| 229 |
+
# Backwards compatible hack: due to a previous bug in FontTools,
|
| 230 |
+
# 16.16 fixed numbers were written out as 4-byte ints. When
|
| 231 |
+
# these numbers were small, they were wrongly written back as
|
| 232 |
+
# small ints instead of 4-byte ints, breaking round-tripping.
|
| 233 |
+
# This here workaround doesn't do it any better, since we can't
|
| 234 |
+
# distinguish anymore between small ints that were supposed to
|
| 235 |
+
# be small fixed numbers and small ints that were just small
|
| 236 |
+
# ints. Hence the warning.
|
| 237 |
+
log.warning(
|
| 238 |
+
"4-byte T2 number got passed to the "
|
| 239 |
+
"IntType handler. This should happen only when reading in "
|
| 240 |
+
"old XML files.\n"
|
| 241 |
+
)
|
| 242 |
+
code = bytechr(255) + pack(">l", value)
|
| 243 |
+
else:
|
| 244 |
+
code = fourByteOp + pack(">l", value)
|
| 245 |
+
return code
|
| 246 |
+
|
| 247 |
+
return encodeInt
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
encodeIntCFF = getIntEncoder("cff")
|
| 251 |
+
encodeIntT1 = getIntEncoder("t1")
|
| 252 |
+
encodeIntT2 = getIntEncoder("t2")
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def encodeFixed(f, pack=struct.pack):
|
| 256 |
+
"""For T2 only"""
|
| 257 |
+
value = floatToFixed(f, precisionBits=16)
|
| 258 |
+
if value & 0xFFFF == 0: # check if the fractional part is zero
|
| 259 |
+
return encodeIntT2(value >> 16) # encode only the integer part
|
| 260 |
+
else:
|
| 261 |
+
return b"\xff" + pack(">l", value) # encode the entire fixed point value
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
realZeroBytes = bytechr(30) + bytechr(0xF)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def encodeFloat(f):
|
| 268 |
+
# For CFF only, used in cffLib
|
| 269 |
+
if f == 0.0: # 0.0 == +0.0 == -0.0
|
| 270 |
+
return realZeroBytes
|
| 271 |
+
# Note: 14 decimal digits seems to be the limitation for CFF real numbers
|
| 272 |
+
# in macOS. However, we use 8 here to match the implementation of AFDKO.
|
| 273 |
+
s = "%.8G" % f
|
| 274 |
+
if s[:2] == "0.":
|
| 275 |
+
s = s[1:]
|
| 276 |
+
elif s[:3] == "-0.":
|
| 277 |
+
s = "-" + s[2:]
|
| 278 |
+
elif s.endswith("000"):
|
| 279 |
+
significantDigits = s.rstrip("0")
|
| 280 |
+
s = "%sE%d" % (significantDigits, len(s) - len(significantDigits))
|
| 281 |
+
else:
|
| 282 |
+
dotIndex = s.find(".")
|
| 283 |
+
eIndex = s.find("E")
|
| 284 |
+
if dotIndex != -1 and eIndex != -1:
|
| 285 |
+
integerPart = s[:dotIndex]
|
| 286 |
+
fractionalPart = s[dotIndex + 1 : eIndex]
|
| 287 |
+
exponent = int(s[eIndex + 1 :])
|
| 288 |
+
newExponent = exponent - len(fractionalPart)
|
| 289 |
+
if newExponent == 1:
|
| 290 |
+
s = "%s%s0" % (integerPart, fractionalPart)
|
| 291 |
+
else:
|
| 292 |
+
s = "%s%sE%d" % (integerPart, fractionalPart, newExponent)
|
| 293 |
+
if s.startswith((".0", "-.0")):
|
| 294 |
+
sign, s = s.split(".", 1)
|
| 295 |
+
s = "%s%sE-%d" % (sign, s.lstrip("0"), len(s))
|
| 296 |
+
nibbles = []
|
| 297 |
+
while s:
|
| 298 |
+
c = s[0]
|
| 299 |
+
s = s[1:]
|
| 300 |
+
if c == "E":
|
| 301 |
+
c2 = s[:1]
|
| 302 |
+
if c2 == "-":
|
| 303 |
+
s = s[1:]
|
| 304 |
+
c = "E-"
|
| 305 |
+
elif c2 == "+":
|
| 306 |
+
s = s[1:]
|
| 307 |
+
if s.startswith("0"):
|
| 308 |
+
s = s[1:]
|
| 309 |
+
nibbles.append(realNibblesDict[c])
|
| 310 |
+
nibbles.append(0xF)
|
| 311 |
+
if len(nibbles) % 2:
|
| 312 |
+
nibbles.append(0xF)
|
| 313 |
+
d = bytechr(30)
|
| 314 |
+
for i in range(0, len(nibbles), 2):
|
| 315 |
+
d = d + bytechr(nibbles[i] << 4 | nibbles[i + 1])
|
| 316 |
+
return d
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class CharStringCompileError(Exception):
|
| 320 |
+
pass
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class SimpleT2Decompiler(object):
|
| 324 |
+
def __init__(self, localSubrs, globalSubrs, private=None, blender=None):
|
| 325 |
+
self.localSubrs = localSubrs
|
| 326 |
+
self.localBias = calcSubrBias(localSubrs)
|
| 327 |
+
self.globalSubrs = globalSubrs
|
| 328 |
+
self.globalBias = calcSubrBias(globalSubrs)
|
| 329 |
+
self.private = private
|
| 330 |
+
self.blender = blender
|
| 331 |
+
self.reset()
|
| 332 |
+
|
| 333 |
+
def reset(self):
|
| 334 |
+
self.callingStack = []
|
| 335 |
+
self.operandStack = []
|
| 336 |
+
self.hintCount = 0
|
| 337 |
+
self.hintMaskBytes = 0
|
| 338 |
+
self.numRegions = 0
|
| 339 |
+
self.vsIndex = 0
|
| 340 |
+
|
| 341 |
+
def execute(self, charString):
|
| 342 |
+
self.callingStack.append(charString)
|
| 343 |
+
needsDecompilation = charString.needsDecompilation()
|
| 344 |
+
if needsDecompilation:
|
| 345 |
+
program = []
|
| 346 |
+
pushToProgram = program.append
|
| 347 |
+
else:
|
| 348 |
+
pushToProgram = lambda x: None
|
| 349 |
+
pushToStack = self.operandStack.append
|
| 350 |
+
index = 0
|
| 351 |
+
while True:
|
| 352 |
+
token, isOperator, index = charString.getToken(index)
|
| 353 |
+
if token is None:
|
| 354 |
+
break # we're done!
|
| 355 |
+
pushToProgram(token)
|
| 356 |
+
if isOperator:
|
| 357 |
+
handlerName = "op_" + token
|
| 358 |
+
handler = getattr(self, handlerName, None)
|
| 359 |
+
if handler is not None:
|
| 360 |
+
rv = handler(index)
|
| 361 |
+
if rv:
|
| 362 |
+
hintMaskBytes, index = rv
|
| 363 |
+
pushToProgram(hintMaskBytes)
|
| 364 |
+
else:
|
| 365 |
+
self.popall()
|
| 366 |
+
else:
|
| 367 |
+
pushToStack(token)
|
| 368 |
+
if needsDecompilation:
|
| 369 |
+
charString.setProgram(program)
|
| 370 |
+
del self.callingStack[-1]
|
| 371 |
+
|
| 372 |
+
def pop(self):
|
| 373 |
+
value = self.operandStack[-1]
|
| 374 |
+
del self.operandStack[-1]
|
| 375 |
+
return value
|
| 376 |
+
|
| 377 |
+
def popall(self):
|
| 378 |
+
stack = self.operandStack[:]
|
| 379 |
+
self.operandStack[:] = []
|
| 380 |
+
return stack
|
| 381 |
+
|
| 382 |
+
def push(self, value):
|
| 383 |
+
self.operandStack.append(value)
|
| 384 |
+
|
| 385 |
+
def op_return(self, index):
|
| 386 |
+
if self.operandStack:
|
| 387 |
+
pass
|
| 388 |
+
|
| 389 |
+
def op_endchar(self, index):
|
| 390 |
+
pass
|
| 391 |
+
|
| 392 |
+
def op_ignore(self, index):
|
| 393 |
+
pass
|
| 394 |
+
|
| 395 |
+
def op_callsubr(self, index):
|
| 396 |
+
subrIndex = self.pop()
|
| 397 |
+
subr = self.localSubrs[subrIndex + self.localBias]
|
| 398 |
+
self.execute(subr)
|
| 399 |
+
|
| 400 |
+
def op_callgsubr(self, index):
|
| 401 |
+
subrIndex = self.pop()
|
| 402 |
+
subr = self.globalSubrs[subrIndex + self.globalBias]
|
| 403 |
+
self.execute(subr)
|
| 404 |
+
|
| 405 |
+
def op_hstem(self, index):
|
| 406 |
+
self.countHints()
|
| 407 |
+
|
| 408 |
+
def op_vstem(self, index):
|
| 409 |
+
self.countHints()
|
| 410 |
+
|
| 411 |
+
def op_hstemhm(self, index):
|
| 412 |
+
self.countHints()
|
| 413 |
+
|
| 414 |
+
def op_vstemhm(self, index):
|
| 415 |
+
self.countHints()
|
| 416 |
+
|
| 417 |
+
def op_hintmask(self, index):
|
| 418 |
+
if not self.hintMaskBytes:
|
| 419 |
+
self.countHints()
|
| 420 |
+
self.hintMaskBytes = (self.hintCount + 7) // 8
|
| 421 |
+
hintMaskBytes, index = self.callingStack[-1].getBytes(index, self.hintMaskBytes)
|
| 422 |
+
return hintMaskBytes, index
|
| 423 |
+
|
| 424 |
+
op_cntrmask = op_hintmask
|
| 425 |
+
|
| 426 |
+
def countHints(self):
|
| 427 |
+
args = self.popall()
|
| 428 |
+
self.hintCount = self.hintCount + len(args) // 2
|
| 429 |
+
|
| 430 |
+
# misc
|
| 431 |
+
def op_and(self, index):
|
| 432 |
+
raise NotImplementedError
|
| 433 |
+
|
| 434 |
+
def op_or(self, index):
|
| 435 |
+
raise NotImplementedError
|
| 436 |
+
|
| 437 |
+
def op_not(self, index):
|
| 438 |
+
raise NotImplementedError
|
| 439 |
+
|
| 440 |
+
def op_store(self, index):
|
| 441 |
+
raise NotImplementedError
|
| 442 |
+
|
| 443 |
+
def op_abs(self, index):
|
| 444 |
+
raise NotImplementedError
|
| 445 |
+
|
| 446 |
+
def op_add(self, index):
|
| 447 |
+
raise NotImplementedError
|
| 448 |
+
|
| 449 |
+
def op_sub(self, index):
|
| 450 |
+
raise NotImplementedError
|
| 451 |
+
|
| 452 |
+
def op_div(self, index):
|
| 453 |
+
raise NotImplementedError
|
| 454 |
+
|
| 455 |
+
def op_load(self, index):
|
| 456 |
+
raise NotImplementedError
|
| 457 |
+
|
| 458 |
+
def op_neg(self, index):
|
| 459 |
+
raise NotImplementedError
|
| 460 |
+
|
| 461 |
+
def op_eq(self, index):
|
| 462 |
+
raise NotImplementedError
|
| 463 |
+
|
| 464 |
+
def op_drop(self, index):
|
| 465 |
+
raise NotImplementedError
|
| 466 |
+
|
| 467 |
+
def op_put(self, index):
|
| 468 |
+
raise NotImplementedError
|
| 469 |
+
|
| 470 |
+
def op_get(self, index):
|
| 471 |
+
raise NotImplementedError
|
| 472 |
+
|
| 473 |
+
def op_ifelse(self, index):
|
| 474 |
+
raise NotImplementedError
|
| 475 |
+
|
| 476 |
+
def op_random(self, index):
|
| 477 |
+
raise NotImplementedError
|
| 478 |
+
|
| 479 |
+
def op_mul(self, index):
|
| 480 |
+
raise NotImplementedError
|
| 481 |
+
|
| 482 |
+
def op_sqrt(self, index):
|
| 483 |
+
raise NotImplementedError
|
| 484 |
+
|
| 485 |
+
def op_dup(self, index):
|
| 486 |
+
raise NotImplementedError
|
| 487 |
+
|
| 488 |
+
def op_exch(self, index):
|
| 489 |
+
raise NotImplementedError
|
| 490 |
+
|
| 491 |
+
def op_index(self, index):
|
| 492 |
+
raise NotImplementedError
|
| 493 |
+
|
| 494 |
+
def op_roll(self, index):
|
| 495 |
+
raise NotImplementedError
|
| 496 |
+
|
| 497 |
+
def op_blend(self, index):
|
| 498 |
+
if self.numRegions == 0:
|
| 499 |
+
self.numRegions = self.private.getNumRegions()
|
| 500 |
+
numBlends = self.pop()
|
| 501 |
+
numOps = numBlends * (self.numRegions + 1)
|
| 502 |
+
if self.blender is None:
|
| 503 |
+
del self.operandStack[
|
| 504 |
+
-(numOps - numBlends) :
|
| 505 |
+
] # Leave the default operands on the stack.
|
| 506 |
+
else:
|
| 507 |
+
argi = len(self.operandStack) - numOps
|
| 508 |
+
end_args = tuplei = argi + numBlends
|
| 509 |
+
while argi < end_args:
|
| 510 |
+
next_ti = tuplei + self.numRegions
|
| 511 |
+
deltas = self.operandStack[tuplei:next_ti]
|
| 512 |
+
delta = self.blender(self.vsIndex, deltas)
|
| 513 |
+
self.operandStack[argi] += delta
|
| 514 |
+
tuplei = next_ti
|
| 515 |
+
argi += 1
|
| 516 |
+
self.operandStack[end_args:] = []
|
| 517 |
+
|
| 518 |
+
def op_vsindex(self, index):
|
| 519 |
+
vi = self.pop()
|
| 520 |
+
self.vsIndex = vi
|
| 521 |
+
self.numRegions = self.private.getNumRegions(vi)
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
t1Operators = [
|
| 525 |
+
# opcode name
|
| 526 |
+
(1, "hstem"),
|
| 527 |
+
(3, "vstem"),
|
| 528 |
+
(4, "vmoveto"),
|
| 529 |
+
(5, "rlineto"),
|
| 530 |
+
(6, "hlineto"),
|
| 531 |
+
(7, "vlineto"),
|
| 532 |
+
(8, "rrcurveto"),
|
| 533 |
+
(9, "closepath"),
|
| 534 |
+
(10, "callsubr"),
|
| 535 |
+
(11, "return"),
|
| 536 |
+
(13, "hsbw"),
|
| 537 |
+
(14, "endchar"),
|
| 538 |
+
(21, "rmoveto"),
|
| 539 |
+
(22, "hmoveto"),
|
| 540 |
+
(30, "vhcurveto"),
|
| 541 |
+
(31, "hvcurveto"),
|
| 542 |
+
((12, 0), "dotsection"),
|
| 543 |
+
((12, 1), "vstem3"),
|
| 544 |
+
((12, 2), "hstem3"),
|
| 545 |
+
((12, 6), "seac"),
|
| 546 |
+
((12, 7), "sbw"),
|
| 547 |
+
((12, 12), "div"),
|
| 548 |
+
((12, 16), "callothersubr"),
|
| 549 |
+
((12, 17), "pop"),
|
| 550 |
+
((12, 33), "setcurrentpoint"),
|
| 551 |
+
]
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
class T2WidthExtractor(SimpleT2Decompiler):
|
| 555 |
+
def __init__(
|
| 556 |
+
self,
|
| 557 |
+
localSubrs,
|
| 558 |
+
globalSubrs,
|
| 559 |
+
nominalWidthX,
|
| 560 |
+
defaultWidthX,
|
| 561 |
+
private=None,
|
| 562 |
+
blender=None,
|
| 563 |
+
):
|
| 564 |
+
SimpleT2Decompiler.__init__(self, localSubrs, globalSubrs, private, blender)
|
| 565 |
+
self.nominalWidthX = nominalWidthX
|
| 566 |
+
self.defaultWidthX = defaultWidthX
|
| 567 |
+
|
| 568 |
+
def reset(self):
|
| 569 |
+
SimpleT2Decompiler.reset(self)
|
| 570 |
+
self.gotWidth = 0
|
| 571 |
+
self.width = 0
|
| 572 |
+
|
| 573 |
+
def popallWidth(self, evenOdd=0):
|
| 574 |
+
args = self.popall()
|
| 575 |
+
if not self.gotWidth:
|
| 576 |
+
if evenOdd ^ (len(args) % 2):
|
| 577 |
+
# For CFF2 charstrings, this should never happen
|
| 578 |
+
assert (
|
| 579 |
+
self.defaultWidthX is not None
|
| 580 |
+
), "CFF2 CharStrings must not have an initial width value"
|
| 581 |
+
self.width = self.nominalWidthX + args[0]
|
| 582 |
+
args = args[1:]
|
| 583 |
+
else:
|
| 584 |
+
self.width = self.defaultWidthX
|
| 585 |
+
self.gotWidth = 1
|
| 586 |
+
return args
|
| 587 |
+
|
| 588 |
+
def countHints(self):
|
| 589 |
+
args = self.popallWidth()
|
| 590 |
+
self.hintCount = self.hintCount + len(args) // 2
|
| 591 |
+
|
| 592 |
+
def op_rmoveto(self, index):
|
| 593 |
+
self.popallWidth()
|
| 594 |
+
|
| 595 |
+
def op_hmoveto(self, index):
|
| 596 |
+
self.popallWidth(1)
|
| 597 |
+
|
| 598 |
+
def op_vmoveto(self, index):
|
| 599 |
+
self.popallWidth(1)
|
| 600 |
+
|
| 601 |
+
def op_endchar(self, index):
|
| 602 |
+
self.popallWidth()
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
class T2OutlineExtractor(T2WidthExtractor):
|
| 606 |
+
def __init__(
|
| 607 |
+
self,
|
| 608 |
+
pen,
|
| 609 |
+
localSubrs,
|
| 610 |
+
globalSubrs,
|
| 611 |
+
nominalWidthX,
|
| 612 |
+
defaultWidthX,
|
| 613 |
+
private=None,
|
| 614 |
+
blender=None,
|
| 615 |
+
):
|
| 616 |
+
T2WidthExtractor.__init__(
|
| 617 |
+
self,
|
| 618 |
+
localSubrs,
|
| 619 |
+
globalSubrs,
|
| 620 |
+
nominalWidthX,
|
| 621 |
+
defaultWidthX,
|
| 622 |
+
private,
|
| 623 |
+
blender,
|
| 624 |
+
)
|
| 625 |
+
self.pen = pen
|
| 626 |
+
self.subrLevel = 0
|
| 627 |
+
|
| 628 |
+
def reset(self):
|
| 629 |
+
T2WidthExtractor.reset(self)
|
| 630 |
+
self.currentPoint = (0, 0)
|
| 631 |
+
self.sawMoveTo = 0
|
| 632 |
+
self.subrLevel = 0
|
| 633 |
+
|
| 634 |
+
def execute(self, charString):
|
| 635 |
+
self.subrLevel += 1
|
| 636 |
+
super().execute(charString)
|
| 637 |
+
self.subrLevel -= 1
|
| 638 |
+
if self.subrLevel == 0:
|
| 639 |
+
self.endPath()
|
| 640 |
+
|
| 641 |
+
def _nextPoint(self, point):
|
| 642 |
+
x, y = self.currentPoint
|
| 643 |
+
point = x + point[0], y + point[1]
|
| 644 |
+
self.currentPoint = point
|
| 645 |
+
return point
|
| 646 |
+
|
| 647 |
+
def rMoveTo(self, point):
|
| 648 |
+
self.pen.moveTo(self._nextPoint(point))
|
| 649 |
+
self.sawMoveTo = 1
|
| 650 |
+
|
| 651 |
+
def rLineTo(self, point):
|
| 652 |
+
if not self.sawMoveTo:
|
| 653 |
+
self.rMoveTo((0, 0))
|
| 654 |
+
self.pen.lineTo(self._nextPoint(point))
|
| 655 |
+
|
| 656 |
+
def rCurveTo(self, pt1, pt2, pt3):
|
| 657 |
+
if not self.sawMoveTo:
|
| 658 |
+
self.rMoveTo((0, 0))
|
| 659 |
+
nextPoint = self._nextPoint
|
| 660 |
+
self.pen.curveTo(nextPoint(pt1), nextPoint(pt2), nextPoint(pt3))
|
| 661 |
+
|
| 662 |
+
def closePath(self):
|
| 663 |
+
if self.sawMoveTo:
|
| 664 |
+
self.pen.closePath()
|
| 665 |
+
self.sawMoveTo = 0
|
| 666 |
+
|
| 667 |
+
def endPath(self):
|
| 668 |
+
# In T2 there are no open paths, so always do a closePath when
|
| 669 |
+
# finishing a sub path. We avoid spurious calls to closePath()
|
| 670 |
+
# because its a real T1 op we're emulating in T2 whereas
|
| 671 |
+
# endPath() is just a means to that emulation
|
| 672 |
+
if self.sawMoveTo:
|
| 673 |
+
self.closePath()
|
| 674 |
+
|
| 675 |
+
#
|
| 676 |
+
# hint operators
|
| 677 |
+
#
|
| 678 |
+
# def op_hstem(self, index):
|
| 679 |
+
# self.countHints()
|
| 680 |
+
# def op_vstem(self, index):
|
| 681 |
+
# self.countHints()
|
| 682 |
+
# def op_hstemhm(self, index):
|
| 683 |
+
# self.countHints()
|
| 684 |
+
# def op_vstemhm(self, index):
|
| 685 |
+
# self.countHints()
|
| 686 |
+
# def op_hintmask(self, index):
|
| 687 |
+
# self.countHints()
|
| 688 |
+
# def op_cntrmask(self, index):
|
| 689 |
+
# self.countHints()
|
| 690 |
+
|
| 691 |
+
#
|
| 692 |
+
# path constructors, moveto
|
| 693 |
+
#
|
| 694 |
+
def op_rmoveto(self, index):
|
| 695 |
+
self.endPath()
|
| 696 |
+
self.rMoveTo(self.popallWidth())
|
| 697 |
+
|
| 698 |
+
def op_hmoveto(self, index):
|
| 699 |
+
self.endPath()
|
| 700 |
+
self.rMoveTo((self.popallWidth(1)[0], 0))
|
| 701 |
+
|
| 702 |
+
def op_vmoveto(self, index):
|
| 703 |
+
self.endPath()
|
| 704 |
+
self.rMoveTo((0, self.popallWidth(1)[0]))
|
| 705 |
+
|
| 706 |
+
def op_endchar(self, index):
|
| 707 |
+
self.endPath()
|
| 708 |
+
args = self.popallWidth()
|
| 709 |
+
if args:
|
| 710 |
+
from fontTools.encodings.StandardEncoding import StandardEncoding
|
| 711 |
+
|
| 712 |
+
# endchar can do seac accent bulding; The T2 spec says it's deprecated,
|
| 713 |
+
# but recent software that shall remain nameless does output it.
|
| 714 |
+
adx, ady, bchar, achar = args
|
| 715 |
+
baseGlyph = StandardEncoding[bchar]
|
| 716 |
+
self.pen.addComponent(baseGlyph, (1, 0, 0, 1, 0, 0))
|
| 717 |
+
accentGlyph = StandardEncoding[achar]
|
| 718 |
+
self.pen.addComponent(accentGlyph, (1, 0, 0, 1, adx, ady))
|
| 719 |
+
|
| 720 |
+
#
|
| 721 |
+
# path constructors, lines
|
| 722 |
+
#
|
| 723 |
+
def op_rlineto(self, index):
|
| 724 |
+
args = self.popall()
|
| 725 |
+
for i in range(0, len(args), 2):
|
| 726 |
+
point = args[i : i + 2]
|
| 727 |
+
self.rLineTo(point)
|
| 728 |
+
|
| 729 |
+
def op_hlineto(self, index):
|
| 730 |
+
self.alternatingLineto(1)
|
| 731 |
+
|
| 732 |
+
def op_vlineto(self, index):
|
| 733 |
+
self.alternatingLineto(0)
|
| 734 |
+
|
| 735 |
+
#
|
| 736 |
+
# path constructors, curves
|
| 737 |
+
#
|
| 738 |
+
def op_rrcurveto(self, index):
|
| 739 |
+
"""{dxa dya dxb dyb dxc dyc}+ rrcurveto"""
|
| 740 |
+
args = self.popall()
|
| 741 |
+
for i in range(0, len(args), 6):
|
| 742 |
+
(
|
| 743 |
+
dxa,
|
| 744 |
+
dya,
|
| 745 |
+
dxb,
|
| 746 |
+
dyb,
|
| 747 |
+
dxc,
|
| 748 |
+
dyc,
|
| 749 |
+
) = args[i : i + 6]
|
| 750 |
+
self.rCurveTo((dxa, dya), (dxb, dyb), (dxc, dyc))
|
| 751 |
+
|
| 752 |
+
def op_rcurveline(self, index):
|
| 753 |
+
"""{dxa dya dxb dyb dxc dyc}+ dxd dyd rcurveline"""
|
| 754 |
+
args = self.popall()
|
| 755 |
+
for i in range(0, len(args) - 2, 6):
|
| 756 |
+
dxb, dyb, dxc, dyc, dxd, dyd = args[i : i + 6]
|
| 757 |
+
self.rCurveTo((dxb, dyb), (dxc, dyc), (dxd, dyd))
|
| 758 |
+
self.rLineTo(args[-2:])
|
| 759 |
+
|
| 760 |
+
def op_rlinecurve(self, index):
|
| 761 |
+
"""{dxa dya}+ dxb dyb dxc dyc dxd dyd rlinecurve"""
|
| 762 |
+
args = self.popall()
|
| 763 |
+
lineArgs = args[:-6]
|
| 764 |
+
for i in range(0, len(lineArgs), 2):
|
| 765 |
+
self.rLineTo(lineArgs[i : i + 2])
|
| 766 |
+
dxb, dyb, dxc, dyc, dxd, dyd = args[-6:]
|
| 767 |
+
self.rCurveTo((dxb, dyb), (dxc, dyc), (dxd, dyd))
|
| 768 |
+
|
| 769 |
+
def op_vvcurveto(self, index):
|
| 770 |
+
"dx1? {dya dxb dyb dyc}+ vvcurveto"
|
| 771 |
+
args = self.popall()
|
| 772 |
+
if len(args) % 2:
|
| 773 |
+
dx1 = args[0]
|
| 774 |
+
args = args[1:]
|
| 775 |
+
else:
|
| 776 |
+
dx1 = 0
|
| 777 |
+
for i in range(0, len(args), 4):
|
| 778 |
+
dya, dxb, dyb, dyc = args[i : i + 4]
|
| 779 |
+
self.rCurveTo((dx1, dya), (dxb, dyb), (0, dyc))
|
| 780 |
+
dx1 = 0
|
| 781 |
+
|
| 782 |
+
def op_hhcurveto(self, index):
|
| 783 |
+
"""dy1? {dxa dxb dyb dxc}+ hhcurveto"""
|
| 784 |
+
args = self.popall()
|
| 785 |
+
if len(args) % 2:
|
| 786 |
+
dy1 = args[0]
|
| 787 |
+
args = args[1:]
|
| 788 |
+
else:
|
| 789 |
+
dy1 = 0
|
| 790 |
+
for i in range(0, len(args), 4):
|
| 791 |
+
dxa, dxb, dyb, dxc = args[i : i + 4]
|
| 792 |
+
self.rCurveTo((dxa, dy1), (dxb, dyb), (dxc, 0))
|
| 793 |
+
dy1 = 0
|
| 794 |
+
|
| 795 |
+
def op_vhcurveto(self, index):
|
| 796 |
+
"""dy1 dx2 dy2 dx3 {dxa dxb dyb dyc dyd dxe dye dxf}* dyf? vhcurveto (30)
|
| 797 |
+
{dya dxb dyb dxc dxd dxe dye dyf}+ dxf? vhcurveto
|
| 798 |
+
"""
|
| 799 |
+
args = self.popall()
|
| 800 |
+
while args:
|
| 801 |
+
args = self.vcurveto(args)
|
| 802 |
+
if args:
|
| 803 |
+
args = self.hcurveto(args)
|
| 804 |
+
|
| 805 |
+
def op_hvcurveto(self, index):
|
| 806 |
+
"""dx1 dx2 dy2 dy3 {dya dxb dyb dxc dxd dxe dye dyf}* dxf?
|
| 807 |
+
{dxa dxb dyb dyc dyd dxe dye dxf}+ dyf?
|
| 808 |
+
"""
|
| 809 |
+
args = self.popall()
|
| 810 |
+
while args:
|
| 811 |
+
args = self.hcurveto(args)
|
| 812 |
+
if args:
|
| 813 |
+
args = self.vcurveto(args)
|
| 814 |
+
|
| 815 |
+
#
|
| 816 |
+
# path constructors, flex
|
| 817 |
+
#
|
| 818 |
+
def op_hflex(self, index):
|
| 819 |
+
dx1, dx2, dy2, dx3, dx4, dx5, dx6 = self.popall()
|
| 820 |
+
dy1 = dy3 = dy4 = dy6 = 0
|
| 821 |
+
dy5 = -dy2
|
| 822 |
+
self.rCurveTo((dx1, dy1), (dx2, dy2), (dx3, dy3))
|
| 823 |
+
self.rCurveTo((dx4, dy4), (dx5, dy5), (dx6, dy6))
|
| 824 |
+
|
| 825 |
+
def op_flex(self, index):
|
| 826 |
+
dx1, dy1, dx2, dy2, dx3, dy3, dx4, dy4, dx5, dy5, dx6, dy6, fd = self.popall()
|
| 827 |
+
self.rCurveTo((dx1, dy1), (dx2, dy2), (dx3, dy3))
|
| 828 |
+
self.rCurveTo((dx4, dy4), (dx5, dy5), (dx6, dy6))
|
| 829 |
+
|
| 830 |
+
def op_hflex1(self, index):
|
| 831 |
+
dx1, dy1, dx2, dy2, dx3, dx4, dx5, dy5, dx6 = self.popall()
|
| 832 |
+
dy3 = dy4 = 0
|
| 833 |
+
dy6 = -(dy1 + dy2 + dy3 + dy4 + dy5)
|
| 834 |
+
|
| 835 |
+
self.rCurveTo((dx1, dy1), (dx2, dy2), (dx3, dy3))
|
| 836 |
+
self.rCurveTo((dx4, dy4), (dx5, dy5), (dx6, dy6))
|
| 837 |
+
|
| 838 |
+
def op_flex1(self, index):
|
| 839 |
+
dx1, dy1, dx2, dy2, dx3, dy3, dx4, dy4, dx5, dy5, d6 = self.popall()
|
| 840 |
+
dx = dx1 + dx2 + dx3 + dx4 + dx5
|
| 841 |
+
dy = dy1 + dy2 + dy3 + dy4 + dy5
|
| 842 |
+
if abs(dx) > abs(dy):
|
| 843 |
+
dx6 = d6
|
| 844 |
+
dy6 = -dy
|
| 845 |
+
else:
|
| 846 |
+
dx6 = -dx
|
| 847 |
+
dy6 = d6
|
| 848 |
+
self.rCurveTo((dx1, dy1), (dx2, dy2), (dx3, dy3))
|
| 849 |
+
self.rCurveTo((dx4, dy4), (dx5, dy5), (dx6, dy6))
|
| 850 |
+
|
| 851 |
+
# misc
|
| 852 |
+
def op_and(self, index):
|
| 853 |
+
raise NotImplementedError
|
| 854 |
+
|
| 855 |
+
def op_or(self, index):
|
| 856 |
+
raise NotImplementedError
|
| 857 |
+
|
| 858 |
+
def op_not(self, index):
|
| 859 |
+
raise NotImplementedError
|
| 860 |
+
|
| 861 |
+
def op_store(self, index):
|
| 862 |
+
raise NotImplementedError
|
| 863 |
+
|
| 864 |
+
def op_abs(self, index):
|
| 865 |
+
raise NotImplementedError
|
| 866 |
+
|
| 867 |
+
def op_add(self, index):
|
| 868 |
+
raise NotImplementedError
|
| 869 |
+
|
| 870 |
+
def op_sub(self, index):
|
| 871 |
+
raise NotImplementedError
|
| 872 |
+
|
| 873 |
+
def op_div(self, index):
|
| 874 |
+
num2 = self.pop()
|
| 875 |
+
num1 = self.pop()
|
| 876 |
+
d1 = num1 // num2
|
| 877 |
+
d2 = num1 / num2
|
| 878 |
+
if d1 == d2:
|
| 879 |
+
self.push(d1)
|
| 880 |
+
else:
|
| 881 |
+
self.push(d2)
|
| 882 |
+
|
| 883 |
+
def op_load(self, index):
|
| 884 |
+
raise NotImplementedError
|
| 885 |
+
|
| 886 |
+
def op_neg(self, index):
|
| 887 |
+
raise NotImplementedError
|
| 888 |
+
|
| 889 |
+
def op_eq(self, index):
|
| 890 |
+
raise NotImplementedError
|
| 891 |
+
|
| 892 |
+
def op_drop(self, index):
|
| 893 |
+
raise NotImplementedError
|
| 894 |
+
|
| 895 |
+
def op_put(self, index):
|
| 896 |
+
raise NotImplementedError
|
| 897 |
+
|
| 898 |
+
def op_get(self, index):
|
| 899 |
+
raise NotImplementedError
|
| 900 |
+
|
| 901 |
+
def op_ifelse(self, index):
|
| 902 |
+
raise NotImplementedError
|
| 903 |
+
|
| 904 |
+
def op_random(self, index):
|
| 905 |
+
raise NotImplementedError
|
| 906 |
+
|
| 907 |
+
def op_mul(self, index):
|
| 908 |
+
raise NotImplementedError
|
| 909 |
+
|
| 910 |
+
def op_sqrt(self, index):
|
| 911 |
+
raise NotImplementedError
|
| 912 |
+
|
| 913 |
+
def op_dup(self, index):
|
| 914 |
+
raise NotImplementedError
|
| 915 |
+
|
| 916 |
+
def op_exch(self, index):
|
| 917 |
+
raise NotImplementedError
|
| 918 |
+
|
| 919 |
+
def op_index(self, index):
|
| 920 |
+
raise NotImplementedError
|
| 921 |
+
|
| 922 |
+
def op_roll(self, index):
|
| 923 |
+
raise NotImplementedError
|
| 924 |
+
|
| 925 |
+
#
|
| 926 |
+
# miscellaneous helpers
|
| 927 |
+
#
|
| 928 |
+
def alternatingLineto(self, isHorizontal):
|
| 929 |
+
args = self.popall()
|
| 930 |
+
for arg in args:
|
| 931 |
+
if isHorizontal:
|
| 932 |
+
point = (arg, 0)
|
| 933 |
+
else:
|
| 934 |
+
point = (0, arg)
|
| 935 |
+
self.rLineTo(point)
|
| 936 |
+
isHorizontal = not isHorizontal
|
| 937 |
+
|
| 938 |
+
def vcurveto(self, args):
|
| 939 |
+
dya, dxb, dyb, dxc = args[:4]
|
| 940 |
+
args = args[4:]
|
| 941 |
+
if len(args) == 1:
|
| 942 |
+
dyc = args[0]
|
| 943 |
+
args = []
|
| 944 |
+
else:
|
| 945 |
+
dyc = 0
|
| 946 |
+
self.rCurveTo((0, dya), (dxb, dyb), (dxc, dyc))
|
| 947 |
+
return args
|
| 948 |
+
|
| 949 |
+
def hcurveto(self, args):
|
| 950 |
+
dxa, dxb, dyb, dyc = args[:4]
|
| 951 |
+
args = args[4:]
|
| 952 |
+
if len(args) == 1:
|
| 953 |
+
dxc = args[0]
|
| 954 |
+
args = []
|
| 955 |
+
else:
|
| 956 |
+
dxc = 0
|
| 957 |
+
self.rCurveTo((dxa, 0), (dxb, dyb), (dxc, dyc))
|
| 958 |
+
return args
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
class T1OutlineExtractor(T2OutlineExtractor):
|
| 962 |
+
def __init__(self, pen, subrs):
|
| 963 |
+
self.pen = pen
|
| 964 |
+
self.subrs = subrs
|
| 965 |
+
self.reset()
|
| 966 |
+
|
| 967 |
+
def reset(self):
|
| 968 |
+
self.flexing = 0
|
| 969 |
+
self.width = 0
|
| 970 |
+
self.sbx = 0
|
| 971 |
+
T2OutlineExtractor.reset(self)
|
| 972 |
+
|
| 973 |
+
def endPath(self):
|
| 974 |
+
if self.sawMoveTo:
|
| 975 |
+
self.pen.endPath()
|
| 976 |
+
self.sawMoveTo = 0
|
| 977 |
+
|
| 978 |
+
def popallWidth(self, evenOdd=0):
|
| 979 |
+
return self.popall()
|
| 980 |
+
|
| 981 |
+
def exch(self):
|
| 982 |
+
stack = self.operandStack
|
| 983 |
+
stack[-1], stack[-2] = stack[-2], stack[-1]
|
| 984 |
+
|
| 985 |
+
#
|
| 986 |
+
# path constructors
|
| 987 |
+
#
|
| 988 |
+
def op_rmoveto(self, index):
|
| 989 |
+
if self.flexing:
|
| 990 |
+
return
|
| 991 |
+
self.endPath()
|
| 992 |
+
self.rMoveTo(self.popall())
|
| 993 |
+
|
| 994 |
+
def op_hmoveto(self, index):
|
| 995 |
+
if self.flexing:
|
| 996 |
+
# We must add a parameter to the stack if we are flexing
|
| 997 |
+
self.push(0)
|
| 998 |
+
return
|
| 999 |
+
self.endPath()
|
| 1000 |
+
self.rMoveTo((self.popall()[0], 0))
|
| 1001 |
+
|
| 1002 |
+
def op_vmoveto(self, index):
|
| 1003 |
+
if self.flexing:
|
| 1004 |
+
# We must add a parameter to the stack if we are flexing
|
| 1005 |
+
self.push(0)
|
| 1006 |
+
self.exch()
|
| 1007 |
+
return
|
| 1008 |
+
self.endPath()
|
| 1009 |
+
self.rMoveTo((0, self.popall()[0]))
|
| 1010 |
+
|
| 1011 |
+
def op_closepath(self, index):
|
| 1012 |
+
self.closePath()
|
| 1013 |
+
|
| 1014 |
+
def op_setcurrentpoint(self, index):
|
| 1015 |
+
args = self.popall()
|
| 1016 |
+
x, y = args
|
| 1017 |
+
self.currentPoint = x, y
|
| 1018 |
+
|
| 1019 |
+
def op_endchar(self, index):
|
| 1020 |
+
self.endPath()
|
| 1021 |
+
|
| 1022 |
+
def op_hsbw(self, index):
|
| 1023 |
+
sbx, wx = self.popall()
|
| 1024 |
+
self.width = wx
|
| 1025 |
+
self.sbx = sbx
|
| 1026 |
+
self.currentPoint = sbx, self.currentPoint[1]
|
| 1027 |
+
|
| 1028 |
+
def op_sbw(self, index):
|
| 1029 |
+
self.popall() # XXX
|
| 1030 |
+
|
| 1031 |
+
#
|
| 1032 |
+
def op_callsubr(self, index):
|
| 1033 |
+
subrIndex = self.pop()
|
| 1034 |
+
subr = self.subrs[subrIndex]
|
| 1035 |
+
self.execute(subr)
|
| 1036 |
+
|
| 1037 |
+
def op_callothersubr(self, index):
|
| 1038 |
+
subrIndex = self.pop()
|
| 1039 |
+
nArgs = self.pop()
|
| 1040 |
+
# print nArgs, subrIndex, "callothersubr"
|
| 1041 |
+
if subrIndex == 0 and nArgs == 3:
|
| 1042 |
+
self.doFlex()
|
| 1043 |
+
self.flexing = 0
|
| 1044 |
+
elif subrIndex == 1 and nArgs == 0:
|
| 1045 |
+
self.flexing = 1
|
| 1046 |
+
# ignore...
|
| 1047 |
+
|
| 1048 |
+
def op_pop(self, index):
|
| 1049 |
+
pass # ignore...
|
| 1050 |
+
|
| 1051 |
+
def doFlex(self):
|
| 1052 |
+
finaly = self.pop()
|
| 1053 |
+
finalx = self.pop()
|
| 1054 |
+
self.pop() # flex height is unused
|
| 1055 |
+
|
| 1056 |
+
p3y = self.pop()
|
| 1057 |
+
p3x = self.pop()
|
| 1058 |
+
bcp4y = self.pop()
|
| 1059 |
+
bcp4x = self.pop()
|
| 1060 |
+
bcp3y = self.pop()
|
| 1061 |
+
bcp3x = self.pop()
|
| 1062 |
+
p2y = self.pop()
|
| 1063 |
+
p2x = self.pop()
|
| 1064 |
+
bcp2y = self.pop()
|
| 1065 |
+
bcp2x = self.pop()
|
| 1066 |
+
bcp1y = self.pop()
|
| 1067 |
+
bcp1x = self.pop()
|
| 1068 |
+
rpy = self.pop()
|
| 1069 |
+
rpx = self.pop()
|
| 1070 |
+
|
| 1071 |
+
# call rrcurveto
|
| 1072 |
+
self.push(bcp1x + rpx)
|
| 1073 |
+
self.push(bcp1y + rpy)
|
| 1074 |
+
self.push(bcp2x)
|
| 1075 |
+
self.push(bcp2y)
|
| 1076 |
+
self.push(p2x)
|
| 1077 |
+
self.push(p2y)
|
| 1078 |
+
self.op_rrcurveto(None)
|
| 1079 |
+
|
| 1080 |
+
# call rrcurveto
|
| 1081 |
+
self.push(bcp3x)
|
| 1082 |
+
self.push(bcp3y)
|
| 1083 |
+
self.push(bcp4x)
|
| 1084 |
+
self.push(bcp4y)
|
| 1085 |
+
self.push(p3x)
|
| 1086 |
+
self.push(p3y)
|
| 1087 |
+
self.op_rrcurveto(None)
|
| 1088 |
+
|
| 1089 |
+
# Push back final coords so subr 0 can find them
|
| 1090 |
+
self.push(finalx)
|
| 1091 |
+
self.push(finaly)
|
| 1092 |
+
|
| 1093 |
+
def op_dotsection(self, index):
|
| 1094 |
+
self.popall() # XXX
|
| 1095 |
+
|
| 1096 |
+
def op_hstem3(self, index):
|
| 1097 |
+
self.popall() # XXX
|
| 1098 |
+
|
| 1099 |
+
def op_seac(self, index):
|
| 1100 |
+
"asb adx ady bchar achar seac"
|
| 1101 |
+
from fontTools.encodings.StandardEncoding import StandardEncoding
|
| 1102 |
+
|
| 1103 |
+
asb, adx, ady, bchar, achar = self.popall()
|
| 1104 |
+
baseGlyph = StandardEncoding[bchar]
|
| 1105 |
+
self.pen.addComponent(baseGlyph, (1, 0, 0, 1, 0, 0))
|
| 1106 |
+
accentGlyph = StandardEncoding[achar]
|
| 1107 |
+
adx = adx + self.sbx - asb # seac weirdness
|
| 1108 |
+
self.pen.addComponent(accentGlyph, (1, 0, 0, 1, adx, ady))
|
| 1109 |
+
|
| 1110 |
+
def op_vstem3(self, index):
|
| 1111 |
+
self.popall() # XXX
|
| 1112 |
+
|
| 1113 |
+
|
| 1114 |
+
class T2CharString(object):
|
| 1115 |
+
operandEncoding = t2OperandEncoding
|
| 1116 |
+
operators, opcodes = buildOperatorDict(t2Operators)
|
| 1117 |
+
decompilerClass = SimpleT2Decompiler
|
| 1118 |
+
outlineExtractor = T2OutlineExtractor
|
| 1119 |
+
|
| 1120 |
+
def __init__(self, bytecode=None, program=None, private=None, globalSubrs=None):
|
| 1121 |
+
if program is None:
|
| 1122 |
+
program = []
|
| 1123 |
+
self.bytecode = bytecode
|
| 1124 |
+
self.program = program
|
| 1125 |
+
self.private = private
|
| 1126 |
+
self.globalSubrs = globalSubrs if globalSubrs is not None else []
|
| 1127 |
+
self._cur_vsindex = None
|
| 1128 |
+
|
| 1129 |
+
def getNumRegions(self, vsindex=None):
|
| 1130 |
+
pd = self.private
|
| 1131 |
+
assert pd is not None
|
| 1132 |
+
if vsindex is not None:
|
| 1133 |
+
self._cur_vsindex = vsindex
|
| 1134 |
+
elif self._cur_vsindex is None:
|
| 1135 |
+
self._cur_vsindex = pd.vsindex if hasattr(pd, "vsindex") else 0
|
| 1136 |
+
return pd.getNumRegions(self._cur_vsindex)
|
| 1137 |
+
|
| 1138 |
+
def __repr__(self):
|
| 1139 |
+
if self.bytecode is None:
|
| 1140 |
+
return "<%s (source) at %x>" % (self.__class__.__name__, id(self))
|
| 1141 |
+
else:
|
| 1142 |
+
return "<%s (bytecode) at %x>" % (self.__class__.__name__, id(self))
|
| 1143 |
+
|
| 1144 |
+
def getIntEncoder(self):
|
| 1145 |
+
return encodeIntT2
|
| 1146 |
+
|
| 1147 |
+
def getFixedEncoder(self):
|
| 1148 |
+
return encodeFixed
|
| 1149 |
+
|
| 1150 |
+
def decompile(self):
|
| 1151 |
+
if not self.needsDecompilation():
|
| 1152 |
+
return
|
| 1153 |
+
subrs = getattr(self.private, "Subrs", [])
|
| 1154 |
+
decompiler = self.decompilerClass(subrs, self.globalSubrs, self.private)
|
| 1155 |
+
decompiler.execute(self)
|
| 1156 |
+
|
| 1157 |
+
def draw(self, pen, blender=None):
|
| 1158 |
+
subrs = getattr(self.private, "Subrs", [])
|
| 1159 |
+
extractor = self.outlineExtractor(
|
| 1160 |
+
pen,
|
| 1161 |
+
subrs,
|
| 1162 |
+
self.globalSubrs,
|
| 1163 |
+
self.private.nominalWidthX,
|
| 1164 |
+
self.private.defaultWidthX,
|
| 1165 |
+
self.private,
|
| 1166 |
+
blender,
|
| 1167 |
+
)
|
| 1168 |
+
extractor.execute(self)
|
| 1169 |
+
self.width = extractor.width
|
| 1170 |
+
|
| 1171 |
+
def calcBounds(self, glyphSet):
|
| 1172 |
+
boundsPen = BoundsPen(glyphSet)
|
| 1173 |
+
self.draw(boundsPen)
|
| 1174 |
+
return boundsPen.bounds
|
| 1175 |
+
|
| 1176 |
+
def compile(self, isCFF2=False):
|
| 1177 |
+
if self.bytecode is not None:
|
| 1178 |
+
return
|
| 1179 |
+
opcodes = self.opcodes
|
| 1180 |
+
program = self.program
|
| 1181 |
+
|
| 1182 |
+
if isCFF2:
|
| 1183 |
+
# If present, remove return and endchar operators.
|
| 1184 |
+
if program and program[-1] in ("return", "endchar"):
|
| 1185 |
+
program = program[:-1]
|
| 1186 |
+
elif program and not isinstance(program[-1], str):
|
| 1187 |
+
raise CharStringCompileError(
|
| 1188 |
+
"T2CharString or Subr has items on the stack after last operator."
|
| 1189 |
+
)
|
| 1190 |
+
|
| 1191 |
+
bytecode = []
|
| 1192 |
+
encodeInt = self.getIntEncoder()
|
| 1193 |
+
encodeFixed = self.getFixedEncoder()
|
| 1194 |
+
i = 0
|
| 1195 |
+
end = len(program)
|
| 1196 |
+
while i < end:
|
| 1197 |
+
token = program[i]
|
| 1198 |
+
i = i + 1
|
| 1199 |
+
if isinstance(token, str):
|
| 1200 |
+
try:
|
| 1201 |
+
bytecode.extend(bytechr(b) for b in opcodes[token])
|
| 1202 |
+
except KeyError:
|
| 1203 |
+
raise CharStringCompileError("illegal operator: %s" % token)
|
| 1204 |
+
if token in ("hintmask", "cntrmask"):
|
| 1205 |
+
bytecode.append(program[i]) # hint mask
|
| 1206 |
+
i = i + 1
|
| 1207 |
+
elif isinstance(token, int):
|
| 1208 |
+
bytecode.append(encodeInt(token))
|
| 1209 |
+
elif isinstance(token, float):
|
| 1210 |
+
bytecode.append(encodeFixed(token))
|
| 1211 |
+
else:
|
| 1212 |
+
assert 0, "unsupported type: %s" % type(token)
|
| 1213 |
+
try:
|
| 1214 |
+
bytecode = bytesjoin(bytecode)
|
| 1215 |
+
except TypeError:
|
| 1216 |
+
log.error(bytecode)
|
| 1217 |
+
raise
|
| 1218 |
+
self.setBytecode(bytecode)
|
| 1219 |
+
|
| 1220 |
+
def needsDecompilation(self):
|
| 1221 |
+
return self.bytecode is not None
|
| 1222 |
+
|
| 1223 |
+
def setProgram(self, program):
|
| 1224 |
+
self.program = program
|
| 1225 |
+
self.bytecode = None
|
| 1226 |
+
|
| 1227 |
+
def setBytecode(self, bytecode):
|
| 1228 |
+
self.bytecode = bytecode
|
| 1229 |
+
self.program = None
|
| 1230 |
+
|
| 1231 |
+
def getToken(self, index, len=len, byteord=byteord, isinstance=isinstance):
|
| 1232 |
+
if self.bytecode is not None:
|
| 1233 |
+
if index >= len(self.bytecode):
|
| 1234 |
+
return None, 0, 0
|
| 1235 |
+
b0 = byteord(self.bytecode[index])
|
| 1236 |
+
index = index + 1
|
| 1237 |
+
handler = self.operandEncoding[b0]
|
| 1238 |
+
token, index = handler(self, b0, self.bytecode, index)
|
| 1239 |
+
else:
|
| 1240 |
+
if index >= len(self.program):
|
| 1241 |
+
return None, 0, 0
|
| 1242 |
+
token = self.program[index]
|
| 1243 |
+
index = index + 1
|
| 1244 |
+
isOperator = isinstance(token, str)
|
| 1245 |
+
return token, isOperator, index
|
| 1246 |
+
|
| 1247 |
+
def getBytes(self, index, nBytes):
|
| 1248 |
+
if self.bytecode is not None:
|
| 1249 |
+
newIndex = index + nBytes
|
| 1250 |
+
bytes = self.bytecode[index:newIndex]
|
| 1251 |
+
index = newIndex
|
| 1252 |
+
else:
|
| 1253 |
+
bytes = self.program[index]
|
| 1254 |
+
index = index + 1
|
| 1255 |
+
assert len(bytes) == nBytes
|
| 1256 |
+
return bytes, index
|
| 1257 |
+
|
| 1258 |
+
def handle_operator(self, operator):
|
| 1259 |
+
return operator
|
| 1260 |
+
|
| 1261 |
+
def toXML(self, xmlWriter, ttFont=None):
|
| 1262 |
+
from fontTools.misc.textTools import num2binary
|
| 1263 |
+
|
| 1264 |
+
if self.bytecode is not None:
|
| 1265 |
+
xmlWriter.dumphex(self.bytecode)
|
| 1266 |
+
else:
|
| 1267 |
+
index = 0
|
| 1268 |
+
args = []
|
| 1269 |
+
while True:
|
| 1270 |
+
token, isOperator, index = self.getToken(index)
|
| 1271 |
+
if token is None:
|
| 1272 |
+
break
|
| 1273 |
+
if isOperator:
|
| 1274 |
+
if token in ("hintmask", "cntrmask"):
|
| 1275 |
+
hintMask, isOperator, index = self.getToken(index)
|
| 1276 |
+
bits = []
|
| 1277 |
+
for byte in hintMask:
|
| 1278 |
+
bits.append(num2binary(byteord(byte), 8))
|
| 1279 |
+
hintMask = strjoin(bits)
|
| 1280 |
+
line = " ".join(args + [token, hintMask])
|
| 1281 |
+
else:
|
| 1282 |
+
line = " ".join(args + [token])
|
| 1283 |
+
xmlWriter.write(line)
|
| 1284 |
+
xmlWriter.newline()
|
| 1285 |
+
args = []
|
| 1286 |
+
else:
|
| 1287 |
+
if isinstance(token, float):
|
| 1288 |
+
token = floatToFixedToStr(token, precisionBits=16)
|
| 1289 |
+
else:
|
| 1290 |
+
token = str(token)
|
| 1291 |
+
args.append(token)
|
| 1292 |
+
if args:
|
| 1293 |
+
# NOTE: only CFF2 charstrings/subrs can have numeric arguments on
|
| 1294 |
+
# the stack after the last operator. Compiling this would fail if
|
| 1295 |
+
# this is part of CFF 1.0 table.
|
| 1296 |
+
line = " ".join(args)
|
| 1297 |
+
xmlWriter.write(line)
|
| 1298 |
+
|
| 1299 |
+
def fromXML(self, name, attrs, content):
|
| 1300 |
+
from fontTools.misc.textTools import binary2num, readHex
|
| 1301 |
+
|
| 1302 |
+
if attrs.get("raw"):
|
| 1303 |
+
self.setBytecode(readHex(content))
|
| 1304 |
+
return
|
| 1305 |
+
content = strjoin(content)
|
| 1306 |
+
content = content.split()
|
| 1307 |
+
program = []
|
| 1308 |
+
end = len(content)
|
| 1309 |
+
i = 0
|
| 1310 |
+
while i < end:
|
| 1311 |
+
token = content[i]
|
| 1312 |
+
i = i + 1
|
| 1313 |
+
try:
|
| 1314 |
+
token = int(token)
|
| 1315 |
+
except ValueError:
|
| 1316 |
+
try:
|
| 1317 |
+
token = strToFixedToFloat(token, precisionBits=16)
|
| 1318 |
+
except ValueError:
|
| 1319 |
+
program.append(token)
|
| 1320 |
+
if token in ("hintmask", "cntrmask"):
|
| 1321 |
+
mask = content[i]
|
| 1322 |
+
maskBytes = b""
|
| 1323 |
+
for j in range(0, len(mask), 8):
|
| 1324 |
+
maskBytes = maskBytes + bytechr(binary2num(mask[j : j + 8]))
|
| 1325 |
+
program.append(maskBytes)
|
| 1326 |
+
i = i + 1
|
| 1327 |
+
else:
|
| 1328 |
+
program.append(token)
|
| 1329 |
+
else:
|
| 1330 |
+
program.append(token)
|
| 1331 |
+
self.setProgram(program)
|
| 1332 |
+
|
| 1333 |
+
|
| 1334 |
+
class T1CharString(T2CharString):
|
| 1335 |
+
operandEncoding = t1OperandEncoding
|
| 1336 |
+
operators, opcodes = buildOperatorDict(t1Operators)
|
| 1337 |
+
|
| 1338 |
+
def __init__(self, bytecode=None, program=None, subrs=None):
|
| 1339 |
+
super().__init__(bytecode, program)
|
| 1340 |
+
self.subrs = subrs
|
| 1341 |
+
|
| 1342 |
+
def getIntEncoder(self):
|
| 1343 |
+
return encodeIntT1
|
| 1344 |
+
|
| 1345 |
+
def getFixedEncoder(self):
|
| 1346 |
+
def encodeFixed(value):
|
| 1347 |
+
raise TypeError("Type 1 charstrings don't support floating point operands")
|
| 1348 |
+
|
| 1349 |
+
def decompile(self):
|
| 1350 |
+
if self.bytecode is None:
|
| 1351 |
+
return
|
| 1352 |
+
program = []
|
| 1353 |
+
index = 0
|
| 1354 |
+
while True:
|
| 1355 |
+
token, isOperator, index = self.getToken(index)
|
| 1356 |
+
if token is None:
|
| 1357 |
+
break
|
| 1358 |
+
program.append(token)
|
| 1359 |
+
self.setProgram(program)
|
| 1360 |
+
|
| 1361 |
+
def draw(self, pen):
|
| 1362 |
+
extractor = T1OutlineExtractor(pen, self.subrs)
|
| 1363 |
+
extractor.execute(self)
|
| 1364 |
+
self.width = extractor.width
|
| 1365 |
+
|
| 1366 |
+
|
| 1367 |
+
class DictDecompiler(object):
|
| 1368 |
+
operandEncoding = cffDictOperandEncoding
|
| 1369 |
+
|
| 1370 |
+
def __init__(self, strings, parent=None):
|
| 1371 |
+
self.stack = []
|
| 1372 |
+
self.strings = strings
|
| 1373 |
+
self.dict = {}
|
| 1374 |
+
self.parent = parent
|
| 1375 |
+
|
| 1376 |
+
def getDict(self):
|
| 1377 |
+
assert len(self.stack) == 0, "non-empty stack"
|
| 1378 |
+
return self.dict
|
| 1379 |
+
|
| 1380 |
+
def decompile(self, data):
|
| 1381 |
+
index = 0
|
| 1382 |
+
lenData = len(data)
|
| 1383 |
+
push = self.stack.append
|
| 1384 |
+
while index < lenData:
|
| 1385 |
+
b0 = byteord(data[index])
|
| 1386 |
+
index = index + 1
|
| 1387 |
+
handler = self.operandEncoding[b0]
|
| 1388 |
+
value, index = handler(self, b0, data, index)
|
| 1389 |
+
if value is not None:
|
| 1390 |
+
push(value)
|
| 1391 |
+
|
| 1392 |
+
def pop(self):
|
| 1393 |
+
value = self.stack[-1]
|
| 1394 |
+
del self.stack[-1]
|
| 1395 |
+
return value
|
| 1396 |
+
|
| 1397 |
+
def popall(self):
|
| 1398 |
+
args = self.stack[:]
|
| 1399 |
+
del self.stack[:]
|
| 1400 |
+
return args
|
| 1401 |
+
|
| 1402 |
+
def handle_operator(self, operator):
|
| 1403 |
+
operator, argType = operator
|
| 1404 |
+
if isinstance(argType, tuple):
|
| 1405 |
+
value = ()
|
| 1406 |
+
for i in range(len(argType) - 1, -1, -1):
|
| 1407 |
+
arg = argType[i]
|
| 1408 |
+
arghandler = getattr(self, "arg_" + arg)
|
| 1409 |
+
value = (arghandler(operator),) + value
|
| 1410 |
+
else:
|
| 1411 |
+
arghandler = getattr(self, "arg_" + argType)
|
| 1412 |
+
value = arghandler(operator)
|
| 1413 |
+
if operator == "blend":
|
| 1414 |
+
self.stack.extend(value)
|
| 1415 |
+
else:
|
| 1416 |
+
self.dict[operator] = value
|
| 1417 |
+
|
| 1418 |
+
def arg_number(self, name):
|
| 1419 |
+
if isinstance(self.stack[0], list):
|
| 1420 |
+
out = self.arg_blend_number(self.stack)
|
| 1421 |
+
else:
|
| 1422 |
+
out = self.pop()
|
| 1423 |
+
return out
|
| 1424 |
+
|
| 1425 |
+
def arg_blend_number(self, name):
|
| 1426 |
+
out = []
|
| 1427 |
+
blendArgs = self.pop()
|
| 1428 |
+
numMasters = len(blendArgs)
|
| 1429 |
+
out.append(blendArgs)
|
| 1430 |
+
out.append("blend")
|
| 1431 |
+
dummy = self.popall()
|
| 1432 |
+
return blendArgs
|
| 1433 |
+
|
| 1434 |
+
def arg_SID(self, name):
|
| 1435 |
+
return self.strings[self.pop()]
|
| 1436 |
+
|
| 1437 |
+
def arg_array(self, name):
|
| 1438 |
+
return self.popall()
|
| 1439 |
+
|
| 1440 |
+
def arg_blendList(self, name):
|
| 1441 |
+
"""
|
| 1442 |
+
There may be non-blend args at the top of the stack. We first calculate
|
| 1443 |
+
where the blend args start in the stack. These are the last
|
| 1444 |
+
numMasters*numBlends) +1 args.
|
| 1445 |
+
The blend args starts with numMasters relative coordinate values, the BlueValues in the list from the default master font. This is followed by
|
| 1446 |
+
numBlends list of values. Each of value in one of these lists is the
|
| 1447 |
+
Variable Font delta for the matching region.
|
| 1448 |
+
|
| 1449 |
+
We re-arrange this to be a list of numMaster entries. Each entry starts with the corresponding default font relative value, and is followed by
|
| 1450 |
+
the delta values. We then convert the default values, the first item in each entry, to an absolute value.
|
| 1451 |
+
"""
|
| 1452 |
+
vsindex = self.dict.get("vsindex", 0)
|
| 1453 |
+
numMasters = (
|
| 1454 |
+
self.parent.getNumRegions(vsindex) + 1
|
| 1455 |
+
) # only a PrivateDict has blended ops.
|
| 1456 |
+
numBlends = self.pop()
|
| 1457 |
+
args = self.popall()
|
| 1458 |
+
numArgs = len(args)
|
| 1459 |
+
# The spec says that there should be no non-blended Blue Values,.
|
| 1460 |
+
assert numArgs == numMasters * numBlends
|
| 1461 |
+
value = [None] * numBlends
|
| 1462 |
+
numDeltas = numMasters - 1
|
| 1463 |
+
i = 0
|
| 1464 |
+
prevVal = 0
|
| 1465 |
+
while i < numBlends:
|
| 1466 |
+
newVal = args[i] + prevVal
|
| 1467 |
+
prevVal = newVal
|
| 1468 |
+
masterOffset = numBlends + (i * numDeltas)
|
| 1469 |
+
blendList = [newVal] + args[masterOffset : masterOffset + numDeltas]
|
| 1470 |
+
value[i] = blendList
|
| 1471 |
+
i += 1
|
| 1472 |
+
return value
|
| 1473 |
+
|
| 1474 |
+
def arg_delta(self, name):
|
| 1475 |
+
valueList = self.popall()
|
| 1476 |
+
out = []
|
| 1477 |
+
if valueList and isinstance(valueList[0], list):
|
| 1478 |
+
# arg_blendList() has already converted these to absolute values.
|
| 1479 |
+
out = valueList
|
| 1480 |
+
else:
|
| 1481 |
+
current = 0
|
| 1482 |
+
for v in valueList:
|
| 1483 |
+
current = current + v
|
| 1484 |
+
out.append(current)
|
| 1485 |
+
return out
|
| 1486 |
+
|
| 1487 |
+
|
| 1488 |
+
def calcSubrBias(subrs):
|
| 1489 |
+
nSubrs = len(subrs)
|
| 1490 |
+
if nSubrs < 1240:
|
| 1491 |
+
bias = 107
|
| 1492 |
+
elif nSubrs < 33900:
|
| 1493 |
+
bias = 1131
|
| 1494 |
+
else:
|
| 1495 |
+
bias = 32768
|
| 1496 |
+
return bias
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/psLib.py
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 6 |
+
ps_array,
|
| 7 |
+
ps_boolean,
|
| 8 |
+
ps_dict,
|
| 9 |
+
ps_integer,
|
| 10 |
+
ps_literal,
|
| 11 |
+
ps_mark,
|
| 12 |
+
ps_name,
|
| 13 |
+
ps_operator,
|
| 14 |
+
ps_procedure,
|
| 15 |
+
ps_procmark,
|
| 16 |
+
ps_real,
|
| 17 |
+
ps_string,
|
| 18 |
+
)
|
| 19 |
+
import re
|
| 20 |
+
from collections.abc import Callable
|
| 21 |
+
from string import whitespace
|
| 22 |
+
import logging
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
log = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
ps_special = b"()<>[]{}%" # / is one too, but we take care of that one differently
|
| 28 |
+
|
| 29 |
+
skipwhiteRE = re.compile(bytesjoin([b"[", whitespace, b"]*"]))
|
| 30 |
+
endofthingPat = bytesjoin([b"[^][(){}<>/%", whitespace, b"]*"])
|
| 31 |
+
endofthingRE = re.compile(endofthingPat)
|
| 32 |
+
commentRE = re.compile(b"%[^\n\r]*")
|
| 33 |
+
|
| 34 |
+
# XXX This not entirely correct as it doesn't allow *nested* embedded parens:
|
| 35 |
+
stringPat = rb"""
|
| 36 |
+
\(
|
| 37 |
+
(
|
| 38 |
+
(
|
| 39 |
+
[^()]* \ [()]
|
| 40 |
+
)
|
| 41 |
+
|
|
| 42 |
+
(
|
| 43 |
+
[^()]* \( [^()]* \)
|
| 44 |
+
)
|
| 45 |
+
)*
|
| 46 |
+
[^()]*
|
| 47 |
+
\)
|
| 48 |
+
"""
|
| 49 |
+
stringPat = b"".join(stringPat.split())
|
| 50 |
+
stringRE = re.compile(stringPat)
|
| 51 |
+
|
| 52 |
+
hexstringRE = re.compile(bytesjoin([b"<[", whitespace, b"0-9A-Fa-f]*>"]))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class PSTokenError(Exception):
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class PSError(Exception):
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class PSTokenizer(object):
|
| 64 |
+
def __init__(self, buf=b"", encoding="ascii"):
|
| 65 |
+
# Force self.buf to be a byte string
|
| 66 |
+
buf = tobytes(buf)
|
| 67 |
+
self.buf = buf
|
| 68 |
+
self.len = len(buf)
|
| 69 |
+
self.pos = 0
|
| 70 |
+
self.closed = False
|
| 71 |
+
self.encoding = encoding
|
| 72 |
+
|
| 73 |
+
def read(self, n=-1):
|
| 74 |
+
"""Read at most 'n' bytes from the buffer, or less if the read
|
| 75 |
+
hits EOF before obtaining 'n' bytes.
|
| 76 |
+
If 'n' is negative or omitted, read all data until EOF is reached.
|
| 77 |
+
"""
|
| 78 |
+
if self.closed:
|
| 79 |
+
raise ValueError("I/O operation on closed file")
|
| 80 |
+
if n is None or n < 0:
|
| 81 |
+
newpos = self.len
|
| 82 |
+
else:
|
| 83 |
+
newpos = min(self.pos + n, self.len)
|
| 84 |
+
r = self.buf[self.pos : newpos]
|
| 85 |
+
self.pos = newpos
|
| 86 |
+
return r
|
| 87 |
+
|
| 88 |
+
def close(self):
|
| 89 |
+
if not self.closed:
|
| 90 |
+
self.closed = True
|
| 91 |
+
del self.buf, self.pos
|
| 92 |
+
|
| 93 |
+
def getnexttoken(
|
| 94 |
+
self,
|
| 95 |
+
# localize some stuff, for performance
|
| 96 |
+
len=len,
|
| 97 |
+
ps_special=ps_special,
|
| 98 |
+
stringmatch=stringRE.match,
|
| 99 |
+
hexstringmatch=hexstringRE.match,
|
| 100 |
+
commentmatch=commentRE.match,
|
| 101 |
+
endmatch=endofthingRE.match,
|
| 102 |
+
):
|
| 103 |
+
self.skipwhite()
|
| 104 |
+
if self.pos >= self.len:
|
| 105 |
+
return None, None
|
| 106 |
+
pos = self.pos
|
| 107 |
+
buf = self.buf
|
| 108 |
+
char = bytechr(byteord(buf[pos]))
|
| 109 |
+
if char in ps_special:
|
| 110 |
+
if char in b"{}[]":
|
| 111 |
+
tokentype = "do_special"
|
| 112 |
+
token = char
|
| 113 |
+
elif char == b"%":
|
| 114 |
+
tokentype = "do_comment"
|
| 115 |
+
_, nextpos = commentmatch(buf, pos).span()
|
| 116 |
+
token = buf[pos:nextpos]
|
| 117 |
+
elif char == b"(":
|
| 118 |
+
tokentype = "do_string"
|
| 119 |
+
m = stringmatch(buf, pos)
|
| 120 |
+
if m is None:
|
| 121 |
+
raise PSTokenError("bad string at character %d" % pos)
|
| 122 |
+
_, nextpos = m.span()
|
| 123 |
+
token = buf[pos:nextpos]
|
| 124 |
+
elif char == b"<":
|
| 125 |
+
tokentype = "do_hexstring"
|
| 126 |
+
m = hexstringmatch(buf, pos)
|
| 127 |
+
if m is None:
|
| 128 |
+
raise PSTokenError("bad hexstring at character %d" % pos)
|
| 129 |
+
_, nextpos = m.span()
|
| 130 |
+
token = buf[pos:nextpos]
|
| 131 |
+
else:
|
| 132 |
+
raise PSTokenError("bad token at character %d" % pos)
|
| 133 |
+
else:
|
| 134 |
+
if char == b"/":
|
| 135 |
+
tokentype = "do_literal"
|
| 136 |
+
m = endmatch(buf, pos + 1)
|
| 137 |
+
else:
|
| 138 |
+
tokentype = ""
|
| 139 |
+
m = endmatch(buf, pos)
|
| 140 |
+
if m is None:
|
| 141 |
+
raise PSTokenError("bad token at character %d" % pos)
|
| 142 |
+
_, nextpos = m.span()
|
| 143 |
+
token = buf[pos:nextpos]
|
| 144 |
+
self.pos = pos + len(token)
|
| 145 |
+
token = tostr(token, encoding=self.encoding)
|
| 146 |
+
return tokentype, token
|
| 147 |
+
|
| 148 |
+
def skipwhite(self, whitematch=skipwhiteRE.match):
|
| 149 |
+
_, nextpos = whitematch(self.buf, self.pos).span()
|
| 150 |
+
self.pos = nextpos
|
| 151 |
+
|
| 152 |
+
def starteexec(self):
|
| 153 |
+
self.pos = self.pos + 1
|
| 154 |
+
self.dirtybuf = self.buf[self.pos :]
|
| 155 |
+
self.buf, R = eexec.decrypt(self.dirtybuf, 55665)
|
| 156 |
+
self.len = len(self.buf)
|
| 157 |
+
self.pos = 4
|
| 158 |
+
|
| 159 |
+
def stopeexec(self):
|
| 160 |
+
if not hasattr(self, "dirtybuf"):
|
| 161 |
+
return
|
| 162 |
+
self.buf = self.dirtybuf
|
| 163 |
+
del self.dirtybuf
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class PSInterpreter(PSOperators):
|
| 167 |
+
def __init__(self, encoding="ascii"):
|
| 168 |
+
systemdict = {}
|
| 169 |
+
userdict = {}
|
| 170 |
+
self.encoding = encoding
|
| 171 |
+
self.dictstack = [systemdict, userdict]
|
| 172 |
+
self.stack = []
|
| 173 |
+
self.proclevel = 0
|
| 174 |
+
self.procmark = ps_procmark()
|
| 175 |
+
self.fillsystemdict()
|
| 176 |
+
|
| 177 |
+
def fillsystemdict(self):
|
| 178 |
+
systemdict = self.dictstack[0]
|
| 179 |
+
systemdict["["] = systemdict["mark"] = self.mark = ps_mark()
|
| 180 |
+
systemdict["]"] = ps_operator("]", self.do_makearray)
|
| 181 |
+
systemdict["true"] = ps_boolean(1)
|
| 182 |
+
systemdict["false"] = ps_boolean(0)
|
| 183 |
+
systemdict["StandardEncoding"] = ps_array(ps_StandardEncoding)
|
| 184 |
+
systemdict["FontDirectory"] = ps_dict({})
|
| 185 |
+
self.suckoperators(systemdict, self.__class__)
|
| 186 |
+
|
| 187 |
+
def suckoperators(self, systemdict, klass):
|
| 188 |
+
for name in dir(klass):
|
| 189 |
+
attr = getattr(self, name)
|
| 190 |
+
if isinstance(attr, Callable) and name[:3] == "ps_":
|
| 191 |
+
name = name[3:]
|
| 192 |
+
systemdict[name] = ps_operator(name, attr)
|
| 193 |
+
for baseclass in klass.__bases__:
|
| 194 |
+
self.suckoperators(systemdict, baseclass)
|
| 195 |
+
|
| 196 |
+
def interpret(self, data, getattr=getattr):
|
| 197 |
+
tokenizer = self.tokenizer = PSTokenizer(data, self.encoding)
|
| 198 |
+
getnexttoken = tokenizer.getnexttoken
|
| 199 |
+
do_token = self.do_token
|
| 200 |
+
handle_object = self.handle_object
|
| 201 |
+
try:
|
| 202 |
+
while 1:
|
| 203 |
+
tokentype, token = getnexttoken()
|
| 204 |
+
if not token:
|
| 205 |
+
break
|
| 206 |
+
if tokentype:
|
| 207 |
+
handler = getattr(self, tokentype)
|
| 208 |
+
object = handler(token)
|
| 209 |
+
else:
|
| 210 |
+
object = do_token(token)
|
| 211 |
+
if object is not None:
|
| 212 |
+
handle_object(object)
|
| 213 |
+
tokenizer.close()
|
| 214 |
+
self.tokenizer = None
|
| 215 |
+
except:
|
| 216 |
+
if self.tokenizer is not None:
|
| 217 |
+
log.debug(
|
| 218 |
+
"ps error:\n"
|
| 219 |
+
"- - - - - - -\n"
|
| 220 |
+
"%s\n"
|
| 221 |
+
">>>\n"
|
| 222 |
+
"%s\n"
|
| 223 |
+
"- - - - - - -",
|
| 224 |
+
self.tokenizer.buf[self.tokenizer.pos - 50 : self.tokenizer.pos],
|
| 225 |
+
self.tokenizer.buf[self.tokenizer.pos : self.tokenizer.pos + 50],
|
| 226 |
+
)
|
| 227 |
+
raise
|
| 228 |
+
|
| 229 |
+
def handle_object(self, object):
|
| 230 |
+
if not (self.proclevel or object.literal or object.type == "proceduretype"):
|
| 231 |
+
if object.type != "operatortype":
|
| 232 |
+
object = self.resolve_name(object.value)
|
| 233 |
+
if object.literal:
|
| 234 |
+
self.push(object)
|
| 235 |
+
else:
|
| 236 |
+
if object.type == "proceduretype":
|
| 237 |
+
self.call_procedure(object)
|
| 238 |
+
else:
|
| 239 |
+
object.function()
|
| 240 |
+
else:
|
| 241 |
+
self.push(object)
|
| 242 |
+
|
| 243 |
+
def call_procedure(self, proc):
|
| 244 |
+
handle_object = self.handle_object
|
| 245 |
+
for item in proc.value:
|
| 246 |
+
handle_object(item)
|
| 247 |
+
|
| 248 |
+
def resolve_name(self, name):
|
| 249 |
+
dictstack = self.dictstack
|
| 250 |
+
for i in range(len(dictstack) - 1, -1, -1):
|
| 251 |
+
if name in dictstack[i]:
|
| 252 |
+
return dictstack[i][name]
|
| 253 |
+
raise PSError("name error: " + str(name))
|
| 254 |
+
|
| 255 |
+
def do_token(
|
| 256 |
+
self,
|
| 257 |
+
token,
|
| 258 |
+
int=int,
|
| 259 |
+
float=float,
|
| 260 |
+
ps_name=ps_name,
|
| 261 |
+
ps_integer=ps_integer,
|
| 262 |
+
ps_real=ps_real,
|
| 263 |
+
):
|
| 264 |
+
try:
|
| 265 |
+
num = int(token)
|
| 266 |
+
except (ValueError, OverflowError):
|
| 267 |
+
try:
|
| 268 |
+
num = float(token)
|
| 269 |
+
except (ValueError, OverflowError):
|
| 270 |
+
if "#" in token:
|
| 271 |
+
hashpos = token.find("#")
|
| 272 |
+
try:
|
| 273 |
+
base = int(token[:hashpos])
|
| 274 |
+
num = int(token[hashpos + 1 :], base)
|
| 275 |
+
except (ValueError, OverflowError):
|
| 276 |
+
return ps_name(token)
|
| 277 |
+
else:
|
| 278 |
+
return ps_integer(num)
|
| 279 |
+
else:
|
| 280 |
+
return ps_name(token)
|
| 281 |
+
else:
|
| 282 |
+
return ps_real(num)
|
| 283 |
+
else:
|
| 284 |
+
return ps_integer(num)
|
| 285 |
+
|
| 286 |
+
def do_comment(self, token):
|
| 287 |
+
pass
|
| 288 |
+
|
| 289 |
+
def do_literal(self, token):
|
| 290 |
+
return ps_literal(token[1:])
|
| 291 |
+
|
| 292 |
+
def do_string(self, token):
|
| 293 |
+
return ps_string(token[1:-1])
|
| 294 |
+
|
| 295 |
+
def do_hexstring(self, token):
|
| 296 |
+
hexStr = "".join(token[1:-1].split())
|
| 297 |
+
if len(hexStr) % 2:
|
| 298 |
+
hexStr = hexStr + "0"
|
| 299 |
+
cleanstr = []
|
| 300 |
+
for i in range(0, len(hexStr), 2):
|
| 301 |
+
cleanstr.append(chr(int(hexStr[i : i + 2], 16)))
|
| 302 |
+
cleanstr = "".join(cleanstr)
|
| 303 |
+
return ps_string(cleanstr)
|
| 304 |
+
|
| 305 |
+
def do_special(self, token):
|
| 306 |
+
if token == "{":
|
| 307 |
+
self.proclevel = self.proclevel + 1
|
| 308 |
+
return self.procmark
|
| 309 |
+
elif token == "}":
|
| 310 |
+
proc = []
|
| 311 |
+
while 1:
|
| 312 |
+
topobject = self.pop()
|
| 313 |
+
if topobject == self.procmark:
|
| 314 |
+
break
|
| 315 |
+
proc.append(topobject)
|
| 316 |
+
self.proclevel = self.proclevel - 1
|
| 317 |
+
proc.reverse()
|
| 318 |
+
return ps_procedure(proc)
|
| 319 |
+
elif token == "[":
|
| 320 |
+
return self.mark
|
| 321 |
+
elif token == "]":
|
| 322 |
+
return ps_name("]")
|
| 323 |
+
else:
|
| 324 |
+
raise PSTokenError("huh?")
|
| 325 |
+
|
| 326 |
+
def push(self, object):
|
| 327 |
+
self.stack.append(object)
|
| 328 |
+
|
| 329 |
+
def pop(self, *types):
|
| 330 |
+
stack = self.stack
|
| 331 |
+
if not stack:
|
| 332 |
+
raise PSError("stack underflow")
|
| 333 |
+
object = stack[-1]
|
| 334 |
+
if types:
|
| 335 |
+
if object.type not in types:
|
| 336 |
+
raise PSError(
|
| 337 |
+
"typecheck, expected %s, found %s" % (repr(types), object.type)
|
| 338 |
+
)
|
| 339 |
+
del stack[-1]
|
| 340 |
+
return object
|
| 341 |
+
|
| 342 |
+
def do_makearray(self):
|
| 343 |
+
array = []
|
| 344 |
+
while 1:
|
| 345 |
+
topobject = self.pop()
|
| 346 |
+
if topobject == self.mark:
|
| 347 |
+
break
|
| 348 |
+
array.append(topobject)
|
| 349 |
+
array.reverse()
|
| 350 |
+
self.push(ps_array(array))
|
| 351 |
+
|
| 352 |
+
def close(self):
|
| 353 |
+
"""Remove circular references."""
|
| 354 |
+
del self.stack
|
| 355 |
+
del self.dictstack
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def unpack_item(item):
|
| 359 |
+
tp = type(item.value)
|
| 360 |
+
if tp == dict:
|
| 361 |
+
newitem = {}
|
| 362 |
+
for key, value in item.value.items():
|
| 363 |
+
newitem[key] = unpack_item(value)
|
| 364 |
+
elif tp == list:
|
| 365 |
+
newitem = [None] * len(item.value)
|
| 366 |
+
for i in range(len(item.value)):
|
| 367 |
+
newitem[i] = unpack_item(item.value[i])
|
| 368 |
+
if item.type == "proceduretype":
|
| 369 |
+
newitem = tuple(newitem)
|
| 370 |
+
else:
|
| 371 |
+
newitem = item.value
|
| 372 |
+
return newitem
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def suckfont(data, encoding="ascii"):
|
| 376 |
+
m = re.search(rb"/FontName\s+/([^ \t\n\r]+)\s+def", data)
|
| 377 |
+
if m:
|
| 378 |
+
fontName = m.group(1)
|
| 379 |
+
fontName = fontName.decode()
|
| 380 |
+
else:
|
| 381 |
+
fontName = None
|
| 382 |
+
interpreter = PSInterpreter(encoding=encoding)
|
| 383 |
+
interpreter.interpret(
|
| 384 |
+
b"/Helvetica 4 dict dup /Encoding StandardEncoding put definefont pop"
|
| 385 |
+
)
|
| 386 |
+
interpreter.interpret(data)
|
| 387 |
+
fontdir = interpreter.dictstack[0]["FontDirectory"].value
|
| 388 |
+
if fontName in fontdir:
|
| 389 |
+
rawfont = fontdir[fontName]
|
| 390 |
+
else:
|
| 391 |
+
# fall back, in case fontName wasn't found
|
| 392 |
+
fontNames = list(fontdir.keys())
|
| 393 |
+
if len(fontNames) > 1:
|
| 394 |
+
fontNames.remove("Helvetica")
|
| 395 |
+
fontNames.sort()
|
| 396 |
+
rawfont = fontdir[fontNames[0]]
|
| 397 |
+
interpreter.close()
|
| 398 |
+
return unpack_item(rawfont)
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/py23.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Python 2/3 compat layer leftovers."""
|
| 2 |
+
|
| 3 |
+
import decimal as _decimal
|
| 4 |
+
import math as _math
|
| 5 |
+
import warnings
|
| 6 |
+
from contextlib import redirect_stderr, redirect_stdout
|
| 7 |
+
from io import BytesIO
|
| 8 |
+
from io import StringIO as UnicodeIO
|
| 9 |
+
from types import SimpleNamespace
|
| 10 |
+
|
| 11 |
+
from .textTools import Tag, bytechr, byteord, bytesjoin, strjoin, tobytes, tostr
|
| 12 |
+
|
| 13 |
+
warnings.warn(
|
| 14 |
+
"The py23 module has been deprecated and will be removed in a future release. "
|
| 15 |
+
"Please update your code.",
|
| 16 |
+
DeprecationWarning,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
"basestring",
|
| 21 |
+
"bytechr",
|
| 22 |
+
"byteord",
|
| 23 |
+
"BytesIO",
|
| 24 |
+
"bytesjoin",
|
| 25 |
+
"open",
|
| 26 |
+
"Py23Error",
|
| 27 |
+
"range",
|
| 28 |
+
"RecursionError",
|
| 29 |
+
"round",
|
| 30 |
+
"SimpleNamespace",
|
| 31 |
+
"StringIO",
|
| 32 |
+
"strjoin",
|
| 33 |
+
"Tag",
|
| 34 |
+
"tobytes",
|
| 35 |
+
"tostr",
|
| 36 |
+
"tounicode",
|
| 37 |
+
"unichr",
|
| 38 |
+
"unicode",
|
| 39 |
+
"UnicodeIO",
|
| 40 |
+
"xrange",
|
| 41 |
+
"zip",
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class Py23Error(NotImplementedError):
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
RecursionError = RecursionError
|
| 50 |
+
StringIO = UnicodeIO
|
| 51 |
+
|
| 52 |
+
basestring = str
|
| 53 |
+
isclose = _math.isclose
|
| 54 |
+
isfinite = _math.isfinite
|
| 55 |
+
open = open
|
| 56 |
+
range = range
|
| 57 |
+
round = round3 = round
|
| 58 |
+
unichr = chr
|
| 59 |
+
unicode = str
|
| 60 |
+
zip = zip
|
| 61 |
+
|
| 62 |
+
tounicode = tostr
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def xrange(*args, **kwargs):
|
| 66 |
+
raise Py23Error("'xrange' is not defined. Use 'range' instead.")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def round2(number, ndigits=None):
|
| 70 |
+
"""
|
| 71 |
+
Implementation of Python 2 built-in round() function.
|
| 72 |
+
Rounds a number to a given precision in decimal digits (default
|
| 73 |
+
0 digits). The result is a floating point number. Values are rounded
|
| 74 |
+
to the closest multiple of 10 to the power minus ndigits; if two
|
| 75 |
+
multiples are equally close, rounding is done away from 0.
|
| 76 |
+
ndigits may be negative.
|
| 77 |
+
See Python 2 documentation:
|
| 78 |
+
https://docs.python.org/2/library/functions.html?highlight=round#round
|
| 79 |
+
"""
|
| 80 |
+
if ndigits is None:
|
| 81 |
+
ndigits = 0
|
| 82 |
+
|
| 83 |
+
if ndigits < 0:
|
| 84 |
+
exponent = 10 ** (-ndigits)
|
| 85 |
+
quotient, remainder = divmod(number, exponent)
|
| 86 |
+
if remainder >= exponent // 2 and number >= 0:
|
| 87 |
+
quotient += 1
|
| 88 |
+
return float(quotient * exponent)
|
| 89 |
+
else:
|
| 90 |
+
exponent = _decimal.Decimal("10") ** (-ndigits)
|
| 91 |
+
|
| 92 |
+
d = _decimal.Decimal.from_float(number).quantize(
|
| 93 |
+
exponent, rounding=_decimal.ROUND_HALF_UP
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
return float(d)
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/roundTools.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Various round-to-integer helpers.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
import functools
|
| 7 |
+
import logging
|
| 8 |
+
|
| 9 |
+
log = logging.getLogger(__name__)
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"noRound",
|
| 13 |
+
"otRound",
|
| 14 |
+
"maybeRound",
|
| 15 |
+
"roundFunc",
|
| 16 |
+
"nearestMultipleShortestRepr",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def noRound(value):
|
| 21 |
+
return value
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def otRound(value):
|
| 25 |
+
"""Round float value to nearest integer towards ``+Infinity``.
|
| 26 |
+
|
| 27 |
+
The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_)
|
| 28 |
+
defines the required method for converting floating point values to
|
| 29 |
+
fixed-point. In particular it specifies the following rounding strategy:
|
| 30 |
+
|
| 31 |
+
for fractional values of 0.5 and higher, take the next higher integer;
|
| 32 |
+
for other fractional values, truncate.
|
| 33 |
+
|
| 34 |
+
This function rounds the floating-point value according to this strategy
|
| 35 |
+
in preparation for conversion to fixed-point.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
value (float): The input floating-point value.
|
| 39 |
+
|
| 40 |
+
Returns
|
| 41 |
+
float: The rounded value.
|
| 42 |
+
"""
|
| 43 |
+
# See this thread for how we ended up with this implementation:
|
| 44 |
+
# https://github.com/fonttools/fonttools/issues/1248#issuecomment-383198166
|
| 45 |
+
return int(math.floor(value + 0.5))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def maybeRound(v, tolerance, round=otRound):
|
| 49 |
+
rounded = round(v)
|
| 50 |
+
return rounded if abs(rounded - v) <= tolerance else v
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def roundFunc(tolerance, round=otRound):
|
| 54 |
+
if tolerance < 0:
|
| 55 |
+
raise ValueError("Rounding tolerance must be positive")
|
| 56 |
+
|
| 57 |
+
if tolerance == 0:
|
| 58 |
+
return noRound
|
| 59 |
+
|
| 60 |
+
if tolerance >= 0.5:
|
| 61 |
+
return round
|
| 62 |
+
|
| 63 |
+
return functools.partial(maybeRound, tolerance=tolerance, round=round)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def nearestMultipleShortestRepr(value: float, factor: float) -> str:
|
| 67 |
+
"""Round to nearest multiple of factor and return shortest decimal representation.
|
| 68 |
+
|
| 69 |
+
This chooses the float that is closer to a multiple of the given factor while
|
| 70 |
+
having the shortest decimal representation (the least number of fractional decimal
|
| 71 |
+
digits).
|
| 72 |
+
|
| 73 |
+
For example, given the following:
|
| 74 |
+
|
| 75 |
+
>>> nearestMultipleShortestRepr(-0.61883544921875, 1.0/(1<<14))
|
| 76 |
+
'-0.61884'
|
| 77 |
+
|
| 78 |
+
Useful when you need to serialize or print a fixed-point number (or multiples
|
| 79 |
+
thereof, such as F2Dot14 fractions of 180 degrees in COLRv1 PaintRotate) in
|
| 80 |
+
a human-readable form.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
value (value): The value to be rounded and serialized.
|
| 84 |
+
factor (float): The value which the result is a close multiple of.
|
| 85 |
+
|
| 86 |
+
Returns:
|
| 87 |
+
str: A compact string representation of the value.
|
| 88 |
+
"""
|
| 89 |
+
if not value:
|
| 90 |
+
return "0.0"
|
| 91 |
+
|
| 92 |
+
value = otRound(value / factor) * factor
|
| 93 |
+
eps = 0.5 * factor
|
| 94 |
+
lo = value - eps
|
| 95 |
+
hi = value + eps
|
| 96 |
+
# If the range of valid choices spans an integer, return the integer.
|
| 97 |
+
if int(lo) != int(hi):
|
| 98 |
+
return str(float(round(value)))
|
| 99 |
+
|
| 100 |
+
fmt = "%.8f"
|
| 101 |
+
lo = fmt % lo
|
| 102 |
+
hi = fmt % hi
|
| 103 |
+
assert len(lo) == len(hi) and lo != hi
|
| 104 |
+
for i in range(len(lo)):
|
| 105 |
+
if lo[i] != hi[i]:
|
| 106 |
+
break
|
| 107 |
+
period = lo.find(".")
|
| 108 |
+
assert period < i
|
| 109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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.pens.basePen import BasePen
|
| 2 |
+
from functools import partial
|
| 3 |
+
from itertools import count
|
| 4 |
+
import sympy as sp
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
n = 3 # Max Bezier degree; 3 for cubic, 2 for quadratic
|
| 8 |
+
|
| 9 |
+
t, x, y = sp.symbols("t x y", real=True)
|
| 10 |
+
c = sp.symbols("c", real=False) # Complex representation instead of x/y
|
| 11 |
+
|
| 12 |
+
X = tuple(sp.symbols("x:%d" % (n + 1), real=True))
|
| 13 |
+
Y = tuple(sp.symbols("y:%d" % (n + 1), real=True))
|
| 14 |
+
P = tuple(zip(*(sp.symbols("p:%d[%s]" % (n + 1, w), real=True) for w in "01")))
|
| 15 |
+
C = tuple(sp.symbols("c:%d" % (n + 1), real=False))
|
| 16 |
+
|
| 17 |
+
# Cubic Bernstein basis functions
|
| 18 |
+
BinomialCoefficient = [(1, 0)]
|
| 19 |
+
for i in range(1, n + 1):
|
| 20 |
+
last = BinomialCoefficient[-1]
|
| 21 |
+
this = tuple(last[j - 1] + last[j] for j in range(len(last))) + (0,)
|
| 22 |
+
BinomialCoefficient.append(this)
|
| 23 |
+
BinomialCoefficient = tuple(tuple(item[:-1]) for item in BinomialCoefficient)
|
| 24 |
+
del last, this
|
| 25 |
+
|
| 26 |
+
BernsteinPolynomial = tuple(
|
| 27 |
+
tuple(c * t**i * (1 - t) ** (n - i) for i, c in enumerate(coeffs))
|
| 28 |
+
for n, coeffs in enumerate(BinomialCoefficient)
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
BezierCurve = tuple(
|
| 32 |
+
tuple(
|
| 33 |
+
sum(P[i][j] * bernstein for i, bernstein in enumerate(bernsteins))
|
| 34 |
+
for j in range(2)
|
| 35 |
+
)
|
| 36 |
+
for n, bernsteins in enumerate(BernsteinPolynomial)
|
| 37 |
+
)
|
| 38 |
+
BezierCurveC = tuple(
|
| 39 |
+
sum(C[i] * bernstein for i, bernstein in enumerate(bernsteins))
|
| 40 |
+
for n, bernsteins in enumerate(BernsteinPolynomial)
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def green(f, curveXY):
|
| 45 |
+
f = -sp.integrate(sp.sympify(f), y)
|
| 46 |
+
f = f.subs({x: curveXY[0], y: curveXY[1]})
|
| 47 |
+
f = sp.integrate(f * sp.diff(curveXY[0], t), (t, 0, 1))
|
| 48 |
+
return f
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class _BezierFuncsLazy(dict):
|
| 52 |
+
def __init__(self, symfunc):
|
| 53 |
+
self._symfunc = symfunc
|
| 54 |
+
self._bezfuncs = {}
|
| 55 |
+
|
| 56 |
+
def __missing__(self, i):
|
| 57 |
+
args = ["p%d" % d for d in range(i + 1)]
|
| 58 |
+
f = green(self._symfunc, BezierCurve[i])
|
| 59 |
+
f = sp.gcd_terms(f.collect(sum(P, ()))) # Optimize
|
| 60 |
+
return sp.lambdify(args, f)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class GreenPen(BasePen):
|
| 64 |
+
_BezierFuncs = {}
|
| 65 |
+
|
| 66 |
+
@classmethod
|
| 67 |
+
def _getGreenBezierFuncs(celf, func):
|
| 68 |
+
funcstr = str(func)
|
| 69 |
+
if not funcstr in celf._BezierFuncs:
|
| 70 |
+
celf._BezierFuncs[funcstr] = _BezierFuncsLazy(func)
|
| 71 |
+
return celf._BezierFuncs[funcstr]
|
| 72 |
+
|
| 73 |
+
def __init__(self, func, glyphset=None):
|
| 74 |
+
BasePen.__init__(self, glyphset)
|
| 75 |
+
self._funcs = self._getGreenBezierFuncs(func)
|
| 76 |
+
self.value = 0
|
| 77 |
+
|
| 78 |
+
def _moveTo(self, p0):
|
| 79 |
+
self._startPoint = p0
|
| 80 |
+
|
| 81 |
+
def _closePath(self):
|
| 82 |
+
p0 = self._getCurrentPoint()
|
| 83 |
+
if p0 != self._startPoint:
|
| 84 |
+
self._lineTo(self._startPoint)
|
| 85 |
+
|
| 86 |
+
def _endPath(self):
|
| 87 |
+
p0 = self._getCurrentPoint()
|
| 88 |
+
if p0 != self._startPoint:
|
| 89 |
+
# Green theorem is not defined on open contours.
|
| 90 |
+
raise NotImplementedError
|
| 91 |
+
|
| 92 |
+
def _lineTo(self, p1):
|
| 93 |
+
p0 = self._getCurrentPoint()
|
| 94 |
+
self.value += self._funcs[1](p0, p1)
|
| 95 |
+
|
| 96 |
+
def _qCurveToOne(self, p1, p2):
|
| 97 |
+
p0 = self._getCurrentPoint()
|
| 98 |
+
self.value += self._funcs[2](p0, p1, p2)
|
| 99 |
+
|
| 100 |
+
def _curveToOne(self, p1, p2, p3):
|
| 101 |
+
p0 = self._getCurrentPoint()
|
| 102 |
+
self.value += self._funcs[3](p0, p1, p2, p3)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# Sample pens.
|
| 106 |
+
# Do not use this in real code.
|
| 107 |
+
# Use fontTools.pens.momentsPen.MomentsPen instead.
|
| 108 |
+
AreaPen = partial(GreenPen, func=1)
|
| 109 |
+
MomentXPen = partial(GreenPen, func=x)
|
| 110 |
+
MomentYPen = partial(GreenPen, func=y)
|
| 111 |
+
MomentXXPen = partial(GreenPen, func=x * x)
|
| 112 |
+
MomentYYPen = partial(GreenPen, func=y * y)
|
| 113 |
+
MomentXYPen = partial(GreenPen, func=x * y)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def printGreenPen(penName, funcs, file=sys.stdout, docstring=None):
|
| 117 |
+
if docstring is not None:
|
| 118 |
+
print('"""%s"""' % docstring)
|
| 119 |
+
|
| 120 |
+
print(
|
| 121 |
+
"""from fontTools.pens.basePen import BasePen, OpenContourError
|
| 122 |
+
try:
|
| 123 |
+
import cython
|
| 124 |
+
|
| 125 |
+
COMPILED = cython.compiled
|
| 126 |
+
except (AttributeError, ImportError):
|
| 127 |
+
# if cython not installed, use mock module with no-op decorators and types
|
| 128 |
+
from fontTools.misc import cython
|
| 129 |
+
|
| 130 |
+
COMPILED = False
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
__all__ = ["%s"]
|
| 134 |
+
|
| 135 |
+
class %s(BasePen):
|
| 136 |
+
|
| 137 |
+
def __init__(self, glyphset=None):
|
| 138 |
+
BasePen.__init__(self, glyphset)
|
| 139 |
+
"""
|
| 140 |
+
% (penName, penName),
|
| 141 |
+
file=file,
|
| 142 |
+
)
|
| 143 |
+
for name, f in funcs:
|
| 144 |
+
print(" self.%s = 0" % name, file=file)
|
| 145 |
+
print(
|
| 146 |
+
"""
|
| 147 |
+
def _moveTo(self, p0):
|
| 148 |
+
self._startPoint = p0
|
| 149 |
+
|
| 150 |
+
def _closePath(self):
|
| 151 |
+
p0 = self._getCurrentPoint()
|
| 152 |
+
if p0 != self._startPoint:
|
| 153 |
+
self._lineTo(self._startPoint)
|
| 154 |
+
|
| 155 |
+
def _endPath(self):
|
| 156 |
+
p0 = self._getCurrentPoint()
|
| 157 |
+
if p0 != self._startPoint:
|
| 158 |
+
raise OpenContourError(
|
| 159 |
+
"Glyph statistics is not defined on open contours."
|
| 160 |
+
)
|
| 161 |
+
""",
|
| 162 |
+
end="",
|
| 163 |
+
file=file,
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
for n in (1, 2, 3):
|
| 167 |
+
subs = {P[i][j]: [X, Y][j][i] for i in range(n + 1) for j in range(2)}
|
| 168 |
+
greens = [green(f, BezierCurve[n]) for name, f in funcs]
|
| 169 |
+
greens = [sp.gcd_terms(f.collect(sum(P, ()))) for f in greens] # Optimize
|
| 170 |
+
greens = [f.subs(subs) for f in greens] # Convert to p to x/y
|
| 171 |
+
defs, exprs = sp.cse(
|
| 172 |
+
greens,
|
| 173 |
+
optimizations="basic",
|
| 174 |
+
symbols=(sp.Symbol("r%d" % i) for i in count()),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
print()
|
| 178 |
+
for name, value in defs:
|
| 179 |
+
print(" @cython.locals(%s=cython.double)" % name, file=file)
|
| 180 |
+
if n == 1:
|
| 181 |
+
print(
|
| 182 |
+
"""\
|
| 183 |
+
@cython.locals(x0=cython.double, y0=cython.double)
|
| 184 |
+
@cython.locals(x1=cython.double, y1=cython.double)
|
| 185 |
+
def _lineTo(self, p1):
|
| 186 |
+
x0,y0 = self._getCurrentPoint()
|
| 187 |
+
x1,y1 = p1
|
| 188 |
+
""",
|
| 189 |
+
file=file,
|
| 190 |
+
)
|
| 191 |
+
elif n == 2:
|
| 192 |
+
print(
|
| 193 |
+
"""\
|
| 194 |
+
@cython.locals(x0=cython.double, y0=cython.double)
|
| 195 |
+
@cython.locals(x1=cython.double, y1=cython.double)
|
| 196 |
+
@cython.locals(x2=cython.double, y2=cython.double)
|
| 197 |
+
def _qCurveToOne(self, p1, p2):
|
| 198 |
+
x0,y0 = self._getCurrentPoint()
|
| 199 |
+
x1,y1 = p1
|
| 200 |
+
x2,y2 = p2
|
| 201 |
+
""",
|
| 202 |
+
file=file,
|
| 203 |
+
)
|
| 204 |
+
elif n == 3:
|
| 205 |
+
print(
|
| 206 |
+
"""\
|
| 207 |
+
@cython.locals(x0=cython.double, y0=cython.double)
|
| 208 |
+
@cython.locals(x1=cython.double, y1=cython.double)
|
| 209 |
+
@cython.locals(x2=cython.double, y2=cython.double)
|
| 210 |
+
@cython.locals(x3=cython.double, y3=cython.double)
|
| 211 |
+
def _curveToOne(self, p1, p2, p3):
|
| 212 |
+
x0,y0 = self._getCurrentPoint()
|
| 213 |
+
x1,y1 = p1
|
| 214 |
+
x2,y2 = p2
|
| 215 |
+
x3,y3 = p3
|
| 216 |
+
""",
|
| 217 |
+
file=file,
|
| 218 |
+
)
|
| 219 |
+
for name, value in defs:
|
| 220 |
+
print(" %s = %s" % (name, value), file=file)
|
| 221 |
+
|
| 222 |
+
print(file=file)
|
| 223 |
+
for name, value in zip([f[0] for f in funcs], exprs):
|
| 224 |
+
print(" self.%s += %s" % (name, value), file=file)
|
| 225 |
+
|
| 226 |
+
print(
|
| 227 |
+
"""
|
| 228 |
+
if __name__ == '__main__':
|
| 229 |
+
from fontTools.misc.symfont import x, y, printGreenPen
|
| 230 |
+
printGreenPen('%s', ["""
|
| 231 |
+
% penName,
|
| 232 |
+
file=file,
|
| 233 |
+
)
|
| 234 |
+
for name, f in funcs:
|
| 235 |
+
print(" ('%s', %s)," % (name, str(f)), file=file)
|
| 236 |
+
print(" ])", file=file)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
if __name__ == "__main__":
|
| 240 |
+
pen = AreaPen()
|
| 241 |
+
pen.moveTo((100, 100))
|
| 242 |
+
pen.lineTo((100, 200))
|
| 243 |
+
pen.lineTo((200, 200))
|
| 244 |
+
pen.curveTo((200, 250), (300, 300), (250, 350))
|
| 245 |
+
pen.lineTo((200, 100))
|
| 246 |
+
pen.closePath()
|
| 247 |
+
print(pen.value)
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/textTools.py
ADDED
|
@@ -0,0 +1,154 @@
|
|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| 7 |
+
# alias kept for backward compatibility
|
| 8 |
+
safeEval = ast.literal_eval
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Tag(str):
|
| 12 |
+
@staticmethod
|
| 13 |
+
def transcode(blob):
|
| 14 |
+
if isinstance(blob, bytes):
|
| 15 |
+
blob = blob.decode("latin-1")
|
| 16 |
+
return blob
|
| 17 |
+
|
| 18 |
+
def __new__(self, content):
|
| 19 |
+
return str.__new__(self, self.transcode(content))
|
| 20 |
+
|
| 21 |
+
def __ne__(self, other):
|
| 22 |
+
return not self.__eq__(other)
|
| 23 |
+
|
| 24 |
+
def __eq__(self, other):
|
| 25 |
+
return str.__eq__(self, self.transcode(other))
|
| 26 |
+
|
| 27 |
+
def __hash__(self):
|
| 28 |
+
return str.__hash__(self)
|
| 29 |
+
|
| 30 |
+
def tobytes(self):
|
| 31 |
+
return self.encode("latin-1")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def readHex(content):
|
| 35 |
+
"""Convert a list of hex strings to binary data."""
|
| 36 |
+
return deHexStr(strjoin(chunk for chunk in content if isinstance(chunk, str)))
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def deHexStr(hexdata):
|
| 40 |
+
"""Convert a hex string to binary data."""
|
| 41 |
+
hexdata = strjoin(hexdata.split())
|
| 42 |
+
if len(hexdata) % 2:
|
| 43 |
+
hexdata = hexdata + "0"
|
| 44 |
+
data = []
|
| 45 |
+
for i in range(0, len(hexdata), 2):
|
| 46 |
+
data.append(bytechr(int(hexdata[i : i + 2], 16)))
|
| 47 |
+
return bytesjoin(data)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def hexStr(data):
|
| 51 |
+
"""Convert binary data to a hex string."""
|
| 52 |
+
h = string.hexdigits
|
| 53 |
+
r = ""
|
| 54 |
+
for c in data:
|
| 55 |
+
i = byteord(c)
|
| 56 |
+
r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
|
| 57 |
+
return r
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def num2binary(l, bits=32):
|
| 61 |
+
items = []
|
| 62 |
+
binary = ""
|
| 63 |
+
for i in range(bits):
|
| 64 |
+
if l & 0x1:
|
| 65 |
+
binary = "1" + binary
|
| 66 |
+
else:
|
| 67 |
+
binary = "0" + binary
|
| 68 |
+
l = l >> 1
|
| 69 |
+
if not ((i + 1) % 8):
|
| 70 |
+
items.append(binary)
|
| 71 |
+
binary = ""
|
| 72 |
+
if binary:
|
| 73 |
+
items.append(binary)
|
| 74 |
+
items.reverse()
|
| 75 |
+
assert l in (0, -1), "number doesn't fit in number of bits"
|
| 76 |
+
return " ".join(items)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def binary2num(bin):
|
| 80 |
+
bin = strjoin(bin.split())
|
| 81 |
+
l = 0
|
| 82 |
+
for digit in bin:
|
| 83 |
+
l = l << 1
|
| 84 |
+
if digit != "0":
|
| 85 |
+
l = l | 0x1
|
| 86 |
+
return l
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def caselessSort(alist):
|
| 90 |
+
"""Return a sorted copy of a list. If there are only strings
|
| 91 |
+
in the list, it will not consider case.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
try:
|
| 95 |
+
return sorted(alist, key=lambda a: (a.lower(), a))
|
| 96 |
+
except TypeError:
|
| 97 |
+
return sorted(alist)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def pad(data, size):
|
| 101 |
+
r"""Pad byte string 'data' with null bytes until its length is a
|
| 102 |
+
multiple of 'size'.
|
| 103 |
+
|
| 104 |
+
>>> len(pad(b'abcd', 4))
|
| 105 |
+
4
|
| 106 |
+
>>> len(pad(b'abcde', 2))
|
| 107 |
+
6
|
| 108 |
+
>>> len(pad(b'abcde', 4))
|
| 109 |
+
8
|
| 110 |
+
>>> pad(b'abcdef', 4) == b'abcdef\x00\x00'
|
| 111 |
+
True
|
| 112 |
+
"""
|
| 113 |
+
data = tobytes(data)
|
| 114 |
+
if size > 1:
|
| 115 |
+
remainder = len(data) % size
|
| 116 |
+
if remainder:
|
| 117 |
+
data += b"\0" * (size - remainder)
|
| 118 |
+
return data
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def tostr(s, encoding="ascii", errors="strict"):
|
| 122 |
+
if not isinstance(s, str):
|
| 123 |
+
return s.decode(encoding, errors)
|
| 124 |
+
else:
|
| 125 |
+
return s
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def tobytes(s, encoding="ascii", errors="strict"):
|
| 129 |
+
if isinstance(s, str):
|
| 130 |
+
return s.encode(encoding, errors)
|
| 131 |
+
else:
|
| 132 |
+
return bytes(s)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def bytechr(n):
|
| 136 |
+
return bytes([n])
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def byteord(c):
|
| 140 |
+
return c if isinstance(c, int) else ord(c)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def strjoin(iterable, joiner=""):
|
| 144 |
+
return tostr(joiner).join(iterable)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def bytesjoin(iterable, joiner=b""):
|
| 148 |
+
return tobytes(joiner).join(tobytes(item) for item in iterable)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
import doctest, sys
|
| 153 |
+
|
| 154 |
+
sys.exit(doctest.testmod().failed)
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/timeTools.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""fontTools.misc.timeTools.py -- tools for working with OpenType timestamps.
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
import calendar
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
epoch_diff = calendar.timegm((1904, 1, 1, 0, 0, 0, 0, 0, 0))
|
| 11 |
+
|
| 12 |
+
DAYNAMES = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
| 13 |
+
MONTHNAMES = [
|
| 14 |
+
None,
|
| 15 |
+
"Jan",
|
| 16 |
+
"Feb",
|
| 17 |
+
"Mar",
|
| 18 |
+
"Apr",
|
| 19 |
+
"May",
|
| 20 |
+
"Jun",
|
| 21 |
+
"Jul",
|
| 22 |
+
"Aug",
|
| 23 |
+
"Sep",
|
| 24 |
+
"Oct",
|
| 25 |
+
"Nov",
|
| 26 |
+
"Dec",
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def asctime(t=None):
|
| 31 |
+
"""
|
| 32 |
+
Convert a tuple or struct_time representing a time as returned by gmtime()
|
| 33 |
+
or localtime() to a 24-character string of the following form:
|
| 34 |
+
|
| 35 |
+
>>> asctime(time.gmtime(0))
|
| 36 |
+
'Thu Jan 1 00:00:00 1970'
|
| 37 |
+
|
| 38 |
+
If t is not provided, the current time as returned by localtime() is used.
|
| 39 |
+
Locale information is not used by asctime().
|
| 40 |
+
|
| 41 |
+
This is meant to normalise the output of the built-in time.asctime() across
|
| 42 |
+
different platforms and Python versions.
|
| 43 |
+
In Python 3.x, the day of the month is right-justified, whereas on Windows
|
| 44 |
+
Python 2.7 it is padded with zeros.
|
| 45 |
+
|
| 46 |
+
See https://github.com/fonttools/fonttools/issues/455
|
| 47 |
+
"""
|
| 48 |
+
if t is None:
|
| 49 |
+
t = time.localtime()
|
| 50 |
+
s = "%s %s %2s %s" % (
|
| 51 |
+
DAYNAMES[t.tm_wday],
|
| 52 |
+
MONTHNAMES[t.tm_mon],
|
| 53 |
+
t.tm_mday,
|
| 54 |
+
time.strftime("%H:%M:%S %Y", t),
|
| 55 |
+
)
|
| 56 |
+
return s
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def timestampToString(value):
|
| 60 |
+
return asctime(time.gmtime(max(0, value + epoch_diff)))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def timestampFromString(value):
|
| 64 |
+
wkday, mnth = value[:7].split()
|
| 65 |
+
t = datetime.strptime(value[7:], " %d %H:%M:%S %Y")
|
| 66 |
+
t = t.replace(month=MONTHNAMES.index(mnth), tzinfo=timezone.utc)
|
| 67 |
+
wkday_idx = DAYNAMES.index(wkday)
|
| 68 |
+
assert t.weekday() == wkday_idx, '"' + value + '" has inconsistent weekday'
|
| 69 |
+
return int(t.timestamp()) - epoch_diff
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def timestampNow():
|
| 73 |
+
# https://reproducible-builds.org/specs/source-date-epoch/
|
| 74 |
+
source_date_epoch = os.environ.get("SOURCE_DATE_EPOCH")
|
| 75 |
+
if source_date_epoch is not None:
|
| 76 |
+
return int(source_date_epoch) - epoch_diff
|
| 77 |
+
return int(time.time() - epoch_diff)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def timestampSinceEpoch(value):
|
| 81 |
+
return int(value - epoch_diff)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
if __name__ == "__main__":
|
| 85 |
+
import sys
|
| 86 |
+
import doctest
|
| 87 |
+
|
| 88 |
+
sys.exit(doctest.testmod().failed)
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/treeTools.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generic tools for working with trees."""
|
| 2 |
+
|
| 3 |
+
from math import ceil, log
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def build_n_ary_tree(leaves, n):
|
| 7 |
+
"""Build N-ary tree from sequence of leaf nodes.
|
| 8 |
+
|
| 9 |
+
Return a list of lists where each non-leaf node is a list containing
|
| 10 |
+
max n nodes.
|
| 11 |
+
"""
|
| 12 |
+
if not leaves:
|
| 13 |
+
return []
|
| 14 |
+
|
| 15 |
+
assert n > 1
|
| 16 |
+
|
| 17 |
+
depth = ceil(log(len(leaves), n))
|
| 18 |
+
|
| 19 |
+
if depth <= 1:
|
| 20 |
+
return list(leaves)
|
| 21 |
+
|
| 22 |
+
# Fully populate complete subtrees of root until we have enough leaves left
|
| 23 |
+
root = []
|
| 24 |
+
unassigned = None
|
| 25 |
+
full_step = n ** (depth - 1)
|
| 26 |
+
for i in range(0, len(leaves), full_step):
|
| 27 |
+
subtree = leaves[i : i + full_step]
|
| 28 |
+
if len(subtree) < full_step:
|
| 29 |
+
unassigned = subtree
|
| 30 |
+
break
|
| 31 |
+
while len(subtree) > n:
|
| 32 |
+
subtree = [subtree[k : k + n] for k in range(0, len(subtree), n)]
|
| 33 |
+
root.append(subtree)
|
| 34 |
+
|
| 35 |
+
if unassigned:
|
| 36 |
+
# Recurse to fill the last subtree, which is the only partially populated one
|
| 37 |
+
subtree = build_n_ary_tree(unassigned, n)
|
| 38 |
+
if len(subtree) <= n - len(root):
|
| 39 |
+
# replace last subtree with its children if they can still fit
|
| 40 |
+
root.extend(subtree)
|
| 41 |
+
else:
|
| 42 |
+
root.append(subtree)
|
| 43 |
+
assert len(root) <= n
|
| 44 |
+
|
| 45 |
+
return root
|
evalkit_tf437/lib/python3.10/site-packages/fontTools/misc/vector.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numbers import Number
|
| 2 |
+
import math
|
| 3 |
+
import operator
|
| 4 |
+
import warnings
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = ["Vector"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Vector(tuple):
|
| 11 |
+
"""A math-like vector.
|
| 12 |
+
|
| 13 |
+
Represents an n-dimensional numeric vector. ``Vector`` objects support
|
| 14 |
+
vector addition and subtraction, scalar multiplication and division,
|
| 15 |
+
negation, rounding, and comparison tests.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
__slots__ = ()
|
| 19 |
+
|
| 20 |
+
def __new__(cls, values, keep=False):
|
| 21 |
+
if keep is not False:
|
| 22 |
+
warnings.warn(
|
| 23 |
+
"the 'keep' argument has been deprecated",
|
| 24 |
+
DeprecationWarning,
|
| 25 |
+
)
|
| 26 |
+
if type(values) == Vector:
|
| 27 |
+
# No need to create a new object
|
| 28 |
+
return values
|
| 29 |
+
return super().__new__(cls, values)
|
| 30 |
+
|
| 31 |
+
def __repr__(self):
|
| 32 |
+
return f"{self.__class__.__name__}({super().__repr__()})"
|
| 33 |
+
|
| 34 |
+
def _vectorOp(self, other, op):
|
| 35 |
+
if isinstance(other, Vector):
|
| 36 |
+
assert len(self) == len(other)
|
| 37 |
+
return self.__class__(op(a, b) for a, b in zip(self, other))
|
| 38 |
+
if isinstance(other, Number):
|
| 39 |
+
return self.__class__(op(v, other) for v in self)
|
| 40 |
+
raise NotImplementedError()
|
| 41 |
+
|
| 42 |
+
def _scalarOp(self, other, op):
|
| 43 |
+
if isinstance(other, Number):
|
| 44 |
+
return self.__class__(op(v, other) for v in self)
|
| 45 |
+
raise NotImplementedError()
|
| 46 |
+
|
| 47 |
+
def _unaryOp(self, op):
|
| 48 |
+
return self.__class__(op(v) for v in self)
|
| 49 |
+
|
| 50 |
+
def __add__(self, other):
|
| 51 |
+
return self._vectorOp(other, operator.add)
|
| 52 |
+
|
| 53 |
+
__radd__ = __add__
|
| 54 |
+
|
| 55 |
+
def __sub__(self, other):
|
| 56 |
+
return self._vectorOp(other, operator.sub)
|
| 57 |
+
|
| 58 |
+
def __rsub__(self, other):
|
| 59 |
+
return self._vectorOp(other, _operator_rsub)
|
| 60 |
+
|
| 61 |
+
def __mul__(self, other):
|
| 62 |
+
return self._scalarOp(other, operator.mul)
|
| 63 |
+
|
| 64 |
+
__rmul__ = __mul__
|
| 65 |
+
|
| 66 |
+
def __truediv__(self, other):
|
| 67 |
+
return self._scalarOp(other, operator.truediv)
|
| 68 |
+
|
| 69 |
+
def __rtruediv__(self, other):
|
| 70 |
+
return self._scalarOp(other, _operator_rtruediv)
|
| 71 |
+
|
| 72 |
+
def __pos__(self):
|
| 73 |
+
return self._unaryOp(operator.pos)
|
| 74 |
+
|
| 75 |
+
def __neg__(self):
|
| 76 |
+
return self._unaryOp(operator.neg)
|
| 77 |
+
|
| 78 |
+
def __round__(self, *, round=round):
|
| 79 |
+
return self._unaryOp(round)
|
| 80 |
+
|
| 81 |
+
def __eq__(self, other):
|
| 82 |
+
if isinstance(other, list):
|
| 83 |
+
# bw compat Vector([1, 2, 3]) == [1, 2, 3]
|
| 84 |
+
other = tuple(other)
|
| 85 |
+
return super().__eq__(other)
|
| 86 |
+
|
| 87 |
+
def __ne__(self, other):
|
| 88 |
+
return not self.__eq__(other)
|
| 89 |
+
|
| 90 |
+
def __bool__(self):
|
| 91 |
+
return any(self)
|
| 92 |
+
|
| 93 |
+
__nonzero__ = __bool__
|
| 94 |
+
|
| 95 |
+
def __abs__(self):
|
| 96 |
+
return math.sqrt(sum(x * x for x in self))
|
| 97 |
+
|
| 98 |
+
def length(self):
|
| 99 |
+
"""Return the length of the vector. Equivalent to abs(vector)."""
|
| 100 |
+
return abs(self)
|
| 101 |
+
|
| 102 |
+
def normalized(self):
|
| 103 |
+
"""Return the normalized vector of the vector."""
|
| 104 |
+
return self / abs(self)
|
| 105 |
+
|
| 106 |
+
def dot(self, other):
|
| 107 |
+
"""Performs vector dot product, returning the sum of
|
| 108 |
+
``a[0] * b[0], a[1] * b[1], ...``"""
|
| 109 |
+
assert len(self) == len(other)
|
| 110 |
+
return sum(a * b for a, b in zip(self, other))
|
| 111 |
+
|
| 112 |
+
# Deprecated methods/properties
|
| 113 |
+
|
| 114 |
+
def toInt(self):
|
| 115 |
+
warnings.warn(
|
| 116 |
+
"the 'toInt' method has been deprecated, use round(vector) instead",
|
| 117 |
+
DeprecationWarning,
|
| 118 |
+
)
|
| 119 |
+
return self.__round__()
|
| 120 |
+
|
| 121 |
+
@property
|
| 122 |
+
def values(self):
|
| 123 |
+
warnings.warn(
|
| 124 |
+
"the 'values' attribute has been deprecated, use "
|
| 125 |
+
"the vector object itself instead",
|
| 126 |
+
DeprecationWarning,
|
| 127 |
+
)
|
| 128 |
+
return list(self)
|
| 129 |
+
|
| 130 |
+
@values.setter
|
| 131 |
+
def values(self, values):
|
| 132 |
+
raise AttributeError(
|
| 133 |
+
"can't set attribute, the 'values' attribute has been deprecated",
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
def isclose(self, other: "Vector", **kwargs) -> bool:
|
| 137 |
+
"""Return True if the vector is close to another Vector."""
|
| 138 |
+
assert len(self) == len(other)
|
| 139 |
+
return all(math.isclose(a, b, **kwargs) for a, b in zip(self, other))
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _operator_rsub(a, b):
|
| 143 |
+
return operator.sub(b, a)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _operator_rtruediv(a, b):
|
| 147 |
+
return operator.truediv(b, a)
|