fonttools 4.58.3__cp39-cp39-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 (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-39-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 +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-39-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 +40136 -0
  62. fontTools/misc/bezierTools.cpython-39-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/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-39-aarch64-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-39-aarch64-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-39-aarch64-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 +7 -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,1946 @@
1
+ """ Partially instantiate a variable font.
2
+
3
+ The module exports an `instantiateVariableFont` function and CLI that allow to
4
+ create full instances (i.e. static fonts) from variable fonts, as well as "partial"
5
+ variable fonts that only contain a subset of the original variation space.
6
+
7
+ For example, if you wish to pin the width axis to a given location while also
8
+ restricting the weight axis to 400..700 range, you can do:
9
+
10
+ .. code-block:: sh
11
+
12
+ $ fonttools varLib.instancer ./NotoSans-VF.ttf wdth=85 wght=400:700
13
+
14
+ See `fonttools varLib.instancer --help` for more info on the CLI options.
15
+
16
+ The module's entry point is the `instantiateVariableFont` function, which takes
17
+ a TTFont object and a dict specifying either axis coodinates or (min, max) ranges,
18
+ and returns a new TTFont representing either a partial VF, or full instance if all
19
+ the VF axes were given an explicit coordinate.
20
+
21
+ E.g. here's how to pin the wght axis at a given location in a wght+wdth variable
22
+ font, keeping only the deltas associated with the wdth axis:
23
+ .. code-block:: pycon
24
+
25
+ >>>
26
+ >> from fontTools import ttLib
27
+ >> from fontTools.varLib import instancer
28
+ >> varfont = ttLib.TTFont("path/to/MyVariableFont.ttf")
29
+ >> [a.axisTag for a in varfont["fvar"].axes] # the varfont's current axes
30
+ ['wght', 'wdth']
31
+ >> partial = instancer.instantiateVariableFont(varfont, {"wght": 300})
32
+ >> [a.axisTag for a in partial["fvar"].axes] # axes left after pinning 'wght'
33
+ ['wdth']
34
+
35
+ If the input location specifies all the axes, the resulting instance is no longer
36
+ 'variable' (same as using fontools varLib.mutator):
37
+ .. code-block:: pycon
38
+
39
+ >>>
40
+ >> instance = instancer.instantiateVariableFont(
41
+ ... varfont, {"wght": 700, "wdth": 67.5}
42
+ ... )
43
+ >> "fvar" not in instance
44
+ True
45
+
46
+ If one just want to drop an axis at the default location, without knowing in
47
+ advance what the default value for that axis is, one can pass a `None` value:
48
+ .. code-block:: pycon
49
+
50
+ >>>
51
+ >> instance = instancer.instantiateVariableFont(varfont, {"wght": None})
52
+ >> len(varfont["fvar"].axes)
53
+ 1
54
+
55
+ From the console script, this is equivalent to passing `wght=drop` as input.
56
+
57
+ This module is similar to fontTools.varLib.mutator, which it's intended to supersede.
58
+ Note that, unlike varLib.mutator, when an axis is not mentioned in the input
59
+ location, the varLib.instancer will keep the axis and the corresponding deltas,
60
+ whereas mutator implicitly drops the axis at its default coordinate.
61
+
62
+ The module supports all the following "levels" of instancing, which can of
63
+ course be combined:
64
+
65
+ L1
66
+ dropping one or more axes while leaving the default tables unmodified;
67
+ .. code-block:: pycon
68
+
69
+ >>>
70
+ >> font = instancer.instantiateVariableFont(varfont, {"wght": None})
71
+
72
+ L2
73
+ dropping one or more axes while pinning them at non-default locations;
74
+ .. code-block:: pycon
75
+
76
+ >>>
77
+ >> font = instancer.instantiateVariableFont(varfont, {"wght": 700})
78
+
79
+ L3
80
+ restricting the range of variation of one or more axes, by setting either
81
+ a new minimum or maximum, potentially -- though not necessarily -- dropping
82
+ entire regions of variations that fall completely outside this new range.
83
+ .. code-block:: pycon
84
+
85
+ >>>
86
+ >> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300)})
87
+
88
+ L4
89
+ moving the default location of an axis, by specifying (min,defalt,max) values:
90
+ .. code-block:: pycon
91
+
92
+ >>>
93
+ >> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300, 700)})
94
+
95
+ Currently only TrueType-flavored variable fonts (i.e. containing 'glyf' table)
96
+ are supported, but support for CFF2 variable fonts will be added soon.
97
+
98
+ The discussion and implementation of these features are tracked at
99
+ https://github.com/fonttools/fonttools/issues/1537
100
+ """
101
+
102
+ from fontTools.misc.fixedTools import (
103
+ floatToFixedToFloat,
104
+ strToFixedToFloat,
105
+ otRound,
106
+ )
107
+ from fontTools.varLib.models import normalizeValue, piecewiseLinearMap
108
+ from fontTools.ttLib import TTFont, newTable
109
+ from fontTools.ttLib.tables.TupleVariation import TupleVariation
110
+ from fontTools.ttLib.tables import _g_l_y_f
111
+ from fontTools import varLib
112
+
113
+ # we import the `subset` module because we use the `prune_lookups` method on the GSUB
114
+ # table class, and that method is only defined dynamically upon importing `subset`
115
+ from fontTools import subset # noqa: F401
116
+ from fontTools.cffLib import privateDictOperators2
117
+ from fontTools.cffLib.specializer import (
118
+ programToCommands,
119
+ commandsToProgram,
120
+ specializeCommands,
121
+ generalizeCommands,
122
+ )
123
+ from fontTools.varLib import builder
124
+ from fontTools.varLib.mvar import MVAR_ENTRIES
125
+ from fontTools.varLib.merger import MutatorMerger
126
+ from fontTools.varLib.instancer import names
127
+ from .featureVars import instantiateFeatureVariations
128
+ from fontTools.misc.cliTools import makeOutputFileName
129
+ from fontTools.varLib.instancer import solver
130
+ from fontTools.ttLib.tables.otTables import VarComponentFlags
131
+ import collections
132
+ import dataclasses
133
+ from contextlib import contextmanager
134
+ from copy import deepcopy
135
+ from enum import IntEnum
136
+ import logging
137
+ import os
138
+ import re
139
+ from typing import Dict, Iterable, Mapping, Optional, Sequence, Tuple, Union
140
+ import warnings
141
+
142
+
143
+ log = logging.getLogger("fontTools.varLib.instancer")
144
+
145
+
146
+ def AxisRange(minimum, maximum):
147
+ warnings.warn(
148
+ "AxisRange is deprecated; use AxisTriple instead",
149
+ DeprecationWarning,
150
+ stacklevel=2,
151
+ )
152
+ return AxisTriple(minimum, None, maximum)
153
+
154
+
155
+ def NormalizedAxisRange(minimum, maximum):
156
+ warnings.warn(
157
+ "NormalizedAxisRange is deprecated; use AxisTriple instead",
158
+ DeprecationWarning,
159
+ stacklevel=2,
160
+ )
161
+ return NormalizedAxisTriple(minimum, None, maximum)
162
+
163
+
164
+ @dataclasses.dataclass(frozen=True, order=True, repr=False)
165
+ class AxisTriple(Sequence):
166
+ """A triple of (min, default, max) axis values.
167
+
168
+ Any of the values can be None, in which case the limitRangeAndPopulateDefaults()
169
+ method can be used to fill in the missing values based on the fvar axis values.
170
+ """
171
+
172
+ minimum: Optional[float]
173
+ default: Optional[float]
174
+ maximum: Optional[float]
175
+
176
+ def __post_init__(self):
177
+ if self.default is None and self.minimum == self.maximum:
178
+ object.__setattr__(self, "default", self.minimum)
179
+ if (
180
+ (
181
+ self.minimum is not None
182
+ and self.default is not None
183
+ and self.minimum > self.default
184
+ )
185
+ or (
186
+ self.default is not None
187
+ and self.maximum is not None
188
+ and self.default > self.maximum
189
+ )
190
+ or (
191
+ self.minimum is not None
192
+ and self.maximum is not None
193
+ and self.minimum > self.maximum
194
+ )
195
+ ):
196
+ raise ValueError(
197
+ f"{type(self).__name__} minimum ({self.minimum}), default ({self.default}), maximum ({self.maximum}) must be in sorted order"
198
+ )
199
+
200
+ def __getitem__(self, i):
201
+ fields = dataclasses.fields(self)
202
+ return getattr(self, fields[i].name)
203
+
204
+ def __len__(self):
205
+ return len(dataclasses.fields(self))
206
+
207
+ def _replace(self, **kwargs):
208
+ return dataclasses.replace(self, **kwargs)
209
+
210
+ def __repr__(self):
211
+ return (
212
+ f"({', '.join(format(v, 'g') if v is not None else 'None' for v in self)})"
213
+ )
214
+
215
+ @classmethod
216
+ def expand(
217
+ cls,
218
+ v: Union[
219
+ "AxisTriple",
220
+ float, # pin axis at single value, same as min==default==max
221
+ Tuple[float, float], # (min, max), restrict axis and keep default
222
+ Tuple[float, float, float], # (min, default, max)
223
+ ],
224
+ ) -> "AxisTriple":
225
+ """Convert a single value or a tuple into an AxisTriple.
226
+
227
+ If the input is a single value, it is interpreted as a pin at that value.
228
+ If the input is a tuple, it is interpreted as (min, max) or (min, default, max).
229
+ """
230
+ if isinstance(v, cls):
231
+ return v
232
+ if isinstance(v, (int, float)):
233
+ return cls(v, v, v)
234
+ try:
235
+ n = len(v)
236
+ except TypeError as e:
237
+ raise ValueError(
238
+ f"expected float, 2- or 3-tuple of floats; got {type(v)}: {v!r}"
239
+ ) from e
240
+ default = None
241
+ if n == 2:
242
+ minimum, maximum = v
243
+ elif n >= 3:
244
+ return cls(*v)
245
+ else:
246
+ raise ValueError(f"expected sequence of 2 or 3; got {n}: {v!r}")
247
+ return cls(minimum, default, maximum)
248
+
249
+ def limitRangeAndPopulateDefaults(self, fvarTriple) -> "AxisTriple":
250
+ """Return a new AxisTriple with the default value filled in.
251
+
252
+ Set default to fvar axis default if the latter is within the min/max range,
253
+ otherwise set default to the min or max value, whichever is closer to the
254
+ fvar axis default.
255
+ If the default value is already set, return self.
256
+ """
257
+ minimum = self.minimum
258
+ if minimum is None:
259
+ minimum = fvarTriple[0]
260
+ default = self.default
261
+ if default is None:
262
+ default = fvarTriple[1]
263
+ maximum = self.maximum
264
+ if maximum is None:
265
+ maximum = fvarTriple[2]
266
+
267
+ minimum = max(minimum, fvarTriple[0])
268
+ maximum = max(maximum, fvarTriple[0])
269
+ minimum = min(minimum, fvarTriple[2])
270
+ maximum = min(maximum, fvarTriple[2])
271
+ default = max(minimum, min(maximum, default))
272
+
273
+ return AxisTriple(minimum, default, maximum)
274
+
275
+
276
+ @dataclasses.dataclass(frozen=True, order=True, repr=False)
277
+ class NormalizedAxisTriple(AxisTriple):
278
+ """A triple of (min, default, max) normalized axis values."""
279
+
280
+ minimum: float
281
+ default: float
282
+ maximum: float
283
+
284
+ def __post_init__(self):
285
+ if self.default is None:
286
+ object.__setattr__(self, "default", max(self.minimum, min(self.maximum, 0)))
287
+ if not (-1.0 <= self.minimum <= self.default <= self.maximum <= 1.0):
288
+ raise ValueError(
289
+ "Normalized axis values not in -1..+1 range; got "
290
+ f"minimum={self.minimum:g}, default={self.default:g}, maximum={self.maximum:g})"
291
+ )
292
+
293
+
294
+ @dataclasses.dataclass(frozen=True, order=True, repr=False)
295
+ class NormalizedAxisTripleAndDistances(AxisTriple):
296
+ """A triple of (min, default, max) normalized axis values,
297
+ with distances between min and default, and default and max,
298
+ in the *pre-normalized* space."""
299
+
300
+ minimum: float
301
+ default: float
302
+ maximum: float
303
+ distanceNegative: Optional[float] = 1
304
+ distancePositive: Optional[float] = 1
305
+
306
+ def __post_init__(self):
307
+ if self.default is None:
308
+ object.__setattr__(self, "default", max(self.minimum, min(self.maximum, 0)))
309
+ if not (-1.0 <= self.minimum <= self.default <= self.maximum <= 1.0):
310
+ raise ValueError(
311
+ "Normalized axis values not in -1..+1 range; got "
312
+ f"minimum={self.minimum:g}, default={self.default:g}, maximum={self.maximum:g})"
313
+ )
314
+
315
+ def reverse_negate(self):
316
+ v = self
317
+ return self.__class__(-v[2], -v[1], -v[0], v[4], v[3])
318
+
319
+ def renormalizeValue(self, v, extrapolate=True):
320
+ """Renormalizes a normalized value v to the range of this axis,
321
+ considering the pre-normalized distances as well as the new
322
+ axis limits."""
323
+
324
+ lower, default, upper, distanceNegative, distancePositive = self
325
+ assert lower <= default <= upper
326
+
327
+ if not extrapolate:
328
+ v = max(lower, min(upper, v))
329
+
330
+ if v == default:
331
+ return 0
332
+
333
+ if default < 0:
334
+ return -self.reverse_negate().renormalizeValue(-v, extrapolate=extrapolate)
335
+
336
+ # default >= 0 and v != default
337
+
338
+ if v > default:
339
+ return (v - default) / (upper - default)
340
+
341
+ # v < default
342
+
343
+ if lower >= 0:
344
+ return (v - default) / (default - lower)
345
+
346
+ # lower < 0 and v < default
347
+
348
+ totalDistance = distanceNegative * -lower + distancePositive * default
349
+
350
+ if v >= 0:
351
+ vDistance = (default - v) * distancePositive
352
+ else:
353
+ vDistance = -v * distanceNegative + distancePositive * default
354
+
355
+ return -vDistance / totalDistance
356
+
357
+
358
+ class _BaseAxisLimits(Mapping[str, AxisTriple]):
359
+ def __getitem__(self, key: str) -> AxisTriple:
360
+ return self._data[key]
361
+
362
+ def __iter__(self) -> Iterable[str]:
363
+ return iter(self._data)
364
+
365
+ def __len__(self) -> int:
366
+ return len(self._data)
367
+
368
+ def __repr__(self) -> str:
369
+ return f"{type(self).__name__}({self._data!r})"
370
+
371
+ def __str__(self) -> str:
372
+ return str(self._data)
373
+
374
+ def defaultLocation(self) -> Dict[str, float]:
375
+ """Return a dict of default axis values."""
376
+ return {k: v.default for k, v in self.items()}
377
+
378
+ def pinnedLocation(self) -> Dict[str, float]:
379
+ """Return a location dict with only the pinned axes."""
380
+ return {k: v.default for k, v in self.items() if v.minimum == v.maximum}
381
+
382
+
383
+ class AxisLimits(_BaseAxisLimits):
384
+ """Maps axis tags (str) to AxisTriple values."""
385
+
386
+ def __init__(self, *args, **kwargs):
387
+ self._data = data = {}
388
+ for k, v in dict(*args, **kwargs).items():
389
+ if v is None:
390
+ # will be filled in by limitAxesAndPopulateDefaults
391
+ data[k] = v
392
+ else:
393
+ try:
394
+ triple = AxisTriple.expand(v)
395
+ except ValueError as e:
396
+ raise ValueError(f"Invalid axis limits for {k!r}: {v!r}") from e
397
+ data[k] = triple
398
+
399
+ def limitAxesAndPopulateDefaults(self, varfont) -> "AxisLimits":
400
+ """Return a new AxisLimits with defaults filled in from fvar table.
401
+
402
+ If all axis limits already have defaults, return self.
403
+ """
404
+ fvar = varfont["fvar"]
405
+ fvarTriples = {
406
+ a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in fvar.axes
407
+ }
408
+ newLimits = {}
409
+ for axisTag, triple in self.items():
410
+ fvarTriple = fvarTriples[axisTag]
411
+ default = fvarTriple[1]
412
+ if triple is None:
413
+ newLimits[axisTag] = AxisTriple(default, default, default)
414
+ else:
415
+ newLimits[axisTag] = triple.limitRangeAndPopulateDefaults(fvarTriple)
416
+ return type(self)(newLimits)
417
+
418
+ def normalize(self, varfont, usingAvar=True) -> "NormalizedAxisLimits":
419
+ """Return a new NormalizedAxisLimits with normalized -1..0..+1 values.
420
+
421
+ If usingAvar is True, the avar table is used to warp the default normalization.
422
+ """
423
+ fvar = varfont["fvar"]
424
+ badLimits = set(self.keys()).difference(a.axisTag for a in fvar.axes)
425
+ if badLimits:
426
+ raise ValueError("Cannot limit: {} not present in fvar".format(badLimits))
427
+
428
+ axes = {
429
+ a.axisTag: (a.minValue, a.defaultValue, a.maxValue)
430
+ for a in fvar.axes
431
+ if a.axisTag in self
432
+ }
433
+
434
+ avarSegments = {}
435
+ if usingAvar and "avar" in varfont:
436
+ avarSegments = varfont["avar"].segments
437
+
438
+ normalizedLimits = {}
439
+
440
+ for axis_tag, triple in axes.items():
441
+ distanceNegative = triple[1] - triple[0]
442
+ distancePositive = triple[2] - triple[1]
443
+
444
+ if self[axis_tag] is None:
445
+ normalizedLimits[axis_tag] = NormalizedAxisTripleAndDistances(
446
+ 0, 0, 0, distanceNegative, distancePositive
447
+ )
448
+ continue
449
+
450
+ minV, defaultV, maxV = self[axis_tag]
451
+
452
+ if defaultV is None:
453
+ defaultV = triple[1]
454
+
455
+ avarMapping = avarSegments.get(axis_tag, None)
456
+ normalizedLimits[axis_tag] = NormalizedAxisTripleAndDistances(
457
+ *(normalize(v, triple, avarMapping) for v in (minV, defaultV, maxV)),
458
+ distanceNegative,
459
+ distancePositive,
460
+ )
461
+
462
+ return NormalizedAxisLimits(normalizedLimits)
463
+
464
+
465
+ class NormalizedAxisLimits(_BaseAxisLimits):
466
+ """Maps axis tags (str) to NormalizedAxisTriple values."""
467
+
468
+ def __init__(self, *args, **kwargs):
469
+ self._data = data = {}
470
+ for k, v in dict(*args, **kwargs).items():
471
+ try:
472
+ triple = NormalizedAxisTripleAndDistances.expand(v)
473
+ except ValueError as e:
474
+ raise ValueError(f"Invalid axis limits for {k!r}: {v!r}") from e
475
+ data[k] = triple
476
+
477
+
478
+ class OverlapMode(IntEnum):
479
+ KEEP_AND_DONT_SET_FLAGS = 0
480
+ KEEP_AND_SET_FLAGS = 1
481
+ REMOVE = 2
482
+ REMOVE_AND_IGNORE_ERRORS = 3
483
+
484
+
485
+ def instantiateVARC(varfont, axisLimits):
486
+ log.info("Instantiating VARC tables")
487
+
488
+ # TODO(behdad) My confidence in this function is rather low;
489
+ # It needs more testing. Specially with partial-instancing,
490
+ # I don't think it currently works.
491
+
492
+ varc = varfont["VARC"].table
493
+ fvarAxes = varfont["fvar"].axes if "fvar" in varfont else []
494
+
495
+ location = axisLimits.pinnedLocation()
496
+ axisMap = [i for i, axis in enumerate(fvarAxes) if axis.axisTag not in location]
497
+ reverseAxisMap = {i: j for j, i in enumerate(axisMap)}
498
+
499
+ if varc.AxisIndicesList:
500
+ axisIndicesList = varc.AxisIndicesList.Item
501
+ for i, axisIndices in enumerate(axisIndicesList):
502
+ if any(fvarAxes[j].axisTag in axisLimits for j in axisIndices):
503
+ raise NotImplementedError(
504
+ "Instancing across VarComponent axes is not supported."
505
+ )
506
+ axisIndicesList[i] = [reverseAxisMap[j] for j in axisIndices]
507
+
508
+ store = varc.MultiVarStore
509
+ if store:
510
+ for region in store.SparseVarRegionList.Region:
511
+ newRegionAxis = []
512
+ for regionRecord in region.SparseVarRegionAxis:
513
+ tag = fvarAxes[regionRecord.AxisIndex].axisTag
514
+ if tag in axisLimits:
515
+ raise NotImplementedError(
516
+ "Instancing across VarComponent axes is not supported."
517
+ )
518
+ regionRecord.AxisIndex = reverseAxisMap[regionRecord.AxisIndex]
519
+
520
+
521
+ def instantiateTupleVariationStore(
522
+ variations, axisLimits, origCoords=None, endPts=None
523
+ ):
524
+ """Instantiate TupleVariation list at the given location, or limit axes' min/max.
525
+
526
+ The 'variations' list of TupleVariation objects is modified in-place.
527
+ The 'axisLimits' (dict) maps axis tags (str) to NormalizedAxisTriple namedtuples
528
+ specifying (minimum, default, maximum) in the -1,0,+1 normalized space. Pinned axes
529
+ have minimum == default == maximum.
530
+
531
+ A 'full' instance (i.e. static font) is produced when all the axes are pinned to
532
+ single coordinates; a 'partial' instance (i.e. a less variable font) is produced
533
+ when some of the axes are omitted, or restricted with a new range.
534
+
535
+ Tuples that do not participate are kept as they are. Those that have 0 influence
536
+ at the given location are removed from the variation store.
537
+ Those that are fully instantiated (i.e. all their axes are being pinned) are also
538
+ removed from the variation store, their scaled deltas accummulated and returned, so
539
+ that they can be added by the caller to the default instance's coordinates.
540
+ Tuples that are only partially instantiated (i.e. not all the axes that they
541
+ participate in are being pinned) are kept in the store, and their deltas multiplied
542
+ by the scalar support of the axes to be pinned at the desired location.
543
+
544
+ Args:
545
+ variations: List[TupleVariation] from either 'gvar' or 'cvar'.
546
+ axisLimits: NormalizedAxisLimits: map from axis tags to (min, default, max)
547
+ normalized coordinates for the full or partial instance.
548
+ origCoords: GlyphCoordinates: default instance's coordinates for computing 'gvar'
549
+ inferred points (cf. table__g_l_y_f._getCoordinatesAndControls).
550
+ endPts: List[int]: indices of contour end points, for inferring 'gvar' deltas.
551
+
552
+ Returns:
553
+ List[float]: the overall delta adjustment after applicable deltas were summed.
554
+ """
555
+
556
+ newVariations = changeTupleVariationsAxisLimits(variations, axisLimits)
557
+
558
+ mergedVariations = collections.OrderedDict()
559
+ for var in newVariations:
560
+ # compute inferred deltas only for gvar ('origCoords' is None for cvar)
561
+ if origCoords is not None:
562
+ var.calcInferredDeltas(origCoords, endPts)
563
+
564
+ # merge TupleVariations with overlapping "tents"
565
+ axes = frozenset(var.axes.items())
566
+ if axes in mergedVariations:
567
+ mergedVariations[axes] += var
568
+ else:
569
+ mergedVariations[axes] = var
570
+
571
+ # drop TupleVariation if all axes have been pinned (var.axes.items() is empty);
572
+ # its deltas will be added to the default instance's coordinates
573
+ defaultVar = mergedVariations.pop(frozenset(), None)
574
+
575
+ for var in mergedVariations.values():
576
+ var.roundDeltas()
577
+ variations[:] = list(mergedVariations.values())
578
+
579
+ return defaultVar.coordinates if defaultVar is not None else []
580
+
581
+
582
+ def changeTupleVariationsAxisLimits(variations, axisLimits):
583
+ for axisTag, axisLimit in sorted(axisLimits.items()):
584
+ newVariations = []
585
+ for var in variations:
586
+ newVariations.extend(changeTupleVariationAxisLimit(var, axisTag, axisLimit))
587
+ variations = newVariations
588
+ return variations
589
+
590
+
591
+ def changeTupleVariationAxisLimit(var, axisTag, axisLimit):
592
+ assert isinstance(axisLimit, NormalizedAxisTripleAndDistances)
593
+
594
+ # Skip when current axis is missing or peaks at 0 (i.e. doesn't participate)
595
+ lower, peak, upper = var.axes.get(axisTag, (-1, 0, 1))
596
+ if peak == 0:
597
+ # explicitly defined, no-op axes can be omitted
598
+ # https://github.com/fonttools/fonttools/issues/3453
599
+ if axisTag in var.axes:
600
+ del var.axes[axisTag]
601
+ return [var]
602
+ # Drop if the var 'tent' isn't well-formed
603
+ if not (lower <= peak <= upper) or (lower < 0 and upper > 0):
604
+ return []
605
+
606
+ if axisTag not in var.axes:
607
+ return [var]
608
+
609
+ tent = var.axes[axisTag]
610
+
611
+ solutions = solver.rebaseTent(tent, axisLimit)
612
+
613
+ out = []
614
+ for scalar, tent in solutions:
615
+ newVar = (
616
+ TupleVariation(var.axes, var.coordinates) if len(solutions) > 1 else var
617
+ )
618
+ if tent is None:
619
+ newVar.axes.pop(axisTag)
620
+ else:
621
+ assert tent[1] != 0, tent
622
+ newVar.axes[axisTag] = tent
623
+ newVar *= scalar
624
+ out.append(newVar)
625
+
626
+ return out
627
+
628
+
629
+ def instantiateCFF2(
630
+ varfont,
631
+ axisLimits,
632
+ *,
633
+ round=round,
634
+ specialize=True,
635
+ generalize=False,
636
+ downgrade=False,
637
+ ):
638
+ # The algorithm here is rather simple:
639
+ #
640
+ # Take all blend operations and store their deltas in the (otherwise empty)
641
+ # CFF2 VarStore. Then, instantiate the VarStore with the given axis limits,
642
+ # and read back the new deltas. This is done for both the CharStrings and
643
+ # the Private dicts.
644
+ #
645
+ # Then prune unused things and possibly drop the VarStore if it's empty.
646
+ # In which case, downgrade to CFF table if requested.
647
+
648
+ log.info("Instantiating CFF2 table")
649
+
650
+ fvarAxes = varfont["fvar"].axes
651
+
652
+ cff = varfont["CFF2"].cff
653
+ topDict = cff.topDictIndex[0]
654
+ varStore = topDict.VarStore.otVarStore
655
+ if not varStore:
656
+ if downgrade:
657
+ from fontTools.cffLib.CFF2ToCFF import convertCFF2ToCFF
658
+
659
+ convertCFF2ToCFF(varfont)
660
+ return
661
+
662
+ cff.desubroutinize()
663
+
664
+ def getNumRegions(vsindex):
665
+ return varStore.VarData[vsindex if vsindex is not None else 0].VarRegionCount
666
+
667
+ charStrings = topDict.CharStrings.values()
668
+
669
+ # Gather all unique private dicts
670
+ uniquePrivateDicts = set()
671
+ privateDicts = []
672
+ for fd in topDict.FDArray:
673
+ if fd.Private not in uniquePrivateDicts:
674
+ uniquePrivateDicts.add(fd.Private)
675
+ privateDicts.append(fd.Private)
676
+
677
+ allCommands = []
678
+ allCommandPrivates = []
679
+ for cs in charStrings:
680
+ assert cs.private.vstore.otVarStore is varStore # Or in many places!!
681
+ commands = programToCommands(cs.program, getNumRegions=getNumRegions)
682
+ if generalize:
683
+ commands = generalizeCommands(commands)
684
+ if specialize:
685
+ commands = specializeCommands(commands, generalizeFirst=not generalize)
686
+ allCommands.append(commands)
687
+ allCommandPrivates.append(cs.private)
688
+
689
+ def storeBlendsToVarStore(arg):
690
+ if not isinstance(arg, list):
691
+ return
692
+
693
+ if any(isinstance(subarg, list) for subarg in arg[:-1]):
694
+ raise NotImplementedError("Nested blend lists not supported (yet)")
695
+
696
+ count = arg[-1]
697
+ assert (len(arg) - 1) % count == 0
698
+ nRegions = (len(arg) - 1) // count - 1
699
+ assert nRegions == getNumRegions(vsindex)
700
+ for i in range(count, len(arg) - 1, nRegions):
701
+ deltas = arg[i : i + nRegions]
702
+ assert len(deltas) == nRegions
703
+ varData = varStore.VarData[vsindex]
704
+ varData.Item.append(deltas)
705
+ varData.ItemCount += 1
706
+
707
+ def fetchBlendsFromVarStore(arg):
708
+ if not isinstance(arg, list):
709
+ return [arg]
710
+
711
+ if any(isinstance(subarg, list) for subarg in arg[:-1]):
712
+ raise NotImplementedError("Nested blend lists not supported (yet)")
713
+
714
+ count = arg[-1]
715
+ assert (len(arg) - 1) % count == 0
716
+ numRegions = getNumRegions(vsindex)
717
+ newDefaults = []
718
+ newDeltas = []
719
+ for i in range(count):
720
+ defaultValue = arg[i]
721
+
722
+ major = vsindex
723
+ minor = varDataCursor[major]
724
+ varDataCursor[major] += 1
725
+
726
+ varIdx = (major << 16) + minor
727
+
728
+ defaultValue += round(defaultDeltas[varIdx])
729
+ newDefaults.append(defaultValue)
730
+
731
+ varData = varStore.VarData[major]
732
+ deltas = varData.Item[minor]
733
+ assert len(deltas) == numRegions
734
+ newDeltas.extend(deltas)
735
+
736
+ if not numRegions:
737
+ return newDefaults # No deltas, just return the defaults
738
+
739
+ return [newDefaults + newDeltas + [count]]
740
+
741
+ # Check VarData's are empty
742
+ for varData in varStore.VarData:
743
+ assert varData.Item == []
744
+ assert varData.ItemCount == 0
745
+
746
+ # Add charstring blend lists to VarStore so we can instantiate them
747
+ for commands, private in zip(allCommands, allCommandPrivates):
748
+ vsindex = getattr(private, "vsindex", 0)
749
+ for command in commands:
750
+ if command[0] == "vsindex":
751
+ vsindex = command[1][0]
752
+ continue
753
+ for arg in command[1]:
754
+ storeBlendsToVarStore(arg)
755
+
756
+ # Add private blend lists to VarStore so we can instantiate values
757
+ for opcode, name, arg_type, default, converter in privateDictOperators2:
758
+ if arg_type not in ("number", "delta", "array"):
759
+ continue
760
+
761
+ vsindex = 0
762
+ for private in privateDicts:
763
+ if not hasattr(private, name):
764
+ continue
765
+ values = getattr(private, name)
766
+
767
+ # This is safe here since "vsindex" is the first in the privateDictOperators2
768
+ if name == "vsindex":
769
+ vsindex = values[0]
770
+ continue
771
+
772
+ if arg_type == "number":
773
+ values = [values]
774
+
775
+ for value in values:
776
+ if not isinstance(value, list):
777
+ continue
778
+
779
+ assert len(value) % (getNumRegions(vsindex) + 1) == 0
780
+ count = len(value) // (getNumRegions(vsindex) + 1)
781
+ storeBlendsToVarStore(value + [count])
782
+
783
+ # Instantiate VarStore
784
+ defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
785
+
786
+ # Read back new charstring blends from the instantiated VarStore
787
+ varDataCursor = [0] * len(varStore.VarData)
788
+ for commands, private in zip(allCommands, allCommandPrivates):
789
+ vsindex = getattr(private, "vsindex", 0)
790
+ for command in commands:
791
+ if command[0] == "vsindex":
792
+ vsindex = command[1][0]
793
+ continue
794
+ newArgs = []
795
+ for arg in command[1]:
796
+ newArgs.extend(fetchBlendsFromVarStore(arg))
797
+ command[1][:] = newArgs
798
+
799
+ # Read back new private blends from the instantiated VarStore
800
+ for opcode, name, arg_type, default, converter in privateDictOperators2:
801
+ if arg_type not in ("number", "delta", "array"):
802
+ continue
803
+
804
+ vsindex = 0
805
+ for private in privateDicts:
806
+ if not hasattr(private, name):
807
+ continue
808
+
809
+ # This is safe here since "vsindex" is the first in the privateDictOperators2
810
+ if name == "vsindex":
811
+ vsindex = values[0]
812
+ continue
813
+
814
+ values = getattr(private, name)
815
+ if arg_type == "number":
816
+ values = [values]
817
+
818
+ newValues = []
819
+ for value in values:
820
+ if not isinstance(value, list):
821
+ newValues.append(value)
822
+ continue
823
+
824
+ value.append(1)
825
+ value = fetchBlendsFromVarStore(value)
826
+ newValues.extend(v[:-1] if isinstance(v, list) else v for v in value)
827
+
828
+ if arg_type == "number":
829
+ newValues = newValues[0]
830
+
831
+ setattr(private, name, newValues)
832
+
833
+ # Empty out the VarStore
834
+ for i, varData in enumerate(varStore.VarData):
835
+ assert varDataCursor[i] == varData.ItemCount, (
836
+ varDataCursor[i],
837
+ varData.ItemCount,
838
+ )
839
+ varData.Item = []
840
+ varData.ItemCount = 0
841
+
842
+ # Remove vsindex commands that are no longer needed, collect those that are.
843
+ usedVsindex = set()
844
+ for commands in allCommands:
845
+ if any(isinstance(arg, list) for command in commands for arg in command[1]):
846
+ vsindex = 0
847
+ for command in commands:
848
+ if command[0] == "vsindex":
849
+ vsindex = command[1][0]
850
+ continue
851
+ if any(isinstance(arg, list) for arg in command[1]):
852
+ usedVsindex.add(vsindex)
853
+ else:
854
+ commands[:] = [command for command in commands if command[0] != "vsindex"]
855
+
856
+ # Remove unused VarData and update vsindex values
857
+ vsindexMapping = {v: i for i, v in enumerate(sorted(usedVsindex))}
858
+ varStore.VarData = [
859
+ varData for i, varData in enumerate(varStore.VarData) if i in usedVsindex
860
+ ]
861
+ varStore.VarDataCount = len(varStore.VarData)
862
+ for commands in allCommands:
863
+ for command in commands:
864
+ if command[0] == "vsindex":
865
+ command[1][0] = vsindexMapping[command[1][0]]
866
+
867
+ # Remove initial vsindex commands that are implied
868
+ for commands in allCommands:
869
+ if commands and commands[0] == ("vsindex", [0]):
870
+ commands.pop(0)
871
+
872
+ # Ship the charstrings!
873
+ for cs, commands in zip(charStrings, allCommands):
874
+ cs.program = commandsToProgram(commands)
875
+
876
+ # Remove empty VarStore
877
+ if not varStore.VarData:
878
+ if "VarStore" in topDict.rawDict:
879
+ del topDict.rawDict["VarStore"]
880
+ del topDict.VarStore
881
+ del topDict.CharStrings.varStore
882
+ for private in privateDicts:
883
+ del private.vstore
884
+
885
+ if downgrade:
886
+ from fontTools.cffLib.CFF2ToCFF import convertCFF2ToCFF
887
+
888
+ convertCFF2ToCFF(varfont)
889
+
890
+
891
+ def _instantiateGvarGlyph(
892
+ glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=True
893
+ ):
894
+ coordinates, ctrl = glyf._getCoordinatesAndControls(glyphname, hMetrics, vMetrics)
895
+ endPts = ctrl.endPts
896
+
897
+ # Not every glyph may have variations
898
+ tupleVarStore = gvar.variations.get(glyphname)
899
+
900
+ if tupleVarStore:
901
+ defaultDeltas = instantiateTupleVariationStore(
902
+ tupleVarStore, axisLimits, coordinates, endPts
903
+ )
904
+
905
+ if defaultDeltas:
906
+ coordinates += _g_l_y_f.GlyphCoordinates(defaultDeltas)
907
+
908
+ # _setCoordinates also sets the hmtx/vmtx advance widths and sidebearings from
909
+ # the four phantom points and glyph bounding boxes.
910
+ # We call it unconditionally even if a glyph has no variations or no deltas are
911
+ # applied at this location, in case the glyph's xMin and in turn its sidebearing
912
+ # have changed. E.g. a composite glyph has no deltas for the component's (x, y)
913
+ # offset nor for the 4 phantom points (e.g. it's monospaced). Thus its entry in
914
+ # gvar table is empty; however, the composite's base glyph may have deltas
915
+ # applied, hence the composite's bbox and left/top sidebearings may need updating
916
+ # in the instanced font.
917
+ glyf._setCoordinates(glyphname, coordinates, hMetrics, vMetrics)
918
+
919
+ if not tupleVarStore:
920
+ if glyphname in gvar.variations:
921
+ del gvar.variations[glyphname]
922
+ return
923
+
924
+ if optimize:
925
+ # IUP semantics depend on point equality, and so round prior to
926
+ # optimization to ensure that comparisons that happen now will be the
927
+ # same as those that happen at render time. This is especially needed
928
+ # when floating point deltas have been applied to the default position.
929
+ # See https://github.com/fonttools/fonttools/issues/3634
930
+ # Rounding must happen only after calculating glyf metrics above, to
931
+ # preserve backwards compatibility.
932
+ # See 0010a3cd9aa25f84a3a6250dafb119743d32aa40
933
+ coordinates.toInt()
934
+
935
+ isComposite = glyf[glyphname].isComposite()
936
+
937
+ for var in tupleVarStore:
938
+ var.optimize(coordinates, endPts, isComposite=isComposite)
939
+
940
+
941
+ def instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True):
942
+ """Remove?
943
+ https://github.com/fonttools/fonttools/pull/2266"""
944
+ gvar = varfont["gvar"]
945
+ glyf = varfont["glyf"]
946
+ hMetrics = varfont["hmtx"].metrics
947
+ vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
948
+ _instantiateGvarGlyph(
949
+ glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
950
+ )
951
+
952
+
953
+ def instantiateGvar(varfont, axisLimits, optimize=True):
954
+ log.info("Instantiating glyf/gvar tables")
955
+
956
+ gvar = varfont["gvar"]
957
+ glyf = varfont["glyf"]
958
+ hMetrics = varfont["hmtx"].metrics
959
+ vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
960
+ # Get list of glyph names sorted by component depth.
961
+ # If a composite glyph is processed before its base glyph, the bounds may
962
+ # be calculated incorrectly because deltas haven't been applied to the
963
+ # base glyph yet.
964
+ glyphnames = sorted(
965
+ glyf.glyphOrder,
966
+ key=lambda name: (
967
+ (
968
+ glyf[name].getCompositeMaxpValues(glyf).maxComponentDepth
969
+ if glyf[name].isComposite()
970
+ else 0
971
+ ),
972
+ name,
973
+ ),
974
+ )
975
+ for glyphname in glyphnames:
976
+ _instantiateGvarGlyph(
977
+ glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
978
+ )
979
+
980
+ if not gvar.variations:
981
+ del varfont["gvar"]
982
+
983
+
984
+ def setCvarDeltas(cvt, deltas):
985
+ for i, delta in enumerate(deltas):
986
+ if delta:
987
+ cvt[i] += otRound(delta)
988
+
989
+
990
+ def instantiateCvar(varfont, axisLimits):
991
+ log.info("Instantiating cvt/cvar tables")
992
+
993
+ cvar = varfont["cvar"]
994
+
995
+ defaultDeltas = instantiateTupleVariationStore(cvar.variations, axisLimits)
996
+
997
+ if defaultDeltas:
998
+ setCvarDeltas(varfont["cvt "], defaultDeltas)
999
+
1000
+ if not cvar.variations:
1001
+ del varfont["cvar"]
1002
+
1003
+
1004
+ def setMvarDeltas(varfont, deltas):
1005
+ mvar = varfont["MVAR"].table
1006
+ records = mvar.ValueRecord
1007
+ for rec in records:
1008
+ mvarTag = rec.ValueTag
1009
+ if mvarTag not in MVAR_ENTRIES:
1010
+ continue
1011
+ tableTag, itemName = MVAR_ENTRIES[mvarTag]
1012
+ delta = deltas[rec.VarIdx]
1013
+ if delta != 0:
1014
+ setattr(
1015
+ varfont[tableTag],
1016
+ itemName,
1017
+ getattr(varfont[tableTag], itemName) + otRound(delta),
1018
+ )
1019
+
1020
+
1021
+ @contextmanager
1022
+ def verticalMetricsKeptInSync(varfont):
1023
+ """Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing.
1024
+
1025
+ When applying MVAR deltas to the OS/2 table, if the ascender, descender and
1026
+ line gap change but they were the same as the respective hhea metrics in the
1027
+ original font, this context manager ensures that hhea metrcs also get updated
1028
+ accordingly.
1029
+ The MVAR spec only has tags for the OS/2 metrics, but it is common in fonts
1030
+ to have the hhea metrics be equal to those for compat reasons.
1031
+
1032
+ https://learn.microsoft.com/en-us/typography/opentype/spec/mvar
1033
+ https://googlefonts.github.io/gf-guide/metrics.html#7-hhea-and-typo-metrics-should-be-equal
1034
+ https://github.com/fonttools/fonttools/issues/3297
1035
+ """
1036
+ current_os2_vmetrics = [
1037
+ getattr(varfont["OS/2"], attr)
1038
+ for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap")
1039
+ ]
1040
+ metrics_are_synced = current_os2_vmetrics == [
1041
+ getattr(varfont["hhea"], attr) for attr in ("ascender", "descender", "lineGap")
1042
+ ]
1043
+
1044
+ yield metrics_are_synced
1045
+
1046
+ if metrics_are_synced:
1047
+ new_os2_vmetrics = [
1048
+ getattr(varfont["OS/2"], attr)
1049
+ for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap")
1050
+ ]
1051
+ if current_os2_vmetrics != new_os2_vmetrics:
1052
+ for attr, value in zip(
1053
+ ("ascender", "descender", "lineGap"), new_os2_vmetrics
1054
+ ):
1055
+ setattr(varfont["hhea"], attr, value)
1056
+
1057
+
1058
+ def instantiateMVAR(varfont, axisLimits):
1059
+ log.info("Instantiating MVAR table")
1060
+
1061
+ mvar = varfont["MVAR"].table
1062
+ fvarAxes = varfont["fvar"].axes
1063
+ varStore = mvar.VarStore
1064
+ defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
1065
+
1066
+ with verticalMetricsKeptInSync(varfont):
1067
+ setMvarDeltas(varfont, defaultDeltas)
1068
+
1069
+ if varStore.VarRegionList.Region:
1070
+ varIndexMapping = varStore.optimize()
1071
+ for rec in mvar.ValueRecord:
1072
+ rec.VarIdx = varIndexMapping[rec.VarIdx]
1073
+ else:
1074
+ del varfont["MVAR"]
1075
+
1076
+
1077
+ def _remapVarIdxMap(table, attrName, varIndexMapping, glyphOrder):
1078
+ oldMapping = getattr(table, attrName).mapping
1079
+ newMapping = [varIndexMapping[oldMapping[glyphName]] for glyphName in glyphOrder]
1080
+ setattr(table, attrName, builder.buildVarIdxMap(newMapping, glyphOrder))
1081
+
1082
+
1083
+ # TODO(anthrotype) Add support for HVAR/VVAR in CFF2
1084
+ def _instantiateVHVAR(varfont, axisLimits, tableFields, *, round=round):
1085
+ location = axisLimits.pinnedLocation()
1086
+ tableTag = tableFields.tableTag
1087
+ fvarAxes = varfont["fvar"].axes
1088
+
1089
+ log.info("Instantiating %s table", tableTag)
1090
+ vhvar = varfont[tableTag].table
1091
+ varStore = vhvar.VarStore
1092
+
1093
+ if "glyf" in varfont:
1094
+ # Deltas from gvar table have already been applied to the hmtx/vmtx. For full
1095
+ # instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return
1096
+ if set(location).issuperset(axis.axisTag for axis in fvarAxes):
1097
+ log.info("Dropping %s table", tableTag)
1098
+ del varfont[tableTag]
1099
+ return
1100
+
1101
+ defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
1102
+
1103
+ if "glyf" not in varfont:
1104
+ # CFF2 fonts need hmtx/vmtx updated here. For glyf fonts, the instantiateGvar
1105
+ # function already updated the hmtx/vmtx from phantom points. Maybe remove
1106
+ # that and do it here for both CFF2 and glyf fonts?
1107
+ #
1108
+ # Specially, if a font has glyf but not gvar, the hmtx/vmtx will not have been
1109
+ # updated by instantiateGvar. Though one can call that a faulty font.
1110
+ metricsTag = "vmtx" if tableTag == "VVAR" else "hmtx"
1111
+ if metricsTag in varfont:
1112
+ advMapping = getattr(vhvar, tableFields.advMapping)
1113
+ metricsTable = varfont[metricsTag]
1114
+ metrics = metricsTable.metrics
1115
+ for glyphName, (advanceWidth, sb) in metrics.items():
1116
+ if advMapping:
1117
+ varIdx = advMapping.mapping[glyphName]
1118
+ else:
1119
+ varIdx = varfont.getGlyphID(glyphName)
1120
+ metrics[glyphName] = (advanceWidth + round(defaultDeltas[varIdx]), sb)
1121
+
1122
+ if (
1123
+ tableTag == "VVAR"
1124
+ and getattr(vhvar, tableFields.vOrigMapping) is not None
1125
+ ):
1126
+ log.warning(
1127
+ "VORG table not yet updated to reflect changes in VVAR table"
1128
+ )
1129
+
1130
+ # For full instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return
1131
+ if set(location).issuperset(axis.axisTag for axis in fvarAxes):
1132
+ log.info("Dropping %s table", tableTag)
1133
+ del varfont[tableTag]
1134
+ return
1135
+
1136
+ if varStore.VarRegionList.Region:
1137
+ # Only re-optimize VarStore if the HVAR/VVAR already uses indirect AdvWidthMap
1138
+ # or AdvHeightMap. If a direct, implicit glyphID->VariationIndex mapping is
1139
+ # used for advances, skip re-optimizing and maintain original VariationIndex.
1140
+ if getattr(vhvar, tableFields.advMapping):
1141
+ varIndexMapping = varStore.optimize(use_NO_VARIATION_INDEX=False)
1142
+ glyphOrder = varfont.getGlyphOrder()
1143
+ _remapVarIdxMap(vhvar, tableFields.advMapping, varIndexMapping, glyphOrder)
1144
+ if getattr(vhvar, tableFields.sb1): # left or top sidebearings
1145
+ _remapVarIdxMap(vhvar, tableFields.sb1, varIndexMapping, glyphOrder)
1146
+ if getattr(vhvar, tableFields.sb2): # right or bottom sidebearings
1147
+ _remapVarIdxMap(vhvar, tableFields.sb2, varIndexMapping, glyphOrder)
1148
+ if tableTag == "VVAR" and getattr(vhvar, tableFields.vOrigMapping):
1149
+ _remapVarIdxMap(
1150
+ vhvar, tableFields.vOrigMapping, varIndexMapping, glyphOrder
1151
+ )
1152
+
1153
+
1154
+ def instantiateHVAR(varfont, axisLimits):
1155
+ return _instantiateVHVAR(varfont, axisLimits, varLib.HVAR_FIELDS)
1156
+
1157
+
1158
+ def instantiateVVAR(varfont, axisLimits):
1159
+ return _instantiateVHVAR(varfont, axisLimits, varLib.VVAR_FIELDS)
1160
+
1161
+
1162
+ class _TupleVarStoreAdapter(object):
1163
+ def __init__(self, regions, axisOrder, tupleVarData, itemCounts):
1164
+ self.regions = regions
1165
+ self.axisOrder = axisOrder
1166
+ self.tupleVarData = tupleVarData
1167
+ self.itemCounts = itemCounts
1168
+
1169
+ @classmethod
1170
+ def fromItemVarStore(cls, itemVarStore, fvarAxes):
1171
+ axisOrder = [axis.axisTag for axis in fvarAxes]
1172
+ regions = [
1173
+ region.get_support(fvarAxes) for region in itemVarStore.VarRegionList.Region
1174
+ ]
1175
+ tupleVarData = []
1176
+ itemCounts = []
1177
+ for varData in itemVarStore.VarData:
1178
+ variations = []
1179
+ varDataRegions = (regions[i] for i in varData.VarRegionIndex)
1180
+ for axes, coordinates in zip(varDataRegions, zip(*varData.Item)):
1181
+ variations.append(TupleVariation(axes, list(coordinates)))
1182
+ tupleVarData.append(variations)
1183
+ itemCounts.append(varData.ItemCount)
1184
+ return cls(regions, axisOrder, tupleVarData, itemCounts)
1185
+
1186
+ def rebuildRegions(self):
1187
+ # Collect the set of all unique region axes from the current TupleVariations.
1188
+ # We use an OrderedDict to de-duplicate regions while keeping the order.
1189
+ uniqueRegions = collections.OrderedDict.fromkeys(
1190
+ (
1191
+ frozenset(var.axes.items())
1192
+ for variations in self.tupleVarData
1193
+ for var in variations
1194
+ )
1195
+ )
1196
+ # Maintain the original order for the regions that pre-existed, appending
1197
+ # the new regions at the end of the region list.
1198
+ newRegions = []
1199
+ for region in self.regions:
1200
+ regionAxes = frozenset(region.items())
1201
+ if regionAxes in uniqueRegions:
1202
+ newRegions.append(region)
1203
+ del uniqueRegions[regionAxes]
1204
+ if uniqueRegions:
1205
+ newRegions.extend(dict(region) for region in uniqueRegions)
1206
+ self.regions = newRegions
1207
+
1208
+ def instantiate(self, axisLimits):
1209
+ defaultDeltaArray = []
1210
+ for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
1211
+ defaultDeltas = instantiateTupleVariationStore(variations, axisLimits)
1212
+ if not defaultDeltas:
1213
+ defaultDeltas = [0] * itemCount
1214
+ defaultDeltaArray.append(defaultDeltas)
1215
+
1216
+ # rebuild regions whose axes were dropped or limited
1217
+ self.rebuildRegions()
1218
+
1219
+ pinnedAxes = set(axisLimits.pinnedLocation())
1220
+ self.axisOrder = [
1221
+ axisTag for axisTag in self.axisOrder if axisTag not in pinnedAxes
1222
+ ]
1223
+
1224
+ return defaultDeltaArray
1225
+
1226
+ def asItemVarStore(self):
1227
+ regionOrder = [frozenset(axes.items()) for axes in self.regions]
1228
+ varDatas = []
1229
+ for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
1230
+ if variations:
1231
+ assert len(variations[0].coordinates) == itemCount
1232
+ varRegionIndices = [
1233
+ regionOrder.index(frozenset(var.axes.items())) for var in variations
1234
+ ]
1235
+ varDataItems = list(zip(*(var.coordinates for var in variations)))
1236
+ varDatas.append(
1237
+ builder.buildVarData(varRegionIndices, varDataItems, optimize=False)
1238
+ )
1239
+ else:
1240
+ varDatas.append(
1241
+ builder.buildVarData([], [[] for _ in range(itemCount)])
1242
+ )
1243
+ regionList = builder.buildVarRegionList(self.regions, self.axisOrder)
1244
+ itemVarStore = builder.buildVarStore(regionList, varDatas)
1245
+ # remove unused regions from VarRegionList
1246
+ itemVarStore.prune_regions()
1247
+ return itemVarStore
1248
+
1249
+
1250
+ def instantiateItemVariationStore(itemVarStore, fvarAxes, axisLimits):
1251
+ """Compute deltas at partial location, and update varStore in-place.
1252
+
1253
+ Remove regions in which all axes were instanced, or fall outside the new axis
1254
+ limits. Scale the deltas of the remaining regions where only some of the axes
1255
+ were instanced.
1256
+
1257
+ The number of VarData subtables, and the number of items within each, are
1258
+ not modified, in order to keep the existing VariationIndex valid.
1259
+ One may call VarStore.optimize() method after this to further optimize those.
1260
+
1261
+ Args:
1262
+ varStore: An otTables.VarStore object (Item Variation Store)
1263
+ fvarAxes: list of fvar's Axis objects
1264
+ axisLimits: NormalizedAxisLimits: mapping axis tags to normalized
1265
+ min/default/max axis coordinates. May not specify coordinates/ranges for
1266
+ all the fvar axes.
1267
+
1268
+ Returns:
1269
+ defaultDeltas: to be added to the default instance, of type dict of floats
1270
+ keyed by VariationIndex compound values: i.e. (outer << 16) + inner.
1271
+ """
1272
+ tupleVarStore = _TupleVarStoreAdapter.fromItemVarStore(itemVarStore, fvarAxes)
1273
+ defaultDeltaArray = tupleVarStore.instantiate(axisLimits)
1274
+ newItemVarStore = tupleVarStore.asItemVarStore()
1275
+
1276
+ itemVarStore.VarRegionList = newItemVarStore.VarRegionList
1277
+ if not hasattr(itemVarStore, "VarDataCount"): # Happens fromXML
1278
+ itemVarStore.VarDataCount = len(newItemVarStore.VarData)
1279
+ assert itemVarStore.VarDataCount == newItemVarStore.VarDataCount
1280
+ itemVarStore.VarData = newItemVarStore.VarData
1281
+
1282
+ defaultDeltas = {
1283
+ ((major << 16) + minor): delta
1284
+ for major, deltas in enumerate(defaultDeltaArray)
1285
+ for minor, delta in enumerate(deltas)
1286
+ }
1287
+ defaultDeltas[itemVarStore.NO_VARIATION_INDEX] = 0
1288
+ return defaultDeltas
1289
+
1290
+
1291
+ def instantiateOTL(varfont, axisLimits):
1292
+ # TODO(anthrotype) Support partial instancing of JSTF and BASE tables
1293
+
1294
+ if (
1295
+ "GDEF" not in varfont
1296
+ or varfont["GDEF"].table.Version < 0x00010003
1297
+ or not varfont["GDEF"].table.VarStore
1298
+ ):
1299
+ return
1300
+
1301
+ if "GPOS" in varfont:
1302
+ msg = "Instantiating GDEF and GPOS tables"
1303
+ else:
1304
+ msg = "Instantiating GDEF table"
1305
+ log.info(msg)
1306
+
1307
+ gdef = varfont["GDEF"].table
1308
+ varStore = gdef.VarStore
1309
+ fvarAxes = varfont["fvar"].axes
1310
+
1311
+ defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
1312
+
1313
+ # When VF are built, big lookups may overflow and be broken into multiple
1314
+ # subtables. MutatorMerger (which inherits from AligningMerger) reattaches
1315
+ # them upon instancing, in case they can now fit a single subtable (if not,
1316
+ # they will be split again upon compilation).
1317
+ # This 'merger' also works as a 'visitor' that traverses the OTL tables and
1318
+ # calls specific methods when instances of a given type are found.
1319
+ # Specifically, it adds default deltas to GPOS Anchors/ValueRecords and GDEF
1320
+ # LigatureCarets, and optionally deletes all VariationIndex tables if the
1321
+ # VarStore is fully instanced.
1322
+ merger = MutatorMerger(
1323
+ varfont, defaultDeltas, deleteVariations=(not varStore.VarRegionList.Region)
1324
+ )
1325
+ merger.mergeTables(varfont, [varfont], ["GDEF", "GPOS"])
1326
+
1327
+ if varStore.VarRegionList.Region:
1328
+ varIndexMapping = varStore.optimize()
1329
+ gdef.remap_device_varidxes(varIndexMapping)
1330
+ if "GPOS" in varfont:
1331
+ varfont["GPOS"].table.remap_device_varidxes(varIndexMapping)
1332
+ else:
1333
+ # Downgrade GDEF.
1334
+ del gdef.VarStore
1335
+ gdef.Version = 0x00010002
1336
+ if gdef.MarkGlyphSetsDef is None:
1337
+ del gdef.MarkGlyphSetsDef
1338
+ gdef.Version = 0x00010000
1339
+
1340
+ if not (
1341
+ gdef.LigCaretList
1342
+ or gdef.MarkAttachClassDef
1343
+ or gdef.GlyphClassDef
1344
+ or gdef.AttachList
1345
+ or (gdef.Version >= 0x00010002 and gdef.MarkGlyphSetsDef)
1346
+ ):
1347
+ del varfont["GDEF"]
1348
+
1349
+
1350
+ def _isValidAvarSegmentMap(axisTag, segmentMap):
1351
+ if not segmentMap:
1352
+ return True
1353
+ if not {(-1.0, -1.0), (0, 0), (1.0, 1.0)}.issubset(segmentMap.items()):
1354
+ log.warning(
1355
+ f"Invalid avar SegmentMap record for axis '{axisTag}': does not "
1356
+ "include all required value maps {-1.0: -1.0, 0: 0, 1.0: 1.0}"
1357
+ )
1358
+ return False
1359
+ previousValue = None
1360
+ for fromCoord, toCoord in sorted(segmentMap.items()):
1361
+ if previousValue is not None and previousValue > toCoord:
1362
+ log.warning(
1363
+ f"Invalid avar AxisValueMap({fromCoord}, {toCoord}) record "
1364
+ f"for axis '{axisTag}': the toCoordinate value must be >= to "
1365
+ f"the toCoordinate value of the preceding record ({previousValue})."
1366
+ )
1367
+ return False
1368
+ previousValue = toCoord
1369
+ return True
1370
+
1371
+
1372
+ def instantiateAvar(varfont, axisLimits):
1373
+ # 'axisLimits' dict must contain user-space (non-normalized) coordinates.
1374
+
1375
+ avar = varfont["avar"]
1376
+ if getattr(avar, "majorVersion", 1) >= 2 and avar.table.VarStore:
1377
+ raise NotImplementedError("avar table with VarStore is not supported")
1378
+
1379
+ segments = avar.segments
1380
+
1381
+ # drop table if we instantiate all the axes
1382
+ pinnedAxes = set(axisLimits.pinnedLocation())
1383
+ if pinnedAxes.issuperset(segments):
1384
+ log.info("Dropping avar table")
1385
+ del varfont["avar"]
1386
+ return
1387
+
1388
+ log.info("Instantiating avar table")
1389
+ for axis in pinnedAxes:
1390
+ if axis in segments:
1391
+ del segments[axis]
1392
+
1393
+ # First compute the default normalization for axisLimits coordinates: i.e.
1394
+ # min = -1.0, default = 0, max = +1.0, and in between values interpolated linearly,
1395
+ # without using the avar table's mappings.
1396
+ # Then, for each SegmentMap, if we are restricting its axis, compute the new
1397
+ # mappings by dividing the key/value pairs by the desired new min/max values,
1398
+ # dropping any mappings that fall outside the restricted range.
1399
+ # The keys ('fromCoord') are specified in default normalized coordinate space,
1400
+ # whereas the values ('toCoord') are "mapped forward" using the SegmentMap.
1401
+ normalizedRanges = axisLimits.normalize(varfont, usingAvar=False)
1402
+ newSegments = {}
1403
+ for axisTag, mapping in segments.items():
1404
+ if not _isValidAvarSegmentMap(axisTag, mapping):
1405
+ continue
1406
+ if mapping and axisTag in normalizedRanges:
1407
+ axisRange = normalizedRanges[axisTag]
1408
+ mappedMin = floatToFixedToFloat(
1409
+ piecewiseLinearMap(axisRange.minimum, mapping), 14
1410
+ )
1411
+ mappedDef = floatToFixedToFloat(
1412
+ piecewiseLinearMap(axisRange.default, mapping), 14
1413
+ )
1414
+ mappedMax = floatToFixedToFloat(
1415
+ piecewiseLinearMap(axisRange.maximum, mapping), 14
1416
+ )
1417
+ mappedAxisLimit = NormalizedAxisTripleAndDistances(
1418
+ mappedMin,
1419
+ mappedDef,
1420
+ mappedMax,
1421
+ axisRange.distanceNegative,
1422
+ axisRange.distancePositive,
1423
+ )
1424
+ newMapping = {}
1425
+ for fromCoord, toCoord in mapping.items():
1426
+ if fromCoord < axisRange.minimum or fromCoord > axisRange.maximum:
1427
+ continue
1428
+ fromCoord = axisRange.renormalizeValue(fromCoord)
1429
+
1430
+ assert mappedMin <= toCoord <= mappedMax
1431
+ toCoord = mappedAxisLimit.renormalizeValue(toCoord)
1432
+
1433
+ fromCoord = floatToFixedToFloat(fromCoord, 14)
1434
+ toCoord = floatToFixedToFloat(toCoord, 14)
1435
+ newMapping[fromCoord] = toCoord
1436
+ newMapping.update({-1.0: -1.0, 0.0: 0.0, 1.0: 1.0})
1437
+ newSegments[axisTag] = newMapping
1438
+ else:
1439
+ newSegments[axisTag] = mapping
1440
+ avar.segments = newSegments
1441
+
1442
+
1443
+ def isInstanceWithinAxisRanges(location, axisRanges):
1444
+ for axisTag, coord in location.items():
1445
+ if axisTag in axisRanges:
1446
+ axisRange = axisRanges[axisTag]
1447
+ if coord < axisRange.minimum or coord > axisRange.maximum:
1448
+ return False
1449
+ return True
1450
+
1451
+
1452
+ def instantiateFvar(varfont, axisLimits):
1453
+ # 'axisLimits' dict must contain user-space (non-normalized) coordinates
1454
+
1455
+ location = axisLimits.pinnedLocation()
1456
+
1457
+ fvar = varfont["fvar"]
1458
+
1459
+ # drop table if we instantiate all the axes
1460
+ if set(location).issuperset(axis.axisTag for axis in fvar.axes):
1461
+ log.info("Dropping fvar table")
1462
+ del varfont["fvar"]
1463
+ return
1464
+
1465
+ log.info("Instantiating fvar table")
1466
+
1467
+ axes = []
1468
+ for axis in fvar.axes:
1469
+ axisTag = axis.axisTag
1470
+ if axisTag in location:
1471
+ continue
1472
+ if axisTag in axisLimits:
1473
+ triple = axisLimits[axisTag]
1474
+ if triple.default is None:
1475
+ triple = (triple.minimum, axis.defaultValue, triple.maximum)
1476
+ axis.minValue, axis.defaultValue, axis.maxValue = triple
1477
+ axes.append(axis)
1478
+ fvar.axes = axes
1479
+
1480
+ # only keep NamedInstances whose coordinates == pinned axis location
1481
+ instances = []
1482
+ for instance in fvar.instances:
1483
+ if any(instance.coordinates[axis] != value for axis, value in location.items()):
1484
+ continue
1485
+ for axisTag in location:
1486
+ del instance.coordinates[axisTag]
1487
+ if not isInstanceWithinAxisRanges(instance.coordinates, axisLimits):
1488
+ continue
1489
+ instances.append(instance)
1490
+ fvar.instances = instances
1491
+
1492
+
1493
+ def instantiateSTAT(varfont, axisLimits):
1494
+ # 'axisLimits' dict must contain user-space (non-normalized) coordinates
1495
+
1496
+ stat = varfont["STAT"].table
1497
+ if not stat.DesignAxisRecord or not (
1498
+ stat.AxisValueArray and stat.AxisValueArray.AxisValue
1499
+ ):
1500
+ return # STAT table empty, nothing to do
1501
+
1502
+ log.info("Instantiating STAT table")
1503
+ newAxisValueTables = axisValuesFromAxisLimits(stat, axisLimits)
1504
+ stat.AxisValueCount = len(newAxisValueTables)
1505
+ if stat.AxisValueCount:
1506
+ stat.AxisValueArray.AxisValue = newAxisValueTables
1507
+ else:
1508
+ stat.AxisValueArray = None
1509
+
1510
+
1511
+ def axisValuesFromAxisLimits(stat, axisLimits):
1512
+ def isAxisValueOutsideLimits(axisTag, axisValue):
1513
+ if axisTag in axisLimits:
1514
+ triple = axisLimits[axisTag]
1515
+ if axisValue < triple.minimum or axisValue > triple.maximum:
1516
+ return True
1517
+ return False
1518
+
1519
+ # only keep AxisValues whose axis is not pinned nor restricted, or is pinned at the
1520
+ # exact (nominal) value, or is restricted but the value is within the new range
1521
+ designAxes = stat.DesignAxisRecord.Axis
1522
+ newAxisValueTables = []
1523
+ for axisValueTable in stat.AxisValueArray.AxisValue:
1524
+ axisValueFormat = axisValueTable.Format
1525
+ if axisValueFormat in (1, 2, 3):
1526
+ axisTag = designAxes[axisValueTable.AxisIndex].AxisTag
1527
+ if axisValueFormat == 2:
1528
+ axisValue = axisValueTable.NominalValue
1529
+ else:
1530
+ axisValue = axisValueTable.Value
1531
+ if isAxisValueOutsideLimits(axisTag, axisValue):
1532
+ continue
1533
+ elif axisValueFormat == 4:
1534
+ # drop 'non-analytic' AxisValue if _any_ AxisValueRecord doesn't match
1535
+ # the pinned location or is outside range
1536
+ dropAxisValueTable = False
1537
+ for rec in axisValueTable.AxisValueRecord:
1538
+ axisTag = designAxes[rec.AxisIndex].AxisTag
1539
+ axisValue = rec.Value
1540
+ if isAxisValueOutsideLimits(axisTag, axisValue):
1541
+ dropAxisValueTable = True
1542
+ break
1543
+ if dropAxisValueTable:
1544
+ continue
1545
+ else:
1546
+ log.warning("Unknown AxisValue table format (%s); ignored", axisValueFormat)
1547
+ newAxisValueTables.append(axisValueTable)
1548
+ return newAxisValueTables
1549
+
1550
+
1551
+ def setMacOverlapFlags(glyfTable):
1552
+ flagOverlapCompound = _g_l_y_f.OVERLAP_COMPOUND
1553
+ flagOverlapSimple = _g_l_y_f.flagOverlapSimple
1554
+ for glyphName in glyfTable.keys():
1555
+ glyph = glyfTable[glyphName]
1556
+ # Set OVERLAP_COMPOUND bit for compound glyphs
1557
+ if glyph.isComposite():
1558
+ glyph.components[0].flags |= flagOverlapCompound
1559
+ # Set OVERLAP_SIMPLE bit for simple glyphs
1560
+ elif glyph.numberOfContours > 0:
1561
+ glyph.flags[0] |= flagOverlapSimple
1562
+
1563
+
1564
+ def normalize(value, triple, avarMapping):
1565
+ value = normalizeValue(value, triple)
1566
+ if avarMapping:
1567
+ value = piecewiseLinearMap(value, avarMapping)
1568
+ # Quantize to F2Dot14, to avoid surprise interpolations.
1569
+ return floatToFixedToFloat(value, 14)
1570
+
1571
+
1572
+ def sanityCheckVariableTables(varfont):
1573
+ if "fvar" not in varfont:
1574
+ raise ValueError("Missing required table fvar")
1575
+ if "gvar" in varfont:
1576
+ if "glyf" not in varfont:
1577
+ raise ValueError("Can't have gvar without glyf")
1578
+
1579
+
1580
+ def instantiateVariableFont(
1581
+ varfont,
1582
+ axisLimits,
1583
+ inplace=False,
1584
+ optimize=True,
1585
+ overlap=OverlapMode.KEEP_AND_SET_FLAGS,
1586
+ updateFontNames=False,
1587
+ *,
1588
+ downgradeCFF2=False,
1589
+ ):
1590
+ """Instantiate variable font, either fully or partially.
1591
+
1592
+ Depending on whether the `axisLimits` dictionary references all or some of the
1593
+ input varfont's axes, the output font will either be a full instance (static
1594
+ font) or a variable font with possibly less variation data.
1595
+
1596
+ Args:
1597
+ varfont: a TTFont instance, which must contain at least an 'fvar' table.
1598
+ axisLimits: a dict keyed by axis tags (str) containing the coordinates (float)
1599
+ along one or more axes where the desired instance will be located.
1600
+ If the value is `None`, the default coordinate as per 'fvar' table for
1601
+ that axis is used.
1602
+ The limit values can also be (min, max) tuples for restricting an
1603
+ axis's variation range. The default axis value must be included in
1604
+ the new range.
1605
+ inplace (bool): whether to modify input TTFont object in-place instead of
1606
+ returning a distinct object.
1607
+ optimize (bool): if False, do not perform IUP-delta optimization on the
1608
+ remaining 'gvar' table's deltas. Possibly faster, and might work around
1609
+ rendering issues in some buggy environments, at the cost of a slightly
1610
+ larger file size.
1611
+ overlap (OverlapMode): variable fonts usually contain overlapping contours, and
1612
+ some font rendering engines on Apple platforms require that the
1613
+ `OVERLAP_SIMPLE` and `OVERLAP_COMPOUND` flags in the 'glyf' table be set to
1614
+ force rendering using a non-zero fill rule. Thus we always set these flags
1615
+ on all glyphs to maximise cross-compatibility of the generated instance.
1616
+ You can disable this by passing OverlapMode.KEEP_AND_DONT_SET_FLAGS.
1617
+ If you want to remove the overlaps altogether and merge overlapping
1618
+ contours and components, you can pass OverlapMode.REMOVE (or
1619
+ REMOVE_AND_IGNORE_ERRORS to not hard-fail on tricky glyphs). Note that this
1620
+ requires the skia-pathops package (available to pip install).
1621
+ The overlap parameter only has effect when generating full static instances.
1622
+ updateFontNames (bool): if True, update the instantiated font's name table using
1623
+ the Axis Value Tables from the STAT table. The name table and the style bits
1624
+ in the head and OS/2 table will be updated so they conform to the R/I/B/BI
1625
+ model. If the STAT table is missing or an Axis Value table is missing for
1626
+ a given axis coordinate, a ValueError will be raised.
1627
+ downgradeCFF2 (bool): if True, downgrade the CFF2 table to CFF table when possible
1628
+ ie. full instancing of all axes. This is useful for compatibility with older
1629
+ software that does not support CFF2. Defaults to False. Note that this
1630
+ operation also removes overlaps within glyph shapes, as CFF does not support
1631
+ overlaps but CFF2 does.
1632
+ """
1633
+ # 'overlap' used to be bool and is now enum; for backward compat keep accepting bool
1634
+ overlap = OverlapMode(int(overlap))
1635
+
1636
+ sanityCheckVariableTables(varfont)
1637
+
1638
+ axisLimits = AxisLimits(axisLimits).limitAxesAndPopulateDefaults(varfont)
1639
+
1640
+ log.info("Restricted limits: %s", axisLimits)
1641
+
1642
+ normalizedLimits = axisLimits.normalize(varfont)
1643
+
1644
+ log.info("Normalized limits: %s", normalizedLimits)
1645
+
1646
+ if not inplace:
1647
+ varfont = deepcopy(varfont)
1648
+
1649
+ if "DSIG" in varfont:
1650
+ del varfont["DSIG"]
1651
+
1652
+ if updateFontNames:
1653
+ log.info("Updating name table")
1654
+ names.updateNameTable(varfont, axisLimits)
1655
+
1656
+ if "VARC" in varfont:
1657
+ instantiateVARC(varfont, normalizedLimits)
1658
+
1659
+ if "CFF2" in varfont:
1660
+ instantiateCFF2(varfont, normalizedLimits, downgrade=downgradeCFF2)
1661
+
1662
+ if "gvar" in varfont:
1663
+ instantiateGvar(varfont, normalizedLimits, optimize=optimize)
1664
+
1665
+ if "cvar" in varfont:
1666
+ instantiateCvar(varfont, normalizedLimits)
1667
+
1668
+ if "MVAR" in varfont:
1669
+ instantiateMVAR(varfont, normalizedLimits)
1670
+
1671
+ if "HVAR" in varfont:
1672
+ instantiateHVAR(varfont, normalizedLimits)
1673
+
1674
+ if "VVAR" in varfont:
1675
+ instantiateVVAR(varfont, normalizedLimits)
1676
+
1677
+ instantiateOTL(varfont, normalizedLimits)
1678
+
1679
+ instantiateFeatureVariations(varfont, normalizedLimits)
1680
+
1681
+ if "avar" in varfont:
1682
+ instantiateAvar(varfont, axisLimits)
1683
+
1684
+ with names.pruningUnusedNames(varfont):
1685
+ if "STAT" in varfont:
1686
+ instantiateSTAT(varfont, axisLimits)
1687
+
1688
+ instantiateFvar(varfont, axisLimits)
1689
+
1690
+ if "fvar" not in varfont:
1691
+ if "glyf" in varfont:
1692
+ if overlap == OverlapMode.KEEP_AND_SET_FLAGS:
1693
+ setMacOverlapFlags(varfont["glyf"])
1694
+ elif overlap in (OverlapMode.REMOVE, OverlapMode.REMOVE_AND_IGNORE_ERRORS):
1695
+ from fontTools.ttLib.removeOverlaps import removeOverlaps
1696
+
1697
+ log.info("Removing overlaps from glyf table")
1698
+ removeOverlaps(
1699
+ varfont,
1700
+ ignoreErrors=(overlap == OverlapMode.REMOVE_AND_IGNORE_ERRORS),
1701
+ )
1702
+
1703
+ if "OS/2" in varfont:
1704
+ varfont["OS/2"].recalcAvgCharWidth(varfont)
1705
+
1706
+ varLib.set_default_weight_width_slant(
1707
+ varfont, location=axisLimits.defaultLocation()
1708
+ )
1709
+
1710
+ if updateFontNames:
1711
+ # Set Regular/Italic/Bold/Bold Italic bits as appropriate, after the
1712
+ # name table has been updated.
1713
+ setRibbiBits(varfont)
1714
+
1715
+ return varfont
1716
+
1717
+
1718
+ def setRibbiBits(font):
1719
+ """Set the `head.macStyle` and `OS/2.fsSelection` style bits
1720
+ appropriately."""
1721
+
1722
+ english_ribbi_style = font["name"].getName(names.NameID.SUBFAMILY_NAME, 3, 1, 0x409)
1723
+ if english_ribbi_style is None:
1724
+ return
1725
+
1726
+ styleMapStyleName = english_ribbi_style.toStr().lower()
1727
+ if styleMapStyleName not in {"regular", "bold", "italic", "bold italic"}:
1728
+ return
1729
+
1730
+ if styleMapStyleName == "bold":
1731
+ font["head"].macStyle = 0b01
1732
+ elif styleMapStyleName == "bold italic":
1733
+ font["head"].macStyle = 0b11
1734
+ elif styleMapStyleName == "italic":
1735
+ font["head"].macStyle = 0b10
1736
+
1737
+ selection = font["OS/2"].fsSelection
1738
+ # First clear...
1739
+ selection &= ~(1 << 0)
1740
+ selection &= ~(1 << 5)
1741
+ selection &= ~(1 << 6)
1742
+ # ...then re-set the bits.
1743
+ if styleMapStyleName == "regular":
1744
+ selection |= 1 << 6
1745
+ elif styleMapStyleName == "bold":
1746
+ selection |= 1 << 5
1747
+ elif styleMapStyleName == "italic":
1748
+ selection |= 1 << 0
1749
+ elif styleMapStyleName == "bold italic":
1750
+ selection |= 1 << 0
1751
+ selection |= 1 << 5
1752
+ font["OS/2"].fsSelection = selection
1753
+
1754
+
1755
+ def parseLimits(limits: Iterable[str]) -> Dict[str, Optional[AxisTriple]]:
1756
+ result = {}
1757
+ for limitString in limits:
1758
+ match = re.match(
1759
+ r"^(\w{1,4})=(?:(drop)|(?:([^:]*)(?:[:]([^:]*))?(?:[:]([^:]*))?))$",
1760
+ limitString,
1761
+ )
1762
+ if not match:
1763
+ raise ValueError("invalid location format: %r" % limitString)
1764
+ tag = match.group(1).ljust(4)
1765
+
1766
+ if match.group(2): # 'drop'
1767
+ result[tag] = None
1768
+ continue
1769
+
1770
+ triple = match.group(3, 4, 5)
1771
+
1772
+ if triple[1] is None: # "value" syntax
1773
+ triple = (triple[0], triple[0], triple[0])
1774
+ elif triple[2] is None: # "min:max" syntax
1775
+ triple = (triple[0], None, triple[1])
1776
+
1777
+ triple = tuple(float(v) if v else None for v in triple)
1778
+
1779
+ result[tag] = AxisTriple(*triple)
1780
+
1781
+ return result
1782
+
1783
+
1784
+ def parseArgs(args):
1785
+ """Parse argv.
1786
+
1787
+ Returns:
1788
+ 3-tuple (infile, axisLimits, options)
1789
+ axisLimits is either a Dict[str, Optional[float]], for pinning variation axes
1790
+ to specific coordinates along those axes (with `None` as a placeholder for an
1791
+ axis' default value); or a Dict[str, Tuple(float, float)], meaning limit this
1792
+ axis to min/max range.
1793
+ Axes locations are in user-space coordinates, as defined in the "fvar" table.
1794
+ """
1795
+ from fontTools import configLogger
1796
+ import argparse
1797
+
1798
+ parser = argparse.ArgumentParser(
1799
+ "fonttools varLib.instancer",
1800
+ description="Partially instantiate a variable font",
1801
+ )
1802
+ parser.add_argument("input", metavar="INPUT.ttf", help="Input variable TTF file.")
1803
+ parser.add_argument(
1804
+ "locargs",
1805
+ metavar="AXIS=LOC",
1806
+ nargs="*",
1807
+ help="List of space separated locations. A location consists of "
1808
+ "the tag of a variation axis, followed by '=' and the literal, "
1809
+ "string 'drop', or colon-separated list of one to three values, "
1810
+ "each of which is the empty string, or a number. "
1811
+ "E.g.: wdth=100 or wght=75.0:125.0 or wght=100:400:700 or wght=:500: "
1812
+ "or wght=drop",
1813
+ )
1814
+ parser.add_argument(
1815
+ "-o",
1816
+ "--output",
1817
+ metavar="OUTPUT.ttf",
1818
+ default=None,
1819
+ help="Output instance TTF file (default: INPUT-instance.ttf).",
1820
+ )
1821
+ parser.add_argument(
1822
+ "--no-optimize",
1823
+ dest="optimize",
1824
+ action="store_false",
1825
+ help="Don't perform IUP optimization on the remaining gvar TupleVariations",
1826
+ )
1827
+ parser.add_argument(
1828
+ "--no-overlap-flag",
1829
+ dest="overlap",
1830
+ action="store_false",
1831
+ help="Don't set OVERLAP_SIMPLE/OVERLAP_COMPOUND glyf flags (only applicable "
1832
+ "when generating a full instance)",
1833
+ )
1834
+ parser.add_argument(
1835
+ "--remove-overlaps",
1836
+ dest="remove_overlaps",
1837
+ action="store_true",
1838
+ help="Merge overlapping contours and components (only applicable "
1839
+ "when generating a full instance). Requires skia-pathops",
1840
+ )
1841
+ parser.add_argument(
1842
+ "--ignore-overlap-errors",
1843
+ dest="ignore_overlap_errors",
1844
+ action="store_true",
1845
+ help="Don't crash if the remove-overlaps operation fails for some glyphs.",
1846
+ )
1847
+ parser.add_argument(
1848
+ "--update-name-table",
1849
+ action="store_true",
1850
+ help="Update the instantiated font's `name` table. Input font must have "
1851
+ "a STAT table with Axis Value Tables",
1852
+ )
1853
+ parser.add_argument(
1854
+ "--downgrade-cff2",
1855
+ action="store_true",
1856
+ help="If all axes are pinned, downgrade CFF2 to CFF table format",
1857
+ )
1858
+ parser.add_argument(
1859
+ "--no-recalc-timestamp",
1860
+ dest="recalc_timestamp",
1861
+ action="store_false",
1862
+ help="Don't set the output font's timestamp to the current time.",
1863
+ )
1864
+ parser.add_argument(
1865
+ "--no-recalc-bounds",
1866
+ dest="recalc_bounds",
1867
+ action="store_false",
1868
+ help="Don't recalculate font bounding boxes",
1869
+ )
1870
+ loggingGroup = parser.add_mutually_exclusive_group(required=False)
1871
+ loggingGroup.add_argument(
1872
+ "-v", "--verbose", action="store_true", help="Run more verbosely."
1873
+ )
1874
+ loggingGroup.add_argument(
1875
+ "-q", "--quiet", action="store_true", help="Turn verbosity off."
1876
+ )
1877
+ options = parser.parse_args(args)
1878
+
1879
+ if options.remove_overlaps:
1880
+ if options.ignore_overlap_errors:
1881
+ options.overlap = OverlapMode.REMOVE_AND_IGNORE_ERRORS
1882
+ else:
1883
+ options.overlap = OverlapMode.REMOVE
1884
+ else:
1885
+ options.overlap = OverlapMode(int(options.overlap))
1886
+
1887
+ infile = options.input
1888
+ if not os.path.isfile(infile):
1889
+ parser.error("No such file '{}'".format(infile))
1890
+
1891
+ configLogger(
1892
+ level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
1893
+ )
1894
+
1895
+ try:
1896
+ axisLimits = parseLimits(options.locargs)
1897
+ except ValueError as e:
1898
+ parser.error(str(e))
1899
+
1900
+ if len(axisLimits) != len(options.locargs):
1901
+ parser.error("Specified multiple limits for the same axis")
1902
+
1903
+ return (infile, axisLimits, options)
1904
+
1905
+
1906
+ def main(args=None):
1907
+ """Partially instantiate a variable font"""
1908
+ infile, axisLimits, options = parseArgs(args)
1909
+ log.info("Restricting axes: %s", axisLimits)
1910
+
1911
+ log.info("Loading variable font")
1912
+ varfont = TTFont(
1913
+ infile,
1914
+ recalcTimestamp=options.recalc_timestamp,
1915
+ recalcBBoxes=options.recalc_bounds,
1916
+ )
1917
+
1918
+ isFullInstance = {
1919
+ axisTag
1920
+ for axisTag, limit in axisLimits.items()
1921
+ if limit is None or limit[0] == limit[2]
1922
+ }.issuperset(axis.axisTag for axis in varfont["fvar"].axes)
1923
+
1924
+ instantiateVariableFont(
1925
+ varfont,
1926
+ axisLimits,
1927
+ inplace=True,
1928
+ optimize=options.optimize,
1929
+ overlap=options.overlap,
1930
+ updateFontNames=options.update_name_table,
1931
+ downgradeCFF2=options.downgrade_cff2,
1932
+ )
1933
+
1934
+ suffix = "-instance" if isFullInstance else "-partial"
1935
+ outfile = (
1936
+ makeOutputFileName(infile, overWrite=True, suffix=suffix)
1937
+ if not options.output
1938
+ else options.output
1939
+ )
1940
+
1941
+ log.info(
1942
+ "Saving %s font %s",
1943
+ "instance" if isFullInstance else "partial variable",
1944
+ outfile,
1945
+ )
1946
+ varfont.save(outfile)