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