jonghanko commited on
Commit
05a19c0
·
verified ·
1 Parent(s): f4e0339

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_to_LAI/.venv/include/site/python3.10/greenlet/greenlet.h +164 -0
  2. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cffLib/CFF2ToCFF.py +233 -0
  3. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cffLib/CFFToCFF2.py +305 -0
  4. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cffLib/__init__.py +0 -0
  5. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cffLib/specializer.py +927 -0
  6. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cffLib/transforms.py +495 -0
  7. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cffLib/width.py +210 -0
  8. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/colorLib/__init__.py +0 -0
  9. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/colorLib/builder.py +664 -0
  10. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/colorLib/errors.py +2 -0
  11. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/colorLib/geometry.py +143 -0
  12. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/colorLib/table_builder.py +223 -0
  13. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/colorLib/unbuilder.py +81 -0
  14. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/config/__init__.py +90 -0
  15. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cu2qu/__init__.py +15 -0
  16. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cu2qu/__main__.py +6 -0
  17. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cu2qu/benchmark.py +54 -0
  18. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cu2qu/cli.py +198 -0
  19. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cu2qu/cu2qu.c +0 -0
  20. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cu2qu/cu2qu.py +546 -0
  21. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cu2qu/errors.py +77 -0
  22. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cu2qu/ufo.py +349 -0
  23. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/__init__.py +0 -0
  24. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/__main__.py +6 -0
  25. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/split.py +475 -0
  26. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/statNames.py +260 -0
  27. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/designspaceLib/types.py +147 -0
  28. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/encodings/MacRoman.py +258 -0
  29. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/encodings/StandardEncoding.py +258 -0
  30. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/encodings/__init__.py +1 -0
  31. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/encodings/codecs.py +135 -0
  32. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/__init__.py +4 -0
  33. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/__main__.py +78 -0
  34. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/ast.py +2143 -0
  35. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/builder.py +1808 -0
  36. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/error.py +22 -0
  37. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/lexer.c +0 -0
  38. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/lexer.py +287 -0
  39. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/location.py +12 -0
  40. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/lookupDebugInfo.py +12 -0
  41. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/parser.py +0 -0
  42. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/variableScalar.py +118 -0
  43. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/merge/__init__.py +248 -0
  44. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/merge/__main__.py +6 -0
  45. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/merge/base.py +81 -0
  46. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/merge/cmap.py +173 -0
  47. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/merge/layout.py +526 -0
  48. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/merge/options.py +85 -0
  49. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/merge/tables.py +352 -0
  50. Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/merge/unicode.py +78 -0
Scripts_Climate_to_LAI/.venv/include/site/python3.10/greenlet/greenlet.h ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* -*- indent-tabs-mode: nil; tab-width: 4; -*- */
2
+
3
+ /* Greenlet object interface */
4
+
5
+ #ifndef Py_GREENLETOBJECT_H
6
+ #define Py_GREENLETOBJECT_H
7
+
8
+
9
+ #include <Python.h>
10
+
11
+ #ifdef __cplusplus
12
+ extern "C" {
13
+ #endif
14
+
15
+ /* This is deprecated and undocumented. It does not change. */
16
+ #define GREENLET_VERSION "1.0.0"
17
+
18
+ #ifndef GREENLET_MODULE
19
+ #define implementation_ptr_t void*
20
+ #endif
21
+
22
+ typedef struct _greenlet {
23
+ PyObject_HEAD
24
+ PyObject* weakreflist;
25
+ PyObject* dict;
26
+ implementation_ptr_t pimpl;
27
+ } PyGreenlet;
28
+
29
+ #define PyGreenlet_Check(op) (op && PyObject_TypeCheck(op, &PyGreenlet_Type))
30
+
31
+
32
+ /* C API functions */
33
+
34
+ /* Total number of symbols that are exported */
35
+ #define PyGreenlet_API_pointers 12
36
+
37
+ #define PyGreenlet_Type_NUM 0
38
+ #define PyExc_GreenletError_NUM 1
39
+ #define PyExc_GreenletExit_NUM 2
40
+
41
+ #define PyGreenlet_New_NUM 3
42
+ #define PyGreenlet_GetCurrent_NUM 4
43
+ #define PyGreenlet_Throw_NUM 5
44
+ #define PyGreenlet_Switch_NUM 6
45
+ #define PyGreenlet_SetParent_NUM 7
46
+
47
+ #define PyGreenlet_MAIN_NUM 8
48
+ #define PyGreenlet_STARTED_NUM 9
49
+ #define PyGreenlet_ACTIVE_NUM 10
50
+ #define PyGreenlet_GET_PARENT_NUM 11
51
+
52
+ #ifndef GREENLET_MODULE
53
+ /* This section is used by modules that uses the greenlet C API */
54
+ static void** _PyGreenlet_API = NULL;
55
+
56
+ # define PyGreenlet_Type \
57
+ (*(PyTypeObject*)_PyGreenlet_API[PyGreenlet_Type_NUM])
58
+
59
+ # define PyExc_GreenletError \
60
+ ((PyObject*)_PyGreenlet_API[PyExc_GreenletError_NUM])
61
+
62
+ # define PyExc_GreenletExit \
63
+ ((PyObject*)_PyGreenlet_API[PyExc_GreenletExit_NUM])
64
+
65
+ /*
66
+ * PyGreenlet_New(PyObject *args)
67
+ *
68
+ * greenlet.greenlet(run, parent=None)
69
+ */
70
+ # define PyGreenlet_New \
71
+ (*(PyGreenlet * (*)(PyObject * run, PyGreenlet * parent)) \
72
+ _PyGreenlet_API[PyGreenlet_New_NUM])
73
+
74
+ /*
75
+ * PyGreenlet_GetCurrent(void)
76
+ *
77
+ * greenlet.getcurrent()
78
+ */
79
+ # define PyGreenlet_GetCurrent \
80
+ (*(PyGreenlet * (*)(void)) _PyGreenlet_API[PyGreenlet_GetCurrent_NUM])
81
+
82
+ /*
83
+ * PyGreenlet_Throw(
84
+ * PyGreenlet *greenlet,
85
+ * PyObject *typ,
86
+ * PyObject *val,
87
+ * PyObject *tb)
88
+ *
89
+ * g.throw(...)
90
+ */
91
+ # define PyGreenlet_Throw \
92
+ (*(PyObject * (*)(PyGreenlet * self, \
93
+ PyObject * typ, \
94
+ PyObject * val, \
95
+ PyObject * tb)) \
96
+ _PyGreenlet_API[PyGreenlet_Throw_NUM])
97
+
98
+ /*
99
+ * PyGreenlet_Switch(PyGreenlet *greenlet, PyObject *args)
100
+ *
101
+ * g.switch(*args, **kwargs)
102
+ */
103
+ # define PyGreenlet_Switch \
104
+ (*(PyObject * \
105
+ (*)(PyGreenlet * greenlet, PyObject * args, PyObject * kwargs)) \
106
+ _PyGreenlet_API[PyGreenlet_Switch_NUM])
107
+
108
+ /*
109
+ * PyGreenlet_SetParent(PyObject *greenlet, PyObject *new_parent)
110
+ *
111
+ * g.parent = new_parent
112
+ */
113
+ # define PyGreenlet_SetParent \
114
+ (*(int (*)(PyGreenlet * greenlet, PyGreenlet * nparent)) \
115
+ _PyGreenlet_API[PyGreenlet_SetParent_NUM])
116
+
117
+ /*
118
+ * PyGreenlet_GetParent(PyObject* greenlet)
119
+ *
120
+ * return greenlet.parent;
121
+ *
122
+ * This could return NULL even if there is no exception active.
123
+ * If it does not return NULL, you are responsible for decrementing the
124
+ * reference count.
125
+ */
126
+ # define PyGreenlet_GetParent \
127
+ (*(PyGreenlet* (*)(PyGreenlet*)) \
128
+ _PyGreenlet_API[PyGreenlet_GET_PARENT_NUM])
129
+
130
+ /*
131
+ * deprecated, undocumented alias.
132
+ */
133
+ # define PyGreenlet_GET_PARENT PyGreenlet_GetParent
134
+
135
+ # define PyGreenlet_MAIN \
136
+ (*(int (*)(PyGreenlet*)) \
137
+ _PyGreenlet_API[PyGreenlet_MAIN_NUM])
138
+
139
+ # define PyGreenlet_STARTED \
140
+ (*(int (*)(PyGreenlet*)) \
141
+ _PyGreenlet_API[PyGreenlet_STARTED_NUM])
142
+
143
+ # define PyGreenlet_ACTIVE \
144
+ (*(int (*)(PyGreenlet*)) \
145
+ _PyGreenlet_API[PyGreenlet_ACTIVE_NUM])
146
+
147
+
148
+
149
+
150
+ /* Macro that imports greenlet and initializes C API */
151
+ /* NOTE: This has actually moved to ``greenlet._greenlet._C_API``, but we
152
+ keep the older definition to be sure older code that might have a copy of
153
+ the header still works. */
154
+ # define PyGreenlet_Import() \
155
+ { \
156
+ _PyGreenlet_API = (void**)PyCapsule_Import("greenlet._C_API", 0); \
157
+ }
158
+
159
+ #endif /* GREENLET_MODULE */
160
+
161
+ #ifdef __cplusplus
162
+ }
163
+ #endif
164
+ #endif /* !Py_GREENLETOBJECT_H */
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cffLib/CFF2ToCFF.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CFF2 to CFF converter."""
2
+
3
+ from fontTools.ttLib import TTFont, newTable
4
+ from fontTools.misc.cliTools import makeOutputFileName
5
+ from fontTools.misc.psCharStrings import T2StackUseExtractor
6
+ from fontTools.cffLib import (
7
+ TopDictIndex,
8
+ buildOrder,
9
+ buildDefaults,
10
+ topDictOperators,
11
+ privateDictOperators,
12
+ FDSelect,
13
+ )
14
+ from .transforms import desubroutinizeCharString
15
+ from .specializer import specializeProgram
16
+ from .width import optimizeWidths
17
+ from collections import defaultdict
18
+ import logging
19
+
20
+
21
+ __all__ = ["convertCFF2ToCFF", "main"]
22
+
23
+
24
+ log = logging.getLogger("fontTools.cffLib")
25
+
26
+
27
+ def _convertCFF2ToCFF(cff, otFont):
28
+ """Converts this object from CFF2 format to CFF format. This conversion
29
+ is done 'in-place'. The conversion cannot be reversed.
30
+
31
+ The CFF2 font cannot be variable. (TODO Accept those and convert to the
32
+ default instance?)
33
+
34
+ This assumes a decompiled CFF2 table. (i.e. that the object has been
35
+ filled via :meth:`decompile` and e.g. not loaded from XML.)"""
36
+
37
+ cff.major = 1
38
+
39
+ topDictData = TopDictIndex(None)
40
+ for item in cff.topDictIndex:
41
+ # Iterate over, such that all are decompiled
42
+ item.cff2GetGlyphOrder = None
43
+ topDictData.append(item)
44
+ cff.topDictIndex = topDictData
45
+ topDict = topDictData[0]
46
+
47
+ if hasattr(topDict, "VarStore"):
48
+ raise ValueError("Variable CFF2 font cannot be converted to CFF format.")
49
+
50
+ opOrder = buildOrder(topDictOperators)
51
+ topDict.order = opOrder
52
+ for key in topDict.rawDict.keys():
53
+ if key not in opOrder:
54
+ del topDict.rawDict[key]
55
+ if hasattr(topDict, key):
56
+ delattr(topDict, key)
57
+
58
+ charStrings = topDict.CharStrings
59
+
60
+ fdArray = topDict.FDArray
61
+ if not hasattr(topDict, "FDSelect"):
62
+ # FDSelect is optional in CFF2, but required in CFF.
63
+ fdSelect = topDict.FDSelect = FDSelect()
64
+ fdSelect.gidArray = [0] * len(charStrings.charStrings)
65
+
66
+ defaults = buildDefaults(privateDictOperators)
67
+ order = buildOrder(privateDictOperators)
68
+ for fd in fdArray:
69
+ fd.setCFF2(False)
70
+ privateDict = fd.Private
71
+ privateDict.order = order
72
+ for key in order:
73
+ if key not in privateDict.rawDict and key in defaults:
74
+ privateDict.rawDict[key] = defaults[key]
75
+ for key in privateDict.rawDict.keys():
76
+ if key not in order:
77
+ del privateDict.rawDict[key]
78
+ if hasattr(privateDict, key):
79
+ delattr(privateDict, key)
80
+
81
+ # Add ending operators
82
+ for cs in charStrings.values():
83
+ cs.decompile()
84
+ cs.program.append("endchar")
85
+ for subrSets in [cff.GlobalSubrs] + [
86
+ getattr(fd.Private, "Subrs", []) for fd in fdArray
87
+ ]:
88
+ for cs in subrSets:
89
+ cs.program.append("return")
90
+
91
+ # Add (optimal) width to CharStrings that need it.
92
+ widths = defaultdict(list)
93
+ metrics = otFont["hmtx"].metrics
94
+ for glyphName in charStrings.keys():
95
+ cs, fdIndex = charStrings.getItemAndSelector(glyphName)
96
+ if fdIndex == None:
97
+ fdIndex = 0
98
+ widths[fdIndex].append(metrics[glyphName][0])
99
+ for fdIndex, widthList in widths.items():
100
+ bestDefault, bestNominal = optimizeWidths(widthList)
101
+ private = fdArray[fdIndex].Private
102
+ private.defaultWidthX = bestDefault
103
+ private.nominalWidthX = bestNominal
104
+ for glyphName in charStrings.keys():
105
+ cs, fdIndex = charStrings.getItemAndSelector(glyphName)
106
+ if fdIndex == None:
107
+ fdIndex = 0
108
+ private = fdArray[fdIndex].Private
109
+ width = metrics[glyphName][0]
110
+ if width != private.defaultWidthX:
111
+ cs.program.insert(0, width - private.nominalWidthX)
112
+
113
+ # Handle stack use since stack-depth is lower in CFF than in CFF2.
114
+ for glyphName in charStrings.keys():
115
+ cs, fdIndex = charStrings.getItemAndSelector(glyphName)
116
+ if fdIndex is None:
117
+ fdIndex = 0
118
+ private = fdArray[fdIndex].Private
119
+ extractor = T2StackUseExtractor(
120
+ getattr(private, "Subrs", []), cff.GlobalSubrs, private=private
121
+ )
122
+ stackUse = extractor.execute(cs)
123
+ if stackUse > 48: # CFF stack depth is 48
124
+ desubroutinizeCharString(cs)
125
+ cs.program = specializeProgram(cs.program)
126
+
127
+ # Unused subroutines are still in CFF2 (ie. lacking 'return' operator)
128
+ # because they were not decompiled when we added the 'return'.
129
+ # Moreover, some used subroutines may have become unused after the
130
+ # stack-use fixup. So we remove all unused subroutines now.
131
+ cff.remove_unused_subroutines()
132
+
133
+ mapping = {
134
+ name: ("cid" + str(n).zfill(5) if n else ".notdef")
135
+ for n, name in enumerate(topDict.charset)
136
+ }
137
+ topDict.charset = [
138
+ "cid" + str(n).zfill(5) if n else ".notdef" for n in range(len(topDict.charset))
139
+ ]
140
+ charStrings.charStrings = {
141
+ mapping[name]: v for name, v in charStrings.charStrings.items()
142
+ }
143
+
144
+ topDict.ROS = ("Adobe", "Identity", 0)
145
+
146
+
147
+ def convertCFF2ToCFF(font, *, updatePostTable=True):
148
+ if "CFF2" not in font:
149
+ raise ValueError("Input font does not contain a CFF2 table.")
150
+ cff = font["CFF2"].cff
151
+ _convertCFF2ToCFF(cff, font)
152
+ del font["CFF2"]
153
+ table = font["CFF "] = newTable("CFF ")
154
+ table.cff = cff
155
+
156
+ if updatePostTable and "post" in font:
157
+ # Only version supported for fonts with CFF table is 0x00030000 not 0x20000
158
+ post = font["post"]
159
+ if post.formatType == 2.0:
160
+ post.formatType = 3.0
161
+
162
+
163
+ def main(args=None):
164
+ """Convert CFF2 OTF font to CFF OTF font"""
165
+ if args is None:
166
+ import sys
167
+
168
+ args = sys.argv[1:]
169
+
170
+ import argparse
171
+
172
+ parser = argparse.ArgumentParser(
173
+ "fonttools cffLib.CFF2ToCFF",
174
+ description="Convert a non-variable CFF2 font to CFF.",
175
+ )
176
+ parser.add_argument(
177
+ "input", metavar="INPUT.ttf", help="Input OTF file with CFF table."
178
+ )
179
+ parser.add_argument(
180
+ "-o",
181
+ "--output",
182
+ metavar="OUTPUT.ttf",
183
+ default=None,
184
+ help="Output instance OTF file (default: INPUT-CFF2.ttf).",
185
+ )
186
+ parser.add_argument(
187
+ "--no-recalc-timestamp",
188
+ dest="recalc_timestamp",
189
+ action="store_false",
190
+ help="Don't set the output font's timestamp to the current time.",
191
+ )
192
+ loggingGroup = parser.add_mutually_exclusive_group(required=False)
193
+ loggingGroup.add_argument(
194
+ "-v", "--verbose", action="store_true", help="Run more verbosely."
195
+ )
196
+ loggingGroup.add_argument(
197
+ "-q", "--quiet", action="store_true", help="Turn verbosity off."
198
+ )
199
+ options = parser.parse_args(args)
200
+
201
+ from fontTools import configLogger
202
+
203
+ configLogger(
204
+ level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
205
+ )
206
+
207
+ import os
208
+
209
+ infile = options.input
210
+ if not os.path.isfile(infile):
211
+ parser.error("No such file '{}'".format(infile))
212
+
213
+ outfile = (
214
+ makeOutputFileName(infile, overWrite=True, suffix="-CFF")
215
+ if not options.output
216
+ else options.output
217
+ )
218
+
219
+ font = TTFont(infile, recalcTimestamp=options.recalc_timestamp, recalcBBoxes=False)
220
+
221
+ convertCFF2ToCFF(font)
222
+
223
+ log.info(
224
+ "Saving %s",
225
+ outfile,
226
+ )
227
+ font.save(outfile)
228
+
229
+
230
+ if __name__ == "__main__":
231
+ import sys
232
+
233
+ sys.exit(main(sys.argv[1:]))
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cffLib/CFFToCFF2.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CFF to CFF2 converter."""
2
+
3
+ from fontTools.ttLib import TTFont, newTable
4
+ from fontTools.misc.cliTools import makeOutputFileName
5
+ from fontTools.misc.psCharStrings import T2WidthExtractor
6
+ from fontTools.cffLib import (
7
+ TopDictIndex,
8
+ FDArrayIndex,
9
+ FontDict,
10
+ buildOrder,
11
+ topDictOperators,
12
+ privateDictOperators,
13
+ topDictOperators2,
14
+ privateDictOperators2,
15
+ )
16
+ from io import BytesIO
17
+ import logging
18
+
19
+ __all__ = ["convertCFFToCFF2", "main"]
20
+
21
+
22
+ log = logging.getLogger("fontTools.cffLib")
23
+
24
+
25
+ class _NominalWidthUsedError(Exception):
26
+ def __add__(self, other):
27
+ raise self
28
+
29
+ def __radd__(self, other):
30
+ raise self
31
+
32
+
33
+ def _convertCFFToCFF2(cff, otFont):
34
+ """Converts this object from CFF format to CFF2 format. This conversion
35
+ is done 'in-place'. The conversion cannot be reversed.
36
+
37
+ This assumes a decompiled CFF table. (i.e. that the object has been
38
+ filled via :meth:`decompile` and e.g. not loaded from XML.)"""
39
+
40
+ # Clean up T2CharStrings
41
+
42
+ topDict = cff.topDictIndex[0]
43
+ fdArray = topDict.FDArray if hasattr(topDict, "FDArray") else None
44
+ charStrings = topDict.CharStrings
45
+ globalSubrs = cff.GlobalSubrs
46
+ localSubrs = (
47
+ [getattr(fd.Private, "Subrs", []) for fd in fdArray]
48
+ if fdArray
49
+ else (
50
+ [topDict.Private.Subrs]
51
+ if hasattr(topDict, "Private") and hasattr(topDict.Private, "Subrs")
52
+ else []
53
+ )
54
+ )
55
+
56
+ for glyphName in charStrings.keys():
57
+ cs, fdIndex = charStrings.getItemAndSelector(glyphName)
58
+ cs.decompile()
59
+
60
+ # Clean up subroutines first
61
+ for subrs in [globalSubrs] + localSubrs:
62
+ for subr in subrs:
63
+ program = subr.program
64
+ i = j = len(program)
65
+ try:
66
+ i = program.index("return")
67
+ except ValueError:
68
+ pass
69
+ try:
70
+ j = program.index("endchar")
71
+ except ValueError:
72
+ pass
73
+ program[min(i, j) :] = []
74
+
75
+ # Clean up glyph charstrings
76
+ removeUnusedSubrs = False
77
+ nominalWidthXError = _NominalWidthUsedError()
78
+ for glyphName in charStrings.keys():
79
+ cs, fdIndex = charStrings.getItemAndSelector(glyphName)
80
+ program = cs.program
81
+
82
+ thisLocalSubrs = (
83
+ localSubrs[fdIndex]
84
+ if fdIndex is not None
85
+ else (
86
+ getattr(topDict.Private, "Subrs", [])
87
+ if hasattr(topDict, "Private")
88
+ else []
89
+ )
90
+ )
91
+
92
+ # Intentionally use custom type for nominalWidthX, such that any
93
+ # CharString that has an explicit width encoded will throw back to us.
94
+ extractor = T2WidthExtractor(
95
+ thisLocalSubrs,
96
+ globalSubrs,
97
+ nominalWidthXError,
98
+ 0,
99
+ )
100
+ try:
101
+ extractor.execute(cs)
102
+ except _NominalWidthUsedError:
103
+ # Program has explicit width. We want to drop it, but can't
104
+ # just pop the first number since it may be a subroutine call.
105
+ # Instead, when seeing that, we embed the subroutine and recurse.
106
+ # If this ever happened, we later prune unused subroutines.
107
+ while len(program) >= 2 and program[1] in ["callsubr", "callgsubr"]:
108
+ removeUnusedSubrs = True
109
+ subrNumber = program.pop(0)
110
+ assert isinstance(subrNumber, int), subrNumber
111
+ op = program.pop(0)
112
+ bias = extractor.localBias if op == "callsubr" else extractor.globalBias
113
+ subrNumber += bias
114
+ subrSet = thisLocalSubrs if op == "callsubr" else globalSubrs
115
+ subrProgram = subrSet[subrNumber].program
116
+ program[:0] = subrProgram
117
+ # Now pop the actual width
118
+ assert len(program) >= 1, program
119
+ program.pop(0)
120
+
121
+ if program and program[-1] == "endchar":
122
+ program.pop()
123
+
124
+ if removeUnusedSubrs:
125
+ cff.remove_unused_subroutines()
126
+
127
+ # Upconvert TopDict
128
+
129
+ cff.major = 2
130
+ cff2GetGlyphOrder = cff.otFont.getGlyphOrder
131
+ topDictData = TopDictIndex(None, cff2GetGlyphOrder)
132
+ for item in cff.topDictIndex:
133
+ # Iterate over, such that all are decompiled
134
+ topDictData.append(item)
135
+ cff.topDictIndex = topDictData
136
+ topDict = topDictData[0]
137
+ if hasattr(topDict, "Private"):
138
+ privateDict = topDict.Private
139
+ else:
140
+ privateDict = None
141
+ opOrder = buildOrder(topDictOperators2)
142
+ topDict.order = opOrder
143
+ topDict.cff2GetGlyphOrder = cff2GetGlyphOrder
144
+
145
+ if not hasattr(topDict, "FDArray"):
146
+ fdArray = topDict.FDArray = FDArrayIndex()
147
+ fdArray.strings = None
148
+ fdArray.GlobalSubrs = topDict.GlobalSubrs
149
+ topDict.GlobalSubrs.fdArray = fdArray
150
+ charStrings = topDict.CharStrings
151
+ if charStrings.charStringsAreIndexed:
152
+ charStrings.charStringsIndex.fdArray = fdArray
153
+ else:
154
+ charStrings.fdArray = fdArray
155
+ fontDict = FontDict()
156
+ fontDict.setCFF2(True)
157
+ fdArray.append(fontDict)
158
+ fontDict.Private = privateDict
159
+ privateOpOrder = buildOrder(privateDictOperators2)
160
+ if privateDict is not None:
161
+ for entry in privateDictOperators:
162
+ key = entry[1]
163
+ if key not in privateOpOrder:
164
+ if key in privateDict.rawDict:
165
+ # print "Removing private dict", key
166
+ del privateDict.rawDict[key]
167
+ if hasattr(privateDict, key):
168
+ delattr(privateDict, key)
169
+ # print "Removing privateDict attr", key
170
+ else:
171
+ # clean up the PrivateDicts in the fdArray
172
+ fdArray = topDict.FDArray
173
+ privateOpOrder = buildOrder(privateDictOperators2)
174
+ for fontDict in fdArray:
175
+ fontDict.setCFF2(True)
176
+ for key in list(fontDict.rawDict.keys()):
177
+ if key not in fontDict.order:
178
+ del fontDict.rawDict[key]
179
+ if hasattr(fontDict, key):
180
+ delattr(fontDict, key)
181
+
182
+ privateDict = fontDict.Private
183
+ for entry in privateDictOperators:
184
+ key = entry[1]
185
+ if key not in privateOpOrder:
186
+ if key in list(privateDict.rawDict.keys()):
187
+ # print "Removing private dict", key
188
+ del privateDict.rawDict[key]
189
+ if hasattr(privateDict, key):
190
+ delattr(privateDict, key)
191
+ # print "Removing privateDict attr", key
192
+
193
+ # Now delete up the deprecated topDict operators from CFF 1.0
194
+ for entry in topDictOperators:
195
+ key = entry[1]
196
+ # We seem to need to keep the charset operator for now,
197
+ # or we fail to compile with some fonts, like AdditionFont.otf.
198
+ # I don't know which kind of CFF font those are. But keeping
199
+ # charset seems to work. It will be removed when we save and
200
+ # read the font again.
201
+ #
202
+ # AdditionFont.otf has <Encoding name="StandardEncoding"/>.
203
+ if key == "charset":
204
+ continue
205
+ if key not in opOrder:
206
+ if key in topDict.rawDict:
207
+ del topDict.rawDict[key]
208
+ if hasattr(topDict, key):
209
+ delattr(topDict, key)
210
+
211
+ # TODO(behdad): What does the following comment even mean? Both CFF and CFF2
212
+ # use the same T2Charstring class. I *think* what it means is that the CharStrings
213
+ # were loaded for CFF1, and we need to reload them for CFF2 to set varstore, etc
214
+ # on them. At least that's what I understand. It's probably safe to remove this
215
+ # and just set vstore where needed.
216
+ #
217
+ # See comment above about charset as well.
218
+
219
+ # At this point, the Subrs and Charstrings are all still T2Charstring class
220
+ # easiest to fix this by compiling, then decompiling again
221
+ file = BytesIO()
222
+ cff.compile(file, otFont, isCFF2=True)
223
+ file.seek(0)
224
+ cff.decompile(file, otFont, isCFF2=True)
225
+
226
+
227
+ def convertCFFToCFF2(font):
228
+ cff = font["CFF "].cff
229
+ del font["CFF "]
230
+ _convertCFFToCFF2(cff, font)
231
+ table = font["CFF2"] = newTable("CFF2")
232
+ table.cff = cff
233
+
234
+
235
+ def main(args=None):
236
+ """Convert CFF OTF font to CFF2 OTF font"""
237
+ if args is None:
238
+ import sys
239
+
240
+ args = sys.argv[1:]
241
+
242
+ import argparse
243
+
244
+ parser = argparse.ArgumentParser(
245
+ "fonttools cffLib.CFFToCFF2",
246
+ description="Upgrade a CFF font to CFF2.",
247
+ )
248
+ parser.add_argument(
249
+ "input", metavar="INPUT.ttf", help="Input OTF file with CFF table."
250
+ )
251
+ parser.add_argument(
252
+ "-o",
253
+ "--output",
254
+ metavar="OUTPUT.ttf",
255
+ default=None,
256
+ help="Output instance OTF file (default: INPUT-CFF2.ttf).",
257
+ )
258
+ parser.add_argument(
259
+ "--no-recalc-timestamp",
260
+ dest="recalc_timestamp",
261
+ action="store_false",
262
+ help="Don't set the output font's timestamp to the current time.",
263
+ )
264
+ loggingGroup = parser.add_mutually_exclusive_group(required=False)
265
+ loggingGroup.add_argument(
266
+ "-v", "--verbose", action="store_true", help="Run more verbosely."
267
+ )
268
+ loggingGroup.add_argument(
269
+ "-q", "--quiet", action="store_true", help="Turn verbosity off."
270
+ )
271
+ options = parser.parse_args(args)
272
+
273
+ from fontTools import configLogger
274
+
275
+ configLogger(
276
+ level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
277
+ )
278
+
279
+ import os
280
+
281
+ infile = options.input
282
+ if not os.path.isfile(infile):
283
+ parser.error("No such file '{}'".format(infile))
284
+
285
+ outfile = (
286
+ makeOutputFileName(infile, overWrite=True, suffix="-CFF2")
287
+ if not options.output
288
+ else options.output
289
+ )
290
+
291
+ font = TTFont(infile, recalcTimestamp=options.recalc_timestamp, recalcBBoxes=False)
292
+
293
+ convertCFFToCFF2(font)
294
+
295
+ log.info(
296
+ "Saving %s",
297
+ outfile,
298
+ )
299
+ font.save(outfile)
300
+
301
+
302
+ if __name__ == "__main__":
303
+ import sys
304
+
305
+ sys.exit(main(sys.argv[1:]))
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cffLib/__init__.py ADDED
The diff for this file is too large to render. See raw diff
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cffLib/specializer.py ADDED
@@ -0,0 +1,927 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ """T2CharString operator specializer and generalizer.
4
+
5
+ PostScript glyph drawing operations can be expressed in multiple different
6
+ ways. For example, as well as the ``lineto`` operator, there is also a
7
+ ``hlineto`` operator which draws a horizontal line, removing the need to
8
+ specify a ``dx`` coordinate, and a ``vlineto`` operator which draws a
9
+ vertical line, removing the need to specify a ``dy`` coordinate. As well
10
+ as decompiling :class:`fontTools.misc.psCharStrings.T2CharString` objects
11
+ into lists of operations, this module allows for conversion between general
12
+ and specific forms of the operation.
13
+
14
+ """
15
+
16
+ from fontTools.cffLib import maxStackLimit
17
+
18
+
19
+ def stringToProgram(string):
20
+ if isinstance(string, str):
21
+ string = string.split()
22
+ program = []
23
+ for token in string:
24
+ try:
25
+ token = int(token)
26
+ except ValueError:
27
+ try:
28
+ token = float(token)
29
+ except ValueError:
30
+ pass
31
+ program.append(token)
32
+ return program
33
+
34
+
35
+ def programToString(program):
36
+ return " ".join(str(x) for x in program)
37
+
38
+
39
+ def programToCommands(program, getNumRegions=None):
40
+ """Takes a T2CharString program list and returns list of commands.
41
+ Each command is a two-tuple of commandname,arg-list. The commandname might
42
+ be empty string if no commandname shall be emitted (used for glyph width,
43
+ hintmask/cntrmask argument, as well as stray arguments at the end of the
44
+ program (🤷).
45
+ 'getNumRegions' may be None, or a callable object. It must return the
46
+ number of regions. 'getNumRegions' takes a single argument, vsindex. It
47
+ returns the numRegions for the vsindex.
48
+ The Charstring may or may not start with a width value. If the first
49
+ non-blend operator has an odd number of arguments, then the first argument is
50
+ a width, and is popped off. This is complicated with blend operators, as
51
+ there may be more than one before the first hint or moveto operator, and each
52
+ one reduces several arguments to just one list argument. We have to sum the
53
+ number of arguments that are not part of the blend arguments, and all the
54
+ 'numBlends' values. We could instead have said that by definition, if there
55
+ is a blend operator, there is no width value, since CFF2 Charstrings don't
56
+ have width values. I discussed this with Behdad, and we are allowing for an
57
+ initial width value in this case because developers may assemble a CFF2
58
+ charstring from CFF Charstrings, which could have width values.
59
+ """
60
+
61
+ seenWidthOp = False
62
+ vsIndex = 0
63
+ lenBlendStack = 0
64
+ lastBlendIndex = 0
65
+ commands = []
66
+ stack = []
67
+ it = iter(program)
68
+
69
+ for token in it:
70
+ if not isinstance(token, str):
71
+ stack.append(token)
72
+ continue
73
+
74
+ if token == "blend":
75
+ assert getNumRegions is not None
76
+ numSourceFonts = 1 + getNumRegions(vsIndex)
77
+ # replace the blend op args on the stack with a single list
78
+ # containing all the blend op args.
79
+ numBlends = stack[-1]
80
+ numBlendArgs = numBlends * numSourceFonts + 1
81
+ # replace first blend op by a list of the blend ops.
82
+ stack[-numBlendArgs:] = [stack[-numBlendArgs:]]
83
+ lenStack = len(stack)
84
+ lenBlendStack += numBlends + lenStack - 1
85
+ lastBlendIndex = lenStack
86
+ # if a blend op exists, this is or will be a CFF2 charstring.
87
+ continue
88
+
89
+ elif token == "vsindex":
90
+ vsIndex = stack[-1]
91
+ assert type(vsIndex) is int
92
+
93
+ elif (not seenWidthOp) and token in {
94
+ "hstem",
95
+ "hstemhm",
96
+ "vstem",
97
+ "vstemhm",
98
+ "cntrmask",
99
+ "hintmask",
100
+ "hmoveto",
101
+ "vmoveto",
102
+ "rmoveto",
103
+ "endchar",
104
+ }:
105
+ seenWidthOp = True
106
+ parity = token in {"hmoveto", "vmoveto"}
107
+ if lenBlendStack:
108
+ # lenBlendStack has the number of args represented by the last blend
109
+ # arg and all the preceding args. We need to now add the number of
110
+ # args following the last blend arg.
111
+ numArgs = lenBlendStack + len(stack[lastBlendIndex:])
112
+ else:
113
+ numArgs = len(stack)
114
+ if numArgs and (numArgs % 2) ^ parity:
115
+ width = stack.pop(0)
116
+ commands.append(("", [width]))
117
+
118
+ if token in {"hintmask", "cntrmask"}:
119
+ if stack:
120
+ commands.append(("", stack))
121
+ commands.append((token, []))
122
+ commands.append(("", [next(it)]))
123
+ else:
124
+ commands.append((token, stack))
125
+ stack = []
126
+ if stack:
127
+ commands.append(("", stack))
128
+ return commands
129
+
130
+
131
+ def _flattenBlendArgs(args):
132
+ token_list = []
133
+ for arg in args:
134
+ if isinstance(arg, list):
135
+ token_list.extend(arg)
136
+ token_list.append("blend")
137
+ else:
138
+ token_list.append(arg)
139
+ return token_list
140
+
141
+
142
+ def commandsToProgram(commands):
143
+ """Takes a commands list as returned by programToCommands() and converts
144
+ it back to a T2CharString program list."""
145
+ program = []
146
+ for op, args in commands:
147
+ if any(isinstance(arg, list) for arg in args):
148
+ args = _flattenBlendArgs(args)
149
+ program.extend(args)
150
+ if op:
151
+ program.append(op)
152
+ return program
153
+
154
+
155
+ def _everyN(el, n):
156
+ """Group the list el into groups of size n"""
157
+ l = len(el)
158
+ if l % n != 0:
159
+ raise ValueError(el)
160
+ for i in range(0, l, n):
161
+ yield el[i : i + n]
162
+
163
+
164
+ class _GeneralizerDecombinerCommandsMap(object):
165
+ @staticmethod
166
+ def rmoveto(args):
167
+ if len(args) != 2:
168
+ raise ValueError(args)
169
+ yield ("rmoveto", args)
170
+
171
+ @staticmethod
172
+ def hmoveto(args):
173
+ if len(args) != 1:
174
+ raise ValueError(args)
175
+ yield ("rmoveto", [args[0], 0])
176
+
177
+ @staticmethod
178
+ def vmoveto(args):
179
+ if len(args) != 1:
180
+ raise ValueError(args)
181
+ yield ("rmoveto", [0, args[0]])
182
+
183
+ @staticmethod
184
+ def rlineto(args):
185
+ if not args:
186
+ raise ValueError(args)
187
+ for args in _everyN(args, 2):
188
+ yield ("rlineto", args)
189
+
190
+ @staticmethod
191
+ def hlineto(args):
192
+ if not args:
193
+ raise ValueError(args)
194
+ it = iter(args)
195
+ try:
196
+ while True:
197
+ yield ("rlineto", [next(it), 0])
198
+ yield ("rlineto", [0, next(it)])
199
+ except StopIteration:
200
+ pass
201
+
202
+ @staticmethod
203
+ def vlineto(args):
204
+ if not args:
205
+ raise ValueError(args)
206
+ it = iter(args)
207
+ try:
208
+ while True:
209
+ yield ("rlineto", [0, next(it)])
210
+ yield ("rlineto", [next(it), 0])
211
+ except StopIteration:
212
+ pass
213
+
214
+ @staticmethod
215
+ def rrcurveto(args):
216
+ if not args:
217
+ raise ValueError(args)
218
+ for args in _everyN(args, 6):
219
+ yield ("rrcurveto", args)
220
+
221
+ @staticmethod
222
+ def hhcurveto(args):
223
+ l = len(args)
224
+ if l < 4 or l % 4 > 1:
225
+ raise ValueError(args)
226
+ if l % 2 == 1:
227
+ yield ("rrcurveto", [args[1], args[0], args[2], args[3], args[4], 0])
228
+ args = args[5:]
229
+ for args in _everyN(args, 4):
230
+ yield ("rrcurveto", [args[0], 0, args[1], args[2], args[3], 0])
231
+
232
+ @staticmethod
233
+ def vvcurveto(args):
234
+ l = len(args)
235
+ if l < 4 or l % 4 > 1:
236
+ raise ValueError(args)
237
+ if l % 2 == 1:
238
+ yield ("rrcurveto", [args[0], args[1], args[2], args[3], 0, args[4]])
239
+ args = args[5:]
240
+ for args in _everyN(args, 4):
241
+ yield ("rrcurveto", [0, args[0], args[1], args[2], 0, args[3]])
242
+
243
+ @staticmethod
244
+ def hvcurveto(args):
245
+ l = len(args)
246
+ if l < 4 or l % 8 not in {0, 1, 4, 5}:
247
+ raise ValueError(args)
248
+ last_args = None
249
+ if l % 2 == 1:
250
+ lastStraight = l % 8 == 5
251
+ args, last_args = args[:-5], args[-5:]
252
+ it = _everyN(args, 4)
253
+ try:
254
+ while True:
255
+ args = next(it)
256
+ yield ("rrcurveto", [args[0], 0, args[1], args[2], 0, args[3]])
257
+ args = next(it)
258
+ yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], 0])
259
+ except StopIteration:
260
+ pass
261
+ if last_args:
262
+ args = last_args
263
+ if lastStraight:
264
+ yield ("rrcurveto", [args[0], 0, args[1], args[2], args[4], args[3]])
265
+ else:
266
+ yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], args[4]])
267
+
268
+ @staticmethod
269
+ def vhcurveto(args):
270
+ l = len(args)
271
+ if l < 4 or l % 8 not in {0, 1, 4, 5}:
272
+ raise ValueError(args)
273
+ last_args = None
274
+ if l % 2 == 1:
275
+ lastStraight = l % 8 == 5
276
+ args, last_args = args[:-5], args[-5:]
277
+ it = _everyN(args, 4)
278
+ try:
279
+ while True:
280
+ args = next(it)
281
+ yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], 0])
282
+ args = next(it)
283
+ yield ("rrcurveto", [args[0], 0, args[1], args[2], 0, args[3]])
284
+ except StopIteration:
285
+ pass
286
+ if last_args:
287
+ args = last_args
288
+ if lastStraight:
289
+ yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], args[4]])
290
+ else:
291
+ yield ("rrcurveto", [args[0], 0, args[1], args[2], args[4], args[3]])
292
+
293
+ @staticmethod
294
+ def rcurveline(args):
295
+ l = len(args)
296
+ if l < 8 or l % 6 != 2:
297
+ raise ValueError(args)
298
+ args, last_args = args[:-2], args[-2:]
299
+ for args in _everyN(args, 6):
300
+ yield ("rrcurveto", args)
301
+ yield ("rlineto", last_args)
302
+
303
+ @staticmethod
304
+ def rlinecurve(args):
305
+ l = len(args)
306
+ if l < 8 or l % 2 != 0:
307
+ raise ValueError(args)
308
+ args, last_args = args[:-6], args[-6:]
309
+ for args in _everyN(args, 2):
310
+ yield ("rlineto", args)
311
+ yield ("rrcurveto", last_args)
312
+
313
+
314
+ def _convertBlendOpToArgs(blendList):
315
+ # args is list of blend op args. Since we are supporting
316
+ # recursive blend op calls, some of these args may also
317
+ # be a list of blend op args, and need to be converted before
318
+ # we convert the current list.
319
+ if any([isinstance(arg, list) for arg in blendList]):
320
+ args = [
321
+ i
322
+ for e in blendList
323
+ for i in (_convertBlendOpToArgs(e) if isinstance(e, list) else [e])
324
+ ]
325
+ else:
326
+ args = blendList
327
+
328
+ # We now know that blendList contains a blend op argument list, even if
329
+ # some of the args are lists that each contain a blend op argument list.
330
+ # Convert from:
331
+ # [default font arg sequence x0,...,xn] + [delta tuple for x0] + ... + [delta tuple for xn]
332
+ # to:
333
+ # [ [x0] + [delta tuple for x0],
334
+ # ...,
335
+ # [xn] + [delta tuple for xn] ]
336
+ numBlends = args[-1]
337
+ # Can't use args.pop() when the args are being used in a nested list
338
+ # comprehension. See calling context
339
+ args = args[:-1]
340
+
341
+ l = len(args)
342
+ numRegions = l // numBlends - 1
343
+ if not (numBlends * (numRegions + 1) == l):
344
+ raise ValueError(blendList)
345
+
346
+ defaultArgs = [[arg] for arg in args[:numBlends]]
347
+ deltaArgs = args[numBlends:]
348
+ numDeltaValues = len(deltaArgs)
349
+ deltaList = [
350
+ deltaArgs[i : i + numRegions] for i in range(0, numDeltaValues, numRegions)
351
+ ]
352
+ blend_args = [a + b + [1] for a, b in zip(defaultArgs, deltaList)]
353
+ return blend_args
354
+
355
+
356
+ def generalizeCommands(commands, ignoreErrors=False):
357
+ result = []
358
+ mapping = _GeneralizerDecombinerCommandsMap
359
+ for op, args in commands:
360
+ # First, generalize any blend args in the arg list.
361
+ if any([isinstance(arg, list) for arg in args]):
362
+ try:
363
+ args = [
364
+ n
365
+ for arg in args
366
+ for n in (
367
+ _convertBlendOpToArgs(arg) if isinstance(arg, list) else [arg]
368
+ )
369
+ ]
370
+ except ValueError:
371
+ if ignoreErrors:
372
+ # Store op as data, such that consumers of commands do not have to
373
+ # deal with incorrect number of arguments.
374
+ result.append(("", args))
375
+ result.append(("", [op]))
376
+ else:
377
+ raise
378
+
379
+ func = getattr(mapping, op, None)
380
+ if func is None:
381
+ result.append((op, args))
382
+ continue
383
+ try:
384
+ for command in func(args):
385
+ result.append(command)
386
+ except ValueError:
387
+ if ignoreErrors:
388
+ # Store op as data, such that consumers of commands do not have to
389
+ # deal with incorrect number of arguments.
390
+ result.append(("", args))
391
+ result.append(("", [op]))
392
+ else:
393
+ raise
394
+ return result
395
+
396
+
397
+ def generalizeProgram(program, getNumRegions=None, **kwargs):
398
+ return commandsToProgram(
399
+ generalizeCommands(programToCommands(program, getNumRegions), **kwargs)
400
+ )
401
+
402
+
403
+ def _categorizeVector(v):
404
+ """
405
+ Takes X,Y vector v and returns one of r, h, v, or 0 depending on which
406
+ of X and/or Y are zero, plus tuple of nonzero ones. If both are zero,
407
+ it returns a single zero still.
408
+
409
+ >>> _categorizeVector((0,0))
410
+ ('0', (0,))
411
+ >>> _categorizeVector((1,0))
412
+ ('h', (1,))
413
+ >>> _categorizeVector((0,2))
414
+ ('v', (2,))
415
+ >>> _categorizeVector((1,2))
416
+ ('r', (1, 2))
417
+ """
418
+ if not v[0]:
419
+ if not v[1]:
420
+ return "0", v[:1]
421
+ else:
422
+ return "v", v[1:]
423
+ else:
424
+ if not v[1]:
425
+ return "h", v[:1]
426
+ else:
427
+ return "r", v
428
+
429
+
430
+ def _mergeCategories(a, b):
431
+ if a == "0":
432
+ return b
433
+ if b == "0":
434
+ return a
435
+ if a == b:
436
+ return a
437
+ return None
438
+
439
+
440
+ def _negateCategory(a):
441
+ if a == "h":
442
+ return "v"
443
+ if a == "v":
444
+ return "h"
445
+ assert a in "0r"
446
+ return a
447
+
448
+
449
+ def _convertToBlendCmds(args):
450
+ # return a list of blend commands, and
451
+ # the remaining non-blended args, if any.
452
+ num_args = len(args)
453
+ stack_use = 0
454
+ new_args = []
455
+ i = 0
456
+ while i < num_args:
457
+ arg = args[i]
458
+ i += 1
459
+ if not isinstance(arg, list):
460
+ new_args.append(arg)
461
+ stack_use += 1
462
+ else:
463
+ prev_stack_use = stack_use
464
+ # The arg is a tuple of blend values.
465
+ # These are each (master 0,delta 1..delta n, 1)
466
+ # Combine as many successive tuples as we can,
467
+ # up to the max stack limit.
468
+ num_sources = len(arg) - 1
469
+ blendlist = [arg]
470
+ stack_use += 1 + num_sources # 1 for the num_blends arg
471
+
472
+ # if we are here, max stack is the CFF2 max stack.
473
+ # I use the CFF2 max stack limit here rather than
474
+ # the 'maxstack' chosen by the client, as the default
475
+ # maxstack may have been used unintentionally. For all
476
+ # the other operators, this just produces a little less
477
+ # optimization, but here it puts a hard (and low) limit
478
+ # on the number of source fonts that can be used.
479
+ #
480
+ # Make sure the stack depth does not exceed (maxstack - 1), so
481
+ # that subroutinizer can insert subroutine calls at any point.
482
+ while (
483
+ (i < num_args)
484
+ and isinstance(args[i], list)
485
+ and stack_use + num_sources < maxStackLimit
486
+ ):
487
+ blendlist.append(args[i])
488
+ i += 1
489
+ stack_use += num_sources
490
+ # blendList now contains as many single blend tuples as can be
491
+ # combined without exceeding the CFF2 stack limit.
492
+ num_blends = len(blendlist)
493
+ # append the 'num_blends' default font values
494
+ blend_args = []
495
+ for arg in blendlist:
496
+ blend_args.append(arg[0])
497
+ for arg in blendlist:
498
+ assert arg[-1] == 1
499
+ blend_args.extend(arg[1:-1])
500
+ blend_args.append(num_blends)
501
+ new_args.append(blend_args)
502
+ stack_use = prev_stack_use + num_blends
503
+
504
+ return new_args
505
+
506
+
507
+ def _addArgs(a, b):
508
+ if isinstance(b, list):
509
+ if isinstance(a, list):
510
+ if len(a) != len(b) or a[-1] != b[-1]:
511
+ raise ValueError()
512
+ return [_addArgs(va, vb) for va, vb in zip(a[:-1], b[:-1])] + [a[-1]]
513
+ else:
514
+ a, b = b, a
515
+ if isinstance(a, list):
516
+ assert a[-1] == 1
517
+ return [_addArgs(a[0], b)] + a[1:]
518
+ return a + b
519
+
520
+
521
+ def _argsStackUse(args):
522
+ stackLen = 0
523
+ maxLen = 0
524
+ for arg in args:
525
+ if type(arg) is list:
526
+ # Blended arg
527
+ maxLen = max(maxLen, stackLen + _argsStackUse(arg))
528
+ stackLen += arg[-1]
529
+ else:
530
+ stackLen += 1
531
+ return max(stackLen, maxLen)
532
+
533
+
534
+ def specializeCommands(
535
+ commands,
536
+ ignoreErrors=False,
537
+ generalizeFirst=True,
538
+ preserveTopology=False,
539
+ maxstack=48,
540
+ ):
541
+ # We perform several rounds of optimizations. They are carefully ordered and are:
542
+ #
543
+ # 0. Generalize commands.
544
+ # This ensures that they are in our expected simple form, with each line/curve only
545
+ # having arguments for one segment, and using the generic form (rlineto/rrcurveto).
546
+ # If caller is sure the input is in this form, they can turn off generalization to
547
+ # save time.
548
+ #
549
+ # 1. Combine successive rmoveto operations.
550
+ #
551
+ # 2. Specialize rmoveto/rlineto/rrcurveto operators into horizontal/vertical variants.
552
+ # We specialize into some, made-up, variants as well, which simplifies following
553
+ # passes.
554
+ #
555
+ # 3. Merge or delete redundant operations, to the extent requested.
556
+ # OpenType spec declares point numbers in CFF undefined. As such, we happily
557
+ # change topology. If client relies on point numbers (in GPOS anchors, or for
558
+ # hinting purposes(what?)) they can turn this off.
559
+ #
560
+ # 4. Peephole optimization to revert back some of the h/v variants back into their
561
+ # original "relative" operator (rline/rrcurveto) if that saves a byte.
562
+ #
563
+ # 5. Combine adjacent operators when possible, minding not to go over max stack size.
564
+ #
565
+ # 6. Resolve any remaining made-up operators into real operators.
566
+ #
567
+ # I have convinced myself that this produces optimal bytecode (except for, possibly
568
+ # one byte each time maxstack size prohibits combining.) YMMV, but you'd be wrong. :-)
569
+ # A dynamic-programming approach can do the same but would be significantly slower.
570
+ #
571
+ # 7. For any args which are blend lists, convert them to a blend command.
572
+
573
+ # 0. Generalize commands.
574
+ if generalizeFirst:
575
+ commands = generalizeCommands(commands, ignoreErrors=ignoreErrors)
576
+ else:
577
+ commands = list(commands) # Make copy since we modify in-place later.
578
+
579
+ # 1. Combine successive rmoveto operations.
580
+ for i in range(len(commands) - 1, 0, -1):
581
+ if "rmoveto" == commands[i][0] == commands[i - 1][0]:
582
+ v1, v2 = commands[i - 1][1], commands[i][1]
583
+ commands[i - 1] = (
584
+ "rmoveto",
585
+ [_addArgs(v1[0], v2[0]), _addArgs(v1[1], v2[1])],
586
+ )
587
+ del commands[i]
588
+
589
+ # 2. Specialize rmoveto/rlineto/rrcurveto operators into horizontal/vertical variants.
590
+ #
591
+ # We, in fact, specialize into more, made-up, variants that special-case when both
592
+ # X and Y components are zero. This simplifies the following optimization passes.
593
+ # This case is rare, but OCD does not let me skip it.
594
+ #
595
+ # After this round, we will have four variants that use the following mnemonics:
596
+ #
597
+ # - 'r' for relative, ie. non-zero X and non-zero Y,
598
+ # - 'h' for horizontal, ie. zero X and non-zero Y,
599
+ # - 'v' for vertical, ie. non-zero X and zero Y,
600
+ # - '0' for zeros, ie. zero X and zero Y.
601
+ #
602
+ # The '0' pseudo-operators are not part of the spec, but help simplify the following
603
+ # optimization rounds. We resolve them at the end. So, after this, we will have four
604
+ # moveto and four lineto variants:
605
+ #
606
+ # - 0moveto, 0lineto
607
+ # - hmoveto, hlineto
608
+ # - vmoveto, vlineto
609
+ # - rmoveto, rlineto
610
+ #
611
+ # and sixteen curveto variants. For example, a '0hcurveto' operator means a curve
612
+ # dx0,dy0,dx1,dy1,dx2,dy2,dx3,dy3 where dx0, dx1, and dy3 are zero but not dx3.
613
+ # An 'rvcurveto' means dx3 is zero but not dx0,dy0,dy3.
614
+ #
615
+ # There are nine different variants of curves without the '0'. Those nine map exactly
616
+ # to the existing curve variants in the spec: rrcurveto, and the four variants hhcurveto,
617
+ # vvcurveto, hvcurveto, and vhcurveto each cover two cases, one with an odd number of
618
+ # arguments and one without. Eg. an hhcurveto with an extra argument (odd number of
619
+ # arguments) is in fact an rhcurveto. The operators in the spec are designed such that
620
+ # all four of rhcurveto, rvcurveto, hrcurveto, and vrcurveto are encodable for one curve.
621
+ #
622
+ # Of the curve types with '0', the 00curveto is equivalent to a lineto variant. The rest
623
+ # of the curve types with a 0 need to be encoded as a h or v variant. Ie. a '0' can be
624
+ # thought of a "don't care" and can be used as either an 'h' or a 'v'. As such, we always
625
+ # encode a number 0 as argument when we use a '0' variant. Later on, we can just substitute
626
+ # the '0' with either 'h' or 'v' and it works.
627
+ #
628
+ # When we get to curve splines however, things become more complicated... XXX finish this.
629
+ # There's one more complexity with splines. If one side of the spline is not horizontal or
630
+ # vertical (or zero), ie. if it's 'r', then it limits which spline types we can encode.
631
+ # Only hhcurveto and vvcurveto operators can encode a spline starting with 'r', and
632
+ # only hvcurveto and vhcurveto operators can encode a spline ending with 'r'.
633
+ # This limits our merge opportunities later.
634
+ #
635
+ for i in range(len(commands)):
636
+ op, args = commands[i]
637
+
638
+ if op in {"rmoveto", "rlineto"}:
639
+ c, args = _categorizeVector(args)
640
+ commands[i] = c + op[1:], args
641
+ continue
642
+
643
+ if op == "rrcurveto":
644
+ c1, args1 = _categorizeVector(args[:2])
645
+ c2, args2 = _categorizeVector(args[-2:])
646
+ commands[i] = c1 + c2 + "curveto", args1 + args[2:4] + args2
647
+ continue
648
+
649
+ # 3. Merge or delete redundant operations, to the extent requested.
650
+ #
651
+ # TODO
652
+ # A 0moveto that comes before all other path operations can be removed.
653
+ # though I find conflicting evidence for this.
654
+ #
655
+ # TODO
656
+ # "If hstem and vstem hints are both declared at the beginning of a
657
+ # CharString, and this sequence is followed directly by the hintmask or
658
+ # cntrmask operators, then the vstem hint operator (or, if applicable,
659
+ # the vstemhm operator) need not be included."
660
+ #
661
+ # "The sequence and form of a CFF2 CharString program may be represented as:
662
+ # {hs* vs* cm* hm* mt subpath}? {mt subpath}*"
663
+ #
664
+ # https://www.microsoft.com/typography/otspec/cff2charstr.htm#section3.1
665
+ #
666
+ # For Type2 CharStrings the sequence is:
667
+ # w? {hs* vs* cm* hm* mt subpath}? {mt subpath}* endchar"
668
+
669
+ # Some other redundancies change topology (point numbers).
670
+ if not preserveTopology:
671
+ for i in range(len(commands) - 1, -1, -1):
672
+ op, args = commands[i]
673
+
674
+ # A 00curveto is demoted to a (specialized) lineto.
675
+ if op == "00curveto":
676
+ assert len(args) == 4
677
+ c, args = _categorizeVector(args[1:3])
678
+ op = c + "lineto"
679
+ commands[i] = op, args
680
+ # and then...
681
+
682
+ # A 0lineto can be deleted.
683
+ if op == "0lineto":
684
+ del commands[i]
685
+ continue
686
+
687
+ # Merge adjacent hlineto's and vlineto's.
688
+ # In CFF2 charstrings from variable fonts, each
689
+ # arg item may be a list of blendable values, one from
690
+ # each source font.
691
+ if i and op in {"hlineto", "vlineto"} and (op == commands[i - 1][0]):
692
+ _, other_args = commands[i - 1]
693
+ assert len(args) == 1 and len(other_args) == 1
694
+ try:
695
+ new_args = [_addArgs(args[0], other_args[0])]
696
+ except ValueError:
697
+ continue
698
+ commands[i - 1] = (op, new_args)
699
+ del commands[i]
700
+ continue
701
+
702
+ # 4. Peephole optimization to revert back some of the h/v variants back into their
703
+ # original "relative" operator (rline/rrcurveto) if that saves a byte.
704
+ for i in range(1, len(commands) - 1):
705
+ op, args = commands[i]
706
+ prv, nxt = commands[i - 1][0], commands[i + 1][0]
707
+
708
+ if op in {"0lineto", "hlineto", "vlineto"} and prv == nxt == "rlineto":
709
+ assert len(args) == 1
710
+ args = [0, args[0]] if op[0] == "v" else [args[0], 0]
711
+ commands[i] = ("rlineto", args)
712
+ continue
713
+
714
+ if op[2:] == "curveto" and len(args) == 5 and prv == nxt == "rrcurveto":
715
+ assert (op[0] == "r") ^ (op[1] == "r")
716
+ if op[0] == "v":
717
+ pos = 0
718
+ elif op[0] != "r":
719
+ pos = 1
720
+ elif op[1] == "v":
721
+ pos = 4
722
+ else:
723
+ pos = 5
724
+ # Insert, while maintaining the type of args (can be tuple or list).
725
+ args = args[:pos] + type(args)((0,)) + args[pos:]
726
+ commands[i] = ("rrcurveto", args)
727
+ continue
728
+
729
+ # 5. Combine adjacent operators when possible, minding not to go over max stack size.
730
+ stackUse = _argsStackUse(commands[-1][1]) if commands else 0
731
+ for i in range(len(commands) - 1, 0, -1):
732
+ op1, args1 = commands[i - 1]
733
+ op2, args2 = commands[i]
734
+ new_op = None
735
+
736
+ # Merge logic...
737
+ if {op1, op2} <= {"rlineto", "rrcurveto"}:
738
+ if op1 == op2:
739
+ new_op = op1
740
+ else:
741
+ l = len(args2)
742
+ if op2 == "rrcurveto" and l == 6:
743
+ new_op = "rlinecurve"
744
+ elif l == 2:
745
+ new_op = "rcurveline"
746
+
747
+ elif (op1, op2) in {("rlineto", "rlinecurve"), ("rrcurveto", "rcurveline")}:
748
+ new_op = op2
749
+
750
+ elif {op1, op2} == {"vlineto", "hlineto"}:
751
+ new_op = op1
752
+
753
+ elif "curveto" == op1[2:] == op2[2:]:
754
+ d0, d1 = op1[:2]
755
+ d2, d3 = op2[:2]
756
+
757
+ if d1 == "r" or d2 == "r" or d0 == d3 == "r":
758
+ continue
759
+
760
+ d = _mergeCategories(d1, d2)
761
+ if d is None:
762
+ continue
763
+ if d0 == "r":
764
+ d = _mergeCategories(d, d3)
765
+ if d is None:
766
+ continue
767
+ new_op = "r" + d + "curveto"
768
+ elif d3 == "r":
769
+ d0 = _mergeCategories(d0, _negateCategory(d))
770
+ if d0 is None:
771
+ continue
772
+ new_op = d0 + "r" + "curveto"
773
+ else:
774
+ d0 = _mergeCategories(d0, d3)
775
+ if d0 is None:
776
+ continue
777
+ new_op = d0 + d + "curveto"
778
+
779
+ # Make sure the stack depth does not exceed (maxstack - 1), so
780
+ # that subroutinizer can insert subroutine calls at any point.
781
+ args1StackUse = _argsStackUse(args1)
782
+ combinedStackUse = max(args1StackUse, len(args1) + stackUse)
783
+ if new_op and combinedStackUse < maxstack:
784
+ commands[i - 1] = (new_op, args1 + args2)
785
+ del commands[i]
786
+ stackUse = combinedStackUse
787
+ else:
788
+ stackUse = args1StackUse
789
+
790
+ # 6. Resolve any remaining made-up operators into real operators.
791
+ for i in range(len(commands)):
792
+ op, args = commands[i]
793
+
794
+ if op in {"0moveto", "0lineto"}:
795
+ commands[i] = "h" + op[1:], args
796
+ continue
797
+
798
+ if op[2:] == "curveto" and op[:2] not in {"rr", "hh", "vv", "vh", "hv"}:
799
+ l = len(args)
800
+
801
+ op0, op1 = op[:2]
802
+ if (op0 == "r") ^ (op1 == "r"):
803
+ assert l % 2 == 1
804
+ if op0 == "0":
805
+ op0 = "h"
806
+ if op1 == "0":
807
+ op1 = "h"
808
+ if op0 == "r":
809
+ op0 = op1
810
+ if op1 == "r":
811
+ op1 = _negateCategory(op0)
812
+ assert {op0, op1} <= {"h", "v"}, (op0, op1)
813
+
814
+ if l % 2:
815
+ if op0 != op1: # vhcurveto / hvcurveto
816
+ if (op0 == "h") ^ (l % 8 == 1):
817
+ # Swap last two args order
818
+ args = args[:-2] + args[-1:] + args[-2:-1]
819
+ else: # hhcurveto / vvcurveto
820
+ if op0 == "h": # hhcurveto
821
+ # Swap first two args order
822
+ args = args[1:2] + args[:1] + args[2:]
823
+
824
+ commands[i] = op0 + op1 + "curveto", args
825
+ continue
826
+
827
+ # 7. For any series of args which are blend lists, convert the series to a single blend arg.
828
+ for i in range(len(commands)):
829
+ op, args = commands[i]
830
+ if any(isinstance(arg, list) for arg in args):
831
+ commands[i] = op, _convertToBlendCmds(args)
832
+
833
+ return commands
834
+
835
+
836
+ def specializeProgram(program, getNumRegions=None, **kwargs):
837
+ return commandsToProgram(
838
+ specializeCommands(programToCommands(program, getNumRegions), **kwargs)
839
+ )
840
+
841
+
842
+ if __name__ == "__main__":
843
+ import sys
844
+
845
+ if len(sys.argv) == 1:
846
+ import doctest
847
+
848
+ sys.exit(doctest.testmod().failed)
849
+
850
+ import argparse
851
+
852
+ parser = argparse.ArgumentParser(
853
+ "fonttools cffLib.specializer",
854
+ description="CFF CharString generalizer/specializer",
855
+ )
856
+ parser.add_argument("program", metavar="command", nargs="*", help="Commands.")
857
+ parser.add_argument(
858
+ "--num-regions",
859
+ metavar="NumRegions",
860
+ nargs="*",
861
+ default=None,
862
+ help="Number of variable-font regions for blend opertaions.",
863
+ )
864
+ parser.add_argument(
865
+ "--font",
866
+ metavar="FONTFILE",
867
+ default=None,
868
+ help="CFF2 font to specialize.",
869
+ )
870
+ parser.add_argument(
871
+ "-o",
872
+ "--output-file",
873
+ type=str,
874
+ help="Output font file name.",
875
+ )
876
+
877
+ options = parser.parse_args(sys.argv[1:])
878
+
879
+ if options.program:
880
+ getNumRegions = (
881
+ None
882
+ if options.num_regions is None
883
+ else lambda vsIndex: int(
884
+ options.num_regions[0 if vsIndex is None else vsIndex]
885
+ )
886
+ )
887
+
888
+ program = stringToProgram(options.program)
889
+ print("Program:")
890
+ print(programToString(program))
891
+ commands = programToCommands(program, getNumRegions)
892
+ print("Commands:")
893
+ print(commands)
894
+ program2 = commandsToProgram(commands)
895
+ print("Program from commands:")
896
+ print(programToString(program2))
897
+ assert program == program2
898
+ print("Generalized program:")
899
+ print(programToString(generalizeProgram(program, getNumRegions)))
900
+ print("Specialized program:")
901
+ print(programToString(specializeProgram(program, getNumRegions)))
902
+
903
+ if options.font:
904
+ from fontTools.ttLib import TTFont
905
+
906
+ font = TTFont(options.font)
907
+ cff2 = font["CFF2"].cff.topDictIndex[0]
908
+ charstrings = cff2.CharStrings
909
+ for glyphName in charstrings.keys():
910
+ charstring = charstrings[glyphName]
911
+ charstring.decompile()
912
+ getNumRegions = charstring.private.getNumRegions
913
+ charstring.program = specializeProgram(
914
+ charstring.program, getNumRegions, maxstack=maxStackLimit
915
+ )
916
+
917
+ if options.output_file is None:
918
+ from fontTools.misc.cliTools import makeOutputFileName
919
+
920
+ outfile = makeOutputFileName(
921
+ options.font, overWrite=True, suffix=".specialized"
922
+ )
923
+ else:
924
+ outfile = options.output_file
925
+ if outfile:
926
+ print("Saving", outfile)
927
+ font.save(outfile)
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cffLib/transforms.py ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc.psCharStrings import (
2
+ SimpleT2Decompiler,
3
+ T2WidthExtractor,
4
+ calcSubrBias,
5
+ )
6
+
7
+
8
+ def _uniq_sort(l):
9
+ return sorted(set(l))
10
+
11
+
12
+ class StopHintCountEvent(Exception):
13
+ pass
14
+
15
+
16
+ class _DesubroutinizingT2Decompiler(SimpleT2Decompiler):
17
+ stop_hintcount_ops = (
18
+ "op_hintmask",
19
+ "op_cntrmask",
20
+ "op_rmoveto",
21
+ "op_hmoveto",
22
+ "op_vmoveto",
23
+ )
24
+
25
+ def __init__(self, localSubrs, globalSubrs, private=None):
26
+ SimpleT2Decompiler.__init__(self, localSubrs, globalSubrs, private)
27
+
28
+ def execute(self, charString):
29
+ self.need_hintcount = True # until proven otherwise
30
+ for op_name in self.stop_hintcount_ops:
31
+ setattr(self, op_name, self.stop_hint_count)
32
+
33
+ if hasattr(charString, "_desubroutinized"):
34
+ # If a charstring has already been desubroutinized, we will still
35
+ # need to execute it if we need to count hints in order to
36
+ # compute the byte length for mask arguments, and haven't finished
37
+ # counting hints pairs.
38
+ if self.need_hintcount and self.callingStack:
39
+ try:
40
+ SimpleT2Decompiler.execute(self, charString)
41
+ except StopHintCountEvent:
42
+ del self.callingStack[-1]
43
+ return
44
+
45
+ charString._patches = []
46
+ SimpleT2Decompiler.execute(self, charString)
47
+ desubroutinized = charString.program[:]
48
+ for idx, expansion in reversed(charString._patches):
49
+ assert idx >= 2
50
+ assert desubroutinized[idx - 1] in [
51
+ "callsubr",
52
+ "callgsubr",
53
+ ], desubroutinized[idx - 1]
54
+ assert type(desubroutinized[idx - 2]) == int
55
+ if expansion[-1] == "return":
56
+ expansion = expansion[:-1]
57
+ desubroutinized[idx - 2 : idx] = expansion
58
+ if not self.private.in_cff2:
59
+ if "endchar" in desubroutinized:
60
+ # Cut off after first endchar
61
+ desubroutinized = desubroutinized[
62
+ : desubroutinized.index("endchar") + 1
63
+ ]
64
+
65
+ charString._desubroutinized = desubroutinized
66
+ del charString._patches
67
+
68
+ def op_callsubr(self, index):
69
+ subr = self.localSubrs[self.operandStack[-1] + self.localBias]
70
+ SimpleT2Decompiler.op_callsubr(self, index)
71
+ self.processSubr(index, subr)
72
+
73
+ def op_callgsubr(self, index):
74
+ subr = self.globalSubrs[self.operandStack[-1] + self.globalBias]
75
+ SimpleT2Decompiler.op_callgsubr(self, index)
76
+ self.processSubr(index, subr)
77
+
78
+ def stop_hint_count(self, *args):
79
+ self.need_hintcount = False
80
+ for op_name in self.stop_hintcount_ops:
81
+ setattr(self, op_name, None)
82
+ cs = self.callingStack[-1]
83
+ if hasattr(cs, "_desubroutinized"):
84
+ raise StopHintCountEvent()
85
+
86
+ def op_hintmask(self, index):
87
+ SimpleT2Decompiler.op_hintmask(self, index)
88
+ if self.need_hintcount:
89
+ self.stop_hint_count()
90
+
91
+ def processSubr(self, index, subr):
92
+ cs = self.callingStack[-1]
93
+ if not hasattr(cs, "_desubroutinized"):
94
+ cs._patches.append((index, subr._desubroutinized))
95
+
96
+
97
+ def desubroutinizeCharString(cs):
98
+ """Desubroutinize a charstring in-place."""
99
+ cs.decompile()
100
+ subrs = getattr(cs.private, "Subrs", [])
101
+ decompiler = _DesubroutinizingT2Decompiler(subrs, cs.globalSubrs, cs.private)
102
+ decompiler.execute(cs)
103
+ cs.program = cs._desubroutinized
104
+ del cs._desubroutinized
105
+
106
+
107
+ def desubroutinize(cff):
108
+ for fontName in cff.fontNames:
109
+ font = cff[fontName]
110
+ cs = font.CharStrings
111
+ for c in cs.values():
112
+ desubroutinizeCharString(c)
113
+ # Delete all the local subrs
114
+ if hasattr(font, "FDArray"):
115
+ for fd in font.FDArray:
116
+ pd = fd.Private
117
+ if hasattr(pd, "Subrs"):
118
+ del pd.Subrs
119
+ if "Subrs" in pd.rawDict:
120
+ del pd.rawDict["Subrs"]
121
+ else:
122
+ pd = font.Private
123
+ if hasattr(pd, "Subrs"):
124
+ del pd.Subrs
125
+ if "Subrs" in pd.rawDict:
126
+ del pd.rawDict["Subrs"]
127
+ # as well as the global subrs
128
+ cff.GlobalSubrs.clear()
129
+
130
+
131
+ class _MarkingT2Decompiler(SimpleT2Decompiler):
132
+ def __init__(self, localSubrs, globalSubrs, private):
133
+ SimpleT2Decompiler.__init__(self, localSubrs, globalSubrs, private)
134
+ for subrs in [localSubrs, globalSubrs]:
135
+ if subrs and not hasattr(subrs, "_used"):
136
+ subrs._used = set()
137
+
138
+ def op_callsubr(self, index):
139
+ self.localSubrs._used.add(self.operandStack[-1] + self.localBias)
140
+ SimpleT2Decompiler.op_callsubr(self, index)
141
+
142
+ def op_callgsubr(self, index):
143
+ self.globalSubrs._used.add(self.operandStack[-1] + self.globalBias)
144
+ SimpleT2Decompiler.op_callgsubr(self, index)
145
+
146
+
147
+ class _DehintingT2Decompiler(T2WidthExtractor):
148
+ class Hints(object):
149
+ def __init__(self):
150
+ # Whether calling this charstring produces any hint stems
151
+ # Note that if a charstring starts with hintmask, it will
152
+ # have has_hint set to True, because it *might* produce an
153
+ # implicit vstem if called under certain conditions.
154
+ self.has_hint = False
155
+ # Index to start at to drop all hints
156
+ self.last_hint = 0
157
+ # Index up to which we know more hints are possible.
158
+ # Only relevant if status is 0 or 1.
159
+ self.last_checked = 0
160
+ # The status means:
161
+ # 0: after dropping hints, this charstring is empty
162
+ # 1: after dropping hints, there may be more hints
163
+ # continuing after this, or there might be
164
+ # other things. Not clear yet.
165
+ # 2: no more hints possible after this charstring
166
+ self.status = 0
167
+ # Has hintmask instructions; not recursive
168
+ self.has_hintmask = False
169
+ # List of indices of calls to empty subroutines to remove.
170
+ self.deletions = []
171
+
172
+ pass
173
+
174
+ def __init__(
175
+ self, css, localSubrs, globalSubrs, nominalWidthX, defaultWidthX, private=None
176
+ ):
177
+ self._css = css
178
+ T2WidthExtractor.__init__(
179
+ self, localSubrs, globalSubrs, nominalWidthX, defaultWidthX
180
+ )
181
+ self.private = private
182
+
183
+ def execute(self, charString):
184
+ old_hints = charString._hints if hasattr(charString, "_hints") else None
185
+ charString._hints = self.Hints()
186
+
187
+ T2WidthExtractor.execute(self, charString)
188
+
189
+ hints = charString._hints
190
+
191
+ if hints.has_hint or hints.has_hintmask:
192
+ self._css.add(charString)
193
+
194
+ if hints.status != 2:
195
+ # Check from last_check, make sure we didn't have any operators.
196
+ for i in range(hints.last_checked, len(charString.program) - 1):
197
+ if isinstance(charString.program[i], str):
198
+ hints.status = 2
199
+ break
200
+ else:
201
+ hints.status = 1 # There's *something* here
202
+ hints.last_checked = len(charString.program)
203
+
204
+ if old_hints:
205
+ assert hints.__dict__ == old_hints.__dict__
206
+
207
+ def op_callsubr(self, index):
208
+ subr = self.localSubrs[self.operandStack[-1] + self.localBias]
209
+ T2WidthExtractor.op_callsubr(self, index)
210
+ self.processSubr(index, subr)
211
+
212
+ def op_callgsubr(self, index):
213
+ subr = self.globalSubrs[self.operandStack[-1] + self.globalBias]
214
+ T2WidthExtractor.op_callgsubr(self, index)
215
+ self.processSubr(index, subr)
216
+
217
+ def op_hstem(self, index):
218
+ T2WidthExtractor.op_hstem(self, index)
219
+ self.processHint(index)
220
+
221
+ def op_vstem(self, index):
222
+ T2WidthExtractor.op_vstem(self, index)
223
+ self.processHint(index)
224
+
225
+ def op_hstemhm(self, index):
226
+ T2WidthExtractor.op_hstemhm(self, index)
227
+ self.processHint(index)
228
+
229
+ def op_vstemhm(self, index):
230
+ T2WidthExtractor.op_vstemhm(self, index)
231
+ self.processHint(index)
232
+
233
+ def op_hintmask(self, index):
234
+ rv = T2WidthExtractor.op_hintmask(self, index)
235
+ self.processHintmask(index)
236
+ return rv
237
+
238
+ def op_cntrmask(self, index):
239
+ rv = T2WidthExtractor.op_cntrmask(self, index)
240
+ self.processHintmask(index)
241
+ return rv
242
+
243
+ def processHintmask(self, index):
244
+ cs = self.callingStack[-1]
245
+ hints = cs._hints
246
+ hints.has_hintmask = True
247
+ if hints.status != 2:
248
+ # Check from last_check, see if we may be an implicit vstem
249
+ for i in range(hints.last_checked, index - 1):
250
+ if isinstance(cs.program[i], str):
251
+ hints.status = 2
252
+ break
253
+ else:
254
+ # We are an implicit vstem
255
+ hints.has_hint = True
256
+ hints.last_hint = index + 1
257
+ hints.status = 0
258
+ hints.last_checked = index + 1
259
+
260
+ def processHint(self, index):
261
+ cs = self.callingStack[-1]
262
+ hints = cs._hints
263
+ hints.has_hint = True
264
+ hints.last_hint = index
265
+ hints.last_checked = index
266
+
267
+ def processSubr(self, index, subr):
268
+ cs = self.callingStack[-1]
269
+ hints = cs._hints
270
+ subr_hints = subr._hints
271
+
272
+ # Check from last_check, make sure we didn't have
273
+ # any operators.
274
+ if hints.status != 2:
275
+ for i in range(hints.last_checked, index - 1):
276
+ if isinstance(cs.program[i], str):
277
+ hints.status = 2
278
+ break
279
+ hints.last_checked = index
280
+
281
+ if hints.status != 2:
282
+ if subr_hints.has_hint:
283
+ hints.has_hint = True
284
+
285
+ # Decide where to chop off from
286
+ if subr_hints.status == 0:
287
+ hints.last_hint = index
288
+ else:
289
+ hints.last_hint = index - 2 # Leave the subr call in
290
+
291
+ elif subr_hints.status == 0:
292
+ hints.deletions.append(index)
293
+
294
+ hints.status = max(hints.status, subr_hints.status)
295
+
296
+
297
+ def _cs_subset_subroutines(charstring, subrs, gsubrs):
298
+ p = charstring.program
299
+ for i in range(1, len(p)):
300
+ if p[i] == "callsubr":
301
+ assert isinstance(p[i - 1], int)
302
+ p[i - 1] = subrs._used.index(p[i - 1] + subrs._old_bias) - subrs._new_bias
303
+ elif p[i] == "callgsubr":
304
+ assert isinstance(p[i - 1], int)
305
+ p[i - 1] = (
306
+ gsubrs._used.index(p[i - 1] + gsubrs._old_bias) - gsubrs._new_bias
307
+ )
308
+
309
+
310
+ def _cs_drop_hints(charstring):
311
+ hints = charstring._hints
312
+
313
+ if hints.deletions:
314
+ p = charstring.program
315
+ for idx in reversed(hints.deletions):
316
+ del p[idx - 2 : idx]
317
+
318
+ if hints.has_hint:
319
+ assert not hints.deletions or hints.last_hint <= hints.deletions[0]
320
+ charstring.program = charstring.program[hints.last_hint :]
321
+ if not charstring.program:
322
+ # TODO CFF2 no need for endchar.
323
+ charstring.program.append("endchar")
324
+ if hasattr(charstring, "width"):
325
+ # Insert width back if needed
326
+ if charstring.width != charstring.private.defaultWidthX:
327
+ # For CFF2 charstrings, this should never happen
328
+ assert (
329
+ charstring.private.defaultWidthX is not None
330
+ ), "CFF2 CharStrings must not have an initial width value"
331
+ charstring.program.insert(
332
+ 0, charstring.width - charstring.private.nominalWidthX
333
+ )
334
+
335
+ if hints.has_hintmask:
336
+ i = 0
337
+ p = charstring.program
338
+ while i < len(p):
339
+ if p[i] in ["hintmask", "cntrmask"]:
340
+ assert i + 1 <= len(p)
341
+ del p[i : i + 2]
342
+ continue
343
+ i += 1
344
+
345
+ assert len(charstring.program)
346
+
347
+ del charstring._hints
348
+
349
+
350
+ def remove_hints(cff, *, removeUnusedSubrs: bool = True):
351
+ for fontname in cff.keys():
352
+ font = cff[fontname]
353
+ cs = font.CharStrings
354
+ # This can be tricky, but doesn't have to. What we do is:
355
+ #
356
+ # - Run all used glyph charstrings and recurse into subroutines,
357
+ # - For each charstring (including subroutines), if it has any
358
+ # of the hint stem operators, we mark it as such.
359
+ # Upon returning, for each charstring we note all the
360
+ # subroutine calls it makes that (recursively) contain a stem,
361
+ # - Dropping hinting then consists of the following two ops:
362
+ # * Drop the piece of the program in each charstring before the
363
+ # last call to a stem op or a stem-calling subroutine,
364
+ # * Drop all hintmask operations.
365
+ # - It's trickier... A hintmask right after hints and a few numbers
366
+ # will act as an implicit vstemhm. As such, we track whether
367
+ # we have seen any non-hint operators so far and do the right
368
+ # thing, recursively... Good luck understanding that :(
369
+ css = set()
370
+ for c in cs.values():
371
+ c.decompile()
372
+ subrs = getattr(c.private, "Subrs", [])
373
+ decompiler = _DehintingT2Decompiler(
374
+ css,
375
+ subrs,
376
+ c.globalSubrs,
377
+ c.private.nominalWidthX,
378
+ c.private.defaultWidthX,
379
+ c.private,
380
+ )
381
+ decompiler.execute(c)
382
+ c.width = decompiler.width
383
+ for charstring in css:
384
+ _cs_drop_hints(charstring)
385
+ del css
386
+
387
+ # Drop font-wide hinting values
388
+ all_privs = []
389
+ if hasattr(font, "FDArray"):
390
+ all_privs.extend(fd.Private for fd in font.FDArray)
391
+ else:
392
+ all_privs.append(font.Private)
393
+ for priv in all_privs:
394
+ for k in [
395
+ "BlueValues",
396
+ "OtherBlues",
397
+ "FamilyBlues",
398
+ "FamilyOtherBlues",
399
+ "BlueScale",
400
+ "BlueShift",
401
+ "BlueFuzz",
402
+ "StemSnapH",
403
+ "StemSnapV",
404
+ "StdHW",
405
+ "StdVW",
406
+ "ForceBold",
407
+ "LanguageGroup",
408
+ "ExpansionFactor",
409
+ ]:
410
+ if hasattr(priv, k):
411
+ setattr(priv, k, None)
412
+ if removeUnusedSubrs:
413
+ remove_unused_subroutines(cff)
414
+
415
+
416
+ def _pd_delete_empty_subrs(private_dict):
417
+ if hasattr(private_dict, "Subrs") and not private_dict.Subrs:
418
+ if "Subrs" in private_dict.rawDict:
419
+ del private_dict.rawDict["Subrs"]
420
+ del private_dict.Subrs
421
+
422
+
423
+ def remove_unused_subroutines(cff):
424
+ for fontname in cff.keys():
425
+ font = cff[fontname]
426
+ cs = font.CharStrings
427
+ # Renumber subroutines to remove unused ones
428
+
429
+ # Mark all used subroutines
430
+ for c in cs.values():
431
+ subrs = getattr(c.private, "Subrs", [])
432
+ decompiler = _MarkingT2Decompiler(subrs, c.globalSubrs, c.private)
433
+ decompiler.execute(c)
434
+
435
+ all_subrs = [font.GlobalSubrs]
436
+ if hasattr(font, "FDArray"):
437
+ all_subrs.extend(
438
+ fd.Private.Subrs
439
+ for fd in font.FDArray
440
+ if hasattr(fd.Private, "Subrs") and fd.Private.Subrs
441
+ )
442
+ elif hasattr(font.Private, "Subrs") and font.Private.Subrs:
443
+ all_subrs.append(font.Private.Subrs)
444
+
445
+ subrs = set(subrs) # Remove duplicates
446
+
447
+ # Prepare
448
+ for subrs in all_subrs:
449
+ if not hasattr(subrs, "_used"):
450
+ subrs._used = set()
451
+ subrs._used = _uniq_sort(subrs._used)
452
+ subrs._old_bias = calcSubrBias(subrs)
453
+ subrs._new_bias = calcSubrBias(subrs._used)
454
+
455
+ # Renumber glyph charstrings
456
+ for c in cs.values():
457
+ subrs = getattr(c.private, "Subrs", None)
458
+ _cs_subset_subroutines(c, subrs, font.GlobalSubrs)
459
+
460
+ # Renumber subroutines themselves
461
+ for subrs in all_subrs:
462
+ if subrs == font.GlobalSubrs:
463
+ if not hasattr(font, "FDArray") and hasattr(font.Private, "Subrs"):
464
+ local_subrs = font.Private.Subrs
465
+ elif (
466
+ hasattr(font, "FDArray")
467
+ and len(font.FDArray) == 1
468
+ and hasattr(font.FDArray[0].Private, "Subrs")
469
+ ):
470
+ # Technically we shouldn't do this. But I've run into fonts that do it.
471
+ local_subrs = font.FDArray[0].Private.Subrs
472
+ else:
473
+ local_subrs = None
474
+ else:
475
+ local_subrs = subrs
476
+
477
+ subrs.items = [subrs.items[i] for i in subrs._used]
478
+ if hasattr(subrs, "file"):
479
+ del subrs.file
480
+ if hasattr(subrs, "offsets"):
481
+ del subrs.offsets
482
+
483
+ for subr in subrs.items:
484
+ _cs_subset_subroutines(subr, local_subrs, font.GlobalSubrs)
485
+
486
+ # Delete local SubrsIndex if empty
487
+ if hasattr(font, "FDArray"):
488
+ for fd in font.FDArray:
489
+ _pd_delete_empty_subrs(fd.Private)
490
+ else:
491
+ _pd_delete_empty_subrs(font.Private)
492
+
493
+ # Cleanup
494
+ for subrs in all_subrs:
495
+ del subrs._used, subrs._old_bias, subrs._new_bias
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cffLib/width.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ """T2CharString glyph width optimizer.
4
+
5
+ CFF glyphs whose width equals the CFF Private dictionary's ``defaultWidthX``
6
+ value do not need to specify their width in their charstring, saving bytes.
7
+ This module determines the optimum ``defaultWidthX`` and ``nominalWidthX``
8
+ values for a font, when provided with a list of glyph widths."""
9
+
10
+ from fontTools.ttLib import TTFont
11
+ from collections import defaultdict
12
+ from operator import add
13
+ from functools import reduce
14
+
15
+
16
+ __all__ = ["optimizeWidths", "main"]
17
+
18
+
19
+ class missingdict(dict):
20
+ def __init__(self, missing_func):
21
+ self.missing_func = missing_func
22
+
23
+ def __missing__(self, v):
24
+ return self.missing_func(v)
25
+
26
+
27
+ def cumSum(f, op=add, start=0, decreasing=False):
28
+ keys = sorted(f.keys())
29
+ minx, maxx = keys[0], keys[-1]
30
+
31
+ total = reduce(op, f.values(), start)
32
+
33
+ if decreasing:
34
+ missing = lambda x: start if x > maxx else total
35
+ domain = range(maxx, minx - 1, -1)
36
+ else:
37
+ missing = lambda x: start if x < minx else total
38
+ domain = range(minx, maxx + 1)
39
+
40
+ out = missingdict(missing)
41
+
42
+ v = start
43
+ for x in domain:
44
+ v = op(v, f[x])
45
+ out[x] = v
46
+
47
+ return out
48
+
49
+
50
+ def byteCost(widths, default, nominal):
51
+ if not hasattr(widths, "items"):
52
+ d = defaultdict(int)
53
+ for w in widths:
54
+ d[w] += 1
55
+ widths = d
56
+
57
+ cost = 0
58
+ for w, freq in widths.items():
59
+ if w == default:
60
+ continue
61
+ diff = abs(w - nominal)
62
+ if diff <= 107:
63
+ cost += freq
64
+ elif diff <= 1131:
65
+ cost += freq * 2
66
+ else:
67
+ cost += freq * 5
68
+ return cost
69
+
70
+
71
+ def optimizeWidthsBruteforce(widths):
72
+ """Bruteforce version. Veeeeeeeeeeeeeeeeery slow. Only works for smallests of fonts."""
73
+
74
+ d = defaultdict(int)
75
+ for w in widths:
76
+ d[w] += 1
77
+
78
+ # Maximum number of bytes using default can possibly save
79
+ maxDefaultAdvantage = 5 * max(d.values())
80
+
81
+ minw, maxw = min(widths), max(widths)
82
+ domain = list(range(minw, maxw + 1))
83
+
84
+ bestCostWithoutDefault = min(byteCost(widths, None, nominal) for nominal in domain)
85
+
86
+ bestCost = len(widths) * 5 + 1
87
+ for nominal in domain:
88
+ if byteCost(widths, None, nominal) > bestCost + maxDefaultAdvantage:
89
+ continue
90
+ for default in domain:
91
+ cost = byteCost(widths, default, nominal)
92
+ if cost < bestCost:
93
+ bestCost = cost
94
+ bestDefault = default
95
+ bestNominal = nominal
96
+
97
+ return bestDefault, bestNominal
98
+
99
+
100
+ def optimizeWidths(widths):
101
+ """Given a list of glyph widths, or dictionary mapping glyph width to number of
102
+ glyphs having that, returns a tuple of best CFF default and nominal glyph widths.
103
+
104
+ This algorithm is linear in UPEM+numGlyphs."""
105
+
106
+ if not hasattr(widths, "items"):
107
+ d = defaultdict(int)
108
+ for w in widths:
109
+ d[w] += 1
110
+ widths = d
111
+
112
+ keys = sorted(widths.keys())
113
+ minw, maxw = keys[0], keys[-1]
114
+ domain = list(range(minw, maxw + 1))
115
+
116
+ # Cumulative sum/max forward/backward.
117
+ cumFrqU = cumSum(widths, op=add)
118
+ cumMaxU = cumSum(widths, op=max)
119
+ cumFrqD = cumSum(widths, op=add, decreasing=True)
120
+ cumMaxD = cumSum(widths, op=max, decreasing=True)
121
+
122
+ # Cost per nominal choice, without default consideration.
123
+ nomnCostU = missingdict(
124
+ lambda x: cumFrqU[x] + cumFrqU[x - 108] + cumFrqU[x - 1132] * 3
125
+ )
126
+ nomnCostD = missingdict(
127
+ lambda x: cumFrqD[x] + cumFrqD[x + 108] + cumFrqD[x + 1132] * 3
128
+ )
129
+ nomnCost = missingdict(lambda x: nomnCostU[x] + nomnCostD[x] - widths[x])
130
+
131
+ # Cost-saving per nominal choice, by best default choice.
132
+ dfltCostU = missingdict(
133
+ lambda x: max(cumMaxU[x], cumMaxU[x - 108] * 2, cumMaxU[x - 1132] * 5)
134
+ )
135
+ dfltCostD = missingdict(
136
+ lambda x: max(cumMaxD[x], cumMaxD[x + 108] * 2, cumMaxD[x + 1132] * 5)
137
+ )
138
+ dfltCost = missingdict(lambda x: max(dfltCostU[x], dfltCostD[x]))
139
+
140
+ # Combined cost per nominal choice.
141
+ bestCost = missingdict(lambda x: nomnCost[x] - dfltCost[x])
142
+
143
+ # Best nominal.
144
+ nominal = min(domain, key=lambda x: bestCost[x])
145
+
146
+ # Work back the best default.
147
+ bestC = bestCost[nominal]
148
+ dfltC = nomnCost[nominal] - bestCost[nominal]
149
+ ends = []
150
+ if dfltC == dfltCostU[nominal]:
151
+ starts = [nominal, nominal - 108, nominal - 1132]
152
+ for start in starts:
153
+ while cumMaxU[start] and cumMaxU[start] == cumMaxU[start - 1]:
154
+ start -= 1
155
+ ends.append(start)
156
+ else:
157
+ starts = [nominal, nominal + 108, nominal + 1132]
158
+ for start in starts:
159
+ while cumMaxD[start] and cumMaxD[start] == cumMaxD[start + 1]:
160
+ start += 1
161
+ ends.append(start)
162
+ default = min(ends, key=lambda default: byteCost(widths, default, nominal))
163
+
164
+ return default, nominal
165
+
166
+
167
+ def main(args=None):
168
+ """Calculate optimum defaultWidthX/nominalWidthX values"""
169
+
170
+ import argparse
171
+
172
+ parser = argparse.ArgumentParser(
173
+ "fonttools cffLib.width",
174
+ description=main.__doc__,
175
+ )
176
+ parser.add_argument(
177
+ "inputs", metavar="FILE", type=str, nargs="+", help="Input TTF files"
178
+ )
179
+ parser.add_argument(
180
+ "-b",
181
+ "--brute-force",
182
+ dest="brute",
183
+ action="store_true",
184
+ help="Use brute-force approach (VERY slow)",
185
+ )
186
+
187
+ args = parser.parse_args(args)
188
+
189
+ for fontfile in args.inputs:
190
+ font = TTFont(fontfile)
191
+ hmtx = font["hmtx"]
192
+ widths = [m[0] for m in hmtx.metrics.values()]
193
+ if args.brute:
194
+ default, nominal = optimizeWidthsBruteforce(widths)
195
+ else:
196
+ default, nominal = optimizeWidths(widths)
197
+ print(
198
+ "glyphs=%d default=%d nominal=%d byteCost=%d"
199
+ % (len(widths), default, nominal, byteCost(widths, default, nominal))
200
+ )
201
+
202
+
203
+ if __name__ == "__main__":
204
+ import sys
205
+
206
+ if len(sys.argv) == 1:
207
+ import doctest
208
+
209
+ sys.exit(doctest.testmod().failed)
210
+ main()
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/colorLib/__init__.py ADDED
File without changes
Scripts_Climate_to_LAI/.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_to_LAI/.venv/lib/python3.10/site-packages/fontTools/colorLib/errors.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ class ColorLibError(Exception):
2
+ pass
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/colorLib/geometry.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpers for manipulating 2D points and vectors in COLR table."""
2
+
3
+ from math import copysign, cos, hypot, isclose, pi
4
+ from fontTools.misc.roundTools import otRound
5
+
6
+
7
+ def _vector_between(origin, target):
8
+ return (target[0] - origin[0], target[1] - origin[1])
9
+
10
+
11
+ def _round_point(pt):
12
+ return (otRound(pt[0]), otRound(pt[1]))
13
+
14
+
15
+ def _unit_vector(vec):
16
+ length = hypot(*vec)
17
+ if length == 0:
18
+ return None
19
+ return (vec[0] / length, vec[1] / length)
20
+
21
+
22
+ _CIRCLE_INSIDE_TOLERANCE = 1e-4
23
+
24
+
25
+ # The unit vector's X and Y components are respectively
26
+ # U = (cos(α), sin(α))
27
+ # where α is the angle between the unit vector and the positive x axis.
28
+ _UNIT_VECTOR_THRESHOLD = cos(3 / 8 * pi) # == sin(1/8 * pi) == 0.38268343236508984
29
+
30
+
31
+ def _rounding_offset(direction):
32
+ # Return 2-tuple of -/+ 1.0 or 0.0 approximately based on the direction vector.
33
+ # We divide the unit circle in 8 equal slices oriented towards the cardinal
34
+ # (N, E, S, W) and intermediate (NE, SE, SW, NW) directions. To each slice we
35
+ # map one of the possible cases: -1, 0, +1 for either X and Y coordinate.
36
+ # E.g. Return (+1.0, -1.0) if unit vector is oriented towards SE, or
37
+ # (-1.0, 0.0) if it's pointing West, etc.
38
+ uv = _unit_vector(direction)
39
+ if not uv:
40
+ return (0, 0)
41
+
42
+ result = []
43
+ for uv_component in uv:
44
+ if -_UNIT_VECTOR_THRESHOLD <= uv_component < _UNIT_VECTOR_THRESHOLD:
45
+ # unit vector component near 0: direction almost orthogonal to the
46
+ # direction of the current axis, thus keep coordinate unchanged
47
+ result.append(0)
48
+ else:
49
+ # nudge coord by +/- 1.0 in direction of unit vector
50
+ result.append(copysign(1.0, uv_component))
51
+ return tuple(result)
52
+
53
+
54
+ class Circle:
55
+ def __init__(self, centre, radius):
56
+ self.centre = centre
57
+ self.radius = radius
58
+
59
+ def __repr__(self):
60
+ return f"Circle(centre={self.centre}, radius={self.radius})"
61
+
62
+ def round(self):
63
+ return Circle(_round_point(self.centre), otRound(self.radius))
64
+
65
+ def inside(self, outer_circle, tolerance=_CIRCLE_INSIDE_TOLERANCE):
66
+ dist = self.radius + hypot(*_vector_between(self.centre, outer_circle.centre))
67
+ return (
68
+ isclose(outer_circle.radius, dist, rel_tol=_CIRCLE_INSIDE_TOLERANCE)
69
+ or outer_circle.radius > dist
70
+ )
71
+
72
+ def concentric(self, other):
73
+ return self.centre == other.centre
74
+
75
+ def move(self, dx, dy):
76
+ self.centre = (self.centre[0] + dx, self.centre[1] + dy)
77
+
78
+
79
+ def round_start_circle_stable_containment(c0, r0, c1, r1):
80
+ """Round start circle so that it stays inside/outside end circle after rounding.
81
+
82
+ The rounding of circle coordinates to integers may cause an abrupt change
83
+ if the start circle c0 is so close to the end circle c1's perimiter that
84
+ it ends up falling outside (or inside) as a result of the rounding.
85
+ To keep the gradient unchanged, we nudge it in the right direction.
86
+
87
+ See:
88
+ https://github.com/googlefonts/colr-gradients-spec/issues/204
89
+ https://github.com/googlefonts/picosvg/issues/158
90
+ """
91
+ start, end = Circle(c0, r0), Circle(c1, r1)
92
+
93
+ inside_before_round = start.inside(end)
94
+
95
+ round_start = start.round()
96
+ round_end = end.round()
97
+ inside_after_round = round_start.inside(round_end)
98
+
99
+ if inside_before_round == inside_after_round:
100
+ return round_start
101
+ elif inside_after_round:
102
+ # start was outside before rounding: we need to push start away from end
103
+ direction = _vector_between(round_end.centre, round_start.centre)
104
+ radius_delta = +1.0
105
+ else:
106
+ # start was inside before rounding: we need to push start towards end
107
+ direction = _vector_between(round_start.centre, round_end.centre)
108
+ radius_delta = -1.0
109
+ dx, dy = _rounding_offset(direction)
110
+
111
+ # At most 2 iterations ought to be enough to converge. Before the loop, we
112
+ # know the start circle didn't keep containment after normal rounding; thus
113
+ # we continue adjusting by -/+ 1.0 until containment is restored.
114
+ # Normal rounding can at most move each coordinates -/+0.5; in the worst case
115
+ # both the start and end circle's centres and radii will be rounded in opposite
116
+ # directions, e.g. when they move along a 45 degree diagonal:
117
+ # c0 = (1.5, 1.5) ===> (2.0, 2.0)
118
+ # r0 = 0.5 ===> 1.0
119
+ # c1 = (0.499, 0.499) ===> (0.0, 0.0)
120
+ # r1 = 2.499 ===> 2.0
121
+ # In this example, the relative distance between the circles, calculated
122
+ # as r1 - (r0 + distance(c0, c1)) is initially 0.57437 (c0 is inside c1), and
123
+ # -1.82842 after rounding (c0 is now outside c1). Nudging c0 by -1.0 on both
124
+ # x and y axes moves it towards c1 by hypot(-1.0, -1.0) = 1.41421. Two of these
125
+ # moves cover twice that distance, which is enough to restore containment.
126
+ max_attempts = 2
127
+ for _ in range(max_attempts):
128
+ if round_start.concentric(round_end):
129
+ # can't move c0 towards c1 (they are the same), so we change the radius
130
+ round_start.radius += radius_delta
131
+ assert round_start.radius >= 0
132
+ else:
133
+ round_start.move(dx, dy)
134
+ if inside_before_round == round_start.inside(round_end):
135
+ break
136
+ else: # likely a bug
137
+ raise AssertionError(
138
+ f"Rounding circle {start} "
139
+ f"{'inside' if inside_before_round else 'outside'} "
140
+ f"{end} failed after {max_attempts} attempts!"
141
+ )
142
+
143
+ return round_start
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/colorLib/table_builder.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ colorLib.table_builder: Generic helper for filling in BaseTable derivatives from tuples and maps and such.
3
+
4
+ """
5
+
6
+ import collections
7
+ import enum
8
+ from fontTools.ttLib.tables.otBase import (
9
+ BaseTable,
10
+ FormatSwitchingBaseTable,
11
+ UInt8FormatSwitchingBaseTable,
12
+ )
13
+ from fontTools.ttLib.tables.otConverters import (
14
+ ComputedInt,
15
+ SimpleValue,
16
+ Struct,
17
+ Short,
18
+ UInt8,
19
+ UShort,
20
+ IntValue,
21
+ FloatValue,
22
+ OptionalValue,
23
+ )
24
+ from fontTools.misc.roundTools import otRound
25
+
26
+
27
+ class BuildCallback(enum.Enum):
28
+ """Keyed on (BEFORE_BUILD, class[, Format if available]).
29
+ Receives (dest, source).
30
+ Should return (dest, source), which can be new objects.
31
+ """
32
+
33
+ BEFORE_BUILD = enum.auto()
34
+
35
+ """Keyed on (AFTER_BUILD, class[, Format if available]).
36
+ Receives (dest).
37
+ Should return dest, which can be a new object.
38
+ """
39
+ AFTER_BUILD = enum.auto()
40
+
41
+ """Keyed on (CREATE_DEFAULT, class[, Format if available]).
42
+ Receives no arguments.
43
+ Should return a new instance of class.
44
+ """
45
+ CREATE_DEFAULT = enum.auto()
46
+
47
+
48
+ def _assignable(convertersByName):
49
+ return {k: v for k, v in convertersByName.items() if not isinstance(v, ComputedInt)}
50
+
51
+
52
+ def _isNonStrSequence(value):
53
+ return isinstance(value, collections.abc.Sequence) and not isinstance(value, str)
54
+
55
+
56
+ def _split_format(cls, source):
57
+ if _isNonStrSequence(source):
58
+ assert len(source) > 0, f"{cls} needs at least format from {source}"
59
+ fmt, remainder = source[0], source[1:]
60
+ elif isinstance(source, collections.abc.Mapping):
61
+ assert "Format" in source, f"{cls} needs at least Format from {source}"
62
+ remainder = source.copy()
63
+ fmt = remainder.pop("Format")
64
+ else:
65
+ raise ValueError(f"Not sure how to populate {cls} from {source}")
66
+
67
+ assert isinstance(
68
+ fmt, collections.abc.Hashable
69
+ ), f"{cls} Format is not hashable: {fmt!r}"
70
+ assert fmt in cls.convertersByName, f"{cls} invalid Format: {fmt!r}"
71
+
72
+ return fmt, remainder
73
+
74
+
75
+ class TableBuilder:
76
+ """
77
+ Helps to populate things derived from BaseTable from maps, tuples, etc.
78
+
79
+ A table of lifecycle callbacks may be provided to add logic beyond what is possible
80
+ based on otData info for the target class. See BuildCallbacks.
81
+ """
82
+
83
+ def __init__(self, callbackTable=None):
84
+ if callbackTable is None:
85
+ callbackTable = {}
86
+ self._callbackTable = callbackTable
87
+
88
+ def _convert(self, dest, field, converter, value):
89
+ enumClass = getattr(converter, "enumClass", None)
90
+
91
+ if enumClass:
92
+ if isinstance(value, enumClass):
93
+ pass
94
+ elif isinstance(value, str):
95
+ try:
96
+ value = getattr(enumClass, value.upper())
97
+ except AttributeError:
98
+ raise ValueError(f"{value} is not a valid {enumClass}")
99
+ else:
100
+ value = enumClass(value)
101
+
102
+ elif isinstance(converter, IntValue):
103
+ value = otRound(value)
104
+ elif isinstance(converter, FloatValue):
105
+ value = float(value)
106
+
107
+ elif isinstance(converter, Struct):
108
+ if converter.repeat:
109
+ if _isNonStrSequence(value):
110
+ value = [self.build(converter.tableClass, v) for v in value]
111
+ else:
112
+ value = [self.build(converter.tableClass, value)]
113
+ setattr(dest, converter.repeat, len(value))
114
+ else:
115
+ value = self.build(converter.tableClass, value)
116
+ elif callable(converter):
117
+ value = converter(value)
118
+
119
+ setattr(dest, field, value)
120
+
121
+ def build(self, cls, source):
122
+ assert issubclass(cls, BaseTable)
123
+
124
+ if isinstance(source, cls):
125
+ return source
126
+
127
+ callbackKey = (cls,)
128
+ fmt = None
129
+ if issubclass(cls, FormatSwitchingBaseTable):
130
+ fmt, source = _split_format(cls, source)
131
+ callbackKey = (cls, fmt)
132
+
133
+ dest = self._callbackTable.get(
134
+ (BuildCallback.CREATE_DEFAULT,) + callbackKey, lambda: cls()
135
+ )()
136
+ assert isinstance(dest, cls)
137
+
138
+ convByName = _assignable(cls.convertersByName)
139
+ skippedFields = set()
140
+
141
+ # For format switchers we need to resolve converters based on format
142
+ if issubclass(cls, FormatSwitchingBaseTable):
143
+ dest.Format = fmt
144
+ convByName = _assignable(convByName[dest.Format])
145
+ skippedFields.add("Format")
146
+
147
+ # Convert sequence => mapping so before thunk only has to handle one format
148
+ if _isNonStrSequence(source):
149
+ # Sequence (typically list or tuple) assumed to match fields in declaration order
150
+ assert len(source) <= len(
151
+ convByName
152
+ ), f"Sequence of {len(source)} too long for {cls}; expected <= {len(convByName)} values"
153
+ source = dict(zip(convByName.keys(), source))
154
+
155
+ dest, source = self._callbackTable.get(
156
+ (BuildCallback.BEFORE_BUILD,) + callbackKey, lambda d, s: (d, s)
157
+ )(dest, source)
158
+
159
+ if isinstance(source, collections.abc.Mapping):
160
+ for field, value in source.items():
161
+ if field in skippedFields:
162
+ continue
163
+ converter = convByName.get(field, None)
164
+ if not converter:
165
+ raise ValueError(
166
+ f"Unrecognized field {field} for {cls}; expected one of {sorted(convByName.keys())}"
167
+ )
168
+ self._convert(dest, field, converter, value)
169
+ else:
170
+ # let's try as a 1-tuple
171
+ dest = self.build(cls, (source,))
172
+
173
+ for field, conv in convByName.items():
174
+ if not hasattr(dest, field) and isinstance(conv, OptionalValue):
175
+ setattr(dest, field, conv.DEFAULT)
176
+
177
+ dest = self._callbackTable.get(
178
+ (BuildCallback.AFTER_BUILD,) + callbackKey, lambda d: d
179
+ )(dest)
180
+
181
+ return dest
182
+
183
+
184
+ class TableUnbuilder:
185
+ def __init__(self, callbackTable=None):
186
+ if callbackTable is None:
187
+ callbackTable = {}
188
+ self._callbackTable = callbackTable
189
+
190
+ def unbuild(self, table):
191
+ assert isinstance(table, BaseTable)
192
+
193
+ source = {}
194
+
195
+ callbackKey = (type(table),)
196
+ if isinstance(table, FormatSwitchingBaseTable):
197
+ source["Format"] = int(table.Format)
198
+ callbackKey += (table.Format,)
199
+
200
+ for converter in table.getConverters():
201
+ if isinstance(converter, ComputedInt):
202
+ continue
203
+ value = getattr(table, converter.name)
204
+
205
+ enumClass = getattr(converter, "enumClass", None)
206
+ if enumClass:
207
+ source[converter.name] = value.name.lower()
208
+ elif isinstance(converter, Struct):
209
+ if converter.repeat:
210
+ source[converter.name] = [self.unbuild(v) for v in value]
211
+ else:
212
+ source[converter.name] = self.unbuild(value)
213
+ elif isinstance(converter, SimpleValue):
214
+ # "simple" values (e.g. int, float, str) need no further un-building
215
+ source[converter.name] = value
216
+ else:
217
+ raise NotImplementedError(
218
+ "Don't know how unbuild {value!r} with {converter!r}"
219
+ )
220
+
221
+ source = self._callbackTable.get(callbackKey, lambda s: s)(source)
222
+
223
+ return source
Scripts_Climate_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.venv/lib/python3.10/site-packages/fontTools/cu2qu/cu2qu.py ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.inline
65
+ @cython.locals(a=cython.complex, b=cython.complex, c=cython.complex, d=cython.complex)
66
+ @cython.locals(
67
+ _1=cython.complex, _2=cython.complex, _3=cython.complex, _4=cython.complex
68
+ )
69
+ def calc_cubic_points(a, b, c, d):
70
+ _1 = d
71
+ _2 = (c / 3.0) + d
72
+ _3 = (b + c) / 3.0 + _2
73
+ _4 = a + d + c + b
74
+ return _1, _2, _3, _4
75
+
76
+
77
+ @cython.cfunc
78
+ @cython.inline
79
+ @cython.locals(
80
+ p0=cython.complex, p1=cython.complex, p2=cython.complex, p3=cython.complex
81
+ )
82
+ @cython.locals(a=cython.complex, b=cython.complex, c=cython.complex, d=cython.complex)
83
+ def calc_cubic_parameters(p0, p1, p2, p3):
84
+ c = (p1 - p0) * 3.0
85
+ b = (p2 - p1) * 3.0 - c
86
+ d = p0
87
+ a = p3 - d - c - b
88
+ return a, b, c, d
89
+
90
+
91
+ @cython.cfunc
92
+ @cython.inline
93
+ @cython.locals(
94
+ p0=cython.complex, p1=cython.complex, p2=cython.complex, p3=cython.complex
95
+ )
96
+ def split_cubic_into_n_iter(p0, p1, p2, p3, n):
97
+ """Split a cubic Bezier into n equal parts.
98
+
99
+ Splits the curve into `n` equal parts by curve time.
100
+ (t=0..1/n, t=1/n..2/n, ...)
101
+
102
+ Args:
103
+ p0 (complex): Start point of curve.
104
+ p1 (complex): First handle of curve.
105
+ p2 (complex): Second handle of curve.
106
+ p3 (complex): End point of curve.
107
+
108
+ Returns:
109
+ An iterator yielding the control points (four complex values) of the
110
+ subcurves.
111
+ """
112
+ # Hand-coded special-cases
113
+ if n == 2:
114
+ return iter(split_cubic_into_two(p0, p1, p2, p3))
115
+ if n == 3:
116
+ return iter(split_cubic_into_three(p0, p1, p2, p3))
117
+ if n == 4:
118
+ a, b = split_cubic_into_two(p0, p1, p2, p3)
119
+ return iter(
120
+ split_cubic_into_two(a[0], a[1], a[2], a[3])
121
+ + split_cubic_into_two(b[0], b[1], b[2], b[3])
122
+ )
123
+ if n == 6:
124
+ a, b = split_cubic_into_two(p0, p1, p2, p3)
125
+ return iter(
126
+ split_cubic_into_three(a[0], a[1], a[2], a[3])
127
+ + split_cubic_into_three(b[0], b[1], b[2], b[3])
128
+ )
129
+
130
+ return _split_cubic_into_n_gen(p0, p1, p2, p3, n)
131
+
132
+
133
+ @cython.locals(
134
+ p0=cython.complex,
135
+ p1=cython.complex,
136
+ p2=cython.complex,
137
+ p3=cython.complex,
138
+ n=cython.int,
139
+ )
140
+ @cython.locals(a=cython.complex, b=cython.complex, c=cython.complex, d=cython.complex)
141
+ @cython.locals(
142
+ dt=cython.double, delta_2=cython.double, delta_3=cython.double, i=cython.int
143
+ )
144
+ @cython.locals(
145
+ a1=cython.complex, b1=cython.complex, c1=cython.complex, d1=cython.complex
146
+ )
147
+ def _split_cubic_into_n_gen(p0, p1, p2, p3, n):
148
+ a, b, c, d = calc_cubic_parameters(p0, p1, p2, p3)
149
+ dt = 1 / n
150
+ delta_2 = dt * dt
151
+ delta_3 = dt * delta_2
152
+ for i in range(n):
153
+ t1 = i * dt
154
+ t1_2 = t1 * t1
155
+ # calc new a, b, c and d
156
+ a1 = a * delta_3
157
+ b1 = (3 * a * t1 + b) * delta_2
158
+ c1 = (2 * b * t1 + c + 3 * a * t1_2) * dt
159
+ d1 = a * t1 * t1_2 + b * t1_2 + c * t1 + d
160
+ yield calc_cubic_points(a1, b1, c1, d1)
161
+
162
+
163
+ @cython.cfunc
164
+ @cython.inline
165
+ @cython.locals(
166
+ p0=cython.complex, p1=cython.complex, p2=cython.complex, p3=cython.complex
167
+ )
168
+ @cython.locals(mid=cython.complex, deriv3=cython.complex)
169
+ def split_cubic_into_two(p0, p1, p2, p3):
170
+ """Split a cubic Bezier into two equal parts.
171
+
172
+ Splits the curve into two equal parts at t = 0.5
173
+
174
+ Args:
175
+ p0 (complex): Start point of curve.
176
+ p1 (complex): First handle of curve.
177
+ p2 (complex): Second handle of curve.
178
+ p3 (complex): End point of curve.
179
+
180
+ Returns:
181
+ tuple: Two cubic Beziers (each expressed as a tuple of four complex
182
+ values).
183
+ """
184
+ mid = (p0 + 3 * (p1 + p2) + p3) * 0.125
185
+ deriv3 = (p3 + p2 - p1 - p0) * 0.125
186
+ return (
187
+ (p0, (p0 + p1) * 0.5, mid - deriv3, mid),
188
+ (mid, mid + deriv3, (p2 + p3) * 0.5, p3),
189
+ )
190
+
191
+
192
+ @cython.cfunc
193
+ @cython.inline
194
+ @cython.locals(
195
+ p0=cython.complex,
196
+ p1=cython.complex,
197
+ p2=cython.complex,
198
+ p3=cython.complex,
199
+ )
200
+ @cython.locals(
201
+ mid1=cython.complex,
202
+ deriv1=cython.complex,
203
+ mid2=cython.complex,
204
+ deriv2=cython.complex,
205
+ )
206
+ def split_cubic_into_three(p0, p1, p2, p3):
207
+ """Split a cubic Bezier into three equal parts.
208
+
209
+ Splits the curve into three equal parts at t = 1/3 and t = 2/3
210
+
211
+ Args:
212
+ p0 (complex): Start point of curve.
213
+ p1 (complex): First handle of curve.
214
+ p2 (complex): Second handle of curve.
215
+ p3 (complex): End point of curve.
216
+
217
+ Returns:
218
+ tuple: Three cubic Beziers (each expressed as a tuple of four complex
219
+ values).
220
+ """
221
+ mid1 = (8 * p0 + 12 * p1 + 6 * p2 + p3) * (1 / 27)
222
+ deriv1 = (p3 + 3 * p2 - 4 * p0) * (1 / 27)
223
+ mid2 = (p0 + 6 * p1 + 12 * p2 + 8 * p3) * (1 / 27)
224
+ deriv2 = (4 * p3 - 3 * p1 - p0) * (1 / 27)
225
+ return (
226
+ (p0, (2 * p0 + p1) / 3.0, mid1 - deriv1, mid1),
227
+ (mid1, mid1 + deriv1, mid2 - deriv2, mid2),
228
+ (mid2, mid2 + deriv2, (p2 + 2 * p3) / 3.0, p3),
229
+ )
230
+
231
+
232
+ @cython.cfunc
233
+ @cython.inline
234
+ @cython.returns(cython.complex)
235
+ @cython.locals(
236
+ t=cython.double,
237
+ p0=cython.complex,
238
+ p1=cython.complex,
239
+ p2=cython.complex,
240
+ p3=cython.complex,
241
+ )
242
+ @cython.locals(_p1=cython.complex, _p2=cython.complex)
243
+ def cubic_approx_control(t, p0, p1, p2, p3):
244
+ """Approximate a cubic Bezier using a quadratic one.
245
+
246
+ Args:
247
+ t (double): Position of control point.
248
+ p0 (complex): Start point of curve.
249
+ p1 (complex): First handle of curve.
250
+ p2 (complex): Second handle of curve.
251
+ p3 (complex): End point of curve.
252
+
253
+ Returns:
254
+ complex: Location of candidate control point on quadratic curve.
255
+ """
256
+ _p1 = p0 + (p1 - p0) * 1.5
257
+ _p2 = p3 + (p2 - p3) * 1.5
258
+ return _p1 + (_p2 - _p1) * t
259
+
260
+
261
+ @cython.cfunc
262
+ @cython.inline
263
+ @cython.returns(cython.complex)
264
+ @cython.locals(a=cython.complex, b=cython.complex, c=cython.complex, d=cython.complex)
265
+ @cython.locals(ab=cython.complex, cd=cython.complex, p=cython.complex, h=cython.double)
266
+ def calc_intersect(a, b, c, d):
267
+ """Calculate the intersection of two lines.
268
+
269
+ Args:
270
+ a (complex): Start point of first line.
271
+ b (complex): End point of first line.
272
+ c (complex): Start point of second line.
273
+ d (complex): End point of second line.
274
+
275
+ Returns:
276
+ complex: Location of intersection if one present, ``complex(NaN,NaN)``
277
+ if no intersection was found.
278
+ """
279
+ ab = b - a
280
+ cd = d - c
281
+ p = ab * 1j
282
+ try:
283
+ h = dot(p, a - c) / dot(p, cd)
284
+ except ZeroDivisionError:
285
+ # if 3 or 4 points are equal, we do have an intersection despite the zero-div:
286
+ # return one of the off-curves so that the algorithm can attempt a one-curve
287
+ # solution if it's within tolerance:
288
+ # https://github.com/linebender/kurbo/pull/484
289
+ if b == c and (a == b or c == d):
290
+ return b
291
+ return complex(NAN, NAN)
292
+ return c + cd * h
293
+
294
+
295
+ @cython.cfunc
296
+ @cython.returns(cython.int)
297
+ @cython.locals(
298
+ tolerance=cython.double,
299
+ p0=cython.complex,
300
+ p1=cython.complex,
301
+ p2=cython.complex,
302
+ p3=cython.complex,
303
+ )
304
+ @cython.locals(mid=cython.complex, deriv3=cython.complex)
305
+ def cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance):
306
+ """Check if a cubic Bezier lies within a given distance of the origin.
307
+
308
+ "Origin" means *the* origin (0,0), not the start of the curve. Note that no
309
+ checks are made on the start and end positions of the curve; this function
310
+ only checks the inside of the curve.
311
+
312
+ Args:
313
+ p0 (complex): Start point of curve.
314
+ p1 (complex): First handle of curve.
315
+ p2 (complex): Second handle of curve.
316
+ p3 (complex): End point of curve.
317
+ tolerance (double): Distance from origin.
318
+
319
+ Returns:
320
+ bool: True if the cubic Bezier ``p`` entirely lies within a distance
321
+ ``tolerance`` of the origin, False otherwise.
322
+ """
323
+ # First check p2 then p1, as p2 has higher error early on.
324
+ if abs(p2) <= tolerance and abs(p1) <= tolerance:
325
+ return True
326
+
327
+ # Split.
328
+ mid = (p0 + 3 * (p1 + p2) + p3) * 0.125
329
+ if abs(mid) > tolerance:
330
+ return False
331
+ deriv3 = (p3 + p2 - p1 - p0) * 0.125
332
+ return cubic_farthest_fit_inside(
333
+ p0, (p0 + p1) * 0.5, mid - deriv3, mid, tolerance
334
+ ) and cubic_farthest_fit_inside(mid, mid + deriv3, (p2 + p3) * 0.5, p3, tolerance)
335
+
336
+
337
+ @cython.cfunc
338
+ @cython.inline
339
+ @cython.locals(tolerance=cython.double)
340
+ @cython.locals(
341
+ q1=cython.complex,
342
+ c0=cython.complex,
343
+ c1=cython.complex,
344
+ c2=cython.complex,
345
+ c3=cython.complex,
346
+ )
347
+ def cubic_approx_quadratic(cubic, tolerance):
348
+ """Approximate a cubic Bezier with a single quadratic within a given tolerance.
349
+
350
+ Args:
351
+ cubic (sequence): Four complex numbers representing control points of
352
+ the cubic Bezier curve.
353
+ tolerance (double): Permitted deviation from the original curve.
354
+
355
+ Returns:
356
+ Three complex numbers representing control points of the quadratic
357
+ curve if it fits within the given tolerance, or ``None`` if no suitable
358
+ curve could be calculated.
359
+ """
360
+
361
+ q1 = calc_intersect(cubic[0], cubic[1], cubic[2], cubic[3])
362
+ if math.isnan(q1.imag):
363
+ return None
364
+ c0 = cubic[0]
365
+ c3 = cubic[3]
366
+ c1 = c0 + (q1 - c0) * (2 / 3)
367
+ c2 = c3 + (q1 - c3) * (2 / 3)
368
+ if not cubic_farthest_fit_inside(0, c1 - cubic[1], c2 - cubic[2], 0, tolerance):
369
+ return None
370
+ return c0, q1, c3
371
+
372
+
373
+ @cython.cfunc
374
+ @cython.locals(n=cython.int, tolerance=cython.double)
375
+ @cython.locals(i=cython.int)
376
+ @cython.locals(all_quadratic=cython.int)
377
+ @cython.locals(
378
+ c0=cython.complex, c1=cython.complex, c2=cython.complex, c3=cython.complex
379
+ )
380
+ @cython.locals(
381
+ q0=cython.complex,
382
+ q1=cython.complex,
383
+ next_q1=cython.complex,
384
+ q2=cython.complex,
385
+ d1=cython.complex,
386
+ )
387
+ def cubic_approx_spline(cubic, n, tolerance, all_quadratic):
388
+ """Approximate a cubic Bezier curve with a spline of n quadratics.
389
+
390
+ Args:
391
+ cubic (sequence): Four complex numbers representing control points of
392
+ the cubic Bezier curve.
393
+ n (int): Number of quadratic Bezier curves in the spline.
394
+ tolerance (double): Permitted deviation from the original curve.
395
+
396
+ Returns:
397
+ A list of ``n+2`` complex numbers, representing control points of the
398
+ quadratic spline if it fits within the given tolerance, or ``None`` if
399
+ no suitable spline could be calculated.
400
+ """
401
+
402
+ if n == 1:
403
+ return cubic_approx_quadratic(cubic, tolerance)
404
+ if n == 2 and all_quadratic == False:
405
+ return cubic
406
+
407
+ cubics = split_cubic_into_n_iter(cubic[0], cubic[1], cubic[2], cubic[3], n)
408
+
409
+ # calculate the spline of quadratics and check errors at the same time.
410
+ next_cubic = next(cubics)
411
+ next_q1 = cubic_approx_control(
412
+ 0, next_cubic[0], next_cubic[1], next_cubic[2], next_cubic[3]
413
+ )
414
+ q2 = cubic[0]
415
+ d1 = 0j
416
+ spline = [cubic[0], next_q1]
417
+ for i in range(1, n + 1):
418
+ # Current cubic to convert
419
+ c0, c1, c2, c3 = next_cubic
420
+
421
+ # Current quadratic approximation of current cubic
422
+ q0 = q2
423
+ q1 = next_q1
424
+ if i < n:
425
+ next_cubic = next(cubics)
426
+ next_q1 = cubic_approx_control(
427
+ i / (n - 1), next_cubic[0], next_cubic[1], next_cubic[2], next_cubic[3]
428
+ )
429
+ spline.append(next_q1)
430
+ q2 = (q1 + next_q1) * 0.5
431
+ else:
432
+ q2 = c3
433
+
434
+ # End-point deltas
435
+ d0 = d1
436
+ d1 = q2 - c3
437
+
438
+ if abs(d1) > tolerance or not cubic_farthest_fit_inside(
439
+ d0,
440
+ q0 + (q1 - q0) * (2 / 3) - c1,
441
+ q2 + (q1 - q2) * (2 / 3) - c2,
442
+ d1,
443
+ tolerance,
444
+ ):
445
+ return None
446
+ spline.append(cubic[3])
447
+
448
+ return spline
449
+
450
+
451
+ @cython.locals(max_err=cython.double)
452
+ @cython.locals(n=cython.int)
453
+ @cython.locals(all_quadratic=cython.int)
454
+ def curve_to_quadratic(curve, max_err, all_quadratic=True):
455
+ """Approximate a cubic Bezier curve with a spline of n quadratics.
456
+
457
+ Args:
458
+ cubic (sequence): Four 2D tuples representing control points of
459
+ the cubic Bezier curve.
460
+ max_err (double): Permitted deviation from the original curve.
461
+ all_quadratic (bool): If True (default) returned value is a
462
+ quadratic spline. If False, it's either a single quadratic
463
+ curve or a single cubic curve.
464
+
465
+ Returns:
466
+ If all_quadratic is True: A list of 2D tuples, representing
467
+ control points of the quadratic spline if it fits within the
468
+ given tolerance, or ``None`` if no suitable spline could be
469
+ calculated.
470
+
471
+ If all_quadratic is False: Either a quadratic curve (if length
472
+ of output is 3), or a cubic curve (if length of output is 4).
473
+ """
474
+
475
+ curve = [complex(*p) for p in curve]
476
+
477
+ for n in range(1, MAX_N + 1):
478
+ spline = cubic_approx_spline(curve, n, max_err, all_quadratic)
479
+ if spline is not None:
480
+ # done. go home
481
+ return [(s.real, s.imag) for s in spline]
482
+
483
+ raise ApproxNotFoundError(curve)
484
+
485
+
486
+ @cython.locals(l=cython.int, last_i=cython.int, i=cython.int)
487
+ @cython.locals(all_quadratic=cython.int)
488
+ def curves_to_quadratic(curves, max_errors, all_quadratic=True):
489
+ """Return quadratic Bezier splines approximating the input cubic Beziers.
490
+
491
+ Args:
492
+ curves: A sequence of *n* curves, each curve being a sequence of four
493
+ 2D tuples.
494
+ max_errors: A sequence of *n* floats representing the maximum permissible
495
+ deviation from each of the cubic Bezier curves.
496
+ all_quadratic (bool): If True (default) returned values are a
497
+ quadratic spline. If False, they are either a single quadratic
498
+ curve or a single cubic curve.
499
+
500
+ Example::
501
+
502
+ >>> curves_to_quadratic( [
503
+ ... [ (50,50), (100,100), (150,100), (200,50) ],
504
+ ... [ (75,50), (120,100), (150,75), (200,60) ]
505
+ ... ], [1,1] )
506
+ [[(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)]]
507
+
508
+ The returned splines have "implied oncurve points" suitable for use in
509
+ TrueType ``glif`` outlines - i.e. in the first spline returned above,
510
+ the first quadratic segment runs from (50,50) to
511
+ ( (75 + 125)/2 , (120 + 91.666..)/2 ) = (100, 83.333...).
512
+
513
+ Returns:
514
+ If all_quadratic is True, a list of splines, each spline being a list
515
+ of 2D tuples.
516
+
517
+ If all_quadratic is False, a list of curves, each curve being a quadratic
518
+ (length 3), or cubic (length 4).
519
+
520
+ Raises:
521
+ fontTools.cu2qu.Errors.ApproxNotFoundError: if no suitable approximation
522
+ can be found for all curves with the given parameters.
523
+ """
524
+
525
+ curves = [[complex(*p) for p in curve] for curve in curves]
526
+ assert len(max_errors) == len(curves)
527
+
528
+ l = len(curves)
529
+ splines = [None] * l
530
+ last_i = i = 0
531
+ n = 1
532
+ while True:
533
+ spline = cubic_approx_spline(curves[i], n, max_errors[i], all_quadratic)
534
+ if spline is None:
535
+ if n == MAX_N:
536
+ break
537
+ n += 1
538
+ last_i = i
539
+ continue
540
+ splines[i] = spline
541
+ i = (i + 1) % l
542
+ if i == last_i:
543
+ # done. go home
544
+ return [[(s.real, s.imag) for s in spline] for spline in splines]
545
+
546
+ raise ApproxNotFoundError(curves)
Scripts_Climate_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.venv/lib/python3.10/site-packages/fontTools/encodings/MacRoman.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MacRoman = [
2
+ "NUL",
3
+ "Eth",
4
+ "eth",
5
+ "Lslash",
6
+ "lslash",
7
+ "Scaron",
8
+ "scaron",
9
+ "Yacute",
10
+ "yacute",
11
+ "HT",
12
+ "LF",
13
+ "Thorn",
14
+ "thorn",
15
+ "CR",
16
+ "Zcaron",
17
+ "zcaron",
18
+ "DLE",
19
+ "DC1",
20
+ "DC2",
21
+ "DC3",
22
+ "DC4",
23
+ "onehalf",
24
+ "onequarter",
25
+ "onesuperior",
26
+ "threequarters",
27
+ "threesuperior",
28
+ "twosuperior",
29
+ "brokenbar",
30
+ "minus",
31
+ "multiply",
32
+ "RS",
33
+ "US",
34
+ "space",
35
+ "exclam",
36
+ "quotedbl",
37
+ "numbersign",
38
+ "dollar",
39
+ "percent",
40
+ "ampersand",
41
+ "quotesingle",
42
+ "parenleft",
43
+ "parenright",
44
+ "asterisk",
45
+ "plus",
46
+ "comma",
47
+ "hyphen",
48
+ "period",
49
+ "slash",
50
+ "zero",
51
+ "one",
52
+ "two",
53
+ "three",
54
+ "four",
55
+ "five",
56
+ "six",
57
+ "seven",
58
+ "eight",
59
+ "nine",
60
+ "colon",
61
+ "semicolon",
62
+ "less",
63
+ "equal",
64
+ "greater",
65
+ "question",
66
+ "at",
67
+ "A",
68
+ "B",
69
+ "C",
70
+ "D",
71
+ "E",
72
+ "F",
73
+ "G",
74
+ "H",
75
+ "I",
76
+ "J",
77
+ "K",
78
+ "L",
79
+ "M",
80
+ "N",
81
+ "O",
82
+ "P",
83
+ "Q",
84
+ "R",
85
+ "S",
86
+ "T",
87
+ "U",
88
+ "V",
89
+ "W",
90
+ "X",
91
+ "Y",
92
+ "Z",
93
+ "bracketleft",
94
+ "backslash",
95
+ "bracketright",
96
+ "asciicircum",
97
+ "underscore",
98
+ "grave",
99
+ "a",
100
+ "b",
101
+ "c",
102
+ "d",
103
+ "e",
104
+ "f",
105
+ "g",
106
+ "h",
107
+ "i",
108
+ "j",
109
+ "k",
110
+ "l",
111
+ "m",
112
+ "n",
113
+ "o",
114
+ "p",
115
+ "q",
116
+ "r",
117
+ "s",
118
+ "t",
119
+ "u",
120
+ "v",
121
+ "w",
122
+ "x",
123
+ "y",
124
+ "z",
125
+ "braceleft",
126
+ "bar",
127
+ "braceright",
128
+ "asciitilde",
129
+ "DEL",
130
+ "Adieresis",
131
+ "Aring",
132
+ "Ccedilla",
133
+ "Eacute",
134
+ "Ntilde",
135
+ "Odieresis",
136
+ "Udieresis",
137
+ "aacute",
138
+ "agrave",
139
+ "acircumflex",
140
+ "adieresis",
141
+ "atilde",
142
+ "aring",
143
+ "ccedilla",
144
+ "eacute",
145
+ "egrave",
146
+ "ecircumflex",
147
+ "edieresis",
148
+ "iacute",
149
+ "igrave",
150
+ "icircumflex",
151
+ "idieresis",
152
+ "ntilde",
153
+ "oacute",
154
+ "ograve",
155
+ "ocircumflex",
156
+ "odieresis",
157
+ "otilde",
158
+ "uacute",
159
+ "ugrave",
160
+ "ucircumflex",
161
+ "udieresis",
162
+ "dagger",
163
+ "degree",
164
+ "cent",
165
+ "sterling",
166
+ "section",
167
+ "bullet",
168
+ "paragraph",
169
+ "germandbls",
170
+ "registered",
171
+ "copyright",
172
+ "trademark",
173
+ "acute",
174
+ "dieresis",
175
+ "notequal",
176
+ "AE",
177
+ "Oslash",
178
+ "infinity",
179
+ "plusminus",
180
+ "lessequal",
181
+ "greaterequal",
182
+ "yen",
183
+ "mu",
184
+ "partialdiff",
185
+ "summation",
186
+ "product",
187
+ "pi",
188
+ "integral",
189
+ "ordfeminine",
190
+ "ordmasculine",
191
+ "Omega",
192
+ "ae",
193
+ "oslash",
194
+ "questiondown",
195
+ "exclamdown",
196
+ "logicalnot",
197
+ "radical",
198
+ "florin",
199
+ "approxequal",
200
+ "Delta",
201
+ "guillemotleft",
202
+ "guillemotright",
203
+ "ellipsis",
204
+ "nbspace",
205
+ "Agrave",
206
+ "Atilde",
207
+ "Otilde",
208
+ "OE",
209
+ "oe",
210
+ "endash",
211
+ "emdash",
212
+ "quotedblleft",
213
+ "quotedblright",
214
+ "quoteleft",
215
+ "quoteright",
216
+ "divide",
217
+ "lozenge",
218
+ "ydieresis",
219
+ "Ydieresis",
220
+ "fraction",
221
+ "currency",
222
+ "guilsinglleft",
223
+ "guilsinglright",
224
+ "fi",
225
+ "fl",
226
+ "daggerdbl",
227
+ "periodcentered",
228
+ "quotesinglbase",
229
+ "quotedblbase",
230
+ "perthousand",
231
+ "Acircumflex",
232
+ "Ecircumflex",
233
+ "Aacute",
234
+ "Edieresis",
235
+ "Egrave",
236
+ "Iacute",
237
+ "Icircumflex",
238
+ "Idieresis",
239
+ "Igrave",
240
+ "Oacute",
241
+ "Ocircumflex",
242
+ "apple",
243
+ "Ograve",
244
+ "Uacute",
245
+ "Ucircumflex",
246
+ "Ugrave",
247
+ "dotlessi",
248
+ "circumflex",
249
+ "tilde",
250
+ "macron",
251
+ "breve",
252
+ "dotaccent",
253
+ "ring",
254
+ "cedilla",
255
+ "hungarumlaut",
256
+ "ogonek",
257
+ "caron",
258
+ ]
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/encodings/StandardEncoding.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ StandardEncoding = [
2
+ ".notdef",
3
+ ".notdef",
4
+ ".notdef",
5
+ ".notdef",
6
+ ".notdef",
7
+ ".notdef",
8
+ ".notdef",
9
+ ".notdef",
10
+ ".notdef",
11
+ ".notdef",
12
+ ".notdef",
13
+ ".notdef",
14
+ ".notdef",
15
+ ".notdef",
16
+ ".notdef",
17
+ ".notdef",
18
+ ".notdef",
19
+ ".notdef",
20
+ ".notdef",
21
+ ".notdef",
22
+ ".notdef",
23
+ ".notdef",
24
+ ".notdef",
25
+ ".notdef",
26
+ ".notdef",
27
+ ".notdef",
28
+ ".notdef",
29
+ ".notdef",
30
+ ".notdef",
31
+ ".notdef",
32
+ ".notdef",
33
+ ".notdef",
34
+ "space",
35
+ "exclam",
36
+ "quotedbl",
37
+ "numbersign",
38
+ "dollar",
39
+ "percent",
40
+ "ampersand",
41
+ "quoteright",
42
+ "parenleft",
43
+ "parenright",
44
+ "asterisk",
45
+ "plus",
46
+ "comma",
47
+ "hyphen",
48
+ "period",
49
+ "slash",
50
+ "zero",
51
+ "one",
52
+ "two",
53
+ "three",
54
+ "four",
55
+ "five",
56
+ "six",
57
+ "seven",
58
+ "eight",
59
+ "nine",
60
+ "colon",
61
+ "semicolon",
62
+ "less",
63
+ "equal",
64
+ "greater",
65
+ "question",
66
+ "at",
67
+ "A",
68
+ "B",
69
+ "C",
70
+ "D",
71
+ "E",
72
+ "F",
73
+ "G",
74
+ "H",
75
+ "I",
76
+ "J",
77
+ "K",
78
+ "L",
79
+ "M",
80
+ "N",
81
+ "O",
82
+ "P",
83
+ "Q",
84
+ "R",
85
+ "S",
86
+ "T",
87
+ "U",
88
+ "V",
89
+ "W",
90
+ "X",
91
+ "Y",
92
+ "Z",
93
+ "bracketleft",
94
+ "backslash",
95
+ "bracketright",
96
+ "asciicircum",
97
+ "underscore",
98
+ "quoteleft",
99
+ "a",
100
+ "b",
101
+ "c",
102
+ "d",
103
+ "e",
104
+ "f",
105
+ "g",
106
+ "h",
107
+ "i",
108
+ "j",
109
+ "k",
110
+ "l",
111
+ "m",
112
+ "n",
113
+ "o",
114
+ "p",
115
+ "q",
116
+ "r",
117
+ "s",
118
+ "t",
119
+ "u",
120
+ "v",
121
+ "w",
122
+ "x",
123
+ "y",
124
+ "z",
125
+ "braceleft",
126
+ "bar",
127
+ "braceright",
128
+ "asciitilde",
129
+ ".notdef",
130
+ ".notdef",
131
+ ".notdef",
132
+ ".notdef",
133
+ ".notdef",
134
+ ".notdef",
135
+ ".notdef",
136
+ ".notdef",
137
+ ".notdef",
138
+ ".notdef",
139
+ ".notdef",
140
+ ".notdef",
141
+ ".notdef",
142
+ ".notdef",
143
+ ".notdef",
144
+ ".notdef",
145
+ ".notdef",
146
+ ".notdef",
147
+ ".notdef",
148
+ ".notdef",
149
+ ".notdef",
150
+ ".notdef",
151
+ ".notdef",
152
+ ".notdef",
153
+ ".notdef",
154
+ ".notdef",
155
+ ".notdef",
156
+ ".notdef",
157
+ ".notdef",
158
+ ".notdef",
159
+ ".notdef",
160
+ ".notdef",
161
+ ".notdef",
162
+ ".notdef",
163
+ "exclamdown",
164
+ "cent",
165
+ "sterling",
166
+ "fraction",
167
+ "yen",
168
+ "florin",
169
+ "section",
170
+ "currency",
171
+ "quotesingle",
172
+ "quotedblleft",
173
+ "guillemotleft",
174
+ "guilsinglleft",
175
+ "guilsinglright",
176
+ "fi",
177
+ "fl",
178
+ ".notdef",
179
+ "endash",
180
+ "dagger",
181
+ "daggerdbl",
182
+ "periodcentered",
183
+ ".notdef",
184
+ "paragraph",
185
+ "bullet",
186
+ "quotesinglbase",
187
+ "quotedblbase",
188
+ "quotedblright",
189
+ "guillemotright",
190
+ "ellipsis",
191
+ "perthousand",
192
+ ".notdef",
193
+ "questiondown",
194
+ ".notdef",
195
+ "grave",
196
+ "acute",
197
+ "circumflex",
198
+ "tilde",
199
+ "macron",
200
+ "breve",
201
+ "dotaccent",
202
+ "dieresis",
203
+ ".notdef",
204
+ "ring",
205
+ "cedilla",
206
+ ".notdef",
207
+ "hungarumlaut",
208
+ "ogonek",
209
+ "caron",
210
+ "emdash",
211
+ ".notdef",
212
+ ".notdef",
213
+ ".notdef",
214
+ ".notdef",
215
+ ".notdef",
216
+ ".notdef",
217
+ ".notdef",
218
+ ".notdef",
219
+ ".notdef",
220
+ ".notdef",
221
+ ".notdef",
222
+ ".notdef",
223
+ ".notdef",
224
+ ".notdef",
225
+ ".notdef",
226
+ ".notdef",
227
+ "AE",
228
+ ".notdef",
229
+ "ordfeminine",
230
+ ".notdef",
231
+ ".notdef",
232
+ ".notdef",
233
+ ".notdef",
234
+ "Lslash",
235
+ "Oslash",
236
+ "OE",
237
+ "ordmasculine",
238
+ ".notdef",
239
+ ".notdef",
240
+ ".notdef",
241
+ ".notdef",
242
+ ".notdef",
243
+ "ae",
244
+ ".notdef",
245
+ ".notdef",
246
+ ".notdef",
247
+ "dotlessi",
248
+ ".notdef",
249
+ ".notdef",
250
+ "lslash",
251
+ "oslash",
252
+ "oe",
253
+ "germandbls",
254
+ ".notdef",
255
+ ".notdef",
256
+ ".notdef",
257
+ ".notdef",
258
+ ]
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/encodings/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Empty __init__.py file to signal Python this directory is a package."""
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/encodings/codecs.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extend the Python codecs module with a few encodings that are used in OpenType (name table)
2
+ but missing from Python. See https://github.com/fonttools/fonttools/issues/236 for details."""
3
+
4
+ import codecs
5
+ import encodings
6
+
7
+
8
+ class ExtendCodec(codecs.Codec):
9
+ def __init__(self, name, base_encoding, mapping):
10
+ self.name = name
11
+ self.base_encoding = base_encoding
12
+ self.mapping = mapping
13
+ self.reverse = {v: k for k, v in mapping.items()}
14
+ self.max_len = max(len(v) for v in mapping.values())
15
+ self.info = codecs.CodecInfo(
16
+ name=self.name, encode=self.encode, decode=self.decode
17
+ )
18
+ codecs.register_error(name, self.error)
19
+
20
+ def _map(self, mapper, output_type, exc_type, input, errors):
21
+ base_error_handler = codecs.lookup_error(errors)
22
+ length = len(input)
23
+ out = output_type()
24
+ while input:
25
+ # first try to use self.error as the error handler
26
+ try:
27
+ part = mapper(input, self.base_encoding, errors=self.name)
28
+ out += part
29
+ break # All converted
30
+ except exc_type as e:
31
+ # else convert the correct part, handle error as requested and continue
32
+ out += mapper(input[: e.start], self.base_encoding, self.name)
33
+ replacement, pos = base_error_handler(e)
34
+ out += replacement
35
+ input = input[pos:]
36
+ return out, length
37
+
38
+ def encode(self, input, errors="strict"):
39
+ return self._map(codecs.encode, bytes, UnicodeEncodeError, input, errors)
40
+
41
+ def decode(self, input, errors="strict"):
42
+ return self._map(codecs.decode, str, UnicodeDecodeError, input, errors)
43
+
44
+ def error(self, e):
45
+ if isinstance(e, UnicodeDecodeError):
46
+ for end in range(e.start + 1, e.end + 1):
47
+ s = e.object[e.start : end]
48
+ if s in self.mapping:
49
+ return self.mapping[s], end
50
+ elif isinstance(e, UnicodeEncodeError):
51
+ for end in range(e.start + 1, e.start + self.max_len + 1):
52
+ s = e.object[e.start : end]
53
+ if s in self.reverse:
54
+ return self.reverse[s], end
55
+ e.encoding = self.name
56
+ raise e
57
+
58
+
59
+ _extended_encodings = {
60
+ "x_mac_japanese_ttx": (
61
+ "shift_jis",
62
+ {
63
+ b"\xFC": chr(0x007C),
64
+ b"\x7E": chr(0x007E),
65
+ b"\x80": chr(0x005C),
66
+ b"\xA0": chr(0x00A0),
67
+ b"\xFD": chr(0x00A9),
68
+ b"\xFE": chr(0x2122),
69
+ b"\xFF": chr(0x2026),
70
+ },
71
+ ),
72
+ "x_mac_trad_chinese_ttx": (
73
+ "big5",
74
+ {
75
+ b"\x80": chr(0x005C),
76
+ b"\xA0": chr(0x00A0),
77
+ b"\xFD": chr(0x00A9),
78
+ b"\xFE": chr(0x2122),
79
+ b"\xFF": chr(0x2026),
80
+ },
81
+ ),
82
+ "x_mac_korean_ttx": (
83
+ "euc_kr",
84
+ {
85
+ b"\x80": chr(0x00A0),
86
+ b"\x81": chr(0x20A9),
87
+ b"\x82": chr(0x2014),
88
+ b"\x83": chr(0x00A9),
89
+ b"\xFE": chr(0x2122),
90
+ b"\xFF": chr(0x2026),
91
+ },
92
+ ),
93
+ "x_mac_simp_chinese_ttx": (
94
+ "gb2312",
95
+ {
96
+ b"\x80": chr(0x00FC),
97
+ b"\xA0": chr(0x00A0),
98
+ b"\xFD": chr(0x00A9),
99
+ b"\xFE": chr(0x2122),
100
+ b"\xFF": chr(0x2026),
101
+ },
102
+ ),
103
+ }
104
+
105
+ _cache = {}
106
+
107
+
108
+ def search_function(name):
109
+ name = encodings.normalize_encoding(name) # Rather undocumented...
110
+ if name in _extended_encodings:
111
+ if name not in _cache:
112
+ base_encoding, mapping = _extended_encodings[name]
113
+ assert name[-4:] == "_ttx"
114
+ # Python 2 didn't have any of the encodings that we are implementing
115
+ # in this file. Python 3 added aliases for the East Asian ones, mapping
116
+ # them "temporarily" to the same base encoding as us, with a comment
117
+ # suggesting that full implementation will appear some time later.
118
+ # As such, try the Python version of the x_mac_... first, if that is found,
119
+ # use *that* as our base encoding. This would make our encoding upgrade
120
+ # to the full encoding when and if Python finally implements that.
121
+ # http://bugs.python.org/issue24041
122
+ base_encodings = [name[:-4], base_encoding]
123
+ for base_encoding in base_encodings:
124
+ try:
125
+ codecs.lookup(base_encoding)
126
+ except LookupError:
127
+ continue
128
+ _cache[name] = ExtendCodec(name, base_encoding, mapping)
129
+ break
130
+ return _cache[name].info
131
+
132
+ return None
133
+
134
+
135
+ codecs.register(search_function)
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """fontTools.feaLib -- a package for dealing with OpenType feature files."""
2
+
3
+ # The structure of OpenType feature files is defined here:
4
+ # http://www.adobe.com/devnet/opentype/afdko/topic_feature_file_syntax.html
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/__main__.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.ttLib import TTFont
2
+ from fontTools.feaLib.builder import addOpenTypeFeatures, Builder
3
+ from fontTools.feaLib.error import FeatureLibError
4
+ from fontTools import configLogger
5
+ from fontTools.misc.cliTools import makeOutputFileName
6
+ import sys
7
+ import argparse
8
+ import logging
9
+
10
+
11
+ log = logging.getLogger("fontTools.feaLib")
12
+
13
+
14
+ def main(args=None):
15
+ """Add features from a feature file (.fea) into an OTF font"""
16
+ parser = argparse.ArgumentParser(
17
+ description="Use fontTools to compile OpenType feature files (*.fea)."
18
+ )
19
+ parser.add_argument(
20
+ "input_fea", metavar="FEATURES", help="Path to the feature file"
21
+ )
22
+ parser.add_argument(
23
+ "input_font", metavar="INPUT_FONT", help="Path to the input font"
24
+ )
25
+ parser.add_argument(
26
+ "-o",
27
+ "--output",
28
+ dest="output_font",
29
+ metavar="OUTPUT_FONT",
30
+ help="Path to the output font.",
31
+ )
32
+ parser.add_argument(
33
+ "-t",
34
+ "--tables",
35
+ metavar="TABLE_TAG",
36
+ choices=Builder.supportedTables,
37
+ nargs="+",
38
+ help="Specify the table(s) to be built.",
39
+ )
40
+ parser.add_argument(
41
+ "-d",
42
+ "--debug",
43
+ action="store_true",
44
+ help="Add source-level debugging information to font.",
45
+ )
46
+ parser.add_argument(
47
+ "-v",
48
+ "--verbose",
49
+ help="Increase the logger verbosity. Multiple -v " "options are allowed.",
50
+ action="count",
51
+ default=0,
52
+ )
53
+ parser.add_argument(
54
+ "--traceback", help="show traceback for exceptions.", action="store_true"
55
+ )
56
+ options = parser.parse_args(args)
57
+
58
+ levels = ["WARNING", "INFO", "DEBUG"]
59
+ configLogger(level=levels[min(len(levels) - 1, options.verbose)])
60
+
61
+ output_font = options.output_font or makeOutputFileName(options.input_font)
62
+ log.info("Compiling features to '%s'" % (output_font))
63
+
64
+ font = TTFont(options.input_font)
65
+ try:
66
+ addOpenTypeFeatures(
67
+ font, options.input_fea, tables=options.tables, debug=options.debug
68
+ )
69
+ except FeatureLibError as e:
70
+ if options.traceback:
71
+ raise
72
+ log.error(e)
73
+ sys.exit(1)
74
+ font.save(output_font)
75
+
76
+
77
+ if __name__ == "__main__":
78
+ sys.exit(main())
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/ast.py ADDED
@@ -0,0 +1,2143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import weakref
2
+ from fontTools.feaLib.error import FeatureLibError
3
+ from fontTools.feaLib.location import FeatureLibLocation
4
+ from fontTools.misc.encodingTools import getEncoding
5
+ from fontTools.misc.textTools import byteord, tobytes
6
+ from collections import OrderedDict
7
+ import itertools
8
+
9
+ SHIFT = " " * 4
10
+
11
+ __all__ = [
12
+ "Element",
13
+ "FeatureFile",
14
+ "Comment",
15
+ "GlyphName",
16
+ "GlyphClass",
17
+ "GlyphClassName",
18
+ "MarkClassName",
19
+ "AnonymousBlock",
20
+ "Block",
21
+ "FeatureBlock",
22
+ "NestedBlock",
23
+ "LookupBlock",
24
+ "GlyphClassDefinition",
25
+ "GlyphClassDefStatement",
26
+ "MarkClass",
27
+ "MarkClassDefinition",
28
+ "AlternateSubstStatement",
29
+ "Anchor",
30
+ "AnchorDefinition",
31
+ "AttachStatement",
32
+ "AxisValueLocationStatement",
33
+ "BaseAxis",
34
+ "CVParametersNameStatement",
35
+ "ChainContextPosStatement",
36
+ "ChainContextSubstStatement",
37
+ "CharacterStatement",
38
+ "ConditionsetStatement",
39
+ "CursivePosStatement",
40
+ "ElidedFallbackName",
41
+ "ElidedFallbackNameID",
42
+ "Expression",
43
+ "FeatureNameStatement",
44
+ "FeatureReferenceStatement",
45
+ "FontRevisionStatement",
46
+ "HheaField",
47
+ "IgnorePosStatement",
48
+ "IgnoreSubstStatement",
49
+ "IncludeStatement",
50
+ "LanguageStatement",
51
+ "LanguageSystemStatement",
52
+ "LigatureCaretByIndexStatement",
53
+ "LigatureCaretByPosStatement",
54
+ "LigatureSubstStatement",
55
+ "LookupFlagStatement",
56
+ "LookupReferenceStatement",
57
+ "MarkBasePosStatement",
58
+ "MarkLigPosStatement",
59
+ "MarkMarkPosStatement",
60
+ "MultipleSubstStatement",
61
+ "NameRecord",
62
+ "OS2Field",
63
+ "PairPosStatement",
64
+ "ReverseChainSingleSubstStatement",
65
+ "ScriptStatement",
66
+ "SinglePosStatement",
67
+ "SingleSubstStatement",
68
+ "SizeParameters",
69
+ "Statement",
70
+ "STATAxisValueStatement",
71
+ "STATDesignAxisStatement",
72
+ "STATNameStatement",
73
+ "SubtableStatement",
74
+ "TableBlock",
75
+ "ValueRecord",
76
+ "ValueRecordDefinition",
77
+ "VheaField",
78
+ ]
79
+
80
+
81
+ def deviceToString(device):
82
+ if device is None:
83
+ return "<device NULL>"
84
+ else:
85
+ return "<device %s>" % ", ".join("%d %d" % t for t in device)
86
+
87
+
88
+ fea_keywords = set(
89
+ [
90
+ "anchor",
91
+ "anchordef",
92
+ "anon",
93
+ "anonymous",
94
+ "by",
95
+ "contour",
96
+ "cursive",
97
+ "device",
98
+ "enum",
99
+ "enumerate",
100
+ "excludedflt",
101
+ "exclude_dflt",
102
+ "feature",
103
+ "from",
104
+ "ignore",
105
+ "ignorebaseglyphs",
106
+ "ignoreligatures",
107
+ "ignoremarks",
108
+ "include",
109
+ "includedflt",
110
+ "include_dflt",
111
+ "language",
112
+ "languagesystem",
113
+ "lookup",
114
+ "lookupflag",
115
+ "mark",
116
+ "markattachmenttype",
117
+ "markclass",
118
+ "nameid",
119
+ "null",
120
+ "parameters",
121
+ "pos",
122
+ "position",
123
+ "required",
124
+ "righttoleft",
125
+ "reversesub",
126
+ "rsub",
127
+ "script",
128
+ "sub",
129
+ "substitute",
130
+ "subtable",
131
+ "table",
132
+ "usemarkfilteringset",
133
+ "useextension",
134
+ "valuerecorddef",
135
+ "base",
136
+ "gdef",
137
+ "head",
138
+ "hhea",
139
+ "name",
140
+ "vhea",
141
+ "vmtx",
142
+ ]
143
+ )
144
+
145
+
146
+ def asFea(g):
147
+ if hasattr(g, "asFea"):
148
+ return g.asFea()
149
+ elif isinstance(g, tuple) and len(g) == 2:
150
+ return asFea(g[0]) + " - " + asFea(g[1]) # a range
151
+ elif g.lower() in fea_keywords:
152
+ return "\\" + g
153
+ else:
154
+ return g
155
+
156
+
157
+ class Element(object):
158
+ """A base class representing "something" in a feature file."""
159
+
160
+ def __init__(self, location=None):
161
+ #: location of this element as a `FeatureLibLocation` object.
162
+ if location and not isinstance(location, FeatureLibLocation):
163
+ location = FeatureLibLocation(*location)
164
+ self.location = location
165
+
166
+ def build(self, builder):
167
+ pass
168
+
169
+ def asFea(self, indent=""):
170
+ """Returns this element as a string of feature code. For block-type
171
+ elements (such as :class:`FeatureBlock`), the `indent` string is
172
+ added to the start of each line in the output."""
173
+ raise NotImplementedError
174
+
175
+ def __str__(self):
176
+ return self.asFea()
177
+
178
+
179
+ class Statement(Element):
180
+ pass
181
+
182
+
183
+ class Expression(Element):
184
+ pass
185
+
186
+
187
+ class Comment(Element):
188
+ """A comment in a feature file."""
189
+
190
+ def __init__(self, text, location=None):
191
+ super(Comment, self).__init__(location)
192
+ #: Text of the comment
193
+ self.text = text
194
+
195
+ def asFea(self, indent=""):
196
+ return self.text
197
+
198
+
199
+ class NullGlyph(Expression):
200
+ """The NULL glyph, used in glyph deletion substitutions."""
201
+
202
+ def __init__(self, location=None):
203
+ Expression.__init__(self, location)
204
+ #: The name itself as a string
205
+
206
+ def glyphSet(self):
207
+ """The glyphs in this class as a tuple of :class:`GlyphName` objects."""
208
+ return ()
209
+
210
+ def asFea(self, indent=""):
211
+ return "NULL"
212
+
213
+
214
+ class GlyphName(Expression):
215
+ """A single glyph name, such as ``cedilla``."""
216
+
217
+ def __init__(self, glyph, location=None):
218
+ Expression.__init__(self, location)
219
+ #: The name itself as a string
220
+ self.glyph = glyph
221
+
222
+ def glyphSet(self):
223
+ """The glyphs in this class as a tuple of :class:`GlyphName` objects."""
224
+ return (self.glyph,)
225
+
226
+ def asFea(self, indent=""):
227
+ return asFea(self.glyph)
228
+
229
+
230
+ class GlyphClass(Expression):
231
+ """A glyph class, such as ``[acute cedilla grave]``."""
232
+
233
+ def __init__(self, glyphs=None, location=None):
234
+ Expression.__init__(self, location)
235
+ #: The list of glyphs in this class, as :class:`GlyphName` objects.
236
+ self.glyphs = glyphs if glyphs is not None else []
237
+ self.original = []
238
+ self.curr = 0
239
+
240
+ def glyphSet(self):
241
+ """The glyphs in this class as a tuple of :class:`GlyphName` objects."""
242
+ return tuple(self.glyphs)
243
+
244
+ def asFea(self, indent=""):
245
+ if len(self.original):
246
+ if self.curr < len(self.glyphs):
247
+ self.original.extend(self.glyphs[self.curr :])
248
+ self.curr = len(self.glyphs)
249
+ return "[" + " ".join(map(asFea, self.original)) + "]"
250
+ else:
251
+ return "[" + " ".join(map(asFea, self.glyphs)) + "]"
252
+
253
+ def extend(self, glyphs):
254
+ """Add a list of :class:`GlyphName` objects to the class."""
255
+ self.glyphs.extend(glyphs)
256
+
257
+ def append(self, glyph):
258
+ """Add a single :class:`GlyphName` object to the class."""
259
+ self.glyphs.append(glyph)
260
+
261
+ def add_range(self, start, end, glyphs):
262
+ """Add a range (e.g. ``A-Z``) to the class. ``start`` and ``end``
263
+ are either :class:`GlyphName` objects or strings representing the
264
+ start and end glyphs in the class, and ``glyphs`` is the full list of
265
+ :class:`GlyphName` objects in the range."""
266
+ if self.curr < len(self.glyphs):
267
+ self.original.extend(self.glyphs[self.curr :])
268
+ self.original.append((start, end))
269
+ self.glyphs.extend(glyphs)
270
+ self.curr = len(self.glyphs)
271
+
272
+ def add_cid_range(self, start, end, glyphs):
273
+ """Add a range to the class by glyph ID. ``start`` and ``end`` are the
274
+ initial and final IDs, and ``glyphs`` is the full list of
275
+ :class:`GlyphName` objects in the range."""
276
+ if self.curr < len(self.glyphs):
277
+ self.original.extend(self.glyphs[self.curr :])
278
+ self.original.append(("\\{}".format(start), "\\{}".format(end)))
279
+ self.glyphs.extend(glyphs)
280
+ self.curr = len(self.glyphs)
281
+
282
+ def add_class(self, gc):
283
+ """Add glyphs from the given :class:`GlyphClassName` object to the
284
+ class."""
285
+ if self.curr < len(self.glyphs):
286
+ self.original.extend(self.glyphs[self.curr :])
287
+ self.original.append(gc)
288
+ self.glyphs.extend(gc.glyphSet())
289
+ self.curr = len(self.glyphs)
290
+
291
+
292
+ class GlyphClassName(Expression):
293
+ """A glyph class name, such as ``@FRENCH_MARKS``. This must be instantiated
294
+ with a :class:`GlyphClassDefinition` object."""
295
+
296
+ def __init__(self, glyphclass, location=None):
297
+ Expression.__init__(self, location)
298
+ assert isinstance(glyphclass, GlyphClassDefinition)
299
+ self.glyphclass = glyphclass
300
+
301
+ def glyphSet(self):
302
+ """The glyphs in this class as a tuple of :class:`GlyphName` objects."""
303
+ return tuple(self.glyphclass.glyphSet())
304
+
305
+ def asFea(self, indent=""):
306
+ return "@" + self.glyphclass.name
307
+
308
+
309
+ class MarkClassName(Expression):
310
+ """A mark class name, such as ``@FRENCH_MARKS`` defined with ``markClass``.
311
+ This must be instantiated with a :class:`MarkClass` object."""
312
+
313
+ def __init__(self, markClass, location=None):
314
+ Expression.__init__(self, location)
315
+ assert isinstance(markClass, MarkClass)
316
+ self.markClass = markClass
317
+
318
+ def glyphSet(self):
319
+ """The glyphs in this class as a tuple of :class:`GlyphName` objects."""
320
+ return self.markClass.glyphSet()
321
+
322
+ def asFea(self, indent=""):
323
+ return "@" + self.markClass.name
324
+
325
+
326
+ class AnonymousBlock(Statement):
327
+ """An anonymous data block."""
328
+
329
+ def __init__(self, tag, content, location=None):
330
+ Statement.__init__(self, location)
331
+ self.tag = tag #: string containing the block's "tag"
332
+ self.content = content #: block data as string
333
+
334
+ def asFea(self, indent=""):
335
+ res = "anon {} {{\n".format(self.tag)
336
+ res += self.content
337
+ res += "}} {};\n\n".format(self.tag)
338
+ return res
339
+
340
+
341
+ class Block(Statement):
342
+ """A block of statements: feature, lookup, etc."""
343
+
344
+ def __init__(self, location=None):
345
+ Statement.__init__(self, location)
346
+ self.statements = [] #: Statements contained in the block
347
+
348
+ def build(self, builder):
349
+ """When handed a 'builder' object of comparable interface to
350
+ :class:`fontTools.feaLib.builder`, walks the statements in this
351
+ block, calling the builder callbacks."""
352
+ for s in self.statements:
353
+ s.build(builder)
354
+
355
+ def asFea(self, indent=""):
356
+ indent += SHIFT
357
+ return (
358
+ indent
359
+ + ("\n" + indent).join([s.asFea(indent=indent) for s in self.statements])
360
+ + "\n"
361
+ )
362
+
363
+
364
+ class FeatureFile(Block):
365
+ """The top-level element of the syntax tree, containing the whole feature
366
+ file in its ``statements`` attribute."""
367
+
368
+ def __init__(self):
369
+ Block.__init__(self, location=None)
370
+ self.markClasses = {} # name --> ast.MarkClass
371
+
372
+ def asFea(self, indent=""):
373
+ return "\n".join(s.asFea(indent=indent) for s in self.statements)
374
+
375
+
376
+ class FeatureBlock(Block):
377
+ """A named feature block."""
378
+
379
+ def __init__(self, name, use_extension=False, location=None):
380
+ Block.__init__(self, location)
381
+ self.name, self.use_extension = name, use_extension
382
+
383
+ def build(self, builder):
384
+ """Call the ``start_feature`` callback on the builder object, visit
385
+ all the statements in this feature, and then call ``end_feature``."""
386
+ builder.start_feature(self.location, self.name, self.use_extension)
387
+ # language exclude_dflt statements modify builder.features_
388
+ # limit them to this block with temporary builder.features_
389
+ features = builder.features_
390
+ builder.features_ = {}
391
+ Block.build(self, builder)
392
+ for key, value in builder.features_.items():
393
+ features.setdefault(key, []).extend(value)
394
+ builder.features_ = features
395
+ builder.end_feature()
396
+
397
+ def asFea(self, indent=""):
398
+ res = indent + "feature %s " % self.name.strip()
399
+ if self.use_extension:
400
+ res += "useExtension "
401
+ res += "{\n"
402
+ res += Block.asFea(self, indent=indent)
403
+ res += indent + "} %s;\n" % self.name.strip()
404
+ return res
405
+
406
+
407
+ class NestedBlock(Block):
408
+ """A block inside another block, for example when found inside a
409
+ ``cvParameters`` block."""
410
+
411
+ def __init__(self, tag, block_name, location=None):
412
+ Block.__init__(self, location)
413
+ self.tag = tag
414
+ self.block_name = block_name
415
+
416
+ def build(self, builder):
417
+ Block.build(self, builder)
418
+ if self.block_name == "ParamUILabelNameID":
419
+ builder.add_to_cv_num_named_params(self.tag)
420
+
421
+ def asFea(self, indent=""):
422
+ res = "{}{} {{\n".format(indent, self.block_name)
423
+ res += Block.asFea(self, indent=indent)
424
+ res += "{}}};\n".format(indent)
425
+ return res
426
+
427
+
428
+ class LookupBlock(Block):
429
+ """A named lookup, containing ``statements``."""
430
+
431
+ def __init__(self, name, use_extension=False, location=None):
432
+ Block.__init__(self, location)
433
+ self.name, self.use_extension = name, use_extension
434
+
435
+ def build(self, builder):
436
+ builder.start_lookup_block(self.location, self.name, self.use_extension)
437
+ Block.build(self, builder)
438
+ builder.end_lookup_block()
439
+
440
+ def asFea(self, indent=""):
441
+ res = "lookup {} ".format(self.name)
442
+ if self.use_extension:
443
+ res += "useExtension "
444
+ res += "{\n"
445
+ res += Block.asFea(self, indent=indent)
446
+ res += "{}}} {};\n".format(indent, self.name)
447
+ return res
448
+
449
+
450
+ class TableBlock(Block):
451
+ """A ``table ... { }`` block."""
452
+
453
+ def __init__(self, name, location=None):
454
+ Block.__init__(self, location)
455
+ self.name = name
456
+
457
+ def asFea(self, indent=""):
458
+ res = "table {} {{\n".format(self.name.strip())
459
+ res += super(TableBlock, self).asFea(indent=indent)
460
+ res += "}} {};\n".format(self.name.strip())
461
+ return res
462
+
463
+
464
+ class GlyphClassDefinition(Statement):
465
+ """Example: ``@UPPERCASE = [A-Z];``."""
466
+
467
+ def __init__(self, name, glyphs, location=None):
468
+ Statement.__init__(self, location)
469
+ self.name = name #: class name as a string, without initial ``@``
470
+ self.glyphs = glyphs #: a :class:`GlyphClass` object
471
+
472
+ def glyphSet(self):
473
+ """The glyphs in this class as a tuple of :class:`GlyphName` objects."""
474
+ return tuple(self.glyphs.glyphSet())
475
+
476
+ def asFea(self, indent=""):
477
+ return "@" + self.name + " = " + self.glyphs.asFea() + ";"
478
+
479
+
480
+ class GlyphClassDefStatement(Statement):
481
+ """Example: ``GlyphClassDef @UPPERCASE, [B], [C], [D];``. The parameters
482
+ must be either :class:`GlyphClass` or :class:`GlyphClassName` objects, or
483
+ ``None``."""
484
+
485
+ def __init__(
486
+ self, baseGlyphs, markGlyphs, ligatureGlyphs, componentGlyphs, location=None
487
+ ):
488
+ Statement.__init__(self, location)
489
+ self.baseGlyphs, self.markGlyphs = (baseGlyphs, markGlyphs)
490
+ self.ligatureGlyphs = ligatureGlyphs
491
+ self.componentGlyphs = componentGlyphs
492
+
493
+ def build(self, builder):
494
+ """Calls the builder's ``add_glyphClassDef`` callback."""
495
+ base = self.baseGlyphs.glyphSet() if self.baseGlyphs else tuple()
496
+ liga = self.ligatureGlyphs.glyphSet() if self.ligatureGlyphs else tuple()
497
+ mark = self.markGlyphs.glyphSet() if self.markGlyphs else tuple()
498
+ comp = self.componentGlyphs.glyphSet() if self.componentGlyphs else tuple()
499
+ builder.add_glyphClassDef(self.location, base, liga, mark, comp)
500
+
501
+ def asFea(self, indent=""):
502
+ return "GlyphClassDef {}, {}, {}, {};".format(
503
+ self.baseGlyphs.asFea() if self.baseGlyphs else "",
504
+ self.ligatureGlyphs.asFea() if self.ligatureGlyphs else "",
505
+ self.markGlyphs.asFea() if self.markGlyphs else "",
506
+ self.componentGlyphs.asFea() if self.componentGlyphs else "",
507
+ )
508
+
509
+
510
+ class MarkClass(object):
511
+ """One `or more` ``markClass`` statements for the same mark class.
512
+
513
+ While glyph classes can be defined only once, the feature file format
514
+ allows expanding mark classes with multiple definitions, each using
515
+ different glyphs and anchors. The following are two ``MarkClassDefinitions``
516
+ for the same ``MarkClass``::
517
+
518
+ markClass [acute grave] <anchor 350 800> @FRENCH_ACCENTS;
519
+ markClass [cedilla] <anchor 350 -200> @FRENCH_ACCENTS;
520
+
521
+ The ``MarkClass`` object is therefore just a container for a list of
522
+ :class:`MarkClassDefinition` statements.
523
+ """
524
+
525
+ def __init__(self, name):
526
+ self.name = name
527
+ self.definitions = []
528
+ self.glyphs = OrderedDict() # glyph --> ast.MarkClassDefinitions
529
+
530
+ def addDefinition(self, definition):
531
+ """Add a :class:`MarkClassDefinition` statement to this mark class."""
532
+ assert isinstance(definition, MarkClassDefinition)
533
+ self.definitions.append(weakref.proxy(definition))
534
+ for glyph in definition.glyphSet():
535
+ if glyph in self.glyphs:
536
+ otherLoc = self.glyphs[glyph].location
537
+ if otherLoc is None:
538
+ end = ""
539
+ else:
540
+ end = f" at {otherLoc}"
541
+ raise FeatureLibError(
542
+ "Glyph %s already defined%s" % (glyph, end), definition.location
543
+ )
544
+ self.glyphs[glyph] = definition
545
+
546
+ def glyphSet(self):
547
+ """The glyphs in this class as a tuple of :class:`GlyphName` objects."""
548
+ return tuple(self.glyphs.keys())
549
+
550
+ def asFea(self, indent=""):
551
+ res = "\n".join(d.asFea() for d in self.definitions)
552
+ return res
553
+
554
+
555
+ class MarkClassDefinition(Statement):
556
+ """A single ``markClass`` statement. The ``markClass`` should be a
557
+ :class:`MarkClass` object, the ``anchor`` an :class:`Anchor` object,
558
+ and the ``glyphs`` parameter should be a `glyph-containing object`_ .
559
+
560
+ Example:
561
+
562
+ .. code:: python
563
+
564
+ mc = MarkClass("FRENCH_ACCENTS")
565
+ mc.addDefinition( MarkClassDefinition(mc, Anchor(350, 800),
566
+ GlyphClass([ GlyphName("acute"), GlyphName("grave") ])
567
+ ) )
568
+ mc.addDefinition( MarkClassDefinition(mc, Anchor(350, -200),
569
+ GlyphClass([ GlyphName("cedilla") ])
570
+ ) )
571
+
572
+ mc.asFea()
573
+ # markClass [acute grave] <anchor 350 800> @FRENCH_ACCENTS;
574
+ # markClass [cedilla] <anchor 350 -200> @FRENCH_ACCENTS;
575
+
576
+ """
577
+
578
+ def __init__(self, markClass, anchor, glyphs, location=None):
579
+ Statement.__init__(self, location)
580
+ assert isinstance(markClass, MarkClass)
581
+ assert isinstance(anchor, Anchor) and isinstance(glyphs, Expression)
582
+ self.markClass, self.anchor, self.glyphs = markClass, anchor, glyphs
583
+
584
+ def glyphSet(self):
585
+ """The glyphs in this class as a tuple of :class:`GlyphName` objects."""
586
+ return self.glyphs.glyphSet()
587
+
588
+ def asFea(self, indent=""):
589
+ return "markClass {} {} @{};".format(
590
+ self.glyphs.asFea(), self.anchor.asFea(), self.markClass.name
591
+ )
592
+
593
+
594
+ class AlternateSubstStatement(Statement):
595
+ """A ``sub ... from ...`` statement.
596
+
597
+ ``glyph`` and ``replacement`` should be `glyph-containing objects`_.
598
+ ``prefix`` and ``suffix`` should be lists of `glyph-containing objects`_."""
599
+
600
+ def __init__(self, prefix, glyph, suffix, replacement, location=None):
601
+ Statement.__init__(self, location)
602
+ self.prefix, self.glyph, self.suffix = (prefix, glyph, suffix)
603
+ self.replacement = replacement
604
+
605
+ def build(self, builder):
606
+ """Calls the builder's ``add_alternate_subst`` callback."""
607
+ glyph = self.glyph.glyphSet()
608
+ assert len(glyph) == 1, glyph
609
+ glyph = list(glyph)[0]
610
+ prefix = [p.glyphSet() for p in self.prefix]
611
+ suffix = [s.glyphSet() for s in self.suffix]
612
+ replacement = self.replacement.glyphSet()
613
+ builder.add_alternate_subst(self.location, prefix, glyph, suffix, replacement)
614
+
615
+ def asFea(self, indent=""):
616
+ res = "sub "
617
+ if len(self.prefix) or len(self.suffix):
618
+ if len(self.prefix):
619
+ res += " ".join(map(asFea, self.prefix)) + " "
620
+ res += asFea(self.glyph) + "'" # even though we really only use 1
621
+ if len(self.suffix):
622
+ res += " " + " ".join(map(asFea, self.suffix))
623
+ else:
624
+ res += asFea(self.glyph)
625
+ res += " from "
626
+ res += asFea(self.replacement)
627
+ res += ";"
628
+ return res
629
+
630
+
631
+ class Anchor(Expression):
632
+ """An ``Anchor`` element, used inside a ``pos`` rule.
633
+
634
+ If a ``name`` is given, this will be used in preference to the coordinates.
635
+ Other values should be integer.
636
+ """
637
+
638
+ def __init__(
639
+ self,
640
+ x,
641
+ y,
642
+ name=None,
643
+ contourpoint=None,
644
+ xDeviceTable=None,
645
+ yDeviceTable=None,
646
+ location=None,
647
+ ):
648
+ Expression.__init__(self, location)
649
+ self.name = name
650
+ self.x, self.y, self.contourpoint = x, y, contourpoint
651
+ self.xDeviceTable, self.yDeviceTable = xDeviceTable, yDeviceTable
652
+
653
+ def asFea(self, indent=""):
654
+ if self.name is not None:
655
+ return "<anchor {}>".format(self.name)
656
+ res = "<anchor {} {}".format(self.x, self.y)
657
+ if self.contourpoint:
658
+ res += " contourpoint {}".format(self.contourpoint)
659
+ if self.xDeviceTable or self.yDeviceTable:
660
+ res += " "
661
+ res += deviceToString(self.xDeviceTable)
662
+ res += " "
663
+ res += deviceToString(self.yDeviceTable)
664
+ res += ">"
665
+ return res
666
+
667
+
668
+ class AnchorDefinition(Statement):
669
+ """A named anchor definition. (2.e.viii). ``name`` should be a string."""
670
+
671
+ def __init__(self, name, x, y, contourpoint=None, location=None):
672
+ Statement.__init__(self, location)
673
+ self.name, self.x, self.y, self.contourpoint = name, x, y, contourpoint
674
+
675
+ def asFea(self, indent=""):
676
+ res = "anchorDef {} {}".format(self.x, self.y)
677
+ if self.contourpoint:
678
+ res += " contourpoint {}".format(self.contourpoint)
679
+ res += " {};".format(self.name)
680
+ return res
681
+
682
+
683
+ class AttachStatement(Statement):
684
+ """A ``GDEF`` table ``Attach`` statement."""
685
+
686
+ def __init__(self, glyphs, contourPoints, location=None):
687
+ Statement.__init__(self, location)
688
+ self.glyphs = glyphs #: A `glyph-containing object`_
689
+ self.contourPoints = contourPoints #: A list of integer contour points
690
+
691
+ def build(self, builder):
692
+ """Calls the builder's ``add_attach_points`` callback."""
693
+ glyphs = self.glyphs.glyphSet()
694
+ builder.add_attach_points(self.location, glyphs, self.contourPoints)
695
+
696
+ def asFea(self, indent=""):
697
+ return "Attach {} {};".format(
698
+ self.glyphs.asFea(), " ".join(str(c) for c in self.contourPoints)
699
+ )
700
+
701
+
702
+ class ChainContextPosStatement(Statement):
703
+ r"""A chained contextual positioning statement.
704
+
705
+ ``prefix``, ``glyphs``, and ``suffix`` should be lists of
706
+ `glyph-containing objects`_ .
707
+
708
+ ``lookups`` should be a list of elements representing what lookups
709
+ to apply at each glyph position. Each element should be a
710
+ :class:`LookupBlock` to apply a single chaining lookup at the given
711
+ position, a list of :class:`LookupBlock`\ s to apply multiple
712
+ lookups, or ``None`` to apply no lookup. The length of the outer
713
+ list should equal the length of ``glyphs``; the inner lists can be
714
+ of variable length."""
715
+
716
+ def __init__(self, prefix, glyphs, suffix, lookups, location=None):
717
+ Statement.__init__(self, location)
718
+ self.prefix, self.glyphs, self.suffix = prefix, glyphs, suffix
719
+ self.lookups = list(lookups)
720
+ for i, lookup in enumerate(lookups):
721
+ if lookup:
722
+ try:
723
+ iter(lookup)
724
+ except TypeError:
725
+ self.lookups[i] = [lookup]
726
+
727
+ def build(self, builder):
728
+ """Calls the builder's ``add_chain_context_pos`` callback."""
729
+ prefix = [p.glyphSet() for p in self.prefix]
730
+ glyphs = [g.glyphSet() for g in self.glyphs]
731
+ suffix = [s.glyphSet() for s in self.suffix]
732
+ builder.add_chain_context_pos(
733
+ self.location, prefix, glyphs, suffix, self.lookups
734
+ )
735
+
736
+ def asFea(self, indent=""):
737
+ res = "pos "
738
+ if (
739
+ len(self.prefix)
740
+ or len(self.suffix)
741
+ or any([x is not None for x in self.lookups])
742
+ ):
743
+ if len(self.prefix):
744
+ res += " ".join(g.asFea() for g in self.prefix) + " "
745
+ for i, g in enumerate(self.glyphs):
746
+ res += g.asFea() + "'"
747
+ if self.lookups[i]:
748
+ for lu in self.lookups[i]:
749
+ res += " lookup " + lu.name
750
+ if i < len(self.glyphs) - 1:
751
+ res += " "
752
+ if len(self.suffix):
753
+ res += " " + " ".join(map(asFea, self.suffix))
754
+ else:
755
+ res += " ".join(map(asFea, self.glyphs))
756
+ res += ";"
757
+ return res
758
+
759
+
760
+ class ChainContextSubstStatement(Statement):
761
+ r"""A chained contextual substitution statement.
762
+
763
+ ``prefix``, ``glyphs``, and ``suffix`` should be lists of
764
+ `glyph-containing objects`_ .
765
+
766
+ ``lookups`` should be a list of elements representing what lookups
767
+ to apply at each glyph position. Each element should be a
768
+ :class:`LookupBlock` to apply a single chaining lookup at the given
769
+ position, a list of :class:`LookupBlock`\ s to apply multiple
770
+ lookups, or ``None`` to apply no lookup. The length of the outer
771
+ list should equal the length of ``glyphs``; the inner lists can be
772
+ of variable length."""
773
+
774
+ def __init__(self, prefix, glyphs, suffix, lookups, location=None):
775
+ Statement.__init__(self, location)
776
+ self.prefix, self.glyphs, self.suffix = prefix, glyphs, suffix
777
+ self.lookups = list(lookups)
778
+ for i, lookup in enumerate(lookups):
779
+ if lookup:
780
+ try:
781
+ iter(lookup)
782
+ except TypeError:
783
+ self.lookups[i] = [lookup]
784
+
785
+ def build(self, builder):
786
+ """Calls the builder's ``add_chain_context_subst`` callback."""
787
+ prefix = [p.glyphSet() for p in self.prefix]
788
+ glyphs = [g.glyphSet() for g in self.glyphs]
789
+ suffix = [s.glyphSet() for s in self.suffix]
790
+ builder.add_chain_context_subst(
791
+ self.location, prefix, glyphs, suffix, self.lookups
792
+ )
793
+
794
+ def asFea(self, indent=""):
795
+ res = "sub "
796
+ if (
797
+ len(self.prefix)
798
+ or len(self.suffix)
799
+ or any([x is not None for x in self.lookups])
800
+ ):
801
+ if len(self.prefix):
802
+ res += " ".join(g.asFea() for g in self.prefix) + " "
803
+ for i, g in enumerate(self.glyphs):
804
+ res += g.asFea() + "'"
805
+ if self.lookups[i]:
806
+ for lu in self.lookups[i]:
807
+ res += " lookup " + lu.name
808
+ if i < len(self.glyphs) - 1:
809
+ res += " "
810
+ if len(self.suffix):
811
+ res += " " + " ".join(map(asFea, self.suffix))
812
+ else:
813
+ res += " ".join(map(asFea, self.glyphs))
814
+ res += ";"
815
+ return res
816
+
817
+
818
+ class CursivePosStatement(Statement):
819
+ """A cursive positioning statement. Entry and exit anchors can either
820
+ be :class:`Anchor` objects or ``None``."""
821
+
822
+ def __init__(self, glyphclass, entryAnchor, exitAnchor, location=None):
823
+ Statement.__init__(self, location)
824
+ self.glyphclass = glyphclass
825
+ self.entryAnchor, self.exitAnchor = entryAnchor, exitAnchor
826
+
827
+ def build(self, builder):
828
+ """Calls the builder object's ``add_cursive_pos`` callback."""
829
+ builder.add_cursive_pos(
830
+ self.location, self.glyphclass.glyphSet(), self.entryAnchor, self.exitAnchor
831
+ )
832
+
833
+ def asFea(self, indent=""):
834
+ entry = self.entryAnchor.asFea() if self.entryAnchor else "<anchor NULL>"
835
+ exit = self.exitAnchor.asFea() if self.exitAnchor else "<anchor NULL>"
836
+ return "pos cursive {} {} {};".format(self.glyphclass.asFea(), entry, exit)
837
+
838
+
839
+ class FeatureReferenceStatement(Statement):
840
+ """Example: ``feature salt;``"""
841
+
842
+ def __init__(self, featureName, location=None):
843
+ Statement.__init__(self, location)
844
+ self.location, self.featureName = (location, featureName)
845
+
846
+ def build(self, builder):
847
+ """Calls the builder object's ``add_feature_reference`` callback."""
848
+ builder.add_feature_reference(self.location, self.featureName)
849
+
850
+ def asFea(self, indent=""):
851
+ return "feature {};".format(self.featureName)
852
+
853
+
854
+ class IgnorePosStatement(Statement):
855
+ """An ``ignore pos`` statement, containing `one or more` contexts to ignore.
856
+
857
+ ``chainContexts`` should be a list of ``(prefix, glyphs, suffix)`` tuples,
858
+ with each of ``prefix``, ``glyphs`` and ``suffix`` being
859
+ `glyph-containing objects`_ ."""
860
+
861
+ def __init__(self, chainContexts, location=None):
862
+ Statement.__init__(self, location)
863
+ self.chainContexts = chainContexts
864
+
865
+ def build(self, builder):
866
+ """Calls the builder object's ``add_chain_context_pos`` callback on each
867
+ rule context."""
868
+ for prefix, glyphs, suffix in self.chainContexts:
869
+ prefix = [p.glyphSet() for p in prefix]
870
+ glyphs = [g.glyphSet() for g in glyphs]
871
+ suffix = [s.glyphSet() for s in suffix]
872
+ builder.add_chain_context_pos(self.location, prefix, glyphs, suffix, [])
873
+
874
+ def asFea(self, indent=""):
875
+ contexts = []
876
+ for prefix, glyphs, suffix in self.chainContexts:
877
+ res = ""
878
+ if len(prefix) or len(suffix):
879
+ if len(prefix):
880
+ res += " ".join(map(asFea, prefix)) + " "
881
+ res += " ".join(g.asFea() + "'" for g in glyphs)
882
+ if len(suffix):
883
+ res += " " + " ".join(map(asFea, suffix))
884
+ else:
885
+ res += " ".join(map(asFea, glyphs))
886
+ contexts.append(res)
887
+ return "ignore pos " + ", ".join(contexts) + ";"
888
+
889
+
890
+ class IgnoreSubstStatement(Statement):
891
+ """An ``ignore sub`` statement, containing `one or more` contexts to ignore.
892
+
893
+ ``chainContexts`` should be a list of ``(prefix, glyphs, suffix)`` tuples,
894
+ with each of ``prefix``, ``glyphs`` and ``suffix`` being
895
+ `glyph-containing objects`_ ."""
896
+
897
+ def __init__(self, chainContexts, location=None):
898
+ Statement.__init__(self, location)
899
+ self.chainContexts = chainContexts
900
+
901
+ def build(self, builder):
902
+ """Calls the builder object's ``add_chain_context_subst`` callback on
903
+ each rule context."""
904
+ for prefix, glyphs, suffix in self.chainContexts:
905
+ prefix = [p.glyphSet() for p in prefix]
906
+ glyphs = [g.glyphSet() for g in glyphs]
907
+ suffix = [s.glyphSet() for s in suffix]
908
+ builder.add_chain_context_subst(self.location, prefix, glyphs, suffix, [])
909
+
910
+ def asFea(self, indent=""):
911
+ contexts = []
912
+ for prefix, glyphs, suffix in self.chainContexts:
913
+ res = ""
914
+ if len(prefix):
915
+ res += " ".join(map(asFea, prefix)) + " "
916
+ res += " ".join(g.asFea() + "'" for g in glyphs)
917
+ if len(suffix):
918
+ res += " " + " ".join(map(asFea, suffix))
919
+ contexts.append(res)
920
+ return "ignore sub " + ", ".join(contexts) + ";"
921
+
922
+
923
+ class IncludeStatement(Statement):
924
+ """An ``include()`` statement."""
925
+
926
+ def __init__(self, filename, location=None):
927
+ super(IncludeStatement, self).__init__(location)
928
+ self.filename = filename #: String containing name of file to include
929
+
930
+ def build(self):
931
+ # TODO: consider lazy-loading the including parser/lexer?
932
+ raise FeatureLibError(
933
+ "Building an include statement is not implemented yet. "
934
+ "Instead, use Parser(..., followIncludes=True) for building.",
935
+ self.location,
936
+ )
937
+
938
+ def asFea(self, indent=""):
939
+ return indent + "include(%s);" % self.filename
940
+
941
+
942
+ class LanguageStatement(Statement):
943
+ """A ``language`` statement within a feature."""
944
+
945
+ def __init__(self, language, include_default=True, required=False, location=None):
946
+ Statement.__init__(self, location)
947
+ assert len(language) == 4
948
+ self.language = language #: A four-character language tag
949
+ self.include_default = include_default #: If false, "exclude_dflt"
950
+ self.required = required
951
+
952
+ def build(self, builder):
953
+ """Call the builder object's ``set_language`` callback."""
954
+ builder.set_language(
955
+ location=self.location,
956
+ language=self.language,
957
+ include_default=self.include_default,
958
+ required=self.required,
959
+ )
960
+
961
+ def asFea(self, indent=""):
962
+ res = "language {}".format(self.language.strip())
963
+ if not self.include_default:
964
+ res += " exclude_dflt"
965
+ if self.required:
966
+ res += " required"
967
+ res += ";"
968
+ return res
969
+
970
+
971
+ class LanguageSystemStatement(Statement):
972
+ """A top-level ``languagesystem`` statement."""
973
+
974
+ def __init__(self, script, language, location=None):
975
+ Statement.__init__(self, location)
976
+ self.script, self.language = (script, language)
977
+
978
+ def build(self, builder):
979
+ """Calls the builder object's ``add_language_system`` callback."""
980
+ builder.add_language_system(self.location, self.script, self.language)
981
+
982
+ def asFea(self, indent=""):
983
+ return "languagesystem {} {};".format(self.script, self.language.strip())
984
+
985
+
986
+ class FontRevisionStatement(Statement):
987
+ """A ``head`` table ``FontRevision`` statement. ``revision`` should be a
988
+ number, and will be formatted to three significant decimal places."""
989
+
990
+ def __init__(self, revision, location=None):
991
+ Statement.__init__(self, location)
992
+ self.revision = revision
993
+
994
+ def build(self, builder):
995
+ builder.set_font_revision(self.location, self.revision)
996
+
997
+ def asFea(self, indent=""):
998
+ return "FontRevision {:.3f};".format(self.revision)
999
+
1000
+
1001
+ class LigatureCaretByIndexStatement(Statement):
1002
+ """A ``GDEF`` table ``LigatureCaretByIndex`` statement. ``glyphs`` should be
1003
+ a `glyph-containing object`_, and ``carets`` should be a list of integers."""
1004
+
1005
+ def __init__(self, glyphs, carets, location=None):
1006
+ Statement.__init__(self, location)
1007
+ self.glyphs, self.carets = (glyphs, carets)
1008
+
1009
+ def build(self, builder):
1010
+ """Calls the builder object's ``add_ligatureCaretByIndex_`` callback."""
1011
+ glyphs = self.glyphs.glyphSet()
1012
+ builder.add_ligatureCaretByIndex_(self.location, glyphs, set(self.carets))
1013
+
1014
+ def asFea(self, indent=""):
1015
+ return "LigatureCaretByIndex {} {};".format(
1016
+ self.glyphs.asFea(), " ".join(str(x) for x in self.carets)
1017
+ )
1018
+
1019
+
1020
+ class LigatureCaretByPosStatement(Statement):
1021
+ """A ``GDEF`` table ``LigatureCaretByPos`` statement. ``glyphs`` should be
1022
+ a `glyph-containing object`_, and ``carets`` should be a list of integers."""
1023
+
1024
+ def __init__(self, glyphs, carets, location=None):
1025
+ Statement.__init__(self, location)
1026
+ self.glyphs, self.carets = (glyphs, carets)
1027
+
1028
+ def build(self, builder):
1029
+ """Calls the builder object's ``add_ligatureCaretByPos_`` callback."""
1030
+ glyphs = self.glyphs.glyphSet()
1031
+ builder.add_ligatureCaretByPos_(self.location, glyphs, set(self.carets))
1032
+
1033
+ def asFea(self, indent=""):
1034
+ return "LigatureCaretByPos {} {};".format(
1035
+ self.glyphs.asFea(), " ".join(str(x) for x in self.carets)
1036
+ )
1037
+
1038
+
1039
+ class LigatureSubstStatement(Statement):
1040
+ """A chained contextual substitution statement.
1041
+
1042
+ ``prefix``, ``glyphs``, and ``suffix`` should be lists of
1043
+ `glyph-containing objects`_; ``replacement`` should be a single
1044
+ `glyph-containing object`_.
1045
+
1046
+ If ``forceChain`` is True, this is expressed as a chaining rule
1047
+ (e.g. ``sub f' i' by f_i``) even when no context is given."""
1048
+
1049
+ def __init__(self, prefix, glyphs, suffix, replacement, forceChain, location=None):
1050
+ Statement.__init__(self, location)
1051
+ self.prefix, self.glyphs, self.suffix = (prefix, glyphs, suffix)
1052
+ self.replacement, self.forceChain = replacement, forceChain
1053
+
1054
+ def build(self, builder):
1055
+ prefix = [p.glyphSet() for p in self.prefix]
1056
+ glyphs = [g.glyphSet() for g in self.glyphs]
1057
+ suffix = [s.glyphSet() for s in self.suffix]
1058
+ builder.add_ligature_subst(
1059
+ self.location, prefix, glyphs, suffix, self.replacement, self.forceChain
1060
+ )
1061
+
1062
+ def asFea(self, indent=""):
1063
+ res = "sub "
1064
+ if len(self.prefix) or len(self.suffix) or self.forceChain:
1065
+ if len(self.prefix):
1066
+ res += " ".join(g.asFea() for g in self.prefix) + " "
1067
+ res += " ".join(g.asFea() + "'" for g in self.glyphs)
1068
+ if len(self.suffix):
1069
+ res += " " + " ".join(g.asFea() for g in self.suffix)
1070
+ else:
1071
+ res += " ".join(g.asFea() for g in self.glyphs)
1072
+ res += " by "
1073
+ res += asFea(self.replacement)
1074
+ res += ";"
1075
+ return res
1076
+
1077
+
1078
+ class LookupFlagStatement(Statement):
1079
+ """A ``lookupflag`` statement. The ``value`` should be an integer value
1080
+ representing the flags in use, but not including the ``markAttachment``
1081
+ class and ``markFilteringSet`` values, which must be specified as
1082
+ glyph-containing objects."""
1083
+
1084
+ def __init__(
1085
+ self, value=0, markAttachment=None, markFilteringSet=None, location=None
1086
+ ):
1087
+ Statement.__init__(self, location)
1088
+ self.value = value
1089
+ self.markAttachment = markAttachment
1090
+ self.markFilteringSet = markFilteringSet
1091
+
1092
+ def build(self, builder):
1093
+ """Calls the builder object's ``set_lookup_flag`` callback."""
1094
+ markAttach = None
1095
+ if self.markAttachment is not None:
1096
+ markAttach = self.markAttachment.glyphSet()
1097
+ markFilter = None
1098
+ if self.markFilteringSet is not None:
1099
+ markFilter = self.markFilteringSet.glyphSet()
1100
+ builder.set_lookup_flag(self.location, self.value, markAttach, markFilter)
1101
+
1102
+ def asFea(self, indent=""):
1103
+ res = []
1104
+ flags = ["RightToLeft", "IgnoreBaseGlyphs", "IgnoreLigatures", "IgnoreMarks"]
1105
+ curr = 1
1106
+ for i in range(len(flags)):
1107
+ if self.value & curr != 0:
1108
+ res.append(flags[i])
1109
+ curr = curr << 1
1110
+ if self.markAttachment is not None:
1111
+ res.append("MarkAttachmentType {}".format(self.markAttachment.asFea()))
1112
+ if self.markFilteringSet is not None:
1113
+ res.append("UseMarkFilteringSet {}".format(self.markFilteringSet.asFea()))
1114
+ if not res:
1115
+ res = ["0"]
1116
+ return "lookupflag {};".format(" ".join(res))
1117
+
1118
+
1119
+ class LookupReferenceStatement(Statement):
1120
+ """Represents a ``lookup ...;`` statement to include a lookup in a feature.
1121
+
1122
+ The ``lookup`` should be a :class:`LookupBlock` object."""
1123
+
1124
+ def __init__(self, lookup, location=None):
1125
+ Statement.__init__(self, location)
1126
+ self.location, self.lookup = (location, lookup)
1127
+
1128
+ def build(self, builder):
1129
+ """Calls the builder object's ``add_lookup_call`` callback."""
1130
+ builder.add_lookup_call(self.lookup.name)
1131
+
1132
+ def asFea(self, indent=""):
1133
+ return "lookup {};".format(self.lookup.name)
1134
+
1135
+
1136
+ class MarkBasePosStatement(Statement):
1137
+ """A mark-to-base positioning rule. The ``base`` should be a
1138
+ `glyph-containing object`_. The ``marks`` should be a list of
1139
+ (:class:`Anchor`, :class:`MarkClass`) tuples."""
1140
+
1141
+ def __init__(self, base, marks, location=None):
1142
+ Statement.__init__(self, location)
1143
+ self.base, self.marks = base, marks
1144
+
1145
+ def build(self, builder):
1146
+ """Calls the builder object's ``add_mark_base_pos`` callback."""
1147
+ builder.add_mark_base_pos(self.location, self.base.glyphSet(), self.marks)
1148
+
1149
+ def asFea(self, indent=""):
1150
+ res = "pos base {}".format(self.base.asFea())
1151
+ for a, m in self.marks:
1152
+ res += "\n" + indent + SHIFT + "{} mark @{}".format(a.asFea(), m.name)
1153
+ res += ";"
1154
+ return res
1155
+
1156
+
1157
+ class MarkLigPosStatement(Statement):
1158
+ """A mark-to-ligature positioning rule. The ``ligatures`` must be a
1159
+ `glyph-containing object`_. The ``marks`` should be a list of lists: each
1160
+ element in the top-level list represents a component glyph, and is made
1161
+ up of a list of (:class:`Anchor`, :class:`MarkClass`) tuples representing
1162
+ mark attachment points for that position.
1163
+
1164
+ Example::
1165
+
1166
+ m1 = MarkClass("TOP_MARKS")
1167
+ m2 = MarkClass("BOTTOM_MARKS")
1168
+ # ... add definitions to mark classes...
1169
+
1170
+ glyph = GlyphName("lam_meem_jeem")
1171
+ marks = [
1172
+ [ (Anchor(625,1800), m1) ], # Attachments on 1st component (lam)
1173
+ [ (Anchor(376,-378), m2) ], # Attachments on 2nd component (meem)
1174
+ [ ] # No attachments on the jeem
1175
+ ]
1176
+ mlp = MarkLigPosStatement(glyph, marks)
1177
+
1178
+ mlp.asFea()
1179
+ # pos ligature lam_meem_jeem <anchor 625 1800> mark @TOP_MARKS
1180
+ # ligComponent <anchor 376 -378> mark @BOTTOM_MARKS;
1181
+
1182
+ """
1183
+
1184
+ def __init__(self, ligatures, marks, location=None):
1185
+ Statement.__init__(self, location)
1186
+ self.ligatures, self.marks = ligatures, marks
1187
+
1188
+ def build(self, builder):
1189
+ """Calls the builder object's ``add_mark_lig_pos`` callback."""
1190
+ builder.add_mark_lig_pos(self.location, self.ligatures.glyphSet(), self.marks)
1191
+
1192
+ def asFea(self, indent=""):
1193
+ res = "pos ligature {}".format(self.ligatures.asFea())
1194
+ ligs = []
1195
+ for l in self.marks:
1196
+ temp = ""
1197
+ if l is None or not len(l):
1198
+ temp = "\n" + indent + SHIFT * 2 + "<anchor NULL>"
1199
+ else:
1200
+ for a, m in l:
1201
+ temp += (
1202
+ "\n"
1203
+ + indent
1204
+ + SHIFT * 2
1205
+ + "{} mark @{}".format(a.asFea(), m.name)
1206
+ )
1207
+ ligs.append(temp)
1208
+ res += ("\n" + indent + SHIFT + "ligComponent").join(ligs)
1209
+ res += ";"
1210
+ return res
1211
+
1212
+
1213
+ class MarkMarkPosStatement(Statement):
1214
+ """A mark-to-mark positioning rule. The ``baseMarks`` must be a
1215
+ `glyph-containing object`_. The ``marks`` should be a list of
1216
+ (:class:`Anchor`, :class:`MarkClass`) tuples."""
1217
+
1218
+ def __init__(self, baseMarks, marks, location=None):
1219
+ Statement.__init__(self, location)
1220
+ self.baseMarks, self.marks = baseMarks, marks
1221
+
1222
+ def build(self, builder):
1223
+ """Calls the builder object's ``add_mark_mark_pos`` callback."""
1224
+ builder.add_mark_mark_pos(self.location, self.baseMarks.glyphSet(), self.marks)
1225
+
1226
+ def asFea(self, indent=""):
1227
+ res = "pos mark {}".format(self.baseMarks.asFea())
1228
+ for a, m in self.marks:
1229
+ res += "\n" + indent + SHIFT + "{} mark @{}".format(a.asFea(), m.name)
1230
+ res += ";"
1231
+ return res
1232
+
1233
+
1234
+ class MultipleSubstStatement(Statement):
1235
+ """A multiple substitution statement.
1236
+
1237
+ Args:
1238
+ prefix: a list of `glyph-containing objects`_.
1239
+ glyph: a single glyph-containing object.
1240
+ suffix: a list of glyph-containing objects.
1241
+ replacement: a list of glyph-containing objects.
1242
+ forceChain: If true, the statement is expressed as a chaining rule
1243
+ (e.g. ``sub f' i' by f_i``) even when no context is given.
1244
+ """
1245
+
1246
+ def __init__(
1247
+ self, prefix, glyph, suffix, replacement, forceChain=False, location=None
1248
+ ):
1249
+ Statement.__init__(self, location)
1250
+ self.prefix, self.glyph, self.suffix = prefix, glyph, suffix
1251
+ self.replacement = replacement
1252
+ self.forceChain = forceChain
1253
+
1254
+ def build(self, builder):
1255
+ """Calls the builder object's ``add_multiple_subst`` callback."""
1256
+ prefix = [p.glyphSet() for p in self.prefix]
1257
+ suffix = [s.glyphSet() for s in self.suffix]
1258
+ if hasattr(self.glyph, "glyphSet"):
1259
+ originals = self.glyph.glyphSet()
1260
+ else:
1261
+ originals = [self.glyph]
1262
+ count = len(originals)
1263
+ replaces = []
1264
+ for r in self.replacement:
1265
+ if hasattr(r, "glyphSet"):
1266
+ replace = r.glyphSet()
1267
+ else:
1268
+ replace = [r]
1269
+ if len(replace) == 1 and len(replace) != count:
1270
+ replace = replace * count
1271
+ replaces.append(replace)
1272
+ replaces = list(zip(*replaces))
1273
+
1274
+ seen_originals = set()
1275
+ for i, original in enumerate(originals):
1276
+ if original not in seen_originals:
1277
+ seen_originals.add(original)
1278
+ builder.add_multiple_subst(
1279
+ self.location,
1280
+ prefix,
1281
+ original,
1282
+ suffix,
1283
+ replaces and replaces[i] or (),
1284
+ self.forceChain,
1285
+ )
1286
+
1287
+ def asFea(self, indent=""):
1288
+ res = "sub "
1289
+ if len(self.prefix) or len(self.suffix) or self.forceChain:
1290
+ if len(self.prefix):
1291
+ res += " ".join(map(asFea, self.prefix)) + " "
1292
+ res += asFea(self.glyph) + "'"
1293
+ if len(self.suffix):
1294
+ res += " " + " ".join(map(asFea, self.suffix))
1295
+ else:
1296
+ res += asFea(self.glyph)
1297
+ replacement = self.replacement or [NullGlyph()]
1298
+ res += " by "
1299
+ res += " ".join(map(asFea, replacement))
1300
+ res += ";"
1301
+ return res
1302
+
1303
+
1304
+ class PairPosStatement(Statement):
1305
+ """A pair positioning statement.
1306
+
1307
+ ``glyphs1`` and ``glyphs2`` should be `glyph-containing objects`_.
1308
+ ``valuerecord1`` should be a :class:`ValueRecord` object;
1309
+ ``valuerecord2`` should be either a :class:`ValueRecord` object or ``None``.
1310
+ If ``enumerated`` is true, then this is expressed as an
1311
+ `enumerated pair <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#6.b.ii>`_.
1312
+ """
1313
+
1314
+ def __init__(
1315
+ self,
1316
+ glyphs1,
1317
+ valuerecord1,
1318
+ glyphs2,
1319
+ valuerecord2,
1320
+ enumerated=False,
1321
+ location=None,
1322
+ ):
1323
+ Statement.__init__(self, location)
1324
+ self.enumerated = enumerated
1325
+ self.glyphs1, self.valuerecord1 = glyphs1, valuerecord1
1326
+ self.glyphs2, self.valuerecord2 = glyphs2, valuerecord2
1327
+
1328
+ def build(self, builder):
1329
+ """Calls a callback on the builder object:
1330
+
1331
+ * If the rule is enumerated, calls ``add_specific_pair_pos`` on each
1332
+ combination of first and second glyphs.
1333
+ * If the glyphs are both single :class:`GlyphName` objects, calls
1334
+ ``add_specific_pair_pos``.
1335
+ * Else, calls ``add_class_pair_pos``.
1336
+ """
1337
+ if self.enumerated:
1338
+ g = [self.glyphs1.glyphSet(), self.glyphs2.glyphSet()]
1339
+ seen_pair = False
1340
+ for glyph1, glyph2 in itertools.product(*g):
1341
+ seen_pair = True
1342
+ builder.add_specific_pair_pos(
1343
+ self.location, glyph1, self.valuerecord1, glyph2, self.valuerecord2
1344
+ )
1345
+ if not seen_pair:
1346
+ raise FeatureLibError(
1347
+ "Empty glyph class in positioning rule", self.location
1348
+ )
1349
+ return
1350
+
1351
+ is_specific = isinstance(self.glyphs1, GlyphName) and isinstance(
1352
+ self.glyphs2, GlyphName
1353
+ )
1354
+ if is_specific:
1355
+ builder.add_specific_pair_pos(
1356
+ self.location,
1357
+ self.glyphs1.glyph,
1358
+ self.valuerecord1,
1359
+ self.glyphs2.glyph,
1360
+ self.valuerecord2,
1361
+ )
1362
+ else:
1363
+ builder.add_class_pair_pos(
1364
+ self.location,
1365
+ self.glyphs1.glyphSet(),
1366
+ self.valuerecord1,
1367
+ self.glyphs2.glyphSet(),
1368
+ self.valuerecord2,
1369
+ )
1370
+
1371
+ def asFea(self, indent=""):
1372
+ res = "enum " if self.enumerated else ""
1373
+ if self.valuerecord2:
1374
+ res += "pos {} {} {} {};".format(
1375
+ self.glyphs1.asFea(),
1376
+ self.valuerecord1.asFea(),
1377
+ self.glyphs2.asFea(),
1378
+ self.valuerecord2.asFea(),
1379
+ )
1380
+ else:
1381
+ res += "pos {} {} {};".format(
1382
+ self.glyphs1.asFea(), self.glyphs2.asFea(), self.valuerecord1.asFea()
1383
+ )
1384
+ return res
1385
+
1386
+
1387
+ class ReverseChainSingleSubstStatement(Statement):
1388
+ """A reverse chaining substitution statement. You don't see those every day.
1389
+
1390
+ Note the unusual argument order: ``suffix`` comes `before` ``glyphs``.
1391
+ ``old_prefix``, ``old_suffix``, ``glyphs`` and ``replacements`` should be
1392
+ lists of `glyph-containing objects`_. ``glyphs`` and ``replacements`` should
1393
+ be one-item lists.
1394
+ """
1395
+
1396
+ def __init__(self, old_prefix, old_suffix, glyphs, replacements, location=None):
1397
+ Statement.__init__(self, location)
1398
+ self.old_prefix, self.old_suffix = old_prefix, old_suffix
1399
+ self.glyphs = glyphs
1400
+ self.replacements = replacements
1401
+
1402
+ def build(self, builder):
1403
+ prefix = [p.glyphSet() for p in self.old_prefix]
1404
+ suffix = [s.glyphSet() for s in self.old_suffix]
1405
+ originals = self.glyphs[0].glyphSet()
1406
+ replaces = self.replacements[0].glyphSet()
1407
+ if len(replaces) == 1:
1408
+ replaces = replaces * len(originals)
1409
+ builder.add_reverse_chain_single_subst(
1410
+ self.location, prefix, suffix, dict(zip(originals, replaces))
1411
+ )
1412
+
1413
+ def asFea(self, indent=""):
1414
+ res = "rsub "
1415
+ if len(self.old_prefix) or len(self.old_suffix):
1416
+ if len(self.old_prefix):
1417
+ res += " ".join(asFea(g) for g in self.old_prefix) + " "
1418
+ res += " ".join(asFea(g) + "'" for g in self.glyphs)
1419
+ if len(self.old_suffix):
1420
+ res += " " + " ".join(asFea(g) for g in self.old_suffix)
1421
+ else:
1422
+ res += " ".join(map(asFea, self.glyphs))
1423
+ res += " by {};".format(" ".join(asFea(g) for g in self.replacements))
1424
+ return res
1425
+
1426
+
1427
+ class SingleSubstStatement(Statement):
1428
+ """A single substitution statement.
1429
+
1430
+ Note the unusual argument order: ``prefix`` and suffix come `after`
1431
+ the replacement ``glyphs``. ``prefix``, ``suffix``, ``glyphs`` and
1432
+ ``replace`` should be lists of `glyph-containing objects`_. ``glyphs`` and
1433
+ ``replace`` should be one-item lists.
1434
+ """
1435
+
1436
+ def __init__(self, glyphs, replace, prefix, suffix, forceChain, location=None):
1437
+ Statement.__init__(self, location)
1438
+ self.prefix, self.suffix = prefix, suffix
1439
+ self.forceChain = forceChain
1440
+ self.glyphs = glyphs
1441
+ self.replacements = replace
1442
+
1443
+ def build(self, builder):
1444
+ """Calls the builder object's ``add_single_subst`` callback."""
1445
+ prefix = [p.glyphSet() for p in self.prefix]
1446
+ suffix = [s.glyphSet() for s in self.suffix]
1447
+ originals = self.glyphs[0].glyphSet()
1448
+ replaces = self.replacements[0].glyphSet()
1449
+ if len(replaces) == 1:
1450
+ replaces = replaces * len(originals)
1451
+ builder.add_single_subst(
1452
+ self.location,
1453
+ prefix,
1454
+ suffix,
1455
+ OrderedDict(zip(originals, replaces)),
1456
+ self.forceChain,
1457
+ )
1458
+
1459
+ def asFea(self, indent=""):
1460
+ res = "sub "
1461
+ if len(self.prefix) or len(self.suffix) or self.forceChain:
1462
+ if len(self.prefix):
1463
+ res += " ".join(asFea(g) for g in self.prefix) + " "
1464
+ res += " ".join(asFea(g) + "'" for g in self.glyphs)
1465
+ if len(self.suffix):
1466
+ res += " " + " ".join(asFea(g) for g in self.suffix)
1467
+ else:
1468
+ res += " ".join(asFea(g) for g in self.glyphs)
1469
+ res += " by {};".format(" ".join(asFea(g) for g in self.replacements))
1470
+ return res
1471
+
1472
+
1473
+ class ScriptStatement(Statement):
1474
+ """A ``script`` statement."""
1475
+
1476
+ def __init__(self, script, location=None):
1477
+ Statement.__init__(self, location)
1478
+ self.script = script #: the script code
1479
+
1480
+ def build(self, builder):
1481
+ """Calls the builder's ``set_script`` callback."""
1482
+ builder.set_script(self.location, self.script)
1483
+
1484
+ def asFea(self, indent=""):
1485
+ return "script {};".format(self.script.strip())
1486
+
1487
+
1488
+ class SinglePosStatement(Statement):
1489
+ """A single position statement. ``prefix`` and ``suffix`` should be
1490
+ lists of `glyph-containing objects`_.
1491
+
1492
+ ``pos`` should be a one-element list containing a (`glyph-containing object`_,
1493
+ :class:`ValueRecord`) tuple."""
1494
+
1495
+ def __init__(self, pos, prefix, suffix, forceChain, location=None):
1496
+ Statement.__init__(self, location)
1497
+ self.pos, self.prefix, self.suffix = pos, prefix, suffix
1498
+ self.forceChain = forceChain
1499
+
1500
+ def build(self, builder):
1501
+ """Calls the builder object's ``add_single_pos`` callback."""
1502
+ prefix = [p.glyphSet() for p in self.prefix]
1503
+ suffix = [s.glyphSet() for s in self.suffix]
1504
+ pos = [(g.glyphSet(), value) for g, value in self.pos]
1505
+ builder.add_single_pos(self.location, prefix, suffix, pos, self.forceChain)
1506
+
1507
+ def asFea(self, indent=""):
1508
+ res = "pos "
1509
+ if len(self.prefix) or len(self.suffix) or self.forceChain:
1510
+ if len(self.prefix):
1511
+ res += " ".join(map(asFea, self.prefix)) + " "
1512
+ res += " ".join(
1513
+ [
1514
+ asFea(x[0])
1515
+ + "'"
1516
+ + ((" " + x[1].asFea()) if x[1] is not None else "")
1517
+ for x in self.pos
1518
+ ]
1519
+ )
1520
+ if len(self.suffix):
1521
+ res += " " + " ".join(map(asFea, self.suffix))
1522
+ else:
1523
+ res += " ".join(
1524
+ [
1525
+ asFea(x[0]) + " " + (x[1].asFea() if x[1] is not None else "")
1526
+ for x in self.pos
1527
+ ]
1528
+ )
1529
+ res += ";"
1530
+ return res
1531
+
1532
+
1533
+ class SubtableStatement(Statement):
1534
+ """Represents a subtable break."""
1535
+
1536
+ def __init__(self, location=None):
1537
+ Statement.__init__(self, location)
1538
+
1539
+ def build(self, builder):
1540
+ """Calls the builder objects's ``add_subtable_break`` callback."""
1541
+ builder.add_subtable_break(self.location)
1542
+
1543
+ def asFea(self, indent=""):
1544
+ return "subtable;"
1545
+
1546
+
1547
+ class ValueRecord(Expression):
1548
+ """Represents a value record."""
1549
+
1550
+ def __init__(
1551
+ self,
1552
+ xPlacement=None,
1553
+ yPlacement=None,
1554
+ xAdvance=None,
1555
+ yAdvance=None,
1556
+ xPlaDevice=None,
1557
+ yPlaDevice=None,
1558
+ xAdvDevice=None,
1559
+ yAdvDevice=None,
1560
+ vertical=False,
1561
+ location=None,
1562
+ ):
1563
+ Expression.__init__(self, location)
1564
+ self.xPlacement, self.yPlacement = (xPlacement, yPlacement)
1565
+ self.xAdvance, self.yAdvance = (xAdvance, yAdvance)
1566
+ self.xPlaDevice, self.yPlaDevice = (xPlaDevice, yPlaDevice)
1567
+ self.xAdvDevice, self.yAdvDevice = (xAdvDevice, yAdvDevice)
1568
+ self.vertical = vertical
1569
+
1570
+ def __eq__(self, other):
1571
+ return (
1572
+ self.xPlacement == other.xPlacement
1573
+ and self.yPlacement == other.yPlacement
1574
+ and self.xAdvance == other.xAdvance
1575
+ and self.yAdvance == other.yAdvance
1576
+ and self.xPlaDevice == other.xPlaDevice
1577
+ and self.xAdvDevice == other.xAdvDevice
1578
+ )
1579
+
1580
+ def __ne__(self, other):
1581
+ return not self.__eq__(other)
1582
+
1583
+ def __hash__(self):
1584
+ return (
1585
+ hash(self.xPlacement)
1586
+ ^ hash(self.yPlacement)
1587
+ ^ hash(self.xAdvance)
1588
+ ^ hash(self.yAdvance)
1589
+ ^ hash(self.xPlaDevice)
1590
+ ^ hash(self.yPlaDevice)
1591
+ ^ hash(self.xAdvDevice)
1592
+ ^ hash(self.yAdvDevice)
1593
+ )
1594
+
1595
+ def asFea(self, indent=""):
1596
+ if not self:
1597
+ return "<NULL>"
1598
+
1599
+ x, y = self.xPlacement, self.yPlacement
1600
+ xAdvance, yAdvance = self.xAdvance, self.yAdvance
1601
+ xPlaDevice, yPlaDevice = self.xPlaDevice, self.yPlaDevice
1602
+ xAdvDevice, yAdvDevice = self.xAdvDevice, self.yAdvDevice
1603
+ vertical = self.vertical
1604
+
1605
+ # Try format A, if possible.
1606
+ if x is None and y is None:
1607
+ if xAdvance is None and vertical:
1608
+ return str(yAdvance)
1609
+ elif yAdvance is None and not vertical:
1610
+ return str(xAdvance)
1611
+
1612
+ # Make any remaining None value 0 to avoid generating invalid records.
1613
+ x = x or 0
1614
+ y = y or 0
1615
+ xAdvance = xAdvance or 0
1616
+ yAdvance = yAdvance or 0
1617
+
1618
+ # Try format B, if possible.
1619
+ if (
1620
+ xPlaDevice is None
1621
+ and yPlaDevice is None
1622
+ and xAdvDevice is None
1623
+ and yAdvDevice is None
1624
+ ):
1625
+ return "<%s %s %s %s>" % (x, y, xAdvance, yAdvance)
1626
+
1627
+ # Last resort is format C.
1628
+ return "<%s %s %s %s %s %s %s %s>" % (
1629
+ x,
1630
+ y,
1631
+ xAdvance,
1632
+ yAdvance,
1633
+ deviceToString(xPlaDevice),
1634
+ deviceToString(yPlaDevice),
1635
+ deviceToString(xAdvDevice),
1636
+ deviceToString(yAdvDevice),
1637
+ )
1638
+
1639
+ def __bool__(self):
1640
+ return any(
1641
+ getattr(self, v) is not None
1642
+ for v in [
1643
+ "xPlacement",
1644
+ "yPlacement",
1645
+ "xAdvance",
1646
+ "yAdvance",
1647
+ "xPlaDevice",
1648
+ "yPlaDevice",
1649
+ "xAdvDevice",
1650
+ "yAdvDevice",
1651
+ ]
1652
+ )
1653
+
1654
+ __nonzero__ = __bool__
1655
+
1656
+
1657
+ class ValueRecordDefinition(Statement):
1658
+ """Represents a named value record definition."""
1659
+
1660
+ def __init__(self, name, value, location=None):
1661
+ Statement.__init__(self, location)
1662
+ self.name = name #: Value record name as string
1663
+ self.value = value #: :class:`ValueRecord` object
1664
+
1665
+ def asFea(self, indent=""):
1666
+ return "valueRecordDef {} {};".format(self.value.asFea(), self.name)
1667
+
1668
+
1669
+ def simplify_name_attributes(pid, eid, lid):
1670
+ if pid == 3 and eid == 1 and lid == 1033:
1671
+ return ""
1672
+ elif pid == 1 and eid == 0 and lid == 0:
1673
+ return "1"
1674
+ else:
1675
+ return "{} {} {}".format(pid, eid, lid)
1676
+
1677
+
1678
+ class NameRecord(Statement):
1679
+ """Represents a name record. (`Section 9.e. <https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html#9.e>`_)"""
1680
+
1681
+ def __init__(self, nameID, platformID, platEncID, langID, string, location=None):
1682
+ Statement.__init__(self, location)
1683
+ self.nameID = nameID #: Name ID as integer (e.g. 9 for designer's name)
1684
+ self.platformID = platformID #: Platform ID as integer
1685
+ self.platEncID = platEncID #: Platform encoding ID as integer
1686
+ self.langID = langID #: Language ID as integer
1687
+ self.string = string #: Name record value
1688
+
1689
+ def build(self, builder):
1690
+ """Calls the builder object's ``add_name_record`` callback."""
1691
+ builder.add_name_record(
1692
+ self.location,
1693
+ self.nameID,
1694
+ self.platformID,
1695
+ self.platEncID,
1696
+ self.langID,
1697
+ self.string,
1698
+ )
1699
+
1700
+ def asFea(self, indent=""):
1701
+ def escape(c, escape_pattern):
1702
+ # Also escape U+0022 QUOTATION MARK and U+005C REVERSE SOLIDUS
1703
+ if c >= 0x20 and c <= 0x7E and c not in (0x22, 0x5C):
1704
+ return chr(c)
1705
+ else:
1706
+ return escape_pattern % c
1707
+
1708
+ encoding = getEncoding(self.platformID, self.platEncID, self.langID)
1709
+ if encoding is None:
1710
+ raise FeatureLibError("Unsupported encoding", self.location)
1711
+ s = tobytes(self.string, encoding=encoding)
1712
+ if encoding == "utf_16_be":
1713
+ escaped_string = "".join(
1714
+ [
1715
+ escape(byteord(s[i]) * 256 + byteord(s[i + 1]), r"\%04x")
1716
+ for i in range(0, len(s), 2)
1717
+ ]
1718
+ )
1719
+ else:
1720
+ escaped_string = "".join([escape(byteord(b), r"\%02x") for b in s])
1721
+ plat = simplify_name_attributes(self.platformID, self.platEncID, self.langID)
1722
+ if plat != "":
1723
+ plat += " "
1724
+ return 'nameid {} {}"{}";'.format(self.nameID, plat, escaped_string)
1725
+
1726
+
1727
+ class FeatureNameStatement(NameRecord):
1728
+ """Represents a ``sizemenuname`` or ``name`` statement."""
1729
+
1730
+ def build(self, builder):
1731
+ """Calls the builder object's ``add_featureName`` callback."""
1732
+ NameRecord.build(self, builder)
1733
+ builder.add_featureName(self.nameID)
1734
+
1735
+ def asFea(self, indent=""):
1736
+ if self.nameID == "size":
1737
+ tag = "sizemenuname"
1738
+ else:
1739
+ tag = "name"
1740
+ plat = simplify_name_attributes(self.platformID, self.platEncID, self.langID)
1741
+ if plat != "":
1742
+ plat += " "
1743
+ return '{} {}"{}";'.format(tag, plat, self.string)
1744
+
1745
+
1746
+ class STATNameStatement(NameRecord):
1747
+ """Represents a STAT table ``name`` statement."""
1748
+
1749
+ def asFea(self, indent=""):
1750
+ plat = simplify_name_attributes(self.platformID, self.platEncID, self.langID)
1751
+ if plat != "":
1752
+ plat += " "
1753
+ return 'name {}"{}";'.format(plat, self.string)
1754
+
1755
+
1756
+ class SizeParameters(Statement):
1757
+ """A ``parameters`` statement."""
1758
+
1759
+ def __init__(self, DesignSize, SubfamilyID, RangeStart, RangeEnd, location=None):
1760
+ Statement.__init__(self, location)
1761
+ self.DesignSize = DesignSize
1762
+ self.SubfamilyID = SubfamilyID
1763
+ self.RangeStart = RangeStart
1764
+ self.RangeEnd = RangeEnd
1765
+
1766
+ def build(self, builder):
1767
+ """Calls the builder object's ``set_size_parameters`` callback."""
1768
+ builder.set_size_parameters(
1769
+ self.location,
1770
+ self.DesignSize,
1771
+ self.SubfamilyID,
1772
+ self.RangeStart,
1773
+ self.RangeEnd,
1774
+ )
1775
+
1776
+ def asFea(self, indent=""):
1777
+ res = "parameters {:.1f} {}".format(self.DesignSize, self.SubfamilyID)
1778
+ if self.RangeStart != 0 or self.RangeEnd != 0:
1779
+ res += " {} {}".format(int(self.RangeStart * 10), int(self.RangeEnd * 10))
1780
+ return res + ";"
1781
+
1782
+
1783
+ class CVParametersNameStatement(NameRecord):
1784
+ """Represent a name statement inside a ``cvParameters`` block."""
1785
+
1786
+ def __init__(
1787
+ self, nameID, platformID, platEncID, langID, string, block_name, location=None
1788
+ ):
1789
+ NameRecord.__init__(
1790
+ self, nameID, platformID, platEncID, langID, string, location=location
1791
+ )
1792
+ self.block_name = block_name
1793
+
1794
+ def build(self, builder):
1795
+ """Calls the builder object's ``add_cv_parameter`` callback."""
1796
+ item = ""
1797
+ if self.block_name == "ParamUILabelNameID":
1798
+ item = "_{}".format(builder.cv_num_named_params_.get(self.nameID, 0))
1799
+ builder.add_cv_parameter(self.nameID)
1800
+ self.nameID = (self.nameID, self.block_name + item)
1801
+ NameRecord.build(self, builder)
1802
+
1803
+ def asFea(self, indent=""):
1804
+ plat = simplify_name_attributes(self.platformID, self.platEncID, self.langID)
1805
+ if plat != "":
1806
+ plat += " "
1807
+ return 'name {}"{}";'.format(plat, self.string)
1808
+
1809
+
1810
+ class CharacterStatement(Statement):
1811
+ """
1812
+ Statement used in cvParameters blocks of Character Variant features (cvXX).
1813
+ The Unicode value may be written with either decimal or hexadecimal
1814
+ notation. The value must be preceded by '0x' if it is a hexadecimal value.
1815
+ The largest Unicode value allowed is 0xFFFFFF.
1816
+ """
1817
+
1818
+ def __init__(self, character, tag, location=None):
1819
+ Statement.__init__(self, location)
1820
+ self.character = character
1821
+ self.tag = tag
1822
+
1823
+ def build(self, builder):
1824
+ """Calls the builder object's ``add_cv_character`` callback."""
1825
+ builder.add_cv_character(self.character, self.tag)
1826
+
1827
+ def asFea(self, indent=""):
1828
+ return "Character {:#x};".format(self.character)
1829
+
1830
+
1831
+ class BaseAxis(Statement):
1832
+ """An axis definition, being either a ``VertAxis.BaseTagList/BaseScriptList``
1833
+ pair or a ``HorizAxis.BaseTagList/BaseScriptList`` pair."""
1834
+
1835
+ def __init__(self, bases, scripts, vertical, minmax=None, location=None):
1836
+ Statement.__init__(self, location)
1837
+ self.bases = bases #: A list of baseline tag names as strings
1838
+ self.scripts = scripts #: A list of script record tuplets (script tag, default baseline tag, base coordinate)
1839
+ self.vertical = vertical #: Boolean; VertAxis if True, HorizAxis if False
1840
+ self.minmax = [] #: A set of minmax record
1841
+
1842
+ def build(self, builder):
1843
+ """Calls the builder object's ``set_base_axis`` callback."""
1844
+ builder.set_base_axis(self.bases, self.scripts, self.vertical, self.minmax)
1845
+
1846
+ def asFea(self, indent=""):
1847
+ direction = "Vert" if self.vertical else "Horiz"
1848
+ scripts = [
1849
+ "{} {} {}".format(a[0], a[1], " ".join(map(str, a[2])))
1850
+ for a in self.scripts
1851
+ ]
1852
+ minmaxes = [
1853
+ "\n{}Axis.MinMax {} {} {}, {};".format(direction, a[0], a[1], a[2], a[3])
1854
+ for a in self.minmax
1855
+ ]
1856
+ return "{}Axis.BaseTagList {};\n{}{}Axis.BaseScriptList {};".format(
1857
+ direction, " ".join(self.bases), indent, direction, ", ".join(scripts)
1858
+ ) + "\n".join(minmaxes)
1859
+
1860
+
1861
+ class OS2Field(Statement):
1862
+ """An entry in the ``OS/2`` table. Most ``values`` should be numbers or
1863
+ strings, apart from when the key is ``UnicodeRange``, ``CodePageRange``
1864
+ or ``Panose``, in which case it should be an array of integers."""
1865
+
1866
+ def __init__(self, key, value, location=None):
1867
+ Statement.__init__(self, location)
1868
+ self.key = key
1869
+ self.value = value
1870
+
1871
+ def build(self, builder):
1872
+ """Calls the builder object's ``add_os2_field`` callback."""
1873
+ builder.add_os2_field(self.key, self.value)
1874
+
1875
+ def asFea(self, indent=""):
1876
+ def intarr2str(x):
1877
+ return " ".join(map(str, x))
1878
+
1879
+ numbers = (
1880
+ "FSType",
1881
+ "TypoAscender",
1882
+ "TypoDescender",
1883
+ "TypoLineGap",
1884
+ "winAscent",
1885
+ "winDescent",
1886
+ "XHeight",
1887
+ "CapHeight",
1888
+ "WeightClass",
1889
+ "WidthClass",
1890
+ "LowerOpSize",
1891
+ "UpperOpSize",
1892
+ )
1893
+ ranges = ("UnicodeRange", "CodePageRange")
1894
+ keywords = dict([(x.lower(), [x, str]) for x in numbers])
1895
+ keywords.update([(x.lower(), [x, intarr2str]) for x in ranges])
1896
+ keywords["panose"] = ["Panose", intarr2str]
1897
+ keywords["vendor"] = ["Vendor", lambda y: '"{}"'.format(y)]
1898
+ if self.key in keywords:
1899
+ return "{} {};".format(
1900
+ keywords[self.key][0], keywords[self.key][1](self.value)
1901
+ )
1902
+ return "" # should raise exception
1903
+
1904
+
1905
+ class HheaField(Statement):
1906
+ """An entry in the ``hhea`` table."""
1907
+
1908
+ def __init__(self, key, value, location=None):
1909
+ Statement.__init__(self, location)
1910
+ self.key = key
1911
+ self.value = value
1912
+
1913
+ def build(self, builder):
1914
+ """Calls the builder object's ``add_hhea_field`` callback."""
1915
+ builder.add_hhea_field(self.key, self.value)
1916
+
1917
+ def asFea(self, indent=""):
1918
+ fields = ("CaretOffset", "Ascender", "Descender", "LineGap")
1919
+ keywords = dict([(x.lower(), x) for x in fields])
1920
+ return "{} {};".format(keywords[self.key], self.value)
1921
+
1922
+
1923
+ class VheaField(Statement):
1924
+ """An entry in the ``vhea`` table."""
1925
+
1926
+ def __init__(self, key, value, location=None):
1927
+ Statement.__init__(self, location)
1928
+ self.key = key
1929
+ self.value = value
1930
+
1931
+ def build(self, builder):
1932
+ """Calls the builder object's ``add_vhea_field`` callback."""
1933
+ builder.add_vhea_field(self.key, self.value)
1934
+
1935
+ def asFea(self, indent=""):
1936
+ fields = ("VertTypoAscender", "VertTypoDescender", "VertTypoLineGap")
1937
+ keywords = dict([(x.lower(), x) for x in fields])
1938
+ return "{} {};".format(keywords[self.key], self.value)
1939
+
1940
+
1941
+ class STATDesignAxisStatement(Statement):
1942
+ """A STAT table Design Axis
1943
+
1944
+ Args:
1945
+ tag (str): a 4 letter axis tag
1946
+ axisOrder (int): an int
1947
+ names (list): a list of :class:`STATNameStatement` objects
1948
+ """
1949
+
1950
+ def __init__(self, tag, axisOrder, names, location=None):
1951
+ Statement.__init__(self, location)
1952
+ self.tag = tag
1953
+ self.axisOrder = axisOrder
1954
+ self.names = names
1955
+ self.location = location
1956
+
1957
+ def build(self, builder):
1958
+ builder.addDesignAxis(self, self.location)
1959
+
1960
+ def asFea(self, indent=""):
1961
+ indent += SHIFT
1962
+ res = f"DesignAxis {self.tag} {self.axisOrder} {{ \n"
1963
+ res += ("\n" + indent).join([s.asFea(indent=indent) for s in self.names]) + "\n"
1964
+ res += "};"
1965
+ return res
1966
+
1967
+
1968
+ class ElidedFallbackName(Statement):
1969
+ """STAT table ElidedFallbackName
1970
+
1971
+ Args:
1972
+ names: a list of :class:`STATNameStatement` objects
1973
+ """
1974
+
1975
+ def __init__(self, names, location=None):
1976
+ Statement.__init__(self, location)
1977
+ self.names = names
1978
+ self.location = location
1979
+
1980
+ def build(self, builder):
1981
+ builder.setElidedFallbackName(self.names, self.location)
1982
+
1983
+ def asFea(self, indent=""):
1984
+ indent += SHIFT
1985
+ res = "ElidedFallbackName { \n"
1986
+ res += ("\n" + indent).join([s.asFea(indent=indent) for s in self.names]) + "\n"
1987
+ res += "};"
1988
+ return res
1989
+
1990
+
1991
+ class ElidedFallbackNameID(Statement):
1992
+ """STAT table ElidedFallbackNameID
1993
+
1994
+ Args:
1995
+ value: an int pointing to an existing name table name ID
1996
+ """
1997
+
1998
+ def __init__(self, value, location=None):
1999
+ Statement.__init__(self, location)
2000
+ self.value = value
2001
+ self.location = location
2002
+
2003
+ def build(self, builder):
2004
+ builder.setElidedFallbackName(self.value, self.location)
2005
+
2006
+ def asFea(self, indent=""):
2007
+ return f"ElidedFallbackNameID {self.value};"
2008
+
2009
+
2010
+ class STATAxisValueStatement(Statement):
2011
+ """A STAT table Axis Value Record
2012
+
2013
+ Args:
2014
+ names (list): a list of :class:`STATNameStatement` objects
2015
+ locations (list): a list of :class:`AxisValueLocationStatement` objects
2016
+ flags (int): an int
2017
+ """
2018
+
2019
+ def __init__(self, names, locations, flags, location=None):
2020
+ Statement.__init__(self, location)
2021
+ self.names = names
2022
+ self.locations = locations
2023
+ self.flags = flags
2024
+
2025
+ def build(self, builder):
2026
+ builder.addAxisValueRecord(self, self.location)
2027
+
2028
+ def asFea(self, indent=""):
2029
+ res = "AxisValue {\n"
2030
+ for location in self.locations:
2031
+ res += location.asFea()
2032
+
2033
+ for nameRecord in self.names:
2034
+ res += nameRecord.asFea()
2035
+ res += "\n"
2036
+
2037
+ if self.flags:
2038
+ flags = ["OlderSiblingFontAttribute", "ElidableAxisValueName"]
2039
+ flagStrings = []
2040
+ curr = 1
2041
+ for i in range(len(flags)):
2042
+ if self.flags & curr != 0:
2043
+ flagStrings.append(flags[i])
2044
+ curr = curr << 1
2045
+ res += f"flag {' '.join(flagStrings)};\n"
2046
+ res += "};"
2047
+ return res
2048
+
2049
+
2050
+ class AxisValueLocationStatement(Statement):
2051
+ """
2052
+ A STAT table Axis Value Location
2053
+
2054
+ Args:
2055
+ tag (str): a 4 letter axis tag
2056
+ values (list): a list of ints and/or floats
2057
+ """
2058
+
2059
+ def __init__(self, tag, values, location=None):
2060
+ Statement.__init__(self, location)
2061
+ self.tag = tag
2062
+ self.values = values
2063
+
2064
+ def asFea(self, res=""):
2065
+ res += f"location {self.tag} "
2066
+ res += f"{' '.join(str(i) for i in self.values)};\n"
2067
+ return res
2068
+
2069
+
2070
+ class ConditionsetStatement(Statement):
2071
+ """
2072
+ A variable layout conditionset
2073
+
2074
+ Args:
2075
+ name (str): the name of this conditionset
2076
+ conditions (dict): a dictionary mapping axis tags to a
2077
+ tuple of (min,max) userspace coordinates.
2078
+ """
2079
+
2080
+ def __init__(self, name, conditions, location=None):
2081
+ Statement.__init__(self, location)
2082
+ self.name = name
2083
+ self.conditions = conditions
2084
+
2085
+ def build(self, builder):
2086
+ builder.add_conditionset(self.location, self.name, self.conditions)
2087
+
2088
+ def asFea(self, res="", indent=""):
2089
+ res += indent + f"conditionset {self.name} " + "{\n"
2090
+ for tag, (minvalue, maxvalue) in self.conditions.items():
2091
+ res += indent + SHIFT + f"{tag} {minvalue} {maxvalue};\n"
2092
+ res += indent + "}" + f" {self.name};\n"
2093
+ return res
2094
+
2095
+
2096
+ class VariationBlock(Block):
2097
+ """A variation feature block, applicable in a given set of conditions."""
2098
+
2099
+ def __init__(self, name, conditionset, use_extension=False, location=None):
2100
+ Block.__init__(self, location)
2101
+ self.name, self.conditionset, self.use_extension = (
2102
+ name,
2103
+ conditionset,
2104
+ use_extension,
2105
+ )
2106
+
2107
+ def build(self, builder):
2108
+ """Call the ``start_feature`` callback on the builder object, visit
2109
+ all the statements in this feature, and then call ``end_feature``."""
2110
+ builder.start_feature(self.location, self.name, self.use_extension)
2111
+ if (
2112
+ self.conditionset != "NULL"
2113
+ and self.conditionset not in builder.conditionsets_
2114
+ ):
2115
+ raise FeatureLibError(
2116
+ f"variation block used undefined conditionset {self.conditionset}",
2117
+ self.location,
2118
+ )
2119
+
2120
+ # language exclude_dflt statements modify builder.features_
2121
+ # limit them to this block with temporary builder.features_
2122
+ features = builder.features_
2123
+ builder.features_ = {}
2124
+ Block.build(self, builder)
2125
+ for key, value in builder.features_.items():
2126
+ items = builder.feature_variations_.setdefault(key, {}).setdefault(
2127
+ self.conditionset, []
2128
+ )
2129
+ items.extend(value)
2130
+ if key not in features:
2131
+ features[key] = [] # Ensure we make a feature record
2132
+ builder.features_ = features
2133
+ builder.end_feature()
2134
+
2135
+ def asFea(self, indent=""):
2136
+ res = indent + "variation %s " % self.name.strip()
2137
+ res += self.conditionset + " "
2138
+ if self.use_extension:
2139
+ res += "useExtension "
2140
+ res += "{\n"
2141
+ res += Block.asFea(self, indent=indent)
2142
+ res += indent + "} %s;\n" % self.name.strip()
2143
+ return res
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/builder.py ADDED
@@ -0,0 +1,1808 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.misc import sstruct
2
+ from fontTools.misc.textTools import Tag, tostr, binary2num, safeEval
3
+ from fontTools.feaLib.error import FeatureLibError
4
+ from fontTools.feaLib.lookupDebugInfo import (
5
+ LookupDebugInfo,
6
+ LOOKUP_DEBUG_INFO_KEY,
7
+ LOOKUP_DEBUG_ENV_VAR,
8
+ )
9
+ from fontTools.feaLib.parser import Parser
10
+ from fontTools.feaLib.ast import FeatureFile
11
+ from fontTools.feaLib.variableScalar import VariableScalar
12
+ from fontTools.otlLib import builder as otl
13
+ from fontTools.otlLib.maxContextCalc import maxCtxFont
14
+ from fontTools.ttLib import newTable, getTableModule
15
+ from fontTools.ttLib.tables import otBase, otTables
16
+ from fontTools.otlLib.builder import (
17
+ AlternateSubstBuilder,
18
+ ChainContextPosBuilder,
19
+ ChainContextSubstBuilder,
20
+ LigatureSubstBuilder,
21
+ MultipleSubstBuilder,
22
+ CursivePosBuilder,
23
+ MarkBasePosBuilder,
24
+ MarkLigPosBuilder,
25
+ MarkMarkPosBuilder,
26
+ ReverseChainSingleSubstBuilder,
27
+ SingleSubstBuilder,
28
+ ClassPairPosSubtableBuilder,
29
+ PairPosBuilder,
30
+ SinglePosBuilder,
31
+ ChainContextualRule,
32
+ AnySubstBuilder,
33
+ )
34
+ from fontTools.otlLib.error import OpenTypeLibError
35
+ from fontTools.varLib.errors import VarLibError
36
+ from fontTools.varLib.varStore import OnlineVarStoreBuilder
37
+ from fontTools.varLib.builder import buildVarDevTable
38
+ from fontTools.varLib.featureVars import addFeatureVariationsRaw
39
+ from fontTools.varLib.models import normalizeValue, piecewiseLinearMap
40
+ from collections import defaultdict
41
+ import copy
42
+ import itertools
43
+ from io import StringIO
44
+ import logging
45
+ import warnings
46
+ import os
47
+
48
+
49
+ log = logging.getLogger(__name__)
50
+
51
+
52
+ def addOpenTypeFeatures(font, featurefile, tables=None, debug=False):
53
+ """Add features from a file to a font. Note that this replaces any features
54
+ currently present.
55
+
56
+ Args:
57
+ font (feaLib.ttLib.TTFont): The font object.
58
+ featurefile: Either a path or file object (in which case we
59
+ parse it into an AST), or a pre-parsed AST instance.
60
+ tables: If passed, restrict the set of affected tables to those in the
61
+ list.
62
+ debug: Whether to add source debugging information to the font in the
63
+ ``Debg`` table
64
+
65
+ """
66
+ builder = Builder(font, featurefile)
67
+ builder.build(tables=tables, debug=debug)
68
+
69
+
70
+ def addOpenTypeFeaturesFromString(
71
+ font, features, filename=None, tables=None, debug=False
72
+ ):
73
+ """Add features from a string to a font. Note that this replaces any
74
+ features currently present.
75
+
76
+ Args:
77
+ font (feaLib.ttLib.TTFont): The font object.
78
+ features: A string containing feature code.
79
+ filename: The directory containing ``filename`` is used as the root of
80
+ relative ``include()`` paths; if ``None`` is provided, the current
81
+ directory is assumed.
82
+ tables: If passed, restrict the set of affected tables to those in the
83
+ list.
84
+ debug: Whether to add source debugging information to the font in the
85
+ ``Debg`` table
86
+
87
+ """
88
+
89
+ featurefile = StringIO(tostr(features))
90
+ if filename:
91
+ featurefile.name = filename
92
+ addOpenTypeFeatures(font, featurefile, tables=tables, debug=debug)
93
+
94
+
95
+ class Builder(object):
96
+ supportedTables = frozenset(
97
+ Tag(tag)
98
+ for tag in [
99
+ "BASE",
100
+ "GDEF",
101
+ "GPOS",
102
+ "GSUB",
103
+ "OS/2",
104
+ "head",
105
+ "hhea",
106
+ "name",
107
+ "vhea",
108
+ "STAT",
109
+ ]
110
+ )
111
+
112
+ def __init__(self, font, featurefile):
113
+ self.font = font
114
+ # 'featurefile' can be either a path or file object (in which case we
115
+ # parse it into an AST), or a pre-parsed AST instance
116
+ if isinstance(featurefile, FeatureFile):
117
+ self.parseTree, self.file = featurefile, None
118
+ else:
119
+ self.parseTree, self.file = None, featurefile
120
+ self.glyphMap = font.getReverseGlyphMap()
121
+ self.varstorebuilder = None
122
+ if "fvar" in font:
123
+ self.axes = font["fvar"].axes
124
+ self.varstorebuilder = OnlineVarStoreBuilder(
125
+ [ax.axisTag for ax in self.axes]
126
+ )
127
+ self.default_language_systems_ = set()
128
+ self.script_ = None
129
+ self.lookupflag_ = 0
130
+ self.lookupflag_markFilterSet_ = None
131
+ self.use_extension_ = False
132
+ self.language_systems = set()
133
+ self.seen_non_DFLT_script_ = False
134
+ self.named_lookups_ = {}
135
+ self.cur_lookup_ = None
136
+ self.cur_lookup_name_ = None
137
+ self.cur_feature_name_ = None
138
+ self.lookups_ = []
139
+ self.lookup_locations = {"GSUB": {}, "GPOS": {}}
140
+ self.features_ = {} # ('latn', 'DEU ', 'smcp') --> [LookupBuilder*]
141
+ self.required_features_ = {} # ('latn', 'DEU ') --> 'scmp'
142
+ self.feature_variations_ = {}
143
+ # for feature 'aalt'
144
+ self.aalt_features_ = [] # [(location, featureName)*], for 'aalt'
145
+ self.aalt_location_ = None
146
+ self.aalt_alternates_ = {}
147
+ self.aalt_use_extension_ = False
148
+ # for 'featureNames'
149
+ self.featureNames_ = set()
150
+ self.featureNames_ids_ = {}
151
+ # for 'cvParameters'
152
+ self.cv_parameters_ = set()
153
+ self.cv_parameters_ids_ = {}
154
+ self.cv_num_named_params_ = {}
155
+ self.cv_characters_ = defaultdict(list)
156
+ # for feature 'size'
157
+ self.size_parameters_ = None
158
+ # for table 'head'
159
+ self.fontRevision_ = None # 2.71
160
+ # for table 'name'
161
+ self.names_ = []
162
+ # for table 'BASE'
163
+ self.base_horiz_axis_ = None
164
+ self.base_vert_axis_ = None
165
+ # for table 'GDEF'
166
+ self.attachPoints_ = {} # "a" --> {3, 7}
167
+ self.ligCaretCoords_ = {} # "f_f_i" --> {300, 600}
168
+ self.ligCaretPoints_ = {} # "f_f_i" --> {3, 7}
169
+ self.glyphClassDefs_ = {} # "fi" --> (2, (file, line, column))
170
+ self.markAttach_ = {} # "acute" --> (4, (file, line, column))
171
+ self.markAttachClassID_ = {} # frozenset({"acute", "grave"}) --> 4
172
+ self.markFilterSets_ = {} # frozenset({"acute", "grave"}) --> 4
173
+ # for table 'OS/2'
174
+ self.os2_ = {}
175
+ # for table 'hhea'
176
+ self.hhea_ = {}
177
+ # for table 'vhea'
178
+ self.vhea_ = {}
179
+ # for table 'STAT'
180
+ self.stat_ = {}
181
+ # for conditionsets
182
+ self.conditionsets_ = {}
183
+ # We will often use exactly the same locations (i.e. the font's masters)
184
+ # for a large number of variable scalars. Instead of creating a model
185
+ # for each, let's share the models.
186
+ self.model_cache = {}
187
+
188
+ def build(self, tables=None, debug=False):
189
+ if self.parseTree is None:
190
+ self.parseTree = Parser(self.file, self.glyphMap).parse()
191
+ self.parseTree.build(self)
192
+ # by default, build all the supported tables
193
+ if tables is None:
194
+ tables = self.supportedTables
195
+ else:
196
+ tables = frozenset(tables)
197
+ unsupported = tables - self.supportedTables
198
+ if unsupported:
199
+ unsupported_string = ", ".join(sorted(unsupported))
200
+ raise NotImplementedError(
201
+ "The following tables were requested but are unsupported: "
202
+ f"{unsupported_string}."
203
+ )
204
+ if "GSUB" in tables:
205
+ self.build_feature_aalt_()
206
+ if "head" in tables:
207
+ self.build_head()
208
+ if "hhea" in tables:
209
+ self.build_hhea()
210
+ if "vhea" in tables:
211
+ self.build_vhea()
212
+ if "name" in tables:
213
+ self.build_name()
214
+ if "OS/2" in tables:
215
+ self.build_OS_2()
216
+ if "STAT" in tables:
217
+ self.build_STAT()
218
+ for tag in ("GPOS", "GSUB"):
219
+ if tag not in tables:
220
+ continue
221
+ table = self.makeTable(tag)
222
+ if self.feature_variations_:
223
+ self.makeFeatureVariations(table, tag)
224
+ if (
225
+ table.ScriptList.ScriptCount > 0
226
+ or table.FeatureList.FeatureCount > 0
227
+ or table.LookupList.LookupCount > 0
228
+ ):
229
+ fontTable = self.font[tag] = newTable(tag)
230
+ fontTable.table = table
231
+ elif tag in self.font:
232
+ del self.font[tag]
233
+ if any(tag in self.font for tag in ("GPOS", "GSUB")) and "OS/2" in self.font:
234
+ self.font["OS/2"].usMaxContext = maxCtxFont(self.font)
235
+ if "GDEF" in tables:
236
+ gdef = self.buildGDEF()
237
+ if gdef:
238
+ self.font["GDEF"] = gdef
239
+ elif "GDEF" in self.font:
240
+ del self.font["GDEF"]
241
+ if "BASE" in tables:
242
+ base = self.buildBASE()
243
+ if base:
244
+ self.font["BASE"] = base
245
+ elif "BASE" in self.font:
246
+ del self.font["BASE"]
247
+ if debug or os.environ.get(LOOKUP_DEBUG_ENV_VAR):
248
+ self.buildDebg()
249
+
250
+ def get_chained_lookup_(self, location, builder_class):
251
+ result = builder_class(self.font, location)
252
+ result.lookupflag = self.lookupflag_
253
+ result.markFilterSet = self.lookupflag_markFilterSet_
254
+ result.extension = self.use_extension_
255
+ self.lookups_.append(result)
256
+ return result
257
+
258
+ def add_lookup_to_feature_(self, lookup, feature_name):
259
+ for script, lang in self.language_systems:
260
+ key = (script, lang, feature_name)
261
+ self.features_.setdefault(key, []).append(lookup)
262
+
263
+ def get_lookup_(self, location, builder_class, mapping=None):
264
+ if (
265
+ self.cur_lookup_
266
+ and type(self.cur_lookup_) == builder_class
267
+ and self.cur_lookup_.lookupflag == self.lookupflag_
268
+ and self.cur_lookup_.markFilterSet == self.lookupflag_markFilterSet_
269
+ and self.cur_lookup_.can_add_mapping(mapping)
270
+ ):
271
+ return self.cur_lookup_
272
+ if self.cur_lookup_name_ and self.cur_lookup_:
273
+ raise FeatureLibError(
274
+ "Within a named lookup block, all rules must be of "
275
+ "the same lookup type and flag",
276
+ location,
277
+ )
278
+ self.cur_lookup_ = builder_class(self.font, location)
279
+ self.cur_lookup_.lookupflag = self.lookupflag_
280
+ self.cur_lookup_.markFilterSet = self.lookupflag_markFilterSet_
281
+ self.cur_lookup_.extension = self.use_extension_
282
+ self.lookups_.append(self.cur_lookup_)
283
+ if self.cur_lookup_name_:
284
+ # We are starting a lookup rule inside a named lookup block.
285
+ self.named_lookups_[self.cur_lookup_name_] = self.cur_lookup_
286
+ if self.cur_feature_name_:
287
+ # We are starting a lookup rule inside a feature. This includes
288
+ # lookup rules inside named lookups inside features.
289
+ self.add_lookup_to_feature_(self.cur_lookup_, self.cur_feature_name_)
290
+ return self.cur_lookup_
291
+
292
+ def build_feature_aalt_(self):
293
+ if not self.aalt_features_ and not self.aalt_alternates_:
294
+ return
295
+ # > alternate glyphs will be sorted in the order that the source features
296
+ # > are named in the aalt definition, not the order of the feature definitions
297
+ # > in the file. Alternates defined explicitly ... will precede all others.
298
+ # https://github.com/fonttools/fonttools/issues/836
299
+ alternates = {g: list(a) for g, a in self.aalt_alternates_.items()}
300
+ for location, name in self.aalt_features_ + [(None, "aalt")]:
301
+ feature = [
302
+ (script, lang, feature, lookups)
303
+ for (script, lang, feature), lookups in self.features_.items()
304
+ if feature == name
305
+ ]
306
+ # "aalt" does not have to specify its own lookups, but it might.
307
+ if not feature and name != "aalt":
308
+ warnings.warn("%s: Feature %s has not been defined" % (location, name))
309
+ continue
310
+ for script, lang, feature, lookups in feature:
311
+ for lookuplist in lookups:
312
+ if not isinstance(lookuplist, list):
313
+ lookuplist = [lookuplist]
314
+ for lookup in lookuplist:
315
+ for glyph, alts in lookup.getAlternateGlyphs().items():
316
+ alts_for_glyph = alternates.setdefault(glyph, [])
317
+ alts_for_glyph.extend(
318
+ g for g in alts if g not in alts_for_glyph
319
+ )
320
+ single = {
321
+ glyph: repl[0] for glyph, repl in alternates.items() if len(repl) == 1
322
+ }
323
+ multi = {glyph: repl for glyph, repl in alternates.items() if len(repl) > 1}
324
+ if not single and not multi:
325
+ return
326
+ self.features_ = {
327
+ (script, lang, feature): lookups
328
+ for (script, lang, feature), lookups in self.features_.items()
329
+ if feature != "aalt"
330
+ }
331
+ old_lookups = self.lookups_
332
+ self.lookups_ = []
333
+ self.start_feature(self.aalt_location_, "aalt", self.aalt_use_extension_)
334
+ if single:
335
+ single_lookup = self.get_lookup_(location, SingleSubstBuilder)
336
+ single_lookup.mapping = single
337
+ if multi:
338
+ multi_lookup = self.get_lookup_(location, AlternateSubstBuilder)
339
+ multi_lookup.alternates = multi
340
+ self.end_feature()
341
+ self.lookups_.extend(old_lookups)
342
+
343
+ def build_head(self):
344
+ if not self.fontRevision_:
345
+ return
346
+ table = self.font.get("head")
347
+ if not table: # this only happens for unit tests
348
+ table = self.font["head"] = newTable("head")
349
+ table.decompile(b"\0" * 54, self.font)
350
+ table.tableVersion = 1.0
351
+ table.magicNumber = 0x5F0F3CF5
352
+ table.created = table.modified = 3406620153 # 2011-12-13 11:22:33
353
+ table.fontRevision = self.fontRevision_
354
+
355
+ def build_hhea(self):
356
+ if not self.hhea_:
357
+ return
358
+ table = self.font.get("hhea")
359
+ if not table: # this only happens for unit tests
360
+ table = self.font["hhea"] = newTable("hhea")
361
+ table.decompile(b"\0" * 36, self.font)
362
+ table.tableVersion = 0x00010000
363
+ if "caretoffset" in self.hhea_:
364
+ table.caretOffset = self.hhea_["caretoffset"]
365
+ if "ascender" in self.hhea_:
366
+ table.ascent = self.hhea_["ascender"]
367
+ if "descender" in self.hhea_:
368
+ table.descent = self.hhea_["descender"]
369
+ if "linegap" in self.hhea_:
370
+ table.lineGap = self.hhea_["linegap"]
371
+
372
+ def build_vhea(self):
373
+ if not self.vhea_:
374
+ return
375
+ table = self.font.get("vhea")
376
+ if not table: # this only happens for unit tests
377
+ table = self.font["vhea"] = newTable("vhea")
378
+ table.decompile(b"\0" * 36, self.font)
379
+ table.tableVersion = 0x00011000
380
+ if "verttypoascender" in self.vhea_:
381
+ table.ascent = self.vhea_["verttypoascender"]
382
+ if "verttypodescender" in self.vhea_:
383
+ table.descent = self.vhea_["verttypodescender"]
384
+ if "verttypolinegap" in self.vhea_:
385
+ table.lineGap = self.vhea_["verttypolinegap"]
386
+
387
+ def get_user_name_id(self, table):
388
+ # Try to find first unused font-specific name id
389
+ nameIDs = [name.nameID for name in table.names]
390
+ for user_name_id in range(256, 32767):
391
+ if user_name_id not in nameIDs:
392
+ return user_name_id
393
+
394
+ def buildFeatureParams(self, tag):
395
+ params = None
396
+ if tag == "size":
397
+ params = otTables.FeatureParamsSize()
398
+ (
399
+ params.DesignSize,
400
+ params.SubfamilyID,
401
+ params.RangeStart,
402
+ params.RangeEnd,
403
+ ) = self.size_parameters_
404
+ if tag in self.featureNames_ids_:
405
+ params.SubfamilyNameID = self.featureNames_ids_[tag]
406
+ else:
407
+ params.SubfamilyNameID = 0
408
+ elif tag in self.featureNames_:
409
+ if not self.featureNames_ids_:
410
+ # name table wasn't selected among the tables to build; skip
411
+ pass
412
+ else:
413
+ assert tag in self.featureNames_ids_
414
+ params = otTables.FeatureParamsStylisticSet()
415
+ params.Version = 0
416
+ params.UINameID = self.featureNames_ids_[tag]
417
+ elif tag in self.cv_parameters_:
418
+ params = otTables.FeatureParamsCharacterVariants()
419
+ params.Format = 0
420
+ params.FeatUILabelNameID = self.cv_parameters_ids_.get(
421
+ (tag, "FeatUILabelNameID"), 0
422
+ )
423
+ params.FeatUITooltipTextNameID = self.cv_parameters_ids_.get(
424
+ (tag, "FeatUITooltipTextNameID"), 0
425
+ )
426
+ params.SampleTextNameID = self.cv_parameters_ids_.get(
427
+ (tag, "SampleTextNameID"), 0
428
+ )
429
+ params.NumNamedParameters = self.cv_num_named_params_.get(tag, 0)
430
+ params.FirstParamUILabelNameID = self.cv_parameters_ids_.get(
431
+ (tag, "ParamUILabelNameID_0"), 0
432
+ )
433
+ params.CharCount = len(self.cv_characters_[tag])
434
+ params.Character = self.cv_characters_[tag]
435
+ return params
436
+
437
+ def build_name(self):
438
+ if not self.names_:
439
+ return
440
+ table = self.font.get("name")
441
+ if not table: # this only happens for unit tests
442
+ table = self.font["name"] = newTable("name")
443
+ table.names = []
444
+ for name in self.names_:
445
+ nameID, platformID, platEncID, langID, string = name
446
+ # For featureNames block, nameID is 'feature tag'
447
+ # For cvParameters blocks, nameID is ('feature tag', 'block name')
448
+ if not isinstance(nameID, int):
449
+ tag = nameID
450
+ if tag in self.featureNames_:
451
+ if tag not in self.featureNames_ids_:
452
+ self.featureNames_ids_[tag] = self.get_user_name_id(table)
453
+ assert self.featureNames_ids_[tag] is not None
454
+ nameID = self.featureNames_ids_[tag]
455
+ elif tag[0] in self.cv_parameters_:
456
+ if tag not in self.cv_parameters_ids_:
457
+ self.cv_parameters_ids_[tag] = self.get_user_name_id(table)
458
+ assert self.cv_parameters_ids_[tag] is not None
459
+ nameID = self.cv_parameters_ids_[tag]
460
+ table.setName(string, nameID, platformID, platEncID, langID)
461
+ table.names.sort()
462
+
463
+ def build_OS_2(self):
464
+ if not self.os2_:
465
+ return
466
+ table = self.font.get("OS/2")
467
+ if not table: # this only happens for unit tests
468
+ table = self.font["OS/2"] = newTable("OS/2")
469
+ data = b"\0" * sstruct.calcsize(getTableModule("OS/2").OS2_format_0)
470
+ table.decompile(data, self.font)
471
+ version = 0
472
+ if "fstype" in self.os2_:
473
+ table.fsType = self.os2_["fstype"]
474
+ if "panose" in self.os2_:
475
+ panose = getTableModule("OS/2").Panose()
476
+ (
477
+ panose.bFamilyType,
478
+ panose.bSerifStyle,
479
+ panose.bWeight,
480
+ panose.bProportion,
481
+ panose.bContrast,
482
+ panose.bStrokeVariation,
483
+ panose.bArmStyle,
484
+ panose.bLetterForm,
485
+ panose.bMidline,
486
+ panose.bXHeight,
487
+ ) = self.os2_["panose"]
488
+ table.panose = panose
489
+ if "typoascender" in self.os2_:
490
+ table.sTypoAscender = self.os2_["typoascender"]
491
+ if "typodescender" in self.os2_:
492
+ table.sTypoDescender = self.os2_["typodescender"]
493
+ if "typolinegap" in self.os2_:
494
+ table.sTypoLineGap = self.os2_["typolinegap"]
495
+ if "winascent" in self.os2_:
496
+ table.usWinAscent = self.os2_["winascent"]
497
+ if "windescent" in self.os2_:
498
+ table.usWinDescent = self.os2_["windescent"]
499
+ if "vendor" in self.os2_:
500
+ table.achVendID = safeEval("'''" + self.os2_["vendor"] + "'''")
501
+ if "weightclass" in self.os2_:
502
+ table.usWeightClass = self.os2_["weightclass"]
503
+ if "widthclass" in self.os2_:
504
+ table.usWidthClass = self.os2_["widthclass"]
505
+ if "unicoderange" in self.os2_:
506
+ table.setUnicodeRanges(self.os2_["unicoderange"])
507
+ if "codepagerange" in self.os2_:
508
+ pages = self.build_codepages_(self.os2_["codepagerange"])
509
+ table.ulCodePageRange1, table.ulCodePageRange2 = pages
510
+ version = 1
511
+ if "xheight" in self.os2_:
512
+ table.sxHeight = self.os2_["xheight"]
513
+ version = 2
514
+ if "capheight" in self.os2_:
515
+ table.sCapHeight = self.os2_["capheight"]
516
+ version = 2
517
+ if "loweropsize" in self.os2_:
518
+ table.usLowerOpticalPointSize = self.os2_["loweropsize"]
519
+ version = 5
520
+ if "upperopsize" in self.os2_:
521
+ table.usUpperOpticalPointSize = self.os2_["upperopsize"]
522
+ version = 5
523
+
524
+ def checkattr(table, attrs):
525
+ for attr in attrs:
526
+ if not hasattr(table, attr):
527
+ setattr(table, attr, 0)
528
+
529
+ table.version = max(version, table.version)
530
+ # this only happens for unit tests
531
+ if version >= 1:
532
+ checkattr(table, ("ulCodePageRange1", "ulCodePageRange2"))
533
+ if version >= 2:
534
+ checkattr(
535
+ table,
536
+ (
537
+ "sxHeight",
538
+ "sCapHeight",
539
+ "usDefaultChar",
540
+ "usBreakChar",
541
+ "usMaxContext",
542
+ ),
543
+ )
544
+ if version >= 5:
545
+ checkattr(table, ("usLowerOpticalPointSize", "usUpperOpticalPointSize"))
546
+
547
+ def setElidedFallbackName(self, value, location):
548
+ # ElidedFallbackName is a convenience method for setting
549
+ # ElidedFallbackNameID so only one can be allowed
550
+ for token in ("ElidedFallbackName", "ElidedFallbackNameID"):
551
+ if token in self.stat_:
552
+ raise FeatureLibError(
553
+ f"{token} is already set.",
554
+ location,
555
+ )
556
+ if isinstance(value, int):
557
+ self.stat_["ElidedFallbackNameID"] = value
558
+ elif isinstance(value, list):
559
+ self.stat_["ElidedFallbackName"] = value
560
+ else:
561
+ raise AssertionError(value)
562
+
563
+ def addDesignAxis(self, designAxis, location):
564
+ if "DesignAxes" not in self.stat_:
565
+ self.stat_["DesignAxes"] = []
566
+ if designAxis.tag in (r.tag for r in self.stat_["DesignAxes"]):
567
+ raise FeatureLibError(
568
+ f'DesignAxis already defined for tag "{designAxis.tag}".',
569
+ location,
570
+ )
571
+ if designAxis.axisOrder in (r.axisOrder for r in self.stat_["DesignAxes"]):
572
+ raise FeatureLibError(
573
+ f"DesignAxis already defined for axis number {designAxis.axisOrder}.",
574
+ location,
575
+ )
576
+ self.stat_["DesignAxes"].append(designAxis)
577
+
578
+ def addAxisValueRecord(self, axisValueRecord, location):
579
+ if "AxisValueRecords" not in self.stat_:
580
+ self.stat_["AxisValueRecords"] = []
581
+ # Check for duplicate AxisValueRecords
582
+ for record_ in self.stat_["AxisValueRecords"]:
583
+ if (
584
+ {n.asFea() for n in record_.names}
585
+ == {n.asFea() for n in axisValueRecord.names}
586
+ and {n.asFea() for n in record_.locations}
587
+ == {n.asFea() for n in axisValueRecord.locations}
588
+ and record_.flags == axisValueRecord.flags
589
+ ):
590
+ raise FeatureLibError(
591
+ "An AxisValueRecord with these values is already defined.",
592
+ location,
593
+ )
594
+ self.stat_["AxisValueRecords"].append(axisValueRecord)
595
+
596
+ def build_STAT(self):
597
+ if not self.stat_:
598
+ return
599
+
600
+ axes = self.stat_.get("DesignAxes")
601
+ if not axes:
602
+ raise FeatureLibError("DesignAxes not defined", None)
603
+ axisValueRecords = self.stat_.get("AxisValueRecords")
604
+ axisValues = {}
605
+ format4_locations = []
606
+ for tag in axes:
607
+ axisValues[tag.tag] = []
608
+ if axisValueRecords is not None:
609
+ for avr in axisValueRecords:
610
+ valuesDict = {}
611
+ if avr.flags > 0:
612
+ valuesDict["flags"] = avr.flags
613
+ if len(avr.locations) == 1:
614
+ location = avr.locations[0]
615
+ values = location.values
616
+ if len(values) == 1: # format1
617
+ valuesDict.update({"value": values[0], "name": avr.names})
618
+ if len(values) == 2: # format3
619
+ valuesDict.update(
620
+ {
621
+ "value": values[0],
622
+ "linkedValue": values[1],
623
+ "name": avr.names,
624
+ }
625
+ )
626
+ if len(values) == 3: # format2
627
+ nominal, minVal, maxVal = values
628
+ valuesDict.update(
629
+ {
630
+ "nominalValue": nominal,
631
+ "rangeMinValue": minVal,
632
+ "rangeMaxValue": maxVal,
633
+ "name": avr.names,
634
+ }
635
+ )
636
+ axisValues[location.tag].append(valuesDict)
637
+ else:
638
+ valuesDict.update(
639
+ {
640
+ "location": {i.tag: i.values[0] for i in avr.locations},
641
+ "name": avr.names,
642
+ }
643
+ )
644
+ format4_locations.append(valuesDict)
645
+
646
+ designAxes = [
647
+ {
648
+ "ordering": a.axisOrder,
649
+ "tag": a.tag,
650
+ "name": a.names,
651
+ "values": axisValues[a.tag],
652
+ }
653
+ for a in axes
654
+ ]
655
+
656
+ nameTable = self.font.get("name")
657
+ if not nameTable: # this only happens for unit tests
658
+ nameTable = self.font["name"] = newTable("name")
659
+ nameTable.names = []
660
+
661
+ if "ElidedFallbackNameID" in self.stat_:
662
+ nameID = self.stat_["ElidedFallbackNameID"]
663
+ name = nameTable.getDebugName(nameID)
664
+ if not name:
665
+ raise FeatureLibError(
666
+ f"ElidedFallbackNameID {nameID} points "
667
+ "to a nameID that does not exist in the "
668
+ '"name" table',
669
+ None,
670
+ )
671
+ elif "ElidedFallbackName" in self.stat_:
672
+ nameID = self.stat_["ElidedFallbackName"]
673
+
674
+ otl.buildStatTable(
675
+ self.font,
676
+ designAxes,
677
+ locations=format4_locations,
678
+ elidedFallbackName=nameID,
679
+ )
680
+
681
+ def build_codepages_(self, pages):
682
+ pages2bits = {
683
+ 1252: 0,
684
+ 1250: 1,
685
+ 1251: 2,
686
+ 1253: 3,
687
+ 1254: 4,
688
+ 1255: 5,
689
+ 1256: 6,
690
+ 1257: 7,
691
+ 1258: 8,
692
+ 874: 16,
693
+ 932: 17,
694
+ 936: 18,
695
+ 949: 19,
696
+ 950: 20,
697
+ 1361: 21,
698
+ 869: 48,
699
+ 866: 49,
700
+ 865: 50,
701
+ 864: 51,
702
+ 863: 52,
703
+ 862: 53,
704
+ 861: 54,
705
+ 860: 55,
706
+ 857: 56,
707
+ 855: 57,
708
+ 852: 58,
709
+ 775: 59,
710
+ 737: 60,
711
+ 708: 61,
712
+ 850: 62,
713
+ 437: 63,
714
+ }
715
+ bits = [pages2bits[p] for p in pages if p in pages2bits]
716
+ pages = []
717
+ for i in range(2):
718
+ pages.append("")
719
+ for j in range(i * 32, (i + 1) * 32):
720
+ if j in bits:
721
+ pages[i] += "1"
722
+ else:
723
+ pages[i] += "0"
724
+ return [binary2num(p[::-1]) for p in pages]
725
+
726
+ def buildBASE(self):
727
+ if not self.base_horiz_axis_ and not self.base_vert_axis_:
728
+ return None
729
+ base = otTables.BASE()
730
+ base.Version = 0x00010000
731
+ base.HorizAxis = self.buildBASEAxis(self.base_horiz_axis_)
732
+ base.VertAxis = self.buildBASEAxis(self.base_vert_axis_)
733
+
734
+ result = newTable("BASE")
735
+ result.table = base
736
+ return result
737
+
738
+ def buildBASECoord(self, c):
739
+ coord = otTables.BaseCoord()
740
+ coord.Format = 1
741
+ coord.Coordinate = c
742
+ return coord
743
+
744
+ def buildBASEAxis(self, axis):
745
+ if not axis:
746
+ return
747
+ bases, scripts, minmax = axis
748
+ axis = otTables.Axis()
749
+ axis.BaseTagList = otTables.BaseTagList()
750
+ axis.BaseTagList.BaselineTag = bases
751
+ axis.BaseTagList.BaseTagCount = len(bases)
752
+ axis.BaseScriptList = otTables.BaseScriptList()
753
+ axis.BaseScriptList.BaseScriptRecord = []
754
+ axis.BaseScriptList.BaseScriptCount = len(scripts)
755
+ for script in sorted(scripts):
756
+ minmax_for_script = [
757
+ record[1:] for record in minmax if record[0] == script[0]
758
+ ]
759
+ record = otTables.BaseScriptRecord()
760
+ record.BaseScriptTag = script[0]
761
+ record.BaseScript = otTables.BaseScript()
762
+ record.BaseScript.BaseValues = otTables.BaseValues()
763
+ record.BaseScript.BaseValues.DefaultIndex = bases.index(script[1])
764
+ record.BaseScript.BaseValues.BaseCoord = []
765
+ record.BaseScript.BaseValues.BaseCoordCount = len(script[2])
766
+ record.BaseScript.BaseLangSysRecord = []
767
+
768
+ for c in script[2]:
769
+ record.BaseScript.BaseValues.BaseCoord.append(self.buildBASECoord(c))
770
+ for language, min_coord, max_coord in minmax_for_script:
771
+ minmax_record = otTables.MinMax()
772
+ minmax_record.MinCoord = self.buildBASECoord(min_coord)
773
+ minmax_record.MaxCoord = self.buildBASECoord(max_coord)
774
+ minmax_record.FeatMinMaxCount = 0
775
+ if language == "dflt":
776
+ record.BaseScript.DefaultMinMax = minmax_record
777
+ else:
778
+ lang_record = otTables.BaseLangSysRecord()
779
+ lang_record.BaseLangSysTag = language
780
+ lang_record.MinMax = minmax_record
781
+ record.BaseScript.BaseLangSysRecord.append(lang_record)
782
+ record.BaseScript.BaseLangSysCount = len(
783
+ record.BaseScript.BaseLangSysRecord
784
+ )
785
+ axis.BaseScriptList.BaseScriptRecord.append(record)
786
+ return axis
787
+
788
+ def buildGDEF(self):
789
+ gdef = otTables.GDEF()
790
+ gdef.GlyphClassDef = self.buildGDEFGlyphClassDef_()
791
+ gdef.AttachList = otl.buildAttachList(self.attachPoints_, self.glyphMap)
792
+ gdef.LigCaretList = otl.buildLigCaretList(
793
+ self.ligCaretCoords_, self.ligCaretPoints_, self.glyphMap
794
+ )
795
+ gdef.MarkAttachClassDef = self.buildGDEFMarkAttachClassDef_()
796
+ gdef.MarkGlyphSetsDef = self.buildGDEFMarkGlyphSetsDef_()
797
+ gdef.Version = 0x00010002 if gdef.MarkGlyphSetsDef else 0x00010000
798
+ if self.varstorebuilder:
799
+ store = self.varstorebuilder.finish()
800
+ if store:
801
+ gdef.Version = 0x00010003
802
+ gdef.VarStore = store
803
+ varidx_map = store.optimize()
804
+
805
+ gdef.remap_device_varidxes(varidx_map)
806
+ if "GPOS" in self.font:
807
+ self.font["GPOS"].table.remap_device_varidxes(varidx_map)
808
+ self.model_cache.clear()
809
+ if any(
810
+ (
811
+ gdef.GlyphClassDef,
812
+ gdef.AttachList,
813
+ gdef.LigCaretList,
814
+ gdef.MarkAttachClassDef,
815
+ gdef.MarkGlyphSetsDef,
816
+ )
817
+ ) or hasattr(gdef, "VarStore"):
818
+ result = newTable("GDEF")
819
+ result.table = gdef
820
+ return result
821
+ else:
822
+ return None
823
+
824
+ def buildGDEFGlyphClassDef_(self):
825
+ if self.glyphClassDefs_:
826
+ classes = {g: c for (g, (c, _)) in self.glyphClassDefs_.items()}
827
+ else:
828
+ classes = {}
829
+ for lookup in self.lookups_:
830
+ classes.update(lookup.inferGlyphClasses())
831
+ for markClass in self.parseTree.markClasses.values():
832
+ for markClassDef in markClass.definitions:
833
+ for glyph in markClassDef.glyphSet():
834
+ classes[glyph] = 3
835
+ if classes:
836
+ result = otTables.GlyphClassDef()
837
+ result.classDefs = classes
838
+ return result
839
+ else:
840
+ return None
841
+
842
+ def buildGDEFMarkAttachClassDef_(self):
843
+ classDefs = {g: c for g, (c, _) in self.markAttach_.items()}
844
+ if not classDefs:
845
+ return None
846
+ result = otTables.MarkAttachClassDef()
847
+ result.classDefs = classDefs
848
+ return result
849
+
850
+ def buildGDEFMarkGlyphSetsDef_(self):
851
+ sets = []
852
+ for glyphs, id_ in sorted(
853
+ self.markFilterSets_.items(), key=lambda item: item[1]
854
+ ):
855
+ sets.append(glyphs)
856
+ return otl.buildMarkGlyphSetsDef(sets, self.glyphMap)
857
+
858
+ def buildDebg(self):
859
+ if "Debg" not in self.font:
860
+ self.font["Debg"] = newTable("Debg")
861
+ self.font["Debg"].data = {}
862
+ self.font["Debg"].data[LOOKUP_DEBUG_INFO_KEY] = self.lookup_locations
863
+
864
+ def buildLookups_(self, tag):
865
+ assert tag in ("GPOS", "GSUB"), tag
866
+ for lookup in self.lookups_:
867
+ lookup.lookup_index = None
868
+ lookups = []
869
+ for lookup in self.lookups_:
870
+ if lookup.table != tag:
871
+ continue
872
+ name = self.get_lookup_name_(lookup)
873
+ resolved = lookup.promote_lookup_type(is_named_lookup=name is not None)
874
+ if resolved is None:
875
+ raise FeatureLibError(
876
+ "Within a named lookup block, all rules must be of "
877
+ "the same lookup type and flag",
878
+ lookup.location,
879
+ )
880
+ for l in resolved:
881
+ lookup.lookup_index = len(lookups)
882
+ self.lookup_locations[tag][str(lookup.lookup_index)] = LookupDebugInfo(
883
+ location=str(lookup.location),
884
+ name=name,
885
+ feature=None,
886
+ )
887
+ lookups.append(l)
888
+ otLookups = []
889
+ for l in lookups:
890
+ try:
891
+ otLookups.append(l.build())
892
+ except OpenTypeLibError as e:
893
+ raise FeatureLibError(str(e), e.location) from e
894
+ except Exception as e:
895
+ location = self.lookup_locations[tag][str(l.lookup_index)].location
896
+ raise FeatureLibError(str(e), location) from e
897
+ return otLookups
898
+
899
+ def makeTable(self, tag):
900
+ table = getattr(otTables, tag, None)()
901
+ table.Version = 0x00010000
902
+ table.ScriptList = otTables.ScriptList()
903
+ table.ScriptList.ScriptRecord = []
904
+ table.FeatureList = otTables.FeatureList()
905
+ table.FeatureList.FeatureRecord = []
906
+ table.LookupList = otTables.LookupList()
907
+ table.LookupList.Lookup = self.buildLookups_(tag)
908
+
909
+ # Build a table for mapping (tag, lookup_indices) to feature_index.
910
+ # For example, ('liga', (2,3,7)) --> 23.
911
+ feature_indices = {}
912
+ required_feature_indices = {} # ('latn', 'DEU') --> 23
913
+ scripts = {} # 'latn' --> {'DEU': [23, 24]} for feature #23,24
914
+ # Sort the feature table by feature tag:
915
+ # https://github.com/fonttools/fonttools/issues/568
916
+ sortFeatureTag = lambda f: (f[0][2], f[0][1], f[0][0], f[1])
917
+ for key, lookups in sorted(self.features_.items(), key=sortFeatureTag):
918
+ script, lang, feature_tag = key
919
+ # l.lookup_index will be None when a lookup is not needed
920
+ # for the table under construction. For example, substitution
921
+ # rules will have no lookup_index while building GPOS tables.
922
+ # We also deduplicate lookup indices, as they only get applied once
923
+ # within a given feature:
924
+ # https://github.com/fonttools/fonttools/issues/2946
925
+ lookup_indices = tuple(
926
+ dict.fromkeys(
927
+ l.lookup_index for l in lookups if l.lookup_index is not None
928
+ )
929
+ )
930
+ # order doesn't matter, but lookup_indices preserves it.
931
+ # We want to combine identical sets of lookups (order doesn't matter)
932
+ # but also respect the order provided by the user (although there's
933
+ # a reasonable argument to just sort and dedupe, which fontc does)
934
+ lookup_key = frozenset(lookup_indices)
935
+
936
+ size_feature = tag == "GPOS" and feature_tag == "size"
937
+ force_feature = self.any_feature_variations(feature_tag, tag)
938
+ if len(lookup_indices) == 0 and not size_feature and not force_feature:
939
+ continue
940
+
941
+ for ix in lookup_indices:
942
+ try:
943
+ self.lookup_locations[tag][str(ix)] = self.lookup_locations[tag][
944
+ str(ix)
945
+ ]._replace(feature=key)
946
+ except KeyError:
947
+ warnings.warn(
948
+ "feaLib.Builder subclass needs upgrading to "
949
+ "stash debug information. See fonttools#2065."
950
+ )
951
+
952
+ feature_key = (feature_tag, lookup_key)
953
+ feature_index = feature_indices.get(feature_key)
954
+ if feature_index is None:
955
+ feature_index = len(table.FeatureList.FeatureRecord)
956
+ frec = otTables.FeatureRecord()
957
+ frec.FeatureTag = feature_tag
958
+ frec.Feature = otTables.Feature()
959
+ frec.Feature.FeatureParams = self.buildFeatureParams(feature_tag)
960
+ frec.Feature.LookupListIndex = list(lookup_indices)
961
+ frec.Feature.LookupCount = len(lookup_indices)
962
+ table.FeatureList.FeatureRecord.append(frec)
963
+ feature_indices[feature_key] = feature_index
964
+ scripts.setdefault(script, {}).setdefault(lang, []).append(feature_index)
965
+ if self.required_features_.get((script, lang)) == feature_tag:
966
+ required_feature_indices[(script, lang)] = feature_index
967
+
968
+ # Build ScriptList.
969
+ for script, lang_features in sorted(scripts.items()):
970
+ srec = otTables.ScriptRecord()
971
+ srec.ScriptTag = script
972
+ srec.Script = otTables.Script()
973
+ srec.Script.DefaultLangSys = None
974
+ srec.Script.LangSysRecord = []
975
+ for lang, feature_indices in sorted(lang_features.items()):
976
+ langrec = otTables.LangSysRecord()
977
+ langrec.LangSys = otTables.LangSys()
978
+ langrec.LangSys.LookupOrder = None
979
+
980
+ req_feature_index = required_feature_indices.get((script, lang))
981
+ if req_feature_index is None:
982
+ langrec.LangSys.ReqFeatureIndex = 0xFFFF
983
+ else:
984
+ langrec.LangSys.ReqFeatureIndex = req_feature_index
985
+
986
+ langrec.LangSys.FeatureIndex = [
987
+ i for i in feature_indices if i != req_feature_index
988
+ ]
989
+ langrec.LangSys.FeatureCount = len(langrec.LangSys.FeatureIndex)
990
+
991
+ if lang == "dflt":
992
+ srec.Script.DefaultLangSys = langrec.LangSys
993
+ else:
994
+ langrec.LangSysTag = lang
995
+ srec.Script.LangSysRecord.append(langrec)
996
+ srec.Script.LangSysCount = len(srec.Script.LangSysRecord)
997
+ table.ScriptList.ScriptRecord.append(srec)
998
+
999
+ table.ScriptList.ScriptCount = len(table.ScriptList.ScriptRecord)
1000
+ table.FeatureList.FeatureCount = len(table.FeatureList.FeatureRecord)
1001
+ table.LookupList.LookupCount = len(table.LookupList.Lookup)
1002
+ return table
1003
+
1004
+ def makeFeatureVariations(self, table, table_tag):
1005
+ feature_vars = {}
1006
+ has_any_variations = False
1007
+ # Sort out which lookups to build, gather their indices
1008
+ for (_, _, feature_tag), variations in self.feature_variations_.items():
1009
+ feature_vars[feature_tag] = []
1010
+ for conditionset, builders in variations.items():
1011
+ raw_conditionset = self.conditionsets_[conditionset]
1012
+ indices = []
1013
+ for b in builders:
1014
+ if b.table != table_tag:
1015
+ continue
1016
+ assert b.lookup_index is not None
1017
+ indices.append(b.lookup_index)
1018
+ has_any_variations = True
1019
+ feature_vars[feature_tag].append((raw_conditionset, indices))
1020
+
1021
+ if has_any_variations:
1022
+ for feature_tag, conditions_and_lookups in feature_vars.items():
1023
+ addFeatureVariationsRaw(
1024
+ self.font, table, conditions_and_lookups, feature_tag
1025
+ )
1026
+
1027
+ def any_feature_variations(self, feature_tag, table_tag):
1028
+ for (_, _, feature), variations in self.feature_variations_.items():
1029
+ if feature != feature_tag:
1030
+ continue
1031
+ for conditionset, builders in variations.items():
1032
+ if any(b.table == table_tag for b in builders):
1033
+ return True
1034
+ return False
1035
+
1036
+ def get_lookup_name_(self, lookup):
1037
+ rev = {v: k for k, v in self.named_lookups_.items()}
1038
+ if lookup in rev:
1039
+ return rev[lookup]
1040
+ return None
1041
+
1042
+ def add_language_system(self, location, script, language):
1043
+ # OpenType Feature File Specification, section 4.b.i
1044
+ if script == "DFLT" and language == "dflt" and self.default_language_systems_:
1045
+ raise FeatureLibError(
1046
+ 'If "languagesystem DFLT dflt" is present, it must be '
1047
+ "the first of the languagesystem statements",
1048
+ location,
1049
+ )
1050
+ if script == "DFLT":
1051
+ if self.seen_non_DFLT_script_:
1052
+ raise FeatureLibError(
1053
+ 'languagesystems using the "DFLT" script tag must '
1054
+ "precede all other languagesystems",
1055
+ location,
1056
+ )
1057
+ else:
1058
+ self.seen_non_DFLT_script_ = True
1059
+ if (script, language) in self.default_language_systems_:
1060
+ raise FeatureLibError(
1061
+ '"languagesystem %s %s" has already been specified'
1062
+ % (script.strip(), language.strip()),
1063
+ location,
1064
+ )
1065
+ self.default_language_systems_.add((script, language))
1066
+
1067
+ def get_default_language_systems_(self):
1068
+ # OpenType Feature File specification, 4.b.i. languagesystem:
1069
+ # If no "languagesystem" statement is present, then the
1070
+ # implementation must behave exactly as though the following
1071
+ # statement were present at the beginning of the feature file:
1072
+ # languagesystem DFLT dflt;
1073
+ if self.default_language_systems_:
1074
+ return frozenset(self.default_language_systems_)
1075
+ else:
1076
+ return frozenset({("DFLT", "dflt")})
1077
+
1078
+ def start_feature(self, location, name, use_extension=False):
1079
+ if use_extension and name != "aalt":
1080
+ raise FeatureLibError(
1081
+ "'useExtension' keyword for feature blocks is allowed only for 'aalt' feature",
1082
+ location,
1083
+ )
1084
+ self.language_systems = self.get_default_language_systems_()
1085
+ self.script_ = "DFLT"
1086
+ self.cur_lookup_ = None
1087
+ self.cur_feature_name_ = name
1088
+ self.lookupflag_ = 0
1089
+ self.lookupflag_markFilterSet_ = None
1090
+ self.use_extension_ = use_extension
1091
+ if name == "aalt":
1092
+ self.aalt_location_ = location
1093
+ self.aalt_use_extension_ = use_extension
1094
+
1095
+ def end_feature(self):
1096
+ assert self.cur_feature_name_ is not None
1097
+ self.cur_feature_name_ = None
1098
+ self.language_systems = None
1099
+ self.cur_lookup_ = None
1100
+ self.lookupflag_ = 0
1101
+ self.lookupflag_markFilterSet_ = None
1102
+ self.use_extension_ = False
1103
+
1104
+ def start_lookup_block(self, location, name, use_extension=False):
1105
+ if name in self.named_lookups_:
1106
+ raise FeatureLibError(
1107
+ 'Lookup "%s" has already been defined' % name, location
1108
+ )
1109
+ if self.cur_feature_name_ == "aalt":
1110
+ raise FeatureLibError(
1111
+ "Lookup blocks cannot be placed inside 'aalt' features; "
1112
+ "move it out, and then refer to it with a lookup statement",
1113
+ location,
1114
+ )
1115
+ self.cur_lookup_name_ = name
1116
+ self.named_lookups_[name] = None
1117
+ self.cur_lookup_ = None
1118
+ self.use_extension_ = use_extension
1119
+ if self.cur_feature_name_ is None:
1120
+ self.lookupflag_ = 0
1121
+ self.lookupflag_markFilterSet_ = None
1122
+
1123
+ def end_lookup_block(self):
1124
+ assert self.cur_lookup_name_ is not None
1125
+ self.cur_lookup_name_ = None
1126
+ self.cur_lookup_ = None
1127
+ self.use_extension_ = False
1128
+ if self.cur_feature_name_ is None:
1129
+ self.lookupflag_ = 0
1130
+ self.lookupflag_markFilterSet_ = None
1131
+
1132
+ def add_lookup_call(self, lookup_name):
1133
+ assert lookup_name in self.named_lookups_, lookup_name
1134
+ self.cur_lookup_ = None
1135
+ lookup = self.named_lookups_[lookup_name]
1136
+ if lookup is not None: # skip empty named lookup
1137
+ self.add_lookup_to_feature_(lookup, self.cur_feature_name_)
1138
+
1139
+ def set_font_revision(self, location, revision):
1140
+ self.fontRevision_ = revision
1141
+
1142
+ def set_language(self, location, language, include_default, required):
1143
+ assert len(language) == 4
1144
+ if self.cur_feature_name_ in ("aalt", "size"):
1145
+ raise FeatureLibError(
1146
+ "Language statements are not allowed "
1147
+ 'within "feature %s"' % self.cur_feature_name_,
1148
+ location,
1149
+ )
1150
+ if self.cur_feature_name_ is None:
1151
+ raise FeatureLibError(
1152
+ "Language statements are not allowed "
1153
+ "within standalone lookup blocks",
1154
+ location,
1155
+ )
1156
+ self.cur_lookup_ = None
1157
+
1158
+ key = (self.script_, language, self.cur_feature_name_)
1159
+ lookups = self.features_.get((key[0], "dflt", key[2]))
1160
+ if (language == "dflt" or include_default) and lookups:
1161
+ self.features_[key] = lookups[:]
1162
+ else:
1163
+ # if we aren't including default we need to manually remove the
1164
+ # default lookups, which were added to all declared langsystems
1165
+ # as they were encountered (we don't remove all lookups because
1166
+ # we want to allow duplicate script/lang statements;
1167
+ # see https://github.com/fonttools/fonttools/issues/3748
1168
+ cur_lookups = self.features_.get(key, [])
1169
+ self.features_[key] = [x for x in cur_lookups if x not in lookups]
1170
+ self.language_systems = frozenset([(self.script_, language)])
1171
+
1172
+ if required:
1173
+ key = (self.script_, language)
1174
+ if key in self.required_features_:
1175
+ raise FeatureLibError(
1176
+ "Language %s (script %s) has already "
1177
+ "specified feature %s as its required feature"
1178
+ % (
1179
+ language.strip(),
1180
+ self.script_.strip(),
1181
+ self.required_features_[key].strip(),
1182
+ ),
1183
+ location,
1184
+ )
1185
+ self.required_features_[key] = self.cur_feature_name_
1186
+
1187
+ def getMarkAttachClass_(self, location, glyphs):
1188
+ glyphs = frozenset(glyphs)
1189
+ id_ = self.markAttachClassID_.get(glyphs)
1190
+ if id_ is not None:
1191
+ return id_
1192
+ id_ = len(self.markAttachClassID_) + 1
1193
+ self.markAttachClassID_[glyphs] = id_
1194
+ for glyph in glyphs:
1195
+ if glyph in self.markAttach_:
1196
+ _, loc = self.markAttach_[glyph]
1197
+ raise FeatureLibError(
1198
+ "Glyph %s already has been assigned "
1199
+ "a MarkAttachmentType at %s" % (glyph, loc),
1200
+ location,
1201
+ )
1202
+ self.markAttach_[glyph] = (id_, location)
1203
+ return id_
1204
+
1205
+ def getMarkFilterSet_(self, location, glyphs):
1206
+ glyphs = frozenset(glyphs)
1207
+ id_ = self.markFilterSets_.get(glyphs)
1208
+ if id_ is not None:
1209
+ return id_
1210
+ id_ = len(self.markFilterSets_)
1211
+ self.markFilterSets_[glyphs] = id_
1212
+ return id_
1213
+
1214
+ def set_lookup_flag(self, location, value, markAttach, markFilter):
1215
+ value = value & 0xFF
1216
+ if markAttach is not None:
1217
+ markAttachClass = self.getMarkAttachClass_(location, markAttach)
1218
+ value = value | (markAttachClass << 8)
1219
+ if markFilter is not None:
1220
+ markFilterSet = self.getMarkFilterSet_(location, markFilter)
1221
+ value = value | 0x10
1222
+ self.lookupflag_markFilterSet_ = markFilterSet
1223
+ else:
1224
+ self.lookupflag_markFilterSet_ = None
1225
+ self.lookupflag_ = value
1226
+
1227
+ def set_script(self, location, script):
1228
+ if self.cur_feature_name_ in ("aalt", "size"):
1229
+ raise FeatureLibError(
1230
+ "Script statements are not allowed "
1231
+ 'within "feature %s"' % self.cur_feature_name_,
1232
+ location,
1233
+ )
1234
+ if self.cur_feature_name_ is None:
1235
+ raise FeatureLibError(
1236
+ "Script statements are not allowed " "within standalone lookup blocks",
1237
+ location,
1238
+ )
1239
+ if self.language_systems == {(script, "dflt")}:
1240
+ # Nothing to do.
1241
+ return
1242
+ self.cur_lookup_ = None
1243
+ self.script_ = script
1244
+ self.lookupflag_ = 0
1245
+ self.lookupflag_markFilterSet_ = None
1246
+ self.set_language(location, "dflt", include_default=True, required=False)
1247
+
1248
+ def find_lookup_builders_(self, lookups):
1249
+ """Helper for building chain contextual substitutions
1250
+
1251
+ Given a list of lookup names, finds the LookupBuilder for each name.
1252
+ If an input name is None, it gets mapped to a None LookupBuilder.
1253
+ """
1254
+ lookup_builders = []
1255
+ for lookuplist in lookups:
1256
+ if lookuplist is not None:
1257
+ lookup_builders.append(
1258
+ [self.named_lookups_.get(l.name) for l in lookuplist]
1259
+ )
1260
+ else:
1261
+ lookup_builders.append(None)
1262
+ return lookup_builders
1263
+
1264
+ def add_attach_points(self, location, glyphs, contourPoints):
1265
+ for glyph in glyphs:
1266
+ self.attachPoints_.setdefault(glyph, set()).update(contourPoints)
1267
+
1268
+ def add_feature_reference(self, location, featureName):
1269
+ if self.cur_feature_name_ != "aalt":
1270
+ raise FeatureLibError(
1271
+ 'Feature references are only allowed inside "feature aalt"', location
1272
+ )
1273
+ self.aalt_features_.append((location, featureName))
1274
+
1275
+ def add_featureName(self, tag):
1276
+ self.featureNames_.add(tag)
1277
+
1278
+ def add_cv_parameter(self, tag):
1279
+ self.cv_parameters_.add(tag)
1280
+
1281
+ def add_to_cv_num_named_params(self, tag):
1282
+ """Adds new items to ``self.cv_num_named_params_``
1283
+ or increments the count of existing items."""
1284
+ if tag in self.cv_num_named_params_:
1285
+ self.cv_num_named_params_[tag] += 1
1286
+ else:
1287
+ self.cv_num_named_params_[tag] = 1
1288
+
1289
+ def add_cv_character(self, character, tag):
1290
+ self.cv_characters_[tag].append(character)
1291
+
1292
+ def set_base_axis(self, bases, scripts, vertical, minmax=[]):
1293
+ if vertical:
1294
+ self.base_vert_axis_ = (bases, scripts, minmax)
1295
+ else:
1296
+ self.base_horiz_axis_ = (bases, scripts, minmax)
1297
+
1298
+ def set_size_parameters(
1299
+ self, location, DesignSize, SubfamilyID, RangeStart, RangeEnd
1300
+ ):
1301
+ if self.cur_feature_name_ != "size":
1302
+ raise FeatureLibError(
1303
+ "Parameters statements are not allowed "
1304
+ 'within "feature %s"' % self.cur_feature_name_,
1305
+ location,
1306
+ )
1307
+ self.size_parameters_ = [DesignSize, SubfamilyID, RangeStart, RangeEnd]
1308
+ for script, lang in self.language_systems:
1309
+ key = (script, lang, self.cur_feature_name_)
1310
+ self.features_.setdefault(key, [])
1311
+
1312
+ # GSUB rules
1313
+
1314
+ def add_any_subst_(self, location, mapping):
1315
+ lookup = self.get_lookup_(location, AnySubstBuilder, mapping=mapping)
1316
+ for key, value in mapping.items():
1317
+ if key in lookup.mapping:
1318
+ if value == lookup.mapping[key]:
1319
+ log.info(
1320
+ 'Removing duplicate substitution from "%s" to "%s" at %s',
1321
+ ", ".join(key),
1322
+ ", ".join(value),
1323
+ location,
1324
+ )
1325
+ else:
1326
+ raise FeatureLibError(
1327
+ 'Already defined substitution for "%s"' % ", ".join(key),
1328
+ location,
1329
+ )
1330
+ lookup.mapping[key] = value
1331
+
1332
+ # GSUB 1
1333
+ def add_single_subst(self, location, prefix, suffix, mapping, forceChain):
1334
+ if self.cur_feature_name_ == "aalt":
1335
+ for from_glyph, to_glyph in mapping.items():
1336
+ alts = self.aalt_alternates_.setdefault(from_glyph, [])
1337
+ if to_glyph not in alts:
1338
+ alts.append(to_glyph)
1339
+ return
1340
+ if prefix or suffix or forceChain:
1341
+ self.add_single_subst_chained_(location, prefix, suffix, mapping)
1342
+ return
1343
+
1344
+ self.add_any_subst_(
1345
+ location,
1346
+ {(key,): (value,) for key, value in mapping.items()},
1347
+ )
1348
+
1349
+ # GSUB 2
1350
+ def add_multiple_subst(
1351
+ self, location, prefix, glyph, suffix, replacements, forceChain=False
1352
+ ):
1353
+ if prefix or suffix or forceChain:
1354
+ self.add_multi_subst_chained_(location, prefix, glyph, suffix, replacements)
1355
+ return
1356
+ self.add_any_subst_(
1357
+ location,
1358
+ {(glyph,): tuple(replacements)},
1359
+ )
1360
+
1361
+ # GSUB 3
1362
+ def add_alternate_subst(self, location, prefix, glyph, suffix, replacement):
1363
+ if self.cur_feature_name_ == "aalt":
1364
+ alts = self.aalt_alternates_.setdefault(glyph, [])
1365
+ alts.extend(g for g in replacement if g not in alts)
1366
+ return
1367
+ if prefix or suffix:
1368
+ chain = self.get_lookup_(location, ChainContextSubstBuilder)
1369
+ lookup = self.get_chained_lookup_(location, AlternateSubstBuilder)
1370
+ chain.rules.append(ChainContextualRule(prefix, [{glyph}], suffix, [lookup]))
1371
+ else:
1372
+ lookup = self.get_lookup_(location, AlternateSubstBuilder)
1373
+ if glyph in lookup.alternates:
1374
+ raise FeatureLibError(
1375
+ 'Already defined alternates for glyph "%s"' % glyph, location
1376
+ )
1377
+ # We allow empty replacement glyphs here.
1378
+ lookup.alternates[glyph] = replacement
1379
+
1380
+ # GSUB 4
1381
+ def add_ligature_subst(
1382
+ self, location, prefix, glyphs, suffix, replacement, forceChain
1383
+ ):
1384
+ if prefix or suffix or forceChain:
1385
+ self.add_ligature_subst_chained_(
1386
+ location, prefix, glyphs, suffix, replacement
1387
+ )
1388
+ return
1389
+ if not all(glyphs):
1390
+ raise FeatureLibError("Empty glyph class in substitution", location)
1391
+
1392
+ # OpenType feature file syntax, section 5.d, "Ligature substitution":
1393
+ # "Since the OpenType specification does not allow ligature
1394
+ # substitutions to be specified on target sequences that contain
1395
+ # glyph classes, the implementation software will enumerate
1396
+ # all specific glyph sequences if glyph classes are detected"
1397
+ self.add_any_subst_(
1398
+ location,
1399
+ {g: (replacement,) for g in itertools.product(*glyphs)},
1400
+ )
1401
+
1402
+ # GSUB 5/6
1403
+ def add_chain_context_subst(self, location, prefix, glyphs, suffix, lookups):
1404
+ if not all(glyphs) or not all(prefix) or not all(suffix):
1405
+ raise FeatureLibError(
1406
+ "Empty glyph class in contextual substitution", location
1407
+ )
1408
+ lookup = self.get_lookup_(location, ChainContextSubstBuilder)
1409
+ lookup.rules.append(
1410
+ ChainContextualRule(
1411
+ prefix, glyphs, suffix, self.find_lookup_builders_(lookups)
1412
+ )
1413
+ )
1414
+
1415
+ def add_single_subst_chained_(self, location, prefix, suffix, mapping):
1416
+ if not mapping or not all(prefix) or not all(suffix):
1417
+ raise FeatureLibError(
1418
+ "Empty glyph class in contextual substitution", location
1419
+ )
1420
+ # https://github.com/fonttools/fonttools/issues/512
1421
+ # https://github.com/fonttools/fonttools/issues/2150
1422
+ chain = self.get_lookup_(location, ChainContextSubstBuilder)
1423
+ sub = chain.find_chainable_subst(mapping, SingleSubstBuilder)
1424
+ if sub is None:
1425
+ sub = self.get_chained_lookup_(location, SingleSubstBuilder)
1426
+ sub.mapping.update(mapping)
1427
+ chain.rules.append(
1428
+ ChainContextualRule(prefix, [list(mapping.keys())], suffix, [sub])
1429
+ )
1430
+
1431
+ def add_multi_subst_chained_(self, location, prefix, glyph, suffix, replacements):
1432
+ if not all(prefix) or not all(suffix):
1433
+ raise FeatureLibError(
1434
+ "Empty glyph class in contextual substitution", location
1435
+ )
1436
+ # https://github.com/fonttools/fonttools/issues/3551
1437
+ chain = self.get_lookup_(location, ChainContextSubstBuilder)
1438
+ sub = chain.find_chainable_subst({glyph: replacements}, MultipleSubstBuilder)
1439
+ if sub is None:
1440
+ sub = self.get_chained_lookup_(location, MultipleSubstBuilder)
1441
+ sub.mapping[glyph] = replacements
1442
+ chain.rules.append(ChainContextualRule(prefix, [{glyph}], suffix, [sub]))
1443
+
1444
+ def add_ligature_subst_chained_(
1445
+ self, location, prefix, glyphs, suffix, replacement
1446
+ ):
1447
+ # https://github.com/fonttools/fonttools/issues/3701
1448
+ if not all(prefix) or not all(suffix):
1449
+ raise FeatureLibError(
1450
+ "Empty glyph class in contextual substitution", location
1451
+ )
1452
+ chain = self.get_lookup_(location, ChainContextSubstBuilder)
1453
+ sub = chain.find_chainable_ligature_subst(glyphs, replacement)
1454
+ if sub is None:
1455
+ sub = self.get_chained_lookup_(location, LigatureSubstBuilder)
1456
+
1457
+ for g in itertools.product(*glyphs):
1458
+ existing = sub.ligatures.get(g, replacement)
1459
+ if existing != replacement:
1460
+ raise FeatureLibError(
1461
+ f"Conflicting ligature sub rules: '{g}' maps to '{existing}' and '{replacement}'",
1462
+ location,
1463
+ )
1464
+
1465
+ sub.ligatures[g] = replacement
1466
+
1467
+ chain.rules.append(ChainContextualRule(prefix, glyphs, suffix, [sub]))
1468
+
1469
+ # GSUB 8
1470
+ def add_reverse_chain_single_subst(self, location, old_prefix, old_suffix, mapping):
1471
+ if not mapping:
1472
+ raise FeatureLibError("Empty glyph class in substitution", location)
1473
+ lookup = self.get_lookup_(location, ReverseChainSingleSubstBuilder)
1474
+ lookup.rules.append((old_prefix, old_suffix, mapping))
1475
+
1476
+ # GPOS rules
1477
+
1478
+ # GPOS 1
1479
+ def add_single_pos(self, location, prefix, suffix, pos, forceChain):
1480
+ if prefix or suffix or forceChain:
1481
+ self.add_single_pos_chained_(location, prefix, suffix, pos)
1482
+ else:
1483
+ lookup = self.get_lookup_(location, SinglePosBuilder)
1484
+ for glyphs, value in pos:
1485
+ if not glyphs:
1486
+ raise FeatureLibError(
1487
+ "Empty glyph class in positioning rule", location
1488
+ )
1489
+ otValueRecord = self.makeOpenTypeValueRecord(
1490
+ location, value, pairPosContext=False
1491
+ )
1492
+ for glyph in glyphs:
1493
+ try:
1494
+ lookup.add_pos(location, glyph, otValueRecord)
1495
+ except OpenTypeLibError as e:
1496
+ raise FeatureLibError(str(e), e.location) from e
1497
+
1498
+ # GPOS 2
1499
+ def add_class_pair_pos(self, location, glyphclass1, value1, glyphclass2, value2):
1500
+ if not glyphclass1 or not glyphclass2:
1501
+ raise FeatureLibError("Empty glyph class in positioning rule", location)
1502
+ lookup = self.get_lookup_(location, PairPosBuilder)
1503
+ v1 = self.makeOpenTypeValueRecord(location, value1, pairPosContext=True)
1504
+ v2 = self.makeOpenTypeValueRecord(location, value2, pairPosContext=True)
1505
+ cls1 = tuple(sorted(set(glyphclass1)))
1506
+ cls2 = tuple(sorted(set(glyphclass2)))
1507
+ lookup.addClassPair(location, cls1, v1, cls2, v2)
1508
+
1509
+ def add_specific_pair_pos(self, location, glyph1, value1, glyph2, value2):
1510
+ if not glyph1 or not glyph2:
1511
+ raise FeatureLibError("Empty glyph class in positioning rule", location)
1512
+ lookup = self.get_lookup_(location, PairPosBuilder)
1513
+ v1 = self.makeOpenTypeValueRecord(location, value1, pairPosContext=True)
1514
+ v2 = self.makeOpenTypeValueRecord(location, value2, pairPosContext=True)
1515
+ lookup.addGlyphPair(location, glyph1, v1, glyph2, v2)
1516
+
1517
+ # GPOS 3
1518
+ def add_cursive_pos(self, location, glyphclass, entryAnchor, exitAnchor):
1519
+ if not glyphclass:
1520
+ raise FeatureLibError("Empty glyph class in positioning rule", location)
1521
+ lookup = self.get_lookup_(location, CursivePosBuilder)
1522
+ lookup.add_attachment(
1523
+ location,
1524
+ glyphclass,
1525
+ self.makeOpenTypeAnchor(location, entryAnchor),
1526
+ self.makeOpenTypeAnchor(location, exitAnchor),
1527
+ )
1528
+
1529
+ # GPOS 4
1530
+ def add_mark_base_pos(self, location, bases, marks):
1531
+ builder = self.get_lookup_(location, MarkBasePosBuilder)
1532
+ self.add_marks_(location, builder, marks)
1533
+ if not bases:
1534
+ raise FeatureLibError("Empty glyph class in positioning rule", location)
1535
+ for baseAnchor, markClass in marks:
1536
+ otBaseAnchor = self.makeOpenTypeAnchor(location, baseAnchor)
1537
+ for base in bases:
1538
+ builder.bases.setdefault(base, {})[markClass.name] = otBaseAnchor
1539
+
1540
+ # GPOS 5
1541
+ def add_mark_lig_pos(self, location, ligatures, components):
1542
+ builder = self.get_lookup_(location, MarkLigPosBuilder)
1543
+ componentAnchors = []
1544
+ if not ligatures:
1545
+ raise FeatureLibError("Empty glyph class in positioning rule", location)
1546
+ for marks in components:
1547
+ anchors = {}
1548
+ self.add_marks_(location, builder, marks)
1549
+ for ligAnchor, markClass in marks:
1550
+ anchors[markClass.name] = self.makeOpenTypeAnchor(location, ligAnchor)
1551
+ componentAnchors.append(anchors)
1552
+ for glyph in ligatures:
1553
+ builder.ligatures[glyph] = componentAnchors
1554
+
1555
+ # GPOS 6
1556
+ def add_mark_mark_pos(self, location, baseMarks, marks):
1557
+ builder = self.get_lookup_(location, MarkMarkPosBuilder)
1558
+ self.add_marks_(location, builder, marks)
1559
+ if not baseMarks:
1560
+ raise FeatureLibError("Empty glyph class in positioning rule", location)
1561
+ for baseAnchor, markClass in marks:
1562
+ otBaseAnchor = self.makeOpenTypeAnchor(location, baseAnchor)
1563
+ for baseMark in baseMarks:
1564
+ builder.baseMarks.setdefault(baseMark, {})[
1565
+ markClass.name
1566
+ ] = otBaseAnchor
1567
+
1568
+ # GPOS 7/8
1569
+ def add_chain_context_pos(self, location, prefix, glyphs, suffix, lookups):
1570
+ if not all(glyphs) or not all(prefix) or not all(suffix):
1571
+ raise FeatureLibError(
1572
+ "Empty glyph class in contextual positioning rule", location
1573
+ )
1574
+ lookup = self.get_lookup_(location, ChainContextPosBuilder)
1575
+ lookup.rules.append(
1576
+ ChainContextualRule(
1577
+ prefix, glyphs, suffix, self.find_lookup_builders_(lookups)
1578
+ )
1579
+ )
1580
+
1581
+ def add_single_pos_chained_(self, location, prefix, suffix, pos):
1582
+ if not pos or not all(prefix) or not all(suffix):
1583
+ raise FeatureLibError(
1584
+ "Empty glyph class in contextual positioning rule", location
1585
+ )
1586
+ # https://github.com/fonttools/fonttools/issues/514
1587
+ chain = self.get_lookup_(location, ChainContextPosBuilder)
1588
+ targets = []
1589
+ for _, _, _, lookups in chain.rules:
1590
+ targets.extend(lookups)
1591
+ subs = []
1592
+ for glyphs, value in pos:
1593
+ if value is None:
1594
+ subs.append(None)
1595
+ continue
1596
+ otValue = self.makeOpenTypeValueRecord(
1597
+ location, value, pairPosContext=False
1598
+ )
1599
+ sub = chain.find_chainable_single_pos(targets, glyphs, otValue)
1600
+ if sub is None:
1601
+ sub = self.get_chained_lookup_(location, SinglePosBuilder)
1602
+ targets.append(sub)
1603
+ for glyph in glyphs:
1604
+ sub.add_pos(location, glyph, otValue)
1605
+ subs.append(sub)
1606
+ assert len(pos) == len(subs), (pos, subs)
1607
+ chain.rules.append(
1608
+ ChainContextualRule(prefix, [g for g, v in pos], suffix, subs)
1609
+ )
1610
+
1611
+ def add_marks_(self, location, lookupBuilder, marks):
1612
+ """Helper for add_mark_{base,liga,mark}_pos."""
1613
+ for _, markClass in marks:
1614
+ for markClassDef in markClass.definitions:
1615
+ for mark in markClassDef.glyphs.glyphSet():
1616
+ if mark not in lookupBuilder.marks:
1617
+ otMarkAnchor = self.makeOpenTypeAnchor(
1618
+ location, copy.deepcopy(markClassDef.anchor)
1619
+ )
1620
+ lookupBuilder.marks[mark] = (markClass.name, otMarkAnchor)
1621
+ else:
1622
+ existingMarkClass = lookupBuilder.marks[mark][0]
1623
+ if markClass.name != existingMarkClass:
1624
+ raise FeatureLibError(
1625
+ "Glyph %s cannot be in both @%s and @%s"
1626
+ % (mark, existingMarkClass, markClass.name),
1627
+ location,
1628
+ )
1629
+
1630
+ def add_subtable_break(self, location):
1631
+ self.cur_lookup_.add_subtable_break(location)
1632
+
1633
+ def setGlyphClass_(self, location, glyph, glyphClass):
1634
+ oldClass, oldLocation = self.glyphClassDefs_.get(glyph, (None, None))
1635
+ if oldClass and oldClass != glyphClass:
1636
+ raise FeatureLibError(
1637
+ "Glyph %s was assigned to a different class at %s"
1638
+ % (glyph, oldLocation),
1639
+ location,
1640
+ )
1641
+ self.glyphClassDefs_[glyph] = (glyphClass, location)
1642
+
1643
+ def add_glyphClassDef(
1644
+ self, location, baseGlyphs, ligatureGlyphs, markGlyphs, componentGlyphs
1645
+ ):
1646
+ for glyph in baseGlyphs:
1647
+ self.setGlyphClass_(location, glyph, 1)
1648
+ for glyph in ligatureGlyphs:
1649
+ self.setGlyphClass_(location, glyph, 2)
1650
+ for glyph in markGlyphs:
1651
+ self.setGlyphClass_(location, glyph, 3)
1652
+ for glyph in componentGlyphs:
1653
+ self.setGlyphClass_(location, glyph, 4)
1654
+
1655
+ def add_ligatureCaretByIndex_(self, location, glyphs, carets):
1656
+ for glyph in glyphs:
1657
+ if glyph not in self.ligCaretPoints_:
1658
+ self.ligCaretPoints_[glyph] = carets
1659
+
1660
+ def makeLigCaret(self, location, caret):
1661
+ if not isinstance(caret, VariableScalar):
1662
+ return caret
1663
+ default, device = self.makeVariablePos(location, caret)
1664
+ if device is not None:
1665
+ return (default, device)
1666
+ return default
1667
+
1668
+ def add_ligatureCaretByPos_(self, location, glyphs, carets):
1669
+ carets = [self.makeLigCaret(location, caret) for caret in carets]
1670
+ for glyph in glyphs:
1671
+ if glyph not in self.ligCaretCoords_:
1672
+ self.ligCaretCoords_[glyph] = carets
1673
+
1674
+ def add_name_record(self, location, nameID, platformID, platEncID, langID, string):
1675
+ self.names_.append([nameID, platformID, platEncID, langID, string])
1676
+
1677
+ def add_os2_field(self, key, value):
1678
+ self.os2_[key] = value
1679
+
1680
+ def add_hhea_field(self, key, value):
1681
+ self.hhea_[key] = value
1682
+
1683
+ def add_vhea_field(self, key, value):
1684
+ self.vhea_[key] = value
1685
+
1686
+ def add_conditionset(self, location, key, value):
1687
+ if "fvar" not in self.font:
1688
+ raise FeatureLibError(
1689
+ "Cannot add feature variations to a font without an 'fvar' table",
1690
+ location,
1691
+ )
1692
+
1693
+ # Normalize
1694
+ axisMap = {
1695
+ axis.axisTag: (axis.minValue, axis.defaultValue, axis.maxValue)
1696
+ for axis in self.axes
1697
+ }
1698
+
1699
+ value = {
1700
+ tag: (
1701
+ normalizeValue(bottom, axisMap[tag]),
1702
+ normalizeValue(top, axisMap[tag]),
1703
+ )
1704
+ for tag, (bottom, top) in value.items()
1705
+ }
1706
+
1707
+ # NOTE: This might result in rounding errors (off-by-ones) compared to
1708
+ # rules in Designspace files, since we're working with what's in the
1709
+ # `avar` table rather than the original values.
1710
+ if "avar" in self.font:
1711
+ mapping = self.font["avar"].segments
1712
+ value = {
1713
+ axis: tuple(
1714
+ piecewiseLinearMap(v, mapping[axis]) if axis in mapping else v
1715
+ for v in condition_range
1716
+ )
1717
+ for axis, condition_range in value.items()
1718
+ }
1719
+
1720
+ self.conditionsets_[key] = value
1721
+
1722
+ def makeVariablePos(self, location, varscalar):
1723
+ if not self.varstorebuilder:
1724
+ raise FeatureLibError(
1725
+ "Can't define a variable scalar in a non-variable font", location
1726
+ )
1727
+
1728
+ varscalar.axes = self.axes
1729
+ if not varscalar.does_vary:
1730
+ return varscalar.default, None
1731
+
1732
+ try:
1733
+ default, index = varscalar.add_to_variation_store(
1734
+ self.varstorebuilder, self.model_cache, self.font.get("avar")
1735
+ )
1736
+ except VarLibError as e:
1737
+ raise FeatureLibError(
1738
+ "Failed to compute deltas for variable scalar", location
1739
+ ) from e
1740
+
1741
+ device = None
1742
+ if index is not None and index != 0xFFFFFFFF:
1743
+ device = buildVarDevTable(index)
1744
+
1745
+ return default, device
1746
+
1747
+ def makeAnchorPos(self, varscalar, deviceTable, location):
1748
+ device = None
1749
+ if not isinstance(varscalar, VariableScalar):
1750
+ if deviceTable is not None:
1751
+ device = otl.buildDevice(dict(deviceTable))
1752
+ return varscalar, device
1753
+ default, device = self.makeVariablePos(location, varscalar)
1754
+ if device is not None and deviceTable is not None:
1755
+ raise FeatureLibError(
1756
+ "Can't define a device coordinate and variable scalar", location
1757
+ )
1758
+ return default, device
1759
+
1760
+ def makeOpenTypeAnchor(self, location, anchor):
1761
+ """ast.Anchor --> otTables.Anchor"""
1762
+ if anchor is None:
1763
+ return None
1764
+ deviceX, deviceY = None, None
1765
+ if anchor.xDeviceTable is not None:
1766
+ deviceX = otl.buildDevice(dict(anchor.xDeviceTable))
1767
+ if anchor.yDeviceTable is not None:
1768
+ deviceY = otl.buildDevice(dict(anchor.yDeviceTable))
1769
+ x, deviceX = self.makeAnchorPos(anchor.x, anchor.xDeviceTable, location)
1770
+ y, deviceY = self.makeAnchorPos(anchor.y, anchor.yDeviceTable, location)
1771
+ otlanchor = otl.buildAnchor(x, y, anchor.contourpoint, deviceX, deviceY)
1772
+ return otlanchor
1773
+
1774
+ _VALUEREC_ATTRS = {
1775
+ name[0].lower() + name[1:]: (name, isDevice)
1776
+ for _, name, isDevice, _ in otBase.valueRecordFormat
1777
+ if not name.startswith("Reserved")
1778
+ }
1779
+
1780
+ def makeOpenTypeValueRecord(self, location, v, pairPosContext):
1781
+ """ast.ValueRecord --> otBase.ValueRecord"""
1782
+ if not v:
1783
+ return None
1784
+
1785
+ vr = {}
1786
+ for astName, (otName, isDevice) in self._VALUEREC_ATTRS.items():
1787
+ val = getattr(v, astName, None)
1788
+ if not val:
1789
+ continue
1790
+ if isDevice:
1791
+ vr[otName] = otl.buildDevice(dict(val))
1792
+ elif isinstance(val, VariableScalar):
1793
+ otDeviceName = otName[0:4] + "Device"
1794
+ feaDeviceName = otDeviceName[0].lower() + otDeviceName[1:]
1795
+ if getattr(v, feaDeviceName):
1796
+ raise FeatureLibError(
1797
+ "Can't define a device coordinate and variable scalar", location
1798
+ )
1799
+ vr[otName], device = self.makeVariablePos(location, val)
1800
+ if device is not None:
1801
+ vr[otDeviceName] = device
1802
+ else:
1803
+ vr[otName] = val
1804
+
1805
+ if pairPosContext and not vr:
1806
+ vr = {"YAdvance": 0} if v.vertical else {"XAdvance": 0}
1807
+ valRec = otl.buildValue(vr)
1808
+ return valRec
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/error.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class FeatureLibError(Exception):
2
+ def __init__(self, message, location=None):
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
12
+
13
+
14
+ class IncludedFeaNotFound(FeatureLibError):
15
+ def __str__(self):
16
+ assert self.location is not None
17
+
18
+ message = (
19
+ "The following feature file should be included but cannot be found: "
20
+ f"{Exception.__str__(self)}"
21
+ )
22
+ return f"{self.location}: {message}"
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/lexer.c ADDED
The diff for this file is too large to render. See raw diff
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/lexer.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.feaLib.error import FeatureLibError, IncludedFeaNotFound
2
+ from fontTools.feaLib.location import FeatureLibLocation
3
+ import re
4
+ import os
5
+
6
+ try:
7
+ import cython
8
+ except ImportError:
9
+ # if cython not installed, use mock module with no-op decorators and types
10
+ from fontTools.misc import cython
11
+
12
+
13
+ class Lexer(object):
14
+ NUMBER = "NUMBER"
15
+ HEXADECIMAL = "HEXADECIMAL"
16
+ OCTAL = "OCTAL"
17
+ NUMBERS = (NUMBER, HEXADECIMAL, OCTAL)
18
+ FLOAT = "FLOAT"
19
+ STRING = "STRING"
20
+ NAME = "NAME"
21
+ FILENAME = "FILENAME"
22
+ GLYPHCLASS = "GLYPHCLASS"
23
+ CID = "CID"
24
+ SYMBOL = "SYMBOL"
25
+ COMMENT = "COMMENT"
26
+ NEWLINE = "NEWLINE"
27
+ ANONYMOUS_BLOCK = "ANONYMOUS_BLOCK"
28
+
29
+ CHAR_WHITESPACE_ = " \t"
30
+ CHAR_NEWLINE_ = "\r\n"
31
+ CHAR_SYMBOL_ = ",;:-+'{}[]<>()="
32
+ CHAR_DIGIT_ = "0123456789"
33
+ CHAR_HEXDIGIT_ = "0123456789ABCDEFabcdef"
34
+ CHAR_LETTER_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
35
+ CHAR_NAME_START_ = CHAR_LETTER_ + "_+*:.^~!\\"
36
+ CHAR_NAME_CONTINUATION_ = CHAR_LETTER_ + CHAR_DIGIT_ + "_.+*:^~!/-"
37
+
38
+ RE_GLYPHCLASS = re.compile(r"^[A-Za-z_0-9.\-]+$")
39
+
40
+ MODE_NORMAL_ = "NORMAL"
41
+ MODE_FILENAME_ = "FILENAME"
42
+
43
+ def __init__(self, text, filename):
44
+ self.filename_ = filename
45
+ self.line_ = 1
46
+ self.pos_ = 0
47
+ self.line_start_ = 0
48
+ self.text_ = text
49
+ self.text_length_ = len(text)
50
+ self.mode_ = Lexer.MODE_NORMAL_
51
+
52
+ def __iter__(self):
53
+ return self
54
+
55
+ def next(self): # Python 2
56
+ return self.__next__()
57
+
58
+ def __next__(self): # Python 3
59
+ while True:
60
+ token_type, token, location = self.next_()
61
+ if token_type != Lexer.NEWLINE:
62
+ return (token_type, token, location)
63
+
64
+ def location_(self):
65
+ column = self.pos_ - self.line_start_ + 1
66
+ return FeatureLibLocation(self.filename_ or "<features>", self.line_, column)
67
+
68
+ def next_(self):
69
+ self.scan_over_(Lexer.CHAR_WHITESPACE_)
70
+ location = self.location_()
71
+ start = self.pos_
72
+ text = self.text_
73
+ limit = len(text)
74
+ if start >= limit:
75
+ raise StopIteration()
76
+ cur_char = text[start]
77
+ next_char = text[start + 1] if start + 1 < limit else None
78
+
79
+ if cur_char == "\n":
80
+ self.pos_ += 1
81
+ self.line_ += 1
82
+ self.line_start_ = self.pos_
83
+ return (Lexer.NEWLINE, None, location)
84
+ if cur_char == "\r":
85
+ self.pos_ += 2 if next_char == "\n" else 1
86
+ self.line_ += 1
87
+ self.line_start_ = self.pos_
88
+ return (Lexer.NEWLINE, None, location)
89
+ if cur_char == "#":
90
+ self.scan_until_(Lexer.CHAR_NEWLINE_)
91
+ return (Lexer.COMMENT, text[start : self.pos_], location)
92
+
93
+ if self.mode_ is Lexer.MODE_FILENAME_:
94
+ if cur_char != "(":
95
+ raise FeatureLibError("Expected '(' before file name", location)
96
+ self.scan_until_(")")
97
+ cur_char = text[self.pos_] if self.pos_ < limit else None
98
+ if cur_char != ")":
99
+ raise FeatureLibError("Expected ')' after file name", location)
100
+ self.pos_ += 1
101
+ self.mode_ = Lexer.MODE_NORMAL_
102
+ return (Lexer.FILENAME, text[start + 1 : self.pos_ - 1], location)
103
+
104
+ if cur_char == "\\" and next_char in Lexer.CHAR_DIGIT_:
105
+ self.pos_ += 1
106
+ self.scan_over_(Lexer.CHAR_DIGIT_)
107
+ return (Lexer.CID, int(text[start + 1 : self.pos_], 10), location)
108
+ if cur_char == "@":
109
+ self.pos_ += 1
110
+ self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_)
111
+ glyphclass = text[start + 1 : self.pos_]
112
+ if len(glyphclass) < 1:
113
+ raise FeatureLibError("Expected glyph class name", location)
114
+ if not Lexer.RE_GLYPHCLASS.match(glyphclass):
115
+ raise FeatureLibError(
116
+ "Glyph class names must consist of letters, digits, "
117
+ "underscore, period or hyphen",
118
+ location,
119
+ )
120
+ return (Lexer.GLYPHCLASS, glyphclass, location)
121
+ if cur_char in Lexer.CHAR_NAME_START_:
122
+ self.pos_ += 1
123
+ self.scan_over_(Lexer.CHAR_NAME_CONTINUATION_)
124
+ token = text[start : self.pos_]
125
+ if token == "include":
126
+ self.mode_ = Lexer.MODE_FILENAME_
127
+ return (Lexer.NAME, token, location)
128
+ if cur_char == "0" and next_char in "xX":
129
+ self.pos_ += 2
130
+ self.scan_over_(Lexer.CHAR_HEXDIGIT_)
131
+ return (Lexer.HEXADECIMAL, int(text[start : self.pos_], 16), location)
132
+ if cur_char == "0" and next_char in Lexer.CHAR_DIGIT_:
133
+ self.scan_over_(Lexer.CHAR_DIGIT_)
134
+ return (Lexer.OCTAL, int(text[start : self.pos_], 8), location)
135
+ if cur_char in Lexer.CHAR_DIGIT_:
136
+ self.scan_over_(Lexer.CHAR_DIGIT_)
137
+ if self.pos_ >= limit or text[self.pos_] != ".":
138
+ return (Lexer.NUMBER, int(text[start : self.pos_], 10), location)
139
+ self.scan_over_(".")
140
+ self.scan_over_(Lexer.CHAR_DIGIT_)
141
+ return (Lexer.FLOAT, float(text[start : self.pos_]), location)
142
+ if cur_char == "-" and next_char in Lexer.CHAR_DIGIT_:
143
+ self.pos_ += 1
144
+ self.scan_over_(Lexer.CHAR_DIGIT_)
145
+ if self.pos_ >= limit or text[self.pos_] != ".":
146
+ return (Lexer.NUMBER, int(text[start : self.pos_], 10), location)
147
+ self.scan_over_(".")
148
+ self.scan_over_(Lexer.CHAR_DIGIT_)
149
+ return (Lexer.FLOAT, float(text[start : self.pos_]), location)
150
+ if cur_char in Lexer.CHAR_SYMBOL_:
151
+ self.pos_ += 1
152
+ return (Lexer.SYMBOL, cur_char, location)
153
+ if cur_char == '"':
154
+ self.pos_ += 1
155
+ self.scan_until_('"')
156
+ if self.pos_ < self.text_length_ and self.text_[self.pos_] == '"':
157
+ self.pos_ += 1
158
+ # strip newlines embedded within a string
159
+ string = re.sub("[\r\n]", "", text[start + 1 : self.pos_ - 1])
160
+ return (Lexer.STRING, string, location)
161
+ else:
162
+ raise FeatureLibError("Expected '\"' to terminate string", location)
163
+ raise FeatureLibError("Unexpected character: %r" % cur_char, location)
164
+
165
+ def scan_over_(self, valid):
166
+ p = self.pos_
167
+ while p < self.text_length_ and self.text_[p] in valid:
168
+ p += 1
169
+ self.pos_ = p
170
+
171
+ def scan_until_(self, stop_at):
172
+ p = self.pos_
173
+ while p < self.text_length_ and self.text_[p] not in stop_at:
174
+ p += 1
175
+ self.pos_ = p
176
+
177
+ def scan_anonymous_block(self, tag):
178
+ location = self.location_()
179
+ tag = tag.strip()
180
+ self.scan_until_(Lexer.CHAR_NEWLINE_)
181
+ self.scan_over_(Lexer.CHAR_NEWLINE_)
182
+ regexp = r"}\s*" + tag + r"\s*;"
183
+ split = re.split(regexp, self.text_[self.pos_ :], maxsplit=1)
184
+ if len(split) != 2:
185
+ raise FeatureLibError(
186
+ "Expected '} %s;' to terminate anonymous block" % tag, location
187
+ )
188
+ self.pos_ += len(split[0])
189
+ return (Lexer.ANONYMOUS_BLOCK, split[0], location)
190
+
191
+
192
+ class IncludingLexer(object):
193
+ """A Lexer that follows include statements.
194
+
195
+ The OpenType feature file specification states that due to
196
+ historical reasons, relative imports should be resolved in this
197
+ order:
198
+
199
+ 1. If the source font is UFO format, then relative to the UFO's
200
+ font directory
201
+ 2. relative to the top-level include file
202
+ 3. relative to the parent include file
203
+
204
+ We only support 1 (via includeDir) and 2.
205
+ """
206
+
207
+ def __init__(self, featurefile, *, includeDir=None):
208
+ """Initializes an IncludingLexer.
209
+
210
+ Behavior:
211
+ If includeDir is passed, it will be used to determine the top-level
212
+ include directory to use for all encountered include statements. If it is
213
+ not passed, ``os.path.dirname(featurefile)`` will be considered the
214
+ include directory.
215
+ """
216
+
217
+ self.lexers_ = [self.make_lexer_(featurefile)]
218
+ self.featurefilepath = self.lexers_[0].filename_
219
+ self.includeDir = includeDir
220
+
221
+ def __iter__(self):
222
+ return self
223
+
224
+ def next(self): # Python 2
225
+ return self.__next__()
226
+
227
+ def __next__(self): # Python 3
228
+ while self.lexers_:
229
+ lexer = self.lexers_[-1]
230
+ try:
231
+ token_type, token, location = next(lexer)
232
+ except StopIteration:
233
+ self.lexers_.pop()
234
+ continue
235
+ if token_type is Lexer.NAME and token == "include":
236
+ fname_type, fname_token, fname_location = lexer.next()
237
+ if fname_type is not Lexer.FILENAME:
238
+ raise FeatureLibError("Expected file name", fname_location)
239
+ # semi_type, semi_token, semi_location = lexer.next()
240
+ # if semi_type is not Lexer.SYMBOL or semi_token != ";":
241
+ # raise FeatureLibError("Expected ';'", semi_location)
242
+ if os.path.isabs(fname_token):
243
+ path = fname_token
244
+ else:
245
+ if self.includeDir is not None:
246
+ curpath = self.includeDir
247
+ elif self.featurefilepath is not None:
248
+ curpath = os.path.dirname(self.featurefilepath)
249
+ else:
250
+ # if the IncludingLexer was initialized from an in-memory
251
+ # file-like stream, it doesn't have a 'name' pointing to
252
+ # its filesystem path, therefore we fall back to using the
253
+ # current working directory to resolve relative includes
254
+ curpath = os.getcwd()
255
+ path = os.path.join(curpath, fname_token)
256
+ if len(self.lexers_) >= 5:
257
+ raise FeatureLibError("Too many recursive includes", fname_location)
258
+ try:
259
+ self.lexers_.append(self.make_lexer_(path))
260
+ except FileNotFoundError as err:
261
+ raise IncludedFeaNotFound(fname_token, fname_location) from err
262
+ else:
263
+ return (token_type, token, location)
264
+ raise StopIteration()
265
+
266
+ @staticmethod
267
+ def make_lexer_(file_or_path):
268
+ if hasattr(file_or_path, "read"):
269
+ fileobj, closing = file_or_path, False
270
+ else:
271
+ filename, closing = file_or_path, True
272
+ fileobj = open(filename, "r", encoding="utf-8-sig")
273
+ data = fileobj.read()
274
+ filename = getattr(fileobj, "name", None)
275
+ if closing:
276
+ fileobj.close()
277
+ return Lexer(data, filename)
278
+
279
+ def scan_anonymous_block(self, tag):
280
+ return self.lexers_[-1].scan_anonymous_block(tag)
281
+
282
+
283
+ class NonIncludingLexer(IncludingLexer):
284
+ """Lexer that does not follow `include` statements, emits them as-is."""
285
+
286
+ def __next__(self): # Python 3
287
+ return next(self.lexers_[0])
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/location.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import NamedTuple
2
+
3
+
4
+ class FeatureLibLocation(NamedTuple):
5
+ """A location in a feature file"""
6
+
7
+ file: str
8
+ line: int
9
+ column: int
10
+
11
+ def __str__(self):
12
+ return f"{self.file}:{self.line}:{self.column}"
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/lookupDebugInfo.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import NamedTuple
2
+
3
+ LOOKUP_DEBUG_INFO_KEY = "com.github.fonttools.feaLib"
4
+ LOOKUP_DEBUG_ENV_VAR = "FONTTOOLS_LOOKUP_DEBUGGING"
5
+
6
+
7
+ class LookupDebugInfo(NamedTuple):
8
+ """Information about where a lookup came from, to be embedded in a font"""
9
+
10
+ location: str
11
+ name: str
12
+ feature: list
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/parser.py ADDED
The diff for this file is too large to render. See raw diff
 
Scripts_Climate_to_LAI/.venv/lib/python3.10/site-packages/fontTools/feaLib/variableScalar.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fontTools.varLib.models import VariationModel, normalizeValue, piecewiseLinearMap
2
+
3
+
4
+ def Location(loc):
5
+ return tuple(sorted(loc.items()))
6
+
7
+
8
+ class VariableScalar:
9
+ """A scalar with different values at different points in the designspace."""
10
+
11
+ def __init__(self, location_value={}):
12
+ self.values = {}
13
+ self.axes = {}
14
+ for location, value in location_value.items():
15
+ self.add_value(location, value)
16
+
17
+ def __repr__(self):
18
+ items = []
19
+ for location, value in self.values.items():
20
+ loc = ",".join(
21
+ [
22
+ f"{ax}={int(coord) if float(coord).is_integer() else coord}"
23
+ for ax, coord in location
24
+ ]
25
+ )
26
+ items.append("%s:%i" % (loc, value))
27
+ return "(" + (" ".join(items)) + ")"
28
+
29
+ @property
30
+ def does_vary(self):
31
+ values = list(self.values.values())
32
+ return any(v != values[0] for v in values[1:])
33
+
34
+ @property
35
+ def axes_dict(self):
36
+ if not self.axes:
37
+ raise ValueError(
38
+ ".axes must be defined on variable scalar before interpolating"
39
+ )
40
+ return {ax.axisTag: ax for ax in self.axes}
41
+
42
+ def _normalized_location(self, location):
43
+ location = self.fix_location(location)
44
+ normalized_location = {}
45
+ for axtag in location.keys():
46
+ if axtag not in self.axes_dict:
47
+ raise ValueError("Unknown axis %s in %s" % (axtag, location))
48
+ axis = self.axes_dict[axtag]
49
+ normalized_location[axtag] = normalizeValue(
50
+ location[axtag], (axis.minValue, axis.defaultValue, axis.maxValue)
51
+ )
52
+
53
+ return Location(normalized_location)
54
+
55
+ def fix_location(self, location):
56
+ location = dict(location)
57
+ for tag, axis in self.axes_dict.items():
58
+ if tag not in location:
59
+ location[tag] = axis.defaultValue
60
+ return location
61
+
62
+ def add_value(self, location, value):
63
+ if self.axes:
64
+ location = self.fix_location(location)
65
+
66
+ self.values[Location(location)] = value
67
+
68
+ def fix_all_locations(self):
69
+ self.values = {
70
+ Location(self.fix_location(l)): v for l, v in self.values.items()
71
+ }
72
+
73
+ @property
74
+ def default(self):
75
+ self.fix_all_locations()
76
+ key = Location({ax.axisTag: ax.defaultValue for ax in self.axes})
77
+ if key not in self.values:
78
+ raise ValueError("Default value could not be found")
79
+ # I *guess* we could interpolate one, but I don't know how.
80
+ return self.values[key]
81
+
82
+ def value_at_location(self, location, model_cache=None, avar=None):
83
+ loc = Location(location)
84
+ if loc in self.values.keys():
85
+ return self.values[loc]
86
+ values = list(self.values.values())
87
+ loc = dict(self._normalized_location(loc))
88
+ return self.model(model_cache, avar).interpolateFromMasters(loc, values)
89
+
90
+ def model(self, model_cache=None, avar=None):
91
+ if model_cache is not None:
92
+ key = tuple(self.values.keys())
93
+ if key in model_cache:
94
+ return model_cache[key]
95
+ locations = [dict(self._normalized_location(k)) for k in self.values.keys()]
96
+ if avar is not None:
97
+ mapping = avar.segments
98
+ locations = [
99
+ {
100
+ k: piecewiseLinearMap(v, mapping[k]) if k in mapping else v
101
+ for k, v in location.items()
102
+ }
103
+ for location in locations
104
+ ]
105
+ m = VariationModel(locations)
106
+ if model_cache is not None:
107
+ model_cache[key] = m
108
+ return m
109
+
110
+ def get_deltas_and_supports(self, model_cache=None, avar=None):
111
+ values = list(self.values.values())
112
+ return self.model(model_cache, avar).getDeltasAndSupports(values)
113
+
114
+ def add_to_variation_store(self, store_builder, model_cache=None, avar=None):
115
+ deltas, supports = self.get_deltas_and_supports(model_cache, avar)
116
+ store_builder.setSupports(supports)
117
+ index = store_builder.storeDeltas(deltas)
118
+ return int(self.default), index
Scripts_Climate_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.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_to_LAI/.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
+ )