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