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