Upload folder using huggingface_hub (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +5 -0
- .venv/lib/python3.12/site-packages/fontTools/svgLib/__init__.py +3 -0
- .venv/lib/python3.12/site-packages/fontTools/svgLib/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/svgLib/path/__init__.py +64 -0
- .venv/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/arc.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/parser.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/shapes.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/svgLib/path/arc.py +153 -0
- .venv/lib/python3.12/site-packages/fontTools/svgLib/path/parser.py +350 -0
- .venv/lib/python3.12/site-packages/fontTools/svgLib/path/shapes.py +185 -0
- .venv/lib/python3.12/site-packages/fontTools/t1Lib/__init__.py +648 -0
- .venv/lib/python3.12/site-packages/fontTools/t1Lib/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/tfmLib.py +460 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__init__.py +29 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__main__.py +148 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__main__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/macUtils.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/removeOverlaps.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/reorderGlyphs.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/scaleUpem.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/sfnt.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/standardGlyphOrder.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttCollection.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttFont.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttGlyphSet.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttVisitor.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/woff2.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/macUtils.py +54 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/removeOverlaps.py +394 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/reorderGlyphs.py +284 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/scaleUpem.py +435 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/sfnt.py +708 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/standardGlyphOrder.py +271 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/B_A_S_E_.py +14 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/BitmapGlyphMetrics.py +63 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_B_D_T_.py +113 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_B_L_C_.py +19 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_F_F_.py +61 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_F_F__2.py +26 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_O_L_R_.py +165 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_P_A_L_.py +305 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/D_S_I_G_.py +170 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/D__e_b_g.py +35 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/DefaultTable.py +64 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_D_T_.py +856 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_L_C_.py +717 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_S_C_.py +153 -0
- .venv/lib/python3.12/site-packages/fontTools/ttLib/tables/F_F_T_M_.py +52 -0
.gitattributes
CHANGED
|
@@ -164,3 +164,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 164 |
.venv/lib/python3.12/site-packages/fontTools/pens/momentsPen.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 165 |
.venv/lib/python3.12/site-packages/fontTools/qu2cu/qu2cu.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 166 |
.venv/lib/python3.12/site-packages/fontTools/subset/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
.venv/lib/python3.12/site-packages/fontTools/pens/momentsPen.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 165 |
.venv/lib/python3.12/site-packages/fontTools/qu2cu/qu2cu.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 166 |
.venv/lib/python3.12/site-packages/fontTools/subset/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 167 |
+
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otConverters.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 168 |
+
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otData.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 169 |
+
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otTables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 170 |
+
.venv/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 171 |
+
.venv/lib/python3.12/site-packages/fontTools/varLib/iup.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
.venv/lib/python3.12/site-packages/fontTools/svgLib/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .path import SVGPath, parse_path
|
| 2 |
+
|
| 3 |
+
__all__ = ["SVGPath", "parse_path"]
|
.venv/lib/python3.12/site-packages/fontTools/svgLib/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (288 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/svgLib/path/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.pens.transformPen import TransformPen
|
| 2 |
+
from fontTools.misc import etree
|
| 3 |
+
from fontTools.misc.textTools import tostr
|
| 4 |
+
from .parser import parse_path
|
| 5 |
+
from .shapes import PathBuilder
|
| 6 |
+
|
| 7 |
+
__all__ = [tostr(s) for s in ("SVGPath", "parse_path")]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class SVGPath(object):
|
| 11 |
+
"""Parse SVG ``path`` elements from a file or string, and draw them
|
| 12 |
+
onto a glyph object that supports the FontTools Pen protocol.
|
| 13 |
+
|
| 14 |
+
For example, reading from an SVG file and drawing to a Defcon Glyph:
|
| 15 |
+
|
| 16 |
+
.. code-block::
|
| 17 |
+
|
| 18 |
+
import defcon
|
| 19 |
+
glyph = defcon.Glyph()
|
| 20 |
+
pen = glyph.getPen()
|
| 21 |
+
svg = SVGPath("path/to/a.svg")
|
| 22 |
+
svg.draw(pen)
|
| 23 |
+
|
| 24 |
+
Or reading from a string containing SVG data, using the alternative
|
| 25 |
+
'fromstring' (a class method):
|
| 26 |
+
|
| 27 |
+
.. code-block::
|
| 28 |
+
|
| 29 |
+
data = '<?xml version="1.0" ...'
|
| 30 |
+
svg = SVGPath.fromstring(data)
|
| 31 |
+
svg.draw(pen)
|
| 32 |
+
|
| 33 |
+
Both constructors can optionally take a 'transform' matrix (6-float
|
| 34 |
+
tuple, or a FontTools Transform object) to modify the draw output.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self, filename=None, transform=None):
|
| 38 |
+
if filename is None:
|
| 39 |
+
self.root = etree.ElementTree()
|
| 40 |
+
else:
|
| 41 |
+
tree = etree.parse(filename, parser=etree.XMLParser())
|
| 42 |
+
self.root = tree.getroot()
|
| 43 |
+
self.transform = transform
|
| 44 |
+
|
| 45 |
+
@classmethod
|
| 46 |
+
def fromstring(cls, data, transform=None):
|
| 47 |
+
self = cls(transform=transform)
|
| 48 |
+
self.root = etree.fromstring(data, parser=etree.XMLParser())
|
| 49 |
+
return self
|
| 50 |
+
|
| 51 |
+
def draw(self, pen):
|
| 52 |
+
if self.transform:
|
| 53 |
+
pen = TransformPen(pen, self.transform)
|
| 54 |
+
pb = PathBuilder()
|
| 55 |
+
# xpath | doesn't seem to reliable work so just walk it
|
| 56 |
+
for el in self.root.iter():
|
| 57 |
+
pb.add_path_from_element(el)
|
| 58 |
+
original_pen = pen
|
| 59 |
+
for path, transform in zip(pb.paths, pb.transforms):
|
| 60 |
+
if transform:
|
| 61 |
+
pen = TransformPen(original_pen, transform)
|
| 62 |
+
else:
|
| 63 |
+
pen = original_pen
|
| 64 |
+
parse_path(path, pen)
|
.venv/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (3.07 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/arc.cpython-312.pyc
ADDED
|
Binary file (6.59 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/parser.cpython-312.pyc
ADDED
|
Binary file (9.99 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/shapes.cpython-312.pyc
ADDED
|
Binary file (11 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/svgLib/path/arc.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convert SVG Path's elliptical arcs to Bezier curves.
|
| 2 |
+
|
| 3 |
+
The code is mostly adapted from Blink's SVGPathNormalizer::DecomposeArcToCubic
|
| 4 |
+
https://github.com/chromium/chromium/blob/93831f2/third_party/
|
| 5 |
+
blink/renderer/core/svg/svg_path_parser.cc#L169-L278
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from fontTools.misc.transform import Identity, Scale
|
| 9 |
+
from math import atan2, ceil, cos, fabs, isfinite, pi, radians, sin, sqrt, tan
|
| 10 |
+
|
| 11 |
+
TWO_PI = 2 * pi
|
| 12 |
+
PI_OVER_TWO = 0.5 * pi
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _map_point(matrix, pt):
|
| 16 |
+
# apply Transform matrix to a point represented as a complex number
|
| 17 |
+
r = matrix.transformPoint((pt.real, pt.imag))
|
| 18 |
+
return r[0] + r[1] * 1j
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class EllipticalArc(object):
|
| 22 |
+
def __init__(self, current_point, rx, ry, rotation, large, sweep, target_point):
|
| 23 |
+
self.current_point = current_point
|
| 24 |
+
self.rx = rx
|
| 25 |
+
self.ry = ry
|
| 26 |
+
self.rotation = rotation
|
| 27 |
+
self.large = large
|
| 28 |
+
self.sweep = sweep
|
| 29 |
+
self.target_point = target_point
|
| 30 |
+
|
| 31 |
+
# SVG arc's rotation angle is expressed in degrees, whereas Transform.rotate
|
| 32 |
+
# uses radians
|
| 33 |
+
self.angle = radians(rotation)
|
| 34 |
+
|
| 35 |
+
# these derived attributes are computed by the _parametrize method
|
| 36 |
+
self.center_point = self.theta1 = self.theta2 = self.theta_arc = None
|
| 37 |
+
|
| 38 |
+
def _parametrize(self):
|
| 39 |
+
# convert from endopoint to center parametrization:
|
| 40 |
+
# https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
|
| 41 |
+
|
| 42 |
+
# If rx = 0 or ry = 0 then this arc is treated as a straight line segment (a
|
| 43 |
+
# "lineto") joining the endpoints.
|
| 44 |
+
# http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters
|
| 45 |
+
rx = fabs(self.rx)
|
| 46 |
+
ry = fabs(self.ry)
|
| 47 |
+
if not (rx and ry):
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
+
# If the current point and target point for the arc are identical, it should
|
| 51 |
+
# be treated as a zero length path. This ensures continuity in animations.
|
| 52 |
+
if self.target_point == self.current_point:
|
| 53 |
+
return False
|
| 54 |
+
|
| 55 |
+
mid_point_distance = (self.current_point - self.target_point) * 0.5
|
| 56 |
+
|
| 57 |
+
point_transform = Identity.rotate(-self.angle)
|
| 58 |
+
|
| 59 |
+
transformed_mid_point = _map_point(point_transform, mid_point_distance)
|
| 60 |
+
square_rx = rx * rx
|
| 61 |
+
square_ry = ry * ry
|
| 62 |
+
square_x = transformed_mid_point.real * transformed_mid_point.real
|
| 63 |
+
square_y = transformed_mid_point.imag * transformed_mid_point.imag
|
| 64 |
+
|
| 65 |
+
# Check if the radii are big enough to draw the arc, scale radii if not.
|
| 66 |
+
# http://www.w3.org/TR/SVG/implnote.html#ArcCorrectionOutOfRangeRadii
|
| 67 |
+
radii_scale = square_x / square_rx + square_y / square_ry
|
| 68 |
+
if radii_scale > 1:
|
| 69 |
+
rx *= sqrt(radii_scale)
|
| 70 |
+
ry *= sqrt(radii_scale)
|
| 71 |
+
self.rx, self.ry = rx, ry
|
| 72 |
+
|
| 73 |
+
point_transform = Scale(1 / rx, 1 / ry).rotate(-self.angle)
|
| 74 |
+
|
| 75 |
+
point1 = _map_point(point_transform, self.current_point)
|
| 76 |
+
point2 = _map_point(point_transform, self.target_point)
|
| 77 |
+
delta = point2 - point1
|
| 78 |
+
|
| 79 |
+
d = delta.real * delta.real + delta.imag * delta.imag
|
| 80 |
+
scale_factor_squared = max(1 / d - 0.25, 0.0)
|
| 81 |
+
|
| 82 |
+
scale_factor = sqrt(scale_factor_squared)
|
| 83 |
+
if self.sweep == self.large:
|
| 84 |
+
scale_factor = -scale_factor
|
| 85 |
+
|
| 86 |
+
delta *= scale_factor
|
| 87 |
+
center_point = (point1 + point2) * 0.5
|
| 88 |
+
center_point += complex(-delta.imag, delta.real)
|
| 89 |
+
point1 -= center_point
|
| 90 |
+
point2 -= center_point
|
| 91 |
+
|
| 92 |
+
theta1 = atan2(point1.imag, point1.real)
|
| 93 |
+
theta2 = atan2(point2.imag, point2.real)
|
| 94 |
+
|
| 95 |
+
theta_arc = theta2 - theta1
|
| 96 |
+
if theta_arc < 0 and self.sweep:
|
| 97 |
+
theta_arc += TWO_PI
|
| 98 |
+
elif theta_arc > 0 and not self.sweep:
|
| 99 |
+
theta_arc -= TWO_PI
|
| 100 |
+
|
| 101 |
+
self.theta1 = theta1
|
| 102 |
+
self.theta2 = theta1 + theta_arc
|
| 103 |
+
self.theta_arc = theta_arc
|
| 104 |
+
self.center_point = center_point
|
| 105 |
+
|
| 106 |
+
return True
|
| 107 |
+
|
| 108 |
+
def _decompose_to_cubic_curves(self):
|
| 109 |
+
if self.center_point is None and not self._parametrize():
|
| 110 |
+
return
|
| 111 |
+
|
| 112 |
+
point_transform = Identity.rotate(self.angle).scale(self.rx, self.ry)
|
| 113 |
+
|
| 114 |
+
# Some results of atan2 on some platform implementations are not exact
|
| 115 |
+
# enough. So that we get more cubic curves than expected here. Adding 0.001f
|
| 116 |
+
# reduces the count of sgements to the correct count.
|
| 117 |
+
num_segments = int(ceil(fabs(self.theta_arc / (PI_OVER_TWO + 0.001))))
|
| 118 |
+
for i in range(num_segments):
|
| 119 |
+
start_theta = self.theta1 + i * self.theta_arc / num_segments
|
| 120 |
+
end_theta = self.theta1 + (i + 1) * self.theta_arc / num_segments
|
| 121 |
+
|
| 122 |
+
t = (4 / 3) * tan(0.25 * (end_theta - start_theta))
|
| 123 |
+
if not isfinite(t):
|
| 124 |
+
return
|
| 125 |
+
|
| 126 |
+
sin_start_theta = sin(start_theta)
|
| 127 |
+
cos_start_theta = cos(start_theta)
|
| 128 |
+
sin_end_theta = sin(end_theta)
|
| 129 |
+
cos_end_theta = cos(end_theta)
|
| 130 |
+
|
| 131 |
+
point1 = complex(
|
| 132 |
+
cos_start_theta - t * sin_start_theta,
|
| 133 |
+
sin_start_theta + t * cos_start_theta,
|
| 134 |
+
)
|
| 135 |
+
point1 += self.center_point
|
| 136 |
+
target_point = complex(cos_end_theta, sin_end_theta)
|
| 137 |
+
target_point += self.center_point
|
| 138 |
+
point2 = target_point
|
| 139 |
+
point2 += complex(t * sin_end_theta, -t * cos_end_theta)
|
| 140 |
+
|
| 141 |
+
point1 = _map_point(point_transform, point1)
|
| 142 |
+
point2 = _map_point(point_transform, point2)
|
| 143 |
+
target_point = _map_point(point_transform, target_point)
|
| 144 |
+
|
| 145 |
+
yield point1, point2, target_point
|
| 146 |
+
|
| 147 |
+
def draw(self, pen):
|
| 148 |
+
for point1, point2, target_point in self._decompose_to_cubic_curves():
|
| 149 |
+
pen.curveTo(
|
| 150 |
+
(point1.real, point1.imag),
|
| 151 |
+
(point2.real, point2.imag),
|
| 152 |
+
(target_point.real, target_point.imag),
|
| 153 |
+
)
|
.venv/lib/python3.12/site-packages/fontTools/svgLib/path/parser.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SVG Path specification parser.
|
| 2 |
+
# This is an adaptation from 'svg.path' by Lennart Regebro (@regebro),
|
| 3 |
+
# modified so that the parser takes a FontTools Pen object instead of
|
| 4 |
+
# returning a list of svg.path Path objects.
|
| 5 |
+
# The original code can be found at:
|
| 6 |
+
# https://github.com/regebro/svg.path/blob/4f9b6e3/src/svg/path/parser.py
|
| 7 |
+
# Copyright (c) 2013-2014 Lennart Regebro
|
| 8 |
+
# License: MIT
|
| 9 |
+
|
| 10 |
+
from .arc import EllipticalArc
|
| 11 |
+
import cmath
|
| 12 |
+
import re
|
| 13 |
+
|
| 14 |
+
COMMANDS = set("MmZzLlHhVvCcSsQqTtAa")
|
| 15 |
+
ARC_COMMANDS = set("Aa")
|
| 16 |
+
UPPERCASE = set("MZLHVCSQTA")
|
| 17 |
+
|
| 18 |
+
COMMAND_RE = re.compile("([MmZzLlHhVvCcSsQqTtAa])")
|
| 19 |
+
|
| 20 |
+
# https://www.w3.org/TR/css-syntax-3/#number-token-diagram
|
| 21 |
+
# but -6.e-5 will be tokenized as "-6" then "-5" and confuse parsing
|
| 22 |
+
FLOAT_RE = re.compile(
|
| 23 |
+
r"[-+]?" # optional sign
|
| 24 |
+
r"(?:"
|
| 25 |
+
r"(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?" # int/float
|
| 26 |
+
r"|"
|
| 27 |
+
r"(?:\.[0-9]+(?:[eE][-+]?[0-9]+)?)" # float with leading dot (e.g. '.42')
|
| 28 |
+
r")"
|
| 29 |
+
)
|
| 30 |
+
BOOL_RE = re.compile("^[01]")
|
| 31 |
+
SEPARATOR_RE = re.compile(f"[, \t]")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _tokenize_path(pathdef):
|
| 35 |
+
arc_cmd = None
|
| 36 |
+
for x in COMMAND_RE.split(pathdef):
|
| 37 |
+
if x in COMMANDS:
|
| 38 |
+
arc_cmd = x if x in ARC_COMMANDS else None
|
| 39 |
+
yield x
|
| 40 |
+
continue
|
| 41 |
+
|
| 42 |
+
if arc_cmd:
|
| 43 |
+
try:
|
| 44 |
+
yield from _tokenize_arc_arguments(x)
|
| 45 |
+
except ValueError as e:
|
| 46 |
+
raise ValueError(f"Invalid arc command: '{arc_cmd}{x}'") from e
|
| 47 |
+
else:
|
| 48 |
+
for token in FLOAT_RE.findall(x):
|
| 49 |
+
yield token
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
ARC_ARGUMENT_TYPES = (
|
| 53 |
+
("rx", FLOAT_RE),
|
| 54 |
+
("ry", FLOAT_RE),
|
| 55 |
+
("x-axis-rotation", FLOAT_RE),
|
| 56 |
+
("large-arc-flag", BOOL_RE),
|
| 57 |
+
("sweep-flag", BOOL_RE),
|
| 58 |
+
("x", FLOAT_RE),
|
| 59 |
+
("y", FLOAT_RE),
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _tokenize_arc_arguments(arcdef):
|
| 64 |
+
raw_args = [s for s in SEPARATOR_RE.split(arcdef) if s]
|
| 65 |
+
if not raw_args:
|
| 66 |
+
raise ValueError(f"Not enough arguments: '{arcdef}'")
|
| 67 |
+
raw_args.reverse()
|
| 68 |
+
|
| 69 |
+
i = 0
|
| 70 |
+
while raw_args:
|
| 71 |
+
arg = raw_args.pop()
|
| 72 |
+
|
| 73 |
+
name, pattern = ARC_ARGUMENT_TYPES[i]
|
| 74 |
+
match = pattern.search(arg)
|
| 75 |
+
if not match:
|
| 76 |
+
raise ValueError(f"Invalid argument for '{name}' parameter: {arg!r}")
|
| 77 |
+
|
| 78 |
+
j, k = match.span()
|
| 79 |
+
yield arg[j:k]
|
| 80 |
+
arg = arg[k:]
|
| 81 |
+
|
| 82 |
+
if arg:
|
| 83 |
+
raw_args.append(arg)
|
| 84 |
+
|
| 85 |
+
# wrap around every 7 consecutive arguments
|
| 86 |
+
if i == 6:
|
| 87 |
+
i = 0
|
| 88 |
+
else:
|
| 89 |
+
i += 1
|
| 90 |
+
|
| 91 |
+
if i != 0:
|
| 92 |
+
raise ValueError(f"Not enough arguments: '{arcdef}'")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def parse_path(pathdef, pen, current_pos=(0, 0), arc_class=EllipticalArc):
|
| 96 |
+
"""Parse SVG path definition (i.e. "d" attribute of <path> elements)
|
| 97 |
+
and call a 'pen' object's moveTo, lineTo, curveTo, qCurveTo and closePath
|
| 98 |
+
methods.
|
| 99 |
+
|
| 100 |
+
If 'current_pos' (2-float tuple) is provided, the initial moveTo will
|
| 101 |
+
be relative to that instead being absolute.
|
| 102 |
+
|
| 103 |
+
If the pen has an "arcTo" method, it is called with the original values
|
| 104 |
+
of the elliptical arc curve commands:
|
| 105 |
+
|
| 106 |
+
.. code-block::
|
| 107 |
+
|
| 108 |
+
pen.arcTo(rx, ry, rotation, arc_large, arc_sweep, (x, y))
|
| 109 |
+
|
| 110 |
+
Otherwise, the arcs are approximated by series of cubic Bezier segments
|
| 111 |
+
("curveTo"), one every 90 degrees.
|
| 112 |
+
"""
|
| 113 |
+
# In the SVG specs, initial movetos are absolute, even if
|
| 114 |
+
# specified as 'm'. This is the default behavior here as well.
|
| 115 |
+
# But if you pass in a current_pos variable, the initial moveto
|
| 116 |
+
# will be relative to that current_pos. This is useful.
|
| 117 |
+
current_pos = complex(*current_pos)
|
| 118 |
+
|
| 119 |
+
elements = list(_tokenize_path(pathdef))
|
| 120 |
+
# Reverse for easy use of .pop()
|
| 121 |
+
elements.reverse()
|
| 122 |
+
|
| 123 |
+
# A path data segment (if there is one) must begin with a moveto
|
| 124 |
+
# command (https://www.w3.org/TR/SVG11/paths.html#PathDataMovetoCommands);
|
| 125 |
+
# raise before any pen call instead of inventing a start point.
|
| 126 |
+
if elements and elements[-1] not in ("M", "m"):
|
| 127 |
+
raise ValueError("Path must start with a moveto command: %r" % pathdef)
|
| 128 |
+
|
| 129 |
+
# start_pos is the initial point of the current subpath; it is retained
|
| 130 |
+
# after a closepath so that a drawto command following Z can start a new
|
| 131 |
+
# subpath at that same point, while subpath_open tracks whether there is
|
| 132 |
+
# a subpath in progress that still needs closePath/endPath.
|
| 133 |
+
start_pos = None
|
| 134 |
+
subpath_open = False
|
| 135 |
+
command = None
|
| 136 |
+
last_control = None
|
| 137 |
+
|
| 138 |
+
have_arcTo = hasattr(pen, "arcTo")
|
| 139 |
+
|
| 140 |
+
while elements:
|
| 141 |
+
if elements[-1] in COMMANDS:
|
| 142 |
+
# New command.
|
| 143 |
+
last_command = command # Used by S and T
|
| 144 |
+
command = elements.pop()
|
| 145 |
+
absolute = command in UPPERCASE
|
| 146 |
+
command = command.upper()
|
| 147 |
+
else:
|
| 148 |
+
# If this element starts with numbers, it is an implicit command
|
| 149 |
+
# and we don't change the command. Check that it's allowed:
|
| 150 |
+
if command is None:
|
| 151 |
+
raise ValueError(
|
| 152 |
+
"Unallowed implicit command in %s, position %s"
|
| 153 |
+
% (pathdef, len(pathdef.split()) - len(elements))
|
| 154 |
+
)
|
| 155 |
+
last_command = command # Used by S and T
|
| 156 |
+
|
| 157 |
+
if command not in ("M", "Z") and not subpath_open and start_pos is not None:
|
| 158 |
+
# If a closepath is followed immediately by any other command,
|
| 159 |
+
# the next subpath starts at the same initial point as the
|
| 160 |
+
# current subpath:
|
| 161 |
+
# https://www.w3.org/TR/SVG11/paths.html#PathDataClosePathCommand
|
| 162 |
+
pen.moveTo((start_pos.real, start_pos.imag))
|
| 163 |
+
subpath_open = True
|
| 164 |
+
|
| 165 |
+
if command == "M":
|
| 166 |
+
# Moveto command.
|
| 167 |
+
x = elements.pop()
|
| 168 |
+
y = elements.pop()
|
| 169 |
+
pos = float(x) + float(y) * 1j
|
| 170 |
+
if absolute:
|
| 171 |
+
current_pos = pos
|
| 172 |
+
else:
|
| 173 |
+
current_pos += pos
|
| 174 |
+
|
| 175 |
+
# M is not preceded by Z; it's an open subpath
|
| 176 |
+
if subpath_open:
|
| 177 |
+
pen.endPath()
|
| 178 |
+
|
| 179 |
+
pen.moveTo((current_pos.real, current_pos.imag))
|
| 180 |
+
|
| 181 |
+
# when M is called, reset start_pos
|
| 182 |
+
# This behavior of Z is defined in svg spec:
|
| 183 |
+
# http://www.w3.org/TR/SVG/paths.html#PathDataClosePathCommand
|
| 184 |
+
start_pos = current_pos
|
| 185 |
+
subpath_open = True
|
| 186 |
+
|
| 187 |
+
# Implicit moveto commands are treated as lineto commands.
|
| 188 |
+
# So we set command to lineto here, in case there are
|
| 189 |
+
# further implicit commands after this moveto.
|
| 190 |
+
command = "L"
|
| 191 |
+
|
| 192 |
+
elif command == "Z":
|
| 193 |
+
# Close path
|
| 194 |
+
# A redundant Z with no open subpath (e.g. "M0,0 Z Z") is valid
|
| 195 |
+
# per the SVG path grammar and has no effect; ignore it instead
|
| 196 |
+
# of emitting a second closePath.
|
| 197 |
+
if subpath_open:
|
| 198 |
+
if not cmath.isclose(
|
| 199 |
+
current_pos, start_pos, rel_tol=1e-15, abs_tol=1e-15
|
| 200 |
+
):
|
| 201 |
+
pen.lineTo((start_pos.real, start_pos.imag))
|
| 202 |
+
pen.closePath()
|
| 203 |
+
current_pos = start_pos
|
| 204 |
+
subpath_open = False
|
| 205 |
+
command = None # You can't have implicit commands after closing.
|
| 206 |
+
|
| 207 |
+
elif command == "L":
|
| 208 |
+
x = elements.pop()
|
| 209 |
+
y = elements.pop()
|
| 210 |
+
pos = float(x) + float(y) * 1j
|
| 211 |
+
if not absolute:
|
| 212 |
+
pos += current_pos
|
| 213 |
+
pen.lineTo((pos.real, pos.imag))
|
| 214 |
+
current_pos = pos
|
| 215 |
+
|
| 216 |
+
elif command == "H":
|
| 217 |
+
x = elements.pop()
|
| 218 |
+
pos = float(x) + current_pos.imag * 1j
|
| 219 |
+
if not absolute:
|
| 220 |
+
pos += current_pos.real
|
| 221 |
+
pen.lineTo((pos.real, pos.imag))
|
| 222 |
+
current_pos = pos
|
| 223 |
+
|
| 224 |
+
elif command == "V":
|
| 225 |
+
y = elements.pop()
|
| 226 |
+
pos = current_pos.real + float(y) * 1j
|
| 227 |
+
if not absolute:
|
| 228 |
+
pos += current_pos.imag * 1j
|
| 229 |
+
pen.lineTo((pos.real, pos.imag))
|
| 230 |
+
current_pos = pos
|
| 231 |
+
|
| 232 |
+
elif command == "C":
|
| 233 |
+
control1 = float(elements.pop()) + float(elements.pop()) * 1j
|
| 234 |
+
control2 = float(elements.pop()) + float(elements.pop()) * 1j
|
| 235 |
+
end = float(elements.pop()) + float(elements.pop()) * 1j
|
| 236 |
+
|
| 237 |
+
if not absolute:
|
| 238 |
+
control1 += current_pos
|
| 239 |
+
control2 += current_pos
|
| 240 |
+
end += current_pos
|
| 241 |
+
|
| 242 |
+
pen.curveTo(
|
| 243 |
+
(control1.real, control1.imag),
|
| 244 |
+
(control2.real, control2.imag),
|
| 245 |
+
(end.real, end.imag),
|
| 246 |
+
)
|
| 247 |
+
current_pos = end
|
| 248 |
+
last_control = control2
|
| 249 |
+
|
| 250 |
+
elif command == "S":
|
| 251 |
+
# Smooth curve. First control point is the "reflection" of
|
| 252 |
+
# the second control point in the previous path.
|
| 253 |
+
|
| 254 |
+
# last_command is None right after a closepath (Z is not C/S)
|
| 255 |
+
if last_command not in ("C", "S"):
|
| 256 |
+
# If there is no previous command or if the previous command
|
| 257 |
+
# was not an C, c, S or s, assume the first control point is
|
| 258 |
+
# coincident with the current point.
|
| 259 |
+
control1 = current_pos
|
| 260 |
+
else:
|
| 261 |
+
# The first control point is assumed to be the reflection of
|
| 262 |
+
# the second control point on the previous command relative
|
| 263 |
+
# to the current point.
|
| 264 |
+
control1 = current_pos + current_pos - last_control
|
| 265 |
+
|
| 266 |
+
control2 = float(elements.pop()) + float(elements.pop()) * 1j
|
| 267 |
+
end = float(elements.pop()) + float(elements.pop()) * 1j
|
| 268 |
+
|
| 269 |
+
if not absolute:
|
| 270 |
+
control2 += current_pos
|
| 271 |
+
end += current_pos
|
| 272 |
+
|
| 273 |
+
pen.curveTo(
|
| 274 |
+
(control1.real, control1.imag),
|
| 275 |
+
(control2.real, control2.imag),
|
| 276 |
+
(end.real, end.imag),
|
| 277 |
+
)
|
| 278 |
+
current_pos = end
|
| 279 |
+
last_control = control2
|
| 280 |
+
|
| 281 |
+
elif command == "Q":
|
| 282 |
+
control = float(elements.pop()) + float(elements.pop()) * 1j
|
| 283 |
+
end = float(elements.pop()) + float(elements.pop()) * 1j
|
| 284 |
+
|
| 285 |
+
if not absolute:
|
| 286 |
+
control += current_pos
|
| 287 |
+
end += current_pos
|
| 288 |
+
|
| 289 |
+
pen.qCurveTo((control.real, control.imag), (end.real, end.imag))
|
| 290 |
+
current_pos = end
|
| 291 |
+
last_control = control
|
| 292 |
+
|
| 293 |
+
elif command == "T":
|
| 294 |
+
# Smooth curve. Control point is the "reflection" of
|
| 295 |
+
# the second control point in the previous path.
|
| 296 |
+
|
| 297 |
+
# last_command is None right after a closepath (Z is not Q/T)
|
| 298 |
+
if last_command not in ("Q", "T"):
|
| 299 |
+
# If there is no previous command or if the previous command
|
| 300 |
+
# was not an Q, q, T or t, assume the first control point is
|
| 301 |
+
# coincident with the current point.
|
| 302 |
+
control = current_pos
|
| 303 |
+
else:
|
| 304 |
+
# The control point is assumed to be the reflection of
|
| 305 |
+
# the control point on the previous command relative
|
| 306 |
+
# to the current point.
|
| 307 |
+
control = current_pos + current_pos - last_control
|
| 308 |
+
|
| 309 |
+
end = float(elements.pop()) + float(elements.pop()) * 1j
|
| 310 |
+
|
| 311 |
+
if not absolute:
|
| 312 |
+
end += current_pos
|
| 313 |
+
|
| 314 |
+
pen.qCurveTo((control.real, control.imag), (end.real, end.imag))
|
| 315 |
+
current_pos = end
|
| 316 |
+
last_control = control
|
| 317 |
+
|
| 318 |
+
elif command == "A":
|
| 319 |
+
rx = abs(float(elements.pop()))
|
| 320 |
+
ry = abs(float(elements.pop()))
|
| 321 |
+
rotation = float(elements.pop())
|
| 322 |
+
arc_large = bool(int(elements.pop()))
|
| 323 |
+
arc_sweep = bool(int(elements.pop()))
|
| 324 |
+
end = float(elements.pop()) + float(elements.pop()) * 1j
|
| 325 |
+
|
| 326 |
+
if not absolute:
|
| 327 |
+
end += current_pos
|
| 328 |
+
|
| 329 |
+
# if the pen supports arcs, pass the values unchanged, otherwise
|
| 330 |
+
# approximate the arc with a series of cubic bezier curves
|
| 331 |
+
if have_arcTo:
|
| 332 |
+
pen.arcTo(
|
| 333 |
+
rx,
|
| 334 |
+
ry,
|
| 335 |
+
rotation,
|
| 336 |
+
arc_large,
|
| 337 |
+
arc_sweep,
|
| 338 |
+
(end.real, end.imag),
|
| 339 |
+
)
|
| 340 |
+
else:
|
| 341 |
+
arc = arc_class(
|
| 342 |
+
current_pos, rx, ry, rotation, arc_large, arc_sweep, end
|
| 343 |
+
)
|
| 344 |
+
arc.draw(pen)
|
| 345 |
+
|
| 346 |
+
current_pos = end
|
| 347 |
+
|
| 348 |
+
# no final Z command, it's an open path
|
| 349 |
+
if subpath_open:
|
| 350 |
+
pen.endPath()
|
.venv/lib/python3.12/site-packages/fontTools/svgLib/path/shapes.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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0's, %g isn't consistent about # decimals
|
| 13 |
+
return ("%.3f" % n).rstrip("0").rstrip(".")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _strip_xml_ns(tag):
|
| 17 |
+
# ElementTree API doesn't provide a way to ignore XML namespaces in tags
|
| 18 |
+
# so we here strip them ourselves: cf. https://bugs.python.org/issue18304
|
| 19 |
+
return tag.split("}", 1)[1] if "}" in tag else tag
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _transform(raw_value):
|
| 23 |
+
# TODO assumes a 'matrix' transform.
|
| 24 |
+
# No other transform functions are supported at the moment.
|
| 25 |
+
# https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform
|
| 26 |
+
# start simple: if you aren't exactly matrix(...) then no love
|
| 27 |
+
match = re.match(r"matrix\((.*)\)", raw_value)
|
| 28 |
+
if not match:
|
| 29 |
+
raise NotImplementedError
|
| 30 |
+
matrix = tuple(float(p) for p in re.split(r"\s+|,", match.group(1)))
|
| 31 |
+
if len(matrix) != 6:
|
| 32 |
+
raise ValueError("wrong # of terms in %s" % raw_value)
|
| 33 |
+
return matrix
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class PathBuilder(object):
|
| 37 |
+
def __init__(self):
|
| 38 |
+
self.paths = []
|
| 39 |
+
self.transforms = []
|
| 40 |
+
|
| 41 |
+
def _start_path(self, initial_path=""):
|
| 42 |
+
self.paths.append(initial_path)
|
| 43 |
+
self.transforms.append(None)
|
| 44 |
+
|
| 45 |
+
def _end_path(self):
|
| 46 |
+
self._add("z")
|
| 47 |
+
|
| 48 |
+
def _add(self, path_snippet):
|
| 49 |
+
path = self.paths[-1]
|
| 50 |
+
if path:
|
| 51 |
+
path += " " + path_snippet
|
| 52 |
+
else:
|
| 53 |
+
path = path_snippet
|
| 54 |
+
self.paths[-1] = path
|
| 55 |
+
|
| 56 |
+
def _move(self, c, x, y):
|
| 57 |
+
self._add("%s%s,%s" % (c, _ntos(x), _ntos(y)))
|
| 58 |
+
|
| 59 |
+
def M(self, x, y):
|
| 60 |
+
self._move("M", x, y)
|
| 61 |
+
|
| 62 |
+
def m(self, x, y):
|
| 63 |
+
self._move("m", x, y)
|
| 64 |
+
|
| 65 |
+
def _arc(self, c, rx, ry, x, y, large_arc):
|
| 66 |
+
self._add(
|
| 67 |
+
"%s%s,%s 0 %d 1 %s,%s"
|
| 68 |
+
% (c, _ntos(rx), _ntos(ry), large_arc, _ntos(x), _ntos(y))
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
def A(self, rx, ry, x, y, large_arc=0):
|
| 72 |
+
self._arc("A", rx, ry, x, y, large_arc)
|
| 73 |
+
|
| 74 |
+
def a(self, rx, ry, x, y, large_arc=0):
|
| 75 |
+
self._arc("a", rx, ry, x, y, large_arc)
|
| 76 |
+
|
| 77 |
+
def _vhline(self, c, x):
|
| 78 |
+
self._add("%s%s" % (c, _ntos(x)))
|
| 79 |
+
|
| 80 |
+
def H(self, x):
|
| 81 |
+
self._vhline("H", x)
|
| 82 |
+
|
| 83 |
+
def h(self, x):
|
| 84 |
+
self._vhline("h", x)
|
| 85 |
+
|
| 86 |
+
def V(self, y):
|
| 87 |
+
self._vhline("V", y)
|
| 88 |
+
|
| 89 |
+
def v(self, y):
|
| 90 |
+
self._vhline("v", y)
|
| 91 |
+
|
| 92 |
+
def _line(self, c, x, y):
|
| 93 |
+
self._add("%s%s,%s" % (c, _ntos(x), _ntos(y)))
|
| 94 |
+
|
| 95 |
+
def L(self, x, y):
|
| 96 |
+
self._line("L", x, y)
|
| 97 |
+
|
| 98 |
+
def l(self, x, y):
|
| 99 |
+
self._line("l", x, y)
|
| 100 |
+
|
| 101 |
+
def _parse_line(self, line):
|
| 102 |
+
x1 = float(line.attrib.get("x1", 0))
|
| 103 |
+
y1 = float(line.attrib.get("y1", 0))
|
| 104 |
+
x2 = float(line.attrib.get("x2", 0))
|
| 105 |
+
y2 = float(line.attrib.get("y2", 0))
|
| 106 |
+
|
| 107 |
+
self._start_path()
|
| 108 |
+
self.M(x1, y1)
|
| 109 |
+
self.L(x2, y2)
|
| 110 |
+
|
| 111 |
+
def _parse_rect(self, rect):
|
| 112 |
+
x = float(rect.attrib.get("x", 0))
|
| 113 |
+
y = float(rect.attrib.get("y", 0))
|
| 114 |
+
w = float(rect.attrib.get("width"))
|
| 115 |
+
h = float(rect.attrib.get("height"))
|
| 116 |
+
rx = float(rect.attrib.get("rx", 0))
|
| 117 |
+
ry = float(rect.attrib.get("ry", 0))
|
| 118 |
+
|
| 119 |
+
rx = _prefer_non_zero(rx, ry)
|
| 120 |
+
ry = _prefer_non_zero(ry, rx)
|
| 121 |
+
# TODO there are more rules for adjusting rx, ry
|
| 122 |
+
|
| 123 |
+
self._start_path()
|
| 124 |
+
self.M(x + rx, y)
|
| 125 |
+
self.H(x + w - rx)
|
| 126 |
+
if rx > 0:
|
| 127 |
+
self.A(rx, ry, x + w, y + ry)
|
| 128 |
+
self.V(y + h - ry)
|
| 129 |
+
if rx > 0:
|
| 130 |
+
self.A(rx, ry, x + w - rx, y + h)
|
| 131 |
+
self.H(x + rx)
|
| 132 |
+
if rx > 0:
|
| 133 |
+
self.A(rx, ry, x, y + h - ry)
|
| 134 |
+
self.V(y + ry)
|
| 135 |
+
if rx > 0:
|
| 136 |
+
self.A(rx, ry, x + rx, y)
|
| 137 |
+
self._end_path()
|
| 138 |
+
|
| 139 |
+
def _parse_path(self, path):
|
| 140 |
+
if "d" in path.attrib:
|
| 141 |
+
self._start_path(initial_path=path.attrib["d"])
|
| 142 |
+
|
| 143 |
+
def _parse_polygon(self, poly):
|
| 144 |
+
if "points" in poly.attrib:
|
| 145 |
+
self._start_path("M" + poly.attrib["points"])
|
| 146 |
+
self._end_path()
|
| 147 |
+
|
| 148 |
+
def _parse_polyline(self, poly):
|
| 149 |
+
if "points" in poly.attrib:
|
| 150 |
+
self._start_path("M" + poly.attrib["points"])
|
| 151 |
+
|
| 152 |
+
def _parse_circle(self, circle):
|
| 153 |
+
cx = float(circle.attrib.get("cx", 0))
|
| 154 |
+
cy = float(circle.attrib.get("cy", 0))
|
| 155 |
+
r = float(circle.attrib.get("r"))
|
| 156 |
+
|
| 157 |
+
# arc doesn't seem to like being a complete shape, draw two halves
|
| 158 |
+
self._start_path()
|
| 159 |
+
self.M(cx - r, cy)
|
| 160 |
+
self.A(r, r, cx + r, cy, large_arc=1)
|
| 161 |
+
self.A(r, r, cx - r, cy, large_arc=1)
|
| 162 |
+
|
| 163 |
+
def _parse_ellipse(self, ellipse):
|
| 164 |
+
cx = float(ellipse.attrib.get("cx", 0))
|
| 165 |
+
cy = float(ellipse.attrib.get("cy", 0))
|
| 166 |
+
rx = float(ellipse.attrib.get("rx"))
|
| 167 |
+
ry = float(ellipse.attrib.get("ry"))
|
| 168 |
+
|
| 169 |
+
# arc doesn't seem to like being a complete shape, draw two halves
|
| 170 |
+
self._start_path()
|
| 171 |
+
self.M(cx - rx, cy)
|
| 172 |
+
self.A(rx, ry, cx + rx, cy, large_arc=1)
|
| 173 |
+
self.A(rx, ry, cx - rx, cy, large_arc=1)
|
| 174 |
+
|
| 175 |
+
def add_path_from_element(self, el):
|
| 176 |
+
if not isinstance(el.tag, str):
|
| 177 |
+
return False
|
| 178 |
+
tag = _strip_xml_ns(el.tag)
|
| 179 |
+
parse_fn = getattr(self, "_parse_%s" % tag.lower(), None)
|
| 180 |
+
if not callable(parse_fn):
|
| 181 |
+
return False
|
| 182 |
+
parse_fn(el)
|
| 183 |
+
if "transform" in el.attrib:
|
| 184 |
+
self.transforms[-1] = _transform(el.attrib["transform"])
|
| 185 |
+
return True
|
.venv/lib/python3.12/site-packages/fontTools/t1Lib/__init__.py
ADDED
|
@@ -0,0 +1,648 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""fontTools.t1Lib.py -- Tools for PostScript Type 1 fonts.
|
| 2 |
+
|
| 3 |
+
Functions for reading and writing raw Type 1 data:
|
| 4 |
+
|
| 5 |
+
read(path)
|
| 6 |
+
reads any Type 1 font file, returns the raw data and a type indicator:
|
| 7 |
+
'LWFN', 'PFB' or 'OTHER', depending on the format of the file pointed
|
| 8 |
+
to by 'path'.
|
| 9 |
+
Raises an error when the file does not contain valid Type 1 data.
|
| 10 |
+
|
| 11 |
+
write(path, data, kind='OTHER', dohex=False)
|
| 12 |
+
writes raw Type 1 data to the file pointed to by 'path'.
|
| 13 |
+
'kind' can be one of 'LWFN', 'PFB' or 'OTHER'; it defaults to 'OTHER'.
|
| 14 |
+
'dohex' is a flag which determines whether the eexec encrypted
|
| 15 |
+
part should be written as hexadecimal or binary, but only if kind
|
| 16 |
+
is 'OTHER'.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import fontTools
|
| 20 |
+
from fontTools.misc import eexec
|
| 21 |
+
from fontTools.misc.macCreatorType import getMacCreatorAndType
|
| 22 |
+
from fontTools.misc.textTools import bytechr, byteord, bytesjoin, tobytes
|
| 23 |
+
from fontTools.misc.psOperators import (
|
| 24 |
+
_type1_pre_eexec_order,
|
| 25 |
+
_type1_fontinfo_order,
|
| 26 |
+
_type1_post_eexec_order,
|
| 27 |
+
)
|
| 28 |
+
from fontTools.encodings.StandardEncoding import StandardEncoding
|
| 29 |
+
import os
|
| 30 |
+
import re
|
| 31 |
+
|
| 32 |
+
__author__ = "jvr"
|
| 33 |
+
__version__ = "1.0b3"
|
| 34 |
+
DEBUG = 0
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
try:
|
| 39 |
+
from Carbon import Res
|
| 40 |
+
except ImportError:
|
| 41 |
+
import Res # MacPython < 2.2
|
| 42 |
+
except ImportError:
|
| 43 |
+
haveMacSupport = 0
|
| 44 |
+
else:
|
| 45 |
+
haveMacSupport = 1
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class T1Error(Exception):
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class T1Font(object):
|
| 53 |
+
"""Type 1 font class.
|
| 54 |
+
|
| 55 |
+
Uses a minimal interpeter that supports just about enough PS to parse
|
| 56 |
+
Type 1 fonts.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(self, path, encoding="ascii", kind=None):
|
| 60 |
+
if kind is None:
|
| 61 |
+
self.data, _ = read(path)
|
| 62 |
+
elif kind == "LWFN":
|
| 63 |
+
self.data = readLWFN(path)
|
| 64 |
+
elif kind == "PFB":
|
| 65 |
+
self.data = readPFB(path)
|
| 66 |
+
elif kind == "OTHER":
|
| 67 |
+
self.data = readOther(path)
|
| 68 |
+
else:
|
| 69 |
+
raise ValueError(kind)
|
| 70 |
+
self.encoding = encoding
|
| 71 |
+
|
| 72 |
+
def saveAs(self, path, type, dohex=False):
|
| 73 |
+
write(path, self.getData(), type, dohex)
|
| 74 |
+
|
| 75 |
+
def getData(self):
|
| 76 |
+
if not hasattr(self, "data"):
|
| 77 |
+
self.data = self.createData()
|
| 78 |
+
return self.data
|
| 79 |
+
|
| 80 |
+
def getGlyphSet(self):
|
| 81 |
+
"""Return a generic GlyphSet, which is a dict-like object
|
| 82 |
+
mapping glyph names to glyph objects. The returned glyph objects
|
| 83 |
+
have a .draw() method that supports the Pen protocol, and will
|
| 84 |
+
have an attribute named 'width', but only *after* the .draw() method
|
| 85 |
+
has been called.
|
| 86 |
+
|
| 87 |
+
In the case of Type 1, the GlyphSet is simply the CharStrings dict.
|
| 88 |
+
"""
|
| 89 |
+
return self["CharStrings"]
|
| 90 |
+
|
| 91 |
+
def __getitem__(self, key):
|
| 92 |
+
if not hasattr(self, "font"):
|
| 93 |
+
self.parse()
|
| 94 |
+
return self.font[key]
|
| 95 |
+
|
| 96 |
+
def parse(self):
|
| 97 |
+
from fontTools.misc import psLib
|
| 98 |
+
from fontTools.misc import psCharStrings
|
| 99 |
+
|
| 100 |
+
self.font = psLib.suckfont(self.data, self.encoding)
|
| 101 |
+
charStrings = self.font["CharStrings"]
|
| 102 |
+
lenIV = self.font["Private"].get("lenIV", 4)
|
| 103 |
+
assert lenIV >= 0
|
| 104 |
+
subrs = self.font["Private"]["Subrs"]
|
| 105 |
+
for glyphName, charString in charStrings.items():
|
| 106 |
+
charString, R = eexec.decrypt(charString, 4330)
|
| 107 |
+
charStrings[glyphName] = psCharStrings.T1CharString(
|
| 108 |
+
charString[lenIV:], subrs=subrs
|
| 109 |
+
)
|
| 110 |
+
for i in range(len(subrs)):
|
| 111 |
+
charString, R = eexec.decrypt(subrs[i], 4330)
|
| 112 |
+
subrs[i] = psCharStrings.T1CharString(charString[lenIV:], subrs=subrs)
|
| 113 |
+
del self.data
|
| 114 |
+
|
| 115 |
+
def createData(self):
|
| 116 |
+
sf = self.font
|
| 117 |
+
|
| 118 |
+
eexec_began = False
|
| 119 |
+
eexec_dict = {}
|
| 120 |
+
lines = []
|
| 121 |
+
lines.extend(
|
| 122 |
+
[
|
| 123 |
+
self._tobytes(f"%!FontType1-1.1: {sf['FontName']}"),
|
| 124 |
+
self._tobytes(f"%t1Font: ({fontTools.version})"),
|
| 125 |
+
self._tobytes(f"%%BeginResource: font {sf['FontName']}"),
|
| 126 |
+
]
|
| 127 |
+
)
|
| 128 |
+
# follow t1write.c:writeRegNameKeyedFont
|
| 129 |
+
size = 3 # Headroom for new key addition
|
| 130 |
+
size += 1 # FontMatrix is always counted
|
| 131 |
+
size += 1 + 1 # Private, CharStings
|
| 132 |
+
for key in font_dictionary_keys:
|
| 133 |
+
size += int(key in sf)
|
| 134 |
+
lines.append(self._tobytes(f"{size} dict dup begin"))
|
| 135 |
+
|
| 136 |
+
for key, value in sf.items():
|
| 137 |
+
if eexec_began:
|
| 138 |
+
eexec_dict[key] = value
|
| 139 |
+
continue
|
| 140 |
+
|
| 141 |
+
if key == "FontInfo":
|
| 142 |
+
fi = sf["FontInfo"]
|
| 143 |
+
# follow t1write.c:writeFontInfoDict
|
| 144 |
+
size = 3 # Headroom for new key addition
|
| 145 |
+
for subkey in FontInfo_dictionary_keys:
|
| 146 |
+
size += int(subkey in fi)
|
| 147 |
+
lines.append(self._tobytes(f"/FontInfo {size} dict dup begin"))
|
| 148 |
+
|
| 149 |
+
for subkey, subvalue in fi.items():
|
| 150 |
+
lines.extend(self._make_lines(subkey, subvalue))
|
| 151 |
+
lines.append(b"end def")
|
| 152 |
+
elif key in _type1_post_eexec_order: # usually 'Private'
|
| 153 |
+
eexec_dict[key] = value
|
| 154 |
+
eexec_began = True
|
| 155 |
+
else:
|
| 156 |
+
lines.extend(self._make_lines(key, value))
|
| 157 |
+
lines.append(b"end")
|
| 158 |
+
eexec_portion = self.encode_eexec(eexec_dict)
|
| 159 |
+
lines.append(bytesjoin([b"currentfile eexec ", eexec_portion]))
|
| 160 |
+
|
| 161 |
+
for _ in range(8):
|
| 162 |
+
lines.append(self._tobytes("0" * 64))
|
| 163 |
+
lines.extend([b"cleartomark", b"%%EndResource", b"%%EOF"])
|
| 164 |
+
|
| 165 |
+
data = bytesjoin(lines, "\n")
|
| 166 |
+
return data
|
| 167 |
+
|
| 168 |
+
def encode_eexec(self, eexec_dict):
|
| 169 |
+
lines = []
|
| 170 |
+
|
| 171 |
+
# '-|', '|-', '|'
|
| 172 |
+
RD_key, ND_key, NP_key = None, None, None
|
| 173 |
+
lenIV = 4
|
| 174 |
+
subrs = std_subrs
|
| 175 |
+
|
| 176 |
+
# Ensure we look at Private first, because we need RD_key, ND_key, NP_key and lenIV
|
| 177 |
+
sortedItems = sorted(eexec_dict.items(), key=lambda item: item[0] != "Private")
|
| 178 |
+
|
| 179 |
+
for key, value in sortedItems:
|
| 180 |
+
if key == "Private":
|
| 181 |
+
pr = eexec_dict["Private"]
|
| 182 |
+
# follow t1write.c:writePrivateDict
|
| 183 |
+
size = 3 # for RD, ND, NP
|
| 184 |
+
for subkey in Private_dictionary_keys:
|
| 185 |
+
size += int(subkey in pr)
|
| 186 |
+
lines.append(b"dup /Private")
|
| 187 |
+
lines.append(self._tobytes(f"{size} dict dup begin"))
|
| 188 |
+
for subkey, subvalue in pr.items():
|
| 189 |
+
if not RD_key and subvalue == RD_value:
|
| 190 |
+
RD_key = subkey
|
| 191 |
+
elif not ND_key and subvalue in ND_values:
|
| 192 |
+
ND_key = subkey
|
| 193 |
+
elif not NP_key and subvalue in PD_values:
|
| 194 |
+
NP_key = subkey
|
| 195 |
+
|
| 196 |
+
if subkey == "lenIV":
|
| 197 |
+
lenIV = subvalue
|
| 198 |
+
|
| 199 |
+
if subkey == "OtherSubrs":
|
| 200 |
+
# XXX: assert that no flex hint is used
|
| 201 |
+
lines.append(self._tobytes(hintothers))
|
| 202 |
+
elif subkey == "Subrs":
|
| 203 |
+
for subr_bin in subvalue:
|
| 204 |
+
subr_bin.compile()
|
| 205 |
+
subrs = [subr_bin.bytecode for subr_bin in subvalue]
|
| 206 |
+
lines.append(f"/Subrs {len(subrs)} array".encode("ascii"))
|
| 207 |
+
for i, subr_bin in enumerate(subrs):
|
| 208 |
+
encrypted_subr, R = eexec.encrypt(
|
| 209 |
+
bytesjoin([char_IV[:lenIV], subr_bin]), 4330
|
| 210 |
+
)
|
| 211 |
+
lines.append(
|
| 212 |
+
bytesjoin(
|
| 213 |
+
[
|
| 214 |
+
self._tobytes(
|
| 215 |
+
f"dup {i} {len(encrypted_subr)} {RD_key} "
|
| 216 |
+
),
|
| 217 |
+
encrypted_subr,
|
| 218 |
+
self._tobytes(f" {NP_key}"),
|
| 219 |
+
]
|
| 220 |
+
)
|
| 221 |
+
)
|
| 222 |
+
lines.append(b"def")
|
| 223 |
+
|
| 224 |
+
lines.append(b"put")
|
| 225 |
+
else:
|
| 226 |
+
lines.extend(self._make_lines(subkey, subvalue))
|
| 227 |
+
elif key == "CharStrings":
|
| 228 |
+
lines.append(b"dup /CharStrings")
|
| 229 |
+
lines.append(
|
| 230 |
+
self._tobytes(f"{len(eexec_dict['CharStrings'])} dict dup begin")
|
| 231 |
+
)
|
| 232 |
+
for glyph_name, char_bin in eexec_dict["CharStrings"].items():
|
| 233 |
+
char_bin.compile()
|
| 234 |
+
encrypted_char, R = eexec.encrypt(
|
| 235 |
+
bytesjoin([char_IV[:lenIV], char_bin.bytecode]), 4330
|
| 236 |
+
)
|
| 237 |
+
lines.append(
|
| 238 |
+
bytesjoin(
|
| 239 |
+
[
|
| 240 |
+
self._tobytes(
|
| 241 |
+
f"/{glyph_name} {len(encrypted_char)} {RD_key} "
|
| 242 |
+
),
|
| 243 |
+
encrypted_char,
|
| 244 |
+
self._tobytes(f" {ND_key}"),
|
| 245 |
+
]
|
| 246 |
+
)
|
| 247 |
+
)
|
| 248 |
+
lines.append(b"end put")
|
| 249 |
+
else:
|
| 250 |
+
lines.extend(self._make_lines(key, value))
|
| 251 |
+
|
| 252 |
+
lines.extend(
|
| 253 |
+
[
|
| 254 |
+
b"end",
|
| 255 |
+
b"dup /FontName get exch definefont pop",
|
| 256 |
+
b"mark",
|
| 257 |
+
b"currentfile closefile\n",
|
| 258 |
+
]
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
eexec_portion = bytesjoin(lines, "\n")
|
| 262 |
+
encrypted_eexec, R = eexec.encrypt(bytesjoin([eexec_IV, eexec_portion]), 55665)
|
| 263 |
+
|
| 264 |
+
return encrypted_eexec
|
| 265 |
+
|
| 266 |
+
def _make_lines(self, key, value):
|
| 267 |
+
if key == "FontName":
|
| 268 |
+
return [self._tobytes(f"/{key} /{value} def")]
|
| 269 |
+
if key in ["isFixedPitch", "ForceBold", "RndStemUp"]:
|
| 270 |
+
return [self._tobytes(f"/{key} {'true' if value else 'false'} def")]
|
| 271 |
+
elif key == "Encoding":
|
| 272 |
+
if value == StandardEncoding:
|
| 273 |
+
return [self._tobytes(f"/{key} StandardEncoding def")]
|
| 274 |
+
else:
|
| 275 |
+
# follow fontTools.misc.psOperators._type1_Encoding_repr
|
| 276 |
+
lines = []
|
| 277 |
+
lines.append(b"/Encoding 256 array")
|
| 278 |
+
lines.append(b"0 1 255 {1 index exch /.notdef put} for")
|
| 279 |
+
for i in range(256):
|
| 280 |
+
name = value[i]
|
| 281 |
+
if name != ".notdef":
|
| 282 |
+
lines.append(self._tobytes(f"dup {i} /{name} put"))
|
| 283 |
+
lines.append(b"def")
|
| 284 |
+
return lines
|
| 285 |
+
if isinstance(value, str):
|
| 286 |
+
return [self._tobytes(f"/{key} ({value}) def")]
|
| 287 |
+
elif isinstance(value, bool):
|
| 288 |
+
return [self._tobytes(f"/{key} {'true' if value else 'false'} def")]
|
| 289 |
+
elif isinstance(value, list):
|
| 290 |
+
return [self._tobytes(f"/{key} [{' '.join(str(v) for v in value)}] def")]
|
| 291 |
+
elif isinstance(value, tuple):
|
| 292 |
+
return [self._tobytes(f"/{key} {{{' '.join(str(v) for v in value)}}} def")]
|
| 293 |
+
else:
|
| 294 |
+
return [self._tobytes(f"/{key} {value} def")]
|
| 295 |
+
|
| 296 |
+
def _tobytes(self, s, errors="strict"):
|
| 297 |
+
return tobytes(s, self.encoding, errors)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
# low level T1 data read and write functions
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def read(path, onlyHeader=False):
|
| 304 |
+
"""reads any Type 1 font file, returns raw data"""
|
| 305 |
+
_, ext = os.path.splitext(path)
|
| 306 |
+
ext = ext.lower()
|
| 307 |
+
creator, typ = getMacCreatorAndType(path)
|
| 308 |
+
if typ == "LWFN":
|
| 309 |
+
return readLWFN(path, onlyHeader), "LWFN"
|
| 310 |
+
if ext == ".pfb":
|
| 311 |
+
return readPFB(path, onlyHeader), "PFB"
|
| 312 |
+
else:
|
| 313 |
+
return readOther(path), "OTHER"
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def write(path, data, kind="OTHER", dohex=False):
|
| 317 |
+
assertType1(data)
|
| 318 |
+
kind = kind.upper()
|
| 319 |
+
try:
|
| 320 |
+
os.remove(path)
|
| 321 |
+
except os.error:
|
| 322 |
+
pass
|
| 323 |
+
err = 1
|
| 324 |
+
try:
|
| 325 |
+
if kind == "LWFN":
|
| 326 |
+
writeLWFN(path, data)
|
| 327 |
+
elif kind == "PFB":
|
| 328 |
+
writePFB(path, data)
|
| 329 |
+
else:
|
| 330 |
+
writeOther(path, data, dohex)
|
| 331 |
+
err = 0
|
| 332 |
+
finally:
|
| 333 |
+
if err and not DEBUG:
|
| 334 |
+
try:
|
| 335 |
+
os.remove(path)
|
| 336 |
+
except os.error:
|
| 337 |
+
pass
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
# -- internal --
|
| 341 |
+
|
| 342 |
+
LWFNCHUNKSIZE = 2000
|
| 343 |
+
HEXLINELENGTH = 80
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def readLWFN(path, onlyHeader=False):
|
| 347 |
+
"""reads an LWFN font file, returns raw data"""
|
| 348 |
+
from fontTools.misc.macRes import ResourceReader
|
| 349 |
+
|
| 350 |
+
reader = ResourceReader(path)
|
| 351 |
+
try:
|
| 352 |
+
data = []
|
| 353 |
+
for res in reader.get("POST", []):
|
| 354 |
+
code = byteord(res.data[0])
|
| 355 |
+
if byteord(res.data[1]) != 0:
|
| 356 |
+
raise T1Error("corrupt LWFN file")
|
| 357 |
+
if code in [1, 2]:
|
| 358 |
+
if onlyHeader and code == 2:
|
| 359 |
+
break
|
| 360 |
+
data.append(res.data[2:])
|
| 361 |
+
elif code in [3, 5]:
|
| 362 |
+
break
|
| 363 |
+
elif code == 4:
|
| 364 |
+
with open(path, "rb") as f:
|
| 365 |
+
data.append(f.read())
|
| 366 |
+
elif code == 0:
|
| 367 |
+
pass # comment, ignore
|
| 368 |
+
else:
|
| 369 |
+
raise T1Error("bad chunk code: " + repr(code))
|
| 370 |
+
finally:
|
| 371 |
+
reader.close()
|
| 372 |
+
data = bytesjoin(data)
|
| 373 |
+
assertType1(data)
|
| 374 |
+
return data
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def readPFB(path, onlyHeader=False):
|
| 378 |
+
"""reads a PFB font file, returns raw data"""
|
| 379 |
+
data = []
|
| 380 |
+
with open(path, "rb") as f:
|
| 381 |
+
while True:
|
| 382 |
+
if f.read(1) != bytechr(128):
|
| 383 |
+
raise T1Error("corrupt PFB file")
|
| 384 |
+
code = byteord(f.read(1))
|
| 385 |
+
if code in [1, 2]:
|
| 386 |
+
chunklen = stringToLong(f.read(4))
|
| 387 |
+
chunk = f.read(chunklen)
|
| 388 |
+
assert len(chunk) == chunklen
|
| 389 |
+
data.append(chunk)
|
| 390 |
+
elif code == 3:
|
| 391 |
+
break
|
| 392 |
+
else:
|
| 393 |
+
raise T1Error("bad chunk code: " + repr(code))
|
| 394 |
+
if onlyHeader:
|
| 395 |
+
break
|
| 396 |
+
data = bytesjoin(data)
|
| 397 |
+
assertType1(data)
|
| 398 |
+
return data
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def readOther(path):
|
| 402 |
+
"""reads any (font) file, returns raw data"""
|
| 403 |
+
with open(path, "rb") as f:
|
| 404 |
+
data = f.read()
|
| 405 |
+
assertType1(data)
|
| 406 |
+
chunks = findEncryptedChunks(data)
|
| 407 |
+
data = []
|
| 408 |
+
for isEncrypted, chunk in chunks:
|
| 409 |
+
if isEncrypted and isHex(chunk[:4]):
|
| 410 |
+
data.append(deHexString(chunk))
|
| 411 |
+
else:
|
| 412 |
+
data.append(chunk)
|
| 413 |
+
return bytesjoin(data)
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
# file writing tools
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def writeLWFN(path, data):
|
| 420 |
+
# Res.FSpCreateResFile was deprecated in OS X 10.5
|
| 421 |
+
Res.FSpCreateResFile(path, "just", "LWFN", 0)
|
| 422 |
+
resRef = Res.FSOpenResFile(path, 2) # write-only
|
| 423 |
+
try:
|
| 424 |
+
Res.UseResFile(resRef)
|
| 425 |
+
resID = 501
|
| 426 |
+
chunks = findEncryptedChunks(data)
|
| 427 |
+
for isEncrypted, chunk in chunks:
|
| 428 |
+
if isEncrypted:
|
| 429 |
+
code = 2
|
| 430 |
+
else:
|
| 431 |
+
code = 1
|
| 432 |
+
while chunk:
|
| 433 |
+
res = Res.Resource(bytechr(code) + "\0" + chunk[: LWFNCHUNKSIZE - 2])
|
| 434 |
+
res.AddResource("POST", resID, "")
|
| 435 |
+
chunk = chunk[LWFNCHUNKSIZE - 2 :]
|
| 436 |
+
resID = resID + 1
|
| 437 |
+
res = Res.Resource(bytechr(5) + "\0")
|
| 438 |
+
res.AddResource("POST", resID, "")
|
| 439 |
+
finally:
|
| 440 |
+
Res.CloseResFile(resRef)
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def writePFB(path, data):
|
| 444 |
+
chunks = findEncryptedChunks(data)
|
| 445 |
+
with open(path, "wb") as f:
|
| 446 |
+
for isEncrypted, chunk in chunks:
|
| 447 |
+
if isEncrypted:
|
| 448 |
+
code = 2
|
| 449 |
+
else:
|
| 450 |
+
code = 1
|
| 451 |
+
f.write(bytechr(128) + bytechr(code))
|
| 452 |
+
f.write(longToString(len(chunk)))
|
| 453 |
+
f.write(chunk)
|
| 454 |
+
f.write(bytechr(128) + bytechr(3))
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def writeOther(path, data, dohex=False):
|
| 458 |
+
chunks = findEncryptedChunks(data)
|
| 459 |
+
with open(path, "wb") as f:
|
| 460 |
+
hexlinelen = HEXLINELENGTH // 2
|
| 461 |
+
for isEncrypted, chunk in chunks:
|
| 462 |
+
if isEncrypted:
|
| 463 |
+
code = 2
|
| 464 |
+
else:
|
| 465 |
+
code = 1
|
| 466 |
+
if code == 2 and dohex:
|
| 467 |
+
while chunk:
|
| 468 |
+
f.write(eexec.hexString(chunk[:hexlinelen]))
|
| 469 |
+
f.write(b"\r")
|
| 470 |
+
chunk = chunk[hexlinelen:]
|
| 471 |
+
else:
|
| 472 |
+
f.write(chunk)
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
# decryption tools
|
| 476 |
+
|
| 477 |
+
EEXECBEGIN = b"currentfile eexec"
|
| 478 |
+
# The spec allows for 512 ASCII zeros interrupted by arbitrary whitespace to
|
| 479 |
+
# follow eexec
|
| 480 |
+
EEXECEND = re.compile(b"(0[ \t\r\n]*){512}", flags=re.M)
|
| 481 |
+
EEXECINTERNALEND = b"currentfile closefile"
|
| 482 |
+
EEXECBEGINMARKER = b"%-- eexec start\r"
|
| 483 |
+
EEXECENDMARKER = b"%-- eexec end\r"
|
| 484 |
+
|
| 485 |
+
_ishexRE = re.compile(b"[0-9A-Fa-f]*$")
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def isHex(text):
|
| 489 |
+
return _ishexRE.match(text) is not None
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
def decryptType1(data):
|
| 493 |
+
chunks = findEncryptedChunks(data)
|
| 494 |
+
data = []
|
| 495 |
+
for isEncrypted, chunk in chunks:
|
| 496 |
+
if isEncrypted:
|
| 497 |
+
if isHex(chunk[:4]):
|
| 498 |
+
chunk = deHexString(chunk)
|
| 499 |
+
decrypted, R = eexec.decrypt(chunk, 55665)
|
| 500 |
+
decrypted = decrypted[4:]
|
| 501 |
+
if (
|
| 502 |
+
decrypted[-len(EEXECINTERNALEND) - 1 : -1] != EEXECINTERNALEND
|
| 503 |
+
and decrypted[-len(EEXECINTERNALEND) - 2 : -2] != EEXECINTERNALEND
|
| 504 |
+
):
|
| 505 |
+
raise T1Error("invalid end of eexec part")
|
| 506 |
+
decrypted = decrypted[: -len(EEXECINTERNALEND) - 2] + b"\r"
|
| 507 |
+
data.append(EEXECBEGINMARKER + decrypted + EEXECENDMARKER)
|
| 508 |
+
else:
|
| 509 |
+
if chunk[-len(EEXECBEGIN) - 1 : -1] == EEXECBEGIN:
|
| 510 |
+
data.append(chunk[: -len(EEXECBEGIN) - 1])
|
| 511 |
+
else:
|
| 512 |
+
data.append(chunk)
|
| 513 |
+
return bytesjoin(data)
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def findEncryptedChunks(data):
|
| 517 |
+
chunks = []
|
| 518 |
+
while True:
|
| 519 |
+
eBegin = data.find(EEXECBEGIN)
|
| 520 |
+
if eBegin < 0:
|
| 521 |
+
break
|
| 522 |
+
eBegin = eBegin + len(EEXECBEGIN) + 1
|
| 523 |
+
endMatch = EEXECEND.search(data, eBegin)
|
| 524 |
+
if endMatch is None:
|
| 525 |
+
raise T1Error("can't find end of eexec part")
|
| 526 |
+
eEnd = endMatch.start()
|
| 527 |
+
cypherText = data[eBegin : eEnd + 2]
|
| 528 |
+
if isHex(cypherText[:4]):
|
| 529 |
+
cypherText = deHexString(cypherText)
|
| 530 |
+
plainText, R = eexec.decrypt(cypherText, 55665)
|
| 531 |
+
eEndLocal = plainText.find(EEXECINTERNALEND)
|
| 532 |
+
if eEndLocal < 0:
|
| 533 |
+
raise T1Error("can't find end of eexec part")
|
| 534 |
+
chunks.append((0, data[:eBegin]))
|
| 535 |
+
chunks.append((1, cypherText[: eEndLocal + len(EEXECINTERNALEND) + 1]))
|
| 536 |
+
data = data[eEnd:]
|
| 537 |
+
chunks.append((0, data))
|
| 538 |
+
return chunks
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def deHexString(hexstring):
|
| 542 |
+
return eexec.deHexString(bytesjoin(hexstring.split()))
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
# Type 1 assertion
|
| 546 |
+
|
| 547 |
+
_fontType1RE = re.compile(rb"/FontType\s+1\s+def")
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def assertType1(data):
|
| 551 |
+
for head in [b"%!PS-AdobeFont", b"%!FontType1"]:
|
| 552 |
+
if data[: len(head)] == head:
|
| 553 |
+
break
|
| 554 |
+
else:
|
| 555 |
+
raise T1Error("not a PostScript font")
|
| 556 |
+
if not _fontType1RE.search(data):
|
| 557 |
+
raise T1Error("not a Type 1 font")
|
| 558 |
+
if data.find(b"currentfile eexec") < 0:
|
| 559 |
+
raise T1Error("not an encrypted Type 1 font")
|
| 560 |
+
# XXX what else?
|
| 561 |
+
return data
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
# pfb helpers
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
def longToString(long):
|
| 568 |
+
s = b""
|
| 569 |
+
for i in range(4):
|
| 570 |
+
s += bytechr((long & (0xFF << (i * 8))) >> i * 8)
|
| 571 |
+
return s
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def stringToLong(s):
|
| 575 |
+
if len(s) != 4:
|
| 576 |
+
raise ValueError("string must be 4 bytes long")
|
| 577 |
+
l = 0
|
| 578 |
+
for i in range(4):
|
| 579 |
+
l += byteord(s[i]) << (i * 8)
|
| 580 |
+
return l
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
# PS stream helpers
|
| 584 |
+
|
| 585 |
+
font_dictionary_keys = list(_type1_pre_eexec_order)
|
| 586 |
+
# t1write.c:writeRegNameKeyedFont
|
| 587 |
+
# always counts following keys
|
| 588 |
+
font_dictionary_keys.remove("FontMatrix")
|
| 589 |
+
|
| 590 |
+
FontInfo_dictionary_keys = list(_type1_fontinfo_order)
|
| 591 |
+
# extend because AFDKO tx may use following keys
|
| 592 |
+
FontInfo_dictionary_keys.extend(
|
| 593 |
+
[
|
| 594 |
+
"FSType",
|
| 595 |
+
"Copyright",
|
| 596 |
+
]
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
Private_dictionary_keys = [
|
| 600 |
+
# We don't know what names will be actually used.
|
| 601 |
+
# "RD",
|
| 602 |
+
# "ND",
|
| 603 |
+
# "NP",
|
| 604 |
+
"Subrs",
|
| 605 |
+
"OtherSubrs",
|
| 606 |
+
"UniqueID",
|
| 607 |
+
"BlueValues",
|
| 608 |
+
"OtherBlues",
|
| 609 |
+
"FamilyBlues",
|
| 610 |
+
"FamilyOtherBlues",
|
| 611 |
+
"BlueScale",
|
| 612 |
+
"BlueShift",
|
| 613 |
+
"BlueFuzz",
|
| 614 |
+
"StdHW",
|
| 615 |
+
"StdVW",
|
| 616 |
+
"StemSnapH",
|
| 617 |
+
"StemSnapV",
|
| 618 |
+
"ForceBold",
|
| 619 |
+
"LanguageGroup",
|
| 620 |
+
"password",
|
| 621 |
+
"lenIV",
|
| 622 |
+
"MinFeature",
|
| 623 |
+
"RndStemUp",
|
| 624 |
+
]
|
| 625 |
+
|
| 626 |
+
# t1write_hintothers.h
|
| 627 |
+
hintothers = """/OtherSubrs[{}{}{}{systemdict/internaldict known not{pop 3}{1183615869
|
| 628 |
+
systemdict/internaldict get exec dup/startlock known{/startlock get exec}{dup
|
| 629 |
+
/strtlck known{/strtlck get exec}{pop 3}ifelse}ifelse}ifelse}executeonly]def"""
|
| 630 |
+
# t1write.c:saveStdSubrs
|
| 631 |
+
std_subrs = [
|
| 632 |
+
# 3 0 callother pop pop setcurrentpoint return
|
| 633 |
+
b"\x8e\x8b\x0c\x10\x0c\x11\x0c\x11\x0c\x21\x0b",
|
| 634 |
+
# 0 1 callother return
|
| 635 |
+
b"\x8b\x8c\x0c\x10\x0b",
|
| 636 |
+
# 0 2 callother return
|
| 637 |
+
b"\x8b\x8d\x0c\x10\x0b",
|
| 638 |
+
# return
|
| 639 |
+
b"\x0b",
|
| 640 |
+
# 3 1 3 callother pop callsubr return
|
| 641 |
+
b"\x8e\x8c\x8e\x0c\x10\x0c\x11\x0a\x0b",
|
| 642 |
+
]
|
| 643 |
+
# follow t1write.c:writeRegNameKeyedFont
|
| 644 |
+
eexec_IV = b"cccc"
|
| 645 |
+
char_IV = b"\x0c\x0c\x0c\x0c"
|
| 646 |
+
RD_value = ("string", "currentfile", "exch", "readstring", "pop")
|
| 647 |
+
ND_values = [("def",), ("noaccess", "def")]
|
| 648 |
+
PD_values = [("put",), ("noaccess", "put")]
|
.venv/lib/python3.12/site-packages/fontTools/t1Lib/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (26.8 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/tfmLib.py
ADDED
|
@@ -0,0 +1,460 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Module for reading TFM (TeX Font Metrics) files.
|
| 2 |
+
|
| 3 |
+
The TFM format is described in the TFtoPL WEB source code, whose typeset form
|
| 4 |
+
can be found on `CTAN <http://mirrors.ctan.org/info/knuth-pdf/texware/tftopl.pdf>`_.
|
| 5 |
+
|
| 6 |
+
>>> from fontTools.tfmLib import TFM
|
| 7 |
+
>>> tfm = TFM("Tests/tfmLib/data/cmr10.tfm")
|
| 8 |
+
>>>
|
| 9 |
+
>>> # Accessing an attribute gets you metadata.
|
| 10 |
+
>>> tfm.checksum
|
| 11 |
+
1274110073
|
| 12 |
+
>>> tfm.designsize
|
| 13 |
+
10.0
|
| 14 |
+
>>> tfm.codingscheme
|
| 15 |
+
'TeX text'
|
| 16 |
+
>>> tfm.family
|
| 17 |
+
'CMR'
|
| 18 |
+
>>> tfm.seven_bit_safe_flag
|
| 19 |
+
False
|
| 20 |
+
>>> tfm.face
|
| 21 |
+
234
|
| 22 |
+
>>> tfm.extraheader
|
| 23 |
+
{}
|
| 24 |
+
>>> tfm.fontdimens
|
| 25 |
+
{'SLANT': 0.0, 'SPACE': 0.33333396911621094, 'STRETCH': 0.16666698455810547, 'SHRINK': 0.11111164093017578, 'XHEIGHT': 0.4305553436279297, 'QUAD': 1.0000028610229492, 'EXTRASPACE': 0.11111164093017578}
|
| 26 |
+
>>> # Accessing a character gets you its metrics.
|
| 27 |
+
>>> # “width” is always available, other metrics are available only when
|
| 28 |
+
>>> # applicable. All values are relative to “designsize”.
|
| 29 |
+
>>> tfm.chars[ord("g")]
|
| 30 |
+
{'width': 0.5000019073486328, 'height': 0.4305553436279297, 'depth': 0.1944446563720703, 'italic': 0.013888359069824219}
|
| 31 |
+
>>> # Kerning and ligature can be accessed as well.
|
| 32 |
+
>>> tfm.kerning[ord("c")]
|
| 33 |
+
{104: -0.02777862548828125, 107: -0.02777862548828125}
|
| 34 |
+
>>> tfm.ligatures[ord("f")]
|
| 35 |
+
{105: ('LIG', 12), 102: ('LIG', 11), 108: ('LIG', 13)}
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from types import SimpleNamespace
|
| 39 |
+
|
| 40 |
+
from fontTools.misc.sstruct import calcsize, unpack, unpack2
|
| 41 |
+
|
| 42 |
+
SIZES_FORMAT = """
|
| 43 |
+
>
|
| 44 |
+
lf: h # length of the entire file, in words
|
| 45 |
+
lh: h # length of the header data, in words
|
| 46 |
+
bc: h # smallest character code in the font
|
| 47 |
+
ec: h # largest character code in the font
|
| 48 |
+
nw: h # number of words in the width table
|
| 49 |
+
nh: h # number of words in the height table
|
| 50 |
+
nd: h # number of words in the depth table
|
| 51 |
+
ni: h # number of words in the italic correction table
|
| 52 |
+
nl: h # number of words in the ligature/kern table
|
| 53 |
+
nk: h # number of words in the kern table
|
| 54 |
+
ne: h # number of words in the extensible character table
|
| 55 |
+
np: h # number of font parameter words
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
SIZES_SIZE = calcsize(SIZES_FORMAT)
|
| 59 |
+
|
| 60 |
+
FIXED_FORMAT = "12.20F"
|
| 61 |
+
|
| 62 |
+
HEADER_FORMAT1 = f"""
|
| 63 |
+
>
|
| 64 |
+
checksum: L
|
| 65 |
+
designsize: {FIXED_FORMAT}
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
HEADER_FORMAT2 = f"""
|
| 69 |
+
{HEADER_FORMAT1}
|
| 70 |
+
codingscheme: 40p
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
HEADER_FORMAT3 = f"""
|
| 74 |
+
{HEADER_FORMAT2}
|
| 75 |
+
family: 20p
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
HEADER_FORMAT4 = f"""
|
| 79 |
+
{HEADER_FORMAT3}
|
| 80 |
+
seven_bit_safe_flag: ?
|
| 81 |
+
ignored: x
|
| 82 |
+
ignored: x
|
| 83 |
+
face: B
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
HEADER_SIZE1 = calcsize(HEADER_FORMAT1)
|
| 87 |
+
HEADER_SIZE2 = calcsize(HEADER_FORMAT2)
|
| 88 |
+
HEADER_SIZE3 = calcsize(HEADER_FORMAT3)
|
| 89 |
+
HEADER_SIZE4 = calcsize(HEADER_FORMAT4)
|
| 90 |
+
|
| 91 |
+
LIG_KERN_COMMAND = """
|
| 92 |
+
>
|
| 93 |
+
skip_byte: B
|
| 94 |
+
next_char: B
|
| 95 |
+
op_byte: B
|
| 96 |
+
remainder: B
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
BASE_PARAMS = [
|
| 100 |
+
"SLANT",
|
| 101 |
+
"SPACE",
|
| 102 |
+
"STRETCH",
|
| 103 |
+
"SHRINK",
|
| 104 |
+
"XHEIGHT",
|
| 105 |
+
"QUAD",
|
| 106 |
+
"EXTRASPACE",
|
| 107 |
+
]
|
| 108 |
+
|
| 109 |
+
MATHSY_PARAMS = [
|
| 110 |
+
"NUM1",
|
| 111 |
+
"NUM2",
|
| 112 |
+
"NUM3",
|
| 113 |
+
"DENOM1",
|
| 114 |
+
"DENOM2",
|
| 115 |
+
"SUP1",
|
| 116 |
+
"SUP2",
|
| 117 |
+
"SUP3",
|
| 118 |
+
"SUB1",
|
| 119 |
+
"SUB2",
|
| 120 |
+
"SUPDROP",
|
| 121 |
+
"SUBDROP",
|
| 122 |
+
"DELIM1",
|
| 123 |
+
"DELIM2",
|
| 124 |
+
"AXISHEIGHT",
|
| 125 |
+
]
|
| 126 |
+
|
| 127 |
+
MATHEX_PARAMS = [
|
| 128 |
+
"DEFAULTRULETHICKNESS",
|
| 129 |
+
"BIGOPSPACING1",
|
| 130 |
+
"BIGOPSPACING2",
|
| 131 |
+
"BIGOPSPACING3",
|
| 132 |
+
"BIGOPSPACING4",
|
| 133 |
+
"BIGOPSPACING5",
|
| 134 |
+
]
|
| 135 |
+
|
| 136 |
+
VANILLA = 0
|
| 137 |
+
MATHSY = 1
|
| 138 |
+
MATHEX = 2
|
| 139 |
+
|
| 140 |
+
UNREACHABLE = 0
|
| 141 |
+
PASSTHROUGH = 1
|
| 142 |
+
ACCESSABLE = 2
|
| 143 |
+
|
| 144 |
+
NO_TAG = 0
|
| 145 |
+
LIG_TAG = 1
|
| 146 |
+
LIST_TAG = 2
|
| 147 |
+
EXT_TAG = 3
|
| 148 |
+
|
| 149 |
+
STOP_FLAG = 128
|
| 150 |
+
KERN_FLAG = 128
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class TFMException(Exception):
|
| 154 |
+
def __init__(self, message):
|
| 155 |
+
super().__init__(message)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class TFM:
|
| 159 |
+
def __init__(self, file):
|
| 160 |
+
self._read(file)
|
| 161 |
+
|
| 162 |
+
def __repr__(self):
|
| 163 |
+
return (
|
| 164 |
+
f"<TFM"
|
| 165 |
+
f" for {self.family}"
|
| 166 |
+
f" in {self.codingscheme}"
|
| 167 |
+
f" at {self.designsize:g}pt>"
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
def _read(self, file):
|
| 171 |
+
if hasattr(file, "read"):
|
| 172 |
+
data = file.read()
|
| 173 |
+
else:
|
| 174 |
+
with open(file, "rb") as fp:
|
| 175 |
+
data = fp.read()
|
| 176 |
+
|
| 177 |
+
self._data = data
|
| 178 |
+
|
| 179 |
+
if len(data) < SIZES_SIZE:
|
| 180 |
+
raise TFMException("Too short input file")
|
| 181 |
+
|
| 182 |
+
sizes = SimpleNamespace()
|
| 183 |
+
unpack2(SIZES_FORMAT, data, sizes)
|
| 184 |
+
|
| 185 |
+
# Do some file structure sanity checks.
|
| 186 |
+
# TeX and TFtoPL do additional functional checks and might even correct
|
| 187 |
+
# “errors” in the input file, but we instead try to output the file as
|
| 188 |
+
# it is as long as it is parsable, even if the data make no sense.
|
| 189 |
+
|
| 190 |
+
if sizes.lf < 0:
|
| 191 |
+
raise TFMException("The file claims to have negative or zero length!")
|
| 192 |
+
|
| 193 |
+
if len(data) < sizes.lf * 4:
|
| 194 |
+
raise TFMException("The file has fewer bytes than it claims!")
|
| 195 |
+
|
| 196 |
+
for name, length in vars(sizes).items():
|
| 197 |
+
if length < 0:
|
| 198 |
+
raise TFMException("The subfile size: '{name}' is negative!")
|
| 199 |
+
|
| 200 |
+
if sizes.lh < 2:
|
| 201 |
+
raise TFMException(f"The header length is only {sizes.lh}!")
|
| 202 |
+
|
| 203 |
+
if sizes.bc > sizes.ec + 1 or sizes.ec > 255:
|
| 204 |
+
raise TFMException(
|
| 205 |
+
f"The character code range {sizes.bc}..{sizes.ec} is illegal!"
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
if sizes.nw == 0 or sizes.nh == 0 or sizes.nd == 0 or sizes.ni == 0:
|
| 209 |
+
raise TFMException("Incomplete subfiles for character dimensions!")
|
| 210 |
+
|
| 211 |
+
if sizes.ne > 256:
|
| 212 |
+
raise TFMException(f"There are {ne} extensible recipes!")
|
| 213 |
+
|
| 214 |
+
if sizes.lf != (
|
| 215 |
+
6
|
| 216 |
+
+ sizes.lh
|
| 217 |
+
+ (sizes.ec - sizes.bc + 1)
|
| 218 |
+
+ sizes.nw
|
| 219 |
+
+ sizes.nh
|
| 220 |
+
+ sizes.nd
|
| 221 |
+
+ sizes.ni
|
| 222 |
+
+ sizes.nl
|
| 223 |
+
+ sizes.nk
|
| 224 |
+
+ sizes.ne
|
| 225 |
+
+ sizes.np
|
| 226 |
+
):
|
| 227 |
+
raise TFMException("Subfile sizes don’t add up to the stated total")
|
| 228 |
+
|
| 229 |
+
# Subfile offsets, used in the helper function below. These all are
|
| 230 |
+
# 32-bit word offsets not 8-bit byte offsets.
|
| 231 |
+
char_base = 6 + sizes.lh - sizes.bc
|
| 232 |
+
width_base = char_base + sizes.ec + 1
|
| 233 |
+
height_base = width_base + sizes.nw
|
| 234 |
+
depth_base = height_base + sizes.nh
|
| 235 |
+
italic_base = depth_base + sizes.nd
|
| 236 |
+
lig_kern_base = italic_base + sizes.ni
|
| 237 |
+
kern_base = lig_kern_base + sizes.nl
|
| 238 |
+
exten_base = kern_base + sizes.nk
|
| 239 |
+
param_base = exten_base + sizes.ne
|
| 240 |
+
|
| 241 |
+
# Helper functions for accessing individual data. If this looks
|
| 242 |
+
# nonidiomatic Python, I blame the effect of reading the literate WEB
|
| 243 |
+
# documentation of TFtoPL.
|
| 244 |
+
def char_info(c):
|
| 245 |
+
return 4 * (char_base + c)
|
| 246 |
+
|
| 247 |
+
def width_index(c):
|
| 248 |
+
return data[char_info(c)]
|
| 249 |
+
|
| 250 |
+
def noneexistent(c):
|
| 251 |
+
return c < sizes.bc or c > sizes.ec or width_index(c) == 0
|
| 252 |
+
|
| 253 |
+
def height_index(c):
|
| 254 |
+
return data[char_info(c) + 1] // 16
|
| 255 |
+
|
| 256 |
+
def depth_index(c):
|
| 257 |
+
return data[char_info(c) + 1] % 16
|
| 258 |
+
|
| 259 |
+
def italic_index(c):
|
| 260 |
+
return data[char_info(c) + 2] // 4
|
| 261 |
+
|
| 262 |
+
def tag(c):
|
| 263 |
+
return data[char_info(c) + 2] % 4
|
| 264 |
+
|
| 265 |
+
def remainder(c):
|
| 266 |
+
return data[char_info(c) + 3]
|
| 267 |
+
|
| 268 |
+
def width(c):
|
| 269 |
+
r = 4 * (width_base + width_index(c))
|
| 270 |
+
return read_fixed(r, "v")["v"]
|
| 271 |
+
|
| 272 |
+
def height(c):
|
| 273 |
+
r = 4 * (height_base + height_index(c))
|
| 274 |
+
return read_fixed(r, "v")["v"]
|
| 275 |
+
|
| 276 |
+
def depth(c):
|
| 277 |
+
r = 4 * (depth_base + depth_index(c))
|
| 278 |
+
return read_fixed(r, "v")["v"]
|
| 279 |
+
|
| 280 |
+
def italic(c):
|
| 281 |
+
r = 4 * (italic_base + italic_index(c))
|
| 282 |
+
return read_fixed(r, "v")["v"]
|
| 283 |
+
|
| 284 |
+
def exten(c):
|
| 285 |
+
return 4 * (exten_base + remainder(c))
|
| 286 |
+
|
| 287 |
+
def lig_step(i):
|
| 288 |
+
return 4 * (lig_kern_base + i)
|
| 289 |
+
|
| 290 |
+
def lig_kern_command(i):
|
| 291 |
+
command = SimpleNamespace()
|
| 292 |
+
unpack2(LIG_KERN_COMMAND, data[i:], command)
|
| 293 |
+
return command
|
| 294 |
+
|
| 295 |
+
def kern(i):
|
| 296 |
+
r = 4 * (kern_base + i)
|
| 297 |
+
return read_fixed(r, "v")["v"]
|
| 298 |
+
|
| 299 |
+
def param(i):
|
| 300 |
+
return 4 * (param_base + i)
|
| 301 |
+
|
| 302 |
+
def read_fixed(index, key, obj=None):
|
| 303 |
+
ret = unpack2(f">;{key}:{FIXED_FORMAT}", data[index:], obj)
|
| 304 |
+
return ret[0]
|
| 305 |
+
|
| 306 |
+
# Set all attributes to empty values regardless of the header size.
|
| 307 |
+
unpack(HEADER_FORMAT4, [0] * HEADER_SIZE4, self)
|
| 308 |
+
|
| 309 |
+
offset = 24
|
| 310 |
+
length = sizes.lh * 4
|
| 311 |
+
self.extraheader = {}
|
| 312 |
+
if length >= HEADER_SIZE4:
|
| 313 |
+
rest = unpack2(HEADER_FORMAT4, data[offset:], self)[1]
|
| 314 |
+
if self.face < 18:
|
| 315 |
+
s = self.face % 2
|
| 316 |
+
b = self.face // 2
|
| 317 |
+
self.face = "MBL"[b % 3] + "RI"[s] + "RCE"[b // 3]
|
| 318 |
+
for i in range(sizes.lh - HEADER_SIZE4 // 4):
|
| 319 |
+
rest = unpack2(f">;HEADER{i + 18}:l", rest, self.extraheader)[1]
|
| 320 |
+
elif length >= HEADER_SIZE3:
|
| 321 |
+
unpack2(HEADER_FORMAT3, data[offset:], self)
|
| 322 |
+
elif length >= HEADER_SIZE2:
|
| 323 |
+
unpack2(HEADER_FORMAT2, data[offset:], self)
|
| 324 |
+
elif length >= HEADER_SIZE1:
|
| 325 |
+
unpack2(HEADER_FORMAT1, data[offset:], self)
|
| 326 |
+
|
| 327 |
+
self.fonttype = VANILLA
|
| 328 |
+
scheme = self.codingscheme.upper()
|
| 329 |
+
if scheme.startswith("TEX MATH SY"):
|
| 330 |
+
self.fonttype = MATHSY
|
| 331 |
+
elif scheme.startswith("TEX MATH EX"):
|
| 332 |
+
self.fonttype = MATHEX
|
| 333 |
+
|
| 334 |
+
self.fontdimens = {}
|
| 335 |
+
for i in range(sizes.np):
|
| 336 |
+
name = f"PARAMETER{i+1}"
|
| 337 |
+
if i <= 6:
|
| 338 |
+
name = BASE_PARAMS[i]
|
| 339 |
+
elif self.fonttype == MATHSY and i <= 21:
|
| 340 |
+
name = MATHSY_PARAMS[i - 7]
|
| 341 |
+
elif self.fonttype == MATHEX and i <= 12:
|
| 342 |
+
name = MATHEX_PARAMS[i - 7]
|
| 343 |
+
read_fixed(param(i), name, self.fontdimens)
|
| 344 |
+
|
| 345 |
+
lig_kern_map = {}
|
| 346 |
+
self.right_boundary_char = None
|
| 347 |
+
self.left_boundary_char = None
|
| 348 |
+
if sizes.nl > 0:
|
| 349 |
+
cmd = lig_kern_command(lig_step(0))
|
| 350 |
+
if cmd.skip_byte == 255:
|
| 351 |
+
self.right_boundary_char = cmd.next_char
|
| 352 |
+
|
| 353 |
+
cmd = lig_kern_command(lig_step((sizes.nl - 1)))
|
| 354 |
+
if cmd.skip_byte == 255:
|
| 355 |
+
self.left_boundary_char = 256
|
| 356 |
+
r = 256 * cmd.op_byte + cmd.remainder
|
| 357 |
+
lig_kern_map[self.left_boundary_char] = r
|
| 358 |
+
|
| 359 |
+
self.chars = {}
|
| 360 |
+
for c in range(sizes.bc, sizes.ec + 1):
|
| 361 |
+
if width_index(c) > 0:
|
| 362 |
+
self.chars[c] = info = {}
|
| 363 |
+
info["width"] = width(c)
|
| 364 |
+
if height_index(c) > 0:
|
| 365 |
+
info["height"] = height(c)
|
| 366 |
+
if depth_index(c) > 0:
|
| 367 |
+
info["depth"] = depth(c)
|
| 368 |
+
if italic_index(c) > 0:
|
| 369 |
+
info["italic"] = italic(c)
|
| 370 |
+
char_tag = tag(c)
|
| 371 |
+
if char_tag == NO_TAG:
|
| 372 |
+
pass
|
| 373 |
+
elif char_tag == LIG_TAG:
|
| 374 |
+
lig_kern_map[c] = remainder(c)
|
| 375 |
+
elif char_tag == LIST_TAG:
|
| 376 |
+
info["nextlarger"] = remainder(c)
|
| 377 |
+
elif char_tag == EXT_TAG:
|
| 378 |
+
info["varchar"] = varchar = {}
|
| 379 |
+
for i in range(4):
|
| 380 |
+
part = data[exten(c) + i]
|
| 381 |
+
if i == 3 or part > 0:
|
| 382 |
+
name = "rep"
|
| 383 |
+
if i == 0:
|
| 384 |
+
name = "top"
|
| 385 |
+
elif i == 1:
|
| 386 |
+
name = "mid"
|
| 387 |
+
elif i == 2:
|
| 388 |
+
name = "bot"
|
| 389 |
+
if noneexistent(part):
|
| 390 |
+
varchar[name] = c
|
| 391 |
+
else:
|
| 392 |
+
varchar[name] = part
|
| 393 |
+
|
| 394 |
+
self.ligatures = {}
|
| 395 |
+
self.kerning = {}
|
| 396 |
+
for c, i in sorted(lig_kern_map.items()):
|
| 397 |
+
cmd = lig_kern_command(lig_step(i))
|
| 398 |
+
if cmd.skip_byte > STOP_FLAG:
|
| 399 |
+
i = 256 * cmd.op_byte + cmd.remainder
|
| 400 |
+
|
| 401 |
+
while i < sizes.nl:
|
| 402 |
+
cmd = lig_kern_command(lig_step(i))
|
| 403 |
+
if cmd.skip_byte > STOP_FLAG:
|
| 404 |
+
pass
|
| 405 |
+
else:
|
| 406 |
+
if cmd.op_byte >= KERN_FLAG:
|
| 407 |
+
r = 256 * (cmd.op_byte - KERN_FLAG) + cmd.remainder
|
| 408 |
+
self.kerning.setdefault(c, {})[cmd.next_char] = kern(r)
|
| 409 |
+
else:
|
| 410 |
+
r = cmd.op_byte
|
| 411 |
+
if r == 4 or (r > 7 and r != 11):
|
| 412 |
+
# Ligature step with nonstandard code, we output
|
| 413 |
+
# the code verbatim.
|
| 414 |
+
lig = r
|
| 415 |
+
else:
|
| 416 |
+
lig = ""
|
| 417 |
+
if r % 4 > 1:
|
| 418 |
+
lig += "/"
|
| 419 |
+
lig += "LIG"
|
| 420 |
+
if r % 2 != 0:
|
| 421 |
+
lig += "/"
|
| 422 |
+
while r > 3:
|
| 423 |
+
lig += ">"
|
| 424 |
+
r -= 4
|
| 425 |
+
self.ligatures.setdefault(c, {})[cmd.next_char] = (
|
| 426 |
+
lig,
|
| 427 |
+
cmd.remainder,
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
if cmd.skip_byte >= STOP_FLAG:
|
| 431 |
+
break
|
| 432 |
+
i += cmd.skip_byte + 1
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
if __name__ == "__main__":
|
| 436 |
+
import sys
|
| 437 |
+
|
| 438 |
+
tfm = TFM(sys.argv[1])
|
| 439 |
+
print(
|
| 440 |
+
"\n".join(
|
| 441 |
+
x
|
| 442 |
+
for x in [
|
| 443 |
+
f"tfm.checksum={tfm.checksum}",
|
| 444 |
+
f"tfm.designsize={tfm.designsize}",
|
| 445 |
+
f"tfm.codingscheme={tfm.codingscheme}",
|
| 446 |
+
f"tfm.fonttype={tfm.fonttype}",
|
| 447 |
+
f"tfm.family={tfm.family}",
|
| 448 |
+
f"tfm.seven_bit_safe_flag={tfm.seven_bit_safe_flag}",
|
| 449 |
+
f"tfm.face={tfm.face}",
|
| 450 |
+
f"tfm.extraheader={tfm.extraheader}",
|
| 451 |
+
f"tfm.fontdimens={tfm.fontdimens}",
|
| 452 |
+
f"tfm.right_boundary_char={tfm.right_boundary_char}",
|
| 453 |
+
f"tfm.left_boundary_char={tfm.left_boundary_char}",
|
| 454 |
+
f"tfm.kerning={tfm.kerning}",
|
| 455 |
+
f"tfm.ligatures={tfm.ligatures}",
|
| 456 |
+
f"tfm.chars={tfm.chars}",
|
| 457 |
+
]
|
| 458 |
+
)
|
| 459 |
+
)
|
| 460 |
+
print(tfm)
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""fontTools.ttLib -- a package for dealing with TrueType fonts."""
|
| 2 |
+
|
| 3 |
+
from fontTools.config import OPTIONS
|
| 4 |
+
from fontTools.misc.loggingTools import deprecateFunction
|
| 5 |
+
import logging
|
| 6 |
+
|
| 7 |
+
log = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
OPTIMIZE_FONT_SPEED = OPTIONS["fontTools.ttLib:OPTIMIZE_FONT_SPEED"]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class TTLibError(Exception):
|
| 14 |
+
pass
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class TTLibFileIsCollectionError(TTLibError):
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@deprecateFunction("use logging instead", category=DeprecationWarning)
|
| 22 |
+
def debugmsg(msg):
|
| 23 |
+
import time
|
| 24 |
+
|
| 25 |
+
print(msg + time.strftime(" (%H:%M:%S)", time.localtime(time.time())))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
from fontTools.ttLib.ttFont import *
|
| 29 |
+
from fontTools.ttLib.tt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ibFileIsCollectionError
|
| 3 |
+
from fontTools.ttLib.ttFont import *
|
| 4 |
+
from fontTools.ttLib.ttCollection import TTCollection
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def main(args=None):
|
| 8 |
+
"""Open/save fonts with TTFont() or TTCollection()
|
| 9 |
+
|
| 10 |
+
./fonttools ttLib [-oFILE] [-yNUMBER] files...
|
| 11 |
+
|
| 12 |
+
If multiple files are given on the command-line,
|
| 13 |
+
they are each opened (as a font or collection),
|
| 14 |
+
and added to the font list.
|
| 15 |
+
|
| 16 |
+
If -o (output-file) argument is given, the font
|
| 17 |
+
list is then saved to the output file, either as
|
| 18 |
+
a single font, if there is only one font, or as
|
| 19 |
+
a collection otherwise.
|
| 20 |
+
|
| 21 |
+
If -y (font-number) argument is given, only the
|
| 22 |
+
specified font from collections is opened.
|
| 23 |
+
|
| 24 |
+
The above allow extracting a single font from a
|
| 25 |
+
collection, or combining multiple fonts into a
|
| 26 |
+
collection.
|
| 27 |
+
|
| 28 |
+
If --lazy or --no-lazy are give, those are passed
|
| 29 |
+
to the TTFont() or TTCollection() constructors.
|
| 30 |
+
"""
|
| 31 |
+
from fontTools import configLogger
|
| 32 |
+
|
| 33 |
+
if args is None:
|
| 34 |
+
args = sys.argv[1:]
|
| 35 |
+
|
| 36 |
+
import argparse
|
| 37 |
+
|
| 38 |
+
parser = argparse.ArgumentParser(
|
| 39 |
+
"fonttools ttLib",
|
| 40 |
+
description="Open/save fonts with TTFont() or TTCollection()",
|
| 41 |
+
epilog="""
|
| 42 |
+
If multiple files are given on the command-line,
|
| 43 |
+
they are each opened (as a font or collection),
|
| 44 |
+
and added to the font list.
|
| 45 |
+
|
| 46 |
+
The above, when combined with -o / --output,
|
| 47 |
+
allows for extracting a single font from a
|
| 48 |
+
collection, or combining multiple fonts into a
|
| 49 |
+
collection.
|
| 50 |
+
""",
|
| 51 |
+
)
|
| 52 |
+
parser.add_argument("font", metavar="font", nargs="*", help="Font file.")
|
| 53 |
+
parser.add_argument(
|
| 54 |
+
"-t", "--table", metavar="table", action="append", help="Tables to decompile."
|
| 55 |
+
)
|
| 56 |
+
parser.add_argument(
|
| 57 |
+
"-o", "--output", metavar="FILE", default=None, help="Output file."
|
| 58 |
+
)
|
| 59 |
+
parser.add_argument(
|
| 60 |
+
"-y", metavar="NUMBER", default=-1, help="Font number to load from collections."
|
| 61 |
+
)
|
| 62 |
+
parser.add_argument(
|
| 63 |
+
"--lazy", action="store_true", default=None, help="Load fonts lazily."
|
| 64 |
+
)
|
| 65 |
+
parser.add_argument(
|
| 66 |
+
"--no-lazy", dest="lazy", action="store_false", help="Load fonts immediately."
|
| 67 |
+
)
|
| 68 |
+
parser.add_argument(
|
| 69 |
+
"--flavor",
|
| 70 |
+
dest="flavor",
|
| 71 |
+
default=None,
|
| 72 |
+
help="Flavor of output font. 'woff' or 'woff2'.",
|
| 73 |
+
)
|
| 74 |
+
parser.add_argument(
|
| 75 |
+
"--no-recalc-timestamp",
|
| 76 |
+
dest="recalcTimestamp",
|
| 77 |
+
action="store_false",
|
| 78 |
+
help="Keep the original font 'modified' timestamp.",
|
| 79 |
+
)
|
| 80 |
+
parser.add_argument(
|
| 81 |
+
"-b",
|
| 82 |
+
dest="recalcBBoxes",
|
| 83 |
+
action="store_false",
|
| 84 |
+
help="Don't recalc glyph bounding boxes: use the values in the original font.",
|
| 85 |
+
)
|
| 86 |
+
parser.add_argument(
|
| 87 |
+
"--optimize-font-speed",
|
| 88 |
+
action="store_true",
|
| 89 |
+
help=(
|
| 90 |
+
"Enable optimizations that prioritize speed over file size. This "
|
| 91 |
+
"mainly affects how glyf table and gvar / VARC tables are compiled."
|
| 92 |
+
),
|
| 93 |
+
)
|
| 94 |
+
options = parser.parse_args(args)
|
| 95 |
+
|
| 96 |
+
fontNumber = int(options.y) if options.y is not None else None
|
| 97 |
+
outFile = options.output
|
| 98 |
+
lazy = options.lazy
|
| 99 |
+
flavor = options.flavor
|
| 100 |
+
tables = options.table
|
| 101 |
+
recalcBBoxes = options.recalcBBoxes
|
| 102 |
+
recalcTimestamp = options.recalcTimestamp
|
| 103 |
+
optimizeFontSpeed = options.optimize_font_speed
|
| 104 |
+
|
| 105 |
+
fonts = []
|
| 106 |
+
for f in options.font:
|
| 107 |
+
try:
|
| 108 |
+
font = TTFont(
|
| 109 |
+
f,
|
| 110 |
+
recalcBBoxes=recalcBBoxes,
|
| 111 |
+
recalcTimestamp=recalcTimestamp,
|
| 112 |
+
fontNumber=fontNumber,
|
| 113 |
+
lazy=lazy,
|
| 114 |
+
)
|
| 115 |
+
if optimizeFontSpeed:
|
| 116 |
+
font.cfg[OPTIMIZE_FONT_SPEED] = optimizeFontSpeed
|
| 117 |
+
fonts.append(font)
|
| 118 |
+
except TTLibFileIsCollectionError:
|
| 119 |
+
collection = TTCollection(f, lazy=lazy)
|
| 120 |
+
fonts.extend(collection.fonts)
|
| 121 |
+
|
| 122 |
+
if tables is None:
|
| 123 |
+
if lazy is False:
|
| 124 |
+
tables = ["*"]
|
| 125 |
+
elif optimizeFontSpeed:
|
| 126 |
+
tables = {"glyf", "gvar", "VARC"}.intersection(font.keys())
|
| 127 |
+
else:
|
| 128 |
+
tables = []
|
| 129 |
+
for font in fonts:
|
| 130 |
+
if "GlyphOrder" in tables:
|
| 131 |
+
font.getGlyphOrder()
|
| 132 |
+
for table in tables if "*" not in tables else font.keys():
|
| 133 |
+
font[table] # Decompiles
|
| 134 |
+
|
| 135 |
+
if outFile is not None:
|
| 136 |
+
if len(fonts) == 1:
|
| 137 |
+
fonts[0].flavor = flavor
|
| 138 |
+
fonts[0].save(outFile)
|
| 139 |
+
else:
|
| 140 |
+
if flavor is not None:
|
| 141 |
+
raise TTLibError("Cannot set flavor for collections.")
|
| 142 |
+
collection = TTCollection()
|
| 143 |
+
collection.fonts = fonts
|
| 144 |
+
collection.save(outFile)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
if __name__ == "__main__":
|
| 148 |
+
sys.exit(main())
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (1.46 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__main__.cpython-312.pyc
ADDED
|
Binary file (5.41 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/macUtils.cpython-312.pyc
ADDED
|
Binary file (2.72 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/removeOverlaps.cpython-312.pyc
ADDED
|
Binary file (15.5 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/reorderGlyphs.cpython-312.pyc
ADDED
|
Binary file (13.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/scaleUpem.cpython-312.pyc
ADDED
|
Binary file (18.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/sfnt.cpython-312.pyc
ADDED
|
Binary file (31.6 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/standardGlyphOrder.cpython-312.pyc
ADDED
|
Binary file (2.35 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttCollection.cpython-312.pyc
ADDED
|
Binary file (9.12 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttFont.cpython-312.pyc
ADDED
|
Binary file (83.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttGlyphSet.cpython-312.pyc
ADDED
|
Binary file (25.4 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttVisitor.cpython-312.pyc
ADDED
|
Binary file (1.68 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/woff2.cpython-312.pyc
ADDED
|
Binary file (73.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/macUtils.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ttLib.macUtils.py -- Various Mac-specific stuff."""
|
| 2 |
+
|
| 3 |
+
from io import BytesIO
|
| 4 |
+
from fontTools.misc.macRes import ResourceReader, ResourceError
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def getSFNTResIndices(path):
|
| 8 |
+
"""Determine whether a file has a 'sfnt' resource fork or not."""
|
| 9 |
+
try:
|
| 10 |
+
reader = ResourceReader(path)
|
| 11 |
+
indices = reader.getIndices("sfnt")
|
| 12 |
+
reader.close()
|
| 13 |
+
return indices
|
| 14 |
+
except ResourceError:
|
| 15 |
+
return []
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def openTTFonts(path):
|
| 19 |
+
"""Given a pathname, return a list of TTFont objects. In the case
|
| 20 |
+
of a flat TTF/OTF file, the list will contain just one font object;
|
| 21 |
+
but in the case of a Mac font suitcase it will contain as many
|
| 22 |
+
font objects as there are sfnt resources in the file.
|
| 23 |
+
"""
|
| 24 |
+
from fontTools import ttLib
|
| 25 |
+
|
| 26 |
+
fonts = []
|
| 27 |
+
sfnts = getSFNTResIndices(path)
|
| 28 |
+
if not sfnts:
|
| 29 |
+
fonts.append(ttLib.TTFont(path))
|
| 30 |
+
else:
|
| 31 |
+
for index in sfnts:
|
| 32 |
+
fonts.append(ttLib.TTFont(path, index))
|
| 33 |
+
if not fonts:
|
| 34 |
+
raise ttLib.TTLibError("no fonts found in file '%s'" % path)
|
| 35 |
+
return fonts
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class SFNTResourceReader(BytesIO):
|
| 39 |
+
"""Simple read-only file wrapper for 'sfnt' resources."""
|
| 40 |
+
|
| 41 |
+
def __init__(self, path, res_name_or_index):
|
| 42 |
+
from fontTools import ttLib
|
| 43 |
+
|
| 44 |
+
reader = ResourceReader(path)
|
| 45 |
+
if isinstance(res_name_or_index, str):
|
| 46 |
+
rsrc = reader.getNamedResource("sfnt", res_name_or_index)
|
| 47 |
+
else:
|
| 48 |
+
rsrc = reader.getIndResource("sfnt", res_name_or_index)
|
| 49 |
+
if rsrc is None:
|
| 50 |
+
raise ttLib.TTLibError("sfnt resource not found: %s" % res_name_or_index)
|
| 51 |
+
reader.close()
|
| 52 |
+
self.rsrc = rsrc
|
| 53 |
+
super(SFNTResourceReader, self).__init__(rsrc.data)
|
| 54 |
+
self.name = path
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/removeOverlaps.py
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
import logging
|
| 8 |
+
from typing import Callable, Iterable, Optional, Mapping
|
| 9 |
+
|
| 10 |
+
from fontTools.cffLib import CFFFontSet
|
| 11 |
+
from fontTools.ttLib import ttFont
|
| 12 |
+
from fontTools.ttLib.tables import _g_l_y_f
|
| 13 |
+
from fontTools.ttLib.tables import _h_m_t_x
|
| 14 |
+
from fontTools.misc.psCharStrings import T2CharString
|
| 15 |
+
from fontTools.misc.roundTools import otRound, noRound
|
| 16 |
+
from fontTools.pens.ttGlyphPen import TTGlyphPen
|
| 17 |
+
from fontTools.pens.t2CharStringPen import T2CharStringPen
|
| 18 |
+
|
| 19 |
+
import pathops
|
| 20 |
+
|
| 21 |
+
__all__ = ["removeOverlaps"]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class RemoveOverlapsError(Exception):
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
log = logging.getLogger("fontTools.ttLib.removeOverlaps")
|
| 29 |
+
|
| 30 |
+
_TTGlyphMapping = Mapping[str, ttFont._TTGlyph]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def skPathFromGlyph(glyphName: str, glyphSet: _TTGlyphMapping) -> pathops.Path:
|
| 34 |
+
path = pathops.Path()
|
| 35 |
+
pathPen = path.getPen(glyphSet=glyphSet)
|
| 36 |
+
glyphSet[glyphName].draw(pathPen)
|
| 37 |
+
return path
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def skPathFromGlyphComponent(
|
| 41 |
+
component: _g_l_y_f.GlyphComponent, glyphSet: _TTGlyphMapping
|
| 42 |
+
):
|
| 43 |
+
baseGlyphName, transformation = component.getComponentInfo()
|
| 44 |
+
path = skPathFromGlyph(baseGlyphName, glyphSet)
|
| 45 |
+
return path.transform(*transformation)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def componentsOverlap(glyph: _g_l_y_f.Glyph, glyphSet: _TTGlyphMapping) -> bool:
|
| 49 |
+
if not glyph.isComposite():
|
| 50 |
+
raise ValueError("This method only works with TrueType composite glyphs")
|
| 51 |
+
if len(glyph.components) < 2:
|
| 52 |
+
return False # single component, no overlaps
|
| 53 |
+
|
| 54 |
+
component_paths = {}
|
| 55 |
+
|
| 56 |
+
def _get_nth_component_path(index: int) -> pathops.Path:
|
| 57 |
+
if index not in component_paths:
|
| 58 |
+
component_paths[index] = skPathFromGlyphComponent(
|
| 59 |
+
glyph.components[index], glyphSet
|
| 60 |
+
)
|
| 61 |
+
return component_paths[index]
|
| 62 |
+
|
| 63 |
+
return any(
|
| 64 |
+
pathops.op(
|
| 65 |
+
_get_nth_component_path(i),
|
| 66 |
+
_get_nth_component_path(j),
|
| 67 |
+
pathops.PathOp.INTERSECTION,
|
| 68 |
+
fix_winding=False,
|
| 69 |
+
keep_starting_points=False,
|
| 70 |
+
)
|
| 71 |
+
for i, j in itertools.combinations(range(len(glyph.components)), 2)
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def ttfGlyphFromSkPath(path: pathops.Path) -> _g_l_y_f.Glyph:
|
| 76 |
+
# Skia paths have no 'components', no need for glyphSet
|
| 77 |
+
ttPen = TTGlyphPen(glyphSet=None)
|
| 78 |
+
path.draw(ttPen)
|
| 79 |
+
glyph = ttPen.glyph()
|
| 80 |
+
assert not glyph.isComposite()
|
| 81 |
+
# compute glyph.xMin (glyfTable parameter unused for non composites)
|
| 82 |
+
glyph.recalcBounds(glyfTable=None)
|
| 83 |
+
return glyph
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _charString_from_SkPath(
|
| 87 |
+
path: pathops.Path, charString: T2CharString
|
| 88 |
+
) -> T2CharString:
|
| 89 |
+
if charString.width == charString.private.defaultWidthX:
|
| 90 |
+
width = None
|
| 91 |
+
else:
|
| 92 |
+
width = charString.width - charString.private.nominalWidthX
|
| 93 |
+
t2Pen = T2CharStringPen(width=width, glyphSet=None)
|
| 94 |
+
path.draw(t2Pen)
|
| 95 |
+
return t2Pen.getCharString(charString.private, charString.globalSubrs)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _round_path(
|
| 99 |
+
path: pathops.Path, round: Callable[[float], float] = otRound
|
| 100 |
+
) -> pathops.Path:
|
| 101 |
+
rounded_path = pathops.Path()
|
| 102 |
+
for verb, points in path:
|
| 103 |
+
rounded_path.add(verb, *((round(p[0]), round(p[1])) for p in points))
|
| 104 |
+
return rounded_path
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _simplify(
|
| 108 |
+
path: pathops.Path,
|
| 109 |
+
debugGlyphName: str,
|
| 110 |
+
*,
|
| 111 |
+
round: Callable[[float], float] = otRound,
|
| 112 |
+
) -> pathops.Path:
|
| 113 |
+
# skia-pathops has a bug where it sometimes fails to simplify paths when there
|
| 114 |
+
# are float coordinates and control points are very close to one another.
|
| 115 |
+
# Rounding coordinates to integers works around the bug.
|
| 116 |
+
# Since we are going to round glyf coordinates later on anyway, here it is
|
| 117 |
+
# ok(-ish) to also round before simplify. Better than failing the whole process
|
| 118 |
+
# for the entire font.
|
| 119 |
+
# https://bugs.chromium.org/p/skia/issues/detail?id=11958
|
| 120 |
+
# https://github.com/google/fonts/issues/3365
|
| 121 |
+
# TODO(anthrotype): remove once this Skia bug is fixed
|
| 122 |
+
try:
|
| 123 |
+
return pathops.simplify(path, clockwise=path.clockwise)
|
| 124 |
+
except pathops.PathOpsError:
|
| 125 |
+
pass
|
| 126 |
+
|
| 127 |
+
path = _round_path(path, round=round)
|
| 128 |
+
try:
|
| 129 |
+
path = pathops.simplify(path, clockwise=path.clockwise)
|
| 130 |
+
log.debug(
|
| 131 |
+
"skia-pathops failed to simplify '%s' with float coordinates, "
|
| 132 |
+
"but succeded using rounded integer coordinates",
|
| 133 |
+
debugGlyphName,
|
| 134 |
+
)
|
| 135 |
+
return path
|
| 136 |
+
except pathops.PathOpsError as e:
|
| 137 |
+
if log.isEnabledFor(logging.DEBUG):
|
| 138 |
+
path.dump()
|
| 139 |
+
raise RemoveOverlapsError(
|
| 140 |
+
f"Failed to remove overlaps from glyph {debugGlyphName!r}"
|
| 141 |
+
) from e
|
| 142 |
+
|
| 143 |
+
raise AssertionError("Unreachable")
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _same_path(path1: pathops.Path, path2: pathops.Path) -> bool:
|
| 147 |
+
return {tuple(c) for c in path1.contours} == {tuple(c) for c in path2.contours}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def removeTTGlyphOverlaps(
|
| 151 |
+
glyphName: str,
|
| 152 |
+
glyphSet: _TTGlyphMapping,
|
| 153 |
+
glyfTable: _g_l_y_f.table__g_l_y_f,
|
| 154 |
+
hmtxTable: _h_m_t_x.table__h_m_t_x,
|
| 155 |
+
removeHinting: bool = True,
|
| 156 |
+
) -> bool:
|
| 157 |
+
glyph = glyfTable[glyphName]
|
| 158 |
+
# decompose composite glyphs only if components overlap each other
|
| 159 |
+
if (
|
| 160 |
+
glyph.numberOfContours > 0
|
| 161 |
+
or glyph.isComposite()
|
| 162 |
+
and componentsOverlap(glyph, glyphSet)
|
| 163 |
+
):
|
| 164 |
+
path = skPathFromGlyph(glyphName, glyphSet)
|
| 165 |
+
|
| 166 |
+
# remove overlaps
|
| 167 |
+
path2 = _simplify(path, glyphName)
|
| 168 |
+
|
| 169 |
+
# replace TTGlyph if simplified path is different (ignoring contour order)
|
| 170 |
+
if not _same_path(path, path2):
|
| 171 |
+
glyfTable[glyphName] = glyph = ttfGlyphFromSkPath(path2)
|
| 172 |
+
# simplified glyph is always unhinted
|
| 173 |
+
assert not glyph.program
|
| 174 |
+
# also ensure hmtx LSB == glyph.xMin so glyph origin is at x=0
|
| 175 |
+
width, lsb = hmtxTable[glyphName]
|
| 176 |
+
if lsb != glyph.xMin:
|
| 177 |
+
hmtxTable[glyphName] = (width, glyph.xMin)
|
| 178 |
+
return True
|
| 179 |
+
|
| 180 |
+
if removeHinting:
|
| 181 |
+
glyph.removeHinting()
|
| 182 |
+
return False
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _remove_glyf_overlaps(
|
| 186 |
+
*,
|
| 187 |
+
font: ttFont.TTFont,
|
| 188 |
+
glyphNames: Iterable[str],
|
| 189 |
+
glyphSet: _TTGlyphMapping,
|
| 190 |
+
removeHinting: bool,
|
| 191 |
+
ignoreErrors: bool,
|
| 192 |
+
) -> None:
|
| 193 |
+
glyfTable = font["glyf"]
|
| 194 |
+
hmtxTable = font["hmtx"]
|
| 195 |
+
|
| 196 |
+
# process all simple glyphs first, then composites with increasing component depth,
|
| 197 |
+
# so that by the time we test for component intersections the respective base glyphs
|
| 198 |
+
# have already been simplified
|
| 199 |
+
glyphNames = sorted(
|
| 200 |
+
glyphNames,
|
| 201 |
+
key=lambda name: (
|
| 202 |
+
(
|
| 203 |
+
glyfTable[name].getCompositeMaxpValues(glyfTable).maxComponentDepth
|
| 204 |
+
if glyfTable[name].isComposite()
|
| 205 |
+
else 0
|
| 206 |
+
),
|
| 207 |
+
name,
|
| 208 |
+
),
|
| 209 |
+
)
|
| 210 |
+
modified = set()
|
| 211 |
+
for glyphName in glyphNames:
|
| 212 |
+
try:
|
| 213 |
+
if removeTTGlyphOverlaps(
|
| 214 |
+
glyphName, glyphSet, glyfTable, hmtxTable, removeHinting
|
| 215 |
+
):
|
| 216 |
+
modified.add(glyphName)
|
| 217 |
+
except RemoveOverlapsError:
|
| 218 |
+
if not ignoreErrors:
|
| 219 |
+
raise
|
| 220 |
+
log.error("Failed to remove overlaps for '%s'", glyphName)
|
| 221 |
+
|
| 222 |
+
log.debug("Removed overlaps for %s glyphs:\n%s", len(modified), " ".join(modified))
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def _remove_charstring_overlaps(
|
| 226 |
+
*,
|
| 227 |
+
glyphName: str,
|
| 228 |
+
glyphSet: _TTGlyphMapping,
|
| 229 |
+
cffFontSet: CFFFontSet,
|
| 230 |
+
) -> bool:
|
| 231 |
+
path = skPathFromGlyph(glyphName, glyphSet)
|
| 232 |
+
|
| 233 |
+
# remove overlaps
|
| 234 |
+
path2 = _simplify(path, glyphName, round=noRound)
|
| 235 |
+
|
| 236 |
+
# replace TTGlyph if simplified path is different (ignoring contour order)
|
| 237 |
+
if not _same_path(path, path2):
|
| 238 |
+
charStrings = cffFontSet[0].CharStrings
|
| 239 |
+
charStrings[glyphName] = _charString_from_SkPath(path2, charStrings[glyphName])
|
| 240 |
+
return True
|
| 241 |
+
|
| 242 |
+
return False
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _remove_cff_overlaps(
|
| 246 |
+
*,
|
| 247 |
+
font: ttFont.TTFont,
|
| 248 |
+
glyphNames: Iterable[str],
|
| 249 |
+
glyphSet: _TTGlyphMapping,
|
| 250 |
+
removeHinting: bool,
|
| 251 |
+
ignoreErrors: bool,
|
| 252 |
+
table_tag: str,
|
| 253 |
+
removeUnusedSubroutines: bool = True,
|
| 254 |
+
) -> None:
|
| 255 |
+
cffFontSet = font[table_tag].cff
|
| 256 |
+
modified = set()
|
| 257 |
+
for glyphName in glyphNames:
|
| 258 |
+
try:
|
| 259 |
+
if _remove_charstring_overlaps(
|
| 260 |
+
glyphName=glyphName,
|
| 261 |
+
glyphSet=glyphSet,
|
| 262 |
+
cffFontSet=cffFontSet,
|
| 263 |
+
):
|
| 264 |
+
modified.add(glyphName)
|
| 265 |
+
except RemoveOverlapsError:
|
| 266 |
+
if not ignoreErrors:
|
| 267 |
+
raise
|
| 268 |
+
log.error("Failed to remove overlaps for '%s'", glyphName)
|
| 269 |
+
|
| 270 |
+
if not modified:
|
| 271 |
+
log.debug("No overlaps found in the specified CFF glyphs")
|
| 272 |
+
return
|
| 273 |
+
|
| 274 |
+
if removeHinting:
|
| 275 |
+
cffFontSet.remove_hints()
|
| 276 |
+
|
| 277 |
+
if removeUnusedSubroutines:
|
| 278 |
+
cffFontSet.remove_unused_subroutines()
|
| 279 |
+
|
| 280 |
+
log.debug("Removed overlaps for %s glyphs:\n%s", len(modified), " ".join(modified))
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def removeOverlaps(
|
| 284 |
+
font: ttFont.TTFont,
|
| 285 |
+
glyphNames: Optional[Iterable[str]] = None,
|
| 286 |
+
removeHinting: bool = True,
|
| 287 |
+
ignoreErrors: bool = False,
|
| 288 |
+
*,
|
| 289 |
+
removeUnusedSubroutines: bool = True,
|
| 290 |
+
) -> None:
|
| 291 |
+
"""Simplify glyphs in TTFont by merging overlapping contours.
|
| 292 |
+
|
| 293 |
+
Overlapping components are first decomposed to simple contours, then merged.
|
| 294 |
+
|
| 295 |
+
Currently this only works for fonts with 'glyf' or 'CFF ' tables.
|
| 296 |
+
Raises NotImplementedError if 'glyf' or 'CFF ' tables are absent.
|
| 297 |
+
|
| 298 |
+
Note that removing overlaps invalidates the hinting. By default we drop hinting
|
| 299 |
+
from all glyphs whether or not overlaps are removed from a given one, as it would
|
| 300 |
+
look weird if only some glyphs are left (un)hinted.
|
| 301 |
+
|
| 302 |
+
Args:
|
| 303 |
+
font: input TTFont object, modified in place.
|
| 304 |
+
glyphNames: optional iterable of glyph names (str) to remove overlaps from.
|
| 305 |
+
By default, all glyphs in the font are processed.
|
| 306 |
+
removeHinting (bool): set to False to keep hinting for unmodified glyphs.
|
| 307 |
+
ignoreErrors (bool): set to True to ignore errors while removing overlaps,
|
| 308 |
+
thus keeping the tricky glyphs unchanged (fonttools/fonttools#2363).
|
| 309 |
+
removeUnusedSubroutines (bool): set to False to keep unused subroutines
|
| 310 |
+
in CFF table after removing overlaps. Default is to remove them if
|
| 311 |
+
any glyphs are modified.
|
| 312 |
+
"""
|
| 313 |
+
|
| 314 |
+
if "glyf" not in font and "CFF " not in font and "CFF2" not in font:
|
| 315 |
+
raise NotImplementedError(
|
| 316 |
+
"No outline data found in the font: missing 'glyf', 'CFF ', or 'CFF2' table"
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
if glyphNames is None:
|
| 320 |
+
glyphNames = font.getGlyphOrder()
|
| 321 |
+
|
| 322 |
+
# Wraps the underlying glyphs, takes care of interfacing with drawing pens
|
| 323 |
+
glyphSet = font.getGlyphSet()
|
| 324 |
+
|
| 325 |
+
if "glyf" in font:
|
| 326 |
+
_remove_glyf_overlaps(
|
| 327 |
+
font=font,
|
| 328 |
+
glyphNames=glyphNames,
|
| 329 |
+
glyphSet=glyphSet,
|
| 330 |
+
removeHinting=removeHinting,
|
| 331 |
+
ignoreErrors=ignoreErrors,
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
if "CFF " in font or "CFF2" in font:
|
| 335 |
+
_remove_cff_overlaps(
|
| 336 |
+
font=font,
|
| 337 |
+
glyphNames=glyphNames,
|
| 338 |
+
glyphSet=glyphSet,
|
| 339 |
+
removeHinting=removeHinting,
|
| 340 |
+
ignoreErrors=ignoreErrors,
|
| 341 |
+
table_tag="CFF " if "CFF " in font else "CFF2",
|
| 342 |
+
removeUnusedSubroutines=removeUnusedSubroutines,
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def main(args=None):
|
| 347 |
+
"""Simplify glyphs in TTFont by merging overlapping contours."""
|
| 348 |
+
|
| 349 |
+
import argparse
|
| 350 |
+
|
| 351 |
+
parser = argparse.ArgumentParser(
|
| 352 |
+
"fonttools ttLib.removeOverlaps", description=__doc__
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
parser.add_argument("input", metavar="INPUT.ttf", help="Input font file")
|
| 356 |
+
parser.add_argument("output", metavar="OUTPUT.ttf", help="Output font file")
|
| 357 |
+
parser.add_argument(
|
| 358 |
+
"glyphs",
|
| 359 |
+
metavar="GLYPHS",
|
| 360 |
+
nargs="*",
|
| 361 |
+
help="Optional list of glyph names to remove overlaps from",
|
| 362 |
+
)
|
| 363 |
+
parser.add_argument(
|
| 364 |
+
"--keep-hinting",
|
| 365 |
+
action="store_true",
|
| 366 |
+
help="Keep hinting for unmodified glyphs, default is to drop hinting",
|
| 367 |
+
)
|
| 368 |
+
parser.add_argument(
|
| 369 |
+
"--ignore-errors",
|
| 370 |
+
action="store_true",
|
| 371 |
+
help="ignore errors while removing overlaps, "
|
| 372 |
+
"thus keeping the tricky glyphs unchanged",
|
| 373 |
+
)
|
| 374 |
+
parser.add_argument(
|
| 375 |
+
"--keep-unused-subroutines",
|
| 376 |
+
action="store_true",
|
| 377 |
+
help="Keep unused subroutines in CFF table after removing overlaps, "
|
| 378 |
+
"default is to remove them if any glyphs are modified",
|
| 379 |
+
)
|
| 380 |
+
args = parser.parse_args(args)
|
| 381 |
+
|
| 382 |
+
with ttFont.TTFont(args.input) as font:
|
| 383 |
+
removeOverlaps(
|
| 384 |
+
font=font,
|
| 385 |
+
glyphNames=args.glyphs or None,
|
| 386 |
+
removeHinting=not args.keep_hinting,
|
| 387 |
+
ignoreErrors=args.ignore_errors,
|
| 388 |
+
removeUnusedSubroutines=not args.keep_unused_subroutines,
|
| 389 |
+
)
|
| 390 |
+
font.save(args.output)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
if __name__ == "__main__":
|
| 394 |
+
main()
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/reorderGlyphs.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reorder glyphs in a font."""
|
| 2 |
+
|
| 3 |
+
__author__ = "Rod Sheeter"
|
| 4 |
+
|
| 5 |
+
# See https://docs.google.com/document/d/1h9O-C_ndods87uY0QeIIcgAMiX2gDTpvO_IhMJsKAqs/
|
| 6 |
+
# for details.
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
from fontTools import ttLib
|
| 10 |
+
from fontTools.ttLib.tables import otBase
|
| 11 |
+
from fontTools.ttLib.tables import otTables as ot
|
| 12 |
+
from abc import ABC, abstractmethod
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
+
from collections import deque
|
| 15 |
+
from typing import (
|
| 16 |
+
Optional,
|
| 17 |
+
Any,
|
| 18 |
+
Callable,
|
| 19 |
+
Deque,
|
| 20 |
+
Iterable,
|
| 21 |
+
List,
|
| 22 |
+
Tuple,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
_COVERAGE_ATTR = "Coverage" # tables that have one coverage use this name
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _sort_by_gid(
|
| 29 |
+
get_glyph_id: Callable[[str], int],
|
| 30 |
+
glyphs: List[str],
|
| 31 |
+
parallel_list: Optional[List[Any]],
|
| 32 |
+
):
|
| 33 |
+
if parallel_list:
|
| 34 |
+
reordered = sorted(
|
| 35 |
+
((g, e) for g, e in zip(glyphs, parallel_list)),
|
| 36 |
+
key=lambda t: get_glyph_id(t[0]),
|
| 37 |
+
)
|
| 38 |
+
sorted_glyphs, sorted_parallel_list = map(list, zip(*reordered))
|
| 39 |
+
parallel_list[:] = sorted_parallel_list
|
| 40 |
+
else:
|
| 41 |
+
sorted_glyphs = sorted(glyphs, key=get_glyph_id)
|
| 42 |
+
|
| 43 |
+
glyphs[:] = sorted_glyphs
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _get_dotted_attr(value: Any, dotted_attr: str) -> Any:
|
| 47 |
+
attr_names = dotted_attr.split(".")
|
| 48 |
+
assert attr_names
|
| 49 |
+
|
| 50 |
+
while attr_names:
|
| 51 |
+
attr_name = attr_names.pop(0)
|
| 52 |
+
value = getattr(value, attr_name)
|
| 53 |
+
return value
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class ReorderRule(ABC):
|
| 57 |
+
"""A rule to reorder something in a font to match the fonts glyph order."""
|
| 58 |
+
|
| 59 |
+
@abstractmethod
|
| 60 |
+
def apply(self, font: ttLib.TTFont, value: otBase.BaseTable) -> None: ...
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@dataclass(frozen=True)
|
| 64 |
+
class ReorderCoverage(ReorderRule):
|
| 65 |
+
"""Reorder a Coverage table, and optionally a list that is sorted parallel to it."""
|
| 66 |
+
|
| 67 |
+
# A list that is parallel to Coverage
|
| 68 |
+
parallel_list_attr: Optional[str] = None
|
| 69 |
+
coverage_attr: str = _COVERAGE_ATTR
|
| 70 |
+
|
| 71 |
+
def apply(self, font: ttLib.TTFont, value: otBase.BaseTable) -> None:
|
| 72 |
+
coverage = _get_dotted_attr(value, self.coverage_attr)
|
| 73 |
+
|
| 74 |
+
if type(coverage) is not list:
|
| 75 |
+
# Normal path, process one coverage that might have a parallel list
|
| 76 |
+
parallel_list = None
|
| 77 |
+
if self.parallel_list_attr:
|
| 78 |
+
parallel_list = _get_dotted_attr(value, self.parallel_list_attr)
|
| 79 |
+
assert (
|
| 80 |
+
type(parallel_list) is list
|
| 81 |
+
), f"{self.parallel_list_attr} should be a list"
|
| 82 |
+
assert len(parallel_list) == len(coverage.glyphs), "Nothing makes sense"
|
| 83 |
+
|
| 84 |
+
_sort_by_gid(font.getGlyphID, coverage.glyphs, parallel_list)
|
| 85 |
+
|
| 86 |
+
else:
|
| 87 |
+
# A few tables have a list of coverage. No parallel list can exist.
|
| 88 |
+
assert (
|
| 89 |
+
not self.parallel_list_attr
|
| 90 |
+
), f"Can't have multiple coverage AND a parallel list; {self}"
|
| 91 |
+
for coverage_entry in coverage:
|
| 92 |
+
_sort_by_gid(font.getGlyphID, coverage_entry.glyphs, None)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@dataclass(frozen=True)
|
| 96 |
+
class ReorderList(ReorderRule):
|
| 97 |
+
"""Reorder the items within a list to match the updated glyph order.
|
| 98 |
+
|
| 99 |
+
Useful when a list ordered by coverage itself contains something ordered by a gid.
|
| 100 |
+
For example, the PairSet table of https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-2-pair-adjustment-positioning-subtable.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
list_attr: str
|
| 104 |
+
key: str
|
| 105 |
+
|
| 106 |
+
def apply(self, font: ttLib.TTFont, value: otBase.BaseTable) -> None:
|
| 107 |
+
lst = _get_dotted_attr(value, self.list_attr)
|
| 108 |
+
assert isinstance(lst, list), f"{self.list_attr} should be a list"
|
| 109 |
+
lst.sort(key=lambda v: font.getGlyphID(getattr(v, self.key)))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# (Type, Optional Format) => List[ReorderRule]
|
| 113 |
+
# Encodes the relationships Cosimo identified
|
| 114 |
+
_REORDER_RULES = {
|
| 115 |
+
# GPOS
|
| 116 |
+
(ot.SinglePos, 1): [ReorderCoverage()],
|
| 117 |
+
(ot.SinglePos, 2): [ReorderCoverage(parallel_list_attr="Value")],
|
| 118 |
+
(ot.PairPos, 1): [ReorderCoverage(parallel_list_attr="PairSet")],
|
| 119 |
+
(ot.PairSet, None): [ReorderList("PairValueRecord", key="SecondGlyph")],
|
| 120 |
+
(ot.PairPos, 2): [ReorderCoverage()],
|
| 121 |
+
(ot.CursivePos, 1): [ReorderCoverage(parallel_list_attr="EntryExitRecord")],
|
| 122 |
+
(ot.MarkBasePos, 1): [
|
| 123 |
+
ReorderCoverage(
|
| 124 |
+
coverage_attr="MarkCoverage", parallel_list_attr="MarkArray.MarkRecord"
|
| 125 |
+
),
|
| 126 |
+
ReorderCoverage(
|
| 127 |
+
coverage_attr="BaseCoverage", parallel_list_attr="BaseArray.BaseRecord"
|
| 128 |
+
),
|
| 129 |
+
],
|
| 130 |
+
(ot.MarkLigPos, 1): [
|
| 131 |
+
ReorderCoverage(
|
| 132 |
+
coverage_attr="MarkCoverage", parallel_list_attr="MarkArray.MarkRecord"
|
| 133 |
+
),
|
| 134 |
+
ReorderCoverage(
|
| 135 |
+
coverage_attr="LigatureCoverage",
|
| 136 |
+
parallel_list_attr="LigatureArray.LigatureAttach",
|
| 137 |
+
),
|
| 138 |
+
],
|
| 139 |
+
(ot.MarkMarkPos, 1): [
|
| 140 |
+
ReorderCoverage(
|
| 141 |
+
coverage_attr="Mark1Coverage", parallel_list_attr="Mark1Array.MarkRecord"
|
| 142 |
+
),
|
| 143 |
+
ReorderCoverage(
|
| 144 |
+
coverage_attr="Mark2Coverage", parallel_list_attr="Mark2Array.Mark2Record"
|
| 145 |
+
),
|
| 146 |
+
],
|
| 147 |
+
(ot.ContextPos, 1): [ReorderCoverage(parallel_list_attr="PosRuleSet")],
|
| 148 |
+
(ot.ContextPos, 2): [ReorderCoverage()],
|
| 149 |
+
(ot.ContextPos, 3): [ReorderCoverage()],
|
| 150 |
+
(ot.ChainContextPos, 1): [ReorderCoverage(parallel_list_attr="ChainPosRuleSet")],
|
| 151 |
+
(ot.ChainContextPos, 2): [ReorderCoverage()],
|
| 152 |
+
(ot.ChainContextPos, 3): [
|
| 153 |
+
ReorderCoverage(coverage_attr="BacktrackCoverage"),
|
| 154 |
+
ReorderCoverage(coverage_attr="InputCoverage"),
|
| 155 |
+
ReorderCoverage(coverage_attr="LookAheadCoverage"),
|
| 156 |
+
],
|
| 157 |
+
# GSUB
|
| 158 |
+
(ot.ContextSubst, 1): [ReorderCoverage(parallel_list_attr="SubRuleSet")],
|
| 159 |
+
(ot.ContextSubst, 2): [ReorderCoverage()],
|
| 160 |
+
(ot.ContextSubst, 3): [ReorderCoverage()],
|
| 161 |
+
(ot.ChainContextSubst, 1): [ReorderCoverage(parallel_list_attr="ChainSubRuleSet")],
|
| 162 |
+
(ot.ChainContextSubst, 2): [ReorderCoverage()],
|
| 163 |
+
(ot.ChainContextSubst, 3): [
|
| 164 |
+
ReorderCoverage(coverage_attr="BacktrackCoverage"),
|
| 165 |
+
ReorderCoverage(coverage_attr="InputCoverage"),
|
| 166 |
+
ReorderCoverage(coverage_attr="LookAheadCoverage"),
|
| 167 |
+
],
|
| 168 |
+
(ot.ReverseChainSingleSubst, 1): [
|
| 169 |
+
ReorderCoverage(parallel_list_attr="Substitute"),
|
| 170 |
+
ReorderCoverage(coverage_attr="BacktrackCoverage"),
|
| 171 |
+
ReorderCoverage(coverage_attr="LookAheadCoverage"),
|
| 172 |
+
],
|
| 173 |
+
# GDEF
|
| 174 |
+
(ot.AttachList, None): [ReorderCoverage(parallel_list_attr="AttachPoint")],
|
| 175 |
+
(ot.LigCaretList, None): [ReorderCoverage(parallel_list_attr="LigGlyph")],
|
| 176 |
+
(ot.MarkGlyphSetsDef, None): [ReorderCoverage()],
|
| 177 |
+
# MATH
|
| 178 |
+
(ot.MathGlyphInfo, None): [ReorderCoverage(coverage_attr="ExtendedShapeCoverage")],
|
| 179 |
+
(ot.MathItalicsCorrectionInfo, None): [
|
| 180 |
+
ReorderCoverage(parallel_list_attr="ItalicsCorrection")
|
| 181 |
+
],
|
| 182 |
+
(ot.MathTopAccentAttachment, None): [
|
| 183 |
+
ReorderCoverage(
|
| 184 |
+
coverage_attr="TopAccentCoverage", parallel_list_attr="TopAccentAttachment"
|
| 185 |
+
)
|
| 186 |
+
],
|
| 187 |
+
(ot.MathKernInfo, None): [
|
| 188 |
+
ReorderCoverage(
|
| 189 |
+
coverage_attr="MathKernCoverage", parallel_list_attr="MathKernInfoRecords"
|
| 190 |
+
)
|
| 191 |
+
],
|
| 192 |
+
(ot.MathVariants, None): [
|
| 193 |
+
ReorderCoverage(
|
| 194 |
+
coverage_attr="VertGlyphCoverage",
|
| 195 |
+
parallel_list_attr="VertGlyphConstruction",
|
| 196 |
+
),
|
| 197 |
+
ReorderCoverage(
|
| 198 |
+
coverage_attr="HorizGlyphCoverage",
|
| 199 |
+
parallel_list_attr="HorizGlyphConstruction",
|
| 200 |
+
),
|
| 201 |
+
],
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
# TODO Port to otTraverse
|
| 206 |
+
|
| 207 |
+
SubTablePath = Tuple[otBase.BaseTable.SubTableEntry, ...]
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def _bfs_base_table(
|
| 211 |
+
root: otBase.BaseTable, root_accessor: str
|
| 212 |
+
) -> Iterable[SubTablePath]:
|
| 213 |
+
yield from _traverse_ot_data(
|
| 214 |
+
root, root_accessor, lambda frontier, new: frontier.extend(new)
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# Given f(current frontier, new entries) add new entries to frontier
|
| 219 |
+
AddToFrontierFn = Callable[[Deque[SubTablePath], List[SubTablePath]], None]
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _traverse_ot_data(
|
| 223 |
+
root: otBase.BaseTable, root_accessor: str, add_to_frontier_fn: AddToFrontierFn
|
| 224 |
+
) -> Iterable[SubTablePath]:
|
| 225 |
+
# no visited because general otData is forward-offset only and thus cannot cycle
|
| 226 |
+
|
| 227 |
+
frontier: Deque[SubTablePath] = deque()
|
| 228 |
+
frontier.append((otBase.BaseTable.SubTableEntry(root_accessor, root),))
|
| 229 |
+
while frontier:
|
| 230 |
+
# path is (value, attr_name) tuples. attr_name is attr of parent to get value
|
| 231 |
+
path = frontier.popleft()
|
| 232 |
+
current = path[-1].value
|
| 233 |
+
|
| 234 |
+
yield path
|
| 235 |
+
|
| 236 |
+
new_entries = []
|
| 237 |
+
for subtable_entry in current.iterSubTables():
|
| 238 |
+
new_entries.append(path + (subtable_entry,))
|
| 239 |
+
|
| 240 |
+
add_to_frontier_fn(frontier, new_entries)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def reorderGlyphs(font: ttLib.TTFont, new_glyph_order: List[str]):
|
| 244 |
+
old_glyph_order = font.getGlyphOrder()
|
| 245 |
+
if len(new_glyph_order) != len(old_glyph_order):
|
| 246 |
+
raise ValueError(
|
| 247 |
+
f"New glyph order contains {len(new_glyph_order)} glyphs, "
|
| 248 |
+
f"but font has {len(old_glyph_order)} glyphs"
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
if set(old_glyph_order) != set(new_glyph_order):
|
| 252 |
+
raise ValueError(
|
| 253 |
+
"New glyph order does not contain the same set of glyphs as the font:\n"
|
| 254 |
+
f"* only in new: {set(new_glyph_order) - set(old_glyph_order)}\n"
|
| 255 |
+
f"* only in old: {set(old_glyph_order) - set(new_glyph_order)}"
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
# Changing the order of glyphs in a TTFont requires that all tables that use
|
| 259 |
+
# glyph indexes have been fully.
|
| 260 |
+
# Cf. https://github.com/fonttools/fonttools/issues/2060
|
| 261 |
+
font.ensureDecompiled()
|
| 262 |
+
not_loaded = sorted(t for t in font.keys() if not font.isLoaded(t))
|
| 263 |
+
if not_loaded:
|
| 264 |
+
raise ValueError(f"Everything should be loaded, following aren't: {not_loaded}")
|
| 265 |
+
|
| 266 |
+
font.setGlyphOrder(new_glyph_order)
|
| 267 |
+
|
| 268 |
+
coverage_containers = {"GDEF", "GPOS", "GSUB", "MATH"}
|
| 269 |
+
for tag in coverage_containers:
|
| 270 |
+
if tag in font.keys():
|
| 271 |
+
for path in _bfs_base_table(font[tag].table, f'font["{tag}"]'):
|
| 272 |
+
value = path[-1].value
|
| 273 |
+
reorder_key = (type(value), getattr(value, "Format", None))
|
| 274 |
+
for reorder in _REORDER_RULES.get(reorder_key, []):
|
| 275 |
+
reorder.apply(font, value)
|
| 276 |
+
|
| 277 |
+
for tag in ["CFF ", "CFF2"]:
|
| 278 |
+
if tag in font:
|
| 279 |
+
cff_table = font[tag]
|
| 280 |
+
charstrings = cff_table.cff.topDictIndex[0].CharStrings.charStrings
|
| 281 |
+
cff_table.cff.topDictIndex[0].charset = new_glyph_order
|
| 282 |
+
cff_table.cff.topDictIndex[0].CharStrings.charStrings = {
|
| 283 |
+
k: charstrings.get(k) for k in new_glyph_order
|
| 284 |
+
}
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/scaleUpem.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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.ttVisitor import TTVisitor
|
| 7 |
+
import fontTools.ttLib as ttLib
|
| 8 |
+
import fontTools.ttLib.tables.otBase as otBase
|
| 9 |
+
import fontTools.ttLib.tables.otTables as otTables
|
| 10 |
+
from fontTools.cffLib import VarStoreData
|
| 11 |
+
import fontTools.cffLib.specializer as cffSpecializer
|
| 12 |
+
from fontTools.varLib import builder # for VarData.calculateNumShorts
|
| 13 |
+
from fontTools.varLib.multiVarStore import OnlineMultiVarStoreBuilder
|
| 14 |
+
from fontTools.misc.vector import Vector
|
| 15 |
+
from fontTools.misc.fixedTools import otRound
|
| 16 |
+
from fontTools.misc.iterTools import batched
|
| 17 |
+
|
| 18 |
+
__all__ = ["scale_upem", "ScalerVisitor"]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ScalerVisitor(TTVisitor):
|
| 22 |
+
def __init__(self, scaleFactor):
|
| 23 |
+
self.scaleFactor = scaleFactor
|
| 24 |
+
|
| 25 |
+
def scale(self, v):
|
| 26 |
+
return otRound(v * self.scaleFactor)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@ScalerVisitor.register_attrs(
|
| 30 |
+
(
|
| 31 |
+
(ttLib.getTableClass("head"), ("unitsPerEm", "xMin", "yMin", "xMax", "yMax")),
|
| 32 |
+
(ttLib.getTableClass("post"), ("underlinePosition", "underlineThickness")),
|
| 33 |
+
(ttLib.getTableClass("VORG"), ("defaultVertOriginY")),
|
| 34 |
+
(
|
| 35 |
+
ttLib.getTableClass("hhea"),
|
| 36 |
+
(
|
| 37 |
+
"ascent",
|
| 38 |
+
"descent",
|
| 39 |
+
"lineGap",
|
| 40 |
+
"advanceWidthMax",
|
| 41 |
+
"minLeftSideBearing",
|
| 42 |
+
"minRightSideBearing",
|
| 43 |
+
"xMaxExtent",
|
| 44 |
+
"caretOffset",
|
| 45 |
+
),
|
| 46 |
+
),
|
| 47 |
+
(
|
| 48 |
+
ttLib.getTableClass("vhea"),
|
| 49 |
+
(
|
| 50 |
+
"ascent",
|
| 51 |
+
"descent",
|
| 52 |
+
"lineGap",
|
| 53 |
+
"advanceHeightMax",
|
| 54 |
+
"minTopSideBearing",
|
| 55 |
+
"minBottomSideBearing",
|
| 56 |
+
"yMaxExtent",
|
| 57 |
+
"caretOffset",
|
| 58 |
+
),
|
| 59 |
+
),
|
| 60 |
+
(
|
| 61 |
+
ttLib.getTableClass("OS/2"),
|
| 62 |
+
(
|
| 63 |
+
"xAvgCharWidth",
|
| 64 |
+
"ySubscriptXSize",
|
| 65 |
+
"ySubscriptYSize",
|
| 66 |
+
"ySubscriptXOffset",
|
| 67 |
+
"ySubscriptYOffset",
|
| 68 |
+
"ySuperscriptXSize",
|
| 69 |
+
"ySuperscriptYSize",
|
| 70 |
+
"ySuperscriptXOffset",
|
| 71 |
+
"ySuperscriptYOffset",
|
| 72 |
+
"yStrikeoutSize",
|
| 73 |
+
"yStrikeoutPosition",
|
| 74 |
+
"sTypoAscender",
|
| 75 |
+
"sTypoDescender",
|
| 76 |
+
"sTypoLineGap",
|
| 77 |
+
"usWinAscent",
|
| 78 |
+
"usWinDescent",
|
| 79 |
+
"sxHeight",
|
| 80 |
+
"sCapHeight",
|
| 81 |
+
),
|
| 82 |
+
),
|
| 83 |
+
(
|
| 84 |
+
otTables.ValueRecord,
|
| 85 |
+
("XAdvance", "YAdvance", "XPlacement", "YPlacement"),
|
| 86 |
+
), # GPOS
|
| 87 |
+
(otTables.Anchor, ("XCoordinate", "YCoordinate")), # GPOS
|
| 88 |
+
(otTables.CaretValue, ("Coordinate")), # GDEF
|
| 89 |
+
(otTables.BaseCoord, ("Coordinate")), # BASE
|
| 90 |
+
(otTables.MathValueRecord, ("Value")), # MATH
|
| 91 |
+
(otTables.ClipBox, ("xMin", "yMin", "xMax", "yMax")), # COLR
|
| 92 |
+
)
|
| 93 |
+
)
|
| 94 |
+
def visit(visitor, obj, attr, value):
|
| 95 |
+
setattr(obj, attr, visitor.scale(value))
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@ScalerVisitor.register_attr(
|
| 99 |
+
(ttLib.getTableClass("hmtx"), ttLib.getTableClass("vmtx")), "metrics"
|
| 100 |
+
)
|
| 101 |
+
def visit(visitor, obj, attr, metrics):
|
| 102 |
+
for g in metrics:
|
| 103 |
+
advance, lsb = metrics[g]
|
| 104 |
+
metrics[g] = visitor.scale(advance), visitor.scale(lsb)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@ScalerVisitor.register_attr(ttLib.getTableClass("VMTX"), "VOriginRecords")
|
| 108 |
+
def visit(visitor, obj, attr, VOriginRecords):
|
| 109 |
+
for g in VOriginRecords:
|
| 110 |
+
VOriginRecords[g] = visitor.scale(VOriginRecords[g])
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@ScalerVisitor.register_attr(ttLib.getTableClass("glyf"), "glyphs")
|
| 114 |
+
def visit(visitor, obj, attr, glyphs):
|
| 115 |
+
for g in glyphs.values():
|
| 116 |
+
for attr in ("xMin", "xMax", "yMin", "yMax"):
|
| 117 |
+
v = getattr(g, attr, None)
|
| 118 |
+
if v is not None:
|
| 119 |
+
setattr(g, attr, visitor.scale(v))
|
| 120 |
+
|
| 121 |
+
if g.isComposite():
|
| 122 |
+
for component in g.components:
|
| 123 |
+
component.x = visitor.scale(component.x)
|
| 124 |
+
component.y = visitor.scale(component.y)
|
| 125 |
+
continue
|
| 126 |
+
|
| 127 |
+
if hasattr(g, "coordinates"):
|
| 128 |
+
coordinates = g.coordinates
|
| 129 |
+
for i, (x, y) in enumerate(coordinates):
|
| 130 |
+
coordinates[i] = visitor.scale(x), visitor.scale(y)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@ScalerVisitor.register_attr(ttLib.getTableClass("gvar"), "variations")
|
| 134 |
+
def visit(visitor, obj, attr, variations):
|
| 135 |
+
glyfTable = visitor.font["glyf"]
|
| 136 |
+
|
| 137 |
+
for glyphName, varlist in variations.items():
|
| 138 |
+
glyph = glyfTable[glyphName]
|
| 139 |
+
for var in varlist:
|
| 140 |
+
coordinates = var.coordinates
|
| 141 |
+
for i, xy in enumerate(coordinates):
|
| 142 |
+
if xy is None:
|
| 143 |
+
continue
|
| 144 |
+
coordinates[i] = visitor.scale(xy[0]), visitor.scale(xy[1])
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@ScalerVisitor.register_attr(ttLib.getTableClass("VARC"), "table")
|
| 148 |
+
def visit(visitor, obj, attr, varc):
|
| 149 |
+
# VarComposite variations are a pain
|
| 150 |
+
|
| 151 |
+
fvar = visitor.font["fvar"]
|
| 152 |
+
fvarAxes = [a.axisTag for a in fvar.axes]
|
| 153 |
+
|
| 154 |
+
store = varc.MultiVarStore
|
| 155 |
+
storeBuilder = OnlineMultiVarStoreBuilder(fvarAxes)
|
| 156 |
+
|
| 157 |
+
for g in varc.VarCompositeGlyphs.VarCompositeGlyph:
|
| 158 |
+
for component in g.components:
|
| 159 |
+
t = component.transform
|
| 160 |
+
t.translateX = visitor.scale(t.translateX)
|
| 161 |
+
t.translateY = visitor.scale(t.translateY)
|
| 162 |
+
t.tCenterX = visitor.scale(t.tCenterX)
|
| 163 |
+
t.tCenterY = visitor.scale(t.tCenterY)
|
| 164 |
+
|
| 165 |
+
if component.axisValuesVarIndex != otTables.NO_VARIATION_INDEX:
|
| 166 |
+
varIdx = component.axisValuesVarIndex
|
| 167 |
+
# TODO Move this code duplicated below to MultiVarStore.__getitem__,
|
| 168 |
+
# or a getDeltasAndSupports().
|
| 169 |
+
if varIdx != otTables.NO_VARIATION_INDEX:
|
| 170 |
+
major = varIdx >> 16
|
| 171 |
+
minor = varIdx & 0xFFFF
|
| 172 |
+
varData = store.MultiVarData[major]
|
| 173 |
+
vec = varData.Item[minor]
|
| 174 |
+
storeBuilder.setSupports(store.get_supports(major, fvar.axes))
|
| 175 |
+
if vec:
|
| 176 |
+
m = len(vec) // varData.VarRegionCount
|
| 177 |
+
vec = list(batched(vec, m))
|
| 178 |
+
vec = [Vector(v) for v in vec]
|
| 179 |
+
component.axisValuesVarIndex = storeBuilder.storeDeltas(vec)
|
| 180 |
+
else:
|
| 181 |
+
component.axisValuesVarIndex = otTables.NO_VARIATION_INDEX
|
| 182 |
+
|
| 183 |
+
if component.transformVarIndex != otTables.NO_VARIATION_INDEX:
|
| 184 |
+
varIdx = component.transformVarIndex
|
| 185 |
+
if varIdx != otTables.NO_VARIATION_INDEX:
|
| 186 |
+
major = varIdx >> 16
|
| 187 |
+
minor = varIdx & 0xFFFF
|
| 188 |
+
vec = varData.Item[varIdx & 0xFFFF]
|
| 189 |
+
major = varIdx >> 16
|
| 190 |
+
minor = varIdx & 0xFFFF
|
| 191 |
+
varData = store.MultiVarData[major]
|
| 192 |
+
vec = varData.Item[minor]
|
| 193 |
+
storeBuilder.setSupports(store.get_supports(major, fvar.axes))
|
| 194 |
+
if vec:
|
| 195 |
+
m = len(vec) // varData.VarRegionCount
|
| 196 |
+
flags = component.flags
|
| 197 |
+
vec = list(batched(vec, m))
|
| 198 |
+
newVec = []
|
| 199 |
+
for v in vec:
|
| 200 |
+
v = list(v)
|
| 201 |
+
i = 0
|
| 202 |
+
## Scale translate & tCenter
|
| 203 |
+
if flags & otTables.VarComponentFlags.HAVE_TRANSLATE_X:
|
| 204 |
+
v[i] = visitor.scale(v[i])
|
| 205 |
+
i += 1
|
| 206 |
+
if flags & otTables.VarComponentFlags.HAVE_TRANSLATE_Y:
|
| 207 |
+
v[i] = visitor.scale(v[i])
|
| 208 |
+
i += 1
|
| 209 |
+
if flags & otTables.VarComponentFlags.HAVE_ROTATION:
|
| 210 |
+
i += 1
|
| 211 |
+
if flags & otTables.VarComponentFlags.HAVE_SCALE_X:
|
| 212 |
+
i += 1
|
| 213 |
+
if flags & otTables.VarComponentFlags.HAVE_SCALE_Y:
|
| 214 |
+
i += 1
|
| 215 |
+
if flags & otTables.VarComponentFlags.HAVE_SKEW_X:
|
| 216 |
+
i += 1
|
| 217 |
+
if flags & otTables.VarComponentFlags.HAVE_SKEW_Y:
|
| 218 |
+
i += 1
|
| 219 |
+
if flags & otTables.VarComponentFlags.HAVE_TCENTER_X:
|
| 220 |
+
v[i] = visitor.scale(v[i])
|
| 221 |
+
i += 1
|
| 222 |
+
if flags & otTables.VarComponentFlags.HAVE_TCENTER_Y:
|
| 223 |
+
v[i] = visitor.scale(v[i])
|
| 224 |
+
i += 1
|
| 225 |
+
|
| 226 |
+
newVec.append(Vector(v))
|
| 227 |
+
vec = newVec
|
| 228 |
+
|
| 229 |
+
component.transformVarIndex = storeBuilder.storeDeltas(vec)
|
| 230 |
+
else:
|
| 231 |
+
component.transformVarIndex = otTables.NO_VARIATION_INDEX
|
| 232 |
+
|
| 233 |
+
varc.MultiVarStore = storeBuilder.finish()
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@ScalerVisitor.register_attr(ttLib.getTableClass("kern"), "kernTables")
|
| 237 |
+
def visit(visitor, obj, attr, kernTables):
|
| 238 |
+
for table in kernTables:
|
| 239 |
+
kernTable = table.kernTable
|
| 240 |
+
for k in kernTable.keys():
|
| 241 |
+
kernTable[k] = visitor.scale(kernTable[k])
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def _cff_scale(visitor, args):
|
| 245 |
+
for i, arg in enumerate(args):
|
| 246 |
+
if not isinstance(arg, list):
|
| 247 |
+
if not isinstance(arg, bytes):
|
| 248 |
+
args[i] = visitor.scale(arg)
|
| 249 |
+
else:
|
| 250 |
+
num_blends = arg[-1]
|
| 251 |
+
_cff_scale(visitor, arg)
|
| 252 |
+
arg[-1] = num_blends
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
@ScalerVisitor.register_attr(
|
| 256 |
+
(ttLib.getTableClass("CFF "), ttLib.getTableClass("CFF2")), "cff"
|
| 257 |
+
)
|
| 258 |
+
def visit(visitor, obj, attr, cff):
|
| 259 |
+
cff.desubroutinize()
|
| 260 |
+
topDict = cff.topDictIndex[0]
|
| 261 |
+
varStore = getattr(topDict, "VarStore", None)
|
| 262 |
+
getNumRegions = varStore.getNumRegions if varStore is not None else None
|
| 263 |
+
privates = set()
|
| 264 |
+
for fontname in cff.keys():
|
| 265 |
+
font = cff[fontname]
|
| 266 |
+
cs = font.CharStrings
|
| 267 |
+
for g in font.charset:
|
| 268 |
+
c, _ = cs.getItemAndSelector(g)
|
| 269 |
+
privates.add(c.private)
|
| 270 |
+
|
| 271 |
+
commands = cffSpecializer.programToCommands(
|
| 272 |
+
c.program, getNumRegions=getNumRegions
|
| 273 |
+
)
|
| 274 |
+
for op, args in commands:
|
| 275 |
+
if op == "vsindex":
|
| 276 |
+
continue
|
| 277 |
+
_cff_scale(visitor, args)
|
| 278 |
+
c.program[:] = cffSpecializer.commandsToProgram(commands)
|
| 279 |
+
|
| 280 |
+
# Annoying business of scaling numbers that do not matter whatsoever
|
| 281 |
+
|
| 282 |
+
for attr in (
|
| 283 |
+
"UnderlinePosition",
|
| 284 |
+
"UnderlineThickness",
|
| 285 |
+
"FontBBox",
|
| 286 |
+
"StrokeWidth",
|
| 287 |
+
):
|
| 288 |
+
value = getattr(topDict, attr, None)
|
| 289 |
+
if value is None:
|
| 290 |
+
continue
|
| 291 |
+
if isinstance(value, list):
|
| 292 |
+
_cff_scale(visitor, value)
|
| 293 |
+
else:
|
| 294 |
+
setattr(topDict, attr, visitor.scale(value))
|
| 295 |
+
|
| 296 |
+
for i in range(6):
|
| 297 |
+
topDict.FontMatrix[i] /= visitor.scaleFactor
|
| 298 |
+
|
| 299 |
+
for private in privates:
|
| 300 |
+
for attr in (
|
| 301 |
+
"BlueValues",
|
| 302 |
+
"OtherBlues",
|
| 303 |
+
"FamilyBlues",
|
| 304 |
+
"FamilyOtherBlues",
|
| 305 |
+
# "BlueScale",
|
| 306 |
+
# "BlueShift",
|
| 307 |
+
# "BlueFuzz",
|
| 308 |
+
"StdHW",
|
| 309 |
+
"StdVW",
|
| 310 |
+
"StemSnapH",
|
| 311 |
+
"StemSnapV",
|
| 312 |
+
"defaultWidthX",
|
| 313 |
+
"nominalWidthX",
|
| 314 |
+
):
|
| 315 |
+
value = getattr(private, attr, None)
|
| 316 |
+
if value is None:
|
| 317 |
+
continue
|
| 318 |
+
if isinstance(value, list):
|
| 319 |
+
_cff_scale(visitor, value)
|
| 320 |
+
else:
|
| 321 |
+
setattr(private, attr, visitor.scale(value))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
# ItemVariationStore
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
@ScalerVisitor.register(otTables.VarData)
|
| 328 |
+
def visit(visitor, varData):
|
| 329 |
+
for item in varData.Item:
|
| 330 |
+
for i, v in enumerate(item):
|
| 331 |
+
item[i] = visitor.scale(v)
|
| 332 |
+
varData.calculateNumShorts()
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
# COLRv1
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def _setup_scale_paint(paint, scale):
|
| 339 |
+
if -2 <= scale <= 2 - (1 >> 14):
|
| 340 |
+
paint.Format = otTables.PaintFormat.PaintScaleUniform
|
| 341 |
+
paint.scale = scale
|
| 342 |
+
return
|
| 343 |
+
|
| 344 |
+
transform = otTables.Affine2x3()
|
| 345 |
+
transform.populateDefaults()
|
| 346 |
+
transform.xy = transform.yx = transform.dx = transform.dy = 0
|
| 347 |
+
transform.xx = transform.yy = scale
|
| 348 |
+
|
| 349 |
+
paint.Format = otTables.PaintFormat.PaintTransform
|
| 350 |
+
paint.Transform = transform
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
@ScalerVisitor.register(otTables.BaseGlyphPaintRecord)
|
| 354 |
+
def visit(visitor, record):
|
| 355 |
+
oldPaint = record.Paint
|
| 356 |
+
|
| 357 |
+
scale = otTables.Paint()
|
| 358 |
+
_setup_scale_paint(scale, visitor.scaleFactor)
|
| 359 |
+
scale.Paint = oldPaint
|
| 360 |
+
|
| 361 |
+
record.Paint = scale
|
| 362 |
+
|
| 363 |
+
return True
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
@ScalerVisitor.register(otTables.Paint)
|
| 367 |
+
def visit(visitor, paint):
|
| 368 |
+
if paint.Format != otTables.PaintFormat.PaintGlyph:
|
| 369 |
+
return True
|
| 370 |
+
|
| 371 |
+
newPaint = otTables.Paint()
|
| 372 |
+
newPaint.Format = paint.Format
|
| 373 |
+
newPaint.Paint = paint.Paint
|
| 374 |
+
newPaint.Glyph = paint.Glyph
|
| 375 |
+
del paint.Paint
|
| 376 |
+
del paint.Glyph
|
| 377 |
+
|
| 378 |
+
_setup_scale_paint(paint, 1 / visitor.scaleFactor)
|
| 379 |
+
paint.Paint = newPaint
|
| 380 |
+
|
| 381 |
+
visitor.visit(newPaint.Paint)
|
| 382 |
+
|
| 383 |
+
return False
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def scale_upem(font, new_upem):
|
| 387 |
+
"""Change the units-per-EM of font to the new value."""
|
| 388 |
+
upem = font["head"].unitsPerEm
|
| 389 |
+
visitor = ScalerVisitor(new_upem / upem)
|
| 390 |
+
visitor.visit(font)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def main(args=None):
|
| 394 |
+
"""Change the units-per-EM of fonts"""
|
| 395 |
+
|
| 396 |
+
if args is None:
|
| 397 |
+
import sys
|
| 398 |
+
|
| 399 |
+
args = sys.argv[1:]
|
| 400 |
+
|
| 401 |
+
from fontTools.ttLib import TTFont
|
| 402 |
+
from fontTools.misc.cliTools import makeOutputFileName
|
| 403 |
+
import argparse
|
| 404 |
+
|
| 405 |
+
parser = argparse.ArgumentParser(
|
| 406 |
+
"fonttools ttLib.scaleUpem", description="Change the units-per-EM of fonts"
|
| 407 |
+
)
|
| 408 |
+
parser.add_argument("font", metavar="font", help="Font file.")
|
| 409 |
+
parser.add_argument(
|
| 410 |
+
"new_upem", metavar="new-upem", help="New units-per-EM integer value."
|
| 411 |
+
)
|
| 412 |
+
parser.add_argument(
|
| 413 |
+
"--output-file", metavar="path", default=None, help="Output file."
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
options = parser.parse_args(args)
|
| 417 |
+
|
| 418 |
+
font = TTFont(options.font)
|
| 419 |
+
new_upem = int(options.new_upem)
|
| 420 |
+
output_file = (
|
| 421 |
+
options.output_file
|
| 422 |
+
if options.output_file is not None
|
| 423 |
+
else makeOutputFileName(options.font, overWrite=True, suffix="-scaled")
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
scale_upem(font, new_upem)
|
| 427 |
+
|
| 428 |
+
print("Writing %s" % output_file)
|
| 429 |
+
font.save(output_file)
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
if __name__ == "__main__":
|
| 433 |
+
import sys
|
| 434 |
+
|
| 435 |
+
sys.exit(main())
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/sfnt.py
ADDED
|
@@ -0,0 +1,708 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ttLib/sfnt.py -- low-level module to deal with the sfnt file format.
|
| 2 |
+
|
| 3 |
+
Defines two public classes:
|
| 4 |
+
|
| 5 |
+
- SFNTReader
|
| 6 |
+
- SFNTWriter
|
| 7 |
+
|
| 8 |
+
(Normally you don't have to use these classes explicitly; they are
|
| 9 |
+
used automatically by ttLib.TTFont.)
|
| 10 |
+
|
| 11 |
+
The reading and writing of sfnt files is separated in two distinct
|
| 12 |
+
classes, since whenever the number of tables changes or whenever
|
| 13 |
+
a table's length changes you need to rewrite the whole file anyway.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
from collections.abc import KeysView
|
| 19 |
+
from io import BytesIO
|
| 20 |
+
from types import SimpleNamespace
|
| 21 |
+
from fontTools.misc.textTools import Tag
|
| 22 |
+
from fontTools.misc import sstruct
|
| 23 |
+
from fontTools.ttLib import TTLibError, TTLibFileIsCollectionError
|
| 24 |
+
import struct
|
| 25 |
+
from collections import OrderedDict
|
| 26 |
+
import logging
|
| 27 |
+
|
| 28 |
+
log = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class SFNTReader(object):
|
| 32 |
+
def __new__(cls, *args, **kwargs):
|
| 33 |
+
"""Return an instance of the SFNTReader sub-class which is compatible
|
| 34 |
+
with the input file type.
|
| 35 |
+
"""
|
| 36 |
+
if args and cls is SFNTReader:
|
| 37 |
+
infile = args[0]
|
| 38 |
+
infile.seek(0)
|
| 39 |
+
sfntVersion = Tag(infile.read(4))
|
| 40 |
+
infile.seek(0)
|
| 41 |
+
if sfntVersion == "wOF2":
|
| 42 |
+
# return new WOFF2Reader object
|
| 43 |
+
from fontTools.ttLib.woff2 import WOFF2Reader
|
| 44 |
+
|
| 45 |
+
return object.__new__(WOFF2Reader)
|
| 46 |
+
# return default object
|
| 47 |
+
return object.__new__(cls)
|
| 48 |
+
|
| 49 |
+
def __init__(self, file, checkChecksums=0, fontNumber=-1):
|
| 50 |
+
self.file = file
|
| 51 |
+
self.checkChecksums = checkChecksums
|
| 52 |
+
|
| 53 |
+
self.flavor = None
|
| 54 |
+
self.flavorData = None
|
| 55 |
+
self.DirectoryEntry = SFNTDirectoryEntry
|
| 56 |
+
self.file.seek(0)
|
| 57 |
+
self.sfntVersion = self.file.read(4)
|
| 58 |
+
self.file.seek(0)
|
| 59 |
+
if self.sfntVersion == b"ttcf":
|
| 60 |
+
header = readTTCHeader(self.file)
|
| 61 |
+
numFonts = header.numFonts
|
| 62 |
+
if not 0 <= fontNumber < numFonts:
|
| 63 |
+
raise TTLibFileIsCollectionError(
|
| 64 |
+
"specify a font number between 0 and %d (inclusive)"
|
| 65 |
+
% (numFonts - 1)
|
| 66 |
+
)
|
| 67 |
+
self.numFonts = numFonts
|
| 68 |
+
self.file.seek(header.offsetTable[fontNumber])
|
| 69 |
+
data = self.file.read(sfntDirectorySize)
|
| 70 |
+
if len(data) != sfntDirectorySize:
|
| 71 |
+
raise TTLibError("Not a Font Collection (not enough data)")
|
| 72 |
+
sstruct.unpack(sfntDirectoryFormat, data, self)
|
| 73 |
+
elif self.sfntVersion == b"wOFF":
|
| 74 |
+
self.flavor = "woff"
|
| 75 |
+
self.DirectoryEntry = WOFFDirectoryEntry
|
| 76 |
+
data = self.file.read(woffDirectorySize)
|
| 77 |
+
if len(data) != woffDirectorySize:
|
| 78 |
+
raise TTLibError("Not a WOFF font (not enough data)")
|
| 79 |
+
sstruct.unpack(woffDirectoryFormat, data, self)
|
| 80 |
+
else:
|
| 81 |
+
data = self.file.read(sfntDirectorySize)
|
| 82 |
+
if len(data) != sfntDirectorySize:
|
| 83 |
+
raise TTLibError("Not a TrueType or OpenType font (not enough data)")
|
| 84 |
+
sstruct.unpack(sfntDirectoryFormat, data, self)
|
| 85 |
+
self.sfntVersion = Tag(self.sfntVersion)
|
| 86 |
+
|
| 87 |
+
if self.sfntVersion not in ("\x00\x01\x00\x00", "OTTO", "true"):
|
| 88 |
+
raise TTLibError("Not a TrueType or OpenType font (bad sfntVersion)")
|
| 89 |
+
tables: dict[Tag, DirectoryEntry] = {}
|
| 90 |
+
for i in range(self.numTables):
|
| 91 |
+
entry = self.DirectoryEntry()
|
| 92 |
+
entry.fromFile(self.file)
|
| 93 |
+
tag = Tag(entry.tag)
|
| 94 |
+
tables[tag] = entry
|
| 95 |
+
self.tables = OrderedDict(sorted(tables.items(), key=lambda i: i[1].offset))
|
| 96 |
+
|
| 97 |
+
# Load flavor data if any
|
| 98 |
+
if self.flavor == "woff":
|
| 99 |
+
self.flavorData = WOFFFlavorData(self)
|
| 100 |
+
|
| 101 |
+
def has_key(self, tag: str | bytes) -> bool:
|
| 102 |
+
return tag in self.tables
|
| 103 |
+
|
| 104 |
+
__contains__ = has_key
|
| 105 |
+
|
| 106 |
+
def keys(self) -> KeysView[Tag]:
|
| 107 |
+
return self.tables.keys()
|
| 108 |
+
|
| 109 |
+
def __getitem__(self, tag: str | bytes) -> bytes:
|
| 110 |
+
"""Fetch the raw table data."""
|
| 111 |
+
entry = self.tables[Tag(tag)]
|
| 112 |
+
data = entry.loadData(self.file)
|
| 113 |
+
if self.checkChecksums:
|
| 114 |
+
if tag == "head":
|
| 115 |
+
# Beh: we have to special-case the 'head' table.
|
| 116 |
+
checksum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:])
|
| 117 |
+
else:
|
| 118 |
+
checksum = calcChecksum(data)
|
| 119 |
+
if self.checkChecksums > 1:
|
| 120 |
+
# Be obnoxious, and barf when it's wrong
|
| 121 |
+
assert checksum == entry.checkSum, "bad checksum for '%s' table" % tag
|
| 122 |
+
elif checksum != entry.checkSum:
|
| 123 |
+
# Be friendly, and just log a warning.
|
| 124 |
+
log.warning("bad checksum for '%s' table", tag)
|
| 125 |
+
return data
|
| 126 |
+
|
| 127 |
+
def __delitem__(self, tag: str | bytes) -> None:
|
| 128 |
+
del self.tables[Tag(tag)]
|
| 129 |
+
|
| 130 |
+
def close(self) -> None:
|
| 131 |
+
self.file.close()
|
| 132 |
+
|
| 133 |
+
# We define custom __getstate__ and __setstate__ to make SFNTReader pickle-able
|
| 134 |
+
# and deepcopy-able. When a TTFont is loaded as lazy=True, SFNTReader holds a
|
| 135 |
+
# reference to an external file object which is not pickleable. So in __getstate__
|
| 136 |
+
# we store the file name and current position, and in __setstate__ we reopen the
|
| 137 |
+
# same named file after unpickling.
|
| 138 |
+
|
| 139 |
+
def __getstate__(self):
|
| 140 |
+
if isinstance(self.file, BytesIO):
|
| 141 |
+
# BytesIO is already pickleable, return the state unmodified
|
| 142 |
+
return self.__dict__
|
| 143 |
+
|
| 144 |
+
# remove unpickleable file attribute, and only store its name and pos
|
| 145 |
+
state = self.__dict__.copy()
|
| 146 |
+
del state["file"]
|
| 147 |
+
state["_filename"] = self.file.name
|
| 148 |
+
state["_filepos"] = self.file.tell()
|
| 149 |
+
return state
|
| 150 |
+
|
| 151 |
+
def __setstate__(self, state):
|
| 152 |
+
if "file" not in state:
|
| 153 |
+
self.file = open(state.pop("_filename"), "rb")
|
| 154 |
+
self.file.seek(state.pop("_filepos"))
|
| 155 |
+
self.__dict__.update(state)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
# default compression level for WOFF 1.0 tables and metadata
|
| 159 |
+
ZLIB_COMPRESSION_LEVEL = 6
|
| 160 |
+
|
| 161 |
+
# if set to True, use zopfli instead of zlib for compressing WOFF 1.0.
|
| 162 |
+
# The Python bindings are available at https://pypi.python.org/pypi/zopfli
|
| 163 |
+
USE_ZOPFLI = False
|
| 164 |
+
|
| 165 |
+
# mapping between zlib's compression levels and zopfli's 'numiterations'.
|
| 166 |
+
# Use lower values for files over several MB in size or it will be too slow
|
| 167 |
+
ZOPFLI_LEVELS = {
|
| 168 |
+
# 0: 0, # can't do 0 iterations...
|
| 169 |
+
1: 1,
|
| 170 |
+
2: 3,
|
| 171 |
+
3: 5,
|
| 172 |
+
4: 8,
|
| 173 |
+
5: 10,
|
| 174 |
+
6: 15,
|
| 175 |
+
7: 25,
|
| 176 |
+
8: 50,
|
| 177 |
+
9: 100,
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def compress(data, level=ZLIB_COMPRESSION_LEVEL):
|
| 182 |
+
"""Compress 'data' to Zlib format. If 'USE_ZOPFLI' variable is True,
|
| 183 |
+
zopfli is used instead of the zlib module.
|
| 184 |
+
The compression 'level' must be between 0 and 9. 1 gives best speed,
|
| 185 |
+
9 gives best compression (0 gives no compression at all).
|
| 186 |
+
The default value is a compromise between speed and compression (6).
|
| 187 |
+
"""
|
| 188 |
+
if not (0 <= level <= 9):
|
| 189 |
+
raise ValueError("Bad compression level: %s" % level)
|
| 190 |
+
if not USE_ZOPFLI or level == 0:
|
| 191 |
+
from zlib import compress
|
| 192 |
+
|
| 193 |
+
return compress(data, level)
|
| 194 |
+
else:
|
| 195 |
+
from zopfli.zlib import compress
|
| 196 |
+
|
| 197 |
+
return compress(data, numiterations=ZOPFLI_LEVELS[level])
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class SFNTWriter(object):
|
| 201 |
+
def __new__(cls, *args, **kwargs):
|
| 202 |
+
"""Return an instance of the SFNTWriter sub-class which is compatible
|
| 203 |
+
with the specified 'flavor'.
|
| 204 |
+
"""
|
| 205 |
+
flavor = None
|
| 206 |
+
if kwargs and "flavor" in kwargs:
|
| 207 |
+
flavor = kwargs["flavor"]
|
| 208 |
+
elif args and len(args) > 3:
|
| 209 |
+
flavor = args[3]
|
| 210 |
+
if cls is SFNTWriter:
|
| 211 |
+
if flavor == "woff2":
|
| 212 |
+
# return new WOFF2Writer object
|
| 213 |
+
from fontTools.ttLib.woff2 import WOFF2Writer
|
| 214 |
+
|
| 215 |
+
return object.__new__(WOFF2Writer)
|
| 216 |
+
# return default object
|
| 217 |
+
return object.__new__(cls)
|
| 218 |
+
|
| 219 |
+
def __init__(
|
| 220 |
+
self,
|
| 221 |
+
file,
|
| 222 |
+
numTables,
|
| 223 |
+
sfntVersion="\000\001\000\000",
|
| 224 |
+
flavor=None,
|
| 225 |
+
flavorData=None,
|
| 226 |
+
):
|
| 227 |
+
self.file = file
|
| 228 |
+
self.numTables = numTables
|
| 229 |
+
self.sfntVersion = Tag(sfntVersion)
|
| 230 |
+
self.flavor = flavor
|
| 231 |
+
self.flavorData = flavorData
|
| 232 |
+
|
| 233 |
+
if self.flavor == "woff":
|
| 234 |
+
self.directoryFormat = woffDirectoryFormat
|
| 235 |
+
self.directorySize = woffDirectorySize
|
| 236 |
+
self.DirectoryEntry = WOFFDirectoryEntry
|
| 237 |
+
|
| 238 |
+
self.signature = "wOFF"
|
| 239 |
+
|
| 240 |
+
# to calculate WOFF checksum adjustment, we also need the original SFNT offsets
|
| 241 |
+
self.origNextTableOffset = (
|
| 242 |
+
sfntDirectorySize + numTables * sfntDirectoryEntrySize
|
| 243 |
+
)
|
| 244 |
+
else:
|
| 245 |
+
assert not self.flavor, "Unknown flavor '%s'" % self.flavor
|
| 246 |
+
self.directoryFormat = sfntDirectoryFormat
|
| 247 |
+
self.directorySize = sfntDirectorySize
|
| 248 |
+
self.DirectoryEntry = SFNTDirectoryEntry
|
| 249 |
+
|
| 250 |
+
from fontTools.ttLib import getSearchRange
|
| 251 |
+
|
| 252 |
+
self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(
|
| 253 |
+
numTables, 16
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
self.directoryOffset = self.file.tell()
|
| 257 |
+
self.nextTableOffset = (
|
| 258 |
+
self.directoryOffset
|
| 259 |
+
+ self.directorySize
|
| 260 |
+
+ numTables * self.DirectoryEntry.formatSize
|
| 261 |
+
)
|
| 262 |
+
# clear out directory area
|
| 263 |
+
self.file.seek(self.nextTableOffset)
|
| 264 |
+
# make sure we're actually where we want to be. (old cStringIO bug)
|
| 265 |
+
self.file.write(b"\0" * (self.nextTableOffset - self.file.tell()))
|
| 266 |
+
self.tables = OrderedDict()
|
| 267 |
+
|
| 268 |
+
def setEntry(self, tag, entry):
|
| 269 |
+
if tag in self.tables:
|
| 270 |
+
raise TTLibError("cannot rewrite '%s' table" % tag)
|
| 271 |
+
|
| 272 |
+
self.tables[tag] = entry
|
| 273 |
+
|
| 274 |
+
def __setitem__(self, tag, data):
|
| 275 |
+
"""Write raw table data to disk."""
|
| 276 |
+
if tag in self.tables:
|
| 277 |
+
raise TTLibError("cannot rewrite '%s' table" % tag)
|
| 278 |
+
|
| 279 |
+
entry = self.DirectoryEntry()
|
| 280 |
+
entry.tag = tag
|
| 281 |
+
entry.offset = self.nextTableOffset
|
| 282 |
+
if tag == "head":
|
| 283 |
+
entry.checkSum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:])
|
| 284 |
+
self.headTable = data
|
| 285 |
+
entry.uncompressed = True
|
| 286 |
+
else:
|
| 287 |
+
entry.checkSum = calcChecksum(data)
|
| 288 |
+
entry.saveData(self.file, data)
|
| 289 |
+
|
| 290 |
+
if self.flavor == "woff":
|
| 291 |
+
entry.origOffset = self.origNextTableOffset
|
| 292 |
+
self.origNextTableOffset += (entry.origLength + 3) & ~3
|
| 293 |
+
|
| 294 |
+
self.nextTableOffset = self.nextTableOffset + ((entry.length + 3) & ~3)
|
| 295 |
+
# Add NUL bytes to pad the table data to a 4-byte boundary.
|
| 296 |
+
# Don't depend on f.seek() as we need to add the padding even if no
|
| 297 |
+
# subsequent write follows (seek is lazy), ie. after the final table
|
| 298 |
+
# in the font.
|
| 299 |
+
self.file.write(b"\0" * (self.nextTableOffset - self.file.tell()))
|
| 300 |
+
assert self.nextTableOffset == self.file.tell()
|
| 301 |
+
|
| 302 |
+
self.setEntry(tag, entry)
|
| 303 |
+
|
| 304 |
+
def __getitem__(self, tag):
|
| 305 |
+
return self.tables[tag]
|
| 306 |
+
|
| 307 |
+
def close(self):
|
| 308 |
+
"""All tables must have been written to disk. Now write the
|
| 309 |
+
directory.
|
| 310 |
+
"""
|
| 311 |
+
tables = sorted(self.tables.items())
|
| 312 |
+
if len(tables) != self.numTables:
|
| 313 |
+
raise TTLibError(
|
| 314 |
+
"wrong number of tables; expected %d, found %d"
|
| 315 |
+
% (self.numTables, len(tables))
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
if self.flavor == "woff":
|
| 319 |
+
self.signature = b"wOFF"
|
| 320 |
+
self.reserved = 0
|
| 321 |
+
|
| 322 |
+
self.totalSfntSize = 12
|
| 323 |
+
self.totalSfntSize += 16 * len(tables)
|
| 324 |
+
for tag, entry in tables:
|
| 325 |
+
self.totalSfntSize += (entry.origLength + 3) & ~3
|
| 326 |
+
|
| 327 |
+
data = self.flavorData if self.flavorData else WOFFFlavorData()
|
| 328 |
+
if data.majorVersion is not None and data.minorVersion is not None:
|
| 329 |
+
self.majorVersion = data.majorVersion
|
| 330 |
+
self.minorVersion = data.minorVersion
|
| 331 |
+
else:
|
| 332 |
+
if hasattr(self, "headTable"):
|
| 333 |
+
self.majorVersion, self.minorVersion = struct.unpack(
|
| 334 |
+
">HH", self.headTable[4:8]
|
| 335 |
+
)
|
| 336 |
+
else:
|
| 337 |
+
self.majorVersion = self.minorVersion = 0
|
| 338 |
+
if data.metaData:
|
| 339 |
+
self.metaOrigLength = len(data.metaData)
|
| 340 |
+
self.file.seek(0, 2)
|
| 341 |
+
self.metaOffset = self.file.tell()
|
| 342 |
+
compressedMetaData = compress(data.metaData)
|
| 343 |
+
self.metaLength = len(compressedMetaData)
|
| 344 |
+
self.file.write(compressedMetaData)
|
| 345 |
+
else:
|
| 346 |
+
self.metaOffset = self.metaLength = self.metaOrigLength = 0
|
| 347 |
+
if data.privData:
|
| 348 |
+
self.file.seek(0, 2)
|
| 349 |
+
off = self.file.tell()
|
| 350 |
+
paddedOff = (off + 3) & ~3
|
| 351 |
+
self.file.write(b"\0" * (paddedOff - off))
|
| 352 |
+
self.privOffset = self.file.tell()
|
| 353 |
+
self.privLength = len(data.privData)
|
| 354 |
+
self.file.write(data.privData)
|
| 355 |
+
else:
|
| 356 |
+
self.privOffset = self.privLength = 0
|
| 357 |
+
|
| 358 |
+
self.file.seek(0, 2)
|
| 359 |
+
self.length = self.file.tell()
|
| 360 |
+
|
| 361 |
+
else:
|
| 362 |
+
assert not self.flavor, "Unknown flavor '%s'" % self.flavor
|
| 363 |
+
pass
|
| 364 |
+
|
| 365 |
+
directory = sstruct.pack(self.directoryFormat, self)
|
| 366 |
+
|
| 367 |
+
self.file.seek(self.directoryOffset + self.directorySize)
|
| 368 |
+
seenHead = 0
|
| 369 |
+
for tag, entry in tables:
|
| 370 |
+
if tag == "head":
|
| 371 |
+
seenHead = 1
|
| 372 |
+
directory = directory + entry.toString()
|
| 373 |
+
if seenHead:
|
| 374 |
+
self.writeMasterChecksum(directory)
|
| 375 |
+
self.file.seek(self.directoryOffset)
|
| 376 |
+
self.file.write(directory)
|
| 377 |
+
|
| 378 |
+
def _calcMasterChecksum(self, directory):
|
| 379 |
+
# calculate checkSumAdjustment
|
| 380 |
+
checksums = []
|
| 381 |
+
for tag in self.tables.keys():
|
| 382 |
+
checksums.append(self.tables[tag].checkSum)
|
| 383 |
+
|
| 384 |
+
if self.DirectoryEntry != SFNTDirectoryEntry:
|
| 385 |
+
# Create a SFNT directory for checksum calculation purposes
|
| 386 |
+
from fontTools.ttLib import getSearchRange
|
| 387 |
+
|
| 388 |
+
self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(
|
| 389 |
+
self.numTables, 16
|
| 390 |
+
)
|
| 391 |
+
directory = sstruct.pack(sfntDirectoryFormat, self)
|
| 392 |
+
tables = sorted(self.tables.items())
|
| 393 |
+
for tag, entry in tables:
|
| 394 |
+
sfntEntry = SFNTDirectoryEntry()
|
| 395 |
+
sfntEntry.tag = entry.tag
|
| 396 |
+
sfntEntry.checkSum = entry.checkSum
|
| 397 |
+
sfntEntry.offset = entry.origOffset
|
| 398 |
+
sfntEntry.length = entry.origLength
|
| 399 |
+
directory = directory + sfntEntry.toString()
|
| 400 |
+
|
| 401 |
+
directory_end = sfntDirectorySize + len(self.tables) * sfntDirectoryEntrySize
|
| 402 |
+
assert directory_end == len(directory)
|
| 403 |
+
|
| 404 |
+
checksums.append(calcChecksum(directory))
|
| 405 |
+
checksum = sum(checksums) & 0xFFFFFFFF
|
| 406 |
+
# BiboAfba!
|
| 407 |
+
checksumadjustment = (0xB1B0AFBA - checksum) & 0xFFFFFFFF
|
| 408 |
+
return checksumadjustment
|
| 409 |
+
|
| 410 |
+
def writeMasterChecksum(self, directory):
|
| 411 |
+
checksumadjustment = self._calcMasterChecksum(directory)
|
| 412 |
+
# write the checksum to the file
|
| 413 |
+
self.file.seek(self.tables["head"].offset + 8)
|
| 414 |
+
self.file.write(struct.pack(">L", checksumadjustment))
|
| 415 |
+
|
| 416 |
+
def reordersTables(self):
|
| 417 |
+
return False
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
# -- sfnt directory helpers and cruft
|
| 421 |
+
|
| 422 |
+
ttcHeaderFormat = """
|
| 423 |
+
> # big endian
|
| 424 |
+
TTCTag: 4s # "ttcf"
|
| 425 |
+
Version: L # 0x00010000 or 0x00020000
|
| 426 |
+
numFonts: L # number of fonts
|
| 427 |
+
# OffsetTable[numFonts]: L # array with offsets from beginning of file
|
| 428 |
+
# ulDsigTag: L # version 2.0 only
|
| 429 |
+
# ulDsigLength: L # version 2.0 only
|
| 430 |
+
# ulDsigOffset: L # version 2.0 only
|
| 431 |
+
"""
|
| 432 |
+
|
| 433 |
+
ttcHeaderSize = sstruct.calcsize(ttcHeaderFormat)
|
| 434 |
+
|
| 435 |
+
ttcTailFormatV2 = """
|
| 436 |
+
> # big endian
|
| 437 |
+
ulDsigTag: L # version 2.0 only
|
| 438 |
+
ulDsigLength: L # version 2.0 only
|
| 439 |
+
ulDsigOffset: L # version 2.0 only
|
| 440 |
+
"""
|
| 441 |
+
|
| 442 |
+
ttcTailSizeV2 = sstruct.calcsize(ttcTailFormatV2)
|
| 443 |
+
|
| 444 |
+
TTC_V1 = 0x00010000
|
| 445 |
+
TTC_V2 = 0x00020000
|
| 446 |
+
|
| 447 |
+
sfntDirectoryFormat = """
|
| 448 |
+
> # big endian
|
| 449 |
+
sfntVersion: 4s
|
| 450 |
+
numTables: H # number of tables
|
| 451 |
+
searchRange: H # (max2 <= numTables)*16
|
| 452 |
+
entrySelector: H # log2(max2 <= numTables)
|
| 453 |
+
rangeShift: H # numTables*16-searchRange
|
| 454 |
+
"""
|
| 455 |
+
|
| 456 |
+
sfntDirectorySize = sstruct.calcsize(sfntDirectoryFormat)
|
| 457 |
+
|
| 458 |
+
sfntDirectoryEntryFormat = """
|
| 459 |
+
> # big endian
|
| 460 |
+
tag: 4s
|
| 461 |
+
checkSum: L
|
| 462 |
+
offset: L
|
| 463 |
+
length: L
|
| 464 |
+
"""
|
| 465 |
+
|
| 466 |
+
sfntDirectoryEntrySize = sstruct.calcsize(sfntDirectoryEntryFormat)
|
| 467 |
+
|
| 468 |
+
woffDirectoryFormat = """
|
| 469 |
+
> # big endian
|
| 470 |
+
signature: 4s # "wOFF"
|
| 471 |
+
sfntVersion: 4s
|
| 472 |
+
length: L # total woff file size
|
| 473 |
+
numTables: H # number of tables
|
| 474 |
+
reserved: H # set to 0
|
| 475 |
+
totalSfntSize: L # uncompressed size
|
| 476 |
+
majorVersion: H # major version of WOFF file
|
| 477 |
+
minorVersion: H # minor version of WOFF file
|
| 478 |
+
metaOffset: L # offset to metadata block
|
| 479 |
+
metaLength: L # length of compressed metadata
|
| 480 |
+
metaOrigLength: L # length of uncompressed metadata
|
| 481 |
+
privOffset: L # offset to private data block
|
| 482 |
+
privLength: L # length of private data block
|
| 483 |
+
"""
|
| 484 |
+
|
| 485 |
+
woffDirectorySize = sstruct.calcsize(woffDirectoryFormat)
|
| 486 |
+
|
| 487 |
+
woffDirectoryEntryFormat = """
|
| 488 |
+
> # big endian
|
| 489 |
+
tag: 4s
|
| 490 |
+
offset: L
|
| 491 |
+
length: L # compressed length
|
| 492 |
+
origLength: L # original length
|
| 493 |
+
checkSum: L # original checksum
|
| 494 |
+
"""
|
| 495 |
+
|
| 496 |
+
woffDirectoryEntrySize = sstruct.calcsize(woffDirectoryEntryFormat)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
class DirectoryEntry(object):
|
| 500 |
+
def __init__(self):
|
| 501 |
+
self.uncompressed = False # if True, always embed entry raw
|
| 502 |
+
|
| 503 |
+
def fromFile(self, file):
|
| 504 |
+
data = file.read(self.formatSize)
|
| 505 |
+
if len(data) != self.formatSize:
|
| 506 |
+
# A file truncated inside the table directory, or one whose
|
| 507 |
+
# numTables is corrupt, would otherwise fail with a struct.error.
|
| 508 |
+
raise TTLibError(
|
| 509 |
+
"unexpected end of table directory: expected %d bytes but got %d"
|
| 510 |
+
% (self.formatSize, len(data))
|
| 511 |
+
)
|
| 512 |
+
sstruct.unpack(self.format, data, self)
|
| 513 |
+
|
| 514 |
+
def fromString(self, str):
|
| 515 |
+
sstruct.unpack(self.format, str, self)
|
| 516 |
+
|
| 517 |
+
def toString(self):
|
| 518 |
+
return sstruct.pack(self.format, self)
|
| 519 |
+
|
| 520 |
+
def __repr__(self):
|
| 521 |
+
if hasattr(self, "tag"):
|
| 522 |
+
return "<%s '%s' at %x>" % (self.__class__.__name__, self.tag, id(self))
|
| 523 |
+
else:
|
| 524 |
+
return "<%s at %x>" % (self.__class__.__name__, id(self))
|
| 525 |
+
|
| 526 |
+
def loadData(self, file):
|
| 527 |
+
file.seek(self.offset)
|
| 528 |
+
data = file.read(self.length)
|
| 529 |
+
if len(data) != self.length:
|
| 530 |
+
# A corrupt or truncated table directory entry can point past the
|
| 531 |
+
# end of the file; raise a TTLibError instead of a bare assertion
|
| 532 |
+
# (which is also silently skipped under `python -O`).
|
| 533 |
+
tag = getattr(self, "tag", None)
|
| 534 |
+
raise TTLibError(
|
| 535 |
+
"unexpected end of '%s' table data: expected %d bytes but got "
|
| 536 |
+
"%d at offset %d"
|
| 537 |
+
% (
|
| 538 |
+
Tag(tag) if tag is not None else "????",
|
| 539 |
+
self.length,
|
| 540 |
+
len(data),
|
| 541 |
+
self.offset,
|
| 542 |
+
)
|
| 543 |
+
)
|
| 544 |
+
if hasattr(self.__class__, "decodeData"):
|
| 545 |
+
data = self.decodeData(data)
|
| 546 |
+
return data
|
| 547 |
+
|
| 548 |
+
def saveData(self, file, data):
|
| 549 |
+
if hasattr(self.__class__, "encodeData"):
|
| 550 |
+
data = self.encodeData(data)
|
| 551 |
+
self.length = len(data)
|
| 552 |
+
file.seek(self.offset)
|
| 553 |
+
file.write(data)
|
| 554 |
+
|
| 555 |
+
def decodeData(self, rawData):
|
| 556 |
+
return rawData
|
| 557 |
+
|
| 558 |
+
def encodeData(self, data):
|
| 559 |
+
return data
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
class SFNTDirectoryEntry(DirectoryEntry):
|
| 563 |
+
format = sfntDirectoryEntryFormat
|
| 564 |
+
formatSize = sfntDirectoryEntrySize
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
class WOFFDirectoryEntry(DirectoryEntry):
|
| 568 |
+
format = woffDirectoryEntryFormat
|
| 569 |
+
formatSize = woffDirectoryEntrySize
|
| 570 |
+
|
| 571 |
+
def __init__(self):
|
| 572 |
+
super(WOFFDirectoryEntry, self).__init__()
|
| 573 |
+
# With fonttools<=3.1.2, the only way to set a different zlib
|
| 574 |
+
# compression level for WOFF directory entries was to set the class
|
| 575 |
+
# attribute 'zlibCompressionLevel'. This is now replaced by a globally
|
| 576 |
+
# defined `ZLIB_COMPRESSION_LEVEL`, which is also applied when
|
| 577 |
+
# compressing the metadata. For backward compatibility, we still
|
| 578 |
+
# use the class attribute if it was already set.
|
| 579 |
+
if not hasattr(WOFFDirectoryEntry, "zlibCompressionLevel"):
|
| 580 |
+
self.zlibCompressionLevel = ZLIB_COMPRESSION_LEVEL
|
| 581 |
+
|
| 582 |
+
def decodeData(self, rawData):
|
| 583 |
+
import zlib
|
| 584 |
+
|
| 585 |
+
if self.length == self.origLength:
|
| 586 |
+
data = rawData
|
| 587 |
+
else:
|
| 588 |
+
assert self.length < self.origLength
|
| 589 |
+
data = zlib.decompress(rawData)
|
| 590 |
+
assert len(data) == self.origLength
|
| 591 |
+
return data
|
| 592 |
+
|
| 593 |
+
def encodeData(self, data):
|
| 594 |
+
self.origLength = len(data)
|
| 595 |
+
if not self.uncompressed:
|
| 596 |
+
compressedData = compress(data, self.zlibCompressionLevel)
|
| 597 |
+
if self.uncompressed or len(compressedData) >= self.origLength:
|
| 598 |
+
# Encode uncompressed
|
| 599 |
+
rawData = data
|
| 600 |
+
self.length = self.origLength
|
| 601 |
+
else:
|
| 602 |
+
rawData = compressedData
|
| 603 |
+
self.length = len(rawData)
|
| 604 |
+
return rawData
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
class WOFFFlavorData:
|
| 608 |
+
Flavor = "woff"
|
| 609 |
+
|
| 610 |
+
def __init__(self, reader=None):
|
| 611 |
+
self.majorVersion = None
|
| 612 |
+
self.minorVersion = None
|
| 613 |
+
self.metaData = None
|
| 614 |
+
self.privData = None
|
| 615 |
+
if reader:
|
| 616 |
+
self.majorVersion = reader.majorVersion
|
| 617 |
+
self.minorVersion = reader.minorVersion
|
| 618 |
+
if reader.metaLength:
|
| 619 |
+
reader.file.seek(reader.metaOffset)
|
| 620 |
+
rawData = reader.file.read(reader.metaLength)
|
| 621 |
+
assert len(rawData) == reader.metaLength
|
| 622 |
+
data = self._decompress(rawData)
|
| 623 |
+
assert len(data) == reader.metaOrigLength
|
| 624 |
+
self.metaData = data
|
| 625 |
+
if reader.privLength:
|
| 626 |
+
reader.file.seek(reader.privOffset)
|
| 627 |
+
data = reader.file.read(reader.privLength)
|
| 628 |
+
assert len(data) == reader.privLength
|
| 629 |
+
self.privData = data
|
| 630 |
+
|
| 631 |
+
def _decompress(self, rawData):
|
| 632 |
+
import zlib
|
| 633 |
+
|
| 634 |
+
return zlib.decompress(rawData)
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def calcChecksum(data):
|
| 638 |
+
"""Calculate the checksum for an arbitrary block of data.
|
| 639 |
+
|
| 640 |
+
If the data length is not a multiple of four, it assumes
|
| 641 |
+
it is to be padded with null byte.
|
| 642 |
+
|
| 643 |
+
>>> print(calcChecksum(b"abcd"))
|
| 644 |
+
1633837924
|
| 645 |
+
>>> print(calcChecksum(b"abcdxyz"))
|
| 646 |
+
3655064932
|
| 647 |
+
"""
|
| 648 |
+
remainder = len(data) % 4
|
| 649 |
+
if remainder:
|
| 650 |
+
data += b"\0" * (4 - remainder)
|
| 651 |
+
value = 0
|
| 652 |
+
blockSize = 4096
|
| 653 |
+
assert blockSize % 4 == 0
|
| 654 |
+
for i in range(0, len(data), blockSize):
|
| 655 |
+
block = data[i : i + blockSize]
|
| 656 |
+
longs = struct.unpack(">%dL" % (len(block) // 4), block)
|
| 657 |
+
value = (value + sum(longs)) & 0xFFFFFFFF
|
| 658 |
+
return value
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def readTTCHeader(file):
|
| 662 |
+
file.seek(0)
|
| 663 |
+
data = file.read(ttcHeaderSize)
|
| 664 |
+
if len(data) != ttcHeaderSize:
|
| 665 |
+
raise TTLibError("Not a Font Collection (not enough data)")
|
| 666 |
+
self = SimpleNamespace()
|
| 667 |
+
sstruct.unpack(ttcHeaderFormat, data, self)
|
| 668 |
+
if self.TTCTag != "ttcf":
|
| 669 |
+
raise TTLibError("Not a Font Collection")
|
| 670 |
+
assert self.Version in (TTC_V1, TTC_V2), (
|
| 671 |
+
"unrecognized TTC version 0x%08x" % self.Version
|
| 672 |
+
)
|
| 673 |
+
self.offsetTable = struct.unpack(
|
| 674 |
+
">%dL" % self.numFonts, file.read(self.numFonts * 4)
|
| 675 |
+
)
|
| 676 |
+
if self.Version == TTC_V2:
|
| 677 |
+
# Unpack additional DSIG fields
|
| 678 |
+
data = file.read(ttcTailSizeV2)
|
| 679 |
+
if len(data) != ttcTailSizeV2:
|
| 680 |
+
raise TTLibError("Not a Font Collection (not enough data)")
|
| 681 |
+
sstruct.unpack(ttcTailFormatV2, data, self)
|
| 682 |
+
return self
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
def writeTTCHeader(file, numFonts, version=TTC_V1):
|
| 686 |
+
self = SimpleNamespace()
|
| 687 |
+
self.TTCTag = "ttcf"
|
| 688 |
+
self.Version = version
|
| 689 |
+
assert self.Version in (TTC_V1, TTC_V2), (
|
| 690 |
+
"unrecognized TTC version 0x%08x" % self.Version
|
| 691 |
+
)
|
| 692 |
+
self.numFonts = numFonts
|
| 693 |
+
file.seek(0)
|
| 694 |
+
file.write(sstruct.pack(ttcHeaderFormat, self))
|
| 695 |
+
offset = file.tell()
|
| 696 |
+
file.write(struct.pack(">%dL" % self.numFonts, *([0] * self.numFonts)))
|
| 697 |
+
if version == TTC_V2:
|
| 698 |
+
# write empty ulDsigTag, ulDsigLength, ulDsigOffset
|
| 699 |
+
# Actual values are be written in TTCollection.save()
|
| 700 |
+
file.write(struct.pack(">3L", 0, 0, 0))
|
| 701 |
+
return offset
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
if __name__ == "__main__":
|
| 705 |
+
import sys
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# 'post' table formats 1.0 and 2.0 rely on this list of "standard"
|
| 3 |
+
# glyphs.
|
| 4 |
+
#
|
| 5 |
+
# My list is correct according to the Apple documentation for the 'post' table:
|
| 6 |
+
# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
|
| 7 |
+
# (However, it seems that TTFdump (from MS) and FontLab disagree, at
|
| 8 |
+
# least with respect to the last glyph, which they list as 'dslash'
|
| 9 |
+
# instead of 'dcroat'.)
|
| 10 |
+
#
|
| 11 |
+
|
| 12 |
+
standardGlyphOrder = [
|
| 13 |
+
".notdef", # 0
|
| 14 |
+
".null", # 1
|
| 15 |
+
"nonmarkingreturn", # 2
|
| 16 |
+
"space", # 3
|
| 17 |
+
"exclam", # 4
|
| 18 |
+
"quotedbl", # 5
|
| 19 |
+
"numbersign", # 6
|
| 20 |
+
"dollar", # 7
|
| 21 |
+
"percent", # 8
|
| 22 |
+
"ampersand", # 9
|
| 23 |
+
"quotesingle", # 10
|
| 24 |
+
"parenleft", # 11
|
| 25 |
+
"parenright", # 12
|
| 26 |
+
"asterisk", # 13
|
| 27 |
+
"plus", # 14
|
| 28 |
+
"comma", # 15
|
| 29 |
+
"hyphen", # 16
|
| 30 |
+
"period", # 17
|
| 31 |
+
"slash", # 18
|
| 32 |
+
"zero", # 19
|
| 33 |
+
"one", # 20
|
| 34 |
+
"two", # 21
|
| 35 |
+
"three", # 22
|
| 36 |
+
"four", # 23
|
| 37 |
+
"five", # 24
|
| 38 |
+
"six", # 25
|
| 39 |
+
"seven", # 26
|
| 40 |
+
"eight", # 27
|
| 41 |
+
"nine", # 28
|
| 42 |
+
"colon", # 29
|
| 43 |
+
"semicolon", # 30
|
| 44 |
+
"less", # 31
|
| 45 |
+
"equal", # 32
|
| 46 |
+
"greater", # 33
|
| 47 |
+
"question", # 34
|
| 48 |
+
"at", # 35
|
| 49 |
+
"A", # 36
|
| 50 |
+
"B", # 37
|
| 51 |
+
"C", # 38
|
| 52 |
+
"D", # 39
|
| 53 |
+
"E", # 40
|
| 54 |
+
"F", # 41
|
| 55 |
+
"G", # 42
|
| 56 |
+
"H", # 43
|
| 57 |
+
"I", # 44
|
| 58 |
+
"J", # 45
|
| 59 |
+
"K", # 46
|
| 60 |
+
"L", # 47
|
| 61 |
+
"M", # 48
|
| 62 |
+
"N", # 49
|
| 63 |
+
"O", # 50
|
| 64 |
+
"P", # 51
|
| 65 |
+
"Q", # 52
|
| 66 |
+
"R", # 53
|
| 67 |
+
"S", # 54
|
| 68 |
+
"T", # 55
|
| 69 |
+
"U", # 56
|
| 70 |
+
"V", # 57
|
| 71 |
+
"W", # 58
|
| 72 |
+
"X", # 59
|
| 73 |
+
"Y", # 60
|
| 74 |
+
"Z", # 61
|
| 75 |
+
"bracketleft", # 62
|
| 76 |
+
"backslash", # 63
|
| 77 |
+
"bracketright", # 64
|
| 78 |
+
"asciicircum", # 65
|
| 79 |
+
"underscore", # 66
|
| 80 |
+
"grave", # 67
|
| 81 |
+
"a", # 68
|
| 82 |
+
"b", # 69
|
| 83 |
+
"c", # 70
|
| 84 |
+
"d", # 71
|
| 85 |
+
"e", # 72
|
| 86 |
+
"f", # 73
|
| 87 |
+
"g", # 74
|
| 88 |
+
"h", # 75
|
| 89 |
+
"i", # 76
|
| 90 |
+
"j", # 77
|
| 91 |
+
"k", # 78
|
| 92 |
+
"l", # 79
|
| 93 |
+
"m", # 80
|
| 94 |
+
"n", # 81
|
| 95 |
+
"o", # 82
|
| 96 |
+
"p", # 83
|
| 97 |
+
"q", # 84
|
| 98 |
+
"r", # 85
|
| 99 |
+
"s", # 86
|
| 100 |
+
"t", # 87
|
| 101 |
+
"u", # 88
|
| 102 |
+
"v", # 89
|
| 103 |
+
"w", # 90
|
| 104 |
+
"x", # 91
|
| 105 |
+
"y", # 92
|
| 106 |
+
"z", # 93
|
| 107 |
+
"braceleft", # 94
|
| 108 |
+
"bar", # 95
|
| 109 |
+
"braceright", # 96
|
| 110 |
+
"asciitilde", # 97
|
| 111 |
+
"Adieresis", # 98
|
| 112 |
+
"Aring", # 99
|
| 113 |
+
"Ccedilla", # 100
|
| 114 |
+
"Eacute", # 101
|
| 115 |
+
"Ntilde", # 102
|
| 116 |
+
"Odieresis", # 103
|
| 117 |
+
"Udieresis", # 104
|
| 118 |
+
"aacute", # 105
|
| 119 |
+
"agrave", # 106
|
| 120 |
+
"acircumflex", # 107
|
| 121 |
+
"adieresis", # 108
|
| 122 |
+
"atilde", # 109
|
| 123 |
+
"aring", # 110
|
| 124 |
+
"ccedilla", # 111
|
| 125 |
+
"eacute", # 112
|
| 126 |
+
"egrave", # 113
|
| 127 |
+
"ecircumflex", # 114
|
| 128 |
+
"edieresis", # 115
|
| 129 |
+
"iacute", # 116
|
| 130 |
+
"igrave", # 117
|
| 131 |
+
"icircumflex", # 118
|
| 132 |
+
"idieresis", # 119
|
| 133 |
+
"ntilde", # 120
|
| 134 |
+
"oacute", # 121
|
| 135 |
+
"ograve", # 122
|
| 136 |
+
"ocircumflex", # 123
|
| 137 |
+
"odieresis", # 124
|
| 138 |
+
"otilde", # 125
|
| 139 |
+
"uacute", # 126
|
| 140 |
+
"ugrave", # 127
|
| 141 |
+
"ucircumflex", # 128
|
| 142 |
+
"udieresis", # 129
|
| 143 |
+
"dagger", # 130
|
| 144 |
+
"degree", # 131
|
| 145 |
+
"cent", # 132
|
| 146 |
+
"sterling", # 133
|
| 147 |
+
"section", # 134
|
| 148 |
+
"bullet", # 135
|
| 149 |
+
"paragraph", # 136
|
| 150 |
+
"germandbls", # 137
|
| 151 |
+
"registered", # 138
|
| 152 |
+
"copyright", # 139
|
| 153 |
+
"trademark", # 140
|
| 154 |
+
"acute", # 141
|
| 155 |
+
"dieresis", # 142
|
| 156 |
+
"notequal", # 143
|
| 157 |
+
"AE", # 144
|
| 158 |
+
"Oslash", # 145
|
| 159 |
+
"infinity", # 146
|
| 160 |
+
"plusminus", # 147
|
| 161 |
+
"lessequal", # 148
|
| 162 |
+
"greaterequal", # 149
|
| 163 |
+
"yen", # 150
|
| 164 |
+
"mu", # 151
|
| 165 |
+
"partialdiff", # 152
|
| 166 |
+
"summation", # 153
|
| 167 |
+
"product", # 154
|
| 168 |
+
"pi", # 155
|
| 169 |
+
"integral", # 156
|
| 170 |
+
"ordfeminine", # 157
|
| 171 |
+
"ordmasculine", # 158
|
| 172 |
+
"Omega", # 159
|
| 173 |
+
"ae", # 160
|
| 174 |
+
"oslash", # 161
|
| 175 |
+
"questiondown", # 162
|
| 176 |
+
"exclamdown", # 163
|
| 177 |
+
"logicalnot", # 164
|
| 178 |
+
"radical", # 165
|
| 179 |
+
"florin", # 166
|
| 180 |
+
"approxequal", # 167
|
| 181 |
+
"Delta", # 168
|
| 182 |
+
"guillemotleft", # 169
|
| 183 |
+
"guillemotright", # 170
|
| 184 |
+
"ellipsis", # 171
|
| 185 |
+
"nonbreakingspace", # 172
|
| 186 |
+
"Agrave", # 173
|
| 187 |
+
"Atilde", # 174
|
| 188 |
+
"Otilde", # 175
|
| 189 |
+
"OE", # 176
|
| 190 |
+
"oe", # 177
|
| 191 |
+
"endash", # 178
|
| 192 |
+
"emdash", # 179
|
| 193 |
+
"quotedblleft", # 180
|
| 194 |
+
"quotedblright", # 181
|
| 195 |
+
"quoteleft", # 182
|
| 196 |
+
"quoteright", # 183
|
| 197 |
+
"divide", # 184
|
| 198 |
+
"lozenge", # 185
|
| 199 |
+
"ydieresis", # 186
|
| 200 |
+
"Ydieresis", # 187
|
| 201 |
+
"fraction", # 188
|
| 202 |
+
"currency", # 189
|
| 203 |
+
"guilsinglleft", # 190
|
| 204 |
+
"guilsinglright", # 191
|
| 205 |
+
"fi", # 192
|
| 206 |
+
"fl", # 193
|
| 207 |
+
"daggerdbl", # 194
|
| 208 |
+
"periodcentered", # 195
|
| 209 |
+
"quotesinglbase", # 196
|
| 210 |
+
"quotedblbase", # 197
|
| 211 |
+
"perthousand", # 198
|
| 212 |
+
"Acircumflex", # 199
|
| 213 |
+
"Ecircumflex", # 200
|
| 214 |
+
"Aacute", # 201
|
| 215 |
+
"Edieresis", # 202
|
| 216 |
+
"Egrave", # 203
|
| 217 |
+
"Iacute", # 204
|
| 218 |
+
"Icircumflex", # 205
|
| 219 |
+
"Idieresis", # 206
|
| 220 |
+
"Igrave", # 207
|
| 221 |
+
"Oacute", # 208
|
| 222 |
+
"Ocircumflex", # 209
|
| 223 |
+
"apple", # 210
|
| 224 |
+
"Ograve", # 211
|
| 225 |
+
"Uacute", # 212
|
| 226 |
+
"Ucircumflex", # 213
|
| 227 |
+
"Ugrave", # 214
|
| 228 |
+
"dotlessi", # 215
|
| 229 |
+
"circumflex", # 216
|
| 230 |
+
"tilde", # 217
|
| 231 |
+
"macron", # 218
|
| 232 |
+
"breve", # 219
|
| 233 |
+
"dotaccent", # 220
|
| 234 |
+
"ring", # 221
|
| 235 |
+
"cedilla", # 222
|
| 236 |
+
"hungarumlaut", # 223
|
| 237 |
+
"ogonek", # 224
|
| 238 |
+
"caron", # 225
|
| 239 |
+
"Lslash", # 226
|
| 240 |
+
"lslash", # 227
|
| 241 |
+
"Scaron", # 228
|
| 242 |
+
"scaron", # 229
|
| 243 |
+
"Zcaron", # 230
|
| 244 |
+
"zcaron", # 231
|
| 245 |
+
"brokenbar", # 232
|
| 246 |
+
"Eth", # 233
|
| 247 |
+
"eth", # 234
|
| 248 |
+
"Yacute", # 235
|
| 249 |
+
"yacute", # 236
|
| 250 |
+
"Thorn", # 237
|
| 251 |
+
"thorn", # 238
|
| 252 |
+
"minus", # 239
|
| 253 |
+
"multiply", # 240
|
| 254 |
+
"onesuperior", # 241
|
| 255 |
+
"twosuperior", # 242
|
| 256 |
+
"threesuperior", # 243
|
| 257 |
+
"onehalf", # 244
|
| 258 |
+
"onequarter", # 245
|
| 259 |
+
"threequarters", # 246
|
| 260 |
+
"franc", # 247
|
| 261 |
+
"Gbreve", # 248
|
| 262 |
+
"gbreve", # 249
|
| 263 |
+
"Idotaccent", # 250
|
| 264 |
+
"Scedilla", # 251
|
| 265 |
+
"scedilla", # 252
|
| 266 |
+
"Cacute", # 253
|
| 267 |
+
"cacute", # 254
|
| 268 |
+
"Ccaron", # 255
|
| 269 |
+
"ccaron", # 256
|
| 270 |
+
"dcroat", # 257
|
| 271 |
+
]
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/B_A_S_E_.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .otBase import BaseTTXConverter
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class table_B_A_S_E_(BaseTTXConverter):
|
| 5 |
+
"""Baseline table
|
| 6 |
+
|
| 7 |
+
The ``BASE`` table contains information needed to align glyphs in
|
| 8 |
+
different scripts, from different fonts, or at different sizes
|
| 9 |
+
within the same line of text.
|
| 10 |
+
|
| 11 |
+
See also https://learn.microsoft.com/en-us/typography/opentype/spec/base
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
pass
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/BitmapGlyphMetrics.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Since bitmap glyph metrics are shared between EBLC and EBDT
|
| 2 |
+
# this class gets its own python file.
|
| 3 |
+
from fontTools.misc import sstruct
|
| 4 |
+
from fontTools.misc.textTools import safeEval
|
| 5 |
+
import logging
|
| 6 |
+
|
| 7 |
+
log = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
bigGlyphMetricsFormat = """
|
| 10 |
+
> # big endian
|
| 11 |
+
height: B
|
| 12 |
+
width: B
|
| 13 |
+
horiBearingX: b
|
| 14 |
+
horiBearingY: b
|
| 15 |
+
horiAdvance: B
|
| 16 |
+
vertBearingX: b
|
| 17 |
+
vertBearingY: b
|
| 18 |
+
vertAdvance: B
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
smallGlyphMetricsFormat = """
|
| 22 |
+
> # big endian
|
| 23 |
+
height: B
|
| 24 |
+
width: B
|
| 25 |
+
BearingX: b
|
| 26 |
+
BearingY: b
|
| 27 |
+
Advance: B
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class BitmapGlyphMetrics(object):
|
| 32 |
+
def toXML(self, writer, ttFont):
|
| 33 |
+
writer.begintag(self.__class__.__name__)
|
| 34 |
+
writer.newline()
|
| 35 |
+
for metricName in sstruct.getformat(self.__class__.binaryFormat)[1]:
|
| 36 |
+
writer.simpletag(metricName, value=getattr(self, metricName))
|
| 37 |
+
writer.newline()
|
| 38 |
+
writer.endtag(self.__class__.__name__)
|
| 39 |
+
writer.newline()
|
| 40 |
+
|
| 41 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 42 |
+
metricNames = set(sstruct.getformat(self.__class__.binaryFormat)[1])
|
| 43 |
+
for element in content:
|
| 44 |
+
if not isinstance(element, tuple):
|
| 45 |
+
continue
|
| 46 |
+
name, attrs, content = element
|
| 47 |
+
# Make sure this is a metric that is needed by GlyphMetrics.
|
| 48 |
+
if name in metricNames:
|
| 49 |
+
vars(self)[name] = safeEval(attrs["value"])
|
| 50 |
+
else:
|
| 51 |
+
log.warning(
|
| 52 |
+
"unknown name '%s' being ignored in %s.",
|
| 53 |
+
name,
|
| 54 |
+
self.__class__.__name__,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class BigGlyphMetrics(BitmapGlyphMetrics):
|
| 59 |
+
binaryFormat = bigGlyphMetricsFormat
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class SmallGlyphMetrics(BitmapGlyphMetrics):
|
| 63 |
+
binaryFormat = smallGlyphMetricsFormat
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_B_D_T_.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2013 Google, Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Google Author(s): Matt Fontaine
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
from fontTools.misc.textTools import bytesjoin
|
| 7 |
+
from fontTools.misc import sstruct
|
| 8 |
+
from . import E_B_D_T_
|
| 9 |
+
from .BitmapGlyphMetrics import (
|
| 10 |
+
BigGlyphMetrics,
|
| 11 |
+
bigGlyphMetricsFormat,
|
| 12 |
+
SmallGlyphMetrics,
|
| 13 |
+
smallGlyphMetricsFormat,
|
| 14 |
+
)
|
| 15 |
+
from .E_B_D_T_ import (
|
| 16 |
+
BitmapGlyph,
|
| 17 |
+
BitmapPlusSmallMetricsMixin,
|
| 18 |
+
BitmapPlusBigMetricsMixin,
|
| 19 |
+
)
|
| 20 |
+
import struct
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class table_C_B_D_T_(E_B_D_T_.table_E_B_D_T_):
|
| 24 |
+
"""Color Bitmap Data table
|
| 25 |
+
|
| 26 |
+
The ``CBDT`` table contains color bitmap data for glyphs. It must
|
| 27 |
+
be used in concert with the ``CBLC`` table.
|
| 28 |
+
|
| 29 |
+
It is backwards-compatible with the monochrome/grayscale ``EBDT`` table.
|
| 30 |
+
|
| 31 |
+
See also https://learn.microsoft.com/en-us/typography/opentype/spec/cbdt
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
# Change the data locator table being referenced.
|
| 35 |
+
locatorName = "CBLC"
|
| 36 |
+
|
| 37 |
+
# Modify the format class accessor for color bitmap use.
|
| 38 |
+
def getImageFormatClass(self, imageFormat):
|
| 39 |
+
try:
|
| 40 |
+
return E_B_D_T_.table_E_B_D_T_.getImageFormatClass(self, imageFormat)
|
| 41 |
+
except KeyError:
|
| 42 |
+
return cbdt_bitmap_classes[imageFormat]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# Helper method for removing export features not supported by color bitmaps.
|
| 46 |
+
# Write data in the parent class will default to raw if an option is unsupported.
|
| 47 |
+
def _removeUnsupportedForColor(dataFunctions):
|
| 48 |
+
dataFunctions = dict(dataFunctions)
|
| 49 |
+
del dataFunctions["row"]
|
| 50 |
+
return dataFunctions
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class ColorBitmapGlyph(BitmapGlyph):
|
| 54 |
+
fileExtension = ".png"
|
| 55 |
+
xmlDataFunctions = _removeUnsupportedForColor(BitmapGlyph.xmlDataFunctions)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class cbdt_bitmap_format_17(BitmapPlusSmallMetricsMixin, ColorBitmapGlyph):
|
| 59 |
+
def decompile(self):
|
| 60 |
+
self.metrics = SmallGlyphMetrics()
|
| 61 |
+
dummy, data = sstruct.unpack2(smallGlyphMetricsFormat, self.data, self.metrics)
|
| 62 |
+
(dataLen,) = struct.unpack(">L", data[:4])
|
| 63 |
+
data = data[4:]
|
| 64 |
+
|
| 65 |
+
# For the image data cut it to the size specified by dataLen.
|
| 66 |
+
assert dataLen <= len(data), "Data overun in format 17"
|
| 67 |
+
self.imageData = data[:dataLen]
|
| 68 |
+
|
| 69 |
+
def compile(self, ttFont):
|
| 70 |
+
dataList = []
|
| 71 |
+
dataList.append(sstruct.pack(smallGlyphMetricsFormat, self.metrics))
|
| 72 |
+
dataList.append(struct.pack(">L", len(self.imageData)))
|
| 73 |
+
dataList.append(self.imageData)
|
| 74 |
+
return bytesjoin(dataList)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class cbdt_bitmap_format_18(BitmapPlusBigMetricsMixin, ColorBitmapGlyph):
|
| 78 |
+
def decompile(self):
|
| 79 |
+
self.metrics = BigGlyphMetrics()
|
| 80 |
+
dummy, data = sstruct.unpack2(bigGlyphMetricsFormat, self.data, self.metrics)
|
| 81 |
+
(dataLen,) = struct.unpack(">L", data[:4])
|
| 82 |
+
data = data[4:]
|
| 83 |
+
|
| 84 |
+
# For the image data cut it to the size specified by dataLen.
|
| 85 |
+
assert dataLen <= len(data), "Data overun in format 18"
|
| 86 |
+
self.imageData = data[:dataLen]
|
| 87 |
+
|
| 88 |
+
def compile(self, ttFont):
|
| 89 |
+
dataList = []
|
| 90 |
+
dataList.append(sstruct.pack(bigGlyphMetricsFormat, self.metrics))
|
| 91 |
+
dataList.append(struct.pack(">L", len(self.imageData)))
|
| 92 |
+
dataList.append(self.imageData)
|
| 93 |
+
return bytesjoin(dataList)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class cbdt_bitmap_format_19(ColorBitmapGlyph):
|
| 97 |
+
def decompile(self):
|
| 98 |
+
(dataLen,) = struct.unpack(">L", self.data[:4])
|
| 99 |
+
data = self.data[4:]
|
| 100 |
+
|
| 101 |
+
assert dataLen <= len(data), "Data overun in format 19"
|
| 102 |
+
self.imageData = data[:dataLen]
|
| 103 |
+
|
| 104 |
+
def compile(self, ttFont):
|
| 105 |
+
return struct.pack(">L", len(self.imageData)) + self.imageData
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# Dict for CBDT extended formats.
|
| 109 |
+
cbdt_bitmap_classes = {
|
| 110 |
+
17: cbdt_bitmap_format_17,
|
| 111 |
+
18: cbdt_bitmap_format_18,
|
| 112 |
+
19: cbdt_bitmap_format_19,
|
| 113 |
+
}
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_B_L_C_.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2013 Google, Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Google Author(s): Matt Fontaine
|
| 4 |
+
|
| 5 |
+
from . import E_B_L_C_
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class table_C_B_L_C_(E_B_L_C_.table_E_B_L_C_):
|
| 9 |
+
"""Color Bitmap Location table
|
| 10 |
+
|
| 11 |
+
The ``CBLC`` table contains the locations of color bitmaps for glyphs. It must
|
| 12 |
+
be used in concert with the ``CBDT`` table.
|
| 13 |
+
|
| 14 |
+
It is backwards-compatible with the monochrome/grayscale ``EBLC`` table.
|
| 15 |
+
|
| 16 |
+
See also https://learn.microsoft.com/en-us/typography/opentype/spec/cblc
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
dependencies = ["CBDT"]
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_F_F_.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from io import BytesIO
|
| 2 |
+
from fontTools import cffLib
|
| 3 |
+
from . import DefaultTable
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class table_C_F_F_(DefaultTable.DefaultTable):
|
| 7 |
+
"""Compact Font Format table (version 1)
|
| 8 |
+
|
| 9 |
+
The ``CFF`` table embeds a CFF-formatted font. The CFF font format
|
| 10 |
+
predates OpenType and could be used as a standalone font file, but the
|
| 11 |
+
``CFF`` table is also used to package CFF fonts into an OpenType
|
| 12 |
+
container.
|
| 13 |
+
|
| 14 |
+
.. note::
|
| 15 |
+
``CFF`` has been succeeded by ``CFF2``, which eliminates much of
|
| 16 |
+
the redundancy incurred by embedding CFF version 1 in an OpenType
|
| 17 |
+
font.
|
| 18 |
+
|
| 19 |
+
See also https://learn.microsoft.com/en-us/typography/opentype/spec/cff
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self, tag=None):
|
| 23 |
+
DefaultTable.DefaultTable.__init__(self, tag)
|
| 24 |
+
self.cff = cffLib.CFFFontSet()
|
| 25 |
+
self._gaveGlyphOrder = False
|
| 26 |
+
|
| 27 |
+
def decompile(self, data, otFont):
|
| 28 |
+
self.cff.decompile(BytesIO(data), otFont, isCFF2=False)
|
| 29 |
+
assert len(self.cff) == 1, "can't deal with multi-font CFF tables."
|
| 30 |
+
|
| 31 |
+
def compile(self, otFont):
|
| 32 |
+
f = BytesIO()
|
| 33 |
+
self.cff.compile(f, otFont, isCFF2=False)
|
| 34 |
+
return f.getvalue()
|
| 35 |
+
|
| 36 |
+
def haveGlyphNames(self):
|
| 37 |
+
if hasattr(self.cff[self.cff.fontNames[0]], "ROS"):
|
| 38 |
+
return False # CID-keyed font
|
| 39 |
+
else:
|
| 40 |
+
return True
|
| 41 |
+
|
| 42 |
+
def getGlyphOrder(self):
|
| 43 |
+
if self._gaveGlyphOrder:
|
| 44 |
+
from fontTools import ttLib
|
| 45 |
+
|
| 46 |
+
raise ttLib.TTLibError("illegal use of getGlyphOrder()")
|
| 47 |
+
self._gaveGlyphOrder = True
|
| 48 |
+
return self.cff[self.cff.fontNames[0]].getGlyphOrder()
|
| 49 |
+
|
| 50 |
+
def setGlyphOrder(self, glyphOrder):
|
| 51 |
+
pass
|
| 52 |
+
# XXX
|
| 53 |
+
# self.cff[self.cff.fontNames[0]].setGlyphOrder(glyphOrder)
|
| 54 |
+
|
| 55 |
+
def toXML(self, writer, otFont):
|
| 56 |
+
self.cff.toXML(writer)
|
| 57 |
+
|
| 58 |
+
def fromXML(self, name, attrs, content, otFont):
|
| 59 |
+
if not hasattr(self, "cff"):
|
| 60 |
+
self.cff = cffLib.CFFFontSet()
|
| 61 |
+
self.cff.fromXML(name, attrs, content, otFont)
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_F_F__2.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from io import BytesIO
|
| 2 |
+
from fontTools.ttLib.tables.C_F_F_ import table_C_F_F_
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class table_C_F_F__2(table_C_F_F_):
|
| 6 |
+
"""Compact Font Format version 2 table
|
| 7 |
+
|
| 8 |
+
The ``CFF2`` table contains glyph data for a CFF2-flavored OpenType
|
| 9 |
+
font.
|
| 10 |
+
|
| 11 |
+
.. note::
|
| 12 |
+
``CFF2`` is the successor to ``CFF``, and eliminates much of
|
| 13 |
+
the redundancy incurred by embedding CFF version 1 in an OpenType
|
| 14 |
+
font.
|
| 15 |
+
|
| 16 |
+
See also https://learn.microsoft.com/en-us/typography/opentype/spec/cff2
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
def decompile(self, data, otFont):
|
| 20 |
+
self.cff.decompile(BytesIO(data), otFont, isCFF2=True)
|
| 21 |
+
assert len(self.cff) == 1, "can't deal with multi-font CFF tables."
|
| 22 |
+
|
| 23 |
+
def compile(self, otFont):
|
| 24 |
+
f = BytesIO()
|
| 25 |
+
self.cff.compile(f, otFont, isCFF2=True)
|
| 26 |
+
return f.getvalue()
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_O_L_R_.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2013 Google, Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Google Author(s): Behdad Esfahbod
|
| 4 |
+
|
| 5 |
+
from fontTools.misc.textTools import safeEval
|
| 6 |
+
from . import DefaultTable
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class table_C_O_L_R_(DefaultTable.DefaultTable):
|
| 10 |
+
"""Color table
|
| 11 |
+
|
| 12 |
+
The ``COLR`` table defines color presentation of outline glyphs. It must
|
| 13 |
+
be used in concert with the ``CPAL`` table, which contains the color
|
| 14 |
+
descriptors used.
|
| 15 |
+
|
| 16 |
+
This table is structured so that you can treat it like a dictionary keyed by glyph name.
|
| 17 |
+
|
| 18 |
+
``ttFont['COLR'][<glyphName>]`` will return the color layers for any glyph.
|
| 19 |
+
|
| 20 |
+
``ttFont['COLR'][<glyphName>] = <value>`` will set the color layers for any glyph.
|
| 21 |
+
|
| 22 |
+
See also https://learn.microsoft.com/en-us/typography/opentype/spec/colr
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
@staticmethod
|
| 26 |
+
def _decompileColorLayersV0(table):
|
| 27 |
+
if not table.LayerRecordArray:
|
| 28 |
+
return {}
|
| 29 |
+
colorLayerLists = {}
|
| 30 |
+
layerRecords = table.LayerRecordArray.LayerRecord
|
| 31 |
+
numLayerRecords = len(layerRecords)
|
| 32 |
+
for baseRec in table.BaseGlyphRecordArray.BaseGlyphRecord:
|
| 33 |
+
baseGlyph = baseRec.BaseGlyph
|
| 34 |
+
firstLayerIndex = baseRec.FirstLayerIndex
|
| 35 |
+
numLayers = baseRec.NumLayers
|
| 36 |
+
assert firstLayerIndex + numLayers <= numLayerRecords
|
| 37 |
+
layers = []
|
| 38 |
+
for i in range(firstLayerIndex, firstLayerIndex + numLayers):
|
| 39 |
+
layerRec = layerRecords[i]
|
| 40 |
+
layers.append(LayerRecord(layerRec.LayerGlyph, layerRec.PaletteIndex))
|
| 41 |
+
colorLayerLists[baseGlyph] = layers
|
| 42 |
+
return colorLayerLists
|
| 43 |
+
|
| 44 |
+
def _toOTTable(self, ttFont):
|
| 45 |
+
from . import otTables
|
| 46 |
+
from fontTools.colorLib.builder import populateCOLRv0
|
| 47 |
+
|
| 48 |
+
tableClass = getattr(otTables, self.tableTag)
|
| 49 |
+
table = tableClass()
|
| 50 |
+
table.Version = self.version
|
| 51 |
+
|
| 52 |
+
populateCOLRv0(
|
| 53 |
+
table,
|
| 54 |
+
{
|
| 55 |
+
baseGlyph: [(layer.name, layer.colorID) for layer in layers]
|
| 56 |
+
for baseGlyph, layers in self.ColorLayers.items()
|
| 57 |
+
},
|
| 58 |
+
glyphMap=ttFont.getReverseGlyphMap(rebuild=True),
|
| 59 |
+
)
|
| 60 |
+
return table
|
| 61 |
+
|
| 62 |
+
def decompile(self, data, ttFont):
|
| 63 |
+
from .otBase import OTTableReader
|
| 64 |
+
from . import otTables
|
| 65 |
+
|
| 66 |
+
# We use otData to decompile, but we adapt the decompiled otTables to the
|
| 67 |
+
# existing COLR v0 API for backward compatibility.
|
| 68 |
+
reader = OTTableReader(data, tableTag=self.tableTag)
|
| 69 |
+
tableClass = getattr(otTables, self.tableTag)
|
| 70 |
+
table = tableClass()
|
| 71 |
+
table.decompile(reader, ttFont)
|
| 72 |
+
|
| 73 |
+
self.version = table.Version
|
| 74 |
+
if self.version == 0:
|
| 75 |
+
self.ColorLayers = self._decompileColorLayersV0(table)
|
| 76 |
+
else:
|
| 77 |
+
# for new versions, keep the raw otTables around
|
| 78 |
+
self.table = table
|
| 79 |
+
|
| 80 |
+
def compile(self, ttFont):
|
| 81 |
+
from .otBase import OTTableWriter
|
| 82 |
+
|
| 83 |
+
if hasattr(self, "table"):
|
| 84 |
+
table = self.table
|
| 85 |
+
else:
|
| 86 |
+
table = self._toOTTable(ttFont)
|
| 87 |
+
|
| 88 |
+
writer = OTTableWriter(tableTag=self.tableTag)
|
| 89 |
+
table.compile(writer, ttFont)
|
| 90 |
+
return writer.getAllData()
|
| 91 |
+
|
| 92 |
+
def toXML(self, writer, ttFont):
|
| 93 |
+
if hasattr(self, "table"):
|
| 94 |
+
self.table.toXML2(writer, ttFont)
|
| 95 |
+
else:
|
| 96 |
+
writer.simpletag("version", value=self.version)
|
| 97 |
+
writer.newline()
|
| 98 |
+
for baseGlyph in sorted(self.ColorLayers.keys(), key=ttFont.getGlyphID):
|
| 99 |
+
writer.begintag("ColorGlyph", name=baseGlyph)
|
| 100 |
+
writer.newline()
|
| 101 |
+
for layer in self.ColorLayers[baseGlyph]:
|
| 102 |
+
layer.toXML(writer, ttFont)
|
| 103 |
+
writer.endtag("ColorGlyph")
|
| 104 |
+
writer.newline()
|
| 105 |
+
|
| 106 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 107 |
+
if name == "version": # old COLR v0 API
|
| 108 |
+
setattr(self, name, safeEval(attrs["value"]))
|
| 109 |
+
elif name == "ColorGlyph":
|
| 110 |
+
if not hasattr(self, "ColorLayers"):
|
| 111 |
+
self.ColorLayers = {}
|
| 112 |
+
glyphName = attrs["name"]
|
| 113 |
+
for element in content:
|
| 114 |
+
if isinstance(element, str):
|
| 115 |
+
continue
|
| 116 |
+
layers = []
|
| 117 |
+
for element in content:
|
| 118 |
+
if isinstance(element, str):
|
| 119 |
+
continue
|
| 120 |
+
layer = LayerRecord()
|
| 121 |
+
layer.fromXML(element[0], element[1], element[2], ttFont)
|
| 122 |
+
layers.append(layer)
|
| 123 |
+
self.ColorLayers[glyphName] = layers
|
| 124 |
+
else: # new COLR v1 API
|
| 125 |
+
from . import otTables
|
| 126 |
+
|
| 127 |
+
if not hasattr(self, "table"):
|
| 128 |
+
tableClass = getattr(otTables, self.tableTag)
|
| 129 |
+
self.table = tableClass()
|
| 130 |
+
self.table.fromXML(name, attrs, content, ttFont)
|
| 131 |
+
self.table.populateDefaults()
|
| 132 |
+
self.version = self.table.Version
|
| 133 |
+
|
| 134 |
+
def __getitem__(self, glyphName):
|
| 135 |
+
if not isinstance(glyphName, str):
|
| 136 |
+
raise TypeError(f"expected str, found {type(glyphName).__name__}")
|
| 137 |
+
return self.ColorLayers[glyphName]
|
| 138 |
+
|
| 139 |
+
def __setitem__(self, glyphName, value):
|
| 140 |
+
if not isinstance(glyphName, str):
|
| 141 |
+
raise TypeError(f"expected str, found {type(glyphName).__name__}")
|
| 142 |
+
if value is not None:
|
| 143 |
+
self.ColorLayers[glyphName] = value
|
| 144 |
+
elif glyphName in self.ColorLayers:
|
| 145 |
+
del self.ColorLayers[glyphName]
|
| 146 |
+
|
| 147 |
+
def __delitem__(self, glyphName):
|
| 148 |
+
del self.ColorLayers[glyphName]
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class LayerRecord(object):
|
| 152 |
+
def __init__(self, name=None, colorID=None):
|
| 153 |
+
self.name = name
|
| 154 |
+
self.colorID = colorID
|
| 155 |
+
|
| 156 |
+
def toXML(self, writer, ttFont):
|
| 157 |
+
writer.simpletag("layer", name=self.name, colorID=self.colorID)
|
| 158 |
+
writer.newline()
|
| 159 |
+
|
| 160 |
+
def fromXML(self, eltname, attrs, content, ttFont):
|
| 161 |
+
for name, value in attrs.items():
|
| 162 |
+
if name == "name":
|
| 163 |
+
setattr(self, name, value)
|
| 164 |
+
else:
|
| 165 |
+
setattr(self, name, safeEval(value))
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/C_P_A_L_.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2013 Google, Inc. All Rights Reserved.
|
| 2 |
+
#
|
| 3 |
+
# Google Author(s): Behdad Esfahbod
|
| 4 |
+
|
| 5 |
+
from fontTools.misc.textTools import bytesjoin, safeEval
|
| 6 |
+
from . import DefaultTable
|
| 7 |
+
import array
|
| 8 |
+
from collections import namedtuple
|
| 9 |
+
import struct
|
| 10 |
+
import sys
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class table_C_P_A_L_(DefaultTable.DefaultTable):
|
| 14 |
+
"""Color Palette table
|
| 15 |
+
|
| 16 |
+
The ``CPAL`` table contains a set of one or more color palettes. The color
|
| 17 |
+
records in each palette can be referenced by the ``COLR`` table to specify
|
| 18 |
+
the colors used in a color glyph.
|
| 19 |
+
|
| 20 |
+
See also https://learn.microsoft.com/en-us/typography/opentype/spec/cpal
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
NO_NAME_ID = 0xFFFF
|
| 24 |
+
DEFAULT_PALETTE_TYPE = 0
|
| 25 |
+
|
| 26 |
+
def __init__(self, tag=None):
|
| 27 |
+
DefaultTable.DefaultTable.__init__(self, tag)
|
| 28 |
+
self.palettes = []
|
| 29 |
+
self.paletteTypes = []
|
| 30 |
+
self.paletteLabels = []
|
| 31 |
+
self.paletteEntryLabels = []
|
| 32 |
+
|
| 33 |
+
def decompile(self, data, ttFont):
|
| 34 |
+
(
|
| 35 |
+
self.version,
|
| 36 |
+
self.numPaletteEntries,
|
| 37 |
+
numPalettes,
|
| 38 |
+
numColorRecords,
|
| 39 |
+
goffsetFirstColorRecord,
|
| 40 |
+
) = struct.unpack(">HHHHL", data[:12])
|
| 41 |
+
assert (
|
| 42 |
+
self.version <= 1
|
| 43 |
+
), "Version of CPAL table is higher than I know how to handle"
|
| 44 |
+
self.palettes = []
|
| 45 |
+
pos = 12
|
| 46 |
+
for i in range(numPalettes):
|
| 47 |
+
startIndex = struct.unpack(">H", data[pos : pos + 2])[0]
|
| 48 |
+
assert startIndex + self.numPaletteEntries <= numColorRecords
|
| 49 |
+
pos += 2
|
| 50 |
+
palette = []
|
| 51 |
+
ppos = goffsetFirstColorRecord + startIndex * 4
|
| 52 |
+
for j in range(self.numPaletteEntries):
|
| 53 |
+
palette.append(Color(*struct.unpack(">BBBB", data[ppos : ppos + 4])))
|
| 54 |
+
ppos += 4
|
| 55 |
+
self.palettes.append(palette)
|
| 56 |
+
if self.version == 0:
|
| 57 |
+
offsetToPaletteTypeArray = 0
|
| 58 |
+
offsetToPaletteLabelArray = 0
|
| 59 |
+
offsetToPaletteEntryLabelArray = 0
|
| 60 |
+
else:
|
| 61 |
+
pos = 12 + numPalettes * 2
|
| 62 |
+
(
|
| 63 |
+
offsetToPaletteTypeArray,
|
| 64 |
+
offsetToPaletteLabelArray,
|
| 65 |
+
offsetToPaletteEntryLabelArray,
|
| 66 |
+
) = struct.unpack(">LLL", data[pos : pos + 12])
|
| 67 |
+
self.paletteTypes = self._decompileUInt32Array(
|
| 68 |
+
data,
|
| 69 |
+
offsetToPaletteTypeArray,
|
| 70 |
+
numPalettes,
|
| 71 |
+
default=self.DEFAULT_PALETTE_TYPE,
|
| 72 |
+
)
|
| 73 |
+
self.paletteLabels = self._decompileUInt16Array(
|
| 74 |
+
data, offsetToPaletteLabelArray, numPalettes, default=self.NO_NAME_ID
|
| 75 |
+
)
|
| 76 |
+
self.paletteEntryLabels = self._decompileUInt16Array(
|
| 77 |
+
data,
|
| 78 |
+
offsetToPaletteEntryLabelArray,
|
| 79 |
+
self.numPaletteEntries,
|
| 80 |
+
default=self.NO_NAME_ID,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
def _decompileUInt16Array(self, data, offset, numElements, default=0):
|
| 84 |
+
if offset == 0:
|
| 85 |
+
return [default] * numElements
|
| 86 |
+
result = array.array("H", data[offset : offset + 2 * numElements])
|
| 87 |
+
if sys.byteorder != "big":
|
| 88 |
+
result.byteswap()
|
| 89 |
+
assert len(result) == numElements, result
|
| 90 |
+
return result.tolist()
|
| 91 |
+
|
| 92 |
+
def _decompileUInt32Array(self, data, offset, numElements, default=0):
|
| 93 |
+
if offset == 0:
|
| 94 |
+
return [default] * numElements
|
| 95 |
+
result = array.array("I", data[offset : offset + 4 * numElements])
|
| 96 |
+
if sys.byteorder != "big":
|
| 97 |
+
result.byteswap()
|
| 98 |
+
assert len(result) == numElements, result
|
| 99 |
+
return result.tolist()
|
| 100 |
+
|
| 101 |
+
def compile(self, ttFont):
|
| 102 |
+
colorRecordIndices, colorRecords = self._compileColorRecords()
|
| 103 |
+
paletteTypes = self._compilePaletteTypes()
|
| 104 |
+
paletteLabels = self._compilePaletteLabels()
|
| 105 |
+
paletteEntryLabels = self._compilePaletteEntryLabels()
|
| 106 |
+
numColorRecords = len(colorRecords) // 4
|
| 107 |
+
offsetToFirstColorRecord = 12 + len(colorRecordIndices)
|
| 108 |
+
if self.version >= 1:
|
| 109 |
+
offsetToFirstColorRecord += 12
|
| 110 |
+
header = struct.pack(
|
| 111 |
+
">HHHHL",
|
| 112 |
+
self.version,
|
| 113 |
+
self.numPaletteEntries,
|
| 114 |
+
len(self.palettes),
|
| 115 |
+
numColorRecords,
|
| 116 |
+
offsetToFirstColorRecord,
|
| 117 |
+
)
|
| 118 |
+
if self.version == 0:
|
| 119 |
+
dataList = [header, colorRecordIndices, colorRecords]
|
| 120 |
+
else:
|
| 121 |
+
pos = offsetToFirstColorRecord + len(colorRecords)
|
| 122 |
+
if len(paletteTypes) == 0:
|
| 123 |
+
offsetToPaletteTypeArray = 0
|
| 124 |
+
else:
|
| 125 |
+
offsetToPaletteTypeArray = pos
|
| 126 |
+
pos += len(paletteTypes)
|
| 127 |
+
if len(paletteLabels) == 0:
|
| 128 |
+
offsetToPaletteLabelArray = 0
|
| 129 |
+
else:
|
| 130 |
+
offsetToPaletteLabelArray = pos
|
| 131 |
+
pos += len(paletteLabels)
|
| 132 |
+
if len(paletteEntryLabels) == 0:
|
| 133 |
+
offsetToPaletteEntryLabelArray = 0
|
| 134 |
+
else:
|
| 135 |
+
offsetToPaletteEntryLabelArray = pos
|
| 136 |
+
pos += len(paletteLabels)
|
| 137 |
+
header1 = struct.pack(
|
| 138 |
+
">LLL",
|
| 139 |
+
offsetToPaletteTypeArray,
|
| 140 |
+
offsetToPaletteLabelArray,
|
| 141 |
+
offsetToPaletteEntryLabelArray,
|
| 142 |
+
)
|
| 143 |
+
dataList = [
|
| 144 |
+
header,
|
| 145 |
+
colorRecordIndices,
|
| 146 |
+
header1,
|
| 147 |
+
colorRecords,
|
| 148 |
+
paletteTypes,
|
| 149 |
+
paletteLabels,
|
| 150 |
+
paletteEntryLabels,
|
| 151 |
+
]
|
| 152 |
+
return bytesjoin(dataList)
|
| 153 |
+
|
| 154 |
+
def _compilePalette(self, palette):
|
| 155 |
+
assert len(palette) == self.numPaletteEntries
|
| 156 |
+
pack = lambda c: struct.pack(">BBBB", c.blue, c.green, c.red, c.alpha)
|
| 157 |
+
return bytesjoin([pack(color) for color in palette])
|
| 158 |
+
|
| 159 |
+
def _compileColorRecords(self):
|
| 160 |
+
colorRecords, colorRecordIndices, pool = [], [], {}
|
| 161 |
+
for palette in self.palettes:
|
| 162 |
+
packedPalette = self._compilePalette(palette)
|
| 163 |
+
if packedPalette in pool:
|
| 164 |
+
index = pool[packedPalette]
|
| 165 |
+
else:
|
| 166 |
+
index = len(colorRecords)
|
| 167 |
+
colorRecords.append(packedPalette)
|
| 168 |
+
pool[packedPalette] = index
|
| 169 |
+
colorRecordIndices.append(struct.pack(">H", index * self.numPaletteEntries))
|
| 170 |
+
return bytesjoin(colorRecordIndices), bytesjoin(colorRecords)
|
| 171 |
+
|
| 172 |
+
def _compilePaletteTypes(self):
|
| 173 |
+
if self.version == 0 or not any(self.paletteTypes):
|
| 174 |
+
return b""
|
| 175 |
+
assert len(self.paletteTypes) == len(self.palettes)
|
| 176 |
+
result = bytesjoin([struct.pack(">I", ptype) for ptype in self.paletteTypes])
|
| 177 |
+
assert len(result) == 4 * len(self.palettes)
|
| 178 |
+
return result
|
| 179 |
+
|
| 180 |
+
def _compilePaletteLabels(self):
|
| 181 |
+
if self.version == 0 or all(l == self.NO_NAME_ID for l in self.paletteLabels):
|
| 182 |
+
return b""
|
| 183 |
+
assert len(self.paletteLabels) == len(self.palettes)
|
| 184 |
+
result = bytesjoin([struct.pack(">H", label) for label in self.paletteLabels])
|
| 185 |
+
assert len(result) == 2 * len(self.palettes)
|
| 186 |
+
return result
|
| 187 |
+
|
| 188 |
+
def _compilePaletteEntryLabels(self):
|
| 189 |
+
if self.version == 0 or all(
|
| 190 |
+
l == self.NO_NAME_ID for l in self.paletteEntryLabels
|
| 191 |
+
):
|
| 192 |
+
return b""
|
| 193 |
+
assert len(self.paletteEntryLabels) == self.numPaletteEntries
|
| 194 |
+
result = bytesjoin(
|
| 195 |
+
[struct.pack(">H", label) for label in self.paletteEntryLabels]
|
| 196 |
+
)
|
| 197 |
+
assert len(result) == 2 * self.numPaletteEntries
|
| 198 |
+
return result
|
| 199 |
+
|
| 200 |
+
def toXML(self, writer, ttFont):
|
| 201 |
+
numPalettes = len(self.palettes)
|
| 202 |
+
paletteLabels = {i: nameID for (i, nameID) in enumerate(self.paletteLabels)}
|
| 203 |
+
paletteTypes = {i: typ for (i, typ) in enumerate(self.paletteTypes)}
|
| 204 |
+
writer.simpletag("version", value=self.version)
|
| 205 |
+
writer.newline()
|
| 206 |
+
writer.simpletag("numPaletteEntries", value=self.numPaletteEntries)
|
| 207 |
+
writer.newline()
|
| 208 |
+
for index, palette in enumerate(self.palettes):
|
| 209 |
+
attrs = {"index": index}
|
| 210 |
+
paletteType = paletteTypes.get(index, self.DEFAULT_PALETTE_TYPE)
|
| 211 |
+
paletteLabel = paletteLabels.get(index, self.NO_NAME_ID)
|
| 212 |
+
if self.version > 0 and paletteLabel != self.NO_NAME_ID:
|
| 213 |
+
attrs["label"] = paletteLabel
|
| 214 |
+
if self.version > 0 and paletteType != self.DEFAULT_PALETTE_TYPE:
|
| 215 |
+
attrs["type"] = paletteType
|
| 216 |
+
writer.begintag("palette", **attrs)
|
| 217 |
+
writer.newline()
|
| 218 |
+
if (
|
| 219 |
+
self.version > 0
|
| 220 |
+
and paletteLabel != self.NO_NAME_ID
|
| 221 |
+
and ttFont
|
| 222 |
+
and "name" in ttFont
|
| 223 |
+
):
|
| 224 |
+
name = ttFont["name"].getDebugName(paletteLabel)
|
| 225 |
+
if name is not None:
|
| 226 |
+
writer.comment(name)
|
| 227 |
+
writer.newline()
|
| 228 |
+
assert len(palette) == self.numPaletteEntries
|
| 229 |
+
for cindex, color in enumerate(palette):
|
| 230 |
+
color.toXML(writer, ttFont, cindex)
|
| 231 |
+
writer.endtag("palette")
|
| 232 |
+
writer.newline()
|
| 233 |
+
if self.version > 0 and not all(
|
| 234 |
+
l == self.NO_NAME_ID for l in self.paletteEntryLabels
|
| 235 |
+
):
|
| 236 |
+
writer.begintag("paletteEntryLabels")
|
| 237 |
+
writer.newline()
|
| 238 |
+
for index, label in enumerate(self.paletteEntryLabels):
|
| 239 |
+
if label != self.NO_NAME_ID:
|
| 240 |
+
writer.simpletag("label", index=index, value=label)
|
| 241 |
+
if self.version > 0 and label and ttFont and "name" in ttFont:
|
| 242 |
+
name = ttFont["name"].getDebugName(label)
|
| 243 |
+
if name is not None:
|
| 244 |
+
writer.comment(name)
|
| 245 |
+
writer.newline()
|
| 246 |
+
writer.endtag("paletteEntryLabels")
|
| 247 |
+
writer.newline()
|
| 248 |
+
|
| 249 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 250 |
+
if name == "palette":
|
| 251 |
+
self.paletteLabels.append(int(attrs.get("label", self.NO_NAME_ID)))
|
| 252 |
+
self.paletteTypes.append(int(attrs.get("type", self.DEFAULT_PALETTE_TYPE)))
|
| 253 |
+
palette = []
|
| 254 |
+
for element in content:
|
| 255 |
+
if isinstance(element, str):
|
| 256 |
+
continue
|
| 257 |
+
attrs = element[1]
|
| 258 |
+
color = Color.fromHex(attrs["value"])
|
| 259 |
+
palette.append(color)
|
| 260 |
+
self.palettes.append(palette)
|
| 261 |
+
elif name == "paletteEntryLabels":
|
| 262 |
+
colorLabels = {}
|
| 263 |
+
for element in content:
|
| 264 |
+
if isinstance(element, str):
|
| 265 |
+
continue
|
| 266 |
+
elementName, elementAttr, _ = element
|
| 267 |
+
if elementName == "label":
|
| 268 |
+
labelIndex = safeEval(elementAttr["index"])
|
| 269 |
+
nameID = safeEval(elementAttr["value"])
|
| 270 |
+
colorLabels[labelIndex] = nameID
|
| 271 |
+
self.paletteEntryLabels = [
|
| 272 |
+
colorLabels.get(i, self.NO_NAME_ID)
|
| 273 |
+
for i in range(self.numPaletteEntries)
|
| 274 |
+
]
|
| 275 |
+
elif "value" in attrs:
|
| 276 |
+
value = safeEval(attrs["value"])
|
| 277 |
+
setattr(self, name, value)
|
| 278 |
+
if name == "numPaletteEntries":
|
| 279 |
+
self.paletteEntryLabels = [self.NO_NAME_ID] * self.numPaletteEntries
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class Color(namedtuple("Color", "blue green red alpha")):
|
| 283 |
+
def hex(self):
|
| 284 |
+
return "#%02X%02X%02X%02X" % (self.red, self.green, self.blue, self.alpha)
|
| 285 |
+
|
| 286 |
+
def __repr__(self):
|
| 287 |
+
return self.hex()
|
| 288 |
+
|
| 289 |
+
def toXML(self, writer, ttFont, index=None):
|
| 290 |
+
writer.simpletag("color", value=self.hex(), index=index)
|
| 291 |
+
writer.newline()
|
| 292 |
+
|
| 293 |
+
@classmethod
|
| 294 |
+
def fromHex(cls, value):
|
| 295 |
+
if value[0] == "#":
|
| 296 |
+
value = value[1:]
|
| 297 |
+
red = int(value[0:2], 16)
|
| 298 |
+
green = int(value[2:4], 16)
|
| 299 |
+
blue = int(value[4:6], 16)
|
| 300 |
+
alpha = int(value[6:8], 16) if len(value) >= 8 else 0xFF
|
| 301 |
+
return cls(red=red, green=green, blue=blue, alpha=alpha)
|
| 302 |
+
|
| 303 |
+
@classmethod
|
| 304 |
+
def fromRGBA(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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
from typing import TYPE_CHECKING
|
| 5 |
+
|
| 6 |
+
from fontTools.misc import sstruct
|
| 7 |
+
from fontTools.misc.textTools import bytesjoin, safeEval, strjoin, tobytes, tostr
|
| 8 |
+
|
| 9 |
+
from . import DefaultTable
|
| 10 |
+
|
| 11 |
+
if TYPE_CHECKING:
|
| 12 |
+
from fontTools.misc.xmlWriter import XMLWriter
|
| 13 |
+
from fontTools.ttLib import TTFont
|
| 14 |
+
|
| 15 |
+
DSIG_HeaderFormat = """
|
| 16 |
+
> # big endian
|
| 17 |
+
ulVersion: L
|
| 18 |
+
usNumSigs: H
|
| 19 |
+
usFlag: H
|
| 20 |
+
"""
|
| 21 |
+
# followed by an array of usNumSigs DSIG_Signature records
|
| 22 |
+
DSIG_SignatureFormat = """
|
| 23 |
+
> # big endian
|
| 24 |
+
ulFormat: L
|
| 25 |
+
ulLength: L # length includes DSIG_SignatureBlock header
|
| 26 |
+
ulOffset: L
|
| 27 |
+
"""
|
| 28 |
+
# followed by an array of usNumSigs DSIG_SignatureBlock records,
|
| 29 |
+
# each followed immediately by the pkcs7 bytes
|
| 30 |
+
DSIG_SignatureBlockFormat = """
|
| 31 |
+
> # big endian
|
| 32 |
+
usReserved1: H
|
| 33 |
+
usReserved2: H
|
| 34 |
+
cbSignature: l # length of following raw pkcs7 data
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
#
|
| 38 |
+
# NOTE
|
| 39 |
+
# the DSIG table format allows for SignatureBlocks residing
|
| 40 |
+
# anywhere in the table and possibly in a different order as
|
| 41 |
+
# listed in the array after the first table header
|
| 42 |
+
#
|
| 43 |
+
# this implementation does not keep track of any gaps and/or data
|
| 44 |
+
# before or after the actual signature blocks while decompiling,
|
| 45 |
+
# and puts them in the same physical order as listed in the header
|
| 46 |
+
# on compilation with no padding whatsoever.
|
| 47 |
+
#
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class table_D_S_I_G_(DefaultTable.DefaultTable):
|
| 51 |
+
"""Digital Signature table
|
| 52 |
+
|
| 53 |
+
The ``DSIG`` table contains cryptographic signatures for the font.
|
| 54 |
+
|
| 55 |
+
See also https://learn.microsoft.com/en-us/typography/opentype/spec/dsig
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
def decompile(self, data: bytes, ttFont: TTFont) -> None:
|
| 59 |
+
dummy, newData = sstruct.unpack2(DSIG_HeaderFormat, data, self)
|
| 60 |
+
assert self.ulVersion == 1, "DSIG ulVersion must be 1"
|
| 61 |
+
assert self.usFlag & ~1 == 0, "DSIG usFlag must be 0x1 or 0x0"
|
| 62 |
+
self.signatureRecords: list[SignatureRecord] = []
|
| 63 |
+
sigrecs = self.signatureRecords
|
| 64 |
+
for n in range(self.usNumSigs):
|
| 65 |
+
sigrec, newData = sstruct.unpack2(
|
| 66 |
+
DSIG_SignatureFormat, newData, SignatureRecord()
|
| 67 |
+
)
|
| 68 |
+
assert sigrec.ulFormat == 1, (
|
| 69 |
+
"DSIG signature record #%d ulFormat must be 1" % n
|
| 70 |
+
)
|
| 71 |
+
sigrecs.append(sigrec)
|
| 72 |
+
for sigrec in sigrecs:
|
| 73 |
+
dummy, newData = sstruct.unpack2(
|
| 74 |
+
DSIG_SignatureBlockFormat, data[sigrec.ulOffset :], sigrec
|
| 75 |
+
)
|
| 76 |
+
assert sigrec.usReserved1 == 0, (
|
| 77 |
+
"DSIG signature record #%d usReserverd1 must be 0" % n
|
| 78 |
+
)
|
| 79 |
+
assert sigrec.usReserved2 == 0, (
|
| 80 |
+
"DSIG signature record #%d usReserverd2 must be 0" % n
|
| 81 |
+
)
|
| 82 |
+
sigrec.pkcs7 = newData[: sigrec.cbSignature]
|
| 83 |
+
|
| 84 |
+
def compile(self, ttFont: TTFont) -> bytes:
|
| 85 |
+
packed = sstruct.pack(DSIG_HeaderFormat, self)
|
| 86 |
+
headers = [packed]
|
| 87 |
+
offset = len(packed) + self.usNumSigs * sstruct.calcsize(DSIG_SignatureFormat)
|
| 88 |
+
data = []
|
| 89 |
+
for sigrec in self.signatureRecords:
|
| 90 |
+
# first pack signature block
|
| 91 |
+
sigrec.cbSignature = len(sigrec.pkcs7)
|
| 92 |
+
packed = sstruct.pack(DSIG_SignatureBlockFormat, sigrec) + sigrec.pkcs7
|
| 93 |
+
data.append(packed)
|
| 94 |
+
# update redundant length field
|
| 95 |
+
sigrec.ulLength = len(packed)
|
| 96 |
+
# update running table offset
|
| 97 |
+
sigrec.ulOffset = offset
|
| 98 |
+
headers.append(sstruct.pack(DSIG_SignatureFormat, sigrec))
|
| 99 |
+
offset += sigrec.ulLength
|
| 100 |
+
if offset % 2:
|
| 101 |
+
# Pad to even bytes
|
| 102 |
+
data.append(b"\0")
|
| 103 |
+
return bytesjoin(headers + data)
|
| 104 |
+
|
| 105 |
+
def toXML(self, xmlWriter: XMLWriter, ttFont: TTFont) -> None:
|
| 106 |
+
xmlWriter.comment(
|
| 107 |
+
"note that the Digital Signature will be invalid after recompilation!"
|
| 108 |
+
)
|
| 109 |
+
xmlWriter.newline()
|
| 110 |
+
xmlWriter.simpletag(
|
| 111 |
+
"tableHeader",
|
| 112 |
+
version=self.ulVersion,
|
| 113 |
+
numSigs=self.usNumSigs,
|
| 114 |
+
flag="0x%X" % self.usFlag,
|
| 115 |
+
)
|
| 116 |
+
for sigrec in self.signatureRecords:
|
| 117 |
+
xmlWriter.newline()
|
| 118 |
+
sigrec.toXML(xmlWriter, ttFont)
|
| 119 |
+
xmlWriter.newline()
|
| 120 |
+
|
| 121 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 122 |
+
if name == "tableHeader":
|
| 123 |
+
self.signatureRecords = []
|
| 124 |
+
self.ulVersion = safeEval(attrs["version"])
|
| 125 |
+
self.usNumSigs = safeEval(attrs["numSigs"])
|
| 126 |
+
self.usFlag = safeEval(attrs["flag"])
|
| 127 |
+
return
|
| 128 |
+
if name == "SignatureRecord":
|
| 129 |
+
sigrec = SignatureRecord()
|
| 130 |
+
sigrec.fromXML(name, attrs, content, ttFont)
|
| 131 |
+
self.signatureRecords.append(sigrec)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
pem_spam = lambda l, spam={
|
| 135 |
+
"-----BEGIN PKCS7-----": True,
|
| 136 |
+
"-----END PKCS7-----": True,
|
| 137 |
+
"": True,
|
| 138 |
+
}: not spam.get(l.strip())
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def b64encode(b):
|
| 142 |
+
s = base64.b64encode(b)
|
| 143 |
+
# Line-break at 76 chars.
|
| 144 |
+
items = []
|
| 145 |
+
while s:
|
| 146 |
+
items.append(tostr(s[:76]))
|
| 147 |
+
items.append("\n")
|
| 148 |
+
s = s[76:]
|
| 149 |
+
return strjoin(items)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class SignatureRecord:
|
| 153 |
+
def __repr__(self) -> str:
|
| 154 |
+
return "<%s: %s>" % (self.__class__.__name__, self.__dict__)
|
| 155 |
+
|
| 156 |
+
def toXML(self, writer, ttFont: TTFont) -> None:
|
| 157 |
+
writer.begintag(self.__class__.__name__, format=self.ulFormat)
|
| 158 |
+
writer.newline()
|
| 159 |
+
writer.write_noindent("-----BEGIN PKCS7-----\n")
|
| 160 |
+
writer.write_noindent(b64encode(self.pkcs7))
|
| 161 |
+
writer.write_noindent("-----END PKCS7-----\n")
|
| 162 |
+
writer.endtag(self.__class__.__name__)
|
| 163 |
+
|
| 164 |
+
def fromXML(
|
| 165 |
+
self, name: str, attrs: dict[str, str], content: str, ttFont: TTFont
|
| 166 |
+
) -> None:
|
| 167 |
+
self.ulFormat: int = safeEval(attrs["format"])
|
| 168 |
+
self.usReserved1: int = safeEval(attrs.get("reserved1", "0"))
|
| 169 |
+
self.usReserved2: int = safeEval(attrs.get("reserved2", "0"))
|
| 170 |
+
self.pkcs7 = base64.b64decode(tobytes(strjoin(filter(pem_spam, content))))
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/D__e_b_g.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from textwrap import indent
|
| 3 |
+
|
| 4 |
+
from . import DefaultTable
|
| 5 |
+
from fontTools.misc.textTools import tostr
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class table_D__e_b_g(DefaultTable.DefaultTable):
|
| 9 |
+
def __init__(self, tag=None):
|
| 10 |
+
DefaultTable.DefaultTable.__init__(self, tag)
|
| 11 |
+
self.data = {}
|
| 12 |
+
|
| 13 |
+
def decompile(self, data, ttFont):
|
| 14 |
+
self.data = json.loads(data)
|
| 15 |
+
|
| 16 |
+
def compile(self, ttFont):
|
| 17 |
+
return json.dumps(self.data).encode("utf-8")
|
| 18 |
+
|
| 19 |
+
def toXML(self, writer, ttFont):
|
| 20 |
+
# make sure json indentation inside CDATA block matches XMLWriter's
|
| 21 |
+
data = json.dumps(self.data, indent=len(writer.indentwhite))
|
| 22 |
+
prefix = tostr(writer.indentwhite) * (writer.indentlevel + 1)
|
| 23 |
+
# but don't indent the first json line so it's adjacent to `<![CDATA[{`
|
| 24 |
+
cdata = indent(data, prefix, lambda ln: ln != "{\n")
|
| 25 |
+
|
| 26 |
+
writer.begintag("json")
|
| 27 |
+
writer.newline()
|
| 28 |
+
writer.writecdata(cdata)
|
| 29 |
+
writer.newline()
|
| 30 |
+
writer.endtag("json")
|
| 31 |
+
writer.newline()
|
| 32 |
+
|
| 33 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 34 |
+
if name == "json":
|
| 35 |
+
self.data = json.loads("".join(content))
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/DefaultTable.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
from fontTools.misc.textTools import Tag
|
| 6 |
+
from fontTools.ttLib import getClassTag
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
from fontTools.misc.xmlWriter import XMLWriter
|
| 12 |
+
from fontTools.ttLib import TTFont
|
| 13 |
+
|
| 14 |
+
XMLAttrs = dict[str, str]
|
| 15 |
+
XMLContent = list[str | tuple[str, XMLAttrs, "XMLContent"]]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class DefaultTable:
|
| 19 |
+
dependencies: list[str] = []
|
| 20 |
+
|
| 21 |
+
def __init__(self, tag: str | bytes | None = None) -> None:
|
| 22 |
+
if tag is None:
|
| 23 |
+
tag = getClassTag(self.__class__)
|
| 24 |
+
self.tableTag = Tag(tag)
|
| 25 |
+
|
| 26 |
+
def decompile(self, data: bytes, ttFont: TTFont) -> None:
|
| 27 |
+
self.data = data
|
| 28 |
+
|
| 29 |
+
def compile(self, ttFont: TTFont) -> bytes:
|
| 30 |
+
return self.data
|
| 31 |
+
|
| 32 |
+
def toXML(self, writer: XMLWriter, ttFont: TTFont, **kwargs: Any) -> None:
|
| 33 |
+
if hasattr(self, "ERROR"):
|
| 34 |
+
writer.comment("An error occurred during the decompilation of this table")
|
| 35 |
+
writer.newline()
|
| 36 |
+
writer.comment(self.ERROR)
|
| 37 |
+
writer.newline()
|
| 38 |
+
writer.begintag("hexdata")
|
| 39 |
+
writer.newline()
|
| 40 |
+
writer.dumphex(self.compile(ttFont))
|
| 41 |
+
writer.endtag("hexdata")
|
| 42 |
+
writer.newline()
|
| 43 |
+
|
| 44 |
+
def fromXML(
|
| 45 |
+
self, name: str, attrs: XMLAttrs, content: XMLContent, ttFont: TTFont
|
| 46 |
+
) -> None:
|
| 47 |
+
from fontTools import ttLib
|
| 48 |
+
from fontTools.misc.textTools import readHex
|
| 49 |
+
|
| 50 |
+
if name != "hexdata":
|
| 51 |
+
raise ttLib.TTLibError("can't handle '%s' element" % name)
|
| 52 |
+
self.decompile(readHex(content), ttFont)
|
| 53 |
+
|
| 54 |
+
def __repr__(self) -> str:
|
| 55 |
+
return "<'%s' table at %x>" % (self.tableTag, id(self))
|
| 56 |
+
|
| 57 |
+
def __eq__(self, other: object) -> bool:
|
| 58 |
+
if type(self) is not type(other):
|
| 59 |
+
return NotImplemented
|
| 60 |
+
return self.__dict__ == other.__dict__
|
| 61 |
+
|
| 62 |
+
def __ne__(self, other: object) -> bool:
|
| 63 |
+
result = self.__eq__(other)
|
| 64 |
+
return result if result is NotImplemented else not result
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_D_T_.py
ADDED
|
@@ -0,0 +1,856 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
from fontTools.misc import sstruct
|
| 2 |
+
from fontTools.misc.textTools import (
|
| 3 |
+
bytechr,
|
| 4 |
+
byteord,
|
| 5 |
+
bytesjoin,
|
| 6 |
+
strjoin,
|
| 7 |
+
safeEval,
|
| 8 |
+
readHex,
|
| 9 |
+
hexStr,
|
| 10 |
+
deHexStr,
|
| 11 |
+
)
|
| 12 |
+
from .BitmapGlyphMetrics import (
|
| 13 |
+
BigGlyphMetrics,
|
| 14 |
+
bigGlyphMetricsFormat,
|
| 15 |
+
SmallGlyphMetrics,
|
| 16 |
+
smallGlyphMetricsFormat,
|
| 17 |
+
)
|
| 18 |
+
from . import DefaultTable
|
| 19 |
+
import itertools
|
| 20 |
+
import os
|
| 21 |
+
import re
|
| 22 |
+
from urllib.parse import quote
|
| 23 |
+
|
| 24 |
+
# a glyph name is usable as a filename as-is unless it contains a path
|
| 25 |
+
# separator (on any platform, not just this one) or the '%' that marks an
|
| 26 |
+
# encoded name
|
| 27 |
+
_UNSAFE_IN_FILENAME = re.compile(r"[%/\\]")
|
| 28 |
+
import struct
|
| 29 |
+
import logging
|
| 30 |
+
|
| 31 |
+
log = logging.getLogger(__name__)
|
| 32 |
+
|
| 33 |
+
ebdtTableVersionFormat = """
|
| 34 |
+
> # big endian
|
| 35 |
+
version: 16.16F
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
ebdtComponentFormat = """
|
| 39 |
+
> # big endian
|
| 40 |
+
glyphCode: H
|
| 41 |
+
xOffset: b
|
| 42 |
+
yOffset: b
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class table_E_B_D_T_(DefaultTable.DefaultTable):
|
| 47 |
+
"""Embedded Bitmap Data table
|
| 48 |
+
|
| 49 |
+
The ``EBDT`` table contains monochrome or grayscale bitmap data for
|
| 50 |
+
glyphs. It must be used in concert with the ``EBLC`` table.
|
| 51 |
+
|
| 52 |
+
See also https://learn.microsoft.com/en-us/typography/opentype/spec/ebdt
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
# Keep a reference to the name of the data locator table.
|
| 56 |
+
locatorName = "EBLC"
|
| 57 |
+
|
| 58 |
+
# This method can be overridden in subclasses to support new formats
|
| 59 |
+
# without changing the other implementation. Also can be used as a
|
| 60 |
+
# convenience method for coverting a font file to an alternative format.
|
| 61 |
+
def getImageFormatClass(self, imageFormat):
|
| 62 |
+
return ebdt_bitmap_classes[imageFormat]
|
| 63 |
+
|
| 64 |
+
def decompile(self, data, ttFont):
|
| 65 |
+
# Get the version but don't advance the slice.
|
| 66 |
+
# Most of the lookup for this table is done relative
|
| 67 |
+
# to the begining so slice by the offsets provided
|
| 68 |
+
# in the EBLC table.
|
| 69 |
+
sstruct.unpack2(ebdtTableVersionFormat, data, self)
|
| 70 |
+
|
| 71 |
+
# Keep a dict of glyphs that have been seen so they aren't remade.
|
| 72 |
+
# This dict maps intervals of data to the BitmapGlyph.
|
| 73 |
+
glyphDict = {}
|
| 74 |
+
|
| 75 |
+
# Pull out the EBLC table and loop through glyphs.
|
| 76 |
+
# A strike is a concept that spans both tables.
|
| 77 |
+
# The actual bitmap data is stored in the EBDT.
|
| 78 |
+
locator = ttFont[self.__class__.locatorName]
|
| 79 |
+
self.strikeData = []
|
| 80 |
+
for curStrike in locator.strikes:
|
| 81 |
+
bitmapGlyphDict = {}
|
| 82 |
+
self.strikeData.append(bitmapGlyphDict)
|
| 83 |
+
for indexSubTable in curStrike.indexSubTables:
|
| 84 |
+
dataIter = zip(indexSubTable.names, indexSubTable.locations)
|
| 85 |
+
for curName, curLoc in dataIter:
|
| 86 |
+
# Don't create duplicate data entries for the same glyphs.
|
| 87 |
+
# Instead just use the structures that already exist if they exist.
|
| 88 |
+
if curLoc in glyphDict:
|
| 89 |
+
curGlyph = glyphDict[curLoc]
|
| 90 |
+
else:
|
| 91 |
+
curGlyphData = data[slice(*curLoc)]
|
| 92 |
+
imageFormatClass = self.getImageFormatClass(
|
| 93 |
+
indexSubTable.imageFormat
|
| 94 |
+
)
|
| 95 |
+
curGlyph = imageFormatClass(curGlyphData, ttFont)
|
| 96 |
+
glyphDict[curLoc] = curGlyph
|
| 97 |
+
bitmapGlyphDict[curName] = curGlyph
|
| 98 |
+
|
| 99 |
+
def compile(self, ttFont):
|
| 100 |
+
dataList = []
|
| 101 |
+
dataList.append(sstruct.pack(ebdtTableVersionFormat, self))
|
| 102 |
+
dataSize = len(dataList[0])
|
| 103 |
+
|
| 104 |
+
# Keep a dict of glyphs that have been seen so they aren't remade.
|
| 105 |
+
# This dict maps the id of the BitmapGlyph to the interval
|
| 106 |
+
# in the data.
|
| 107 |
+
glyphDict = {}
|
| 108 |
+
|
| 109 |
+
# Go through the bitmap glyph data. Just in case the data for a glyph
|
| 110 |
+
# changed the size metrics should be recalculated. There are a variety
|
| 111 |
+
# of formats and they get stored in the EBLC table. That is why
|
| 112 |
+
# recalculation is defered to the EblcIndexSubTable class and just
|
| 113 |
+
# pass what is known about bitmap glyphs from this particular table.
|
| 114 |
+
locator = ttFont[self.__class__.locatorName]
|
| 115 |
+
for curStrike, curGlyphDict in zip(locator.strikes, self.strikeData):
|
| 116 |
+
for curIndexSubTable in curStrike.indexSubTables:
|
| 117 |
+
dataLocations = []
|
| 118 |
+
for curName in curIndexSubTable.names:
|
| 119 |
+
# Handle the data placement based on seeing the glyph or not.
|
| 120 |
+
# Just save a reference to the location if the glyph has already
|
| 121 |
+
# been saved in compile. This code assumes that glyphs will only
|
| 122 |
+
# be referenced multiple times from indexFormat5. By luck the
|
| 123 |
+
# code may still work when referencing poorly ordered fonts with
|
| 124 |
+
# duplicate references. If there is a font that is unlucky the
|
| 125 |
+
# respective compile methods for the indexSubTables will fail
|
| 126 |
+
# their assertions. All fonts seem to follow this assumption.
|
| 127 |
+
# More complicated packing may be needed if a counter-font exists.
|
| 128 |
+
glyph = curGlyphDict[curName]
|
| 129 |
+
objectId = id(glyph)
|
| 130 |
+
if objectId not in glyphDict:
|
| 131 |
+
data = glyph.compile(ttFont)
|
| 132 |
+
data = curIndexSubTable.padBitmapData(data)
|
| 133 |
+
startByte = dataSize
|
| 134 |
+
dataSize += len(data)
|
| 135 |
+
endByte = dataSize
|
| 136 |
+
dataList.append(data)
|
| 137 |
+
dataLoc = (startByte, endByte)
|
| 138 |
+
glyphDict[objectId] = dataLoc
|
| 139 |
+
else:
|
| 140 |
+
dataLoc = glyphDict[objectId]
|
| 141 |
+
dataLocations.append(dataLoc)
|
| 142 |
+
# Just use the new data locations in the indexSubTable.
|
| 143 |
+
# The respective compile implementations will take care
|
| 144 |
+
# of any of the problems in the convertion that may arise.
|
| 145 |
+
curIndexSubTable.locations = dataLocations
|
| 146 |
+
|
| 147 |
+
return bytesjoin(dataList)
|
| 148 |
+
|
| 149 |
+
def toXML(self, writer, ttFont):
|
| 150 |
+
# When exporting to XML if one of the data export formats
|
| 151 |
+
# requires metrics then those metrics may be in the locator.
|
| 152 |
+
# In this case populate the bitmaps with "export metrics".
|
| 153 |
+
if ttFont.bitmapGlyphDataFormat in ("row", "bitwise"):
|
| 154 |
+
locator = ttFont[self.__class__.locatorName]
|
| 155 |
+
for curStrike, curGlyphDict in zip(locator.strikes, self.strikeData):
|
| 156 |
+
for curIndexSubTable in curStrike.indexSubTables:
|
| 157 |
+
for curName in curIndexSubTable.names:
|
| 158 |
+
glyph = curGlyphDict[curName]
|
| 159 |
+
# I'm not sure which metrics have priority here.
|
| 160 |
+
# For now if both metrics exist go with glyph metrics.
|
| 161 |
+
if hasattr(glyph, "metrics"):
|
| 162 |
+
glyph.exportMetrics = glyph.metrics
|
| 163 |
+
else:
|
| 164 |
+
glyph.exportMetrics = curIndexSubTable.metrics
|
| 165 |
+
glyph.exportBitDepth = curStrike.bitmapSizeTable.bitDepth
|
| 166 |
+
|
| 167 |
+
writer.simpletag("header", [("version", self.version)])
|
| 168 |
+
writer.newline()
|
| 169 |
+
locator = ttFont[self.__class__.locatorName]
|
| 170 |
+
for strikeIndex, bitmapGlyphDict in enumerate(self.strikeData):
|
| 171 |
+
writer.begintag("strikedata", [("index", strikeIndex)])
|
| 172 |
+
writer.newline()
|
| 173 |
+
for curName, curBitmap in bitmapGlyphDict.items():
|
| 174 |
+
curBitmap.toXML(strikeIndex, curName, writer, ttFont)
|
| 175 |
+
writer.endtag("strikedata")
|
| 176 |
+
writer.newline()
|
| 177 |
+
|
| 178 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 179 |
+
if name == "header":
|
| 180 |
+
self.version = safeEval(attrs["version"])
|
| 181 |
+
elif name == "strikedata":
|
| 182 |
+
if not hasattr(self, "strikeData"):
|
| 183 |
+
self.strikeData = []
|
| 184 |
+
strikeIndex = safeEval(attrs["index"])
|
| 185 |
+
|
| 186 |
+
bitmapGlyphDict = {}
|
| 187 |
+
for element in content:
|
| 188 |
+
if not isinstance(element, tuple):
|
| 189 |
+
continue
|
| 190 |
+
name, attrs, content = element
|
| 191 |
+
if name[4:].startswith(_bitmapGlyphSubclassPrefix[4:]):
|
| 192 |
+
imageFormat = safeEval(name[len(_bitmapGlyphSubclassPrefix) :])
|
| 193 |
+
glyphName = attrs["name"]
|
| 194 |
+
imageFormatClass = self.getImageFormatClass(imageFormat)
|
| 195 |
+
curGlyph = imageFormatClass(None, None)
|
| 196 |
+
curGlyph.fromXML(name, attrs, content, ttFont)
|
| 197 |
+
assert glyphName not in bitmapGlyphDict, (
|
| 198 |
+
"Duplicate glyphs with the same name '%s' in the same strike."
|
| 199 |
+
% glyphName
|
| 200 |
+
)
|
| 201 |
+
bitmapGlyphDict[glyphName] = curGlyph
|
| 202 |
+
else:
|
| 203 |
+
log.warning("%s being ignored by %s", name, self.__class__.__name__)
|
| 204 |
+
|
| 205 |
+
# Grow the strike data array to the appropriate size. The XML
|
| 206 |
+
# format allows the strike index value to be out of order.
|
| 207 |
+
if strikeIndex >= len(self.strikeData):
|
| 208 |
+
self.strikeData += [None] * (strikeIndex + 1 - len(self.strikeData))
|
| 209 |
+
assert (
|
| 210 |
+
self.strikeData[strikeIndex] is None
|
| 211 |
+
), "Duplicate strike EBDT indices."
|
| 212 |
+
self.strikeData[strikeIndex] = bitmapGlyphDict
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class EbdtComponent(object):
|
| 216 |
+
def toXML(self, writer, ttFont):
|
| 217 |
+
writer.begintag("ebdtComponent", [("name", self.name)])
|
| 218 |
+
writer.newline()
|
| 219 |
+
for componentName in sstruct.getformat(ebdtComponentFormat)[1][1:]:
|
| 220 |
+
writer.simpletag(componentName, value=getattr(self, componentName))
|
| 221 |
+
writer.newline()
|
| 222 |
+
writer.endtag("ebdtComponent")
|
| 223 |
+
writer.newline()
|
| 224 |
+
|
| 225 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 226 |
+
self.name = attrs["name"]
|
| 227 |
+
componentNames = set(sstruct.getformat(ebdtComponentFormat)[1][1:])
|
| 228 |
+
for element in content:
|
| 229 |
+
if not isinstance(element, tuple):
|
| 230 |
+
continue
|
| 231 |
+
name, attrs, content = element
|
| 232 |
+
if name in componentNames:
|
| 233 |
+
vars(self)[name] = safeEval(attrs["value"])
|
| 234 |
+
else:
|
| 235 |
+
log.warning("unknown name '%s' being ignored by EbdtComponent.", name)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
# Helper functions for dealing with binary.
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def _data2binary(data, numBits):
|
| 242 |
+
binaryList = []
|
| 243 |
+
for curByte in data:
|
| 244 |
+
value = byteord(curByte)
|
| 245 |
+
numBitsCut = min(8, numBits)
|
| 246 |
+
for i in range(numBitsCut):
|
| 247 |
+
if value & 0x1:
|
| 248 |
+
binaryList.append("1")
|
| 249 |
+
else:
|
| 250 |
+
binaryList.append("0")
|
| 251 |
+
value = value >> 1
|
| 252 |
+
numBits -= numBitsCut
|
| 253 |
+
return strjoin(binaryList)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def _binary2data(binary):
|
| 257 |
+
byteList = []
|
| 258 |
+
for bitLoc in range(0, len(binary), 8):
|
| 259 |
+
byteString = binary[bitLoc : bitLoc + 8]
|
| 260 |
+
curByte = 0
|
| 261 |
+
for curBit in reversed(byteString):
|
| 262 |
+
curByte = curByte << 1
|
| 263 |
+
if curBit == "1":
|
| 264 |
+
curByte |= 1
|
| 265 |
+
byteList.append(bytechr(curByte))
|
| 266 |
+
return bytesjoin(byteList)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def _memoize(f):
|
| 270 |
+
class memodict(dict):
|
| 271 |
+
def __missing__(self, key):
|
| 272 |
+
ret = f(key)
|
| 273 |
+
if isinstance(key, int) or len(key) == 1:
|
| 274 |
+
self[key] = ret
|
| 275 |
+
return ret
|
| 276 |
+
|
| 277 |
+
return memodict().__getitem__
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
# 00100111 -> 11100100 per byte, not to be confused with little/big endian.
|
| 281 |
+
# Bitmap data per byte is in the order that binary is written on the page
|
| 282 |
+
# with the least significant bit as far right as possible. This is the
|
| 283 |
+
# opposite of what makes sense algorithmically and hence this function.
|
| 284 |
+
@_memoize
|
| 285 |
+
def _reverseBytes(data):
|
| 286 |
+
r"""
|
| 287 |
+
>>> bin(ord(_reverseBytes(0b00100111)))
|
| 288 |
+
'0b11100100'
|
| 289 |
+
>>> _reverseBytes(b'\x00\xf0')
|
| 290 |
+
b'\x00\x0f'
|
| 291 |
+
"""
|
| 292 |
+
if isinstance(data, bytes) and len(data) != 1:
|
| 293 |
+
return bytesjoin(map(_reverseBytes, data))
|
| 294 |
+
byte = byteord(data)
|
| 295 |
+
result = 0
|
| 296 |
+
for i in range(8):
|
| 297 |
+
result = result << 1
|
| 298 |
+
result |= byte & 1
|
| 299 |
+
byte = byte >> 1
|
| 300 |
+
return bytechr(result)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
# This section of code is for reading and writing image data to/from XML.
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def _writeRawImageData(strikeIndex, glyphName, bitmapObject, writer, ttFont):
|
| 307 |
+
writer.begintag("rawimagedata")
|
| 308 |
+
writer.newline()
|
| 309 |
+
writer.dumphex(bitmapObject.imageData)
|
| 310 |
+
writer.endtag("rawimagedata")
|
| 311 |
+
writer.newline()
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _readRawImageData(bitmapObject, name, attrs, content, ttFont):
|
| 315 |
+
bitmapObject.imageData = readHex(content)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _writeRowImageData(strikeIndex, glyphName, bitmapObject, writer, ttFont):
|
| 319 |
+
metrics = bitmapObject.exportMetrics
|
| 320 |
+
del bitmapObject.exportMetrics
|
| 321 |
+
bitDepth = bitmapObject.exportBitDepth
|
| 322 |
+
del bitmapObject.exportBitDepth
|
| 323 |
+
|
| 324 |
+
writer.begintag(
|
| 325 |
+
"rowimagedata", bitDepth=bitDepth, width=metrics.width, height=metrics.height
|
| 326 |
+
)
|
| 327 |
+
writer.newline()
|
| 328 |
+
for curRow in range(metrics.height):
|
| 329 |
+
rowData = bitmapObject.getRow(curRow, bitDepth=bitDepth, metrics=metrics)
|
| 330 |
+
writer.simpletag("row", value=hexStr(rowData))
|
| 331 |
+
writer.newline()
|
| 332 |
+
writer.endtag("rowimagedata")
|
| 333 |
+
writer.newline()
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def _readRowImageData(bitmapObject, name, attrs, content, ttFont):
|
| 337 |
+
bitDepth = safeEval(attrs["bitDepth"])
|
| 338 |
+
metrics = SmallGlyphMetrics()
|
| 339 |
+
metrics.width = safeEval(attrs["width"])
|
| 340 |
+
metrics.height = safeEval(attrs["height"])
|
| 341 |
+
|
| 342 |
+
dataRows = []
|
| 343 |
+
for element in content:
|
| 344 |
+
if not isinstance(element, tuple):
|
| 345 |
+
continue
|
| 346 |
+
name, attr, content = element
|
| 347 |
+
# Chop off 'imagedata' from the tag to get just the option.
|
| 348 |
+
if name == "row":
|
| 349 |
+
dataRows.append(deHexStr(attr["value"]))
|
| 350 |
+
bitmapObject.setRows(dataRows, bitDepth=bitDepth, metrics=metrics)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def _writeBitwiseImageData(strikeIndex, glyphName, bitmapObject, writer, ttFont):
|
| 354 |
+
metrics = bitmapObject.exportMetrics
|
| 355 |
+
del bitmapObject.exportMetrics
|
| 356 |
+
bitDepth = bitmapObject.exportBitDepth
|
| 357 |
+
del bitmapObject.exportBitDepth
|
| 358 |
+
|
| 359 |
+
# A dict for mapping binary to more readable/artistic ASCII characters.
|
| 360 |
+
binaryConv = {"0": ".", "1": "@"}
|
| 361 |
+
|
| 362 |
+
writer.begintag(
|
| 363 |
+
"bitwiseimagedata",
|
| 364 |
+
bitDepth=bitDepth,
|
| 365 |
+
width=metrics.width,
|
| 366 |
+
height=metrics.height,
|
| 367 |
+
)
|
| 368 |
+
writer.newline()
|
| 369 |
+
for curRow in range(metrics.height):
|
| 370 |
+
rowData = bitmapObject.getRow(
|
| 371 |
+
curRow, bitDepth=1, metrics=metrics, reverseBytes=True
|
| 372 |
+
)
|
| 373 |
+
rowData = _data2binary(rowData, metrics.width)
|
| 374 |
+
# Make the output a readable ASCII art form.
|
| 375 |
+
rowData = strjoin(map(binaryConv.get, rowData))
|
| 376 |
+
writer.simpletag("row", value=rowData)
|
| 377 |
+
writer.newline()
|
| 378 |
+
writer.endtag("bitwiseimagedata")
|
| 379 |
+
writer.newline()
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def _readBitwiseImageData(bitmapObject, name, attrs, content, ttFont):
|
| 383 |
+
bitDepth = safeEval(attrs["bitDepth"])
|
| 384 |
+
metrics = SmallGlyphMetrics()
|
| 385 |
+
metrics.width = safeEval(attrs["width"])
|
| 386 |
+
metrics.height = safeEval(attrs["height"])
|
| 387 |
+
|
| 388 |
+
# A dict for mapping from ASCII to binary. All characters are considered
|
| 389 |
+
# a '1' except space, period and '0' which maps to '0'.
|
| 390 |
+
binaryConv = {" ": "0", ".": "0", "0": "0"}
|
| 391 |
+
|
| 392 |
+
dataRows = []
|
| 393 |
+
for element in content:
|
| 394 |
+
if not isinstance(element, tuple):
|
| 395 |
+
continue
|
| 396 |
+
name, attr, content = element
|
| 397 |
+
if name == "row":
|
| 398 |
+
mapParams = zip(attr["value"], itertools.repeat("1"))
|
| 399 |
+
rowData = strjoin(itertools.starmap(binaryConv.get, mapParams))
|
| 400 |
+
dataRows.append(_binary2data(rowData))
|
| 401 |
+
|
| 402 |
+
bitmapObject.setRows(
|
| 403 |
+
dataRows, bitDepth=bitDepth, metrics=metrics, reverseBytes=True
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def _extFileName(glyphName):
|
| 408 |
+
# Glyph names come straight from the font and may contain path separators
|
| 409 |
+
# (e.g. a crafted 'post' table), which would let the exported bitmap escape
|
| 410 |
+
# the output folder. Names that are usable as a filename verbatim -- i.e.
|
| 411 |
+
# every real glyph name -- are returned unchanged, so existing exports keep
|
| 412 |
+
# their filenames; the rest are percent-encoded and marked with a leading
|
| 413 |
+
# '%'. The mapping has to be injective, or two glyphs quietly share one
|
| 414 |
+
# file and the second overwrites the first: a plain name is never encoded
|
| 415 |
+
# and never contains '%', an encoded one always starts with '%', and
|
| 416 |
+
# percent-encoding is itself reversible, so no two names can meet.
|
| 417 |
+
if glyphName not in ("", ".", "..") and not _UNSAFE_IN_FILENAME.search(glyphName):
|
| 418 |
+
return glyphName
|
| 419 |
+
return "%" + quote(glyphName, safe="", encoding="utf-8", errors="surrogatepass")
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def _writeExtFileImageData(strikeIndex, glyphName, bitmapObject, writer, ttFont):
|
| 423 |
+
try:
|
| 424 |
+
folder = os.path.dirname(writer.file.name)
|
| 425 |
+
except AttributeError:
|
| 426 |
+
# fall back to current directory if output file's directory isn't found
|
| 427 |
+
folder = "."
|
| 428 |
+
folder = os.path.join(folder, "bitmaps")
|
| 429 |
+
filename = _extFileName(glyphName) + bitmapObject.fileExtension
|
| 430 |
+
if not os.path.isdir(folder):
|
| 431 |
+
os.makedirs(folder)
|
| 432 |
+
folder = os.path.join(folder, "strike%d" % strikeIndex)
|
| 433 |
+
if not os.path.isdir(folder):
|
| 434 |
+
os.makedirs(folder)
|
| 435 |
+
|
| 436 |
+
fullPath = os.path.join(folder, filename)
|
| 437 |
+
writer.simpletag("extfileimagedata", value=fullPath)
|
| 438 |
+
writer.newline()
|
| 439 |
+
|
| 440 |
+
with open(fullPath, "wb") as file:
|
| 441 |
+
file.write(bitmapObject.imageData)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def _readExtFileImageData(bitmapObject, name, attrs, content, ttFont):
|
| 445 |
+
fullPath = attrs["value"]
|
| 446 |
+
with open(fullPath, "rb") as file:
|
| 447 |
+
bitmapObject.imageData = file.read()
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
# End of XML writing code.
|
| 451 |
+
|
| 452 |
+
# Important information about the naming scheme. Used for identifying formats
|
| 453 |
+
# in XML.
|
| 454 |
+
_bitmapGlyphSubclassPrefix = "ebdt_bitmap_format_"
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
class BitmapGlyph(object):
|
| 458 |
+
# For the external file format. This can be changed in subclasses. This way
|
| 459 |
+
# when the extfile option is turned on files have the form: glyphName.ext
|
| 460 |
+
# The default is just a flat binary file with no meaning.
|
| 461 |
+
fileExtension = ".bin"
|
| 462 |
+
|
| 463 |
+
# Keep track of reading and writing of various forms.
|
| 464 |
+
xmlDataFunctions = {
|
| 465 |
+
"raw": (_writeRawImageData, _readRawImageData),
|
| 466 |
+
"row": (_writeRowImageData, _readRowImageData),
|
| 467 |
+
"bitwise": (_writeBitwiseImageData, _readBitwiseImageData),
|
| 468 |
+
"extfile": (_writeExtFileImageData, _readExtFileImageData),
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
def __init__(self, data, ttFont):
|
| 472 |
+
self.data = data
|
| 473 |
+
self.ttFont = ttFont
|
| 474 |
+
# TODO Currently non-lazy decompilation is untested here...
|
| 475 |
+
# if not ttFont.lazy:
|
| 476 |
+
# self.decompile()
|
| 477 |
+
# del self.data
|
| 478 |
+
|
| 479 |
+
def __getattr__(self, attr):
|
| 480 |
+
# Allow lazy decompile.
|
| 481 |
+
if attr[:2] == "__":
|
| 482 |
+
raise AttributeError(attr)
|
| 483 |
+
if attr == "data":
|
| 484 |
+
raise AttributeError(attr)
|
| 485 |
+
self.decompile()
|
| 486 |
+
del self.data
|
| 487 |
+
return getattr(self, attr)
|
| 488 |
+
|
| 489 |
+
def ensureDecompiled(self, recurse=False):
|
| 490 |
+
if hasattr(self, "data"):
|
| 491 |
+
self.decompile()
|
| 492 |
+
del self.data
|
| 493 |
+
|
| 494 |
+
# Not a fan of this but it is needed for safer safety checking.
|
| 495 |
+
def getFormat(self):
|
| 496 |
+
return safeEval(self.__class__.__name__[len(_bitmapGlyphSubclassPrefix) :])
|
| 497 |
+
|
| 498 |
+
def toXML(self, strikeIndex, glyphName, writer, ttFont):
|
| 499 |
+
writer.begintag(self.__class__.__name__, [("name", glyphName)])
|
| 500 |
+
writer.newline()
|
| 501 |
+
|
| 502 |
+
self.writeMetrics(writer, ttFont)
|
| 503 |
+
# Use the internal write method to write using the correct output format.
|
| 504 |
+
self.writeData(strikeIndex, glyphName, writer, ttFont)
|
| 505 |
+
|
| 506 |
+
writer.endtag(self.__class__.__name__)
|
| 507 |
+
writer.newline()
|
| 508 |
+
|
| 509 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 510 |
+
self.readMetrics(name, attrs, content, ttFont)
|
| 511 |
+
for element in content:
|
| 512 |
+
if not isinstance(element, tuple):
|
| 513 |
+
continue
|
| 514 |
+
name, attr, content = element
|
| 515 |
+
if not name.endswith("imagedata"):
|
| 516 |
+
continue
|
| 517 |
+
# Chop off 'imagedata' from the tag to get just the option.
|
| 518 |
+
option = name[: -len("imagedata")]
|
| 519 |
+
assert option in self.__class__.xmlDataFunctions
|
| 520 |
+
self.readData(name, attr, content, ttFont)
|
| 521 |
+
|
| 522 |
+
# Some of the glyphs have the metrics. This allows for metrics to be
|
| 523 |
+
# added if the glyph format has them. Default behavior is to do nothing.
|
| 524 |
+
def writeMetrics(self, writer, ttFont):
|
| 525 |
+
pass
|
| 526 |
+
|
| 527 |
+
# The opposite of write metrics.
|
| 528 |
+
def readMetrics(self, name, attrs, content, ttFont):
|
| 529 |
+
pass
|
| 530 |
+
|
| 531 |
+
def writeData(self, strikeIndex, glyphName, writer, ttFont):
|
| 532 |
+
try:
|
| 533 |
+
writeFunc, readFunc = self.__class__.xmlDataFunctions[
|
| 534 |
+
ttFont.bitmapGlyphDataFormat
|
| 535 |
+
]
|
| 536 |
+
except KeyError:
|
| 537 |
+
writeFunc = _writeRawImageData
|
| 538 |
+
writeFunc(strikeIndex, glyphName, self, writer, ttFont)
|
| 539 |
+
|
| 540 |
+
def readData(self, name, attrs, content, ttFont):
|
| 541 |
+
# Chop off 'imagedata' from the tag to get just the option.
|
| 542 |
+
option = name[: -len("imagedata")]
|
| 543 |
+
writeFunc, readFunc = self.__class__.xmlDataFunctions[option]
|
| 544 |
+
readFunc(self, name, attrs, content, ttFont)
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
# A closure for creating a mixin for the two types of metrics handling.
|
| 548 |
+
# Most of the code is very similar so its easier to deal with here.
|
| 549 |
+
# Everything works just by passing the class that the mixin is for.
|
| 550 |
+
def _createBitmapPlusMetricsMixin(metricsClass):
|
| 551 |
+
# Both metrics names are listed here to make meaningful error messages.
|
| 552 |
+
metricStrings = [BigGlyphMetrics.__name__, SmallGlyphMetrics.__name__]
|
| 553 |
+
curMetricsName = metricsClass.__name__
|
| 554 |
+
# Find which metrics this is for and determine the opposite name.
|
| 555 |
+
metricsId = metricStrings.index(curMetricsName)
|
| 556 |
+
oppositeMetricsName = metricStrings[1 - metricsId]
|
| 557 |
+
|
| 558 |
+
class BitmapPlusMetricsMixin(object):
|
| 559 |
+
def writeMetrics(self, writer, ttFont):
|
| 560 |
+
self.metrics.toXML(writer, ttFont)
|
| 561 |
+
|
| 562 |
+
def readMetrics(self, name, attrs, content, ttFont):
|
| 563 |
+
for element in content:
|
| 564 |
+
if not isinstance(element, tuple):
|
| 565 |
+
continue
|
| 566 |
+
name, attrs, content = element
|
| 567 |
+
if name == curMetricsName:
|
| 568 |
+
self.metrics = metricsClass()
|
| 569 |
+
self.metrics.fromXML(name, attrs, content, ttFont)
|
| 570 |
+
elif name == oppositeMetricsName:
|
| 571 |
+
log.warning(
|
| 572 |
+
"Warning: %s being ignored in format %d.",
|
| 573 |
+
oppositeMetricsName,
|
| 574 |
+
self.getFormat(),
|
| 575 |
+
)
|
| 576 |
+
|
| 577 |
+
return BitmapPlusMetricsMixin
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
# Since there are only two types of mixin's just create them here.
|
| 581 |
+
BitmapPlusBigMetricsMixin = _createBitmapPlusMetricsMixin(BigGlyphMetrics)
|
| 582 |
+
BitmapPlusSmallMetricsMixin = _createBitmapPlusMetricsMixin(SmallGlyphMetrics)
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
# Data that is bit aligned can be tricky to deal with. These classes implement
|
| 586 |
+
# helper functionality for dealing with the data and getting a particular row
|
| 587 |
+
# of bitwise data. Also helps implement fancy data export/import in XML.
|
| 588 |
+
class BitAlignedBitmapMixin(object):
|
| 589 |
+
def _getBitRange(self, row, bitDepth, metrics):
|
| 590 |
+
rowBits = bitDepth * metrics.width
|
| 591 |
+
bitOffset = row * rowBits
|
| 592 |
+
return (bitOffset, bitOffset + rowBits)
|
| 593 |
+
|
| 594 |
+
def getRow(self, row, bitDepth=1, metrics=None, reverseBytes=False):
|
| 595 |
+
if metrics is None:
|
| 596 |
+
metrics = self.metrics
|
| 597 |
+
assert 0 <= row and row < metrics.height, "Illegal row access in bitmap"
|
| 598 |
+
|
| 599 |
+
# Loop through each byte. This can cover two bytes in the original data or
|
| 600 |
+
# a single byte if things happen to be aligned. The very last entry might
|
| 601 |
+
# not be aligned so take care to trim the binary data to size and pad with
|
| 602 |
+
# zeros in the row data. Bit aligned data is somewhat tricky.
|
| 603 |
+
#
|
| 604 |
+
# Example of data cut. Data cut represented in x's.
|
| 605 |
+
# '|' represents byte boundary.
|
| 606 |
+
# data = ...0XX|XXXXXX00|000... => XXXXXXXX
|
| 607 |
+
# or
|
| 608 |
+
# data = ...0XX|XXXX0000|000... => XXXXXX00
|
| 609 |
+
# or
|
| 610 |
+
# data = ...000|XXXXXXXX|000... => XXXXXXXX
|
| 611 |
+
# or
|
| 612 |
+
# data = ...000|00XXXX00|000... => XXXX0000
|
| 613 |
+
#
|
| 614 |
+
dataList = []
|
| 615 |
+
bitRange = self._getBitRange(row, bitDepth, metrics)
|
| 616 |
+
stepRange = bitRange + (8,)
|
| 617 |
+
for curBit in range(*stepRange):
|
| 618 |
+
endBit = min(curBit + 8, bitRange[1])
|
| 619 |
+
numBits = endBit - curBit
|
| 620 |
+
cutPoint = curBit % 8
|
| 621 |
+
firstByteLoc = curBit // 8
|
| 622 |
+
secondByteLoc = endBit // 8
|
| 623 |
+
if firstByteLoc < secondByteLoc:
|
| 624 |
+
numBitsCut = 8 - cutPoint
|
| 625 |
+
else:
|
| 626 |
+
numBitsCut = endBit - curBit
|
| 627 |
+
curByte = _reverseBytes(self.imageData[firstByteLoc])
|
| 628 |
+
firstHalf = byteord(curByte) >> cutPoint
|
| 629 |
+
firstHalf = ((1 << numBitsCut) - 1) & firstHalf
|
| 630 |
+
newByte = firstHalf
|
| 631 |
+
if firstByteLoc < secondByteLoc and secondByteLoc < len(self.imageData):
|
| 632 |
+
curByte = _reverseBytes(self.imageData[secondByteLoc])
|
| 633 |
+
secondHalf = byteord(curByte) << numBitsCut
|
| 634 |
+
newByte = (firstHalf | secondHalf) & ((1 << numBits) - 1)
|
| 635 |
+
dataList.append(bytechr(newByte))
|
| 636 |
+
|
| 637 |
+
# The way the data is kept is opposite the algorithm used.
|
| 638 |
+
data = bytesjoin(dataList)
|
| 639 |
+
if not reverseBytes:
|
| 640 |
+
data = _reverseBytes(data)
|
| 641 |
+
return data
|
| 642 |
+
|
| 643 |
+
def setRows(self, dataRows, bitDepth=1, metrics=None, reverseBytes=False):
|
| 644 |
+
if metrics is None:
|
| 645 |
+
metrics = self.metrics
|
| 646 |
+
if not reverseBytes:
|
| 647 |
+
dataRows = list(map(_reverseBytes, dataRows))
|
| 648 |
+
|
| 649 |
+
# Keep track of a list of ordinal values as they are easier to modify
|
| 650 |
+
# than a list of strings. Map to actual strings later.
|
| 651 |
+
numBytes = (self._getBitRange(len(dataRows), bitDepth, metrics)[0] + 7) // 8
|
| 652 |
+
ordDataList = [0] * numBytes
|
| 653 |
+
for row, data in enumerate(dataRows):
|
| 654 |
+
bitRange = self._getBitRange(row, bitDepth, metrics)
|
| 655 |
+
stepRange = bitRange + (8,)
|
| 656 |
+
for curBit, curByte in zip(range(*stepRange), data):
|
| 657 |
+
endBit = min(curBit + 8, bitRange[1])
|
| 658 |
+
cutPoint = curBit % 8
|
| 659 |
+
firstByteLoc = curBit // 8
|
| 660 |
+
secondByteLoc = endBit // 8
|
| 661 |
+
if firstByteLoc < secondByteLoc:
|
| 662 |
+
numBitsCut = 8 - cutPoint
|
| 663 |
+
else:
|
| 664 |
+
numBitsCut = endBit - curBit
|
| 665 |
+
curByte = byteord(curByte)
|
| 666 |
+
firstByte = curByte & ((1 << numBitsCut) - 1)
|
| 667 |
+
ordDataList[firstByteLoc] |= firstByte << cutPoint
|
| 668 |
+
if firstByteLoc < secondByteLoc and secondByteLoc < numBytes:
|
| 669 |
+
secondByte = (curByte >> numBitsCut) & ((1 << 8 - numBitsCut) - 1)
|
| 670 |
+
ordDataList[secondByteLoc] |= secondByte
|
| 671 |
+
|
| 672 |
+
# Save the image data with the bits going the correct way.
|
| 673 |
+
self.imageData = _reverseBytes(bytesjoin(map(bytechr, ordDataList)))
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
class ByteAlignedBitmapMixin(object):
|
| 677 |
+
def _getByteRange(self, row, bitDepth, metrics):
|
| 678 |
+
rowBytes = (bitDepth * metrics.width + 7) // 8
|
| 679 |
+
byteOffset = row * rowBytes
|
| 680 |
+
return (byteOffset, byteOffset + rowBytes)
|
| 681 |
+
|
| 682 |
+
def getRow(self, row, bitDepth=1, metrics=None, reverseBytes=False):
|
| 683 |
+
if metrics is None:
|
| 684 |
+
metrics = self.metrics
|
| 685 |
+
assert 0 <= row and row < metrics.height, "Illegal row access in bitmap"
|
| 686 |
+
byteRange = self._getByteRange(row, bitDepth, metrics)
|
| 687 |
+
data = self.imageData[slice(*byteRange)]
|
| 688 |
+
if reverseBytes:
|
| 689 |
+
data = _reverseBytes(data)
|
| 690 |
+
return data
|
| 691 |
+
|
| 692 |
+
def setRows(self, dataRows, bitDepth=1, metrics=None, reverseBytes=False):
|
| 693 |
+
if metrics is None:
|
| 694 |
+
metrics = self.metrics
|
| 695 |
+
if reverseBytes:
|
| 696 |
+
dataRows = map(_reverseBytes, dataRows)
|
| 697 |
+
self.imageData = bytesjoin(dataRows)
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
class ebdt_bitmap_format_1(
|
| 701 |
+
ByteAlignedBitmapMixin, BitmapPlusSmallMetricsMixin, BitmapGlyph
|
| 702 |
+
):
|
| 703 |
+
def decompile(self):
|
| 704 |
+
self.metrics = SmallGlyphMetrics()
|
| 705 |
+
dummy, data = sstruct.unpack2(smallGlyphMetricsFormat, self.data, self.metrics)
|
| 706 |
+
self.imageData = data
|
| 707 |
+
|
| 708 |
+
def compile(self, ttFont):
|
| 709 |
+
data = sstruct.pack(smallGlyphMetricsFormat, self.metrics)
|
| 710 |
+
return data + self.imageData
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
class ebdt_bitmap_format_2(
|
| 714 |
+
BitAlignedBitmapMixin, BitmapPlusSmallMetricsMixin, BitmapGlyph
|
| 715 |
+
):
|
| 716 |
+
def decompile(self):
|
| 717 |
+
self.metrics = SmallGlyphMetrics()
|
| 718 |
+
dummy, data = sstruct.unpack2(smallGlyphMetricsFormat, self.data, self.metrics)
|
| 719 |
+
self.imageData = data
|
| 720 |
+
|
| 721 |
+
def compile(self, ttFont):
|
| 722 |
+
data = sstruct.pack(smallGlyphMetricsFormat, self.metrics)
|
| 723 |
+
return data + self.imageData
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
class ebdt_bitmap_format_5(BitAlignedBitmapMixin, BitmapGlyph):
|
| 727 |
+
def decompile(self):
|
| 728 |
+
self.imageData = self.data
|
| 729 |
+
|
| 730 |
+
def compile(self, ttFont):
|
| 731 |
+
return self.imageData
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
class ebdt_bitmap_format_6(
|
| 735 |
+
ByteAlignedBitmapMixin, BitmapPlusBigMetricsMixin, BitmapGlyph
|
| 736 |
+
):
|
| 737 |
+
def decompile(self):
|
| 738 |
+
self.metrics = BigGlyphMetrics()
|
| 739 |
+
dummy, data = sstruct.unpack2(bigGlyphMetricsFormat, self.data, self.metrics)
|
| 740 |
+
self.imageData = data
|
| 741 |
+
|
| 742 |
+
def compile(self, ttFont):
|
| 743 |
+
data = sstruct.pack(bigGlyphMetricsFormat, self.metrics)
|
| 744 |
+
return data + self.imageData
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
class ebdt_bitmap_format_7(
|
| 748 |
+
BitAlignedBitmapMixin, BitmapPlusBigMetricsMixin, BitmapGlyph
|
| 749 |
+
):
|
| 750 |
+
def decompile(self):
|
| 751 |
+
self.metrics = BigGlyphMetrics()
|
| 752 |
+
dummy, data = sstruct.unpack2(bigGlyphMetricsFormat, self.data, self.metrics)
|
| 753 |
+
self.imageData = data
|
| 754 |
+
|
| 755 |
+
def compile(self, ttFont):
|
| 756 |
+
data = sstruct.pack(bigGlyphMetricsFormat, self.metrics)
|
| 757 |
+
return data + self.imageData
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
class ComponentBitmapGlyph(BitmapGlyph):
|
| 761 |
+
def toXML(self, strikeIndex, glyphName, writer, ttFont):
|
| 762 |
+
writer.begintag(self.__class__.__name__, [("name", glyphName)])
|
| 763 |
+
writer.newline()
|
| 764 |
+
|
| 765 |
+
self.writeMetrics(writer, ttFont)
|
| 766 |
+
|
| 767 |
+
writer.begintag("components")
|
| 768 |
+
writer.newline()
|
| 769 |
+
for curComponent in self.componentArray:
|
| 770 |
+
curComponent.toXML(writer, ttFont)
|
| 771 |
+
writer.endtag("components")
|
| 772 |
+
writer.newline()
|
| 773 |
+
|
| 774 |
+
writer.endtag(self.__class__.__name__)
|
| 775 |
+
writer.newline()
|
| 776 |
+
|
| 777 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 778 |
+
self.readMetrics(name, attrs, content, ttFont)
|
| 779 |
+
for element in content:
|
| 780 |
+
if not isinstance(element, tuple):
|
| 781 |
+
continue
|
| 782 |
+
name, attr, content = element
|
| 783 |
+
if name == "components":
|
| 784 |
+
self.componentArray = []
|
| 785 |
+
for compElement in content:
|
| 786 |
+
if not isinstance(compElement, tuple):
|
| 787 |
+
continue
|
| 788 |
+
name, attrs, content = compElement
|
| 789 |
+
if name == "ebdtComponent":
|
| 790 |
+
curComponent = EbdtComponent()
|
| 791 |
+
curComponent.fromXML(name, attrs, content, ttFont)
|
| 792 |
+
self.componentArray.append(curComponent)
|
| 793 |
+
else:
|
| 794 |
+
log.warning("'%s' being ignored in component array.", name)
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
class ebdt_bitmap_format_8(BitmapPlusSmallMetricsMixin, ComponentBitmapGlyph):
|
| 798 |
+
def decompile(self):
|
| 799 |
+
self.metrics = SmallGlyphMetrics()
|
| 800 |
+
dummy, data = sstruct.unpack2(smallGlyphMetricsFormat, self.data, self.metrics)
|
| 801 |
+
data = data[1:]
|
| 802 |
+
|
| 803 |
+
(numComponents,) = struct.unpack(">H", data[:2])
|
| 804 |
+
data = data[2:]
|
| 805 |
+
self.componentArray = []
|
| 806 |
+
for i in range(numComponents):
|
| 807 |
+
curComponent = EbdtComponent()
|
| 808 |
+
dummy, data = sstruct.unpack2(ebdtComponentFormat, data, curComponent)
|
| 809 |
+
curComponent.name = self.ttFont.getGlyphName(curComponent.glyphCode)
|
| 810 |
+
self.componentArray.append(curComponent)
|
| 811 |
+
|
| 812 |
+
def compile(self, ttFont):
|
| 813 |
+
dataList = []
|
| 814 |
+
dataList.append(sstruct.pack(smallGlyphMetricsFormat, self.metrics))
|
| 815 |
+
dataList.append(b"\0")
|
| 816 |
+
dataList.append(struct.pack(">H", len(self.componentArray)))
|
| 817 |
+
for curComponent in self.componentArray:
|
| 818 |
+
curComponent.glyphCode = ttFont.getGlyphID(curComponent.name)
|
| 819 |
+
dataList.append(sstruct.pack(ebdtComponentFormat, curComponent))
|
| 820 |
+
return bytesjoin(dataList)
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
class ebdt_bitmap_format_9(BitmapPlusBigMetricsMixin, ComponentBitmapGlyph):
|
| 824 |
+
def decompile(self):
|
| 825 |
+
self.metrics = BigGlyphMetrics()
|
| 826 |
+
dummy, data = sstruct.unpack2(bigGlyphMetricsFormat, self.data, self.metrics)
|
| 827 |
+
(numComponents,) = struct.unpack(">H", data[:2])
|
| 828 |
+
data = data[2:]
|
| 829 |
+
self.componentArray = []
|
| 830 |
+
for i in range(numComponents):
|
| 831 |
+
curComponent = EbdtComponent()
|
| 832 |
+
dummy, data = sstruct.unpack2(ebdtComponentFormat, data, curComponent)
|
| 833 |
+
curComponent.name = self.ttFont.getGlyphName(curComponent.glyphCode)
|
| 834 |
+
self.componentArray.append(curComponent)
|
| 835 |
+
|
| 836 |
+
def compile(self, ttFont):
|
| 837 |
+
dataList = []
|
| 838 |
+
dataList.append(sstruct.pack(bigGlyphMetricsFormat, self.metrics))
|
| 839 |
+
dataList.append(struct.pack(">H", len(self.componentArray)))
|
| 840 |
+
for curComponent in self.componentArray:
|
| 841 |
+
curComponent.glyphCode = ttFont.getGlyphID(curComponent.name)
|
| 842 |
+
dataList.append(sstruct.pack(ebdtComponentFormat, curComponent))
|
| 843 |
+
return bytesjoin(dataList)
|
| 844 |
+
|
| 845 |
+
|
| 846 |
+
# Dictionary of bitmap formats to the class representing that format
|
| 847 |
+
# currently only the ones listed in this map are the ones supported.
|
| 848 |
+
ebdt_bitmap_classes = {
|
| 849 |
+
1: ebdt_bitmap_format_1,
|
| 850 |
+
2: ebdt_bitmap_format_2,
|
| 851 |
+
5: ebdt_bitmap_format_5,
|
| 852 |
+
6: ebdt_bitmap_format_6,
|
| 853 |
+
7: ebdt_bitmap_format_7,
|
| 854 |
+
8: ebdt_bitmap_format_8,
|
| 855 |
+
9: ebdt_bitmap_format_9,
|
| 856 |
+
}
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/E_B_L_C_.py
ADDED
|
@@ -0,0 +1,717 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.misc import sstruct
|
| 2 |
+
from . import DefaultTable
|
| 3 |
+
from fontTools.misc.textTools import bytesjoin, safeEval
|
| 4 |
+
from .BitmapGlyphMetrics import (
|
| 5 |
+
BigGlyphMetrics,
|
| 6 |
+
bigGlyphMetricsFormat,
|
| 7 |
+
SmallGlyphMetrics,
|
| 8 |
+
smallGlyphMetricsFormat,
|
| 9 |
+
)
|
| 10 |
+
import struct
|
| 11 |
+
import itertools
|
| 12 |
+
from collections import deque
|
| 13 |
+
import logging
|
| 14 |
+
|
| 15 |
+
log = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
eblcHeaderFormat = """
|
| 18 |
+
> # big endian
|
| 19 |
+
version: 16.16F
|
| 20 |
+
numSizes: I
|
| 21 |
+
"""
|
| 22 |
+
# The table format string is split to handle sbitLineMetrics simply.
|
| 23 |
+
bitmapSizeTableFormatPart1 = """
|
| 24 |
+
> # big endian
|
| 25 |
+
indexSubTableArrayOffset: I
|
| 26 |
+
indexTablesSize: I
|
| 27 |
+
numberOfIndexSubTables: I
|
| 28 |
+
colorRef: I
|
| 29 |
+
"""
|
| 30 |
+
# The compound type for hori and vert.
|
| 31 |
+
sbitLineMetricsFormat = """
|
| 32 |
+
> # big endian
|
| 33 |
+
ascender: b
|
| 34 |
+
descender: b
|
| 35 |
+
widthMax: B
|
| 36 |
+
caretSlopeNumerator: b
|
| 37 |
+
caretSlopeDenominator: b
|
| 38 |
+
caretOffset: b
|
| 39 |
+
minOriginSB: b
|
| 40 |
+
minAdvanceSB: b
|
| 41 |
+
maxBeforeBL: b
|
| 42 |
+
minAfterBL: b
|
| 43 |
+
pad1: b
|
| 44 |
+
pad2: b
|
| 45 |
+
"""
|
| 46 |
+
# hori and vert go between the two parts.
|
| 47 |
+
bitmapSizeTableFormatPart2 = """
|
| 48 |
+
> # big endian
|
| 49 |
+
startGlyphIndex: H
|
| 50 |
+
endGlyphIndex: H
|
| 51 |
+
ppemX: B
|
| 52 |
+
ppemY: B
|
| 53 |
+
bitDepth: B
|
| 54 |
+
flags: b
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
indexSubTableArrayFormat = ">HHL"
|
| 58 |
+
indexSubTableArraySize = struct.calcsize(indexSubTableArrayFormat)
|
| 59 |
+
|
| 60 |
+
indexSubHeaderFormat = ">HHL"
|
| 61 |
+
indexSubHeaderSize = struct.calcsize(indexSubHeaderFormat)
|
| 62 |
+
|
| 63 |
+
codeOffsetPairFormat = ">HH"
|
| 64 |
+
codeOffsetPairSize = struct.calcsize(codeOffsetPairFormat)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class table_E_B_L_C_(DefaultTable.DefaultTable):
|
| 68 |
+
"""Embedded Bitmap Location table
|
| 69 |
+
|
| 70 |
+
The ``EBLC`` table contains the locations of monochrome or grayscale
|
| 71 |
+
bitmaps for glyphs. It must be used in concert with the ``EBDT`` table.
|
| 72 |
+
|
| 73 |
+
See also https://learn.microsoft.com/en-us/typography/opentype/spec/eblc
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
dependencies = ["EBDT"]
|
| 77 |
+
|
| 78 |
+
# This method can be overridden in subclasses to support new formats
|
| 79 |
+
# without changing the other implementation. Also can be used as a
|
| 80 |
+
# convenience method for coverting a font file to an alternative format.
|
| 81 |
+
def getIndexFormatClass(self, indexFormat):
|
| 82 |
+
return eblc_sub_table_classes[indexFormat]
|
| 83 |
+
|
| 84 |
+
def decompile(self, data, ttFont):
|
| 85 |
+
# Save the original data because offsets are from the start of the table.
|
| 86 |
+
origData = data
|
| 87 |
+
i = 0
|
| 88 |
+
|
| 89 |
+
dummy = sstruct.unpack(eblcHeaderFormat, data[:8], self)
|
| 90 |
+
i += 8
|
| 91 |
+
|
| 92 |
+
self.strikes = []
|
| 93 |
+
for curStrikeIndex in range(self.numSizes):
|
| 94 |
+
curStrike = Strike()
|
| 95 |
+
self.strikes.append(curStrike)
|
| 96 |
+
curTable = curStrike.bitmapSizeTable
|
| 97 |
+
dummy = sstruct.unpack2(
|
| 98 |
+
bitmapSizeTableFormatPart1, data[i : i + 16], curTable
|
| 99 |
+
)
|
| 100 |
+
i += 16
|
| 101 |
+
for metric in ("hori", "vert"):
|
| 102 |
+
metricObj = SbitLineMetrics()
|
| 103 |
+
vars(curTable)[metric] = metricObj
|
| 104 |
+
dummy = sstruct.unpack2(
|
| 105 |
+
sbitLineMetricsFormat, data[i : i + 12], metricObj
|
| 106 |
+
)
|
| 107 |
+
i += 12
|
| 108 |
+
dummy = sstruct.unpack(
|
| 109 |
+
bitmapSizeTableFormatPart2, data[i : i + 8], curTable
|
| 110 |
+
)
|
| 111 |
+
i += 8
|
| 112 |
+
|
| 113 |
+
for curStrike in self.strikes:
|
| 114 |
+
curTable = curStrike.bitmapSizeTable
|
| 115 |
+
for subtableIndex in range(curTable.numberOfIndexSubTables):
|
| 116 |
+
i = (
|
| 117 |
+
curTable.indexSubTableArrayOffset
|
| 118 |
+
+ subtableIndex * indexSubTableArraySize
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
tup = struct.unpack(
|
| 122 |
+
indexSubTableArrayFormat, data[i : i + indexSubTableArraySize]
|
| 123 |
+
)
|
| 124 |
+
firstGlyphIndex, lastGlyphIndex, additionalOffsetToIndexSubtable = tup
|
| 125 |
+
i = curTable.indexSubTableArrayOffset + additionalOffsetToIndexSubtable
|
| 126 |
+
|
| 127 |
+
tup = struct.unpack(
|
| 128 |
+
indexSubHeaderFormat, data[i : i + indexSubHeaderSize]
|
| 129 |
+
)
|
| 130 |
+
indexFormat, imageFormat, imageDataOffset = tup
|
| 131 |
+
|
| 132 |
+
indexFormatClass = self.getIndexFormatClass(indexFormat)
|
| 133 |
+
indexSubTable = indexFormatClass(data[i + indexSubHeaderSize :], ttFont)
|
| 134 |
+
indexSubTable.firstGlyphIndex = firstGlyphIndex
|
| 135 |
+
indexSubTable.lastGlyphIndex = lastGlyphIndex
|
| 136 |
+
indexSubTable.additionalOffsetToIndexSubtable = (
|
| 137 |
+
additionalOffsetToIndexSubtable
|
| 138 |
+
)
|
| 139 |
+
indexSubTable.indexFormat = indexFormat
|
| 140 |
+
indexSubTable.imageFormat = imageFormat
|
| 141 |
+
indexSubTable.imageDataOffset = imageDataOffset
|
| 142 |
+
indexSubTable.decompile() # https://github.com/fonttools/fonttools/issues/317
|
| 143 |
+
curStrike.indexSubTables.append(indexSubTable)
|
| 144 |
+
|
| 145 |
+
def compile(self, ttFont):
|
| 146 |
+
dataList = []
|
| 147 |
+
self.numSizes = len(self.strikes)
|
| 148 |
+
dataList.append(sstruct.pack(eblcHeaderFormat, self))
|
| 149 |
+
|
| 150 |
+
# Data size of the header + bitmapSizeTable needs to be calculated
|
| 151 |
+
# in order to form offsets. This value will hold the size of the data
|
| 152 |
+
# in dataList after all the data is consolidated in dataList.
|
| 153 |
+
dataSize = len(dataList[0])
|
| 154 |
+
|
| 155 |
+
# The table will be structured in the following order:
|
| 156 |
+
# (0) header
|
| 157 |
+
# (1) Each bitmapSizeTable [1 ... self.numSizes]
|
| 158 |
+
# (2) Alternate between indexSubTableArray and indexSubTable
|
| 159 |
+
# for each bitmapSizeTable present.
|
| 160 |
+
#
|
| 161 |
+
# The issue is maintaining the proper offsets when table information
|
| 162 |
+
# gets moved around. All offsets and size information must be recalculated
|
| 163 |
+
# when building the table to allow editing within ttLib and also allow easy
|
| 164 |
+
# import/export to and from XML. All of this offset information is lost
|
| 165 |
+
# when exporting to XML so everything must be calculated fresh so importing
|
| 166 |
+
# from XML will work cleanly. Only byte offset and size information is
|
| 167 |
+
# calculated fresh. Count information like numberOfIndexSubTables is
|
| 168 |
+
# checked through assertions. If the information in this table was not
|
| 169 |
+
# touched or was changed properly then these types of values should match.
|
| 170 |
+
#
|
| 171 |
+
# The table will be rebuilt the following way:
|
| 172 |
+
# (0) Precompute the size of all the bitmapSizeTables. This is needed to
|
| 173 |
+
# compute the offsets properly.
|
| 174 |
+
# (1) For each bitmapSizeTable compute the indexSubTable and
|
| 175 |
+
# indexSubTableArray pair. The indexSubTable must be computed first
|
| 176 |
+
# so that the offset information in indexSubTableArray can be
|
| 177 |
+
# calculated. Update the data size after each pairing.
|
| 178 |
+
# (2) Build each bitmapSizeTable.
|
| 179 |
+
# (3) Consolidate all the data into the main dataList in the correct order.
|
| 180 |
+
|
| 181 |
+
for _ in self.strikes:
|
| 182 |
+
dataSize += sstruct.calcsize(bitmapSizeTableFormatPart1)
|
| 183 |
+
dataSize += len(("hori", "vert")) * sstruct.calcsize(sbitLineMetricsFormat)
|
| 184 |
+
dataSize += sstruct.calcsize(bitmapSizeTableFormatPart2)
|
| 185 |
+
|
| 186 |
+
indexSubTablePairDataList = []
|
| 187 |
+
for curStrike in self.strikes:
|
| 188 |
+
curTable = curStrike.bitmapSizeTable
|
| 189 |
+
curTable.numberOfIndexSubTables = len(curStrike.indexSubTables)
|
| 190 |
+
curTable.indexSubTableArrayOffset = dataSize
|
| 191 |
+
|
| 192 |
+
# Precompute the size of the indexSubTableArray. This information
|
| 193 |
+
# is important for correctly calculating the new value for
|
| 194 |
+
# additionalOffsetToIndexSubtable.
|
| 195 |
+
sizeOfSubTableArray = (
|
| 196 |
+
curTable.numberOfIndexSubTables * indexSubTableArraySize
|
| 197 |
+
)
|
| 198 |
+
lowerBound = dataSize
|
| 199 |
+
dataSize += sizeOfSubTableArray
|
| 200 |
+
upperBound = dataSize
|
| 201 |
+
|
| 202 |
+
indexSubTableDataList = []
|
| 203 |
+
for indexSubTable in curStrike.indexSubTables:
|
| 204 |
+
indexSubTable.additionalOffsetToIndexSubtable = (
|
| 205 |
+
dataSize - curTable.indexSubTableArrayOffset
|
| 206 |
+
)
|
| 207 |
+
glyphIds = list(map(ttFont.getGlyphID, indexSubTable.names))
|
| 208 |
+
indexSubTable.firstGlyphIndex = min(glyphIds)
|
| 209 |
+
indexSubTable.lastGlyphIndex = max(glyphIds)
|
| 210 |
+
data = indexSubTable.compile(ttFont)
|
| 211 |
+
indexSubTableDataList.append(data)
|
| 212 |
+
dataSize += len(data)
|
| 213 |
+
curTable.startGlyphIndex = min(
|
| 214 |
+
ist.firstGlyphIndex for ist in curStrike.indexSubTables
|
| 215 |
+
)
|
| 216 |
+
curTable.endGlyphIndex = max(
|
| 217 |
+
ist.lastGlyphIndex for ist in curStrike.indexSubTables
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
for i in curStrike.indexSubTables:
|
| 221 |
+
data = struct.pack(
|
| 222 |
+
indexSubHeaderFormat,
|
| 223 |
+
i.firstGlyphIndex,
|
| 224 |
+
i.lastGlyphIndex,
|
| 225 |
+
i.additionalOffsetToIndexSubtable,
|
| 226 |
+
)
|
| 227 |
+
indexSubTablePairDataList.append(data)
|
| 228 |
+
indexSubTablePairDataList.extend(indexSubTableDataList)
|
| 229 |
+
curTable.indexTablesSize = dataSize - curTable.indexSubTableArrayOffset
|
| 230 |
+
|
| 231 |
+
for curStrike in self.strikes:
|
| 232 |
+
curTable = curStrike.bitmapSizeTable
|
| 233 |
+
data = sstruct.pack(bitmapSizeTableFormatPart1, curTable)
|
| 234 |
+
dataList.append(data)
|
| 235 |
+
for metric in ("hori", "vert"):
|
| 236 |
+
metricObj = vars(curTable)[metric]
|
| 237 |
+
data = sstruct.pack(sbitLineMetricsFormat, metricObj)
|
| 238 |
+
dataList.append(data)
|
| 239 |
+
data = sstruct.pack(bitmapSizeTableFormatPart2, curTable)
|
| 240 |
+
dataList.append(data)
|
| 241 |
+
dataList.extend(indexSubTablePairDataList)
|
| 242 |
+
|
| 243 |
+
return bytesjoin(dataList)
|
| 244 |
+
|
| 245 |
+
def toXML(self, writer, ttFont):
|
| 246 |
+
writer.simpletag("header", [("version", self.version)])
|
| 247 |
+
writer.newline()
|
| 248 |
+
for curIndex, curStrike in enumerate(self.strikes):
|
| 249 |
+
curStrike.toXML(curIndex, writer, ttFont)
|
| 250 |
+
|
| 251 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 252 |
+
if name == "header":
|
| 253 |
+
self.version = safeEval(attrs["version"])
|
| 254 |
+
elif name == "strike":
|
| 255 |
+
if not hasattr(self, "strikes"):
|
| 256 |
+
self.strikes = []
|
| 257 |
+
strikeIndex = safeEval(attrs["index"])
|
| 258 |
+
curStrike = Strike()
|
| 259 |
+
curStrike.fromXML(name, attrs, content, ttFont, self)
|
| 260 |
+
|
| 261 |
+
# Grow the strike array to the appropriate size. The XML format
|
| 262 |
+
# allows for the strike index value to be out of order.
|
| 263 |
+
if strikeIndex >= len(self.strikes):
|
| 264 |
+
self.strikes += [None] * (strikeIndex + 1 - len(self.strikes))
|
| 265 |
+
assert self.strikes[strikeIndex] is None, "Duplicate strike EBLC indices."
|
| 266 |
+
self.strikes[strikeIndex] = curStrike
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class Strike(object):
|
| 270 |
+
def __init__(self):
|
| 271 |
+
self.bitmapSizeTable = BitmapSizeTable()
|
| 272 |
+
self.indexSubTables = []
|
| 273 |
+
|
| 274 |
+
def toXML(self, strikeIndex, writer, ttFont):
|
| 275 |
+
writer.begintag("strike", [("index", strikeIndex)])
|
| 276 |
+
writer.newline()
|
| 277 |
+
self.bitmapSizeTable.toXML(writer, ttFont)
|
| 278 |
+
writer.comment(
|
| 279 |
+
"GlyphIds are written but not read. The firstGlyphIndex and\nlastGlyphIndex values will be recalculated by the compiler."
|
| 280 |
+
)
|
| 281 |
+
writer.newline()
|
| 282 |
+
for indexSubTable in self.indexSubTables:
|
| 283 |
+
indexSubTable.toXML(writer, ttFont)
|
| 284 |
+
writer.endtag("strike")
|
| 285 |
+
writer.newline()
|
| 286 |
+
|
| 287 |
+
def fromXML(self, name, attrs, content, ttFont, locator):
|
| 288 |
+
for element in content:
|
| 289 |
+
if not isinstance(element, tuple):
|
| 290 |
+
continue
|
| 291 |
+
name, attrs, content = element
|
| 292 |
+
if name == "bitmapSizeTable":
|
| 293 |
+
self.bitmapSizeTable.fromXML(name, attrs, content, ttFont)
|
| 294 |
+
elif name.startswith(_indexSubTableSubclassPrefix):
|
| 295 |
+
indexFormat = safeEval(name[len(_indexSubTableSubclassPrefix) :])
|
| 296 |
+
indexFormatClass = locator.getIndexFormatClass(indexFormat)
|
| 297 |
+
indexSubTable = indexFormatClass(None, None)
|
| 298 |
+
indexSubTable.indexFormat = indexFormat
|
| 299 |
+
indexSubTable.fromXML(name, attrs, content, ttFont)
|
| 300 |
+
self.indexSubTables.append(indexSubTable)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class BitmapSizeTable(object):
|
| 304 |
+
# Returns all the simple metric names that bitmap size table
|
| 305 |
+
# cares about in terms of XML creation.
|
| 306 |
+
def _getXMLMetricNames(self):
|
| 307 |
+
dataNames = sstruct.getformat(bitmapSizeTableFormatPart1)[1]
|
| 308 |
+
dataNames = {**dataNames, **sstruct.getformat(bitmapSizeTableFormatPart2)[1]}
|
| 309 |
+
# Skip the first 3 data names because they are byte offsets and counts.
|
| 310 |
+
return list(dataNames.keys())[3:]
|
| 311 |
+
|
| 312 |
+
def toXML(self, writer, ttFont):
|
| 313 |
+
writer.begintag("bitmapSizeTable")
|
| 314 |
+
writer.newline()
|
| 315 |
+
for metric in ("hori", "vert"):
|
| 316 |
+
getattr(self, metric).toXML(metric, writer, ttFont)
|
| 317 |
+
for metricName in self._getXMLMetricNames():
|
| 318 |
+
writer.simpletag(metricName, value=getattr(self, metricName))
|
| 319 |
+
writer.newline()
|
| 320 |
+
writer.endtag("bitmapSizeTable")
|
| 321 |
+
writer.newline()
|
| 322 |
+
|
| 323 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 324 |
+
# Create a lookup for all the simple names that make sense to
|
| 325 |
+
# bitmap size table. Only read the information from these names.
|
| 326 |
+
dataNames = set(self._getXMLMetricNames())
|
| 327 |
+
for element in content:
|
| 328 |
+
if not isinstance(element, tuple):
|
| 329 |
+
continue
|
| 330 |
+
name, attrs, content = element
|
| 331 |
+
if name == "sbitLineMetrics":
|
| 332 |
+
direction = attrs["direction"]
|
| 333 |
+
assert direction in (
|
| 334 |
+
"hori",
|
| 335 |
+
"vert",
|
| 336 |
+
), "SbitLineMetrics direction specified invalid."
|
| 337 |
+
metricObj = SbitLineMetrics()
|
| 338 |
+
metricObj.fromXML(name, attrs, content, ttFont)
|
| 339 |
+
vars(self)[direction] = metricObj
|
| 340 |
+
elif name in dataNames:
|
| 341 |
+
vars(self)[name] = safeEval(attrs["value"])
|
| 342 |
+
else:
|
| 343 |
+
log.warning("unknown name '%s' being ignored in BitmapSizeTable.", name)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class SbitLineMetrics(object):
|
| 347 |
+
def toXML(self, name, writer, ttFont):
|
| 348 |
+
writer.begintag("sbitLineMetrics", [("direction", name)])
|
| 349 |
+
writer.newline()
|
| 350 |
+
for metricName in sstruct.getformat(sbitLineMetricsFormat)[1]:
|
| 351 |
+
writer.simpletag(metricName, value=getattr(self, metricName))
|
| 352 |
+
writer.newline()
|
| 353 |
+
writer.endtag("sbitLineMetrics")
|
| 354 |
+
writer.newline()
|
| 355 |
+
|
| 356 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 357 |
+
metricNames = set(sstruct.getformat(sbitLineMetricsFormat)[1])
|
| 358 |
+
for element in content:
|
| 359 |
+
if not isinstance(element, tuple):
|
| 360 |
+
continue
|
| 361 |
+
name, attrs, content = element
|
| 362 |
+
if name in metricNames:
|
| 363 |
+
vars(self)[name] = safeEval(attrs["value"])
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
# Important information about the naming scheme. Used for identifying subtables.
|
| 367 |
+
_indexSubTableSubclassPrefix = "eblc_index_sub_table_"
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
class EblcIndexSubTable(object):
|
| 371 |
+
def __init__(self, data, ttFont):
|
| 372 |
+
self.data = data
|
| 373 |
+
self.ttFont = ttFont
|
| 374 |
+
# TODO Currently non-lazy decompiling doesn't work for this class...
|
| 375 |
+
# if not ttFont.lazy:
|
| 376 |
+
# self.decompile()
|
| 377 |
+
# del self.data, self.ttFont
|
| 378 |
+
|
| 379 |
+
def __getattr__(self, attr):
|
| 380 |
+
# Allow lazy decompile.
|
| 381 |
+
if attr[:2] == "__":
|
| 382 |
+
raise AttributeError(attr)
|
| 383 |
+
if attr == "data":
|
| 384 |
+
raise AttributeError(attr)
|
| 385 |
+
self.decompile()
|
| 386 |
+
return getattr(self, attr)
|
| 387 |
+
|
| 388 |
+
def ensureDecompiled(self, recurse=False):
|
| 389 |
+
if hasattr(self, "data"):
|
| 390 |
+
self.decompile()
|
| 391 |
+
|
| 392 |
+
# This method just takes care of the indexSubHeader. Implementing subclasses
|
| 393 |
+
# should call it to compile the indexSubHeader and then continue compiling
|
| 394 |
+
# the remainder of their unique format.
|
| 395 |
+
def compile(self, ttFont):
|
| 396 |
+
return struct.pack(
|
| 397 |
+
indexSubHeaderFormat,
|
| 398 |
+
self.indexFormat,
|
| 399 |
+
self.imageFormat,
|
| 400 |
+
self.imageDataOffset,
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
# Creates the XML for bitmap glyphs. Each index sub table basically makes
|
| 404 |
+
# the same XML except for specific metric information that is written
|
| 405 |
+
# out via a method call that a subclass implements optionally.
|
| 406 |
+
def toXML(self, writer, ttFont):
|
| 407 |
+
writer.begintag(
|
| 408 |
+
self.__class__.__name__,
|
| 409 |
+
[
|
| 410 |
+
("imageFormat", self.imageFormat),
|
| 411 |
+
("firstGlyphIndex", self.firstGlyphIndex),
|
| 412 |
+
("lastGlyphIndex", self.lastGlyphIndex),
|
| 413 |
+
],
|
| 414 |
+
)
|
| 415 |
+
writer.newline()
|
| 416 |
+
self.writeMetrics(writer, ttFont)
|
| 417 |
+
# Write out the names as thats all thats needed to rebuild etc.
|
| 418 |
+
# For font debugging of consecutive formats the ids are also written.
|
| 419 |
+
# The ids are not read when moving from the XML format.
|
| 420 |
+
glyphIds = map(ttFont.getGlyphID, self.names)
|
| 421 |
+
for glyphName, glyphId in zip(self.names, glyphIds):
|
| 422 |
+
writer.simpletag("glyphLoc", name=glyphName, id=glyphId)
|
| 423 |
+
writer.newline()
|
| 424 |
+
writer.endtag(self.__class__.__name__)
|
| 425 |
+
writer.newline()
|
| 426 |
+
|
| 427 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 428 |
+
# Read all the attributes. Even though the glyph indices are
|
| 429 |
+
# recalculated, they are still read in case there needs to
|
| 430 |
+
# be an immediate export of the data.
|
| 431 |
+
self.imageFormat = safeEval(attrs["imageFormat"])
|
| 432 |
+
self.firstGlyphIndex = safeEval(attrs["firstGlyphIndex"])
|
| 433 |
+
self.lastGlyphIndex = safeEval(attrs["lastGlyphIndex"])
|
| 434 |
+
|
| 435 |
+
self.readMetrics(name, attrs, content, ttFont)
|
| 436 |
+
|
| 437 |
+
self.names = []
|
| 438 |
+
for element in content:
|
| 439 |
+
if not isinstance(element, tuple):
|
| 440 |
+
continue
|
| 441 |
+
name, attrs, content = element
|
| 442 |
+
if name == "glyphLoc":
|
| 443 |
+
self.names.append(attrs["name"])
|
| 444 |
+
|
| 445 |
+
# A helper method that writes the metrics for the index sub table. It also
|
| 446 |
+
# is responsible for writing the image size for fixed size data since fixed
|
| 447 |
+
# size is not recalculated on compile. Default behavior is to do nothing.
|
| 448 |
+
def writeMetrics(self, writer, ttFont):
|
| 449 |
+
pass
|
| 450 |
+
|
| 451 |
+
# A helper method that is the inverse of writeMetrics.
|
| 452 |
+
def readMetrics(self, name, attrs, content, ttFont):
|
| 453 |
+
pass
|
| 454 |
+
|
| 455 |
+
# This method is for fixed glyph data sizes. There are formats where
|
| 456 |
+
# the glyph data is fixed but are actually composite glyphs. To handle
|
| 457 |
+
# this the font spec in indexSubTable makes the data the size of the
|
| 458 |
+
# fixed size by padding the component arrays. This function abstracts
|
| 459 |
+
# out this padding process. Input is data unpadded. Output is data
|
| 460 |
+
# padded only in fixed formats. Default behavior is to return the data.
|
| 461 |
+
def padBitmapData(self, data):
|
| 462 |
+
return data
|
| 463 |
+
|
| 464 |
+
# Remove any of the glyph locations and names that are flagged as skipped.
|
| 465 |
+
# This only occurs in formats {1,3}.
|
| 466 |
+
def removeSkipGlyphs(self):
|
| 467 |
+
# Determines if a name, location pair is a valid data location.
|
| 468 |
+
# Skip glyphs are marked when the size is equal to zero.
|
| 469 |
+
def isValidLocation(args):
|
| 470 |
+
name, (startByte, endByte) = args
|
| 471 |
+
return startByte < endByte
|
| 472 |
+
|
| 473 |
+
# Remove all skip glyphs.
|
| 474 |
+
dataPairs = list(filter(isValidLocation, zip(self.names, self.locations)))
|
| 475 |
+
self.names, self.locations = list(map(list, zip(*dataPairs)))
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
# A closure for creating a custom mixin. This is done because formats 1 and 3
|
| 479 |
+
# are very similar. The only difference between them is the size per offset
|
| 480 |
+
# value. Code put in here should handle both cases generally.
|
| 481 |
+
def _createOffsetArrayIndexSubTableMixin(formatStringForDataType):
|
| 482 |
+
# Prep the data size for the offset array data format.
|
| 483 |
+
dataFormat = ">" + formatStringForDataType
|
| 484 |
+
offsetDataSize = struct.calcsize(dataFormat)
|
| 485 |
+
|
| 486 |
+
class OffsetArrayIndexSubTableMixin(object):
|
| 487 |
+
def decompile(self):
|
| 488 |
+
numGlyphs = self.lastGlyphIndex - self.firstGlyphIndex + 1
|
| 489 |
+
indexingOffsets = [
|
| 490 |
+
glyphIndex * offsetDataSize for glyphIndex in range(numGlyphs + 2)
|
| 491 |
+
]
|
| 492 |
+
indexingLocations = zip(indexingOffsets, indexingOffsets[1:])
|
| 493 |
+
offsetArray = [
|
| 494 |
+
struct.unpack(dataFormat, self.data[slice(*loc)])[0]
|
| 495 |
+
for loc in indexingLocations
|
| 496 |
+
]
|
| 497 |
+
|
| 498 |
+
glyphIds = list(range(self.firstGlyphIndex, self.lastGlyphIndex + 1))
|
| 499 |
+
modifiedOffsets = [offset + self.imageDataOffset for offset in offsetArray]
|
| 500 |
+
self.locations = list(zip(modifiedOffsets, modifiedOffsets[1:]))
|
| 501 |
+
|
| 502 |
+
self.names = list(map(self.ttFont.getGlyphName, glyphIds))
|
| 503 |
+
self.removeSkipGlyphs()
|
| 504 |
+
del self.data, self.ttFont
|
| 505 |
+
|
| 506 |
+
def compile(self, ttFont):
|
| 507 |
+
# First make sure that all the data lines up properly. Formats 1 and 3
|
| 508 |
+
# must have all its data lined up consecutively. If not this will fail.
|
| 509 |
+
for curLoc, nxtLoc in zip(self.locations, self.locations[1:]):
|
| 510 |
+
assert (
|
| 511 |
+
curLoc[1] == nxtLoc[0]
|
| 512 |
+
), "Data must be consecutive in indexSubTable offset formats"
|
| 513 |
+
|
| 514 |
+
glyphIds = list(map(ttFont.getGlyphID, self.names))
|
| 515 |
+
# Make sure that all ids are sorted strictly increasing.
|
| 516 |
+
assert all(glyphIds[i] < glyphIds[i + 1] for i in range(len(glyphIds) - 1))
|
| 517 |
+
|
| 518 |
+
# Run a simple algorithm to add skip glyphs to the data locations at
|
| 519 |
+
# the places where an id is not present.
|
| 520 |
+
idQueue = deque(glyphIds)
|
| 521 |
+
locQueue = deque(self.locations)
|
| 522 |
+
allGlyphIds = list(range(self.firstGlyphIndex, self.lastGlyphIndex + 1))
|
| 523 |
+
allLocations = []
|
| 524 |
+
for curId in allGlyphIds:
|
| 525 |
+
if curId != idQueue[0]:
|
| 526 |
+
allLocations.append((locQueue[0][0], locQueue[0][0]))
|
| 527 |
+
else:
|
| 528 |
+
idQueue.popleft()
|
| 529 |
+
allLocations.append(locQueue.popleft())
|
| 530 |
+
|
| 531 |
+
# Now that all the locations are collected, pack them appropriately into
|
| 532 |
+
# offsets. This is the form where offset[i] is the location and
|
| 533 |
+
# offset[i+1]-offset[i] is the size of the data location.
|
| 534 |
+
offsets = list(allLocations[0]) + [loc[1] for loc in allLocations[1:]]
|
| 535 |
+
# Image data offset must be less than or equal to the minimum of locations.
|
| 536 |
+
# This offset may change the value for round tripping but is safer and
|
| 537 |
+
# allows imageDataOffset to not be required to be in the XML version.
|
| 538 |
+
self.imageDataOffset = min(offsets)
|
| 539 |
+
offsetArray = [offset - self.imageDataOffset for offset in offsets]
|
| 540 |
+
|
| 541 |
+
dataList = [EblcIndexSubTable.compile(self, ttFont)]
|
| 542 |
+
dataList += [
|
| 543 |
+
struct.pack(dataFormat, offsetValue) for offsetValue in offsetArray
|
| 544 |
+
]
|
| 545 |
+
# Take care of any padding issues. Only occurs in format 3.
|
| 546 |
+
if offsetDataSize * len(offsetArray) % 4 != 0:
|
| 547 |
+
dataList.append(struct.pack(dataFormat, 0))
|
| 548 |
+
return bytesjoin(dataList)
|
| 549 |
+
|
| 550 |
+
return OffsetArrayIndexSubTableMixin
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
# A Mixin for functionality shared between the different kinds
|
| 554 |
+
# of fixed sized data handling. Both kinds have big metrics so
|
| 555 |
+
# that kind of special processing is also handled in this mixin.
|
| 556 |
+
class FixedSizeIndexSubTableMixin(object):
|
| 557 |
+
def writeMetrics(self, writer, ttFont):
|
| 558 |
+
writer.simpletag("imageSize", value=self.imageSize)
|
| 559 |
+
writer.newline()
|
| 560 |
+
self.metrics.toXML(writer, ttFont)
|
| 561 |
+
|
| 562 |
+
def readMetrics(self, name, attrs, content, ttFont):
|
| 563 |
+
for element in content:
|
| 564 |
+
if not isinstance(element, tuple):
|
| 565 |
+
continue
|
| 566 |
+
name, attrs, content = element
|
| 567 |
+
if name == "imageSize":
|
| 568 |
+
self.imageSize = safeEval(attrs["value"])
|
| 569 |
+
elif name == BigGlyphMetrics.__name__:
|
| 570 |
+
self.metrics = BigGlyphMetrics()
|
| 571 |
+
self.metrics.fromXML(name, attrs, content, ttFont)
|
| 572 |
+
elif name == SmallGlyphMetrics.__name__:
|
| 573 |
+
log.warning(
|
| 574 |
+
"SmallGlyphMetrics being ignored in format %d.", self.indexFormat
|
| 575 |
+
)
|
| 576 |
+
|
| 577 |
+
def padBitmapData(self, data):
|
| 578 |
+
# Make sure that the data isn't bigger than the fixed size.
|
| 579 |
+
assert len(data) <= self.imageSize, (
|
| 580 |
+
"Data in indexSubTable format %d must be less than the fixed size."
|
| 581 |
+
% self.indexFormat
|
| 582 |
+
)
|
| 583 |
+
# Pad the data so that it matches the fixed size.
|
| 584 |
+
pad = (self.imageSize - len(data)) * b"\0"
|
| 585 |
+
return data + pad
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
class eblc_index_sub_table_1(
|
| 589 |
+
_createOffsetArrayIndexSubTableMixin("L"), EblcIndexSubTable
|
| 590 |
+
):
|
| 591 |
+
pass
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
class eblc_index_sub_table_2(FixedSizeIndexSubTableMixin, EblcIndexSubTable):
|
| 595 |
+
def decompile(self):
|
| 596 |
+
(self.imageSize,) = struct.unpack(">L", self.data[:4])
|
| 597 |
+
self.metrics = BigGlyphMetrics()
|
| 598 |
+
sstruct.unpack2(bigGlyphMetricsFormat, self.data[4:], self.metrics)
|
| 599 |
+
glyphIds = list(range(self.firstGlyphIndex, self.lastGlyphIndex + 1))
|
| 600 |
+
offsets = [
|
| 601 |
+
self.imageSize * i + self.imageDataOffset for i in range(len(glyphIds) + 1)
|
| 602 |
+
]
|
| 603 |
+
self.locations = list(zip(offsets, offsets[1:]))
|
| 604 |
+
self.names = list(map(self.ttFont.getGlyphName, glyphIds))
|
| 605 |
+
del self.data, self.ttFont
|
| 606 |
+
|
| 607 |
+
def compile(self, ttFont):
|
| 608 |
+
glyphIds = list(map(ttFont.getGlyphID, self.names))
|
| 609 |
+
# Make sure all the ids are consecutive. This is required by Format 2.
|
| 610 |
+
assert glyphIds == list(
|
| 611 |
+
range(self.firstGlyphIndex, self.lastGlyphIndex + 1)
|
| 612 |
+
), "Format 2 ids must be consecutive."
|
| 613 |
+
self.imageDataOffset = min(next(iter(zip(*self.locations))))
|
| 614 |
+
|
| 615 |
+
dataList = [EblcIndexSubTable.compile(self, ttFont)]
|
| 616 |
+
dataList.append(struct.pack(">L", self.imageSize))
|
| 617 |
+
dataList.append(sstruct.pack(bigGlyphMetricsFormat, self.metrics))
|
| 618 |
+
return bytesjoin(dataList)
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
class eblc_index_sub_table_3(
|
| 622 |
+
_createOffsetArrayIndexSubTableMixin("H"), EblcIndexSubTable
|
| 623 |
+
):
|
| 624 |
+
pass
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
class eblc_index_sub_table_4(EblcIndexSubTable):
|
| 628 |
+
def decompile(self):
|
| 629 |
+
(numGlyphs,) = struct.unpack(">L", self.data[:4])
|
| 630 |
+
data = self.data[4:]
|
| 631 |
+
indexingOffsets = [
|
| 632 |
+
glyphIndex * codeOffsetPairSize for glyphIndex in range(numGlyphs + 2)
|
| 633 |
+
]
|
| 634 |
+
indexingLocations = zip(indexingOffsets, indexingOffsets[1:])
|
| 635 |
+
glyphArray = [
|
| 636 |
+
struct.unpack(codeOffsetPairFormat, data[slice(*loc)])
|
| 637 |
+
for loc in indexingLocations
|
| 638 |
+
]
|
| 639 |
+
glyphIds, offsets = list(map(list, zip(*glyphArray)))
|
| 640 |
+
# There are one too many glyph ids. Get rid of the last one.
|
| 641 |
+
glyphIds.pop()
|
| 642 |
+
|
| 643 |
+
offsets = [offset + self.imageDataOffset for offset in offsets]
|
| 644 |
+
self.locations = list(zip(offsets, offsets[1:]))
|
| 645 |
+
self.names = list(map(self.ttFont.getGlyphName, glyphIds))
|
| 646 |
+
del self.data, self.ttFont
|
| 647 |
+
|
| 648 |
+
def compile(self, ttFont):
|
| 649 |
+
# First make sure that all the data lines up properly. Format 4
|
| 650 |
+
# must have all its data lined up consecutively. If not this will fail.
|
| 651 |
+
for curLoc, nxtLoc in zip(self.locations, self.locations[1:]):
|
| 652 |
+
assert (
|
| 653 |
+
curLoc[1] == nxtLoc[0]
|
| 654 |
+
), "Data must be consecutive in indexSubTable format 4"
|
| 655 |
+
|
| 656 |
+
offsets = list(self.locations[0]) + [loc[1] for loc in self.locations[1:]]
|
| 657 |
+
# Image data offset must be less than or equal to the minimum of locations.
|
| 658 |
+
# Resetting this offset may change the value for round tripping but is safer
|
| 659 |
+
# and allows imageDataOffset to not be required to be in the XML version.
|
| 660 |
+
self.imageDataOffset = min(offsets)
|
| 661 |
+
offsets = [offset - self.imageDataOffset for offset in offsets]
|
| 662 |
+
glyphIds = list(map(ttFont.getGlyphID, self.names))
|
| 663 |
+
# Create an iterator over the ids plus a padding value.
|
| 664 |
+
idsPlusPad = list(itertools.chain(glyphIds, [0]))
|
| 665 |
+
|
| 666 |
+
dataList = [EblcIndexSubTable.compile(self, ttFont)]
|
| 667 |
+
dataList.append(struct.pack(">L", len(glyphIds)))
|
| 668 |
+
tmp = [
|
| 669 |
+
struct.pack(codeOffsetPairFormat, *cop) for cop in zip(idsPlusPad, offsets)
|
| 670 |
+
]
|
| 671 |
+
dataList += tmp
|
| 672 |
+
data = bytesjoin(dataList)
|
| 673 |
+
return data
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
class eblc_index_sub_table_5(FixedSizeIndexSubTableMixin, EblcIndexSubTable):
|
| 677 |
+
def decompile(self):
|
| 678 |
+
self.origDataLen = 0
|
| 679 |
+
(self.imageSize,) = struct.unpack(">L", self.data[:4])
|
| 680 |
+
data = self.data[4:]
|
| 681 |
+
self.metrics, data = sstruct.unpack2(
|
| 682 |
+
bigGlyphMetricsFormat, data, BigGlyphMetrics()
|
| 683 |
+
)
|
| 684 |
+
(numGlyphs,) = struct.unpack(">L", data[:4])
|
| 685 |
+
data = data[4:]
|
| 686 |
+
glyphIds = [
|
| 687 |
+
struct.unpack(">H", data[2 * i : 2 * (i + 1)])[0] for i in range(numGlyphs)
|
| 688 |
+
]
|
| 689 |
+
|
| 690 |
+
offsets = [
|
| 691 |
+
self.imageSize * i + self.imageDataOffset for i in range(len(glyphIds) + 1)
|
| 692 |
+
]
|
| 693 |
+
self.locations = list(zip(offsets, offsets[1:]))
|
| 694 |
+
self.names = list(map(self.ttFont.getGlyphName, glyphIds))
|
| 695 |
+
del self.data, self.ttFont
|
| 696 |
+
|
| 697 |
+
def compile(self, ttFont):
|
| 698 |
+
self.imageDataOffset = min(next(iter(zip(*self.locations))))
|
| 699 |
+
dataList = [EblcIndexSubTable.compile(self, ttFont)]
|
| 700 |
+
dataList.append(struct.pack(">L", self.imageSize))
|
| 701 |
+
dataList.append(sstruct.pack(bigGlyphMetricsFormat, self.metrics))
|
| 702 |
+
glyphIds = list(map(ttFont.getGlyphID, self.names))
|
| 703 |
+
dataList.append(struct.pack(">L", len(glyphIds)))
|
| 704 |
+
dataList += [struct.pack(">H", curId) for curId in glyphIds]
|
| 705 |
+
if len(glyphIds) % 2 == 1:
|
| 706 |
+
dataList.append(struct.pack(">H", 0))
|
| 707 |
+
return bytesjoin(dataList)
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
# Dictionary of indexFormat to the class representing that format.
|
| 711 |
+
eblc_sub_table_classes = {
|
| 712 |
+
1: eblc_index_sub_table_1,
|
| 713 |
+
2: eblc_index_sub_table_2,
|
| 714 |
+
3: eblc_index_sub_table_3,
|
| 715 |
+
4: eblc_index_sub_table_4,
|
| 716 |
+
5: eblc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__future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
from fontTools.misc import sstruct
|
| 6 |
+
from fontTools.misc.textTools import bytesjoin, safeEval
|
| 7 |
+
from fontTools.misc.xmlWriter import XMLWriter
|
| 8 |
+
from fontTools.ttLib import TTFont, TTLibError
|
| 9 |
+
from fontTools.ttLib.tables import DefaultTable
|
| 10 |
+
from fontTools.ttLib.tables.DefaultTable import XMLAttrs, XMLContent
|
| 11 |
+
from fontTools.ttLib.tables.E_B_L_C_ import sbitLineMetricsFormat, SbitLineMetrics
|
| 12 |
+
|
| 13 |
+
ebscHeaderFormat = """
|
| 14 |
+
> # big endian
|
| 15 |
+
version: 16.16F
|
| 16 |
+
numSizes: I
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
bitmapScaleTableFormatPart2 = """
|
| 20 |
+
> # big endian
|
| 21 |
+
ppemX: B
|
| 22 |
+
ppemY: B
|
| 23 |
+
substitutePpemX: B
|
| 24 |
+
substitutePpemY: B
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class table_E_B_S_C_(DefaultTable.DefaultTable):
|
| 29 |
+
"""
|
| 30 |
+
Embedded Bitmap Scaling Table
|
| 31 |
+
|
| 32 |
+
The ``EBSC`` table provides a mechanism for describing embedded bitmaps which are created by
|
| 33 |
+
scaling other embedded bitmaps. While this is the sort of thing that outline font technologies
|
| 34 |
+
were invented to avoid, there are cases (small sizes of Kanji, for example) where scaling a bitmap
|
| 35 |
+
produces more legible glyphs than scan-converting an outline. For this reason, the EBSC table
|
| 36 |
+
allows a font to define a bitmap strike as a scaled version of another strike.
|
| 37 |
+
|
| 38 |
+
The ``EBSC`` table is used together with the ``EBDT`` table, which provides embedded monochrome or
|
| 39 |
+
grayscale bitmap data, and the ``EBLC`` table, which provides embedded bitmap locators.
|
| 40 |
+
|
| 41 |
+
See also https://learn.microsoft.com/en-us/typography/opentype/spec/ebsc
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
dependencies = ["EBDT", "EBLC"]
|
| 45 |
+
|
| 46 |
+
version: float
|
| 47 |
+
numSizes: int
|
| 48 |
+
bitmapScaleTables: list[BitmapScaleTable]
|
| 49 |
+
|
| 50 |
+
def decompile(self, data: bytes, ttFont: TTFont):
|
| 51 |
+
_, data = sstruct.unpack2(ebscHeaderFormat, data, self)
|
| 52 |
+
self.bitmapScaleTables = []
|
| 53 |
+
for _ in range(self.numSizes):
|
| 54 |
+
bitmapScaleTable = BitmapScaleTable()
|
| 55 |
+
data = bitmapScaleTable.decompile(data)
|
| 56 |
+
self.bitmapScaleTables.append(bitmapScaleTable)
|
| 57 |
+
|
| 58 |
+
def compile(self, ttFont: TTFont) -> bytes:
|
| 59 |
+
self.numSizes = len(self.bitmapScaleTables)
|
| 60 |
+
dataList = [sstruct.pack(ebscHeaderFormat, self)]
|
| 61 |
+
for bitmapScaleTable in self.bitmapScaleTables:
|
| 62 |
+
dataList.append(bitmapScaleTable.compile())
|
| 63 |
+
return bytesjoin(dataList)
|
| 64 |
+
|
| 65 |
+
def toXML(self, writer: XMLWriter, ttFont: TTFont, **kwargs: Any):
|
| 66 |
+
writer.simpletag(
|
| 67 |
+
"header",
|
| 68 |
+
[("version", self.version), ("numSizes", len(self.bitmapScaleTables))],
|
| 69 |
+
)
|
| 70 |
+
writer.newline()
|
| 71 |
+
for index, bitmapScaleTable in enumerate(self.bitmapScaleTables):
|
| 72 |
+
bitmapScaleTable.toXML(index, writer, ttFont)
|
| 73 |
+
|
| 74 |
+
def fromXML(
|
| 75 |
+
self, name: str, attrs: dict[str, str], content: XMLContent, ttFont: TTFont
|
| 76 |
+
):
|
| 77 |
+
if not hasattr(self, "bitmapScaleTables"):
|
| 78 |
+
self.bitmapScaleTables = []
|
| 79 |
+
if name == "header":
|
| 80 |
+
self.version = safeEval(attrs["version"])
|
| 81 |
+
self.numSizes = safeEval(attrs["numSizes"])
|
| 82 |
+
elif name == "bitmapScaleTable":
|
| 83 |
+
bitmapScaleTable = BitmapScaleTable()
|
| 84 |
+
bitmapScaleTable.fromXML(content, ttFont)
|
| 85 |
+
self.bitmapScaleTables.append(bitmapScaleTable)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class BitmapScaleTable:
|
| 89 |
+
hori: SbitLineMetrics
|
| 90 |
+
vert: SbitLineMetrics
|
| 91 |
+
ppemX: int
|
| 92 |
+
ppemY: int
|
| 93 |
+
substitutePpemX: int
|
| 94 |
+
substitutePpemY: int
|
| 95 |
+
|
| 96 |
+
def __init__(
|
| 97 |
+
self,
|
| 98 |
+
hori: SbitLineMetrics | None = None,
|
| 99 |
+
vert: SbitLineMetrics | None = None,
|
| 100 |
+
ppemX: int = 0,
|
| 101 |
+
ppemY: int = 0,
|
| 102 |
+
substitutePpemX: int = 0,
|
| 103 |
+
substitutePpemY: int = 0,
|
| 104 |
+
):
|
| 105 |
+
self.hori = hori if hori is not None else SbitLineMetrics()
|
| 106 |
+
self.vert = vert if vert is not None else SbitLineMetrics()
|
| 107 |
+
self.ppemX = ppemX
|
| 108 |
+
self.ppemY = ppemY
|
| 109 |
+
self.substitutePpemX = substitutePpemX
|
| 110 |
+
self.substitutePpemY = substitutePpemY
|
| 111 |
+
|
| 112 |
+
def decompile(self, data: bytes) -> bytes:
|
| 113 |
+
dummy, data = sstruct.unpack2(sbitLineMetricsFormat, data, self.hori)
|
| 114 |
+
dummy, data = sstruct.unpack2(sbitLineMetricsFormat, data, self.vert)
|
| 115 |
+
dummy, data = sstruct.unpack2(bitmapScaleTableFormatPart2, data, self)
|
| 116 |
+
return data
|
| 117 |
+
|
| 118 |
+
def compile(self) -> bytes:
|
| 119 |
+
dataList = [
|
| 120 |
+
sstruct.pack(sbitLineMetricsFormat, self.hori),
|
| 121 |
+
sstruct.pack(sbitLineMetricsFormat, self.vert),
|
| 122 |
+
sstruct.pack(bitmapScaleTableFormatPart2, self),
|
| 123 |
+
]
|
| 124 |
+
return bytesjoin(dataList)
|
| 125 |
+
|
| 126 |
+
def toXML(self, index: int, writer: XMLWriter, ttFont: TTFont):
|
| 127 |
+
writer.begintag("bitmapScaleTable", [("index", index)])
|
| 128 |
+
writer.newline()
|
| 129 |
+
self.hori.toXML("hori", writer, ttFont)
|
| 130 |
+
self.vert.toXML("vert", writer, ttFont)
|
| 131 |
+
for name in sstruct.getformat(bitmapScaleTableFormatPart2)[1]:
|
| 132 |
+
writer.simpletag(name, value=getattr(self, name))
|
| 133 |
+
writer.newline()
|
| 134 |
+
writer.endtag("bitmapScaleTable")
|
| 135 |
+
writer.newline()
|
| 136 |
+
|
| 137 |
+
def fromXML(self, content: XMLContent, ttFont: TTFont):
|
| 138 |
+
dataNames = set(sstruct.getformat(bitmapScaleTableFormatPart2)[1])
|
| 139 |
+
for element in content:
|
| 140 |
+
if not isinstance(element, tuple):
|
| 141 |
+
continue
|
| 142 |
+
name, attrs, content = element
|
| 143 |
+
if name == "sbitLineMetrics":
|
| 144 |
+
direction = attrs["direction"]
|
| 145 |
+
if direction not in ("hori", "vert"):
|
| 146 |
+
raise TTLibError(
|
| 147 |
+
f"invalid sbitLineMetrics direction: {direction!r}"
|
| 148 |
+
)
|
| 149 |
+
metricObj = SbitLineMetrics()
|
| 150 |
+
metricObj.fromXML(name, attrs, content, ttFont)
|
| 151 |
+
setattr(self, direction, metricObj)
|
| 152 |
+
elif name in dataNames:
|
| 153 |
+
setattr(self, name, safeEval(attrs["value"]))
|
.venv/lib/python3.12/site-packages/fontTools/ttLib/tables/F_F_T_M_.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fontTools.misc import sstruct
|
| 2 |
+
from fontTools.misc.textTools import safeEval
|
| 3 |
+
from fontTools.misc.timeTools import timestampFromString, timestampToString
|
| 4 |
+
from . import DefaultTable
|
| 5 |
+
|
| 6 |
+
FFTMFormat = """
|
| 7 |
+
> # big endian
|
| 8 |
+
version: I
|
| 9 |
+
FFTimeStamp: Q
|
| 10 |
+
sourceCreated: Q
|
| 11 |
+
sourceModified: Q
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class table_F_F_T_M_(DefaultTable.DefaultTable):
|
| 16 |
+
"""FontForge Time Stamp table
|
| 17 |
+
|
| 18 |
+
The ``FFTM`` table is used by the free-software font editor
|
| 19 |
+
FontForge to record timestamps for the creation and modification
|
| 20 |
+
of font source (.sfd) files and a timestamp for FontForge's
|
| 21 |
+
own source code.
|
| 22 |
+
|
| 23 |
+
See also https://fontforge.org/docs/techref/non-standard.html
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def decompile(self, data, ttFont):
|
| 27 |
+
dummy, rest = sstruct.unpack2(FFTMFormat, data, self)
|
| 28 |
+
|
| 29 |
+
def compile(self, ttFont):
|
| 30 |
+
data = sstruct.pack(FFTMFormat, self)
|
| 31 |
+
return data
|
| 32 |
+
|
| 33 |
+
def toXML(self, writer, ttFont):
|
| 34 |
+
writer.comment(
|
| 35 |
+
"FontForge's timestamp, font source creation and modification dates"
|
| 36 |
+
)
|
| 37 |
+
writer.newline()
|
| 38 |
+
formatstring, names, fixes = sstruct.getformat(FFTMFormat)
|
| 39 |
+
for name in names:
|
| 40 |
+
value = getattr(self, name)
|
| 41 |
+
if name in ("FFTimeStamp", "sourceCreated", "sourceModified"):
|
| 42 |
+
value = timestampToString(value)
|
| 43 |
+
writer.simpletag(name, value=value)
|
| 44 |
+
writer.newline()
|
| 45 |
+
|
| 46 |
+
def fromXML(self, name, attrs, content, ttFont):
|
| 47 |
+
value = attrs["value"]
|
| 48 |
+
if name in ("FFTimeStamp", "sourceCreated", "sourceModified"):
|
| 49 |
+
value = timestampFromString(value)
|
| 50 |
+
else:
|
| 51 |
+
value = safeEval(value)
|
| 52 |
+
setattr(self, name, value)
|