ZTWHHH commited on
Commit
46ef1d2
·
verified ·
1 Parent(s): ee8cdb7

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/afmLib.py +439 -0
  2. evalkit_tf437/lib/python3.10/site-packages/fontTools/fontBuilder.py +989 -0
  3. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/__init__.cpython-310.pyc +0 -0
  4. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/__main__.cpython-310.pyc +0 -0
  5. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/removeOverlaps.cpython-310.pyc +0 -0
  6. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/reorderGlyphs.cpython-310.pyc +0 -0
  7. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/sfnt.cpython-310.pyc +0 -0
  8. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/macUtils.py +54 -0
  9. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/reorderGlyphs.py +278 -0
  10. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/sfnt.py +662 -0
  11. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/standardGlyphOrder.py +271 -0
  12. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/BitmapGlyphMetrics.py +64 -0
  13. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/C_B_L_C_.py +9 -0
  14. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/C_F_F_.py +46 -0
  15. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/D_S_I_G_.py +151 -0
  16. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/F__e_a_t.py +144 -0
  17. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/G_M_A_P_.py +141 -0
  18. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/G_S_U_B_.py +5 -0
  19. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/H_V_A_R_.py +5 -0
  20. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/M_E_T_A_.py +345 -0
  21. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/M_V_A_R_.py +5 -0
  22. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/S_V_G_.py +215 -0
  23. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/S__i_l_l.py +87 -0
  24. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/T_S_I_C_.py +5 -0
  25. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/T_S_I_J_.py +5 -0
  26. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/T_S_I__0.py +57 -0
  27. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/T_S_I__2.py +15 -0
  28. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/T_S_I__3.py +20 -0
  29. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/V_O_R_G_.py +158 -0
  30. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/V_V_A_R_.py +5 -0
  31. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__init__.py +97 -0
  32. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_a_n_k_r.py +14 -0
  33. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_c_i_d_g.py +19 -0
  34. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_f_e_a_t.py +12 -0
  35. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_f_p_g_m.py +49 -0
  36. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_f_v_a_r.py +253 -0
  37. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_g_a_s_p.py +55 -0
  38. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_g_l_y_f.py +2222 -0
  39. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_h_m_t_x.py +151 -0
  40. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_l_o_c_a.py +62 -0
  41. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_l_t_a_g.py +64 -0
  42. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_p_o_s_t.py +308 -0
  43. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_p_r_e_p.py +7 -0
  44. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_p_r_o_p.py +6 -0
  45. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_s_b_i_x.py +119 -0
  46. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_v_h_e_a.py +127 -0
  47. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/table_API_readme.txt +91 -0
  48. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/ttProgram.py +594 -0
  49. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/woff2.py +1683 -0
  50. evalkit_tf437/lib/python3.10/site-packages/fontTools/ttx.py +467 -0
evalkit_tf437/lib/python3.10/site-packages/fontTools/afmLib.py ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module for reading and writing AFM (Adobe Font Metrics) files.
2
+
3
+ Note that this has been designed to read in AFM files generated by Fontographer
4
+ and has not been tested on many other files. In particular, it does not
5
+ implement the whole Adobe AFM specification [#f1]_ but, it should read most
6
+ "common" AFM files.
7
+
8
+ Here is an example of using `afmLib` to read, modify and write an AFM file:
9
+
10
+ >>> from fontTools.afmLib import AFM
11
+ >>> f = AFM("Tests/afmLib/data/TestAFM.afm")
12
+ >>>
13
+ >>> # Accessing a pair gets you the kern value
14
+ >>> f[("V","A")]
15
+ -60
16
+ >>>
17
+ >>> # Accessing a glyph name gets you metrics
18
+ >>> f["A"]
19
+ (65, 668, (8, -25, 660, 666))
20
+ >>> # (charnum, width, bounding box)
21
+ >>>
22
+ >>> # Accessing an attribute gets you metadata
23
+ >>> f.FontName
24
+ 'TestFont-Regular'
25
+ >>> f.FamilyName
26
+ 'TestFont'
27
+ >>> f.Weight
28
+ 'Regular'
29
+ >>> f.XHeight
30
+ 500
31
+ >>> f.Ascender
32
+ 750
33
+ >>>
34
+ >>> # Attributes and items can also be set
35
+ >>> f[("A","V")] = -150 # Tighten kerning
36
+ >>> f.FontName = "TestFont Squished"
37
+ >>>
38
+ >>> # And the font written out again (remove the # in front)
39
+ >>> #f.write("testfont-squished.afm")
40
+
41
+ .. rubric:: Footnotes
42
+
43
+ .. [#f1] `Adobe Technote 5004 <https://www.adobe.com/content/dam/acom/en/devnet/font/pdfs/5004.AFM_Spec.pdf>`_,
44
+ Adobe Font Metrics File Format Specification.
45
+
46
+ """
47
+
48
+ import re
49
+
50
+ # every single line starts with a "word"
51
+ identifierRE = re.compile(r"^([A-Za-z]+).*")
52
+
53
+ # regular expression to parse char lines
54
+ charRE = re.compile(
55
+ r"(-?\d+)" # charnum
56
+ r"\s*;\s*WX\s+" # ; WX
57
+ r"(-?\d+)" # width
58
+ r"\s*;\s*N\s+" # ; N
59
+ r"([.A-Za-z0-9_]+)" # charname
60
+ r"\s*;\s*B\s+" # ; B
61
+ r"(-?\d+)" # left
62
+ r"\s+"
63
+ r"(-?\d+)" # bottom
64
+ r"\s+"
65
+ r"(-?\d+)" # right
66
+ r"\s+"
67
+ r"(-?\d+)" # top
68
+ r"\s*;\s*" # ;
69
+ )
70
+
71
+ # regular expression to parse kerning lines
72
+ kernRE = re.compile(
73
+ r"([.A-Za-z0-9_]+)" # leftchar
74
+ r"\s+"
75
+ r"([.A-Za-z0-9_]+)" # rightchar
76
+ r"\s+"
77
+ r"(-?\d+)" # value
78
+ r"\s*"
79
+ )
80
+
81
+ # regular expressions to parse composite info lines of the form:
82
+ # Aacute 2 ; PCC A 0 0 ; PCC acute 182 211 ;
83
+ compositeRE = re.compile(
84
+ r"([.A-Za-z0-9_]+)" # char name
85
+ r"\s+"
86
+ r"(\d+)" # number of parts
87
+ r"\s*;\s*"
88
+ )
89
+ componentRE = re.compile(
90
+ r"PCC\s+" # PPC
91
+ r"([.A-Za-z0-9_]+)" # base char name
92
+ r"\s+"
93
+ r"(-?\d+)" # x offset
94
+ r"\s+"
95
+ r"(-?\d+)" # y offset
96
+ r"\s*;\s*"
97
+ )
98
+
99
+ preferredAttributeOrder = [
100
+ "FontName",
101
+ "FullName",
102
+ "FamilyName",
103
+ "Weight",
104
+ "ItalicAngle",
105
+ "IsFixedPitch",
106
+ "FontBBox",
107
+ "UnderlinePosition",
108
+ "UnderlineThickness",
109
+ "Version",
110
+ "Notice",
111
+ "EncodingScheme",
112
+ "CapHeight",
113
+ "XHeight",
114
+ "Ascender",
115
+ "Descender",
116
+ ]
117
+
118
+
119
+ class error(Exception):
120
+ pass
121
+
122
+
123
+ class AFM(object):
124
+ _attrs = None
125
+
126
+ _keywords = [
127
+ "StartFontMetrics",
128
+ "EndFontMetrics",
129
+ "StartCharMetrics",
130
+ "EndCharMetrics",
131
+ "StartKernData",
132
+ "StartKernPairs",
133
+ "EndKernPairs",
134
+ "EndKernData",
135
+ "StartComposites",
136
+ "EndComposites",
137
+ ]
138
+
139
+ def __init__(self, path=None):
140
+ """AFM file reader.
141
+
142
+ Instantiating an object with a path name will cause the file to be opened,
143
+ read, and parsed. Alternatively the path can be left unspecified, and a
144
+ file can be parsed later with the :meth:`read` method."""
145
+ self._attrs = {}
146
+ self._chars = {}
147
+ self._kerning = {}
148
+ self._index = {}
149
+ self._comments = []
150
+ self._composites = {}
151
+ if path is not None:
152
+ self.read(path)
153
+
154
+ def read(self, path):
155
+ """Opens, reads and parses a file."""
156
+ lines = readlines(path)
157
+ for line in lines:
158
+ if not line.strip():
159
+ continue
160
+ m = identifierRE.match(line)
161
+ if m is None:
162
+ raise error("syntax error in AFM file: " + repr(line))
163
+
164
+ pos = m.regs[1][1]
165
+ word = line[:pos]
166
+ rest = line[pos:].strip()
167
+ if word in self._keywords:
168
+ continue
169
+ if word == "C":
170
+ self.parsechar(rest)
171
+ elif word == "KPX":
172
+ self.parsekernpair(rest)
173
+ elif word == "CC":
174
+ self.parsecomposite(rest)
175
+ else:
176
+ self.parseattr(word, rest)
177
+
178
+ def parsechar(self, rest):
179
+ m = charRE.match(rest)
180
+ if m is None:
181
+ raise error("syntax error in AFM file: " + repr(rest))
182
+ things = []
183
+ for fr, to in m.regs[1:]:
184
+ things.append(rest[fr:to])
185
+ charname = things[2]
186
+ del things[2]
187
+ charnum, width, l, b, r, t = (int(thing) for thing in things)
188
+ self._chars[charname] = charnum, width, (l, b, r, t)
189
+
190
+ def parsekernpair(self, rest):
191
+ m = kernRE.match(rest)
192
+ if m is None:
193
+ raise error("syntax error in AFM file: " + repr(rest))
194
+ things = []
195
+ for fr, to in m.regs[1:]:
196
+ things.append(rest[fr:to])
197
+ leftchar, rightchar, value = things
198
+ value = int(value)
199
+ self._kerning[(leftchar, rightchar)] = value
200
+
201
+ def parseattr(self, word, rest):
202
+ if word == "FontBBox":
203
+ l, b, r, t = [int(thing) for thing in rest.split()]
204
+ self._attrs[word] = l, b, r, t
205
+ elif word == "Comment":
206
+ self._comments.append(rest)
207
+ else:
208
+ try:
209
+ value = int(rest)
210
+ except (ValueError, OverflowError):
211
+ self._attrs[word] = rest
212
+ else:
213
+ self._attrs[word] = value
214
+
215
+ def parsecomposite(self, rest):
216
+ m = compositeRE.match(rest)
217
+ if m is None:
218
+ raise error("syntax error in AFM file: " + repr(rest))
219
+ charname = m.group(1)
220
+ ncomponents = int(m.group(2))
221
+ rest = rest[m.regs[0][1] :]
222
+ components = []
223
+ while True:
224
+ m = componentRE.match(rest)
225
+ if m is None:
226
+ raise error("syntax error in AFM file: " + repr(rest))
227
+ basechar = m.group(1)
228
+ xoffset = int(m.group(2))
229
+ yoffset = int(m.group(3))
230
+ components.append((basechar, xoffset, yoffset))
231
+ rest = rest[m.regs[0][1] :]
232
+ if not rest:
233
+ break
234
+ assert len(components) == ncomponents
235
+ self._composites[charname] = components
236
+
237
+ def write(self, path, sep="\r"):
238
+ """Writes out an AFM font to the given path."""
239
+ import time
240
+
241
+ lines = [
242
+ "StartFontMetrics 2.0",
243
+ "Comment Generated by afmLib; at %s"
244
+ % (time.strftime("%m/%d/%Y %H:%M:%S", time.localtime(time.time()))),
245
+ ]
246
+
247
+ # write comments, assuming (possibly wrongly!) they should
248
+ # all appear at the top
249
+ for comment in self._comments:
250
+ lines.append("Comment " + comment)
251
+
252
+ # write attributes, first the ones we know about, in
253
+ # a preferred order
254
+ attrs = self._attrs
255
+ for attr in preferredAttributeOrder:
256
+ if attr in attrs:
257
+ value = attrs[attr]
258
+ if attr == "FontBBox":
259
+ value = "%s %s %s %s" % value
260
+ lines.append(attr + " " + str(value))
261
+ # then write the attributes we don't know about,
262
+ # in alphabetical order
263
+ items = sorted(attrs.items())
264
+ for attr, value in items:
265
+ if attr in preferredAttributeOrder:
266
+ continue
267
+ lines.append(attr + " " + str(value))
268
+
269
+ # write char metrics
270
+ lines.append("StartCharMetrics " + repr(len(self._chars)))
271
+ items = [
272
+ (charnum, (charname, width, box))
273
+ for charname, (charnum, width, box) in self._chars.items()
274
+ ]
275
+
276
+ def myKey(a):
277
+ """Custom key function to make sure unencoded chars (-1)
278
+ end up at the end of the list after sorting."""
279
+ if a[0] == -1:
280
+ a = (0xFFFF,) + a[1:] # 0xffff is an arbitrary large number
281
+ return a
282
+
283
+ items.sort(key=myKey)
284
+
285
+ for charnum, (charname, width, (l, b, r, t)) in items:
286
+ lines.append(
287
+ "C %d ; WX %d ; N %s ; B %d %d %d %d ;"
288
+ % (charnum, width, charname, l, b, r, t)
289
+ )
290
+ lines.append("EndCharMetrics")
291
+
292
+ # write kerning info
293
+ lines.append("StartKernData")
294
+ lines.append("StartKernPairs " + repr(len(self._kerning)))
295
+ items = sorted(self._kerning.items())
296
+ for (leftchar, rightchar), value in items:
297
+ lines.append("KPX %s %s %d" % (leftchar, rightchar, value))
298
+ lines.append("EndKernPairs")
299
+ lines.append("EndKernData")
300
+
301
+ if self._composites:
302
+ composites = sorted(self._composites.items())
303
+ lines.append("StartComposites %s" % len(self._composites))
304
+ for charname, components in composites:
305
+ line = "CC %s %s ;" % (charname, len(components))
306
+ for basechar, xoffset, yoffset in components:
307
+ line = line + " PCC %s %s %s ;" % (basechar, xoffset, yoffset)
308
+ lines.append(line)
309
+ lines.append("EndComposites")
310
+
311
+ lines.append("EndFontMetrics")
312
+
313
+ writelines(path, lines, sep)
314
+
315
+ def has_kernpair(self, pair):
316
+ """Returns `True` if the given glyph pair (specified as a tuple) exists
317
+ in the kerning dictionary."""
318
+ return pair in self._kerning
319
+
320
+ def kernpairs(self):
321
+ """Returns a list of all kern pairs in the kerning dictionary."""
322
+ return list(self._kerning.keys())
323
+
324
+ def has_char(self, char):
325
+ """Returns `True` if the given glyph exists in the font."""
326
+ return char in self._chars
327
+
328
+ def chars(self):
329
+ """Returns a list of all glyph names in the font."""
330
+ return list(self._chars.keys())
331
+
332
+ def comments(self):
333
+ """Returns all comments from the file."""
334
+ return self._comments
335
+
336
+ def addComment(self, comment):
337
+ """Adds a new comment to the file."""
338
+ self._comments.append(comment)
339
+
340
+ def addComposite(self, glyphName, components):
341
+ """Specifies that the glyph `glyphName` is made up of the given components.
342
+ The components list should be of the following form::
343
+
344
+ [
345
+ (glyphname, xOffset, yOffset),
346
+ ...
347
+ ]
348
+
349
+ """
350
+ self._composites[glyphName] = components
351
+
352
+ def __getattr__(self, attr):
353
+ if attr in self._attrs:
354
+ return self._attrs[attr]
355
+ else:
356
+ raise AttributeError(attr)
357
+
358
+ def __setattr__(self, attr, value):
359
+ # all attrs *not* starting with "_" are consider to be AFM keywords
360
+ if attr[:1] == "_":
361
+ self.__dict__[attr] = value
362
+ else:
363
+ self._attrs[attr] = value
364
+
365
+ def __delattr__(self, attr):
366
+ # all attrs *not* starting with "_" are consider to be AFM keywords
367
+ if attr[:1] == "_":
368
+ try:
369
+ del self.__dict__[attr]
370
+ except KeyError:
371
+ raise AttributeError(attr)
372
+ else:
373
+ try:
374
+ del self._attrs[attr]
375
+ except KeyError:
376
+ raise AttributeError(attr)
377
+
378
+ def __getitem__(self, key):
379
+ if isinstance(key, tuple):
380
+ # key is a tuple, return the kernpair
381
+ return self._kerning[key]
382
+ else:
383
+ # return the metrics instead
384
+ return self._chars[key]
385
+
386
+ def __setitem__(self, key, value):
387
+ if isinstance(key, tuple):
388
+ # key is a tuple, set kernpair
389
+ self._kerning[key] = value
390
+ else:
391
+ # set char metrics
392
+ self._chars[key] = value
393
+
394
+ def __delitem__(self, key):
395
+ if isinstance(key, tuple):
396
+ # key is a tuple, del kernpair
397
+ del self._kerning[key]
398
+ else:
399
+ # del char metrics
400
+ del self._chars[key]
401
+
402
+ def __repr__(self):
403
+ if hasattr(self, "FullName"):
404
+ return "<AFM object for %s>" % self.FullName
405
+ else:
406
+ return "<AFM object at %x>" % id(self)
407
+
408
+
409
+ def readlines(path):
410
+ with open(path, "r", encoding="ascii") as f:
411
+ data = f.read()
412
+ return data.splitlines()
413
+
414
+
415
+ def writelines(path, lines, sep="\r"):
416
+ with open(path, "w", encoding="ascii", newline=sep) as f:
417
+ f.write("\n".join(lines) + "\n")
418
+
419
+
420
+ if __name__ == "__main__":
421
+ import EasyDialogs
422
+
423
+ path = EasyDialogs.AskFileForOpen()
424
+ if path:
425
+ afm = AFM(path)
426
+ char = "A"
427
+ if afm.has_char(char):
428
+ print(afm[char]) # print charnum, width and boundingbox
429
+ pair = ("A", "V")
430
+ if afm.has_kernpair(pair):
431
+ print(afm[pair]) # print kerning value for pair
432
+ print(afm.Version) # various other afm entries have become attributes
433
+ print(afm.Weight)
434
+ # afm.comments() returns a list of all Comment lines found in the AFM
435
+ print(afm.comments())
436
+ # print afm.chars()
437
+ # print afm.kernpairs()
438
+ print(afm)
439
+ afm.write(path + ".muck")
evalkit_tf437/lib/python3.10/site-packages/fontTools/fontBuilder.py ADDED
@@ -0,0 +1,989 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ["FontBuilder"]
2
+
3
+ """
4
+ This module is *experimental*, meaning it still may evolve and change.
5
+
6
+ The `FontBuilder` class is a convenient helper to construct working TTF or
7
+ OTF fonts from scratch.
8
+
9
+ Note that the various setup methods cannot be called in arbitrary order,
10
+ due to various interdependencies between OpenType tables. Here is an order
11
+ that works:
12
+
13
+ fb = FontBuilder(...)
14
+ fb.setupGlyphOrder(...)
15
+ fb.setupCharacterMap(...)
16
+ fb.setupGlyf(...) --or-- fb.setupCFF(...)
17
+ fb.setupHorizontalMetrics(...)
18
+ fb.setupHorizontalHeader()
19
+ fb.setupNameTable(...)
20
+ fb.setupOS2()
21
+ fb.addOpenTypeFeatures(...)
22
+ fb.setupPost()
23
+ fb.save(...)
24
+
25
+ Here is how to build a minimal TTF:
26
+
27
+ ```python
28
+ from fontTools.fontBuilder import FontBuilder
29
+ from fontTools.pens.ttGlyphPen import TTGlyphPen
30
+
31
+
32
+ def drawTestGlyph(pen):
33
+ pen.moveTo((100, 100))
34
+ pen.lineTo((100, 1000))
35
+ pen.qCurveTo((200, 900), (400, 900), (500, 1000))
36
+ pen.lineTo((500, 100))
37
+ pen.closePath()
38
+
39
+
40
+ fb = FontBuilder(1024, isTTF=True)
41
+ fb.setupGlyphOrder([".notdef", ".null", "space", "A", "a"])
42
+ fb.setupCharacterMap({32: "space", 65: "A", 97: "a"})
43
+ advanceWidths = {".notdef": 600, "space": 500, "A": 600, "a": 600, ".null": 0}
44
+
45
+ familyName = "HelloTestFont"
46
+ styleName = "TotallyNormal"
47
+ version = "0.1"
48
+
49
+ nameStrings = dict(
50
+ familyName=dict(en=familyName, nl="HalloTestFont"),
51
+ styleName=dict(en=styleName, nl="TotaalNormaal"),
52
+ uniqueFontIdentifier="fontBuilder: " + familyName + "." + styleName,
53
+ fullName=familyName + "-" + styleName,
54
+ psName=familyName + "-" + styleName,
55
+ version="Version " + version,
56
+ )
57
+
58
+ pen = TTGlyphPen(None)
59
+ drawTestGlyph(pen)
60
+ glyph = pen.glyph()
61
+ glyphs = {".notdef": glyph, "space": glyph, "A": glyph, "a": glyph, ".null": glyph}
62
+ fb.setupGlyf(glyphs)
63
+ metrics = {}
64
+ glyphTable = fb.font["glyf"]
65
+ for gn, advanceWidth in advanceWidths.items():
66
+ metrics[gn] = (advanceWidth, glyphTable[gn].xMin)
67
+ fb.setupHorizontalMetrics(metrics)
68
+ fb.setupHorizontalHeader(ascent=824, descent=-200)
69
+ fb.setupNameTable(nameStrings)
70
+ fb.setupOS2(sTypoAscender=824, usWinAscent=824, usWinDescent=200)
71
+ fb.setupPost()
72
+ fb.save("test.ttf")
73
+ ```
74
+
75
+ And here's how to build a minimal OTF:
76
+
77
+ ```python
78
+ from fontTools.fontBuilder import FontBuilder
79
+ from fontTools.pens.t2CharStringPen import T2CharStringPen
80
+
81
+
82
+ def drawTestGlyph(pen):
83
+ pen.moveTo((100, 100))
84
+ pen.lineTo((100, 1000))
85
+ pen.curveTo((200, 900), (400, 900), (500, 1000))
86
+ pen.lineTo((500, 100))
87
+ pen.closePath()
88
+
89
+
90
+ fb = FontBuilder(1024, isTTF=False)
91
+ fb.setupGlyphOrder([".notdef", ".null", "space", "A", "a"])
92
+ fb.setupCharacterMap({32: "space", 65: "A", 97: "a"})
93
+ advanceWidths = {".notdef": 600, "space": 500, "A": 600, "a": 600, ".null": 0}
94
+
95
+ familyName = "HelloTestFont"
96
+ styleName = "TotallyNormal"
97
+ version = "0.1"
98
+
99
+ nameStrings = dict(
100
+ familyName=dict(en=familyName, nl="HalloTestFont"),
101
+ styleName=dict(en=styleName, nl="TotaalNormaal"),
102
+ uniqueFontIdentifier="fontBuilder: " + familyName + "." + styleName,
103
+ fullName=familyName + "-" + styleName,
104
+ psName=familyName + "-" + styleName,
105
+ version="Version " + version,
106
+ )
107
+
108
+ pen = T2CharStringPen(600, None)
109
+ drawTestGlyph(pen)
110
+ charString = pen.getCharString()
111
+ charStrings = {
112
+ ".notdef": charString,
113
+ "space": charString,
114
+ "A": charString,
115
+ "a": charString,
116
+ ".null": charString,
117
+ }
118
+ fb.setupCFF(nameStrings["psName"], {"FullName": nameStrings["psName"]}, charStrings, {})
119
+ lsb = {gn: cs.calcBounds(None)[0] for gn, cs in charStrings.items()}
120
+ metrics = {}
121
+ for gn, advanceWidth in advanceWidths.items():
122
+ metrics[gn] = (advanceWidth, lsb[gn])
123
+ fb.setupHorizontalMetrics(metrics)
124
+ fb.setupHorizontalHeader(ascent=824, descent=200)
125
+ fb.setupNameTable(nameStrings)
126
+ fb.setupOS2(sTypoAscender=824, usWinAscent=824, usWinDescent=200)
127
+ fb.setupPost()
128
+ fb.save("test.otf")
129
+ ```
130
+ """
131
+
132
+ from .ttLib import TTFont, newTable
133
+ from .ttLib.tables._c_m_a_p import cmap_classes
134
+ from .ttLib.tables._g_l_y_f import flagCubic
135
+ from .ttLib.tables.O_S_2f_2 import Panose
136
+ from .misc.timeTools import timestampNow
137
+ import struct
138
+ from collections import OrderedDict
139
+
140
+
141
+ _headDefaults = dict(
142
+ tableVersion=1.0,
143
+ fontRevision=1.0,
144
+ checkSumAdjustment=0,
145
+ magicNumber=0x5F0F3CF5,
146
+ flags=0x0003,
147
+ unitsPerEm=1000,
148
+ created=0,
149
+ modified=0,
150
+ xMin=0,
151
+ yMin=0,
152
+ xMax=0,
153
+ yMax=0,
154
+ macStyle=0,
155
+ lowestRecPPEM=3,
156
+ fontDirectionHint=2,
157
+ indexToLocFormat=0,
158
+ glyphDataFormat=0,
159
+ )
160
+
161
+ _maxpDefaultsTTF = dict(
162
+ tableVersion=0x00010000,
163
+ numGlyphs=0,
164
+ maxPoints=0,
165
+ maxContours=0,
166
+ maxCompositePoints=0,
167
+ maxCompositeContours=0,
168
+ maxZones=2,
169
+ maxTwilightPoints=0,
170
+ maxStorage=0,
171
+ maxFunctionDefs=0,
172
+ maxInstructionDefs=0,
173
+ maxStackElements=0,
174
+ maxSizeOfInstructions=0,
175
+ maxComponentElements=0,
176
+ maxComponentDepth=0,
177
+ )
178
+ _maxpDefaultsOTF = dict(
179
+ tableVersion=0x00005000,
180
+ numGlyphs=0,
181
+ )
182
+
183
+ _postDefaults = dict(
184
+ formatType=3.0,
185
+ italicAngle=0,
186
+ underlinePosition=0,
187
+ underlineThickness=0,
188
+ isFixedPitch=0,
189
+ minMemType42=0,
190
+ maxMemType42=0,
191
+ minMemType1=0,
192
+ maxMemType1=0,
193
+ )
194
+
195
+ _hheaDefaults = dict(
196
+ tableVersion=0x00010000,
197
+ ascent=0,
198
+ descent=0,
199
+ lineGap=0,
200
+ advanceWidthMax=0,
201
+ minLeftSideBearing=0,
202
+ minRightSideBearing=0,
203
+ xMaxExtent=0,
204
+ caretSlopeRise=1,
205
+ caretSlopeRun=0,
206
+ caretOffset=0,
207
+ reserved0=0,
208
+ reserved1=0,
209
+ reserved2=0,
210
+ reserved3=0,
211
+ metricDataFormat=0,
212
+ numberOfHMetrics=0,
213
+ )
214
+
215
+ _vheaDefaults = dict(
216
+ tableVersion=0x00010000,
217
+ ascent=0,
218
+ descent=0,
219
+ lineGap=0,
220
+ advanceHeightMax=0,
221
+ minTopSideBearing=0,
222
+ minBottomSideBearing=0,
223
+ yMaxExtent=0,
224
+ caretSlopeRise=0,
225
+ caretSlopeRun=0,
226
+ reserved0=0,
227
+ reserved1=0,
228
+ reserved2=0,
229
+ reserved3=0,
230
+ reserved4=0,
231
+ metricDataFormat=0,
232
+ numberOfVMetrics=0,
233
+ )
234
+
235
+ _nameIDs = dict(
236
+ copyright=0,
237
+ familyName=1,
238
+ styleName=2,
239
+ uniqueFontIdentifier=3,
240
+ fullName=4,
241
+ version=5,
242
+ psName=6,
243
+ trademark=7,
244
+ manufacturer=8,
245
+ designer=9,
246
+ description=10,
247
+ vendorURL=11,
248
+ designerURL=12,
249
+ licenseDescription=13,
250
+ licenseInfoURL=14,
251
+ # reserved = 15,
252
+ typographicFamily=16,
253
+ typographicSubfamily=17,
254
+ compatibleFullName=18,
255
+ sampleText=19,
256
+ postScriptCIDFindfontName=20,
257
+ wwsFamilyName=21,
258
+ wwsSubfamilyName=22,
259
+ lightBackgroundPalette=23,
260
+ darkBackgroundPalette=24,
261
+ variationsPostScriptNamePrefix=25,
262
+ )
263
+
264
+ # to insert in setupNameTable doc string:
265
+ # print("\n".join(("%s (nameID %s)" % (k, v)) for k, v in sorted(_nameIDs.items(), key=lambda x: x[1])))
266
+
267
+ _panoseDefaults = Panose()
268
+
269
+ _OS2Defaults = dict(
270
+ version=3,
271
+ xAvgCharWidth=0,
272
+ usWeightClass=400,
273
+ usWidthClass=5,
274
+ fsType=0x0004, # default: Preview & Print embedding
275
+ ySubscriptXSize=0,
276
+ ySubscriptYSize=0,
277
+ ySubscriptXOffset=0,
278
+ ySubscriptYOffset=0,
279
+ ySuperscriptXSize=0,
280
+ ySuperscriptYSize=0,
281
+ ySuperscriptXOffset=0,
282
+ ySuperscriptYOffset=0,
283
+ yStrikeoutSize=0,
284
+ yStrikeoutPosition=0,
285
+ sFamilyClass=0,
286
+ panose=_panoseDefaults,
287
+ ulUnicodeRange1=0,
288
+ ulUnicodeRange2=0,
289
+ ulUnicodeRange3=0,
290
+ ulUnicodeRange4=0,
291
+ achVendID="????",
292
+ fsSelection=0,
293
+ usFirstCharIndex=0,
294
+ usLastCharIndex=0,
295
+ sTypoAscender=0,
296
+ sTypoDescender=0,
297
+ sTypoLineGap=0,
298
+ usWinAscent=0,
299
+ usWinDescent=0,
300
+ ulCodePageRange1=0,
301
+ ulCodePageRange2=0,
302
+ sxHeight=0,
303
+ sCapHeight=0,
304
+ usDefaultChar=0, # .notdef
305
+ usBreakChar=32, # space
306
+ usMaxContext=0,
307
+ usLowerOpticalPointSize=0,
308
+ usUpperOpticalPointSize=0,
309
+ )
310
+
311
+
312
+ class FontBuilder(object):
313
+ def __init__(self, unitsPerEm=None, font=None, isTTF=True, glyphDataFormat=0):
314
+ """Initialize a FontBuilder instance.
315
+
316
+ If the `font` argument is not given, a new `TTFont` will be
317
+ constructed, and `unitsPerEm` must be given. If `isTTF` is True,
318
+ the font will be a glyf-based TTF; if `isTTF` is False it will be
319
+ a CFF-based OTF.
320
+
321
+ The `glyphDataFormat` argument corresponds to the `head` table field
322
+ that defines the format of the TrueType `glyf` table (default=0).
323
+ TrueType glyphs historically can only contain quadratic splines and static
324
+ components, but there's a proposal to add support for cubic Bezier curves as well
325
+ as variable composites/components at
326
+ https://github.com/harfbuzz/boring-expansion-spec/blob/main/glyf1.md
327
+ You can experiment with the new features by setting `glyphDataFormat` to 1.
328
+ A ValueError is raised if `glyphDataFormat` is left at 0 but glyphs are added
329
+ that contain cubic splines or varcomposites. This is to prevent accidentally
330
+ creating fonts that are incompatible with existing TrueType implementations.
331
+
332
+ If `font` is given, it must be a `TTFont` instance and `unitsPerEm`
333
+ must _not_ be given. The `isTTF` and `glyphDataFormat` arguments will be ignored.
334
+ """
335
+ if font is None:
336
+ self.font = TTFont(recalcTimestamp=False)
337
+ self.isTTF = isTTF
338
+ now = timestampNow()
339
+ assert unitsPerEm is not None
340
+ self.setupHead(
341
+ unitsPerEm=unitsPerEm,
342
+ created=now,
343
+ modified=now,
344
+ glyphDataFormat=glyphDataFormat,
345
+ )
346
+ self.setupMaxp()
347
+ else:
348
+ assert unitsPerEm is None
349
+ self.font = font
350
+ self.isTTF = "glyf" in font
351
+
352
+ def save(self, file):
353
+ """Save the font. The 'file' argument can be either a pathname or a
354
+ writable file object.
355
+ """
356
+ self.font.save(file)
357
+
358
+ def _initTableWithValues(self, tableTag, defaults, values):
359
+ table = self.font[tableTag] = newTable(tableTag)
360
+ for k, v in defaults.items():
361
+ setattr(table, k, v)
362
+ for k, v in values.items():
363
+ setattr(table, k, v)
364
+ return table
365
+
366
+ def _updateTableWithValues(self, tableTag, values):
367
+ table = self.font[tableTag]
368
+ for k, v in values.items():
369
+ setattr(table, k, v)
370
+
371
+ def setupHead(self, **values):
372
+ """Create a new `head` table and initialize it with default values,
373
+ which can be overridden by keyword arguments.
374
+ """
375
+ self._initTableWithValues("head", _headDefaults, values)
376
+
377
+ def updateHead(self, **values):
378
+ """Update the head table with the fields and values passed as
379
+ keyword arguments.
380
+ """
381
+ self._updateTableWithValues("head", values)
382
+
383
+ def setupGlyphOrder(self, glyphOrder):
384
+ """Set the glyph order for the font."""
385
+ self.font.setGlyphOrder(glyphOrder)
386
+
387
+ def setupCharacterMap(self, cmapping, uvs=None, allowFallback=False):
388
+ """Build the `cmap` table for the font. The `cmapping` argument should
389
+ be a dict mapping unicode code points as integers to glyph names.
390
+
391
+ The `uvs` argument, when passed, must be a list of tuples, describing
392
+ Unicode Variation Sequences. These tuples have three elements:
393
+ (unicodeValue, variationSelector, glyphName)
394
+ `unicodeValue` and `variationSelector` are integer code points.
395
+ `glyphName` may be None, to indicate this is the default variation.
396
+ Text processors will then use the cmap to find the glyph name.
397
+ Each Unicode Variation Sequence should be an officially supported
398
+ sequence, but this is not policed.
399
+ """
400
+ subTables = []
401
+ highestUnicode = max(cmapping) if cmapping else 0
402
+ if highestUnicode > 0xFFFF:
403
+ cmapping_3_1 = dict((k, v) for k, v in cmapping.items() if k < 0x10000)
404
+ subTable_3_10 = buildCmapSubTable(cmapping, 12, 3, 10)
405
+ subTables.append(subTable_3_10)
406
+ else:
407
+ cmapping_3_1 = cmapping
408
+ format = 4
409
+ subTable_3_1 = buildCmapSubTable(cmapping_3_1, format, 3, 1)
410
+ try:
411
+ subTable_3_1.compile(self.font)
412
+ except struct.error:
413
+ # format 4 overflowed, fall back to format 12
414
+ if not allowFallback:
415
+ raise ValueError(
416
+ "cmap format 4 subtable overflowed; sort glyph order by unicode to fix."
417
+ )
418
+ format = 12
419
+ subTable_3_1 = buildCmapSubTable(cmapping_3_1, format, 3, 1)
420
+ subTables.append(subTable_3_1)
421
+ subTable_0_3 = buildCmapSubTable(cmapping_3_1, format, 0, 3)
422
+ subTables.append(subTable_0_3)
423
+
424
+ if uvs is not None:
425
+ uvsDict = {}
426
+ for unicodeValue, variationSelector, glyphName in uvs:
427
+ if cmapping.get(unicodeValue) == glyphName:
428
+ # this is a default variation
429
+ glyphName = None
430
+ if variationSelector not in uvsDict:
431
+ uvsDict[variationSelector] = []
432
+ uvsDict[variationSelector].append((unicodeValue, glyphName))
433
+ uvsSubTable = buildCmapSubTable({}, 14, 0, 5)
434
+ uvsSubTable.uvsDict = uvsDict
435
+ subTables.append(uvsSubTable)
436
+
437
+ self.font["cmap"] = newTable("cmap")
438
+ self.font["cmap"].tableVersion = 0
439
+ self.font["cmap"].tables = subTables
440
+
441
+ def setupNameTable(self, nameStrings, windows=True, mac=True):
442
+ """Create the `name` table for the font. The `nameStrings` argument must
443
+ be a dict, mapping nameIDs or descriptive names for the nameIDs to name
444
+ record values. A value is either a string, or a dict, mapping language codes
445
+ to strings, to allow localized name table entries.
446
+
447
+ By default, both Windows (platformID=3) and Macintosh (platformID=1) name
448
+ records are added, unless any of `windows` or `mac` arguments is False.
449
+
450
+ The following descriptive names are available for nameIDs:
451
+
452
+ copyright (nameID 0)
453
+ familyName (nameID 1)
454
+ styleName (nameID 2)
455
+ uniqueFontIdentifier (nameID 3)
456
+ fullName (nameID 4)
457
+ version (nameID 5)
458
+ psName (nameID 6)
459
+ trademark (nameID 7)
460
+ manufacturer (nameID 8)
461
+ designer (nameID 9)
462
+ description (nameID 10)
463
+ vendorURL (nameID 11)
464
+ designerURL (nameID 12)
465
+ licenseDescription (nameID 13)
466
+ licenseInfoURL (nameID 14)
467
+ typographicFamily (nameID 16)
468
+ typographicSubfamily (nameID 17)
469
+ compatibleFullName (nameID 18)
470
+ sampleText (nameID 19)
471
+ postScriptCIDFindfontName (nameID 20)
472
+ wwsFamilyName (nameID 21)
473
+ wwsSubfamilyName (nameID 22)
474
+ lightBackgroundPalette (nameID 23)
475
+ darkBackgroundPalette (nameID 24)
476
+ variationsPostScriptNamePrefix (nameID 25)
477
+ """
478
+ nameTable = self.font["name"] = newTable("name")
479
+ nameTable.names = []
480
+
481
+ for nameName, nameValue in nameStrings.items():
482
+ if isinstance(nameName, int):
483
+ nameID = nameName
484
+ else:
485
+ nameID = _nameIDs[nameName]
486
+ if isinstance(nameValue, str):
487
+ nameValue = dict(en=nameValue)
488
+ nameTable.addMultilingualName(
489
+ nameValue, ttFont=self.font, nameID=nameID, windows=windows, mac=mac
490
+ )
491
+
492
+ def setupOS2(self, **values):
493
+ """Create a new `OS/2` table and initialize it with default values,
494
+ which can be overridden by keyword arguments.
495
+ """
496
+ self._initTableWithValues("OS/2", _OS2Defaults, values)
497
+ if "xAvgCharWidth" not in values:
498
+ assert (
499
+ "hmtx" in self.font
500
+ ), "the 'hmtx' table must be setup before the 'OS/2' table"
501
+ self.font["OS/2"].recalcAvgCharWidth(self.font)
502
+ if not (
503
+ "ulUnicodeRange1" in values
504
+ or "ulUnicodeRange2" in values
505
+ or "ulUnicodeRange3" in values
506
+ or "ulUnicodeRange3" in values
507
+ ):
508
+ assert (
509
+ "cmap" in self.font
510
+ ), "the 'cmap' table must be setup before the 'OS/2' table"
511
+ self.font["OS/2"].recalcUnicodeRanges(self.font)
512
+
513
+ def setupCFF(self, psName, fontInfo, charStringsDict, privateDict):
514
+ from .cffLib import (
515
+ CFFFontSet,
516
+ TopDictIndex,
517
+ TopDict,
518
+ CharStrings,
519
+ GlobalSubrsIndex,
520
+ PrivateDict,
521
+ )
522
+
523
+ assert not self.isTTF
524
+ self.font.sfntVersion = "OTTO"
525
+ fontSet = CFFFontSet()
526
+ fontSet.major = 1
527
+ fontSet.minor = 0
528
+ fontSet.otFont = self.font
529
+ fontSet.fontNames = [psName]
530
+ fontSet.topDictIndex = TopDictIndex()
531
+
532
+ globalSubrs = GlobalSubrsIndex()
533
+ fontSet.GlobalSubrs = globalSubrs
534
+ private = PrivateDict()
535
+ for key, value in privateDict.items():
536
+ setattr(private, key, value)
537
+ fdSelect = None
538
+ fdArray = None
539
+
540
+ topDict = TopDict()
541
+ topDict.charset = self.font.getGlyphOrder()
542
+ topDict.Private = private
543
+ topDict.GlobalSubrs = fontSet.GlobalSubrs
544
+ for key, value in fontInfo.items():
545
+ setattr(topDict, key, value)
546
+ if "FontMatrix" not in fontInfo:
547
+ scale = 1 / self.font["head"].unitsPerEm
548
+ topDict.FontMatrix = [scale, 0, 0, scale, 0, 0]
549
+
550
+ charStrings = CharStrings(
551
+ None, topDict.charset, globalSubrs, private, fdSelect, fdArray
552
+ )
553
+ for glyphName, charString in charStringsDict.items():
554
+ charString.private = private
555
+ charString.globalSubrs = globalSubrs
556
+ charStrings[glyphName] = charString
557
+ topDict.CharStrings = charStrings
558
+
559
+ fontSet.topDictIndex.append(topDict)
560
+
561
+ self.font["CFF "] = newTable("CFF ")
562
+ self.font["CFF "].cff = fontSet
563
+
564
+ def setupCFF2(self, charStringsDict, fdArrayList=None, regions=None):
565
+ from .cffLib import (
566
+ CFFFontSet,
567
+ TopDictIndex,
568
+ TopDict,
569
+ CharStrings,
570
+ GlobalSubrsIndex,
571
+ PrivateDict,
572
+ FDArrayIndex,
573
+ FontDict,
574
+ )
575
+
576
+ assert not self.isTTF
577
+ self.font.sfntVersion = "OTTO"
578
+ fontSet = CFFFontSet()
579
+ fontSet.major = 2
580
+ fontSet.minor = 0
581
+
582
+ cff2GetGlyphOrder = self.font.getGlyphOrder
583
+ fontSet.topDictIndex = TopDictIndex(None, cff2GetGlyphOrder, None)
584
+
585
+ globalSubrs = GlobalSubrsIndex()
586
+ fontSet.GlobalSubrs = globalSubrs
587
+
588
+ if fdArrayList is None:
589
+ fdArrayList = [{}]
590
+ fdSelect = None
591
+ fdArray = FDArrayIndex()
592
+ fdArray.strings = None
593
+ fdArray.GlobalSubrs = globalSubrs
594
+ for privateDict in fdArrayList:
595
+ fontDict = FontDict()
596
+ fontDict.setCFF2(True)
597
+ private = PrivateDict()
598
+ for key, value in privateDict.items():
599
+ setattr(private, key, value)
600
+ fontDict.Private = private
601
+ fdArray.append(fontDict)
602
+
603
+ topDict = TopDict()
604
+ topDict.cff2GetGlyphOrder = cff2GetGlyphOrder
605
+ topDict.FDArray = fdArray
606
+ scale = 1 / self.font["head"].unitsPerEm
607
+ topDict.FontMatrix = [scale, 0, 0, scale, 0, 0]
608
+
609
+ private = fdArray[0].Private
610
+ charStrings = CharStrings(None, None, globalSubrs, private, fdSelect, fdArray)
611
+ for glyphName, charString in charStringsDict.items():
612
+ charString.private = private
613
+ charString.globalSubrs = globalSubrs
614
+ charStrings[glyphName] = charString
615
+ topDict.CharStrings = charStrings
616
+
617
+ fontSet.topDictIndex.append(topDict)
618
+
619
+ self.font["CFF2"] = newTable("CFF2")
620
+ self.font["CFF2"].cff = fontSet
621
+
622
+ if regions:
623
+ self.setupCFF2Regions(regions)
624
+
625
+ def setupCFF2Regions(self, regions):
626
+ from .varLib.builder import buildVarRegionList, buildVarData, buildVarStore
627
+ from .cffLib import VarStoreData
628
+
629
+ assert "fvar" in self.font, "fvar must to be set up first"
630
+ assert "CFF2" in self.font, "CFF2 must to be set up first"
631
+ axisTags = [a.axisTag for a in self.font["fvar"].axes]
632
+ varRegionList = buildVarRegionList(regions, axisTags)
633
+ varData = buildVarData(list(range(len(regions))), None, optimize=False)
634
+ varStore = buildVarStore(varRegionList, [varData])
635
+ vstore = VarStoreData(otVarStore=varStore)
636
+ topDict = self.font["CFF2"].cff.topDictIndex[0]
637
+ topDict.VarStore = vstore
638
+ for fontDict in topDict.FDArray:
639
+ fontDict.Private.vstore = vstore
640
+
641
+ def setupGlyf(self, glyphs, calcGlyphBounds=True, validateGlyphFormat=True):
642
+ """Create the `glyf` table from a dict, that maps glyph names
643
+ to `fontTools.ttLib.tables._g_l_y_f.Glyph` objects, for example
644
+ as made by `fontTools.pens.ttGlyphPen.TTGlyphPen`.
645
+
646
+ If `calcGlyphBounds` is True, the bounds of all glyphs will be
647
+ calculated. Only pass False if your glyph objects already have
648
+ their bounding box values set.
649
+
650
+ If `validateGlyphFormat` is True, raise ValueError if any of the glyphs contains
651
+ cubic curves or is a variable composite but head.glyphDataFormat=0.
652
+ Set it to False to skip the check if you know in advance all the glyphs are
653
+ compatible with the specified glyphDataFormat.
654
+ """
655
+ assert self.isTTF
656
+
657
+ if validateGlyphFormat and self.font["head"].glyphDataFormat == 0:
658
+ for name, g in glyphs.items():
659
+ if g.numberOfContours > 0 and any(f & flagCubic for f in g.flags):
660
+ raise ValueError(
661
+ f"Glyph {name!r} has cubic Bezier outlines, but glyphDataFormat=0; "
662
+ "either convert to quadratics with cu2qu or set glyphDataFormat=1."
663
+ )
664
+
665
+ self.font["loca"] = newTable("loca")
666
+ self.font["glyf"] = newTable("glyf")
667
+ self.font["glyf"].glyphs = glyphs
668
+ if hasattr(self.font, "glyphOrder"):
669
+ self.font["glyf"].glyphOrder = self.font.glyphOrder
670
+ if calcGlyphBounds:
671
+ self.calcGlyphBounds()
672
+
673
+ def setupFvar(self, axes, instances):
674
+ """Adds an font variations table to the font.
675
+
676
+ Args:
677
+ axes (list): See below.
678
+ instances (list): See below.
679
+
680
+ ``axes`` should be a list of axes, with each axis either supplied as
681
+ a py:class:`.designspaceLib.AxisDescriptor` object, or a tuple in the
682
+ format ```tupletag, minValue, defaultValue, maxValue, name``.
683
+ The ``name`` is either a string, or a dict, mapping language codes
684
+ to strings, to allow localized name table entries.
685
+
686
+ ```instances`` should be a list of instances, with each instance either
687
+ supplied as a py:class:`.designspaceLib.InstanceDescriptor` object, or a
688
+ dict with keys ``location`` (mapping of axis tags to float values),
689
+ ``stylename`` and (optionally) ``postscriptfontname``.
690
+ The ``stylename`` is either a string, or a dict, mapping language codes
691
+ to strings, to allow localized name table entries.
692
+ """
693
+
694
+ addFvar(self.font, axes, instances)
695
+
696
+ def setupAvar(self, axes, mappings=None):
697
+ """Adds an axis variations table to the font.
698
+
699
+ Args:
700
+ axes (list): A list of py:class:`.designspaceLib.AxisDescriptor` objects.
701
+ """
702
+ from .varLib import _add_avar
703
+
704
+ if "fvar" not in self.font:
705
+ raise KeyError("'fvar' table is missing; can't add 'avar'.")
706
+
707
+ axisTags = [axis.axisTag for axis in self.font["fvar"].axes]
708
+ axes = OrderedDict(enumerate(axes)) # Only values are used
709
+ _add_avar(self.font, axes, mappings, axisTags)
710
+
711
+ def setupGvar(self, variations):
712
+ gvar = self.font["gvar"] = newTable("gvar")
713
+ gvar.version = 1
714
+ gvar.reserved = 0
715
+ gvar.variations = variations
716
+
717
+ def calcGlyphBounds(self):
718
+ """Calculate the bounding boxes of all glyphs in the `glyf` table.
719
+ This is usually not called explicitly by client code.
720
+ """
721
+ glyphTable = self.font["glyf"]
722
+ for glyph in glyphTable.glyphs.values():
723
+ glyph.recalcBounds(glyphTable)
724
+
725
+ def setupHorizontalMetrics(self, metrics):
726
+ """Create a new `hmtx` table, for horizontal metrics.
727
+
728
+ The `metrics` argument must be a dict, mapping glyph names to
729
+ `(width, leftSidebearing)` tuples.
730
+ """
731
+ self.setupMetrics("hmtx", metrics)
732
+
733
+ def setupVerticalMetrics(self, metrics):
734
+ """Create a new `vmtx` table, for horizontal metrics.
735
+
736
+ The `metrics` argument must be a dict, mapping glyph names to
737
+ `(height, topSidebearing)` tuples.
738
+ """
739
+ self.setupMetrics("vmtx", metrics)
740
+
741
+ def setupMetrics(self, tableTag, metrics):
742
+ """See `setupHorizontalMetrics()` and `setupVerticalMetrics()`."""
743
+ assert tableTag in ("hmtx", "vmtx")
744
+ mtxTable = self.font[tableTag] = newTable(tableTag)
745
+ roundedMetrics = {}
746
+ for gn in metrics:
747
+ w, lsb = metrics[gn]
748
+ roundedMetrics[gn] = int(round(w)), int(round(lsb))
749
+ mtxTable.metrics = roundedMetrics
750
+
751
+ def setupHorizontalHeader(self, **values):
752
+ """Create a new `hhea` table initialize it with default values,
753
+ which can be overridden by keyword arguments.
754
+ """
755
+ self._initTableWithValues("hhea", _hheaDefaults, values)
756
+
757
+ def setupVerticalHeader(self, **values):
758
+ """Create a new `vhea` table initialize it with default values,
759
+ which can be overridden by keyword arguments.
760
+ """
761
+ self._initTableWithValues("vhea", _vheaDefaults, values)
762
+
763
+ def setupVerticalOrigins(self, verticalOrigins, defaultVerticalOrigin=None):
764
+ """Create a new `VORG` table. The `verticalOrigins` argument must be
765
+ a dict, mapping glyph names to vertical origin values.
766
+
767
+ The `defaultVerticalOrigin` argument should be the most common vertical
768
+ origin value. If omitted, this value will be derived from the actual
769
+ values in the `verticalOrigins` argument.
770
+ """
771
+ if defaultVerticalOrigin is None:
772
+ # find the most frequent vorg value
773
+ bag = {}
774
+ for gn in verticalOrigins:
775
+ vorg = verticalOrigins[gn]
776
+ if vorg not in bag:
777
+ bag[vorg] = 1
778
+ else:
779
+ bag[vorg] += 1
780
+ defaultVerticalOrigin = sorted(
781
+ bag, key=lambda vorg: bag[vorg], reverse=True
782
+ )[0]
783
+ self._initTableWithValues(
784
+ "VORG",
785
+ {},
786
+ dict(VOriginRecords={}, defaultVertOriginY=defaultVerticalOrigin),
787
+ )
788
+ vorgTable = self.font["VORG"]
789
+ vorgTable.majorVersion = 1
790
+ vorgTable.minorVersion = 0
791
+ for gn in verticalOrigins:
792
+ vorgTable[gn] = verticalOrigins[gn]
793
+
794
+ def setupPost(self, keepGlyphNames=True, **values):
795
+ """Create a new `post` table and initialize it with default values,
796
+ which can be overridden by keyword arguments.
797
+ """
798
+ isCFF2 = "CFF2" in self.font
799
+ postTable = self._initTableWithValues("post", _postDefaults, values)
800
+ if (self.isTTF or isCFF2) and keepGlyphNames:
801
+ postTable.formatType = 2.0
802
+ postTable.extraNames = []
803
+ postTable.mapping = {}
804
+ else:
805
+ postTable.formatType = 3.0
806
+
807
+ def setupMaxp(self):
808
+ """Create a new `maxp` table. This is called implicitly by FontBuilder
809
+ itself and is usually not called by client code.
810
+ """
811
+ if self.isTTF:
812
+ defaults = _maxpDefaultsTTF
813
+ else:
814
+ defaults = _maxpDefaultsOTF
815
+ self._initTableWithValues("maxp", defaults, {})
816
+
817
+ def setupDummyDSIG(self):
818
+ """This adds an empty DSIG table to the font to make some MS applications
819
+ happy. This does not properly sign the font.
820
+ """
821
+ values = dict(
822
+ ulVersion=1,
823
+ usFlag=0,
824
+ usNumSigs=0,
825
+ signatureRecords=[],
826
+ )
827
+ self._initTableWithValues("DSIG", {}, values)
828
+
829
+ def addOpenTypeFeatures(self, features, filename=None, tables=None, debug=False):
830
+ """Add OpenType features to the font from a string containing
831
+ Feature File syntax.
832
+
833
+ The `filename` argument is used in error messages and to determine
834
+ where to look for "include" files.
835
+
836
+ The optional `tables` argument can be a list of OTL tables tags to
837
+ build, allowing the caller to only build selected OTL tables. See
838
+ `fontTools.feaLib` for details.
839
+
840
+ The optional `debug` argument controls whether to add source debugging
841
+ information to the font in the `Debg` table.
842
+ """
843
+ from .feaLib.builder import addOpenTypeFeaturesFromString
844
+
845
+ addOpenTypeFeaturesFromString(
846
+ self.font, features, filename=filename, tables=tables, debug=debug
847
+ )
848
+
849
+ def addFeatureVariations(self, conditionalSubstitutions, featureTag="rvrn"):
850
+ """Add conditional substitutions to a Variable Font.
851
+
852
+ See `fontTools.varLib.featureVars.addFeatureVariations`.
853
+ """
854
+ from .varLib import featureVars
855
+
856
+ if "fvar" not in self.font:
857
+ raise KeyError("'fvar' table is missing; can't add FeatureVariations.")
858
+
859
+ featureVars.addFeatureVariations(
860
+ self.font, conditionalSubstitutions, featureTag=featureTag
861
+ )
862
+
863
+ def setupCOLR(
864
+ self,
865
+ colorLayers,
866
+ version=None,
867
+ varStore=None,
868
+ varIndexMap=None,
869
+ clipBoxes=None,
870
+ allowLayerReuse=True,
871
+ ):
872
+ """Build new COLR table using color layers dictionary.
873
+
874
+ Cf. `fontTools.colorLib.builder.buildCOLR`.
875
+ """
876
+ from fontTools.colorLib.builder import buildCOLR
877
+
878
+ glyphMap = self.font.getReverseGlyphMap()
879
+ self.font["COLR"] = buildCOLR(
880
+ colorLayers,
881
+ version=version,
882
+ glyphMap=glyphMap,
883
+ varStore=varStore,
884
+ varIndexMap=varIndexMap,
885
+ clipBoxes=clipBoxes,
886
+ allowLayerReuse=allowLayerReuse,
887
+ )
888
+
889
+ def setupCPAL(
890
+ self,
891
+ palettes,
892
+ paletteTypes=None,
893
+ paletteLabels=None,
894
+ paletteEntryLabels=None,
895
+ ):
896
+ """Build new CPAL table using list of palettes.
897
+
898
+ Optionally build CPAL v1 table using paletteTypes, paletteLabels and
899
+ paletteEntryLabels.
900
+
901
+ Cf. `fontTools.colorLib.builder.buildCPAL`.
902
+ """
903
+ from fontTools.colorLib.builder import buildCPAL
904
+
905
+ self.font["CPAL"] = buildCPAL(
906
+ palettes,
907
+ paletteTypes=paletteTypes,
908
+ paletteLabels=paletteLabels,
909
+ paletteEntryLabels=paletteEntryLabels,
910
+ nameTable=self.font.get("name"),
911
+ )
912
+
913
+ def setupStat(self, axes, locations=None, elidedFallbackName=2):
914
+ """Build a new 'STAT' table.
915
+
916
+ See `fontTools.otlLib.builder.buildStatTable` for details about
917
+ the arguments.
918
+ """
919
+ from .otlLib.builder import buildStatTable
920
+
921
+ buildStatTable(self.font, axes, locations, elidedFallbackName)
922
+
923
+
924
+ def buildCmapSubTable(cmapping, format, platformID, platEncID):
925
+ subTable = cmap_classes[format](format)
926
+ subTable.cmap = cmapping
927
+ subTable.platformID = platformID
928
+ subTable.platEncID = platEncID
929
+ subTable.language = 0
930
+ return subTable
931
+
932
+
933
+ def addFvar(font, axes, instances):
934
+ from .ttLib.tables._f_v_a_r import Axis, NamedInstance
935
+
936
+ assert axes
937
+
938
+ fvar = newTable("fvar")
939
+ nameTable = font["name"]
940
+
941
+ for axis_def in axes:
942
+ axis = Axis()
943
+
944
+ if isinstance(axis_def, tuple):
945
+ (
946
+ axis.axisTag,
947
+ axis.minValue,
948
+ axis.defaultValue,
949
+ axis.maxValue,
950
+ name,
951
+ ) = axis_def
952
+ else:
953
+ (axis.axisTag, axis.minValue, axis.defaultValue, axis.maxValue, name) = (
954
+ axis_def.tag,
955
+ axis_def.minimum,
956
+ axis_def.default,
957
+ axis_def.maximum,
958
+ axis_def.name,
959
+ )
960
+ if axis_def.hidden:
961
+ axis.flags = 0x0001 # HIDDEN_AXIS
962
+
963
+ if isinstance(name, str):
964
+ name = dict(en=name)
965
+
966
+ axis.axisNameID = nameTable.addMultilingualName(name, ttFont=font)
967
+ fvar.axes.append(axis)
968
+
969
+ for instance in instances:
970
+ if isinstance(instance, dict):
971
+ coordinates = instance["location"]
972
+ name = instance["stylename"]
973
+ psname = instance.get("postscriptfontname")
974
+ else:
975
+ coordinates = instance.location
976
+ name = instance.localisedStyleName or instance.styleName
977
+ psname = instance.postScriptFontName
978
+
979
+ if isinstance(name, str):
980
+ name = dict(en=name)
981
+
982
+ inst = NamedInstance()
983
+ inst.subfamilyNameID = nameTable.addMultilingualName(name, ttFont=font)
984
+ if psname is not None:
985
+ inst.postscriptNameID = nameTable.addName(psname)
986
+ inst.coordinates = coordinates
987
+ fvar.instances.append(inst)
988
+
989
+ font["fvar"] = fvar
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.04 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (3.06 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/removeOverlaps.cpython-310.pyc ADDED
Binary file (9.97 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/reorderGlyphs.cpython-310.pyc ADDED
Binary file (7.84 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/__pycache__/sfnt.cpython-310.pyc ADDED
Binary file (17.3 kB). View file
 
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/macUtils.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ttLib.macUtils.py -- Various Mac-specific stuff."""
2
+
3
+ from io import BytesIO
4
+ from fontTools.misc.macRes import ResourceReader, ResourceError
5
+
6
+
7
+ def getSFNTResIndices(path):
8
+ """Determine whether a file has a 'sfnt' resource fork or not."""
9
+ try:
10
+ reader = ResourceReader(path)
11
+ indices = reader.getIndices("sfnt")
12
+ reader.close()
13
+ return indices
14
+ except ResourceError:
15
+ return []
16
+
17
+
18
+ def openTTFonts(path):
19
+ """Given a pathname, return a list of TTFont objects. In the case
20
+ of a flat TTF/OTF file, the list will contain just one font object;
21
+ but in the case of a Mac font suitcase it will contain as many
22
+ font objects as there are sfnt resources in the file.
23
+ """
24
+ from fontTools import ttLib
25
+
26
+ fonts = []
27
+ sfnts = getSFNTResIndices(path)
28
+ if not sfnts:
29
+ fonts.append(ttLib.TTFont(path))
30
+ else:
31
+ for index in sfnts:
32
+ fonts.append(ttLib.TTFont(path, index))
33
+ if not fonts:
34
+ raise ttLib.TTLibError("no fonts found in file '%s'" % path)
35
+ return fonts
36
+
37
+
38
+ class SFNTResourceReader(BytesIO):
39
+ """Simple read-only file wrapper for 'sfnt' resources."""
40
+
41
+ def __init__(self, path, res_name_or_index):
42
+ from fontTools import ttLib
43
+
44
+ reader = ResourceReader(path)
45
+ if isinstance(res_name_or_index, str):
46
+ rsrc = reader.getNamedResource("sfnt", res_name_or_index)
47
+ else:
48
+ rsrc = reader.getIndResource("sfnt", res_name_or_index)
49
+ if rsrc is None:
50
+ raise ttLib.TTLibError("sfnt resource not found: %s" % res_name_or_index)
51
+ reader.close()
52
+ self.rsrc = rsrc
53
+ super(SFNTResourceReader, self).__init__(rsrc.data)
54
+ self.name = path
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/reorderGlyphs.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reorder glyphs in a font."""
2
+
3
+ __author__ = "Rod Sheeter"
4
+
5
+ # See https://docs.google.com/document/d/1h9O-C_ndods87uY0QeIIcgAMiX2gDTpvO_IhMJsKAqs/
6
+ # for details.
7
+
8
+
9
+ from fontTools import ttLib
10
+ from fontTools.ttLib.tables import otBase
11
+ from fontTools.ttLib.tables import otTables as ot
12
+ from abc import ABC, abstractmethod
13
+ from dataclasses import dataclass
14
+ from collections import deque
15
+ from typing import (
16
+ Optional,
17
+ Any,
18
+ Callable,
19
+ Deque,
20
+ Iterable,
21
+ List,
22
+ NamedTuple,
23
+ Tuple,
24
+ Union,
25
+ )
26
+
27
+
28
+ _COVERAGE_ATTR = "Coverage" # tables that have one coverage use this name
29
+
30
+
31
+ def _sort_by_gid(
32
+ get_glyph_id: Callable[[str], int],
33
+ glyphs: List[str],
34
+ parallel_list: Optional[List[Any]],
35
+ ):
36
+ if parallel_list:
37
+ reordered = sorted(
38
+ ((g, e) for g, e in zip(glyphs, parallel_list)),
39
+ key=lambda t: get_glyph_id(t[0]),
40
+ )
41
+ sorted_glyphs, sorted_parallel_list = map(list, zip(*reordered))
42
+ parallel_list[:] = sorted_parallel_list
43
+ else:
44
+ sorted_glyphs = sorted(glyphs, key=get_glyph_id)
45
+
46
+ glyphs[:] = sorted_glyphs
47
+
48
+
49
+ def _get_dotted_attr(value: Any, dotted_attr: str) -> Any:
50
+ attr_names = dotted_attr.split(".")
51
+ assert attr_names
52
+
53
+ while attr_names:
54
+ attr_name = attr_names.pop(0)
55
+ value = getattr(value, attr_name)
56
+ return value
57
+
58
+
59
+ class ReorderRule(ABC):
60
+ """A rule to reorder something in a font to match the fonts glyph order."""
61
+
62
+ @abstractmethod
63
+ def apply(self, font: ttLib.TTFont, value: otBase.BaseTable) -> None: ...
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class ReorderCoverage(ReorderRule):
68
+ """Reorder a Coverage table, and optionally a list that is sorted parallel to it."""
69
+
70
+ # A list that is parallel to Coverage
71
+ parallel_list_attr: Optional[str] = None
72
+ coverage_attr: str = _COVERAGE_ATTR
73
+
74
+ def apply(self, font: ttLib.TTFont, value: otBase.BaseTable) -> None:
75
+ coverage = _get_dotted_attr(value, self.coverage_attr)
76
+
77
+ if type(coverage) is not list:
78
+ # Normal path, process one coverage that might have a parallel list
79
+ parallel_list = None
80
+ if self.parallel_list_attr:
81
+ parallel_list = _get_dotted_attr(value, self.parallel_list_attr)
82
+ assert (
83
+ type(parallel_list) is list
84
+ ), f"{self.parallel_list_attr} should be a list"
85
+ assert len(parallel_list) == len(coverage.glyphs), "Nothing makes sense"
86
+
87
+ _sort_by_gid(font.getGlyphID, coverage.glyphs, parallel_list)
88
+
89
+ else:
90
+ # A few tables have a list of coverage. No parallel list can exist.
91
+ assert (
92
+ not self.parallel_list_attr
93
+ ), f"Can't have multiple coverage AND a parallel list; {self}"
94
+ for coverage_entry in coverage:
95
+ _sort_by_gid(font.getGlyphID, coverage_entry.glyphs, None)
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class ReorderList(ReorderRule):
100
+ """Reorder the items within a list to match the updated glyph order.
101
+
102
+ Useful when a list ordered by coverage itself contains something ordered by a gid.
103
+ For example, the PairSet table of https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-2-pair-adjustment-positioning-subtable.
104
+ """
105
+
106
+ list_attr: str
107
+ key: str
108
+
109
+ def apply(self, font: ttLib.TTFont, value: otBase.BaseTable) -> None:
110
+ lst = _get_dotted_attr(value, self.list_attr)
111
+ assert isinstance(lst, list), f"{self.list_attr} should be a list"
112
+ lst.sort(key=lambda v: font.getGlyphID(getattr(v, self.key)))
113
+
114
+
115
+ # (Type, Optional Format) => List[ReorderRule]
116
+ # Encodes the relationships Cosimo identified
117
+ _REORDER_RULES = {
118
+ # GPOS
119
+ (ot.SinglePos, 1): [ReorderCoverage()],
120
+ (ot.SinglePos, 2): [ReorderCoverage(parallel_list_attr="Value")],
121
+ (ot.PairPos, 1): [ReorderCoverage(parallel_list_attr="PairSet")],
122
+ (ot.PairSet, None): [ReorderList("PairValueRecord", key="SecondGlyph")],
123
+ (ot.PairPos, 2): [ReorderCoverage()],
124
+ (ot.CursivePos, 1): [ReorderCoverage(parallel_list_attr="EntryExitRecord")],
125
+ (ot.MarkBasePos, 1): [
126
+ ReorderCoverage(
127
+ coverage_attr="MarkCoverage", parallel_list_attr="MarkArray.MarkRecord"
128
+ ),
129
+ ReorderCoverage(
130
+ coverage_attr="BaseCoverage", parallel_list_attr="BaseArray.BaseRecord"
131
+ ),
132
+ ],
133
+ (ot.MarkLigPos, 1): [
134
+ ReorderCoverage(
135
+ coverage_attr="MarkCoverage", parallel_list_attr="MarkArray.MarkRecord"
136
+ ),
137
+ ReorderCoverage(
138
+ coverage_attr="LigatureCoverage",
139
+ parallel_list_attr="LigatureArray.LigatureAttach",
140
+ ),
141
+ ],
142
+ (ot.MarkMarkPos, 1): [
143
+ ReorderCoverage(
144
+ coverage_attr="Mark1Coverage", parallel_list_attr="Mark1Array.MarkRecord"
145
+ ),
146
+ ReorderCoverage(
147
+ coverage_attr="Mark2Coverage", parallel_list_attr="Mark2Array.Mark2Record"
148
+ ),
149
+ ],
150
+ (ot.ContextPos, 1): [ReorderCoverage(parallel_list_attr="PosRuleSet")],
151
+ (ot.ContextPos, 2): [ReorderCoverage()],
152
+ (ot.ContextPos, 3): [ReorderCoverage()],
153
+ (ot.ChainContextPos, 1): [ReorderCoverage(parallel_list_attr="ChainPosRuleSet")],
154
+ (ot.ChainContextPos, 2): [ReorderCoverage()],
155
+ (ot.ChainContextPos, 3): [
156
+ ReorderCoverage(coverage_attr="BacktrackCoverage"),
157
+ ReorderCoverage(coverage_attr="InputCoverage"),
158
+ ReorderCoverage(coverage_attr="LookAheadCoverage"),
159
+ ],
160
+ # GSUB
161
+ (ot.ContextSubst, 1): [ReorderCoverage(parallel_list_attr="SubRuleSet")],
162
+ (ot.ContextSubst, 2): [ReorderCoverage()],
163
+ (ot.ContextSubst, 3): [ReorderCoverage()],
164
+ (ot.ChainContextSubst, 1): [ReorderCoverage(parallel_list_attr="ChainSubRuleSet")],
165
+ (ot.ChainContextSubst, 2): [ReorderCoverage()],
166
+ (ot.ChainContextSubst, 3): [
167
+ ReorderCoverage(coverage_attr="BacktrackCoverage"),
168
+ ReorderCoverage(coverage_attr="InputCoverage"),
169
+ ReorderCoverage(coverage_attr="LookAheadCoverage"),
170
+ ],
171
+ (ot.ReverseChainSingleSubst, 1): [
172
+ ReorderCoverage(parallel_list_attr="Substitute"),
173
+ ReorderCoverage(coverage_attr="BacktrackCoverage"),
174
+ ReorderCoverage(coverage_attr="LookAheadCoverage"),
175
+ ],
176
+ # GDEF
177
+ (ot.AttachList, None): [ReorderCoverage(parallel_list_attr="AttachPoint")],
178
+ (ot.LigCaretList, None): [ReorderCoverage(parallel_list_attr="LigGlyph")],
179
+ (ot.MarkGlyphSetsDef, None): [ReorderCoverage()],
180
+ # MATH
181
+ (ot.MathGlyphInfo, None): [ReorderCoverage(coverage_attr="ExtendedShapeCoverage")],
182
+ (ot.MathItalicsCorrectionInfo, None): [
183
+ ReorderCoverage(parallel_list_attr="ItalicsCorrection")
184
+ ],
185
+ (ot.MathTopAccentAttachment, None): [
186
+ ReorderCoverage(
187
+ coverage_attr="TopAccentCoverage", parallel_list_attr="TopAccentAttachment"
188
+ )
189
+ ],
190
+ (ot.MathKernInfo, None): [
191
+ ReorderCoverage(
192
+ coverage_attr="MathKernCoverage", parallel_list_attr="MathKernInfoRecords"
193
+ )
194
+ ],
195
+ (ot.MathVariants, None): [
196
+ ReorderCoverage(
197
+ coverage_attr="VertGlyphCoverage",
198
+ parallel_list_attr="VertGlyphConstruction",
199
+ ),
200
+ ReorderCoverage(
201
+ coverage_attr="HorizGlyphCoverage",
202
+ parallel_list_attr="HorizGlyphConstruction",
203
+ ),
204
+ ],
205
+ }
206
+
207
+
208
+ # TODO Port to otTraverse
209
+
210
+ SubTablePath = Tuple[otBase.BaseTable.SubTableEntry, ...]
211
+
212
+
213
+ def _bfs_base_table(
214
+ root: otBase.BaseTable, root_accessor: str
215
+ ) -> Iterable[SubTablePath]:
216
+ yield from _traverse_ot_data(
217
+ root, root_accessor, lambda frontier, new: frontier.extend(new)
218
+ )
219
+
220
+
221
+ # Given f(current frontier, new entries) add new entries to frontier
222
+ AddToFrontierFn = Callable[[Deque[SubTablePath], List[SubTablePath]], None]
223
+
224
+
225
+ def _traverse_ot_data(
226
+ root: otBase.BaseTable, root_accessor: str, add_to_frontier_fn: AddToFrontierFn
227
+ ) -> Iterable[SubTablePath]:
228
+ # no visited because general otData is forward-offset only and thus cannot cycle
229
+
230
+ frontier: Deque[SubTablePath] = deque()
231
+ frontier.append((otBase.BaseTable.SubTableEntry(root_accessor, root),))
232
+ while frontier:
233
+ # path is (value, attr_name) tuples. attr_name is attr of parent to get value
234
+ path = frontier.popleft()
235
+ current = path[-1].value
236
+
237
+ yield path
238
+
239
+ new_entries = []
240
+ for subtable_entry in current.iterSubTables():
241
+ new_entries.append(path + (subtable_entry,))
242
+
243
+ add_to_frontier_fn(frontier, new_entries)
244
+
245
+
246
+ def reorderGlyphs(font: ttLib.TTFont, new_glyph_order: List[str]):
247
+ old_glyph_order = font.getGlyphOrder()
248
+ if len(new_glyph_order) != len(old_glyph_order):
249
+ raise ValueError(
250
+ f"New glyph order contains {len(new_glyph_order)} glyphs, "
251
+ f"but font has {len(old_glyph_order)} glyphs"
252
+ )
253
+
254
+ if set(old_glyph_order) != set(new_glyph_order):
255
+ raise ValueError(
256
+ "New glyph order does not contain the same set of glyphs as the font:\n"
257
+ f"* only in new: {set(new_glyph_order) - set(old_glyph_order)}\n"
258
+ f"* only in old: {set(old_glyph_order) - set(new_glyph_order)}"
259
+ )
260
+
261
+ # Changing the order of glyphs in a TTFont requires that all tables that use
262
+ # glyph indexes have been fully.
263
+ # Cf. https://github.com/fonttools/fonttools/issues/2060
264
+ font.ensureDecompiled()
265
+ not_loaded = sorted(t for t in font.keys() if not font.isLoaded(t))
266
+ if not_loaded:
267
+ raise ValueError(f"Everything should be loaded, following aren't: {not_loaded}")
268
+
269
+ font.setGlyphOrder(new_glyph_order)
270
+
271
+ coverage_containers = {"GDEF", "GPOS", "GSUB", "MATH"}
272
+ for tag in coverage_containers:
273
+ if tag in font.keys():
274
+ for path in _bfs_base_table(font[tag].table, f'font["{tag}"]'):
275
+ value = path[-1].value
276
+ reorder_key = (type(value), getattr(value, "Format", None))
277
+ for reorder in _REORDER_RULES.get(reorder_key, []):
278
+ reorder.apply(font, value)
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/sfnt.py ADDED
@@ -0,0 +1,662 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ttLib/sfnt.py -- low-level module to deal with the sfnt file format.
2
+
3
+ Defines two public classes:
4
+
5
+ - SFNTReader
6
+ - SFNTWriter
7
+
8
+ (Normally you don't have to use these classes explicitly; they are
9
+ used automatically by ttLib.TTFont.)
10
+
11
+ The reading and writing of sfnt files is separated in two distinct
12
+ classes, since whenever the number of tables changes or whenever
13
+ a table's length changes you need to rewrite the whole file anyway.
14
+ """
15
+
16
+ from io import BytesIO
17
+ from types import SimpleNamespace
18
+ from fontTools.misc.textTools import Tag
19
+ from fontTools.misc import sstruct
20
+ from fontTools.ttLib import TTLibError, TTLibFileIsCollectionError
21
+ import struct
22
+ from collections import OrderedDict
23
+ import logging
24
+
25
+
26
+ log = logging.getLogger(__name__)
27
+
28
+
29
+ class SFNTReader(object):
30
+ def __new__(cls, *args, **kwargs):
31
+ """Return an instance of the SFNTReader sub-class which is compatible
32
+ with the input file type.
33
+ """
34
+ if args and cls is SFNTReader:
35
+ infile = args[0]
36
+ infile.seek(0)
37
+ sfntVersion = Tag(infile.read(4))
38
+ infile.seek(0)
39
+ if sfntVersion == "wOF2":
40
+ # return new WOFF2Reader object
41
+ from fontTools.ttLib.woff2 import WOFF2Reader
42
+
43
+ return object.__new__(WOFF2Reader)
44
+ # return default object
45
+ return object.__new__(cls)
46
+
47
+ def __init__(self, file, checkChecksums=0, fontNumber=-1):
48
+ self.file = file
49
+ self.checkChecksums = checkChecksums
50
+
51
+ self.flavor = None
52
+ self.flavorData = None
53
+ self.DirectoryEntry = SFNTDirectoryEntry
54
+ self.file.seek(0)
55
+ self.sfntVersion = self.file.read(4)
56
+ self.file.seek(0)
57
+ if self.sfntVersion == b"ttcf":
58
+ header = readTTCHeader(self.file)
59
+ numFonts = header.numFonts
60
+ if not 0 <= fontNumber < numFonts:
61
+ raise TTLibFileIsCollectionError(
62
+ "specify a font number between 0 and %d (inclusive)"
63
+ % (numFonts - 1)
64
+ )
65
+ self.numFonts = numFonts
66
+ self.file.seek(header.offsetTable[fontNumber])
67
+ data = self.file.read(sfntDirectorySize)
68
+ if len(data) != sfntDirectorySize:
69
+ raise TTLibError("Not a Font Collection (not enough data)")
70
+ sstruct.unpack(sfntDirectoryFormat, data, self)
71
+ elif self.sfntVersion == b"wOFF":
72
+ self.flavor = "woff"
73
+ self.DirectoryEntry = WOFFDirectoryEntry
74
+ data = self.file.read(woffDirectorySize)
75
+ if len(data) != woffDirectorySize:
76
+ raise TTLibError("Not a WOFF font (not enough data)")
77
+ sstruct.unpack(woffDirectoryFormat, data, self)
78
+ else:
79
+ data = self.file.read(sfntDirectorySize)
80
+ if len(data) != sfntDirectorySize:
81
+ raise TTLibError("Not a TrueType or OpenType font (not enough data)")
82
+ sstruct.unpack(sfntDirectoryFormat, data, self)
83
+ self.sfntVersion = Tag(self.sfntVersion)
84
+
85
+ if self.sfntVersion not in ("\x00\x01\x00\x00", "OTTO", "true"):
86
+ raise TTLibError("Not a TrueType or OpenType font (bad sfntVersion)")
87
+ tables = {}
88
+ for i in range(self.numTables):
89
+ entry = self.DirectoryEntry()
90
+ entry.fromFile(self.file)
91
+ tag = Tag(entry.tag)
92
+ tables[tag] = entry
93
+ self.tables = OrderedDict(sorted(tables.items(), key=lambda i: i[1].offset))
94
+
95
+ # Load flavor data if any
96
+ if self.flavor == "woff":
97
+ self.flavorData = WOFFFlavorData(self)
98
+
99
+ def has_key(self, tag):
100
+ return tag in self.tables
101
+
102
+ __contains__ = has_key
103
+
104
+ def keys(self):
105
+ return self.tables.keys()
106
+
107
+ def __getitem__(self, tag):
108
+ """Fetch the raw table data."""
109
+ entry = self.tables[Tag(tag)]
110
+ data = entry.loadData(self.file)
111
+ if self.checkChecksums:
112
+ if tag == "head":
113
+ # Beh: we have to special-case the 'head' table.
114
+ checksum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:])
115
+ else:
116
+ checksum = calcChecksum(data)
117
+ if self.checkChecksums > 1:
118
+ # Be obnoxious, and barf when it's wrong
119
+ assert checksum == entry.checkSum, "bad checksum for '%s' table" % tag
120
+ elif checksum != entry.checkSum:
121
+ # Be friendly, and just log a warning.
122
+ log.warning("bad checksum for '%s' table", tag)
123
+ return data
124
+
125
+ def __delitem__(self, tag):
126
+ del self.tables[Tag(tag)]
127
+
128
+ def close(self):
129
+ self.file.close()
130
+
131
+ # We define custom __getstate__ and __setstate__ to make SFNTReader pickle-able
132
+ # and deepcopy-able. When a TTFont is loaded as lazy=True, SFNTReader holds a
133
+ # reference to an external file object which is not pickleable. So in __getstate__
134
+ # we store the file name and current position, and in __setstate__ we reopen the
135
+ # same named file after unpickling.
136
+
137
+ def __getstate__(self):
138
+ if isinstance(self.file, BytesIO):
139
+ # BytesIO is already pickleable, return the state unmodified
140
+ return self.__dict__
141
+
142
+ # remove unpickleable file attribute, and only store its name and pos
143
+ state = self.__dict__.copy()
144
+ del state["file"]
145
+ state["_filename"] = self.file.name
146
+ state["_filepos"] = self.file.tell()
147
+ return state
148
+
149
+ def __setstate__(self, state):
150
+ if "file" not in state:
151
+ self.file = open(state.pop("_filename"), "rb")
152
+ self.file.seek(state.pop("_filepos"))
153
+ self.__dict__.update(state)
154
+
155
+
156
+ # default compression level for WOFF 1.0 tables and metadata
157
+ ZLIB_COMPRESSION_LEVEL = 6
158
+
159
+ # if set to True, use zopfli instead of zlib for compressing WOFF 1.0.
160
+ # The Python bindings are available at https://pypi.python.org/pypi/zopfli
161
+ USE_ZOPFLI = False
162
+
163
+ # mapping between zlib's compression levels and zopfli's 'numiterations'.
164
+ # Use lower values for files over several MB in size or it will be too slow
165
+ ZOPFLI_LEVELS = {
166
+ # 0: 0, # can't do 0 iterations...
167
+ 1: 1,
168
+ 2: 3,
169
+ 3: 5,
170
+ 4: 8,
171
+ 5: 10,
172
+ 6: 15,
173
+ 7: 25,
174
+ 8: 50,
175
+ 9: 100,
176
+ }
177
+
178
+
179
+ def compress(data, level=ZLIB_COMPRESSION_LEVEL):
180
+ """Compress 'data' to Zlib format. If 'USE_ZOPFLI' variable is True,
181
+ zopfli is used instead of the zlib module.
182
+ The compression 'level' must be between 0 and 9. 1 gives best speed,
183
+ 9 gives best compression (0 gives no compression at all).
184
+ The default value is a compromise between speed and compression (6).
185
+ """
186
+ if not (0 <= level <= 9):
187
+ raise ValueError("Bad compression level: %s" % level)
188
+ if not USE_ZOPFLI or level == 0:
189
+ from zlib import compress
190
+
191
+ return compress(data, level)
192
+ else:
193
+ from zopfli.zlib import compress
194
+
195
+ return compress(data, numiterations=ZOPFLI_LEVELS[level])
196
+
197
+
198
+ class SFNTWriter(object):
199
+ def __new__(cls, *args, **kwargs):
200
+ """Return an instance of the SFNTWriter sub-class which is compatible
201
+ with the specified 'flavor'.
202
+ """
203
+ flavor = None
204
+ if kwargs and "flavor" in kwargs:
205
+ flavor = kwargs["flavor"]
206
+ elif args and len(args) > 3:
207
+ flavor = args[3]
208
+ if cls is SFNTWriter:
209
+ if flavor == "woff2":
210
+ # return new WOFF2Writer object
211
+ from fontTools.ttLib.woff2 import WOFF2Writer
212
+
213
+ return object.__new__(WOFF2Writer)
214
+ # return default object
215
+ return object.__new__(cls)
216
+
217
+ def __init__(
218
+ self,
219
+ file,
220
+ numTables,
221
+ sfntVersion="\000\001\000\000",
222
+ flavor=None,
223
+ flavorData=None,
224
+ ):
225
+ self.file = file
226
+ self.numTables = numTables
227
+ self.sfntVersion = Tag(sfntVersion)
228
+ self.flavor = flavor
229
+ self.flavorData = flavorData
230
+
231
+ if self.flavor == "woff":
232
+ self.directoryFormat = woffDirectoryFormat
233
+ self.directorySize = woffDirectorySize
234
+ self.DirectoryEntry = WOFFDirectoryEntry
235
+
236
+ self.signature = "wOFF"
237
+
238
+ # to calculate WOFF checksum adjustment, we also need the original SFNT offsets
239
+ self.origNextTableOffset = (
240
+ sfntDirectorySize + numTables * sfntDirectoryEntrySize
241
+ )
242
+ else:
243
+ assert not self.flavor, "Unknown flavor '%s'" % self.flavor
244
+ self.directoryFormat = sfntDirectoryFormat
245
+ self.directorySize = sfntDirectorySize
246
+ self.DirectoryEntry = SFNTDirectoryEntry
247
+
248
+ from fontTools.ttLib import getSearchRange
249
+
250
+ self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(
251
+ numTables, 16
252
+ )
253
+
254
+ self.directoryOffset = self.file.tell()
255
+ self.nextTableOffset = (
256
+ self.directoryOffset
257
+ + self.directorySize
258
+ + numTables * self.DirectoryEntry.formatSize
259
+ )
260
+ # clear out directory area
261
+ self.file.seek(self.nextTableOffset)
262
+ # make sure we're actually where we want to be. (old cStringIO bug)
263
+ self.file.write(b"\0" * (self.nextTableOffset - self.file.tell()))
264
+ self.tables = OrderedDict()
265
+
266
+ def setEntry(self, tag, entry):
267
+ if tag in self.tables:
268
+ raise TTLibError("cannot rewrite '%s' table" % tag)
269
+
270
+ self.tables[tag] = entry
271
+
272
+ def __setitem__(self, tag, data):
273
+ """Write raw table data to disk."""
274
+ if tag in self.tables:
275
+ raise TTLibError("cannot rewrite '%s' table" % tag)
276
+
277
+ entry = self.DirectoryEntry()
278
+ entry.tag = tag
279
+ entry.offset = self.nextTableOffset
280
+ if tag == "head":
281
+ entry.checkSum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:])
282
+ self.headTable = data
283
+ entry.uncompressed = True
284
+ else:
285
+ entry.checkSum = calcChecksum(data)
286
+ entry.saveData(self.file, data)
287
+
288
+ if self.flavor == "woff":
289
+ entry.origOffset = self.origNextTableOffset
290
+ self.origNextTableOffset += (entry.origLength + 3) & ~3
291
+
292
+ self.nextTableOffset = self.nextTableOffset + ((entry.length + 3) & ~3)
293
+ # Add NUL bytes to pad the table data to a 4-byte boundary.
294
+ # Don't depend on f.seek() as we need to add the padding even if no
295
+ # subsequent write follows (seek is lazy), ie. after the final table
296
+ # in the font.
297
+ self.file.write(b"\0" * (self.nextTableOffset - self.file.tell()))
298
+ assert self.nextTableOffset == self.file.tell()
299
+
300
+ self.setEntry(tag, entry)
301
+
302
+ def __getitem__(self, tag):
303
+ return self.tables[tag]
304
+
305
+ def close(self):
306
+ """All tables must have been written to disk. Now write the
307
+ directory.
308
+ """
309
+ tables = sorted(self.tables.items())
310
+ if len(tables) != self.numTables:
311
+ raise TTLibError(
312
+ "wrong number of tables; expected %d, found %d"
313
+ % (self.numTables, len(tables))
314
+ )
315
+
316
+ if self.flavor == "woff":
317
+ self.signature = b"wOFF"
318
+ self.reserved = 0
319
+
320
+ self.totalSfntSize = 12
321
+ self.totalSfntSize += 16 * len(tables)
322
+ for tag, entry in tables:
323
+ self.totalSfntSize += (entry.origLength + 3) & ~3
324
+
325
+ data = self.flavorData if self.flavorData else WOFFFlavorData()
326
+ if data.majorVersion is not None and data.minorVersion is not None:
327
+ self.majorVersion = data.majorVersion
328
+ self.minorVersion = data.minorVersion
329
+ else:
330
+ if hasattr(self, "headTable"):
331
+ self.majorVersion, self.minorVersion = struct.unpack(
332
+ ">HH", self.headTable[4:8]
333
+ )
334
+ else:
335
+ self.majorVersion = self.minorVersion = 0
336
+ if data.metaData:
337
+ self.metaOrigLength = len(data.metaData)
338
+ self.file.seek(0, 2)
339
+ self.metaOffset = self.file.tell()
340
+ compressedMetaData = compress(data.metaData)
341
+ self.metaLength = len(compressedMetaData)
342
+ self.file.write(compressedMetaData)
343
+ else:
344
+ self.metaOffset = self.metaLength = self.metaOrigLength = 0
345
+ if data.privData:
346
+ self.file.seek(0, 2)
347
+ off = self.file.tell()
348
+ paddedOff = (off + 3) & ~3
349
+ self.file.write(b"\0" * (paddedOff - off))
350
+ self.privOffset = self.file.tell()
351
+ self.privLength = len(data.privData)
352
+ self.file.write(data.privData)
353
+ else:
354
+ self.privOffset = self.privLength = 0
355
+
356
+ self.file.seek(0, 2)
357
+ self.length = self.file.tell()
358
+
359
+ else:
360
+ assert not self.flavor, "Unknown flavor '%s'" % self.flavor
361
+ pass
362
+
363
+ directory = sstruct.pack(self.directoryFormat, self)
364
+
365
+ self.file.seek(self.directoryOffset + self.directorySize)
366
+ seenHead = 0
367
+ for tag, entry in tables:
368
+ if tag == "head":
369
+ seenHead = 1
370
+ directory = directory + entry.toString()
371
+ if seenHead:
372
+ self.writeMasterChecksum(directory)
373
+ self.file.seek(self.directoryOffset)
374
+ self.file.write(directory)
375
+
376
+ def _calcMasterChecksum(self, directory):
377
+ # calculate checkSumAdjustment
378
+ tags = list(self.tables.keys())
379
+ checksums = []
380
+ for i in range(len(tags)):
381
+ checksums.append(self.tables[tags[i]].checkSum)
382
+
383
+ if self.DirectoryEntry != SFNTDirectoryEntry:
384
+ # Create a SFNT directory for checksum calculation purposes
385
+ from fontTools.ttLib import getSearchRange
386
+
387
+ self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(
388
+ self.numTables, 16
389
+ )
390
+ directory = sstruct.pack(sfntDirectoryFormat, self)
391
+ tables = sorted(self.tables.items())
392
+ for tag, entry in tables:
393
+ sfntEntry = SFNTDirectoryEntry()
394
+ sfntEntry.tag = entry.tag
395
+ sfntEntry.checkSum = entry.checkSum
396
+ sfntEntry.offset = entry.origOffset
397
+ sfntEntry.length = entry.origLength
398
+ directory = directory + sfntEntry.toString()
399
+
400
+ directory_end = sfntDirectorySize + len(self.tables) * sfntDirectoryEntrySize
401
+ assert directory_end == len(directory)
402
+
403
+ checksums.append(calcChecksum(directory))
404
+ checksum = sum(checksums) & 0xFFFFFFFF
405
+ # BiboAfba!
406
+ checksumadjustment = (0xB1B0AFBA - checksum) & 0xFFFFFFFF
407
+ return checksumadjustment
408
+
409
+ def writeMasterChecksum(self, directory):
410
+ checksumadjustment = self._calcMasterChecksum(directory)
411
+ # write the checksum to the file
412
+ self.file.seek(self.tables["head"].offset + 8)
413
+ self.file.write(struct.pack(">L", checksumadjustment))
414
+
415
+ def reordersTables(self):
416
+ return False
417
+
418
+
419
+ # -- sfnt directory helpers and cruft
420
+
421
+ ttcHeaderFormat = """
422
+ > # big endian
423
+ TTCTag: 4s # "ttcf"
424
+ Version: L # 0x00010000 or 0x00020000
425
+ numFonts: L # number of fonts
426
+ # OffsetTable[numFonts]: L # array with offsets from beginning of file
427
+ # ulDsigTag: L # version 2.0 only
428
+ # ulDsigLength: L # version 2.0 only
429
+ # ulDsigOffset: L # version 2.0 only
430
+ """
431
+
432
+ ttcHeaderSize = sstruct.calcsize(ttcHeaderFormat)
433
+
434
+ sfntDirectoryFormat = """
435
+ > # big endian
436
+ sfntVersion: 4s
437
+ numTables: H # number of tables
438
+ searchRange: H # (max2 <= numTables)*16
439
+ entrySelector: H # log2(max2 <= numTables)
440
+ rangeShift: H # numTables*16-searchRange
441
+ """
442
+
443
+ sfntDirectorySize = sstruct.calcsize(sfntDirectoryFormat)
444
+
445
+ sfntDirectoryEntryFormat = """
446
+ > # big endian
447
+ tag: 4s
448
+ checkSum: L
449
+ offset: L
450
+ length: L
451
+ """
452
+
453
+ sfntDirectoryEntrySize = sstruct.calcsize(sfntDirectoryEntryFormat)
454
+
455
+ woffDirectoryFormat = """
456
+ > # big endian
457
+ signature: 4s # "wOFF"
458
+ sfntVersion: 4s
459
+ length: L # total woff file size
460
+ numTables: H # number of tables
461
+ reserved: H # set to 0
462
+ totalSfntSize: L # uncompressed size
463
+ majorVersion: H # major version of WOFF file
464
+ minorVersion: H # minor version of WOFF file
465
+ metaOffset: L # offset to metadata block
466
+ metaLength: L # length of compressed metadata
467
+ metaOrigLength: L # length of uncompressed metadata
468
+ privOffset: L # offset to private data block
469
+ privLength: L # length of private data block
470
+ """
471
+
472
+ woffDirectorySize = sstruct.calcsize(woffDirectoryFormat)
473
+
474
+ woffDirectoryEntryFormat = """
475
+ > # big endian
476
+ tag: 4s
477
+ offset: L
478
+ length: L # compressed length
479
+ origLength: L # original length
480
+ checkSum: L # original checksum
481
+ """
482
+
483
+ woffDirectoryEntrySize = sstruct.calcsize(woffDirectoryEntryFormat)
484
+
485
+
486
+ class DirectoryEntry(object):
487
+ def __init__(self):
488
+ self.uncompressed = False # if True, always embed entry raw
489
+
490
+ def fromFile(self, file):
491
+ sstruct.unpack(self.format, file.read(self.formatSize), self)
492
+
493
+ def fromString(self, str):
494
+ sstruct.unpack(self.format, str, self)
495
+
496
+ def toString(self):
497
+ return sstruct.pack(self.format, self)
498
+
499
+ def __repr__(self):
500
+ if hasattr(self, "tag"):
501
+ return "<%s '%s' at %x>" % (self.__class__.__name__, self.tag, id(self))
502
+ else:
503
+ return "<%s at %x>" % (self.__class__.__name__, id(self))
504
+
505
+ def loadData(self, file):
506
+ file.seek(self.offset)
507
+ data = file.read(self.length)
508
+ assert len(data) == self.length
509
+ if hasattr(self.__class__, "decodeData"):
510
+ data = self.decodeData(data)
511
+ return data
512
+
513
+ def saveData(self, file, data):
514
+ if hasattr(self.__class__, "encodeData"):
515
+ data = self.encodeData(data)
516
+ self.length = len(data)
517
+ file.seek(self.offset)
518
+ file.write(data)
519
+
520
+ def decodeData(self, rawData):
521
+ return rawData
522
+
523
+ def encodeData(self, data):
524
+ return data
525
+
526
+
527
+ class SFNTDirectoryEntry(DirectoryEntry):
528
+ format = sfntDirectoryEntryFormat
529
+ formatSize = sfntDirectoryEntrySize
530
+
531
+
532
+ class WOFFDirectoryEntry(DirectoryEntry):
533
+ format = woffDirectoryEntryFormat
534
+ formatSize = woffDirectoryEntrySize
535
+
536
+ def __init__(self):
537
+ super(WOFFDirectoryEntry, self).__init__()
538
+ # With fonttools<=3.1.2, the only way to set a different zlib
539
+ # compression level for WOFF directory entries was to set the class
540
+ # attribute 'zlibCompressionLevel'. This is now replaced by a globally
541
+ # defined `ZLIB_COMPRESSION_LEVEL`, which is also applied when
542
+ # compressing the metadata. For backward compatibility, we still
543
+ # use the class attribute if it was already set.
544
+ if not hasattr(WOFFDirectoryEntry, "zlibCompressionLevel"):
545
+ self.zlibCompressionLevel = ZLIB_COMPRESSION_LEVEL
546
+
547
+ def decodeData(self, rawData):
548
+ import zlib
549
+
550
+ if self.length == self.origLength:
551
+ data = rawData
552
+ else:
553
+ assert self.length < self.origLength
554
+ data = zlib.decompress(rawData)
555
+ assert len(data) == self.origLength
556
+ return data
557
+
558
+ def encodeData(self, data):
559
+ self.origLength = len(data)
560
+ if not self.uncompressed:
561
+ compressedData = compress(data, self.zlibCompressionLevel)
562
+ if self.uncompressed or len(compressedData) >= self.origLength:
563
+ # Encode uncompressed
564
+ rawData = data
565
+ self.length = self.origLength
566
+ else:
567
+ rawData = compressedData
568
+ self.length = len(rawData)
569
+ return rawData
570
+
571
+
572
+ class WOFFFlavorData:
573
+ Flavor = "woff"
574
+
575
+ def __init__(self, reader=None):
576
+ self.majorVersion = None
577
+ self.minorVersion = None
578
+ self.metaData = None
579
+ self.privData = None
580
+ if reader:
581
+ self.majorVersion = reader.majorVersion
582
+ self.minorVersion = reader.minorVersion
583
+ if reader.metaLength:
584
+ reader.file.seek(reader.metaOffset)
585
+ rawData = reader.file.read(reader.metaLength)
586
+ assert len(rawData) == reader.metaLength
587
+ data = self._decompress(rawData)
588
+ assert len(data) == reader.metaOrigLength
589
+ self.metaData = data
590
+ if reader.privLength:
591
+ reader.file.seek(reader.privOffset)
592
+ data = reader.file.read(reader.privLength)
593
+ assert len(data) == reader.privLength
594
+ self.privData = data
595
+
596
+ def _decompress(self, rawData):
597
+ import zlib
598
+
599
+ return zlib.decompress(rawData)
600
+
601
+
602
+ def calcChecksum(data):
603
+ """Calculate the checksum for an arbitrary block of data.
604
+
605
+ If the data length is not a multiple of four, it assumes
606
+ it is to be padded with null byte.
607
+
608
+ >>> print(calcChecksum(b"abcd"))
609
+ 1633837924
610
+ >>> print(calcChecksum(b"abcdxyz"))
611
+ 3655064932
612
+ """
613
+ remainder = len(data) % 4
614
+ if remainder:
615
+ data += b"\0" * (4 - remainder)
616
+ value = 0
617
+ blockSize = 4096
618
+ assert blockSize % 4 == 0
619
+ for i in range(0, len(data), blockSize):
620
+ block = data[i : i + blockSize]
621
+ longs = struct.unpack(">%dL" % (len(block) // 4), block)
622
+ value = (value + sum(longs)) & 0xFFFFFFFF
623
+ return value
624
+
625
+
626
+ def readTTCHeader(file):
627
+ file.seek(0)
628
+ data = file.read(ttcHeaderSize)
629
+ if len(data) != ttcHeaderSize:
630
+ raise TTLibError("Not a Font Collection (not enough data)")
631
+ self = SimpleNamespace()
632
+ sstruct.unpack(ttcHeaderFormat, data, self)
633
+ if self.TTCTag != "ttcf":
634
+ raise TTLibError("Not a Font Collection")
635
+ assert self.Version == 0x00010000 or self.Version == 0x00020000, (
636
+ "unrecognized TTC version 0x%08x" % self.Version
637
+ )
638
+ self.offsetTable = struct.unpack(
639
+ ">%dL" % self.numFonts, file.read(self.numFonts * 4)
640
+ )
641
+ if self.Version == 0x00020000:
642
+ pass # ignoring version 2.0 signatures
643
+ return self
644
+
645
+
646
+ def writeTTCHeader(file, numFonts):
647
+ self = SimpleNamespace()
648
+ self.TTCTag = "ttcf"
649
+ self.Version = 0x00010000
650
+ self.numFonts = numFonts
651
+ file.seek(0)
652
+ file.write(sstruct.pack(ttcHeaderFormat, self))
653
+ offset = file.tell()
654
+ file.write(struct.pack(">%dL" % self.numFonts, *([0] * self.numFonts)))
655
+ return offset
656
+
657
+
658
+ if __name__ == "__main__":
659
+ import sys
660
+ import doctest
661
+
662
+ sys.exit(doctest.testmod().failed)
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/standardGlyphOrder.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # 'post' table formats 1.0 and 2.0 rely on this list of "standard"
3
+ # glyphs.
4
+ #
5
+ # My list is correct according to the Apple documentation for the 'post' table:
6
+ # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html
7
+ # (However, it seems that TTFdump (from MS) and FontLab disagree, at
8
+ # least with respect to the last glyph, which they list as 'dslash'
9
+ # instead of 'dcroat'.)
10
+ #
11
+
12
+ standardGlyphOrder = [
13
+ ".notdef", # 0
14
+ ".null", # 1
15
+ "nonmarkingreturn", # 2
16
+ "space", # 3
17
+ "exclam", # 4
18
+ "quotedbl", # 5
19
+ "numbersign", # 6
20
+ "dollar", # 7
21
+ "percent", # 8
22
+ "ampersand", # 9
23
+ "quotesingle", # 10
24
+ "parenleft", # 11
25
+ "parenright", # 12
26
+ "asterisk", # 13
27
+ "plus", # 14
28
+ "comma", # 15
29
+ "hyphen", # 16
30
+ "period", # 17
31
+ "slash", # 18
32
+ "zero", # 19
33
+ "one", # 20
34
+ "two", # 21
35
+ "three", # 22
36
+ "four", # 23
37
+ "five", # 24
38
+ "six", # 25
39
+ "seven", # 26
40
+ "eight", # 27
41
+ "nine", # 28
42
+ "colon", # 29
43
+ "semicolon", # 30
44
+ "less", # 31
45
+ "equal", # 32
46
+ "greater", # 33
47
+ "question", # 34
48
+ "at", # 35
49
+ "A", # 36
50
+ "B", # 37
51
+ "C", # 38
52
+ "D", # 39
53
+ "E", # 40
54
+ "F", # 41
55
+ "G", # 42
56
+ "H", # 43
57
+ "I", # 44
58
+ "J", # 45
59
+ "K", # 46
60
+ "L", # 47
61
+ "M", # 48
62
+ "N", # 49
63
+ "O", # 50
64
+ "P", # 51
65
+ "Q", # 52
66
+ "R", # 53
67
+ "S", # 54
68
+ "T", # 55
69
+ "U", # 56
70
+ "V", # 57
71
+ "W", # 58
72
+ "X", # 59
73
+ "Y", # 60
74
+ "Z", # 61
75
+ "bracketleft", # 62
76
+ "backslash", # 63
77
+ "bracketright", # 64
78
+ "asciicircum", # 65
79
+ "underscore", # 66
80
+ "grave", # 67
81
+ "a", # 68
82
+ "b", # 69
83
+ "c", # 70
84
+ "d", # 71
85
+ "e", # 72
86
+ "f", # 73
87
+ "g", # 74
88
+ "h", # 75
89
+ "i", # 76
90
+ "j", # 77
91
+ "k", # 78
92
+ "l", # 79
93
+ "m", # 80
94
+ "n", # 81
95
+ "o", # 82
96
+ "p", # 83
97
+ "q", # 84
98
+ "r", # 85
99
+ "s", # 86
100
+ "t", # 87
101
+ "u", # 88
102
+ "v", # 89
103
+ "w", # 90
104
+ "x", # 91
105
+ "y", # 92
106
+ "z", # 93
107
+ "braceleft", # 94
108
+ "bar", # 95
109
+ "braceright", # 96
110
+ "asciitilde", # 97
111
+ "Adieresis", # 98
112
+ "Aring", # 99
113
+ "Ccedilla", # 100
114
+ "Eacute", # 101
115
+ "Ntilde", # 102
116
+ "Odieresis", # 103
117
+ "Udieresis", # 104
118
+ "aacute", # 105
119
+ "agrave", # 106
120
+ "acircumflex", # 107
121
+ "adieresis", # 108
122
+ "atilde", # 109
123
+ "aring", # 110
124
+ "ccedilla", # 111
125
+ "eacute", # 112
126
+ "egrave", # 113
127
+ "ecircumflex", # 114
128
+ "edieresis", # 115
129
+ "iacute", # 116
130
+ "igrave", # 117
131
+ "icircumflex", # 118
132
+ "idieresis", # 119
133
+ "ntilde", # 120
134
+ "oacute", # 121
135
+ "ograve", # 122
136
+ "ocircumflex", # 123
137
+ "odieresis", # 124
138
+ "otilde", # 125
139
+ "uacute", # 126
140
+ "ugrave", # 127
141
+ "ucircumflex", # 128
142
+ "udieresis", # 129
143
+ "dagger", # 130
144
+ "degree", # 131
145
+ "cent", # 132
146
+ "sterling", # 133
147
+ "section", # 134
148
+ "bullet", # 135
149
+ "paragraph", # 136
150
+ "germandbls", # 137
151
+ "registered", # 138
152
+ "copyright", # 139
153
+ "trademark", # 140
154
+ "acute", # 141
155
+ "dieresis", # 142
156
+ "notequal", # 143
157
+ "AE", # 144
158
+ "Oslash", # 145
159
+ "infinity", # 146
160
+ "plusminus", # 147
161
+ "lessequal", # 148
162
+ "greaterequal", # 149
163
+ "yen", # 150
164
+ "mu", # 151
165
+ "partialdiff", # 152
166
+ "summation", # 153
167
+ "product", # 154
168
+ "pi", # 155
169
+ "integral", # 156
170
+ "ordfeminine", # 157
171
+ "ordmasculine", # 158
172
+ "Omega", # 159
173
+ "ae", # 160
174
+ "oslash", # 161
175
+ "questiondown", # 162
176
+ "exclamdown", # 163
177
+ "logicalnot", # 164
178
+ "radical", # 165
179
+ "florin", # 166
180
+ "approxequal", # 167
181
+ "Delta", # 168
182
+ "guillemotleft", # 169
183
+ "guillemotright", # 170
184
+ "ellipsis", # 171
185
+ "nonbreakingspace", # 172
186
+ "Agrave", # 173
187
+ "Atilde", # 174
188
+ "Otilde", # 175
189
+ "OE", # 176
190
+ "oe", # 177
191
+ "endash", # 178
192
+ "emdash", # 179
193
+ "quotedblleft", # 180
194
+ "quotedblright", # 181
195
+ "quoteleft", # 182
196
+ "quoteright", # 183
197
+ "divide", # 184
198
+ "lozenge", # 185
199
+ "ydieresis", # 186
200
+ "Ydieresis", # 187
201
+ "fraction", # 188
202
+ "currency", # 189
203
+ "guilsinglleft", # 190
204
+ "guilsinglright", # 191
205
+ "fi", # 192
206
+ "fl", # 193
207
+ "daggerdbl", # 194
208
+ "periodcentered", # 195
209
+ "quotesinglbase", # 196
210
+ "quotedblbase", # 197
211
+ "perthousand", # 198
212
+ "Acircumflex", # 199
213
+ "Ecircumflex", # 200
214
+ "Aacute", # 201
215
+ "Edieresis", # 202
216
+ "Egrave", # 203
217
+ "Iacute", # 204
218
+ "Icircumflex", # 205
219
+ "Idieresis", # 206
220
+ "Igrave", # 207
221
+ "Oacute", # 208
222
+ "Ocircumflex", # 209
223
+ "apple", # 210
224
+ "Ograve", # 211
225
+ "Uacute", # 212
226
+ "Ucircumflex", # 213
227
+ "Ugrave", # 214
228
+ "dotlessi", # 215
229
+ "circumflex", # 216
230
+ "tilde", # 217
231
+ "macron", # 218
232
+ "breve", # 219
233
+ "dotaccent", # 220
234
+ "ring", # 221
235
+ "cedilla", # 222
236
+ "hungarumlaut", # 223
237
+ "ogonek", # 224
238
+ "caron", # 225
239
+ "Lslash", # 226
240
+ "lslash", # 227
241
+ "Scaron", # 228
242
+ "scaron", # 229
243
+ "Zcaron", # 230
244
+ "zcaron", # 231
245
+ "brokenbar", # 232
246
+ "Eth", # 233
247
+ "eth", # 234
248
+ "Yacute", # 235
249
+ "yacute", # 236
250
+ "Thorn", # 237
251
+ "thorn", # 238
252
+ "minus", # 239
253
+ "multiply", # 240
254
+ "onesuperior", # 241
255
+ "twosuperior", # 242
256
+ "threesuperior", # 243
257
+ "onehalf", # 244
258
+ "onequarter", # 245
259
+ "threequarters", # 246
260
+ "franc", # 247
261
+ "Gbreve", # 248
262
+ "gbreve", # 249
263
+ "Idotaccent", # 250
264
+ "Scedilla", # 251
265
+ "scedilla", # 252
266
+ "Cacute", # 253
267
+ "cacute", # 254
268
+ "Ccaron", # 255
269
+ "ccaron", # 256
270
+ "dcroat", # 257
271
+ ]
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/BitmapGlyphMetrics.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Since bitmap glyph metrics are shared between EBLC and EBDT
2
+ # this class gets its own python file.
3
+ from fontTools.misc import sstruct
4
+ from fontTools.misc.textTools import safeEval
5
+ import logging
6
+
7
+
8
+ log = logging.getLogger(__name__)
9
+
10
+ bigGlyphMetricsFormat = """
11
+ > # big endian
12
+ height: B
13
+ width: B
14
+ horiBearingX: b
15
+ horiBearingY: b
16
+ horiAdvance: B
17
+ vertBearingX: b
18
+ vertBearingY: b
19
+ vertAdvance: B
20
+ """
21
+
22
+ smallGlyphMetricsFormat = """
23
+ > # big endian
24
+ height: B
25
+ width: B
26
+ BearingX: b
27
+ BearingY: b
28
+ Advance: B
29
+ """
30
+
31
+
32
+ class BitmapGlyphMetrics(object):
33
+ def toXML(self, writer, ttFont):
34
+ writer.begintag(self.__class__.__name__)
35
+ writer.newline()
36
+ for metricName in sstruct.getformat(self.__class__.binaryFormat)[1]:
37
+ writer.simpletag(metricName, value=getattr(self, metricName))
38
+ writer.newline()
39
+ writer.endtag(self.__class__.__name__)
40
+ writer.newline()
41
+
42
+ def fromXML(self, name, attrs, content, ttFont):
43
+ metricNames = set(sstruct.getformat(self.__class__.binaryFormat)[1])
44
+ for element in content:
45
+ if not isinstance(element, tuple):
46
+ continue
47
+ name, attrs, content = element
48
+ # Make sure this is a metric that is needed by GlyphMetrics.
49
+ if name in metricNames:
50
+ vars(self)[name] = safeEval(attrs["value"])
51
+ else:
52
+ log.warning(
53
+ "unknown name '%s' being ignored in %s.",
54
+ name,
55
+ self.__class__.__name__,
56
+ )
57
+
58
+
59
+ class BigGlyphMetrics(BitmapGlyphMetrics):
60
+ binaryFormat = bigGlyphMetricsFormat
61
+
62
+
63
+ class SmallGlyphMetrics(BitmapGlyphMetrics):
64
+ binaryFormat = smallGlyphMetricsFormat
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/C_B_L_C_.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2013 Google, Inc. All Rights Reserved.
2
+ #
3
+ # Google Author(s): Matt Fontaine
4
+
5
+ from . import E_B_L_C_
6
+
7
+
8
+ class table_C_B_L_C_(E_B_L_C_.table_E_B_L_C_):
9
+ dependencies = ["CBDT"]
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/C_F_F_.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ from fontTools import cffLib
3
+ from . import DefaultTable
4
+
5
+
6
+ class table_C_F_F_(DefaultTable.DefaultTable):
7
+ def __init__(self, tag=None):
8
+ DefaultTable.DefaultTable.__init__(self, tag)
9
+ self.cff = cffLib.CFFFontSet()
10
+ self._gaveGlyphOrder = False
11
+
12
+ def decompile(self, data, otFont):
13
+ self.cff.decompile(BytesIO(data), otFont, isCFF2=False)
14
+ assert len(self.cff) == 1, "can't deal with multi-font CFF tables."
15
+
16
+ def compile(self, otFont):
17
+ f = BytesIO()
18
+ self.cff.compile(f, otFont, isCFF2=False)
19
+ return f.getvalue()
20
+
21
+ def haveGlyphNames(self):
22
+ if hasattr(self.cff[self.cff.fontNames[0]], "ROS"):
23
+ return False # CID-keyed font
24
+ else:
25
+ return True
26
+
27
+ def getGlyphOrder(self):
28
+ if self._gaveGlyphOrder:
29
+ from fontTools import ttLib
30
+
31
+ raise ttLib.TTLibError("illegal use of getGlyphOrder()")
32
+ self._gaveGlyphOrder = True
33
+ return self.cff[self.cff.fontNames[0]].getGlyphOrder()
34
+
35
+ def setGlyphOrder(self, glyphOrder):
36
+ pass
37
+ # XXX
38
+ # self.cff[self.cff.fontNames[0]].setGlyphOrder(glyphOrder)
39
+
40
+ def toXML(self, writer, otFont):
41
+ self.cff.toXML(writer)
42
+
43
+ def fromXML(self, name, attrs, content, otFont):
44
+ if not hasattr(self, "cff"):
45
+ self.cff = cffLib.CFFFontSet()
46
+ self.cff.fromXML(name, attrs, content, otFont)
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/D_S_I_G_.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc.textTools import bytesjoin, strjoin, tobytes, tostr, safeEval
2
+ from fontTools.misc import sstruct
3
+ from . import DefaultTable
4
+ import base64
5
+
6
+ DSIG_HeaderFormat = """
7
+ > # big endian
8
+ ulVersion: L
9
+ usNumSigs: H
10
+ usFlag: H
11
+ """
12
+ # followed by an array of usNumSigs DSIG_Signature records
13
+ DSIG_SignatureFormat = """
14
+ > # big endian
15
+ ulFormat: L
16
+ ulLength: L # length includes DSIG_SignatureBlock header
17
+ ulOffset: L
18
+ """
19
+ # followed by an array of usNumSigs DSIG_SignatureBlock records,
20
+ # each followed immediately by the pkcs7 bytes
21
+ DSIG_SignatureBlockFormat = """
22
+ > # big endian
23
+ usReserved1: H
24
+ usReserved2: H
25
+ cbSignature: l # length of following raw pkcs7 data
26
+ """
27
+
28
+ #
29
+ # NOTE
30
+ # the DSIG table format allows for SignatureBlocks residing
31
+ # anywhere in the table and possibly in a different order as
32
+ # listed in the array after the first table header
33
+ #
34
+ # this implementation does not keep track of any gaps and/or data
35
+ # before or after the actual signature blocks while decompiling,
36
+ # and puts them in the same physical order as listed in the header
37
+ # on compilation with no padding whatsoever.
38
+ #
39
+
40
+
41
+ class table_D_S_I_G_(DefaultTable.DefaultTable):
42
+ def decompile(self, data, ttFont):
43
+ dummy, newData = sstruct.unpack2(DSIG_HeaderFormat, data, self)
44
+ assert self.ulVersion == 1, "DSIG ulVersion must be 1"
45
+ assert self.usFlag & ~1 == 0, "DSIG usFlag must be 0x1 or 0x0"
46
+ self.signatureRecords = sigrecs = []
47
+ for n in range(self.usNumSigs):
48
+ sigrec, newData = sstruct.unpack2(
49
+ DSIG_SignatureFormat, newData, SignatureRecord()
50
+ )
51
+ assert sigrec.ulFormat == 1, (
52
+ "DSIG signature record #%d ulFormat must be 1" % n
53
+ )
54
+ sigrecs.append(sigrec)
55
+ for sigrec in sigrecs:
56
+ dummy, newData = sstruct.unpack2(
57
+ DSIG_SignatureBlockFormat, data[sigrec.ulOffset :], sigrec
58
+ )
59
+ assert sigrec.usReserved1 == 0, (
60
+ "DSIG signature record #%d usReserverd1 must be 0" % n
61
+ )
62
+ assert sigrec.usReserved2 == 0, (
63
+ "DSIG signature record #%d usReserverd2 must be 0" % n
64
+ )
65
+ sigrec.pkcs7 = newData[: sigrec.cbSignature]
66
+
67
+ def compile(self, ttFont):
68
+ packed = sstruct.pack(DSIG_HeaderFormat, self)
69
+ headers = [packed]
70
+ offset = len(packed) + self.usNumSigs * sstruct.calcsize(DSIG_SignatureFormat)
71
+ data = []
72
+ for sigrec in self.signatureRecords:
73
+ # first pack signature block
74
+ sigrec.cbSignature = len(sigrec.pkcs7)
75
+ packed = sstruct.pack(DSIG_SignatureBlockFormat, sigrec) + sigrec.pkcs7
76
+ data.append(packed)
77
+ # update redundant length field
78
+ sigrec.ulLength = len(packed)
79
+ # update running table offset
80
+ sigrec.ulOffset = offset
81
+ headers.append(sstruct.pack(DSIG_SignatureFormat, sigrec))
82
+ offset += sigrec.ulLength
83
+ if offset % 2:
84
+ # Pad to even bytes
85
+ data.append(b"\0")
86
+ return bytesjoin(headers + data)
87
+
88
+ def toXML(self, xmlWriter, ttFont):
89
+ xmlWriter.comment(
90
+ "note that the Digital Signature will be invalid after recompilation!"
91
+ )
92
+ xmlWriter.newline()
93
+ xmlWriter.simpletag(
94
+ "tableHeader",
95
+ version=self.ulVersion,
96
+ numSigs=self.usNumSigs,
97
+ flag="0x%X" % self.usFlag,
98
+ )
99
+ for sigrec in self.signatureRecords:
100
+ xmlWriter.newline()
101
+ sigrec.toXML(xmlWriter, ttFont)
102
+ xmlWriter.newline()
103
+
104
+ def fromXML(self, name, attrs, content, ttFont):
105
+ if name == "tableHeader":
106
+ self.signatureRecords = []
107
+ self.ulVersion = safeEval(attrs["version"])
108
+ self.usNumSigs = safeEval(attrs["numSigs"])
109
+ self.usFlag = safeEval(attrs["flag"])
110
+ return
111
+ if name == "SignatureRecord":
112
+ sigrec = SignatureRecord()
113
+ sigrec.fromXML(name, attrs, content, ttFont)
114
+ self.signatureRecords.append(sigrec)
115
+
116
+
117
+ pem_spam = lambda l, spam={
118
+ "-----BEGIN PKCS7-----": True,
119
+ "-----END PKCS7-----": True,
120
+ "": True,
121
+ }: not spam.get(l.strip())
122
+
123
+
124
+ def b64encode(b):
125
+ s = base64.b64encode(b)
126
+ # Line-break at 76 chars.
127
+ items = []
128
+ while s:
129
+ items.append(tostr(s[:76]))
130
+ items.append("\n")
131
+ s = s[76:]
132
+ return strjoin(items)
133
+
134
+
135
+ class SignatureRecord(object):
136
+ def __repr__(self):
137
+ return "<%s: %s>" % (self.__class__.__name__, self.__dict__)
138
+
139
+ def toXML(self, writer, ttFont):
140
+ writer.begintag(self.__class__.__name__, format=self.ulFormat)
141
+ writer.newline()
142
+ writer.write_noindent("-----BEGIN PKCS7-----\n")
143
+ writer.write_noindent(b64encode(self.pkcs7))
144
+ writer.write_noindent("-----END PKCS7-----\n")
145
+ writer.endtag(self.__class__.__name__)
146
+
147
+ def fromXML(self, name, attrs, content, ttFont):
148
+ self.ulFormat = safeEval(attrs["format"])
149
+ self.usReserved1 = safeEval(attrs.get("reserved1", "0"))
150
+ self.usReserved2 = safeEval(attrs.get("reserved2", "0"))
151
+ self.pkcs7 = base64.b64decode(tobytes(strjoin(filter(pem_spam, content))))
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/F__e_a_t.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc import sstruct
2
+ from fontTools.misc.fixedTools import floatToFixedToStr
3
+ from fontTools.misc.textTools import safeEval
4
+ from . import DefaultTable
5
+ from . import grUtils
6
+ import struct
7
+
8
+ Feat_hdr_format = """
9
+ >
10
+ version: 16.16F
11
+ """
12
+
13
+
14
+ class table_F__e_a_t(DefaultTable.DefaultTable):
15
+ """The ``Feat`` table is used exclusively by the Graphite shaping engine
16
+ to store features and possible settings specified in GDL. Graphite features
17
+ determine what rules are applied to transform a glyph stream.
18
+
19
+ Not to be confused with ``feat``, or the OpenType Layout tables
20
+ ``GSUB``/``GPOS``."""
21
+
22
+ def __init__(self, tag=None):
23
+ DefaultTable.DefaultTable.__init__(self, tag)
24
+ self.features = {}
25
+
26
+ def decompile(self, data, ttFont):
27
+ (_, data) = sstruct.unpack2(Feat_hdr_format, data, self)
28
+ self.version = float(floatToFixedToStr(self.version, precisionBits=16))
29
+ (numFeats,) = struct.unpack(">H", data[:2])
30
+ data = data[8:]
31
+ allfeats = []
32
+ maxsetting = 0
33
+ for i in range(numFeats):
34
+ if self.version >= 2.0:
35
+ (fid, nums, _, offset, flags, lid) = struct.unpack(
36
+ ">LHHLHH", data[16 * i : 16 * (i + 1)]
37
+ )
38
+ offset = int((offset - 12 - 16 * numFeats) / 4)
39
+ else:
40
+ (fid, nums, offset, flags, lid) = struct.unpack(
41
+ ">HHLHH", data[12 * i : 12 * (i + 1)]
42
+ )
43
+ offset = int((offset - 12 - 12 * numFeats) / 4)
44
+ allfeats.append((fid, nums, offset, flags, lid))
45
+ maxsetting = max(maxsetting, offset + nums)
46
+ data = data[16 * numFeats :]
47
+ allsettings = []
48
+ for i in range(maxsetting):
49
+ if len(data) >= 4 * (i + 1):
50
+ (val, lid) = struct.unpack(">HH", data[4 * i : 4 * (i + 1)])
51
+ allsettings.append((val, lid))
52
+ for i, f in enumerate(allfeats):
53
+ (fid, nums, offset, flags, lid) = f
54
+ fobj = Feature()
55
+ fobj.flags = flags
56
+ fobj.label = lid
57
+ self.features[grUtils.num2tag(fid)] = fobj
58
+ fobj.settings = {}
59
+ fobj.default = None
60
+ fobj.index = i
61
+ for i in range(offset, offset + nums):
62
+ if i >= len(allsettings):
63
+ continue
64
+ (vid, vlid) = allsettings[i]
65
+ fobj.settings[vid] = vlid
66
+ if fobj.default is None:
67
+ fobj.default = vid
68
+
69
+ def compile(self, ttFont):
70
+ fdat = b""
71
+ vdat = b""
72
+ offset = 0
73
+ for f, v in sorted(self.features.items(), key=lambda x: x[1].index):
74
+ fnum = grUtils.tag2num(f)
75
+ if self.version >= 2.0:
76
+ fdat += struct.pack(
77
+ ">LHHLHH",
78
+ grUtils.tag2num(f),
79
+ len(v.settings),
80
+ 0,
81
+ offset * 4 + 12 + 16 * len(self.features),
82
+ v.flags,
83
+ v.label,
84
+ )
85
+ elif fnum > 65535: # self healing for alphabetic ids
86
+ self.version = 2.0
87
+ return self.compile(ttFont)
88
+ else:
89
+ fdat += struct.pack(
90
+ ">HHLHH",
91
+ grUtils.tag2num(f),
92
+ len(v.settings),
93
+ offset * 4 + 12 + 12 * len(self.features),
94
+ v.flags,
95
+ v.label,
96
+ )
97
+ for s, l in sorted(
98
+ v.settings.items(), key=lambda x: (-1, x[1]) if x[0] == v.default else x
99
+ ):
100
+ vdat += struct.pack(">HH", s, l)
101
+ offset += len(v.settings)
102
+ hdr = sstruct.pack(Feat_hdr_format, self)
103
+ return hdr + struct.pack(">HHL", len(self.features), 0, 0) + fdat + vdat
104
+
105
+ def toXML(self, writer, ttFont):
106
+ writer.simpletag("version", version=self.version)
107
+ writer.newline()
108
+ for f, v in sorted(self.features.items(), key=lambda x: x[1].index):
109
+ writer.begintag(
110
+ "feature",
111
+ fid=f,
112
+ label=v.label,
113
+ flags=v.flags,
114
+ default=(v.default if v.default else 0),
115
+ )
116
+ writer.newline()
117
+ for s, l in sorted(v.settings.items()):
118
+ writer.simpletag("setting", value=s, label=l)
119
+ writer.newline()
120
+ writer.endtag("feature")
121
+ writer.newline()
122
+
123
+ def fromXML(self, name, attrs, content, ttFont):
124
+ if name == "version":
125
+ self.version = float(safeEval(attrs["version"]))
126
+ elif name == "feature":
127
+ fid = attrs["fid"]
128
+ fobj = Feature()
129
+ fobj.flags = int(safeEval(attrs["flags"]))
130
+ fobj.label = int(safeEval(attrs["label"]))
131
+ fobj.default = int(safeEval(attrs.get("default", "0")))
132
+ fobj.index = len(self.features)
133
+ self.features[fid] = fobj
134
+ fobj.settings = {}
135
+ for element in content:
136
+ if not isinstance(element, tuple):
137
+ continue
138
+ tag, a, c = element
139
+ if tag == "setting":
140
+ fobj.settings[int(safeEval(a["value"]))] = int(safeEval(a["label"]))
141
+
142
+
143
+ class Feature(object):
144
+ pass
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/G_M_A_P_.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc import sstruct
2
+ from fontTools.misc.textTools import tobytes, tostr, safeEval
3
+ from . import DefaultTable
4
+
5
+ GMAPFormat = """
6
+ > # big endian
7
+ tableVersionMajor: H
8
+ tableVersionMinor: H
9
+ flags: H
10
+ recordsCount: H
11
+ recordsOffset: H
12
+ fontNameLength: H
13
+ """
14
+ # psFontName is a byte string which follows the record above. This is zero padded
15
+ # to the beginning of the records array. The recordsOffsst is 32 bit aligned.
16
+
17
+ GMAPRecordFormat1 = """
18
+ > # big endian
19
+ UV: L
20
+ cid: H
21
+ gid: H
22
+ ggid: H
23
+ name: 32s
24
+ """
25
+
26
+
27
+ class GMAPRecord(object):
28
+ def __init__(self, uv=0, cid=0, gid=0, ggid=0, name=""):
29
+ self.UV = uv
30
+ self.cid = cid
31
+ self.gid = gid
32
+ self.ggid = ggid
33
+ self.name = name
34
+
35
+ def toXML(self, writer, ttFont):
36
+ writer.begintag("GMAPRecord")
37
+ writer.newline()
38
+ writer.simpletag("UV", value=self.UV)
39
+ writer.newline()
40
+ writer.simpletag("cid", value=self.cid)
41
+ writer.newline()
42
+ writer.simpletag("gid", value=self.gid)
43
+ writer.newline()
44
+ writer.simpletag("glyphletGid", value=self.gid)
45
+ writer.newline()
46
+ writer.simpletag("GlyphletName", value=self.name)
47
+ writer.newline()
48
+ writer.endtag("GMAPRecord")
49
+ writer.newline()
50
+
51
+ def fromXML(self, name, attrs, content, ttFont):
52
+ value = attrs["value"]
53
+ if name == "GlyphletName":
54
+ self.name = value
55
+ else:
56
+ setattr(self, name, safeEval(value))
57
+
58
+ def compile(self, ttFont):
59
+ if self.UV is None:
60
+ self.UV = 0
61
+ nameLen = len(self.name)
62
+ if nameLen < 32:
63
+ self.name = self.name + "\0" * (32 - nameLen)
64
+ data = sstruct.pack(GMAPRecordFormat1, self)
65
+ return data
66
+
67
+ def __repr__(self):
68
+ return (
69
+ "GMAPRecord[ UV: "
70
+ + str(self.UV)
71
+ + ", cid: "
72
+ + str(self.cid)
73
+ + ", gid: "
74
+ + str(self.gid)
75
+ + ", ggid: "
76
+ + str(self.ggid)
77
+ + ", Glyphlet Name: "
78
+ + str(self.name)
79
+ + " ]"
80
+ )
81
+
82
+
83
+ class table_G_M_A_P_(DefaultTable.DefaultTable):
84
+ dependencies = []
85
+
86
+ def decompile(self, data, ttFont):
87
+ dummy, newData = sstruct.unpack2(GMAPFormat, data, self)
88
+ self.psFontName = tostr(newData[: self.fontNameLength])
89
+ assert (
90
+ self.recordsOffset % 4
91
+ ) == 0, "GMAP error: recordsOffset is not 32 bit aligned."
92
+ newData = data[self.recordsOffset :]
93
+ self.gmapRecords = []
94
+ for i in range(self.recordsCount):
95
+ gmapRecord, newData = sstruct.unpack2(
96
+ GMAPRecordFormat1, newData, GMAPRecord()
97
+ )
98
+ gmapRecord.name = gmapRecord.name.strip("\0")
99
+ self.gmapRecords.append(gmapRecord)
100
+
101
+ def compile(self, ttFont):
102
+ self.recordsCount = len(self.gmapRecords)
103
+ self.fontNameLength = len(self.psFontName)
104
+ self.recordsOffset = 4 * (((self.fontNameLength + 12) + 3) // 4)
105
+ data = sstruct.pack(GMAPFormat, self)
106
+ data = data + tobytes(self.psFontName)
107
+ data = data + b"\0" * (self.recordsOffset - len(data))
108
+ for record in self.gmapRecords:
109
+ data = data + record.compile(ttFont)
110
+ return data
111
+
112
+ def toXML(self, writer, ttFont):
113
+ writer.comment("Most of this table will be recalculated by the compiler")
114
+ writer.newline()
115
+ formatstring, names, fixes = sstruct.getformat(GMAPFormat)
116
+ for name in names:
117
+ value = getattr(self, name)
118
+ writer.simpletag(name, value=value)
119
+ writer.newline()
120
+ writer.simpletag("PSFontName", value=self.psFontName)
121
+ writer.newline()
122
+ for gmapRecord in self.gmapRecords:
123
+ gmapRecord.toXML(writer, ttFont)
124
+
125
+ def fromXML(self, name, attrs, content, ttFont):
126
+ if name == "GMAPRecord":
127
+ if not hasattr(self, "gmapRecords"):
128
+ self.gmapRecords = []
129
+ gmapRecord = GMAPRecord()
130
+ self.gmapRecords.append(gmapRecord)
131
+ for element in content:
132
+ if isinstance(element, str):
133
+ continue
134
+ name, attrs, content = element
135
+ gmapRecord.fromXML(name, attrs, content, ttFont)
136
+ else:
137
+ value = attrs["value"]
138
+ if name == "PSFontName":
139
+ self.psFontName = value
140
+ else:
141
+ setattr(self, name, safeEval(value))
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/G_S_U_B_.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .otBase import BaseTTXConverter
2
+
3
+
4
+ class table_G_S_U_B_(BaseTTXConverter):
5
+ pass
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/H_V_A_R_.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .otBase import BaseTTXConverter
2
+
3
+
4
+ class table_H_V_A_R_(BaseTTXConverter):
5
+ pass
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/M_E_T_A_.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc import sstruct
2
+ from fontTools.misc.textTools import byteord, safeEval
3
+ from . import DefaultTable
4
+ import pdb
5
+ import struct
6
+
7
+
8
+ METAHeaderFormat = """
9
+ > # big endian
10
+ tableVersionMajor: H
11
+ tableVersionMinor: H
12
+ metaEntriesVersionMajor: H
13
+ metaEntriesVersionMinor: H
14
+ unicodeVersion: L
15
+ metaFlags: H
16
+ nMetaRecs: H
17
+ """
18
+ # This record is followed by nMetaRecs of METAGlyphRecordFormat.
19
+ # This in turn is followd by as many METAStringRecordFormat entries
20
+ # as specified by the METAGlyphRecordFormat entries
21
+ # this is followed by the strings specifried in the METAStringRecordFormat
22
+ METAGlyphRecordFormat = """
23
+ > # big endian
24
+ glyphID: H
25
+ nMetaEntry: H
26
+ """
27
+ # This record is followd by a variable data length field:
28
+ # USHORT or ULONG hdrOffset
29
+ # Offset from start of META table to the beginning
30
+ # of this glyphs array of ns Metadata string entries.
31
+ # Size determined by metaFlags field
32
+ # METAGlyphRecordFormat entries must be sorted by glyph ID
33
+
34
+ METAStringRecordFormat = """
35
+ > # big endian
36
+ labelID: H
37
+ stringLen: H
38
+ """
39
+ # This record is followd by a variable data length field:
40
+ # USHORT or ULONG stringOffset
41
+ # METAStringRecordFormat entries must be sorted in order of labelID
42
+ # There may be more than one entry with the same labelID
43
+ # There may be more than one strign with the same content.
44
+
45
+ # Strings shall be Unicode UTF-8 encoded, and null-terminated.
46
+
47
+ METALabelDict = {
48
+ 0: "MojikumiX4051", # An integer in the range 1-20
49
+ 1: "UNIUnifiedBaseChars",
50
+ 2: "BaseFontName",
51
+ 3: "Language",
52
+ 4: "CreationDate",
53
+ 5: "FoundryName",
54
+ 6: "FoundryCopyright",
55
+ 7: "OwnerURI",
56
+ 8: "WritingScript",
57
+ 10: "StrokeCount",
58
+ 11: "IndexingRadical",
59
+ }
60
+
61
+
62
+ def getLabelString(labelID):
63
+ try:
64
+ label = METALabelDict[labelID]
65
+ except KeyError:
66
+ label = "Unknown label"
67
+ return str(label)
68
+
69
+
70
+ class table_M_E_T_A_(DefaultTable.DefaultTable):
71
+ dependencies = []
72
+
73
+ def decompile(self, data, ttFont):
74
+ dummy, newData = sstruct.unpack2(METAHeaderFormat, data, self)
75
+ self.glyphRecords = []
76
+ for i in range(self.nMetaRecs):
77
+ glyphRecord, newData = sstruct.unpack2(
78
+ METAGlyphRecordFormat, newData, GlyphRecord()
79
+ )
80
+ if self.metaFlags == 0:
81
+ [glyphRecord.offset] = struct.unpack(">H", newData[:2])
82
+ newData = newData[2:]
83
+ elif self.metaFlags == 1:
84
+ [glyphRecord.offset] = struct.unpack(">H", newData[:4])
85
+ newData = newData[4:]
86
+ else:
87
+ assert 0, (
88
+ "The metaFlags field in the META table header has a value other than 0 or 1 :"
89
+ + str(self.metaFlags)
90
+ )
91
+ glyphRecord.stringRecs = []
92
+ newData = data[glyphRecord.offset :]
93
+ for j in range(glyphRecord.nMetaEntry):
94
+ stringRec, newData = sstruct.unpack2(
95
+ METAStringRecordFormat, newData, StringRecord()
96
+ )
97
+ if self.metaFlags == 0:
98
+ [stringRec.offset] = struct.unpack(">H", newData[:2])
99
+ newData = newData[2:]
100
+ else:
101
+ [stringRec.offset] = struct.unpack(">H", newData[:4])
102
+ newData = newData[4:]
103
+ stringRec.string = data[
104
+ stringRec.offset : stringRec.offset + stringRec.stringLen
105
+ ]
106
+ glyphRecord.stringRecs.append(stringRec)
107
+ self.glyphRecords.append(glyphRecord)
108
+
109
+ def compile(self, ttFont):
110
+ offsetOK = 0
111
+ self.nMetaRecs = len(self.glyphRecords)
112
+ count = 0
113
+ while offsetOK != 1:
114
+ count = count + 1
115
+ if count > 4:
116
+ pdb.set_trace()
117
+ metaData = sstruct.pack(METAHeaderFormat, self)
118
+ stringRecsOffset = len(metaData) + self.nMetaRecs * (
119
+ 6 + 2 * (self.metaFlags & 1)
120
+ )
121
+ stringRecSize = 6 + 2 * (self.metaFlags & 1)
122
+ for glyphRec in self.glyphRecords:
123
+ glyphRec.offset = stringRecsOffset
124
+ if (glyphRec.offset > 65535) and ((self.metaFlags & 1) == 0):
125
+ self.metaFlags = self.metaFlags + 1
126
+ offsetOK = -1
127
+ break
128
+ metaData = metaData + glyphRec.compile(self)
129
+ stringRecsOffset = stringRecsOffset + (
130
+ glyphRec.nMetaEntry * stringRecSize
131
+ )
132
+ # this will be the String Record offset for the next GlyphRecord.
133
+ if offsetOK == -1:
134
+ offsetOK = 0
135
+ continue
136
+
137
+ # metaData now contains the header and all of the GlyphRecords. Its length should bw
138
+ # the offset to the first StringRecord.
139
+ stringOffset = stringRecsOffset
140
+ for glyphRec in self.glyphRecords:
141
+ assert glyphRec.offset == len(
142
+ metaData
143
+ ), "Glyph record offset did not compile correctly! for rec:" + str(
144
+ glyphRec
145
+ )
146
+ for stringRec in glyphRec.stringRecs:
147
+ stringRec.offset = stringOffset
148
+ if (stringRec.offset > 65535) and ((self.metaFlags & 1) == 0):
149
+ self.metaFlags = self.metaFlags + 1
150
+ offsetOK = -1
151
+ break
152
+ metaData = metaData + stringRec.compile(self)
153
+ stringOffset = stringOffset + stringRec.stringLen
154
+ if offsetOK == -1:
155
+ offsetOK = 0
156
+ continue
157
+
158
+ if ((self.metaFlags & 1) == 1) and (stringOffset < 65536):
159
+ self.metaFlags = self.metaFlags - 1
160
+ continue
161
+ else:
162
+ offsetOK = 1
163
+
164
+ # metaData now contains the header and all of the GlyphRecords and all of the String Records.
165
+ # Its length should be the offset to the first string datum.
166
+ for glyphRec in self.glyphRecords:
167
+ for stringRec in glyphRec.stringRecs:
168
+ assert stringRec.offset == len(
169
+ metaData
170
+ ), "String offset did not compile correctly! for string:" + str(
171
+ stringRec.string
172
+ )
173
+ metaData = metaData + stringRec.string
174
+
175
+ return metaData
176
+
177
+ def toXML(self, writer, ttFont):
178
+ writer.comment(
179
+ "Lengths and number of entries in this table will be recalculated by the compiler"
180
+ )
181
+ writer.newline()
182
+ formatstring, names, fixes = sstruct.getformat(METAHeaderFormat)
183
+ for name in names:
184
+ value = getattr(self, name)
185
+ writer.simpletag(name, value=value)
186
+ writer.newline()
187
+ for glyphRec in self.glyphRecords:
188
+ glyphRec.toXML(writer, ttFont)
189
+
190
+ def fromXML(self, name, attrs, content, ttFont):
191
+ if name == "GlyphRecord":
192
+ if not hasattr(self, "glyphRecords"):
193
+ self.glyphRecords = []
194
+ glyphRec = GlyphRecord()
195
+ self.glyphRecords.append(glyphRec)
196
+ for element in content:
197
+ if isinstance(element, str):
198
+ continue
199
+ name, attrs, content = element
200
+ glyphRec.fromXML(name, attrs, content, ttFont)
201
+ glyphRec.offset = -1
202
+ glyphRec.nMetaEntry = len(glyphRec.stringRecs)
203
+ else:
204
+ setattr(self, name, safeEval(attrs["value"]))
205
+
206
+
207
+ class GlyphRecord(object):
208
+ def __init__(self):
209
+ self.glyphID = -1
210
+ self.nMetaEntry = -1
211
+ self.offset = -1
212
+ self.stringRecs = []
213
+
214
+ def toXML(self, writer, ttFont):
215
+ writer.begintag("GlyphRecord")
216
+ writer.newline()
217
+ writer.simpletag("glyphID", value=self.glyphID)
218
+ writer.newline()
219
+ writer.simpletag("nMetaEntry", value=self.nMetaEntry)
220
+ writer.newline()
221
+ for stringRec in self.stringRecs:
222
+ stringRec.toXML(writer, ttFont)
223
+ writer.endtag("GlyphRecord")
224
+ writer.newline()
225
+
226
+ def fromXML(self, name, attrs, content, ttFont):
227
+ if name == "StringRecord":
228
+ stringRec = StringRecord()
229
+ self.stringRecs.append(stringRec)
230
+ for element in content:
231
+ if isinstance(element, str):
232
+ continue
233
+ stringRec.fromXML(name, attrs, content, ttFont)
234
+ stringRec.stringLen = len(stringRec.string)
235
+ else:
236
+ setattr(self, name, safeEval(attrs["value"]))
237
+
238
+ def compile(self, parentTable):
239
+ data = sstruct.pack(METAGlyphRecordFormat, self)
240
+ if parentTable.metaFlags == 0:
241
+ datum = struct.pack(">H", self.offset)
242
+ elif parentTable.metaFlags == 1:
243
+ datum = struct.pack(">L", self.offset)
244
+ data = data + datum
245
+ return data
246
+
247
+ def __repr__(self):
248
+ return (
249
+ "GlyphRecord[ glyphID: "
250
+ + str(self.glyphID)
251
+ + ", nMetaEntry: "
252
+ + str(self.nMetaEntry)
253
+ + ", offset: "
254
+ + str(self.offset)
255
+ + " ]"
256
+ )
257
+
258
+
259
+ # XXX The following two functions are really broken around UTF-8 vs Unicode
260
+
261
+
262
+ def mapXMLToUTF8(string):
263
+ uString = str()
264
+ strLen = len(string)
265
+ i = 0
266
+ while i < strLen:
267
+ prefixLen = 0
268
+ if string[i : i + 3] == "&#x":
269
+ prefixLen = 3
270
+ elif string[i : i + 7] == "&amp;#x":
271
+ prefixLen = 7
272
+ if prefixLen:
273
+ i = i + prefixLen
274
+ j = i
275
+ while string[i] != ";":
276
+ i = i + 1
277
+ valStr = string[j:i]
278
+
279
+ uString = uString + chr(eval("0x" + valStr))
280
+ else:
281
+ uString = uString + chr(byteord(string[i]))
282
+ i = i + 1
283
+
284
+ return uString.encode("utf_8")
285
+
286
+
287
+ def mapUTF8toXML(string):
288
+ uString = string.decode("utf_8")
289
+ string = ""
290
+ for uChar in uString:
291
+ i = ord(uChar)
292
+ if (i < 0x80) and (i > 0x1F):
293
+ string = string + uChar
294
+ else:
295
+ string = string + "&#x" + hex(i)[2:] + ";"
296
+ return string
297
+
298
+
299
+ class StringRecord(object):
300
+ def toXML(self, writer, ttFont):
301
+ writer.begintag("StringRecord")
302
+ writer.newline()
303
+ writer.simpletag("labelID", value=self.labelID)
304
+ writer.comment(getLabelString(self.labelID))
305
+ writer.newline()
306
+ writer.newline()
307
+ writer.simpletag("string", value=mapUTF8toXML(self.string))
308
+ writer.newline()
309
+ writer.endtag("StringRecord")
310
+ writer.newline()
311
+
312
+ def fromXML(self, name, attrs, content, ttFont):
313
+ for element in content:
314
+ if isinstance(element, str):
315
+ continue
316
+ name, attrs, content = element
317
+ value = attrs["value"]
318
+ if name == "string":
319
+ self.string = mapXMLToUTF8(value)
320
+ else:
321
+ setattr(self, name, safeEval(value))
322
+
323
+ def compile(self, parentTable):
324
+ data = sstruct.pack(METAStringRecordFormat, self)
325
+ if parentTable.metaFlags == 0:
326
+ datum = struct.pack(">H", self.offset)
327
+ elif parentTable.metaFlags == 1:
328
+ datum = struct.pack(">L", self.offset)
329
+ data = data + datum
330
+ return data
331
+
332
+ def __repr__(self):
333
+ return (
334
+ "StringRecord [ labelID: "
335
+ + str(self.labelID)
336
+ + " aka "
337
+ + getLabelString(self.labelID)
338
+ + ", offset: "
339
+ + str(self.offset)
340
+ + ", length: "
341
+ + str(self.stringLen)
342
+ + ", string: "
343
+ + self.string
344
+ + " ]"
345
+ )
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/M_V_A_R_.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .otBase import BaseTTXConverter
2
+
3
+
4
+ class table_M_V_A_R_(BaseTTXConverter):
5
+ pass
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/S_V_G_.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compiles/decompiles SVG table.
2
+
3
+ https://docs.microsoft.com/en-us/typography/opentype/spec/svg
4
+
5
+ The XML format is:
6
+
7
+ .. code-block:: xml
8
+
9
+ <SVG>
10
+ <svgDoc endGlyphID="1" startGlyphID="1">
11
+ <![CDATA[ <complete SVG doc> ]]
12
+ </svgDoc>
13
+ ...
14
+ <svgDoc endGlyphID="n" startGlyphID="m">
15
+ <![CDATA[ <complete SVG doc> ]]
16
+ </svgDoc>
17
+ </SVG>
18
+ """
19
+
20
+ from fontTools.misc.textTools import bytesjoin, safeEval, strjoin, tobytes, tostr
21
+ from fontTools.misc import sstruct
22
+ from . import DefaultTable
23
+ from collections.abc import Sequence
24
+ from dataclasses import dataclass, astuple
25
+ from io import BytesIO
26
+ import struct
27
+ import logging
28
+
29
+
30
+ log = logging.getLogger(__name__)
31
+
32
+
33
+ SVG_format_0 = """
34
+ > # big endian
35
+ version: H
36
+ offsetToSVGDocIndex: L
37
+ reserved: L
38
+ """
39
+
40
+ SVG_format_0Size = sstruct.calcsize(SVG_format_0)
41
+
42
+ doc_index_entry_format_0 = """
43
+ > # big endian
44
+ startGlyphID: H
45
+ endGlyphID: H
46
+ svgDocOffset: L
47
+ svgDocLength: L
48
+ """
49
+
50
+ doc_index_entry_format_0Size = sstruct.calcsize(doc_index_entry_format_0)
51
+
52
+
53
+ class table_S_V_G_(DefaultTable.DefaultTable):
54
+ def decompile(self, data, ttFont):
55
+ self.docList = []
56
+ # Version 0 is the standardized version of the table; and current.
57
+ # https://www.microsoft.com/typography/otspec/svg.htm
58
+ sstruct.unpack(SVG_format_0, data[:SVG_format_0Size], self)
59
+ if self.version != 0:
60
+ log.warning(
61
+ "Unknown SVG table version '%s'. Decompiling as version 0.",
62
+ self.version,
63
+ )
64
+ # read in SVG Documents Index
65
+ # data starts with the first entry of the entry list.
66
+ pos = subTableStart = self.offsetToSVGDocIndex
67
+ self.numEntries = struct.unpack(">H", data[pos : pos + 2])[0]
68
+ pos += 2
69
+ if self.numEntries > 0:
70
+ data2 = data[pos:]
71
+ entries = []
72
+ for i in range(self.numEntries):
73
+ record_data = data2[
74
+ i
75
+ * doc_index_entry_format_0Size : (i + 1)
76
+ * doc_index_entry_format_0Size
77
+ ]
78
+ docIndexEntry = sstruct.unpack(
79
+ doc_index_entry_format_0, record_data, DocumentIndexEntry()
80
+ )
81
+ entries.append(docIndexEntry)
82
+
83
+ for entry in entries:
84
+ start = entry.svgDocOffset + subTableStart
85
+ end = start + entry.svgDocLength
86
+ doc = data[start:end]
87
+ compressed = False
88
+ if doc.startswith(b"\x1f\x8b"):
89
+ import gzip
90
+
91
+ bytesIO = BytesIO(doc)
92
+ with gzip.GzipFile(None, "r", fileobj=bytesIO) as gunzipper:
93
+ doc = gunzipper.read()
94
+ del bytesIO
95
+ compressed = True
96
+ doc = tostr(doc, "utf_8")
97
+ self.docList.append(
98
+ SVGDocument(doc, entry.startGlyphID, entry.endGlyphID, compressed)
99
+ )
100
+
101
+ def compile(self, ttFont):
102
+ version = 0
103
+ offsetToSVGDocIndex = (
104
+ SVG_format_0Size # I start the SVGDocIndex right after the header.
105
+ )
106
+ # get SGVDoc info.
107
+ docList = []
108
+ entryList = []
109
+ numEntries = len(self.docList)
110
+ datum = struct.pack(">H", numEntries)
111
+ entryList.append(datum)
112
+ curOffset = len(datum) + doc_index_entry_format_0Size * numEntries
113
+ seenDocs = {}
114
+ allCompressed = getattr(self, "compressed", False)
115
+ for i, doc in enumerate(self.docList):
116
+ if isinstance(doc, (list, tuple)):
117
+ doc = SVGDocument(*doc)
118
+ self.docList[i] = doc
119
+ docBytes = tobytes(doc.data, encoding="utf_8")
120
+ if (allCompressed or doc.compressed) and not docBytes.startswith(
121
+ b"\x1f\x8b"
122
+ ):
123
+ import gzip
124
+
125
+ bytesIO = BytesIO()
126
+ # mtime=0 strips the useless timestamp and makes gzip output reproducible;
127
+ # equivalent to `gzip -n`
128
+ with gzip.GzipFile(None, "w", fileobj=bytesIO, mtime=0) as gzipper:
129
+ gzipper.write(docBytes)
130
+ gzipped = bytesIO.getvalue()
131
+ if len(gzipped) < len(docBytes):
132
+ docBytes = gzipped
133
+ del gzipped, bytesIO
134
+ docLength = len(docBytes)
135
+ if docBytes in seenDocs:
136
+ docOffset = seenDocs[docBytes]
137
+ else:
138
+ docOffset = curOffset
139
+ curOffset += docLength
140
+ seenDocs[docBytes] = docOffset
141
+ docList.append(docBytes)
142
+ entry = struct.pack(
143
+ ">HHLL", doc.startGlyphID, doc.endGlyphID, docOffset, docLength
144
+ )
145
+ entryList.append(entry)
146
+ entryList.extend(docList)
147
+ svgDocData = bytesjoin(entryList)
148
+
149
+ reserved = 0
150
+ header = struct.pack(">HLL", version, offsetToSVGDocIndex, reserved)
151
+ data = [header, svgDocData]
152
+ data = bytesjoin(data)
153
+ return data
154
+
155
+ def toXML(self, writer, ttFont):
156
+ for i, doc in enumerate(self.docList):
157
+ if isinstance(doc, (list, tuple)):
158
+ doc = SVGDocument(*doc)
159
+ self.docList[i] = doc
160
+ attrs = {"startGlyphID": doc.startGlyphID, "endGlyphID": doc.endGlyphID}
161
+ if doc.compressed:
162
+ attrs["compressed"] = 1
163
+ writer.begintag("svgDoc", **attrs)
164
+ writer.newline()
165
+ writer.writecdata(doc.data)
166
+ writer.newline()
167
+ writer.endtag("svgDoc")
168
+ writer.newline()
169
+
170
+ def fromXML(self, name, attrs, content, ttFont):
171
+ if name == "svgDoc":
172
+ if not hasattr(self, "docList"):
173
+ self.docList = []
174
+ doc = strjoin(content)
175
+ doc = doc.strip()
176
+ startGID = int(attrs["startGlyphID"])
177
+ endGID = int(attrs["endGlyphID"])
178
+ compressed = bool(safeEval(attrs.get("compressed", "0")))
179
+ self.docList.append(SVGDocument(doc, startGID, endGID, compressed))
180
+ else:
181
+ log.warning("Unknown %s %s", name, content)
182
+
183
+
184
+ class DocumentIndexEntry(object):
185
+ def __init__(self):
186
+ self.startGlyphID = None # USHORT
187
+ self.endGlyphID = None # USHORT
188
+ self.svgDocOffset = None # ULONG
189
+ self.svgDocLength = None # ULONG
190
+
191
+ def __repr__(self):
192
+ return (
193
+ "startGlyphID: %s, endGlyphID: %s, svgDocOffset: %s, svgDocLength: %s"
194
+ % (self.startGlyphID, self.endGlyphID, self.svgDocOffset, self.svgDocLength)
195
+ )
196
+
197
+
198
+ @dataclass
199
+ class SVGDocument(Sequence):
200
+ data: str
201
+ startGlyphID: int
202
+ endGlyphID: int
203
+ compressed: bool = False
204
+
205
+ # Previously, the SVG table's docList attribute contained a lists of 3 items:
206
+ # [doc, startGlyphID, endGlyphID]; later, we added a `compressed` attribute.
207
+ # For backward compatibility with code that depends of them being sequences of
208
+ # fixed length=3, we subclass the Sequence abstract base class and pretend only
209
+ # the first three items are present. 'compressed' is only accessible via named
210
+ # attribute lookup like regular dataclasses: i.e. `doc.compressed`, not `doc[3]`
211
+ def __getitem__(self, index):
212
+ return astuple(self)[:3][index]
213
+
214
+ def __len__(self):
215
+ return 3
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/S__i_l_l.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc import sstruct
2
+ from fontTools.misc.fixedTools import floatToFixedToStr
3
+ from fontTools.misc.textTools import safeEval
4
+ from . import DefaultTable
5
+ from . import grUtils
6
+ import struct
7
+
8
+ Sill_hdr = """
9
+ >
10
+ version: 16.16F
11
+ """
12
+
13
+
14
+ class table_S__i_l_l(DefaultTable.DefaultTable):
15
+ def __init__(self, tag=None):
16
+ DefaultTable.DefaultTable.__init__(self, tag)
17
+ self.langs = {}
18
+
19
+ def decompile(self, data, ttFont):
20
+ (_, data) = sstruct.unpack2(Sill_hdr, data, self)
21
+ self.version = float(floatToFixedToStr(self.version, precisionBits=16))
22
+ (numLangs,) = struct.unpack(">H", data[:2])
23
+ data = data[8:]
24
+ maxsetting = 0
25
+ langinfo = []
26
+ for i in range(numLangs):
27
+ (langcode, numsettings, offset) = struct.unpack(
28
+ ">4sHH", data[i * 8 : (i + 1) * 8]
29
+ )
30
+ offset = int(offset / 8) - (numLangs + 1)
31
+ langcode = langcode.replace(b"\000", b"")
32
+ langinfo.append((langcode.decode("utf-8"), numsettings, offset))
33
+ maxsetting = max(maxsetting, offset + numsettings)
34
+ data = data[numLangs * 8 :]
35
+ finfo = []
36
+ for i in range(maxsetting):
37
+ (fid, val, _) = struct.unpack(">LHH", data[i * 8 : (i + 1) * 8])
38
+ finfo.append((fid, val))
39
+ self.langs = {}
40
+ for c, n, o in langinfo:
41
+ self.langs[c] = []
42
+ for i in range(o, o + n):
43
+ self.langs[c].append(finfo[i])
44
+
45
+ def compile(self, ttFont):
46
+ ldat = b""
47
+ fdat = b""
48
+ offset = len(self.langs)
49
+ for c, inf in sorted(self.langs.items()):
50
+ ldat += struct.pack(">4sHH", c.encode("utf8"), len(inf), 8 * offset + 20)
51
+ for fid, val in inf:
52
+ fdat += struct.pack(">LHH", fid, val, 0)
53
+ offset += len(inf)
54
+ ldat += struct.pack(">LHH", 0x80808080, 0, 8 * offset + 20)
55
+ return (
56
+ sstruct.pack(Sill_hdr, self)
57
+ + grUtils.bininfo(len(self.langs))
58
+ + ldat
59
+ + fdat
60
+ )
61
+
62
+ def toXML(self, writer, ttFont):
63
+ writer.simpletag("version", version=self.version)
64
+ writer.newline()
65
+ for c, inf in sorted(self.langs.items()):
66
+ writer.begintag("lang", name=c)
67
+ writer.newline()
68
+ for fid, val in inf:
69
+ writer.simpletag("feature", fid=grUtils.num2tag(fid), val=val)
70
+ writer.newline()
71
+ writer.endtag("lang")
72
+ writer.newline()
73
+
74
+ def fromXML(self, name, attrs, content, ttFont):
75
+ if name == "version":
76
+ self.version = float(safeEval(attrs["version"]))
77
+ elif name == "lang":
78
+ c = attrs["name"]
79
+ self.langs[c] = []
80
+ for element in content:
81
+ if not isinstance(element, tuple):
82
+ continue
83
+ tag, a, subcontent = element
84
+ if tag == "feature":
85
+ self.langs[c].append(
86
+ (grUtils.tag2num(a["fid"]), int(safeEval(a["val"])))
87
+ )
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/T_S_I_C_.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .otBase import BaseTTXConverter
2
+
3
+
4
+ class table_T_S_I_C_(BaseTTXConverter):
5
+ pass
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/T_S_I_J_.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .T_S_I_V_ import table_T_S_I_V_
2
+
3
+
4
+ class table_T_S_I_J_(table_T_S_I_V_):
5
+ pass
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/T_S_I__0.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT)
2
+ tool to store its hinting source data.
3
+
4
+ TSI0 is the index table containing the lengths and offsets for the glyph
5
+ programs and 'extra' programs ('fpgm', 'prep', and 'cvt') that are contained
6
+ in the TSI1 table.
7
+ """
8
+
9
+ from . import DefaultTable
10
+ import struct
11
+
12
+ tsi0Format = ">HHL"
13
+
14
+
15
+ def fixlongs(glyphID, textLength, textOffset):
16
+ return int(glyphID), int(textLength), textOffset
17
+
18
+
19
+ class table_T_S_I__0(DefaultTable.DefaultTable):
20
+ dependencies = ["TSI1"]
21
+
22
+ def decompile(self, data, ttFont):
23
+ numGlyphs = ttFont["maxp"].numGlyphs
24
+ indices = []
25
+ size = struct.calcsize(tsi0Format)
26
+ for i in range(numGlyphs + 5):
27
+ glyphID, textLength, textOffset = fixlongs(
28
+ *struct.unpack(tsi0Format, data[:size])
29
+ )
30
+ indices.append((glyphID, textLength, textOffset))
31
+ data = data[size:]
32
+ assert len(data) == 0
33
+ assert indices[-5] == (0xFFFE, 0, 0xABFC1F34), "bad magic number"
34
+ self.indices = indices[:-5]
35
+ self.extra_indices = indices[-4:]
36
+
37
+ def compile(self, ttFont):
38
+ if not hasattr(self, "indices"):
39
+ # We have no corresponding table (TSI1 or TSI3); let's return
40
+ # no data, which effectively means "ignore us".
41
+ return b""
42
+ data = b""
43
+ for index, textLength, textOffset in self.indices:
44
+ data = data + struct.pack(tsi0Format, index, textLength, textOffset)
45
+ data = data + struct.pack(tsi0Format, 0xFFFE, 0, 0xABFC1F34)
46
+ for index, textLength, textOffset in self.extra_indices:
47
+ data = data + struct.pack(tsi0Format, index, textLength, textOffset)
48
+ return data
49
+
50
+ def set(self, indices, extra_indices):
51
+ # gets called by 'TSI1' or 'TSI3'
52
+ self.indices = indices
53
+ self.extra_indices = extra_indices
54
+
55
+ def toXML(self, writer, ttFont):
56
+ writer.comment("This table will be calculated by the compiler")
57
+ writer.newline()
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/T_S_I__2.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT)
2
+ tool to store its hinting source data.
3
+
4
+ TSI2 is the index table containing the lengths and offsets for the glyph
5
+ programs that are contained in the TSI3 table. It uses the same format as
6
+ the TSI0 table.
7
+ """
8
+
9
+ from fontTools import ttLib
10
+
11
+ superclass = ttLib.getTableClass("TSI0")
12
+
13
+
14
+ class table_T_S_I__2(superclass):
15
+ dependencies = ["TSI3"]
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/T_S_I__3.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ TSI{0,1,2,3,5} are private tables used by Microsoft Visual TrueType (VTT)
2
+ tool to store its hinting source data.
3
+
4
+ TSI3 contains the text of the glyph programs in the form of 'VTTTalk' code.
5
+ """
6
+
7
+ from fontTools import ttLib
8
+
9
+ superclass = ttLib.getTableClass("TSI1")
10
+
11
+
12
+ class table_T_S_I__3(superclass):
13
+ extras = {
14
+ 0xFFFA: "reserved0",
15
+ 0xFFFB: "reserved1",
16
+ 0xFFFC: "reserved2",
17
+ 0xFFFD: "reserved3",
18
+ }
19
+
20
+ indextable = "TSI2"
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/V_O_R_G_.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc.textTools import bytesjoin, safeEval
2
+ from . import DefaultTable
3
+ import struct
4
+
5
+
6
+ class table_V_O_R_G_(DefaultTable.DefaultTable):
7
+ """This table is structured so that you can treat it like a dictionary keyed by glyph name.
8
+
9
+ ``ttFont['VORG'][<glyphName>]`` will return the vertical origin for any glyph.
10
+
11
+ ``ttFont['VORG'][<glyphName>] = <value>`` will set the vertical origin for any glyph.
12
+ """
13
+
14
+ def decompile(self, data, ttFont):
15
+ self.getGlyphName = (
16
+ ttFont.getGlyphName
17
+ ) # for use in get/set item functions, for access by GID
18
+ (
19
+ self.majorVersion,
20
+ self.minorVersion,
21
+ self.defaultVertOriginY,
22
+ self.numVertOriginYMetrics,
23
+ ) = struct.unpack(">HHhH", data[:8])
24
+ assert (
25
+ self.majorVersion <= 1
26
+ ), "Major version of VORG table is higher than I know how to handle"
27
+ data = data[8:]
28
+ vids = []
29
+ gids = []
30
+ pos = 0
31
+ for i in range(self.numVertOriginYMetrics):
32
+ gid, vOrigin = struct.unpack(">Hh", data[pos : pos + 4])
33
+ pos += 4
34
+ gids.append(gid)
35
+ vids.append(vOrigin)
36
+
37
+ self.VOriginRecords = vOrig = {}
38
+ glyphOrder = ttFont.getGlyphOrder()
39
+ try:
40
+ names = [glyphOrder[gid] for gid in gids]
41
+ except IndexError:
42
+ getGlyphName = self.getGlyphName
43
+ names = map(getGlyphName, gids)
44
+
45
+ for name, vid in zip(names, vids):
46
+ vOrig[name] = vid
47
+
48
+ def compile(self, ttFont):
49
+ vorgs = list(self.VOriginRecords.values())
50
+ names = list(self.VOriginRecords.keys())
51
+ nameMap = ttFont.getReverseGlyphMap()
52
+ try:
53
+ gids = [nameMap[name] for name in names]
54
+ except KeyError:
55
+ nameMap = ttFont.getReverseGlyphMap(rebuild=True)
56
+ gids = [nameMap[name] for name in names]
57
+ vOriginTable = list(zip(gids, vorgs))
58
+ self.numVertOriginYMetrics = len(vorgs)
59
+ vOriginTable.sort() # must be in ascending GID order
60
+ dataList = [struct.pack(">Hh", rec[0], rec[1]) for rec in vOriginTable]
61
+ header = struct.pack(
62
+ ">HHhH",
63
+ self.majorVersion,
64
+ self.minorVersion,
65
+ self.defaultVertOriginY,
66
+ self.numVertOriginYMetrics,
67
+ )
68
+ dataList.insert(0, header)
69
+ data = bytesjoin(dataList)
70
+ return data
71
+
72
+ def toXML(self, writer, ttFont):
73
+ writer.simpletag("majorVersion", value=self.majorVersion)
74
+ writer.newline()
75
+ writer.simpletag("minorVersion", value=self.minorVersion)
76
+ writer.newline()
77
+ writer.simpletag("defaultVertOriginY", value=self.defaultVertOriginY)
78
+ writer.newline()
79
+ writer.simpletag("numVertOriginYMetrics", value=self.numVertOriginYMetrics)
80
+ writer.newline()
81
+ vOriginTable = []
82
+ glyphNames = self.VOriginRecords.keys()
83
+ for glyphName in glyphNames:
84
+ try:
85
+ gid = ttFont.getGlyphID(glyphName)
86
+ except:
87
+ assert 0, (
88
+ "VORG table contains a glyph name not in ttFont.getGlyphNames(): "
89
+ + str(glyphName)
90
+ )
91
+ vOriginTable.append([gid, glyphName, self.VOriginRecords[glyphName]])
92
+ vOriginTable.sort()
93
+ for entry in vOriginTable:
94
+ vOriginRec = VOriginRecord(entry[1], entry[2])
95
+ vOriginRec.toXML(writer, ttFont)
96
+
97
+ def fromXML(self, name, attrs, content, ttFont):
98
+ if not hasattr(self, "VOriginRecords"):
99
+ self.VOriginRecords = {}
100
+ self.getGlyphName = (
101
+ ttFont.getGlyphName
102
+ ) # for use in get/set item functions, for access by GID
103
+ if name == "VOriginRecord":
104
+ vOriginRec = VOriginRecord()
105
+ for element in content:
106
+ if isinstance(element, str):
107
+ continue
108
+ name, attrs, content = element
109
+ vOriginRec.fromXML(name, attrs, content, ttFont)
110
+ self.VOriginRecords[vOriginRec.glyphName] = vOriginRec.vOrigin
111
+ elif "value" in attrs:
112
+ setattr(self, name, safeEval(attrs["value"]))
113
+
114
+ def __getitem__(self, glyphSelector):
115
+ if isinstance(glyphSelector, int):
116
+ # its a gid, convert to glyph name
117
+ glyphSelector = self.getGlyphName(glyphSelector)
118
+
119
+ if glyphSelector not in self.VOriginRecords:
120
+ return self.defaultVertOriginY
121
+
122
+ return self.VOriginRecords[glyphSelector]
123
+
124
+ def __setitem__(self, glyphSelector, value):
125
+ if isinstance(glyphSelector, int):
126
+ # its a gid, convert to glyph name
127
+ glyphSelector = self.getGlyphName(glyphSelector)
128
+
129
+ if value != self.defaultVertOriginY:
130
+ self.VOriginRecords[glyphSelector] = value
131
+ elif glyphSelector in self.VOriginRecords:
132
+ del self.VOriginRecords[glyphSelector]
133
+
134
+ def __delitem__(self, glyphSelector):
135
+ del self.VOriginRecords[glyphSelector]
136
+
137
+
138
+ class VOriginRecord(object):
139
+ def __init__(self, name=None, vOrigin=None):
140
+ self.glyphName = name
141
+ self.vOrigin = vOrigin
142
+
143
+ def toXML(self, writer, ttFont):
144
+ writer.begintag("VOriginRecord")
145
+ writer.newline()
146
+ writer.simpletag("glyphName", value=self.glyphName)
147
+ writer.newline()
148
+ writer.simpletag("vOrigin", value=self.vOrigin)
149
+ writer.newline()
150
+ writer.endtag("VOriginRecord")
151
+ writer.newline()
152
+
153
+ def fromXML(self, name, attrs, content, ttFont):
154
+ value = attrs["value"]
155
+ if name == "glyphName":
156
+ setattr(self, name, value)
157
+ else:
158
+ setattr(self, name, safeEval(value))
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/V_V_A_R_.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .otBase import BaseTTXConverter
2
+
3
+
4
+ class table_V_V_A_R_(BaseTTXConverter):
5
+ pass
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/__init__.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DON'T EDIT! This file is generated by MetaTools/buildTableList.py.
2
+ def _moduleFinderHint():
3
+ """Dummy function to let modulefinder know what tables may be
4
+ dynamically imported. Generated by MetaTools/buildTableList.py.
5
+
6
+ >>> _moduleFinderHint()
7
+ """
8
+ from . import B_A_S_E_
9
+ from . import C_B_D_T_
10
+ from . import C_B_L_C_
11
+ from . import C_F_F_
12
+ from . import C_F_F__2
13
+ from . import C_O_L_R_
14
+ from . import C_P_A_L_
15
+ from . import D_S_I_G_
16
+ from . import D__e_b_g
17
+ from . import E_B_D_T_
18
+ from . import E_B_L_C_
19
+ from . import F_F_T_M_
20
+ from . import F__e_a_t
21
+ from . import G_D_E_F_
22
+ from . import G_M_A_P_
23
+ from . import G_P_K_G_
24
+ from . import G_P_O_S_
25
+ from . import G_S_U_B_
26
+ from . import G__l_a_t
27
+ from . import G__l_o_c
28
+ from . import H_V_A_R_
29
+ from . import J_S_T_F_
30
+ from . import L_T_S_H_
31
+ from . import M_A_T_H_
32
+ from . import M_E_T_A_
33
+ from . import M_V_A_R_
34
+ from . import O_S_2f_2
35
+ from . import S_I_N_G_
36
+ from . import S_T_A_T_
37
+ from . import S_V_G_
38
+ from . import S__i_l_f
39
+ from . import S__i_l_l
40
+ from . import T_S_I_B_
41
+ from . import T_S_I_C_
42
+ from . import T_S_I_D_
43
+ from . import T_S_I_J_
44
+ from . import T_S_I_P_
45
+ from . import T_S_I_S_
46
+ from . import T_S_I_V_
47
+ from . import T_S_I__0
48
+ from . import T_S_I__1
49
+ from . import T_S_I__2
50
+ from . import T_S_I__3
51
+ from . import T_S_I__5
52
+ from . import T_T_F_A_
53
+ from . import V_A_R_C_
54
+ from . import V_D_M_X_
55
+ from . import V_O_R_G_
56
+ from . import V_V_A_R_
57
+ from . import _a_n_k_r
58
+ from . import _a_v_a_r
59
+ from . import _b_s_l_n
60
+ from . import _c_i_d_g
61
+ from . import _c_m_a_p
62
+ from . import _c_v_a_r
63
+ from . import _c_v_t
64
+ from . import _f_e_a_t
65
+ from . import _f_p_g_m
66
+ from . import _f_v_a_r
67
+ from . import _g_a_s_p
68
+ from . import _g_c_i_d
69
+ from . import _g_l_y_f
70
+ from . import _g_v_a_r
71
+ from . import _h_d_m_x
72
+ from . import _h_e_a_d
73
+ from . import _h_h_e_a
74
+ from . import _h_m_t_x
75
+ from . import _k_e_r_n
76
+ from . import _l_c_a_r
77
+ from . import _l_o_c_a
78
+ from . import _l_t_a_g
79
+ from . import _m_a_x_p
80
+ from . import _m_e_t_a
81
+ from . import _m_o_r_t
82
+ from . import _m_o_r_x
83
+ from . import _n_a_m_e
84
+ from . import _o_p_b_d
85
+ from . import _p_o_s_t
86
+ from . import _p_r_e_p
87
+ from . import _p_r_o_p
88
+ from . import _s_b_i_x
89
+ from . import _t_r_a_k
90
+ from . import _v_h_e_a
91
+ from . import _v_m_t_x
92
+
93
+
94
+ if __name__ == "__main__":
95
+ import doctest, sys
96
+
97
+ sys.exit(doctest.testmod().failed)
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_a_n_k_r.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .otBase import BaseTTXConverter
2
+
3
+
4
+ class table__a_n_k_r(BaseTTXConverter):
5
+ """
6
+ The anchor point table provides a way to define anchor points.
7
+ These are points within the coordinate space of a given glyph,
8
+ independent of the control points used to render the glyph.
9
+ Anchor points are used in conjunction with the 'kerx' table.
10
+
11
+ See also https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ankr.html
12
+ """
13
+
14
+ pass
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_c_i_d_g.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+ from .otBase import BaseTTXConverter
3
+
4
+
5
+ class table__c_i_d_g(BaseTTXConverter):
6
+ """The AAT ``cidg`` table has almost the same structure as ``gidc``,
7
+ just mapping CIDs to GlyphIDs instead of the reverse direction.
8
+
9
+ It is useful for fonts that may be used by a PDF renderer in lieu of
10
+ a font reference with a known glyph collection but no subsetted
11
+ glyphs. For instance, a PDF can say “please use a font conforming
12
+ to Adobe-Japan-1”; the ``cidg`` mapping is necessary if the font is,
13
+ say, a TrueType font. ``gidc`` is lossy for this purpose and is
14
+ obsoleted by ``cidg``.
15
+
16
+ For example, the first font in ``/System/Library/Fonts/PingFang.ttc``
17
+ (which Apple ships pre-installed on MacOS 10.12.6) has a ``cidg`` table."""
18
+
19
+ pass
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_f_e_a_t.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .otBase import BaseTTXConverter
2
+
3
+
4
+ class table__f_e_a_t(BaseTTXConverter):
5
+ """The feature name table is an AAT (Apple Advanced Typography) table for
6
+ storing font features, settings, and their human-readable names. It should
7
+ not be confused with the ``Feat`` table or the OpenType Layout ``GSUB``/``GPOS``
8
+ tables. See `Feature Name Table <https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6feat.html>`_
9
+ in the TrueType Reference Manual for more information on the structure and
10
+ purpose of this table."""
11
+
12
+ pass
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_f_p_g_m.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import DefaultTable
2
+ from . import ttProgram
3
+
4
+
5
+ class table__f_p_g_m(DefaultTable.DefaultTable):
6
+ def decompile(self, data, ttFont):
7
+ program = ttProgram.Program()
8
+ program.fromBytecode(data)
9
+ self.program = program
10
+
11
+ def compile(self, ttFont):
12
+ return self.program.getBytecode()
13
+
14
+ def toXML(self, writer, ttFont):
15
+ self.program.toXML(writer, ttFont)
16
+
17
+ def fromXML(self, name, attrs, content, ttFont):
18
+ program = ttProgram.Program()
19
+ program.fromXML(name, attrs, content, ttFont)
20
+ self.program = program
21
+
22
+ def __bool__(self):
23
+ """
24
+ >>> fpgm = table__f_p_g_m()
25
+ >>> bool(fpgm)
26
+ False
27
+ >>> p = ttProgram.Program()
28
+ >>> fpgm.program = p
29
+ >>> bool(fpgm)
30
+ False
31
+ >>> bc = bytearray([0])
32
+ >>> p.fromBytecode(bc)
33
+ >>> bool(fpgm)
34
+ True
35
+ >>> p.bytecode.pop()
36
+ 0
37
+ >>> bool(fpgm)
38
+ False
39
+ """
40
+ return hasattr(self, "program") and bool(self.program)
41
+
42
+ __nonzero__ = __bool__
43
+
44
+
45
+ if __name__ == "__main__":
46
+ import sys
47
+ import doctest
48
+
49
+ sys.exit(doctest.testmod().failed)
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_f_v_a_r.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc import sstruct
2
+ from fontTools.misc.fixedTools import (
3
+ fixedToFloat as fi2fl,
4
+ floatToFixed as fl2fi,
5
+ floatToFixedToStr as fl2str,
6
+ strToFixedToFloat as str2fl,
7
+ )
8
+ from fontTools.misc.textTools import Tag, bytesjoin, safeEval
9
+ from fontTools.ttLib import TTLibError
10
+ from . import DefaultTable
11
+ import struct
12
+
13
+
14
+ # Apple's documentation of 'fvar':
15
+ # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6fvar.html
16
+
17
+ FVAR_HEADER_FORMAT = """
18
+ > # big endian
19
+ version: L
20
+ offsetToData: H
21
+ countSizePairs: H
22
+ axisCount: H
23
+ axisSize: H
24
+ instanceCount: H
25
+ instanceSize: H
26
+ """
27
+
28
+ FVAR_AXIS_FORMAT = """
29
+ > # big endian
30
+ axisTag: 4s
31
+ minValue: 16.16F
32
+ defaultValue: 16.16F
33
+ maxValue: 16.16F
34
+ flags: H
35
+ axisNameID: H
36
+ """
37
+
38
+ FVAR_INSTANCE_FORMAT = """
39
+ > # big endian
40
+ subfamilyNameID: H
41
+ flags: H
42
+ """
43
+
44
+
45
+ class table__f_v_a_r(DefaultTable.DefaultTable):
46
+ dependencies = ["name"]
47
+
48
+ def __init__(self, tag=None):
49
+ DefaultTable.DefaultTable.__init__(self, tag)
50
+ self.axes = []
51
+ self.instances = []
52
+
53
+ def compile(self, ttFont):
54
+ instanceSize = sstruct.calcsize(FVAR_INSTANCE_FORMAT) + (len(self.axes) * 4)
55
+ includePostScriptNames = any(
56
+ instance.postscriptNameID != 0xFFFF for instance in self.instances
57
+ )
58
+ if includePostScriptNames:
59
+ instanceSize += 2
60
+ header = {
61
+ "version": 0x00010000,
62
+ "offsetToData": sstruct.calcsize(FVAR_HEADER_FORMAT),
63
+ "countSizePairs": 2,
64
+ "axisCount": len(self.axes),
65
+ "axisSize": sstruct.calcsize(FVAR_AXIS_FORMAT),
66
+ "instanceCount": len(self.instances),
67
+ "instanceSize": instanceSize,
68
+ }
69
+ result = [sstruct.pack(FVAR_HEADER_FORMAT, header)]
70
+ result.extend([axis.compile() for axis in self.axes])
71
+ axisTags = [axis.axisTag for axis in self.axes]
72
+ for instance in self.instances:
73
+ result.append(instance.compile(axisTags, includePostScriptNames))
74
+ return bytesjoin(result)
75
+
76
+ def decompile(self, data, ttFont):
77
+ header = {}
78
+ headerSize = sstruct.calcsize(FVAR_HEADER_FORMAT)
79
+ header = sstruct.unpack(FVAR_HEADER_FORMAT, data[0:headerSize])
80
+ if header["version"] != 0x00010000:
81
+ raise TTLibError("unsupported 'fvar' version %04x" % header["version"])
82
+ pos = header["offsetToData"]
83
+ axisSize = header["axisSize"]
84
+ for _ in range(header["axisCount"]):
85
+ axis = Axis()
86
+ axis.decompile(data[pos : pos + axisSize])
87
+ self.axes.append(axis)
88
+ pos += axisSize
89
+ instanceSize = header["instanceSize"]
90
+ axisTags = [axis.axisTag for axis in self.axes]
91
+ for _ in range(header["instanceCount"]):
92
+ instance = NamedInstance()
93
+ instance.decompile(data[pos : pos + instanceSize], axisTags)
94
+ self.instances.append(instance)
95
+ pos += instanceSize
96
+
97
+ def toXML(self, writer, ttFont):
98
+ for axis in self.axes:
99
+ axis.toXML(writer, ttFont)
100
+ for instance in self.instances:
101
+ instance.toXML(writer, ttFont)
102
+
103
+ def fromXML(self, name, attrs, content, ttFont):
104
+ if name == "Axis":
105
+ axis = Axis()
106
+ axis.fromXML(name, attrs, content, ttFont)
107
+ self.axes.append(axis)
108
+ elif name == "NamedInstance":
109
+ instance = NamedInstance()
110
+ instance.fromXML(name, attrs, content, ttFont)
111
+ self.instances.append(instance)
112
+
113
+ def getAxes(self):
114
+ return {a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in self.axes}
115
+
116
+
117
+ class Axis(object):
118
+ def __init__(self):
119
+ self.axisTag = None
120
+ self.axisNameID = 0
121
+ self.flags = 0
122
+ self.minValue = -1.0
123
+ self.defaultValue = 0.0
124
+ self.maxValue = 1.0
125
+
126
+ def compile(self):
127
+ return sstruct.pack(FVAR_AXIS_FORMAT, self)
128
+
129
+ def decompile(self, data):
130
+ sstruct.unpack2(FVAR_AXIS_FORMAT, data, self)
131
+
132
+ def toXML(self, writer, ttFont):
133
+ name = (
134
+ ttFont["name"].getDebugName(self.axisNameID) if "name" in ttFont else None
135
+ )
136
+ if name is not None:
137
+ writer.newline()
138
+ writer.comment(name)
139
+ writer.newline()
140
+ writer.begintag("Axis")
141
+ writer.newline()
142
+ for tag, value in [
143
+ ("AxisTag", self.axisTag),
144
+ ("Flags", "0x%X" % self.flags),
145
+ ("MinValue", fl2str(self.minValue, 16)),
146
+ ("DefaultValue", fl2str(self.defaultValue, 16)),
147
+ ("MaxValue", fl2str(self.maxValue, 16)),
148
+ ("AxisNameID", str(self.axisNameID)),
149
+ ]:
150
+ writer.begintag(tag)
151
+ writer.write(value)
152
+ writer.endtag(tag)
153
+ writer.newline()
154
+ writer.endtag("Axis")
155
+ writer.newline()
156
+
157
+ def fromXML(self, name, _attrs, content, ttFont):
158
+ assert name == "Axis"
159
+ for tag, _, value in filter(lambda t: type(t) is tuple, content):
160
+ value = "".join(value)
161
+ if tag == "AxisTag":
162
+ self.axisTag = Tag(value)
163
+ elif tag in {"Flags", "MinValue", "DefaultValue", "MaxValue", "AxisNameID"}:
164
+ setattr(
165
+ self,
166
+ tag[0].lower() + tag[1:],
167
+ str2fl(value, 16) if tag.endswith("Value") else safeEval(value),
168
+ )
169
+
170
+
171
+ class NamedInstance(object):
172
+ def __init__(self):
173
+ self.subfamilyNameID = 0
174
+ self.postscriptNameID = 0xFFFF
175
+ self.flags = 0
176
+ self.coordinates = {}
177
+
178
+ def compile(self, axisTags, includePostScriptName):
179
+ result = [sstruct.pack(FVAR_INSTANCE_FORMAT, self)]
180
+ for axis in axisTags:
181
+ fixedCoord = fl2fi(self.coordinates[axis], 16)
182
+ result.append(struct.pack(">l", fixedCoord))
183
+ if includePostScriptName:
184
+ result.append(struct.pack(">H", self.postscriptNameID))
185
+ return bytesjoin(result)
186
+
187
+ def decompile(self, data, axisTags):
188
+ sstruct.unpack2(FVAR_INSTANCE_FORMAT, data, self)
189
+ pos = sstruct.calcsize(FVAR_INSTANCE_FORMAT)
190
+ for axis in axisTags:
191
+ value = struct.unpack(">l", data[pos : pos + 4])[0]
192
+ self.coordinates[axis] = fi2fl(value, 16)
193
+ pos += 4
194
+ if pos + 2 <= len(data):
195
+ self.postscriptNameID = struct.unpack(">H", data[pos : pos + 2])[0]
196
+ else:
197
+ self.postscriptNameID = 0xFFFF
198
+
199
+ def toXML(self, writer, ttFont):
200
+ name = (
201
+ ttFont["name"].getDebugName(self.subfamilyNameID)
202
+ if "name" in ttFont
203
+ else None
204
+ )
205
+ if name is not None:
206
+ writer.newline()
207
+ writer.comment(name)
208
+ writer.newline()
209
+ psname = (
210
+ ttFont["name"].getDebugName(self.postscriptNameID)
211
+ if "name" in ttFont
212
+ else None
213
+ )
214
+ if psname is not None:
215
+ writer.comment("PostScript: " + psname)
216
+ writer.newline()
217
+ if self.postscriptNameID == 0xFFFF:
218
+ writer.begintag(
219
+ "NamedInstance",
220
+ flags=("0x%X" % self.flags),
221
+ subfamilyNameID=self.subfamilyNameID,
222
+ )
223
+ else:
224
+ writer.begintag(
225
+ "NamedInstance",
226
+ flags=("0x%X" % self.flags),
227
+ subfamilyNameID=self.subfamilyNameID,
228
+ postscriptNameID=self.postscriptNameID,
229
+ )
230
+ writer.newline()
231
+ for axis in ttFont["fvar"].axes:
232
+ writer.simpletag(
233
+ "coord",
234
+ axis=axis.axisTag,
235
+ value=fl2str(self.coordinates[axis.axisTag], 16),
236
+ )
237
+ writer.newline()
238
+ writer.endtag("NamedInstance")
239
+ writer.newline()
240
+
241
+ def fromXML(self, name, attrs, content, ttFont):
242
+ assert name == "NamedInstance"
243
+ self.subfamilyNameID = safeEval(attrs["subfamilyNameID"])
244
+ self.flags = safeEval(attrs.get("flags", "0"))
245
+ if "postscriptNameID" in attrs:
246
+ self.postscriptNameID = safeEval(attrs["postscriptNameID"])
247
+ else:
248
+ self.postscriptNameID = 0xFFFF
249
+
250
+ for tag, elementAttrs, _ in filter(lambda t: type(t) is tuple, content):
251
+ if tag == "coord":
252
+ value = str2fl(elementAttrs["value"], 16)
253
+ self.coordinates[elementAttrs["axis"]] = value
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_g_a_s_p.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc.textTools import safeEval
2
+ from . import DefaultTable
3
+ import struct
4
+
5
+
6
+ GASP_SYMMETRIC_GRIDFIT = 0x0004
7
+ GASP_SYMMETRIC_SMOOTHING = 0x0008
8
+ GASP_DOGRAY = 0x0002
9
+ GASP_GRIDFIT = 0x0001
10
+
11
+
12
+ class table__g_a_s_p(DefaultTable.DefaultTable):
13
+ def decompile(self, data, ttFont):
14
+ self.version, numRanges = struct.unpack(">HH", data[:4])
15
+ assert 0 <= self.version <= 1, "unknown 'gasp' format: %s" % self.version
16
+ data = data[4:]
17
+ self.gaspRange = {}
18
+ for i in range(numRanges):
19
+ rangeMaxPPEM, rangeGaspBehavior = struct.unpack(">HH", data[:4])
20
+ self.gaspRange[int(rangeMaxPPEM)] = int(rangeGaspBehavior)
21
+ data = data[4:]
22
+ assert not data, "too much data"
23
+
24
+ def compile(self, ttFont):
25
+ version = 0 # ignore self.version
26
+ numRanges = len(self.gaspRange)
27
+ data = b""
28
+ items = sorted(self.gaspRange.items())
29
+ for rangeMaxPPEM, rangeGaspBehavior in items:
30
+ data = data + struct.pack(">HH", rangeMaxPPEM, rangeGaspBehavior)
31
+ if rangeGaspBehavior & ~(GASP_GRIDFIT | GASP_DOGRAY):
32
+ version = 1
33
+ data = struct.pack(">HH", version, numRanges) + data
34
+ return data
35
+
36
+ def toXML(self, writer, ttFont):
37
+ items = sorted(self.gaspRange.items())
38
+ for rangeMaxPPEM, rangeGaspBehavior in items:
39
+ writer.simpletag(
40
+ "gaspRange",
41
+ [
42
+ ("rangeMaxPPEM", rangeMaxPPEM),
43
+ ("rangeGaspBehavior", rangeGaspBehavior),
44
+ ],
45
+ )
46
+ writer.newline()
47
+
48
+ def fromXML(self, name, attrs, content, ttFont):
49
+ if name != "gaspRange":
50
+ return
51
+ if not hasattr(self, "gaspRange"):
52
+ self.gaspRange = {}
53
+ self.gaspRange[safeEval(attrs["rangeMaxPPEM"])] = safeEval(
54
+ attrs["rangeGaspBehavior"]
55
+ )
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_g_l_y_f.py ADDED
@@ -0,0 +1,2222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """_g_l_y_f.py -- Converter classes for the 'glyf' table."""
2
+
3
+ from collections import namedtuple
4
+ from fontTools.misc import sstruct
5
+ from fontTools import ttLib
6
+ from fontTools import version
7
+ from fontTools.misc.transform import DecomposedTransform
8
+ from fontTools.misc.textTools import tostr, safeEval, pad
9
+ from fontTools.misc.arrayTools import updateBounds, pointInRect
10
+ from fontTools.misc.bezierTools import calcQuadraticBounds
11
+ from fontTools.misc.fixedTools import (
12
+ fixedToFloat as fi2fl,
13
+ floatToFixed as fl2fi,
14
+ floatToFixedToStr as fl2str,
15
+ strToFixedToFloat as str2fl,
16
+ )
17
+ from fontTools.misc.roundTools import noRound, otRound
18
+ from fontTools.misc.vector import Vector
19
+ from numbers import Number
20
+ from . import DefaultTable
21
+ from . import ttProgram
22
+ import sys
23
+ import struct
24
+ import array
25
+ import logging
26
+ import math
27
+ import os
28
+ from fontTools.misc import xmlWriter
29
+ from fontTools.misc.filenames import userNameToFileName
30
+ from fontTools.misc.loggingTools import deprecateFunction
31
+ from enum import IntFlag
32
+ from functools import partial
33
+ from types import SimpleNamespace
34
+ from typing import Set
35
+
36
+ log = logging.getLogger(__name__)
37
+
38
+ # We compute the version the same as is computed in ttlib/__init__
39
+ # so that we can write 'ttLibVersion' attribute of the glyf TTX files
40
+ # when glyf is written to separate files.
41
+ version = ".".join(version.split(".")[:2])
42
+
43
+ #
44
+ # The Apple and MS rasterizers behave differently for
45
+ # scaled composite components: one does scale first and then translate
46
+ # and the other does it vice versa. MS defined some flags to indicate
47
+ # the difference, but it seems nobody actually _sets_ those flags.
48
+ #
49
+ # Funny thing: Apple seems to _only_ do their thing in the
50
+ # WE_HAVE_A_SCALE (eg. Chicago) case, and not when it's WE_HAVE_AN_X_AND_Y_SCALE
51
+ # (eg. Charcoal)...
52
+ #
53
+ SCALE_COMPONENT_OFFSET_DEFAULT = 0 # 0 == MS, 1 == Apple
54
+
55
+
56
+ class table__g_l_y_f(DefaultTable.DefaultTable):
57
+ """Glyph Data Table
58
+
59
+ This class represents the `glyf <https://docs.microsoft.com/en-us/typography/opentype/spec/glyf>`_
60
+ table, which contains outlines for glyphs in TrueType format. In many cases,
61
+ it is easier to access and manipulate glyph outlines through the ``GlyphSet``
62
+ object returned from :py:meth:`fontTools.ttLib.ttFont.getGlyphSet`::
63
+
64
+ >> from fontTools.pens.boundsPen import BoundsPen
65
+ >> glyphset = font.getGlyphSet()
66
+ >> bp = BoundsPen(glyphset)
67
+ >> glyphset["A"].draw(bp)
68
+ >> bp.bounds
69
+ (19, 0, 633, 716)
70
+
71
+ However, this class can be used for low-level access to the ``glyf`` table data.
72
+ Objects of this class support dictionary-like access, mapping glyph names to
73
+ :py:class:`Glyph` objects::
74
+
75
+ >> glyf = font["glyf"]
76
+ >> len(glyf["Aacute"].components)
77
+ 2
78
+
79
+ Note that when adding glyphs to the font via low-level access to the ``glyf``
80
+ table, the new glyphs must also be added to the ``hmtx``/``vmtx`` table::
81
+
82
+ >> font["glyf"]["divisionslash"] = Glyph()
83
+ >> font["hmtx"]["divisionslash"] = (640, 0)
84
+
85
+ """
86
+
87
+ dependencies = ["fvar"]
88
+
89
+ # this attribute controls the amount of padding applied to glyph data upon compile.
90
+ # Glyph lenghts are aligned to multiples of the specified value.
91
+ # Allowed values are (0, 1, 2, 4). '0' means no padding; '1' (default) also means
92
+ # no padding, except for when padding would allow to use short loca offsets.
93
+ padding = 1
94
+
95
+ def decompile(self, data, ttFont):
96
+ self.axisTags = (
97
+ [axis.axisTag for axis in ttFont["fvar"].axes] if "fvar" in ttFont else []
98
+ )
99
+ loca = ttFont["loca"]
100
+ pos = int(loca[0])
101
+ nextPos = 0
102
+ noname = 0
103
+ self.glyphs = {}
104
+ self.glyphOrder = glyphOrder = ttFont.getGlyphOrder()
105
+ self._reverseGlyphOrder = {}
106
+ for i in range(0, len(loca) - 1):
107
+ try:
108
+ glyphName = glyphOrder[i]
109
+ except IndexError:
110
+ noname = noname + 1
111
+ glyphName = "ttxautoglyph%s" % i
112
+ nextPos = int(loca[i + 1])
113
+ glyphdata = data[pos:nextPos]
114
+ if len(glyphdata) != (nextPos - pos):
115
+ raise ttLib.TTLibError("not enough 'glyf' table data")
116
+ glyph = Glyph(glyphdata)
117
+ self.glyphs[glyphName] = glyph
118
+ pos = nextPos
119
+ if len(data) - nextPos >= 4:
120
+ log.warning(
121
+ "too much 'glyf' table data: expected %d, received %d bytes",
122
+ nextPos,
123
+ len(data),
124
+ )
125
+ if noname:
126
+ log.warning("%s glyphs have no name", noname)
127
+ if ttFont.lazy is False: # Be lazy for None and True
128
+ self.ensureDecompiled()
129
+
130
+ def ensureDecompiled(self, recurse=False):
131
+ # The recurse argument is unused, but part of the signature of
132
+ # ensureDecompiled across the library.
133
+ for glyph in self.glyphs.values():
134
+ glyph.expand(self)
135
+
136
+ def compile(self, ttFont):
137
+ self.axisTags = (
138
+ [axis.axisTag for axis in ttFont["fvar"].axes] if "fvar" in ttFont else []
139
+ )
140
+ if not hasattr(self, "glyphOrder"):
141
+ self.glyphOrder = ttFont.getGlyphOrder()
142
+ padding = self.padding
143
+ assert padding in (0, 1, 2, 4)
144
+ locations = []
145
+ currentLocation = 0
146
+ dataList = []
147
+ recalcBBoxes = ttFont.recalcBBoxes
148
+ boundsDone = set()
149
+ for glyphName in self.glyphOrder:
150
+ glyph = self.glyphs[glyphName]
151
+ glyphData = glyph.compile(self, recalcBBoxes, boundsDone=boundsDone)
152
+ if padding > 1:
153
+ glyphData = pad(glyphData, size=padding)
154
+ locations.append(currentLocation)
155
+ currentLocation = currentLocation + len(glyphData)
156
+ dataList.append(glyphData)
157
+ locations.append(currentLocation)
158
+
159
+ if padding == 1 and currentLocation < 0x20000:
160
+ # See if we can pad any odd-lengthed glyphs to allow loca
161
+ # table to use the short offsets.
162
+ indices = [
163
+ i for i, glyphData in enumerate(dataList) if len(glyphData) % 2 == 1
164
+ ]
165
+ if indices and currentLocation + len(indices) < 0x20000:
166
+ # It fits. Do it.
167
+ for i in indices:
168
+ dataList[i] += b"\0"
169
+ currentLocation = 0
170
+ for i, glyphData in enumerate(dataList):
171
+ locations[i] = currentLocation
172
+ currentLocation += len(glyphData)
173
+ locations[len(dataList)] = currentLocation
174
+
175
+ data = b"".join(dataList)
176
+ if "loca" in ttFont:
177
+ ttFont["loca"].set(locations)
178
+ if "maxp" in ttFont:
179
+ ttFont["maxp"].numGlyphs = len(self.glyphs)
180
+ if not data:
181
+ # As a special case when all glyph in the font are empty, add a zero byte
182
+ # to the table, so that OTS doesn’t reject it, and to make the table work
183
+ # on Windows as well.
184
+ # See https://github.com/khaledhosny/ots/issues/52
185
+ data = b"\0"
186
+ return data
187
+
188
+ def toXML(self, writer, ttFont, splitGlyphs=False):
189
+ notice = (
190
+ "The xMin, yMin, xMax and yMax values\n"
191
+ "will be recalculated by the compiler."
192
+ )
193
+ glyphNames = ttFont.getGlyphNames()
194
+ if not splitGlyphs:
195
+ writer.newline()
196
+ writer.comment(notice)
197
+ writer.newline()
198
+ writer.newline()
199
+ numGlyphs = len(glyphNames)
200
+ if splitGlyphs:
201
+ path, ext = os.path.splitext(writer.file.name)
202
+ existingGlyphFiles = set()
203
+ for glyphName in glyphNames:
204
+ glyph = self.get(glyphName)
205
+ if glyph is None:
206
+ log.warning("glyph '%s' does not exist in glyf table", glyphName)
207
+ continue
208
+ if glyph.numberOfContours:
209
+ if splitGlyphs:
210
+ glyphPath = userNameToFileName(
211
+ tostr(glyphName, "utf-8"),
212
+ existingGlyphFiles,
213
+ prefix=path + ".",
214
+ suffix=ext,
215
+ )
216
+ existingGlyphFiles.add(glyphPath.lower())
217
+ glyphWriter = xmlWriter.XMLWriter(
218
+ glyphPath,
219
+ idlefunc=writer.idlefunc,
220
+ newlinestr=writer.newlinestr,
221
+ )
222
+ glyphWriter.begintag("ttFont", ttLibVersion=version)
223
+ glyphWriter.newline()
224
+ glyphWriter.begintag("glyf")
225
+ glyphWriter.newline()
226
+ glyphWriter.comment(notice)
227
+ glyphWriter.newline()
228
+ writer.simpletag("TTGlyph", src=os.path.basename(glyphPath))
229
+ else:
230
+ glyphWriter = writer
231
+ glyphWriter.begintag(
232
+ "TTGlyph",
233
+ [
234
+ ("name", glyphName),
235
+ ("xMin", glyph.xMin),
236
+ ("yMin", glyph.yMin),
237
+ ("xMax", glyph.xMax),
238
+ ("yMax", glyph.yMax),
239
+ ],
240
+ )
241
+ glyphWriter.newline()
242
+ glyph.toXML(glyphWriter, ttFont)
243
+ glyphWriter.endtag("TTGlyph")
244
+ glyphWriter.newline()
245
+ if splitGlyphs:
246
+ glyphWriter.endtag("glyf")
247
+ glyphWriter.newline()
248
+ glyphWriter.endtag("ttFont")
249
+ glyphWriter.newline()
250
+ glyphWriter.close()
251
+ else:
252
+ writer.simpletag("TTGlyph", name=glyphName)
253
+ writer.comment("contains no outline data")
254
+ if not splitGlyphs:
255
+ writer.newline()
256
+ writer.newline()
257
+
258
+ def fromXML(self, name, attrs, content, ttFont):
259
+ if name != "TTGlyph":
260
+ return
261
+ if not hasattr(self, "glyphs"):
262
+ self.glyphs = {}
263
+ if not hasattr(self, "glyphOrder"):
264
+ self.glyphOrder = ttFont.getGlyphOrder()
265
+ glyphName = attrs["name"]
266
+ log.debug("unpacking glyph '%s'", glyphName)
267
+ glyph = Glyph()
268
+ for attr in ["xMin", "yMin", "xMax", "yMax"]:
269
+ setattr(glyph, attr, safeEval(attrs.get(attr, "0")))
270
+ self.glyphs[glyphName] = glyph
271
+ for element in content:
272
+ if not isinstance(element, tuple):
273
+ continue
274
+ name, attrs, content = element
275
+ glyph.fromXML(name, attrs, content, ttFont)
276
+ if not ttFont.recalcBBoxes:
277
+ glyph.compact(self, 0)
278
+
279
+ def setGlyphOrder(self, glyphOrder):
280
+ """Sets the glyph order
281
+
282
+ Args:
283
+ glyphOrder ([str]): List of glyph names in order.
284
+ """
285
+ self.glyphOrder = glyphOrder
286
+ self._reverseGlyphOrder = {}
287
+
288
+ def getGlyphName(self, glyphID):
289
+ """Returns the name for the glyph with the given ID.
290
+
291
+ Raises a ``KeyError`` if the glyph name is not found in the font.
292
+ """
293
+ return self.glyphOrder[glyphID]
294
+
295
+ def _buildReverseGlyphOrderDict(self):
296
+ self._reverseGlyphOrder = d = {}
297
+ for glyphID, glyphName in enumerate(self.glyphOrder):
298
+ d[glyphName] = glyphID
299
+
300
+ def getGlyphID(self, glyphName):
301
+ """Returns the ID of the glyph with the given name.
302
+
303
+ Raises a ``ValueError`` if the glyph is not found in the font.
304
+ """
305
+ glyphOrder = self.glyphOrder
306
+ id = getattr(self, "_reverseGlyphOrder", {}).get(glyphName)
307
+ if id is None or id >= len(glyphOrder) or glyphOrder[id] != glyphName:
308
+ self._buildReverseGlyphOrderDict()
309
+ id = self._reverseGlyphOrder.get(glyphName)
310
+ if id is None:
311
+ raise ValueError(glyphName)
312
+ return id
313
+
314
+ def removeHinting(self):
315
+ """Removes TrueType hints from all glyphs in the glyphset.
316
+
317
+ See :py:meth:`Glyph.removeHinting`.
318
+ """
319
+ for glyph in self.glyphs.values():
320
+ glyph.removeHinting()
321
+
322
+ def keys(self):
323
+ return self.glyphs.keys()
324
+
325
+ def has_key(self, glyphName):
326
+ return glyphName in self.glyphs
327
+
328
+ __contains__ = has_key
329
+
330
+ def get(self, glyphName, default=None):
331
+ glyph = self.glyphs.get(glyphName, default)
332
+ if glyph is not None:
333
+ glyph.expand(self)
334
+ return glyph
335
+
336
+ def __getitem__(self, glyphName):
337
+ glyph = self.glyphs[glyphName]
338
+ glyph.expand(self)
339
+ return glyph
340
+
341
+ def __setitem__(self, glyphName, glyph):
342
+ self.glyphs[glyphName] = glyph
343
+ if glyphName not in self.glyphOrder:
344
+ self.glyphOrder.append(glyphName)
345
+
346
+ def __delitem__(self, glyphName):
347
+ del self.glyphs[glyphName]
348
+ self.glyphOrder.remove(glyphName)
349
+
350
+ def __len__(self):
351
+ assert len(self.glyphOrder) == len(self.glyphs)
352
+ return len(self.glyphs)
353
+
354
+ def _getPhantomPoints(self, glyphName, hMetrics, vMetrics=None):
355
+ """Compute the four "phantom points" for the given glyph from its bounding box
356
+ and the horizontal and vertical advance widths and sidebearings stored in the
357
+ ttFont's "hmtx" and "vmtx" tables.
358
+
359
+ 'hMetrics' should be ttFont['hmtx'].metrics.
360
+
361
+ 'vMetrics' should be ttFont['vmtx'].metrics if there is "vmtx" or None otherwise.
362
+ If there is no vMetrics passed in, vertical phantom points are set to the zero coordinate.
363
+
364
+ https://docs.microsoft.com/en-us/typography/opentype/spec/tt_instructing_glyphs#phantoms
365
+ """
366
+ glyph = self[glyphName]
367
+ if not hasattr(glyph, "xMin"):
368
+ glyph.recalcBounds(self)
369
+
370
+ horizontalAdvanceWidth, leftSideBearing = hMetrics[glyphName]
371
+ leftSideX = glyph.xMin - leftSideBearing
372
+ rightSideX = leftSideX + horizontalAdvanceWidth
373
+
374
+ if vMetrics:
375
+ verticalAdvanceWidth, topSideBearing = vMetrics[glyphName]
376
+ topSideY = topSideBearing + glyph.yMax
377
+ bottomSideY = topSideY - verticalAdvanceWidth
378
+ else:
379
+ bottomSideY = topSideY = 0
380
+
381
+ return [
382
+ (leftSideX, 0),
383
+ (rightSideX, 0),
384
+ (0, topSideY),
385
+ (0, bottomSideY),
386
+ ]
387
+
388
+ def _getCoordinatesAndControls(
389
+ self, glyphName, hMetrics, vMetrics=None, *, round=otRound
390
+ ):
391
+ """Return glyph coordinates and controls as expected by "gvar" table.
392
+
393
+ The coordinates includes four "phantom points" for the glyph metrics,
394
+ as mandated by the "gvar" spec.
395
+
396
+ The glyph controls is a namedtuple with the following attributes:
397
+ - numberOfContours: -1 for composite glyphs.
398
+ - endPts: list of indices of end points for each contour in simple
399
+ glyphs, or component indices in composite glyphs (used for IUP
400
+ optimization).
401
+ - flags: array of contour point flags for simple glyphs (None for
402
+ composite glyphs).
403
+ - components: list of base glyph names (str) for each component in
404
+ composite glyphs (None for simple glyphs).
405
+
406
+ The "hMetrics" and vMetrics are used to compute the "phantom points" (see
407
+ the "_getPhantomPoints" method).
408
+
409
+ Return None if the requested glyphName is not present.
410
+ """
411
+ glyph = self.get(glyphName)
412
+ if glyph is None:
413
+ return None
414
+ if glyph.isComposite():
415
+ coords = GlyphCoordinates(
416
+ [(getattr(c, "x", 0), getattr(c, "y", 0)) for c in glyph.components]
417
+ )
418
+ controls = _GlyphControls(
419
+ numberOfContours=glyph.numberOfContours,
420
+ endPts=list(range(len(glyph.components))),
421
+ flags=None,
422
+ components=[
423
+ (c.glyphName, getattr(c, "transform", None))
424
+ for c in glyph.components
425
+ ],
426
+ )
427
+ else:
428
+ coords, endPts, flags = glyph.getCoordinates(self)
429
+ coords = coords.copy()
430
+ controls = _GlyphControls(
431
+ numberOfContours=glyph.numberOfContours,
432
+ endPts=endPts,
433
+ flags=flags,
434
+ components=None,
435
+ )
436
+ # Add phantom points for (left, right, top, bottom) positions.
437
+ phantomPoints = self._getPhantomPoints(glyphName, hMetrics, vMetrics)
438
+ coords.extend(phantomPoints)
439
+ coords.toInt(round=round)
440
+ return coords, controls
441
+
442
+ def _setCoordinates(self, glyphName, coord, hMetrics, vMetrics=None):
443
+ """Set coordinates and metrics for the given glyph.
444
+
445
+ "coord" is an array of GlyphCoordinates which must include the "phantom
446
+ points" as the last four coordinates.
447
+
448
+ Both the horizontal/vertical advances and left/top sidebearings in "hmtx"
449
+ and "vmtx" tables (if any) are updated from four phantom points and
450
+ the glyph's bounding boxes.
451
+
452
+ The "hMetrics" and vMetrics are used to propagate "phantom points"
453
+ into "hmtx" and "vmtx" tables if desired. (see the "_getPhantomPoints"
454
+ method).
455
+ """
456
+ glyph = self[glyphName]
457
+
458
+ # Handle phantom points for (left, right, top, bottom) positions.
459
+ assert len(coord) >= 4
460
+ leftSideX = coord[-4][0]
461
+ rightSideX = coord[-3][0]
462
+ topSideY = coord[-2][1]
463
+ bottomSideY = coord[-1][1]
464
+
465
+ coord = coord[:-4]
466
+
467
+ if glyph.isComposite():
468
+ assert len(coord) == len(glyph.components)
469
+ for p, comp in zip(coord, glyph.components):
470
+ if hasattr(comp, "x"):
471
+ comp.x, comp.y = p
472
+ elif glyph.numberOfContours == 0:
473
+ assert len(coord) == 0
474
+ else:
475
+ assert len(coord) == len(glyph.coordinates)
476
+ glyph.coordinates = GlyphCoordinates(coord)
477
+
478
+ glyph.recalcBounds(self, boundsDone=set())
479
+
480
+ horizontalAdvanceWidth = otRound(rightSideX - leftSideX)
481
+ if horizontalAdvanceWidth < 0:
482
+ # unlikely, but it can happen, see:
483
+ # https://github.com/fonttools/fonttools/pull/1198
484
+ horizontalAdvanceWidth = 0
485
+ leftSideBearing = otRound(glyph.xMin - leftSideX)
486
+ hMetrics[glyphName] = horizontalAdvanceWidth, leftSideBearing
487
+
488
+ if vMetrics is not None:
489
+ verticalAdvanceWidth = otRound(topSideY - bottomSideY)
490
+ if verticalAdvanceWidth < 0: # unlikely but do the same as horizontal
491
+ verticalAdvanceWidth = 0
492
+ topSideBearing = otRound(topSideY - glyph.yMax)
493
+ vMetrics[glyphName] = verticalAdvanceWidth, topSideBearing
494
+
495
+ # Deprecated
496
+
497
+ def _synthesizeVMetrics(self, glyphName, ttFont, defaultVerticalOrigin):
498
+ """This method is wrong and deprecated.
499
+ For rationale see:
500
+ https://github.com/fonttools/fonttools/pull/2266/files#r613569473
501
+ """
502
+ vMetrics = getattr(ttFont.get("vmtx"), "metrics", None)
503
+ if vMetrics is None:
504
+ verticalAdvanceWidth = ttFont["head"].unitsPerEm
505
+ topSideY = getattr(ttFont.get("hhea"), "ascent", None)
506
+ if topSideY is None:
507
+ if defaultVerticalOrigin is not None:
508
+ topSideY = defaultVerticalOrigin
509
+ else:
510
+ topSideY = verticalAdvanceWidth
511
+ glyph = self[glyphName]
512
+ glyph.recalcBounds(self)
513
+ topSideBearing = otRound(topSideY - glyph.yMax)
514
+ vMetrics = {glyphName: (verticalAdvanceWidth, topSideBearing)}
515
+ return vMetrics
516
+
517
+ @deprecateFunction("use '_getPhantomPoints' instead", category=DeprecationWarning)
518
+ def getPhantomPoints(self, glyphName, ttFont, defaultVerticalOrigin=None):
519
+ """Old public name for self._getPhantomPoints().
520
+ See: https://github.com/fonttools/fonttools/pull/2266"""
521
+ hMetrics = ttFont["hmtx"].metrics
522
+ vMetrics = self._synthesizeVMetrics(glyphName, ttFont, defaultVerticalOrigin)
523
+ return self._getPhantomPoints(glyphName, hMetrics, vMetrics)
524
+
525
+ @deprecateFunction(
526
+ "use '_getCoordinatesAndControls' instead", category=DeprecationWarning
527
+ )
528
+ def getCoordinatesAndControls(self, glyphName, ttFont, defaultVerticalOrigin=None):
529
+ """Old public name for self._getCoordinatesAndControls().
530
+ See: https://github.com/fonttools/fonttools/pull/2266"""
531
+ hMetrics = ttFont["hmtx"].metrics
532
+ vMetrics = self._synthesizeVMetrics(glyphName, ttFont, defaultVerticalOrigin)
533
+ return self._getCoordinatesAndControls(glyphName, hMetrics, vMetrics)
534
+
535
+ @deprecateFunction("use '_setCoordinates' instead", category=DeprecationWarning)
536
+ def setCoordinates(self, glyphName, ttFont):
537
+ """Old public name for self._setCoordinates().
538
+ See: https://github.com/fonttools/fonttools/pull/2266"""
539
+ hMetrics = ttFont["hmtx"].metrics
540
+ vMetrics = getattr(ttFont.get("vmtx"), "metrics", None)
541
+ self._setCoordinates(glyphName, hMetrics, vMetrics)
542
+
543
+
544
+ _GlyphControls = namedtuple(
545
+ "_GlyphControls", "numberOfContours endPts flags components"
546
+ )
547
+
548
+
549
+ glyphHeaderFormat = """
550
+ > # big endian
551
+ numberOfContours: h
552
+ xMin: h
553
+ yMin: h
554
+ xMax: h
555
+ yMax: h
556
+ """
557
+
558
+ # flags
559
+ flagOnCurve = 0x01
560
+ flagXShort = 0x02
561
+ flagYShort = 0x04
562
+ flagRepeat = 0x08
563
+ flagXsame = 0x10
564
+ flagYsame = 0x20
565
+ flagOverlapSimple = 0x40
566
+ flagCubic = 0x80
567
+
568
+ # These flags are kept for XML output after decompiling the coordinates
569
+ keepFlags = flagOnCurve + flagOverlapSimple + flagCubic
570
+
571
+ _flagSignBytes = {
572
+ 0: 2,
573
+ flagXsame: 0,
574
+ flagXShort | flagXsame: +1,
575
+ flagXShort: -1,
576
+ flagYsame: 0,
577
+ flagYShort | flagYsame: +1,
578
+ flagYShort: -1,
579
+ }
580
+
581
+
582
+ def flagBest(x, y, onCurve):
583
+ """For a given x,y delta pair, returns the flag that packs this pair
584
+ most efficiently, as well as the number of byte cost of such flag."""
585
+
586
+ flag = flagOnCurve if onCurve else 0
587
+ cost = 0
588
+ # do x
589
+ if x == 0:
590
+ flag = flag | flagXsame
591
+ elif -255 <= x <= 255:
592
+ flag = flag | flagXShort
593
+ if x > 0:
594
+ flag = flag | flagXsame
595
+ cost += 1
596
+ else:
597
+ cost += 2
598
+ # do y
599
+ if y == 0:
600
+ flag = flag | flagYsame
601
+ elif -255 <= y <= 255:
602
+ flag = flag | flagYShort
603
+ if y > 0:
604
+ flag = flag | flagYsame
605
+ cost += 1
606
+ else:
607
+ cost += 2
608
+ return flag, cost
609
+
610
+
611
+ def flagFits(newFlag, oldFlag, mask):
612
+ newBytes = _flagSignBytes[newFlag & mask]
613
+ oldBytes = _flagSignBytes[oldFlag & mask]
614
+ return newBytes == oldBytes or abs(newBytes) > abs(oldBytes)
615
+
616
+
617
+ def flagSupports(newFlag, oldFlag):
618
+ return (
619
+ (oldFlag & flagOnCurve) == (newFlag & flagOnCurve)
620
+ and flagFits(newFlag, oldFlag, flagXsame | flagXShort)
621
+ and flagFits(newFlag, oldFlag, flagYsame | flagYShort)
622
+ )
623
+
624
+
625
+ def flagEncodeCoord(flag, mask, coord, coordBytes):
626
+ byteCount = _flagSignBytes[flag & mask]
627
+ if byteCount == 1:
628
+ coordBytes.append(coord)
629
+ elif byteCount == -1:
630
+ coordBytes.append(-coord)
631
+ elif byteCount == 2:
632
+ coordBytes.extend(struct.pack(">h", coord))
633
+
634
+
635
+ def flagEncodeCoords(flag, x, y, xBytes, yBytes):
636
+ flagEncodeCoord(flag, flagXsame | flagXShort, x, xBytes)
637
+ flagEncodeCoord(flag, flagYsame | flagYShort, y, yBytes)
638
+
639
+
640
+ ARG_1_AND_2_ARE_WORDS = 0x0001 # if set args are words otherwise they are bytes
641
+ ARGS_ARE_XY_VALUES = 0x0002 # if set args are xy values, otherwise they are points
642
+ ROUND_XY_TO_GRID = 0x0004 # for the xy values if above is true
643
+ WE_HAVE_A_SCALE = 0x0008 # Sx = Sy, otherwise scale == 1.0
644
+ NON_OVERLAPPING = 0x0010 # set to same value for all components (obsolete!)
645
+ MORE_COMPONENTS = 0x0020 # indicates at least one more glyph after this one
646
+ WE_HAVE_AN_X_AND_Y_SCALE = 0x0040 # Sx, Sy
647
+ WE_HAVE_A_TWO_BY_TWO = 0x0080 # t00, t01, t10, t11
648
+ WE_HAVE_INSTRUCTIONS = 0x0100 # instructions follow
649
+ USE_MY_METRICS = 0x0200 # apply these metrics to parent glyph
650
+ OVERLAP_COMPOUND = 0x0400 # used by Apple in GX fonts
651
+ SCALED_COMPONENT_OFFSET = 0x0800 # composite designed to have the component offset scaled (designed for Apple)
652
+ UNSCALED_COMPONENT_OFFSET = 0x1000 # composite designed not to have the component offset scaled (designed for MS)
653
+
654
+
655
+ CompositeMaxpValues = namedtuple(
656
+ "CompositeMaxpValues", ["nPoints", "nContours", "maxComponentDepth"]
657
+ )
658
+
659
+
660
+ class Glyph(object):
661
+ """This class represents an individual TrueType glyph.
662
+
663
+ TrueType glyph objects come in two flavours: simple and composite. Simple
664
+ glyph objects contain contours, represented via the ``.coordinates``,
665
+ ``.flags``, ``.numberOfContours``, and ``.endPtsOfContours`` attributes;
666
+ composite glyphs contain components, available through the ``.components``
667
+ attributes.
668
+
669
+ Because the ``.coordinates`` attribute (and other simple glyph attributes mentioned
670
+ above) is only set on simple glyphs and the ``.components`` attribute is only
671
+ set on composite glyphs, it is necessary to use the :py:meth:`isComposite`
672
+ method to test whether a glyph is simple or composite before attempting to
673
+ access its data.
674
+
675
+ For a composite glyph, the components can also be accessed via array-like access::
676
+
677
+ >> assert(font["glyf"]["Aacute"].isComposite())
678
+ >> font["glyf"]["Aacute"][0]
679
+ <fontTools.ttLib.tables._g_l_y_f.GlyphComponent at 0x1027b2ee0>
680
+
681
+ """
682
+
683
+ def __init__(self, data=b""):
684
+ if not data:
685
+ # empty char
686
+ self.numberOfContours = 0
687
+ return
688
+ self.data = data
689
+
690
+ def compact(self, glyfTable, recalcBBoxes=True):
691
+ data = self.compile(glyfTable, recalcBBoxes)
692
+ self.__dict__.clear()
693
+ self.data = data
694
+
695
+ def expand(self, glyfTable):
696
+ if not hasattr(self, "data"):
697
+ # already unpacked
698
+ return
699
+ if not self.data:
700
+ # empty char
701
+ del self.data
702
+ self.numberOfContours = 0
703
+ return
704
+ dummy, data = sstruct.unpack2(glyphHeaderFormat, self.data, self)
705
+ del self.data
706
+ # Some fonts (eg. Neirizi.ttf) have a 0 for numberOfContours in
707
+ # some glyphs; decompileCoordinates assumes that there's at least
708
+ # one, so short-circuit here.
709
+ if self.numberOfContours == 0:
710
+ return
711
+ if self.isComposite():
712
+ self.decompileComponents(data, glyfTable)
713
+ else:
714
+ self.decompileCoordinates(data)
715
+
716
+ def compile(self, glyfTable, recalcBBoxes=True, *, boundsDone=None):
717
+ if hasattr(self, "data"):
718
+ if recalcBBoxes:
719
+ # must unpack glyph in order to recalculate bounding box
720
+ self.expand(glyfTable)
721
+ else:
722
+ return self.data
723
+ if self.numberOfContours == 0:
724
+ return b""
725
+
726
+ if recalcBBoxes:
727
+ self.recalcBounds(glyfTable, boundsDone=boundsDone)
728
+
729
+ data = sstruct.pack(glyphHeaderFormat, self)
730
+ if self.isComposite():
731
+ data = data + self.compileComponents(glyfTable)
732
+ else:
733
+ data = data + self.compileCoordinates()
734
+ return data
735
+
736
+ def toXML(self, writer, ttFont):
737
+ if self.isComposite():
738
+ for compo in self.components:
739
+ compo.toXML(writer, ttFont)
740
+ haveInstructions = hasattr(self, "program")
741
+ else:
742
+ last = 0
743
+ for i in range(self.numberOfContours):
744
+ writer.begintag("contour")
745
+ writer.newline()
746
+ for j in range(last, self.endPtsOfContours[i] + 1):
747
+ attrs = [
748
+ ("x", self.coordinates[j][0]),
749
+ ("y", self.coordinates[j][1]),
750
+ ("on", self.flags[j] & flagOnCurve),
751
+ ]
752
+ if self.flags[j] & flagOverlapSimple:
753
+ # Apple's rasterizer uses flagOverlapSimple in the first contour/first pt to flag glyphs that contain overlapping contours
754
+ attrs.append(("overlap", 1))
755
+ if self.flags[j] & flagCubic:
756
+ attrs.append(("cubic", 1))
757
+ writer.simpletag("pt", attrs)
758
+ writer.newline()
759
+ last = self.endPtsOfContours[i] + 1
760
+ writer.endtag("contour")
761
+ writer.newline()
762
+ haveInstructions = self.numberOfContours > 0
763
+ if haveInstructions:
764
+ if self.program:
765
+ writer.begintag("instructions")
766
+ writer.newline()
767
+ self.program.toXML(writer, ttFont)
768
+ writer.endtag("instructions")
769
+ else:
770
+ writer.simpletag("instructions")
771
+ writer.newline()
772
+
773
+ def fromXML(self, name, attrs, content, ttFont):
774
+ if name == "contour":
775
+ if self.numberOfContours < 0:
776
+ raise ttLib.TTLibError("can't mix composites and contours in glyph")
777
+ self.numberOfContours = self.numberOfContours + 1
778
+ coordinates = GlyphCoordinates()
779
+ flags = bytearray()
780
+ for element in content:
781
+ if not isinstance(element, tuple):
782
+ continue
783
+ name, attrs, content = element
784
+ if name != "pt":
785
+ continue # ignore anything but "pt"
786
+ coordinates.append((safeEval(attrs["x"]), safeEval(attrs["y"])))
787
+ flag = bool(safeEval(attrs["on"]))
788
+ if "overlap" in attrs and bool(safeEval(attrs["overlap"])):
789
+ flag |= flagOverlapSimple
790
+ if "cubic" in attrs and bool(safeEval(attrs["cubic"])):
791
+ flag |= flagCubic
792
+ flags.append(flag)
793
+ if not hasattr(self, "coordinates"):
794
+ self.coordinates = coordinates
795
+ self.flags = flags
796
+ self.endPtsOfContours = [len(coordinates) - 1]
797
+ else:
798
+ self.coordinates.extend(coordinates)
799
+ self.flags.extend(flags)
800
+ self.endPtsOfContours.append(len(self.coordinates) - 1)
801
+ elif name == "component":
802
+ if self.numberOfContours > 0:
803
+ raise ttLib.TTLibError("can't mix composites and contours in glyph")
804
+ self.numberOfContours = -1
805
+ if not hasattr(self, "components"):
806
+ self.components = []
807
+ component = GlyphComponent()
808
+ self.components.append(component)
809
+ component.fromXML(name, attrs, content, ttFont)
810
+ elif name == "instructions":
811
+ self.program = ttProgram.Program()
812
+ for element in content:
813
+ if not isinstance(element, tuple):
814
+ continue
815
+ name, attrs, content = element
816
+ self.program.fromXML(name, attrs, content, ttFont)
817
+
818
+ def getCompositeMaxpValues(self, glyfTable, maxComponentDepth=1):
819
+ assert self.isComposite()
820
+ nContours = 0
821
+ nPoints = 0
822
+ initialMaxComponentDepth = maxComponentDepth
823
+ for compo in self.components:
824
+ baseGlyph = glyfTable[compo.glyphName]
825
+ if baseGlyph.numberOfContours == 0:
826
+ continue
827
+ elif baseGlyph.numberOfContours > 0:
828
+ nP, nC = baseGlyph.getMaxpValues()
829
+ else:
830
+ nP, nC, componentDepth = baseGlyph.getCompositeMaxpValues(
831
+ glyfTable, initialMaxComponentDepth + 1
832
+ )
833
+ maxComponentDepth = max(maxComponentDepth, componentDepth)
834
+ nPoints = nPoints + nP
835
+ nContours = nContours + nC
836
+ return CompositeMaxpValues(nPoints, nContours, maxComponentDepth)
837
+
838
+ def getMaxpValues(self):
839
+ assert self.numberOfContours > 0
840
+ return len(self.coordinates), len(self.endPtsOfContours)
841
+
842
+ def decompileComponents(self, data, glyfTable):
843
+ self.components = []
844
+ more = 1
845
+ haveInstructions = 0
846
+ while more:
847
+ component = GlyphComponent()
848
+ more, haveInstr, data = component.decompile(data, glyfTable)
849
+ haveInstructions = haveInstructions | haveInstr
850
+ self.components.append(component)
851
+ if haveInstructions:
852
+ (numInstructions,) = struct.unpack(">h", data[:2])
853
+ data = data[2:]
854
+ self.program = ttProgram.Program()
855
+ self.program.fromBytecode(data[:numInstructions])
856
+ data = data[numInstructions:]
857
+ if len(data) >= 4:
858
+ log.warning(
859
+ "too much glyph data at the end of composite glyph: %d excess bytes",
860
+ len(data),
861
+ )
862
+
863
+ def decompileCoordinates(self, data):
864
+ endPtsOfContours = array.array("H")
865
+ endPtsOfContours.frombytes(data[: 2 * self.numberOfContours])
866
+ if sys.byteorder != "big":
867
+ endPtsOfContours.byteswap()
868
+ self.endPtsOfContours = endPtsOfContours.tolist()
869
+
870
+ pos = 2 * self.numberOfContours
871
+ (instructionLength,) = struct.unpack(">h", data[pos : pos + 2])
872
+ self.program = ttProgram.Program()
873
+ self.program.fromBytecode(data[pos + 2 : pos + 2 + instructionLength])
874
+ pos += 2 + instructionLength
875
+ nCoordinates = self.endPtsOfContours[-1] + 1
876
+ flags, xCoordinates, yCoordinates = self.decompileCoordinatesRaw(
877
+ nCoordinates, data, pos
878
+ )
879
+
880
+ # fill in repetitions and apply signs
881
+ self.coordinates = coordinates = GlyphCoordinates.zeros(nCoordinates)
882
+ xIndex = 0
883
+ yIndex = 0
884
+ for i in range(nCoordinates):
885
+ flag = flags[i]
886
+ # x coordinate
887
+ if flag & flagXShort:
888
+ if flag & flagXsame:
889
+ x = xCoordinates[xIndex]
890
+ else:
891
+ x = -xCoordinates[xIndex]
892
+ xIndex = xIndex + 1
893
+ elif flag & flagXsame:
894
+ x = 0
895
+ else:
896
+ x = xCoordinates[xIndex]
897
+ xIndex = xIndex + 1
898
+ # y coordinate
899
+ if flag & flagYShort:
900
+ if flag & flagYsame:
901
+ y = yCoordinates[yIndex]
902
+ else:
903
+ y = -yCoordinates[yIndex]
904
+ yIndex = yIndex + 1
905
+ elif flag & flagYsame:
906
+ y = 0
907
+ else:
908
+ y = yCoordinates[yIndex]
909
+ yIndex = yIndex + 1
910
+ coordinates[i] = (x, y)
911
+ assert xIndex == len(xCoordinates)
912
+ assert yIndex == len(yCoordinates)
913
+ coordinates.relativeToAbsolute()
914
+ # discard all flags except "keepFlags"
915
+ for i in range(len(flags)):
916
+ flags[i] &= keepFlags
917
+ self.flags = flags
918
+
919
+ def decompileCoordinatesRaw(self, nCoordinates, data, pos=0):
920
+ # unpack flags and prepare unpacking of coordinates
921
+ flags = bytearray(nCoordinates)
922
+ # Warning: deep Python trickery going on. We use the struct module to unpack
923
+ # the coordinates. We build a format string based on the flags, so we can
924
+ # unpack the coordinates in one struct.unpack() call.
925
+ xFormat = ">" # big endian
926
+ yFormat = ">" # big endian
927
+ j = 0
928
+ while True:
929
+ flag = data[pos]
930
+ pos += 1
931
+ repeat = 1
932
+ if flag & flagRepeat:
933
+ repeat = data[pos] + 1
934
+ pos += 1
935
+ for k in range(repeat):
936
+ if flag & flagXShort:
937
+ xFormat = xFormat + "B"
938
+ elif not (flag & flagXsame):
939
+ xFormat = xFormat + "h"
940
+ if flag & flagYShort:
941
+ yFormat = yFormat + "B"
942
+ elif not (flag & flagYsame):
943
+ yFormat = yFormat + "h"
944
+ flags[j] = flag
945
+ j = j + 1
946
+ if j >= nCoordinates:
947
+ break
948
+ assert j == nCoordinates, "bad glyph flags"
949
+ # unpack raw coordinates, krrrrrr-tching!
950
+ xDataLen = struct.calcsize(xFormat)
951
+ yDataLen = struct.calcsize(yFormat)
952
+ if len(data) - pos - (xDataLen + yDataLen) >= 4:
953
+ log.warning(
954
+ "too much glyph data: %d excess bytes",
955
+ len(data) - pos - (xDataLen + yDataLen),
956
+ )
957
+ xCoordinates = struct.unpack(xFormat, data[pos : pos + xDataLen])
958
+ yCoordinates = struct.unpack(
959
+ yFormat, data[pos + xDataLen : pos + xDataLen + yDataLen]
960
+ )
961
+ return flags, xCoordinates, yCoordinates
962
+
963
+ def compileComponents(self, glyfTable):
964
+ data = b""
965
+ lastcomponent = len(self.components) - 1
966
+ more = 1
967
+ haveInstructions = 0
968
+ for i in range(len(self.components)):
969
+ if i == lastcomponent:
970
+ haveInstructions = hasattr(self, "program")
971
+ more = 0
972
+ compo = self.components[i]
973
+ data = data + compo.compile(more, haveInstructions, glyfTable)
974
+ if haveInstructions:
975
+ instructions = self.program.getBytecode()
976
+ data = data + struct.pack(">h", len(instructions)) + instructions
977
+ return data
978
+
979
+ def compileCoordinates(self):
980
+ assert len(self.coordinates) == len(self.flags)
981
+ data = []
982
+ endPtsOfContours = array.array("H", self.endPtsOfContours)
983
+ if sys.byteorder != "big":
984
+ endPtsOfContours.byteswap()
985
+ data.append(endPtsOfContours.tobytes())
986
+ instructions = self.program.getBytecode()
987
+ data.append(struct.pack(">h", len(instructions)))
988
+ data.append(instructions)
989
+
990
+ deltas = self.coordinates.copy()
991
+ deltas.toInt()
992
+ deltas.absoluteToRelative()
993
+
994
+ # TODO(behdad): Add a configuration option for this?
995
+ deltas = self.compileDeltasGreedy(self.flags, deltas)
996
+ # deltas = self.compileDeltasOptimal(self.flags, deltas)
997
+
998
+ data.extend(deltas)
999
+ return b"".join(data)
1000
+
1001
+ def compileDeltasGreedy(self, flags, deltas):
1002
+ # Implements greedy algorithm for packing coordinate deltas:
1003
+ # uses shortest representation one coordinate at a time.
1004
+ compressedFlags = bytearray()
1005
+ compressedXs = bytearray()
1006
+ compressedYs = bytearray()
1007
+ lastflag = None
1008
+ repeat = 0
1009
+ for flag, (x, y) in zip(flags, deltas):
1010
+ # Oh, the horrors of TrueType
1011
+ # do x
1012
+ if x == 0:
1013
+ flag = flag | flagXsame
1014
+ elif -255 <= x <= 255:
1015
+ flag = flag | flagXShort
1016
+ if x > 0:
1017
+ flag = flag | flagXsame
1018
+ else:
1019
+ x = -x
1020
+ compressedXs.append(x)
1021
+ else:
1022
+ compressedXs.extend(struct.pack(">h", x))
1023
+ # do y
1024
+ if y == 0:
1025
+ flag = flag | flagYsame
1026
+ elif -255 <= y <= 255:
1027
+ flag = flag | flagYShort
1028
+ if y > 0:
1029
+ flag = flag | flagYsame
1030
+ else:
1031
+ y = -y
1032
+ compressedYs.append(y)
1033
+ else:
1034
+ compressedYs.extend(struct.pack(">h", y))
1035
+ # handle repeating flags
1036
+ if flag == lastflag and repeat != 255:
1037
+ repeat = repeat + 1
1038
+ if repeat == 1:
1039
+ compressedFlags.append(flag)
1040
+ else:
1041
+ compressedFlags[-2] = flag | flagRepeat
1042
+ compressedFlags[-1] = repeat
1043
+ else:
1044
+ repeat = 0
1045
+ compressedFlags.append(flag)
1046
+ lastflag = flag
1047
+ return (compressedFlags, compressedXs, compressedYs)
1048
+
1049
+ def compileDeltasOptimal(self, flags, deltas):
1050
+ # Implements optimal, dynaic-programming, algorithm for packing coordinate
1051
+ # deltas. The savings are negligible :(.
1052
+ candidates = []
1053
+ bestTuple = None
1054
+ bestCost = 0
1055
+ repeat = 0
1056
+ for flag, (x, y) in zip(flags, deltas):
1057
+ # Oh, the horrors of TrueType
1058
+ flag, coordBytes = flagBest(x, y, flag)
1059
+ bestCost += 1 + coordBytes
1060
+ newCandidates = [
1061
+ (bestCost, bestTuple, flag, coordBytes),
1062
+ (bestCost + 1, bestTuple, (flag | flagRepeat), coordBytes),
1063
+ ]
1064
+ for lastCost, lastTuple, lastFlag, coordBytes in candidates:
1065
+ if (
1066
+ lastCost + coordBytes <= bestCost + 1
1067
+ and (lastFlag & flagRepeat)
1068
+ and (lastFlag < 0xFF00)
1069
+ and flagSupports(lastFlag, flag)
1070
+ ):
1071
+ if (lastFlag & 0xFF) == (
1072
+ flag | flagRepeat
1073
+ ) and lastCost == bestCost + 1:
1074
+ continue
1075
+ newCandidates.append(
1076
+ (lastCost + coordBytes, lastTuple, lastFlag + 256, coordBytes)
1077
+ )
1078
+ candidates = newCandidates
1079
+ bestTuple = min(candidates, key=lambda t: t[0])
1080
+ bestCost = bestTuple[0]
1081
+
1082
+ flags = []
1083
+ while bestTuple:
1084
+ cost, bestTuple, flag, coordBytes = bestTuple
1085
+ flags.append(flag)
1086
+ flags.reverse()
1087
+
1088
+ compressedFlags = bytearray()
1089
+ compressedXs = bytearray()
1090
+ compressedYs = bytearray()
1091
+ coords = iter(deltas)
1092
+ ff = []
1093
+ for flag in flags:
1094
+ repeatCount, flag = flag >> 8, flag & 0xFF
1095
+ compressedFlags.append(flag)
1096
+ if flag & flagRepeat:
1097
+ assert repeatCount > 0
1098
+ compressedFlags.append(repeatCount)
1099
+ else:
1100
+ assert repeatCount == 0
1101
+ for i in range(1 + repeatCount):
1102
+ x, y = next(coords)
1103
+ flagEncodeCoords(flag, x, y, compressedXs, compressedYs)
1104
+ ff.append(flag)
1105
+ try:
1106
+ next(coords)
1107
+ raise Exception("internal error")
1108
+ except StopIteration:
1109
+ pass
1110
+
1111
+ return (compressedFlags, compressedXs, compressedYs)
1112
+
1113
+ def recalcBounds(self, glyfTable, *, boundsDone=None):
1114
+ """Recalculates the bounds of the glyph.
1115
+
1116
+ Each glyph object stores its bounding box in the
1117
+ ``xMin``/``yMin``/``xMax``/``yMax`` attributes. These bounds must be
1118
+ recomputed when the ``coordinates`` change. The ``table__g_l_y_f`` bounds
1119
+ must be provided to resolve component bounds.
1120
+ """
1121
+ if self.isComposite() and self.tryRecalcBoundsComposite(
1122
+ glyfTable, boundsDone=boundsDone
1123
+ ):
1124
+ return
1125
+ try:
1126
+ coords, endPts, flags = self.getCoordinates(glyfTable)
1127
+ self.xMin, self.yMin, self.xMax, self.yMax = coords.calcIntBounds()
1128
+ except NotImplementedError:
1129
+ pass
1130
+
1131
+ def tryRecalcBoundsComposite(self, glyfTable, *, boundsDone=None):
1132
+ """Try recalculating the bounds of a composite glyph that has
1133
+ certain constrained properties. Namely, none of the components
1134
+ have a transform other than an integer translate, and none
1135
+ uses the anchor points.
1136
+
1137
+ Each glyph object stores its bounding box in the
1138
+ ``xMin``/``yMin``/``xMax``/``yMax`` attributes. These bounds must be
1139
+ recomputed when the ``coordinates`` change. The ``table__g_l_y_f`` bounds
1140
+ must be provided to resolve component bounds.
1141
+
1142
+ Return True if bounds were calculated, False otherwise.
1143
+ """
1144
+ for compo in self.components:
1145
+ if hasattr(compo, "firstPt") or hasattr(compo, "transform"):
1146
+ return False
1147
+ if not float(compo.x).is_integer() or not float(compo.y).is_integer():
1148
+ return False
1149
+
1150
+ # All components are untransformed and have an integer x/y translate
1151
+ bounds = None
1152
+ for compo in self.components:
1153
+ glyphName = compo.glyphName
1154
+ g = glyfTable[glyphName]
1155
+
1156
+ if boundsDone is None or glyphName not in boundsDone:
1157
+ g.recalcBounds(glyfTable, boundsDone=boundsDone)
1158
+ if boundsDone is not None:
1159
+ boundsDone.add(glyphName)
1160
+ # empty components shouldn't update the bounds of the parent glyph
1161
+ if g.numberOfContours == 0:
1162
+ continue
1163
+
1164
+ x, y = compo.x, compo.y
1165
+ bounds = updateBounds(bounds, (g.xMin + x, g.yMin + y))
1166
+ bounds = updateBounds(bounds, (g.xMax + x, g.yMax + y))
1167
+
1168
+ if bounds is None:
1169
+ bounds = (0, 0, 0, 0)
1170
+ self.xMin, self.yMin, self.xMax, self.yMax = bounds
1171
+ return True
1172
+
1173
+ def isComposite(self):
1174
+ """Test whether a glyph has components"""
1175
+ if hasattr(self, "data"):
1176
+ return struct.unpack(">h", self.data[:2])[0] == -1 if self.data else False
1177
+ else:
1178
+ return self.numberOfContours == -1
1179
+
1180
+ def getCoordinates(self, glyfTable):
1181
+ """Return the coordinates, end points and flags
1182
+
1183
+ This method returns three values: A :py:class:`GlyphCoordinates` object,
1184
+ a list of the indexes of the final points of each contour (allowing you
1185
+ to split up the coordinates list into contours) and a list of flags.
1186
+
1187
+ On simple glyphs, this method returns information from the glyph's own
1188
+ contours; on composite glyphs, it "flattens" all components recursively
1189
+ to return a list of coordinates representing all the components involved
1190
+ in the glyph.
1191
+
1192
+ To interpret the flags for each point, see the "Simple Glyph Flags"
1193
+ section of the `glyf table specification <https://docs.microsoft.com/en-us/typography/opentype/spec/glyf#simple-glyph-description>`.
1194
+ """
1195
+
1196
+ if self.numberOfContours > 0:
1197
+ return self.coordinates, self.endPtsOfContours, self.flags
1198
+ elif self.isComposite():
1199
+ # it's a composite
1200
+ allCoords = GlyphCoordinates()
1201
+ allFlags = bytearray()
1202
+ allEndPts = []
1203
+ for compo in self.components:
1204
+ g = glyfTable[compo.glyphName]
1205
+ try:
1206
+ coordinates, endPts, flags = g.getCoordinates(glyfTable)
1207
+ except RecursionError:
1208
+ raise ttLib.TTLibError(
1209
+ "glyph '%s' contains a recursive component reference"
1210
+ % compo.glyphName
1211
+ )
1212
+ coordinates = GlyphCoordinates(coordinates)
1213
+ if hasattr(compo, "firstPt"):
1214
+ # component uses two reference points: we apply the transform _before_
1215
+ # computing the offset between the points
1216
+ if hasattr(compo, "transform"):
1217
+ coordinates.transform(compo.transform)
1218
+ x1, y1 = allCoords[compo.firstPt]
1219
+ x2, y2 = coordinates[compo.secondPt]
1220
+ move = x1 - x2, y1 - y2
1221
+ coordinates.translate(move)
1222
+ else:
1223
+ # component uses XY offsets
1224
+ move = compo.x, compo.y
1225
+ if not hasattr(compo, "transform"):
1226
+ coordinates.translate(move)
1227
+ else:
1228
+ apple_way = compo.flags & SCALED_COMPONENT_OFFSET
1229
+ ms_way = compo.flags & UNSCALED_COMPONENT_OFFSET
1230
+ assert not (apple_way and ms_way)
1231
+ if not (apple_way or ms_way):
1232
+ scale_component_offset = (
1233
+ SCALE_COMPONENT_OFFSET_DEFAULT # see top of this file
1234
+ )
1235
+ else:
1236
+ scale_component_offset = apple_way
1237
+ if scale_component_offset:
1238
+ # the Apple way: first move, then scale (ie. scale the component offset)
1239
+ coordinates.translate(move)
1240
+ coordinates.transform(compo.transform)
1241
+ else:
1242
+ # the MS way: first scale, then move
1243
+ coordinates.transform(compo.transform)
1244
+ coordinates.translate(move)
1245
+ offset = len(allCoords)
1246
+ allEndPts.extend(e + offset for e in endPts)
1247
+ allCoords.extend(coordinates)
1248
+ allFlags.extend(flags)
1249
+ return allCoords, allEndPts, allFlags
1250
+ else:
1251
+ return GlyphCoordinates(), [], bytearray()
1252
+
1253
+ def getComponentNames(self, glyfTable):
1254
+ """Returns a list of names of component glyphs used in this glyph
1255
+
1256
+ This method can be used on simple glyphs (in which case it returns an
1257
+ empty list) or composite glyphs.
1258
+ """
1259
+ if not hasattr(self, "data"):
1260
+ if self.isComposite():
1261
+ return [c.glyphName for c in self.components]
1262
+ else:
1263
+ return []
1264
+
1265
+ # Extract components without expanding glyph
1266
+
1267
+ if not self.data or struct.unpack(">h", self.data[:2])[0] >= 0:
1268
+ return [] # Not composite
1269
+
1270
+ data = self.data
1271
+ i = 10
1272
+ components = []
1273
+ more = 1
1274
+ while more:
1275
+ flags, glyphID = struct.unpack(">HH", data[i : i + 4])
1276
+ i += 4
1277
+ flags = int(flags)
1278
+ components.append(glyfTable.getGlyphName(int(glyphID)))
1279
+
1280
+ if flags & ARG_1_AND_2_ARE_WORDS:
1281
+ i += 4
1282
+ else:
1283
+ i += 2
1284
+ if flags & WE_HAVE_A_SCALE:
1285
+ i += 2
1286
+ elif flags & WE_HAVE_AN_X_AND_Y_SCALE:
1287
+ i += 4
1288
+ elif flags & WE_HAVE_A_TWO_BY_TWO:
1289
+ i += 8
1290
+ more = flags & MORE_COMPONENTS
1291
+
1292
+ return components
1293
+
1294
+ def trim(self, remove_hinting=False):
1295
+ """Remove padding and, if requested, hinting, from a glyph.
1296
+ This works on both expanded and compacted glyphs, without
1297
+ expanding it."""
1298
+ if not hasattr(self, "data"):
1299
+ if remove_hinting:
1300
+ if self.isComposite():
1301
+ if hasattr(self, "program"):
1302
+ del self.program
1303
+ else:
1304
+ self.program = ttProgram.Program()
1305
+ self.program.fromBytecode([])
1306
+ # No padding to trim.
1307
+ return
1308
+ if not self.data:
1309
+ return
1310
+ numContours = struct.unpack(">h", self.data[:2])[0]
1311
+ data = bytearray(self.data)
1312
+ i = 10
1313
+ if numContours >= 0:
1314
+ i += 2 * numContours # endPtsOfContours
1315
+ nCoordinates = ((data[i - 2] << 8) | data[i - 1]) + 1
1316
+ instructionLen = (data[i] << 8) | data[i + 1]
1317
+ if remove_hinting:
1318
+ # Zero instruction length
1319
+ data[i] = data[i + 1] = 0
1320
+ i += 2
1321
+ if instructionLen:
1322
+ # Splice it out
1323
+ data = data[:i] + data[i + instructionLen :]
1324
+ instructionLen = 0
1325
+ else:
1326
+ i += 2 + instructionLen
1327
+
1328
+ coordBytes = 0
1329
+ j = 0
1330
+ while True:
1331
+ flag = data[i]
1332
+ i = i + 1
1333
+ repeat = 1
1334
+ if flag & flagRepeat:
1335
+ repeat = data[i] + 1
1336
+ i = i + 1
1337
+ xBytes = yBytes = 0
1338
+ if flag & flagXShort:
1339
+ xBytes = 1
1340
+ elif not (flag & flagXsame):
1341
+ xBytes = 2
1342
+ if flag & flagYShort:
1343
+ yBytes = 1
1344
+ elif not (flag & flagYsame):
1345
+ yBytes = 2
1346
+ coordBytes += (xBytes + yBytes) * repeat
1347
+ j += repeat
1348
+ if j >= nCoordinates:
1349
+ break
1350
+ assert j == nCoordinates, "bad glyph flags"
1351
+ i += coordBytes
1352
+ # Remove padding
1353
+ data = data[:i]
1354
+ elif self.isComposite():
1355
+ more = 1
1356
+ we_have_instructions = False
1357
+ while more:
1358
+ flags = (data[i] << 8) | data[i + 1]
1359
+ if remove_hinting:
1360
+ flags &= ~WE_HAVE_INSTRUCTIONS
1361
+ if flags & WE_HAVE_INSTRUCTIONS:
1362
+ we_have_instructions = True
1363
+ data[i + 0] = flags >> 8
1364
+ data[i + 1] = flags & 0xFF
1365
+ i += 4
1366
+ flags = int(flags)
1367
+
1368
+ if flags & ARG_1_AND_2_ARE_WORDS:
1369
+ i += 4
1370
+ else:
1371
+ i += 2
1372
+ if flags & WE_HAVE_A_SCALE:
1373
+ i += 2
1374
+ elif flags & WE_HAVE_AN_X_AND_Y_SCALE:
1375
+ i += 4
1376
+ elif flags & WE_HAVE_A_TWO_BY_TWO:
1377
+ i += 8
1378
+ more = flags & MORE_COMPONENTS
1379
+ if we_have_instructions:
1380
+ instructionLen = (data[i] << 8) | data[i + 1]
1381
+ i += 2 + instructionLen
1382
+ # Remove padding
1383
+ data = data[:i]
1384
+
1385
+ self.data = data
1386
+
1387
+ def removeHinting(self):
1388
+ """Removes TrueType hinting instructions from the glyph."""
1389
+ self.trim(remove_hinting=True)
1390
+
1391
+ def draw(self, pen, glyfTable, offset=0):
1392
+ """Draws the glyph using the supplied pen object.
1393
+
1394
+ Arguments:
1395
+ pen: An object conforming to the pen protocol.
1396
+ glyfTable: A :py:class:`table__g_l_y_f` object, to resolve components.
1397
+ offset (int): A horizontal offset. If provided, all coordinates are
1398
+ translated by this offset.
1399
+ """
1400
+
1401
+ if self.isComposite():
1402
+ for component in self.components:
1403
+ glyphName, transform = component.getComponentInfo()
1404
+ pen.addComponent(glyphName, transform)
1405
+ return
1406
+
1407
+ coordinates, endPts, flags = self.getCoordinates(glyfTable)
1408
+ if offset:
1409
+ coordinates = coordinates.copy()
1410
+ coordinates.translate((offset, 0))
1411
+ start = 0
1412
+ maybeInt = lambda v: int(v) if v == int(v) else v
1413
+ for end in endPts:
1414
+ end = end + 1
1415
+ contour = coordinates[start:end]
1416
+ cFlags = [flagOnCurve & f for f in flags[start:end]]
1417
+ cuFlags = [flagCubic & f for f in flags[start:end]]
1418
+ start = end
1419
+ if 1 not in cFlags:
1420
+ assert all(cuFlags) or not any(cuFlags)
1421
+ cubic = all(cuFlags)
1422
+ if cubic:
1423
+ count = len(contour)
1424
+ assert count % 2 == 0, "Odd number of cubic off-curves undefined"
1425
+ l = contour[-1]
1426
+ f = contour[0]
1427
+ p0 = (maybeInt((l[0] + f[0]) * 0.5), maybeInt((l[1] + f[1]) * 0.5))
1428
+ pen.moveTo(p0)
1429
+ for i in range(0, count, 2):
1430
+ p1 = contour[i]
1431
+ p2 = contour[i + 1]
1432
+ p4 = contour[i + 2 if i + 2 < count else 0]
1433
+ p3 = (
1434
+ maybeInt((p2[0] + p4[0]) * 0.5),
1435
+ maybeInt((p2[1] + p4[1]) * 0.5),
1436
+ )
1437
+ pen.curveTo(p1, p2, p3)
1438
+ else:
1439
+ # There is not a single on-curve point on the curve,
1440
+ # use pen.qCurveTo's special case by specifying None
1441
+ # as the on-curve point.
1442
+ contour.append(None)
1443
+ pen.qCurveTo(*contour)
1444
+ else:
1445
+ # Shuffle the points so that the contour is guaranteed
1446
+ # to *end* in an on-curve point, which we'll use for
1447
+ # the moveTo.
1448
+ firstOnCurve = cFlags.index(1) + 1
1449
+ contour = contour[firstOnCurve:] + contour[:firstOnCurve]
1450
+ cFlags = cFlags[firstOnCurve:] + cFlags[:firstOnCurve]
1451
+ cuFlags = cuFlags[firstOnCurve:] + cuFlags[:firstOnCurve]
1452
+ pen.moveTo(contour[-1])
1453
+ while contour:
1454
+ nextOnCurve = cFlags.index(1) + 1
1455
+ if nextOnCurve == 1:
1456
+ # Skip a final lineTo(), as it is implied by
1457
+ # pen.closePath()
1458
+ if len(contour) > 1:
1459
+ pen.lineTo(contour[0])
1460
+ else:
1461
+ cubicFlags = [f for f in cuFlags[: nextOnCurve - 1]]
1462
+ assert all(cubicFlags) or not any(cubicFlags)
1463
+ cubic = any(cubicFlags)
1464
+ if cubic:
1465
+ assert all(
1466
+ cubicFlags
1467
+ ), "Mixed cubic and quadratic segment undefined"
1468
+
1469
+ count = nextOnCurve
1470
+ assert (
1471
+ count >= 3
1472
+ ), "At least two cubic off-curve points required"
1473
+ assert (
1474
+ count - 1
1475
+ ) % 2 == 0, "Odd number of cubic off-curves undefined"
1476
+ for i in range(0, count - 3, 2):
1477
+ p1 = contour[i]
1478
+ p2 = contour[i + 1]
1479
+ p4 = contour[i + 2]
1480
+ p3 = (
1481
+ maybeInt((p2[0] + p4[0]) * 0.5),
1482
+ maybeInt((p2[1] + p4[1]) * 0.5),
1483
+ )
1484
+ lastOnCurve = p3
1485
+ pen.curveTo(p1, p2, p3)
1486
+ pen.curveTo(*contour[count - 3 : count])
1487
+ else:
1488
+ pen.qCurveTo(*contour[:nextOnCurve])
1489
+ contour = contour[nextOnCurve:]
1490
+ cFlags = cFlags[nextOnCurve:]
1491
+ cuFlags = cuFlags[nextOnCurve:]
1492
+ pen.closePath()
1493
+
1494
+ def drawPoints(self, pen, glyfTable, offset=0):
1495
+ """Draw the glyph using the supplied pointPen. As opposed to Glyph.draw(),
1496
+ this will not change the point indices.
1497
+ """
1498
+
1499
+ if self.isComposite():
1500
+ for component in self.components:
1501
+ glyphName, transform = component.getComponentInfo()
1502
+ pen.addComponent(glyphName, transform)
1503
+ return
1504
+
1505
+ coordinates, endPts, flags = self.getCoordinates(glyfTable)
1506
+ if offset:
1507
+ coordinates = coordinates.copy()
1508
+ coordinates.translate((offset, 0))
1509
+ start = 0
1510
+ for end in endPts:
1511
+ end = end + 1
1512
+ contour = coordinates[start:end]
1513
+ cFlags = flags[start:end]
1514
+ start = end
1515
+ pen.beginPath()
1516
+ # Start with the appropriate segment type based on the final segment
1517
+
1518
+ if cFlags[-1] & flagOnCurve:
1519
+ segmentType = "line"
1520
+ elif cFlags[-1] & flagCubic:
1521
+ segmentType = "curve"
1522
+ else:
1523
+ segmentType = "qcurve"
1524
+ for i, pt in enumerate(contour):
1525
+ if cFlags[i] & flagOnCurve:
1526
+ pen.addPoint(pt, segmentType=segmentType)
1527
+ segmentType = "line"
1528
+ else:
1529
+ pen.addPoint(pt)
1530
+ segmentType = "curve" if cFlags[i] & flagCubic else "qcurve"
1531
+ pen.endPath()
1532
+
1533
+ def __eq__(self, other):
1534
+ if type(self) != type(other):
1535
+ return NotImplemented
1536
+ return self.__dict__ == other.__dict__
1537
+
1538
+ def __ne__(self, other):
1539
+ result = self.__eq__(other)
1540
+ return result if result is NotImplemented else not result
1541
+
1542
+
1543
+ # Vector.__round__ uses the built-in (Banker's) `round` but we want
1544
+ # to use otRound below
1545
+ _roundv = partial(Vector.__round__, round=otRound)
1546
+
1547
+
1548
+ def _is_mid_point(p0: tuple, p1: tuple, p2: tuple) -> bool:
1549
+ # True if p1 is in the middle of p0 and p2, either before or after rounding
1550
+ p0 = Vector(p0)
1551
+ p1 = Vector(p1)
1552
+ p2 = Vector(p2)
1553
+ return ((p0 + p2) * 0.5).isclose(p1) or _roundv(p0) + _roundv(p2) == _roundv(p1) * 2
1554
+
1555
+
1556
+ def dropImpliedOnCurvePoints(*interpolatable_glyphs: Glyph) -> Set[int]:
1557
+ """Drop impliable on-curve points from the (simple) glyph or glyphs.
1558
+
1559
+ In TrueType glyf outlines, on-curve points can be implied when they are located at
1560
+ the midpoint of the line connecting two consecutive off-curve points.
1561
+
1562
+ If more than one glyphs are passed, these are assumed to be interpolatable masters
1563
+ of the same glyph impliable, and thus only the on-curve points that are impliable
1564
+ for all of them will actually be implied.
1565
+ Composite glyphs or empty glyphs are skipped, only simple glyphs with 1 or more
1566
+ contours are considered.
1567
+ The input glyph(s) is/are modified in-place.
1568
+
1569
+ Args:
1570
+ interpolatable_glyphs: The glyph or glyphs to modify in-place.
1571
+
1572
+ Returns:
1573
+ The set of point indices that were dropped if any.
1574
+
1575
+ Raises:
1576
+ ValueError if simple glyphs are not in fact interpolatable because they have
1577
+ different point flags or number of contours.
1578
+
1579
+ Reference:
1580
+ https://developer.apple.com/fonts/TrueType-Reference-Manual/RM01/Chap1.html
1581
+ """
1582
+ staticAttributes = SimpleNamespace(
1583
+ numberOfContours=None, flags=None, endPtsOfContours=None
1584
+ )
1585
+ drop = None
1586
+ simple_glyphs = []
1587
+ for i, glyph in enumerate(interpolatable_glyphs):
1588
+ if glyph.numberOfContours < 1:
1589
+ # ignore composite or empty glyphs
1590
+ continue
1591
+
1592
+ for attr in staticAttributes.__dict__:
1593
+ expected = getattr(staticAttributes, attr)
1594
+ found = getattr(glyph, attr)
1595
+ if expected is None:
1596
+ setattr(staticAttributes, attr, found)
1597
+ elif expected != found:
1598
+ raise ValueError(
1599
+ f"Incompatible {attr} for glyph at master index {i}: "
1600
+ f"expected {expected}, found {found}"
1601
+ )
1602
+
1603
+ may_drop = set()
1604
+ start = 0
1605
+ coords = glyph.coordinates
1606
+ flags = staticAttributes.flags
1607
+ endPtsOfContours = staticAttributes.endPtsOfContours
1608
+ for last in endPtsOfContours:
1609
+ for i in range(start, last + 1):
1610
+ if not (flags[i] & flagOnCurve):
1611
+ continue
1612
+ prv = i - 1 if i > start else last
1613
+ nxt = i + 1 if i < last else start
1614
+ if (flags[prv] & flagOnCurve) or flags[prv] != flags[nxt]:
1615
+ continue
1616
+ # we may drop the ith on-curve if halfway between previous/next off-curves
1617
+ if not _is_mid_point(coords[prv], coords[i], coords[nxt]):
1618
+ continue
1619
+
1620
+ may_drop.add(i)
1621
+ start = last + 1
1622
+ # we only want to drop if ALL interpolatable glyphs have the same implied oncurves
1623
+ if drop is None:
1624
+ drop = may_drop
1625
+ else:
1626
+ drop.intersection_update(may_drop)
1627
+
1628
+ simple_glyphs.append(glyph)
1629
+
1630
+ if drop:
1631
+ # Do the actual dropping
1632
+ flags = staticAttributes.flags
1633
+ assert flags is not None
1634
+ newFlags = array.array(
1635
+ "B", (flags[i] for i in range(len(flags)) if i not in drop)
1636
+ )
1637
+
1638
+ endPts = staticAttributes.endPtsOfContours
1639
+ assert endPts is not None
1640
+ newEndPts = []
1641
+ i = 0
1642
+ delta = 0
1643
+ for d in sorted(drop):
1644
+ while d > endPts[i]:
1645
+ newEndPts.append(endPts[i] - delta)
1646
+ i += 1
1647
+ delta += 1
1648
+ while i < len(endPts):
1649
+ newEndPts.append(endPts[i] - delta)
1650
+ i += 1
1651
+
1652
+ for glyph in simple_glyphs:
1653
+ coords = glyph.coordinates
1654
+ glyph.coordinates = GlyphCoordinates(
1655
+ coords[i] for i in range(len(coords)) if i not in drop
1656
+ )
1657
+ glyph.flags = newFlags
1658
+ glyph.endPtsOfContours = newEndPts
1659
+
1660
+ return drop if drop is not None else set()
1661
+
1662
+
1663
+ class GlyphComponent(object):
1664
+ """Represents a component within a composite glyph.
1665
+
1666
+ The component is represented internally with four attributes: ``glyphName``,
1667
+ ``x``, ``y`` and ``transform``. If there is no "two-by-two" matrix (i.e
1668
+ no scaling, reflection, or rotation; only translation), the ``transform``
1669
+ attribute is not present.
1670
+ """
1671
+
1672
+ # The above documentation is not *completely* true, but is *true enough* because
1673
+ # the rare firstPt/lastPt attributes are not totally supported and nobody seems to
1674
+ # mind - see below.
1675
+
1676
+ def __init__(self):
1677
+ pass
1678
+
1679
+ def getComponentInfo(self):
1680
+ """Return information about the component
1681
+
1682
+ This method returns a tuple of two values: the glyph name of the component's
1683
+ base glyph, and a transformation matrix. As opposed to accessing the attributes
1684
+ directly, ``getComponentInfo`` always returns a six-element tuple of the
1685
+ component's transformation matrix, even when the two-by-two ``.transform``
1686
+ matrix is not present.
1687
+ """
1688
+ # XXX Ignoring self.firstPt & self.lastpt for now: I need to implement
1689
+ # something equivalent in fontTools.objects.glyph (I'd rather not
1690
+ # convert it to an absolute offset, since it is valuable information).
1691
+ # This method will now raise "AttributeError: x" on glyphs that use
1692
+ # this TT feature.
1693
+ if hasattr(self, "transform"):
1694
+ [[xx, xy], [yx, yy]] = self.transform
1695
+ trans = (xx, xy, yx, yy, self.x, self.y)
1696
+ else:
1697
+ trans = (1, 0, 0, 1, self.x, self.y)
1698
+ return self.glyphName, trans
1699
+
1700
+ def decompile(self, data, glyfTable):
1701
+ flags, glyphID = struct.unpack(">HH", data[:4])
1702
+ self.flags = int(flags)
1703
+ glyphID = int(glyphID)
1704
+ self.glyphName = glyfTable.getGlyphName(int(glyphID))
1705
+ data = data[4:]
1706
+
1707
+ if self.flags & ARG_1_AND_2_ARE_WORDS:
1708
+ if self.flags & ARGS_ARE_XY_VALUES:
1709
+ self.x, self.y = struct.unpack(">hh", data[:4])
1710
+ else:
1711
+ x, y = struct.unpack(">HH", data[:4])
1712
+ self.firstPt, self.secondPt = int(x), int(y)
1713
+ data = data[4:]
1714
+ else:
1715
+ if self.flags & ARGS_ARE_XY_VALUES:
1716
+ self.x, self.y = struct.unpack(">bb", data[:2])
1717
+ else:
1718
+ x, y = struct.unpack(">BB", data[:2])
1719
+ self.firstPt, self.secondPt = int(x), int(y)
1720
+ data = data[2:]
1721
+
1722
+ if self.flags & WE_HAVE_A_SCALE:
1723
+ (scale,) = struct.unpack(">h", data[:2])
1724
+ self.transform = [
1725
+ [fi2fl(scale, 14), 0],
1726
+ [0, fi2fl(scale, 14)],
1727
+ ] # fixed 2.14
1728
+ data = data[2:]
1729
+ elif self.flags & WE_HAVE_AN_X_AND_Y_SCALE:
1730
+ xscale, yscale = struct.unpack(">hh", data[:4])
1731
+ self.transform = [
1732
+ [fi2fl(xscale, 14), 0],
1733
+ [0, fi2fl(yscale, 14)],
1734
+ ] # fixed 2.14
1735
+ data = data[4:]
1736
+ elif self.flags & WE_HAVE_A_TWO_BY_TWO:
1737
+ (xscale, scale01, scale10, yscale) = struct.unpack(">hhhh", data[:8])
1738
+ self.transform = [
1739
+ [fi2fl(xscale, 14), fi2fl(scale01, 14)],
1740
+ [fi2fl(scale10, 14), fi2fl(yscale, 14)],
1741
+ ] # fixed 2.14
1742
+ data = data[8:]
1743
+ more = self.flags & MORE_COMPONENTS
1744
+ haveInstructions = self.flags & WE_HAVE_INSTRUCTIONS
1745
+ self.flags = self.flags & (
1746
+ ROUND_XY_TO_GRID
1747
+ | USE_MY_METRICS
1748
+ | SCALED_COMPONENT_OFFSET
1749
+ | UNSCALED_COMPONENT_OFFSET
1750
+ | NON_OVERLAPPING
1751
+ | OVERLAP_COMPOUND
1752
+ )
1753
+ return more, haveInstructions, data
1754
+
1755
+ def compile(self, more, haveInstructions, glyfTable):
1756
+ data = b""
1757
+
1758
+ # reset all flags we will calculate ourselves
1759
+ flags = self.flags & (
1760
+ ROUND_XY_TO_GRID
1761
+ | USE_MY_METRICS
1762
+ | SCALED_COMPONENT_OFFSET
1763
+ | UNSCALED_COMPONENT_OFFSET
1764
+ | NON_OVERLAPPING
1765
+ | OVERLAP_COMPOUND
1766
+ )
1767
+ if more:
1768
+ flags = flags | MORE_COMPONENTS
1769
+ if haveInstructions:
1770
+ flags = flags | WE_HAVE_INSTRUCTIONS
1771
+
1772
+ if hasattr(self, "firstPt"):
1773
+ if (0 <= self.firstPt <= 255) and (0 <= self.secondPt <= 255):
1774
+ data = data + struct.pack(">BB", self.firstPt, self.secondPt)
1775
+ else:
1776
+ data = data + struct.pack(">HH", self.firstPt, self.secondPt)
1777
+ flags = flags | ARG_1_AND_2_ARE_WORDS
1778
+ else:
1779
+ x = otRound(self.x)
1780
+ y = otRound(self.y)
1781
+ flags = flags | ARGS_ARE_XY_VALUES
1782
+ if (-128 <= x <= 127) and (-128 <= y <= 127):
1783
+ data = data + struct.pack(">bb", x, y)
1784
+ else:
1785
+ data = data + struct.pack(">hh", x, y)
1786
+ flags = flags | ARG_1_AND_2_ARE_WORDS
1787
+
1788
+ if hasattr(self, "transform"):
1789
+ transform = [[fl2fi(x, 14) for x in row] for row in self.transform]
1790
+ if transform[0][1] or transform[1][0]:
1791
+ flags = flags | WE_HAVE_A_TWO_BY_TWO
1792
+ data = data + struct.pack(
1793
+ ">hhhh",
1794
+ transform[0][0],
1795
+ transform[0][1],
1796
+ transform[1][0],
1797
+ transform[1][1],
1798
+ )
1799
+ elif transform[0][0] != transform[1][1]:
1800
+ flags = flags | WE_HAVE_AN_X_AND_Y_SCALE
1801
+ data = data + struct.pack(">hh", transform[0][0], transform[1][1])
1802
+ else:
1803
+ flags = flags | WE_HAVE_A_SCALE
1804
+ data = data + struct.pack(">h", transform[0][0])
1805
+
1806
+ glyphID = glyfTable.getGlyphID(self.glyphName)
1807
+ return struct.pack(">HH", flags, glyphID) + data
1808
+
1809
+ def toXML(self, writer, ttFont):
1810
+ attrs = [("glyphName", self.glyphName)]
1811
+ if not hasattr(self, "firstPt"):
1812
+ attrs = attrs + [("x", self.x), ("y", self.y)]
1813
+ else:
1814
+ attrs = attrs + [("firstPt", self.firstPt), ("secondPt", self.secondPt)]
1815
+
1816
+ if hasattr(self, "transform"):
1817
+ transform = self.transform
1818
+ if transform[0][1] or transform[1][0]:
1819
+ attrs = attrs + [
1820
+ ("scalex", fl2str(transform[0][0], 14)),
1821
+ ("scale01", fl2str(transform[0][1], 14)),
1822
+ ("scale10", fl2str(transform[1][0], 14)),
1823
+ ("scaley", fl2str(transform[1][1], 14)),
1824
+ ]
1825
+ elif transform[0][0] != transform[1][1]:
1826
+ attrs = attrs + [
1827
+ ("scalex", fl2str(transform[0][0], 14)),
1828
+ ("scaley", fl2str(transform[1][1], 14)),
1829
+ ]
1830
+ else:
1831
+ attrs = attrs + [("scale", fl2str(transform[0][0], 14))]
1832
+ attrs = attrs + [("flags", hex(self.flags))]
1833
+ writer.simpletag("component", attrs)
1834
+ writer.newline()
1835
+
1836
+ def fromXML(self, name, attrs, content, ttFont):
1837
+ self.glyphName = attrs["glyphName"]
1838
+ if "firstPt" in attrs:
1839
+ self.firstPt = safeEval(attrs["firstPt"])
1840
+ self.secondPt = safeEval(attrs["secondPt"])
1841
+ else:
1842
+ self.x = safeEval(attrs["x"])
1843
+ self.y = safeEval(attrs["y"])
1844
+ if "scale01" in attrs:
1845
+ scalex = str2fl(attrs["scalex"], 14)
1846
+ scale01 = str2fl(attrs["scale01"], 14)
1847
+ scale10 = str2fl(attrs["scale10"], 14)
1848
+ scaley = str2fl(attrs["scaley"], 14)
1849
+ self.transform = [[scalex, scale01], [scale10, scaley]]
1850
+ elif "scalex" in attrs:
1851
+ scalex = str2fl(attrs["scalex"], 14)
1852
+ scaley = str2fl(attrs["scaley"], 14)
1853
+ self.transform = [[scalex, 0], [0, scaley]]
1854
+ elif "scale" in attrs:
1855
+ scale = str2fl(attrs["scale"], 14)
1856
+ self.transform = [[scale, 0], [0, scale]]
1857
+ self.flags = safeEval(attrs["flags"])
1858
+
1859
+ def __eq__(self, other):
1860
+ if type(self) != type(other):
1861
+ return NotImplemented
1862
+ return self.__dict__ == other.__dict__
1863
+
1864
+ def __ne__(self, other):
1865
+ result = self.__eq__(other)
1866
+ return result if result is NotImplemented else not result
1867
+
1868
+
1869
+ class GlyphCoordinates(object):
1870
+ """A list of glyph coordinates.
1871
+
1872
+ Unlike an ordinary list, this is a numpy-like matrix object which supports
1873
+ matrix addition, scalar multiplication and other operations described below.
1874
+ """
1875
+
1876
+ def __init__(self, iterable=[]):
1877
+ self._a = array.array("d")
1878
+ self.extend(iterable)
1879
+
1880
+ @property
1881
+ def array(self):
1882
+ """Returns the underlying array of coordinates"""
1883
+ return self._a
1884
+
1885
+ @staticmethod
1886
+ def zeros(count):
1887
+ """Creates a new ``GlyphCoordinates`` object with all coordinates set to (0,0)"""
1888
+ g = GlyphCoordinates()
1889
+ g._a.frombytes(bytes(count * 2 * g._a.itemsize))
1890
+ return g
1891
+
1892
+ def copy(self):
1893
+ """Creates a new ``GlyphCoordinates`` object which is a copy of the current one."""
1894
+ c = GlyphCoordinates()
1895
+ c._a.extend(self._a)
1896
+ return c
1897
+
1898
+ def __len__(self):
1899
+ """Returns the number of coordinates in the array."""
1900
+ return len(self._a) // 2
1901
+
1902
+ def __getitem__(self, k):
1903
+ """Returns a two element tuple (x,y)"""
1904
+ a = self._a
1905
+ if isinstance(k, slice):
1906
+ indices = range(*k.indices(len(self)))
1907
+ # Instead of calling ourselves recursively, duplicate code; faster
1908
+ ret = []
1909
+ for k in indices:
1910
+ x = a[2 * k]
1911
+ y = a[2 * k + 1]
1912
+ ret.append(
1913
+ (int(x) if x.is_integer() else x, int(y) if y.is_integer() else y)
1914
+ )
1915
+ return ret
1916
+ x = a[2 * k]
1917
+ y = a[2 * k + 1]
1918
+ return (int(x) if x.is_integer() else x, int(y) if y.is_integer() else y)
1919
+
1920
+ def __setitem__(self, k, v):
1921
+ """Sets a point's coordinates to a two element tuple (x,y)"""
1922
+ if isinstance(k, slice):
1923
+ indices = range(*k.indices(len(self)))
1924
+ # XXX This only works if len(v) == len(indices)
1925
+ for j, i in enumerate(indices):
1926
+ self[i] = v[j]
1927
+ return
1928
+ self._a[2 * k], self._a[2 * k + 1] = v
1929
+
1930
+ def __delitem__(self, i):
1931
+ """Removes a point from the list"""
1932
+ i = (2 * i) % len(self._a)
1933
+ del self._a[i]
1934
+ del self._a[i]
1935
+
1936
+ def __repr__(self):
1937
+ return "GlyphCoordinates([" + ",".join(str(c) for c in self) + "])"
1938
+
1939
+ def append(self, p):
1940
+ self._a.extend(tuple(p))
1941
+
1942
+ def extend(self, iterable):
1943
+ for p in iterable:
1944
+ self._a.extend(p)
1945
+
1946
+ def toInt(self, *, round=otRound):
1947
+ if round is noRound:
1948
+ return
1949
+ a = self._a
1950
+ for i in range(len(a)):
1951
+ a[i] = round(a[i])
1952
+
1953
+ def calcBounds(self):
1954
+ a = self._a
1955
+ if not a:
1956
+ return 0, 0, 0, 0
1957
+ xs = a[0::2]
1958
+ ys = a[1::2]
1959
+ return min(xs), min(ys), max(xs), max(ys)
1960
+
1961
+ def calcIntBounds(self, round=otRound):
1962
+ return tuple(round(v) for v in self.calcBounds())
1963
+
1964
+ def relativeToAbsolute(self):
1965
+ a = self._a
1966
+ x, y = 0, 0
1967
+ for i in range(0, len(a), 2):
1968
+ a[i] = x = a[i] + x
1969
+ a[i + 1] = y = a[i + 1] + y
1970
+
1971
+ def absoluteToRelative(self):
1972
+ a = self._a
1973
+ x, y = 0, 0
1974
+ for i in range(0, len(a), 2):
1975
+ nx = a[i]
1976
+ ny = a[i + 1]
1977
+ a[i] = nx - x
1978
+ a[i + 1] = ny - y
1979
+ x = nx
1980
+ y = ny
1981
+
1982
+ def translate(self, p):
1983
+ """
1984
+ >>> GlyphCoordinates([(1,2)]).translate((.5,0))
1985
+ """
1986
+ x, y = p
1987
+ if x == 0 and y == 0:
1988
+ return
1989
+ a = self._a
1990
+ for i in range(0, len(a), 2):
1991
+ a[i] += x
1992
+ a[i + 1] += y
1993
+
1994
+ def scale(self, p):
1995
+ """
1996
+ >>> GlyphCoordinates([(1,2)]).scale((.5,0))
1997
+ """
1998
+ x, y = p
1999
+ if x == 1 and y == 1:
2000
+ return
2001
+ a = self._a
2002
+ for i in range(0, len(a), 2):
2003
+ a[i] *= x
2004
+ a[i + 1] *= y
2005
+
2006
+ def transform(self, t):
2007
+ """
2008
+ >>> GlyphCoordinates([(1,2)]).transform(((.5,0),(.2,.5)))
2009
+ """
2010
+ a = self._a
2011
+ for i in range(0, len(a), 2):
2012
+ x = a[i]
2013
+ y = a[i + 1]
2014
+ px = x * t[0][0] + y * t[1][0]
2015
+ py = x * t[0][1] + y * t[1][1]
2016
+ a[i] = px
2017
+ a[i + 1] = py
2018
+
2019
+ def __eq__(self, other):
2020
+ """
2021
+ >>> g = GlyphCoordinates([(1,2)])
2022
+ >>> g2 = GlyphCoordinates([(1.0,2)])
2023
+ >>> g3 = GlyphCoordinates([(1.5,2)])
2024
+ >>> g == g2
2025
+ True
2026
+ >>> g == g3
2027
+ False
2028
+ >>> g2 == g3
2029
+ False
2030
+ """
2031
+ if type(self) != type(other):
2032
+ return NotImplemented
2033
+ return self._a == other._a
2034
+
2035
+ def __ne__(self, other):
2036
+ """
2037
+ >>> g = GlyphCoordinates([(1,2)])
2038
+ >>> g2 = GlyphCoordinates([(1.0,2)])
2039
+ >>> g3 = GlyphCoordinates([(1.5,2)])
2040
+ >>> g != g2
2041
+ False
2042
+ >>> g != g3
2043
+ True
2044
+ >>> g2 != g3
2045
+ True
2046
+ """
2047
+ result = self.__eq__(other)
2048
+ return result if result is NotImplemented else not result
2049
+
2050
+ # Math operations
2051
+
2052
+ def __pos__(self):
2053
+ """
2054
+ >>> g = GlyphCoordinates([(1,2)])
2055
+ >>> g
2056
+ GlyphCoordinates([(1, 2)])
2057
+ >>> g2 = +g
2058
+ >>> g2
2059
+ GlyphCoordinates([(1, 2)])
2060
+ >>> g2.translate((1,0))
2061
+ >>> g2
2062
+ GlyphCoordinates([(2, 2)])
2063
+ >>> g
2064
+ GlyphCoordinates([(1, 2)])
2065
+ """
2066
+ return self.copy()
2067
+
2068
+ def __neg__(self):
2069
+ """
2070
+ >>> g = GlyphCoordinates([(1,2)])
2071
+ >>> g
2072
+ GlyphCoordinates([(1, 2)])
2073
+ >>> g2 = -g
2074
+ >>> g2
2075
+ GlyphCoordinates([(-1, -2)])
2076
+ >>> g
2077
+ GlyphCoordinates([(1, 2)])
2078
+ """
2079
+ r = self.copy()
2080
+ a = r._a
2081
+ for i in range(len(a)):
2082
+ a[i] = -a[i]
2083
+ return r
2084
+
2085
+ def __round__(self, *, round=otRound):
2086
+ r = self.copy()
2087
+ r.toInt(round=round)
2088
+ return r
2089
+
2090
+ def __add__(self, other):
2091
+ return self.copy().__iadd__(other)
2092
+
2093
+ def __sub__(self, other):
2094
+ return self.copy().__isub__(other)
2095
+
2096
+ def __mul__(self, other):
2097
+ return self.copy().__imul__(other)
2098
+
2099
+ def __truediv__(self, other):
2100
+ return self.copy().__itruediv__(other)
2101
+
2102
+ __radd__ = __add__
2103
+ __rmul__ = __mul__
2104
+
2105
+ def __rsub__(self, other):
2106
+ return other + (-self)
2107
+
2108
+ def __iadd__(self, other):
2109
+ """
2110
+ >>> g = GlyphCoordinates([(1,2)])
2111
+ >>> g += (.5,0)
2112
+ >>> g
2113
+ GlyphCoordinates([(1.5, 2)])
2114
+ >>> g2 = GlyphCoordinates([(3,4)])
2115
+ >>> g += g2
2116
+ >>> g
2117
+ GlyphCoordinates([(4.5, 6)])
2118
+ """
2119
+ if isinstance(other, tuple):
2120
+ assert len(other) == 2
2121
+ self.translate(other)
2122
+ return self
2123
+ if isinstance(other, GlyphCoordinates):
2124
+ other = other._a
2125
+ a = self._a
2126
+ assert len(a) == len(other)
2127
+ for i in range(len(a)):
2128
+ a[i] += other[i]
2129
+ return self
2130
+ return NotImplemented
2131
+
2132
+ def __isub__(self, other):
2133
+ """
2134
+ >>> g = GlyphCoordinates([(1,2)])
2135
+ >>> g -= (.5,0)
2136
+ >>> g
2137
+ GlyphCoordinates([(0.5, 2)])
2138
+ >>> g2 = GlyphCoordinates([(3,4)])
2139
+ >>> g -= g2
2140
+ >>> g
2141
+ GlyphCoordinates([(-2.5, -2)])
2142
+ """
2143
+ if isinstance(other, tuple):
2144
+ assert len(other) == 2
2145
+ self.translate((-other[0], -other[1]))
2146
+ return self
2147
+ if isinstance(other, GlyphCoordinates):
2148
+ other = other._a
2149
+ a = self._a
2150
+ assert len(a) == len(other)
2151
+ for i in range(len(a)):
2152
+ a[i] -= other[i]
2153
+ return self
2154
+ return NotImplemented
2155
+
2156
+ def __imul__(self, other):
2157
+ """
2158
+ >>> g = GlyphCoordinates([(1,2)])
2159
+ >>> g *= (2,.5)
2160
+ >>> g *= 2
2161
+ >>> g
2162
+ GlyphCoordinates([(4, 2)])
2163
+ >>> g = GlyphCoordinates([(1,2)])
2164
+ >>> g *= 2
2165
+ >>> g
2166
+ GlyphCoordinates([(2, 4)])
2167
+ """
2168
+ if isinstance(other, tuple):
2169
+ assert len(other) == 2
2170
+ self.scale(other)
2171
+ return self
2172
+ if isinstance(other, Number):
2173
+ if other == 1:
2174
+ return self
2175
+ a = self._a
2176
+ for i in range(len(a)):
2177
+ a[i] *= other
2178
+ return self
2179
+ return NotImplemented
2180
+
2181
+ def __itruediv__(self, other):
2182
+ """
2183
+ >>> g = GlyphCoordinates([(1,3)])
2184
+ >>> g /= (.5,1.5)
2185
+ >>> g /= 2
2186
+ >>> g
2187
+ GlyphCoordinates([(1, 1)])
2188
+ """
2189
+ if isinstance(other, Number):
2190
+ other = (other, other)
2191
+ if isinstance(other, tuple):
2192
+ if other == (1, 1):
2193
+ return self
2194
+ assert len(other) == 2
2195
+ self.scale((1.0 / other[0], 1.0 / other[1]))
2196
+ return self
2197
+ return NotImplemented
2198
+
2199
+ def __bool__(self):
2200
+ """
2201
+ >>> g = GlyphCoordinates([])
2202
+ >>> bool(g)
2203
+ False
2204
+ >>> g = GlyphCoordinates([(0,0), (0.,0)])
2205
+ >>> bool(g)
2206
+ True
2207
+ >>> g = GlyphCoordinates([(0,0), (1,0)])
2208
+ >>> bool(g)
2209
+ True
2210
+ >>> g = GlyphCoordinates([(0,.5), (0,0)])
2211
+ >>> bool(g)
2212
+ True
2213
+ """
2214
+ return bool(self._a)
2215
+
2216
+ __nonzero__ = __bool__
2217
+
2218
+
2219
+ if __name__ == "__main__":
2220
+ import doctest, sys
2221
+
2222
+ sys.exit(doctest.testmod().failed)
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_h_m_t_x.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc.roundTools import otRound
2
+ from fontTools import ttLib
3
+ from fontTools.misc.textTools import safeEval
4
+ from . import DefaultTable
5
+ import sys
6
+ import struct
7
+ import array
8
+ import logging
9
+
10
+
11
+ log = logging.getLogger(__name__)
12
+
13
+
14
+ class table__h_m_t_x(DefaultTable.DefaultTable):
15
+ headerTag = "hhea"
16
+ advanceName = "width"
17
+ sideBearingName = "lsb"
18
+ numberOfMetricsName = "numberOfHMetrics"
19
+ longMetricFormat = "Hh"
20
+
21
+ def decompile(self, data, ttFont):
22
+ numGlyphs = ttFont["maxp"].numGlyphs
23
+ headerTable = ttFont.get(self.headerTag)
24
+ if headerTable is not None:
25
+ numberOfMetrics = int(getattr(headerTable, self.numberOfMetricsName))
26
+ else:
27
+ numberOfMetrics = numGlyphs
28
+ if numberOfMetrics > numGlyphs:
29
+ log.warning(
30
+ "The %s.%s exceeds the maxp.numGlyphs"
31
+ % (self.headerTag, self.numberOfMetricsName)
32
+ )
33
+ numberOfMetrics = numGlyphs
34
+ if len(data) < 4 * numberOfMetrics:
35
+ raise ttLib.TTLibError("not enough '%s' table data" % self.tableTag)
36
+ # Note: advanceWidth is unsigned, but some font editors might
37
+ # read/write as signed. We can't be sure whether it was a mistake
38
+ # or not, so we read as unsigned but also issue a warning...
39
+ metricsFmt = ">" + self.longMetricFormat * numberOfMetrics
40
+ metrics = struct.unpack(metricsFmt, data[: 4 * numberOfMetrics])
41
+ data = data[4 * numberOfMetrics :]
42
+ numberOfSideBearings = numGlyphs - numberOfMetrics
43
+ sideBearings = array.array("h", data[: 2 * numberOfSideBearings])
44
+ data = data[2 * numberOfSideBearings :]
45
+
46
+ if sys.byteorder != "big":
47
+ sideBearings.byteswap()
48
+ if data:
49
+ log.warning("too much '%s' table data" % self.tableTag)
50
+ self.metrics = {}
51
+ glyphOrder = ttFont.getGlyphOrder()
52
+ for i in range(numberOfMetrics):
53
+ glyphName = glyphOrder[i]
54
+ advanceWidth, lsb = metrics[i * 2 : i * 2 + 2]
55
+ if advanceWidth > 32767:
56
+ log.warning(
57
+ "Glyph %r has a huge advance %s (%d); is it intentional or "
58
+ "an (invalid) negative value?",
59
+ glyphName,
60
+ self.advanceName,
61
+ advanceWidth,
62
+ )
63
+ self.metrics[glyphName] = (advanceWidth, lsb)
64
+ lastAdvance = metrics[-2]
65
+ for i in range(numberOfSideBearings):
66
+ glyphName = glyphOrder[i + numberOfMetrics]
67
+ self.metrics[glyphName] = (lastAdvance, sideBearings[i])
68
+
69
+ def compile(self, ttFont):
70
+ metrics = []
71
+ hasNegativeAdvances = False
72
+ for glyphName in ttFont.getGlyphOrder():
73
+ advanceWidth, sideBearing = self.metrics[glyphName]
74
+ if advanceWidth < 0:
75
+ log.error(
76
+ "Glyph %r has negative advance %s" % (glyphName, self.advanceName)
77
+ )
78
+ hasNegativeAdvances = True
79
+ metrics.append([advanceWidth, sideBearing])
80
+
81
+ headerTable = ttFont.get(self.headerTag)
82
+ if headerTable is not None:
83
+ lastAdvance = metrics[-1][0]
84
+ lastIndex = len(metrics)
85
+ while metrics[lastIndex - 2][0] == lastAdvance:
86
+ lastIndex -= 1
87
+ if lastIndex <= 1:
88
+ # all advances are equal
89
+ lastIndex = 1
90
+ break
91
+ additionalMetrics = metrics[lastIndex:]
92
+ additionalMetrics = [otRound(sb) for _, sb in additionalMetrics]
93
+ metrics = metrics[:lastIndex]
94
+ numberOfMetrics = len(metrics)
95
+ setattr(headerTable, self.numberOfMetricsName, numberOfMetrics)
96
+ else:
97
+ # no hhea/vhea, can't store numberOfMetrics; assume == numGlyphs
98
+ numberOfMetrics = ttFont["maxp"].numGlyphs
99
+ additionalMetrics = []
100
+
101
+ allMetrics = []
102
+ for advance, sb in metrics:
103
+ allMetrics.extend([otRound(advance), otRound(sb)])
104
+ metricsFmt = ">" + self.longMetricFormat * numberOfMetrics
105
+ try:
106
+ data = struct.pack(metricsFmt, *allMetrics)
107
+ except struct.error as e:
108
+ if "out of range" in str(e) and hasNegativeAdvances:
109
+ raise ttLib.TTLibError(
110
+ "'%s' table can't contain negative advance %ss"
111
+ % (self.tableTag, self.advanceName)
112
+ )
113
+ else:
114
+ raise
115
+ additionalMetrics = array.array("h", additionalMetrics)
116
+ if sys.byteorder != "big":
117
+ additionalMetrics.byteswap()
118
+ data = data + additionalMetrics.tobytes()
119
+ return data
120
+
121
+ def toXML(self, writer, ttFont):
122
+ names = sorted(self.metrics.keys())
123
+ for glyphName in names:
124
+ advance, sb = self.metrics[glyphName]
125
+ writer.simpletag(
126
+ "mtx",
127
+ [
128
+ ("name", glyphName),
129
+ (self.advanceName, advance),
130
+ (self.sideBearingName, sb),
131
+ ],
132
+ )
133
+ writer.newline()
134
+
135
+ def fromXML(self, name, attrs, content, ttFont):
136
+ if not hasattr(self, "metrics"):
137
+ self.metrics = {}
138
+ if name == "mtx":
139
+ self.metrics[attrs["name"]] = (
140
+ safeEval(attrs[self.advanceName]),
141
+ safeEval(attrs[self.sideBearingName]),
142
+ )
143
+
144
+ def __delitem__(self, glyphName):
145
+ del self.metrics[glyphName]
146
+
147
+ def __getitem__(self, glyphName):
148
+ return self.metrics[glyphName]
149
+
150
+ def __setitem__(self, glyphName, advance_sb_pair):
151
+ self.metrics[glyphName] = tuple(advance_sb_pair)
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_l_o_c_a.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import DefaultTable
2
+ import sys
3
+ import array
4
+ import logging
5
+
6
+
7
+ log = logging.getLogger(__name__)
8
+
9
+
10
+ class table__l_o_c_a(DefaultTable.DefaultTable):
11
+ dependencies = ["glyf"]
12
+
13
+ def decompile(self, data, ttFont):
14
+ longFormat = ttFont["head"].indexToLocFormat
15
+ if longFormat:
16
+ format = "I"
17
+ else:
18
+ format = "H"
19
+ locations = array.array(format)
20
+ locations.frombytes(data)
21
+ if sys.byteorder != "big":
22
+ locations.byteswap()
23
+ if not longFormat:
24
+ locations = array.array("I", (2 * l for l in locations))
25
+ if len(locations) < (ttFont["maxp"].numGlyphs + 1):
26
+ log.warning(
27
+ "corrupt 'loca' table, or wrong numGlyphs in 'maxp': %d %d",
28
+ len(locations) - 1,
29
+ ttFont["maxp"].numGlyphs,
30
+ )
31
+ self.locations = locations
32
+
33
+ def compile(self, ttFont):
34
+ try:
35
+ max_location = max(self.locations)
36
+ except AttributeError:
37
+ self.set([])
38
+ max_location = 0
39
+ if max_location < 0x20000 and all(l % 2 == 0 for l in self.locations):
40
+ locations = array.array("H")
41
+ for i in range(len(self.locations)):
42
+ locations.append(self.locations[i] // 2)
43
+ ttFont["head"].indexToLocFormat = 0
44
+ else:
45
+ locations = array.array("I", self.locations)
46
+ ttFont["head"].indexToLocFormat = 1
47
+ if sys.byteorder != "big":
48
+ locations.byteswap()
49
+ return locations.tobytes()
50
+
51
+ def set(self, locations):
52
+ self.locations = array.array("I", locations)
53
+
54
+ def toXML(self, writer, ttFont):
55
+ writer.comment("The 'loca' table will be calculated by the compiler")
56
+ writer.newline()
57
+
58
+ def __getitem__(self, index):
59
+ return self.locations[index]
60
+
61
+ def __len__(self):
62
+ return len(self.locations)
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_l_t_a_g.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc.textTools import bytesjoin, tobytes, safeEval
2
+ from . import DefaultTable
3
+ import struct
4
+
5
+ # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6ltag.html
6
+
7
+
8
+ class table__l_t_a_g(DefaultTable.DefaultTable):
9
+ def __init__(self, tag=None):
10
+ DefaultTable.DefaultTable.__init__(self, tag)
11
+ self.version, self.flags = 1, 0
12
+ self.tags = []
13
+
14
+ def addTag(self, tag):
15
+ """Add 'tag' to the list of langauge tags if not already there.
16
+
17
+ Returns the integer index of 'tag' in the list of all tags.
18
+ """
19
+ try:
20
+ return self.tags.index(tag)
21
+ except ValueError:
22
+ self.tags.append(tag)
23
+ return len(self.tags) - 1
24
+
25
+ def decompile(self, data, ttFont):
26
+ self.version, self.flags, numTags = struct.unpack(">LLL", data[:12])
27
+ assert self.version == 1
28
+ self.tags = []
29
+ for i in range(numTags):
30
+ pos = 12 + i * 4
31
+ offset, length = struct.unpack(">HH", data[pos : pos + 4])
32
+ tag = data[offset : offset + length].decode("ascii")
33
+ self.tags.append(tag)
34
+
35
+ def compile(self, ttFont):
36
+ dataList = [struct.pack(">LLL", self.version, self.flags, len(self.tags))]
37
+ stringPool = ""
38
+ for tag in self.tags:
39
+ offset = stringPool.find(tag)
40
+ if offset < 0:
41
+ offset = len(stringPool)
42
+ stringPool = stringPool + tag
43
+ offset = offset + 12 + len(self.tags) * 4
44
+ dataList.append(struct.pack(">HH", offset, len(tag)))
45
+ dataList.append(tobytes(stringPool))
46
+ return bytesjoin(dataList)
47
+
48
+ def toXML(self, writer, ttFont):
49
+ writer.simpletag("version", value=self.version)
50
+ writer.newline()
51
+ writer.simpletag("flags", value=self.flags)
52
+ writer.newline()
53
+ for tag in self.tags:
54
+ writer.simpletag("LanguageTag", tag=tag)
55
+ writer.newline()
56
+
57
+ def fromXML(self, name, attrs, content, ttFont):
58
+ if not hasattr(self, "tags"):
59
+ self.tags = []
60
+ if name == "LanguageTag":
61
+ self.tags.append(attrs["tag"])
62
+ elif "value" in attrs:
63
+ value = safeEval(attrs["value"])
64
+ setattr(self, name, value)
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_p_o_s_t.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools import ttLib
2
+ from fontTools.ttLib.standardGlyphOrder import standardGlyphOrder
3
+ from fontTools.misc import sstruct
4
+ from fontTools.misc.textTools import bytechr, byteord, tobytes, tostr, safeEval, readHex
5
+ from . import DefaultTable
6
+ import sys
7
+ import struct
8
+ import array
9
+ import logging
10
+
11
+ log = logging.getLogger(__name__)
12
+
13
+ postFormat = """
14
+ >
15
+ formatType: 16.16F
16
+ italicAngle: 16.16F # italic angle in degrees
17
+ underlinePosition: h
18
+ underlineThickness: h
19
+ isFixedPitch: L
20
+ minMemType42: L # minimum memory if TrueType font is downloaded
21
+ maxMemType42: L # maximum memory if TrueType font is downloaded
22
+ minMemType1: L # minimum memory if Type1 font is downloaded
23
+ maxMemType1: L # maximum memory if Type1 font is downloaded
24
+ """
25
+
26
+ postFormatSize = sstruct.calcsize(postFormat)
27
+
28
+
29
+ class table__p_o_s_t(DefaultTable.DefaultTable):
30
+ def decompile(self, data, ttFont):
31
+ sstruct.unpack(postFormat, data[:postFormatSize], self)
32
+ data = data[postFormatSize:]
33
+ if self.formatType == 1.0:
34
+ self.decode_format_1_0(data, ttFont)
35
+ elif self.formatType == 2.0:
36
+ self.decode_format_2_0(data, ttFont)
37
+ elif self.formatType == 3.0:
38
+ self.decode_format_3_0(data, ttFont)
39
+ elif self.formatType == 4.0:
40
+ self.decode_format_4_0(data, ttFont)
41
+ else:
42
+ # supported format
43
+ raise ttLib.TTLibError(
44
+ "'post' table format %f not supported" % self.formatType
45
+ )
46
+
47
+ def compile(self, ttFont):
48
+ data = sstruct.pack(postFormat, self)
49
+ if self.formatType == 1.0:
50
+ pass # we're done
51
+ elif self.formatType == 2.0:
52
+ data = data + self.encode_format_2_0(ttFont)
53
+ elif self.formatType == 3.0:
54
+ pass # we're done
55
+ elif self.formatType == 4.0:
56
+ data = data + self.encode_format_4_0(ttFont)
57
+ else:
58
+ # supported format
59
+ raise ttLib.TTLibError(
60
+ "'post' table format %f not supported" % self.formatType
61
+ )
62
+ return data
63
+
64
+ def getGlyphOrder(self):
65
+ """This function will get called by a ttLib.TTFont instance.
66
+ Do not call this function yourself, use TTFont().getGlyphOrder()
67
+ or its relatives instead!
68
+ """
69
+ if not hasattr(self, "glyphOrder"):
70
+ raise ttLib.TTLibError("illegal use of getGlyphOrder()")
71
+ glyphOrder = self.glyphOrder
72
+ del self.glyphOrder
73
+ return glyphOrder
74
+
75
+ def decode_format_1_0(self, data, ttFont):
76
+ self.glyphOrder = standardGlyphOrder[: ttFont["maxp"].numGlyphs]
77
+
78
+ def decode_format_2_0(self, data, ttFont):
79
+ (numGlyphs,) = struct.unpack(">H", data[:2])
80
+ numGlyphs = int(numGlyphs)
81
+ if numGlyphs > ttFont["maxp"].numGlyphs:
82
+ # Assume the numGlyphs field is bogus, so sync with maxp.
83
+ # I've seen this in one font, and if the assumption is
84
+ # wrong elsewhere, well, so be it: it's hard enough to
85
+ # work around _one_ non-conforming post format...
86
+ numGlyphs = ttFont["maxp"].numGlyphs
87
+ data = data[2:]
88
+ indices = array.array("H")
89
+ indices.frombytes(data[: 2 * numGlyphs])
90
+ if sys.byteorder != "big":
91
+ indices.byteswap()
92
+ data = data[2 * numGlyphs :]
93
+ maxIndex = max(indices)
94
+ self.extraNames = extraNames = unpackPStrings(data, maxIndex - 257)
95
+ self.glyphOrder = glyphOrder = [""] * int(ttFont["maxp"].numGlyphs)
96
+ for glyphID in range(numGlyphs):
97
+ index = indices[glyphID]
98
+ if index > 257:
99
+ try:
100
+ name = extraNames[index - 258]
101
+ except IndexError:
102
+ name = ""
103
+ else:
104
+ # fetch names from standard list
105
+ name = standardGlyphOrder[index]
106
+ glyphOrder[glyphID] = name
107
+ self.build_psNameMapping(ttFont)
108
+
109
+ def build_psNameMapping(self, ttFont):
110
+ mapping = {}
111
+ allNames = {}
112
+ for i in range(ttFont["maxp"].numGlyphs):
113
+ glyphName = psName = self.glyphOrder[i]
114
+ if glyphName == "":
115
+ glyphName = "glyph%.5d" % i
116
+ if glyphName in allNames:
117
+ # make up a new glyphName that's unique
118
+ n = allNames[glyphName]
119
+ while (glyphName + "#" + str(n)) in allNames:
120
+ n += 1
121
+ allNames[glyphName] = n + 1
122
+ glyphName = glyphName + "#" + str(n)
123
+
124
+ self.glyphOrder[i] = glyphName
125
+ allNames[glyphName] = 1
126
+ if glyphName != psName:
127
+ mapping[glyphName] = psName
128
+
129
+ self.mapping = mapping
130
+
131
+ def decode_format_3_0(self, data, ttFont):
132
+ # Setting self.glyphOrder to None will cause the TTFont object
133
+ # try and construct glyph names from a Unicode cmap table.
134
+ self.glyphOrder = None
135
+
136
+ def decode_format_4_0(self, data, ttFont):
137
+ from fontTools import agl
138
+
139
+ numGlyphs = ttFont["maxp"].numGlyphs
140
+ indices = array.array("H")
141
+ indices.frombytes(data)
142
+ if sys.byteorder != "big":
143
+ indices.byteswap()
144
+ # In some older fonts, the size of the post table doesn't match
145
+ # the number of glyphs. Sometimes it's bigger, sometimes smaller.
146
+ self.glyphOrder = glyphOrder = [""] * int(numGlyphs)
147
+ for i in range(min(len(indices), numGlyphs)):
148
+ if indices[i] == 0xFFFF:
149
+ self.glyphOrder[i] = ""
150
+ elif indices[i] in agl.UV2AGL:
151
+ self.glyphOrder[i] = agl.UV2AGL[indices[i]]
152
+ else:
153
+ self.glyphOrder[i] = "uni%04X" % indices[i]
154
+ self.build_psNameMapping(ttFont)
155
+
156
+ def encode_format_2_0(self, ttFont):
157
+ numGlyphs = ttFont["maxp"].numGlyphs
158
+ glyphOrder = ttFont.getGlyphOrder()
159
+ assert len(glyphOrder) == numGlyphs
160
+ indices = array.array("H")
161
+ extraDict = {}
162
+ extraNames = self.extraNames = [
163
+ n for n in self.extraNames if n not in standardGlyphOrder
164
+ ]
165
+ for i in range(len(extraNames)):
166
+ extraDict[extraNames[i]] = i
167
+ for glyphID in range(numGlyphs):
168
+ glyphName = glyphOrder[glyphID]
169
+ if glyphName in self.mapping:
170
+ psName = self.mapping[glyphName]
171
+ else:
172
+ psName = glyphName
173
+ if psName in extraDict:
174
+ index = 258 + extraDict[psName]
175
+ elif psName in standardGlyphOrder:
176
+ index = standardGlyphOrder.index(psName)
177
+ else:
178
+ index = 258 + len(extraNames)
179
+ extraDict[psName] = len(extraNames)
180
+ extraNames.append(psName)
181
+ indices.append(index)
182
+ if sys.byteorder != "big":
183
+ indices.byteswap()
184
+ return (
185
+ struct.pack(">H", numGlyphs) + indices.tobytes() + packPStrings(extraNames)
186
+ )
187
+
188
+ def encode_format_4_0(self, ttFont):
189
+ from fontTools import agl
190
+
191
+ numGlyphs = ttFont["maxp"].numGlyphs
192
+ glyphOrder = ttFont.getGlyphOrder()
193
+ assert len(glyphOrder) == numGlyphs
194
+ indices = array.array("H")
195
+ for glyphID in glyphOrder:
196
+ glyphID = glyphID.split("#")[0]
197
+ if glyphID in agl.AGL2UV:
198
+ indices.append(agl.AGL2UV[glyphID])
199
+ elif len(glyphID) == 7 and glyphID[:3] == "uni":
200
+ indices.append(int(glyphID[3:], 16))
201
+ else:
202
+ indices.append(0xFFFF)
203
+ if sys.byteorder != "big":
204
+ indices.byteswap()
205
+ return indices.tobytes()
206
+
207
+ def toXML(self, writer, ttFont):
208
+ formatstring, names, fixes = sstruct.getformat(postFormat)
209
+ for name in names:
210
+ value = getattr(self, name)
211
+ writer.simpletag(name, value=value)
212
+ writer.newline()
213
+ if hasattr(self, "mapping"):
214
+ writer.begintag("psNames")
215
+ writer.newline()
216
+ writer.comment(
217
+ "This file uses unique glyph names based on the information\n"
218
+ "found in the 'post' table. Since these names might not be unique,\n"
219
+ "we have to invent artificial names in case of clashes. In order to\n"
220
+ "be able to retain the original information, we need a name to\n"
221
+ "ps name mapping for those cases where they differ. That's what\n"
222
+ "you see below.\n"
223
+ )
224
+ writer.newline()
225
+ items = sorted(self.mapping.items())
226
+ for name, psName in items:
227
+ writer.simpletag("psName", name=name, psName=psName)
228
+ writer.newline()
229
+ writer.endtag("psNames")
230
+ writer.newline()
231
+ if hasattr(self, "extraNames"):
232
+ writer.begintag("extraNames")
233
+ writer.newline()
234
+ writer.comment(
235
+ "following are the name that are not taken from the standard Mac glyph order"
236
+ )
237
+ writer.newline()
238
+ for name in self.extraNames:
239
+ writer.simpletag("psName", name=name)
240
+ writer.newline()
241
+ writer.endtag("extraNames")
242
+ writer.newline()
243
+ if hasattr(self, "data"):
244
+ writer.begintag("hexdata")
245
+ writer.newline()
246
+ writer.dumphex(self.data)
247
+ writer.endtag("hexdata")
248
+ writer.newline()
249
+
250
+ def fromXML(self, name, attrs, content, ttFont):
251
+ if name not in ("psNames", "extraNames", "hexdata"):
252
+ setattr(self, name, safeEval(attrs["value"]))
253
+ elif name == "psNames":
254
+ self.mapping = {}
255
+ for element in content:
256
+ if not isinstance(element, tuple):
257
+ continue
258
+ name, attrs, content = element
259
+ if name == "psName":
260
+ self.mapping[attrs["name"]] = attrs["psName"]
261
+ elif name == "extraNames":
262
+ self.extraNames = []
263
+ for element in content:
264
+ if not isinstance(element, tuple):
265
+ continue
266
+ name, attrs, content = element
267
+ if name == "psName":
268
+ self.extraNames.append(attrs["name"])
269
+ else:
270
+ self.data = readHex(content)
271
+
272
+
273
+ def unpackPStrings(data, n):
274
+ # extract n Pascal strings from data.
275
+ # if there is not enough data, use ""
276
+
277
+ strings = []
278
+ index = 0
279
+ dataLen = len(data)
280
+
281
+ for _ in range(n):
282
+ if dataLen <= index:
283
+ length = 0
284
+ else:
285
+ length = byteord(data[index])
286
+ index += 1
287
+
288
+ if dataLen <= index + length - 1:
289
+ name = ""
290
+ else:
291
+ name = tostr(data[index : index + length], encoding="latin1")
292
+ strings.append(name)
293
+ index += length
294
+
295
+ if index < dataLen:
296
+ log.warning("%d extra bytes in post.stringData array", dataLen - index)
297
+
298
+ elif dataLen < index:
299
+ log.warning("not enough data in post.stringData array")
300
+
301
+ return strings
302
+
303
+
304
+ def packPStrings(strings):
305
+ data = b""
306
+ for s in strings:
307
+ data = data + bytechr(len(s)) + tobytes(s, encoding="latin1")
308
+ return data
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_p_r_e_p.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from fontTools import ttLib
2
+
3
+ superclass = ttLib.getTableClass("fpgm")
4
+
5
+
6
+ class table__p_r_e_p(superclass):
7
+ pass
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_p_r_o_p.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .otBase import BaseTTXConverter
2
+
3
+
4
+ # https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6prop.html
5
+ class table__p_r_o_p(BaseTTXConverter):
6
+ pass
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_s_b_i_x.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc import sstruct
2
+ from fontTools.misc.textTools import safeEval, num2binary, binary2num
3
+ from . import DefaultTable
4
+ from .sbixStrike import Strike
5
+
6
+
7
+ sbixHeaderFormat = """
8
+ >
9
+ version: H # Version number (set to 1)
10
+ flags: H # The only two bits used in the flags field are bits 0
11
+ # and 1. For historical reasons, bit 0 must always be 1.
12
+ # Bit 1 is a sbixDrawOutlines flag and is interpreted as
13
+ # follows:
14
+ # 0: Draw only 'sbix' bitmaps
15
+ # 1: Draw both 'sbix' bitmaps and outlines, in that
16
+ # order
17
+ numStrikes: L # Number of bitmap strikes to follow
18
+ """
19
+ sbixHeaderFormatSize = sstruct.calcsize(sbixHeaderFormat)
20
+
21
+
22
+ sbixStrikeOffsetFormat = """
23
+ >
24
+ strikeOffset: L # Offset from begining of table to data for the
25
+ # individual strike
26
+ """
27
+ sbixStrikeOffsetFormatSize = sstruct.calcsize(sbixStrikeOffsetFormat)
28
+
29
+
30
+ class table__s_b_i_x(DefaultTable.DefaultTable):
31
+ def __init__(self, tag=None):
32
+ DefaultTable.DefaultTable.__init__(self, tag)
33
+ self.version = 1
34
+ self.flags = 1
35
+ self.numStrikes = 0
36
+ self.strikes = {}
37
+ self.strikeOffsets = []
38
+
39
+ def decompile(self, data, ttFont):
40
+ # read table header
41
+ sstruct.unpack(sbixHeaderFormat, data[:sbixHeaderFormatSize], self)
42
+ # collect offsets to individual strikes in self.strikeOffsets
43
+ for i in range(self.numStrikes):
44
+ current_offset = sbixHeaderFormatSize + i * sbixStrikeOffsetFormatSize
45
+ offset_entry = sbixStrikeOffset()
46
+ sstruct.unpack(
47
+ sbixStrikeOffsetFormat,
48
+ data[current_offset : current_offset + sbixStrikeOffsetFormatSize],
49
+ offset_entry,
50
+ )
51
+ self.strikeOffsets.append(offset_entry.strikeOffset)
52
+
53
+ # decompile Strikes
54
+ for i in range(self.numStrikes - 1, -1, -1):
55
+ current_strike = Strike(rawdata=data[self.strikeOffsets[i] :])
56
+ data = data[: self.strikeOffsets[i]]
57
+ current_strike.decompile(ttFont)
58
+ # print " Strike length: %xh" % len(bitmapSetData)
59
+ # print "Number of Glyph entries:", len(current_strike.glyphs)
60
+ if current_strike.ppem in self.strikes:
61
+ from fontTools import ttLib
62
+
63
+ raise ttLib.TTLibError("Pixel 'ppem' must be unique for each Strike")
64
+ self.strikes[current_strike.ppem] = current_strike
65
+
66
+ # after the glyph data records have been extracted, we don't need the offsets anymore
67
+ del self.strikeOffsets
68
+ del self.numStrikes
69
+
70
+ def compile(self, ttFont):
71
+ sbixData = b""
72
+ self.numStrikes = len(self.strikes)
73
+ sbixHeader = sstruct.pack(sbixHeaderFormat, self)
74
+
75
+ # calculate offset to start of first strike
76
+ setOffset = sbixHeaderFormatSize + sbixStrikeOffsetFormatSize * self.numStrikes
77
+
78
+ for si in sorted(self.strikes.keys()):
79
+ current_strike = self.strikes[si]
80
+ current_strike.compile(ttFont)
81
+ # append offset to this strike to table header
82
+ current_strike.strikeOffset = setOffset
83
+ sbixHeader += sstruct.pack(sbixStrikeOffsetFormat, current_strike)
84
+ setOffset += len(current_strike.data)
85
+ sbixData += current_strike.data
86
+
87
+ return sbixHeader + sbixData
88
+
89
+ def toXML(self, xmlWriter, ttFont):
90
+ xmlWriter.simpletag("version", value=self.version)
91
+ xmlWriter.newline()
92
+ xmlWriter.simpletag("flags", value=num2binary(self.flags, 16))
93
+ xmlWriter.newline()
94
+ for i in sorted(self.strikes.keys()):
95
+ self.strikes[i].toXML(xmlWriter, ttFont)
96
+
97
+ def fromXML(self, name, attrs, content, ttFont):
98
+ if name == "version":
99
+ setattr(self, name, safeEval(attrs["value"]))
100
+ elif name == "flags":
101
+ setattr(self, name, binary2num(attrs["value"]))
102
+ elif name == "strike":
103
+ current_strike = Strike()
104
+ for element in content:
105
+ if isinstance(element, tuple):
106
+ name, attrs, content = element
107
+ current_strike.fromXML(name, attrs, content, ttFont)
108
+ self.strikes[current_strike.ppem] = current_strike
109
+ else:
110
+ from fontTools import ttLib
111
+
112
+ raise ttLib.TTLibError("can't handle '%s' element" % name)
113
+
114
+
115
+ # Helper classes
116
+
117
+
118
+ class sbixStrikeOffset(object):
119
+ pass
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/_v_h_e_a.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc import sstruct
2
+ from fontTools.misc.textTools import safeEval
3
+ from fontTools.misc.fixedTools import (
4
+ ensureVersionIsLong as fi2ve,
5
+ versionToFixed as ve2fi,
6
+ )
7
+ from . import DefaultTable
8
+ import math
9
+
10
+
11
+ vheaFormat = """
12
+ > # big endian
13
+ tableVersion: L
14
+ ascent: h
15
+ descent: h
16
+ lineGap: h
17
+ advanceHeightMax: H
18
+ minTopSideBearing: h
19
+ minBottomSideBearing: h
20
+ yMaxExtent: h
21
+ caretSlopeRise: h
22
+ caretSlopeRun: h
23
+ caretOffset: h
24
+ reserved1: h
25
+ reserved2: h
26
+ reserved3: h
27
+ reserved4: h
28
+ metricDataFormat: h
29
+ numberOfVMetrics: H
30
+ """
31
+
32
+
33
+ class table__v_h_e_a(DefaultTable.DefaultTable):
34
+ # Note: Keep in sync with table__h_h_e_a
35
+
36
+ dependencies = ["vmtx", "glyf", "CFF ", "CFF2"]
37
+
38
+ def decompile(self, data, ttFont):
39
+ sstruct.unpack(vheaFormat, data, self)
40
+
41
+ def compile(self, ttFont):
42
+ if ttFont.recalcBBoxes and (
43
+ ttFont.isLoaded("glyf")
44
+ or ttFont.isLoaded("CFF ")
45
+ or ttFont.isLoaded("CFF2")
46
+ ):
47
+ self.recalc(ttFont)
48
+ self.tableVersion = fi2ve(self.tableVersion)
49
+ return sstruct.pack(vheaFormat, self)
50
+
51
+ def recalc(self, ttFont):
52
+ if "vmtx" not in ttFont:
53
+ return
54
+
55
+ vmtxTable = ttFont["vmtx"]
56
+ self.advanceHeightMax = max(adv for adv, _ in vmtxTable.metrics.values())
57
+
58
+ boundsHeightDict = {}
59
+ if "glyf" in ttFont:
60
+ glyfTable = ttFont["glyf"]
61
+ for name in ttFont.getGlyphOrder():
62
+ g = glyfTable[name]
63
+ if g.numberOfContours == 0:
64
+ continue
65
+ if g.numberOfContours < 0 and not hasattr(g, "yMax"):
66
+ # Composite glyph without extents set.
67
+ # Calculate those.
68
+ g.recalcBounds(glyfTable)
69
+ boundsHeightDict[name] = g.yMax - g.yMin
70
+ elif "CFF " in ttFont or "CFF2" in ttFont:
71
+ if "CFF " in ttFont:
72
+ topDict = ttFont["CFF "].cff.topDictIndex[0]
73
+ else:
74
+ topDict = ttFont["CFF2"].cff.topDictIndex[0]
75
+ charStrings = topDict.CharStrings
76
+ for name in ttFont.getGlyphOrder():
77
+ cs = charStrings[name]
78
+ bounds = cs.calcBounds(charStrings)
79
+ if bounds is not None:
80
+ boundsHeightDict[name] = int(
81
+ math.ceil(bounds[3]) - math.floor(bounds[1])
82
+ )
83
+
84
+ if boundsHeightDict:
85
+ minTopSideBearing = float("inf")
86
+ minBottomSideBearing = float("inf")
87
+ yMaxExtent = -float("inf")
88
+ for name, boundsHeight in boundsHeightDict.items():
89
+ advanceHeight, tsb = vmtxTable[name]
90
+ bsb = advanceHeight - tsb - boundsHeight
91
+ extent = tsb + boundsHeight
92
+ minTopSideBearing = min(minTopSideBearing, tsb)
93
+ minBottomSideBearing = min(minBottomSideBearing, bsb)
94
+ yMaxExtent = max(yMaxExtent, extent)
95
+ self.minTopSideBearing = minTopSideBearing
96
+ self.minBottomSideBearing = minBottomSideBearing
97
+ self.yMaxExtent = yMaxExtent
98
+
99
+ else: # No glyph has outlines.
100
+ self.minTopSideBearing = 0
101
+ self.minBottomSideBearing = 0
102
+ self.yMaxExtent = 0
103
+
104
+ def toXML(self, writer, ttFont):
105
+ formatstring, names, fixes = sstruct.getformat(vheaFormat)
106
+ for name in names:
107
+ value = getattr(self, name)
108
+ if name == "tableVersion":
109
+ value = fi2ve(value)
110
+ value = "0x%08x" % value
111
+ writer.simpletag(name, value=value)
112
+ writer.newline()
113
+
114
+ def fromXML(self, name, attrs, content, ttFont):
115
+ if name == "tableVersion":
116
+ setattr(self, name, ve2fi(attrs["value"]))
117
+ return
118
+ setattr(self, name, safeEval(attrs["value"]))
119
+
120
+ # reserved0 is caretOffset for legacy reasons
121
+ @property
122
+ def reserved0(self):
123
+ return self.caretOffset
124
+
125
+ @reserved0.setter
126
+ def reserved0(self, value):
127
+ self.caretOffset = value
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/table_API_readme.txt ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This folder is a subpackage of ttLib. Each module here is a
2
+ specialized TT/OT table converter: they can convert raw data
3
+ to Python objects and vice versa. Usually you don't need to
4
+ use the modules directly: they are imported and used
5
+ automatically when needed by ttLib.
6
+
7
+ If you are writing you own table converter the following is
8
+ important.
9
+
10
+ The modules here have pretty strange names: this is due to the
11
+ fact that we need to map TT table tags (which are case sensitive)
12
+ to filenames (which on Mac and Win aren't case sensitive) as well
13
+ as to Python identifiers. The latter means it can only contain
14
+ [A-Za-z0-9_] and cannot start with a number.
15
+
16
+ ttLib provides functions to expand a tag into the format used here:
17
+
18
+ >>> from fontTools import ttLib
19
+ >>> ttLib.tagToIdentifier("FOO ")
20
+ 'F_O_O_'
21
+ >>> ttLib.tagToIdentifier("cvt ")
22
+ '_c_v_t'
23
+ >>> ttLib.tagToIdentifier("OS/2")
24
+ 'O_S_2f_2'
25
+ >>> ttLib.tagToIdentifier("glyf")
26
+ '_g_l_y_f'
27
+ >>>
28
+
29
+ And vice versa:
30
+
31
+ >>> ttLib.identifierToTag("F_O_O_")
32
+ 'FOO '
33
+ >>> ttLib.identifierToTag("_c_v_t")
34
+ 'cvt '
35
+ >>> ttLib.identifierToTag("O_S_2f_2")
36
+ 'OS/2'
37
+ >>> ttLib.identifierToTag("_g_l_y_f")
38
+ 'glyf'
39
+ >>>
40
+
41
+ Eg. the 'glyf' table converter lives in a Python file called:
42
+
43
+ _g_l_y_f.py
44
+
45
+ The converter itself is a class, named "table_" + expandedtag. Eg:
46
+
47
+ class table__g_l_y_f:
48
+ etc.
49
+
50
+ Note that if you _do_ need to use such modules or classes manually,
51
+ there are two convenient API functions that let you find them by tag:
52
+
53
+ >>> ttLib.getTableModule('glyf')
54
+ <module 'ttLib.tables._g_l_y_f'>
55
+ >>> ttLib.getTableClass('glyf')
56
+ <class ttLib.tables._g_l_y_f.table__g_l_y_f at 645f400>
57
+ >>>
58
+
59
+ You must subclass from DefaultTable.DefaultTable. It provides some default
60
+ behavior, as well as a constructor method (__init__) that you don't need to
61
+ override.
62
+
63
+ Your converter should minimally provide two methods:
64
+
65
+ class table_F_O_O_(DefaultTable.DefaultTable): # converter for table 'FOO '
66
+
67
+ def decompile(self, data, ttFont):
68
+ # 'data' is the raw table data. Unpack it into a
69
+ # Python data structure.
70
+ # 'ttFont' is a ttLib.TTfile instance, enabling you to
71
+ # refer to other tables. Do ***not*** keep a reference to
72
+ # it: it will cause a circular reference (ttFont saves
73
+ # a reference to us), and that means we'll be leaking
74
+ # memory. If you need to use it in other methods, just
75
+ # pass it around as a method argument.
76
+
77
+ def compile(self, ttFont):
78
+ # Return the raw data, as converted from the Python
79
+ # data structure.
80
+ # Again, 'ttFont' is there so you can access other tables.
81
+ # Same warning applies.
82
+
83
+ If you want to support TTX import/export as well, you need to provide two
84
+ additional methods:
85
+
86
+ def toXML(self, writer, ttFont):
87
+ # XXX
88
+
89
+ def fromXML(self, (name, attrs, content), ttFont):
90
+ # XXX
91
+
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/tables/ttProgram.py ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ttLib.tables.ttProgram.py -- Assembler/disassembler for TrueType bytecode programs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fontTools.misc.textTools import num2binary, binary2num, readHex, strjoin
6
+ import array
7
+ from io import StringIO
8
+ from typing import List
9
+ import re
10
+ import logging
11
+
12
+
13
+ log = logging.getLogger(__name__)
14
+
15
+ # fmt: off
16
+
17
+ # first, the list of instructions that eat bytes or words from the instruction stream
18
+
19
+ streamInstructions = [
20
+ #
21
+ # opcode mnemonic argBits descriptive name pops pushes eats from instruction stream pushes
22
+ #
23
+ (0x40, 'NPUSHB', 0, 'PushNBytes', 0, -1), # n, b1, b2,...bn b1,b2...bn
24
+ (0x41, 'NPUSHW', 0, 'PushNWords', 0, -1), # n, w1, w2,...w w1,w2...wn
25
+ (0xb0, 'PUSHB', 3, 'PushBytes', 0, -1), # b0, b1,..bn b0, b1, ...,bn
26
+ (0xb8, 'PUSHW', 3, 'PushWords', 0, -1), # w0,w1,..wn w0 ,w1, ...wn
27
+ ]
28
+
29
+
30
+ # next, the list of "normal" instructions
31
+
32
+ instructions = [
33
+ #
34
+ # opcode mnemonic argBits descriptive name pops pushes eats from instruction stream pushes
35
+ #
36
+ (0x7f, 'AA', 0, 'AdjustAngle', 1, 0), # p -
37
+ (0x64, 'ABS', 0, 'Absolute', 1, 1), # n |n|
38
+ (0x60, 'ADD', 0, 'Add', 2, 1), # n2, n1 (n1 + n2)
39
+ (0x27, 'ALIGNPTS', 0, 'AlignPts', 2, 0), # p2, p1 -
40
+ (0x3c, 'ALIGNRP', 0, 'AlignRelativePt', -1, 0), # p1, p2, ... , ploopvalue -
41
+ (0x5a, 'AND', 0, 'LogicalAnd', 2, 1), # e2, e1 b
42
+ (0x2b, 'CALL', 0, 'CallFunction', 1, 0), # f -
43
+ (0x67, 'CEILING', 0, 'Ceiling', 1, 1), # n ceil(n)
44
+ (0x25, 'CINDEX', 0, 'CopyXToTopStack', 1, 1), # k ek
45
+ (0x22, 'CLEAR', 0, 'ClearStack', -1, 0), # all items on the stack -
46
+ (0x4f, 'DEBUG', 0, 'DebugCall', 1, 0), # n -
47
+ (0x73, 'DELTAC1', 0, 'DeltaExceptionC1', -1, 0), # argn, cn, argn-1,cn-1, , arg1, c1 -
48
+ (0x74, 'DELTAC2', 0, 'DeltaExceptionC2', -1, 0), # argn, cn, argn-1,cn-1, , arg1, c1 -
49
+ (0x75, 'DELTAC3', 0, 'DeltaExceptionC3', -1, 0), # argn, cn, argn-1,cn-1, , arg1, c1 -
50
+ (0x5d, 'DELTAP1', 0, 'DeltaExceptionP1', -1, 0), # argn, pn, argn-1, pn-1, , arg1, p1 -
51
+ (0x71, 'DELTAP2', 0, 'DeltaExceptionP2', -1, 0), # argn, pn, argn-1, pn-1, , arg1, p1 -
52
+ (0x72, 'DELTAP3', 0, 'DeltaExceptionP3', -1, 0), # argn, pn, argn-1, pn-1, , arg1, p1 -
53
+ (0x24, 'DEPTH', 0, 'GetDepthStack', 0, 1), # - n
54
+ (0x62, 'DIV', 0, 'Divide', 2, 1), # n2, n1 (n1 * 64)/ n2
55
+ (0x20, 'DUP', 0, 'DuplicateTopStack', 1, 2), # e e, e
56
+ (0x59, 'EIF', 0, 'EndIf', 0, 0), # - -
57
+ (0x1b, 'ELSE', 0, 'Else', 0, 0), # - -
58
+ (0x2d, 'ENDF', 0, 'EndFunctionDefinition', 0, 0), # - -
59
+ (0x54, 'EQ', 0, 'Equal', 2, 1), # e2, e1 b
60
+ (0x57, 'EVEN', 0, 'Even', 1, 1), # e b
61
+ (0x2c, 'FDEF', 0, 'FunctionDefinition', 1, 0), # f -
62
+ (0x4e, 'FLIPOFF', 0, 'SetAutoFlipOff', 0, 0), # - -
63
+ (0x4d, 'FLIPON', 0, 'SetAutoFlipOn', 0, 0), # - -
64
+ (0x80, 'FLIPPT', 0, 'FlipPoint', -1, 0), # p1, p2, ..., ploopvalue -
65
+ (0x82, 'FLIPRGOFF', 0, 'FlipRangeOff', 2, 0), # h, l -
66
+ (0x81, 'FLIPRGON', 0, 'FlipRangeOn', 2, 0), # h, l -
67
+ (0x66, 'FLOOR', 0, 'Floor', 1, 1), # n floor(n)
68
+ (0x46, 'GC', 1, 'GetCoordOnPVector', 1, 1), # p c
69
+ (0x88, 'GETINFO', 0, 'GetInfo', 1, 1), # selector result
70
+ (0x91, 'GETVARIATION', 0, 'GetVariation', 0, -1), # - a1,..,an
71
+ (0x0d, 'GFV', 0, 'GetFVector', 0, 2), # - px, py
72
+ (0x0c, 'GPV', 0, 'GetPVector', 0, 2), # - px, py
73
+ (0x52, 'GT', 0, 'GreaterThan', 2, 1), # e2, e1 b
74
+ (0x53, 'GTEQ', 0, 'GreaterThanOrEqual', 2, 1), # e2, e1 b
75
+ (0x89, 'IDEF', 0, 'InstructionDefinition', 1, 0), # f -
76
+ (0x58, 'IF', 0, 'If', 1, 0), # e -
77
+ (0x8e, 'INSTCTRL', 0, 'SetInstrExecControl', 2, 0), # s, v -
78
+ (0x39, 'IP', 0, 'InterpolatePts', -1, 0), # p1, p2, ... , ploopvalue -
79
+ (0x0f, 'ISECT', 0, 'MovePtToIntersect', 5, 0), # a1, a0, b1, b0, p -
80
+ (0x30, 'IUP', 1, 'InterpolateUntPts', 0, 0), # - -
81
+ (0x1c, 'JMPR', 0, 'Jump', 1, 0), # offset -
82
+ (0x79, 'JROF', 0, 'JumpRelativeOnFalse', 2, 0), # e, offset -
83
+ (0x78, 'JROT', 0, 'JumpRelativeOnTrue', 2, 0), # e, offset -
84
+ (0x2a, 'LOOPCALL', 0, 'LoopAndCallFunction', 2, 0), # f, count -
85
+ (0x50, 'LT', 0, 'LessThan', 2, 1), # e2, e1 b
86
+ (0x51, 'LTEQ', 0, 'LessThenOrEqual', 2, 1), # e2, e1 b
87
+ (0x8b, 'MAX', 0, 'Maximum', 2, 1), # e2, e1 max(e1, e2)
88
+ (0x49, 'MD', 1, 'MeasureDistance', 2, 1), # p2,p1 d
89
+ (0x2e, 'MDAP', 1, 'MoveDirectAbsPt', 1, 0), # p -
90
+ (0xc0, 'MDRP', 5, 'MoveDirectRelPt', 1, 0), # p -
91
+ (0x3e, 'MIAP', 1, 'MoveIndirectAbsPt', 2, 0), # n, p -
92
+ (0x8c, 'MIN', 0, 'Minimum', 2, 1), # e2, e1 min(e1, e2)
93
+ (0x26, 'MINDEX', 0, 'MoveXToTopStack', 1, 1), # k ek
94
+ (0xe0, 'MIRP', 5, 'MoveIndirectRelPt', 2, 0), # n, p -
95
+ (0x4b, 'MPPEM', 0, 'MeasurePixelPerEm', 0, 1), # - ppem
96
+ (0x4c, 'MPS', 0, 'MeasurePointSize', 0, 1), # - pointSize
97
+ (0x3a, 'MSIRP', 1, 'MoveStackIndirRelPt', 2, 0), # d, p -
98
+ (0x63, 'MUL', 0, 'Multiply', 2, 1), # n2, n1 (n1 * n2)/64
99
+ (0x65, 'NEG', 0, 'Negate', 1, 1), # n -n
100
+ (0x55, 'NEQ', 0, 'NotEqual', 2, 1), # e2, e1 b
101
+ (0x5c, 'NOT', 0, 'LogicalNot', 1, 1), # e ( not e )
102
+ (0x6c, 'NROUND', 2, 'NoRound', 1, 1), # n1 n2
103
+ (0x56, 'ODD', 0, 'Odd', 1, 1), # e b
104
+ (0x5b, 'OR', 0, 'LogicalOr', 2, 1), # e2, e1 b
105
+ (0x21, 'POP', 0, 'PopTopStack', 1, 0), # e -
106
+ (0x45, 'RCVT', 0, 'ReadCVT', 1, 1), # location value
107
+ (0x7d, 'RDTG', 0, 'RoundDownToGrid', 0, 0), # - -
108
+ (0x7a, 'ROFF', 0, 'RoundOff', 0, 0), # - -
109
+ (0x8a, 'ROLL', 0, 'RollTopThreeStack', 3, 3), # a,b,c b,a,c
110
+ (0x68, 'ROUND', 2, 'Round', 1, 1), # n1 n2
111
+ (0x43, 'RS', 0, 'ReadStore', 1, 1), # n v
112
+ (0x3d, 'RTDG', 0, 'RoundToDoubleGrid', 0, 0), # - -
113
+ (0x18, 'RTG', 0, 'RoundToGrid', 0, 0), # - -
114
+ (0x19, 'RTHG', 0, 'RoundToHalfGrid', 0, 0), # - -
115
+ (0x7c, 'RUTG', 0, 'RoundUpToGrid', 0, 0), # - -
116
+ (0x77, 'S45ROUND', 0, 'SuperRound45Degrees', 1, 0), # n -
117
+ (0x7e, 'SANGW', 0, 'SetAngleWeight', 1, 0), # weight -
118
+ (0x85, 'SCANCTRL', 0, 'ScanConversionControl', 1, 0), # n -
119
+ (0x8d, 'SCANTYPE', 0, 'ScanType', 1, 0), # n -
120
+ (0x48, 'SCFS', 0, 'SetCoordFromStackFP', 2, 0), # c, p -
121
+ (0x1d, 'SCVTCI', 0, 'SetCVTCutIn', 1, 0), # n -
122
+ (0x5e, 'SDB', 0, 'SetDeltaBaseInGState', 1, 0), # n -
123
+ (0x86, 'SDPVTL', 1, 'SetDualPVectorToLine', 2, 0), # p2, p1 -
124
+ (0x5f, 'SDS', 0, 'SetDeltaShiftInGState', 1, 0), # n -
125
+ (0x0b, 'SFVFS', 0, 'SetFVectorFromStack', 2, 0), # y, x -
126
+ (0x04, 'SFVTCA', 1, 'SetFVectorToAxis', 0, 0), # - -
127
+ (0x08, 'SFVTL', 1, 'SetFVectorToLine', 2, 0), # p2, p1 -
128
+ (0x0e, 'SFVTPV', 0, 'SetFVectorToPVector', 0, 0), # - -
129
+ (0x34, 'SHC', 1, 'ShiftContourByLastPt', 1, 0), # c -
130
+ (0x32, 'SHP', 1, 'ShiftPointByLastPoint', -1, 0), # p1, p2, ..., ploopvalue -
131
+ (0x38, 'SHPIX', 0, 'ShiftZoneByPixel', -1, 0), # d, p1, p2, ..., ploopvalue -
132
+ (0x36, 'SHZ', 1, 'ShiftZoneByLastPoint', 1, 0), # e -
133
+ (0x17, 'SLOOP', 0, 'SetLoopVariable', 1, 0), # n -
134
+ (0x1a, 'SMD', 0, 'SetMinimumDistance', 1, 0), # distance -
135
+ (0x0a, 'SPVFS', 0, 'SetPVectorFromStack', 2, 0), # y, x -
136
+ (0x02, 'SPVTCA', 1, 'SetPVectorToAxis', 0, 0), # - -
137
+ (0x06, 'SPVTL', 1, 'SetPVectorToLine', 2, 0), # p2, p1 -
138
+ (0x76, 'SROUND', 0, 'SuperRound', 1, 0), # n -
139
+ (0x10, 'SRP0', 0, 'SetRefPoint0', 1, 0), # p -
140
+ (0x11, 'SRP1', 0, 'SetRefPoint1', 1, 0), # p -
141
+ (0x12, 'SRP2', 0, 'SetRefPoint2', 1, 0), # p -
142
+ (0x1f, 'SSW', 0, 'SetSingleWidth', 1, 0), # n -
143
+ (0x1e, 'SSWCI', 0, 'SetSingleWidthCutIn', 1, 0), # n -
144
+ (0x61, 'SUB', 0, 'Subtract', 2, 1), # n2, n1 (n1 - n2)
145
+ (0x00, 'SVTCA', 1, 'SetFPVectorToAxis', 0, 0), # - -
146
+ (0x23, 'SWAP', 0, 'SwapTopStack', 2, 2), # e2, e1 e1, e2
147
+ (0x13, 'SZP0', 0, 'SetZonePointer0', 1, 0), # n -
148
+ (0x14, 'SZP1', 0, 'SetZonePointer1', 1, 0), # n -
149
+ (0x15, 'SZP2', 0, 'SetZonePointer2', 1, 0), # n -
150
+ (0x16, 'SZPS', 0, 'SetZonePointerS', 1, 0), # n -
151
+ (0x29, 'UTP', 0, 'UnTouchPt', 1, 0), # p -
152
+ (0x70, 'WCVTF', 0, 'WriteCVTInFUnits', 2, 0), # n, l -
153
+ (0x44, 'WCVTP', 0, 'WriteCVTInPixels', 2, 0), # v, l -
154
+ (0x42, 'WS', 0, 'WriteStore', 2, 0), # v, l -
155
+ ]
156
+
157
+ # fmt: on
158
+
159
+
160
+ def bitRepr(value, bits):
161
+ s = ""
162
+ for i in range(bits):
163
+ s = "01"[value & 0x1] + s
164
+ value = value >> 1
165
+ return s
166
+
167
+
168
+ _mnemonicPat = re.compile(r"[A-Z][A-Z0-9]*$")
169
+
170
+
171
+ def _makeDict(instructionList):
172
+ opcodeDict = {}
173
+ mnemonicDict = {}
174
+ for op, mnemonic, argBits, name, pops, pushes in instructionList:
175
+ assert _mnemonicPat.match(mnemonic)
176
+ mnemonicDict[mnemonic] = op, argBits, name
177
+ if argBits:
178
+ argoffset = op
179
+ for i in range(1 << argBits):
180
+ opcodeDict[op + i] = mnemonic, argBits, argoffset, name
181
+ else:
182
+ opcodeDict[op] = mnemonic, 0, 0, name
183
+ return opcodeDict, mnemonicDict
184
+
185
+
186
+ streamOpcodeDict, streamMnemonicDict = _makeDict(streamInstructions)
187
+ opcodeDict, mnemonicDict = _makeDict(instructions)
188
+
189
+
190
+ class tt_instructions_error(Exception):
191
+ def __init__(self, error):
192
+ self.error = error
193
+
194
+ def __str__(self):
195
+ return "TT instructions error: %s" % repr(self.error)
196
+
197
+
198
+ _comment = r"/\*.*?\*/"
199
+ _instruction = r"([A-Z][A-Z0-9]*)\s*\[(.*?)\]"
200
+ _number = r"-?[0-9]+"
201
+ _token = "(%s)|(%s)|(%s)" % (_instruction, _number, _comment)
202
+
203
+ _tokenRE = re.compile(_token)
204
+ _whiteRE = re.compile(r"\s*")
205
+
206
+ _pushCountPat = re.compile(r"[A-Z][A-Z0-9]*\s*\[.*?\]\s*/\* ([0-9]+).*?\*/")
207
+
208
+ _indentRE = re.compile(r"^FDEF|IF|ELSE\[ \]\t.+")
209
+ _unindentRE = re.compile(r"^ELSE|ENDF|EIF\[ \]\t.+")
210
+
211
+
212
+ def _skipWhite(data, pos):
213
+ m = _whiteRE.match(data, pos)
214
+ newPos = m.regs[0][1]
215
+ assert newPos >= pos
216
+ return newPos
217
+
218
+
219
+ class Program(object):
220
+ def __init__(self) -> None:
221
+ pass
222
+
223
+ def fromBytecode(self, bytecode: bytes) -> None:
224
+ self.bytecode = array.array("B", bytecode)
225
+ if hasattr(self, "assembly"):
226
+ del self.assembly
227
+
228
+ def fromAssembly(self, assembly: List[str] | str) -> None:
229
+ if isinstance(assembly, list):
230
+ self.assembly = assembly
231
+ elif isinstance(assembly, str):
232
+ self.assembly = assembly.splitlines()
233
+ else:
234
+ raise TypeError(f"expected str or List[str], got {type(assembly).__name__}")
235
+ if hasattr(self, "bytecode"):
236
+ del self.bytecode
237
+
238
+ def getBytecode(self) -> bytes:
239
+ if not hasattr(self, "bytecode"):
240
+ self._assemble()
241
+ return self.bytecode.tobytes()
242
+
243
+ def getAssembly(self, preserve=True) -> List[str]:
244
+ if not hasattr(self, "assembly"):
245
+ self._disassemble(preserve=preserve)
246
+ return self.assembly
247
+
248
+ def toXML(self, writer, ttFont) -> None:
249
+ if (
250
+ not hasattr(ttFont, "disassembleInstructions")
251
+ or ttFont.disassembleInstructions
252
+ ):
253
+ try:
254
+ assembly = self.getAssembly()
255
+ except:
256
+ import traceback
257
+
258
+ tmp = StringIO()
259
+ traceback.print_exc(file=tmp)
260
+ msg = "An exception occurred during the decompilation of glyph program:\n\n"
261
+ msg += tmp.getvalue()
262
+ log.error(msg)
263
+ writer.begintag("bytecode")
264
+ writer.newline()
265
+ writer.comment(msg.strip())
266
+ writer.newline()
267
+ writer.dumphex(self.getBytecode())
268
+ writer.endtag("bytecode")
269
+ writer.newline()
270
+ else:
271
+ if not assembly:
272
+ return
273
+ writer.begintag("assembly")
274
+ writer.newline()
275
+ i = 0
276
+ indent = 0
277
+ nInstr = len(assembly)
278
+ while i < nInstr:
279
+ instr = assembly[i]
280
+ if _unindentRE.match(instr):
281
+ indent -= 1
282
+ writer.write(writer.indentwhite * indent)
283
+ writer.write(instr)
284
+ writer.newline()
285
+ m = _pushCountPat.match(instr)
286
+ i = i + 1
287
+ if m:
288
+ nValues = int(m.group(1))
289
+ line: List[str] = []
290
+ j = 0
291
+ for j in range(nValues):
292
+ if j and not (j % 25):
293
+ writer.write(writer.indentwhite * indent)
294
+ writer.write(" ".join(line))
295
+ writer.newline()
296
+ line = []
297
+ line.append(assembly[i + j])
298
+ writer.write(writer.indentwhite * indent)
299
+ writer.write(" ".join(line))
300
+ writer.newline()
301
+ i = i + j + 1
302
+ if _indentRE.match(instr):
303
+ indent += 1
304
+ writer.endtag("assembly")
305
+ writer.newline()
306
+ else:
307
+ bytecode = self.getBytecode()
308
+ if not bytecode:
309
+ return
310
+ writer.begintag("bytecode")
311
+ writer.newline()
312
+ writer.dumphex(bytecode)
313
+ writer.endtag("bytecode")
314
+ writer.newline()
315
+
316
+ def fromXML(self, name, attrs, content, ttFont) -> None:
317
+ if name == "assembly":
318
+ self.fromAssembly(strjoin(content))
319
+ self._assemble()
320
+ del self.assembly
321
+ else:
322
+ assert name == "bytecode"
323
+ self.fromBytecode(readHex(content))
324
+
325
+ def _assemble(self) -> None:
326
+ assembly = " ".join(getattr(self, "assembly", []))
327
+ bytecode: List[int] = []
328
+ push = bytecode.append
329
+ lenAssembly = len(assembly)
330
+ pos = _skipWhite(assembly, 0)
331
+ while pos < lenAssembly:
332
+ m = _tokenRE.match(assembly, pos)
333
+ if m is None:
334
+ raise tt_instructions_error(
335
+ "Syntax error in TT program (%s)" % assembly[pos - 5 : pos + 15]
336
+ )
337
+ dummy, mnemonic, arg, number, comment = m.groups()
338
+ pos = m.regs[0][1]
339
+ if comment:
340
+ pos = _skipWhite(assembly, pos)
341
+ continue
342
+
343
+ arg = arg.strip()
344
+ if mnemonic.startswith("INSTR"):
345
+ # Unknown instruction
346
+ op = int(mnemonic[5:])
347
+ push(op)
348
+ elif mnemonic not in ("PUSH", "NPUSHB", "NPUSHW", "PUSHB", "PUSHW"):
349
+ op, argBits, name = mnemonicDict[mnemonic]
350
+ if len(arg) != argBits:
351
+ raise tt_instructions_error(
352
+ "Incorrect number of argument bits (%s[%s])" % (mnemonic, arg)
353
+ )
354
+ if arg:
355
+ arg = binary2num(arg)
356
+ push(op + arg)
357
+ else:
358
+ push(op)
359
+ else:
360
+ args = []
361
+ pos = _skipWhite(assembly, pos)
362
+ while pos < lenAssembly:
363
+ m = _tokenRE.match(assembly, pos)
364
+ if m is None:
365
+ raise tt_instructions_error(
366
+ "Syntax error in TT program (%s)" % assembly[pos : pos + 15]
367
+ )
368
+ dummy, _mnemonic, arg, number, comment = m.groups()
369
+ if number is None and comment is None:
370
+ break
371
+ pos = m.regs[0][1]
372
+ pos = _skipWhite(assembly, pos)
373
+ if comment is not None:
374
+ continue
375
+ args.append(int(number))
376
+ nArgs = len(args)
377
+ if mnemonic == "PUSH":
378
+ # Automatically choose the most compact representation
379
+ nWords = 0
380
+ while nArgs:
381
+ while (
382
+ nWords < nArgs
383
+ and nWords < 255
384
+ and not (0 <= args[nWords] <= 255)
385
+ ):
386
+ nWords += 1
387
+ nBytes = 0
388
+ while (
389
+ nWords + nBytes < nArgs
390
+ and nBytes < 255
391
+ and 0 <= args[nWords + nBytes] <= 255
392
+ ):
393
+ nBytes += 1
394
+ if (
395
+ nBytes < 2
396
+ and nWords + nBytes < 255
397
+ and nWords + nBytes != nArgs
398
+ ):
399
+ # Will write bytes as words
400
+ nWords += nBytes
401
+ continue
402
+
403
+ # Write words
404
+ if nWords:
405
+ if nWords <= 8:
406
+ op, argBits, name = streamMnemonicDict["PUSHW"]
407
+ op = op + nWords - 1
408
+ push(op)
409
+ else:
410
+ op, argBits, name = streamMnemonicDict["NPUSHW"]
411
+ push(op)
412
+ push(nWords)
413
+ for value in args[:nWords]:
414
+ assert -32768 <= value < 32768, (
415
+ "PUSH value out of range %d" % value
416
+ )
417
+ push((value >> 8) & 0xFF)
418
+ push(value & 0xFF)
419
+
420
+ # Write bytes
421
+ if nBytes:
422
+ pass
423
+ if nBytes <= 8:
424
+ op, argBits, name = streamMnemonicDict["PUSHB"]
425
+ op = op + nBytes - 1
426
+ push(op)
427
+ else:
428
+ op, argBits, name = streamMnemonicDict["NPUSHB"]
429
+ push(op)
430
+ push(nBytes)
431
+ for value in args[nWords : nWords + nBytes]:
432
+ push(value)
433
+
434
+ nTotal = nWords + nBytes
435
+ args = args[nTotal:]
436
+ nArgs -= nTotal
437
+ nWords = 0
438
+ else:
439
+ # Write exactly what we've been asked to
440
+ words = mnemonic[-1] == "W"
441
+ op, argBits, name = streamMnemonicDict[mnemonic]
442
+ if mnemonic[0] != "N":
443
+ assert nArgs <= 8, nArgs
444
+ op = op + nArgs - 1
445
+ push(op)
446
+ else:
447
+ assert nArgs < 256
448
+ push(op)
449
+ push(nArgs)
450
+ if words:
451
+ for value in args:
452
+ assert -32768 <= value < 32768, (
453
+ "PUSHW value out of range %d" % value
454
+ )
455
+ push((value >> 8) & 0xFF)
456
+ push(value & 0xFF)
457
+ else:
458
+ for value in args:
459
+ assert 0 <= value < 256, (
460
+ "PUSHB value out of range %d" % value
461
+ )
462
+ push(value)
463
+
464
+ pos = _skipWhite(assembly, pos)
465
+
466
+ if bytecode:
467
+ assert max(bytecode) < 256 and min(bytecode) >= 0
468
+ self.bytecode = array.array("B", bytecode)
469
+
470
+ def _disassemble(self, preserve=False) -> None:
471
+ assembly = []
472
+ i = 0
473
+ bytecode = getattr(self, "bytecode", [])
474
+ numBytecode = len(bytecode)
475
+ while i < numBytecode:
476
+ op = bytecode[i]
477
+ try:
478
+ mnemonic, argBits, argoffset, name = opcodeDict[op]
479
+ except KeyError:
480
+ if op in streamOpcodeDict:
481
+ values = []
482
+
483
+ # Merge consecutive PUSH operations
484
+ while bytecode[i] in streamOpcodeDict:
485
+ op = bytecode[i]
486
+ mnemonic, argBits, argoffset, name = streamOpcodeDict[op]
487
+ words = mnemonic[-1] == "W"
488
+ if argBits:
489
+ nValues = op - argoffset + 1
490
+ else:
491
+ i = i + 1
492
+ nValues = bytecode[i]
493
+ i = i + 1
494
+ assert nValues > 0
495
+ if not words:
496
+ for j in range(nValues):
497
+ value = bytecode[i]
498
+ values.append(repr(value))
499
+ i = i + 1
500
+ else:
501
+ for j in range(nValues):
502
+ # cast to signed int16
503
+ value = (bytecode[i] << 8) | bytecode[i + 1]
504
+ if value >= 0x8000:
505
+ value = value - 0x10000
506
+ values.append(repr(value))
507
+ i = i + 2
508
+ if preserve:
509
+ break
510
+
511
+ if not preserve:
512
+ mnemonic = "PUSH"
513
+ nValues = len(values)
514
+ if nValues == 1:
515
+ assembly.append("%s[ ] /* 1 value pushed */" % mnemonic)
516
+ else:
517
+ assembly.append(
518
+ "%s[ ] /* %s values pushed */" % (mnemonic, nValues)
519
+ )
520
+ assembly.extend(values)
521
+ else:
522
+ assembly.append("INSTR%d[ ]" % op)
523
+ i = i + 1
524
+ else:
525
+ if argBits:
526
+ assembly.append(
527
+ mnemonic
528
+ + "[%s] /* %s */" % (num2binary(op - argoffset, argBits), name)
529
+ )
530
+ else:
531
+ assembly.append(mnemonic + "[ ] /* %s */" % name)
532
+ i = i + 1
533
+ self.assembly = assembly
534
+
535
+ def __bool__(self) -> bool:
536
+ """
537
+ >>> p = Program()
538
+ >>> bool(p)
539
+ False
540
+ >>> bc = array.array("B", [0])
541
+ >>> p.fromBytecode(bc)
542
+ >>> bool(p)
543
+ True
544
+ >>> p.bytecode.pop()
545
+ 0
546
+ >>> bool(p)
547
+ False
548
+
549
+ >>> p = Program()
550
+ >>> asm = ['SVTCA[0]']
551
+ >>> p.fromAssembly(asm)
552
+ >>> bool(p)
553
+ True
554
+ >>> p.assembly.pop()
555
+ 'SVTCA[0]'
556
+ >>> bool(p)
557
+ False
558
+ """
559
+ return (hasattr(self, "assembly") and len(self.assembly) > 0) or (
560
+ hasattr(self, "bytecode") and len(self.bytecode) > 0
561
+ )
562
+
563
+ __nonzero__ = __bool__
564
+
565
+ def __eq__(self, other) -> bool:
566
+ if type(self) != type(other):
567
+ return NotImplemented
568
+ return self.__dict__ == other.__dict__
569
+
570
+ def __ne__(self, other) -> bool:
571
+ result = self.__eq__(other)
572
+ return result if result is NotImplemented else not result
573
+
574
+
575
+ def _test():
576
+ """
577
+ >>> _test()
578
+ True
579
+ """
580
+
581
+ bc = b"""@;:9876543210/.-,+*)(\'&%$#"! \037\036\035\034\033\032\031\030\027\026\025\024\023\022\021\020\017\016\015\014\013\012\011\010\007\006\005\004\003\002\001\000,\001\260\030CXEj\260\031C`\260F#D#\020 \260FN\360M/\260\000\022\033!#\0213Y-,\001\260\030CX\260\005+\260\000\023K\260\024PX\261\000@8Y\260\006+\033!#\0213Y-,\001\260\030CXN\260\003%\020\362!\260\000\022M\033 E\260\004%\260\004%#Jad\260(RX!#\020\326\033\260\003%\020\362!\260\000\022YY-,\260\032CX!!\033\260\002%\260\002%I\260\003%\260\003%Ja d\260\020PX!!!\033\260\003%\260\003%I\260\000PX\260\000PX\270\377\3428!\033\260\0208!Y\033\260\000RX\260\0368!\033\270\377\3608!YYYY-,\001\260\030CX\260\005+\260\000\023K\260\024PX\271\000\000\377\3008Y\260\006+\033!#\0213Y-,N\001\212\020\261F\031CD\260\000\024\261\000F\342\260\000\025\271\000\000\377\3608\000\260\000<\260(+\260\002%\020\260\000<-,\001\030\260\000/\260\001\024\362\260\001\023\260\001\025M\260\000\022-,\001\260\030CX\260\005+\260\000\023\271\000\000\377\3408\260\006+\033!#\0213Y-,\001\260\030CXEdj#Edi\260\031Cd``\260F#D#\020 \260F\360/\260\000\022\033!! \212 \212RX\0213\033!!YY-,\001\261\013\012C#Ce\012-,\000\261\012\013C#C\013-,\000\260F#p\261\001F>\001\260F#p\261\002FE:\261\002\000\010\015-,\260\022+\260\002%E\260\002%Ej\260@\213`\260\002%#D!!!-,\260\023+\260\002%E\260\002%Ej\270\377\300\214`\260\002%#D!!!-,\260\000\260\022+!!!-,\260\000\260\023+!!!-,\001\260\006C\260\007Ce\012-, i\260@a\260\000\213 \261,\300\212\214\270\020\000b`+\014d#da\\X\260\003aY-,\261\000\003%EhT\260\034KPZX\260\003%E\260\003%E`h \260\004%#D\260\004%#D\033\260\003% Eh \212#D\260\003%Eh`\260\003%#DY-,\260\003% Eh \212#D\260\003%Edhe`\260\004%\260\001`#D-,\260\011CX\207!\300\033\260\022CX\207E\260\021+\260G#D\260Gz\344\033\003\212E\030i \260G#D\212\212\207 \260\240QX\260\021+\260G#D\260Gz\344\033!\260Gz\344YYY\030-, \212E#Eh`D-,EjB-,\001\030/-,\001\260\030CX\260\004%\260\004%Id#Edi\260@\213a \260\200bj\260\002%\260\002%a\214\260\031C`\260F#D!\212\020\260F\366!\033!!!!Y-,\001\260\030CX\260\002%E\260\002%Ed`j\260\003%Eja \260\004%Ej \212\213e\260\004%#D\214\260\003%#D!!\033 EjD EjDY-,\001 E\260\000U\260\030CZXEh#Ei\260@\213a \260\200bj \212#a \260\003%\213e\260\004%#D\214\260\003%#D!!\033!!\260\031+Y-,\001\212\212Ed#EdadB-,\260\004%\260\004%\260\031+\260\030CX\260\004%\260\004%\260\003%\260\033+\001\260\002%C\260@T\260\002%C\260\000TZX\260\003% E\260@aDY\260\002%C\260\000T\260\002%C\260@TZX\260\004% E\260@`DYY!!!!-,\001KRXC\260\002%E#aD\033!!Y-,\001KRXC\260\002%E#`D\033!!Y-,KRXED\033!!Y-,\001 \260\003%#I\260@`\260 c \260\000RX#\260\002%8#\260\002%e8\000\212c8\033!!!!!Y\001-,KPXED\033!!Y-,\001\260\005%\020# \212\365\000\260\001`#\355\354-,\001\260\005%\020# \212\365\000\260\001a#\355\354-,\001\260\006%\020\365\000\355\354-,F#F`\212\212F# F\212`\212a\270\377\200b# \020#\212\261KK\212pE` \260\000PX\260\001a\270\377\272\213\033\260F\214Y\260\020`h\001:-, E\260\003%FRX\260\002%F ha\260\003%\260\003%?#!8\033!\021Y-, E\260\003%FPX\260\002%F ha\260\003%\260\003%?#!8\033!\021Y-,\000\260\007C\260\006C\013-,\212\020\354-,\260\014CX!\033 F\260\000RX\270\377\3608\033\260\0208YY-, \260\000UX\270\020\000c\260\003%Ed\260\003%Eda\260\000SX\260\002\033\260@a\260\003Y%EiSXED\033!!Y\033!\260\002%E\260\002%Ead\260(QXED\033!!YY-,!!\014d#d\213\270@\000b-,!\260\200QX\014d#d\213\270 \000b\033\262\000@/+Y\260\002`-,!\260\300QX\014d#d\213\270\025Ub\033\262\000\200/+Y\260\002`-,\014d#d\213\270@\000b`#!-,KSX\260\004%\260\004%Id#Edi\260@\213a \260\200bj\260\002%\260\002%a\214\260F#D!\212\020\260F\366!\033!\212\021#\022 9/Y-,\260\002%\260\002%Id\260\300TX\270\377\3708\260\0108\033!!Y-,\260\023CX\003\033\002Y-,\260\023CX\002\033\003Y-,\260\012+#\020 <\260\027+-,\260\002%\270\377\3608\260(+\212\020# \320#\260\020+\260\005CX\300\033<Y \020\021\260\000\022\001-,KS#KQZX8\033!!Y-,\001\260\002%\020\320#\311\001\260\001\023\260\000\024\020\260\001<\260\001\026-,\001\260\000\023\260\001\260\003%I\260\003\0278\260\001\023-,KS#KQZX E\212`D\033!!Y-, 9/-"""
582
+
583
+ p = Program()
584
+ p.fromBytecode(bc)
585
+ asm = p.getAssembly(preserve=True)
586
+ p.fromAssembly(asm)
587
+ print(bc == p.getBytecode())
588
+
589
+
590
+ if __name__ == "__main__":
591
+ import sys
592
+ import doctest
593
+
594
+ sys.exit(doctest.testmod().failed)
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttLib/woff2.py ADDED
@@ -0,0 +1,1683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from io import BytesIO
2
+ import sys
3
+ import array
4
+ import struct
5
+ from collections import OrderedDict
6
+ from fontTools.misc import sstruct
7
+ from fontTools.misc.arrayTools import calcIntBounds
8
+ from fontTools.misc.textTools import Tag, bytechr, byteord, bytesjoin, pad
9
+ from fontTools.ttLib import (
10
+ TTFont,
11
+ TTLibError,
12
+ getTableModule,
13
+ getTableClass,
14
+ getSearchRange,
15
+ )
16
+ from fontTools.ttLib.sfnt import (
17
+ SFNTReader,
18
+ SFNTWriter,
19
+ DirectoryEntry,
20
+ WOFFFlavorData,
21
+ sfntDirectoryFormat,
22
+ sfntDirectorySize,
23
+ SFNTDirectoryEntry,
24
+ sfntDirectoryEntrySize,
25
+ calcChecksum,
26
+ )
27
+ from fontTools.ttLib.tables import ttProgram, _g_l_y_f
28
+ import logging
29
+
30
+
31
+ log = logging.getLogger("fontTools.ttLib.woff2")
32
+
33
+ haveBrotli = False
34
+ try:
35
+ try:
36
+ import brotlicffi as brotli
37
+ except ImportError:
38
+ import brotli
39
+ haveBrotli = True
40
+ except ImportError:
41
+ pass
42
+
43
+
44
+ class WOFF2Reader(SFNTReader):
45
+ flavor = "woff2"
46
+
47
+ def __init__(self, file, checkChecksums=0, fontNumber=-1):
48
+ if not haveBrotli:
49
+ log.error(
50
+ "The WOFF2 decoder requires the Brotli Python extension, available at: "
51
+ "https://github.com/google/brotli"
52
+ )
53
+ raise ImportError("No module named brotli")
54
+
55
+ self.file = file
56
+
57
+ signature = Tag(self.file.read(4))
58
+ if signature != b"wOF2":
59
+ raise TTLibError("Not a WOFF2 font (bad signature)")
60
+
61
+ self.file.seek(0)
62
+ self.DirectoryEntry = WOFF2DirectoryEntry
63
+ data = self.file.read(woff2DirectorySize)
64
+ if len(data) != woff2DirectorySize:
65
+ raise TTLibError("Not a WOFF2 font (not enough data)")
66
+ sstruct.unpack(woff2DirectoryFormat, data, self)
67
+
68
+ self.tables = OrderedDict()
69
+ offset = 0
70
+ for i in range(self.numTables):
71
+ entry = self.DirectoryEntry()
72
+ entry.fromFile(self.file)
73
+ tag = Tag(entry.tag)
74
+ self.tables[tag] = entry
75
+ entry.offset = offset
76
+ offset += entry.length
77
+
78
+ totalUncompressedSize = offset
79
+ compressedData = self.file.read(self.totalCompressedSize)
80
+ decompressedData = brotli.decompress(compressedData)
81
+ if len(decompressedData) != totalUncompressedSize:
82
+ raise TTLibError(
83
+ "unexpected size for decompressed font data: expected %d, found %d"
84
+ % (totalUncompressedSize, len(decompressedData))
85
+ )
86
+ self.transformBuffer = BytesIO(decompressedData)
87
+
88
+ self.file.seek(0, 2)
89
+ if self.length != self.file.tell():
90
+ raise TTLibError("reported 'length' doesn't match the actual file size")
91
+
92
+ self.flavorData = WOFF2FlavorData(self)
93
+
94
+ # make empty TTFont to store data while reconstructing tables
95
+ self.ttFont = TTFont(recalcBBoxes=False, recalcTimestamp=False)
96
+
97
+ def __getitem__(self, tag):
98
+ """Fetch the raw table data. Reconstruct transformed tables."""
99
+ entry = self.tables[Tag(tag)]
100
+ if not hasattr(entry, "data"):
101
+ if entry.transformed:
102
+ entry.data = self.reconstructTable(tag)
103
+ else:
104
+ entry.data = entry.loadData(self.transformBuffer)
105
+ return entry.data
106
+
107
+ def reconstructTable(self, tag):
108
+ """Reconstruct table named 'tag' from transformed data."""
109
+ entry = self.tables[Tag(tag)]
110
+ rawData = entry.loadData(self.transformBuffer)
111
+ if tag == "glyf":
112
+ # no need to pad glyph data when reconstructing
113
+ padding = self.padding if hasattr(self, "padding") else None
114
+ data = self._reconstructGlyf(rawData, padding)
115
+ elif tag == "loca":
116
+ data = self._reconstructLoca()
117
+ elif tag == "hmtx":
118
+ data = self._reconstructHmtx(rawData)
119
+ else:
120
+ raise TTLibError("transform for table '%s' is unknown" % tag)
121
+ return data
122
+
123
+ def _reconstructGlyf(self, data, padding=None):
124
+ """Return recostructed glyf table data, and set the corresponding loca's
125
+ locations. Optionally pad glyph offsets to the specified number of bytes.
126
+ """
127
+ self.ttFont["loca"] = WOFF2LocaTable()
128
+ glyfTable = self.ttFont["glyf"] = WOFF2GlyfTable()
129
+ glyfTable.reconstruct(data, self.ttFont)
130
+ if padding:
131
+ glyfTable.padding = padding
132
+ data = glyfTable.compile(self.ttFont)
133
+ return data
134
+
135
+ def _reconstructLoca(self):
136
+ """Return reconstructed loca table data."""
137
+ if "loca" not in self.ttFont:
138
+ # make sure glyf is reconstructed first
139
+ self.tables["glyf"].data = self.reconstructTable("glyf")
140
+ locaTable = self.ttFont["loca"]
141
+ data = locaTable.compile(self.ttFont)
142
+ if len(data) != self.tables["loca"].origLength:
143
+ raise TTLibError(
144
+ "reconstructed 'loca' table doesn't match original size: "
145
+ "expected %d, found %d" % (self.tables["loca"].origLength, len(data))
146
+ )
147
+ return data
148
+
149
+ def _reconstructHmtx(self, data):
150
+ """Return reconstructed hmtx table data."""
151
+ # Before reconstructing 'hmtx' table we need to parse other tables:
152
+ # 'glyf' is required for reconstructing the sidebearings from the glyphs'
153
+ # bounding box; 'hhea' is needed for the numberOfHMetrics field.
154
+ if "glyf" in self.flavorData.transformedTables:
155
+ # transformed 'glyf' table is self-contained, thus 'loca' not needed
156
+ tableDependencies = ("maxp", "hhea", "glyf")
157
+ else:
158
+ # decompiling untransformed 'glyf' requires 'loca', which requires 'head'
159
+ tableDependencies = ("maxp", "head", "hhea", "loca", "glyf")
160
+ for tag in tableDependencies:
161
+ self._decompileTable(tag)
162
+ hmtxTable = self.ttFont["hmtx"] = WOFF2HmtxTable()
163
+ hmtxTable.reconstruct(data, self.ttFont)
164
+ data = hmtxTable.compile(self.ttFont)
165
+ return data
166
+
167
+ def _decompileTable(self, tag):
168
+ """Decompile table data and store it inside self.ttFont."""
169
+ data = self[tag]
170
+ if self.ttFont.isLoaded(tag):
171
+ return self.ttFont[tag]
172
+ tableClass = getTableClass(tag)
173
+ table = tableClass(tag)
174
+ self.ttFont.tables[tag] = table
175
+ table.decompile(data, self.ttFont)
176
+
177
+
178
+ class WOFF2Writer(SFNTWriter):
179
+ flavor = "woff2"
180
+
181
+ def __init__(
182
+ self,
183
+ file,
184
+ numTables,
185
+ sfntVersion="\000\001\000\000",
186
+ flavor=None,
187
+ flavorData=None,
188
+ ):
189
+ if not haveBrotli:
190
+ log.error(
191
+ "The WOFF2 encoder requires the Brotli Python extension, available at: "
192
+ "https://github.com/google/brotli"
193
+ )
194
+ raise ImportError("No module named brotli")
195
+
196
+ self.file = file
197
+ self.numTables = numTables
198
+ self.sfntVersion = Tag(sfntVersion)
199
+ self.flavorData = WOFF2FlavorData(data=flavorData)
200
+
201
+ self.directoryFormat = woff2DirectoryFormat
202
+ self.directorySize = woff2DirectorySize
203
+ self.DirectoryEntry = WOFF2DirectoryEntry
204
+
205
+ self.signature = Tag("wOF2")
206
+
207
+ self.nextTableOffset = 0
208
+ self.transformBuffer = BytesIO()
209
+
210
+ self.tables = OrderedDict()
211
+
212
+ # make empty TTFont to store data while normalising and transforming tables
213
+ self.ttFont = TTFont(recalcBBoxes=False, recalcTimestamp=False)
214
+
215
+ def __setitem__(self, tag, data):
216
+ """Associate new entry named 'tag' with raw table data."""
217
+ if tag in self.tables:
218
+ raise TTLibError("cannot rewrite '%s' table" % tag)
219
+ if tag == "DSIG":
220
+ # always drop DSIG table, since the encoding process can invalidate it
221
+ self.numTables -= 1
222
+ return
223
+
224
+ entry = self.DirectoryEntry()
225
+ entry.tag = Tag(tag)
226
+ entry.flags = getKnownTagIndex(entry.tag)
227
+ # WOFF2 table data are written to disk only on close(), after all tags
228
+ # have been specified
229
+ entry.data = data
230
+
231
+ self.tables[tag] = entry
232
+
233
+ def close(self):
234
+ """All tags must have been specified. Now write the table data and directory."""
235
+ if len(self.tables) != self.numTables:
236
+ raise TTLibError(
237
+ "wrong number of tables; expected %d, found %d"
238
+ % (self.numTables, len(self.tables))
239
+ )
240
+
241
+ if self.sfntVersion in ("\x00\x01\x00\x00", "true"):
242
+ isTrueType = True
243
+ elif self.sfntVersion == "OTTO":
244
+ isTrueType = False
245
+ else:
246
+ raise TTLibError("Not a TrueType or OpenType font (bad sfntVersion)")
247
+
248
+ # The WOFF2 spec no longer requires the glyph offsets to be 4-byte aligned.
249
+ # However, the reference WOFF2 implementation still fails to reconstruct
250
+ # 'unpadded' glyf tables, therefore we need to 'normalise' them.
251
+ # See:
252
+ # https://github.com/khaledhosny/ots/issues/60
253
+ # https://github.com/google/woff2/issues/15
254
+ if (
255
+ isTrueType
256
+ and "glyf" in self.flavorData.transformedTables
257
+ and "glyf" in self.tables
258
+ ):
259
+ self._normaliseGlyfAndLoca(padding=4)
260
+ self._setHeadTransformFlag()
261
+
262
+ # To pass the legacy OpenType Sanitiser currently included in browsers,
263
+ # we must sort the table directory and data alphabetically by tag.
264
+ # See:
265
+ # https://github.com/google/woff2/pull/3
266
+ # https://lists.w3.org/Archives/Public/public-webfonts-wg/2015Mar/0000.html
267
+ #
268
+ # 2023: We rely on this in _transformTables where we expect that
269
+ # "loca" comes after "glyf" table.
270
+ self.tables = OrderedDict(sorted(self.tables.items()))
271
+
272
+ self.totalSfntSize = self._calcSFNTChecksumsLengthsAndOffsets()
273
+
274
+ fontData = self._transformTables()
275
+ compressedFont = brotli.compress(fontData, mode=brotli.MODE_FONT)
276
+
277
+ self.totalCompressedSize = len(compressedFont)
278
+ self.length = self._calcTotalSize()
279
+ self.majorVersion, self.minorVersion = self._getVersion()
280
+ self.reserved = 0
281
+
282
+ directory = self._packTableDirectory()
283
+ self.file.seek(0)
284
+ self.file.write(pad(directory + compressedFont, size=4))
285
+ self._writeFlavorData()
286
+
287
+ def _normaliseGlyfAndLoca(self, padding=4):
288
+ """Recompile glyf and loca tables, aligning glyph offsets to multiples of
289
+ 'padding' size. Update the head table's 'indexToLocFormat' accordingly while
290
+ compiling loca.
291
+ """
292
+ if self.sfntVersion == "OTTO":
293
+ return
294
+
295
+ for tag in ("maxp", "head", "loca", "glyf", "fvar"):
296
+ if tag in self.tables:
297
+ self._decompileTable(tag)
298
+ self.ttFont["glyf"].padding = padding
299
+ for tag in ("glyf", "loca"):
300
+ self._compileTable(tag)
301
+
302
+ def _setHeadTransformFlag(self):
303
+ """Set bit 11 of 'head' table flags to indicate that the font has undergone
304
+ a lossless modifying transform. Re-compile head table data."""
305
+ self._decompileTable("head")
306
+ self.ttFont["head"].flags |= 1 << 11
307
+ self._compileTable("head")
308
+
309
+ def _decompileTable(self, tag):
310
+ """Fetch table data, decompile it, and store it inside self.ttFont."""
311
+ tag = Tag(tag)
312
+ if tag not in self.tables:
313
+ raise TTLibError("missing required table: %s" % tag)
314
+ if self.ttFont.isLoaded(tag):
315
+ return
316
+ data = self.tables[tag].data
317
+ if tag == "loca":
318
+ tableClass = WOFF2LocaTable
319
+ elif tag == "glyf":
320
+ tableClass = WOFF2GlyfTable
321
+ elif tag == "hmtx":
322
+ tableClass = WOFF2HmtxTable
323
+ else:
324
+ tableClass = getTableClass(tag)
325
+ table = tableClass(tag)
326
+ self.ttFont.tables[tag] = table
327
+ table.decompile(data, self.ttFont)
328
+
329
+ def _compileTable(self, tag):
330
+ """Compile table and store it in its 'data' attribute."""
331
+ self.tables[tag].data = self.ttFont[tag].compile(self.ttFont)
332
+
333
+ def _calcSFNTChecksumsLengthsAndOffsets(self):
334
+ """Compute the 'original' SFNT checksums, lengths and offsets for checksum
335
+ adjustment calculation. Return the total size of the uncompressed font.
336
+ """
337
+ offset = sfntDirectorySize + sfntDirectoryEntrySize * len(self.tables)
338
+ for tag, entry in self.tables.items():
339
+ data = entry.data
340
+ entry.origOffset = offset
341
+ entry.origLength = len(data)
342
+ if tag == "head":
343
+ entry.checkSum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:])
344
+ else:
345
+ entry.checkSum = calcChecksum(data)
346
+ offset += (entry.origLength + 3) & ~3
347
+ return offset
348
+
349
+ def _transformTables(self):
350
+ """Return transformed font data."""
351
+ transformedTables = self.flavorData.transformedTables
352
+ for tag, entry in self.tables.items():
353
+ data = None
354
+ if tag in transformedTables:
355
+ data = self.transformTable(tag)
356
+ if data is not None:
357
+ entry.transformed = True
358
+ if data is None:
359
+ if tag == "glyf":
360
+ # Currently we always sort table tags so
361
+ # 'loca' comes after 'glyf'.
362
+ transformedTables.discard("loca")
363
+ # pass-through the table data without transformation
364
+ data = entry.data
365
+ entry.transformed = False
366
+ entry.offset = self.nextTableOffset
367
+ entry.saveData(self.transformBuffer, data)
368
+ self.nextTableOffset += entry.length
369
+ self.writeMasterChecksum()
370
+ fontData = self.transformBuffer.getvalue()
371
+ return fontData
372
+
373
+ def transformTable(self, tag):
374
+ """Return transformed table data, or None if some pre-conditions aren't
375
+ met -- in which case, the non-transformed table data will be used.
376
+ """
377
+ if tag == "loca":
378
+ data = b""
379
+ elif tag == "glyf":
380
+ for tag in ("maxp", "head", "loca", "glyf"):
381
+ self._decompileTable(tag)
382
+ glyfTable = self.ttFont["glyf"]
383
+ data = glyfTable.transform(self.ttFont)
384
+ elif tag == "hmtx":
385
+ if "glyf" not in self.tables:
386
+ return
387
+ for tag in ("maxp", "head", "hhea", "loca", "glyf", "hmtx"):
388
+ self._decompileTable(tag)
389
+ hmtxTable = self.ttFont["hmtx"]
390
+ data = hmtxTable.transform(self.ttFont) # can be None
391
+ else:
392
+ raise TTLibError("Transform for table '%s' is unknown" % tag)
393
+ return data
394
+
395
+ def _calcMasterChecksum(self):
396
+ """Calculate checkSumAdjustment."""
397
+ tags = list(self.tables.keys())
398
+ checksums = []
399
+ for i in range(len(tags)):
400
+ checksums.append(self.tables[tags[i]].checkSum)
401
+
402
+ # Create a SFNT directory for checksum calculation purposes
403
+ self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(
404
+ self.numTables, 16
405
+ )
406
+ directory = sstruct.pack(sfntDirectoryFormat, self)
407
+ tables = sorted(self.tables.items())
408
+ for tag, entry in tables:
409
+ sfntEntry = SFNTDirectoryEntry()
410
+ sfntEntry.tag = entry.tag
411
+ sfntEntry.checkSum = entry.checkSum
412
+ sfntEntry.offset = entry.origOffset
413
+ sfntEntry.length = entry.origLength
414
+ directory = directory + sfntEntry.toString()
415
+
416
+ directory_end = sfntDirectorySize + len(self.tables) * sfntDirectoryEntrySize
417
+ assert directory_end == len(directory)
418
+
419
+ checksums.append(calcChecksum(directory))
420
+ checksum = sum(checksums) & 0xFFFFFFFF
421
+ # BiboAfba!
422
+ checksumadjustment = (0xB1B0AFBA - checksum) & 0xFFFFFFFF
423
+ return checksumadjustment
424
+
425
+ def writeMasterChecksum(self):
426
+ """Write checkSumAdjustment to the transformBuffer."""
427
+ checksumadjustment = self._calcMasterChecksum()
428
+ self.transformBuffer.seek(self.tables["head"].offset + 8)
429
+ self.transformBuffer.write(struct.pack(">L", checksumadjustment))
430
+
431
+ def _calcTotalSize(self):
432
+ """Calculate total size of WOFF2 font, including any meta- and/or private data."""
433
+ offset = self.directorySize
434
+ for entry in self.tables.values():
435
+ offset += len(entry.toString())
436
+ offset += self.totalCompressedSize
437
+ offset = (offset + 3) & ~3
438
+ offset = self._calcFlavorDataOffsetsAndSize(offset)
439
+ return offset
440
+
441
+ def _calcFlavorDataOffsetsAndSize(self, start):
442
+ """Calculate offsets and lengths for any meta- and/or private data."""
443
+ offset = start
444
+ data = self.flavorData
445
+ if data.metaData:
446
+ self.metaOrigLength = len(data.metaData)
447
+ self.metaOffset = offset
448
+ self.compressedMetaData = brotli.compress(
449
+ data.metaData, mode=brotli.MODE_TEXT
450
+ )
451
+ self.metaLength = len(self.compressedMetaData)
452
+ offset += self.metaLength
453
+ else:
454
+ self.metaOffset = self.metaLength = self.metaOrigLength = 0
455
+ self.compressedMetaData = b""
456
+ if data.privData:
457
+ # make sure private data is padded to 4-byte boundary
458
+ offset = (offset + 3) & ~3
459
+ self.privOffset = offset
460
+ self.privLength = len(data.privData)
461
+ offset += self.privLength
462
+ else:
463
+ self.privOffset = self.privLength = 0
464
+ return offset
465
+
466
+ def _getVersion(self):
467
+ """Return the WOFF2 font's (majorVersion, minorVersion) tuple."""
468
+ data = self.flavorData
469
+ if data.majorVersion is not None and data.minorVersion is not None:
470
+ return data.majorVersion, data.minorVersion
471
+ else:
472
+ # if None, return 'fontRevision' from 'head' table
473
+ if "head" in self.tables:
474
+ return struct.unpack(">HH", self.tables["head"].data[4:8])
475
+ else:
476
+ return 0, 0
477
+
478
+ def _packTableDirectory(self):
479
+ """Return WOFF2 table directory data."""
480
+ directory = sstruct.pack(self.directoryFormat, self)
481
+ for entry in self.tables.values():
482
+ directory = directory + entry.toString()
483
+ return directory
484
+
485
+ def _writeFlavorData(self):
486
+ """Write metadata and/or private data using appropiate padding."""
487
+ compressedMetaData = self.compressedMetaData
488
+ privData = self.flavorData.privData
489
+ if compressedMetaData and privData:
490
+ compressedMetaData = pad(compressedMetaData, size=4)
491
+ if compressedMetaData:
492
+ self.file.seek(self.metaOffset)
493
+ assert self.file.tell() == self.metaOffset
494
+ self.file.write(compressedMetaData)
495
+ if privData:
496
+ self.file.seek(self.privOffset)
497
+ assert self.file.tell() == self.privOffset
498
+ self.file.write(privData)
499
+
500
+ def reordersTables(self):
501
+ return True
502
+
503
+
504
+ # -- woff2 directory helpers and cruft
505
+
506
+ woff2DirectoryFormat = """
507
+ > # big endian
508
+ signature: 4s # "wOF2"
509
+ sfntVersion: 4s
510
+ length: L # total woff2 file size
511
+ numTables: H # number of tables
512
+ reserved: H # set to 0
513
+ totalSfntSize: L # uncompressed size
514
+ totalCompressedSize: L # compressed size
515
+ majorVersion: H # major version of WOFF file
516
+ minorVersion: H # minor version of WOFF file
517
+ metaOffset: L # offset to metadata block
518
+ metaLength: L # length of compressed metadata
519
+ metaOrigLength: L # length of uncompressed metadata
520
+ privOffset: L # offset to private data block
521
+ privLength: L # length of private data block
522
+ """
523
+
524
+ woff2DirectorySize = sstruct.calcsize(woff2DirectoryFormat)
525
+
526
+ woff2KnownTags = (
527
+ "cmap",
528
+ "head",
529
+ "hhea",
530
+ "hmtx",
531
+ "maxp",
532
+ "name",
533
+ "OS/2",
534
+ "post",
535
+ "cvt ",
536
+ "fpgm",
537
+ "glyf",
538
+ "loca",
539
+ "prep",
540
+ "CFF ",
541
+ "VORG",
542
+ "EBDT",
543
+ "EBLC",
544
+ "gasp",
545
+ "hdmx",
546
+ "kern",
547
+ "LTSH",
548
+ "PCLT",
549
+ "VDMX",
550
+ "vhea",
551
+ "vmtx",
552
+ "BASE",
553
+ "GDEF",
554
+ "GPOS",
555
+ "GSUB",
556
+ "EBSC",
557
+ "JSTF",
558
+ "MATH",
559
+ "CBDT",
560
+ "CBLC",
561
+ "COLR",
562
+ "CPAL",
563
+ "SVG ",
564
+ "sbix",
565
+ "acnt",
566
+ "avar",
567
+ "bdat",
568
+ "bloc",
569
+ "bsln",
570
+ "cvar",
571
+ "fdsc",
572
+ "feat",
573
+ "fmtx",
574
+ "fvar",
575
+ "gvar",
576
+ "hsty",
577
+ "just",
578
+ "lcar",
579
+ "mort",
580
+ "morx",
581
+ "opbd",
582
+ "prop",
583
+ "trak",
584
+ "Zapf",
585
+ "Silf",
586
+ "Glat",
587
+ "Gloc",
588
+ "Feat",
589
+ "Sill",
590
+ )
591
+
592
+ woff2FlagsFormat = """
593
+ > # big endian
594
+ flags: B # table type and flags
595
+ """
596
+
597
+ woff2FlagsSize = sstruct.calcsize(woff2FlagsFormat)
598
+
599
+ woff2UnknownTagFormat = """
600
+ > # big endian
601
+ tag: 4s # 4-byte tag (optional)
602
+ """
603
+
604
+ woff2UnknownTagSize = sstruct.calcsize(woff2UnknownTagFormat)
605
+
606
+ woff2UnknownTagIndex = 0x3F
607
+
608
+ woff2Base128MaxSize = 5
609
+ woff2DirectoryEntryMaxSize = (
610
+ woff2FlagsSize + woff2UnknownTagSize + 2 * woff2Base128MaxSize
611
+ )
612
+
613
+ woff2TransformedTableTags = ("glyf", "loca")
614
+
615
+ woff2GlyfTableFormat = """
616
+ > # big endian
617
+ version: H # = 0x0000
618
+ optionFlags: H # Bit 0: we have overlapSimpleBitmap[], Bits 1-15: reserved
619
+ numGlyphs: H # Number of glyphs
620
+ indexFormat: H # Offset format for loca table
621
+ nContourStreamSize: L # Size of nContour stream
622
+ nPointsStreamSize: L # Size of nPoints stream
623
+ flagStreamSize: L # Size of flag stream
624
+ glyphStreamSize: L # Size of glyph stream
625
+ compositeStreamSize: L # Size of composite stream
626
+ bboxStreamSize: L # Comnined size of bboxBitmap and bboxStream
627
+ instructionStreamSize: L # Size of instruction stream
628
+ """
629
+
630
+ woff2GlyfTableFormatSize = sstruct.calcsize(woff2GlyfTableFormat)
631
+
632
+ bboxFormat = """
633
+ > # big endian
634
+ xMin: h
635
+ yMin: h
636
+ xMax: h
637
+ yMax: h
638
+ """
639
+
640
+ woff2OverlapSimpleBitmapFlag = 0x0001
641
+
642
+
643
+ def getKnownTagIndex(tag):
644
+ """Return index of 'tag' in woff2KnownTags list. Return 63 if not found."""
645
+ for i in range(len(woff2KnownTags)):
646
+ if tag == woff2KnownTags[i]:
647
+ return i
648
+ return woff2UnknownTagIndex
649
+
650
+
651
+ class WOFF2DirectoryEntry(DirectoryEntry):
652
+ def fromFile(self, file):
653
+ pos = file.tell()
654
+ data = file.read(woff2DirectoryEntryMaxSize)
655
+ left = self.fromString(data)
656
+ consumed = len(data) - len(left)
657
+ file.seek(pos + consumed)
658
+
659
+ def fromString(self, data):
660
+ if len(data) < 1:
661
+ raise TTLibError("can't read table 'flags': not enough data")
662
+ dummy, data = sstruct.unpack2(woff2FlagsFormat, data, self)
663
+ if self.flags & 0x3F == 0x3F:
664
+ # if bits [0..5] of the flags byte == 63, read a 4-byte arbitrary tag value
665
+ if len(data) < woff2UnknownTagSize:
666
+ raise TTLibError("can't read table 'tag': not enough data")
667
+ dummy, data = sstruct.unpack2(woff2UnknownTagFormat, data, self)
668
+ else:
669
+ # otherwise, tag is derived from a fixed 'Known Tags' table
670
+ self.tag = woff2KnownTags[self.flags & 0x3F]
671
+ self.tag = Tag(self.tag)
672
+ self.origLength, data = unpackBase128(data)
673
+ self.length = self.origLength
674
+ if self.transformed:
675
+ self.length, data = unpackBase128(data)
676
+ if self.tag == "loca" and self.length != 0:
677
+ raise TTLibError("the transformLength of the 'loca' table must be 0")
678
+ # return left over data
679
+ return data
680
+
681
+ def toString(self):
682
+ data = bytechr(self.flags)
683
+ if (self.flags & 0x3F) == 0x3F:
684
+ data += struct.pack(">4s", self.tag.tobytes())
685
+ data += packBase128(self.origLength)
686
+ if self.transformed:
687
+ data += packBase128(self.length)
688
+ return data
689
+
690
+ @property
691
+ def transformVersion(self):
692
+ """Return bits 6-7 of table entry's flags, which indicate the preprocessing
693
+ transformation version number (between 0 and 3).
694
+ """
695
+ return self.flags >> 6
696
+
697
+ @transformVersion.setter
698
+ def transformVersion(self, value):
699
+ assert 0 <= value <= 3
700
+ self.flags |= value << 6
701
+
702
+ @property
703
+ def transformed(self):
704
+ """Return True if the table has any transformation, else return False."""
705
+ # For all tables in a font, except for 'glyf' and 'loca', the transformation
706
+ # version 0 indicates the null transform (where the original table data is
707
+ # passed directly to the Brotli compressor). For 'glyf' and 'loca' tables,
708
+ # transformation version 3 indicates the null transform
709
+ if self.tag in {"glyf", "loca"}:
710
+ return self.transformVersion != 3
711
+ else:
712
+ return self.transformVersion != 0
713
+
714
+ @transformed.setter
715
+ def transformed(self, booleanValue):
716
+ # here we assume that a non-null transform means version 0 for 'glyf' and
717
+ # 'loca' and 1 for every other table (e.g. hmtx); but that may change as
718
+ # new transformation formats are introduced in the future (if ever).
719
+ if self.tag in {"glyf", "loca"}:
720
+ self.transformVersion = 3 if not booleanValue else 0
721
+ else:
722
+ self.transformVersion = int(booleanValue)
723
+
724
+
725
+ class WOFF2LocaTable(getTableClass("loca")):
726
+ """Same as parent class. The only difference is that it attempts to preserve
727
+ the 'indexFormat' as encoded in the WOFF2 glyf table.
728
+ """
729
+
730
+ def __init__(self, tag=None):
731
+ self.tableTag = Tag(tag or "loca")
732
+
733
+ def compile(self, ttFont):
734
+ try:
735
+ max_location = max(self.locations)
736
+ except AttributeError:
737
+ self.set([])
738
+ max_location = 0
739
+ if "glyf" in ttFont and hasattr(ttFont["glyf"], "indexFormat"):
740
+ # copile loca using the indexFormat specified in the WOFF2 glyf table
741
+ indexFormat = ttFont["glyf"].indexFormat
742
+ if indexFormat == 0:
743
+ if max_location >= 0x20000:
744
+ raise TTLibError("indexFormat is 0 but local offsets > 0x20000")
745
+ if not all(l % 2 == 0 for l in self.locations):
746
+ raise TTLibError(
747
+ "indexFormat is 0 but local offsets not multiples of 2"
748
+ )
749
+ locations = array.array("H")
750
+ for i in range(len(self.locations)):
751
+ locations.append(self.locations[i] // 2)
752
+ else:
753
+ locations = array.array("I", self.locations)
754
+ if sys.byteorder != "big":
755
+ locations.byteswap()
756
+ data = locations.tobytes()
757
+ else:
758
+ # use the most compact indexFormat given the current glyph offsets
759
+ data = super(WOFF2LocaTable, self).compile(ttFont)
760
+ return data
761
+
762
+
763
+ class WOFF2GlyfTable(getTableClass("glyf")):
764
+ """Decoder/Encoder for WOFF2 'glyf' table transform."""
765
+
766
+ subStreams = (
767
+ "nContourStream",
768
+ "nPointsStream",
769
+ "flagStream",
770
+ "glyphStream",
771
+ "compositeStream",
772
+ "bboxStream",
773
+ "instructionStream",
774
+ )
775
+
776
+ def __init__(self, tag=None):
777
+ self.tableTag = Tag(tag or "glyf")
778
+
779
+ def reconstruct(self, data, ttFont):
780
+ """Decompile transformed 'glyf' data."""
781
+ inputDataSize = len(data)
782
+
783
+ if inputDataSize < woff2GlyfTableFormatSize:
784
+ raise TTLibError("not enough 'glyf' data")
785
+ dummy, data = sstruct.unpack2(woff2GlyfTableFormat, data, self)
786
+ offset = woff2GlyfTableFormatSize
787
+
788
+ for stream in self.subStreams:
789
+ size = getattr(self, stream + "Size")
790
+ setattr(self, stream, data[:size])
791
+ data = data[size:]
792
+ offset += size
793
+
794
+ hasOverlapSimpleBitmap = self.optionFlags & woff2OverlapSimpleBitmapFlag
795
+ self.overlapSimpleBitmap = None
796
+ if hasOverlapSimpleBitmap:
797
+ overlapSimpleBitmapSize = (self.numGlyphs + 7) >> 3
798
+ self.overlapSimpleBitmap = array.array("B", data[:overlapSimpleBitmapSize])
799
+ offset += overlapSimpleBitmapSize
800
+
801
+ if offset != inputDataSize:
802
+ raise TTLibError(
803
+ "incorrect size of transformed 'glyf' table: expected %d, received %d bytes"
804
+ % (offset, inputDataSize)
805
+ )
806
+
807
+ bboxBitmapSize = ((self.numGlyphs + 31) >> 5) << 2
808
+ bboxBitmap = self.bboxStream[:bboxBitmapSize]
809
+ self.bboxBitmap = array.array("B", bboxBitmap)
810
+ self.bboxStream = self.bboxStream[bboxBitmapSize:]
811
+
812
+ self.nContourStream = array.array("h", self.nContourStream)
813
+ if sys.byteorder != "big":
814
+ self.nContourStream.byteswap()
815
+ assert len(self.nContourStream) == self.numGlyphs
816
+
817
+ if "head" in ttFont:
818
+ ttFont["head"].indexToLocFormat = self.indexFormat
819
+ try:
820
+ self.glyphOrder = ttFont.getGlyphOrder()
821
+ except:
822
+ self.glyphOrder = None
823
+ if self.glyphOrder is None:
824
+ self.glyphOrder = [".notdef"]
825
+ self.glyphOrder.extend(["glyph%.5d" % i for i in range(1, self.numGlyphs)])
826
+ else:
827
+ if len(self.glyphOrder) != self.numGlyphs:
828
+ raise TTLibError(
829
+ "incorrect glyphOrder: expected %d glyphs, found %d"
830
+ % (len(self.glyphOrder), self.numGlyphs)
831
+ )
832
+
833
+ glyphs = self.glyphs = {}
834
+ for glyphID, glyphName in enumerate(self.glyphOrder):
835
+ glyph = self._decodeGlyph(glyphID)
836
+ glyphs[glyphName] = glyph
837
+
838
+ def transform(self, ttFont):
839
+ """Return transformed 'glyf' data"""
840
+ self.numGlyphs = len(self.glyphs)
841
+ assert len(self.glyphOrder) == self.numGlyphs
842
+ if "maxp" in ttFont:
843
+ ttFont["maxp"].numGlyphs = self.numGlyphs
844
+ self.indexFormat = ttFont["head"].indexToLocFormat
845
+
846
+ for stream in self.subStreams:
847
+ setattr(self, stream, b"")
848
+ bboxBitmapSize = ((self.numGlyphs + 31) >> 5) << 2
849
+ self.bboxBitmap = array.array("B", [0] * bboxBitmapSize)
850
+
851
+ self.overlapSimpleBitmap = array.array("B", [0] * ((self.numGlyphs + 7) >> 3))
852
+ for glyphID in range(self.numGlyphs):
853
+ try:
854
+ self._encodeGlyph(glyphID)
855
+ except NotImplementedError:
856
+ return None
857
+ hasOverlapSimpleBitmap = any(self.overlapSimpleBitmap)
858
+
859
+ self.bboxStream = self.bboxBitmap.tobytes() + self.bboxStream
860
+ for stream in self.subStreams:
861
+ setattr(self, stream + "Size", len(getattr(self, stream)))
862
+ self.version = 0
863
+ self.optionFlags = 0
864
+ if hasOverlapSimpleBitmap:
865
+ self.optionFlags |= woff2OverlapSimpleBitmapFlag
866
+ data = sstruct.pack(woff2GlyfTableFormat, self)
867
+ data += bytesjoin([getattr(self, s) for s in self.subStreams])
868
+ if hasOverlapSimpleBitmap:
869
+ data += self.overlapSimpleBitmap.tobytes()
870
+ return data
871
+
872
+ def _decodeGlyph(self, glyphID):
873
+ glyph = getTableModule("glyf").Glyph()
874
+ glyph.numberOfContours = self.nContourStream[glyphID]
875
+ if glyph.numberOfContours == 0:
876
+ return glyph
877
+ elif glyph.isComposite():
878
+ self._decodeComponents(glyph)
879
+ else:
880
+ self._decodeCoordinates(glyph)
881
+ self._decodeOverlapSimpleFlag(glyph, glyphID)
882
+ self._decodeBBox(glyphID, glyph)
883
+ return glyph
884
+
885
+ def _decodeComponents(self, glyph):
886
+ data = self.compositeStream
887
+ glyph.components = []
888
+ more = 1
889
+ haveInstructions = 0
890
+ while more:
891
+ component = getTableModule("glyf").GlyphComponent()
892
+ more, haveInstr, data = component.decompile(data, self)
893
+ haveInstructions = haveInstructions | haveInstr
894
+ glyph.components.append(component)
895
+ self.compositeStream = data
896
+ if haveInstructions:
897
+ self._decodeInstructions(glyph)
898
+
899
+ def _decodeCoordinates(self, glyph):
900
+ data = self.nPointsStream
901
+ endPtsOfContours = []
902
+ endPoint = -1
903
+ for i in range(glyph.numberOfContours):
904
+ ptsOfContour, data = unpack255UShort(data)
905
+ endPoint += ptsOfContour
906
+ endPtsOfContours.append(endPoint)
907
+ glyph.endPtsOfContours = endPtsOfContours
908
+ self.nPointsStream = data
909
+ self._decodeTriplets(glyph)
910
+ self._decodeInstructions(glyph)
911
+
912
+ def _decodeOverlapSimpleFlag(self, glyph, glyphID):
913
+ if self.overlapSimpleBitmap is None or glyph.numberOfContours <= 0:
914
+ return
915
+ byte = glyphID >> 3
916
+ bit = glyphID & 7
917
+ if self.overlapSimpleBitmap[byte] & (0x80 >> bit):
918
+ glyph.flags[0] |= _g_l_y_f.flagOverlapSimple
919
+
920
+ def _decodeInstructions(self, glyph):
921
+ glyphStream = self.glyphStream
922
+ instructionStream = self.instructionStream
923
+ instructionLength, glyphStream = unpack255UShort(glyphStream)
924
+ glyph.program = ttProgram.Program()
925
+ glyph.program.fromBytecode(instructionStream[:instructionLength])
926
+ self.glyphStream = glyphStream
927
+ self.instructionStream = instructionStream[instructionLength:]
928
+
929
+ def _decodeBBox(self, glyphID, glyph):
930
+ haveBBox = bool(self.bboxBitmap[glyphID >> 3] & (0x80 >> (glyphID & 7)))
931
+ if glyph.isComposite() and not haveBBox:
932
+ raise TTLibError("no bbox values for composite glyph %d" % glyphID)
933
+ if haveBBox:
934
+ dummy, self.bboxStream = sstruct.unpack2(bboxFormat, self.bboxStream, glyph)
935
+ else:
936
+ glyph.recalcBounds(self)
937
+
938
+ def _decodeTriplets(self, glyph):
939
+ def withSign(flag, baseval):
940
+ assert 0 <= baseval and baseval < 65536, "integer overflow"
941
+ return baseval if flag & 1 else -baseval
942
+
943
+ nPoints = glyph.endPtsOfContours[-1] + 1
944
+ flagSize = nPoints
945
+ if flagSize > len(self.flagStream):
946
+ raise TTLibError("not enough 'flagStream' data")
947
+ flagsData = self.flagStream[:flagSize]
948
+ self.flagStream = self.flagStream[flagSize:]
949
+ flags = array.array("B", flagsData)
950
+
951
+ triplets = array.array("B", self.glyphStream)
952
+ nTriplets = len(triplets)
953
+ assert nPoints <= nTriplets
954
+
955
+ x = 0
956
+ y = 0
957
+ glyph.coordinates = getTableModule("glyf").GlyphCoordinates.zeros(nPoints)
958
+ glyph.flags = array.array("B")
959
+ tripletIndex = 0
960
+ for i in range(nPoints):
961
+ flag = flags[i]
962
+ onCurve = not bool(flag >> 7)
963
+ flag &= 0x7F
964
+ if flag < 84:
965
+ nBytes = 1
966
+ elif flag < 120:
967
+ nBytes = 2
968
+ elif flag < 124:
969
+ nBytes = 3
970
+ else:
971
+ nBytes = 4
972
+ assert (tripletIndex + nBytes) <= nTriplets
973
+ if flag < 10:
974
+ dx = 0
975
+ dy = withSign(flag, ((flag & 14) << 7) + triplets[tripletIndex])
976
+ elif flag < 20:
977
+ dx = withSign(flag, (((flag - 10) & 14) << 7) + triplets[tripletIndex])
978
+ dy = 0
979
+ elif flag < 84:
980
+ b0 = flag - 20
981
+ b1 = triplets[tripletIndex]
982
+ dx = withSign(flag, 1 + (b0 & 0x30) + (b1 >> 4))
983
+ dy = withSign(flag >> 1, 1 + ((b0 & 0x0C) << 2) + (b1 & 0x0F))
984
+ elif flag < 120:
985
+ b0 = flag - 84
986
+ dx = withSign(flag, 1 + ((b0 // 12) << 8) + triplets[tripletIndex])
987
+ dy = withSign(
988
+ flag >> 1, 1 + (((b0 % 12) >> 2) << 8) + triplets[tripletIndex + 1]
989
+ )
990
+ elif flag < 124:
991
+ b2 = triplets[tripletIndex + 1]
992
+ dx = withSign(flag, (triplets[tripletIndex] << 4) + (b2 >> 4))
993
+ dy = withSign(
994
+ flag >> 1, ((b2 & 0x0F) << 8) + triplets[tripletIndex + 2]
995
+ )
996
+ else:
997
+ dx = withSign(
998
+ flag, (triplets[tripletIndex] << 8) + triplets[tripletIndex + 1]
999
+ )
1000
+ dy = withSign(
1001
+ flag >> 1,
1002
+ (triplets[tripletIndex + 2] << 8) + triplets[tripletIndex + 3],
1003
+ )
1004
+ tripletIndex += nBytes
1005
+ x += dx
1006
+ y += dy
1007
+ glyph.coordinates[i] = (x, y)
1008
+ glyph.flags.append(int(onCurve))
1009
+ bytesConsumed = tripletIndex
1010
+ self.glyphStream = self.glyphStream[bytesConsumed:]
1011
+
1012
+ def _encodeGlyph(self, glyphID):
1013
+ glyphName = self.getGlyphName(glyphID)
1014
+ glyph = self[glyphName]
1015
+ self.nContourStream += struct.pack(">h", glyph.numberOfContours)
1016
+ if glyph.numberOfContours == 0:
1017
+ return
1018
+ elif glyph.isComposite():
1019
+ self._encodeComponents(glyph)
1020
+ else:
1021
+ self._encodeCoordinates(glyph)
1022
+ self._encodeOverlapSimpleFlag(glyph, glyphID)
1023
+ self._encodeBBox(glyphID, glyph)
1024
+
1025
+ def _encodeComponents(self, glyph):
1026
+ lastcomponent = len(glyph.components) - 1
1027
+ more = 1
1028
+ haveInstructions = 0
1029
+ for i in range(len(glyph.components)):
1030
+ if i == lastcomponent:
1031
+ haveInstructions = hasattr(glyph, "program")
1032
+ more = 0
1033
+ component = glyph.components[i]
1034
+ self.compositeStream += component.compile(more, haveInstructions, self)
1035
+ if haveInstructions:
1036
+ self._encodeInstructions(glyph)
1037
+
1038
+ def _encodeCoordinates(self, glyph):
1039
+ lastEndPoint = -1
1040
+ if _g_l_y_f.flagCubic in glyph.flags:
1041
+ raise NotImplementedError
1042
+ for endPoint in glyph.endPtsOfContours:
1043
+ ptsOfContour = endPoint - lastEndPoint
1044
+ self.nPointsStream += pack255UShort(ptsOfContour)
1045
+ lastEndPoint = endPoint
1046
+ self._encodeTriplets(glyph)
1047
+ self._encodeInstructions(glyph)
1048
+
1049
+ def _encodeOverlapSimpleFlag(self, glyph, glyphID):
1050
+ if glyph.numberOfContours <= 0:
1051
+ return
1052
+ if glyph.flags[0] & _g_l_y_f.flagOverlapSimple:
1053
+ byte = glyphID >> 3
1054
+ bit = glyphID & 7
1055
+ self.overlapSimpleBitmap[byte] |= 0x80 >> bit
1056
+
1057
+ def _encodeInstructions(self, glyph):
1058
+ instructions = glyph.program.getBytecode()
1059
+ self.glyphStream += pack255UShort(len(instructions))
1060
+ self.instructionStream += instructions
1061
+
1062
+ def _encodeBBox(self, glyphID, glyph):
1063
+ assert glyph.numberOfContours != 0, "empty glyph has no bbox"
1064
+ if not glyph.isComposite():
1065
+ # for simple glyphs, compare the encoded bounding box info with the calculated
1066
+ # values, and if they match omit the bounding box info
1067
+ currentBBox = glyph.xMin, glyph.yMin, glyph.xMax, glyph.yMax
1068
+ calculatedBBox = calcIntBounds(glyph.coordinates)
1069
+ if currentBBox == calculatedBBox:
1070
+ return
1071
+ self.bboxBitmap[glyphID >> 3] |= 0x80 >> (glyphID & 7)
1072
+ self.bboxStream += sstruct.pack(bboxFormat, glyph)
1073
+
1074
+ def _encodeTriplets(self, glyph):
1075
+ assert len(glyph.coordinates) == len(glyph.flags)
1076
+ coordinates = glyph.coordinates.copy()
1077
+ coordinates.absoluteToRelative()
1078
+
1079
+ flags = array.array("B")
1080
+ triplets = array.array("B")
1081
+ for i in range(len(coordinates)):
1082
+ onCurve = glyph.flags[i] & _g_l_y_f.flagOnCurve
1083
+ x, y = coordinates[i]
1084
+ absX = abs(x)
1085
+ absY = abs(y)
1086
+ onCurveBit = 0 if onCurve else 128
1087
+ xSignBit = 0 if (x < 0) else 1
1088
+ ySignBit = 0 if (y < 0) else 1
1089
+ xySignBits = xSignBit + 2 * ySignBit
1090
+
1091
+ if x == 0 and absY < 1280:
1092
+ flags.append(onCurveBit + ((absY & 0xF00) >> 7) + ySignBit)
1093
+ triplets.append(absY & 0xFF)
1094
+ elif y == 0 and absX < 1280:
1095
+ flags.append(onCurveBit + 10 + ((absX & 0xF00) >> 7) + xSignBit)
1096
+ triplets.append(absX & 0xFF)
1097
+ elif absX < 65 and absY < 65:
1098
+ flags.append(
1099
+ onCurveBit
1100
+ + 20
1101
+ + ((absX - 1) & 0x30)
1102
+ + (((absY - 1) & 0x30) >> 2)
1103
+ + xySignBits
1104
+ )
1105
+ triplets.append((((absX - 1) & 0xF) << 4) | ((absY - 1) & 0xF))
1106
+ elif absX < 769 and absY < 769:
1107
+ flags.append(
1108
+ onCurveBit
1109
+ + 84
1110
+ + 12 * (((absX - 1) & 0x300) >> 8)
1111
+ + (((absY - 1) & 0x300) >> 6)
1112
+ + xySignBits
1113
+ )
1114
+ triplets.append((absX - 1) & 0xFF)
1115
+ triplets.append((absY - 1) & 0xFF)
1116
+ elif absX < 4096 and absY < 4096:
1117
+ flags.append(onCurveBit + 120 + xySignBits)
1118
+ triplets.append(absX >> 4)
1119
+ triplets.append(((absX & 0xF) << 4) | (absY >> 8))
1120
+ triplets.append(absY & 0xFF)
1121
+ else:
1122
+ flags.append(onCurveBit + 124 + xySignBits)
1123
+ triplets.append(absX >> 8)
1124
+ triplets.append(absX & 0xFF)
1125
+ triplets.append(absY >> 8)
1126
+ triplets.append(absY & 0xFF)
1127
+
1128
+ self.flagStream += flags.tobytes()
1129
+ self.glyphStream += triplets.tobytes()
1130
+
1131
+
1132
+ class WOFF2HmtxTable(getTableClass("hmtx")):
1133
+ def __init__(self, tag=None):
1134
+ self.tableTag = Tag(tag or "hmtx")
1135
+
1136
+ def reconstruct(self, data, ttFont):
1137
+ (flags,) = struct.unpack(">B", data[:1])
1138
+ data = data[1:]
1139
+ if flags & 0b11111100 != 0:
1140
+ raise TTLibError("Bits 2-7 of '%s' flags are reserved" % self.tableTag)
1141
+
1142
+ # When bit 0 is _not_ set, the lsb[] array is present
1143
+ hasLsbArray = flags & 1 == 0
1144
+ # When bit 1 is _not_ set, the leftSideBearing[] array is present
1145
+ hasLeftSideBearingArray = flags & 2 == 0
1146
+ if hasLsbArray and hasLeftSideBearingArray:
1147
+ raise TTLibError(
1148
+ "either bits 0 or 1 (or both) must set in transformed '%s' flags"
1149
+ % self.tableTag
1150
+ )
1151
+
1152
+ glyfTable = ttFont["glyf"]
1153
+ headerTable = ttFont["hhea"]
1154
+ glyphOrder = glyfTable.glyphOrder
1155
+ numGlyphs = len(glyphOrder)
1156
+ numberOfHMetrics = min(int(headerTable.numberOfHMetrics), numGlyphs)
1157
+
1158
+ assert len(data) >= 2 * numberOfHMetrics
1159
+ advanceWidthArray = array.array("H", data[: 2 * numberOfHMetrics])
1160
+ if sys.byteorder != "big":
1161
+ advanceWidthArray.byteswap()
1162
+ data = data[2 * numberOfHMetrics :]
1163
+
1164
+ if hasLsbArray:
1165
+ assert len(data) >= 2 * numberOfHMetrics
1166
+ lsbArray = array.array("h", data[: 2 * numberOfHMetrics])
1167
+ if sys.byteorder != "big":
1168
+ lsbArray.byteswap()
1169
+ data = data[2 * numberOfHMetrics :]
1170
+ else:
1171
+ # compute (proportional) glyphs' lsb from their xMin
1172
+ lsbArray = array.array("h")
1173
+ for i, glyphName in enumerate(glyphOrder):
1174
+ if i >= numberOfHMetrics:
1175
+ break
1176
+ glyph = glyfTable[glyphName]
1177
+ xMin = getattr(glyph, "xMin", 0)
1178
+ lsbArray.append(xMin)
1179
+
1180
+ numberOfSideBearings = numGlyphs - numberOfHMetrics
1181
+ if hasLeftSideBearingArray:
1182
+ assert len(data) >= 2 * numberOfSideBearings
1183
+ leftSideBearingArray = array.array("h", data[: 2 * numberOfSideBearings])
1184
+ if sys.byteorder != "big":
1185
+ leftSideBearingArray.byteswap()
1186
+ data = data[2 * numberOfSideBearings :]
1187
+ else:
1188
+ # compute (monospaced) glyphs' leftSideBearing from their xMin
1189
+ leftSideBearingArray = array.array("h")
1190
+ for i, glyphName in enumerate(glyphOrder):
1191
+ if i < numberOfHMetrics:
1192
+ continue
1193
+ glyph = glyfTable[glyphName]
1194
+ xMin = getattr(glyph, "xMin", 0)
1195
+ leftSideBearingArray.append(xMin)
1196
+
1197
+ if data:
1198
+ raise TTLibError("too much '%s' table data" % self.tableTag)
1199
+
1200
+ self.metrics = {}
1201
+ for i in range(numberOfHMetrics):
1202
+ glyphName = glyphOrder[i]
1203
+ advanceWidth, lsb = advanceWidthArray[i], lsbArray[i]
1204
+ self.metrics[glyphName] = (advanceWidth, lsb)
1205
+ lastAdvance = advanceWidthArray[-1]
1206
+ for i in range(numberOfSideBearings):
1207
+ glyphName = glyphOrder[i + numberOfHMetrics]
1208
+ self.metrics[glyphName] = (lastAdvance, leftSideBearingArray[i])
1209
+
1210
+ def transform(self, ttFont):
1211
+ glyphOrder = ttFont.getGlyphOrder()
1212
+ glyf = ttFont["glyf"]
1213
+ hhea = ttFont["hhea"]
1214
+ numberOfHMetrics = hhea.numberOfHMetrics
1215
+
1216
+ # check if any of the proportional glyphs has left sidebearings that
1217
+ # differ from their xMin bounding box values.
1218
+ hasLsbArray = False
1219
+ for i in range(numberOfHMetrics):
1220
+ glyphName = glyphOrder[i]
1221
+ lsb = self.metrics[glyphName][1]
1222
+ if lsb != getattr(glyf[glyphName], "xMin", 0):
1223
+ hasLsbArray = True
1224
+ break
1225
+
1226
+ # do the same for the monospaced glyphs (if any) at the end of hmtx table
1227
+ hasLeftSideBearingArray = False
1228
+ for i in range(numberOfHMetrics, len(glyphOrder)):
1229
+ glyphName = glyphOrder[i]
1230
+ lsb = self.metrics[glyphName][1]
1231
+ if lsb != getattr(glyf[glyphName], "xMin", 0):
1232
+ hasLeftSideBearingArray = True
1233
+ break
1234
+
1235
+ # if we need to encode both sidebearings arrays, then no transformation is
1236
+ # applicable, and we must use the untransformed hmtx data
1237
+ if hasLsbArray and hasLeftSideBearingArray:
1238
+ return
1239
+
1240
+ # set bit 0 and 1 when the respective arrays are _not_ present
1241
+ flags = 0
1242
+ if not hasLsbArray:
1243
+ flags |= 1 << 0
1244
+ if not hasLeftSideBearingArray:
1245
+ flags |= 1 << 1
1246
+
1247
+ data = struct.pack(">B", flags)
1248
+
1249
+ advanceWidthArray = array.array(
1250
+ "H",
1251
+ [
1252
+ self.metrics[glyphName][0]
1253
+ for i, glyphName in enumerate(glyphOrder)
1254
+ if i < numberOfHMetrics
1255
+ ],
1256
+ )
1257
+ if sys.byteorder != "big":
1258
+ advanceWidthArray.byteswap()
1259
+ data += advanceWidthArray.tobytes()
1260
+
1261
+ if hasLsbArray:
1262
+ lsbArray = array.array(
1263
+ "h",
1264
+ [
1265
+ self.metrics[glyphName][1]
1266
+ for i, glyphName in enumerate(glyphOrder)
1267
+ if i < numberOfHMetrics
1268
+ ],
1269
+ )
1270
+ if sys.byteorder != "big":
1271
+ lsbArray.byteswap()
1272
+ data += lsbArray.tobytes()
1273
+
1274
+ if hasLeftSideBearingArray:
1275
+ leftSideBearingArray = array.array(
1276
+ "h",
1277
+ [
1278
+ self.metrics[glyphOrder[i]][1]
1279
+ for i in range(numberOfHMetrics, len(glyphOrder))
1280
+ ],
1281
+ )
1282
+ if sys.byteorder != "big":
1283
+ leftSideBearingArray.byteswap()
1284
+ data += leftSideBearingArray.tobytes()
1285
+
1286
+ return data
1287
+
1288
+
1289
+ class WOFF2FlavorData(WOFFFlavorData):
1290
+ Flavor = "woff2"
1291
+
1292
+ def __init__(self, reader=None, data=None, transformedTables=None):
1293
+ """Data class that holds the WOFF2 header major/minor version, any
1294
+ metadata or private data (as bytes strings), and the set of
1295
+ table tags that have transformations applied (if reader is not None),
1296
+ or will have once the WOFF2 font is compiled.
1297
+
1298
+ Args:
1299
+ reader: an SFNTReader (or subclass) object to read flavor data from.
1300
+ data: another WOFFFlavorData object to initialise data from.
1301
+ transformedTables: set of strings containing table tags to be transformed.
1302
+
1303
+ Raises:
1304
+ ImportError if the brotli module is not installed.
1305
+
1306
+ NOTE: The 'reader' argument, on the one hand, and the 'data' and
1307
+ 'transformedTables' arguments, on the other hand, are mutually exclusive.
1308
+ """
1309
+ if not haveBrotli:
1310
+ raise ImportError("No module named brotli")
1311
+
1312
+ if reader is not None:
1313
+ if data is not None:
1314
+ raise TypeError("'reader' and 'data' arguments are mutually exclusive")
1315
+ if transformedTables is not None:
1316
+ raise TypeError(
1317
+ "'reader' and 'transformedTables' arguments are mutually exclusive"
1318
+ )
1319
+
1320
+ if transformedTables is not None and (
1321
+ "glyf" in transformedTables
1322
+ and "loca" not in transformedTables
1323
+ or "loca" in transformedTables
1324
+ and "glyf" not in transformedTables
1325
+ ):
1326
+ raise ValueError("'glyf' and 'loca' must be transformed (or not) together")
1327
+ super(WOFF2FlavorData, self).__init__(reader=reader)
1328
+ if reader:
1329
+ transformedTables = [
1330
+ tag for tag, entry in reader.tables.items() if entry.transformed
1331
+ ]
1332
+ elif data:
1333
+ self.majorVersion = data.majorVersion
1334
+ self.majorVersion = data.minorVersion
1335
+ self.metaData = data.metaData
1336
+ self.privData = data.privData
1337
+ if transformedTables is None and hasattr(data, "transformedTables"):
1338
+ transformedTables = data.transformedTables
1339
+
1340
+ if transformedTables is None:
1341
+ transformedTables = woff2TransformedTableTags
1342
+
1343
+ self.transformedTables = set(transformedTables)
1344
+
1345
+ def _decompress(self, rawData):
1346
+ return brotli.decompress(rawData)
1347
+
1348
+
1349
+ def unpackBase128(data):
1350
+ r"""Read one to five bytes from UIntBase128-encoded input string, and return
1351
+ a tuple containing the decoded integer plus any leftover data.
1352
+
1353
+ >>> unpackBase128(b'\x3f\x00\x00') == (63, b"\x00\x00")
1354
+ True
1355
+ >>> unpackBase128(b'\x8f\xff\xff\xff\x7f')[0] == 4294967295
1356
+ True
1357
+ >>> unpackBase128(b'\x80\x80\x3f') # doctest: +IGNORE_EXCEPTION_DETAIL
1358
+ Traceback (most recent call last):
1359
+ File "<stdin>", line 1, in ?
1360
+ TTLibError: UIntBase128 value must not start with leading zeros
1361
+ >>> unpackBase128(b'\x8f\xff\xff\xff\xff\x7f')[0] # doctest: +IGNORE_EXCEPTION_DETAIL
1362
+ Traceback (most recent call last):
1363
+ File "<stdin>", line 1, in ?
1364
+ TTLibError: UIntBase128-encoded sequence is longer than 5 bytes
1365
+ >>> unpackBase128(b'\x90\x80\x80\x80\x00')[0] # doctest: +IGNORE_EXCEPTION_DETAIL
1366
+ Traceback (most recent call last):
1367
+ File "<stdin>", line 1, in ?
1368
+ TTLibError: UIntBase128 value exceeds 2**32-1
1369
+ """
1370
+ if len(data) == 0:
1371
+ raise TTLibError("not enough data to unpack UIntBase128")
1372
+ result = 0
1373
+ if byteord(data[0]) == 0x80:
1374
+ # font must be rejected if UIntBase128 value starts with 0x80
1375
+ raise TTLibError("UIntBase128 value must not start with leading zeros")
1376
+ for i in range(woff2Base128MaxSize):
1377
+ if len(data) == 0:
1378
+ raise TTLibError("not enough data to unpack UIntBase128")
1379
+ code = byteord(data[0])
1380
+ data = data[1:]
1381
+ # if any of the top seven bits are set then we're about to overflow
1382
+ if result & 0xFE000000:
1383
+ raise TTLibError("UIntBase128 value exceeds 2**32-1")
1384
+ # set current value = old value times 128 bitwise-or (byte bitwise-and 127)
1385
+ result = (result << 7) | (code & 0x7F)
1386
+ # repeat until the most significant bit of byte is false
1387
+ if (code & 0x80) == 0:
1388
+ # return result plus left over data
1389
+ return result, data
1390
+ # make sure not to exceed the size bound
1391
+ raise TTLibError("UIntBase128-encoded sequence is longer than 5 bytes")
1392
+
1393
+
1394
+ def base128Size(n):
1395
+ """Return the length in bytes of a UIntBase128-encoded sequence with value n.
1396
+
1397
+ >>> base128Size(0)
1398
+ 1
1399
+ >>> base128Size(24567)
1400
+ 3
1401
+ >>> base128Size(2**32-1)
1402
+ 5
1403
+ """
1404
+ assert n >= 0
1405
+ size = 1
1406
+ while n >= 128:
1407
+ size += 1
1408
+ n >>= 7
1409
+ return size
1410
+
1411
+
1412
+ def packBase128(n):
1413
+ r"""Encode unsigned integer in range 0 to 2**32-1 (inclusive) to a string of
1414
+ bytes using UIntBase128 variable-length encoding. Produce the shortest possible
1415
+ encoding.
1416
+
1417
+ >>> packBase128(63) == b"\x3f"
1418
+ True
1419
+ >>> packBase128(2**32-1) == b'\x8f\xff\xff\xff\x7f'
1420
+ True
1421
+ """
1422
+ if n < 0 or n >= 2**32:
1423
+ raise TTLibError("UIntBase128 format requires 0 <= integer <= 2**32-1")
1424
+ data = b""
1425
+ size = base128Size(n)
1426
+ for i in range(size):
1427
+ b = (n >> (7 * (size - i - 1))) & 0x7F
1428
+ if i < size - 1:
1429
+ b |= 0x80
1430
+ data += struct.pack("B", b)
1431
+ return data
1432
+
1433
+
1434
+ def unpack255UShort(data):
1435
+ """Read one to three bytes from 255UInt16-encoded input string, and return a
1436
+ tuple containing the decoded integer plus any leftover data.
1437
+
1438
+ >>> unpack255UShort(bytechr(252))[0]
1439
+ 252
1440
+
1441
+ Note that some numbers (e.g. 506) can have multiple encodings:
1442
+ >>> unpack255UShort(struct.pack("BB", 254, 0))[0]
1443
+ 506
1444
+ >>> unpack255UShort(struct.pack("BB", 255, 253))[0]
1445
+ 506
1446
+ >>> unpack255UShort(struct.pack("BBB", 253, 1, 250))[0]
1447
+ 506
1448
+ """
1449
+ code = byteord(data[:1])
1450
+ data = data[1:]
1451
+ if code == 253:
1452
+ # read two more bytes as an unsigned short
1453
+ if len(data) < 2:
1454
+ raise TTLibError("not enough data to unpack 255UInt16")
1455
+ (result,) = struct.unpack(">H", data[:2])
1456
+ data = data[2:]
1457
+ elif code == 254:
1458
+ # read another byte, plus 253 * 2
1459
+ if len(data) == 0:
1460
+ raise TTLibError("not enough data to unpack 255UInt16")
1461
+ result = byteord(data[:1])
1462
+ result += 506
1463
+ data = data[1:]
1464
+ elif code == 255:
1465
+ # read another byte, plus 253
1466
+ if len(data) == 0:
1467
+ raise TTLibError("not enough data to unpack 255UInt16")
1468
+ result = byteord(data[:1])
1469
+ result += 253
1470
+ data = data[1:]
1471
+ else:
1472
+ # leave as is if lower than 253
1473
+ result = code
1474
+ # return result plus left over data
1475
+ return result, data
1476
+
1477
+
1478
+ def pack255UShort(value):
1479
+ r"""Encode unsigned integer in range 0 to 65535 (inclusive) to a bytestring
1480
+ using 255UInt16 variable-length encoding.
1481
+
1482
+ >>> pack255UShort(252) == b'\xfc'
1483
+ True
1484
+ >>> pack255UShort(506) == b'\xfe\x00'
1485
+ True
1486
+ >>> pack255UShort(762) == b'\xfd\x02\xfa'
1487
+ True
1488
+ """
1489
+ if value < 0 or value > 0xFFFF:
1490
+ raise TTLibError("255UInt16 format requires 0 <= integer <= 65535")
1491
+ if value < 253:
1492
+ return struct.pack(">B", value)
1493
+ elif value < 506:
1494
+ return struct.pack(">BB", 255, value - 253)
1495
+ elif value < 762:
1496
+ return struct.pack(">BB", 254, value - 506)
1497
+ else:
1498
+ return struct.pack(">BH", 253, value)
1499
+
1500
+
1501
+ def compress(input_file, output_file, transform_tables=None):
1502
+ """Compress OpenType font to WOFF2.
1503
+
1504
+ Args:
1505
+ input_file: a file path, file or file-like object (open in binary mode)
1506
+ containing an OpenType font (either CFF- or TrueType-flavored).
1507
+ output_file: a file path, file or file-like object where to save the
1508
+ compressed WOFF2 font.
1509
+ transform_tables: Optional[Iterable[str]]: a set of table tags for which
1510
+ to enable preprocessing transformations. By default, only 'glyf'
1511
+ and 'loca' tables are transformed. An empty set means disable all
1512
+ transformations.
1513
+ """
1514
+ log.info("Processing %s => %s" % (input_file, output_file))
1515
+
1516
+ font = TTFont(input_file, recalcBBoxes=False, recalcTimestamp=False)
1517
+ font.flavor = "woff2"
1518
+
1519
+ if transform_tables is not None:
1520
+ font.flavorData = WOFF2FlavorData(
1521
+ data=font.flavorData, transformedTables=transform_tables
1522
+ )
1523
+
1524
+ font.save(output_file, reorderTables=False)
1525
+
1526
+
1527
+ def decompress(input_file, output_file):
1528
+ """Decompress WOFF2 font to OpenType font.
1529
+
1530
+ Args:
1531
+ input_file: a file path, file or file-like object (open in binary mode)
1532
+ containing a compressed WOFF2 font.
1533
+ output_file: a file path, file or file-like object where to save the
1534
+ decompressed OpenType font.
1535
+ """
1536
+ log.info("Processing %s => %s" % (input_file, output_file))
1537
+
1538
+ font = TTFont(input_file, recalcBBoxes=False, recalcTimestamp=False)
1539
+ font.flavor = None
1540
+ font.flavorData = None
1541
+ font.save(output_file, reorderTables=True)
1542
+
1543
+
1544
+ def main(args=None):
1545
+ """Compress and decompress WOFF2 fonts"""
1546
+ import argparse
1547
+ from fontTools import configLogger
1548
+ from fontTools.ttx import makeOutputFileName
1549
+
1550
+ class _HelpAction(argparse._HelpAction):
1551
+ def __call__(self, parser, namespace, values, option_string=None):
1552
+ subparsers_actions = [
1553
+ action
1554
+ for action in parser._actions
1555
+ if isinstance(action, argparse._SubParsersAction)
1556
+ ]
1557
+ for subparsers_action in subparsers_actions:
1558
+ for choice, subparser in subparsers_action.choices.items():
1559
+ print(subparser.format_help())
1560
+ parser.exit()
1561
+
1562
+ class _NoGlyfTransformAction(argparse.Action):
1563
+ def __call__(self, parser, namespace, values, option_string=None):
1564
+ namespace.transform_tables.difference_update({"glyf", "loca"})
1565
+
1566
+ class _HmtxTransformAction(argparse.Action):
1567
+ def __call__(self, parser, namespace, values, option_string=None):
1568
+ namespace.transform_tables.add("hmtx")
1569
+
1570
+ parser = argparse.ArgumentParser(
1571
+ prog="fonttools ttLib.woff2", description=main.__doc__, add_help=False
1572
+ )
1573
+
1574
+ parser.add_argument(
1575
+ "-h", "--help", action=_HelpAction, help="show this help message and exit"
1576
+ )
1577
+
1578
+ parser_group = parser.add_subparsers(title="sub-commands")
1579
+ parser_compress = parser_group.add_parser(
1580
+ "compress", description="Compress a TTF or OTF font to WOFF2"
1581
+ )
1582
+ parser_decompress = parser_group.add_parser(
1583
+ "decompress", description="Decompress a WOFF2 font to OTF"
1584
+ )
1585
+
1586
+ for subparser in (parser_compress, parser_decompress):
1587
+ group = subparser.add_mutually_exclusive_group(required=False)
1588
+ group.add_argument(
1589
+ "-v",
1590
+ "--verbose",
1591
+ action="store_true",
1592
+ help="print more messages to console",
1593
+ )
1594
+ group.add_argument(
1595
+ "-q",
1596
+ "--quiet",
1597
+ action="store_true",
1598
+ help="do not print messages to console",
1599
+ )
1600
+
1601
+ parser_compress.add_argument(
1602
+ "input_file",
1603
+ metavar="INPUT",
1604
+ help="the input OpenType font (.ttf or .otf)",
1605
+ )
1606
+ parser_decompress.add_argument(
1607
+ "input_file",
1608
+ metavar="INPUT",
1609
+ help="the input WOFF2 font",
1610
+ )
1611
+
1612
+ parser_compress.add_argument(
1613
+ "-o",
1614
+ "--output-file",
1615
+ metavar="OUTPUT",
1616
+ help="the output WOFF2 font",
1617
+ )
1618
+ parser_decompress.add_argument(
1619
+ "-o",
1620
+ "--output-file",
1621
+ metavar="OUTPUT",
1622
+ help="the output OpenType font",
1623
+ )
1624
+
1625
+ transform_group = parser_compress.add_argument_group()
1626
+ transform_group.add_argument(
1627
+ "--no-glyf-transform",
1628
+ dest="transform_tables",
1629
+ nargs=0,
1630
+ action=_NoGlyfTransformAction,
1631
+ help="Do not transform glyf (and loca) tables",
1632
+ )
1633
+ transform_group.add_argument(
1634
+ "--hmtx-transform",
1635
+ dest="transform_tables",
1636
+ nargs=0,
1637
+ action=_HmtxTransformAction,
1638
+ help="Enable optional transformation for 'hmtx' table",
1639
+ )
1640
+
1641
+ parser_compress.set_defaults(
1642
+ subcommand=compress,
1643
+ transform_tables={"glyf", "loca"},
1644
+ )
1645
+ parser_decompress.set_defaults(subcommand=decompress)
1646
+
1647
+ options = vars(parser.parse_args(args))
1648
+
1649
+ subcommand = options.pop("subcommand", None)
1650
+ if not subcommand:
1651
+ parser.print_help()
1652
+ return
1653
+
1654
+ quiet = options.pop("quiet")
1655
+ verbose = options.pop("verbose")
1656
+ configLogger(
1657
+ level=("ERROR" if quiet else "DEBUG" if verbose else "INFO"),
1658
+ )
1659
+
1660
+ if not options["output_file"]:
1661
+ if subcommand is compress:
1662
+ extension = ".woff2"
1663
+ elif subcommand is decompress:
1664
+ # choose .ttf/.otf file extension depending on sfntVersion
1665
+ with open(options["input_file"], "rb") as f:
1666
+ f.seek(4) # skip 'wOF2' signature
1667
+ sfntVersion = f.read(4)
1668
+ assert len(sfntVersion) == 4, "not enough data"
1669
+ extension = ".otf" if sfntVersion == b"OTTO" else ".ttf"
1670
+ else:
1671
+ raise AssertionError(subcommand)
1672
+ options["output_file"] = makeOutputFileName(
1673
+ options["input_file"], outputDir=None, extension=extension
1674
+ )
1675
+
1676
+ try:
1677
+ subcommand(**options)
1678
+ except TTLibError as e:
1679
+ parser.error(e)
1680
+
1681
+
1682
+ if __name__ == "__main__":
1683
+ sys.exit(main())
evalkit_tf437/lib/python3.10/site-packages/fontTools/ttx.py ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """\
2
+ usage: ttx [options] inputfile1 [... inputfileN]
3
+
4
+ TTX -- From OpenType To XML And Back
5
+
6
+ If an input file is a TrueType or OpenType font file, it will be
7
+ decompiled to a TTX file (an XML-based text format).
8
+ If an input file is a TTX file, it will be compiled to whatever
9
+ format the data is in, a TrueType or OpenType/CFF font file.
10
+ A special input value of - means read from the standard input.
11
+
12
+ Output files are created so they are unique: an existing file is
13
+ never overwritten.
14
+
15
+ General options
16
+ ===============
17
+
18
+ -h Help print this message.
19
+ --version show version and exit.
20
+ -d <outputfolder> Specify a directory where the output files are
21
+ to be created.
22
+ -o <outputfile> Specify a file to write the output to. A special
23
+ value of - would use the standard output.
24
+ -f Overwrite existing output file(s), ie. don't append
25
+ numbers.
26
+ -v Verbose: more messages will be written to stdout
27
+ about what is being done.
28
+ -q Quiet: No messages will be written to stdout about
29
+ what is being done.
30
+ -a allow virtual glyphs ID's on compile or decompile.
31
+
32
+ Dump options
33
+ ============
34
+
35
+ -l List table info: instead of dumping to a TTX file, list
36
+ some minimal info about each table.
37
+ -t <table> Specify a table to dump. Multiple -t options
38
+ are allowed. When no -t option is specified, all tables
39
+ will be dumped.
40
+ -x <table> Specify a table to exclude from the dump. Multiple
41
+ -x options are allowed. -t and -x are mutually exclusive.
42
+ -s Split tables: save the TTX data into separate TTX files per
43
+ table and write one small TTX file that contains references
44
+ to the individual table dumps. This file can be used as
45
+ input to ttx, as long as the table files are in the
46
+ same directory.
47
+ -g Split glyf table: Save the glyf data into separate TTX files
48
+ per glyph and write a small TTX for the glyf table which
49
+ contains references to the individual TTGlyph elements.
50
+ NOTE: specifying -g implies -s (no need for -s together
51
+ with -g)
52
+ -i Do NOT disassemble TT instructions: when this option is
53
+ given, all TrueType programs (glyph programs, the font
54
+ program and the pre-program) will be written to the TTX
55
+ file as hex data instead of assembly. This saves some time
56
+ and makes the TTX file smaller.
57
+ -z <format> Specify a bitmap data export option for EBDT:
58
+ {'raw', 'row', 'bitwise', 'extfile'} or for the CBDT:
59
+ {'raw', 'extfile'} Each option does one of the following:
60
+
61
+ -z raw
62
+ export the bitmap data as a hex dump
63
+ -z row
64
+ export each row as hex data
65
+ -z bitwise
66
+ export each row as binary in an ASCII art style
67
+ -z extfile
68
+ export the data as external files with XML references
69
+
70
+ If no export format is specified 'raw' format is used.
71
+ -e Don't ignore decompilation errors, but show a full traceback
72
+ and abort.
73
+ -y <number> Select font number for TrueType Collection (.ttc/.otc),
74
+ starting from 0.
75
+ --unicodedata <UnicodeData.txt>
76
+ Use custom database file to write character names in the
77
+ comments of the cmap TTX output.
78
+ --newline <value>
79
+ Control how line endings are written in the XML file. It
80
+ can be 'LF', 'CR', or 'CRLF'. If not specified, the
81
+ default platform-specific line endings are used.
82
+
83
+ Compile options
84
+ ===============
85
+
86
+ -m Merge with TrueType-input-file: specify a TrueType or
87
+ OpenType font file to be merged with the TTX file. This
88
+ option is only valid when at most one TTX file is specified.
89
+ -b Don't recalc glyph bounding boxes: use the values in the
90
+ TTX file as-is.
91
+ --recalc-timestamp
92
+ Set font 'modified' timestamp to current time.
93
+ By default, the modification time of the TTX file will be
94
+ used.
95
+ --no-recalc-timestamp
96
+ Keep the original font 'modified' timestamp.
97
+ --flavor <type>
98
+ Specify flavor of output font file. May be 'woff' or 'woff2'.
99
+ Note that WOFF2 requires the Brotli Python extension,
100
+ available at https://github.com/google/brotli
101
+ --with-zopfli
102
+ Use Zopfli instead of Zlib to compress WOFF. The Python
103
+ extension is available at https://pypi.python.org/pypi/zopfli
104
+ """
105
+
106
+ from fontTools.ttLib import TTFont, TTLibError
107
+ from fontTools.misc.macCreatorType import getMacCreatorAndType
108
+ from fontTools.unicode import setUnicodeData
109
+ from fontTools.misc.textTools import Tag, tostr
110
+ from fontTools.misc.timeTools import timestampSinceEpoch
111
+ from fontTools.misc.loggingTools import Timer
112
+ from fontTools.misc.cliTools import makeOutputFileName
113
+ import os
114
+ import sys
115
+ import getopt
116
+ import re
117
+ import logging
118
+
119
+
120
+ log = logging.getLogger("fontTools.ttx")
121
+
122
+ opentypeheaderRE = re.compile("""sfntVersion=['"]OTTO["']""")
123
+
124
+
125
+ class Options(object):
126
+ listTables = False
127
+ outputDir = None
128
+ outputFile = None
129
+ overWrite = False
130
+ verbose = False
131
+ quiet = False
132
+ splitTables = False
133
+ splitGlyphs = False
134
+ disassembleInstructions = True
135
+ mergeFile = None
136
+ recalcBBoxes = True
137
+ ignoreDecompileErrors = True
138
+ bitmapGlyphDataFormat = "raw"
139
+ unicodedata = None
140
+ newlinestr = "\n"
141
+ recalcTimestamp = None
142
+ flavor = None
143
+ useZopfli = False
144
+
145
+ def __init__(self, rawOptions, numFiles):
146
+ self.onlyTables = []
147
+ self.skipTables = []
148
+ self.fontNumber = -1
149
+ for option, value in rawOptions:
150
+ # general options
151
+ if option == "-h":
152
+ print(__doc__)
153
+ sys.exit(0)
154
+ elif option == "--version":
155
+ from fontTools import version
156
+
157
+ print(version)
158
+ sys.exit(0)
159
+ elif option == "-d":
160
+ if not os.path.isdir(value):
161
+ raise getopt.GetoptError(
162
+ "The -d option value must be an existing directory"
163
+ )
164
+ self.outputDir = value
165
+ elif option == "-o":
166
+ self.outputFile = value
167
+ elif option == "-f":
168
+ self.overWrite = True
169
+ elif option == "-v":
170
+ self.verbose = True
171
+ elif option == "-q":
172
+ self.quiet = True
173
+ # dump options
174
+ elif option == "-l":
175
+ self.listTables = True
176
+ elif option == "-t":
177
+ # pad with space if table tag length is less than 4
178
+ value = value.ljust(4)
179
+ self.onlyTables.append(value)
180
+ elif option == "-x":
181
+ # pad with space if table tag length is less than 4
182
+ value = value.ljust(4)
183
+ self.skipTables.append(value)
184
+ elif option == "-s":
185
+ self.splitTables = True
186
+ elif option == "-g":
187
+ # -g implies (and forces) splitTables
188
+ self.splitGlyphs = True
189
+ self.splitTables = True
190
+ elif option == "-i":
191
+ self.disassembleInstructions = False
192
+ elif option == "-z":
193
+ validOptions = ("raw", "row", "bitwise", "extfile")
194
+ if value not in validOptions:
195
+ raise getopt.GetoptError(
196
+ "-z does not allow %s as a format. Use %s"
197
+ % (option, validOptions)
198
+ )
199
+ self.bitmapGlyphDataFormat = value
200
+ elif option == "-y":
201
+ self.fontNumber = int(value)
202
+ # compile options
203
+ elif option == "-m":
204
+ self.mergeFile = value
205
+ elif option == "-b":
206
+ self.recalcBBoxes = False
207
+ elif option == "-e":
208
+ self.ignoreDecompileErrors = False
209
+ elif option == "--unicodedata":
210
+ self.unicodedata = value
211
+ elif option == "--newline":
212
+ validOptions = ("LF", "CR", "CRLF")
213
+ if value == "LF":
214
+ self.newlinestr = "\n"
215
+ elif value == "CR":
216
+ self.newlinestr = "\r"
217
+ elif value == "CRLF":
218
+ self.newlinestr = "\r\n"
219
+ else:
220
+ raise getopt.GetoptError(
221
+ "Invalid choice for --newline: %r (choose from %s)"
222
+ % (value, ", ".join(map(repr, validOptions)))
223
+ )
224
+ elif option == "--recalc-timestamp":
225
+ self.recalcTimestamp = True
226
+ elif option == "--no-recalc-timestamp":
227
+ self.recalcTimestamp = False
228
+ elif option == "--flavor":
229
+ self.flavor = value
230
+ elif option == "--with-zopfli":
231
+ self.useZopfli = True
232
+ if self.verbose and self.quiet:
233
+ raise getopt.GetoptError("-q and -v options are mutually exclusive")
234
+ if self.verbose:
235
+ self.logLevel = logging.DEBUG
236
+ elif self.quiet:
237
+ self.logLevel = logging.WARNING
238
+ else:
239
+ self.logLevel = logging.INFO
240
+ if self.mergeFile and self.flavor:
241
+ raise getopt.GetoptError("-m and --flavor options are mutually exclusive")
242
+ if self.onlyTables and self.skipTables:
243
+ raise getopt.GetoptError("-t and -x options are mutually exclusive")
244
+ if self.mergeFile and numFiles > 1:
245
+ raise getopt.GetoptError(
246
+ "Must specify exactly one TTX source file when using -m"
247
+ )
248
+ if self.flavor != "woff" and self.useZopfli:
249
+ raise getopt.GetoptError("--with-zopfli option requires --flavor 'woff'")
250
+
251
+
252
+ def ttList(input, output, options):
253
+ ttf = TTFont(input, fontNumber=options.fontNumber, lazy=True)
254
+ reader = ttf.reader
255
+ tags = sorted(reader.keys())
256
+ print('Listing table info for "%s":' % input)
257
+ format = " %4s %10s %8s %8s"
258
+ print(format % ("tag ", " checksum", " length", " offset"))
259
+ print(format % ("----", "----------", "--------", "--------"))
260
+ for tag in tags:
261
+ entry = reader.tables[tag]
262
+ if ttf.flavor == "woff2":
263
+ # WOFF2 doesn't store table checksums, so they must be calculated
264
+ from fontTools.ttLib.sfnt import calcChecksum
265
+
266
+ data = entry.loadData(reader.transformBuffer)
267
+ checkSum = calcChecksum(data)
268
+ else:
269
+ checkSum = int(entry.checkSum)
270
+ if checkSum < 0:
271
+ checkSum = checkSum + 0x100000000
272
+ checksum = "0x%08X" % checkSum
273
+ print(format % (tag, checksum, entry.length, entry.offset))
274
+ print()
275
+ ttf.close()
276
+
277
+
278
+ @Timer(log, "Done dumping TTX in %(time).3f seconds")
279
+ def ttDump(input, output, options):
280
+ input_name = input
281
+ if input == "-":
282
+ input, input_name = sys.stdin.buffer, sys.stdin.name
283
+ output_name = output
284
+ if output == "-":
285
+ output, output_name = sys.stdout, sys.stdout.name
286
+ log.info('Dumping "%s" to "%s"...', input_name, output_name)
287
+ if options.unicodedata:
288
+ setUnicodeData(options.unicodedata)
289
+ ttf = TTFont(
290
+ input,
291
+ 0,
292
+ ignoreDecompileErrors=options.ignoreDecompileErrors,
293
+ fontNumber=options.fontNumber,
294
+ )
295
+ ttf.saveXML(
296
+ output,
297
+ tables=options.onlyTables,
298
+ skipTables=options.skipTables,
299
+ splitTables=options.splitTables,
300
+ splitGlyphs=options.splitGlyphs,
301
+ disassembleInstructions=options.disassembleInstructions,
302
+ bitmapGlyphDataFormat=options.bitmapGlyphDataFormat,
303
+ newlinestr=options.newlinestr,
304
+ )
305
+ ttf.close()
306
+
307
+
308
+ @Timer(log, "Done compiling TTX in %(time).3f seconds")
309
+ def ttCompile(input, output, options):
310
+ input_name = input
311
+ if input == "-":
312
+ input, input_name = sys.stdin, sys.stdin.name
313
+ output_name = output
314
+ if output == "-":
315
+ output, output_name = sys.stdout.buffer, sys.stdout.name
316
+ log.info('Compiling "%s" to "%s"...' % (input_name, output))
317
+ if options.useZopfli:
318
+ from fontTools.ttLib import sfnt
319
+
320
+ sfnt.USE_ZOPFLI = True
321
+ ttf = TTFont(
322
+ options.mergeFile,
323
+ flavor=options.flavor,
324
+ recalcBBoxes=options.recalcBBoxes,
325
+ recalcTimestamp=options.recalcTimestamp,
326
+ )
327
+ ttf.importXML(input)
328
+
329
+ if options.recalcTimestamp is None and "head" in ttf and input is not sys.stdin:
330
+ # use TTX file modification time for head "modified" timestamp
331
+ mtime = os.path.getmtime(input)
332
+ ttf["head"].modified = timestampSinceEpoch(mtime)
333
+
334
+ ttf.save(output)
335
+
336
+
337
+ def guessFileType(fileName):
338
+ if fileName == "-":
339
+ header = sys.stdin.buffer.peek(256)
340
+ ext = ""
341
+ else:
342
+ base, ext = os.path.splitext(fileName)
343
+ try:
344
+ with open(fileName, "rb") as f:
345
+ header = f.read(256)
346
+ except IOError:
347
+ return None
348
+
349
+ if header.startswith(b"\xef\xbb\xbf<?xml"):
350
+ header = header.lstrip(b"\xef\xbb\xbf")
351
+ cr, tp = getMacCreatorAndType(fileName)
352
+ if tp in ("sfnt", "FFIL"):
353
+ return "TTF"
354
+ if ext == ".dfont":
355
+ return "TTF"
356
+ head = Tag(header[:4])
357
+ if head == "OTTO":
358
+ return "OTF"
359
+ elif head == "ttcf":
360
+ return "TTC"
361
+ elif head in ("\0\1\0\0", "true"):
362
+ return "TTF"
363
+ elif head == "wOFF":
364
+ return "WOFF"
365
+ elif head == "wOF2":
366
+ return "WOFF2"
367
+ elif head == "<?xm":
368
+ # Use 'latin1' because that can't fail.
369
+ header = tostr(header, "latin1")
370
+ if opentypeheaderRE.search(header):
371
+ return "OTX"
372
+ else:
373
+ return "TTX"
374
+ return None
375
+
376
+
377
+ def parseOptions(args):
378
+ rawOptions, files = getopt.gnu_getopt(
379
+ args,
380
+ "ld:o:fvqht:x:sgim:z:baey:",
381
+ [
382
+ "unicodedata=",
383
+ "recalc-timestamp",
384
+ "no-recalc-timestamp",
385
+ "flavor=",
386
+ "version",
387
+ "with-zopfli",
388
+ "newline=",
389
+ ],
390
+ )
391
+
392
+ options = Options(rawOptions, len(files))
393
+ jobs = []
394
+
395
+ if not files:
396
+ raise getopt.GetoptError("Must specify at least one input file")
397
+
398
+ for input in files:
399
+ if input != "-" and not os.path.isfile(input):
400
+ raise getopt.GetoptError('File not found: "%s"' % input)
401
+ tp = guessFileType(input)
402
+ if tp in ("OTF", "TTF", "TTC", "WOFF", "WOFF2"):
403
+ extension = ".ttx"
404
+ if options.listTables:
405
+ action = ttList
406
+ else:
407
+ action = ttDump
408
+ elif tp == "TTX":
409
+ extension = "." + options.flavor if options.flavor else ".ttf"
410
+ action = ttCompile
411
+ elif tp == "OTX":
412
+ extension = "." + options.flavor if options.flavor else ".otf"
413
+ action = ttCompile
414
+ else:
415
+ raise getopt.GetoptError('Unknown file type: "%s"' % input)
416
+
417
+ if options.outputFile:
418
+ output = options.outputFile
419
+ else:
420
+ if input == "-":
421
+ raise getopt.GetoptError("Must provide -o when reading from stdin")
422
+ output = makeOutputFileName(
423
+ input, options.outputDir, extension, options.overWrite
424
+ )
425
+ # 'touch' output file to avoid race condition in choosing file names
426
+ if action != ttList:
427
+ open(output, "a").close()
428
+ jobs.append((action, input, output))
429
+ return jobs, options
430
+
431
+
432
+ def process(jobs, options):
433
+ for action, input, output in jobs:
434
+ action(input, output, options)
435
+
436
+
437
+ def main(args=None):
438
+ """Convert OpenType fonts to XML and back"""
439
+ from fontTools import configLogger
440
+
441
+ if args is None:
442
+ args = sys.argv[1:]
443
+ try:
444
+ jobs, options = parseOptions(args)
445
+ except getopt.GetoptError as e:
446
+ print("%s\nERROR: %s" % (__doc__, e), file=sys.stderr)
447
+ sys.exit(2)
448
+
449
+ configLogger(level=options.logLevel)
450
+
451
+ try:
452
+ process(jobs, options)
453
+ except KeyboardInterrupt:
454
+ log.error("(Cancelled.)")
455
+ sys.exit(1)
456
+ except SystemExit:
457
+ raise
458
+ except TTLibError as e:
459
+ log.error(e)
460
+ sys.exit(1)
461
+ except:
462
+ log.exception("Unhandled exception has occurred")
463
+ sys.exit(1)
464
+
465
+
466
+ if __name__ == "__main__":
467
+ sys.exit(main())