Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/__init__.py +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/builder.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/errors.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/geometry.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/table_builder.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/unbuilder.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/builder.py +664 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/errors.py +2 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/geometry.py +143 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/config/__init__.py +75 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/config/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__init__.py +4 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__init__.py +1 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/areaPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/basePen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/boundsPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/cairoPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/cocoaPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/cu2quPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/explicitClosingLinePen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/filterPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/hashPointPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/momentsPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/perimeterPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/pointInsidePen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/qtPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/quartzPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/recordingPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/roundingPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/wxPen.cpython-310.pyc +0 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/areaPen.py +52 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/basePen.py +475 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/boundsPen.py +98 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/cocoaPen.py +26 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/cu2quPen.py +325 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/filterPen.py +241 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/freetypePen.py +462 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/hashPointPen.py +89 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/perimeterPen.py +69 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/pointInsidePen.py +192 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/pointPen.py +600 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/qtPen.py +29 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/qu2cuPen.py +105 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/quartzPen.py +43 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/reportLabPen.py +79 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/reverseContourPen.py +96 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/roundingPen.py +130 -0
- infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/statisticsPen.py +307 -0
infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/__init__.py
ADDED
|
File without changes
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (176 Bytes). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/builder.cpython-310.pyc
ADDED
|
Binary file (19 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/errors.cpython-310.pyc
ADDED
|
Binary file (344 Bytes). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/geometry.cpython-310.pyc
ADDED
|
Binary file (3.66 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/table_builder.cpython-310.pyc
ADDED
|
Binary file (6.16 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/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
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
colorLib.builder: Build COLR/CPAL tables from scratch
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import collections
|
| 7 |
+
import copy
|
| 8 |
+
import enum
|
| 9 |
+
from functools import partial
|
| 10 |
+
from math import ceil, log
|
| 11 |
+
from typing import (
|
| 12 |
+
Any,
|
| 13 |
+
Dict,
|
| 14 |
+
Generator,
|
| 15 |
+
Iterable,
|
| 16 |
+
List,
|
| 17 |
+
Mapping,
|
| 18 |
+
Optional,
|
| 19 |
+
Sequence,
|
| 20 |
+
Tuple,
|
| 21 |
+
Type,
|
| 22 |
+
TypeVar,
|
| 23 |
+
Union,
|
| 24 |
+
)
|
| 25 |
+
from fontTools.misc.arrayTools import intRect
|
| 26 |
+
from fontTools.misc.fixedTools import fixedToFloat
|
| 27 |
+
from fontTools.misc.treeTools import build_n_ary_tree
|
| 28 |
+
from fontTools.ttLib.tables import C_O_L_R_
|
| 29 |
+
from fontTools.ttLib.tables import C_P_A_L_
|
| 30 |
+
from fontTools.ttLib.tables import _n_a_m_e
|
| 31 |
+
from fontTools.ttLib.tables import otTables as ot
|
| 32 |
+
from fontTools.ttLib.tables.otTables import ExtendMode, CompositeMode
|
| 33 |
+
from .errors import ColorLibError
|
| 34 |
+
from .geometry import round_start_circle_stable_containment
|
| 35 |
+
from .table_builder import BuildCallback, TableBuilder
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# TODO move type aliases to colorLib.types?
|
| 39 |
+
T = TypeVar("T")
|
| 40 |
+
_Kwargs = Mapping[str, Any]
|
| 41 |
+
_PaintInput = Union[int, _Kwargs, ot.Paint, Tuple[str, "_PaintInput"]]
|
| 42 |
+
_PaintInputList = Sequence[_PaintInput]
|
| 43 |
+
_ColorGlyphsDict = Dict[str, Union[_PaintInputList, _PaintInput]]
|
| 44 |
+
_ColorGlyphsV0Dict = Dict[str, Sequence[Tuple[str, int]]]
|
| 45 |
+
_ClipBoxInput = Union[
|
| 46 |
+
Tuple[int, int, int, int, int], # format 1, variable
|
| 47 |
+
Tuple[int, int, int, int], # format 0, non-variable
|
| 48 |
+
ot.ClipBox,
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
MAX_PAINT_COLR_LAYER_COUNT = 255
|
| 53 |
+
_DEFAULT_ALPHA = 1.0
|
| 54 |
+
_MAX_REUSE_LEN = 32
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _beforeBuildPaintRadialGradient(paint, source):
|
| 58 |
+
x0 = source["x0"]
|
| 59 |
+
y0 = source["y0"]
|
| 60 |
+
r0 = source["r0"]
|
| 61 |
+
x1 = source["x1"]
|
| 62 |
+
y1 = source["y1"]
|
| 63 |
+
r1 = source["r1"]
|
| 64 |
+
|
| 65 |
+
# TODO apparently no builder_test confirms this works (?)
|
| 66 |
+
|
| 67 |
+
# avoid abrupt change after rounding when c0 is near c1's perimeter
|
| 68 |
+
c = round_start_circle_stable_containment((x0, y0), r0, (x1, y1), r1)
|
| 69 |
+
x0, y0 = c.centre
|
| 70 |
+
r0 = c.radius
|
| 71 |
+
|
| 72 |
+
# update source to ensure paint is built with corrected values
|
| 73 |
+
source["x0"] = x0
|
| 74 |
+
source["y0"] = y0
|
| 75 |
+
source["r0"] = r0
|
| 76 |
+
source["x1"] = x1
|
| 77 |
+
source["y1"] = y1
|
| 78 |
+
source["r1"] = r1
|
| 79 |
+
|
| 80 |
+
return paint, source
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _defaultColorStop():
|
| 84 |
+
colorStop = ot.ColorStop()
|
| 85 |
+
colorStop.Alpha = _DEFAULT_ALPHA
|
| 86 |
+
return colorStop
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _defaultVarColorStop():
|
| 90 |
+
colorStop = ot.VarColorStop()
|
| 91 |
+
colorStop.Alpha = _DEFAULT_ALPHA
|
| 92 |
+
return colorStop
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _defaultColorLine():
|
| 96 |
+
colorLine = ot.ColorLine()
|
| 97 |
+
colorLine.Extend = ExtendMode.PAD
|
| 98 |
+
return colorLine
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _defaultVarColorLine():
|
| 102 |
+
colorLine = ot.VarColorLine()
|
| 103 |
+
colorLine.Extend = ExtendMode.PAD
|
| 104 |
+
return colorLine
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _defaultPaintSolid():
|
| 108 |
+
paint = ot.Paint()
|
| 109 |
+
paint.Alpha = _DEFAULT_ALPHA
|
| 110 |
+
return paint
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _buildPaintCallbacks():
|
| 114 |
+
return {
|
| 115 |
+
(
|
| 116 |
+
BuildCallback.BEFORE_BUILD,
|
| 117 |
+
ot.Paint,
|
| 118 |
+
ot.PaintFormat.PaintRadialGradient,
|
| 119 |
+
): _beforeBuildPaintRadialGradient,
|
| 120 |
+
(
|
| 121 |
+
BuildCallback.BEFORE_BUILD,
|
| 122 |
+
ot.Paint,
|
| 123 |
+
ot.PaintFormat.PaintVarRadialGradient,
|
| 124 |
+
): _beforeBuildPaintRadialGradient,
|
| 125 |
+
(BuildCallback.CREATE_DEFAULT, ot.ColorStop): _defaultColorStop,
|
| 126 |
+
(BuildCallback.CREATE_DEFAULT, ot.VarColorStop): _defaultVarColorStop,
|
| 127 |
+
(BuildCallback.CREATE_DEFAULT, ot.ColorLine): _defaultColorLine,
|
| 128 |
+
(BuildCallback.CREATE_DEFAULT, ot.VarColorLine): _defaultVarColorLine,
|
| 129 |
+
(
|
| 130 |
+
BuildCallback.CREATE_DEFAULT,
|
| 131 |
+
ot.Paint,
|
| 132 |
+
ot.PaintFormat.PaintSolid,
|
| 133 |
+
): _defaultPaintSolid,
|
| 134 |
+
(
|
| 135 |
+
BuildCallback.CREATE_DEFAULT,
|
| 136 |
+
ot.Paint,
|
| 137 |
+
ot.PaintFormat.PaintVarSolid,
|
| 138 |
+
): _defaultPaintSolid,
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def populateCOLRv0(
|
| 143 |
+
table: ot.COLR,
|
| 144 |
+
colorGlyphsV0: _ColorGlyphsV0Dict,
|
| 145 |
+
glyphMap: Optional[Mapping[str, int]] = None,
|
| 146 |
+
):
|
| 147 |
+
"""Build v0 color layers and add to existing COLR table.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
table: a raw ``otTables.COLR()`` object (not ttLib's ``table_C_O_L_R_``).
|
| 151 |
+
colorGlyphsV0: map of base glyph names to lists of (layer glyph names,
|
| 152 |
+
color palette index) tuples. Can be empty.
|
| 153 |
+
glyphMap: a map from glyph names to glyph indices, as returned from
|
| 154 |
+
``TTFont.getReverseGlyphMap()``, to optionally sort base records by GID.
|
| 155 |
+
"""
|
| 156 |
+
if glyphMap is not None:
|
| 157 |
+
colorGlyphItems = sorted(
|
| 158 |
+
colorGlyphsV0.items(), key=lambda item: glyphMap[item[0]]
|
| 159 |
+
)
|
| 160 |
+
else:
|
| 161 |
+
colorGlyphItems = colorGlyphsV0.items()
|
| 162 |
+
baseGlyphRecords = []
|
| 163 |
+
layerRecords = []
|
| 164 |
+
for baseGlyph, layers in colorGlyphItems:
|
| 165 |
+
baseRec = ot.BaseGlyphRecord()
|
| 166 |
+
baseRec.BaseGlyph = baseGlyph
|
| 167 |
+
baseRec.FirstLayerIndex = len(layerRecords)
|
| 168 |
+
baseRec.NumLayers = len(layers)
|
| 169 |
+
baseGlyphRecords.append(baseRec)
|
| 170 |
+
|
| 171 |
+
for layerGlyph, paletteIndex in layers:
|
| 172 |
+
layerRec = ot.LayerRecord()
|
| 173 |
+
layerRec.LayerGlyph = layerGlyph
|
| 174 |
+
layerRec.PaletteIndex = paletteIndex
|
| 175 |
+
layerRecords.append(layerRec)
|
| 176 |
+
|
| 177 |
+
table.BaseGlyphRecordArray = table.LayerRecordArray = None
|
| 178 |
+
if baseGlyphRecords:
|
| 179 |
+
table.BaseGlyphRecordArray = ot.BaseGlyphRecordArray()
|
| 180 |
+
table.BaseGlyphRecordArray.BaseGlyphRecord = baseGlyphRecords
|
| 181 |
+
if layerRecords:
|
| 182 |
+
table.LayerRecordArray = ot.LayerRecordArray()
|
| 183 |
+
table.LayerRecordArray.LayerRecord = layerRecords
|
| 184 |
+
table.BaseGlyphRecordCount = len(baseGlyphRecords)
|
| 185 |
+
table.LayerRecordCount = len(layerRecords)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def buildCOLR(
|
| 189 |
+
colorGlyphs: _ColorGlyphsDict,
|
| 190 |
+
version: Optional[int] = None,
|
| 191 |
+
*,
|
| 192 |
+
glyphMap: Optional[Mapping[str, int]] = None,
|
| 193 |
+
varStore: Optional[ot.VarStore] = None,
|
| 194 |
+
varIndexMap: Optional[ot.DeltaSetIndexMap] = None,
|
| 195 |
+
clipBoxes: Optional[Dict[str, _ClipBoxInput]] = None,
|
| 196 |
+
allowLayerReuse: bool = True,
|
| 197 |
+
) -> C_O_L_R_.table_C_O_L_R_:
|
| 198 |
+
"""Build COLR table from color layers mapping.
|
| 199 |
+
|
| 200 |
+
Args:
|
| 201 |
+
|
| 202 |
+
colorGlyphs: map of base glyph name to, either list of (layer glyph name,
|
| 203 |
+
color palette index) tuples for COLRv0; or a single ``Paint`` (dict) or
|
| 204 |
+
list of ``Paint`` for COLRv1.
|
| 205 |
+
version: the version of COLR table. If None, the version is determined
|
| 206 |
+
by the presence of COLRv1 paints or variation data (varStore), which
|
| 207 |
+
require version 1; otherwise, if all base glyphs use only simple color
|
| 208 |
+
layers, version 0 is used.
|
| 209 |
+
glyphMap: a map from glyph names to glyph indices, as returned from
|
| 210 |
+
TTFont.getReverseGlyphMap(), to optionally sort base records by GID.
|
| 211 |
+
varStore: Optional ItemVarationStore for deltas associated with v1 layer.
|
| 212 |
+
varIndexMap: Optional DeltaSetIndexMap for deltas associated with v1 layer.
|
| 213 |
+
clipBoxes: Optional map of base glyph name to clip box 4- or 5-tuples:
|
| 214 |
+
(xMin, yMin, xMax, yMax) or (xMin, yMin, xMax, yMax, varIndexBase).
|
| 215 |
+
|
| 216 |
+
Returns:
|
| 217 |
+
A new COLR table.
|
| 218 |
+
"""
|
| 219 |
+
self = C_O_L_R_.table_C_O_L_R_()
|
| 220 |
+
|
| 221 |
+
if varStore is not None and version == 0:
|
| 222 |
+
raise ValueError("Can't add VarStore to COLRv0")
|
| 223 |
+
|
| 224 |
+
if version in (None, 0) and not varStore:
|
| 225 |
+
# split color glyphs into v0 and v1 and encode separately
|
| 226 |
+
colorGlyphsV0, colorGlyphsV1 = _split_color_glyphs_by_version(colorGlyphs)
|
| 227 |
+
if version == 0 and colorGlyphsV1:
|
| 228 |
+
raise ValueError("Can't encode COLRv1 glyphs in COLRv0")
|
| 229 |
+
else:
|
| 230 |
+
# unless explicitly requested for v1 or have variations, in which case
|
| 231 |
+
# we encode all color glyph as v1
|
| 232 |
+
colorGlyphsV0, colorGlyphsV1 = {}, colorGlyphs
|
| 233 |
+
|
| 234 |
+
colr = ot.COLR()
|
| 235 |
+
|
| 236 |
+
populateCOLRv0(colr, colorGlyphsV0, glyphMap)
|
| 237 |
+
|
| 238 |
+
colr.LayerList, colr.BaseGlyphList = buildColrV1(
|
| 239 |
+
colorGlyphsV1,
|
| 240 |
+
glyphMap,
|
| 241 |
+
allowLayerReuse=allowLayerReuse,
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
if version is None:
|
| 245 |
+
version = 1 if (varStore or colorGlyphsV1) else 0
|
| 246 |
+
elif version not in (0, 1):
|
| 247 |
+
raise NotImplementedError(version)
|
| 248 |
+
self.version = colr.Version = version
|
| 249 |
+
|
| 250 |
+
if version == 0:
|
| 251 |
+
self.ColorLayers = self._decompileColorLayersV0(colr)
|
| 252 |
+
else:
|
| 253 |
+
colr.ClipList = buildClipList(clipBoxes) if clipBoxes else None
|
| 254 |
+
colr.VarIndexMap = varIndexMap
|
| 255 |
+
colr.VarStore = varStore
|
| 256 |
+
self.table = colr
|
| 257 |
+
|
| 258 |
+
return self
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def buildClipList(clipBoxes: Dict[str, _ClipBoxInput]) -> ot.ClipList:
|
| 262 |
+
clipList = ot.ClipList()
|
| 263 |
+
clipList.Format = 1
|
| 264 |
+
clipList.clips = {name: buildClipBox(box) for name, box in clipBoxes.items()}
|
| 265 |
+
return clipList
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def buildClipBox(clipBox: _ClipBoxInput) -> ot.ClipBox:
|
| 269 |
+
if isinstance(clipBox, ot.ClipBox):
|
| 270 |
+
return clipBox
|
| 271 |
+
n = len(clipBox)
|
| 272 |
+
clip = ot.ClipBox()
|
| 273 |
+
if n not in (4, 5):
|
| 274 |
+
raise ValueError(f"Invalid ClipBox: expected 4 or 5 values, found {n}")
|
| 275 |
+
clip.xMin, clip.yMin, clip.xMax, clip.yMax = intRect(clipBox[:4])
|
| 276 |
+
clip.Format = int(n == 5) + 1
|
| 277 |
+
if n == 5:
|
| 278 |
+
clip.VarIndexBase = int(clipBox[4])
|
| 279 |
+
return clip
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class ColorPaletteType(enum.IntFlag):
|
| 283 |
+
USABLE_WITH_LIGHT_BACKGROUND = 0x0001
|
| 284 |
+
USABLE_WITH_DARK_BACKGROUND = 0x0002
|
| 285 |
+
|
| 286 |
+
@classmethod
|
| 287 |
+
def _missing_(cls, value):
|
| 288 |
+
# enforce reserved bits
|
| 289 |
+
if isinstance(value, int) and (value < 0 or value & 0xFFFC != 0):
|
| 290 |
+
raise ValueError(f"{value} is not a valid {cls.__name__}")
|
| 291 |
+
return super()._missing_(value)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
# None, 'abc' or {'en': 'abc', 'de': 'xyz'}
|
| 295 |
+
_OptionalLocalizedString = Union[None, str, Dict[str, str]]
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def buildPaletteLabels(
|
| 299 |
+
labels: Iterable[_OptionalLocalizedString], nameTable: _n_a_m_e.table__n_a_m_e
|
| 300 |
+
) -> List[Optional[int]]:
|
| 301 |
+
return [
|
| 302 |
+
(
|
| 303 |
+
nameTable.addMultilingualName(l, mac=False)
|
| 304 |
+
if isinstance(l, dict)
|
| 305 |
+
else (
|
| 306 |
+
C_P_A_L_.table_C_P_A_L_.NO_NAME_ID
|
| 307 |
+
if l is None
|
| 308 |
+
else nameTable.addMultilingualName({"en": l}, mac=False)
|
| 309 |
+
)
|
| 310 |
+
)
|
| 311 |
+
for l in labels
|
| 312 |
+
]
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def buildCPAL(
|
| 316 |
+
palettes: Sequence[Sequence[Tuple[float, float, float, float]]],
|
| 317 |
+
paletteTypes: Optional[Sequence[ColorPaletteType]] = None,
|
| 318 |
+
paletteLabels: Optional[Sequence[_OptionalLocalizedString]] = None,
|
| 319 |
+
paletteEntryLabels: Optional[Sequence[_OptionalLocalizedString]] = None,
|
| 320 |
+
nameTable: Optional[_n_a_m_e.table__n_a_m_e] = None,
|
| 321 |
+
) -> C_P_A_L_.table_C_P_A_L_:
|
| 322 |
+
"""Build CPAL table from list of color palettes.
|
| 323 |
+
|
| 324 |
+
Args:
|
| 325 |
+
palettes: list of lists of colors encoded as tuples of (R, G, B, A) floats
|
| 326 |
+
in the range [0..1].
|
| 327 |
+
paletteTypes: optional list of ColorPaletteType, one for each palette.
|
| 328 |
+
paletteLabels: optional list of palette labels. Each lable can be either:
|
| 329 |
+
None (no label), a string (for for default English labels), or a
|
| 330 |
+
localized string (as a dict keyed with BCP47 language codes).
|
| 331 |
+
paletteEntryLabels: optional list of palette entry labels, one for each
|
| 332 |
+
palette entry (see paletteLabels).
|
| 333 |
+
nameTable: optional name table where to store palette and palette entry
|
| 334 |
+
labels. Required if either paletteLabels or paletteEntryLabels is set.
|
| 335 |
+
|
| 336 |
+
Return:
|
| 337 |
+
A new CPAL v0 or v1 table, if custom palette types or labels are specified.
|
| 338 |
+
"""
|
| 339 |
+
if len({len(p) for p in palettes}) != 1:
|
| 340 |
+
raise ColorLibError("color palettes have different lengths")
|
| 341 |
+
|
| 342 |
+
if (paletteLabels or paletteEntryLabels) and not nameTable:
|
| 343 |
+
raise TypeError(
|
| 344 |
+
"nameTable is required if palette or palette entries have labels"
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
cpal = C_P_A_L_.table_C_P_A_L_()
|
| 348 |
+
cpal.numPaletteEntries = len(palettes[0])
|
| 349 |
+
|
| 350 |
+
cpal.palettes = []
|
| 351 |
+
for i, palette in enumerate(palettes):
|
| 352 |
+
colors = []
|
| 353 |
+
for j, color in enumerate(palette):
|
| 354 |
+
if not isinstance(color, tuple) or len(color) != 4:
|
| 355 |
+
raise ColorLibError(
|
| 356 |
+
f"In palette[{i}][{j}]: expected (R, G, B, A) tuple, got {color!r}"
|
| 357 |
+
)
|
| 358 |
+
if any(v > 1 or v < 0 for v in color):
|
| 359 |
+
raise ColorLibError(
|
| 360 |
+
f"palette[{i}][{j}] has invalid out-of-range [0..1] color: {color!r}"
|
| 361 |
+
)
|
| 362 |
+
# input colors are RGBA, CPAL encodes them as BGRA
|
| 363 |
+
red, green, blue, alpha = color
|
| 364 |
+
colors.append(
|
| 365 |
+
C_P_A_L_.Color(*(round(v * 255) for v in (blue, green, red, alpha)))
|
| 366 |
+
)
|
| 367 |
+
cpal.palettes.append(colors)
|
| 368 |
+
|
| 369 |
+
if any(v is not None for v in (paletteTypes, paletteLabels, paletteEntryLabels)):
|
| 370 |
+
cpal.version = 1
|
| 371 |
+
|
| 372 |
+
if paletteTypes is not None:
|
| 373 |
+
if len(paletteTypes) != len(palettes):
|
| 374 |
+
raise ColorLibError(
|
| 375 |
+
f"Expected {len(palettes)} paletteTypes, got {len(paletteTypes)}"
|
| 376 |
+
)
|
| 377 |
+
cpal.paletteTypes = [ColorPaletteType(t).value for t in paletteTypes]
|
| 378 |
+
else:
|
| 379 |
+
cpal.paletteTypes = [C_P_A_L_.table_C_P_A_L_.DEFAULT_PALETTE_TYPE] * len(
|
| 380 |
+
palettes
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
if paletteLabels is not None:
|
| 384 |
+
if len(paletteLabels) != len(palettes):
|
| 385 |
+
raise ColorLibError(
|
| 386 |
+
f"Expected {len(palettes)} paletteLabels, got {len(paletteLabels)}"
|
| 387 |
+
)
|
| 388 |
+
cpal.paletteLabels = buildPaletteLabels(paletteLabels, nameTable)
|
| 389 |
+
else:
|
| 390 |
+
cpal.paletteLabels = [C_P_A_L_.table_C_P_A_L_.NO_NAME_ID] * len(palettes)
|
| 391 |
+
|
| 392 |
+
if paletteEntryLabels is not None:
|
| 393 |
+
if len(paletteEntryLabels) != cpal.numPaletteEntries:
|
| 394 |
+
raise ColorLibError(
|
| 395 |
+
f"Expected {cpal.numPaletteEntries} paletteEntryLabels, "
|
| 396 |
+
f"got {len(paletteEntryLabels)}"
|
| 397 |
+
)
|
| 398 |
+
cpal.paletteEntryLabels = buildPaletteLabels(paletteEntryLabels, nameTable)
|
| 399 |
+
else:
|
| 400 |
+
cpal.paletteEntryLabels = [
|
| 401 |
+
C_P_A_L_.table_C_P_A_L_.NO_NAME_ID
|
| 402 |
+
] * cpal.numPaletteEntries
|
| 403 |
+
else:
|
| 404 |
+
cpal.version = 0
|
| 405 |
+
|
| 406 |
+
return cpal
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
# COLR v1 tables
|
| 410 |
+
# See draft proposal at: https://github.com/googlefonts/colr-gradients-spec
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def _is_colrv0_layer(layer: Any) -> bool:
|
| 414 |
+
# Consider as COLRv0 layer any sequence of length 2 (be it tuple or list) in which
|
| 415 |
+
# the first element is a str (the layerGlyph) and the second element is an int
|
| 416 |
+
# (CPAL paletteIndex).
|
| 417 |
+
# https://github.com/googlefonts/ufo2ft/issues/426
|
| 418 |
+
try:
|
| 419 |
+
layerGlyph, paletteIndex = layer
|
| 420 |
+
except (TypeError, ValueError):
|
| 421 |
+
return False
|
| 422 |
+
else:
|
| 423 |
+
return isinstance(layerGlyph, str) and isinstance(paletteIndex, int)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def _split_color_glyphs_by_version(
|
| 427 |
+
colorGlyphs: _ColorGlyphsDict,
|
| 428 |
+
) -> Tuple[_ColorGlyphsV0Dict, _ColorGlyphsDict]:
|
| 429 |
+
colorGlyphsV0 = {}
|
| 430 |
+
colorGlyphsV1 = {}
|
| 431 |
+
for baseGlyph, layers in colorGlyphs.items():
|
| 432 |
+
if all(_is_colrv0_layer(l) for l in layers):
|
| 433 |
+
colorGlyphsV0[baseGlyph] = layers
|
| 434 |
+
else:
|
| 435 |
+
colorGlyphsV1[baseGlyph] = layers
|
| 436 |
+
|
| 437 |
+
# sanity check
|
| 438 |
+
assert set(colorGlyphs) == (set(colorGlyphsV0) | set(colorGlyphsV1))
|
| 439 |
+
|
| 440 |
+
return colorGlyphsV0, colorGlyphsV1
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def _reuse_ranges(num_layers: int) -> Generator[Tuple[int, int], None, None]:
|
| 444 |
+
# TODO feels like something itertools might have already
|
| 445 |
+
for lbound in range(num_layers):
|
| 446 |
+
# Reuse of very large #s of layers is relatively unlikely
|
| 447 |
+
# +2: we want sequences of at least 2
|
| 448 |
+
# otData handles single-record duplication
|
| 449 |
+
for ubound in range(
|
| 450 |
+
lbound + 2, min(num_layers + 1, lbound + 2 + _MAX_REUSE_LEN)
|
| 451 |
+
):
|
| 452 |
+
yield (lbound, ubound)
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
class LayerReuseCache:
|
| 456 |
+
reusePool: Mapping[Tuple[Any, ...], int]
|
| 457 |
+
tuples: Mapping[int, Tuple[Any, ...]]
|
| 458 |
+
keepAlive: List[ot.Paint] # we need id to remain valid
|
| 459 |
+
|
| 460 |
+
def __init__(self):
|
| 461 |
+
self.reusePool = {}
|
| 462 |
+
self.tuples = {}
|
| 463 |
+
self.keepAlive = []
|
| 464 |
+
|
| 465 |
+
def _paint_tuple(self, paint: ot.Paint):
|
| 466 |
+
# start simple, who even cares about cyclic graphs or interesting field types
|
| 467 |
+
def _tuple_safe(value):
|
| 468 |
+
if isinstance(value, enum.Enum):
|
| 469 |
+
return value
|
| 470 |
+
elif hasattr(value, "__dict__"):
|
| 471 |
+
return tuple(
|
| 472 |
+
(k, _tuple_safe(v)) for k, v in sorted(value.__dict__.items())
|
| 473 |
+
)
|
| 474 |
+
elif isinstance(value, collections.abc.MutableSequence):
|
| 475 |
+
return tuple(_tuple_safe(e) for e in value)
|
| 476 |
+
return value
|
| 477 |
+
|
| 478 |
+
# Cache the tuples for individual Paint instead of the whole sequence
|
| 479 |
+
# because the seq could be a transient slice
|
| 480 |
+
result = self.tuples.get(id(paint), None)
|
| 481 |
+
if result is None:
|
| 482 |
+
result = _tuple_safe(paint)
|
| 483 |
+
self.tuples[id(paint)] = result
|
| 484 |
+
self.keepAlive.append(paint)
|
| 485 |
+
return result
|
| 486 |
+
|
| 487 |
+
def _as_tuple(self, paints: Sequence[ot.Paint]) -> Tuple[Any, ...]:
|
| 488 |
+
return tuple(self._paint_tuple(p) for p in paints)
|
| 489 |
+
|
| 490 |
+
def try_reuse(self, layers: List[ot.Paint]) -> List[ot.Paint]:
|
| 491 |
+
found_reuse = True
|
| 492 |
+
while found_reuse:
|
| 493 |
+
found_reuse = False
|
| 494 |
+
|
| 495 |
+
ranges = sorted(
|
| 496 |
+
_reuse_ranges(len(layers)),
|
| 497 |
+
key=lambda t: (t[1] - t[0], t[1], t[0]),
|
| 498 |
+
reverse=True,
|
| 499 |
+
)
|
| 500 |
+
for lbound, ubound in ranges:
|
| 501 |
+
reuse_lbound = self.reusePool.get(
|
| 502 |
+
self._as_tuple(layers[lbound:ubound]), -1
|
| 503 |
+
)
|
| 504 |
+
if reuse_lbound == -1:
|
| 505 |
+
continue
|
| 506 |
+
new_slice = ot.Paint()
|
| 507 |
+
new_slice.Format = int(ot.PaintFormat.PaintColrLayers)
|
| 508 |
+
new_slice.NumLayers = ubound - lbound
|
| 509 |
+
new_slice.FirstLayerIndex = reuse_lbound
|
| 510 |
+
layers = layers[:lbound] + [new_slice] + layers[ubound:]
|
| 511 |
+
found_reuse = True
|
| 512 |
+
break
|
| 513 |
+
return layers
|
| 514 |
+
|
| 515 |
+
def add(self, layers: List[ot.Paint], first_layer_index: int):
|
| 516 |
+
for lbound, ubound in _reuse_ranges(len(layers)):
|
| 517 |
+
self.reusePool[self._as_tuple(layers[lbound:ubound])] = (
|
| 518 |
+
lbound + first_layer_index
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
class LayerListBuilder:
|
| 523 |
+
layers: List[ot.Paint]
|
| 524 |
+
cache: LayerReuseCache
|
| 525 |
+
allowLayerReuse: bool
|
| 526 |
+
|
| 527 |
+
def __init__(self, *, allowLayerReuse=True):
|
| 528 |
+
self.layers = []
|
| 529 |
+
if allowLayerReuse:
|
| 530 |
+
self.cache = LayerReuseCache()
|
| 531 |
+
else:
|
| 532 |
+
self.cache = None
|
| 533 |
+
|
| 534 |
+
# We need to intercept construction of PaintColrLayers
|
| 535 |
+
callbacks = _buildPaintCallbacks()
|
| 536 |
+
callbacks[
|
| 537 |
+
(
|
| 538 |
+
BuildCallback.BEFORE_BUILD,
|
| 539 |
+
ot.Paint,
|
| 540 |
+
ot.PaintFormat.PaintColrLayers,
|
| 541 |
+
)
|
| 542 |
+
] = self._beforeBuildPaintColrLayers
|
| 543 |
+
self.tableBuilder = TableBuilder(callbacks)
|
| 544 |
+
|
| 545 |
+
# COLR layers is unusual in that it modifies shared state
|
| 546 |
+
# so we need a callback into an object
|
| 547 |
+
def _beforeBuildPaintColrLayers(self, dest, source):
|
| 548 |
+
# Sketchy gymnastics: a sequence input will have dropped it's layers
|
| 549 |
+
# into NumLayers; get it back
|
| 550 |
+
if isinstance(source.get("NumLayers", None), collections.abc.Sequence):
|
| 551 |
+
layers = source["NumLayers"]
|
| 552 |
+
else:
|
| 553 |
+
layers = source["Layers"]
|
| 554 |
+
|
| 555 |
+
# Convert maps seqs or whatever into typed objects
|
| 556 |
+
layers = [self.buildPaint(l) for l in layers]
|
| 557 |
+
|
| 558 |
+
# No reason to have a colr layers with just one entry
|
| 559 |
+
if len(layers) == 1:
|
| 560 |
+
return layers[0], {}
|
| 561 |
+
|
| 562 |
+
if self.cache is not None:
|
| 563 |
+
# Look for reuse, with preference to longer sequences
|
| 564 |
+
# This may make the layer list smaller
|
| 565 |
+
layers = self.cache.try_reuse(layers)
|
| 566 |
+
|
| 567 |
+
# The layer list is now final; if it's too big we need to tree it
|
| 568 |
+
is_tree = len(layers) > MAX_PAINT_COLR_LAYER_COUNT
|
| 569 |
+
layers = build_n_ary_tree(layers, n=MAX_PAINT_COLR_LAYER_COUNT)
|
| 570 |
+
|
| 571 |
+
# We now have a tree of sequences with Paint leaves.
|
| 572 |
+
# Convert the sequences into PaintColrLayers.
|
| 573 |
+
def listToColrLayers(layer):
|
| 574 |
+
if isinstance(layer, collections.abc.Sequence):
|
| 575 |
+
return self.buildPaint(
|
| 576 |
+
{
|
| 577 |
+
"Format": ot.PaintFormat.PaintColrLayers,
|
| 578 |
+
"Layers": [listToColrLayers(l) for l in layer],
|
| 579 |
+
}
|
| 580 |
+
)
|
| 581 |
+
return layer
|
| 582 |
+
|
| 583 |
+
layers = [listToColrLayers(l) for l in layers]
|
| 584 |
+
|
| 585 |
+
# No reason to have a colr layers with just one entry
|
| 586 |
+
if len(layers) == 1:
|
| 587 |
+
return layers[0], {}
|
| 588 |
+
|
| 589 |
+
paint = ot.Paint()
|
| 590 |
+
paint.Format = int(ot.PaintFormat.PaintColrLayers)
|
| 591 |
+
paint.NumLayers = len(layers)
|
| 592 |
+
paint.FirstLayerIndex = len(self.layers)
|
| 593 |
+
self.layers.extend(layers)
|
| 594 |
+
|
| 595 |
+
# Register our parts for reuse provided we aren't a tree
|
| 596 |
+
# If we are a tree the leaves registered for reuse and that will suffice
|
| 597 |
+
if self.cache is not None and not is_tree:
|
| 598 |
+
self.cache.add(layers, paint.FirstLayerIndex)
|
| 599 |
+
|
| 600 |
+
# we've fully built dest; empty source prevents generalized build from kicking in
|
| 601 |
+
return paint, {}
|
| 602 |
+
|
| 603 |
+
def buildPaint(self, paint: _PaintInput) -> ot.Paint:
|
| 604 |
+
return self.tableBuilder.build(ot.Paint, paint)
|
| 605 |
+
|
| 606 |
+
def build(self) -> Optional[ot.LayerList]:
|
| 607 |
+
if not self.layers:
|
| 608 |
+
return None
|
| 609 |
+
layers = ot.LayerList()
|
| 610 |
+
layers.LayerCount = len(self.layers)
|
| 611 |
+
layers.Paint = self.layers
|
| 612 |
+
return layers
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def buildBaseGlyphPaintRecord(
|
| 616 |
+
baseGlyph: str, layerBuilder: LayerListBuilder, paint: _PaintInput
|
| 617 |
+
) -> ot.BaseGlyphList:
|
| 618 |
+
self = ot.BaseGlyphPaintRecord()
|
| 619 |
+
self.BaseGlyph = baseGlyph
|
| 620 |
+
self.Paint = layerBuilder.buildPaint(paint)
|
| 621 |
+
return self
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
def _format_glyph_errors(errors: Mapping[str, Exception]) -> str:
|
| 625 |
+
lines = []
|
| 626 |
+
for baseGlyph, error in sorted(errors.items()):
|
| 627 |
+
lines.append(f" {baseGlyph} => {type(error).__name__}: {error}")
|
| 628 |
+
return "\n".join(lines)
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def buildColrV1(
|
| 632 |
+
colorGlyphs: _ColorGlyphsDict,
|
| 633 |
+
glyphMap: Optional[Mapping[str, int]] = None,
|
| 634 |
+
*,
|
| 635 |
+
allowLayerReuse: bool = True,
|
| 636 |
+
) -> Tuple[Optional[ot.LayerList], ot.BaseGlyphList]:
|
| 637 |
+
if glyphMap is not None:
|
| 638 |
+
colorGlyphItems = sorted(
|
| 639 |
+
colorGlyphs.items(), key=lambda item: glyphMap[item[0]]
|
| 640 |
+
)
|
| 641 |
+
else:
|
| 642 |
+
colorGlyphItems = colorGlyphs.items()
|
| 643 |
+
|
| 644 |
+
errors = {}
|
| 645 |
+
baseGlyphs = []
|
| 646 |
+
layerBuilder = LayerListBuilder(allowLayerReuse=allowLayerReuse)
|
| 647 |
+
for baseGlyph, paint in colorGlyphItems:
|
| 648 |
+
try:
|
| 649 |
+
baseGlyphs.append(buildBaseGlyphPaintRecord(baseGlyph, layerBuilder, paint))
|
| 650 |
+
|
| 651 |
+
except (ColorLibError, OverflowError, ValueError, TypeError) as e:
|
| 652 |
+
errors[baseGlyph] = e
|
| 653 |
+
|
| 654 |
+
if errors:
|
| 655 |
+
failed_glyphs = _format_glyph_errors(errors)
|
| 656 |
+
exc = ColorLibError(f"Failed to build BaseGlyphList:\n{failed_glyphs}")
|
| 657 |
+
exc.errors = errors
|
| 658 |
+
raise exc from next(iter(errors.values()))
|
| 659 |
+
|
| 660 |
+
layers = layerBuilder.build()
|
| 661 |
+
glyphs = ot.BaseGlyphList()
|
| 662 |
+
glyphs.BaseGlyphCount = len(baseGlyphs)
|
| 663 |
+
glyphs.BaseGlyphPaintRecord = baseGlyphs
|
| 664 |
+
return (layers, glyphs)
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/errors.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class ColorLibError(Exception):
|
| 2 |
+
pass
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/colorLib/geometry.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helpers for manipulating 2D points and vectors in COLR table."""
|
| 2 |
+
|
| 3 |
+
from math import copysign, cos, hypot, isclose, pi
|
| 4 |
+
from fontTools.misc.roundTools import otRound
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _vector_between(origin, target):
|
| 8 |
+
return (target[0] - origin[0], target[1] - origin[1])
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _round_point(pt):
|
| 12 |
+
return (otRound(pt[0]), otRound(pt[1]))
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _unit_vector(vec):
|
| 16 |
+
length = hypot(*vec)
|
| 17 |
+
if length == 0:
|
| 18 |
+
return None
|
| 19 |
+
return (vec[0] / length, vec[1] / length)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
_CIRCLE_INSIDE_TOLERANCE = 1e-4
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# The unit vector's X and Y components are respectively
|
| 26 |
+
# U = (cos(α), sin(α))
|
| 27 |
+
# where α is the angle between the unit vector and the positive x axis.
|
| 28 |
+
_UNIT_VECTOR_THRESHOLD = cos(3 / 8 * pi) # == sin(1/8 * pi) == 0.38268343236508984
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _rounding_offset(direction):
|
| 32 |
+
# Return 2-tuple of -/+ 1.0 or 0.0 approximately based on the direction vector.
|
| 33 |
+
# We divide the unit circle in 8 equal slices oriented towards the cardinal
|
| 34 |
+
# (N, E, S, W) and intermediate (NE, SE, SW, NW) directions. To each slice we
|
| 35 |
+
# map one of the possible cases: -1, 0, +1 for either X and Y coordinate.
|
| 36 |
+
# E.g. Return (+1.0, -1.0) if unit vector is oriented towards SE, or
|
| 37 |
+
# (-1.0, 0.0) if it's pointing West, etc.
|
| 38 |
+
uv = _unit_vector(direction)
|
| 39 |
+
if not uv:
|
| 40 |
+
return (0, 0)
|
| 41 |
+
|
| 42 |
+
result = []
|
| 43 |
+
for uv_component in uv:
|
| 44 |
+
if -_UNIT_VECTOR_THRESHOLD <= uv_component < _UNIT_VECTOR_THRESHOLD:
|
| 45 |
+
# unit vector component near 0: direction almost orthogonal to the
|
| 46 |
+
# direction of the current axis, thus keep coordinate unchanged
|
| 47 |
+
result.append(0)
|
| 48 |
+
else:
|
| 49 |
+
# nudge coord by +/- 1.0 in direction of unit vector
|
| 50 |
+
result.append(copysign(1.0, uv_component))
|
| 51 |
+
return tuple(result)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class Circle:
|
| 55 |
+
def __init__(self, centre, radius):
|
| 56 |
+
self.centre = centre
|
| 57 |
+
self.radius = radius
|
| 58 |
+
|
| 59 |
+
def __repr__(self):
|
| 60 |
+
return f"Circle(centre={self.centre}, radius={self.radius})"
|
| 61 |
+
|
| 62 |
+
def round(self):
|
| 63 |
+
return Circle(_round_point(self.centre), otRound(self.radius))
|
| 64 |
+
|
| 65 |
+
def inside(self, outer_circle, tolerance=_CIRCLE_INSIDE_TOLERANCE):
|
| 66 |
+
dist = self.radius + hypot(*_vector_between(self.centre, outer_circle.centre))
|
| 67 |
+
return (
|
| 68 |
+
isclose(outer_circle.radius, dist, rel_tol=_CIRCLE_INSIDE_TOLERANCE)
|
| 69 |
+
or outer_circle.radius > dist
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
def concentric(self, other):
|
| 73 |
+
return self.centre == other.centre
|
| 74 |
+
|
| 75 |
+
def move(self, dx, dy):
|
| 76 |
+
self.centre = (self.centre[0] + dx, self.centre[1] + dy)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def round_start_circle_stable_containment(c0, r0, c1, r1):
|
| 80 |
+
"""Round start circle so that it stays inside/outside end circle after rounding.
|
| 81 |
+
|
| 82 |
+
The rounding of circle coordinates to integers may cause an abrupt change
|
| 83 |
+
if the start circle c0 is so close to the end circle c1's perimiter that
|
| 84 |
+
it ends up falling outside (or inside) as a result of the rounding.
|
| 85 |
+
To keep the gradient unchanged, we nudge it in the right direction.
|
| 86 |
+
|
| 87 |
+
See:
|
| 88 |
+
https://github.com/googlefonts/colr-gradients-spec/issues/204
|
| 89 |
+
https://github.com/googlefonts/picosvg/issues/158
|
| 90 |
+
"""
|
| 91 |
+
start, end = Circle(c0, r0), Circle(c1, r1)
|
| 92 |
+
|
| 93 |
+
inside_before_round = start.inside(end)
|
| 94 |
+
|
| 95 |
+
round_start = start.round()
|
| 96 |
+
round_end = end.round()
|
| 97 |
+
inside_after_round = round_start.inside(round_end)
|
| 98 |
+
|
| 99 |
+
if inside_before_round == inside_after_round:
|
| 100 |
+
return round_start
|
| 101 |
+
elif inside_after_round:
|
| 102 |
+
# start was outside before rounding: we need to push start away from end
|
| 103 |
+
direction = _vector_between(round_end.centre, round_start.centre)
|
| 104 |
+
radius_delta = +1.0
|
| 105 |
+
else:
|
| 106 |
+
# start was inside before rounding: we need to push start towards end
|
| 107 |
+
direction = _vector_between(round_start.centre, round_end.centre)
|
| 108 |
+
radius_delta = -1.0
|
| 109 |
+
dx, dy = _rounding_offset(direction)
|
| 110 |
+
|
| 111 |
+
# At most 2 iterations ought to be enough to converge. Before the loop, we
|
| 112 |
+
# know the start circle didn't keep containment after normal rounding; thus
|
| 113 |
+
# we continue adjusting by -/+ 1.0 until containment is restored.
|
| 114 |
+
# Normal rounding can at most move each coordinates -/+0.5; in the worst case
|
| 115 |
+
# both the start and end circle's centres and radii will be rounded in opposite
|
| 116 |
+
# directions, e.g. when they move along a 45 degree diagonal:
|
| 117 |
+
# c0 = (1.5, 1.5) ===> (2.0, 2.0)
|
| 118 |
+
# r0 = 0.5 ===> 1.0
|
| 119 |
+
# c1 = (0.499, 0.499) ===> (0.0, 0.0)
|
| 120 |
+
# r1 = 2.499 ===> 2.0
|
| 121 |
+
# In this example, the relative distance between the circles, calculated
|
| 122 |
+
# as r1 - (r0 + distance(c0, c1)) is initially 0.57437 (c0 is inside c1), and
|
| 123 |
+
# -1.82842 after rounding (c0 is now outside c1). Nudging c0 by -1.0 on both
|
| 124 |
+
# x and y axes moves it towards c1 by hypot(-1.0, -1.0) = 1.41421. Two of these
|
| 125 |
+
# moves cover twice that distance, which is enough to restore containment.
|
| 126 |
+
max_attempts = 2
|
| 127 |
+
for _ in range(max_attempts):
|
| 128 |
+
if round_start.concentric(round_end):
|
| 129 |
+
# can't move c0 towards c1 (they are the same), so we change the radius
|
| 130 |
+
round_start.radius += radius_delta
|
| 131 |
+
assert round_start.radius >= 0
|
| 132 |
+
else:
|
| 133 |
+
round_start.move(dx, dy)
|
| 134 |
+
if inside_before_round == round_start.inside(round_end):
|
| 135 |
+
break
|
| 136 |
+
else: # likely a bug
|
| 137 |
+
raise AssertionError(
|
| 138 |
+
f"Rounding circle {start} "
|
| 139 |
+
f"{'inside' if inside_before_round else 'outside'} "
|
| 140 |
+
f"{end} failed after {max_attempts} attempts!"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
return round_start
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/config/__init__.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Define all configuration options that can affect the working of fontTools
|
| 3 |
+
modules. E.g. optimization levels of varLib IUP, otlLib GPOS compression level,
|
| 4 |
+
etc. If this file gets too big, split it into smaller files per-module.
|
| 5 |
+
|
| 6 |
+
An instance of the Config class can be attached to a TTFont object, so that
|
| 7 |
+
the various modules can access their configuration options from it.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from textwrap import dedent
|
| 11 |
+
|
| 12 |
+
from fontTools.misc.configTools import *
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Config(AbstractConfig):
|
| 16 |
+
options = Options()
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
OPTIONS = Config.options
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
Config.register_option(
|
| 23 |
+
name="fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL",
|
| 24 |
+
help=dedent(
|
| 25 |
+
"""\
|
| 26 |
+
GPOS Lookup type 2 (PairPos) compression level:
|
| 27 |
+
0 = do not attempt to compact PairPos lookups;
|
| 28 |
+
1 to 8 = create at most 1 to 8 new subtables for each existing
|
| 29 |
+
subtable, provided that it would yield a 50%% file size saving;
|
| 30 |
+
9 = create as many new subtables as needed to yield a file size saving.
|
| 31 |
+
Default: 0.
|
| 32 |
+
|
| 33 |
+
This compaction aims to save file size, by splitting large class
|
| 34 |
+
kerning subtables (Format 2) that contain many zero values into
|
| 35 |
+
smaller and denser subtables. It's a trade-off between the overhead
|
| 36 |
+
of several subtables versus the sparseness of one big subtable.
|
| 37 |
+
|
| 38 |
+
See the pull request: https://github.com/fonttools/fonttools/pull/2326
|
| 39 |
+
"""
|
| 40 |
+
),
|
| 41 |
+
default=0,
|
| 42 |
+
parse=int,
|
| 43 |
+
validate=lambda v: v in range(10),
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
Config.register_option(
|
| 47 |
+
name="fontTools.ttLib.tables.otBase:USE_HARFBUZZ_REPACKER",
|
| 48 |
+
help=dedent(
|
| 49 |
+
"""\
|
| 50 |
+
FontTools tries to use the HarfBuzz Repacker to serialize GPOS/GSUB tables
|
| 51 |
+
if the uharfbuzz python bindings are importable, otherwise falls back to its
|
| 52 |
+
slower, less efficient serializer. Set to False to always use the latter.
|
| 53 |
+
Set to True to explicitly request the HarfBuzz Repacker (will raise an
|
| 54 |
+
error if uharfbuzz cannot be imported).
|
| 55 |
+
"""
|
| 56 |
+
),
|
| 57 |
+
default=None,
|
| 58 |
+
parse=Option.parse_optional_bool,
|
| 59 |
+
validate=Option.validate_optional_bool,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
Config.register_option(
|
| 63 |
+
name="fontTools.otlLib.builder:WRITE_GPOS7",
|
| 64 |
+
help=dedent(
|
| 65 |
+
"""\
|
| 66 |
+
macOS before 13.2 didn’t support GPOS LookupType 7 (non-chaining
|
| 67 |
+
ContextPos lookups), so FontTools.otlLib.builder disables a file size
|
| 68 |
+
optimisation that would use LookupType 7 instead of 8 when there is no
|
| 69 |
+
chaining (no prefix or suffix). Set to True to enable the optimization.
|
| 70 |
+
"""
|
| 71 |
+
),
|
| 72 |
+
default=False,
|
| 73 |
+
parse=Option.parse_optional_bool,
|
| 74 |
+
validate=Option.validate_optional_bool,
|
| 75 |
+
)
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/config/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (2.84 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/feaLib/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""fontTools.feaLib -- a package for dealing with OpenType feature files."""
|
| 2 |
+
|
| 3 |
+
# The structure of OpenType feature files is defined here:
|
| 4 |
+
# http://www.adobe.com/devnet/opentype/afdko/topic_feature_file_syntax.html
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Empty __init__.py file to signal Python this directory is a package."""
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (252 Bytes). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/areaPen.cpython-310.pyc
ADDED
|
Binary file (2.04 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/basePen.cpython-310.pyc
ADDED
|
Binary file (16.7 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/boundsPen.cpython-310.pyc
ADDED
|
Binary file (3.48 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/cairoPen.cpython-310.pyc
ADDED
|
Binary file (1.25 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/cocoaPen.cpython-310.pyc
ADDED
|
Binary file (1.28 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/cu2quPen.cpython-310.pyc
ADDED
|
Binary file (10.6 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/explicitClosingLinePen.cpython-310.pyc
ADDED
|
Binary file (3.52 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/filterPen.cpython-310.pyc
ADDED
|
Binary file (8.97 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/hashPointPen.cpython-310.pyc
ADDED
|
Binary file (4.15 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/momentsPen.cpython-310.pyc
ADDED
|
Binary file (15.7 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/perimeterPen.cpython-310.pyc
ADDED
|
Binary file (2.81 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/pointInsidePen.cpython-310.pyc
ADDED
|
Binary file (5.26 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/qtPen.cpython-310.pyc
ADDED
|
Binary file (1.39 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/quartzPen.cpython-310.pyc
ADDED
|
Binary file (1.92 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/recordingPen.cpython-310.pyc
ADDED
|
Binary file (13.5 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/roundingPen.cpython-310.pyc
ADDED
|
Binary file (5.02 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/__pycache__/wxPen.cpython-310.pyc
ADDED
|
Binary file (1.43 kB). View file
|
|
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/areaPen.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Calculate the area of a glyph."""
|
| 2 |
+
|
| 3 |
+
from fontTools.pens.basePen import BasePen
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
__all__ = ["AreaPen"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class AreaPen(BasePen):
|
| 10 |
+
def __init__(self, glyphset=None):
|
| 11 |
+
BasePen.__init__(self, glyphset)
|
| 12 |
+
self.value = 0
|
| 13 |
+
|
| 14 |
+
def _moveTo(self, p0):
|
| 15 |
+
self._p0 = self._startPoint = p0
|
| 16 |
+
|
| 17 |
+
def _lineTo(self, p1):
|
| 18 |
+
x0, y0 = self._p0
|
| 19 |
+
x1, y1 = p1
|
| 20 |
+
self.value -= (x1 - x0) * (y1 + y0) * 0.5
|
| 21 |
+
self._p0 = p1
|
| 22 |
+
|
| 23 |
+
def _qCurveToOne(self, p1, p2):
|
| 24 |
+
# https://github.com/Pomax/bezierinfo/issues/44
|
| 25 |
+
p0 = self._p0
|
| 26 |
+
x0, y0 = p0[0], p0[1]
|
| 27 |
+
x1, y1 = p1[0] - x0, p1[1] - y0
|
| 28 |
+
x2, y2 = p2[0] - x0, p2[1] - y0
|
| 29 |
+
self.value -= (x2 * y1 - x1 * y2) / 3
|
| 30 |
+
self._lineTo(p2)
|
| 31 |
+
self._p0 = p2
|
| 32 |
+
|
| 33 |
+
def _curveToOne(self, p1, p2, p3):
|
| 34 |
+
# https://github.com/Pomax/bezierinfo/issues/44
|
| 35 |
+
p0 = self._p0
|
| 36 |
+
x0, y0 = p0[0], p0[1]
|
| 37 |
+
x1, y1 = p1[0] - x0, p1[1] - y0
|
| 38 |
+
x2, y2 = p2[0] - x0, p2[1] - y0
|
| 39 |
+
x3, y3 = p3[0] - x0, p3[1] - y0
|
| 40 |
+
self.value -= (x1 * (-y2 - y3) + x2 * (y1 - 2 * y3) + x3 * (y1 + 2 * y2)) * 0.15
|
| 41 |
+
self._lineTo(p3)
|
| 42 |
+
self._p0 = p3
|
| 43 |
+
|
| 44 |
+
def _closePath(self):
|
| 45 |
+
self._lineTo(self._startPoint)
|
| 46 |
+
del self._p0, self._startPoint
|
| 47 |
+
|
| 48 |
+
def _endPath(self):
|
| 49 |
+
if self._p0 != self._startPoint:
|
| 50 |
+
# Area is not defined for open contours.
|
| 51 |
+
raise NotImplementedError
|
| 52 |
+
del self._p0, self._startPoint
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/basePen.py
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""fontTools.pens.basePen.py -- Tools and base classes to build pen objects.
|
| 2 |
+
|
| 3 |
+
The Pen Protocol
|
| 4 |
+
|
| 5 |
+
A Pen is a kind of object that standardizes the way how to "draw" outlines:
|
| 6 |
+
it is a middle man between an outline and a drawing. In other words:
|
| 7 |
+
it is an abstraction for drawing outlines, making sure that outline objects
|
| 8 |
+
don't need to know the details about how and where they're being drawn, and
|
| 9 |
+
that drawings don't need to know the details of how outlines are stored.
|
| 10 |
+
|
| 11 |
+
The most basic pattern is this::
|
| 12 |
+
|
| 13 |
+
outline.draw(pen) # 'outline' draws itself onto 'pen'
|
| 14 |
+
|
| 15 |
+
Pens can be used to render outlines to the screen, but also to construct
|
| 16 |
+
new outlines. Eg. an outline object can be both a drawable object (it has a
|
| 17 |
+
draw() method) as well as a pen itself: you *build* an outline using pen
|
| 18 |
+
methods.
|
| 19 |
+
|
| 20 |
+
The AbstractPen class defines the Pen protocol. It implements almost
|
| 21 |
+
nothing (only no-op closePath() and endPath() methods), but is useful
|
| 22 |
+
for documentation purposes. Subclassing it basically tells the reader:
|
| 23 |
+
"this class implements the Pen protocol.". An examples of an AbstractPen
|
| 24 |
+
subclass is :py:class:`fontTools.pens.transformPen.TransformPen`.
|
| 25 |
+
|
| 26 |
+
The BasePen class is a base implementation useful for pens that actually
|
| 27 |
+
draw (for example a pen renders outlines using a native graphics engine).
|
| 28 |
+
BasePen contains a lot of base functionality, making it very easy to build
|
| 29 |
+
a pen that fully conforms to the pen protocol. Note that if you subclass
|
| 30 |
+
BasePen, you *don't* override moveTo(), lineTo(), etc., but _moveTo(),
|
| 31 |
+
_lineTo(), etc. See the BasePen doc string for details. Examples of
|
| 32 |
+
BasePen subclasses are fontTools.pens.boundsPen.BoundsPen and
|
| 33 |
+
fontTools.pens.cocoaPen.CocoaPen.
|
| 34 |
+
|
| 35 |
+
Coordinates are usually expressed as (x, y) tuples, but generally any
|
| 36 |
+
sequence of length 2 will do.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
from typing import Tuple, Dict
|
| 40 |
+
|
| 41 |
+
from fontTools.misc.loggingTools import LogMixin
|
| 42 |
+
from fontTools.misc.transform import DecomposedTransform, Identity
|
| 43 |
+
|
| 44 |
+
__all__ = [
|
| 45 |
+
"AbstractPen",
|
| 46 |
+
"NullPen",
|
| 47 |
+
"BasePen",
|
| 48 |
+
"PenError",
|
| 49 |
+
"decomposeSuperBezierSegment",
|
| 50 |
+
"decomposeQuadraticSegment",
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class PenError(Exception):
|
| 55 |
+
"""Represents an error during penning."""
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class OpenContourError(PenError):
|
| 59 |
+
pass
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class AbstractPen:
|
| 63 |
+
def moveTo(self, pt: Tuple[float, float]) -> None:
|
| 64 |
+
"""Begin a new sub path, set the current point to 'pt'. You must
|
| 65 |
+
end each sub path with a call to pen.closePath() or pen.endPath().
|
| 66 |
+
"""
|
| 67 |
+
raise NotImplementedError
|
| 68 |
+
|
| 69 |
+
def lineTo(self, pt: Tuple[float, float]) -> None:
|
| 70 |
+
"""Draw a straight line from the current point to 'pt'."""
|
| 71 |
+
raise NotImplementedError
|
| 72 |
+
|
| 73 |
+
def curveTo(self, *points: Tuple[float, float]) -> None:
|
| 74 |
+
"""Draw a cubic bezier with an arbitrary number of control points.
|
| 75 |
+
|
| 76 |
+
The last point specified is on-curve, all others are off-curve
|
| 77 |
+
(control) points. If the number of control points is > 2, the
|
| 78 |
+
segment is split into multiple bezier segments. This works
|
| 79 |
+
like this:
|
| 80 |
+
|
| 81 |
+
Let n be the number of control points (which is the number of
|
| 82 |
+
arguments to this call minus 1). If n==2, a plain vanilla cubic
|
| 83 |
+
bezier is drawn. If n==1, we fall back to a quadratic segment and
|
| 84 |
+
if n==0 we draw a straight line. It gets interesting when n>2:
|
| 85 |
+
n-1 PostScript-style cubic segments will be drawn as if it were
|
| 86 |
+
one curve. See decomposeSuperBezierSegment().
|
| 87 |
+
|
| 88 |
+
The conversion algorithm used for n>2 is inspired by NURB
|
| 89 |
+
splines, and is conceptually equivalent to the TrueType "implied
|
| 90 |
+
points" principle. See also decomposeQuadraticSegment().
|
| 91 |
+
"""
|
| 92 |
+
raise NotImplementedError
|
| 93 |
+
|
| 94 |
+
def qCurveTo(self, *points: Tuple[float, float]) -> None:
|
| 95 |
+
"""Draw a whole string of quadratic curve segments.
|
| 96 |
+
|
| 97 |
+
The last point specified is on-curve, all others are off-curve
|
| 98 |
+
points.
|
| 99 |
+
|
| 100 |
+
This method implements TrueType-style curves, breaking up curves
|
| 101 |
+
using 'implied points': between each two consequtive off-curve points,
|
| 102 |
+
there is one implied point exactly in the middle between them. See
|
| 103 |
+
also decomposeQuadraticSegment().
|
| 104 |
+
|
| 105 |
+
The last argument (normally the on-curve point) may be None.
|
| 106 |
+
This is to support contours that have NO on-curve points (a rarely
|
| 107 |
+
seen feature of TrueType outlines).
|
| 108 |
+
"""
|
| 109 |
+
raise NotImplementedError
|
| 110 |
+
|
| 111 |
+
def closePath(self) -> None:
|
| 112 |
+
"""Close the current sub path. You must call either pen.closePath()
|
| 113 |
+
or pen.endPath() after each sub path.
|
| 114 |
+
"""
|
| 115 |
+
pass
|
| 116 |
+
|
| 117 |
+
def endPath(self) -> None:
|
| 118 |
+
"""End the current sub path, but don't close it. You must call
|
| 119 |
+
either pen.closePath() or pen.endPath() after each sub path.
|
| 120 |
+
"""
|
| 121 |
+
pass
|
| 122 |
+
|
| 123 |
+
def addComponent(
|
| 124 |
+
self,
|
| 125 |
+
glyphName: str,
|
| 126 |
+
transformation: Tuple[float, float, float, float, float, float],
|
| 127 |
+
) -> None:
|
| 128 |
+
"""Add a sub glyph. The 'transformation' argument must be a 6-tuple
|
| 129 |
+
containing an affine transformation, or a Transform object from the
|
| 130 |
+
fontTools.misc.transform module. More precisely: it should be a
|
| 131 |
+
sequence containing 6 numbers.
|
| 132 |
+
"""
|
| 133 |
+
raise NotImplementedError
|
| 134 |
+
|
| 135 |
+
def addVarComponent(
|
| 136 |
+
self,
|
| 137 |
+
glyphName: str,
|
| 138 |
+
transformation: DecomposedTransform,
|
| 139 |
+
location: Dict[str, float],
|
| 140 |
+
) -> None:
|
| 141 |
+
"""Add a VarComponent sub glyph. The 'transformation' argument
|
| 142 |
+
must be a DecomposedTransform from the fontTools.misc.transform module,
|
| 143 |
+
and the 'location' argument must be a dictionary mapping axis tags
|
| 144 |
+
to their locations.
|
| 145 |
+
"""
|
| 146 |
+
# GlyphSet decomposes for us
|
| 147 |
+
raise AttributeError
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class NullPen(AbstractPen):
|
| 151 |
+
"""A pen that does nothing."""
|
| 152 |
+
|
| 153 |
+
def moveTo(self, pt):
|
| 154 |
+
pass
|
| 155 |
+
|
| 156 |
+
def lineTo(self, pt):
|
| 157 |
+
pass
|
| 158 |
+
|
| 159 |
+
def curveTo(self, *points):
|
| 160 |
+
pass
|
| 161 |
+
|
| 162 |
+
def qCurveTo(self, *points):
|
| 163 |
+
pass
|
| 164 |
+
|
| 165 |
+
def closePath(self):
|
| 166 |
+
pass
|
| 167 |
+
|
| 168 |
+
def endPath(self):
|
| 169 |
+
pass
|
| 170 |
+
|
| 171 |
+
def addComponent(self, glyphName, transformation):
|
| 172 |
+
pass
|
| 173 |
+
|
| 174 |
+
def addVarComponent(self, glyphName, transformation, location):
|
| 175 |
+
pass
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class LoggingPen(LogMixin, AbstractPen):
|
| 179 |
+
"""A pen with a ``log`` property (see fontTools.misc.loggingTools.LogMixin)"""
|
| 180 |
+
|
| 181 |
+
pass
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class MissingComponentError(KeyError):
|
| 185 |
+
"""Indicates a component pointing to a non-existent glyph in the glyphset."""
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class DecomposingPen(LoggingPen):
|
| 189 |
+
"""Implements a 'addComponent' method that decomposes components
|
| 190 |
+
(i.e. draws them onto self as simple contours).
|
| 191 |
+
It can also be used as a mixin class (e.g. see ContourRecordingPen).
|
| 192 |
+
|
| 193 |
+
You must override moveTo, lineTo, curveTo and qCurveTo. You may
|
| 194 |
+
additionally override closePath, endPath and addComponent.
|
| 195 |
+
|
| 196 |
+
By default a warning message is logged when a base glyph is missing;
|
| 197 |
+
set the class variable ``skipMissingComponents`` to False if you want
|
| 198 |
+
all instances of a sub-class to raise a :class:`MissingComponentError`
|
| 199 |
+
exception by default.
|
| 200 |
+
"""
|
| 201 |
+
|
| 202 |
+
skipMissingComponents = True
|
| 203 |
+
# alias error for convenience
|
| 204 |
+
MissingComponentError = MissingComponentError
|
| 205 |
+
|
| 206 |
+
def __init__(
|
| 207 |
+
self,
|
| 208 |
+
glyphSet,
|
| 209 |
+
*args,
|
| 210 |
+
skipMissingComponents=None,
|
| 211 |
+
reverseFlipped=False,
|
| 212 |
+
**kwargs,
|
| 213 |
+
):
|
| 214 |
+
"""Takes a 'glyphSet' argument (dict), in which the glyphs that are referenced
|
| 215 |
+
as components are looked up by their name.
|
| 216 |
+
|
| 217 |
+
If the optional 'reverseFlipped' argument is True, components whose transformation
|
| 218 |
+
matrix has a negative determinant will be decomposed with a reversed path direction
|
| 219 |
+
to compensate for the flip.
|
| 220 |
+
|
| 221 |
+
The optional 'skipMissingComponents' argument can be set to True/False to
|
| 222 |
+
override the homonymous class attribute for a given pen instance.
|
| 223 |
+
"""
|
| 224 |
+
super(DecomposingPen, self).__init__(*args, **kwargs)
|
| 225 |
+
self.glyphSet = glyphSet
|
| 226 |
+
self.skipMissingComponents = (
|
| 227 |
+
self.__class__.skipMissingComponents
|
| 228 |
+
if skipMissingComponents is None
|
| 229 |
+
else skipMissingComponents
|
| 230 |
+
)
|
| 231 |
+
self.reverseFlipped = reverseFlipped
|
| 232 |
+
|
| 233 |
+
def addComponent(self, glyphName, transformation):
|
| 234 |
+
"""Transform the points of the base glyph and draw it onto self."""
|
| 235 |
+
from fontTools.pens.transformPen import TransformPen
|
| 236 |
+
|
| 237 |
+
try:
|
| 238 |
+
glyph = self.glyphSet[glyphName]
|
| 239 |
+
except KeyError:
|
| 240 |
+
if not self.skipMissingComponents:
|
| 241 |
+
raise MissingComponentError(glyphName)
|
| 242 |
+
self.log.warning("glyph '%s' is missing from glyphSet; skipped" % glyphName)
|
| 243 |
+
else:
|
| 244 |
+
pen = self
|
| 245 |
+
if transformation != Identity:
|
| 246 |
+
pen = TransformPen(pen, transformation)
|
| 247 |
+
if self.reverseFlipped:
|
| 248 |
+
# if the transformation has a negative determinant, it will
|
| 249 |
+
# reverse the contour direction of the component
|
| 250 |
+
a, b, c, d = transformation[:4]
|
| 251 |
+
det = a * d - b * c
|
| 252 |
+
if det < 0:
|
| 253 |
+
from fontTools.pens.reverseContourPen import ReverseContourPen
|
| 254 |
+
|
| 255 |
+
pen = ReverseContourPen(pen)
|
| 256 |
+
glyph.draw(pen)
|
| 257 |
+
|
| 258 |
+
def addVarComponent(self, glyphName, transformation, location):
|
| 259 |
+
# GlyphSet decomposes for us
|
| 260 |
+
raise AttributeError
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class BasePen(DecomposingPen):
|
| 264 |
+
"""Base class for drawing pens. You must override _moveTo, _lineTo and
|
| 265 |
+
_curveToOne. You may additionally override _closePath, _endPath,
|
| 266 |
+
addComponent, addVarComponent, and/or _qCurveToOne. You should not
|
| 267 |
+
override any other methods.
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
def __init__(self, glyphSet=None):
|
| 271 |
+
super(BasePen, self).__init__(glyphSet)
|
| 272 |
+
self.__currentPoint = None
|
| 273 |
+
|
| 274 |
+
# must override
|
| 275 |
+
|
| 276 |
+
def _moveTo(self, pt):
|
| 277 |
+
raise NotImplementedError
|
| 278 |
+
|
| 279 |
+
def _lineTo(self, pt):
|
| 280 |
+
raise NotImplementedError
|
| 281 |
+
|
| 282 |
+
def _curveToOne(self, pt1, pt2, pt3):
|
| 283 |
+
raise NotImplementedError
|
| 284 |
+
|
| 285 |
+
# may override
|
| 286 |
+
|
| 287 |
+
def _closePath(self):
|
| 288 |
+
pass
|
| 289 |
+
|
| 290 |
+
def _endPath(self):
|
| 291 |
+
pass
|
| 292 |
+
|
| 293 |
+
def _qCurveToOne(self, pt1, pt2):
|
| 294 |
+
"""This method implements the basic quadratic curve type. The
|
| 295 |
+
default implementation delegates the work to the cubic curve
|
| 296 |
+
function. Optionally override with a native implementation.
|
| 297 |
+
"""
|
| 298 |
+
pt0x, pt0y = self.__currentPoint
|
| 299 |
+
pt1x, pt1y = pt1
|
| 300 |
+
pt2x, pt2y = pt2
|
| 301 |
+
mid1x = pt0x + 0.66666666666666667 * (pt1x - pt0x)
|
| 302 |
+
mid1y = pt0y + 0.66666666666666667 * (pt1y - pt0y)
|
| 303 |
+
mid2x = pt2x + 0.66666666666666667 * (pt1x - pt2x)
|
| 304 |
+
mid2y = pt2y + 0.66666666666666667 * (pt1y - pt2y)
|
| 305 |
+
self._curveToOne((mid1x, mid1y), (mid2x, mid2y), pt2)
|
| 306 |
+
|
| 307 |
+
# don't override
|
| 308 |
+
|
| 309 |
+
def _getCurrentPoint(self):
|
| 310 |
+
"""Return the current point. This is not part of the public
|
| 311 |
+
interface, yet is useful for subclasses.
|
| 312 |
+
"""
|
| 313 |
+
return self.__currentPoint
|
| 314 |
+
|
| 315 |
+
def closePath(self):
|
| 316 |
+
self._closePath()
|
| 317 |
+
self.__currentPoint = None
|
| 318 |
+
|
| 319 |
+
def endPath(self):
|
| 320 |
+
self._endPath()
|
| 321 |
+
self.__currentPoint = None
|
| 322 |
+
|
| 323 |
+
def moveTo(self, pt):
|
| 324 |
+
self._moveTo(pt)
|
| 325 |
+
self.__currentPoint = pt
|
| 326 |
+
|
| 327 |
+
def lineTo(self, pt):
|
| 328 |
+
self._lineTo(pt)
|
| 329 |
+
self.__currentPoint = pt
|
| 330 |
+
|
| 331 |
+
def curveTo(self, *points):
|
| 332 |
+
n = len(points) - 1 # 'n' is the number of control points
|
| 333 |
+
assert n >= 0
|
| 334 |
+
if n == 2:
|
| 335 |
+
# The common case, we have exactly two BCP's, so this is a standard
|
| 336 |
+
# cubic bezier. Even though decomposeSuperBezierSegment() handles
|
| 337 |
+
# this case just fine, we special-case it anyway since it's so
|
| 338 |
+
# common.
|
| 339 |
+
self._curveToOne(*points)
|
| 340 |
+
self.__currentPoint = points[-1]
|
| 341 |
+
elif n > 2:
|
| 342 |
+
# n is the number of control points; split curve into n-1 cubic
|
| 343 |
+
# bezier segments. The algorithm used here is inspired by NURB
|
| 344 |
+
# splines and the TrueType "implied point" principle, and ensures
|
| 345 |
+
# the smoothest possible connection between two curve segments,
|
| 346 |
+
# with no disruption in the curvature. It is practical since it
|
| 347 |
+
# allows one to construct multiple bezier segments with a much
|
| 348 |
+
# smaller amount of points.
|
| 349 |
+
_curveToOne = self._curveToOne
|
| 350 |
+
for pt1, pt2, pt3 in decomposeSuperBezierSegment(points):
|
| 351 |
+
_curveToOne(pt1, pt2, pt3)
|
| 352 |
+
self.__currentPoint = pt3
|
| 353 |
+
elif n == 1:
|
| 354 |
+
self.qCurveTo(*points)
|
| 355 |
+
elif n == 0:
|
| 356 |
+
self.lineTo(points[0])
|
| 357 |
+
else:
|
| 358 |
+
raise AssertionError("can't get there from here")
|
| 359 |
+
|
| 360 |
+
def qCurveTo(self, *points):
|
| 361 |
+
n = len(points) - 1 # 'n' is the number of control points
|
| 362 |
+
assert n >= 0
|
| 363 |
+
if points[-1] is None:
|
| 364 |
+
# Special case for TrueType quadratics: it is possible to
|
| 365 |
+
# define a contour with NO on-curve points. BasePen supports
|
| 366 |
+
# this by allowing the final argument (the expected on-curve
|
| 367 |
+
# point) to be None. We simulate the feature by making the implied
|
| 368 |
+
# on-curve point between the last and the first off-curve points
|
| 369 |
+
# explicit.
|
| 370 |
+
x, y = points[-2] # last off-curve point
|
| 371 |
+
nx, ny = points[0] # first off-curve point
|
| 372 |
+
impliedStartPoint = (0.5 * (x + nx), 0.5 * (y + ny))
|
| 373 |
+
self.__currentPoint = impliedStartPoint
|
| 374 |
+
self._moveTo(impliedStartPoint)
|
| 375 |
+
points = points[:-1] + (impliedStartPoint,)
|
| 376 |
+
if n > 0:
|
| 377 |
+
# Split the string of points into discrete quadratic curve
|
| 378 |
+
# segments. Between any two consecutive off-curve points
|
| 379 |
+
# there's an implied on-curve point exactly in the middle.
|
| 380 |
+
# This is where the segment splits.
|
| 381 |
+
_qCurveToOne = self._qCurveToOne
|
| 382 |
+
for pt1, pt2 in decomposeQuadraticSegment(points):
|
| 383 |
+
_qCurveToOne(pt1, pt2)
|
| 384 |
+
self.__currentPoint = pt2
|
| 385 |
+
else:
|
| 386 |
+
self.lineTo(points[0])
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def decomposeSuperBezierSegment(points):
|
| 390 |
+
"""Split the SuperBezier described by 'points' into a list of regular
|
| 391 |
+
bezier segments. The 'points' argument must be a sequence with length
|
| 392 |
+
3 or greater, containing (x, y) coordinates. The last point is the
|
| 393 |
+
destination on-curve point, the rest of the points are off-curve points.
|
| 394 |
+
The start point should not be supplied.
|
| 395 |
+
|
| 396 |
+
This function returns a list of (pt1, pt2, pt3) tuples, which each
|
| 397 |
+
specify a regular curveto-style bezier segment.
|
| 398 |
+
"""
|
| 399 |
+
n = len(points) - 1
|
| 400 |
+
assert n > 1
|
| 401 |
+
bezierSegments = []
|
| 402 |
+
pt1, pt2, pt3 = points[0], None, None
|
| 403 |
+
for i in range(2, n + 1):
|
| 404 |
+
# calculate points in between control points.
|
| 405 |
+
nDivisions = min(i, 3, n - i + 2)
|
| 406 |
+
for j in range(1, nDivisions):
|
| 407 |
+
factor = j / nDivisions
|
| 408 |
+
temp1 = points[i - 1]
|
| 409 |
+
temp2 = points[i - 2]
|
| 410 |
+
temp = (
|
| 411 |
+
temp2[0] + factor * (temp1[0] - temp2[0]),
|
| 412 |
+
temp2[1] + factor * (temp1[1] - temp2[1]),
|
| 413 |
+
)
|
| 414 |
+
if pt2 is None:
|
| 415 |
+
pt2 = temp
|
| 416 |
+
else:
|
| 417 |
+
pt3 = (0.5 * (pt2[0] + temp[0]), 0.5 * (pt2[1] + temp[1]))
|
| 418 |
+
bezierSegments.append((pt1, pt2, pt3))
|
| 419 |
+
pt1, pt2, pt3 = temp, None, None
|
| 420 |
+
bezierSegments.append((pt1, points[-2], points[-1]))
|
| 421 |
+
return bezierSegments
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def decomposeQuadraticSegment(points):
|
| 425 |
+
"""Split the quadratic curve segment described by 'points' into a list
|
| 426 |
+
of "atomic" quadratic segments. The 'points' argument must be a sequence
|
| 427 |
+
with length 2 or greater, containing (x, y) coordinates. The last point
|
| 428 |
+
is the destination on-curve point, the rest of the points are off-curve
|
| 429 |
+
points. The start point should not be supplied.
|
| 430 |
+
|
| 431 |
+
This function returns a list of (pt1, pt2) tuples, which each specify a
|
| 432 |
+
plain quadratic bezier segment.
|
| 433 |
+
"""
|
| 434 |
+
n = len(points) - 1
|
| 435 |
+
assert n > 0
|
| 436 |
+
quadSegments = []
|
| 437 |
+
for i in range(n - 1):
|
| 438 |
+
x, y = points[i]
|
| 439 |
+
nx, ny = points[i + 1]
|
| 440 |
+
impliedPt = (0.5 * (x + nx), 0.5 * (y + ny))
|
| 441 |
+
quadSegments.append((points[i], impliedPt))
|
| 442 |
+
quadSegments.append((points[-2], points[-1]))
|
| 443 |
+
return quadSegments
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
class _TestPen(BasePen):
|
| 447 |
+
"""Test class that prints PostScript to stdout."""
|
| 448 |
+
|
| 449 |
+
def _moveTo(self, pt):
|
| 450 |
+
print("%s %s moveto" % (pt[0], pt[1]))
|
| 451 |
+
|
| 452 |
+
def _lineTo(self, pt):
|
| 453 |
+
print("%s %s lineto" % (pt[0], pt[1]))
|
| 454 |
+
|
| 455 |
+
def _curveToOne(self, bcp1, bcp2, pt):
|
| 456 |
+
print(
|
| 457 |
+
"%s %s %s %s %s %s curveto"
|
| 458 |
+
% (bcp1[0], bcp1[1], bcp2[0], bcp2[1], pt[0], pt[1])
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
def _closePath(self):
|
| 462 |
+
print("closepath")
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
if __name__ == "__main__":
|
| 466 |
+
pen = _TestPen(None)
|
| 467 |
+
pen.moveTo((0, 0))
|
| 468 |
+
pen.lineTo((0, 100))
|
| 469 |
+
pen.curveTo((50, 75), (60, 50), (50, 25), (0, 0))
|
| 470 |
+
pen.closePath()
|
| 471 |
+
|
| 472 |
+
pen = _TestPen(None)
|
| 473 |
+
# testing the "no on-curve point" scenario
|
| 474 |
+
pen.qCurveTo((0, 0), (0, 100), (100, 100), (100, 0), None)
|
| 475 |
+
pen.closePath()
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/boundsPen.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.misc.arrayTools import updateBounds, pointInRect, unionRect
|
| 2 |
+
from fontTools.misc.bezierTools import calcCubicBounds, calcQuadraticBounds
|
| 3 |
+
from fontTools.pens.basePen import BasePen
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
__all__ = ["BoundsPen", "ControlBoundsPen"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ControlBoundsPen(BasePen):
|
| 10 |
+
"""Pen to calculate the "control bounds" of a shape. This is the
|
| 11 |
+
bounding box of all control points, so may be larger than the
|
| 12 |
+
actual bounding box if there are curves that don't have points
|
| 13 |
+
on their extremes.
|
| 14 |
+
|
| 15 |
+
When the shape has been drawn, the bounds are available as the
|
| 16 |
+
``bounds`` attribute of the pen object. It's a 4-tuple::
|
| 17 |
+
|
| 18 |
+
(xMin, yMin, xMax, yMax).
|
| 19 |
+
|
| 20 |
+
If ``ignoreSinglePoints`` is True, single points are ignored.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, glyphSet, ignoreSinglePoints=False):
|
| 24 |
+
BasePen.__init__(self, glyphSet)
|
| 25 |
+
self.ignoreSinglePoints = ignoreSinglePoints
|
| 26 |
+
self.init()
|
| 27 |
+
|
| 28 |
+
def init(self):
|
| 29 |
+
self.bounds = None
|
| 30 |
+
self._start = None
|
| 31 |
+
|
| 32 |
+
def _moveTo(self, pt):
|
| 33 |
+
self._start = pt
|
| 34 |
+
if not self.ignoreSinglePoints:
|
| 35 |
+
self._addMoveTo()
|
| 36 |
+
|
| 37 |
+
def _addMoveTo(self):
|
| 38 |
+
if self._start is None:
|
| 39 |
+
return
|
| 40 |
+
bounds = self.bounds
|
| 41 |
+
if bounds:
|
| 42 |
+
self.bounds = updateBounds(bounds, self._start)
|
| 43 |
+
else:
|
| 44 |
+
x, y = self._start
|
| 45 |
+
self.bounds = (x, y, x, y)
|
| 46 |
+
self._start = None
|
| 47 |
+
|
| 48 |
+
def _lineTo(self, pt):
|
| 49 |
+
self._addMoveTo()
|
| 50 |
+
self.bounds = updateBounds(self.bounds, pt)
|
| 51 |
+
|
| 52 |
+
def _curveToOne(self, bcp1, bcp2, pt):
|
| 53 |
+
self._addMoveTo()
|
| 54 |
+
bounds = self.bounds
|
| 55 |
+
bounds = updateBounds(bounds, bcp1)
|
| 56 |
+
bounds = updateBounds(bounds, bcp2)
|
| 57 |
+
bounds = updateBounds(bounds, pt)
|
| 58 |
+
self.bounds = bounds
|
| 59 |
+
|
| 60 |
+
def _qCurveToOne(self, bcp, pt):
|
| 61 |
+
self._addMoveTo()
|
| 62 |
+
bounds = self.bounds
|
| 63 |
+
bounds = updateBounds(bounds, bcp)
|
| 64 |
+
bounds = updateBounds(bounds, pt)
|
| 65 |
+
self.bounds = bounds
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class BoundsPen(ControlBoundsPen):
|
| 69 |
+
"""Pen to calculate the bounds of a shape. It calculates the
|
| 70 |
+
correct bounds even when the shape contains curves that don't
|
| 71 |
+
have points on their extremes. This is somewhat slower to compute
|
| 72 |
+
than the "control bounds".
|
| 73 |
+
|
| 74 |
+
When the shape has been drawn, the bounds are available as the
|
| 75 |
+
``bounds`` attribute of the pen object. It's a 4-tuple::
|
| 76 |
+
|
| 77 |
+
(xMin, yMin, xMax, yMax)
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
def _curveToOne(self, bcp1, bcp2, pt):
|
| 81 |
+
self._addMoveTo()
|
| 82 |
+
bounds = self.bounds
|
| 83 |
+
bounds = updateBounds(bounds, pt)
|
| 84 |
+
if not pointInRect(bcp1, bounds) or not pointInRect(bcp2, bounds):
|
| 85 |
+
bounds = unionRect(
|
| 86 |
+
bounds, calcCubicBounds(self._getCurrentPoint(), bcp1, bcp2, pt)
|
| 87 |
+
)
|
| 88 |
+
self.bounds = bounds
|
| 89 |
+
|
| 90 |
+
def _qCurveToOne(self, bcp, pt):
|
| 91 |
+
self._addMoveTo()
|
| 92 |
+
bounds = self.bounds
|
| 93 |
+
bounds = updateBounds(bounds, pt)
|
| 94 |
+
if not pointInRect(bcp, bounds):
|
| 95 |
+
bounds = unionRect(
|
| 96 |
+
bounds, calcQuadraticBounds(self._getCurrentPoint(), bcp, pt)
|
| 97 |
+
)
|
| 98 |
+
self.bounds = bounds
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/cocoaPen.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.pens.basePen import BasePen
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
__all__ = ["CocoaPen"]
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class CocoaPen(BasePen):
|
| 8 |
+
def __init__(self, glyphSet, path=None):
|
| 9 |
+
BasePen.__init__(self, glyphSet)
|
| 10 |
+
if path is None:
|
| 11 |
+
from AppKit import NSBezierPath
|
| 12 |
+
|
| 13 |
+
path = NSBezierPath.bezierPath()
|
| 14 |
+
self.path = path
|
| 15 |
+
|
| 16 |
+
def _moveTo(self, p):
|
| 17 |
+
self.path.moveToPoint_(p)
|
| 18 |
+
|
| 19 |
+
def _lineTo(self, p):
|
| 20 |
+
self.path.lineToPoint_(p)
|
| 21 |
+
|
| 22 |
+
def _curveToOne(self, p1, p2, p3):
|
| 23 |
+
self.path.curveToPoint_controlPoint1_controlPoint2_(p3, p1, p2)
|
| 24 |
+
|
| 25 |
+
def _closePath(self):
|
| 26 |
+
self.path.closePath()
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/cu2quPen.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2016 Google Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import operator
|
| 16 |
+
from fontTools.cu2qu import curve_to_quadratic, curves_to_quadratic
|
| 17 |
+
from fontTools.pens.basePen import decomposeSuperBezierSegment
|
| 18 |
+
from fontTools.pens.filterPen import FilterPen
|
| 19 |
+
from fontTools.pens.reverseContourPen import ReverseContourPen
|
| 20 |
+
from fontTools.pens.pointPen import BasePointToSegmentPen
|
| 21 |
+
from fontTools.pens.pointPen import ReverseContourPointPen
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Cu2QuPen(FilterPen):
|
| 25 |
+
"""A filter pen to convert cubic bezier curves to quadratic b-splines
|
| 26 |
+
using the FontTools SegmentPen protocol.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
|
| 30 |
+
other_pen: another SegmentPen used to draw the transformed outline.
|
| 31 |
+
max_err: maximum approximation error in font units. For optimal results,
|
| 32 |
+
if you know the UPEM of the font, we recommend setting this to a
|
| 33 |
+
value equal, or close to UPEM / 1000.
|
| 34 |
+
reverse_direction: flip the contours' direction but keep starting point.
|
| 35 |
+
stats: a dictionary counting the point numbers of quadratic segments.
|
| 36 |
+
all_quadratic: if True (default), only quadratic b-splines are generated.
|
| 37 |
+
if False, quadratic curves or cubic curves are generated depending
|
| 38 |
+
on which one is more economical.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(
|
| 42 |
+
self,
|
| 43 |
+
other_pen,
|
| 44 |
+
max_err,
|
| 45 |
+
reverse_direction=False,
|
| 46 |
+
stats=None,
|
| 47 |
+
all_quadratic=True,
|
| 48 |
+
):
|
| 49 |
+
if reverse_direction:
|
| 50 |
+
other_pen = ReverseContourPen(other_pen)
|
| 51 |
+
super().__init__(other_pen)
|
| 52 |
+
self.max_err = max_err
|
| 53 |
+
self.stats = stats
|
| 54 |
+
self.all_quadratic = all_quadratic
|
| 55 |
+
|
| 56 |
+
def _convert_curve(self, pt1, pt2, pt3):
|
| 57 |
+
curve = (self.current_pt, pt1, pt2, pt3)
|
| 58 |
+
result = curve_to_quadratic(curve, self.max_err, self.all_quadratic)
|
| 59 |
+
if self.stats is not None:
|
| 60 |
+
n = str(len(result) - 2)
|
| 61 |
+
self.stats[n] = self.stats.get(n, 0) + 1
|
| 62 |
+
if self.all_quadratic:
|
| 63 |
+
self.qCurveTo(*result[1:])
|
| 64 |
+
else:
|
| 65 |
+
if len(result) == 3:
|
| 66 |
+
self.qCurveTo(*result[1:])
|
| 67 |
+
else:
|
| 68 |
+
assert len(result) == 4
|
| 69 |
+
super().curveTo(*result[1:])
|
| 70 |
+
|
| 71 |
+
def curveTo(self, *points):
|
| 72 |
+
n = len(points)
|
| 73 |
+
if n == 3:
|
| 74 |
+
# this is the most common case, so we special-case it
|
| 75 |
+
self._convert_curve(*points)
|
| 76 |
+
elif n > 3:
|
| 77 |
+
for segment in decomposeSuperBezierSegment(points):
|
| 78 |
+
self._convert_curve(*segment)
|
| 79 |
+
else:
|
| 80 |
+
self.qCurveTo(*points)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class Cu2QuPointPen(BasePointToSegmentPen):
|
| 84 |
+
"""A filter pen to convert cubic bezier curves to quadratic b-splines
|
| 85 |
+
using the FontTools PointPen protocol.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
other_point_pen: another PointPen used to draw the transformed outline.
|
| 89 |
+
max_err: maximum approximation error in font units. For optimal results,
|
| 90 |
+
if you know the UPEM of the font, we recommend setting this to a
|
| 91 |
+
value equal, or close to UPEM / 1000.
|
| 92 |
+
reverse_direction: reverse the winding direction of all contours.
|
| 93 |
+
stats: a dictionary counting the point numbers of quadratic segments.
|
| 94 |
+
all_quadratic: if True (default), only quadratic b-splines are generated.
|
| 95 |
+
if False, quadratic curves or cubic curves are generated depending
|
| 96 |
+
on which one is more economical.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
__points_required = {
|
| 100 |
+
"move": (1, operator.eq),
|
| 101 |
+
"line": (1, operator.eq),
|
| 102 |
+
"qcurve": (2, operator.ge),
|
| 103 |
+
"curve": (3, operator.eq),
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
def __init__(
|
| 107 |
+
self,
|
| 108 |
+
other_point_pen,
|
| 109 |
+
max_err,
|
| 110 |
+
reverse_direction=False,
|
| 111 |
+
stats=None,
|
| 112 |
+
all_quadratic=True,
|
| 113 |
+
):
|
| 114 |
+
BasePointToSegmentPen.__init__(self)
|
| 115 |
+
if reverse_direction:
|
| 116 |
+
self.pen = ReverseContourPointPen(other_point_pen)
|
| 117 |
+
else:
|
| 118 |
+
self.pen = other_point_pen
|
| 119 |
+
self.max_err = max_err
|
| 120 |
+
self.stats = stats
|
| 121 |
+
self.all_quadratic = all_quadratic
|
| 122 |
+
|
| 123 |
+
def _flushContour(self, segments):
|
| 124 |
+
assert len(segments) >= 1
|
| 125 |
+
closed = segments[0][0] != "move"
|
| 126 |
+
new_segments = []
|
| 127 |
+
prev_points = segments[-1][1]
|
| 128 |
+
prev_on_curve = prev_points[-1][0]
|
| 129 |
+
for segment_type, points in segments:
|
| 130 |
+
if segment_type == "curve":
|
| 131 |
+
for sub_points in self._split_super_bezier_segments(points):
|
| 132 |
+
on_curve, smooth, name, kwargs = sub_points[-1]
|
| 133 |
+
bcp1, bcp2 = sub_points[0][0], sub_points[1][0]
|
| 134 |
+
cubic = [prev_on_curve, bcp1, bcp2, on_curve]
|
| 135 |
+
quad = curve_to_quadratic(cubic, self.max_err, self.all_quadratic)
|
| 136 |
+
if self.stats is not None:
|
| 137 |
+
n = str(len(quad) - 2)
|
| 138 |
+
self.stats[n] = self.stats.get(n, 0) + 1
|
| 139 |
+
new_points = [(pt, False, None, {}) for pt in quad[1:-1]]
|
| 140 |
+
new_points.append((on_curve, smooth, name, kwargs))
|
| 141 |
+
if self.all_quadratic or len(new_points) == 2:
|
| 142 |
+
new_segments.append(["qcurve", new_points])
|
| 143 |
+
else:
|
| 144 |
+
new_segments.append(["curve", new_points])
|
| 145 |
+
prev_on_curve = sub_points[-1][0]
|
| 146 |
+
else:
|
| 147 |
+
new_segments.append([segment_type, points])
|
| 148 |
+
prev_on_curve = points[-1][0]
|
| 149 |
+
if closed:
|
| 150 |
+
# the BasePointToSegmentPen.endPath method that calls _flushContour
|
| 151 |
+
# rotates the point list of closed contours so that they end with
|
| 152 |
+
# the first on-curve point. We restore the original starting point.
|
| 153 |
+
new_segments = new_segments[-1:] + new_segments[:-1]
|
| 154 |
+
self._drawPoints(new_segments)
|
| 155 |
+
|
| 156 |
+
def _split_super_bezier_segments(self, points):
|
| 157 |
+
sub_segments = []
|
| 158 |
+
# n is the number of control points
|
| 159 |
+
n = len(points) - 1
|
| 160 |
+
if n == 2:
|
| 161 |
+
# a simple bezier curve segment
|
| 162 |
+
sub_segments.append(points)
|
| 163 |
+
elif n > 2:
|
| 164 |
+
# a "super" bezier; decompose it
|
| 165 |
+
on_curve, smooth, name, kwargs = points[-1]
|
| 166 |
+
num_sub_segments = n - 1
|
| 167 |
+
for i, sub_points in enumerate(
|
| 168 |
+
decomposeSuperBezierSegment([pt for pt, _, _, _ in points])
|
| 169 |
+
):
|
| 170 |
+
new_segment = []
|
| 171 |
+
for point in sub_points[:-1]:
|
| 172 |
+
new_segment.append((point, False, None, {}))
|
| 173 |
+
if i == (num_sub_segments - 1):
|
| 174 |
+
# the last on-curve keeps its original attributes
|
| 175 |
+
new_segment.append((on_curve, smooth, name, kwargs))
|
| 176 |
+
else:
|
| 177 |
+
# on-curves of sub-segments are always "smooth"
|
| 178 |
+
new_segment.append((sub_points[-1], True, None, {}))
|
| 179 |
+
sub_segments.append(new_segment)
|
| 180 |
+
else:
|
| 181 |
+
raise AssertionError("expected 2 control points, found: %d" % n)
|
| 182 |
+
return sub_segments
|
| 183 |
+
|
| 184 |
+
def _drawPoints(self, segments):
|
| 185 |
+
pen = self.pen
|
| 186 |
+
pen.beginPath()
|
| 187 |
+
last_offcurves = []
|
| 188 |
+
points_required = self.__points_required
|
| 189 |
+
for i, (segment_type, points) in enumerate(segments):
|
| 190 |
+
if segment_type in points_required:
|
| 191 |
+
n, op = points_required[segment_type]
|
| 192 |
+
assert op(len(points), n), (
|
| 193 |
+
f"illegal {segment_type!r} segment point count: "
|
| 194 |
+
f"expected {n}, got {len(points)}"
|
| 195 |
+
)
|
| 196 |
+
offcurves = points[:-1]
|
| 197 |
+
if i == 0:
|
| 198 |
+
# any off-curve points preceding the first on-curve
|
| 199 |
+
# will be appended at the end of the contour
|
| 200 |
+
last_offcurves = offcurves
|
| 201 |
+
else:
|
| 202 |
+
for pt, smooth, name, kwargs in offcurves:
|
| 203 |
+
pen.addPoint(pt, None, smooth, name, **kwargs)
|
| 204 |
+
pt, smooth, name, kwargs = points[-1]
|
| 205 |
+
if pt is None:
|
| 206 |
+
assert segment_type == "qcurve"
|
| 207 |
+
# special quadratic contour with no on-curve points:
|
| 208 |
+
# we need to skip the "None" point. See also the Pen
|
| 209 |
+
# protocol's qCurveTo() method and fontTools.pens.basePen
|
| 210 |
+
pass
|
| 211 |
+
else:
|
| 212 |
+
pen.addPoint(pt, segment_type, smooth, name, **kwargs)
|
| 213 |
+
else:
|
| 214 |
+
raise AssertionError("unexpected segment type: %r" % segment_type)
|
| 215 |
+
for pt, smooth, name, kwargs in last_offcurves:
|
| 216 |
+
pen.addPoint(pt, None, smooth, name, **kwargs)
|
| 217 |
+
pen.endPath()
|
| 218 |
+
|
| 219 |
+
def addComponent(self, baseGlyphName, transformation):
|
| 220 |
+
assert self.currentPath is None
|
| 221 |
+
self.pen.addComponent(baseGlyphName, transformation)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class Cu2QuMultiPen:
|
| 225 |
+
"""A filter multi-pen to convert cubic bezier curves to quadratic b-splines
|
| 226 |
+
in a interpolation-compatible manner, using the FontTools SegmentPen protocol.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
|
| 230 |
+
other_pens: list of SegmentPens used to draw the transformed outlines.
|
| 231 |
+
max_err: maximum approximation error in font units. For optimal results,
|
| 232 |
+
if you know the UPEM of the font, we recommend setting this to a
|
| 233 |
+
value equal, or close to UPEM / 1000.
|
| 234 |
+
reverse_direction: flip the contours' direction but keep starting point.
|
| 235 |
+
|
| 236 |
+
This pen does not follow the normal SegmentPen protocol. Instead, its
|
| 237 |
+
moveTo/lineTo/qCurveTo/curveTo methods take a list of tuples that are
|
| 238 |
+
arguments that would normally be passed to a SegmentPen, one item for
|
| 239 |
+
each of the pens in other_pens.
|
| 240 |
+
"""
|
| 241 |
+
|
| 242 |
+
# TODO Simplify like 3e8ebcdce592fe8a59ca4c3a294cc9724351e1ce
|
| 243 |
+
# Remove start_pts and _add_moveTO
|
| 244 |
+
|
| 245 |
+
def __init__(self, other_pens, max_err, reverse_direction=False):
|
| 246 |
+
if reverse_direction:
|
| 247 |
+
other_pens = [
|
| 248 |
+
ReverseContourPen(pen, outputImpliedClosingLine=True)
|
| 249 |
+
for pen in other_pens
|
| 250 |
+
]
|
| 251 |
+
self.pens = other_pens
|
| 252 |
+
self.max_err = max_err
|
| 253 |
+
self.start_pts = None
|
| 254 |
+
self.current_pts = None
|
| 255 |
+
|
| 256 |
+
def _check_contour_is_open(self):
|
| 257 |
+
if self.current_pts is None:
|
| 258 |
+
raise AssertionError("moveTo is required")
|
| 259 |
+
|
| 260 |
+
def _check_contour_is_closed(self):
|
| 261 |
+
if self.current_pts is not None:
|
| 262 |
+
raise AssertionError("closePath or endPath is required")
|
| 263 |
+
|
| 264 |
+
def _add_moveTo(self):
|
| 265 |
+
if self.start_pts is not None:
|
| 266 |
+
for pt, pen in zip(self.start_pts, self.pens):
|
| 267 |
+
pen.moveTo(*pt)
|
| 268 |
+
self.start_pts = None
|
| 269 |
+
|
| 270 |
+
def moveTo(self, pts):
|
| 271 |
+
self._check_contour_is_closed()
|
| 272 |
+
self.start_pts = self.current_pts = pts
|
| 273 |
+
self._add_moveTo()
|
| 274 |
+
|
| 275 |
+
def lineTo(self, pts):
|
| 276 |
+
self._check_contour_is_open()
|
| 277 |
+
self._add_moveTo()
|
| 278 |
+
for pt, pen in zip(pts, self.pens):
|
| 279 |
+
pen.lineTo(*pt)
|
| 280 |
+
self.current_pts = pts
|
| 281 |
+
|
| 282 |
+
def qCurveTo(self, pointsList):
|
| 283 |
+
self._check_contour_is_open()
|
| 284 |
+
if len(pointsList[0]) == 1:
|
| 285 |
+
self.lineTo([(points[0],) for points in pointsList])
|
| 286 |
+
return
|
| 287 |
+
self._add_moveTo()
|
| 288 |
+
current_pts = []
|
| 289 |
+
for points, pen in zip(pointsList, self.pens):
|
| 290 |
+
pen.qCurveTo(*points)
|
| 291 |
+
current_pts.append((points[-1],))
|
| 292 |
+
self.current_pts = current_pts
|
| 293 |
+
|
| 294 |
+
def _curves_to_quadratic(self, pointsList):
|
| 295 |
+
curves = []
|
| 296 |
+
for current_pt, points in zip(self.current_pts, pointsList):
|
| 297 |
+
curves.append(current_pt + points)
|
| 298 |
+
quadratics = curves_to_quadratic(curves, [self.max_err] * len(curves))
|
| 299 |
+
pointsList = []
|
| 300 |
+
for quadratic in quadratics:
|
| 301 |
+
pointsList.append(quadratic[1:])
|
| 302 |
+
self.qCurveTo(pointsList)
|
| 303 |
+
|
| 304 |
+
def curveTo(self, pointsList):
|
| 305 |
+
self._check_contour_is_open()
|
| 306 |
+
self._curves_to_quadratic(pointsList)
|
| 307 |
+
|
| 308 |
+
def closePath(self):
|
| 309 |
+
self._check_contour_is_open()
|
| 310 |
+
if self.start_pts is None:
|
| 311 |
+
for pen in self.pens:
|
| 312 |
+
pen.closePath()
|
| 313 |
+
self.current_pts = self.start_pts = None
|
| 314 |
+
|
| 315 |
+
def endPath(self):
|
| 316 |
+
self._check_contour_is_open()
|
| 317 |
+
if self.start_pts is None:
|
| 318 |
+
for pen in self.pens:
|
| 319 |
+
pen.endPath()
|
| 320 |
+
self.current_pts = self.start_pts = None
|
| 321 |
+
|
| 322 |
+
def addComponent(self, glyphName, transformations):
|
| 323 |
+
self._check_contour_is_closed()
|
| 324 |
+
for trans, pen in zip(transformations, self.pens):
|
| 325 |
+
pen.addComponent(glyphName, trans)
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/filterPen.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from fontTools.pens.basePen import AbstractPen, DecomposingPen
|
| 4 |
+
from fontTools.pens.pointPen import AbstractPointPen, DecomposingPointPen
|
| 5 |
+
from fontTools.pens.recordingPen import RecordingPen
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class _PassThruComponentsMixin(object):
|
| 9 |
+
def addComponent(self, glyphName, transformation, **kwargs):
|
| 10 |
+
self._outPen.addComponent(glyphName, transformation, **kwargs)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class FilterPen(_PassThruComponentsMixin, AbstractPen):
|
| 14 |
+
"""Base class for pens that apply some transformation to the coordinates
|
| 15 |
+
they receive and pass them to another pen.
|
| 16 |
+
|
| 17 |
+
You can override any of its methods. The default implementation does
|
| 18 |
+
nothing, but passes the commands unmodified to the other pen.
|
| 19 |
+
|
| 20 |
+
>>> from fontTools.pens.recordingPen import RecordingPen
|
| 21 |
+
>>> rec = RecordingPen()
|
| 22 |
+
>>> pen = FilterPen(rec)
|
| 23 |
+
>>> v = iter(rec.value)
|
| 24 |
+
|
| 25 |
+
>>> pen.moveTo((0, 0))
|
| 26 |
+
>>> next(v)
|
| 27 |
+
('moveTo', ((0, 0),))
|
| 28 |
+
|
| 29 |
+
>>> pen.lineTo((1, 1))
|
| 30 |
+
>>> next(v)
|
| 31 |
+
('lineTo', ((1, 1),))
|
| 32 |
+
|
| 33 |
+
>>> pen.curveTo((2, 2), (3, 3), (4, 4))
|
| 34 |
+
>>> next(v)
|
| 35 |
+
('curveTo', ((2, 2), (3, 3), (4, 4)))
|
| 36 |
+
|
| 37 |
+
>>> pen.qCurveTo((5, 5), (6, 6), (7, 7), (8, 8))
|
| 38 |
+
>>> next(v)
|
| 39 |
+
('qCurveTo', ((5, 5), (6, 6), (7, 7), (8, 8)))
|
| 40 |
+
|
| 41 |
+
>>> pen.closePath()
|
| 42 |
+
>>> next(v)
|
| 43 |
+
('closePath', ())
|
| 44 |
+
|
| 45 |
+
>>> pen.moveTo((9, 9))
|
| 46 |
+
>>> next(v)
|
| 47 |
+
('moveTo', ((9, 9),))
|
| 48 |
+
|
| 49 |
+
>>> pen.endPath()
|
| 50 |
+
>>> next(v)
|
| 51 |
+
('endPath', ())
|
| 52 |
+
|
| 53 |
+
>>> pen.addComponent('foo', (1, 0, 0, 1, 0, 0))
|
| 54 |
+
>>> next(v)
|
| 55 |
+
('addComponent', ('foo', (1, 0, 0, 1, 0, 0)))
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
def __init__(self, outPen):
|
| 59 |
+
self._outPen = outPen
|
| 60 |
+
self.current_pt = None
|
| 61 |
+
|
| 62 |
+
def moveTo(self, pt):
|
| 63 |
+
self._outPen.moveTo(pt)
|
| 64 |
+
self.current_pt = pt
|
| 65 |
+
|
| 66 |
+
def lineTo(self, pt):
|
| 67 |
+
self._outPen.lineTo(pt)
|
| 68 |
+
self.current_pt = pt
|
| 69 |
+
|
| 70 |
+
def curveTo(self, *points):
|
| 71 |
+
self._outPen.curveTo(*points)
|
| 72 |
+
self.current_pt = points[-1]
|
| 73 |
+
|
| 74 |
+
def qCurveTo(self, *points):
|
| 75 |
+
self._outPen.qCurveTo(*points)
|
| 76 |
+
self.current_pt = points[-1]
|
| 77 |
+
|
| 78 |
+
def closePath(self):
|
| 79 |
+
self._outPen.closePath()
|
| 80 |
+
self.current_pt = None
|
| 81 |
+
|
| 82 |
+
def endPath(self):
|
| 83 |
+
self._outPen.endPath()
|
| 84 |
+
self.current_pt = None
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class ContourFilterPen(_PassThruComponentsMixin, RecordingPen):
|
| 88 |
+
"""A "buffered" filter pen that accumulates contour data, passes
|
| 89 |
+
it through a ``filterContour`` method when the contour is closed or ended,
|
| 90 |
+
and finally draws the result with the output pen.
|
| 91 |
+
|
| 92 |
+
Components are passed through unchanged.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
def __init__(self, outPen):
|
| 96 |
+
super(ContourFilterPen, self).__init__()
|
| 97 |
+
self._outPen = outPen
|
| 98 |
+
|
| 99 |
+
def closePath(self):
|
| 100 |
+
super(ContourFilterPen, self).closePath()
|
| 101 |
+
self._flushContour()
|
| 102 |
+
|
| 103 |
+
def endPath(self):
|
| 104 |
+
super(ContourFilterPen, self).endPath()
|
| 105 |
+
self._flushContour()
|
| 106 |
+
|
| 107 |
+
def _flushContour(self):
|
| 108 |
+
result = self.filterContour(self.value)
|
| 109 |
+
if result is not None:
|
| 110 |
+
self.value = result
|
| 111 |
+
self.replay(self._outPen)
|
| 112 |
+
self.value = []
|
| 113 |
+
|
| 114 |
+
def filterContour(self, contour):
|
| 115 |
+
"""Subclasses must override this to perform the filtering.
|
| 116 |
+
|
| 117 |
+
The contour is a list of pen (operator, operands) tuples.
|
| 118 |
+
Operators are strings corresponding to the AbstractPen methods:
|
| 119 |
+
"moveTo", "lineTo", "curveTo", "qCurveTo", "closePath" and
|
| 120 |
+
"endPath". The operands are the positional arguments that are
|
| 121 |
+
passed to each method.
|
| 122 |
+
|
| 123 |
+
If the method doesn't return a value (i.e. returns None), it's
|
| 124 |
+
assumed that the argument was modified in-place.
|
| 125 |
+
Otherwise, the return value is drawn with the output pen.
|
| 126 |
+
"""
|
| 127 |
+
return # or return contour
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class FilterPointPen(_PassThruComponentsMixin, AbstractPointPen):
|
| 131 |
+
"""Baseclass for point pens that apply some transformation to the
|
| 132 |
+
coordinates they receive and pass them to another point pen.
|
| 133 |
+
|
| 134 |
+
You can override any of its methods. The default implementation does
|
| 135 |
+
nothing, but passes the commands unmodified to the other pen.
|
| 136 |
+
|
| 137 |
+
>>> from fontTools.pens.recordingPen import RecordingPointPen
|
| 138 |
+
>>> rec = RecordingPointPen()
|
| 139 |
+
>>> pen = FilterPointPen(rec)
|
| 140 |
+
>>> v = iter(rec.value)
|
| 141 |
+
>>> pen.beginPath(identifier="abc")
|
| 142 |
+
>>> next(v)
|
| 143 |
+
('beginPath', (), {'identifier': 'abc'})
|
| 144 |
+
>>> pen.addPoint((1, 2), "line", False)
|
| 145 |
+
>>> next(v)
|
| 146 |
+
('addPoint', ((1, 2), 'line', False, None), {})
|
| 147 |
+
>>> pen.addComponent("a", (2, 0, 0, 2, 10, -10), identifier="0001")
|
| 148 |
+
>>> next(v)
|
| 149 |
+
('addComponent', ('a', (2, 0, 0, 2, 10, -10)), {'identifier': '0001'})
|
| 150 |
+
>>> pen.endPath()
|
| 151 |
+
>>> next(v)
|
| 152 |
+
('endPath', (), {})
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
def __init__(self, outPen):
|
| 156 |
+
self._outPen = outPen
|
| 157 |
+
|
| 158 |
+
def beginPath(self, **kwargs):
|
| 159 |
+
self._outPen.beginPath(**kwargs)
|
| 160 |
+
|
| 161 |
+
def endPath(self):
|
| 162 |
+
self._outPen.endPath()
|
| 163 |
+
|
| 164 |
+
def addPoint(self, pt, segmentType=None, smooth=False, name=None, **kwargs):
|
| 165 |
+
self._outPen.addPoint(pt, segmentType, smooth, name, **kwargs)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class _DecomposingFilterPenMixin:
|
| 169 |
+
"""Mixin class that decomposes components as regular contours.
|
| 170 |
+
|
| 171 |
+
Shared by both DecomposingFilterPen and DecomposingFilterPointPen.
|
| 172 |
+
|
| 173 |
+
Takes two required parameters, another (segment or point) pen 'outPen' to draw
|
| 174 |
+
with, and a 'glyphSet' dict of drawable glyph objects to draw components from.
|
| 175 |
+
|
| 176 |
+
The 'skipMissingComponents' and 'reverseFlipped' optional arguments work the
|
| 177 |
+
same as in the DecomposingPen/DecomposingPointPen. Both are False by default.
|
| 178 |
+
|
| 179 |
+
In addition, the decomposing filter pens also take the following two options:
|
| 180 |
+
|
| 181 |
+
'include' is an optional set of component base glyph names to consider for
|
| 182 |
+
decomposition; the default include=None means decompose all components no matter
|
| 183 |
+
the base glyph name).
|
| 184 |
+
|
| 185 |
+
'decomposeNested' (bool) controls whether to recurse decomposition into nested
|
| 186 |
+
components of components (this only matters when 'include' was also provided);
|
| 187 |
+
if False, only decompose top-level components included in the set, but not
|
| 188 |
+
also their children.
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
# raises MissingComponentError if base glyph is not found in glyphSet
|
| 192 |
+
skipMissingComponents = False
|
| 193 |
+
|
| 194 |
+
def __init__(
|
| 195 |
+
self,
|
| 196 |
+
outPen,
|
| 197 |
+
glyphSet,
|
| 198 |
+
skipMissingComponents=None,
|
| 199 |
+
reverseFlipped=False,
|
| 200 |
+
include: set[str] | None = None,
|
| 201 |
+
decomposeNested: bool = True,
|
| 202 |
+
):
|
| 203 |
+
super().__init__(
|
| 204 |
+
outPen=outPen,
|
| 205 |
+
glyphSet=glyphSet,
|
| 206 |
+
skipMissingComponents=skipMissingComponents,
|
| 207 |
+
reverseFlipped=reverseFlipped,
|
| 208 |
+
)
|
| 209 |
+
self.include = include
|
| 210 |
+
self.decomposeNested = decomposeNested
|
| 211 |
+
|
| 212 |
+
def addComponent(self, baseGlyphName, transformation, **kwargs):
|
| 213 |
+
# only decompose the component if it's included in the set
|
| 214 |
+
if self.include is None or baseGlyphName in self.include:
|
| 215 |
+
# if we're decomposing nested components, temporarily set include to None
|
| 216 |
+
include_bak = self.include
|
| 217 |
+
if self.decomposeNested and self.include:
|
| 218 |
+
self.include = None
|
| 219 |
+
try:
|
| 220 |
+
super().addComponent(baseGlyphName, transformation, **kwargs)
|
| 221 |
+
finally:
|
| 222 |
+
if self.include != include_bak:
|
| 223 |
+
self.include = include_bak
|
| 224 |
+
else:
|
| 225 |
+
_PassThruComponentsMixin.addComponent(
|
| 226 |
+
self, baseGlyphName, transformation, **kwargs
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class DecomposingFilterPen(_DecomposingFilterPenMixin, DecomposingPen, FilterPen):
|
| 231 |
+
"""Filter pen that draws components as regular contours."""
|
| 232 |
+
|
| 233 |
+
pass
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class DecomposingFilterPointPen(
|
| 237 |
+
_DecomposingFilterPenMixin, DecomposingPointPen, FilterPointPen
|
| 238 |
+
):
|
| 239 |
+
"""Filter point pen that draws components as regular contours."""
|
| 240 |
+
|
| 241 |
+
pass
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/freetypePen.py
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
"""Pen to rasterize paths with FreeType."""
|
| 4 |
+
|
| 5 |
+
__all__ = ["FreeTypePen"]
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import ctypes
|
| 9 |
+
import platform
|
| 10 |
+
import subprocess
|
| 11 |
+
import collections
|
| 12 |
+
import math
|
| 13 |
+
|
| 14 |
+
import freetype
|
| 15 |
+
from freetype.raw import FT_Outline_Get_Bitmap, FT_Outline_Get_BBox, FT_Outline_Get_CBox
|
| 16 |
+
from freetype.ft_types import FT_Pos
|
| 17 |
+
from freetype.ft_structs import FT_Vector, FT_BBox, FT_Bitmap, FT_Outline
|
| 18 |
+
from freetype.ft_enums import (
|
| 19 |
+
FT_OUTLINE_NONE,
|
| 20 |
+
FT_OUTLINE_EVEN_ODD_FILL,
|
| 21 |
+
FT_PIXEL_MODE_GRAY,
|
| 22 |
+
FT_CURVE_TAG_ON,
|
| 23 |
+
FT_CURVE_TAG_CONIC,
|
| 24 |
+
FT_CURVE_TAG_CUBIC,
|
| 25 |
+
)
|
| 26 |
+
from freetype.ft_errors import FT_Exception
|
| 27 |
+
|
| 28 |
+
from fontTools.pens.basePen import BasePen, PenError
|
| 29 |
+
from fontTools.misc.roundTools import otRound
|
| 30 |
+
from fontTools.misc.transform import Transform
|
| 31 |
+
|
| 32 |
+
Contour = collections.namedtuple("Contour", ("points", "tags"))
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class FreeTypePen(BasePen):
|
| 36 |
+
"""Pen to rasterize paths with FreeType. Requires `freetype-py` module.
|
| 37 |
+
|
| 38 |
+
Constructs ``FT_Outline`` from the paths, and renders it within a bitmap
|
| 39 |
+
buffer.
|
| 40 |
+
|
| 41 |
+
For ``array()`` and ``show()``, `numpy` and `matplotlib` must be installed.
|
| 42 |
+
For ``image()``, `Pillow` is required. Each module is lazily loaded when the
|
| 43 |
+
corresponding method is called.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
glyphSet: a dictionary of drawable glyph objects keyed by name
|
| 47 |
+
used to resolve component references in composite glyphs.
|
| 48 |
+
|
| 49 |
+
Examples:
|
| 50 |
+
If `numpy` and `matplotlib` is available, the following code will
|
| 51 |
+
show the glyph image of `fi` in a new window::
|
| 52 |
+
|
| 53 |
+
from fontTools.ttLib import TTFont
|
| 54 |
+
from fontTools.pens.freetypePen import FreeTypePen
|
| 55 |
+
from fontTools.misc.transform import Offset
|
| 56 |
+
pen = FreeTypePen(None)
|
| 57 |
+
font = TTFont('SourceSansPro-Regular.otf')
|
| 58 |
+
glyph = font.getGlyphSet()['fi']
|
| 59 |
+
glyph.draw(pen)
|
| 60 |
+
width, ascender, descender = glyph.width, font['OS/2'].usWinAscent, -font['OS/2'].usWinDescent
|
| 61 |
+
height = ascender - descender
|
| 62 |
+
pen.show(width=width, height=height, transform=Offset(0, -descender))
|
| 63 |
+
|
| 64 |
+
Combining with `uharfbuzz`, you can typeset a chunk of glyphs in a pen::
|
| 65 |
+
|
| 66 |
+
import uharfbuzz as hb
|
| 67 |
+
from fontTools.pens.freetypePen import FreeTypePen
|
| 68 |
+
from fontTools.pens.transformPen import TransformPen
|
| 69 |
+
from fontTools.misc.transform import Offset
|
| 70 |
+
|
| 71 |
+
en1, en2, ar, ja = 'Typesetting', 'Jeff', 'صف الحروف', 'たいぷせっと'
|
| 72 |
+
for text, font_path, direction, typo_ascender, typo_descender, vhea_ascender, vhea_descender, contain, features in (
|
| 73 |
+
(en1, 'NotoSans-Regular.ttf', 'ltr', 2189, -600, None, None, False, {"kern": True, "liga": True}),
|
| 74 |
+
(en2, 'NotoSans-Regular.ttf', 'ltr', 2189, -600, None, None, True, {"kern": True, "liga": True}),
|
| 75 |
+
(ar, 'NotoSansArabic-Regular.ttf', 'rtl', 1374, -738, None, None, False, {"kern": True, "liga": True}),
|
| 76 |
+
(ja, 'NotoSansJP-Regular.otf', 'ltr', 880, -120, 500, -500, False, {"palt": True, "kern": True}),
|
| 77 |
+
(ja, 'NotoSansJP-Regular.otf', 'ttb', 880, -120, 500, -500, False, {"vert": True, "vpal": True, "vkrn": True})
|
| 78 |
+
):
|
| 79 |
+
blob = hb.Blob.from_file_path(font_path)
|
| 80 |
+
face = hb.Face(blob)
|
| 81 |
+
font = hb.Font(face)
|
| 82 |
+
buf = hb.Buffer()
|
| 83 |
+
buf.direction = direction
|
| 84 |
+
buf.add_str(text)
|
| 85 |
+
buf.guess_segment_properties()
|
| 86 |
+
hb.shape(font, buf, features)
|
| 87 |
+
|
| 88 |
+
x, y = 0, 0
|
| 89 |
+
pen = FreeTypePen(None)
|
| 90 |
+
for info, pos in zip(buf.glyph_infos, buf.glyph_positions):
|
| 91 |
+
gid = info.codepoint
|
| 92 |
+
transformed = TransformPen(pen, Offset(x + pos.x_offset, y + pos.y_offset))
|
| 93 |
+
font.draw_glyph_with_pen(gid, transformed)
|
| 94 |
+
x += pos.x_advance
|
| 95 |
+
y += pos.y_advance
|
| 96 |
+
|
| 97 |
+
offset, width, height = None, None, None
|
| 98 |
+
if direction in ('ltr', 'rtl'):
|
| 99 |
+
offset = (0, -typo_descender)
|
| 100 |
+
width = x
|
| 101 |
+
height = typo_ascender - typo_descender
|
| 102 |
+
else:
|
| 103 |
+
offset = (-vhea_descender, -y)
|
| 104 |
+
width = vhea_ascender - vhea_descender
|
| 105 |
+
height = -y
|
| 106 |
+
pen.show(width=width, height=height, transform=Offset(*offset), contain=contain)
|
| 107 |
+
|
| 108 |
+
For Jupyter Notebook, the rendered image will be displayed in a cell if
|
| 109 |
+
you replace ``show()`` with ``image()`` in the examples.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, glyphSet):
|
| 113 |
+
BasePen.__init__(self, glyphSet)
|
| 114 |
+
self.contours = []
|
| 115 |
+
|
| 116 |
+
def outline(self, transform=None, evenOdd=False):
|
| 117 |
+
"""Converts the current contours to ``FT_Outline``.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
transform: An optional 6-tuple containing an affine transformation,
|
| 121 |
+
or a ``Transform`` object from the ``fontTools.misc.transform``
|
| 122 |
+
module.
|
| 123 |
+
evenOdd: Pass ``True`` for even-odd fill instead of non-zero.
|
| 124 |
+
"""
|
| 125 |
+
transform = transform or Transform()
|
| 126 |
+
if not hasattr(transform, "transformPoint"):
|
| 127 |
+
transform = Transform(*transform)
|
| 128 |
+
n_contours = len(self.contours)
|
| 129 |
+
n_points = sum((len(contour.points) for contour in self.contours))
|
| 130 |
+
points = []
|
| 131 |
+
for contour in self.contours:
|
| 132 |
+
for point in contour.points:
|
| 133 |
+
point = transform.transformPoint(point)
|
| 134 |
+
points.append(
|
| 135 |
+
FT_Vector(
|
| 136 |
+
FT_Pos(otRound(point[0] * 64)), FT_Pos(otRound(point[1] * 64))
|
| 137 |
+
)
|
| 138 |
+
)
|
| 139 |
+
tags = []
|
| 140 |
+
for contour in self.contours:
|
| 141 |
+
for tag in contour.tags:
|
| 142 |
+
tags.append(tag)
|
| 143 |
+
contours = []
|
| 144 |
+
contours_sum = 0
|
| 145 |
+
for contour in self.contours:
|
| 146 |
+
contours_sum += len(contour.points)
|
| 147 |
+
contours.append(contours_sum - 1)
|
| 148 |
+
flags = FT_OUTLINE_EVEN_ODD_FILL if evenOdd else FT_OUTLINE_NONE
|
| 149 |
+
return FT_Outline(
|
| 150 |
+
(ctypes.c_short)(n_contours),
|
| 151 |
+
(ctypes.c_short)(n_points),
|
| 152 |
+
(FT_Vector * n_points)(*points),
|
| 153 |
+
(ctypes.c_ubyte * n_points)(*tags),
|
| 154 |
+
(ctypes.c_short * n_contours)(*contours),
|
| 155 |
+
(ctypes.c_int)(flags),
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
def buffer(
|
| 159 |
+
self, width=None, height=None, transform=None, contain=False, evenOdd=False
|
| 160 |
+
):
|
| 161 |
+
"""Renders the current contours within a bitmap buffer.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
width: Image width of the bitmap in pixels. If omitted, it
|
| 165 |
+
automatically fits to the bounding box of the contours.
|
| 166 |
+
height: Image height of the bitmap in pixels. If omitted, it
|
| 167 |
+
automatically fits to the bounding box of the contours.
|
| 168 |
+
transform: An optional 6-tuple containing an affine transformation,
|
| 169 |
+
or a ``Transform`` object from the ``fontTools.misc.transform``
|
| 170 |
+
module. The bitmap size is not affected by this matrix.
|
| 171 |
+
contain: If ``True``, the image size will be automatically expanded
|
| 172 |
+
so that it fits to the bounding box of the paths. Useful for
|
| 173 |
+
rendering glyphs with negative sidebearings without clipping.
|
| 174 |
+
evenOdd: Pass ``True`` for even-odd fill instead of non-zero.
|
| 175 |
+
|
| 176 |
+
Returns:
|
| 177 |
+
A tuple of ``(buffer, size)``, where ``buffer`` is a ``bytes``
|
| 178 |
+
object of the resulted bitmap and ``size`` is a 2-tuple of its
|
| 179 |
+
dimension.
|
| 180 |
+
|
| 181 |
+
Notes:
|
| 182 |
+
The image size should always be given explicitly if you need to get
|
| 183 |
+
a proper glyph image. When ``width`` and ``height`` are omitted, it
|
| 184 |
+
forcifully fits to the bounding box and the side bearings get
|
| 185 |
+
cropped. If you pass ``0`` to both ``width`` and ``height`` and set
|
| 186 |
+
``contain`` to ``True``, it expands to the bounding box while
|
| 187 |
+
maintaining the origin of the contours, meaning that LSB will be
|
| 188 |
+
maintained but RSB won’t. The difference between the two becomes
|
| 189 |
+
more obvious when rotate or skew transformation is applied.
|
| 190 |
+
|
| 191 |
+
Example:
|
| 192 |
+
.. code-block:: pycon
|
| 193 |
+
|
| 194 |
+
>>>
|
| 195 |
+
>> pen = FreeTypePen(None)
|
| 196 |
+
>> glyph.draw(pen)
|
| 197 |
+
>> buf, size = pen.buffer(width=500, height=1000)
|
| 198 |
+
>> type(buf), len(buf), size
|
| 199 |
+
(<class 'bytes'>, 500000, (500, 1000))
|
| 200 |
+
"""
|
| 201 |
+
transform = transform or Transform()
|
| 202 |
+
if not hasattr(transform, "transformPoint"):
|
| 203 |
+
transform = Transform(*transform)
|
| 204 |
+
contain_x, contain_y = contain or width is None, contain or height is None
|
| 205 |
+
if contain_x or contain_y:
|
| 206 |
+
dx, dy = transform.dx, transform.dy
|
| 207 |
+
bbox = self.bbox
|
| 208 |
+
p1, p2, p3, p4 = (
|
| 209 |
+
transform.transformPoint((bbox[0], bbox[1])),
|
| 210 |
+
transform.transformPoint((bbox[2], bbox[1])),
|
| 211 |
+
transform.transformPoint((bbox[0], bbox[3])),
|
| 212 |
+
transform.transformPoint((bbox[2], bbox[3])),
|
| 213 |
+
)
|
| 214 |
+
px, py = (p1[0], p2[0], p3[0], p4[0]), (p1[1], p2[1], p3[1], p4[1])
|
| 215 |
+
if contain_x:
|
| 216 |
+
if width is None:
|
| 217 |
+
dx = dx - min(*px)
|
| 218 |
+
width = max(*px) - min(*px)
|
| 219 |
+
else:
|
| 220 |
+
dx = dx - min(min(*px), 0.0)
|
| 221 |
+
width = max(width, max(*px) - min(min(*px), 0.0))
|
| 222 |
+
if contain_y:
|
| 223 |
+
if height is None:
|
| 224 |
+
dy = dy - min(*py)
|
| 225 |
+
height = max(*py) - min(*py)
|
| 226 |
+
else:
|
| 227 |
+
dy = dy - min(min(*py), 0.0)
|
| 228 |
+
height = max(height, max(*py) - min(min(*py), 0.0))
|
| 229 |
+
transform = Transform(*transform[:4], dx, dy)
|
| 230 |
+
width, height = math.ceil(width), math.ceil(height)
|
| 231 |
+
buf = ctypes.create_string_buffer(width * height)
|
| 232 |
+
bitmap = FT_Bitmap(
|
| 233 |
+
(ctypes.c_int)(height),
|
| 234 |
+
(ctypes.c_int)(width),
|
| 235 |
+
(ctypes.c_int)(width),
|
| 236 |
+
(ctypes.POINTER(ctypes.c_ubyte))(buf),
|
| 237 |
+
(ctypes.c_short)(256),
|
| 238 |
+
(ctypes.c_ubyte)(FT_PIXEL_MODE_GRAY),
|
| 239 |
+
(ctypes.c_char)(0),
|
| 240 |
+
(ctypes.c_void_p)(None),
|
| 241 |
+
)
|
| 242 |
+
outline = self.outline(transform=transform, evenOdd=evenOdd)
|
| 243 |
+
err = FT_Outline_Get_Bitmap(
|
| 244 |
+
freetype.get_handle(), ctypes.byref(outline), ctypes.byref(bitmap)
|
| 245 |
+
)
|
| 246 |
+
if err != 0:
|
| 247 |
+
raise FT_Exception(err)
|
| 248 |
+
return buf.raw, (width, height)
|
| 249 |
+
|
| 250 |
+
def array(
|
| 251 |
+
self, width=None, height=None, transform=None, contain=False, evenOdd=False
|
| 252 |
+
):
|
| 253 |
+
"""Returns the rendered contours as a numpy array. Requires `numpy`.
|
| 254 |
+
|
| 255 |
+
Args:
|
| 256 |
+
width: Image width of the bitmap in pixels. If omitted, it
|
| 257 |
+
automatically fits to the bounding box of the contours.
|
| 258 |
+
height: Image height of the bitmap in pixels. If omitted, it
|
| 259 |
+
automatically fits to the bounding box of the contours.
|
| 260 |
+
transform: An optional 6-tuple containing an affine transformation,
|
| 261 |
+
or a ``Transform`` object from the ``fontTools.misc.transform``
|
| 262 |
+
module. The bitmap size is not affected by this matrix.
|
| 263 |
+
contain: If ``True``, the image size will be automatically expanded
|
| 264 |
+
so that it fits to the bounding box of the paths. Useful for
|
| 265 |
+
rendering glyphs with negative sidebearings without clipping.
|
| 266 |
+
evenOdd: Pass ``True`` for even-odd fill instead of non-zero.
|
| 267 |
+
|
| 268 |
+
Returns:
|
| 269 |
+
A ``numpy.ndarray`` object with a shape of ``(height, width)``.
|
| 270 |
+
Each element takes a value in the range of ``[0.0, 1.0]``.
|
| 271 |
+
|
| 272 |
+
Notes:
|
| 273 |
+
The image size should always be given explicitly if you need to get
|
| 274 |
+
a proper glyph image. When ``width`` and ``height`` are omitted, it
|
| 275 |
+
forcifully fits to the bounding box and the side bearings get
|
| 276 |
+
cropped. If you pass ``0`` to both ``width`` and ``height`` and set
|
| 277 |
+
``contain`` to ``True``, it expands to the bounding box while
|
| 278 |
+
maintaining the origin of the contours, meaning that LSB will be
|
| 279 |
+
maintained but RSB won’t. The difference between the two becomes
|
| 280 |
+
more obvious when rotate or skew transformation is applied.
|
| 281 |
+
|
| 282 |
+
Example:
|
| 283 |
+
.. code-block:: pycon
|
| 284 |
+
|
| 285 |
+
>>>
|
| 286 |
+
>> pen = FreeTypePen(None)
|
| 287 |
+
>> glyph.draw(pen)
|
| 288 |
+
>> arr = pen.array(width=500, height=1000)
|
| 289 |
+
>> type(a), a.shape
|
| 290 |
+
(<class 'numpy.ndarray'>, (1000, 500))
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
import numpy as np
|
| 294 |
+
|
| 295 |
+
buf, size = self.buffer(
|
| 296 |
+
width=width,
|
| 297 |
+
height=height,
|
| 298 |
+
transform=transform,
|
| 299 |
+
contain=contain,
|
| 300 |
+
evenOdd=evenOdd,
|
| 301 |
+
)
|
| 302 |
+
return np.frombuffer(buf, "B").reshape((size[1], size[0])) / 255.0
|
| 303 |
+
|
| 304 |
+
def show(
|
| 305 |
+
self, width=None, height=None, transform=None, contain=False, evenOdd=False
|
| 306 |
+
):
|
| 307 |
+
"""Plots the rendered contours with `pyplot`. Requires `numpy` and
|
| 308 |
+
`matplotlib`.
|
| 309 |
+
|
| 310 |
+
Args:
|
| 311 |
+
width: Image width of the bitmap in pixels. If omitted, it
|
| 312 |
+
automatically fits to the bounding box of the contours.
|
| 313 |
+
height: Image height of the bitmap in pixels. If omitted, it
|
| 314 |
+
automatically fits to the bounding box of the contours.
|
| 315 |
+
transform: An optional 6-tuple containing an affine transformation,
|
| 316 |
+
or a ``Transform`` object from the ``fontTools.misc.transform``
|
| 317 |
+
module. The bitmap size is not affected by this matrix.
|
| 318 |
+
contain: If ``True``, the image size will be automatically expanded
|
| 319 |
+
so that it fits to the bounding box of the paths. Useful for
|
| 320 |
+
rendering glyphs with negative sidebearings without clipping.
|
| 321 |
+
evenOdd: Pass ``True`` for even-odd fill instead of non-zero.
|
| 322 |
+
|
| 323 |
+
Notes:
|
| 324 |
+
The image size should always be given explicitly if you need to get
|
| 325 |
+
a proper glyph image. When ``width`` and ``height`` are omitted, it
|
| 326 |
+
forcifully fits to the bounding box and the side bearings get
|
| 327 |
+
cropped. If you pass ``0`` to both ``width`` and ``height`` and set
|
| 328 |
+
``contain`` to ``True``, it expands to the bounding box while
|
| 329 |
+
maintaining the origin of the contours, meaning that LSB will be
|
| 330 |
+
maintained but RSB won’t. The difference between the two becomes
|
| 331 |
+
more obvious when rotate or skew transformation is applied.
|
| 332 |
+
|
| 333 |
+
Example:
|
| 334 |
+
.. code-block:: pycon
|
| 335 |
+
|
| 336 |
+
>>>
|
| 337 |
+
>> pen = FreeTypePen(None)
|
| 338 |
+
>> glyph.draw(pen)
|
| 339 |
+
>> pen.show(width=500, height=1000)
|
| 340 |
+
"""
|
| 341 |
+
from matplotlib import pyplot as plt
|
| 342 |
+
|
| 343 |
+
a = self.array(
|
| 344 |
+
width=width,
|
| 345 |
+
height=height,
|
| 346 |
+
transform=transform,
|
| 347 |
+
contain=contain,
|
| 348 |
+
evenOdd=evenOdd,
|
| 349 |
+
)
|
| 350 |
+
plt.imshow(a, cmap="gray_r", vmin=0, vmax=1)
|
| 351 |
+
plt.show()
|
| 352 |
+
|
| 353 |
+
def image(
|
| 354 |
+
self, width=None, height=None, transform=None, contain=False, evenOdd=False
|
| 355 |
+
):
|
| 356 |
+
"""Returns the rendered contours as a PIL image. Requires `Pillow`.
|
| 357 |
+
Can be used to display a glyph image in Jupyter Notebook.
|
| 358 |
+
|
| 359 |
+
Args:
|
| 360 |
+
width: Image width of the bitmap in pixels. If omitted, it
|
| 361 |
+
automatically fits to the bounding box of the contours.
|
| 362 |
+
height: Image height of the bitmap in pixels. If omitted, it
|
| 363 |
+
automatically fits to the bounding box of the contours.
|
| 364 |
+
transform: An optional 6-tuple containing an affine transformation,
|
| 365 |
+
or a ``Transform`` object from the ``fontTools.misc.transform``
|
| 366 |
+
module. The bitmap size is not affected by this matrix.
|
| 367 |
+
contain: If ``True``, the image size will be automatically expanded
|
| 368 |
+
so that it fits to the bounding box of the paths. Useful for
|
| 369 |
+
rendering glyphs with negative sidebearings without clipping.
|
| 370 |
+
evenOdd: Pass ``True`` for even-odd fill instead of non-zero.
|
| 371 |
+
|
| 372 |
+
Returns:
|
| 373 |
+
A ``PIL.image`` object. The image is filled in black with alpha
|
| 374 |
+
channel obtained from the rendered bitmap.
|
| 375 |
+
|
| 376 |
+
Notes:
|
| 377 |
+
The image size should always be given explicitly if you need to get
|
| 378 |
+
a proper glyph image. When ``width`` and ``height`` are omitted, it
|
| 379 |
+
forcifully fits to the bounding box and the side bearings get
|
| 380 |
+
cropped. If you pass ``0`` to both ``width`` and ``height`` and set
|
| 381 |
+
``contain`` to ``True``, it expands to the bounding box while
|
| 382 |
+
maintaining the origin of the contours, meaning that LSB will be
|
| 383 |
+
maintained but RSB won’t. The difference between the two becomes
|
| 384 |
+
more obvious when rotate or skew transformation is applied.
|
| 385 |
+
|
| 386 |
+
Example:
|
| 387 |
+
.. code-block:: pycon
|
| 388 |
+
|
| 389 |
+
>>>
|
| 390 |
+
>> pen = FreeTypePen(None)
|
| 391 |
+
>> glyph.draw(pen)
|
| 392 |
+
>> img = pen.image(width=500, height=1000)
|
| 393 |
+
>> type(img), img.size
|
| 394 |
+
(<class 'PIL.Image.Image'>, (500, 1000))
|
| 395 |
+
"""
|
| 396 |
+
from PIL import Image
|
| 397 |
+
|
| 398 |
+
buf, size = self.buffer(
|
| 399 |
+
width=width,
|
| 400 |
+
height=height,
|
| 401 |
+
transform=transform,
|
| 402 |
+
contain=contain,
|
| 403 |
+
evenOdd=evenOdd,
|
| 404 |
+
)
|
| 405 |
+
img = Image.new("L", size, 0)
|
| 406 |
+
img.putalpha(Image.frombuffer("L", size, buf))
|
| 407 |
+
return img
|
| 408 |
+
|
| 409 |
+
@property
|
| 410 |
+
def bbox(self):
|
| 411 |
+
"""Computes the exact bounding box of an outline.
|
| 412 |
+
|
| 413 |
+
Returns:
|
| 414 |
+
A tuple of ``(xMin, yMin, xMax, yMax)``.
|
| 415 |
+
"""
|
| 416 |
+
bbox = FT_BBox()
|
| 417 |
+
outline = self.outline()
|
| 418 |
+
FT_Outline_Get_BBox(ctypes.byref(outline), ctypes.byref(bbox))
|
| 419 |
+
return (bbox.xMin / 64.0, bbox.yMin / 64.0, bbox.xMax / 64.0, bbox.yMax / 64.0)
|
| 420 |
+
|
| 421 |
+
@property
|
| 422 |
+
def cbox(self):
|
| 423 |
+
"""Returns an outline's ‘control box’.
|
| 424 |
+
|
| 425 |
+
Returns:
|
| 426 |
+
A tuple of ``(xMin, yMin, xMax, yMax)``.
|
| 427 |
+
"""
|
| 428 |
+
cbox = FT_BBox()
|
| 429 |
+
outline = self.outline()
|
| 430 |
+
FT_Outline_Get_CBox(ctypes.byref(outline), ctypes.byref(cbox))
|
| 431 |
+
return (cbox.xMin / 64.0, cbox.yMin / 64.0, cbox.xMax / 64.0, cbox.yMax / 64.0)
|
| 432 |
+
|
| 433 |
+
def _moveTo(self, pt):
|
| 434 |
+
contour = Contour([], [])
|
| 435 |
+
self.contours.append(contour)
|
| 436 |
+
contour.points.append(pt)
|
| 437 |
+
contour.tags.append(FT_CURVE_TAG_ON)
|
| 438 |
+
|
| 439 |
+
def _lineTo(self, pt):
|
| 440 |
+
if not (self.contours and len(self.contours[-1].points) > 0):
|
| 441 |
+
raise PenError("Contour missing required initial moveTo")
|
| 442 |
+
contour = self.contours[-1]
|
| 443 |
+
contour.points.append(pt)
|
| 444 |
+
contour.tags.append(FT_CURVE_TAG_ON)
|
| 445 |
+
|
| 446 |
+
def _curveToOne(self, p1, p2, p3):
|
| 447 |
+
if not (self.contours and len(self.contours[-1].points) > 0):
|
| 448 |
+
raise PenError("Contour missing required initial moveTo")
|
| 449 |
+
t1, t2, t3 = FT_CURVE_TAG_CUBIC, FT_CURVE_TAG_CUBIC, FT_CURVE_TAG_ON
|
| 450 |
+
contour = self.contours[-1]
|
| 451 |
+
for p, t in ((p1, t1), (p2, t2), (p3, t3)):
|
| 452 |
+
contour.points.append(p)
|
| 453 |
+
contour.tags.append(t)
|
| 454 |
+
|
| 455 |
+
def _qCurveToOne(self, p1, p2):
|
| 456 |
+
if not (self.contours and len(self.contours[-1].points) > 0):
|
| 457 |
+
raise PenError("Contour missing required initial moveTo")
|
| 458 |
+
t1, t2 = FT_CURVE_TAG_CONIC, FT_CURVE_TAG_ON
|
| 459 |
+
contour = self.contours[-1]
|
| 460 |
+
for p, t in ((p1, t1), (p2, t2)):
|
| 461 |
+
contour.points.append(p)
|
| 462 |
+
contour.tags.append(t)
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/hashPointPen.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified from https://github.com/adobe-type-tools/psautohint/blob/08b346865710ed3c172f1eb581d6ef243b203f99/python/psautohint/ufoFont.py#L800-L838
|
| 2 |
+
import hashlib
|
| 3 |
+
|
| 4 |
+
from fontTools.pens.basePen import MissingComponentError
|
| 5 |
+
from fontTools.pens.pointPen import AbstractPointPen
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class HashPointPen(AbstractPointPen):
|
| 9 |
+
"""
|
| 10 |
+
This pen can be used to check if a glyph's contents (outlines plus
|
| 11 |
+
components) have changed.
|
| 12 |
+
|
| 13 |
+
Components are added as the original outline plus each composite's
|
| 14 |
+
transformation.
|
| 15 |
+
|
| 16 |
+
Example: You have some TrueType hinting code for a glyph which you want to
|
| 17 |
+
compile. The hinting code specifies a hash value computed with HashPointPen
|
| 18 |
+
that was valid for the glyph's outlines at the time the hinting code was
|
| 19 |
+
written. Now you can calculate the hash for the glyph's current outlines to
|
| 20 |
+
check if the outlines have changed, which would probably make the hinting
|
| 21 |
+
code invalid.
|
| 22 |
+
|
| 23 |
+
> glyph = ufo[name]
|
| 24 |
+
> hash_pen = HashPointPen(glyph.width, ufo)
|
| 25 |
+
> glyph.drawPoints(hash_pen)
|
| 26 |
+
> ttdata = glyph.lib.get("public.truetype.instructions", None)
|
| 27 |
+
> stored_hash = ttdata.get("id", None) # The hash is stored in the "id" key
|
| 28 |
+
> if stored_hash is None or stored_hash != hash_pen.hash:
|
| 29 |
+
> logger.error(f"Glyph hash mismatch, glyph '{name}' will have no instructions in font.")
|
| 30 |
+
> else:
|
| 31 |
+
> # The hash values are identical, the outline has not changed.
|
| 32 |
+
> # Compile the hinting code ...
|
| 33 |
+
> pass
|
| 34 |
+
|
| 35 |
+
If you want to compare a glyph from a source format which supports floating point
|
| 36 |
+
coordinates and transformations against a glyph from a format which has restrictions
|
| 37 |
+
on the precision of floats, e.g. UFO vs. TTF, you must use an appropriate rounding
|
| 38 |
+
function to make the values comparable. For TTF fonts with composites, this
|
| 39 |
+
construct can be used to make the transform values conform to F2Dot14:
|
| 40 |
+
|
| 41 |
+
> ttf_hash_pen = HashPointPen(ttf_glyph_width, ttFont.getGlyphSet())
|
| 42 |
+
> ttf_round_pen = RoundingPointPen(ttf_hash_pen, transformRoundFunc=partial(floatToFixedToFloat, precisionBits=14))
|
| 43 |
+
> ufo_hash_pen = HashPointPen(ufo_glyph.width, ufo)
|
| 44 |
+
> ttf_glyph.drawPoints(ttf_round_pen, ttFont["glyf"])
|
| 45 |
+
> ufo_round_pen = RoundingPointPen(ufo_hash_pen, transformRoundFunc=partial(floatToFixedToFloat, precisionBits=14))
|
| 46 |
+
> ufo_glyph.drawPoints(ufo_round_pen)
|
| 47 |
+
> assert ttf_hash_pen.hash == ufo_hash_pen.hash
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
def __init__(self, glyphWidth=0, glyphSet=None):
|
| 51 |
+
self.glyphset = glyphSet
|
| 52 |
+
self.data = ["w%s" % round(glyphWidth, 9)]
|
| 53 |
+
|
| 54 |
+
@property
|
| 55 |
+
def hash(self):
|
| 56 |
+
data = "".join(self.data)
|
| 57 |
+
if len(data) >= 128:
|
| 58 |
+
data = hashlib.sha512(data.encode("ascii")).hexdigest()
|
| 59 |
+
return data
|
| 60 |
+
|
| 61 |
+
def beginPath(self, identifier=None, **kwargs):
|
| 62 |
+
pass
|
| 63 |
+
|
| 64 |
+
def endPath(self):
|
| 65 |
+
self.data.append("|")
|
| 66 |
+
|
| 67 |
+
def addPoint(
|
| 68 |
+
self,
|
| 69 |
+
pt,
|
| 70 |
+
segmentType=None,
|
| 71 |
+
smooth=False,
|
| 72 |
+
name=None,
|
| 73 |
+
identifier=None,
|
| 74 |
+
**kwargs,
|
| 75 |
+
):
|
| 76 |
+
if segmentType is None:
|
| 77 |
+
pt_type = "o" # offcurve
|
| 78 |
+
else:
|
| 79 |
+
pt_type = segmentType[0]
|
| 80 |
+
self.data.append(f"{pt_type}{pt[0]:g}{pt[1]:+g}")
|
| 81 |
+
|
| 82 |
+
def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs):
|
| 83 |
+
tr = "".join([f"{t:+}" for t in transformation])
|
| 84 |
+
self.data.append("[")
|
| 85 |
+
try:
|
| 86 |
+
self.glyphset[baseGlyphName].drawPoints(self)
|
| 87 |
+
except KeyError:
|
| 88 |
+
raise MissingComponentError(baseGlyphName)
|
| 89 |
+
self.data.append(f"({tr})]")
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/perimeterPen.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Calculate the perimeter of a glyph."""
|
| 3 |
+
|
| 4 |
+
from fontTools.pens.basePen import BasePen
|
| 5 |
+
from fontTools.misc.bezierTools import (
|
| 6 |
+
approximateQuadraticArcLengthC,
|
| 7 |
+
calcQuadraticArcLengthC,
|
| 8 |
+
approximateCubicArcLengthC,
|
| 9 |
+
calcCubicArcLengthC,
|
| 10 |
+
)
|
| 11 |
+
import math
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = ["PerimeterPen"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _distance(p0, p1):
|
| 18 |
+
return math.hypot(p0[0] - p1[0], p0[1] - p1[1])
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class PerimeterPen(BasePen):
|
| 22 |
+
def __init__(self, glyphset=None, tolerance=0.005):
|
| 23 |
+
BasePen.__init__(self, glyphset)
|
| 24 |
+
self.value = 0
|
| 25 |
+
self.tolerance = tolerance
|
| 26 |
+
|
| 27 |
+
# Choose which algorithm to use for quadratic and for cubic.
|
| 28 |
+
# Quadrature is faster but has fixed error characteristic with no strong
|
| 29 |
+
# error bound. The cutoff points are derived empirically.
|
| 30 |
+
self._addCubic = (
|
| 31 |
+
self._addCubicQuadrature if tolerance >= 0.0015 else self._addCubicRecursive
|
| 32 |
+
)
|
| 33 |
+
self._addQuadratic = (
|
| 34 |
+
self._addQuadraticQuadrature
|
| 35 |
+
if tolerance >= 0.00075
|
| 36 |
+
else self._addQuadraticExact
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
def _moveTo(self, p0):
|
| 40 |
+
self.__startPoint = p0
|
| 41 |
+
|
| 42 |
+
def _closePath(self):
|
| 43 |
+
p0 = self._getCurrentPoint()
|
| 44 |
+
if p0 != self.__startPoint:
|
| 45 |
+
self._lineTo(self.__startPoint)
|
| 46 |
+
|
| 47 |
+
def _lineTo(self, p1):
|
| 48 |
+
p0 = self._getCurrentPoint()
|
| 49 |
+
self.value += _distance(p0, p1)
|
| 50 |
+
|
| 51 |
+
def _addQuadraticExact(self, c0, c1, c2):
|
| 52 |
+
self.value += calcQuadraticArcLengthC(c0, c1, c2)
|
| 53 |
+
|
| 54 |
+
def _addQuadraticQuadrature(self, c0, c1, c2):
|
| 55 |
+
self.value += approximateQuadraticArcLengthC(c0, c1, c2)
|
| 56 |
+
|
| 57 |
+
def _qCurveToOne(self, p1, p2):
|
| 58 |
+
p0 = self._getCurrentPoint()
|
| 59 |
+
self._addQuadratic(complex(*p0), complex(*p1), complex(*p2))
|
| 60 |
+
|
| 61 |
+
def _addCubicRecursive(self, c0, c1, c2, c3):
|
| 62 |
+
self.value += calcCubicArcLengthC(c0, c1, c2, c3, self.tolerance)
|
| 63 |
+
|
| 64 |
+
def _addCubicQuadrature(self, c0, c1, c2, c3):
|
| 65 |
+
self.value += approximateCubicArcLengthC(c0, c1, c2, c3)
|
| 66 |
+
|
| 67 |
+
def _curveToOne(self, p1, p2, p3):
|
| 68 |
+
p0 = self._getCurrentPoint()
|
| 69 |
+
self._addCubic(complex(*p0), complex(*p1), complex(*p2), complex(*p3))
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/pointInsidePen.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""fontTools.pens.pointInsidePen -- Pen implementing "point inside" testing
|
| 2 |
+
for shapes.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from fontTools.pens.basePen import BasePen
|
| 6 |
+
from fontTools.misc.bezierTools import solveQuadratic, solveCubic
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
__all__ = ["PointInsidePen"]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class PointInsidePen(BasePen):
|
| 13 |
+
"""This pen implements "point inside" testing: to test whether
|
| 14 |
+
a given point lies inside the shape (black) or outside (white).
|
| 15 |
+
Instances of this class can be recycled, as long as the
|
| 16 |
+
setTestPoint() method is used to set the new point to test.
|
| 17 |
+
|
| 18 |
+
:Example:
|
| 19 |
+
.. code-block::
|
| 20 |
+
|
| 21 |
+
pen = PointInsidePen(glyphSet, (100, 200))
|
| 22 |
+
outline.draw(pen)
|
| 23 |
+
isInside = pen.getResult()
|
| 24 |
+
|
| 25 |
+
Both the even-odd algorithm and the non-zero-winding-rule
|
| 26 |
+
algorithm are implemented. The latter is the default, specify
|
| 27 |
+
True for the evenOdd argument of __init__ or setTestPoint
|
| 28 |
+
to use the even-odd algorithm.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
# This class implements the classical "shoot a ray from the test point
|
| 32 |
+
# to infinity and count how many times it intersects the outline" (as well
|
| 33 |
+
# as the non-zero variant, where the counter is incremented if the outline
|
| 34 |
+
# intersects the ray in one direction and decremented if it intersects in
|
| 35 |
+
# the other direction).
|
| 36 |
+
# I found an amazingly clear explanation of the subtleties involved in
|
| 37 |
+
# implementing this correctly for polygons here:
|
| 38 |
+
# http://graphics.cs.ucdavis.edu/~okreylos/TAship/Spring2000/PointInPolygon.html
|
| 39 |
+
# I extended the principles outlined on that page to curves.
|
| 40 |
+
|
| 41 |
+
def __init__(self, glyphSet, testPoint, evenOdd=False):
|
| 42 |
+
BasePen.__init__(self, glyphSet)
|
| 43 |
+
self.setTestPoint(testPoint, evenOdd)
|
| 44 |
+
|
| 45 |
+
def setTestPoint(self, testPoint, evenOdd=False):
|
| 46 |
+
"""Set the point to test. Call this _before_ the outline gets drawn."""
|
| 47 |
+
self.testPoint = testPoint
|
| 48 |
+
self.evenOdd = evenOdd
|
| 49 |
+
self.firstPoint = None
|
| 50 |
+
self.intersectionCount = 0
|
| 51 |
+
|
| 52 |
+
def getWinding(self):
|
| 53 |
+
if self.firstPoint is not None:
|
| 54 |
+
# always make sure the sub paths are closed; the algorithm only works
|
| 55 |
+
# for closed paths.
|
| 56 |
+
self.closePath()
|
| 57 |
+
return self.intersectionCount
|
| 58 |
+
|
| 59 |
+
def getResult(self):
|
| 60 |
+
"""After the shape has been drawn, getResult() returns True if the test
|
| 61 |
+
point lies within the (black) shape, and False if it doesn't.
|
| 62 |
+
"""
|
| 63 |
+
winding = self.getWinding()
|
| 64 |
+
if self.evenOdd:
|
| 65 |
+
result = winding % 2
|
| 66 |
+
else: # non-zero
|
| 67 |
+
result = self.intersectionCount != 0
|
| 68 |
+
return not not result
|
| 69 |
+
|
| 70 |
+
def _addIntersection(self, goingUp):
|
| 71 |
+
if self.evenOdd or goingUp:
|
| 72 |
+
self.intersectionCount += 1
|
| 73 |
+
else:
|
| 74 |
+
self.intersectionCount -= 1
|
| 75 |
+
|
| 76 |
+
def _moveTo(self, point):
|
| 77 |
+
if self.firstPoint is not None:
|
| 78 |
+
# always make sure the sub paths are closed; the algorithm only works
|
| 79 |
+
# for closed paths.
|
| 80 |
+
self.closePath()
|
| 81 |
+
self.firstPoint = point
|
| 82 |
+
|
| 83 |
+
def _lineTo(self, point):
|
| 84 |
+
x, y = self.testPoint
|
| 85 |
+
x1, y1 = self._getCurrentPoint()
|
| 86 |
+
x2, y2 = point
|
| 87 |
+
|
| 88 |
+
if x1 < x and x2 < x:
|
| 89 |
+
return
|
| 90 |
+
if y1 < y and y2 < y:
|
| 91 |
+
return
|
| 92 |
+
if y1 >= y and y2 >= y:
|
| 93 |
+
return
|
| 94 |
+
|
| 95 |
+
dx = x2 - x1
|
| 96 |
+
dy = y2 - y1
|
| 97 |
+
t = (y - y1) / dy
|
| 98 |
+
ix = dx * t + x1
|
| 99 |
+
if ix < x:
|
| 100 |
+
return
|
| 101 |
+
self._addIntersection(y2 > y1)
|
| 102 |
+
|
| 103 |
+
def _curveToOne(self, bcp1, bcp2, point):
|
| 104 |
+
x, y = self.testPoint
|
| 105 |
+
x1, y1 = self._getCurrentPoint()
|
| 106 |
+
x2, y2 = bcp1
|
| 107 |
+
x3, y3 = bcp2
|
| 108 |
+
x4, y4 = point
|
| 109 |
+
|
| 110 |
+
if x1 < x and x2 < x and x3 < x and x4 < x:
|
| 111 |
+
return
|
| 112 |
+
if y1 < y and y2 < y and y3 < y and y4 < y:
|
| 113 |
+
return
|
| 114 |
+
if y1 >= y and y2 >= y and y3 >= y and y4 >= y:
|
| 115 |
+
return
|
| 116 |
+
|
| 117 |
+
dy = y1
|
| 118 |
+
cy = (y2 - dy) * 3.0
|
| 119 |
+
by = (y3 - y2) * 3.0 - cy
|
| 120 |
+
ay = y4 - dy - cy - by
|
| 121 |
+
solutions = sorted(solveCubic(ay, by, cy, dy - y))
|
| 122 |
+
solutions = [t for t in solutions if -0.0 <= t <= 1.0]
|
| 123 |
+
if not solutions:
|
| 124 |
+
return
|
| 125 |
+
|
| 126 |
+
dx = x1
|
| 127 |
+
cx = (x2 - dx) * 3.0
|
| 128 |
+
bx = (x3 - x2) * 3.0 - cx
|
| 129 |
+
ax = x4 - dx - cx - bx
|
| 130 |
+
|
| 131 |
+
above = y1 >= y
|
| 132 |
+
lastT = None
|
| 133 |
+
for t in solutions:
|
| 134 |
+
if t == lastT:
|
| 135 |
+
continue
|
| 136 |
+
lastT = t
|
| 137 |
+
t2 = t * t
|
| 138 |
+
t3 = t2 * t
|
| 139 |
+
|
| 140 |
+
direction = 3 * ay * t2 + 2 * by * t + cy
|
| 141 |
+
incomingGoingUp = outgoingGoingUp = direction > 0.0
|
| 142 |
+
if direction == 0.0:
|
| 143 |
+
direction = 6 * ay * t + 2 * by
|
| 144 |
+
outgoingGoingUp = direction > 0.0
|
| 145 |
+
incomingGoingUp = not outgoingGoingUp
|
| 146 |
+
if direction == 0.0:
|
| 147 |
+
direction = ay
|
| 148 |
+
incomingGoingUp = outgoingGoingUp = direction > 0.0
|
| 149 |
+
|
| 150 |
+
xt = ax * t3 + bx * t2 + cx * t + dx
|
| 151 |
+
if xt < x:
|
| 152 |
+
continue
|
| 153 |
+
|
| 154 |
+
if t in (0.0, -0.0):
|
| 155 |
+
if not outgoingGoingUp:
|
| 156 |
+
self._addIntersection(outgoingGoingUp)
|
| 157 |
+
elif t == 1.0:
|
| 158 |
+
if incomingGoingUp:
|
| 159 |
+
self._addIntersection(incomingGoingUp)
|
| 160 |
+
else:
|
| 161 |
+
if incomingGoingUp == outgoingGoingUp:
|
| 162 |
+
self._addIntersection(outgoingGoingUp)
|
| 163 |
+
# else:
|
| 164 |
+
# we're not really intersecting, merely touching
|
| 165 |
+
|
| 166 |
+
def _qCurveToOne_unfinished(self, bcp, point):
|
| 167 |
+
# XXX need to finish this, for now doing it through a cubic
|
| 168 |
+
# (BasePen implements _qCurveTo in terms of a cubic) will
|
| 169 |
+
# have to do.
|
| 170 |
+
x, y = self.testPoint
|
| 171 |
+
x1, y1 = self._getCurrentPoint()
|
| 172 |
+
x2, y2 = bcp
|
| 173 |
+
x3, y3 = point
|
| 174 |
+
c = y1
|
| 175 |
+
b = (y2 - c) * 2.0
|
| 176 |
+
a = y3 - c - b
|
| 177 |
+
solutions = sorted(solveQuadratic(a, b, c - y))
|
| 178 |
+
solutions = [
|
| 179 |
+
t for t in solutions if ZERO_MINUS_EPSILON <= t <= ONE_PLUS_EPSILON
|
| 180 |
+
]
|
| 181 |
+
if not solutions:
|
| 182 |
+
return
|
| 183 |
+
# XXX
|
| 184 |
+
|
| 185 |
+
def _closePath(self):
|
| 186 |
+
if self._getCurrentPoint() != self.firstPoint:
|
| 187 |
+
self.lineTo(self.firstPoint)
|
| 188 |
+
self.firstPoint = None
|
| 189 |
+
|
| 190 |
+
def _endPath(self):
|
| 191 |
+
"""Insideness is not defined for open contours."""
|
| 192 |
+
raise NotImplementedError
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/pointPen.py
ADDED
|
@@ -0,0 +1,600 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ointPens
|
| 4 |
+
=========
|
| 5 |
+
|
| 6 |
+
Where **SegmentPens** have an intuitive approach to drawing
|
| 7 |
+
(if you're familiar with postscript anyway), the **PointPen**
|
| 8 |
+
is geared towards accessing all the data in the contours of
|
| 9 |
+
the glyph. A PointPen has a very simple interface, it just
|
| 10 |
+
steps through all the points in a call from glyph.drawPoints().
|
| 11 |
+
This allows the caller to provide more data for each point.
|
| 12 |
+
For instance, whether or not a point is smooth, and its name.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
from typing import Any, Optional, Tuple, Dict
|
| 17 |
+
|
| 18 |
+
from fontTools.misc.loggingTools import LogMixin
|
| 19 |
+
from fontTools.pens.basePen import AbstractPen, MissingComponentError, PenError
|
| 20 |
+
from fontTools.misc.transform import DecomposedTransform, Identity
|
| 21 |
+
|
| 22 |
+
__all__ = [
|
| 23 |
+
"AbstractPointPen",
|
| 24 |
+
"BasePointToSegmentPen",
|
| 25 |
+
"PointToSegmentPen",
|
| 26 |
+
"SegmentToPointPen",
|
| 27 |
+
"GuessSmoothPointPen",
|
| 28 |
+
"ReverseContourPointPen",
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class AbstractPointPen:
|
| 33 |
+
"""Baseclass for all PointPens."""
|
| 34 |
+
|
| 35 |
+
def beginPath(self, identifier: Optional[str] = None, **kwargs: Any) -> None:
|
| 36 |
+
"""Start a new sub path."""
|
| 37 |
+
raise NotImplementedError
|
| 38 |
+
|
| 39 |
+
def endPath(self) -> None:
|
| 40 |
+
"""End the current sub path."""
|
| 41 |
+
raise NotImplementedError
|
| 42 |
+
|
| 43 |
+
def addPoint(
|
| 44 |
+
self,
|
| 45 |
+
pt: Tuple[float, float],
|
| 46 |
+
segmentType: Optional[str] = None,
|
| 47 |
+
smooth: bool = False,
|
| 48 |
+
name: Optional[str] = None,
|
| 49 |
+
identifier: Optional[str] = None,
|
| 50 |
+
**kwargs: Any,
|
| 51 |
+
) -> None:
|
| 52 |
+
"""Add a point to the current sub path."""
|
| 53 |
+
raise NotImplementedError
|
| 54 |
+
|
| 55 |
+
def addComponent(
|
| 56 |
+
self,
|
| 57 |
+
baseGlyphName: str,
|
| 58 |
+
transformation: Tuple[float, float, float, float, float, float],
|
| 59 |
+
identifier: Optional[str] = None,
|
| 60 |
+
**kwargs: Any,
|
| 61 |
+
) -> None:
|
| 62 |
+
"""Add a sub glyph."""
|
| 63 |
+
raise NotImplementedError
|
| 64 |
+
|
| 65 |
+
def addVarComponent(
|
| 66 |
+
self,
|
| 67 |
+
glyphName: str,
|
| 68 |
+
transformation: DecomposedTransform,
|
| 69 |
+
location: Dict[str, float],
|
| 70 |
+
identifier: Optional[str] = None,
|
| 71 |
+
**kwargs: Any,
|
| 72 |
+
) -> None:
|
| 73 |
+
"""Add a VarComponent sub glyph. The 'transformation' argument
|
| 74 |
+
must be a DecomposedTransform from the fontTools.misc.transform module,
|
| 75 |
+
and the 'location' argument must be a dictionary mapping axis tags
|
| 76 |
+
to their locations.
|
| 77 |
+
"""
|
| 78 |
+
# ttGlyphSet decomposes for us
|
| 79 |
+
raise AttributeError
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class BasePointToSegmentPen(AbstractPointPen):
|
| 83 |
+
"""
|
| 84 |
+
Base class for retrieving the outline in a segment-oriented
|
| 85 |
+
way. The PointPen protocol is simple yet also a little tricky,
|
| 86 |
+
so when you need an outline presented as segments but you have
|
| 87 |
+
as points, do use this base implementation as it properly takes
|
| 88 |
+
care of all the edge cases.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
def __init__(self):
|
| 92 |
+
self.currentPath = None
|
| 93 |
+
|
| 94 |
+
def beginPath(self, identifier=None, **kwargs):
|
| 95 |
+
if self.currentPath is not None:
|
| 96 |
+
raise PenError("Path already begun.")
|
| 97 |
+
self.currentPath = []
|
| 98 |
+
|
| 99 |
+
def _flushContour(self, segments):
|
| 100 |
+
"""Override this method.
|
| 101 |
+
|
| 102 |
+
It will be called for each non-empty sub path with a list
|
| 103 |
+
of segments: the 'segments' argument.
|
| 104 |
+
|
| 105 |
+
The segments list contains tuples of length 2:
|
| 106 |
+
(segmentType, points)
|
| 107 |
+
|
| 108 |
+
segmentType is one of "move", "line", "curve" or "qcurve".
|
| 109 |
+
"move" may only occur as the first segment, and it signifies
|
| 110 |
+
an OPEN path. A CLOSED path does NOT start with a "move", in
|
| 111 |
+
fact it will not contain a "move" at ALL.
|
| 112 |
+
|
| 113 |
+
The 'points' field in the 2-tuple is a list of point info
|
| 114 |
+
tuples. The list has 1 or more items, a point tuple has
|
| 115 |
+
four items:
|
| 116 |
+
(point, smooth, name, kwargs)
|
| 117 |
+
'point' is an (x, y) coordinate pair.
|
| 118 |
+
|
| 119 |
+
For a closed path, the initial moveTo point is defined as
|
| 120 |
+
the last point of the last segment.
|
| 121 |
+
|
| 122 |
+
The 'points' list of "move" and "line" segments always contains
|
| 123 |
+
exactly one point tuple.
|
| 124 |
+
"""
|
| 125 |
+
raise NotImplementedError
|
| 126 |
+
|
| 127 |
+
def endPath(self):
|
| 128 |
+
if self.currentPath is None:
|
| 129 |
+
raise PenError("Path not begun.")
|
| 130 |
+
points = self.currentPath
|
| 131 |
+
self.currentPath = None
|
| 132 |
+
if not points:
|
| 133 |
+
return
|
| 134 |
+
if len(points) == 1:
|
| 135 |
+
# Not much more we can do than output a single move segment.
|
| 136 |
+
pt, segmentType, smooth, name, kwargs = points[0]
|
| 137 |
+
segments = [("move", [(pt, smooth, name, kwargs)])]
|
| 138 |
+
self._flushContour(segments)
|
| 139 |
+
return
|
| 140 |
+
segments = []
|
| 141 |
+
if points[0][1] == "move":
|
| 142 |
+
# It's an open contour, insert a "move" segment for the first
|
| 143 |
+
# point and remove that first point from the point list.
|
| 144 |
+
pt, segmentType, smooth, name, kwargs = points[0]
|
| 145 |
+
segments.append(("move", [(pt, smooth, name, kwargs)]))
|
| 146 |
+
points.pop(0)
|
| 147 |
+
else:
|
| 148 |
+
# It's a closed contour. Locate the first on-curve point, and
|
| 149 |
+
# rotate the point list so that it _ends_ with an on-curve
|
| 150 |
+
# point.
|
| 151 |
+
firstOnCurve = None
|
| 152 |
+
for i in range(len(points)):
|
| 153 |
+
segmentType = points[i][1]
|
| 154 |
+
if segmentType is not None:
|
| 155 |
+
firstOnCurve = i
|
| 156 |
+
break
|
| 157 |
+
if firstOnCurve is None:
|
| 158 |
+
# Special case for quadratics: a contour with no on-curve
|
| 159 |
+
# points. Add a "None" point. (See also the Pen protocol's
|
| 160 |
+
# qCurveTo() method and fontTools.pens.basePen.py.)
|
| 161 |
+
points.append((None, "qcurve", None, None, None))
|
| 162 |
+
else:
|
| 163 |
+
points = points[firstOnCurve + 1 :] + points[: firstOnCurve + 1]
|
| 164 |
+
|
| 165 |
+
currentSegment = []
|
| 166 |
+
for pt, segmentType, smooth, name, kwargs in points:
|
| 167 |
+
currentSegment.append((pt, smooth, name, kwargs))
|
| 168 |
+
if segmentType is None:
|
| 169 |
+
continue
|
| 170 |
+
segments.append((segmentType, currentSegment))
|
| 171 |
+
currentSegment = []
|
| 172 |
+
|
| 173 |
+
self._flushContour(segments)
|
| 174 |
+
|
| 175 |
+
def addPoint(
|
| 176 |
+
self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs
|
| 177 |
+
):
|
| 178 |
+
if self.currentPath is None:
|
| 179 |
+
raise PenError("Path not begun")
|
| 180 |
+
self.currentPath.append((pt, segmentType, smooth, name, kwargs))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class PointToSegmentPen(BasePointToSegmentPen):
|
| 184 |
+
"""
|
| 185 |
+
Adapter class that converts the PointPen protocol to the
|
| 186 |
+
(Segment)Pen protocol.
|
| 187 |
+
|
| 188 |
+
NOTE: The segment pen does not support and will drop point names, identifiers
|
| 189 |
+
and kwargs.
|
| 190 |
+
"""
|
| 191 |
+
|
| 192 |
+
def __init__(self, segmentPen, outputImpliedClosingLine=False):
|
| 193 |
+
BasePointToSegmentPen.__init__(self)
|
| 194 |
+
self.pen = segmentPen
|
| 195 |
+
self.outputImpliedClosingLine = outputImpliedClosingLine
|
| 196 |
+
|
| 197 |
+
def _flushContour(self, segments):
|
| 198 |
+
if not segments:
|
| 199 |
+
raise PenError("Must have at least one segment.")
|
| 200 |
+
pen = self.pen
|
| 201 |
+
if segments[0][0] == "move":
|
| 202 |
+
# It's an open path.
|
| 203 |
+
closed = False
|
| 204 |
+
points = segments[0][1]
|
| 205 |
+
if len(points) != 1:
|
| 206 |
+
raise PenError(f"Illegal move segment point count: {len(points)}")
|
| 207 |
+
movePt, _, _, _ = points[0]
|
| 208 |
+
del segments[0]
|
| 209 |
+
else:
|
| 210 |
+
# It's a closed path, do a moveTo to the last
|
| 211 |
+
# point of the last segment.
|
| 212 |
+
closed = True
|
| 213 |
+
segmentType, points = segments[-1]
|
| 214 |
+
movePt, _, _, _ = points[-1]
|
| 215 |
+
if movePt is None:
|
| 216 |
+
# quad special case: a contour with no on-curve points contains
|
| 217 |
+
# one "qcurve" segment that ends with a point that's None. We
|
| 218 |
+
# must not output a moveTo() in that case.
|
| 219 |
+
pass
|
| 220 |
+
else:
|
| 221 |
+
pen.moveTo(movePt)
|
| 222 |
+
outputImpliedClosingLine = self.outputImpliedClosingLine
|
| 223 |
+
nSegments = len(segments)
|
| 224 |
+
lastPt = movePt
|
| 225 |
+
for i in range(nSegments):
|
| 226 |
+
segmentType, points = segments[i]
|
| 227 |
+
points = [pt for pt, _, _, _ in points]
|
| 228 |
+
if segmentType == "line":
|
| 229 |
+
if len(points) != 1:
|
| 230 |
+
raise PenError(f"Illegal line segment point count: {len(points)}")
|
| 231 |
+
pt = points[0]
|
| 232 |
+
# For closed contours, a 'lineTo' is always implied from the last oncurve
|
| 233 |
+
# point to the starting point, thus we can omit it when the last and
|
| 234 |
+
# starting point don't overlap.
|
| 235 |
+
# However, when the last oncurve point is a "line" segment and has same
|
| 236 |
+
# coordinates as the starting point of a closed contour, we need to output
|
| 237 |
+
# the closing 'lineTo' explicitly (regardless of the value of the
|
| 238 |
+
# 'outputImpliedClosingLine' option) in order to disambiguate this case from
|
| 239 |
+
# the implied closing 'lineTo', otherwise the duplicate point would be lost.
|
| 240 |
+
# See https://github.com/googlefonts/fontmake/issues/572.
|
| 241 |
+
if (
|
| 242 |
+
i + 1 != nSegments
|
| 243 |
+
or outputImpliedClosingLine
|
| 244 |
+
or not closed
|
| 245 |
+
or pt == lastPt
|
| 246 |
+
):
|
| 247 |
+
pen.lineTo(pt)
|
| 248 |
+
lastPt = pt
|
| 249 |
+
elif segmentType == "curve":
|
| 250 |
+
pen.curveTo(*points)
|
| 251 |
+
lastPt = points[-1]
|
| 252 |
+
elif segmentType == "qcurve":
|
| 253 |
+
pen.qCurveTo(*points)
|
| 254 |
+
lastPt = points[-1]
|
| 255 |
+
else:
|
| 256 |
+
raise PenError(f"Illegal segmentType: {segmentType}")
|
| 257 |
+
if closed:
|
| 258 |
+
pen.closePath()
|
| 259 |
+
else:
|
| 260 |
+
pen.endPath()
|
| 261 |
+
|
| 262 |
+
def addComponent(self, glyphName, transform, identifier=None, **kwargs):
|
| 263 |
+
del identifier # unused
|
| 264 |
+
del kwargs # unused
|
| 265 |
+
self.pen.addComponent(glyphName, transform)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class SegmentToPointPen(AbstractPen):
|
| 269 |
+
"""
|
| 270 |
+
Adapter class that converts the (Segment)Pen protocol to the
|
| 271 |
+
PointPen protocol.
|
| 272 |
+
"""
|
| 273 |
+
|
| 274 |
+
def __init__(self, pointPen, guessSmooth=True):
|
| 275 |
+
if guessSmooth:
|
| 276 |
+
self.pen = GuessSmoothPointPen(pointPen)
|
| 277 |
+
else:
|
| 278 |
+
self.pen = pointPen
|
| 279 |
+
self.contour = None
|
| 280 |
+
|
| 281 |
+
def _flushContour(self):
|
| 282 |
+
pen = self.pen
|
| 283 |
+
pen.beginPath()
|
| 284 |
+
for pt, segmentType in self.contour:
|
| 285 |
+
pen.addPoint(pt, segmentType=segmentType)
|
| 286 |
+
pen.endPath()
|
| 287 |
+
|
| 288 |
+
def moveTo(self, pt):
|
| 289 |
+
self.contour = []
|
| 290 |
+
self.contour.append((pt, "move"))
|
| 291 |
+
|
| 292 |
+
def lineTo(self, pt):
|
| 293 |
+
if self.contour is None:
|
| 294 |
+
raise PenError("Contour missing required initial moveTo")
|
| 295 |
+
self.contour.append((pt, "line"))
|
| 296 |
+
|
| 297 |
+
def curveTo(self, *pts):
|
| 298 |
+
if not pts:
|
| 299 |
+
raise TypeError("Must pass in at least one point")
|
| 300 |
+
if self.contour is None:
|
| 301 |
+
raise PenError("Contour missing required initial moveTo")
|
| 302 |
+
for pt in pts[:-1]:
|
| 303 |
+
self.contour.append((pt, None))
|
| 304 |
+
self.contour.append((pts[-1], "curve"))
|
| 305 |
+
|
| 306 |
+
def qCurveTo(self, *pts):
|
| 307 |
+
if not pts:
|
| 308 |
+
raise TypeError("Must pass in at least one point")
|
| 309 |
+
if pts[-1] is None:
|
| 310 |
+
self.contour = []
|
| 311 |
+
else:
|
| 312 |
+
if self.contour is None:
|
| 313 |
+
raise PenError("Contour missing required initial moveTo")
|
| 314 |
+
for pt in pts[:-1]:
|
| 315 |
+
self.contour.append((pt, None))
|
| 316 |
+
if pts[-1] is not None:
|
| 317 |
+
self.contour.append((pts[-1], "qcurve"))
|
| 318 |
+
|
| 319 |
+
def closePath(self):
|
| 320 |
+
if self.contour is None:
|
| 321 |
+
raise PenError("Contour missing required initial moveTo")
|
| 322 |
+
if len(self.contour) > 1 and self.contour[0][0] == self.contour[-1][0]:
|
| 323 |
+
self.contour[0] = self.contour[-1]
|
| 324 |
+
del self.contour[-1]
|
| 325 |
+
else:
|
| 326 |
+
# There's an implied line at the end, replace "move" with "line"
|
| 327 |
+
# for the first point
|
| 328 |
+
pt, tp = self.contour[0]
|
| 329 |
+
if tp == "move":
|
| 330 |
+
self.contour[0] = pt, "line"
|
| 331 |
+
self._flushContour()
|
| 332 |
+
self.contour = None
|
| 333 |
+
|
| 334 |
+
def endPath(self):
|
| 335 |
+
if self.contour is None:
|
| 336 |
+
raise PenError("Contour missing required initial moveTo")
|
| 337 |
+
self._flushContour()
|
| 338 |
+
self.contour = None
|
| 339 |
+
|
| 340 |
+
def addComponent(self, glyphName, transform):
|
| 341 |
+
if self.contour is not None:
|
| 342 |
+
raise PenError("Components must be added before or after contours")
|
| 343 |
+
self.pen.addComponent(glyphName, transform)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class GuessSmoothPointPen(AbstractPointPen):
|
| 347 |
+
"""
|
| 348 |
+
Filtering PointPen that tries to determine whether an on-curve point
|
| 349 |
+
should be "smooth", ie. that it's a "tangent" point or a "curve" point.
|
| 350 |
+
"""
|
| 351 |
+
|
| 352 |
+
def __init__(self, outPen, error=0.05):
|
| 353 |
+
self._outPen = outPen
|
| 354 |
+
self._error = error
|
| 355 |
+
self._points = None
|
| 356 |
+
|
| 357 |
+
def _flushContour(self):
|
| 358 |
+
if self._points is None:
|
| 359 |
+
raise PenError("Path not begun")
|
| 360 |
+
points = self._points
|
| 361 |
+
nPoints = len(points)
|
| 362 |
+
if not nPoints:
|
| 363 |
+
return
|
| 364 |
+
if points[0][1] == "move":
|
| 365 |
+
# Open path.
|
| 366 |
+
indices = range(1, nPoints - 1)
|
| 367 |
+
elif nPoints > 1:
|
| 368 |
+
# Closed path. To avoid having to mod the contour index, we
|
| 369 |
+
# simply abuse Python's negative index feature, and start at -1
|
| 370 |
+
indices = range(-1, nPoints - 1)
|
| 371 |
+
else:
|
| 372 |
+
# closed path containing 1 point (!), ignore.
|
| 373 |
+
indices = []
|
| 374 |
+
for i in indices:
|
| 375 |
+
pt, segmentType, _, name, kwargs = points[i]
|
| 376 |
+
if segmentType is None:
|
| 377 |
+
continue
|
| 378 |
+
prev = i - 1
|
| 379 |
+
next = i + 1
|
| 380 |
+
if points[prev][1] is not None and points[next][1] is not None:
|
| 381 |
+
continue
|
| 382 |
+
# At least one of our neighbors is an off-curve point
|
| 383 |
+
pt = points[i][0]
|
| 384 |
+
prevPt = points[prev][0]
|
| 385 |
+
nextPt = points[next][0]
|
| 386 |
+
if pt != prevPt and pt != nextPt:
|
| 387 |
+
dx1, dy1 = pt[0] - prevPt[0], pt[1] - prevPt[1]
|
| 388 |
+
dx2, dy2 = nextPt[0] - pt[0], nextPt[1] - pt[1]
|
| 389 |
+
a1 = math.atan2(dy1, dx1)
|
| 390 |
+
a2 = math.atan2(dy2, dx2)
|
| 391 |
+
if abs(a1 - a2) < self._error:
|
| 392 |
+
points[i] = pt, segmentType, True, name, kwargs
|
| 393 |
+
|
| 394 |
+
for pt, segmentType, smooth, name, kwargs in points:
|
| 395 |
+
self._outPen.addPoint(pt, segmentType, smooth, name, **kwargs)
|
| 396 |
+
|
| 397 |
+
def beginPath(self, identifier=None, **kwargs):
|
| 398 |
+
if self._points is not None:
|
| 399 |
+
raise PenError("Path already begun")
|
| 400 |
+
self._points = []
|
| 401 |
+
if identifier is not None:
|
| 402 |
+
kwargs["identifier"] = identifier
|
| 403 |
+
self._outPen.beginPath(**kwargs)
|
| 404 |
+
|
| 405 |
+
def endPath(self):
|
| 406 |
+
self._flushContour()
|
| 407 |
+
self._outPen.endPath()
|
| 408 |
+
self._points = None
|
| 409 |
+
|
| 410 |
+
def addPoint(
|
| 411 |
+
self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs
|
| 412 |
+
):
|
| 413 |
+
if self._points is None:
|
| 414 |
+
raise PenError("Path not begun")
|
| 415 |
+
if identifier is not None:
|
| 416 |
+
kwargs["identifier"] = identifier
|
| 417 |
+
self._points.append((pt, segmentType, False, name, kwargs))
|
| 418 |
+
|
| 419 |
+
def addComponent(self, glyphName, transformation, identifier=None, **kwargs):
|
| 420 |
+
if self._points is not None:
|
| 421 |
+
raise PenError("Components must be added before or after contours")
|
| 422 |
+
if identifier is not None:
|
| 423 |
+
kwargs["identifier"] = identifier
|
| 424 |
+
self._outPen.addComponent(glyphName, transformation, **kwargs)
|
| 425 |
+
|
| 426 |
+
def addVarComponent(
|
| 427 |
+
self, glyphName, transformation, location, identifier=None, **kwargs
|
| 428 |
+
):
|
| 429 |
+
if self._points is not None:
|
| 430 |
+
raise PenError("VarComponents must be added before or after contours")
|
| 431 |
+
if identifier is not None:
|
| 432 |
+
kwargs["identifier"] = identifier
|
| 433 |
+
self._outPen.addVarComponent(glyphName, transformation, location, **kwargs)
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class ReverseContourPointPen(AbstractPointPen):
|
| 437 |
+
"""
|
| 438 |
+
This is a PointPen that passes outline data to another PointPen, but
|
| 439 |
+
reversing the winding direction of all contours. Components are simply
|
| 440 |
+
passed through unchanged.
|
| 441 |
+
|
| 442 |
+
Closed contours are reversed in such a way that the first point remains
|
| 443 |
+
the first point.
|
| 444 |
+
"""
|
| 445 |
+
|
| 446 |
+
def __init__(self, outputPointPen):
|
| 447 |
+
self.pen = outputPointPen
|
| 448 |
+
# a place to store the points for the current sub path
|
| 449 |
+
self.currentContour = None
|
| 450 |
+
|
| 451 |
+
def _flushContour(self):
|
| 452 |
+
pen = self.pen
|
| 453 |
+
contour = self.currentContour
|
| 454 |
+
if not contour:
|
| 455 |
+
pen.beginPath(identifier=self.currentContourIdentifier)
|
| 456 |
+
pen.endPath()
|
| 457 |
+
return
|
| 458 |
+
|
| 459 |
+
closed = contour[0][1] != "move"
|
| 460 |
+
if not closed:
|
| 461 |
+
lastSegmentType = "move"
|
| 462 |
+
else:
|
| 463 |
+
# Remove the first point and insert it at the end. When
|
| 464 |
+
# the list of points gets reversed, this point will then
|
| 465 |
+
# again be at the start. In other words, the following
|
| 466 |
+
# will hold:
|
| 467 |
+
# for N in range(len(originalContour)):
|
| 468 |
+
# originalContour[N] == reversedContour[-N]
|
| 469 |
+
contour.append(contour.pop(0))
|
| 470 |
+
# Find the first on-curve point.
|
| 471 |
+
firstOnCurve = None
|
| 472 |
+
for i in range(len(contour)):
|
| 473 |
+
if contour[i][1] is not None:
|
| 474 |
+
firstOnCurve = i
|
| 475 |
+
break
|
| 476 |
+
if firstOnCurve is None:
|
| 477 |
+
# There are no on-curve points, be basically have to
|
| 478 |
+
# do nothing but contour.reverse().
|
| 479 |
+
lastSegmentType = None
|
| 480 |
+
else:
|
| 481 |
+
lastSegmentType = contour[firstOnCurve][1]
|
| 482 |
+
|
| 483 |
+
contour.reverse()
|
| 484 |
+
if not closed:
|
| 485 |
+
# Open paths must start with a move, so we simply dump
|
| 486 |
+
# all off-curve points leading up to the first on-curve.
|
| 487 |
+
while contour[0][1] is None:
|
| 488 |
+
contour.pop(0)
|
| 489 |
+
pen.beginPath(identifier=self.currentContourIdentifier)
|
| 490 |
+
for pt, nextSegmentType, smooth, name, kwargs in contour:
|
| 491 |
+
if nextSegmentType is not None:
|
| 492 |
+
segmentType = lastSegmentType
|
| 493 |
+
lastSegmentType = nextSegmentType
|
| 494 |
+
else:
|
| 495 |
+
segmentType = None
|
| 496 |
+
pen.addPoint(
|
| 497 |
+
pt, segmentType=segmentType, smooth=smooth, name=name, **kwargs
|
| 498 |
+
)
|
| 499 |
+
pen.endPath()
|
| 500 |
+
|
| 501 |
+
def beginPath(self, identifier=None, **kwargs):
|
| 502 |
+
if self.currentContour is not None:
|
| 503 |
+
raise PenError("Path already begun")
|
| 504 |
+
self.currentContour = []
|
| 505 |
+
self.currentContourIdentifier = identifier
|
| 506 |
+
self.onCurve = []
|
| 507 |
+
|
| 508 |
+
def endPath(self):
|
| 509 |
+
if self.currentContour is None:
|
| 510 |
+
raise PenError("Path not begun")
|
| 511 |
+
self._flushContour()
|
| 512 |
+
self.currentContour = None
|
| 513 |
+
|
| 514 |
+
def addPoint(
|
| 515 |
+
self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs
|
| 516 |
+
):
|
| 517 |
+
if self.currentContour is None:
|
| 518 |
+
raise PenError("Path not begun")
|
| 519 |
+
if identifier is not None:
|
| 520 |
+
kwargs["identifier"] = identifier
|
| 521 |
+
self.currentContour.append((pt, segmentType, smooth, name, kwargs))
|
| 522 |
+
|
| 523 |
+
def addComponent(self, glyphName, transform, identifier=None, **kwargs):
|
| 524 |
+
if self.currentContour is not None:
|
| 525 |
+
raise PenError("Components must be added before or after contours")
|
| 526 |
+
self.pen.addComponent(glyphName, transform, identifier=identifier, **kwargs)
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
class DecomposingPointPen(LogMixin, AbstractPointPen):
|
| 530 |
+
"""Implements a 'addComponent' method that decomposes components
|
| 531 |
+
(i.e. draws them onto self as simple contours).
|
| 532 |
+
It can also be used as a mixin class (e.g. see DecomposingRecordingPointPen).
|
| 533 |
+
|
| 534 |
+
You must override beginPath, addPoint, endPath. You may
|
| 535 |
+
additionally override addVarComponent and addComponent.
|
| 536 |
+
|
| 537 |
+
By default a warning message is logged when a base glyph is missing;
|
| 538 |
+
set the class variable ``skipMissingComponents`` to False if you want
|
| 539 |
+
all instances of a sub-class to raise a :class:`MissingComponentError`
|
| 540 |
+
exception by default.
|
| 541 |
+
"""
|
| 542 |
+
|
| 543 |
+
skipMissingComponents = True
|
| 544 |
+
# alias error for convenience
|
| 545 |
+
MissingComponentError = MissingComponentError
|
| 546 |
+
|
| 547 |
+
def __init__(
|
| 548 |
+
self,
|
| 549 |
+
glyphSet,
|
| 550 |
+
*args,
|
| 551 |
+
skipMissingComponents=None,
|
| 552 |
+
reverseFlipped=False,
|
| 553 |
+
**kwargs,
|
| 554 |
+
):
|
| 555 |
+
"""Takes a 'glyphSet' argument (dict), in which the glyphs that are referenced
|
| 556 |
+
as components are looked up by their name.
|
| 557 |
+
|
| 558 |
+
If the optional 'reverseFlipped' argument is True, components whose transformation
|
| 559 |
+
matrix has a negative determinant will be decomposed with a reversed path direction
|
| 560 |
+
to compensate for the flip.
|
| 561 |
+
|
| 562 |
+
The optional 'skipMissingComponents' argument can be set to True/False to
|
| 563 |
+
override the homonymous class attribute for a given pen instance.
|
| 564 |
+
"""
|
| 565 |
+
super().__init__(*args, **kwargs)
|
| 566 |
+
self.glyphSet = glyphSet
|
| 567 |
+
self.skipMissingComponents = (
|
| 568 |
+
self.__class__.skipMissingComponents
|
| 569 |
+
if skipMissingComponents is None
|
| 570 |
+
else skipMissingComponents
|
| 571 |
+
)
|
| 572 |
+
self.reverseFlipped = reverseFlipped
|
| 573 |
+
|
| 574 |
+
def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs):
|
| 575 |
+
"""Transform the points of the base glyph and draw it onto self.
|
| 576 |
+
|
| 577 |
+
The `identifier` parameter and any extra kwargs are ignored.
|
| 578 |
+
"""
|
| 579 |
+
from fontTools.pens.transformPen import TransformPointPen
|
| 580 |
+
|
| 581 |
+
try:
|
| 582 |
+
glyph = self.glyphSet[baseGlyphName]
|
| 583 |
+
except KeyError:
|
| 584 |
+
if not self.skipMissingComponents:
|
| 585 |
+
raise MissingComponentError(baseGlyphName)
|
| 586 |
+
self.log.warning(
|
| 587 |
+
"glyph '%s' is missing from glyphSet; skipped" % baseGlyphName
|
| 588 |
+
)
|
| 589 |
+
else:
|
| 590 |
+
pen = self
|
| 591 |
+
if transformation != Identity:
|
| 592 |
+
pen = TransformPointPen(pen, transformation)
|
| 593 |
+
if self.reverseFlipped:
|
| 594 |
+
# if the transformation has a negative determinant, it will
|
| 595 |
+
# reverse the contour direction of the component
|
| 596 |
+
a, b, c, d = transformation[:4]
|
| 597 |
+
det = a * d - b * c
|
| 598 |
+
if a * d - b * c < 0:
|
| 599 |
+
pen = ReverseContourPointPen(pen)
|
| 600 |
+
glyph.drawPoints(pen)
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/qtPen.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.pens.basePen import BasePen
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
__all__ = ["QtPen"]
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class QtPen(BasePen):
|
| 8 |
+
def __init__(self, glyphSet, path=None):
|
| 9 |
+
BasePen.__init__(self, glyphSet)
|
| 10 |
+
if path is None:
|
| 11 |
+
from PyQt5.QtGui import QPainterPath
|
| 12 |
+
|
| 13 |
+
path = QPainterPath()
|
| 14 |
+
self.path = path
|
| 15 |
+
|
| 16 |
+
def _moveTo(self, p):
|
| 17 |
+
self.path.moveTo(*p)
|
| 18 |
+
|
| 19 |
+
def _lineTo(self, p):
|
| 20 |
+
self.path.lineTo(*p)
|
| 21 |
+
|
| 22 |
+
def _curveToOne(self, p1, p2, p3):
|
| 23 |
+
self.path.cubicTo(*p1, *p2, *p3)
|
| 24 |
+
|
| 25 |
+
def _qCurveToOne(self, p1, p2):
|
| 26 |
+
self.path.quadTo(*p1, *p2)
|
| 27 |
+
|
| 28 |
+
def _closePath(self):
|
| 29 |
+
self.path.closeSubpath()
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/qu2cuPen.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2016 Google Inc. All Rights Reserved.
|
| 2 |
+
# Copyright 2023 Behdad Esfahbod. All Rights Reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from fontTools.qu2cu import quadratic_to_curves
|
| 17 |
+
from fontTools.pens.filterPen import ContourFilterPen
|
| 18 |
+
from fontTools.pens.reverseContourPen import ReverseContourPen
|
| 19 |
+
import math
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Qu2CuPen(ContourFilterPen):
|
| 23 |
+
"""A filter pen to convert quadratic bezier splines to cubic curves
|
| 24 |
+
using the FontTools SegmentPen protocol.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
|
| 28 |
+
other_pen: another SegmentPen used to draw the transformed outline.
|
| 29 |
+
max_err: maximum approximation error in font units. For optimal results,
|
| 30 |
+
if you know the UPEM of the font, we recommend setting this to a
|
| 31 |
+
value equal, or close to UPEM / 1000.
|
| 32 |
+
reverse_direction: flip the contours' direction but keep starting point.
|
| 33 |
+
stats: a dictionary counting the point numbers of cubic segments.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
other_pen,
|
| 39 |
+
max_err,
|
| 40 |
+
all_cubic=False,
|
| 41 |
+
reverse_direction=False,
|
| 42 |
+
stats=None,
|
| 43 |
+
):
|
| 44 |
+
if reverse_direction:
|
| 45 |
+
other_pen = ReverseContourPen(other_pen)
|
| 46 |
+
super().__init__(other_pen)
|
| 47 |
+
self.all_cubic = all_cubic
|
| 48 |
+
self.max_err = max_err
|
| 49 |
+
self.stats = stats
|
| 50 |
+
|
| 51 |
+
def _quadratics_to_curve(self, q):
|
| 52 |
+
curves = quadratic_to_curves(q, self.max_err, all_cubic=self.all_cubic)
|
| 53 |
+
if self.stats is not None:
|
| 54 |
+
for curve in curves:
|
| 55 |
+
n = str(len(curve) - 2)
|
| 56 |
+
self.stats[n] = self.stats.get(n, 0) + 1
|
| 57 |
+
for curve in curves:
|
| 58 |
+
if len(curve) == 4:
|
| 59 |
+
yield ("curveTo", curve[1:])
|
| 60 |
+
else:
|
| 61 |
+
yield ("qCurveTo", curve[1:])
|
| 62 |
+
|
| 63 |
+
def filterContour(self, contour):
|
| 64 |
+
quadratics = []
|
| 65 |
+
currentPt = None
|
| 66 |
+
newContour = []
|
| 67 |
+
for op, args in contour:
|
| 68 |
+
if op == "qCurveTo" and (
|
| 69 |
+
self.all_cubic or (len(args) > 2 and args[-1] is not None)
|
| 70 |
+
):
|
| 71 |
+
if args[-1] is None:
|
| 72 |
+
raise NotImplementedError(
|
| 73 |
+
"oncurve-less contours with all_cubic not implemented"
|
| 74 |
+
)
|
| 75 |
+
quadratics.append((currentPt,) + args)
|
| 76 |
+
else:
|
| 77 |
+
if quadratics:
|
| 78 |
+
newContour.extend(self._quadratics_to_curve(quadratics))
|
| 79 |
+
quadratics = []
|
| 80 |
+
newContour.append((op, args))
|
| 81 |
+
currentPt = args[-1] if args else None
|
| 82 |
+
if quadratics:
|
| 83 |
+
newContour.extend(self._quadratics_to_curve(quadratics))
|
| 84 |
+
|
| 85 |
+
if not self.all_cubic:
|
| 86 |
+
# Add back implicit oncurve points
|
| 87 |
+
contour = newContour
|
| 88 |
+
newContour = []
|
| 89 |
+
for op, args in contour:
|
| 90 |
+
if op == "qCurveTo" and newContour and newContour[-1][0] == "qCurveTo":
|
| 91 |
+
pt0 = newContour[-1][1][-2]
|
| 92 |
+
pt1 = newContour[-1][1][-1]
|
| 93 |
+
pt2 = args[0]
|
| 94 |
+
if (
|
| 95 |
+
pt1 is not None
|
| 96 |
+
and math.isclose(pt2[0] - pt1[0], pt1[0] - pt0[0])
|
| 97 |
+
and math.isclose(pt2[1] - pt1[1], pt1[1] - pt0[1])
|
| 98 |
+
):
|
| 99 |
+
newArgs = newContour[-1][1][:-1] + args
|
| 100 |
+
newContour[-1] = (op, newArgs)
|
| 101 |
+
continue
|
| 102 |
+
|
| 103 |
+
newContour.append((op, args))
|
| 104 |
+
|
| 105 |
+
return newContour
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/quartzPen.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.pens.basePen import BasePen
|
| 2 |
+
|
| 3 |
+
from Quartz.CoreGraphics import CGPathCreateMutable, CGPathMoveToPoint
|
| 4 |
+
from Quartz.CoreGraphics import CGPathAddLineToPoint, CGPathAddCurveToPoint
|
| 5 |
+
from Quartz.CoreGraphics import CGPathAddQuadCurveToPoint, CGPathCloseSubpath
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = ["QuartzPen"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class QuartzPen(BasePen):
|
| 12 |
+
"""A pen that creates a CGPath
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
- path: an optional CGPath to add to
|
| 16 |
+
- xform: an optional CGAffineTransform to apply to the path
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def __init__(self, glyphSet, path=None, xform=None):
|
| 20 |
+
BasePen.__init__(self, glyphSet)
|
| 21 |
+
if path is None:
|
| 22 |
+
path = CGPathCreateMutable()
|
| 23 |
+
self.path = path
|
| 24 |
+
self.xform = xform
|
| 25 |
+
|
| 26 |
+
def _moveTo(self, pt):
|
| 27 |
+
x, y = pt
|
| 28 |
+
CGPathMoveToPoint(self.path, self.xform, x, y)
|
| 29 |
+
|
| 30 |
+
def _lineTo(self, pt):
|
| 31 |
+
x, y = pt
|
| 32 |
+
CGPathAddLineToPoint(self.path, self.xform, x, y)
|
| 33 |
+
|
| 34 |
+
def _curveToOne(self, p1, p2, p3):
|
| 35 |
+
(x1, y1), (x2, y2), (x3, y3) = p1, p2, p3
|
| 36 |
+
CGPathAddCurveToPoint(self.path, self.xform, x1, y1, x2, y2, x3, y3)
|
| 37 |
+
|
| 38 |
+
def _qCurveToOne(self, p1, p2):
|
| 39 |
+
(x1, y1), (x2, y2) = p1, p2
|
| 40 |
+
CGPathAddQuadCurveToPoint(self.path, self.xform, x1, y1, x2, y2)
|
| 41 |
+
|
| 42 |
+
def _closePath(self):
|
| 43 |
+
CGPathCloseSubpath(self.path)
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/reportLabPen.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.pens.basePen import BasePen
|
| 2 |
+
from reportlab.graphics.shapes import Path
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
__all__ = ["ReportLabPen"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class ReportLabPen(BasePen):
|
| 9 |
+
"""A pen for drawing onto a ``reportlab.graphics.shapes.Path`` object."""
|
| 10 |
+
|
| 11 |
+
def __init__(self, glyphSet, path=None):
|
| 12 |
+
BasePen.__init__(self, glyphSet)
|
| 13 |
+
if path is None:
|
| 14 |
+
path = Path()
|
| 15 |
+
self.path = path
|
| 16 |
+
|
| 17 |
+
def _moveTo(self, p):
|
| 18 |
+
(x, y) = p
|
| 19 |
+
self.path.moveTo(x, y)
|
| 20 |
+
|
| 21 |
+
def _lineTo(self, p):
|
| 22 |
+
(x, y) = p
|
| 23 |
+
self.path.lineTo(x, y)
|
| 24 |
+
|
| 25 |
+
def _curveToOne(self, p1, p2, p3):
|
| 26 |
+
(x1, y1) = p1
|
| 27 |
+
(x2, y2) = p2
|
| 28 |
+
(x3, y3) = p3
|
| 29 |
+
self.path.curveTo(x1, y1, x2, y2, x3, y3)
|
| 30 |
+
|
| 31 |
+
def _closePath(self):
|
| 32 |
+
self.path.closePath()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if __name__ == "__main__":
|
| 36 |
+
import sys
|
| 37 |
+
|
| 38 |
+
if len(sys.argv) < 3:
|
| 39 |
+
print(
|
| 40 |
+
"Usage: reportLabPen.py <OTF/TTF font> <glyphname> [<image file to create>]"
|
| 41 |
+
)
|
| 42 |
+
print(
|
| 43 |
+
" If no image file name is created, by default <glyphname>.png is created."
|
| 44 |
+
)
|
| 45 |
+
print(" example: reportLabPen.py Arial.TTF R test.png")
|
| 46 |
+
print(
|
| 47 |
+
" (The file format will be PNG, regardless of the image file name supplied)"
|
| 48 |
+
)
|
| 49 |
+
sys.exit(0)
|
| 50 |
+
|
| 51 |
+
from fontTools.ttLib import TTFont
|
| 52 |
+
from reportlab.lib import colors
|
| 53 |
+
|
| 54 |
+
path = sys.argv[1]
|
| 55 |
+
glyphName = sys.argv[2]
|
| 56 |
+
if len(sys.argv) > 3:
|
| 57 |
+
imageFile = sys.argv[3]
|
| 58 |
+
else:
|
| 59 |
+
imageFile = "%s.png" % glyphName
|
| 60 |
+
|
| 61 |
+
font = TTFont(path) # it would work just as well with fontTools.t1Lib.T1Font
|
| 62 |
+
gs = font.getGlyphSet()
|
| 63 |
+
pen = ReportLabPen(gs, Path(fillColor=colors.red, strokeWidth=5))
|
| 64 |
+
g = gs[glyphName]
|
| 65 |
+
g.draw(pen)
|
| 66 |
+
|
| 67 |
+
w, h = g.width, 1000
|
| 68 |
+
from reportlab.graphics import renderPM
|
| 69 |
+
from reportlab.graphics.shapes import Group, Drawing, scale
|
| 70 |
+
|
| 71 |
+
# Everything is wrapped in a group to allow transformations.
|
| 72 |
+
g = Group(pen.path)
|
| 73 |
+
g.translate(0, 200)
|
| 74 |
+
g.scale(0.3, 0.3)
|
| 75 |
+
|
| 76 |
+
d = Drawing(w, h)
|
| 77 |
+
d.add(g)
|
| 78 |
+
|
| 79 |
+
renderPM.drawToFile(d, imageFile, fmt="PNG")
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/reverseContourPen.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.misc.arrayTools import pairwise
|
| 2 |
+
from fontTools.pens.filterPen import ContourFilterPen
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
__all__ = ["reversedContour", "ReverseContourPen"]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class ReverseContourPen(ContourFilterPen):
|
| 9 |
+
"""Filter pen that passes outline data to another pen, but reversing
|
| 10 |
+
the winding direction of all contours. Components are simply passed
|
| 11 |
+
through unchanged.
|
| 12 |
+
|
| 13 |
+
Closed contours are reversed in such a way that the first point remains
|
| 14 |
+
the first point.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self, outPen, outputImpliedClosingLine=False):
|
| 18 |
+
super().__init__(outPen)
|
| 19 |
+
self.outputImpliedClosingLine = outputImpliedClosingLine
|
| 20 |
+
|
| 21 |
+
def filterContour(self, contour):
|
| 22 |
+
return reversedContour(contour, self.outputImpliedClosingLine)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def reversedContour(contour, outputImpliedClosingLine=False):
|
| 26 |
+
"""Generator that takes a list of pen's (operator, operands) tuples,
|
| 27 |
+
and yields them with the winding direction reversed.
|
| 28 |
+
"""
|
| 29 |
+
if not contour:
|
| 30 |
+
return # nothing to do, stop iteration
|
| 31 |
+
|
| 32 |
+
# valid contours must have at least a starting and ending command,
|
| 33 |
+
# can't have one without the other
|
| 34 |
+
assert len(contour) > 1, "invalid contour"
|
| 35 |
+
|
| 36 |
+
# the type of the last command determines if the contour is closed
|
| 37 |
+
contourType = contour.pop()[0]
|
| 38 |
+
assert contourType in ("endPath", "closePath")
|
| 39 |
+
closed = contourType == "closePath"
|
| 40 |
+
|
| 41 |
+
firstType, firstPts = contour.pop(0)
|
| 42 |
+
assert firstType in ("moveTo", "qCurveTo"), (
|
| 43 |
+
"invalid initial segment type: %r" % firstType
|
| 44 |
+
)
|
| 45 |
+
firstOnCurve = firstPts[-1]
|
| 46 |
+
if firstType == "qCurveTo":
|
| 47 |
+
# special case for TrueType paths contaning only off-curve points
|
| 48 |
+
assert firstOnCurve is None, "off-curve only paths must end with 'None'"
|
| 49 |
+
assert not contour, "only one qCurveTo allowed per off-curve path"
|
| 50 |
+
firstPts = (firstPts[0],) + tuple(reversed(firstPts[1:-1])) + (None,)
|
| 51 |
+
|
| 52 |
+
if not contour:
|
| 53 |
+
# contour contains only one segment, nothing to reverse
|
| 54 |
+
if firstType == "moveTo":
|
| 55 |
+
closed = False # single-point paths can't be closed
|
| 56 |
+
else:
|
| 57 |
+
closed = True # off-curve paths are closed by definition
|
| 58 |
+
yield firstType, firstPts
|
| 59 |
+
else:
|
| 60 |
+
lastType, lastPts = contour[-1]
|
| 61 |
+
lastOnCurve = lastPts[-1]
|
| 62 |
+
if closed:
|
| 63 |
+
# for closed paths, we keep the starting point
|
| 64 |
+
yield firstType, firstPts
|
| 65 |
+
if firstOnCurve != lastOnCurve:
|
| 66 |
+
# emit an implied line between the last and first points
|
| 67 |
+
yield "lineTo", (lastOnCurve,)
|
| 68 |
+
contour[-1] = (lastType, tuple(lastPts[:-1]) + (firstOnCurve,))
|
| 69 |
+
|
| 70 |
+
if len(contour) > 1:
|
| 71 |
+
secondType, secondPts = contour[0]
|
| 72 |
+
else:
|
| 73 |
+
# contour has only two points, the second and last are the same
|
| 74 |
+
secondType, secondPts = lastType, lastPts
|
| 75 |
+
|
| 76 |
+
if not outputImpliedClosingLine:
|
| 77 |
+
# if a lineTo follows the initial moveTo, after reversing it
|
| 78 |
+
# will be implied by the closePath, so we don't emit one;
|
| 79 |
+
# unless the lineTo and moveTo overlap, in which case we keep the
|
| 80 |
+
# duplicate points
|
| 81 |
+
if secondType == "lineTo" and firstPts != secondPts:
|
| 82 |
+
del contour[0]
|
| 83 |
+
if contour:
|
| 84 |
+
contour[-1] = (lastType, tuple(lastPts[:-1]) + secondPts)
|
| 85 |
+
else:
|
| 86 |
+
# for open paths, the last point will become the first
|
| 87 |
+
yield firstType, (lastOnCurve,)
|
| 88 |
+
contour[-1] = (lastType, tuple(lastPts[:-1]) + (firstOnCurve,))
|
| 89 |
+
|
| 90 |
+
# we iterate over all segment pairs in reverse order, and yield
|
| 91 |
+
# each one with the off-curve points reversed (if any), and
|
| 92 |
+
# with the on-curve point of the following segment
|
| 93 |
+
for (curType, curPts), (_, nextPts) in pairwise(contour, reverse=True):
|
| 94 |
+
yield curType, tuple(reversed(curPts[:-1])) + (nextPts[-1],)
|
| 95 |
+
|
| 96 |
+
yield "closePath" if closed else "endPath", ()
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/roundingPen.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.misc.roundTools import noRound, otRound
|
| 2 |
+
from fontTools.misc.transform import Transform
|
| 3 |
+
from fontTools.pens.filterPen import FilterPen, FilterPointPen
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
__all__ = ["RoundingPen", "RoundingPointPen"]
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class RoundingPen(FilterPen):
|
| 10 |
+
"""
|
| 11 |
+
Filter pen that rounds point coordinates and component XY offsets to integer. For
|
| 12 |
+
rounding the component transform values, a separate round function can be passed to
|
| 13 |
+
the pen.
|
| 14 |
+
|
| 15 |
+
>>> from fontTools.pens.recordingPen import RecordingPen
|
| 16 |
+
>>> recpen = RecordingPen()
|
| 17 |
+
>>> roundpen = RoundingPen(recpen)
|
| 18 |
+
>>> roundpen.moveTo((0.4, 0.6))
|
| 19 |
+
>>> roundpen.lineTo((1.6, 2.5))
|
| 20 |
+
>>> roundpen.qCurveTo((2.4, 4.6), (3.3, 5.7), (4.9, 6.1))
|
| 21 |
+
>>> roundpen.curveTo((6.4, 8.6), (7.3, 9.7), (8.9, 10.1))
|
| 22 |
+
>>> roundpen.addComponent("a", (1.5, 0, 0, 1.5, 10.5, -10.5))
|
| 23 |
+
>>> recpen.value == [
|
| 24 |
+
... ('moveTo', ((0, 1),)),
|
| 25 |
+
... ('lineTo', ((2, 3),)),
|
| 26 |
+
... ('qCurveTo', ((2, 5), (3, 6), (5, 6))),
|
| 27 |
+
... ('curveTo', ((6, 9), (7, 10), (9, 10))),
|
| 28 |
+
... ('addComponent', ('a', (1.5, 0, 0, 1.5, 11, -10))),
|
| 29 |
+
... ]
|
| 30 |
+
True
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, outPen, roundFunc=otRound, transformRoundFunc=noRound):
|
| 34 |
+
super().__init__(outPen)
|
| 35 |
+
self.roundFunc = roundFunc
|
| 36 |
+
self.transformRoundFunc = transformRoundFunc
|
| 37 |
+
|
| 38 |
+
def moveTo(self, pt):
|
| 39 |
+
self._outPen.moveTo((self.roundFunc(pt[0]), self.roundFunc(pt[1])))
|
| 40 |
+
|
| 41 |
+
def lineTo(self, pt):
|
| 42 |
+
self._outPen.lineTo((self.roundFunc(pt[0]), self.roundFunc(pt[1])))
|
| 43 |
+
|
| 44 |
+
def curveTo(self, *points):
|
| 45 |
+
self._outPen.curveTo(
|
| 46 |
+
*((self.roundFunc(x), self.roundFunc(y)) for x, y in points)
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
def qCurveTo(self, *points):
|
| 50 |
+
self._outPen.qCurveTo(
|
| 51 |
+
*((self.roundFunc(x), self.roundFunc(y)) for x, y in points)
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
def addComponent(self, glyphName, transformation):
|
| 55 |
+
xx, xy, yx, yy, dx, dy = transformation
|
| 56 |
+
self._outPen.addComponent(
|
| 57 |
+
glyphName,
|
| 58 |
+
Transform(
|
| 59 |
+
self.transformRoundFunc(xx),
|
| 60 |
+
self.transformRoundFunc(xy),
|
| 61 |
+
self.transformRoundFunc(yx),
|
| 62 |
+
self.transformRoundFunc(yy),
|
| 63 |
+
self.roundFunc(dx),
|
| 64 |
+
self.roundFunc(dy),
|
| 65 |
+
),
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class RoundingPointPen(FilterPointPen):
|
| 70 |
+
"""
|
| 71 |
+
Filter point pen that rounds point coordinates and component XY offsets to integer.
|
| 72 |
+
For rounding the component scale values, a separate round function can be passed to
|
| 73 |
+
the pen.
|
| 74 |
+
|
| 75 |
+
>>> from fontTools.pens.recordingPen import RecordingPointPen
|
| 76 |
+
>>> recpen = RecordingPointPen()
|
| 77 |
+
>>> roundpen = RoundingPointPen(recpen)
|
| 78 |
+
>>> roundpen.beginPath()
|
| 79 |
+
>>> roundpen.addPoint((0.4, 0.6), 'line')
|
| 80 |
+
>>> roundpen.addPoint((1.6, 2.5), 'line')
|
| 81 |
+
>>> roundpen.addPoint((2.4, 4.6))
|
| 82 |
+
>>> roundpen.addPoint((3.3, 5.7))
|
| 83 |
+
>>> roundpen.addPoint((4.9, 6.1), 'qcurve')
|
| 84 |
+
>>> roundpen.endPath()
|
| 85 |
+
>>> roundpen.addComponent("a", (1.5, 0, 0, 1.5, 10.5, -10.5))
|
| 86 |
+
>>> recpen.value == [
|
| 87 |
+
... ('beginPath', (), {}),
|
| 88 |
+
... ('addPoint', ((0, 1), 'line', False, None), {}),
|
| 89 |
+
... ('addPoint', ((2, 3), 'line', False, None), {}),
|
| 90 |
+
... ('addPoint', ((2, 5), None, False, None), {}),
|
| 91 |
+
... ('addPoint', ((3, 6), None, False, None), {}),
|
| 92 |
+
... ('addPoint', ((5, 6), 'qcurve', False, None), {}),
|
| 93 |
+
... ('endPath', (), {}),
|
| 94 |
+
... ('addComponent', ('a', (1.5, 0, 0, 1.5, 11, -10)), {}),
|
| 95 |
+
... ]
|
| 96 |
+
True
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
def __init__(self, outPen, roundFunc=otRound, transformRoundFunc=noRound):
|
| 100 |
+
super().__init__(outPen)
|
| 101 |
+
self.roundFunc = roundFunc
|
| 102 |
+
self.transformRoundFunc = transformRoundFunc
|
| 103 |
+
|
| 104 |
+
def addPoint(
|
| 105 |
+
self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs
|
| 106 |
+
):
|
| 107 |
+
self._outPen.addPoint(
|
| 108 |
+
(self.roundFunc(pt[0]), self.roundFunc(pt[1])),
|
| 109 |
+
segmentType=segmentType,
|
| 110 |
+
smooth=smooth,
|
| 111 |
+
name=name,
|
| 112 |
+
identifier=identifier,
|
| 113 |
+
**kwargs,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs):
|
| 117 |
+
xx, xy, yx, yy, dx, dy = transformation
|
| 118 |
+
self._outPen.addComponent(
|
| 119 |
+
baseGlyphName=baseGlyphName,
|
| 120 |
+
transformation=Transform(
|
| 121 |
+
self.transformRoundFunc(xx),
|
| 122 |
+
self.transformRoundFunc(xy),
|
| 123 |
+
self.transformRoundFunc(yx),
|
| 124 |
+
self.transformRoundFunc(yy),
|
| 125 |
+
self.roundFunc(dx),
|
| 126 |
+
self.roundFunc(dy),
|
| 127 |
+
),
|
| 128 |
+
identifier=identifier,
|
| 129 |
+
**kwargs,
|
| 130 |
+
)
|
infer_4_47_1/lib/python3.10/site-packages/fontTools/pens/statisticsPen.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pen calculating area, center of mass, variance and standard-deviation,
|
| 2 |
+
covariance and correlation, and slant, of glyph shapes."""
|
| 3 |
+
|
| 4 |
+
from math import sqrt, degrees, atan
|
| 5 |
+
from fontTools.pens.basePen import BasePen, OpenContourError
|
| 6 |
+
from fontTools.pens.momentsPen import MomentsPen
|
| 7 |
+
|
| 8 |
+
__all__ = ["StatisticsPen", "StatisticsControlPen"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class StatisticsBase:
|
| 12 |
+
def __init__(self):
|
| 13 |
+
self._zero()
|
| 14 |
+
|
| 15 |
+
def _zero(self):
|
| 16 |
+
self.area = 0
|
| 17 |
+
self.meanX = 0
|
| 18 |
+
self.meanY = 0
|
| 19 |
+
self.varianceX = 0
|
| 20 |
+
self.varianceY = 0
|
| 21 |
+
self.stddevX = 0
|
| 22 |
+
self.stddevY = 0
|
| 23 |
+
self.covariance = 0
|
| 24 |
+
self.correlation = 0
|
| 25 |
+
self.slant = 0
|
| 26 |
+
|
| 27 |
+
def _update(self):
|
| 28 |
+
# XXX The variance formulas should never produce a negative value,
|
| 29 |
+
# but due to reasons I don't understand, both of our pens do.
|
| 30 |
+
# So we take the absolute value here.
|
| 31 |
+
self.varianceX = abs(self.varianceX)
|
| 32 |
+
self.varianceY = abs(self.varianceY)
|
| 33 |
+
|
| 34 |
+
self.stddevX = stddevX = sqrt(self.varianceX)
|
| 35 |
+
self.stddevY = stddevY = sqrt(self.varianceY)
|
| 36 |
+
|
| 37 |
+
# Correlation(X,Y) = Covariance(X,Y) / ( stddev(X) * stddev(Y) )
|
| 38 |
+
# https://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient
|
| 39 |
+
if stddevX * stddevY == 0:
|
| 40 |
+
correlation = float("NaN")
|
| 41 |
+
else:
|
| 42 |
+
# XXX The above formula should never produce a value outside
|
| 43 |
+
# the range [-1, 1], but due to reasons I don't understand,
|
| 44 |
+
# (probably the same issue as above), it does. So we clamp.
|
| 45 |
+
correlation = self.covariance / (stddevX * stddevY)
|
| 46 |
+
correlation = max(-1, min(1, correlation))
|
| 47 |
+
self.correlation = correlation if abs(correlation) > 1e-3 else 0
|
| 48 |
+
|
| 49 |
+
slant = (
|
| 50 |
+
self.covariance / self.varianceY if self.varianceY != 0 else float("NaN")
|
| 51 |
+
)
|
| 52 |
+
self.slant = slant if abs(slant) > 1e-3 else 0
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class StatisticsPen(StatisticsBase, MomentsPen):
|
| 56 |
+
"""Pen calculating area, center of mass, variance and
|
| 57 |
+
standard-deviation, covariance and correlation, and slant,
|
| 58 |
+
of glyph shapes.
|
| 59 |
+
|
| 60 |
+
Note that if the glyph shape is self-intersecting, the values
|
| 61 |
+
are not correct (but well-defined). Moreover, area will be
|
| 62 |
+
negative if contour directions are clockwise."""
|
| 63 |
+
|
| 64 |
+
def __init__(self, glyphset=None):
|
| 65 |
+
MomentsPen.__init__(self, glyphset=glyphset)
|
| 66 |
+
StatisticsBase.__init__(self)
|
| 67 |
+
|
| 68 |
+
def _closePath(self):
|
| 69 |
+
MomentsPen._closePath(self)
|
| 70 |
+
self._update()
|
| 71 |
+
|
| 72 |
+
def _update(self):
|
| 73 |
+
area = self.area
|
| 74 |
+
if not area:
|
| 75 |
+
self._zero()
|
| 76 |
+
return
|
| 77 |
+
|
| 78 |
+
# Center of mass
|
| 79 |
+
# https://en.wikipedia.org/wiki/Center_of_mass#A_continuous_volume
|
| 80 |
+
self.meanX = meanX = self.momentX / area
|
| 81 |
+
self.meanY = meanY = self.momentY / area
|
| 82 |
+
|
| 83 |
+
# Var(X) = E[X^2] - E[X]^2
|
| 84 |
+
self.varianceX = self.momentXX / area - meanX * meanX
|
| 85 |
+
self.varianceY = self.momentYY / area - meanY * meanY
|
| 86 |
+
|
| 87 |
+
# Covariance(X,Y) = (E[X.Y] - E[X]E[Y])
|
| 88 |
+
self.covariance = self.momentXY / area - meanX * meanY
|
| 89 |
+
|
| 90 |
+
StatisticsBase._update(self)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class StatisticsControlPen(StatisticsBase, BasePen):
|
| 94 |
+
"""Pen calculating area, center of mass, variance and
|
| 95 |
+
standard-deviation, covariance and correlation, and slant,
|
| 96 |
+
of glyph shapes, using the control polygon only.
|
| 97 |
+
|
| 98 |
+
Note that if the glyph shape is self-intersecting, the values
|
| 99 |
+
are not correct (but well-defined). Moreover, area will be
|
| 100 |
+
negative if contour directions are clockwise."""
|
| 101 |
+
|
| 102 |
+
def __init__(self, glyphset=None):
|
| 103 |
+
BasePen.__init__(self, glyphset)
|
| 104 |
+
StatisticsBase.__init__(self)
|
| 105 |
+
self._nodes = []
|
| 106 |
+
|
| 107 |
+
def _moveTo(self, pt):
|
| 108 |
+
self._nodes.append(complex(*pt))
|
| 109 |
+
|
| 110 |
+
def _lineTo(self, pt):
|
| 111 |
+
self._nodes.append(complex(*pt))
|
| 112 |
+
|
| 113 |
+
def _qCurveToOne(self, pt1, pt2):
|
| 114 |
+
for pt in (pt1, pt2):
|
| 115 |
+
self._nodes.append(complex(*pt))
|
| 116 |
+
|
| 117 |
+
def _curveToOne(self, pt1, pt2, pt3):
|
| 118 |
+
for pt in (pt1, pt2, pt3):
|
| 119 |
+
self._nodes.append(complex(*pt))
|
| 120 |
+
|
| 121 |
+
def _closePath(self):
|
| 122 |
+
self._update()
|
| 123 |
+
|
| 124 |
+
def _endPath(self):
|
| 125 |
+
p0 = self._getCurrentPoint()
|
| 126 |
+
if p0 != self._startPoint:
|
| 127 |
+
raise OpenContourError("Glyph statistics not defined on open contours.")
|
| 128 |
+
|
| 129 |
+
def _update(self):
|
| 130 |
+
nodes = self._nodes
|
| 131 |
+
n = len(nodes)
|
| 132 |
+
|
| 133 |
+
# Triangle formula
|
| 134 |
+
self.area = (
|
| 135 |
+
sum(
|
| 136 |
+
(p0.real * p1.imag - p1.real * p0.imag)
|
| 137 |
+
for p0, p1 in zip(nodes, nodes[1:] + nodes[:1])
|
| 138 |
+
)
|
| 139 |
+
/ 2
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
# Center of mass
|
| 143 |
+
# https://en.wikipedia.org/wiki/Center_of_mass#A_system_of_particles
|
| 144 |
+
sumNodes = sum(nodes)
|
| 145 |
+
self.meanX = meanX = sumNodes.real / n
|
| 146 |
+
self.meanY = meanY = sumNodes.imag / n
|
| 147 |
+
|
| 148 |
+
if n > 1:
|
| 149 |
+
# Var(X) = (sum[X^2] - sum[X]^2 / n) / (n - 1)
|
| 150 |
+
# https://www.statisticshowto.com/probability-and-statistics/descriptive-statistics/sample-variance/
|
| 151 |
+
self.varianceX = varianceX = (
|
| 152 |
+
sum(p.real * p.real for p in nodes)
|
| 153 |
+
- (sumNodes.real * sumNodes.real) / n
|
| 154 |
+
) / (n - 1)
|
| 155 |
+
self.varianceY = varianceY = (
|
| 156 |
+
sum(p.imag * p.imag for p in nodes)
|
| 157 |
+
- (sumNodes.imag * sumNodes.imag) / n
|
| 158 |
+
) / (n - 1)
|
| 159 |
+
|
| 160 |
+
# Covariance(X,Y) = (sum[X.Y] - sum[X].sum[Y] / n) / (n - 1)
|
| 161 |
+
self.covariance = covariance = (
|
| 162 |
+
sum(p.real * p.imag for p in nodes)
|
| 163 |
+
- (sumNodes.real * sumNodes.imag) / n
|
| 164 |
+
) / (n - 1)
|
| 165 |
+
else:
|
| 166 |
+
self.varianceX = varianceX = 0
|
| 167 |
+
self.varianceY = varianceY = 0
|
| 168 |
+
self.covariance = covariance = 0
|
| 169 |
+
|
| 170 |
+
StatisticsBase._update(self)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _test(glyphset, upem, glyphs, quiet=False, *, control=False):
|
| 174 |
+
from fontTools.pens.transformPen import TransformPen
|
| 175 |
+
from fontTools.misc.transform import Scale
|
| 176 |
+
|
| 177 |
+
wght_sum = 0
|
| 178 |
+
wght_sum_perceptual = 0
|
| 179 |
+
wdth_sum = 0
|
| 180 |
+
slnt_sum = 0
|
| 181 |
+
slnt_sum_perceptual = 0
|
| 182 |
+
for glyph_name in glyphs:
|
| 183 |
+
glyph = glyphset[glyph_name]
|
| 184 |
+
if control:
|
| 185 |
+
pen = StatisticsControlPen(glyphset=glyphset)
|
| 186 |
+
else:
|
| 187 |
+
pen = StatisticsPen(glyphset=glyphset)
|
| 188 |
+
transformer = TransformPen(pen, Scale(1.0 / upem))
|
| 189 |
+
glyph.draw(transformer)
|
| 190 |
+
|
| 191 |
+
area = abs(pen.area)
|
| 192 |
+
width = glyph.width
|
| 193 |
+
wght_sum += area
|
| 194 |
+
wght_sum_perceptual += pen.area * width
|
| 195 |
+
wdth_sum += width
|
| 196 |
+
slnt_sum += pen.slant
|
| 197 |
+
slnt_sum_perceptual += pen.slant * width
|
| 198 |
+
|
| 199 |
+
if quiet:
|
| 200 |
+
continue
|
| 201 |
+
|
| 202 |
+
print()
|
| 203 |
+
print("glyph:", glyph_name)
|
| 204 |
+
|
| 205 |
+
for item in [
|
| 206 |
+
"area",
|
| 207 |
+
"momentX",
|
| 208 |
+
"momentY",
|
| 209 |
+
"momentXX",
|
| 210 |
+
"momentYY",
|
| 211 |
+
"momentXY",
|
| 212 |
+
"meanX",
|
| 213 |
+
"meanY",
|
| 214 |
+
"varianceX",
|
| 215 |
+
"varianceY",
|
| 216 |
+
"stddevX",
|
| 217 |
+
"stddevY",
|
| 218 |
+
"covariance",
|
| 219 |
+
"correlation",
|
| 220 |
+
"slant",
|
| 221 |
+
]:
|
| 222 |
+
print("%s: %g" % (item, getattr(pen, item)))
|
| 223 |
+
|
| 224 |
+
if not quiet:
|
| 225 |
+
print()
|
| 226 |
+
print("font:")
|
| 227 |
+
|
| 228 |
+
print("weight: %g" % (wght_sum * upem / wdth_sum))
|
| 229 |
+
print("weight (perceptual): %g" % (wght_sum_perceptual / wdth_sum))
|
| 230 |
+
print("width: %g" % (wdth_sum / upem / len(glyphs)))
|
| 231 |
+
slant = slnt_sum / len(glyphs)
|
| 232 |
+
print("slant: %g" % slant)
|
| 233 |
+
print("slant angle: %g" % -degrees(atan(slant)))
|
| 234 |
+
slant_perceptual = slnt_sum_perceptual / wdth_sum
|
| 235 |
+
print("slant (perceptual): %g" % slant_perceptual)
|
| 236 |
+
print("slant (perceptual) angle: %g" % -degrees(atan(slant_perceptual)))
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def main(args):
|
| 240 |
+
"""Report font glyph shape geometricsl statistics"""
|
| 241 |
+
|
| 242 |
+
if args is None:
|
| 243 |
+
import sys
|
| 244 |
+
|
| 245 |
+
args = sys.argv[1:]
|
| 246 |
+
|
| 247 |
+
import argparse
|
| 248 |
+
|
| 249 |
+
parser = argparse.ArgumentParser(
|
| 250 |
+
"fonttools pens.statisticsPen",
|
| 251 |
+
description="Report font glyph shape geometricsl statistics",
|
| 252 |
+
)
|
| 253 |
+
parser.add_argument("font", metavar="font.ttf", help="Font file.")
|
| 254 |
+
parser.add_argument("glyphs", metavar="glyph-name", help="Glyph names.", nargs="*")
|
| 255 |
+
parser.add_argument(
|
| 256 |
+
"-y",
|
| 257 |
+
metavar="<number>",
|
| 258 |
+
help="Face index into a collection to open. Zero based.",
|
| 259 |
+
)
|
| 260 |
+
parser.add_argument(
|
| 261 |
+
"-c",
|
| 262 |
+
"--control",
|
| 263 |
+
action="store_true",
|
| 264 |
+
help="Use the control-box pen instead of the Green therem.",
|
| 265 |
+
)
|
| 266 |
+
parser.add_argument(
|
| 267 |
+
"-q", "--quiet", action="store_true", help="Only report font-wide statistics."
|
| 268 |
+
)
|
| 269 |
+
parser.add_argument(
|
| 270 |
+
"--variations",
|
| 271 |
+
metavar="AXIS=LOC",
|
| 272 |
+
default="",
|
| 273 |
+
help="List of space separated locations. A location consist in "
|
| 274 |
+
"the name of a variation axis, followed by '=' and a number. E.g.: "
|
| 275 |
+
"wght=700 wdth=80. The default is the location of the base master.",
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
options = parser.parse_args(args)
|
| 279 |
+
|
| 280 |
+
glyphs = options.glyphs
|
| 281 |
+
fontNumber = int(options.y) if options.y is not None else 0
|
| 282 |
+
|
| 283 |
+
location = {}
|
| 284 |
+
for tag_v in options.variations.split():
|
| 285 |
+
fields = tag_v.split("=")
|
| 286 |
+
tag = fields[0].strip()
|
| 287 |
+
v = int(fields[1])
|
| 288 |
+
location[tag] = v
|
| 289 |
+
|
| 290 |
+
from fontTools.ttLib import TTFont
|
| 291 |
+
|
| 292 |
+
font = TTFont(options.font, fontNumber=fontNumber)
|
| 293 |
+
if not glyphs:
|
| 294 |
+
glyphs = font.getGlyphOrder()
|
| 295 |
+
_test(
|
| 296 |
+
font.getGlyphSet(location=location),
|
| 297 |
+
font["head"].unitsPerEm,
|
| 298 |
+
glyphs,
|
| 299 |
+
quiet=options.quiet,
|
| 300 |
+
control=options.control,
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
if __name__ == "__main__":
|
| 305 |
+
import sys
|
| 306 |
+
|
| 307 |
+
main(sys.argv[1:])
|