fonttools 4.60.2__cp311-cp311-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (353) hide show
  1. fontTools/__init__.py +8 -0
  2. fontTools/__main__.py +35 -0
  3. fontTools/afmLib.py +439 -0
  4. fontTools/agl.py +5233 -0
  5. fontTools/annotations.py +30 -0
  6. fontTools/cffLib/CFF2ToCFF.py +258 -0
  7. fontTools/cffLib/CFFToCFF2.py +305 -0
  8. fontTools/cffLib/__init__.py +3694 -0
  9. fontTools/cffLib/specializer.py +927 -0
  10. fontTools/cffLib/transforms.py +495 -0
  11. fontTools/cffLib/width.py +210 -0
  12. fontTools/colorLib/__init__.py +0 -0
  13. fontTools/colorLib/builder.py +664 -0
  14. fontTools/colorLib/errors.py +2 -0
  15. fontTools/colorLib/geometry.py +143 -0
  16. fontTools/colorLib/table_builder.py +223 -0
  17. fontTools/colorLib/unbuilder.py +81 -0
  18. fontTools/config/__init__.py +90 -0
  19. fontTools/cu2qu/__init__.py +15 -0
  20. fontTools/cu2qu/__main__.py +6 -0
  21. fontTools/cu2qu/benchmark.py +54 -0
  22. fontTools/cu2qu/cli.py +198 -0
  23. fontTools/cu2qu/cu2qu.c +15817 -0
  24. fontTools/cu2qu/cu2qu.cp311-win32.pyd +0 -0
  25. fontTools/cu2qu/cu2qu.py +563 -0
  26. fontTools/cu2qu/errors.py +77 -0
  27. fontTools/cu2qu/ufo.py +363 -0
  28. fontTools/designspaceLib/__init__.py +3343 -0
  29. fontTools/designspaceLib/__main__.py +6 -0
  30. fontTools/designspaceLib/split.py +475 -0
  31. fontTools/designspaceLib/statNames.py +260 -0
  32. fontTools/designspaceLib/types.py +147 -0
  33. fontTools/encodings/MacRoman.py +258 -0
  34. fontTools/encodings/StandardEncoding.py +258 -0
  35. fontTools/encodings/__init__.py +1 -0
  36. fontTools/encodings/codecs.py +135 -0
  37. fontTools/feaLib/__init__.py +4 -0
  38. fontTools/feaLib/__main__.py +78 -0
  39. fontTools/feaLib/ast.py +2143 -0
  40. fontTools/feaLib/builder.py +1814 -0
  41. fontTools/feaLib/error.py +22 -0
  42. fontTools/feaLib/lexer.c +17029 -0
  43. fontTools/feaLib/lexer.cp311-win32.pyd +0 -0
  44. fontTools/feaLib/lexer.py +287 -0
  45. fontTools/feaLib/location.py +12 -0
  46. fontTools/feaLib/lookupDebugInfo.py +12 -0
  47. fontTools/feaLib/parser.py +2394 -0
  48. fontTools/feaLib/variableScalar.py +118 -0
  49. fontTools/fontBuilder.py +1014 -0
  50. fontTools/help.py +36 -0
  51. fontTools/merge/__init__.py +248 -0
  52. fontTools/merge/__main__.py +6 -0
  53. fontTools/merge/base.py +81 -0
  54. fontTools/merge/cmap.py +173 -0
  55. fontTools/merge/layout.py +526 -0
  56. fontTools/merge/options.py +85 -0
  57. fontTools/merge/tables.py +352 -0
  58. fontTools/merge/unicode.py +78 -0
  59. fontTools/merge/util.py +143 -0
  60. fontTools/misc/__init__.py +1 -0
  61. fontTools/misc/arrayTools.py +424 -0
  62. fontTools/misc/bezierTools.c +39731 -0
  63. fontTools/misc/bezierTools.cp311-win32.pyd +0 -0
  64. fontTools/misc/bezierTools.py +1500 -0
  65. fontTools/misc/classifyTools.py +170 -0
  66. fontTools/misc/cliTools.py +53 -0
  67. fontTools/misc/configTools.py +349 -0
  68. fontTools/misc/cython.py +27 -0
  69. fontTools/misc/dictTools.py +83 -0
  70. fontTools/misc/eexec.py +119 -0
  71. fontTools/misc/encodingTools.py +72 -0
  72. fontTools/misc/enumTools.py +23 -0
  73. fontTools/misc/etree.py +456 -0
  74. fontTools/misc/filenames.py +245 -0
  75. fontTools/misc/filesystem/__init__.py +68 -0
  76. fontTools/misc/filesystem/_base.py +134 -0
  77. fontTools/misc/filesystem/_copy.py +45 -0
  78. fontTools/misc/filesystem/_errors.py +54 -0
  79. fontTools/misc/filesystem/_info.py +75 -0
  80. fontTools/misc/filesystem/_osfs.py +164 -0
  81. fontTools/misc/filesystem/_path.py +67 -0
  82. fontTools/misc/filesystem/_subfs.py +92 -0
  83. fontTools/misc/filesystem/_tempfs.py +34 -0
  84. fontTools/misc/filesystem/_tools.py +34 -0
  85. fontTools/misc/filesystem/_walk.py +55 -0
  86. fontTools/misc/filesystem/_zipfs.py +204 -0
  87. fontTools/misc/fixedTools.py +253 -0
  88. fontTools/misc/intTools.py +25 -0
  89. fontTools/misc/iterTools.py +12 -0
  90. fontTools/misc/lazyTools.py +42 -0
  91. fontTools/misc/loggingTools.py +543 -0
  92. fontTools/misc/macCreatorType.py +56 -0
  93. fontTools/misc/macRes.py +261 -0
  94. fontTools/misc/plistlib/__init__.py +681 -0
  95. fontTools/misc/plistlib/py.typed +0 -0
  96. fontTools/misc/psCharStrings.py +1511 -0
  97. fontTools/misc/psLib.py +398 -0
  98. fontTools/misc/psOperators.py +572 -0
  99. fontTools/misc/py23.py +96 -0
  100. fontTools/misc/roundTools.py +110 -0
  101. fontTools/misc/sstruct.py +227 -0
  102. fontTools/misc/symfont.py +242 -0
  103. fontTools/misc/testTools.py +233 -0
  104. fontTools/misc/textTools.py +156 -0
  105. fontTools/misc/timeTools.py +88 -0
  106. fontTools/misc/transform.py +516 -0
  107. fontTools/misc/treeTools.py +45 -0
  108. fontTools/misc/vector.py +147 -0
  109. fontTools/misc/visitor.py +158 -0
  110. fontTools/misc/xmlReader.py +188 -0
  111. fontTools/misc/xmlWriter.py +231 -0
  112. fontTools/mtiLib/__init__.py +1400 -0
  113. fontTools/mtiLib/__main__.py +5 -0
  114. fontTools/otlLib/__init__.py +1 -0
  115. fontTools/otlLib/builder.py +3465 -0
  116. fontTools/otlLib/error.py +11 -0
  117. fontTools/otlLib/maxContextCalc.py +96 -0
  118. fontTools/otlLib/optimize/__init__.py +53 -0
  119. fontTools/otlLib/optimize/__main__.py +6 -0
  120. fontTools/otlLib/optimize/gpos.py +439 -0
  121. fontTools/pens/__init__.py +1 -0
  122. fontTools/pens/areaPen.py +52 -0
  123. fontTools/pens/basePen.py +475 -0
  124. fontTools/pens/boundsPen.py +98 -0
  125. fontTools/pens/cairoPen.py +26 -0
  126. fontTools/pens/cocoaPen.py +26 -0
  127. fontTools/pens/cu2quPen.py +325 -0
  128. fontTools/pens/explicitClosingLinePen.py +101 -0
  129. fontTools/pens/filterPen.py +433 -0
  130. fontTools/pens/freetypePen.py +462 -0
  131. fontTools/pens/hashPointPen.py +89 -0
  132. fontTools/pens/momentsPen.c +13378 -0
  133. fontTools/pens/momentsPen.cp311-win32.pyd +0 -0
  134. fontTools/pens/momentsPen.py +879 -0
  135. fontTools/pens/perimeterPen.py +69 -0
  136. fontTools/pens/pointInsidePen.py +192 -0
  137. fontTools/pens/pointPen.py +643 -0
  138. fontTools/pens/qtPen.py +29 -0
  139. fontTools/pens/qu2cuPen.py +105 -0
  140. fontTools/pens/quartzPen.py +43 -0
  141. fontTools/pens/recordingPen.py +335 -0
  142. fontTools/pens/reportLabPen.py +79 -0
  143. fontTools/pens/reverseContourPen.py +96 -0
  144. fontTools/pens/roundingPen.py +130 -0
  145. fontTools/pens/statisticsPen.py +312 -0
  146. fontTools/pens/svgPathPen.py +310 -0
  147. fontTools/pens/t2CharStringPen.py +88 -0
  148. fontTools/pens/teePen.py +55 -0
  149. fontTools/pens/transformPen.py +115 -0
  150. fontTools/pens/ttGlyphPen.py +335 -0
  151. fontTools/pens/wxPen.py +29 -0
  152. fontTools/qu2cu/__init__.py +15 -0
  153. fontTools/qu2cu/__main__.py +7 -0
  154. fontTools/qu2cu/benchmark.py +56 -0
  155. fontTools/qu2cu/cli.py +125 -0
  156. fontTools/qu2cu/qu2cu.c +16682 -0
  157. fontTools/qu2cu/qu2cu.cp311-win32.pyd +0 -0
  158. fontTools/qu2cu/qu2cu.py +405 -0
  159. fontTools/subset/__init__.py +4096 -0
  160. fontTools/subset/__main__.py +6 -0
  161. fontTools/subset/cff.py +184 -0
  162. fontTools/subset/svg.py +253 -0
  163. fontTools/subset/util.py +25 -0
  164. fontTools/svgLib/__init__.py +3 -0
  165. fontTools/svgLib/path/__init__.py +65 -0
  166. fontTools/svgLib/path/arc.py +154 -0
  167. fontTools/svgLib/path/parser.py +322 -0
  168. fontTools/svgLib/path/shapes.py +183 -0
  169. fontTools/t1Lib/__init__.py +648 -0
  170. fontTools/tfmLib.py +460 -0
  171. fontTools/ttLib/__init__.py +30 -0
  172. fontTools/ttLib/__main__.py +148 -0
  173. fontTools/ttLib/macUtils.py +54 -0
  174. fontTools/ttLib/removeOverlaps.py +395 -0
  175. fontTools/ttLib/reorderGlyphs.py +285 -0
  176. fontTools/ttLib/scaleUpem.py +436 -0
  177. fontTools/ttLib/sfnt.py +661 -0
  178. fontTools/ttLib/standardGlyphOrder.py +271 -0
  179. fontTools/ttLib/tables/B_A_S_E_.py +14 -0
  180. fontTools/ttLib/tables/BitmapGlyphMetrics.py +64 -0
  181. fontTools/ttLib/tables/C_B_D_T_.py +113 -0
  182. fontTools/ttLib/tables/C_B_L_C_.py +19 -0
  183. fontTools/ttLib/tables/C_F_F_.py +61 -0
  184. fontTools/ttLib/tables/C_F_F__2.py +26 -0
  185. fontTools/ttLib/tables/C_O_L_R_.py +165 -0
  186. fontTools/ttLib/tables/C_P_A_L_.py +305 -0
  187. fontTools/ttLib/tables/D_S_I_G_.py +158 -0
  188. fontTools/ttLib/tables/D__e_b_g.py +35 -0
  189. fontTools/ttLib/tables/DefaultTable.py +49 -0
  190. fontTools/ttLib/tables/E_B_D_T_.py +835 -0
  191. fontTools/ttLib/tables/E_B_L_C_.py +718 -0
  192. fontTools/ttLib/tables/F_F_T_M_.py +52 -0
  193. fontTools/ttLib/tables/F__e_a_t.py +149 -0
  194. fontTools/ttLib/tables/G_D_E_F_.py +13 -0
  195. fontTools/ttLib/tables/G_M_A_P_.py +148 -0
  196. fontTools/ttLib/tables/G_P_K_G_.py +133 -0
  197. fontTools/ttLib/tables/G_P_O_S_.py +14 -0
  198. fontTools/ttLib/tables/G_S_U_B_.py +13 -0
  199. fontTools/ttLib/tables/G_V_A_R_.py +5 -0
  200. fontTools/ttLib/tables/G__l_a_t.py +235 -0
  201. fontTools/ttLib/tables/G__l_o_c.py +85 -0
  202. fontTools/ttLib/tables/H_V_A_R_.py +13 -0
  203. fontTools/ttLib/tables/J_S_T_F_.py +13 -0
  204. fontTools/ttLib/tables/L_T_S_H_.py +58 -0
  205. fontTools/ttLib/tables/M_A_T_H_.py +13 -0
  206. fontTools/ttLib/tables/M_E_T_A_.py +352 -0
  207. fontTools/ttLib/tables/M_V_A_R_.py +13 -0
  208. fontTools/ttLib/tables/O_S_2f_2.py +752 -0
  209. fontTools/ttLib/tables/S_I_N_G_.py +99 -0
  210. fontTools/ttLib/tables/S_T_A_T_.py +15 -0
  211. fontTools/ttLib/tables/S_V_G_.py +223 -0
  212. fontTools/ttLib/tables/S__i_l_f.py +1040 -0
  213. fontTools/ttLib/tables/S__i_l_l.py +92 -0
  214. fontTools/ttLib/tables/T_S_I_B_.py +13 -0
  215. fontTools/ttLib/tables/T_S_I_C_.py +14 -0
  216. fontTools/ttLib/tables/T_S_I_D_.py +13 -0
  217. fontTools/ttLib/tables/T_S_I_J_.py +13 -0
  218. fontTools/ttLib/tables/T_S_I_P_.py +13 -0
  219. fontTools/ttLib/tables/T_S_I_S_.py +13 -0
  220. fontTools/ttLib/tables/T_S_I_V_.py +26 -0
  221. fontTools/ttLib/tables/T_S_I__0.py +70 -0
  222. fontTools/ttLib/tables/T_S_I__1.py +163 -0
  223. fontTools/ttLib/tables/T_S_I__2.py +17 -0
  224. fontTools/ttLib/tables/T_S_I__3.py +22 -0
  225. fontTools/ttLib/tables/T_S_I__5.py +60 -0
  226. fontTools/ttLib/tables/T_T_F_A_.py +14 -0
  227. fontTools/ttLib/tables/TupleVariation.py +884 -0
  228. fontTools/ttLib/tables/V_A_R_C_.py +12 -0
  229. fontTools/ttLib/tables/V_D_M_X_.py +249 -0
  230. fontTools/ttLib/tables/V_O_R_G_.py +165 -0
  231. fontTools/ttLib/tables/V_V_A_R_.py +13 -0
  232. fontTools/ttLib/tables/__init__.py +98 -0
  233. fontTools/ttLib/tables/_a_n_k_r.py +15 -0
  234. fontTools/ttLib/tables/_a_v_a_r.py +193 -0
  235. fontTools/ttLib/tables/_b_s_l_n.py +15 -0
  236. fontTools/ttLib/tables/_c_i_d_g.py +24 -0
  237. fontTools/ttLib/tables/_c_m_a_p.py +1591 -0
  238. fontTools/ttLib/tables/_c_v_a_r.py +94 -0
  239. fontTools/ttLib/tables/_c_v_t.py +56 -0
  240. fontTools/ttLib/tables/_f_e_a_t.py +15 -0
  241. fontTools/ttLib/tables/_f_p_g_m.py +62 -0
  242. fontTools/ttLib/tables/_f_v_a_r.py +261 -0
  243. fontTools/ttLib/tables/_g_a_s_p.py +63 -0
  244. fontTools/ttLib/tables/_g_c_i_d.py +13 -0
  245. fontTools/ttLib/tables/_g_l_y_f.py +2311 -0
  246. fontTools/ttLib/tables/_g_v_a_r.py +340 -0
  247. fontTools/ttLib/tables/_h_d_m_x.py +127 -0
  248. fontTools/ttLib/tables/_h_e_a_d.py +130 -0
  249. fontTools/ttLib/tables/_h_h_e_a.py +147 -0
  250. fontTools/ttLib/tables/_h_m_t_x.py +164 -0
  251. fontTools/ttLib/tables/_k_e_r_n.py +289 -0
  252. fontTools/ttLib/tables/_l_c_a_r.py +13 -0
  253. fontTools/ttLib/tables/_l_o_c_a.py +70 -0
  254. fontTools/ttLib/tables/_l_t_a_g.py +72 -0
  255. fontTools/ttLib/tables/_m_a_x_p.py +147 -0
  256. fontTools/ttLib/tables/_m_e_t_a.py +112 -0
  257. fontTools/ttLib/tables/_m_o_r_t.py +14 -0
  258. fontTools/ttLib/tables/_m_o_r_x.py +15 -0
  259. fontTools/ttLib/tables/_n_a_m_e.py +1242 -0
  260. fontTools/ttLib/tables/_o_p_b_d.py +14 -0
  261. fontTools/ttLib/tables/_p_o_s_t.py +319 -0
  262. fontTools/ttLib/tables/_p_r_e_p.py +16 -0
  263. fontTools/ttLib/tables/_p_r_o_p.py +12 -0
  264. fontTools/ttLib/tables/_s_b_i_x.py +129 -0
  265. fontTools/ttLib/tables/_t_r_a_k.py +332 -0
  266. fontTools/ttLib/tables/_v_h_e_a.py +139 -0
  267. fontTools/ttLib/tables/_v_m_t_x.py +19 -0
  268. fontTools/ttLib/tables/asciiTable.py +20 -0
  269. fontTools/ttLib/tables/grUtils.py +92 -0
  270. fontTools/ttLib/tables/otBase.py +1458 -0
  271. fontTools/ttLib/tables/otConverters.py +2068 -0
  272. fontTools/ttLib/tables/otData.py +6400 -0
  273. fontTools/ttLib/tables/otTables.py +2703 -0
  274. fontTools/ttLib/tables/otTraverse.py +163 -0
  275. fontTools/ttLib/tables/sbixGlyph.py +149 -0
  276. fontTools/ttLib/tables/sbixStrike.py +177 -0
  277. fontTools/ttLib/tables/table_API_readme.txt +91 -0
  278. fontTools/ttLib/tables/ttProgram.py +594 -0
  279. fontTools/ttLib/ttCollection.py +125 -0
  280. fontTools/ttLib/ttFont.py +1148 -0
  281. fontTools/ttLib/ttGlyphSet.py +490 -0
  282. fontTools/ttLib/ttVisitor.py +32 -0
  283. fontTools/ttLib/woff2.py +1680 -0
  284. fontTools/ttx.py +479 -0
  285. fontTools/ufoLib/__init__.py +2575 -0
  286. fontTools/ufoLib/converters.py +407 -0
  287. fontTools/ufoLib/errors.py +30 -0
  288. fontTools/ufoLib/etree.py +6 -0
  289. fontTools/ufoLib/filenames.py +356 -0
  290. fontTools/ufoLib/glifLib.py +2120 -0
  291. fontTools/ufoLib/kerning.py +141 -0
  292. fontTools/ufoLib/plistlib.py +47 -0
  293. fontTools/ufoLib/pointPen.py +6 -0
  294. fontTools/ufoLib/utils.py +107 -0
  295. fontTools/ufoLib/validators.py +1208 -0
  296. fontTools/unicode.py +50 -0
  297. fontTools/unicodedata/Blocks.py +817 -0
  298. fontTools/unicodedata/Mirrored.py +446 -0
  299. fontTools/unicodedata/OTTags.py +50 -0
  300. fontTools/unicodedata/ScriptExtensions.py +832 -0
  301. fontTools/unicodedata/Scripts.py +3639 -0
  302. fontTools/unicodedata/__init__.py +306 -0
  303. fontTools/varLib/__init__.py +1600 -0
  304. fontTools/varLib/__main__.py +6 -0
  305. fontTools/varLib/avar/__init__.py +0 -0
  306. fontTools/varLib/avar/__main__.py +72 -0
  307. fontTools/varLib/avar/build.py +79 -0
  308. fontTools/varLib/avar/map.py +108 -0
  309. fontTools/varLib/avar/plan.py +1004 -0
  310. fontTools/varLib/avar/unbuild.py +271 -0
  311. fontTools/varLib/avarPlanner.py +8 -0
  312. fontTools/varLib/builder.py +215 -0
  313. fontTools/varLib/cff.py +631 -0
  314. fontTools/varLib/errors.py +219 -0
  315. fontTools/varLib/featureVars.py +703 -0
  316. fontTools/varLib/hvar.py +113 -0
  317. fontTools/varLib/instancer/__init__.py +2052 -0
  318. fontTools/varLib/instancer/__main__.py +5 -0
  319. fontTools/varLib/instancer/featureVars.py +190 -0
  320. fontTools/varLib/instancer/names.py +388 -0
  321. fontTools/varLib/instancer/solver.py +309 -0
  322. fontTools/varLib/interpolatable.py +1209 -0
  323. fontTools/varLib/interpolatableHelpers.py +399 -0
  324. fontTools/varLib/interpolatablePlot.py +1269 -0
  325. fontTools/varLib/interpolatableTestContourOrder.py +82 -0
  326. fontTools/varLib/interpolatableTestStartingPoint.py +107 -0
  327. fontTools/varLib/interpolate_layout.py +124 -0
  328. fontTools/varLib/iup.c +19815 -0
  329. fontTools/varLib/iup.cp311-win32.pyd +0 -0
  330. fontTools/varLib/iup.py +490 -0
  331. fontTools/varLib/merger.py +1717 -0
  332. fontTools/varLib/models.py +642 -0
  333. fontTools/varLib/multiVarStore.py +253 -0
  334. fontTools/varLib/mutator.py +529 -0
  335. fontTools/varLib/mvar.py +40 -0
  336. fontTools/varLib/plot.py +238 -0
  337. fontTools/varLib/stat.py +149 -0
  338. fontTools/varLib/varStore.py +739 -0
  339. fontTools/voltLib/__init__.py +5 -0
  340. fontTools/voltLib/__main__.py +206 -0
  341. fontTools/voltLib/ast.py +452 -0
  342. fontTools/voltLib/error.py +12 -0
  343. fontTools/voltLib/lexer.py +99 -0
  344. fontTools/voltLib/parser.py +664 -0
  345. fontTools/voltLib/voltToFea.py +911 -0
  346. fonttools-4.60.2.data/data/share/man/man1/ttx.1 +225 -0
  347. fonttools-4.60.2.dist-info/METADATA +2250 -0
  348. fonttools-4.60.2.dist-info/RECORD +353 -0
  349. fonttools-4.60.2.dist-info/WHEEL +5 -0
  350. fonttools-4.60.2.dist-info/entry_points.txt +5 -0
  351. fonttools-4.60.2.dist-info/licenses/LICENSE +21 -0
  352. fonttools-4.60.2.dist-info/licenses/LICENSE.external +388 -0
  353. fonttools-4.60.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3343 @@
1
+ """
2
+ designSpaceDocument
3
+
4
+ - Read and write designspace files
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import collections
10
+ import copy
11
+ import itertools
12
+ import math
13
+ import os
14
+ import posixpath
15
+ from io import BytesIO, StringIO
16
+ from textwrap import indent
17
+ from typing import Any, Dict, List, MutableMapping, Optional, Tuple, Union, cast
18
+
19
+ from fontTools.misc import etree as ET
20
+ from fontTools.misc import plistlib
21
+ from fontTools.misc.loggingTools import LogMixin
22
+ from fontTools.misc.textTools import tobytes, tostr
23
+
24
+
25
+ __all__ = [
26
+ "AxisDescriptor",
27
+ "AxisLabelDescriptor",
28
+ "AxisMappingDescriptor",
29
+ "BaseDocReader",
30
+ "BaseDocWriter",
31
+ "DesignSpaceDocument",
32
+ "DesignSpaceDocumentError",
33
+ "DiscreteAxisDescriptor",
34
+ "InstanceDescriptor",
35
+ "LocationLabelDescriptor",
36
+ "RangeAxisSubsetDescriptor",
37
+ "RuleDescriptor",
38
+ "SourceDescriptor",
39
+ "ValueAxisSubsetDescriptor",
40
+ "VariableFontDescriptor",
41
+ ]
42
+
43
+ # ElementTree allows to find namespace-prefixed elements, but not attributes
44
+ # so we have to do it ourselves for 'xml:lang'
45
+ XML_NS = "{http://www.w3.org/XML/1998/namespace}"
46
+ XML_LANG = XML_NS + "lang"
47
+
48
+
49
+ def posix(path):
50
+ """Normalize paths using forward slash to work also on Windows."""
51
+ new_path = posixpath.join(*path.split(os.path.sep))
52
+ if path.startswith("/"):
53
+ # The above transformation loses absolute paths
54
+ new_path = "/" + new_path
55
+ elif path.startswith(r"\\"):
56
+ # The above transformation loses leading slashes of UNC path mounts
57
+ new_path = "//" + new_path
58
+ return new_path
59
+
60
+
61
+ def posixpath_property(private_name):
62
+ """Generate a propery that holds a path always using forward slashes."""
63
+
64
+ def getter(self):
65
+ # Normal getter
66
+ return getattr(self, private_name)
67
+
68
+ def setter(self, value):
69
+ # The setter rewrites paths using forward slashes
70
+ if value is not None:
71
+ value = posix(value)
72
+ setattr(self, private_name, value)
73
+
74
+ return property(getter, setter)
75
+
76
+
77
+ class DesignSpaceDocumentError(Exception):
78
+ def __init__(self, msg, obj=None):
79
+ self.msg = msg
80
+ self.obj = obj
81
+
82
+ def __str__(self):
83
+ return str(self.msg) + (": %r" % self.obj if self.obj is not None else "")
84
+
85
+
86
+ class AsDictMixin(object):
87
+ def asdict(self):
88
+ d = {}
89
+ for attr, value in self.__dict__.items():
90
+ if attr.startswith("_"):
91
+ continue
92
+ if hasattr(value, "asdict"):
93
+ value = value.asdict()
94
+ elif isinstance(value, list):
95
+ value = [v.asdict() if hasattr(v, "asdict") else v for v in value]
96
+ d[attr] = value
97
+ return d
98
+
99
+
100
+ class SimpleDescriptor(AsDictMixin):
101
+ """Containers for a bunch of attributes"""
102
+
103
+ # XXX this is ugly. The 'print' is inappropriate here, and instead of
104
+ # assert, it should simply return True/False
105
+ def compare(self, other):
106
+ # test if this object contains the same data as the other
107
+ for attr in self._attrs:
108
+ try:
109
+ assert getattr(self, attr) == getattr(other, attr)
110
+ except AssertionError:
111
+ print(
112
+ "failed attribute",
113
+ attr,
114
+ getattr(self, attr),
115
+ "!=",
116
+ getattr(other, attr),
117
+ )
118
+
119
+ def __repr__(self):
120
+ attrs = [f"{a}={repr(getattr(self, a))}," for a in self._attrs]
121
+ attrs = indent("\n".join(attrs), " ")
122
+ return f"{self.__class__.__name__}(\n{attrs}\n)"
123
+
124
+
125
+ class SourceDescriptor(SimpleDescriptor):
126
+ """Simple container for data related to the source
127
+
128
+ .. code:: python
129
+
130
+ doc = DesignSpaceDocument()
131
+ s1 = SourceDescriptor()
132
+ s1.path = masterPath1
133
+ s1.name = "master.ufo1"
134
+ s1.font = defcon.Font("master.ufo1")
135
+ s1.location = dict(weight=0)
136
+ s1.familyName = "MasterFamilyName"
137
+ s1.styleName = "MasterStyleNameOne"
138
+ s1.localisedFamilyName = dict(fr="Caractère")
139
+ s1.mutedGlyphNames.append("A")
140
+ s1.mutedGlyphNames.append("Z")
141
+ doc.addSource(s1)
142
+
143
+ """
144
+
145
+ flavor = "source"
146
+ _attrs = [
147
+ "filename",
148
+ "path",
149
+ "name",
150
+ "layerName",
151
+ "location",
152
+ "copyLib",
153
+ "copyGroups",
154
+ "copyFeatures",
155
+ "muteKerning",
156
+ "muteInfo",
157
+ "mutedGlyphNames",
158
+ "familyName",
159
+ "styleName",
160
+ "localisedFamilyName",
161
+ ]
162
+
163
+ filename = posixpath_property("_filename")
164
+ path = posixpath_property("_path")
165
+
166
+ def __init__(
167
+ self,
168
+ *,
169
+ filename=None,
170
+ path=None,
171
+ font=None,
172
+ name=None,
173
+ location=None,
174
+ designLocation=None,
175
+ layerName=None,
176
+ familyName=None,
177
+ styleName=None,
178
+ localisedFamilyName=None,
179
+ copyLib=False,
180
+ copyInfo=False,
181
+ copyGroups=False,
182
+ copyFeatures=False,
183
+ muteKerning=False,
184
+ muteInfo=False,
185
+ mutedGlyphNames=None,
186
+ ):
187
+ self.filename = filename
188
+ """string. A relative path to the source file, **as it is in the document**.
189
+
190
+ MutatorMath + VarLib.
191
+ """
192
+ self.path = path
193
+ """The absolute path, calculated from filename."""
194
+
195
+ self.font = font
196
+ """Any Python object. Optional. Points to a representation of this
197
+ source font that is loaded in memory, as a Python object (e.g. a
198
+ ``defcon.Font`` or a ``fontTools.ttFont.TTFont``).
199
+
200
+ The default document reader will not fill-in this attribute, and the
201
+ default writer will not use this attribute. It is up to the user of
202
+ ``designspaceLib`` to either load the resource identified by
203
+ ``filename`` and store it in this field, or write the contents of
204
+ this field to the disk and make ```filename`` point to that.
205
+ """
206
+
207
+ self.name = name
208
+ """string. Optional. Unique identifier name for this source.
209
+
210
+ MutatorMath + varLib.
211
+ """
212
+
213
+ self.designLocation = (
214
+ designLocation if designLocation is not None else location or {}
215
+ )
216
+ """dict. Axis values for this source, in design space coordinates.
217
+
218
+ MutatorMath + varLib.
219
+
220
+ This may be only part of the full design location.
221
+ See :meth:`getFullDesignLocation()`
222
+
223
+ .. versionadded:: 5.0
224
+ """
225
+
226
+ self.layerName = layerName
227
+ """string. The name of the layer in the source to look for
228
+ outline data. Default ``None`` which means ``foreground``.
229
+ """
230
+ self.familyName = familyName
231
+ """string. Family name of this source. Though this data
232
+ can be extracted from the font, it can be efficient to have it right
233
+ here.
234
+
235
+ varLib.
236
+ """
237
+ self.styleName = styleName
238
+ """string. Style name of this source. Though this data
239
+ can be extracted from the font, it can be efficient to have it right
240
+ here.
241
+
242
+ varLib.
243
+ """
244
+ self.localisedFamilyName = localisedFamilyName or {}
245
+ """dict. A dictionary of localised family name strings, keyed by
246
+ language code.
247
+
248
+ If present, will be used to build localized names for all instances.
249
+
250
+ .. versionadded:: 5.0
251
+ """
252
+
253
+ self.copyLib = copyLib
254
+ """bool. Indicates if the contents of the font.lib need to
255
+ be copied to the instances.
256
+
257
+ MutatorMath.
258
+
259
+ .. deprecated:: 5.0
260
+ """
261
+ self.copyInfo = copyInfo
262
+ """bool. Indicates if the non-interpolating font.info needs
263
+ to be copied to the instances.
264
+
265
+ MutatorMath.
266
+
267
+ .. deprecated:: 5.0
268
+ """
269
+ self.copyGroups = copyGroups
270
+ """bool. Indicates if the groups need to be copied to the
271
+ instances.
272
+
273
+ MutatorMath.
274
+
275
+ .. deprecated:: 5.0
276
+ """
277
+ self.copyFeatures = copyFeatures
278
+ """bool. Indicates if the feature text needs to be
279
+ copied to the instances.
280
+
281
+ MutatorMath.
282
+
283
+ .. deprecated:: 5.0
284
+ """
285
+ self.muteKerning = muteKerning
286
+ """bool. Indicates if the kerning data from this source
287
+ needs to be muted (i.e. not be part of the calculations).
288
+
289
+ MutatorMath only.
290
+ """
291
+ self.muteInfo = muteInfo
292
+ """bool. Indicated if the interpolating font.info data for
293
+ this source needs to be muted.
294
+
295
+ MutatorMath only.
296
+ """
297
+ self.mutedGlyphNames = mutedGlyphNames or []
298
+ """list. Glyphnames that need to be muted in the
299
+ instances.
300
+
301
+ MutatorMath only.
302
+ """
303
+
304
+ @property
305
+ def location(self):
306
+ """dict. Axis values for this source, in design space coordinates.
307
+
308
+ MutatorMath + varLib.
309
+
310
+ .. deprecated:: 5.0
311
+ Use the more explicit alias for this property :attr:`designLocation`.
312
+ """
313
+ return self.designLocation
314
+
315
+ @location.setter
316
+ def location(self, location: Optional[SimpleLocationDict]):
317
+ self.designLocation = location or {}
318
+
319
+ def setFamilyName(self, familyName, languageCode="en"):
320
+ """Setter for :attr:`localisedFamilyName`
321
+
322
+ .. versionadded:: 5.0
323
+ """
324
+ self.localisedFamilyName[languageCode] = tostr(familyName)
325
+
326
+ def getFamilyName(self, languageCode="en"):
327
+ """Getter for :attr:`localisedFamilyName`
328
+
329
+ .. versionadded:: 5.0
330
+ """
331
+ return self.localisedFamilyName.get(languageCode)
332
+
333
+ def getFullDesignLocation(self, doc: "DesignSpaceDocument") -> SimpleLocationDict:
334
+ """Get the complete design location of this source, from its
335
+ :attr:`designLocation` and the document's axis defaults.
336
+
337
+ .. versionadded:: 5.0
338
+ """
339
+ result: SimpleLocationDict = {}
340
+ for axis in doc.axes:
341
+ if axis.name in self.designLocation:
342
+ result[axis.name] = self.designLocation[axis.name]
343
+ else:
344
+ result[axis.name] = axis.map_forward(axis.default)
345
+ return result
346
+
347
+
348
+ class RuleDescriptor(SimpleDescriptor):
349
+ """Represents the rule descriptor element: a set of glyph substitutions to
350
+ trigger conditionally in some parts of the designspace.
351
+
352
+ .. code:: python
353
+
354
+ r1 = RuleDescriptor()
355
+ r1.name = "unique.rule.name"
356
+ r1.conditionSets.append([dict(name="weight", minimum=-10, maximum=10), dict(...)])
357
+ r1.conditionSets.append([dict(...), dict(...)])
358
+ r1.subs.append(("a", "a.alt"))
359
+
360
+ .. code:: xml
361
+
362
+ <!-- optional: list of substitution rules -->
363
+ <rules>
364
+ <rule name="vertical.bars">
365
+ <conditionset>
366
+ <condition minimum="250.000000" maximum="750.000000" name="weight"/>
367
+ <condition minimum="100" name="width"/>
368
+ <condition minimum="10" maximum="40" name="optical"/>
369
+ </conditionset>
370
+ <sub name="cent" with="cent.alt"/>
371
+ <sub name="dollar" with="dollar.alt"/>
372
+ </rule>
373
+ </rules>
374
+ """
375
+
376
+ _attrs = ["name", "conditionSets", "subs"] # what do we need here
377
+
378
+ def __init__(self, *, name=None, conditionSets=None, subs=None):
379
+ self.name = name
380
+ """string. Unique name for this rule. Can be used to reference this rule data."""
381
+ # list of lists of dict(name='aaaa', minimum=0, maximum=1000)
382
+ self.conditionSets = conditionSets or []
383
+ """a list of conditionsets.
384
+
385
+ - Each conditionset is a list of conditions.
386
+ - Each condition is a dict with ``name``, ``minimum`` and ``maximum`` keys.
387
+ """
388
+ # list of substitutions stored as tuples of glyphnames ("a", "a.alt")
389
+ self.subs = subs or []
390
+ """list of substitutions.
391
+
392
+ - Each substitution is stored as tuples of glyphnames, e.g. ("a", "a.alt").
393
+ - Note: By default, rules are applied first, before other text
394
+ shaping/OpenType layout, as they are part of the
395
+ `Required Variation Alternates OpenType feature <https://docs.microsoft.com/en-us/typography/opentype/spec/features_pt#-tag-rvrn>`_.
396
+ See ref:`rules-element` § Attributes.
397
+ """
398
+
399
+
400
+ def evaluateRule(rule, location):
401
+ """Return True if any of the rule's conditionsets matches the given location."""
402
+ return any(evaluateConditions(c, location) for c in rule.conditionSets)
403
+
404
+
405
+ def evaluateConditions(conditions, location):
406
+ """Return True if all the conditions matches the given location.
407
+
408
+ - If a condition has no minimum, check for < maximum.
409
+ - If a condition has no maximum, check for > minimum.
410
+ """
411
+ for cd in conditions:
412
+ value = location[cd["name"]]
413
+ if cd.get("minimum") is None:
414
+ if value > cd["maximum"]:
415
+ return False
416
+ elif cd.get("maximum") is None:
417
+ if cd["minimum"] > value:
418
+ return False
419
+ elif not cd["minimum"] <= value <= cd["maximum"]:
420
+ return False
421
+ return True
422
+
423
+
424
+ def processRules(rules, location, glyphNames):
425
+ """Apply these rules at this location to these glyphnames.
426
+
427
+ Return a new list of glyphNames with substitutions applied.
428
+
429
+ - rule order matters
430
+ """
431
+ newNames = []
432
+ for rule in rules:
433
+ if evaluateRule(rule, location):
434
+ for name in glyphNames:
435
+ swap = False
436
+ for a, b in rule.subs:
437
+ if name == a:
438
+ swap = True
439
+ break
440
+ if swap:
441
+ newNames.append(b)
442
+ else:
443
+ newNames.append(name)
444
+ glyphNames = newNames
445
+ newNames = []
446
+ return glyphNames
447
+
448
+
449
+ AnisotropicLocationDict = Dict[str, Union[float, Tuple[float, float]]]
450
+ SimpleLocationDict = Dict[str, float]
451
+
452
+
453
+ class AxisMappingDescriptor(SimpleDescriptor):
454
+ """Represents the axis mapping element: mapping an input location
455
+ to an output location in the designspace.
456
+
457
+ .. code:: python
458
+
459
+ m1 = AxisMappingDescriptor()
460
+ m1.inputLocation = {"weight": 900, "width": 150}
461
+ m1.outputLocation = {"weight": 870}
462
+
463
+ .. code:: xml
464
+
465
+ <mappings>
466
+ <mapping>
467
+ <input>
468
+ <dimension name="weight" xvalue="900"/>
469
+ <dimension name="width" xvalue="150"/>
470
+ </input>
471
+ <output>
472
+ <dimension name="weight" xvalue="870"/>
473
+ </output>
474
+ </mapping>
475
+ </mappings>
476
+ """
477
+
478
+ _attrs = ["inputLocation", "outputLocation"]
479
+
480
+ def __init__(
481
+ self,
482
+ *,
483
+ inputLocation=None,
484
+ outputLocation=None,
485
+ description=None,
486
+ groupDescription=None,
487
+ ):
488
+ self.inputLocation: SimpleLocationDict = inputLocation or {}
489
+ """dict. Axis values for the input of the mapping, in design space coordinates.
490
+
491
+ varLib.
492
+
493
+ .. versionadded:: 5.1
494
+ """
495
+ self.outputLocation: SimpleLocationDict = outputLocation or {}
496
+ """dict. Axis values for the output of the mapping, in design space coordinates.
497
+
498
+ varLib.
499
+
500
+ .. versionadded:: 5.1
501
+ """
502
+ self.description = description
503
+ """string. A description of the mapping.
504
+
505
+ varLib.
506
+
507
+ .. versionadded:: 5.2
508
+ """
509
+ self.groupDescription = groupDescription
510
+ """string. A description of the group of mappings.
511
+
512
+ varLib.
513
+
514
+ .. versionadded:: 5.2
515
+ """
516
+
517
+
518
+ class InstanceDescriptor(SimpleDescriptor):
519
+ """Simple container for data related to the instance
520
+
521
+
522
+ .. code:: python
523
+
524
+ i2 = InstanceDescriptor()
525
+ i2.path = instancePath2
526
+ i2.familyName = "InstanceFamilyName"
527
+ i2.styleName = "InstanceStyleName"
528
+ i2.name = "instance.ufo2"
529
+ # anisotropic location
530
+ i2.designLocation = dict(weight=500, width=(400,300))
531
+ i2.postScriptFontName = "InstancePostscriptName"
532
+ i2.styleMapFamilyName = "InstanceStyleMapFamilyName"
533
+ i2.styleMapStyleName = "InstanceStyleMapStyleName"
534
+ i2.lib['com.coolDesignspaceApp.specimenText'] = 'Hamburgerwhatever'
535
+ doc.addInstance(i2)
536
+ """
537
+
538
+ flavor = "instance"
539
+ _defaultLanguageCode = "en"
540
+ _attrs = [
541
+ "filename",
542
+ "path",
543
+ "name",
544
+ "locationLabel",
545
+ "designLocation",
546
+ "userLocation",
547
+ "familyName",
548
+ "styleName",
549
+ "postScriptFontName",
550
+ "styleMapFamilyName",
551
+ "styleMapStyleName",
552
+ "localisedFamilyName",
553
+ "localisedStyleName",
554
+ "localisedStyleMapFamilyName",
555
+ "localisedStyleMapStyleName",
556
+ "glyphs",
557
+ "kerning",
558
+ "info",
559
+ "lib",
560
+ ]
561
+
562
+ filename = posixpath_property("_filename")
563
+ path = posixpath_property("_path")
564
+
565
+ def __init__(
566
+ self,
567
+ *,
568
+ filename=None,
569
+ path=None,
570
+ font=None,
571
+ name=None,
572
+ location=None,
573
+ locationLabel=None,
574
+ designLocation=None,
575
+ userLocation=None,
576
+ familyName=None,
577
+ styleName=None,
578
+ postScriptFontName=None,
579
+ styleMapFamilyName=None,
580
+ styleMapStyleName=None,
581
+ localisedFamilyName=None,
582
+ localisedStyleName=None,
583
+ localisedStyleMapFamilyName=None,
584
+ localisedStyleMapStyleName=None,
585
+ glyphs=None,
586
+ kerning=True,
587
+ info=True,
588
+ lib=None,
589
+ ):
590
+ self.filename = filename
591
+ """string. Relative path to the instance file, **as it is
592
+ in the document**. The file may or may not exist.
593
+
594
+ MutatorMath + VarLib.
595
+ """
596
+ self.path = path
597
+ """string. Absolute path to the instance file, calculated from
598
+ the document path and the string in the filename attr. The file may
599
+ or may not exist.
600
+
601
+ MutatorMath.
602
+ """
603
+ self.font = font
604
+ """Same as :attr:`SourceDescriptor.font`
605
+
606
+ .. seealso:: :attr:`SourceDescriptor.font`
607
+ """
608
+ self.name = name
609
+ """string. Unique identifier name of the instance, used to
610
+ identify it if it needs to be referenced from elsewhere in the
611
+ document.
612
+ """
613
+ self.locationLabel = locationLabel
614
+ """Name of a :class:`LocationLabelDescriptor`. If
615
+ provided, the instance should have the same location as the
616
+ LocationLabel.
617
+
618
+ .. seealso::
619
+ :meth:`getFullDesignLocation`
620
+ :meth:`getFullUserLocation`
621
+
622
+ .. versionadded:: 5.0
623
+ """
624
+ self.designLocation: AnisotropicLocationDict = (
625
+ designLocation if designLocation is not None else (location or {})
626
+ )
627
+ """dict. Axis values for this instance, in design space coordinates.
628
+
629
+ MutatorMath + varLib.
630
+
631
+ .. seealso:: This may be only part of the full location. See:
632
+ :meth:`getFullDesignLocation`
633
+ :meth:`getFullUserLocation`
634
+
635
+ .. versionadded:: 5.0
636
+ """
637
+ self.userLocation: SimpleLocationDict = userLocation or {}
638
+ """dict. Axis values for this instance, in user space coordinates.
639
+
640
+ MutatorMath + varLib.
641
+
642
+ .. seealso:: This may be only part of the full location. See:
643
+ :meth:`getFullDesignLocation`
644
+ :meth:`getFullUserLocation`
645
+
646
+ .. versionadded:: 5.0
647
+ """
648
+ self.familyName = familyName
649
+ """string. Family name of this instance.
650
+
651
+ MutatorMath + varLib.
652
+ """
653
+ self.styleName = styleName
654
+ """string. Style name of this instance.
655
+
656
+ MutatorMath + varLib.
657
+ """
658
+ self.postScriptFontName = postScriptFontName
659
+ """string. Postscript fontname for this instance.
660
+
661
+ MutatorMath + varLib.
662
+ """
663
+ self.styleMapFamilyName = styleMapFamilyName
664
+ """string. StyleMap familyname for this instance.
665
+
666
+ MutatorMath + varLib.
667
+ """
668
+ self.styleMapStyleName = styleMapStyleName
669
+ """string. StyleMap stylename for this instance.
670
+
671
+ MutatorMath + varLib.
672
+ """
673
+ self.localisedFamilyName = localisedFamilyName or {}
674
+ """dict. A dictionary of localised family name
675
+ strings, keyed by language code.
676
+ """
677
+ self.localisedStyleName = localisedStyleName or {}
678
+ """dict. A dictionary of localised stylename
679
+ strings, keyed by language code.
680
+ """
681
+ self.localisedStyleMapFamilyName = localisedStyleMapFamilyName or {}
682
+ """A dictionary of localised style map
683
+ familyname strings, keyed by language code.
684
+ """
685
+ self.localisedStyleMapStyleName = localisedStyleMapStyleName or {}
686
+ """A dictionary of localised style map
687
+ stylename strings, keyed by language code.
688
+ """
689
+ self.glyphs = glyphs or {}
690
+ """dict for special master definitions for glyphs. If glyphs
691
+ need special masters (to record the results of executed rules for
692
+ example).
693
+
694
+ MutatorMath.
695
+
696
+ .. deprecated:: 5.0
697
+ Use rules or sparse sources instead.
698
+ """
699
+ self.kerning = kerning
700
+ """ bool. Indicates if this instance needs its kerning
701
+ calculated.
702
+
703
+ MutatorMath.
704
+
705
+ .. deprecated:: 5.0
706
+ """
707
+ self.info = info
708
+ """bool. Indicated if this instance needs the interpolating
709
+ font.info calculated.
710
+
711
+ .. deprecated:: 5.0
712
+ """
713
+
714
+ self.lib = lib or {}
715
+ """Custom data associated with this instance."""
716
+
717
+ @property
718
+ def location(self):
719
+ """dict. Axis values for this instance.
720
+
721
+ MutatorMath + varLib.
722
+
723
+ .. deprecated:: 5.0
724
+ Use the more explicit alias for this property :attr:`designLocation`.
725
+ """
726
+ return self.designLocation
727
+
728
+ @location.setter
729
+ def location(self, location: Optional[AnisotropicLocationDict]):
730
+ self.designLocation = location or {}
731
+
732
+ def setStyleName(self, styleName, languageCode="en"):
733
+ """These methods give easier access to the localised names."""
734
+ self.localisedStyleName[languageCode] = tostr(styleName)
735
+
736
+ def getStyleName(self, languageCode="en"):
737
+ return self.localisedStyleName.get(languageCode)
738
+
739
+ def setFamilyName(self, familyName, languageCode="en"):
740
+ self.localisedFamilyName[languageCode] = tostr(familyName)
741
+
742
+ def getFamilyName(self, languageCode="en"):
743
+ return self.localisedFamilyName.get(languageCode)
744
+
745
+ def setStyleMapStyleName(self, styleMapStyleName, languageCode="en"):
746
+ self.localisedStyleMapStyleName[languageCode] = tostr(styleMapStyleName)
747
+
748
+ def getStyleMapStyleName(self, languageCode="en"):
749
+ return self.localisedStyleMapStyleName.get(languageCode)
750
+
751
+ def setStyleMapFamilyName(self, styleMapFamilyName, languageCode="en"):
752
+ self.localisedStyleMapFamilyName[languageCode] = tostr(styleMapFamilyName)
753
+
754
+ def getStyleMapFamilyName(self, languageCode="en"):
755
+ return self.localisedStyleMapFamilyName.get(languageCode)
756
+
757
+ def clearLocation(self, axisName: Optional[str] = None):
758
+ """Clear all location-related fields. Ensures that
759
+ :attr:``designLocation`` and :attr:``userLocation`` are dictionaries
760
+ (possibly empty if clearing everything).
761
+
762
+ In order to update the location of this instance wholesale, a user
763
+ should first clear all the fields, then change the field(s) for which
764
+ they have data.
765
+
766
+ .. code:: python
767
+
768
+ instance.clearLocation()
769
+ instance.designLocation = {'Weight': (34, 36.5), 'Width': 100}
770
+ instance.userLocation = {'Opsz': 16}
771
+
772
+ In order to update a single axis location, the user should only clear
773
+ that axis, then edit the values:
774
+
775
+ .. code:: python
776
+
777
+ instance.clearLocation('Weight')
778
+ instance.designLocation['Weight'] = (34, 36.5)
779
+
780
+ Args:
781
+ axisName: if provided, only clear the location for that axis.
782
+
783
+ .. versionadded:: 5.0
784
+ """
785
+ self.locationLabel = None
786
+ if axisName is None:
787
+ self.designLocation = {}
788
+ self.userLocation = {}
789
+ else:
790
+ if self.designLocation is None:
791
+ self.designLocation = {}
792
+ if axisName in self.designLocation:
793
+ del self.designLocation[axisName]
794
+ if self.userLocation is None:
795
+ self.userLocation = {}
796
+ if axisName in self.userLocation:
797
+ del self.userLocation[axisName]
798
+
799
+ def getLocationLabelDescriptor(
800
+ self, doc: "DesignSpaceDocument"
801
+ ) -> Optional[LocationLabelDescriptor]:
802
+ """Get the :class:`LocationLabelDescriptor` instance that matches
803
+ this instances's :attr:`locationLabel`.
804
+
805
+ Raises if the named label can't be found.
806
+
807
+ .. versionadded:: 5.0
808
+ """
809
+ if self.locationLabel is None:
810
+ return None
811
+ label = doc.getLocationLabel(self.locationLabel)
812
+ if label is None:
813
+ raise DesignSpaceDocumentError(
814
+ "InstanceDescriptor.getLocationLabelDescriptor(): "
815
+ f"unknown location label `{self.locationLabel}` in instance `{self.name}`."
816
+ )
817
+ return label
818
+
819
+ def getFullDesignLocation(
820
+ self, doc: "DesignSpaceDocument"
821
+ ) -> AnisotropicLocationDict:
822
+ """Get the complete design location of this instance, by combining data
823
+ from the various location fields, default axis values and mappings, and
824
+ top-level location labels.
825
+
826
+ The source of truth for this instance's location is determined for each
827
+ axis independently by taking the first not-None field in this list:
828
+
829
+ - ``locationLabel``: the location along this axis is the same as the
830
+ matching STAT format 4 label. No anisotropy.
831
+ - ``designLocation[axisName]``: the explicit design location along this
832
+ axis, possibly anisotropic.
833
+ - ``userLocation[axisName]``: the explicit user location along this
834
+ axis. No anisotropy.
835
+ - ``axis.default``: default axis value. No anisotropy.
836
+
837
+ .. versionadded:: 5.0
838
+ """
839
+ label = self.getLocationLabelDescriptor(doc)
840
+ if label is not None:
841
+ return doc.map_forward(label.userLocation) # type: ignore
842
+ result: AnisotropicLocationDict = {}
843
+ for axis in doc.axes:
844
+ if axis.name in self.designLocation:
845
+ result[axis.name] = self.designLocation[axis.name]
846
+ elif axis.name in self.userLocation:
847
+ result[axis.name] = axis.map_forward(self.userLocation[axis.name])
848
+ else:
849
+ result[axis.name] = axis.map_forward(axis.default)
850
+ return result
851
+
852
+ def getFullUserLocation(self, doc: "DesignSpaceDocument") -> SimpleLocationDict:
853
+ """Get the complete user location for this instance.
854
+
855
+ .. seealso:: :meth:`getFullDesignLocation`
856
+
857
+ .. versionadded:: 5.0
858
+ """
859
+ return doc.map_backward(self.getFullDesignLocation(doc))
860
+
861
+
862
+ def tagForAxisName(name):
863
+ # try to find or make a tag name for this axis name
864
+ names = {
865
+ "weight": ("wght", dict(en="Weight")),
866
+ "width": ("wdth", dict(en="Width")),
867
+ "optical": ("opsz", dict(en="Optical Size")),
868
+ "slant": ("slnt", dict(en="Slant")),
869
+ "italic": ("ital", dict(en="Italic")),
870
+ }
871
+ if name.lower() in names:
872
+ return names[name.lower()]
873
+ if len(name) < 4:
874
+ tag = name + "*" * (4 - len(name))
875
+ else:
876
+ tag = name[:4]
877
+ return tag, dict(en=name)
878
+
879
+
880
+ class AbstractAxisDescriptor(SimpleDescriptor):
881
+ flavor = "axis"
882
+
883
+ def __init__(
884
+ self,
885
+ *,
886
+ tag=None,
887
+ name=None,
888
+ labelNames=None,
889
+ hidden=False,
890
+ map=None,
891
+ axisOrdering=None,
892
+ axisLabels=None,
893
+ ):
894
+ # opentype tag for this axis
895
+ self.tag = tag
896
+ """string. Four letter tag for this axis. Some might be
897
+ registered at the `OpenType
898
+ specification <https://www.microsoft.com/typography/otspec/fvar.htm#VAT>`__.
899
+ Privately-defined axis tags must begin with an uppercase letter and
900
+ use only uppercase letters or digits.
901
+ """
902
+ # name of the axis used in locations
903
+ self.name = name
904
+ """string. Name of the axis as it is used in the location dicts.
905
+
906
+ MutatorMath + varLib.
907
+ """
908
+ # names for UI purposes, if this is not a standard axis,
909
+ self.labelNames = labelNames or {}
910
+ """dict. When defining a non-registered axis, it will be
911
+ necessary to define user-facing readable names for the axis. Keyed by
912
+ xml:lang code. Values are required to be ``unicode`` strings, even if
913
+ they only contain ASCII characters.
914
+ """
915
+ self.hidden = hidden
916
+ """bool. Whether this axis should be hidden in user interfaces.
917
+ """
918
+ self.map = map or []
919
+ """list of input / output values that can describe a warp of user space
920
+ to design space coordinates. If no map values are present, it is assumed
921
+ user space is the same as design space, as in [(minimum, minimum),
922
+ (maximum, maximum)].
923
+
924
+ varLib.
925
+ """
926
+ self.axisOrdering = axisOrdering
927
+ """STAT table field ``axisOrdering``.
928
+
929
+ See: `OTSpec STAT Axis Record <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-records>`_
930
+
931
+ .. versionadded:: 5.0
932
+ """
933
+ self.axisLabels: List[AxisLabelDescriptor] = axisLabels or []
934
+ """STAT table entries for Axis Value Tables format 1, 2, 3.
935
+
936
+ See: `OTSpec STAT Axis Value Tables <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-value-tables>`_
937
+
938
+ .. versionadded:: 5.0
939
+ """
940
+
941
+
942
+ class AxisDescriptor(AbstractAxisDescriptor):
943
+ """Simple container for the axis data.
944
+
945
+ Add more localisations?
946
+
947
+ .. code:: python
948
+
949
+ a1 = AxisDescriptor()
950
+ a1.minimum = 1
951
+ a1.maximum = 1000
952
+ a1.default = 400
953
+ a1.name = "weight"
954
+ a1.tag = "wght"
955
+ a1.labelNames['fa-IR'] = "قطر"
956
+ a1.labelNames['en'] = "Wéíght"
957
+ a1.map = [(1.0, 10.0), (400.0, 66.0), (1000.0, 990.0)]
958
+ a1.axisOrdering = 1
959
+ a1.axisLabels = [
960
+ AxisLabelDescriptor(name="Regular", userValue=400, elidable=True)
961
+ ]
962
+ doc.addAxis(a1)
963
+ """
964
+
965
+ _attrs = [
966
+ "tag",
967
+ "name",
968
+ "maximum",
969
+ "minimum",
970
+ "default",
971
+ "map",
972
+ "axisOrdering",
973
+ "axisLabels",
974
+ ]
975
+
976
+ def __init__(
977
+ self,
978
+ *,
979
+ tag=None,
980
+ name=None,
981
+ labelNames=None,
982
+ minimum=None,
983
+ default=None,
984
+ maximum=None,
985
+ hidden=False,
986
+ map=None,
987
+ axisOrdering=None,
988
+ axisLabels=None,
989
+ ):
990
+ super().__init__(
991
+ tag=tag,
992
+ name=name,
993
+ labelNames=labelNames,
994
+ hidden=hidden,
995
+ map=map,
996
+ axisOrdering=axisOrdering,
997
+ axisLabels=axisLabels,
998
+ )
999
+ self.minimum = minimum
1000
+ """number. The minimum value for this axis in user space.
1001
+
1002
+ MutatorMath + varLib.
1003
+ """
1004
+ self.maximum = maximum
1005
+ """number. The maximum value for this axis in user space.
1006
+
1007
+ MutatorMath + varLib.
1008
+ """
1009
+ self.default = default
1010
+ """number. The default value for this axis, i.e. when a new location is
1011
+ created, this is the value this axis will get in user space.
1012
+
1013
+ MutatorMath + varLib.
1014
+ """
1015
+
1016
+ def serialize(self):
1017
+ # output to a dict, used in testing
1018
+ return dict(
1019
+ tag=self.tag,
1020
+ name=self.name,
1021
+ labelNames=self.labelNames,
1022
+ maximum=self.maximum,
1023
+ minimum=self.minimum,
1024
+ default=self.default,
1025
+ hidden=self.hidden,
1026
+ map=self.map,
1027
+ axisOrdering=self.axisOrdering,
1028
+ axisLabels=self.axisLabels,
1029
+ )
1030
+
1031
+ def map_forward(self, v):
1032
+ """Maps value from axis mapping's input (user) to output (design)."""
1033
+ from fontTools.varLib.models import piecewiseLinearMap
1034
+
1035
+ if not self.map:
1036
+ return v
1037
+ return piecewiseLinearMap(v, {k: v for k, v in self.map})
1038
+
1039
+ def map_backward(self, v):
1040
+ """Maps value from axis mapping's output (design) to input (user)."""
1041
+ from fontTools.varLib.models import piecewiseLinearMap
1042
+
1043
+ if isinstance(v, tuple):
1044
+ v = v[0]
1045
+ if not self.map:
1046
+ return v
1047
+ return piecewiseLinearMap(v, {v: k for k, v in self.map})
1048
+
1049
+
1050
+ class DiscreteAxisDescriptor(AbstractAxisDescriptor):
1051
+ """Container for discrete axis data.
1052
+
1053
+ Use this for axes that do not interpolate. The main difference from a
1054
+ continuous axis is that a continuous axis has a ``minimum`` and ``maximum``,
1055
+ while a discrete axis has a list of ``values``.
1056
+
1057
+ Example: an Italic axis with 2 stops, Roman and Italic, that are not
1058
+ compatible. The axis still allows to bind together the full font family,
1059
+ which is useful for the STAT table, however it can't become a variation
1060
+ axis in a VF.
1061
+
1062
+ .. code:: python
1063
+
1064
+ a2 = DiscreteAxisDescriptor()
1065
+ a2.values = [0, 1]
1066
+ a2.default = 0
1067
+ a2.name = "Italic"
1068
+ a2.tag = "ITAL"
1069
+ a2.labelNames['fr'] = "Italique"
1070
+ a2.map = [(0, 0), (1, -11)]
1071
+ a2.axisOrdering = 2
1072
+ a2.axisLabels = [
1073
+ AxisLabelDescriptor(name="Roman", userValue=0, elidable=True)
1074
+ ]
1075
+ doc.addAxis(a2)
1076
+
1077
+ .. versionadded:: 5.0
1078
+ """
1079
+
1080
+ flavor = "axis"
1081
+ _attrs = ("tag", "name", "values", "default", "map", "axisOrdering", "axisLabels")
1082
+
1083
+ def __init__(
1084
+ self,
1085
+ *,
1086
+ tag=None,
1087
+ name=None,
1088
+ labelNames=None,
1089
+ values=None,
1090
+ default=None,
1091
+ hidden=False,
1092
+ map=None,
1093
+ axisOrdering=None,
1094
+ axisLabels=None,
1095
+ ):
1096
+ super().__init__(
1097
+ tag=tag,
1098
+ name=name,
1099
+ labelNames=labelNames,
1100
+ hidden=hidden,
1101
+ map=map,
1102
+ axisOrdering=axisOrdering,
1103
+ axisLabels=axisLabels,
1104
+ )
1105
+ self.default: float = default
1106
+ """The default value for this axis, i.e. when a new location is
1107
+ created, this is the value this axis will get in user space.
1108
+
1109
+ However, this default value is less important than in continuous axes:
1110
+
1111
+ - it doesn't define the "neutral" version of outlines from which
1112
+ deltas would apply, as this axis does not interpolate.
1113
+ - it doesn't provide the reference glyph set for the designspace, as
1114
+ fonts at each value can have different glyph sets.
1115
+ """
1116
+ self.values: List[float] = values or []
1117
+ """List of possible values for this axis. Contrary to continuous axes,
1118
+ only the values in this list can be taken by the axis, nothing in-between.
1119
+ """
1120
+
1121
+ def map_forward(self, value):
1122
+ """Maps value from axis mapping's input to output.
1123
+
1124
+ Returns value unchanged if no mapping entry is found.
1125
+
1126
+ Note: for discrete axes, each value must have its mapping entry, if
1127
+ you intend that value to be mapped.
1128
+ """
1129
+ return next((v for k, v in self.map if k == value), value)
1130
+
1131
+ def map_backward(self, value):
1132
+ """Maps value from axis mapping's output to input.
1133
+
1134
+ Returns value unchanged if no mapping entry is found.
1135
+
1136
+ Note: for discrete axes, each value must have its mapping entry, if
1137
+ you intend that value to be mapped.
1138
+ """
1139
+ if isinstance(value, tuple):
1140
+ value = value[0]
1141
+ return next((k for k, v in self.map if v == value), value)
1142
+
1143
+
1144
+ class AxisLabelDescriptor(SimpleDescriptor):
1145
+ """Container for axis label data.
1146
+
1147
+ Analogue of OpenType's STAT data for a single axis (formats 1, 2 and 3).
1148
+ All values are user values.
1149
+ See: `OTSpec STAT Axis value table, format 1, 2, 3 <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-value-table-format-1>`_
1150
+
1151
+ The STAT format of the Axis value depends on which field are filled-in,
1152
+ see :meth:`getFormat`
1153
+
1154
+ .. versionadded:: 5.0
1155
+ """
1156
+
1157
+ flavor = "label"
1158
+ _attrs = (
1159
+ "userMinimum",
1160
+ "userValue",
1161
+ "userMaximum",
1162
+ "name",
1163
+ "elidable",
1164
+ "olderSibling",
1165
+ "linkedUserValue",
1166
+ "labelNames",
1167
+ )
1168
+
1169
+ def __init__(
1170
+ self,
1171
+ *,
1172
+ name,
1173
+ userValue,
1174
+ userMinimum=None,
1175
+ userMaximum=None,
1176
+ elidable=False,
1177
+ olderSibling=False,
1178
+ linkedUserValue=None,
1179
+ labelNames=None,
1180
+ ):
1181
+ self.userMinimum: Optional[float] = userMinimum
1182
+ """STAT field ``rangeMinValue`` (format 2)."""
1183
+ self.userValue: float = userValue
1184
+ """STAT field ``value`` (format 1, 3) or ``nominalValue`` (format 2)."""
1185
+ self.userMaximum: Optional[float] = userMaximum
1186
+ """STAT field ``rangeMaxValue`` (format 2)."""
1187
+ self.name: str = name
1188
+ """Label for this axis location, STAT field ``valueNameID``."""
1189
+ self.elidable: bool = elidable
1190
+ """STAT flag ``ELIDABLE_AXIS_VALUE_NAME``.
1191
+
1192
+ See: `OTSpec STAT Flags <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#flags>`_
1193
+ """
1194
+ self.olderSibling: bool = olderSibling
1195
+ """STAT flag ``OLDER_SIBLING_FONT_ATTRIBUTE``.
1196
+
1197
+ See: `OTSpec STAT Flags <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#flags>`_
1198
+ """
1199
+ self.linkedUserValue: Optional[float] = linkedUserValue
1200
+ """STAT field ``linkedValue`` (format 3)."""
1201
+ self.labelNames: MutableMapping[str, str] = labelNames or {}
1202
+ """User-facing translations of this location's label. Keyed by
1203
+ ``xml:lang`` code.
1204
+ """
1205
+
1206
+ def getFormat(self) -> int:
1207
+ """Determine which format of STAT Axis value to use to encode this label.
1208
+
1209
+ =========== ========= =========== =========== ===============
1210
+ STAT Format userValue userMinimum userMaximum linkedUserValue
1211
+ =========== ========= =========== =========== ===============
1212
+ 1 ✅ ❌ ❌ ❌
1213
+ 2 ✅ ✅ ✅ ❌
1214
+ 3 ✅ ❌ ❌ ✅
1215
+ =========== ========= =========== =========== ===============
1216
+ """
1217
+ if self.linkedUserValue is not None:
1218
+ return 3
1219
+ if self.userMinimum is not None or self.userMaximum is not None:
1220
+ return 2
1221
+ return 1
1222
+
1223
+ @property
1224
+ def defaultName(self) -> str:
1225
+ """Return the English name from :attr:`labelNames` or the :attr:`name`."""
1226
+ return self.labelNames.get("en") or self.name
1227
+
1228
+
1229
+ class LocationLabelDescriptor(SimpleDescriptor):
1230
+ """Container for location label data.
1231
+
1232
+ Analogue of OpenType's STAT data for a free-floating location (format 4).
1233
+ All values are user values.
1234
+
1235
+ See: `OTSpec STAT Axis value table, format 4 <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#axis-value-table-format-4>`_
1236
+
1237
+ .. versionadded:: 5.0
1238
+ """
1239
+
1240
+ flavor = "label"
1241
+ _attrs = ("name", "elidable", "olderSibling", "userLocation", "labelNames")
1242
+
1243
+ def __init__(
1244
+ self,
1245
+ *,
1246
+ name,
1247
+ userLocation,
1248
+ elidable=False,
1249
+ olderSibling=False,
1250
+ labelNames=None,
1251
+ ):
1252
+ self.name: str = name
1253
+ """Label for this named location, STAT field ``valueNameID``."""
1254
+ self.userLocation: SimpleLocationDict = userLocation or {}
1255
+ """Location in user coordinates along each axis.
1256
+
1257
+ If an axis is not mentioned, it is assumed to be at its default location.
1258
+
1259
+ .. seealso:: This may be only part of the full location. See:
1260
+ :meth:`getFullUserLocation`
1261
+ """
1262
+ self.elidable: bool = elidable
1263
+ """STAT flag ``ELIDABLE_AXIS_VALUE_NAME``.
1264
+
1265
+ See: `OTSpec STAT Flags <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#flags>`_
1266
+ """
1267
+ self.olderSibling: bool = olderSibling
1268
+ """STAT flag ``OLDER_SIBLING_FONT_ATTRIBUTE``.
1269
+
1270
+ See: `OTSpec STAT Flags <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#flags>`_
1271
+ """
1272
+ self.labelNames: Dict[str, str] = labelNames or {}
1273
+ """User-facing translations of this location's label. Keyed by
1274
+ xml:lang code.
1275
+ """
1276
+
1277
+ @property
1278
+ def defaultName(self) -> str:
1279
+ """Return the English name from :attr:`labelNames` or the :attr:`name`."""
1280
+ return self.labelNames.get("en") or self.name
1281
+
1282
+ def getFullUserLocation(self, doc: "DesignSpaceDocument") -> SimpleLocationDict:
1283
+ """Get the complete user location of this label, by combining data
1284
+ from the explicit user location and default axis values.
1285
+
1286
+ .. versionadded:: 5.0
1287
+ """
1288
+ return {
1289
+ axis.name: self.userLocation.get(axis.name, axis.default)
1290
+ for axis in doc.axes
1291
+ }
1292
+
1293
+
1294
+ class VariableFontDescriptor(SimpleDescriptor):
1295
+ """Container for variable fonts, sub-spaces of the Designspace.
1296
+
1297
+ Use-cases:
1298
+
1299
+ - From a single DesignSpace with discrete axes, define 1 variable font
1300
+ per value on the discrete axes. Before version 5, you would have needed
1301
+ 1 DesignSpace per such variable font, and a lot of data duplication.
1302
+ - From a big variable font with many axes, define subsets of that variable
1303
+ font that only include some axes and freeze other axes at a given location.
1304
+
1305
+ .. versionadded:: 5.0
1306
+ """
1307
+
1308
+ flavor = "variable-font"
1309
+ _attrs = ("filename", "axisSubsets", "lib")
1310
+
1311
+ filename = posixpath_property("_filename")
1312
+
1313
+ def __init__(self, *, name, filename=None, axisSubsets=None, lib=None):
1314
+ self.name: str = name
1315
+ """string, required. Name of this variable to identify it during the
1316
+ build process and from other parts of the document, and also as a
1317
+ filename in case the filename property is empty.
1318
+
1319
+ VarLib.
1320
+ """
1321
+ self.filename: str = filename
1322
+ """string, optional. Relative path to the variable font file, **as it is
1323
+ in the document**. The file may or may not exist.
1324
+
1325
+ If not specified, the :attr:`name` will be used as a basename for the file.
1326
+
1327
+ .. note::
1328
+ This is intended to be a simple filename (basename or stem) only.
1329
+ Build tools will only use the basename component and ignore any
1330
+ directory separators for security reasons.
1331
+ """
1332
+ self.axisSubsets: List[
1333
+ Union[RangeAxisSubsetDescriptor, ValueAxisSubsetDescriptor]
1334
+ ] = (axisSubsets or [])
1335
+ """Axis subsets to include in this variable font.
1336
+
1337
+ If an axis is not mentioned, assume that we only want the default
1338
+ location of that axis (same as a :class:`ValueAxisSubsetDescriptor`).
1339
+ """
1340
+ self.lib: MutableMapping[str, Any] = lib or {}
1341
+ """Custom data associated with this variable font."""
1342
+
1343
+
1344
+ class RangeAxisSubsetDescriptor(SimpleDescriptor):
1345
+ """Subset of a continuous axis to include in a variable font.
1346
+
1347
+ .. versionadded:: 5.0
1348
+ """
1349
+
1350
+ flavor = "axis-subset"
1351
+ _attrs = ("name", "userMinimum", "userDefault", "userMaximum")
1352
+
1353
+ def __init__(
1354
+ self, *, name, userMinimum=-math.inf, userDefault=None, userMaximum=math.inf
1355
+ ):
1356
+ self.name: str = name
1357
+ """Name of the :class:`AxisDescriptor` to subset."""
1358
+ self.userMinimum: float = userMinimum
1359
+ """New minimum value of the axis in the target variable font.
1360
+ If not specified, assume the same minimum value as the full axis.
1361
+ (default = ``-math.inf``)
1362
+ """
1363
+ self.userDefault: Optional[float] = userDefault
1364
+ """New default value of the axis in the target variable font.
1365
+ If not specified, assume the same default value as the full axis.
1366
+ (default = ``None``)
1367
+ """
1368
+ self.userMaximum: float = userMaximum
1369
+ """New maximum value of the axis in the target variable font.
1370
+ If not specified, assume the same maximum value as the full axis.
1371
+ (default = ``math.inf``)
1372
+ """
1373
+
1374
+
1375
+ class ValueAxisSubsetDescriptor(SimpleDescriptor):
1376
+ """Single value of a discrete or continuous axis to use in a variable font.
1377
+
1378
+ .. versionadded:: 5.0
1379
+ """
1380
+
1381
+ flavor = "axis-subset"
1382
+ _attrs = ("name", "userValue")
1383
+
1384
+ def __init__(self, *, name, userValue):
1385
+ self.name: str = name
1386
+ """Name of the :class:`AxisDescriptor` or :class:`DiscreteAxisDescriptor`
1387
+ to "snapshot" or "freeze".
1388
+ """
1389
+ self.userValue: float = userValue
1390
+ """Value in user coordinates at which to freeze the given axis."""
1391
+
1392
+
1393
+ class BaseDocWriter(object):
1394
+ _whiteSpace = " "
1395
+ axisDescriptorClass = AxisDescriptor
1396
+ discreteAxisDescriptorClass = DiscreteAxisDescriptor
1397
+ axisLabelDescriptorClass = AxisLabelDescriptor
1398
+ axisMappingDescriptorClass = AxisMappingDescriptor
1399
+ locationLabelDescriptorClass = LocationLabelDescriptor
1400
+ ruleDescriptorClass = RuleDescriptor
1401
+ sourceDescriptorClass = SourceDescriptor
1402
+ variableFontDescriptorClass = VariableFontDescriptor
1403
+ valueAxisSubsetDescriptorClass = ValueAxisSubsetDescriptor
1404
+ rangeAxisSubsetDescriptorClass = RangeAxisSubsetDescriptor
1405
+ instanceDescriptorClass = InstanceDescriptor
1406
+
1407
+ @classmethod
1408
+ def getAxisDecriptor(cls):
1409
+ return cls.axisDescriptorClass()
1410
+
1411
+ @classmethod
1412
+ def getAxisMappingDescriptor(cls):
1413
+ return cls.axisMappingDescriptorClass()
1414
+
1415
+ @classmethod
1416
+ def getSourceDescriptor(cls):
1417
+ return cls.sourceDescriptorClass()
1418
+
1419
+ @classmethod
1420
+ def getInstanceDescriptor(cls):
1421
+ return cls.instanceDescriptorClass()
1422
+
1423
+ @classmethod
1424
+ def getRuleDescriptor(cls):
1425
+ return cls.ruleDescriptorClass()
1426
+
1427
+ def __init__(self, documentPath, documentObject: DesignSpaceDocument):
1428
+ self.path = documentPath
1429
+ self.documentObject = documentObject
1430
+ self.effectiveFormatTuple = self._getEffectiveFormatTuple()
1431
+ self.root = ET.Element("designspace")
1432
+
1433
+ def write(self, pretty=True, encoding="UTF-8", xml_declaration=True):
1434
+ self.root.attrib["format"] = ".".join(str(i) for i in self.effectiveFormatTuple)
1435
+
1436
+ if (
1437
+ self.documentObject.axes
1438
+ or self.documentObject.axisMappings
1439
+ or self.documentObject.elidedFallbackName is not None
1440
+ ):
1441
+ axesElement = ET.Element("axes")
1442
+ if self.documentObject.elidedFallbackName is not None:
1443
+ axesElement.attrib["elidedfallbackname"] = (
1444
+ self.documentObject.elidedFallbackName
1445
+ )
1446
+ self.root.append(axesElement)
1447
+ for axisObject in self.documentObject.axes:
1448
+ self._addAxis(axisObject)
1449
+
1450
+ if self.documentObject.axisMappings:
1451
+ mappingsElement = None
1452
+ lastGroup = object()
1453
+ for mappingObject in self.documentObject.axisMappings:
1454
+ if getattr(mappingObject, "groupDescription", None) != lastGroup:
1455
+ if mappingsElement is not None:
1456
+ self.root.findall(".axes")[0].append(mappingsElement)
1457
+ lastGroup = getattr(mappingObject, "groupDescription", None)
1458
+ mappingsElement = ET.Element("mappings")
1459
+ if lastGroup is not None:
1460
+ mappingsElement.attrib["description"] = lastGroup
1461
+ self._addAxisMapping(mappingsElement, mappingObject)
1462
+ if mappingsElement is not None:
1463
+ self.root.findall(".axes")[0].append(mappingsElement)
1464
+
1465
+ if self.documentObject.locationLabels:
1466
+ labelsElement = ET.Element("labels")
1467
+ for labelObject in self.documentObject.locationLabels:
1468
+ self._addLocationLabel(labelsElement, labelObject)
1469
+ self.root.append(labelsElement)
1470
+
1471
+ if self.documentObject.rules:
1472
+ if getattr(self.documentObject, "rulesProcessingLast", False):
1473
+ attributes = {"processing": "last"}
1474
+ else:
1475
+ attributes = {}
1476
+ self.root.append(ET.Element("rules", attributes))
1477
+ for ruleObject in self.documentObject.rules:
1478
+ self._addRule(ruleObject)
1479
+
1480
+ if self.documentObject.sources:
1481
+ self.root.append(ET.Element("sources"))
1482
+ for sourceObject in self.documentObject.sources:
1483
+ self._addSource(sourceObject)
1484
+
1485
+ if self.documentObject.variableFonts:
1486
+ variableFontsElement = ET.Element("variable-fonts")
1487
+ for variableFont in self.documentObject.variableFonts:
1488
+ self._addVariableFont(variableFontsElement, variableFont)
1489
+ self.root.append(variableFontsElement)
1490
+
1491
+ if self.documentObject.instances:
1492
+ self.root.append(ET.Element("instances"))
1493
+ for instanceObject in self.documentObject.instances:
1494
+ self._addInstance(instanceObject)
1495
+
1496
+ if self.documentObject.lib:
1497
+ self._addLib(self.root, self.documentObject.lib, 2)
1498
+
1499
+ tree = ET.ElementTree(self.root)
1500
+ tree.write(
1501
+ self.path,
1502
+ encoding=encoding,
1503
+ method="xml",
1504
+ xml_declaration=xml_declaration,
1505
+ pretty_print=pretty,
1506
+ )
1507
+
1508
+ def _getEffectiveFormatTuple(self):
1509
+ """Try to use the version specified in the document, or a sufficiently
1510
+ recent version to be able to encode what the document contains.
1511
+ """
1512
+ minVersion = self.documentObject.formatTuple
1513
+ if (
1514
+ any(
1515
+ hasattr(axis, "values")
1516
+ or axis.axisOrdering is not None
1517
+ or axis.axisLabels
1518
+ for axis in self.documentObject.axes
1519
+ )
1520
+ or self.documentObject.locationLabels
1521
+ or any(source.localisedFamilyName for source in self.documentObject.sources)
1522
+ or self.documentObject.variableFonts
1523
+ or any(
1524
+ instance.locationLabel or instance.userLocation
1525
+ for instance in self.documentObject.instances
1526
+ )
1527
+ ):
1528
+ if minVersion < (5, 0):
1529
+ minVersion = (5, 0)
1530
+ if self.documentObject.axisMappings:
1531
+ if minVersion < (5, 1):
1532
+ minVersion = (5, 1)
1533
+ return minVersion
1534
+
1535
+ def _makeLocationElement(self, locationObject, name=None):
1536
+ """Convert Location dict to a locationElement."""
1537
+ locElement = ET.Element("location")
1538
+ if name is not None:
1539
+ locElement.attrib["name"] = name
1540
+ validatedLocation = self.documentObject.newDefaultLocation()
1541
+ for axisName, axisValue in locationObject.items():
1542
+ if axisName in validatedLocation:
1543
+ # only accept values we know
1544
+ validatedLocation[axisName] = axisValue
1545
+ for dimensionName, dimensionValue in validatedLocation.items():
1546
+ dimElement = ET.Element("dimension")
1547
+ dimElement.attrib["name"] = dimensionName
1548
+ if type(dimensionValue) == tuple:
1549
+ dimElement.attrib["xvalue"] = self.intOrFloat(dimensionValue[0])
1550
+ dimElement.attrib["yvalue"] = self.intOrFloat(dimensionValue[1])
1551
+ else:
1552
+ dimElement.attrib["xvalue"] = self.intOrFloat(dimensionValue)
1553
+ locElement.append(dimElement)
1554
+ return locElement, validatedLocation
1555
+
1556
+ def intOrFloat(self, num):
1557
+ if int(num) == num:
1558
+ return "%d" % num
1559
+ return ("%f" % num).rstrip("0").rstrip(".")
1560
+
1561
+ def _addRule(self, ruleObject):
1562
+ # if none of the conditions have minimum or maximum values, do not add the rule.
1563
+ ruleElement = ET.Element("rule")
1564
+ if ruleObject.name is not None:
1565
+ ruleElement.attrib["name"] = ruleObject.name
1566
+ for conditions in ruleObject.conditionSets:
1567
+ conditionsetElement = ET.Element("conditionset")
1568
+ for cond in conditions:
1569
+ if cond.get("minimum") is None and cond.get("maximum") is None:
1570
+ # neither is defined, don't add this condition
1571
+ continue
1572
+ conditionElement = ET.Element("condition")
1573
+ conditionElement.attrib["name"] = cond.get("name")
1574
+ if cond.get("minimum") is not None:
1575
+ conditionElement.attrib["minimum"] = self.intOrFloat(
1576
+ cond.get("minimum")
1577
+ )
1578
+ if cond.get("maximum") is not None:
1579
+ conditionElement.attrib["maximum"] = self.intOrFloat(
1580
+ cond.get("maximum")
1581
+ )
1582
+ conditionsetElement.append(conditionElement)
1583
+ if len(conditionsetElement):
1584
+ ruleElement.append(conditionsetElement)
1585
+ for sub in ruleObject.subs:
1586
+ subElement = ET.Element("sub")
1587
+ subElement.attrib["name"] = sub[0]
1588
+ subElement.attrib["with"] = sub[1]
1589
+ ruleElement.append(subElement)
1590
+ if len(ruleElement):
1591
+ self.root.findall(".rules")[0].append(ruleElement)
1592
+
1593
+ def _addAxis(self, axisObject):
1594
+ axisElement = ET.Element("axis")
1595
+ axisElement.attrib["tag"] = axisObject.tag
1596
+ axisElement.attrib["name"] = axisObject.name
1597
+ self._addLabelNames(axisElement, axisObject.labelNames)
1598
+ if axisObject.map:
1599
+ for inputValue, outputValue in axisObject.map:
1600
+ mapElement = ET.Element("map")
1601
+ mapElement.attrib["input"] = self.intOrFloat(inputValue)
1602
+ mapElement.attrib["output"] = self.intOrFloat(outputValue)
1603
+ axisElement.append(mapElement)
1604
+ if axisObject.axisOrdering is not None or axisObject.axisLabels:
1605
+ labelsElement = ET.Element("labels")
1606
+ if axisObject.axisOrdering is not None:
1607
+ labelsElement.attrib["ordering"] = str(axisObject.axisOrdering)
1608
+ for label in axisObject.axisLabels:
1609
+ self._addAxisLabel(labelsElement, label)
1610
+ axisElement.append(labelsElement)
1611
+ if hasattr(axisObject, "minimum"):
1612
+ axisElement.attrib["minimum"] = self.intOrFloat(axisObject.minimum)
1613
+ axisElement.attrib["maximum"] = self.intOrFloat(axisObject.maximum)
1614
+ elif hasattr(axisObject, "values"):
1615
+ axisElement.attrib["values"] = " ".join(
1616
+ self.intOrFloat(v) for v in axisObject.values
1617
+ )
1618
+ axisElement.attrib["default"] = self.intOrFloat(axisObject.default)
1619
+ if axisObject.hidden:
1620
+ axisElement.attrib["hidden"] = "1"
1621
+ self.root.findall(".axes")[0].append(axisElement)
1622
+
1623
+ def _addAxisMapping(self, mappingsElement, mappingObject):
1624
+ mappingElement = ET.Element("mapping")
1625
+ if getattr(mappingObject, "description", None) is not None:
1626
+ mappingElement.attrib["description"] = mappingObject.description
1627
+ for what in ("inputLocation", "outputLocation"):
1628
+ whatObject = getattr(mappingObject, what, None)
1629
+ if whatObject is None:
1630
+ continue
1631
+ whatElement = ET.Element(what[:-8])
1632
+ mappingElement.append(whatElement)
1633
+
1634
+ for name, value in whatObject.items():
1635
+ dimensionElement = ET.Element("dimension")
1636
+ dimensionElement.attrib["name"] = name
1637
+ dimensionElement.attrib["xvalue"] = self.intOrFloat(value)
1638
+ whatElement.append(dimensionElement)
1639
+
1640
+ mappingsElement.append(mappingElement)
1641
+
1642
+ def _addAxisLabel(
1643
+ self, axisElement: ET.Element, label: AxisLabelDescriptor
1644
+ ) -> None:
1645
+ labelElement = ET.Element("label")
1646
+ labelElement.attrib["uservalue"] = self.intOrFloat(label.userValue)
1647
+ if label.userMinimum is not None:
1648
+ labelElement.attrib["userminimum"] = self.intOrFloat(label.userMinimum)
1649
+ if label.userMaximum is not None:
1650
+ labelElement.attrib["usermaximum"] = self.intOrFloat(label.userMaximum)
1651
+ labelElement.attrib["name"] = label.name
1652
+ if label.elidable:
1653
+ labelElement.attrib["elidable"] = "true"
1654
+ if label.olderSibling:
1655
+ labelElement.attrib["oldersibling"] = "true"
1656
+ if label.linkedUserValue is not None:
1657
+ labelElement.attrib["linkeduservalue"] = self.intOrFloat(
1658
+ label.linkedUserValue
1659
+ )
1660
+ self._addLabelNames(labelElement, label.labelNames)
1661
+ axisElement.append(labelElement)
1662
+
1663
+ def _addLabelNames(self, parentElement, labelNames):
1664
+ for languageCode, labelName in sorted(labelNames.items()):
1665
+ languageElement = ET.Element("labelname")
1666
+ languageElement.attrib[XML_LANG] = languageCode
1667
+ languageElement.text = labelName
1668
+ parentElement.append(languageElement)
1669
+
1670
+ def _addLocationLabel(
1671
+ self, parentElement: ET.Element, label: LocationLabelDescriptor
1672
+ ) -> None:
1673
+ labelElement = ET.Element("label")
1674
+ labelElement.attrib["name"] = label.name
1675
+ if label.elidable:
1676
+ labelElement.attrib["elidable"] = "true"
1677
+ if label.olderSibling:
1678
+ labelElement.attrib["oldersibling"] = "true"
1679
+ self._addLabelNames(labelElement, label.labelNames)
1680
+ self._addLocationElement(labelElement, userLocation=label.userLocation)
1681
+ parentElement.append(labelElement)
1682
+
1683
+ def _addLocationElement(
1684
+ self,
1685
+ parentElement,
1686
+ *,
1687
+ designLocation: AnisotropicLocationDict = None,
1688
+ userLocation: SimpleLocationDict = None,
1689
+ ):
1690
+ locElement = ET.Element("location")
1691
+ for axis in self.documentObject.axes:
1692
+ if designLocation is not None and axis.name in designLocation:
1693
+ dimElement = ET.Element("dimension")
1694
+ dimElement.attrib["name"] = axis.name
1695
+ value = designLocation[axis.name]
1696
+ if isinstance(value, tuple):
1697
+ dimElement.attrib["xvalue"] = self.intOrFloat(value[0])
1698
+ dimElement.attrib["yvalue"] = self.intOrFloat(value[1])
1699
+ else:
1700
+ dimElement.attrib["xvalue"] = self.intOrFloat(value)
1701
+ locElement.append(dimElement)
1702
+ elif userLocation is not None and axis.name in userLocation:
1703
+ dimElement = ET.Element("dimension")
1704
+ dimElement.attrib["name"] = axis.name
1705
+ value = userLocation[axis.name]
1706
+ dimElement.attrib["uservalue"] = self.intOrFloat(value)
1707
+ locElement.append(dimElement)
1708
+ if len(locElement) > 0:
1709
+ parentElement.append(locElement)
1710
+
1711
+ def _addInstance(self, instanceObject):
1712
+ instanceElement = ET.Element("instance")
1713
+ if instanceObject.name is not None:
1714
+ instanceElement.attrib["name"] = instanceObject.name
1715
+ if instanceObject.locationLabel is not None:
1716
+ instanceElement.attrib["location"] = instanceObject.locationLabel
1717
+ if instanceObject.familyName is not None:
1718
+ instanceElement.attrib["familyname"] = instanceObject.familyName
1719
+ if instanceObject.styleName is not None:
1720
+ instanceElement.attrib["stylename"] = instanceObject.styleName
1721
+ # add localisations
1722
+ if instanceObject.localisedStyleName:
1723
+ languageCodes = list(instanceObject.localisedStyleName.keys())
1724
+ languageCodes.sort()
1725
+ for code in languageCodes:
1726
+ if code == "en":
1727
+ continue # already stored in the element attribute
1728
+ localisedStyleNameElement = ET.Element("stylename")
1729
+ localisedStyleNameElement.attrib[XML_LANG] = code
1730
+ localisedStyleNameElement.text = instanceObject.getStyleName(code)
1731
+ instanceElement.append(localisedStyleNameElement)
1732
+ if instanceObject.localisedFamilyName:
1733
+ languageCodes = list(instanceObject.localisedFamilyName.keys())
1734
+ languageCodes.sort()
1735
+ for code in languageCodes:
1736
+ if code == "en":
1737
+ continue # already stored in the element attribute
1738
+ localisedFamilyNameElement = ET.Element("familyname")
1739
+ localisedFamilyNameElement.attrib[XML_LANG] = code
1740
+ localisedFamilyNameElement.text = instanceObject.getFamilyName(code)
1741
+ instanceElement.append(localisedFamilyNameElement)
1742
+ if instanceObject.localisedStyleMapStyleName:
1743
+ languageCodes = list(instanceObject.localisedStyleMapStyleName.keys())
1744
+ languageCodes.sort()
1745
+ for code in languageCodes:
1746
+ if code == "en":
1747
+ continue
1748
+ localisedStyleMapStyleNameElement = ET.Element("stylemapstylename")
1749
+ localisedStyleMapStyleNameElement.attrib[XML_LANG] = code
1750
+ localisedStyleMapStyleNameElement.text = (
1751
+ instanceObject.getStyleMapStyleName(code)
1752
+ )
1753
+ instanceElement.append(localisedStyleMapStyleNameElement)
1754
+ if instanceObject.localisedStyleMapFamilyName:
1755
+ languageCodes = list(instanceObject.localisedStyleMapFamilyName.keys())
1756
+ languageCodes.sort()
1757
+ for code in languageCodes:
1758
+ if code == "en":
1759
+ continue
1760
+ localisedStyleMapFamilyNameElement = ET.Element("stylemapfamilyname")
1761
+ localisedStyleMapFamilyNameElement.attrib[XML_LANG] = code
1762
+ localisedStyleMapFamilyNameElement.text = (
1763
+ instanceObject.getStyleMapFamilyName(code)
1764
+ )
1765
+ instanceElement.append(localisedStyleMapFamilyNameElement)
1766
+
1767
+ if self.effectiveFormatTuple >= (5, 0):
1768
+ if instanceObject.locationLabel is None:
1769
+ self._addLocationElement(
1770
+ instanceElement,
1771
+ designLocation=instanceObject.designLocation,
1772
+ userLocation=instanceObject.userLocation,
1773
+ )
1774
+ else:
1775
+ # Pre-version 5.0 code was validating and filling in the location
1776
+ # dict while writing it out, as preserved below.
1777
+ if instanceObject.location is not None:
1778
+ locationElement, instanceObject.location = self._makeLocationElement(
1779
+ instanceObject.location
1780
+ )
1781
+ instanceElement.append(locationElement)
1782
+ if instanceObject.filename is not None:
1783
+ instanceElement.attrib["filename"] = instanceObject.filename
1784
+ if instanceObject.postScriptFontName is not None:
1785
+ instanceElement.attrib["postscriptfontname"] = (
1786
+ instanceObject.postScriptFontName
1787
+ )
1788
+ if instanceObject.styleMapFamilyName is not None:
1789
+ instanceElement.attrib["stylemapfamilyname"] = (
1790
+ instanceObject.styleMapFamilyName
1791
+ )
1792
+ if instanceObject.styleMapStyleName is not None:
1793
+ instanceElement.attrib["stylemapstylename"] = (
1794
+ instanceObject.styleMapStyleName
1795
+ )
1796
+ if self.effectiveFormatTuple < (5, 0):
1797
+ # Deprecated members as of version 5.0
1798
+ if instanceObject.glyphs:
1799
+ if instanceElement.findall(".glyphs") == []:
1800
+ glyphsElement = ET.Element("glyphs")
1801
+ instanceElement.append(glyphsElement)
1802
+ glyphsElement = instanceElement.findall(".glyphs")[0]
1803
+ for glyphName, data in sorted(instanceObject.glyphs.items()):
1804
+ glyphElement = self._writeGlyphElement(
1805
+ instanceElement, instanceObject, glyphName, data
1806
+ )
1807
+ glyphsElement.append(glyphElement)
1808
+ if instanceObject.kerning:
1809
+ kerningElement = ET.Element("kerning")
1810
+ instanceElement.append(kerningElement)
1811
+ if instanceObject.info:
1812
+ infoElement = ET.Element("info")
1813
+ instanceElement.append(infoElement)
1814
+ self._addLib(instanceElement, instanceObject.lib, 4)
1815
+ self.root.findall(".instances")[0].append(instanceElement)
1816
+
1817
+ def _addSource(self, sourceObject):
1818
+ sourceElement = ET.Element("source")
1819
+ if sourceObject.filename is not None:
1820
+ sourceElement.attrib["filename"] = sourceObject.filename
1821
+ if sourceObject.name is not None:
1822
+ if sourceObject.name.find("temp_master") != 0:
1823
+ # do not save temporary source names
1824
+ sourceElement.attrib["name"] = sourceObject.name
1825
+ if sourceObject.familyName is not None:
1826
+ sourceElement.attrib["familyname"] = sourceObject.familyName
1827
+ if sourceObject.styleName is not None:
1828
+ sourceElement.attrib["stylename"] = sourceObject.styleName
1829
+ if sourceObject.layerName is not None:
1830
+ sourceElement.attrib["layer"] = sourceObject.layerName
1831
+ if sourceObject.localisedFamilyName:
1832
+ languageCodes = list(sourceObject.localisedFamilyName.keys())
1833
+ languageCodes.sort()
1834
+ for code in languageCodes:
1835
+ if code == "en":
1836
+ continue # already stored in the element attribute
1837
+ localisedFamilyNameElement = ET.Element("familyname")
1838
+ localisedFamilyNameElement.attrib[XML_LANG] = code
1839
+ localisedFamilyNameElement.text = sourceObject.getFamilyName(code)
1840
+ sourceElement.append(localisedFamilyNameElement)
1841
+ if sourceObject.copyLib:
1842
+ libElement = ET.Element("lib")
1843
+ libElement.attrib["copy"] = "1"
1844
+ sourceElement.append(libElement)
1845
+ if sourceObject.copyGroups:
1846
+ groupsElement = ET.Element("groups")
1847
+ groupsElement.attrib["copy"] = "1"
1848
+ sourceElement.append(groupsElement)
1849
+ if sourceObject.copyFeatures:
1850
+ featuresElement = ET.Element("features")
1851
+ featuresElement.attrib["copy"] = "1"
1852
+ sourceElement.append(featuresElement)
1853
+ if sourceObject.copyInfo or sourceObject.muteInfo:
1854
+ infoElement = ET.Element("info")
1855
+ if sourceObject.copyInfo:
1856
+ infoElement.attrib["copy"] = "1"
1857
+ if sourceObject.muteInfo:
1858
+ infoElement.attrib["mute"] = "1"
1859
+ sourceElement.append(infoElement)
1860
+ if sourceObject.muteKerning:
1861
+ kerningElement = ET.Element("kerning")
1862
+ kerningElement.attrib["mute"] = "1"
1863
+ sourceElement.append(kerningElement)
1864
+ if sourceObject.mutedGlyphNames:
1865
+ for name in sourceObject.mutedGlyphNames:
1866
+ glyphElement = ET.Element("glyph")
1867
+ glyphElement.attrib["name"] = name
1868
+ glyphElement.attrib["mute"] = "1"
1869
+ sourceElement.append(glyphElement)
1870
+ if self.effectiveFormatTuple >= (5, 0):
1871
+ self._addLocationElement(
1872
+ sourceElement, designLocation=sourceObject.location
1873
+ )
1874
+ else:
1875
+ # Pre-version 5.0 code was validating and filling in the location
1876
+ # dict while writing it out, as preserved below.
1877
+ locationElement, sourceObject.location = self._makeLocationElement(
1878
+ sourceObject.location
1879
+ )
1880
+ sourceElement.append(locationElement)
1881
+ self.root.findall(".sources")[0].append(sourceElement)
1882
+
1883
+ def _addVariableFont(
1884
+ self, parentElement: ET.Element, vf: VariableFontDescriptor
1885
+ ) -> None:
1886
+ vfElement = ET.Element("variable-font")
1887
+ vfElement.attrib["name"] = vf.name
1888
+ if vf.filename is not None:
1889
+ vfElement.attrib["filename"] = vf.filename
1890
+ if vf.axisSubsets:
1891
+ subsetsElement = ET.Element("axis-subsets")
1892
+ for subset in vf.axisSubsets:
1893
+ subsetElement = ET.Element("axis-subset")
1894
+ subsetElement.attrib["name"] = subset.name
1895
+ # Mypy doesn't support narrowing union types via hasattr()
1896
+ # https://mypy.readthedocs.io/en/stable/type_narrowing.html
1897
+ # TODO(Python 3.10): use TypeGuard
1898
+ if hasattr(subset, "userMinimum"):
1899
+ subset = cast(RangeAxisSubsetDescriptor, subset)
1900
+ if subset.userMinimum != -math.inf:
1901
+ subsetElement.attrib["userminimum"] = self.intOrFloat(
1902
+ subset.userMinimum
1903
+ )
1904
+ if subset.userMaximum != math.inf:
1905
+ subsetElement.attrib["usermaximum"] = self.intOrFloat(
1906
+ subset.userMaximum
1907
+ )
1908
+ if subset.userDefault is not None:
1909
+ subsetElement.attrib["userdefault"] = self.intOrFloat(
1910
+ subset.userDefault
1911
+ )
1912
+ elif hasattr(subset, "userValue"):
1913
+ subset = cast(ValueAxisSubsetDescriptor, subset)
1914
+ subsetElement.attrib["uservalue"] = self.intOrFloat(
1915
+ subset.userValue
1916
+ )
1917
+ subsetsElement.append(subsetElement)
1918
+ vfElement.append(subsetsElement)
1919
+ self._addLib(vfElement, vf.lib, 4)
1920
+ parentElement.append(vfElement)
1921
+
1922
+ def _addLib(self, parentElement: ET.Element, data: Any, indent_level: int) -> None:
1923
+ if not data:
1924
+ return
1925
+ libElement = ET.Element("lib")
1926
+ libElement.append(plistlib.totree(data, indent_level=indent_level))
1927
+ parentElement.append(libElement)
1928
+
1929
+ def _writeGlyphElement(self, instanceElement, instanceObject, glyphName, data):
1930
+ glyphElement = ET.Element("glyph")
1931
+ if data.get("mute"):
1932
+ glyphElement.attrib["mute"] = "1"
1933
+ if data.get("unicodes") is not None:
1934
+ glyphElement.attrib["unicode"] = " ".join(
1935
+ [hex(u) for u in data.get("unicodes")]
1936
+ )
1937
+ if data.get("instanceLocation") is not None:
1938
+ locationElement, data["instanceLocation"] = self._makeLocationElement(
1939
+ data.get("instanceLocation")
1940
+ )
1941
+ glyphElement.append(locationElement)
1942
+ if glyphName is not None:
1943
+ glyphElement.attrib["name"] = glyphName
1944
+ if data.get("note") is not None:
1945
+ noteElement = ET.Element("note")
1946
+ noteElement.text = data.get("note")
1947
+ glyphElement.append(noteElement)
1948
+ if data.get("masters") is not None:
1949
+ mastersElement = ET.Element("masters")
1950
+ for m in data.get("masters"):
1951
+ masterElement = ET.Element("master")
1952
+ if m.get("glyphName") is not None:
1953
+ masterElement.attrib["glyphname"] = m.get("glyphName")
1954
+ if m.get("font") is not None:
1955
+ masterElement.attrib["source"] = m.get("font")
1956
+ if m.get("location") is not None:
1957
+ locationElement, m["location"] = self._makeLocationElement(
1958
+ m.get("location")
1959
+ )
1960
+ masterElement.append(locationElement)
1961
+ mastersElement.append(masterElement)
1962
+ glyphElement.append(mastersElement)
1963
+ return glyphElement
1964
+
1965
+
1966
+ class BaseDocReader(LogMixin):
1967
+ axisDescriptorClass = AxisDescriptor
1968
+ discreteAxisDescriptorClass = DiscreteAxisDescriptor
1969
+ axisLabelDescriptorClass = AxisLabelDescriptor
1970
+ axisMappingDescriptorClass = AxisMappingDescriptor
1971
+ locationLabelDescriptorClass = LocationLabelDescriptor
1972
+ ruleDescriptorClass = RuleDescriptor
1973
+ sourceDescriptorClass = SourceDescriptor
1974
+ variableFontsDescriptorClass = VariableFontDescriptor
1975
+ valueAxisSubsetDescriptorClass = ValueAxisSubsetDescriptor
1976
+ rangeAxisSubsetDescriptorClass = RangeAxisSubsetDescriptor
1977
+ instanceDescriptorClass = InstanceDescriptor
1978
+
1979
+ def __init__(self, documentPath, documentObject):
1980
+ self.path = documentPath
1981
+ self.documentObject = documentObject
1982
+ tree = ET.parse(self.path)
1983
+ self.root = tree.getroot()
1984
+ self.documentObject.formatVersion = self.root.attrib.get("format", "3.0")
1985
+ self._axes = []
1986
+ self.rules = []
1987
+ self.sources = []
1988
+ self.instances = []
1989
+ self.axisDefaults = {}
1990
+ self._strictAxisNames = True
1991
+
1992
+ @classmethod
1993
+ def fromstring(cls, string, documentObject):
1994
+ f = BytesIO(tobytes(string, encoding="utf-8"))
1995
+ self = cls(f, documentObject)
1996
+ self.path = None
1997
+ return self
1998
+
1999
+ def read(self):
2000
+ self.readAxes()
2001
+ self.readLabels()
2002
+ self.readRules()
2003
+ self.readVariableFonts()
2004
+ self.readSources()
2005
+ self.readInstances()
2006
+ self.readLib()
2007
+
2008
+ def readRules(self):
2009
+ # we also need to read any conditions that are outside of a condition set.
2010
+ rules = []
2011
+ rulesElement = self.root.find(".rules")
2012
+ if rulesElement is not None:
2013
+ processingValue = rulesElement.attrib.get("processing", "first")
2014
+ if processingValue not in {"first", "last"}:
2015
+ raise DesignSpaceDocumentError(
2016
+ "<rules> processing attribute value is not valid: %r, "
2017
+ "expected 'first' or 'last'" % processingValue
2018
+ )
2019
+ self.documentObject.rulesProcessingLast = processingValue == "last"
2020
+ for ruleElement in self.root.findall(".rules/rule"):
2021
+ ruleObject = self.ruleDescriptorClass()
2022
+ ruleName = ruleObject.name = ruleElement.attrib.get("name")
2023
+ # read any stray conditions outside a condition set
2024
+ externalConditions = self._readConditionElements(
2025
+ ruleElement,
2026
+ ruleName,
2027
+ )
2028
+ if externalConditions:
2029
+ ruleObject.conditionSets.append(externalConditions)
2030
+ self.log.info(
2031
+ "Found stray rule conditions outside a conditionset. "
2032
+ "Wrapped them in a new conditionset."
2033
+ )
2034
+ # read the conditionsets
2035
+ for conditionSetElement in ruleElement.findall(".conditionset"):
2036
+ conditionSet = self._readConditionElements(
2037
+ conditionSetElement,
2038
+ ruleName,
2039
+ )
2040
+ if conditionSet is not None:
2041
+ ruleObject.conditionSets.append(conditionSet)
2042
+ for subElement in ruleElement.findall(".sub"):
2043
+ a = subElement.attrib["name"]
2044
+ b = subElement.attrib["with"]
2045
+ ruleObject.subs.append((a, b))
2046
+ rules.append(ruleObject)
2047
+ self.documentObject.rules = rules
2048
+
2049
+ def _readConditionElements(self, parentElement, ruleName=None):
2050
+ cds = []
2051
+ for conditionElement in parentElement.findall(".condition"):
2052
+ cd = {}
2053
+ cdMin = conditionElement.attrib.get("minimum")
2054
+ if cdMin is not None:
2055
+ cd["minimum"] = float(cdMin)
2056
+ else:
2057
+ # will allow these to be None, assume axis.minimum
2058
+ cd["minimum"] = None
2059
+ cdMax = conditionElement.attrib.get("maximum")
2060
+ if cdMax is not None:
2061
+ cd["maximum"] = float(cdMax)
2062
+ else:
2063
+ # will allow these to be None, assume axis.maximum
2064
+ cd["maximum"] = None
2065
+ cd["name"] = conditionElement.attrib.get("name")
2066
+ # # test for things
2067
+ if cd.get("minimum") is None and cd.get("maximum") is None:
2068
+ raise DesignSpaceDocumentError(
2069
+ "condition missing required minimum or maximum in rule"
2070
+ + (" '%s'" % ruleName if ruleName is not None else "")
2071
+ )
2072
+ cds.append(cd)
2073
+ return cds
2074
+
2075
+ def readAxes(self):
2076
+ # read the axes elements, including the warp map.
2077
+ axesElement = self.root.find(".axes")
2078
+ if axesElement is not None and "elidedfallbackname" in axesElement.attrib:
2079
+ self.documentObject.elidedFallbackName = axesElement.attrib[
2080
+ "elidedfallbackname"
2081
+ ]
2082
+ axisElements = self.root.findall(".axes/axis")
2083
+ if not axisElements:
2084
+ return
2085
+ for axisElement in axisElements:
2086
+ if (
2087
+ self.documentObject.formatTuple >= (5, 0)
2088
+ and "values" in axisElement.attrib
2089
+ ):
2090
+ axisObject = self.discreteAxisDescriptorClass()
2091
+ axisObject.values = [
2092
+ float(s) for s in axisElement.attrib["values"].split(" ")
2093
+ ]
2094
+ else:
2095
+ axisObject = self.axisDescriptorClass()
2096
+ axisObject.minimum = float(axisElement.attrib.get("minimum"))
2097
+ axisObject.maximum = float(axisElement.attrib.get("maximum"))
2098
+ axisObject.default = float(axisElement.attrib.get("default"))
2099
+ axisObject.name = axisElement.attrib.get("name")
2100
+ if axisElement.attrib.get("hidden", False):
2101
+ axisObject.hidden = True
2102
+ axisObject.tag = axisElement.attrib.get("tag")
2103
+ for mapElement in axisElement.findall("map"):
2104
+ a = float(mapElement.attrib["input"])
2105
+ b = float(mapElement.attrib["output"])
2106
+ axisObject.map.append((a, b))
2107
+ for labelNameElement in axisElement.findall("labelname"):
2108
+ # Note: elementtree reads the "xml:lang" attribute name as
2109
+ # '{http://www.w3.org/XML/1998/namespace}lang'
2110
+ for key, lang in labelNameElement.items():
2111
+ if key == XML_LANG:
2112
+ axisObject.labelNames[lang] = tostr(labelNameElement.text)
2113
+ labelElement = axisElement.find(".labels")
2114
+ if labelElement is not None:
2115
+ if "ordering" in labelElement.attrib:
2116
+ axisObject.axisOrdering = int(labelElement.attrib["ordering"])
2117
+ for label in labelElement.findall(".label"):
2118
+ axisObject.axisLabels.append(self.readAxisLabel(label))
2119
+ self.documentObject.axes.append(axisObject)
2120
+ self.axisDefaults[axisObject.name] = axisObject.default
2121
+
2122
+ self.documentObject.axisMappings = []
2123
+ for mappingsElement in self.root.findall(".axes/mappings"):
2124
+ groupDescription = mappingsElement.attrib.get("description")
2125
+ for mappingElement in mappingsElement.findall("mapping"):
2126
+ description = mappingElement.attrib.get("description")
2127
+ inputElement = mappingElement.find("input")
2128
+ outputElement = mappingElement.find("output")
2129
+ inputLoc = {}
2130
+ outputLoc = {}
2131
+ for dimElement in inputElement.findall(".dimension"):
2132
+ name = dimElement.attrib["name"]
2133
+ value = float(dimElement.attrib["xvalue"])
2134
+ inputLoc[name] = value
2135
+ for dimElement in outputElement.findall(".dimension"):
2136
+ name = dimElement.attrib["name"]
2137
+ value = float(dimElement.attrib["xvalue"])
2138
+ outputLoc[name] = value
2139
+ axisMappingObject = self.axisMappingDescriptorClass(
2140
+ inputLocation=inputLoc,
2141
+ outputLocation=outputLoc,
2142
+ description=description,
2143
+ groupDescription=groupDescription,
2144
+ )
2145
+ self.documentObject.axisMappings.append(axisMappingObject)
2146
+
2147
+ def readAxisLabel(self, element: ET.Element):
2148
+ xml_attrs = {
2149
+ "userminimum",
2150
+ "uservalue",
2151
+ "usermaximum",
2152
+ "name",
2153
+ "elidable",
2154
+ "oldersibling",
2155
+ "linkeduservalue",
2156
+ }
2157
+ unknown_attrs = set(element.attrib) - xml_attrs
2158
+ if unknown_attrs:
2159
+ raise DesignSpaceDocumentError(
2160
+ f"label element contains unknown attributes: {', '.join(unknown_attrs)}"
2161
+ )
2162
+
2163
+ name = element.get("name")
2164
+ if name is None:
2165
+ raise DesignSpaceDocumentError("label element must have a name attribute.")
2166
+ valueStr = element.get("uservalue")
2167
+ if valueStr is None:
2168
+ raise DesignSpaceDocumentError(
2169
+ "label element must have a uservalue attribute."
2170
+ )
2171
+ value = float(valueStr)
2172
+ minimumStr = element.get("userminimum")
2173
+ minimum = float(minimumStr) if minimumStr is not None else None
2174
+ maximumStr = element.get("usermaximum")
2175
+ maximum = float(maximumStr) if maximumStr is not None else None
2176
+ linkedValueStr = element.get("linkeduservalue")
2177
+ linkedValue = float(linkedValueStr) if linkedValueStr is not None else None
2178
+ elidable = True if element.get("elidable") == "true" else False
2179
+ olderSibling = True if element.get("oldersibling") == "true" else False
2180
+ labelNames = {
2181
+ lang: label_name.text or ""
2182
+ for label_name in element.findall("labelname")
2183
+ for attr, lang in label_name.items()
2184
+ if attr == XML_LANG
2185
+ # Note: elementtree reads the "xml:lang" attribute name as
2186
+ # '{http://www.w3.org/XML/1998/namespace}lang'
2187
+ }
2188
+ return self.axisLabelDescriptorClass(
2189
+ name=name,
2190
+ userValue=value,
2191
+ userMinimum=minimum,
2192
+ userMaximum=maximum,
2193
+ elidable=elidable,
2194
+ olderSibling=olderSibling,
2195
+ linkedUserValue=linkedValue,
2196
+ labelNames=labelNames,
2197
+ )
2198
+
2199
+ def readLabels(self):
2200
+ if self.documentObject.formatTuple < (5, 0):
2201
+ return
2202
+
2203
+ xml_attrs = {"name", "elidable", "oldersibling"}
2204
+ for labelElement in self.root.findall(".labels/label"):
2205
+ unknown_attrs = set(labelElement.attrib) - xml_attrs
2206
+ if unknown_attrs:
2207
+ raise DesignSpaceDocumentError(
2208
+ f"Label element contains unknown attributes: {', '.join(unknown_attrs)}"
2209
+ )
2210
+
2211
+ name = labelElement.get("name")
2212
+ if name is None:
2213
+ raise DesignSpaceDocumentError(
2214
+ "label element must have a name attribute."
2215
+ )
2216
+ designLocation, userLocation = self.locationFromElement(labelElement)
2217
+ if designLocation:
2218
+ raise DesignSpaceDocumentError(
2219
+ f'<label> element "{name}" must only have user locations (using uservalue="").'
2220
+ )
2221
+ elidable = True if labelElement.get("elidable") == "true" else False
2222
+ olderSibling = True if labelElement.get("oldersibling") == "true" else False
2223
+ labelNames = {
2224
+ lang: label_name.text or ""
2225
+ for label_name in labelElement.findall("labelname")
2226
+ for attr, lang in label_name.items()
2227
+ if attr == XML_LANG
2228
+ # Note: elementtree reads the "xml:lang" attribute name as
2229
+ # '{http://www.w3.org/XML/1998/namespace}lang'
2230
+ }
2231
+ locationLabel = self.locationLabelDescriptorClass(
2232
+ name=name,
2233
+ userLocation=userLocation,
2234
+ elidable=elidable,
2235
+ olderSibling=olderSibling,
2236
+ labelNames=labelNames,
2237
+ )
2238
+ self.documentObject.locationLabels.append(locationLabel)
2239
+
2240
+ def readVariableFonts(self):
2241
+ if self.documentObject.formatTuple < (5, 0):
2242
+ return
2243
+
2244
+ xml_attrs = {"name", "filename"}
2245
+ for variableFontElement in self.root.findall(".variable-fonts/variable-font"):
2246
+ unknown_attrs = set(variableFontElement.attrib) - xml_attrs
2247
+ if unknown_attrs:
2248
+ raise DesignSpaceDocumentError(
2249
+ f"variable-font element contains unknown attributes: {', '.join(unknown_attrs)}"
2250
+ )
2251
+
2252
+ name = variableFontElement.get("name")
2253
+ if name is None:
2254
+ raise DesignSpaceDocumentError(
2255
+ "variable-font element must have a name attribute."
2256
+ )
2257
+
2258
+ filename = variableFontElement.get("filename")
2259
+
2260
+ axisSubsetsElement = variableFontElement.find(".axis-subsets")
2261
+ if axisSubsetsElement is None:
2262
+ raise DesignSpaceDocumentError(
2263
+ "variable-font element must contain an axis-subsets element."
2264
+ )
2265
+ axisSubsets = []
2266
+ for axisSubset in axisSubsetsElement.iterfind(".axis-subset"):
2267
+ axisSubsets.append(self.readAxisSubset(axisSubset))
2268
+
2269
+ lib = None
2270
+ libElement = variableFontElement.find(".lib")
2271
+ if libElement is not None:
2272
+ lib = plistlib.fromtree(libElement[0])
2273
+
2274
+ variableFont = self.variableFontsDescriptorClass(
2275
+ name=name,
2276
+ filename=filename,
2277
+ axisSubsets=axisSubsets,
2278
+ lib=lib,
2279
+ )
2280
+ self.documentObject.variableFonts.append(variableFont)
2281
+
2282
+ def readAxisSubset(self, element: ET.Element):
2283
+ if "uservalue" in element.attrib:
2284
+ xml_attrs = {"name", "uservalue"}
2285
+ unknown_attrs = set(element.attrib) - xml_attrs
2286
+ if unknown_attrs:
2287
+ raise DesignSpaceDocumentError(
2288
+ f"axis-subset element contains unknown attributes: {', '.join(unknown_attrs)}"
2289
+ )
2290
+
2291
+ name = element.get("name")
2292
+ if name is None:
2293
+ raise DesignSpaceDocumentError(
2294
+ "axis-subset element must have a name attribute."
2295
+ )
2296
+ userValueStr = element.get("uservalue")
2297
+ if userValueStr is None:
2298
+ raise DesignSpaceDocumentError(
2299
+ "The axis-subset element for a discrete subset must have a uservalue attribute."
2300
+ )
2301
+ userValue = float(userValueStr)
2302
+
2303
+ return self.valueAxisSubsetDescriptorClass(name=name, userValue=userValue)
2304
+ else:
2305
+ xml_attrs = {"name", "userminimum", "userdefault", "usermaximum"}
2306
+ unknown_attrs = set(element.attrib) - xml_attrs
2307
+ if unknown_attrs:
2308
+ raise DesignSpaceDocumentError(
2309
+ f"axis-subset element contains unknown attributes: {', '.join(unknown_attrs)}"
2310
+ )
2311
+
2312
+ name = element.get("name")
2313
+ if name is None:
2314
+ raise DesignSpaceDocumentError(
2315
+ "axis-subset element must have a name attribute."
2316
+ )
2317
+
2318
+ userMinimum = element.get("userminimum")
2319
+ userDefault = element.get("userdefault")
2320
+ userMaximum = element.get("usermaximum")
2321
+ if (
2322
+ userMinimum is not None
2323
+ and userDefault is not None
2324
+ and userMaximum is not None
2325
+ ):
2326
+ return self.rangeAxisSubsetDescriptorClass(
2327
+ name=name,
2328
+ userMinimum=float(userMinimum),
2329
+ userDefault=float(userDefault),
2330
+ userMaximum=float(userMaximum),
2331
+ )
2332
+ if all(v is None for v in (userMinimum, userDefault, userMaximum)):
2333
+ return self.rangeAxisSubsetDescriptorClass(name=name)
2334
+
2335
+ raise DesignSpaceDocumentError(
2336
+ "axis-subset element must have min/max/default values or none at all."
2337
+ )
2338
+
2339
+ def readSources(self):
2340
+ for sourceCount, sourceElement in enumerate(
2341
+ self.root.findall(".sources/source")
2342
+ ):
2343
+ filename = sourceElement.attrib.get("filename")
2344
+ if filename is not None and self.path is not None:
2345
+ sourcePath = os.path.abspath(
2346
+ os.path.join(os.path.dirname(self.path), filename)
2347
+ )
2348
+ else:
2349
+ sourcePath = None
2350
+ sourceName = sourceElement.attrib.get("name")
2351
+ if sourceName is None:
2352
+ # add a temporary source name
2353
+ sourceName = "temp_master.%d" % (sourceCount)
2354
+ sourceObject = self.sourceDescriptorClass()
2355
+ sourceObject.path = sourcePath # absolute path to the ufo source
2356
+ sourceObject.filename = filename # path as it is stored in the document
2357
+ sourceObject.name = sourceName
2358
+ familyName = sourceElement.attrib.get("familyname")
2359
+ if familyName is not None:
2360
+ sourceObject.familyName = familyName
2361
+ styleName = sourceElement.attrib.get("stylename")
2362
+ if styleName is not None:
2363
+ sourceObject.styleName = styleName
2364
+ for familyNameElement in sourceElement.findall("familyname"):
2365
+ for key, lang in familyNameElement.items():
2366
+ if key == XML_LANG:
2367
+ familyName = familyNameElement.text
2368
+ sourceObject.setFamilyName(familyName, lang)
2369
+ designLocation, userLocation = self.locationFromElement(sourceElement)
2370
+ if userLocation:
2371
+ raise DesignSpaceDocumentError(
2372
+ f'<source> element "{sourceName}" must only have design locations (using xvalue="").'
2373
+ )
2374
+ sourceObject.location = designLocation
2375
+ layerName = sourceElement.attrib.get("layer")
2376
+ if layerName is not None:
2377
+ sourceObject.layerName = layerName
2378
+ for libElement in sourceElement.findall(".lib"):
2379
+ if libElement.attrib.get("copy") == "1":
2380
+ sourceObject.copyLib = True
2381
+ for groupsElement in sourceElement.findall(".groups"):
2382
+ if groupsElement.attrib.get("copy") == "1":
2383
+ sourceObject.copyGroups = True
2384
+ for infoElement in sourceElement.findall(".info"):
2385
+ if infoElement.attrib.get("copy") == "1":
2386
+ sourceObject.copyInfo = True
2387
+ if infoElement.attrib.get("mute") == "1":
2388
+ sourceObject.muteInfo = True
2389
+ for featuresElement in sourceElement.findall(".features"):
2390
+ if featuresElement.attrib.get("copy") == "1":
2391
+ sourceObject.copyFeatures = True
2392
+ for glyphElement in sourceElement.findall(".glyph"):
2393
+ glyphName = glyphElement.attrib.get("name")
2394
+ if glyphName is None:
2395
+ continue
2396
+ if glyphElement.attrib.get("mute") == "1":
2397
+ sourceObject.mutedGlyphNames.append(glyphName)
2398
+ for kerningElement in sourceElement.findall(".kerning"):
2399
+ if kerningElement.attrib.get("mute") == "1":
2400
+ sourceObject.muteKerning = True
2401
+ self.documentObject.sources.append(sourceObject)
2402
+
2403
+ def locationFromElement(self, element):
2404
+ """Read a nested ``<location>`` element inside the given ``element``.
2405
+
2406
+ .. versionchanged:: 5.0
2407
+ Return a tuple of (designLocation, userLocation)
2408
+ """
2409
+ elementLocation = (None, None)
2410
+ for locationElement in element.findall(".location"):
2411
+ elementLocation = self.readLocationElement(locationElement)
2412
+ break
2413
+ return elementLocation
2414
+
2415
+ def readLocationElement(self, locationElement):
2416
+ """Read a ``<location>`` element.
2417
+
2418
+ .. versionchanged:: 5.0
2419
+ Return a tuple of (designLocation, userLocation)
2420
+ """
2421
+ if self._strictAxisNames and not self.documentObject.axes:
2422
+ raise DesignSpaceDocumentError("No axes defined")
2423
+ userLoc = {}
2424
+ designLoc = {}
2425
+ for dimensionElement in locationElement.findall(".dimension"):
2426
+ dimName = dimensionElement.attrib.get("name")
2427
+ if self._strictAxisNames and dimName not in self.axisDefaults:
2428
+ # In case the document contains no axis definitions,
2429
+ self.log.warning('Location with undefined axis: "%s".', dimName)
2430
+ continue
2431
+ userValue = xValue = yValue = None
2432
+ try:
2433
+ userValue = dimensionElement.attrib.get("uservalue")
2434
+ if userValue is not None:
2435
+ userValue = float(userValue)
2436
+ except ValueError:
2437
+ self.log.warning(
2438
+ "ValueError in readLocation userValue %3.3f", userValue
2439
+ )
2440
+ try:
2441
+ xValue = dimensionElement.attrib.get("xvalue")
2442
+ if xValue is not None:
2443
+ xValue = float(xValue)
2444
+ except ValueError:
2445
+ self.log.warning("ValueError in readLocation xValue %3.3f", xValue)
2446
+ try:
2447
+ yValue = dimensionElement.attrib.get("yvalue")
2448
+ if yValue is not None:
2449
+ yValue = float(yValue)
2450
+ except ValueError:
2451
+ self.log.warning("ValueError in readLocation yValue %3.3f", yValue)
2452
+ if userValue is None == xValue is None:
2453
+ raise DesignSpaceDocumentError(
2454
+ f'Exactly one of uservalue="" or xvalue="" must be provided for location dimension "{dimName}"'
2455
+ )
2456
+ if yValue is not None:
2457
+ if xValue is None:
2458
+ raise DesignSpaceDocumentError(
2459
+ f'Missing xvalue="" for the location dimension "{dimName}"" with yvalue="{yValue}"'
2460
+ )
2461
+ designLoc[dimName] = (xValue, yValue)
2462
+ elif xValue is not None:
2463
+ designLoc[dimName] = xValue
2464
+ else:
2465
+ userLoc[dimName] = userValue
2466
+ return designLoc, userLoc
2467
+
2468
+ def readInstances(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
2469
+ instanceElements = self.root.findall(".instances/instance")
2470
+ for instanceElement in instanceElements:
2471
+ self._readSingleInstanceElement(
2472
+ instanceElement,
2473
+ makeGlyphs=makeGlyphs,
2474
+ makeKerning=makeKerning,
2475
+ makeInfo=makeInfo,
2476
+ )
2477
+
2478
+ def _readSingleInstanceElement(
2479
+ self, instanceElement, makeGlyphs=True, makeKerning=True, makeInfo=True
2480
+ ):
2481
+ filename = instanceElement.attrib.get("filename")
2482
+ if filename is not None and self.documentObject.path is not None:
2483
+ instancePath = os.path.join(
2484
+ os.path.dirname(self.documentObject.path), filename
2485
+ )
2486
+ else:
2487
+ instancePath = None
2488
+ instanceObject = self.instanceDescriptorClass()
2489
+ instanceObject.path = instancePath # absolute path to the instance
2490
+ instanceObject.filename = filename # path as it is stored in the document
2491
+ name = instanceElement.attrib.get("name")
2492
+ if name is not None:
2493
+ instanceObject.name = name
2494
+ familyname = instanceElement.attrib.get("familyname")
2495
+ if familyname is not None:
2496
+ instanceObject.familyName = familyname
2497
+ stylename = instanceElement.attrib.get("stylename")
2498
+ if stylename is not None:
2499
+ instanceObject.styleName = stylename
2500
+ postScriptFontName = instanceElement.attrib.get("postscriptfontname")
2501
+ if postScriptFontName is not None:
2502
+ instanceObject.postScriptFontName = postScriptFontName
2503
+ styleMapFamilyName = instanceElement.attrib.get("stylemapfamilyname")
2504
+ if styleMapFamilyName is not None:
2505
+ instanceObject.styleMapFamilyName = styleMapFamilyName
2506
+ styleMapStyleName = instanceElement.attrib.get("stylemapstylename")
2507
+ if styleMapStyleName is not None:
2508
+ instanceObject.styleMapStyleName = styleMapStyleName
2509
+ # read localised names
2510
+ for styleNameElement in instanceElement.findall("stylename"):
2511
+ for key, lang in styleNameElement.items():
2512
+ if key == XML_LANG:
2513
+ styleName = styleNameElement.text
2514
+ instanceObject.setStyleName(styleName, lang)
2515
+ for familyNameElement in instanceElement.findall("familyname"):
2516
+ for key, lang in familyNameElement.items():
2517
+ if key == XML_LANG:
2518
+ familyName = familyNameElement.text
2519
+ instanceObject.setFamilyName(familyName, lang)
2520
+ for styleMapStyleNameElement in instanceElement.findall("stylemapstylename"):
2521
+ for key, lang in styleMapStyleNameElement.items():
2522
+ if key == XML_LANG:
2523
+ styleMapStyleName = styleMapStyleNameElement.text
2524
+ instanceObject.setStyleMapStyleName(styleMapStyleName, lang)
2525
+ for styleMapFamilyNameElement in instanceElement.findall("stylemapfamilyname"):
2526
+ for key, lang in styleMapFamilyNameElement.items():
2527
+ if key == XML_LANG:
2528
+ styleMapFamilyName = styleMapFamilyNameElement.text
2529
+ instanceObject.setStyleMapFamilyName(styleMapFamilyName, lang)
2530
+ designLocation, userLocation = self.locationFromElement(instanceElement)
2531
+ locationLabel = instanceElement.attrib.get("location")
2532
+ if (designLocation or userLocation) and locationLabel is not None:
2533
+ raise DesignSpaceDocumentError(
2534
+ 'instance element must have at most one of the location="..." attribute or the nested location element'
2535
+ )
2536
+ instanceObject.locationLabel = locationLabel
2537
+ instanceObject.userLocation = userLocation or {}
2538
+ instanceObject.designLocation = designLocation or {}
2539
+ for glyphElement in instanceElement.findall(".glyphs/glyph"):
2540
+ self.readGlyphElement(glyphElement, instanceObject)
2541
+ for infoElement in instanceElement.findall("info"):
2542
+ self.readInfoElement(infoElement, instanceObject)
2543
+ for libElement in instanceElement.findall("lib"):
2544
+ self.readLibElement(libElement, instanceObject)
2545
+ self.documentObject.instances.append(instanceObject)
2546
+
2547
+ def readLibElement(self, libElement, instanceObject):
2548
+ """Read the lib element for the given instance."""
2549
+ instanceObject.lib = plistlib.fromtree(libElement[0])
2550
+
2551
+ def readInfoElement(self, infoElement, instanceObject):
2552
+ """Read the info element."""
2553
+ instanceObject.info = True
2554
+
2555
+ def readGlyphElement(self, glyphElement, instanceObject):
2556
+ """
2557
+ Read the glyph element, which could look like either one of these:
2558
+
2559
+ .. code-block:: xml
2560
+
2561
+ <glyph name="b" unicode="0x62"/>
2562
+
2563
+ <glyph name="b"/>
2564
+
2565
+ <glyph name="b">
2566
+ <master location="location-token-bbb" source="master-token-aaa2"/>
2567
+ <master glyphname="b.alt1" location="location-token-ccc" source="master-token-aaa3"/>
2568
+ <note>
2569
+ This is an instance from an anisotropic interpolation.
2570
+ </note>
2571
+ </glyph>
2572
+ """
2573
+ glyphData = {}
2574
+ glyphName = glyphElement.attrib.get("name")
2575
+ if glyphName is None:
2576
+ raise DesignSpaceDocumentError("Glyph object without name attribute")
2577
+ mute = glyphElement.attrib.get("mute")
2578
+ if mute == "1":
2579
+ glyphData["mute"] = True
2580
+ # unicode
2581
+ unicodes = glyphElement.attrib.get("unicode")
2582
+ if unicodes is not None:
2583
+ try:
2584
+ unicodes = [int(u, 16) for u in unicodes.split(" ")]
2585
+ glyphData["unicodes"] = unicodes
2586
+ except ValueError:
2587
+ raise DesignSpaceDocumentError(
2588
+ "unicode values %s are not integers" % unicodes
2589
+ )
2590
+
2591
+ for noteElement in glyphElement.findall(".note"):
2592
+ glyphData["note"] = noteElement.text
2593
+ break
2594
+ designLocation, userLocation = self.locationFromElement(glyphElement)
2595
+ if userLocation:
2596
+ raise DesignSpaceDocumentError(
2597
+ f'<glyph> element "{glyphName}" must only have design locations (using xvalue="").'
2598
+ )
2599
+ if designLocation is not None:
2600
+ glyphData["instanceLocation"] = designLocation
2601
+ glyphSources = None
2602
+ for masterElement in glyphElement.findall(".masters/master"):
2603
+ fontSourceName = masterElement.attrib.get("source")
2604
+ designLocation, userLocation = self.locationFromElement(masterElement)
2605
+ if userLocation:
2606
+ raise DesignSpaceDocumentError(
2607
+ f'<master> element "{fontSourceName}" must only have design locations (using xvalue="").'
2608
+ )
2609
+ masterGlyphName = masterElement.attrib.get("glyphname")
2610
+ if masterGlyphName is None:
2611
+ # if we don't read a glyphname, use the one we have
2612
+ masterGlyphName = glyphName
2613
+ d = dict(
2614
+ font=fontSourceName, location=designLocation, glyphName=masterGlyphName
2615
+ )
2616
+ if glyphSources is None:
2617
+ glyphSources = []
2618
+ glyphSources.append(d)
2619
+ if glyphSources is not None:
2620
+ glyphData["masters"] = glyphSources
2621
+ instanceObject.glyphs[glyphName] = glyphData
2622
+
2623
+ def readLib(self):
2624
+ """Read the lib element for the whole document."""
2625
+ for libElement in self.root.findall(".lib"):
2626
+ self.documentObject.lib = plistlib.fromtree(libElement[0])
2627
+
2628
+
2629
+ class DesignSpaceDocument(LogMixin, AsDictMixin):
2630
+ """The DesignSpaceDocument object can read and write ``.designspace`` data.
2631
+ It imports the axes, sources, variable fonts and instances to very basic
2632
+ **descriptor** objects that store the data in attributes. Data is added to
2633
+ the document by creating such descriptor objects, filling them with data
2634
+ and then adding them to the document. This makes it easy to integrate this
2635
+ object in different contexts.
2636
+
2637
+ The **DesignSpaceDocument** object can be subclassed to work with
2638
+ different objects, as long as they have the same attributes. Reader and
2639
+ Writer objects can be subclassed as well.
2640
+
2641
+ **Note:** Python attribute names are usually camelCased, the
2642
+ corresponding `XML <document-xml-structure>`_ attributes are usually
2643
+ all lowercase.
2644
+
2645
+ .. code:: python
2646
+
2647
+ from fontTools.designspaceLib import DesignSpaceDocument
2648
+ doc = DesignSpaceDocument.fromfile("some/path/to/my.designspace")
2649
+ doc.formatVersion
2650
+ doc.elidedFallbackName
2651
+ doc.axes
2652
+ doc.axisMappings
2653
+ doc.locationLabels
2654
+ doc.rules
2655
+ doc.rulesProcessingLast
2656
+ doc.sources
2657
+ doc.variableFonts
2658
+ doc.instances
2659
+ doc.lib
2660
+
2661
+ """
2662
+
2663
+ def __init__(self, readerClass=None, writerClass=None):
2664
+ self.path = None
2665
+ """String, optional. When the document is read from the disk, this is
2666
+ the full path that was given to :meth:`read` or :meth:`fromfile`.
2667
+ """
2668
+ self.filename = None
2669
+ """String, optional. When the document is read from the disk, this is
2670
+ its original file name, i.e. the last part of its path.
2671
+
2672
+ When the document is produced by a Python script and still only exists
2673
+ in memory, the producing script can write here an indication of a
2674
+ possible "good" filename, in case one wants to save the file somewhere.
2675
+ """
2676
+
2677
+ self.formatVersion: Optional[str] = None
2678
+ """Format version for this document, as a string. E.g. "4.0" """
2679
+
2680
+ self.elidedFallbackName: Optional[str] = None
2681
+ """STAT Style Attributes Header field ``elidedFallbackNameID``.
2682
+
2683
+ See: `OTSpec STAT Style Attributes Header <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#style-attributes-header>`_
2684
+
2685
+ .. versionadded:: 5.0
2686
+ """
2687
+
2688
+ self.axes: List[Union[AxisDescriptor, DiscreteAxisDescriptor]] = []
2689
+ """List of this document's axes."""
2690
+
2691
+ self.axisMappings: List[AxisMappingDescriptor] = []
2692
+ """List of this document's axis mappings."""
2693
+
2694
+ self.locationLabels: List[LocationLabelDescriptor] = []
2695
+ """List of this document's STAT format 4 labels.
2696
+
2697
+ .. versionadded:: 5.0"""
2698
+ self.rules: List[RuleDescriptor] = []
2699
+ """List of this document's rules."""
2700
+ self.rulesProcessingLast: bool = False
2701
+ """This flag indicates whether the substitution rules should be applied
2702
+ before or after other glyph substitution features.
2703
+
2704
+ - False: before
2705
+ - True: after.
2706
+
2707
+ Default is False. For new projects, you probably want True. See
2708
+ the following issues for more information:
2709
+ `fontTools#1371 <https://github.com/fonttools/fonttools/issues/1371#issuecomment-590214572>`__
2710
+ `fontTools#2050 <https://github.com/fonttools/fonttools/issues/2050#issuecomment-678691020>`__
2711
+
2712
+ If you want to use a different feature altogether, e.g. ``calt``,
2713
+ use the lib key ``com.github.fonttools.varLib.featureVarsFeatureTag``
2714
+
2715
+ .. code:: xml
2716
+
2717
+ <lib>
2718
+ <dict>
2719
+ <key>com.github.fonttools.varLib.featureVarsFeatureTag</key>
2720
+ <string>calt</string>
2721
+ </dict>
2722
+ </lib>
2723
+ """
2724
+ self.sources: List[SourceDescriptor] = []
2725
+ """List of this document's sources."""
2726
+ self.variableFonts: List[VariableFontDescriptor] = []
2727
+ """List of this document's variable fonts.
2728
+
2729
+ .. versionadded:: 5.0"""
2730
+ self.instances: List[InstanceDescriptor] = []
2731
+ """List of this document's instances."""
2732
+ self.lib: Dict = {}
2733
+ """User defined, custom data associated with the whole document.
2734
+
2735
+ Use reverse-DNS notation to identify your own data.
2736
+ Respect the data stored by others.
2737
+ """
2738
+
2739
+ self.default: Optional[str] = None
2740
+ """Name of the default master.
2741
+
2742
+ This attribute is updated by the :meth:`findDefault`
2743
+ """
2744
+
2745
+ if readerClass is not None:
2746
+ self.readerClass = readerClass
2747
+ else:
2748
+ self.readerClass = BaseDocReader
2749
+ if writerClass is not None:
2750
+ self.writerClass = writerClass
2751
+ else:
2752
+ self.writerClass = BaseDocWriter
2753
+
2754
+ @classmethod
2755
+ def fromfile(cls, path, readerClass=None, writerClass=None):
2756
+ """Read a designspace file from ``path`` and return a new instance of
2757
+ :class:.
2758
+ """
2759
+ self = cls(readerClass=readerClass, writerClass=writerClass)
2760
+ self.read(path)
2761
+ return self
2762
+
2763
+ @classmethod
2764
+ def fromstring(cls, string, readerClass=None, writerClass=None):
2765
+ self = cls(readerClass=readerClass, writerClass=writerClass)
2766
+ reader = self.readerClass.fromstring(string, self)
2767
+ reader.read()
2768
+ if self.sources:
2769
+ self.findDefault()
2770
+ return self
2771
+
2772
+ def tostring(self, encoding=None):
2773
+ """Returns the designspace as a string. Default encoding ``utf-8``."""
2774
+ if encoding is str or (encoding is not None and encoding.lower() == "unicode"):
2775
+ f = StringIO()
2776
+ xml_declaration = False
2777
+ elif encoding is None or encoding == "utf-8":
2778
+ f = BytesIO()
2779
+ encoding = "UTF-8"
2780
+ xml_declaration = True
2781
+ else:
2782
+ raise ValueError("unsupported encoding: '%s'" % encoding)
2783
+ writer = self.writerClass(f, self)
2784
+ writer.write(encoding=encoding, xml_declaration=xml_declaration)
2785
+ return f.getvalue()
2786
+
2787
+ def read(self, path):
2788
+ """Read a designspace file from ``path`` and populates the fields of
2789
+ ``self`` with the data.
2790
+ """
2791
+ if hasattr(path, "__fspath__"): # support os.PathLike objects
2792
+ path = path.__fspath__()
2793
+ self.path = path
2794
+ self.filename = os.path.basename(path)
2795
+ reader = self.readerClass(path, self)
2796
+ reader.read()
2797
+ if self.sources:
2798
+ self.findDefault()
2799
+
2800
+ def write(self, path):
2801
+ """Write this designspace to ``path``."""
2802
+ if hasattr(path, "__fspath__"): # support os.PathLike objects
2803
+ path = path.__fspath__()
2804
+ self.path = path
2805
+ self.filename = os.path.basename(path)
2806
+ self.updatePaths()
2807
+ writer = self.writerClass(path, self)
2808
+ writer.write()
2809
+
2810
+ def _posixRelativePath(self, otherPath):
2811
+ relative = os.path.relpath(otherPath, os.path.dirname(self.path))
2812
+ return posix(relative)
2813
+
2814
+ def updatePaths(self):
2815
+ """
2816
+ Right before we save we need to identify and respond to the following situations:
2817
+ In each descriptor, we have to do the right thing for the filename attribute.
2818
+
2819
+ ::
2820
+
2821
+ case 1.
2822
+ descriptor.filename == None
2823
+ descriptor.path == None
2824
+
2825
+ -- action:
2826
+ write as is, descriptors will not have a filename attr.
2827
+ useless, but no reason to interfere.
2828
+
2829
+
2830
+ case 2.
2831
+ descriptor.filename == "../something"
2832
+ descriptor.path == None
2833
+
2834
+ -- action:
2835
+ write as is. The filename attr should not be touched.
2836
+
2837
+
2838
+ case 3.
2839
+ descriptor.filename == None
2840
+ descriptor.path == "~/absolute/path/there"
2841
+
2842
+ -- action:
2843
+ calculate the relative path for filename.
2844
+ We're not overwriting some other value for filename, it should be fine
2845
+
2846
+
2847
+ case 4.
2848
+ descriptor.filename == '../somewhere'
2849
+ descriptor.path == "~/absolute/path/there"
2850
+
2851
+ -- action:
2852
+ there is a conflict between the given filename, and the path.
2853
+ So we know where the file is relative to the document.
2854
+ Can't guess why they're different, we just choose for path to be correct and update filename.
2855
+ """
2856
+ assert self.path is not None
2857
+ for descriptor in self.sources + self.instances:
2858
+ if descriptor.path is not None:
2859
+ # case 3 and 4: filename gets updated and relativized
2860
+ descriptor.filename = self._posixRelativePath(descriptor.path)
2861
+
2862
+ def addSource(self, sourceDescriptor: SourceDescriptor):
2863
+ """Add the given ``sourceDescriptor`` to ``doc.sources``."""
2864
+ self.sources.append(sourceDescriptor)
2865
+
2866
+ def addSourceDescriptor(self, **kwargs):
2867
+ """Instantiate a new :class:`SourceDescriptor` using the given
2868
+ ``kwargs`` and add it to ``doc.sources``.
2869
+ """
2870
+ source = self.writerClass.sourceDescriptorClass(**kwargs)
2871
+ self.addSource(source)
2872
+ return source
2873
+
2874
+ def addInstance(self, instanceDescriptor: InstanceDescriptor):
2875
+ """Add the given ``instanceDescriptor`` to :attr:`instances`."""
2876
+ self.instances.append(instanceDescriptor)
2877
+
2878
+ def addInstanceDescriptor(self, **kwargs):
2879
+ """Instantiate a new :class:`InstanceDescriptor` using the given
2880
+ ``kwargs`` and add it to :attr:`instances`.
2881
+ """
2882
+ instance = self.writerClass.instanceDescriptorClass(**kwargs)
2883
+ self.addInstance(instance)
2884
+ return instance
2885
+
2886
+ def addAxis(self, axisDescriptor: Union[AxisDescriptor, DiscreteAxisDescriptor]):
2887
+ """Add the given ``axisDescriptor`` to :attr:`axes`."""
2888
+ self.axes.append(axisDescriptor)
2889
+
2890
+ def addAxisDescriptor(self, **kwargs):
2891
+ """Instantiate a new :class:`AxisDescriptor` using the given
2892
+ ``kwargs`` and add it to :attr:`axes`.
2893
+
2894
+ The axis will be and instance of :class:`DiscreteAxisDescriptor` if
2895
+ the ``kwargs`` provide a ``value``, or a :class:`AxisDescriptor` otherwise.
2896
+ """
2897
+ if "values" in kwargs:
2898
+ axis = self.writerClass.discreteAxisDescriptorClass(**kwargs)
2899
+ else:
2900
+ axis = self.writerClass.axisDescriptorClass(**kwargs)
2901
+ self.addAxis(axis)
2902
+ return axis
2903
+
2904
+ def addAxisMapping(self, axisMappingDescriptor: AxisMappingDescriptor):
2905
+ """Add the given ``axisMappingDescriptor`` to :attr:`axisMappings`."""
2906
+ self.axisMappings.append(axisMappingDescriptor)
2907
+
2908
+ def addAxisMappingDescriptor(self, **kwargs):
2909
+ """Instantiate a new :class:`AxisMappingDescriptor` using the given
2910
+ ``kwargs`` and add it to :attr:`rules`.
2911
+ """
2912
+ axisMapping = self.writerClass.axisMappingDescriptorClass(**kwargs)
2913
+ self.addAxisMapping(axisMapping)
2914
+ return axisMapping
2915
+
2916
+ def addRule(self, ruleDescriptor: RuleDescriptor):
2917
+ """Add the given ``ruleDescriptor`` to :attr:`rules`."""
2918
+ self.rules.append(ruleDescriptor)
2919
+
2920
+ def addRuleDescriptor(self, **kwargs):
2921
+ """Instantiate a new :class:`RuleDescriptor` using the given
2922
+ ``kwargs`` and add it to :attr:`rules`.
2923
+ """
2924
+ rule = self.writerClass.ruleDescriptorClass(**kwargs)
2925
+ self.addRule(rule)
2926
+ return rule
2927
+
2928
+ def addVariableFont(self, variableFontDescriptor: VariableFontDescriptor):
2929
+ """Add the given ``variableFontDescriptor`` to :attr:`variableFonts`.
2930
+
2931
+ .. versionadded:: 5.0
2932
+ """
2933
+ self.variableFonts.append(variableFontDescriptor)
2934
+
2935
+ def addVariableFontDescriptor(self, **kwargs):
2936
+ """Instantiate a new :class:`VariableFontDescriptor` using the given
2937
+ ``kwargs`` and add it to :attr:`variableFonts`.
2938
+
2939
+ .. versionadded:: 5.0
2940
+ """
2941
+ variableFont = self.writerClass.variableFontDescriptorClass(**kwargs)
2942
+ self.addVariableFont(variableFont)
2943
+ return variableFont
2944
+
2945
+ def addLocationLabel(self, locationLabelDescriptor: LocationLabelDescriptor):
2946
+ """Add the given ``locationLabelDescriptor`` to :attr:`locationLabels`.
2947
+
2948
+ .. versionadded:: 5.0
2949
+ """
2950
+ self.locationLabels.append(locationLabelDescriptor)
2951
+
2952
+ def addLocationLabelDescriptor(self, **kwargs):
2953
+ """Instantiate a new :class:`LocationLabelDescriptor` using the given
2954
+ ``kwargs`` and add it to :attr:`locationLabels`.
2955
+
2956
+ .. versionadded:: 5.0
2957
+ """
2958
+ locationLabel = self.writerClass.locationLabelDescriptorClass(**kwargs)
2959
+ self.addLocationLabel(locationLabel)
2960
+ return locationLabel
2961
+
2962
+ def newDefaultLocation(self):
2963
+ """Return a dict with the default location in design space coordinates."""
2964
+ # Without OrderedDict, output XML would be non-deterministic.
2965
+ # https://github.com/LettError/designSpaceDocument/issues/10
2966
+ loc = collections.OrderedDict()
2967
+ for axisDescriptor in self.axes:
2968
+ loc[axisDescriptor.name] = axisDescriptor.map_forward(
2969
+ axisDescriptor.default
2970
+ )
2971
+ return loc
2972
+
2973
+ def labelForUserLocation(
2974
+ self, userLocation: SimpleLocationDict
2975
+ ) -> Optional[LocationLabelDescriptor]:
2976
+ """Return the :class:`LocationLabel` that matches the given
2977
+ ``userLocation``, or ``None`` if no such label exists.
2978
+
2979
+ .. versionadded:: 5.0
2980
+ """
2981
+ return next(
2982
+ (
2983
+ label
2984
+ for label in self.locationLabels
2985
+ if label.userLocation == userLocation
2986
+ ),
2987
+ None,
2988
+ )
2989
+
2990
+ def updateFilenameFromPath(self, masters=True, instances=True, force=False):
2991
+ """Set a descriptor filename attr from the path and this document path.
2992
+
2993
+ If the filename attribute is not None: skip it.
2994
+ """
2995
+ if masters:
2996
+ for descriptor in self.sources:
2997
+ if descriptor.filename is not None and not force:
2998
+ continue
2999
+ if self.path is not None:
3000
+ descriptor.filename = self._posixRelativePath(descriptor.path)
3001
+ if instances:
3002
+ for descriptor in self.instances:
3003
+ if descriptor.filename is not None and not force:
3004
+ continue
3005
+ if self.path is not None:
3006
+ descriptor.filename = self._posixRelativePath(descriptor.path)
3007
+
3008
+ def newAxisDescriptor(self):
3009
+ """Ask the writer class to make us a new axisDescriptor."""
3010
+ return self.writerClass.getAxisDecriptor()
3011
+
3012
+ def newSourceDescriptor(self):
3013
+ """Ask the writer class to make us a new sourceDescriptor."""
3014
+ return self.writerClass.getSourceDescriptor()
3015
+
3016
+ def newInstanceDescriptor(self):
3017
+ """Ask the writer class to make us a new instanceDescriptor."""
3018
+ return self.writerClass.getInstanceDescriptor()
3019
+
3020
+ def getAxisOrder(self):
3021
+ """Return a list of axis names, in the same order as defined in the document."""
3022
+ names = []
3023
+ for axisDescriptor in self.axes:
3024
+ names.append(axisDescriptor.name)
3025
+ return names
3026
+
3027
+ def getAxis(self, name: str) -> AxisDescriptor | DiscreteAxisDescriptor | None:
3028
+ """Return the axis with the given ``name``, or ``None`` if no such axis exists."""
3029
+ return next((axis for axis in self.axes if axis.name == name), None)
3030
+
3031
+ def getAxisByTag(self, tag: str) -> AxisDescriptor | DiscreteAxisDescriptor | None:
3032
+ """Return the axis with the given ``tag``, or ``None`` if no such axis exists."""
3033
+ return next((axis for axis in self.axes if axis.tag == tag), None)
3034
+
3035
+ def getLocationLabel(self, name: str) -> Optional[LocationLabelDescriptor]:
3036
+ """Return the top-level location label with the given ``name``, or
3037
+ ``None`` if no such label exists.
3038
+
3039
+ .. versionadded:: 5.0
3040
+ """
3041
+ for label in self.locationLabels:
3042
+ if label.name == name:
3043
+ return label
3044
+ return None
3045
+
3046
+ def map_forward(self, userLocation: SimpleLocationDict) -> SimpleLocationDict:
3047
+ """Map a user location to a design location.
3048
+
3049
+ Assume that missing coordinates are at the default location for that axis.
3050
+
3051
+ Note: the output won't be anisotropic, only the xvalue is set.
3052
+
3053
+ .. versionadded:: 5.0
3054
+ """
3055
+ return {
3056
+ axis.name: axis.map_forward(userLocation.get(axis.name, axis.default))
3057
+ for axis in self.axes
3058
+ }
3059
+
3060
+ def map_backward(
3061
+ self, designLocation: AnisotropicLocationDict
3062
+ ) -> SimpleLocationDict:
3063
+ """Map a design location to a user location.
3064
+
3065
+ Assume that missing coordinates are at the default location for that axis.
3066
+
3067
+ When the input has anisotropic locations, only the xvalue is used.
3068
+
3069
+ .. versionadded:: 5.0
3070
+ """
3071
+ return {
3072
+ axis.name: (
3073
+ axis.map_backward(designLocation[axis.name])
3074
+ if axis.name in designLocation
3075
+ else axis.default
3076
+ )
3077
+ for axis in self.axes
3078
+ }
3079
+
3080
+ def findDefault(self):
3081
+ """Set and return SourceDescriptor at the default location or None.
3082
+
3083
+ The default location is the set of all `default` values in user space
3084
+ of all axes.
3085
+
3086
+ This function updates the document's :attr:`default` value.
3087
+
3088
+ .. versionchanged:: 5.0
3089
+ Allow the default source to not specify some of the axis values, and
3090
+ they are assumed to be the default.
3091
+ See :meth:`SourceDescriptor.getFullDesignLocation()`
3092
+ """
3093
+ self.default = None
3094
+
3095
+ # Convert the default location from user space to design space before comparing
3096
+ # it against the SourceDescriptor locations (always in design space).
3097
+ defaultDesignLocation = self.newDefaultLocation()
3098
+
3099
+ for sourceDescriptor in self.sources:
3100
+ if sourceDescriptor.getFullDesignLocation(self) == defaultDesignLocation:
3101
+ self.default = sourceDescriptor
3102
+ return sourceDescriptor
3103
+
3104
+ return None
3105
+
3106
+ def normalizeLocation(self, location):
3107
+ """Return a dict with normalized axis values."""
3108
+ from fontTools.varLib.models import normalizeValue
3109
+
3110
+ new = {}
3111
+ for axis in self.axes:
3112
+ if axis.name not in location:
3113
+ # skipping this dimension it seems
3114
+ continue
3115
+ value = location[axis.name]
3116
+ # 'anisotropic' location, take first coord only
3117
+ if isinstance(value, tuple):
3118
+ value = value[0]
3119
+ triple = [
3120
+ axis.map_forward(v) for v in (axis.minimum, axis.default, axis.maximum)
3121
+ ]
3122
+ new[axis.name] = normalizeValue(value, triple)
3123
+ return new
3124
+
3125
+ def normalize(self):
3126
+ """
3127
+ Normalise the geometry of this designspace:
3128
+
3129
+ - scale all the locations of all masters and instances to the -1 - 0 - 1 value.
3130
+ - we need the axis data to do the scaling, so we do those last.
3131
+ """
3132
+ # masters
3133
+ for item in self.sources:
3134
+ item.location = self.normalizeLocation(item.location)
3135
+ # instances
3136
+ for item in self.instances:
3137
+ # glyph masters for this instance
3138
+ for _, glyphData in item.glyphs.items():
3139
+ glyphData["instanceLocation"] = self.normalizeLocation(
3140
+ glyphData["instanceLocation"]
3141
+ )
3142
+ for glyphMaster in glyphData["masters"]:
3143
+ glyphMaster["location"] = self.normalizeLocation(
3144
+ glyphMaster["location"]
3145
+ )
3146
+ item.location = self.normalizeLocation(item.location)
3147
+ # the axes
3148
+ for axis in self.axes:
3149
+ # scale the map first
3150
+ newMap = []
3151
+ for inputValue, outputValue in axis.map:
3152
+ newOutputValue = self.normalizeLocation({axis.name: outputValue}).get(
3153
+ axis.name
3154
+ )
3155
+ newMap.append((inputValue, newOutputValue))
3156
+ if newMap:
3157
+ axis.map = newMap
3158
+ # finally the axis values
3159
+ minimum = self.normalizeLocation({axis.name: axis.minimum}).get(axis.name)
3160
+ maximum = self.normalizeLocation({axis.name: axis.maximum}).get(axis.name)
3161
+ default = self.normalizeLocation({axis.name: axis.default}).get(axis.name)
3162
+ # and set them in the axis.minimum
3163
+ axis.minimum = minimum
3164
+ axis.maximum = maximum
3165
+ axis.default = default
3166
+ # now the rules
3167
+ for rule in self.rules:
3168
+ newConditionSets = []
3169
+ for conditions in rule.conditionSets:
3170
+ newConditions = []
3171
+ for cond in conditions:
3172
+ if cond.get("minimum") is not None:
3173
+ minimum = self.normalizeLocation(
3174
+ {cond["name"]: cond["minimum"]}
3175
+ ).get(cond["name"])
3176
+ else:
3177
+ minimum = None
3178
+ if cond.get("maximum") is not None:
3179
+ maximum = self.normalizeLocation(
3180
+ {cond["name"]: cond["maximum"]}
3181
+ ).get(cond["name"])
3182
+ else:
3183
+ maximum = None
3184
+ newConditions.append(
3185
+ dict(name=cond["name"], minimum=minimum, maximum=maximum)
3186
+ )
3187
+ newConditionSets.append(newConditions)
3188
+ rule.conditionSets = newConditionSets
3189
+
3190
+ def loadSourceFonts(self, opener, **kwargs):
3191
+ """Ensure SourceDescriptor.font attributes are loaded, and return list of fonts.
3192
+
3193
+ Takes a callable which initializes a new font object (e.g. TTFont, or
3194
+ defcon.Font, etc.) from the SourceDescriptor.path, and sets the
3195
+ SourceDescriptor.font attribute.
3196
+ If the font attribute is already not None, it is not loaded again.
3197
+ Fonts with the same path are only loaded once and shared among SourceDescriptors.
3198
+
3199
+ For example, to load UFO sources using defcon:
3200
+
3201
+ designspace = DesignSpaceDocument.fromfile("path/to/my.designspace")
3202
+ designspace.loadSourceFonts(defcon.Font)
3203
+
3204
+ Or to load masters as FontTools binary fonts, including extra options:
3205
+
3206
+ designspace.loadSourceFonts(ttLib.TTFont, recalcBBoxes=False)
3207
+
3208
+ Args:
3209
+ opener (Callable): takes one required positional argument, the source.path,
3210
+ and an optional list of keyword arguments, and returns a new font object
3211
+ loaded from the path.
3212
+ **kwargs: extra options passed on to the opener function.
3213
+
3214
+ Returns:
3215
+ List of font objects in the order they appear in the sources list.
3216
+ """
3217
+ # we load fonts with the same source.path only once
3218
+ loaded = {}
3219
+ fonts = []
3220
+ for source in self.sources:
3221
+ if source.font is not None: # font already loaded
3222
+ fonts.append(source.font)
3223
+ continue
3224
+ if source.path in loaded:
3225
+ source.font = loaded[source.path]
3226
+ else:
3227
+ if source.path is None:
3228
+ raise DesignSpaceDocumentError(
3229
+ "Designspace source '%s' has no 'path' attribute"
3230
+ % (source.name or "<Unknown>")
3231
+ )
3232
+ source.font = opener(source.path, **kwargs)
3233
+ loaded[source.path] = source.font
3234
+ fonts.append(source.font)
3235
+ return fonts
3236
+
3237
+ @property
3238
+ def formatTuple(self):
3239
+ """Return the formatVersion as a tuple of (major, minor).
3240
+
3241
+ .. versionadded:: 5.0
3242
+ """
3243
+ if self.formatVersion is None:
3244
+ return (5, 0)
3245
+ numbers = (int(i) for i in self.formatVersion.split("."))
3246
+ major = next(numbers)
3247
+ minor = next(numbers, 0)
3248
+ return (major, minor)
3249
+
3250
+ def getVariableFonts(self) -> List[VariableFontDescriptor]:
3251
+ """Return all variable fonts defined in this document, or implicit
3252
+ variable fonts that can be built from the document's continuous axes.
3253
+
3254
+ In the case of Designspace documents before version 5, the whole
3255
+ document was implicitly describing a variable font that covers the
3256
+ whole space.
3257
+
3258
+ In version 5 and above documents, there can be as many variable fonts
3259
+ as there are locations on discrete axes.
3260
+
3261
+ .. seealso:: :func:`splitInterpolable`
3262
+
3263
+ .. versionadded:: 5.0
3264
+ """
3265
+ if self.variableFonts:
3266
+ return self.variableFonts
3267
+
3268
+ variableFonts = []
3269
+ discreteAxes = []
3270
+ rangeAxisSubsets: List[
3271
+ Union[RangeAxisSubsetDescriptor, ValueAxisSubsetDescriptor]
3272
+ ] = []
3273
+ for axis in self.axes:
3274
+ if hasattr(axis, "values"):
3275
+ # Mypy doesn't support narrowing union types via hasattr()
3276
+ # TODO(Python 3.10): use TypeGuard
3277
+ # https://mypy.readthedocs.io/en/stable/type_narrowing.html
3278
+ axis = cast(DiscreteAxisDescriptor, axis)
3279
+ discreteAxes.append(axis) # type: ignore
3280
+ else:
3281
+ rangeAxisSubsets.append(RangeAxisSubsetDescriptor(name=axis.name))
3282
+ valueCombinations = itertools.product(*[axis.values for axis in discreteAxes])
3283
+ for values in valueCombinations:
3284
+ basename = None
3285
+ if self.filename is not None:
3286
+ basename = os.path.splitext(self.filename)[0] + "-VF"
3287
+ if self.path is not None:
3288
+ basename = os.path.splitext(os.path.basename(self.path))[0] + "-VF"
3289
+ if basename is None:
3290
+ basename = "VF"
3291
+ axisNames = "".join(
3292
+ [f"-{axis.tag}{value}" for axis, value in zip(discreteAxes, values)]
3293
+ )
3294
+ variableFonts.append(
3295
+ VariableFontDescriptor(
3296
+ name=f"{basename}{axisNames}",
3297
+ axisSubsets=rangeAxisSubsets
3298
+ + [
3299
+ ValueAxisSubsetDescriptor(name=axis.name, userValue=value)
3300
+ for axis, value in zip(discreteAxes, values)
3301
+ ],
3302
+ )
3303
+ )
3304
+ return variableFonts
3305
+
3306
+ def deepcopyExceptFonts(self):
3307
+ """Allow deep-copying a DesignSpace document without deep-copying
3308
+ attached UFO fonts or TTFont objects. The :attr:`font` attribute
3309
+ is shared by reference between the original and the copy.
3310
+
3311
+ .. versionadded:: 5.0
3312
+ """
3313
+ fonts = [source.font for source in self.sources]
3314
+ try:
3315
+ for source in self.sources:
3316
+ source.font = None
3317
+ res = copy.deepcopy(self)
3318
+ for source, font in zip(res.sources, fonts):
3319
+ source.font = font
3320
+ return res
3321
+ finally:
3322
+ for source, font in zip(self.sources, fonts):
3323
+ source.font = font
3324
+
3325
+
3326
+ def main(args=None):
3327
+ """Roundtrip .designspace file through the DesignSpaceDocument class"""
3328
+
3329
+ if args is None:
3330
+ import sys
3331
+
3332
+ args = sys.argv[1:]
3333
+
3334
+ from argparse import ArgumentParser
3335
+
3336
+ parser = ArgumentParser(prog="designspaceLib", description=main.__doc__)
3337
+ parser.add_argument("input")
3338
+ parser.add_argument("output")
3339
+
3340
+ options = parser.parse_args(args)
3341
+
3342
+ ds = DesignSpaceDocument.fromfile(options.input)
3343
+ ds.write(options.output)