fonttools 4.59.1__cp314-cp314t-musllinux_1_2_x86_64.whl

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

Potentially problematic release.


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

Files changed (346) hide show
  1. fontTools/__init__.py +8 -0
  2. fontTools/__main__.py +35 -0
  3. fontTools/afmLib.py +439 -0
  4. fontTools/agl.py +5233 -0
  5. fontTools/cffLib/CFF2ToCFF.py +233 -0
  6. fontTools/cffLib/CFFToCFF2.py +305 -0
  7. fontTools/cffLib/__init__.py +3694 -0
  8. fontTools/cffLib/specializer.py +927 -0
  9. fontTools/cffLib/transforms.py +495 -0
  10. fontTools/cffLib/width.py +210 -0
  11. fontTools/colorLib/__init__.py +0 -0
  12. fontTools/colorLib/builder.py +664 -0
  13. fontTools/colorLib/errors.py +2 -0
  14. fontTools/colorLib/geometry.py +143 -0
  15. fontTools/colorLib/table_builder.py +223 -0
  16. fontTools/colorLib/unbuilder.py +81 -0
  17. fontTools/config/__init__.py +90 -0
  18. fontTools/cu2qu/__init__.py +15 -0
  19. fontTools/cu2qu/__main__.py +6 -0
  20. fontTools/cu2qu/benchmark.py +54 -0
  21. fontTools/cu2qu/cli.py +198 -0
  22. fontTools/cu2qu/cu2qu.c +15560 -0
  23. fontTools/cu2qu/cu2qu.cpython-314t-x86_64-linux-musl.so +0 -0
  24. fontTools/cu2qu/cu2qu.py +531 -0
  25. fontTools/cu2qu/errors.py +77 -0
  26. fontTools/cu2qu/ufo.py +349 -0
  27. fontTools/designspaceLib/__init__.py +3338 -0
  28. fontTools/designspaceLib/__main__.py +6 -0
  29. fontTools/designspaceLib/split.py +475 -0
  30. fontTools/designspaceLib/statNames.py +260 -0
  31. fontTools/designspaceLib/types.py +147 -0
  32. fontTools/encodings/MacRoman.py +258 -0
  33. fontTools/encodings/StandardEncoding.py +258 -0
  34. fontTools/encodings/__init__.py +1 -0
  35. fontTools/encodings/codecs.py +135 -0
  36. fontTools/feaLib/__init__.py +4 -0
  37. fontTools/feaLib/__main__.py +78 -0
  38. fontTools/feaLib/ast.py +2143 -0
  39. fontTools/feaLib/builder.py +1802 -0
  40. fontTools/feaLib/error.py +22 -0
  41. fontTools/feaLib/lexer.c +17351 -0
  42. fontTools/feaLib/lexer.cpython-314t-x86_64-linux-musl.so +0 -0
  43. fontTools/feaLib/lexer.py +287 -0
  44. fontTools/feaLib/location.py +12 -0
  45. fontTools/feaLib/lookupDebugInfo.py +12 -0
  46. fontTools/feaLib/parser.py +2379 -0
  47. fontTools/feaLib/variableScalar.py +113 -0
  48. fontTools/fontBuilder.py +1014 -0
  49. fontTools/help.py +36 -0
  50. fontTools/merge/__init__.py +248 -0
  51. fontTools/merge/__main__.py +6 -0
  52. fontTools/merge/base.py +81 -0
  53. fontTools/merge/cmap.py +173 -0
  54. fontTools/merge/layout.py +526 -0
  55. fontTools/merge/options.py +85 -0
  56. fontTools/merge/tables.py +352 -0
  57. fontTools/merge/unicode.py +78 -0
  58. fontTools/merge/util.py +143 -0
  59. fontTools/misc/__init__.py +1 -0
  60. fontTools/misc/arrayTools.py +424 -0
  61. fontTools/misc/bezierTools.c +40151 -0
  62. fontTools/misc/bezierTools.cpython-314t-x86_64-linux-musl.so +0 -0
  63. fontTools/misc/bezierTools.py +1497 -0
  64. fontTools/misc/classifyTools.py +170 -0
  65. fontTools/misc/cliTools.py +53 -0
  66. fontTools/misc/configTools.py +349 -0
  67. fontTools/misc/cython.py +27 -0
  68. fontTools/misc/dictTools.py +83 -0
  69. fontTools/misc/eexec.py +119 -0
  70. fontTools/misc/encodingTools.py +72 -0
  71. fontTools/misc/etree.py +456 -0
  72. fontTools/misc/filenames.py +245 -0
  73. fontTools/misc/filesystem/__init__.py +68 -0
  74. fontTools/misc/filesystem/_base.py +134 -0
  75. fontTools/misc/filesystem/_copy.py +45 -0
  76. fontTools/misc/filesystem/_errors.py +54 -0
  77. fontTools/misc/filesystem/_info.py +75 -0
  78. fontTools/misc/filesystem/_osfs.py +164 -0
  79. fontTools/misc/filesystem/_path.py +67 -0
  80. fontTools/misc/filesystem/_subfs.py +92 -0
  81. fontTools/misc/filesystem/_tempfs.py +34 -0
  82. fontTools/misc/filesystem/_tools.py +34 -0
  83. fontTools/misc/filesystem/_walk.py +55 -0
  84. fontTools/misc/filesystem/_zipfs.py +204 -0
  85. fontTools/misc/fixedTools.py +253 -0
  86. fontTools/misc/intTools.py +25 -0
  87. fontTools/misc/iterTools.py +12 -0
  88. fontTools/misc/lazyTools.py +42 -0
  89. fontTools/misc/loggingTools.py +543 -0
  90. fontTools/misc/macCreatorType.py +56 -0
  91. fontTools/misc/macRes.py +261 -0
  92. fontTools/misc/plistlib/__init__.py +681 -0
  93. fontTools/misc/plistlib/py.typed +0 -0
  94. fontTools/misc/psCharStrings.py +1511 -0
  95. fontTools/misc/psLib.py +398 -0
  96. fontTools/misc/psOperators.py +572 -0
  97. fontTools/misc/py23.py +96 -0
  98. fontTools/misc/roundTools.py +110 -0
  99. fontTools/misc/sstruct.py +227 -0
  100. fontTools/misc/symfont.py +242 -0
  101. fontTools/misc/testTools.py +233 -0
  102. fontTools/misc/textTools.py +154 -0
  103. fontTools/misc/timeTools.py +88 -0
  104. fontTools/misc/transform.py +516 -0
  105. fontTools/misc/treeTools.py +45 -0
  106. fontTools/misc/vector.py +147 -0
  107. fontTools/misc/visitor.py +150 -0
  108. fontTools/misc/xmlReader.py +188 -0
  109. fontTools/misc/xmlWriter.py +231 -0
  110. fontTools/mtiLib/__init__.py +1400 -0
  111. fontTools/mtiLib/__main__.py +5 -0
  112. fontTools/otlLib/__init__.py +1 -0
  113. fontTools/otlLib/builder.py +3465 -0
  114. fontTools/otlLib/error.py +11 -0
  115. fontTools/otlLib/maxContextCalc.py +96 -0
  116. fontTools/otlLib/optimize/__init__.py +53 -0
  117. fontTools/otlLib/optimize/__main__.py +6 -0
  118. fontTools/otlLib/optimize/gpos.py +439 -0
  119. fontTools/pens/__init__.py +1 -0
  120. fontTools/pens/areaPen.py +52 -0
  121. fontTools/pens/basePen.py +475 -0
  122. fontTools/pens/boundsPen.py +98 -0
  123. fontTools/pens/cairoPen.py +26 -0
  124. fontTools/pens/cocoaPen.py +26 -0
  125. fontTools/pens/cu2quPen.py +325 -0
  126. fontTools/pens/explicitClosingLinePen.py +101 -0
  127. fontTools/pens/filterPen.py +241 -0
  128. fontTools/pens/freetypePen.py +462 -0
  129. fontTools/pens/hashPointPen.py +89 -0
  130. fontTools/pens/momentsPen.c +13466 -0
  131. fontTools/pens/momentsPen.cpython-314t-x86_64-linux-musl.so +0 -0
  132. fontTools/pens/momentsPen.py +879 -0
  133. fontTools/pens/perimeterPen.py +69 -0
  134. fontTools/pens/pointInsidePen.py +192 -0
  135. fontTools/pens/pointPen.py +609 -0
  136. fontTools/pens/qtPen.py +29 -0
  137. fontTools/pens/qu2cuPen.py +105 -0
  138. fontTools/pens/quartzPen.py +43 -0
  139. fontTools/pens/recordingPen.py +335 -0
  140. fontTools/pens/reportLabPen.py +79 -0
  141. fontTools/pens/reverseContourPen.py +96 -0
  142. fontTools/pens/roundingPen.py +130 -0
  143. fontTools/pens/statisticsPen.py +312 -0
  144. fontTools/pens/svgPathPen.py +310 -0
  145. fontTools/pens/t2CharStringPen.py +88 -0
  146. fontTools/pens/teePen.py +55 -0
  147. fontTools/pens/transformPen.py +115 -0
  148. fontTools/pens/ttGlyphPen.py +335 -0
  149. fontTools/pens/wxPen.py +29 -0
  150. fontTools/qu2cu/__init__.py +15 -0
  151. fontTools/qu2cu/__main__.py +7 -0
  152. fontTools/qu2cu/benchmark.py +56 -0
  153. fontTools/qu2cu/cli.py +125 -0
  154. fontTools/qu2cu/qu2cu.c +16753 -0
  155. fontTools/qu2cu/qu2cu.cpython-314t-x86_64-linux-musl.so +0 -0
  156. fontTools/qu2cu/qu2cu.py +405 -0
  157. fontTools/subset/__init__.py +3929 -0
  158. fontTools/subset/__main__.py +6 -0
  159. fontTools/subset/cff.py +184 -0
  160. fontTools/subset/svg.py +253 -0
  161. fontTools/subset/util.py +25 -0
  162. fontTools/svgLib/__init__.py +3 -0
  163. fontTools/svgLib/path/__init__.py +65 -0
  164. fontTools/svgLib/path/arc.py +154 -0
  165. fontTools/svgLib/path/parser.py +322 -0
  166. fontTools/svgLib/path/shapes.py +183 -0
  167. fontTools/t1Lib/__init__.py +648 -0
  168. fontTools/tfmLib.py +460 -0
  169. fontTools/ttLib/__init__.py +30 -0
  170. fontTools/ttLib/__main__.py +148 -0
  171. fontTools/ttLib/macUtils.py +54 -0
  172. fontTools/ttLib/removeOverlaps.py +393 -0
  173. fontTools/ttLib/reorderGlyphs.py +285 -0
  174. fontTools/ttLib/scaleUpem.py +436 -0
  175. fontTools/ttLib/sfnt.py +661 -0
  176. fontTools/ttLib/standardGlyphOrder.py +271 -0
  177. fontTools/ttLib/tables/B_A_S_E_.py +14 -0
  178. fontTools/ttLib/tables/BitmapGlyphMetrics.py +64 -0
  179. fontTools/ttLib/tables/C_B_D_T_.py +113 -0
  180. fontTools/ttLib/tables/C_B_L_C_.py +19 -0
  181. fontTools/ttLib/tables/C_F_F_.py +61 -0
  182. fontTools/ttLib/tables/C_F_F__2.py +26 -0
  183. fontTools/ttLib/tables/C_O_L_R_.py +165 -0
  184. fontTools/ttLib/tables/C_P_A_L_.py +305 -0
  185. fontTools/ttLib/tables/D_S_I_G_.py +158 -0
  186. fontTools/ttLib/tables/D__e_b_g.py +35 -0
  187. fontTools/ttLib/tables/DefaultTable.py +49 -0
  188. fontTools/ttLib/tables/E_B_D_T_.py +835 -0
  189. fontTools/ttLib/tables/E_B_L_C_.py +718 -0
  190. fontTools/ttLib/tables/F_F_T_M_.py +52 -0
  191. fontTools/ttLib/tables/F__e_a_t.py +149 -0
  192. fontTools/ttLib/tables/G_D_E_F_.py +13 -0
  193. fontTools/ttLib/tables/G_M_A_P_.py +148 -0
  194. fontTools/ttLib/tables/G_P_K_G_.py +133 -0
  195. fontTools/ttLib/tables/G_P_O_S_.py +14 -0
  196. fontTools/ttLib/tables/G_S_U_B_.py +13 -0
  197. fontTools/ttLib/tables/G_V_A_R_.py +5 -0
  198. fontTools/ttLib/tables/G__l_a_t.py +235 -0
  199. fontTools/ttLib/tables/G__l_o_c.py +85 -0
  200. fontTools/ttLib/tables/H_V_A_R_.py +13 -0
  201. fontTools/ttLib/tables/J_S_T_F_.py +13 -0
  202. fontTools/ttLib/tables/L_T_S_H_.py +58 -0
  203. fontTools/ttLib/tables/M_A_T_H_.py +13 -0
  204. fontTools/ttLib/tables/M_E_T_A_.py +352 -0
  205. fontTools/ttLib/tables/M_V_A_R_.py +13 -0
  206. fontTools/ttLib/tables/O_S_2f_2.py +752 -0
  207. fontTools/ttLib/tables/S_I_N_G_.py +99 -0
  208. fontTools/ttLib/tables/S_T_A_T_.py +15 -0
  209. fontTools/ttLib/tables/S_V_G_.py +223 -0
  210. fontTools/ttLib/tables/S__i_l_f.py +1040 -0
  211. fontTools/ttLib/tables/S__i_l_l.py +92 -0
  212. fontTools/ttLib/tables/T_S_I_B_.py +13 -0
  213. fontTools/ttLib/tables/T_S_I_C_.py +14 -0
  214. fontTools/ttLib/tables/T_S_I_D_.py +13 -0
  215. fontTools/ttLib/tables/T_S_I_J_.py +13 -0
  216. fontTools/ttLib/tables/T_S_I_P_.py +13 -0
  217. fontTools/ttLib/tables/T_S_I_S_.py +13 -0
  218. fontTools/ttLib/tables/T_S_I_V_.py +26 -0
  219. fontTools/ttLib/tables/T_S_I__0.py +70 -0
  220. fontTools/ttLib/tables/T_S_I__1.py +163 -0
  221. fontTools/ttLib/tables/T_S_I__2.py +17 -0
  222. fontTools/ttLib/tables/T_S_I__3.py +22 -0
  223. fontTools/ttLib/tables/T_S_I__5.py +60 -0
  224. fontTools/ttLib/tables/T_T_F_A_.py +14 -0
  225. fontTools/ttLib/tables/TupleVariation.py +884 -0
  226. fontTools/ttLib/tables/V_A_R_C_.py +12 -0
  227. fontTools/ttLib/tables/V_D_M_X_.py +249 -0
  228. fontTools/ttLib/tables/V_O_R_G_.py +165 -0
  229. fontTools/ttLib/tables/V_V_A_R_.py +13 -0
  230. fontTools/ttLib/tables/__init__.py +98 -0
  231. fontTools/ttLib/tables/_a_n_k_r.py +15 -0
  232. fontTools/ttLib/tables/_a_v_a_r.py +191 -0
  233. fontTools/ttLib/tables/_b_s_l_n.py +15 -0
  234. fontTools/ttLib/tables/_c_i_d_g.py +24 -0
  235. fontTools/ttLib/tables/_c_m_a_p.py +1591 -0
  236. fontTools/ttLib/tables/_c_v_a_r.py +94 -0
  237. fontTools/ttLib/tables/_c_v_t.py +56 -0
  238. fontTools/ttLib/tables/_f_e_a_t.py +15 -0
  239. fontTools/ttLib/tables/_f_p_g_m.py +62 -0
  240. fontTools/ttLib/tables/_f_v_a_r.py +261 -0
  241. fontTools/ttLib/tables/_g_a_s_p.py +63 -0
  242. fontTools/ttLib/tables/_g_c_i_d.py +13 -0
  243. fontTools/ttLib/tables/_g_l_y_f.py +2311 -0
  244. fontTools/ttLib/tables/_g_v_a_r.py +340 -0
  245. fontTools/ttLib/tables/_h_d_m_x.py +127 -0
  246. fontTools/ttLib/tables/_h_e_a_d.py +130 -0
  247. fontTools/ttLib/tables/_h_h_e_a.py +147 -0
  248. fontTools/ttLib/tables/_h_m_t_x.py +164 -0
  249. fontTools/ttLib/tables/_k_e_r_n.py +289 -0
  250. fontTools/ttLib/tables/_l_c_a_r.py +13 -0
  251. fontTools/ttLib/tables/_l_o_c_a.py +70 -0
  252. fontTools/ttLib/tables/_l_t_a_g.py +72 -0
  253. fontTools/ttLib/tables/_m_a_x_p.py +147 -0
  254. fontTools/ttLib/tables/_m_e_t_a.py +112 -0
  255. fontTools/ttLib/tables/_m_o_r_t.py +14 -0
  256. fontTools/ttLib/tables/_m_o_r_x.py +15 -0
  257. fontTools/ttLib/tables/_n_a_m_e.py +1237 -0
  258. fontTools/ttLib/tables/_o_p_b_d.py +14 -0
  259. fontTools/ttLib/tables/_p_o_s_t.py +319 -0
  260. fontTools/ttLib/tables/_p_r_e_p.py +16 -0
  261. fontTools/ttLib/tables/_p_r_o_p.py +12 -0
  262. fontTools/ttLib/tables/_s_b_i_x.py +129 -0
  263. fontTools/ttLib/tables/_t_r_a_k.py +332 -0
  264. fontTools/ttLib/tables/_v_h_e_a.py +139 -0
  265. fontTools/ttLib/tables/_v_m_t_x.py +19 -0
  266. fontTools/ttLib/tables/asciiTable.py +20 -0
  267. fontTools/ttLib/tables/grUtils.py +92 -0
  268. fontTools/ttLib/tables/otBase.py +1464 -0
  269. fontTools/ttLib/tables/otConverters.py +2068 -0
  270. fontTools/ttLib/tables/otData.py +6400 -0
  271. fontTools/ttLib/tables/otTables.py +2703 -0
  272. fontTools/ttLib/tables/otTraverse.py +163 -0
  273. fontTools/ttLib/tables/sbixGlyph.py +149 -0
  274. fontTools/ttLib/tables/sbixStrike.py +177 -0
  275. fontTools/ttLib/tables/table_API_readme.txt +91 -0
  276. fontTools/ttLib/tables/ttProgram.py +594 -0
  277. fontTools/ttLib/ttCollection.py +125 -0
  278. fontTools/ttLib/ttFont.py +1148 -0
  279. fontTools/ttLib/ttGlyphSet.py +490 -0
  280. fontTools/ttLib/ttVisitor.py +32 -0
  281. fontTools/ttLib/woff2.py +1680 -0
  282. fontTools/ttx.py +479 -0
  283. fontTools/ufoLib/__init__.py +2472 -0
  284. fontTools/ufoLib/converters.py +398 -0
  285. fontTools/ufoLib/errors.py +30 -0
  286. fontTools/ufoLib/etree.py +6 -0
  287. fontTools/ufoLib/filenames.py +346 -0
  288. fontTools/ufoLib/glifLib.py +2024 -0
  289. fontTools/ufoLib/kerning.py +121 -0
  290. fontTools/ufoLib/plistlib.py +47 -0
  291. fontTools/ufoLib/pointPen.py +6 -0
  292. fontTools/ufoLib/utils.py +79 -0
  293. fontTools/ufoLib/validators.py +1184 -0
  294. fontTools/unicode.py +50 -0
  295. fontTools/unicodedata/Blocks.py +801 -0
  296. fontTools/unicodedata/Mirrored.py +446 -0
  297. fontTools/unicodedata/OTTags.py +50 -0
  298. fontTools/unicodedata/ScriptExtensions.py +826 -0
  299. fontTools/unicodedata/Scripts.py +3617 -0
  300. fontTools/unicodedata/__init__.py +304 -0
  301. fontTools/varLib/__init__.py +1517 -0
  302. fontTools/varLib/__main__.py +6 -0
  303. fontTools/varLib/avar.py +260 -0
  304. fontTools/varLib/avarPlanner.py +1004 -0
  305. fontTools/varLib/builder.py +215 -0
  306. fontTools/varLib/cff.py +631 -0
  307. fontTools/varLib/errors.py +219 -0
  308. fontTools/varLib/featureVars.py +703 -0
  309. fontTools/varLib/hvar.py +113 -0
  310. fontTools/varLib/instancer/__init__.py +2014 -0
  311. fontTools/varLib/instancer/__main__.py +5 -0
  312. fontTools/varLib/instancer/featureVars.py +190 -0
  313. fontTools/varLib/instancer/names.py +388 -0
  314. fontTools/varLib/instancer/solver.py +309 -0
  315. fontTools/varLib/interpolatable.py +1209 -0
  316. fontTools/varLib/interpolatableHelpers.py +396 -0
  317. fontTools/varLib/interpolatablePlot.py +1269 -0
  318. fontTools/varLib/interpolatableTestContourOrder.py +82 -0
  319. fontTools/varLib/interpolatableTestStartingPoint.py +107 -0
  320. fontTools/varLib/interpolate_layout.py +124 -0
  321. fontTools/varLib/iup.c +19845 -0
  322. fontTools/varLib/iup.cpython-314t-x86_64-linux-musl.so +0 -0
  323. fontTools/varLib/iup.py +490 -0
  324. fontTools/varLib/merger.py +1717 -0
  325. fontTools/varLib/models.py +642 -0
  326. fontTools/varLib/multiVarStore.py +253 -0
  327. fontTools/varLib/mutator.py +529 -0
  328. fontTools/varLib/mvar.py +40 -0
  329. fontTools/varLib/plot.py +238 -0
  330. fontTools/varLib/stat.py +149 -0
  331. fontTools/varLib/varStore.py +739 -0
  332. fontTools/voltLib/__init__.py +5 -0
  333. fontTools/voltLib/__main__.py +206 -0
  334. fontTools/voltLib/ast.py +452 -0
  335. fontTools/voltLib/error.py +12 -0
  336. fontTools/voltLib/lexer.py +99 -0
  337. fontTools/voltLib/parser.py +664 -0
  338. fontTools/voltLib/voltToFea.py +911 -0
  339. fonttools-4.59.1.data/data/share/man/man1/ttx.1 +225 -0
  340. fonttools-4.59.1.dist-info/METADATA +2175 -0
  341. fonttools-4.59.1.dist-info/RECORD +346 -0
  342. fonttools-4.59.1.dist-info/WHEEL +5 -0
  343. fonttools-4.59.1.dist-info/entry_points.txt +5 -0
  344. fonttools-4.59.1.dist-info/licenses/LICENSE +21 -0
  345. fonttools-4.59.1.dist-info/licenses/LICENSE.external +388 -0
  346. fonttools-4.59.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1517 @@
1
+ """
2
+ Module for dealing with 'gvar'-style font variations, also known as run-time
3
+ interpolation.
4
+
5
+ The ideas here are very similar to MutatorMath. There is even code to read
6
+ MutatorMath .designspace files in the varLib.designspace module.
7
+
8
+ For now, if you run this file on a designspace file, it tries to find
9
+ ttf-interpolatable files for the masters and build a variable-font from
10
+ them. Such ttf-interpolatable and designspace files can be generated from
11
+ a Glyphs source, eg., using noto-source as an example:
12
+
13
+ .. code-block:: sh
14
+
15
+ $ fontmake -o ttf-interpolatable -g NotoSansArabic-MM.glyphs
16
+
17
+ Then you can make a variable-font this way:
18
+
19
+ .. code-block:: sh
20
+
21
+ $ fonttools varLib master_ufo/NotoSansArabic.designspace
22
+
23
+ API *will* change in near future.
24
+ """
25
+
26
+ from typing import List
27
+ from fontTools.misc.vector import Vector
28
+ from fontTools.misc.roundTools import noRound, otRound
29
+ from fontTools.misc.fixedTools import floatToFixed as fl2fi
30
+ from fontTools.misc.textTools import Tag, tostr
31
+ from fontTools.ttLib import TTFont, newTable
32
+ from fontTools.ttLib.tables._f_v_a_r import Axis, NamedInstance
33
+ from fontTools.ttLib.tables._g_l_y_f import GlyphCoordinates, dropImpliedOnCurvePoints
34
+ from fontTools.ttLib.tables.ttProgram import Program
35
+ from fontTools.ttLib.tables.TupleVariation import TupleVariation
36
+ from fontTools.ttLib.tables import otTables as ot
37
+ from fontTools.ttLib.tables.otBase import OTTableWriter
38
+ from fontTools.varLib import builder, models, varStore
39
+ from fontTools.varLib.merger import VariationMerger, COLRVariationMerger
40
+ from fontTools.varLib.mvar import MVAR_ENTRIES
41
+ from fontTools.varLib.iup import iup_delta_optimize
42
+ from fontTools.varLib.featureVars import addFeatureVariations
43
+ from fontTools.designspaceLib import DesignSpaceDocument, InstanceDescriptor
44
+ from fontTools.designspaceLib.split import splitInterpolable, splitVariableFonts
45
+ from fontTools.varLib.stat import buildVFStatTable
46
+ from fontTools.colorLib.builder import buildColrV1
47
+ from fontTools.colorLib.unbuilder import unbuildColrV1
48
+ from functools import partial
49
+ from collections import OrderedDict, defaultdict, namedtuple
50
+ import os.path
51
+ import logging
52
+ from copy import deepcopy
53
+ from pprint import pformat
54
+ from re import fullmatch
55
+ from .errors import VarLibError, VarLibValidationError
56
+
57
+ log = logging.getLogger("fontTools.varLib")
58
+
59
+ # This is a lib key for the designspace document. The value should be
60
+ # a comma-separated list of OpenType feature tag(s), to be used as the
61
+ # FeatureVariations feature.
62
+ # If present, the DesignSpace <rules processing="..."> flag is ignored.
63
+ FEAVAR_FEATURETAG_LIB_KEY = "com.github.fonttools.varLib.featureVarsFeatureTag"
64
+
65
+ #
66
+ # Creation routines
67
+ #
68
+
69
+
70
+ def _add_fvar(font, axes, instances: List[InstanceDescriptor]):
71
+ """
72
+ Add 'fvar' table to font.
73
+
74
+ axes is an ordered dictionary of DesignspaceAxis objects.
75
+
76
+ instances is list of dictionary objects with 'location', 'stylename',
77
+ and possibly 'postscriptfontname' entries.
78
+ """
79
+
80
+ assert axes
81
+ assert isinstance(axes, OrderedDict)
82
+
83
+ log.info("Generating fvar")
84
+
85
+ fvar = newTable("fvar")
86
+ nameTable = font["name"]
87
+
88
+ # if there are not currently any mac names don't add them here, that's inconsistent
89
+ # https://github.com/fonttools/fonttools/issues/683
90
+ macNames = any(nr.platformID == 1 for nr in getattr(nameTable, "names", ()))
91
+
92
+ # we have all the best ways to express mac names
93
+ platforms = ((3, 1, 0x409),)
94
+ if macNames:
95
+ platforms = ((1, 0, 0),) + platforms
96
+
97
+ for a in axes.values():
98
+ axis = Axis()
99
+ axis.axisTag = Tag(a.tag)
100
+ # TODO Skip axes that have no variation.
101
+ axis.minValue, axis.defaultValue, axis.maxValue = (
102
+ a.minimum,
103
+ a.default,
104
+ a.maximum,
105
+ )
106
+ axis.axisNameID = nameTable.addMultilingualName(
107
+ a.labelNames, font, minNameID=256, mac=macNames
108
+ )
109
+ axis.flags = int(a.hidden)
110
+ fvar.axes.append(axis)
111
+
112
+ default_coordinates = {axis.axisTag: axis.defaultValue for axis in fvar.axes}
113
+
114
+ for instance in instances:
115
+ # Filter out discrete axis locations
116
+ coordinates = {
117
+ name: value for name, value in instance.location.items() if name in axes
118
+ }
119
+
120
+ if "en" not in instance.localisedStyleName:
121
+ if not instance.styleName:
122
+ raise VarLibValidationError(
123
+ f"Instance at location '{coordinates}' must have a default English "
124
+ "style name ('stylename' attribute on the instance element or a "
125
+ "stylename element with an 'xml:lang=\"en\"' attribute)."
126
+ )
127
+ localisedStyleName = dict(instance.localisedStyleName)
128
+ localisedStyleName["en"] = tostr(instance.styleName)
129
+ else:
130
+ localisedStyleName = instance.localisedStyleName
131
+
132
+ psname = instance.postScriptFontName
133
+
134
+ inst = NamedInstance()
135
+ inst.coordinates = {
136
+ axes[k].tag: axes[k].map_backward(v) for k, v in coordinates.items()
137
+ }
138
+
139
+ subfamilyNameID = nameTable.findMultilingualName(
140
+ localisedStyleName, windows=True, mac=macNames
141
+ )
142
+ if subfamilyNameID in {2, 17} and inst.coordinates == default_coordinates:
143
+ # Instances can only reuse an existing name ID 2 or 17 if they are at the
144
+ # default location across all axes, see:
145
+ # https://github.com/fonttools/fonttools/issues/3825.
146
+ inst.subfamilyNameID = subfamilyNameID
147
+ else:
148
+ inst.subfamilyNameID = nameTable.addMultilingualName(
149
+ localisedStyleName, windows=True, mac=macNames, minNameID=256
150
+ )
151
+
152
+ if psname is not None:
153
+ psname = tostr(psname)
154
+ inst.postscriptNameID = nameTable.addName(psname, platforms=platforms)
155
+ fvar.instances.append(inst)
156
+
157
+ assert "fvar" not in font
158
+ font["fvar"] = fvar
159
+
160
+ return fvar
161
+
162
+
163
+ def _add_avar(font, axes, mappings, axisTags):
164
+ """
165
+ Add 'avar' table to font.
166
+
167
+ axes is an ordered dictionary of AxisDescriptor objects.
168
+ """
169
+
170
+ assert axes
171
+ assert isinstance(axes, OrderedDict)
172
+
173
+ log.info("Generating avar")
174
+
175
+ avar = newTable("avar")
176
+
177
+ interesting = False
178
+ vals_triples = {}
179
+ for axis in axes.values():
180
+ # Currently, some rasterizers require that the default value maps
181
+ # (-1 to -1, 0 to 0, and 1 to 1) be present for all the segment
182
+ # maps, even when the default normalization mapping for the axis
183
+ # was not modified.
184
+ # https://github.com/googlei18n/fontmake/issues/295
185
+ # https://github.com/fonttools/fonttools/issues/1011
186
+ # TODO(anthrotype) revert this (and 19c4b37) when issue is fixed
187
+ curve = avar.segments[axis.tag] = {-1.0: -1.0, 0.0: 0.0, 1.0: 1.0}
188
+
189
+ keys_triple = (axis.minimum, axis.default, axis.maximum)
190
+ vals_triple = tuple(axis.map_forward(v) for v in keys_triple)
191
+ vals_triples[axis.tag] = vals_triple
192
+
193
+ if not axis.map:
194
+ continue
195
+
196
+ items = sorted(axis.map)
197
+ keys = [item[0] for item in items]
198
+ vals = [item[1] for item in items]
199
+
200
+ # Current avar requirements. We don't have to enforce
201
+ # these on the designer and can deduce some ourselves,
202
+ # but for now just enforce them.
203
+ if axis.minimum != min(keys):
204
+ raise VarLibValidationError(
205
+ f"Axis '{axis.name}': there must be a mapping for the axis minimum "
206
+ f"value {axis.minimum} and it must be the lowest input mapping value."
207
+ )
208
+ if axis.maximum != max(keys):
209
+ raise VarLibValidationError(
210
+ f"Axis '{axis.name}': there must be a mapping for the axis maximum "
211
+ f"value {axis.maximum} and it must be the highest input mapping value."
212
+ )
213
+ if axis.default not in keys:
214
+ raise VarLibValidationError(
215
+ f"Axis '{axis.name}': there must be a mapping for the axis default "
216
+ f"value {axis.default}."
217
+ )
218
+ # No duplicate input values (output values can be >= their preceeding value).
219
+ if len(set(keys)) != len(keys):
220
+ raise VarLibValidationError(
221
+ f"Axis '{axis.name}': All axis mapping input='...' values must be "
222
+ "unique, but we found duplicates."
223
+ )
224
+ # Ascending values
225
+ if sorted(vals) != vals:
226
+ raise VarLibValidationError(
227
+ f"Axis '{axis.name}': mapping output values must be in ascending order."
228
+ )
229
+
230
+ keys = [models.normalizeValue(v, keys_triple) for v in keys]
231
+ vals = [models.normalizeValue(v, vals_triple) for v in vals]
232
+
233
+ if all(k == v for k, v in zip(keys, vals)):
234
+ continue
235
+ interesting = True
236
+
237
+ curve.update(zip(keys, vals))
238
+
239
+ assert 0.0 in curve and curve[0.0] == 0.0
240
+ assert -1.0 not in curve or curve[-1.0] == -1.0
241
+ assert +1.0 not in curve or curve[+1.0] == +1.0
242
+ # curve.update({-1.0: -1.0, 0.0: 0.0, 1.0: 1.0})
243
+
244
+ if mappings:
245
+ interesting = True
246
+
247
+ inputLocations = [
248
+ {
249
+ axes[name].tag: models.normalizeValue(v, vals_triples[axes[name].tag])
250
+ for name, v in mapping.inputLocation.items()
251
+ }
252
+ for mapping in mappings
253
+ ]
254
+ outputLocations = [
255
+ {
256
+ axes[name].tag: models.normalizeValue(v, vals_triples[axes[name].tag])
257
+ for name, v in mapping.outputLocation.items()
258
+ }
259
+ for mapping in mappings
260
+ ]
261
+ assert len(inputLocations) == len(outputLocations)
262
+
263
+ # If base-master is missing, insert it at zero location.
264
+ if not any(all(v == 0 for k, v in loc.items()) for loc in inputLocations):
265
+ inputLocations.insert(0, {})
266
+ outputLocations.insert(0, {})
267
+
268
+ model = models.VariationModel(inputLocations, axisTags)
269
+ storeBuilder = varStore.OnlineVarStoreBuilder(axisTags)
270
+ storeBuilder.setModel(model)
271
+ varIdxes = {}
272
+ for tag in axisTags:
273
+ masterValues = []
274
+ for vo, vi in zip(outputLocations, inputLocations):
275
+ if tag not in vo:
276
+ masterValues.append(0)
277
+ continue
278
+ v = vo[tag] - vi.get(tag, 0)
279
+ masterValues.append(fl2fi(v, 14))
280
+ varIdxes[tag] = storeBuilder.storeMasters(masterValues)[1]
281
+
282
+ store = storeBuilder.finish()
283
+ optimized = store.optimize()
284
+ varIdxes = {axis: optimized[value] for axis, value in varIdxes.items()}
285
+
286
+ varIdxMap = builder.buildDeltaSetIndexMap(varIdxes[t] for t in axisTags)
287
+
288
+ avar.majorVersion = 2
289
+ avar.table = ot.avar()
290
+ avar.table.VarIdxMap = varIdxMap
291
+ avar.table.VarStore = store
292
+
293
+ assert "avar" not in font
294
+ if not interesting:
295
+ log.info("No need for avar")
296
+ avar = None
297
+ else:
298
+ font["avar"] = avar
299
+
300
+ return avar
301
+
302
+
303
+ def _add_stat(font):
304
+ # Note: this function only gets called by old code that calls `build()`
305
+ # directly. Newer code that wants to benefit from STAT data from the
306
+ # designspace should call `build_many()`
307
+
308
+ if "STAT" in font:
309
+ return
310
+
311
+ from ..otlLib.builder import buildStatTable
312
+
313
+ fvarTable = font["fvar"]
314
+ axes = [dict(tag=a.axisTag, name=a.axisNameID) for a in fvarTable.axes]
315
+ buildStatTable(font, axes)
316
+
317
+
318
+ _MasterData = namedtuple("_MasterData", ["glyf", "hMetrics", "vMetrics"])
319
+
320
+
321
+ def _add_gvar(font, masterModel, master_ttfs, tolerance=0.5, optimize=True):
322
+ if tolerance < 0:
323
+ raise ValueError("`tolerance` must be a positive number.")
324
+
325
+ log.info("Generating gvar")
326
+ assert "gvar" not in font
327
+ gvar = font["gvar"] = newTable("gvar")
328
+ glyf = font["glyf"]
329
+ defaultMasterIndex = masterModel.reverseMapping[0]
330
+
331
+ master_datas = [
332
+ _MasterData(
333
+ m["glyf"], m["hmtx"].metrics, getattr(m.get("vmtx"), "metrics", None)
334
+ )
335
+ for m in master_ttfs
336
+ ]
337
+
338
+ for glyph in font.getGlyphOrder():
339
+ log.debug("building gvar for glyph '%s'", glyph)
340
+
341
+ allData = [
342
+ m.glyf._getCoordinatesAndControls(glyph, m.hMetrics, m.vMetrics)
343
+ for m in master_datas
344
+ ]
345
+
346
+ if allData[defaultMasterIndex][1].numberOfContours != 0:
347
+ # If the default master is not empty, interpret empty non-default masters
348
+ # as missing glyphs from a sparse master
349
+ allData = [
350
+ d if d is not None and d[1].numberOfContours != 0 else None
351
+ for d in allData
352
+ ]
353
+
354
+ model, allData = masterModel.getSubModel(allData)
355
+
356
+ allCoords = [d[0] for d in allData]
357
+ allControls = [d[1] for d in allData]
358
+ control = allControls[0]
359
+ if not models.allEqual(allControls):
360
+ log.warning("glyph %s has incompatible masters; skipping" % glyph)
361
+ continue
362
+ del allControls
363
+
364
+ # Update gvar
365
+ gvar.variations[glyph] = []
366
+ deltas = model.getDeltas(
367
+ allCoords, round=partial(GlyphCoordinates.__round__, round=round)
368
+ )
369
+ supports = model.supports
370
+ assert len(deltas) == len(supports)
371
+
372
+ # Prepare for IUP optimization
373
+ origCoords = deltas[0]
374
+ endPts = control.endPts
375
+
376
+ for i, (delta, support) in enumerate(zip(deltas[1:], supports[1:])):
377
+ if all(v == 0 for v in delta.array):
378
+ continue
379
+ var = TupleVariation(support, delta)
380
+ if optimize:
381
+ delta_opt = iup_delta_optimize(
382
+ delta, origCoords, endPts, tolerance=tolerance
383
+ )
384
+
385
+ if None in delta_opt:
386
+ # Use "optimized" version only if smaller...
387
+ var_opt = TupleVariation(support, delta_opt)
388
+
389
+ axis_tags = sorted(
390
+ support.keys()
391
+ ) # Shouldn't matter that this is different from fvar...?
392
+ tupleData, auxData = var.compile(axis_tags)
393
+ unoptimized_len = len(tupleData) + len(auxData)
394
+ tupleData, auxData = var_opt.compile(axis_tags)
395
+ optimized_len = len(tupleData) + len(auxData)
396
+
397
+ if optimized_len < unoptimized_len:
398
+ var = var_opt
399
+
400
+ gvar.variations[glyph].append(var)
401
+
402
+
403
+ def _remove_TTHinting(font):
404
+ for tag in ("cvar", "cvt ", "fpgm", "prep"):
405
+ if tag in font:
406
+ del font[tag]
407
+ maxp = font["maxp"]
408
+ for attr in (
409
+ "maxTwilightPoints",
410
+ "maxStorage",
411
+ "maxFunctionDefs",
412
+ "maxInstructionDefs",
413
+ "maxStackElements",
414
+ "maxSizeOfInstructions",
415
+ ):
416
+ setattr(maxp, attr, 0)
417
+ maxp.maxZones = 1
418
+ font["glyf"].removeHinting()
419
+ # TODO: Modify gasp table to deactivate gridfitting for all ranges?
420
+
421
+
422
+ def _merge_TTHinting(font, masterModel, master_ttfs):
423
+ log.info("Merging TT hinting")
424
+ assert "cvar" not in font
425
+
426
+ # Check that the existing hinting is compatible
427
+
428
+ # fpgm and prep table
429
+
430
+ for tag in ("fpgm", "prep"):
431
+ all_pgms = [m[tag].program for m in master_ttfs if tag in m]
432
+ if not all_pgms:
433
+ continue
434
+ font_pgm = getattr(font.get(tag), "program", None)
435
+ if any(pgm != font_pgm for pgm in all_pgms):
436
+ log.warning(
437
+ "Masters have incompatible %s tables, hinting is discarded." % tag
438
+ )
439
+ _remove_TTHinting(font)
440
+ return
441
+
442
+ # glyf table
443
+
444
+ font_glyf = font["glyf"]
445
+ master_glyfs = [m["glyf"] for m in master_ttfs]
446
+ for name, glyph in font_glyf.glyphs.items():
447
+ all_pgms = [getattr(glyf.get(name), "program", None) for glyf in master_glyfs]
448
+ if not any(all_pgms):
449
+ continue
450
+ glyph.expand(font_glyf)
451
+ font_pgm = getattr(glyph, "program", None)
452
+ if any(pgm != font_pgm for pgm in all_pgms if pgm):
453
+ log.warning(
454
+ "Masters have incompatible glyph programs in glyph '%s', hinting is discarded."
455
+ % name
456
+ )
457
+ # TODO Only drop hinting from this glyph.
458
+ _remove_TTHinting(font)
459
+ return
460
+
461
+ # cvt table
462
+
463
+ all_cvs = [Vector(m["cvt "].values) if "cvt " in m else None for m in master_ttfs]
464
+
465
+ nonNone_cvs = models.nonNone(all_cvs)
466
+ if not nonNone_cvs:
467
+ # There is no cvt table to make a cvar table from, we're done here.
468
+ return
469
+
470
+ if not models.allEqual(len(c) for c in nonNone_cvs):
471
+ log.warning("Masters have incompatible cvt tables, hinting is discarded.")
472
+ _remove_TTHinting(font)
473
+ return
474
+
475
+ variations = []
476
+ deltas, supports = masterModel.getDeltasAndSupports(
477
+ all_cvs, round=round
478
+ ) # builtin round calls into Vector.__round__, which uses builtin round as we like
479
+ for i, (delta, support) in enumerate(zip(deltas[1:], supports[1:])):
480
+ if all(v == 0 for v in delta):
481
+ continue
482
+ var = TupleVariation(support, delta)
483
+ variations.append(var)
484
+
485
+ # We can build the cvar table now.
486
+ if variations:
487
+ cvar = font["cvar"] = newTable("cvar")
488
+ cvar.version = 1
489
+ cvar.variations = variations
490
+
491
+
492
+ _MetricsFields = namedtuple(
493
+ "_MetricsFields",
494
+ [
495
+ "tableTag",
496
+ "metricsTag",
497
+ "sb1",
498
+ "sb2",
499
+ "advMapping",
500
+ "vOrigMapping",
501
+ "phantomIndex",
502
+ ],
503
+ )
504
+
505
+ HVAR_FIELDS = _MetricsFields(
506
+ tableTag="HVAR",
507
+ metricsTag="hmtx",
508
+ sb1="LsbMap",
509
+ sb2="RsbMap",
510
+ advMapping="AdvWidthMap",
511
+ vOrigMapping=None,
512
+ phantomIndex=0,
513
+ )
514
+
515
+ VVAR_FIELDS = _MetricsFields(
516
+ tableTag="VVAR",
517
+ metricsTag="vmtx",
518
+ sb1="TsbMap",
519
+ sb2="BsbMap",
520
+ advMapping="AdvHeightMap",
521
+ vOrigMapping="VOrgMap",
522
+ phantomIndex=1,
523
+ )
524
+
525
+
526
+ def _add_HVAR(font, masterModel, master_ttfs, axisTags):
527
+ getAdvanceMetrics = partial(
528
+ _get_advance_metrics, font, masterModel, master_ttfs, axisTags, HVAR_FIELDS
529
+ )
530
+ _add_VHVAR(font, axisTags, HVAR_FIELDS, getAdvanceMetrics)
531
+
532
+
533
+ def _add_VVAR(font, masterModel, master_ttfs, axisTags):
534
+ getAdvanceMetrics = partial(
535
+ _get_advance_metrics, font, masterModel, master_ttfs, axisTags, VVAR_FIELDS
536
+ )
537
+ _add_VHVAR(font, axisTags, VVAR_FIELDS, getAdvanceMetrics)
538
+
539
+
540
+ def _add_VHVAR(font, axisTags, tableFields, getAdvanceMetrics):
541
+ tableTag = tableFields.tableTag
542
+ assert tableTag not in font
543
+ glyphOrder = font.getGlyphOrder()
544
+ log.info("Generating " + tableTag)
545
+ VHVAR = newTable(tableTag)
546
+ tableClass = getattr(ot, tableTag)
547
+ vhvar = VHVAR.table = tableClass()
548
+ vhvar.Version = 0x00010000
549
+
550
+ vhAdvanceDeltasAndSupports, vOrigDeltasAndSupports = getAdvanceMetrics()
551
+
552
+ if vOrigDeltasAndSupports:
553
+ singleModel = False
554
+ else:
555
+ singleModel = models.allEqual(
556
+ id(v[1]) for v in vhAdvanceDeltasAndSupports.values()
557
+ )
558
+
559
+ directStore = None
560
+ if singleModel:
561
+ # Build direct mapping
562
+ supports = next(iter(vhAdvanceDeltasAndSupports.values()))[1][1:]
563
+ varTupleList = builder.buildVarRegionList(supports, axisTags)
564
+ varTupleIndexes = list(range(len(supports)))
565
+ varData = builder.buildVarData(varTupleIndexes, [], optimize=False)
566
+ for glyphName in glyphOrder:
567
+ varData.addItem(vhAdvanceDeltasAndSupports[glyphName][0], round=noRound)
568
+ varData.optimize()
569
+ directStore = builder.buildVarStore(varTupleList, [varData])
570
+ # remove unused regions from VarRegionList
571
+ directStore.prune_regions()
572
+
573
+ # Build optimized indirect mapping
574
+ storeBuilder = varStore.OnlineVarStoreBuilder(axisTags)
575
+ advMapping = {}
576
+ for glyphName in glyphOrder:
577
+ deltas, supports = vhAdvanceDeltasAndSupports[glyphName]
578
+ storeBuilder.setSupports(supports)
579
+ advMapping[glyphName] = storeBuilder.storeDeltas(deltas, round=noRound)
580
+
581
+ if vOrigDeltasAndSupports:
582
+ vOrigMap = {}
583
+ for glyphName in glyphOrder:
584
+ deltas, supports = vOrigDeltasAndSupports[glyphName]
585
+ storeBuilder.setSupports(supports)
586
+ vOrigMap[glyphName] = storeBuilder.storeDeltas(deltas, round=noRound)
587
+
588
+ indirectStore = storeBuilder.finish()
589
+ mapping2 = indirectStore.optimize(use_NO_VARIATION_INDEX=False)
590
+ advMapping = [mapping2[advMapping[g]] for g in glyphOrder]
591
+ advanceMapping = builder.buildVarIdxMap(advMapping, glyphOrder)
592
+
593
+ if vOrigDeltasAndSupports:
594
+ vOrigMap = [mapping2[vOrigMap[g]] for g in glyphOrder]
595
+
596
+ useDirect = False
597
+ vOrigMapping = None
598
+ if directStore:
599
+ # Compile both, see which is more compact
600
+
601
+ writer = OTTableWriter()
602
+ directStore.compile(writer, font)
603
+ directSize = len(writer.getAllData())
604
+
605
+ writer = OTTableWriter()
606
+ indirectStore.compile(writer, font)
607
+ advanceMapping.compile(writer, font)
608
+ indirectSize = len(writer.getAllData())
609
+
610
+ useDirect = directSize < indirectSize
611
+
612
+ if useDirect:
613
+ metricsStore = directStore
614
+ advanceMapping = None
615
+ else:
616
+ metricsStore = indirectStore
617
+ if vOrigDeltasAndSupports:
618
+ vOrigMapping = builder.buildVarIdxMap(vOrigMap, glyphOrder)
619
+
620
+ vhvar.VarStore = metricsStore
621
+ setattr(vhvar, tableFields.advMapping, advanceMapping)
622
+ if vOrigMapping is not None:
623
+ setattr(vhvar, tableFields.vOrigMapping, vOrigMapping)
624
+ setattr(vhvar, tableFields.sb1, None)
625
+ setattr(vhvar, tableFields.sb2, None)
626
+
627
+ font[tableTag] = VHVAR
628
+ return
629
+
630
+
631
+ def _get_advance_metrics(font, masterModel, master_ttfs, axisTags, tableFields):
632
+ tableTag = tableFields.tableTag
633
+ glyphOrder = font.getGlyphOrder()
634
+
635
+ # Build list of source font advance widths for each glyph
636
+ metricsTag = tableFields.metricsTag
637
+ advMetricses = [m[metricsTag].metrics for m in master_ttfs]
638
+
639
+ # Build list of source font vertical origin coords for each glyph
640
+ if tableTag == "VVAR" and "VORG" in master_ttfs[0]:
641
+ vOrigMetricses = [m["VORG"].VOriginRecords for m in master_ttfs]
642
+ defaultYOrigs = [m["VORG"].defaultVertOriginY for m in master_ttfs]
643
+ vOrigMetricses = list(zip(vOrigMetricses, defaultYOrigs))
644
+ else:
645
+ vOrigMetricses = None
646
+
647
+ vhAdvanceDeltasAndSupports = {}
648
+ vOrigDeltasAndSupports = {}
649
+ # HACK: we treat width 65535 as a sentinel value to signal that a glyph
650
+ # from a non-default master should not participate in computing {H,V}VAR,
651
+ # as if it were missing. Allows to variate other glyph-related data independently
652
+ # from glyph metrics
653
+ sparse_advance = 0xFFFF
654
+ for glyph in glyphOrder:
655
+ vhAdvances = [
656
+ (
657
+ metrics[glyph][0]
658
+ if glyph in metrics and metrics[glyph][0] != sparse_advance
659
+ else None
660
+ )
661
+ for metrics in advMetricses
662
+ ]
663
+ vhAdvanceDeltasAndSupports[glyph] = masterModel.getDeltasAndSupports(
664
+ vhAdvances, round=round
665
+ )
666
+
667
+ if vOrigMetricses:
668
+ for glyph in glyphOrder:
669
+ # We need to supply a vOrigs tuple with non-None default values
670
+ # for each glyph. vOrigMetricses contains values only for those
671
+ # glyphs which have a non-default vOrig.
672
+ vOrigs = [
673
+ metrics[glyph] if glyph in metrics else defaultVOrig
674
+ for metrics, defaultVOrig in vOrigMetricses
675
+ ]
676
+ vOrigDeltasAndSupports[glyph] = masterModel.getDeltasAndSupports(
677
+ vOrigs, round=round
678
+ )
679
+
680
+ return vhAdvanceDeltasAndSupports, vOrigDeltasAndSupports
681
+
682
+
683
+ def _add_MVAR(font, masterModel, master_ttfs, axisTags):
684
+ log.info("Generating MVAR")
685
+
686
+ store_builder = varStore.OnlineVarStoreBuilder(axisTags)
687
+
688
+ records = []
689
+ lastTableTag = None
690
+ fontTable = None
691
+ tables = None
692
+ # HACK: we need to special-case post.underlineThickness and .underlinePosition
693
+ # and unilaterally/arbitrarily define a sentinel value to distinguish the case
694
+ # when a post table is present in a given master simply because that's where
695
+ # the glyph names in TrueType must be stored, but the underline values are not
696
+ # meant to be used for building MVAR's deltas. The value of -0x8000 (-36768)
697
+ # the minimum FWord (int16) value, was chosen for its unlikelyhood to appear
698
+ # in real-world underline position/thickness values.
699
+ specialTags = {"unds": -0x8000, "undo": -0x8000}
700
+
701
+ for tag, (tableTag, itemName) in sorted(MVAR_ENTRIES.items(), key=lambda kv: kv[1]):
702
+ # For each tag, fetch the associated table from all fonts (or not when we are
703
+ # still looking at a tag from the same tables) and set up the variation model
704
+ # for them.
705
+ if tableTag != lastTableTag:
706
+ tables = fontTable = None
707
+ if tableTag in font:
708
+ fontTable = font[tableTag]
709
+ tables = []
710
+ for master in master_ttfs:
711
+ if tableTag not in master or (
712
+ tag in specialTags
713
+ and getattr(master[tableTag], itemName) == specialTags[tag]
714
+ ):
715
+ tables.append(None)
716
+ else:
717
+ tables.append(master[tableTag])
718
+ model, tables = masterModel.getSubModel(tables)
719
+ store_builder.setModel(model)
720
+ lastTableTag = tableTag
721
+
722
+ if tables is None: # Tag not applicable to the master font.
723
+ continue
724
+
725
+ # TODO support gasp entries
726
+
727
+ master_values = [getattr(table, itemName) for table in tables]
728
+ if models.allEqual(master_values):
729
+ base, varIdx = master_values[0], None
730
+ else:
731
+ base, varIdx = store_builder.storeMasters(master_values)
732
+ setattr(fontTable, itemName, base)
733
+
734
+ if varIdx is None:
735
+ continue
736
+ log.info(" %s: %s.%s %s", tag, tableTag, itemName, master_values)
737
+ rec = ot.MetricsValueRecord()
738
+ rec.ValueTag = tag
739
+ rec.VarIdx = varIdx
740
+ records.append(rec)
741
+
742
+ assert "MVAR" not in font
743
+ if records:
744
+ store = store_builder.finish()
745
+ # Optimize
746
+ mapping = store.optimize()
747
+ for rec in records:
748
+ rec.VarIdx = mapping[rec.VarIdx]
749
+
750
+ MVAR = font["MVAR"] = newTable("MVAR")
751
+ mvar = MVAR.table = ot.MVAR()
752
+ mvar.Version = 0x00010000
753
+ mvar.Reserved = 0
754
+ mvar.VarStore = store
755
+ # XXX these should not be hard-coded but computed automatically
756
+ mvar.ValueRecordSize = 8
757
+ mvar.ValueRecordCount = len(records)
758
+ mvar.ValueRecord = sorted(records, key=lambda r: r.ValueTag)
759
+
760
+
761
+ def _add_BASE(font, masterModel, master_ttfs, axisTags):
762
+ log.info("Generating BASE")
763
+
764
+ merger = VariationMerger(masterModel, axisTags, font)
765
+ merger.mergeTables(font, master_ttfs, ["BASE"])
766
+ store = merger.store_builder.finish()
767
+
768
+ if not store:
769
+ return
770
+ base = font["BASE"].table
771
+ assert base.Version == 0x00010000
772
+ base.Version = 0x00010001
773
+ base.VarStore = store
774
+
775
+
776
+ def _merge_OTL(font, model, master_fonts, axisTags):
777
+ otl_tags = ["GSUB", "GDEF", "GPOS"]
778
+ if not any(tag in font for tag in otl_tags):
779
+ return
780
+
781
+ log.info("Merging OpenType Layout tables")
782
+ merger = VariationMerger(model, axisTags, font)
783
+
784
+ merger.mergeTables(font, master_fonts, otl_tags)
785
+ store = merger.store_builder.finish()
786
+ if not store:
787
+ return
788
+ try:
789
+ GDEF = font["GDEF"].table
790
+ assert GDEF.Version <= 0x00010002
791
+ except KeyError:
792
+ font["GDEF"] = newTable("GDEF")
793
+ GDEFTable = font["GDEF"] = newTable("GDEF")
794
+ GDEF = GDEFTable.table = ot.GDEF()
795
+ GDEF.GlyphClassDef = None
796
+ GDEF.AttachList = None
797
+ GDEF.LigCaretList = None
798
+ GDEF.MarkAttachClassDef = None
799
+ GDEF.MarkGlyphSetsDef = None
800
+
801
+ GDEF.Version = 0x00010003
802
+ GDEF.VarStore = store
803
+
804
+ # Optimize
805
+ varidx_map = store.optimize()
806
+ GDEF.remap_device_varidxes(varidx_map)
807
+ if "GPOS" in font:
808
+ font["GPOS"].table.remap_device_varidxes(varidx_map)
809
+
810
+
811
+ def _add_GSUB_feature_variations(
812
+ font, axes, internal_axis_supports, rules, featureTags
813
+ ):
814
+ def normalize(name, value):
815
+ return models.normalizeLocation({name: value}, internal_axis_supports)[name]
816
+
817
+ log.info("Generating GSUB FeatureVariations")
818
+
819
+ axis_tags = {name: axis.tag for name, axis in axes.items()}
820
+
821
+ conditional_subs = []
822
+ for rule in rules:
823
+ region = []
824
+ for conditions in rule.conditionSets:
825
+ space = {}
826
+ for condition in conditions:
827
+ axis_name = condition["name"]
828
+ if condition["minimum"] is not None:
829
+ minimum = normalize(axis_name, condition["minimum"])
830
+ else:
831
+ minimum = -1.0
832
+ if condition["maximum"] is not None:
833
+ maximum = normalize(axis_name, condition["maximum"])
834
+ else:
835
+ maximum = 1.0
836
+ tag = axis_tags[axis_name]
837
+ space[tag] = (minimum, maximum)
838
+ region.append(space)
839
+
840
+ subs = {k: v for k, v in rule.subs}
841
+
842
+ conditional_subs.append((region, subs))
843
+
844
+ addFeatureVariations(font, conditional_subs, featureTags)
845
+
846
+
847
+ _DesignSpaceData = namedtuple(
848
+ "_DesignSpaceData",
849
+ [
850
+ "axes",
851
+ "axisMappings",
852
+ "internal_axis_supports",
853
+ "base_idx",
854
+ "normalized_master_locs",
855
+ "masters",
856
+ "instances",
857
+ "rules",
858
+ "rulesProcessingLast",
859
+ "lib",
860
+ ],
861
+ )
862
+
863
+
864
+ def _add_CFF2(varFont, model, master_fonts):
865
+ from .cff import merge_region_fonts
866
+
867
+ glyphOrder = varFont.getGlyphOrder()
868
+ if "CFF2" not in varFont:
869
+ from fontTools.cffLib.CFFToCFF2 import convertCFFToCFF2
870
+
871
+ convertCFFToCFF2(varFont)
872
+
873
+ ordered_fonts_list = model.reorderMasters(master_fonts, model.reverseMapping)
874
+ # re-ordering the master list simplifies building the CFF2 data item lists.
875
+ merge_region_fonts(varFont, model, ordered_fonts_list, glyphOrder)
876
+
877
+
878
+ def _add_COLR(font, model, master_fonts, axisTags, colr_layer_reuse=True):
879
+ merger = COLRVariationMerger(
880
+ model, axisTags, font, allowLayerReuse=colr_layer_reuse
881
+ )
882
+ merger.mergeTables(font, master_fonts)
883
+ store = merger.store_builder.finish()
884
+
885
+ colr = font["COLR"].table
886
+ if store:
887
+ mapping = store.optimize()
888
+ colr.VarStore = store
889
+ varIdxes = [mapping[v] for v in merger.varIdxes]
890
+ colr.VarIndexMap = builder.buildDeltaSetIndexMap(varIdxes)
891
+
892
+
893
+ def load_designspace(designspace, log_enabled=True, *, require_sources=True):
894
+ # TODO: remove this and always assume 'designspace' is a DesignSpaceDocument,
895
+ # never a file path, as that's already handled by caller
896
+ if hasattr(designspace, "sources"): # Assume a DesignspaceDocument
897
+ ds = designspace
898
+ else: # Assume a file path
899
+ ds = DesignSpaceDocument.fromfile(designspace)
900
+
901
+ masters = ds.sources
902
+ if require_sources and not masters:
903
+ raise VarLibValidationError("Designspace must have at least one source.")
904
+ instances = ds.instances
905
+
906
+ # TODO: Use fontTools.designspaceLib.tagForAxisName instead.
907
+ standard_axis_map = OrderedDict(
908
+ [
909
+ ("weight", ("wght", {"en": "Weight"})),
910
+ ("width", ("wdth", {"en": "Width"})),
911
+ ("slant", ("slnt", {"en": "Slant"})),
912
+ ("optical", ("opsz", {"en": "Optical Size"})),
913
+ ("italic", ("ital", {"en": "Italic"})),
914
+ ]
915
+ )
916
+
917
+ # Setup axes
918
+ if not ds.axes:
919
+ raise VarLibValidationError(f"Designspace must have at least one axis.")
920
+
921
+ axes = OrderedDict()
922
+ for axis_index, axis in enumerate(ds.axes):
923
+ axis_name = axis.name
924
+ if not axis_name:
925
+ if not axis.tag:
926
+ raise VarLibValidationError(f"Axis at index {axis_index} needs a tag.")
927
+ axis_name = axis.name = axis.tag
928
+
929
+ if axis_name in standard_axis_map:
930
+ if axis.tag is None:
931
+ axis.tag = standard_axis_map[axis_name][0]
932
+ if not axis.labelNames:
933
+ axis.labelNames.update(standard_axis_map[axis_name][1])
934
+ else:
935
+ if not axis.tag:
936
+ raise VarLibValidationError(f"Axis at index {axis_index} needs a tag.")
937
+ if not axis.labelNames:
938
+ axis.labelNames["en"] = tostr(axis_name)
939
+
940
+ axes[axis_name] = axis
941
+ if log_enabled:
942
+ log.info("Axes:\n%s", pformat([axis.asdict() for axis in axes.values()]))
943
+
944
+ axisMappings = ds.axisMappings
945
+ if axisMappings and log_enabled:
946
+ log.info("Mappings:\n%s", pformat(axisMappings))
947
+
948
+ # Check all master and instance locations are valid and fill in defaults
949
+ for obj in masters + instances:
950
+ obj_name = obj.name or obj.styleName or ""
951
+ loc = obj.getFullDesignLocation(ds)
952
+ obj.designLocation = loc
953
+ if loc is None:
954
+ raise VarLibValidationError(
955
+ f"Source or instance '{obj_name}' has no location."
956
+ )
957
+ for axis_name in loc.keys():
958
+ if axis_name not in axes:
959
+ raise VarLibValidationError(
960
+ f"Location axis '{axis_name}' unknown for '{obj_name}'."
961
+ )
962
+ for axis_name, axis in axes.items():
963
+ v = axis.map_backward(loc[axis_name])
964
+ if not (axis.minimum <= v <= axis.maximum):
965
+ raise VarLibValidationError(
966
+ f"Source or instance '{obj_name}' has out-of-range location "
967
+ f"for axis '{axis_name}': is mapped to {v} but must be in "
968
+ f"mapped range [{axis.minimum}..{axis.maximum}] (NOTE: all "
969
+ "values are in user-space)."
970
+ )
971
+
972
+ # Normalize master locations
973
+
974
+ internal_master_locs = [o.getFullDesignLocation(ds) for o in masters]
975
+ if log_enabled:
976
+ log.info("Internal master locations:\n%s", pformat(internal_master_locs))
977
+
978
+ # TODO This mapping should ideally be moved closer to logic in _add_fvar/avar
979
+ internal_axis_supports = {}
980
+ for axis in axes.values():
981
+ triple = (axis.minimum, axis.default, axis.maximum)
982
+ internal_axis_supports[axis.name] = [axis.map_forward(v) for v in triple]
983
+ if log_enabled:
984
+ log.info("Internal axis supports:\n%s", pformat(internal_axis_supports))
985
+
986
+ normalized_master_locs = [
987
+ models.normalizeLocation(m, internal_axis_supports)
988
+ for m in internal_master_locs
989
+ ]
990
+ if log_enabled:
991
+ log.info("Normalized master locations:\n%s", pformat(normalized_master_locs))
992
+
993
+ # Find base master
994
+ base_idx = None
995
+ for i, m in enumerate(normalized_master_locs):
996
+ if all(v == 0 for v in m.values()):
997
+ if base_idx is not None:
998
+ raise VarLibValidationError(
999
+ "More than one base master found in Designspace."
1000
+ )
1001
+ base_idx = i
1002
+ if require_sources and base_idx is None:
1003
+ raise VarLibValidationError(
1004
+ "Base master not found; no master at default location?"
1005
+ )
1006
+ if log_enabled:
1007
+ log.info("Index of base master: %s", base_idx)
1008
+
1009
+ return _DesignSpaceData(
1010
+ axes,
1011
+ axisMappings,
1012
+ internal_axis_supports,
1013
+ base_idx,
1014
+ normalized_master_locs,
1015
+ masters,
1016
+ instances,
1017
+ ds.rules,
1018
+ ds.rulesProcessingLast,
1019
+ ds.lib,
1020
+ )
1021
+
1022
+
1023
+ # https://docs.microsoft.com/en-us/typography/opentype/spec/os2#uswidthclass
1024
+ WDTH_VALUE_TO_OS2_WIDTH_CLASS = {
1025
+ 50: 1,
1026
+ 62.5: 2,
1027
+ 75: 3,
1028
+ 87.5: 4,
1029
+ 100: 5,
1030
+ 112.5: 6,
1031
+ 125: 7,
1032
+ 150: 8,
1033
+ 200: 9,
1034
+ }
1035
+
1036
+
1037
+ def set_default_weight_width_slant(font, location):
1038
+ if "OS/2" in font:
1039
+ if "wght" in location:
1040
+ weight_class = otRound(max(1, min(location["wght"], 1000)))
1041
+ if font["OS/2"].usWeightClass != weight_class:
1042
+ log.info("Setting OS/2.usWeightClass = %s", weight_class)
1043
+ font["OS/2"].usWeightClass = weight_class
1044
+
1045
+ if "wdth" in location:
1046
+ # map 'wdth' axis (50..200) to OS/2.usWidthClass (1..9), rounding to closest
1047
+ widthValue = min(max(location["wdth"], 50), 200)
1048
+ widthClass = otRound(
1049
+ models.piecewiseLinearMap(widthValue, WDTH_VALUE_TO_OS2_WIDTH_CLASS)
1050
+ )
1051
+ if font["OS/2"].usWidthClass != widthClass:
1052
+ log.info("Setting OS/2.usWidthClass = %s", widthClass)
1053
+ font["OS/2"].usWidthClass = widthClass
1054
+
1055
+ if "slnt" in location and "post" in font:
1056
+ italicAngle = max(-90, min(location["slnt"], 90))
1057
+ if font["post"].italicAngle != italicAngle:
1058
+ log.info("Setting post.italicAngle = %s", italicAngle)
1059
+ font["post"].italicAngle = italicAngle
1060
+
1061
+
1062
+ def drop_implied_oncurve_points(*masters: TTFont) -> int:
1063
+ """Drop impliable on-curve points from all the simple glyphs in masters.
1064
+
1065
+ In TrueType glyf outlines, on-curve points can be implied when they are located
1066
+ exactly at the midpoint of the line connecting two consecutive off-curve points.
1067
+
1068
+ The input masters' glyf tables are assumed to contain same-named glyphs that are
1069
+ interpolatable. Oncurve points are only dropped if they can be implied for all
1070
+ the masters. The fonts are modified in-place.
1071
+
1072
+ Args:
1073
+ masters: The TTFont(s) to modify
1074
+
1075
+ Returns:
1076
+ The total number of points that were dropped if any.
1077
+
1078
+ Reference:
1079
+ https://developer.apple.com/fonts/TrueType-Reference-Manual/RM01/Chap1.html
1080
+ """
1081
+
1082
+ count = 0
1083
+ glyph_masters = defaultdict(list)
1084
+ # multiple DS source may point to the same TTFont object and we want to
1085
+ # avoid processing the same glyph twice as they are modified in-place
1086
+ for font in {id(m): m for m in masters}.values():
1087
+ glyf = font["glyf"]
1088
+ for glyphName in glyf.keys():
1089
+ glyph_masters[glyphName].append(glyf[glyphName])
1090
+ count = 0
1091
+ for glyphName, glyphs in glyph_masters.items():
1092
+ try:
1093
+ dropped = dropImpliedOnCurvePoints(*glyphs)
1094
+ except ValueError as e:
1095
+ # we don't fail for incompatible glyphs in _add_gvar so we shouldn't here
1096
+ log.warning("Failed to drop implied oncurves for %r: %s", glyphName, e)
1097
+ else:
1098
+ count += len(dropped)
1099
+ return count
1100
+
1101
+
1102
+ def build_many(
1103
+ designspace: DesignSpaceDocument,
1104
+ master_finder=lambda s: s,
1105
+ exclude=[],
1106
+ optimize=True,
1107
+ skip_vf=lambda vf_name: False,
1108
+ colr_layer_reuse=True,
1109
+ drop_implied_oncurves=False,
1110
+ ):
1111
+ """
1112
+ Build variable fonts from a designspace file, version 5 which can define
1113
+ several VFs, or version 4 which has implicitly one VF covering the whole doc.
1114
+
1115
+ If master_finder is set, it should be a callable that takes master
1116
+ filename as found in designspace file and map it to master font
1117
+ binary as to be opened (eg. .ttf or .otf).
1118
+
1119
+ skip_vf can be used to skip building some of the variable fonts defined in
1120
+ the input designspace. It's a predicate that takes as argument the name
1121
+ of the variable font and returns `bool`.
1122
+
1123
+ Always returns a Dict[str, TTFont] keyed by VariableFontDescriptor.name
1124
+ """
1125
+ res = {}
1126
+ # varLib.build (used further below) by default only builds an incomplete 'STAT'
1127
+ # with an empty AxisValueArray--unless the VF inherited 'STAT' from its base master.
1128
+ # Designspace version 5 can also be used to define 'STAT' labels or customize
1129
+ # axes ordering, etc. To avoid overwriting a pre-existing 'STAT' or redoing the
1130
+ # same work twice, here we check if designspace contains any 'STAT' info before
1131
+ # proceeding to call buildVFStatTable for each VF.
1132
+ # https://github.com/fonttools/fonttools/pull/3024
1133
+ # https://github.com/fonttools/fonttools/issues/3045
1134
+ doBuildStatFromDSv5 = (
1135
+ "STAT" not in exclude
1136
+ and designspace.formatTuple >= (5, 0)
1137
+ and (
1138
+ any(a.axisLabels or a.axisOrdering is not None for a in designspace.axes)
1139
+ or designspace.locationLabels
1140
+ )
1141
+ )
1142
+ for _location, subDoc in splitInterpolable(designspace):
1143
+ for name, vfDoc in splitVariableFonts(subDoc):
1144
+ if skip_vf(name):
1145
+ log.debug(f"Skipping variable TTF font: {name}")
1146
+ continue
1147
+ vf = build(
1148
+ vfDoc,
1149
+ master_finder,
1150
+ exclude=exclude,
1151
+ optimize=optimize,
1152
+ colr_layer_reuse=colr_layer_reuse,
1153
+ drop_implied_oncurves=drop_implied_oncurves,
1154
+ )[0]
1155
+ if doBuildStatFromDSv5:
1156
+ buildVFStatTable(vf, designspace, name)
1157
+ res[name] = vf
1158
+ return res
1159
+
1160
+
1161
+ def build(
1162
+ designspace,
1163
+ master_finder=lambda s: s,
1164
+ exclude=[],
1165
+ optimize=True,
1166
+ colr_layer_reuse=True,
1167
+ drop_implied_oncurves=False,
1168
+ ):
1169
+ """
1170
+ Build variation font from a designspace file.
1171
+
1172
+ If master_finder is set, it should be a callable that takes master
1173
+ filename as found in designspace file and map it to master font
1174
+ binary as to be opened (eg. .ttf or .otf).
1175
+ """
1176
+ if hasattr(designspace, "sources"): # Assume a DesignspaceDocument
1177
+ pass
1178
+ else: # Assume a file path
1179
+ designspace = DesignSpaceDocument.fromfile(designspace)
1180
+
1181
+ ds = load_designspace(designspace)
1182
+ log.info("Building variable font")
1183
+
1184
+ log.info("Loading master fonts")
1185
+ master_fonts = load_masters(designspace, master_finder)
1186
+
1187
+ # TODO: 'master_ttfs' is unused except for return value, remove later
1188
+ master_ttfs = []
1189
+ for master in master_fonts:
1190
+ try:
1191
+ master_ttfs.append(master.reader.file.name)
1192
+ except AttributeError:
1193
+ master_ttfs.append(None) # in-memory fonts have no path
1194
+
1195
+ if drop_implied_oncurves and "glyf" in master_fonts[ds.base_idx]:
1196
+ drop_count = drop_implied_oncurve_points(*master_fonts)
1197
+ log.info(
1198
+ "Dropped %s on-curve points from simple glyphs in the 'glyf' table",
1199
+ drop_count,
1200
+ )
1201
+
1202
+ # Copy the base master to work from it
1203
+ vf = deepcopy(master_fonts[ds.base_idx])
1204
+
1205
+ if "DSIG" in vf:
1206
+ del vf["DSIG"]
1207
+
1208
+ # TODO append masters as named-instances as well; needs .designspace change.
1209
+ fvar = _add_fvar(vf, ds.axes, ds.instances)
1210
+ if "STAT" not in exclude:
1211
+ _add_stat(vf)
1212
+
1213
+ # Map from axis names to axis tags...
1214
+ normalized_master_locs = [
1215
+ {ds.axes[k].tag: v for k, v in loc.items()} for loc in ds.normalized_master_locs
1216
+ ]
1217
+ # From here on, we use fvar axes only
1218
+ axisTags = [axis.axisTag for axis in fvar.axes]
1219
+
1220
+ # Assume single-model for now.
1221
+ model = models.VariationModel(normalized_master_locs, axisOrder=axisTags)
1222
+ assert 0 == model.mapping[ds.base_idx]
1223
+
1224
+ log.info("Building variations tables")
1225
+ if "avar" not in exclude:
1226
+ _add_avar(vf, ds.axes, ds.axisMappings, axisTags)
1227
+ if "BASE" not in exclude and "BASE" in vf:
1228
+ _add_BASE(vf, model, master_fonts, axisTags)
1229
+ if "MVAR" not in exclude:
1230
+ _add_MVAR(vf, model, master_fonts, axisTags)
1231
+ if "HVAR" not in exclude:
1232
+ _add_HVAR(vf, model, master_fonts, axisTags)
1233
+ if "VVAR" not in exclude and "vmtx" in vf:
1234
+ _add_VVAR(vf, model, master_fonts, axisTags)
1235
+ if "GDEF" not in exclude or "GPOS" not in exclude:
1236
+ _merge_OTL(vf, model, master_fonts, axisTags)
1237
+ if "gvar" not in exclude and "glyf" in vf:
1238
+ _add_gvar(vf, model, master_fonts, optimize=optimize)
1239
+ if "cvar" not in exclude and "glyf" in vf:
1240
+ _merge_TTHinting(vf, model, master_fonts)
1241
+ if "GSUB" not in exclude and ds.rules:
1242
+ featureTags = _feature_variations_tags(ds)
1243
+ _add_GSUB_feature_variations(
1244
+ vf, ds.axes, ds.internal_axis_supports, ds.rules, featureTags
1245
+ )
1246
+ if "CFF2" not in exclude and ("CFF " in vf or "CFF2" in vf):
1247
+ _add_CFF2(vf, model, master_fonts)
1248
+ if "post" in vf:
1249
+ # set 'post' to format 2 to keep the glyph names dropped from CFF2
1250
+ post = vf["post"]
1251
+ if post.formatType != 2.0:
1252
+ post.formatType = 2.0
1253
+ post.extraNames = []
1254
+ post.mapping = {}
1255
+ if "COLR" not in exclude and "COLR" in vf and vf["COLR"].version > 0:
1256
+ _add_COLR(vf, model, master_fonts, axisTags, colr_layer_reuse)
1257
+
1258
+ set_default_weight_width_slant(
1259
+ vf, location={axis.axisTag: axis.defaultValue for axis in vf["fvar"].axes}
1260
+ )
1261
+
1262
+ for tag in exclude:
1263
+ if tag in vf:
1264
+ del vf[tag]
1265
+
1266
+ # TODO: Only return vf for 4.0+, the rest is unused.
1267
+ return vf, model, master_ttfs
1268
+
1269
+
1270
+ def _open_font(path, master_finder=lambda s: s):
1271
+ # load TTFont masters from given 'path': this can be either a .TTX or an
1272
+ # OpenType binary font; or if neither of these, try use the 'master_finder'
1273
+ # callable to resolve the path to a valid .TTX or OpenType font binary.
1274
+ from fontTools.ttx import guessFileType
1275
+
1276
+ master_path = os.path.normpath(path)
1277
+ tp = guessFileType(master_path)
1278
+ if tp is None:
1279
+ # not an OpenType binary/ttx, fall back to the master finder.
1280
+ master_path = master_finder(master_path)
1281
+ tp = guessFileType(master_path)
1282
+ if tp in ("TTX", "OTX"):
1283
+ font = TTFont()
1284
+ font.importXML(master_path)
1285
+ elif tp in ("TTF", "OTF", "WOFF", "WOFF2"):
1286
+ font = TTFont(master_path)
1287
+ else:
1288
+ raise VarLibValidationError("Invalid master path: %r" % master_path)
1289
+ return font
1290
+
1291
+
1292
+ def load_masters(designspace, master_finder=lambda s: s):
1293
+ """Ensure that all SourceDescriptor.font attributes have an appropriate TTFont
1294
+ object loaded, or else open TTFont objects from the SourceDescriptor.path
1295
+ attributes.
1296
+
1297
+ The paths can point to either an OpenType font, a TTX file, or a UFO. In the
1298
+ latter case, use the provided master_finder callable to map from UFO paths to
1299
+ the respective master font binaries (e.g. .ttf, .otf or .ttx).
1300
+
1301
+ Return list of master TTFont objects in the same order they are listed in the
1302
+ DesignSpaceDocument.
1303
+ """
1304
+ for master in designspace.sources:
1305
+ # If a SourceDescriptor has a layer name, demand that the compiled TTFont
1306
+ # be supplied by the caller. This spares us from modifying MasterFinder.
1307
+ if master.layerName and master.font is None:
1308
+ raise VarLibValidationError(
1309
+ f"Designspace source '{master.name or '<Unknown>'}' specified a "
1310
+ "layer name but lacks the required TTFont object in the 'font' "
1311
+ "attribute."
1312
+ )
1313
+
1314
+ return designspace.loadSourceFonts(_open_font, master_finder=master_finder)
1315
+
1316
+
1317
+ class MasterFinder(object):
1318
+ def __init__(self, template):
1319
+ self.template = template
1320
+
1321
+ def __call__(self, src_path):
1322
+ fullname = os.path.abspath(src_path)
1323
+ dirname, basename = os.path.split(fullname)
1324
+ stem, ext = os.path.splitext(basename)
1325
+ path = self.template.format(
1326
+ fullname=fullname,
1327
+ dirname=dirname,
1328
+ basename=basename,
1329
+ stem=stem,
1330
+ ext=ext,
1331
+ )
1332
+ return os.path.normpath(path)
1333
+
1334
+
1335
+ def _feature_variations_tags(ds):
1336
+ raw_tags = ds.lib.get(
1337
+ FEAVAR_FEATURETAG_LIB_KEY,
1338
+ "rclt" if ds.rulesProcessingLast else "rvrn",
1339
+ )
1340
+ return sorted({t.strip() for t in raw_tags.split(",")})
1341
+
1342
+
1343
+ def addGSUBFeatureVariations(vf, designspace, featureTags=(), *, log_enabled=False):
1344
+ """Add GSUB FeatureVariations table to variable font, based on DesignSpace rules.
1345
+
1346
+ Args:
1347
+ vf: A TTFont object representing the variable font.
1348
+ designspace: A DesignSpaceDocument object.
1349
+ featureTags: Optional feature tag(s) to use for the FeatureVariations records.
1350
+ If unset, the key 'com.github.fonttools.varLib.featureVarsFeatureTag' is
1351
+ looked up in the DS <lib> and used; otherwise the default is 'rclt' if
1352
+ the <rules processing="last"> attribute is set, else 'rvrn'.
1353
+ See <https://fonttools.readthedocs.io/en/latest/designspaceLib/xml.html#rules-element>
1354
+ log_enabled: If True, log info about DS axes and sources. Default is False, as
1355
+ the same info may have already been logged as part of varLib.build.
1356
+ """
1357
+ ds = load_designspace(designspace, log_enabled=log_enabled)
1358
+ if not ds.rules:
1359
+ return
1360
+ if not featureTags:
1361
+ featureTags = _feature_variations_tags(ds)
1362
+ _add_GSUB_feature_variations(
1363
+ vf, ds.axes, ds.internal_axis_supports, ds.rules, featureTags
1364
+ )
1365
+
1366
+
1367
+ def main(args=None):
1368
+ """Build variable fonts from a designspace file and masters"""
1369
+ from argparse import ArgumentParser
1370
+ from fontTools import configLogger
1371
+
1372
+ parser = ArgumentParser(prog="varLib", description=main.__doc__)
1373
+ parser.add_argument("designspace")
1374
+ output_group = parser.add_mutually_exclusive_group()
1375
+ output_group.add_argument(
1376
+ "-o", metavar="OUTPUTFILE", dest="outfile", default=None, help="output file"
1377
+ )
1378
+ output_group.add_argument(
1379
+ "-d",
1380
+ "--output-dir",
1381
+ metavar="OUTPUTDIR",
1382
+ default=None,
1383
+ help="output dir (default: same as input designspace file)",
1384
+ )
1385
+ parser.add_argument(
1386
+ "-x",
1387
+ metavar="TAG",
1388
+ dest="exclude",
1389
+ action="append",
1390
+ default=[],
1391
+ help="exclude table",
1392
+ )
1393
+ parser.add_argument(
1394
+ "--disable-iup",
1395
+ dest="optimize",
1396
+ action="store_false",
1397
+ help="do not perform IUP optimization",
1398
+ )
1399
+ parser.add_argument(
1400
+ "--no-colr-layer-reuse",
1401
+ dest="colr_layer_reuse",
1402
+ action="store_false",
1403
+ help="do not rebuild variable COLR table to optimize COLR layer reuse",
1404
+ )
1405
+ parser.add_argument(
1406
+ "--drop-implied-oncurves",
1407
+ action="store_true",
1408
+ help=(
1409
+ "drop on-curve points that can be implied when exactly in the middle of "
1410
+ "two off-curve points (only applies to TrueType fonts)"
1411
+ ),
1412
+ )
1413
+ parser.add_argument(
1414
+ "--master-finder",
1415
+ default="master_ttf_interpolatable/{stem}.ttf",
1416
+ help=(
1417
+ "templated string used for finding binary font "
1418
+ "files given the source file names defined in the "
1419
+ "designspace document. The following special strings "
1420
+ "are defined: {fullname} is the absolute source file "
1421
+ "name; {basename} is the file name without its "
1422
+ "directory; {stem} is the basename without the file "
1423
+ "extension; {ext} is the source file extension; "
1424
+ "{dirname} is the directory of the absolute file "
1425
+ 'name. The default value is "%(default)s".'
1426
+ ),
1427
+ )
1428
+ parser.add_argument(
1429
+ "--variable-fonts",
1430
+ default=".*",
1431
+ metavar="VF_NAME",
1432
+ help=(
1433
+ "Filter the list of variable fonts produced from the input "
1434
+ "Designspace v5 file. By default all listed variable fonts are "
1435
+ "generated. To generate a specific variable font (or variable fonts) "
1436
+ 'that match a given "name" attribute, you can pass as argument '
1437
+ "the full name or a regular expression. E.g.: --variable-fonts "
1438
+ '"MyFontVF_WeightOnly"; or --variable-fonts "MyFontVFItalic_.*".'
1439
+ ),
1440
+ )
1441
+ logging_group = parser.add_mutually_exclusive_group(required=False)
1442
+ logging_group.add_argument(
1443
+ "-v", "--verbose", action="store_true", help="Run more verbosely."
1444
+ )
1445
+ logging_group.add_argument(
1446
+ "-q", "--quiet", action="store_true", help="Turn verbosity off."
1447
+ )
1448
+ options = parser.parse_args(args)
1449
+
1450
+ configLogger(
1451
+ level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
1452
+ )
1453
+
1454
+ designspace_filename = options.designspace
1455
+ designspace = DesignSpaceDocument.fromfile(designspace_filename)
1456
+
1457
+ vf_descriptors = designspace.getVariableFonts()
1458
+ if not vf_descriptors:
1459
+ parser.error(f"No variable fonts in given designspace {designspace.path!r}")
1460
+
1461
+ vfs_to_build = []
1462
+ for vf in vf_descriptors:
1463
+ # Skip variable fonts that do not match the user's inclusion regex if given.
1464
+ if not fullmatch(options.variable_fonts, vf.name):
1465
+ continue
1466
+ vfs_to_build.append(vf)
1467
+
1468
+ if not vfs_to_build:
1469
+ parser.error(f"No variable fonts matching {options.variable_fonts!r}")
1470
+
1471
+ if options.outfile is not None and len(vfs_to_build) > 1:
1472
+ parser.error(
1473
+ "can't specify -o because there are multiple VFs to build; "
1474
+ "use --output-dir, or select a single VF with --variable-fonts"
1475
+ )
1476
+
1477
+ output_dir = options.output_dir
1478
+ if output_dir is None:
1479
+ output_dir = os.path.dirname(designspace_filename)
1480
+
1481
+ vf_name_to_output_path = {}
1482
+ if len(vfs_to_build) == 1 and options.outfile is not None:
1483
+ vf_name_to_output_path[vfs_to_build[0].name] = options.outfile
1484
+ else:
1485
+ for vf in vfs_to_build:
1486
+ filename = vf.filename if vf.filename is not None else vf.name + ".{ext}"
1487
+ vf_name_to_output_path[vf.name] = os.path.join(output_dir, filename)
1488
+
1489
+ finder = MasterFinder(options.master_finder)
1490
+
1491
+ vfs = build_many(
1492
+ designspace,
1493
+ finder,
1494
+ exclude=options.exclude,
1495
+ optimize=options.optimize,
1496
+ colr_layer_reuse=options.colr_layer_reuse,
1497
+ drop_implied_oncurves=options.drop_implied_oncurves,
1498
+ )
1499
+
1500
+ for vf_name, vf in vfs.items():
1501
+ ext = "otf" if vf.sfntVersion == "OTTO" else "ttf"
1502
+ output_path = vf_name_to_output_path[vf_name].format(ext=ext)
1503
+ output_dir = os.path.dirname(output_path)
1504
+ if output_dir:
1505
+ os.makedirs(output_dir, exist_ok=True)
1506
+ log.info("Saving variation font %s", output_path)
1507
+ vf.save(output_path)
1508
+
1509
+
1510
+ if __name__ == "__main__":
1511
+ import sys
1512
+
1513
+ if len(sys.argv) > 1:
1514
+ sys.exit(main())
1515
+ import doctest
1516
+
1517
+ sys.exit(doctest.testmod().failed)