ZTWHHH commited on
Commit
5b18006
·
verified ·
1 Parent(s): 6bd0daa

Add files using upload-large-folder tool

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 +4 -0
  2. infer_4_37_2/lib/python3.10/site-packages/fontTools/__pycache__/help.cpython-310.pyc +0 -0
  3. infer_4_37_2/lib/python3.10/site-packages/fontTools/cu2qu/cu2qu.cpython-310-x86_64-linux-gnu.so +3 -0
  4. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__init__.py +1 -0
  5. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/__init__.cpython-310.pyc +0 -0
  6. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/arrayTools.cpython-310.pyc +0 -0
  7. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/classifyTools.cpython-310.pyc +0 -0
  8. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/cliTools.cpython-310.pyc +0 -0
  9. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/cython.cpython-310.pyc +0 -0
  10. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/dictTools.cpython-310.pyc +0 -0
  11. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/eexec.cpython-310.pyc +0 -0
  12. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/etree.cpython-310.pyc +0 -0
  13. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/intTools.cpython-310.pyc +0 -0
  14. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/lazyTools.cpython-310.pyc +0 -0
  15. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/macCreatorType.cpython-310.pyc +0 -0
  16. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/macRes.cpython-310.pyc +0 -0
  17. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/psCharStrings.cpython-310.pyc +0 -0
  18. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/psLib.cpython-310.pyc +0 -0
  19. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/psOperators.cpython-310.pyc +0 -0
  20. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/py23.cpython-310.pyc +0 -0
  21. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/roundTools.cpython-310.pyc +0 -0
  22. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/symfont.cpython-310.pyc +0 -0
  23. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/testTools.cpython-310.pyc +0 -0
  24. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/treeTools.cpython-310.pyc +0 -0
  25. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/vector.cpython-310.pyc +0 -0
  26. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/xmlReader.cpython-310.pyc +0 -0
  27. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/xmlWriter.cpython-310.pyc +0 -0
  28. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/arrayTools.py +424 -0
  29. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/bezierTools.c +0 -0
  30. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/bezierTools.cpython-310-x86_64-linux-gnu.so +3 -0
  31. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/bezierTools.py +1490 -0
  32. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/classifyTools.py +170 -0
  33. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/cliTools.py +53 -0
  34. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/configTools.py +349 -0
  35. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/cython.py +27 -0
  36. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/dictTools.py +83 -0
  37. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/eexec.py +119 -0
  38. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/encodingTools.py +72 -0
  39. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/etree.py +479 -0
  40. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/filenames.py +245 -0
  41. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/fixedTools.py +253 -0
  42. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/intTools.py +25 -0
  43. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/lazyTools.py +42 -0
  44. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/loggingTools.py +543 -0
  45. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/macCreatorType.py +56 -0
  46. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/macRes.py +261 -0
  47. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/psCharStrings.py +1496 -0
  48. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/psOperators.py +572 -0
  49. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/py23.py +96 -0
  50. infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/roundTools.py +110 -0
.gitattributes CHANGED
@@ -1113,3 +1113,7 @@ infer_4_37_2/lib/python3.10/site-packages/zmq/backend/cython/_zmq.cpython-310-x8
1113
  infer_4_37_2/lib/python3.10/site-packages/PIL/_imaging.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1114
  infer_4_37_2/lib/python3.10/site-packages/PIL/_imagingmath.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1115
  infer_4_37_2/lib/python3.10/site-packages/PIL/_imagingft.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
1113
  infer_4_37_2/lib/python3.10/site-packages/PIL/_imaging.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1114
  infer_4_37_2/lib/python3.10/site-packages/PIL/_imagingmath.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1115
  infer_4_37_2/lib/python3.10/site-packages/PIL/_imagingft.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1116
+ infer_4_37_2/lib/python3.10/site-packages/fontTools/cu2qu/cu2qu.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1117
+ infer_4_37_2/lib/python3.10/site-packages/fontTools/qu2cu/qu2cu.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1118
+ infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/bezierTools.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1119
+ infer_4_37_2/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/otData.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
infer_4_37_2/lib/python3.10/site-packages/fontTools/__pycache__/help.cpython-310.pyc ADDED
Binary file (1.24 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/cu2qu/cu2qu.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:77933cf1f59333b95b32f35c115a197c264de1caec5f47f7836903fb562948a5
3
+ size 967424
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Empty __init__.py file to signal Python this directory is a package."""
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (252 Bytes). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/arrayTools.cpython-310.pyc ADDED
Binary file (12.9 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/classifyTools.cpython-310.pyc ADDED
Binary file (5.44 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/cliTools.cpython-310.pyc ADDED
Binary file (1.88 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/cython.cpython-310.pyc ADDED
Binary file (1.03 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/dictTools.cpython-310.pyc ADDED
Binary file (2.74 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/eexec.cpython-310.pyc ADDED
Binary file (3.64 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/etree.cpython-310.pyc ADDED
Binary file (9.81 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/intTools.cpython-310.pyc ADDED
Binary file (849 Bytes). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/lazyTools.cpython-310.pyc ADDED
Binary file (1.72 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/macCreatorType.cpython-310.pyc ADDED
Binary file (1.94 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/macRes.cpython-310.pyc ADDED
Binary file (8.85 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/psCharStrings.cpython-310.pyc ADDED
Binary file (41.5 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/psLib.cpython-310.pyc ADDED
Binary file (10.2 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/psOperators.cpython-310.pyc ADDED
Binary file (18.7 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/py23.cpython-310.pyc ADDED
Binary file (2.34 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/roundTools.cpython-310.pyc ADDED
Binary file (3.17 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/symfont.cpython-310.pyc ADDED
Binary file (8.93 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/testTools.cpython-310.pyc ADDED
Binary file (9.41 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/treeTools.cpython-310.pyc ADDED
Binary file (1.11 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/vector.cpython-310.pyc ADDED
Binary file (6.32 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/xmlReader.cpython-310.pyc ADDED
Binary file (4.94 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/__pycache__/xmlWriter.cpython-310.pyc ADDED
Binary file (6.32 kB). View file
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/arrayTools.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Routines for calculating bounding boxes, point in rectangle calculations and
2
+ so on.
3
+ """
4
+
5
+ from fontTools.misc.roundTools import otRound
6
+ from fontTools.misc.vector import Vector as _Vector
7
+ import math
8
+ import warnings
9
+
10
+
11
+ def calcBounds(array):
12
+ """Calculate the bounding rectangle of a 2D points array.
13
+
14
+ Args:
15
+ array: A sequence of 2D tuples.
16
+
17
+ Returns:
18
+ A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
19
+ """
20
+ if not array:
21
+ return 0, 0, 0, 0
22
+ xs = [x for x, y in array]
23
+ ys = [y for x, y in array]
24
+ return min(xs), min(ys), max(xs), max(ys)
25
+
26
+
27
+ def calcIntBounds(array, round=otRound):
28
+ """Calculate the integer bounding rectangle of a 2D points array.
29
+
30
+ Values are rounded to closest integer towards ``+Infinity`` using the
31
+ :func:`fontTools.misc.fixedTools.otRound` function by default, unless
32
+ an optional ``round`` function is passed.
33
+
34
+ Args:
35
+ array: A sequence of 2D tuples.
36
+ round: A rounding function of type ``f(x: float) -> int``.
37
+
38
+ Returns:
39
+ A four-item tuple of integers representing the bounding rectangle:
40
+ ``(xMin, yMin, xMax, yMax)``.
41
+ """
42
+ return tuple(round(v) for v in calcBounds(array))
43
+
44
+
45
+ def updateBounds(bounds, p, min=min, max=max):
46
+ """Add a point to a bounding rectangle.
47
+
48
+ Args:
49
+ bounds: A bounding rectangle expressed as a tuple
50
+ ``(xMin, yMin, xMax, yMax), or None``.
51
+ p: A 2D tuple representing a point.
52
+ min,max: functions to compute the minimum and maximum.
53
+
54
+ Returns:
55
+ The updated bounding rectangle ``(xMin, yMin, xMax, yMax)``.
56
+ """
57
+ (x, y) = p
58
+ if bounds is None:
59
+ return x, y, x, y
60
+ xMin, yMin, xMax, yMax = bounds
61
+ return min(xMin, x), min(yMin, y), max(xMax, x), max(yMax, y)
62
+
63
+
64
+ def pointInRect(p, rect):
65
+ """Test if a point is inside a bounding rectangle.
66
+
67
+ Args:
68
+ p: A 2D tuple representing a point.
69
+ rect: A bounding rectangle expressed as a tuple
70
+ ``(xMin, yMin, xMax, yMax)``.
71
+
72
+ Returns:
73
+ ``True`` if the point is inside the rectangle, ``False`` otherwise.
74
+ """
75
+ (x, y) = p
76
+ xMin, yMin, xMax, yMax = rect
77
+ return (xMin <= x <= xMax) and (yMin <= y <= yMax)
78
+
79
+
80
+ def pointsInRect(array, rect):
81
+ """Determine which points are inside a bounding rectangle.
82
+
83
+ Args:
84
+ array: A sequence of 2D tuples.
85
+ rect: A bounding rectangle expressed as a tuple
86
+ ``(xMin, yMin, xMax, yMax)``.
87
+
88
+ Returns:
89
+ A list containing the points inside the rectangle.
90
+ """
91
+ if len(array) < 1:
92
+ return []
93
+ xMin, yMin, xMax, yMax = rect
94
+ return [(xMin <= x <= xMax) and (yMin <= y <= yMax) for x, y in array]
95
+
96
+
97
+ def vectorLength(vector):
98
+ """Calculate the length of the given vector.
99
+
100
+ Args:
101
+ vector: A 2D tuple.
102
+
103
+ Returns:
104
+ The Euclidean length of the vector.
105
+ """
106
+ x, y = vector
107
+ return math.sqrt(x**2 + y**2)
108
+
109
+
110
+ def asInt16(array):
111
+ """Round a list of floats to 16-bit signed integers.
112
+
113
+ Args:
114
+ array: List of float values.
115
+
116
+ Returns:
117
+ A list of rounded integers.
118
+ """
119
+ return [int(math.floor(i + 0.5)) for i in array]
120
+
121
+
122
+ def normRect(rect):
123
+ """Normalize a bounding box rectangle.
124
+
125
+ This function "turns the rectangle the right way up", so that the following
126
+ holds::
127
+
128
+ xMin <= xMax and yMin <= yMax
129
+
130
+ Args:
131
+ rect: A bounding rectangle expressed as a tuple
132
+ ``(xMin, yMin, xMax, yMax)``.
133
+
134
+ Returns:
135
+ A normalized bounding rectangle.
136
+ """
137
+ (xMin, yMin, xMax, yMax) = rect
138
+ return min(xMin, xMax), min(yMin, yMax), max(xMin, xMax), max(yMin, yMax)
139
+
140
+
141
+ def scaleRect(rect, x, y):
142
+ """Scale a bounding box rectangle.
143
+
144
+ Args:
145
+ rect: A bounding rectangle expressed as a tuple
146
+ ``(xMin, yMin, xMax, yMax)``.
147
+ x: Factor to scale the rectangle along the X axis.
148
+ Y: Factor to scale the rectangle along the Y axis.
149
+
150
+ Returns:
151
+ A scaled bounding rectangle.
152
+ """
153
+ (xMin, yMin, xMax, yMax) = rect
154
+ return xMin * x, yMin * y, xMax * x, yMax * y
155
+
156
+
157
+ def offsetRect(rect, dx, dy):
158
+ """Offset a bounding box rectangle.
159
+
160
+ Args:
161
+ rect: A bounding rectangle expressed as a tuple
162
+ ``(xMin, yMin, xMax, yMax)``.
163
+ dx: Amount to offset the rectangle along the X axis.
164
+ dY: Amount to offset the rectangle along the Y axis.
165
+
166
+ Returns:
167
+ An offset bounding rectangle.
168
+ """
169
+ (xMin, yMin, xMax, yMax) = rect
170
+ return xMin + dx, yMin + dy, xMax + dx, yMax + dy
171
+
172
+
173
+ def insetRect(rect, dx, dy):
174
+ """Inset a bounding box rectangle on all sides.
175
+
176
+ Args:
177
+ rect: A bounding rectangle expressed as a tuple
178
+ ``(xMin, yMin, xMax, yMax)``.
179
+ dx: Amount to inset the rectangle along the X axis.
180
+ dY: Amount to inset the rectangle along the Y axis.
181
+
182
+ Returns:
183
+ An inset bounding rectangle.
184
+ """
185
+ (xMin, yMin, xMax, yMax) = rect
186
+ return xMin + dx, yMin + dy, xMax - dx, yMax - dy
187
+
188
+
189
+ def sectRect(rect1, rect2):
190
+ """Test for rectangle-rectangle intersection.
191
+
192
+ Args:
193
+ rect1: First bounding rectangle, expressed as tuples
194
+ ``(xMin, yMin, xMax, yMax)``.
195
+ rect2: Second bounding rectangle.
196
+
197
+ Returns:
198
+ A boolean and a rectangle.
199
+ If the input rectangles intersect, returns ``True`` and the intersecting
200
+ rectangle. Returns ``False`` and ``(0, 0, 0, 0)`` if the input
201
+ rectangles don't intersect.
202
+ """
203
+ (xMin1, yMin1, xMax1, yMax1) = rect1
204
+ (xMin2, yMin2, xMax2, yMax2) = rect2
205
+ xMin, yMin, xMax, yMax = (
206
+ max(xMin1, xMin2),
207
+ max(yMin1, yMin2),
208
+ min(xMax1, xMax2),
209
+ min(yMax1, yMax2),
210
+ )
211
+ if xMin >= xMax or yMin >= yMax:
212
+ return False, (0, 0, 0, 0)
213
+ return True, (xMin, yMin, xMax, yMax)
214
+
215
+
216
+ def unionRect(rect1, rect2):
217
+ """Determine union of bounding rectangles.
218
+
219
+ Args:
220
+ rect1: First bounding rectangle, expressed as tuples
221
+ ``(xMin, yMin, xMax, yMax)``.
222
+ rect2: Second bounding rectangle.
223
+
224
+ Returns:
225
+ The smallest rectangle in which both input rectangles are fully
226
+ enclosed.
227
+ """
228
+ (xMin1, yMin1, xMax1, yMax1) = rect1
229
+ (xMin2, yMin2, xMax2, yMax2) = rect2
230
+ xMin, yMin, xMax, yMax = (
231
+ min(xMin1, xMin2),
232
+ min(yMin1, yMin2),
233
+ max(xMax1, xMax2),
234
+ max(yMax1, yMax2),
235
+ )
236
+ return (xMin, yMin, xMax, yMax)
237
+
238
+
239
+ def rectCenter(rect):
240
+ """Determine rectangle center.
241
+
242
+ Args:
243
+ rect: Bounding rectangle, expressed as tuples
244
+ ``(xMin, yMin, xMax, yMax)``.
245
+
246
+ Returns:
247
+ A 2D tuple representing the point at the center of the rectangle.
248
+ """
249
+ (xMin, yMin, xMax, yMax) = rect
250
+ return (xMin + xMax) / 2, (yMin + yMax) / 2
251
+
252
+
253
+ def rectArea(rect):
254
+ """Determine rectangle area.
255
+
256
+ Args:
257
+ rect: Bounding rectangle, expressed as tuples
258
+ ``(xMin, yMin, xMax, yMax)``.
259
+
260
+ Returns:
261
+ The area of the rectangle.
262
+ """
263
+ (xMin, yMin, xMax, yMax) = rect
264
+ return (yMax - yMin) * (xMax - xMin)
265
+
266
+
267
+ def intRect(rect):
268
+ """Round a rectangle to integer values.
269
+
270
+ Guarantees that the resulting rectangle is NOT smaller than the original.
271
+
272
+ Args:
273
+ rect: Bounding rectangle, expressed as tuples
274
+ ``(xMin, yMin, xMax, yMax)``.
275
+
276
+ Returns:
277
+ A rounded bounding rectangle.
278
+ """
279
+ (xMin, yMin, xMax, yMax) = rect
280
+ xMin = int(math.floor(xMin))
281
+ yMin = int(math.floor(yMin))
282
+ xMax = int(math.ceil(xMax))
283
+ yMax = int(math.ceil(yMax))
284
+ return (xMin, yMin, xMax, yMax)
285
+
286
+
287
+ def quantizeRect(rect, factor=1):
288
+ """
289
+ >>> bounds = (72.3, -218.4, 1201.3, 919.1)
290
+ >>> quantizeRect(bounds)
291
+ (72, -219, 1202, 920)
292
+ >>> quantizeRect(bounds, factor=10)
293
+ (70, -220, 1210, 920)
294
+ >>> quantizeRect(bounds, factor=100)
295
+ (0, -300, 1300, 1000)
296
+ """
297
+ if factor < 1:
298
+ raise ValueError(f"Expected quantization factor >= 1, found: {factor!r}")
299
+ xMin, yMin, xMax, yMax = normRect(rect)
300
+ return (
301
+ int(math.floor(xMin / factor) * factor),
302
+ int(math.floor(yMin / factor) * factor),
303
+ int(math.ceil(xMax / factor) * factor),
304
+ int(math.ceil(yMax / factor) * factor),
305
+ )
306
+
307
+
308
+ class Vector(_Vector):
309
+ def __init__(self, *args, **kwargs):
310
+ warnings.warn(
311
+ "fontTools.misc.arrayTools.Vector has been deprecated, please use "
312
+ "fontTools.misc.vector.Vector instead.",
313
+ DeprecationWarning,
314
+ )
315
+
316
+
317
+ def pairwise(iterable, reverse=False):
318
+ """Iterate over current and next items in iterable.
319
+
320
+ Args:
321
+ iterable: An iterable
322
+ reverse: If true, iterate in reverse order.
323
+
324
+ Returns:
325
+ A iterable yielding two elements per iteration.
326
+
327
+ Example:
328
+
329
+ >>> tuple(pairwise([]))
330
+ ()
331
+ >>> tuple(pairwise([], reverse=True))
332
+ ()
333
+ >>> tuple(pairwise([0]))
334
+ ((0, 0),)
335
+ >>> tuple(pairwise([0], reverse=True))
336
+ ((0, 0),)
337
+ >>> tuple(pairwise([0, 1]))
338
+ ((0, 1), (1, 0))
339
+ >>> tuple(pairwise([0, 1], reverse=True))
340
+ ((1, 0), (0, 1))
341
+ >>> tuple(pairwise([0, 1, 2]))
342
+ ((0, 1), (1, 2), (2, 0))
343
+ >>> tuple(pairwise([0, 1, 2], reverse=True))
344
+ ((2, 1), (1, 0), (0, 2))
345
+ >>> tuple(pairwise(['a', 'b', 'c', 'd']))
346
+ (('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'a'))
347
+ >>> tuple(pairwise(['a', 'b', 'c', 'd'], reverse=True))
348
+ (('d', 'c'), ('c', 'b'), ('b', 'a'), ('a', 'd'))
349
+ """
350
+ if not iterable:
351
+ return
352
+ if reverse:
353
+ it = reversed(iterable)
354
+ else:
355
+ it = iter(iterable)
356
+ first = next(it, None)
357
+ a = first
358
+ for b in it:
359
+ yield (a, b)
360
+ a = b
361
+ yield (a, first)
362
+
363
+
364
+ def _test():
365
+ """
366
+ >>> import math
367
+ >>> calcBounds([])
368
+ (0, 0, 0, 0)
369
+ >>> calcBounds([(0, 40), (0, 100), (50, 50), (80, 10)])
370
+ (0, 10, 80, 100)
371
+ >>> updateBounds((0, 0, 0, 0), (100, 100))
372
+ (0, 0, 100, 100)
373
+ >>> pointInRect((50, 50), (0, 0, 100, 100))
374
+ True
375
+ >>> pointInRect((0, 0), (0, 0, 100, 100))
376
+ True
377
+ >>> pointInRect((100, 100), (0, 0, 100, 100))
378
+ True
379
+ >>> not pointInRect((101, 100), (0, 0, 100, 100))
380
+ True
381
+ >>> list(pointsInRect([(50, 50), (0, 0), (100, 100), (101, 100)], (0, 0, 100, 100)))
382
+ [True, True, True, False]
383
+ >>> vectorLength((3, 4))
384
+ 5.0
385
+ >>> vectorLength((1, 1)) == math.sqrt(2)
386
+ True
387
+ >>> list(asInt16([0, 0.1, 0.5, 0.9]))
388
+ [0, 0, 1, 1]
389
+ >>> normRect((0, 10, 100, 200))
390
+ (0, 10, 100, 200)
391
+ >>> normRect((100, 200, 0, 10))
392
+ (0, 10, 100, 200)
393
+ >>> scaleRect((10, 20, 50, 150), 1.5, 2)
394
+ (15.0, 40, 75.0, 300)
395
+ >>> offsetRect((10, 20, 30, 40), 5, 6)
396
+ (15, 26, 35, 46)
397
+ >>> insetRect((10, 20, 50, 60), 5, 10)
398
+ (15, 30, 45, 50)
399
+ >>> insetRect((10, 20, 50, 60), -5, -10)
400
+ (5, 10, 55, 70)
401
+ >>> intersects, rect = sectRect((0, 10, 20, 30), (0, 40, 20, 50))
402
+ >>> not intersects
403
+ True
404
+ >>> intersects, rect = sectRect((0, 10, 20, 30), (5, 20, 35, 50))
405
+ >>> intersects
406
+ 1
407
+ >>> rect
408
+ (5, 20, 20, 30)
409
+ >>> unionRect((0, 10, 20, 30), (0, 40, 20, 50))
410
+ (0, 10, 20, 50)
411
+ >>> rectCenter((0, 0, 100, 200))
412
+ (50.0, 100.0)
413
+ >>> rectCenter((0, 0, 100, 199.0))
414
+ (50.0, 99.5)
415
+ >>> intRect((0.9, 2.9, 3.1, 4.1))
416
+ (0, 2, 4, 5)
417
+ """
418
+
419
+
420
+ if __name__ == "__main__":
421
+ import sys
422
+ import doctest
423
+
424
+ sys.exit(doctest.testmod().failed)
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/bezierTools.c ADDED
The diff for this file is too large to render. See raw diff
 
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/bezierTools.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ed03e75f0c25536412e15ccc6072c4642c0ace0037227828bfd5233ff97e8562
3
+ size 4305824
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/bezierTools.py ADDED
@@ -0,0 +1,1490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """fontTools.misc.bezierTools.py -- tools for working with Bezier path segments.
3
+ """
4
+
5
+ from fontTools.misc.arrayTools import calcBounds, sectRect, rectArea
6
+ from fontTools.misc.transform import Identity
7
+ import math
8
+ from collections import namedtuple
9
+
10
+ try:
11
+ import cython
12
+ except (AttributeError, ImportError):
13
+ # if cython not installed, use mock module with no-op decorators and types
14
+ from fontTools.misc import cython
15
+ COMPILED = cython.compiled
16
+
17
+
18
+ EPSILON = 1e-9
19
+
20
+
21
+ Intersection = namedtuple("Intersection", ["pt", "t1", "t2"])
22
+
23
+
24
+ __all__ = [
25
+ "approximateCubicArcLength",
26
+ "approximateCubicArcLengthC",
27
+ "approximateQuadraticArcLength",
28
+ "approximateQuadraticArcLengthC",
29
+ "calcCubicArcLength",
30
+ "calcCubicArcLengthC",
31
+ "calcQuadraticArcLength",
32
+ "calcQuadraticArcLengthC",
33
+ "calcCubicBounds",
34
+ "calcQuadraticBounds",
35
+ "splitLine",
36
+ "splitQuadratic",
37
+ "splitCubic",
38
+ "splitQuadraticAtT",
39
+ "splitCubicAtT",
40
+ "splitCubicAtTC",
41
+ "splitCubicIntoTwoAtTC",
42
+ "solveQuadratic",
43
+ "solveCubic",
44
+ "quadraticPointAtT",
45
+ "cubicPointAtT",
46
+ "cubicPointAtTC",
47
+ "linePointAtT",
48
+ "segmentPointAtT",
49
+ "lineLineIntersections",
50
+ "curveLineIntersections",
51
+ "curveCurveIntersections",
52
+ "segmentSegmentIntersections",
53
+ ]
54
+
55
+
56
+ def calcCubicArcLength(pt1, pt2, pt3, pt4, tolerance=0.005):
57
+ """Calculates the arc length for a cubic Bezier segment.
58
+
59
+ Whereas :func:`approximateCubicArcLength` approximates the length, this
60
+ function calculates it by "measuring", recursively dividing the curve
61
+ until the divided segments are shorter than ``tolerance``.
62
+
63
+ Args:
64
+ pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
65
+ tolerance: Controls the precision of the calcuation.
66
+
67
+ Returns:
68
+ Arc length value.
69
+ """
70
+ return calcCubicArcLengthC(
71
+ complex(*pt1), complex(*pt2), complex(*pt3), complex(*pt4), tolerance
72
+ )
73
+
74
+
75
+ def _split_cubic_into_two(p0, p1, p2, p3):
76
+ mid = (p0 + 3 * (p1 + p2) + p3) * 0.125
77
+ deriv3 = (p3 + p2 - p1 - p0) * 0.125
78
+ return (
79
+ (p0, (p0 + p1) * 0.5, mid - deriv3, mid),
80
+ (mid, mid + deriv3, (p2 + p3) * 0.5, p3),
81
+ )
82
+
83
+
84
+ @cython.returns(cython.double)
85
+ @cython.locals(
86
+ p0=cython.complex,
87
+ p1=cython.complex,
88
+ p2=cython.complex,
89
+ p3=cython.complex,
90
+ )
91
+ @cython.locals(mult=cython.double, arch=cython.double, box=cython.double)
92
+ def _calcCubicArcLengthCRecurse(mult, p0, p1, p2, p3):
93
+ arch = abs(p0 - p3)
94
+ box = abs(p0 - p1) + abs(p1 - p2) + abs(p2 - p3)
95
+ if arch * mult + EPSILON >= box:
96
+ return (arch + box) * 0.5
97
+ else:
98
+ one, two = _split_cubic_into_two(p0, p1, p2, p3)
99
+ return _calcCubicArcLengthCRecurse(mult, *one) + _calcCubicArcLengthCRecurse(
100
+ mult, *two
101
+ )
102
+
103
+
104
+ @cython.returns(cython.double)
105
+ @cython.locals(
106
+ pt1=cython.complex,
107
+ pt2=cython.complex,
108
+ pt3=cython.complex,
109
+ pt4=cython.complex,
110
+ )
111
+ @cython.locals(
112
+ tolerance=cython.double,
113
+ mult=cython.double,
114
+ )
115
+ def calcCubicArcLengthC(pt1, pt2, pt3, pt4, tolerance=0.005):
116
+ """Calculates the arc length for a cubic Bezier segment.
117
+
118
+ Args:
119
+ pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.
120
+ tolerance: Controls the precision of the calcuation.
121
+
122
+ Returns:
123
+ Arc length value.
124
+ """
125
+ mult = 1.0 + 1.5 * tolerance # The 1.5 is a empirical hack; no math
126
+ return _calcCubicArcLengthCRecurse(mult, pt1, pt2, pt3, pt4)
127
+
128
+
129
+ epsilonDigits = 6
130
+ epsilon = 1e-10
131
+
132
+
133
+ @cython.cfunc
134
+ @cython.inline
135
+ @cython.returns(cython.double)
136
+ @cython.locals(v1=cython.complex, v2=cython.complex)
137
+ def _dot(v1, v2):
138
+ return (v1 * v2.conjugate()).real
139
+
140
+
141
+ @cython.cfunc
142
+ @cython.inline
143
+ @cython.returns(cython.double)
144
+ @cython.locals(x=cython.double)
145
+ def _intSecAtan(x):
146
+ # In : sympy.integrate(sp.sec(sp.atan(x)))
147
+ # Out: x*sqrt(x**2 + 1)/2 + asinh(x)/2
148
+ return x * math.sqrt(x**2 + 1) / 2 + math.asinh(x) / 2
149
+
150
+
151
+ def calcQuadraticArcLength(pt1, pt2, pt3):
152
+ """Calculates the arc length for a quadratic Bezier segment.
153
+
154
+ Args:
155
+ pt1: Start point of the Bezier as 2D tuple.
156
+ pt2: Handle point of the Bezier as 2D tuple.
157
+ pt3: End point of the Bezier as 2D tuple.
158
+
159
+ Returns:
160
+ Arc length value.
161
+
162
+ Example::
163
+
164
+ >>> calcQuadraticArcLength((0, 0), (0, 0), (0, 0)) # empty segment
165
+ 0.0
166
+ >>> calcQuadraticArcLength((0, 0), (50, 0), (80, 0)) # collinear points
167
+ 80.0
168
+ >>> calcQuadraticArcLength((0, 0), (0, 50), (0, 80)) # collinear points vertical
169
+ 80.0
170
+ >>> calcQuadraticArcLength((0, 0), (50, 20), (100, 40)) # collinear points
171
+ 107.70329614269008
172
+ >>> calcQuadraticArcLength((0, 0), (0, 100), (100, 0))
173
+ 154.02976155645263
174
+ >>> calcQuadraticArcLength((0, 0), (0, 50), (100, 0))
175
+ 120.21581243984076
176
+ >>> calcQuadraticArcLength((0, 0), (50, -10), (80, 50))
177
+ 102.53273816445825
178
+ >>> calcQuadraticArcLength((0, 0), (40, 0), (-40, 0)) # collinear points, control point outside
179
+ 66.66666666666667
180
+ >>> calcQuadraticArcLength((0, 0), (40, 0), (0, 0)) # collinear points, looping back
181
+ 40.0
182
+ """
183
+ return calcQuadraticArcLengthC(complex(*pt1), complex(*pt2), complex(*pt3))
184
+
185
+
186
+ @cython.returns(cython.double)
187
+ @cython.locals(
188
+ pt1=cython.complex,
189
+ pt2=cython.complex,
190
+ pt3=cython.complex,
191
+ d0=cython.complex,
192
+ d1=cython.complex,
193
+ d=cython.complex,
194
+ n=cython.complex,
195
+ )
196
+ @cython.locals(
197
+ scale=cython.double,
198
+ origDist=cython.double,
199
+ a=cython.double,
200
+ b=cython.double,
201
+ x0=cython.double,
202
+ x1=cython.double,
203
+ Len=cython.double,
204
+ )
205
+ def calcQuadraticArcLengthC(pt1, pt2, pt3):
206
+ """Calculates the arc length for a quadratic Bezier segment.
207
+
208
+ Args:
209
+ pt1: Start point of the Bezier as a complex number.
210
+ pt2: Handle point of the Bezier as a complex number.
211
+ pt3: End point of the Bezier as a complex number.
212
+
213
+ Returns:
214
+ Arc length value.
215
+ """
216
+ # Analytical solution to the length of a quadratic bezier.
217
+ # Documentation: https://github.com/fonttools/fonttools/issues/3055
218
+ d0 = pt2 - pt1
219
+ d1 = pt3 - pt2
220
+ d = d1 - d0
221
+ n = d * 1j
222
+ scale = abs(n)
223
+ if scale == 0.0:
224
+ return abs(pt3 - pt1)
225
+ origDist = _dot(n, d0)
226
+ if abs(origDist) < epsilon:
227
+ if _dot(d0, d1) >= 0:
228
+ return abs(pt3 - pt1)
229
+ a, b = abs(d0), abs(d1)
230
+ return (a * a + b * b) / (a + b)
231
+ x0 = _dot(d, d0) / origDist
232
+ x1 = _dot(d, d1) / origDist
233
+ Len = abs(2 * (_intSecAtan(x1) - _intSecAtan(x0)) * origDist / (scale * (x1 - x0)))
234
+ return Len
235
+
236
+
237
+ def approximateQuadraticArcLength(pt1, pt2, pt3):
238
+ """Calculates the arc length for a quadratic Bezier segment.
239
+
240
+ Uses Gauss-Legendre quadrature for a branch-free approximation.
241
+ See :func:`calcQuadraticArcLength` for a slower but more accurate result.
242
+
243
+ Args:
244
+ pt1: Start point of the Bezier as 2D tuple.
245
+ pt2: Handle point of the Bezier as 2D tuple.
246
+ pt3: End point of the Bezier as 2D tuple.
247
+
248
+ Returns:
249
+ Approximate arc length value.
250
+ """
251
+ return approximateQuadraticArcLengthC(complex(*pt1), complex(*pt2), complex(*pt3))
252
+
253
+
254
+ @cython.returns(cython.double)
255
+ @cython.locals(
256
+ pt1=cython.complex,
257
+ pt2=cython.complex,
258
+ pt3=cython.complex,
259
+ )
260
+ @cython.locals(
261
+ v0=cython.double,
262
+ v1=cython.double,
263
+ v2=cython.double,
264
+ )
265
+ def approximateQuadraticArcLengthC(pt1, pt2, pt3):
266
+ """Calculates the arc length for a quadratic Bezier segment.
267
+
268
+ Uses Gauss-Legendre quadrature for a branch-free approximation.
269
+ See :func:`calcQuadraticArcLength` for a slower but more accurate result.
270
+
271
+ Args:
272
+ pt1: Start point of the Bezier as a complex number.
273
+ pt2: Handle point of the Bezier as a complex number.
274
+ pt3: End point of the Bezier as a complex number.
275
+
276
+ Returns:
277
+ Approximate arc length value.
278
+ """
279
+ # This, essentially, approximates the length-of-derivative function
280
+ # to be integrated with the best-matching fifth-degree polynomial
281
+ # approximation of it.
282
+ #
283
+ # https://en.wikipedia.org/wiki/Gaussian_quadrature#Gauss.E2.80.93Legendre_quadrature
284
+
285
+ # abs(BezierCurveC[2].diff(t).subs({t:T})) for T in sorted(.5, .5±sqrt(3/5)/2),
286
+ # weighted 5/18, 8/18, 5/18 respectively.
287
+ v0 = abs(
288
+ -0.492943519233745 * pt1 + 0.430331482911935 * pt2 + 0.0626120363218102 * pt3
289
+ )
290
+ v1 = abs(pt3 - pt1) * 0.4444444444444444
291
+ v2 = abs(
292
+ -0.0626120363218102 * pt1 - 0.430331482911935 * pt2 + 0.492943519233745 * pt3
293
+ )
294
+
295
+ return v0 + v1 + v2
296
+
297
+
298
+ def calcQuadraticBounds(pt1, pt2, pt3):
299
+ """Calculates the bounding rectangle for a quadratic Bezier segment.
300
+
301
+ Args:
302
+ pt1: Start point of the Bezier as a 2D tuple.
303
+ pt2: Handle point of the Bezier as a 2D tuple.
304
+ pt3: End point of the Bezier as a 2D tuple.
305
+
306
+ Returns:
307
+ A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
308
+
309
+ Example::
310
+
311
+ >>> calcQuadraticBounds((0, 0), (50, 100), (100, 0))
312
+ (0, 0, 100, 50.0)
313
+ >>> calcQuadraticBounds((0, 0), (100, 0), (100, 100))
314
+ (0.0, 0.0, 100, 100)
315
+ """
316
+ (ax, ay), (bx, by), (cx, cy) = calcQuadraticParameters(pt1, pt2, pt3)
317
+ ax2 = ax * 2.0
318
+ ay2 = ay * 2.0
319
+ roots = []
320
+ if ax2 != 0:
321
+ roots.append(-bx / ax2)
322
+ if ay2 != 0:
323
+ roots.append(-by / ay2)
324
+ points = [
325
+ (ax * t * t + bx * t + cx, ay * t * t + by * t + cy)
326
+ for t in roots
327
+ if 0 <= t < 1
328
+ ] + [pt1, pt3]
329
+ return calcBounds(points)
330
+
331
+
332
+ def approximateCubicArcLength(pt1, pt2, pt3, pt4):
333
+ """Approximates the arc length for a cubic Bezier segment.
334
+
335
+ Uses Gauss-Lobatto quadrature with n=5 points to approximate arc length.
336
+ See :func:`calcCubicArcLength` for a slower but more accurate result.
337
+
338
+ Args:
339
+ pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
340
+
341
+ Returns:
342
+ Arc length value.
343
+
344
+ Example::
345
+
346
+ >>> approximateCubicArcLength((0, 0), (25, 100), (75, 100), (100, 0))
347
+ 190.04332968932817
348
+ >>> approximateCubicArcLength((0, 0), (50, 0), (100, 50), (100, 100))
349
+ 154.8852074945903
350
+ >>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (150, 0)) # line; exact result should be 150.
351
+ 149.99999999999991
352
+ >>> approximateCubicArcLength((0, 0), (50, 0), (100, 0), (-50, 0)) # cusp; exact result should be 150.
353
+ 136.9267662156362
354
+ >>> approximateCubicArcLength((0, 0), (50, 0), (100, -50), (-50, 0)) # cusp
355
+ 154.80848416537057
356
+ """
357
+ return approximateCubicArcLengthC(
358
+ complex(*pt1), complex(*pt2), complex(*pt3), complex(*pt4)
359
+ )
360
+
361
+
362
+ @cython.returns(cython.double)
363
+ @cython.locals(
364
+ pt1=cython.complex,
365
+ pt2=cython.complex,
366
+ pt3=cython.complex,
367
+ pt4=cython.complex,
368
+ )
369
+ @cython.locals(
370
+ v0=cython.double,
371
+ v1=cython.double,
372
+ v2=cython.double,
373
+ v3=cython.double,
374
+ v4=cython.double,
375
+ )
376
+ def approximateCubicArcLengthC(pt1, pt2, pt3, pt4):
377
+ """Approximates the arc length for a cubic Bezier segment.
378
+
379
+ Args:
380
+ pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.
381
+
382
+ Returns:
383
+ Arc length value.
384
+ """
385
+ # This, essentially, approximates the length-of-derivative function
386
+ # to be integrated with the best-matching seventh-degree polynomial
387
+ # approximation of it.
388
+ #
389
+ # https://en.wikipedia.org/wiki/Gaussian_quadrature#Gauss.E2.80.93Lobatto_rules
390
+
391
+ # abs(BezierCurveC[3].diff(t).subs({t:T})) for T in sorted(0, .5±(3/7)**.5/2, .5, 1),
392
+ # weighted 1/20, 49/180, 32/90, 49/180, 1/20 respectively.
393
+ v0 = abs(pt2 - pt1) * 0.15
394
+ v1 = abs(
395
+ -0.558983582205757 * pt1
396
+ + 0.325650248872424 * pt2
397
+ + 0.208983582205757 * pt3
398
+ + 0.024349751127576 * pt4
399
+ )
400
+ v2 = abs(pt4 - pt1 + pt3 - pt2) * 0.26666666666666666
401
+ v3 = abs(
402
+ -0.024349751127576 * pt1
403
+ - 0.208983582205757 * pt2
404
+ - 0.325650248872424 * pt3
405
+ + 0.558983582205757 * pt4
406
+ )
407
+ v4 = abs(pt4 - pt3) * 0.15
408
+
409
+ return v0 + v1 + v2 + v3 + v4
410
+
411
+
412
+ def calcCubicBounds(pt1, pt2, pt3, pt4):
413
+ """Calculates the bounding rectangle for a quadratic Bezier segment.
414
+
415
+ Args:
416
+ pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
417
+
418
+ Returns:
419
+ A four-item tuple representing the bounding rectangle ``(xMin, yMin, xMax, yMax)``.
420
+
421
+ Example::
422
+
423
+ >>> calcCubicBounds((0, 0), (25, 100), (75, 100), (100, 0))
424
+ (0, 0, 100, 75.0)
425
+ >>> calcCubicBounds((0, 0), (50, 0), (100, 50), (100, 100))
426
+ (0.0, 0.0, 100, 100)
427
+ >>> print("%f %f %f %f" % calcCubicBounds((50, 0), (0, 100), (100, 100), (50, 0)))
428
+ 35.566243 0.000000 64.433757 75.000000
429
+ """
430
+ (ax, ay), (bx, by), (cx, cy), (dx, dy) = calcCubicParameters(pt1, pt2, pt3, pt4)
431
+ # calc first derivative
432
+ ax3 = ax * 3.0
433
+ ay3 = ay * 3.0
434
+ bx2 = bx * 2.0
435
+ by2 = by * 2.0
436
+ xRoots = [t for t in solveQuadratic(ax3, bx2, cx) if 0 <= t < 1]
437
+ yRoots = [t for t in solveQuadratic(ay3, by2, cy) if 0 <= t < 1]
438
+ roots = xRoots + yRoots
439
+
440
+ points = [
441
+ (
442
+ ax * t * t * t + bx * t * t + cx * t + dx,
443
+ ay * t * t * t + by * t * t + cy * t + dy,
444
+ )
445
+ for t in roots
446
+ ] + [pt1, pt4]
447
+ return calcBounds(points)
448
+
449
+
450
+ def splitLine(pt1, pt2, where, isHorizontal):
451
+ """Split a line at a given coordinate.
452
+
453
+ Args:
454
+ pt1: Start point of line as 2D tuple.
455
+ pt2: End point of line as 2D tuple.
456
+ where: Position at which to split the line.
457
+ isHorizontal: Direction of the ray splitting the line. If true,
458
+ ``where`` is interpreted as a Y coordinate; if false, then
459
+ ``where`` is interpreted as an X coordinate.
460
+
461
+ Returns:
462
+ A list of two line segments (each line segment being two 2D tuples)
463
+ if the line was successfully split, or a list containing the original
464
+ line.
465
+
466
+ Example::
467
+
468
+ >>> printSegments(splitLine((0, 0), (100, 100), 50, True))
469
+ ((0, 0), (50, 50))
470
+ ((50, 50), (100, 100))
471
+ >>> printSegments(splitLine((0, 0), (100, 100), 100, True))
472
+ ((0, 0), (100, 100))
473
+ >>> printSegments(splitLine((0, 0), (100, 100), 0, True))
474
+ ((0, 0), (0, 0))
475
+ ((0, 0), (100, 100))
476
+ >>> printSegments(splitLine((0, 0), (100, 100), 0, False))
477
+ ((0, 0), (0, 0))
478
+ ((0, 0), (100, 100))
479
+ >>> printSegments(splitLine((100, 0), (0, 0), 50, False))
480
+ ((100, 0), (50, 0))
481
+ ((50, 0), (0, 0))
482
+ >>> printSegments(splitLine((0, 100), (0, 0), 50, True))
483
+ ((0, 100), (0, 50))
484
+ ((0, 50), (0, 0))
485
+ """
486
+ pt1x, pt1y = pt1
487
+ pt2x, pt2y = pt2
488
+
489
+ ax = pt2x - pt1x
490
+ ay = pt2y - pt1y
491
+
492
+ bx = pt1x
493
+ by = pt1y
494
+
495
+ a = (ax, ay)[isHorizontal]
496
+
497
+ if a == 0:
498
+ return [(pt1, pt2)]
499
+ t = (where - (bx, by)[isHorizontal]) / a
500
+ if 0 <= t < 1:
501
+ midPt = ax * t + bx, ay * t + by
502
+ return [(pt1, midPt), (midPt, pt2)]
503
+ else:
504
+ return [(pt1, pt2)]
505
+
506
+
507
+ def splitQuadratic(pt1, pt2, pt3, where, isHorizontal):
508
+ """Split a quadratic Bezier curve at a given coordinate.
509
+
510
+ Args:
511
+ pt1,pt2,pt3: Control points of the Bezier as 2D tuples.
512
+ where: Position at which to split the curve.
513
+ isHorizontal: Direction of the ray splitting the curve. If true,
514
+ ``where`` is interpreted as a Y coordinate; if false, then
515
+ ``where`` is interpreted as an X coordinate.
516
+
517
+ Returns:
518
+ A list of two curve segments (each curve segment being three 2D tuples)
519
+ if the curve was successfully split, or a list containing the original
520
+ curve.
521
+
522
+ Example::
523
+
524
+ >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 150, False))
525
+ ((0, 0), (50, 100), (100, 0))
526
+ >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, False))
527
+ ((0, 0), (25, 50), (50, 50))
528
+ ((50, 50), (75, 50), (100, 0))
529
+ >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, False))
530
+ ((0, 0), (12.5, 25), (25, 37.5))
531
+ ((25, 37.5), (62.5, 75), (100, 0))
532
+ >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 25, True))
533
+ ((0, 0), (7.32233, 14.6447), (14.6447, 25))
534
+ ((14.6447, 25), (50, 75), (85.3553, 25))
535
+ ((85.3553, 25), (92.6777, 14.6447), (100, -7.10543e-15))
536
+ >>> # XXX I'm not at all sure if the following behavior is desirable:
537
+ >>> printSegments(splitQuadratic((0, 0), (50, 100), (100, 0), 50, True))
538
+ ((0, 0), (25, 50), (50, 50))
539
+ ((50, 50), (50, 50), (50, 50))
540
+ ((50, 50), (75, 50), (100, 0))
541
+ """
542
+ a, b, c = calcQuadraticParameters(pt1, pt2, pt3)
543
+ solutions = solveQuadratic(
544
+ a[isHorizontal], b[isHorizontal], c[isHorizontal] - where
545
+ )
546
+ solutions = sorted(t for t in solutions if 0 <= t < 1)
547
+ if not solutions:
548
+ return [(pt1, pt2, pt3)]
549
+ return _splitQuadraticAtT(a, b, c, *solutions)
550
+
551
+
552
+ def splitCubic(pt1, pt2, pt3, pt4, where, isHorizontal):
553
+ """Split a cubic Bezier curve at a given coordinate.
554
+
555
+ Args:
556
+ pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
557
+ where: Position at which to split the curve.
558
+ isHorizontal: Direction of the ray splitting the curve. If true,
559
+ ``where`` is interpreted as a Y coordinate; if false, then
560
+ ``where`` is interpreted as an X coordinate.
561
+
562
+ Returns:
563
+ A list of two curve segments (each curve segment being four 2D tuples)
564
+ if the curve was successfully split, or a list containing the original
565
+ curve.
566
+
567
+ Example::
568
+
569
+ >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 150, False))
570
+ ((0, 0), (25, 100), (75, 100), (100, 0))
571
+ >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 50, False))
572
+ ((0, 0), (12.5, 50), (31.25, 75), (50, 75))
573
+ ((50, 75), (68.75, 75), (87.5, 50), (100, 0))
574
+ >>> printSegments(splitCubic((0, 0), (25, 100), (75, 100), (100, 0), 25, True))
575
+ ((0, 0), (2.29379, 9.17517), (4.79804, 17.5085), (7.47414, 25))
576
+ ((7.47414, 25), (31.2886, 91.6667), (68.7114, 91.6667), (92.5259, 25))
577
+ ((92.5259, 25), (95.202, 17.5085), (97.7062, 9.17517), (100, 1.77636e-15))
578
+ """
579
+ a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4)
580
+ solutions = solveCubic(
581
+ a[isHorizontal], b[isHorizontal], c[isHorizontal], d[isHorizontal] - where
582
+ )
583
+ solutions = sorted(t for t in solutions if 0 <= t < 1)
584
+ if not solutions:
585
+ return [(pt1, pt2, pt3, pt4)]
586
+ return _splitCubicAtT(a, b, c, d, *solutions)
587
+
588
+
589
+ def splitQuadraticAtT(pt1, pt2, pt3, *ts):
590
+ """Split a quadratic Bezier curve at one or more values of t.
591
+
592
+ Args:
593
+ pt1,pt2,pt3: Control points of the Bezier as 2D tuples.
594
+ *ts: Positions at which to split the curve.
595
+
596
+ Returns:
597
+ A list of curve segments (each curve segment being three 2D tuples).
598
+
599
+ Examples::
600
+
601
+ >>> printSegments(splitQuadraticAtT((0, 0), (50, 100), (100, 0), 0.5))
602
+ ((0, 0), (25, 50), (50, 50))
603
+ ((50, 50), (75, 50), (100, 0))
604
+ >>> printSegments(splitQuadraticAtT((0, 0), (50, 100), (100, 0), 0.5, 0.75))
605
+ ((0, 0), (25, 50), (50, 50))
606
+ ((50, 50), (62.5, 50), (75, 37.5))
607
+ ((75, 37.5), (87.5, 25), (100, 0))
608
+ """
609
+ a, b, c = calcQuadraticParameters(pt1, pt2, pt3)
610
+ return _splitQuadraticAtT(a, b, c, *ts)
611
+
612
+
613
+ def splitCubicAtT(pt1, pt2, pt3, pt4, *ts):
614
+ """Split a cubic Bezier curve at one or more values of t.
615
+
616
+ Args:
617
+ pt1,pt2,pt3,pt4: Control points of the Bezier as 2D tuples.
618
+ *ts: Positions at which to split the curve.
619
+
620
+ Returns:
621
+ A list of curve segments (each curve segment being four 2D tuples).
622
+
623
+ Examples::
624
+
625
+ >>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5))
626
+ ((0, 0), (12.5, 50), (31.25, 75), (50, 75))
627
+ ((50, 75), (68.75, 75), (87.5, 50), (100, 0))
628
+ >>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5, 0.75))
629
+ ((0, 0), (12.5, 50), (31.25, 75), (50, 75))
630
+ ((50, 75), (59.375, 75), (68.75, 68.75), (77.3438, 56.25))
631
+ ((77.3438, 56.25), (85.9375, 43.75), (93.75, 25), (100, 0))
632
+ """
633
+ a, b, c, d = calcCubicParameters(pt1, pt2, pt3, pt4)
634
+ return _splitCubicAtT(a, b, c, d, *ts)
635
+
636
+
637
+ @cython.locals(
638
+ pt1=cython.complex,
639
+ pt2=cython.complex,
640
+ pt3=cython.complex,
641
+ pt4=cython.complex,
642
+ a=cython.complex,
643
+ b=cython.complex,
644
+ c=cython.complex,
645
+ d=cython.complex,
646
+ )
647
+ def splitCubicAtTC(pt1, pt2, pt3, pt4, *ts):
648
+ """Split a cubic Bezier curve at one or more values of t.
649
+
650
+ Args:
651
+ pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers..
652
+ *ts: Positions at which to split the curve.
653
+
654
+ Yields:
655
+ Curve segments (each curve segment being four complex numbers).
656
+ """
657
+ a, b, c, d = calcCubicParametersC(pt1, pt2, pt3, pt4)
658
+ yield from _splitCubicAtTC(a, b, c, d, *ts)
659
+
660
+
661
+ @cython.returns(cython.complex)
662
+ @cython.locals(
663
+ t=cython.double,
664
+ pt1=cython.complex,
665
+ pt2=cython.complex,
666
+ pt3=cython.complex,
667
+ pt4=cython.complex,
668
+ pointAtT=cython.complex,
669
+ off1=cython.complex,
670
+ off2=cython.complex,
671
+ )
672
+ @cython.locals(
673
+ t2=cython.double, _1_t=cython.double, _1_t_2=cython.double, _2_t_1_t=cython.double
674
+ )
675
+ def splitCubicIntoTwoAtTC(pt1, pt2, pt3, pt4, t):
676
+ """Split a cubic Bezier curve at t.
677
+
678
+ Args:
679
+ pt1,pt2,pt3,pt4: Control points of the Bezier as complex numbers.
680
+ t: Position at which to split the curve.
681
+
682
+ Returns:
683
+ A tuple of two curve segments (each curve segment being four complex numbers).
684
+ """
685
+ t2 = t * t
686
+ _1_t = 1 - t
687
+ _1_t_2 = _1_t * _1_t
688
+ _2_t_1_t = 2 * t * _1_t
689
+ pointAtT = (
690
+ _1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4
691
+ )
692
+ off1 = _1_t_2 * pt1 + _2_t_1_t * pt2 + t2 * pt3
693
+ off2 = _1_t_2 * pt2 + _2_t_1_t * pt3 + t2 * pt4
694
+
695
+ pt2 = pt1 + (pt2 - pt1) * t
696
+ pt3 = pt4 + (pt3 - pt4) * _1_t
697
+
698
+ return ((pt1, pt2, off1, pointAtT), (pointAtT, off2, pt3, pt4))
699
+
700
+
701
+ def _splitQuadraticAtT(a, b, c, *ts):
702
+ ts = list(ts)
703
+ segments = []
704
+ ts.insert(0, 0.0)
705
+ ts.append(1.0)
706
+ ax, ay = a
707
+ bx, by = b
708
+ cx, cy = c
709
+ for i in range(len(ts) - 1):
710
+ t1 = ts[i]
711
+ t2 = ts[i + 1]
712
+ delta = t2 - t1
713
+ # calc new a, b and c
714
+ delta_2 = delta * delta
715
+ a1x = ax * delta_2
716
+ a1y = ay * delta_2
717
+ b1x = (2 * ax * t1 + bx) * delta
718
+ b1y = (2 * ay * t1 + by) * delta
719
+ t1_2 = t1 * t1
720
+ c1x = ax * t1_2 + bx * t1 + cx
721
+ c1y = ay * t1_2 + by * t1 + cy
722
+
723
+ pt1, pt2, pt3 = calcQuadraticPoints((a1x, a1y), (b1x, b1y), (c1x, c1y))
724
+ segments.append((pt1, pt2, pt3))
725
+ return segments
726
+
727
+
728
+ def _splitCubicAtT(a, b, c, d, *ts):
729
+ ts = list(ts)
730
+ ts.insert(0, 0.0)
731
+ ts.append(1.0)
732
+ segments = []
733
+ ax, ay = a
734
+ bx, by = b
735
+ cx, cy = c
736
+ dx, dy = d
737
+ for i in range(len(ts) - 1):
738
+ t1 = ts[i]
739
+ t2 = ts[i + 1]
740
+ delta = t2 - t1
741
+
742
+ delta_2 = delta * delta
743
+ delta_3 = delta * delta_2
744
+ t1_2 = t1 * t1
745
+ t1_3 = t1 * t1_2
746
+
747
+ # calc new a, b, c and d
748
+ a1x = ax * delta_3
749
+ a1y = ay * delta_3
750
+ b1x = (3 * ax * t1 + bx) * delta_2
751
+ b1y = (3 * ay * t1 + by) * delta_2
752
+ c1x = (2 * bx * t1 + cx + 3 * ax * t1_2) * delta
753
+ c1y = (2 * by * t1 + cy + 3 * ay * t1_2) * delta
754
+ d1x = ax * t1_3 + bx * t1_2 + cx * t1 + dx
755
+ d1y = ay * t1_3 + by * t1_2 + cy * t1 + dy
756
+ pt1, pt2, pt3, pt4 = calcCubicPoints(
757
+ (a1x, a1y), (b1x, b1y), (c1x, c1y), (d1x, d1y)
758
+ )
759
+ segments.append((pt1, pt2, pt3, pt4))
760
+ return segments
761
+
762
+
763
+ @cython.locals(
764
+ a=cython.complex,
765
+ b=cython.complex,
766
+ c=cython.complex,
767
+ d=cython.complex,
768
+ t1=cython.double,
769
+ t2=cython.double,
770
+ delta=cython.double,
771
+ delta_2=cython.double,
772
+ delta_3=cython.double,
773
+ a1=cython.complex,
774
+ b1=cython.complex,
775
+ c1=cython.complex,
776
+ d1=cython.complex,
777
+ )
778
+ def _splitCubicAtTC(a, b, c, d, *ts):
779
+ ts = list(ts)
780
+ ts.insert(0, 0.0)
781
+ ts.append(1.0)
782
+ for i in range(len(ts) - 1):
783
+ t1 = ts[i]
784
+ t2 = ts[i + 1]
785
+ delta = t2 - t1
786
+
787
+ delta_2 = delta * delta
788
+ delta_3 = delta * delta_2
789
+ t1_2 = t1 * t1
790
+ t1_3 = t1 * t1_2
791
+
792
+ # calc new a, b, c and d
793
+ a1 = a * delta_3
794
+ b1 = (3 * a * t1 + b) * delta_2
795
+ c1 = (2 * b * t1 + c + 3 * a * t1_2) * delta
796
+ d1 = a * t1_3 + b * t1_2 + c * t1 + d
797
+ pt1, pt2, pt3, pt4 = calcCubicPointsC(a1, b1, c1, d1)
798
+ yield (pt1, pt2, pt3, pt4)
799
+
800
+
801
+ #
802
+ # Equation solvers.
803
+ #
804
+
805
+ from math import sqrt, acos, cos, pi
806
+
807
+
808
+ def solveQuadratic(a, b, c, sqrt=sqrt):
809
+ """Solve a quadratic equation.
810
+
811
+ Solves *a*x*x + b*x + c = 0* where a, b and c are real.
812
+
813
+ Args:
814
+ a: coefficient of *x²*
815
+ b: coefficient of *x*
816
+ c: constant term
817
+
818
+ Returns:
819
+ A list of roots. Note that the returned list is neither guaranteed to
820
+ be sorted nor to contain unique values!
821
+ """
822
+ if abs(a) < epsilon:
823
+ if abs(b) < epsilon:
824
+ # We have a non-equation; therefore, we have no valid solution
825
+ roots = []
826
+ else:
827
+ # We have a linear equation with 1 root.
828
+ roots = [-c / b]
829
+ else:
830
+ # We have a true quadratic equation. Apply the quadratic formula to find two roots.
831
+ DD = b * b - 4.0 * a * c
832
+ if DD >= 0.0:
833
+ rDD = sqrt(DD)
834
+ roots = [(-b + rDD) / 2.0 / a, (-b - rDD) / 2.0 / a]
835
+ else:
836
+ # complex roots, ignore
837
+ roots = []
838
+ return roots
839
+
840
+
841
+ def solveCubic(a, b, c, d):
842
+ """Solve a cubic equation.
843
+
844
+ Solves *a*x*x*x + b*x*x + c*x + d = 0* where a, b, c and d are real.
845
+
846
+ Args:
847
+ a: coefficient of *x³*
848
+ b: coefficient of *x²*
849
+ c: coefficient of *x*
850
+ d: constant term
851
+
852
+ Returns:
853
+ A list of roots. Note that the returned list is neither guaranteed to
854
+ be sorted nor to contain unique values!
855
+
856
+ Examples::
857
+
858
+ >>> solveCubic(1, 1, -6, 0)
859
+ [-3.0, -0.0, 2.0]
860
+ >>> solveCubic(-10.0, -9.0, 48.0, -29.0)
861
+ [-2.9, 1.0, 1.0]
862
+ >>> solveCubic(-9.875, -9.0, 47.625, -28.75)
863
+ [-2.911392, 1.0, 1.0]
864
+ >>> solveCubic(1.0, -4.5, 6.75, -3.375)
865
+ [1.5, 1.5, 1.5]
866
+ >>> solveCubic(-12.0, 18.0, -9.0, 1.50023651123)
867
+ [0.5, 0.5, 0.5]
868
+ >>> solveCubic(
869
+ ... 9.0, 0.0, 0.0, -7.62939453125e-05
870
+ ... ) == [-0.0, -0.0, -0.0]
871
+ True
872
+ """
873
+ #
874
+ # adapted from:
875
+ # CUBIC.C - Solve a cubic polynomial
876
+ # public domain by Ross Cottrell
877
+ # found at: http://www.strangecreations.com/library/snippets/Cubic.C
878
+ #
879
+ if abs(a) < epsilon:
880
+ # don't just test for zero; for very small values of 'a' solveCubic()
881
+ # returns unreliable results, so we fall back to quad.
882
+ return solveQuadratic(b, c, d)
883
+ a = float(a)
884
+ a1 = b / a
885
+ a2 = c / a
886
+ a3 = d / a
887
+
888
+ Q = (a1 * a1 - 3.0 * a2) / 9.0
889
+ R = (2.0 * a1 * a1 * a1 - 9.0 * a1 * a2 + 27.0 * a3) / 54.0
890
+
891
+ R2 = R * R
892
+ Q3 = Q * Q * Q
893
+ R2 = 0 if R2 < epsilon else R2
894
+ Q3 = 0 if abs(Q3) < epsilon else Q3
895
+
896
+ R2_Q3 = R2 - Q3
897
+
898
+ if R2 == 0.0 and Q3 == 0.0:
899
+ x = round(-a1 / 3.0, epsilonDigits)
900
+ return [x, x, x]
901
+ elif R2_Q3 <= epsilon * 0.5:
902
+ # The epsilon * .5 above ensures that Q3 is not zero.
903
+ theta = acos(max(min(R / sqrt(Q3), 1.0), -1.0))
904
+ rQ2 = -2.0 * sqrt(Q)
905
+ a1_3 = a1 / 3.0
906
+ x0 = rQ2 * cos(theta / 3.0) - a1_3
907
+ x1 = rQ2 * cos((theta + 2.0 * pi) / 3.0) - a1_3
908
+ x2 = rQ2 * cos((theta + 4.0 * pi) / 3.0) - a1_3
909
+ x0, x1, x2 = sorted([x0, x1, x2])
910
+ # Merge roots that are close-enough
911
+ if x1 - x0 < epsilon and x2 - x1 < epsilon:
912
+ x0 = x1 = x2 = round((x0 + x1 + x2) / 3.0, epsilonDigits)
913
+ elif x1 - x0 < epsilon:
914
+ x0 = x1 = round((x0 + x1) / 2.0, epsilonDigits)
915
+ x2 = round(x2, epsilonDigits)
916
+ elif x2 - x1 < epsilon:
917
+ x0 = round(x0, epsilonDigits)
918
+ x1 = x2 = round((x1 + x2) / 2.0, epsilonDigits)
919
+ else:
920
+ x0 = round(x0, epsilonDigits)
921
+ x1 = round(x1, epsilonDigits)
922
+ x2 = round(x2, epsilonDigits)
923
+ return [x0, x1, x2]
924
+ else:
925
+ x = pow(sqrt(R2_Q3) + abs(R), 1 / 3.0)
926
+ x = x + Q / x
927
+ if R >= 0.0:
928
+ x = -x
929
+ x = round(x - a1 / 3.0, epsilonDigits)
930
+ return [x]
931
+
932
+
933
+ #
934
+ # Conversion routines for points to parameters and vice versa
935
+ #
936
+
937
+
938
+ def calcQuadraticParameters(pt1, pt2, pt3):
939
+ x2, y2 = pt2
940
+ x3, y3 = pt3
941
+ cx, cy = pt1
942
+ bx = (x2 - cx) * 2.0
943
+ by = (y2 - cy) * 2.0
944
+ ax = x3 - cx - bx
945
+ ay = y3 - cy - by
946
+ return (ax, ay), (bx, by), (cx, cy)
947
+
948
+
949
+ def calcCubicParameters(pt1, pt2, pt3, pt4):
950
+ x2, y2 = pt2
951
+ x3, y3 = pt3
952
+ x4, y4 = pt4
953
+ dx, dy = pt1
954
+ cx = (x2 - dx) * 3.0
955
+ cy = (y2 - dy) * 3.0
956
+ bx = (x3 - x2) * 3.0 - cx
957
+ by = (y3 - y2) * 3.0 - cy
958
+ ax = x4 - dx - cx - bx
959
+ ay = y4 - dy - cy - by
960
+ return (ax, ay), (bx, by), (cx, cy), (dx, dy)
961
+
962
+
963
+ @cython.cfunc
964
+ @cython.inline
965
+ @cython.locals(
966
+ pt1=cython.complex,
967
+ pt2=cython.complex,
968
+ pt3=cython.complex,
969
+ pt4=cython.complex,
970
+ a=cython.complex,
971
+ b=cython.complex,
972
+ c=cython.complex,
973
+ )
974
+ def calcCubicParametersC(pt1, pt2, pt3, pt4):
975
+ c = (pt2 - pt1) * 3.0
976
+ b = (pt3 - pt2) * 3.0 - c
977
+ a = pt4 - pt1 - c - b
978
+ return (a, b, c, pt1)
979
+
980
+
981
+ def calcQuadraticPoints(a, b, c):
982
+ ax, ay = a
983
+ bx, by = b
984
+ cx, cy = c
985
+ x1 = cx
986
+ y1 = cy
987
+ x2 = (bx * 0.5) + cx
988
+ y2 = (by * 0.5) + cy
989
+ x3 = ax + bx + cx
990
+ y3 = ay + by + cy
991
+ return (x1, y1), (x2, y2), (x3, y3)
992
+
993
+
994
+ def calcCubicPoints(a, b, c, d):
995
+ ax, ay = a
996
+ bx, by = b
997
+ cx, cy = c
998
+ dx, dy = d
999
+ x1 = dx
1000
+ y1 = dy
1001
+ x2 = (cx / 3.0) + dx
1002
+ y2 = (cy / 3.0) + dy
1003
+ x3 = (bx + cx) / 3.0 + x2
1004
+ y3 = (by + cy) / 3.0 + y2
1005
+ x4 = ax + dx + cx + bx
1006
+ y4 = ay + dy + cy + by
1007
+ return (x1, y1), (x2, y2), (x3, y3), (x4, y4)
1008
+
1009
+
1010
+ @cython.cfunc
1011
+ @cython.inline
1012
+ @cython.locals(
1013
+ a=cython.complex,
1014
+ b=cython.complex,
1015
+ c=cython.complex,
1016
+ d=cython.complex,
1017
+ p2=cython.complex,
1018
+ p3=cython.complex,
1019
+ p4=cython.complex,
1020
+ )
1021
+ def calcCubicPointsC(a, b, c, d):
1022
+ p2 = c * (1 / 3) + d
1023
+ p3 = (b + c) * (1 / 3) + p2
1024
+ p4 = a + b + c + d
1025
+ return (d, p2, p3, p4)
1026
+
1027
+
1028
+ #
1029
+ # Point at time
1030
+ #
1031
+
1032
+
1033
+ def linePointAtT(pt1, pt2, t):
1034
+ """Finds the point at time `t` on a line.
1035
+
1036
+ Args:
1037
+ pt1, pt2: Coordinates of the line as 2D tuples.
1038
+ t: The time along the line.
1039
+
1040
+ Returns:
1041
+ A 2D tuple with the coordinates of the point.
1042
+ """
1043
+ return ((pt1[0] * (1 - t) + pt2[0] * t), (pt1[1] * (1 - t) + pt2[1] * t))
1044
+
1045
+
1046
+ def quadraticPointAtT(pt1, pt2, pt3, t):
1047
+ """Finds the point at time `t` on a quadratic curve.
1048
+
1049
+ Args:
1050
+ pt1, pt2, pt3: Coordinates of the curve as 2D tuples.
1051
+ t: The time along the curve.
1052
+
1053
+ Returns:
1054
+ A 2D tuple with the coordinates of the point.
1055
+ """
1056
+ x = (1 - t) * (1 - t) * pt1[0] + 2 * (1 - t) * t * pt2[0] + t * t * pt3[0]
1057
+ y = (1 - t) * (1 - t) * pt1[1] + 2 * (1 - t) * t * pt2[1] + t * t * pt3[1]
1058
+ return (x, y)
1059
+
1060
+
1061
+ def cubicPointAtT(pt1, pt2, pt3, pt4, t):
1062
+ """Finds the point at time `t` on a cubic curve.
1063
+
1064
+ Args:
1065
+ pt1, pt2, pt3, pt4: Coordinates of the curve as 2D tuples.
1066
+ t: The time along the curve.
1067
+
1068
+ Returns:
1069
+ A 2D tuple with the coordinates of the point.
1070
+ """
1071
+ t2 = t * t
1072
+ _1_t = 1 - t
1073
+ _1_t_2 = _1_t * _1_t
1074
+ x = (
1075
+ _1_t_2 * _1_t * pt1[0]
1076
+ + 3 * (_1_t_2 * t * pt2[0] + _1_t * t2 * pt3[0])
1077
+ + t2 * t * pt4[0]
1078
+ )
1079
+ y = (
1080
+ _1_t_2 * _1_t * pt1[1]
1081
+ + 3 * (_1_t_2 * t * pt2[1] + _1_t * t2 * pt3[1])
1082
+ + t2 * t * pt4[1]
1083
+ )
1084
+ return (x, y)
1085
+
1086
+
1087
+ @cython.returns(cython.complex)
1088
+ @cython.locals(
1089
+ t=cython.double,
1090
+ pt1=cython.complex,
1091
+ pt2=cython.complex,
1092
+ pt3=cython.complex,
1093
+ pt4=cython.complex,
1094
+ )
1095
+ @cython.locals(t2=cython.double, _1_t=cython.double, _1_t_2=cython.double)
1096
+ def cubicPointAtTC(pt1, pt2, pt3, pt4, t):
1097
+ """Finds the point at time `t` on a cubic curve.
1098
+
1099
+ Args:
1100
+ pt1, pt2, pt3, pt4: Coordinates of the curve as complex numbers.
1101
+ t: The time along the curve.
1102
+
1103
+ Returns:
1104
+ A complex number with the coordinates of the point.
1105
+ """
1106
+ t2 = t * t
1107
+ _1_t = 1 - t
1108
+ _1_t_2 = _1_t * _1_t
1109
+ return _1_t_2 * _1_t * pt1 + 3 * (_1_t_2 * t * pt2 + _1_t * t2 * pt3) + t2 * t * pt4
1110
+
1111
+
1112
+ def segmentPointAtT(seg, t):
1113
+ if len(seg) == 2:
1114
+ return linePointAtT(*seg, t)
1115
+ elif len(seg) == 3:
1116
+ return quadraticPointAtT(*seg, t)
1117
+ elif len(seg) == 4:
1118
+ return cubicPointAtT(*seg, t)
1119
+ raise ValueError("Unknown curve degree")
1120
+
1121
+
1122
+ #
1123
+ # Intersection finders
1124
+ #
1125
+
1126
+
1127
+ def _line_t_of_pt(s, e, pt):
1128
+ sx, sy = s
1129
+ ex, ey = e
1130
+ px, py = pt
1131
+ if abs(sx - ex) < epsilon and abs(sy - ey) < epsilon:
1132
+ # Line is a point!
1133
+ return -1
1134
+ # Use the largest
1135
+ if abs(sx - ex) > abs(sy - ey):
1136
+ return (px - sx) / (ex - sx)
1137
+ else:
1138
+ return (py - sy) / (ey - sy)
1139
+
1140
+
1141
+ def _both_points_are_on_same_side_of_origin(a, b, origin):
1142
+ xDiff = (a[0] - origin[0]) * (b[0] - origin[0])
1143
+ yDiff = (a[1] - origin[1]) * (b[1] - origin[1])
1144
+ return not (xDiff <= 0.0 and yDiff <= 0.0)
1145
+
1146
+
1147
+ def lineLineIntersections(s1, e1, s2, e2):
1148
+ """Finds intersections between two line segments.
1149
+
1150
+ Args:
1151
+ s1, e1: Coordinates of the first line as 2D tuples.
1152
+ s2, e2: Coordinates of the second line as 2D tuples.
1153
+
1154
+ Returns:
1155
+ A list of ``Intersection`` objects, each object having ``pt``, ``t1``
1156
+ and ``t2`` attributes containing the intersection point, time on first
1157
+ segment and time on second segment respectively.
1158
+
1159
+ Examples::
1160
+
1161
+ >>> a = lineLineIntersections( (310,389), (453, 222), (289, 251), (447, 367))
1162
+ >>> len(a)
1163
+ 1
1164
+ >>> intersection = a[0]
1165
+ >>> intersection.pt
1166
+ (374.44882952482897, 313.73458370177315)
1167
+ >>> (intersection.t1, intersection.t2)
1168
+ (0.45069111555824465, 0.5408153767394238)
1169
+ """
1170
+ s1x, s1y = s1
1171
+ e1x, e1y = e1
1172
+ s2x, s2y = s2
1173
+ e2x, e2y = e2
1174
+ if (
1175
+ math.isclose(s2x, e2x) and math.isclose(s1x, e1x) and not math.isclose(s1x, s2x)
1176
+ ): # Parallel vertical
1177
+ return []
1178
+ if (
1179
+ math.isclose(s2y, e2y) and math.isclose(s1y, e1y) and not math.isclose(s1y, s2y)
1180
+ ): # Parallel horizontal
1181
+ return []
1182
+ if math.isclose(s2x, e2x) and math.isclose(s2y, e2y): # Line segment is tiny
1183
+ return []
1184
+ if math.isclose(s1x, e1x) and math.isclose(s1y, e1y): # Line segment is tiny
1185
+ return []
1186
+ if math.isclose(e1x, s1x):
1187
+ x = s1x
1188
+ slope34 = (e2y - s2y) / (e2x - s2x)
1189
+ y = slope34 * (x - s2x) + s2y
1190
+ pt = (x, y)
1191
+ return [
1192
+ Intersection(
1193
+ pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt)
1194
+ )
1195
+ ]
1196
+ if math.isclose(s2x, e2x):
1197
+ x = s2x
1198
+ slope12 = (e1y - s1y) / (e1x - s1x)
1199
+ y = slope12 * (x - s1x) + s1y
1200
+ pt = (x, y)
1201
+ return [
1202
+ Intersection(
1203
+ pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt)
1204
+ )
1205
+ ]
1206
+
1207
+ slope12 = (e1y - s1y) / (e1x - s1x)
1208
+ slope34 = (e2y - s2y) / (e2x - s2x)
1209
+ if math.isclose(slope12, slope34):
1210
+ return []
1211
+ x = (slope12 * s1x - s1y - slope34 * s2x + s2y) / (slope12 - slope34)
1212
+ y = slope12 * (x - s1x) + s1y
1213
+ pt = (x, y)
1214
+ if _both_points_are_on_same_side_of_origin(
1215
+ pt, e1, s1
1216
+ ) and _both_points_are_on_same_side_of_origin(pt, s2, e2):
1217
+ return [
1218
+ Intersection(
1219
+ pt=pt, t1=_line_t_of_pt(s1, e1, pt), t2=_line_t_of_pt(s2, e2, pt)
1220
+ )
1221
+ ]
1222
+ return []
1223
+
1224
+
1225
+ def _alignment_transformation(segment):
1226
+ # Returns a transformation which aligns a segment horizontally at the
1227
+ # origin. Apply this transformation to curves and root-find to find
1228
+ # intersections with the segment.
1229
+ start = segment[0]
1230
+ end = segment[-1]
1231
+ angle = math.atan2(end[1] - start[1], end[0] - start[0])
1232
+ return Identity.rotate(-angle).translate(-start[0], -start[1])
1233
+
1234
+
1235
+ def _curve_line_intersections_t(curve, line):
1236
+ aligned_curve = _alignment_transformation(line).transformPoints(curve)
1237
+ if len(curve) == 3:
1238
+ a, b, c = calcQuadraticParameters(*aligned_curve)
1239
+ intersections = solveQuadratic(a[1], b[1], c[1])
1240
+ elif len(curve) == 4:
1241
+ a, b, c, d = calcCubicParameters(*aligned_curve)
1242
+ intersections = solveCubic(a[1], b[1], c[1], d[1])
1243
+ else:
1244
+ raise ValueError("Unknown curve degree")
1245
+ return sorted(i for i in intersections if 0.0 <= i <= 1)
1246
+
1247
+
1248
+ def curveLineIntersections(curve, line):
1249
+ """Finds intersections between a curve and a line.
1250
+
1251
+ Args:
1252
+ curve: List of coordinates of the curve segment as 2D tuples.
1253
+ line: List of coordinates of the line segment as 2D tuples.
1254
+
1255
+ Returns:
1256
+ A list of ``Intersection`` objects, each object having ``pt``, ``t1``
1257
+ and ``t2`` attributes containing the intersection point, time on first
1258
+ segment and time on second segment respectively.
1259
+
1260
+ Examples::
1261
+ >>> curve = [ (100, 240), (30, 60), (210, 230), (160, 30) ]
1262
+ >>> line = [ (25, 260), (230, 20) ]
1263
+ >>> intersections = curveLineIntersections(curve, line)
1264
+ >>> len(intersections)
1265
+ 3
1266
+ >>> intersections[0].pt
1267
+ (84.9000930760723, 189.87306176459828)
1268
+ """
1269
+ if len(curve) == 3:
1270
+ pointFinder = quadraticPointAtT
1271
+ elif len(curve) == 4:
1272
+ pointFinder = cubicPointAtT
1273
+ else:
1274
+ raise ValueError("Unknown curve degree")
1275
+ intersections = []
1276
+ for t in _curve_line_intersections_t(curve, line):
1277
+ pt = pointFinder(*curve, t)
1278
+ # Back-project the point onto the line, to avoid problems with
1279
+ # numerical accuracy in the case of vertical and horizontal lines
1280
+ line_t = _line_t_of_pt(*line, pt)
1281
+ pt = linePointAtT(*line, line_t)
1282
+ intersections.append(Intersection(pt=pt, t1=t, t2=line_t))
1283
+ return intersections
1284
+
1285
+
1286
+ def _curve_bounds(c):
1287
+ if len(c) == 3:
1288
+ return calcQuadraticBounds(*c)
1289
+ elif len(c) == 4:
1290
+ return calcCubicBounds(*c)
1291
+ raise ValueError("Unknown curve degree")
1292
+
1293
+
1294
+ def _split_segment_at_t(c, t):
1295
+ if len(c) == 2:
1296
+ s, e = c
1297
+ midpoint = linePointAtT(s, e, t)
1298
+ return [(s, midpoint), (midpoint, e)]
1299
+ if len(c) == 3:
1300
+ return splitQuadraticAtT(*c, t)
1301
+ elif len(c) == 4:
1302
+ return splitCubicAtT(*c, t)
1303
+ raise ValueError("Unknown curve degree")
1304
+
1305
+
1306
+ def _curve_curve_intersections_t(
1307
+ curve1, curve2, precision=1e-3, range1=None, range2=None
1308
+ ):
1309
+ bounds1 = _curve_bounds(curve1)
1310
+ bounds2 = _curve_bounds(curve2)
1311
+
1312
+ if not range1:
1313
+ range1 = (0.0, 1.0)
1314
+ if not range2:
1315
+ range2 = (0.0, 1.0)
1316
+
1317
+ # If bounds don't intersect, go home
1318
+ intersects, _ = sectRect(bounds1, bounds2)
1319
+ if not intersects:
1320
+ return []
1321
+
1322
+ def midpoint(r):
1323
+ return 0.5 * (r[0] + r[1])
1324
+
1325
+ # If they do overlap but they're tiny, approximate
1326
+ if rectArea(bounds1) < precision and rectArea(bounds2) < precision:
1327
+ return [(midpoint(range1), midpoint(range2))]
1328
+
1329
+ c11, c12 = _split_segment_at_t(curve1, 0.5)
1330
+ c11_range = (range1[0], midpoint(range1))
1331
+ c12_range = (midpoint(range1), range1[1])
1332
+
1333
+ c21, c22 = _split_segment_at_t(curve2, 0.5)
1334
+ c21_range = (range2[0], midpoint(range2))
1335
+ c22_range = (midpoint(range2), range2[1])
1336
+
1337
+ found = []
1338
+ found.extend(
1339
+ _curve_curve_intersections_t(
1340
+ c11, c21, precision, range1=c11_range, range2=c21_range
1341
+ )
1342
+ )
1343
+ found.extend(
1344
+ _curve_curve_intersections_t(
1345
+ c12, c21, precision, range1=c12_range, range2=c21_range
1346
+ )
1347
+ )
1348
+ found.extend(
1349
+ _curve_curve_intersections_t(
1350
+ c11, c22, precision, range1=c11_range, range2=c22_range
1351
+ )
1352
+ )
1353
+ found.extend(
1354
+ _curve_curve_intersections_t(
1355
+ c12, c22, precision, range1=c12_range, range2=c22_range
1356
+ )
1357
+ )
1358
+
1359
+ unique_key = lambda ts: (int(ts[0] / precision), int(ts[1] / precision))
1360
+ seen = set()
1361
+ unique_values = []
1362
+
1363
+ for ts in found:
1364
+ key = unique_key(ts)
1365
+ if key in seen:
1366
+ continue
1367
+ seen.add(key)
1368
+ unique_values.append(ts)
1369
+
1370
+ return unique_values
1371
+
1372
+
1373
+ def _is_linelike(segment):
1374
+ maybeline = _alignment_transformation(segment).transformPoints(segment)
1375
+ return all(math.isclose(p[1], 0.0) for p in maybeline)
1376
+
1377
+
1378
+ def curveCurveIntersections(curve1, curve2):
1379
+ """Finds intersections between a curve and a curve.
1380
+
1381
+ Args:
1382
+ curve1: List of coordinates of the first curve segment as 2D tuples.
1383
+ curve2: List of coordinates of the second curve segment as 2D tuples.
1384
+
1385
+ Returns:
1386
+ A list of ``Intersection`` objects, each object having ``pt``, ``t1``
1387
+ and ``t2`` attributes containing the intersection point, time on first
1388
+ segment and time on second segment respectively.
1389
+
1390
+ Examples::
1391
+ >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ]
1392
+ >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ]
1393
+ >>> intersections = curveCurveIntersections(curve1, curve2)
1394
+ >>> len(intersections)
1395
+ 3
1396
+ >>> intersections[0].pt
1397
+ (81.7831487395506, 109.88904552375288)
1398
+ """
1399
+ if _is_linelike(curve1):
1400
+ line1 = curve1[0], curve1[-1]
1401
+ if _is_linelike(curve2):
1402
+ line2 = curve2[0], curve2[-1]
1403
+ return lineLineIntersections(*line1, *line2)
1404
+ else:
1405
+ return curveLineIntersections(curve2, line1)
1406
+ elif _is_linelike(curve2):
1407
+ line2 = curve2[0], curve2[-1]
1408
+ return curveLineIntersections(curve1, line2)
1409
+
1410
+ intersection_ts = _curve_curve_intersections_t(curve1, curve2)
1411
+ return [
1412
+ Intersection(pt=segmentPointAtT(curve1, ts[0]), t1=ts[0], t2=ts[1])
1413
+ for ts in intersection_ts
1414
+ ]
1415
+
1416
+
1417
+ def segmentSegmentIntersections(seg1, seg2):
1418
+ """Finds intersections between two segments.
1419
+
1420
+ Args:
1421
+ seg1: List of coordinates of the first segment as 2D tuples.
1422
+ seg2: List of coordinates of the second segment as 2D tuples.
1423
+
1424
+ Returns:
1425
+ A list of ``Intersection`` objects, each object having ``pt``, ``t1``
1426
+ and ``t2`` attributes containing the intersection point, time on first
1427
+ segment and time on second segment respectively.
1428
+
1429
+ Examples::
1430
+ >>> curve1 = [ (10,100), (90,30), (40,140), (220,220) ]
1431
+ >>> curve2 = [ (5,150), (180,20), (80,250), (210,190) ]
1432
+ >>> intersections = segmentSegmentIntersections(curve1, curve2)
1433
+ >>> len(intersections)
1434
+ 3
1435
+ >>> intersections[0].pt
1436
+ (81.7831487395506, 109.88904552375288)
1437
+ >>> curve3 = [ (100, 240), (30, 60), (210, 230), (160, 30) ]
1438
+ >>> line = [ (25, 260), (230, 20) ]
1439
+ >>> intersections = segmentSegmentIntersections(curve3, line)
1440
+ >>> len(intersections)
1441
+ 3
1442
+ >>> intersections[0].pt
1443
+ (84.9000930760723, 189.87306176459828)
1444
+
1445
+ """
1446
+ # Arrange by degree
1447
+ swapped = False
1448
+ if len(seg2) > len(seg1):
1449
+ seg2, seg1 = seg1, seg2
1450
+ swapped = True
1451
+ if len(seg1) > 2:
1452
+ if len(seg2) > 2:
1453
+ intersections = curveCurveIntersections(seg1, seg2)
1454
+ else:
1455
+ intersections = curveLineIntersections(seg1, seg2)
1456
+ elif len(seg1) == 2 and len(seg2) == 2:
1457
+ intersections = lineLineIntersections(*seg1, *seg2)
1458
+ else:
1459
+ raise ValueError("Couldn't work out which intersection function to use")
1460
+ if not swapped:
1461
+ return intersections
1462
+ return [Intersection(pt=i.pt, t1=i.t2, t2=i.t1) for i in intersections]
1463
+
1464
+
1465
+ def _segmentrepr(obj):
1466
+ """
1467
+ >>> _segmentrepr([1, [2, 3], [], [[2, [3, 4], [0.1, 2.2]]]])
1468
+ '(1, (2, 3), (), ((2, (3, 4), (0.1, 2.2))))'
1469
+ """
1470
+ try:
1471
+ it = iter(obj)
1472
+ except TypeError:
1473
+ return "%g" % obj
1474
+ else:
1475
+ return "(%s)" % ", ".join(_segmentrepr(x) for x in it)
1476
+
1477
+
1478
+ def printSegments(segments):
1479
+ """Helper for the doctests, displaying each segment in a list of
1480
+ segments on a single line as a tuple.
1481
+ """
1482
+ for segment in segments:
1483
+ print(_segmentrepr(segment))
1484
+
1485
+
1486
+ if __name__ == "__main__":
1487
+ import sys
1488
+ import doctest
1489
+
1490
+ sys.exit(doctest.testmod().failed)
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/classifyTools.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ fontTools.misc.classifyTools.py -- tools for classifying things.
2
+ """
3
+
4
+
5
+ class Classifier(object):
6
+ """
7
+ Main Classifier object, used to classify things into similar sets.
8
+ """
9
+
10
+ def __init__(self, sort=True):
11
+ self._things = set() # set of all things known so far
12
+ self._sets = [] # list of class sets produced so far
13
+ self._mapping = {} # map from things to their class set
14
+ self._dirty = False
15
+ self._sort = sort
16
+
17
+ def add(self, set_of_things):
18
+ """
19
+ Add a set to the classifier. Any iterable is accepted.
20
+ """
21
+ if not set_of_things:
22
+ return
23
+
24
+ self._dirty = True
25
+
26
+ things, sets, mapping = self._things, self._sets, self._mapping
27
+
28
+ s = set(set_of_things)
29
+ intersection = s.intersection(things) # existing things
30
+ s.difference_update(intersection) # new things
31
+ difference = s
32
+ del s
33
+
34
+ # Add new class for new things
35
+ if difference:
36
+ things.update(difference)
37
+ sets.append(difference)
38
+ for thing in difference:
39
+ mapping[thing] = difference
40
+ del difference
41
+
42
+ while intersection:
43
+ # Take one item and process the old class it belongs to
44
+ old_class = mapping[next(iter(intersection))]
45
+ old_class_intersection = old_class.intersection(intersection)
46
+
47
+ # Update old class to remove items from new set
48
+ old_class.difference_update(old_class_intersection)
49
+
50
+ # Remove processed items from todo list
51
+ intersection.difference_update(old_class_intersection)
52
+
53
+ # Add new class for the intersection with old class
54
+ sets.append(old_class_intersection)
55
+ for thing in old_class_intersection:
56
+ mapping[thing] = old_class_intersection
57
+ del old_class_intersection
58
+
59
+ def update(self, list_of_sets):
60
+ """
61
+ Add a a list of sets to the classifier. Any iterable of iterables is accepted.
62
+ """
63
+ for s in list_of_sets:
64
+ self.add(s)
65
+
66
+ def _process(self):
67
+ if not self._dirty:
68
+ return
69
+
70
+ # Do any deferred processing
71
+ sets = self._sets
72
+ self._sets = [s for s in sets if s]
73
+
74
+ if self._sort:
75
+ self._sets = sorted(self._sets, key=lambda s: (-len(s), sorted(s)))
76
+
77
+ self._dirty = False
78
+
79
+ # Output methods
80
+
81
+ def getThings(self):
82
+ """Returns the set of all things known so far.
83
+
84
+ The return value belongs to the Classifier object and should NOT
85
+ be modified while the classifier is still in use.
86
+ """
87
+ self._process()
88
+ return self._things
89
+
90
+ def getMapping(self):
91
+ """Returns the mapping from things to their class set.
92
+
93
+ The return value belongs to the Classifier object and should NOT
94
+ be modified while the classifier is still in use.
95
+ """
96
+ self._process()
97
+ return self._mapping
98
+
99
+ def getClasses(self):
100
+ """Returns the list of class sets.
101
+
102
+ The return value belongs to the Classifier object and should NOT
103
+ be modified while the classifier is still in use.
104
+ """
105
+ self._process()
106
+ return self._sets
107
+
108
+
109
+ def classify(list_of_sets, sort=True):
110
+ """
111
+ Takes a iterable of iterables (list of sets from here on; but any
112
+ iterable works.), and returns the smallest list of sets such that
113
+ each set, is either a subset, or is disjoint from, each of the input
114
+ sets.
115
+
116
+ In other words, this function classifies all the things present in
117
+ any of the input sets, into similar classes, based on which sets
118
+ things are a member of.
119
+
120
+ If sort=True, return class sets are sorted by decreasing size and
121
+ their natural sort order within each class size. Otherwise, class
122
+ sets are returned in the order that they were identified, which is
123
+ generally not significant.
124
+
125
+ >>> classify([]) == ([], {})
126
+ True
127
+ >>> classify([[]]) == ([], {})
128
+ True
129
+ >>> classify([[], []]) == ([], {})
130
+ True
131
+ >>> classify([[1]]) == ([{1}], {1: {1}})
132
+ True
133
+ >>> classify([[1,2]]) == ([{1, 2}], {1: {1, 2}, 2: {1, 2}})
134
+ True
135
+ >>> classify([[1],[2]]) == ([{1}, {2}], {1: {1}, 2: {2}})
136
+ True
137
+ >>> classify([[1,2],[2]]) == ([{1}, {2}], {1: {1}, 2: {2}})
138
+ True
139
+ >>> classify([[1,2],[2,4]]) == ([{1}, {2}, {4}], {1: {1}, 2: {2}, 4: {4}})
140
+ True
141
+ >>> classify([[1,2],[2,4,5]]) == (
142
+ ... [{4, 5}, {1}, {2}], {1: {1}, 2: {2}, 4: {4, 5}, 5: {4, 5}})
143
+ True
144
+ >>> classify([[1,2],[2,4,5]], sort=False) == (
145
+ ... [{1}, {4, 5}, {2}], {1: {1}, 2: {2}, 4: {4, 5}, 5: {4, 5}})
146
+ True
147
+ >>> classify([[1,2,9],[2,4,5]], sort=False) == (
148
+ ... [{1, 9}, {4, 5}, {2}], {1: {1, 9}, 2: {2}, 4: {4, 5}, 5: {4, 5},
149
+ ... 9: {1, 9}})
150
+ True
151
+ >>> classify([[1,2,9,15],[2,4,5]], sort=False) == (
152
+ ... [{1, 9, 15}, {4, 5}, {2}], {1: {1, 9, 15}, 2: {2}, 4: {4, 5},
153
+ ... 5: {4, 5}, 9: {1, 9, 15}, 15: {1, 9, 15}})
154
+ True
155
+ >>> classes, mapping = classify([[1,2,9,15],[2,4,5],[15,5]], sort=False)
156
+ >>> set([frozenset(c) for c in classes]) == set(
157
+ ... [frozenset(s) for s in ({1, 9}, {4}, {2}, {5}, {15})])
158
+ True
159
+ >>> mapping == {1: {1, 9}, 2: {2}, 4: {4}, 5: {5}, 9: {1, 9}, 15: {15}}
160
+ True
161
+ """
162
+ classifier = Classifier(sort=sort)
163
+ classifier.update(list_of_sets)
164
+ return classifier.getClasses(), classifier.getMapping()
165
+
166
+
167
+ if __name__ == "__main__":
168
+ import sys, doctest
169
+
170
+ sys.exit(doctest.testmod(optionflags=doctest.ELLIPSIS).failed)
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/cliTools.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Collection of utilities for command-line interfaces and console scripts."""
2
+
3
+ import os
4
+ import re
5
+
6
+
7
+ numberAddedRE = re.compile(r"#\d+$")
8
+
9
+
10
+ def makeOutputFileName(
11
+ input, outputDir=None, extension=None, overWrite=False, suffix=""
12
+ ):
13
+ """Generates a suitable file name for writing output.
14
+
15
+ Often tools will want to take a file, do some kind of transformation to it,
16
+ and write it out again. This function determines an appropriate name for the
17
+ output file, through one or more of the following steps:
18
+
19
+ - changing the output directory
20
+ - appending suffix before file extension
21
+ - replacing the file extension
22
+ - suffixing the filename with a number (``#1``, ``#2``, etc.) to avoid
23
+ overwriting an existing file.
24
+
25
+ Args:
26
+ input: Name of input file.
27
+ outputDir: Optionally, a new directory to write the file into.
28
+ suffix: Optionally, a string suffix is appended to file name before
29
+ the extension.
30
+ extension: Optionally, a replacement for the current file extension.
31
+ overWrite: Overwriting an existing file is permitted if true; if false
32
+ and the proposed filename exists, a new name will be generated by
33
+ adding an appropriate number suffix.
34
+
35
+ Returns:
36
+ str: Suitable output filename
37
+ """
38
+ dirName, fileName = os.path.split(input)
39
+ fileName, ext = os.path.splitext(fileName)
40
+ if outputDir:
41
+ dirName = outputDir
42
+ fileName = numberAddedRE.split(fileName)[0]
43
+ if extension is None:
44
+ extension = os.path.splitext(input)[1]
45
+ output = os.path.join(dirName, fileName + suffix + extension)
46
+ n = 1
47
+ if not overWrite:
48
+ while os.path.exists(output):
49
+ output = os.path.join(
50
+ dirName, fileName + suffix + "#" + repr(n) + extension
51
+ )
52
+ n += 1
53
+ return output
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/configTools.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Code of the config system; not related to fontTools or fonts in particular.
3
+
4
+ The options that are specific to fontTools are in :mod:`fontTools.config`.
5
+
6
+ To create your own config system, you need to create an instance of
7
+ :class:`Options`, and a subclass of :class:`AbstractConfig` with its
8
+ ``options`` class variable set to your instance of Options.
9
+
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ from dataclasses import dataclass
16
+ from typing import (
17
+ Any,
18
+ Callable,
19
+ ClassVar,
20
+ Dict,
21
+ Iterable,
22
+ Mapping,
23
+ MutableMapping,
24
+ Optional,
25
+ Set,
26
+ Union,
27
+ )
28
+
29
+
30
+ log = logging.getLogger(__name__)
31
+
32
+ __all__ = [
33
+ "AbstractConfig",
34
+ "ConfigAlreadyRegisteredError",
35
+ "ConfigError",
36
+ "ConfigUnknownOptionError",
37
+ "ConfigValueParsingError",
38
+ "ConfigValueValidationError",
39
+ "Option",
40
+ "Options",
41
+ ]
42
+
43
+
44
+ class ConfigError(Exception):
45
+ """Base exception for the config module."""
46
+
47
+
48
+ class ConfigAlreadyRegisteredError(ConfigError):
49
+ """Raised when a module tries to register a configuration option that
50
+ already exists.
51
+
52
+ Should not be raised too much really, only when developing new fontTools
53
+ modules.
54
+ """
55
+
56
+ def __init__(self, name):
57
+ super().__init__(f"Config option {name} is already registered.")
58
+
59
+
60
+ class ConfigValueParsingError(ConfigError):
61
+ """Raised when a configuration value cannot be parsed."""
62
+
63
+ def __init__(self, name, value):
64
+ super().__init__(
65
+ f"Config option {name}: value cannot be parsed (given {repr(value)})"
66
+ )
67
+
68
+
69
+ class ConfigValueValidationError(ConfigError):
70
+ """Raised when a configuration value cannot be validated."""
71
+
72
+ def __init__(self, name, value):
73
+ super().__init__(
74
+ f"Config option {name}: value is invalid (given {repr(value)})"
75
+ )
76
+
77
+
78
+ class ConfigUnknownOptionError(ConfigError):
79
+ """Raised when a configuration option is unknown."""
80
+
81
+ def __init__(self, option_or_name):
82
+ name = (
83
+ f"'{option_or_name.name}' (id={id(option_or_name)})>"
84
+ if isinstance(option_or_name, Option)
85
+ else f"'{option_or_name}'"
86
+ )
87
+ super().__init__(f"Config option {name} is unknown")
88
+
89
+
90
+ # eq=False because Options are unique, not fungible objects
91
+ @dataclass(frozen=True, eq=False)
92
+ class Option:
93
+ name: str
94
+ """Unique name identifying the option (e.g. package.module:MY_OPTION)."""
95
+ help: str
96
+ """Help text for this option."""
97
+ default: Any
98
+ """Default value for this option."""
99
+ parse: Callable[[str], Any]
100
+ """Turn input (e.g. string) into proper type. Only when reading from file."""
101
+ validate: Optional[Callable[[Any], bool]] = None
102
+ """Return true if the given value is an acceptable value."""
103
+
104
+ @staticmethod
105
+ def parse_optional_bool(v: str) -> Optional[bool]:
106
+ s = str(v).lower()
107
+ if s in {"0", "no", "false"}:
108
+ return False
109
+ if s in {"1", "yes", "true"}:
110
+ return True
111
+ if s in {"auto", "none"}:
112
+ return None
113
+ raise ValueError("invalid optional bool: {v!r}")
114
+
115
+ @staticmethod
116
+ def validate_optional_bool(v: Any) -> bool:
117
+ return v is None or isinstance(v, bool)
118
+
119
+
120
+ class Options(Mapping):
121
+ """Registry of available options for a given config system.
122
+
123
+ Define new options using the :meth:`register()` method.
124
+
125
+ Access existing options using the Mapping interface.
126
+ """
127
+
128
+ __options: Dict[str, Option]
129
+
130
+ def __init__(self, other: "Options" = None) -> None:
131
+ self.__options = {}
132
+ if other is not None:
133
+ for option in other.values():
134
+ self.register_option(option)
135
+
136
+ def register(
137
+ self,
138
+ name: str,
139
+ help: str,
140
+ default: Any,
141
+ parse: Callable[[str], Any],
142
+ validate: Optional[Callable[[Any], bool]] = None,
143
+ ) -> Option:
144
+ """Create and register a new option."""
145
+ return self.register_option(Option(name, help, default, parse, validate))
146
+
147
+ def register_option(self, option: Option) -> Option:
148
+ """Register a new option."""
149
+ name = option.name
150
+ if name in self.__options:
151
+ raise ConfigAlreadyRegisteredError(name)
152
+ self.__options[name] = option
153
+ return option
154
+
155
+ def is_registered(self, option: Option) -> bool:
156
+ """Return True if the same option object is already registered."""
157
+ return self.__options.get(option.name) is option
158
+
159
+ def __getitem__(self, key: str) -> Option:
160
+ return self.__options.__getitem__(key)
161
+
162
+ def __iter__(self) -> Iterator[str]:
163
+ return self.__options.__iter__()
164
+
165
+ def __len__(self) -> int:
166
+ return self.__options.__len__()
167
+
168
+ def __repr__(self) -> str:
169
+ return (
170
+ f"{self.__class__.__name__}({{\n"
171
+ + "".join(
172
+ f" {k!r}: Option(default={v.default!r}, ...),\n"
173
+ for k, v in self.__options.items()
174
+ )
175
+ + "})"
176
+ )
177
+
178
+
179
+ _USE_GLOBAL_DEFAULT = object()
180
+
181
+
182
+ class AbstractConfig(MutableMapping):
183
+ """
184
+ Create a set of config values, optionally pre-filled with values from
185
+ the given dictionary or pre-existing config object.
186
+
187
+ The class implements the MutableMapping protocol keyed by option name (`str`).
188
+ For convenience its methods accept either Option or str as the key parameter.
189
+
190
+ .. seealso:: :meth:`set()`
191
+
192
+ This config class is abstract because it needs its ``options`` class
193
+ var to be set to an instance of :class:`Options` before it can be
194
+ instanciated and used.
195
+
196
+ .. code:: python
197
+
198
+ class MyConfig(AbstractConfig):
199
+ options = Options()
200
+
201
+ MyConfig.register_option( "test:option_name", "This is an option", 0, int, lambda v: isinstance(v, int))
202
+
203
+ cfg = MyConfig({"test:option_name": 10})
204
+
205
+ """
206
+
207
+ options: ClassVar[Options]
208
+
209
+ @classmethod
210
+ def register_option(
211
+ cls,
212
+ name: str,
213
+ help: str,
214
+ default: Any,
215
+ parse: Callable[[str], Any],
216
+ validate: Optional[Callable[[Any], bool]] = None,
217
+ ) -> Option:
218
+ """Register an available option in this config system."""
219
+ return cls.options.register(
220
+ name, help=help, default=default, parse=parse, validate=validate
221
+ )
222
+
223
+ _values: Dict[str, Any]
224
+
225
+ def __init__(
226
+ self,
227
+ values: Union[AbstractConfig, Dict[Union[Option, str], Any]] = {},
228
+ parse_values: bool = False,
229
+ skip_unknown: bool = False,
230
+ ):
231
+ self._values = {}
232
+ values_dict = values._values if isinstance(values, AbstractConfig) else values
233
+ for name, value in values_dict.items():
234
+ self.set(name, value, parse_values, skip_unknown)
235
+
236
+ def _resolve_option(self, option_or_name: Union[Option, str]) -> Option:
237
+ if isinstance(option_or_name, Option):
238
+ option = option_or_name
239
+ if not self.options.is_registered(option):
240
+ raise ConfigUnknownOptionError(option)
241
+ return option
242
+ elif isinstance(option_or_name, str):
243
+ name = option_or_name
244
+ try:
245
+ return self.options[name]
246
+ except KeyError:
247
+ raise ConfigUnknownOptionError(name)
248
+ else:
249
+ raise TypeError(
250
+ "expected Option or str, found "
251
+ f"{type(option_or_name).__name__}: {option_or_name!r}"
252
+ )
253
+
254
+ def set(
255
+ self,
256
+ option_or_name: Union[Option, str],
257
+ value: Any,
258
+ parse_values: bool = False,
259
+ skip_unknown: bool = False,
260
+ ):
261
+ """Set the value of an option.
262
+
263
+ Args:
264
+ * `option_or_name`: an `Option` object or its name (`str`).
265
+ * `value`: the value to be assigned to given option.
266
+ * `parse_values`: parse the configuration value from a string into
267
+ its proper type, as per its `Option` object. The default
268
+ behavior is to raise `ConfigValueValidationError` when the value
269
+ is not of the right type. Useful when reading options from a
270
+ file type that doesn't support as many types as Python.
271
+ * `skip_unknown`: skip unknown configuration options. The default
272
+ behaviour is to raise `ConfigUnknownOptionError`. Useful when
273
+ reading options from a configuration file that has extra entries
274
+ (e.g. for a later version of fontTools)
275
+ """
276
+ try:
277
+ option = self._resolve_option(option_or_name)
278
+ except ConfigUnknownOptionError as e:
279
+ if skip_unknown:
280
+ log.debug(str(e))
281
+ return
282
+ raise
283
+
284
+ # Can be useful if the values come from a source that doesn't have
285
+ # strict typing (.ini file? Terminal input?)
286
+ if parse_values:
287
+ try:
288
+ value = option.parse(value)
289
+ except Exception as e:
290
+ raise ConfigValueParsingError(option.name, value) from e
291
+
292
+ if option.validate is not None and not option.validate(value):
293
+ raise ConfigValueValidationError(option.name, value)
294
+
295
+ self._values[option.name] = value
296
+
297
+ def get(
298
+ self, option_or_name: Union[Option, str], default: Any = _USE_GLOBAL_DEFAULT
299
+ ) -> Any:
300
+ """
301
+ Get the value of an option. The value which is returned is the first
302
+ provided among:
303
+
304
+ 1. a user-provided value in the options's ``self._values`` dict
305
+ 2. a caller-provided default value to this method call
306
+ 3. the global default for the option provided in ``fontTools.config``
307
+
308
+ This is to provide the ability to migrate progressively from config
309
+ options passed as arguments to fontTools APIs to config options read
310
+ from the current TTFont, e.g.
311
+
312
+ .. code:: python
313
+
314
+ def fontToolsAPI(font, some_option):
315
+ value = font.cfg.get("someLib.module:SOME_OPTION", some_option)
316
+ # use value
317
+
318
+ That way, the function will work the same for users of the API that
319
+ still pass the option to the function call, but will favour the new
320
+ config mechanism if the given font specifies a value for that option.
321
+ """
322
+ option = self._resolve_option(option_or_name)
323
+ if option.name in self._values:
324
+ return self._values[option.name]
325
+ if default is not _USE_GLOBAL_DEFAULT:
326
+ return default
327
+ return option.default
328
+
329
+ def copy(self):
330
+ return self.__class__(self._values)
331
+
332
+ def __getitem__(self, option_or_name: Union[Option, str]) -> Any:
333
+ return self.get(option_or_name)
334
+
335
+ def __setitem__(self, option_or_name: Union[Option, str], value: Any) -> None:
336
+ return self.set(option_or_name, value)
337
+
338
+ def __delitem__(self, option_or_name: Union[Option, str]) -> None:
339
+ option = self._resolve_option(option_or_name)
340
+ del self._values[option.name]
341
+
342
+ def __iter__(self) -> Iterable[str]:
343
+ return self._values.__iter__()
344
+
345
+ def __len__(self) -> int:
346
+ return len(self._values)
347
+
348
+ def __repr__(self) -> str:
349
+ return f"{self.__class__.__name__}({repr(self._values)})"
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/cython.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Exports a no-op 'cython' namespace similar to
2
+ https://github.com/cython/cython/blob/master/Cython/Shadow.py
3
+
4
+ This allows to optionally compile @cython decorated functions
5
+ (when cython is available at built time), or run the same code
6
+ as pure-python, without runtime dependency on cython module.
7
+
8
+ We only define the symbols that we use. E.g. see fontTools.cu2qu
9
+ """
10
+
11
+ from types import SimpleNamespace
12
+
13
+
14
+ def _empty_decorator(x):
15
+ return x
16
+
17
+
18
+ compiled = False
19
+
20
+ for name in ("double", "complex", "int"):
21
+ globals()[name] = None
22
+
23
+ for name in ("cfunc", "inline"):
24
+ globals()[name] = _empty_decorator
25
+
26
+ locals = lambda **_: _empty_decorator
27
+ returns = lambda _: _empty_decorator
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/dictTools.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Misc dict tools."""
2
+
3
+ __all__ = ["hashdict"]
4
+
5
+
6
+ # https://stackoverflow.com/questions/1151658/python-hashable-dicts
7
+ class hashdict(dict):
8
+ """
9
+ hashable dict implementation, suitable for use as a key into
10
+ other dicts.
11
+
12
+ >>> h1 = hashdict({"apples": 1, "bananas":2})
13
+ >>> h2 = hashdict({"bananas": 3, "mangoes": 5})
14
+ >>> h1+h2
15
+ hashdict(apples=1, bananas=3, mangoes=5)
16
+ >>> d1 = {}
17
+ >>> d1[h1] = "salad"
18
+ >>> d1[h1]
19
+ 'salad'
20
+ >>> d1[h2]
21
+ Traceback (most recent call last):
22
+ ...
23
+ KeyError: hashdict(bananas=3, mangoes=5)
24
+
25
+ based on answers from
26
+ http://stackoverflow.com/questions/1151658/python-hashable-dicts
27
+
28
+ """
29
+
30
+ def __key(self):
31
+ return tuple(sorted(self.items()))
32
+
33
+ def __repr__(self):
34
+ return "{0}({1})".format(
35
+ self.__class__.__name__,
36
+ ", ".join("{0}={1}".format(str(i[0]), repr(i[1])) for i in self.__key()),
37
+ )
38
+
39
+ def __hash__(self):
40
+ return hash(self.__key())
41
+
42
+ def __setitem__(self, key, value):
43
+ raise TypeError(
44
+ "{0} does not support item assignment".format(self.__class__.__name__)
45
+ )
46
+
47
+ def __delitem__(self, key):
48
+ raise TypeError(
49
+ "{0} does not support item assignment".format(self.__class__.__name__)
50
+ )
51
+
52
+ def clear(self):
53
+ raise TypeError(
54
+ "{0} does not support item assignment".format(self.__class__.__name__)
55
+ )
56
+
57
+ def pop(self, *args, **kwargs):
58
+ raise TypeError(
59
+ "{0} does not support item assignment".format(self.__class__.__name__)
60
+ )
61
+
62
+ def popitem(self, *args, **kwargs):
63
+ raise TypeError(
64
+ "{0} does not support item assignment".format(self.__class__.__name__)
65
+ )
66
+
67
+ def setdefault(self, *args, **kwargs):
68
+ raise TypeError(
69
+ "{0} does not support item assignment".format(self.__class__.__name__)
70
+ )
71
+
72
+ def update(self, *args, **kwargs):
73
+ raise TypeError(
74
+ "{0} does not support item assignment".format(self.__class__.__name__)
75
+ )
76
+
77
+ # update is not ok because it mutates the object
78
+ # __add__ is ok because it creates a new object
79
+ # while the new object is under construction, it's ok to mutate it
80
+ def __add__(self, right):
81
+ result = hashdict(self)
82
+ dict.update(result, right)
83
+ return result
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/eexec.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PostScript Type 1 fonts make use of two types of encryption: charstring
3
+ encryption and ``eexec`` encryption. Charstring encryption is used for
4
+ the charstrings themselves, while ``eexec`` is used to encrypt larger
5
+ sections of the font program, such as the ``Private`` and ``CharStrings``
6
+ dictionaries. Despite the different names, the algorithm is the same,
7
+ although ``eexec`` encryption uses a fixed initial key R=55665.
8
+
9
+ The algorithm uses cipher feedback, meaning that the ciphertext is used
10
+ to modify the key. Because of this, the routines in this module return
11
+ the new key at the end of the operation.
12
+
13
+ """
14
+
15
+ from fontTools.misc.textTools import bytechr, bytesjoin, byteord
16
+
17
+
18
+ def _decryptChar(cipher, R):
19
+ cipher = byteord(cipher)
20
+ plain = ((cipher ^ (R >> 8))) & 0xFF
21
+ R = ((cipher + R) * 52845 + 22719) & 0xFFFF
22
+ return bytechr(plain), R
23
+
24
+
25
+ def _encryptChar(plain, R):
26
+ plain = byteord(plain)
27
+ cipher = ((plain ^ (R >> 8))) & 0xFF
28
+ R = ((cipher + R) * 52845 + 22719) & 0xFFFF
29
+ return bytechr(cipher), R
30
+
31
+
32
+ def decrypt(cipherstring, R):
33
+ r"""
34
+ Decrypts a string using the Type 1 encryption algorithm.
35
+
36
+ Args:
37
+ cipherstring: String of ciphertext.
38
+ R: Initial key.
39
+
40
+ Returns:
41
+ decryptedStr: Plaintext string.
42
+ R: Output key for subsequent decryptions.
43
+
44
+ Examples::
45
+
46
+ >>> testStr = b"\0\0asdadads asds\265"
47
+ >>> decryptedStr, R = decrypt(testStr, 12321)
48
+ >>> decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1'
49
+ True
50
+ >>> R == 36142
51
+ True
52
+ """
53
+ plainList = []
54
+ for cipher in cipherstring:
55
+ plain, R = _decryptChar(cipher, R)
56
+ plainList.append(plain)
57
+ plainstring = bytesjoin(plainList)
58
+ return plainstring, int(R)
59
+
60
+
61
+ def encrypt(plainstring, R):
62
+ r"""
63
+ Encrypts a string using the Type 1 encryption algorithm.
64
+
65
+ Note that the algorithm as described in the Type 1 specification requires the
66
+ plaintext to be prefixed with a number of random bytes. (For ``eexec`` the
67
+ number of random bytes is set to 4.) This routine does *not* add the random
68
+ prefix to its input.
69
+
70
+ Args:
71
+ plainstring: String of plaintext.
72
+ R: Initial key.
73
+
74
+ Returns:
75
+ cipherstring: Ciphertext string.
76
+ R: Output key for subsequent encryptions.
77
+
78
+ Examples::
79
+
80
+ >>> testStr = b"\0\0asdadads asds\265"
81
+ >>> decryptedStr, R = decrypt(testStr, 12321)
82
+ >>> decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1'
83
+ True
84
+ >>> R == 36142
85
+ True
86
+
87
+ >>> testStr = b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1'
88
+ >>> encryptedStr, R = encrypt(testStr, 12321)
89
+ >>> encryptedStr == b"\0\0asdadads asds\265"
90
+ True
91
+ >>> R == 36142
92
+ True
93
+ """
94
+ cipherList = []
95
+ for plain in plainstring:
96
+ cipher, R = _encryptChar(plain, R)
97
+ cipherList.append(cipher)
98
+ cipherstring = bytesjoin(cipherList)
99
+ return cipherstring, int(R)
100
+
101
+
102
+ def hexString(s):
103
+ import binascii
104
+
105
+ return binascii.hexlify(s)
106
+
107
+
108
+ def deHexString(h):
109
+ import binascii
110
+
111
+ h = bytesjoin(h.split())
112
+ return binascii.unhexlify(h)
113
+
114
+
115
+ if __name__ == "__main__":
116
+ import sys
117
+ import doctest
118
+
119
+ sys.exit(doctest.testmod().failed)
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/encodingTools.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """fontTools.misc.encodingTools.py -- tools for working with OpenType encodings.
2
+ """
3
+
4
+ import fontTools.encodings.codecs
5
+
6
+ # Map keyed by platformID, then platEncID, then possibly langID
7
+ _encodingMap = {
8
+ 0: { # Unicode
9
+ 0: "utf_16_be",
10
+ 1: "utf_16_be",
11
+ 2: "utf_16_be",
12
+ 3: "utf_16_be",
13
+ 4: "utf_16_be",
14
+ 5: "utf_16_be",
15
+ 6: "utf_16_be",
16
+ },
17
+ 1: { # Macintosh
18
+ # See
19
+ # https://github.com/fonttools/fonttools/issues/236
20
+ 0: { # Macintosh, platEncID==0, keyed by langID
21
+ 15: "mac_iceland",
22
+ 17: "mac_turkish",
23
+ 18: "mac_croatian",
24
+ 24: "mac_latin2",
25
+ 25: "mac_latin2",
26
+ 26: "mac_latin2",
27
+ 27: "mac_latin2",
28
+ 28: "mac_latin2",
29
+ 36: "mac_latin2",
30
+ 37: "mac_romanian",
31
+ 38: "mac_latin2",
32
+ 39: "mac_latin2",
33
+ 40: "mac_latin2",
34
+ Ellipsis: "mac_roman", # Other
35
+ },
36
+ 1: "x_mac_japanese_ttx",
37
+ 2: "x_mac_trad_chinese_ttx",
38
+ 3: "x_mac_korean_ttx",
39
+ 6: "mac_greek",
40
+ 7: "mac_cyrillic",
41
+ 25: "x_mac_simp_chinese_ttx",
42
+ 29: "mac_latin2",
43
+ 35: "mac_turkish",
44
+ 37: "mac_iceland",
45
+ },
46
+ 2: { # ISO
47
+ 0: "ascii",
48
+ 1: "utf_16_be",
49
+ 2: "latin1",
50
+ },
51
+ 3: { # Microsoft
52
+ 0: "utf_16_be",
53
+ 1: "utf_16_be",
54
+ 2: "shift_jis",
55
+ 3: "gb2312",
56
+ 4: "big5",
57
+ 5: "euc_kr",
58
+ 6: "johab",
59
+ 10: "utf_16_be",
60
+ },
61
+ }
62
+
63
+
64
+ def getEncoding(platformID, platEncID, langID, default=None):
65
+ """Returns the Python encoding name for OpenType platformID/encodingID/langID
66
+ triplet. If encoding for these values is not known, by default None is
67
+ returned. That can be overriden by passing a value to the default argument.
68
+ """
69
+ encoding = _encodingMap.get(platformID, {}).get(platEncID, default)
70
+ if isinstance(encoding, dict):
71
+ encoding = encoding.get(langID, encoding[Ellipsis])
72
+ return encoding
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/etree.py ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shim module exporting the same ElementTree API for lxml and
2
+ xml.etree backends.
3
+
4
+ When lxml is installed, it is automatically preferred over the built-in
5
+ xml.etree module.
6
+ On Python 2.7, the cElementTree module is preferred over the pure-python
7
+ ElementTree module.
8
+
9
+ Besides exporting a unified interface, this also defines extra functions
10
+ or subclasses built-in ElementTree classes to add features that are
11
+ only availble in lxml, like OrderedDict for attributes, pretty_print and
12
+ iterwalk.
13
+ """
14
+
15
+ from fontTools.misc.textTools import tostr
16
+
17
+
18
+ XML_DECLARATION = """<?xml version='1.0' encoding='%s'?>"""
19
+
20
+ __all__ = [
21
+ # public symbols
22
+ "Comment",
23
+ "dump",
24
+ "Element",
25
+ "ElementTree",
26
+ "fromstring",
27
+ "fromstringlist",
28
+ "iselement",
29
+ "iterparse",
30
+ "parse",
31
+ "ParseError",
32
+ "PI",
33
+ "ProcessingInstruction",
34
+ "QName",
35
+ "SubElement",
36
+ "tostring",
37
+ "tostringlist",
38
+ "TreeBuilder",
39
+ "XML",
40
+ "XMLParser",
41
+ "register_namespace",
42
+ ]
43
+
44
+ try:
45
+ from lxml.etree import *
46
+
47
+ _have_lxml = True
48
+ except ImportError:
49
+ try:
50
+ from xml.etree.cElementTree import *
51
+
52
+ # the cElementTree version of XML function doesn't support
53
+ # the optional 'parser' keyword argument
54
+ from xml.etree.ElementTree import XML
55
+ except ImportError: # pragma: no cover
56
+ from xml.etree.ElementTree import *
57
+ _have_lxml = False
58
+
59
+ import sys
60
+
61
+ # dict is always ordered in python >= 3.6 and on pypy
62
+ PY36 = sys.version_info >= (3, 6)
63
+ try:
64
+ import __pypy__
65
+ except ImportError:
66
+ __pypy__ = None
67
+ _dict_is_ordered = bool(PY36 or __pypy__)
68
+ del PY36, __pypy__
69
+
70
+ if _dict_is_ordered:
71
+ _Attrib = dict
72
+ else:
73
+ from collections import OrderedDict as _Attrib
74
+
75
+ if isinstance(Element, type):
76
+ _Element = Element
77
+ else:
78
+ # in py27, cElementTree.Element cannot be subclassed, so
79
+ # we need to import the pure-python class
80
+ from xml.etree.ElementTree import Element as _Element
81
+
82
+ class Element(_Element):
83
+ """Element subclass that keeps the order of attributes."""
84
+
85
+ def __init__(self, tag, attrib=_Attrib(), **extra):
86
+ super(Element, self).__init__(tag)
87
+ self.attrib = _Attrib()
88
+ if attrib:
89
+ self.attrib.update(attrib)
90
+ if extra:
91
+ self.attrib.update(extra)
92
+
93
+ def SubElement(parent, tag, attrib=_Attrib(), **extra):
94
+ """Must override SubElement as well otherwise _elementtree.SubElement
95
+ fails if 'parent' is a subclass of Element object.
96
+ """
97
+ element = parent.__class__(tag, attrib, **extra)
98
+ parent.append(element)
99
+ return element
100
+
101
+ def _iterwalk(element, events, tag):
102
+ include = tag is None or element.tag == tag
103
+ if include and "start" in events:
104
+ yield ("start", element)
105
+ for e in element:
106
+ for item in _iterwalk(e, events, tag):
107
+ yield item
108
+ if include:
109
+ yield ("end", element)
110
+
111
+ def iterwalk(element_or_tree, events=("end",), tag=None):
112
+ """A tree walker that generates events from an existing tree as
113
+ if it was parsing XML data with iterparse().
114
+ Drop-in replacement for lxml.etree.iterwalk.
115
+ """
116
+ if iselement(element_or_tree):
117
+ element = element_or_tree
118
+ else:
119
+ element = element_or_tree.getroot()
120
+ if tag == "*":
121
+ tag = None
122
+ for item in _iterwalk(element, events, tag):
123
+ yield item
124
+
125
+ _ElementTree = ElementTree
126
+
127
+ class ElementTree(_ElementTree):
128
+ """ElementTree subclass that adds 'pretty_print' and 'doctype'
129
+ arguments to the 'write' method.
130
+ Currently these are only supported for the default XML serialization
131
+ 'method', and not also for "html" or "text", for these are delegated
132
+ to the base class.
133
+ """
134
+
135
+ def write(
136
+ self,
137
+ file_or_filename,
138
+ encoding=None,
139
+ xml_declaration=False,
140
+ method=None,
141
+ doctype=None,
142
+ pretty_print=False,
143
+ ):
144
+ if method and method != "xml":
145
+ # delegate to super-class
146
+ super(ElementTree, self).write(
147
+ file_or_filename,
148
+ encoding=encoding,
149
+ xml_declaration=xml_declaration,
150
+ method=method,
151
+ )
152
+ return
153
+
154
+ if encoding is not None and encoding.lower() == "unicode":
155
+ if xml_declaration:
156
+ raise ValueError(
157
+ "Serialisation to unicode must not request an XML declaration"
158
+ )
159
+ write_declaration = False
160
+ encoding = "unicode"
161
+ elif xml_declaration is None:
162
+ # by default, write an XML declaration only for non-standard encodings
163
+ write_declaration = encoding is not None and encoding.upper() not in (
164
+ "ASCII",
165
+ "UTF-8",
166
+ "UTF8",
167
+ "US-ASCII",
168
+ )
169
+ else:
170
+ write_declaration = xml_declaration
171
+
172
+ if encoding is None:
173
+ encoding = "ASCII"
174
+
175
+ if pretty_print:
176
+ # NOTE this will modify the tree in-place
177
+ _indent(self._root)
178
+
179
+ with _get_writer(file_or_filename, encoding) as write:
180
+ if write_declaration:
181
+ write(XML_DECLARATION % encoding.upper())
182
+ if pretty_print:
183
+ write("\n")
184
+ if doctype:
185
+ write(_tounicode(doctype))
186
+ if pretty_print:
187
+ write("\n")
188
+
189
+ qnames, namespaces = _namespaces(self._root)
190
+ _serialize_xml(write, self._root, qnames, namespaces)
191
+
192
+ import io
193
+
194
+ def tostring(
195
+ element,
196
+ encoding=None,
197
+ xml_declaration=None,
198
+ method=None,
199
+ doctype=None,
200
+ pretty_print=False,
201
+ ):
202
+ """Custom 'tostring' function that uses our ElementTree subclass, with
203
+ pretty_print support.
204
+ """
205
+ stream = io.StringIO() if encoding == "unicode" else io.BytesIO()
206
+ ElementTree(element).write(
207
+ stream,
208
+ encoding=encoding,
209
+ xml_declaration=xml_declaration,
210
+ method=method,
211
+ doctype=doctype,
212
+ pretty_print=pretty_print,
213
+ )
214
+ return stream.getvalue()
215
+
216
+ # serialization support
217
+
218
+ import re
219
+
220
+ # Valid XML strings can include any Unicode character, excluding control
221
+ # characters, the surrogate blocks, FFFE, and FFFF:
222
+ # Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
223
+ # Here we reversed the pattern to match only the invalid characters.
224
+ # For the 'narrow' python builds supporting only UCS-2, which represent
225
+ # characters beyond BMP as UTF-16 surrogate pairs, we need to pass through
226
+ # the surrogate block. I haven't found a more elegant solution...
227
+ UCS2 = sys.maxunicode < 0x10FFFF
228
+ if UCS2:
229
+ _invalid_xml_string = re.compile(
230
+ "[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uFFFE-\uFFFF]"
231
+ )
232
+ else:
233
+ _invalid_xml_string = re.compile(
234
+ "[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]"
235
+ )
236
+
237
+ def _tounicode(s):
238
+ """Test if a string is valid user input and decode it to unicode string
239
+ using ASCII encoding if it's a bytes string.
240
+ Reject all bytes/unicode input that contains non-XML characters.
241
+ Reject all bytes input that contains non-ASCII characters.
242
+ """
243
+ try:
244
+ s = tostr(s, encoding="ascii", errors="strict")
245
+ except UnicodeDecodeError:
246
+ raise ValueError(
247
+ "Bytes strings can only contain ASCII characters. "
248
+ "Use unicode strings for non-ASCII characters."
249
+ )
250
+ except AttributeError:
251
+ _raise_serialization_error(s)
252
+ if s and _invalid_xml_string.search(s):
253
+ raise ValueError(
254
+ "All strings must be XML compatible: Unicode or ASCII, "
255
+ "no NULL bytes or control characters"
256
+ )
257
+ return s
258
+
259
+ import contextlib
260
+
261
+ @contextlib.contextmanager
262
+ def _get_writer(file_or_filename, encoding):
263
+ # returns text write method and release all resources after using
264
+ try:
265
+ write = file_or_filename.write
266
+ except AttributeError:
267
+ # file_or_filename is a file name
268
+ f = open(
269
+ file_or_filename,
270
+ "w",
271
+ encoding="utf-8" if encoding == "unicode" else encoding,
272
+ errors="xmlcharrefreplace",
273
+ )
274
+ with f:
275
+ yield f.write
276
+ else:
277
+ # file_or_filename is a file-like object
278
+ # encoding determines if it is a text or binary writer
279
+ if encoding == "unicode":
280
+ # use a text writer as is
281
+ yield write
282
+ else:
283
+ # wrap a binary writer with TextIOWrapper
284
+ detach_buffer = False
285
+ if isinstance(file_or_filename, io.BufferedIOBase):
286
+ buf = file_or_filename
287
+ elif isinstance(file_or_filename, io.RawIOBase):
288
+ buf = io.BufferedWriter(file_or_filename)
289
+ detach_buffer = True
290
+ else:
291
+ # This is to handle passed objects that aren't in the
292
+ # IOBase hierarchy, but just have a write method
293
+ buf = io.BufferedIOBase()
294
+ buf.writable = lambda: True
295
+ buf.write = write
296
+ try:
297
+ # TextIOWrapper uses this methods to determine
298
+ # if BOM (for UTF-16, etc) should be added
299
+ buf.seekable = file_or_filename.seekable
300
+ buf.tell = file_or_filename.tell
301
+ except AttributeError:
302
+ pass
303
+ wrapper = io.TextIOWrapper(
304
+ buf,
305
+ encoding=encoding,
306
+ errors="xmlcharrefreplace",
307
+ newline="\n",
308
+ )
309
+ try:
310
+ yield wrapper.write
311
+ finally:
312
+ # Keep the original file open when the TextIOWrapper and
313
+ # the BufferedWriter are destroyed
314
+ wrapper.detach()
315
+ if detach_buffer:
316
+ buf.detach()
317
+
318
+ from xml.etree.ElementTree import _namespace_map
319
+
320
+ def _namespaces(elem):
321
+ # identify namespaces used in this tree
322
+
323
+ # maps qnames to *encoded* prefix:local names
324
+ qnames = {None: None}
325
+
326
+ # maps uri:s to prefixes
327
+ namespaces = {}
328
+
329
+ def add_qname(qname):
330
+ # calculate serialized qname representation
331
+ try:
332
+ qname = _tounicode(qname)
333
+ if qname[:1] == "{":
334
+ uri, tag = qname[1:].rsplit("}", 1)
335
+ prefix = namespaces.get(uri)
336
+ if prefix is None:
337
+ prefix = _namespace_map.get(uri)
338
+ if prefix is None:
339
+ prefix = "ns%d" % len(namespaces)
340
+ else:
341
+ prefix = _tounicode(prefix)
342
+ if prefix != "xml":
343
+ namespaces[uri] = prefix
344
+ if prefix:
345
+ qnames[qname] = "%s:%s" % (prefix, tag)
346
+ else:
347
+ qnames[qname] = tag # default element
348
+ else:
349
+ qnames[qname] = qname
350
+ except TypeError:
351
+ _raise_serialization_error(qname)
352
+
353
+ # populate qname and namespaces table
354
+ for elem in elem.iter():
355
+ tag = elem.tag
356
+ if isinstance(tag, QName):
357
+ if tag.text not in qnames:
358
+ add_qname(tag.text)
359
+ elif isinstance(tag, str):
360
+ if tag not in qnames:
361
+ add_qname(tag)
362
+ elif tag is not None and tag is not Comment and tag is not PI:
363
+ _raise_serialization_error(tag)
364
+ for key, value in elem.items():
365
+ if isinstance(key, QName):
366
+ key = key.text
367
+ if key not in qnames:
368
+ add_qname(key)
369
+ if isinstance(value, QName) and value.text not in qnames:
370
+ add_qname(value.text)
371
+ text = elem.text
372
+ if isinstance(text, QName) and text.text not in qnames:
373
+ add_qname(text.text)
374
+ return qnames, namespaces
375
+
376
+ def _serialize_xml(write, elem, qnames, namespaces, **kwargs):
377
+ tag = elem.tag
378
+ text = elem.text
379
+ if tag is Comment:
380
+ write("<!--%s-->" % _tounicode(text))
381
+ elif tag is ProcessingInstruction:
382
+ write("<?%s?>" % _tounicode(text))
383
+ else:
384
+ tag = qnames[_tounicode(tag) if tag is not None else None]
385
+ if tag is None:
386
+ if text:
387
+ write(_escape_cdata(text))
388
+ for e in elem:
389
+ _serialize_xml(write, e, qnames, None)
390
+ else:
391
+ write("<" + tag)
392
+ if namespaces:
393
+ for uri, prefix in sorted(
394
+ namespaces.items(), key=lambda x: x[1]
395
+ ): # sort on prefix
396
+ if prefix:
397
+ prefix = ":" + prefix
398
+ write(' xmlns%s="%s"' % (prefix, _escape_attrib(uri)))
399
+ attrs = elem.attrib
400
+ if attrs:
401
+ # try to keep existing attrib order
402
+ if len(attrs) <= 1 or type(attrs) is _Attrib:
403
+ items = attrs.items()
404
+ else:
405
+ # if plain dict, use lexical order
406
+ items = sorted(attrs.items())
407
+ for k, v in items:
408
+ if isinstance(k, QName):
409
+ k = _tounicode(k.text)
410
+ else:
411
+ k = _tounicode(k)
412
+ if isinstance(v, QName):
413
+ v = qnames[_tounicode(v.text)]
414
+ else:
415
+ v = _escape_attrib(v)
416
+ write(' %s="%s"' % (qnames[k], v))
417
+ if text is not None or len(elem):
418
+ write(">")
419
+ if text:
420
+ write(_escape_cdata(text))
421
+ for e in elem:
422
+ _serialize_xml(write, e, qnames, None)
423
+ write("</" + tag + ">")
424
+ else:
425
+ write("/>")
426
+ if elem.tail:
427
+ write(_escape_cdata(elem.tail))
428
+
429
+ def _raise_serialization_error(text):
430
+ raise TypeError("cannot serialize %r (type %s)" % (text, type(text).__name__))
431
+
432
+ def _escape_cdata(text):
433
+ # escape character data
434
+ try:
435
+ text = _tounicode(text)
436
+ # it's worth avoiding do-nothing calls for short strings
437
+ if "&" in text:
438
+ text = text.replace("&", "&amp;")
439
+ if "<" in text:
440
+ text = text.replace("<", "&lt;")
441
+ if ">" in text:
442
+ text = text.replace(">", "&gt;")
443
+ return text
444
+ except (TypeError, AttributeError):
445
+ _raise_serialization_error(text)
446
+
447
+ def _escape_attrib(text):
448
+ # escape attribute value
449
+ try:
450
+ text = _tounicode(text)
451
+ if "&" in text:
452
+ text = text.replace("&", "&amp;")
453
+ if "<" in text:
454
+ text = text.replace("<", "&lt;")
455
+ if ">" in text:
456
+ text = text.replace(">", "&gt;")
457
+ if '"' in text:
458
+ text = text.replace('"', "&quot;")
459
+ if "\n" in text:
460
+ text = text.replace("\n", "&#10;")
461
+ return text
462
+ except (TypeError, AttributeError):
463
+ _raise_serialization_error(text)
464
+
465
+ def _indent(elem, level=0):
466
+ # From http://effbot.org/zone/element-lib.htm#prettyprint
467
+ i = "\n" + level * " "
468
+ if len(elem):
469
+ if not elem.text or not elem.text.strip():
470
+ elem.text = i + " "
471
+ if not elem.tail or not elem.tail.strip():
472
+ elem.tail = i
473
+ for elem in elem:
474
+ _indent(elem, level + 1)
475
+ if not elem.tail or not elem.tail.strip():
476
+ elem.tail = i
477
+ else:
478
+ if level and (not elem.tail or not elem.tail.strip()):
479
+ elem.tail = i
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/filenames.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module implements the algorithm for converting between a "user name" -
3
+ something that a user can choose arbitrarily inside a font editor - and a file
4
+ name suitable for use in a wide range of operating systems and filesystems.
5
+
6
+ The `UFO 3 specification <http://unifiedfontobject.org/versions/ufo3/conventions/>`_
7
+ provides an example of an algorithm for such conversion, which avoids illegal
8
+ characters, reserved file names, ambiguity between upper- and lower-case
9
+ characters, and clashes with existing files.
10
+
11
+ This code was originally copied from
12
+ `ufoLib <https://github.com/unified-font-object/ufoLib/blob/8747da7/Lib/ufoLib/filenames.py>`_
13
+ by Tal Leming and is copyright (c) 2005-2016, The RoboFab Developers:
14
+
15
+ - Erik van Blokland
16
+ - Tal Leming
17
+ - Just van Rossum
18
+ """
19
+
20
+ illegalCharacters = r"\" * + / : < > ? [ \ ] | \0".split(" ")
21
+ illegalCharacters += [chr(i) for i in range(1, 32)]
22
+ illegalCharacters += [chr(0x7F)]
23
+ reservedFileNames = "CON PRN AUX CLOCK$ NUL A:-Z: COM1".lower().split(" ")
24
+ reservedFileNames += "LPT1 LPT2 LPT3 COM2 COM3 COM4".lower().split(" ")
25
+ maxFileNameLength = 255
26
+
27
+
28
+ class NameTranslationError(Exception):
29
+ pass
30
+
31
+
32
+ def userNameToFileName(userName, existing=[], prefix="", suffix=""):
33
+ """Converts from a user name to a file name.
34
+
35
+ Takes care to avoid illegal characters, reserved file names, ambiguity between
36
+ upper- and lower-case characters, and clashes with existing files.
37
+
38
+ Args:
39
+ userName (str): The input file name.
40
+ existing: A case-insensitive list of all existing file names.
41
+ prefix: Prefix to be prepended to the file name.
42
+ suffix: Suffix to be appended to the file name.
43
+
44
+ Returns:
45
+ A suitable filename.
46
+
47
+ Raises:
48
+ NameTranslationError: If no suitable name could be generated.
49
+
50
+ Examples::
51
+
52
+ >>> userNameToFileName("a") == "a"
53
+ True
54
+ >>> userNameToFileName("A") == "A_"
55
+ True
56
+ >>> userNameToFileName("AE") == "A_E_"
57
+ True
58
+ >>> userNameToFileName("Ae") == "A_e"
59
+ True
60
+ >>> userNameToFileName("ae") == "ae"
61
+ True
62
+ >>> userNameToFileName("aE") == "aE_"
63
+ True
64
+ >>> userNameToFileName("a.alt") == "a.alt"
65
+ True
66
+ >>> userNameToFileName("A.alt") == "A_.alt"
67
+ True
68
+ >>> userNameToFileName("A.Alt") == "A_.A_lt"
69
+ True
70
+ >>> userNameToFileName("A.aLt") == "A_.aL_t"
71
+ True
72
+ >>> userNameToFileName(u"A.alT") == "A_.alT_"
73
+ True
74
+ >>> userNameToFileName("T_H") == "T__H_"
75
+ True
76
+ >>> userNameToFileName("T_h") == "T__h"
77
+ True
78
+ >>> userNameToFileName("t_h") == "t_h"
79
+ True
80
+ >>> userNameToFileName("F_F_I") == "F__F__I_"
81
+ True
82
+ >>> userNameToFileName("f_f_i") == "f_f_i"
83
+ True
84
+ >>> userNameToFileName("Aacute_V.swash") == "A_acute_V_.swash"
85
+ True
86
+ >>> userNameToFileName(".notdef") == "_notdef"
87
+ True
88
+ >>> userNameToFileName("con") == "_con"
89
+ True
90
+ >>> userNameToFileName("CON") == "C_O_N_"
91
+ True
92
+ >>> userNameToFileName("con.alt") == "_con.alt"
93
+ True
94
+ >>> userNameToFileName("alt.con") == "alt._con"
95
+ True
96
+ """
97
+ # the incoming name must be a str
98
+ if not isinstance(userName, str):
99
+ raise ValueError("The value for userName must be a string.")
100
+ # establish the prefix and suffix lengths
101
+ prefixLength = len(prefix)
102
+ suffixLength = len(suffix)
103
+ # replace an initial period with an _
104
+ # if no prefix is to be added
105
+ if not prefix and userName[0] == ".":
106
+ userName = "_" + userName[1:]
107
+ # filter the user name
108
+ filteredUserName = []
109
+ for character in userName:
110
+ # replace illegal characters with _
111
+ if character in illegalCharacters:
112
+ character = "_"
113
+ # add _ to all non-lower characters
114
+ elif character != character.lower():
115
+ character += "_"
116
+ filteredUserName.append(character)
117
+ userName = "".join(filteredUserName)
118
+ # clip to 255
119
+ sliceLength = maxFileNameLength - prefixLength - suffixLength
120
+ userName = userName[:sliceLength]
121
+ # test for illegal files names
122
+ parts = []
123
+ for part in userName.split("."):
124
+ if part.lower() in reservedFileNames:
125
+ part = "_" + part
126
+ parts.append(part)
127
+ userName = ".".join(parts)
128
+ # test for clash
129
+ fullName = prefix + userName + suffix
130
+ if fullName.lower() in existing:
131
+ fullName = handleClash1(userName, existing, prefix, suffix)
132
+ # finished
133
+ return fullName
134
+
135
+
136
+ def handleClash1(userName, existing=[], prefix="", suffix=""):
137
+ """
138
+ existing should be a case-insensitive list
139
+ of all existing file names.
140
+
141
+ >>> prefix = ("0" * 5) + "."
142
+ >>> suffix = "." + ("0" * 10)
143
+ >>> existing = ["a" * 5]
144
+
145
+ >>> e = list(existing)
146
+ >>> handleClash1(userName="A" * 5, existing=e,
147
+ ... prefix=prefix, suffix=suffix) == (
148
+ ... '00000.AAAAA000000000000001.0000000000')
149
+ True
150
+
151
+ >>> e = list(existing)
152
+ >>> e.append(prefix + "aaaaa" + "1".zfill(15) + suffix)
153
+ >>> handleClash1(userName="A" * 5, existing=e,
154
+ ... prefix=prefix, suffix=suffix) == (
155
+ ... '00000.AAAAA000000000000002.0000000000')
156
+ True
157
+
158
+ >>> e = list(existing)
159
+ >>> e.append(prefix + "AAAAA" + "2".zfill(15) + suffix)
160
+ >>> handleClash1(userName="A" * 5, existing=e,
161
+ ... prefix=prefix, suffix=suffix) == (
162
+ ... '00000.AAAAA000000000000001.0000000000')
163
+ True
164
+ """
165
+ # if the prefix length + user name length + suffix length + 15 is at
166
+ # or past the maximum length, silce 15 characters off of the user name
167
+ prefixLength = len(prefix)
168
+ suffixLength = len(suffix)
169
+ if prefixLength + len(userName) + suffixLength + 15 > maxFileNameLength:
170
+ l = prefixLength + len(userName) + suffixLength + 15
171
+ sliceLength = maxFileNameLength - l
172
+ userName = userName[:sliceLength]
173
+ finalName = None
174
+ # try to add numbers to create a unique name
175
+ counter = 1
176
+ while finalName is None:
177
+ name = userName + str(counter).zfill(15)
178
+ fullName = prefix + name + suffix
179
+ if fullName.lower() not in existing:
180
+ finalName = fullName
181
+ break
182
+ else:
183
+ counter += 1
184
+ if counter >= 999999999999999:
185
+ break
186
+ # if there is a clash, go to the next fallback
187
+ if finalName is None:
188
+ finalName = handleClash2(existing, prefix, suffix)
189
+ # finished
190
+ return finalName
191
+
192
+
193
+ def handleClash2(existing=[], prefix="", suffix=""):
194
+ """
195
+ existing should be a case-insensitive list
196
+ of all existing file names.
197
+
198
+ >>> prefix = ("0" * 5) + "."
199
+ >>> suffix = "." + ("0" * 10)
200
+ >>> existing = [prefix + str(i) + suffix for i in range(100)]
201
+
202
+ >>> e = list(existing)
203
+ >>> handleClash2(existing=e, prefix=prefix, suffix=suffix) == (
204
+ ... '00000.100.0000000000')
205
+ True
206
+
207
+ >>> e = list(existing)
208
+ >>> e.remove(prefix + "1" + suffix)
209
+ >>> handleClash2(existing=e, prefix=prefix, suffix=suffix) == (
210
+ ... '00000.1.0000000000')
211
+ True
212
+
213
+ >>> e = list(existing)
214
+ >>> e.remove(prefix + "2" + suffix)
215
+ >>> handleClash2(existing=e, prefix=prefix, suffix=suffix) == (
216
+ ... '00000.2.0000000000')
217
+ True
218
+ """
219
+ # calculate the longest possible string
220
+ maxLength = maxFileNameLength - len(prefix) - len(suffix)
221
+ maxValue = int("9" * maxLength)
222
+ # try to find a number
223
+ finalName = None
224
+ counter = 1
225
+ while finalName is None:
226
+ fullName = prefix + str(counter) + suffix
227
+ if fullName.lower() not in existing:
228
+ finalName = fullName
229
+ break
230
+ else:
231
+ counter += 1
232
+ if counter >= maxValue:
233
+ break
234
+ # raise an error if nothing has been found
235
+ if finalName is None:
236
+ raise NameTranslationError("No unique name could be found.")
237
+ # finished
238
+ return finalName
239
+
240
+
241
+ if __name__ == "__main__":
242
+ import doctest
243
+ import sys
244
+
245
+ sys.exit(doctest.testmod().failed)
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/fixedTools.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The `OpenType specification <https://docs.microsoft.com/en-us/typography/opentype/spec/otff#data-types>`_
3
+ defines two fixed-point data types:
4
+
5
+ ``Fixed``
6
+ A 32-bit signed fixed-point number with a 16 bit twos-complement
7
+ magnitude component and 16 fractional bits.
8
+ ``F2DOT14``
9
+ A 16-bit signed fixed-point number with a 2 bit twos-complement
10
+ magnitude component and 14 fractional bits.
11
+
12
+ To support reading and writing data with these data types, this module provides
13
+ functions for converting between fixed-point, float and string representations.
14
+
15
+ .. data:: MAX_F2DOT14
16
+
17
+ The maximum value that can still fit in an F2Dot14. (1.99993896484375)
18
+ """
19
+
20
+ from .roundTools import otRound, nearestMultipleShortestRepr
21
+ import logging
22
+
23
+ log = logging.getLogger(__name__)
24
+
25
+ __all__ = [
26
+ "MAX_F2DOT14",
27
+ "fixedToFloat",
28
+ "floatToFixed",
29
+ "floatToFixedToFloat",
30
+ "floatToFixedToStr",
31
+ "fixedToStr",
32
+ "strToFixed",
33
+ "strToFixedToFloat",
34
+ "ensureVersionIsLong",
35
+ "versionToFixed",
36
+ ]
37
+
38
+
39
+ MAX_F2DOT14 = 0x7FFF / (1 << 14)
40
+
41
+
42
+ def fixedToFloat(value, precisionBits):
43
+ """Converts a fixed-point number to a float given the number of
44
+ precision bits.
45
+
46
+ Args:
47
+ value (int): Number in fixed-point format.
48
+ precisionBits (int): Number of precision bits.
49
+
50
+ Returns:
51
+ Floating point value.
52
+
53
+ Examples::
54
+
55
+ >>> import math
56
+ >>> f = fixedToFloat(-10139, precisionBits=14)
57
+ >>> math.isclose(f, -0.61883544921875)
58
+ True
59
+ """
60
+ return value / (1 << precisionBits)
61
+
62
+
63
+ def floatToFixed(value, precisionBits):
64
+ """Converts a float to a fixed-point number given the number of
65
+ precision bits.
66
+
67
+ Args:
68
+ value (float): Floating point value.
69
+ precisionBits (int): Number of precision bits.
70
+
71
+ Returns:
72
+ int: Fixed-point representation.
73
+
74
+ Examples::
75
+
76
+ >>> floatToFixed(-0.61883544921875, precisionBits=14)
77
+ -10139
78
+ >>> floatToFixed(-0.61884, precisionBits=14)
79
+ -10139
80
+ """
81
+ return otRound(value * (1 << precisionBits))
82
+
83
+
84
+ def floatToFixedToFloat(value, precisionBits):
85
+ """Converts a float to a fixed-point number and back again.
86
+
87
+ By converting the float to fixed, rounding it, and converting it back
88
+ to float again, this returns a floating point values which is exactly
89
+ representable in fixed-point format.
90
+
91
+ Note: this **is** equivalent to ``fixedToFloat(floatToFixed(value))``.
92
+
93
+ Args:
94
+ value (float): The input floating point value.
95
+ precisionBits (int): Number of precision bits.
96
+
97
+ Returns:
98
+ float: The transformed and rounded value.
99
+
100
+ Examples::
101
+ >>> import math
102
+ >>> f1 = -0.61884
103
+ >>> f2 = floatToFixedToFloat(-0.61884, precisionBits=14)
104
+ >>> f1 != f2
105
+ True
106
+ >>> math.isclose(f2, -0.61883544921875)
107
+ True
108
+ """
109
+ scale = 1 << precisionBits
110
+ return otRound(value * scale) / scale
111
+
112
+
113
+ def fixedToStr(value, precisionBits):
114
+ """Converts a fixed-point number to a string representing a decimal float.
115
+
116
+ This chooses the float that has the shortest decimal representation (the least
117
+ number of fractional decimal digits).
118
+
119
+ For example, to convert a fixed-point number in a 2.14 format, use
120
+ ``precisionBits=14``::
121
+
122
+ >>> fixedToStr(-10139, precisionBits=14)
123
+ '-0.61884'
124
+
125
+ This is pretty slow compared to the simple division used in ``fixedToFloat``.
126
+ Use sporadically when you need to serialize or print the fixed-point number in
127
+ a human-readable form.
128
+ It uses nearestMultipleShortestRepr under the hood.
129
+
130
+ Args:
131
+ value (int): The fixed-point value to convert.
132
+ precisionBits (int): Number of precision bits, *up to a maximum of 16*.
133
+
134
+ Returns:
135
+ str: A string representation of the value.
136
+ """
137
+ scale = 1 << precisionBits
138
+ return nearestMultipleShortestRepr(value / scale, factor=1.0 / scale)
139
+
140
+
141
+ def strToFixed(string, precisionBits):
142
+ """Converts a string representing a decimal float to a fixed-point number.
143
+
144
+ Args:
145
+ string (str): A string representing a decimal float.
146
+ precisionBits (int): Number of precision bits, *up to a maximum of 16*.
147
+
148
+ Returns:
149
+ int: Fixed-point representation.
150
+
151
+ Examples::
152
+
153
+ >>> ## to convert a float string to a 2.14 fixed-point number:
154
+ >>> strToFixed('-0.61884', precisionBits=14)
155
+ -10139
156
+ """
157
+ value = float(string)
158
+ return otRound(value * (1 << precisionBits))
159
+
160
+
161
+ def strToFixedToFloat(string, precisionBits):
162
+ """Convert a string to a decimal float with fixed-point rounding.
163
+
164
+ This first converts string to a float, then turns it into a fixed-point
165
+ number with ``precisionBits`` fractional binary digits, then back to a
166
+ float again.
167
+
168
+ This is simply a shorthand for fixedToFloat(floatToFixed(float(s))).
169
+
170
+ Args:
171
+ string (str): A string representing a decimal float.
172
+ precisionBits (int): Number of precision bits.
173
+
174
+ Returns:
175
+ float: The transformed and rounded value.
176
+
177
+ Examples::
178
+
179
+ >>> import math
180
+ >>> s = '-0.61884'
181
+ >>> bits = 14
182
+ >>> f = strToFixedToFloat(s, precisionBits=bits)
183
+ >>> math.isclose(f, -0.61883544921875)
184
+ True
185
+ >>> f == fixedToFloat(floatToFixed(float(s), precisionBits=bits), precisionBits=bits)
186
+ True
187
+ """
188
+ value = float(string)
189
+ scale = 1 << precisionBits
190
+ return otRound(value * scale) / scale
191
+
192
+
193
+ def floatToFixedToStr(value, precisionBits):
194
+ """Convert float to string with fixed-point rounding.
195
+
196
+ This uses the shortest decimal representation (ie. the least
197
+ number of fractional decimal digits) to represent the equivalent
198
+ fixed-point number with ``precisionBits`` fractional binary digits.
199
+ It uses nearestMultipleShortestRepr under the hood.
200
+
201
+ >>> floatToFixedToStr(-0.61883544921875, precisionBits=14)
202
+ '-0.61884'
203
+
204
+ Args:
205
+ value (float): The float value to convert.
206
+ precisionBits (int): Number of precision bits, *up to a maximum of 16*.
207
+
208
+ Returns:
209
+ str: A string representation of the value.
210
+
211
+ """
212
+ scale = 1 << precisionBits
213
+ return nearestMultipleShortestRepr(value, factor=1.0 / scale)
214
+
215
+
216
+ def ensureVersionIsLong(value):
217
+ """Ensure a table version is an unsigned long.
218
+
219
+ OpenType table version numbers are expressed as a single unsigned long
220
+ comprising of an unsigned short major version and unsigned short minor
221
+ version. This function detects if the value to be used as a version number
222
+ looks too small (i.e. is less than ``0x10000``), and converts it to
223
+ fixed-point using :func:`floatToFixed` if so.
224
+
225
+ Args:
226
+ value (Number): a candidate table version number.
227
+
228
+ Returns:
229
+ int: A table version number, possibly corrected to fixed-point.
230
+ """
231
+ if value < 0x10000:
232
+ newValue = floatToFixed(value, 16)
233
+ log.warning(
234
+ "Table version value is a float: %.4f; " "fix to use hex instead: 0x%08x",
235
+ value,
236
+ newValue,
237
+ )
238
+ value = newValue
239
+ return value
240
+
241
+
242
+ def versionToFixed(value):
243
+ """Ensure a table version number is fixed-point.
244
+
245
+ Args:
246
+ value (str): a candidate table version number.
247
+
248
+ Returns:
249
+ int: A table version number, possibly corrected to fixed-point.
250
+ """
251
+ value = int(value, 0) if value.startswith("0") else float(value)
252
+ value = ensureVersionIsLong(value)
253
+ return value
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/intTools.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ["popCount", "bit_count", "bit_indices"]
2
+
3
+
4
+ try:
5
+ bit_count = int.bit_count
6
+ except AttributeError:
7
+
8
+ def bit_count(v):
9
+ return bin(v).count("1")
10
+
11
+
12
+ """Return number of 1 bits (population count) of the absolute value of an integer.
13
+
14
+ See https://docs.python.org/3.10/library/stdtypes.html#int.bit_count
15
+ """
16
+ popCount = bit_count # alias
17
+
18
+
19
+ def bit_indices(v):
20
+ """Return list of indices where bits are set, 0 being the index of the least significant bit.
21
+
22
+ >>> bit_indices(0b101)
23
+ [0, 2]
24
+ """
25
+ return [i for i, b in enumerate(bin(v)[::-1]) if b == "1"]
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/lazyTools.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import UserDict, UserList
2
+
3
+ __all__ = ["LazyDict", "LazyList"]
4
+
5
+
6
+ class LazyDict(UserDict):
7
+ def __init__(self, data):
8
+ super().__init__()
9
+ self.data = data
10
+
11
+ def __getitem__(self, k):
12
+ v = self.data[k]
13
+ if callable(v):
14
+ v = v(k)
15
+ self.data[k] = v
16
+ return v
17
+
18
+
19
+ class LazyList(UserList):
20
+ def __getitem__(self, k):
21
+ if isinstance(k, slice):
22
+ indices = range(*k.indices(len(self)))
23
+ return [self[i] for i in indices]
24
+ v = self.data[k]
25
+ if callable(v):
26
+ v = v(k)
27
+ self.data[k] = v
28
+ return v
29
+
30
+ def __add__(self, other):
31
+ if isinstance(other, LazyList):
32
+ other = list(other)
33
+ elif isinstance(other, list):
34
+ pass
35
+ else:
36
+ return NotImplemented
37
+ return list(self) + other
38
+
39
+ def __radd__(self, other):
40
+ if not isinstance(other, list):
41
+ return NotImplemented
42
+ return other + list(self)
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/loggingTools.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import logging
3
+ import timeit
4
+ from functools import wraps
5
+ from collections.abc import Mapping, Callable
6
+ import warnings
7
+ from logging import PercentStyle
8
+
9
+
10
+ # default logging level used by Timer class
11
+ TIME_LEVEL = logging.DEBUG
12
+
13
+ # per-level format strings used by the default formatter
14
+ # (the level name is not printed for INFO and DEBUG messages)
15
+ DEFAULT_FORMATS = {
16
+ "*": "%(levelname)s: %(message)s",
17
+ "INFO": "%(message)s",
18
+ "DEBUG": "%(message)s",
19
+ }
20
+
21
+
22
+ class LevelFormatter(logging.Formatter):
23
+ """Log formatter with level-specific formatting.
24
+
25
+ Formatter class which optionally takes a dict of logging levels to
26
+ format strings, allowing to customise the log records appearance for
27
+ specific levels.
28
+
29
+
30
+ Attributes:
31
+ fmt: A dictionary mapping logging levels to format strings.
32
+ The ``*`` key identifies the default format string.
33
+ datefmt: As per py:class:`logging.Formatter`
34
+ style: As per py:class:`logging.Formatter`
35
+
36
+ >>> import sys
37
+ >>> handler = logging.StreamHandler(sys.stdout)
38
+ >>> formatter = LevelFormatter(
39
+ ... fmt={
40
+ ... '*': '[%(levelname)s] %(message)s',
41
+ ... 'DEBUG': '%(name)s [%(levelname)s] %(message)s',
42
+ ... 'INFO': '%(message)s',
43
+ ... })
44
+ >>> handler.setFormatter(formatter)
45
+ >>> log = logging.getLogger('test')
46
+ >>> log.setLevel(logging.DEBUG)
47
+ >>> log.addHandler(handler)
48
+ >>> log.debug('this uses a custom format string')
49
+ test [DEBUG] this uses a custom format string
50
+ >>> log.info('this also uses a custom format string')
51
+ this also uses a custom format string
52
+ >>> log.warning("this one uses the default format string")
53
+ [WARNING] this one uses the default format string
54
+ """
55
+
56
+ def __init__(self, fmt=None, datefmt=None, style="%"):
57
+ if style != "%":
58
+ raise ValueError(
59
+ "only '%' percent style is supported in both python 2 and 3"
60
+ )
61
+ if fmt is None:
62
+ fmt = DEFAULT_FORMATS
63
+ if isinstance(fmt, str):
64
+ default_format = fmt
65
+ custom_formats = {}
66
+ elif isinstance(fmt, Mapping):
67
+ custom_formats = dict(fmt)
68
+ default_format = custom_formats.pop("*", None)
69
+ else:
70
+ raise TypeError("fmt must be a str or a dict of str: %r" % fmt)
71
+ super(LevelFormatter, self).__init__(default_format, datefmt)
72
+ self.default_format = self._fmt
73
+ self.custom_formats = {}
74
+ for level, fmt in custom_formats.items():
75
+ level = logging._checkLevel(level)
76
+ self.custom_formats[level] = fmt
77
+
78
+ def format(self, record):
79
+ if self.custom_formats:
80
+ fmt = self.custom_formats.get(record.levelno, self.default_format)
81
+ if self._fmt != fmt:
82
+ self._fmt = fmt
83
+ # for python >= 3.2, _style needs to be set if _fmt changes
84
+ if PercentStyle:
85
+ self._style = PercentStyle(fmt)
86
+ return super(LevelFormatter, self).format(record)
87
+
88
+
89
+ def configLogger(**kwargs):
90
+ """A more sophisticated logging system configuation manager.
91
+
92
+ This is more or less the same as :py:func:`logging.basicConfig`,
93
+ with some additional options and defaults.
94
+
95
+ The default behaviour is to create a ``StreamHandler`` which writes to
96
+ sys.stderr, set a formatter using the ``DEFAULT_FORMATS`` strings, and add
97
+ the handler to the top-level library logger ("fontTools").
98
+
99
+ A number of optional keyword arguments may be specified, which can alter
100
+ the default behaviour.
101
+
102
+ Args:
103
+
104
+ logger: Specifies the logger name or a Logger instance to be
105
+ configured. (Defaults to "fontTools" logger). Unlike ``basicConfig``,
106
+ this function can be called multiple times to reconfigure a logger.
107
+ If the logger or any of its children already exists before the call is
108
+ made, they will be reset before the new configuration is applied.
109
+ filename: Specifies that a ``FileHandler`` be created, using the
110
+ specified filename, rather than a ``StreamHandler``.
111
+ filemode: Specifies the mode to open the file, if filename is
112
+ specified. (If filemode is unspecified, it defaults to ``a``).
113
+ format: Use the specified format string for the handler. This
114
+ argument also accepts a dictionary of format strings keyed by
115
+ level name, to allow customising the records appearance for
116
+ specific levels. The special ``'*'`` key is for 'any other' level.
117
+ datefmt: Use the specified date/time format.
118
+ level: Set the logger level to the specified level.
119
+ stream: Use the specified stream to initialize the StreamHandler. Note
120
+ that this argument is incompatible with ``filename`` - if both
121
+ are present, ``stream`` is ignored.
122
+ handlers: If specified, this should be an iterable of already created
123
+ handlers, which will be added to the logger. Any handler in the
124
+ list which does not have a formatter assigned will be assigned the
125
+ formatter created in this function.
126
+ filters: If specified, this should be an iterable of already created
127
+ filters. If the ``handlers`` do not already have filters assigned,
128
+ these filters will be added to them.
129
+ propagate: All loggers have a ``propagate`` attribute which determines
130
+ whether to continue searching for handlers up the logging hierarchy.
131
+ If not provided, the "propagate" attribute will be set to ``False``.
132
+ """
133
+ # using kwargs to enforce keyword-only arguments in py2.
134
+ handlers = kwargs.pop("handlers", None)
135
+ if handlers is None:
136
+ if "stream" in kwargs and "filename" in kwargs:
137
+ raise ValueError(
138
+ "'stream' and 'filename' should not be " "specified together"
139
+ )
140
+ else:
141
+ if "stream" in kwargs or "filename" in kwargs:
142
+ raise ValueError(
143
+ "'stream' or 'filename' should not be "
144
+ "specified together with 'handlers'"
145
+ )
146
+ if handlers is None:
147
+ filename = kwargs.pop("filename", None)
148
+ mode = kwargs.pop("filemode", "a")
149
+ if filename:
150
+ h = logging.FileHandler(filename, mode)
151
+ else:
152
+ stream = kwargs.pop("stream", None)
153
+ h = logging.StreamHandler(stream)
154
+ handlers = [h]
155
+ # By default, the top-level library logger is configured.
156
+ logger = kwargs.pop("logger", "fontTools")
157
+ if not logger or isinstance(logger, str):
158
+ # empty "" or None means the 'root' logger
159
+ logger = logging.getLogger(logger)
160
+ # before (re)configuring, reset named logger and its children (if exist)
161
+ _resetExistingLoggers(parent=logger.name)
162
+ # use DEFAULT_FORMATS if 'format' is None
163
+ fs = kwargs.pop("format", None)
164
+ dfs = kwargs.pop("datefmt", None)
165
+ # XXX: '%' is the only format style supported on both py2 and 3
166
+ style = kwargs.pop("style", "%")
167
+ fmt = LevelFormatter(fs, dfs, style)
168
+ filters = kwargs.pop("filters", [])
169
+ for h in handlers:
170
+ if h.formatter is None:
171
+ h.setFormatter(fmt)
172
+ if not h.filters:
173
+ for f in filters:
174
+ h.addFilter(f)
175
+ logger.addHandler(h)
176
+ if logger.name != "root":
177
+ # stop searching up the hierarchy for handlers
178
+ logger.propagate = kwargs.pop("propagate", False)
179
+ # set a custom severity level
180
+ level = kwargs.pop("level", None)
181
+ if level is not None:
182
+ logger.setLevel(level)
183
+ if kwargs:
184
+ keys = ", ".join(kwargs.keys())
185
+ raise ValueError("Unrecognised argument(s): %s" % keys)
186
+
187
+
188
+ def _resetExistingLoggers(parent="root"):
189
+ """Reset the logger named 'parent' and all its children to their initial
190
+ state, if they already exist in the current configuration.
191
+ """
192
+ root = logging.root
193
+ # get sorted list of all existing loggers
194
+ existing = sorted(root.manager.loggerDict.keys())
195
+ if parent == "root":
196
+ # all the existing loggers are children of 'root'
197
+ loggers_to_reset = [parent] + existing
198
+ elif parent not in existing:
199
+ # nothing to do
200
+ return
201
+ elif parent in existing:
202
+ loggers_to_reset = [parent]
203
+ # collect children, starting with the entry after parent name
204
+ i = existing.index(parent) + 1
205
+ prefixed = parent + "."
206
+ pflen = len(prefixed)
207
+ num_existing = len(existing)
208
+ while i < num_existing:
209
+ if existing[i][:pflen] == prefixed:
210
+ loggers_to_reset.append(existing[i])
211
+ i += 1
212
+ for name in loggers_to_reset:
213
+ if name == "root":
214
+ root.setLevel(logging.WARNING)
215
+ for h in root.handlers[:]:
216
+ root.removeHandler(h)
217
+ for f in root.filters[:]:
218
+ root.removeFilters(f)
219
+ root.disabled = False
220
+ else:
221
+ logger = root.manager.loggerDict[name]
222
+ logger.level = logging.NOTSET
223
+ logger.handlers = []
224
+ logger.filters = []
225
+ logger.propagate = True
226
+ logger.disabled = False
227
+
228
+
229
+ class Timer(object):
230
+ """Keeps track of overall time and split/lap times.
231
+
232
+ >>> import time
233
+ >>> timer = Timer()
234
+ >>> time.sleep(0.01)
235
+ >>> print("First lap:", timer.split())
236
+ First lap: ...
237
+ >>> time.sleep(0.02)
238
+ >>> print("Second lap:", timer.split())
239
+ Second lap: ...
240
+ >>> print("Overall time:", timer.time())
241
+ Overall time: ...
242
+
243
+ Can be used as a context manager inside with-statements.
244
+
245
+ >>> with Timer() as t:
246
+ ... time.sleep(0.01)
247
+ >>> print("%0.3f seconds" % t.elapsed)
248
+ 0... seconds
249
+
250
+ If initialised with a logger, it can log the elapsed time automatically
251
+ upon exiting the with-statement.
252
+
253
+ >>> import logging
254
+ >>> log = logging.getLogger("my-fancy-timer-logger")
255
+ >>> configLogger(logger=log, level="DEBUG", format="%(message)s", stream=sys.stdout)
256
+ >>> with Timer(log, 'do something'):
257
+ ... time.sleep(0.01)
258
+ Took ... to do something
259
+
260
+ The same Timer instance, holding a reference to a logger, can be reused
261
+ in multiple with-statements, optionally with different messages or levels.
262
+
263
+ >>> timer = Timer(log)
264
+ >>> with timer():
265
+ ... time.sleep(0.01)
266
+ elapsed time: ...s
267
+ >>> with timer('redo it', level=logging.INFO):
268
+ ... time.sleep(0.02)
269
+ Took ... to redo it
270
+
271
+ It can also be used as a function decorator to log the time elapsed to run
272
+ the decorated function.
273
+
274
+ >>> @timer()
275
+ ... def test1():
276
+ ... time.sleep(0.01)
277
+ >>> @timer('run test 2', level=logging.INFO)
278
+ ... def test2():
279
+ ... time.sleep(0.02)
280
+ >>> test1()
281
+ Took ... to run 'test1'
282
+ >>> test2()
283
+ Took ... to run test 2
284
+ """
285
+
286
+ # timeit.default_timer choses the most accurate clock for each platform
287
+ _time = timeit.default_timer
288
+ default_msg = "elapsed time: %(time).3fs"
289
+ default_format = "Took %(time).3fs to %(msg)s"
290
+
291
+ def __init__(self, logger=None, msg=None, level=None, start=None):
292
+ self.reset(start)
293
+ if logger is None:
294
+ for arg in ("msg", "level"):
295
+ if locals().get(arg) is not None:
296
+ raise ValueError("'%s' can't be specified without a 'logger'" % arg)
297
+ self.logger = logger
298
+ self.level = level if level is not None else TIME_LEVEL
299
+ self.msg = msg
300
+
301
+ def reset(self, start=None):
302
+ """Reset timer to 'start_time' or the current time."""
303
+ if start is None:
304
+ self.start = self._time()
305
+ else:
306
+ self.start = start
307
+ self.last = self.start
308
+ self.elapsed = 0.0
309
+
310
+ def time(self):
311
+ """Return the overall time (in seconds) since the timer started."""
312
+ return self._time() - self.start
313
+
314
+ def split(self):
315
+ """Split and return the lap time (in seconds) in between splits."""
316
+ current = self._time()
317
+ self.elapsed = current - self.last
318
+ self.last = current
319
+ return self.elapsed
320
+
321
+ def formatTime(self, msg, time):
322
+ """Format 'time' value in 'msg' and return formatted string.
323
+ If 'msg' contains a '%(time)' format string, try to use that.
324
+ Otherwise, use the predefined 'default_format'.
325
+ If 'msg' is empty or None, fall back to 'default_msg'.
326
+ """
327
+ if not msg:
328
+ msg = self.default_msg
329
+ if msg.find("%(time)") < 0:
330
+ msg = self.default_format % {"msg": msg, "time": time}
331
+ else:
332
+ try:
333
+ msg = msg % {"time": time}
334
+ except (KeyError, ValueError):
335
+ pass # skip if the format string is malformed
336
+ return msg
337
+
338
+ def __enter__(self):
339
+ """Start a new lap"""
340
+ self.last = self._time()
341
+ self.elapsed = 0.0
342
+ return self
343
+
344
+ def __exit__(self, exc_type, exc_value, traceback):
345
+ """End the current lap. If timer has a logger, log the time elapsed,
346
+ using the format string in self.msg (or the default one).
347
+ """
348
+ time = self.split()
349
+ if self.logger is None or exc_type:
350
+ # if there's no logger attached, or if any exception occurred in
351
+ # the with-statement, exit without logging the time
352
+ return
353
+ message = self.formatTime(self.msg, time)
354
+ # Allow log handlers to see the individual parts to facilitate things
355
+ # like a server accumulating aggregate stats.
356
+ msg_parts = {"msg": self.msg, "time": time}
357
+ self.logger.log(self.level, message, msg_parts)
358
+
359
+ def __call__(self, func_or_msg=None, **kwargs):
360
+ """If the first argument is a function, return a decorator which runs
361
+ the wrapped function inside Timer's context manager.
362
+ Otherwise, treat the first argument as a 'msg' string and return an updated
363
+ Timer instance, referencing the same logger.
364
+ A 'level' keyword can also be passed to override self.level.
365
+ """
366
+ if isinstance(func_or_msg, Callable):
367
+ func = func_or_msg
368
+ # use the function name when no explicit 'msg' is provided
369
+ if not self.msg:
370
+ self.msg = "run '%s'" % func.__name__
371
+
372
+ @wraps(func)
373
+ def wrapper(*args, **kwds):
374
+ with self:
375
+ return func(*args, **kwds)
376
+
377
+ return wrapper
378
+ else:
379
+ msg = func_or_msg or kwargs.get("msg")
380
+ level = kwargs.get("level", self.level)
381
+ return self.__class__(self.logger, msg, level)
382
+
383
+ def __float__(self):
384
+ return self.elapsed
385
+
386
+ def __int__(self):
387
+ return int(self.elapsed)
388
+
389
+ def __str__(self):
390
+ return "%.3f" % self.elapsed
391
+
392
+
393
+ class ChannelsFilter(logging.Filter):
394
+ """Provides a hierarchical filter for log entries based on channel names.
395
+
396
+ Filters out records emitted from a list of enabled channel names,
397
+ including their children. It works the same as the ``logging.Filter``
398
+ class, but allows the user to specify multiple channel names.
399
+
400
+ >>> import sys
401
+ >>> handler = logging.StreamHandler(sys.stdout)
402
+ >>> handler.setFormatter(logging.Formatter("%(message)s"))
403
+ >>> filter = ChannelsFilter("A.B", "C.D")
404
+ >>> handler.addFilter(filter)
405
+ >>> root = logging.getLogger()
406
+ >>> root.addHandler(handler)
407
+ >>> root.setLevel(level=logging.DEBUG)
408
+ >>> logging.getLogger('A.B').debug('this record passes through')
409
+ this record passes through
410
+ >>> logging.getLogger('A.B.C').debug('records from children also pass')
411
+ records from children also pass
412
+ >>> logging.getLogger('C.D').debug('this one as well')
413
+ this one as well
414
+ >>> logging.getLogger('A.B.').debug('also this one')
415
+ also this one
416
+ >>> logging.getLogger('A.F').debug('but this one does not!')
417
+ >>> logging.getLogger('C.DE').debug('neither this one!')
418
+ """
419
+
420
+ def __init__(self, *names):
421
+ self.names = names
422
+ self.num = len(names)
423
+ self.lengths = {n: len(n) for n in names}
424
+
425
+ def filter(self, record):
426
+ if self.num == 0:
427
+ return True
428
+ for name in self.names:
429
+ nlen = self.lengths[name]
430
+ if name == record.name:
431
+ return True
432
+ elif record.name.find(name, 0, nlen) == 0 and record.name[nlen] == ".":
433
+ return True
434
+ return False
435
+
436
+
437
+ class CapturingLogHandler(logging.Handler):
438
+ def __init__(self, logger, level):
439
+ super(CapturingLogHandler, self).__init__(level=level)
440
+ self.records = []
441
+ if isinstance(logger, str):
442
+ self.logger = logging.getLogger(logger)
443
+ else:
444
+ self.logger = logger
445
+
446
+ def __enter__(self):
447
+ self.original_disabled = self.logger.disabled
448
+ self.original_level = self.logger.level
449
+ self.original_propagate = self.logger.propagate
450
+
451
+ self.logger.addHandler(self)
452
+ self.logger.setLevel(self.level)
453
+ self.logger.disabled = False
454
+ self.logger.propagate = False
455
+
456
+ return self
457
+
458
+ def __exit__(self, type, value, traceback):
459
+ self.logger.removeHandler(self)
460
+ self.logger.setLevel(self.original_level)
461
+ self.logger.disabled = self.original_disabled
462
+ self.logger.propagate = self.original_propagate
463
+
464
+ return self
465
+
466
+ def emit(self, record):
467
+ self.records.append(record)
468
+
469
+ def assertRegex(self, regexp, msg=None):
470
+ import re
471
+
472
+ pattern = re.compile(regexp)
473
+ for r in self.records:
474
+ if pattern.search(r.getMessage()):
475
+ return True
476
+ if msg is None:
477
+ msg = "Pattern '%s' not found in logger records" % regexp
478
+ assert 0, msg
479
+
480
+
481
+ class LogMixin(object):
482
+ """Mixin class that adds logging functionality to another class.
483
+
484
+ You can define a new class that subclasses from ``LogMixin`` as well as
485
+ other base classes through multiple inheritance.
486
+ All instances of that class will have a ``log`` property that returns
487
+ a ``logging.Logger`` named after their respective ``<module>.<class>``.
488
+
489
+ For example:
490
+
491
+ >>> class BaseClass(object):
492
+ ... pass
493
+ >>> class MyClass(LogMixin, BaseClass):
494
+ ... pass
495
+ >>> a = MyClass()
496
+ >>> isinstance(a.log, logging.Logger)
497
+ True
498
+ >>> print(a.log.name)
499
+ fontTools.misc.loggingTools.MyClass
500
+ >>> class AnotherClass(MyClass):
501
+ ... pass
502
+ >>> b = AnotherClass()
503
+ >>> isinstance(b.log, logging.Logger)
504
+ True
505
+ >>> print(b.log.name)
506
+ fontTools.misc.loggingTools.AnotherClass
507
+ """
508
+
509
+ @property
510
+ def log(self):
511
+ if not hasattr(self, "_log"):
512
+ name = ".".join((self.__class__.__module__, self.__class__.__name__))
513
+ self._log = logging.getLogger(name)
514
+ return self._log
515
+
516
+
517
+ def deprecateArgument(name, msg, category=UserWarning):
518
+ """Raise a warning about deprecated function argument 'name'."""
519
+ warnings.warn("%r is deprecated; %s" % (name, msg), category=category, stacklevel=3)
520
+
521
+
522
+ def deprecateFunction(msg, category=UserWarning):
523
+ """Decorator to raise a warning when a deprecated function is called."""
524
+
525
+ def decorator(func):
526
+ @wraps(func)
527
+ def wrapper(*args, **kwargs):
528
+ warnings.warn(
529
+ "%r is deprecated; %s" % (func.__name__, msg),
530
+ category=category,
531
+ stacklevel=2,
532
+ )
533
+ return func(*args, **kwargs)
534
+
535
+ return wrapper
536
+
537
+ return decorator
538
+
539
+
540
+ if __name__ == "__main__":
541
+ import doctest
542
+
543
+ sys.exit(doctest.testmod(optionflags=doctest.ELLIPSIS).failed)
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/macCreatorType.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc.textTools import Tag, bytesjoin, strjoin
2
+
3
+ try:
4
+ import xattr
5
+ except ImportError:
6
+ xattr = None
7
+
8
+
9
+ def _reverseString(s):
10
+ s = list(s)
11
+ s.reverse()
12
+ return strjoin(s)
13
+
14
+
15
+ def getMacCreatorAndType(path):
16
+ """Returns file creator and file type codes for a path.
17
+
18
+ Args:
19
+ path (str): A file path.
20
+
21
+ Returns:
22
+ A tuple of two :py:class:`fontTools.textTools.Tag` objects, the first
23
+ representing the file creator and the second representing the
24
+ file type.
25
+ """
26
+ if xattr is not None:
27
+ try:
28
+ finderInfo = xattr.getxattr(path, "com.apple.FinderInfo")
29
+ except (KeyError, IOError):
30
+ pass
31
+ else:
32
+ fileType = Tag(finderInfo[:4])
33
+ fileCreator = Tag(finderInfo[4:8])
34
+ return fileCreator, fileType
35
+ return None, None
36
+
37
+
38
+ def setMacCreatorAndType(path, fileCreator, fileType):
39
+ """Set file creator and file type codes for a path.
40
+
41
+ Note that if the ``xattr`` module is not installed, no action is
42
+ taken but no error is raised.
43
+
44
+ Args:
45
+ path (str): A file path.
46
+ fileCreator: A four-character file creator tag.
47
+ fileType: A four-character file type tag.
48
+
49
+ """
50
+ if xattr is not None:
51
+ from fontTools.misc.textTools import pad
52
+
53
+ if not all(len(s) == 4 for s in (fileCreator, fileType)):
54
+ raise TypeError("arg must be string of 4 chars")
55
+ finderInfo = pad(bytesjoin([fileType, fileCreator]), 32)
56
+ xattr.setxattr(path, "com.apple.FinderInfo", finderInfo)
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/macRes.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ import struct
3
+ from fontTools.misc import sstruct
4
+ from fontTools.misc.textTools import bytesjoin, tostr
5
+ from collections import OrderedDict
6
+ from collections.abc import MutableMapping
7
+
8
+
9
+ class ResourceError(Exception):
10
+ pass
11
+
12
+
13
+ class ResourceReader(MutableMapping):
14
+ """Reader for Mac OS resource forks.
15
+
16
+ Parses a resource fork and returns resources according to their type.
17
+ If run on OS X, this will open the resource fork in the filesystem.
18
+ Otherwise, it will open the file itself and attempt to read it as
19
+ though it were a resource fork.
20
+
21
+ The returned object can be indexed by type and iterated over,
22
+ returning in each case a list of py:class:`Resource` objects
23
+ representing all the resources of a certain type.
24
+
25
+ """
26
+
27
+ def __init__(self, fileOrPath):
28
+ """Open a file
29
+
30
+ Args:
31
+ fileOrPath: Either an object supporting a ``read`` method, an
32
+ ``os.PathLike`` object, or a string.
33
+ """
34
+ self._resources = OrderedDict()
35
+ if hasattr(fileOrPath, "read"):
36
+ self.file = fileOrPath
37
+ else:
38
+ try:
39
+ # try reading from the resource fork (only works on OS X)
40
+ self.file = self.openResourceFork(fileOrPath)
41
+ self._readFile()
42
+ return
43
+ except (ResourceError, IOError):
44
+ # if it fails, use the data fork
45
+ self.file = self.openDataFork(fileOrPath)
46
+ self._readFile()
47
+
48
+ @staticmethod
49
+ def openResourceFork(path):
50
+ if hasattr(path, "__fspath__"): # support os.PathLike objects
51
+ path = path.__fspath__()
52
+ with open(path + "/..namedfork/rsrc", "rb") as resfork:
53
+ data = resfork.read()
54
+ infile = BytesIO(data)
55
+ infile.name = path
56
+ return infile
57
+
58
+ @staticmethod
59
+ def openDataFork(path):
60
+ with open(path, "rb") as datafork:
61
+ data = datafork.read()
62
+ infile = BytesIO(data)
63
+ infile.name = path
64
+ return infile
65
+
66
+ def _readFile(self):
67
+ self._readHeaderAndMap()
68
+ self._readTypeList()
69
+
70
+ def _read(self, numBytes, offset=None):
71
+ if offset is not None:
72
+ try:
73
+ self.file.seek(offset)
74
+ except OverflowError:
75
+ raise ResourceError("Failed to seek offset ('offset' is too large)")
76
+ if self.file.tell() != offset:
77
+ raise ResourceError("Failed to seek offset (reached EOF)")
78
+ try:
79
+ data = self.file.read(numBytes)
80
+ except OverflowError:
81
+ raise ResourceError("Cannot read resource ('numBytes' is too large)")
82
+ if len(data) != numBytes:
83
+ raise ResourceError("Cannot read resource (not enough data)")
84
+ return data
85
+
86
+ def _readHeaderAndMap(self):
87
+ self.file.seek(0)
88
+ headerData = self._read(ResourceForkHeaderSize)
89
+ sstruct.unpack(ResourceForkHeader, headerData, self)
90
+ # seek to resource map, skip reserved
91
+ mapOffset = self.mapOffset + 22
92
+ resourceMapData = self._read(ResourceMapHeaderSize, mapOffset)
93
+ sstruct.unpack(ResourceMapHeader, resourceMapData, self)
94
+ self.absTypeListOffset = self.mapOffset + self.typeListOffset
95
+ self.absNameListOffset = self.mapOffset + self.nameListOffset
96
+
97
+ def _readTypeList(self):
98
+ absTypeListOffset = self.absTypeListOffset
99
+ numTypesData = self._read(2, absTypeListOffset)
100
+ (self.numTypes,) = struct.unpack(">H", numTypesData)
101
+ absTypeListOffset2 = absTypeListOffset + 2
102
+ for i in range(self.numTypes + 1):
103
+ resTypeItemOffset = absTypeListOffset2 + ResourceTypeItemSize * i
104
+ resTypeItemData = self._read(ResourceTypeItemSize, resTypeItemOffset)
105
+ item = sstruct.unpack(ResourceTypeItem, resTypeItemData)
106
+ resType = tostr(item["type"], encoding="mac-roman")
107
+ refListOffset = absTypeListOffset + item["refListOffset"]
108
+ numRes = item["numRes"] + 1
109
+ resources = self._readReferenceList(resType, refListOffset, numRes)
110
+ self._resources[resType] = resources
111
+
112
+ def _readReferenceList(self, resType, refListOffset, numRes):
113
+ resources = []
114
+ for i in range(numRes):
115
+ refOffset = refListOffset + ResourceRefItemSize * i
116
+ refData = self._read(ResourceRefItemSize, refOffset)
117
+ res = Resource(resType)
118
+ res.decompile(refData, self)
119
+ resources.append(res)
120
+ return resources
121
+
122
+ def __getitem__(self, resType):
123
+ return self._resources[resType]
124
+
125
+ def __delitem__(self, resType):
126
+ del self._resources[resType]
127
+
128
+ def __setitem__(self, resType, resources):
129
+ self._resources[resType] = resources
130
+
131
+ def __len__(self):
132
+ return len(self._resources)
133
+
134
+ def __iter__(self):
135
+ return iter(self._resources)
136
+
137
+ def keys(self):
138
+ return self._resources.keys()
139
+
140
+ @property
141
+ def types(self):
142
+ """A list of the types of resources in the resource fork."""
143
+ return list(self._resources.keys())
144
+
145
+ def countResources(self, resType):
146
+ """Return the number of resources of a given type."""
147
+ try:
148
+ return len(self[resType])
149
+ except KeyError:
150
+ return 0
151
+
152
+ def getIndices(self, resType):
153
+ """Returns a list of indices of resources of a given type."""
154
+ numRes = self.countResources(resType)
155
+ if numRes:
156
+ return list(range(1, numRes + 1))
157
+ else:
158
+ return []
159
+
160
+ def getNames(self, resType):
161
+ """Return list of names of all resources of a given type."""
162
+ return [res.name for res in self.get(resType, []) if res.name is not None]
163
+
164
+ def getIndResource(self, resType, index):
165
+ """Return resource of given type located at an index ranging from 1
166
+ to the number of resources for that type, or None if not found.
167
+ """
168
+ if index < 1:
169
+ return None
170
+ try:
171
+ res = self[resType][index - 1]
172
+ except (KeyError, IndexError):
173
+ return None
174
+ return res
175
+
176
+ def getNamedResource(self, resType, name):
177
+ """Return the named resource of given type, else return None."""
178
+ name = tostr(name, encoding="mac-roman")
179
+ for res in self.get(resType, []):
180
+ if res.name == name:
181
+ return res
182
+ return None
183
+
184
+ def close(self):
185
+ if not self.file.closed:
186
+ self.file.close()
187
+
188
+
189
+ class Resource(object):
190
+ """Represents a resource stored within a resource fork.
191
+
192
+ Attributes:
193
+ type: resource type.
194
+ data: resource data.
195
+ id: ID.
196
+ name: resource name.
197
+ attr: attributes.
198
+ """
199
+
200
+ def __init__(
201
+ self, resType=None, resData=None, resID=None, resName=None, resAttr=None
202
+ ):
203
+ self.type = resType
204
+ self.data = resData
205
+ self.id = resID
206
+ self.name = resName
207
+ self.attr = resAttr
208
+
209
+ def decompile(self, refData, reader):
210
+ sstruct.unpack(ResourceRefItem, refData, self)
211
+ # interpret 3-byte dataOffset as (padded) ULONG to unpack it with struct
212
+ (self.dataOffset,) = struct.unpack(">L", bytesjoin([b"\0", self.dataOffset]))
213
+ absDataOffset = reader.dataOffset + self.dataOffset
214
+ (dataLength,) = struct.unpack(">L", reader._read(4, absDataOffset))
215
+ self.data = reader._read(dataLength)
216
+ if self.nameOffset == -1:
217
+ return
218
+ absNameOffset = reader.absNameListOffset + self.nameOffset
219
+ (nameLength,) = struct.unpack("B", reader._read(1, absNameOffset))
220
+ (name,) = struct.unpack(">%ss" % nameLength, reader._read(nameLength))
221
+ self.name = tostr(name, encoding="mac-roman")
222
+
223
+
224
+ ResourceForkHeader = """
225
+ > # big endian
226
+ dataOffset: L
227
+ mapOffset: L
228
+ dataLen: L
229
+ mapLen: L
230
+ """
231
+
232
+ ResourceForkHeaderSize = sstruct.calcsize(ResourceForkHeader)
233
+
234
+ ResourceMapHeader = """
235
+ > # big endian
236
+ attr: H
237
+ typeListOffset: H
238
+ nameListOffset: H
239
+ """
240
+
241
+ ResourceMapHeaderSize = sstruct.calcsize(ResourceMapHeader)
242
+
243
+ ResourceTypeItem = """
244
+ > # big endian
245
+ type: 4s
246
+ numRes: H
247
+ refListOffset: H
248
+ """
249
+
250
+ ResourceTypeItemSize = sstruct.calcsize(ResourceTypeItem)
251
+
252
+ ResourceRefItem = """
253
+ > # big endian
254
+ id: h
255
+ nameOffset: h
256
+ attr: B
257
+ dataOffset: 3s
258
+ reserved: L
259
+ """
260
+
261
+ ResourceRefItemSize = sstruct.calcsize(ResourceRefItem)
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/psCharStrings.py ADDED
@@ -0,0 +1,1496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """psCharStrings.py -- module implementing various kinds of CharStrings:
2
+ CFF dictionary data and Type1/Type2 CharStrings.
3
+ """
4
+
5
+ from fontTools.misc.fixedTools import (
6
+ fixedToFloat,
7
+ floatToFixed,
8
+ floatToFixedToStr,
9
+ strToFixedToFloat,
10
+ )
11
+ from fontTools.misc.textTools import bytechr, byteord, bytesjoin, strjoin
12
+ from fontTools.pens.boundsPen import BoundsPen
13
+ import struct
14
+ import logging
15
+
16
+
17
+ log = logging.getLogger(__name__)
18
+
19
+
20
+ def read_operator(self, b0, data, index):
21
+ if b0 == 12:
22
+ op = (b0, byteord(data[index]))
23
+ index = index + 1
24
+ else:
25
+ op = b0
26
+ try:
27
+ operator = self.operators[op]
28
+ except KeyError:
29
+ return None, index
30
+ value = self.handle_operator(operator)
31
+ return value, index
32
+
33
+
34
+ def read_byte(self, b0, data, index):
35
+ return b0 - 139, index
36
+
37
+
38
+ def read_smallInt1(self, b0, data, index):
39
+ b1 = byteord(data[index])
40
+ return (b0 - 247) * 256 + b1 + 108, index + 1
41
+
42
+
43
+ def read_smallInt2(self, b0, data, index):
44
+ b1 = byteord(data[index])
45
+ return -(b0 - 251) * 256 - b1 - 108, index + 1
46
+
47
+
48
+ def read_shortInt(self, b0, data, index):
49
+ (value,) = struct.unpack(">h", data[index : index + 2])
50
+ return value, index + 2
51
+
52
+
53
+ def read_longInt(self, b0, data, index):
54
+ (value,) = struct.unpack(">l", data[index : index + 4])
55
+ return value, index + 4
56
+
57
+
58
+ def read_fixed1616(self, b0, data, index):
59
+ (value,) = struct.unpack(">l", data[index : index + 4])
60
+ return fixedToFloat(value, precisionBits=16), index + 4
61
+
62
+
63
+ def read_reserved(self, b0, data, index):
64
+ assert NotImplementedError
65
+ return NotImplemented, index
66
+
67
+
68
+ def read_realNumber(self, b0, data, index):
69
+ number = ""
70
+ while True:
71
+ b = byteord(data[index])
72
+ index = index + 1
73
+ nibble0 = (b & 0xF0) >> 4
74
+ nibble1 = b & 0x0F
75
+ if nibble0 == 0xF:
76
+ break
77
+ number = number + realNibbles[nibble0]
78
+ if nibble1 == 0xF:
79
+ break
80
+ number = number + realNibbles[nibble1]
81
+ return float(number), index
82
+
83
+
84
+ t1OperandEncoding = [None] * 256
85
+ t1OperandEncoding[0:32] = (32) * [read_operator]
86
+ t1OperandEncoding[32:247] = (247 - 32) * [read_byte]
87
+ t1OperandEncoding[247:251] = (251 - 247) * [read_smallInt1]
88
+ t1OperandEncoding[251:255] = (255 - 251) * [read_smallInt2]
89
+ t1OperandEncoding[255] = read_longInt
90
+ assert len(t1OperandEncoding) == 256
91
+
92
+ t2OperandEncoding = t1OperandEncoding[:]
93
+ t2OperandEncoding[28] = read_shortInt
94
+ t2OperandEncoding[255] = read_fixed1616
95
+
96
+ cffDictOperandEncoding = t2OperandEncoding[:]
97
+ cffDictOperandEncoding[29] = read_longInt
98
+ cffDictOperandEncoding[30] = read_realNumber
99
+ cffDictOperandEncoding[255] = read_reserved
100
+
101
+
102
+ realNibbles = [
103
+ "0",
104
+ "1",
105
+ "2",
106
+ "3",
107
+ "4",
108
+ "5",
109
+ "6",
110
+ "7",
111
+ "8",
112
+ "9",
113
+ ".",
114
+ "E",
115
+ "E-",
116
+ None,
117
+ "-",
118
+ ]
119
+ realNibblesDict = {v: i for i, v in enumerate(realNibbles)}
120
+
121
+ maxOpStack = 193
122
+
123
+
124
+ def buildOperatorDict(operatorList):
125
+ oper = {}
126
+ opc = {}
127
+ for item in operatorList:
128
+ if len(item) == 2:
129
+ oper[item[0]] = item[1]
130
+ else:
131
+ oper[item[0]] = item[1:]
132
+ if isinstance(item[0], tuple):
133
+ opc[item[1]] = item[0]
134
+ else:
135
+ opc[item[1]] = (item[0],)
136
+ return oper, opc
137
+
138
+
139
+ t2Operators = [
140
+ # opcode name
141
+ (1, "hstem"),
142
+ (3, "vstem"),
143
+ (4, "vmoveto"),
144
+ (5, "rlineto"),
145
+ (6, "hlineto"),
146
+ (7, "vlineto"),
147
+ (8, "rrcurveto"),
148
+ (10, "callsubr"),
149
+ (11, "return"),
150
+ (14, "endchar"),
151
+ (15, "vsindex"),
152
+ (16, "blend"),
153
+ (18, "hstemhm"),
154
+ (19, "hintmask"),
155
+ (20, "cntrmask"),
156
+ (21, "rmoveto"),
157
+ (22, "hmoveto"),
158
+ (23, "vstemhm"),
159
+ (24, "rcurveline"),
160
+ (25, "rlinecurve"),
161
+ (26, "vvcurveto"),
162
+ (27, "hhcurveto"),
163
+ # (28, 'shortint'), # not really an operator
164
+ (29, "callgsubr"),
165
+ (30, "vhcurveto"),
166
+ (31, "hvcurveto"),
167
+ ((12, 0), "ignore"), # dotsection. Yes, there a few very early OTF/CFF
168
+ # fonts with this deprecated operator. Just ignore it.
169
+ ((12, 3), "and"),
170
+ ((12, 4), "or"),
171
+ ((12, 5), "not"),
172
+ ((12, 8), "store"),
173
+ ((12, 9), "abs"),
174
+ ((12, 10), "add"),
175
+ ((12, 11), "sub"),
176
+ ((12, 12), "div"),
177
+ ((12, 13), "load"),
178
+ ((12, 14), "neg"),
179
+ ((12, 15), "eq"),
180
+ ((12, 18), "drop"),
181
+ ((12, 20), "put"),
182
+ ((12, 21), "get"),
183
+ ((12, 22), "ifelse"),
184
+ ((12, 23), "random"),
185
+ ((12, 24), "mul"),
186
+ ((12, 26), "sqrt"),
187
+ ((12, 27), "dup"),
188
+ ((12, 28), "exch"),
189
+ ((12, 29), "index"),
190
+ ((12, 30), "roll"),
191
+ ((12, 34), "hflex"),
192
+ ((12, 35), "flex"),
193
+ ((12, 36), "hflex1"),
194
+ ((12, 37), "flex1"),
195
+ ]
196
+
197
+
198
+ def getIntEncoder(format):
199
+ if format == "cff":
200
+ twoByteOp = bytechr(28)
201
+ fourByteOp = bytechr(29)
202
+ elif format == "t1":
203
+ twoByteOp = None
204
+ fourByteOp = bytechr(255)
205
+ else:
206
+ assert format == "t2"
207
+ twoByteOp = bytechr(28)
208
+ fourByteOp = None
209
+
210
+ def encodeInt(
211
+ value,
212
+ fourByteOp=fourByteOp,
213
+ bytechr=bytechr,
214
+ pack=struct.pack,
215
+ unpack=struct.unpack,
216
+ twoByteOp=twoByteOp,
217
+ ):
218
+ if -107 <= value <= 107:
219
+ code = bytechr(value + 139)
220
+ elif 108 <= value <= 1131:
221
+ value = value - 108
222
+ code = bytechr((value >> 8) + 247) + bytechr(value & 0xFF)
223
+ elif -1131 <= value <= -108:
224
+ value = -value - 108
225
+ code = bytechr((value >> 8) + 251) + bytechr(value & 0xFF)
226
+ elif twoByteOp is not None and -32768 <= value <= 32767:
227
+ code = twoByteOp + pack(">h", value)
228
+ elif fourByteOp is None:
229
+ # Backwards compatible hack: due to a previous bug in FontTools,
230
+ # 16.16 fixed numbers were written out as 4-byte ints. When
231
+ # these numbers were small, they were wrongly written back as
232
+ # small ints instead of 4-byte ints, breaking round-tripping.
233
+ # This here workaround doesn't do it any better, since we can't
234
+ # distinguish anymore between small ints that were supposed to
235
+ # be small fixed numbers and small ints that were just small
236
+ # ints. Hence the warning.
237
+ log.warning(
238
+ "4-byte T2 number got passed to the "
239
+ "IntType handler. This should happen only when reading in "
240
+ "old XML files.\n"
241
+ )
242
+ code = bytechr(255) + pack(">l", value)
243
+ else:
244
+ code = fourByteOp + pack(">l", value)
245
+ return code
246
+
247
+ return encodeInt
248
+
249
+
250
+ encodeIntCFF = getIntEncoder("cff")
251
+ encodeIntT1 = getIntEncoder("t1")
252
+ encodeIntT2 = getIntEncoder("t2")
253
+
254
+
255
+ def encodeFixed(f, pack=struct.pack):
256
+ """For T2 only"""
257
+ value = floatToFixed(f, precisionBits=16)
258
+ if value & 0xFFFF == 0: # check if the fractional part is zero
259
+ return encodeIntT2(value >> 16) # encode only the integer part
260
+ else:
261
+ return b"\xff" + pack(">l", value) # encode the entire fixed point value
262
+
263
+
264
+ realZeroBytes = bytechr(30) + bytechr(0xF)
265
+
266
+
267
+ def encodeFloat(f):
268
+ # For CFF only, used in cffLib
269
+ if f == 0.0: # 0.0 == +0.0 == -0.0
270
+ return realZeroBytes
271
+ # Note: 14 decimal digits seems to be the limitation for CFF real numbers
272
+ # in macOS. However, we use 8 here to match the implementation of AFDKO.
273
+ s = "%.8G" % f
274
+ if s[:2] == "0.":
275
+ s = s[1:]
276
+ elif s[:3] == "-0.":
277
+ s = "-" + s[2:]
278
+ elif s.endswith("000"):
279
+ significantDigits = s.rstrip("0")
280
+ s = "%sE%d" % (significantDigits, len(s) - len(significantDigits))
281
+ else:
282
+ dotIndex = s.find(".")
283
+ eIndex = s.find("E")
284
+ if dotIndex != -1 and eIndex != -1:
285
+ integerPart = s[:dotIndex]
286
+ fractionalPart = s[dotIndex + 1 : eIndex]
287
+ exponent = int(s[eIndex + 1 :])
288
+ newExponent = exponent - len(fractionalPart)
289
+ if newExponent == 1:
290
+ s = "%s%s0" % (integerPart, fractionalPart)
291
+ else:
292
+ s = "%s%sE%d" % (integerPart, fractionalPart, newExponent)
293
+ if s.startswith((".0", "-.0")):
294
+ sign, s = s.split(".", 1)
295
+ s = "%s%sE-%d" % (sign, s.lstrip("0"), len(s))
296
+ nibbles = []
297
+ while s:
298
+ c = s[0]
299
+ s = s[1:]
300
+ if c == "E":
301
+ c2 = s[:1]
302
+ if c2 == "-":
303
+ s = s[1:]
304
+ c = "E-"
305
+ elif c2 == "+":
306
+ s = s[1:]
307
+ if s.startswith("0"):
308
+ s = s[1:]
309
+ nibbles.append(realNibblesDict[c])
310
+ nibbles.append(0xF)
311
+ if len(nibbles) % 2:
312
+ nibbles.append(0xF)
313
+ d = bytechr(30)
314
+ for i in range(0, len(nibbles), 2):
315
+ d = d + bytechr(nibbles[i] << 4 | nibbles[i + 1])
316
+ return d
317
+
318
+
319
+ class CharStringCompileError(Exception):
320
+ pass
321
+
322
+
323
+ class SimpleT2Decompiler(object):
324
+ def __init__(self, localSubrs, globalSubrs, private=None, blender=None):
325
+ self.localSubrs = localSubrs
326
+ self.localBias = calcSubrBias(localSubrs)
327
+ self.globalSubrs = globalSubrs
328
+ self.globalBias = calcSubrBias(globalSubrs)
329
+ self.private = private
330
+ self.blender = blender
331
+ self.reset()
332
+
333
+ def reset(self):
334
+ self.callingStack = []
335
+ self.operandStack = []
336
+ self.hintCount = 0
337
+ self.hintMaskBytes = 0
338
+ self.numRegions = 0
339
+ self.vsIndex = 0
340
+
341
+ def execute(self, charString):
342
+ self.callingStack.append(charString)
343
+ needsDecompilation = charString.needsDecompilation()
344
+ if needsDecompilation:
345
+ program = []
346
+ pushToProgram = program.append
347
+ else:
348
+ pushToProgram = lambda x: None
349
+ pushToStack = self.operandStack.append
350
+ index = 0
351
+ while True:
352
+ token, isOperator, index = charString.getToken(index)
353
+ if token is None:
354
+ break # we're done!
355
+ pushToProgram(token)
356
+ if isOperator:
357
+ handlerName = "op_" + token
358
+ handler = getattr(self, handlerName, None)
359
+ if handler is not None:
360
+ rv = handler(index)
361
+ if rv:
362
+ hintMaskBytes, index = rv
363
+ pushToProgram(hintMaskBytes)
364
+ else:
365
+ self.popall()
366
+ else:
367
+ pushToStack(token)
368
+ if needsDecompilation:
369
+ charString.setProgram(program)
370
+ del self.callingStack[-1]
371
+
372
+ def pop(self):
373
+ value = self.operandStack[-1]
374
+ del self.operandStack[-1]
375
+ return value
376
+
377
+ def popall(self):
378
+ stack = self.operandStack[:]
379
+ self.operandStack[:] = []
380
+ return stack
381
+
382
+ def push(self, value):
383
+ self.operandStack.append(value)
384
+
385
+ def op_return(self, index):
386
+ if self.operandStack:
387
+ pass
388
+
389
+ def op_endchar(self, index):
390
+ pass
391
+
392
+ def op_ignore(self, index):
393
+ pass
394
+
395
+ def op_callsubr(self, index):
396
+ subrIndex = self.pop()
397
+ subr = self.localSubrs[subrIndex + self.localBias]
398
+ self.execute(subr)
399
+
400
+ def op_callgsubr(self, index):
401
+ subrIndex = self.pop()
402
+ subr = self.globalSubrs[subrIndex + self.globalBias]
403
+ self.execute(subr)
404
+
405
+ def op_hstem(self, index):
406
+ self.countHints()
407
+
408
+ def op_vstem(self, index):
409
+ self.countHints()
410
+
411
+ def op_hstemhm(self, index):
412
+ self.countHints()
413
+
414
+ def op_vstemhm(self, index):
415
+ self.countHints()
416
+
417
+ def op_hintmask(self, index):
418
+ if not self.hintMaskBytes:
419
+ self.countHints()
420
+ self.hintMaskBytes = (self.hintCount + 7) // 8
421
+ hintMaskBytes, index = self.callingStack[-1].getBytes(index, self.hintMaskBytes)
422
+ return hintMaskBytes, index
423
+
424
+ op_cntrmask = op_hintmask
425
+
426
+ def countHints(self):
427
+ args = self.popall()
428
+ self.hintCount = self.hintCount + len(args) // 2
429
+
430
+ # misc
431
+ def op_and(self, index):
432
+ raise NotImplementedError
433
+
434
+ def op_or(self, index):
435
+ raise NotImplementedError
436
+
437
+ def op_not(self, index):
438
+ raise NotImplementedError
439
+
440
+ def op_store(self, index):
441
+ raise NotImplementedError
442
+
443
+ def op_abs(self, index):
444
+ raise NotImplementedError
445
+
446
+ def op_add(self, index):
447
+ raise NotImplementedError
448
+
449
+ def op_sub(self, index):
450
+ raise NotImplementedError
451
+
452
+ def op_div(self, index):
453
+ raise NotImplementedError
454
+
455
+ def op_load(self, index):
456
+ raise NotImplementedError
457
+
458
+ def op_neg(self, index):
459
+ raise NotImplementedError
460
+
461
+ def op_eq(self, index):
462
+ raise NotImplementedError
463
+
464
+ def op_drop(self, index):
465
+ raise NotImplementedError
466
+
467
+ def op_put(self, index):
468
+ raise NotImplementedError
469
+
470
+ def op_get(self, index):
471
+ raise NotImplementedError
472
+
473
+ def op_ifelse(self, index):
474
+ raise NotImplementedError
475
+
476
+ def op_random(self, index):
477
+ raise NotImplementedError
478
+
479
+ def op_mul(self, index):
480
+ raise NotImplementedError
481
+
482
+ def op_sqrt(self, index):
483
+ raise NotImplementedError
484
+
485
+ def op_dup(self, index):
486
+ raise NotImplementedError
487
+
488
+ def op_exch(self, index):
489
+ raise NotImplementedError
490
+
491
+ def op_index(self, index):
492
+ raise NotImplementedError
493
+
494
+ def op_roll(self, index):
495
+ raise NotImplementedError
496
+
497
+ def op_blend(self, index):
498
+ if self.numRegions == 0:
499
+ self.numRegions = self.private.getNumRegions()
500
+ numBlends = self.pop()
501
+ numOps = numBlends * (self.numRegions + 1)
502
+ if self.blender is None:
503
+ del self.operandStack[
504
+ -(numOps - numBlends) :
505
+ ] # Leave the default operands on the stack.
506
+ else:
507
+ argi = len(self.operandStack) - numOps
508
+ end_args = tuplei = argi + numBlends
509
+ while argi < end_args:
510
+ next_ti = tuplei + self.numRegions
511
+ deltas = self.operandStack[tuplei:next_ti]
512
+ delta = self.blender(self.vsIndex, deltas)
513
+ self.operandStack[argi] += delta
514
+ tuplei = next_ti
515
+ argi += 1
516
+ self.operandStack[end_args:] = []
517
+
518
+ def op_vsindex(self, index):
519
+ vi = self.pop()
520
+ self.vsIndex = vi
521
+ self.numRegions = self.private.getNumRegions(vi)
522
+
523
+
524
+ t1Operators = [
525
+ # opcode name
526
+ (1, "hstem"),
527
+ (3, "vstem"),
528
+ (4, "vmoveto"),
529
+ (5, "rlineto"),
530
+ (6, "hlineto"),
531
+ (7, "vlineto"),
532
+ (8, "rrcurveto"),
533
+ (9, "closepath"),
534
+ (10, "callsubr"),
535
+ (11, "return"),
536
+ (13, "hsbw"),
537
+ (14, "endchar"),
538
+ (21, "rmoveto"),
539
+ (22, "hmoveto"),
540
+ (30, "vhcurveto"),
541
+ (31, "hvcurveto"),
542
+ ((12, 0), "dotsection"),
543
+ ((12, 1), "vstem3"),
544
+ ((12, 2), "hstem3"),
545
+ ((12, 6), "seac"),
546
+ ((12, 7), "sbw"),
547
+ ((12, 12), "div"),
548
+ ((12, 16), "callothersubr"),
549
+ ((12, 17), "pop"),
550
+ ((12, 33), "setcurrentpoint"),
551
+ ]
552
+
553
+
554
+ class T2WidthExtractor(SimpleT2Decompiler):
555
+ def __init__(
556
+ self,
557
+ localSubrs,
558
+ globalSubrs,
559
+ nominalWidthX,
560
+ defaultWidthX,
561
+ private=None,
562
+ blender=None,
563
+ ):
564
+ SimpleT2Decompiler.__init__(self, localSubrs, globalSubrs, private, blender)
565
+ self.nominalWidthX = nominalWidthX
566
+ self.defaultWidthX = defaultWidthX
567
+
568
+ def reset(self):
569
+ SimpleT2Decompiler.reset(self)
570
+ self.gotWidth = 0
571
+ self.width = 0
572
+
573
+ def popallWidth(self, evenOdd=0):
574
+ args = self.popall()
575
+ if not self.gotWidth:
576
+ if evenOdd ^ (len(args) % 2):
577
+ # For CFF2 charstrings, this should never happen
578
+ assert (
579
+ self.defaultWidthX is not None
580
+ ), "CFF2 CharStrings must not have an initial width value"
581
+ self.width = self.nominalWidthX + args[0]
582
+ args = args[1:]
583
+ else:
584
+ self.width = self.defaultWidthX
585
+ self.gotWidth = 1
586
+ return args
587
+
588
+ def countHints(self):
589
+ args = self.popallWidth()
590
+ self.hintCount = self.hintCount + len(args) // 2
591
+
592
+ def op_rmoveto(self, index):
593
+ self.popallWidth()
594
+
595
+ def op_hmoveto(self, index):
596
+ self.popallWidth(1)
597
+
598
+ def op_vmoveto(self, index):
599
+ self.popallWidth(1)
600
+
601
+ def op_endchar(self, index):
602
+ self.popallWidth()
603
+
604
+
605
+ class T2OutlineExtractor(T2WidthExtractor):
606
+ def __init__(
607
+ self,
608
+ pen,
609
+ localSubrs,
610
+ globalSubrs,
611
+ nominalWidthX,
612
+ defaultWidthX,
613
+ private=None,
614
+ blender=None,
615
+ ):
616
+ T2WidthExtractor.__init__(
617
+ self,
618
+ localSubrs,
619
+ globalSubrs,
620
+ nominalWidthX,
621
+ defaultWidthX,
622
+ private,
623
+ blender,
624
+ )
625
+ self.pen = pen
626
+ self.subrLevel = 0
627
+
628
+ def reset(self):
629
+ T2WidthExtractor.reset(self)
630
+ self.currentPoint = (0, 0)
631
+ self.sawMoveTo = 0
632
+ self.subrLevel = 0
633
+
634
+ def execute(self, charString):
635
+ self.subrLevel += 1
636
+ super().execute(charString)
637
+ self.subrLevel -= 1
638
+ if self.subrLevel == 0:
639
+ self.endPath()
640
+
641
+ def _nextPoint(self, point):
642
+ x, y = self.currentPoint
643
+ point = x + point[0], y + point[1]
644
+ self.currentPoint = point
645
+ return point
646
+
647
+ def rMoveTo(self, point):
648
+ self.pen.moveTo(self._nextPoint(point))
649
+ self.sawMoveTo = 1
650
+
651
+ def rLineTo(self, point):
652
+ if not self.sawMoveTo:
653
+ self.rMoveTo((0, 0))
654
+ self.pen.lineTo(self._nextPoint(point))
655
+
656
+ def rCurveTo(self, pt1, pt2, pt3):
657
+ if not self.sawMoveTo:
658
+ self.rMoveTo((0, 0))
659
+ nextPoint = self._nextPoint
660
+ self.pen.curveTo(nextPoint(pt1), nextPoint(pt2), nextPoint(pt3))
661
+
662
+ def closePath(self):
663
+ if self.sawMoveTo:
664
+ self.pen.closePath()
665
+ self.sawMoveTo = 0
666
+
667
+ def endPath(self):
668
+ # In T2 there are no open paths, so always do a closePath when
669
+ # finishing a sub path. We avoid spurious calls to closePath()
670
+ # because its a real T1 op we're emulating in T2 whereas
671
+ # endPath() is just a means to that emulation
672
+ if self.sawMoveTo:
673
+ self.closePath()
674
+
675
+ #
676
+ # hint operators
677
+ #
678
+ # def op_hstem(self, index):
679
+ # self.countHints()
680
+ # def op_vstem(self, index):
681
+ # self.countHints()
682
+ # def op_hstemhm(self, index):
683
+ # self.countHints()
684
+ # def op_vstemhm(self, index):
685
+ # self.countHints()
686
+ # def op_hintmask(self, index):
687
+ # self.countHints()
688
+ # def op_cntrmask(self, index):
689
+ # self.countHints()
690
+
691
+ #
692
+ # path constructors, moveto
693
+ #
694
+ def op_rmoveto(self, index):
695
+ self.endPath()
696
+ self.rMoveTo(self.popallWidth())
697
+
698
+ def op_hmoveto(self, index):
699
+ self.endPath()
700
+ self.rMoveTo((self.popallWidth(1)[0], 0))
701
+
702
+ def op_vmoveto(self, index):
703
+ self.endPath()
704
+ self.rMoveTo((0, self.popallWidth(1)[0]))
705
+
706
+ def op_endchar(self, index):
707
+ self.endPath()
708
+ args = self.popallWidth()
709
+ if args:
710
+ from fontTools.encodings.StandardEncoding import StandardEncoding
711
+
712
+ # endchar can do seac accent bulding; The T2 spec says it's deprecated,
713
+ # but recent software that shall remain nameless does output it.
714
+ adx, ady, bchar, achar = args
715
+ baseGlyph = StandardEncoding[bchar]
716
+ self.pen.addComponent(baseGlyph, (1, 0, 0, 1, 0, 0))
717
+ accentGlyph = StandardEncoding[achar]
718
+ self.pen.addComponent(accentGlyph, (1, 0, 0, 1, adx, ady))
719
+
720
+ #
721
+ # path constructors, lines
722
+ #
723
+ def op_rlineto(self, index):
724
+ args = self.popall()
725
+ for i in range(0, len(args), 2):
726
+ point = args[i : i + 2]
727
+ self.rLineTo(point)
728
+
729
+ def op_hlineto(self, index):
730
+ self.alternatingLineto(1)
731
+
732
+ def op_vlineto(self, index):
733
+ self.alternatingLineto(0)
734
+
735
+ #
736
+ # path constructors, curves
737
+ #
738
+ def op_rrcurveto(self, index):
739
+ """{dxa dya dxb dyb dxc dyc}+ rrcurveto"""
740
+ args = self.popall()
741
+ for i in range(0, len(args), 6):
742
+ (
743
+ dxa,
744
+ dya,
745
+ dxb,
746
+ dyb,
747
+ dxc,
748
+ dyc,
749
+ ) = args[i : i + 6]
750
+ self.rCurveTo((dxa, dya), (dxb, dyb), (dxc, dyc))
751
+
752
+ def op_rcurveline(self, index):
753
+ """{dxa dya dxb dyb dxc dyc}+ dxd dyd rcurveline"""
754
+ args = self.popall()
755
+ for i in range(0, len(args) - 2, 6):
756
+ dxb, dyb, dxc, dyc, dxd, dyd = args[i : i + 6]
757
+ self.rCurveTo((dxb, dyb), (dxc, dyc), (dxd, dyd))
758
+ self.rLineTo(args[-2:])
759
+
760
+ def op_rlinecurve(self, index):
761
+ """{dxa dya}+ dxb dyb dxc dyc dxd dyd rlinecurve"""
762
+ args = self.popall()
763
+ lineArgs = args[:-6]
764
+ for i in range(0, len(lineArgs), 2):
765
+ self.rLineTo(lineArgs[i : i + 2])
766
+ dxb, dyb, dxc, dyc, dxd, dyd = args[-6:]
767
+ self.rCurveTo((dxb, dyb), (dxc, dyc), (dxd, dyd))
768
+
769
+ def op_vvcurveto(self, index):
770
+ "dx1? {dya dxb dyb dyc}+ vvcurveto"
771
+ args = self.popall()
772
+ if len(args) % 2:
773
+ dx1 = args[0]
774
+ args = args[1:]
775
+ else:
776
+ dx1 = 0
777
+ for i in range(0, len(args), 4):
778
+ dya, dxb, dyb, dyc = args[i : i + 4]
779
+ self.rCurveTo((dx1, dya), (dxb, dyb), (0, dyc))
780
+ dx1 = 0
781
+
782
+ def op_hhcurveto(self, index):
783
+ """dy1? {dxa dxb dyb dxc}+ hhcurveto"""
784
+ args = self.popall()
785
+ if len(args) % 2:
786
+ dy1 = args[0]
787
+ args = args[1:]
788
+ else:
789
+ dy1 = 0
790
+ for i in range(0, len(args), 4):
791
+ dxa, dxb, dyb, dxc = args[i : i + 4]
792
+ self.rCurveTo((dxa, dy1), (dxb, dyb), (dxc, 0))
793
+ dy1 = 0
794
+
795
+ def op_vhcurveto(self, index):
796
+ """dy1 dx2 dy2 dx3 {dxa dxb dyb dyc dyd dxe dye dxf}* dyf? vhcurveto (30)
797
+ {dya dxb dyb dxc dxd dxe dye dyf}+ dxf? vhcurveto
798
+ """
799
+ args = self.popall()
800
+ while args:
801
+ args = self.vcurveto(args)
802
+ if args:
803
+ args = self.hcurveto(args)
804
+
805
+ def op_hvcurveto(self, index):
806
+ """dx1 dx2 dy2 dy3 {dya dxb dyb dxc dxd dxe dye dyf}* dxf?
807
+ {dxa dxb dyb dyc dyd dxe dye dxf}+ dyf?
808
+ """
809
+ args = self.popall()
810
+ while args:
811
+ args = self.hcurveto(args)
812
+ if args:
813
+ args = self.vcurveto(args)
814
+
815
+ #
816
+ # path constructors, flex
817
+ #
818
+ def op_hflex(self, index):
819
+ dx1, dx2, dy2, dx3, dx4, dx5, dx6 = self.popall()
820
+ dy1 = dy3 = dy4 = dy6 = 0
821
+ dy5 = -dy2
822
+ self.rCurveTo((dx1, dy1), (dx2, dy2), (dx3, dy3))
823
+ self.rCurveTo((dx4, dy4), (dx5, dy5), (dx6, dy6))
824
+
825
+ def op_flex(self, index):
826
+ dx1, dy1, dx2, dy2, dx3, dy3, dx4, dy4, dx5, dy5, dx6, dy6, fd = self.popall()
827
+ self.rCurveTo((dx1, dy1), (dx2, dy2), (dx3, dy3))
828
+ self.rCurveTo((dx4, dy4), (dx5, dy5), (dx6, dy6))
829
+
830
+ def op_hflex1(self, index):
831
+ dx1, dy1, dx2, dy2, dx3, dx4, dx5, dy5, dx6 = self.popall()
832
+ dy3 = dy4 = 0
833
+ dy6 = -(dy1 + dy2 + dy3 + dy4 + dy5)
834
+
835
+ self.rCurveTo((dx1, dy1), (dx2, dy2), (dx3, dy3))
836
+ self.rCurveTo((dx4, dy4), (dx5, dy5), (dx6, dy6))
837
+
838
+ def op_flex1(self, index):
839
+ dx1, dy1, dx2, dy2, dx3, dy3, dx4, dy4, dx5, dy5, d6 = self.popall()
840
+ dx = dx1 + dx2 + dx3 + dx4 + dx5
841
+ dy = dy1 + dy2 + dy3 + dy4 + dy5
842
+ if abs(dx) > abs(dy):
843
+ dx6 = d6
844
+ dy6 = -dy
845
+ else:
846
+ dx6 = -dx
847
+ dy6 = d6
848
+ self.rCurveTo((dx1, dy1), (dx2, dy2), (dx3, dy3))
849
+ self.rCurveTo((dx4, dy4), (dx5, dy5), (dx6, dy6))
850
+
851
+ # misc
852
+ def op_and(self, index):
853
+ raise NotImplementedError
854
+
855
+ def op_or(self, index):
856
+ raise NotImplementedError
857
+
858
+ def op_not(self, index):
859
+ raise NotImplementedError
860
+
861
+ def op_store(self, index):
862
+ raise NotImplementedError
863
+
864
+ def op_abs(self, index):
865
+ raise NotImplementedError
866
+
867
+ def op_add(self, index):
868
+ raise NotImplementedError
869
+
870
+ def op_sub(self, index):
871
+ raise NotImplementedError
872
+
873
+ def op_div(self, index):
874
+ num2 = self.pop()
875
+ num1 = self.pop()
876
+ d1 = num1 // num2
877
+ d2 = num1 / num2
878
+ if d1 == d2:
879
+ self.push(d1)
880
+ else:
881
+ self.push(d2)
882
+
883
+ def op_load(self, index):
884
+ raise NotImplementedError
885
+
886
+ def op_neg(self, index):
887
+ raise NotImplementedError
888
+
889
+ def op_eq(self, index):
890
+ raise NotImplementedError
891
+
892
+ def op_drop(self, index):
893
+ raise NotImplementedError
894
+
895
+ def op_put(self, index):
896
+ raise NotImplementedError
897
+
898
+ def op_get(self, index):
899
+ raise NotImplementedError
900
+
901
+ def op_ifelse(self, index):
902
+ raise NotImplementedError
903
+
904
+ def op_random(self, index):
905
+ raise NotImplementedError
906
+
907
+ def op_mul(self, index):
908
+ raise NotImplementedError
909
+
910
+ def op_sqrt(self, index):
911
+ raise NotImplementedError
912
+
913
+ def op_dup(self, index):
914
+ raise NotImplementedError
915
+
916
+ def op_exch(self, index):
917
+ raise NotImplementedError
918
+
919
+ def op_index(self, index):
920
+ raise NotImplementedError
921
+
922
+ def op_roll(self, index):
923
+ raise NotImplementedError
924
+
925
+ #
926
+ # miscellaneous helpers
927
+ #
928
+ def alternatingLineto(self, isHorizontal):
929
+ args = self.popall()
930
+ for arg in args:
931
+ if isHorizontal:
932
+ point = (arg, 0)
933
+ else:
934
+ point = (0, arg)
935
+ self.rLineTo(point)
936
+ isHorizontal = not isHorizontal
937
+
938
+ def vcurveto(self, args):
939
+ dya, dxb, dyb, dxc = args[:4]
940
+ args = args[4:]
941
+ if len(args) == 1:
942
+ dyc = args[0]
943
+ args = []
944
+ else:
945
+ dyc = 0
946
+ self.rCurveTo((0, dya), (dxb, dyb), (dxc, dyc))
947
+ return args
948
+
949
+ def hcurveto(self, args):
950
+ dxa, dxb, dyb, dyc = args[:4]
951
+ args = args[4:]
952
+ if len(args) == 1:
953
+ dxc = args[0]
954
+ args = []
955
+ else:
956
+ dxc = 0
957
+ self.rCurveTo((dxa, 0), (dxb, dyb), (dxc, dyc))
958
+ return args
959
+
960
+
961
+ class T1OutlineExtractor(T2OutlineExtractor):
962
+ def __init__(self, pen, subrs):
963
+ self.pen = pen
964
+ self.subrs = subrs
965
+ self.reset()
966
+
967
+ def reset(self):
968
+ self.flexing = 0
969
+ self.width = 0
970
+ self.sbx = 0
971
+ T2OutlineExtractor.reset(self)
972
+
973
+ def endPath(self):
974
+ if self.sawMoveTo:
975
+ self.pen.endPath()
976
+ self.sawMoveTo = 0
977
+
978
+ def popallWidth(self, evenOdd=0):
979
+ return self.popall()
980
+
981
+ def exch(self):
982
+ stack = self.operandStack
983
+ stack[-1], stack[-2] = stack[-2], stack[-1]
984
+
985
+ #
986
+ # path constructors
987
+ #
988
+ def op_rmoveto(self, index):
989
+ if self.flexing:
990
+ return
991
+ self.endPath()
992
+ self.rMoveTo(self.popall())
993
+
994
+ def op_hmoveto(self, index):
995
+ if self.flexing:
996
+ # We must add a parameter to the stack if we are flexing
997
+ self.push(0)
998
+ return
999
+ self.endPath()
1000
+ self.rMoveTo((self.popall()[0], 0))
1001
+
1002
+ def op_vmoveto(self, index):
1003
+ if self.flexing:
1004
+ # We must add a parameter to the stack if we are flexing
1005
+ self.push(0)
1006
+ self.exch()
1007
+ return
1008
+ self.endPath()
1009
+ self.rMoveTo((0, self.popall()[0]))
1010
+
1011
+ def op_closepath(self, index):
1012
+ self.closePath()
1013
+
1014
+ def op_setcurrentpoint(self, index):
1015
+ args = self.popall()
1016
+ x, y = args
1017
+ self.currentPoint = x, y
1018
+
1019
+ def op_endchar(self, index):
1020
+ self.endPath()
1021
+
1022
+ def op_hsbw(self, index):
1023
+ sbx, wx = self.popall()
1024
+ self.width = wx
1025
+ self.sbx = sbx
1026
+ self.currentPoint = sbx, self.currentPoint[1]
1027
+
1028
+ def op_sbw(self, index):
1029
+ self.popall() # XXX
1030
+
1031
+ #
1032
+ def op_callsubr(self, index):
1033
+ subrIndex = self.pop()
1034
+ subr = self.subrs[subrIndex]
1035
+ self.execute(subr)
1036
+
1037
+ def op_callothersubr(self, index):
1038
+ subrIndex = self.pop()
1039
+ nArgs = self.pop()
1040
+ # print nArgs, subrIndex, "callothersubr"
1041
+ if subrIndex == 0 and nArgs == 3:
1042
+ self.doFlex()
1043
+ self.flexing = 0
1044
+ elif subrIndex == 1 and nArgs == 0:
1045
+ self.flexing = 1
1046
+ # ignore...
1047
+
1048
+ def op_pop(self, index):
1049
+ pass # ignore...
1050
+
1051
+ def doFlex(self):
1052
+ finaly = self.pop()
1053
+ finalx = self.pop()
1054
+ self.pop() # flex height is unused
1055
+
1056
+ p3y = self.pop()
1057
+ p3x = self.pop()
1058
+ bcp4y = self.pop()
1059
+ bcp4x = self.pop()
1060
+ bcp3y = self.pop()
1061
+ bcp3x = self.pop()
1062
+ p2y = self.pop()
1063
+ p2x = self.pop()
1064
+ bcp2y = self.pop()
1065
+ bcp2x = self.pop()
1066
+ bcp1y = self.pop()
1067
+ bcp1x = self.pop()
1068
+ rpy = self.pop()
1069
+ rpx = self.pop()
1070
+
1071
+ # call rrcurveto
1072
+ self.push(bcp1x + rpx)
1073
+ self.push(bcp1y + rpy)
1074
+ self.push(bcp2x)
1075
+ self.push(bcp2y)
1076
+ self.push(p2x)
1077
+ self.push(p2y)
1078
+ self.op_rrcurveto(None)
1079
+
1080
+ # call rrcurveto
1081
+ self.push(bcp3x)
1082
+ self.push(bcp3y)
1083
+ self.push(bcp4x)
1084
+ self.push(bcp4y)
1085
+ self.push(p3x)
1086
+ self.push(p3y)
1087
+ self.op_rrcurveto(None)
1088
+
1089
+ # Push back final coords so subr 0 can find them
1090
+ self.push(finalx)
1091
+ self.push(finaly)
1092
+
1093
+ def op_dotsection(self, index):
1094
+ self.popall() # XXX
1095
+
1096
+ def op_hstem3(self, index):
1097
+ self.popall() # XXX
1098
+
1099
+ def op_seac(self, index):
1100
+ "asb adx ady bchar achar seac"
1101
+ from fontTools.encodings.StandardEncoding import StandardEncoding
1102
+
1103
+ asb, adx, ady, bchar, achar = self.popall()
1104
+ baseGlyph = StandardEncoding[bchar]
1105
+ self.pen.addComponent(baseGlyph, (1, 0, 0, 1, 0, 0))
1106
+ accentGlyph = StandardEncoding[achar]
1107
+ adx = adx + self.sbx - asb # seac weirdness
1108
+ self.pen.addComponent(accentGlyph, (1, 0, 0, 1, adx, ady))
1109
+
1110
+ def op_vstem3(self, index):
1111
+ self.popall() # XXX
1112
+
1113
+
1114
+ class T2CharString(object):
1115
+ operandEncoding = t2OperandEncoding
1116
+ operators, opcodes = buildOperatorDict(t2Operators)
1117
+ decompilerClass = SimpleT2Decompiler
1118
+ outlineExtractor = T2OutlineExtractor
1119
+
1120
+ def __init__(self, bytecode=None, program=None, private=None, globalSubrs=None):
1121
+ if program is None:
1122
+ program = []
1123
+ self.bytecode = bytecode
1124
+ self.program = program
1125
+ self.private = private
1126
+ self.globalSubrs = globalSubrs if globalSubrs is not None else []
1127
+ self._cur_vsindex = None
1128
+
1129
+ def getNumRegions(self, vsindex=None):
1130
+ pd = self.private
1131
+ assert pd is not None
1132
+ if vsindex is not None:
1133
+ self._cur_vsindex = vsindex
1134
+ elif self._cur_vsindex is None:
1135
+ self._cur_vsindex = pd.vsindex if hasattr(pd, "vsindex") else 0
1136
+ return pd.getNumRegions(self._cur_vsindex)
1137
+
1138
+ def __repr__(self):
1139
+ if self.bytecode is None:
1140
+ return "<%s (source) at %x>" % (self.__class__.__name__, id(self))
1141
+ else:
1142
+ return "<%s (bytecode) at %x>" % (self.__class__.__name__, id(self))
1143
+
1144
+ def getIntEncoder(self):
1145
+ return encodeIntT2
1146
+
1147
+ def getFixedEncoder(self):
1148
+ return encodeFixed
1149
+
1150
+ def decompile(self):
1151
+ if not self.needsDecompilation():
1152
+ return
1153
+ subrs = getattr(self.private, "Subrs", [])
1154
+ decompiler = self.decompilerClass(subrs, self.globalSubrs, self.private)
1155
+ decompiler.execute(self)
1156
+
1157
+ def draw(self, pen, blender=None):
1158
+ subrs = getattr(self.private, "Subrs", [])
1159
+ extractor = self.outlineExtractor(
1160
+ pen,
1161
+ subrs,
1162
+ self.globalSubrs,
1163
+ self.private.nominalWidthX,
1164
+ self.private.defaultWidthX,
1165
+ self.private,
1166
+ blender,
1167
+ )
1168
+ extractor.execute(self)
1169
+ self.width = extractor.width
1170
+
1171
+ def calcBounds(self, glyphSet):
1172
+ boundsPen = BoundsPen(glyphSet)
1173
+ self.draw(boundsPen)
1174
+ return boundsPen.bounds
1175
+
1176
+ def compile(self, isCFF2=False):
1177
+ if self.bytecode is not None:
1178
+ return
1179
+ opcodes = self.opcodes
1180
+ program = self.program
1181
+
1182
+ if isCFF2:
1183
+ # If present, remove return and endchar operators.
1184
+ if program and program[-1] in ("return", "endchar"):
1185
+ program = program[:-1]
1186
+ elif program and not isinstance(program[-1], str):
1187
+ raise CharStringCompileError(
1188
+ "T2CharString or Subr has items on the stack after last operator."
1189
+ )
1190
+
1191
+ bytecode = []
1192
+ encodeInt = self.getIntEncoder()
1193
+ encodeFixed = self.getFixedEncoder()
1194
+ i = 0
1195
+ end = len(program)
1196
+ while i < end:
1197
+ token = program[i]
1198
+ i = i + 1
1199
+ if isinstance(token, str):
1200
+ try:
1201
+ bytecode.extend(bytechr(b) for b in opcodes[token])
1202
+ except KeyError:
1203
+ raise CharStringCompileError("illegal operator: %s" % token)
1204
+ if token in ("hintmask", "cntrmask"):
1205
+ bytecode.append(program[i]) # hint mask
1206
+ i = i + 1
1207
+ elif isinstance(token, int):
1208
+ bytecode.append(encodeInt(token))
1209
+ elif isinstance(token, float):
1210
+ bytecode.append(encodeFixed(token))
1211
+ else:
1212
+ assert 0, "unsupported type: %s" % type(token)
1213
+ try:
1214
+ bytecode = bytesjoin(bytecode)
1215
+ except TypeError:
1216
+ log.error(bytecode)
1217
+ raise
1218
+ self.setBytecode(bytecode)
1219
+
1220
+ def needsDecompilation(self):
1221
+ return self.bytecode is not None
1222
+
1223
+ def setProgram(self, program):
1224
+ self.program = program
1225
+ self.bytecode = None
1226
+
1227
+ def setBytecode(self, bytecode):
1228
+ self.bytecode = bytecode
1229
+ self.program = None
1230
+
1231
+ def getToken(self, index, len=len, byteord=byteord, isinstance=isinstance):
1232
+ if self.bytecode is not None:
1233
+ if index >= len(self.bytecode):
1234
+ return None, 0, 0
1235
+ b0 = byteord(self.bytecode[index])
1236
+ index = index + 1
1237
+ handler = self.operandEncoding[b0]
1238
+ token, index = handler(self, b0, self.bytecode, index)
1239
+ else:
1240
+ if index >= len(self.program):
1241
+ return None, 0, 0
1242
+ token = self.program[index]
1243
+ index = index + 1
1244
+ isOperator = isinstance(token, str)
1245
+ return token, isOperator, index
1246
+
1247
+ def getBytes(self, index, nBytes):
1248
+ if self.bytecode is not None:
1249
+ newIndex = index + nBytes
1250
+ bytes = self.bytecode[index:newIndex]
1251
+ index = newIndex
1252
+ else:
1253
+ bytes = self.program[index]
1254
+ index = index + 1
1255
+ assert len(bytes) == nBytes
1256
+ return bytes, index
1257
+
1258
+ def handle_operator(self, operator):
1259
+ return operator
1260
+
1261
+ def toXML(self, xmlWriter, ttFont=None):
1262
+ from fontTools.misc.textTools import num2binary
1263
+
1264
+ if self.bytecode is not None:
1265
+ xmlWriter.dumphex(self.bytecode)
1266
+ else:
1267
+ index = 0
1268
+ args = []
1269
+ while True:
1270
+ token, isOperator, index = self.getToken(index)
1271
+ if token is None:
1272
+ break
1273
+ if isOperator:
1274
+ if token in ("hintmask", "cntrmask"):
1275
+ hintMask, isOperator, index = self.getToken(index)
1276
+ bits = []
1277
+ for byte in hintMask:
1278
+ bits.append(num2binary(byteord(byte), 8))
1279
+ hintMask = strjoin(bits)
1280
+ line = " ".join(args + [token, hintMask])
1281
+ else:
1282
+ line = " ".join(args + [token])
1283
+ xmlWriter.write(line)
1284
+ xmlWriter.newline()
1285
+ args = []
1286
+ else:
1287
+ if isinstance(token, float):
1288
+ token = floatToFixedToStr(token, precisionBits=16)
1289
+ else:
1290
+ token = str(token)
1291
+ args.append(token)
1292
+ if args:
1293
+ # NOTE: only CFF2 charstrings/subrs can have numeric arguments on
1294
+ # the stack after the last operator. Compiling this would fail if
1295
+ # this is part of CFF 1.0 table.
1296
+ line = " ".join(args)
1297
+ xmlWriter.write(line)
1298
+
1299
+ def fromXML(self, name, attrs, content):
1300
+ from fontTools.misc.textTools import binary2num, readHex
1301
+
1302
+ if attrs.get("raw"):
1303
+ self.setBytecode(readHex(content))
1304
+ return
1305
+ content = strjoin(content)
1306
+ content = content.split()
1307
+ program = []
1308
+ end = len(content)
1309
+ i = 0
1310
+ while i < end:
1311
+ token = content[i]
1312
+ i = i + 1
1313
+ try:
1314
+ token = int(token)
1315
+ except ValueError:
1316
+ try:
1317
+ token = strToFixedToFloat(token, precisionBits=16)
1318
+ except ValueError:
1319
+ program.append(token)
1320
+ if token in ("hintmask", "cntrmask"):
1321
+ mask = content[i]
1322
+ maskBytes = b""
1323
+ for j in range(0, len(mask), 8):
1324
+ maskBytes = maskBytes + bytechr(binary2num(mask[j : j + 8]))
1325
+ program.append(maskBytes)
1326
+ i = i + 1
1327
+ else:
1328
+ program.append(token)
1329
+ else:
1330
+ program.append(token)
1331
+ self.setProgram(program)
1332
+
1333
+
1334
+ class T1CharString(T2CharString):
1335
+ operandEncoding = t1OperandEncoding
1336
+ operators, opcodes = buildOperatorDict(t1Operators)
1337
+
1338
+ def __init__(self, bytecode=None, program=None, subrs=None):
1339
+ super().__init__(bytecode, program)
1340
+ self.subrs = subrs
1341
+
1342
+ def getIntEncoder(self):
1343
+ return encodeIntT1
1344
+
1345
+ def getFixedEncoder(self):
1346
+ def encodeFixed(value):
1347
+ raise TypeError("Type 1 charstrings don't support floating point operands")
1348
+
1349
+ def decompile(self):
1350
+ if self.bytecode is None:
1351
+ return
1352
+ program = []
1353
+ index = 0
1354
+ while True:
1355
+ token, isOperator, index = self.getToken(index)
1356
+ if token is None:
1357
+ break
1358
+ program.append(token)
1359
+ self.setProgram(program)
1360
+
1361
+ def draw(self, pen):
1362
+ extractor = T1OutlineExtractor(pen, self.subrs)
1363
+ extractor.execute(self)
1364
+ self.width = extractor.width
1365
+
1366
+
1367
+ class DictDecompiler(object):
1368
+ operandEncoding = cffDictOperandEncoding
1369
+
1370
+ def __init__(self, strings, parent=None):
1371
+ self.stack = []
1372
+ self.strings = strings
1373
+ self.dict = {}
1374
+ self.parent = parent
1375
+
1376
+ def getDict(self):
1377
+ assert len(self.stack) == 0, "non-empty stack"
1378
+ return self.dict
1379
+
1380
+ def decompile(self, data):
1381
+ index = 0
1382
+ lenData = len(data)
1383
+ push = self.stack.append
1384
+ while index < lenData:
1385
+ b0 = byteord(data[index])
1386
+ index = index + 1
1387
+ handler = self.operandEncoding[b0]
1388
+ value, index = handler(self, b0, data, index)
1389
+ if value is not None:
1390
+ push(value)
1391
+
1392
+ def pop(self):
1393
+ value = self.stack[-1]
1394
+ del self.stack[-1]
1395
+ return value
1396
+
1397
+ def popall(self):
1398
+ args = self.stack[:]
1399
+ del self.stack[:]
1400
+ return args
1401
+
1402
+ def handle_operator(self, operator):
1403
+ operator, argType = operator
1404
+ if isinstance(argType, tuple):
1405
+ value = ()
1406
+ for i in range(len(argType) - 1, -1, -1):
1407
+ arg = argType[i]
1408
+ arghandler = getattr(self, "arg_" + arg)
1409
+ value = (arghandler(operator),) + value
1410
+ else:
1411
+ arghandler = getattr(self, "arg_" + argType)
1412
+ value = arghandler(operator)
1413
+ if operator == "blend":
1414
+ self.stack.extend(value)
1415
+ else:
1416
+ self.dict[operator] = value
1417
+
1418
+ def arg_number(self, name):
1419
+ if isinstance(self.stack[0], list):
1420
+ out = self.arg_blend_number(self.stack)
1421
+ else:
1422
+ out = self.pop()
1423
+ return out
1424
+
1425
+ def arg_blend_number(self, name):
1426
+ out = []
1427
+ blendArgs = self.pop()
1428
+ numMasters = len(blendArgs)
1429
+ out.append(blendArgs)
1430
+ out.append("blend")
1431
+ dummy = self.popall()
1432
+ return blendArgs
1433
+
1434
+ def arg_SID(self, name):
1435
+ return self.strings[self.pop()]
1436
+
1437
+ def arg_array(self, name):
1438
+ return self.popall()
1439
+
1440
+ def arg_blendList(self, name):
1441
+ """
1442
+ There may be non-blend args at the top of the stack. We first calculate
1443
+ where the blend args start in the stack. These are the last
1444
+ numMasters*numBlends) +1 args.
1445
+ The blend args starts with numMasters relative coordinate values, the BlueValues in the list from the default master font. This is followed by
1446
+ numBlends list of values. Each of value in one of these lists is the
1447
+ Variable Font delta for the matching region.
1448
+
1449
+ We re-arrange this to be a list of numMaster entries. Each entry starts with the corresponding default font relative value, and is followed by
1450
+ the delta values. We then convert the default values, the first item in each entry, to an absolute value.
1451
+ """
1452
+ vsindex = self.dict.get("vsindex", 0)
1453
+ numMasters = (
1454
+ self.parent.getNumRegions(vsindex) + 1
1455
+ ) # only a PrivateDict has blended ops.
1456
+ numBlends = self.pop()
1457
+ args = self.popall()
1458
+ numArgs = len(args)
1459
+ # The spec says that there should be no non-blended Blue Values,.
1460
+ assert numArgs == numMasters * numBlends
1461
+ value = [None] * numBlends
1462
+ numDeltas = numMasters - 1
1463
+ i = 0
1464
+ prevVal = 0
1465
+ while i < numBlends:
1466
+ newVal = args[i] + prevVal
1467
+ prevVal = newVal
1468
+ masterOffset = numBlends + (i * numDeltas)
1469
+ blendList = [newVal] + args[masterOffset : masterOffset + numDeltas]
1470
+ value[i] = blendList
1471
+ i += 1
1472
+ return value
1473
+
1474
+ def arg_delta(self, name):
1475
+ valueList = self.popall()
1476
+ out = []
1477
+ if valueList and isinstance(valueList[0], list):
1478
+ # arg_blendList() has already converted these to absolute values.
1479
+ out = valueList
1480
+ else:
1481
+ current = 0
1482
+ for v in valueList:
1483
+ current = current + v
1484
+ out.append(current)
1485
+ return out
1486
+
1487
+
1488
+ def calcSubrBias(subrs):
1489
+ nSubrs = len(subrs)
1490
+ if nSubrs < 1240:
1491
+ bias = 107
1492
+ elif nSubrs < 33900:
1493
+ bias = 1131
1494
+ else:
1495
+ bias = 32768
1496
+ return bias
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/psOperators.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ _accessstrings = {0: "", 1: "readonly", 2: "executeonly", 3: "noaccess"}
2
+
3
+
4
+ class ps_object(object):
5
+ literal = 1
6
+ access = 0
7
+ value = None
8
+
9
+ def __init__(self, value):
10
+ self.value = value
11
+ self.type = self.__class__.__name__[3:] + "type"
12
+
13
+ def __repr__(self):
14
+ return "<%s %s>" % (self.__class__.__name__[3:], repr(self.value))
15
+
16
+
17
+ class ps_operator(ps_object):
18
+ literal = 0
19
+
20
+ def __init__(self, name, function):
21
+ self.name = name
22
+ self.function = function
23
+ self.type = self.__class__.__name__[3:] + "type"
24
+
25
+ def __repr__(self):
26
+ return "<operator %s>" % self.name
27
+
28
+
29
+ class ps_procedure(ps_object):
30
+ literal = 0
31
+
32
+ def __repr__(self):
33
+ return "<procedure>"
34
+
35
+ def __str__(self):
36
+ psstring = "{"
37
+ for i in range(len(self.value)):
38
+ if i:
39
+ psstring = psstring + " " + str(self.value[i])
40
+ else:
41
+ psstring = psstring + str(self.value[i])
42
+ return psstring + "}"
43
+
44
+
45
+ class ps_name(ps_object):
46
+ literal = 0
47
+
48
+ def __str__(self):
49
+ if self.literal:
50
+ return "/" + self.value
51
+ else:
52
+ return self.value
53
+
54
+
55
+ class ps_literal(ps_object):
56
+ def __str__(self):
57
+ return "/" + self.value
58
+
59
+
60
+ class ps_array(ps_object):
61
+ def __str__(self):
62
+ psstring = "["
63
+ for i in range(len(self.value)):
64
+ item = self.value[i]
65
+ access = _accessstrings[item.access]
66
+ if access:
67
+ access = " " + access
68
+ if i:
69
+ psstring = psstring + " " + str(item) + access
70
+ else:
71
+ psstring = psstring + str(item) + access
72
+ return psstring + "]"
73
+
74
+ def __repr__(self):
75
+ return "<array>"
76
+
77
+
78
+ _type1_pre_eexec_order = [
79
+ "FontInfo",
80
+ "FontName",
81
+ "Encoding",
82
+ "PaintType",
83
+ "FontType",
84
+ "FontMatrix",
85
+ "FontBBox",
86
+ "UniqueID",
87
+ "Metrics",
88
+ "StrokeWidth",
89
+ ]
90
+
91
+ _type1_fontinfo_order = [
92
+ "version",
93
+ "Notice",
94
+ "FullName",
95
+ "FamilyName",
96
+ "Weight",
97
+ "ItalicAngle",
98
+ "isFixedPitch",
99
+ "UnderlinePosition",
100
+ "UnderlineThickness",
101
+ ]
102
+
103
+ _type1_post_eexec_order = ["Private", "CharStrings", "FID"]
104
+
105
+
106
+ def _type1_item_repr(key, value):
107
+ psstring = ""
108
+ access = _accessstrings[value.access]
109
+ if access:
110
+ access = access + " "
111
+ if key == "CharStrings":
112
+ psstring = psstring + "/%s %s def\n" % (
113
+ key,
114
+ _type1_CharString_repr(value.value),
115
+ )
116
+ elif key == "Encoding":
117
+ psstring = psstring + _type1_Encoding_repr(value, access)
118
+ else:
119
+ psstring = psstring + "/%s %s %sdef\n" % (str(key), str(value), access)
120
+ return psstring
121
+
122
+
123
+ def _type1_Encoding_repr(encoding, access):
124
+ encoding = encoding.value
125
+ psstring = "/Encoding 256 array\n0 1 255 {1 index exch /.notdef put} for\n"
126
+ for i in range(256):
127
+ name = encoding[i].value
128
+ if name != ".notdef":
129
+ psstring = psstring + "dup %d /%s put\n" % (i, name)
130
+ return psstring + access + "def\n"
131
+
132
+
133
+ def _type1_CharString_repr(charstrings):
134
+ items = sorted(charstrings.items())
135
+ return "xxx"
136
+
137
+
138
+ class ps_font(ps_object):
139
+ def __str__(self):
140
+ psstring = "%d dict dup begin\n" % len(self.value)
141
+ for key in _type1_pre_eexec_order:
142
+ try:
143
+ value = self.value[key]
144
+ except KeyError:
145
+ pass
146
+ else:
147
+ psstring = psstring + _type1_item_repr(key, value)
148
+ items = sorted(self.value.items())
149
+ for key, value in items:
150
+ if key not in _type1_pre_eexec_order + _type1_post_eexec_order:
151
+ psstring = psstring + _type1_item_repr(key, value)
152
+ psstring = psstring + "currentdict end\ncurrentfile eexec\ndup "
153
+ for key in _type1_post_eexec_order:
154
+ try:
155
+ value = self.value[key]
156
+ except KeyError:
157
+ pass
158
+ else:
159
+ psstring = psstring + _type1_item_repr(key, value)
160
+ return (
161
+ psstring
162
+ + "dup/FontName get exch definefont pop\nmark currentfile closefile\n"
163
+ + 8 * (64 * "0" + "\n")
164
+ + "cleartomark"
165
+ + "\n"
166
+ )
167
+
168
+ def __repr__(self):
169
+ return "<font>"
170
+
171
+
172
+ class ps_file(ps_object):
173
+ pass
174
+
175
+
176
+ class ps_dict(ps_object):
177
+ def __str__(self):
178
+ psstring = "%d dict dup begin\n" % len(self.value)
179
+ items = sorted(self.value.items())
180
+ for key, value in items:
181
+ access = _accessstrings[value.access]
182
+ if access:
183
+ access = access + " "
184
+ psstring = psstring + "/%s %s %sdef\n" % (str(key), str(value), access)
185
+ return psstring + "end "
186
+
187
+ def __repr__(self):
188
+ return "<dict>"
189
+
190
+
191
+ class ps_mark(ps_object):
192
+ def __init__(self):
193
+ self.value = "mark"
194
+ self.type = self.__class__.__name__[3:] + "type"
195
+
196
+
197
+ class ps_procmark(ps_object):
198
+ def __init__(self):
199
+ self.value = "procmark"
200
+ self.type = self.__class__.__name__[3:] + "type"
201
+
202
+
203
+ class ps_null(ps_object):
204
+ def __init__(self):
205
+ self.type = self.__class__.__name__[3:] + "type"
206
+
207
+
208
+ class ps_boolean(ps_object):
209
+ def __str__(self):
210
+ if self.value:
211
+ return "true"
212
+ else:
213
+ return "false"
214
+
215
+
216
+ class ps_string(ps_object):
217
+ def __str__(self):
218
+ return "(%s)" % repr(self.value)[1:-1]
219
+
220
+
221
+ class ps_integer(ps_object):
222
+ def __str__(self):
223
+ return repr(self.value)
224
+
225
+
226
+ class ps_real(ps_object):
227
+ def __str__(self):
228
+ return repr(self.value)
229
+
230
+
231
+ class PSOperators(object):
232
+ def ps_def(self):
233
+ obj = self.pop()
234
+ name = self.pop()
235
+ self.dictstack[-1][name.value] = obj
236
+
237
+ def ps_bind(self):
238
+ proc = self.pop("proceduretype")
239
+ self.proc_bind(proc)
240
+ self.push(proc)
241
+
242
+ def proc_bind(self, proc):
243
+ for i in range(len(proc.value)):
244
+ item = proc.value[i]
245
+ if item.type == "proceduretype":
246
+ self.proc_bind(item)
247
+ else:
248
+ if not item.literal:
249
+ try:
250
+ obj = self.resolve_name(item.value)
251
+ except:
252
+ pass
253
+ else:
254
+ if obj.type == "operatortype":
255
+ proc.value[i] = obj
256
+
257
+ def ps_exch(self):
258
+ if len(self.stack) < 2:
259
+ raise RuntimeError("stack underflow")
260
+ obj1 = self.pop()
261
+ obj2 = self.pop()
262
+ self.push(obj1)
263
+ self.push(obj2)
264
+
265
+ def ps_dup(self):
266
+ if not self.stack:
267
+ raise RuntimeError("stack underflow")
268
+ self.push(self.stack[-1])
269
+
270
+ def ps_exec(self):
271
+ obj = self.pop()
272
+ if obj.type == "proceduretype":
273
+ self.call_procedure(obj)
274
+ else:
275
+ self.handle_object(obj)
276
+
277
+ def ps_count(self):
278
+ self.push(ps_integer(len(self.stack)))
279
+
280
+ def ps_eq(self):
281
+ any1 = self.pop()
282
+ any2 = self.pop()
283
+ self.push(ps_boolean(any1.value == any2.value))
284
+
285
+ def ps_ne(self):
286
+ any1 = self.pop()
287
+ any2 = self.pop()
288
+ self.push(ps_boolean(any1.value != any2.value))
289
+
290
+ def ps_cvx(self):
291
+ obj = self.pop()
292
+ obj.literal = 0
293
+ self.push(obj)
294
+
295
+ def ps_matrix(self):
296
+ matrix = [
297
+ ps_real(1.0),
298
+ ps_integer(0),
299
+ ps_integer(0),
300
+ ps_real(1.0),
301
+ ps_integer(0),
302
+ ps_integer(0),
303
+ ]
304
+ self.push(ps_array(matrix))
305
+
306
+ def ps_string(self):
307
+ num = self.pop("integertype").value
308
+ self.push(ps_string("\0" * num))
309
+
310
+ def ps_type(self):
311
+ obj = self.pop()
312
+ self.push(ps_string(obj.type))
313
+
314
+ def ps_store(self):
315
+ value = self.pop()
316
+ key = self.pop()
317
+ name = key.value
318
+ for i in range(len(self.dictstack) - 1, -1, -1):
319
+ if name in self.dictstack[i]:
320
+ self.dictstack[i][name] = value
321
+ break
322
+ self.dictstack[-1][name] = value
323
+
324
+ def ps_where(self):
325
+ name = self.pop()
326
+ # XXX
327
+ self.push(ps_boolean(0))
328
+
329
+ def ps_systemdict(self):
330
+ self.push(ps_dict(self.dictstack[0]))
331
+
332
+ def ps_userdict(self):
333
+ self.push(ps_dict(self.dictstack[1]))
334
+
335
+ def ps_currentdict(self):
336
+ self.push(ps_dict(self.dictstack[-1]))
337
+
338
+ def ps_currentfile(self):
339
+ self.push(ps_file(self.tokenizer))
340
+
341
+ def ps_eexec(self):
342
+ f = self.pop("filetype").value
343
+ f.starteexec()
344
+
345
+ def ps_closefile(self):
346
+ f = self.pop("filetype").value
347
+ f.skipwhite()
348
+ f.stopeexec()
349
+
350
+ def ps_cleartomark(self):
351
+ obj = self.pop()
352
+ while obj != self.mark:
353
+ obj = self.pop()
354
+
355
+ def ps_readstring(self, ps_boolean=ps_boolean, len=len):
356
+ s = self.pop("stringtype")
357
+ oldstr = s.value
358
+ f = self.pop("filetype")
359
+ # pad = file.value.read(1)
360
+ # for StringIO, this is faster
361
+ f.value.pos = f.value.pos + 1
362
+ newstr = f.value.read(len(oldstr))
363
+ s.value = newstr
364
+ self.push(s)
365
+ self.push(ps_boolean(len(oldstr) == len(newstr)))
366
+
367
+ def ps_known(self):
368
+ key = self.pop()
369
+ d = self.pop("dicttype", "fonttype")
370
+ self.push(ps_boolean(key.value in d.value))
371
+
372
+ def ps_if(self):
373
+ proc = self.pop("proceduretype")
374
+ if self.pop("booleantype").value:
375
+ self.call_procedure(proc)
376
+
377
+ def ps_ifelse(self):
378
+ proc2 = self.pop("proceduretype")
379
+ proc1 = self.pop("proceduretype")
380
+ if self.pop("booleantype").value:
381
+ self.call_procedure(proc1)
382
+ else:
383
+ self.call_procedure(proc2)
384
+
385
+ def ps_readonly(self):
386
+ obj = self.pop()
387
+ if obj.access < 1:
388
+ obj.access = 1
389
+ self.push(obj)
390
+
391
+ def ps_executeonly(self):
392
+ obj = self.pop()
393
+ if obj.access < 2:
394
+ obj.access = 2
395
+ self.push(obj)
396
+
397
+ def ps_noaccess(self):
398
+ obj = self.pop()
399
+ if obj.access < 3:
400
+ obj.access = 3
401
+ self.push(obj)
402
+
403
+ def ps_not(self):
404
+ obj = self.pop("booleantype", "integertype")
405
+ if obj.type == "booleantype":
406
+ self.push(ps_boolean(not obj.value))
407
+ else:
408
+ self.push(ps_integer(~obj.value))
409
+
410
+ def ps_print(self):
411
+ str = self.pop("stringtype")
412
+ print("PS output --->", str.value)
413
+
414
+ def ps_anchorsearch(self):
415
+ seek = self.pop("stringtype")
416
+ s = self.pop("stringtype")
417
+ seeklen = len(seek.value)
418
+ if s.value[:seeklen] == seek.value:
419
+ self.push(ps_string(s.value[seeklen:]))
420
+ self.push(seek)
421
+ self.push(ps_boolean(1))
422
+ else:
423
+ self.push(s)
424
+ self.push(ps_boolean(0))
425
+
426
+ def ps_array(self):
427
+ num = self.pop("integertype")
428
+ array = ps_array([None] * num.value)
429
+ self.push(array)
430
+
431
+ def ps_astore(self):
432
+ array = self.pop("arraytype")
433
+ for i in range(len(array.value) - 1, -1, -1):
434
+ array.value[i] = self.pop()
435
+ self.push(array)
436
+
437
+ def ps_load(self):
438
+ name = self.pop()
439
+ self.push(self.resolve_name(name.value))
440
+
441
+ def ps_put(self):
442
+ obj1 = self.pop()
443
+ obj2 = self.pop()
444
+ obj3 = self.pop("arraytype", "dicttype", "stringtype", "proceduretype")
445
+ tp = obj3.type
446
+ if tp == "arraytype" or tp == "proceduretype":
447
+ obj3.value[obj2.value] = obj1
448
+ elif tp == "dicttype":
449
+ obj3.value[obj2.value] = obj1
450
+ elif tp == "stringtype":
451
+ index = obj2.value
452
+ obj3.value = obj3.value[:index] + chr(obj1.value) + obj3.value[index + 1 :]
453
+
454
+ def ps_get(self):
455
+ obj1 = self.pop()
456
+ if obj1.value == "Encoding":
457
+ pass
458
+ obj2 = self.pop(
459
+ "arraytype", "dicttype", "stringtype", "proceduretype", "fonttype"
460
+ )
461
+ tp = obj2.type
462
+ if tp in ("arraytype", "proceduretype"):
463
+ self.push(obj2.value[obj1.value])
464
+ elif tp in ("dicttype", "fonttype"):
465
+ self.push(obj2.value[obj1.value])
466
+ elif tp == "stringtype":
467
+ self.push(ps_integer(ord(obj2.value[obj1.value])))
468
+ else:
469
+ assert False, "shouldn't get here"
470
+
471
+ def ps_getinterval(self):
472
+ obj1 = self.pop("integertype")
473
+ obj2 = self.pop("integertype")
474
+ obj3 = self.pop("arraytype", "stringtype")
475
+ tp = obj3.type
476
+ if tp == "arraytype":
477
+ self.push(ps_array(obj3.value[obj2.value : obj2.value + obj1.value]))
478
+ elif tp == "stringtype":
479
+ self.push(ps_string(obj3.value[obj2.value : obj2.value + obj1.value]))
480
+
481
+ def ps_putinterval(self):
482
+ obj1 = self.pop("arraytype", "stringtype")
483
+ obj2 = self.pop("integertype")
484
+ obj3 = self.pop("arraytype", "stringtype")
485
+ tp = obj3.type
486
+ if tp == "arraytype":
487
+ obj3.value[obj2.value : obj2.value + len(obj1.value)] = obj1.value
488
+ elif tp == "stringtype":
489
+ newstr = obj3.value[: obj2.value]
490
+ newstr = newstr + obj1.value
491
+ newstr = newstr + obj3.value[obj2.value + len(obj1.value) :]
492
+ obj3.value = newstr
493
+
494
+ def ps_cvn(self):
495
+ self.push(ps_name(self.pop("stringtype").value))
496
+
497
+ def ps_index(self):
498
+ n = self.pop("integertype").value
499
+ if n < 0:
500
+ raise RuntimeError("index may not be negative")
501
+ self.push(self.stack[-1 - n])
502
+
503
+ def ps_for(self):
504
+ proc = self.pop("proceduretype")
505
+ limit = self.pop("integertype", "realtype").value
506
+ increment = self.pop("integertype", "realtype").value
507
+ i = self.pop("integertype", "realtype").value
508
+ while 1:
509
+ if increment > 0:
510
+ if i > limit:
511
+ break
512
+ else:
513
+ if i < limit:
514
+ break
515
+ if type(i) == type(0.0):
516
+ self.push(ps_real(i))
517
+ else:
518
+ self.push(ps_integer(i))
519
+ self.call_procedure(proc)
520
+ i = i + increment
521
+
522
+ def ps_forall(self):
523
+ proc = self.pop("proceduretype")
524
+ obj = self.pop("arraytype", "stringtype", "dicttype")
525
+ tp = obj.type
526
+ if tp == "arraytype":
527
+ for item in obj.value:
528
+ self.push(item)
529
+ self.call_procedure(proc)
530
+ elif tp == "stringtype":
531
+ for item in obj.value:
532
+ self.push(ps_integer(ord(item)))
533
+ self.call_procedure(proc)
534
+ elif tp == "dicttype":
535
+ for key, value in obj.value.items():
536
+ self.push(ps_name(key))
537
+ self.push(value)
538
+ self.call_procedure(proc)
539
+
540
+ def ps_definefont(self):
541
+ font = self.pop("dicttype")
542
+ name = self.pop()
543
+ font = ps_font(font.value)
544
+ self.dictstack[0]["FontDirectory"].value[name.value] = font
545
+ self.push(font)
546
+
547
+ def ps_findfont(self):
548
+ name = self.pop()
549
+ font = self.dictstack[0]["FontDirectory"].value[name.value]
550
+ self.push(font)
551
+
552
+ def ps_pop(self):
553
+ self.pop()
554
+
555
+ def ps_dict(self):
556
+ self.pop("integertype")
557
+ self.push(ps_dict({}))
558
+
559
+ def ps_begin(self):
560
+ self.dictstack.append(self.pop("dicttype").value)
561
+
562
+ def ps_end(self):
563
+ if len(self.dictstack) > 2:
564
+ del self.dictstack[-1]
565
+ else:
566
+ raise RuntimeError("dictstack underflow")
567
+
568
+
569
+ notdef = ".notdef"
570
+ from fontTools.encodings.StandardEncoding import StandardEncoding
571
+
572
+ ps_StandardEncoding = list(map(ps_name, StandardEncoding))
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/py23.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Python 2/3 compat layer leftovers."""
2
+
3
+ import decimal as _decimal
4
+ import math as _math
5
+ import warnings
6
+ from contextlib import redirect_stderr, redirect_stdout
7
+ from io import BytesIO
8
+ from io import StringIO as UnicodeIO
9
+ from types import SimpleNamespace
10
+
11
+ from .textTools import Tag, bytechr, byteord, bytesjoin, strjoin, tobytes, tostr
12
+
13
+ warnings.warn(
14
+ "The py23 module has been deprecated and will be removed in a future release. "
15
+ "Please update your code.",
16
+ DeprecationWarning,
17
+ )
18
+
19
+ __all__ = [
20
+ "basestring",
21
+ "bytechr",
22
+ "byteord",
23
+ "BytesIO",
24
+ "bytesjoin",
25
+ "open",
26
+ "Py23Error",
27
+ "range",
28
+ "RecursionError",
29
+ "round",
30
+ "SimpleNamespace",
31
+ "StringIO",
32
+ "strjoin",
33
+ "Tag",
34
+ "tobytes",
35
+ "tostr",
36
+ "tounicode",
37
+ "unichr",
38
+ "unicode",
39
+ "UnicodeIO",
40
+ "xrange",
41
+ "zip",
42
+ ]
43
+
44
+
45
+ class Py23Error(NotImplementedError):
46
+ pass
47
+
48
+
49
+ RecursionError = RecursionError
50
+ StringIO = UnicodeIO
51
+
52
+ basestring = str
53
+ isclose = _math.isclose
54
+ isfinite = _math.isfinite
55
+ open = open
56
+ range = range
57
+ round = round3 = round
58
+ unichr = chr
59
+ unicode = str
60
+ zip = zip
61
+
62
+ tounicode = tostr
63
+
64
+
65
+ def xrange(*args, **kwargs):
66
+ raise Py23Error("'xrange' is not defined. Use 'range' instead.")
67
+
68
+
69
+ def round2(number, ndigits=None):
70
+ """
71
+ Implementation of Python 2 built-in round() function.
72
+ Rounds a number to a given precision in decimal digits (default
73
+ 0 digits). The result is a floating point number. Values are rounded
74
+ to the closest multiple of 10 to the power minus ndigits; if two
75
+ multiples are equally close, rounding is done away from 0.
76
+ ndigits may be negative.
77
+ See Python 2 documentation:
78
+ https://docs.python.org/2/library/functions.html?highlight=round#round
79
+ """
80
+ if ndigits is None:
81
+ ndigits = 0
82
+
83
+ if ndigits < 0:
84
+ exponent = 10 ** (-ndigits)
85
+ quotient, remainder = divmod(number, exponent)
86
+ if remainder >= exponent // 2 and number >= 0:
87
+ quotient += 1
88
+ return float(quotient * exponent)
89
+ else:
90
+ exponent = _decimal.Decimal("10") ** (-ndigits)
91
+
92
+ d = _decimal.Decimal.from_float(number).quantize(
93
+ exponent, rounding=_decimal.ROUND_HALF_UP
94
+ )
95
+
96
+ return float(d)
infer_4_37_2/lib/python3.10/site-packages/fontTools/misc/roundTools.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Various round-to-integer helpers.
3
+ """
4
+
5
+ import math
6
+ import functools
7
+ import logging
8
+
9
+ log = logging.getLogger(__name__)
10
+
11
+ __all__ = [
12
+ "noRound",
13
+ "otRound",
14
+ "maybeRound",
15
+ "roundFunc",
16
+ "nearestMultipleShortestRepr",
17
+ ]
18
+
19
+
20
+ def noRound(value):
21
+ return value
22
+
23
+
24
+ def otRound(value):
25
+ """Round float value to nearest integer towards ``+Infinity``.
26
+
27
+ The OpenType spec (in the section on `"normalization" of OpenType Font Variations <https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#coordinate-scales-and-normalization>`_)
28
+ defines the required method for converting floating point values to
29
+ fixed-point. In particular it specifies the following rounding strategy:
30
+
31
+ for fractional values of 0.5 and higher, take the next higher integer;
32
+ for other fractional values, truncate.
33
+
34
+ This function rounds the floating-point value according to this strategy
35
+ in preparation for conversion to fixed-point.
36
+
37
+ Args:
38
+ value (float): The input floating-point value.
39
+
40
+ Returns
41
+ float: The rounded value.
42
+ """
43
+ # See this thread for how we ended up with this implementation:
44
+ # https://github.com/fonttools/fonttools/issues/1248#issuecomment-383198166
45
+ return int(math.floor(value + 0.5))
46
+
47
+
48
+ def maybeRound(v, tolerance, round=otRound):
49
+ rounded = round(v)
50
+ return rounded if abs(rounded - v) <= tolerance else v
51
+
52
+
53
+ def roundFunc(tolerance, round=otRound):
54
+ if tolerance < 0:
55
+ raise ValueError("Rounding tolerance must be positive")
56
+
57
+ if tolerance == 0:
58
+ return noRound
59
+
60
+ if tolerance >= 0.5:
61
+ return round
62
+
63
+ return functools.partial(maybeRound, tolerance=tolerance, round=round)
64
+
65
+
66
+ def nearestMultipleShortestRepr(value: float, factor: float) -> str:
67
+ """Round to nearest multiple of factor and return shortest decimal representation.
68
+
69
+ This chooses the float that is closer to a multiple of the given factor while
70
+ having the shortest decimal representation (the least number of fractional decimal
71
+ digits).
72
+
73
+ For example, given the following:
74
+
75
+ >>> nearestMultipleShortestRepr(-0.61883544921875, 1.0/(1<<14))
76
+ '-0.61884'
77
+
78
+ Useful when you need to serialize or print a fixed-point number (or multiples
79
+ thereof, such as F2Dot14 fractions of 180 degrees in COLRv1 PaintRotate) in
80
+ a human-readable form.
81
+
82
+ Args:
83
+ value (value): The value to be rounded and serialized.
84
+ factor (float): The value which the result is a close multiple of.
85
+
86
+ Returns:
87
+ str: A compact string representation of the value.
88
+ """
89
+ if not value:
90
+ return "0.0"
91
+
92
+ value = otRound(value / factor) * factor
93
+ eps = 0.5 * factor
94
+ lo = value - eps
95
+ hi = value + eps
96
+ # If the range of valid choices spans an integer, return the integer.
97
+ if int(lo) != int(hi):
98
+ return str(float(round(value)))
99
+
100
+ fmt = "%.8f"
101
+ lo = fmt % lo
102
+ hi = fmt % hi
103
+ assert len(lo) == len(hi) and lo != hi
104
+ for i in range(len(lo)):
105
+ if lo[i] != hi[i]:
106
+ break
107
+ period = lo.find(".")
108
+ assert period < i
109
+ fmt = "%%.%df" % (i - period)
110
+ return fmt % value