Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__init__.py +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/__init__.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/builder.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/errors.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/geometry.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/table_builder.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/unbuilder.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/builder.py +664 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/errors.py +2 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/geometry.py +143 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/table_builder.py +223 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/unbuilder.py +81 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/config/__init__.py +75 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/config/__pycache__/__init__.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/__init__.py +1 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/basePen.py +475 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/cu2quPen.py +325 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/filterPen.py +241 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/hashPointPen.py +89 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/qtPen.py +29 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/qu2cuPen.py +105 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/quartzPen.py +43 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/statisticsPen.py +307 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/svgPathPen.py +310 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/ttGlyphPen.py +335 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/wxPen.py +29 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/C_B_D_T_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/C_B_L_C_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/D_S_I_G_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/D__e_b_g.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/DefaultTable.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/E_B_D_T_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/F_F_T_M_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/G_M_A_P_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/G_P_K_G_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/G__l_a_t.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/H_V_A_R_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/M_E_T_A_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/S_I_N_G_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/S_T_A_T_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/S_V_G_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/S__i_l_f.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_B_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_D_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_V_.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__0.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__1.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__2.cpython-310.pyc +0 -0
- mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/V_A_R_C_.cpython-310.pyc +0 -0
mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__init__.py
ADDED
|
File without changes
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (178 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/builder.cpython-310.pyc
ADDED
|
Binary file (19 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/errors.cpython-310.pyc
ADDED
|
Binary file (346 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/geometry.cpython-310.pyc
ADDED
|
Binary file (3.66 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/table_builder.cpython-310.pyc
ADDED
|
Binary file (6.16 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/unbuilder.cpython-310.pyc
ADDED
|
Binary file (2.58 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/builder.py
ADDED
|
@@ -0,0 +1,664 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/errors.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class ColorLibError(Exception):
|
| 2 |
+
pass
|
mantis_evalkit/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
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/table_builder.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
colorLib.table_builder: Generic helper for filling in BaseTable derivatives from tuples and maps and such.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import collections
|
| 7 |
+
import enum
|
| 8 |
+
from fontTools.ttLib.tables.otBase import (
|
| 9 |
+
BaseTable,
|
| 10 |
+
FormatSwitchingBaseTable,
|
| 11 |
+
UInt8FormatSwitchingBaseTable,
|
| 12 |
+
)
|
| 13 |
+
from fontTools.ttLib.tables.otConverters import (
|
| 14 |
+
ComputedInt,
|
| 15 |
+
SimpleValue,
|
| 16 |
+
Struct,
|
| 17 |
+
Short,
|
| 18 |
+
UInt8,
|
| 19 |
+
UShort,
|
| 20 |
+
IntValue,
|
| 21 |
+
FloatValue,
|
| 22 |
+
OptionalValue,
|
| 23 |
+
)
|
| 24 |
+
from fontTools.misc.roundTools import otRound
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class BuildCallback(enum.Enum):
|
| 28 |
+
"""Keyed on (BEFORE_BUILD, class[, Format if available]).
|
| 29 |
+
Receives (dest, source).
|
| 30 |
+
Should return (dest, source), which can be new objects.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
BEFORE_BUILD = enum.auto()
|
| 34 |
+
|
| 35 |
+
"""Keyed on (AFTER_BUILD, class[, Format if available]).
|
| 36 |
+
Receives (dest).
|
| 37 |
+
Should return dest, which can be a new object.
|
| 38 |
+
"""
|
| 39 |
+
AFTER_BUILD = enum.auto()
|
| 40 |
+
|
| 41 |
+
"""Keyed on (CREATE_DEFAULT, class[, Format if available]).
|
| 42 |
+
Receives no arguments.
|
| 43 |
+
Should return a new instance of class.
|
| 44 |
+
"""
|
| 45 |
+
CREATE_DEFAULT = enum.auto()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _assignable(convertersByName):
|
| 49 |
+
return {k: v for k, v in convertersByName.items() if not isinstance(v, ComputedInt)}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _isNonStrSequence(value):
|
| 53 |
+
return isinstance(value, collections.abc.Sequence) and not isinstance(value, str)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _split_format(cls, source):
|
| 57 |
+
if _isNonStrSequence(source):
|
| 58 |
+
assert len(source) > 0, f"{cls} needs at least format from {source}"
|
| 59 |
+
fmt, remainder = source[0], source[1:]
|
| 60 |
+
elif isinstance(source, collections.abc.Mapping):
|
| 61 |
+
assert "Format" in source, f"{cls} needs at least Format from {source}"
|
| 62 |
+
remainder = source.copy()
|
| 63 |
+
fmt = remainder.pop("Format")
|
| 64 |
+
else:
|
| 65 |
+
raise ValueError(f"Not sure how to populate {cls} from {source}")
|
| 66 |
+
|
| 67 |
+
assert isinstance(
|
| 68 |
+
fmt, collections.abc.Hashable
|
| 69 |
+
), f"{cls} Format is not hashable: {fmt!r}"
|
| 70 |
+
assert fmt in cls.convertersByName, f"{cls} invalid Format: {fmt!r}"
|
| 71 |
+
|
| 72 |
+
return fmt, remainder
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class TableBuilder:
|
| 76 |
+
"""
|
| 77 |
+
Helps to populate things derived from BaseTable from maps, tuples, etc.
|
| 78 |
+
|
| 79 |
+
A table of lifecycle callbacks may be provided to add logic beyond what is possible
|
| 80 |
+
based on otData info for the target class. See BuildCallbacks.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
def __init__(self, callbackTable=None):
|
| 84 |
+
if callbackTable is None:
|
| 85 |
+
callbackTable = {}
|
| 86 |
+
self._callbackTable = callbackTable
|
| 87 |
+
|
| 88 |
+
def _convert(self, dest, field, converter, value):
|
| 89 |
+
enumClass = getattr(converter, "enumClass", None)
|
| 90 |
+
|
| 91 |
+
if enumClass:
|
| 92 |
+
if isinstance(value, enumClass):
|
| 93 |
+
pass
|
| 94 |
+
elif isinstance(value, str):
|
| 95 |
+
try:
|
| 96 |
+
value = getattr(enumClass, value.upper())
|
| 97 |
+
except AttributeError:
|
| 98 |
+
raise ValueError(f"{value} is not a valid {enumClass}")
|
| 99 |
+
else:
|
| 100 |
+
value = enumClass(value)
|
| 101 |
+
|
| 102 |
+
elif isinstance(converter, IntValue):
|
| 103 |
+
value = otRound(value)
|
| 104 |
+
elif isinstance(converter, FloatValue):
|
| 105 |
+
value = float(value)
|
| 106 |
+
|
| 107 |
+
elif isinstance(converter, Struct):
|
| 108 |
+
if converter.repeat:
|
| 109 |
+
if _isNonStrSequence(value):
|
| 110 |
+
value = [self.build(converter.tableClass, v) for v in value]
|
| 111 |
+
else:
|
| 112 |
+
value = [self.build(converter.tableClass, value)]
|
| 113 |
+
setattr(dest, converter.repeat, len(value))
|
| 114 |
+
else:
|
| 115 |
+
value = self.build(converter.tableClass, value)
|
| 116 |
+
elif callable(converter):
|
| 117 |
+
value = converter(value)
|
| 118 |
+
|
| 119 |
+
setattr(dest, field, value)
|
| 120 |
+
|
| 121 |
+
def build(self, cls, source):
|
| 122 |
+
assert issubclass(cls, BaseTable)
|
| 123 |
+
|
| 124 |
+
if isinstance(source, cls):
|
| 125 |
+
return source
|
| 126 |
+
|
| 127 |
+
callbackKey = (cls,)
|
| 128 |
+
fmt = None
|
| 129 |
+
if issubclass(cls, FormatSwitchingBaseTable):
|
| 130 |
+
fmt, source = _split_format(cls, source)
|
| 131 |
+
callbackKey = (cls, fmt)
|
| 132 |
+
|
| 133 |
+
dest = self._callbackTable.get(
|
| 134 |
+
(BuildCallback.CREATE_DEFAULT,) + callbackKey, lambda: cls()
|
| 135 |
+
)()
|
| 136 |
+
assert isinstance(dest, cls)
|
| 137 |
+
|
| 138 |
+
convByName = _assignable(cls.convertersByName)
|
| 139 |
+
skippedFields = set()
|
| 140 |
+
|
| 141 |
+
# For format switchers we need to resolve converters based on format
|
| 142 |
+
if issubclass(cls, FormatSwitchingBaseTable):
|
| 143 |
+
dest.Format = fmt
|
| 144 |
+
convByName = _assignable(convByName[dest.Format])
|
| 145 |
+
skippedFields.add("Format")
|
| 146 |
+
|
| 147 |
+
# Convert sequence => mapping so before thunk only has to handle one format
|
| 148 |
+
if _isNonStrSequence(source):
|
| 149 |
+
# Sequence (typically list or tuple) assumed to match fields in declaration order
|
| 150 |
+
assert len(source) <= len(
|
| 151 |
+
convByName
|
| 152 |
+
), f"Sequence of {len(source)} too long for {cls}; expected <= {len(convByName)} values"
|
| 153 |
+
source = dict(zip(convByName.keys(), source))
|
| 154 |
+
|
| 155 |
+
dest, source = self._callbackTable.get(
|
| 156 |
+
(BuildCallback.BEFORE_BUILD,) + callbackKey, lambda d, s: (d, s)
|
| 157 |
+
)(dest, source)
|
| 158 |
+
|
| 159 |
+
if isinstance(source, collections.abc.Mapping):
|
| 160 |
+
for field, value in source.items():
|
| 161 |
+
if field in skippedFields:
|
| 162 |
+
continue
|
| 163 |
+
converter = convByName.get(field, None)
|
| 164 |
+
if not converter:
|
| 165 |
+
raise ValueError(
|
| 166 |
+
f"Unrecognized field {field} for {cls}; expected one of {sorted(convByName.keys())}"
|
| 167 |
+
)
|
| 168 |
+
self._convert(dest, field, converter, value)
|
| 169 |
+
else:
|
| 170 |
+
# let's try as a 1-tuple
|
| 171 |
+
dest = self.build(cls, (source,))
|
| 172 |
+
|
| 173 |
+
for field, conv in convByName.items():
|
| 174 |
+
if not hasattr(dest, field) and isinstance(conv, OptionalValue):
|
| 175 |
+
setattr(dest, field, conv.DEFAULT)
|
| 176 |
+
|
| 177 |
+
dest = self._callbackTable.get(
|
| 178 |
+
(BuildCallback.AFTER_BUILD,) + callbackKey, lambda d: d
|
| 179 |
+
)(dest)
|
| 180 |
+
|
| 181 |
+
return dest
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class TableUnbuilder:
|
| 185 |
+
def __init__(self, callbackTable=None):
|
| 186 |
+
if callbackTable is None:
|
| 187 |
+
callbackTable = {}
|
| 188 |
+
self._callbackTable = callbackTable
|
| 189 |
+
|
| 190 |
+
def unbuild(self, table):
|
| 191 |
+
assert isinstance(table, BaseTable)
|
| 192 |
+
|
| 193 |
+
source = {}
|
| 194 |
+
|
| 195 |
+
callbackKey = (type(table),)
|
| 196 |
+
if isinstance(table, FormatSwitchingBaseTable):
|
| 197 |
+
source["Format"] = int(table.Format)
|
| 198 |
+
callbackKey += (table.Format,)
|
| 199 |
+
|
| 200 |
+
for converter in table.getConverters():
|
| 201 |
+
if isinstance(converter, ComputedInt):
|
| 202 |
+
continue
|
| 203 |
+
value = getattr(table, converter.name)
|
| 204 |
+
|
| 205 |
+
enumClass = getattr(converter, "enumClass", None)
|
| 206 |
+
if enumClass:
|
| 207 |
+
source[converter.name] = value.name.lower()
|
| 208 |
+
elif isinstance(converter, Struct):
|
| 209 |
+
if converter.repeat:
|
| 210 |
+
source[converter.name] = [self.unbuild(v) for v in value]
|
| 211 |
+
else:
|
| 212 |
+
source[converter.name] = self.unbuild(value)
|
| 213 |
+
elif isinstance(converter, SimpleValue):
|
| 214 |
+
# "simple" values (e.g. int, float, str) need no further un-building
|
| 215 |
+
source[converter.name] = value
|
| 216 |
+
else:
|
| 217 |
+
raise NotImplementedError(
|
| 218 |
+
"Don't know how unbuild {value!r} with {converter!r}"
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
source = self._callbackTable.get(callbackKey, lambda s: s)(source)
|
| 222 |
+
|
| 223 |
+
return source
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/colorLib/unbuilder.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.ttLib.tables import otTables as ot
|
| 2 |
+
from .table_builder import TableUnbuilder
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def unbuildColrV1(layerList, baseGlyphList):
|
| 6 |
+
layers = []
|
| 7 |
+
if layerList:
|
| 8 |
+
layers = layerList.Paint
|
| 9 |
+
unbuilder = LayerListUnbuilder(layers)
|
| 10 |
+
return {
|
| 11 |
+
rec.BaseGlyph: unbuilder.unbuildPaint(rec.Paint)
|
| 12 |
+
for rec in baseGlyphList.BaseGlyphPaintRecord
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _flatten_layers(lst):
|
| 17 |
+
for paint in lst:
|
| 18 |
+
if paint["Format"] == ot.PaintFormat.PaintColrLayers:
|
| 19 |
+
yield from _flatten_layers(paint["Layers"])
|
| 20 |
+
else:
|
| 21 |
+
yield paint
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class LayerListUnbuilder:
|
| 25 |
+
def __init__(self, layers):
|
| 26 |
+
self.layers = layers
|
| 27 |
+
|
| 28 |
+
callbacks = {
|
| 29 |
+
(
|
| 30 |
+
ot.Paint,
|
| 31 |
+
ot.PaintFormat.PaintColrLayers,
|
| 32 |
+
): self._unbuildPaintColrLayers,
|
| 33 |
+
}
|
| 34 |
+
self.tableUnbuilder = TableUnbuilder(callbacks)
|
| 35 |
+
|
| 36 |
+
def unbuildPaint(self, paint):
|
| 37 |
+
assert isinstance(paint, ot.Paint)
|
| 38 |
+
return self.tableUnbuilder.unbuild(paint)
|
| 39 |
+
|
| 40 |
+
def _unbuildPaintColrLayers(self, source):
|
| 41 |
+
assert source["Format"] == ot.PaintFormat.PaintColrLayers
|
| 42 |
+
|
| 43 |
+
layers = list(
|
| 44 |
+
_flatten_layers(
|
| 45 |
+
[
|
| 46 |
+
self.unbuildPaint(childPaint)
|
| 47 |
+
for childPaint in self.layers[
|
| 48 |
+
source["FirstLayerIndex"] : source["FirstLayerIndex"]
|
| 49 |
+
+ source["NumLayers"]
|
| 50 |
+
]
|
| 51 |
+
]
|
| 52 |
+
)
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
if len(layers) == 1:
|
| 56 |
+
return layers[0]
|
| 57 |
+
|
| 58 |
+
return {"Format": source["Format"], "Layers": layers}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
if __name__ == "__main__":
|
| 62 |
+
from pprint import pprint
|
| 63 |
+
import sys
|
| 64 |
+
from fontTools.ttLib import TTFont
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
fontfile = sys.argv[1]
|
| 68 |
+
except IndexError:
|
| 69 |
+
sys.exit("usage: fonttools colorLib.unbuilder FONTFILE")
|
| 70 |
+
|
| 71 |
+
font = TTFont(fontfile)
|
| 72 |
+
colr = font["COLR"]
|
| 73 |
+
if colr.version < 1:
|
| 74 |
+
sys.exit(f"error: No COLR table version=1 found in {fontfile}")
|
| 75 |
+
|
| 76 |
+
colorGlyphs = unbuildColrV1(
|
| 77 |
+
colr.table.LayerList,
|
| 78 |
+
colr.table.BaseGlyphList,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
pprint(colorGlyphs)
|
mantis_evalkit/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 |
+
)
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/config/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (2.85 kB). View file
|
|
|
mantis_evalkit/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."""
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/basePen.py
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/cu2quPen.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/filterPen.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
mantis_evalkit/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})]")
|
mantis_evalkit/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()
|
mantis_evalkit/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
|
mantis_evalkit/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)
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/statisticsPen.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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:])
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/svgPathPen.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable
|
| 2 |
+
from fontTools.pens.basePen import BasePen
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def pointToString(pt, ntos=str):
|
| 6 |
+
return " ".join(ntos(i) for i in pt)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class SVGPathPen(BasePen):
|
| 10 |
+
"""Pen to draw SVG path d commands.
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
glyphSet: a dictionary of drawable glyph objects keyed by name
|
| 14 |
+
used to resolve component references in composite glyphs.
|
| 15 |
+
ntos: a callable that takes a number and returns a string, to
|
| 16 |
+
customize how numbers are formatted (default: str).
|
| 17 |
+
|
| 18 |
+
:Example:
|
| 19 |
+
.. code-block::
|
| 20 |
+
|
| 21 |
+
>>> pen = SVGPathPen(None)
|
| 22 |
+
>>> pen.moveTo((0, 0))
|
| 23 |
+
>>> pen.lineTo((1, 1))
|
| 24 |
+
>>> pen.curveTo((2, 2), (3, 3), (4, 4))
|
| 25 |
+
>>> pen.closePath()
|
| 26 |
+
>>> pen.getCommands()
|
| 27 |
+
'M0 0 1 1C2 2 3 3 4 4Z'
|
| 28 |
+
|
| 29 |
+
Note:
|
| 30 |
+
Fonts have a coordinate system where Y grows up, whereas in SVG,
|
| 31 |
+
Y grows down. As such, rendering path data from this pen in
|
| 32 |
+
SVG typically results in upside-down glyphs. You can fix this
|
| 33 |
+
by wrapping the data from this pen in an SVG group element with
|
| 34 |
+
transform, or wrap this pen in a transform pen. For example:
|
| 35 |
+
.. code-block:: python
|
| 36 |
+
|
| 37 |
+
spen = svgPathPen.SVGPathPen(glyphset)
|
| 38 |
+
pen= TransformPen(spen , (1, 0, 0, -1, 0, 0))
|
| 39 |
+
glyphset[glyphname].draw(pen)
|
| 40 |
+
print(tpen.getCommands())
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(self, glyphSet, ntos: Callable[[float], str] = str):
|
| 44 |
+
BasePen.__init__(self, glyphSet)
|
| 45 |
+
self._commands = []
|
| 46 |
+
self._lastCommand = None
|
| 47 |
+
self._lastX = None
|
| 48 |
+
self._lastY = None
|
| 49 |
+
self._ntos = ntos
|
| 50 |
+
|
| 51 |
+
def _handleAnchor(self):
|
| 52 |
+
"""
|
| 53 |
+
>>> pen = SVGPathPen(None)
|
| 54 |
+
>>> pen.moveTo((0, 0))
|
| 55 |
+
>>> pen.moveTo((10, 10))
|
| 56 |
+
>>> pen._commands
|
| 57 |
+
['M10 10']
|
| 58 |
+
"""
|
| 59 |
+
if self._lastCommand == "M":
|
| 60 |
+
self._commands.pop(-1)
|
| 61 |
+
|
| 62 |
+
def _moveTo(self, pt):
|
| 63 |
+
"""
|
| 64 |
+
>>> pen = SVGPathPen(None)
|
| 65 |
+
>>> pen.moveTo((0, 0))
|
| 66 |
+
>>> pen._commands
|
| 67 |
+
['M0 0']
|
| 68 |
+
|
| 69 |
+
>>> pen = SVGPathPen(None)
|
| 70 |
+
>>> pen.moveTo((10, 0))
|
| 71 |
+
>>> pen._commands
|
| 72 |
+
['M10 0']
|
| 73 |
+
|
| 74 |
+
>>> pen = SVGPathPen(None)
|
| 75 |
+
>>> pen.moveTo((0, 10))
|
| 76 |
+
>>> pen._commands
|
| 77 |
+
['M0 10']
|
| 78 |
+
"""
|
| 79 |
+
self._handleAnchor()
|
| 80 |
+
t = "M%s" % (pointToString(pt, self._ntos))
|
| 81 |
+
self._commands.append(t)
|
| 82 |
+
self._lastCommand = "M"
|
| 83 |
+
self._lastX, self._lastY = pt
|
| 84 |
+
|
| 85 |
+
def _lineTo(self, pt):
|
| 86 |
+
"""
|
| 87 |
+
# duplicate point
|
| 88 |
+
>>> pen = SVGPathPen(None)
|
| 89 |
+
>>> pen.moveTo((10, 10))
|
| 90 |
+
>>> pen.lineTo((10, 10))
|
| 91 |
+
>>> pen._commands
|
| 92 |
+
['M10 10']
|
| 93 |
+
|
| 94 |
+
# vertical line
|
| 95 |
+
>>> pen = SVGPathPen(None)
|
| 96 |
+
>>> pen.moveTo((10, 10))
|
| 97 |
+
>>> pen.lineTo((10, 0))
|
| 98 |
+
>>> pen._commands
|
| 99 |
+
['M10 10', 'V0']
|
| 100 |
+
|
| 101 |
+
# horizontal line
|
| 102 |
+
>>> pen = SVGPathPen(None)
|
| 103 |
+
>>> pen.moveTo((10, 10))
|
| 104 |
+
>>> pen.lineTo((0, 10))
|
| 105 |
+
>>> pen._commands
|
| 106 |
+
['M10 10', 'H0']
|
| 107 |
+
|
| 108 |
+
# basic
|
| 109 |
+
>>> pen = SVGPathPen(None)
|
| 110 |
+
>>> pen.lineTo((70, 80))
|
| 111 |
+
>>> pen._commands
|
| 112 |
+
['L70 80']
|
| 113 |
+
|
| 114 |
+
# basic following a moveto
|
| 115 |
+
>>> pen = SVGPathPen(None)
|
| 116 |
+
>>> pen.moveTo((0, 0))
|
| 117 |
+
>>> pen.lineTo((10, 10))
|
| 118 |
+
>>> pen._commands
|
| 119 |
+
['M0 0', ' 10 10']
|
| 120 |
+
"""
|
| 121 |
+
x, y = pt
|
| 122 |
+
# duplicate point
|
| 123 |
+
if x == self._lastX and y == self._lastY:
|
| 124 |
+
return
|
| 125 |
+
# vertical line
|
| 126 |
+
elif x == self._lastX:
|
| 127 |
+
cmd = "V"
|
| 128 |
+
pts = self._ntos(y)
|
| 129 |
+
# horizontal line
|
| 130 |
+
elif y == self._lastY:
|
| 131 |
+
cmd = "H"
|
| 132 |
+
pts = self._ntos(x)
|
| 133 |
+
# previous was a moveto
|
| 134 |
+
elif self._lastCommand == "M":
|
| 135 |
+
cmd = None
|
| 136 |
+
pts = " " + pointToString(pt, self._ntos)
|
| 137 |
+
# basic
|
| 138 |
+
else:
|
| 139 |
+
cmd = "L"
|
| 140 |
+
pts = pointToString(pt, self._ntos)
|
| 141 |
+
# write the string
|
| 142 |
+
t = ""
|
| 143 |
+
if cmd:
|
| 144 |
+
t += cmd
|
| 145 |
+
self._lastCommand = cmd
|
| 146 |
+
t += pts
|
| 147 |
+
self._commands.append(t)
|
| 148 |
+
# store for future reference
|
| 149 |
+
self._lastX, self._lastY = pt
|
| 150 |
+
|
| 151 |
+
def _curveToOne(self, pt1, pt2, pt3):
|
| 152 |
+
"""
|
| 153 |
+
>>> pen = SVGPathPen(None)
|
| 154 |
+
>>> pen.curveTo((10, 20), (30, 40), (50, 60))
|
| 155 |
+
>>> pen._commands
|
| 156 |
+
['C10 20 30 40 50 60']
|
| 157 |
+
"""
|
| 158 |
+
t = "C"
|
| 159 |
+
t += pointToString(pt1, self._ntos) + " "
|
| 160 |
+
t += pointToString(pt2, self._ntos) + " "
|
| 161 |
+
t += pointToString(pt3, self._ntos)
|
| 162 |
+
self._commands.append(t)
|
| 163 |
+
self._lastCommand = "C"
|
| 164 |
+
self._lastX, self._lastY = pt3
|
| 165 |
+
|
| 166 |
+
def _qCurveToOne(self, pt1, pt2):
|
| 167 |
+
"""
|
| 168 |
+
>>> pen = SVGPathPen(None)
|
| 169 |
+
>>> pen.qCurveTo((10, 20), (30, 40))
|
| 170 |
+
>>> pen._commands
|
| 171 |
+
['Q10 20 30 40']
|
| 172 |
+
>>> from fontTools.misc.roundTools import otRound
|
| 173 |
+
>>> pen = SVGPathPen(None, ntos=lambda v: str(otRound(v)))
|
| 174 |
+
>>> pen.qCurveTo((3, 3), (7, 5), (11, 4))
|
| 175 |
+
>>> pen._commands
|
| 176 |
+
['Q3 3 5 4', 'Q7 5 11 4']
|
| 177 |
+
"""
|
| 178 |
+
assert pt2 is not None
|
| 179 |
+
t = "Q"
|
| 180 |
+
t += pointToString(pt1, self._ntos) + " "
|
| 181 |
+
t += pointToString(pt2, self._ntos)
|
| 182 |
+
self._commands.append(t)
|
| 183 |
+
self._lastCommand = "Q"
|
| 184 |
+
self._lastX, self._lastY = pt2
|
| 185 |
+
|
| 186 |
+
def _closePath(self):
|
| 187 |
+
"""
|
| 188 |
+
>>> pen = SVGPathPen(None)
|
| 189 |
+
>>> pen.closePath()
|
| 190 |
+
>>> pen._commands
|
| 191 |
+
['Z']
|
| 192 |
+
"""
|
| 193 |
+
self._commands.append("Z")
|
| 194 |
+
self._lastCommand = "Z"
|
| 195 |
+
self._lastX = self._lastY = None
|
| 196 |
+
|
| 197 |
+
def _endPath(self):
|
| 198 |
+
"""
|
| 199 |
+
>>> pen = SVGPathPen(None)
|
| 200 |
+
>>> pen.endPath()
|
| 201 |
+
>>> pen._commands
|
| 202 |
+
[]
|
| 203 |
+
"""
|
| 204 |
+
self._lastCommand = None
|
| 205 |
+
self._lastX = self._lastY = None
|
| 206 |
+
|
| 207 |
+
def getCommands(self):
|
| 208 |
+
return "".join(self._commands)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def main(args=None):
|
| 212 |
+
"""Generate per-character SVG from font and text"""
|
| 213 |
+
|
| 214 |
+
if args is None:
|
| 215 |
+
import sys
|
| 216 |
+
|
| 217 |
+
args = sys.argv[1:]
|
| 218 |
+
|
| 219 |
+
from fontTools.ttLib import TTFont
|
| 220 |
+
import argparse
|
| 221 |
+
|
| 222 |
+
parser = argparse.ArgumentParser(
|
| 223 |
+
"fonttools pens.svgPathPen", description="Generate SVG from text"
|
| 224 |
+
)
|
| 225 |
+
parser.add_argument("font", metavar="font.ttf", help="Font file.")
|
| 226 |
+
parser.add_argument("text", metavar="text", nargs="?", help="Text string.")
|
| 227 |
+
parser.add_argument(
|
| 228 |
+
"-y",
|
| 229 |
+
metavar="<number>",
|
| 230 |
+
help="Face index into a collection to open. Zero based.",
|
| 231 |
+
)
|
| 232 |
+
parser.add_argument(
|
| 233 |
+
"--glyphs",
|
| 234 |
+
metavar="whitespace-separated list of glyph names",
|
| 235 |
+
type=str,
|
| 236 |
+
help="Glyphs to show. Exclusive with text option",
|
| 237 |
+
)
|
| 238 |
+
parser.add_argument(
|
| 239 |
+
"--variations",
|
| 240 |
+
metavar="AXIS=LOC",
|
| 241 |
+
default="",
|
| 242 |
+
help="List of space separated locations. A location consist in "
|
| 243 |
+
"the name of a variation axis, followed by '=' and a number. E.g.: "
|
| 244 |
+
"wght=700 wdth=80. The default is the location of the base master.",
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
options = parser.parse_args(args)
|
| 248 |
+
|
| 249 |
+
fontNumber = int(options.y) if options.y is not None else 0
|
| 250 |
+
|
| 251 |
+
font = TTFont(options.font, fontNumber=fontNumber)
|
| 252 |
+
text = options.text
|
| 253 |
+
glyphs = options.glyphs
|
| 254 |
+
|
| 255 |
+
location = {}
|
| 256 |
+
for tag_v in options.variations.split():
|
| 257 |
+
fields = tag_v.split("=")
|
| 258 |
+
tag = fields[0].strip()
|
| 259 |
+
v = float(fields[1])
|
| 260 |
+
location[tag] = v
|
| 261 |
+
|
| 262 |
+
hhea = font["hhea"]
|
| 263 |
+
ascent, descent = hhea.ascent, hhea.descent
|
| 264 |
+
|
| 265 |
+
glyphset = font.getGlyphSet(location=location)
|
| 266 |
+
cmap = font["cmap"].getBestCmap()
|
| 267 |
+
|
| 268 |
+
if glyphs is not None and text is not None:
|
| 269 |
+
raise ValueError("Options --glyphs and --text are exclusive")
|
| 270 |
+
|
| 271 |
+
if glyphs is None:
|
| 272 |
+
glyphs = " ".join(cmap[ord(u)] for u in text)
|
| 273 |
+
|
| 274 |
+
glyphs = glyphs.split()
|
| 275 |
+
|
| 276 |
+
s = ""
|
| 277 |
+
width = 0
|
| 278 |
+
for g in glyphs:
|
| 279 |
+
glyph = glyphset[g]
|
| 280 |
+
|
| 281 |
+
pen = SVGPathPen(glyphset)
|
| 282 |
+
glyph.draw(pen)
|
| 283 |
+
commands = pen.getCommands()
|
| 284 |
+
|
| 285 |
+
s += '<g transform="translate(%d %d) scale(1 -1)"><path d="%s"/></g>\n' % (
|
| 286 |
+
width,
|
| 287 |
+
ascent,
|
| 288 |
+
commands,
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
width += glyph.width
|
| 292 |
+
|
| 293 |
+
print('<?xml version="1.0" encoding="UTF-8"?>')
|
| 294 |
+
print(
|
| 295 |
+
'<svg width="%d" height="%d" xmlns="http://www.w3.org/2000/svg">'
|
| 296 |
+
% (width, ascent - descent)
|
| 297 |
+
)
|
| 298 |
+
print(s, end="")
|
| 299 |
+
print("</svg>")
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
if __name__ == "__main__":
|
| 303 |
+
import sys
|
| 304 |
+
|
| 305 |
+
if len(sys.argv) == 1:
|
| 306 |
+
import doctest
|
| 307 |
+
|
| 308 |
+
sys.exit(doctest.testmod().failed)
|
| 309 |
+
|
| 310 |
+
sys.exit(main())
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/ttGlyphPen.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from array import array
|
| 2 |
+
from typing import Any, Callable, Dict, Optional, Tuple
|
| 3 |
+
from fontTools.misc.fixedTools import MAX_F2DOT14, floatToFixedToFloat
|
| 4 |
+
from fontTools.misc.loggingTools import LogMixin
|
| 5 |
+
from fontTools.pens.pointPen import AbstractPointPen
|
| 6 |
+
from fontTools.misc.roundTools import otRound
|
| 7 |
+
from fontTools.pens.basePen import LoggingPen, PenError
|
| 8 |
+
from fontTools.pens.transformPen import TransformPen, TransformPointPen
|
| 9 |
+
from fontTools.ttLib.tables import ttProgram
|
| 10 |
+
from fontTools.ttLib.tables._g_l_y_f import flagOnCurve, flagCubic
|
| 11 |
+
from fontTools.ttLib.tables._g_l_y_f import Glyph
|
| 12 |
+
from fontTools.ttLib.tables._g_l_y_f import GlyphComponent
|
| 13 |
+
from fontTools.ttLib.tables._g_l_y_f import GlyphCoordinates
|
| 14 |
+
from fontTools.ttLib.tables._g_l_y_f import dropImpliedOnCurvePoints
|
| 15 |
+
import math
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = ["TTGlyphPen", "TTGlyphPointPen"]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class _TTGlyphBasePen:
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
glyphSet: Optional[Dict[str, Any]],
|
| 25 |
+
handleOverflowingTransforms: bool = True,
|
| 26 |
+
) -> None:
|
| 27 |
+
"""
|
| 28 |
+
Construct a new pen.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
glyphSet (Dict[str, Any]): A glyphset object, used to resolve components.
|
| 32 |
+
handleOverflowingTransforms (bool): See below.
|
| 33 |
+
|
| 34 |
+
If ``handleOverflowingTransforms`` is True, the components' transform values
|
| 35 |
+
are checked that they don't overflow the limits of a F2Dot14 number:
|
| 36 |
+
-2.0 <= v < +2.0. If any transform value exceeds these, the composite
|
| 37 |
+
glyph is decomposed.
|
| 38 |
+
|
| 39 |
+
An exception to this rule is done for values that are very close to +2.0
|
| 40 |
+
(both for consistency with the -2.0 case, and for the relative frequency
|
| 41 |
+
these occur in real fonts). When almost +2.0 values occur (and all other
|
| 42 |
+
values are within the range -2.0 <= x <= +2.0), they are clamped to the
|
| 43 |
+
maximum positive value that can still be encoded as an F2Dot14: i.e.
|
| 44 |
+
1.99993896484375.
|
| 45 |
+
|
| 46 |
+
If False, no check is done and all components are translated unmodified
|
| 47 |
+
into the glyf table, followed by an inevitable ``struct.error`` once an
|
| 48 |
+
attempt is made to compile them.
|
| 49 |
+
|
| 50 |
+
If both contours and components are present in a glyph, the components
|
| 51 |
+
are decomposed.
|
| 52 |
+
"""
|
| 53 |
+
self.glyphSet = glyphSet
|
| 54 |
+
self.handleOverflowingTransforms = handleOverflowingTransforms
|
| 55 |
+
self.init()
|
| 56 |
+
|
| 57 |
+
def _decompose(
|
| 58 |
+
self,
|
| 59 |
+
glyphName: str,
|
| 60 |
+
transformation: Tuple[float, float, float, float, float, float],
|
| 61 |
+
):
|
| 62 |
+
tpen = self.transformPen(self, transformation)
|
| 63 |
+
getattr(self.glyphSet[glyphName], self.drawMethod)(tpen)
|
| 64 |
+
|
| 65 |
+
def _isClosed(self):
|
| 66 |
+
"""
|
| 67 |
+
Check if the current path is closed.
|
| 68 |
+
"""
|
| 69 |
+
raise NotImplementedError
|
| 70 |
+
|
| 71 |
+
def init(self) -> None:
|
| 72 |
+
self.points = []
|
| 73 |
+
self.endPts = []
|
| 74 |
+
self.types = []
|
| 75 |
+
self.components = []
|
| 76 |
+
|
| 77 |
+
def addComponent(
|
| 78 |
+
self,
|
| 79 |
+
baseGlyphName: str,
|
| 80 |
+
transformation: Tuple[float, float, float, float, float, float],
|
| 81 |
+
identifier: Optional[str] = None,
|
| 82 |
+
**kwargs: Any,
|
| 83 |
+
) -> None:
|
| 84 |
+
"""
|
| 85 |
+
Add a sub glyph.
|
| 86 |
+
"""
|
| 87 |
+
self.components.append((baseGlyphName, transformation))
|
| 88 |
+
|
| 89 |
+
def _buildComponents(self, componentFlags):
|
| 90 |
+
if self.handleOverflowingTransforms:
|
| 91 |
+
# we can't encode transform values > 2 or < -2 in F2Dot14,
|
| 92 |
+
# so we must decompose the glyph if any transform exceeds these
|
| 93 |
+
overflowing = any(
|
| 94 |
+
s > 2 or s < -2
|
| 95 |
+
for (glyphName, transformation) in self.components
|
| 96 |
+
for s in transformation[:4]
|
| 97 |
+
)
|
| 98 |
+
components = []
|
| 99 |
+
for glyphName, transformation in self.components:
|
| 100 |
+
if glyphName not in self.glyphSet:
|
| 101 |
+
self.log.warning(f"skipped non-existing component '{glyphName}'")
|
| 102 |
+
continue
|
| 103 |
+
if self.points or (self.handleOverflowingTransforms and overflowing):
|
| 104 |
+
# can't have both coordinates and components, so decompose
|
| 105 |
+
self._decompose(glyphName, transformation)
|
| 106 |
+
continue
|
| 107 |
+
|
| 108 |
+
component = GlyphComponent()
|
| 109 |
+
component.glyphName = glyphName
|
| 110 |
+
component.x, component.y = (otRound(v) for v in transformation[4:])
|
| 111 |
+
# quantize floats to F2Dot14 so we get same values as when decompiled
|
| 112 |
+
# from a binary glyf table
|
| 113 |
+
transformation = tuple(
|
| 114 |
+
floatToFixedToFloat(v, 14) for v in transformation[:4]
|
| 115 |
+
)
|
| 116 |
+
if transformation != (1, 0, 0, 1):
|
| 117 |
+
if self.handleOverflowingTransforms and any(
|
| 118 |
+
MAX_F2DOT14 < s <= 2 for s in transformation
|
| 119 |
+
):
|
| 120 |
+
# clamp values ~= +2.0 so we can keep the component
|
| 121 |
+
transformation = tuple(
|
| 122 |
+
MAX_F2DOT14 if MAX_F2DOT14 < s <= 2 else s
|
| 123 |
+
for s in transformation
|
| 124 |
+
)
|
| 125 |
+
component.transform = (transformation[:2], transformation[2:])
|
| 126 |
+
component.flags = componentFlags
|
| 127 |
+
components.append(component)
|
| 128 |
+
return components
|
| 129 |
+
|
| 130 |
+
def glyph(
|
| 131 |
+
self,
|
| 132 |
+
componentFlags: int = 0x04,
|
| 133 |
+
dropImpliedOnCurves: bool = False,
|
| 134 |
+
*,
|
| 135 |
+
round: Callable[[float], int] = otRound,
|
| 136 |
+
) -> Glyph:
|
| 137 |
+
"""
|
| 138 |
+
Returns a :py:class:`~._g_l_y_f.Glyph` object representing the glyph.
|
| 139 |
+
|
| 140 |
+
Args:
|
| 141 |
+
componentFlags: Flags to use for component glyphs. (default: 0x04)
|
| 142 |
+
|
| 143 |
+
dropImpliedOnCurves: Whether to remove implied-oncurve points. (default: False)
|
| 144 |
+
"""
|
| 145 |
+
if not self._isClosed():
|
| 146 |
+
raise PenError("Didn't close last contour.")
|
| 147 |
+
components = self._buildComponents(componentFlags)
|
| 148 |
+
|
| 149 |
+
glyph = Glyph()
|
| 150 |
+
glyph.coordinates = GlyphCoordinates(self.points)
|
| 151 |
+
glyph.endPtsOfContours = self.endPts
|
| 152 |
+
glyph.flags = array("B", self.types)
|
| 153 |
+
self.init()
|
| 154 |
+
|
| 155 |
+
if components:
|
| 156 |
+
# If both components and contours were present, they have by now
|
| 157 |
+
# been decomposed by _buildComponents.
|
| 158 |
+
glyph.components = components
|
| 159 |
+
glyph.numberOfContours = -1
|
| 160 |
+
else:
|
| 161 |
+
glyph.numberOfContours = len(glyph.endPtsOfContours)
|
| 162 |
+
glyph.program = ttProgram.Program()
|
| 163 |
+
glyph.program.fromBytecode(b"")
|
| 164 |
+
if dropImpliedOnCurves:
|
| 165 |
+
dropImpliedOnCurvePoints(glyph)
|
| 166 |
+
glyph.coordinates.toInt(round=round)
|
| 167 |
+
|
| 168 |
+
return glyph
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class TTGlyphPen(_TTGlyphBasePen, LoggingPen):
|
| 172 |
+
"""
|
| 173 |
+
Pen used for drawing to a TrueType glyph.
|
| 174 |
+
|
| 175 |
+
This pen can be used to construct or modify glyphs in a TrueType format
|
| 176 |
+
font. After using the pen to draw, use the ``.glyph()`` method to retrieve
|
| 177 |
+
a :py:class:`~._g_l_y_f.Glyph` object representing the glyph.
|
| 178 |
+
"""
|
| 179 |
+
|
| 180 |
+
drawMethod = "draw"
|
| 181 |
+
transformPen = TransformPen
|
| 182 |
+
|
| 183 |
+
def __init__(
|
| 184 |
+
self,
|
| 185 |
+
glyphSet: Optional[Dict[str, Any]] = None,
|
| 186 |
+
handleOverflowingTransforms: bool = True,
|
| 187 |
+
outputImpliedClosingLine: bool = False,
|
| 188 |
+
) -> None:
|
| 189 |
+
super().__init__(glyphSet, handleOverflowingTransforms)
|
| 190 |
+
self.outputImpliedClosingLine = outputImpliedClosingLine
|
| 191 |
+
|
| 192 |
+
def _addPoint(self, pt: Tuple[float, float], tp: int) -> None:
|
| 193 |
+
self.points.append(pt)
|
| 194 |
+
self.types.append(tp)
|
| 195 |
+
|
| 196 |
+
def _popPoint(self) -> None:
|
| 197 |
+
self.points.pop()
|
| 198 |
+
self.types.pop()
|
| 199 |
+
|
| 200 |
+
def _isClosed(self) -> bool:
|
| 201 |
+
return (not self.points) or (
|
| 202 |
+
self.endPts and self.endPts[-1] == len(self.points) - 1
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
def lineTo(self, pt: Tuple[float, float]) -> None:
|
| 206 |
+
self._addPoint(pt, flagOnCurve)
|
| 207 |
+
|
| 208 |
+
def moveTo(self, pt: Tuple[float, float]) -> None:
|
| 209 |
+
if not self._isClosed():
|
| 210 |
+
raise PenError('"move"-type point must begin a new contour.')
|
| 211 |
+
self._addPoint(pt, flagOnCurve)
|
| 212 |
+
|
| 213 |
+
def curveTo(self, *points) -> None:
|
| 214 |
+
assert len(points) % 2 == 1
|
| 215 |
+
for pt in points[:-1]:
|
| 216 |
+
self._addPoint(pt, flagCubic)
|
| 217 |
+
|
| 218 |
+
# last point is None if there are no on-curve points
|
| 219 |
+
if points[-1] is not None:
|
| 220 |
+
self._addPoint(points[-1], 1)
|
| 221 |
+
|
| 222 |
+
def qCurveTo(self, *points) -> None:
|
| 223 |
+
assert len(points) >= 1
|
| 224 |
+
for pt in points[:-1]:
|
| 225 |
+
self._addPoint(pt, 0)
|
| 226 |
+
|
| 227 |
+
# last point is None if there are no on-curve points
|
| 228 |
+
if points[-1] is not None:
|
| 229 |
+
self._addPoint(points[-1], 1)
|
| 230 |
+
|
| 231 |
+
def closePath(self) -> None:
|
| 232 |
+
endPt = len(self.points) - 1
|
| 233 |
+
|
| 234 |
+
# ignore anchors (one-point paths)
|
| 235 |
+
if endPt == 0 or (self.endPts and endPt == self.endPts[-1] + 1):
|
| 236 |
+
self._popPoint()
|
| 237 |
+
return
|
| 238 |
+
|
| 239 |
+
if not self.outputImpliedClosingLine:
|
| 240 |
+
# if first and last point on this path are the same, remove last
|
| 241 |
+
startPt = 0
|
| 242 |
+
if self.endPts:
|
| 243 |
+
startPt = self.endPts[-1] + 1
|
| 244 |
+
if self.points[startPt] == self.points[endPt]:
|
| 245 |
+
self._popPoint()
|
| 246 |
+
endPt -= 1
|
| 247 |
+
|
| 248 |
+
self.endPts.append(endPt)
|
| 249 |
+
|
| 250 |
+
def endPath(self) -> None:
|
| 251 |
+
# TrueType contours are always "closed"
|
| 252 |
+
self.closePath()
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
class TTGlyphPointPen(_TTGlyphBasePen, LogMixin, AbstractPointPen):
|
| 256 |
+
"""
|
| 257 |
+
Point pen used for drawing to a TrueType glyph.
|
| 258 |
+
|
| 259 |
+
This pen can be used to construct or modify glyphs in a TrueType format
|
| 260 |
+
font. After using the pen to draw, use the ``.glyph()`` method to retrieve
|
| 261 |
+
a :py:class:`~._g_l_y_f.Glyph` object representing the glyph.
|
| 262 |
+
"""
|
| 263 |
+
|
| 264 |
+
drawMethod = "drawPoints"
|
| 265 |
+
transformPen = TransformPointPen
|
| 266 |
+
|
| 267 |
+
def init(self) -> None:
|
| 268 |
+
super().init()
|
| 269 |
+
self._currentContourStartIndex = None
|
| 270 |
+
|
| 271 |
+
def _isClosed(self) -> bool:
|
| 272 |
+
return self._currentContourStartIndex is None
|
| 273 |
+
|
| 274 |
+
def beginPath(self, identifier: Optional[str] = None, **kwargs: Any) -> None:
|
| 275 |
+
"""
|
| 276 |
+
Start a new sub path.
|
| 277 |
+
"""
|
| 278 |
+
if not self._isClosed():
|
| 279 |
+
raise PenError("Didn't close previous contour.")
|
| 280 |
+
self._currentContourStartIndex = len(self.points)
|
| 281 |
+
|
| 282 |
+
def endPath(self) -> None:
|
| 283 |
+
"""
|
| 284 |
+
End the current sub path.
|
| 285 |
+
"""
|
| 286 |
+
# TrueType contours are always "closed"
|
| 287 |
+
if self._isClosed():
|
| 288 |
+
raise PenError("Contour is already closed.")
|
| 289 |
+
if self._currentContourStartIndex == len(self.points):
|
| 290 |
+
# ignore empty contours
|
| 291 |
+
self._currentContourStartIndex = None
|
| 292 |
+
return
|
| 293 |
+
|
| 294 |
+
contourStart = self.endPts[-1] + 1 if self.endPts else 0
|
| 295 |
+
self.endPts.append(len(self.points) - 1)
|
| 296 |
+
self._currentContourStartIndex = None
|
| 297 |
+
|
| 298 |
+
# Resolve types for any cubic segments
|
| 299 |
+
flags = self.types
|
| 300 |
+
for i in range(contourStart, len(flags)):
|
| 301 |
+
if flags[i] == "curve":
|
| 302 |
+
j = i - 1
|
| 303 |
+
if j < contourStart:
|
| 304 |
+
j = len(flags) - 1
|
| 305 |
+
while flags[j] == 0:
|
| 306 |
+
flags[j] = flagCubic
|
| 307 |
+
j -= 1
|
| 308 |
+
flags[i] = flagOnCurve
|
| 309 |
+
|
| 310 |
+
def addPoint(
|
| 311 |
+
self,
|
| 312 |
+
pt: Tuple[float, float],
|
| 313 |
+
segmentType: Optional[str] = None,
|
| 314 |
+
smooth: bool = False,
|
| 315 |
+
name: Optional[str] = None,
|
| 316 |
+
identifier: Optional[str] = None,
|
| 317 |
+
**kwargs: Any,
|
| 318 |
+
) -> None:
|
| 319 |
+
"""
|
| 320 |
+
Add a point to the current sub path.
|
| 321 |
+
"""
|
| 322 |
+
if self._isClosed():
|
| 323 |
+
raise PenError("Can't add a point to a closed contour.")
|
| 324 |
+
if segmentType is None:
|
| 325 |
+
self.types.append(0)
|
| 326 |
+
elif segmentType in ("line", "move"):
|
| 327 |
+
self.types.append(flagOnCurve)
|
| 328 |
+
elif segmentType == "qcurve":
|
| 329 |
+
self.types.append(flagOnCurve)
|
| 330 |
+
elif segmentType == "curve":
|
| 331 |
+
self.types.append("curve")
|
| 332 |
+
else:
|
| 333 |
+
raise AssertionError(segmentType)
|
| 334 |
+
|
| 335 |
+
self.points.append(pt)
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/pens/wxPen.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.pens.basePen import BasePen
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
__all__ = ["WxPen"]
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class WxPen(BasePen):
|
| 8 |
+
def __init__(self, glyphSet, path=None):
|
| 9 |
+
BasePen.__init__(self, glyphSet)
|
| 10 |
+
if path is None:
|
| 11 |
+
import wx
|
| 12 |
+
|
| 13 |
+
path = wx.GraphicsRenderer.GetDefaultRenderer().CreatePath()
|
| 14 |
+
self.path = path
|
| 15 |
+
|
| 16 |
+
def _moveTo(self, p):
|
| 17 |
+
self.path.MoveToPoint(*p)
|
| 18 |
+
|
| 19 |
+
def _lineTo(self, p):
|
| 20 |
+
self.path.AddLineToPoint(*p)
|
| 21 |
+
|
| 22 |
+
def _curveToOne(self, p1, p2, p3):
|
| 23 |
+
self.path.AddCurveToPoint(*p1 + p2 + p3)
|
| 24 |
+
|
| 25 |
+
def _qCurveToOne(self, p1, p2):
|
| 26 |
+
self.path.AddQuadCurveToPoint(*p1 + p2)
|
| 27 |
+
|
| 28 |
+
def _closePath(self):
|
| 29 |
+
self.path.CloseSubpath()
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/C_B_D_T_.cpython-310.pyc
ADDED
|
Binary file (3.58 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/C_B_L_C_.cpython-310.pyc
ADDED
|
Binary file (764 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F_.cpython-310.pyc
ADDED
|
Binary file (2.66 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/D_S_I_G_.cpython-310.pyc
ADDED
|
Binary file (4.64 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/D__e_b_g.cpython-310.pyc
ADDED
|
Binary file (1.1 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/DefaultTable.cpython-310.pyc
ADDED
|
Binary file (2.19 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/E_B_D_T_.cpython-310.pyc
ADDED
|
Binary file (20.8 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/F_F_T_M_.cpython-310.pyc
ADDED
|
Binary file (2.1 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/G_M_A_P_.cpython-310.pyc
ADDED
|
Binary file (4.37 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/G_P_K_G_.cpython-310.pyc
ADDED
|
Binary file (3.41 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/G__l_a_t.cpython-310.pyc
ADDED
|
Binary file (7.27 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/H_V_A_R_.cpython-310.pyc
ADDED
|
Binary file (624 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/M_E_T_A_.cpython-310.pyc
ADDED
|
Binary file (7.89 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/S_I_N_G_.cpython-310.pyc
ADDED
|
Binary file (3.27 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/S_T_A_T_.cpython-310.pyc
ADDED
|
Binary file (812 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/S_V_G_.cpython-310.pyc
ADDED
|
Binary file (5.76 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/S__i_l_f.cpython-310.pyc
ADDED
|
Binary file (26.4 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_B_.cpython-310.pyc
ADDED
|
Binary file (658 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_D_.cpython-310.pyc
ADDED
|
Binary file (658 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_V_.cpython-310.pyc
ADDED
|
Binary file (1.26 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__0.cpython-310.pyc
ADDED
|
Binary file (2.2 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__1.cpython-310.pyc
ADDED
|
Binary file (3.72 kB). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__2.cpython-310.pyc
ADDED
|
Binary file (831 Bytes). View file
|
|
|
mantis_evalkit/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/V_A_R_C_.cpython-310.pyc
ADDED
|
Binary file (600 Bytes). View file
|
|
|