fonttools 4.55.6__cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

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

Potentially problematic release.


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

Files changed (329) 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 +3659 -0
  8. fontTools/cffLib/specializer.py +924 -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 +75 -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 +14829 -0
  23. fontTools/cu2qu/cu2qu.cpython-39-x86_64-linux-gnu.so +0 -0
  24. fontTools/cu2qu/cu2qu.py +531 -0
  25. fontTools/cu2qu/errors.py +77 -0
  26. fontTools/cu2qu/ufo.py +349 -0
  27. fontTools/designspaceLib/__init__.py +3338 -0
  28. fontTools/designspaceLib/__main__.py +6 -0
  29. fontTools/designspaceLib/split.py +475 -0
  30. fontTools/designspaceLib/statNames.py +253 -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 +2134 -0
  39. fontTools/feaLib/builder.py +1747 -0
  40. fontTools/feaLib/error.py +22 -0
  41. fontTools/feaLib/lexer.c +17986 -0
  42. fontTools/feaLib/lexer.cpython-39-x86_64-linux-gnu.so +0 -0
  43. fontTools/feaLib/lexer.py +287 -0
  44. fontTools/feaLib/location.py +12 -0
  45. fontTools/feaLib/lookupDebugInfo.py +12 -0
  46. fontTools/feaLib/parser.py +2359 -0
  47. fontTools/feaLib/variableScalar.py +113 -0
  48. fontTools/fontBuilder.py +1008 -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 +141 -0
  54. fontTools/merge/layout.py +526 -0
  55. fontTools/merge/options.py +85 -0
  56. fontTools/merge/tables.py +341 -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 +41831 -0
  62. fontTools/misc/bezierTools.cpython-39-x86_64-linux-gnu.so +0 -0
  63. fontTools/misc/bezierTools.py +1497 -0
  64. fontTools/misc/classifyTools.py +170 -0
  65. fontTools/misc/cliTools.py +53 -0
  66. fontTools/misc/configTools.py +349 -0
  67. fontTools/misc/cython.py +27 -0
  68. fontTools/misc/dictTools.py +83 -0
  69. fontTools/misc/eexec.py +119 -0
  70. fontTools/misc/encodingTools.py +72 -0
  71. fontTools/misc/etree.py +479 -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 +244 -0
  89. fontTools/misc/testTools.py +229 -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 +1402 -0
  99. fontTools/mtiLib/__main__.py +5 -0
  100. fontTools/otlLib/__init__.py +1 -0
  101. fontTools/otlLib/builder.py +3221 -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 +453 -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 +13448 -0
  119. fontTools/pens/momentsPen.cpython-39-x86_64-linux-gnu.so +0 -0
  120. fontTools/pens/momentsPen.py +879 -0
  121. fontTools/pens/perimeterPen.py +69 -0
  122. fontTools/pens/pointInsidePen.py +192 -0
  123. fontTools/pens/pointPen.py +600 -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 +68 -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 +16269 -0
  143. fontTools/qu2cu/qu2cu.cpython-39-x86_64-linux-gnu.so +0 -0
  144. fontTools/qu2cu/qu2cu.py +405 -0
  145. fontTools/subset/__init__.py +3838 -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 +26 -0
  158. fontTools/ttLib/__main__.py +109 -0
  159. fontTools/ttLib/macUtils.py +54 -0
  160. fontTools/ttLib/removeOverlaps.py +393 -0
  161. fontTools/ttLib/reorderGlyphs.py +284 -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 +17 -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__l_a_t.py +235 -0
  186. fontTools/ttLib/tables/G__l_o_c.py +85 -0
  187. fontTools/ttLib/tables/H_V_A_R_.py +13 -0
  188. fontTools/ttLib/tables/J_S_T_F_.py +13 -0
  189. fontTools/ttLib/tables/L_T_S_H_.py +58 -0
  190. fontTools/ttLib/tables/M_A_T_H_.py +13 -0
  191. fontTools/ttLib/tables/M_E_T_A_.py +352 -0
  192. fontTools/ttLib/tables/M_V_A_R_.py +13 -0
  193. fontTools/ttLib/tables/O_S_2f_2.py +752 -0
  194. fontTools/ttLib/tables/S_I_N_G_.py +99 -0
  195. fontTools/ttLib/tables/S_T_A_T_.py +15 -0
  196. fontTools/ttLib/tables/S_V_G_.py +223 -0
  197. fontTools/ttLib/tables/S__i_l_f.py +1040 -0
  198. fontTools/ttLib/tables/S__i_l_l.py +92 -0
  199. fontTools/ttLib/tables/T_S_I_B_.py +13 -0
  200. fontTools/ttLib/tables/T_S_I_C_.py +14 -0
  201. fontTools/ttLib/tables/T_S_I_D_.py +13 -0
  202. fontTools/ttLib/tables/T_S_I_J_.py +13 -0
  203. fontTools/ttLib/tables/T_S_I_P_.py +13 -0
  204. fontTools/ttLib/tables/T_S_I_S_.py +13 -0
  205. fontTools/ttLib/tables/T_S_I_V_.py +26 -0
  206. fontTools/ttLib/tables/T_S_I__0.py +59 -0
  207. fontTools/ttLib/tables/T_S_I__1.py +166 -0
  208. fontTools/ttLib/tables/T_S_I__2.py +17 -0
  209. fontTools/ttLib/tables/T_S_I__3.py +22 -0
  210. fontTools/ttLib/tables/T_S_I__5.py +49 -0
  211. fontTools/ttLib/tables/T_T_F_A_.py +14 -0
  212. fontTools/ttLib/tables/TupleVariation.py +884 -0
  213. fontTools/ttLib/tables/V_A_R_C_.py +12 -0
  214. fontTools/ttLib/tables/V_D_M_X_.py +249 -0
  215. fontTools/ttLib/tables/V_O_R_G_.py +165 -0
  216. fontTools/ttLib/tables/V_V_A_R_.py +13 -0
  217. fontTools/ttLib/tables/__init__.py +97 -0
  218. fontTools/ttLib/tables/_a_n_k_r.py +15 -0
  219. fontTools/ttLib/tables/_a_v_a_r.py +191 -0
  220. fontTools/ttLib/tables/_b_s_l_n.py +15 -0
  221. fontTools/ttLib/tables/_c_i_d_g.py +24 -0
  222. fontTools/ttLib/tables/_c_m_a_p.py +1578 -0
  223. fontTools/ttLib/tables/_c_v_a_r.py +94 -0
  224. fontTools/ttLib/tables/_c_v_t.py +55 -0
  225. fontTools/ttLib/tables/_f_e_a_t.py +15 -0
  226. fontTools/ttLib/tables/_f_p_g_m.py +60 -0
  227. fontTools/ttLib/tables/_f_v_a_r.py +261 -0
  228. fontTools/ttLib/tables/_g_a_s_p.py +63 -0
  229. fontTools/ttLib/tables/_g_c_i_d.py +13 -0
  230. fontTools/ttLib/tables/_g_l_y_f.py +2311 -0
  231. fontTools/ttLib/tables/_g_v_a_r.py +292 -0
  232. fontTools/ttLib/tables/_h_d_m_x.py +127 -0
  233. fontTools/ttLib/tables/_h_e_a_d.py +130 -0
  234. fontTools/ttLib/tables/_h_h_e_a.py +147 -0
  235. fontTools/ttLib/tables/_h_m_t_x.py +160 -0
  236. fontTools/ttLib/tables/_k_e_r_n.py +289 -0
  237. fontTools/ttLib/tables/_l_c_a_r.py +13 -0
  238. fontTools/ttLib/tables/_l_o_c_a.py +70 -0
  239. fontTools/ttLib/tables/_l_t_a_g.py +72 -0
  240. fontTools/ttLib/tables/_m_a_x_p.py +147 -0
  241. fontTools/ttLib/tables/_m_e_t_a.py +112 -0
  242. fontTools/ttLib/tables/_m_o_r_t.py +14 -0
  243. fontTools/ttLib/tables/_m_o_r_x.py +15 -0
  244. fontTools/ttLib/tables/_n_a_m_e.py +1237 -0
  245. fontTools/ttLib/tables/_o_p_b_d.py +14 -0
  246. fontTools/ttLib/tables/_p_o_s_t.py +317 -0
  247. fontTools/ttLib/tables/_p_r_e_p.py +16 -0
  248. fontTools/ttLib/tables/_p_r_o_p.py +12 -0
  249. fontTools/ttLib/tables/_s_b_i_x.py +129 -0
  250. fontTools/ttLib/tables/_t_r_a_k.py +332 -0
  251. fontTools/ttLib/tables/_v_h_e_a.py +139 -0
  252. fontTools/ttLib/tables/_v_m_t_x.py +19 -0
  253. fontTools/ttLib/tables/asciiTable.py +20 -0
  254. fontTools/ttLib/tables/grUtils.py +92 -0
  255. fontTools/ttLib/tables/otBase.py +1465 -0
  256. fontTools/ttLib/tables/otConverters.py +2065 -0
  257. fontTools/ttLib/tables/otData.py +6400 -0
  258. fontTools/ttLib/tables/otTables.py +2700 -0
  259. fontTools/ttLib/tables/otTraverse.py +162 -0
  260. fontTools/ttLib/tables/sbixGlyph.py +149 -0
  261. fontTools/ttLib/tables/sbixStrike.py +177 -0
  262. fontTools/ttLib/tables/table_API_readme.txt +91 -0
  263. fontTools/ttLib/tables/ttProgram.py +594 -0
  264. fontTools/ttLib/ttCollection.py +125 -0
  265. fontTools/ttLib/ttFont.py +1155 -0
  266. fontTools/ttLib/ttGlyphSet.py +500 -0
  267. fontTools/ttLib/ttVisitor.py +32 -0
  268. fontTools/ttLib/woff2.py +1683 -0
  269. fontTools/ttx.py +467 -0
  270. fontTools/ufoLib/__init__.py +2477 -0
  271. fontTools/ufoLib/converters.py +334 -0
  272. fontTools/ufoLib/errors.py +22 -0
  273. fontTools/ufoLib/etree.py +6 -0
  274. fontTools/ufoLib/filenames.py +291 -0
  275. fontTools/ufoLib/glifLib.py +2022 -0
  276. fontTools/ufoLib/kerning.py +91 -0
  277. fontTools/ufoLib/plistlib.py +47 -0
  278. fontTools/ufoLib/pointPen.py +6 -0
  279. fontTools/ufoLib/utils.py +76 -0
  280. fontTools/ufoLib/validators.py +1186 -0
  281. fontTools/unicode.py +50 -0
  282. fontTools/unicodedata/Blocks.py +802 -0
  283. fontTools/unicodedata/OTTags.py +50 -0
  284. fontTools/unicodedata/ScriptExtensions.py +806 -0
  285. fontTools/unicodedata/Scripts.py +3618 -0
  286. fontTools/unicodedata/__init__.py +298 -0
  287. fontTools/varLib/__init__.py +1511 -0
  288. fontTools/varLib/__main__.py +6 -0
  289. fontTools/varLib/avar.py +260 -0
  290. fontTools/varLib/avarPlanner.py +1004 -0
  291. fontTools/varLib/builder.py +215 -0
  292. fontTools/varLib/cff.py +631 -0
  293. fontTools/varLib/errors.py +219 -0
  294. fontTools/varLib/featureVars.py +689 -0
  295. fontTools/varLib/instancer/__init__.py +1937 -0
  296. fontTools/varLib/instancer/__main__.py +5 -0
  297. fontTools/varLib/instancer/featureVars.py +190 -0
  298. fontTools/varLib/instancer/names.py +388 -0
  299. fontTools/varLib/instancer/solver.py +309 -0
  300. fontTools/varLib/interpolatable.py +1209 -0
  301. fontTools/varLib/interpolatableHelpers.py +396 -0
  302. fontTools/varLib/interpolatablePlot.py +1269 -0
  303. fontTools/varLib/interpolatableTestContourOrder.py +82 -0
  304. fontTools/varLib/interpolatableTestStartingPoint.py +107 -0
  305. fontTools/varLib/interpolate_layout.py +124 -0
  306. fontTools/varLib/iup.c +19154 -0
  307. fontTools/varLib/iup.cpython-39-x86_64-linux-gnu.so +0 -0
  308. fontTools/varLib/iup.py +490 -0
  309. fontTools/varLib/merger.py +1717 -0
  310. fontTools/varLib/models.py +642 -0
  311. fontTools/varLib/multiVarStore.py +253 -0
  312. fontTools/varLib/mutator.py +518 -0
  313. fontTools/varLib/mvar.py +40 -0
  314. fontTools/varLib/plot.py +238 -0
  315. fontTools/varLib/stat.py +149 -0
  316. fontTools/varLib/varStore.py +767 -0
  317. fontTools/voltLib/__init__.py +5 -0
  318. fontTools/voltLib/ast.py +448 -0
  319. fontTools/voltLib/error.py +12 -0
  320. fontTools/voltLib/lexer.py +99 -0
  321. fontTools/voltLib/parser.py +656 -0
  322. fontTools/voltLib/voltToFea.py +730 -0
  323. fonttools-4.55.6.data/data/share/man/man1/ttx.1 +225 -0
  324. fonttools-4.55.6.dist-info/LICENSE +21 -0
  325. fonttools-4.55.6.dist-info/METADATA +3413 -0
  326. fonttools-4.55.6.dist-info/RECORD +329 -0
  327. fonttools-4.55.6.dist-info/WHEEL +6 -0
  328. fonttools-4.55.6.dist-info/entry_points.txt +5 -0
  329. fonttools-4.55.6.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1937 @@
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
+ for cs in charStrings:
679
+ assert cs.private.vstore.otVarStore is varStore # Or in many places!!
680
+ commands = programToCommands(cs.program, getNumRegions=getNumRegions)
681
+ if generalize:
682
+ commands = generalizeCommands(commands)
683
+ if specialize:
684
+ commands = specializeCommands(commands, generalizeFirst=not generalize)
685
+ allCommands.append(commands)
686
+
687
+ def storeBlendsToVarStore(arg):
688
+ if not isinstance(arg, list):
689
+ return
690
+
691
+ if any(isinstance(subarg, list) for subarg in arg[:-1]):
692
+ raise NotImplementedError("Nested blend lists not supported (yet)")
693
+
694
+ count = arg[-1]
695
+ assert (len(arg) - 1) % count == 0
696
+ nRegions = (len(arg) - 1) // count - 1
697
+ assert nRegions == getNumRegions(vsindex)
698
+ for i in range(count, len(arg) - 1, nRegions):
699
+ deltas = arg[i : i + nRegions]
700
+ assert len(deltas) == nRegions
701
+ varData = varStore.VarData[vsindex]
702
+ varData.Item.append(deltas)
703
+ varData.ItemCount += 1
704
+
705
+ def fetchBlendsFromVarStore(arg):
706
+ if not isinstance(arg, list):
707
+ return [arg]
708
+
709
+ if any(isinstance(subarg, list) for subarg in arg[:-1]):
710
+ raise NotImplementedError("Nested blend lists not supported (yet)")
711
+
712
+ count = arg[-1]
713
+ assert (len(arg) - 1) % count == 0
714
+ numRegions = getNumRegions(vsindex)
715
+ newDefaults = []
716
+ newDeltas = []
717
+ for i in range(count):
718
+ defaultValue = arg[i]
719
+
720
+ major = vsindex
721
+ minor = varDataCursor[major]
722
+ varDataCursor[major] += 1
723
+
724
+ varIdx = (major << 16) + minor
725
+
726
+ defaultValue += round(defaultDeltas[varIdx])
727
+ newDefaults.append(defaultValue)
728
+
729
+ varData = varStore.VarData[major]
730
+ deltas = varData.Item[minor]
731
+ assert len(deltas) == numRegions
732
+ newDeltas.extend(deltas)
733
+
734
+ if not numRegions:
735
+ return newDefaults # No deltas, just return the defaults
736
+
737
+ return [newDefaults + newDeltas + [count]]
738
+
739
+ # Check VarData's are empty
740
+ for varData in varStore.VarData:
741
+ assert varData.Item == []
742
+ assert varData.ItemCount == 0
743
+
744
+ # Add charstring blend lists to VarStore so we can instantiate them
745
+ for commands in allCommands:
746
+ vsindex = 0
747
+ for command in commands:
748
+ if command[0] == "vsindex":
749
+ vsindex = command[1][0]
750
+ continue
751
+ for arg in command[1]:
752
+ storeBlendsToVarStore(arg)
753
+
754
+ # Add private blend lists to VarStore so we can instantiate values
755
+ vsindex = 0
756
+ for opcode, name, arg_type, default, converter in privateDictOperators2:
757
+ if arg_type not in ("number", "delta", "array"):
758
+ continue
759
+
760
+ vsindex = 0
761
+ for private in privateDicts:
762
+ if not hasattr(private, name):
763
+ continue
764
+ values = getattr(private, name)
765
+
766
+ if name == "vsindex":
767
+ vsindex = values[0]
768
+ continue
769
+
770
+ if arg_type == "number":
771
+ values = [values]
772
+
773
+ for value in values:
774
+ if not isinstance(value, list):
775
+ continue
776
+
777
+ assert len(value) % (getNumRegions(vsindex) + 1) == 0
778
+ count = len(value) // (getNumRegions(vsindex) + 1)
779
+ storeBlendsToVarStore(value + [count])
780
+
781
+ # Instantiate VarStore
782
+ defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
783
+
784
+ # Read back new charstring blends from the instantiated VarStore
785
+ varDataCursor = [0] * len(varStore.VarData)
786
+ for commands in allCommands:
787
+ vsindex = 0
788
+ for command in commands:
789
+ if command[0] == "vsindex":
790
+ vsindex = command[1][0]
791
+ continue
792
+ newArgs = []
793
+ for arg in command[1]:
794
+ newArgs.extend(fetchBlendsFromVarStore(arg))
795
+ command[1][:] = newArgs
796
+
797
+ # Read back new private blends from the instantiated VarStore
798
+ for opcode, name, arg_type, default, converter in privateDictOperators2:
799
+ if arg_type not in ("number", "delta", "array"):
800
+ continue
801
+
802
+ for private in privateDicts:
803
+ if not hasattr(private, name):
804
+ continue
805
+ values = getattr(private, name)
806
+ if arg_type == "number":
807
+ values = [values]
808
+
809
+ newValues = []
810
+ for value in values:
811
+ if not isinstance(value, list):
812
+ newValues.append(value)
813
+ continue
814
+
815
+ value.append(1)
816
+ value = fetchBlendsFromVarStore(value)
817
+ newValues.extend(v[:-1] if isinstance(v, list) else v for v in value)
818
+
819
+ if arg_type == "number":
820
+ newValues = newValues[0]
821
+
822
+ setattr(private, name, newValues)
823
+
824
+ # Empty out the VarStore
825
+ for i, varData in enumerate(varStore.VarData):
826
+ assert varDataCursor[i] == varData.ItemCount, (
827
+ varDataCursor[i],
828
+ varData.ItemCount,
829
+ )
830
+ varData.Item = []
831
+ varData.ItemCount = 0
832
+
833
+ # Remove vsindex commands that are no longer needed, collect those that are.
834
+ usedVsindex = set()
835
+ for commands in allCommands:
836
+ if any(isinstance(arg, list) for command in commands for arg in command[1]):
837
+ vsindex = 0
838
+ for command in commands:
839
+ if command[0] == "vsindex":
840
+ vsindex = command[1][0]
841
+ continue
842
+ if any(isinstance(arg, list) for arg in command[1]):
843
+ usedVsindex.add(vsindex)
844
+ else:
845
+ commands[:] = [command for command in commands if command[0] != "vsindex"]
846
+
847
+ # Remove unused VarData and update vsindex values
848
+ vsindexMapping = {v: i for i, v in enumerate(sorted(usedVsindex))}
849
+ varStore.VarData = [
850
+ varData for i, varData in enumerate(varStore.VarData) if i in usedVsindex
851
+ ]
852
+ varStore.VarDataCount = len(varStore.VarData)
853
+ for commands in allCommands:
854
+ for command in commands:
855
+ if command[0] == "vsindex":
856
+ command[1][0] = vsindexMapping[command[1][0]]
857
+
858
+ # Remove initial vsindex commands that are implied
859
+ for commands in allCommands:
860
+ if commands and commands[0] == ("vsindex", [0]):
861
+ commands.pop(0)
862
+
863
+ # Ship the charstrings!
864
+ for cs, commands in zip(charStrings, allCommands):
865
+ cs.program = commandsToProgram(commands)
866
+
867
+ # Remove empty VarStore
868
+ if not varStore.VarData:
869
+ if "VarStore" in topDict.rawDict:
870
+ del topDict.rawDict["VarStore"]
871
+ del topDict.VarStore
872
+ del topDict.CharStrings.varStore
873
+ for private in privateDicts:
874
+ del private.vstore
875
+
876
+ if downgrade:
877
+ from fontTools.cffLib.CFF2ToCFF import convertCFF2ToCFF
878
+
879
+ convertCFF2ToCFF(varfont)
880
+
881
+
882
+ def _instantiateGvarGlyph(
883
+ glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=True
884
+ ):
885
+ coordinates, ctrl = glyf._getCoordinatesAndControls(glyphname, hMetrics, vMetrics)
886
+ endPts = ctrl.endPts
887
+
888
+ # Not every glyph may have variations
889
+ tupleVarStore = gvar.variations.get(glyphname)
890
+
891
+ if tupleVarStore:
892
+ defaultDeltas = instantiateTupleVariationStore(
893
+ tupleVarStore, axisLimits, coordinates, endPts
894
+ )
895
+
896
+ if defaultDeltas:
897
+ coordinates += _g_l_y_f.GlyphCoordinates(defaultDeltas)
898
+
899
+ # _setCoordinates also sets the hmtx/vmtx advance widths and sidebearings from
900
+ # the four phantom points and glyph bounding boxes.
901
+ # We call it unconditionally even if a glyph has no variations or no deltas are
902
+ # applied at this location, in case the glyph's xMin and in turn its sidebearing
903
+ # have changed. E.g. a composite glyph has no deltas for the component's (x, y)
904
+ # offset nor for the 4 phantom points (e.g. it's monospaced). Thus its entry in
905
+ # gvar table is empty; however, the composite's base glyph may have deltas
906
+ # applied, hence the composite's bbox and left/top sidebearings may need updating
907
+ # in the instanced font.
908
+ glyf._setCoordinates(glyphname, coordinates, hMetrics, vMetrics)
909
+
910
+ if not tupleVarStore:
911
+ if glyphname in gvar.variations:
912
+ del gvar.variations[glyphname]
913
+ return
914
+
915
+ if optimize:
916
+ # IUP semantics depend on point equality, and so round prior to
917
+ # optimization to ensure that comparisons that happen now will be the
918
+ # same as those that happen at render time. This is especially needed
919
+ # when floating point deltas have been applied to the default position.
920
+ # See https://github.com/fonttools/fonttools/issues/3634
921
+ # Rounding must happen only after calculating glyf metrics above, to
922
+ # preserve backwards compatibility.
923
+ # See 0010a3cd9aa25f84a3a6250dafb119743d32aa40
924
+ coordinates.toInt()
925
+
926
+ isComposite = glyf[glyphname].isComposite()
927
+
928
+ for var in tupleVarStore:
929
+ var.optimize(coordinates, endPts, isComposite=isComposite)
930
+
931
+
932
+ def instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True):
933
+ """Remove?
934
+ https://github.com/fonttools/fonttools/pull/2266"""
935
+ gvar = varfont["gvar"]
936
+ glyf = varfont["glyf"]
937
+ hMetrics = varfont["hmtx"].metrics
938
+ vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
939
+ _instantiateGvarGlyph(
940
+ glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
941
+ )
942
+
943
+
944
+ def instantiateGvar(varfont, axisLimits, optimize=True):
945
+ log.info("Instantiating glyf/gvar tables")
946
+
947
+ gvar = varfont["gvar"]
948
+ glyf = varfont["glyf"]
949
+ hMetrics = varfont["hmtx"].metrics
950
+ vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
951
+ # Get list of glyph names sorted by component depth.
952
+ # If a composite glyph is processed before its base glyph, the bounds may
953
+ # be calculated incorrectly because deltas haven't been applied to the
954
+ # base glyph yet.
955
+ glyphnames = sorted(
956
+ glyf.glyphOrder,
957
+ key=lambda name: (
958
+ (
959
+ glyf[name].getCompositeMaxpValues(glyf).maxComponentDepth
960
+ if glyf[name].isComposite()
961
+ else 0
962
+ ),
963
+ name,
964
+ ),
965
+ )
966
+ for glyphname in glyphnames:
967
+ _instantiateGvarGlyph(
968
+ glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
969
+ )
970
+
971
+ if not gvar.variations:
972
+ del varfont["gvar"]
973
+
974
+
975
+ def setCvarDeltas(cvt, deltas):
976
+ for i, delta in enumerate(deltas):
977
+ if delta:
978
+ cvt[i] += otRound(delta)
979
+
980
+
981
+ def instantiateCvar(varfont, axisLimits):
982
+ log.info("Instantiating cvt/cvar tables")
983
+
984
+ cvar = varfont["cvar"]
985
+
986
+ defaultDeltas = instantiateTupleVariationStore(cvar.variations, axisLimits)
987
+
988
+ if defaultDeltas:
989
+ setCvarDeltas(varfont["cvt "], defaultDeltas)
990
+
991
+ if not cvar.variations:
992
+ del varfont["cvar"]
993
+
994
+
995
+ def setMvarDeltas(varfont, deltas):
996
+ mvar = varfont["MVAR"].table
997
+ records = mvar.ValueRecord
998
+ for rec in records:
999
+ mvarTag = rec.ValueTag
1000
+ if mvarTag not in MVAR_ENTRIES:
1001
+ continue
1002
+ tableTag, itemName = MVAR_ENTRIES[mvarTag]
1003
+ delta = deltas[rec.VarIdx]
1004
+ if delta != 0:
1005
+ setattr(
1006
+ varfont[tableTag],
1007
+ itemName,
1008
+ getattr(varfont[tableTag], itemName) + otRound(delta),
1009
+ )
1010
+
1011
+
1012
+ @contextmanager
1013
+ def verticalMetricsKeptInSync(varfont):
1014
+ """Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing.
1015
+
1016
+ When applying MVAR deltas to the OS/2 table, if the ascender, descender and
1017
+ line gap change but they were the same as the respective hhea metrics in the
1018
+ original font, this context manager ensures that hhea metrcs also get updated
1019
+ accordingly.
1020
+ The MVAR spec only has tags for the OS/2 metrics, but it is common in fonts
1021
+ to have the hhea metrics be equal to those for compat reasons.
1022
+
1023
+ https://learn.microsoft.com/en-us/typography/opentype/spec/mvar
1024
+ https://googlefonts.github.io/gf-guide/metrics.html#7-hhea-and-typo-metrics-should-be-equal
1025
+ https://github.com/fonttools/fonttools/issues/3297
1026
+ """
1027
+ current_os2_vmetrics = [
1028
+ getattr(varfont["OS/2"], attr)
1029
+ for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap")
1030
+ ]
1031
+ metrics_are_synced = current_os2_vmetrics == [
1032
+ getattr(varfont["hhea"], attr) for attr in ("ascender", "descender", "lineGap")
1033
+ ]
1034
+
1035
+ yield metrics_are_synced
1036
+
1037
+ if metrics_are_synced:
1038
+ new_os2_vmetrics = [
1039
+ getattr(varfont["OS/2"], attr)
1040
+ for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap")
1041
+ ]
1042
+ if current_os2_vmetrics != new_os2_vmetrics:
1043
+ for attr, value in zip(
1044
+ ("ascender", "descender", "lineGap"), new_os2_vmetrics
1045
+ ):
1046
+ setattr(varfont["hhea"], attr, value)
1047
+
1048
+
1049
+ def instantiateMVAR(varfont, axisLimits):
1050
+ log.info("Instantiating MVAR table")
1051
+
1052
+ mvar = varfont["MVAR"].table
1053
+ fvarAxes = varfont["fvar"].axes
1054
+ varStore = mvar.VarStore
1055
+ defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
1056
+
1057
+ with verticalMetricsKeptInSync(varfont):
1058
+ setMvarDeltas(varfont, defaultDeltas)
1059
+
1060
+ if varStore.VarRegionList.Region:
1061
+ varIndexMapping = varStore.optimize()
1062
+ for rec in mvar.ValueRecord:
1063
+ rec.VarIdx = varIndexMapping[rec.VarIdx]
1064
+ else:
1065
+ del varfont["MVAR"]
1066
+
1067
+
1068
+ def _remapVarIdxMap(table, attrName, varIndexMapping, glyphOrder):
1069
+ oldMapping = getattr(table, attrName).mapping
1070
+ newMapping = [varIndexMapping[oldMapping[glyphName]] for glyphName in glyphOrder]
1071
+ setattr(table, attrName, builder.buildVarIdxMap(newMapping, glyphOrder))
1072
+
1073
+
1074
+ # TODO(anthrotype) Add support for HVAR/VVAR in CFF2
1075
+ def _instantiateVHVAR(varfont, axisLimits, tableFields, *, round=round):
1076
+ location = axisLimits.pinnedLocation()
1077
+ tableTag = tableFields.tableTag
1078
+ fvarAxes = varfont["fvar"].axes
1079
+
1080
+ log.info("Instantiating %s table", tableTag)
1081
+ vhvar = varfont[tableTag].table
1082
+ varStore = vhvar.VarStore
1083
+
1084
+ if "glyf" in varfont:
1085
+ # Deltas from gvar table have already been applied to the hmtx/vmtx. For full
1086
+ # instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return
1087
+ if set(location).issuperset(axis.axisTag for axis in fvarAxes):
1088
+ log.info("Dropping %s table", tableTag)
1089
+ del varfont[tableTag]
1090
+ return
1091
+
1092
+ defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
1093
+
1094
+ if "glyf" not in varfont:
1095
+ # CFF2 fonts need hmtx/vmtx updated here. For glyf fonts, the instantiateGvar
1096
+ # function already updated the hmtx/vmtx from phantom points. Maybe remove
1097
+ # that and do it here for both CFF2 and glyf fonts?
1098
+ #
1099
+ # Specially, if a font has glyf but not gvar, the hmtx/vmtx will not have been
1100
+ # updated by instantiateGvar. Though one can call that a faulty font.
1101
+ metricsTag = "vmtx" if tableTag == "VVAR" else "hmtx"
1102
+ if metricsTag in varfont:
1103
+ advMapping = getattr(vhvar, tableFields.advMapping)
1104
+ metricsTable = varfont[metricsTag]
1105
+ metrics = metricsTable.metrics
1106
+ for glyphName, (advanceWidth, sb) in metrics.items():
1107
+ if advMapping:
1108
+ varIdx = advMapping.mapping[glyphName]
1109
+ else:
1110
+ varIdx = varfont.getGlyphID(glyphName)
1111
+ metrics[glyphName] = (advanceWidth + round(defaultDeltas[varIdx]), sb)
1112
+
1113
+ if (
1114
+ tableTag == "VVAR"
1115
+ and getattr(vhvar, tableFields.vOrigMapping) is not None
1116
+ ):
1117
+ log.warning(
1118
+ "VORG table not yet updated to reflect changes in VVAR table"
1119
+ )
1120
+
1121
+ # For full instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return
1122
+ if set(location).issuperset(axis.axisTag for axis in fvarAxes):
1123
+ log.info("Dropping %s table", tableTag)
1124
+ del varfont[tableTag]
1125
+ return
1126
+
1127
+ if varStore.VarRegionList.Region:
1128
+ # Only re-optimize VarStore if the HVAR/VVAR already uses indirect AdvWidthMap
1129
+ # or AdvHeightMap. If a direct, implicit glyphID->VariationIndex mapping is
1130
+ # used for advances, skip re-optimizing and maintain original VariationIndex.
1131
+ if getattr(vhvar, tableFields.advMapping):
1132
+ varIndexMapping = varStore.optimize(use_NO_VARIATION_INDEX=False)
1133
+ glyphOrder = varfont.getGlyphOrder()
1134
+ _remapVarIdxMap(vhvar, tableFields.advMapping, varIndexMapping, glyphOrder)
1135
+ if getattr(vhvar, tableFields.sb1): # left or top sidebearings
1136
+ _remapVarIdxMap(vhvar, tableFields.sb1, varIndexMapping, glyphOrder)
1137
+ if getattr(vhvar, tableFields.sb2): # right or bottom sidebearings
1138
+ _remapVarIdxMap(vhvar, tableFields.sb2, varIndexMapping, glyphOrder)
1139
+ if tableTag == "VVAR" and getattr(vhvar, tableFields.vOrigMapping):
1140
+ _remapVarIdxMap(
1141
+ vhvar, tableFields.vOrigMapping, varIndexMapping, glyphOrder
1142
+ )
1143
+
1144
+
1145
+ def instantiateHVAR(varfont, axisLimits):
1146
+ return _instantiateVHVAR(varfont, axisLimits, varLib.HVAR_FIELDS)
1147
+
1148
+
1149
+ def instantiateVVAR(varfont, axisLimits):
1150
+ return _instantiateVHVAR(varfont, axisLimits, varLib.VVAR_FIELDS)
1151
+
1152
+
1153
+ class _TupleVarStoreAdapter(object):
1154
+ def __init__(self, regions, axisOrder, tupleVarData, itemCounts):
1155
+ self.regions = regions
1156
+ self.axisOrder = axisOrder
1157
+ self.tupleVarData = tupleVarData
1158
+ self.itemCounts = itemCounts
1159
+
1160
+ @classmethod
1161
+ def fromItemVarStore(cls, itemVarStore, fvarAxes):
1162
+ axisOrder = [axis.axisTag for axis in fvarAxes]
1163
+ regions = [
1164
+ region.get_support(fvarAxes) for region in itemVarStore.VarRegionList.Region
1165
+ ]
1166
+ tupleVarData = []
1167
+ itemCounts = []
1168
+ for varData in itemVarStore.VarData:
1169
+ variations = []
1170
+ varDataRegions = (regions[i] for i in varData.VarRegionIndex)
1171
+ for axes, coordinates in zip(varDataRegions, zip(*varData.Item)):
1172
+ variations.append(TupleVariation(axes, list(coordinates)))
1173
+ tupleVarData.append(variations)
1174
+ itemCounts.append(varData.ItemCount)
1175
+ return cls(regions, axisOrder, tupleVarData, itemCounts)
1176
+
1177
+ def rebuildRegions(self):
1178
+ # Collect the set of all unique region axes from the current TupleVariations.
1179
+ # We use an OrderedDict to de-duplicate regions while keeping the order.
1180
+ uniqueRegions = collections.OrderedDict.fromkeys(
1181
+ (
1182
+ frozenset(var.axes.items())
1183
+ for variations in self.tupleVarData
1184
+ for var in variations
1185
+ )
1186
+ )
1187
+ # Maintain the original order for the regions that pre-existed, appending
1188
+ # the new regions at the end of the region list.
1189
+ newRegions = []
1190
+ for region in self.regions:
1191
+ regionAxes = frozenset(region.items())
1192
+ if regionAxes in uniqueRegions:
1193
+ newRegions.append(region)
1194
+ del uniqueRegions[regionAxes]
1195
+ if uniqueRegions:
1196
+ newRegions.extend(dict(region) for region in uniqueRegions)
1197
+ self.regions = newRegions
1198
+
1199
+ def instantiate(self, axisLimits):
1200
+ defaultDeltaArray = []
1201
+ for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
1202
+ defaultDeltas = instantiateTupleVariationStore(variations, axisLimits)
1203
+ if not defaultDeltas:
1204
+ defaultDeltas = [0] * itemCount
1205
+ defaultDeltaArray.append(defaultDeltas)
1206
+
1207
+ # rebuild regions whose axes were dropped or limited
1208
+ self.rebuildRegions()
1209
+
1210
+ pinnedAxes = set(axisLimits.pinnedLocation())
1211
+ self.axisOrder = [
1212
+ axisTag for axisTag in self.axisOrder if axisTag not in pinnedAxes
1213
+ ]
1214
+
1215
+ return defaultDeltaArray
1216
+
1217
+ def asItemVarStore(self):
1218
+ regionOrder = [frozenset(axes.items()) for axes in self.regions]
1219
+ varDatas = []
1220
+ for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
1221
+ if variations:
1222
+ assert len(variations[0].coordinates) == itemCount
1223
+ varRegionIndices = [
1224
+ regionOrder.index(frozenset(var.axes.items())) for var in variations
1225
+ ]
1226
+ varDataItems = list(zip(*(var.coordinates for var in variations)))
1227
+ varDatas.append(
1228
+ builder.buildVarData(varRegionIndices, varDataItems, optimize=False)
1229
+ )
1230
+ else:
1231
+ varDatas.append(
1232
+ builder.buildVarData([], [[] for _ in range(itemCount)])
1233
+ )
1234
+ regionList = builder.buildVarRegionList(self.regions, self.axisOrder)
1235
+ itemVarStore = builder.buildVarStore(regionList, varDatas)
1236
+ # remove unused regions from VarRegionList
1237
+ itemVarStore.prune_regions()
1238
+ return itemVarStore
1239
+
1240
+
1241
+ def instantiateItemVariationStore(itemVarStore, fvarAxes, axisLimits):
1242
+ """Compute deltas at partial location, and update varStore in-place.
1243
+
1244
+ Remove regions in which all axes were instanced, or fall outside the new axis
1245
+ limits. Scale the deltas of the remaining regions where only some of the axes
1246
+ were instanced.
1247
+
1248
+ The number of VarData subtables, and the number of items within each, are
1249
+ not modified, in order to keep the existing VariationIndex valid.
1250
+ One may call VarStore.optimize() method after this to further optimize those.
1251
+
1252
+ Args:
1253
+ varStore: An otTables.VarStore object (Item Variation Store)
1254
+ fvarAxes: list of fvar's Axis objects
1255
+ axisLimits: NormalizedAxisLimits: mapping axis tags to normalized
1256
+ min/default/max axis coordinates. May not specify coordinates/ranges for
1257
+ all the fvar axes.
1258
+
1259
+ Returns:
1260
+ defaultDeltas: to be added to the default instance, of type dict of floats
1261
+ keyed by VariationIndex compound values: i.e. (outer << 16) + inner.
1262
+ """
1263
+ tupleVarStore = _TupleVarStoreAdapter.fromItemVarStore(itemVarStore, fvarAxes)
1264
+ defaultDeltaArray = tupleVarStore.instantiate(axisLimits)
1265
+ newItemVarStore = tupleVarStore.asItemVarStore()
1266
+
1267
+ itemVarStore.VarRegionList = newItemVarStore.VarRegionList
1268
+ if not hasattr(itemVarStore, "VarDataCount"): # Happens fromXML
1269
+ itemVarStore.VarDataCount = len(newItemVarStore.VarData)
1270
+ assert itemVarStore.VarDataCount == newItemVarStore.VarDataCount
1271
+ itemVarStore.VarData = newItemVarStore.VarData
1272
+
1273
+ defaultDeltas = {
1274
+ ((major << 16) + minor): delta
1275
+ for major, deltas in enumerate(defaultDeltaArray)
1276
+ for minor, delta in enumerate(deltas)
1277
+ }
1278
+ defaultDeltas[itemVarStore.NO_VARIATION_INDEX] = 0
1279
+ return defaultDeltas
1280
+
1281
+
1282
+ def instantiateOTL(varfont, axisLimits):
1283
+ # TODO(anthrotype) Support partial instancing of JSTF and BASE tables
1284
+
1285
+ if (
1286
+ "GDEF" not in varfont
1287
+ or varfont["GDEF"].table.Version < 0x00010003
1288
+ or not varfont["GDEF"].table.VarStore
1289
+ ):
1290
+ return
1291
+
1292
+ if "GPOS" in varfont:
1293
+ msg = "Instantiating GDEF and GPOS tables"
1294
+ else:
1295
+ msg = "Instantiating GDEF table"
1296
+ log.info(msg)
1297
+
1298
+ gdef = varfont["GDEF"].table
1299
+ varStore = gdef.VarStore
1300
+ fvarAxes = varfont["fvar"].axes
1301
+
1302
+ defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
1303
+
1304
+ # When VF are built, big lookups may overflow and be broken into multiple
1305
+ # subtables. MutatorMerger (which inherits from AligningMerger) reattaches
1306
+ # them upon instancing, in case they can now fit a single subtable (if not,
1307
+ # they will be split again upon compilation).
1308
+ # This 'merger' also works as a 'visitor' that traverses the OTL tables and
1309
+ # calls specific methods when instances of a given type are found.
1310
+ # Specifically, it adds default deltas to GPOS Anchors/ValueRecords and GDEF
1311
+ # LigatureCarets, and optionally deletes all VariationIndex tables if the
1312
+ # VarStore is fully instanced.
1313
+ merger = MutatorMerger(
1314
+ varfont, defaultDeltas, deleteVariations=(not varStore.VarRegionList.Region)
1315
+ )
1316
+ merger.mergeTables(varfont, [varfont], ["GDEF", "GPOS"])
1317
+
1318
+ if varStore.VarRegionList.Region:
1319
+ varIndexMapping = varStore.optimize()
1320
+ gdef.remap_device_varidxes(varIndexMapping)
1321
+ if "GPOS" in varfont:
1322
+ varfont["GPOS"].table.remap_device_varidxes(varIndexMapping)
1323
+ else:
1324
+ # Downgrade GDEF.
1325
+ del gdef.VarStore
1326
+ gdef.Version = 0x00010002
1327
+ if gdef.MarkGlyphSetsDef is None:
1328
+ del gdef.MarkGlyphSetsDef
1329
+ gdef.Version = 0x00010000
1330
+
1331
+ if not (
1332
+ gdef.LigCaretList
1333
+ or gdef.MarkAttachClassDef
1334
+ or gdef.GlyphClassDef
1335
+ or gdef.AttachList
1336
+ or (gdef.Version >= 0x00010002 and gdef.MarkGlyphSetsDef)
1337
+ ):
1338
+ del varfont["GDEF"]
1339
+
1340
+
1341
+ def _isValidAvarSegmentMap(axisTag, segmentMap):
1342
+ if not segmentMap:
1343
+ return True
1344
+ if not {(-1.0, -1.0), (0, 0), (1.0, 1.0)}.issubset(segmentMap.items()):
1345
+ log.warning(
1346
+ f"Invalid avar SegmentMap record for axis '{axisTag}': does not "
1347
+ "include all required value maps {-1.0: -1.0, 0: 0, 1.0: 1.0}"
1348
+ )
1349
+ return False
1350
+ previousValue = None
1351
+ for fromCoord, toCoord in sorted(segmentMap.items()):
1352
+ if previousValue is not None and previousValue > toCoord:
1353
+ log.warning(
1354
+ f"Invalid avar AxisValueMap({fromCoord}, {toCoord}) record "
1355
+ f"for axis '{axisTag}': the toCoordinate value must be >= to "
1356
+ f"the toCoordinate value of the preceding record ({previousValue})."
1357
+ )
1358
+ return False
1359
+ previousValue = toCoord
1360
+ return True
1361
+
1362
+
1363
+ def instantiateAvar(varfont, axisLimits):
1364
+ # 'axisLimits' dict must contain user-space (non-normalized) coordinates.
1365
+
1366
+ avar = varfont["avar"]
1367
+ if getattr(avar, "majorVersion", 1) >= 2 and avar.table.VarStore:
1368
+ raise NotImplementedError("avar table with VarStore is not supported")
1369
+
1370
+ segments = avar.segments
1371
+
1372
+ # drop table if we instantiate all the axes
1373
+ pinnedAxes = set(axisLimits.pinnedLocation())
1374
+ if pinnedAxes.issuperset(segments):
1375
+ log.info("Dropping avar table")
1376
+ del varfont["avar"]
1377
+ return
1378
+
1379
+ log.info("Instantiating avar table")
1380
+ for axis in pinnedAxes:
1381
+ if axis in segments:
1382
+ del segments[axis]
1383
+
1384
+ # First compute the default normalization for axisLimits coordinates: i.e.
1385
+ # min = -1.0, default = 0, max = +1.0, and in between values interpolated linearly,
1386
+ # without using the avar table's mappings.
1387
+ # Then, for each SegmentMap, if we are restricting its axis, compute the new
1388
+ # mappings by dividing the key/value pairs by the desired new min/max values,
1389
+ # dropping any mappings that fall outside the restricted range.
1390
+ # The keys ('fromCoord') are specified in default normalized coordinate space,
1391
+ # whereas the values ('toCoord') are "mapped forward" using the SegmentMap.
1392
+ normalizedRanges = axisLimits.normalize(varfont, usingAvar=False)
1393
+ newSegments = {}
1394
+ for axisTag, mapping in segments.items():
1395
+ if not _isValidAvarSegmentMap(axisTag, mapping):
1396
+ continue
1397
+ if mapping and axisTag in normalizedRanges:
1398
+ axisRange = normalizedRanges[axisTag]
1399
+ mappedMin = floatToFixedToFloat(
1400
+ piecewiseLinearMap(axisRange.minimum, mapping), 14
1401
+ )
1402
+ mappedDef = floatToFixedToFloat(
1403
+ piecewiseLinearMap(axisRange.default, mapping), 14
1404
+ )
1405
+ mappedMax = floatToFixedToFloat(
1406
+ piecewiseLinearMap(axisRange.maximum, mapping), 14
1407
+ )
1408
+ mappedAxisLimit = NormalizedAxisTripleAndDistances(
1409
+ mappedMin,
1410
+ mappedDef,
1411
+ mappedMax,
1412
+ axisRange.distanceNegative,
1413
+ axisRange.distancePositive,
1414
+ )
1415
+ newMapping = {}
1416
+ for fromCoord, toCoord in mapping.items():
1417
+ if fromCoord < axisRange.minimum or fromCoord > axisRange.maximum:
1418
+ continue
1419
+ fromCoord = axisRange.renormalizeValue(fromCoord)
1420
+
1421
+ assert mappedMin <= toCoord <= mappedMax
1422
+ toCoord = mappedAxisLimit.renormalizeValue(toCoord)
1423
+
1424
+ fromCoord = floatToFixedToFloat(fromCoord, 14)
1425
+ toCoord = floatToFixedToFloat(toCoord, 14)
1426
+ newMapping[fromCoord] = toCoord
1427
+ newMapping.update({-1.0: -1.0, 0.0: 0.0, 1.0: 1.0})
1428
+ newSegments[axisTag] = newMapping
1429
+ else:
1430
+ newSegments[axisTag] = mapping
1431
+ avar.segments = newSegments
1432
+
1433
+
1434
+ def isInstanceWithinAxisRanges(location, axisRanges):
1435
+ for axisTag, coord in location.items():
1436
+ if axisTag in axisRanges:
1437
+ axisRange = axisRanges[axisTag]
1438
+ if coord < axisRange.minimum or coord > axisRange.maximum:
1439
+ return False
1440
+ return True
1441
+
1442
+
1443
+ def instantiateFvar(varfont, axisLimits):
1444
+ # 'axisLimits' dict must contain user-space (non-normalized) coordinates
1445
+
1446
+ location = axisLimits.pinnedLocation()
1447
+
1448
+ fvar = varfont["fvar"]
1449
+
1450
+ # drop table if we instantiate all the axes
1451
+ if set(location).issuperset(axis.axisTag for axis in fvar.axes):
1452
+ log.info("Dropping fvar table")
1453
+ del varfont["fvar"]
1454
+ return
1455
+
1456
+ log.info("Instantiating fvar table")
1457
+
1458
+ axes = []
1459
+ for axis in fvar.axes:
1460
+ axisTag = axis.axisTag
1461
+ if axisTag in location:
1462
+ continue
1463
+ if axisTag in axisLimits:
1464
+ triple = axisLimits[axisTag]
1465
+ if triple.default is None:
1466
+ triple = (triple.minimum, axis.defaultValue, triple.maximum)
1467
+ axis.minValue, axis.defaultValue, axis.maxValue = triple
1468
+ axes.append(axis)
1469
+ fvar.axes = axes
1470
+
1471
+ # only keep NamedInstances whose coordinates == pinned axis location
1472
+ instances = []
1473
+ for instance in fvar.instances:
1474
+ if any(instance.coordinates[axis] != value for axis, value in location.items()):
1475
+ continue
1476
+ for axisTag in location:
1477
+ del instance.coordinates[axisTag]
1478
+ if not isInstanceWithinAxisRanges(instance.coordinates, axisLimits):
1479
+ continue
1480
+ instances.append(instance)
1481
+ fvar.instances = instances
1482
+
1483
+
1484
+ def instantiateSTAT(varfont, axisLimits):
1485
+ # 'axisLimits' dict must contain user-space (non-normalized) coordinates
1486
+
1487
+ stat = varfont["STAT"].table
1488
+ if not stat.DesignAxisRecord or not (
1489
+ stat.AxisValueArray and stat.AxisValueArray.AxisValue
1490
+ ):
1491
+ return # STAT table empty, nothing to do
1492
+
1493
+ log.info("Instantiating STAT table")
1494
+ newAxisValueTables = axisValuesFromAxisLimits(stat, axisLimits)
1495
+ stat.AxisValueCount = len(newAxisValueTables)
1496
+ if stat.AxisValueCount:
1497
+ stat.AxisValueArray.AxisValue = newAxisValueTables
1498
+ else:
1499
+ stat.AxisValueArray = None
1500
+
1501
+
1502
+ def axisValuesFromAxisLimits(stat, axisLimits):
1503
+ def isAxisValueOutsideLimits(axisTag, axisValue):
1504
+ if axisTag in axisLimits:
1505
+ triple = axisLimits[axisTag]
1506
+ if axisValue < triple.minimum or axisValue > triple.maximum:
1507
+ return True
1508
+ return False
1509
+
1510
+ # only keep AxisValues whose axis is not pinned nor restricted, or is pinned at the
1511
+ # exact (nominal) value, or is restricted but the value is within the new range
1512
+ designAxes = stat.DesignAxisRecord.Axis
1513
+ newAxisValueTables = []
1514
+ for axisValueTable in stat.AxisValueArray.AxisValue:
1515
+ axisValueFormat = axisValueTable.Format
1516
+ if axisValueFormat in (1, 2, 3):
1517
+ axisTag = designAxes[axisValueTable.AxisIndex].AxisTag
1518
+ if axisValueFormat == 2:
1519
+ axisValue = axisValueTable.NominalValue
1520
+ else:
1521
+ axisValue = axisValueTable.Value
1522
+ if isAxisValueOutsideLimits(axisTag, axisValue):
1523
+ continue
1524
+ elif axisValueFormat == 4:
1525
+ # drop 'non-analytic' AxisValue if _any_ AxisValueRecord doesn't match
1526
+ # the pinned location or is outside range
1527
+ dropAxisValueTable = False
1528
+ for rec in axisValueTable.AxisValueRecord:
1529
+ axisTag = designAxes[rec.AxisIndex].AxisTag
1530
+ axisValue = rec.Value
1531
+ if isAxisValueOutsideLimits(axisTag, axisValue):
1532
+ dropAxisValueTable = True
1533
+ break
1534
+ if dropAxisValueTable:
1535
+ continue
1536
+ else:
1537
+ log.warning("Unknown AxisValue table format (%s); ignored", axisValueFormat)
1538
+ newAxisValueTables.append(axisValueTable)
1539
+ return newAxisValueTables
1540
+
1541
+
1542
+ def setMacOverlapFlags(glyfTable):
1543
+ flagOverlapCompound = _g_l_y_f.OVERLAP_COMPOUND
1544
+ flagOverlapSimple = _g_l_y_f.flagOverlapSimple
1545
+ for glyphName in glyfTable.keys():
1546
+ glyph = glyfTable[glyphName]
1547
+ # Set OVERLAP_COMPOUND bit for compound glyphs
1548
+ if glyph.isComposite():
1549
+ glyph.components[0].flags |= flagOverlapCompound
1550
+ # Set OVERLAP_SIMPLE bit for simple glyphs
1551
+ elif glyph.numberOfContours > 0:
1552
+ glyph.flags[0] |= flagOverlapSimple
1553
+
1554
+
1555
+ def normalize(value, triple, avarMapping):
1556
+ value = normalizeValue(value, triple)
1557
+ if avarMapping:
1558
+ value = piecewiseLinearMap(value, avarMapping)
1559
+ # Quantize to F2Dot14, to avoid surprise interpolations.
1560
+ return floatToFixedToFloat(value, 14)
1561
+
1562
+
1563
+ def sanityCheckVariableTables(varfont):
1564
+ if "fvar" not in varfont:
1565
+ raise ValueError("Missing required table fvar")
1566
+ if "gvar" in varfont:
1567
+ if "glyf" not in varfont:
1568
+ raise ValueError("Can't have gvar without glyf")
1569
+
1570
+
1571
+ def instantiateVariableFont(
1572
+ varfont,
1573
+ axisLimits,
1574
+ inplace=False,
1575
+ optimize=True,
1576
+ overlap=OverlapMode.KEEP_AND_SET_FLAGS,
1577
+ updateFontNames=False,
1578
+ *,
1579
+ downgradeCFF2=False,
1580
+ ):
1581
+ """Instantiate variable font, either fully or partially.
1582
+
1583
+ Depending on whether the `axisLimits` dictionary references all or some of the
1584
+ input varfont's axes, the output font will either be a full instance (static
1585
+ font) or a variable font with possibly less variation data.
1586
+
1587
+ Args:
1588
+ varfont: a TTFont instance, which must contain at least an 'fvar' table.
1589
+ axisLimits: a dict keyed by axis tags (str) containing the coordinates (float)
1590
+ along one or more axes where the desired instance will be located.
1591
+ If the value is `None`, the default coordinate as per 'fvar' table for
1592
+ that axis is used.
1593
+ The limit values can also be (min, max) tuples for restricting an
1594
+ axis's variation range. The default axis value must be included in
1595
+ the new range.
1596
+ inplace (bool): whether to modify input TTFont object in-place instead of
1597
+ returning a distinct object.
1598
+ optimize (bool): if False, do not perform IUP-delta optimization on the
1599
+ remaining 'gvar' table's deltas. Possibly faster, and might work around
1600
+ rendering issues in some buggy environments, at the cost of a slightly
1601
+ larger file size.
1602
+ overlap (OverlapMode): variable fonts usually contain overlapping contours, and
1603
+ some font rendering engines on Apple platforms require that the
1604
+ `OVERLAP_SIMPLE` and `OVERLAP_COMPOUND` flags in the 'glyf' table be set to
1605
+ force rendering using a non-zero fill rule. Thus we always set these flags
1606
+ on all glyphs to maximise cross-compatibility of the generated instance.
1607
+ You can disable this by passing OverlapMode.KEEP_AND_DONT_SET_FLAGS.
1608
+ If you want to remove the overlaps altogether and merge overlapping
1609
+ contours and components, you can pass OverlapMode.REMOVE (or
1610
+ REMOVE_AND_IGNORE_ERRORS to not hard-fail on tricky glyphs). Note that this
1611
+ requires the skia-pathops package (available to pip install).
1612
+ The overlap parameter only has effect when generating full static instances.
1613
+ updateFontNames (bool): if True, update the instantiated font's name table using
1614
+ the Axis Value Tables from the STAT table. The name table and the style bits
1615
+ in the head and OS/2 table will be updated so they conform to the R/I/B/BI
1616
+ model. If the STAT table is missing or an Axis Value table is missing for
1617
+ a given axis coordinate, a ValueError will be raised.
1618
+ downgradeCFF2 (bool): if True, downgrade the CFF2 table to CFF table when possible
1619
+ ie. full instancing of all axes. This is useful for compatibility with older
1620
+ software that does not support CFF2. Defaults to False. Note that this
1621
+ operation also removes overlaps within glyph shapes, as CFF does not support
1622
+ overlaps but CFF2 does.
1623
+ """
1624
+ # 'overlap' used to be bool and is now enum; for backward compat keep accepting bool
1625
+ overlap = OverlapMode(int(overlap))
1626
+
1627
+ sanityCheckVariableTables(varfont)
1628
+
1629
+ axisLimits = AxisLimits(axisLimits).limitAxesAndPopulateDefaults(varfont)
1630
+
1631
+ log.info("Restricted limits: %s", axisLimits)
1632
+
1633
+ normalizedLimits = axisLimits.normalize(varfont)
1634
+
1635
+ log.info("Normalized limits: %s", normalizedLimits)
1636
+
1637
+ if not inplace:
1638
+ varfont = deepcopy(varfont)
1639
+
1640
+ if "DSIG" in varfont:
1641
+ del varfont["DSIG"]
1642
+
1643
+ if updateFontNames:
1644
+ log.info("Updating name table")
1645
+ names.updateNameTable(varfont, axisLimits)
1646
+
1647
+ if "VARC" in varfont:
1648
+ instantiateVARC(varfont, normalizedLimits)
1649
+
1650
+ if "CFF2" in varfont:
1651
+ instantiateCFF2(varfont, normalizedLimits, downgrade=downgradeCFF2)
1652
+
1653
+ if "gvar" in varfont:
1654
+ instantiateGvar(varfont, normalizedLimits, optimize=optimize)
1655
+
1656
+ if "cvar" in varfont:
1657
+ instantiateCvar(varfont, normalizedLimits)
1658
+
1659
+ if "MVAR" in varfont:
1660
+ instantiateMVAR(varfont, normalizedLimits)
1661
+
1662
+ if "HVAR" in varfont:
1663
+ instantiateHVAR(varfont, normalizedLimits)
1664
+
1665
+ if "VVAR" in varfont:
1666
+ instantiateVVAR(varfont, normalizedLimits)
1667
+
1668
+ instantiateOTL(varfont, normalizedLimits)
1669
+
1670
+ instantiateFeatureVariations(varfont, normalizedLimits)
1671
+
1672
+ if "avar" in varfont:
1673
+ instantiateAvar(varfont, axisLimits)
1674
+
1675
+ with names.pruningUnusedNames(varfont):
1676
+ if "STAT" in varfont:
1677
+ instantiateSTAT(varfont, axisLimits)
1678
+
1679
+ instantiateFvar(varfont, axisLimits)
1680
+
1681
+ if "fvar" not in varfont:
1682
+ if "glyf" in varfont:
1683
+ if overlap == OverlapMode.KEEP_AND_SET_FLAGS:
1684
+ setMacOverlapFlags(varfont["glyf"])
1685
+ elif overlap in (OverlapMode.REMOVE, OverlapMode.REMOVE_AND_IGNORE_ERRORS):
1686
+ from fontTools.ttLib.removeOverlaps import removeOverlaps
1687
+
1688
+ log.info("Removing overlaps from glyf table")
1689
+ removeOverlaps(
1690
+ varfont,
1691
+ ignoreErrors=(overlap == OverlapMode.REMOVE_AND_IGNORE_ERRORS),
1692
+ )
1693
+
1694
+ if "OS/2" in varfont:
1695
+ varfont["OS/2"].recalcAvgCharWidth(varfont)
1696
+
1697
+ varLib.set_default_weight_width_slant(
1698
+ varfont, location=axisLimits.defaultLocation()
1699
+ )
1700
+
1701
+ if updateFontNames:
1702
+ # Set Regular/Italic/Bold/Bold Italic bits as appropriate, after the
1703
+ # name table has been updated.
1704
+ setRibbiBits(varfont)
1705
+
1706
+ return varfont
1707
+
1708
+
1709
+ def setRibbiBits(font):
1710
+ """Set the `head.macStyle` and `OS/2.fsSelection` style bits
1711
+ appropriately."""
1712
+
1713
+ english_ribbi_style = font["name"].getName(names.NameID.SUBFAMILY_NAME, 3, 1, 0x409)
1714
+ if english_ribbi_style is None:
1715
+ return
1716
+
1717
+ styleMapStyleName = english_ribbi_style.toStr().lower()
1718
+ if styleMapStyleName not in {"regular", "bold", "italic", "bold italic"}:
1719
+ return
1720
+
1721
+ if styleMapStyleName == "bold":
1722
+ font["head"].macStyle = 0b01
1723
+ elif styleMapStyleName == "bold italic":
1724
+ font["head"].macStyle = 0b11
1725
+ elif styleMapStyleName == "italic":
1726
+ font["head"].macStyle = 0b10
1727
+
1728
+ selection = font["OS/2"].fsSelection
1729
+ # First clear...
1730
+ selection &= ~(1 << 0)
1731
+ selection &= ~(1 << 5)
1732
+ selection &= ~(1 << 6)
1733
+ # ...then re-set the bits.
1734
+ if styleMapStyleName == "regular":
1735
+ selection |= 1 << 6
1736
+ elif styleMapStyleName == "bold":
1737
+ selection |= 1 << 5
1738
+ elif styleMapStyleName == "italic":
1739
+ selection |= 1 << 0
1740
+ elif styleMapStyleName == "bold italic":
1741
+ selection |= 1 << 0
1742
+ selection |= 1 << 5
1743
+ font["OS/2"].fsSelection = selection
1744
+
1745
+
1746
+ def parseLimits(limits: Iterable[str]) -> Dict[str, Optional[AxisTriple]]:
1747
+ result = {}
1748
+ for limitString in limits:
1749
+ match = re.match(
1750
+ r"^(\w{1,4})=(?:(drop)|(?:([^:]*)(?:[:]([^:]*))?(?:[:]([^:]*))?))$",
1751
+ limitString,
1752
+ )
1753
+ if not match:
1754
+ raise ValueError("invalid location format: %r" % limitString)
1755
+ tag = match.group(1).ljust(4)
1756
+
1757
+ if match.group(2): # 'drop'
1758
+ result[tag] = None
1759
+ continue
1760
+
1761
+ triple = match.group(3, 4, 5)
1762
+
1763
+ if triple[1] is None: # "value" syntax
1764
+ triple = (triple[0], triple[0], triple[0])
1765
+ elif triple[2] is None: # "min:max" syntax
1766
+ triple = (triple[0], None, triple[1])
1767
+
1768
+ triple = tuple(float(v) if v else None for v in triple)
1769
+
1770
+ result[tag] = AxisTriple(*triple)
1771
+
1772
+ return result
1773
+
1774
+
1775
+ def parseArgs(args):
1776
+ """Parse argv.
1777
+
1778
+ Returns:
1779
+ 3-tuple (infile, axisLimits, options)
1780
+ axisLimits is either a Dict[str, Optional[float]], for pinning variation axes
1781
+ to specific coordinates along those axes (with `None` as a placeholder for an
1782
+ axis' default value); or a Dict[str, Tuple(float, float)], meaning limit this
1783
+ axis to min/max range.
1784
+ Axes locations are in user-space coordinates, as defined in the "fvar" table.
1785
+ """
1786
+ from fontTools import configLogger
1787
+ import argparse
1788
+
1789
+ parser = argparse.ArgumentParser(
1790
+ "fonttools varLib.instancer",
1791
+ description="Partially instantiate a variable font",
1792
+ )
1793
+ parser.add_argument("input", metavar="INPUT.ttf", help="Input variable TTF file.")
1794
+ parser.add_argument(
1795
+ "locargs",
1796
+ metavar="AXIS=LOC",
1797
+ nargs="*",
1798
+ help="List of space separated locations. A location consists of "
1799
+ "the tag of a variation axis, followed by '=' and the literal, "
1800
+ "string 'drop', or colon-separated list of one to three values, "
1801
+ "each of which is the empty string, or a number. "
1802
+ "E.g.: wdth=100 or wght=75.0:125.0 or wght=100:400:700 or wght=:500: "
1803
+ "or wght=drop",
1804
+ )
1805
+ parser.add_argument(
1806
+ "-o",
1807
+ "--output",
1808
+ metavar="OUTPUT.ttf",
1809
+ default=None,
1810
+ help="Output instance TTF file (default: INPUT-instance.ttf).",
1811
+ )
1812
+ parser.add_argument(
1813
+ "--no-optimize",
1814
+ dest="optimize",
1815
+ action="store_false",
1816
+ help="Don't perform IUP optimization on the remaining gvar TupleVariations",
1817
+ )
1818
+ parser.add_argument(
1819
+ "--no-overlap-flag",
1820
+ dest="overlap",
1821
+ action="store_false",
1822
+ help="Don't set OVERLAP_SIMPLE/OVERLAP_COMPOUND glyf flags (only applicable "
1823
+ "when generating a full instance)",
1824
+ )
1825
+ parser.add_argument(
1826
+ "--remove-overlaps",
1827
+ dest="remove_overlaps",
1828
+ action="store_true",
1829
+ help="Merge overlapping contours and components (only applicable "
1830
+ "when generating a full instance). Requires skia-pathops",
1831
+ )
1832
+ parser.add_argument(
1833
+ "--ignore-overlap-errors",
1834
+ dest="ignore_overlap_errors",
1835
+ action="store_true",
1836
+ help="Don't crash if the remove-overlaps operation fails for some glyphs.",
1837
+ )
1838
+ parser.add_argument(
1839
+ "--update-name-table",
1840
+ action="store_true",
1841
+ help="Update the instantiated font's `name` table. Input font must have "
1842
+ "a STAT table with Axis Value Tables",
1843
+ )
1844
+ parser.add_argument(
1845
+ "--downgrade-cff2",
1846
+ action="store_true",
1847
+ help="If all axes are pinned, downgrade CFF2 to CFF table format",
1848
+ )
1849
+ parser.add_argument(
1850
+ "--no-recalc-timestamp",
1851
+ dest="recalc_timestamp",
1852
+ action="store_false",
1853
+ help="Don't set the output font's timestamp to the current time.",
1854
+ )
1855
+ parser.add_argument(
1856
+ "--no-recalc-bounds",
1857
+ dest="recalc_bounds",
1858
+ action="store_false",
1859
+ help="Don't recalculate font bounding boxes",
1860
+ )
1861
+ loggingGroup = parser.add_mutually_exclusive_group(required=False)
1862
+ loggingGroup.add_argument(
1863
+ "-v", "--verbose", action="store_true", help="Run more verbosely."
1864
+ )
1865
+ loggingGroup.add_argument(
1866
+ "-q", "--quiet", action="store_true", help="Turn verbosity off."
1867
+ )
1868
+ options = parser.parse_args(args)
1869
+
1870
+ if options.remove_overlaps:
1871
+ if options.ignore_overlap_errors:
1872
+ options.overlap = OverlapMode.REMOVE_AND_IGNORE_ERRORS
1873
+ else:
1874
+ options.overlap = OverlapMode.REMOVE
1875
+ else:
1876
+ options.overlap = OverlapMode(int(options.overlap))
1877
+
1878
+ infile = options.input
1879
+ if not os.path.isfile(infile):
1880
+ parser.error("No such file '{}'".format(infile))
1881
+
1882
+ configLogger(
1883
+ level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
1884
+ )
1885
+
1886
+ try:
1887
+ axisLimits = parseLimits(options.locargs)
1888
+ except ValueError as e:
1889
+ parser.error(str(e))
1890
+
1891
+ if len(axisLimits) != len(options.locargs):
1892
+ parser.error("Specified multiple limits for the same axis")
1893
+
1894
+ return (infile, axisLimits, options)
1895
+
1896
+
1897
+ def main(args=None):
1898
+ """Partially instantiate a variable font"""
1899
+ infile, axisLimits, options = parseArgs(args)
1900
+ log.info("Restricting axes: %s", axisLimits)
1901
+
1902
+ log.info("Loading variable font")
1903
+ varfont = TTFont(
1904
+ infile,
1905
+ recalcTimestamp=options.recalc_timestamp,
1906
+ recalcBBoxes=options.recalc_bounds,
1907
+ )
1908
+
1909
+ isFullInstance = {
1910
+ axisTag
1911
+ for axisTag, limit in axisLimits.items()
1912
+ if limit is None or limit[0] == limit[2]
1913
+ }.issuperset(axis.axisTag for axis in varfont["fvar"].axes)
1914
+
1915
+ instantiateVariableFont(
1916
+ varfont,
1917
+ axisLimits,
1918
+ inplace=True,
1919
+ optimize=options.optimize,
1920
+ overlap=options.overlap,
1921
+ updateFontNames=options.update_name_table,
1922
+ downgradeCFF2=options.downgrade_cff2,
1923
+ )
1924
+
1925
+ suffix = "-instance" if isFullInstance else "-partial"
1926
+ outfile = (
1927
+ makeOutputFileName(infile, overWrite=True, suffix=suffix)
1928
+ if not options.output
1929
+ else options.output
1930
+ )
1931
+
1932
+ log.info(
1933
+ "Saving %s font %s",
1934
+ "instance" if isFullInstance else "partial variable",
1935
+ outfile,
1936
+ )
1937
+ varfont.save(outfile)