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