ZTWHHH commited on
Commit
77e7d90
·
verified ·
1 Parent(s): 4e408a0

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. evalkit_tf437/lib/python3.10/site-packages/fontTools/cffLib/CFFToCFF2.py +303 -0
  2. evalkit_tf437/lib/python3.10/site-packages/fontTools/cffLib/__pycache__/transforms.cpython-310.pyc +0 -0
  3. evalkit_tf437/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/__init__.cpython-310.pyc +0 -0
  4. evalkit_tf437/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/builder.cpython-310.pyc +0 -0
  5. evalkit_tf437/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/unbuilder.cpython-310.pyc +0 -0
  6. evalkit_tf437/lib/python3.10/site-packages/fontTools/colorLib/builder.py +664 -0
  7. evalkit_tf437/lib/python3.10/site-packages/fontTools/colorLib/geometry.py +143 -0
  8. evalkit_tf437/lib/python3.10/site-packages/fontTools/designspaceLib/__main__.py +6 -0
  9. evalkit_tf437/lib/python3.10/site-packages/fontTools/designspaceLib/__pycache__/__main__.cpython-310.pyc +0 -0
  10. evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/__pycache__/boundsPen.cpython-310.pyc +0 -0
  11. evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/__pycache__/cu2quPen.cpython-310.pyc +0 -0
  12. evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/__pycache__/momentsPen.cpython-310.pyc +0 -0
  13. evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/__pycache__/reportLabPen.cpython-310.pyc +0 -0
  14. evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/cairoPen.py +26 -0
  15. evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/hashPointPen.py +89 -0
  16. evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/momentsPen.py +882 -0
  17. evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/perimeterPen.py +69 -0
  18. evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/qu2cuPen.py +105 -0
  19. evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/reverseContourPen.py +96 -0
  20. evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/roundingPen.py +130 -0
  21. evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/svgPathPen.py +310 -0
  22. evalkit_tf437/lib/python3.10/site-packages/fontTools/tfmLib.py +460 -0
  23. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__init__.py +26 -0
  24. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/macUtils.cpython-310.pyc +0 -0
  25. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/scaleUpem.cpython-310.pyc +0 -0
  26. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/ttGlyphSet.cpython-310.pyc +0 -0
  27. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/DefaultTable.py +49 -0
  28. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/G__l_o_c.py +84 -0
  29. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/L_T_S_H_.py +48 -0
  30. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/O_S_2f_2.py +745 -0
  31. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F__2.cpython-310.pyc +0 -0
  32. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/C_O_L_R_.cpython-310.pyc +0 -0
  33. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/C_P_A_L_.cpython-310.pyc +0 -0
  34. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/D_S_I_G_.cpython-310.pyc +0 -0
  35. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/E_B_L_C_.cpython-310.pyc +0 -0
  36. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/G_D_E_F_.cpython-310.pyc +0 -0
  37. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/G__l_o_c.cpython-310.pyc +0 -0
  38. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/M_A_T_H_.cpython-310.pyc +0 -0
  39. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/M_E_T_A_.cpython-310.pyc +0 -0
  40. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/O_S_2f_2.cpython-310.pyc +0 -0
  41. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_C_.cpython-310.pyc +0 -0
  42. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_D_.cpython-310.pyc +0 -0
  43. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_P_.cpython-310.pyc +0 -0
  44. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_V_.cpython-310.pyc +0 -0
  45. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__3.cpython-310.pyc +0 -0
  46. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/V_D_M_X_.cpython-310.pyc +0 -0
  47. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/__init__.cpython-310.pyc +0 -0
  48. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/_a_n_k_r.cpython-310.pyc +0 -0
  49. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/_c_i_d_g.cpython-310.pyc +0 -0
  50. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/_c_v_a_r.cpython-310.pyc +0 -0
evalkit_tf437/lib/python3.10/site-packages/fontTools/cffLib/CFFToCFF2.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CFF to CFF2 converter."""
2
+
3
+ from fontTools.ttLib import TTFont, newTable
4
+ from fontTools.misc.cliTools import makeOutputFileName
5
+ from fontTools.misc.psCharStrings import T2WidthExtractor
6
+ from fontTools.cffLib import (
7
+ TopDictIndex,
8
+ FDArrayIndex,
9
+ FontDict,
10
+ buildOrder,
11
+ topDictOperators,
12
+ privateDictOperators,
13
+ topDictOperators2,
14
+ privateDictOperators2,
15
+ )
16
+ from io import BytesIO
17
+ import logging
18
+
19
+ __all__ = ["convertCFFToCFF2", "main"]
20
+
21
+
22
+ log = logging.getLogger("fontTools.cffLib")
23
+
24
+
25
+ class _NominalWidthUsedError(Exception):
26
+ def __add__(self, other):
27
+ raise self
28
+
29
+ def __radd__(self, other):
30
+ raise self
31
+
32
+
33
+ def _convertCFFToCFF2(cff, otFont):
34
+ """Converts this object from CFF format to CFF2 format. This conversion
35
+ is done 'in-place'. The conversion cannot be reversed.
36
+
37
+ This assumes a decompiled CFF table. (i.e. that the object has been
38
+ filled via :meth:`decompile` and e.g. not loaded from XML.)"""
39
+
40
+ # Clean up T2CharStrings
41
+
42
+ topDict = cff.topDictIndex[0]
43
+ fdArray = topDict.FDArray if hasattr(topDict, "FDArray") else None
44
+ charStrings = topDict.CharStrings
45
+ globalSubrs = cff.GlobalSubrs
46
+ localSubrs = (
47
+ [getattr(fd.Private, "Subrs", []) for fd in fdArray]
48
+ if fdArray
49
+ else (
50
+ [topDict.Private.Subrs]
51
+ if hasattr(topDict, "Private") and hasattr(topDict.Private, "Subrs")
52
+ else []
53
+ )
54
+ )
55
+
56
+ for glyphName in charStrings.keys():
57
+ cs, fdIndex = charStrings.getItemAndSelector(glyphName)
58
+ cs.decompile()
59
+
60
+ # Clean up subroutines first
61
+ for subrs in [globalSubrs] + localSubrs:
62
+ for subr in subrs:
63
+ program = subr.program
64
+ i = j = len(program)
65
+ try:
66
+ i = program.index("return")
67
+ except ValueError:
68
+ pass
69
+ try:
70
+ j = program.index("endchar")
71
+ except ValueError:
72
+ pass
73
+ program[min(i, j) :] = []
74
+
75
+ # Clean up glyph charstrings
76
+ removeUnusedSubrs = False
77
+ nominalWidthXError = _NominalWidthUsedError()
78
+ for glyphName in charStrings.keys():
79
+ cs, fdIndex = charStrings.getItemAndSelector(glyphName)
80
+ program = cs.program
81
+
82
+ thisLocalSubrs = (
83
+ localSubrs[fdIndex]
84
+ if fdIndex
85
+ else (
86
+ getattr(topDict.Private, "Subrs", [])
87
+ if hasattr(topDict, "Private")
88
+ else []
89
+ )
90
+ )
91
+
92
+ # Intentionally use custom type for nominalWidthX, such that any
93
+ # CharString that has an explicit width encoded will throw back to us.
94
+ extractor = T2WidthExtractor(
95
+ thisLocalSubrs,
96
+ globalSubrs,
97
+ nominalWidthXError,
98
+ 0,
99
+ )
100
+ try:
101
+ extractor.execute(cs)
102
+ except _NominalWidthUsedError:
103
+ # Program has explicit width. We want to drop it, but can't
104
+ # just pop the first number since it may be a subroutine call.
105
+ # Instead, when seeing that, we embed the subroutine and recurse.
106
+ # If this ever happened, we later prune unused subroutines.
107
+ while program[1] in ["callsubr", "callgsubr"]:
108
+ removeUnusedSubrs = True
109
+ subrNumber = program.pop(0)
110
+ op = program.pop(0)
111
+ bias = extractor.localBias if op == "callsubr" else extractor.globalBias
112
+ subrNumber += bias
113
+ subrSet = thisLocalSubrs if op == "callsubr" else globalSubrs
114
+ subrProgram = subrSet[subrNumber].program
115
+ program[:0] = subrProgram
116
+ # Now pop the actual width
117
+ program.pop(0)
118
+
119
+ if program and program[-1] == "endchar":
120
+ program.pop()
121
+
122
+ if removeUnusedSubrs:
123
+ cff.remove_unused_subroutines()
124
+
125
+ # Upconvert TopDict
126
+
127
+ cff.major = 2
128
+ cff2GetGlyphOrder = cff.otFont.getGlyphOrder
129
+ topDictData = TopDictIndex(None, cff2GetGlyphOrder)
130
+ for item in cff.topDictIndex:
131
+ # Iterate over, such that all are decompiled
132
+ topDictData.append(item)
133
+ cff.topDictIndex = topDictData
134
+ topDict = topDictData[0]
135
+ if hasattr(topDict, "Private"):
136
+ privateDict = topDict.Private
137
+ else:
138
+ privateDict = None
139
+ opOrder = buildOrder(topDictOperators2)
140
+ topDict.order = opOrder
141
+ topDict.cff2GetGlyphOrder = cff2GetGlyphOrder
142
+
143
+ if not hasattr(topDict, "FDArray"):
144
+ fdArray = topDict.FDArray = FDArrayIndex()
145
+ fdArray.strings = None
146
+ fdArray.GlobalSubrs = topDict.GlobalSubrs
147
+ topDict.GlobalSubrs.fdArray = fdArray
148
+ charStrings = topDict.CharStrings
149
+ if charStrings.charStringsAreIndexed:
150
+ charStrings.charStringsIndex.fdArray = fdArray
151
+ else:
152
+ charStrings.fdArray = fdArray
153
+ fontDict = FontDict()
154
+ fontDict.setCFF2(True)
155
+ fdArray.append(fontDict)
156
+ fontDict.Private = privateDict
157
+ privateOpOrder = buildOrder(privateDictOperators2)
158
+ if privateDict is not None:
159
+ for entry in privateDictOperators:
160
+ key = entry[1]
161
+ if key not in privateOpOrder:
162
+ if key in privateDict.rawDict:
163
+ # print "Removing private dict", key
164
+ del privateDict.rawDict[key]
165
+ if hasattr(privateDict, key):
166
+ delattr(privateDict, key)
167
+ # print "Removing privateDict attr", key
168
+ else:
169
+ # clean up the PrivateDicts in the fdArray
170
+ fdArray = topDict.FDArray
171
+ privateOpOrder = buildOrder(privateDictOperators2)
172
+ for fontDict in fdArray:
173
+ fontDict.setCFF2(True)
174
+ for key in list(fontDict.rawDict.keys()):
175
+ if key not in fontDict.order:
176
+ del fontDict.rawDict[key]
177
+ if hasattr(fontDict, key):
178
+ delattr(fontDict, key)
179
+
180
+ privateDict = fontDict.Private
181
+ for entry in privateDictOperators:
182
+ key = entry[1]
183
+ if key not in privateOpOrder:
184
+ if key in list(privateDict.rawDict.keys()):
185
+ # print "Removing private dict", key
186
+ del privateDict.rawDict[key]
187
+ if hasattr(privateDict, key):
188
+ delattr(privateDict, key)
189
+ # print "Removing privateDict attr", key
190
+
191
+ # Now delete up the deprecated topDict operators from CFF 1.0
192
+ for entry in topDictOperators:
193
+ key = entry[1]
194
+ # We seem to need to keep the charset operator for now,
195
+ # or we fail to compile with some fonts, like AdditionFont.otf.
196
+ # I don't know which kind of CFF font those are. But keeping
197
+ # charset seems to work. It will be removed when we save and
198
+ # read the font again.
199
+ #
200
+ # AdditionFont.otf has <Encoding name="StandardEncoding"/>.
201
+ if key == "charset":
202
+ continue
203
+ if key not in opOrder:
204
+ if key in topDict.rawDict:
205
+ del topDict.rawDict[key]
206
+ if hasattr(topDict, key):
207
+ delattr(topDict, key)
208
+
209
+ # TODO(behdad): What does the following comment even mean? Both CFF and CFF2
210
+ # use the same T2Charstring class. I *think* what it means is that the CharStrings
211
+ # were loaded for CFF1, and we need to reload them for CFF2 to set varstore, etc
212
+ # on them. At least that's what I understand. It's probably safe to remove this
213
+ # and just set vstore where needed.
214
+ #
215
+ # See comment above about charset as well.
216
+
217
+ # At this point, the Subrs and Charstrings are all still T2Charstring class
218
+ # easiest to fix this by compiling, then decompiling again
219
+ file = BytesIO()
220
+ cff.compile(file, otFont, isCFF2=True)
221
+ file.seek(0)
222
+ cff.decompile(file, otFont, isCFF2=True)
223
+
224
+
225
+ def convertCFFToCFF2(font):
226
+ cff = font["CFF "].cff
227
+ del font["CFF "]
228
+ _convertCFFToCFF2(cff, font)
229
+ table = font["CFF2"] = newTable("CFF2")
230
+ table.cff = cff
231
+
232
+
233
+ def main(args=None):
234
+ """Convert CFF OTF font to CFF2 OTF font"""
235
+ if args is None:
236
+ import sys
237
+
238
+ args = sys.argv[1:]
239
+
240
+ import argparse
241
+
242
+ parser = argparse.ArgumentParser(
243
+ "fonttools cffLib.CFFToCFF2",
244
+ description="Upgrade a CFF font to CFF2.",
245
+ )
246
+ parser.add_argument(
247
+ "input", metavar="INPUT.ttf", help="Input OTF file with CFF table."
248
+ )
249
+ parser.add_argument(
250
+ "-o",
251
+ "--output",
252
+ metavar="OUTPUT.ttf",
253
+ default=None,
254
+ help="Output instance OTF file (default: INPUT-CFF2.ttf).",
255
+ )
256
+ parser.add_argument(
257
+ "--no-recalc-timestamp",
258
+ dest="recalc_timestamp",
259
+ action="store_false",
260
+ help="Don't set the output font's timestamp to the current time.",
261
+ )
262
+ loggingGroup = parser.add_mutually_exclusive_group(required=False)
263
+ loggingGroup.add_argument(
264
+ "-v", "--verbose", action="store_true", help="Run more verbosely."
265
+ )
266
+ loggingGroup.add_argument(
267
+ "-q", "--quiet", action="store_true", help="Turn verbosity off."
268
+ )
269
+ options = parser.parse_args(args)
270
+
271
+ from fontTools import configLogger
272
+
273
+ configLogger(
274
+ level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
275
+ )
276
+
277
+ import os
278
+
279
+ infile = options.input
280
+ if not os.path.isfile(infile):
281
+ parser.error("No such file '{}'".format(infile))
282
+
283
+ outfile = (
284
+ makeOutputFileName(infile, overWrite=True, suffix="-CFF2")
285
+ if not options.output
286
+ else options.output
287
+ )
288
+
289
+ font = TTFont(infile, recalcTimestamp=options.recalc_timestamp, recalcBBoxes=False)
290
+
291
+ convertCFFToCFF2(font)
292
+
293
+ log.info(
294
+ "Saving %s",
295
+ outfile,
296
+ )
297
+ font.save(outfile)
298
+
299
+
300
+ if __name__ == "__main__":
301
+ import sys
302
+
303
+ sys.exit(main(sys.argv[1:]))
evalkit_tf437/lib/python3.10/site-packages/fontTools/cffLib/__pycache__/transforms.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (177 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/builder.cpython-310.pyc ADDED
Binary file (19 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/colorLib/__pycache__/unbuilder.cpython-310.pyc ADDED
Binary file (2.58 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/colorLib/builder.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ colorLib.builder: Build COLR/CPAL tables from scratch
3
+
4
+ """
5
+
6
+ import collections
7
+ import copy
8
+ import enum
9
+ from functools import partial
10
+ from math import ceil, log
11
+ from typing import (
12
+ Any,
13
+ Dict,
14
+ Generator,
15
+ Iterable,
16
+ List,
17
+ Mapping,
18
+ Optional,
19
+ Sequence,
20
+ Tuple,
21
+ Type,
22
+ TypeVar,
23
+ Union,
24
+ )
25
+ from fontTools.misc.arrayTools import intRect
26
+ from fontTools.misc.fixedTools import fixedToFloat
27
+ from fontTools.misc.treeTools import build_n_ary_tree
28
+ from fontTools.ttLib.tables import C_O_L_R_
29
+ from fontTools.ttLib.tables import C_P_A_L_
30
+ from fontTools.ttLib.tables import _n_a_m_e
31
+ from fontTools.ttLib.tables import otTables as ot
32
+ from fontTools.ttLib.tables.otTables import ExtendMode, CompositeMode
33
+ from .errors import ColorLibError
34
+ from .geometry import round_start_circle_stable_containment
35
+ from .table_builder import BuildCallback, TableBuilder
36
+
37
+
38
+ # TODO move type aliases to colorLib.types?
39
+ T = TypeVar("T")
40
+ _Kwargs = Mapping[str, Any]
41
+ _PaintInput = Union[int, _Kwargs, ot.Paint, Tuple[str, "_PaintInput"]]
42
+ _PaintInputList = Sequence[_PaintInput]
43
+ _ColorGlyphsDict = Dict[str, Union[_PaintInputList, _PaintInput]]
44
+ _ColorGlyphsV0Dict = Dict[str, Sequence[Tuple[str, int]]]
45
+ _ClipBoxInput = Union[
46
+ Tuple[int, int, int, int, int], # format 1, variable
47
+ Tuple[int, int, int, int], # format 0, non-variable
48
+ ot.ClipBox,
49
+ ]
50
+
51
+
52
+ MAX_PAINT_COLR_LAYER_COUNT = 255
53
+ _DEFAULT_ALPHA = 1.0
54
+ _MAX_REUSE_LEN = 32
55
+
56
+
57
+ def _beforeBuildPaintRadialGradient(paint, source):
58
+ x0 = source["x0"]
59
+ y0 = source["y0"]
60
+ r0 = source["r0"]
61
+ x1 = source["x1"]
62
+ y1 = source["y1"]
63
+ r1 = source["r1"]
64
+
65
+ # TODO apparently no builder_test confirms this works (?)
66
+
67
+ # avoid abrupt change after rounding when c0 is near c1's perimeter
68
+ c = round_start_circle_stable_containment((x0, y0), r0, (x1, y1), r1)
69
+ x0, y0 = c.centre
70
+ r0 = c.radius
71
+
72
+ # update source to ensure paint is built with corrected values
73
+ source["x0"] = x0
74
+ source["y0"] = y0
75
+ source["r0"] = r0
76
+ source["x1"] = x1
77
+ source["y1"] = y1
78
+ source["r1"] = r1
79
+
80
+ return paint, source
81
+
82
+
83
+ def _defaultColorStop():
84
+ colorStop = ot.ColorStop()
85
+ colorStop.Alpha = _DEFAULT_ALPHA
86
+ return colorStop
87
+
88
+
89
+ def _defaultVarColorStop():
90
+ colorStop = ot.VarColorStop()
91
+ colorStop.Alpha = _DEFAULT_ALPHA
92
+ return colorStop
93
+
94
+
95
+ def _defaultColorLine():
96
+ colorLine = ot.ColorLine()
97
+ colorLine.Extend = ExtendMode.PAD
98
+ return colorLine
99
+
100
+
101
+ def _defaultVarColorLine():
102
+ colorLine = ot.VarColorLine()
103
+ colorLine.Extend = ExtendMode.PAD
104
+ return colorLine
105
+
106
+
107
+ def _defaultPaintSolid():
108
+ paint = ot.Paint()
109
+ paint.Alpha = _DEFAULT_ALPHA
110
+ return paint
111
+
112
+
113
+ def _buildPaintCallbacks():
114
+ return {
115
+ (
116
+ BuildCallback.BEFORE_BUILD,
117
+ ot.Paint,
118
+ ot.PaintFormat.PaintRadialGradient,
119
+ ): _beforeBuildPaintRadialGradient,
120
+ (
121
+ BuildCallback.BEFORE_BUILD,
122
+ ot.Paint,
123
+ ot.PaintFormat.PaintVarRadialGradient,
124
+ ): _beforeBuildPaintRadialGradient,
125
+ (BuildCallback.CREATE_DEFAULT, ot.ColorStop): _defaultColorStop,
126
+ (BuildCallback.CREATE_DEFAULT, ot.VarColorStop): _defaultVarColorStop,
127
+ (BuildCallback.CREATE_DEFAULT, ot.ColorLine): _defaultColorLine,
128
+ (BuildCallback.CREATE_DEFAULT, ot.VarColorLine): _defaultVarColorLine,
129
+ (
130
+ BuildCallback.CREATE_DEFAULT,
131
+ ot.Paint,
132
+ ot.PaintFormat.PaintSolid,
133
+ ): _defaultPaintSolid,
134
+ (
135
+ BuildCallback.CREATE_DEFAULT,
136
+ ot.Paint,
137
+ ot.PaintFormat.PaintVarSolid,
138
+ ): _defaultPaintSolid,
139
+ }
140
+
141
+
142
+ def populateCOLRv0(
143
+ table: ot.COLR,
144
+ colorGlyphsV0: _ColorGlyphsV0Dict,
145
+ glyphMap: Optional[Mapping[str, int]] = None,
146
+ ):
147
+ """Build v0 color layers and add to existing COLR table.
148
+
149
+ Args:
150
+ table: a raw ``otTables.COLR()`` object (not ttLib's ``table_C_O_L_R_``).
151
+ colorGlyphsV0: map of base glyph names to lists of (layer glyph names,
152
+ color palette index) tuples. Can be empty.
153
+ glyphMap: a map from glyph names to glyph indices, as returned from
154
+ ``TTFont.getReverseGlyphMap()``, to optionally sort base records by GID.
155
+ """
156
+ if glyphMap is not None:
157
+ colorGlyphItems = sorted(
158
+ colorGlyphsV0.items(), key=lambda item: glyphMap[item[0]]
159
+ )
160
+ else:
161
+ colorGlyphItems = colorGlyphsV0.items()
162
+ baseGlyphRecords = []
163
+ layerRecords = []
164
+ for baseGlyph, layers in colorGlyphItems:
165
+ baseRec = ot.BaseGlyphRecord()
166
+ baseRec.BaseGlyph = baseGlyph
167
+ baseRec.FirstLayerIndex = len(layerRecords)
168
+ baseRec.NumLayers = len(layers)
169
+ baseGlyphRecords.append(baseRec)
170
+
171
+ for layerGlyph, paletteIndex in layers:
172
+ layerRec = ot.LayerRecord()
173
+ layerRec.LayerGlyph = layerGlyph
174
+ layerRec.PaletteIndex = paletteIndex
175
+ layerRecords.append(layerRec)
176
+
177
+ table.BaseGlyphRecordArray = table.LayerRecordArray = None
178
+ if baseGlyphRecords:
179
+ table.BaseGlyphRecordArray = ot.BaseGlyphRecordArray()
180
+ table.BaseGlyphRecordArray.BaseGlyphRecord = baseGlyphRecords
181
+ if layerRecords:
182
+ table.LayerRecordArray = ot.LayerRecordArray()
183
+ table.LayerRecordArray.LayerRecord = layerRecords
184
+ table.BaseGlyphRecordCount = len(baseGlyphRecords)
185
+ table.LayerRecordCount = len(layerRecords)
186
+
187
+
188
+ def buildCOLR(
189
+ colorGlyphs: _ColorGlyphsDict,
190
+ version: Optional[int] = None,
191
+ *,
192
+ glyphMap: Optional[Mapping[str, int]] = None,
193
+ varStore: Optional[ot.VarStore] = None,
194
+ varIndexMap: Optional[ot.DeltaSetIndexMap] = None,
195
+ clipBoxes: Optional[Dict[str, _ClipBoxInput]] = None,
196
+ allowLayerReuse: bool = True,
197
+ ) -> C_O_L_R_.table_C_O_L_R_:
198
+ """Build COLR table from color layers mapping.
199
+
200
+ Args:
201
+
202
+ colorGlyphs: map of base glyph name to, either list of (layer glyph name,
203
+ color palette index) tuples for COLRv0; or a single ``Paint`` (dict) or
204
+ list of ``Paint`` for COLRv1.
205
+ version: the version of COLR table. If None, the version is determined
206
+ by the presence of COLRv1 paints or variation data (varStore), which
207
+ require version 1; otherwise, if all base glyphs use only simple color
208
+ layers, version 0 is used.
209
+ glyphMap: a map from glyph names to glyph indices, as returned from
210
+ TTFont.getReverseGlyphMap(), to optionally sort base records by GID.
211
+ varStore: Optional ItemVarationStore for deltas associated with v1 layer.
212
+ varIndexMap: Optional DeltaSetIndexMap for deltas associated with v1 layer.
213
+ clipBoxes: Optional map of base glyph name to clip box 4- or 5-tuples:
214
+ (xMin, yMin, xMax, yMax) or (xMin, yMin, xMax, yMax, varIndexBase).
215
+
216
+ Returns:
217
+ A new COLR table.
218
+ """
219
+ self = C_O_L_R_.table_C_O_L_R_()
220
+
221
+ if varStore is not None and version == 0:
222
+ raise ValueError("Can't add VarStore to COLRv0")
223
+
224
+ if version in (None, 0) and not varStore:
225
+ # split color glyphs into v0 and v1 and encode separately
226
+ colorGlyphsV0, colorGlyphsV1 = _split_color_glyphs_by_version(colorGlyphs)
227
+ if version == 0 and colorGlyphsV1:
228
+ raise ValueError("Can't encode COLRv1 glyphs in COLRv0")
229
+ else:
230
+ # unless explicitly requested for v1 or have variations, in which case
231
+ # we encode all color glyph as v1
232
+ colorGlyphsV0, colorGlyphsV1 = {}, colorGlyphs
233
+
234
+ colr = ot.COLR()
235
+
236
+ populateCOLRv0(colr, colorGlyphsV0, glyphMap)
237
+
238
+ colr.LayerList, colr.BaseGlyphList = buildColrV1(
239
+ colorGlyphsV1,
240
+ glyphMap,
241
+ allowLayerReuse=allowLayerReuse,
242
+ )
243
+
244
+ if version is None:
245
+ version = 1 if (varStore or colorGlyphsV1) else 0
246
+ elif version not in (0, 1):
247
+ raise NotImplementedError(version)
248
+ self.version = colr.Version = version
249
+
250
+ if version == 0:
251
+ self.ColorLayers = self._decompileColorLayersV0(colr)
252
+ else:
253
+ colr.ClipList = buildClipList(clipBoxes) if clipBoxes else None
254
+ colr.VarIndexMap = varIndexMap
255
+ colr.VarStore = varStore
256
+ self.table = colr
257
+
258
+ return self
259
+
260
+
261
+ def buildClipList(clipBoxes: Dict[str, _ClipBoxInput]) -> ot.ClipList:
262
+ clipList = ot.ClipList()
263
+ clipList.Format = 1
264
+ clipList.clips = {name: buildClipBox(box) for name, box in clipBoxes.items()}
265
+ return clipList
266
+
267
+
268
+ def buildClipBox(clipBox: _ClipBoxInput) -> ot.ClipBox:
269
+ if isinstance(clipBox, ot.ClipBox):
270
+ return clipBox
271
+ n = len(clipBox)
272
+ clip = ot.ClipBox()
273
+ if n not in (4, 5):
274
+ raise ValueError(f"Invalid ClipBox: expected 4 or 5 values, found {n}")
275
+ clip.xMin, clip.yMin, clip.xMax, clip.yMax = intRect(clipBox[:4])
276
+ clip.Format = int(n == 5) + 1
277
+ if n == 5:
278
+ clip.VarIndexBase = int(clipBox[4])
279
+ return clip
280
+
281
+
282
+ class ColorPaletteType(enum.IntFlag):
283
+ USABLE_WITH_LIGHT_BACKGROUND = 0x0001
284
+ USABLE_WITH_DARK_BACKGROUND = 0x0002
285
+
286
+ @classmethod
287
+ def _missing_(cls, value):
288
+ # enforce reserved bits
289
+ if isinstance(value, int) and (value < 0 or value & 0xFFFC != 0):
290
+ raise ValueError(f"{value} is not a valid {cls.__name__}")
291
+ return super()._missing_(value)
292
+
293
+
294
+ # None, 'abc' or {'en': 'abc', 'de': 'xyz'}
295
+ _OptionalLocalizedString = Union[None, str, Dict[str, str]]
296
+
297
+
298
+ def buildPaletteLabels(
299
+ labels: Iterable[_OptionalLocalizedString], nameTable: _n_a_m_e.table__n_a_m_e
300
+ ) -> List[Optional[int]]:
301
+ return [
302
+ (
303
+ nameTable.addMultilingualName(l, mac=False)
304
+ if isinstance(l, dict)
305
+ else (
306
+ C_P_A_L_.table_C_P_A_L_.NO_NAME_ID
307
+ if l is None
308
+ else nameTable.addMultilingualName({"en": l}, mac=False)
309
+ )
310
+ )
311
+ for l in labels
312
+ ]
313
+
314
+
315
+ def buildCPAL(
316
+ palettes: Sequence[Sequence[Tuple[float, float, float, float]]],
317
+ paletteTypes: Optional[Sequence[ColorPaletteType]] = None,
318
+ paletteLabels: Optional[Sequence[_OptionalLocalizedString]] = None,
319
+ paletteEntryLabels: Optional[Sequence[_OptionalLocalizedString]] = None,
320
+ nameTable: Optional[_n_a_m_e.table__n_a_m_e] = None,
321
+ ) -> C_P_A_L_.table_C_P_A_L_:
322
+ """Build CPAL table from list of color palettes.
323
+
324
+ Args:
325
+ palettes: list of lists of colors encoded as tuples of (R, G, B, A) floats
326
+ in the range [0..1].
327
+ paletteTypes: optional list of ColorPaletteType, one for each palette.
328
+ paletteLabels: optional list of palette labels. Each lable can be either:
329
+ None (no label), a string (for for default English labels), or a
330
+ localized string (as a dict keyed with BCP47 language codes).
331
+ paletteEntryLabels: optional list of palette entry labels, one for each
332
+ palette entry (see paletteLabels).
333
+ nameTable: optional name table where to store palette and palette entry
334
+ labels. Required if either paletteLabels or paletteEntryLabels is set.
335
+
336
+ Return:
337
+ A new CPAL v0 or v1 table, if custom palette types or labels are specified.
338
+ """
339
+ if len({len(p) for p in palettes}) != 1:
340
+ raise ColorLibError("color palettes have different lengths")
341
+
342
+ if (paletteLabels or paletteEntryLabels) and not nameTable:
343
+ raise TypeError(
344
+ "nameTable is required if palette or palette entries have labels"
345
+ )
346
+
347
+ cpal = C_P_A_L_.table_C_P_A_L_()
348
+ cpal.numPaletteEntries = len(palettes[0])
349
+
350
+ cpal.palettes = []
351
+ for i, palette in enumerate(palettes):
352
+ colors = []
353
+ for j, color in enumerate(palette):
354
+ if not isinstance(color, tuple) or len(color) != 4:
355
+ raise ColorLibError(
356
+ f"In palette[{i}][{j}]: expected (R, G, B, A) tuple, got {color!r}"
357
+ )
358
+ if any(v > 1 or v < 0 for v in color):
359
+ raise ColorLibError(
360
+ f"palette[{i}][{j}] has invalid out-of-range [0..1] color: {color!r}"
361
+ )
362
+ # input colors are RGBA, CPAL encodes them as BGRA
363
+ red, green, blue, alpha = color
364
+ colors.append(
365
+ C_P_A_L_.Color(*(round(v * 255) for v in (blue, green, red, alpha)))
366
+ )
367
+ cpal.palettes.append(colors)
368
+
369
+ if any(v is not None for v in (paletteTypes, paletteLabels, paletteEntryLabels)):
370
+ cpal.version = 1
371
+
372
+ if paletteTypes is not None:
373
+ if len(paletteTypes) != len(palettes):
374
+ raise ColorLibError(
375
+ f"Expected {len(palettes)} paletteTypes, got {len(paletteTypes)}"
376
+ )
377
+ cpal.paletteTypes = [ColorPaletteType(t).value for t in paletteTypes]
378
+ else:
379
+ cpal.paletteTypes = [C_P_A_L_.table_C_P_A_L_.DEFAULT_PALETTE_TYPE] * len(
380
+ palettes
381
+ )
382
+
383
+ if paletteLabels is not None:
384
+ if len(paletteLabels) != len(palettes):
385
+ raise ColorLibError(
386
+ f"Expected {len(palettes)} paletteLabels, got {len(paletteLabels)}"
387
+ )
388
+ cpal.paletteLabels = buildPaletteLabels(paletteLabels, nameTable)
389
+ else:
390
+ cpal.paletteLabels = [C_P_A_L_.table_C_P_A_L_.NO_NAME_ID] * len(palettes)
391
+
392
+ if paletteEntryLabels is not None:
393
+ if len(paletteEntryLabels) != cpal.numPaletteEntries:
394
+ raise ColorLibError(
395
+ f"Expected {cpal.numPaletteEntries} paletteEntryLabels, "
396
+ f"got {len(paletteEntryLabels)}"
397
+ )
398
+ cpal.paletteEntryLabels = buildPaletteLabels(paletteEntryLabels, nameTable)
399
+ else:
400
+ cpal.paletteEntryLabels = [
401
+ C_P_A_L_.table_C_P_A_L_.NO_NAME_ID
402
+ ] * cpal.numPaletteEntries
403
+ else:
404
+ cpal.version = 0
405
+
406
+ return cpal
407
+
408
+
409
+ # COLR v1 tables
410
+ # See draft proposal at: https://github.com/googlefonts/colr-gradients-spec
411
+
412
+
413
+ def _is_colrv0_layer(layer: Any) -> bool:
414
+ # Consider as COLRv0 layer any sequence of length 2 (be it tuple or list) in which
415
+ # the first element is a str (the layerGlyph) and the second element is an int
416
+ # (CPAL paletteIndex).
417
+ # https://github.com/googlefonts/ufo2ft/issues/426
418
+ try:
419
+ layerGlyph, paletteIndex = layer
420
+ except (TypeError, ValueError):
421
+ return False
422
+ else:
423
+ return isinstance(layerGlyph, str) and isinstance(paletteIndex, int)
424
+
425
+
426
+ def _split_color_glyphs_by_version(
427
+ colorGlyphs: _ColorGlyphsDict,
428
+ ) -> Tuple[_ColorGlyphsV0Dict, _ColorGlyphsDict]:
429
+ colorGlyphsV0 = {}
430
+ colorGlyphsV1 = {}
431
+ for baseGlyph, layers in colorGlyphs.items():
432
+ if all(_is_colrv0_layer(l) for l in layers):
433
+ colorGlyphsV0[baseGlyph] = layers
434
+ else:
435
+ colorGlyphsV1[baseGlyph] = layers
436
+
437
+ # sanity check
438
+ assert set(colorGlyphs) == (set(colorGlyphsV0) | set(colorGlyphsV1))
439
+
440
+ return colorGlyphsV0, colorGlyphsV1
441
+
442
+
443
+ def _reuse_ranges(num_layers: int) -> Generator[Tuple[int, int], None, None]:
444
+ # TODO feels like something itertools might have already
445
+ for lbound in range(num_layers):
446
+ # Reuse of very large #s of layers is relatively unlikely
447
+ # +2: we want sequences of at least 2
448
+ # otData handles single-record duplication
449
+ for ubound in range(
450
+ lbound + 2, min(num_layers + 1, lbound + 2 + _MAX_REUSE_LEN)
451
+ ):
452
+ yield (lbound, ubound)
453
+
454
+
455
+ class LayerReuseCache:
456
+ reusePool: Mapping[Tuple[Any, ...], int]
457
+ tuples: Mapping[int, Tuple[Any, ...]]
458
+ keepAlive: List[ot.Paint] # we need id to remain valid
459
+
460
+ def __init__(self):
461
+ self.reusePool = {}
462
+ self.tuples = {}
463
+ self.keepAlive = []
464
+
465
+ def _paint_tuple(self, paint: ot.Paint):
466
+ # start simple, who even cares about cyclic graphs or interesting field types
467
+ def _tuple_safe(value):
468
+ if isinstance(value, enum.Enum):
469
+ return value
470
+ elif hasattr(value, "__dict__"):
471
+ return tuple(
472
+ (k, _tuple_safe(v)) for k, v in sorted(value.__dict__.items())
473
+ )
474
+ elif isinstance(value, collections.abc.MutableSequence):
475
+ return tuple(_tuple_safe(e) for e in value)
476
+ return value
477
+
478
+ # Cache the tuples for individual Paint instead of the whole sequence
479
+ # because the seq could be a transient slice
480
+ result = self.tuples.get(id(paint), None)
481
+ if result is None:
482
+ result = _tuple_safe(paint)
483
+ self.tuples[id(paint)] = result
484
+ self.keepAlive.append(paint)
485
+ return result
486
+
487
+ def _as_tuple(self, paints: Sequence[ot.Paint]) -> Tuple[Any, ...]:
488
+ return tuple(self._paint_tuple(p) for p in paints)
489
+
490
+ def try_reuse(self, layers: List[ot.Paint]) -> List[ot.Paint]:
491
+ found_reuse = True
492
+ while found_reuse:
493
+ found_reuse = False
494
+
495
+ ranges = sorted(
496
+ _reuse_ranges(len(layers)),
497
+ key=lambda t: (t[1] - t[0], t[1], t[0]),
498
+ reverse=True,
499
+ )
500
+ for lbound, ubound in ranges:
501
+ reuse_lbound = self.reusePool.get(
502
+ self._as_tuple(layers[lbound:ubound]), -1
503
+ )
504
+ if reuse_lbound == -1:
505
+ continue
506
+ new_slice = ot.Paint()
507
+ new_slice.Format = int(ot.PaintFormat.PaintColrLayers)
508
+ new_slice.NumLayers = ubound - lbound
509
+ new_slice.FirstLayerIndex = reuse_lbound
510
+ layers = layers[:lbound] + [new_slice] + layers[ubound:]
511
+ found_reuse = True
512
+ break
513
+ return layers
514
+
515
+ def add(self, layers: List[ot.Paint], first_layer_index: int):
516
+ for lbound, ubound in _reuse_ranges(len(layers)):
517
+ self.reusePool[self._as_tuple(layers[lbound:ubound])] = (
518
+ lbound + first_layer_index
519
+ )
520
+
521
+
522
+ class LayerListBuilder:
523
+ layers: List[ot.Paint]
524
+ cache: LayerReuseCache
525
+ allowLayerReuse: bool
526
+
527
+ def __init__(self, *, allowLayerReuse=True):
528
+ self.layers = []
529
+ if allowLayerReuse:
530
+ self.cache = LayerReuseCache()
531
+ else:
532
+ self.cache = None
533
+
534
+ # We need to intercept construction of PaintColrLayers
535
+ callbacks = _buildPaintCallbacks()
536
+ callbacks[
537
+ (
538
+ BuildCallback.BEFORE_BUILD,
539
+ ot.Paint,
540
+ ot.PaintFormat.PaintColrLayers,
541
+ )
542
+ ] = self._beforeBuildPaintColrLayers
543
+ self.tableBuilder = TableBuilder(callbacks)
544
+
545
+ # COLR layers is unusual in that it modifies shared state
546
+ # so we need a callback into an object
547
+ def _beforeBuildPaintColrLayers(self, dest, source):
548
+ # Sketchy gymnastics: a sequence input will have dropped it's layers
549
+ # into NumLayers; get it back
550
+ if isinstance(source.get("NumLayers", None), collections.abc.Sequence):
551
+ layers = source["NumLayers"]
552
+ else:
553
+ layers = source["Layers"]
554
+
555
+ # Convert maps seqs or whatever into typed objects
556
+ layers = [self.buildPaint(l) for l in layers]
557
+
558
+ # No reason to have a colr layers with just one entry
559
+ if len(layers) == 1:
560
+ return layers[0], {}
561
+
562
+ if self.cache is not None:
563
+ # Look for reuse, with preference to longer sequences
564
+ # This may make the layer list smaller
565
+ layers = self.cache.try_reuse(layers)
566
+
567
+ # The layer list is now final; if it's too big we need to tree it
568
+ is_tree = len(layers) > MAX_PAINT_COLR_LAYER_COUNT
569
+ layers = build_n_ary_tree(layers, n=MAX_PAINT_COLR_LAYER_COUNT)
570
+
571
+ # We now have a tree of sequences with Paint leaves.
572
+ # Convert the sequences into PaintColrLayers.
573
+ def listToColrLayers(layer):
574
+ if isinstance(layer, collections.abc.Sequence):
575
+ return self.buildPaint(
576
+ {
577
+ "Format": ot.PaintFormat.PaintColrLayers,
578
+ "Layers": [listToColrLayers(l) for l in layer],
579
+ }
580
+ )
581
+ return layer
582
+
583
+ layers = [listToColrLayers(l) for l in layers]
584
+
585
+ # No reason to have a colr layers with just one entry
586
+ if len(layers) == 1:
587
+ return layers[0], {}
588
+
589
+ paint = ot.Paint()
590
+ paint.Format = int(ot.PaintFormat.PaintColrLayers)
591
+ paint.NumLayers = len(layers)
592
+ paint.FirstLayerIndex = len(self.layers)
593
+ self.layers.extend(layers)
594
+
595
+ # Register our parts for reuse provided we aren't a tree
596
+ # If we are a tree the leaves registered for reuse and that will suffice
597
+ if self.cache is not None and not is_tree:
598
+ self.cache.add(layers, paint.FirstLayerIndex)
599
+
600
+ # we've fully built dest; empty source prevents generalized build from kicking in
601
+ return paint, {}
602
+
603
+ def buildPaint(self, paint: _PaintInput) -> ot.Paint:
604
+ return self.tableBuilder.build(ot.Paint, paint)
605
+
606
+ def build(self) -> Optional[ot.LayerList]:
607
+ if not self.layers:
608
+ return None
609
+ layers = ot.LayerList()
610
+ layers.LayerCount = len(self.layers)
611
+ layers.Paint = self.layers
612
+ return layers
613
+
614
+
615
+ def buildBaseGlyphPaintRecord(
616
+ baseGlyph: str, layerBuilder: LayerListBuilder, paint: _PaintInput
617
+ ) -> ot.BaseGlyphList:
618
+ self = ot.BaseGlyphPaintRecord()
619
+ self.BaseGlyph = baseGlyph
620
+ self.Paint = layerBuilder.buildPaint(paint)
621
+ return self
622
+
623
+
624
+ def _format_glyph_errors(errors: Mapping[str, Exception]) -> str:
625
+ lines = []
626
+ for baseGlyph, error in sorted(errors.items()):
627
+ lines.append(f" {baseGlyph} => {type(error).__name__}: {error}")
628
+ return "\n".join(lines)
629
+
630
+
631
+ def buildColrV1(
632
+ colorGlyphs: _ColorGlyphsDict,
633
+ glyphMap: Optional[Mapping[str, int]] = None,
634
+ *,
635
+ allowLayerReuse: bool = True,
636
+ ) -> Tuple[Optional[ot.LayerList], ot.BaseGlyphList]:
637
+ if glyphMap is not None:
638
+ colorGlyphItems = sorted(
639
+ colorGlyphs.items(), key=lambda item: glyphMap[item[0]]
640
+ )
641
+ else:
642
+ colorGlyphItems = colorGlyphs.items()
643
+
644
+ errors = {}
645
+ baseGlyphs = []
646
+ layerBuilder = LayerListBuilder(allowLayerReuse=allowLayerReuse)
647
+ for baseGlyph, paint in colorGlyphItems:
648
+ try:
649
+ baseGlyphs.append(buildBaseGlyphPaintRecord(baseGlyph, layerBuilder, paint))
650
+
651
+ except (ColorLibError, OverflowError, ValueError, TypeError) as e:
652
+ errors[baseGlyph] = e
653
+
654
+ if errors:
655
+ failed_glyphs = _format_glyph_errors(errors)
656
+ exc = ColorLibError(f"Failed to build BaseGlyphList:\n{failed_glyphs}")
657
+ exc.errors = errors
658
+ raise exc from next(iter(errors.values()))
659
+
660
+ layers = layerBuilder.build()
661
+ glyphs = ot.BaseGlyphList()
662
+ glyphs.BaseGlyphCount = len(baseGlyphs)
663
+ glyphs.BaseGlyphPaintRecord = baseGlyphs
664
+ return (layers, glyphs)
evalkit_tf437/lib/python3.10/site-packages/fontTools/colorLib/geometry.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpers for manipulating 2D points and vectors in COLR table."""
2
+
3
+ from math import copysign, cos, hypot, isclose, pi
4
+ from fontTools.misc.roundTools import otRound
5
+
6
+
7
+ def _vector_between(origin, target):
8
+ return (target[0] - origin[0], target[1] - origin[1])
9
+
10
+
11
+ def _round_point(pt):
12
+ return (otRound(pt[0]), otRound(pt[1]))
13
+
14
+
15
+ def _unit_vector(vec):
16
+ length = hypot(*vec)
17
+ if length == 0:
18
+ return None
19
+ return (vec[0] / length, vec[1] / length)
20
+
21
+
22
+ _CIRCLE_INSIDE_TOLERANCE = 1e-4
23
+
24
+
25
+ # The unit vector's X and Y components are respectively
26
+ # U = (cos(α), sin(α))
27
+ # where α is the angle between the unit vector and the positive x axis.
28
+ _UNIT_VECTOR_THRESHOLD = cos(3 / 8 * pi) # == sin(1/8 * pi) == 0.38268343236508984
29
+
30
+
31
+ def _rounding_offset(direction):
32
+ # Return 2-tuple of -/+ 1.0 or 0.0 approximately based on the direction vector.
33
+ # We divide the unit circle in 8 equal slices oriented towards the cardinal
34
+ # (N, E, S, W) and intermediate (NE, SE, SW, NW) directions. To each slice we
35
+ # map one of the possible cases: -1, 0, +1 for either X and Y coordinate.
36
+ # E.g. Return (+1.0, -1.0) if unit vector is oriented towards SE, or
37
+ # (-1.0, 0.0) if it's pointing West, etc.
38
+ uv = _unit_vector(direction)
39
+ if not uv:
40
+ return (0, 0)
41
+
42
+ result = []
43
+ for uv_component in uv:
44
+ if -_UNIT_VECTOR_THRESHOLD <= uv_component < _UNIT_VECTOR_THRESHOLD:
45
+ # unit vector component near 0: direction almost orthogonal to the
46
+ # direction of the current axis, thus keep coordinate unchanged
47
+ result.append(0)
48
+ else:
49
+ # nudge coord by +/- 1.0 in direction of unit vector
50
+ result.append(copysign(1.0, uv_component))
51
+ return tuple(result)
52
+
53
+
54
+ class Circle:
55
+ def __init__(self, centre, radius):
56
+ self.centre = centre
57
+ self.radius = radius
58
+
59
+ def __repr__(self):
60
+ return f"Circle(centre={self.centre}, radius={self.radius})"
61
+
62
+ def round(self):
63
+ return Circle(_round_point(self.centre), otRound(self.radius))
64
+
65
+ def inside(self, outer_circle, tolerance=_CIRCLE_INSIDE_TOLERANCE):
66
+ dist = self.radius + hypot(*_vector_between(self.centre, outer_circle.centre))
67
+ return (
68
+ isclose(outer_circle.radius, dist, rel_tol=_CIRCLE_INSIDE_TOLERANCE)
69
+ or outer_circle.radius > dist
70
+ )
71
+
72
+ def concentric(self, other):
73
+ return self.centre == other.centre
74
+
75
+ def move(self, dx, dy):
76
+ self.centre = (self.centre[0] + dx, self.centre[1] + dy)
77
+
78
+
79
+ def round_start_circle_stable_containment(c0, r0, c1, r1):
80
+ """Round start circle so that it stays inside/outside end circle after rounding.
81
+
82
+ The rounding of circle coordinates to integers may cause an abrupt change
83
+ if the start circle c0 is so close to the end circle c1's perimiter that
84
+ it ends up falling outside (or inside) as a result of the rounding.
85
+ To keep the gradient unchanged, we nudge it in the right direction.
86
+
87
+ See:
88
+ https://github.com/googlefonts/colr-gradients-spec/issues/204
89
+ https://github.com/googlefonts/picosvg/issues/158
90
+ """
91
+ start, end = Circle(c0, r0), Circle(c1, r1)
92
+
93
+ inside_before_round = start.inside(end)
94
+
95
+ round_start = start.round()
96
+ round_end = end.round()
97
+ inside_after_round = round_start.inside(round_end)
98
+
99
+ if inside_before_round == inside_after_round:
100
+ return round_start
101
+ elif inside_after_round:
102
+ # start was outside before rounding: we need to push start away from end
103
+ direction = _vector_between(round_end.centre, round_start.centre)
104
+ radius_delta = +1.0
105
+ else:
106
+ # start was inside before rounding: we need to push start towards end
107
+ direction = _vector_between(round_start.centre, round_end.centre)
108
+ radius_delta = -1.0
109
+ dx, dy = _rounding_offset(direction)
110
+
111
+ # At most 2 iterations ought to be enough to converge. Before the loop, we
112
+ # know the start circle didn't keep containment after normal rounding; thus
113
+ # we continue adjusting by -/+ 1.0 until containment is restored.
114
+ # Normal rounding can at most move each coordinates -/+0.5; in the worst case
115
+ # both the start and end circle's centres and radii will be rounded in opposite
116
+ # directions, e.g. when they move along a 45 degree diagonal:
117
+ # c0 = (1.5, 1.5) ===> (2.0, 2.0)
118
+ # r0 = 0.5 ===> 1.0
119
+ # c1 = (0.499, 0.499) ===> (0.0, 0.0)
120
+ # r1 = 2.499 ===> 2.0
121
+ # In this example, the relative distance between the circles, calculated
122
+ # as r1 - (r0 + distance(c0, c1)) is initially 0.57437 (c0 is inside c1), and
123
+ # -1.82842 after rounding (c0 is now outside c1). Nudging c0 by -1.0 on both
124
+ # x and y axes moves it towards c1 by hypot(-1.0, -1.0) = 1.41421. Two of these
125
+ # moves cover twice that distance, which is enough to restore containment.
126
+ max_attempts = 2
127
+ for _ in range(max_attempts):
128
+ if round_start.concentric(round_end):
129
+ # can't move c0 towards c1 (they are the same), so we change the radius
130
+ round_start.radius += radius_delta
131
+ assert round_start.radius >= 0
132
+ else:
133
+ round_start.move(dx, dy)
134
+ if inside_before_round == round_start.inside(round_end):
135
+ break
136
+ else: # likely a bug
137
+ raise AssertionError(
138
+ f"Rounding circle {start} "
139
+ f"{'inside' if inside_before_round else 'outside'} "
140
+ f"{end} failed after {max_attempts} attempts!"
141
+ )
142
+
143
+ return round_start
evalkit_tf437/lib/python3.10/site-packages/fontTools/designspaceLib/__main__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import sys
2
+ from fontTools.designspaceLib import main
3
+
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
evalkit_tf437/lib/python3.10/site-packages/fontTools/designspaceLib/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (307 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/__pycache__/boundsPen.cpython-310.pyc ADDED
Binary file (3.48 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/__pycache__/cu2quPen.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/__pycache__/momentsPen.cpython-310.pyc ADDED
Binary file (15.7 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/__pycache__/reportLabPen.cpython-310.pyc ADDED
Binary file (2.48 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/cairoPen.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pen to draw to a Cairo graphics library context."""
2
+
3
+ from fontTools.pens.basePen import BasePen
4
+
5
+
6
+ __all__ = ["CairoPen"]
7
+
8
+
9
+ class CairoPen(BasePen):
10
+ """Pen to draw to a Cairo graphics library context."""
11
+
12
+ def __init__(self, glyphSet, context):
13
+ BasePen.__init__(self, glyphSet)
14
+ self.context = context
15
+
16
+ def _moveTo(self, p):
17
+ self.context.move_to(*p)
18
+
19
+ def _lineTo(self, p):
20
+ self.context.line_to(*p)
21
+
22
+ def _curveToOne(self, p1, p2, p3):
23
+ self.context.curve_to(*p1, *p2, *p3)
24
+
25
+ def _closePath(self):
26
+ self.context.close_path()
evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/hashPointPen.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modified from https://github.com/adobe-type-tools/psautohint/blob/08b346865710ed3c172f1eb581d6ef243b203f99/python/psautohint/ufoFont.py#L800-L838
2
+ import hashlib
3
+
4
+ from fontTools.pens.basePen import MissingComponentError
5
+ from fontTools.pens.pointPen import AbstractPointPen
6
+
7
+
8
+ class HashPointPen(AbstractPointPen):
9
+ """
10
+ This pen can be used to check if a glyph's contents (outlines plus
11
+ components) have changed.
12
+
13
+ Components are added as the original outline plus each composite's
14
+ transformation.
15
+
16
+ Example: You have some TrueType hinting code for a glyph which you want to
17
+ compile. The hinting code specifies a hash value computed with HashPointPen
18
+ that was valid for the glyph's outlines at the time the hinting code was
19
+ written. Now you can calculate the hash for the glyph's current outlines to
20
+ check if the outlines have changed, which would probably make the hinting
21
+ code invalid.
22
+
23
+ > glyph = ufo[name]
24
+ > hash_pen = HashPointPen(glyph.width, ufo)
25
+ > glyph.drawPoints(hash_pen)
26
+ > ttdata = glyph.lib.get("public.truetype.instructions", None)
27
+ > stored_hash = ttdata.get("id", None) # The hash is stored in the "id" key
28
+ > if stored_hash is None or stored_hash != hash_pen.hash:
29
+ > logger.error(f"Glyph hash mismatch, glyph '{name}' will have no instructions in font.")
30
+ > else:
31
+ > # The hash values are identical, the outline has not changed.
32
+ > # Compile the hinting code ...
33
+ > pass
34
+
35
+ If you want to compare a glyph from a source format which supports floating point
36
+ coordinates and transformations against a glyph from a format which has restrictions
37
+ on the precision of floats, e.g. UFO vs. TTF, you must use an appropriate rounding
38
+ function to make the values comparable. For TTF fonts with composites, this
39
+ construct can be used to make the transform values conform to F2Dot14:
40
+
41
+ > ttf_hash_pen = HashPointPen(ttf_glyph_width, ttFont.getGlyphSet())
42
+ > ttf_round_pen = RoundingPointPen(ttf_hash_pen, transformRoundFunc=partial(floatToFixedToFloat, precisionBits=14))
43
+ > ufo_hash_pen = HashPointPen(ufo_glyph.width, ufo)
44
+ > ttf_glyph.drawPoints(ttf_round_pen, ttFont["glyf"])
45
+ > ufo_round_pen = RoundingPointPen(ufo_hash_pen, transformRoundFunc=partial(floatToFixedToFloat, precisionBits=14))
46
+ > ufo_glyph.drawPoints(ufo_round_pen)
47
+ > assert ttf_hash_pen.hash == ufo_hash_pen.hash
48
+ """
49
+
50
+ def __init__(self, glyphWidth=0, glyphSet=None):
51
+ self.glyphset = glyphSet
52
+ self.data = ["w%s" % round(glyphWidth, 9)]
53
+
54
+ @property
55
+ def hash(self):
56
+ data = "".join(self.data)
57
+ if len(data) >= 128:
58
+ data = hashlib.sha512(data.encode("ascii")).hexdigest()
59
+ return data
60
+
61
+ def beginPath(self, identifier=None, **kwargs):
62
+ pass
63
+
64
+ def endPath(self):
65
+ self.data.append("|")
66
+
67
+ def addPoint(
68
+ self,
69
+ pt,
70
+ segmentType=None,
71
+ smooth=False,
72
+ name=None,
73
+ identifier=None,
74
+ **kwargs,
75
+ ):
76
+ if segmentType is None:
77
+ pt_type = "o" # offcurve
78
+ else:
79
+ pt_type = segmentType[0]
80
+ self.data.append(f"{pt_type}{pt[0]:g}{pt[1]:+g}")
81
+
82
+ def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs):
83
+ tr = "".join([f"{t:+}" for t in transformation])
84
+ self.data.append("[")
85
+ try:
86
+ self.glyphset[baseGlyphName].drawPoints(self)
87
+ except KeyError:
88
+ raise MissingComponentError(baseGlyphName)
89
+ self.data.append(f"({tr})]")
evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/momentsPen.py ADDED
@@ -0,0 +1,882 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.pens.basePen import BasePen, OpenContourError
2
+
3
+ try:
4
+ import cython
5
+
6
+ COMPILED = cython.compiled
7
+ except (AttributeError, ImportError):
8
+ # if cython not installed, use mock module with no-op decorators and types
9
+ from fontTools.misc import cython
10
+
11
+ COMPILED = False
12
+
13
+
14
+ __all__ = ["MomentsPen"]
15
+
16
+
17
+ class MomentsPen(BasePen):
18
+
19
+ def __init__(self, glyphset=None):
20
+ BasePen.__init__(self, glyphset)
21
+
22
+ self.area = 0
23
+ self.momentX = 0
24
+ self.momentY = 0
25
+ self.momentXX = 0
26
+ self.momentXY = 0
27
+ self.momentYY = 0
28
+
29
+ def _moveTo(self, p0):
30
+ self._startPoint = p0
31
+
32
+ def _closePath(self):
33
+ p0 = self._getCurrentPoint()
34
+ if p0 != self._startPoint:
35
+ self._lineTo(self._startPoint)
36
+
37
+ def _endPath(self):
38
+ p0 = self._getCurrentPoint()
39
+ if p0 != self._startPoint:
40
+ raise OpenContourError("Glyph statistics is not defined on open contours.")
41
+
42
+ @cython.locals(r0=cython.double)
43
+ @cython.locals(r1=cython.double)
44
+ @cython.locals(r2=cython.double)
45
+ @cython.locals(r3=cython.double)
46
+ @cython.locals(r4=cython.double)
47
+ @cython.locals(r5=cython.double)
48
+ @cython.locals(r6=cython.double)
49
+ @cython.locals(r7=cython.double)
50
+ @cython.locals(r8=cython.double)
51
+ @cython.locals(r9=cython.double)
52
+ @cython.locals(r10=cython.double)
53
+ @cython.locals(r11=cython.double)
54
+ @cython.locals(r12=cython.double)
55
+ @cython.locals(x0=cython.double, y0=cython.double)
56
+ @cython.locals(x1=cython.double, y1=cython.double)
57
+ def _lineTo(self, p1):
58
+ x0, y0 = self._getCurrentPoint()
59
+ x1, y1 = p1
60
+
61
+ r0 = x1 * y0
62
+ r1 = x1 * y1
63
+ r2 = x1**2
64
+ r3 = r2 * y1
65
+ r4 = y0 - y1
66
+ r5 = r4 * x0
67
+ r6 = x0**2
68
+ r7 = 2 * y0
69
+ r8 = y0**2
70
+ r9 = y1**2
71
+ r10 = x1**3
72
+ r11 = y0**3
73
+ r12 = y1**3
74
+
75
+ self.area += -r0 / 2 - r1 / 2 + x0 * (y0 + y1) / 2
76
+ self.momentX += -r2 * y0 / 6 - r3 / 3 - r5 * x1 / 6 + r6 * (r7 + y1) / 6
77
+ self.momentY += (
78
+ -r0 * y1 / 6 - r8 * x1 / 6 - r9 * x1 / 6 + x0 * (r8 + r9 + y0 * y1) / 6
79
+ )
80
+ self.momentXX += (
81
+ -r10 * y0 / 12
82
+ - r10 * y1 / 4
83
+ - r2 * r5 / 12
84
+ - r4 * r6 * x1 / 12
85
+ + x0**3 * (3 * y0 + y1) / 12
86
+ )
87
+ self.momentXY += (
88
+ -r2 * r8 / 24
89
+ - r2 * r9 / 8
90
+ - r3 * r7 / 24
91
+ + r6 * (r7 * y1 + 3 * r8 + r9) / 24
92
+ - x0 * x1 * (r8 - r9) / 12
93
+ )
94
+ self.momentYY += (
95
+ -r0 * r9 / 12
96
+ - r1 * r8 / 12
97
+ - r11 * x1 / 12
98
+ - r12 * x1 / 12
99
+ + x0 * (r11 + r12 + r8 * y1 + r9 * y0) / 12
100
+ )
101
+
102
+ @cython.locals(r0=cython.double)
103
+ @cython.locals(r1=cython.double)
104
+ @cython.locals(r2=cython.double)
105
+ @cython.locals(r3=cython.double)
106
+ @cython.locals(r4=cython.double)
107
+ @cython.locals(r5=cython.double)
108
+ @cython.locals(r6=cython.double)
109
+ @cython.locals(r7=cython.double)
110
+ @cython.locals(r8=cython.double)
111
+ @cython.locals(r9=cython.double)
112
+ @cython.locals(r10=cython.double)
113
+ @cython.locals(r11=cython.double)
114
+ @cython.locals(r12=cython.double)
115
+ @cython.locals(r13=cython.double)
116
+ @cython.locals(r14=cython.double)
117
+ @cython.locals(r15=cython.double)
118
+ @cython.locals(r16=cython.double)
119
+ @cython.locals(r17=cython.double)
120
+ @cython.locals(r18=cython.double)
121
+ @cython.locals(r19=cython.double)
122
+ @cython.locals(r20=cython.double)
123
+ @cython.locals(r21=cython.double)
124
+ @cython.locals(r22=cython.double)
125
+ @cython.locals(r23=cython.double)
126
+ @cython.locals(r24=cython.double)
127
+ @cython.locals(r25=cython.double)
128
+ @cython.locals(r26=cython.double)
129
+ @cython.locals(r27=cython.double)
130
+ @cython.locals(r28=cython.double)
131
+ @cython.locals(r29=cython.double)
132
+ @cython.locals(r30=cython.double)
133
+ @cython.locals(r31=cython.double)
134
+ @cython.locals(r32=cython.double)
135
+ @cython.locals(r33=cython.double)
136
+ @cython.locals(r34=cython.double)
137
+ @cython.locals(r35=cython.double)
138
+ @cython.locals(r36=cython.double)
139
+ @cython.locals(r37=cython.double)
140
+ @cython.locals(r38=cython.double)
141
+ @cython.locals(r39=cython.double)
142
+ @cython.locals(r40=cython.double)
143
+ @cython.locals(r41=cython.double)
144
+ @cython.locals(r42=cython.double)
145
+ @cython.locals(r43=cython.double)
146
+ @cython.locals(r44=cython.double)
147
+ @cython.locals(r45=cython.double)
148
+ @cython.locals(r46=cython.double)
149
+ @cython.locals(r47=cython.double)
150
+ @cython.locals(r48=cython.double)
151
+ @cython.locals(r49=cython.double)
152
+ @cython.locals(r50=cython.double)
153
+ @cython.locals(r51=cython.double)
154
+ @cython.locals(r52=cython.double)
155
+ @cython.locals(r53=cython.double)
156
+ @cython.locals(x0=cython.double, y0=cython.double)
157
+ @cython.locals(x1=cython.double, y1=cython.double)
158
+ @cython.locals(x2=cython.double, y2=cython.double)
159
+ def _qCurveToOne(self, p1, p2):
160
+ x0, y0 = self._getCurrentPoint()
161
+ x1, y1 = p1
162
+ x2, y2 = p2
163
+
164
+ r0 = 2 * y1
165
+ r1 = r0 * x2
166
+ r2 = x2 * y2
167
+ r3 = 3 * r2
168
+ r4 = 2 * x1
169
+ r5 = 3 * y0
170
+ r6 = x1**2
171
+ r7 = x2**2
172
+ r8 = 4 * y1
173
+ r9 = 10 * y2
174
+ r10 = 2 * y2
175
+ r11 = r4 * x2
176
+ r12 = x0**2
177
+ r13 = 10 * y0
178
+ r14 = r4 * y2
179
+ r15 = x2 * y0
180
+ r16 = 4 * x1
181
+ r17 = r0 * x1 + r2
182
+ r18 = r2 * r8
183
+ r19 = y1**2
184
+ r20 = 2 * r19
185
+ r21 = y2**2
186
+ r22 = r21 * x2
187
+ r23 = 5 * r22
188
+ r24 = y0**2
189
+ r25 = y0 * y2
190
+ r26 = 5 * r24
191
+ r27 = x1**3
192
+ r28 = x2**3
193
+ r29 = 30 * y1
194
+ r30 = 6 * y1
195
+ r31 = 10 * r7 * x1
196
+ r32 = 5 * y2
197
+ r33 = 12 * r6
198
+ r34 = 30 * x1
199
+ r35 = x1 * y1
200
+ r36 = r3 + 20 * r35
201
+ r37 = 12 * x1
202
+ r38 = 20 * r6
203
+ r39 = 8 * r6 * y1
204
+ r40 = r32 * r7
205
+ r41 = 60 * y1
206
+ r42 = 20 * r19
207
+ r43 = 4 * r19
208
+ r44 = 15 * r21
209
+ r45 = 12 * x2
210
+ r46 = 12 * y2
211
+ r47 = 6 * x1
212
+ r48 = 8 * r19 * x1 + r23
213
+ r49 = 8 * y1**3
214
+ r50 = y2**3
215
+ r51 = y0**3
216
+ r52 = 10 * y1
217
+ r53 = 12 * y1
218
+
219
+ self.area += (
220
+ -r1 / 6
221
+ - r3 / 6
222
+ + x0 * (r0 + r5 + y2) / 6
223
+ + x1 * y2 / 3
224
+ - y0 * (r4 + x2) / 6
225
+ )
226
+ self.momentX += (
227
+ -r11 * (-r10 + y1) / 30
228
+ + r12 * (r13 + r8 + y2) / 30
229
+ + r6 * y2 / 15
230
+ - r7 * r8 / 30
231
+ - r7 * r9 / 30
232
+ + x0 * (r14 - r15 - r16 * y0 + r17) / 30
233
+ - y0 * (r11 + 2 * r6 + r7) / 30
234
+ )
235
+ self.momentY += (
236
+ -r18 / 30
237
+ - r20 * x2 / 30
238
+ - r23 / 30
239
+ - r24 * (r16 + x2) / 30
240
+ + x0 * (r0 * y2 + r20 + r21 + r25 + r26 + r8 * y0) / 30
241
+ + x1 * y2 * (r10 + y1) / 15
242
+ - y0 * (r1 + r17) / 30
243
+ )
244
+ self.momentXX += (
245
+ r12 * (r1 - 5 * r15 - r34 * y0 + r36 + r9 * x1) / 420
246
+ + 2 * r27 * y2 / 105
247
+ - r28 * r29 / 420
248
+ - r28 * y2 / 4
249
+ - r31 * (r0 - 3 * y2) / 420
250
+ - r6 * x2 * (r0 - r32) / 105
251
+ + x0**3 * (r30 + 21 * y0 + y2) / 84
252
+ - x0
253
+ * (
254
+ r0 * r7
255
+ + r15 * r37
256
+ - r2 * r37
257
+ - r33 * y2
258
+ + r38 * y0
259
+ - r39
260
+ - r40
261
+ + r5 * r7
262
+ )
263
+ / 420
264
+ - y0 * (8 * r27 + 5 * r28 + r31 + r33 * x2) / 420
265
+ )
266
+ self.momentXY += (
267
+ r12 * (r13 * y2 + 3 * r21 + 105 * r24 + r41 * y0 + r42 + r46 * y1) / 840
268
+ - r16 * x2 * (r43 - r44) / 840
269
+ - r21 * r7 / 8
270
+ - r24 * (r38 + r45 * x1 + 3 * r7) / 840
271
+ - r41 * r7 * y2 / 840
272
+ - r42 * r7 / 840
273
+ + r6 * y2 * (r32 + r8) / 210
274
+ + x0
275
+ * (
276
+ -r15 * r8
277
+ + r16 * r25
278
+ + r18
279
+ + r21 * r47
280
+ - r24 * r34
281
+ - r26 * x2
282
+ + r35 * r46
283
+ + r48
284
+ )
285
+ / 420
286
+ - y0 * (r16 * r2 + r30 * r7 + r35 * r45 + r39 + r40) / 420
287
+ )
288
+ self.momentYY += (
289
+ -r2 * r42 / 420
290
+ - r22 * r29 / 420
291
+ - r24 * (r14 + r36 + r52 * x2) / 420
292
+ - r49 * x2 / 420
293
+ - r50 * x2 / 12
294
+ - r51 * (r47 + x2) / 84
295
+ + x0
296
+ * (
297
+ r19 * r46
298
+ + r21 * r5
299
+ + r21 * r52
300
+ + r24 * r29
301
+ + r25 * r53
302
+ + r26 * y2
303
+ + r42 * y0
304
+ + r49
305
+ + 5 * r50
306
+ + 35 * r51
307
+ )
308
+ / 420
309
+ + x1 * y2 * (r43 + r44 + r9 * y1) / 210
310
+ - y0 * (r19 * r45 + r2 * r53 - r21 * r4 + r48) / 420
311
+ )
312
+
313
+ @cython.locals(r0=cython.double)
314
+ @cython.locals(r1=cython.double)
315
+ @cython.locals(r2=cython.double)
316
+ @cython.locals(r3=cython.double)
317
+ @cython.locals(r4=cython.double)
318
+ @cython.locals(r5=cython.double)
319
+ @cython.locals(r6=cython.double)
320
+ @cython.locals(r7=cython.double)
321
+ @cython.locals(r8=cython.double)
322
+ @cython.locals(r9=cython.double)
323
+ @cython.locals(r10=cython.double)
324
+ @cython.locals(r11=cython.double)
325
+ @cython.locals(r12=cython.double)
326
+ @cython.locals(r13=cython.double)
327
+ @cython.locals(r14=cython.double)
328
+ @cython.locals(r15=cython.double)
329
+ @cython.locals(r16=cython.double)
330
+ @cython.locals(r17=cython.double)
331
+ @cython.locals(r18=cython.double)
332
+ @cython.locals(r19=cython.double)
333
+ @cython.locals(r20=cython.double)
334
+ @cython.locals(r21=cython.double)
335
+ @cython.locals(r22=cython.double)
336
+ @cython.locals(r23=cython.double)
337
+ @cython.locals(r24=cython.double)
338
+ @cython.locals(r25=cython.double)
339
+ @cython.locals(r26=cython.double)
340
+ @cython.locals(r27=cython.double)
341
+ @cython.locals(r28=cython.double)
342
+ @cython.locals(r29=cython.double)
343
+ @cython.locals(r30=cython.double)
344
+ @cython.locals(r31=cython.double)
345
+ @cython.locals(r32=cython.double)
346
+ @cython.locals(r33=cython.double)
347
+ @cython.locals(r34=cython.double)
348
+ @cython.locals(r35=cython.double)
349
+ @cython.locals(r36=cython.double)
350
+ @cython.locals(r37=cython.double)
351
+ @cython.locals(r38=cython.double)
352
+ @cython.locals(r39=cython.double)
353
+ @cython.locals(r40=cython.double)
354
+ @cython.locals(r41=cython.double)
355
+ @cython.locals(r42=cython.double)
356
+ @cython.locals(r43=cython.double)
357
+ @cython.locals(r44=cython.double)
358
+ @cython.locals(r45=cython.double)
359
+ @cython.locals(r46=cython.double)
360
+ @cython.locals(r47=cython.double)
361
+ @cython.locals(r48=cython.double)
362
+ @cython.locals(r49=cython.double)
363
+ @cython.locals(r50=cython.double)
364
+ @cython.locals(r51=cython.double)
365
+ @cython.locals(r52=cython.double)
366
+ @cython.locals(r53=cython.double)
367
+ @cython.locals(r54=cython.double)
368
+ @cython.locals(r55=cython.double)
369
+ @cython.locals(r56=cython.double)
370
+ @cython.locals(r57=cython.double)
371
+ @cython.locals(r58=cython.double)
372
+ @cython.locals(r59=cython.double)
373
+ @cython.locals(r60=cython.double)
374
+ @cython.locals(r61=cython.double)
375
+ @cython.locals(r62=cython.double)
376
+ @cython.locals(r63=cython.double)
377
+ @cython.locals(r64=cython.double)
378
+ @cython.locals(r65=cython.double)
379
+ @cython.locals(r66=cython.double)
380
+ @cython.locals(r67=cython.double)
381
+ @cython.locals(r68=cython.double)
382
+ @cython.locals(r69=cython.double)
383
+ @cython.locals(r70=cython.double)
384
+ @cython.locals(r71=cython.double)
385
+ @cython.locals(r72=cython.double)
386
+ @cython.locals(r73=cython.double)
387
+ @cython.locals(r74=cython.double)
388
+ @cython.locals(r75=cython.double)
389
+ @cython.locals(r76=cython.double)
390
+ @cython.locals(r77=cython.double)
391
+ @cython.locals(r78=cython.double)
392
+ @cython.locals(r79=cython.double)
393
+ @cython.locals(r80=cython.double)
394
+ @cython.locals(r81=cython.double)
395
+ @cython.locals(r82=cython.double)
396
+ @cython.locals(r83=cython.double)
397
+ @cython.locals(r84=cython.double)
398
+ @cython.locals(r85=cython.double)
399
+ @cython.locals(r86=cython.double)
400
+ @cython.locals(r87=cython.double)
401
+ @cython.locals(r88=cython.double)
402
+ @cython.locals(r89=cython.double)
403
+ @cython.locals(r90=cython.double)
404
+ @cython.locals(r91=cython.double)
405
+ @cython.locals(r92=cython.double)
406
+ @cython.locals(r93=cython.double)
407
+ @cython.locals(r94=cython.double)
408
+ @cython.locals(r95=cython.double)
409
+ @cython.locals(r96=cython.double)
410
+ @cython.locals(r97=cython.double)
411
+ @cython.locals(r98=cython.double)
412
+ @cython.locals(r99=cython.double)
413
+ @cython.locals(r100=cython.double)
414
+ @cython.locals(r101=cython.double)
415
+ @cython.locals(r102=cython.double)
416
+ @cython.locals(r103=cython.double)
417
+ @cython.locals(r104=cython.double)
418
+ @cython.locals(r105=cython.double)
419
+ @cython.locals(r106=cython.double)
420
+ @cython.locals(r107=cython.double)
421
+ @cython.locals(r108=cython.double)
422
+ @cython.locals(r109=cython.double)
423
+ @cython.locals(r110=cython.double)
424
+ @cython.locals(r111=cython.double)
425
+ @cython.locals(r112=cython.double)
426
+ @cython.locals(r113=cython.double)
427
+ @cython.locals(r114=cython.double)
428
+ @cython.locals(r115=cython.double)
429
+ @cython.locals(r116=cython.double)
430
+ @cython.locals(r117=cython.double)
431
+ @cython.locals(r118=cython.double)
432
+ @cython.locals(r119=cython.double)
433
+ @cython.locals(r120=cython.double)
434
+ @cython.locals(r121=cython.double)
435
+ @cython.locals(r122=cython.double)
436
+ @cython.locals(r123=cython.double)
437
+ @cython.locals(r124=cython.double)
438
+ @cython.locals(r125=cython.double)
439
+ @cython.locals(r126=cython.double)
440
+ @cython.locals(r127=cython.double)
441
+ @cython.locals(r128=cython.double)
442
+ @cython.locals(r129=cython.double)
443
+ @cython.locals(r130=cython.double)
444
+ @cython.locals(r131=cython.double)
445
+ @cython.locals(r132=cython.double)
446
+ @cython.locals(x0=cython.double, y0=cython.double)
447
+ @cython.locals(x1=cython.double, y1=cython.double)
448
+ @cython.locals(x2=cython.double, y2=cython.double)
449
+ @cython.locals(x3=cython.double, y3=cython.double)
450
+ def _curveToOne(self, p1, p2, p3):
451
+ x0, y0 = self._getCurrentPoint()
452
+ x1, y1 = p1
453
+ x2, y2 = p2
454
+ x3, y3 = p3
455
+
456
+ r0 = 6 * y2
457
+ r1 = r0 * x3
458
+ r2 = 10 * y3
459
+ r3 = r2 * x3
460
+ r4 = 3 * y1
461
+ r5 = 6 * x1
462
+ r6 = 3 * x2
463
+ r7 = 6 * y1
464
+ r8 = 3 * y2
465
+ r9 = x2**2
466
+ r10 = 45 * r9
467
+ r11 = r10 * y3
468
+ r12 = x3**2
469
+ r13 = r12 * y2
470
+ r14 = r12 * y3
471
+ r15 = 7 * y3
472
+ r16 = 15 * x3
473
+ r17 = r16 * x2
474
+ r18 = x1**2
475
+ r19 = 9 * r18
476
+ r20 = x0**2
477
+ r21 = 21 * y1
478
+ r22 = 9 * r9
479
+ r23 = r7 * x3
480
+ r24 = 9 * y2
481
+ r25 = r24 * x2 + r3
482
+ r26 = 9 * x2
483
+ r27 = x2 * y3
484
+ r28 = -r26 * y1 + 15 * r27
485
+ r29 = 3 * x1
486
+ r30 = 45 * x1
487
+ r31 = 12 * x3
488
+ r32 = 45 * r18
489
+ r33 = 5 * r12
490
+ r34 = r8 * x3
491
+ r35 = 105 * y0
492
+ r36 = 30 * y0
493
+ r37 = r36 * x2
494
+ r38 = 5 * x3
495
+ r39 = 15 * y3
496
+ r40 = 5 * y3
497
+ r41 = r40 * x3
498
+ r42 = x2 * y2
499
+ r43 = 18 * r42
500
+ r44 = 45 * y1
501
+ r45 = r41 + r43 + r44 * x1
502
+ r46 = y2 * y3
503
+ r47 = r46 * x3
504
+ r48 = y2**2
505
+ r49 = 45 * r48
506
+ r50 = r49 * x3
507
+ r51 = y3**2
508
+ r52 = r51 * x3
509
+ r53 = y1**2
510
+ r54 = 9 * r53
511
+ r55 = y0**2
512
+ r56 = 21 * x1
513
+ r57 = 6 * x2
514
+ r58 = r16 * y2
515
+ r59 = r39 * y2
516
+ r60 = 9 * r48
517
+ r61 = r6 * y3
518
+ r62 = 3 * y3
519
+ r63 = r36 * y2
520
+ r64 = y1 * y3
521
+ r65 = 45 * r53
522
+ r66 = 5 * r51
523
+ r67 = x2**3
524
+ r68 = x3**3
525
+ r69 = 630 * y2
526
+ r70 = 126 * x3
527
+ r71 = x1**3
528
+ r72 = 126 * x2
529
+ r73 = 63 * r9
530
+ r74 = r73 * x3
531
+ r75 = r15 * x3 + 15 * r42
532
+ r76 = 630 * x1
533
+ r77 = 14 * x3
534
+ r78 = 21 * r27
535
+ r79 = 42 * x1
536
+ r80 = 42 * x2
537
+ r81 = x1 * y2
538
+ r82 = 63 * r42
539
+ r83 = x1 * y1
540
+ r84 = r41 + r82 + 378 * r83
541
+ r85 = x2 * x3
542
+ r86 = r85 * y1
543
+ r87 = r27 * x3
544
+ r88 = 27 * r9
545
+ r89 = r88 * y2
546
+ r90 = 42 * r14
547
+ r91 = 90 * x1
548
+ r92 = 189 * r18
549
+ r93 = 378 * r18
550
+ r94 = r12 * y1
551
+ r95 = 252 * x1 * x2
552
+ r96 = r79 * x3
553
+ r97 = 30 * r85
554
+ r98 = r83 * x3
555
+ r99 = 30 * x3
556
+ r100 = 42 * x3
557
+ r101 = r42 * x1
558
+ r102 = r10 * y2 + 14 * r14 + 126 * r18 * y1 + r81 * r99
559
+ r103 = 378 * r48
560
+ r104 = 18 * y1
561
+ r105 = r104 * y2
562
+ r106 = y0 * y1
563
+ r107 = 252 * y2
564
+ r108 = r107 * y0
565
+ r109 = y0 * y3
566
+ r110 = 42 * r64
567
+ r111 = 378 * r53
568
+ r112 = 63 * r48
569
+ r113 = 27 * x2
570
+ r114 = r27 * y2
571
+ r115 = r113 * r48 + 42 * r52
572
+ r116 = x3 * y3
573
+ r117 = 54 * r42
574
+ r118 = r51 * x1
575
+ r119 = r51 * x2
576
+ r120 = r48 * x1
577
+ r121 = 21 * x3
578
+ r122 = r64 * x1
579
+ r123 = r81 * y3
580
+ r124 = 30 * r27 * y1 + r49 * x2 + 14 * r52 + 126 * r53 * x1
581
+ r125 = y2**3
582
+ r126 = y3**3
583
+ r127 = y1**3
584
+ r128 = y0**3
585
+ r129 = r51 * y2
586
+ r130 = r112 * y3 + r21 * r51
587
+ r131 = 189 * r53
588
+ r132 = 90 * y2
589
+
590
+ self.area += (
591
+ -r1 / 20
592
+ - r3 / 20
593
+ - r4 * (x2 + x3) / 20
594
+ + x0 * (r7 + r8 + 10 * y0 + y3) / 20
595
+ + 3 * x1 * (y2 + y3) / 20
596
+ + 3 * x2 * y3 / 10
597
+ - y0 * (r5 + r6 + x3) / 20
598
+ )
599
+ self.momentX += (
600
+ r11 / 840
601
+ - r13 / 8
602
+ - r14 / 3
603
+ - r17 * (-r15 + r8) / 840
604
+ + r19 * (r8 + 2 * y3) / 840
605
+ + r20 * (r0 + r21 + 56 * y0 + y3) / 168
606
+ + r29 * (-r23 + r25 + r28) / 840
607
+ - r4 * (10 * r12 + r17 + r22) / 840
608
+ + x0
609
+ * (
610
+ 12 * r27
611
+ + r30 * y2
612
+ + r34
613
+ - r35 * x1
614
+ - r37
615
+ - r38 * y0
616
+ + r39 * x1
617
+ - r4 * x3
618
+ + r45
619
+ )
620
+ / 840
621
+ - y0 * (r17 + r30 * x2 + r31 * x1 + r32 + r33 + 18 * r9) / 840
622
+ )
623
+ self.momentY += (
624
+ -r4 * (r25 + r58) / 840
625
+ - r47 / 8
626
+ - r50 / 840
627
+ - r52 / 6
628
+ - r54 * (r6 + 2 * x3) / 840
629
+ - r55 * (r56 + r57 + x3) / 168
630
+ + x0
631
+ * (
632
+ r35 * y1
633
+ + r40 * y0
634
+ + r44 * y2
635
+ + 18 * r48
636
+ + 140 * r55
637
+ + r59
638
+ + r63
639
+ + 12 * r64
640
+ + r65
641
+ + r66
642
+ )
643
+ / 840
644
+ + x1 * (r24 * y1 + 10 * r51 + r59 + r60 + r7 * y3) / 280
645
+ + x2 * y3 * (r15 + r8) / 56
646
+ - y0 * (r16 * y1 + r31 * y2 + r44 * x2 + r45 + r61 - r62 * x1) / 840
647
+ )
648
+ self.momentXX += (
649
+ -r12 * r72 * (-r40 + r8) / 9240
650
+ + 3 * r18 * (r28 + r34 - r38 * y1 + r75) / 3080
651
+ + r20
652
+ * (
653
+ r24 * x3
654
+ - r72 * y0
655
+ - r76 * y0
656
+ - r77 * y0
657
+ + r78
658
+ + r79 * y3
659
+ + r80 * y1
660
+ + 210 * r81
661
+ + r84
662
+ )
663
+ / 9240
664
+ - r29
665
+ * (
666
+ r12 * r21
667
+ + 14 * r13
668
+ + r44 * r9
669
+ - r73 * y3
670
+ + 54 * r86
671
+ - 84 * r87
672
+ - r89
673
+ - r90
674
+ )
675
+ / 9240
676
+ - r4 * (70 * r12 * x2 + 27 * r67 + 42 * r68 + r74) / 9240
677
+ + 3 * r67 * y3 / 220
678
+ - r68 * r69 / 9240
679
+ - r68 * y3 / 4
680
+ - r70 * r9 * (-r62 + y2) / 9240
681
+ + 3 * r71 * (r24 + r40) / 3080
682
+ + x0**3 * (r24 + r44 + 165 * y0 + y3) / 660
683
+ + x0
684
+ * (
685
+ r100 * r27
686
+ + 162 * r101
687
+ + r102
688
+ + r11
689
+ + 63 * r18 * y3
690
+ + r27 * r91
691
+ - r33 * y0
692
+ - r37 * x3
693
+ + r43 * x3
694
+ - r73 * y0
695
+ - r88 * y1
696
+ + r92 * y2
697
+ - r93 * y0
698
+ - 9 * r94
699
+ - r95 * y0
700
+ - r96 * y0
701
+ - r97 * y1
702
+ - 18 * r98
703
+ + r99 * x1 * y3
704
+ )
705
+ / 9240
706
+ - y0
707
+ * (
708
+ r12 * r56
709
+ + r12 * r80
710
+ + r32 * x3
711
+ + 45 * r67
712
+ + 14 * r68
713
+ + 126 * r71
714
+ + r74
715
+ + r85 * r91
716
+ + 135 * r9 * x1
717
+ + r92 * x2
718
+ )
719
+ / 9240
720
+ )
721
+ self.momentXY += (
722
+ -r103 * r12 / 18480
723
+ - r12 * r51 / 8
724
+ - 3 * r14 * y2 / 44
725
+ + 3 * r18 * (r105 + r2 * y1 + 18 * r46 + 15 * r48 + 7 * r51) / 6160
726
+ + r20
727
+ * (
728
+ 1260 * r106
729
+ + r107 * y1
730
+ + r108
731
+ + 28 * r109
732
+ + r110
733
+ + r111
734
+ + r112
735
+ + 30 * r46
736
+ + 2310 * r55
737
+ + r66
738
+ )
739
+ / 18480
740
+ - r54 * (7 * r12 + 18 * r85 + 15 * r9) / 18480
741
+ - r55 * (r33 + r73 + r93 + r95 + r96 + r97) / 18480
742
+ - r7 * (42 * r13 + r82 * x3 + 28 * r87 + r89 + r90) / 18480
743
+ - 3 * r85 * (r48 - r66) / 220
744
+ + 3 * r9 * y3 * (r62 + 2 * y2) / 440
745
+ + x0
746
+ * (
747
+ -r1 * y0
748
+ - 84 * r106 * x2
749
+ + r109 * r56
750
+ + 54 * r114
751
+ + r117 * y1
752
+ + 15 * r118
753
+ + 21 * r119
754
+ + 81 * r120
755
+ + r121 * r46
756
+ + 54 * r122
757
+ + 60 * r123
758
+ + r124
759
+ - r21 * x3 * y0
760
+ + r23 * y3
761
+ - r54 * x3
762
+ - r55 * r72
763
+ - r55 * r76
764
+ - r55 * r77
765
+ + r57 * y0 * y3
766
+ + r60 * x3
767
+ + 84 * r81 * y0
768
+ + 189 * r81 * y1
769
+ )
770
+ / 9240
771
+ + x1
772
+ * (
773
+ r104 * r27
774
+ - r105 * x3
775
+ - r113 * r53
776
+ + 63 * r114
777
+ + r115
778
+ - r16 * r53
779
+ + 28 * r47
780
+ + r51 * r80
781
+ )
782
+ / 3080
783
+ - y0
784
+ * (
785
+ 54 * r101
786
+ + r102
787
+ + r116 * r5
788
+ + r117 * x3
789
+ + 21 * r13
790
+ - r19 * y3
791
+ + r22 * y3
792
+ + r78 * x3
793
+ + 189 * r83 * x2
794
+ + 60 * r86
795
+ + 81 * r9 * y1
796
+ + 15 * r94
797
+ + 54 * r98
798
+ )
799
+ / 9240
800
+ )
801
+ self.momentYY += (
802
+ -r103 * r116 / 9240
803
+ - r125 * r70 / 9240
804
+ - r126 * x3 / 12
805
+ - 3 * r127 * (r26 + r38) / 3080
806
+ - r128 * (r26 + r30 + x3) / 660
807
+ - r4 * (r112 * x3 + r115 - 14 * r119 + 84 * r47) / 9240
808
+ - r52 * r69 / 9240
809
+ - r54 * (r58 + r61 + r75) / 9240
810
+ - r55
811
+ * (r100 * y1 + r121 * y2 + r26 * y3 + r79 * y2 + r84 + 210 * x2 * y1)
812
+ / 9240
813
+ + x0
814
+ * (
815
+ r108 * y1
816
+ + r110 * y0
817
+ + r111 * y0
818
+ + r112 * y0
819
+ + 45 * r125
820
+ + 14 * r126
821
+ + 126 * r127
822
+ + 770 * r128
823
+ + 42 * r129
824
+ + r130
825
+ + r131 * y2
826
+ + r132 * r64
827
+ + 135 * r48 * y1
828
+ + 630 * r55 * y1
829
+ + 126 * r55 * y2
830
+ + 14 * r55 * y3
831
+ + r63 * y3
832
+ + r65 * y3
833
+ + r66 * y0
834
+ )
835
+ / 9240
836
+ + x1
837
+ * (
838
+ 27 * r125
839
+ + 42 * r126
840
+ + 70 * r129
841
+ + r130
842
+ + r39 * r53
843
+ + r44 * r48
844
+ + 27 * r53 * y2
845
+ + 54 * r64 * y2
846
+ )
847
+ / 3080
848
+ + 3 * x2 * y3 * (r48 + r66 + r8 * y3) / 220
849
+ - y0
850
+ * (
851
+ r100 * r46
852
+ + 18 * r114
853
+ - 9 * r118
854
+ - 27 * r120
855
+ - 18 * r122
856
+ - 30 * r123
857
+ + r124
858
+ + r131 * x2
859
+ + r132 * x3 * y1
860
+ + 162 * r42 * y1
861
+ + r50
862
+ + 63 * r53 * x3
863
+ + r64 * r99
864
+ )
865
+ / 9240
866
+ )
867
+
868
+
869
+ if __name__ == "__main__":
870
+ from fontTools.misc.symfont import x, y, printGreenPen
871
+
872
+ printGreenPen(
873
+ "MomentsPen",
874
+ [
875
+ ("area", 1),
876
+ ("momentX", x),
877
+ ("momentY", y),
878
+ ("momentXX", x**2),
879
+ ("momentXY", x * y),
880
+ ("momentYY", y**2),
881
+ ],
882
+ )
evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/perimeterPen.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Calculate the perimeter of a glyph."""
3
+
4
+ from fontTools.pens.basePen import BasePen
5
+ from fontTools.misc.bezierTools import (
6
+ approximateQuadraticArcLengthC,
7
+ calcQuadraticArcLengthC,
8
+ approximateCubicArcLengthC,
9
+ calcCubicArcLengthC,
10
+ )
11
+ import math
12
+
13
+
14
+ __all__ = ["PerimeterPen"]
15
+
16
+
17
+ def _distance(p0, p1):
18
+ return math.hypot(p0[0] - p1[0], p0[1] - p1[1])
19
+
20
+
21
+ class PerimeterPen(BasePen):
22
+ def __init__(self, glyphset=None, tolerance=0.005):
23
+ BasePen.__init__(self, glyphset)
24
+ self.value = 0
25
+ self.tolerance = tolerance
26
+
27
+ # Choose which algorithm to use for quadratic and for cubic.
28
+ # Quadrature is faster but has fixed error characteristic with no strong
29
+ # error bound. The cutoff points are derived empirically.
30
+ self._addCubic = (
31
+ self._addCubicQuadrature if tolerance >= 0.0015 else self._addCubicRecursive
32
+ )
33
+ self._addQuadratic = (
34
+ self._addQuadraticQuadrature
35
+ if tolerance >= 0.00075
36
+ else self._addQuadraticExact
37
+ )
38
+
39
+ def _moveTo(self, p0):
40
+ self.__startPoint = p0
41
+
42
+ def _closePath(self):
43
+ p0 = self._getCurrentPoint()
44
+ if p0 != self.__startPoint:
45
+ self._lineTo(self.__startPoint)
46
+
47
+ def _lineTo(self, p1):
48
+ p0 = self._getCurrentPoint()
49
+ self.value += _distance(p0, p1)
50
+
51
+ def _addQuadraticExact(self, c0, c1, c2):
52
+ self.value += calcQuadraticArcLengthC(c0, c1, c2)
53
+
54
+ def _addQuadraticQuadrature(self, c0, c1, c2):
55
+ self.value += approximateQuadraticArcLengthC(c0, c1, c2)
56
+
57
+ def _qCurveToOne(self, p1, p2):
58
+ p0 = self._getCurrentPoint()
59
+ self._addQuadratic(complex(*p0), complex(*p1), complex(*p2))
60
+
61
+ def _addCubicRecursive(self, c0, c1, c2, c3):
62
+ self.value += calcCubicArcLengthC(c0, c1, c2, c3, self.tolerance)
63
+
64
+ def _addCubicQuadrature(self, c0, c1, c2, c3):
65
+ self.value += approximateCubicArcLengthC(c0, c1, c2, c3)
66
+
67
+ def _curveToOne(self, p1, p2, p3):
68
+ p0 = self._getCurrentPoint()
69
+ self._addCubic(complex(*p0), complex(*p1), complex(*p2), complex(*p3))
evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/qu2cuPen.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Google Inc. All Rights Reserved.
2
+ # Copyright 2023 Behdad Esfahbod. All Rights Reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from fontTools.qu2cu import quadratic_to_curves
17
+ from fontTools.pens.filterPen import ContourFilterPen
18
+ from fontTools.pens.reverseContourPen import ReverseContourPen
19
+ import math
20
+
21
+
22
+ class Qu2CuPen(ContourFilterPen):
23
+ """A filter pen to convert quadratic bezier splines to cubic curves
24
+ using the FontTools SegmentPen protocol.
25
+
26
+ Args:
27
+
28
+ other_pen: another SegmentPen used to draw the transformed outline.
29
+ max_err: maximum approximation error in font units. For optimal results,
30
+ if you know the UPEM of the font, we recommend setting this to a
31
+ value equal, or close to UPEM / 1000.
32
+ reverse_direction: flip the contours' direction but keep starting point.
33
+ stats: a dictionary counting the point numbers of cubic segments.
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ other_pen,
39
+ max_err,
40
+ all_cubic=False,
41
+ reverse_direction=False,
42
+ stats=None,
43
+ ):
44
+ if reverse_direction:
45
+ other_pen = ReverseContourPen(other_pen)
46
+ super().__init__(other_pen)
47
+ self.all_cubic = all_cubic
48
+ self.max_err = max_err
49
+ self.stats = stats
50
+
51
+ def _quadratics_to_curve(self, q):
52
+ curves = quadratic_to_curves(q, self.max_err, all_cubic=self.all_cubic)
53
+ if self.stats is not None:
54
+ for curve in curves:
55
+ n = str(len(curve) - 2)
56
+ self.stats[n] = self.stats.get(n, 0) + 1
57
+ for curve in curves:
58
+ if len(curve) == 4:
59
+ yield ("curveTo", curve[1:])
60
+ else:
61
+ yield ("qCurveTo", curve[1:])
62
+
63
+ def filterContour(self, contour):
64
+ quadratics = []
65
+ currentPt = None
66
+ newContour = []
67
+ for op, args in contour:
68
+ if op == "qCurveTo" and (
69
+ self.all_cubic or (len(args) > 2 and args[-1] is not None)
70
+ ):
71
+ if args[-1] is None:
72
+ raise NotImplementedError(
73
+ "oncurve-less contours with all_cubic not implemented"
74
+ )
75
+ quadratics.append((currentPt,) + args)
76
+ else:
77
+ if quadratics:
78
+ newContour.extend(self._quadratics_to_curve(quadratics))
79
+ quadratics = []
80
+ newContour.append((op, args))
81
+ currentPt = args[-1] if args else None
82
+ if quadratics:
83
+ newContour.extend(self._quadratics_to_curve(quadratics))
84
+
85
+ if not self.all_cubic:
86
+ # Add back implicit oncurve points
87
+ contour = newContour
88
+ newContour = []
89
+ for op, args in contour:
90
+ if op == "qCurveTo" and newContour and newContour[-1][0] == "qCurveTo":
91
+ pt0 = newContour[-1][1][-2]
92
+ pt1 = newContour[-1][1][-1]
93
+ pt2 = args[0]
94
+ if (
95
+ pt1 is not None
96
+ and math.isclose(pt2[0] - pt1[0], pt1[0] - pt0[0])
97
+ and math.isclose(pt2[1] - pt1[1], pt1[1] - pt0[1])
98
+ ):
99
+ newArgs = newContour[-1][1][:-1] + args
100
+ newContour[-1] = (op, newArgs)
101
+ continue
102
+
103
+ newContour.append((op, args))
104
+
105
+ return newContour
evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/reverseContourPen.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc.arrayTools import pairwise
2
+ from fontTools.pens.filterPen import ContourFilterPen
3
+
4
+
5
+ __all__ = ["reversedContour", "ReverseContourPen"]
6
+
7
+
8
+ class ReverseContourPen(ContourFilterPen):
9
+ """Filter pen that passes outline data to another pen, but reversing
10
+ the winding direction of all contours. Components are simply passed
11
+ through unchanged.
12
+
13
+ Closed contours are reversed in such a way that the first point remains
14
+ the first point.
15
+ """
16
+
17
+ def __init__(self, outPen, outputImpliedClosingLine=False):
18
+ super().__init__(outPen)
19
+ self.outputImpliedClosingLine = outputImpliedClosingLine
20
+
21
+ def filterContour(self, contour):
22
+ return reversedContour(contour, self.outputImpliedClosingLine)
23
+
24
+
25
+ def reversedContour(contour, outputImpliedClosingLine=False):
26
+ """Generator that takes a list of pen's (operator, operands) tuples,
27
+ and yields them with the winding direction reversed.
28
+ """
29
+ if not contour:
30
+ return # nothing to do, stop iteration
31
+
32
+ # valid contours must have at least a starting and ending command,
33
+ # can't have one without the other
34
+ assert len(contour) > 1, "invalid contour"
35
+
36
+ # the type of the last command determines if the contour is closed
37
+ contourType = contour.pop()[0]
38
+ assert contourType in ("endPath", "closePath")
39
+ closed = contourType == "closePath"
40
+
41
+ firstType, firstPts = contour.pop(0)
42
+ assert firstType in ("moveTo", "qCurveTo"), (
43
+ "invalid initial segment type: %r" % firstType
44
+ )
45
+ firstOnCurve = firstPts[-1]
46
+ if firstType == "qCurveTo":
47
+ # special case for TrueType paths contaning only off-curve points
48
+ assert firstOnCurve is None, "off-curve only paths must end with 'None'"
49
+ assert not contour, "only one qCurveTo allowed per off-curve path"
50
+ firstPts = (firstPts[0],) + tuple(reversed(firstPts[1:-1])) + (None,)
51
+
52
+ if not contour:
53
+ # contour contains only one segment, nothing to reverse
54
+ if firstType == "moveTo":
55
+ closed = False # single-point paths can't be closed
56
+ else:
57
+ closed = True # off-curve paths are closed by definition
58
+ yield firstType, firstPts
59
+ else:
60
+ lastType, lastPts = contour[-1]
61
+ lastOnCurve = lastPts[-1]
62
+ if closed:
63
+ # for closed paths, we keep the starting point
64
+ yield firstType, firstPts
65
+ if firstOnCurve != lastOnCurve:
66
+ # emit an implied line between the last and first points
67
+ yield "lineTo", (lastOnCurve,)
68
+ contour[-1] = (lastType, tuple(lastPts[:-1]) + (firstOnCurve,))
69
+
70
+ if len(contour) > 1:
71
+ secondType, secondPts = contour[0]
72
+ else:
73
+ # contour has only two points, the second and last are the same
74
+ secondType, secondPts = lastType, lastPts
75
+
76
+ if not outputImpliedClosingLine:
77
+ # if a lineTo follows the initial moveTo, after reversing it
78
+ # will be implied by the closePath, so we don't emit one;
79
+ # unless the lineTo and moveTo overlap, in which case we keep the
80
+ # duplicate points
81
+ if secondType == "lineTo" and firstPts != secondPts:
82
+ del contour[0]
83
+ if contour:
84
+ contour[-1] = (lastType, tuple(lastPts[:-1]) + secondPts)
85
+ else:
86
+ # for open paths, the last point will become the first
87
+ yield firstType, (lastOnCurve,)
88
+ contour[-1] = (lastType, tuple(lastPts[:-1]) + (firstOnCurve,))
89
+
90
+ # we iterate over all segment pairs in reverse order, and yield
91
+ # each one with the off-curve points reversed (if any), and
92
+ # with the on-curve point of the following segment
93
+ for (curType, curPts), (_, nextPts) in pairwise(contour, reverse=True):
94
+ yield curType, tuple(reversed(curPts[:-1])) + (nextPts[-1],)
95
+
96
+ yield "closePath" if closed else "endPath", ()
evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/roundingPen.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc.roundTools import noRound, otRound
2
+ from fontTools.misc.transform import Transform
3
+ from fontTools.pens.filterPen import FilterPen, FilterPointPen
4
+
5
+
6
+ __all__ = ["RoundingPen", "RoundingPointPen"]
7
+
8
+
9
+ class RoundingPen(FilterPen):
10
+ """
11
+ Filter pen that rounds point coordinates and component XY offsets to integer. For
12
+ rounding the component transform values, a separate round function can be passed to
13
+ the pen.
14
+
15
+ >>> from fontTools.pens.recordingPen import RecordingPen
16
+ >>> recpen = RecordingPen()
17
+ >>> roundpen = RoundingPen(recpen)
18
+ >>> roundpen.moveTo((0.4, 0.6))
19
+ >>> roundpen.lineTo((1.6, 2.5))
20
+ >>> roundpen.qCurveTo((2.4, 4.6), (3.3, 5.7), (4.9, 6.1))
21
+ >>> roundpen.curveTo((6.4, 8.6), (7.3, 9.7), (8.9, 10.1))
22
+ >>> roundpen.addComponent("a", (1.5, 0, 0, 1.5, 10.5, -10.5))
23
+ >>> recpen.value == [
24
+ ... ('moveTo', ((0, 1),)),
25
+ ... ('lineTo', ((2, 3),)),
26
+ ... ('qCurveTo', ((2, 5), (3, 6), (5, 6))),
27
+ ... ('curveTo', ((6, 9), (7, 10), (9, 10))),
28
+ ... ('addComponent', ('a', (1.5, 0, 0, 1.5, 11, -10))),
29
+ ... ]
30
+ True
31
+ """
32
+
33
+ def __init__(self, outPen, roundFunc=otRound, transformRoundFunc=noRound):
34
+ super().__init__(outPen)
35
+ self.roundFunc = roundFunc
36
+ self.transformRoundFunc = transformRoundFunc
37
+
38
+ def moveTo(self, pt):
39
+ self._outPen.moveTo((self.roundFunc(pt[0]), self.roundFunc(pt[1])))
40
+
41
+ def lineTo(self, pt):
42
+ self._outPen.lineTo((self.roundFunc(pt[0]), self.roundFunc(pt[1])))
43
+
44
+ def curveTo(self, *points):
45
+ self._outPen.curveTo(
46
+ *((self.roundFunc(x), self.roundFunc(y)) for x, y in points)
47
+ )
48
+
49
+ def qCurveTo(self, *points):
50
+ self._outPen.qCurveTo(
51
+ *((self.roundFunc(x), self.roundFunc(y)) for x, y in points)
52
+ )
53
+
54
+ def addComponent(self, glyphName, transformation):
55
+ xx, xy, yx, yy, dx, dy = transformation
56
+ self._outPen.addComponent(
57
+ glyphName,
58
+ Transform(
59
+ self.transformRoundFunc(xx),
60
+ self.transformRoundFunc(xy),
61
+ self.transformRoundFunc(yx),
62
+ self.transformRoundFunc(yy),
63
+ self.roundFunc(dx),
64
+ self.roundFunc(dy),
65
+ ),
66
+ )
67
+
68
+
69
+ class RoundingPointPen(FilterPointPen):
70
+ """
71
+ Filter point pen that rounds point coordinates and component XY offsets to integer.
72
+ For rounding the component scale values, a separate round function can be passed to
73
+ the pen.
74
+
75
+ >>> from fontTools.pens.recordingPen import RecordingPointPen
76
+ >>> recpen = RecordingPointPen()
77
+ >>> roundpen = RoundingPointPen(recpen)
78
+ >>> roundpen.beginPath()
79
+ >>> roundpen.addPoint((0.4, 0.6), 'line')
80
+ >>> roundpen.addPoint((1.6, 2.5), 'line')
81
+ >>> roundpen.addPoint((2.4, 4.6))
82
+ >>> roundpen.addPoint((3.3, 5.7))
83
+ >>> roundpen.addPoint((4.9, 6.1), 'qcurve')
84
+ >>> roundpen.endPath()
85
+ >>> roundpen.addComponent("a", (1.5, 0, 0, 1.5, 10.5, -10.5))
86
+ >>> recpen.value == [
87
+ ... ('beginPath', (), {}),
88
+ ... ('addPoint', ((0, 1), 'line', False, None), {}),
89
+ ... ('addPoint', ((2, 3), 'line', False, None), {}),
90
+ ... ('addPoint', ((2, 5), None, False, None), {}),
91
+ ... ('addPoint', ((3, 6), None, False, None), {}),
92
+ ... ('addPoint', ((5, 6), 'qcurve', False, None), {}),
93
+ ... ('endPath', (), {}),
94
+ ... ('addComponent', ('a', (1.5, 0, 0, 1.5, 11, -10)), {}),
95
+ ... ]
96
+ True
97
+ """
98
+
99
+ def __init__(self, outPen, roundFunc=otRound, transformRoundFunc=noRound):
100
+ super().__init__(outPen)
101
+ self.roundFunc = roundFunc
102
+ self.transformRoundFunc = transformRoundFunc
103
+
104
+ def addPoint(
105
+ self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs
106
+ ):
107
+ self._outPen.addPoint(
108
+ (self.roundFunc(pt[0]), self.roundFunc(pt[1])),
109
+ segmentType=segmentType,
110
+ smooth=smooth,
111
+ name=name,
112
+ identifier=identifier,
113
+ **kwargs,
114
+ )
115
+
116
+ def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs):
117
+ xx, xy, yx, yy, dx, dy = transformation
118
+ self._outPen.addComponent(
119
+ baseGlyphName=baseGlyphName,
120
+ transformation=Transform(
121
+ self.transformRoundFunc(xx),
122
+ self.transformRoundFunc(xy),
123
+ self.transformRoundFunc(yx),
124
+ self.transformRoundFunc(yy),
125
+ self.roundFunc(dx),
126
+ self.roundFunc(dy),
127
+ ),
128
+ identifier=identifier,
129
+ **kwargs,
130
+ )
evalkit_tf437/lib/python3.10/site-packages/fontTools/pens/svgPathPen.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable
2
+ from fontTools.pens.basePen import BasePen
3
+
4
+
5
+ def pointToString(pt, ntos=str):
6
+ return " ".join(ntos(i) for i in pt)
7
+
8
+
9
+ class SVGPathPen(BasePen):
10
+ """Pen to draw SVG path d commands.
11
+
12
+ Args:
13
+ glyphSet: a dictionary of drawable glyph objects keyed by name
14
+ used to resolve component references in composite glyphs.
15
+ ntos: a callable that takes a number and returns a string, to
16
+ customize how numbers are formatted (default: str).
17
+
18
+ :Example:
19
+ .. code-block::
20
+
21
+ >>> pen = SVGPathPen(None)
22
+ >>> pen.moveTo((0, 0))
23
+ >>> pen.lineTo((1, 1))
24
+ >>> pen.curveTo((2, 2), (3, 3), (4, 4))
25
+ >>> pen.closePath()
26
+ >>> pen.getCommands()
27
+ 'M0 0 1 1C2 2 3 3 4 4Z'
28
+
29
+ Note:
30
+ Fonts have a coordinate system where Y grows up, whereas in SVG,
31
+ Y grows down. As such, rendering path data from this pen in
32
+ SVG typically results in upside-down glyphs. You can fix this
33
+ by wrapping the data from this pen in an SVG group element with
34
+ transform, or wrap this pen in a transform pen. For example:
35
+ .. code-block:: python
36
+
37
+ spen = svgPathPen.SVGPathPen(glyphset)
38
+ pen= TransformPen(spen , (1, 0, 0, -1, 0, 0))
39
+ glyphset[glyphname].draw(pen)
40
+ print(tpen.getCommands())
41
+ """
42
+
43
+ def __init__(self, glyphSet, ntos: Callable[[float], str] = str):
44
+ BasePen.__init__(self, glyphSet)
45
+ self._commands = []
46
+ self._lastCommand = None
47
+ self._lastX = None
48
+ self._lastY = None
49
+ self._ntos = ntos
50
+
51
+ def _handleAnchor(self):
52
+ """
53
+ >>> pen = SVGPathPen(None)
54
+ >>> pen.moveTo((0, 0))
55
+ >>> pen.moveTo((10, 10))
56
+ >>> pen._commands
57
+ ['M10 10']
58
+ """
59
+ if self._lastCommand == "M":
60
+ self._commands.pop(-1)
61
+
62
+ def _moveTo(self, pt):
63
+ """
64
+ >>> pen = SVGPathPen(None)
65
+ >>> pen.moveTo((0, 0))
66
+ >>> pen._commands
67
+ ['M0 0']
68
+
69
+ >>> pen = SVGPathPen(None)
70
+ >>> pen.moveTo((10, 0))
71
+ >>> pen._commands
72
+ ['M10 0']
73
+
74
+ >>> pen = SVGPathPen(None)
75
+ >>> pen.moveTo((0, 10))
76
+ >>> pen._commands
77
+ ['M0 10']
78
+ """
79
+ self._handleAnchor()
80
+ t = "M%s" % (pointToString(pt, self._ntos))
81
+ self._commands.append(t)
82
+ self._lastCommand = "M"
83
+ self._lastX, self._lastY = pt
84
+
85
+ def _lineTo(self, pt):
86
+ """
87
+ # duplicate point
88
+ >>> pen = SVGPathPen(None)
89
+ >>> pen.moveTo((10, 10))
90
+ >>> pen.lineTo((10, 10))
91
+ >>> pen._commands
92
+ ['M10 10']
93
+
94
+ # vertical line
95
+ >>> pen = SVGPathPen(None)
96
+ >>> pen.moveTo((10, 10))
97
+ >>> pen.lineTo((10, 0))
98
+ >>> pen._commands
99
+ ['M10 10', 'V0']
100
+
101
+ # horizontal line
102
+ >>> pen = SVGPathPen(None)
103
+ >>> pen.moveTo((10, 10))
104
+ >>> pen.lineTo((0, 10))
105
+ >>> pen._commands
106
+ ['M10 10', 'H0']
107
+
108
+ # basic
109
+ >>> pen = SVGPathPen(None)
110
+ >>> pen.lineTo((70, 80))
111
+ >>> pen._commands
112
+ ['L70 80']
113
+
114
+ # basic following a moveto
115
+ >>> pen = SVGPathPen(None)
116
+ >>> pen.moveTo((0, 0))
117
+ >>> pen.lineTo((10, 10))
118
+ >>> pen._commands
119
+ ['M0 0', ' 10 10']
120
+ """
121
+ x, y = pt
122
+ # duplicate point
123
+ if x == self._lastX and y == self._lastY:
124
+ return
125
+ # vertical line
126
+ elif x == self._lastX:
127
+ cmd = "V"
128
+ pts = self._ntos(y)
129
+ # horizontal line
130
+ elif y == self._lastY:
131
+ cmd = "H"
132
+ pts = self._ntos(x)
133
+ # previous was a moveto
134
+ elif self._lastCommand == "M":
135
+ cmd = None
136
+ pts = " " + pointToString(pt, self._ntos)
137
+ # basic
138
+ else:
139
+ cmd = "L"
140
+ pts = pointToString(pt, self._ntos)
141
+ # write the string
142
+ t = ""
143
+ if cmd:
144
+ t += cmd
145
+ self._lastCommand = cmd
146
+ t += pts
147
+ self._commands.append(t)
148
+ # store for future reference
149
+ self._lastX, self._lastY = pt
150
+
151
+ def _curveToOne(self, pt1, pt2, pt3):
152
+ """
153
+ >>> pen = SVGPathPen(None)
154
+ >>> pen.curveTo((10, 20), (30, 40), (50, 60))
155
+ >>> pen._commands
156
+ ['C10 20 30 40 50 60']
157
+ """
158
+ t = "C"
159
+ t += pointToString(pt1, self._ntos) + " "
160
+ t += pointToString(pt2, self._ntos) + " "
161
+ t += pointToString(pt3, self._ntos)
162
+ self._commands.append(t)
163
+ self._lastCommand = "C"
164
+ self._lastX, self._lastY = pt3
165
+
166
+ def _qCurveToOne(self, pt1, pt2):
167
+ """
168
+ >>> pen = SVGPathPen(None)
169
+ >>> pen.qCurveTo((10, 20), (30, 40))
170
+ >>> pen._commands
171
+ ['Q10 20 30 40']
172
+ >>> from fontTools.misc.roundTools import otRound
173
+ >>> pen = SVGPathPen(None, ntos=lambda v: str(otRound(v)))
174
+ >>> pen.qCurveTo((3, 3), (7, 5), (11, 4))
175
+ >>> pen._commands
176
+ ['Q3 3 5 4', 'Q7 5 11 4']
177
+ """
178
+ assert pt2 is not None
179
+ t = "Q"
180
+ t += pointToString(pt1, self._ntos) + " "
181
+ t += pointToString(pt2, self._ntos)
182
+ self._commands.append(t)
183
+ self._lastCommand = "Q"
184
+ self._lastX, self._lastY = pt2
185
+
186
+ def _closePath(self):
187
+ """
188
+ >>> pen = SVGPathPen(None)
189
+ >>> pen.closePath()
190
+ >>> pen._commands
191
+ ['Z']
192
+ """
193
+ self._commands.append("Z")
194
+ self._lastCommand = "Z"
195
+ self._lastX = self._lastY = None
196
+
197
+ def _endPath(self):
198
+ """
199
+ >>> pen = SVGPathPen(None)
200
+ >>> pen.endPath()
201
+ >>> pen._commands
202
+ []
203
+ """
204
+ self._lastCommand = None
205
+ self._lastX = self._lastY = None
206
+
207
+ def getCommands(self):
208
+ return "".join(self._commands)
209
+
210
+
211
+ def main(args=None):
212
+ """Generate per-character SVG from font and text"""
213
+
214
+ if args is None:
215
+ import sys
216
+
217
+ args = sys.argv[1:]
218
+
219
+ from fontTools.ttLib import TTFont
220
+ import argparse
221
+
222
+ parser = argparse.ArgumentParser(
223
+ "fonttools pens.svgPathPen", description="Generate SVG from text"
224
+ )
225
+ parser.add_argument("font", metavar="font.ttf", help="Font file.")
226
+ parser.add_argument("text", metavar="text", nargs="?", help="Text string.")
227
+ parser.add_argument(
228
+ "-y",
229
+ metavar="<number>",
230
+ help="Face index into a collection to open. Zero based.",
231
+ )
232
+ parser.add_argument(
233
+ "--glyphs",
234
+ metavar="whitespace-separated list of glyph names",
235
+ type=str,
236
+ help="Glyphs to show. Exclusive with text option",
237
+ )
238
+ parser.add_argument(
239
+ "--variations",
240
+ metavar="AXIS=LOC",
241
+ default="",
242
+ help="List of space separated locations. A location consist in "
243
+ "the name of a variation axis, followed by '=' and a number. E.g.: "
244
+ "wght=700 wdth=80. The default is the location of the base master.",
245
+ )
246
+
247
+ options = parser.parse_args(args)
248
+
249
+ fontNumber = int(options.y) if options.y is not None else 0
250
+
251
+ font = TTFont(options.font, fontNumber=fontNumber)
252
+ text = options.text
253
+ glyphs = options.glyphs
254
+
255
+ location = {}
256
+ for tag_v in options.variations.split():
257
+ fields = tag_v.split("=")
258
+ tag = fields[0].strip()
259
+ v = float(fields[1])
260
+ location[tag] = v
261
+
262
+ hhea = font["hhea"]
263
+ ascent, descent = hhea.ascent, hhea.descent
264
+
265
+ glyphset = font.getGlyphSet(location=location)
266
+ cmap = font["cmap"].getBestCmap()
267
+
268
+ if glyphs is not None and text is not None:
269
+ raise ValueError("Options --glyphs and --text are exclusive")
270
+
271
+ if glyphs is None:
272
+ glyphs = " ".join(cmap[ord(u)] for u in text)
273
+
274
+ glyphs = glyphs.split()
275
+
276
+ s = ""
277
+ width = 0
278
+ for g in glyphs:
279
+ glyph = glyphset[g]
280
+
281
+ pen = SVGPathPen(glyphset)
282
+ glyph.draw(pen)
283
+ commands = pen.getCommands()
284
+
285
+ s += '<g transform="translate(%d %d) scale(1 -1)"><path d="%s"/></g>\n' % (
286
+ width,
287
+ ascent,
288
+ commands,
289
+ )
290
+
291
+ width += glyph.width
292
+
293
+ print('<?xml version="1.0" encoding="UTF-8"?>')
294
+ print(
295
+ '<svg width="%d" height="%d" xmlns="http://www.w3.org/2000/svg">'
296
+ % (width, ascent - descent)
297
+ )
298
+ print(s, end="")
299
+ print("</svg>")
300
+
301
+
302
+ if __name__ == "__main__":
303
+ import sys
304
+
305
+ if len(sys.argv) == 1:
306
+ import doctest
307
+
308
+ sys.exit(doctest.testmod().failed)
309
+
310
+ sys.exit(main())
evalkit_tf437/lib/python3.10/site-packages/fontTools/tfmLib.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module for reading TFM (TeX Font Metrics) files.
2
+
3
+ The TFM format is described in the TFtoPL WEB source code, whose typeset form
4
+ can be found on `CTAN <http://mirrors.ctan.org/info/knuth-pdf/texware/tftopl.pdf>`_.
5
+
6
+ >>> from fontTools.tfmLib import TFM
7
+ >>> tfm = TFM("Tests/tfmLib/data/cmr10.tfm")
8
+ >>>
9
+ >>> # Accessing an attribute gets you metadata.
10
+ >>> tfm.checksum
11
+ 1274110073
12
+ >>> tfm.designsize
13
+ 10.0
14
+ >>> tfm.codingscheme
15
+ 'TeX text'
16
+ >>> tfm.family
17
+ 'CMR'
18
+ >>> tfm.seven_bit_safe_flag
19
+ False
20
+ >>> tfm.face
21
+ 234
22
+ >>> tfm.extraheader
23
+ {}
24
+ >>> tfm.fontdimens
25
+ {'SLANT': 0.0, 'SPACE': 0.33333396911621094, 'STRETCH': 0.16666698455810547, 'SHRINK': 0.11111164093017578, 'XHEIGHT': 0.4305553436279297, 'QUAD': 1.0000028610229492, 'EXTRASPACE': 0.11111164093017578}
26
+ >>> # Accessing a character gets you its metrics.
27
+ >>> # “width” is always available, other metrics are available only when
28
+ >>> # applicable. All values are relative to “designsize”.
29
+ >>> tfm.chars[ord("g")]
30
+ {'width': 0.5000019073486328, 'height': 0.4305553436279297, 'depth': 0.1944446563720703, 'italic': 0.013888359069824219}
31
+ >>> # Kerning and ligature can be accessed as well.
32
+ >>> tfm.kerning[ord("c")]
33
+ {104: -0.02777862548828125, 107: -0.02777862548828125}
34
+ >>> tfm.ligatures[ord("f")]
35
+ {105: ('LIG', 12), 102: ('LIG', 11), 108: ('LIG', 13)}
36
+ """
37
+
38
+ from types import SimpleNamespace
39
+
40
+ from fontTools.misc.sstruct import calcsize, unpack, unpack2
41
+
42
+ SIZES_FORMAT = """
43
+ >
44
+ lf: h # length of the entire file, in words
45
+ lh: h # length of the header data, in words
46
+ bc: h # smallest character code in the font
47
+ ec: h # largest character code in the font
48
+ nw: h # number of words in the width table
49
+ nh: h # number of words in the height table
50
+ nd: h # number of words in the depth table
51
+ ni: h # number of words in the italic correction table
52
+ nl: h # number of words in the ligature/kern table
53
+ nk: h # number of words in the kern table
54
+ ne: h # number of words in the extensible character table
55
+ np: h # number of font parameter words
56
+ """
57
+
58
+ SIZES_SIZE = calcsize(SIZES_FORMAT)
59
+
60
+ FIXED_FORMAT = "12.20F"
61
+
62
+ HEADER_FORMAT1 = f"""
63
+ >
64
+ checksum: L
65
+ designsize: {FIXED_FORMAT}
66
+ """
67
+
68
+ HEADER_FORMAT2 = f"""
69
+ {HEADER_FORMAT1}
70
+ codingscheme: 40p
71
+ """
72
+
73
+ HEADER_FORMAT3 = f"""
74
+ {HEADER_FORMAT2}
75
+ family: 20p
76
+ """
77
+
78
+ HEADER_FORMAT4 = f"""
79
+ {HEADER_FORMAT3}
80
+ seven_bit_safe_flag: ?
81
+ ignored: x
82
+ ignored: x
83
+ face: B
84
+ """
85
+
86
+ HEADER_SIZE1 = calcsize(HEADER_FORMAT1)
87
+ HEADER_SIZE2 = calcsize(HEADER_FORMAT2)
88
+ HEADER_SIZE3 = calcsize(HEADER_FORMAT3)
89
+ HEADER_SIZE4 = calcsize(HEADER_FORMAT4)
90
+
91
+ LIG_KERN_COMMAND = """
92
+ >
93
+ skip_byte: B
94
+ next_char: B
95
+ op_byte: B
96
+ remainder: B
97
+ """
98
+
99
+ BASE_PARAMS = [
100
+ "SLANT",
101
+ "SPACE",
102
+ "STRETCH",
103
+ "SHRINK",
104
+ "XHEIGHT",
105
+ "QUAD",
106
+ "EXTRASPACE",
107
+ ]
108
+
109
+ MATHSY_PARAMS = [
110
+ "NUM1",
111
+ "NUM2",
112
+ "NUM3",
113
+ "DENOM1",
114
+ "DENOM2",
115
+ "SUP1",
116
+ "SUP2",
117
+ "SUP3",
118
+ "SUB1",
119
+ "SUB2",
120
+ "SUPDROP",
121
+ "SUBDROP",
122
+ "DELIM1",
123
+ "DELIM2",
124
+ "AXISHEIGHT",
125
+ ]
126
+
127
+ MATHEX_PARAMS = [
128
+ "DEFAULTRULETHICKNESS",
129
+ "BIGOPSPACING1",
130
+ "BIGOPSPACING2",
131
+ "BIGOPSPACING3",
132
+ "BIGOPSPACING4",
133
+ "BIGOPSPACING5",
134
+ ]
135
+
136
+ VANILLA = 0
137
+ MATHSY = 1
138
+ MATHEX = 2
139
+
140
+ UNREACHABLE = 0
141
+ PASSTHROUGH = 1
142
+ ACCESSABLE = 2
143
+
144
+ NO_TAG = 0
145
+ LIG_TAG = 1
146
+ LIST_TAG = 2
147
+ EXT_TAG = 3
148
+
149
+ STOP_FLAG = 128
150
+ KERN_FLAG = 128
151
+
152
+
153
+ class TFMException(Exception):
154
+ def __init__(self, message):
155
+ super().__init__(message)
156
+
157
+
158
+ class TFM:
159
+ def __init__(self, file):
160
+ self._read(file)
161
+
162
+ def __repr__(self):
163
+ return (
164
+ f"<TFM"
165
+ f" for {self.family}"
166
+ f" in {self.codingscheme}"
167
+ f" at {self.designsize:g}pt>"
168
+ )
169
+
170
+ def _read(self, file):
171
+ if hasattr(file, "read"):
172
+ data = file.read()
173
+ else:
174
+ with open(file, "rb") as fp:
175
+ data = fp.read()
176
+
177
+ self._data = data
178
+
179
+ if len(data) < SIZES_SIZE:
180
+ raise TFMException("Too short input file")
181
+
182
+ sizes = SimpleNamespace()
183
+ unpack2(SIZES_FORMAT, data, sizes)
184
+
185
+ # Do some file structure sanity checks.
186
+ # TeX and TFtoPL do additional functional checks and might even correct
187
+ # “errors” in the input file, but we instead try to output the file as
188
+ # it is as long as it is parsable, even if the data make no sense.
189
+
190
+ if sizes.lf < 0:
191
+ raise TFMException("The file claims to have negative or zero length!")
192
+
193
+ if len(data) < sizes.lf * 4:
194
+ raise TFMException("The file has fewer bytes than it claims!")
195
+
196
+ for name, length in vars(sizes).items():
197
+ if length < 0:
198
+ raise TFMException("The subfile size: '{name}' is negative!")
199
+
200
+ if sizes.lh < 2:
201
+ raise TFMException(f"The header length is only {sizes.lh}!")
202
+
203
+ if sizes.bc > sizes.ec + 1 or sizes.ec > 255:
204
+ raise TFMException(
205
+ f"The character code range {sizes.bc}..{sizes.ec} is illegal!"
206
+ )
207
+
208
+ if sizes.nw == 0 or sizes.nh == 0 or sizes.nd == 0 or sizes.ni == 0:
209
+ raise TFMException("Incomplete subfiles for character dimensions!")
210
+
211
+ if sizes.ne > 256:
212
+ raise TFMException(f"There are {ne} extensible recipes!")
213
+
214
+ if sizes.lf != (
215
+ 6
216
+ + sizes.lh
217
+ + (sizes.ec - sizes.bc + 1)
218
+ + sizes.nw
219
+ + sizes.nh
220
+ + sizes.nd
221
+ + sizes.ni
222
+ + sizes.nl
223
+ + sizes.nk
224
+ + sizes.ne
225
+ + sizes.np
226
+ ):
227
+ raise TFMException("Subfile sizes don’t add up to the stated total")
228
+
229
+ # Subfile offsets, used in the helper function below. These all are
230
+ # 32-bit word offsets not 8-bit byte offsets.
231
+ char_base = 6 + sizes.lh - sizes.bc
232
+ width_base = char_base + sizes.ec + 1
233
+ height_base = width_base + sizes.nw
234
+ depth_base = height_base + sizes.nh
235
+ italic_base = depth_base + sizes.nd
236
+ lig_kern_base = italic_base + sizes.ni
237
+ kern_base = lig_kern_base + sizes.nl
238
+ exten_base = kern_base + sizes.nk
239
+ param_base = exten_base + sizes.ne
240
+
241
+ # Helper functions for accessing individual data. If this looks
242
+ # nonidiomatic Python, I blame the effect of reading the literate WEB
243
+ # documentation of TFtoPL.
244
+ def char_info(c):
245
+ return 4 * (char_base + c)
246
+
247
+ def width_index(c):
248
+ return data[char_info(c)]
249
+
250
+ def noneexistent(c):
251
+ return c < sizes.bc or c > sizes.ec or width_index(c) == 0
252
+
253
+ def height_index(c):
254
+ return data[char_info(c) + 1] // 16
255
+
256
+ def depth_index(c):
257
+ return data[char_info(c) + 1] % 16
258
+
259
+ def italic_index(c):
260
+ return data[char_info(c) + 2] // 4
261
+
262
+ def tag(c):
263
+ return data[char_info(c) + 2] % 4
264
+
265
+ def remainder(c):
266
+ return data[char_info(c) + 3]
267
+
268
+ def width(c):
269
+ r = 4 * (width_base + width_index(c))
270
+ return read_fixed(r, "v")["v"]
271
+
272
+ def height(c):
273
+ r = 4 * (height_base + height_index(c))
274
+ return read_fixed(r, "v")["v"]
275
+
276
+ def depth(c):
277
+ r = 4 * (depth_base + depth_index(c))
278
+ return read_fixed(r, "v")["v"]
279
+
280
+ def italic(c):
281
+ r = 4 * (italic_base + italic_index(c))
282
+ return read_fixed(r, "v")["v"]
283
+
284
+ def exten(c):
285
+ return 4 * (exten_base + remainder(c))
286
+
287
+ def lig_step(i):
288
+ return 4 * (lig_kern_base + i)
289
+
290
+ def lig_kern_command(i):
291
+ command = SimpleNamespace()
292
+ unpack2(LIG_KERN_COMMAND, data[i:], command)
293
+ return command
294
+
295
+ def kern(i):
296
+ r = 4 * (kern_base + i)
297
+ return read_fixed(r, "v")["v"]
298
+
299
+ def param(i):
300
+ return 4 * (param_base + i)
301
+
302
+ def read_fixed(index, key, obj=None):
303
+ ret = unpack2(f">;{key}:{FIXED_FORMAT}", data[index:], obj)
304
+ return ret[0]
305
+
306
+ # Set all attributes to empty values regardless of the header size.
307
+ unpack(HEADER_FORMAT4, [0] * HEADER_SIZE4, self)
308
+
309
+ offset = 24
310
+ length = sizes.lh * 4
311
+ self.extraheader = {}
312
+ if length >= HEADER_SIZE4:
313
+ rest = unpack2(HEADER_FORMAT4, data[offset:], self)[1]
314
+ if self.face < 18:
315
+ s = self.face % 2
316
+ b = self.face // 2
317
+ self.face = "MBL"[b % 3] + "RI"[s] + "RCE"[b // 3]
318
+ for i in range(sizes.lh - HEADER_SIZE4 // 4):
319
+ rest = unpack2(f">;HEADER{i + 18}:l", rest, self.extraheader)[1]
320
+ elif length >= HEADER_SIZE3:
321
+ unpack2(HEADER_FORMAT3, data[offset:], self)
322
+ elif length >= HEADER_SIZE2:
323
+ unpack2(HEADER_FORMAT2, data[offset:], self)
324
+ elif length >= HEADER_SIZE1:
325
+ unpack2(HEADER_FORMAT1, data[offset:], self)
326
+
327
+ self.fonttype = VANILLA
328
+ scheme = self.codingscheme.upper()
329
+ if scheme.startswith("TEX MATH SY"):
330
+ self.fonttype = MATHSY
331
+ elif scheme.startswith("TEX MATH EX"):
332
+ self.fonttype = MATHEX
333
+
334
+ self.fontdimens = {}
335
+ for i in range(sizes.np):
336
+ name = f"PARAMETER{i+1}"
337
+ if i <= 6:
338
+ name = BASE_PARAMS[i]
339
+ elif self.fonttype == MATHSY and i <= 21:
340
+ name = MATHSY_PARAMS[i - 7]
341
+ elif self.fonttype == MATHEX and i <= 12:
342
+ name = MATHEX_PARAMS[i - 7]
343
+ read_fixed(param(i), name, self.fontdimens)
344
+
345
+ lig_kern_map = {}
346
+ self.right_boundary_char = None
347
+ self.left_boundary_char = None
348
+ if sizes.nl > 0:
349
+ cmd = lig_kern_command(lig_step(0))
350
+ if cmd.skip_byte == 255:
351
+ self.right_boundary_char = cmd.next_char
352
+
353
+ cmd = lig_kern_command(lig_step((sizes.nl - 1)))
354
+ if cmd.skip_byte == 255:
355
+ self.left_boundary_char = 256
356
+ r = 256 * cmd.op_byte + cmd.remainder
357
+ lig_kern_map[self.left_boundary_char] = r
358
+
359
+ self.chars = {}
360
+ for c in range(sizes.bc, sizes.ec + 1):
361
+ if width_index(c) > 0:
362
+ self.chars[c] = info = {}
363
+ info["width"] = width(c)
364
+ if height_index(c) > 0:
365
+ info["height"] = height(c)
366
+ if depth_index(c) > 0:
367
+ info["depth"] = depth(c)
368
+ if italic_index(c) > 0:
369
+ info["italic"] = italic(c)
370
+ char_tag = tag(c)
371
+ if char_tag == NO_TAG:
372
+ pass
373
+ elif char_tag == LIG_TAG:
374
+ lig_kern_map[c] = remainder(c)
375
+ elif char_tag == LIST_TAG:
376
+ info["nextlarger"] = remainder(c)
377
+ elif char_tag == EXT_TAG:
378
+ info["varchar"] = varchar = {}
379
+ for i in range(4):
380
+ part = data[exten(c) + i]
381
+ if i == 3 or part > 0:
382
+ name = "rep"
383
+ if i == 0:
384
+ name = "top"
385
+ elif i == 1:
386
+ name = "mid"
387
+ elif i == 2:
388
+ name = "bot"
389
+ if noneexistent(part):
390
+ varchar[name] = c
391
+ else:
392
+ varchar[name] = part
393
+
394
+ self.ligatures = {}
395
+ self.kerning = {}
396
+ for c, i in sorted(lig_kern_map.items()):
397
+ cmd = lig_kern_command(lig_step(i))
398
+ if cmd.skip_byte > STOP_FLAG:
399
+ i = 256 * cmd.op_byte + cmd.remainder
400
+
401
+ while i < sizes.nl:
402
+ cmd = lig_kern_command(lig_step(i))
403
+ if cmd.skip_byte > STOP_FLAG:
404
+ pass
405
+ else:
406
+ if cmd.op_byte >= KERN_FLAG:
407
+ r = 256 * (cmd.op_byte - KERN_FLAG) + cmd.remainder
408
+ self.kerning.setdefault(c, {})[cmd.next_char] = kern(r)
409
+ else:
410
+ r = cmd.op_byte
411
+ if r == 4 or (r > 7 and r != 11):
412
+ # Ligature step with nonstandard code, we output
413
+ # the code verbatim.
414
+ lig = r
415
+ else:
416
+ lig = ""
417
+ if r % 4 > 1:
418
+ lig += "/"
419
+ lig += "LIG"
420
+ if r % 2 != 0:
421
+ lig += "/"
422
+ while r > 3:
423
+ lig += ">"
424
+ r -= 4
425
+ self.ligatures.setdefault(c, {})[cmd.next_char] = (
426
+ lig,
427
+ cmd.remainder,
428
+ )
429
+
430
+ if cmd.skip_byte >= STOP_FLAG:
431
+ break
432
+ i += cmd.skip_byte + 1
433
+
434
+
435
+ if __name__ == "__main__":
436
+ import sys
437
+
438
+ tfm = TFM(sys.argv[1])
439
+ print(
440
+ "\n".join(
441
+ x
442
+ for x in [
443
+ f"tfm.checksum={tfm.checksum}",
444
+ f"tfm.designsize={tfm.designsize}",
445
+ f"tfm.codingscheme={tfm.codingscheme}",
446
+ f"tfm.fonttype={tfm.fonttype}",
447
+ f"tfm.family={tfm.family}",
448
+ f"tfm.seven_bit_safe_flag={tfm.seven_bit_safe_flag}",
449
+ f"tfm.face={tfm.face}",
450
+ f"tfm.extraheader={tfm.extraheader}",
451
+ f"tfm.fontdimens={tfm.fontdimens}",
452
+ f"tfm.right_boundary_char={tfm.right_boundary_char}",
453
+ f"tfm.left_boundary_char={tfm.left_boundary_char}",
454
+ f"tfm.kerning={tfm.kerning}",
455
+ f"tfm.ligatures={tfm.ligatures}",
456
+ f"tfm.chars={tfm.chars}",
457
+ ]
458
+ )
459
+ )
460
+ print(tfm)
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """fontTools.ttLib -- a package for dealing with TrueType fonts."""
2
+
3
+ from fontTools.misc.loggingTools import deprecateFunction
4
+ import logging
5
+
6
+
7
+ log = logging.getLogger(__name__)
8
+
9
+
10
+ class TTLibError(Exception):
11
+ pass
12
+
13
+
14
+ class TTLibFileIsCollectionError(TTLibError):
15
+ pass
16
+
17
+
18
+ @deprecateFunction("use logging instead", category=DeprecationWarning)
19
+ def debugmsg(msg):
20
+ import time
21
+
22
+ print(msg + time.strftime(" (%H:%M:%S)", time.localtime(time.time())))
23
+
24
+
25
+ from fontTools.ttLib.ttFont import *
26
+ from fontTools.ttLib.ttCollection import TTCollection
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/macUtils.cpython-310.pyc ADDED
Binary file (1.97 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/scaleUpem.cpython-310.pyc ADDED
Binary file (9.84 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/ttGlyphSet.cpython-310.pyc ADDED
Binary file (14.8 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/DefaultTable.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc.textTools import Tag
2
+ from fontTools.ttLib import getClassTag
3
+
4
+
5
+ class DefaultTable(object):
6
+ dependencies = []
7
+
8
+ def __init__(self, tag=None):
9
+ if tag is None:
10
+ tag = getClassTag(self.__class__)
11
+ self.tableTag = Tag(tag)
12
+
13
+ def decompile(self, data, ttFont):
14
+ self.data = data
15
+
16
+ def compile(self, ttFont):
17
+ return self.data
18
+
19
+ def toXML(self, writer, ttFont, **kwargs):
20
+ if hasattr(self, "ERROR"):
21
+ writer.comment("An error occurred during the decompilation of this table")
22
+ writer.newline()
23
+ writer.comment(self.ERROR)
24
+ writer.newline()
25
+ writer.begintag("hexdata")
26
+ writer.newline()
27
+ writer.dumphex(self.compile(ttFont))
28
+ writer.endtag("hexdata")
29
+ writer.newline()
30
+
31
+ def fromXML(self, name, attrs, content, ttFont):
32
+ from fontTools.misc.textTools import readHex
33
+ from fontTools import ttLib
34
+
35
+ if name != "hexdata":
36
+ raise ttLib.TTLibError("can't handle '%s' element" % name)
37
+ self.decompile(readHex(content), ttFont)
38
+
39
+ def __repr__(self):
40
+ return "<'%s' table at %x>" % (self.tableTag, id(self))
41
+
42
+ def __eq__(self, other):
43
+ if type(self) != type(other):
44
+ return NotImplemented
45
+ return self.__dict__ == other.__dict__
46
+
47
+ def __ne__(self, other):
48
+ result = self.__eq__(other)
49
+ return result if result is NotImplemented else not result
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/G__l_o_c.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc import sstruct
2
+ from fontTools.misc.textTools import safeEval
3
+ from . import DefaultTable
4
+ import array
5
+ import sys
6
+
7
+
8
+ Gloc_header = """
9
+ > # big endian
10
+ version: 16.16F # Table version
11
+ flags: H # bit 0: 1=long format, 0=short format
12
+ # bit 1: 1=attribute names, 0=no names
13
+ numAttribs: H # NUmber of attributes
14
+ """
15
+
16
+
17
+ class table_G__l_o_c(DefaultTable.DefaultTable):
18
+ """
19
+ Support Graphite Gloc tables
20
+ """
21
+
22
+ dependencies = ["Glat"]
23
+
24
+ def __init__(self, tag=None):
25
+ DefaultTable.DefaultTable.__init__(self, tag)
26
+ self.attribIds = None
27
+ self.numAttribs = 0
28
+
29
+ def decompile(self, data, ttFont):
30
+ _, data = sstruct.unpack2(Gloc_header, data, self)
31
+ flags = self.flags
32
+ del self.flags
33
+ self.locations = array.array("I" if flags & 1 else "H")
34
+ self.locations.frombytes(data[: len(data) - self.numAttribs * (flags & 2)])
35
+ if sys.byteorder != "big":
36
+ self.locations.byteswap()
37
+ self.attribIds = array.array("H")
38
+ if flags & 2:
39
+ self.attribIds.frombytes(data[-self.numAttribs * 2 :])
40
+ if sys.byteorder != "big":
41
+ self.attribIds.byteswap()
42
+
43
+ def compile(self, ttFont):
44
+ data = sstruct.pack(
45
+ Gloc_header,
46
+ dict(
47
+ version=1.0,
48
+ flags=(bool(self.attribIds) << 1) + (self.locations.typecode == "I"),
49
+ numAttribs=self.numAttribs,
50
+ ),
51
+ )
52
+ if sys.byteorder != "big":
53
+ self.locations.byteswap()
54
+ data += self.locations.tobytes()
55
+ if sys.byteorder != "big":
56
+ self.locations.byteswap()
57
+ if self.attribIds:
58
+ if sys.byteorder != "big":
59
+ self.attribIds.byteswap()
60
+ data += self.attribIds.tobytes()
61
+ if sys.byteorder != "big":
62
+ self.attribIds.byteswap()
63
+ return data
64
+
65
+ def set(self, locations):
66
+ long_format = max(locations) >= 65536
67
+ self.locations = array.array("I" if long_format else "H", locations)
68
+
69
+ def toXML(self, writer, ttFont):
70
+ writer.simpletag("attributes", number=self.numAttribs)
71
+ writer.newline()
72
+
73
+ def fromXML(self, name, attrs, content, ttFont):
74
+ if name == "attributes":
75
+ self.numAttribs = int(safeEval(attrs["number"]))
76
+
77
+ def __getitem__(self, index):
78
+ return self.locations[index]
79
+
80
+ def __len__(self):
81
+ return len(self.locations)
82
+
83
+ def __iter__(self):
84
+ return iter(self.locations)
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/L_T_S_H_.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc.textTools import safeEval
2
+ from . import DefaultTable
3
+ import struct
4
+ import array
5
+
6
+ # XXX I've lowered the strictness, to make sure Apple's own Chicago
7
+ # XXX gets through. They're looking into it, I hope to raise the standards
8
+ # XXX back to normal eventually.
9
+
10
+
11
+ class table_L_T_S_H_(DefaultTable.DefaultTable):
12
+ def decompile(self, data, ttFont):
13
+ version, numGlyphs = struct.unpack(">HH", data[:4])
14
+ data = data[4:]
15
+ assert version == 0, "unknown version: %s" % version
16
+ assert (len(data) % numGlyphs) < 4, "numGlyphs doesn't match data length"
17
+ # ouch: the assertion is not true in Chicago!
18
+ # assert numGlyphs == ttFont['maxp'].numGlyphs
19
+ yPels = array.array("B")
20
+ yPels.frombytes(data)
21
+ self.yPels = {}
22
+ for i in range(numGlyphs):
23
+ self.yPels[ttFont.getGlyphName(i)] = yPels[i]
24
+
25
+ def compile(self, ttFont):
26
+ version = 0
27
+ names = list(self.yPels.keys())
28
+ numGlyphs = len(names)
29
+ yPels = [0] * numGlyphs
30
+ # ouch: the assertion is not true in Chicago!
31
+ # assert len(self.yPels) == ttFont['maxp'].numGlyphs == numGlyphs
32
+ for name in names:
33
+ yPels[ttFont.getGlyphID(name)] = self.yPels[name]
34
+ yPels = array.array("B", yPels)
35
+ return struct.pack(">HH", version, numGlyphs) + yPels.tobytes()
36
+
37
+ def toXML(self, writer, ttFont):
38
+ names = sorted(self.yPels.keys())
39
+ for name in names:
40
+ writer.simpletag("yPel", name=name, value=self.yPels[name])
41
+ writer.newline()
42
+
43
+ def fromXML(self, name, attrs, content, ttFont):
44
+ if not hasattr(self, "yPels"):
45
+ self.yPels = {}
46
+ if name != "yPel":
47
+ return # ignore unknown tags
48
+ self.yPels[attrs["name"]] = safeEval(attrs["value"])
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/O_S_2f_2.py ADDED
@@ -0,0 +1,745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc import sstruct
2
+ from fontTools.misc.roundTools import otRound
3
+ from fontTools.misc.textTools import safeEval, num2binary, binary2num
4
+ from fontTools.ttLib.tables import DefaultTable
5
+ import bisect
6
+ import logging
7
+
8
+
9
+ log = logging.getLogger(__name__)
10
+
11
+ # panose classification
12
+
13
+ panoseFormat = """
14
+ bFamilyType: B
15
+ bSerifStyle: B
16
+ bWeight: B
17
+ bProportion: B
18
+ bContrast: B
19
+ bStrokeVariation: B
20
+ bArmStyle: B
21
+ bLetterForm: B
22
+ bMidline: B
23
+ bXHeight: B
24
+ """
25
+
26
+
27
+ class Panose(object):
28
+ def __init__(self, **kwargs):
29
+ _, names, _ = sstruct.getformat(panoseFormat)
30
+ for name in names:
31
+ setattr(self, name, kwargs.pop(name, 0))
32
+ for k in kwargs:
33
+ raise TypeError(f"Panose() got an unexpected keyword argument {k!r}")
34
+
35
+ def toXML(self, writer, ttFont):
36
+ formatstring, names, fixes = sstruct.getformat(panoseFormat)
37
+ for name in names:
38
+ writer.simpletag(name, value=getattr(self, name))
39
+ writer.newline()
40
+
41
+ def fromXML(self, name, attrs, content, ttFont):
42
+ setattr(self, name, safeEval(attrs["value"]))
43
+
44
+
45
+ # 'sfnt' OS/2 and Windows Metrics table - 'OS/2'
46
+
47
+ OS2_format_0 = """
48
+ > # big endian
49
+ version: H # version
50
+ xAvgCharWidth: h # average character width
51
+ usWeightClass: H # degree of thickness of strokes
52
+ usWidthClass: H # aspect ratio
53
+ fsType: H # type flags
54
+ ySubscriptXSize: h # subscript horizontal font size
55
+ ySubscriptYSize: h # subscript vertical font size
56
+ ySubscriptXOffset: h # subscript x offset
57
+ ySubscriptYOffset: h # subscript y offset
58
+ ySuperscriptXSize: h # superscript horizontal font size
59
+ ySuperscriptYSize: h # superscript vertical font size
60
+ ySuperscriptXOffset: h # superscript x offset
61
+ ySuperscriptYOffset: h # superscript y offset
62
+ yStrikeoutSize: h # strikeout size
63
+ yStrikeoutPosition: h # strikeout position
64
+ sFamilyClass: h # font family class and subclass
65
+ panose: 10s # panose classification number
66
+ ulUnicodeRange1: L # character range
67
+ ulUnicodeRange2: L # character range
68
+ ulUnicodeRange3: L # character range
69
+ ulUnicodeRange4: L # character range
70
+ achVendID: 4s # font vendor identification
71
+ fsSelection: H # font selection flags
72
+ usFirstCharIndex: H # first unicode character index
73
+ usLastCharIndex: H # last unicode character index
74
+ sTypoAscender: h # typographic ascender
75
+ sTypoDescender: h # typographic descender
76
+ sTypoLineGap: h # typographic line gap
77
+ usWinAscent: H # Windows ascender
78
+ usWinDescent: H # Windows descender
79
+ """
80
+
81
+ OS2_format_1_addition = """
82
+ ulCodePageRange1: L
83
+ ulCodePageRange2: L
84
+ """
85
+
86
+ OS2_format_2_addition = (
87
+ OS2_format_1_addition
88
+ + """
89
+ sxHeight: h
90
+ sCapHeight: h
91
+ usDefaultChar: H
92
+ usBreakChar: H
93
+ usMaxContext: H
94
+ """
95
+ )
96
+
97
+ OS2_format_5_addition = (
98
+ OS2_format_2_addition
99
+ + """
100
+ usLowerOpticalPointSize: H
101
+ usUpperOpticalPointSize: H
102
+ """
103
+ )
104
+
105
+ bigendian = " > # big endian\n"
106
+
107
+ OS2_format_1 = OS2_format_0 + OS2_format_1_addition
108
+ OS2_format_2 = OS2_format_0 + OS2_format_2_addition
109
+ OS2_format_5 = OS2_format_0 + OS2_format_5_addition
110
+ OS2_format_1_addition = bigendian + OS2_format_1_addition
111
+ OS2_format_2_addition = bigendian + OS2_format_2_addition
112
+ OS2_format_5_addition = bigendian + OS2_format_5_addition
113
+
114
+
115
+ class table_O_S_2f_2(DefaultTable.DefaultTable):
116
+ """the OS/2 table"""
117
+
118
+ dependencies = ["head"]
119
+
120
+ def decompile(self, data, ttFont):
121
+ dummy, data = sstruct.unpack2(OS2_format_0, data, self)
122
+
123
+ if self.version == 1:
124
+ dummy, data = sstruct.unpack2(OS2_format_1_addition, data, self)
125
+ elif self.version in (2, 3, 4):
126
+ dummy, data = sstruct.unpack2(OS2_format_2_addition, data, self)
127
+ elif self.version == 5:
128
+ dummy, data = sstruct.unpack2(OS2_format_5_addition, data, self)
129
+ self.usLowerOpticalPointSize /= 20
130
+ self.usUpperOpticalPointSize /= 20
131
+ elif self.version != 0:
132
+ from fontTools import ttLib
133
+
134
+ raise ttLib.TTLibError(
135
+ "unknown format for OS/2 table: version %s" % self.version
136
+ )
137
+ if len(data):
138
+ log.warning("too much 'OS/2' table data")
139
+
140
+ self.panose = sstruct.unpack(panoseFormat, self.panose, Panose())
141
+
142
+ def compile(self, ttFont):
143
+ self.updateFirstAndLastCharIndex(ttFont)
144
+ panose = self.panose
145
+ head = ttFont["head"]
146
+ if (self.fsSelection & 1) and not (head.macStyle & 1 << 1):
147
+ log.warning(
148
+ "fsSelection bit 0 (italic) and "
149
+ "head table macStyle bit 1 (italic) should match"
150
+ )
151
+ if (self.fsSelection & 1 << 5) and not (head.macStyle & 1):
152
+ log.warning(
153
+ "fsSelection bit 5 (bold) and "
154
+ "head table macStyle bit 0 (bold) should match"
155
+ )
156
+ if (self.fsSelection & 1 << 6) and (self.fsSelection & 1 + (1 << 5)):
157
+ log.warning(
158
+ "fsSelection bit 6 (regular) is set, "
159
+ "bits 0 (italic) and 5 (bold) must be clear"
160
+ )
161
+ if self.version < 4 and self.fsSelection & 0b1110000000:
162
+ log.warning(
163
+ "fsSelection bits 7, 8 and 9 are only defined in "
164
+ "OS/2 table version 4 and up: version %s",
165
+ self.version,
166
+ )
167
+ self.panose = sstruct.pack(panoseFormat, self.panose)
168
+ if self.version == 0:
169
+ data = sstruct.pack(OS2_format_0, self)
170
+ elif self.version == 1:
171
+ data = sstruct.pack(OS2_format_1, self)
172
+ elif self.version in (2, 3, 4):
173
+ data = sstruct.pack(OS2_format_2, self)
174
+ elif self.version == 5:
175
+ d = self.__dict__.copy()
176
+ d["usLowerOpticalPointSize"] = round(self.usLowerOpticalPointSize * 20)
177
+ d["usUpperOpticalPointSize"] = round(self.usUpperOpticalPointSize * 20)
178
+ data = sstruct.pack(OS2_format_5, d)
179
+ else:
180
+ from fontTools import ttLib
181
+
182
+ raise ttLib.TTLibError(
183
+ "unknown format for OS/2 table: version %s" % self.version
184
+ )
185
+ self.panose = panose
186
+ return data
187
+
188
+ def toXML(self, writer, ttFont):
189
+ writer.comment(
190
+ "The fields 'usFirstCharIndex' and 'usLastCharIndex'\n"
191
+ "will be recalculated by the compiler"
192
+ )
193
+ writer.newline()
194
+ if self.version == 1:
195
+ format = OS2_format_1
196
+ elif self.version in (2, 3, 4):
197
+ format = OS2_format_2
198
+ elif self.version == 5:
199
+ format = OS2_format_5
200
+ else:
201
+ format = OS2_format_0
202
+ formatstring, names, fixes = sstruct.getformat(format)
203
+ for name in names:
204
+ value = getattr(self, name)
205
+ if name == "panose":
206
+ writer.begintag("panose")
207
+ writer.newline()
208
+ value.toXML(writer, ttFont)
209
+ writer.endtag("panose")
210
+ elif name in (
211
+ "ulUnicodeRange1",
212
+ "ulUnicodeRange2",
213
+ "ulUnicodeRange3",
214
+ "ulUnicodeRange4",
215
+ "ulCodePageRange1",
216
+ "ulCodePageRange2",
217
+ ):
218
+ writer.simpletag(name, value=num2binary(value))
219
+ elif name in ("fsType", "fsSelection"):
220
+ writer.simpletag(name, value=num2binary(value, 16))
221
+ elif name == "achVendID":
222
+ writer.simpletag(name, value=repr(value)[1:-1])
223
+ else:
224
+ writer.simpletag(name, value=value)
225
+ writer.newline()
226
+
227
+ def fromXML(self, name, attrs, content, ttFont):
228
+ if name == "panose":
229
+ self.panose = panose = Panose()
230
+ for element in content:
231
+ if isinstance(element, tuple):
232
+ name, attrs, content = element
233
+ panose.fromXML(name, attrs, content, ttFont)
234
+ elif name in (
235
+ "ulUnicodeRange1",
236
+ "ulUnicodeRange2",
237
+ "ulUnicodeRange3",
238
+ "ulUnicodeRange4",
239
+ "ulCodePageRange1",
240
+ "ulCodePageRange2",
241
+ "fsType",
242
+ "fsSelection",
243
+ ):
244
+ setattr(self, name, binary2num(attrs["value"]))
245
+ elif name == "achVendID":
246
+ setattr(self, name, safeEval("'''" + attrs["value"] + "'''"))
247
+ else:
248
+ setattr(self, name, safeEval(attrs["value"]))
249
+
250
+ def updateFirstAndLastCharIndex(self, ttFont):
251
+ if "cmap" not in ttFont:
252
+ return
253
+ codes = set()
254
+ for table in getattr(ttFont["cmap"], "tables", []):
255
+ if table.isUnicode():
256
+ codes.update(table.cmap.keys())
257
+ if codes:
258
+ minCode = min(codes)
259
+ maxCode = max(codes)
260
+ # USHORT cannot hold codepoints greater than 0xFFFF
261
+ self.usFirstCharIndex = min(0xFFFF, minCode)
262
+ self.usLastCharIndex = min(0xFFFF, maxCode)
263
+
264
+ # misspelled attributes kept for legacy reasons
265
+
266
+ @property
267
+ def usMaxContex(self):
268
+ return self.usMaxContext
269
+
270
+ @usMaxContex.setter
271
+ def usMaxContex(self, value):
272
+ self.usMaxContext = value
273
+
274
+ @property
275
+ def fsFirstCharIndex(self):
276
+ return self.usFirstCharIndex
277
+
278
+ @fsFirstCharIndex.setter
279
+ def fsFirstCharIndex(self, value):
280
+ self.usFirstCharIndex = value
281
+
282
+ @property
283
+ def fsLastCharIndex(self):
284
+ return self.usLastCharIndex
285
+
286
+ @fsLastCharIndex.setter
287
+ def fsLastCharIndex(self, value):
288
+ self.usLastCharIndex = value
289
+
290
+ def getUnicodeRanges(self):
291
+ """Return the set of 'ulUnicodeRange*' bits currently enabled."""
292
+ bits = set()
293
+ ul1, ul2 = self.ulUnicodeRange1, self.ulUnicodeRange2
294
+ ul3, ul4 = self.ulUnicodeRange3, self.ulUnicodeRange4
295
+ for i in range(32):
296
+ if ul1 & (1 << i):
297
+ bits.add(i)
298
+ if ul2 & (1 << i):
299
+ bits.add(i + 32)
300
+ if ul3 & (1 << i):
301
+ bits.add(i + 64)
302
+ if ul4 & (1 << i):
303
+ bits.add(i + 96)
304
+ return bits
305
+
306
+ def setUnicodeRanges(self, bits):
307
+ """Set the 'ulUnicodeRange*' fields to the specified 'bits'."""
308
+ ul1, ul2, ul3, ul4 = 0, 0, 0, 0
309
+ for bit in bits:
310
+ if 0 <= bit < 32:
311
+ ul1 |= 1 << bit
312
+ elif 32 <= bit < 64:
313
+ ul2 |= 1 << (bit - 32)
314
+ elif 64 <= bit < 96:
315
+ ul3 |= 1 << (bit - 64)
316
+ elif 96 <= bit < 123:
317
+ ul4 |= 1 << (bit - 96)
318
+ else:
319
+ raise ValueError("expected 0 <= int <= 122, found: %r" % bit)
320
+ self.ulUnicodeRange1, self.ulUnicodeRange2 = ul1, ul2
321
+ self.ulUnicodeRange3, self.ulUnicodeRange4 = ul3, ul4
322
+
323
+ def recalcUnicodeRanges(self, ttFont, pruneOnly=False):
324
+ """Intersect the codepoints in the font's Unicode cmap subtables with
325
+ the Unicode block ranges defined in the OpenType specification (v1.7),
326
+ and set the respective 'ulUnicodeRange*' bits if there is at least ONE
327
+ intersection.
328
+ If 'pruneOnly' is True, only clear unused bits with NO intersection.
329
+ """
330
+ unicodes = set()
331
+ for table in ttFont["cmap"].tables:
332
+ if table.isUnicode():
333
+ unicodes.update(table.cmap.keys())
334
+ if pruneOnly:
335
+ empty = intersectUnicodeRanges(unicodes, inverse=True)
336
+ bits = self.getUnicodeRanges() - empty
337
+ else:
338
+ bits = intersectUnicodeRanges(unicodes)
339
+ self.setUnicodeRanges(bits)
340
+ return bits
341
+
342
+ def getCodePageRanges(self):
343
+ """Return the set of 'ulCodePageRange*' bits currently enabled."""
344
+ bits = set()
345
+ if self.version < 1:
346
+ return bits
347
+ ul1, ul2 = self.ulCodePageRange1, self.ulCodePageRange2
348
+ for i in range(32):
349
+ if ul1 & (1 << i):
350
+ bits.add(i)
351
+ if ul2 & (1 << i):
352
+ bits.add(i + 32)
353
+ return bits
354
+
355
+ def setCodePageRanges(self, bits):
356
+ """Set the 'ulCodePageRange*' fields to the specified 'bits'."""
357
+ ul1, ul2 = 0, 0
358
+ for bit in bits:
359
+ if 0 <= bit < 32:
360
+ ul1 |= 1 << bit
361
+ elif 32 <= bit < 64:
362
+ ul2 |= 1 << (bit - 32)
363
+ else:
364
+ raise ValueError(f"expected 0 <= int <= 63, found: {bit:r}")
365
+ if self.version < 1:
366
+ self.version = 1
367
+ self.ulCodePageRange1, self.ulCodePageRange2 = ul1, ul2
368
+
369
+ def recalcCodePageRanges(self, ttFont, pruneOnly=False):
370
+ unicodes = set()
371
+ for table in ttFont["cmap"].tables:
372
+ if table.isUnicode():
373
+ unicodes.update(table.cmap.keys())
374
+ bits = calcCodePageRanges(unicodes)
375
+ if pruneOnly:
376
+ bits &= self.getCodePageRanges()
377
+ # when no codepage ranges can be enabled, fall back to enabling bit 0
378
+ # (Latin 1) so that the font works in MS Word:
379
+ # https://github.com/googlei18n/fontmake/issues/468
380
+ if not bits:
381
+ bits = {0}
382
+ self.setCodePageRanges(bits)
383
+ return bits
384
+
385
+ def recalcAvgCharWidth(self, ttFont):
386
+ """Recalculate xAvgCharWidth using metrics from ttFont's 'hmtx' table.
387
+
388
+ Set it to 0 if the unlikely event 'hmtx' table is not found.
389
+ """
390
+ avg_width = 0
391
+ hmtx = ttFont.get("hmtx")
392
+ if hmtx is not None:
393
+ widths = [width for width, _ in hmtx.metrics.values() if width > 0]
394
+ if widths:
395
+ avg_width = otRound(sum(widths) / len(widths))
396
+ self.xAvgCharWidth = avg_width
397
+ return avg_width
398
+
399
+
400
+ # Unicode ranges data from the OpenType OS/2 table specification v1.7
401
+
402
+ OS2_UNICODE_RANGES = (
403
+ (("Basic Latin", (0x0000, 0x007F)),),
404
+ (("Latin-1 Supplement", (0x0080, 0x00FF)),),
405
+ (("Latin Extended-A", (0x0100, 0x017F)),),
406
+ (("Latin Extended-B", (0x0180, 0x024F)),),
407
+ (
408
+ ("IPA Extensions", (0x0250, 0x02AF)),
409
+ ("Phonetic Extensions", (0x1D00, 0x1D7F)),
410
+ ("Phonetic Extensions Supplement", (0x1D80, 0x1DBF)),
411
+ ),
412
+ (
413
+ ("Spacing Modifier Letters", (0x02B0, 0x02FF)),
414
+ ("Modifier Tone Letters", (0xA700, 0xA71F)),
415
+ ),
416
+ (
417
+ ("Combining Diacritical Marks", (0x0300, 0x036F)),
418
+ ("Combining Diacritical Marks Supplement", (0x1DC0, 0x1DFF)),
419
+ ),
420
+ (("Greek and Coptic", (0x0370, 0x03FF)),),
421
+ (("Coptic", (0x2C80, 0x2CFF)),),
422
+ (
423
+ ("Cyrillic", (0x0400, 0x04FF)),
424
+ ("Cyrillic Supplement", (0x0500, 0x052F)),
425
+ ("Cyrillic Extended-A", (0x2DE0, 0x2DFF)),
426
+ ("Cyrillic Extended-B", (0xA640, 0xA69F)),
427
+ ),
428
+ (("Armenian", (0x0530, 0x058F)),),
429
+ (("Hebrew", (0x0590, 0x05FF)),),
430
+ (("Vai", (0xA500, 0xA63F)),),
431
+ (("Arabic", (0x0600, 0x06FF)), ("Arabic Supplement", (0x0750, 0x077F))),
432
+ (("NKo", (0x07C0, 0x07FF)),),
433
+ (("Devanagari", (0x0900, 0x097F)),),
434
+ (("Bengali", (0x0980, 0x09FF)),),
435
+ (("Gurmukhi", (0x0A00, 0x0A7F)),),
436
+ (("Gujarati", (0x0A80, 0x0AFF)),),
437
+ (("Oriya", (0x0B00, 0x0B7F)),),
438
+ (("Tamil", (0x0B80, 0x0BFF)),),
439
+ (("Telugu", (0x0C00, 0x0C7F)),),
440
+ (("Kannada", (0x0C80, 0x0CFF)),),
441
+ (("Malayalam", (0x0D00, 0x0D7F)),),
442
+ (("Thai", (0x0E00, 0x0E7F)),),
443
+ (("Lao", (0x0E80, 0x0EFF)),),
444
+ (("Georgian", (0x10A0, 0x10FF)), ("Georgian Supplement", (0x2D00, 0x2D2F))),
445
+ (("Balinese", (0x1B00, 0x1B7F)),),
446
+ (("Hangul Jamo", (0x1100, 0x11FF)),),
447
+ (
448
+ ("Latin Extended Additional", (0x1E00, 0x1EFF)),
449
+ ("Latin Extended-C", (0x2C60, 0x2C7F)),
450
+ ("Latin Extended-D", (0xA720, 0xA7FF)),
451
+ ),
452
+ (("Greek Extended", (0x1F00, 0x1FFF)),),
453
+ (
454
+ ("General Punctuation", (0x2000, 0x206F)),
455
+ ("Supplemental Punctuation", (0x2E00, 0x2E7F)),
456
+ ),
457
+ (("Superscripts And Subscripts", (0x2070, 0x209F)),),
458
+ (("Currency Symbols", (0x20A0, 0x20CF)),),
459
+ (("Combining Diacritical Marks For Symbols", (0x20D0, 0x20FF)),),
460
+ (("Letterlike Symbols", (0x2100, 0x214F)),),
461
+ (("Number Forms", (0x2150, 0x218F)),),
462
+ (
463
+ ("Arrows", (0x2190, 0x21FF)),
464
+ ("Supplemental Arrows-A", (0x27F0, 0x27FF)),
465
+ ("Supplemental Arrows-B", (0x2900, 0x297F)),
466
+ ("Miscellaneous Symbols and Arrows", (0x2B00, 0x2BFF)),
467
+ ),
468
+ (
469
+ ("Mathematical Operators", (0x2200, 0x22FF)),
470
+ ("Supplemental Mathematical Operators", (0x2A00, 0x2AFF)),
471
+ ("Miscellaneous Mathematical Symbols-A", (0x27C0, 0x27EF)),
472
+ ("Miscellaneous Mathematical Symbols-B", (0x2980, 0x29FF)),
473
+ ),
474
+ (("Miscellaneous Technical", (0x2300, 0x23FF)),),
475
+ (("Control Pictures", (0x2400, 0x243F)),),
476
+ (("Optical Character Recognition", (0x2440, 0x245F)),),
477
+ (("Enclosed Alphanumerics", (0x2460, 0x24FF)),),
478
+ (("Box Drawing", (0x2500, 0x257F)),),
479
+ (("Block Elements", (0x2580, 0x259F)),),
480
+ (("Geometric Shapes", (0x25A0, 0x25FF)),),
481
+ (("Miscellaneous Symbols", (0x2600, 0x26FF)),),
482
+ (("Dingbats", (0x2700, 0x27BF)),),
483
+ (("CJK Symbols And Punctuation", (0x3000, 0x303F)),),
484
+ (("Hiragana", (0x3040, 0x309F)),),
485
+ (
486
+ ("Katakana", (0x30A0, 0x30FF)),
487
+ ("Katakana Phonetic Extensions", (0x31F0, 0x31FF)),
488
+ ),
489
+ (("Bopomofo", (0x3100, 0x312F)), ("Bopomofo Extended", (0x31A0, 0x31BF))),
490
+ (("Hangul Compatibility Jamo", (0x3130, 0x318F)),),
491
+ (("Phags-pa", (0xA840, 0xA87F)),),
492
+ (("Enclosed CJK Letters And Months", (0x3200, 0x32FF)),),
493
+ (("CJK Compatibility", (0x3300, 0x33FF)),),
494
+ (("Hangul Syllables", (0xAC00, 0xD7AF)),),
495
+ (("Non-Plane 0 *", (0xD800, 0xDFFF)),),
496
+ (("Phoenician", (0x10900, 0x1091F)),),
497
+ (
498
+ ("CJK Unified Ideographs", (0x4E00, 0x9FFF)),
499
+ ("CJK Radicals Supplement", (0x2E80, 0x2EFF)),
500
+ ("Kangxi Radicals", (0x2F00, 0x2FDF)),
501
+ ("Ideographic Description Characters", (0x2FF0, 0x2FFF)),
502
+ ("CJK Unified Ideographs Extension A", (0x3400, 0x4DBF)),
503
+ ("CJK Unified Ideographs Extension B", (0x20000, 0x2A6DF)),
504
+ ("Kanbun", (0x3190, 0x319F)),
505
+ ),
506
+ (("Private Use Area (plane 0)", (0xE000, 0xF8FF)),),
507
+ (
508
+ ("CJK Strokes", (0x31C0, 0x31EF)),
509
+ ("CJK Compatibility Ideographs", (0xF900, 0xFAFF)),
510
+ ("CJK Compatibility Ideographs Supplement", (0x2F800, 0x2FA1F)),
511
+ ),
512
+ (("Alphabetic Presentation Forms", (0xFB00, 0xFB4F)),),
513
+ (("Arabic Presentation Forms-A", (0xFB50, 0xFDFF)),),
514
+ (("Combining Half Marks", (0xFE20, 0xFE2F)),),
515
+ (
516
+ ("Vertical Forms", (0xFE10, 0xFE1F)),
517
+ ("CJK Compatibility Forms", (0xFE30, 0xFE4F)),
518
+ ),
519
+ (("Small Form Variants", (0xFE50, 0xFE6F)),),
520
+ (("Arabic Presentation Forms-B", (0xFE70, 0xFEFF)),),
521
+ (("Halfwidth And Fullwidth Forms", (0xFF00, 0xFFEF)),),
522
+ (("Specials", (0xFFF0, 0xFFFF)),),
523
+ (("Tibetan", (0x0F00, 0x0FFF)),),
524
+ (("Syriac", (0x0700, 0x074F)),),
525
+ (("Thaana", (0x0780, 0x07BF)),),
526
+ (("Sinhala", (0x0D80, 0x0DFF)),),
527
+ (("Myanmar", (0x1000, 0x109F)),),
528
+ (
529
+ ("Ethiopic", (0x1200, 0x137F)),
530
+ ("Ethiopic Supplement", (0x1380, 0x139F)),
531
+ ("Ethiopic Extended", (0x2D80, 0x2DDF)),
532
+ ),
533
+ (("Cherokee", (0x13A0, 0x13FF)),),
534
+ (("Unified Canadian Aboriginal Syllabics", (0x1400, 0x167F)),),
535
+ (("Ogham", (0x1680, 0x169F)),),
536
+ (("Runic", (0x16A0, 0x16FF)),),
537
+ (("Khmer", (0x1780, 0x17FF)), ("Khmer Symbols", (0x19E0, 0x19FF))),
538
+ (("Mongolian", (0x1800, 0x18AF)),),
539
+ (("Braille Patterns", (0x2800, 0x28FF)),),
540
+ (("Yi Syllables", (0xA000, 0xA48F)), ("Yi Radicals", (0xA490, 0xA4CF))),
541
+ (
542
+ ("Tagalog", (0x1700, 0x171F)),
543
+ ("Hanunoo", (0x1720, 0x173F)),
544
+ ("Buhid", (0x1740, 0x175F)),
545
+ ("Tagbanwa", (0x1760, 0x177F)),
546
+ ),
547
+ (("Old Italic", (0x10300, 0x1032F)),),
548
+ (("Gothic", (0x10330, 0x1034F)),),
549
+ (("Deseret", (0x10400, 0x1044F)),),
550
+ (
551
+ ("Byzantine Musical Symbols", (0x1D000, 0x1D0FF)),
552
+ ("Musical Symbols", (0x1D100, 0x1D1FF)),
553
+ ("Ancient Greek Musical Notation", (0x1D200, 0x1D24F)),
554
+ ),
555
+ (("Mathematical Alphanumeric Symbols", (0x1D400, 0x1D7FF)),),
556
+ (
557
+ ("Private Use (plane 15)", (0xF0000, 0xFFFFD)),
558
+ ("Private Use (plane 16)", (0x100000, 0x10FFFD)),
559
+ ),
560
+ (
561
+ ("Variation Selectors", (0xFE00, 0xFE0F)),
562
+ ("Variation Selectors Supplement", (0xE0100, 0xE01EF)),
563
+ ),
564
+ (("Tags", (0xE0000, 0xE007F)),),
565
+ (("Limbu", (0x1900, 0x194F)),),
566
+ (("Tai Le", (0x1950, 0x197F)),),
567
+ (("New Tai Lue", (0x1980, 0x19DF)),),
568
+ (("Buginese", (0x1A00, 0x1A1F)),),
569
+ (("Glagolitic", (0x2C00, 0x2C5F)),),
570
+ (("Tifinagh", (0x2D30, 0x2D7F)),),
571
+ (("Yijing Hexagram Symbols", (0x4DC0, 0x4DFF)),),
572
+ (("Syloti Nagri", (0xA800, 0xA82F)),),
573
+ (
574
+ ("Linear B Syllabary", (0x10000, 0x1007F)),
575
+ ("Linear B Ideograms", (0x10080, 0x100FF)),
576
+ ("Aegean Numbers", (0x10100, 0x1013F)),
577
+ ),
578
+ (("Ancient Greek Numbers", (0x10140, 0x1018F)),),
579
+ (("Ugaritic", (0x10380, 0x1039F)),),
580
+ (("Old Persian", (0x103A0, 0x103DF)),),
581
+ (("Shavian", (0x10450, 0x1047F)),),
582
+ (("Osmanya", (0x10480, 0x104AF)),),
583
+ (("Cypriot Syllabary", (0x10800, 0x1083F)),),
584
+ (("Kharoshthi", (0x10A00, 0x10A5F)),),
585
+ (("Tai Xuan Jing Symbols", (0x1D300, 0x1D35F)),),
586
+ (
587
+ ("Cuneiform", (0x12000, 0x123FF)),
588
+ ("Cuneiform Numbers and Punctuation", (0x12400, 0x1247F)),
589
+ ),
590
+ (("Counting Rod Numerals", (0x1D360, 0x1D37F)),),
591
+ (("Sundanese", (0x1B80, 0x1BBF)),),
592
+ (("Lepcha", (0x1C00, 0x1C4F)),),
593
+ (("Ol Chiki", (0x1C50, 0x1C7F)),),
594
+ (("Saurashtra", (0xA880, 0xA8DF)),),
595
+ (("Kayah Li", (0xA900, 0xA92F)),),
596
+ (("Rejang", (0xA930, 0xA95F)),),
597
+ (("Cham", (0xAA00, 0xAA5F)),),
598
+ (("Ancient Symbols", (0x10190, 0x101CF)),),
599
+ (("Phaistos Disc", (0x101D0, 0x101FF)),),
600
+ (
601
+ ("Carian", (0x102A0, 0x102DF)),
602
+ ("Lycian", (0x10280, 0x1029F)),
603
+ ("Lydian", (0x10920, 0x1093F)),
604
+ ),
605
+ (("Domino Tiles", (0x1F030, 0x1F09F)), ("Mahjong Tiles", (0x1F000, 0x1F02F))),
606
+ )
607
+
608
+
609
+ _unicodeStarts = []
610
+ _unicodeValues = [None]
611
+
612
+
613
+ def _getUnicodeRanges():
614
+ # build the ranges of codepoints for each unicode range bit, and cache result
615
+ if not _unicodeStarts:
616
+ unicodeRanges = [
617
+ (start, (stop, bit))
618
+ for bit, blocks in enumerate(OS2_UNICODE_RANGES)
619
+ for _, (start, stop) in blocks
620
+ ]
621
+ for start, (stop, bit) in sorted(unicodeRanges):
622
+ _unicodeStarts.append(start)
623
+ _unicodeValues.append((stop, bit))
624
+ return _unicodeStarts, _unicodeValues
625
+
626
+
627
+ def intersectUnicodeRanges(unicodes, inverse=False):
628
+ """Intersect a sequence of (int) Unicode codepoints with the Unicode block
629
+ ranges defined in the OpenType specification v1.7, and return the set of
630
+ 'ulUnicodeRanges' bits for which there is at least ONE intersection.
631
+ If 'inverse' is True, return the the bits for which there is NO intersection.
632
+
633
+ >>> intersectUnicodeRanges([0x0410]) == {9}
634
+ True
635
+ >>> intersectUnicodeRanges([0x0410, 0x1F000]) == {9, 57, 122}
636
+ True
637
+ >>> intersectUnicodeRanges([0x0410, 0x1F000], inverse=True) == (
638
+ ... set(range(len(OS2_UNICODE_RANGES))) - {9, 57, 122})
639
+ True
640
+ """
641
+ unicodes = set(unicodes)
642
+ unicodestarts, unicodevalues = _getUnicodeRanges()
643
+ bits = set()
644
+ for code in unicodes:
645
+ stop, bit = unicodevalues[bisect.bisect(unicodestarts, code)]
646
+ if code <= stop:
647
+ bits.add(bit)
648
+ # The spec says that bit 57 ("Non Plane 0") implies that there's
649
+ # at least one codepoint beyond the BMP; so I also include all
650
+ # the non-BMP codepoints here
651
+ if any(0x10000 <= code < 0x110000 for code in unicodes):
652
+ bits.add(57)
653
+ return set(range(len(OS2_UNICODE_RANGES))) - bits if inverse else bits
654
+
655
+
656
+ def calcCodePageRanges(unicodes):
657
+ """Given a set of Unicode codepoints (integers), calculate the
658
+ corresponding OS/2 CodePage range bits.
659
+ This is a direct translation of FontForge implementation:
660
+ https://github.com/fontforge/fontforge/blob/7b2c074/fontforge/tottf.c#L3158
661
+ """
662
+ bits = set()
663
+ hasAscii = set(range(0x20, 0x7E)).issubset(unicodes)
664
+ hasLineart = ord("┤") in unicodes
665
+
666
+ for uni in unicodes:
667
+ if uni == ord("Þ") and hasAscii:
668
+ bits.add(0) # Latin 1
669
+ elif uni == ord("Ľ") and hasAscii:
670
+ bits.add(1) # Latin 2: Eastern Europe
671
+ if hasLineart:
672
+ bits.add(58) # Latin 2
673
+ elif uni == ord("Б"):
674
+ bits.add(2) # Cyrillic
675
+ if ord("Ѕ") in unicodes and hasLineart:
676
+ bits.add(57) # IBM Cyrillic
677
+ if ord("╜") in unicodes and hasLineart:
678
+ bits.add(49) # MS-DOS Russian
679
+ elif uni == ord("Ά"):
680
+ bits.add(3) # Greek
681
+ if hasLineart and ord("½") in unicodes:
682
+ bits.add(48) # IBM Greek
683
+ if hasLineart and ord("√") in unicodes:
684
+ bits.add(60) # Greek, former 437 G
685
+ elif uni == ord("İ") and hasAscii:
686
+ bits.add(4) # Turkish
687
+ if hasLineart:
688
+ bits.add(56) # IBM turkish
689
+ elif uni == ord("א"):
690
+ bits.add(5) # Hebrew
691
+ if hasLineart and ord("√") in unicodes:
692
+ bits.add(53) # Hebrew
693
+ elif uni == ord("ر"):
694
+ bits.add(6) # Arabic
695
+ if ord("√") in unicodes:
696
+ bits.add(51) # Arabic
697
+ if hasLineart:
698
+ bits.add(61) # Arabic; ASMO 708
699
+ elif uni == ord("ŗ") and hasAscii:
700
+ bits.add(7) # Windows Baltic
701
+ if hasLineart:
702
+ bits.add(59) # MS-DOS Baltic
703
+ elif uni == ord("₫") and hasAscii:
704
+ bits.add(8) # Vietnamese
705
+ elif uni == ord("ๅ"):
706
+ bits.add(16) # Thai
707
+ elif uni == ord("エ"):
708
+ bits.add(17) # JIS/Japan
709
+ elif uni == ord("ㄅ"):
710
+ bits.add(18) # Chinese: Simplified
711
+ elif uni == ord("ㄱ"):
712
+ bits.add(19) # Korean wansung
713
+ elif uni == ord("央"):
714
+ bits.add(20) # Chinese: Traditional
715
+ elif uni == ord("곴"):
716
+ bits.add(21) # Korean Johab
717
+ elif uni == ord("♥") and hasAscii:
718
+ bits.add(30) # OEM Character Set
719
+ # TODO: Symbol bit has a special meaning (check the spec), we need
720
+ # to confirm if this is wanted by default.
721
+ # elif chr(0xF000) <= char <= chr(0xF0FF):
722
+ # codepageRanges.add(31) # Symbol Character Set
723
+ elif uni == ord("þ") and hasAscii and hasLineart:
724
+ bits.add(54) # MS-DOS Icelandic
725
+ elif uni == ord("╚") and hasAscii:
726
+ bits.add(62) # WE/Latin 1
727
+ bits.add(63) # US
728
+ elif hasAscii and hasLineart and ord("√") in unicodes:
729
+ if uni == ord("Å"):
730
+ bits.add(50) # MS-DOS Nordic
731
+ elif uni == ord("é"):
732
+ bits.add(52) # MS-DOS Canadian French
733
+ elif uni == ord("õ"):
734
+ bits.add(55) # MS-DOS Portuguese
735
+
736
+ if hasAscii and ord("‰") in unicodes and ord("∑") in unicodes:
737
+ bits.add(29) # Macintosh Character Set (US Roman)
738
+
739
+ return bits
740
+
741
+
742
+ if __name__ == "__main__":
743
+ import doctest, sys
744
+
745
+ sys.exit(doctest.testmod().failed)
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/C_F_F__2.cpython-310.pyc ADDED
Binary file (896 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/C_O_L_R_.cpython-310.pyc ADDED
Binary file (5.26 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/C_P_A_L_.cpython-310.pyc ADDED
Binary file (9.22 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/D_S_I_G_.cpython-310.pyc ADDED
Binary file (4.44 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/E_B_L_C_.cpython-310.pyc ADDED
Binary file (20 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/G_D_E_F_.cpython-310.pyc ADDED
Binary file (393 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/G__l_o_c.cpython-310.pyc ADDED
Binary file (3 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/M_A_T_H_.cpython-310.pyc ADDED
Binary file (393 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/M_E_T_A_.cpython-310.pyc ADDED
Binary file (7.68 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/O_S_2f_2.cpython-310.pyc ADDED
Binary file (21.2 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_C_.cpython-310.pyc ADDED
Binary file (393 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_D_.cpython-310.pyc ADDED
Binary file (393 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_P_.cpython-310.pyc ADDED
Binary file (393 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I_V_.cpython-310.pyc ADDED
Binary file (1.05 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/T_S_I__3.cpython-310.pyc ADDED
Binary file (758 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/V_D_M_X_.cpython-310.pyc ADDED
Binary file (5.81 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.59 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/_a_n_k_r.cpython-310.pyc ADDED
Binary file (775 Bytes). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/_c_i_d_g.cpython-310.pyc ADDED
Binary file (1.08 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__pycache__/_c_v_a_r.cpython-310.pyc ADDED
Binary file (3.36 kB). View file