jonghanko commited on
Commit
ec40039
·
verified ·
1 Parent(s): 96dd788

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. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/__init__.py +8 -0
  2. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/__main__.py +35 -0
  3. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/afmLib.py +439 -0
  4. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/agl.py +0 -0
  5. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/annotations.py +30 -0
  6. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/colorLib/builder.py +664 -0
  7. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/colorLib/unbuilder.py +81 -0
  8. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/config/__init__.py +90 -0
  9. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/__init__.py +15 -0
  10. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/__main__.py +6 -0
  11. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/benchmark.py +54 -0
  12. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/cli.py +198 -0
  13. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/cu2qu.c +0 -0
  14. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/cu2qu.py +563 -0
  15. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/errors.py +77 -0
  16. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/ufo.py +349 -0
  17. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/__init__.py +0 -0
  18. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/__main__.py +6 -0
  19. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/split.py +475 -0
  20. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/statNames.py +260 -0
  21. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/types.py +147 -0
  22. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/fontBuilder.py +1014 -0
  23. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/help.py +36 -0
  24. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/__init__.py +248 -0
  25. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/__main__.py +6 -0
  26. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/base.py +81 -0
  27. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/cmap.py +173 -0
  28. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/layout.py +526 -0
  29. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/options.py +85 -0
  30. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/tables.py +352 -0
  31. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/unicode.py +78 -0
  32. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/util.py +143 -0
  33. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/mtiLib/__init__.py +1400 -0
  34. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/mtiLib/__main__.py +5 -0
  35. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/__init__.py +1 -0
  36. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/builder.py +0 -0
  37. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/error.py +11 -0
  38. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/maxContextCalc.py +96 -0
  39. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/optimize/__init__.py +53 -0
  40. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/optimize/__main__.py +6 -0
  41. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/optimize/gpos.py +439 -0
  42. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/__init__.py +1 -0
  43. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/areaPen.py +52 -0
  44. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/cairoPen.py +26 -0
  45. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/cocoaPen.py +26 -0
  46. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/cu2quPen.py +325 -0
  47. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/freetypePen.py +462 -0
  48. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/t2CharStringPen.py +88 -0
  49. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/ttGlyphPen.py +335 -0
  50. Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/qu2cu/__init__.py +15 -0
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from fontTools.misc.loggingTools import configLogger
3
+
4
+ log = logging.getLogger(__name__)
5
+
6
+ version = __version__ = "4.60.1"
7
+
8
+ __all__ = ["version", "log", "configLogger"]
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/__main__.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+
4
+ def main(args=None):
5
+ if args is None:
6
+ args = sys.argv[1:]
7
+
8
+ # TODO Handle library-wide options. Eg.:
9
+ # --unicodedata
10
+ # --verbose / other logging stuff
11
+
12
+ # TODO Allow a way to run arbitrary modules? Useful for setting
13
+ # library-wide options and calling another library. Eg.:
14
+ #
15
+ # $ fonttools --unicodedata=... fontmake ...
16
+ #
17
+ # This allows for a git-like command where thirdparty commands
18
+ # can be added. Should we just try importing the fonttools
19
+ # module first and try without if it fails?
20
+
21
+ if len(sys.argv) < 2:
22
+ sys.argv.append("help")
23
+ if sys.argv[1] == "-h" or sys.argv[1] == "--help":
24
+ sys.argv[1] = "help"
25
+ mod = "fontTools." + sys.argv[1]
26
+ sys.argv[1] = sys.argv[0] + " " + sys.argv[1]
27
+ del sys.argv[0]
28
+
29
+ import runpy
30
+
31
+ runpy.run_module(mod, run_name="__main__")
32
+
33
+
34
+ if __name__ == "__main__":
35
+ sys.exit(main())
Scripts_Climate_n_LAI_to_Yield/.venv/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")
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/agl.py ADDED
The diff for this file is too large to render. See raw diff
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/annotations.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import TYPE_CHECKING, Iterable, Optional, TypeVar, Union
3
+ from collections.abc import Callable, Sequence
4
+ from fontTools.misc.filesystem._base import FS
5
+ from os import PathLike
6
+ from xml.etree.ElementTree import Element as ElementTreeElement
7
+
8
+ if TYPE_CHECKING:
9
+ from fontTools.ufoLib import UFOFormatVersion
10
+ from fontTools.ufoLib.glifLib import GLIFFormatVersion
11
+ from lxml.etree import _Element as LxmlElement
12
+
13
+
14
+ T = TypeVar("T") # Generic type
15
+ K = TypeVar("K") # Generic dict key type
16
+ V = TypeVar("V") # Generic dict value type
17
+
18
+ GlyphNameToFileNameFunc = Optional[Callable[[str, set[str]], str]]
19
+ ElementType = Union[ElementTreeElement, "LxmlElement"]
20
+ FormatVersion = Union[int, tuple[int, int]]
21
+ FormatVersions = Optional[Iterable[FormatVersion]]
22
+ GLIFFormatVersionInput = Optional[Union[int, tuple[int, int], "GLIFFormatVersion"]]
23
+ UFOFormatVersionInput = Optional[Union[int, tuple[int, int], "UFOFormatVersion"]]
24
+ IntFloat = Union[int, float]
25
+ KerningPair = tuple[str, str]
26
+ KerningDict = dict[KerningPair, IntFloat]
27
+ KerningGroups = dict[str, Sequence[str]]
28
+ KerningNested = dict[str, dict[str, IntFloat]]
29
+ PathStr = Union[str, PathLike[str]]
30
+ PathOrFS = Union[PathStr, FS]
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/colorLib/builder.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ colorLib.builder: Build COLR/CPAL tables from scratch
3
+
4
+ """
5
+
6
+ import collections
7
+ import copy
8
+ import enum
9
+ from functools import partial
10
+ from math import ceil, log
11
+ from typing import (
12
+ Any,
13
+ Dict,
14
+ Generator,
15
+ Iterable,
16
+ List,
17
+ Mapping,
18
+ Optional,
19
+ Sequence,
20
+ Tuple,
21
+ Type,
22
+ TypeVar,
23
+ Union,
24
+ )
25
+ from fontTools.misc.arrayTools import intRect
26
+ from fontTools.misc.fixedTools import fixedToFloat
27
+ from fontTools.misc.treeTools import build_n_ary_tree
28
+ from fontTools.ttLib.tables import C_O_L_R_
29
+ from fontTools.ttLib.tables import C_P_A_L_
30
+ from fontTools.ttLib.tables import _n_a_m_e
31
+ from fontTools.ttLib.tables import otTables as ot
32
+ from fontTools.ttLib.tables.otTables import ExtendMode, CompositeMode
33
+ from .errors import ColorLibError
34
+ from .geometry import round_start_circle_stable_containment
35
+ from .table_builder import BuildCallback, TableBuilder
36
+
37
+
38
+ # TODO move type aliases to colorLib.types?
39
+ T = TypeVar("T")
40
+ _Kwargs = Mapping[str, Any]
41
+ _PaintInput = Union[int, _Kwargs, ot.Paint, Tuple[str, "_PaintInput"]]
42
+ _PaintInputList = Sequence[_PaintInput]
43
+ _ColorGlyphsDict = Dict[str, Union[_PaintInputList, _PaintInput]]
44
+ _ColorGlyphsV0Dict = Dict[str, Sequence[Tuple[str, int]]]
45
+ _ClipBoxInput = Union[
46
+ Tuple[int, int, int, int, int], # format 1, variable
47
+ Tuple[int, int, int, int], # format 0, non-variable
48
+ ot.ClipBox,
49
+ ]
50
+
51
+
52
+ MAX_PAINT_COLR_LAYER_COUNT = 255
53
+ _DEFAULT_ALPHA = 1.0
54
+ _MAX_REUSE_LEN = 32
55
+
56
+
57
+ def _beforeBuildPaintRadialGradient(paint, source):
58
+ x0 = source["x0"]
59
+ y0 = source["y0"]
60
+ r0 = source["r0"]
61
+ x1 = source["x1"]
62
+ y1 = source["y1"]
63
+ r1 = source["r1"]
64
+
65
+ # TODO apparently no builder_test confirms this works (?)
66
+
67
+ # avoid abrupt change after rounding when c0 is near c1's perimeter
68
+ c = round_start_circle_stable_containment((x0, y0), r0, (x1, y1), r1)
69
+ x0, y0 = c.centre
70
+ r0 = c.radius
71
+
72
+ # update source to ensure paint is built with corrected values
73
+ source["x0"] = x0
74
+ source["y0"] = y0
75
+ source["r0"] = r0
76
+ source["x1"] = x1
77
+ source["y1"] = y1
78
+ source["r1"] = r1
79
+
80
+ return paint, source
81
+
82
+
83
+ def _defaultColorStop():
84
+ colorStop = ot.ColorStop()
85
+ colorStop.Alpha = _DEFAULT_ALPHA
86
+ return colorStop
87
+
88
+
89
+ def _defaultVarColorStop():
90
+ colorStop = ot.VarColorStop()
91
+ colorStop.Alpha = _DEFAULT_ALPHA
92
+ return colorStop
93
+
94
+
95
+ def _defaultColorLine():
96
+ colorLine = ot.ColorLine()
97
+ colorLine.Extend = ExtendMode.PAD
98
+ return colorLine
99
+
100
+
101
+ def _defaultVarColorLine():
102
+ colorLine = ot.VarColorLine()
103
+ colorLine.Extend = ExtendMode.PAD
104
+ return colorLine
105
+
106
+
107
+ def _defaultPaintSolid():
108
+ paint = ot.Paint()
109
+ paint.Alpha = _DEFAULT_ALPHA
110
+ return paint
111
+
112
+
113
+ def _buildPaintCallbacks():
114
+ return {
115
+ (
116
+ BuildCallback.BEFORE_BUILD,
117
+ ot.Paint,
118
+ ot.PaintFormat.PaintRadialGradient,
119
+ ): _beforeBuildPaintRadialGradient,
120
+ (
121
+ BuildCallback.BEFORE_BUILD,
122
+ ot.Paint,
123
+ ot.PaintFormat.PaintVarRadialGradient,
124
+ ): _beforeBuildPaintRadialGradient,
125
+ (BuildCallback.CREATE_DEFAULT, ot.ColorStop): _defaultColorStop,
126
+ (BuildCallback.CREATE_DEFAULT, ot.VarColorStop): _defaultVarColorStop,
127
+ (BuildCallback.CREATE_DEFAULT, ot.ColorLine): _defaultColorLine,
128
+ (BuildCallback.CREATE_DEFAULT, ot.VarColorLine): _defaultVarColorLine,
129
+ (
130
+ BuildCallback.CREATE_DEFAULT,
131
+ ot.Paint,
132
+ ot.PaintFormat.PaintSolid,
133
+ ): _defaultPaintSolid,
134
+ (
135
+ BuildCallback.CREATE_DEFAULT,
136
+ ot.Paint,
137
+ ot.PaintFormat.PaintVarSolid,
138
+ ): _defaultPaintSolid,
139
+ }
140
+
141
+
142
+ def populateCOLRv0(
143
+ table: ot.COLR,
144
+ colorGlyphsV0: _ColorGlyphsV0Dict,
145
+ glyphMap: Optional[Mapping[str, int]] = None,
146
+ ):
147
+ """Build v0 color layers and add to existing COLR table.
148
+
149
+ Args:
150
+ table: a raw ``otTables.COLR()`` object (not ttLib's ``table_C_O_L_R_``).
151
+ colorGlyphsV0: map of base glyph names to lists of (layer glyph names,
152
+ color palette index) tuples. Can be empty.
153
+ glyphMap: a map from glyph names to glyph indices, as returned from
154
+ ``TTFont.getReverseGlyphMap()``, to optionally sort base records by GID.
155
+ """
156
+ if glyphMap is not None:
157
+ colorGlyphItems = sorted(
158
+ colorGlyphsV0.items(), key=lambda item: glyphMap[item[0]]
159
+ )
160
+ else:
161
+ colorGlyphItems = colorGlyphsV0.items()
162
+ baseGlyphRecords = []
163
+ layerRecords = []
164
+ for baseGlyph, layers in colorGlyphItems:
165
+ baseRec = ot.BaseGlyphRecord()
166
+ baseRec.BaseGlyph = baseGlyph
167
+ baseRec.FirstLayerIndex = len(layerRecords)
168
+ baseRec.NumLayers = len(layers)
169
+ baseGlyphRecords.append(baseRec)
170
+
171
+ for layerGlyph, paletteIndex in layers:
172
+ layerRec = ot.LayerRecord()
173
+ layerRec.LayerGlyph = layerGlyph
174
+ layerRec.PaletteIndex = paletteIndex
175
+ layerRecords.append(layerRec)
176
+
177
+ table.BaseGlyphRecordArray = table.LayerRecordArray = None
178
+ if baseGlyphRecords:
179
+ table.BaseGlyphRecordArray = ot.BaseGlyphRecordArray()
180
+ table.BaseGlyphRecordArray.BaseGlyphRecord = baseGlyphRecords
181
+ if layerRecords:
182
+ table.LayerRecordArray = ot.LayerRecordArray()
183
+ table.LayerRecordArray.LayerRecord = layerRecords
184
+ table.BaseGlyphRecordCount = len(baseGlyphRecords)
185
+ table.LayerRecordCount = len(layerRecords)
186
+
187
+
188
+ def buildCOLR(
189
+ colorGlyphs: _ColorGlyphsDict,
190
+ version: Optional[int] = None,
191
+ *,
192
+ glyphMap: Optional[Mapping[str, int]] = None,
193
+ varStore: Optional[ot.VarStore] = None,
194
+ varIndexMap: Optional[ot.DeltaSetIndexMap] = None,
195
+ clipBoxes: Optional[Dict[str, _ClipBoxInput]] = None,
196
+ allowLayerReuse: bool = True,
197
+ ) -> C_O_L_R_.table_C_O_L_R_:
198
+ """Build COLR table from color layers mapping.
199
+
200
+ Args:
201
+
202
+ colorGlyphs: map of base glyph name to, either list of (layer glyph name,
203
+ color palette index) tuples for COLRv0; or a single ``Paint`` (dict) or
204
+ list of ``Paint`` for COLRv1.
205
+ version: the version of COLR table. If None, the version is determined
206
+ by the presence of COLRv1 paints or variation data (varStore), which
207
+ require version 1; otherwise, if all base glyphs use only simple color
208
+ layers, version 0 is used.
209
+ glyphMap: a map from glyph names to glyph indices, as returned from
210
+ TTFont.getReverseGlyphMap(), to optionally sort base records by GID.
211
+ varStore: Optional ItemVarationStore for deltas associated with v1 layer.
212
+ varIndexMap: Optional DeltaSetIndexMap for deltas associated with v1 layer.
213
+ clipBoxes: Optional map of base glyph name to clip box 4- or 5-tuples:
214
+ (xMin, yMin, xMax, yMax) or (xMin, yMin, xMax, yMax, varIndexBase).
215
+
216
+ Returns:
217
+ A new COLR table.
218
+ """
219
+ self = C_O_L_R_.table_C_O_L_R_()
220
+
221
+ if varStore is not None and version == 0:
222
+ raise ValueError("Can't add VarStore to COLRv0")
223
+
224
+ if version in (None, 0) and not varStore:
225
+ # split color glyphs into v0 and v1 and encode separately
226
+ colorGlyphsV0, colorGlyphsV1 = _split_color_glyphs_by_version(colorGlyphs)
227
+ if version == 0 and colorGlyphsV1:
228
+ raise ValueError("Can't encode COLRv1 glyphs in COLRv0")
229
+ else:
230
+ # unless explicitly requested for v1 or have variations, in which case
231
+ # we encode all color glyph as v1
232
+ colorGlyphsV0, colorGlyphsV1 = {}, colorGlyphs
233
+
234
+ colr = ot.COLR()
235
+
236
+ populateCOLRv0(colr, colorGlyphsV0, glyphMap)
237
+
238
+ colr.LayerList, colr.BaseGlyphList = buildColrV1(
239
+ colorGlyphsV1,
240
+ glyphMap,
241
+ allowLayerReuse=allowLayerReuse,
242
+ )
243
+
244
+ if version is None:
245
+ version = 1 if (varStore or colorGlyphsV1) else 0
246
+ elif version not in (0, 1):
247
+ raise NotImplementedError(version)
248
+ self.version = colr.Version = version
249
+
250
+ if version == 0:
251
+ self.ColorLayers = self._decompileColorLayersV0(colr)
252
+ else:
253
+ colr.ClipList = buildClipList(clipBoxes) if clipBoxes else None
254
+ colr.VarIndexMap = varIndexMap
255
+ colr.VarStore = varStore
256
+ self.table = colr
257
+
258
+ return self
259
+
260
+
261
+ def buildClipList(clipBoxes: Dict[str, _ClipBoxInput]) -> ot.ClipList:
262
+ clipList = ot.ClipList()
263
+ clipList.Format = 1
264
+ clipList.clips = {name: buildClipBox(box) for name, box in clipBoxes.items()}
265
+ return clipList
266
+
267
+
268
+ def buildClipBox(clipBox: _ClipBoxInput) -> ot.ClipBox:
269
+ if isinstance(clipBox, ot.ClipBox):
270
+ return clipBox
271
+ n = len(clipBox)
272
+ clip = ot.ClipBox()
273
+ if n not in (4, 5):
274
+ raise ValueError(f"Invalid ClipBox: expected 4 or 5 values, found {n}")
275
+ clip.xMin, clip.yMin, clip.xMax, clip.yMax = intRect(clipBox[:4])
276
+ clip.Format = int(n == 5) + 1
277
+ if n == 5:
278
+ clip.VarIndexBase = int(clipBox[4])
279
+ return clip
280
+
281
+
282
+ class ColorPaletteType(enum.IntFlag):
283
+ USABLE_WITH_LIGHT_BACKGROUND = 0x0001
284
+ USABLE_WITH_DARK_BACKGROUND = 0x0002
285
+
286
+ @classmethod
287
+ def _missing_(cls, value):
288
+ # enforce reserved bits
289
+ if isinstance(value, int) and (value < 0 or value & 0xFFFC != 0):
290
+ raise ValueError(f"{value} is not a valid {cls.__name__}")
291
+ return super()._missing_(value)
292
+
293
+
294
+ # None, 'abc' or {'en': 'abc', 'de': 'xyz'}
295
+ _OptionalLocalizedString = Union[None, str, Dict[str, str]]
296
+
297
+
298
+ def buildPaletteLabels(
299
+ labels: Iterable[_OptionalLocalizedString], nameTable: _n_a_m_e.table__n_a_m_e
300
+ ) -> List[Optional[int]]:
301
+ return [
302
+ (
303
+ nameTable.addMultilingualName(l, mac=False)
304
+ if isinstance(l, dict)
305
+ else (
306
+ C_P_A_L_.table_C_P_A_L_.NO_NAME_ID
307
+ if l is None
308
+ else nameTable.addMultilingualName({"en": l}, mac=False)
309
+ )
310
+ )
311
+ for l in labels
312
+ ]
313
+
314
+
315
+ def buildCPAL(
316
+ palettes: Sequence[Sequence[Tuple[float, float, float, float]]],
317
+ paletteTypes: Optional[Sequence[ColorPaletteType]] = None,
318
+ paletteLabels: Optional[Sequence[_OptionalLocalizedString]] = None,
319
+ paletteEntryLabels: Optional[Sequence[_OptionalLocalizedString]] = None,
320
+ nameTable: Optional[_n_a_m_e.table__n_a_m_e] = None,
321
+ ) -> C_P_A_L_.table_C_P_A_L_:
322
+ """Build CPAL table from list of color palettes.
323
+
324
+ Args:
325
+ palettes: list of lists of colors encoded as tuples of (R, G, B, A) floats
326
+ in the range [0..1].
327
+ paletteTypes: optional list of ColorPaletteType, one for each palette.
328
+ paletteLabels: optional list of palette labels. Each lable can be either:
329
+ None (no label), a string (for for default English labels), or a
330
+ localized string (as a dict keyed with BCP47 language codes).
331
+ paletteEntryLabels: optional list of palette entry labels, one for each
332
+ palette entry (see paletteLabels).
333
+ nameTable: optional name table where to store palette and palette entry
334
+ labels. Required if either paletteLabels or paletteEntryLabels is set.
335
+
336
+ Return:
337
+ A new CPAL v0 or v1 table, if custom palette types or labels are specified.
338
+ """
339
+ if len({len(p) for p in palettes}) != 1:
340
+ raise ColorLibError("color palettes have different lengths")
341
+
342
+ if (paletteLabels or paletteEntryLabels) and not nameTable:
343
+ raise TypeError(
344
+ "nameTable is required if palette or palette entries have labels"
345
+ )
346
+
347
+ cpal = C_P_A_L_.table_C_P_A_L_()
348
+ cpal.numPaletteEntries = len(palettes[0])
349
+
350
+ cpal.palettes = []
351
+ for i, palette in enumerate(palettes):
352
+ colors = []
353
+ for j, color in enumerate(palette):
354
+ if not isinstance(color, tuple) or len(color) != 4:
355
+ raise ColorLibError(
356
+ f"In palette[{i}][{j}]: expected (R, G, B, A) tuple, got {color!r}"
357
+ )
358
+ if any(v > 1 or v < 0 for v in color):
359
+ raise ColorLibError(
360
+ f"palette[{i}][{j}] has invalid out-of-range [0..1] color: {color!r}"
361
+ )
362
+ # input colors are RGBA, CPAL encodes them as BGRA
363
+ red, green, blue, alpha = color
364
+ colors.append(
365
+ C_P_A_L_.Color(*(round(v * 255) for v in (blue, green, red, alpha)))
366
+ )
367
+ cpal.palettes.append(colors)
368
+
369
+ if any(v is not None for v in (paletteTypes, paletteLabels, paletteEntryLabels)):
370
+ cpal.version = 1
371
+
372
+ if paletteTypes is not None:
373
+ if len(paletteTypes) != len(palettes):
374
+ raise ColorLibError(
375
+ f"Expected {len(palettes)} paletteTypes, got {len(paletteTypes)}"
376
+ )
377
+ cpal.paletteTypes = [ColorPaletteType(t).value for t in paletteTypes]
378
+ else:
379
+ cpal.paletteTypes = [C_P_A_L_.table_C_P_A_L_.DEFAULT_PALETTE_TYPE] * len(
380
+ palettes
381
+ )
382
+
383
+ if paletteLabels is not None:
384
+ if len(paletteLabels) != len(palettes):
385
+ raise ColorLibError(
386
+ f"Expected {len(palettes)} paletteLabels, got {len(paletteLabels)}"
387
+ )
388
+ cpal.paletteLabels = buildPaletteLabels(paletteLabels, nameTable)
389
+ else:
390
+ cpal.paletteLabels = [C_P_A_L_.table_C_P_A_L_.NO_NAME_ID] * len(palettes)
391
+
392
+ if paletteEntryLabels is not None:
393
+ if len(paletteEntryLabels) != cpal.numPaletteEntries:
394
+ raise ColorLibError(
395
+ f"Expected {cpal.numPaletteEntries} paletteEntryLabels, "
396
+ f"got {len(paletteEntryLabels)}"
397
+ )
398
+ cpal.paletteEntryLabels = buildPaletteLabels(paletteEntryLabels, nameTable)
399
+ else:
400
+ cpal.paletteEntryLabels = [
401
+ C_P_A_L_.table_C_P_A_L_.NO_NAME_ID
402
+ ] * cpal.numPaletteEntries
403
+ else:
404
+ cpal.version = 0
405
+
406
+ return cpal
407
+
408
+
409
+ # COLR v1 tables
410
+ # See draft proposal at: https://github.com/googlefonts/colr-gradients-spec
411
+
412
+
413
+ def _is_colrv0_layer(layer: Any) -> bool:
414
+ # Consider as COLRv0 layer any sequence of length 2 (be it tuple or list) in which
415
+ # the first element is a str (the layerGlyph) and the second element is an int
416
+ # (CPAL paletteIndex).
417
+ # https://github.com/googlefonts/ufo2ft/issues/426
418
+ try:
419
+ layerGlyph, paletteIndex = layer
420
+ except (TypeError, ValueError):
421
+ return False
422
+ else:
423
+ return isinstance(layerGlyph, str) and isinstance(paletteIndex, int)
424
+
425
+
426
+ def _split_color_glyphs_by_version(
427
+ colorGlyphs: _ColorGlyphsDict,
428
+ ) -> Tuple[_ColorGlyphsV0Dict, _ColorGlyphsDict]:
429
+ colorGlyphsV0 = {}
430
+ colorGlyphsV1 = {}
431
+ for baseGlyph, layers in colorGlyphs.items():
432
+ if all(_is_colrv0_layer(l) for l in layers):
433
+ colorGlyphsV0[baseGlyph] = layers
434
+ else:
435
+ colorGlyphsV1[baseGlyph] = layers
436
+
437
+ # sanity check
438
+ assert set(colorGlyphs) == (set(colorGlyphsV0) | set(colorGlyphsV1))
439
+
440
+ return colorGlyphsV0, colorGlyphsV1
441
+
442
+
443
+ def _reuse_ranges(num_layers: int) -> Generator[Tuple[int, int], None, None]:
444
+ # TODO feels like something itertools might have already
445
+ for lbound in range(num_layers):
446
+ # Reuse of very large #s of layers is relatively unlikely
447
+ # +2: we want sequences of at least 2
448
+ # otData handles single-record duplication
449
+ for ubound in range(
450
+ lbound + 2, min(num_layers + 1, lbound + 2 + _MAX_REUSE_LEN)
451
+ ):
452
+ yield (lbound, ubound)
453
+
454
+
455
+ class LayerReuseCache:
456
+ reusePool: Mapping[Tuple[Any, ...], int]
457
+ tuples: Mapping[int, Tuple[Any, ...]]
458
+ keepAlive: List[ot.Paint] # we need id to remain valid
459
+
460
+ def __init__(self):
461
+ self.reusePool = {}
462
+ self.tuples = {}
463
+ self.keepAlive = []
464
+
465
+ def _paint_tuple(self, paint: ot.Paint):
466
+ # start simple, who even cares about cyclic graphs or interesting field types
467
+ def _tuple_safe(value):
468
+ if isinstance(value, enum.Enum):
469
+ return value
470
+ elif hasattr(value, "__dict__"):
471
+ return tuple(
472
+ (k, _tuple_safe(v)) for k, v in sorted(value.__dict__.items())
473
+ )
474
+ elif isinstance(value, collections.abc.MutableSequence):
475
+ return tuple(_tuple_safe(e) for e in value)
476
+ return value
477
+
478
+ # Cache the tuples for individual Paint instead of the whole sequence
479
+ # because the seq could be a transient slice
480
+ result = self.tuples.get(id(paint), None)
481
+ if result is None:
482
+ result = _tuple_safe(paint)
483
+ self.tuples[id(paint)] = result
484
+ self.keepAlive.append(paint)
485
+ return result
486
+
487
+ def _as_tuple(self, paints: Sequence[ot.Paint]) -> Tuple[Any, ...]:
488
+ return tuple(self._paint_tuple(p) for p in paints)
489
+
490
+ def try_reuse(self, layers: List[ot.Paint]) -> List[ot.Paint]:
491
+ found_reuse = True
492
+ while found_reuse:
493
+ found_reuse = False
494
+
495
+ ranges = sorted(
496
+ _reuse_ranges(len(layers)),
497
+ key=lambda t: (t[1] - t[0], t[1], t[0]),
498
+ reverse=True,
499
+ )
500
+ for lbound, ubound in ranges:
501
+ reuse_lbound = self.reusePool.get(
502
+ self._as_tuple(layers[lbound:ubound]), -1
503
+ )
504
+ if reuse_lbound == -1:
505
+ continue
506
+ new_slice = ot.Paint()
507
+ new_slice.Format = int(ot.PaintFormat.PaintColrLayers)
508
+ new_slice.NumLayers = ubound - lbound
509
+ new_slice.FirstLayerIndex = reuse_lbound
510
+ layers = layers[:lbound] + [new_slice] + layers[ubound:]
511
+ found_reuse = True
512
+ break
513
+ return layers
514
+
515
+ def add(self, layers: List[ot.Paint], first_layer_index: int):
516
+ for lbound, ubound in _reuse_ranges(len(layers)):
517
+ self.reusePool[self._as_tuple(layers[lbound:ubound])] = (
518
+ lbound + first_layer_index
519
+ )
520
+
521
+
522
+ class LayerListBuilder:
523
+ layers: List[ot.Paint]
524
+ cache: LayerReuseCache
525
+ allowLayerReuse: bool
526
+
527
+ def __init__(self, *, allowLayerReuse=True):
528
+ self.layers = []
529
+ if allowLayerReuse:
530
+ self.cache = LayerReuseCache()
531
+ else:
532
+ self.cache = None
533
+
534
+ # We need to intercept construction of PaintColrLayers
535
+ callbacks = _buildPaintCallbacks()
536
+ callbacks[
537
+ (
538
+ BuildCallback.BEFORE_BUILD,
539
+ ot.Paint,
540
+ ot.PaintFormat.PaintColrLayers,
541
+ )
542
+ ] = self._beforeBuildPaintColrLayers
543
+ self.tableBuilder = TableBuilder(callbacks)
544
+
545
+ # COLR layers is unusual in that it modifies shared state
546
+ # so we need a callback into an object
547
+ def _beforeBuildPaintColrLayers(self, dest, source):
548
+ # Sketchy gymnastics: a sequence input will have dropped it's layers
549
+ # into NumLayers; get it back
550
+ if isinstance(source.get("NumLayers", None), collections.abc.Sequence):
551
+ layers = source["NumLayers"]
552
+ else:
553
+ layers = source["Layers"]
554
+
555
+ # Convert maps seqs or whatever into typed objects
556
+ layers = [self.buildPaint(l) for l in layers]
557
+
558
+ # No reason to have a colr layers with just one entry
559
+ if len(layers) == 1:
560
+ return layers[0], {}
561
+
562
+ if self.cache is not None:
563
+ # Look for reuse, with preference to longer sequences
564
+ # This may make the layer list smaller
565
+ layers = self.cache.try_reuse(layers)
566
+
567
+ # The layer list is now final; if it's too big we need to tree it
568
+ is_tree = len(layers) > MAX_PAINT_COLR_LAYER_COUNT
569
+ layers = build_n_ary_tree(layers, n=MAX_PAINT_COLR_LAYER_COUNT)
570
+
571
+ # We now have a tree of sequences with Paint leaves.
572
+ # Convert the sequences into PaintColrLayers.
573
+ def listToColrLayers(layer):
574
+ if isinstance(layer, collections.abc.Sequence):
575
+ return self.buildPaint(
576
+ {
577
+ "Format": ot.PaintFormat.PaintColrLayers,
578
+ "Layers": [listToColrLayers(l) for l in layer],
579
+ }
580
+ )
581
+ return layer
582
+
583
+ layers = [listToColrLayers(l) for l in layers]
584
+
585
+ # No reason to have a colr layers with just one entry
586
+ if len(layers) == 1:
587
+ return layers[0], {}
588
+
589
+ paint = ot.Paint()
590
+ paint.Format = int(ot.PaintFormat.PaintColrLayers)
591
+ paint.NumLayers = len(layers)
592
+ paint.FirstLayerIndex = len(self.layers)
593
+ self.layers.extend(layers)
594
+
595
+ # Register our parts for reuse provided we aren't a tree
596
+ # If we are a tree the leaves registered for reuse and that will suffice
597
+ if self.cache is not None and not is_tree:
598
+ self.cache.add(layers, paint.FirstLayerIndex)
599
+
600
+ # we've fully built dest; empty source prevents generalized build from kicking in
601
+ return paint, {}
602
+
603
+ def buildPaint(self, paint: _PaintInput) -> ot.Paint:
604
+ return self.tableBuilder.build(ot.Paint, paint)
605
+
606
+ def build(self) -> Optional[ot.LayerList]:
607
+ if not self.layers:
608
+ return None
609
+ layers = ot.LayerList()
610
+ layers.LayerCount = len(self.layers)
611
+ layers.Paint = self.layers
612
+ return layers
613
+
614
+
615
+ def buildBaseGlyphPaintRecord(
616
+ baseGlyph: str, layerBuilder: LayerListBuilder, paint: _PaintInput
617
+ ) -> ot.BaseGlyphList:
618
+ self = ot.BaseGlyphPaintRecord()
619
+ self.BaseGlyph = baseGlyph
620
+ self.Paint = layerBuilder.buildPaint(paint)
621
+ return self
622
+
623
+
624
+ def _format_glyph_errors(errors: Mapping[str, Exception]) -> str:
625
+ lines = []
626
+ for baseGlyph, error in sorted(errors.items()):
627
+ lines.append(f" {baseGlyph} => {type(error).__name__}: {error}")
628
+ return "\n".join(lines)
629
+
630
+
631
+ def buildColrV1(
632
+ colorGlyphs: _ColorGlyphsDict,
633
+ glyphMap: Optional[Mapping[str, int]] = None,
634
+ *,
635
+ allowLayerReuse: bool = True,
636
+ ) -> Tuple[Optional[ot.LayerList], ot.BaseGlyphList]:
637
+ if glyphMap is not None:
638
+ colorGlyphItems = sorted(
639
+ colorGlyphs.items(), key=lambda item: glyphMap[item[0]]
640
+ )
641
+ else:
642
+ colorGlyphItems = colorGlyphs.items()
643
+
644
+ errors = {}
645
+ baseGlyphs = []
646
+ layerBuilder = LayerListBuilder(allowLayerReuse=allowLayerReuse)
647
+ for baseGlyph, paint in colorGlyphItems:
648
+ try:
649
+ baseGlyphs.append(buildBaseGlyphPaintRecord(baseGlyph, layerBuilder, paint))
650
+
651
+ except (ColorLibError, OverflowError, ValueError, TypeError) as e:
652
+ errors[baseGlyph] = e
653
+
654
+ if errors:
655
+ failed_glyphs = _format_glyph_errors(errors)
656
+ exc = ColorLibError(f"Failed to build BaseGlyphList:\n{failed_glyphs}")
657
+ exc.errors = errors
658
+ raise exc from next(iter(errors.values()))
659
+
660
+ layers = layerBuilder.build()
661
+ glyphs = ot.BaseGlyphList()
662
+ glyphs.BaseGlyphCount = len(baseGlyphs)
663
+ glyphs.BaseGlyphPaintRecord = baseGlyphs
664
+ return (layers, glyphs)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/colorLib/unbuilder.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.ttLib.tables import otTables as ot
2
+ from .table_builder import TableUnbuilder
3
+
4
+
5
+ def unbuildColrV1(layerList, baseGlyphList):
6
+ layers = []
7
+ if layerList:
8
+ layers = layerList.Paint
9
+ unbuilder = LayerListUnbuilder(layers)
10
+ return {
11
+ rec.BaseGlyph: unbuilder.unbuildPaint(rec.Paint)
12
+ for rec in baseGlyphList.BaseGlyphPaintRecord
13
+ }
14
+
15
+
16
+ def _flatten_layers(lst):
17
+ for paint in lst:
18
+ if paint["Format"] == ot.PaintFormat.PaintColrLayers:
19
+ yield from _flatten_layers(paint["Layers"])
20
+ else:
21
+ yield paint
22
+
23
+
24
+ class LayerListUnbuilder:
25
+ def __init__(self, layers):
26
+ self.layers = layers
27
+
28
+ callbacks = {
29
+ (
30
+ ot.Paint,
31
+ ot.PaintFormat.PaintColrLayers,
32
+ ): self._unbuildPaintColrLayers,
33
+ }
34
+ self.tableUnbuilder = TableUnbuilder(callbacks)
35
+
36
+ def unbuildPaint(self, paint):
37
+ assert isinstance(paint, ot.Paint)
38
+ return self.tableUnbuilder.unbuild(paint)
39
+
40
+ def _unbuildPaintColrLayers(self, source):
41
+ assert source["Format"] == ot.PaintFormat.PaintColrLayers
42
+
43
+ layers = list(
44
+ _flatten_layers(
45
+ [
46
+ self.unbuildPaint(childPaint)
47
+ for childPaint in self.layers[
48
+ source["FirstLayerIndex"] : source["FirstLayerIndex"]
49
+ + source["NumLayers"]
50
+ ]
51
+ ]
52
+ )
53
+ )
54
+
55
+ if len(layers) == 1:
56
+ return layers[0]
57
+
58
+ return {"Format": source["Format"], "Layers": layers}
59
+
60
+
61
+ if __name__ == "__main__":
62
+ from pprint import pprint
63
+ import sys
64
+ from fontTools.ttLib import TTFont
65
+
66
+ try:
67
+ fontfile = sys.argv[1]
68
+ except IndexError:
69
+ sys.exit("usage: fonttools colorLib.unbuilder FONTFILE")
70
+
71
+ font = TTFont(fontfile)
72
+ colr = font["COLR"]
73
+ if colr.version < 1:
74
+ sys.exit(f"error: No COLR table version=1 found in {fontfile}")
75
+
76
+ colorGlyphs = unbuildColrV1(
77
+ colr.table.LayerList,
78
+ colr.table.BaseGlyphList,
79
+ )
80
+
81
+ pprint(colorGlyphs)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/config/__init__.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Define all configuration options that can affect the working of fontTools
3
+ modules. E.g. optimization levels of varLib IUP, otlLib GPOS compression level,
4
+ etc. If this file gets too big, split it into smaller files per-module.
5
+
6
+ An instance of the Config class can be attached to a TTFont object, so that
7
+ the various modules can access their configuration options from it.
8
+ """
9
+
10
+ from textwrap import dedent
11
+
12
+ from fontTools.misc.configTools import *
13
+
14
+
15
+ class Config(AbstractConfig):
16
+ options = Options()
17
+
18
+
19
+ OPTIONS = Config.options
20
+
21
+
22
+ Config.register_option(
23
+ name="fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL",
24
+ help=dedent(
25
+ """\
26
+ GPOS Lookup type 2 (PairPos) compression level:
27
+ 0 = do not attempt to compact PairPos lookups;
28
+ 1 to 8 = create at most 1 to 8 new subtables for each existing
29
+ subtable, provided that it would yield a 50%% file size saving;
30
+ 9 = create as many new subtables as needed to yield a file size saving.
31
+ Default: 0.
32
+
33
+ This compaction aims to save file size, by splitting large class
34
+ kerning subtables (Format 2) that contain many zero values into
35
+ smaller and denser subtables. It's a trade-off between the overhead
36
+ of several subtables versus the sparseness of one big subtable.
37
+
38
+ See the pull request: https://github.com/fonttools/fonttools/pull/2326
39
+ """
40
+ ),
41
+ default=0,
42
+ parse=int,
43
+ validate=lambda v: v in range(10),
44
+ )
45
+
46
+ Config.register_option(
47
+ name="fontTools.ttLib.tables.otBase:USE_HARFBUZZ_REPACKER",
48
+ help=dedent(
49
+ """\
50
+ FontTools tries to use the HarfBuzz Repacker to serialize GPOS/GSUB tables
51
+ if the uharfbuzz python bindings are importable, otherwise falls back to its
52
+ slower, less efficient serializer. Set to False to always use the latter.
53
+ Set to True to explicitly request the HarfBuzz Repacker (will raise an
54
+ error if uharfbuzz cannot be imported).
55
+ """
56
+ ),
57
+ default=None,
58
+ parse=Option.parse_optional_bool,
59
+ validate=Option.validate_optional_bool,
60
+ )
61
+
62
+ Config.register_option(
63
+ name="fontTools.otlLib.builder:WRITE_GPOS7",
64
+ help=dedent(
65
+ """\
66
+ macOS before 13.2 didn’t support GPOS LookupType 7 (non-chaining
67
+ ContextPos lookups), so FontTools.otlLib.builder disables a file size
68
+ optimisation that would use LookupType 7 instead of 8 when there is no
69
+ chaining (no prefix or suffix). Set to True to enable the optimization.
70
+ """
71
+ ),
72
+ default=False,
73
+ parse=Option.parse_optional_bool,
74
+ validate=Option.validate_optional_bool,
75
+ )
76
+
77
+ Config.register_option(
78
+ name="fontTools.ttLib:OPTIMIZE_FONT_SPEED",
79
+ help=dedent(
80
+ """\
81
+ Enable optimizations that prioritize speed over file size. This
82
+ mainly affects how glyf table and gvar / VARC tables are compiled.
83
+ The produced fonts will be larger, but rendering performance will
84
+ be improved with HarfBuzz and other text layout engines.
85
+ """
86
+ ),
87
+ default=False,
88
+ parse=Option.parse_optional_bool,
89
+ validate=Option.validate_optional_bool,
90
+ )
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Google Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .cu2qu import *
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/__main__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import sys
2
+ from .cli import _main as main
3
+
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/benchmark.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Benchmark the cu2qu algorithm performance."""
2
+
3
+ from .cu2qu import *
4
+ import random
5
+ import timeit
6
+
7
+ MAX_ERR = 0.05
8
+
9
+
10
+ def generate_curve():
11
+ return [
12
+ tuple(float(random.randint(0, 2048)) for coord in range(2))
13
+ for point in range(4)
14
+ ]
15
+
16
+
17
+ def setup_curve_to_quadratic():
18
+ return generate_curve(), MAX_ERR
19
+
20
+
21
+ def setup_curves_to_quadratic():
22
+ num_curves = 3
23
+ return ([generate_curve() for curve in range(num_curves)], [MAX_ERR] * num_curves)
24
+
25
+
26
+ def run_benchmark(module, function, setup_suffix="", repeat=5, number=1000):
27
+ setup_func = "setup_" + function
28
+ if setup_suffix:
29
+ print("%s with %s:" % (function, setup_suffix), end="")
30
+ setup_func += "_" + setup_suffix
31
+ else:
32
+ print("%s:" % function, end="")
33
+
34
+ def wrapper(function, setup_func):
35
+ function = globals()[function]
36
+ setup_func = globals()[setup_func]
37
+
38
+ def wrapped():
39
+ return function(*setup_func())
40
+
41
+ return wrapped
42
+
43
+ results = timeit.repeat(wrapper(function, setup_func), repeat=repeat, number=number)
44
+ print("\t%5.1fus" % (min(results) * 1000000.0 / number))
45
+
46
+
47
+ def main():
48
+ run_benchmark("cu2qu", "curve_to_quadratic")
49
+ run_benchmark("cu2qu", "curves_to_quadratic")
50
+
51
+
52
+ if __name__ == "__main__":
53
+ random.seed(1)
54
+ main()
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/cli.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ import logging
4
+ import shutil
5
+ import multiprocessing as mp
6
+ from contextlib import closing
7
+ from functools import partial
8
+
9
+ import fontTools
10
+ from .ufo import font_to_quadratic, fonts_to_quadratic
11
+
12
+ ufo_module = None
13
+ try:
14
+ import ufoLib2 as ufo_module
15
+ except ImportError:
16
+ try:
17
+ import defcon as ufo_module
18
+ except ImportError as e:
19
+ pass
20
+
21
+
22
+ logger = logging.getLogger("fontTools.cu2qu")
23
+
24
+
25
+ def _cpu_count():
26
+ try:
27
+ return mp.cpu_count()
28
+ except NotImplementedError: # pragma: no cover
29
+ return 1
30
+
31
+
32
+ def open_ufo(path):
33
+ if hasattr(ufo_module.Font, "open"): # ufoLib2
34
+ return ufo_module.Font.open(path)
35
+ return ufo_module.Font(path) # defcon
36
+
37
+
38
+ def _font_to_quadratic(input_path, output_path=None, **kwargs):
39
+ ufo = open_ufo(input_path)
40
+ logger.info("Converting curves for %s", input_path)
41
+ if font_to_quadratic(ufo, **kwargs):
42
+ logger.info("Saving %s", output_path)
43
+ if output_path:
44
+ ufo.save(output_path)
45
+ else:
46
+ ufo.save() # save in-place
47
+ elif output_path:
48
+ _copytree(input_path, output_path)
49
+
50
+
51
+ def _samepath(path1, path2):
52
+ # TODO on python3+, there's os.path.samefile
53
+ path1 = os.path.normcase(os.path.abspath(os.path.realpath(path1)))
54
+ path2 = os.path.normcase(os.path.abspath(os.path.realpath(path2)))
55
+ return path1 == path2
56
+
57
+
58
+ def _copytree(input_path, output_path):
59
+ if _samepath(input_path, output_path):
60
+ logger.debug("input and output paths are the same file; skipped copy")
61
+ return
62
+ if os.path.exists(output_path):
63
+ shutil.rmtree(output_path)
64
+ shutil.copytree(input_path, output_path)
65
+
66
+
67
+ def _main(args=None):
68
+ """Convert a UFO font from cubic to quadratic curves"""
69
+ parser = argparse.ArgumentParser(prog="cu2qu")
70
+ parser.add_argument("--version", action="version", version=fontTools.__version__)
71
+ parser.add_argument(
72
+ "infiles",
73
+ nargs="+",
74
+ metavar="INPUT",
75
+ help="one or more input UFO source file(s).",
76
+ )
77
+ parser.add_argument("-v", "--verbose", action="count", default=0)
78
+ parser.add_argument(
79
+ "-e",
80
+ "--conversion-error",
81
+ type=float,
82
+ metavar="ERROR",
83
+ default=None,
84
+ help="maxiumum approximation error measured in EM (default: 0.001)",
85
+ )
86
+ parser.add_argument(
87
+ "-m",
88
+ "--mixed",
89
+ default=False,
90
+ action="store_true",
91
+ help="whether to used mixed quadratic and cubic curves",
92
+ )
93
+ parser.add_argument(
94
+ "--keep-direction",
95
+ dest="reverse_direction",
96
+ action="store_false",
97
+ help="do not reverse the contour direction",
98
+ )
99
+
100
+ mode_parser = parser.add_mutually_exclusive_group()
101
+ mode_parser.add_argument(
102
+ "-i",
103
+ "--interpolatable",
104
+ action="store_true",
105
+ help="whether curve conversion should keep interpolation compatibility",
106
+ )
107
+ mode_parser.add_argument(
108
+ "-j",
109
+ "--jobs",
110
+ type=int,
111
+ nargs="?",
112
+ default=1,
113
+ const=_cpu_count(),
114
+ metavar="N",
115
+ help="Convert using N multiple processes (default: %(default)s)",
116
+ )
117
+
118
+ output_parser = parser.add_mutually_exclusive_group()
119
+ output_parser.add_argument(
120
+ "-o",
121
+ "--output-file",
122
+ default=None,
123
+ metavar="OUTPUT",
124
+ help=(
125
+ "output filename for the converted UFO. By default fonts are "
126
+ "modified in place. This only works with a single input."
127
+ ),
128
+ )
129
+ output_parser.add_argument(
130
+ "-d",
131
+ "--output-dir",
132
+ default=None,
133
+ metavar="DIRECTORY",
134
+ help="output directory where to save converted UFOs",
135
+ )
136
+
137
+ options = parser.parse_args(args)
138
+
139
+ if ufo_module is None:
140
+ parser.error("Either ufoLib2 or defcon are required to run this script.")
141
+
142
+ if not options.verbose:
143
+ level = "WARNING"
144
+ elif options.verbose == 1:
145
+ level = "INFO"
146
+ else:
147
+ level = "DEBUG"
148
+ logging.basicConfig(level=level)
149
+
150
+ if len(options.infiles) > 1 and options.output_file:
151
+ parser.error("-o/--output-file can't be used with multile inputs")
152
+
153
+ if options.output_dir:
154
+ output_dir = options.output_dir
155
+ if not os.path.exists(output_dir):
156
+ os.mkdir(output_dir)
157
+ elif not os.path.isdir(output_dir):
158
+ parser.error("'%s' is not a directory" % output_dir)
159
+ output_paths = [
160
+ os.path.join(output_dir, os.path.basename(p)) for p in options.infiles
161
+ ]
162
+ elif options.output_file:
163
+ output_paths = [options.output_file]
164
+ else:
165
+ # save in-place
166
+ output_paths = [None] * len(options.infiles)
167
+
168
+ kwargs = dict(
169
+ dump_stats=options.verbose > 0,
170
+ max_err_em=options.conversion_error,
171
+ reverse_direction=options.reverse_direction,
172
+ all_quadratic=False if options.mixed else True,
173
+ )
174
+
175
+ if options.interpolatable:
176
+ logger.info("Converting curves compatibly")
177
+ ufos = [open_ufo(infile) for infile in options.infiles]
178
+ if fonts_to_quadratic(ufos, **kwargs):
179
+ for ufo, output_path in zip(ufos, output_paths):
180
+ logger.info("Saving %s", output_path)
181
+ if output_path:
182
+ ufo.save(output_path)
183
+ else:
184
+ ufo.save()
185
+ else:
186
+ for input_path, output_path in zip(options.infiles, output_paths):
187
+ if output_path:
188
+ _copytree(input_path, output_path)
189
+ else:
190
+ jobs = min(len(options.infiles), options.jobs) if options.jobs > 1 else 1
191
+ if jobs > 1:
192
+ func = partial(_font_to_quadratic, **kwargs)
193
+ logger.info("Running %d parallel processes", jobs)
194
+ with closing(mp.Pool(jobs)) as pool:
195
+ pool.starmap(func, zip(options.infiles, output_paths))
196
+ else:
197
+ for input_path, output_path in zip(options.infiles, output_paths):
198
+ _font_to_quadratic(input_path, output_path, **kwargs)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/cu2qu.c ADDED
The diff for this file is too large to render. See raw diff
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/cu2qu.py ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: language_level=3
2
+ # distutils: define_macros=CYTHON_TRACE_NOGIL=1
3
+
4
+ # Copyright 2015 Google Inc. All Rights Reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ try:
19
+ import cython
20
+ except (AttributeError, ImportError):
21
+ # if cython not installed, use mock module with no-op decorators and types
22
+ from fontTools.misc import cython
23
+ COMPILED = cython.compiled
24
+
25
+ import math
26
+
27
+ from .errors import Error as Cu2QuError, ApproxNotFoundError
28
+
29
+
30
+ __all__ = ["curve_to_quadratic", "curves_to_quadratic"]
31
+
32
+ MAX_N = 100
33
+
34
+ NAN = float("NaN")
35
+
36
+
37
+ @cython.cfunc
38
+ @cython.inline
39
+ @cython.returns(cython.double)
40
+ @cython.locals(v1=cython.complex, v2=cython.complex, result=cython.double)
41
+ def dot(v1, v2):
42
+ """Return the dot product of two vectors.
43
+
44
+ Args:
45
+ v1 (complex): First vector.
46
+ v2 (complex): Second vector.
47
+
48
+ Returns:
49
+ double: Dot product.
50
+ """
51
+ result = (v1 * v2.conjugate()).real
52
+ # When vectors are perpendicular (i.e. dot product is 0), the above expression may
53
+ # yield slightly different results when running in pure Python vs C/Cython,
54
+ # both of which are correct within IEEE-754 floating-point precision.
55
+ # It's probably due to the different order of operations and roundings in each
56
+ # implementation. Because we are using the result in a denominator and catching
57
+ # ZeroDivisionError (see `calc_intersect`), it's best to normalize the result here.
58
+ if abs(result) < 1e-15:
59
+ result = 0.0
60
+ return result
61
+
62
+
63
+ @cython.cfunc
64
+ @cython.locals(z=cython.complex, den=cython.double)
65
+ @cython.locals(zr=cython.double, zi=cython.double)
66
+ def _complex_div_by_real(z, den):
67
+ """Divide complex by real using Python's method (two separate divisions).
68
+
69
+ This ensures bit-exact compatibility with Python's complex division,
70
+ avoiding C's multiply-by-reciprocal optimization that can cause 1 ULP differences
71
+ on some platforms/compilers (e.g. clang on macOS arm64).
72
+
73
+ https://github.com/fonttools/fonttools/issues/3928
74
+ """
75
+ zr = z.real
76
+ zi = z.imag
77
+ return complex(zr / den, zi / den)
78
+
79
+
80
+ @cython.cfunc
81
+ @cython.inline
82
+ @cython.locals(a=cython.complex, b=cython.complex, c=cython.complex, d=cython.complex)
83
+ @cython.locals(
84
+ _1=cython.complex, _2=cython.complex, _3=cython.complex, _4=cython.complex
85
+ )
86
+ def calc_cubic_points(a, b, c, d):
87
+ _1 = d
88
+ _2 = _complex_div_by_real(c, 3.0) + d
89
+ _3 = _complex_div_by_real(b + c, 3.0) + _2
90
+ _4 = a + d + c + b
91
+ return _1, _2, _3, _4
92
+
93
+
94
+ @cython.cfunc
95
+ @cython.inline
96
+ @cython.locals(
97
+ p0=cython.complex, p1=cython.complex, p2=cython.complex, p3=cython.complex
98
+ )
99
+ @cython.locals(a=cython.complex, b=cython.complex, c=cython.complex, d=cython.complex)
100
+ def calc_cubic_parameters(p0, p1, p2, p3):
101
+ c = (p1 - p0) * 3.0
102
+ b = (p2 - p1) * 3.0 - c
103
+ d = p0
104
+ a = p3 - d - c - b
105
+ return a, b, c, d
106
+
107
+
108
+ @cython.cfunc
109
+ @cython.inline
110
+ @cython.locals(
111
+ p0=cython.complex, p1=cython.complex, p2=cython.complex, p3=cython.complex
112
+ )
113
+ def split_cubic_into_n_iter(p0, p1, p2, p3, n):
114
+ """Split a cubic Bezier into n equal parts.
115
+
116
+ Splits the curve into `n` equal parts by curve time.
117
+ (t=0..1/n, t=1/n..2/n, ...)
118
+
119
+ Args:
120
+ p0 (complex): Start point of curve.
121
+ p1 (complex): First handle of curve.
122
+ p2 (complex): Second handle of curve.
123
+ p3 (complex): End point of curve.
124
+
125
+ Returns:
126
+ An iterator yielding the control points (four complex values) of the
127
+ subcurves.
128
+ """
129
+ # Hand-coded special-cases
130
+ if n == 2:
131
+ return iter(split_cubic_into_two(p0, p1, p2, p3))
132
+ if n == 3:
133
+ return iter(split_cubic_into_three(p0, p1, p2, p3))
134
+ if n == 4:
135
+ a, b = split_cubic_into_two(p0, p1, p2, p3)
136
+ return iter(
137
+ split_cubic_into_two(a[0], a[1], a[2], a[3])
138
+ + split_cubic_into_two(b[0], b[1], b[2], b[3])
139
+ )
140
+ if n == 6:
141
+ a, b = split_cubic_into_two(p0, p1, p2, p3)
142
+ return iter(
143
+ split_cubic_into_three(a[0], a[1], a[2], a[3])
144
+ + split_cubic_into_three(b[0], b[1], b[2], b[3])
145
+ )
146
+
147
+ return _split_cubic_into_n_gen(p0, p1, p2, p3, n)
148
+
149
+
150
+ @cython.locals(
151
+ p0=cython.complex,
152
+ p1=cython.complex,
153
+ p2=cython.complex,
154
+ p3=cython.complex,
155
+ n=cython.int,
156
+ )
157
+ @cython.locals(a=cython.complex, b=cython.complex, c=cython.complex, d=cython.complex)
158
+ @cython.locals(
159
+ dt=cython.double, delta_2=cython.double, delta_3=cython.double, i=cython.int
160
+ )
161
+ @cython.locals(
162
+ a1=cython.complex, b1=cython.complex, c1=cython.complex, d1=cython.complex
163
+ )
164
+ def _split_cubic_into_n_gen(p0, p1, p2, p3, n):
165
+ a, b, c, d = calc_cubic_parameters(p0, p1, p2, p3)
166
+ dt = 1 / n
167
+ delta_2 = dt * dt
168
+ delta_3 = dt * delta_2
169
+ for i in range(n):
170
+ t1 = i * dt
171
+ t1_2 = t1 * t1
172
+ # calc new a, b, c and d
173
+ a1 = a * delta_3
174
+ b1 = (3 * a * t1 + b) * delta_2
175
+ c1 = (2 * b * t1 + c + 3 * a * t1_2) * dt
176
+ d1 = a * t1 * t1_2 + b * t1_2 + c * t1 + d
177
+ yield calc_cubic_points(a1, b1, c1, d1)
178
+
179
+
180
+ @cython.cfunc
181
+ @cython.inline
182
+ @cython.locals(
183
+ p0=cython.complex, p1=cython.complex, p2=cython.complex, p3=cython.complex
184
+ )
185
+ @cython.locals(mid=cython.complex, deriv3=cython.complex)
186
+ def split_cubic_into_two(p0, p1, p2, p3):
187
+ """Split a cubic Bezier into two equal parts.
188
+
189
+ Splits the curve into two equal parts at t = 0.5
190
+
191
+ Args:
192
+ p0 (complex): Start point of curve.
193
+ p1 (complex): First handle of curve.
194
+ p2 (complex): Second handle of curve.
195
+ p3 (complex): End point of curve.
196
+
197
+ Returns:
198
+ tuple: Two cubic Beziers (each expressed as a tuple of four complex
199
+ values).
200
+ """
201
+ mid = (p0 + 3 * (p1 + p2) + p3) * 0.125
202
+ deriv3 = (p3 + p2 - p1 - p0) * 0.125
203
+ return (
204
+ (p0, (p0 + p1) * 0.5, mid - deriv3, mid),
205
+ (mid, mid + deriv3, (p2 + p3) * 0.5, p3),
206
+ )
207
+
208
+
209
+ @cython.cfunc
210
+ @cython.inline
211
+ @cython.locals(
212
+ p0=cython.complex,
213
+ p1=cython.complex,
214
+ p2=cython.complex,
215
+ p3=cython.complex,
216
+ )
217
+ @cython.locals(
218
+ mid1=cython.complex,
219
+ deriv1=cython.complex,
220
+ mid2=cython.complex,
221
+ deriv2=cython.complex,
222
+ )
223
+ def split_cubic_into_three(p0, p1, p2, p3):
224
+ """Split a cubic Bezier into three equal parts.
225
+
226
+ Splits the curve into three equal parts at t = 1/3 and t = 2/3
227
+
228
+ Args:
229
+ p0 (complex): Start point of curve.
230
+ p1 (complex): First handle of curve.
231
+ p2 (complex): Second handle of curve.
232
+ p3 (complex): End point of curve.
233
+
234
+ Returns:
235
+ tuple: Three cubic Beziers (each expressed as a tuple of four complex
236
+ values).
237
+ """
238
+ mid1 = (8 * p0 + 12 * p1 + 6 * p2 + p3) * (1 / 27)
239
+ deriv1 = (p3 + 3 * p2 - 4 * p0) * (1 / 27)
240
+ mid2 = (p0 + 6 * p1 + 12 * p2 + 8 * p3) * (1 / 27)
241
+ deriv2 = (4 * p3 - 3 * p1 - p0) * (1 / 27)
242
+ return (
243
+ (p0, (2 * p0 + p1) / 3.0, mid1 - deriv1, mid1),
244
+ (mid1, mid1 + deriv1, mid2 - deriv2, mid2),
245
+ (mid2, mid2 + deriv2, (p2 + 2 * p3) / 3.0, p3),
246
+ )
247
+
248
+
249
+ @cython.cfunc
250
+ @cython.inline
251
+ @cython.returns(cython.complex)
252
+ @cython.locals(
253
+ t=cython.double,
254
+ p0=cython.complex,
255
+ p1=cython.complex,
256
+ p2=cython.complex,
257
+ p3=cython.complex,
258
+ )
259
+ @cython.locals(_p1=cython.complex, _p2=cython.complex)
260
+ def cubic_approx_control(t, p0, p1, p2, p3):
261
+ """Approximate a cubic Bezier using a quadratic one.
262
+
263
+ Args:
264
+ t (double): Position of control point.
265
+ p0 (complex): Start point of curve.
266
+ p1 (complex): First handle of curve.
267
+ p2 (complex): Second handle of curve.
268
+ p3 (complex): End point of curve.
269
+
270
+ Returns:
271
+ complex: Location of candidate control point on quadratic curve.
272
+ """
273
+ _p1 = p0 + (p1 - p0) * 1.5
274
+ _p2 = p3 + (p2 - p3) * 1.5
275
+ return _p1 + (_p2 - _p1) * t
276
+
277
+
278
+ @cython.cfunc
279
+ @cython.inline
280
+ @cython.returns(cython.complex)
281
+ @cython.locals(a=cython.complex, b=cython.complex, c=cython.complex, d=cython.complex)
282
+ @cython.locals(ab=cython.complex, cd=cython.complex, p=cython.complex, h=cython.double)
283
+ def calc_intersect(a, b, c, d):
284
+ """Calculate the intersection of two lines.
285
+
286
+ Args:
287
+ a (complex): Start point of first line.
288
+ b (complex): End point of first line.
289
+ c (complex): Start point of second line.
290
+ d (complex): End point of second line.
291
+
292
+ Returns:
293
+ complex: Location of intersection if one present, ``complex(NaN,NaN)``
294
+ if no intersection was found.
295
+ """
296
+ ab = b - a
297
+ cd = d - c
298
+ p = ab * 1j
299
+ try:
300
+ h = dot(p, a - c) / dot(p, cd)
301
+ except ZeroDivisionError:
302
+ # if 3 or 4 points are equal, we do have an intersection despite the zero-div:
303
+ # return one of the off-curves so that the algorithm can attempt a one-curve
304
+ # solution if it's within tolerance:
305
+ # https://github.com/linebender/kurbo/pull/484
306
+ if b == c and (a == b or c == d):
307
+ return b
308
+ return complex(NAN, NAN)
309
+ return c + cd * h
310
+
311
+
312
+ @cython.cfunc
313
+ @cython.returns(cython.int)
314
+ @cython.locals(
315
+ tolerance=cython.double,
316
+ p0=cython.complex,
317
+ p1=cython.complex,
318
+ p2=cython.complex,
319
+ p3=cython.complex,
320
+ )
321
+ @cython.locals(mid=cython.complex, deriv3=cython.complex)
322
+ def cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance):
323
+ """Check if a cubic Bezier lies within a given distance of the origin.
324
+
325
+ "Origin" means *the* origin (0,0), not the start of the curve. Note that no
326
+ checks are made on the start and end positions of the curve; this function
327
+ only checks the inside of the curve.
328
+
329
+ Args:
330
+ p0 (complex): Start point of curve.
331
+ p1 (complex): First handle of curve.
332
+ p2 (complex): Second handle of curve.
333
+ p3 (complex): End point of curve.
334
+ tolerance (double): Distance from origin.
335
+
336
+ Returns:
337
+ bool: True if the cubic Bezier ``p`` entirely lies within a distance
338
+ ``tolerance`` of the origin, False otherwise.
339
+ """
340
+ # First check p2 then p1, as p2 has higher error early on.
341
+ if abs(p2) <= tolerance and abs(p1) <= tolerance:
342
+ return True
343
+
344
+ # Split.
345
+ mid = (p0 + 3 * (p1 + p2) + p3) * 0.125
346
+ if abs(mid) > tolerance:
347
+ return False
348
+ deriv3 = (p3 + p2 - p1 - p0) * 0.125
349
+ return cubic_farthest_fit_inside(
350
+ p0, (p0 + p1) * 0.5, mid - deriv3, mid, tolerance
351
+ ) and cubic_farthest_fit_inside(mid, mid + deriv3, (p2 + p3) * 0.5, p3, tolerance)
352
+
353
+
354
+ @cython.cfunc
355
+ @cython.inline
356
+ @cython.locals(tolerance=cython.double)
357
+ @cython.locals(
358
+ q1=cython.complex,
359
+ c0=cython.complex,
360
+ c1=cython.complex,
361
+ c2=cython.complex,
362
+ c3=cython.complex,
363
+ )
364
+ def cubic_approx_quadratic(cubic, tolerance):
365
+ """Approximate a cubic Bezier with a single quadratic within a given tolerance.
366
+
367
+ Args:
368
+ cubic (sequence): Four complex numbers representing control points of
369
+ the cubic Bezier curve.
370
+ tolerance (double): Permitted deviation from the original curve.
371
+
372
+ Returns:
373
+ Three complex numbers representing control points of the quadratic
374
+ curve if it fits within the given tolerance, or ``None`` if no suitable
375
+ curve could be calculated.
376
+ """
377
+
378
+ q1 = calc_intersect(cubic[0], cubic[1], cubic[2], cubic[3])
379
+ if math.isnan(q1.imag):
380
+ return None
381
+ c0 = cubic[0]
382
+ c3 = cubic[3]
383
+ c1 = c0 + (q1 - c0) * (2 / 3)
384
+ c2 = c3 + (q1 - c3) * (2 / 3)
385
+ if not cubic_farthest_fit_inside(0, c1 - cubic[1], c2 - cubic[2], 0, tolerance):
386
+ return None
387
+ return c0, q1, c3
388
+
389
+
390
+ @cython.cfunc
391
+ @cython.locals(n=cython.int, tolerance=cython.double)
392
+ @cython.locals(i=cython.int)
393
+ @cython.locals(all_quadratic=cython.int)
394
+ @cython.locals(
395
+ c0=cython.complex, c1=cython.complex, c2=cython.complex, c3=cython.complex
396
+ )
397
+ @cython.locals(
398
+ q0=cython.complex,
399
+ q1=cython.complex,
400
+ next_q1=cython.complex,
401
+ q2=cython.complex,
402
+ d1=cython.complex,
403
+ )
404
+ def cubic_approx_spline(cubic, n, tolerance, all_quadratic):
405
+ """Approximate a cubic Bezier curve with a spline of n quadratics.
406
+
407
+ Args:
408
+ cubic (sequence): Four complex numbers representing control points of
409
+ the cubic Bezier curve.
410
+ n (int): Number of quadratic Bezier curves in the spline.
411
+ tolerance (double): Permitted deviation from the original curve.
412
+
413
+ Returns:
414
+ A list of ``n+2`` complex numbers, representing control points of the
415
+ quadratic spline if it fits within the given tolerance, or ``None`` if
416
+ no suitable spline could be calculated.
417
+ """
418
+
419
+ if n == 1:
420
+ return cubic_approx_quadratic(cubic, tolerance)
421
+ if n == 2 and all_quadratic == False:
422
+ return cubic
423
+
424
+ cubics = split_cubic_into_n_iter(cubic[0], cubic[1], cubic[2], cubic[3], n)
425
+
426
+ # calculate the spline of quadratics and check errors at the same time.
427
+ next_cubic = next(cubics)
428
+ next_q1 = cubic_approx_control(
429
+ 0, next_cubic[0], next_cubic[1], next_cubic[2], next_cubic[3]
430
+ )
431
+ q2 = cubic[0]
432
+ d1 = 0j
433
+ spline = [cubic[0], next_q1]
434
+ for i in range(1, n + 1):
435
+ # Current cubic to convert
436
+ c0, c1, c2, c3 = next_cubic
437
+
438
+ # Current quadratic approximation of current cubic
439
+ q0 = q2
440
+ q1 = next_q1
441
+ if i < n:
442
+ next_cubic = next(cubics)
443
+ next_q1 = cubic_approx_control(
444
+ i / (n - 1), next_cubic[0], next_cubic[1], next_cubic[2], next_cubic[3]
445
+ )
446
+ spline.append(next_q1)
447
+ q2 = (q1 + next_q1) * 0.5
448
+ else:
449
+ q2 = c3
450
+
451
+ # End-point deltas
452
+ d0 = d1
453
+ d1 = q2 - c3
454
+
455
+ if abs(d1) > tolerance or not cubic_farthest_fit_inside(
456
+ d0,
457
+ q0 + (q1 - q0) * (2 / 3) - c1,
458
+ q2 + (q1 - q2) * (2 / 3) - c2,
459
+ d1,
460
+ tolerance,
461
+ ):
462
+ return None
463
+ spline.append(cubic[3])
464
+
465
+ return spline
466
+
467
+
468
+ @cython.locals(max_err=cython.double)
469
+ @cython.locals(n=cython.int)
470
+ @cython.locals(all_quadratic=cython.int)
471
+ def curve_to_quadratic(curve, max_err, all_quadratic=True):
472
+ """Approximate a cubic Bezier curve with a spline of n quadratics.
473
+
474
+ Args:
475
+ cubic (sequence): Four 2D tuples representing control points of
476
+ the cubic Bezier curve.
477
+ max_err (double): Permitted deviation from the original curve.
478
+ all_quadratic (bool): If True (default) returned value is a
479
+ quadratic spline. If False, it's either a single quadratic
480
+ curve or a single cubic curve.
481
+
482
+ Returns:
483
+ If all_quadratic is True: A list of 2D tuples, representing
484
+ control points of the quadratic spline if it fits within the
485
+ given tolerance, or ``None`` if no suitable spline could be
486
+ calculated.
487
+
488
+ If all_quadratic is False: Either a quadratic curve (if length
489
+ of output is 3), or a cubic curve (if length of output is 4).
490
+ """
491
+
492
+ curve = [complex(*p) for p in curve]
493
+
494
+ for n in range(1, MAX_N + 1):
495
+ spline = cubic_approx_spline(curve, n, max_err, all_quadratic)
496
+ if spline is not None:
497
+ # done. go home
498
+ return [(s.real, s.imag) for s in spline]
499
+
500
+ raise ApproxNotFoundError(curve)
501
+
502
+
503
+ @cython.locals(l=cython.int, last_i=cython.int, i=cython.int)
504
+ @cython.locals(all_quadratic=cython.int)
505
+ def curves_to_quadratic(curves, max_errors, all_quadratic=True):
506
+ """Return quadratic Bezier splines approximating the input cubic Beziers.
507
+
508
+ Args:
509
+ curves: A sequence of *n* curves, each curve being a sequence of four
510
+ 2D tuples.
511
+ max_errors: A sequence of *n* floats representing the maximum permissible
512
+ deviation from each of the cubic Bezier curves.
513
+ all_quadratic (bool): If True (default) returned values are a
514
+ quadratic spline. If False, they are either a single quadratic
515
+ curve or a single cubic curve.
516
+
517
+ Example::
518
+
519
+ >>> curves_to_quadratic( [
520
+ ... [ (50,50), (100,100), (150,100), (200,50) ],
521
+ ... [ (75,50), (120,100), (150,75), (200,60) ]
522
+ ... ], [1,1] )
523
+ [[(50.0, 50.0), (75.0, 75.0), (125.0, 91.66666666666666), (175.0, 75.0), (200.0, 50.0)], [(75.0, 50.0), (97.5, 75.0), (135.41666666666666, 82.08333333333333), (175.0, 67.5), (200.0, 60.0)]]
524
+
525
+ The returned splines have "implied oncurve points" suitable for use in
526
+ TrueType ``glif`` outlines - i.e. in the first spline returned above,
527
+ the first quadratic segment runs from (50,50) to
528
+ ( (75 + 125)/2 , (120 + 91.666..)/2 ) = (100, 83.333...).
529
+
530
+ Returns:
531
+ If all_quadratic is True, a list of splines, each spline being a list
532
+ of 2D tuples.
533
+
534
+ If all_quadratic is False, a list of curves, each curve being a quadratic
535
+ (length 3), or cubic (length 4).
536
+
537
+ Raises:
538
+ fontTools.cu2qu.Errors.ApproxNotFoundError: if no suitable approximation
539
+ can be found for all curves with the given parameters.
540
+ """
541
+
542
+ curves = [[complex(*p) for p in curve] for curve in curves]
543
+ assert len(max_errors) == len(curves)
544
+
545
+ l = len(curves)
546
+ splines = [None] * l
547
+ last_i = i = 0
548
+ n = 1
549
+ while True:
550
+ spline = cubic_approx_spline(curves[i], n, max_errors[i], all_quadratic)
551
+ if spline is None:
552
+ if n == MAX_N:
553
+ break
554
+ n += 1
555
+ last_i = i
556
+ continue
557
+ splines[i] = spline
558
+ i = (i + 1) % l
559
+ if i == last_i:
560
+ # done. go home
561
+ return [[(s.real, s.imag) for s in spline] for spline in splines]
562
+
563
+ raise ApproxNotFoundError(curves)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/errors.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Google Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ class Error(Exception):
17
+ """Base Cu2Qu exception class for all other errors."""
18
+
19
+
20
+ class ApproxNotFoundError(Error):
21
+ def __init__(self, curve):
22
+ message = "no approximation found: %s" % curve
23
+ super().__init__(message)
24
+ self.curve = curve
25
+
26
+
27
+ class UnequalZipLengthsError(Error):
28
+ pass
29
+
30
+
31
+ class IncompatibleGlyphsError(Error):
32
+ def __init__(self, glyphs):
33
+ assert len(glyphs) > 1
34
+ self.glyphs = glyphs
35
+ names = set(repr(g.name) for g in glyphs)
36
+ if len(names) > 1:
37
+ self.combined_name = "{%s}" % ", ".join(sorted(names))
38
+ else:
39
+ self.combined_name = names.pop()
40
+
41
+ def __repr__(self):
42
+ return "<%s %s>" % (type(self).__name__, self.combined_name)
43
+
44
+
45
+ class IncompatibleSegmentNumberError(IncompatibleGlyphsError):
46
+ def __str__(self):
47
+ return "Glyphs named %s have different number of segments" % (
48
+ self.combined_name
49
+ )
50
+
51
+
52
+ class IncompatibleSegmentTypesError(IncompatibleGlyphsError):
53
+ def __init__(self, glyphs, segments):
54
+ IncompatibleGlyphsError.__init__(self, glyphs)
55
+ self.segments = segments
56
+
57
+ def __str__(self):
58
+ lines = []
59
+ ndigits = len(str(max(self.segments)))
60
+ for i, tags in sorted(self.segments.items()):
61
+ lines.append(
62
+ "%s: (%s)" % (str(i).rjust(ndigits), ", ".join(repr(t) for t in tags))
63
+ )
64
+ return "Glyphs named %s have incompatible segment types:\n %s" % (
65
+ self.combined_name,
66
+ "\n ".join(lines),
67
+ )
68
+
69
+
70
+ class IncompatibleFontsError(Error):
71
+ def __init__(self, glyph_errors):
72
+ self.glyph_errors = glyph_errors
73
+
74
+ def __str__(self):
75
+ return "fonts contains incompatible glyphs: %s" % (
76
+ ", ".join(repr(g) for g in sorted(self.glyph_errors.keys()))
77
+ )
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/cu2qu/ufo.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2015 Google Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ """Converts cubic bezier curves to quadratic splines.
17
+
18
+ Conversion is performed such that the quadratic splines keep the same end-curve
19
+ tangents as the original cubics. The approach is iterative, increasing the
20
+ number of segments for a spline until the error gets below a bound.
21
+
22
+ Respective curves from multiple fonts will be converted at once to ensure that
23
+ the resulting splines are interpolation-compatible.
24
+ """
25
+
26
+ import logging
27
+ from fontTools.pens.basePen import AbstractPen
28
+ from fontTools.pens.pointPen import PointToSegmentPen
29
+ from fontTools.pens.reverseContourPen import ReverseContourPen
30
+
31
+ from . import curves_to_quadratic
32
+ from .errors import (
33
+ UnequalZipLengthsError,
34
+ IncompatibleSegmentNumberError,
35
+ IncompatibleSegmentTypesError,
36
+ IncompatibleGlyphsError,
37
+ IncompatibleFontsError,
38
+ )
39
+
40
+
41
+ __all__ = ["fonts_to_quadratic", "font_to_quadratic"]
42
+
43
+ # The default approximation error below is a relative value (1/1000 of the EM square).
44
+ # Later on, we convert it to absolute font units by multiplying it by a font's UPEM
45
+ # (see fonts_to_quadratic).
46
+ DEFAULT_MAX_ERR = 0.001
47
+ CURVE_TYPE_LIB_KEY = "com.github.googlei18n.cu2qu.curve_type"
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+
52
+ _zip = zip
53
+
54
+
55
+ def zip(*args):
56
+ """Ensure each argument to zip has the same length. Also make sure a list is
57
+ returned for python 2/3 compatibility.
58
+ """
59
+
60
+ if len(set(len(a) for a in args)) != 1:
61
+ raise UnequalZipLengthsError(*args)
62
+ return list(_zip(*args))
63
+
64
+
65
+ class GetSegmentsPen(AbstractPen):
66
+ """Pen to collect segments into lists of points for conversion.
67
+
68
+ Curves always include their initial on-curve point, so some points are
69
+ duplicated between segments.
70
+ """
71
+
72
+ def __init__(self):
73
+ self._last_pt = None
74
+ self.segments = []
75
+
76
+ def _add_segment(self, tag, *args):
77
+ if tag in ["move", "line", "qcurve", "curve"]:
78
+ self._last_pt = args[-1]
79
+ self.segments.append((tag, args))
80
+
81
+ def moveTo(self, pt):
82
+ self._add_segment("move", pt)
83
+
84
+ def lineTo(self, pt):
85
+ self._add_segment("line", pt)
86
+
87
+ def qCurveTo(self, *points):
88
+ self._add_segment("qcurve", self._last_pt, *points)
89
+
90
+ def curveTo(self, *points):
91
+ self._add_segment("curve", self._last_pt, *points)
92
+
93
+ def closePath(self):
94
+ self._add_segment("close")
95
+
96
+ def endPath(self):
97
+ self._add_segment("end")
98
+
99
+ def addComponent(self, glyphName, transformation):
100
+ pass
101
+
102
+
103
+ def _get_segments(glyph):
104
+ """Get a glyph's segments as extracted by GetSegmentsPen."""
105
+
106
+ pen = GetSegmentsPen()
107
+ # glyph.draw(pen)
108
+ # We can't simply draw the glyph with the pen, but we must initialize the
109
+ # PointToSegmentPen explicitly with outputImpliedClosingLine=True.
110
+ # By default PointToSegmentPen does not outputImpliedClosingLine -- unless
111
+ # last and first point on closed contour are duplicated. Because we are
112
+ # converting multiple glyphs at the same time, we want to make sure
113
+ # this function returns the same number of segments, whether or not
114
+ # the last and first point overlap.
115
+ # https://github.com/googlefonts/fontmake/issues/572
116
+ # https://github.com/fonttools/fonttools/pull/1720
117
+ pointPen = PointToSegmentPen(pen, outputImpliedClosingLine=True)
118
+ glyph.drawPoints(pointPen)
119
+ return pen.segments
120
+
121
+
122
+ def _set_segments(glyph, segments, reverse_direction):
123
+ """Draw segments as extracted by GetSegmentsPen back to a glyph."""
124
+
125
+ glyph.clearContours()
126
+ pen = glyph.getPen()
127
+ if reverse_direction:
128
+ pen = ReverseContourPen(pen)
129
+ for tag, args in segments:
130
+ if tag == "move":
131
+ pen.moveTo(*args)
132
+ elif tag == "line":
133
+ pen.lineTo(*args)
134
+ elif tag == "curve":
135
+ pen.curveTo(*args[1:])
136
+ elif tag == "qcurve":
137
+ pen.qCurveTo(*args[1:])
138
+ elif tag == "close":
139
+ pen.closePath()
140
+ elif tag == "end":
141
+ pen.endPath()
142
+ else:
143
+ raise AssertionError('Unhandled segment type "%s"' % tag)
144
+
145
+
146
+ def _segments_to_quadratic(segments, max_err, stats, all_quadratic=True):
147
+ """Return quadratic approximations of cubic segments."""
148
+
149
+ assert all(s[0] == "curve" for s in segments), "Non-cubic given to convert"
150
+
151
+ new_points = curves_to_quadratic([s[1] for s in segments], max_err, all_quadratic)
152
+ n = len(new_points[0])
153
+ assert all(len(s) == n for s in new_points[1:]), "Converted incompatibly"
154
+
155
+ spline_length = str(n - 2)
156
+ stats[spline_length] = stats.get(spline_length, 0) + 1
157
+
158
+ if all_quadratic or n == 3:
159
+ return [("qcurve", p) for p in new_points]
160
+ else:
161
+ return [("curve", p) for p in new_points]
162
+
163
+
164
+ def _glyphs_to_quadratic(glyphs, max_err, reverse_direction, stats, all_quadratic=True):
165
+ """Do the actual conversion of a set of compatible glyphs, after arguments
166
+ have been set up.
167
+
168
+ Return True if the glyphs were modified, else return False.
169
+ """
170
+
171
+ try:
172
+ segments_by_location = zip(*[_get_segments(g) for g in glyphs])
173
+ except UnequalZipLengthsError:
174
+ raise IncompatibleSegmentNumberError(glyphs)
175
+ if not any(segments_by_location):
176
+ return False
177
+
178
+ # always modify input glyphs if reverse_direction is True
179
+ glyphs_modified = reverse_direction
180
+
181
+ new_segments_by_location = []
182
+ incompatible = {}
183
+ for i, segments in enumerate(segments_by_location):
184
+ tag = segments[0][0]
185
+ if not all(s[0] == tag for s in segments[1:]):
186
+ incompatible[i] = [s[0] for s in segments]
187
+ elif tag == "curve":
188
+ new_segments = _segments_to_quadratic(
189
+ segments, max_err, stats, all_quadratic
190
+ )
191
+ if all_quadratic or new_segments != segments:
192
+ glyphs_modified = True
193
+ segments = new_segments
194
+ new_segments_by_location.append(segments)
195
+
196
+ if glyphs_modified:
197
+ new_segments_by_glyph = zip(*new_segments_by_location)
198
+ for glyph, new_segments in zip(glyphs, new_segments_by_glyph):
199
+ _set_segments(glyph, new_segments, reverse_direction)
200
+
201
+ if incompatible:
202
+ raise IncompatibleSegmentTypesError(glyphs, segments=incompatible)
203
+ return glyphs_modified
204
+
205
+
206
+ def glyphs_to_quadratic(
207
+ glyphs, max_err=None, reverse_direction=False, stats=None, all_quadratic=True
208
+ ):
209
+ """Convert the curves of a set of compatible of glyphs to quadratic.
210
+
211
+ All curves will be converted to quadratic at once, ensuring interpolation
212
+ compatibility. If this is not required, calling glyphs_to_quadratic with one
213
+ glyph at a time may yield slightly more optimized results.
214
+
215
+ Return True if glyphs were modified, else return False.
216
+
217
+ Raises IncompatibleGlyphsError if glyphs have non-interpolatable outlines.
218
+ """
219
+ if stats is None:
220
+ stats = {}
221
+
222
+ if not max_err:
223
+ # assume 1000 is the default UPEM
224
+ max_err = DEFAULT_MAX_ERR * 1000
225
+
226
+ if isinstance(max_err, (list, tuple)):
227
+ max_errors = max_err
228
+ else:
229
+ max_errors = [max_err] * len(glyphs)
230
+ assert len(max_errors) == len(glyphs)
231
+
232
+ return _glyphs_to_quadratic(
233
+ glyphs, max_errors, reverse_direction, stats, all_quadratic
234
+ )
235
+
236
+
237
+ def fonts_to_quadratic(
238
+ fonts,
239
+ max_err_em=None,
240
+ max_err=None,
241
+ reverse_direction=False,
242
+ stats=None,
243
+ dump_stats=False,
244
+ remember_curve_type=True,
245
+ all_quadratic=True,
246
+ ):
247
+ """Convert the curves of a collection of fonts to quadratic.
248
+
249
+ All curves will be converted to quadratic at once, ensuring interpolation
250
+ compatibility. If this is not required, calling fonts_to_quadratic with one
251
+ font at a time may yield slightly more optimized results.
252
+
253
+ Return the set of modified glyph names if any, else return an empty set.
254
+
255
+ By default, cu2qu stores the curve type in the fonts' lib, under a private
256
+ key "com.github.googlei18n.cu2qu.curve_type", and will not try to convert
257
+ them again if the curve type is already set to "quadratic".
258
+ Setting 'remember_curve_type' to False disables this optimization.
259
+
260
+ Raises IncompatibleFontsError if same-named glyphs from different fonts
261
+ have non-interpolatable outlines.
262
+ """
263
+
264
+ if remember_curve_type:
265
+ curve_types = {f.lib.get(CURVE_TYPE_LIB_KEY, "cubic") for f in fonts}
266
+ if len(curve_types) == 1:
267
+ curve_type = next(iter(curve_types))
268
+ if curve_type in ("quadratic", "mixed"):
269
+ logger.info("Curves already converted to quadratic")
270
+ return False
271
+ elif curve_type == "cubic":
272
+ pass # keep converting
273
+ else:
274
+ raise NotImplementedError(curve_type)
275
+ elif len(curve_types) > 1:
276
+ # going to crash later if they do differ
277
+ logger.warning("fonts may contain different curve types")
278
+
279
+ if stats is None:
280
+ stats = {}
281
+
282
+ if max_err_em and max_err:
283
+ raise TypeError("Only one of max_err and max_err_em can be specified.")
284
+ if not (max_err_em or max_err):
285
+ max_err_em = DEFAULT_MAX_ERR
286
+
287
+ if isinstance(max_err, (list, tuple)):
288
+ assert len(max_err) == len(fonts)
289
+ max_errors = max_err
290
+ elif max_err:
291
+ max_errors = [max_err] * len(fonts)
292
+
293
+ if isinstance(max_err_em, (list, tuple)):
294
+ assert len(fonts) == len(max_err_em)
295
+ max_errors = [f.info.unitsPerEm * e for f, e in zip(fonts, max_err_em)]
296
+ elif max_err_em:
297
+ max_errors = [f.info.unitsPerEm * max_err_em for f in fonts]
298
+
299
+ modified = set()
300
+ glyph_errors = {}
301
+ for name in set().union(*(f.keys() for f in fonts)):
302
+ glyphs = []
303
+ cur_max_errors = []
304
+ for font, error in zip(fonts, max_errors):
305
+ if name in font:
306
+ glyphs.append(font[name])
307
+ cur_max_errors.append(error)
308
+ try:
309
+ if _glyphs_to_quadratic(
310
+ glyphs, cur_max_errors, reverse_direction, stats, all_quadratic
311
+ ):
312
+ modified.add(name)
313
+ except IncompatibleGlyphsError as exc:
314
+ logger.error(exc)
315
+ glyph_errors[name] = exc
316
+
317
+ if glyph_errors:
318
+ raise IncompatibleFontsError(glyph_errors)
319
+
320
+ if modified and dump_stats:
321
+ spline_lengths = sorted(stats.keys())
322
+ logger.info(
323
+ "New spline lengths: %s"
324
+ % (", ".join("%s: %d" % (l, stats[l]) for l in spline_lengths))
325
+ )
326
+
327
+ if remember_curve_type:
328
+ for font in fonts:
329
+ curve_type = font.lib.get(CURVE_TYPE_LIB_KEY, "cubic")
330
+ new_curve_type = "quadratic" if all_quadratic else "mixed"
331
+ if curve_type != new_curve_type:
332
+ font.lib[CURVE_TYPE_LIB_KEY] = new_curve_type
333
+ return modified
334
+
335
+
336
+ def glyph_to_quadratic(glyph, **kwargs):
337
+ """Convenience wrapper around glyphs_to_quadratic, for just one glyph.
338
+ Return True if the glyph was modified, else return False.
339
+ """
340
+
341
+ return glyphs_to_quadratic([glyph], **kwargs)
342
+
343
+
344
+ def font_to_quadratic(font, **kwargs):
345
+ """Convenience wrapper around fonts_to_quadratic, for just one font.
346
+ Return the set of modified glyph names if any, else return empty set.
347
+ """
348
+
349
+ return fonts_to_quadratic([font], **kwargs)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/__init__.py ADDED
The diff for this file is too large to render. See raw diff
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/__main__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import sys
2
+ from fontTools.designspaceLib import main
3
+
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/split.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Allows building all the variable fonts of a DesignSpace version 5 by
2
+ splitting the document into interpolable sub-space, then into each VF.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import itertools
8
+ import logging
9
+ import math
10
+ from typing import Any, Callable, Dict, Iterator, List, Tuple, cast
11
+
12
+ from fontTools.designspaceLib import (
13
+ AxisDescriptor,
14
+ AxisMappingDescriptor,
15
+ DesignSpaceDocument,
16
+ DiscreteAxisDescriptor,
17
+ InstanceDescriptor,
18
+ RuleDescriptor,
19
+ SimpleLocationDict,
20
+ SourceDescriptor,
21
+ VariableFontDescriptor,
22
+ )
23
+ from fontTools.designspaceLib.statNames import StatNames, getStatNames
24
+ from fontTools.designspaceLib.types import (
25
+ ConditionSet,
26
+ Range,
27
+ Region,
28
+ getVFUserRegion,
29
+ locationInRegion,
30
+ regionInRegion,
31
+ userRegionToDesignRegion,
32
+ )
33
+
34
+ LOGGER = logging.getLogger(__name__)
35
+
36
+ MakeInstanceFilenameCallable = Callable[
37
+ [DesignSpaceDocument, InstanceDescriptor, StatNames], str
38
+ ]
39
+
40
+
41
+ def defaultMakeInstanceFilename(
42
+ doc: DesignSpaceDocument, instance: InstanceDescriptor, statNames: StatNames
43
+ ) -> str:
44
+ """Default callable to synthesize an instance filename
45
+ when makeNames=True, for instances that don't specify an instance name
46
+ in the designspace. This part of the name generation can be overriden
47
+ because it's not specified by the STAT table.
48
+ """
49
+ familyName = instance.familyName or statNames.familyNames.get("en")
50
+ styleName = instance.styleName or statNames.styleNames.get("en")
51
+ return f"{familyName}-{styleName}.ttf"
52
+
53
+
54
+ def splitInterpolable(
55
+ doc: DesignSpaceDocument,
56
+ makeNames: bool = True,
57
+ expandLocations: bool = True,
58
+ makeInstanceFilename: MakeInstanceFilenameCallable = defaultMakeInstanceFilename,
59
+ ) -> Iterator[Tuple[SimpleLocationDict, DesignSpaceDocument]]:
60
+ """Split the given DS5 into several interpolable sub-designspaces.
61
+ There are as many interpolable sub-spaces as there are combinations of
62
+ discrete axis values.
63
+
64
+ E.g. with axes:
65
+ - italic (discrete) Upright or Italic
66
+ - style (discrete) Sans or Serif
67
+ - weight (continuous) 100 to 900
68
+
69
+ There are 4 sub-spaces in which the Weight axis should interpolate:
70
+ (Upright, Sans), (Upright, Serif), (Italic, Sans) and (Italic, Serif).
71
+
72
+ The sub-designspaces still include the full axis definitions and STAT data,
73
+ but the rules, sources, variable fonts, instances are trimmed down to only
74
+ keep what falls within the interpolable sub-space.
75
+
76
+ Args:
77
+ - ``makeNames``: Whether to compute the instance family and style
78
+ names using the STAT data.
79
+ - ``expandLocations``: Whether to turn all locations into "full"
80
+ locations, including implicit default axis values where missing.
81
+ - ``makeInstanceFilename``: Callable to synthesize an instance filename
82
+ when makeNames=True, for instances that don't specify an instance name
83
+ in the designspace. This part of the name generation can be overridden
84
+ because it's not specified by the STAT table.
85
+
86
+ .. versionadded:: 5.0
87
+ """
88
+ discreteAxes = []
89
+ interpolableUserRegion: Region = {}
90
+ for axis in doc.axes:
91
+ if hasattr(axis, "values"):
92
+ # Mypy doesn't support narrowing union types via hasattr()
93
+ # TODO(Python 3.10): use TypeGuard
94
+ # https://mypy.readthedocs.io/en/stable/type_narrowing.html
95
+ axis = cast(DiscreteAxisDescriptor, axis)
96
+ discreteAxes.append(axis)
97
+ else:
98
+ axis = cast(AxisDescriptor, axis)
99
+ interpolableUserRegion[axis.name] = Range(
100
+ axis.minimum,
101
+ axis.maximum,
102
+ axis.default,
103
+ )
104
+ valueCombinations = itertools.product(*[axis.values for axis in discreteAxes])
105
+ for values in valueCombinations:
106
+ discreteUserLocation = {
107
+ discreteAxis.name: value
108
+ for discreteAxis, value in zip(discreteAxes, values)
109
+ }
110
+ subDoc = _extractSubSpace(
111
+ doc,
112
+ {**interpolableUserRegion, **discreteUserLocation},
113
+ keepVFs=True,
114
+ makeNames=makeNames,
115
+ expandLocations=expandLocations,
116
+ makeInstanceFilename=makeInstanceFilename,
117
+ )
118
+ yield discreteUserLocation, subDoc
119
+
120
+
121
+ def splitVariableFonts(
122
+ doc: DesignSpaceDocument,
123
+ makeNames: bool = False,
124
+ expandLocations: bool = False,
125
+ makeInstanceFilename: MakeInstanceFilenameCallable = defaultMakeInstanceFilename,
126
+ ) -> Iterator[Tuple[str, DesignSpaceDocument]]:
127
+ """Convert each variable font listed in this document into a standalone
128
+ designspace. This can be used to compile all the variable fonts from a
129
+ format 5 designspace using tools that can only deal with 1 VF at a time.
130
+
131
+ Args:
132
+ - ``makeNames``: Whether to compute the instance family and style
133
+ names using the STAT data.
134
+ - ``expandLocations``: Whether to turn all locations into "full"
135
+ locations, including implicit default axis values where missing.
136
+ - ``makeInstanceFilename``: Callable to synthesize an instance filename
137
+ when makeNames=True, for instances that don't specify an instance name
138
+ in the designspace. This part of the name generation can be overridden
139
+ because it's not specified by the STAT table.
140
+
141
+ .. versionadded:: 5.0
142
+ """
143
+ # Make one DesignspaceDoc v5 for each variable font
144
+ for vf in doc.getVariableFonts():
145
+ vfUserRegion = getVFUserRegion(doc, vf)
146
+ vfDoc = _extractSubSpace(
147
+ doc,
148
+ vfUserRegion,
149
+ keepVFs=False,
150
+ makeNames=makeNames,
151
+ expandLocations=expandLocations,
152
+ makeInstanceFilename=makeInstanceFilename,
153
+ )
154
+ vfDoc.lib = {**vfDoc.lib, **vf.lib}
155
+ yield vf.name, vfDoc
156
+
157
+
158
+ def convert5to4(
159
+ doc: DesignSpaceDocument,
160
+ ) -> Dict[str, DesignSpaceDocument]:
161
+ """Convert each variable font listed in this document into a standalone
162
+ format 4 designspace. This can be used to compile all the variable fonts
163
+ from a format 5 designspace using tools that only know about format 4.
164
+
165
+ .. versionadded:: 5.0
166
+ """
167
+ vfs = {}
168
+ for _location, subDoc in splitInterpolable(doc):
169
+ for vfName, vfDoc in splitVariableFonts(subDoc):
170
+ vfDoc.formatVersion = "4.1"
171
+ vfs[vfName] = vfDoc
172
+ return vfs
173
+
174
+
175
+ def _extractSubSpace(
176
+ doc: DesignSpaceDocument,
177
+ userRegion: Region,
178
+ *,
179
+ keepVFs: bool,
180
+ makeNames: bool,
181
+ expandLocations: bool,
182
+ makeInstanceFilename: MakeInstanceFilenameCallable,
183
+ ) -> DesignSpaceDocument:
184
+ subDoc = DesignSpaceDocument()
185
+ # Don't include STAT info
186
+ # FIXME: (Jany) let's think about it. Not include = OK because the point of
187
+ # the splitting is to build VFs and we'll use the STAT data of the full
188
+ # document to generate the STAT of the VFs, so "no need" to have STAT data
189
+ # in sub-docs. Counterpoint: what if someone wants to split this DS for
190
+ # other purposes? Maybe for that it would be useful to also subset the STAT
191
+ # data?
192
+ # subDoc.elidedFallbackName = doc.elidedFallbackName
193
+
194
+ def maybeExpandDesignLocation(object):
195
+ if expandLocations:
196
+ return object.getFullDesignLocation(doc)
197
+ else:
198
+ return object.designLocation
199
+
200
+ for axis in doc.axes:
201
+ range = userRegion[axis.name]
202
+ if isinstance(range, Range) and hasattr(axis, "minimum"):
203
+ # Mypy doesn't support narrowing union types via hasattr()
204
+ # TODO(Python 3.10): use TypeGuard
205
+ # https://mypy.readthedocs.io/en/stable/type_narrowing.html
206
+ axis = cast(AxisDescriptor, axis)
207
+ subDoc.addAxis(
208
+ AxisDescriptor(
209
+ # Same info
210
+ tag=axis.tag,
211
+ name=axis.name,
212
+ labelNames=axis.labelNames,
213
+ hidden=axis.hidden,
214
+ # Subset range
215
+ minimum=max(range.minimum, axis.minimum),
216
+ default=range.default or axis.default,
217
+ maximum=min(range.maximum, axis.maximum),
218
+ map=[
219
+ (user, design)
220
+ for user, design in axis.map
221
+ if range.minimum <= user <= range.maximum
222
+ ],
223
+ # Don't include STAT info
224
+ axisOrdering=None,
225
+ axisLabels=None,
226
+ )
227
+ )
228
+
229
+ subDoc.axisMappings = mappings = []
230
+ subDocAxes = {axis.name for axis in subDoc.axes}
231
+ for mapping in doc.axisMappings:
232
+ if not all(axis in subDocAxes for axis in mapping.inputLocation.keys()):
233
+ continue
234
+ if not all(axis in subDocAxes for axis in mapping.outputLocation.keys()):
235
+ LOGGER.error(
236
+ "In axis mapping from input %s, some output axes are not in the variable-font: %s",
237
+ mapping.inputLocation,
238
+ mapping.outputLocation,
239
+ )
240
+ continue
241
+
242
+ mappingAxes = set()
243
+ mappingAxes.update(mapping.inputLocation.keys())
244
+ mappingAxes.update(mapping.outputLocation.keys())
245
+ for axis in doc.axes:
246
+ if axis.name not in mappingAxes:
247
+ continue
248
+ range = userRegion[axis.name]
249
+ if (
250
+ range.minimum != axis.minimum
251
+ or (range.default is not None and range.default != axis.default)
252
+ or range.maximum != axis.maximum
253
+ ):
254
+ LOGGER.error(
255
+ "Limiting axis ranges used in <mapping> elements not supported: %s",
256
+ axis.name,
257
+ )
258
+ continue
259
+
260
+ mappings.append(
261
+ AxisMappingDescriptor(
262
+ inputLocation=mapping.inputLocation,
263
+ outputLocation=mapping.outputLocation,
264
+ )
265
+ )
266
+
267
+ # Don't include STAT info
268
+ # subDoc.locationLabels = doc.locationLabels
269
+
270
+ # Rules: subset them based on conditions
271
+ designRegion = userRegionToDesignRegion(doc, userRegion)
272
+ subDoc.rules = _subsetRulesBasedOnConditions(doc.rules, designRegion)
273
+ subDoc.rulesProcessingLast = doc.rulesProcessingLast
274
+
275
+ # Sources: keep only the ones that fall within the kept axis ranges
276
+ for source in doc.sources:
277
+ if not locationInRegion(doc.map_backward(source.designLocation), userRegion):
278
+ continue
279
+
280
+ subDoc.addSource(
281
+ SourceDescriptor(
282
+ filename=source.filename,
283
+ path=source.path,
284
+ font=source.font,
285
+ name=source.name,
286
+ designLocation=_filterLocation(
287
+ userRegion, maybeExpandDesignLocation(source)
288
+ ),
289
+ layerName=source.layerName,
290
+ familyName=source.familyName,
291
+ styleName=source.styleName,
292
+ muteKerning=source.muteKerning,
293
+ muteInfo=source.muteInfo,
294
+ mutedGlyphNames=source.mutedGlyphNames,
295
+ )
296
+ )
297
+
298
+ # Copy family name translations from the old default source to the new default
299
+ vfDefault = subDoc.findDefault()
300
+ oldDefault = doc.findDefault()
301
+ if vfDefault is not None and oldDefault is not None:
302
+ vfDefault.localisedFamilyName = oldDefault.localisedFamilyName
303
+
304
+ # Variable fonts: keep only the ones that fall within the kept axis ranges
305
+ if keepVFs:
306
+ # Note: call getVariableFont() to make the implicit VFs explicit
307
+ for vf in doc.getVariableFonts():
308
+ vfUserRegion = getVFUserRegion(doc, vf)
309
+ if regionInRegion(vfUserRegion, userRegion):
310
+ subDoc.addVariableFont(
311
+ VariableFontDescriptor(
312
+ name=vf.name,
313
+ filename=vf.filename,
314
+ axisSubsets=[
315
+ axisSubset
316
+ for axisSubset in vf.axisSubsets
317
+ if isinstance(userRegion[axisSubset.name], Range)
318
+ ],
319
+ lib=vf.lib,
320
+ )
321
+ )
322
+
323
+ # Instances: same as Sources + compute missing names
324
+ for instance in doc.instances:
325
+ if not locationInRegion(instance.getFullUserLocation(doc), userRegion):
326
+ continue
327
+
328
+ if makeNames:
329
+ statNames = getStatNames(doc, instance.getFullUserLocation(doc))
330
+ familyName = instance.familyName or statNames.familyNames.get("en")
331
+ styleName = instance.styleName or statNames.styleNames.get("en")
332
+ subDoc.addInstance(
333
+ InstanceDescriptor(
334
+ filename=instance.filename
335
+ or makeInstanceFilename(doc, instance, statNames),
336
+ path=instance.path,
337
+ font=instance.font,
338
+ name=instance.name or f"{familyName} {styleName}",
339
+ userLocation={} if expandLocations else instance.userLocation,
340
+ designLocation=_filterLocation(
341
+ userRegion, maybeExpandDesignLocation(instance)
342
+ ),
343
+ familyName=familyName,
344
+ styleName=styleName,
345
+ postScriptFontName=instance.postScriptFontName
346
+ or statNames.postScriptFontName,
347
+ styleMapFamilyName=instance.styleMapFamilyName
348
+ or statNames.styleMapFamilyNames.get("en"),
349
+ styleMapStyleName=instance.styleMapStyleName
350
+ or statNames.styleMapStyleName,
351
+ localisedFamilyName=instance.localisedFamilyName
352
+ or statNames.familyNames,
353
+ localisedStyleName=instance.localisedStyleName
354
+ or statNames.styleNames,
355
+ localisedStyleMapFamilyName=instance.localisedStyleMapFamilyName
356
+ or statNames.styleMapFamilyNames,
357
+ localisedStyleMapStyleName=instance.localisedStyleMapStyleName
358
+ or {},
359
+ lib=instance.lib,
360
+ )
361
+ )
362
+ else:
363
+ subDoc.addInstance(
364
+ InstanceDescriptor(
365
+ filename=instance.filename,
366
+ path=instance.path,
367
+ font=instance.font,
368
+ name=instance.name,
369
+ userLocation={} if expandLocations else instance.userLocation,
370
+ designLocation=_filterLocation(
371
+ userRegion, maybeExpandDesignLocation(instance)
372
+ ),
373
+ familyName=instance.familyName,
374
+ styleName=instance.styleName,
375
+ postScriptFontName=instance.postScriptFontName,
376
+ styleMapFamilyName=instance.styleMapFamilyName,
377
+ styleMapStyleName=instance.styleMapStyleName,
378
+ localisedFamilyName=instance.localisedFamilyName,
379
+ localisedStyleName=instance.localisedStyleName,
380
+ localisedStyleMapFamilyName=instance.localisedStyleMapFamilyName,
381
+ localisedStyleMapStyleName=instance.localisedStyleMapStyleName,
382
+ lib=instance.lib,
383
+ )
384
+ )
385
+
386
+ subDoc.lib = doc.lib
387
+
388
+ return subDoc
389
+
390
+
391
+ def _conditionSetFrom(conditionSet: List[Dict[str, Any]]) -> ConditionSet:
392
+ c: Dict[str, Range] = {}
393
+ for condition in conditionSet:
394
+ minimum, maximum = condition.get("minimum"), condition.get("maximum")
395
+ c[condition["name"]] = Range(
396
+ minimum if minimum is not None else -math.inf,
397
+ maximum if maximum is not None else math.inf,
398
+ )
399
+ return c
400
+
401
+
402
+ def _subsetRulesBasedOnConditions(
403
+ rules: List[RuleDescriptor], designRegion: Region
404
+ ) -> List[RuleDescriptor]:
405
+ # What rules to keep:
406
+ # - Keep the rule if any conditionset is relevant.
407
+ # - A conditionset is relevant if all conditions are relevant or it is empty.
408
+ # - A condition is relevant if
409
+ # - axis is point (C-AP),
410
+ # - and point in condition's range (C-AP-in)
411
+ # (in this case remove the condition because it's always true)
412
+ # - else (C-AP-out) whole conditionset can be discarded (condition false
413
+ # => conditionset false)
414
+ # - axis is range (C-AR),
415
+ # - (C-AR-all) and axis range fully contained in condition range: we can
416
+ # scrap the condition because it's always true
417
+ # - (C-AR-inter) and intersection(axis range, condition range) not empty:
418
+ # keep the condition with the smaller range (= intersection)
419
+ # - (C-AR-none) else, whole conditionset can be discarded
420
+ newRules: List[RuleDescriptor] = []
421
+ for rule in rules:
422
+ newRule: RuleDescriptor = RuleDescriptor(
423
+ name=rule.name, conditionSets=[], subs=rule.subs
424
+ )
425
+ for conditionset in rule.conditionSets:
426
+ cs = _conditionSetFrom(conditionset)
427
+ newConditionset: List[Dict[str, Any]] = []
428
+ discardConditionset = False
429
+ for selectionName, selectionValue in designRegion.items():
430
+ # TODO: Ensure that all(key in conditionset for key in region.keys())?
431
+ if selectionName not in cs:
432
+ # raise Exception("Selection has different axes than the rules")
433
+ continue
434
+ if isinstance(selectionValue, (float, int)): # is point
435
+ # Case C-AP-in
436
+ if selectionValue in cs[selectionName]:
437
+ pass # always matches, conditionset can stay empty for this one.
438
+ # Case C-AP-out
439
+ else:
440
+ discardConditionset = True
441
+ else: # is range
442
+ # Case C-AR-all
443
+ if selectionValue in cs[selectionName]:
444
+ pass # always matches, conditionset can stay empty for this one.
445
+ else:
446
+ intersection = cs[selectionName].intersection(selectionValue)
447
+ # Case C-AR-inter
448
+ if intersection is not None:
449
+ newConditionset.append(
450
+ {
451
+ "name": selectionName,
452
+ "minimum": intersection.minimum,
453
+ "maximum": intersection.maximum,
454
+ }
455
+ )
456
+ # Case C-AR-none
457
+ else:
458
+ discardConditionset = True
459
+ if not discardConditionset:
460
+ newRule.conditionSets.append(newConditionset)
461
+ if newRule.conditionSets:
462
+ newRules.append(newRule)
463
+
464
+ return newRules
465
+
466
+
467
+ def _filterLocation(
468
+ userRegion: Region,
469
+ location: Dict[str, float],
470
+ ) -> Dict[str, float]:
471
+ return {
472
+ name: value
473
+ for name, value in location.items()
474
+ if name in userRegion and isinstance(userRegion[name], Range)
475
+ }
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/statNames.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compute name information for a given location in user-space coordinates
2
+ using STAT data. This can be used to fill-in automatically the names of an
3
+ instance:
4
+
5
+ .. code:: python
6
+
7
+ instance = doc.instances[0]
8
+ names = getStatNames(doc, instance.getFullUserLocation(doc))
9
+ print(names.styleNames)
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+ from typing import Dict, Literal, Optional, Tuple, Union
16
+ import logging
17
+
18
+ from fontTools.designspaceLib import (
19
+ AxisDescriptor,
20
+ AxisLabelDescriptor,
21
+ DesignSpaceDocument,
22
+ DiscreteAxisDescriptor,
23
+ SimpleLocationDict,
24
+ SourceDescriptor,
25
+ )
26
+
27
+ LOGGER = logging.getLogger(__name__)
28
+
29
+ RibbiStyleName = Union[
30
+ Literal["regular"],
31
+ Literal["bold"],
32
+ Literal["italic"],
33
+ Literal["bold italic"],
34
+ ]
35
+
36
+ BOLD_ITALIC_TO_RIBBI_STYLE = {
37
+ (False, False): "regular",
38
+ (False, True): "italic",
39
+ (True, False): "bold",
40
+ (True, True): "bold italic",
41
+ }
42
+
43
+
44
+ @dataclass
45
+ class StatNames:
46
+ """Name data generated from the STAT table information."""
47
+
48
+ familyNames: Dict[str, str]
49
+ styleNames: Dict[str, str]
50
+ postScriptFontName: Optional[str]
51
+ styleMapFamilyNames: Dict[str, str]
52
+ styleMapStyleName: Optional[RibbiStyleName]
53
+
54
+
55
+ def getStatNames(
56
+ doc: DesignSpaceDocument, userLocation: SimpleLocationDict
57
+ ) -> StatNames:
58
+ """Compute the family, style, PostScript names of the given ``userLocation``
59
+ using the document's STAT information.
60
+
61
+ Also computes localizations.
62
+
63
+ If not enough STAT data is available for a given name, either its dict of
64
+ localized names will be empty (family and style names), or the name will be
65
+ None (PostScript name).
66
+
67
+ Note: this method does not consider info attached to the instance, like
68
+ family name. The user needs to override all names on an instance that STAT
69
+ information would compute differently than desired.
70
+
71
+ .. versionadded:: 5.0
72
+ """
73
+ familyNames: Dict[str, str] = {}
74
+ defaultSource: Optional[SourceDescriptor] = doc.findDefault()
75
+ if defaultSource is None:
76
+ LOGGER.warning("Cannot determine default source to look up family name.")
77
+ elif defaultSource.familyName is None:
78
+ LOGGER.warning(
79
+ "Cannot look up family name, assign the 'familyname' attribute to the default source."
80
+ )
81
+ else:
82
+ familyNames = {
83
+ "en": defaultSource.familyName,
84
+ **defaultSource.localisedFamilyName,
85
+ }
86
+
87
+ styleNames: Dict[str, str] = {}
88
+ # If a free-standing label matches the location, use it for name generation.
89
+ label = doc.labelForUserLocation(userLocation)
90
+ if label is not None:
91
+ styleNames = {"en": label.name, **label.labelNames}
92
+ # Otherwise, scour the axis labels for matches.
93
+ else:
94
+ # Gather all languages in which at least one translation is provided
95
+ # Then build names for all these languages, but fallback to English
96
+ # whenever a translation is missing.
97
+ labels = _getAxisLabelsForUserLocation(doc.axes, userLocation)
98
+ if labels:
99
+ languages = set(
100
+ language for label in labels for language in label.labelNames
101
+ )
102
+ languages.add("en")
103
+ for language in languages:
104
+ styleName = " ".join(
105
+ label.labelNames.get(language, label.defaultName)
106
+ for label in labels
107
+ if not label.elidable
108
+ )
109
+ if not styleName and doc.elidedFallbackName is not None:
110
+ styleName = doc.elidedFallbackName
111
+ styleNames[language] = styleName
112
+
113
+ if "en" not in familyNames or "en" not in styleNames:
114
+ # Not enough information to compute PS names of styleMap names
115
+ return StatNames(
116
+ familyNames=familyNames,
117
+ styleNames=styleNames,
118
+ postScriptFontName=None,
119
+ styleMapFamilyNames={},
120
+ styleMapStyleName=None,
121
+ )
122
+
123
+ postScriptFontName = f"{familyNames['en']}-{styleNames['en']}".replace(" ", "")
124
+
125
+ styleMapStyleName, regularUserLocation = _getRibbiStyle(doc, userLocation)
126
+
127
+ styleNamesForStyleMap = styleNames
128
+ if regularUserLocation != userLocation:
129
+ regularStatNames = getStatNames(doc, regularUserLocation)
130
+ styleNamesForStyleMap = regularStatNames.styleNames
131
+
132
+ styleMapFamilyNames = {}
133
+ for language in set(familyNames).union(styleNames.keys()):
134
+ familyName = familyNames.get(language, familyNames["en"])
135
+ styleName = styleNamesForStyleMap.get(language, styleNamesForStyleMap["en"])
136
+ styleMapFamilyNames[language] = (familyName + " " + styleName).strip()
137
+
138
+ return StatNames(
139
+ familyNames=familyNames,
140
+ styleNames=styleNames,
141
+ postScriptFontName=postScriptFontName,
142
+ styleMapFamilyNames=styleMapFamilyNames,
143
+ styleMapStyleName=styleMapStyleName,
144
+ )
145
+
146
+
147
+ def _getSortedAxisLabels(
148
+ axes: list[Union[AxisDescriptor, DiscreteAxisDescriptor]],
149
+ ) -> Dict[str, list[AxisLabelDescriptor]]:
150
+ """Returns axis labels sorted by their ordering, with unordered ones appended as
151
+ they are listed."""
152
+
153
+ # First, get the axis labels with explicit ordering...
154
+ sortedAxes = sorted(
155
+ (axis for axis in axes if axis.axisOrdering is not None),
156
+ key=lambda a: a.axisOrdering,
157
+ )
158
+ sortedLabels: Dict[str, list[AxisLabelDescriptor]] = {
159
+ axis.name: axis.axisLabels for axis in sortedAxes
160
+ }
161
+
162
+ # ... then append the others in the order they appear.
163
+ # NOTE: This relies on Python 3.7+ dict's preserved insertion order.
164
+ for axis in axes:
165
+ if axis.axisOrdering is None:
166
+ sortedLabels[axis.name] = axis.axisLabels
167
+
168
+ return sortedLabels
169
+
170
+
171
+ def _getAxisLabelsForUserLocation(
172
+ axes: list[Union[AxisDescriptor, DiscreteAxisDescriptor]],
173
+ userLocation: SimpleLocationDict,
174
+ ) -> list[AxisLabelDescriptor]:
175
+ labels: list[AxisLabelDescriptor] = []
176
+
177
+ allAxisLabels = _getSortedAxisLabels(axes)
178
+ if allAxisLabels.keys() != userLocation.keys():
179
+ LOGGER.warning(
180
+ f"Mismatch between user location '{userLocation.keys()}' and available "
181
+ f"labels for '{allAxisLabels.keys()}'."
182
+ )
183
+
184
+ for axisName, axisLabels in allAxisLabels.items():
185
+ userValue = userLocation[axisName]
186
+ label: Optional[AxisLabelDescriptor] = next(
187
+ (
188
+ l
189
+ for l in axisLabels
190
+ if l.userValue == userValue
191
+ or (
192
+ l.userMinimum is not None
193
+ and l.userMaximum is not None
194
+ and l.userMinimum <= userValue <= l.userMaximum
195
+ )
196
+ ),
197
+ None,
198
+ )
199
+ if label is None:
200
+ LOGGER.debug(
201
+ f"Document needs a label for axis '{axisName}', user value '{userValue}'."
202
+ )
203
+ else:
204
+ labels.append(label)
205
+
206
+ return labels
207
+
208
+
209
+ def _getRibbiStyle(
210
+ self: DesignSpaceDocument, userLocation: SimpleLocationDict
211
+ ) -> Tuple[RibbiStyleName, SimpleLocationDict]:
212
+ """Compute the RIBBI style name of the given user location,
213
+ return the location of the matching Regular in the RIBBI group.
214
+
215
+ .. versionadded:: 5.0
216
+ """
217
+ regularUserLocation = {}
218
+ axes_by_tag = {axis.tag: axis for axis in self.axes}
219
+
220
+ bold: bool = False
221
+ italic: bool = False
222
+
223
+ axis = axes_by_tag.get("wght")
224
+ if axis is not None:
225
+ for regular_label in axis.axisLabels:
226
+ if (
227
+ regular_label.linkedUserValue == userLocation[axis.name]
228
+ # In the "recursive" case where both the Regular has
229
+ # linkedUserValue pointing the Bold, and the Bold has
230
+ # linkedUserValue pointing to the Regular, only consider the
231
+ # first case: Regular (e.g. 400) has linkedUserValue pointing to
232
+ # Bold (e.g. 700, higher than Regular)
233
+ and regular_label.userValue < regular_label.linkedUserValue
234
+ ):
235
+ regularUserLocation[axis.name] = regular_label.userValue
236
+ bold = True
237
+ break
238
+
239
+ axis = axes_by_tag.get("ital") or axes_by_tag.get("slnt")
240
+ if axis is not None:
241
+ for upright_label in axis.axisLabels:
242
+ if (
243
+ upright_label.linkedUserValue == userLocation[axis.name]
244
+ # In the "recursive" case where both the Upright has
245
+ # linkedUserValue pointing the Italic, and the Italic has
246
+ # linkedUserValue pointing to the Upright, only consider the
247
+ # first case: Upright (e.g. ital=0, slant=0) has
248
+ # linkedUserValue pointing to Italic (e.g ital=1, slant=-12 or
249
+ # slant=12 for backwards italics, in any case higher than
250
+ # Upright in absolute value, hence the abs() below.
251
+ and abs(upright_label.userValue) < abs(upright_label.linkedUserValue)
252
+ ):
253
+ regularUserLocation[axis.name] = upright_label.userValue
254
+ italic = True
255
+ break
256
+
257
+ return BOLD_ITALIC_TO_RIBBI_STYLE[bold, italic], {
258
+ **userLocation,
259
+ **regularUserLocation,
260
+ }
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/types.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Dict, List, Optional, Union, cast
5
+
6
+ from fontTools.designspaceLib import (
7
+ AxisDescriptor,
8
+ DesignSpaceDocument,
9
+ DesignSpaceDocumentError,
10
+ RangeAxisSubsetDescriptor,
11
+ SimpleLocationDict,
12
+ ValueAxisSubsetDescriptor,
13
+ VariableFontDescriptor,
14
+ )
15
+
16
+
17
+ def clamp(value, minimum, maximum):
18
+ return min(max(value, minimum), maximum)
19
+
20
+
21
+ @dataclass
22
+ class Range:
23
+ minimum: float
24
+ """Inclusive minimum of the range."""
25
+ maximum: float
26
+ """Inclusive maximum of the range."""
27
+ default: float = 0
28
+ """Default value"""
29
+
30
+ def __post_init__(self):
31
+ self.minimum, self.maximum = sorted((self.minimum, self.maximum))
32
+ self.default = clamp(self.default, self.minimum, self.maximum)
33
+
34
+ def __contains__(self, value: Union[float, Range]) -> bool:
35
+ if isinstance(value, Range):
36
+ return self.minimum <= value.minimum and value.maximum <= self.maximum
37
+ return self.minimum <= value <= self.maximum
38
+
39
+ def intersection(self, other: Range) -> Optional[Range]:
40
+ if self.maximum < other.minimum or self.minimum > other.maximum:
41
+ return None
42
+ else:
43
+ return Range(
44
+ max(self.minimum, other.minimum),
45
+ min(self.maximum, other.maximum),
46
+ self.default, # We don't care about the default in this use-case
47
+ )
48
+
49
+
50
+ # A region selection is either a range or a single value, as a Designspace v5
51
+ # axis-subset element only allows a single discrete value or a range for a
52
+ # variable-font element.
53
+ Region = Dict[str, Union[Range, float]]
54
+
55
+ # A conditionset is a set of named ranges.
56
+ ConditionSet = Dict[str, Range]
57
+
58
+ # A rule is a list of conditionsets where any has to be relevant for the whole rule to be relevant.
59
+ Rule = List[ConditionSet]
60
+ Rules = Dict[str, Rule]
61
+
62
+
63
+ def locationInRegion(location: SimpleLocationDict, region: Region) -> bool:
64
+ for name, value in location.items():
65
+ if name not in region:
66
+ return False
67
+ regionValue = region[name]
68
+ if isinstance(regionValue, (float, int)):
69
+ if value != regionValue:
70
+ return False
71
+ else:
72
+ if value not in regionValue:
73
+ return False
74
+ return True
75
+
76
+
77
+ def regionInRegion(region: Region, superRegion: Region) -> bool:
78
+ for name, value in region.items():
79
+ if not name in superRegion:
80
+ return False
81
+ superValue = superRegion[name]
82
+ if isinstance(superValue, (float, int)):
83
+ if value != superValue:
84
+ return False
85
+ else:
86
+ if value not in superValue:
87
+ return False
88
+ return True
89
+
90
+
91
+ def userRegionToDesignRegion(doc: DesignSpaceDocument, userRegion: Region) -> Region:
92
+ designRegion = {}
93
+ for name, value in userRegion.items():
94
+ axis = doc.getAxis(name)
95
+ if axis is None:
96
+ raise DesignSpaceDocumentError(
97
+ f"Cannot find axis named '{name}' for region."
98
+ )
99
+ if isinstance(value, (float, int)):
100
+ designRegion[name] = axis.map_forward(value)
101
+ else:
102
+ designRegion[name] = Range(
103
+ axis.map_forward(value.minimum),
104
+ axis.map_forward(value.maximum),
105
+ axis.map_forward(value.default),
106
+ )
107
+ return designRegion
108
+
109
+
110
+ def getVFUserRegion(doc: DesignSpaceDocument, vf: VariableFontDescriptor) -> Region:
111
+ vfUserRegion: Region = {}
112
+ # For each axis, 2 cases:
113
+ # - it has a range = it's an axis in the VF DS
114
+ # - it's a single location = use it to know which rules should apply in the VF
115
+ for axisSubset in vf.axisSubsets:
116
+ axis = doc.getAxis(axisSubset.name)
117
+ if axis is None:
118
+ raise DesignSpaceDocumentError(
119
+ f"Cannot find axis named '{axisSubset.name}' for variable font '{vf.name}'."
120
+ )
121
+ if hasattr(axisSubset, "userMinimum"):
122
+ # Mypy doesn't support narrowing union types via hasattr()
123
+ # TODO(Python 3.10): use TypeGuard
124
+ # https://mypy.readthedocs.io/en/stable/type_narrowing.html
125
+ axisSubset = cast(RangeAxisSubsetDescriptor, axisSubset)
126
+ if not hasattr(axis, "minimum"):
127
+ raise DesignSpaceDocumentError(
128
+ f"Cannot select a range over '{axis.name}' for variable font '{vf.name}' "
129
+ "because it's a discrete axis, use only 'userValue' instead."
130
+ )
131
+ axis = cast(AxisDescriptor, axis)
132
+ vfUserRegion[axis.name] = Range(
133
+ max(axisSubset.userMinimum, axis.minimum),
134
+ min(axisSubset.userMaximum, axis.maximum),
135
+ axisSubset.userDefault or axis.default,
136
+ )
137
+ else:
138
+ axisSubset = cast(ValueAxisSubsetDescriptor, axisSubset)
139
+ vfUserRegion[axis.name] = axisSubset.userValue
140
+ # Any axis not mentioned explicitly has a single location = default value
141
+ for axis in doc.axes:
142
+ if axis.name not in vfUserRegion:
143
+ assert isinstance(
144
+ axis.default, (int, float)
145
+ ), f"Axis '{axis.name}' has no valid default value."
146
+ vfUserRegion[axis.name] = axis.default
147
+ return vfUserRegion
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/fontBuilder.py ADDED
@@ -0,0 +1,1014 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 setupGVAR(self, variations):
718
+ gvar = self.font["GVAR"] = newTable("GVAR")
719
+ gvar.version = 1
720
+ gvar.reserved = 0
721
+ gvar.variations = variations
722
+
723
+ def calcGlyphBounds(self):
724
+ """Calculate the bounding boxes of all glyphs in the `glyf` table.
725
+ This is usually not called explicitly by client code.
726
+ """
727
+ glyphTable = self.font["glyf"]
728
+ for glyph in glyphTable.glyphs.values():
729
+ glyph.recalcBounds(glyphTable)
730
+
731
+ def setupHorizontalMetrics(self, metrics):
732
+ """Create a new `hmtx` table, for horizontal metrics.
733
+
734
+ The `metrics` argument must be a dict, mapping glyph names to
735
+ `(width, leftSidebearing)` tuples.
736
+ """
737
+ self.setupMetrics("hmtx", metrics)
738
+
739
+ def setupVerticalMetrics(self, metrics):
740
+ """Create a new `vmtx` table, for horizontal metrics.
741
+
742
+ The `metrics` argument must be a dict, mapping glyph names to
743
+ `(height, topSidebearing)` tuples.
744
+ """
745
+ self.setupMetrics("vmtx", metrics)
746
+
747
+ def setupMetrics(self, tableTag, metrics):
748
+ """See `setupHorizontalMetrics()` and `setupVerticalMetrics()`."""
749
+ assert tableTag in ("hmtx", "vmtx")
750
+ mtxTable = self.font[tableTag] = newTable(tableTag)
751
+ roundedMetrics = {}
752
+ for gn in metrics:
753
+ w, lsb = metrics[gn]
754
+ roundedMetrics[gn] = int(round(w)), int(round(lsb))
755
+ mtxTable.metrics = roundedMetrics
756
+
757
+ def setupHorizontalHeader(self, **values):
758
+ """Create a new `hhea` table initialize it with default values,
759
+ which can be overridden by keyword arguments.
760
+ """
761
+ self._initTableWithValues("hhea", _hheaDefaults, values)
762
+
763
+ def setupVerticalHeader(self, **values):
764
+ """Create a new `vhea` table initialize it with default values,
765
+ which can be overridden by keyword arguments.
766
+ """
767
+ self._initTableWithValues("vhea", _vheaDefaults, values)
768
+
769
+ def setupVerticalOrigins(self, verticalOrigins, defaultVerticalOrigin=None):
770
+ """Create a new `VORG` table. The `verticalOrigins` argument must be
771
+ a dict, mapping glyph names to vertical origin values.
772
+
773
+ The `defaultVerticalOrigin` argument should be the most common vertical
774
+ origin value. If omitted, this value will be derived from the actual
775
+ values in the `verticalOrigins` argument.
776
+ """
777
+ if defaultVerticalOrigin is None:
778
+ # find the most frequent vorg value
779
+ bag = {}
780
+ for gn in verticalOrigins:
781
+ vorg = verticalOrigins[gn]
782
+ if vorg not in bag:
783
+ bag[vorg] = 1
784
+ else:
785
+ bag[vorg] += 1
786
+ defaultVerticalOrigin = sorted(
787
+ bag, key=lambda vorg: bag[vorg], reverse=True
788
+ )[0]
789
+ self._initTableWithValues(
790
+ "VORG",
791
+ {},
792
+ dict(VOriginRecords={}, defaultVertOriginY=defaultVerticalOrigin),
793
+ )
794
+ vorgTable = self.font["VORG"]
795
+ vorgTable.majorVersion = 1
796
+ vorgTable.minorVersion = 0
797
+ for gn in verticalOrigins:
798
+ vorgTable[gn] = verticalOrigins[gn]
799
+
800
+ def setupPost(self, keepGlyphNames=True, **values):
801
+ """Create a new `post` table and initialize it with default values,
802
+ which can be overridden by keyword arguments.
803
+ """
804
+ isCFF2 = "CFF2" in self.font
805
+ postTable = self._initTableWithValues("post", _postDefaults, values)
806
+ if (self.isTTF or isCFF2) and keepGlyphNames:
807
+ postTable.formatType = 2.0
808
+ postTable.extraNames = []
809
+ postTable.mapping = {}
810
+ else:
811
+ postTable.formatType = 3.0
812
+
813
+ def setupMaxp(self):
814
+ """Create a new `maxp` table. This is called implicitly by FontBuilder
815
+ itself and is usually not called by client code.
816
+ """
817
+ if self.isTTF:
818
+ defaults = _maxpDefaultsTTF
819
+ else:
820
+ defaults = _maxpDefaultsOTF
821
+ self._initTableWithValues("maxp", defaults, {})
822
+
823
+ def setupDummyDSIG(self):
824
+ """This adds an empty DSIG table to the font to make some MS applications
825
+ happy. This does not properly sign the font.
826
+ """
827
+ values = dict(
828
+ ulVersion=1,
829
+ usFlag=0,
830
+ usNumSigs=0,
831
+ signatureRecords=[],
832
+ )
833
+ self._initTableWithValues("DSIG", {}, values)
834
+
835
+ def addOpenTypeFeatures(self, features, filename=None, tables=None, debug=False):
836
+ """Add OpenType features to the font from a string containing
837
+ Feature File syntax.
838
+
839
+ The `filename` argument is used in error messages and to determine
840
+ where to look for "include" files.
841
+
842
+ The optional `tables` argument can be a list of OTL tables tags to
843
+ build, allowing the caller to only build selected OTL tables. See
844
+ `fontTools.feaLib` for details.
845
+
846
+ The optional `debug` argument controls whether to add source debugging
847
+ information to the font in the `Debg` table.
848
+ """
849
+ from .feaLib.builder import addOpenTypeFeaturesFromString
850
+
851
+ addOpenTypeFeaturesFromString(
852
+ self.font, features, filename=filename, tables=tables, debug=debug
853
+ )
854
+
855
+ def addFeatureVariations(self, conditionalSubstitutions, featureTag="rvrn"):
856
+ """Add conditional substitutions to a Variable Font.
857
+
858
+ See `fontTools.varLib.featureVars.addFeatureVariations`.
859
+ """
860
+ from .varLib import featureVars
861
+
862
+ if "fvar" not in self.font:
863
+ raise KeyError("'fvar' table is missing; can't add FeatureVariations.")
864
+
865
+ featureVars.addFeatureVariations(
866
+ self.font, conditionalSubstitutions, featureTag=featureTag
867
+ )
868
+
869
+ def setupCOLR(
870
+ self,
871
+ colorLayers,
872
+ version=None,
873
+ varStore=None,
874
+ varIndexMap=None,
875
+ clipBoxes=None,
876
+ allowLayerReuse=True,
877
+ ):
878
+ """Build new COLR table using color layers dictionary.
879
+
880
+ Cf. `fontTools.colorLib.builder.buildCOLR`.
881
+ """
882
+ from fontTools.colorLib.builder import buildCOLR
883
+
884
+ glyphMap = self.font.getReverseGlyphMap()
885
+ self.font["COLR"] = buildCOLR(
886
+ colorLayers,
887
+ version=version,
888
+ glyphMap=glyphMap,
889
+ varStore=varStore,
890
+ varIndexMap=varIndexMap,
891
+ clipBoxes=clipBoxes,
892
+ allowLayerReuse=allowLayerReuse,
893
+ )
894
+
895
+ def setupCPAL(
896
+ self,
897
+ palettes,
898
+ paletteTypes=None,
899
+ paletteLabels=None,
900
+ paletteEntryLabels=None,
901
+ ):
902
+ """Build new CPAL table using list of palettes.
903
+
904
+ Optionally build CPAL v1 table using paletteTypes, paletteLabels and
905
+ paletteEntryLabels.
906
+
907
+ Cf. `fontTools.colorLib.builder.buildCPAL`.
908
+ """
909
+ from fontTools.colorLib.builder import buildCPAL
910
+
911
+ self.font["CPAL"] = buildCPAL(
912
+ palettes,
913
+ paletteTypes=paletteTypes,
914
+ paletteLabels=paletteLabels,
915
+ paletteEntryLabels=paletteEntryLabels,
916
+ nameTable=self.font.get("name"),
917
+ )
918
+
919
+ def setupStat(self, axes, locations=None, elidedFallbackName=2):
920
+ """Build a new 'STAT' table.
921
+
922
+ See `fontTools.otlLib.builder.buildStatTable` for details about
923
+ the arguments.
924
+ """
925
+ from .otlLib.builder import buildStatTable
926
+
927
+ assert "name" in self.font, "name must to be set up first"
928
+
929
+ buildStatTable(
930
+ self.font,
931
+ axes,
932
+ locations,
933
+ elidedFallbackName,
934
+ macNames=any(nr.platformID == 1 for nr in self.font["name"].names),
935
+ )
936
+
937
+
938
+ def buildCmapSubTable(cmapping, format, platformID, platEncID):
939
+ subTable = cmap_classes[format](format)
940
+ subTable.cmap = cmapping
941
+ subTable.platformID = platformID
942
+ subTable.platEncID = platEncID
943
+ subTable.language = 0
944
+ return subTable
945
+
946
+
947
+ def addFvar(font, axes, instances):
948
+ from .ttLib.tables._f_v_a_r import Axis, NamedInstance
949
+
950
+ assert axes
951
+
952
+ fvar = newTable("fvar")
953
+ nameTable = font["name"]
954
+
955
+ # if there are not currently any mac names don't add them here, that's inconsistent
956
+ # https://github.com/fonttools/fonttools/issues/683
957
+ macNames = any(nr.platformID == 1 for nr in getattr(nameTable, "names", ()))
958
+
959
+ # we have all the best ways to express mac names
960
+ platforms = ((3, 1, 0x409),)
961
+ if macNames:
962
+ platforms = ((1, 0, 0),) + platforms
963
+
964
+ for axis_def in axes:
965
+ axis = Axis()
966
+
967
+ if isinstance(axis_def, tuple):
968
+ (
969
+ axis.axisTag,
970
+ axis.minValue,
971
+ axis.defaultValue,
972
+ axis.maxValue,
973
+ name,
974
+ ) = axis_def
975
+ else:
976
+ (axis.axisTag, axis.minValue, axis.defaultValue, axis.maxValue, name) = (
977
+ axis_def.tag,
978
+ axis_def.minimum,
979
+ axis_def.default,
980
+ axis_def.maximum,
981
+ axis_def.name,
982
+ )
983
+ if axis_def.hidden:
984
+ axis.flags = 0x0001 # HIDDEN_AXIS
985
+
986
+ if isinstance(name, str):
987
+ name = dict(en=name)
988
+
989
+ axis.axisNameID = nameTable.addMultilingualName(name, ttFont=font, mac=macNames)
990
+ fvar.axes.append(axis)
991
+
992
+ for instance in instances:
993
+ if isinstance(instance, dict):
994
+ coordinates = instance["location"]
995
+ name = instance["stylename"]
996
+ psname = instance.get("postscriptfontname")
997
+ else:
998
+ coordinates = instance.location
999
+ name = instance.localisedStyleName or instance.styleName
1000
+ psname = instance.postScriptFontName
1001
+
1002
+ if isinstance(name, str):
1003
+ name = dict(en=name)
1004
+
1005
+ inst = NamedInstance()
1006
+ inst.subfamilyNameID = nameTable.addMultilingualName(
1007
+ name, ttFont=font, mac=macNames
1008
+ )
1009
+ if psname is not None:
1010
+ inst.postscriptNameID = nameTable.addName(psname, platforms=platforms)
1011
+ inst.coordinates = coordinates
1012
+ fvar.instances.append(inst)
1013
+
1014
+ font["fvar"] = fvar
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/help.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pkgutil
2
+ import sys
3
+ import fontTools
4
+ import importlib
5
+ import os
6
+ from pathlib import Path
7
+
8
+
9
+ def main():
10
+ """Show this help"""
11
+ path = fontTools.__path__
12
+ descriptions = {}
13
+ for pkg in sorted(
14
+ mod.name
15
+ for mod in pkgutil.walk_packages([fontTools.__path__[0]], prefix="fontTools.")
16
+ ):
17
+ try:
18
+ imports = __import__(pkg, globals(), locals(), ["main"])
19
+ except ImportError as e:
20
+ continue
21
+ try:
22
+ description = imports.main.__doc__
23
+ # Cython modules seem to return "main()" as the docstring
24
+ if description and description != "main()":
25
+ pkg = pkg.replace("fontTools.", "").replace(".__main__", "")
26
+ # show the docstring's first line only
27
+ descriptions[pkg] = description.splitlines()[0]
28
+ except AttributeError as e:
29
+ pass
30
+ for pkg, description in descriptions.items():
31
+ print("fonttools %-25s %s" % (pkg, description), file=sys.stderr)
32
+
33
+
34
+ if __name__ == "__main__":
35
+ print("fonttools v%s\n" % fontTools.__version__, file=sys.stderr)
36
+ main()
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/__init__.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2013 Google, Inc. All Rights Reserved.
2
+ #
3
+ # Google Author(s): Behdad Esfahbod, Roozbeh Pournader
4
+
5
+ from fontTools import ttLib
6
+ import fontTools.merge.base
7
+ from fontTools.merge.cmap import (
8
+ computeMegaGlyphOrder,
9
+ computeMegaCmap,
10
+ renameCFFCharStrings,
11
+ )
12
+ from fontTools.merge.layout import layoutPreMerge, layoutPostMerge
13
+ from fontTools.merge.options import Options
14
+ import fontTools.merge.tables
15
+ from fontTools.misc.loggingTools import Timer
16
+ from functools import reduce
17
+ import sys
18
+ import logging
19
+
20
+
21
+ log = logging.getLogger("fontTools.merge")
22
+ timer = Timer(logger=logging.getLogger(__name__ + ".timer"), level=logging.INFO)
23
+
24
+
25
+ class Merger(object):
26
+ """Font merger.
27
+
28
+ This class merges multiple files into a single OpenType font, taking into
29
+ account complexities such as OpenType layout (``GSUB``/``GPOS``) tables and
30
+ cross-font metrics (for example ``hhea.ascent`` is set to the maximum value
31
+ across all the fonts).
32
+
33
+ If multiple glyphs map to the same Unicode value, and the glyphs are considered
34
+ sufficiently different (that is, they differ in any of paths, widths, or
35
+ height), then subsequent glyphs are renamed and a lookup in the ``locl``
36
+ feature will be created to disambiguate them. For example, if the arguments
37
+ are an Arabic font and a Latin font and both contain a set of parentheses,
38
+ the Latin glyphs will be renamed to ``parenleft.1`` and ``parenright.1``,
39
+ and a lookup will be inserted into the to ``locl`` feature (creating it if
40
+ necessary) under the ``latn`` script to substitute ``parenleft`` with
41
+ ``parenleft.1`` etc.
42
+
43
+ Restrictions:
44
+
45
+ - All fonts must have the same units per em.
46
+ - If duplicate glyph disambiguation takes place as described above then the
47
+ fonts must have a ``GSUB`` table.
48
+
49
+ Attributes:
50
+ options: Currently unused.
51
+ """
52
+
53
+ def __init__(self, options=None):
54
+ if not options:
55
+ options = Options()
56
+
57
+ self.options = options
58
+
59
+ def _openFonts(self, fontfiles):
60
+ fonts = [ttLib.TTFont(fontfile) for fontfile in fontfiles]
61
+ for font, fontfile in zip(fonts, fontfiles):
62
+ font._merger__fontfile = fontfile
63
+ font._merger__name = font["name"].getDebugName(4)
64
+ return fonts
65
+
66
+ def merge(self, fontfiles):
67
+ """Merges fonts together.
68
+
69
+ Args:
70
+ fontfiles: A list of file names to be merged
71
+
72
+ Returns:
73
+ A :class:`fontTools.ttLib.TTFont` object. Call the ``save`` method on
74
+ this to write it out to an OTF file.
75
+ """
76
+ #
77
+ # Settle on a mega glyph order.
78
+ #
79
+ fonts = self._openFonts(fontfiles)
80
+ glyphOrders = [list(font.getGlyphOrder()) for font in fonts]
81
+ computeMegaGlyphOrder(self, glyphOrders)
82
+
83
+ # Take first input file sfntVersion
84
+ sfntVersion = fonts[0].sfntVersion
85
+
86
+ # Reload fonts and set new glyph names on them.
87
+ fonts = self._openFonts(fontfiles)
88
+ for font, glyphOrder in zip(fonts, glyphOrders):
89
+ font.setGlyphOrder(glyphOrder)
90
+ if "CFF " in font:
91
+ renameCFFCharStrings(self, glyphOrder, font["CFF "])
92
+
93
+ cmaps = [font["cmap"] for font in fonts]
94
+ self.duplicateGlyphsPerFont = [{} for _ in fonts]
95
+ computeMegaCmap(self, cmaps)
96
+
97
+ mega = ttLib.TTFont(sfntVersion=sfntVersion)
98
+ mega.setGlyphOrder(self.glyphOrder)
99
+
100
+ for font in fonts:
101
+ self._preMerge(font)
102
+
103
+ self.fonts = fonts
104
+
105
+ allTags = reduce(set.union, (list(font.keys()) for font in fonts), set())
106
+ allTags.remove("GlyphOrder")
107
+
108
+ for tag in sorted(allTags):
109
+ if tag in self.options.drop_tables:
110
+ continue
111
+
112
+ with timer("merge '%s'" % tag):
113
+ tables = [font.get(tag, NotImplemented) for font in fonts]
114
+
115
+ log.info("Merging '%s'.", tag)
116
+ clazz = ttLib.getTableClass(tag)
117
+ table = clazz(tag).merge(self, tables)
118
+ # XXX Clean this up and use: table = mergeObjects(tables)
119
+
120
+ if table is not NotImplemented and table is not False:
121
+ mega[tag] = table
122
+ log.info("Merged '%s'.", tag)
123
+ else:
124
+ log.info("Dropped '%s'.", tag)
125
+
126
+ del self.duplicateGlyphsPerFont
127
+ del self.fonts
128
+
129
+ self._postMerge(mega)
130
+
131
+ return mega
132
+
133
+ def mergeObjects(self, returnTable, logic, tables):
134
+ # Right now we don't use self at all. Will use in the future
135
+ # for options and logging.
136
+
137
+ allKeys = set.union(
138
+ set(),
139
+ *(vars(table).keys() for table in tables if table is not NotImplemented),
140
+ )
141
+ for key in allKeys:
142
+ log.info(" %s", key)
143
+ try:
144
+ mergeLogic = logic[key]
145
+ except KeyError:
146
+ try:
147
+ mergeLogic = logic["*"]
148
+ except KeyError:
149
+ raise Exception(
150
+ "Don't know how to merge key %s of class %s"
151
+ % (key, returnTable.__class__.__name__)
152
+ )
153
+ if mergeLogic is NotImplemented:
154
+ continue
155
+ value = mergeLogic(getattr(table, key, NotImplemented) for table in tables)
156
+ if value is not NotImplemented:
157
+ setattr(returnTable, key, value)
158
+
159
+ return returnTable
160
+
161
+ def _preMerge(self, font):
162
+ layoutPreMerge(font)
163
+
164
+ def _postMerge(self, font):
165
+ layoutPostMerge(font)
166
+
167
+ if "OS/2" in font:
168
+ # https://github.com/fonttools/fonttools/issues/2538
169
+ # TODO: Add an option to disable this?
170
+ font["OS/2"].recalcAvgCharWidth(font)
171
+
172
+
173
+ __all__ = ["Options", "Merger", "main"]
174
+
175
+
176
+ @timer("make one with everything (TOTAL TIME)")
177
+ def main(args=None):
178
+ """Merge multiple fonts into one"""
179
+ from fontTools import configLogger
180
+
181
+ if args is None:
182
+ args = sys.argv[1:]
183
+
184
+ options = Options()
185
+ args = options.parse_opts(args)
186
+ fontfiles = []
187
+ if options.input_file:
188
+ with open(options.input_file) as inputfile:
189
+ fontfiles = [
190
+ line.strip()
191
+ for line in inputfile.readlines()
192
+ if not line.lstrip().startswith("#")
193
+ ]
194
+ for g in args:
195
+ fontfiles.append(g)
196
+
197
+ if len(fontfiles) < 1:
198
+ print(
199
+ "usage: fonttools merge [font1 ... fontN] [--input-file=filelist.txt] [--output-file=merged.ttf] [--import-file=tables.ttx]",
200
+ file=sys.stderr,
201
+ )
202
+ print(
203
+ " [--drop-tables=tags] [--verbose] [--timing]",
204
+ file=sys.stderr,
205
+ )
206
+ print("", file=sys.stderr)
207
+ print(" font1 ... fontN Files to merge.", file=sys.stderr)
208
+ print(
209
+ " --input-file=<filename> Read files to merge from a text file, each path new line. # Comment lines allowed.",
210
+ file=sys.stderr,
211
+ )
212
+ print(
213
+ " --output-file=<filename> Specify output file name (default: merged.ttf).",
214
+ file=sys.stderr,
215
+ )
216
+ print(
217
+ " --import-file=<filename> TTX file to import after merging. This can be used to set metadata.",
218
+ file=sys.stderr,
219
+ )
220
+ print(
221
+ " --drop-tables=<table tags> Comma separated list of table tags to skip, case sensitive.",
222
+ file=sys.stderr,
223
+ )
224
+ print(
225
+ " --verbose Output progress information.",
226
+ file=sys.stderr,
227
+ )
228
+ print(" --timing Output progress timing.", file=sys.stderr)
229
+ return 1
230
+
231
+ configLogger(level=logging.INFO if options.verbose else logging.WARNING)
232
+ if options.timing:
233
+ timer.logger.setLevel(logging.DEBUG)
234
+ else:
235
+ timer.logger.disabled = True
236
+
237
+ merger = Merger(options=options)
238
+ font = merger.merge(fontfiles)
239
+
240
+ if options.import_file:
241
+ font.importXML(options.import_file)
242
+
243
+ with timer("compile and save font"):
244
+ font.save(options.output_file)
245
+
246
+
247
+ if __name__ == "__main__":
248
+ sys.exit(main())
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/__main__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import sys
2
+ from fontTools.merge import main
3
+
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/base.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2013 Google, Inc. All Rights Reserved.
2
+ #
3
+ # Google Author(s): Behdad Esfahbod, Roozbeh Pournader
4
+
5
+ from fontTools.ttLib.tables.DefaultTable import DefaultTable
6
+ import logging
7
+
8
+
9
+ log = logging.getLogger("fontTools.merge")
10
+
11
+
12
+ def add_method(*clazzes, **kwargs):
13
+ """Returns a decorator function that adds a new method to one or
14
+ more classes."""
15
+ allowDefault = kwargs.get("allowDefaultTable", False)
16
+
17
+ def wrapper(method):
18
+ done = []
19
+ for clazz in clazzes:
20
+ if clazz in done:
21
+ continue # Support multiple names of a clazz
22
+ done.append(clazz)
23
+ assert allowDefault or clazz != DefaultTable, "Oops, table class not found."
24
+ assert (
25
+ method.__name__ not in clazz.__dict__
26
+ ), "Oops, class '%s' has method '%s'." % (clazz.__name__, method.__name__)
27
+ setattr(clazz, method.__name__, method)
28
+ return None
29
+
30
+ return wrapper
31
+
32
+
33
+ def mergeObjects(lst):
34
+ lst = [item for item in lst if item is not NotImplemented]
35
+ if not lst:
36
+ return NotImplemented
37
+ lst = [item for item in lst if item is not None]
38
+ if not lst:
39
+ return None
40
+
41
+ clazz = lst[0].__class__
42
+ assert all(type(item) == clazz for item in lst), lst
43
+
44
+ logic = clazz.mergeMap
45
+ returnTable = clazz()
46
+ returnDict = {}
47
+
48
+ allKeys = set.union(set(), *(vars(table).keys() for table in lst))
49
+ for key in allKeys:
50
+ try:
51
+ mergeLogic = logic[key]
52
+ except KeyError:
53
+ try:
54
+ mergeLogic = logic["*"]
55
+ except KeyError:
56
+ raise Exception(
57
+ "Don't know how to merge key %s of class %s" % (key, clazz.__name__)
58
+ )
59
+ if mergeLogic is NotImplemented:
60
+ continue
61
+ value = mergeLogic(getattr(table, key, NotImplemented) for table in lst)
62
+ if value is not NotImplemented:
63
+ returnDict[key] = value
64
+
65
+ returnTable.__dict__ = returnDict
66
+
67
+ return returnTable
68
+
69
+
70
+ @add_method(DefaultTable, allowDefaultTable=True)
71
+ def merge(self, m, tables):
72
+ if not hasattr(self, "mergeMap"):
73
+ log.info("Don't know how to merge '%s'.", self.tableTag)
74
+ return NotImplemented
75
+
76
+ logic = self.mergeMap
77
+
78
+ if isinstance(logic, dict):
79
+ return m.mergeObjects(self, self.mergeMap, tables)
80
+ else:
81
+ return logic(tables)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/cmap.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2013 Google, Inc. All Rights Reserved.
2
+ #
3
+ # Google Author(s): Behdad Esfahbod, Roozbeh Pournader
4
+
5
+ from fontTools.merge.unicode import is_Default_Ignorable
6
+ from fontTools.pens.recordingPen import DecomposingRecordingPen
7
+ import logging
8
+
9
+
10
+ log = logging.getLogger("fontTools.merge")
11
+
12
+
13
+ def computeMegaGlyphOrder(merger, glyphOrders):
14
+ """Modifies passed-in glyphOrders to reflect new glyph names.
15
+ Stores merger.glyphOrder."""
16
+ megaOrder = {}
17
+ for glyphOrder in glyphOrders:
18
+ for i, glyphName in enumerate(glyphOrder):
19
+ if glyphName in megaOrder:
20
+ n = megaOrder[glyphName]
21
+ while (glyphName + "." + repr(n)) in megaOrder:
22
+ n += 1
23
+ megaOrder[glyphName] = n
24
+ glyphName += "." + repr(n)
25
+ glyphOrder[i] = glyphName
26
+ megaOrder[glyphName] = 1
27
+ merger.glyphOrder = megaOrder = list(megaOrder.keys())
28
+
29
+
30
+ def _glyphsAreSame(
31
+ glyphSet1,
32
+ glyphSet2,
33
+ glyph1,
34
+ glyph2,
35
+ advanceTolerance=0.05,
36
+ advanceToleranceEmpty=0.20,
37
+ ):
38
+ pen1 = DecomposingRecordingPen(glyphSet1)
39
+ pen2 = DecomposingRecordingPen(glyphSet2)
40
+ g1 = glyphSet1[glyph1]
41
+ g2 = glyphSet2[glyph2]
42
+ g1.draw(pen1)
43
+ g2.draw(pen2)
44
+ if pen1.value != pen2.value:
45
+ return False
46
+ # Allow more width tolerance for glyphs with no ink
47
+ tolerance = advanceTolerance if pen1.value else advanceToleranceEmpty
48
+ # TODO Warn if advances not the same but within tolerance.
49
+ if abs(g1.width - g2.width) > g1.width * tolerance:
50
+ return False
51
+ if hasattr(g1, "height") and g1.height is not None:
52
+ if abs(g1.height - g2.height) > g1.height * tolerance:
53
+ return False
54
+ return True
55
+
56
+
57
+ def computeMegaUvs(merger, uvsTables):
58
+ """Returns merged UVS subtable (cmap format=14)."""
59
+ uvsDict = {}
60
+ cmap = merger.cmap
61
+ for table in uvsTables:
62
+ for variationSelector, uvsMapping in table.uvsDict.items():
63
+ if variationSelector not in uvsDict:
64
+ uvsDict[variationSelector] = {}
65
+ for unicodeValue, glyphName in uvsMapping:
66
+ if cmap.get(unicodeValue) == glyphName:
67
+ # this is a default variation
68
+ glyphName = None
69
+ # prefer previous glyph id if both fonts defined UVS
70
+ if unicodeValue not in uvsDict[variationSelector]:
71
+ uvsDict[variationSelector][unicodeValue] = glyphName
72
+
73
+ for variationSelector in uvsDict:
74
+ uvsDict[variationSelector] = [*uvsDict[variationSelector].items()]
75
+
76
+ return uvsDict
77
+
78
+
79
+ # Valid (format, platformID, platEncID) triplets for cmap subtables containing
80
+ # Unicode BMP-only and Unicode Full Repertoire semantics.
81
+ # Cf. OpenType spec for "Platform specific encodings":
82
+ # https://docs.microsoft.com/en-us/typography/opentype/spec/name
83
+ class _CmapUnicodePlatEncodings:
84
+ BMP = {(4, 3, 1), (4, 0, 3), (4, 0, 4), (4, 0, 6)}
85
+ FullRepertoire = {(12, 3, 10), (12, 0, 4), (12, 0, 6)}
86
+ UVS = {(14, 0, 5)}
87
+
88
+
89
+ def computeMegaCmap(merger, cmapTables):
90
+ """Sets merger.cmap and merger.uvsDict."""
91
+
92
+ # TODO Handle format=14.
93
+ # Only merge format 4 and 12 Unicode subtables, ignores all other subtables
94
+ # If there is a format 12 table for a font, ignore the format 4 table of it
95
+ chosenCmapTables = []
96
+ chosenUvsTables = []
97
+ for fontIdx, table in enumerate(cmapTables):
98
+ format4 = None
99
+ format12 = None
100
+ format14 = None
101
+ for subtable in table.tables:
102
+ properties = (subtable.format, subtable.platformID, subtable.platEncID)
103
+ if properties in _CmapUnicodePlatEncodings.BMP:
104
+ format4 = subtable
105
+ elif properties in _CmapUnicodePlatEncodings.FullRepertoire:
106
+ format12 = subtable
107
+ elif properties in _CmapUnicodePlatEncodings.UVS:
108
+ format14 = subtable
109
+ else:
110
+ log.warning(
111
+ "Dropped cmap subtable from font '%s':\t"
112
+ "format %2s, platformID %2s, platEncID %2s",
113
+ fontIdx,
114
+ subtable.format,
115
+ subtable.platformID,
116
+ subtable.platEncID,
117
+ )
118
+ if format12 is not None:
119
+ chosenCmapTables.append((format12, fontIdx))
120
+ elif format4 is not None:
121
+ chosenCmapTables.append((format4, fontIdx))
122
+
123
+ if format14 is not None:
124
+ chosenUvsTables.append(format14)
125
+
126
+ # Build the unicode mapping
127
+ merger.cmap = cmap = {}
128
+ fontIndexForGlyph = {}
129
+ glyphSets = [None for f in merger.fonts] if hasattr(merger, "fonts") else None
130
+
131
+ for table, fontIdx in chosenCmapTables:
132
+ # handle duplicates
133
+ for uni, gid in table.cmap.items():
134
+ oldgid = cmap.get(uni, None)
135
+ if oldgid is None:
136
+ cmap[uni] = gid
137
+ fontIndexForGlyph[gid] = fontIdx
138
+ elif is_Default_Ignorable(uni) or uni in (0x25CC,): # U+25CC DOTTED CIRCLE
139
+ continue
140
+ elif oldgid != gid:
141
+ # Char previously mapped to oldgid, now to gid.
142
+ # Record, to fix up in GSUB 'locl' later.
143
+ if merger.duplicateGlyphsPerFont[fontIdx].get(oldgid) is None:
144
+ if glyphSets is not None:
145
+ oldFontIdx = fontIndexForGlyph[oldgid]
146
+ for idx in (fontIdx, oldFontIdx):
147
+ if glyphSets[idx] is None:
148
+ glyphSets[idx] = merger.fonts[idx].getGlyphSet()
149
+ # if _glyphsAreSame(glyphSets[oldFontIdx], glyphSets[fontIdx], oldgid, gid):
150
+ # continue
151
+ merger.duplicateGlyphsPerFont[fontIdx][oldgid] = gid
152
+ elif merger.duplicateGlyphsPerFont[fontIdx][oldgid] != gid:
153
+ # Char previously mapped to oldgid but oldgid is already remapped to a different
154
+ # gid, because of another Unicode character.
155
+ # TODO: Try harder to do something about these.
156
+ log.warning(
157
+ "Dropped mapping from codepoint %#06X to glyphId '%s'", uni, gid
158
+ )
159
+
160
+ merger.uvsDict = computeMegaUvs(merger, chosenUvsTables)
161
+
162
+
163
+ def renameCFFCharStrings(merger, glyphOrder, cffTable):
164
+ """Rename topDictIndex charStrings based on glyphOrder."""
165
+ td = cffTable.cff.topDictIndex[0]
166
+
167
+ charStrings = {}
168
+ for i, v in enumerate(td.CharStrings.charStrings.values()):
169
+ glyphName = glyphOrder[i]
170
+ charStrings[glyphName] = v
171
+ td.CharStrings.charStrings = charStrings
172
+
173
+ td.charset = list(glyphOrder)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/layout.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2013 Google, Inc. All Rights Reserved.
2
+ #
3
+ # Google Author(s): Behdad Esfahbod, Roozbeh Pournader
4
+
5
+ from fontTools import ttLib
6
+ from fontTools.ttLib.tables.DefaultTable import DefaultTable
7
+ from fontTools.ttLib.tables import otTables
8
+ from fontTools.merge.base import add_method, mergeObjects
9
+ from fontTools.merge.util import *
10
+ import logging
11
+
12
+
13
+ log = logging.getLogger("fontTools.merge")
14
+
15
+
16
+ def mergeLookupLists(lst):
17
+ # TODO Do smarter merge.
18
+ return sumLists(lst)
19
+
20
+
21
+ def mergeFeatures(lst):
22
+ assert lst
23
+ self = otTables.Feature()
24
+ self.FeatureParams = None
25
+ self.LookupListIndex = mergeLookupLists(
26
+ [l.LookupListIndex for l in lst if l.LookupListIndex]
27
+ )
28
+ self.LookupCount = len(self.LookupListIndex)
29
+ return self
30
+
31
+
32
+ def mergeFeatureLists(lst):
33
+ d = {}
34
+ for l in lst:
35
+ for f in l:
36
+ tag = f.FeatureTag
37
+ if tag not in d:
38
+ d[tag] = []
39
+ d[tag].append(f.Feature)
40
+ ret = []
41
+ for tag in sorted(d.keys()):
42
+ rec = otTables.FeatureRecord()
43
+ rec.FeatureTag = tag
44
+ rec.Feature = mergeFeatures(d[tag])
45
+ ret.append(rec)
46
+ return ret
47
+
48
+
49
+ def mergeLangSyses(lst):
50
+ assert lst
51
+
52
+ # TODO Support merging ReqFeatureIndex
53
+ assert all(l.ReqFeatureIndex == 0xFFFF for l in lst)
54
+
55
+ self = otTables.LangSys()
56
+ self.LookupOrder = None
57
+ self.ReqFeatureIndex = 0xFFFF
58
+ self.FeatureIndex = mergeFeatureLists(
59
+ [l.FeatureIndex for l in lst if l.FeatureIndex]
60
+ )
61
+ self.FeatureCount = len(self.FeatureIndex)
62
+ return self
63
+
64
+
65
+ def mergeScripts(lst):
66
+ assert lst
67
+
68
+ if len(lst) == 1:
69
+ return lst[0]
70
+ langSyses = {}
71
+ for sr in lst:
72
+ for lsr in sr.LangSysRecord:
73
+ if lsr.LangSysTag not in langSyses:
74
+ langSyses[lsr.LangSysTag] = []
75
+ langSyses[lsr.LangSysTag].append(lsr.LangSys)
76
+ lsrecords = []
77
+ for tag, langSys_list in sorted(langSyses.items()):
78
+ lsr = otTables.LangSysRecord()
79
+ lsr.LangSys = mergeLangSyses(langSys_list)
80
+ lsr.LangSysTag = tag
81
+ lsrecords.append(lsr)
82
+
83
+ self = otTables.Script()
84
+ self.LangSysRecord = lsrecords
85
+ self.LangSysCount = len(lsrecords)
86
+ dfltLangSyses = [s.DefaultLangSys for s in lst if s.DefaultLangSys]
87
+ if dfltLangSyses:
88
+ self.DefaultLangSys = mergeLangSyses(dfltLangSyses)
89
+ else:
90
+ self.DefaultLangSys = None
91
+ return self
92
+
93
+
94
+ def mergeScriptRecords(lst):
95
+ d = {}
96
+ for l in lst:
97
+ for s in l:
98
+ tag = s.ScriptTag
99
+ if tag not in d:
100
+ d[tag] = []
101
+ d[tag].append(s.Script)
102
+ ret = []
103
+ for tag in sorted(d.keys()):
104
+ rec = otTables.ScriptRecord()
105
+ rec.ScriptTag = tag
106
+ rec.Script = mergeScripts(d[tag])
107
+ ret.append(rec)
108
+ return ret
109
+
110
+
111
+ otTables.ScriptList.mergeMap = {
112
+ "ScriptCount": lambda lst: None, # TODO
113
+ "ScriptRecord": mergeScriptRecords,
114
+ }
115
+ otTables.BaseScriptList.mergeMap = {
116
+ "BaseScriptCount": lambda lst: None, # TODO
117
+ # TODO: Merge duplicate entries
118
+ "BaseScriptRecord": lambda lst: sorted(
119
+ sumLists(lst), key=lambda s: s.BaseScriptTag
120
+ ),
121
+ }
122
+
123
+ otTables.FeatureList.mergeMap = {
124
+ "FeatureCount": sum,
125
+ "FeatureRecord": lambda lst: sorted(sumLists(lst), key=lambda s: s.FeatureTag),
126
+ }
127
+
128
+ otTables.LookupList.mergeMap = {
129
+ "LookupCount": sum,
130
+ "Lookup": sumLists,
131
+ }
132
+
133
+ otTables.Coverage.mergeMap = {
134
+ "Format": min,
135
+ "glyphs": sumLists,
136
+ }
137
+
138
+ otTables.ClassDef.mergeMap = {
139
+ "Format": min,
140
+ "classDefs": sumDicts,
141
+ }
142
+
143
+ otTables.LigCaretList.mergeMap = {
144
+ "Coverage": mergeObjects,
145
+ "LigGlyphCount": sum,
146
+ "LigGlyph": sumLists,
147
+ }
148
+
149
+ otTables.AttachList.mergeMap = {
150
+ "Coverage": mergeObjects,
151
+ "GlyphCount": sum,
152
+ "AttachPoint": sumLists,
153
+ }
154
+
155
+ # XXX Renumber MarkFilterSets of lookups
156
+ otTables.MarkGlyphSetsDef.mergeMap = {
157
+ "MarkSetTableFormat": equal,
158
+ "MarkSetCount": sum,
159
+ "Coverage": sumLists,
160
+ }
161
+
162
+ otTables.Axis.mergeMap = {
163
+ "*": mergeObjects,
164
+ }
165
+
166
+ # XXX Fix BASE table merging
167
+ otTables.BaseTagList.mergeMap = {
168
+ "BaseTagCount": sum,
169
+ "BaselineTag": sumLists,
170
+ }
171
+
172
+ otTables.GDEF.mergeMap = otTables.GSUB.mergeMap = otTables.GPOS.mergeMap = (
173
+ otTables.BASE.mergeMap
174
+ ) = otTables.JSTF.mergeMap = otTables.MATH.mergeMap = {
175
+ "*": mergeObjects,
176
+ "Version": max,
177
+ }
178
+
179
+ ttLib.getTableClass("GDEF").mergeMap = ttLib.getTableClass("GSUB").mergeMap = (
180
+ ttLib.getTableClass("GPOS").mergeMap
181
+ ) = ttLib.getTableClass("BASE").mergeMap = ttLib.getTableClass(
182
+ "JSTF"
183
+ ).mergeMap = ttLib.getTableClass(
184
+ "MATH"
185
+ ).mergeMap = {
186
+ "tableTag": onlyExisting(equal), # XXX clean me up
187
+ "table": mergeObjects,
188
+ }
189
+
190
+
191
+ @add_method(ttLib.getTableClass("GSUB"))
192
+ def merge(self, m, tables):
193
+ assert len(tables) == len(m.duplicateGlyphsPerFont)
194
+ for i, (table, dups) in enumerate(zip(tables, m.duplicateGlyphsPerFont)):
195
+ if not dups:
196
+ continue
197
+ if table is None or table is NotImplemented:
198
+ log.warning(
199
+ "Have non-identical duplicates to resolve for '%s' but no GSUB. Are duplicates intended?: %s",
200
+ m.fonts[i]._merger__name,
201
+ dups,
202
+ )
203
+ continue
204
+
205
+ synthFeature = None
206
+ synthLookup = None
207
+ for script in table.table.ScriptList.ScriptRecord:
208
+ if script.ScriptTag == "DFLT":
209
+ continue # XXX
210
+ for langsys in [script.Script.DefaultLangSys] + [
211
+ l.LangSys for l in script.Script.LangSysRecord
212
+ ]:
213
+ if langsys is None:
214
+ continue # XXX Create!
215
+ feature = [v for v in langsys.FeatureIndex if v.FeatureTag == "locl"]
216
+ assert len(feature) <= 1
217
+ if feature:
218
+ feature = feature[0]
219
+ else:
220
+ if not synthFeature:
221
+ synthFeature = otTables.FeatureRecord()
222
+ synthFeature.FeatureTag = "locl"
223
+ f = synthFeature.Feature = otTables.Feature()
224
+ f.FeatureParams = None
225
+ f.LookupCount = 0
226
+ f.LookupListIndex = []
227
+ table.table.FeatureList.FeatureRecord.append(synthFeature)
228
+ table.table.FeatureList.FeatureCount += 1
229
+ feature = synthFeature
230
+ langsys.FeatureIndex.append(feature)
231
+ langsys.FeatureIndex.sort(key=lambda v: v.FeatureTag)
232
+
233
+ if not synthLookup:
234
+ subtable = otTables.SingleSubst()
235
+ subtable.mapping = dups
236
+ synthLookup = otTables.Lookup()
237
+ synthLookup.LookupFlag = 0
238
+ synthLookup.LookupType = 1
239
+ synthLookup.SubTableCount = 1
240
+ synthLookup.SubTable = [subtable]
241
+ if table.table.LookupList is None:
242
+ # mtiLib uses None as default value for LookupList,
243
+ # while feaLib points to an empty array with count 0
244
+ # TODO: make them do the same
245
+ table.table.LookupList = otTables.LookupList()
246
+ table.table.LookupList.Lookup = []
247
+ table.table.LookupList.LookupCount = 0
248
+ table.table.LookupList.Lookup.append(synthLookup)
249
+ table.table.LookupList.LookupCount += 1
250
+
251
+ if feature.Feature.LookupListIndex[:1] != [synthLookup]:
252
+ feature.Feature.LookupListIndex[:0] = [synthLookup]
253
+ feature.Feature.LookupCount += 1
254
+
255
+ DefaultTable.merge(self, m, tables)
256
+ return self
257
+
258
+
259
+ @add_method(
260
+ otTables.SingleSubst,
261
+ otTables.MultipleSubst,
262
+ otTables.AlternateSubst,
263
+ otTables.LigatureSubst,
264
+ otTables.ReverseChainSingleSubst,
265
+ otTables.SinglePos,
266
+ otTables.PairPos,
267
+ otTables.CursivePos,
268
+ otTables.MarkBasePos,
269
+ otTables.MarkLigPos,
270
+ otTables.MarkMarkPos,
271
+ )
272
+ def mapLookups(self, lookupMap):
273
+ pass
274
+
275
+
276
+ # Copied and trimmed down from subset.py
277
+ @add_method(
278
+ otTables.ContextSubst,
279
+ otTables.ChainContextSubst,
280
+ otTables.ContextPos,
281
+ otTables.ChainContextPos,
282
+ )
283
+ def __merge_classify_context(self):
284
+ class ContextHelper(object):
285
+ def __init__(self, klass, Format):
286
+ if klass.__name__.endswith("Subst"):
287
+ Typ = "Sub"
288
+ Type = "Subst"
289
+ else:
290
+ Typ = "Pos"
291
+ Type = "Pos"
292
+ if klass.__name__.startswith("Chain"):
293
+ Chain = "Chain"
294
+ else:
295
+ Chain = ""
296
+ ChainTyp = Chain + Typ
297
+
298
+ self.Typ = Typ
299
+ self.Type = Type
300
+ self.Chain = Chain
301
+ self.ChainTyp = ChainTyp
302
+
303
+ self.LookupRecord = Type + "LookupRecord"
304
+
305
+ if Format == 1:
306
+ self.Rule = ChainTyp + "Rule"
307
+ self.RuleSet = ChainTyp + "RuleSet"
308
+ elif Format == 2:
309
+ self.Rule = ChainTyp + "ClassRule"
310
+ self.RuleSet = ChainTyp + "ClassSet"
311
+
312
+ if self.Format not in [1, 2, 3]:
313
+ return None # Don't shoot the messenger; let it go
314
+ if not hasattr(self.__class__, "_merge__ContextHelpers"):
315
+ self.__class__._merge__ContextHelpers = {}
316
+ if self.Format not in self.__class__._merge__ContextHelpers:
317
+ helper = ContextHelper(self.__class__, self.Format)
318
+ self.__class__._merge__ContextHelpers[self.Format] = helper
319
+ return self.__class__._merge__ContextHelpers[self.Format]
320
+
321
+
322
+ @add_method(
323
+ otTables.ContextSubst,
324
+ otTables.ChainContextSubst,
325
+ otTables.ContextPos,
326
+ otTables.ChainContextPos,
327
+ )
328
+ def mapLookups(self, lookupMap):
329
+ c = self.__merge_classify_context()
330
+
331
+ if self.Format in [1, 2]:
332
+ for rs in getattr(self, c.RuleSet):
333
+ if not rs:
334
+ continue
335
+ for r in getattr(rs, c.Rule):
336
+ if not r:
337
+ continue
338
+ for ll in getattr(r, c.LookupRecord):
339
+ if not ll:
340
+ continue
341
+ ll.LookupListIndex = lookupMap[ll.LookupListIndex]
342
+ elif self.Format == 3:
343
+ for ll in getattr(self, c.LookupRecord):
344
+ if not ll:
345
+ continue
346
+ ll.LookupListIndex = lookupMap[ll.LookupListIndex]
347
+ else:
348
+ assert 0, "unknown format: %s" % self.Format
349
+
350
+
351
+ @add_method(otTables.ExtensionSubst, otTables.ExtensionPos)
352
+ def mapLookups(self, lookupMap):
353
+ if self.Format == 1:
354
+ self.ExtSubTable.mapLookups(lookupMap)
355
+ else:
356
+ assert 0, "unknown format: %s" % self.Format
357
+
358
+
359
+ @add_method(otTables.Lookup)
360
+ def mapLookups(self, lookupMap):
361
+ for st in self.SubTable:
362
+ if not st:
363
+ continue
364
+ st.mapLookups(lookupMap)
365
+
366
+
367
+ @add_method(otTables.LookupList)
368
+ def mapLookups(self, lookupMap):
369
+ for l in self.Lookup:
370
+ if not l:
371
+ continue
372
+ l.mapLookups(lookupMap)
373
+
374
+
375
+ @add_method(otTables.Lookup)
376
+ def mapMarkFilteringSets(self, markFilteringSetMap):
377
+ if self.LookupFlag & 0x0010:
378
+ self.MarkFilteringSet = markFilteringSetMap[self.MarkFilteringSet]
379
+
380
+
381
+ @add_method(otTables.LookupList)
382
+ def mapMarkFilteringSets(self, markFilteringSetMap):
383
+ for l in self.Lookup:
384
+ if not l:
385
+ continue
386
+ l.mapMarkFilteringSets(markFilteringSetMap)
387
+
388
+
389
+ @add_method(otTables.Feature)
390
+ def mapLookups(self, lookupMap):
391
+ self.LookupListIndex = [lookupMap[i] for i in self.LookupListIndex]
392
+
393
+
394
+ @add_method(otTables.FeatureList)
395
+ def mapLookups(self, lookupMap):
396
+ for f in self.FeatureRecord:
397
+ if not f or not f.Feature:
398
+ continue
399
+ f.Feature.mapLookups(lookupMap)
400
+
401
+
402
+ @add_method(otTables.DefaultLangSys, otTables.LangSys)
403
+ def mapFeatures(self, featureMap):
404
+ self.FeatureIndex = [featureMap[i] for i in self.FeatureIndex]
405
+ if self.ReqFeatureIndex != 65535:
406
+ self.ReqFeatureIndex = featureMap[self.ReqFeatureIndex]
407
+
408
+
409
+ @add_method(otTables.Script)
410
+ def mapFeatures(self, featureMap):
411
+ if self.DefaultLangSys:
412
+ self.DefaultLangSys.mapFeatures(featureMap)
413
+ for l in self.LangSysRecord:
414
+ if not l or not l.LangSys:
415
+ continue
416
+ l.LangSys.mapFeatures(featureMap)
417
+
418
+
419
+ @add_method(otTables.ScriptList)
420
+ def mapFeatures(self, featureMap):
421
+ for s in self.ScriptRecord:
422
+ if not s or not s.Script:
423
+ continue
424
+ s.Script.mapFeatures(featureMap)
425
+
426
+
427
+ def layoutPreMerge(font):
428
+ # Map indices to references
429
+
430
+ GDEF = font.get("GDEF")
431
+ GSUB = font.get("GSUB")
432
+ GPOS = font.get("GPOS")
433
+
434
+ for t in [GSUB, GPOS]:
435
+ if not t:
436
+ continue
437
+
438
+ if t.table.LookupList:
439
+ lookupMap = {i: v for i, v in enumerate(t.table.LookupList.Lookup)}
440
+ t.table.LookupList.mapLookups(lookupMap)
441
+ t.table.FeatureList.mapLookups(lookupMap)
442
+
443
+ if (
444
+ GDEF
445
+ and GDEF.table.Version >= 0x00010002
446
+ and GDEF.table.MarkGlyphSetsDef
447
+ ):
448
+ markFilteringSetMap = {
449
+ i: v for i, v in enumerate(GDEF.table.MarkGlyphSetsDef.Coverage)
450
+ }
451
+ t.table.LookupList.mapMarkFilteringSets(markFilteringSetMap)
452
+
453
+ if t.table.FeatureList and t.table.ScriptList:
454
+ featureMap = {i: v for i, v in enumerate(t.table.FeatureList.FeatureRecord)}
455
+ t.table.ScriptList.mapFeatures(featureMap)
456
+
457
+ # TODO FeatureParams nameIDs
458
+
459
+
460
+ def layoutPostMerge(font):
461
+ # Map references back to indices
462
+
463
+ GDEF = font.get("GDEF")
464
+ GSUB = font.get("GSUB")
465
+ GPOS = font.get("GPOS")
466
+
467
+ for t in [GSUB, GPOS]:
468
+ if not t:
469
+ continue
470
+
471
+ if t.table.FeatureList and t.table.ScriptList:
472
+ # Collect unregistered (new) features.
473
+ featureMap = GregariousIdentityDict(t.table.FeatureList.FeatureRecord)
474
+ t.table.ScriptList.mapFeatures(featureMap)
475
+
476
+ # Record used features.
477
+ featureMap = AttendanceRecordingIdentityDict(
478
+ t.table.FeatureList.FeatureRecord
479
+ )
480
+ t.table.ScriptList.mapFeatures(featureMap)
481
+ usedIndices = featureMap.s
482
+
483
+ # Remove unused features
484
+ t.table.FeatureList.FeatureRecord = [
485
+ f
486
+ for i, f in enumerate(t.table.FeatureList.FeatureRecord)
487
+ if i in usedIndices
488
+ ]
489
+
490
+ # Map back to indices.
491
+ featureMap = NonhashableDict(t.table.FeatureList.FeatureRecord)
492
+ t.table.ScriptList.mapFeatures(featureMap)
493
+
494
+ t.table.FeatureList.FeatureCount = len(t.table.FeatureList.FeatureRecord)
495
+
496
+ if t.table.LookupList:
497
+ # Collect unregistered (new) lookups.
498
+ lookupMap = GregariousIdentityDict(t.table.LookupList.Lookup)
499
+ t.table.FeatureList.mapLookups(lookupMap)
500
+ t.table.LookupList.mapLookups(lookupMap)
501
+
502
+ # Record used lookups.
503
+ lookupMap = AttendanceRecordingIdentityDict(t.table.LookupList.Lookup)
504
+ t.table.FeatureList.mapLookups(lookupMap)
505
+ t.table.LookupList.mapLookups(lookupMap)
506
+ usedIndices = lookupMap.s
507
+
508
+ # Remove unused lookups
509
+ t.table.LookupList.Lookup = [
510
+ l for i, l in enumerate(t.table.LookupList.Lookup) if i in usedIndices
511
+ ]
512
+
513
+ # Map back to indices.
514
+ lookupMap = NonhashableDict(t.table.LookupList.Lookup)
515
+ t.table.FeatureList.mapLookups(lookupMap)
516
+ t.table.LookupList.mapLookups(lookupMap)
517
+
518
+ t.table.LookupList.LookupCount = len(t.table.LookupList.Lookup)
519
+
520
+ if GDEF and GDEF.table.Version >= 0x00010002:
521
+ markFilteringSetMap = NonhashableDict(
522
+ GDEF.table.MarkGlyphSetsDef.Coverage
523
+ )
524
+ t.table.LookupList.mapMarkFilteringSets(markFilteringSetMap)
525
+
526
+ # TODO FeatureParams nameIDs
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/options.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2013 Google, Inc. All Rights Reserved.
2
+ #
3
+ # Google Author(s): Behdad Esfahbod, Roozbeh Pournader
4
+
5
+
6
+ class Options(object):
7
+ class UnknownOptionError(Exception):
8
+ pass
9
+
10
+ def __init__(self, **kwargs):
11
+ self.verbose = False
12
+ self.timing = False
13
+ self.drop_tables = []
14
+ self.input_file = None
15
+ self.output_file = "merged.ttf"
16
+ self.import_file = None
17
+
18
+ self.set(**kwargs)
19
+
20
+ def set(self, **kwargs):
21
+ for k, v in kwargs.items():
22
+ if not hasattr(self, k):
23
+ raise self.UnknownOptionError("Unknown option '%s'" % k)
24
+ setattr(self, k, v)
25
+
26
+ def parse_opts(self, argv, ignore_unknown=[]):
27
+ ret = []
28
+ opts = {}
29
+ for a in argv:
30
+ orig_a = a
31
+ if not a.startswith("--"):
32
+ ret.append(a)
33
+ continue
34
+ a = a[2:]
35
+ i = a.find("=")
36
+ op = "="
37
+ if i == -1:
38
+ if a.startswith("no-"):
39
+ k = a[3:]
40
+ v = False
41
+ else:
42
+ k = a
43
+ v = True
44
+ else:
45
+ k = a[:i]
46
+ if k[-1] in "-+":
47
+ op = k[-1] + "=" # Ops is '-=' or '+=' now.
48
+ k = k[:-1]
49
+ v = a[i + 1 :]
50
+ ok = k
51
+ k = k.replace("-", "_")
52
+ if not hasattr(self, k):
53
+ if ignore_unknown is True or ok in ignore_unknown:
54
+ ret.append(orig_a)
55
+ continue
56
+ else:
57
+ raise self.UnknownOptionError("Unknown option '%s'" % a)
58
+
59
+ ov = getattr(self, k)
60
+ if isinstance(ov, bool):
61
+ v = bool(v)
62
+ elif isinstance(ov, int):
63
+ v = int(v)
64
+ elif isinstance(ov, list):
65
+ vv = v.split(",")
66
+ if vv == [""]:
67
+ vv = []
68
+ vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv]
69
+ if op == "=":
70
+ v = vv
71
+ elif op == "+=":
72
+ v = ov
73
+ v.extend(vv)
74
+ elif op == "-=":
75
+ v = ov
76
+ for x in vv:
77
+ if x in v:
78
+ v.remove(x)
79
+ else:
80
+ assert 0
81
+
82
+ opts[k] = v
83
+ self.set(**opts)
84
+
85
+ return ret
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/tables.py ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2013 Google, Inc. All Rights Reserved.
2
+ #
3
+ # Google Author(s): Behdad Esfahbod, Roozbeh Pournader
4
+
5
+ from fontTools import ttLib, cffLib
6
+ from fontTools.misc.psCharStrings import T2WidthExtractor
7
+ from fontTools.ttLib.tables.DefaultTable import DefaultTable
8
+ from fontTools.merge.base import add_method, mergeObjects
9
+ from fontTools.merge.cmap import computeMegaCmap
10
+ from fontTools.merge.util import *
11
+ import logging
12
+
13
+
14
+ log = logging.getLogger("fontTools.merge")
15
+
16
+
17
+ ttLib.getTableClass("maxp").mergeMap = {
18
+ "*": max,
19
+ "tableTag": equal,
20
+ "tableVersion": equal,
21
+ "numGlyphs": sum,
22
+ "maxStorage": first,
23
+ "maxFunctionDefs": first,
24
+ "maxInstructionDefs": first,
25
+ # TODO When we correctly merge hinting data, update these values:
26
+ # maxFunctionDefs, maxInstructionDefs, maxSizeOfInstructions
27
+ }
28
+
29
+ headFlagsMergeBitMap = {
30
+ "size": 16,
31
+ "*": bitwise_or,
32
+ 1: bitwise_and, # Baseline at y = 0
33
+ 2: bitwise_and, # lsb at x = 0
34
+ 3: bitwise_and, # Force ppem to integer values. FIXME?
35
+ 5: bitwise_and, # Font is vertical
36
+ 6: lambda bit: 0, # Always set to zero
37
+ 11: bitwise_and, # Font data is 'lossless'
38
+ 13: bitwise_and, # Optimized for ClearType
39
+ 14: bitwise_and, # Last resort font. FIXME? equal or first may be better
40
+ 15: lambda bit: 0, # Always set to zero
41
+ }
42
+
43
+ ttLib.getTableClass("head").mergeMap = {
44
+ "tableTag": equal,
45
+ "tableVersion": max,
46
+ "fontRevision": max,
47
+ "checkSumAdjustment": lambda lst: 0, # We need *something* here
48
+ "magicNumber": equal,
49
+ "flags": mergeBits(headFlagsMergeBitMap),
50
+ "unitsPerEm": equal,
51
+ "created": current_time,
52
+ "modified": current_time,
53
+ "xMin": min,
54
+ "yMin": min,
55
+ "xMax": max,
56
+ "yMax": max,
57
+ "macStyle": first,
58
+ "lowestRecPPEM": max,
59
+ "fontDirectionHint": lambda lst: 2,
60
+ "indexToLocFormat": first,
61
+ "glyphDataFormat": equal,
62
+ }
63
+
64
+ ttLib.getTableClass("hhea").mergeMap = {
65
+ "*": equal,
66
+ "tableTag": equal,
67
+ "tableVersion": max,
68
+ "ascent": max,
69
+ "descent": min,
70
+ "lineGap": max,
71
+ "advanceWidthMax": max,
72
+ "minLeftSideBearing": min,
73
+ "minRightSideBearing": min,
74
+ "xMaxExtent": max,
75
+ "caretSlopeRise": first,
76
+ "caretSlopeRun": first,
77
+ "caretOffset": first,
78
+ "numberOfHMetrics": recalculate,
79
+ }
80
+
81
+ ttLib.getTableClass("vhea").mergeMap = {
82
+ "*": equal,
83
+ "tableTag": equal,
84
+ "tableVersion": max,
85
+ "ascent": max,
86
+ "descent": min,
87
+ "lineGap": max,
88
+ "advanceHeightMax": max,
89
+ "minTopSideBearing": min,
90
+ "minBottomSideBearing": min,
91
+ "yMaxExtent": max,
92
+ "caretSlopeRise": first,
93
+ "caretSlopeRun": first,
94
+ "caretOffset": first,
95
+ "numberOfVMetrics": recalculate,
96
+ }
97
+
98
+ os2FsTypeMergeBitMap = {
99
+ "size": 16,
100
+ "*": lambda bit: 0,
101
+ 1: bitwise_or, # no embedding permitted
102
+ 2: bitwise_and, # allow previewing and printing documents
103
+ 3: bitwise_and, # allow editing documents
104
+ 8: bitwise_or, # no subsetting permitted
105
+ 9: bitwise_or, # no embedding of outlines permitted
106
+ }
107
+
108
+
109
+ def mergeOs2FsType(lst):
110
+ lst = list(lst)
111
+ if all(item == 0 for item in lst):
112
+ return 0
113
+
114
+ # Compute least restrictive logic for each fsType value
115
+ for i in range(len(lst)):
116
+ # unset bit 1 (no embedding permitted) if either bit 2 or 3 is set
117
+ if lst[i] & 0x000C:
118
+ lst[i] &= ~0x0002
119
+ # set bit 2 (allow previewing) if bit 3 is set (allow editing)
120
+ elif lst[i] & 0x0008:
121
+ lst[i] |= 0x0004
122
+ # set bits 2 and 3 if everything is allowed
123
+ elif lst[i] == 0:
124
+ lst[i] = 0x000C
125
+
126
+ fsType = mergeBits(os2FsTypeMergeBitMap)(lst)
127
+ # unset bits 2 and 3 if bit 1 is set (some font is "no embedding")
128
+ if fsType & 0x0002:
129
+ fsType &= ~0x000C
130
+ return fsType
131
+
132
+
133
+ ttLib.getTableClass("OS/2").mergeMap = {
134
+ "*": first,
135
+ "tableTag": equal,
136
+ "version": max,
137
+ "xAvgCharWidth": first, # Will be recalculated at the end on the merged font
138
+ "fsType": mergeOs2FsType, # Will be overwritten
139
+ "panose": first, # FIXME: should really be the first Latin font
140
+ "ulUnicodeRange1": bitwise_or,
141
+ "ulUnicodeRange2": bitwise_or,
142
+ "ulUnicodeRange3": bitwise_or,
143
+ "ulUnicodeRange4": bitwise_or,
144
+ "fsFirstCharIndex": min,
145
+ "fsLastCharIndex": max,
146
+ "sTypoAscender": max,
147
+ "sTypoDescender": min,
148
+ "sTypoLineGap": max,
149
+ "usWinAscent": max,
150
+ "usWinDescent": max,
151
+ # Version 1
152
+ "ulCodePageRange1": onlyExisting(bitwise_or),
153
+ "ulCodePageRange2": onlyExisting(bitwise_or),
154
+ # Version 2, 3, 4
155
+ "sxHeight": onlyExisting(max),
156
+ "sCapHeight": onlyExisting(max),
157
+ "usDefaultChar": onlyExisting(first),
158
+ "usBreakChar": onlyExisting(first),
159
+ "usMaxContext": onlyExisting(max),
160
+ # version 5
161
+ "usLowerOpticalPointSize": onlyExisting(min),
162
+ "usUpperOpticalPointSize": onlyExisting(max),
163
+ }
164
+
165
+
166
+ @add_method(ttLib.getTableClass("OS/2"))
167
+ def merge(self, m, tables):
168
+ DefaultTable.merge(self, m, tables)
169
+ if self.version < 2:
170
+ # bits 8 and 9 are reserved and should be set to zero
171
+ self.fsType &= ~0x0300
172
+ if self.version >= 3:
173
+ # Only one of bits 1, 2, and 3 may be set. We already take
174
+ # care of bit 1 implications in mergeOs2FsType. So unset
175
+ # bit 2 if bit 3 is already set.
176
+ if self.fsType & 0x0008:
177
+ self.fsType &= ~0x0004
178
+ return self
179
+
180
+
181
+ ttLib.getTableClass("post").mergeMap = {
182
+ "*": first,
183
+ "tableTag": equal,
184
+ "formatType": max,
185
+ "isFixedPitch": min,
186
+ "minMemType42": max,
187
+ "maxMemType42": lambda lst: 0,
188
+ "minMemType1": max,
189
+ "maxMemType1": lambda lst: 0,
190
+ "mapping": onlyExisting(sumDicts),
191
+ "extraNames": lambda lst: [],
192
+ }
193
+
194
+ ttLib.getTableClass("vmtx").mergeMap = ttLib.getTableClass("hmtx").mergeMap = {
195
+ "tableTag": equal,
196
+ "metrics": sumDicts,
197
+ }
198
+
199
+ ttLib.getTableClass("name").mergeMap = {
200
+ "tableTag": equal,
201
+ "names": first, # FIXME? Does mixing name records make sense?
202
+ }
203
+
204
+ ttLib.getTableClass("loca").mergeMap = {
205
+ "*": recalculate,
206
+ "tableTag": equal,
207
+ }
208
+
209
+ ttLib.getTableClass("glyf").mergeMap = {
210
+ "tableTag": equal,
211
+ "glyphs": sumDicts,
212
+ "glyphOrder": sumLists,
213
+ "_reverseGlyphOrder": recalculate,
214
+ "axisTags": equal,
215
+ }
216
+
217
+
218
+ @add_method(ttLib.getTableClass("glyf"))
219
+ def merge(self, m, tables):
220
+ for i, table in enumerate(tables):
221
+ for g in table.glyphs.values():
222
+ if i:
223
+ # Drop hints for all but first font, since
224
+ # we don't map functions / CVT values.
225
+ g.removeHinting()
226
+ # Expand composite glyphs to load their
227
+ # composite glyph names.
228
+ if g.isComposite():
229
+ g.expand(table)
230
+ return DefaultTable.merge(self, m, tables)
231
+
232
+
233
+ ttLib.getTableClass("prep").mergeMap = lambda self, lst: first(lst)
234
+ ttLib.getTableClass("fpgm").mergeMap = lambda self, lst: first(lst)
235
+ ttLib.getTableClass("cvt ").mergeMap = lambda self, lst: first(lst)
236
+ ttLib.getTableClass("gasp").mergeMap = lambda self, lst: first(
237
+ lst
238
+ ) # FIXME? Appears irreconcilable
239
+
240
+
241
+ @add_method(ttLib.getTableClass("CFF "))
242
+ def merge(self, m, tables):
243
+ if any(hasattr(table.cff[0], "FDSelect") for table in tables):
244
+ raise NotImplementedError("Merging CID-keyed CFF tables is not supported yet")
245
+
246
+ for table in tables:
247
+ table.cff.desubroutinize()
248
+
249
+ newcff = tables[0]
250
+ newfont = newcff.cff[0]
251
+ private = newfont.Private
252
+ newDefaultWidthX, newNominalWidthX = private.defaultWidthX, private.nominalWidthX
253
+ storedNamesStrings = []
254
+ glyphOrderStrings = []
255
+ glyphOrder = set(newfont.getGlyphOrder())
256
+
257
+ for name in newfont.strings.strings:
258
+ if name not in glyphOrder:
259
+ storedNamesStrings.append(name)
260
+ else:
261
+ glyphOrderStrings.append(name)
262
+
263
+ chrset = list(newfont.charset)
264
+ newcs = newfont.CharStrings
265
+ log.debug("FONT 0 CharStrings: %d.", len(newcs))
266
+
267
+ for i, table in enumerate(tables[1:], start=1):
268
+ font = table.cff[0]
269
+ defaultWidthX, nominalWidthX = (
270
+ font.Private.defaultWidthX,
271
+ font.Private.nominalWidthX,
272
+ )
273
+ widthsDiffer = (
274
+ defaultWidthX != newDefaultWidthX or nominalWidthX != newNominalWidthX
275
+ )
276
+ font.Private = private
277
+ fontGlyphOrder = set(font.getGlyphOrder())
278
+ for name in font.strings.strings:
279
+ if name in fontGlyphOrder:
280
+ glyphOrderStrings.append(name)
281
+ cs = font.CharStrings
282
+ gs = table.cff.GlobalSubrs
283
+ log.debug("Font %d CharStrings: %d.", i, len(cs))
284
+ chrset.extend(font.charset)
285
+ if newcs.charStringsAreIndexed:
286
+ for i, name in enumerate(cs.charStrings, start=len(newcs)):
287
+ newcs.charStrings[name] = i
288
+ newcs.charStringsIndex.items.append(None)
289
+ for name in cs.charStrings:
290
+ if widthsDiffer:
291
+ c = cs[name]
292
+ defaultWidthXToken = object()
293
+ extractor = T2WidthExtractor([], [], nominalWidthX, defaultWidthXToken)
294
+ extractor.execute(c)
295
+ width = extractor.width
296
+ if width is not defaultWidthXToken:
297
+ # The following will be wrong if the width is added
298
+ # by a subroutine. Ouch!
299
+ c.program.pop(0)
300
+ else:
301
+ width = defaultWidthX
302
+ if width != newDefaultWidthX:
303
+ c.program.insert(0, width - newNominalWidthX)
304
+ newcs[name] = cs[name]
305
+
306
+ newfont.charset = chrset
307
+ newfont.numGlyphs = len(chrset)
308
+ newfont.strings.strings = glyphOrderStrings + storedNamesStrings
309
+
310
+ return newcff
311
+
312
+
313
+ @add_method(ttLib.getTableClass("cmap"))
314
+ def merge(self, m, tables):
315
+ if not hasattr(m, "cmap"):
316
+ computeMegaCmap(m, tables)
317
+ cmap = m.cmap
318
+
319
+ cmapBmpOnly = {uni: gid for uni, gid in cmap.items() if uni <= 0xFFFF}
320
+ self.tables = []
321
+ module = ttLib.getTableModule("cmap")
322
+ if len(cmapBmpOnly) != len(cmap):
323
+ # format-12 required.
324
+ cmapTable = module.cmap_classes[12](12)
325
+ cmapTable.platformID = 3
326
+ cmapTable.platEncID = 10
327
+ cmapTable.language = 0
328
+ cmapTable.cmap = cmap
329
+ self.tables.append(cmapTable)
330
+ # always create format-4
331
+ cmapTable = module.cmap_classes[4](4)
332
+ cmapTable.platformID = 3
333
+ cmapTable.platEncID = 1
334
+ cmapTable.language = 0
335
+ cmapTable.cmap = cmapBmpOnly
336
+ # ordered by platform then encoding
337
+ self.tables.insert(0, cmapTable)
338
+
339
+ uvsDict = m.uvsDict
340
+ if uvsDict:
341
+ # format-14
342
+ uvsTable = module.cmap_classes[14](14)
343
+ uvsTable.platformID = 0
344
+ uvsTable.platEncID = 5
345
+ uvsTable.language = 0
346
+ uvsTable.cmap = {}
347
+ uvsTable.uvsDict = uvsDict
348
+ # ordered by platform then encoding
349
+ self.tables.insert(0, uvsTable)
350
+ self.tableVersion = 0
351
+ self.numSubTables = len(self.tables)
352
+ return self
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/unicode.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Behdad Esfahbod. All Rights Reserved.
2
+
3
+
4
+ def is_Default_Ignorable(u):
5
+ # http://www.unicode.org/reports/tr44/#Default_Ignorable_Code_Point
6
+ #
7
+ # TODO Move me to unicodedata module and autogenerate.
8
+ #
9
+ # Unicode 14.0:
10
+ # $ grep '; Default_Ignorable_Code_Point ' DerivedCoreProperties.txt | sed 's/;.*#/#/'
11
+ # 00AD # Cf SOFT HYPHEN
12
+ # 034F # Mn COMBINING GRAPHEME JOINER
13
+ # 061C # Cf ARABIC LETTER MARK
14
+ # 115F..1160 # Lo [2] HANGUL CHOSEONG FILLER..HANGUL JUNGSEONG FILLER
15
+ # 17B4..17B5 # Mn [2] KHMER VOWEL INHERENT AQ..KHMER VOWEL INHERENT AA
16
+ # 180B..180D # Mn [3] MONGOLIAN FREE VARIATION SELECTOR ONE..MONGOLIAN FREE VARIATION SELECTOR THREE
17
+ # 180E # Cf MONGOLIAN VOWEL SEPARATOR
18
+ # 180F # Mn MONGOLIAN FREE VARIATION SELECTOR FOUR
19
+ # 200B..200F # Cf [5] ZERO WIDTH SPACE..RIGHT-TO-LEFT MARK
20
+ # 202A..202E # Cf [5] LEFT-TO-RIGHT EMBEDDING..RIGHT-TO-LEFT OVERRIDE
21
+ # 2060..2064 # Cf [5] WORD JOINER..INVISIBLE PLUS
22
+ # 2065 # Cn <reserved-2065>
23
+ # 2066..206F # Cf [10] LEFT-TO-RIGHT ISOLATE..NOMINAL DIGIT SHAPES
24
+ # 3164 # Lo HANGUL FILLER
25
+ # FE00..FE0F # Mn [16] VARIATION SELECTOR-1..VARIATION SELECTOR-16
26
+ # FEFF # Cf ZERO WIDTH NO-BREAK SPACE
27
+ # FFA0 # Lo HALFWIDTH HANGUL FILLER
28
+ # FFF0..FFF8 # Cn [9] <reserved-FFF0>..<reserved-FFF8>
29
+ # 1BCA0..1BCA3 # Cf [4] SHORTHAND FORMAT LETTER OVERLAP..SHORTHAND FORMAT UP STEP
30
+ # 1D173..1D17A # Cf [8] MUSICAL SYMBOL BEGIN BEAM..MUSICAL SYMBOL END PHRASE
31
+ # E0000 # Cn <reserved-E0000>
32
+ # E0001 # Cf LANGUAGE TAG
33
+ # E0002..E001F # Cn [30] <reserved-E0002>..<reserved-E001F>
34
+ # E0020..E007F # Cf [96] TAG SPACE..CANCEL TAG
35
+ # E0080..E00FF # Cn [128] <reserved-E0080>..<reserved-E00FF>
36
+ # E0100..E01EF # Mn [240] VARIATION SELECTOR-17..VARIATION SELECTOR-256
37
+ # E01F0..E0FFF # Cn [3600] <reserved-E01F0>..<reserved-E0FFF>
38
+ return (
39
+ u == 0x00AD
40
+ or u == 0x034F # Cf SOFT HYPHEN
41
+ or u == 0x061C # Mn COMBINING GRAPHEME JOINER
42
+ or 0x115F <= u <= 0x1160 # Cf ARABIC LETTER MARK
43
+ or 0x17B4 # Lo [2] HANGUL CHOSEONG FILLER..HANGUL JUNGSEONG FILLER
44
+ <= u
45
+ <= 0x17B5
46
+ or 0x180B # Mn [2] KHMER VOWEL INHERENT AQ..KHMER VOWEL INHERENT AA
47
+ <= u
48
+ <= 0x180D
49
+ or u # Mn [3] MONGOLIAN FREE VARIATION SELECTOR ONE..MONGOLIAN FREE VARIATION SELECTOR THREE
50
+ == 0x180E
51
+ or u == 0x180F # Cf MONGOLIAN VOWEL SEPARATOR
52
+ or 0x200B <= u <= 0x200F # Mn MONGOLIAN FREE VARIATION SELECTOR FOUR
53
+ or 0x202A <= u <= 0x202E # Cf [5] ZERO WIDTH SPACE..RIGHT-TO-LEFT MARK
54
+ or 0x2060 # Cf [5] LEFT-TO-RIGHT EMBEDDING..RIGHT-TO-LEFT OVERRIDE
55
+ <= u
56
+ <= 0x2064
57
+ or u == 0x2065 # Cf [5] WORD JOINER..INVISIBLE PLUS
58
+ or 0x2066 <= u <= 0x206F # Cn <reserved-2065>
59
+ or u == 0x3164 # Cf [10] LEFT-TO-RIGHT ISOLATE..NOMINAL DIGIT SHAPES
60
+ or 0xFE00 <= u <= 0xFE0F # Lo HANGUL FILLER
61
+ or u == 0xFEFF # Mn [16] VARIATION SELECTOR-1..VARIATION SELECTOR-16
62
+ or u == 0xFFA0 # Cf ZERO WIDTH NO-BREAK SPACE
63
+ or 0xFFF0 <= u <= 0xFFF8 # Lo HALFWIDTH HANGUL FILLER
64
+ or 0x1BCA0 <= u <= 0x1BCA3 # Cn [9] <reserved-FFF0>..<reserved-FFF8>
65
+ or 0x1D173 # Cf [4] SHORTHAND FORMAT LETTER OVERLAP..SHORTHAND FORMAT UP STEP
66
+ <= u
67
+ <= 0x1D17A
68
+ or u == 0xE0000 # Cf [8] MUSICAL SYMBOL BEGIN BEAM..MUSICAL SYMBOL END PHRASE
69
+ or u == 0xE0001 # Cn <reserved-E0000>
70
+ or 0xE0002 <= u <= 0xE001F # Cf LANGUAGE TAG
71
+ or 0xE0020 <= u <= 0xE007F # Cn [30] <reserved-E0002>..<reserved-E001F>
72
+ or 0xE0080 <= u <= 0xE00FF # Cf [96] TAG SPACE..CANCEL TAG
73
+ or 0xE0100 <= u <= 0xE01EF # Cn [128] <reserved-E0080>..<reserved-E00FF>
74
+ or 0xE01F0 # Mn [240] VARIATION SELECTOR-17..VARIATION SELECTOR-256
75
+ <= u
76
+ <= 0xE0FFF
77
+ or False # Cn [3600] <reserved-E01F0>..<reserved-E0FFF>
78
+ )
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/merge/util.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2013 Google, Inc. All Rights Reserved.
2
+ #
3
+ # Google Author(s): Behdad Esfahbod, Roozbeh Pournader
4
+
5
+ from fontTools.misc.timeTools import timestampNow
6
+ from fontTools.ttLib.tables.DefaultTable import DefaultTable
7
+ from functools import reduce
8
+ import operator
9
+ import logging
10
+
11
+
12
+ log = logging.getLogger("fontTools.merge")
13
+
14
+
15
+ # General utility functions for merging values from different fonts
16
+
17
+
18
+ def equal(lst):
19
+ lst = list(lst)
20
+ t = iter(lst)
21
+ first = next(t)
22
+ assert all(item == first for item in t), "Expected all items to be equal: %s" % lst
23
+ return first
24
+
25
+
26
+ def first(lst):
27
+ return next(iter(lst))
28
+
29
+
30
+ def recalculate(lst):
31
+ return NotImplemented
32
+
33
+
34
+ def current_time(lst):
35
+ return timestampNow()
36
+
37
+
38
+ def bitwise_and(lst):
39
+ return reduce(operator.and_, lst)
40
+
41
+
42
+ def bitwise_or(lst):
43
+ return reduce(operator.or_, lst)
44
+
45
+
46
+ def avg_int(lst):
47
+ lst = list(lst)
48
+ return sum(lst) // len(lst)
49
+
50
+
51
+ def onlyExisting(func):
52
+ """Returns a filter func that when called with a list,
53
+ only calls func on the non-NotImplemented items of the list,
54
+ and only so if there's at least one item remaining.
55
+ Otherwise returns NotImplemented."""
56
+
57
+ def wrapper(lst):
58
+ items = [item for item in lst if item is not NotImplemented]
59
+ return func(items) if items else NotImplemented
60
+
61
+ return wrapper
62
+
63
+
64
+ def sumLists(lst):
65
+ l = []
66
+ for item in lst:
67
+ l.extend(item)
68
+ return l
69
+
70
+
71
+ def sumDicts(lst):
72
+ d = {}
73
+ for item in lst:
74
+ d.update(item)
75
+ return d
76
+
77
+
78
+ def mergeBits(bitmap):
79
+ def wrapper(lst):
80
+ lst = list(lst)
81
+ returnValue = 0
82
+ for bitNumber in range(bitmap["size"]):
83
+ try:
84
+ mergeLogic = bitmap[bitNumber]
85
+ except KeyError:
86
+ try:
87
+ mergeLogic = bitmap["*"]
88
+ except KeyError:
89
+ raise Exception("Don't know how to merge bit %s" % bitNumber)
90
+ shiftedBit = 1 << bitNumber
91
+ mergedValue = mergeLogic(bool(item & shiftedBit) for item in lst)
92
+ returnValue |= mergedValue << bitNumber
93
+ return returnValue
94
+
95
+ return wrapper
96
+
97
+
98
+ class AttendanceRecordingIdentityDict(object):
99
+ """A dictionary-like object that records indices of items actually accessed
100
+ from a list."""
101
+
102
+ def __init__(self, lst):
103
+ self.l = lst
104
+ self.d = {id(v): i for i, v in enumerate(lst)}
105
+ self.s = set()
106
+
107
+ def __getitem__(self, v):
108
+ self.s.add(self.d[id(v)])
109
+ return v
110
+
111
+
112
+ class GregariousIdentityDict(object):
113
+ """A dictionary-like object that welcomes guests without reservations and
114
+ adds them to the end of the guest list."""
115
+
116
+ def __init__(self, lst):
117
+ self.l = lst
118
+ self.s = set(id(v) for v in lst)
119
+
120
+ def __getitem__(self, v):
121
+ if id(v) not in self.s:
122
+ self.s.add(id(v))
123
+ self.l.append(v)
124
+ return v
125
+
126
+
127
+ class NonhashableDict(object):
128
+ """A dictionary-like object mapping objects to values."""
129
+
130
+ def __init__(self, keys, values=None):
131
+ if values is None:
132
+ self.d = {id(v): i for i, v in enumerate(keys)}
133
+ else:
134
+ self.d = {id(k): v for k, v in zip(keys, values)}
135
+
136
+ def __getitem__(self, k):
137
+ return self.d[id(k)]
138
+
139
+ def __setitem__(self, k, v):
140
+ self.d[id(k)] = v
141
+
142
+ def __delitem__(self, k):
143
+ del self.d[id(k)]
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/mtiLib/__init__.py ADDED
@@ -0,0 +1,1400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FontDame-to-FontTools for OpenType Layout tables
2
+ #
3
+ # Source language spec is available at:
4
+ # http://monotype.github.io/OpenType_Table_Source/otl_source.html
5
+ # https://github.com/Monotype/OpenType_Table_Source/
6
+
7
+ from fontTools import ttLib
8
+ from fontTools.ttLib.tables._c_m_a_p import cmap_classes
9
+ from fontTools.ttLib.tables import otTables as ot
10
+ from fontTools.ttLib.tables.otBase import ValueRecord, valueRecordFormatDict
11
+ from fontTools.otlLib import builder as otl
12
+ from contextlib import contextmanager
13
+ from fontTools.ttLib import newTable
14
+ from fontTools.feaLib.lookupDebugInfo import LOOKUP_DEBUG_ENV_VAR, LOOKUP_DEBUG_INFO_KEY
15
+ from operator import setitem
16
+ import os
17
+ import logging
18
+
19
+
20
+ class MtiLibError(Exception):
21
+ pass
22
+
23
+
24
+ class ReferenceNotFoundError(MtiLibError):
25
+ pass
26
+
27
+
28
+ class FeatureNotFoundError(ReferenceNotFoundError):
29
+ pass
30
+
31
+
32
+ class LookupNotFoundError(ReferenceNotFoundError):
33
+ pass
34
+
35
+
36
+ log = logging.getLogger("fontTools.mtiLib")
37
+
38
+
39
+ def makeGlyph(s):
40
+ if s[:2] in ["U ", "u "]:
41
+ return ttLib.TTFont._makeGlyphName(int(s[2:], 16))
42
+ elif s[:2] == "# ":
43
+ return "glyph%.5d" % int(s[2:])
44
+ assert s.find(" ") < 0, "Space found in glyph name: %s" % s
45
+ assert s, "Glyph name is empty"
46
+ return s
47
+
48
+
49
+ def makeGlyphs(l):
50
+ return [makeGlyph(g) for g in l]
51
+
52
+
53
+ def mapLookup(sym, mapping):
54
+ # Lookups are addressed by name. So resolved them using a map if available.
55
+ # Fallback to parsing as lookup index if a map isn't provided.
56
+ if mapping is not None:
57
+ try:
58
+ idx = mapping[sym]
59
+ except KeyError:
60
+ raise LookupNotFoundError(sym)
61
+ else:
62
+ idx = int(sym)
63
+ return idx
64
+
65
+
66
+ def mapFeature(sym, mapping):
67
+ # Features are referenced by index according the spec. So, if symbol is an
68
+ # integer, use it directly. Otherwise look up in the map if provided.
69
+ try:
70
+ idx = int(sym)
71
+ except ValueError:
72
+ try:
73
+ idx = mapping[sym]
74
+ except KeyError:
75
+ raise FeatureNotFoundError(sym)
76
+ return idx
77
+
78
+
79
+ def setReference(mapper, mapping, sym, setter, collection, key):
80
+ try:
81
+ mapped = mapper(sym, mapping)
82
+ except ReferenceNotFoundError as e:
83
+ try:
84
+ if mapping is not None:
85
+ mapping.addDeferredMapping(
86
+ lambda ref: setter(collection, key, ref), sym, e
87
+ )
88
+ return
89
+ except AttributeError:
90
+ pass
91
+ raise
92
+ setter(collection, key, mapped)
93
+
94
+
95
+ class DeferredMapping(dict):
96
+ def __init__(self):
97
+ self._deferredMappings = []
98
+
99
+ def addDeferredMapping(self, setter, sym, e):
100
+ log.debug("Adding deferred mapping for symbol '%s' %s", sym, type(e).__name__)
101
+ self._deferredMappings.append((setter, sym, e))
102
+
103
+ def applyDeferredMappings(self):
104
+ for setter, sym, e in self._deferredMappings:
105
+ log.debug(
106
+ "Applying deferred mapping for symbol '%s' %s", sym, type(e).__name__
107
+ )
108
+ try:
109
+ mapped = self[sym]
110
+ except KeyError:
111
+ raise e
112
+ setter(mapped)
113
+ log.debug("Set to %s", mapped)
114
+ self._deferredMappings = []
115
+
116
+
117
+ def parseScriptList(lines, featureMap=None):
118
+ self = ot.ScriptList()
119
+ records = []
120
+ with lines.between("script table"):
121
+ for line in lines:
122
+ while len(line) < 4:
123
+ line.append("")
124
+ scriptTag, langSysTag, defaultFeature, features = line
125
+ log.debug("Adding script %s language-system %s", scriptTag, langSysTag)
126
+
127
+ langSys = ot.LangSys()
128
+ langSys.LookupOrder = None
129
+ if defaultFeature:
130
+ setReference(
131
+ mapFeature,
132
+ featureMap,
133
+ defaultFeature,
134
+ setattr,
135
+ langSys,
136
+ "ReqFeatureIndex",
137
+ )
138
+ else:
139
+ langSys.ReqFeatureIndex = 0xFFFF
140
+ syms = stripSplitComma(features)
141
+ langSys.FeatureIndex = theList = [3] * len(syms)
142
+ for i, sym in enumerate(syms):
143
+ setReference(mapFeature, featureMap, sym, setitem, theList, i)
144
+ langSys.FeatureCount = len(langSys.FeatureIndex)
145
+
146
+ script = [s for s in records if s.ScriptTag == scriptTag]
147
+ if script:
148
+ script = script[0].Script
149
+ else:
150
+ scriptRec = ot.ScriptRecord()
151
+ scriptRec.ScriptTag = scriptTag + " " * (4 - len(scriptTag))
152
+ scriptRec.Script = ot.Script()
153
+ records.append(scriptRec)
154
+ script = scriptRec.Script
155
+ script.DefaultLangSys = None
156
+ script.LangSysRecord = []
157
+ script.LangSysCount = 0
158
+
159
+ if langSysTag == "default":
160
+ script.DefaultLangSys = langSys
161
+ else:
162
+ langSysRec = ot.LangSysRecord()
163
+ langSysRec.LangSysTag = langSysTag + " " * (4 - len(langSysTag))
164
+ langSysRec.LangSys = langSys
165
+ script.LangSysRecord.append(langSysRec)
166
+ script.LangSysCount = len(script.LangSysRecord)
167
+
168
+ for script in records:
169
+ script.Script.LangSysRecord = sorted(
170
+ script.Script.LangSysRecord, key=lambda rec: rec.LangSysTag
171
+ )
172
+ self.ScriptRecord = sorted(records, key=lambda rec: rec.ScriptTag)
173
+ self.ScriptCount = len(self.ScriptRecord)
174
+ return self
175
+
176
+
177
+ def parseFeatureList(lines, lookupMap=None, featureMap=None):
178
+ self = ot.FeatureList()
179
+ self.FeatureRecord = []
180
+ with lines.between("feature table"):
181
+ for line in lines:
182
+ name, featureTag, lookups = line
183
+ if featureMap is not None:
184
+ assert name not in featureMap, "Duplicate feature name: %s" % name
185
+ featureMap[name] = len(self.FeatureRecord)
186
+ # If feature name is integer, make sure it matches its index.
187
+ try:
188
+ assert int(name) == len(self.FeatureRecord), "%d %d" % (
189
+ name,
190
+ len(self.FeatureRecord),
191
+ )
192
+ except ValueError:
193
+ pass
194
+ featureRec = ot.FeatureRecord()
195
+ featureRec.FeatureTag = featureTag
196
+ featureRec.Feature = ot.Feature()
197
+ self.FeatureRecord.append(featureRec)
198
+ feature = featureRec.Feature
199
+ feature.FeatureParams = None
200
+ syms = stripSplitComma(lookups)
201
+ feature.LookupListIndex = theList = [None] * len(syms)
202
+ for i, sym in enumerate(syms):
203
+ setReference(mapLookup, lookupMap, sym, setitem, theList, i)
204
+ feature.LookupCount = len(feature.LookupListIndex)
205
+
206
+ self.FeatureCount = len(self.FeatureRecord)
207
+ return self
208
+
209
+
210
+ def parseLookupFlags(lines):
211
+ flags = 0
212
+ filterset = None
213
+ allFlags = [
214
+ "righttoleft",
215
+ "ignorebaseglyphs",
216
+ "ignoreligatures",
217
+ "ignoremarks",
218
+ "markattachmenttype",
219
+ "markfiltertype",
220
+ ]
221
+ while lines.peeks()[0].lower() in allFlags:
222
+ line = next(lines)
223
+ flag = {
224
+ "righttoleft": 0x0001,
225
+ "ignorebaseglyphs": 0x0002,
226
+ "ignoreligatures": 0x0004,
227
+ "ignoremarks": 0x0008,
228
+ }.get(line[0].lower())
229
+ if flag:
230
+ assert line[1].lower() in ["yes", "no"], line[1]
231
+ if line[1].lower() == "yes":
232
+ flags |= flag
233
+ continue
234
+ if line[0].lower() == "markattachmenttype":
235
+ flags |= int(line[1]) << 8
236
+ continue
237
+ if line[0].lower() == "markfiltertype":
238
+ flags |= 0x10
239
+ filterset = int(line[1])
240
+ return flags, filterset
241
+
242
+
243
+ def parseSingleSubst(lines, font, _lookupMap=None):
244
+ mapping = {}
245
+ for line in lines:
246
+ assert len(line) == 2, line
247
+ line = makeGlyphs(line)
248
+ mapping[line[0]] = line[1]
249
+ return otl.buildSingleSubstSubtable(mapping)
250
+
251
+
252
+ def parseMultiple(lines, font, _lookupMap=None):
253
+ mapping = {}
254
+ for line in lines:
255
+ line = makeGlyphs(line)
256
+ mapping[line[0]] = line[1:]
257
+ return otl.buildMultipleSubstSubtable(mapping)
258
+
259
+
260
+ def parseAlternate(lines, font, _lookupMap=None):
261
+ mapping = {}
262
+ for line in lines:
263
+ line = makeGlyphs(line)
264
+ mapping[line[0]] = line[1:]
265
+ return otl.buildAlternateSubstSubtable(mapping)
266
+
267
+
268
+ def parseLigature(lines, font, _lookupMap=None):
269
+ mapping = {}
270
+ for line in lines:
271
+ assert len(line) >= 2, line
272
+ line = makeGlyphs(line)
273
+ mapping[tuple(line[1:])] = line[0]
274
+ return otl.buildLigatureSubstSubtable(mapping)
275
+
276
+
277
+ def parseSinglePos(lines, font, _lookupMap=None):
278
+ values = {}
279
+ for line in lines:
280
+ assert len(line) == 3, line
281
+ w = line[0].title().replace(" ", "")
282
+ assert w in valueRecordFormatDict
283
+ g = makeGlyph(line[1])
284
+ v = int(line[2])
285
+ if g not in values:
286
+ values[g] = ValueRecord()
287
+ assert not hasattr(values[g], w), (g, w)
288
+ setattr(values[g], w, v)
289
+ return otl.buildSinglePosSubtable(values, font.getReverseGlyphMap())
290
+
291
+
292
+ def parsePair(lines, font, _lookupMap=None):
293
+ self = ot.PairPos()
294
+ self.ValueFormat1 = self.ValueFormat2 = 0
295
+ typ = lines.peeks()[0].split()[0].lower()
296
+ if typ in ("left", "right"):
297
+ self.Format = 1
298
+ values = {}
299
+ for line in lines:
300
+ assert len(line) == 4, line
301
+ side = line[0].split()[0].lower()
302
+ assert side in ("left", "right"), side
303
+ what = line[0][len(side) :].title().replace(" ", "")
304
+ mask = valueRecordFormatDict[what][0]
305
+ glyph1, glyph2 = makeGlyphs(line[1:3])
306
+ value = int(line[3])
307
+ if not glyph1 in values:
308
+ values[glyph1] = {}
309
+ if not glyph2 in values[glyph1]:
310
+ values[glyph1][glyph2] = (ValueRecord(), ValueRecord())
311
+ rec2 = values[glyph1][glyph2]
312
+ if side == "left":
313
+ self.ValueFormat1 |= mask
314
+ vr = rec2[0]
315
+ else:
316
+ self.ValueFormat2 |= mask
317
+ vr = rec2[1]
318
+ assert not hasattr(vr, what), (vr, what)
319
+ setattr(vr, what, value)
320
+ self.Coverage = makeCoverage(set(values.keys()), font)
321
+ self.PairSet = []
322
+ for glyph1 in self.Coverage.glyphs:
323
+ values1 = values[glyph1]
324
+ pairset = ot.PairSet()
325
+ records = pairset.PairValueRecord = []
326
+ for glyph2 in sorted(values1.keys(), key=font.getGlyphID):
327
+ values2 = values1[glyph2]
328
+ pair = ot.PairValueRecord()
329
+ pair.SecondGlyph = glyph2
330
+ pair.Value1 = values2[0]
331
+ pair.Value2 = values2[1] if self.ValueFormat2 else None
332
+ records.append(pair)
333
+ pairset.PairValueCount = len(pairset.PairValueRecord)
334
+ self.PairSet.append(pairset)
335
+ self.PairSetCount = len(self.PairSet)
336
+ elif typ.endswith("class"):
337
+ self.Format = 2
338
+ classDefs = [None, None]
339
+ while lines.peeks()[0].endswith("class definition begin"):
340
+ typ = lines.peek()[0][: -len("class definition begin")].lower()
341
+ idx, klass = {
342
+ "first": (0, ot.ClassDef1),
343
+ "second": (1, ot.ClassDef2),
344
+ }[typ]
345
+ assert classDefs[idx] is None
346
+ classDefs[idx] = parseClassDef(lines, font, klass=klass)
347
+ self.ClassDef1, self.ClassDef2 = classDefs
348
+ self.Class1Count, self.Class2Count = (
349
+ 1 + max(c.classDefs.values()) for c in classDefs
350
+ )
351
+ self.Class1Record = [ot.Class1Record() for i in range(self.Class1Count)]
352
+ for rec1 in self.Class1Record:
353
+ rec1.Class2Record = [ot.Class2Record() for j in range(self.Class2Count)]
354
+ for rec2 in rec1.Class2Record:
355
+ rec2.Value1 = ValueRecord()
356
+ rec2.Value2 = ValueRecord()
357
+ for line in lines:
358
+ assert len(line) == 4, line
359
+ side = line[0].split()[0].lower()
360
+ assert side in ("left", "right"), side
361
+ what = line[0][len(side) :].title().replace(" ", "")
362
+ mask = valueRecordFormatDict[what][0]
363
+ class1, class2, value = (int(x) for x in line[1:4])
364
+ rec2 = self.Class1Record[class1].Class2Record[class2]
365
+ if side == "left":
366
+ self.ValueFormat1 |= mask
367
+ vr = rec2.Value1
368
+ else:
369
+ self.ValueFormat2 |= mask
370
+ vr = rec2.Value2
371
+ assert not hasattr(vr, what), (vr, what)
372
+ setattr(vr, what, value)
373
+ for rec1 in self.Class1Record:
374
+ for rec2 in rec1.Class2Record:
375
+ rec2.Value1 = ValueRecord(self.ValueFormat1, rec2.Value1)
376
+ rec2.Value2 = (
377
+ ValueRecord(self.ValueFormat2, rec2.Value2)
378
+ if self.ValueFormat2
379
+ else None
380
+ )
381
+
382
+ self.Coverage = makeCoverage(set(self.ClassDef1.classDefs.keys()), font)
383
+ else:
384
+ assert 0, typ
385
+ return self
386
+
387
+
388
+ def parseKernset(lines, font, _lookupMap=None):
389
+ typ = lines.peeks()[0].split()[0].lower()
390
+ if typ in ("left", "right"):
391
+ with lines.until(
392
+ ("firstclass definition begin", "secondclass definition begin")
393
+ ):
394
+ return parsePair(lines, font)
395
+ return parsePair(lines, font)
396
+
397
+
398
+ def makeAnchor(data, klass=ot.Anchor):
399
+ assert len(data) <= 2
400
+ anchor = klass()
401
+ anchor.Format = 1
402
+ anchor.XCoordinate, anchor.YCoordinate = intSplitComma(data[0])
403
+ if len(data) > 1 and data[1] != "":
404
+ anchor.Format = 2
405
+ anchor.AnchorPoint = int(data[1])
406
+ return anchor
407
+
408
+
409
+ def parseCursive(lines, font, _lookupMap=None):
410
+ records = {}
411
+ for line in lines:
412
+ assert len(line) in [3, 4], line
413
+ idx, klass = {
414
+ "entry": (0, ot.EntryAnchor),
415
+ "exit": (1, ot.ExitAnchor),
416
+ }[line[0]]
417
+ glyph = makeGlyph(line[1])
418
+ if glyph not in records:
419
+ records[glyph] = [None, None]
420
+ assert records[glyph][idx] is None, (glyph, idx)
421
+ records[glyph][idx] = makeAnchor(line[2:], klass)
422
+ return otl.buildCursivePosSubtable(records, font.getReverseGlyphMap())
423
+
424
+
425
+ def makeMarkRecords(data, coverage, c):
426
+ records = []
427
+ for glyph in coverage.glyphs:
428
+ klass, anchor = data[glyph]
429
+ record = c.MarkRecordClass()
430
+ record.Class = klass
431
+ setattr(record, c.MarkAnchor, anchor)
432
+ records.append(record)
433
+ return records
434
+
435
+
436
+ def makeBaseRecords(data, coverage, c, classCount):
437
+ records = []
438
+ idx = {}
439
+ for glyph in coverage.glyphs:
440
+ idx[glyph] = len(records)
441
+ record = c.BaseRecordClass()
442
+ anchors = [None] * classCount
443
+ setattr(record, c.BaseAnchor, anchors)
444
+ records.append(record)
445
+ for (glyph, klass), anchor in data.items():
446
+ record = records[idx[glyph]]
447
+ anchors = getattr(record, c.BaseAnchor)
448
+ assert anchors[klass] is None, (glyph, klass)
449
+ anchors[klass] = anchor
450
+ return records
451
+
452
+
453
+ def makeLigatureRecords(data, coverage, c, classCount):
454
+ records = [None] * len(coverage.glyphs)
455
+ idx = {g: i for i, g in enumerate(coverage.glyphs)}
456
+
457
+ for (glyph, klass, compIdx, compCount), anchor in data.items():
458
+ record = records[idx[glyph]]
459
+ if record is None:
460
+ record = records[idx[glyph]] = ot.LigatureAttach()
461
+ record.ComponentCount = compCount
462
+ record.ComponentRecord = [ot.ComponentRecord() for i in range(compCount)]
463
+ for compRec in record.ComponentRecord:
464
+ compRec.LigatureAnchor = [None] * classCount
465
+ assert record.ComponentCount == compCount, (
466
+ glyph,
467
+ record.ComponentCount,
468
+ compCount,
469
+ )
470
+
471
+ anchors = record.ComponentRecord[compIdx - 1].LigatureAnchor
472
+ assert anchors[klass] is None, (glyph, compIdx, klass)
473
+ anchors[klass] = anchor
474
+ return records
475
+
476
+
477
+ def parseMarkToSomething(lines, font, c):
478
+ self = c.Type()
479
+ self.Format = 1
480
+ markData = {}
481
+ baseData = {}
482
+ Data = {
483
+ "mark": (markData, c.MarkAnchorClass),
484
+ "base": (baseData, c.BaseAnchorClass),
485
+ "ligature": (baseData, c.BaseAnchorClass),
486
+ }
487
+ maxKlass = 0
488
+ for line in lines:
489
+ typ = line[0]
490
+ assert typ in ("mark", "base", "ligature")
491
+ glyph = makeGlyph(line[1])
492
+ data, anchorClass = Data[typ]
493
+ extraItems = 2 if typ == "ligature" else 0
494
+ extras = tuple(int(i) for i in line[2 : 2 + extraItems])
495
+ klass = int(line[2 + extraItems])
496
+ anchor = makeAnchor(line[3 + extraItems :], anchorClass)
497
+ if typ == "mark":
498
+ key, value = glyph, (klass, anchor)
499
+ else:
500
+ key, value = ((glyph, klass) + extras), anchor
501
+ assert key not in data, key
502
+ data[key] = value
503
+ maxKlass = max(maxKlass, klass)
504
+
505
+ # Mark
506
+ markCoverage = makeCoverage(set(markData.keys()), font, c.MarkCoverageClass)
507
+ markArray = c.MarkArrayClass()
508
+ markRecords = makeMarkRecords(markData, markCoverage, c)
509
+ setattr(markArray, c.MarkRecord, markRecords)
510
+ setattr(markArray, c.MarkCount, len(markRecords))
511
+ setattr(self, c.MarkCoverage, markCoverage)
512
+ setattr(self, c.MarkArray, markArray)
513
+ self.ClassCount = maxKlass + 1
514
+
515
+ # Base
516
+ self.classCount = 0 if not baseData else 1 + max(k[1] for k, v in baseData.items())
517
+ baseCoverage = makeCoverage(
518
+ set([k[0] for k in baseData.keys()]), font, c.BaseCoverageClass
519
+ )
520
+ baseArray = c.BaseArrayClass()
521
+ if c.Base == "Ligature":
522
+ baseRecords = makeLigatureRecords(baseData, baseCoverage, c, self.classCount)
523
+ else:
524
+ baseRecords = makeBaseRecords(baseData, baseCoverage, c, self.classCount)
525
+ setattr(baseArray, c.BaseRecord, baseRecords)
526
+ setattr(baseArray, c.BaseCount, len(baseRecords))
527
+ setattr(self, c.BaseCoverage, baseCoverage)
528
+ setattr(self, c.BaseArray, baseArray)
529
+
530
+ return self
531
+
532
+
533
+ class MarkHelper(object):
534
+ def __init__(self):
535
+ for Which in ("Mark", "Base"):
536
+ for What in ("Coverage", "Array", "Count", "Record", "Anchor"):
537
+ key = Which + What
538
+ if Which == "Mark" and What in ("Count", "Record", "Anchor"):
539
+ value = key
540
+ else:
541
+ value = getattr(self, Which) + What
542
+ if value == "LigatureRecord":
543
+ value = "LigatureAttach"
544
+ setattr(self, key, value)
545
+ if What != "Count":
546
+ klass = getattr(ot, value)
547
+ setattr(self, key + "Class", klass)
548
+
549
+
550
+ class MarkToBaseHelper(MarkHelper):
551
+ Mark = "Mark"
552
+ Base = "Base"
553
+ Type = ot.MarkBasePos
554
+
555
+
556
+ class MarkToMarkHelper(MarkHelper):
557
+ Mark = "Mark1"
558
+ Base = "Mark2"
559
+ Type = ot.MarkMarkPos
560
+
561
+
562
+ class MarkToLigatureHelper(MarkHelper):
563
+ Mark = "Mark"
564
+ Base = "Ligature"
565
+ Type = ot.MarkLigPos
566
+
567
+
568
+ def parseMarkToBase(lines, font, _lookupMap=None):
569
+ return parseMarkToSomething(lines, font, MarkToBaseHelper())
570
+
571
+
572
+ def parseMarkToMark(lines, font, _lookupMap=None):
573
+ return parseMarkToSomething(lines, font, MarkToMarkHelper())
574
+
575
+
576
+ def parseMarkToLigature(lines, font, _lookupMap=None):
577
+ return parseMarkToSomething(lines, font, MarkToLigatureHelper())
578
+
579
+
580
+ def stripSplitComma(line):
581
+ return [s.strip() for s in line.split(",")] if line else []
582
+
583
+
584
+ def intSplitComma(line):
585
+ return [int(i) for i in line.split(",")] if line else []
586
+
587
+
588
+ # Copied from fontTools.subset
589
+ class ContextHelper(object):
590
+ def __init__(self, klassName, Format):
591
+ if klassName.endswith("Subst"):
592
+ Typ = "Sub"
593
+ Type = "Subst"
594
+ else:
595
+ Typ = "Pos"
596
+ Type = "Pos"
597
+ if klassName.startswith("Chain"):
598
+ Chain = "Chain"
599
+ InputIdx = 1
600
+ DataLen = 3
601
+ else:
602
+ Chain = ""
603
+ InputIdx = 0
604
+ DataLen = 1
605
+ ChainTyp = Chain + Typ
606
+
607
+ self.Typ = Typ
608
+ self.Type = Type
609
+ self.Chain = Chain
610
+ self.ChainTyp = ChainTyp
611
+ self.InputIdx = InputIdx
612
+ self.DataLen = DataLen
613
+
614
+ self.LookupRecord = Type + "LookupRecord"
615
+
616
+ if Format == 1:
617
+ Coverage = lambda r: r.Coverage
618
+ ChainCoverage = lambda r: r.Coverage
619
+ ContextData = lambda r: (None,)
620
+ ChainContextData = lambda r: (None, None, None)
621
+ SetContextData = None
622
+ SetChainContextData = None
623
+ RuleData = lambda r: (r.Input,)
624
+ ChainRuleData = lambda r: (r.Backtrack, r.Input, r.LookAhead)
625
+
626
+ def SetRuleData(r, d):
627
+ (r.Input,) = d
628
+ (r.GlyphCount,) = (len(x) + 1 for x in d)
629
+
630
+ def ChainSetRuleData(r, d):
631
+ (r.Backtrack, r.Input, r.LookAhead) = d
632
+ (
633
+ r.BacktrackGlyphCount,
634
+ r.InputGlyphCount,
635
+ r.LookAheadGlyphCount,
636
+ ) = (len(d[0]), len(d[1]) + 1, len(d[2]))
637
+
638
+ elif Format == 2:
639
+ Coverage = lambda r: r.Coverage
640
+ ChainCoverage = lambda r: r.Coverage
641
+ ContextData = lambda r: (r.ClassDef,)
642
+ ChainContextData = lambda r: (
643
+ r.BacktrackClassDef,
644
+ r.InputClassDef,
645
+ r.LookAheadClassDef,
646
+ )
647
+
648
+ def SetContextData(r, d):
649
+ (r.ClassDef,) = d
650
+
651
+ def SetChainContextData(r, d):
652
+ (r.BacktrackClassDef, r.InputClassDef, r.LookAheadClassDef) = d
653
+
654
+ RuleData = lambda r: (r.Class,)
655
+ ChainRuleData = lambda r: (r.Backtrack, r.Input, r.LookAhead)
656
+
657
+ def SetRuleData(r, d):
658
+ (r.Class,) = d
659
+ (r.GlyphCount,) = (len(x) + 1 for x in d)
660
+
661
+ def ChainSetRuleData(r, d):
662
+ (r.Backtrack, r.Input, r.LookAhead) = d
663
+ (
664
+ r.BacktrackGlyphCount,
665
+ r.InputGlyphCount,
666
+ r.LookAheadGlyphCount,
667
+ ) = (len(d[0]), len(d[1]) + 1, len(d[2]))
668
+
669
+ elif Format == 3:
670
+ Coverage = lambda r: r.Coverage[0]
671
+ ChainCoverage = lambda r: r.InputCoverage[0]
672
+ ContextData = None
673
+ ChainContextData = None
674
+ SetContextData = None
675
+ SetChainContextData = None
676
+ RuleData = lambda r: r.Coverage
677
+ ChainRuleData = lambda r: (
678
+ r.BacktrackCoverage + r.InputCoverage + r.LookAheadCoverage
679
+ )
680
+
681
+ def SetRuleData(r, d):
682
+ (r.Coverage,) = d
683
+ (r.GlyphCount,) = (len(x) for x in d)
684
+
685
+ def ChainSetRuleData(r, d):
686
+ (r.BacktrackCoverage, r.InputCoverage, r.LookAheadCoverage) = d
687
+ (
688
+ r.BacktrackGlyphCount,
689
+ r.InputGlyphCount,
690
+ r.LookAheadGlyphCount,
691
+ ) = (len(x) for x in d)
692
+
693
+ else:
694
+ assert 0, "unknown format: %s" % Format
695
+
696
+ if Chain:
697
+ self.Coverage = ChainCoverage
698
+ self.ContextData = ChainContextData
699
+ self.SetContextData = SetChainContextData
700
+ self.RuleData = ChainRuleData
701
+ self.SetRuleData = ChainSetRuleData
702
+ else:
703
+ self.Coverage = Coverage
704
+ self.ContextData = ContextData
705
+ self.SetContextData = SetContextData
706
+ self.RuleData = RuleData
707
+ self.SetRuleData = SetRuleData
708
+
709
+ if Format == 1:
710
+ self.Rule = ChainTyp + "Rule"
711
+ self.RuleCount = ChainTyp + "RuleCount"
712
+ self.RuleSet = ChainTyp + "RuleSet"
713
+ self.RuleSetCount = ChainTyp + "RuleSetCount"
714
+ self.Intersect = lambda glyphs, c, r: [r] if r in glyphs else []
715
+ elif Format == 2:
716
+ self.Rule = ChainTyp + "ClassRule"
717
+ self.RuleCount = ChainTyp + "ClassRuleCount"
718
+ self.RuleSet = ChainTyp + "ClassSet"
719
+ self.RuleSetCount = ChainTyp + "ClassSetCount"
720
+ self.Intersect = lambda glyphs, c, r: (
721
+ c.intersect_class(glyphs, r)
722
+ if c
723
+ else (set(glyphs) if r == 0 else set())
724
+ )
725
+
726
+ self.ClassDef = "InputClassDef" if Chain else "ClassDef"
727
+ self.ClassDefIndex = 1 if Chain else 0
728
+ self.Input = "Input" if Chain else "Class"
729
+
730
+
731
+ def parseLookupRecords(items, klassName, lookupMap=None):
732
+ klass = getattr(ot, klassName)
733
+ lst = []
734
+ for item in items:
735
+ rec = klass()
736
+ item = stripSplitComma(item)
737
+ assert len(item) == 2, item
738
+ idx = int(item[0])
739
+ assert idx > 0, idx
740
+ rec.SequenceIndex = idx - 1
741
+ setReference(mapLookup, lookupMap, item[1], setattr, rec, "LookupListIndex")
742
+ lst.append(rec)
743
+ return lst
744
+
745
+
746
+ def makeClassDef(classDefs, font, klass=ot.Coverage):
747
+ if not classDefs:
748
+ return None
749
+ self = klass()
750
+ self.classDefs = dict(classDefs)
751
+ return self
752
+
753
+
754
+ def parseClassDef(lines, font, klass=ot.ClassDef):
755
+ classDefs = {}
756
+ with lines.between("class definition"):
757
+ for line in lines:
758
+ glyph = makeGlyph(line[0])
759
+ assert glyph not in classDefs, glyph
760
+ classDefs[glyph] = int(line[1])
761
+ return makeClassDef(classDefs, font, klass)
762
+
763
+
764
+ def makeCoverage(glyphs, font, klass=ot.Coverage):
765
+ if not glyphs:
766
+ return None
767
+ if isinstance(glyphs, set):
768
+ glyphs = sorted(glyphs)
769
+ coverage = klass()
770
+ coverage.glyphs = sorted(set(glyphs), key=font.getGlyphID)
771
+ return coverage
772
+
773
+
774
+ def parseCoverage(lines, font, klass=ot.Coverage):
775
+ glyphs = []
776
+ with lines.between("coverage definition"):
777
+ for line in lines:
778
+ glyphs.append(makeGlyph(line[0]))
779
+ return makeCoverage(glyphs, font, klass)
780
+
781
+
782
+ def bucketizeRules(self, c, rules, bucketKeys):
783
+ buckets = {}
784
+ for seq, recs in rules:
785
+ buckets.setdefault(seq[c.InputIdx][0], []).append(
786
+ (tuple(s[1 if i == c.InputIdx else 0 :] for i, s in enumerate(seq)), recs)
787
+ )
788
+
789
+ rulesets = []
790
+ for firstGlyph in bucketKeys:
791
+ if firstGlyph not in buckets:
792
+ rulesets.append(None)
793
+ continue
794
+ thisRules = []
795
+ for seq, recs in buckets[firstGlyph]:
796
+ rule = getattr(ot, c.Rule)()
797
+ c.SetRuleData(rule, seq)
798
+ setattr(rule, c.Type + "Count", len(recs))
799
+ setattr(rule, c.LookupRecord, recs)
800
+ thisRules.append(rule)
801
+
802
+ ruleset = getattr(ot, c.RuleSet)()
803
+ setattr(ruleset, c.Rule, thisRules)
804
+ setattr(ruleset, c.RuleCount, len(thisRules))
805
+ rulesets.append(ruleset)
806
+
807
+ setattr(self, c.RuleSet, rulesets)
808
+ setattr(self, c.RuleSetCount, len(rulesets))
809
+
810
+
811
+ def parseContext(lines, font, Type, lookupMap=None):
812
+ self = getattr(ot, Type)()
813
+ typ = lines.peeks()[0].split()[0].lower()
814
+ if typ == "glyph":
815
+ self.Format = 1
816
+ log.debug("Parsing %s format %s", Type, self.Format)
817
+ c = ContextHelper(Type, self.Format)
818
+ rules = []
819
+ for line in lines:
820
+ assert line[0].lower() == "glyph", line[0]
821
+ while len(line) < 1 + c.DataLen:
822
+ line.append("")
823
+ seq = tuple(makeGlyphs(stripSplitComma(i)) for i in line[1 : 1 + c.DataLen])
824
+ recs = parseLookupRecords(line[1 + c.DataLen :], c.LookupRecord, lookupMap)
825
+ rules.append((seq, recs))
826
+
827
+ firstGlyphs = set(seq[c.InputIdx][0] for seq, recs in rules)
828
+ self.Coverage = makeCoverage(firstGlyphs, font)
829
+ bucketizeRules(self, c, rules, self.Coverage.glyphs)
830
+ elif typ.endswith("class"):
831
+ self.Format = 2
832
+ log.debug("Parsing %s format %s", Type, self.Format)
833
+ c = ContextHelper(Type, self.Format)
834
+ classDefs = [None] * c.DataLen
835
+ while lines.peeks()[0].endswith("class definition begin"):
836
+ typ = lines.peek()[0][: -len("class definition begin")].lower()
837
+ idx, klass = {
838
+ 1: {
839
+ "": (0, ot.ClassDef),
840
+ },
841
+ 3: {
842
+ "backtrack": (0, ot.BacktrackClassDef),
843
+ "": (1, ot.InputClassDef),
844
+ "lookahead": (2, ot.LookAheadClassDef),
845
+ },
846
+ }[c.DataLen][typ]
847
+ assert classDefs[idx] is None, idx
848
+ classDefs[idx] = parseClassDef(lines, font, klass=klass)
849
+ c.SetContextData(self, classDefs)
850
+ rules = []
851
+ for line in lines:
852
+ assert line[0].lower().startswith("class"), line[0]
853
+ while len(line) < 1 + c.DataLen:
854
+ line.append("")
855
+ seq = tuple(intSplitComma(i) for i in line[1 : 1 + c.DataLen])
856
+ recs = parseLookupRecords(line[1 + c.DataLen :], c.LookupRecord, lookupMap)
857
+ rules.append((seq, recs))
858
+ firstClasses = set(seq[c.InputIdx][0] for seq, recs in rules)
859
+ firstGlyphs = set(
860
+ g for g, c in classDefs[c.InputIdx].classDefs.items() if c in firstClasses
861
+ )
862
+ self.Coverage = makeCoverage(firstGlyphs, font)
863
+ bucketizeRules(self, c, rules, range(max(firstClasses) + 1))
864
+ elif typ.endswith("coverage"):
865
+ self.Format = 3
866
+ log.debug("Parsing %s format %s", Type, self.Format)
867
+ c = ContextHelper(Type, self.Format)
868
+ coverages = tuple([] for i in range(c.DataLen))
869
+ while lines.peeks()[0].endswith("coverage definition begin"):
870
+ typ = lines.peek()[0][: -len("coverage definition begin")].lower()
871
+ idx, klass = {
872
+ 1: {
873
+ "": (0, ot.Coverage),
874
+ },
875
+ 3: {
876
+ "backtrack": (0, ot.BacktrackCoverage),
877
+ "input": (1, ot.InputCoverage),
878
+ "lookahead": (2, ot.LookAheadCoverage),
879
+ },
880
+ }[c.DataLen][typ]
881
+ coverages[idx].append(parseCoverage(lines, font, klass=klass))
882
+ c.SetRuleData(self, coverages)
883
+ lines = list(lines)
884
+ assert len(lines) == 1
885
+ line = lines[0]
886
+ assert line[0].lower() == "coverage", line[0]
887
+ recs = parseLookupRecords(line[1:], c.LookupRecord, lookupMap)
888
+ setattr(self, c.Type + "Count", len(recs))
889
+ setattr(self, c.LookupRecord, recs)
890
+ else:
891
+ assert 0, typ
892
+ return self
893
+
894
+
895
+ def parseContextSubst(lines, font, lookupMap=None):
896
+ return parseContext(lines, font, "ContextSubst", lookupMap=lookupMap)
897
+
898
+
899
+ def parseContextPos(lines, font, lookupMap=None):
900
+ return parseContext(lines, font, "ContextPos", lookupMap=lookupMap)
901
+
902
+
903
+ def parseChainedSubst(lines, font, lookupMap=None):
904
+ return parseContext(lines, font, "ChainContextSubst", lookupMap=lookupMap)
905
+
906
+
907
+ def parseChainedPos(lines, font, lookupMap=None):
908
+ return parseContext(lines, font, "ChainContextPos", lookupMap=lookupMap)
909
+
910
+
911
+ def parseReverseChainedSubst(lines, font, _lookupMap=None):
912
+ self = ot.ReverseChainSingleSubst()
913
+ self.Format = 1
914
+ coverages = ([], [])
915
+ while lines.peeks()[0].endswith("coverage definition begin"):
916
+ typ = lines.peek()[0][: -len("coverage definition begin")].lower()
917
+ idx, klass = {
918
+ "backtrack": (0, ot.BacktrackCoverage),
919
+ "lookahead": (1, ot.LookAheadCoverage),
920
+ }[typ]
921
+ coverages[idx].append(parseCoverage(lines, font, klass=klass))
922
+ self.BacktrackCoverage = coverages[0]
923
+ self.BacktrackGlyphCount = len(self.BacktrackCoverage)
924
+ self.LookAheadCoverage = coverages[1]
925
+ self.LookAheadGlyphCount = len(self.LookAheadCoverage)
926
+ mapping = {}
927
+ for line in lines:
928
+ assert len(line) == 2, line
929
+ line = makeGlyphs(line)
930
+ mapping[line[0]] = line[1]
931
+ self.Coverage = makeCoverage(set(mapping.keys()), font)
932
+ self.Substitute = [mapping[k] for k in self.Coverage.glyphs]
933
+ self.GlyphCount = len(self.Substitute)
934
+ return self
935
+
936
+
937
+ def parseLookup(lines, tableTag, font, lookupMap=None):
938
+ line = lines.expect("lookup")
939
+ _, name, typ = line
940
+ log.debug("Parsing lookup type %s %s", typ, name)
941
+ lookup = ot.Lookup()
942
+ lookup.LookupFlag, filterset = parseLookupFlags(lines)
943
+ if filterset is not None:
944
+ lookup.MarkFilteringSet = filterset
945
+ lookup.LookupType, parseLookupSubTable = {
946
+ "GSUB": {
947
+ "single": (1, parseSingleSubst),
948
+ "multiple": (2, parseMultiple),
949
+ "alternate": (3, parseAlternate),
950
+ "ligature": (4, parseLigature),
951
+ "context": (5, parseContextSubst),
952
+ "chained": (6, parseChainedSubst),
953
+ "reversechained": (8, parseReverseChainedSubst),
954
+ },
955
+ "GPOS": {
956
+ "single": (1, parseSinglePos),
957
+ "pair": (2, parsePair),
958
+ "kernset": (2, parseKernset),
959
+ "cursive": (3, parseCursive),
960
+ "mark to base": (4, parseMarkToBase),
961
+ "mark to ligature": (5, parseMarkToLigature),
962
+ "mark to mark": (6, parseMarkToMark),
963
+ "context": (7, parseContextPos),
964
+ "chained": (8, parseChainedPos),
965
+ },
966
+ }[tableTag][typ]
967
+
968
+ with lines.until("lookup end"):
969
+ subtables = []
970
+
971
+ while lines.peek():
972
+ with lines.until(("% subtable", "subtable end")):
973
+ while lines.peek():
974
+ subtable = parseLookupSubTable(lines, font, lookupMap)
975
+ assert lookup.LookupType == subtable.LookupType
976
+ subtables.append(subtable)
977
+ if lines.peeks()[0] in ("% subtable", "subtable end"):
978
+ next(lines)
979
+ lines.expect("lookup end")
980
+
981
+ lookup.SubTable = subtables
982
+ lookup.SubTableCount = len(lookup.SubTable)
983
+ if lookup.SubTableCount == 0:
984
+ # Remove this return when following is fixed:
985
+ # https://github.com/fonttools/fonttools/issues/789
986
+ return None
987
+ return lookup
988
+
989
+
990
+ def parseGSUBGPOS(lines, font, tableTag):
991
+ container = ttLib.getTableClass(tableTag)()
992
+ lookupMap = DeferredMapping()
993
+ featureMap = DeferredMapping()
994
+ assert tableTag in ("GSUB", "GPOS")
995
+ log.debug("Parsing %s", tableTag)
996
+ self = getattr(ot, tableTag)()
997
+ self.Version = 0x00010000
998
+ fields = {
999
+ "script table begin": (
1000
+ "ScriptList",
1001
+ lambda lines: parseScriptList(lines, featureMap),
1002
+ ),
1003
+ "feature table begin": (
1004
+ "FeatureList",
1005
+ lambda lines: parseFeatureList(lines, lookupMap, featureMap),
1006
+ ),
1007
+ "lookup": ("LookupList", None),
1008
+ }
1009
+ for attr, parser in fields.values():
1010
+ setattr(self, attr, None)
1011
+ while lines.peek() is not None:
1012
+ typ = lines.peek()[0].lower()
1013
+ if typ not in fields:
1014
+ log.debug("Skipping %s", lines.peek())
1015
+ next(lines)
1016
+ continue
1017
+ attr, parser = fields[typ]
1018
+ if typ == "lookup":
1019
+ if self.LookupList is None:
1020
+ self.LookupList = ot.LookupList()
1021
+ self.LookupList.Lookup = []
1022
+ _, name, _ = lines.peek()
1023
+ lookup = parseLookup(lines, tableTag, font, lookupMap)
1024
+ if lookupMap is not None:
1025
+ assert name not in lookupMap, "Duplicate lookup name: %s" % name
1026
+ lookupMap[name] = len(self.LookupList.Lookup)
1027
+ else:
1028
+ assert int(name) == len(self.LookupList.Lookup), "%d %d" % (
1029
+ name,
1030
+ len(self.Lookup),
1031
+ )
1032
+ self.LookupList.Lookup.append(lookup)
1033
+ else:
1034
+ assert getattr(self, attr) is None, attr
1035
+ setattr(self, attr, parser(lines))
1036
+ if self.LookupList:
1037
+ self.LookupList.LookupCount = len(self.LookupList.Lookup)
1038
+ if lookupMap is not None:
1039
+ lookupMap.applyDeferredMappings()
1040
+ if os.environ.get(LOOKUP_DEBUG_ENV_VAR):
1041
+ if "Debg" not in font:
1042
+ font["Debg"] = newTable("Debg")
1043
+ font["Debg"].data = {}
1044
+ debug = (
1045
+ font["Debg"]
1046
+ .data.setdefault(LOOKUP_DEBUG_INFO_KEY, {})
1047
+ .setdefault(tableTag, {})
1048
+ )
1049
+ for name, lookup in lookupMap.items():
1050
+ debug[str(lookup)] = ["", name, ""]
1051
+
1052
+ featureMap.applyDeferredMappings()
1053
+ container.table = self
1054
+ return container
1055
+
1056
+
1057
+ def parseGSUB(lines, font):
1058
+ return parseGSUBGPOS(lines, font, "GSUB")
1059
+
1060
+
1061
+ def parseGPOS(lines, font):
1062
+ return parseGSUBGPOS(lines, font, "GPOS")
1063
+
1064
+
1065
+ def parseAttachList(lines, font):
1066
+ points = {}
1067
+ with lines.between("attachment list"):
1068
+ for line in lines:
1069
+ glyph = makeGlyph(line[0])
1070
+ assert glyph not in points, glyph
1071
+ points[glyph] = [int(i) for i in line[1:]]
1072
+ return otl.buildAttachList(points, font.getReverseGlyphMap())
1073
+
1074
+
1075
+ def parseCaretList(lines, font):
1076
+ carets = {}
1077
+ with lines.between("carets"):
1078
+ for line in lines:
1079
+ glyph = makeGlyph(line[0])
1080
+ assert glyph not in carets, glyph
1081
+ num = int(line[1])
1082
+ thisCarets = [int(i) for i in line[2:]]
1083
+ assert num == len(thisCarets), line
1084
+ carets[glyph] = thisCarets
1085
+ return otl.buildLigCaretList(carets, {}, font.getReverseGlyphMap())
1086
+
1087
+
1088
+ def makeMarkFilteringSets(sets, font):
1089
+ self = ot.MarkGlyphSetsDef()
1090
+ self.MarkSetTableFormat = 1
1091
+ self.MarkSetCount = 1 + max(sets.keys())
1092
+ self.Coverage = [None] * self.MarkSetCount
1093
+ for k, v in sorted(sets.items()):
1094
+ self.Coverage[k] = makeCoverage(set(v), font)
1095
+ return self
1096
+
1097
+
1098
+ def parseMarkFilteringSets(lines, font):
1099
+ sets = {}
1100
+ with lines.between("set definition"):
1101
+ for line in lines:
1102
+ assert len(line) == 2, line
1103
+ glyph = makeGlyph(line[0])
1104
+ # TODO accept set names
1105
+ st = int(line[1])
1106
+ if st not in sets:
1107
+ sets[st] = []
1108
+ sets[st].append(glyph)
1109
+ return makeMarkFilteringSets(sets, font)
1110
+
1111
+
1112
+ def parseGDEF(lines, font):
1113
+ container = ttLib.getTableClass("GDEF")()
1114
+ log.debug("Parsing GDEF")
1115
+ self = ot.GDEF()
1116
+ fields = {
1117
+ "class definition begin": (
1118
+ "GlyphClassDef",
1119
+ lambda lines, font: parseClassDef(lines, font, klass=ot.GlyphClassDef),
1120
+ ),
1121
+ "attachment list begin": ("AttachList", parseAttachList),
1122
+ "carets begin": ("LigCaretList", parseCaretList),
1123
+ "mark attachment class definition begin": (
1124
+ "MarkAttachClassDef",
1125
+ lambda lines, font: parseClassDef(lines, font, klass=ot.MarkAttachClassDef),
1126
+ ),
1127
+ "markfilter set definition begin": ("MarkGlyphSetsDef", parseMarkFilteringSets),
1128
+ }
1129
+ for attr, parser in fields.values():
1130
+ setattr(self, attr, None)
1131
+ while lines.peek() is not None:
1132
+ typ = lines.peek()[0].lower()
1133
+ if typ not in fields:
1134
+ log.debug("Skipping %s", typ)
1135
+ next(lines)
1136
+ continue
1137
+ attr, parser = fields[typ]
1138
+ assert getattr(self, attr) is None, attr
1139
+ setattr(self, attr, parser(lines, font))
1140
+ self.Version = 0x00010000 if self.MarkGlyphSetsDef is None else 0x00010002
1141
+ container.table = self
1142
+ return container
1143
+
1144
+
1145
+ def parseCmap(lines, font):
1146
+ container = ttLib.getTableClass("cmap")()
1147
+ log.debug("Parsing cmap")
1148
+ tables = []
1149
+ while lines.peek() is not None:
1150
+ lines.expect("cmap subtable %d" % len(tables))
1151
+ platId, encId, fmt, lang = [
1152
+ parseCmapId(lines, field)
1153
+ for field in ("platformID", "encodingID", "format", "language")
1154
+ ]
1155
+ table = cmap_classes[fmt](fmt)
1156
+ table.platformID = platId
1157
+ table.platEncID = encId
1158
+ table.language = lang
1159
+ table.cmap = {}
1160
+ line = next(lines)
1161
+ while line[0] != "end subtable":
1162
+ table.cmap[int(line[0], 16)] = line[1]
1163
+ line = next(lines)
1164
+ tables.append(table)
1165
+ container.tableVersion = 0
1166
+ container.tables = tables
1167
+ return container
1168
+
1169
+
1170
+ def parseCmapId(lines, field):
1171
+ line = next(lines)
1172
+ assert field == line[0]
1173
+ return int(line[1])
1174
+
1175
+
1176
+ def parseTable(lines, font, tableTag=None):
1177
+ log.debug("Parsing table")
1178
+ line = lines.peeks()
1179
+ tag = None
1180
+ if line[0].split()[0] == "FontDame":
1181
+ tag = line[0].split()[1]
1182
+ elif " ".join(line[0].split()[:3]) == "Font Chef Table":
1183
+ tag = line[0].split()[3]
1184
+ if tag is not None:
1185
+ next(lines)
1186
+ tag = tag.ljust(4)
1187
+ if tableTag is None:
1188
+ tableTag = tag
1189
+ else:
1190
+ assert tableTag == tag, (tableTag, tag)
1191
+
1192
+ assert (
1193
+ tableTag is not None
1194
+ ), "Don't know what table to parse and data doesn't specify"
1195
+
1196
+ return {
1197
+ "GSUB": parseGSUB,
1198
+ "GPOS": parseGPOS,
1199
+ "GDEF": parseGDEF,
1200
+ "cmap": parseCmap,
1201
+ }[tableTag](lines, font)
1202
+
1203
+
1204
+ class Tokenizer(object):
1205
+ def __init__(self, f):
1206
+ # TODO BytesIO / StringIO as needed? also, figure out whether we work on bytes or unicode
1207
+ lines = iter(f)
1208
+ try:
1209
+ self.filename = f.name
1210
+ except:
1211
+ self.filename = None
1212
+ self.lines = iter(lines)
1213
+ self.line = ""
1214
+ self.lineno = 0
1215
+ self.stoppers = []
1216
+ self.buffer = None
1217
+
1218
+ def __iter__(self):
1219
+ return self
1220
+
1221
+ def _next_line(self):
1222
+ self.lineno += 1
1223
+ line = self.line = next(self.lines)
1224
+ line = [s.strip() for s in line.split("\t")]
1225
+ if len(line) == 1 and not line[0]:
1226
+ del line[0]
1227
+ if line and not line[-1]:
1228
+ log.warning("trailing tab found on line %d: %s" % (self.lineno, self.line))
1229
+ while line and not line[-1]:
1230
+ del line[-1]
1231
+ return line
1232
+
1233
+ def _next_nonempty(self):
1234
+ while True:
1235
+ line = self._next_line()
1236
+ # Skip comments and empty lines
1237
+ if line and line[0] and (line[0][0] != "%" or line[0] == "% subtable"):
1238
+ return line
1239
+
1240
+ def _next_buffered(self):
1241
+ if self.buffer:
1242
+ ret = self.buffer
1243
+ self.buffer = None
1244
+ return ret
1245
+ else:
1246
+ return self._next_nonempty()
1247
+
1248
+ def __next__(self):
1249
+ line = self._next_buffered()
1250
+ if line[0].lower() in self.stoppers:
1251
+ self.buffer = line
1252
+ raise StopIteration
1253
+ return line
1254
+
1255
+ def next(self):
1256
+ return self.__next__()
1257
+
1258
+ def peek(self):
1259
+ if not self.buffer:
1260
+ try:
1261
+ self.buffer = self._next_nonempty()
1262
+ except StopIteration:
1263
+ return None
1264
+ if self.buffer[0].lower() in self.stoppers:
1265
+ return None
1266
+ return self.buffer
1267
+
1268
+ def peeks(self):
1269
+ ret = self.peek()
1270
+ return ret if ret is not None else ("",)
1271
+
1272
+ @contextmanager
1273
+ def between(self, tag):
1274
+ start = tag + " begin"
1275
+ end = tag + " end"
1276
+ self.expectendswith(start)
1277
+ self.stoppers.append(end)
1278
+ yield
1279
+ del self.stoppers[-1]
1280
+ self.expect(tag + " end")
1281
+
1282
+ @contextmanager
1283
+ def until(self, tags):
1284
+ if type(tags) is not tuple:
1285
+ tags = (tags,)
1286
+ self.stoppers.extend(tags)
1287
+ yield
1288
+ del self.stoppers[-len(tags) :]
1289
+
1290
+ def expect(self, s):
1291
+ line = next(self)
1292
+ tag = line[0].lower()
1293
+ assert tag == s, "Expected '%s', got '%s'" % (s, tag)
1294
+ return line
1295
+
1296
+ def expectendswith(self, s):
1297
+ line = next(self)
1298
+ tag = line[0].lower()
1299
+ assert tag.endswith(s), "Expected '*%s', got '%s'" % (s, tag)
1300
+ return line
1301
+
1302
+
1303
+ def build(f, font, tableTag=None):
1304
+ """Convert a Monotype font layout file to an OpenType layout object
1305
+
1306
+ A font object must be passed, but this may be a "dummy" font; it is only
1307
+ used for sorting glyph sets when making coverage tables and to hold the
1308
+ OpenType layout table while it is being built.
1309
+
1310
+ Args:
1311
+ f: A file object.
1312
+ font (TTFont): A font object.
1313
+ tableTag (string): If provided, asserts that the file contains data for the
1314
+ given OpenType table.
1315
+
1316
+ Returns:
1317
+ An object representing the table. (e.g. ``table_G_S_U_B_``)
1318
+ """
1319
+ lines = Tokenizer(f)
1320
+ return parseTable(lines, font, tableTag=tableTag)
1321
+
1322
+
1323
+ def main(args=None, font=None):
1324
+ """Convert a FontDame OTL file to TTX XML
1325
+
1326
+ Writes XML output to stdout.
1327
+
1328
+ Args:
1329
+ args: Command line arguments (``--font``, ``--table``, input files).
1330
+ """
1331
+ import sys
1332
+ from fontTools import configLogger
1333
+ from fontTools.misc.testTools import MockFont
1334
+
1335
+ if args is None:
1336
+ args = sys.argv[1:]
1337
+
1338
+ # configure the library logger (for >= WARNING)
1339
+ configLogger()
1340
+ # comment this out to enable debug messages from mtiLib's logger
1341
+ # log.setLevel(logging.DEBUG)
1342
+
1343
+ import argparse
1344
+
1345
+ parser = argparse.ArgumentParser(
1346
+ "fonttools mtiLib",
1347
+ description=main.__doc__,
1348
+ )
1349
+
1350
+ parser.add_argument(
1351
+ "--font",
1352
+ "-f",
1353
+ metavar="FILE",
1354
+ dest="font",
1355
+ help="Input TTF files (used for glyph classes and sorting coverage tables)",
1356
+ )
1357
+ parser.add_argument(
1358
+ "--table",
1359
+ "-t",
1360
+ metavar="TABLE",
1361
+ dest="tableTag",
1362
+ help="Table to fill (sniffed from input file if not provided)",
1363
+ )
1364
+ parser.add_argument(
1365
+ "inputs", metavar="FILE", type=str, nargs="+", help="Input FontDame .txt files"
1366
+ )
1367
+
1368
+ args = parser.parse_args(args)
1369
+
1370
+ if font is None:
1371
+ if args.font:
1372
+ font = ttLib.TTFont(args.font)
1373
+ else:
1374
+ font = MockFont()
1375
+
1376
+ for f in args.inputs:
1377
+ log.debug("Processing %s", f)
1378
+ with open(f, "rt", encoding="utf-8-sig") as f:
1379
+ table = build(f, font, tableTag=args.tableTag)
1380
+ blob = table.compile(font) # Make sure it compiles
1381
+ decompiled = table.__class__()
1382
+ decompiled.decompile(blob, font) # Make sure it decompiles!
1383
+
1384
+ # continue
1385
+ from fontTools.misc import xmlWriter
1386
+
1387
+ tag = table.tableTag
1388
+ writer = xmlWriter.XMLWriter(sys.stdout)
1389
+ writer.begintag(tag)
1390
+ writer.newline()
1391
+ # table.toXML(writer, font)
1392
+ decompiled.toXML(writer, font)
1393
+ writer.endtag(tag)
1394
+ writer.newline()
1395
+
1396
+
1397
+ if __name__ == "__main__":
1398
+ import sys
1399
+
1400
+ sys.exit(main())
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/mtiLib/__main__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import sys
2
+ from fontTools.mtiLib import main
3
+
4
+ if __name__ == "__main__":
5
+ sys.exit(main())
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """OpenType Layout-related functionality."""
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/builder.py ADDED
The diff for this file is too large to render. See raw diff
 
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/error.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class OpenTypeLibError(Exception):
2
+ def __init__(self, message, location):
3
+ Exception.__init__(self, message)
4
+ self.location = location
5
+
6
+ def __str__(self):
7
+ message = Exception.__str__(self)
8
+ if self.location:
9
+ return f"{self.location}: {message}"
10
+ else:
11
+ return message
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/maxContextCalc.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ["maxCtxFont"]
2
+
3
+
4
+ def maxCtxFont(font):
5
+ """Calculate the usMaxContext value for an entire font."""
6
+
7
+ maxCtx = 0
8
+ for tag in ("GSUB", "GPOS"):
9
+ if tag not in font:
10
+ continue
11
+ table = font[tag].table
12
+ if not table.LookupList:
13
+ continue
14
+ for lookup in table.LookupList.Lookup:
15
+ for st in lookup.SubTable:
16
+ maxCtx = maxCtxSubtable(maxCtx, tag, lookup.LookupType, st)
17
+ return maxCtx
18
+
19
+
20
+ def maxCtxSubtable(maxCtx, tag, lookupType, st):
21
+ """Calculate usMaxContext based on a single lookup table (and an existing
22
+ max value).
23
+ """
24
+
25
+ # single positioning, single / multiple substitution
26
+ if (tag == "GPOS" and lookupType == 1) or (
27
+ tag == "GSUB" and lookupType in (1, 2, 3)
28
+ ):
29
+ maxCtx = max(maxCtx, 1)
30
+
31
+ # pair positioning
32
+ elif tag == "GPOS" and lookupType == 2:
33
+ maxCtx = max(maxCtx, 2)
34
+
35
+ # ligatures
36
+ elif tag == "GSUB" and lookupType == 4:
37
+ for ligatures in st.ligatures.values():
38
+ for ligature in ligatures:
39
+ maxCtx = max(maxCtx, ligature.CompCount)
40
+
41
+ # context
42
+ elif (tag == "GPOS" and lookupType == 7) or (tag == "GSUB" and lookupType == 5):
43
+ maxCtx = maxCtxContextualSubtable(maxCtx, st, "Pos" if tag == "GPOS" else "Sub")
44
+
45
+ # chained context
46
+ elif (tag == "GPOS" and lookupType == 8) or (tag == "GSUB" and lookupType == 6):
47
+ maxCtx = maxCtxContextualSubtable(
48
+ maxCtx, st, "Pos" if tag == "GPOS" else "Sub", "Chain"
49
+ )
50
+
51
+ # extensions
52
+ elif (tag == "GPOS" and lookupType == 9) or (tag == "GSUB" and lookupType == 7):
53
+ maxCtx = maxCtxSubtable(maxCtx, tag, st.ExtensionLookupType, st.ExtSubTable)
54
+
55
+ # reverse-chained context
56
+ elif tag == "GSUB" and lookupType == 8:
57
+ maxCtx = maxCtxContextualRule(maxCtx, st, "Reverse")
58
+
59
+ return maxCtx
60
+
61
+
62
+ def maxCtxContextualSubtable(maxCtx, st, ruleType, chain=""):
63
+ """Calculate usMaxContext based on a contextual feature subtable."""
64
+
65
+ if st.Format == 1:
66
+ for ruleset in getattr(st, "%s%sRuleSet" % (chain, ruleType)):
67
+ if ruleset is None:
68
+ continue
69
+ for rule in getattr(ruleset, "%s%sRule" % (chain, ruleType)):
70
+ if rule is None:
71
+ continue
72
+ maxCtx = maxCtxContextualRule(maxCtx, rule, chain)
73
+
74
+ elif st.Format == 2:
75
+ for ruleset in getattr(st, "%s%sClassSet" % (chain, ruleType)):
76
+ if ruleset is None:
77
+ continue
78
+ for rule in getattr(ruleset, "%s%sClassRule" % (chain, ruleType)):
79
+ if rule is None:
80
+ continue
81
+ maxCtx = maxCtxContextualRule(maxCtx, rule, chain)
82
+
83
+ elif st.Format == 3:
84
+ maxCtx = maxCtxContextualRule(maxCtx, st, chain)
85
+
86
+ return maxCtx
87
+
88
+
89
+ def maxCtxContextualRule(maxCtx, st, chain):
90
+ """Calculate usMaxContext based on a contextual feature rule."""
91
+
92
+ if not chain:
93
+ return max(maxCtx, st.GlyphCount)
94
+ elif chain == "Reverse":
95
+ return max(maxCtx, 1 + st.LookAheadGlyphCount)
96
+ return max(maxCtx, st.InputGlyphCount + st.LookAheadGlyphCount)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/optimize/__init__.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from argparse import RawTextHelpFormatter
2
+ from fontTools.otlLib.optimize.gpos import COMPRESSION_LEVEL, compact
3
+ from fontTools.ttLib import TTFont
4
+
5
+
6
+ def main(args=None):
7
+ """Optimize the layout tables of an existing font"""
8
+ from argparse import ArgumentParser
9
+
10
+ from fontTools import configLogger
11
+
12
+ parser = ArgumentParser(
13
+ prog="otlLib.optimize",
14
+ description=main.__doc__,
15
+ formatter_class=RawTextHelpFormatter,
16
+ )
17
+ parser.add_argument("font")
18
+ parser.add_argument(
19
+ "-o", metavar="OUTPUTFILE", dest="outfile", default=None, help="output file"
20
+ )
21
+ parser.add_argument(
22
+ "--gpos-compression-level",
23
+ help=COMPRESSION_LEVEL.help,
24
+ default=COMPRESSION_LEVEL.default,
25
+ choices=list(range(10)),
26
+ type=int,
27
+ )
28
+ logging_group = parser.add_mutually_exclusive_group(required=False)
29
+ logging_group.add_argument(
30
+ "-v", "--verbose", action="store_true", help="Run more verbosely."
31
+ )
32
+ logging_group.add_argument(
33
+ "-q", "--quiet", action="store_true", help="Turn verbosity off."
34
+ )
35
+ options = parser.parse_args(args)
36
+
37
+ configLogger(
38
+ level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
39
+ )
40
+
41
+ font = TTFont(options.font)
42
+ compact(font, options.gpos_compression_level)
43
+ font.save(options.outfile or options.font)
44
+
45
+
46
+ if __name__ == "__main__":
47
+ import sys
48
+
49
+ if len(sys.argv) > 1:
50
+ sys.exit(main())
51
+ import doctest
52
+
53
+ sys.exit(doctest.testmod().failed)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/optimize/__main__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import sys
2
+ from fontTools.otlLib.optimize import main
3
+
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/otlLib/optimize/gpos.py ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from collections import defaultdict, namedtuple
4
+ from dataclasses import dataclass
5
+ from functools import cached_property, reduce
6
+ from itertools import chain
7
+ from math import log2
8
+ from typing import DefaultDict, Dict, Iterable, List, Sequence, Tuple
9
+
10
+ from fontTools.config import OPTIONS
11
+ from fontTools.misc.intTools import bit_count, bit_indices
12
+ from fontTools.ttLib import TTFont
13
+ from fontTools.ttLib.tables import otBase, otTables
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+ COMPRESSION_LEVEL = OPTIONS[f"{__name__}:COMPRESSION_LEVEL"]
18
+
19
+ # Kept because ufo2ft depends on it, to be removed once ufo2ft uses the config instead
20
+ # https://github.com/fonttools/fonttools/issues/2592
21
+ GPOS_COMPACT_MODE_ENV_KEY = "FONTTOOLS_GPOS_COMPACT_MODE"
22
+ GPOS_COMPACT_MODE_DEFAULT = str(COMPRESSION_LEVEL.default)
23
+
24
+
25
+ def _compression_level_from_env() -> int:
26
+ env_level = GPOS_COMPACT_MODE_DEFAULT
27
+ if GPOS_COMPACT_MODE_ENV_KEY in os.environ:
28
+ import warnings
29
+
30
+ warnings.warn(
31
+ f"'{GPOS_COMPACT_MODE_ENV_KEY}' environment variable is deprecated. "
32
+ "Please set the 'fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL' option "
33
+ "in TTFont.cfg.",
34
+ DeprecationWarning,
35
+ )
36
+
37
+ env_level = os.environ[GPOS_COMPACT_MODE_ENV_KEY]
38
+ if len(env_level) == 1 and env_level in "0123456789":
39
+ return int(env_level)
40
+ raise ValueError(f"Bad {GPOS_COMPACT_MODE_ENV_KEY}={env_level}")
41
+
42
+
43
+ def compact(font: TTFont, level: int) -> TTFont:
44
+ # Ideal plan:
45
+ # 1. Find lookups of Lookup Type 2: Pair Adjustment Positioning Subtable
46
+ # https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-2-pair-adjustment-positioning-subtable
47
+ # 2. Extract glyph-glyph kerning and class-kerning from all present subtables
48
+ # 3. Regroup into different subtable arrangements
49
+ # 4. Put back into the lookup
50
+ #
51
+ # Actual implementation:
52
+ # 2. Only class kerning is optimized currently
53
+ # 3. If the input kerning is already in several subtables, the subtables
54
+ # are not grouped together first; instead each subtable is treated
55
+ # independently, so currently this step is:
56
+ # Split existing subtables into more smaller subtables
57
+ gpos = font.get("GPOS")
58
+
59
+ # If the font does not contain a GPOS table, there is nothing to do.
60
+ if gpos is None:
61
+ return font
62
+
63
+ for lookup in gpos.table.LookupList.Lookup:
64
+ if lookup.LookupType == 2:
65
+ compact_lookup(font, level, lookup)
66
+ elif lookup.LookupType == 9 and lookup.SubTable[0].ExtensionLookupType == 2:
67
+ compact_ext_lookup(font, level, lookup)
68
+
69
+ return font
70
+
71
+
72
+ def compact_lookup(font: TTFont, level: int, lookup: otTables.Lookup) -> None:
73
+ new_subtables = compact_pair_pos(font, level, lookup.SubTable)
74
+ lookup.SubTable = new_subtables
75
+ lookup.SubTableCount = len(new_subtables)
76
+
77
+
78
+ def compact_ext_lookup(font: TTFont, level: int, lookup: otTables.Lookup) -> None:
79
+ new_subtables = compact_pair_pos(
80
+ font, level, [ext_subtable.ExtSubTable for ext_subtable in lookup.SubTable]
81
+ )
82
+ new_ext_subtables = []
83
+ for subtable in new_subtables:
84
+ ext_subtable = otTables.ExtensionPos()
85
+ ext_subtable.Format = 1
86
+ ext_subtable.ExtSubTable = subtable
87
+ new_ext_subtables.append(ext_subtable)
88
+ lookup.SubTable = new_ext_subtables
89
+ lookup.SubTableCount = len(new_ext_subtables)
90
+
91
+
92
+ def compact_pair_pos(
93
+ font: TTFont, level: int, subtables: Sequence[otTables.PairPos]
94
+ ) -> Sequence[otTables.PairPos]:
95
+ new_subtables = []
96
+ for subtable in subtables:
97
+ if subtable.Format == 1:
98
+ # Not doing anything to Format 1 (yet?)
99
+ new_subtables.append(subtable)
100
+ elif subtable.Format == 2:
101
+ new_subtables.extend(compact_class_pairs(font, level, subtable))
102
+ return new_subtables
103
+
104
+
105
+ def compact_class_pairs(
106
+ font: TTFont, level: int, subtable: otTables.PairPos
107
+ ) -> List[otTables.PairPos]:
108
+ from fontTools.otlLib.builder import buildPairPosClassesSubtable
109
+
110
+ subtables = []
111
+ classes1: DefaultDict[int, List[str]] = defaultdict(list)
112
+ for g in subtable.Coverage.glyphs:
113
+ classes1[subtable.ClassDef1.classDefs.get(g, 0)].append(g)
114
+ classes2: DefaultDict[int, List[str]] = defaultdict(list)
115
+ for g, i in subtable.ClassDef2.classDefs.items():
116
+ classes2[i].append(g)
117
+ all_pairs = {}
118
+ for i, class1 in enumerate(subtable.Class1Record):
119
+ for j, class2 in enumerate(class1.Class2Record):
120
+ if is_really_zero(class2):
121
+ continue
122
+ all_pairs[(tuple(sorted(classes1[i])), tuple(sorted(classes2[j])))] = (
123
+ getattr(class2, "Value1", None),
124
+ getattr(class2, "Value2", None),
125
+ )
126
+ grouped_pairs = cluster_pairs_by_class2_coverage_custom_cost(font, all_pairs, level)
127
+ for pairs in grouped_pairs:
128
+ subtables.append(buildPairPosClassesSubtable(pairs, font.getReverseGlyphMap()))
129
+ return subtables
130
+
131
+
132
+ def is_really_zero(class2: otTables.Class2Record) -> bool:
133
+ v1 = getattr(class2, "Value1", None)
134
+ v2 = getattr(class2, "Value2", None)
135
+ return (v1 is None or v1.getEffectiveFormat() == 0) and (
136
+ v2 is None or v2.getEffectiveFormat() == 0
137
+ )
138
+
139
+
140
+ Pairs = Dict[
141
+ Tuple[Tuple[str, ...], Tuple[str, ...]],
142
+ Tuple[otBase.ValueRecord, otBase.ValueRecord],
143
+ ]
144
+
145
+
146
+ # Adapted from https://github.com/fonttools/fonttools/blob/f64f0b42f2d1163b2d85194e0979def539f5dca3/Lib/fontTools/ttLib/tables/otTables.py#L935-L958
147
+ def _getClassRanges(glyphIDs: Iterable[int]):
148
+ glyphIDs = sorted(glyphIDs)
149
+ last = glyphIDs[0]
150
+ ranges = [[last]]
151
+ for glyphID in glyphIDs[1:]:
152
+ if glyphID != last + 1:
153
+ ranges[-1].append(last)
154
+ ranges.append([glyphID])
155
+ last = glyphID
156
+ ranges[-1].append(last)
157
+ return ranges, glyphIDs[0], glyphIDs[-1]
158
+
159
+
160
+ # Adapted from https://github.com/fonttools/fonttools/blob/f64f0b42f2d1163b2d85194e0979def539f5dca3/Lib/fontTools/ttLib/tables/otTables.py#L960-L989
161
+ def _classDef_bytes(
162
+ class_data: List[Tuple[List[Tuple[int, int]], int, int]],
163
+ class_ids: List[int],
164
+ coverage=False,
165
+ ):
166
+ if not class_ids:
167
+ return 0
168
+ first_ranges, min_glyph_id, max_glyph_id = class_data[class_ids[0]]
169
+ range_count = len(first_ranges)
170
+ for i in class_ids[1:]:
171
+ data = class_data[i]
172
+ range_count += len(data[0])
173
+ min_glyph_id = min(min_glyph_id, data[1])
174
+ max_glyph_id = max(max_glyph_id, data[2])
175
+ glyphCount = max_glyph_id - min_glyph_id + 1
176
+ # https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table-format-1
177
+ format1_bytes = 6 + glyphCount * 2
178
+ # https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#class-definition-table-format-2
179
+ format2_bytes = 4 + range_count * 6
180
+ return min(format1_bytes, format2_bytes)
181
+
182
+
183
+ ClusteringContext = namedtuple(
184
+ "ClusteringContext",
185
+ [
186
+ "lines",
187
+ "all_class1",
188
+ "all_class1_data",
189
+ "all_class2_data",
190
+ "valueFormat1_bytes",
191
+ "valueFormat2_bytes",
192
+ ],
193
+ )
194
+
195
+
196
+ @dataclass
197
+ class Cluster:
198
+ ctx: ClusteringContext
199
+ indices_bitmask: int
200
+
201
+ @cached_property
202
+ def indices(self):
203
+ return bit_indices(self.indices_bitmask)
204
+
205
+ @cached_property
206
+ def column_indices(self):
207
+ # Indices of columns that have a 1 in at least 1 line
208
+ # => binary OR all the lines
209
+ bitmask = reduce(int.__or__, (self.ctx.lines[i] for i in self.indices))
210
+ return bit_indices(bitmask)
211
+
212
+ @property
213
+ def width(self):
214
+ # Add 1 because Class2=0 cannot be used but needs to be encoded.
215
+ return len(self.column_indices) + 1
216
+
217
+ @cached_property
218
+ def cost(self):
219
+ return (
220
+ # 2 bytes to store the offset to this subtable in the Lookup table above
221
+ 2
222
+ # Contents of the subtable
223
+ # From: https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#pair-adjustment-positioning-format-2-class-pair-adjustment
224
+ # uint16 posFormat Format identifier: format = 2
225
+ + 2
226
+ # Offset16 coverageOffset Offset to Coverage table, from beginning of PairPos subtable.
227
+ + 2
228
+ + self.coverage_bytes
229
+ # uint16 valueFormat1 ValueRecord definition — for the first glyph of the pair (may be zero).
230
+ + 2
231
+ # uint16 valueFormat2 ValueRecord definition — for the second glyph of the pair (may be zero).
232
+ + 2
233
+ # Offset16 classDef1Offset Offset to ClassDef table, from beginning of PairPos subtable — for the first glyph of the pair.
234
+ + 2
235
+ + self.classDef1_bytes
236
+ # Offset16 classDef2Offset Offset to ClassDef table, from beginning of PairPos subtable — for the second glyph of the pair.
237
+ + 2
238
+ + self.classDef2_bytes
239
+ # uint16 class1Count Number of classes in classDef1 table — includes Class 0.
240
+ + 2
241
+ # uint16 class2Count Number of classes in classDef2 table — includes Class 0.
242
+ + 2
243
+ # Class1Record class1Records[class1Count] Array of Class1 records, ordered by classes in classDef1.
244
+ + (self.ctx.valueFormat1_bytes + self.ctx.valueFormat2_bytes)
245
+ * len(self.indices)
246
+ * self.width
247
+ )
248
+
249
+ @property
250
+ def coverage_bytes(self):
251
+ format1_bytes = (
252
+ # From https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-format-1
253
+ # uint16 coverageFormat Format identifier — format = 1
254
+ # uint16 glyphCount Number of glyphs in the glyph array
255
+ 4
256
+ # uint16 glyphArray[glyphCount] Array of glyph IDs — in numerical order
257
+ + sum(len(self.ctx.all_class1[i]) for i in self.indices) * 2
258
+ )
259
+ ranges = sorted(
260
+ chain.from_iterable(self.ctx.all_class1_data[i][0] for i in self.indices)
261
+ )
262
+ merged_range_count = 0
263
+ last = None
264
+ for start, end in ranges:
265
+ if last is not None and start != last + 1:
266
+ merged_range_count += 1
267
+ last = end
268
+ format2_bytes = (
269
+ # From https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#coverage-format-2
270
+ # uint16 coverageFormat Format identifier — format = 2
271
+ # uint16 rangeCount Number of RangeRecords
272
+ 4
273
+ # RangeRecord rangeRecords[rangeCount] Array of glyph ranges — ordered by startGlyphID.
274
+ # uint16 startGlyphID First glyph ID in the range
275
+ # uint16 endGlyphID Last glyph ID in the range
276
+ # uint16 startCoverageIndex Coverage Index of first glyph ID in range
277
+ + merged_range_count * 6
278
+ )
279
+ return min(format1_bytes, format2_bytes)
280
+
281
+ @property
282
+ def classDef1_bytes(self):
283
+ # We can skip encoding one of the Class1 definitions, and use
284
+ # Class1=0 to represent it instead, because Class1 is gated by the
285
+ # Coverage definition. Use Class1=0 for the highest byte savings.
286
+ # Going through all options takes too long, pick the biggest class
287
+ # = what happens in otlLib.builder.ClassDefBuilder.classes()
288
+ biggest_index = max(self.indices, key=lambda i: len(self.ctx.all_class1[i]))
289
+ return _classDef_bytes(
290
+ self.ctx.all_class1_data, [i for i in self.indices if i != biggest_index]
291
+ )
292
+
293
+ @property
294
+ def classDef2_bytes(self):
295
+ # All Class2 need to be encoded because we can't use Class2=0
296
+ return _classDef_bytes(self.ctx.all_class2_data, self.column_indices)
297
+
298
+
299
+ def cluster_pairs_by_class2_coverage_custom_cost(
300
+ font: TTFont,
301
+ pairs: Pairs,
302
+ compression: int = 5,
303
+ ) -> List[Pairs]:
304
+ if not pairs:
305
+ # The subtable was actually empty?
306
+ return [pairs]
307
+
308
+ # Sorted for reproducibility/determinism
309
+ all_class1 = sorted(set(pair[0] for pair in pairs))
310
+ all_class2 = sorted(set(pair[1] for pair in pairs))
311
+
312
+ # Use Python's big ints for binary vectors representing each line
313
+ lines = [
314
+ sum(
315
+ 1 << i if (class1, class2) in pairs else 0
316
+ for i, class2 in enumerate(all_class2)
317
+ )
318
+ for class1 in all_class1
319
+ ]
320
+
321
+ # Map glyph names to ids and work with ints throughout for ClassDef formats
322
+ name_to_id = font.getReverseGlyphMap()
323
+ # Each entry in the arrays below is (range_count, min_glyph_id, max_glyph_id)
324
+ all_class1_data = [
325
+ _getClassRanges(name_to_id[name] for name in cls) for cls in all_class1
326
+ ]
327
+ all_class2_data = [
328
+ _getClassRanges(name_to_id[name] for name in cls) for cls in all_class2
329
+ ]
330
+
331
+ format1 = 0
332
+ format2 = 0
333
+ for pair, value in pairs.items():
334
+ format1 |= value[0].getEffectiveFormat() if value[0] else 0
335
+ format2 |= value[1].getEffectiveFormat() if value[1] else 0
336
+ valueFormat1_bytes = bit_count(format1) * 2
337
+ valueFormat2_bytes = bit_count(format2) * 2
338
+
339
+ ctx = ClusteringContext(
340
+ lines,
341
+ all_class1,
342
+ all_class1_data,
343
+ all_class2_data,
344
+ valueFormat1_bytes,
345
+ valueFormat2_bytes,
346
+ )
347
+
348
+ cluster_cache: Dict[int, Cluster] = {}
349
+
350
+ def make_cluster(indices: int) -> Cluster:
351
+ cluster = cluster_cache.get(indices, None)
352
+ if cluster is not None:
353
+ return cluster
354
+ cluster = Cluster(ctx, indices)
355
+ cluster_cache[indices] = cluster
356
+ return cluster
357
+
358
+ def merge(cluster: Cluster, other: Cluster) -> Cluster:
359
+ return make_cluster(cluster.indices_bitmask | other.indices_bitmask)
360
+
361
+ # Agglomerative clustering by hand, checking the cost gain of the new
362
+ # cluster against the previously separate clusters
363
+ # Start with 1 cluster per line
364
+ # cluster = set of lines = new subtable
365
+ clusters = [make_cluster(1 << i) for i in range(len(lines))]
366
+
367
+ # Cost of 1 cluster with everything
368
+ # `(1 << len) - 1` gives a bitmask full of 1's of length `len`
369
+ cost_before_splitting = make_cluster((1 << len(lines)) - 1).cost
370
+ log.debug(f" len(clusters) = {len(clusters)}")
371
+
372
+ while len(clusters) > 1:
373
+ lowest_cost_change = None
374
+ best_cluster_index = None
375
+ best_other_index = None
376
+ best_merged = None
377
+ for i, cluster in enumerate(clusters):
378
+ for j, other in enumerate(clusters[i + 1 :]):
379
+ merged = merge(cluster, other)
380
+ cost_change = merged.cost - cluster.cost - other.cost
381
+ if lowest_cost_change is None or cost_change < lowest_cost_change:
382
+ lowest_cost_change = cost_change
383
+ best_cluster_index = i
384
+ best_other_index = i + 1 + j
385
+ best_merged = merged
386
+ assert lowest_cost_change is not None
387
+ assert best_cluster_index is not None
388
+ assert best_other_index is not None
389
+ assert best_merged is not None
390
+
391
+ # If the best merge we found is still taking down the file size, then
392
+ # there's no question: we must do it, because it's beneficial in both
393
+ # ways (lower file size and lower number of subtables). However, if the
394
+ # best merge we found is not reducing file size anymore, then we need to
395
+ # look at the other stop criteria = the compression factor.
396
+ if lowest_cost_change > 0:
397
+ # Stop critera: check whether we should keep merging.
398
+ # Compute size reduction brought by splitting
399
+ cost_after_splitting = sum(c.cost for c in clusters)
400
+ # size_reduction so that after = before * (1 - size_reduction)
401
+ # E.g. before = 1000, after = 800, 1 - 800/1000 = 0.2
402
+ size_reduction = 1 - cost_after_splitting / cost_before_splitting
403
+
404
+ # Force more merging by taking into account the compression number.
405
+ # Target behaviour: compression number = 1 to 9, default 5 like gzip
406
+ # - 1 = accept to add 1 subtable to reduce size by 50%
407
+ # - 5 = accept to add 5 subtables to reduce size by 50%
408
+ # See https://github.com/harfbuzz/packtab/blob/master/Lib/packTab/__init__.py#L690-L691
409
+ # Given the size reduction we have achieved so far, compute how many
410
+ # new subtables are acceptable.
411
+ max_new_subtables = -log2(1 - size_reduction) * compression
412
+ log.debug(
413
+ f" len(clusters) = {len(clusters):3d} size_reduction={size_reduction:5.2f} max_new_subtables={max_new_subtables}",
414
+ )
415
+ if compression == 9:
416
+ # Override level 9 to mean: create any number of subtables
417
+ max_new_subtables = len(clusters)
418
+
419
+ # If we have managed to take the number of new subtables below the
420
+ # threshold, then we can stop.
421
+ if len(clusters) <= max_new_subtables + 1:
422
+ break
423
+
424
+ # No reason to stop yet, do the merge and move on to the next.
425
+ del clusters[best_other_index]
426
+ clusters[best_cluster_index] = best_merged
427
+
428
+ # All clusters are final; turn bitmasks back into the "Pairs" format
429
+ pairs_by_class1: Dict[Tuple[str, ...], Pairs] = defaultdict(dict)
430
+ for pair, values in pairs.items():
431
+ pairs_by_class1[pair[0]][pair] = values
432
+ pairs_groups: List[Pairs] = []
433
+ for cluster in clusters:
434
+ pairs_group: Pairs = dict()
435
+ for i in cluster.indices:
436
+ class1 = all_class1[i]
437
+ pairs_group.update(pairs_by_class1[class1])
438
+ pairs_groups.append(pairs_group)
439
+ return pairs_groups
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Empty __init__.py file to signal Python this directory is a package."""
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/areaPen.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Calculate the area of a glyph."""
2
+
3
+ from fontTools.pens.basePen import BasePen
4
+
5
+
6
+ __all__ = ["AreaPen"]
7
+
8
+
9
+ class AreaPen(BasePen):
10
+ def __init__(self, glyphset=None):
11
+ BasePen.__init__(self, glyphset)
12
+ self.value = 0
13
+
14
+ def _moveTo(self, p0):
15
+ self._p0 = self._startPoint = p0
16
+
17
+ def _lineTo(self, p1):
18
+ x0, y0 = self._p0
19
+ x1, y1 = p1
20
+ self.value -= (x1 - x0) * (y1 + y0) * 0.5
21
+ self._p0 = p1
22
+
23
+ def _qCurveToOne(self, p1, p2):
24
+ # https://github.com/Pomax/bezierinfo/issues/44
25
+ p0 = self._p0
26
+ x0, y0 = p0[0], p0[1]
27
+ x1, y1 = p1[0] - x0, p1[1] - y0
28
+ x2, y2 = p2[0] - x0, p2[1] - y0
29
+ self.value -= (x2 * y1 - x1 * y2) / 3
30
+ self._lineTo(p2)
31
+ self._p0 = p2
32
+
33
+ def _curveToOne(self, p1, p2, p3):
34
+ # https://github.com/Pomax/bezierinfo/issues/44
35
+ p0 = self._p0
36
+ x0, y0 = p0[0], p0[1]
37
+ x1, y1 = p1[0] - x0, p1[1] - y0
38
+ x2, y2 = p2[0] - x0, p2[1] - y0
39
+ x3, y3 = p3[0] - x0, p3[1] - y0
40
+ self.value -= (x1 * (-y2 - y3) + x2 * (y1 - 2 * y3) + x3 * (y1 + 2 * y2)) * 0.15
41
+ self._lineTo(p3)
42
+ self._p0 = p3
43
+
44
+ def _closePath(self):
45
+ self._lineTo(self._startPoint)
46
+ del self._p0, self._startPoint
47
+
48
+ def _endPath(self):
49
+ if self._p0 != self._startPoint:
50
+ # Area is not defined for open contours.
51
+ raise NotImplementedError
52
+ del self._p0, self._startPoint
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/cairoPen.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pen to draw to a Cairo graphics library context."""
2
+
3
+ from fontTools.pens.basePen import BasePen
4
+
5
+
6
+ __all__ = ["CairoPen"]
7
+
8
+
9
+ class CairoPen(BasePen):
10
+ """Pen to draw to a Cairo graphics library context."""
11
+
12
+ def __init__(self, glyphSet, context):
13
+ BasePen.__init__(self, glyphSet)
14
+ self.context = context
15
+
16
+ def _moveTo(self, p):
17
+ self.context.move_to(*p)
18
+
19
+ def _lineTo(self, p):
20
+ self.context.line_to(*p)
21
+
22
+ def _curveToOne(self, p1, p2, p3):
23
+ self.context.curve_to(*p1, *p2, *p3)
24
+
25
+ def _closePath(self):
26
+ self.context.close_path()
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/cocoaPen.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.pens.basePen import BasePen
2
+
3
+
4
+ __all__ = ["CocoaPen"]
5
+
6
+
7
+ class CocoaPen(BasePen):
8
+ def __init__(self, glyphSet, path=None):
9
+ BasePen.__init__(self, glyphSet)
10
+ if path is None:
11
+ from AppKit import NSBezierPath
12
+
13
+ path = NSBezierPath.bezierPath()
14
+ self.path = path
15
+
16
+ def _moveTo(self, p):
17
+ self.path.moveToPoint_(p)
18
+
19
+ def _lineTo(self, p):
20
+ self.path.lineToPoint_(p)
21
+
22
+ def _curveToOne(self, p1, p2, p3):
23
+ self.path.curveToPoint_controlPoint1_controlPoint2_(p3, p1, p2)
24
+
25
+ def _closePath(self):
26
+ self.path.closePath()
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/cu2quPen.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Google Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import operator
16
+ from fontTools.cu2qu import curve_to_quadratic, curves_to_quadratic
17
+ from fontTools.pens.basePen import decomposeSuperBezierSegment
18
+ from fontTools.pens.filterPen import FilterPen
19
+ from fontTools.pens.reverseContourPen import ReverseContourPen
20
+ from fontTools.pens.pointPen import BasePointToSegmentPen
21
+ from fontTools.pens.pointPen import ReverseContourPointPen
22
+
23
+
24
+ class Cu2QuPen(FilterPen):
25
+ """A filter pen to convert cubic bezier curves to quadratic b-splines
26
+ using the FontTools SegmentPen protocol.
27
+
28
+ Args:
29
+
30
+ other_pen: another SegmentPen used to draw the transformed outline.
31
+ max_err: maximum approximation error in font units. For optimal results,
32
+ if you know the UPEM of the font, we recommend setting this to a
33
+ value equal, or close to UPEM / 1000.
34
+ reverse_direction: flip the contours' direction but keep starting point.
35
+ stats: a dictionary counting the point numbers of quadratic segments.
36
+ all_quadratic: if True (default), only quadratic b-splines are generated.
37
+ if False, quadratic curves or cubic curves are generated depending
38
+ on which one is more economical.
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ other_pen,
44
+ max_err,
45
+ reverse_direction=False,
46
+ stats=None,
47
+ all_quadratic=True,
48
+ ):
49
+ if reverse_direction:
50
+ other_pen = ReverseContourPen(other_pen)
51
+ super().__init__(other_pen)
52
+ self.max_err = max_err
53
+ self.stats = stats
54
+ self.all_quadratic = all_quadratic
55
+
56
+ def _convert_curve(self, pt1, pt2, pt3):
57
+ curve = (self.current_pt, pt1, pt2, pt3)
58
+ result = curve_to_quadratic(curve, self.max_err, self.all_quadratic)
59
+ if self.stats is not None:
60
+ n = str(len(result) - 2)
61
+ self.stats[n] = self.stats.get(n, 0) + 1
62
+ if self.all_quadratic:
63
+ self.qCurveTo(*result[1:])
64
+ else:
65
+ if len(result) == 3:
66
+ self.qCurveTo(*result[1:])
67
+ else:
68
+ assert len(result) == 4
69
+ super().curveTo(*result[1:])
70
+
71
+ def curveTo(self, *points):
72
+ n = len(points)
73
+ if n == 3:
74
+ # this is the most common case, so we special-case it
75
+ self._convert_curve(*points)
76
+ elif n > 3:
77
+ for segment in decomposeSuperBezierSegment(points):
78
+ self._convert_curve(*segment)
79
+ else:
80
+ self.qCurveTo(*points)
81
+
82
+
83
+ class Cu2QuPointPen(BasePointToSegmentPen):
84
+ """A filter pen to convert cubic bezier curves to quadratic b-splines
85
+ using the FontTools PointPen protocol.
86
+
87
+ Args:
88
+ other_point_pen: another PointPen used to draw the transformed outline.
89
+ max_err: maximum approximation error in font units. For optimal results,
90
+ if you know the UPEM of the font, we recommend setting this to a
91
+ value equal, or close to UPEM / 1000.
92
+ reverse_direction: reverse the winding direction of all contours.
93
+ stats: a dictionary counting the point numbers of quadratic segments.
94
+ all_quadratic: if True (default), only quadratic b-splines are generated.
95
+ if False, quadratic curves or cubic curves are generated depending
96
+ on which one is more economical.
97
+ """
98
+
99
+ __points_required = {
100
+ "move": (1, operator.eq),
101
+ "line": (1, operator.eq),
102
+ "qcurve": (2, operator.ge),
103
+ "curve": (3, operator.eq),
104
+ }
105
+
106
+ def __init__(
107
+ self,
108
+ other_point_pen,
109
+ max_err,
110
+ reverse_direction=False,
111
+ stats=None,
112
+ all_quadratic=True,
113
+ ):
114
+ BasePointToSegmentPen.__init__(self)
115
+ if reverse_direction:
116
+ self.pen = ReverseContourPointPen(other_point_pen)
117
+ else:
118
+ self.pen = other_point_pen
119
+ self.max_err = max_err
120
+ self.stats = stats
121
+ self.all_quadratic = all_quadratic
122
+
123
+ def _flushContour(self, segments):
124
+ assert len(segments) >= 1
125
+ closed = segments[0][0] != "move"
126
+ new_segments = []
127
+ prev_points = segments[-1][1]
128
+ prev_on_curve = prev_points[-1][0]
129
+ for segment_type, points in segments:
130
+ if segment_type == "curve":
131
+ for sub_points in self._split_super_bezier_segments(points):
132
+ on_curve, smooth, name, kwargs = sub_points[-1]
133
+ bcp1, bcp2 = sub_points[0][0], sub_points[1][0]
134
+ cubic = [prev_on_curve, bcp1, bcp2, on_curve]
135
+ quad = curve_to_quadratic(cubic, self.max_err, self.all_quadratic)
136
+ if self.stats is not None:
137
+ n = str(len(quad) - 2)
138
+ self.stats[n] = self.stats.get(n, 0) + 1
139
+ new_points = [(pt, False, None, {}) for pt in quad[1:-1]]
140
+ new_points.append((on_curve, smooth, name, kwargs))
141
+ if self.all_quadratic or len(new_points) == 2:
142
+ new_segments.append(["qcurve", new_points])
143
+ else:
144
+ new_segments.append(["curve", new_points])
145
+ prev_on_curve = sub_points[-1][0]
146
+ else:
147
+ new_segments.append([segment_type, points])
148
+ prev_on_curve = points[-1][0]
149
+ if closed:
150
+ # the BasePointToSegmentPen.endPath method that calls _flushContour
151
+ # rotates the point list of closed contours so that they end with
152
+ # the first on-curve point. We restore the original starting point.
153
+ new_segments = new_segments[-1:] + new_segments[:-1]
154
+ self._drawPoints(new_segments)
155
+
156
+ def _split_super_bezier_segments(self, points):
157
+ sub_segments = []
158
+ # n is the number of control points
159
+ n = len(points) - 1
160
+ if n == 2:
161
+ # a simple bezier curve segment
162
+ sub_segments.append(points)
163
+ elif n > 2:
164
+ # a "super" bezier; decompose it
165
+ on_curve, smooth, name, kwargs = points[-1]
166
+ num_sub_segments = n - 1
167
+ for i, sub_points in enumerate(
168
+ decomposeSuperBezierSegment([pt for pt, _, _, _ in points])
169
+ ):
170
+ new_segment = []
171
+ for point in sub_points[:-1]:
172
+ new_segment.append((point, False, None, {}))
173
+ if i == (num_sub_segments - 1):
174
+ # the last on-curve keeps its original attributes
175
+ new_segment.append((on_curve, smooth, name, kwargs))
176
+ else:
177
+ # on-curves of sub-segments are always "smooth"
178
+ new_segment.append((sub_points[-1], True, None, {}))
179
+ sub_segments.append(new_segment)
180
+ else:
181
+ raise AssertionError("expected 2 control points, found: %d" % n)
182
+ return sub_segments
183
+
184
+ def _drawPoints(self, segments):
185
+ pen = self.pen
186
+ pen.beginPath()
187
+ last_offcurves = []
188
+ points_required = self.__points_required
189
+ for i, (segment_type, points) in enumerate(segments):
190
+ if segment_type in points_required:
191
+ n, op = points_required[segment_type]
192
+ assert op(len(points), n), (
193
+ f"illegal {segment_type!r} segment point count: "
194
+ f"expected {n}, got {len(points)}"
195
+ )
196
+ offcurves = points[:-1]
197
+ if i == 0:
198
+ # any off-curve points preceding the first on-curve
199
+ # will be appended at the end of the contour
200
+ last_offcurves = offcurves
201
+ else:
202
+ for pt, smooth, name, kwargs in offcurves:
203
+ pen.addPoint(pt, None, smooth, name, **kwargs)
204
+ pt, smooth, name, kwargs = points[-1]
205
+ if pt is None:
206
+ assert segment_type == "qcurve"
207
+ # special quadratic contour with no on-curve points:
208
+ # we need to skip the "None" point. See also the Pen
209
+ # protocol's qCurveTo() method and fontTools.pens.basePen
210
+ pass
211
+ else:
212
+ pen.addPoint(pt, segment_type, smooth, name, **kwargs)
213
+ else:
214
+ raise AssertionError("unexpected segment type: %r" % segment_type)
215
+ for pt, smooth, name, kwargs in last_offcurves:
216
+ pen.addPoint(pt, None, smooth, name, **kwargs)
217
+ pen.endPath()
218
+
219
+ def addComponent(self, baseGlyphName, transformation):
220
+ assert self.currentPath is None
221
+ self.pen.addComponent(baseGlyphName, transformation)
222
+
223
+
224
+ class Cu2QuMultiPen:
225
+ """A filter multi-pen to convert cubic bezier curves to quadratic b-splines
226
+ in a interpolation-compatible manner, using the FontTools SegmentPen protocol.
227
+
228
+ Args:
229
+
230
+ other_pens: list of SegmentPens used to draw the transformed outlines.
231
+ max_err: maximum approximation error in font units. For optimal results,
232
+ if you know the UPEM of the font, we recommend setting this to a
233
+ value equal, or close to UPEM / 1000.
234
+ reverse_direction: flip the contours' direction but keep starting point.
235
+
236
+ This pen does not follow the normal SegmentPen protocol. Instead, its
237
+ moveTo/lineTo/qCurveTo/curveTo methods take a list of tuples that are
238
+ arguments that would normally be passed to a SegmentPen, one item for
239
+ each of the pens in other_pens.
240
+ """
241
+
242
+ # TODO Simplify like 3e8ebcdce592fe8a59ca4c3a294cc9724351e1ce
243
+ # Remove start_pts and _add_moveTO
244
+
245
+ def __init__(self, other_pens, max_err, reverse_direction=False):
246
+ if reverse_direction:
247
+ other_pens = [
248
+ ReverseContourPen(pen, outputImpliedClosingLine=True)
249
+ for pen in other_pens
250
+ ]
251
+ self.pens = other_pens
252
+ self.max_err = max_err
253
+ self.start_pts = None
254
+ self.current_pts = None
255
+
256
+ def _check_contour_is_open(self):
257
+ if self.current_pts is None:
258
+ raise AssertionError("moveTo is required")
259
+
260
+ def _check_contour_is_closed(self):
261
+ if self.current_pts is not None:
262
+ raise AssertionError("closePath or endPath is required")
263
+
264
+ def _add_moveTo(self):
265
+ if self.start_pts is not None:
266
+ for pt, pen in zip(self.start_pts, self.pens):
267
+ pen.moveTo(*pt)
268
+ self.start_pts = None
269
+
270
+ def moveTo(self, pts):
271
+ self._check_contour_is_closed()
272
+ self.start_pts = self.current_pts = pts
273
+ self._add_moveTo()
274
+
275
+ def lineTo(self, pts):
276
+ self._check_contour_is_open()
277
+ self._add_moveTo()
278
+ for pt, pen in zip(pts, self.pens):
279
+ pen.lineTo(*pt)
280
+ self.current_pts = pts
281
+
282
+ def qCurveTo(self, pointsList):
283
+ self._check_contour_is_open()
284
+ if len(pointsList[0]) == 1:
285
+ self.lineTo([(points[0],) for points in pointsList])
286
+ return
287
+ self._add_moveTo()
288
+ current_pts = []
289
+ for points, pen in zip(pointsList, self.pens):
290
+ pen.qCurveTo(*points)
291
+ current_pts.append((points[-1],))
292
+ self.current_pts = current_pts
293
+
294
+ def _curves_to_quadratic(self, pointsList):
295
+ curves = []
296
+ for current_pt, points in zip(self.current_pts, pointsList):
297
+ curves.append(current_pt + points)
298
+ quadratics = curves_to_quadratic(curves, [self.max_err] * len(curves))
299
+ pointsList = []
300
+ for quadratic in quadratics:
301
+ pointsList.append(quadratic[1:])
302
+ self.qCurveTo(pointsList)
303
+
304
+ def curveTo(self, pointsList):
305
+ self._check_contour_is_open()
306
+ self._curves_to_quadratic(pointsList)
307
+
308
+ def closePath(self):
309
+ self._check_contour_is_open()
310
+ if self.start_pts is None:
311
+ for pen in self.pens:
312
+ pen.closePath()
313
+ self.current_pts = self.start_pts = None
314
+
315
+ def endPath(self):
316
+ self._check_contour_is_open()
317
+ if self.start_pts is None:
318
+ for pen in self.pens:
319
+ pen.endPath()
320
+ self.current_pts = self.start_pts = None
321
+
322
+ def addComponent(self, glyphName, transformations):
323
+ self._check_contour_is_closed()
324
+ for trans, pen in zip(transformations, self.pens):
325
+ pen.addComponent(glyphName, trans)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/freetypePen.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ """Pen to rasterize paths with FreeType."""
4
+
5
+ __all__ = ["FreeTypePen"]
6
+
7
+ import os
8
+ import ctypes
9
+ import platform
10
+ import subprocess
11
+ import collections
12
+ import math
13
+
14
+ import freetype
15
+ from freetype.raw import FT_Outline_Get_Bitmap, FT_Outline_Get_BBox, FT_Outline_Get_CBox
16
+ from freetype.ft_types import FT_Pos
17
+ from freetype.ft_structs import FT_Vector, FT_BBox, FT_Bitmap, FT_Outline
18
+ from freetype.ft_enums import (
19
+ FT_OUTLINE_NONE,
20
+ FT_OUTLINE_EVEN_ODD_FILL,
21
+ FT_PIXEL_MODE_GRAY,
22
+ FT_CURVE_TAG_ON,
23
+ FT_CURVE_TAG_CONIC,
24
+ FT_CURVE_TAG_CUBIC,
25
+ )
26
+ from freetype.ft_errors import FT_Exception
27
+
28
+ from fontTools.pens.basePen import BasePen, PenError
29
+ from fontTools.misc.roundTools import otRound
30
+ from fontTools.misc.transform import Transform
31
+
32
+ Contour = collections.namedtuple("Contour", ("points", "tags"))
33
+
34
+
35
+ class FreeTypePen(BasePen):
36
+ """Pen to rasterize paths with FreeType. Requires `freetype-py` module.
37
+
38
+ Constructs ``FT_Outline`` from the paths, and renders it within a bitmap
39
+ buffer.
40
+
41
+ For ``array()`` and ``show()``, `numpy` and `matplotlib` must be installed.
42
+ For ``image()``, `Pillow` is required. Each module is lazily loaded when the
43
+ corresponding method is called.
44
+
45
+ Args:
46
+ glyphSet: a dictionary of drawable glyph objects keyed by name
47
+ used to resolve component references in composite glyphs.
48
+
49
+ Examples:
50
+ If `numpy` and `matplotlib` is available, the following code will
51
+ show the glyph image of `fi` in a new window::
52
+
53
+ from fontTools.ttLib import TTFont
54
+ from fontTools.pens.freetypePen import FreeTypePen
55
+ from fontTools.misc.transform import Offset
56
+ pen = FreeTypePen(None)
57
+ font = TTFont('SourceSansPro-Regular.otf')
58
+ glyph = font.getGlyphSet()['fi']
59
+ glyph.draw(pen)
60
+ width, ascender, descender = glyph.width, font['OS/2'].usWinAscent, -font['OS/2'].usWinDescent
61
+ height = ascender - descender
62
+ pen.show(width=width, height=height, transform=Offset(0, -descender))
63
+
64
+ Combining with `uharfbuzz`, you can typeset a chunk of glyphs in a pen::
65
+
66
+ import uharfbuzz as hb
67
+ from fontTools.pens.freetypePen import FreeTypePen
68
+ from fontTools.pens.transformPen import TransformPen
69
+ from fontTools.misc.transform import Offset
70
+
71
+ en1, en2, ar, ja = 'Typesetting', 'Jeff', 'صف الحروف', 'たいぷせっと'
72
+ for text, font_path, direction, typo_ascender, typo_descender, vhea_ascender, vhea_descender, contain, features in (
73
+ (en1, 'NotoSans-Regular.ttf', 'ltr', 2189, -600, None, None, False, {"kern": True, "liga": True}),
74
+ (en2, 'NotoSans-Regular.ttf', 'ltr', 2189, -600, None, None, True, {"kern": True, "liga": True}),
75
+ (ar, 'NotoSansArabic-Regular.ttf', 'rtl', 1374, -738, None, None, False, {"kern": True, "liga": True}),
76
+ (ja, 'NotoSansJP-Regular.otf', 'ltr', 880, -120, 500, -500, False, {"palt": True, "kern": True}),
77
+ (ja, 'NotoSansJP-Regular.otf', 'ttb', 880, -120, 500, -500, False, {"vert": True, "vpal": True, "vkrn": True})
78
+ ):
79
+ blob = hb.Blob.from_file_path(font_path)
80
+ face = hb.Face(blob)
81
+ font = hb.Font(face)
82
+ buf = hb.Buffer()
83
+ buf.direction = direction
84
+ buf.add_str(text)
85
+ buf.guess_segment_properties()
86
+ hb.shape(font, buf, features)
87
+
88
+ x, y = 0, 0
89
+ pen = FreeTypePen(None)
90
+ for info, pos in zip(buf.glyph_infos, buf.glyph_positions):
91
+ gid = info.codepoint
92
+ transformed = TransformPen(pen, Offset(x + pos.x_offset, y + pos.y_offset))
93
+ font.draw_glyph_with_pen(gid, transformed)
94
+ x += pos.x_advance
95
+ y += pos.y_advance
96
+
97
+ offset, width, height = None, None, None
98
+ if direction in ('ltr', 'rtl'):
99
+ offset = (0, -typo_descender)
100
+ width = x
101
+ height = typo_ascender - typo_descender
102
+ else:
103
+ offset = (-vhea_descender, -y)
104
+ width = vhea_ascender - vhea_descender
105
+ height = -y
106
+ pen.show(width=width, height=height, transform=Offset(*offset), contain=contain)
107
+
108
+ For Jupyter Notebook, the rendered image will be displayed in a cell if
109
+ you replace ``show()`` with ``image()`` in the examples.
110
+ """
111
+
112
+ def __init__(self, glyphSet):
113
+ BasePen.__init__(self, glyphSet)
114
+ self.contours = []
115
+
116
+ def outline(self, transform=None, evenOdd=False):
117
+ """Converts the current contours to ``FT_Outline``.
118
+
119
+ Args:
120
+ transform: An optional 6-tuple containing an affine transformation,
121
+ or a ``Transform`` object from the ``fontTools.misc.transform``
122
+ module.
123
+ evenOdd: Pass ``True`` for even-odd fill instead of non-zero.
124
+ """
125
+ transform = transform or Transform()
126
+ if not hasattr(transform, "transformPoint"):
127
+ transform = Transform(*transform)
128
+ n_contours = len(self.contours)
129
+ n_points = sum((len(contour.points) for contour in self.contours))
130
+ points = []
131
+ for contour in self.contours:
132
+ for point in contour.points:
133
+ point = transform.transformPoint(point)
134
+ points.append(
135
+ FT_Vector(
136
+ FT_Pos(otRound(point[0] * 64)), FT_Pos(otRound(point[1] * 64))
137
+ )
138
+ )
139
+ tags = []
140
+ for contour in self.contours:
141
+ for tag in contour.tags:
142
+ tags.append(tag)
143
+ contours = []
144
+ contours_sum = 0
145
+ for contour in self.contours:
146
+ contours_sum += len(contour.points)
147
+ contours.append(contours_sum - 1)
148
+ flags = FT_OUTLINE_EVEN_ODD_FILL if evenOdd else FT_OUTLINE_NONE
149
+ return FT_Outline(
150
+ (ctypes.c_short)(n_contours),
151
+ (ctypes.c_short)(n_points),
152
+ (FT_Vector * n_points)(*points),
153
+ (ctypes.c_ubyte * n_points)(*tags),
154
+ (ctypes.c_short * n_contours)(*contours),
155
+ (ctypes.c_int)(flags),
156
+ )
157
+
158
+ def buffer(
159
+ self, width=None, height=None, transform=None, contain=False, evenOdd=False
160
+ ):
161
+ """Renders the current contours within a bitmap buffer.
162
+
163
+ Args:
164
+ width: Image width of the bitmap in pixels. If omitted, it
165
+ automatically fits to the bounding box of the contours.
166
+ height: Image height of the bitmap in pixels. If omitted, it
167
+ automatically fits to the bounding box of the contours.
168
+ transform: An optional 6-tuple containing an affine transformation,
169
+ or a ``Transform`` object from the ``fontTools.misc.transform``
170
+ module. The bitmap size is not affected by this matrix.
171
+ contain: If ``True``, the image size will be automatically expanded
172
+ so that it fits to the bounding box of the paths. Useful for
173
+ rendering glyphs with negative sidebearings without clipping.
174
+ evenOdd: Pass ``True`` for even-odd fill instead of non-zero.
175
+
176
+ Returns:
177
+ A tuple of ``(buffer, size)``, where ``buffer`` is a ``bytes``
178
+ object of the resulted bitmap and ``size`` is a 2-tuple of its
179
+ dimension.
180
+
181
+ Notes:
182
+ The image size should always be given explicitly if you need to get
183
+ a proper glyph image. When ``width`` and ``height`` are omitted, it
184
+ forcifully fits to the bounding box and the side bearings get
185
+ cropped. If you pass ``0`` to both ``width`` and ``height`` and set
186
+ ``contain`` to ``True``, it expands to the bounding box while
187
+ maintaining the origin of the contours, meaning that LSB will be
188
+ maintained but RSB won’t. The difference between the two becomes
189
+ more obvious when rotate or skew transformation is applied.
190
+
191
+ Example:
192
+ .. code-block:: pycon
193
+
194
+ >>>
195
+ >> pen = FreeTypePen(None)
196
+ >> glyph.draw(pen)
197
+ >> buf, size = pen.buffer(width=500, height=1000)
198
+ >> type(buf), len(buf), size
199
+ (<class 'bytes'>, 500000, (500, 1000))
200
+ """
201
+ transform = transform or Transform()
202
+ if not hasattr(transform, "transformPoint"):
203
+ transform = Transform(*transform)
204
+ contain_x, contain_y = contain or width is None, contain or height is None
205
+ if contain_x or contain_y:
206
+ dx, dy = transform.dx, transform.dy
207
+ bbox = self.bbox
208
+ p1, p2, p3, p4 = (
209
+ transform.transformPoint((bbox[0], bbox[1])),
210
+ transform.transformPoint((bbox[2], bbox[1])),
211
+ transform.transformPoint((bbox[0], bbox[3])),
212
+ transform.transformPoint((bbox[2], bbox[3])),
213
+ )
214
+ px, py = (p1[0], p2[0], p3[0], p4[0]), (p1[1], p2[1], p3[1], p4[1])
215
+ if contain_x:
216
+ if width is None:
217
+ dx = dx - min(*px)
218
+ width = max(*px) - min(*px)
219
+ else:
220
+ dx = dx - min(min(*px), 0.0)
221
+ width = max(width, max(*px) - min(min(*px), 0.0))
222
+ if contain_y:
223
+ if height is None:
224
+ dy = dy - min(*py)
225
+ height = max(*py) - min(*py)
226
+ else:
227
+ dy = dy - min(min(*py), 0.0)
228
+ height = max(height, max(*py) - min(min(*py), 0.0))
229
+ transform = Transform(*transform[:4], dx, dy)
230
+ width, height = math.ceil(width), math.ceil(height)
231
+ buf = ctypes.create_string_buffer(width * height)
232
+ bitmap = FT_Bitmap(
233
+ (ctypes.c_int)(height),
234
+ (ctypes.c_int)(width),
235
+ (ctypes.c_int)(width),
236
+ (ctypes.POINTER(ctypes.c_ubyte))(buf),
237
+ (ctypes.c_short)(256),
238
+ (ctypes.c_ubyte)(FT_PIXEL_MODE_GRAY),
239
+ (ctypes.c_char)(0),
240
+ (ctypes.c_void_p)(None),
241
+ )
242
+ outline = self.outline(transform=transform, evenOdd=evenOdd)
243
+ err = FT_Outline_Get_Bitmap(
244
+ freetype.get_handle(), ctypes.byref(outline), ctypes.byref(bitmap)
245
+ )
246
+ if err != 0:
247
+ raise FT_Exception(err)
248
+ return buf.raw, (width, height)
249
+
250
+ def array(
251
+ self, width=None, height=None, transform=None, contain=False, evenOdd=False
252
+ ):
253
+ """Returns the rendered contours as a numpy array. Requires `numpy`.
254
+
255
+ Args:
256
+ width: Image width of the bitmap in pixels. If omitted, it
257
+ automatically fits to the bounding box of the contours.
258
+ height: Image height of the bitmap in pixels. If omitted, it
259
+ automatically fits to the bounding box of the contours.
260
+ transform: An optional 6-tuple containing an affine transformation,
261
+ or a ``Transform`` object from the ``fontTools.misc.transform``
262
+ module. The bitmap size is not affected by this matrix.
263
+ contain: If ``True``, the image size will be automatically expanded
264
+ so that it fits to the bounding box of the paths. Useful for
265
+ rendering glyphs with negative sidebearings without clipping.
266
+ evenOdd: Pass ``True`` for even-odd fill instead of non-zero.
267
+
268
+ Returns:
269
+ A ``numpy.ndarray`` object with a shape of ``(height, width)``.
270
+ Each element takes a value in the range of ``[0.0, 1.0]``.
271
+
272
+ Notes:
273
+ The image size should always be given explicitly if you need to get
274
+ a proper glyph image. When ``width`` and ``height`` are omitted, it
275
+ forcifully fits to the bounding box and the side bearings get
276
+ cropped. If you pass ``0`` to both ``width`` and ``height`` and set
277
+ ``contain`` to ``True``, it expands to the bounding box while
278
+ maintaining the origin of the contours, meaning that LSB will be
279
+ maintained but RSB won’t. The difference between the two becomes
280
+ more obvious when rotate or skew transformation is applied.
281
+
282
+ Example:
283
+ .. code-block:: pycon
284
+
285
+ >>>
286
+ >> pen = FreeTypePen(None)
287
+ >> glyph.draw(pen)
288
+ >> arr = pen.array(width=500, height=1000)
289
+ >> type(a), a.shape
290
+ (<class 'numpy.ndarray'>, (1000, 500))
291
+ """
292
+
293
+ import numpy as np
294
+
295
+ buf, size = self.buffer(
296
+ width=width,
297
+ height=height,
298
+ transform=transform,
299
+ contain=contain,
300
+ evenOdd=evenOdd,
301
+ )
302
+ return np.frombuffer(buf, "B").reshape((size[1], size[0])) / 255.0
303
+
304
+ def show(
305
+ self, width=None, height=None, transform=None, contain=False, evenOdd=False
306
+ ):
307
+ """Plots the rendered contours with `pyplot`. Requires `numpy` and
308
+ `matplotlib`.
309
+
310
+ Args:
311
+ width: Image width of the bitmap in pixels. If omitted, it
312
+ automatically fits to the bounding box of the contours.
313
+ height: Image height of the bitmap in pixels. If omitted, it
314
+ automatically fits to the bounding box of the contours.
315
+ transform: An optional 6-tuple containing an affine transformation,
316
+ or a ``Transform`` object from the ``fontTools.misc.transform``
317
+ module. The bitmap size is not affected by this matrix.
318
+ contain: If ``True``, the image size will be automatically expanded
319
+ so that it fits to the bounding box of the paths. Useful for
320
+ rendering glyphs with negative sidebearings without clipping.
321
+ evenOdd: Pass ``True`` for even-odd fill instead of non-zero.
322
+
323
+ Notes:
324
+ The image size should always be given explicitly if you need to get
325
+ a proper glyph image. When ``width`` and ``height`` are omitted, it
326
+ forcifully fits to the bounding box and the side bearings get
327
+ cropped. If you pass ``0`` to both ``width`` and ``height`` and set
328
+ ``contain`` to ``True``, it expands to the bounding box while
329
+ maintaining the origin of the contours, meaning that LSB will be
330
+ maintained but RSB won’t. The difference between the two becomes
331
+ more obvious when rotate or skew transformation is applied.
332
+
333
+ Example:
334
+ .. code-block:: pycon
335
+
336
+ >>>
337
+ >> pen = FreeTypePen(None)
338
+ >> glyph.draw(pen)
339
+ >> pen.show(width=500, height=1000)
340
+ """
341
+ from matplotlib import pyplot as plt
342
+
343
+ a = self.array(
344
+ width=width,
345
+ height=height,
346
+ transform=transform,
347
+ contain=contain,
348
+ evenOdd=evenOdd,
349
+ )
350
+ plt.imshow(a, cmap="gray_r", vmin=0, vmax=1)
351
+ plt.show()
352
+
353
+ def image(
354
+ self, width=None, height=None, transform=None, contain=False, evenOdd=False
355
+ ):
356
+ """Returns the rendered contours as a PIL image. Requires `Pillow`.
357
+ Can be used to display a glyph image in Jupyter Notebook.
358
+
359
+ Args:
360
+ width: Image width of the bitmap in pixels. If omitted, it
361
+ automatically fits to the bounding box of the contours.
362
+ height: Image height of the bitmap in pixels. If omitted, it
363
+ automatically fits to the bounding box of the contours.
364
+ transform: An optional 6-tuple containing an affine transformation,
365
+ or a ``Transform`` object from the ``fontTools.misc.transform``
366
+ module. The bitmap size is not affected by this matrix.
367
+ contain: If ``True``, the image size will be automatically expanded
368
+ so that it fits to the bounding box of the paths. Useful for
369
+ rendering glyphs with negative sidebearings without clipping.
370
+ evenOdd: Pass ``True`` for even-odd fill instead of non-zero.
371
+
372
+ Returns:
373
+ A ``PIL.image`` object. The image is filled in black with alpha
374
+ channel obtained from the rendered bitmap.
375
+
376
+ Notes:
377
+ The image size should always be given explicitly if you need to get
378
+ a proper glyph image. When ``width`` and ``height`` are omitted, it
379
+ forcifully fits to the bounding box and the side bearings get
380
+ cropped. If you pass ``0`` to both ``width`` and ``height`` and set
381
+ ``contain`` to ``True``, it expands to the bounding box while
382
+ maintaining the origin of the contours, meaning that LSB will be
383
+ maintained but RSB won’t. The difference between the two becomes
384
+ more obvious when rotate or skew transformation is applied.
385
+
386
+ Example:
387
+ .. code-block:: pycon
388
+
389
+ >>>
390
+ >> pen = FreeTypePen(None)
391
+ >> glyph.draw(pen)
392
+ >> img = pen.image(width=500, height=1000)
393
+ >> type(img), img.size
394
+ (<class 'PIL.Image.Image'>, (500, 1000))
395
+ """
396
+ from PIL import Image
397
+
398
+ buf, size = self.buffer(
399
+ width=width,
400
+ height=height,
401
+ transform=transform,
402
+ contain=contain,
403
+ evenOdd=evenOdd,
404
+ )
405
+ img = Image.new("L", size, 0)
406
+ img.putalpha(Image.frombuffer("L", size, buf))
407
+ return img
408
+
409
+ @property
410
+ def bbox(self):
411
+ """Computes the exact bounding box of an outline.
412
+
413
+ Returns:
414
+ A tuple of ``(xMin, yMin, xMax, yMax)``.
415
+ """
416
+ bbox = FT_BBox()
417
+ outline = self.outline()
418
+ FT_Outline_Get_BBox(ctypes.byref(outline), ctypes.byref(bbox))
419
+ return (bbox.xMin / 64.0, bbox.yMin / 64.0, bbox.xMax / 64.0, bbox.yMax / 64.0)
420
+
421
+ @property
422
+ def cbox(self):
423
+ """Returns an outline's ‘control box’.
424
+
425
+ Returns:
426
+ A tuple of ``(xMin, yMin, xMax, yMax)``.
427
+ """
428
+ cbox = FT_BBox()
429
+ outline = self.outline()
430
+ FT_Outline_Get_CBox(ctypes.byref(outline), ctypes.byref(cbox))
431
+ return (cbox.xMin / 64.0, cbox.yMin / 64.0, cbox.xMax / 64.0, cbox.yMax / 64.0)
432
+
433
+ def _moveTo(self, pt):
434
+ contour = Contour([], [])
435
+ self.contours.append(contour)
436
+ contour.points.append(pt)
437
+ contour.tags.append(FT_CURVE_TAG_ON)
438
+
439
+ def _lineTo(self, pt):
440
+ if not (self.contours and len(self.contours[-1].points) > 0):
441
+ raise PenError("Contour missing required initial moveTo")
442
+ contour = self.contours[-1]
443
+ contour.points.append(pt)
444
+ contour.tags.append(FT_CURVE_TAG_ON)
445
+
446
+ def _curveToOne(self, p1, p2, p3):
447
+ if not (self.contours and len(self.contours[-1].points) > 0):
448
+ raise PenError("Contour missing required initial moveTo")
449
+ t1, t2, t3 = FT_CURVE_TAG_CUBIC, FT_CURVE_TAG_CUBIC, FT_CURVE_TAG_ON
450
+ contour = self.contours[-1]
451
+ for p, t in ((p1, t1), (p2, t2), (p3, t3)):
452
+ contour.points.append(p)
453
+ contour.tags.append(t)
454
+
455
+ def _qCurveToOne(self, p1, p2):
456
+ if not (self.contours and len(self.contours[-1].points) > 0):
457
+ raise PenError("Contour missing required initial moveTo")
458
+ t1, t2 = FT_CURVE_TAG_CONIC, FT_CURVE_TAG_ON
459
+ contour = self.contours[-1]
460
+ for p, t in ((p1, t1), (p2, t2)):
461
+ contour.points.append(p)
462
+ contour.tags.append(t)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/t2CharStringPen.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2009 Type Supply LLC
2
+ # Author: Tal Leming
3
+
4
+ from __future__ import annotations
5
+
6
+ from typing import Any, Dict, List, Tuple
7
+
8
+ from fontTools.cffLib.specializer import commandsToProgram, specializeCommands
9
+ from fontTools.misc.psCharStrings import T2CharString
10
+ from fontTools.misc.roundTools import otRound, roundFunc
11
+ from fontTools.pens.basePen import BasePen
12
+
13
+
14
+ class T2CharStringPen(BasePen):
15
+ """Pen to draw Type 2 CharStrings.
16
+
17
+ The 'roundTolerance' argument controls the rounding of point coordinates.
18
+ It is defined as the maximum absolute difference between the original
19
+ float and the rounded integer value.
20
+ The default tolerance of 0.5 means that all floats are rounded to integer;
21
+ a value of 0 disables rounding; values in between will only round floats
22
+ which are close to their integral part within the tolerated range.
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ width: float | None,
28
+ glyphSet: Dict[str, Any] | None,
29
+ roundTolerance: float = 0.5,
30
+ CFF2: bool = False,
31
+ ) -> None:
32
+ super(T2CharStringPen, self).__init__(glyphSet)
33
+ self.round = roundFunc(roundTolerance)
34
+ self._CFF2 = CFF2
35
+ self._width = width
36
+ self._commands: List[Tuple[str | bytes, List[float]]] = []
37
+ self._p0 = (0, 0)
38
+
39
+ def _p(self, pt: Tuple[float, float]) -> List[float]:
40
+ p0 = self._p0
41
+ pt = self._p0 = (self.round(pt[0]), self.round(pt[1]))
42
+ return [pt[0] - p0[0], pt[1] - p0[1]]
43
+
44
+ def _moveTo(self, pt: Tuple[float, float]) -> None:
45
+ self._commands.append(("rmoveto", self._p(pt)))
46
+
47
+ def _lineTo(self, pt: Tuple[float, float]) -> None:
48
+ self._commands.append(("rlineto", self._p(pt)))
49
+
50
+ def _curveToOne(
51
+ self,
52
+ pt1: Tuple[float, float],
53
+ pt2: Tuple[float, float],
54
+ pt3: Tuple[float, float],
55
+ ) -> None:
56
+ _p = self._p
57
+ self._commands.append(("rrcurveto", _p(pt1) + _p(pt2) + _p(pt3)))
58
+
59
+ def _closePath(self) -> None:
60
+ pass
61
+
62
+ def _endPath(self) -> None:
63
+ pass
64
+
65
+ def getCharString(
66
+ self,
67
+ private: Dict | None = None,
68
+ globalSubrs: List | None = None,
69
+ optimize: bool = True,
70
+ ) -> T2CharString:
71
+ commands = self._commands
72
+ if optimize:
73
+ maxstack = 48 if not self._CFF2 else 513
74
+ commands = specializeCommands(
75
+ commands, generalizeFirst=False, maxstack=maxstack
76
+ )
77
+ program = commandsToProgram(commands)
78
+ if self._width is not None:
79
+ assert (
80
+ not self._CFF2
81
+ ), "CFF2 does not allow encoding glyph width in CharString."
82
+ program.insert(0, otRound(self._width))
83
+ if not self._CFF2:
84
+ program.append("endchar")
85
+ charString = T2CharString(
86
+ program=program, private=private, globalSubrs=globalSubrs
87
+ )
88
+ return charString
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/pens/ttGlyphPen.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from array import array
2
+ from typing import Any, Callable, Dict, Optional, Tuple
3
+ from fontTools.misc.fixedTools import MAX_F2DOT14, floatToFixedToFloat
4
+ from fontTools.misc.loggingTools import LogMixin
5
+ from fontTools.pens.pointPen import AbstractPointPen
6
+ from fontTools.misc.roundTools import otRound
7
+ from fontTools.pens.basePen import LoggingPen, PenError
8
+ from fontTools.pens.transformPen import TransformPen, TransformPointPen
9
+ from fontTools.ttLib.tables import ttProgram
10
+ from fontTools.ttLib.tables._g_l_y_f import flagOnCurve, flagCubic
11
+ from fontTools.ttLib.tables._g_l_y_f import Glyph
12
+ from fontTools.ttLib.tables._g_l_y_f import GlyphComponent
13
+ from fontTools.ttLib.tables._g_l_y_f import GlyphCoordinates
14
+ from fontTools.ttLib.tables._g_l_y_f import dropImpliedOnCurvePoints
15
+ import math
16
+
17
+
18
+ __all__ = ["TTGlyphPen", "TTGlyphPointPen"]
19
+
20
+
21
+ class _TTGlyphBasePen:
22
+ def __init__(
23
+ self,
24
+ glyphSet: Optional[Dict[str, Any]],
25
+ handleOverflowingTransforms: bool = True,
26
+ ) -> None:
27
+ """
28
+ Construct a new pen.
29
+
30
+ Args:
31
+ glyphSet (Dict[str, Any]): A glyphset object, used to resolve components.
32
+ handleOverflowingTransforms (bool): See below.
33
+
34
+ If ``handleOverflowingTransforms`` is True, the components' transform values
35
+ are checked that they don't overflow the limits of a F2Dot14 number:
36
+ -2.0 <= v < +2.0. If any transform value exceeds these, the composite
37
+ glyph is decomposed.
38
+
39
+ An exception to this rule is done for values that are very close to +2.0
40
+ (both for consistency with the -2.0 case, and for the relative frequency
41
+ these occur in real fonts). When almost +2.0 values occur (and all other
42
+ values are within the range -2.0 <= x <= +2.0), they are clamped to the
43
+ maximum positive value that can still be encoded as an F2Dot14: i.e.
44
+ 1.99993896484375.
45
+
46
+ If False, no check is done and all components are translated unmodified
47
+ into the glyf table, followed by an inevitable ``struct.error`` once an
48
+ attempt is made to compile them.
49
+
50
+ If both contours and components are present in a glyph, the components
51
+ are decomposed.
52
+ """
53
+ self.glyphSet = glyphSet
54
+ self.handleOverflowingTransforms = handleOverflowingTransforms
55
+ self.init()
56
+
57
+ def _decompose(
58
+ self,
59
+ glyphName: str,
60
+ transformation: Tuple[float, float, float, float, float, float],
61
+ ):
62
+ tpen = self.transformPen(self, transformation)
63
+ getattr(self.glyphSet[glyphName], self.drawMethod)(tpen)
64
+
65
+ def _isClosed(self):
66
+ """
67
+ Check if the current path is closed.
68
+ """
69
+ raise NotImplementedError
70
+
71
+ def init(self) -> None:
72
+ self.points = []
73
+ self.endPts = []
74
+ self.types = []
75
+ self.components = []
76
+
77
+ def addComponent(
78
+ self,
79
+ baseGlyphName: str,
80
+ transformation: Tuple[float, float, float, float, float, float],
81
+ identifier: Optional[str] = None,
82
+ **kwargs: Any,
83
+ ) -> None:
84
+ """
85
+ Add a sub glyph.
86
+ """
87
+ self.components.append((baseGlyphName, transformation))
88
+
89
+ def _buildComponents(self, componentFlags):
90
+ if self.handleOverflowingTransforms:
91
+ # we can't encode transform values > 2 or < -2 in F2Dot14,
92
+ # so we must decompose the glyph if any transform exceeds these
93
+ overflowing = any(
94
+ s > 2 or s < -2
95
+ for (glyphName, transformation) in self.components
96
+ for s in transformation[:4]
97
+ )
98
+ components = []
99
+ for glyphName, transformation in self.components:
100
+ if glyphName not in self.glyphSet:
101
+ self.log.warning(f"skipped non-existing component '{glyphName}'")
102
+ continue
103
+ if self.points or (self.handleOverflowingTransforms and overflowing):
104
+ # can't have both coordinates and components, so decompose
105
+ self._decompose(glyphName, transformation)
106
+ continue
107
+
108
+ component = GlyphComponent()
109
+ component.glyphName = glyphName
110
+ component.x, component.y = (otRound(v) for v in transformation[4:])
111
+ # quantize floats to F2Dot14 so we get same values as when decompiled
112
+ # from a binary glyf table
113
+ transformation = tuple(
114
+ floatToFixedToFloat(v, 14) for v in transformation[:4]
115
+ )
116
+ if transformation != (1, 0, 0, 1):
117
+ if self.handleOverflowingTransforms and any(
118
+ MAX_F2DOT14 < s <= 2 for s in transformation
119
+ ):
120
+ # clamp values ~= +2.0 so we can keep the component
121
+ transformation = tuple(
122
+ MAX_F2DOT14 if MAX_F2DOT14 < s <= 2 else s
123
+ for s in transformation
124
+ )
125
+ component.transform = (transformation[:2], transformation[2:])
126
+ component.flags = componentFlags
127
+ components.append(component)
128
+ return components
129
+
130
+ def glyph(
131
+ self,
132
+ componentFlags: int = 0x04,
133
+ dropImpliedOnCurves: bool = False,
134
+ *,
135
+ round: Callable[[float], int] = otRound,
136
+ ) -> Glyph:
137
+ """
138
+ Returns a :py:class:`~._g_l_y_f.Glyph` object representing the glyph.
139
+
140
+ Args:
141
+ componentFlags: Flags to use for component glyphs. (default: 0x04)
142
+
143
+ dropImpliedOnCurves: Whether to remove implied-oncurve points. (default: False)
144
+ """
145
+ if not self._isClosed():
146
+ raise PenError("Didn't close last contour.")
147
+ components = self._buildComponents(componentFlags)
148
+
149
+ glyph = Glyph()
150
+ glyph.coordinates = GlyphCoordinates(self.points)
151
+ glyph.endPtsOfContours = self.endPts
152
+ glyph.flags = array("B", self.types)
153
+ self.init()
154
+
155
+ if components:
156
+ # If both components and contours were present, they have by now
157
+ # been decomposed by _buildComponents.
158
+ glyph.components = components
159
+ glyph.numberOfContours = -1
160
+ else:
161
+ glyph.numberOfContours = len(glyph.endPtsOfContours)
162
+ glyph.program = ttProgram.Program()
163
+ glyph.program.fromBytecode(b"")
164
+ if dropImpliedOnCurves:
165
+ dropImpliedOnCurvePoints(glyph)
166
+ glyph.coordinates.toInt(round=round)
167
+
168
+ return glyph
169
+
170
+
171
+ class TTGlyphPen(_TTGlyphBasePen, LoggingPen):
172
+ """
173
+ Pen used for drawing to a TrueType glyph.
174
+
175
+ This pen can be used to construct or modify glyphs in a TrueType format
176
+ font. After using the pen to draw, use the ``.glyph()`` method to retrieve
177
+ a :py:class:`~._g_l_y_f.Glyph` object representing the glyph.
178
+ """
179
+
180
+ drawMethod = "draw"
181
+ transformPen = TransformPen
182
+
183
+ def __init__(
184
+ self,
185
+ glyphSet: Optional[Dict[str, Any]] = None,
186
+ handleOverflowingTransforms: bool = True,
187
+ outputImpliedClosingLine: bool = False,
188
+ ) -> None:
189
+ super().__init__(glyphSet, handleOverflowingTransforms)
190
+ self.outputImpliedClosingLine = outputImpliedClosingLine
191
+
192
+ def _addPoint(self, pt: Tuple[float, float], tp: int) -> None:
193
+ self.points.append(pt)
194
+ self.types.append(tp)
195
+
196
+ def _popPoint(self) -> None:
197
+ self.points.pop()
198
+ self.types.pop()
199
+
200
+ def _isClosed(self) -> bool:
201
+ return (not self.points) or (
202
+ self.endPts and self.endPts[-1] == len(self.points) - 1
203
+ )
204
+
205
+ def lineTo(self, pt: Tuple[float, float]) -> None:
206
+ self._addPoint(pt, flagOnCurve)
207
+
208
+ def moveTo(self, pt: Tuple[float, float]) -> None:
209
+ if not self._isClosed():
210
+ raise PenError('"move"-type point must begin a new contour.')
211
+ self._addPoint(pt, flagOnCurve)
212
+
213
+ def curveTo(self, *points) -> None:
214
+ assert len(points) % 2 == 1
215
+ for pt in points[:-1]:
216
+ self._addPoint(pt, flagCubic)
217
+
218
+ # last point is None if there are no on-curve points
219
+ if points[-1] is not None:
220
+ self._addPoint(points[-1], 1)
221
+
222
+ def qCurveTo(self, *points) -> None:
223
+ assert len(points) >= 1
224
+ for pt in points[:-1]:
225
+ self._addPoint(pt, 0)
226
+
227
+ # last point is None if there are no on-curve points
228
+ if points[-1] is not None:
229
+ self._addPoint(points[-1], 1)
230
+
231
+ def closePath(self) -> None:
232
+ endPt = len(self.points) - 1
233
+
234
+ # ignore anchors (one-point paths)
235
+ if endPt == 0 or (self.endPts and endPt == self.endPts[-1] + 1):
236
+ self._popPoint()
237
+ return
238
+
239
+ if not self.outputImpliedClosingLine:
240
+ # if first and last point on this path are the same, remove last
241
+ startPt = 0
242
+ if self.endPts:
243
+ startPt = self.endPts[-1] + 1
244
+ if self.points[startPt] == self.points[endPt]:
245
+ self._popPoint()
246
+ endPt -= 1
247
+
248
+ self.endPts.append(endPt)
249
+
250
+ def endPath(self) -> None:
251
+ # TrueType contours are always "closed"
252
+ self.closePath()
253
+
254
+
255
+ class TTGlyphPointPen(_TTGlyphBasePen, LogMixin, AbstractPointPen):
256
+ """
257
+ Point pen used for drawing to a TrueType glyph.
258
+
259
+ This pen can be used to construct or modify glyphs in a TrueType format
260
+ font. After using the pen to draw, use the ``.glyph()`` method to retrieve
261
+ a :py:class:`~._g_l_y_f.Glyph` object representing the glyph.
262
+ """
263
+
264
+ drawMethod = "drawPoints"
265
+ transformPen = TransformPointPen
266
+
267
+ def init(self) -> None:
268
+ super().init()
269
+ self._currentContourStartIndex = None
270
+
271
+ def _isClosed(self) -> bool:
272
+ return self._currentContourStartIndex is None
273
+
274
+ def beginPath(self, identifier: Optional[str] = None, **kwargs: Any) -> None:
275
+ """
276
+ Start a new sub path.
277
+ """
278
+ if not self._isClosed():
279
+ raise PenError("Didn't close previous contour.")
280
+ self._currentContourStartIndex = len(self.points)
281
+
282
+ def endPath(self) -> None:
283
+ """
284
+ End the current sub path.
285
+ """
286
+ # TrueType contours are always "closed"
287
+ if self._isClosed():
288
+ raise PenError("Contour is already closed.")
289
+ if self._currentContourStartIndex == len(self.points):
290
+ # ignore empty contours
291
+ self._currentContourStartIndex = None
292
+ return
293
+
294
+ contourStart = self.endPts[-1] + 1 if self.endPts else 0
295
+ self.endPts.append(len(self.points) - 1)
296
+ self._currentContourStartIndex = None
297
+
298
+ # Resolve types for any cubic segments
299
+ flags = self.types
300
+ for i in range(contourStart, len(flags)):
301
+ if flags[i] == "curve":
302
+ j = i - 1
303
+ if j < contourStart:
304
+ j = len(flags) - 1
305
+ while flags[j] == 0:
306
+ flags[j] = flagCubic
307
+ j -= 1
308
+ flags[i] = flagOnCurve
309
+
310
+ def addPoint(
311
+ self,
312
+ pt: Tuple[float, float],
313
+ segmentType: Optional[str] = None,
314
+ smooth: bool = False,
315
+ name: Optional[str] = None,
316
+ identifier: Optional[str] = None,
317
+ **kwargs: Any,
318
+ ) -> None:
319
+ """
320
+ Add a point to the current sub path.
321
+ """
322
+ if self._isClosed():
323
+ raise PenError("Can't add a point to a closed contour.")
324
+ if segmentType is None:
325
+ self.types.append(0)
326
+ elif segmentType in ("line", "move"):
327
+ self.types.append(flagOnCurve)
328
+ elif segmentType == "qcurve":
329
+ self.types.append(flagOnCurve)
330
+ elif segmentType == "curve":
331
+ self.types.append("curve")
332
+ else:
333
+ raise AssertionError(segmentType)
334
+
335
+ self.points.append(pt)
Scripts_Climate_n_LAI_to_Yield/.venv/lib/python3.10/site-packages/fontTools/qu2cu/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Google Inc. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .qu2cu import *