fonttools 4.58.3__cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of fonttools might be problematic. Click here for more details.

Files changed (334) hide show
  1. fontTools/__init__.py +8 -0
  2. fontTools/__main__.py +35 -0
  3. fontTools/afmLib.py +439 -0
  4. fontTools/agl.py +5233 -0
  5. fontTools/cffLib/CFF2ToCFF.py +203 -0
  6. fontTools/cffLib/CFFToCFF2.py +305 -0
  7. fontTools/cffLib/__init__.py +3694 -0
  8. fontTools/cffLib/specializer.py +927 -0
  9. fontTools/cffLib/transforms.py +490 -0
  10. fontTools/cffLib/width.py +210 -0
  11. fontTools/colorLib/__init__.py +0 -0
  12. fontTools/colorLib/builder.py +664 -0
  13. fontTools/colorLib/errors.py +2 -0
  14. fontTools/colorLib/geometry.py +143 -0
  15. fontTools/colorLib/table_builder.py +223 -0
  16. fontTools/colorLib/unbuilder.py +81 -0
  17. fontTools/config/__init__.py +90 -0
  18. fontTools/cu2qu/__init__.py +15 -0
  19. fontTools/cu2qu/__main__.py +6 -0
  20. fontTools/cu2qu/benchmark.py +54 -0
  21. fontTools/cu2qu/cli.py +198 -0
  22. fontTools/cu2qu/cu2qu.c +15545 -0
  23. fontTools/cu2qu/cu2qu.cpython-311-x86_64-linux-gnu.so +0 -0
  24. fontTools/cu2qu/cu2qu.py +531 -0
  25. fontTools/cu2qu/errors.py +77 -0
  26. fontTools/cu2qu/ufo.py +349 -0
  27. fontTools/designspaceLib/__init__.py +3338 -0
  28. fontTools/designspaceLib/__main__.py +6 -0
  29. fontTools/designspaceLib/split.py +475 -0
  30. fontTools/designspaceLib/statNames.py +260 -0
  31. fontTools/designspaceLib/types.py +147 -0
  32. fontTools/encodings/MacRoman.py +258 -0
  33. fontTools/encodings/StandardEncoding.py +258 -0
  34. fontTools/encodings/__init__.py +1 -0
  35. fontTools/encodings/codecs.py +135 -0
  36. fontTools/feaLib/__init__.py +4 -0
  37. fontTools/feaLib/__main__.py +78 -0
  38. fontTools/feaLib/ast.py +2142 -0
  39. fontTools/feaLib/builder.py +1796 -0
  40. fontTools/feaLib/error.py +22 -0
  41. fontTools/feaLib/lexer.c +17336 -0
  42. fontTools/feaLib/lexer.cpython-311-x86_64-linux-gnu.so +0 -0
  43. fontTools/feaLib/lexer.py +287 -0
  44. fontTools/feaLib/location.py +12 -0
  45. fontTools/feaLib/lookupDebugInfo.py +12 -0
  46. fontTools/feaLib/parser.py +2379 -0
  47. fontTools/feaLib/variableScalar.py +113 -0
  48. fontTools/fontBuilder.py +1014 -0
  49. fontTools/help.py +36 -0
  50. fontTools/merge/__init__.py +248 -0
  51. fontTools/merge/__main__.py +6 -0
  52. fontTools/merge/base.py +81 -0
  53. fontTools/merge/cmap.py +173 -0
  54. fontTools/merge/layout.py +526 -0
  55. fontTools/merge/options.py +85 -0
  56. fontTools/merge/tables.py +352 -0
  57. fontTools/merge/unicode.py +78 -0
  58. fontTools/merge/util.py +143 -0
  59. fontTools/misc/__init__.py +1 -0
  60. fontTools/misc/arrayTools.py +424 -0
  61. fontTools/misc/bezierTools.c +40136 -0
  62. fontTools/misc/bezierTools.cpython-311-x86_64-linux-gnu.so +0 -0
  63. fontTools/misc/bezierTools.py +1497 -0
  64. fontTools/misc/classifyTools.py +170 -0
  65. fontTools/misc/cliTools.py +53 -0
  66. fontTools/misc/configTools.py +349 -0
  67. fontTools/misc/cython.py +27 -0
  68. fontTools/misc/dictTools.py +83 -0
  69. fontTools/misc/eexec.py +119 -0
  70. fontTools/misc/encodingTools.py +72 -0
  71. fontTools/misc/etree.py +456 -0
  72. fontTools/misc/filenames.py +245 -0
  73. fontTools/misc/fixedTools.py +253 -0
  74. fontTools/misc/intTools.py +25 -0
  75. fontTools/misc/iterTools.py +12 -0
  76. fontTools/misc/lazyTools.py +42 -0
  77. fontTools/misc/loggingTools.py +543 -0
  78. fontTools/misc/macCreatorType.py +56 -0
  79. fontTools/misc/macRes.py +261 -0
  80. fontTools/misc/plistlib/__init__.py +681 -0
  81. fontTools/misc/plistlib/py.typed +0 -0
  82. fontTools/misc/psCharStrings.py +1496 -0
  83. fontTools/misc/psLib.py +398 -0
  84. fontTools/misc/psOperators.py +572 -0
  85. fontTools/misc/py23.py +96 -0
  86. fontTools/misc/roundTools.py +110 -0
  87. fontTools/misc/sstruct.py +231 -0
  88. fontTools/misc/symfont.py +242 -0
  89. fontTools/misc/testTools.py +233 -0
  90. fontTools/misc/textTools.py +154 -0
  91. fontTools/misc/timeTools.py +88 -0
  92. fontTools/misc/transform.py +516 -0
  93. fontTools/misc/treeTools.py +45 -0
  94. fontTools/misc/vector.py +147 -0
  95. fontTools/misc/visitor.py +142 -0
  96. fontTools/misc/xmlReader.py +188 -0
  97. fontTools/misc/xmlWriter.py +204 -0
  98. fontTools/mtiLib/__init__.py +1400 -0
  99. fontTools/mtiLib/__main__.py +5 -0
  100. fontTools/otlLib/__init__.py +1 -0
  101. fontTools/otlLib/builder.py +3435 -0
  102. fontTools/otlLib/error.py +11 -0
  103. fontTools/otlLib/maxContextCalc.py +96 -0
  104. fontTools/otlLib/optimize/__init__.py +53 -0
  105. fontTools/otlLib/optimize/__main__.py +6 -0
  106. fontTools/otlLib/optimize/gpos.py +439 -0
  107. fontTools/pens/__init__.py +1 -0
  108. fontTools/pens/areaPen.py +52 -0
  109. fontTools/pens/basePen.py +475 -0
  110. fontTools/pens/boundsPen.py +98 -0
  111. fontTools/pens/cairoPen.py +26 -0
  112. fontTools/pens/cocoaPen.py +26 -0
  113. fontTools/pens/cu2quPen.py +325 -0
  114. fontTools/pens/explicitClosingLinePen.py +101 -0
  115. fontTools/pens/filterPen.py +241 -0
  116. fontTools/pens/freetypePen.py +462 -0
  117. fontTools/pens/hashPointPen.py +89 -0
  118. fontTools/pens/momentsPen.c +13459 -0
  119. fontTools/pens/momentsPen.cpython-311-x86_64-linux-gnu.so +0 -0
  120. fontTools/pens/momentsPen.py +879 -0
  121. fontTools/pens/perimeterPen.py +69 -0
  122. fontTools/pens/pointInsidePen.py +192 -0
  123. fontTools/pens/pointPen.py +609 -0
  124. fontTools/pens/qtPen.py +29 -0
  125. fontTools/pens/qu2cuPen.py +105 -0
  126. fontTools/pens/quartzPen.py +43 -0
  127. fontTools/pens/recordingPen.py +335 -0
  128. fontTools/pens/reportLabPen.py +79 -0
  129. fontTools/pens/reverseContourPen.py +96 -0
  130. fontTools/pens/roundingPen.py +130 -0
  131. fontTools/pens/statisticsPen.py +312 -0
  132. fontTools/pens/svgPathPen.py +310 -0
  133. fontTools/pens/t2CharStringPen.py +88 -0
  134. fontTools/pens/teePen.py +55 -0
  135. fontTools/pens/transformPen.py +115 -0
  136. fontTools/pens/ttGlyphPen.py +335 -0
  137. fontTools/pens/wxPen.py +29 -0
  138. fontTools/qu2cu/__init__.py +15 -0
  139. fontTools/qu2cu/__main__.py +7 -0
  140. fontTools/qu2cu/benchmark.py +56 -0
  141. fontTools/qu2cu/cli.py +125 -0
  142. fontTools/qu2cu/qu2cu.c +16738 -0
  143. fontTools/qu2cu/qu2cu.cpython-311-x86_64-linux-gnu.so +0 -0
  144. fontTools/qu2cu/qu2cu.py +405 -0
  145. fontTools/subset/__init__.py +3929 -0
  146. fontTools/subset/__main__.py +6 -0
  147. fontTools/subset/cff.py +184 -0
  148. fontTools/subset/svg.py +253 -0
  149. fontTools/subset/util.py +25 -0
  150. fontTools/svgLib/__init__.py +3 -0
  151. fontTools/svgLib/path/__init__.py +65 -0
  152. fontTools/svgLib/path/arc.py +154 -0
  153. fontTools/svgLib/path/parser.py +322 -0
  154. fontTools/svgLib/path/shapes.py +183 -0
  155. fontTools/t1Lib/__init__.py +648 -0
  156. fontTools/tfmLib.py +460 -0
  157. fontTools/ttLib/__init__.py +30 -0
  158. fontTools/ttLib/__main__.py +148 -0
  159. fontTools/ttLib/macUtils.py +54 -0
  160. fontTools/ttLib/removeOverlaps.py +393 -0
  161. fontTools/ttLib/reorderGlyphs.py +285 -0
  162. fontTools/ttLib/scaleUpem.py +436 -0
  163. fontTools/ttLib/sfnt.py +662 -0
  164. fontTools/ttLib/standardGlyphOrder.py +271 -0
  165. fontTools/ttLib/tables/B_A_S_E_.py +14 -0
  166. fontTools/ttLib/tables/BitmapGlyphMetrics.py +64 -0
  167. fontTools/ttLib/tables/C_B_D_T_.py +113 -0
  168. fontTools/ttLib/tables/C_B_L_C_.py +19 -0
  169. fontTools/ttLib/tables/C_F_F_.py +61 -0
  170. fontTools/ttLib/tables/C_F_F__2.py +26 -0
  171. fontTools/ttLib/tables/C_O_L_R_.py +165 -0
  172. fontTools/ttLib/tables/C_P_A_L_.py +305 -0
  173. fontTools/ttLib/tables/D_S_I_G_.py +158 -0
  174. fontTools/ttLib/tables/D__e_b_g.py +35 -0
  175. fontTools/ttLib/tables/DefaultTable.py +49 -0
  176. fontTools/ttLib/tables/E_B_D_T_.py +835 -0
  177. fontTools/ttLib/tables/E_B_L_C_.py +718 -0
  178. fontTools/ttLib/tables/F_F_T_M_.py +52 -0
  179. fontTools/ttLib/tables/F__e_a_t.py +149 -0
  180. fontTools/ttLib/tables/G_D_E_F_.py +13 -0
  181. fontTools/ttLib/tables/G_M_A_P_.py +148 -0
  182. fontTools/ttLib/tables/G_P_K_G_.py +133 -0
  183. fontTools/ttLib/tables/G_P_O_S_.py +14 -0
  184. fontTools/ttLib/tables/G_S_U_B_.py +13 -0
  185. fontTools/ttLib/tables/G_V_A_R_.py +5 -0
  186. fontTools/ttLib/tables/G__l_a_t.py +235 -0
  187. fontTools/ttLib/tables/G__l_o_c.py +85 -0
  188. fontTools/ttLib/tables/H_V_A_R_.py +13 -0
  189. fontTools/ttLib/tables/J_S_T_F_.py +13 -0
  190. fontTools/ttLib/tables/L_T_S_H_.py +58 -0
  191. fontTools/ttLib/tables/M_A_T_H_.py +13 -0
  192. fontTools/ttLib/tables/M_E_T_A_.py +352 -0
  193. fontTools/ttLib/tables/M_V_A_R_.py +13 -0
  194. fontTools/ttLib/tables/O_S_2f_2.py +752 -0
  195. fontTools/ttLib/tables/S_I_N_G_.py +99 -0
  196. fontTools/ttLib/tables/S_T_A_T_.py +15 -0
  197. fontTools/ttLib/tables/S_V_G_.py +223 -0
  198. fontTools/ttLib/tables/S__i_l_f.py +1040 -0
  199. fontTools/ttLib/tables/S__i_l_l.py +92 -0
  200. fontTools/ttLib/tables/T_S_I_B_.py +13 -0
  201. fontTools/ttLib/tables/T_S_I_C_.py +14 -0
  202. fontTools/ttLib/tables/T_S_I_D_.py +13 -0
  203. fontTools/ttLib/tables/T_S_I_J_.py +13 -0
  204. fontTools/ttLib/tables/T_S_I_P_.py +13 -0
  205. fontTools/ttLib/tables/T_S_I_S_.py +13 -0
  206. fontTools/ttLib/tables/T_S_I_V_.py +26 -0
  207. fontTools/ttLib/tables/T_S_I__0.py +70 -0
  208. fontTools/ttLib/tables/T_S_I__1.py +166 -0
  209. fontTools/ttLib/tables/T_S_I__2.py +17 -0
  210. fontTools/ttLib/tables/T_S_I__3.py +22 -0
  211. fontTools/ttLib/tables/T_S_I__5.py +60 -0
  212. fontTools/ttLib/tables/T_T_F_A_.py +14 -0
  213. fontTools/ttLib/tables/TupleVariation.py +884 -0
  214. fontTools/ttLib/tables/V_A_R_C_.py +12 -0
  215. fontTools/ttLib/tables/V_D_M_X_.py +249 -0
  216. fontTools/ttLib/tables/V_O_R_G_.py +165 -0
  217. fontTools/ttLib/tables/V_V_A_R_.py +13 -0
  218. fontTools/ttLib/tables/__init__.py +98 -0
  219. fontTools/ttLib/tables/_a_n_k_r.py +15 -0
  220. fontTools/ttLib/tables/_a_v_a_r.py +191 -0
  221. fontTools/ttLib/tables/_b_s_l_n.py +15 -0
  222. fontTools/ttLib/tables/_c_i_d_g.py +24 -0
  223. fontTools/ttLib/tables/_c_m_a_p.py +1591 -0
  224. fontTools/ttLib/tables/_c_v_a_r.py +94 -0
  225. fontTools/ttLib/tables/_c_v_t.py +57 -0
  226. fontTools/ttLib/tables/_f_e_a_t.py +15 -0
  227. fontTools/ttLib/tables/_f_p_g_m.py +62 -0
  228. fontTools/ttLib/tables/_f_v_a_r.py +261 -0
  229. fontTools/ttLib/tables/_g_a_s_p.py +63 -0
  230. fontTools/ttLib/tables/_g_c_i_d.py +13 -0
  231. fontTools/ttLib/tables/_g_l_y_f.py +2312 -0
  232. fontTools/ttLib/tables/_g_v_a_r.py +337 -0
  233. fontTools/ttLib/tables/_h_d_m_x.py +127 -0
  234. fontTools/ttLib/tables/_h_e_a_d.py +130 -0
  235. fontTools/ttLib/tables/_h_h_e_a.py +147 -0
  236. fontTools/ttLib/tables/_h_m_t_x.py +160 -0
  237. fontTools/ttLib/tables/_k_e_r_n.py +289 -0
  238. fontTools/ttLib/tables/_l_c_a_r.py +13 -0
  239. fontTools/ttLib/tables/_l_o_c_a.py +70 -0
  240. fontTools/ttLib/tables/_l_t_a_g.py +72 -0
  241. fontTools/ttLib/tables/_m_a_x_p.py +147 -0
  242. fontTools/ttLib/tables/_m_e_t_a.py +112 -0
  243. fontTools/ttLib/tables/_m_o_r_t.py +14 -0
  244. fontTools/ttLib/tables/_m_o_r_x.py +15 -0
  245. fontTools/ttLib/tables/_n_a_m_e.py +1237 -0
  246. fontTools/ttLib/tables/_o_p_b_d.py +14 -0
  247. fontTools/ttLib/tables/_p_o_s_t.py +320 -0
  248. fontTools/ttLib/tables/_p_r_e_p.py +16 -0
  249. fontTools/ttLib/tables/_p_r_o_p.py +12 -0
  250. fontTools/ttLib/tables/_s_b_i_x.py +129 -0
  251. fontTools/ttLib/tables/_t_r_a_k.py +332 -0
  252. fontTools/ttLib/tables/_v_h_e_a.py +139 -0
  253. fontTools/ttLib/tables/_v_m_t_x.py +19 -0
  254. fontTools/ttLib/tables/asciiTable.py +20 -0
  255. fontTools/ttLib/tables/grUtils.py +92 -0
  256. fontTools/ttLib/tables/otBase.py +1466 -0
  257. fontTools/ttLib/tables/otConverters.py +2068 -0
  258. fontTools/ttLib/tables/otData.py +6400 -0
  259. fontTools/ttLib/tables/otTables.py +2708 -0
  260. fontTools/ttLib/tables/otTraverse.py +163 -0
  261. fontTools/ttLib/tables/sbixGlyph.py +149 -0
  262. fontTools/ttLib/tables/sbixStrike.py +177 -0
  263. fontTools/ttLib/tables/table_API_readme.txt +91 -0
  264. fontTools/ttLib/tables/ttProgram.py +594 -0
  265. fontTools/ttLib/ttCollection.py +125 -0
  266. fontTools/ttLib/ttFont.py +1157 -0
  267. fontTools/ttLib/ttGlyphSet.py +490 -0
  268. fontTools/ttLib/ttVisitor.py +32 -0
  269. fontTools/ttLib/woff2.py +1683 -0
  270. fontTools/ttx.py +479 -0
  271. fontTools/ufoLib/__init__.py +2477 -0
  272. fontTools/ufoLib/converters.py +398 -0
  273. fontTools/ufoLib/errors.py +30 -0
  274. fontTools/ufoLib/etree.py +6 -0
  275. fontTools/ufoLib/filenames.py +346 -0
  276. fontTools/ufoLib/glifLib.py +2029 -0
  277. fontTools/ufoLib/kerning.py +121 -0
  278. fontTools/ufoLib/plistlib.py +47 -0
  279. fontTools/ufoLib/pointPen.py +6 -0
  280. fontTools/ufoLib/utils.py +79 -0
  281. fontTools/ufoLib/validators.py +1186 -0
  282. fontTools/unicode.py +50 -0
  283. fontTools/unicodedata/Blocks.py +801 -0
  284. fontTools/unicodedata/Mirrored.py +446 -0
  285. fontTools/unicodedata/OTTags.py +50 -0
  286. fontTools/unicodedata/ScriptExtensions.py +826 -0
  287. fontTools/unicodedata/Scripts.py +3617 -0
  288. fontTools/unicodedata/__init__.py +302 -0
  289. fontTools/varLib/__init__.py +1517 -0
  290. fontTools/varLib/__main__.py +6 -0
  291. fontTools/varLib/avar.py +260 -0
  292. fontTools/varLib/avarPlanner.py +1004 -0
  293. fontTools/varLib/builder.py +215 -0
  294. fontTools/varLib/cff.py +631 -0
  295. fontTools/varLib/errors.py +219 -0
  296. fontTools/varLib/featureVars.py +695 -0
  297. fontTools/varLib/hvar.py +113 -0
  298. fontTools/varLib/instancer/__init__.py +1946 -0
  299. fontTools/varLib/instancer/__main__.py +5 -0
  300. fontTools/varLib/instancer/featureVars.py +190 -0
  301. fontTools/varLib/instancer/names.py +388 -0
  302. fontTools/varLib/instancer/solver.py +309 -0
  303. fontTools/varLib/interpolatable.py +1209 -0
  304. fontTools/varLib/interpolatableHelpers.py +396 -0
  305. fontTools/varLib/interpolatablePlot.py +1269 -0
  306. fontTools/varLib/interpolatableTestContourOrder.py +82 -0
  307. fontTools/varLib/interpolatableTestStartingPoint.py +107 -0
  308. fontTools/varLib/interpolate_layout.py +124 -0
  309. fontTools/varLib/iup.c +19830 -0
  310. fontTools/varLib/iup.cpython-311-x86_64-linux-gnu.so +0 -0
  311. fontTools/varLib/iup.py +490 -0
  312. fontTools/varLib/merger.py +1717 -0
  313. fontTools/varLib/models.py +642 -0
  314. fontTools/varLib/multiVarStore.py +253 -0
  315. fontTools/varLib/mutator.py +518 -0
  316. fontTools/varLib/mvar.py +40 -0
  317. fontTools/varLib/plot.py +238 -0
  318. fontTools/varLib/stat.py +149 -0
  319. fontTools/varLib/varStore.py +739 -0
  320. fontTools/voltLib/__init__.py +5 -0
  321. fontTools/voltLib/__main__.py +206 -0
  322. fontTools/voltLib/ast.py +452 -0
  323. fontTools/voltLib/error.py +12 -0
  324. fontTools/voltLib/lexer.py +99 -0
  325. fontTools/voltLib/parser.py +664 -0
  326. fontTools/voltLib/voltToFea.py +911 -0
  327. fonttools-4.58.3.data/data/share/man/man1/ttx.1 +225 -0
  328. fonttools-4.58.3.dist-info/METADATA +2133 -0
  329. fonttools-4.58.3.dist-info/RECORD +334 -0
  330. fonttools-4.58.3.dist-info/WHEEL +6 -0
  331. fonttools-4.58.3.dist-info/entry_points.txt +5 -0
  332. fonttools-4.58.3.dist-info/licenses/LICENSE +21 -0
  333. fonttools-4.58.3.dist-info/licenses/LICENSE.external +359 -0
  334. fonttools-4.58.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1796 @@
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.varStore import OnlineVarStoreBuilder
36
+ from fontTools.varLib.builder import buildVarDevTable
37
+ from fontTools.varLib.featureVars import addFeatureVariationsRaw
38
+ from fontTools.varLib.models import normalizeValue, piecewiseLinearMap
39
+ from collections import defaultdict
40
+ import copy
41
+ import itertools
42
+ from io import StringIO
43
+ import logging
44
+ import warnings
45
+ import os
46
+
47
+
48
+ log = logging.getLogger(__name__)
49
+
50
+
51
+ def addOpenTypeFeatures(font, featurefile, tables=None, debug=False):
52
+ """Add features from a file to a font. Note that this replaces any features
53
+ currently present.
54
+
55
+ Args:
56
+ font (feaLib.ttLib.TTFont): The font object.
57
+ featurefile: Either a path or file object (in which case we
58
+ parse it into an AST), or a pre-parsed AST instance.
59
+ tables: If passed, restrict the set of affected tables to those in the
60
+ list.
61
+ debug: Whether to add source debugging information to the font in the
62
+ ``Debg`` table
63
+
64
+ """
65
+ builder = Builder(font, featurefile)
66
+ builder.build(tables=tables, debug=debug)
67
+
68
+
69
+ def addOpenTypeFeaturesFromString(
70
+ font, features, filename=None, tables=None, debug=False
71
+ ):
72
+ """Add features from a string to a font. Note that this replaces any
73
+ features currently present.
74
+
75
+ Args:
76
+ font (feaLib.ttLib.TTFont): The font object.
77
+ features: A string containing feature code.
78
+ filename: The directory containing ``filename`` is used as the root of
79
+ relative ``include()`` paths; if ``None`` is provided, the current
80
+ directory is assumed.
81
+ tables: If passed, restrict the set of affected tables to those in the
82
+ list.
83
+ debug: Whether to add source debugging information to the font in the
84
+ ``Debg`` table
85
+
86
+ """
87
+
88
+ featurefile = StringIO(tostr(features))
89
+ if filename:
90
+ featurefile.name = filename
91
+ addOpenTypeFeatures(font, featurefile, tables=tables, debug=debug)
92
+
93
+
94
+ class Builder(object):
95
+ supportedTables = frozenset(
96
+ Tag(tag)
97
+ for tag in [
98
+ "BASE",
99
+ "GDEF",
100
+ "GPOS",
101
+ "GSUB",
102
+ "OS/2",
103
+ "head",
104
+ "hhea",
105
+ "name",
106
+ "vhea",
107
+ "STAT",
108
+ ]
109
+ )
110
+
111
+ def __init__(self, font, featurefile):
112
+ self.font = font
113
+ # 'featurefile' can be either a path or file object (in which case we
114
+ # parse it into an AST), or a pre-parsed AST instance
115
+ if isinstance(featurefile, FeatureFile):
116
+ self.parseTree, self.file = featurefile, None
117
+ else:
118
+ self.parseTree, self.file = None, featurefile
119
+ self.glyphMap = font.getReverseGlyphMap()
120
+ self.varstorebuilder = None
121
+ if "fvar" in font:
122
+ self.axes = font["fvar"].axes
123
+ self.varstorebuilder = OnlineVarStoreBuilder(
124
+ [ax.axisTag for ax in self.axes]
125
+ )
126
+ self.default_language_systems_ = set()
127
+ self.script_ = None
128
+ self.lookupflag_ = 0
129
+ self.lookupflag_markFilterSet_ = None
130
+ self.use_extension_ = False
131
+ self.language_systems = set()
132
+ self.seen_non_DFLT_script_ = False
133
+ self.named_lookups_ = {}
134
+ self.cur_lookup_ = None
135
+ self.cur_lookup_name_ = None
136
+ self.cur_feature_name_ = None
137
+ self.lookups_ = []
138
+ self.lookup_locations = {"GSUB": {}, "GPOS": {}}
139
+ self.features_ = {} # ('latn', 'DEU ', 'smcp') --> [LookupBuilder*]
140
+ self.required_features_ = {} # ('latn', 'DEU ') --> 'scmp'
141
+ self.feature_variations_ = {}
142
+ # for feature 'aalt'
143
+ self.aalt_features_ = [] # [(location, featureName)*], for 'aalt'
144
+ self.aalt_location_ = None
145
+ self.aalt_alternates_ = {}
146
+ self.aalt_use_extension_ = False
147
+ # for 'featureNames'
148
+ self.featureNames_ = set()
149
+ self.featureNames_ids_ = {}
150
+ # for 'cvParameters'
151
+ self.cv_parameters_ = set()
152
+ self.cv_parameters_ids_ = {}
153
+ self.cv_num_named_params_ = {}
154
+ self.cv_characters_ = defaultdict(list)
155
+ # for feature 'size'
156
+ self.size_parameters_ = None
157
+ # for table 'head'
158
+ self.fontRevision_ = None # 2.71
159
+ # for table 'name'
160
+ self.names_ = []
161
+ # for table 'BASE'
162
+ self.base_horiz_axis_ = None
163
+ self.base_vert_axis_ = None
164
+ # for table 'GDEF'
165
+ self.attachPoints_ = {} # "a" --> {3, 7}
166
+ self.ligCaretCoords_ = {} # "f_f_i" --> {300, 600}
167
+ self.ligCaretPoints_ = {} # "f_f_i" --> {3, 7}
168
+ self.glyphClassDefs_ = {} # "fi" --> (2, (file, line, column))
169
+ self.markAttach_ = {} # "acute" --> (4, (file, line, column))
170
+ self.markAttachClassID_ = {} # frozenset({"acute", "grave"}) --> 4
171
+ self.markFilterSets_ = {} # frozenset({"acute", "grave"}) --> 4
172
+ # for table 'OS/2'
173
+ self.os2_ = {}
174
+ # for table 'hhea'
175
+ self.hhea_ = {}
176
+ # for table 'vhea'
177
+ self.vhea_ = {}
178
+ # for table 'STAT'
179
+ self.stat_ = {}
180
+ # for conditionsets
181
+ self.conditionsets_ = {}
182
+ # We will often use exactly the same locations (i.e. the font's masters)
183
+ # for a large number of variable scalars. Instead of creating a model
184
+ # for each, let's share the models.
185
+ self.model_cache = {}
186
+
187
+ def build(self, tables=None, debug=False):
188
+ if self.parseTree is None:
189
+ self.parseTree = Parser(self.file, self.glyphMap).parse()
190
+ self.parseTree.build(self)
191
+ # by default, build all the supported tables
192
+ if tables is None:
193
+ tables = self.supportedTables
194
+ else:
195
+ tables = frozenset(tables)
196
+ unsupported = tables - self.supportedTables
197
+ if unsupported:
198
+ unsupported_string = ", ".join(sorted(unsupported))
199
+ raise NotImplementedError(
200
+ "The following tables were requested but are unsupported: "
201
+ f"{unsupported_string}."
202
+ )
203
+ if "GSUB" in tables:
204
+ self.build_feature_aalt_()
205
+ if "head" in tables:
206
+ self.build_head()
207
+ if "hhea" in tables:
208
+ self.build_hhea()
209
+ if "vhea" in tables:
210
+ self.build_vhea()
211
+ if "name" in tables:
212
+ self.build_name()
213
+ if "OS/2" in tables:
214
+ self.build_OS_2()
215
+ if "STAT" in tables:
216
+ self.build_STAT()
217
+ for tag in ("GPOS", "GSUB"):
218
+ if tag not in tables:
219
+ continue
220
+ table = self.makeTable(tag)
221
+ if self.feature_variations_:
222
+ self.makeFeatureVariations(table, tag)
223
+ if (
224
+ table.ScriptList.ScriptCount > 0
225
+ or table.FeatureList.FeatureCount > 0
226
+ or table.LookupList.LookupCount > 0
227
+ ):
228
+ fontTable = self.font[tag] = newTable(tag)
229
+ fontTable.table = table
230
+ elif tag in self.font:
231
+ del self.font[tag]
232
+ if any(tag in self.font for tag in ("GPOS", "GSUB")) and "OS/2" in self.font:
233
+ self.font["OS/2"].usMaxContext = maxCtxFont(self.font)
234
+ if "GDEF" in tables:
235
+ gdef = self.buildGDEF()
236
+ if gdef:
237
+ self.font["GDEF"] = gdef
238
+ elif "GDEF" in self.font:
239
+ del self.font["GDEF"]
240
+ if "BASE" in tables:
241
+ base = self.buildBASE()
242
+ if base:
243
+ self.font["BASE"] = base
244
+ elif "BASE" in self.font:
245
+ del self.font["BASE"]
246
+ if debug or os.environ.get(LOOKUP_DEBUG_ENV_VAR):
247
+ self.buildDebg()
248
+
249
+ def get_chained_lookup_(self, location, builder_class):
250
+ result = builder_class(self.font, location)
251
+ result.lookupflag = self.lookupflag_
252
+ result.markFilterSet = self.lookupflag_markFilterSet_
253
+ result.extension = self.use_extension_
254
+ self.lookups_.append(result)
255
+ return result
256
+
257
+ def add_lookup_to_feature_(self, lookup, feature_name):
258
+ for script, lang in self.language_systems:
259
+ key = (script, lang, feature_name)
260
+ self.features_.setdefault(key, []).append(lookup)
261
+
262
+ def get_lookup_(self, location, builder_class):
263
+ if (
264
+ self.cur_lookup_
265
+ and type(self.cur_lookup_) == builder_class
266
+ and self.cur_lookup_.lookupflag == self.lookupflag_
267
+ and self.cur_lookup_.markFilterSet == self.lookupflag_markFilterSet_
268
+ ):
269
+ return self.cur_lookup_
270
+ if self.cur_lookup_name_ and self.cur_lookup_:
271
+ raise FeatureLibError(
272
+ "Within a named lookup block, all rules must be of "
273
+ "the same lookup type and flag",
274
+ location,
275
+ )
276
+ self.cur_lookup_ = builder_class(self.font, location)
277
+ self.cur_lookup_.lookupflag = self.lookupflag_
278
+ self.cur_lookup_.markFilterSet = self.lookupflag_markFilterSet_
279
+ self.cur_lookup_.extension = self.use_extension_
280
+ self.lookups_.append(self.cur_lookup_)
281
+ if self.cur_lookup_name_:
282
+ # We are starting a lookup rule inside a named lookup block.
283
+ self.named_lookups_[self.cur_lookup_name_] = self.cur_lookup_
284
+ if self.cur_feature_name_:
285
+ # We are starting a lookup rule inside a feature. This includes
286
+ # lookup rules inside named lookups inside features.
287
+ self.add_lookup_to_feature_(self.cur_lookup_, self.cur_feature_name_)
288
+ return self.cur_lookup_
289
+
290
+ def build_feature_aalt_(self):
291
+ if not self.aalt_features_ and not self.aalt_alternates_:
292
+ return
293
+ # > alternate glyphs will be sorted in the order that the source features
294
+ # > are named in the aalt definition, not the order of the feature definitions
295
+ # > in the file. Alternates defined explicitly ... will precede all others.
296
+ # https://github.com/fonttools/fonttools/issues/836
297
+ alternates = {g: list(a) for g, a in self.aalt_alternates_.items()}
298
+ for location, name in self.aalt_features_ + [(None, "aalt")]:
299
+ feature = [
300
+ (script, lang, feature, lookups)
301
+ for (script, lang, feature), lookups in self.features_.items()
302
+ if feature == name
303
+ ]
304
+ # "aalt" does not have to specify its own lookups, but it might.
305
+ if not feature and name != "aalt":
306
+ warnings.warn("%s: Feature %s has not been defined" % (location, name))
307
+ continue
308
+ for script, lang, feature, lookups in feature:
309
+ for lookuplist in lookups:
310
+ if not isinstance(lookuplist, list):
311
+ lookuplist = [lookuplist]
312
+ for lookup in lookuplist:
313
+ for glyph, alts in lookup.getAlternateGlyphs().items():
314
+ alts_for_glyph = alternates.setdefault(glyph, [])
315
+ alts_for_glyph.extend(
316
+ g for g in alts if g not in alts_for_glyph
317
+ )
318
+ single = {
319
+ glyph: repl[0] for glyph, repl in alternates.items() if len(repl) == 1
320
+ }
321
+ multi = {glyph: repl for glyph, repl in alternates.items() if len(repl) > 1}
322
+ if not single and not multi:
323
+ return
324
+ self.features_ = {
325
+ (script, lang, feature): lookups
326
+ for (script, lang, feature), lookups in self.features_.items()
327
+ if feature != "aalt"
328
+ }
329
+ old_lookups = self.lookups_
330
+ self.lookups_ = []
331
+ self.start_feature(self.aalt_location_, "aalt", self.aalt_use_extension_)
332
+ if single:
333
+ single_lookup = self.get_lookup_(location, SingleSubstBuilder)
334
+ single_lookup.mapping = single
335
+ if multi:
336
+ multi_lookup = self.get_lookup_(location, AlternateSubstBuilder)
337
+ multi_lookup.alternates = multi
338
+ self.end_feature()
339
+ self.lookups_.extend(old_lookups)
340
+
341
+ def build_head(self):
342
+ if not self.fontRevision_:
343
+ return
344
+ table = self.font.get("head")
345
+ if not table: # this only happens for unit tests
346
+ table = self.font["head"] = newTable("head")
347
+ table.decompile(b"\0" * 54, self.font)
348
+ table.tableVersion = 1.0
349
+ table.magicNumber = 0x5F0F3CF5
350
+ table.created = table.modified = 3406620153 # 2011-12-13 11:22:33
351
+ table.fontRevision = self.fontRevision_
352
+
353
+ def build_hhea(self):
354
+ if not self.hhea_:
355
+ return
356
+ table = self.font.get("hhea")
357
+ if not table: # this only happens for unit tests
358
+ table = self.font["hhea"] = newTable("hhea")
359
+ table.decompile(b"\0" * 36, self.font)
360
+ table.tableVersion = 0x00010000
361
+ if "caretoffset" in self.hhea_:
362
+ table.caretOffset = self.hhea_["caretoffset"]
363
+ if "ascender" in self.hhea_:
364
+ table.ascent = self.hhea_["ascender"]
365
+ if "descender" in self.hhea_:
366
+ table.descent = self.hhea_["descender"]
367
+ if "linegap" in self.hhea_:
368
+ table.lineGap = self.hhea_["linegap"]
369
+
370
+ def build_vhea(self):
371
+ if not self.vhea_:
372
+ return
373
+ table = self.font.get("vhea")
374
+ if not table: # this only happens for unit tests
375
+ table = self.font["vhea"] = newTable("vhea")
376
+ table.decompile(b"\0" * 36, self.font)
377
+ table.tableVersion = 0x00011000
378
+ if "verttypoascender" in self.vhea_:
379
+ table.ascent = self.vhea_["verttypoascender"]
380
+ if "verttypodescender" in self.vhea_:
381
+ table.descent = self.vhea_["verttypodescender"]
382
+ if "verttypolinegap" in self.vhea_:
383
+ table.lineGap = self.vhea_["verttypolinegap"]
384
+
385
+ def get_user_name_id(self, table):
386
+ # Try to find first unused font-specific name id
387
+ nameIDs = [name.nameID for name in table.names]
388
+ for user_name_id in range(256, 32767):
389
+ if user_name_id not in nameIDs:
390
+ return user_name_id
391
+
392
+ def buildFeatureParams(self, tag):
393
+ params = None
394
+ if tag == "size":
395
+ params = otTables.FeatureParamsSize()
396
+ (
397
+ params.DesignSize,
398
+ params.SubfamilyID,
399
+ params.RangeStart,
400
+ params.RangeEnd,
401
+ ) = self.size_parameters_
402
+ if tag in self.featureNames_ids_:
403
+ params.SubfamilyNameID = self.featureNames_ids_[tag]
404
+ else:
405
+ params.SubfamilyNameID = 0
406
+ elif tag in self.featureNames_:
407
+ if not self.featureNames_ids_:
408
+ # name table wasn't selected among the tables to build; skip
409
+ pass
410
+ else:
411
+ assert tag in self.featureNames_ids_
412
+ params = otTables.FeatureParamsStylisticSet()
413
+ params.Version = 0
414
+ params.UINameID = self.featureNames_ids_[tag]
415
+ elif tag in self.cv_parameters_:
416
+ params = otTables.FeatureParamsCharacterVariants()
417
+ params.Format = 0
418
+ params.FeatUILabelNameID = self.cv_parameters_ids_.get(
419
+ (tag, "FeatUILabelNameID"), 0
420
+ )
421
+ params.FeatUITooltipTextNameID = self.cv_parameters_ids_.get(
422
+ (tag, "FeatUITooltipTextNameID"), 0
423
+ )
424
+ params.SampleTextNameID = self.cv_parameters_ids_.get(
425
+ (tag, "SampleTextNameID"), 0
426
+ )
427
+ params.NumNamedParameters = self.cv_num_named_params_.get(tag, 0)
428
+ params.FirstParamUILabelNameID = self.cv_parameters_ids_.get(
429
+ (tag, "ParamUILabelNameID_0"), 0
430
+ )
431
+ params.CharCount = len(self.cv_characters_[tag])
432
+ params.Character = self.cv_characters_[tag]
433
+ return params
434
+
435
+ def build_name(self):
436
+ if not self.names_:
437
+ return
438
+ table = self.font.get("name")
439
+ if not table: # this only happens for unit tests
440
+ table = self.font["name"] = newTable("name")
441
+ table.names = []
442
+ for name in self.names_:
443
+ nameID, platformID, platEncID, langID, string = name
444
+ # For featureNames block, nameID is 'feature tag'
445
+ # For cvParameters blocks, nameID is ('feature tag', 'block name')
446
+ if not isinstance(nameID, int):
447
+ tag = nameID
448
+ if tag in self.featureNames_:
449
+ if tag not in self.featureNames_ids_:
450
+ self.featureNames_ids_[tag] = self.get_user_name_id(table)
451
+ assert self.featureNames_ids_[tag] is not None
452
+ nameID = self.featureNames_ids_[tag]
453
+ elif tag[0] in self.cv_parameters_:
454
+ if tag not in self.cv_parameters_ids_:
455
+ self.cv_parameters_ids_[tag] = self.get_user_name_id(table)
456
+ assert self.cv_parameters_ids_[tag] is not None
457
+ nameID = self.cv_parameters_ids_[tag]
458
+ table.setName(string, nameID, platformID, platEncID, langID)
459
+ table.names.sort()
460
+
461
+ def build_OS_2(self):
462
+ if not self.os2_:
463
+ return
464
+ table = self.font.get("OS/2")
465
+ if not table: # this only happens for unit tests
466
+ table = self.font["OS/2"] = newTable("OS/2")
467
+ data = b"\0" * sstruct.calcsize(getTableModule("OS/2").OS2_format_0)
468
+ table.decompile(data, self.font)
469
+ version = 0
470
+ if "fstype" in self.os2_:
471
+ table.fsType = self.os2_["fstype"]
472
+ if "panose" in self.os2_:
473
+ panose = getTableModule("OS/2").Panose()
474
+ (
475
+ panose.bFamilyType,
476
+ panose.bSerifStyle,
477
+ panose.bWeight,
478
+ panose.bProportion,
479
+ panose.bContrast,
480
+ panose.bStrokeVariation,
481
+ panose.bArmStyle,
482
+ panose.bLetterForm,
483
+ panose.bMidline,
484
+ panose.bXHeight,
485
+ ) = self.os2_["panose"]
486
+ table.panose = panose
487
+ if "typoascender" in self.os2_:
488
+ table.sTypoAscender = self.os2_["typoascender"]
489
+ if "typodescender" in self.os2_:
490
+ table.sTypoDescender = self.os2_["typodescender"]
491
+ if "typolinegap" in self.os2_:
492
+ table.sTypoLineGap = self.os2_["typolinegap"]
493
+ if "winascent" in self.os2_:
494
+ table.usWinAscent = self.os2_["winascent"]
495
+ if "windescent" in self.os2_:
496
+ table.usWinDescent = self.os2_["windescent"]
497
+ if "vendor" in self.os2_:
498
+ table.achVendID = safeEval("'''" + self.os2_["vendor"] + "'''")
499
+ if "weightclass" in self.os2_:
500
+ table.usWeightClass = self.os2_["weightclass"]
501
+ if "widthclass" in self.os2_:
502
+ table.usWidthClass = self.os2_["widthclass"]
503
+ if "unicoderange" in self.os2_:
504
+ table.setUnicodeRanges(self.os2_["unicoderange"])
505
+ if "codepagerange" in self.os2_:
506
+ pages = self.build_codepages_(self.os2_["codepagerange"])
507
+ table.ulCodePageRange1, table.ulCodePageRange2 = pages
508
+ version = 1
509
+ if "xheight" in self.os2_:
510
+ table.sxHeight = self.os2_["xheight"]
511
+ version = 2
512
+ if "capheight" in self.os2_:
513
+ table.sCapHeight = self.os2_["capheight"]
514
+ version = 2
515
+ if "loweropsize" in self.os2_:
516
+ table.usLowerOpticalPointSize = self.os2_["loweropsize"]
517
+ version = 5
518
+ if "upperopsize" in self.os2_:
519
+ table.usUpperOpticalPointSize = self.os2_["upperopsize"]
520
+ version = 5
521
+
522
+ def checkattr(table, attrs):
523
+ for attr in attrs:
524
+ if not hasattr(table, attr):
525
+ setattr(table, attr, 0)
526
+
527
+ table.version = max(version, table.version)
528
+ # this only happens for unit tests
529
+ if version >= 1:
530
+ checkattr(table, ("ulCodePageRange1", "ulCodePageRange2"))
531
+ if version >= 2:
532
+ checkattr(
533
+ table,
534
+ (
535
+ "sxHeight",
536
+ "sCapHeight",
537
+ "usDefaultChar",
538
+ "usBreakChar",
539
+ "usMaxContext",
540
+ ),
541
+ )
542
+ if version >= 5:
543
+ checkattr(table, ("usLowerOpticalPointSize", "usUpperOpticalPointSize"))
544
+
545
+ def setElidedFallbackName(self, value, location):
546
+ # ElidedFallbackName is a convenience method for setting
547
+ # ElidedFallbackNameID so only one can be allowed
548
+ for token in ("ElidedFallbackName", "ElidedFallbackNameID"):
549
+ if token in self.stat_:
550
+ raise FeatureLibError(
551
+ f"{token} is already set.",
552
+ location,
553
+ )
554
+ if isinstance(value, int):
555
+ self.stat_["ElidedFallbackNameID"] = value
556
+ elif isinstance(value, list):
557
+ self.stat_["ElidedFallbackName"] = value
558
+ else:
559
+ raise AssertionError(value)
560
+
561
+ def addDesignAxis(self, designAxis, location):
562
+ if "DesignAxes" not in self.stat_:
563
+ self.stat_["DesignAxes"] = []
564
+ if designAxis.tag in (r.tag for r in self.stat_["DesignAxes"]):
565
+ raise FeatureLibError(
566
+ f'DesignAxis already defined for tag "{designAxis.tag}".',
567
+ location,
568
+ )
569
+ if designAxis.axisOrder in (r.axisOrder for r in self.stat_["DesignAxes"]):
570
+ raise FeatureLibError(
571
+ f"DesignAxis already defined for axis number {designAxis.axisOrder}.",
572
+ location,
573
+ )
574
+ self.stat_["DesignAxes"].append(designAxis)
575
+
576
+ def addAxisValueRecord(self, axisValueRecord, location):
577
+ if "AxisValueRecords" not in self.stat_:
578
+ self.stat_["AxisValueRecords"] = []
579
+ # Check for duplicate AxisValueRecords
580
+ for record_ in self.stat_["AxisValueRecords"]:
581
+ if (
582
+ {n.asFea() for n in record_.names}
583
+ == {n.asFea() for n in axisValueRecord.names}
584
+ and {n.asFea() for n in record_.locations}
585
+ == {n.asFea() for n in axisValueRecord.locations}
586
+ and record_.flags == axisValueRecord.flags
587
+ ):
588
+ raise FeatureLibError(
589
+ "An AxisValueRecord with these values is already defined.",
590
+ location,
591
+ )
592
+ self.stat_["AxisValueRecords"].append(axisValueRecord)
593
+
594
+ def build_STAT(self):
595
+ if not self.stat_:
596
+ return
597
+
598
+ axes = self.stat_.get("DesignAxes")
599
+ if not axes:
600
+ raise FeatureLibError("DesignAxes not defined", None)
601
+ axisValueRecords = self.stat_.get("AxisValueRecords")
602
+ axisValues = {}
603
+ format4_locations = []
604
+ for tag in axes:
605
+ axisValues[tag.tag] = []
606
+ if axisValueRecords is not None:
607
+ for avr in axisValueRecords:
608
+ valuesDict = {}
609
+ if avr.flags > 0:
610
+ valuesDict["flags"] = avr.flags
611
+ if len(avr.locations) == 1:
612
+ location = avr.locations[0]
613
+ values = location.values
614
+ if len(values) == 1: # format1
615
+ valuesDict.update({"value": values[0], "name": avr.names})
616
+ if len(values) == 2: # format3
617
+ valuesDict.update(
618
+ {
619
+ "value": values[0],
620
+ "linkedValue": values[1],
621
+ "name": avr.names,
622
+ }
623
+ )
624
+ if len(values) == 3: # format2
625
+ nominal, minVal, maxVal = values
626
+ valuesDict.update(
627
+ {
628
+ "nominalValue": nominal,
629
+ "rangeMinValue": minVal,
630
+ "rangeMaxValue": maxVal,
631
+ "name": avr.names,
632
+ }
633
+ )
634
+ axisValues[location.tag].append(valuesDict)
635
+ else:
636
+ valuesDict.update(
637
+ {
638
+ "location": {i.tag: i.values[0] for i in avr.locations},
639
+ "name": avr.names,
640
+ }
641
+ )
642
+ format4_locations.append(valuesDict)
643
+
644
+ designAxes = [
645
+ {
646
+ "ordering": a.axisOrder,
647
+ "tag": a.tag,
648
+ "name": a.names,
649
+ "values": axisValues[a.tag],
650
+ }
651
+ for a in axes
652
+ ]
653
+
654
+ nameTable = self.font.get("name")
655
+ if not nameTable: # this only happens for unit tests
656
+ nameTable = self.font["name"] = newTable("name")
657
+ nameTable.names = []
658
+
659
+ if "ElidedFallbackNameID" in self.stat_:
660
+ nameID = self.stat_["ElidedFallbackNameID"]
661
+ name = nameTable.getDebugName(nameID)
662
+ if not name:
663
+ raise FeatureLibError(
664
+ f"ElidedFallbackNameID {nameID} points "
665
+ "to a nameID that does not exist in the "
666
+ '"name" table',
667
+ None,
668
+ )
669
+ elif "ElidedFallbackName" in self.stat_:
670
+ nameID = self.stat_["ElidedFallbackName"]
671
+
672
+ otl.buildStatTable(
673
+ self.font,
674
+ designAxes,
675
+ locations=format4_locations,
676
+ elidedFallbackName=nameID,
677
+ )
678
+
679
+ def build_codepages_(self, pages):
680
+ pages2bits = {
681
+ 1252: 0,
682
+ 1250: 1,
683
+ 1251: 2,
684
+ 1253: 3,
685
+ 1254: 4,
686
+ 1255: 5,
687
+ 1256: 6,
688
+ 1257: 7,
689
+ 1258: 8,
690
+ 874: 16,
691
+ 932: 17,
692
+ 936: 18,
693
+ 949: 19,
694
+ 950: 20,
695
+ 1361: 21,
696
+ 869: 48,
697
+ 866: 49,
698
+ 865: 50,
699
+ 864: 51,
700
+ 863: 52,
701
+ 862: 53,
702
+ 861: 54,
703
+ 860: 55,
704
+ 857: 56,
705
+ 855: 57,
706
+ 852: 58,
707
+ 775: 59,
708
+ 737: 60,
709
+ 708: 61,
710
+ 850: 62,
711
+ 437: 63,
712
+ }
713
+ bits = [pages2bits[p] for p in pages if p in pages2bits]
714
+ pages = []
715
+ for i in range(2):
716
+ pages.append("")
717
+ for j in range(i * 32, (i + 1) * 32):
718
+ if j in bits:
719
+ pages[i] += "1"
720
+ else:
721
+ pages[i] += "0"
722
+ return [binary2num(p[::-1]) for p in pages]
723
+
724
+ def buildBASE(self):
725
+ if not self.base_horiz_axis_ and not self.base_vert_axis_:
726
+ return None
727
+ base = otTables.BASE()
728
+ base.Version = 0x00010000
729
+ base.HorizAxis = self.buildBASEAxis(self.base_horiz_axis_)
730
+ base.VertAxis = self.buildBASEAxis(self.base_vert_axis_)
731
+
732
+ result = newTable("BASE")
733
+ result.table = base
734
+ return result
735
+
736
+ def buildBASECoord(self, c):
737
+ coord = otTables.BaseCoord()
738
+ coord.Format = 1
739
+ coord.Coordinate = c
740
+ return coord
741
+
742
+ def buildBASEAxis(self, axis):
743
+ if not axis:
744
+ return
745
+ bases, scripts, minmax = axis
746
+ axis = otTables.Axis()
747
+ axis.BaseTagList = otTables.BaseTagList()
748
+ axis.BaseTagList.BaselineTag = bases
749
+ axis.BaseTagList.BaseTagCount = len(bases)
750
+ axis.BaseScriptList = otTables.BaseScriptList()
751
+ axis.BaseScriptList.BaseScriptRecord = []
752
+ axis.BaseScriptList.BaseScriptCount = len(scripts)
753
+ for script in sorted(scripts):
754
+ minmax_for_script = [
755
+ record[1:] for record in minmax if record[0] == script[0]
756
+ ]
757
+ record = otTables.BaseScriptRecord()
758
+ record.BaseScriptTag = script[0]
759
+ record.BaseScript = otTables.BaseScript()
760
+ record.BaseScript.BaseValues = otTables.BaseValues()
761
+ record.BaseScript.BaseValues.DefaultIndex = bases.index(script[1])
762
+ record.BaseScript.BaseValues.BaseCoord = []
763
+ record.BaseScript.BaseValues.BaseCoordCount = len(script[2])
764
+ record.BaseScript.BaseLangSysRecord = []
765
+
766
+ for c in script[2]:
767
+ record.BaseScript.BaseValues.BaseCoord.append(self.buildBASECoord(c))
768
+ for language, min_coord, max_coord in minmax_for_script:
769
+ minmax_record = otTables.MinMax()
770
+ minmax_record.MinCoord = self.buildBASECoord(min_coord)
771
+ minmax_record.MaxCoord = self.buildBASECoord(max_coord)
772
+ minmax_record.FeatMinMaxCount = 0
773
+ if language == "dflt":
774
+ record.BaseScript.DefaultMinMax = minmax_record
775
+ else:
776
+ lang_record = otTables.BaseLangSysRecord()
777
+ lang_record.BaseLangSysTag = language
778
+ lang_record.MinMax = minmax_record
779
+ record.BaseScript.BaseLangSysRecord.append(lang_record)
780
+ record.BaseScript.BaseLangSysCount = len(
781
+ record.BaseScript.BaseLangSysRecord
782
+ )
783
+ axis.BaseScriptList.BaseScriptRecord.append(record)
784
+ return axis
785
+
786
+ def buildGDEF(self):
787
+ gdef = otTables.GDEF()
788
+ gdef.GlyphClassDef = self.buildGDEFGlyphClassDef_()
789
+ gdef.AttachList = otl.buildAttachList(self.attachPoints_, self.glyphMap)
790
+ gdef.LigCaretList = otl.buildLigCaretList(
791
+ self.ligCaretCoords_, self.ligCaretPoints_, self.glyphMap
792
+ )
793
+ gdef.MarkAttachClassDef = self.buildGDEFMarkAttachClassDef_()
794
+ gdef.MarkGlyphSetsDef = self.buildGDEFMarkGlyphSetsDef_()
795
+ gdef.Version = 0x00010002 if gdef.MarkGlyphSetsDef else 0x00010000
796
+ if self.varstorebuilder:
797
+ store = self.varstorebuilder.finish()
798
+ if store:
799
+ gdef.Version = 0x00010003
800
+ gdef.VarStore = store
801
+ varidx_map = store.optimize()
802
+
803
+ gdef.remap_device_varidxes(varidx_map)
804
+ if "GPOS" in self.font:
805
+ self.font["GPOS"].table.remap_device_varidxes(varidx_map)
806
+ self.model_cache.clear()
807
+ if any(
808
+ (
809
+ gdef.GlyphClassDef,
810
+ gdef.AttachList,
811
+ gdef.LigCaretList,
812
+ gdef.MarkAttachClassDef,
813
+ gdef.MarkGlyphSetsDef,
814
+ )
815
+ ) or hasattr(gdef, "VarStore"):
816
+ result = newTable("GDEF")
817
+ result.table = gdef
818
+ return result
819
+ else:
820
+ return None
821
+
822
+ def buildGDEFGlyphClassDef_(self):
823
+ if self.glyphClassDefs_:
824
+ classes = {g: c for (g, (c, _)) in self.glyphClassDefs_.items()}
825
+ else:
826
+ classes = {}
827
+ for lookup in self.lookups_:
828
+ classes.update(lookup.inferGlyphClasses())
829
+ for markClass in self.parseTree.markClasses.values():
830
+ for markClassDef in markClass.definitions:
831
+ for glyph in markClassDef.glyphSet():
832
+ classes[glyph] = 3
833
+ if classes:
834
+ result = otTables.GlyphClassDef()
835
+ result.classDefs = classes
836
+ return result
837
+ else:
838
+ return None
839
+
840
+ def buildGDEFMarkAttachClassDef_(self):
841
+ classDefs = {g: c for g, (c, _) in self.markAttach_.items()}
842
+ if not classDefs:
843
+ return None
844
+ result = otTables.MarkAttachClassDef()
845
+ result.classDefs = classDefs
846
+ return result
847
+
848
+ def buildGDEFMarkGlyphSetsDef_(self):
849
+ sets = []
850
+ for glyphs, id_ in sorted(
851
+ self.markFilterSets_.items(), key=lambda item: item[1]
852
+ ):
853
+ sets.append(glyphs)
854
+ return otl.buildMarkGlyphSetsDef(sets, self.glyphMap)
855
+
856
+ def buildDebg(self):
857
+ if "Debg" not in self.font:
858
+ self.font["Debg"] = newTable("Debg")
859
+ self.font["Debg"].data = {}
860
+ self.font["Debg"].data[LOOKUP_DEBUG_INFO_KEY] = self.lookup_locations
861
+
862
+ def buildLookups_(self, tag):
863
+ assert tag in ("GPOS", "GSUB"), tag
864
+ for lookup in self.lookups_:
865
+ lookup.lookup_index = None
866
+ lookups = []
867
+ for lookup in self.lookups_:
868
+ if lookup.table != tag:
869
+ continue
870
+ name = self.get_lookup_name_(lookup)
871
+ resolved = lookup.promote_lookup_type(is_named_lookup=name is not None)
872
+ if resolved is None:
873
+ raise FeatureLibError(
874
+ "Within a named lookup block, all rules must be of "
875
+ "the same lookup type and flag",
876
+ lookup.location,
877
+ )
878
+ for l in resolved:
879
+ lookup.lookup_index = len(lookups)
880
+ self.lookup_locations[tag][str(lookup.lookup_index)] = LookupDebugInfo(
881
+ location=str(lookup.location),
882
+ name=name,
883
+ feature=None,
884
+ )
885
+ lookups.append(l)
886
+ otLookups = []
887
+ for l in lookups:
888
+ try:
889
+ otLookups.append(l.build())
890
+ except OpenTypeLibError as e:
891
+ raise FeatureLibError(str(e), e.location) from e
892
+ except Exception as e:
893
+ location = self.lookup_locations[tag][str(l.lookup_index)].location
894
+ raise FeatureLibError(str(e), location) from e
895
+ return otLookups
896
+
897
+ def makeTable(self, tag):
898
+ table = getattr(otTables, tag, None)()
899
+ table.Version = 0x00010000
900
+ table.ScriptList = otTables.ScriptList()
901
+ table.ScriptList.ScriptRecord = []
902
+ table.FeatureList = otTables.FeatureList()
903
+ table.FeatureList.FeatureRecord = []
904
+ table.LookupList = otTables.LookupList()
905
+ table.LookupList.Lookup = self.buildLookups_(tag)
906
+
907
+ # Build a table for mapping (tag, lookup_indices) to feature_index.
908
+ # For example, ('liga', (2,3,7)) --> 23.
909
+ feature_indices = {}
910
+ required_feature_indices = {} # ('latn', 'DEU') --> 23
911
+ scripts = {} # 'latn' --> {'DEU': [23, 24]} for feature #23,24
912
+ # Sort the feature table by feature tag:
913
+ # https://github.com/fonttools/fonttools/issues/568
914
+ sortFeatureTag = lambda f: (f[0][2], f[0][1], f[0][0], f[1])
915
+ for key, lookups in sorted(self.features_.items(), key=sortFeatureTag):
916
+ script, lang, feature_tag = key
917
+ # l.lookup_index will be None when a lookup is not needed
918
+ # for the table under construction. For example, substitution
919
+ # rules will have no lookup_index while building GPOS tables.
920
+ # We also deduplicate lookup indices, as they only get applied once
921
+ # within a given feature:
922
+ # https://github.com/fonttools/fonttools/issues/2946
923
+ lookup_indices = tuple(
924
+ dict.fromkeys(
925
+ l.lookup_index for l in lookups if l.lookup_index is not None
926
+ )
927
+ )
928
+
929
+ size_feature = tag == "GPOS" and feature_tag == "size"
930
+ force_feature = self.any_feature_variations(feature_tag, tag)
931
+ if len(lookup_indices) == 0 and not size_feature and not force_feature:
932
+ continue
933
+
934
+ for ix in lookup_indices:
935
+ try:
936
+ self.lookup_locations[tag][str(ix)] = self.lookup_locations[tag][
937
+ str(ix)
938
+ ]._replace(feature=key)
939
+ except KeyError:
940
+ warnings.warn(
941
+ "feaLib.Builder subclass needs upgrading to "
942
+ "stash debug information. See fonttools#2065."
943
+ )
944
+
945
+ feature_key = (feature_tag, lookup_indices)
946
+ feature_index = feature_indices.get(feature_key)
947
+ if feature_index is None:
948
+ feature_index = len(table.FeatureList.FeatureRecord)
949
+ frec = otTables.FeatureRecord()
950
+ frec.FeatureTag = feature_tag
951
+ frec.Feature = otTables.Feature()
952
+ frec.Feature.FeatureParams = self.buildFeatureParams(feature_tag)
953
+ frec.Feature.LookupListIndex = list(lookup_indices)
954
+ frec.Feature.LookupCount = len(lookup_indices)
955
+ table.FeatureList.FeatureRecord.append(frec)
956
+ feature_indices[feature_key] = feature_index
957
+ scripts.setdefault(script, {}).setdefault(lang, []).append(feature_index)
958
+ if self.required_features_.get((script, lang)) == feature_tag:
959
+ required_feature_indices[(script, lang)] = feature_index
960
+
961
+ # Build ScriptList.
962
+ for script, lang_features in sorted(scripts.items()):
963
+ srec = otTables.ScriptRecord()
964
+ srec.ScriptTag = script
965
+ srec.Script = otTables.Script()
966
+ srec.Script.DefaultLangSys = None
967
+ srec.Script.LangSysRecord = []
968
+ for lang, feature_indices in sorted(lang_features.items()):
969
+ langrec = otTables.LangSysRecord()
970
+ langrec.LangSys = otTables.LangSys()
971
+ langrec.LangSys.LookupOrder = None
972
+
973
+ req_feature_index = required_feature_indices.get((script, lang))
974
+ if req_feature_index is None:
975
+ langrec.LangSys.ReqFeatureIndex = 0xFFFF
976
+ else:
977
+ langrec.LangSys.ReqFeatureIndex = req_feature_index
978
+
979
+ langrec.LangSys.FeatureIndex = [
980
+ i for i in feature_indices if i != req_feature_index
981
+ ]
982
+ langrec.LangSys.FeatureCount = len(langrec.LangSys.FeatureIndex)
983
+
984
+ if lang == "dflt":
985
+ srec.Script.DefaultLangSys = langrec.LangSys
986
+ else:
987
+ langrec.LangSysTag = lang
988
+ srec.Script.LangSysRecord.append(langrec)
989
+ srec.Script.LangSysCount = len(srec.Script.LangSysRecord)
990
+ table.ScriptList.ScriptRecord.append(srec)
991
+
992
+ table.ScriptList.ScriptCount = len(table.ScriptList.ScriptRecord)
993
+ table.FeatureList.FeatureCount = len(table.FeatureList.FeatureRecord)
994
+ table.LookupList.LookupCount = len(table.LookupList.Lookup)
995
+ return table
996
+
997
+ def makeFeatureVariations(self, table, table_tag):
998
+ feature_vars = {}
999
+ has_any_variations = False
1000
+ # Sort out which lookups to build, gather their indices
1001
+ for (_, _, feature_tag), variations in self.feature_variations_.items():
1002
+ feature_vars[feature_tag] = []
1003
+ for conditionset, builders in variations.items():
1004
+ raw_conditionset = self.conditionsets_[conditionset]
1005
+ indices = []
1006
+ for b in builders:
1007
+ if b.table != table_tag:
1008
+ continue
1009
+ assert b.lookup_index is not None
1010
+ indices.append(b.lookup_index)
1011
+ has_any_variations = True
1012
+ feature_vars[feature_tag].append((raw_conditionset, indices))
1013
+
1014
+ if has_any_variations:
1015
+ for feature_tag, conditions_and_lookups in feature_vars.items():
1016
+ addFeatureVariationsRaw(
1017
+ self.font, table, conditions_and_lookups, feature_tag
1018
+ )
1019
+
1020
+ def any_feature_variations(self, feature_tag, table_tag):
1021
+ for (_, _, feature), variations in self.feature_variations_.items():
1022
+ if feature != feature_tag:
1023
+ continue
1024
+ for conditionset, builders in variations.items():
1025
+ if any(b.table == table_tag for b in builders):
1026
+ return True
1027
+ return False
1028
+
1029
+ def get_lookup_name_(self, lookup):
1030
+ rev = {v: k for k, v in self.named_lookups_.items()}
1031
+ if lookup in rev:
1032
+ return rev[lookup]
1033
+ return None
1034
+
1035
+ def add_language_system(self, location, script, language):
1036
+ # OpenType Feature File Specification, section 4.b.i
1037
+ if script == "DFLT" and language == "dflt" and self.default_language_systems_:
1038
+ raise FeatureLibError(
1039
+ 'If "languagesystem DFLT dflt" is present, it must be '
1040
+ "the first of the languagesystem statements",
1041
+ location,
1042
+ )
1043
+ if script == "DFLT":
1044
+ if self.seen_non_DFLT_script_:
1045
+ raise FeatureLibError(
1046
+ 'languagesystems using the "DFLT" script tag must '
1047
+ "precede all other languagesystems",
1048
+ location,
1049
+ )
1050
+ else:
1051
+ self.seen_non_DFLT_script_ = True
1052
+ if (script, language) in self.default_language_systems_:
1053
+ raise FeatureLibError(
1054
+ '"languagesystem %s %s" has already been specified'
1055
+ % (script.strip(), language.strip()),
1056
+ location,
1057
+ )
1058
+ self.default_language_systems_.add((script, language))
1059
+
1060
+ def get_default_language_systems_(self):
1061
+ # OpenType Feature File specification, 4.b.i. languagesystem:
1062
+ # If no "languagesystem" statement is present, then the
1063
+ # implementation must behave exactly as though the following
1064
+ # statement were present at the beginning of the feature file:
1065
+ # languagesystem DFLT dflt;
1066
+ if self.default_language_systems_:
1067
+ return frozenset(self.default_language_systems_)
1068
+ else:
1069
+ return frozenset({("DFLT", "dflt")})
1070
+
1071
+ def start_feature(self, location, name, use_extension=False):
1072
+ if use_extension and name != "aalt":
1073
+ raise FeatureLibError(
1074
+ "'useExtension' keyword for feature blocks is allowed only for 'aalt' feature",
1075
+ location,
1076
+ )
1077
+ self.language_systems = self.get_default_language_systems_()
1078
+ self.script_ = "DFLT"
1079
+ self.cur_lookup_ = None
1080
+ self.cur_feature_name_ = name
1081
+ self.lookupflag_ = 0
1082
+ self.lookupflag_markFilterSet_ = None
1083
+ self.use_extension_ = use_extension
1084
+ if name == "aalt":
1085
+ self.aalt_location_ = location
1086
+ self.aalt_use_extension_ = use_extension
1087
+
1088
+ def end_feature(self):
1089
+ assert self.cur_feature_name_ is not None
1090
+ self.cur_feature_name_ = None
1091
+ self.language_systems = None
1092
+ self.cur_lookup_ = None
1093
+ self.lookupflag_ = 0
1094
+ self.lookupflag_markFilterSet_ = None
1095
+ self.use_extension_ = False
1096
+
1097
+ def start_lookup_block(self, location, name, use_extension=False):
1098
+ if name in self.named_lookups_:
1099
+ raise FeatureLibError(
1100
+ 'Lookup "%s" has already been defined' % name, location
1101
+ )
1102
+ if self.cur_feature_name_ == "aalt":
1103
+ raise FeatureLibError(
1104
+ "Lookup blocks cannot be placed inside 'aalt' features; "
1105
+ "move it out, and then refer to it with a lookup statement",
1106
+ location,
1107
+ )
1108
+ self.cur_lookup_name_ = name
1109
+ self.named_lookups_[name] = None
1110
+ self.cur_lookup_ = None
1111
+ self.use_extension_ = use_extension
1112
+ if self.cur_feature_name_ is None:
1113
+ self.lookupflag_ = 0
1114
+ self.lookupflag_markFilterSet_ = None
1115
+
1116
+ def end_lookup_block(self):
1117
+ assert self.cur_lookup_name_ is not None
1118
+ self.cur_lookup_name_ = None
1119
+ self.cur_lookup_ = None
1120
+ self.use_extension_ = False
1121
+ if self.cur_feature_name_ is None:
1122
+ self.lookupflag_ = 0
1123
+ self.lookupflag_markFilterSet_ = None
1124
+
1125
+ def add_lookup_call(self, lookup_name):
1126
+ assert lookup_name in self.named_lookups_, lookup_name
1127
+ self.cur_lookup_ = None
1128
+ lookup = self.named_lookups_[lookup_name]
1129
+ if lookup is not None: # skip empty named lookup
1130
+ self.add_lookup_to_feature_(lookup, self.cur_feature_name_)
1131
+
1132
+ def set_font_revision(self, location, revision):
1133
+ self.fontRevision_ = revision
1134
+
1135
+ def set_language(self, location, language, include_default, required):
1136
+ assert len(language) == 4
1137
+ if self.cur_feature_name_ in ("aalt", "size"):
1138
+ raise FeatureLibError(
1139
+ "Language statements are not allowed "
1140
+ 'within "feature %s"' % self.cur_feature_name_,
1141
+ location,
1142
+ )
1143
+ if self.cur_feature_name_ is None:
1144
+ raise FeatureLibError(
1145
+ "Language statements are not allowed "
1146
+ "within standalone lookup blocks",
1147
+ location,
1148
+ )
1149
+ self.cur_lookup_ = None
1150
+
1151
+ key = (self.script_, language, self.cur_feature_name_)
1152
+ lookups = self.features_.get((key[0], "dflt", key[2]))
1153
+ if (language == "dflt" or include_default) and lookups:
1154
+ self.features_[key] = lookups[:]
1155
+ else:
1156
+ # if we aren't including default we need to manually remove the
1157
+ # default lookups, which were added to all declared langsystems
1158
+ # as they were encountered (we don't remove all lookups because
1159
+ # we want to allow duplicate script/lang statements;
1160
+ # see https://github.com/fonttools/fonttools/issues/3748
1161
+ cur_lookups = self.features_.get(key, [])
1162
+ self.features_[key] = [x for x in cur_lookups if x not in lookups]
1163
+ self.language_systems = frozenset([(self.script_, language)])
1164
+
1165
+ if required:
1166
+ key = (self.script_, language)
1167
+ if key in self.required_features_:
1168
+ raise FeatureLibError(
1169
+ "Language %s (script %s) has already "
1170
+ "specified feature %s as its required feature"
1171
+ % (
1172
+ language.strip(),
1173
+ self.script_.strip(),
1174
+ self.required_features_[key].strip(),
1175
+ ),
1176
+ location,
1177
+ )
1178
+ self.required_features_[key] = self.cur_feature_name_
1179
+
1180
+ def getMarkAttachClass_(self, location, glyphs):
1181
+ glyphs = frozenset(glyphs)
1182
+ id_ = self.markAttachClassID_.get(glyphs)
1183
+ if id_ is not None:
1184
+ return id_
1185
+ id_ = len(self.markAttachClassID_) + 1
1186
+ self.markAttachClassID_[glyphs] = id_
1187
+ for glyph in glyphs:
1188
+ if glyph in self.markAttach_:
1189
+ _, loc = self.markAttach_[glyph]
1190
+ raise FeatureLibError(
1191
+ "Glyph %s already has been assigned "
1192
+ "a MarkAttachmentType at %s" % (glyph, loc),
1193
+ location,
1194
+ )
1195
+ self.markAttach_[glyph] = (id_, location)
1196
+ return id_
1197
+
1198
+ def getMarkFilterSet_(self, location, glyphs):
1199
+ glyphs = frozenset(glyphs)
1200
+ id_ = self.markFilterSets_.get(glyphs)
1201
+ if id_ is not None:
1202
+ return id_
1203
+ id_ = len(self.markFilterSets_)
1204
+ self.markFilterSets_[glyphs] = id_
1205
+ return id_
1206
+
1207
+ def set_lookup_flag(self, location, value, markAttach, markFilter):
1208
+ value = value & 0xFF
1209
+ if markAttach:
1210
+ markAttachClass = self.getMarkAttachClass_(location, markAttach)
1211
+ value = value | (markAttachClass << 8)
1212
+ if markFilter:
1213
+ markFilterSet = self.getMarkFilterSet_(location, markFilter)
1214
+ value = value | 0x10
1215
+ self.lookupflag_markFilterSet_ = markFilterSet
1216
+ else:
1217
+ self.lookupflag_markFilterSet_ = None
1218
+ self.lookupflag_ = value
1219
+
1220
+ def set_script(self, location, script):
1221
+ if self.cur_feature_name_ in ("aalt", "size"):
1222
+ raise FeatureLibError(
1223
+ "Script statements are not allowed "
1224
+ 'within "feature %s"' % self.cur_feature_name_,
1225
+ location,
1226
+ )
1227
+ if self.cur_feature_name_ is None:
1228
+ raise FeatureLibError(
1229
+ "Script statements are not allowed " "within standalone lookup blocks",
1230
+ location,
1231
+ )
1232
+ if self.language_systems == {(script, "dflt")}:
1233
+ # Nothing to do.
1234
+ return
1235
+ self.cur_lookup_ = None
1236
+ self.script_ = script
1237
+ self.lookupflag_ = 0
1238
+ self.lookupflag_markFilterSet_ = None
1239
+ self.set_language(location, "dflt", include_default=True, required=False)
1240
+
1241
+ def find_lookup_builders_(self, lookups):
1242
+ """Helper for building chain contextual substitutions
1243
+
1244
+ Given a list of lookup names, finds the LookupBuilder for each name.
1245
+ If an input name is None, it gets mapped to a None LookupBuilder.
1246
+ """
1247
+ lookup_builders = []
1248
+ for lookuplist in lookups:
1249
+ if lookuplist is not None:
1250
+ lookup_builders.append(
1251
+ [self.named_lookups_.get(l.name) for l in lookuplist]
1252
+ )
1253
+ else:
1254
+ lookup_builders.append(None)
1255
+ return lookup_builders
1256
+
1257
+ def add_attach_points(self, location, glyphs, contourPoints):
1258
+ for glyph in glyphs:
1259
+ self.attachPoints_.setdefault(glyph, set()).update(contourPoints)
1260
+
1261
+ def add_feature_reference(self, location, featureName):
1262
+ if self.cur_feature_name_ != "aalt":
1263
+ raise FeatureLibError(
1264
+ 'Feature references are only allowed inside "feature aalt"', location
1265
+ )
1266
+ self.aalt_features_.append((location, featureName))
1267
+
1268
+ def add_featureName(self, tag):
1269
+ self.featureNames_.add(tag)
1270
+
1271
+ def add_cv_parameter(self, tag):
1272
+ self.cv_parameters_.add(tag)
1273
+
1274
+ def add_to_cv_num_named_params(self, tag):
1275
+ """Adds new items to ``self.cv_num_named_params_``
1276
+ or increments the count of existing items."""
1277
+ if tag in self.cv_num_named_params_:
1278
+ self.cv_num_named_params_[tag] += 1
1279
+ else:
1280
+ self.cv_num_named_params_[tag] = 1
1281
+
1282
+ def add_cv_character(self, character, tag):
1283
+ self.cv_characters_[tag].append(character)
1284
+
1285
+ def set_base_axis(self, bases, scripts, vertical, minmax=[]):
1286
+ if vertical:
1287
+ self.base_vert_axis_ = (bases, scripts, minmax)
1288
+ else:
1289
+ self.base_horiz_axis_ = (bases, scripts, minmax)
1290
+
1291
+ def set_size_parameters(
1292
+ self, location, DesignSize, SubfamilyID, RangeStart, RangeEnd
1293
+ ):
1294
+ if self.cur_feature_name_ != "size":
1295
+ raise FeatureLibError(
1296
+ "Parameters statements are not allowed "
1297
+ 'within "feature %s"' % self.cur_feature_name_,
1298
+ location,
1299
+ )
1300
+ self.size_parameters_ = [DesignSize, SubfamilyID, RangeStart, RangeEnd]
1301
+ for script, lang in self.language_systems:
1302
+ key = (script, lang, self.cur_feature_name_)
1303
+ self.features_.setdefault(key, [])
1304
+
1305
+ # GSUB rules
1306
+
1307
+ def add_any_subst_(self, location, mapping):
1308
+ lookup = self.get_lookup_(location, AnySubstBuilder)
1309
+ for key, value in mapping.items():
1310
+ if key in lookup.mapping:
1311
+ if value == lookup.mapping[key]:
1312
+ log.info(
1313
+ 'Removing duplicate substitution from "%s" to "%s" at %s',
1314
+ ", ".join(key),
1315
+ ", ".join(value),
1316
+ location,
1317
+ )
1318
+ else:
1319
+ raise FeatureLibError(
1320
+ 'Already defined substitution for "%s"' % ", ".join(key),
1321
+ location,
1322
+ )
1323
+ lookup.mapping[key] = value
1324
+
1325
+ # GSUB 1
1326
+ def add_single_subst(self, location, prefix, suffix, mapping, forceChain):
1327
+ if self.cur_feature_name_ == "aalt":
1328
+ for from_glyph, to_glyph in mapping.items():
1329
+ alts = self.aalt_alternates_.setdefault(from_glyph, [])
1330
+ if to_glyph not in alts:
1331
+ alts.append(to_glyph)
1332
+ return
1333
+ if prefix or suffix or forceChain:
1334
+ self.add_single_subst_chained_(location, prefix, suffix, mapping)
1335
+ return
1336
+
1337
+ self.add_any_subst_(
1338
+ location,
1339
+ {(key,): (value,) for key, value in mapping.items()},
1340
+ )
1341
+
1342
+ # GSUB 2
1343
+ def add_multiple_subst(
1344
+ self, location, prefix, glyph, suffix, replacements, forceChain=False
1345
+ ):
1346
+ if prefix or suffix or forceChain:
1347
+ self.add_multi_subst_chained_(location, prefix, glyph, suffix, replacements)
1348
+ return
1349
+ self.add_any_subst_(
1350
+ location,
1351
+ {(glyph,): tuple(replacements)},
1352
+ )
1353
+
1354
+ # GSUB 3
1355
+ def add_alternate_subst(self, location, prefix, glyph, suffix, replacement):
1356
+ if self.cur_feature_name_ == "aalt":
1357
+ alts = self.aalt_alternates_.setdefault(glyph, [])
1358
+ alts.extend(g for g in replacement if g not in alts)
1359
+ return
1360
+ if prefix or suffix:
1361
+ chain = self.get_lookup_(location, ChainContextSubstBuilder)
1362
+ lookup = self.get_chained_lookup_(location, AlternateSubstBuilder)
1363
+ chain.rules.append(ChainContextualRule(prefix, [{glyph}], suffix, [lookup]))
1364
+ else:
1365
+ lookup = self.get_lookup_(location, AlternateSubstBuilder)
1366
+ if glyph in lookup.alternates:
1367
+ raise FeatureLibError(
1368
+ 'Already defined alternates for glyph "%s"' % glyph, location
1369
+ )
1370
+ # We allow empty replacement glyphs here.
1371
+ lookup.alternates[glyph] = replacement
1372
+
1373
+ # GSUB 4
1374
+ def add_ligature_subst(
1375
+ self, location, prefix, glyphs, suffix, replacement, forceChain
1376
+ ):
1377
+ if prefix or suffix or forceChain:
1378
+ self.add_ligature_subst_chained_(
1379
+ location, prefix, glyphs, suffix, replacement
1380
+ )
1381
+ return
1382
+ if not all(glyphs):
1383
+ raise FeatureLibError("Empty glyph class in substitution", location)
1384
+
1385
+ # OpenType feature file syntax, section 5.d, "Ligature substitution":
1386
+ # "Since the OpenType specification does not allow ligature
1387
+ # substitutions to be specified on target sequences that contain
1388
+ # glyph classes, the implementation software will enumerate
1389
+ # all specific glyph sequences if glyph classes are detected"
1390
+ self.add_any_subst_(
1391
+ location,
1392
+ {g: (replacement,) for g in itertools.product(*glyphs)},
1393
+ )
1394
+
1395
+ # GSUB 5/6
1396
+ def add_chain_context_subst(self, location, prefix, glyphs, suffix, lookups):
1397
+ if not all(glyphs) or not all(prefix) or not all(suffix):
1398
+ raise FeatureLibError(
1399
+ "Empty glyph class in contextual substitution", location
1400
+ )
1401
+ lookup = self.get_lookup_(location, ChainContextSubstBuilder)
1402
+ lookup.rules.append(
1403
+ ChainContextualRule(
1404
+ prefix, glyphs, suffix, self.find_lookup_builders_(lookups)
1405
+ )
1406
+ )
1407
+
1408
+ def add_single_subst_chained_(self, location, prefix, suffix, mapping):
1409
+ if not mapping or not all(prefix) or not all(suffix):
1410
+ raise FeatureLibError(
1411
+ "Empty glyph class in contextual substitution", location
1412
+ )
1413
+ # https://github.com/fonttools/fonttools/issues/512
1414
+ # https://github.com/fonttools/fonttools/issues/2150
1415
+ chain = self.get_lookup_(location, ChainContextSubstBuilder)
1416
+ sub = chain.find_chainable_subst(mapping, SingleSubstBuilder)
1417
+ if sub is None:
1418
+ sub = self.get_chained_lookup_(location, SingleSubstBuilder)
1419
+ sub.mapping.update(mapping)
1420
+ chain.rules.append(
1421
+ ChainContextualRule(prefix, [list(mapping.keys())], suffix, [sub])
1422
+ )
1423
+
1424
+ def add_multi_subst_chained_(self, location, prefix, glyph, suffix, replacements):
1425
+ if not all(prefix) or not all(suffix):
1426
+ raise FeatureLibError(
1427
+ "Empty glyph class in contextual substitution", location
1428
+ )
1429
+ # https://github.com/fonttools/fonttools/issues/3551
1430
+ chain = self.get_lookup_(location, ChainContextSubstBuilder)
1431
+ sub = chain.find_chainable_subst({glyph: replacements}, MultipleSubstBuilder)
1432
+ if sub is None:
1433
+ sub = self.get_chained_lookup_(location, MultipleSubstBuilder)
1434
+ sub.mapping[glyph] = replacements
1435
+ chain.rules.append(ChainContextualRule(prefix, [{glyph}], suffix, [sub]))
1436
+
1437
+ def add_ligature_subst_chained_(
1438
+ self, location, prefix, glyphs, suffix, replacement
1439
+ ):
1440
+ # https://github.com/fonttools/fonttools/issues/3701
1441
+ if not all(prefix) or not all(suffix):
1442
+ raise FeatureLibError(
1443
+ "Empty glyph class in contextual substitution", location
1444
+ )
1445
+ chain = self.get_lookup_(location, ChainContextSubstBuilder)
1446
+ sub = chain.find_chainable_ligature_subst(glyphs, replacement)
1447
+ if sub is None:
1448
+ sub = self.get_chained_lookup_(location, LigatureSubstBuilder)
1449
+
1450
+ for g in itertools.product(*glyphs):
1451
+ existing = sub.ligatures.get(g, replacement)
1452
+ if existing != replacement:
1453
+ raise FeatureLibError(
1454
+ f"Conflicting ligature sub rules: '{g}' maps to '{existing}' and '{replacement}'",
1455
+ location,
1456
+ )
1457
+
1458
+ sub.ligatures[g] = replacement
1459
+
1460
+ chain.rules.append(ChainContextualRule(prefix, glyphs, suffix, [sub]))
1461
+
1462
+ # GSUB 8
1463
+ def add_reverse_chain_single_subst(self, location, old_prefix, old_suffix, mapping):
1464
+ if not mapping:
1465
+ raise FeatureLibError("Empty glyph class in substitution", location)
1466
+ lookup = self.get_lookup_(location, ReverseChainSingleSubstBuilder)
1467
+ lookup.rules.append((old_prefix, old_suffix, mapping))
1468
+
1469
+ # GPOS rules
1470
+
1471
+ # GPOS 1
1472
+ def add_single_pos(self, location, prefix, suffix, pos, forceChain):
1473
+ if prefix or suffix or forceChain:
1474
+ self.add_single_pos_chained_(location, prefix, suffix, pos)
1475
+ else:
1476
+ lookup = self.get_lookup_(location, SinglePosBuilder)
1477
+ for glyphs, value in pos:
1478
+ if not glyphs:
1479
+ raise FeatureLibError(
1480
+ "Empty glyph class in positioning rule", location
1481
+ )
1482
+ otValueRecord = self.makeOpenTypeValueRecord(
1483
+ location, value, pairPosContext=False
1484
+ )
1485
+ for glyph in glyphs:
1486
+ try:
1487
+ lookup.add_pos(location, glyph, otValueRecord)
1488
+ except OpenTypeLibError as e:
1489
+ raise FeatureLibError(str(e), e.location) from e
1490
+
1491
+ # GPOS 2
1492
+ def add_class_pair_pos(self, location, glyphclass1, value1, glyphclass2, value2):
1493
+ if not glyphclass1 or not glyphclass2:
1494
+ raise FeatureLibError("Empty glyph class in positioning rule", location)
1495
+ lookup = self.get_lookup_(location, PairPosBuilder)
1496
+ v1 = self.makeOpenTypeValueRecord(location, value1, pairPosContext=True)
1497
+ v2 = self.makeOpenTypeValueRecord(location, value2, pairPosContext=True)
1498
+ cls1 = tuple(sorted(set(glyphclass1)))
1499
+ cls2 = tuple(sorted(set(glyphclass2)))
1500
+ lookup.addClassPair(location, cls1, v1, cls2, v2)
1501
+
1502
+ def add_specific_pair_pos(self, location, glyph1, value1, glyph2, value2):
1503
+ if not glyph1 or not glyph2:
1504
+ raise FeatureLibError("Empty glyph class in positioning rule", location)
1505
+ lookup = self.get_lookup_(location, PairPosBuilder)
1506
+ v1 = self.makeOpenTypeValueRecord(location, value1, pairPosContext=True)
1507
+ v2 = self.makeOpenTypeValueRecord(location, value2, pairPosContext=True)
1508
+ lookup.addGlyphPair(location, glyph1, v1, glyph2, v2)
1509
+
1510
+ # GPOS 3
1511
+ def add_cursive_pos(self, location, glyphclass, entryAnchor, exitAnchor):
1512
+ if not glyphclass:
1513
+ raise FeatureLibError("Empty glyph class in positioning rule", location)
1514
+ lookup = self.get_lookup_(location, CursivePosBuilder)
1515
+ lookup.add_attachment(
1516
+ location,
1517
+ glyphclass,
1518
+ self.makeOpenTypeAnchor(location, entryAnchor),
1519
+ self.makeOpenTypeAnchor(location, exitAnchor),
1520
+ )
1521
+
1522
+ # GPOS 4
1523
+ def add_mark_base_pos(self, location, bases, marks):
1524
+ builder = self.get_lookup_(location, MarkBasePosBuilder)
1525
+ self.add_marks_(location, builder, marks)
1526
+ if not bases:
1527
+ raise FeatureLibError("Empty glyph class in positioning rule", location)
1528
+ for baseAnchor, markClass in marks:
1529
+ otBaseAnchor = self.makeOpenTypeAnchor(location, baseAnchor)
1530
+ for base in bases:
1531
+ builder.bases.setdefault(base, {})[markClass.name] = otBaseAnchor
1532
+
1533
+ # GPOS 5
1534
+ def add_mark_lig_pos(self, location, ligatures, components):
1535
+ builder = self.get_lookup_(location, MarkLigPosBuilder)
1536
+ componentAnchors = []
1537
+ if not ligatures:
1538
+ raise FeatureLibError("Empty glyph class in positioning rule", location)
1539
+ for marks in components:
1540
+ anchors = {}
1541
+ self.add_marks_(location, builder, marks)
1542
+ for ligAnchor, markClass in marks:
1543
+ anchors[markClass.name] = self.makeOpenTypeAnchor(location, ligAnchor)
1544
+ componentAnchors.append(anchors)
1545
+ for glyph in ligatures:
1546
+ builder.ligatures[glyph] = componentAnchors
1547
+
1548
+ # GPOS 6
1549
+ def add_mark_mark_pos(self, location, baseMarks, marks):
1550
+ builder = self.get_lookup_(location, MarkMarkPosBuilder)
1551
+ self.add_marks_(location, builder, marks)
1552
+ if not baseMarks:
1553
+ raise FeatureLibError("Empty glyph class in positioning rule", location)
1554
+ for baseAnchor, markClass in marks:
1555
+ otBaseAnchor = self.makeOpenTypeAnchor(location, baseAnchor)
1556
+ for baseMark in baseMarks:
1557
+ builder.baseMarks.setdefault(baseMark, {})[
1558
+ markClass.name
1559
+ ] = otBaseAnchor
1560
+
1561
+ # GPOS 7/8
1562
+ def add_chain_context_pos(self, location, prefix, glyphs, suffix, lookups):
1563
+ if not all(glyphs) or not all(prefix) or not all(suffix):
1564
+ raise FeatureLibError(
1565
+ "Empty glyph class in contextual positioning rule", location
1566
+ )
1567
+ lookup = self.get_lookup_(location, ChainContextPosBuilder)
1568
+ lookup.rules.append(
1569
+ ChainContextualRule(
1570
+ prefix, glyphs, suffix, self.find_lookup_builders_(lookups)
1571
+ )
1572
+ )
1573
+
1574
+ def add_single_pos_chained_(self, location, prefix, suffix, pos):
1575
+ if not pos or not all(prefix) or not all(suffix):
1576
+ raise FeatureLibError(
1577
+ "Empty glyph class in contextual positioning rule", location
1578
+ )
1579
+ # https://github.com/fonttools/fonttools/issues/514
1580
+ chain = self.get_lookup_(location, ChainContextPosBuilder)
1581
+ targets = []
1582
+ for _, _, _, lookups in chain.rules:
1583
+ targets.extend(lookups)
1584
+ subs = []
1585
+ for glyphs, value in pos:
1586
+ if value is None:
1587
+ subs.append(None)
1588
+ continue
1589
+ otValue = self.makeOpenTypeValueRecord(
1590
+ location, value, pairPosContext=False
1591
+ )
1592
+ sub = chain.find_chainable_single_pos(targets, glyphs, otValue)
1593
+ if sub is None:
1594
+ sub = self.get_chained_lookup_(location, SinglePosBuilder)
1595
+ targets.append(sub)
1596
+ for glyph in glyphs:
1597
+ sub.add_pos(location, glyph, otValue)
1598
+ subs.append(sub)
1599
+ assert len(pos) == len(subs), (pos, subs)
1600
+ chain.rules.append(
1601
+ ChainContextualRule(prefix, [g for g, v in pos], suffix, subs)
1602
+ )
1603
+
1604
+ def add_marks_(self, location, lookupBuilder, marks):
1605
+ """Helper for add_mark_{base,liga,mark}_pos."""
1606
+ for _, markClass in marks:
1607
+ for markClassDef in markClass.definitions:
1608
+ for mark in markClassDef.glyphs.glyphSet():
1609
+ if mark not in lookupBuilder.marks:
1610
+ otMarkAnchor = self.makeOpenTypeAnchor(
1611
+ location, copy.deepcopy(markClassDef.anchor)
1612
+ )
1613
+ lookupBuilder.marks[mark] = (markClass.name, otMarkAnchor)
1614
+ else:
1615
+ existingMarkClass = lookupBuilder.marks[mark][0]
1616
+ if markClass.name != existingMarkClass:
1617
+ raise FeatureLibError(
1618
+ "Glyph %s cannot be in both @%s and @%s"
1619
+ % (mark, existingMarkClass, markClass.name),
1620
+ location,
1621
+ )
1622
+
1623
+ def add_subtable_break(self, location):
1624
+ self.cur_lookup_.add_subtable_break(location)
1625
+
1626
+ def setGlyphClass_(self, location, glyph, glyphClass):
1627
+ oldClass, oldLocation = self.glyphClassDefs_.get(glyph, (None, None))
1628
+ if oldClass and oldClass != glyphClass:
1629
+ raise FeatureLibError(
1630
+ "Glyph %s was assigned to a different class at %s"
1631
+ % (glyph, oldLocation),
1632
+ location,
1633
+ )
1634
+ self.glyphClassDefs_[glyph] = (glyphClass, location)
1635
+
1636
+ def add_glyphClassDef(
1637
+ self, location, baseGlyphs, ligatureGlyphs, markGlyphs, componentGlyphs
1638
+ ):
1639
+ for glyph in baseGlyphs:
1640
+ self.setGlyphClass_(location, glyph, 1)
1641
+ for glyph in ligatureGlyphs:
1642
+ self.setGlyphClass_(location, glyph, 2)
1643
+ for glyph in markGlyphs:
1644
+ self.setGlyphClass_(location, glyph, 3)
1645
+ for glyph in componentGlyphs:
1646
+ self.setGlyphClass_(location, glyph, 4)
1647
+
1648
+ def add_ligatureCaretByIndex_(self, location, glyphs, carets):
1649
+ for glyph in glyphs:
1650
+ if glyph not in self.ligCaretPoints_:
1651
+ self.ligCaretPoints_[glyph] = carets
1652
+
1653
+ def makeLigCaret(self, location, caret):
1654
+ if not isinstance(caret, VariableScalar):
1655
+ return caret
1656
+ default, device = self.makeVariablePos(location, caret)
1657
+ if device is not None:
1658
+ return (default, device)
1659
+ return default
1660
+
1661
+ def add_ligatureCaretByPos_(self, location, glyphs, carets):
1662
+ carets = [self.makeLigCaret(location, caret) for caret in carets]
1663
+ for glyph in glyphs:
1664
+ if glyph not in self.ligCaretCoords_:
1665
+ self.ligCaretCoords_[glyph] = carets
1666
+
1667
+ def add_name_record(self, location, nameID, platformID, platEncID, langID, string):
1668
+ self.names_.append([nameID, platformID, platEncID, langID, string])
1669
+
1670
+ def add_os2_field(self, key, value):
1671
+ self.os2_[key] = value
1672
+
1673
+ def add_hhea_field(self, key, value):
1674
+ self.hhea_[key] = value
1675
+
1676
+ def add_vhea_field(self, key, value):
1677
+ self.vhea_[key] = value
1678
+
1679
+ def add_conditionset(self, location, key, value):
1680
+ if "fvar" not in self.font:
1681
+ raise FeatureLibError(
1682
+ "Cannot add feature variations to a font without an 'fvar' table",
1683
+ location,
1684
+ )
1685
+
1686
+ # Normalize
1687
+ axisMap = {
1688
+ axis.axisTag: (axis.minValue, axis.defaultValue, axis.maxValue)
1689
+ for axis in self.axes
1690
+ }
1691
+
1692
+ value = {
1693
+ tag: (
1694
+ normalizeValue(bottom, axisMap[tag]),
1695
+ normalizeValue(top, axisMap[tag]),
1696
+ )
1697
+ for tag, (bottom, top) in value.items()
1698
+ }
1699
+
1700
+ # NOTE: This might result in rounding errors (off-by-ones) compared to
1701
+ # rules in Designspace files, since we're working with what's in the
1702
+ # `avar` table rather than the original values.
1703
+ if "avar" in self.font:
1704
+ mapping = self.font["avar"].segments
1705
+ value = {
1706
+ axis: tuple(
1707
+ piecewiseLinearMap(v, mapping[axis]) if axis in mapping else v
1708
+ for v in condition_range
1709
+ )
1710
+ for axis, condition_range in value.items()
1711
+ }
1712
+
1713
+ self.conditionsets_[key] = value
1714
+
1715
+ def makeVariablePos(self, location, varscalar):
1716
+ if not self.varstorebuilder:
1717
+ raise FeatureLibError(
1718
+ "Can't define a variable scalar in a non-variable font", location
1719
+ )
1720
+
1721
+ varscalar.axes = self.axes
1722
+ if not varscalar.does_vary:
1723
+ return varscalar.default, None
1724
+
1725
+ default, index = varscalar.add_to_variation_store(
1726
+ self.varstorebuilder, self.model_cache, self.font.get("avar")
1727
+ )
1728
+
1729
+ device = None
1730
+ if index is not None and index != 0xFFFFFFFF:
1731
+ device = buildVarDevTable(index)
1732
+
1733
+ return default, device
1734
+
1735
+ def makeAnchorPos(self, varscalar, deviceTable, location):
1736
+ device = None
1737
+ if not isinstance(varscalar, VariableScalar):
1738
+ if deviceTable is not None:
1739
+ device = otl.buildDevice(dict(deviceTable))
1740
+ return varscalar, device
1741
+ default, device = self.makeVariablePos(location, varscalar)
1742
+ if device is not None and deviceTable is not None:
1743
+ raise FeatureLibError(
1744
+ "Can't define a device coordinate and variable scalar", location
1745
+ )
1746
+ return default, device
1747
+
1748
+ def makeOpenTypeAnchor(self, location, anchor):
1749
+ """ast.Anchor --> otTables.Anchor"""
1750
+ if anchor is None:
1751
+ return None
1752
+ deviceX, deviceY = None, None
1753
+ if anchor.xDeviceTable is not None:
1754
+ deviceX = otl.buildDevice(dict(anchor.xDeviceTable))
1755
+ if anchor.yDeviceTable is not None:
1756
+ deviceY = otl.buildDevice(dict(anchor.yDeviceTable))
1757
+ x, deviceX = self.makeAnchorPos(anchor.x, anchor.xDeviceTable, location)
1758
+ y, deviceY = self.makeAnchorPos(anchor.y, anchor.yDeviceTable, location)
1759
+ otlanchor = otl.buildAnchor(x, y, anchor.contourpoint, deviceX, deviceY)
1760
+ return otlanchor
1761
+
1762
+ _VALUEREC_ATTRS = {
1763
+ name[0].lower() + name[1:]: (name, isDevice)
1764
+ for _, name, isDevice, _ in otBase.valueRecordFormat
1765
+ if not name.startswith("Reserved")
1766
+ }
1767
+
1768
+ def makeOpenTypeValueRecord(self, location, v, pairPosContext):
1769
+ """ast.ValueRecord --> otBase.ValueRecord"""
1770
+ if not v:
1771
+ return None
1772
+
1773
+ vr = {}
1774
+ for astName, (otName, isDevice) in self._VALUEREC_ATTRS.items():
1775
+ val = getattr(v, astName, None)
1776
+ if not val:
1777
+ continue
1778
+ if isDevice:
1779
+ vr[otName] = otl.buildDevice(dict(val))
1780
+ elif isinstance(val, VariableScalar):
1781
+ otDeviceName = otName[0:4] + "Device"
1782
+ feaDeviceName = otDeviceName[0].lower() + otDeviceName[1:]
1783
+ if getattr(v, feaDeviceName):
1784
+ raise FeatureLibError(
1785
+ "Can't define a device coordinate and variable scalar", location
1786
+ )
1787
+ vr[otName], device = self.makeVariablePos(location, val)
1788
+ if device is not None:
1789
+ vr[otDeviceName] = device
1790
+ else:
1791
+ vr[otName] = val
1792
+
1793
+ if pairPosContext and not vr:
1794
+ vr = {"YAdvance": 0} if v.vertical else {"XAdvance": 0}
1795
+ valRec = otl.buildValue(vr)
1796
+ return valRec