dl1wjd2 commited on
Commit
88c064c
·
verified ·
1 Parent(s): bbae060

Upload folder using huggingface_hub (part 5)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +8 -0
  2. hug/lib/python3.12/site-packages/fontTools/qu2cu/qu2cu.cpython-312-x86_64-linux-gnu.so +3 -0
  3. hug/lib/python3.12/site-packages/fontTools/qu2cu/qu2cu.py +433 -0
  4. hug/lib/python3.12/site-packages/fontTools/subset/__init__.py +0 -0
  5. hug/lib/python3.12/site-packages/fontTools/subset/__main__.py +5 -0
  6. hug/lib/python3.12/site-packages/fontTools/subset/__pycache__/__init__.cpython-312.pyc +3 -0
  7. hug/lib/python3.12/site-packages/fontTools/subset/__pycache__/__main__.cpython-312.pyc +0 -0
  8. hug/lib/python3.12/site-packages/fontTools/subset/__pycache__/cff.cpython-312.pyc +0 -0
  9. hug/lib/python3.12/site-packages/fontTools/subset/__pycache__/svg.cpython-312.pyc +0 -0
  10. hug/lib/python3.12/site-packages/fontTools/subset/__pycache__/util.cpython-312.pyc +0 -0
  11. hug/lib/python3.12/site-packages/fontTools/subset/cff.py +191 -0
  12. hug/lib/python3.12/site-packages/fontTools/subset/svg.py +251 -0
  13. hug/lib/python3.12/site-packages/fontTools/subset/util.py +25 -0
  14. hug/lib/python3.12/site-packages/fontTools/svgLib/__init__.py +3 -0
  15. hug/lib/python3.12/site-packages/fontTools/svgLib/__pycache__/__init__.cpython-312.pyc +0 -0
  16. hug/lib/python3.12/site-packages/fontTools/svgLib/path/__init__.py +64 -0
  17. hug/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/__init__.cpython-312.pyc +0 -0
  18. hug/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/arc.cpython-312.pyc +0 -0
  19. hug/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/parser.cpython-312.pyc +0 -0
  20. hug/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/shapes.cpython-312.pyc +0 -0
  21. hug/lib/python3.12/site-packages/fontTools/svgLib/path/arc.py +153 -0
  22. hug/lib/python3.12/site-packages/fontTools/svgLib/path/parser.py +362 -0
  23. hug/lib/python3.12/site-packages/fontTools/svgLib/path/shapes.py +185 -0
  24. hug/lib/python3.12/site-packages/fontTools/t1Lib/__init__.py +648 -0
  25. hug/lib/python3.12/site-packages/fontTools/t1Lib/__pycache__/__init__.cpython-312.pyc +0 -0
  26. hug/lib/python3.12/site-packages/fontTools/tfmLib.py +460 -0
  27. hug/lib/python3.12/site-packages/fontTools/ttLib/__init__.py +29 -0
  28. hug/lib/python3.12/site-packages/fontTools/ttLib/__main__.py +148 -0
  29. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__init__.cpython-312.pyc +0 -0
  30. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__main__.cpython-312.pyc +0 -0
  31. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/beyond64k.cpython-312.pyc +0 -0
  32. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/macUtils.cpython-312.pyc +0 -0
  33. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/removeOverlaps.cpython-312.pyc +0 -0
  34. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/reorderGlyphs.cpython-312.pyc +0 -0
  35. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/scaleUpem.cpython-312.pyc +0 -0
  36. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/sfnt.cpython-312.pyc +0 -0
  37. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/standardGlyphOrder.cpython-312.pyc +0 -0
  38. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttCollection.cpython-312.pyc +0 -0
  39. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttFont.cpython-312.pyc +0 -0
  40. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttGlyphSet.cpython-312.pyc +0 -0
  41. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttVisitor.cpython-312.pyc +0 -0
  42. hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/woff2.cpython-312.pyc +0 -0
  43. hug/lib/python3.12/site-packages/fontTools/ttLib/beyond64k.py +1014 -0
  44. hug/lib/python3.12/site-packages/fontTools/ttLib/macUtils.py +54 -0
  45. hug/lib/python3.12/site-packages/fontTools/ttLib/removeOverlaps.py +404 -0
  46. hug/lib/python3.12/site-packages/fontTools/ttLib/reorderGlyphs.py +315 -0
  47. hug/lib/python3.12/site-packages/fontTools/ttLib/scaleUpem.py +475 -0
  48. hug/lib/python3.12/site-packages/fontTools/ttLib/sfnt.py +756 -0
  49. hug/lib/python3.12/site-packages/fontTools/ttLib/standardGlyphOrder.py +271 -0
  50. hug/lib/python3.12/site-packages/fontTools/ttLib/tables/B_A_S_E_.py +14 -0
.gitattributes CHANGED
@@ -82,3 +82,11 @@ hug/lib/python3.12/site-packages/fontTools/feaLib/lexer.cpython-312-x86_64-linux
82
  hug/lib/python3.12/site-packages/fontTools/misc/bezierTools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
83
  hug/lib/python3.12/site-packages/fontTools/otlLib/__pycache__/builder.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
84
  hug/lib/python3.12/site-packages/fontTools/pens/momentsPen.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
82
  hug/lib/python3.12/site-packages/fontTools/misc/bezierTools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
83
  hug/lib/python3.12/site-packages/fontTools/otlLib/__pycache__/builder.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
84
  hug/lib/python3.12/site-packages/fontTools/pens/momentsPen.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
85
+ hug/lib/python3.12/site-packages/fontTools/qu2cu/qu2cu.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
86
+ hug/lib/python3.12/site-packages/fontTools/subset/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
87
+ hug/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/_g_l_y_f.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
88
+ hug/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otConverters.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
89
+ hug/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otData.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
90
+ hug/lib/python3.12/site-packages/fontTools/ttLib/tables/__pycache__/otTables.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
91
+ hug/lib/python3.12/site-packages/fontTools/varLib/instancer/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
92
+ hug/lib/python3.12/site-packages/fontTools/varLib/iup.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
hug/lib/python3.12/site-packages/fontTools/qu2cu/qu2cu.cpython-312-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2fbd70ae5a59ce150f1ec69d7de9e42473a039b81d9487253aceb698de7b46b6
3
+ size 1476144
hug/lib/python3.12/site-packages/fontTools/qu2cu/qu2cu.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+ # distutils: define_macros=CYTHON_TRACE_NOGIL=1
3
+
4
+ # Copyright 2023 Google Inc. All Rights Reserved.
5
+ # Copyright 2023 Behdad Esfahbod. All Rights Reserved.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ try:
20
+ import cython
21
+ except (AttributeError, ImportError):
22
+ # if cython not installed, use mock module with no-op decorators and types
23
+ from fontTools.misc import cython
24
+ COMPILED = cython.compiled
25
+
26
+ from fontTools.misc.bezierTools import splitCubicAtTC
27
+ from collections import namedtuple
28
+ import math
29
+ from typing import (
30
+ List,
31
+ Sequence,
32
+ Tuple,
33
+ Union,
34
+ )
35
+
36
+ __all__ = ["quadratic_to_curves"]
37
+
38
+
39
+ # Copied from cu2qu
40
+ @cython.cfunc
41
+ @cython.returns(cython.int)
42
+ @cython.locals(
43
+ tolerance=cython.double,
44
+ p0=cython.complex,
45
+ p1=cython.complex,
46
+ p2=cython.complex,
47
+ p3=cython.complex,
48
+ )
49
+ @cython.locals(mid=cython.complex, deriv3=cython.complex)
50
+ def cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance):
51
+ """Check if a cubic Bezier lies within a given distance of the origin.
52
+
53
+ "Origin" means *the* origin (0,0), not the start of the curve. Note that no
54
+ checks are made on the start and end positions of the curve; this function
55
+ only checks the inside of the curve.
56
+
57
+ Args:
58
+ p0 (complex): Start point of curve.
59
+ p1 (complex): First handle of curve.
60
+ p2 (complex): Second handle of curve.
61
+ p3 (complex): End point of curve.
62
+ tolerance (double): Distance from origin.
63
+
64
+ Returns:
65
+ bool: True if the cubic Bezier ``p`` entirely lies within a distance
66
+ ``tolerance`` of the origin, False otherwise.
67
+ """
68
+ # First check p2 then p1, as p2 has higher error early on.
69
+ if abs(p2) <= tolerance and abs(p1) <= tolerance:
70
+ return True
71
+
72
+ # Split.
73
+ mid = (p0 + 3 * (p1 + p2) + p3) * 0.125
74
+ if abs(mid) > tolerance:
75
+ return False
76
+ deriv3 = (p3 + p2 - p1 - p0) * 0.125
77
+ return cubic_farthest_fit_inside(
78
+ p0, (p0 + p1) * 0.5, mid - deriv3, mid, tolerance
79
+ ) and cubic_farthest_fit_inside(mid, mid + deriv3, (p2 + p3) * 0.5, p3, tolerance)
80
+
81
+
82
+ @cython.locals(
83
+ p0=cython.complex,
84
+ p1=cython.complex,
85
+ p2=cython.complex,
86
+ p1_2_3=cython.complex,
87
+ )
88
+ def elevate_quadratic(p0, p1, p2):
89
+ """Given a quadratic bezier curve, return its degree-elevated cubic."""
90
+
91
+ # https://pomax.github.io/bezierinfo/#reordering
92
+ p1_2_3 = p1 * (2 / 3)
93
+ return (
94
+ p0,
95
+ (p0 * (1 / 3) + p1_2_3),
96
+ (p2 * (1 / 3) + p1_2_3),
97
+ p2,
98
+ )
99
+
100
+
101
+ @cython.cfunc
102
+ @cython.locals(
103
+ start=cython.int,
104
+ n=cython.int,
105
+ k=cython.int,
106
+ prod_ratio=cython.double,
107
+ sum_ratio=cython.double,
108
+ ratio=cython.double,
109
+ t=cython.double,
110
+ p0=cython.complex,
111
+ p1=cython.complex,
112
+ p2=cython.complex,
113
+ p3=cython.complex,
114
+ )
115
+ def merge_curves(curves, start, n):
116
+ """Give a cubic-Bezier spline, reconstruct one cubic-Bezier
117
+ that has the same endpoints and tangents and approxmates
118
+ the spline."""
119
+
120
+ # Reconstruct the t values of the cut segments
121
+ prod_ratio = 1.0
122
+ sum_ratio = 1.0
123
+ ts = [1]
124
+ for k in range(1, n):
125
+ ck = curves[start + k]
126
+ c_before = curves[start + k - 1]
127
+
128
+ # |t_(k+1) - t_k| / |t_k - t_(k - 1)| = ratio
129
+ assert ck[0] == c_before[3]
130
+ ratio = abs(ck[1] - ck[0]) / abs(c_before[3] - c_before[2])
131
+
132
+ prod_ratio *= ratio
133
+ sum_ratio += prod_ratio
134
+ ts.append(sum_ratio)
135
+
136
+ # (t(n) - t(n - 1)) / (t_(1) - t(0)) = prod_ratio
137
+
138
+ ts = [t / sum_ratio for t in ts[:-1]]
139
+
140
+ p0 = curves[start][0]
141
+ p1 = curves[start][1]
142
+ p2 = curves[start + n - 1][2]
143
+ p3 = curves[start + n - 1][3]
144
+
145
+ # Build the curve by scaling the control-points.
146
+ p1 = p0 + (p1 - p0) / (ts[0] if ts else 1)
147
+ p2 = p3 + (p2 - p3) / ((1 - ts[-1]) if ts else 1)
148
+
149
+ curve = (p0, p1, p2, p3)
150
+
151
+ return curve, ts
152
+
153
+
154
+ @cython.locals(
155
+ count=cython.int,
156
+ num_offcurves=cython.int,
157
+ i=cython.int,
158
+ off1=cython.complex,
159
+ off2=cython.complex,
160
+ on=cython.complex,
161
+ )
162
+ def add_implicit_on_curves(p):
163
+ q = list(p)
164
+ count = 0
165
+ num_offcurves = len(p) - 2
166
+ for i in range(1, num_offcurves):
167
+ off1 = p[i]
168
+ off2 = p[i + 1]
169
+ on = off1 + (off2 - off1) * 0.5
170
+ q.insert(i + 1 + count, on)
171
+ count += 1
172
+ return q
173
+
174
+
175
+ Point = Union[Tuple[float, float], complex]
176
+
177
+
178
+ def _raise_incompatible_point(point, previous_point):
179
+ raise ValueError(
180
+ f"Quadratic splines must connect end-to-start; got {previous_point!r} then {point!r}"
181
+ )
182
+
183
+
184
+ def _validate_spline_length(spline):
185
+ if len(spline) < 3:
186
+ raise ValueError("Quadratic splines must contain at least 3 points")
187
+
188
+
189
+ def _validate_positive_tolerance(max_err):
190
+ if max_err <= 0:
191
+ raise ValueError("max_err must be greater than zero")
192
+
193
+
194
+ @cython.locals(
195
+ cost=cython.int,
196
+ is_complex=cython.int,
197
+ )
198
+ def quadratic_to_curves(
199
+ quads: List[Sequence[Point]],
200
+ max_err: float = 0.5,
201
+ all_cubic: bool = False,
202
+ ) -> List[Tuple[Point, ...]]:
203
+ """Converts a connecting list of quadratic splines to a list of quadratic
204
+ and cubic curves.
205
+
206
+ A quadratic spline is specified as a sequence of points. Either each point is
207
+ a 2-tuple of X,Y coordinates, or each point is a complex number with
208
+ real/imaginary components representing X,Y coordinates.
209
+
210
+ The first and last points are on-curve points and the rest are off-curve
211
+ points, with an implied on-curve point in the middle between every two
212
+ consequtive off-curve points.
213
+
214
+ Returns:
215
+ The output is a list of tuples of points. Points are represented
216
+ in the same format as the input, either as 2-tuples or complex numbers.
217
+ If ``quads`` is empty, returns an empty list.
218
+
219
+ Each tuple is either of length three, for a quadratic curve, or four,
220
+ for a cubic curve. Each curve's last point is the same as the next
221
+ curve's first point.
222
+
223
+ Args:
224
+ quads: quadratic splines
225
+
226
+ max_err: absolute error tolerance; defaults to 0.5
227
+
228
+ all_cubic: if True, only cubic curves are generated; defaults to False
229
+
230
+ Raises:
231
+ ValueError: if an input spline has fewer than 3 points, or if adjacent
232
+ splines do not connect end-to-start.
233
+ """
234
+ if not quads:
235
+ return []
236
+ _validate_positive_tolerance(max_err)
237
+ for spline in quads:
238
+ _validate_spline_length(spline)
239
+
240
+ is_complex = type(quads[0][0]) is complex
241
+ if not is_complex:
242
+ quads = [[complex(x, y) for (x, y) in p] for p in quads]
243
+
244
+ q = [quads[0][0]]
245
+ costs = [1]
246
+ cost = 1
247
+ for p in quads:
248
+ if q[-1] != p[0]:
249
+ _raise_incompatible_point(p[0], q[-1])
250
+ for i in range(len(p) - 2):
251
+ cost += 1
252
+ costs.append(cost)
253
+ costs.append(cost)
254
+ qq = add_implicit_on_curves(p)[1:]
255
+ costs.pop()
256
+ q.extend(qq)
257
+ cost += 1
258
+ costs.append(cost)
259
+
260
+ curves = spline_to_curves(q, costs, max_err, all_cubic)
261
+
262
+ if not is_complex:
263
+ curves = [tuple((c.real, c.imag) for c in curve) for curve in curves]
264
+ return curves
265
+
266
+
267
+ Solution = namedtuple("Solution", ["num_points", "error", "start_index", "is_cubic"])
268
+
269
+
270
+ @cython.locals(
271
+ i=cython.int,
272
+ j=cython.int,
273
+ k=cython.int,
274
+ start=cython.int,
275
+ i_sol_count=cython.int,
276
+ j_sol_count=cython.int,
277
+ this_sol_count=cython.int,
278
+ tolerance=cython.double,
279
+ err=cython.double,
280
+ error=cython.double,
281
+ i_sol_error=cython.double,
282
+ j_sol_error=cython.double,
283
+ all_cubic=cython.int,
284
+ is_cubic=cython.int,
285
+ count=cython.int,
286
+ p0=cython.complex,
287
+ p1=cython.complex,
288
+ p2=cython.complex,
289
+ p3=cython.complex,
290
+ v=cython.complex,
291
+ u=cython.complex,
292
+ )
293
+ def spline_to_curves(q, costs, tolerance=0.5, all_cubic=False):
294
+ """
295
+ q: quadratic spline with alternating on-curve / off-curve points.
296
+
297
+ costs: cumulative list of encoding cost of q in terms of number of
298
+ points that need to be encoded. Implied on-curve points do not
299
+ contribute to the cost. If all points need to be encoded, then
300
+ costs will be range(1, len(q)+1).
301
+ """
302
+
303
+ assert len(q) >= 3, "quadratic spline requires at least 3 points"
304
+
305
+ # Elevate quadratic segments to cubic
306
+ elevated_quadratics = [
307
+ elevate_quadratic(*q[i : i + 3]) for i in range(0, len(q) - 2, 2)
308
+ ]
309
+
310
+ # Find sharp corners; they have to be oncurves for sure.
311
+ forced = set()
312
+ for i in range(1, len(elevated_quadratics)):
313
+ p0 = elevated_quadratics[i - 1][2]
314
+ p1 = elevated_quadratics[i][0]
315
+ p2 = elevated_quadratics[i][1]
316
+ if abs(p1 - p0) + abs(p2 - p1) > tolerance + abs(p2 - p0):
317
+ forced.add(i)
318
+
319
+ # Dynamic-Programming to find the solution with fewest number of
320
+ # cubic curves, and within those the one with smallest error.
321
+ sols = [Solution(0, 0, 0, False)]
322
+ impossible = Solution(len(elevated_quadratics) * 3 + 1, 0, 1, False)
323
+ start = 0
324
+ for i in range(1, len(elevated_quadratics) + 1):
325
+ best_sol = impossible
326
+ for j in range(start, i):
327
+ j_sol_count, j_sol_error = sols[j].num_points, sols[j].error
328
+
329
+ if not all_cubic:
330
+ # Solution with quadratics between j:i
331
+ this_count = costs[2 * i - 1] - costs[2 * j] + 1
332
+ i_sol_count = j_sol_count + this_count
333
+ i_sol_error = j_sol_error
334
+ i_sol = Solution(i_sol_count, i_sol_error, i - j, False)
335
+ if i_sol < best_sol:
336
+ best_sol = i_sol
337
+
338
+ if this_count <= 3:
339
+ # Can't get any better than this in the path below
340
+ continue
341
+
342
+ # Fit elevated_quadratics[j:i] into one cubic
343
+ try:
344
+ curve, ts = merge_curves(elevated_quadratics, j, i - j)
345
+ except ZeroDivisionError:
346
+ continue
347
+
348
+ # Now reconstruct the segments from the fitted curve
349
+ reconstructed_iter = splitCubicAtTC(*curve, *ts)
350
+ reconstructed = []
351
+
352
+ # Knot errors
353
+ error = 0
354
+ for k, reconst in enumerate(reconstructed_iter):
355
+ orig = elevated_quadratics[j + k]
356
+ err = abs(reconst[3] - orig[3])
357
+ error = max(error, err)
358
+ if error > tolerance:
359
+ break
360
+ reconstructed.append(reconst)
361
+ if error > tolerance:
362
+ # Not feasible
363
+ continue
364
+
365
+ # Interior errors
366
+ for k, reconst in enumerate(reconstructed):
367
+ orig = elevated_quadratics[j + k]
368
+ p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig))
369
+
370
+ if not cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance):
371
+ error = tolerance + 1
372
+ break
373
+ if error > tolerance:
374
+ # Not feasible
375
+ continue
376
+
377
+ # Save best solution
378
+ i_sol_count = j_sol_count + 3
379
+ i_sol_error = max(j_sol_error, error)
380
+ i_sol = Solution(i_sol_count, i_sol_error, i - j, True)
381
+ if i_sol < best_sol:
382
+ best_sol = i_sol
383
+
384
+ if i_sol_count == 3:
385
+ # Can't get any better than this
386
+ break
387
+
388
+ sols.append(best_sol)
389
+ if i in forced:
390
+ start = i
391
+
392
+ # Reconstruct solution
393
+ splits = []
394
+ cubic = []
395
+ i = len(sols) - 1
396
+ while i:
397
+ count, is_cubic = sols[i].start_index, sols[i].is_cubic
398
+ splits.append(i)
399
+ cubic.append(is_cubic)
400
+ i -= count
401
+ curves = []
402
+ j = 0
403
+ for i, is_cubic in reversed(list(zip(splits, cubic))):
404
+ if is_cubic:
405
+ curves.append(merge_curves(elevated_quadratics, j, i - j)[0])
406
+ else:
407
+ for k in range(j, i):
408
+ curves.append(q[k * 2 : k * 2 + 3])
409
+ j = i
410
+
411
+ return curves
412
+
413
+
414
+ def main():
415
+ from fontTools.cu2qu.benchmark import generate_curve
416
+ from fontTools.cu2qu import curve_to_quadratic
417
+
418
+ tolerance = 0.05
419
+ reconstruct_tolerance = tolerance * 1
420
+ curve = generate_curve()
421
+ quadratics = curve_to_quadratic(curve, tolerance)
422
+ print(
423
+ "cu2qu tolerance %g. qu2cu tolerance %g." % (tolerance, reconstruct_tolerance)
424
+ )
425
+ print("One random cubic turned into %d quadratics." % len(quadratics))
426
+ curves = quadratic_to_curves([quadratics], reconstruct_tolerance)
427
+ print("Those quadratics turned back into %d cubics. " % len(curves))
428
+ print("Original curve:", curve)
429
+ print("Reconstructed curve(s):", curves)
430
+
431
+
432
+ if __name__ == "__main__":
433
+ main()
hug/lib/python3.12/site-packages/fontTools/subset/__init__.py ADDED
The diff for this file is too large to render. See raw diff
 
hug/lib/python3.12/site-packages/fontTools/subset/__main__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import sys
2
+ from fontTools.subset import main
3
+
4
+ if __name__ == "__main__":
5
+ sys.exit(main())
hug/lib/python3.12/site-packages/fontTools/subset/__pycache__/__init__.cpython-312.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a80597177fb367ec4dd2821e62d9ad8c8820598bc94c70ac9a55803fc36ab65
3
+ size 213789
hug/lib/python3.12/site-packages/fontTools/subset/__pycache__/__main__.cpython-312.pyc ADDED
Binary file (360 Bytes). View file
 
hug/lib/python3.12/site-packages/fontTools/subset/__pycache__/cff.cpython-312.pyc ADDED
Binary file (9.28 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/subset/__pycache__/svg.cpython-312.pyc ADDED
Binary file (9.33 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/subset/__pycache__/util.cpython-312.pyc ADDED
Binary file (1.29 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/subset/cff.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc import psCharStrings
2
+ from fontTools import ttLib
3
+ from fontTools.pens.basePen import NullPen
4
+ from fontTools.misc.roundTools import otRound
5
+ from fontTools.misc.loggingTools import deprecateFunction
6
+ from fontTools.subset.util import _add_method, _uniq_sort
7
+
8
+
9
+ class _ClosureGlyphsT2Decompiler(psCharStrings.SimpleT2Decompiler):
10
+ def __init__(self, components, localSubrs, globalSubrs):
11
+ psCharStrings.SimpleT2Decompiler.__init__(self, localSubrs, globalSubrs)
12
+ self.components = components
13
+
14
+ def op_endchar(self, index):
15
+ args = self.popall()
16
+ if len(args) >= 4:
17
+ from fontTools.encodings.StandardEncoding import StandardEncoding
18
+
19
+ # endchar can do seac accent bulding; The T2 spec says it's deprecated,
20
+ # but recent software that shall remain nameless does output it.
21
+ adx, ady, bchar, achar = args[-4:]
22
+ baseGlyph = StandardEncoding[bchar]
23
+ accentGlyph = StandardEncoding[achar]
24
+ self.components.add(baseGlyph)
25
+ self.components.add(accentGlyph)
26
+
27
+
28
+ @_add_method(ttLib.getTableClass("CFF "))
29
+ def closure_glyphs(self, s):
30
+ cff = self.cff
31
+ assert len(cff) == 1
32
+ font = cff[cff.keys()[0]]
33
+ glyphSet = font.CharStrings
34
+
35
+ decompose = s.glyphs
36
+ while decompose:
37
+ components = set()
38
+ for g in decompose:
39
+ if g not in glyphSet:
40
+ continue
41
+ gl = glyphSet[g]
42
+
43
+ subrs = getattr(gl.private, "Subrs", [])
44
+ decompiler = _ClosureGlyphsT2Decompiler(components, subrs, gl.globalSubrs)
45
+ decompiler.execute(gl)
46
+ components -= s.glyphs
47
+ s.glyphs.update(components)
48
+ decompose = components
49
+
50
+
51
+ def _empty_charstring(font, glyphName, isCFF2, ignoreWidth=False):
52
+ c, fdSelectIndex = font.CharStrings.getItemAndSelector(glyphName)
53
+ if isCFF2 or ignoreWidth:
54
+ # CFF2 charstrings have no widths nor 'endchar' operators
55
+ c.setProgram([] if isCFF2 else ["endchar"])
56
+ else:
57
+ if hasattr(font, "FDArray") and font.FDArray is not None:
58
+ private = font.FDArray[fdSelectIndex].Private
59
+ else:
60
+ private = font.Private
61
+ dfltWdX = private.defaultWidthX
62
+ nmnlWdX = private.nominalWidthX
63
+ pen = NullPen()
64
+ c.draw(pen) # this will set the charstring's width
65
+ if c.width != dfltWdX:
66
+ c.program = [c.width - nmnlWdX, "endchar"]
67
+ else:
68
+ c.program = ["endchar"]
69
+
70
+
71
+ @_add_method(ttLib.getTableClass("CFF "))
72
+ def prune_pre_subset(self, font, options):
73
+ cff = self.cff
74
+ # CFF table must have one font only
75
+ cff.fontNames = cff.fontNames[:1]
76
+
77
+ if options.notdef_glyph and not options.notdef_outline:
78
+ isCFF2 = cff.major > 1
79
+ for fontname in cff.keys():
80
+ font = cff[fontname]
81
+ _empty_charstring(font, ".notdef", isCFF2=isCFF2)
82
+
83
+ # Clear useless Encoding
84
+ for fontname in cff.keys():
85
+ font = cff[fontname]
86
+ # https://github.com/fonttools/fonttools/issues/620
87
+ font.Encoding = "StandardEncoding"
88
+
89
+ return True # bool(cff.fontNames)
90
+
91
+
92
+ @_add_method(ttLib.getTableClass("CFF "))
93
+ def subset_glyphs(self, s):
94
+ cff = self.cff
95
+ for fontname in cff.keys():
96
+ font = cff[fontname]
97
+ cs = font.CharStrings
98
+
99
+ glyphs = s.glyphs.union(s.glyphs_emptied)
100
+
101
+ # Load all glyphs
102
+ for g in font.charset:
103
+ if g not in glyphs:
104
+ continue
105
+ c, _ = cs.getItemAndSelector(g)
106
+
107
+ if cs.charStringsAreIndexed:
108
+ indices = [i for i, g in enumerate(font.charset) if g in glyphs]
109
+ csi = cs.charStringsIndex
110
+ csi.items = [csi.items[i] for i in indices]
111
+ del csi.file, csi.offsets
112
+ newCharStrings = {}
113
+ for indicesIdx, charsetIdx in enumerate(indices):
114
+ g = font.charset[charsetIdx]
115
+ if g in cs.charStrings:
116
+ newCharStrings[g] = indicesIdx
117
+ cs.charStrings = newCharStrings
118
+ else:
119
+ cs.charStrings = {g: v for g, v in cs.charStrings.items() if g in glyphs}
120
+ if hasattr(font, "FDSelect"):
121
+ sel = font.FDSelect
122
+ sel.format = None
123
+ # FDSelect may also map VARC-only glyphs beyond the CFF2 charset.
124
+ sel.gidArray = [
125
+ sel.gidArray[i]
126
+ for i, g in enumerate(s.orig_glyph_order)
127
+ if g in glyphs and i < len(sel.gidArray)
128
+ ]
129
+ font.charset = [g for g in font.charset if g in glyphs]
130
+ font.numGlyphs = len(font.charset)
131
+
132
+ if s.options.retain_gids:
133
+ isCFF2 = cff.major > 1
134
+ for g in s.glyphs_emptied:
135
+ if g not in cs:
136
+ continue
137
+ _empty_charstring(font, g, isCFF2=isCFF2, ignoreWidth=True)
138
+
139
+ return True # any(cff[fontname].numGlyphs for fontname in cff.keys())
140
+
141
+
142
+ @_add_method(ttLib.getTableClass("CFF "))
143
+ def prune_post_subset(self, ttfFont, options):
144
+ cff = self.cff
145
+ for fontname in cff.keys():
146
+ font = cff[fontname]
147
+ cs = font.CharStrings
148
+
149
+ # Drop unused FontDictionaries
150
+ if hasattr(font, "FDSelect"):
151
+ sel = font.FDSelect
152
+ indices = _uniq_sort(sel.gidArray)
153
+ sel.gidArray = [indices.index(ss) for ss in sel.gidArray]
154
+ arr = font.FDArray
155
+ arr.items = [arr[i] for i in indices]
156
+ del arr.file, arr.offsets
157
+
158
+ # Desubroutinize if asked for
159
+ if options.desubroutinize:
160
+ cff.desubroutinize()
161
+
162
+ # Drop hints if not needed
163
+ if not options.hinting:
164
+ self.remove_hints()
165
+ elif not options.desubroutinize:
166
+ self.remove_unused_subroutines()
167
+ return True
168
+
169
+
170
+ @deprecateFunction(
171
+ "use 'CFFFontSet.desubroutinize()' instead", category=DeprecationWarning
172
+ )
173
+ @_add_method(ttLib.getTableClass("CFF "))
174
+ def desubroutinize(self):
175
+ self.cff.desubroutinize()
176
+
177
+
178
+ @deprecateFunction(
179
+ "use 'CFFFontSet.remove_hints()' instead", category=DeprecationWarning
180
+ )
181
+ @_add_method(ttLib.getTableClass("CFF "))
182
+ def remove_hints(self):
183
+ self.cff.remove_hints()
184
+
185
+
186
+ @deprecateFunction(
187
+ "use 'CFFFontSet.remove_unused_subroutines' instead", category=DeprecationWarning
188
+ )
189
+ @_add_method(ttLib.getTableClass("CFF "))
190
+ def remove_unused_subroutines(self):
191
+ self.cff.remove_unused_subroutines()
hug/lib/python3.12/site-packages/fontTools/subset/svg.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from functools import cache
5
+ from itertools import chain, count
6
+ from typing import Dict, Iterable, Iterator, List, Optional, Set, Tuple
7
+
8
+ try:
9
+ from lxml import etree
10
+ except ImportError:
11
+ # lxml is required for subsetting SVG, but we prefer to delay the import error
12
+ # until subset_glyphs() is called (i.e. if font to subset has an 'SVG ' table)
13
+ etree = None
14
+
15
+ from fontTools import ttLib
16
+ from fontTools.subset.util import _add_method
17
+ from fontTools.ttLib.tables.S_V_G_ import SVGDocument
18
+
19
+ __all__ = ["subset_glyphs"]
20
+
21
+
22
+ GID_RE = re.compile(r"^glyph(\d+)$")
23
+
24
+ NAMESPACES = {
25
+ "svg": "http://www.w3.org/2000/svg",
26
+ "xlink": "http://www.w3.org/1999/xlink",
27
+ }
28
+ XLINK_HREF = f'{{{NAMESPACES["xlink"]}}}href'
29
+
30
+
31
+ @cache
32
+ def xpath(path):
33
+ # compile XPath upfront, caching result to reuse on multiple elements
34
+ return etree.XPath(path, namespaces=NAMESPACES)
35
+
36
+
37
+ def group_elements_by_id(tree: etree.Element) -> Dict[str, etree.Element]:
38
+ # select all svg elements with 'id' attribute no matter where they are
39
+ # including the root element itself:
40
+ # https://github.com/fonttools/fonttools/issues/2548
41
+ return {el.attrib["id"]: el for el in xpath("//svg:*[@id]")(tree)}
42
+
43
+
44
+ def parse_css_declarations(style_attr: str) -> Dict[str, str]:
45
+ # https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/style
46
+ # https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations
47
+ result = {}
48
+ for declaration in style_attr.split(";"):
49
+ if declaration.count(":") == 1:
50
+ property_name, value = declaration.split(":")
51
+ property_name = property_name.strip()
52
+ result[property_name] = value.strip()
53
+ elif declaration.strip():
54
+ raise ValueError(f"Invalid CSS declaration syntax: {declaration}")
55
+ return result
56
+
57
+
58
+ def iter_referenced_ids(tree: etree.Element) -> Iterator[str]:
59
+ # Yield all the ids that can be reached via references from this element tree.
60
+ # We currently support xlink:href (as used by <use> and gradient templates),
61
+ # and local url(#...) links found in fill or clip-path attributes
62
+ # TODO(anthrotype): Check we aren't missing other supported kinds of reference
63
+ find_svg_elements_with_references = xpath(
64
+ ".//svg:*[ "
65
+ "starts-with(@xlink:href, '#') "
66
+ "or starts-with(@fill, 'url(#') "
67
+ "or starts-with(@clip-path, 'url(#') "
68
+ "or contains(@style, ':url(#') "
69
+ "]",
70
+ )
71
+ for el in chain([tree], find_svg_elements_with_references(tree)):
72
+ ref_id = href_local_target(el)
73
+ if ref_id is not None:
74
+ yield ref_id
75
+
76
+ attrs = el.attrib
77
+ if "style" in attrs:
78
+ attrs = {**dict(attrs), **parse_css_declarations(el.attrib["style"])}
79
+ for attr in ("fill", "clip-path"):
80
+ if attr in attrs:
81
+ value = attrs[attr]
82
+ if value.startswith("url(#") and value.endswith(")"):
83
+ ref_id = value[5:-1]
84
+ assert ref_id
85
+ yield ref_id
86
+
87
+
88
+ def closure_element_ids(
89
+ elements: Dict[str, etree.Element], element_ids: Set[str]
90
+ ) -> None:
91
+ # Expand the initial subset of element ids to include ids that can be reached
92
+ # via references from the initial set.
93
+ unvisited = element_ids
94
+ while unvisited:
95
+ referenced: Set[str] = set()
96
+ for el_id in unvisited:
97
+ if el_id not in elements:
98
+ # ignore dangling reference; not our job to validate svg
99
+ continue
100
+ referenced.update(iter_referenced_ids(elements[el_id]))
101
+ referenced -= element_ids
102
+ element_ids.update(referenced)
103
+ unvisited = referenced
104
+
105
+
106
+ def subset_elements(el: etree.Element, retained_ids: Set[str]) -> bool:
107
+ # Keep elements if their id is in the subset, or any of their children's id is.
108
+ # Drop elements whose id is not in the subset, and either have no children,
109
+ # or all their children are being dropped.
110
+ if el.attrib.get("id") in retained_ids:
111
+ # if id is in the set, don't recurse; keep whole subtree
112
+ return True
113
+ # recursively subset all the children; we use a list comprehension instead
114
+ # of a parentheses-less generator expression because we don't want any() to
115
+ # short-circuit, as our function has a side effect of dropping empty elements.
116
+ if any([subset_elements(e, retained_ids) for e in el]):
117
+ return True
118
+ assert len(el) == 0
119
+ parent = el.getparent()
120
+ if parent is not None:
121
+ parent.remove(el)
122
+ return False
123
+
124
+
125
+ def remap_glyph_ids(
126
+ svg: etree.Element, glyph_index_map: Dict[int, int]
127
+ ) -> Dict[str, str]:
128
+ # Given {old_gid: new_gid} map, rename all elements containing id="glyph{gid}"
129
+ # special attributes
130
+ elements = group_elements_by_id(svg)
131
+ id_map = {}
132
+ for el_id, el in elements.items():
133
+ m = GID_RE.match(el_id)
134
+ if not m:
135
+ continue
136
+ old_index = int(m.group(1))
137
+ new_index = glyph_index_map.get(old_index)
138
+ if new_index is not None:
139
+ if old_index == new_index:
140
+ continue
141
+ new_id = f"glyph{new_index}"
142
+ else:
143
+ # If the old index is missing, the element correspond to a glyph that was
144
+ # excluded from the font's subset.
145
+ # We rename it to avoid clashes with the new GIDs or other element ids.
146
+ new_id = f".{el_id}"
147
+ n = count(1)
148
+ while new_id in elements:
149
+ new_id = f"{new_id}.{next(n)}"
150
+
151
+ id_map[el_id] = new_id
152
+ el.attrib["id"] = new_id
153
+
154
+ return id_map
155
+
156
+
157
+ def href_local_target(el: etree.Element) -> Optional[str]:
158
+ if XLINK_HREF in el.attrib:
159
+ href = el.attrib[XLINK_HREF]
160
+ if href.startswith("#") and len(href) > 1:
161
+ return href[1:] # drop the leading #
162
+ return None
163
+
164
+
165
+ def update_glyph_href_links(svg: etree.Element, id_map: Dict[str, str]) -> None:
166
+ # update all xlink:href="#glyph..." attributes to point to the new glyph ids
167
+ for el in xpath(".//svg:*[starts-with(@xlink:href, '#glyph')]")(svg):
168
+ old_id = href_local_target(el)
169
+ assert old_id is not None
170
+ if old_id in id_map:
171
+ new_id = id_map[old_id]
172
+ el.attrib[XLINK_HREF] = f"#{new_id}"
173
+
174
+
175
+ def ranges(ints: Iterable[int]) -> Iterator[Tuple[int, int]]:
176
+ # Yield sorted, non-overlapping (min, max) ranges of consecutive integers
177
+ sorted_ints = iter(sorted(set(ints)))
178
+ try:
179
+ start = end = next(sorted_ints)
180
+ except StopIteration:
181
+ return
182
+ for v in sorted_ints:
183
+ if v - 1 == end:
184
+ end = v
185
+ else:
186
+ yield (start, end)
187
+ start = end = v
188
+ yield (start, end)
189
+
190
+
191
+ @_add_method(ttLib.getTableClass("SVG "))
192
+ def subset_glyphs(self, s) -> bool:
193
+ if etree is None:
194
+ raise ImportError("No module named 'lxml', required to subset SVG")
195
+
196
+ # glyph names (before subsetting)
197
+ glyph_order: List[str] = s.orig_glyph_order
198
+ # map from glyph names to original glyph indices
199
+ rev_orig_glyph_map: Dict[str, int] = s.reverseOrigGlyphMap
200
+ # map from original to new glyph indices (after subsetting)
201
+ glyph_index_map: Dict[int, int] = s.glyph_index_map
202
+
203
+ new_docs: List[SVGDocument] = []
204
+ for doc in self.docList:
205
+ glyphs = {
206
+ glyph_order[i] for i in range(doc.startGlyphID, doc.endGlyphID + 1)
207
+ }.intersection(s.glyphs)
208
+ if not glyphs:
209
+ # no intersection: we can drop the whole record
210
+ continue
211
+
212
+ svg = etree.fromstring(
213
+ # encode because fromstring dislikes xml encoding decl if input is str.
214
+ # SVG xml encoding must be utf-8 as per OT spec.
215
+ doc.data.encode("utf-8"),
216
+ parser=etree.XMLParser(
217
+ # Disable libxml2 security restrictions to support very deep trees.
218
+ # Without this we would get an error like this:
219
+ # `lxml.etree.XMLSyntaxError: internal error: Huge input lookup`
220
+ # when parsing big fonts e.g. noto-emoji-picosvg.ttf.
221
+ huge_tree=True,
222
+ # ignore blank text as it's not meaningful in OT-SVG; it also prevents
223
+ # dangling tail text after removing an element when pretty_print=True
224
+ remove_blank_text=True,
225
+ # don't replace entities; we don't expect any in OT-SVG and they may
226
+ # be abused for XXE attacks
227
+ resolve_entities=False,
228
+ ),
229
+ )
230
+
231
+ elements = group_elements_by_id(svg)
232
+ gids = {rev_orig_glyph_map[g] for g in glyphs}
233
+ element_ids = {f"glyph{i}" for i in gids}
234
+ closure_element_ids(elements, element_ids)
235
+
236
+ if not subset_elements(svg, element_ids):
237
+ continue
238
+
239
+ if not s.options.retain_gids:
240
+ id_map = remap_glyph_ids(svg, glyph_index_map)
241
+ update_glyph_href_links(svg, id_map)
242
+
243
+ new_doc = etree.tostring(svg, pretty_print=s.options.pretty_svg).decode("utf-8")
244
+
245
+ new_gids = (glyph_index_map[i] for i in gids)
246
+ for start, end in ranges(new_gids):
247
+ new_docs.append(SVGDocument(new_doc, start, end, doc.compressed))
248
+
249
+ self.docList = new_docs
250
+
251
+ return bool(self.docList)
hug/lib/python3.12/site-packages/fontTools/subset/util.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Private utility methods used by the subset modules"""
2
+
3
+
4
+ def _add_method(*clazzes):
5
+ """Returns a decorator function that adds a new method to one or
6
+ more classes."""
7
+
8
+ def wrapper(method):
9
+ done = []
10
+ for clazz in clazzes:
11
+ if clazz in done:
12
+ continue # Support multiple names of a clazz
13
+ done.append(clazz)
14
+ assert clazz.__name__ != "DefaultTable", "Oops, table class not found."
15
+ assert not hasattr(
16
+ clazz, method.__name__
17
+ ), "Oops, class '%s' has method '%s'." % (clazz.__name__, method.__name__)
18
+ setattr(clazz, method.__name__, method)
19
+ return None
20
+
21
+ return wrapper
22
+
23
+
24
+ def _uniq_sort(l):
25
+ return sorted(set(l))
hug/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"]
hug/lib/python3.12/site-packages/fontTools/svgLib/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (280 Bytes). View file
 
hug/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)
hug/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (3.06 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/arc.cpython-312.pyc ADDED
Binary file (6.58 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/parser.cpython-312.pyc ADDED
Binary file (9.89 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/svgLib/path/__pycache__/shapes.cpython-312.pyc ADDED
Binary file (11 kB). View file
 
hug/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
+ )
hug/lib/python3.12/site-packages/fontTools/svgLib/path/parser.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def pop_coord():
141
+ # A drawto command consumes a fixed number of coordinate tokens. A
142
+ # malformed path (a command with too few numbers) can run the token
143
+ # list dry; turn the resulting IndexError into a clear ValueError, like
144
+ # the parser's other errors, instead of a bare "pop from empty list".
145
+ try:
146
+ return elements.pop()
147
+ except IndexError:
148
+ raise ValueError(
149
+ "Not enough coordinates for command %r in path: %r" % (command, pathdef)
150
+ ) from None
151
+
152
+ while elements:
153
+ if elements[-1] in COMMANDS:
154
+ # New command.
155
+ last_command = command # Used by S and T
156
+ command = elements.pop()
157
+ absolute = command in UPPERCASE
158
+ command = command.upper()
159
+ else:
160
+ # If this element starts with numbers, it is an implicit command
161
+ # and we don't change the command. Check that it's allowed:
162
+ if command is None:
163
+ raise ValueError(
164
+ "Unallowed implicit command in %s, position %s"
165
+ % (pathdef, len(pathdef.split()) - len(elements))
166
+ )
167
+ last_command = command # Used by S and T
168
+
169
+ if command not in ("M", "Z") and not subpath_open and start_pos is not None:
170
+ # If a closepath is followed immediately by any other command,
171
+ # the next subpath starts at the same initial point as the
172
+ # current subpath:
173
+ # https://www.w3.org/TR/SVG11/paths.html#PathDataClosePathCommand
174
+ pen.moveTo((start_pos.real, start_pos.imag))
175
+ subpath_open = True
176
+
177
+ if command == "M":
178
+ # Moveto command.
179
+ x = pop_coord()
180
+ y = pop_coord()
181
+ pos = float(x) + float(y) * 1j
182
+ if absolute:
183
+ current_pos = pos
184
+ else:
185
+ current_pos += pos
186
+
187
+ # M is not preceded by Z; it's an open subpath
188
+ if subpath_open:
189
+ pen.endPath()
190
+
191
+ pen.moveTo((current_pos.real, current_pos.imag))
192
+
193
+ # when M is called, reset start_pos
194
+ # This behavior of Z is defined in svg spec:
195
+ # http://www.w3.org/TR/SVG/paths.html#PathDataClosePathCommand
196
+ start_pos = current_pos
197
+ subpath_open = True
198
+
199
+ # Implicit moveto commands are treated as lineto commands.
200
+ # So we set command to lineto here, in case there are
201
+ # further implicit commands after this moveto.
202
+ command = "L"
203
+
204
+ elif command == "Z":
205
+ # Close path
206
+ # A redundant Z with no open subpath (e.g. "M0,0 Z Z") is valid
207
+ # per the SVG path grammar and has no effect; ignore it instead
208
+ # of emitting a second closePath.
209
+ if subpath_open:
210
+ if not cmath.isclose(
211
+ current_pos, start_pos, rel_tol=1e-15, abs_tol=1e-15
212
+ ):
213
+ pen.lineTo((start_pos.real, start_pos.imag))
214
+ pen.closePath()
215
+ current_pos = start_pos
216
+ subpath_open = False
217
+ command = None # You can't have implicit commands after closing.
218
+
219
+ elif command == "L":
220
+ x = pop_coord()
221
+ y = pop_coord()
222
+ pos = float(x) + float(y) * 1j
223
+ if not absolute:
224
+ pos += current_pos
225
+ pen.lineTo((pos.real, pos.imag))
226
+ current_pos = pos
227
+
228
+ elif command == "H":
229
+ x = pop_coord()
230
+ pos = float(x) + current_pos.imag * 1j
231
+ if not absolute:
232
+ pos += current_pos.real
233
+ pen.lineTo((pos.real, pos.imag))
234
+ current_pos = pos
235
+
236
+ elif command == "V":
237
+ y = pop_coord()
238
+ pos = current_pos.real + float(y) * 1j
239
+ if not absolute:
240
+ pos += current_pos.imag * 1j
241
+ pen.lineTo((pos.real, pos.imag))
242
+ current_pos = pos
243
+
244
+ elif command == "C":
245
+ control1 = float(pop_coord()) + float(pop_coord()) * 1j
246
+ control2 = float(pop_coord()) + float(pop_coord()) * 1j
247
+ end = float(pop_coord()) + float(pop_coord()) * 1j
248
+
249
+ if not absolute:
250
+ control1 += current_pos
251
+ control2 += current_pos
252
+ end += current_pos
253
+
254
+ pen.curveTo(
255
+ (control1.real, control1.imag),
256
+ (control2.real, control2.imag),
257
+ (end.real, end.imag),
258
+ )
259
+ current_pos = end
260
+ last_control = control2
261
+
262
+ elif command == "S":
263
+ # Smooth curve. First control point is the "reflection" of
264
+ # the second control point in the previous path.
265
+
266
+ # last_command is None right after a closepath (Z is not C/S)
267
+ if last_command not in ("C", "S"):
268
+ # If there is no previous command or if the previous command
269
+ # was not an C, c, S or s, assume the first control point is
270
+ # coincident with the current point.
271
+ control1 = current_pos
272
+ else:
273
+ # The first control point is assumed to be the reflection of
274
+ # the second control point on the previous command relative
275
+ # to the current point.
276
+ control1 = current_pos + current_pos - last_control
277
+
278
+ control2 = float(pop_coord()) + float(pop_coord()) * 1j
279
+ end = float(pop_coord()) + float(pop_coord()) * 1j
280
+
281
+ if not absolute:
282
+ control2 += current_pos
283
+ end += current_pos
284
+
285
+ pen.curveTo(
286
+ (control1.real, control1.imag),
287
+ (control2.real, control2.imag),
288
+ (end.real, end.imag),
289
+ )
290
+ current_pos = end
291
+ last_control = control2
292
+
293
+ elif command == "Q":
294
+ control = float(pop_coord()) + float(pop_coord()) * 1j
295
+ end = float(pop_coord()) + float(pop_coord()) * 1j
296
+
297
+ if not absolute:
298
+ control += current_pos
299
+ end += current_pos
300
+
301
+ pen.qCurveTo((control.real, control.imag), (end.real, end.imag))
302
+ current_pos = end
303
+ last_control = control
304
+
305
+ elif command == "T":
306
+ # Smooth curve. Control point is the "reflection" of
307
+ # the second control point in the previous path.
308
+
309
+ # last_command is None right after a closepath (Z is not Q/T)
310
+ if last_command not in ("Q", "T"):
311
+ # If there is no previous command or if the previous command
312
+ # was not an Q, q, T or t, assume the first control point is
313
+ # coincident with the current point.
314
+ control = current_pos
315
+ else:
316
+ # The control point is assumed to be the reflection of
317
+ # the control point on the previous command relative
318
+ # to the current point.
319
+ control = current_pos + current_pos - last_control
320
+
321
+ end = float(pop_coord()) + float(pop_coord()) * 1j
322
+
323
+ if not absolute:
324
+ end += current_pos
325
+
326
+ pen.qCurveTo((control.real, control.imag), (end.real, end.imag))
327
+ current_pos = end
328
+ last_control = control
329
+
330
+ elif command == "A":
331
+ rx = abs(float(elements.pop()))
332
+ ry = abs(float(elements.pop()))
333
+ rotation = float(elements.pop())
334
+ arc_large = bool(int(elements.pop()))
335
+ arc_sweep = bool(int(elements.pop()))
336
+ end = float(elements.pop()) + float(elements.pop()) * 1j
337
+
338
+ if not absolute:
339
+ end += current_pos
340
+
341
+ # if the pen supports arcs, pass the values unchanged, otherwise
342
+ # approximate the arc with a series of cubic bezier curves
343
+ if have_arcTo:
344
+ pen.arcTo(
345
+ rx,
346
+ ry,
347
+ rotation,
348
+ arc_large,
349
+ arc_sweep,
350
+ (end.real, end.imag),
351
+ )
352
+ else:
353
+ arc = arc_class(
354
+ current_pos, rx, ry, rotation, arc_large, arc_sweep, end
355
+ )
356
+ arc.draw(pen)
357
+
358
+ current_pos = end
359
+
360
+ # no final Z command, it's an open path
361
+ if subpath_open:
362
+ pen.endPath()
hug/lib/python3.12/site-packages/fontTools/svgLib/path/shapes.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+
4
+ def _prefer_non_zero(*args):
5
+ for arg in args:
6
+ if arg != 0:
7
+ return arg
8
+ return 0.0
9
+
10
+
11
+ def _ntos(n):
12
+ # %f likes to add unnecessary 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
hug/lib/python3.12/site-packages/fontTools/t1Lib/__init__.py ADDED
@@ -0,0 +1,648 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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")]
hug/lib/python3.12/site-packages/fontTools/t1Lib/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (26.7 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/tfmLib.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
hug/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.ttCollection import TTCollection
hug/lib/python3.12/site-packages/fontTools/ttLib/__main__.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from fontTools.ttLib import OPTIMIZE_FONT_SPEED, TTLibError, TTLibFileIsCollectionError
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", "GLYF", "gvar", "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())
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (1.45 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/__main__.cpython-312.pyc ADDED
Binary file (5.42 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/beyond64k.cpython-312.pyc ADDED
Binary file (42.1 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/macUtils.cpython-312.pyc ADDED
Binary file (2.71 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/removeOverlaps.cpython-312.pyc ADDED
Binary file (15.7 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/reorderGlyphs.cpython-312.pyc ADDED
Binary file (14.6 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/scaleUpem.cpython-312.pyc ADDED
Binary file (20.1 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/sfnt.cpython-312.pyc ADDED
Binary file (33.8 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/standardGlyphOrder.cpython-312.pyc ADDED
Binary file (2.34 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttCollection.cpython-312.pyc ADDED
Binary file (10.9 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttFont.cpython-312.pyc ADDED
Binary file (88.4 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttGlyphSet.cpython-312.pyc ADDED
Binary file (28.7 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/ttVisitor.cpython-312.pyc ADDED
Binary file (1.68 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/__pycache__/woff2.cpython-312.pyc ADDED
Binary file (73.1 kB). View file
 
hug/lib/python3.12/site-packages/fontTools/ttLib/beyond64k.py ADDED
@@ -0,0 +1,1014 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert between Open Font Format beyond-64k companion tables.
2
+
3
+ The Open Font Format beyond-64k specification adds uppercase companion tables and
4
+ extended Layout formats that can address glyph IDs above 65535. This module
5
+ provides helpers to convert a :class:`fontTools.ttLib.TTFont` in place between
6
+ the compact lowercase table family and the extended uppercase table family.
7
+
8
+ The high-level APIs are :func:`upper_tables` and :func:`lower_tables`. By
9
+ default they convert every known table present in the font and validate that
10
+ the result does not mix lowercase and uppercase companion tables. Both helpers
11
+ accept an optional ``tables`` iterable; each entry may use either the compact or
12
+ extended spelling, e.g. ``"glyf"`` and ``"GLYF"`` both identify the glyph table
13
+ family.
14
+
15
+ The module is also available as a command-line tool::
16
+
17
+ fonttools ttLib.beyond64k upper input.ttf -o upper.ttf
18
+ fonttools ttLib.beyond64k lower upper.ttf -o lower.ttf
19
+ fonttools ttLib.beyond64k upper input.ttf GSUB GPOS glyf
20
+
21
+ Lowering validates lossy cases such as ``MAXP.numGlyphs`` values above 65535,
22
+ ``GLYF`` glyphs with cubic outlines, and component glyph IDs that do not fit in
23
+ the compact ``glyf`` table.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ from collections.abc import Iterable
30
+ from contextlib import contextmanager
31
+ from dataclasses import dataclass
32
+ from typing import Callable
33
+
34
+ from fontTools.misc.cliTools import makeOutputFileName
35
+ from fontTools.ttLib import TTFont, TTLibError, newTable
36
+ from fontTools.ttLib.tables import otTables
37
+ from fontTools.ttLib.tables.otTraverse import dfs_base_table
38
+
39
+ _TABLE_PAIRS = {
40
+ "glyf": "GLYF",
41
+ "loca": "LOCA",
42
+ "maxp": "MAXP",
43
+ "hhea": "HHEA",
44
+ "hmtx": "HMTX",
45
+ "vhea": "VHEA",
46
+ "vmtx": "VMTX",
47
+ "gvar": "GVAR",
48
+ }
49
+ _TABLE_IDENTITIES = {
50
+ tag: lower for lower, upper in _TABLE_PAIRS.items() for tag in (lower, upper)
51
+ }
52
+ _TABLE_IDENTITIES.update(
53
+ {
54
+ "BASE": "BASE",
55
+ "COLR": "COLR",
56
+ "GDEF": "GDEF",
57
+ "GPOS": "GPOS",
58
+ "GSUB": "GSUB",
59
+ "JSTF": "JSTF",
60
+ "VORG": "VORG",
61
+ }
62
+ )
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class _TableConversion:
67
+ destination: str
68
+ transform: Callable | None = None
69
+
70
+
71
+ _EXPLICIT_LAYOUT_FORMATS = {
72
+ (otTables.BaseCoord, 2): (4, {}),
73
+ (otTables.SinglePos, 1): (3, {}),
74
+ (otTables.SinglePos, 2): (4, {}),
75
+ (otTables.PairPos, 1): (
76
+ 3,
77
+ {
78
+ otTables.PairSet: otTables.PairSet2,
79
+ otTables.PairValueRecord: otTables.PairValue2,
80
+ },
81
+ ),
82
+ (otTables.PairPos, 2): (4, {}),
83
+ (otTables.CursivePos, 1): (
84
+ 2,
85
+ {otTables.EntryExitRecord: otTables.EntryExit2},
86
+ ),
87
+ (otTables.MarkBasePos, 1): (
88
+ 2,
89
+ {
90
+ otTables.MarkArray: otTables.MarkArray2,
91
+ otTables.MarkRecord: otTables.MarkRecord2,
92
+ otTables.BaseArray: otTables.BaseArray2,
93
+ otTables.BaseRecord: otTables.BaseRecord2,
94
+ },
95
+ ),
96
+ (otTables.MarkLigPos, 1): (
97
+ 2,
98
+ {
99
+ otTables.MarkArray: otTables.MarkArray2,
100
+ otTables.MarkRecord: otTables.MarkRecord2,
101
+ otTables.LigatureArray: otTables.LigatureArray2,
102
+ otTables.LigatureAttach: otTables.LigatureAttach2,
103
+ otTables.ComponentRecord: otTables.ComponentRecord2,
104
+ },
105
+ ),
106
+ (otTables.MarkMarkPos, 1): (
107
+ 2,
108
+ {
109
+ otTables.MarkArray: otTables.MarkArray2,
110
+ otTables.MarkRecord: otTables.MarkRecord2,
111
+ otTables.Mark2Array: otTables.Mark2Array2,
112
+ otTables.Mark2Record: otTables.Mark2Record2,
113
+ },
114
+ ),
115
+ (otTables.ReverseChainSingleSubst, 1): (2, {}),
116
+ }
117
+
118
+
119
+ def _contextual_layout_conversion(
120
+ table_type, compact_format, lookup_prefix, chaining=False
121
+ ):
122
+ compact_prefix = ("Chain" if chaining else "") + lookup_prefix[:3]
123
+ class_based = compact_format == 2
124
+ compact_rule = compact_prefix + ("ClassRule" if class_based else "Rule")
125
+ compact_rule_set = compact_prefix + ("ClassSet" if class_based else "RuleSet")
126
+ extended_rule = ("Chained" if chaining else "") + (
127
+ "ClassSeqRule" if class_based else "SeqRule"
128
+ )
129
+ extended_rule_set = extended_rule + "Set"
130
+ lookup_count = lookup_prefix + "Count"
131
+ lookup_record = lookup_prefix + "LookupRecord"
132
+ replacements = {getattr(otTables, lookup_record): (otTables.SeqLookup, {})}
133
+ outer_renames = {
134
+ lookup_count: "SeqLookupCount",
135
+ lookup_record: "SeqLookupRecord",
136
+ }
137
+
138
+ if compact_format in (1, 2):
139
+ replacements[getattr(otTables, compact_rule_set)] = (
140
+ getattr(otTables, extended_rule_set + "2"),
141
+ {
142
+ compact_rule + "Count": extended_rule + "Count",
143
+ compact_rule: extended_rule,
144
+ },
145
+ )
146
+ rule_renames = {
147
+ lookup_count: "SeqLookupCount",
148
+ lookup_record: "SeqLookupRecord",
149
+ }
150
+ if chaining:
151
+ rule_renames.update(
152
+ {
153
+ "Backtrack": "BacktrackSequence",
154
+ "Input": "InputSequence",
155
+ "LookAhead": "LookAheadSequence",
156
+ }
157
+ )
158
+ else:
159
+ rule_renames["Class" if class_based else "Input"] = "InputSequence"
160
+ replacements[getattr(otTables, compact_rule)] = (
161
+ getattr(otTables, extended_rule + ("" if class_based else "2")),
162
+ rule_renames,
163
+ )
164
+ outer_renames = {
165
+ compact_rule_set + "Count": extended_rule_set + "Count",
166
+ compact_rule_set: extended_rule_set,
167
+ }
168
+
169
+ return table_type, compact_format, compact_format + 3, outer_renames, replacements
170
+
171
+
172
+ _CONTEXTUAL_LAYOUT_FORMATS = {
173
+ (table_type, compact_format): (extended_format, outer_renames, replacements)
174
+ for (
175
+ table_type,
176
+ compact_format,
177
+ extended_format,
178
+ outer_renames,
179
+ replacements,
180
+ ) in (
181
+ *(
182
+ _contextual_layout_conversion(otTables.ContextSubst, format, "Subst")
183
+ for format in (1, 2, 3)
184
+ ),
185
+ *(
186
+ _contextual_layout_conversion(otTables.ContextPos, format, "Pos")
187
+ for format in (1, 2, 3)
188
+ ),
189
+ *(
190
+ _contextual_layout_conversion(
191
+ otTables.ChainContextSubst, format, "Subst", chaining=True
192
+ )
193
+ for format in (1, 2)
194
+ ),
195
+ *(
196
+ _contextual_layout_conversion(
197
+ otTables.ChainContextPos, format, "Pos", chaining=True
198
+ )
199
+ for format in (1, 2)
200
+ ),
201
+ )
202
+ }
203
+
204
+
205
+ def _rename_layout_attributes(table, renames):
206
+ for source, destination in renames.items():
207
+ if hasattr(table, source):
208
+ setattr(table, destination, getattr(table, source))
209
+ delattr(table, source)
210
+
211
+
212
+ def _replace_layout_subtree(table, replacements):
213
+ for path in reversed(list(dfs_base_table(table))):
214
+ subtable = path[-1].value
215
+ replacement_type, renames = replacements.get(
216
+ type(subtable), (type(subtable), {})
217
+ )
218
+ _rename_layout_attributes(subtable, renames)
219
+ if replacement_type is type(subtable):
220
+ continue
221
+ replacement = replacement_type()
222
+ replacement.__dict__.update(subtable.__dict__)
223
+ parent = path[-2].value
224
+ entry = path[-1]
225
+ if entry.index is None:
226
+ setattr(parent, entry.name, replacement)
227
+ else:
228
+ getattr(parent, entry.name)[entry.index] = replacement
229
+
230
+
231
+ def _replace_layout_classes(table, replacements):
232
+ for path in reversed(list(dfs_base_table(table))):
233
+ subtable = path[-1].value
234
+ replacement_type = replacements.get(type(subtable))
235
+ if replacement_type is None:
236
+ continue
237
+ replacement = replacement_type()
238
+ replacement.__dict__.update(subtable.__dict__)
239
+ parent = path[-2].value
240
+ entry = path[-1]
241
+ if entry.index is None:
242
+ setattr(parent, entry.name, replacement)
243
+ else:
244
+ getattr(parent, entry.name)[entry.index] = replacement
245
+
246
+
247
+ def _convert_contextual_layout_formats(table, extended):
248
+ conversions = _CONTEXTUAL_LAYOUT_FORMATS
249
+ if not extended:
250
+ conversions = {
251
+ (table_type, extended_format): (
252
+ compact_format,
253
+ {destination: source for source, destination in outer_renames.items()},
254
+ {
255
+ extended_type: (
256
+ compact_type,
257
+ {
258
+ destination: source
259
+ for source, destination in renames.items()
260
+ },
261
+ )
262
+ for compact_type, (extended_type, renames) in replacements.items()
263
+ },
264
+ )
265
+ for (table_type, compact_format), (
266
+ extended_format,
267
+ outer_renames,
268
+ replacements,
269
+ ) in conversions.items()
270
+ }
271
+
272
+ changed = False
273
+ for path in dfs_base_table(table):
274
+ subtable = path[-1].value
275
+ conversion = conversions.get(
276
+ (type(subtable), getattr(subtable, "Format", None))
277
+ )
278
+ if conversion is None:
279
+ continue
280
+ format, outer_renames, replacements = conversion
281
+ _replace_layout_subtree(subtable, replacements)
282
+ _rename_layout_attributes(subtable, outer_renames)
283
+ subtable.Format = format
284
+ changed = True
285
+ return changed
286
+
287
+
288
+ def _convert_explicit_layout_formats(table, extended):
289
+ conversions = _EXPLICIT_LAYOUT_FORMATS
290
+ if not extended:
291
+ conversions = {
292
+ (table_type, extended_format): (
293
+ compact_format,
294
+ {extended: compact for compact, extended in replacements.items()},
295
+ )
296
+ for (table_type, compact_format), (
297
+ extended_format,
298
+ replacements,
299
+ ) in conversions.items()
300
+ }
301
+
302
+ changed = False
303
+ for path in dfs_base_table(table):
304
+ subtable = path[-1].value
305
+ conversion = conversions.get(
306
+ (type(subtable), getattr(subtable, "Format", None))
307
+ )
308
+ if conversion is None:
309
+ continue
310
+ subtable.Format, replacements = conversion
311
+ _replace_layout_classes(subtable, replacements)
312
+ changed = True
313
+ return changed
314
+
315
+
316
+ def _convert_layout_formats(table, extended):
317
+ contextual = _convert_contextual_layout_formats(table, extended)
318
+ explicit = _convert_explicit_layout_formats(table, extended)
319
+ return contextual or explicit
320
+
321
+
322
+ def _convert_table_object(table, table_type):
323
+ table.ensureDecompiled()
324
+ converted = table_type()
325
+ converted.__dict__.update(table.__dict__)
326
+ return converted
327
+
328
+
329
+ def _move_fields(table, names, extended, overwrite):
330
+ for name in names:
331
+ compact_name = name
332
+ extended_name = name + "2"
333
+ source_name, destination_name = (
334
+ (compact_name, extended_name) if extended else (extended_name, compact_name)
335
+ )
336
+ source = getattr(table, source_name, None)
337
+ destination = getattr(table, destination_name, None)
338
+ if source is not None and destination is not None and not overwrite:
339
+ raise ValueError(
340
+ f"Both {source_name!r} and {destination_name!r} exist; "
341
+ "set overwrite=True to replace the destination"
342
+ )
343
+ if source is not None:
344
+ setattr(table, destination_name, source)
345
+ setattr(table, source_name, None)
346
+
347
+
348
+ def _upper_gdef(font, table, overwrite):
349
+ table = table.table
350
+ _move_fields(
351
+ table,
352
+ (
353
+ "GlyphClassDef",
354
+ "AttachList",
355
+ "LigCaretList",
356
+ "MarkAttachClassDef",
357
+ "MarkGlyphSetsDef",
358
+ ),
359
+ True,
360
+ overwrite,
361
+ )
362
+ if getattr(table, "LigCaretList2", None) is not None:
363
+ table.LigCaretList2 = _convert_table_object(
364
+ table.LigCaretList2, otTables.LigCaretList2
365
+ )
366
+ table.Version = max(table.Version, 0x00010004)
367
+ _convert_layout_formats(table, True)
368
+
369
+
370
+ def _lower_gdef(font, table, overwrite):
371
+ table = table.table
372
+ _move_fields(
373
+ table,
374
+ (
375
+ "GlyphClassDef",
376
+ "AttachList",
377
+ "LigCaretList",
378
+ "MarkAttachClassDef",
379
+ "MarkGlyphSetsDef",
380
+ ),
381
+ False,
382
+ overwrite,
383
+ )
384
+ if getattr(table, "LigCaretList", None) is not None:
385
+ table.LigCaretList = _convert_table_object(
386
+ table.LigCaretList, otTables.LigCaretList
387
+ )
388
+ if getattr(table, "VarStore", None) is not None:
389
+ table.Version = 0x00010003
390
+ elif getattr(table, "MarkGlyphSetsDef", None) is not None:
391
+ table.Version = 0x00010002
392
+ else:
393
+ table.Version = 0x00010000
394
+ _convert_layout_formats(table, False)
395
+
396
+
397
+ def _upper_layout_formats(font, table, overwrite):
398
+ _convert_layout_formats(table.table, True)
399
+
400
+
401
+ def _lower_layout_formats(font, table, overwrite):
402
+ _convert_layout_formats(table.table, False)
403
+
404
+
405
+ def _upper_jstf(font, table, overwrite):
406
+ table = table.table
407
+ _replace_layout_subtree(
408
+ table,
409
+ {
410
+ otTables.JstfScriptRecord: (otTables.JstfScriptRecord2, {}),
411
+ otTables.JstfScript: (otTables.JstfScript2, {}),
412
+ otTables.ExtenderGlyph: (otTables.ExtenderGlyph2, {}),
413
+ },
414
+ )
415
+ _rename_layout_attributes(
416
+ table,
417
+ {
418
+ "JstfScriptCount": "JstfScriptCount2",
419
+ "JstfScriptRecord": "JstfScriptRecord2",
420
+ },
421
+ )
422
+ table.Version = max(table.Version, 0x00010001)
423
+
424
+
425
+ def _lower_jstf(font, table, overwrite):
426
+ table = table.table
427
+ _replace_layout_subtree(
428
+ table,
429
+ {
430
+ otTables.JstfScriptRecord2: (otTables.JstfScriptRecord, {}),
431
+ otTables.JstfScript2: (otTables.JstfScript, {}),
432
+ otTables.ExtenderGlyph2: (otTables.ExtenderGlyph, {}),
433
+ },
434
+ )
435
+ _rename_layout_attributes(
436
+ table,
437
+ {
438
+ "JstfScriptCount2": "JstfScriptCount",
439
+ "JstfScriptRecord2": "JstfScriptRecord",
440
+ },
441
+ )
442
+ table.Version = 0x00010000
443
+
444
+
445
+ def _upper_layout_header(font, table, overwrite):
446
+ table = table.table
447
+ _move_fields(table, ("ScriptList", "FeatureList", "LookupList"), True, overwrite)
448
+ if getattr(table, "LookupList2", None) is not None:
449
+ table.LookupList2 = _convert_table_object(
450
+ table.LookupList2, otTables.LookupList2
451
+ )
452
+ table.Version = max(table.Version, 0x00010002)
453
+ _convert_layout_formats(table, True)
454
+
455
+
456
+ def _lower_layout_header(font, table, overwrite):
457
+ table = table.table
458
+ _move_fields(table, ("ScriptList", "FeatureList", "LookupList"), False, overwrite)
459
+ if getattr(table, "LookupList", None) is not None:
460
+ table.LookupList = _convert_table_object(table.LookupList, otTables.LookupList)
461
+ table.Version = (
462
+ 0x00010001 if getattr(table, "FeatureVariations", None) else 0x00010000
463
+ )
464
+ _convert_layout_formats(table, False)
465
+
466
+
467
+ def _has_extended_layout_formats(table):
468
+ # The dispatch formats live on lookup subtables, including those wrapped
469
+ # by extension lookups. Avoid descending through every rule/value record
470
+ # merely to discover that an ordinary compact font needs no conversion.
471
+ lookup_list = getattr(table, "LookupList", None)
472
+ if lookup_list is None:
473
+ return False
474
+ extended_formats = {
475
+ (table_type, conversion[0])
476
+ for conversions in (_CONTEXTUAL_LAYOUT_FORMATS, _EXPLICIT_LAYOUT_FORMATS)
477
+ for (table_type, _), conversion in conversions.items()
478
+ }
479
+ for lookup in lookup_list.Lookup:
480
+ for subtable in lookup.SubTable:
481
+ if isinstance(subtable, (otTables.ExtensionSubst, otTables.ExtensionPos)):
482
+ subtable = subtable.ExtSubTable
483
+ if (type(subtable), getattr(subtable, "Format", None)) in extended_formats:
484
+ return True
485
+ return False
486
+
487
+
488
+ @contextmanager
489
+ def _compact_layout_tables(font, *, restore=True):
490
+ # Use compact in-memory layouts for algorithms that dispatch on them.
491
+ # No compact serialization occurs here: glyph IDs and counts stay intact.
492
+ restore_actions = []
493
+ try:
494
+ for tag, version, lower, upper in (
495
+ ("GDEF", 0x00010004, _lower_gdef, _upper_gdef),
496
+ ("GSUB", 0x00010002, _lower_layout_header, _upper_layout_header),
497
+ ("GPOS", 0x00010002, _lower_layout_header, _upper_layout_header),
498
+ ):
499
+ if tag not in font:
500
+ continue
501
+ table = font[tag]
502
+ if table.table.Version >= version:
503
+ restore_actions.append((tag, upper))
504
+ lower(font, table, True)
505
+ elif _has_extended_layout_formats(table.table):
506
+ _convert_layout_formats(table.table, False)
507
+ restore_actions.append((tag, None))
508
+ yield
509
+ finally:
510
+ for tag, upper in restore_actions if restore else ():
511
+ if tag not in font:
512
+ continue
513
+ if upper is not None:
514
+ upper(font, font[tag], True)
515
+ else:
516
+ _convert_layout_formats(font[tag].table, True)
517
+
518
+
519
+ def _lower_glyf(font, table, overwrite):
520
+ from fontTools.ttLib.tables._g_l_y_f import flagCubic
521
+
522
+ # Validation has rejected active or hinted CUBIC bits. Explicit lowering
523
+ # may discard the remaining inert bits on unhinted on-curve points.
524
+ for glyph_name in font.getGlyphOrder():
525
+ glyph = table[glyph_name]
526
+ if hasattr(glyph, "flags"):
527
+ for i, flag in enumerate(glyph.flags):
528
+ glyph.flags[i] = flag & ~flagCubic
529
+
530
+
531
+ def _upper_vorg(font, table, overwrite):
532
+ table.majorVersion = 2
533
+ table.minorVersion = 0
534
+
535
+
536
+ def _lower_vorg(font, table, overwrite):
537
+ table.majorVersion = 1
538
+ table.minorVersion = 0
539
+
540
+
541
+ def _iter_colr_paints(table):
542
+ if not hasattr(table, "table"):
543
+ return
544
+ for path in dfs_base_table(table.table):
545
+ value = path[-1].value
546
+ if isinstance(value, otTables.Paint):
547
+ yield value
548
+
549
+
550
+ def _upper_colr(font, table, overwrite):
551
+ for paint in _iter_colr_paints(table):
552
+ if paint.Format == otTables.PaintFormat.PaintGlyph:
553
+ paint.Format = otTables.PaintFormat.PaintGlyph2
554
+
555
+
556
+ def _lower_colr(font, table, overwrite):
557
+ for paint in _iter_colr_paints(table):
558
+ if paint.Format == otTables.PaintFormat.PaintGlyph2:
559
+ paint.Format = otTables.PaintFormat.PaintGlyph
560
+
561
+
562
+ _UPPER_TABLES = {
563
+ **{
564
+ source: _TableConversion(destination)
565
+ for source, destination in _TABLE_PAIRS.items()
566
+ },
567
+ "BASE": _TableConversion("BASE", _upper_layout_formats),
568
+ "COLR": _TableConversion("COLR", _upper_colr),
569
+ "GDEF": _TableConversion("GDEF", _upper_gdef),
570
+ "GSUB": _TableConversion("GSUB", _upper_layout_header),
571
+ "GPOS": _TableConversion("GPOS", _upper_layout_header),
572
+ "JSTF": _TableConversion("JSTF", _upper_jstf),
573
+ "VORG": _TableConversion("VORG", _upper_vorg),
574
+ }
575
+ _LOWER_TABLES = {
576
+ **{upper: _TableConversion(lower) for lower, upper in _TABLE_PAIRS.items()},
577
+ "GLYF": _TableConversion("glyf", _lower_glyf),
578
+ "BASE": _TableConversion("BASE", _lower_layout_formats),
579
+ "COLR": _TableConversion("COLR", _lower_colr),
580
+ "GDEF": _TableConversion("GDEF", _lower_gdef),
581
+ "GSUB": _TableConversion("GSUB", _lower_layout_header),
582
+ "GPOS": _TableConversion("GPOS", _lower_layout_header),
583
+ "JSTF": _TableConversion("JSTF", _lower_jstf),
584
+ "VORG": _TableConversion("VORG", _lower_vorg),
585
+ }
586
+
587
+
588
+ def _normalize_tables(tables: Iterable[str] | None) -> set[str]:
589
+ if tables is None:
590
+ return set(_TABLE_IDENTITIES.values())
591
+
592
+ normalized = set()
593
+ for tag in tables:
594
+ try:
595
+ normalized.add(_TABLE_IDENTITIES[tag])
596
+ except KeyError:
597
+ raise ValueError(f"Unsupported beyond-64k table: {tag!r}") from None
598
+ return normalized
599
+
600
+
601
+ def _validate_family(font: TTFont) -> None:
602
+ lower = sorted(tag for tag in _TABLE_PAIRS if tag in font)
603
+ upper = sorted(tag for tag in _TABLE_PAIRS.values() if tag in font)
604
+ if lower and upper:
605
+ raise ValueError(
606
+ "Mixed beyond-64k table family: "
607
+ f"lowercase {', '.join(lower)}; uppercase {', '.join(upper)}"
608
+ )
609
+
610
+
611
+ def _validate_lowering(font: TTFont, conversions: dict[str, _TableConversion]) -> None:
612
+ if "GLYF" in conversions and "GLYF" in font:
613
+ from fontTools.ttLib.tables._g_l_y_f import flagCubic, flagOnCurve
614
+
615
+ glyf = font["GLYF"]
616
+ for glyph_name in font.getGlyphOrder():
617
+ glyph = glyf[glyph_name]
618
+ if glyph.isComposite():
619
+ for component in glyph.components:
620
+ if font.getGlyphID(component.glyphName) > 0xFFFF:
621
+ raise ValueError(
622
+ f"GLYF component {component.glyphName!r} does not fit in glyf"
623
+ )
624
+ else:
625
+ cubic_flags = [
626
+ flag for flag in getattr(glyph, "flags", ()) if flag & flagCubic
627
+ ]
628
+ program = getattr(glyph, "program", None)
629
+ # Hinting can flip an on-curve point and activate its CUBIC bit.
630
+ if cubic_flags and (
631
+ any(not flag & flagOnCurve for flag in cubic_flags)
632
+ or (program and program.getBytecode())
633
+ ):
634
+ raise ValueError(
635
+ f"GLYF glyph {glyph_name!r} has cubic outlines or hinted CUBIC flags"
636
+ )
637
+ if "MAXP" in conversions and "MAXP" in font and font["MAXP"].numGlyphs > 0xFFFF:
638
+ raise ValueError("MAXP.numGlyphs does not fit in maxp")
639
+ if "HHEA" in conversions and "HHEA" in font:
640
+ if font["HHEA"].numberOfHMetrics > 0xFFFF:
641
+ raise ValueError("HHEA.numberOfHMetrics does not fit in hhea")
642
+ if "VHEA" in conversions and "VHEA" in font:
643
+ if font["VHEA"].numberOfVMetrics > 0xFFFF:
644
+ raise ValueError("VHEA.numberOfVMetrics does not fit in vhea")
645
+ if "VORG" in conversions and "VORG" in font:
646
+ vorg = font["VORG"]
647
+ if len(vorg.VOriginRecords) > 0xFFFF:
648
+ raise ValueError("VORG record count does not fit in version 1")
649
+ for glyph_name in vorg.VOriginRecords:
650
+ if font.getGlyphID(glyph_name) > 0xFFFF:
651
+ raise ValueError(f"VORG glyph {glyph_name!r} does not fit in version 1")
652
+ if "COLR" in conversions and "COLR" in font:
653
+ for paint in _iter_colr_paints(font["COLR"]):
654
+ if (
655
+ paint.Format == otTables.PaintFormat.PaintGlyph2
656
+ and font.getGlyphID(paint.Glyph) > 0xFFFF
657
+ ):
658
+ raise ValueError(
659
+ f"COLR PaintGlyph2 glyph {paint.Glyph!r} does not fit in PaintGlyph"
660
+ )
661
+ _validate_cmap_uvs_lowering(font)
662
+
663
+
664
+ def _cmap_subtable_key(subtable) -> tuple[int, int, int]:
665
+ return subtable.platformID, subtable.platEncID, subtable.language
666
+
667
+
668
+ def _merge_uvs_dict(destination, source) -> None:
669
+ for selector, entries in source.items():
670
+ merged = dict(destination.get(selector, ()))
671
+ merged.update(entries)
672
+ destination[selector] = sorted(merged.items())
673
+
674
+
675
+ def _copy_uvs_subtable(format: int, source):
676
+ from fontTools.ttLib.tables._c_m_a_p import CmapSubtable
677
+
678
+ subtable = CmapSubtable.newSubtable(format)
679
+ subtable.platformID = source.platformID
680
+ subtable.platEncID = source.platEncID
681
+ subtable.language = source.language
682
+ subtable.cmap = {}
683
+ subtable.uvsDict = {
684
+ selector: list(entries) for selector, entries in source.uvsDict.items()
685
+ }
686
+ return subtable
687
+
688
+
689
+ def _uvs_has_high_glyph_id(font: TTFont, subtable) -> bool:
690
+ subtable.ensureDecompiled()
691
+ for entries in subtable.uvsDict.values():
692
+ for _, glyph_name in entries:
693
+ if glyph_name is not None and font.getGlyphID(glyph_name) > 0xFFFF:
694
+ return True
695
+ return False
696
+
697
+
698
+ def _character_map_tables(font: TTFont):
699
+ for tag in ("cmap", "DMAP"):
700
+ if tag in font:
701
+ yield tag, font[tag]
702
+
703
+
704
+ def _validate_cmap_uvs_lowering(font: TTFont) -> None:
705
+ for tag, character_map in _character_map_tables(font):
706
+ for subtable in character_map.tables:
707
+ if subtable.format == 15 and _uvs_has_high_glyph_id(font, subtable):
708
+ raise ValueError(f"{tag} format 15 glyph IDs do not fit in format 14")
709
+
710
+
711
+ def _upper_beyond64k_cmap_uvs(font: TTFont) -> None:
712
+ for _, character_map in _character_map_tables(font):
713
+ format15_by_key = {
714
+ _cmap_subtable_key(subtable): subtable
715
+ for subtable in character_map.tables
716
+ if subtable.format == 15
717
+ }
718
+ tables = []
719
+ for subtable in character_map.tables:
720
+ if subtable.format == 14 and _uvs_has_high_glyph_id(font, subtable):
721
+ key = _cmap_subtable_key(subtable)
722
+ format15 = format15_by_key.get(key)
723
+ if format15 is None:
724
+ format15 = _copy_uvs_subtable(15, subtable)
725
+ format15_by_key[key] = format15
726
+ tables.append(format15)
727
+ else:
728
+ format15.ensureDecompiled()
729
+ _merge_uvs_dict(format15.uvsDict, subtable.uvsDict)
730
+ continue
731
+ tables.append(subtable)
732
+ character_map.tables = tables
733
+
734
+
735
+ def _lower_beyond64k_cmap_uvs(font: TTFont) -> None:
736
+ for tag, character_map in _character_map_tables(font):
737
+ format14_by_key = {
738
+ _cmap_subtable_key(subtable): subtable
739
+ for subtable in character_map.tables
740
+ if subtable.format == 14
741
+ }
742
+ tables = []
743
+ for subtable in character_map.tables:
744
+ if subtable.format == 15:
745
+ if _uvs_has_high_glyph_id(font, subtable):
746
+ raise ValueError(
747
+ f"{tag} format 15 glyph IDs do not fit in format 14"
748
+ )
749
+ key = _cmap_subtable_key(subtable)
750
+ format14 = format14_by_key.get(key)
751
+ if format14 is None:
752
+ format14 = _copy_uvs_subtable(14, subtable)
753
+ format14_by_key[key] = format14
754
+ tables.append(format14)
755
+ else:
756
+ format14.ensureDecompiled()
757
+ _merge_uvs_dict(format14.uvsDict, subtable.uvsDict)
758
+ continue
759
+ tables.append(subtable)
760
+ character_map.tables = tables
761
+
762
+
763
+ def _drop_beyond64k_cmap_format4(font: TTFont) -> None:
764
+ if (
765
+ not any(tag in font for tag in ("cmap", "DMAP"))
766
+ or len(font.getGlyphOrder()) <= 0x10000
767
+ ):
768
+ return
769
+
770
+ for _, character_map in _character_map_tables(font):
771
+ unicode_bmp_tables = [
772
+ subtable
773
+ for subtable in character_map.tables
774
+ if subtable.format == 4 and subtable.isUnicode() and not subtable.isSymbol()
775
+ ]
776
+ if not unicode_bmp_tables:
777
+ continue
778
+ if not any(subtable.format == 12 for subtable in character_map.tables):
779
+ cmap12 = {}
780
+ for subtable in unicode_bmp_tables:
781
+ cmap12.update(subtable.cmap)
782
+ if cmap12:
783
+ from fontTools.ttLib.tables._c_m_a_p import CmapSubtable
784
+
785
+ subtable = CmapSubtable.newSubtable(12)
786
+ subtable.platformID = 3
787
+ subtable.platEncID = 10
788
+ subtable.language = 0
789
+ subtable.cmap = cmap12
790
+ character_map.tables.append(subtable)
791
+
792
+ character_map.tables = [
793
+ subtable
794
+ for subtable in character_map.tables
795
+ if subtable not in unicode_bmp_tables
796
+ ]
797
+
798
+
799
+ def _drop_beyond64k_post_glyph_names(font: TTFont) -> None:
800
+ # post 2.0 numberOfGlyphs is uint16: drop above 0xFFFF, not 0x10000.
801
+ if "post" not in font or len(font.getGlyphOrder()) <= 0xFFFF:
802
+ return
803
+
804
+ post = font["post"]
805
+ if post.formatType == 2.0:
806
+ post.formatType = 3.0
807
+ post.extraNames = []
808
+ post.mapping = {}
809
+
810
+
811
+ def _convert_table(
812
+ font: TTFont,
813
+ source,
814
+ source_tag: str,
815
+ conversion: _TableConversion,
816
+ overwrite: bool,
817
+ ) -> None:
818
+ destination_tag = conversion.destination
819
+ if conversion.transform is not None:
820
+ conversion.transform(font, source, overwrite)
821
+ if source_tag == destination_tag:
822
+ return
823
+ destination = newTable(destination_tag)
824
+ table_tag = destination.tableTag
825
+ destination.__dict__.update(source.__dict__)
826
+ destination.tableTag = table_tag
827
+ font[destination_tag] = destination
828
+ del font[source_tag]
829
+
830
+
831
+ def _convert_tables(
832
+ font: TTFont,
833
+ *,
834
+ tables: Iterable[str] | None,
835
+ table_conversions: dict[str, _TableConversion],
836
+ validate: bool,
837
+ overwrite: bool,
838
+ ignore_missing: bool,
839
+ validate_conversion=None,
840
+ ) -> None:
841
+ tables = _normalize_tables(tables)
842
+ conversions = {
843
+ source: conversion
844
+ for source, conversion in table_conversions.items()
845
+ if _TABLE_IDENTITIES[source] in tables
846
+ }
847
+ if validate_conversion is not None:
848
+ validate_conversion(font, conversions)
849
+
850
+ pending = []
851
+ for source_tag, conversion in conversions.items():
852
+ destination_tag = conversion.destination
853
+ source_exists = source_tag in font
854
+ destination_exists = destination_tag in font
855
+
856
+ if (
857
+ source_tag != destination_tag
858
+ and source_exists
859
+ and destination_exists
860
+ and not overwrite
861
+ ):
862
+ raise ValueError(
863
+ f"Both {source_tag!r} and {destination_tag!r} exist; "
864
+ "set overwrite=True to replace the destination"
865
+ )
866
+ if not source_exists:
867
+ if destination_exists or ignore_missing:
868
+ continue
869
+ raise KeyError(source_tag)
870
+ pending.append((source_tag, conversion))
871
+
872
+ if validate:
873
+ result_tags = set(font.keys())
874
+ for source_tag, conversion in pending:
875
+ destination_tag = conversion.destination
876
+ result_tags.discard(source_tag)
877
+ result_tags.add(destination_tag)
878
+ lower = sorted(tag for tag in _TABLE_PAIRS if tag in result_tags)
879
+ upper = sorted(tag for tag in _TABLE_PAIRS.values() if tag in result_tags)
880
+ if lower and upper:
881
+ raise ValueError(
882
+ "Conversion would create a mixed beyond-64k table family: "
883
+ f"lowercase {', '.join(lower)}; uppercase {', '.join(upper)}"
884
+ )
885
+
886
+ sources = {source_tag: font[source_tag] for source_tag, _ in pending}
887
+ for source_tag, conversion in pending:
888
+ _convert_table(font, sources[source_tag], source_tag, conversion, overwrite)
889
+
890
+ if validate:
891
+ _validate_family(font)
892
+
893
+
894
+ def upper_tables(
895
+ font: TTFont,
896
+ *,
897
+ tables: Iterable[str] | None = None,
898
+ validate: bool = True,
899
+ overwrite: bool = False,
900
+ ignore_missing: bool = True,
901
+ ) -> None:
902
+ """Convert selected tables to their beyond-64k companion forms.
903
+
904
+ Args:
905
+ font: Font to modify in place.
906
+ tables: Optional iterable of table tags to convert. If omitted, all
907
+ supported tables present in ``font`` are converted. Tags may use
908
+ either spelling of a companion table family, such as ``"glyf"`` or
909
+ ``"GLYF"``.
910
+ validate: If true, reject conversions that leave the font with a mixed
911
+ lowercase/uppercase companion table family.
912
+ overwrite: If true, replace an existing destination table. Otherwise an
913
+ existing destination raises ``ValueError``.
914
+ ignore_missing: If true, requested source tables that are not present
915
+ are ignored unless their destination is already present. Otherwise
916
+ missing source tables raise ``KeyError``.
917
+ """
918
+ _convert_tables(
919
+ font,
920
+ tables=tables,
921
+ table_conversions=_UPPER_TABLES,
922
+ validate=validate,
923
+ overwrite=overwrite,
924
+ ignore_missing=ignore_missing,
925
+ )
926
+ _upper_beyond64k_cmap_uvs(font)
927
+ _drop_beyond64k_cmap_format4(font)
928
+ _drop_beyond64k_post_glyph_names(font)
929
+
930
+
931
+ def lower_tables(
932
+ font: TTFont,
933
+ *,
934
+ tables: Iterable[str] | None = None,
935
+ validate: bool = True,
936
+ overwrite: bool = False,
937
+ ignore_missing: bool = True,
938
+ ) -> None:
939
+ """Convert selected tables from their beyond-64k companion forms.
940
+
941
+ Args are the same as :func:`upper_tables`. In addition to mixed-family
942
+ validation, lowering rejects data that cannot be represented in compact
943
+ tables, including glyph counts above 65535, cubic ``GLYF`` outlines, and
944
+ component glyph IDs that do not fit in ``glyf``.
945
+ """
946
+ _convert_tables(
947
+ font,
948
+ tables=tables,
949
+ table_conversions=_LOWER_TABLES,
950
+ validate=validate,
951
+ overwrite=overwrite,
952
+ ignore_missing=ignore_missing,
953
+ validate_conversion=_validate_lowering,
954
+ )
955
+ _lower_beyond64k_cmap_uvs(font)
956
+
957
+
958
+ def main(args=None):
959
+ parser = argparse.ArgumentParser(
960
+ "fonttools ttLib.beyond64k",
961
+ description=__doc__,
962
+ formatter_class=argparse.RawDescriptionHelpFormatter,
963
+ )
964
+ parser.add_argument(
965
+ "direction",
966
+ choices=("upper", "lower"),
967
+ help="'upper' converts to beyond-64k companions; 'lower' converts back",
968
+ )
969
+ parser.add_argument("input", metavar="INPUT", help="input font path")
970
+ parser.add_argument(
971
+ "tables",
972
+ metavar="TABLE",
973
+ nargs="*",
974
+ help="optional table tags to convert, e.g. GSUB GPOS glyf",
975
+ )
976
+ parser.add_argument("-o", "--output", metavar="OUTPUT", help="output font path")
977
+ parser.add_argument(
978
+ "--no-validate",
979
+ action="store_true",
980
+ help="skip mixed-family and lossy-lowering validation",
981
+ )
982
+ parser.add_argument(
983
+ "--overwrite",
984
+ action="store_true",
985
+ help="replace destination tables if they already exist",
986
+ )
987
+ parser.add_argument(
988
+ "--no-ignore-missing",
989
+ dest="ignore_missing",
990
+ action="store_false",
991
+ help="raise an error when a requested source table is missing",
992
+ )
993
+ options = parser.parse_args(args)
994
+
995
+ output = options.output or makeOutputFileName(
996
+ options.input, overWrite=True, suffix=f"-{options.direction}"
997
+ )
998
+ with TTFont(options.input) as font:
999
+ convert = upper_tables if options.direction == "upper" else lower_tables
1000
+ try:
1001
+ convert(
1002
+ font,
1003
+ tables=options.tables or None,
1004
+ validate=not options.no_validate,
1005
+ overwrite=options.overwrite,
1006
+ ignore_missing=options.ignore_missing,
1007
+ )
1008
+ except (KeyError, ValueError) as error:
1009
+ raise TTLibError(str(error)) from error
1010
+ font.save(output)
1011
+
1012
+
1013
+ if __name__ == "__main__":
1014
+ main()
hug/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
hug/lib/python3.12/site-packages/fontTools/ttLib/removeOverlaps.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Simplify TrueType glyphs by merging overlapping contours/components.
2
+
3
+ Requires https://github.com/fonttools/skia-pathops
4
+ """
5
+
6
+ import itertools
7
+ 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
+ glyfTag = "GLYF" if "GLYF" in font else "glyf"
194
+ hmtxTag = "HMTX" if glyfTag == "GLYF" else "hmtx"
195
+ glyfTable = font[glyfTag]
196
+ hmtxTable = font[hmtxTag]
197
+
198
+ # process all simple glyphs first, then composites with increasing component depth,
199
+ # so that by the time we test for component intersections the respective base glyphs
200
+ # have already been simplified
201
+ maxpValuesCache = {}
202
+ glyphNames = sorted(
203
+ glyphNames,
204
+ key=lambda name: (
205
+ (
206
+ glyfTable[name]
207
+ .getCompositeMaxpValues(glyfTable, maxpValuesCache=maxpValuesCache)
208
+ .maxComponentDepth
209
+ if glyfTable[name].isComposite()
210
+ else 0
211
+ ),
212
+ name,
213
+ ),
214
+ )
215
+ modified = set()
216
+ for glyphName in glyphNames:
217
+ try:
218
+ if removeTTGlyphOverlaps(
219
+ glyphName, glyphSet, glyfTable, hmtxTable, removeHinting
220
+ ):
221
+ modified.add(glyphName)
222
+ except RemoveOverlapsError:
223
+ if not ignoreErrors:
224
+ raise
225
+ log.error("Failed to remove overlaps for '%s'", glyphName)
226
+
227
+ log.debug("Removed overlaps for %s glyphs:\n%s", len(modified), " ".join(modified))
228
+
229
+
230
+ def _remove_charstring_overlaps(
231
+ *,
232
+ glyphName: str,
233
+ glyphSet: _TTGlyphMapping,
234
+ cffFontSet: CFFFontSet,
235
+ ) -> bool:
236
+ path = skPathFromGlyph(glyphName, glyphSet)
237
+
238
+ # remove overlaps
239
+ path2 = _simplify(path, glyphName, round=noRound)
240
+
241
+ # replace TTGlyph if simplified path is different (ignoring contour order)
242
+ if not _same_path(path, path2):
243
+ charStrings = cffFontSet[0].CharStrings
244
+ charStrings[glyphName] = _charString_from_SkPath(path2, charStrings[glyphName])
245
+ return True
246
+
247
+ return False
248
+
249
+
250
+ def _remove_cff_overlaps(
251
+ *,
252
+ font: ttFont.TTFont,
253
+ glyphNames: Iterable[str],
254
+ glyphSet: _TTGlyphMapping,
255
+ removeHinting: bool,
256
+ ignoreErrors: bool,
257
+ table_tag: str,
258
+ removeUnusedSubroutines: bool = True,
259
+ ) -> None:
260
+ cffFontSet = font[table_tag].cff
261
+ modified = set()
262
+ for glyphName in glyphNames:
263
+ try:
264
+ if _remove_charstring_overlaps(
265
+ glyphName=glyphName,
266
+ glyphSet=glyphSet,
267
+ cffFontSet=cffFontSet,
268
+ ):
269
+ modified.add(glyphName)
270
+ except RemoveOverlapsError:
271
+ if not ignoreErrors:
272
+ raise
273
+ log.error("Failed to remove overlaps for '%s'", glyphName)
274
+
275
+ if not modified:
276
+ log.debug("No overlaps found in the specified CFF glyphs")
277
+ return
278
+
279
+ if removeHinting:
280
+ cffFontSet.remove_hints()
281
+
282
+ if removeUnusedSubroutines:
283
+ cffFontSet.remove_unused_subroutines()
284
+
285
+ log.debug("Removed overlaps for %s glyphs:\n%s", len(modified), " ".join(modified))
286
+
287
+
288
+ def removeOverlaps(
289
+ font: ttFont.TTFont,
290
+ glyphNames: Optional[Iterable[str]] = None,
291
+ removeHinting: bool = True,
292
+ ignoreErrors: bool = False,
293
+ *,
294
+ removeUnusedSubroutines: bool = True,
295
+ ) -> None:
296
+ """Simplify glyphs in TTFont by merging overlapping contours.
297
+
298
+ Overlapping components are first decomposed to simple contours, then merged.
299
+
300
+ Currently this only works for fonts with 'glyf'/'GLYF', 'CFF ', or 'CFF2'
301
+ tables. Raises NotImplementedError if all of these tables are absent.
302
+
303
+ Note that removing overlaps invalidates the hinting. By default we drop hinting
304
+ from all glyphs whether or not overlaps are removed from a given one, as it would
305
+ look weird if only some glyphs are left (un)hinted.
306
+
307
+ Args:
308
+ font: input TTFont object, modified in place.
309
+ glyphNames: optional iterable of glyph names (str) to remove overlaps from.
310
+ By default, all glyphs in the font are processed.
311
+ removeHinting (bool): set to False to keep hinting for unmodified glyphs.
312
+ ignoreErrors (bool): set to True to ignore errors while removing overlaps,
313
+ thus keeping the tricky glyphs unchanged (fonttools/fonttools#2363).
314
+ removeUnusedSubroutines (bool): set to False to keep unused subroutines
315
+ in CFF table after removing overlaps. Default is to remove them if
316
+ any glyphs are modified.
317
+ """
318
+
319
+ if (
320
+ "glyf" not in font
321
+ and "GLYF" not in font
322
+ and "CFF " not in font
323
+ and "CFF2" not in font
324
+ ):
325
+ raise NotImplementedError(
326
+ "No outline data found in the font: missing 'glyf', 'GLYF', 'CFF ', or 'CFF2' table"
327
+ )
328
+
329
+ if glyphNames is None:
330
+ glyphNames = font.getGlyphOrder()
331
+
332
+ # Wraps the underlying glyphs, takes care of interfacing with drawing pens
333
+ glyphSet = font.getGlyphSet()
334
+
335
+ if "glyf" in font or "GLYF" in font:
336
+ _remove_glyf_overlaps(
337
+ font=font,
338
+ glyphNames=glyphNames,
339
+ glyphSet=glyphSet,
340
+ removeHinting=removeHinting,
341
+ ignoreErrors=ignoreErrors,
342
+ )
343
+
344
+ if "CFF " in font or "CFF2" in font:
345
+ _remove_cff_overlaps(
346
+ font=font,
347
+ glyphNames=glyphNames,
348
+ glyphSet=glyphSet,
349
+ removeHinting=removeHinting,
350
+ ignoreErrors=ignoreErrors,
351
+ table_tag="CFF " if "CFF " in font else "CFF2",
352
+ removeUnusedSubroutines=removeUnusedSubroutines,
353
+ )
354
+
355
+
356
+ def main(args=None):
357
+ """Simplify glyphs in TTFont by merging overlapping contours."""
358
+
359
+ import argparse
360
+
361
+ parser = argparse.ArgumentParser(
362
+ "fonttools ttLib.removeOverlaps", description=__doc__
363
+ )
364
+
365
+ parser.add_argument("input", metavar="INPUT.ttf", help="Input font file")
366
+ parser.add_argument("output", metavar="OUTPUT.ttf", help="Output font file")
367
+ parser.add_argument(
368
+ "glyphs",
369
+ metavar="GLYPHS",
370
+ nargs="*",
371
+ help="Optional list of glyph names to remove overlaps from",
372
+ )
373
+ parser.add_argument(
374
+ "--keep-hinting",
375
+ action="store_true",
376
+ help="Keep hinting for unmodified glyphs, default is to drop hinting",
377
+ )
378
+ parser.add_argument(
379
+ "--ignore-errors",
380
+ action="store_true",
381
+ help="ignore errors while removing overlaps, "
382
+ "thus keeping the tricky glyphs unchanged",
383
+ )
384
+ parser.add_argument(
385
+ "--keep-unused-subroutines",
386
+ action="store_true",
387
+ help="Keep unused subroutines in CFF table after removing overlaps, "
388
+ "default is to remove them if any glyphs are modified",
389
+ )
390
+ args = parser.parse_args(args)
391
+
392
+ with ttFont.TTFont(args.input) as font:
393
+ removeOverlaps(
394
+ font=font,
395
+ glyphNames=args.glyphs or None,
396
+ removeHinting=not args.keep_hinting,
397
+ ignoreErrors=args.ignore_errors,
398
+ removeUnusedSubroutines=not args.keep_unused_subroutines,
399
+ )
400
+ font.save(args.output)
401
+
402
+
403
+ if __name__ == "__main__":
404
+ main()
hug/lib/python3.12/site-packages/fontTools/ttLib/reorderGlyphs.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Extended formats retain the same coverage/parallel-array relationships.
206
+ for table_type, compact_format, extended_format in (
207
+ (ot.SinglePos, 1, 3),
208
+ (ot.SinglePos, 2, 4),
209
+ (ot.PairPos, 1, 3),
210
+ (ot.PairPos, 2, 4),
211
+ (ot.CursivePos, 1, 2),
212
+ (ot.MarkBasePos, 1, 2),
213
+ (ot.MarkLigPos, 1, 2),
214
+ (ot.MarkMarkPos, 1, 2),
215
+ (ot.ContextPos, 2, 5),
216
+ (ot.ContextPos, 3, 6),
217
+ (ot.ChainContextPos, 2, 5),
218
+ (ot.ContextSubst, 2, 5),
219
+ (ot.ContextSubst, 3, 6),
220
+ (ot.ChainContextSubst, 2, 5),
221
+ (ot.ReverseChainSingleSubst, 1, 2),
222
+ ):
223
+ _REORDER_RULES[(table_type, extended_format)] = _REORDER_RULES[
224
+ (table_type, compact_format)
225
+ ]
226
+ for table_type in (ot.ContextPos, ot.ContextSubst):
227
+ _REORDER_RULES[(table_type, 4)] = [ReorderCoverage(parallel_list_attr="SeqRuleSet")]
228
+ for table_type in (ot.ChainContextPos, ot.ChainContextSubst):
229
+ _REORDER_RULES[(table_type, 4)] = [
230
+ ReorderCoverage(parallel_list_attr="ChainedSeqRuleSet")
231
+ ]
232
+ _REORDER_RULES[(ot.PairSet2, None)] = _REORDER_RULES[(ot.PairSet, None)]
233
+ _REORDER_RULES[(ot.LigCaretList2, None)] = _REORDER_RULES[(ot.LigCaretList, None)]
234
+
235
+
236
+ # TODO Port to otTraverse
237
+
238
+ SubTablePath = Tuple[otBase.BaseTable.SubTableEntry, ...]
239
+
240
+
241
+ def _bfs_base_table(
242
+ root: otBase.BaseTable, root_accessor: str
243
+ ) -> Iterable[SubTablePath]:
244
+ yield from _traverse_ot_data(
245
+ root, root_accessor, lambda frontier, new: frontier.extend(new)
246
+ )
247
+
248
+
249
+ # Given f(current frontier, new entries) add new entries to frontier
250
+ AddToFrontierFn = Callable[[Deque[SubTablePath], List[SubTablePath]], None]
251
+
252
+
253
+ def _traverse_ot_data(
254
+ root: otBase.BaseTable, root_accessor: str, add_to_frontier_fn: AddToFrontierFn
255
+ ) -> Iterable[SubTablePath]:
256
+ # no visited because general otData is forward-offset only and thus cannot cycle
257
+
258
+ frontier: Deque[SubTablePath] = deque()
259
+ frontier.append((otBase.BaseTable.SubTableEntry(root_accessor, root),))
260
+ while frontier:
261
+ # path is (value, attr_name) tuples. attr_name is attr of parent to get value
262
+ path = frontier.popleft()
263
+ current = path[-1].value
264
+
265
+ yield path
266
+
267
+ new_entries = []
268
+ for subtable_entry in current.iterSubTables():
269
+ new_entries.append(path + (subtable_entry,))
270
+
271
+ add_to_frontier_fn(frontier, new_entries)
272
+
273
+
274
+ def reorderGlyphs(font: ttLib.TTFont, new_glyph_order: List[str]):
275
+ old_glyph_order = font.getGlyphOrder()
276
+ if len(new_glyph_order) != len(old_glyph_order):
277
+ raise ValueError(
278
+ f"New glyph order contains {len(new_glyph_order)} glyphs, "
279
+ f"but font has {len(old_glyph_order)} glyphs"
280
+ )
281
+
282
+ if set(old_glyph_order) != set(new_glyph_order):
283
+ raise ValueError(
284
+ "New glyph order does not contain the same set of glyphs as the font:\n"
285
+ f"* only in new: {set(new_glyph_order) - set(old_glyph_order)}\n"
286
+ f"* only in old: {set(old_glyph_order) - set(new_glyph_order)}"
287
+ )
288
+
289
+ # Changing the order of glyphs in a TTFont requires that all tables that use
290
+ # glyph indexes have been fully.
291
+ # Cf. https://github.com/fonttools/fonttools/issues/2060
292
+ font.ensureDecompiled()
293
+ not_loaded = sorted(t for t in font.keys() if not font.isLoaded(t))
294
+ if not_loaded:
295
+ raise ValueError(f"Everything should be loaded, following aren't: {not_loaded}")
296
+
297
+ font.setGlyphOrder(new_glyph_order)
298
+
299
+ coverage_containers = {"GDEF", "GPOS", "GSUB", "MATH"}
300
+ for tag in coverage_containers:
301
+ if tag in font.keys():
302
+ for path in _bfs_base_table(font[tag].table, f'font["{tag}"]'):
303
+ value = path[-1].value
304
+ reorder_key = (type(value), getattr(value, "Format", None))
305
+ for reorder in _REORDER_RULES.get(reorder_key, []):
306
+ reorder.apply(font, value)
307
+
308
+ for tag in ["CFF ", "CFF2"]:
309
+ if tag in font:
310
+ cff_table = font[tag]
311
+ charstrings = cff_table.cff.topDictIndex[0].CharStrings.charStrings
312
+ cff_table.cff.topDictIndex[0].charset = new_glyph_order
313
+ cff_table.cff.topDictIndex[0].CharStrings.charStrings = {
314
+ k: charstrings.get(k) for k in new_glyph_order
315
+ }
hug/lib/python3.12/site-packages/fontTools/ttLib/scaleUpem.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Change the units-per-EM of a font.
2
+
3
+ AAT and Graphite tables are not supported. CFF/CFF2 fonts
4
+ are de-subroutinized."""
5
+
6
+ from fontTools.ttLib.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.misc.fixedTools import otRound
14
+ from fontTools.varLib.multiVarStore import OnlineMultiVarStoreBuilder
15
+ from fontTools.misc.vector import Vector
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"), 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"), 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
+ (
92
+ otTables.MathConstants,
93
+ ("DelimitedSubFormulaMinHeight", "DisplayOperatorMinHeight"),
94
+ ), # MATH
95
+ (otTables.MathVariants, ("MinConnectorOverlap")), # MATH
96
+ (otTables.MathGlyphVariantRecord, ("AdvanceMeasurement")), # MATH
97
+ (
98
+ otTables.GlyphPartRecord,
99
+ ("StartConnectorLength", "EndConnectorLength", "FullAdvance"),
100
+ ), # MATH
101
+ (otTables.ClipBox, ("xMin", "yMin", "xMax", "yMax")), # COLR
102
+ )
103
+ )
104
+ def visit(visitor, obj, attr, value):
105
+ setattr(obj, attr, visitor.scale(value))
106
+
107
+
108
+ @ScalerVisitor.register_attr(
109
+ (
110
+ ttLib.getTableClass("hmtx"),
111
+ ttLib.getTableClass("HMTX"),
112
+ ttLib.getTableClass("vmtx"),
113
+ ttLib.getTableClass("VMTX"),
114
+ ),
115
+ "metrics",
116
+ )
117
+ def visit(visitor, obj, attr, metrics):
118
+ for g in metrics:
119
+ advance, lsb = metrics[g]
120
+ metrics[g] = visitor.scale(advance), visitor.scale(lsb)
121
+
122
+
123
+ @ScalerVisitor.register_attr(ttLib.getTableClass("VORG"), "VOriginRecords")
124
+ def visit(visitor, obj, attr, VOriginRecords):
125
+ for g in VOriginRecords:
126
+ VOriginRecords[g] = visitor.scale(VOriginRecords[g])
127
+
128
+
129
+ @ScalerVisitor.register_attr(
130
+ (ttLib.getTableClass("glyf"), ttLib.getTableClass("GLYF")), "glyphs"
131
+ )
132
+ def visit(visitor, obj, attr, glyphs):
133
+ for g in glyphs.values():
134
+ for attr in ("xMin", "xMax", "yMin", "yMax"):
135
+ v = getattr(g, attr, None)
136
+ if v is not None:
137
+ setattr(g, attr, visitor.scale(v))
138
+
139
+ if g.isComposite():
140
+ for component in g.components:
141
+ component.x = visitor.scale(component.x)
142
+ component.y = visitor.scale(component.y)
143
+ continue
144
+
145
+ if hasattr(g, "coordinates"):
146
+ coordinates = g.coordinates
147
+ for i, (x, y) in enumerate(coordinates):
148
+ coordinates[i] = visitor.scale(x), visitor.scale(y)
149
+
150
+
151
+ @ScalerVisitor.register_attr(
152
+ (ttLib.getTableClass("gvar"), ttLib.getTableClass("GVAR")), "variations"
153
+ )
154
+ def visit(visitor, obj, attr, variations):
155
+ glyfTable = visitor.font[obj.glyphTableTag]
156
+
157
+ for glyphName, varlist in variations.items():
158
+ glyph = glyfTable[glyphName]
159
+ for var in varlist:
160
+ coordinates = var.coordinates
161
+ for i, xy in enumerate(coordinates):
162
+ if xy is None:
163
+ continue
164
+ coordinates[i] = visitor.scale(xy[0]), visitor.scale(xy[1])
165
+
166
+
167
+ @ScalerVisitor.register_attr(ttLib.getTableClass("VARC"), "table")
168
+ def visit(visitor, obj, attr, varc):
169
+ fvar = visitor.font.get("fvar")
170
+ axes = fvar.axes if fvar is not None else []
171
+ fvarAxes = [a.axisTag for a in axes]
172
+
173
+ store = varc.MultiVarStore
174
+ storeBuilder = OnlineMultiVarStoreBuilder(fvarAxes)
175
+
176
+ for g in varc.VarCompositeGlyphs.VarCompositeGlyph:
177
+ for component in g.components:
178
+ t = component.transform
179
+ t.translateX = visitor.scale(t.translateX)
180
+ t.translateY = visitor.scale(t.translateY)
181
+ t.tCenterX = visitor.scale(t.tCenterX)
182
+ t.tCenterY = visitor.scale(t.tCenterY)
183
+
184
+ if component.axisValuesVarIndex != otTables.NO_VARIATION_INDEX:
185
+ varIdx = component.axisValuesVarIndex
186
+ # TODO Move this code duplicated below to MultiVarStore.__getitem__,
187
+ # or a getDeltasAndSupports().
188
+ if varIdx != otTables.NO_VARIATION_INDEX:
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, axes))
194
+ if vec:
195
+ m = len(vec) // varData.VarRegionCount
196
+ vec = list(batched(vec, m))
197
+ vec = [Vector(v) for v in vec]
198
+ component.axisValuesVarIndex = storeBuilder.storeDeltas(vec)
199
+ else:
200
+ component.axisValuesVarIndex = otTables.NO_VARIATION_INDEX
201
+
202
+ if component.transformVarIndex != otTables.NO_VARIATION_INDEX:
203
+ varIdx = component.transformVarIndex
204
+ if varIdx != otTables.NO_VARIATION_INDEX:
205
+ major = varIdx >> 16
206
+ minor = varIdx & 0xFFFF
207
+ varData = store.MultiVarData[major]
208
+ vec = varData.Item[minor]
209
+ storeBuilder.setSupports(store.get_supports(major, axes))
210
+ if vec:
211
+ m = len(vec) // varData.VarRegionCount
212
+ flags = component.flags
213
+ vec = list(batched(vec, m))
214
+ newVec = []
215
+ for v in vec:
216
+ v = list(v)
217
+ i = 0
218
+ ## Scale translate & tCenter
219
+ if flags & otTables.VarComponentFlags.HAVE_TRANSLATE_X:
220
+ v[i] = visitor.scale(v[i])
221
+ i += 1
222
+ if flags & otTables.VarComponentFlags.HAVE_TRANSLATE_Y:
223
+ v[i] = visitor.scale(v[i])
224
+ i += 1
225
+ if flags & otTables.VarComponentFlags.HAVE_ROTATION:
226
+ i += 1
227
+ if flags & otTables.VarComponentFlags.HAVE_SCALE_X:
228
+ i += 1
229
+ if flags & otTables.VarComponentFlags.HAVE_SCALE_Y:
230
+ i += 1
231
+ if flags & otTables.VarComponentFlags.HAVE_SKEW_X:
232
+ i += 1
233
+ if flags & otTables.VarComponentFlags.HAVE_SKEW_Y:
234
+ i += 1
235
+ if flags & otTables.VarComponentFlags.HAVE_TCENTER_X:
236
+ v[i] = visitor.scale(v[i])
237
+ i += 1
238
+ if flags & otTables.VarComponentFlags.HAVE_TCENTER_Y:
239
+ v[i] = visitor.scale(v[i])
240
+ i += 1
241
+
242
+ newVec.append(Vector(v))
243
+ vec = newVec
244
+
245
+ component.transformVarIndex = storeBuilder.storeDeltas(vec)
246
+ else:
247
+ component.transformVarIndex = otTables.NO_VARIATION_INDEX
248
+
249
+ if store is None:
250
+ return
251
+
252
+ # Condition deltas are dimensionless; preserve them without UPEM scaling.
253
+ if varc.ConditionList is not None:
254
+ varIdxes = set()
255
+ for condition in varc.ConditionList.ConditionTable:
256
+ condition.collect_varidxes(varIdxes)
257
+ mapping = {otTables.NO_VARIATION_INDEX: otTables.NO_VARIATION_INDEX}
258
+ for varIdx in sorted(varIdxes - {otTables.NO_VARIATION_INDEX}):
259
+ major, minor = varIdx >> 16, varIdx & 0xFFFF
260
+ varData = store.MultiVarData[major]
261
+ vec = varData.Item[minor]
262
+ storeBuilder.setSupports(store.get_supports(major, axes))
263
+ mapping[varIdx] = storeBuilder.storeDeltas([Vector([v]) for v in vec])
264
+ for condition in varc.ConditionList.ConditionTable:
265
+ condition.remap_varidxes(mapping)
266
+
267
+ varc.MultiVarStore = storeBuilder.finish()
268
+
269
+
270
+ @ScalerVisitor.register_attr(ttLib.getTableClass("kern"), "kernTables")
271
+ def visit(visitor, obj, attr, kernTables):
272
+ for table in kernTables:
273
+ kernTable = table.kernTable
274
+ for k in kernTable.keys():
275
+ kernTable[k] = visitor.scale(kernTable[k])
276
+
277
+
278
+ def _cff_scale(visitor, args):
279
+ for i, arg in enumerate(args):
280
+ if not isinstance(arg, list):
281
+ if not isinstance(arg, bytes):
282
+ args[i] = visitor.scale(arg)
283
+ else:
284
+ num_blends = arg[-1]
285
+ _cff_scale(visitor, arg)
286
+ arg[-1] = num_blends
287
+
288
+
289
+ @ScalerVisitor.register_attr(
290
+ (ttLib.getTableClass("CFF "), ttLib.getTableClass("CFF2")), "cff"
291
+ )
292
+ def visit(visitor, obj, attr, cff):
293
+ cff.desubroutinize()
294
+ topDict = cff.topDictIndex[0]
295
+ varStore = getattr(topDict, "VarStore", None)
296
+ getNumRegions = varStore.getNumRegions if varStore is not None else None
297
+ privates = set()
298
+ for fontname in cff.keys():
299
+ font = cff[fontname]
300
+ cs = font.CharStrings
301
+ for g in font.charset:
302
+ c, _ = cs.getItemAndSelector(g)
303
+ privates.add(c.private)
304
+
305
+ commands = cffSpecializer.programToCommands(
306
+ c.program,
307
+ getNumRegions=getNumRegions,
308
+ vsIndex=getattr(c.private, "vsindex", 0),
309
+ )
310
+ for op, args in commands:
311
+ if op == "vsindex":
312
+ continue
313
+ _cff_scale(visitor, args)
314
+ c.program[:] = cffSpecializer.commandsToProgram(commands)
315
+
316
+ # Annoying business of scaling numbers that do not matter whatsoever
317
+
318
+ for attr in (
319
+ "UnderlinePosition",
320
+ "UnderlineThickness",
321
+ "FontBBox",
322
+ "StrokeWidth",
323
+ ):
324
+ value = getattr(topDict, attr, None)
325
+ if value is None:
326
+ continue
327
+ if isinstance(value, list):
328
+ _cff_scale(visitor, value)
329
+ else:
330
+ setattr(topDict, attr, visitor.scale(value))
331
+
332
+ # Assign a new list: a Top DICT without an explicit FontMatrix returns the
333
+ # shared class-level default, which must not be modified in place.
334
+ topDict.FontMatrix = [v / visitor.scaleFactor for v in topDict.FontMatrix]
335
+
336
+ for private in privates:
337
+ for attr in (
338
+ "BlueValues",
339
+ "OtherBlues",
340
+ "FamilyBlues",
341
+ "FamilyOtherBlues",
342
+ # "BlueScale",
343
+ # "BlueShift",
344
+ # "BlueFuzz",
345
+ "StdHW",
346
+ "StdVW",
347
+ "StemSnapH",
348
+ "StemSnapV",
349
+ "defaultWidthX",
350
+ "nominalWidthX",
351
+ ):
352
+ value = getattr(private, attr, None)
353
+ if value is None:
354
+ continue
355
+ if isinstance(value, list):
356
+ _cff_scale(visitor, value)
357
+ else:
358
+ setattr(private, attr, visitor.scale(value))
359
+
360
+
361
+ # ItemVariationStore
362
+
363
+
364
+ @ScalerVisitor.register(otTables.VarData)
365
+ def visit(visitor, varData):
366
+ for item in varData.Item:
367
+ for i, v in enumerate(item):
368
+ item[i] = visitor.scale(v)
369
+ varData.calculateNumShorts()
370
+
371
+
372
+ # COLRv1
373
+
374
+
375
+ def _setup_scale_paint(paint, scale):
376
+ if -2 <= scale <= 2 - (1 >> 14):
377
+ paint.Format = otTables.PaintFormat.PaintScaleUniform
378
+ paint.scale = scale
379
+ return
380
+
381
+ transform = otTables.Affine2x3()
382
+ transform.populateDefaults()
383
+ transform.xy = transform.yx = transform.dx = transform.dy = 0
384
+ transform.xx = transform.yy = scale
385
+
386
+ paint.Format = otTables.PaintFormat.PaintTransform
387
+ paint.Transform = transform
388
+
389
+
390
+ @ScalerVisitor.register(otTables.BaseGlyphPaintRecord)
391
+ def visit(visitor, record):
392
+ oldPaint = record.Paint
393
+
394
+ scale = otTables.Paint()
395
+ _setup_scale_paint(scale, visitor.scaleFactor)
396
+ scale.Paint = oldPaint
397
+
398
+ record.Paint = scale
399
+
400
+ return True
401
+
402
+
403
+ @ScalerVisitor.register(otTables.Paint)
404
+ def visit(visitor, paint):
405
+ if paint.Format not in {
406
+ otTables.PaintFormat.PaintGlyph,
407
+ otTables.PaintFormat.PaintGlyph2,
408
+ }:
409
+ return True
410
+
411
+ newPaint = otTables.Paint()
412
+ newPaint.Format = paint.Format
413
+ newPaint.Paint = paint.Paint
414
+ newPaint.Glyph = paint.Glyph
415
+ del paint.Paint
416
+ del paint.Glyph
417
+
418
+ _setup_scale_paint(paint, 1 / visitor.scaleFactor)
419
+ paint.Paint = newPaint
420
+
421
+ visitor.visit(newPaint.Paint)
422
+
423
+ return False
424
+
425
+
426
+ def scale_upem(font, new_upem):
427
+ """Change the units-per-EM of font to the new value."""
428
+ upem = font["head"].unitsPerEm
429
+ visitor = ScalerVisitor(new_upem / upem)
430
+ visitor.visit(font)
431
+
432
+
433
+ def main(args=None):
434
+ """Change the units-per-EM of fonts"""
435
+
436
+ if args is None:
437
+ import sys
438
+
439
+ args = sys.argv[1:]
440
+
441
+ from fontTools.ttLib import TTFont
442
+ from fontTools.misc.cliTools import makeOutputFileName
443
+ import argparse
444
+
445
+ parser = argparse.ArgumentParser(
446
+ "fonttools ttLib.scaleUpem", description="Change the units-per-EM of fonts"
447
+ )
448
+ parser.add_argument("font", metavar="font", help="Font file.")
449
+ parser.add_argument(
450
+ "new_upem", metavar="new-upem", help="New units-per-EM integer value."
451
+ )
452
+ parser.add_argument(
453
+ "--output-file", metavar="path", default=None, help="Output file."
454
+ )
455
+
456
+ options = parser.parse_args(args)
457
+
458
+ font = TTFont(options.font)
459
+ new_upem = int(options.new_upem)
460
+ output_file = (
461
+ options.output_file
462
+ if options.output_file is not None
463
+ else makeOutputFileName(options.font, overWrite=True, suffix="-scaled")
464
+ )
465
+
466
+ scale_upem(font, new_upem)
467
+
468
+ print("Writing %s" % output_file)
469
+ font.save(output_file)
470
+
471
+
472
+ if __name__ == "__main__":
473
+ import sys
474
+
475
+ sys.exit(main())
hug/lib/python3.12/site-packages/fontTools/ttLib/sfnt.py ADDED
@@ -0,0 +1,756 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, _useLegacyTTC=False):
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
+ if hasattr(header, "offsetTable2") and not _useLegacyTTC:
62
+ numFonts = header.numFonts2
63
+ offsetTable = header.offsetTable2
64
+ else:
65
+ numFonts = header.numFonts
66
+ offsetTable = header.offsetTable
67
+ if not 0 <= fontNumber < numFonts:
68
+ raise TTLibFileIsCollectionError(
69
+ "specify a font number between 0 and %d (inclusive)"
70
+ % (numFonts - 1)
71
+ )
72
+ self.numFonts = numFonts
73
+ self.file.seek(offsetTable[fontNumber])
74
+ data = self.file.read(sfntDirectorySize)
75
+ if len(data) != sfntDirectorySize:
76
+ raise TTLibError("Not a Font Collection (not enough data)")
77
+ sstruct.unpack(sfntDirectoryFormat, data, self)
78
+ elif self.sfntVersion == b"wOFF":
79
+ self.flavor = "woff"
80
+ self.DirectoryEntry = WOFFDirectoryEntry
81
+ data = self.file.read(woffDirectorySize)
82
+ if len(data) != woffDirectorySize:
83
+ raise TTLibError("Not a WOFF font (not enough data)")
84
+ sstruct.unpack(woffDirectoryFormat, data, self)
85
+ else:
86
+ data = self.file.read(sfntDirectorySize)
87
+ if len(data) != sfntDirectorySize:
88
+ raise TTLibError("Not a TrueType or OpenType font (not enough data)")
89
+ sstruct.unpack(sfntDirectoryFormat, data, self)
90
+ self.sfntVersion = Tag(self.sfntVersion)
91
+
92
+ if self.sfntVersion not in ("\x00\x01\x00\x00", "OTTO", "true"):
93
+ raise TTLibError("Not a TrueType or OpenType font (bad sfntVersion)")
94
+ tables: dict[Tag, DirectoryEntry] = {}
95
+ for i in range(self.numTables):
96
+ entry = self.DirectoryEntry()
97
+ entry.fromFile(self.file)
98
+ tag = Tag(entry.tag)
99
+ tables[tag] = entry
100
+ self.tables = OrderedDict(sorted(tables.items(), key=lambda i: i[1].offset))
101
+
102
+ # Load flavor data if any
103
+ if self.flavor == "woff":
104
+ self.flavorData = WOFFFlavorData(self)
105
+
106
+ def has_key(self, tag: str | bytes) -> bool:
107
+ return tag in self.tables
108
+
109
+ __contains__ = has_key
110
+
111
+ def keys(self) -> KeysView[Tag]:
112
+ return self.tables.keys()
113
+
114
+ def __getitem__(self, tag: str | bytes) -> bytes:
115
+ """Fetch the raw table data."""
116
+ entry = self.tables[Tag(tag)]
117
+ data = entry.loadData(self.file)
118
+ if self.checkChecksums:
119
+ if tag == "head":
120
+ # Beh: we have to special-case the 'head' table.
121
+ checksum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:])
122
+ else:
123
+ checksum = calcChecksum(data)
124
+ if self.checkChecksums > 1:
125
+ # Be obnoxious, and barf when it's wrong
126
+ assert checksum == entry.checkSum, "bad checksum for '%s' table" % tag
127
+ elif checksum != entry.checkSum:
128
+ # Be friendly, and just log a warning.
129
+ log.warning("bad checksum for '%s' table", tag)
130
+ return data
131
+
132
+ def __delitem__(self, tag: str | bytes) -> None:
133
+ del self.tables[Tag(tag)]
134
+
135
+ def close(self) -> None:
136
+ self.file.close()
137
+
138
+ # We define custom __getstate__ and __setstate__ to make SFNTReader pickle-able
139
+ # and deepcopy-able. When a TTFont is loaded as lazy=True, SFNTReader holds a
140
+ # reference to an external file object which is not pickleable. So in __getstate__
141
+ # we store the file name and current position, and in __setstate__ we reopen the
142
+ # same named file after unpickling.
143
+
144
+ def __getstate__(self):
145
+ if isinstance(self.file, BytesIO):
146
+ # BytesIO is already pickleable, return the state unmodified
147
+ return self.__dict__
148
+
149
+ # remove unpickleable file attribute, and only store its name and pos
150
+ state = self.__dict__.copy()
151
+ del state["file"]
152
+ state["_filename"] = self.file.name
153
+ state["_filepos"] = self.file.tell()
154
+ return state
155
+
156
+ def __setstate__(self, state):
157
+ if "file" not in state:
158
+ self.file = open(state.pop("_filename"), "rb")
159
+ self.file.seek(state.pop("_filepos"))
160
+ self.__dict__.update(state)
161
+
162
+
163
+ # default compression level for WOFF 1.0 tables and metadata
164
+ ZLIB_COMPRESSION_LEVEL = 6
165
+
166
+ # if set to True, use zopfli instead of zlib for compressing WOFF 1.0.
167
+ # The Python bindings are available at https://pypi.python.org/pypi/zopfli
168
+ USE_ZOPFLI = False
169
+
170
+ # mapping between zlib's compression levels and zopfli's 'numiterations'.
171
+ # Use lower values for files over several MB in size or it will be too slow
172
+ ZOPFLI_LEVELS = {
173
+ # 0: 0, # can't do 0 iterations...
174
+ 1: 1,
175
+ 2: 3,
176
+ 3: 5,
177
+ 4: 8,
178
+ 5: 10,
179
+ 6: 15,
180
+ 7: 25,
181
+ 8: 50,
182
+ 9: 100,
183
+ }
184
+
185
+
186
+ def compress(data, level=ZLIB_COMPRESSION_LEVEL):
187
+ """Compress 'data' to Zlib format. If 'USE_ZOPFLI' variable is True,
188
+ zopfli is used instead of the zlib module.
189
+ The compression 'level' must be between 0 and 9. 1 gives best speed,
190
+ 9 gives best compression (0 gives no compression at all).
191
+ The default value is a compromise between speed and compression (6).
192
+ """
193
+ if not (0 <= level <= 9):
194
+ raise ValueError("Bad compression level: %s" % level)
195
+ if not USE_ZOPFLI or level == 0:
196
+ from zlib import compress
197
+
198
+ return compress(data, level)
199
+ else:
200
+ from zopfli.zlib import compress
201
+
202
+ return compress(data, numiterations=ZOPFLI_LEVELS[level])
203
+
204
+
205
+ class SFNTWriter(object):
206
+ def __new__(cls, *args, **kwargs):
207
+ """Return an instance of the SFNTWriter sub-class which is compatible
208
+ with the specified 'flavor'.
209
+ """
210
+ flavor = None
211
+ if kwargs and "flavor" in kwargs:
212
+ flavor = kwargs["flavor"]
213
+ elif args and len(args) > 3:
214
+ flavor = args[3]
215
+ if cls is SFNTWriter:
216
+ if flavor == "woff2":
217
+ # return new WOFF2Writer object
218
+ from fontTools.ttLib.woff2 import WOFF2Writer
219
+
220
+ return object.__new__(WOFF2Writer)
221
+ # return default object
222
+ return object.__new__(cls)
223
+
224
+ def __init__(
225
+ self,
226
+ file,
227
+ numTables,
228
+ sfntVersion="\000\001\000\000",
229
+ flavor=None,
230
+ flavorData=None,
231
+ ):
232
+ self.file = file
233
+ self.numTables = numTables
234
+ self.sfntVersion = Tag(sfntVersion)
235
+ self.flavor = flavor
236
+ self.flavorData = flavorData
237
+
238
+ if self.flavor == "woff":
239
+ self.directoryFormat = woffDirectoryFormat
240
+ self.directorySize = woffDirectorySize
241
+ self.DirectoryEntry = WOFFDirectoryEntry
242
+
243
+ self.signature = "wOFF"
244
+
245
+ # to calculate WOFF checksum adjustment, we also need the original SFNT offsets
246
+ self.origNextTableOffset = (
247
+ sfntDirectorySize + numTables * sfntDirectoryEntrySize
248
+ )
249
+ else:
250
+ assert not self.flavor, "Unknown flavor '%s'" % self.flavor
251
+ self.directoryFormat = sfntDirectoryFormat
252
+ self.directorySize = sfntDirectorySize
253
+ self.DirectoryEntry = SFNTDirectoryEntry
254
+
255
+ from fontTools.ttLib import getSearchRange
256
+
257
+ self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(
258
+ numTables, 16
259
+ )
260
+
261
+ self.directoryOffset = self.file.tell()
262
+ self.nextTableOffset = (
263
+ self.directoryOffset
264
+ + self.directorySize
265
+ + numTables * self.DirectoryEntry.formatSize
266
+ )
267
+ # clear out directory area
268
+ self.file.seek(self.nextTableOffset)
269
+ # make sure we're actually where we want to be. (old cStringIO bug)
270
+ self.file.write(b"\0" * (self.nextTableOffset - self.file.tell()))
271
+ self.tables = OrderedDict()
272
+
273
+ def setEntry(self, tag, entry):
274
+ if tag in self.tables:
275
+ raise TTLibError("cannot rewrite '%s' table" % tag)
276
+
277
+ self.tables[tag] = entry
278
+
279
+ def __setitem__(self, tag, data):
280
+ """Write raw table data to disk."""
281
+ if tag in self.tables:
282
+ raise TTLibError("cannot rewrite '%s' table" % tag)
283
+
284
+ entry = self.DirectoryEntry()
285
+ entry.tag = tag
286
+ entry.offset = self.nextTableOffset
287
+ if tag == "head":
288
+ entry.checkSum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:])
289
+ self.headTable = data
290
+ entry.uncompressed = True
291
+ else:
292
+ entry.checkSum = calcChecksum(data)
293
+ entry.saveData(self.file, data)
294
+
295
+ if self.flavor == "woff":
296
+ entry.origOffset = self.origNextTableOffset
297
+ self.origNextTableOffset += (entry.origLength + 3) & ~3
298
+
299
+ self.nextTableOffset = self.nextTableOffset + ((entry.length + 3) & ~3)
300
+ # Add NUL bytes to pad the table data to a 4-byte boundary.
301
+ # Don't depend on f.seek() as we need to add the padding even if no
302
+ # subsequent write follows (seek is lazy), ie. after the final table
303
+ # in the font.
304
+ self.file.write(b"\0" * (self.nextTableOffset - self.file.tell()))
305
+ assert self.nextTableOffset == self.file.tell()
306
+
307
+ self.setEntry(tag, entry)
308
+
309
+ def __getitem__(self, tag):
310
+ return self.tables[tag]
311
+
312
+ def close(self):
313
+ """All tables must have been written to disk. Now write the
314
+ directory.
315
+ """
316
+ tables = sorted(self.tables.items())
317
+ if len(tables) != self.numTables:
318
+ raise TTLibError(
319
+ "wrong number of tables; expected %d, found %d"
320
+ % (self.numTables, len(tables))
321
+ )
322
+
323
+ if self.flavor == "woff":
324
+ self.signature = b"wOFF"
325
+ self.reserved = 0
326
+
327
+ self.totalSfntSize = 12
328
+ self.totalSfntSize += 16 * len(tables)
329
+ for tag, entry in tables:
330
+ self.totalSfntSize += (entry.origLength + 3) & ~3
331
+
332
+ data = self.flavorData if self.flavorData else WOFFFlavorData()
333
+ if data.majorVersion is not None and data.minorVersion is not None:
334
+ self.majorVersion = data.majorVersion
335
+ self.minorVersion = data.minorVersion
336
+ else:
337
+ if hasattr(self, "headTable"):
338
+ self.majorVersion, self.minorVersion = struct.unpack(
339
+ ">HH", self.headTable[4:8]
340
+ )
341
+ else:
342
+ self.majorVersion = self.minorVersion = 0
343
+ if data.metaData:
344
+ self.metaOrigLength = len(data.metaData)
345
+ self.file.seek(0, 2)
346
+ self.metaOffset = self.file.tell()
347
+ compressedMetaData = compress(data.metaData)
348
+ self.metaLength = len(compressedMetaData)
349
+ self.file.write(compressedMetaData)
350
+ else:
351
+ self.metaOffset = self.metaLength = self.metaOrigLength = 0
352
+ if data.privData:
353
+ self.file.seek(0, 2)
354
+ off = self.file.tell()
355
+ paddedOff = (off + 3) & ~3
356
+ self.file.write(b"\0" * (paddedOff - off))
357
+ self.privOffset = self.file.tell()
358
+ self.privLength = len(data.privData)
359
+ self.file.write(data.privData)
360
+ else:
361
+ self.privOffset = self.privLength = 0
362
+
363
+ self.file.seek(0, 2)
364
+ self.length = self.file.tell()
365
+
366
+ else:
367
+ assert not self.flavor, "Unknown flavor '%s'" % self.flavor
368
+ pass
369
+
370
+ directory = sstruct.pack(self.directoryFormat, self)
371
+
372
+ self.file.seek(self.directoryOffset + self.directorySize)
373
+ seenHead = 0
374
+ for tag, entry in tables:
375
+ if tag == "head":
376
+ seenHead = 1
377
+ directory = directory + entry.toString()
378
+ if seenHead:
379
+ self.writeMasterChecksum(directory)
380
+ self.file.seek(self.directoryOffset)
381
+ self.file.write(directory)
382
+
383
+ def _calcMasterChecksum(self, directory):
384
+ # calculate checkSumAdjustment
385
+ checksums = []
386
+ for tag in self.tables.keys():
387
+ checksums.append(self.tables[tag].checkSum)
388
+
389
+ if self.DirectoryEntry != SFNTDirectoryEntry:
390
+ # Create a SFNT directory for checksum calculation purposes
391
+ from fontTools.ttLib import getSearchRange
392
+
393
+ self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(
394
+ self.numTables, 16
395
+ )
396
+ directory = sstruct.pack(sfntDirectoryFormat, self)
397
+ tables = sorted(self.tables.items())
398
+ for tag, entry in tables:
399
+ sfntEntry = SFNTDirectoryEntry()
400
+ sfntEntry.tag = entry.tag
401
+ sfntEntry.checkSum = entry.checkSum
402
+ sfntEntry.offset = entry.origOffset
403
+ sfntEntry.length = entry.origLength
404
+ directory = directory + sfntEntry.toString()
405
+
406
+ directory_end = sfntDirectorySize + len(self.tables) * sfntDirectoryEntrySize
407
+ assert directory_end == len(directory)
408
+
409
+ checksums.append(calcChecksum(directory))
410
+ checksum = sum(checksums) & 0xFFFFFFFF
411
+ # BiboAfba!
412
+ checksumadjustment = (0xB1B0AFBA - checksum) & 0xFFFFFFFF
413
+ return checksumadjustment
414
+
415
+ def writeMasterChecksum(self, directory):
416
+ checksumadjustment = self._calcMasterChecksum(directory)
417
+ # write the checksum to the file
418
+ self.file.seek(self.tables["head"].offset + 8)
419
+ self.file.write(struct.pack(">L", checksumadjustment))
420
+
421
+ def reordersTables(self):
422
+ return False
423
+
424
+
425
+ # -- sfnt directory helpers and cruft
426
+
427
+ ttcHeaderFormat = """
428
+ > # big endian
429
+ TTCTag: 4s # "ttcf"
430
+ Version: L # 0x00010000 or 0x00020000
431
+ numFonts: L # number of fonts
432
+ # OffsetTable[numFonts]: L # array with offsets from beginning of file
433
+ # ulDsigTag: L # version 2.0 only
434
+ # ulDsigLength: L # version 2.0 only
435
+ # ulDsigOffset: L # version 2.0 only
436
+ """
437
+
438
+ ttcHeaderSize = sstruct.calcsize(ttcHeaderFormat)
439
+
440
+ ttcTailFormatV2 = """
441
+ > # big endian
442
+ ulDsigTag: L # version 2.0 only
443
+ ulDsigLength: L # version 2.0 only
444
+ ulDsigOffset: L # version 2.0 only
445
+ """
446
+
447
+ ttcTailSizeV2 = sstruct.calcsize(ttcTailFormatV2)
448
+
449
+ TTC_V1 = 0x00010000
450
+ TTC_V1_1 = 0x00010001
451
+ TTC_V2 = 0x00020000
452
+ TTC_V2_1 = 0x00020001
453
+
454
+ sfntDirectoryFormat = """
455
+ > # big endian
456
+ sfntVersion: 4s
457
+ numTables: H # number of tables
458
+ searchRange: H # (max2 <= numTables)*16
459
+ entrySelector: H # log2(max2 <= numTables)
460
+ rangeShift: H # numTables*16-searchRange
461
+ """
462
+
463
+ sfntDirectorySize = sstruct.calcsize(sfntDirectoryFormat)
464
+
465
+ sfntDirectoryEntryFormat = """
466
+ > # big endian
467
+ tag: 4s
468
+ checkSum: L
469
+ offset: L
470
+ length: L
471
+ """
472
+
473
+ sfntDirectoryEntrySize = sstruct.calcsize(sfntDirectoryEntryFormat)
474
+
475
+ woffDirectoryFormat = """
476
+ > # big endian
477
+ signature: 4s # "wOFF"
478
+ sfntVersion: 4s
479
+ length: L # total woff file size
480
+ numTables: H # number of tables
481
+ reserved: H # set to 0
482
+ totalSfntSize: L # uncompressed size
483
+ majorVersion: H # major version of WOFF file
484
+ minorVersion: H # minor version of WOFF file
485
+ metaOffset: L # offset to metadata block
486
+ metaLength: L # length of compressed metadata
487
+ metaOrigLength: L # length of uncompressed metadata
488
+ privOffset: L # offset to private data block
489
+ privLength: L # length of private data block
490
+ """
491
+
492
+ woffDirectorySize = sstruct.calcsize(woffDirectoryFormat)
493
+
494
+ woffDirectoryEntryFormat = """
495
+ > # big endian
496
+ tag: 4s
497
+ offset: L
498
+ length: L # compressed length
499
+ origLength: L # original length
500
+ checkSum: L # original checksum
501
+ """
502
+
503
+ woffDirectoryEntrySize = sstruct.calcsize(woffDirectoryEntryFormat)
504
+
505
+
506
+ class DirectoryEntry(object):
507
+ def __init__(self):
508
+ self.uncompressed = False # if True, always embed entry raw
509
+
510
+ def fromFile(self, file):
511
+ data = file.read(self.formatSize)
512
+ if len(data) != self.formatSize:
513
+ # A file truncated inside the table directory, or one whose
514
+ # numTables is corrupt, would otherwise fail with a struct.error.
515
+ raise TTLibError(
516
+ "unexpected end of table directory: expected %d bytes but got %d"
517
+ % (self.formatSize, len(data))
518
+ )
519
+ sstruct.unpack(self.format, data, self)
520
+
521
+ def fromString(self, str):
522
+ sstruct.unpack(self.format, str, self)
523
+
524
+ def toString(self):
525
+ return sstruct.pack(self.format, self)
526
+
527
+ def __repr__(self):
528
+ if hasattr(self, "tag"):
529
+ return "<%s '%s' at %x>" % (self.__class__.__name__, self.tag, id(self))
530
+ else:
531
+ return "<%s at %x>" % (self.__class__.__name__, id(self))
532
+
533
+ def loadData(self, file):
534
+ file.seek(self.offset)
535
+ data = file.read(self.length)
536
+ if len(data) != self.length:
537
+ # A corrupt or truncated table directory entry can point past the
538
+ # end of the file; raise a TTLibError instead of a bare assertion
539
+ # (which is also silently skipped under `python -O`).
540
+ tag = getattr(self, "tag", None)
541
+ raise TTLibError(
542
+ "unexpected end of '%s' table data: expected %d bytes but got "
543
+ "%d at offset %d"
544
+ % (
545
+ Tag(tag) if tag is not None else "????",
546
+ self.length,
547
+ len(data),
548
+ self.offset,
549
+ )
550
+ )
551
+ if hasattr(self.__class__, "decodeData"):
552
+ data = self.decodeData(data)
553
+ return data
554
+
555
+ def saveData(self, file, data):
556
+ if hasattr(self.__class__, "encodeData"):
557
+ data = self.encodeData(data)
558
+ self.length = len(data)
559
+ file.seek(self.offset)
560
+ file.write(data)
561
+
562
+ def decodeData(self, rawData):
563
+ return rawData
564
+
565
+ def encodeData(self, data):
566
+ return data
567
+
568
+
569
+ class SFNTDirectoryEntry(DirectoryEntry):
570
+ format = sfntDirectoryEntryFormat
571
+ formatSize = sfntDirectoryEntrySize
572
+
573
+
574
+ class WOFFDirectoryEntry(DirectoryEntry):
575
+ format = woffDirectoryEntryFormat
576
+ formatSize = woffDirectoryEntrySize
577
+
578
+ def __init__(self):
579
+ super(WOFFDirectoryEntry, self).__init__()
580
+ # With fonttools<=3.1.2, the only way to set a different zlib
581
+ # compression level for WOFF directory entries was to set the class
582
+ # attribute 'zlibCompressionLevel'. This is now replaced by a globally
583
+ # defined `ZLIB_COMPRESSION_LEVEL`, which is also applied when
584
+ # compressing the metadata. For backward compatibility, we still
585
+ # use the class attribute if it was already set.
586
+ if not hasattr(WOFFDirectoryEntry, "zlibCompressionLevel"):
587
+ self.zlibCompressionLevel = ZLIB_COMPRESSION_LEVEL
588
+
589
+ def decodeData(self, rawData):
590
+ import zlib
591
+
592
+ if self.length == self.origLength:
593
+ data = rawData
594
+ else:
595
+ # These lengths come straight from the (untrusted) WOFF table
596
+ # directory; a bare assertion is also silently skipped under
597
+ # `python -O`, so a corrupt WOFF would be accepted with wrong-sized
598
+ # table data instead of failing.
599
+ tag = Tag(getattr(self, "tag", None) or "????")
600
+ if self.length >= self.origLength:
601
+ raise TTLibError(
602
+ "corrupt WOFF table '%s': compressed length %d is not "
603
+ "smaller than original length %d"
604
+ % (tag, self.length, self.origLength)
605
+ )
606
+ data = zlib.decompress(rawData)
607
+ if len(data) != self.origLength:
608
+ raise TTLibError(
609
+ "unexpected size for decompressed WOFF table '%s': "
610
+ "expected %d but got %d" % (tag, self.origLength, len(data))
611
+ )
612
+ return data
613
+
614
+ def encodeData(self, data):
615
+ self.origLength = len(data)
616
+ if not self.uncompressed:
617
+ compressedData = compress(data, self.zlibCompressionLevel)
618
+ if self.uncompressed or len(compressedData) >= self.origLength:
619
+ # Encode uncompressed
620
+ rawData = data
621
+ self.length = self.origLength
622
+ else:
623
+ rawData = compressedData
624
+ self.length = len(rawData)
625
+ return rawData
626
+
627
+
628
+ class WOFFFlavorData:
629
+ Flavor = "woff"
630
+
631
+ def __init__(self, reader=None):
632
+ self.majorVersion = None
633
+ self.minorVersion = None
634
+ self.metaData = None
635
+ self.privData = None
636
+ if reader:
637
+ self.majorVersion = reader.majorVersion
638
+ self.minorVersion = reader.minorVersion
639
+ # The metadata/private-data offsets and lengths are read from the
640
+ # (untrusted) WOFF header; validate them with real checks rather
641
+ # than bare assertions, which are silently skipped under `python -O`.
642
+ if reader.metaLength:
643
+ reader.file.seek(reader.metaOffset)
644
+ rawData = reader.file.read(reader.metaLength)
645
+ if len(rawData) != reader.metaLength:
646
+ raise TTLibError(
647
+ "unexpected end of WOFF metadata: expected %d bytes "
648
+ "but got %d" % (reader.metaLength, len(rawData))
649
+ )
650
+ data = self._decompress(rawData)
651
+ if len(data) != reader.metaOrigLength:
652
+ raise TTLibError(
653
+ "unexpected size for decompressed WOFF metadata: "
654
+ "expected %d but got %d" % (reader.metaOrigLength, len(data))
655
+ )
656
+ self.metaData = data
657
+ if reader.privLength:
658
+ reader.file.seek(reader.privOffset)
659
+ data = reader.file.read(reader.privLength)
660
+ if len(data) != reader.privLength:
661
+ raise TTLibError(
662
+ "unexpected end of WOFF private data: expected %d "
663
+ "bytes but got %d" % (reader.privLength, len(data))
664
+ )
665
+ self.privData = data
666
+
667
+ def _decompress(self, rawData):
668
+ import zlib
669
+
670
+ return zlib.decompress(rawData)
671
+
672
+
673
+ def calcChecksum(data):
674
+ """Calculate the checksum for an arbitrary block of data.
675
+
676
+ If the data length is not a multiple of four, it assumes
677
+ it is to be padded with null byte.
678
+
679
+ >>> print(calcChecksum(b"abcd"))
680
+ 1633837924
681
+ >>> print(calcChecksum(b"abcdxyz"))
682
+ 3655064932
683
+ """
684
+ remainder = len(data) % 4
685
+ if remainder:
686
+ data += b"\0" * (4 - remainder)
687
+ value = 0
688
+ blockSize = 4096
689
+ assert blockSize % 4 == 0
690
+ for i in range(0, len(data), blockSize):
691
+ block = data[i : i + blockSize]
692
+ longs = struct.unpack(">%dL" % (len(block) // 4), block)
693
+ value = (value + sum(longs)) & 0xFFFFFFFF
694
+ return value
695
+
696
+
697
+ def readTTCHeader(file):
698
+ file.seek(0)
699
+ data = file.read(ttcHeaderSize)
700
+ if len(data) != ttcHeaderSize:
701
+ raise TTLibError("Not a Font Collection (not enough data)")
702
+ self = SimpleNamespace()
703
+ sstruct.unpack(ttcHeaderFormat, data, self)
704
+ if self.TTCTag != "ttcf":
705
+ raise TTLibError("Not a Font Collection")
706
+ assert self.Version in (TTC_V1, TTC_V1_1, TTC_V2, TTC_V2_1), (
707
+ "unrecognized TTC version 0x%08x" % self.Version
708
+ )
709
+ self.offsetTable = struct.unpack(
710
+ ">%dL" % self.numFonts, file.read(self.numFonts * 4)
711
+ )
712
+ if self.Version in (TTC_V2, TTC_V2_1):
713
+ # Unpack additional DSIG fields
714
+ data = file.read(ttcTailSizeV2)
715
+ if len(data) != ttcTailSizeV2:
716
+ raise TTLibError("Not a Font Collection (not enough data)")
717
+ sstruct.unpack(ttcTailFormatV2, data, self)
718
+ if self.Version in (TTC_V1_1, TTC_V2_1):
719
+ data = file.read(4)
720
+ if len(data) != 4:
721
+ raise TTLibError("Not a Font Collection (not enough data)")
722
+ self.numFonts2 = struct.unpack(">L", data)[0]
723
+ data = file.read(self.numFonts2 * 4)
724
+ if len(data) != self.numFonts2 * 4:
725
+ raise TTLibError("Not a Font Collection (not enough data)")
726
+ self.offsetTable2 = struct.unpack(">%dL" % self.numFonts2, data)
727
+ return self
728
+
729
+
730
+ def writeTTCHeader(file, numFonts, version=TTC_V1, numFonts2=0):
731
+ self = SimpleNamespace()
732
+ self.TTCTag = "ttcf"
733
+ self.Version = version
734
+ assert self.Version in (TTC_V1, TTC_V1_1, TTC_V2, TTC_V2_1), (
735
+ "unrecognized TTC version 0x%08x" % self.Version
736
+ )
737
+ self.numFonts = numFonts
738
+ file.seek(0)
739
+ file.write(sstruct.pack(ttcHeaderFormat, self))
740
+ offset = file.tell()
741
+ file.write(struct.pack(">%dL" % self.numFonts, *([0] * self.numFonts)))
742
+ if version in (TTC_V2, TTC_V2_1):
743
+ # write empty ulDsigTag, ulDsigLength, ulDsigOffset
744
+ # Actual values are be written in TTCollection.save()
745
+ file.write(struct.pack(">3L", 0, 0, 0))
746
+ if version in (TTC_V1_1, TTC_V2_1):
747
+ file.write(struct.pack(">L", numFonts2))
748
+ file.write(struct.pack(">%dL" % numFonts2, *([0] * numFonts2)))
749
+ return offset
750
+
751
+
752
+ if __name__ == "__main__":
753
+ import sys
754
+ import doctest
755
+
756
+ sys.exit(doctest.testmod().failed)
hug/lib/python3.12/site-packages/fontTools/ttLib/standardGlyphOrder.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ]
hug/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