fonttools 4.59.1__cp314-cp314-musllinux_1_2_aarch64.whl

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

Potentially problematic release.


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

Files changed (346) hide show
  1. fontTools/__init__.py +8 -0
  2. fontTools/__main__.py +35 -0
  3. fontTools/afmLib.py +439 -0
  4. fontTools/agl.py +5233 -0
  5. fontTools/cffLib/CFF2ToCFF.py +233 -0
  6. fontTools/cffLib/CFFToCFF2.py +305 -0
  7. fontTools/cffLib/__init__.py +3694 -0
  8. fontTools/cffLib/specializer.py +927 -0
  9. fontTools/cffLib/transforms.py +495 -0
  10. fontTools/cffLib/width.py +210 -0
  11. fontTools/colorLib/__init__.py +0 -0
  12. fontTools/colorLib/builder.py +664 -0
  13. fontTools/colorLib/errors.py +2 -0
  14. fontTools/colorLib/geometry.py +143 -0
  15. fontTools/colorLib/table_builder.py +223 -0
  16. fontTools/colorLib/unbuilder.py +81 -0
  17. fontTools/config/__init__.py +90 -0
  18. fontTools/cu2qu/__init__.py +15 -0
  19. fontTools/cu2qu/__main__.py +6 -0
  20. fontTools/cu2qu/benchmark.py +54 -0
  21. fontTools/cu2qu/cli.py +198 -0
  22. fontTools/cu2qu/cu2qu.c +15560 -0
  23. fontTools/cu2qu/cu2qu.cpython-314-aarch64-linux-musl.so +0 -0
  24. fontTools/cu2qu/cu2qu.py +531 -0
  25. fontTools/cu2qu/errors.py +77 -0
  26. fontTools/cu2qu/ufo.py +349 -0
  27. fontTools/designspaceLib/__init__.py +3338 -0
  28. fontTools/designspaceLib/__main__.py +6 -0
  29. fontTools/designspaceLib/split.py +475 -0
  30. fontTools/designspaceLib/statNames.py +260 -0
  31. fontTools/designspaceLib/types.py +147 -0
  32. fontTools/encodings/MacRoman.py +258 -0
  33. fontTools/encodings/StandardEncoding.py +258 -0
  34. fontTools/encodings/__init__.py +1 -0
  35. fontTools/encodings/codecs.py +135 -0
  36. fontTools/feaLib/__init__.py +4 -0
  37. fontTools/feaLib/__main__.py +78 -0
  38. fontTools/feaLib/ast.py +2143 -0
  39. fontTools/feaLib/builder.py +1802 -0
  40. fontTools/feaLib/error.py +22 -0
  41. fontTools/feaLib/lexer.c +17351 -0
  42. fontTools/feaLib/lexer.cpython-314-aarch64-linux-musl.so +0 -0
  43. fontTools/feaLib/lexer.py +287 -0
  44. fontTools/feaLib/location.py +12 -0
  45. fontTools/feaLib/lookupDebugInfo.py +12 -0
  46. fontTools/feaLib/parser.py +2379 -0
  47. fontTools/feaLib/variableScalar.py +113 -0
  48. fontTools/fontBuilder.py +1014 -0
  49. fontTools/help.py +36 -0
  50. fontTools/merge/__init__.py +248 -0
  51. fontTools/merge/__main__.py +6 -0
  52. fontTools/merge/base.py +81 -0
  53. fontTools/merge/cmap.py +173 -0
  54. fontTools/merge/layout.py +526 -0
  55. fontTools/merge/options.py +85 -0
  56. fontTools/merge/tables.py +352 -0
  57. fontTools/merge/unicode.py +78 -0
  58. fontTools/merge/util.py +143 -0
  59. fontTools/misc/__init__.py +1 -0
  60. fontTools/misc/arrayTools.py +424 -0
  61. fontTools/misc/bezierTools.c +40151 -0
  62. fontTools/misc/bezierTools.cpython-314-aarch64-linux-musl.so +0 -0
  63. fontTools/misc/bezierTools.py +1497 -0
  64. fontTools/misc/classifyTools.py +170 -0
  65. fontTools/misc/cliTools.py +53 -0
  66. fontTools/misc/configTools.py +349 -0
  67. fontTools/misc/cython.py +27 -0
  68. fontTools/misc/dictTools.py +83 -0
  69. fontTools/misc/eexec.py +119 -0
  70. fontTools/misc/encodingTools.py +72 -0
  71. fontTools/misc/etree.py +456 -0
  72. fontTools/misc/filenames.py +245 -0
  73. fontTools/misc/filesystem/__init__.py +68 -0
  74. fontTools/misc/filesystem/_base.py +134 -0
  75. fontTools/misc/filesystem/_copy.py +45 -0
  76. fontTools/misc/filesystem/_errors.py +54 -0
  77. fontTools/misc/filesystem/_info.py +75 -0
  78. fontTools/misc/filesystem/_osfs.py +164 -0
  79. fontTools/misc/filesystem/_path.py +67 -0
  80. fontTools/misc/filesystem/_subfs.py +92 -0
  81. fontTools/misc/filesystem/_tempfs.py +34 -0
  82. fontTools/misc/filesystem/_tools.py +34 -0
  83. fontTools/misc/filesystem/_walk.py +55 -0
  84. fontTools/misc/filesystem/_zipfs.py +204 -0
  85. fontTools/misc/fixedTools.py +253 -0
  86. fontTools/misc/intTools.py +25 -0
  87. fontTools/misc/iterTools.py +12 -0
  88. fontTools/misc/lazyTools.py +42 -0
  89. fontTools/misc/loggingTools.py +543 -0
  90. fontTools/misc/macCreatorType.py +56 -0
  91. fontTools/misc/macRes.py +261 -0
  92. fontTools/misc/plistlib/__init__.py +681 -0
  93. fontTools/misc/plistlib/py.typed +0 -0
  94. fontTools/misc/psCharStrings.py +1511 -0
  95. fontTools/misc/psLib.py +398 -0
  96. fontTools/misc/psOperators.py +572 -0
  97. fontTools/misc/py23.py +96 -0
  98. fontTools/misc/roundTools.py +110 -0
  99. fontTools/misc/sstruct.py +227 -0
  100. fontTools/misc/symfont.py +242 -0
  101. fontTools/misc/testTools.py +233 -0
  102. fontTools/misc/textTools.py +154 -0
  103. fontTools/misc/timeTools.py +88 -0
  104. fontTools/misc/transform.py +516 -0
  105. fontTools/misc/treeTools.py +45 -0
  106. fontTools/misc/vector.py +147 -0
  107. fontTools/misc/visitor.py +150 -0
  108. fontTools/misc/xmlReader.py +188 -0
  109. fontTools/misc/xmlWriter.py +231 -0
  110. fontTools/mtiLib/__init__.py +1400 -0
  111. fontTools/mtiLib/__main__.py +5 -0
  112. fontTools/otlLib/__init__.py +1 -0
  113. fontTools/otlLib/builder.py +3465 -0
  114. fontTools/otlLib/error.py +11 -0
  115. fontTools/otlLib/maxContextCalc.py +96 -0
  116. fontTools/otlLib/optimize/__init__.py +53 -0
  117. fontTools/otlLib/optimize/__main__.py +6 -0
  118. fontTools/otlLib/optimize/gpos.py +439 -0
  119. fontTools/pens/__init__.py +1 -0
  120. fontTools/pens/areaPen.py +52 -0
  121. fontTools/pens/basePen.py +475 -0
  122. fontTools/pens/boundsPen.py +98 -0
  123. fontTools/pens/cairoPen.py +26 -0
  124. fontTools/pens/cocoaPen.py +26 -0
  125. fontTools/pens/cu2quPen.py +325 -0
  126. fontTools/pens/explicitClosingLinePen.py +101 -0
  127. fontTools/pens/filterPen.py +241 -0
  128. fontTools/pens/freetypePen.py +462 -0
  129. fontTools/pens/hashPointPen.py +89 -0
  130. fontTools/pens/momentsPen.c +13466 -0
  131. fontTools/pens/momentsPen.cpython-314-aarch64-linux-musl.so +0 -0
  132. fontTools/pens/momentsPen.py +879 -0
  133. fontTools/pens/perimeterPen.py +69 -0
  134. fontTools/pens/pointInsidePen.py +192 -0
  135. fontTools/pens/pointPen.py +609 -0
  136. fontTools/pens/qtPen.py +29 -0
  137. fontTools/pens/qu2cuPen.py +105 -0
  138. fontTools/pens/quartzPen.py +43 -0
  139. fontTools/pens/recordingPen.py +335 -0
  140. fontTools/pens/reportLabPen.py +79 -0
  141. fontTools/pens/reverseContourPen.py +96 -0
  142. fontTools/pens/roundingPen.py +130 -0
  143. fontTools/pens/statisticsPen.py +312 -0
  144. fontTools/pens/svgPathPen.py +310 -0
  145. fontTools/pens/t2CharStringPen.py +88 -0
  146. fontTools/pens/teePen.py +55 -0
  147. fontTools/pens/transformPen.py +115 -0
  148. fontTools/pens/ttGlyphPen.py +335 -0
  149. fontTools/pens/wxPen.py +29 -0
  150. fontTools/qu2cu/__init__.py +15 -0
  151. fontTools/qu2cu/__main__.py +7 -0
  152. fontTools/qu2cu/benchmark.py +56 -0
  153. fontTools/qu2cu/cli.py +125 -0
  154. fontTools/qu2cu/qu2cu.c +16753 -0
  155. fontTools/qu2cu/qu2cu.cpython-314-aarch64-linux-musl.so +0 -0
  156. fontTools/qu2cu/qu2cu.py +405 -0
  157. fontTools/subset/__init__.py +3929 -0
  158. fontTools/subset/__main__.py +6 -0
  159. fontTools/subset/cff.py +184 -0
  160. fontTools/subset/svg.py +253 -0
  161. fontTools/subset/util.py +25 -0
  162. fontTools/svgLib/__init__.py +3 -0
  163. fontTools/svgLib/path/__init__.py +65 -0
  164. fontTools/svgLib/path/arc.py +154 -0
  165. fontTools/svgLib/path/parser.py +322 -0
  166. fontTools/svgLib/path/shapes.py +183 -0
  167. fontTools/t1Lib/__init__.py +648 -0
  168. fontTools/tfmLib.py +460 -0
  169. fontTools/ttLib/__init__.py +30 -0
  170. fontTools/ttLib/__main__.py +148 -0
  171. fontTools/ttLib/macUtils.py +54 -0
  172. fontTools/ttLib/removeOverlaps.py +393 -0
  173. fontTools/ttLib/reorderGlyphs.py +285 -0
  174. fontTools/ttLib/scaleUpem.py +436 -0
  175. fontTools/ttLib/sfnt.py +661 -0
  176. fontTools/ttLib/standardGlyphOrder.py +271 -0
  177. fontTools/ttLib/tables/B_A_S_E_.py +14 -0
  178. fontTools/ttLib/tables/BitmapGlyphMetrics.py +64 -0
  179. fontTools/ttLib/tables/C_B_D_T_.py +113 -0
  180. fontTools/ttLib/tables/C_B_L_C_.py +19 -0
  181. fontTools/ttLib/tables/C_F_F_.py +61 -0
  182. fontTools/ttLib/tables/C_F_F__2.py +26 -0
  183. fontTools/ttLib/tables/C_O_L_R_.py +165 -0
  184. fontTools/ttLib/tables/C_P_A_L_.py +305 -0
  185. fontTools/ttLib/tables/D_S_I_G_.py +158 -0
  186. fontTools/ttLib/tables/D__e_b_g.py +35 -0
  187. fontTools/ttLib/tables/DefaultTable.py +49 -0
  188. fontTools/ttLib/tables/E_B_D_T_.py +835 -0
  189. fontTools/ttLib/tables/E_B_L_C_.py +718 -0
  190. fontTools/ttLib/tables/F_F_T_M_.py +52 -0
  191. fontTools/ttLib/tables/F__e_a_t.py +149 -0
  192. fontTools/ttLib/tables/G_D_E_F_.py +13 -0
  193. fontTools/ttLib/tables/G_M_A_P_.py +148 -0
  194. fontTools/ttLib/tables/G_P_K_G_.py +133 -0
  195. fontTools/ttLib/tables/G_P_O_S_.py +14 -0
  196. fontTools/ttLib/tables/G_S_U_B_.py +13 -0
  197. fontTools/ttLib/tables/G_V_A_R_.py +5 -0
  198. fontTools/ttLib/tables/G__l_a_t.py +235 -0
  199. fontTools/ttLib/tables/G__l_o_c.py +85 -0
  200. fontTools/ttLib/tables/H_V_A_R_.py +13 -0
  201. fontTools/ttLib/tables/J_S_T_F_.py +13 -0
  202. fontTools/ttLib/tables/L_T_S_H_.py +58 -0
  203. fontTools/ttLib/tables/M_A_T_H_.py +13 -0
  204. fontTools/ttLib/tables/M_E_T_A_.py +352 -0
  205. fontTools/ttLib/tables/M_V_A_R_.py +13 -0
  206. fontTools/ttLib/tables/O_S_2f_2.py +752 -0
  207. fontTools/ttLib/tables/S_I_N_G_.py +99 -0
  208. fontTools/ttLib/tables/S_T_A_T_.py +15 -0
  209. fontTools/ttLib/tables/S_V_G_.py +223 -0
  210. fontTools/ttLib/tables/S__i_l_f.py +1040 -0
  211. fontTools/ttLib/tables/S__i_l_l.py +92 -0
  212. fontTools/ttLib/tables/T_S_I_B_.py +13 -0
  213. fontTools/ttLib/tables/T_S_I_C_.py +14 -0
  214. fontTools/ttLib/tables/T_S_I_D_.py +13 -0
  215. fontTools/ttLib/tables/T_S_I_J_.py +13 -0
  216. fontTools/ttLib/tables/T_S_I_P_.py +13 -0
  217. fontTools/ttLib/tables/T_S_I_S_.py +13 -0
  218. fontTools/ttLib/tables/T_S_I_V_.py +26 -0
  219. fontTools/ttLib/tables/T_S_I__0.py +70 -0
  220. fontTools/ttLib/tables/T_S_I__1.py +163 -0
  221. fontTools/ttLib/tables/T_S_I__2.py +17 -0
  222. fontTools/ttLib/tables/T_S_I__3.py +22 -0
  223. fontTools/ttLib/tables/T_S_I__5.py +60 -0
  224. fontTools/ttLib/tables/T_T_F_A_.py +14 -0
  225. fontTools/ttLib/tables/TupleVariation.py +884 -0
  226. fontTools/ttLib/tables/V_A_R_C_.py +12 -0
  227. fontTools/ttLib/tables/V_D_M_X_.py +249 -0
  228. fontTools/ttLib/tables/V_O_R_G_.py +165 -0
  229. fontTools/ttLib/tables/V_V_A_R_.py +13 -0
  230. fontTools/ttLib/tables/__init__.py +98 -0
  231. fontTools/ttLib/tables/_a_n_k_r.py +15 -0
  232. fontTools/ttLib/tables/_a_v_a_r.py +191 -0
  233. fontTools/ttLib/tables/_b_s_l_n.py +15 -0
  234. fontTools/ttLib/tables/_c_i_d_g.py +24 -0
  235. fontTools/ttLib/tables/_c_m_a_p.py +1591 -0
  236. fontTools/ttLib/tables/_c_v_a_r.py +94 -0
  237. fontTools/ttLib/tables/_c_v_t.py +56 -0
  238. fontTools/ttLib/tables/_f_e_a_t.py +15 -0
  239. fontTools/ttLib/tables/_f_p_g_m.py +62 -0
  240. fontTools/ttLib/tables/_f_v_a_r.py +261 -0
  241. fontTools/ttLib/tables/_g_a_s_p.py +63 -0
  242. fontTools/ttLib/tables/_g_c_i_d.py +13 -0
  243. fontTools/ttLib/tables/_g_l_y_f.py +2311 -0
  244. fontTools/ttLib/tables/_g_v_a_r.py +340 -0
  245. fontTools/ttLib/tables/_h_d_m_x.py +127 -0
  246. fontTools/ttLib/tables/_h_e_a_d.py +130 -0
  247. fontTools/ttLib/tables/_h_h_e_a.py +147 -0
  248. fontTools/ttLib/tables/_h_m_t_x.py +164 -0
  249. fontTools/ttLib/tables/_k_e_r_n.py +289 -0
  250. fontTools/ttLib/tables/_l_c_a_r.py +13 -0
  251. fontTools/ttLib/tables/_l_o_c_a.py +70 -0
  252. fontTools/ttLib/tables/_l_t_a_g.py +72 -0
  253. fontTools/ttLib/tables/_m_a_x_p.py +147 -0
  254. fontTools/ttLib/tables/_m_e_t_a.py +112 -0
  255. fontTools/ttLib/tables/_m_o_r_t.py +14 -0
  256. fontTools/ttLib/tables/_m_o_r_x.py +15 -0
  257. fontTools/ttLib/tables/_n_a_m_e.py +1237 -0
  258. fontTools/ttLib/tables/_o_p_b_d.py +14 -0
  259. fontTools/ttLib/tables/_p_o_s_t.py +319 -0
  260. fontTools/ttLib/tables/_p_r_e_p.py +16 -0
  261. fontTools/ttLib/tables/_p_r_o_p.py +12 -0
  262. fontTools/ttLib/tables/_s_b_i_x.py +129 -0
  263. fontTools/ttLib/tables/_t_r_a_k.py +332 -0
  264. fontTools/ttLib/tables/_v_h_e_a.py +139 -0
  265. fontTools/ttLib/tables/_v_m_t_x.py +19 -0
  266. fontTools/ttLib/tables/asciiTable.py +20 -0
  267. fontTools/ttLib/tables/grUtils.py +92 -0
  268. fontTools/ttLib/tables/otBase.py +1464 -0
  269. fontTools/ttLib/tables/otConverters.py +2068 -0
  270. fontTools/ttLib/tables/otData.py +6400 -0
  271. fontTools/ttLib/tables/otTables.py +2703 -0
  272. fontTools/ttLib/tables/otTraverse.py +163 -0
  273. fontTools/ttLib/tables/sbixGlyph.py +149 -0
  274. fontTools/ttLib/tables/sbixStrike.py +177 -0
  275. fontTools/ttLib/tables/table_API_readme.txt +91 -0
  276. fontTools/ttLib/tables/ttProgram.py +594 -0
  277. fontTools/ttLib/ttCollection.py +125 -0
  278. fontTools/ttLib/ttFont.py +1148 -0
  279. fontTools/ttLib/ttGlyphSet.py +490 -0
  280. fontTools/ttLib/ttVisitor.py +32 -0
  281. fontTools/ttLib/woff2.py +1680 -0
  282. fontTools/ttx.py +479 -0
  283. fontTools/ufoLib/__init__.py +2472 -0
  284. fontTools/ufoLib/converters.py +398 -0
  285. fontTools/ufoLib/errors.py +30 -0
  286. fontTools/ufoLib/etree.py +6 -0
  287. fontTools/ufoLib/filenames.py +346 -0
  288. fontTools/ufoLib/glifLib.py +2024 -0
  289. fontTools/ufoLib/kerning.py +121 -0
  290. fontTools/ufoLib/plistlib.py +47 -0
  291. fontTools/ufoLib/pointPen.py +6 -0
  292. fontTools/ufoLib/utils.py +79 -0
  293. fontTools/ufoLib/validators.py +1184 -0
  294. fontTools/unicode.py +50 -0
  295. fontTools/unicodedata/Blocks.py +801 -0
  296. fontTools/unicodedata/Mirrored.py +446 -0
  297. fontTools/unicodedata/OTTags.py +50 -0
  298. fontTools/unicodedata/ScriptExtensions.py +826 -0
  299. fontTools/unicodedata/Scripts.py +3617 -0
  300. fontTools/unicodedata/__init__.py +304 -0
  301. fontTools/varLib/__init__.py +1517 -0
  302. fontTools/varLib/__main__.py +6 -0
  303. fontTools/varLib/avar.py +260 -0
  304. fontTools/varLib/avarPlanner.py +1004 -0
  305. fontTools/varLib/builder.py +215 -0
  306. fontTools/varLib/cff.py +631 -0
  307. fontTools/varLib/errors.py +219 -0
  308. fontTools/varLib/featureVars.py +703 -0
  309. fontTools/varLib/hvar.py +113 -0
  310. fontTools/varLib/instancer/__init__.py +2014 -0
  311. fontTools/varLib/instancer/__main__.py +5 -0
  312. fontTools/varLib/instancer/featureVars.py +190 -0
  313. fontTools/varLib/instancer/names.py +388 -0
  314. fontTools/varLib/instancer/solver.py +309 -0
  315. fontTools/varLib/interpolatable.py +1209 -0
  316. fontTools/varLib/interpolatableHelpers.py +396 -0
  317. fontTools/varLib/interpolatablePlot.py +1269 -0
  318. fontTools/varLib/interpolatableTestContourOrder.py +82 -0
  319. fontTools/varLib/interpolatableTestStartingPoint.py +107 -0
  320. fontTools/varLib/interpolate_layout.py +124 -0
  321. fontTools/varLib/iup.c +19845 -0
  322. fontTools/varLib/iup.cpython-314-aarch64-linux-musl.so +0 -0
  323. fontTools/varLib/iup.py +490 -0
  324. fontTools/varLib/merger.py +1717 -0
  325. fontTools/varLib/models.py +642 -0
  326. fontTools/varLib/multiVarStore.py +253 -0
  327. fontTools/varLib/mutator.py +529 -0
  328. fontTools/varLib/mvar.py +40 -0
  329. fontTools/varLib/plot.py +238 -0
  330. fontTools/varLib/stat.py +149 -0
  331. fontTools/varLib/varStore.py +739 -0
  332. fontTools/voltLib/__init__.py +5 -0
  333. fontTools/voltLib/__main__.py +206 -0
  334. fontTools/voltLib/ast.py +452 -0
  335. fontTools/voltLib/error.py +12 -0
  336. fontTools/voltLib/lexer.py +99 -0
  337. fontTools/voltLib/parser.py +664 -0
  338. fontTools/voltLib/voltToFea.py +911 -0
  339. fonttools-4.59.1.data/data/share/man/man1/ttx.1 +225 -0
  340. fonttools-4.59.1.dist-info/METADATA +2175 -0
  341. fonttools-4.59.1.dist-info/RECORD +346 -0
  342. fonttools-4.59.1.dist-info/WHEEL +5 -0
  343. fonttools-4.59.1.dist-info/entry_points.txt +5 -0
  344. fonttools-4.59.1.dist-info/licenses/LICENSE +21 -0
  345. fonttools-4.59.1.dist-info/licenses/LICENSE.external +388 -0
  346. fonttools-4.59.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3338 @@
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
+ self.axisSubsets: List[
1328
+ Union[RangeAxisSubsetDescriptor, ValueAxisSubsetDescriptor]
1329
+ ] = (axisSubsets or [])
1330
+ """Axis subsets to include in this variable font.
1331
+
1332
+ If an axis is not mentioned, assume that we only want the default
1333
+ location of that axis (same as a :class:`ValueAxisSubsetDescriptor`).
1334
+ """
1335
+ self.lib: MutableMapping[str, Any] = lib or {}
1336
+ """Custom data associated with this variable font."""
1337
+
1338
+
1339
+ class RangeAxisSubsetDescriptor(SimpleDescriptor):
1340
+ """Subset of a continuous axis to include in a variable font.
1341
+
1342
+ .. versionadded:: 5.0
1343
+ """
1344
+
1345
+ flavor = "axis-subset"
1346
+ _attrs = ("name", "userMinimum", "userDefault", "userMaximum")
1347
+
1348
+ def __init__(
1349
+ self, *, name, userMinimum=-math.inf, userDefault=None, userMaximum=math.inf
1350
+ ):
1351
+ self.name: str = name
1352
+ """Name of the :class:`AxisDescriptor` to subset."""
1353
+ self.userMinimum: float = userMinimum
1354
+ """New minimum value of the axis in the target variable font.
1355
+ If not specified, assume the same minimum value as the full axis.
1356
+ (default = ``-math.inf``)
1357
+ """
1358
+ self.userDefault: Optional[float] = userDefault
1359
+ """New default value of the axis in the target variable font.
1360
+ If not specified, assume the same default value as the full axis.
1361
+ (default = ``None``)
1362
+ """
1363
+ self.userMaximum: float = userMaximum
1364
+ """New maximum value of the axis in the target variable font.
1365
+ If not specified, assume the same maximum value as the full axis.
1366
+ (default = ``math.inf``)
1367
+ """
1368
+
1369
+
1370
+ class ValueAxisSubsetDescriptor(SimpleDescriptor):
1371
+ """Single value of a discrete or continuous axis to use in a variable font.
1372
+
1373
+ .. versionadded:: 5.0
1374
+ """
1375
+
1376
+ flavor = "axis-subset"
1377
+ _attrs = ("name", "userValue")
1378
+
1379
+ def __init__(self, *, name, userValue):
1380
+ self.name: str = name
1381
+ """Name of the :class:`AxisDescriptor` or :class:`DiscreteAxisDescriptor`
1382
+ to "snapshot" or "freeze".
1383
+ """
1384
+ self.userValue: float = userValue
1385
+ """Value in user coordinates at which to freeze the given axis."""
1386
+
1387
+
1388
+ class BaseDocWriter(object):
1389
+ _whiteSpace = " "
1390
+ axisDescriptorClass = AxisDescriptor
1391
+ discreteAxisDescriptorClass = DiscreteAxisDescriptor
1392
+ axisLabelDescriptorClass = AxisLabelDescriptor
1393
+ axisMappingDescriptorClass = AxisMappingDescriptor
1394
+ locationLabelDescriptorClass = LocationLabelDescriptor
1395
+ ruleDescriptorClass = RuleDescriptor
1396
+ sourceDescriptorClass = SourceDescriptor
1397
+ variableFontDescriptorClass = VariableFontDescriptor
1398
+ valueAxisSubsetDescriptorClass = ValueAxisSubsetDescriptor
1399
+ rangeAxisSubsetDescriptorClass = RangeAxisSubsetDescriptor
1400
+ instanceDescriptorClass = InstanceDescriptor
1401
+
1402
+ @classmethod
1403
+ def getAxisDecriptor(cls):
1404
+ return cls.axisDescriptorClass()
1405
+
1406
+ @classmethod
1407
+ def getAxisMappingDescriptor(cls):
1408
+ return cls.axisMappingDescriptorClass()
1409
+
1410
+ @classmethod
1411
+ def getSourceDescriptor(cls):
1412
+ return cls.sourceDescriptorClass()
1413
+
1414
+ @classmethod
1415
+ def getInstanceDescriptor(cls):
1416
+ return cls.instanceDescriptorClass()
1417
+
1418
+ @classmethod
1419
+ def getRuleDescriptor(cls):
1420
+ return cls.ruleDescriptorClass()
1421
+
1422
+ def __init__(self, documentPath, documentObject: DesignSpaceDocument):
1423
+ self.path = documentPath
1424
+ self.documentObject = documentObject
1425
+ self.effectiveFormatTuple = self._getEffectiveFormatTuple()
1426
+ self.root = ET.Element("designspace")
1427
+
1428
+ def write(self, pretty=True, encoding="UTF-8", xml_declaration=True):
1429
+ self.root.attrib["format"] = ".".join(str(i) for i in self.effectiveFormatTuple)
1430
+
1431
+ if (
1432
+ self.documentObject.axes
1433
+ or self.documentObject.axisMappings
1434
+ or self.documentObject.elidedFallbackName is not None
1435
+ ):
1436
+ axesElement = ET.Element("axes")
1437
+ if self.documentObject.elidedFallbackName is not None:
1438
+ axesElement.attrib["elidedfallbackname"] = (
1439
+ self.documentObject.elidedFallbackName
1440
+ )
1441
+ self.root.append(axesElement)
1442
+ for axisObject in self.documentObject.axes:
1443
+ self._addAxis(axisObject)
1444
+
1445
+ if self.documentObject.axisMappings:
1446
+ mappingsElement = None
1447
+ lastGroup = object()
1448
+ for mappingObject in self.documentObject.axisMappings:
1449
+ if getattr(mappingObject, "groupDescription", None) != lastGroup:
1450
+ if mappingsElement is not None:
1451
+ self.root.findall(".axes")[0].append(mappingsElement)
1452
+ lastGroup = getattr(mappingObject, "groupDescription", None)
1453
+ mappingsElement = ET.Element("mappings")
1454
+ if lastGroup is not None:
1455
+ mappingsElement.attrib["description"] = lastGroup
1456
+ self._addAxisMapping(mappingsElement, mappingObject)
1457
+ if mappingsElement is not None:
1458
+ self.root.findall(".axes")[0].append(mappingsElement)
1459
+
1460
+ if self.documentObject.locationLabels:
1461
+ labelsElement = ET.Element("labels")
1462
+ for labelObject in self.documentObject.locationLabels:
1463
+ self._addLocationLabel(labelsElement, labelObject)
1464
+ self.root.append(labelsElement)
1465
+
1466
+ if self.documentObject.rules:
1467
+ if getattr(self.documentObject, "rulesProcessingLast", False):
1468
+ attributes = {"processing": "last"}
1469
+ else:
1470
+ attributes = {}
1471
+ self.root.append(ET.Element("rules", attributes))
1472
+ for ruleObject in self.documentObject.rules:
1473
+ self._addRule(ruleObject)
1474
+
1475
+ if self.documentObject.sources:
1476
+ self.root.append(ET.Element("sources"))
1477
+ for sourceObject in self.documentObject.sources:
1478
+ self._addSource(sourceObject)
1479
+
1480
+ if self.documentObject.variableFonts:
1481
+ variableFontsElement = ET.Element("variable-fonts")
1482
+ for variableFont in self.documentObject.variableFonts:
1483
+ self._addVariableFont(variableFontsElement, variableFont)
1484
+ self.root.append(variableFontsElement)
1485
+
1486
+ if self.documentObject.instances:
1487
+ self.root.append(ET.Element("instances"))
1488
+ for instanceObject in self.documentObject.instances:
1489
+ self._addInstance(instanceObject)
1490
+
1491
+ if self.documentObject.lib:
1492
+ self._addLib(self.root, self.documentObject.lib, 2)
1493
+
1494
+ tree = ET.ElementTree(self.root)
1495
+ tree.write(
1496
+ self.path,
1497
+ encoding=encoding,
1498
+ method="xml",
1499
+ xml_declaration=xml_declaration,
1500
+ pretty_print=pretty,
1501
+ )
1502
+
1503
+ def _getEffectiveFormatTuple(self):
1504
+ """Try to use the version specified in the document, or a sufficiently
1505
+ recent version to be able to encode what the document contains.
1506
+ """
1507
+ minVersion = self.documentObject.formatTuple
1508
+ if (
1509
+ any(
1510
+ hasattr(axis, "values")
1511
+ or axis.axisOrdering is not None
1512
+ or axis.axisLabels
1513
+ for axis in self.documentObject.axes
1514
+ )
1515
+ or self.documentObject.locationLabels
1516
+ or any(source.localisedFamilyName for source in self.documentObject.sources)
1517
+ or self.documentObject.variableFonts
1518
+ or any(
1519
+ instance.locationLabel or instance.userLocation
1520
+ for instance in self.documentObject.instances
1521
+ )
1522
+ ):
1523
+ if minVersion < (5, 0):
1524
+ minVersion = (5, 0)
1525
+ if self.documentObject.axisMappings:
1526
+ if minVersion < (5, 1):
1527
+ minVersion = (5, 1)
1528
+ return minVersion
1529
+
1530
+ def _makeLocationElement(self, locationObject, name=None):
1531
+ """Convert Location dict to a locationElement."""
1532
+ locElement = ET.Element("location")
1533
+ if name is not None:
1534
+ locElement.attrib["name"] = name
1535
+ validatedLocation = self.documentObject.newDefaultLocation()
1536
+ for axisName, axisValue in locationObject.items():
1537
+ if axisName in validatedLocation:
1538
+ # only accept values we know
1539
+ validatedLocation[axisName] = axisValue
1540
+ for dimensionName, dimensionValue in validatedLocation.items():
1541
+ dimElement = ET.Element("dimension")
1542
+ dimElement.attrib["name"] = dimensionName
1543
+ if type(dimensionValue) == tuple:
1544
+ dimElement.attrib["xvalue"] = self.intOrFloat(dimensionValue[0])
1545
+ dimElement.attrib["yvalue"] = self.intOrFloat(dimensionValue[1])
1546
+ else:
1547
+ dimElement.attrib["xvalue"] = self.intOrFloat(dimensionValue)
1548
+ locElement.append(dimElement)
1549
+ return locElement, validatedLocation
1550
+
1551
+ def intOrFloat(self, num):
1552
+ if int(num) == num:
1553
+ return "%d" % num
1554
+ return ("%f" % num).rstrip("0").rstrip(".")
1555
+
1556
+ def _addRule(self, ruleObject):
1557
+ # if none of the conditions have minimum or maximum values, do not add the rule.
1558
+ ruleElement = ET.Element("rule")
1559
+ if ruleObject.name is not None:
1560
+ ruleElement.attrib["name"] = ruleObject.name
1561
+ for conditions in ruleObject.conditionSets:
1562
+ conditionsetElement = ET.Element("conditionset")
1563
+ for cond in conditions:
1564
+ if cond.get("minimum") is None and cond.get("maximum") is None:
1565
+ # neither is defined, don't add this condition
1566
+ continue
1567
+ conditionElement = ET.Element("condition")
1568
+ conditionElement.attrib["name"] = cond.get("name")
1569
+ if cond.get("minimum") is not None:
1570
+ conditionElement.attrib["minimum"] = self.intOrFloat(
1571
+ cond.get("minimum")
1572
+ )
1573
+ if cond.get("maximum") is not None:
1574
+ conditionElement.attrib["maximum"] = self.intOrFloat(
1575
+ cond.get("maximum")
1576
+ )
1577
+ conditionsetElement.append(conditionElement)
1578
+ if len(conditionsetElement):
1579
+ ruleElement.append(conditionsetElement)
1580
+ for sub in ruleObject.subs:
1581
+ subElement = ET.Element("sub")
1582
+ subElement.attrib["name"] = sub[0]
1583
+ subElement.attrib["with"] = sub[1]
1584
+ ruleElement.append(subElement)
1585
+ if len(ruleElement):
1586
+ self.root.findall(".rules")[0].append(ruleElement)
1587
+
1588
+ def _addAxis(self, axisObject):
1589
+ axisElement = ET.Element("axis")
1590
+ axisElement.attrib["tag"] = axisObject.tag
1591
+ axisElement.attrib["name"] = axisObject.name
1592
+ self._addLabelNames(axisElement, axisObject.labelNames)
1593
+ if axisObject.map:
1594
+ for inputValue, outputValue in axisObject.map:
1595
+ mapElement = ET.Element("map")
1596
+ mapElement.attrib["input"] = self.intOrFloat(inputValue)
1597
+ mapElement.attrib["output"] = self.intOrFloat(outputValue)
1598
+ axisElement.append(mapElement)
1599
+ if axisObject.axisOrdering is not None or axisObject.axisLabels:
1600
+ labelsElement = ET.Element("labels")
1601
+ if axisObject.axisOrdering is not None:
1602
+ labelsElement.attrib["ordering"] = str(axisObject.axisOrdering)
1603
+ for label in axisObject.axisLabels:
1604
+ self._addAxisLabel(labelsElement, label)
1605
+ axisElement.append(labelsElement)
1606
+ if hasattr(axisObject, "minimum"):
1607
+ axisElement.attrib["minimum"] = self.intOrFloat(axisObject.minimum)
1608
+ axisElement.attrib["maximum"] = self.intOrFloat(axisObject.maximum)
1609
+ elif hasattr(axisObject, "values"):
1610
+ axisElement.attrib["values"] = " ".join(
1611
+ self.intOrFloat(v) for v in axisObject.values
1612
+ )
1613
+ axisElement.attrib["default"] = self.intOrFloat(axisObject.default)
1614
+ if axisObject.hidden:
1615
+ axisElement.attrib["hidden"] = "1"
1616
+ self.root.findall(".axes")[0].append(axisElement)
1617
+
1618
+ def _addAxisMapping(self, mappingsElement, mappingObject):
1619
+ mappingElement = ET.Element("mapping")
1620
+ if getattr(mappingObject, "description", None) is not None:
1621
+ mappingElement.attrib["description"] = mappingObject.description
1622
+ for what in ("inputLocation", "outputLocation"):
1623
+ whatObject = getattr(mappingObject, what, None)
1624
+ if whatObject is None:
1625
+ continue
1626
+ whatElement = ET.Element(what[:-8])
1627
+ mappingElement.append(whatElement)
1628
+
1629
+ for name, value in whatObject.items():
1630
+ dimensionElement = ET.Element("dimension")
1631
+ dimensionElement.attrib["name"] = name
1632
+ dimensionElement.attrib["xvalue"] = self.intOrFloat(value)
1633
+ whatElement.append(dimensionElement)
1634
+
1635
+ mappingsElement.append(mappingElement)
1636
+
1637
+ def _addAxisLabel(
1638
+ self, axisElement: ET.Element, label: AxisLabelDescriptor
1639
+ ) -> None:
1640
+ labelElement = ET.Element("label")
1641
+ labelElement.attrib["uservalue"] = self.intOrFloat(label.userValue)
1642
+ if label.userMinimum is not None:
1643
+ labelElement.attrib["userminimum"] = self.intOrFloat(label.userMinimum)
1644
+ if label.userMaximum is not None:
1645
+ labelElement.attrib["usermaximum"] = self.intOrFloat(label.userMaximum)
1646
+ labelElement.attrib["name"] = label.name
1647
+ if label.elidable:
1648
+ labelElement.attrib["elidable"] = "true"
1649
+ if label.olderSibling:
1650
+ labelElement.attrib["oldersibling"] = "true"
1651
+ if label.linkedUserValue is not None:
1652
+ labelElement.attrib["linkeduservalue"] = self.intOrFloat(
1653
+ label.linkedUserValue
1654
+ )
1655
+ self._addLabelNames(labelElement, label.labelNames)
1656
+ axisElement.append(labelElement)
1657
+
1658
+ def _addLabelNames(self, parentElement, labelNames):
1659
+ for languageCode, labelName in sorted(labelNames.items()):
1660
+ languageElement = ET.Element("labelname")
1661
+ languageElement.attrib[XML_LANG] = languageCode
1662
+ languageElement.text = labelName
1663
+ parentElement.append(languageElement)
1664
+
1665
+ def _addLocationLabel(
1666
+ self, parentElement: ET.Element, label: LocationLabelDescriptor
1667
+ ) -> None:
1668
+ labelElement = ET.Element("label")
1669
+ labelElement.attrib["name"] = label.name
1670
+ if label.elidable:
1671
+ labelElement.attrib["elidable"] = "true"
1672
+ if label.olderSibling:
1673
+ labelElement.attrib["oldersibling"] = "true"
1674
+ self._addLabelNames(labelElement, label.labelNames)
1675
+ self._addLocationElement(labelElement, userLocation=label.userLocation)
1676
+ parentElement.append(labelElement)
1677
+
1678
+ def _addLocationElement(
1679
+ self,
1680
+ parentElement,
1681
+ *,
1682
+ designLocation: AnisotropicLocationDict = None,
1683
+ userLocation: SimpleLocationDict = None,
1684
+ ):
1685
+ locElement = ET.Element("location")
1686
+ for axis in self.documentObject.axes:
1687
+ if designLocation is not None and axis.name in designLocation:
1688
+ dimElement = ET.Element("dimension")
1689
+ dimElement.attrib["name"] = axis.name
1690
+ value = designLocation[axis.name]
1691
+ if isinstance(value, tuple):
1692
+ dimElement.attrib["xvalue"] = self.intOrFloat(value[0])
1693
+ dimElement.attrib["yvalue"] = self.intOrFloat(value[1])
1694
+ else:
1695
+ dimElement.attrib["xvalue"] = self.intOrFloat(value)
1696
+ locElement.append(dimElement)
1697
+ elif userLocation is not None and axis.name in userLocation:
1698
+ dimElement = ET.Element("dimension")
1699
+ dimElement.attrib["name"] = axis.name
1700
+ value = userLocation[axis.name]
1701
+ dimElement.attrib["uservalue"] = self.intOrFloat(value)
1702
+ locElement.append(dimElement)
1703
+ if len(locElement) > 0:
1704
+ parentElement.append(locElement)
1705
+
1706
+ def _addInstance(self, instanceObject):
1707
+ instanceElement = ET.Element("instance")
1708
+ if instanceObject.name is not None:
1709
+ instanceElement.attrib["name"] = instanceObject.name
1710
+ if instanceObject.locationLabel is not None:
1711
+ instanceElement.attrib["location"] = instanceObject.locationLabel
1712
+ if instanceObject.familyName is not None:
1713
+ instanceElement.attrib["familyname"] = instanceObject.familyName
1714
+ if instanceObject.styleName is not None:
1715
+ instanceElement.attrib["stylename"] = instanceObject.styleName
1716
+ # add localisations
1717
+ if instanceObject.localisedStyleName:
1718
+ languageCodes = list(instanceObject.localisedStyleName.keys())
1719
+ languageCodes.sort()
1720
+ for code in languageCodes:
1721
+ if code == "en":
1722
+ continue # already stored in the element attribute
1723
+ localisedStyleNameElement = ET.Element("stylename")
1724
+ localisedStyleNameElement.attrib[XML_LANG] = code
1725
+ localisedStyleNameElement.text = instanceObject.getStyleName(code)
1726
+ instanceElement.append(localisedStyleNameElement)
1727
+ if instanceObject.localisedFamilyName:
1728
+ languageCodes = list(instanceObject.localisedFamilyName.keys())
1729
+ languageCodes.sort()
1730
+ for code in languageCodes:
1731
+ if code == "en":
1732
+ continue # already stored in the element attribute
1733
+ localisedFamilyNameElement = ET.Element("familyname")
1734
+ localisedFamilyNameElement.attrib[XML_LANG] = code
1735
+ localisedFamilyNameElement.text = instanceObject.getFamilyName(code)
1736
+ instanceElement.append(localisedFamilyNameElement)
1737
+ if instanceObject.localisedStyleMapStyleName:
1738
+ languageCodes = list(instanceObject.localisedStyleMapStyleName.keys())
1739
+ languageCodes.sort()
1740
+ for code in languageCodes:
1741
+ if code == "en":
1742
+ continue
1743
+ localisedStyleMapStyleNameElement = ET.Element("stylemapstylename")
1744
+ localisedStyleMapStyleNameElement.attrib[XML_LANG] = code
1745
+ localisedStyleMapStyleNameElement.text = (
1746
+ instanceObject.getStyleMapStyleName(code)
1747
+ )
1748
+ instanceElement.append(localisedStyleMapStyleNameElement)
1749
+ if instanceObject.localisedStyleMapFamilyName:
1750
+ languageCodes = list(instanceObject.localisedStyleMapFamilyName.keys())
1751
+ languageCodes.sort()
1752
+ for code in languageCodes:
1753
+ if code == "en":
1754
+ continue
1755
+ localisedStyleMapFamilyNameElement = ET.Element("stylemapfamilyname")
1756
+ localisedStyleMapFamilyNameElement.attrib[XML_LANG] = code
1757
+ localisedStyleMapFamilyNameElement.text = (
1758
+ instanceObject.getStyleMapFamilyName(code)
1759
+ )
1760
+ instanceElement.append(localisedStyleMapFamilyNameElement)
1761
+
1762
+ if self.effectiveFormatTuple >= (5, 0):
1763
+ if instanceObject.locationLabel is None:
1764
+ self._addLocationElement(
1765
+ instanceElement,
1766
+ designLocation=instanceObject.designLocation,
1767
+ userLocation=instanceObject.userLocation,
1768
+ )
1769
+ else:
1770
+ # Pre-version 5.0 code was validating and filling in the location
1771
+ # dict while writing it out, as preserved below.
1772
+ if instanceObject.location is not None:
1773
+ locationElement, instanceObject.location = self._makeLocationElement(
1774
+ instanceObject.location
1775
+ )
1776
+ instanceElement.append(locationElement)
1777
+ if instanceObject.filename is not None:
1778
+ instanceElement.attrib["filename"] = instanceObject.filename
1779
+ if instanceObject.postScriptFontName is not None:
1780
+ instanceElement.attrib["postscriptfontname"] = (
1781
+ instanceObject.postScriptFontName
1782
+ )
1783
+ if instanceObject.styleMapFamilyName is not None:
1784
+ instanceElement.attrib["stylemapfamilyname"] = (
1785
+ instanceObject.styleMapFamilyName
1786
+ )
1787
+ if instanceObject.styleMapStyleName is not None:
1788
+ instanceElement.attrib["stylemapstylename"] = (
1789
+ instanceObject.styleMapStyleName
1790
+ )
1791
+ if self.effectiveFormatTuple < (5, 0):
1792
+ # Deprecated members as of version 5.0
1793
+ if instanceObject.glyphs:
1794
+ if instanceElement.findall(".glyphs") == []:
1795
+ glyphsElement = ET.Element("glyphs")
1796
+ instanceElement.append(glyphsElement)
1797
+ glyphsElement = instanceElement.findall(".glyphs")[0]
1798
+ for glyphName, data in sorted(instanceObject.glyphs.items()):
1799
+ glyphElement = self._writeGlyphElement(
1800
+ instanceElement, instanceObject, glyphName, data
1801
+ )
1802
+ glyphsElement.append(glyphElement)
1803
+ if instanceObject.kerning:
1804
+ kerningElement = ET.Element("kerning")
1805
+ instanceElement.append(kerningElement)
1806
+ if instanceObject.info:
1807
+ infoElement = ET.Element("info")
1808
+ instanceElement.append(infoElement)
1809
+ self._addLib(instanceElement, instanceObject.lib, 4)
1810
+ self.root.findall(".instances")[0].append(instanceElement)
1811
+
1812
+ def _addSource(self, sourceObject):
1813
+ sourceElement = ET.Element("source")
1814
+ if sourceObject.filename is not None:
1815
+ sourceElement.attrib["filename"] = sourceObject.filename
1816
+ if sourceObject.name is not None:
1817
+ if sourceObject.name.find("temp_master") != 0:
1818
+ # do not save temporary source names
1819
+ sourceElement.attrib["name"] = sourceObject.name
1820
+ if sourceObject.familyName is not None:
1821
+ sourceElement.attrib["familyname"] = sourceObject.familyName
1822
+ if sourceObject.styleName is not None:
1823
+ sourceElement.attrib["stylename"] = sourceObject.styleName
1824
+ if sourceObject.layerName is not None:
1825
+ sourceElement.attrib["layer"] = sourceObject.layerName
1826
+ if sourceObject.localisedFamilyName:
1827
+ languageCodes = list(sourceObject.localisedFamilyName.keys())
1828
+ languageCodes.sort()
1829
+ for code in languageCodes:
1830
+ if code == "en":
1831
+ continue # already stored in the element attribute
1832
+ localisedFamilyNameElement = ET.Element("familyname")
1833
+ localisedFamilyNameElement.attrib[XML_LANG] = code
1834
+ localisedFamilyNameElement.text = sourceObject.getFamilyName(code)
1835
+ sourceElement.append(localisedFamilyNameElement)
1836
+ if sourceObject.copyLib:
1837
+ libElement = ET.Element("lib")
1838
+ libElement.attrib["copy"] = "1"
1839
+ sourceElement.append(libElement)
1840
+ if sourceObject.copyGroups:
1841
+ groupsElement = ET.Element("groups")
1842
+ groupsElement.attrib["copy"] = "1"
1843
+ sourceElement.append(groupsElement)
1844
+ if sourceObject.copyFeatures:
1845
+ featuresElement = ET.Element("features")
1846
+ featuresElement.attrib["copy"] = "1"
1847
+ sourceElement.append(featuresElement)
1848
+ if sourceObject.copyInfo or sourceObject.muteInfo:
1849
+ infoElement = ET.Element("info")
1850
+ if sourceObject.copyInfo:
1851
+ infoElement.attrib["copy"] = "1"
1852
+ if sourceObject.muteInfo:
1853
+ infoElement.attrib["mute"] = "1"
1854
+ sourceElement.append(infoElement)
1855
+ if sourceObject.muteKerning:
1856
+ kerningElement = ET.Element("kerning")
1857
+ kerningElement.attrib["mute"] = "1"
1858
+ sourceElement.append(kerningElement)
1859
+ if sourceObject.mutedGlyphNames:
1860
+ for name in sourceObject.mutedGlyphNames:
1861
+ glyphElement = ET.Element("glyph")
1862
+ glyphElement.attrib["name"] = name
1863
+ glyphElement.attrib["mute"] = "1"
1864
+ sourceElement.append(glyphElement)
1865
+ if self.effectiveFormatTuple >= (5, 0):
1866
+ self._addLocationElement(
1867
+ sourceElement, designLocation=sourceObject.location
1868
+ )
1869
+ else:
1870
+ # Pre-version 5.0 code was validating and filling in the location
1871
+ # dict while writing it out, as preserved below.
1872
+ locationElement, sourceObject.location = self._makeLocationElement(
1873
+ sourceObject.location
1874
+ )
1875
+ sourceElement.append(locationElement)
1876
+ self.root.findall(".sources")[0].append(sourceElement)
1877
+
1878
+ def _addVariableFont(
1879
+ self, parentElement: ET.Element, vf: VariableFontDescriptor
1880
+ ) -> None:
1881
+ vfElement = ET.Element("variable-font")
1882
+ vfElement.attrib["name"] = vf.name
1883
+ if vf.filename is not None:
1884
+ vfElement.attrib["filename"] = vf.filename
1885
+ if vf.axisSubsets:
1886
+ subsetsElement = ET.Element("axis-subsets")
1887
+ for subset in vf.axisSubsets:
1888
+ subsetElement = ET.Element("axis-subset")
1889
+ subsetElement.attrib["name"] = subset.name
1890
+ # Mypy doesn't support narrowing union types via hasattr()
1891
+ # https://mypy.readthedocs.io/en/stable/type_narrowing.html
1892
+ # TODO(Python 3.10): use TypeGuard
1893
+ if hasattr(subset, "userMinimum"):
1894
+ subset = cast(RangeAxisSubsetDescriptor, subset)
1895
+ if subset.userMinimum != -math.inf:
1896
+ subsetElement.attrib["userminimum"] = self.intOrFloat(
1897
+ subset.userMinimum
1898
+ )
1899
+ if subset.userMaximum != math.inf:
1900
+ subsetElement.attrib["usermaximum"] = self.intOrFloat(
1901
+ subset.userMaximum
1902
+ )
1903
+ if subset.userDefault is not None:
1904
+ subsetElement.attrib["userdefault"] = self.intOrFloat(
1905
+ subset.userDefault
1906
+ )
1907
+ elif hasattr(subset, "userValue"):
1908
+ subset = cast(ValueAxisSubsetDescriptor, subset)
1909
+ subsetElement.attrib["uservalue"] = self.intOrFloat(
1910
+ subset.userValue
1911
+ )
1912
+ subsetsElement.append(subsetElement)
1913
+ vfElement.append(subsetsElement)
1914
+ self._addLib(vfElement, vf.lib, 4)
1915
+ parentElement.append(vfElement)
1916
+
1917
+ def _addLib(self, parentElement: ET.Element, data: Any, indent_level: int) -> None:
1918
+ if not data:
1919
+ return
1920
+ libElement = ET.Element("lib")
1921
+ libElement.append(plistlib.totree(data, indent_level=indent_level))
1922
+ parentElement.append(libElement)
1923
+
1924
+ def _writeGlyphElement(self, instanceElement, instanceObject, glyphName, data):
1925
+ glyphElement = ET.Element("glyph")
1926
+ if data.get("mute"):
1927
+ glyphElement.attrib["mute"] = "1"
1928
+ if data.get("unicodes") is not None:
1929
+ glyphElement.attrib["unicode"] = " ".join(
1930
+ [hex(u) for u in data.get("unicodes")]
1931
+ )
1932
+ if data.get("instanceLocation") is not None:
1933
+ locationElement, data["instanceLocation"] = self._makeLocationElement(
1934
+ data.get("instanceLocation")
1935
+ )
1936
+ glyphElement.append(locationElement)
1937
+ if glyphName is not None:
1938
+ glyphElement.attrib["name"] = glyphName
1939
+ if data.get("note") is not None:
1940
+ noteElement = ET.Element("note")
1941
+ noteElement.text = data.get("note")
1942
+ glyphElement.append(noteElement)
1943
+ if data.get("masters") is not None:
1944
+ mastersElement = ET.Element("masters")
1945
+ for m in data.get("masters"):
1946
+ masterElement = ET.Element("master")
1947
+ if m.get("glyphName") is not None:
1948
+ masterElement.attrib["glyphname"] = m.get("glyphName")
1949
+ if m.get("font") is not None:
1950
+ masterElement.attrib["source"] = m.get("font")
1951
+ if m.get("location") is not None:
1952
+ locationElement, m["location"] = self._makeLocationElement(
1953
+ m.get("location")
1954
+ )
1955
+ masterElement.append(locationElement)
1956
+ mastersElement.append(masterElement)
1957
+ glyphElement.append(mastersElement)
1958
+ return glyphElement
1959
+
1960
+
1961
+ class BaseDocReader(LogMixin):
1962
+ axisDescriptorClass = AxisDescriptor
1963
+ discreteAxisDescriptorClass = DiscreteAxisDescriptor
1964
+ axisLabelDescriptorClass = AxisLabelDescriptor
1965
+ axisMappingDescriptorClass = AxisMappingDescriptor
1966
+ locationLabelDescriptorClass = LocationLabelDescriptor
1967
+ ruleDescriptorClass = RuleDescriptor
1968
+ sourceDescriptorClass = SourceDescriptor
1969
+ variableFontsDescriptorClass = VariableFontDescriptor
1970
+ valueAxisSubsetDescriptorClass = ValueAxisSubsetDescriptor
1971
+ rangeAxisSubsetDescriptorClass = RangeAxisSubsetDescriptor
1972
+ instanceDescriptorClass = InstanceDescriptor
1973
+
1974
+ def __init__(self, documentPath, documentObject):
1975
+ self.path = documentPath
1976
+ self.documentObject = documentObject
1977
+ tree = ET.parse(self.path)
1978
+ self.root = tree.getroot()
1979
+ self.documentObject.formatVersion = self.root.attrib.get("format", "3.0")
1980
+ self._axes = []
1981
+ self.rules = []
1982
+ self.sources = []
1983
+ self.instances = []
1984
+ self.axisDefaults = {}
1985
+ self._strictAxisNames = True
1986
+
1987
+ @classmethod
1988
+ def fromstring(cls, string, documentObject):
1989
+ f = BytesIO(tobytes(string, encoding="utf-8"))
1990
+ self = cls(f, documentObject)
1991
+ self.path = None
1992
+ return self
1993
+
1994
+ def read(self):
1995
+ self.readAxes()
1996
+ self.readLabels()
1997
+ self.readRules()
1998
+ self.readVariableFonts()
1999
+ self.readSources()
2000
+ self.readInstances()
2001
+ self.readLib()
2002
+
2003
+ def readRules(self):
2004
+ # we also need to read any conditions that are outside of a condition set.
2005
+ rules = []
2006
+ rulesElement = self.root.find(".rules")
2007
+ if rulesElement is not None:
2008
+ processingValue = rulesElement.attrib.get("processing", "first")
2009
+ if processingValue not in {"first", "last"}:
2010
+ raise DesignSpaceDocumentError(
2011
+ "<rules> processing attribute value is not valid: %r, "
2012
+ "expected 'first' or 'last'" % processingValue
2013
+ )
2014
+ self.documentObject.rulesProcessingLast = processingValue == "last"
2015
+ for ruleElement in self.root.findall(".rules/rule"):
2016
+ ruleObject = self.ruleDescriptorClass()
2017
+ ruleName = ruleObject.name = ruleElement.attrib.get("name")
2018
+ # read any stray conditions outside a condition set
2019
+ externalConditions = self._readConditionElements(
2020
+ ruleElement,
2021
+ ruleName,
2022
+ )
2023
+ if externalConditions:
2024
+ ruleObject.conditionSets.append(externalConditions)
2025
+ self.log.info(
2026
+ "Found stray rule conditions outside a conditionset. "
2027
+ "Wrapped them in a new conditionset."
2028
+ )
2029
+ # read the conditionsets
2030
+ for conditionSetElement in ruleElement.findall(".conditionset"):
2031
+ conditionSet = self._readConditionElements(
2032
+ conditionSetElement,
2033
+ ruleName,
2034
+ )
2035
+ if conditionSet is not None:
2036
+ ruleObject.conditionSets.append(conditionSet)
2037
+ for subElement in ruleElement.findall(".sub"):
2038
+ a = subElement.attrib["name"]
2039
+ b = subElement.attrib["with"]
2040
+ ruleObject.subs.append((a, b))
2041
+ rules.append(ruleObject)
2042
+ self.documentObject.rules = rules
2043
+
2044
+ def _readConditionElements(self, parentElement, ruleName=None):
2045
+ cds = []
2046
+ for conditionElement in parentElement.findall(".condition"):
2047
+ cd = {}
2048
+ cdMin = conditionElement.attrib.get("minimum")
2049
+ if cdMin is not None:
2050
+ cd["minimum"] = float(cdMin)
2051
+ else:
2052
+ # will allow these to be None, assume axis.minimum
2053
+ cd["minimum"] = None
2054
+ cdMax = conditionElement.attrib.get("maximum")
2055
+ if cdMax is not None:
2056
+ cd["maximum"] = float(cdMax)
2057
+ else:
2058
+ # will allow these to be None, assume axis.maximum
2059
+ cd["maximum"] = None
2060
+ cd["name"] = conditionElement.attrib.get("name")
2061
+ # # test for things
2062
+ if cd.get("minimum") is None and cd.get("maximum") is None:
2063
+ raise DesignSpaceDocumentError(
2064
+ "condition missing required minimum or maximum in rule"
2065
+ + (" '%s'" % ruleName if ruleName is not None else "")
2066
+ )
2067
+ cds.append(cd)
2068
+ return cds
2069
+
2070
+ def readAxes(self):
2071
+ # read the axes elements, including the warp map.
2072
+ axesElement = self.root.find(".axes")
2073
+ if axesElement is not None and "elidedfallbackname" in axesElement.attrib:
2074
+ self.documentObject.elidedFallbackName = axesElement.attrib[
2075
+ "elidedfallbackname"
2076
+ ]
2077
+ axisElements = self.root.findall(".axes/axis")
2078
+ if not axisElements:
2079
+ return
2080
+ for axisElement in axisElements:
2081
+ if (
2082
+ self.documentObject.formatTuple >= (5, 0)
2083
+ and "values" in axisElement.attrib
2084
+ ):
2085
+ axisObject = self.discreteAxisDescriptorClass()
2086
+ axisObject.values = [
2087
+ float(s) for s in axisElement.attrib["values"].split(" ")
2088
+ ]
2089
+ else:
2090
+ axisObject = self.axisDescriptorClass()
2091
+ axisObject.minimum = float(axisElement.attrib.get("minimum"))
2092
+ axisObject.maximum = float(axisElement.attrib.get("maximum"))
2093
+ axisObject.default = float(axisElement.attrib.get("default"))
2094
+ axisObject.name = axisElement.attrib.get("name")
2095
+ if axisElement.attrib.get("hidden", False):
2096
+ axisObject.hidden = True
2097
+ axisObject.tag = axisElement.attrib.get("tag")
2098
+ for mapElement in axisElement.findall("map"):
2099
+ a = float(mapElement.attrib["input"])
2100
+ b = float(mapElement.attrib["output"])
2101
+ axisObject.map.append((a, b))
2102
+ for labelNameElement in axisElement.findall("labelname"):
2103
+ # Note: elementtree reads the "xml:lang" attribute name as
2104
+ # '{http://www.w3.org/XML/1998/namespace}lang'
2105
+ for key, lang in labelNameElement.items():
2106
+ if key == XML_LANG:
2107
+ axisObject.labelNames[lang] = tostr(labelNameElement.text)
2108
+ labelElement = axisElement.find(".labels")
2109
+ if labelElement is not None:
2110
+ if "ordering" in labelElement.attrib:
2111
+ axisObject.axisOrdering = int(labelElement.attrib["ordering"])
2112
+ for label in labelElement.findall(".label"):
2113
+ axisObject.axisLabels.append(self.readAxisLabel(label))
2114
+ self.documentObject.axes.append(axisObject)
2115
+ self.axisDefaults[axisObject.name] = axisObject.default
2116
+
2117
+ self.documentObject.axisMappings = []
2118
+ for mappingsElement in self.root.findall(".axes/mappings"):
2119
+ groupDescription = mappingsElement.attrib.get("description")
2120
+ for mappingElement in mappingsElement.findall("mapping"):
2121
+ description = mappingElement.attrib.get("description")
2122
+ inputElement = mappingElement.find("input")
2123
+ outputElement = mappingElement.find("output")
2124
+ inputLoc = {}
2125
+ outputLoc = {}
2126
+ for dimElement in inputElement.findall(".dimension"):
2127
+ name = dimElement.attrib["name"]
2128
+ value = float(dimElement.attrib["xvalue"])
2129
+ inputLoc[name] = value
2130
+ for dimElement in outputElement.findall(".dimension"):
2131
+ name = dimElement.attrib["name"]
2132
+ value = float(dimElement.attrib["xvalue"])
2133
+ outputLoc[name] = value
2134
+ axisMappingObject = self.axisMappingDescriptorClass(
2135
+ inputLocation=inputLoc,
2136
+ outputLocation=outputLoc,
2137
+ description=description,
2138
+ groupDescription=groupDescription,
2139
+ )
2140
+ self.documentObject.axisMappings.append(axisMappingObject)
2141
+
2142
+ def readAxisLabel(self, element: ET.Element):
2143
+ xml_attrs = {
2144
+ "userminimum",
2145
+ "uservalue",
2146
+ "usermaximum",
2147
+ "name",
2148
+ "elidable",
2149
+ "oldersibling",
2150
+ "linkeduservalue",
2151
+ }
2152
+ unknown_attrs = set(element.attrib) - xml_attrs
2153
+ if unknown_attrs:
2154
+ raise DesignSpaceDocumentError(
2155
+ f"label element contains unknown attributes: {', '.join(unknown_attrs)}"
2156
+ )
2157
+
2158
+ name = element.get("name")
2159
+ if name is None:
2160
+ raise DesignSpaceDocumentError("label element must have a name attribute.")
2161
+ valueStr = element.get("uservalue")
2162
+ if valueStr is None:
2163
+ raise DesignSpaceDocumentError(
2164
+ "label element must have a uservalue attribute."
2165
+ )
2166
+ value = float(valueStr)
2167
+ minimumStr = element.get("userminimum")
2168
+ minimum = float(minimumStr) if minimumStr is not None else None
2169
+ maximumStr = element.get("usermaximum")
2170
+ maximum = float(maximumStr) if maximumStr is not None else None
2171
+ linkedValueStr = element.get("linkeduservalue")
2172
+ linkedValue = float(linkedValueStr) if linkedValueStr is not None else None
2173
+ elidable = True if element.get("elidable") == "true" else False
2174
+ olderSibling = True if element.get("oldersibling") == "true" else False
2175
+ labelNames = {
2176
+ lang: label_name.text or ""
2177
+ for label_name in element.findall("labelname")
2178
+ for attr, lang in label_name.items()
2179
+ if attr == XML_LANG
2180
+ # Note: elementtree reads the "xml:lang" attribute name as
2181
+ # '{http://www.w3.org/XML/1998/namespace}lang'
2182
+ }
2183
+ return self.axisLabelDescriptorClass(
2184
+ name=name,
2185
+ userValue=value,
2186
+ userMinimum=minimum,
2187
+ userMaximum=maximum,
2188
+ elidable=elidable,
2189
+ olderSibling=olderSibling,
2190
+ linkedUserValue=linkedValue,
2191
+ labelNames=labelNames,
2192
+ )
2193
+
2194
+ def readLabels(self):
2195
+ if self.documentObject.formatTuple < (5, 0):
2196
+ return
2197
+
2198
+ xml_attrs = {"name", "elidable", "oldersibling"}
2199
+ for labelElement in self.root.findall(".labels/label"):
2200
+ unknown_attrs = set(labelElement.attrib) - xml_attrs
2201
+ if unknown_attrs:
2202
+ raise DesignSpaceDocumentError(
2203
+ f"Label element contains unknown attributes: {', '.join(unknown_attrs)}"
2204
+ )
2205
+
2206
+ name = labelElement.get("name")
2207
+ if name is None:
2208
+ raise DesignSpaceDocumentError(
2209
+ "label element must have a name attribute."
2210
+ )
2211
+ designLocation, userLocation = self.locationFromElement(labelElement)
2212
+ if designLocation:
2213
+ raise DesignSpaceDocumentError(
2214
+ f'<label> element "{name}" must only have user locations (using uservalue="").'
2215
+ )
2216
+ elidable = True if labelElement.get("elidable") == "true" else False
2217
+ olderSibling = True if labelElement.get("oldersibling") == "true" else False
2218
+ labelNames = {
2219
+ lang: label_name.text or ""
2220
+ for label_name in labelElement.findall("labelname")
2221
+ for attr, lang in label_name.items()
2222
+ if attr == XML_LANG
2223
+ # Note: elementtree reads the "xml:lang" attribute name as
2224
+ # '{http://www.w3.org/XML/1998/namespace}lang'
2225
+ }
2226
+ locationLabel = self.locationLabelDescriptorClass(
2227
+ name=name,
2228
+ userLocation=userLocation,
2229
+ elidable=elidable,
2230
+ olderSibling=olderSibling,
2231
+ labelNames=labelNames,
2232
+ )
2233
+ self.documentObject.locationLabels.append(locationLabel)
2234
+
2235
+ def readVariableFonts(self):
2236
+ if self.documentObject.formatTuple < (5, 0):
2237
+ return
2238
+
2239
+ xml_attrs = {"name", "filename"}
2240
+ for variableFontElement in self.root.findall(".variable-fonts/variable-font"):
2241
+ unknown_attrs = set(variableFontElement.attrib) - xml_attrs
2242
+ if unknown_attrs:
2243
+ raise DesignSpaceDocumentError(
2244
+ f"variable-font element contains unknown attributes: {', '.join(unknown_attrs)}"
2245
+ )
2246
+
2247
+ name = variableFontElement.get("name")
2248
+ if name is None:
2249
+ raise DesignSpaceDocumentError(
2250
+ "variable-font element must have a name attribute."
2251
+ )
2252
+
2253
+ filename = variableFontElement.get("filename")
2254
+
2255
+ axisSubsetsElement = variableFontElement.find(".axis-subsets")
2256
+ if axisSubsetsElement is None:
2257
+ raise DesignSpaceDocumentError(
2258
+ "variable-font element must contain an axis-subsets element."
2259
+ )
2260
+ axisSubsets = []
2261
+ for axisSubset in axisSubsetsElement.iterfind(".axis-subset"):
2262
+ axisSubsets.append(self.readAxisSubset(axisSubset))
2263
+
2264
+ lib = None
2265
+ libElement = variableFontElement.find(".lib")
2266
+ if libElement is not None:
2267
+ lib = plistlib.fromtree(libElement[0])
2268
+
2269
+ variableFont = self.variableFontsDescriptorClass(
2270
+ name=name,
2271
+ filename=filename,
2272
+ axisSubsets=axisSubsets,
2273
+ lib=lib,
2274
+ )
2275
+ self.documentObject.variableFonts.append(variableFont)
2276
+
2277
+ def readAxisSubset(self, element: ET.Element):
2278
+ if "uservalue" in element.attrib:
2279
+ xml_attrs = {"name", "uservalue"}
2280
+ unknown_attrs = set(element.attrib) - xml_attrs
2281
+ if unknown_attrs:
2282
+ raise DesignSpaceDocumentError(
2283
+ f"axis-subset element contains unknown attributes: {', '.join(unknown_attrs)}"
2284
+ )
2285
+
2286
+ name = element.get("name")
2287
+ if name is None:
2288
+ raise DesignSpaceDocumentError(
2289
+ "axis-subset element must have a name attribute."
2290
+ )
2291
+ userValueStr = element.get("uservalue")
2292
+ if userValueStr is None:
2293
+ raise DesignSpaceDocumentError(
2294
+ "The axis-subset element for a discrete subset must have a uservalue attribute."
2295
+ )
2296
+ userValue = float(userValueStr)
2297
+
2298
+ return self.valueAxisSubsetDescriptorClass(name=name, userValue=userValue)
2299
+ else:
2300
+ xml_attrs = {"name", "userminimum", "userdefault", "usermaximum"}
2301
+ unknown_attrs = set(element.attrib) - xml_attrs
2302
+ if unknown_attrs:
2303
+ raise DesignSpaceDocumentError(
2304
+ f"axis-subset element contains unknown attributes: {', '.join(unknown_attrs)}"
2305
+ )
2306
+
2307
+ name = element.get("name")
2308
+ if name is None:
2309
+ raise DesignSpaceDocumentError(
2310
+ "axis-subset element must have a name attribute."
2311
+ )
2312
+
2313
+ userMinimum = element.get("userminimum")
2314
+ userDefault = element.get("userdefault")
2315
+ userMaximum = element.get("usermaximum")
2316
+ if (
2317
+ userMinimum is not None
2318
+ and userDefault is not None
2319
+ and userMaximum is not None
2320
+ ):
2321
+ return self.rangeAxisSubsetDescriptorClass(
2322
+ name=name,
2323
+ userMinimum=float(userMinimum),
2324
+ userDefault=float(userDefault),
2325
+ userMaximum=float(userMaximum),
2326
+ )
2327
+ if all(v is None for v in (userMinimum, userDefault, userMaximum)):
2328
+ return self.rangeAxisSubsetDescriptorClass(name=name)
2329
+
2330
+ raise DesignSpaceDocumentError(
2331
+ "axis-subset element must have min/max/default values or none at all."
2332
+ )
2333
+
2334
+ def readSources(self):
2335
+ for sourceCount, sourceElement in enumerate(
2336
+ self.root.findall(".sources/source")
2337
+ ):
2338
+ filename = sourceElement.attrib.get("filename")
2339
+ if filename is not None and self.path is not None:
2340
+ sourcePath = os.path.abspath(
2341
+ os.path.join(os.path.dirname(self.path), filename)
2342
+ )
2343
+ else:
2344
+ sourcePath = None
2345
+ sourceName = sourceElement.attrib.get("name")
2346
+ if sourceName is None:
2347
+ # add a temporary source name
2348
+ sourceName = "temp_master.%d" % (sourceCount)
2349
+ sourceObject = self.sourceDescriptorClass()
2350
+ sourceObject.path = sourcePath # absolute path to the ufo source
2351
+ sourceObject.filename = filename # path as it is stored in the document
2352
+ sourceObject.name = sourceName
2353
+ familyName = sourceElement.attrib.get("familyname")
2354
+ if familyName is not None:
2355
+ sourceObject.familyName = familyName
2356
+ styleName = sourceElement.attrib.get("stylename")
2357
+ if styleName is not None:
2358
+ sourceObject.styleName = styleName
2359
+ for familyNameElement in sourceElement.findall("familyname"):
2360
+ for key, lang in familyNameElement.items():
2361
+ if key == XML_LANG:
2362
+ familyName = familyNameElement.text
2363
+ sourceObject.setFamilyName(familyName, lang)
2364
+ designLocation, userLocation = self.locationFromElement(sourceElement)
2365
+ if userLocation:
2366
+ raise DesignSpaceDocumentError(
2367
+ f'<source> element "{sourceName}" must only have design locations (using xvalue="").'
2368
+ )
2369
+ sourceObject.location = designLocation
2370
+ layerName = sourceElement.attrib.get("layer")
2371
+ if layerName is not None:
2372
+ sourceObject.layerName = layerName
2373
+ for libElement in sourceElement.findall(".lib"):
2374
+ if libElement.attrib.get("copy") == "1":
2375
+ sourceObject.copyLib = True
2376
+ for groupsElement in sourceElement.findall(".groups"):
2377
+ if groupsElement.attrib.get("copy") == "1":
2378
+ sourceObject.copyGroups = True
2379
+ for infoElement in sourceElement.findall(".info"):
2380
+ if infoElement.attrib.get("copy") == "1":
2381
+ sourceObject.copyInfo = True
2382
+ if infoElement.attrib.get("mute") == "1":
2383
+ sourceObject.muteInfo = True
2384
+ for featuresElement in sourceElement.findall(".features"):
2385
+ if featuresElement.attrib.get("copy") == "1":
2386
+ sourceObject.copyFeatures = True
2387
+ for glyphElement in sourceElement.findall(".glyph"):
2388
+ glyphName = glyphElement.attrib.get("name")
2389
+ if glyphName is None:
2390
+ continue
2391
+ if glyphElement.attrib.get("mute") == "1":
2392
+ sourceObject.mutedGlyphNames.append(glyphName)
2393
+ for kerningElement in sourceElement.findall(".kerning"):
2394
+ if kerningElement.attrib.get("mute") == "1":
2395
+ sourceObject.muteKerning = True
2396
+ self.documentObject.sources.append(sourceObject)
2397
+
2398
+ def locationFromElement(self, element):
2399
+ """Read a nested ``<location>`` element inside the given ``element``.
2400
+
2401
+ .. versionchanged:: 5.0
2402
+ Return a tuple of (designLocation, userLocation)
2403
+ """
2404
+ elementLocation = (None, None)
2405
+ for locationElement in element.findall(".location"):
2406
+ elementLocation = self.readLocationElement(locationElement)
2407
+ break
2408
+ return elementLocation
2409
+
2410
+ def readLocationElement(self, locationElement):
2411
+ """Read a ``<location>`` element.
2412
+
2413
+ .. versionchanged:: 5.0
2414
+ Return a tuple of (designLocation, userLocation)
2415
+ """
2416
+ if self._strictAxisNames and not self.documentObject.axes:
2417
+ raise DesignSpaceDocumentError("No axes defined")
2418
+ userLoc = {}
2419
+ designLoc = {}
2420
+ for dimensionElement in locationElement.findall(".dimension"):
2421
+ dimName = dimensionElement.attrib.get("name")
2422
+ if self._strictAxisNames and dimName not in self.axisDefaults:
2423
+ # In case the document contains no axis definitions,
2424
+ self.log.warning('Location with undefined axis: "%s".', dimName)
2425
+ continue
2426
+ userValue = xValue = yValue = None
2427
+ try:
2428
+ userValue = dimensionElement.attrib.get("uservalue")
2429
+ if userValue is not None:
2430
+ userValue = float(userValue)
2431
+ except ValueError:
2432
+ self.log.warning(
2433
+ "ValueError in readLocation userValue %3.3f", userValue
2434
+ )
2435
+ try:
2436
+ xValue = dimensionElement.attrib.get("xvalue")
2437
+ if xValue is not None:
2438
+ xValue = float(xValue)
2439
+ except ValueError:
2440
+ self.log.warning("ValueError in readLocation xValue %3.3f", xValue)
2441
+ try:
2442
+ yValue = dimensionElement.attrib.get("yvalue")
2443
+ if yValue is not None:
2444
+ yValue = float(yValue)
2445
+ except ValueError:
2446
+ self.log.warning("ValueError in readLocation yValue %3.3f", yValue)
2447
+ if userValue is None == xValue is None:
2448
+ raise DesignSpaceDocumentError(
2449
+ f'Exactly one of uservalue="" or xvalue="" must be provided for location dimension "{dimName}"'
2450
+ )
2451
+ if yValue is not None:
2452
+ if xValue is None:
2453
+ raise DesignSpaceDocumentError(
2454
+ f'Missing xvalue="" for the location dimension "{dimName}"" with yvalue="{yValue}"'
2455
+ )
2456
+ designLoc[dimName] = (xValue, yValue)
2457
+ elif xValue is not None:
2458
+ designLoc[dimName] = xValue
2459
+ else:
2460
+ userLoc[dimName] = userValue
2461
+ return designLoc, userLoc
2462
+
2463
+ def readInstances(self, makeGlyphs=True, makeKerning=True, makeInfo=True):
2464
+ instanceElements = self.root.findall(".instances/instance")
2465
+ for instanceElement in instanceElements:
2466
+ self._readSingleInstanceElement(
2467
+ instanceElement,
2468
+ makeGlyphs=makeGlyphs,
2469
+ makeKerning=makeKerning,
2470
+ makeInfo=makeInfo,
2471
+ )
2472
+
2473
+ def _readSingleInstanceElement(
2474
+ self, instanceElement, makeGlyphs=True, makeKerning=True, makeInfo=True
2475
+ ):
2476
+ filename = instanceElement.attrib.get("filename")
2477
+ if filename is not None and self.documentObject.path is not None:
2478
+ instancePath = os.path.join(
2479
+ os.path.dirname(self.documentObject.path), filename
2480
+ )
2481
+ else:
2482
+ instancePath = None
2483
+ instanceObject = self.instanceDescriptorClass()
2484
+ instanceObject.path = instancePath # absolute path to the instance
2485
+ instanceObject.filename = filename # path as it is stored in the document
2486
+ name = instanceElement.attrib.get("name")
2487
+ if name is not None:
2488
+ instanceObject.name = name
2489
+ familyname = instanceElement.attrib.get("familyname")
2490
+ if familyname is not None:
2491
+ instanceObject.familyName = familyname
2492
+ stylename = instanceElement.attrib.get("stylename")
2493
+ if stylename is not None:
2494
+ instanceObject.styleName = stylename
2495
+ postScriptFontName = instanceElement.attrib.get("postscriptfontname")
2496
+ if postScriptFontName is not None:
2497
+ instanceObject.postScriptFontName = postScriptFontName
2498
+ styleMapFamilyName = instanceElement.attrib.get("stylemapfamilyname")
2499
+ if styleMapFamilyName is not None:
2500
+ instanceObject.styleMapFamilyName = styleMapFamilyName
2501
+ styleMapStyleName = instanceElement.attrib.get("stylemapstylename")
2502
+ if styleMapStyleName is not None:
2503
+ instanceObject.styleMapStyleName = styleMapStyleName
2504
+ # read localised names
2505
+ for styleNameElement in instanceElement.findall("stylename"):
2506
+ for key, lang in styleNameElement.items():
2507
+ if key == XML_LANG:
2508
+ styleName = styleNameElement.text
2509
+ instanceObject.setStyleName(styleName, lang)
2510
+ for familyNameElement in instanceElement.findall("familyname"):
2511
+ for key, lang in familyNameElement.items():
2512
+ if key == XML_LANG:
2513
+ familyName = familyNameElement.text
2514
+ instanceObject.setFamilyName(familyName, lang)
2515
+ for styleMapStyleNameElement in instanceElement.findall("stylemapstylename"):
2516
+ for key, lang in styleMapStyleNameElement.items():
2517
+ if key == XML_LANG:
2518
+ styleMapStyleName = styleMapStyleNameElement.text
2519
+ instanceObject.setStyleMapStyleName(styleMapStyleName, lang)
2520
+ for styleMapFamilyNameElement in instanceElement.findall("stylemapfamilyname"):
2521
+ for key, lang in styleMapFamilyNameElement.items():
2522
+ if key == XML_LANG:
2523
+ styleMapFamilyName = styleMapFamilyNameElement.text
2524
+ instanceObject.setStyleMapFamilyName(styleMapFamilyName, lang)
2525
+ designLocation, userLocation = self.locationFromElement(instanceElement)
2526
+ locationLabel = instanceElement.attrib.get("location")
2527
+ if (designLocation or userLocation) and locationLabel is not None:
2528
+ raise DesignSpaceDocumentError(
2529
+ 'instance element must have at most one of the location="..." attribute or the nested location element'
2530
+ )
2531
+ instanceObject.locationLabel = locationLabel
2532
+ instanceObject.userLocation = userLocation or {}
2533
+ instanceObject.designLocation = designLocation or {}
2534
+ for glyphElement in instanceElement.findall(".glyphs/glyph"):
2535
+ self.readGlyphElement(glyphElement, instanceObject)
2536
+ for infoElement in instanceElement.findall("info"):
2537
+ self.readInfoElement(infoElement, instanceObject)
2538
+ for libElement in instanceElement.findall("lib"):
2539
+ self.readLibElement(libElement, instanceObject)
2540
+ self.documentObject.instances.append(instanceObject)
2541
+
2542
+ def readLibElement(self, libElement, instanceObject):
2543
+ """Read the lib element for the given instance."""
2544
+ instanceObject.lib = plistlib.fromtree(libElement[0])
2545
+
2546
+ def readInfoElement(self, infoElement, instanceObject):
2547
+ """Read the info element."""
2548
+ instanceObject.info = True
2549
+
2550
+ def readGlyphElement(self, glyphElement, instanceObject):
2551
+ """
2552
+ Read the glyph element, which could look like either one of these:
2553
+
2554
+ .. code-block:: xml
2555
+
2556
+ <glyph name="b" unicode="0x62"/>
2557
+
2558
+ <glyph name="b"/>
2559
+
2560
+ <glyph name="b">
2561
+ <master location="location-token-bbb" source="master-token-aaa2"/>
2562
+ <master glyphname="b.alt1" location="location-token-ccc" source="master-token-aaa3"/>
2563
+ <note>
2564
+ This is an instance from an anisotropic interpolation.
2565
+ </note>
2566
+ </glyph>
2567
+ """
2568
+ glyphData = {}
2569
+ glyphName = glyphElement.attrib.get("name")
2570
+ if glyphName is None:
2571
+ raise DesignSpaceDocumentError("Glyph object without name attribute")
2572
+ mute = glyphElement.attrib.get("mute")
2573
+ if mute == "1":
2574
+ glyphData["mute"] = True
2575
+ # unicode
2576
+ unicodes = glyphElement.attrib.get("unicode")
2577
+ if unicodes is not None:
2578
+ try:
2579
+ unicodes = [int(u, 16) for u in unicodes.split(" ")]
2580
+ glyphData["unicodes"] = unicodes
2581
+ except ValueError:
2582
+ raise DesignSpaceDocumentError(
2583
+ "unicode values %s are not integers" % unicodes
2584
+ )
2585
+
2586
+ for noteElement in glyphElement.findall(".note"):
2587
+ glyphData["note"] = noteElement.text
2588
+ break
2589
+ designLocation, userLocation = self.locationFromElement(glyphElement)
2590
+ if userLocation:
2591
+ raise DesignSpaceDocumentError(
2592
+ f'<glyph> element "{glyphName}" must only have design locations (using xvalue="").'
2593
+ )
2594
+ if designLocation is not None:
2595
+ glyphData["instanceLocation"] = designLocation
2596
+ glyphSources = None
2597
+ for masterElement in glyphElement.findall(".masters/master"):
2598
+ fontSourceName = masterElement.attrib.get("source")
2599
+ designLocation, userLocation = self.locationFromElement(masterElement)
2600
+ if userLocation:
2601
+ raise DesignSpaceDocumentError(
2602
+ f'<master> element "{fontSourceName}" must only have design locations (using xvalue="").'
2603
+ )
2604
+ masterGlyphName = masterElement.attrib.get("glyphname")
2605
+ if masterGlyphName is None:
2606
+ # if we don't read a glyphname, use the one we have
2607
+ masterGlyphName = glyphName
2608
+ d = dict(
2609
+ font=fontSourceName, location=designLocation, glyphName=masterGlyphName
2610
+ )
2611
+ if glyphSources is None:
2612
+ glyphSources = []
2613
+ glyphSources.append(d)
2614
+ if glyphSources is not None:
2615
+ glyphData["masters"] = glyphSources
2616
+ instanceObject.glyphs[glyphName] = glyphData
2617
+
2618
+ def readLib(self):
2619
+ """Read the lib element for the whole document."""
2620
+ for libElement in self.root.findall(".lib"):
2621
+ self.documentObject.lib = plistlib.fromtree(libElement[0])
2622
+
2623
+
2624
+ class DesignSpaceDocument(LogMixin, AsDictMixin):
2625
+ """The DesignSpaceDocument object can read and write ``.designspace`` data.
2626
+ It imports the axes, sources, variable fonts and instances to very basic
2627
+ **descriptor** objects that store the data in attributes. Data is added to
2628
+ the document by creating such descriptor objects, filling them with data
2629
+ and then adding them to the document. This makes it easy to integrate this
2630
+ object in different contexts.
2631
+
2632
+ The **DesignSpaceDocument** object can be subclassed to work with
2633
+ different objects, as long as they have the same attributes. Reader and
2634
+ Writer objects can be subclassed as well.
2635
+
2636
+ **Note:** Python attribute names are usually camelCased, the
2637
+ corresponding `XML <document-xml-structure>`_ attributes are usually
2638
+ all lowercase.
2639
+
2640
+ .. code:: python
2641
+
2642
+ from fontTools.designspaceLib import DesignSpaceDocument
2643
+ doc = DesignSpaceDocument.fromfile("some/path/to/my.designspace")
2644
+ doc.formatVersion
2645
+ doc.elidedFallbackName
2646
+ doc.axes
2647
+ doc.axisMappings
2648
+ doc.locationLabels
2649
+ doc.rules
2650
+ doc.rulesProcessingLast
2651
+ doc.sources
2652
+ doc.variableFonts
2653
+ doc.instances
2654
+ doc.lib
2655
+
2656
+ """
2657
+
2658
+ def __init__(self, readerClass=None, writerClass=None):
2659
+ self.path = None
2660
+ """String, optional. When the document is read from the disk, this is
2661
+ the full path that was given to :meth:`read` or :meth:`fromfile`.
2662
+ """
2663
+ self.filename = None
2664
+ """String, optional. When the document is read from the disk, this is
2665
+ its original file name, i.e. the last part of its path.
2666
+
2667
+ When the document is produced by a Python script and still only exists
2668
+ in memory, the producing script can write here an indication of a
2669
+ possible "good" filename, in case one wants to save the file somewhere.
2670
+ """
2671
+
2672
+ self.formatVersion: Optional[str] = None
2673
+ """Format version for this document, as a string. E.g. "4.0" """
2674
+
2675
+ self.elidedFallbackName: Optional[str] = None
2676
+ """STAT Style Attributes Header field ``elidedFallbackNameID``.
2677
+
2678
+ See: `OTSpec STAT Style Attributes Header <https://docs.microsoft.com/en-us/typography/opentype/spec/stat#style-attributes-header>`_
2679
+
2680
+ .. versionadded:: 5.0
2681
+ """
2682
+
2683
+ self.axes: List[Union[AxisDescriptor, DiscreteAxisDescriptor]] = []
2684
+ """List of this document's axes."""
2685
+
2686
+ self.axisMappings: List[AxisMappingDescriptor] = []
2687
+ """List of this document's axis mappings."""
2688
+
2689
+ self.locationLabels: List[LocationLabelDescriptor] = []
2690
+ """List of this document's STAT format 4 labels.
2691
+
2692
+ .. versionadded:: 5.0"""
2693
+ self.rules: List[RuleDescriptor] = []
2694
+ """List of this document's rules."""
2695
+ self.rulesProcessingLast: bool = False
2696
+ """This flag indicates whether the substitution rules should be applied
2697
+ before or after other glyph substitution features.
2698
+
2699
+ - False: before
2700
+ - True: after.
2701
+
2702
+ Default is False. For new projects, you probably want True. See
2703
+ the following issues for more information:
2704
+ `fontTools#1371 <https://github.com/fonttools/fonttools/issues/1371#issuecomment-590214572>`__
2705
+ `fontTools#2050 <https://github.com/fonttools/fonttools/issues/2050#issuecomment-678691020>`__
2706
+
2707
+ If you want to use a different feature altogether, e.g. ``calt``,
2708
+ use the lib key ``com.github.fonttools.varLib.featureVarsFeatureTag``
2709
+
2710
+ .. code:: xml
2711
+
2712
+ <lib>
2713
+ <dict>
2714
+ <key>com.github.fonttools.varLib.featureVarsFeatureTag</key>
2715
+ <string>calt</string>
2716
+ </dict>
2717
+ </lib>
2718
+ """
2719
+ self.sources: List[SourceDescriptor] = []
2720
+ """List of this document's sources."""
2721
+ self.variableFonts: List[VariableFontDescriptor] = []
2722
+ """List of this document's variable fonts.
2723
+
2724
+ .. versionadded:: 5.0"""
2725
+ self.instances: List[InstanceDescriptor] = []
2726
+ """List of this document's instances."""
2727
+ self.lib: Dict = {}
2728
+ """User defined, custom data associated with the whole document.
2729
+
2730
+ Use reverse-DNS notation to identify your own data.
2731
+ Respect the data stored by others.
2732
+ """
2733
+
2734
+ self.default: Optional[str] = None
2735
+ """Name of the default master.
2736
+
2737
+ This attribute is updated by the :meth:`findDefault`
2738
+ """
2739
+
2740
+ if readerClass is not None:
2741
+ self.readerClass = readerClass
2742
+ else:
2743
+ self.readerClass = BaseDocReader
2744
+ if writerClass is not None:
2745
+ self.writerClass = writerClass
2746
+ else:
2747
+ self.writerClass = BaseDocWriter
2748
+
2749
+ @classmethod
2750
+ def fromfile(cls, path, readerClass=None, writerClass=None):
2751
+ """Read a designspace file from ``path`` and return a new instance of
2752
+ :class:.
2753
+ """
2754
+ self = cls(readerClass=readerClass, writerClass=writerClass)
2755
+ self.read(path)
2756
+ return self
2757
+
2758
+ @classmethod
2759
+ def fromstring(cls, string, readerClass=None, writerClass=None):
2760
+ self = cls(readerClass=readerClass, writerClass=writerClass)
2761
+ reader = self.readerClass.fromstring(string, self)
2762
+ reader.read()
2763
+ if self.sources:
2764
+ self.findDefault()
2765
+ return self
2766
+
2767
+ def tostring(self, encoding=None):
2768
+ """Returns the designspace as a string. Default encoding ``utf-8``."""
2769
+ if encoding is str or (encoding is not None and encoding.lower() == "unicode"):
2770
+ f = StringIO()
2771
+ xml_declaration = False
2772
+ elif encoding is None or encoding == "utf-8":
2773
+ f = BytesIO()
2774
+ encoding = "UTF-8"
2775
+ xml_declaration = True
2776
+ else:
2777
+ raise ValueError("unsupported encoding: '%s'" % encoding)
2778
+ writer = self.writerClass(f, self)
2779
+ writer.write(encoding=encoding, xml_declaration=xml_declaration)
2780
+ return f.getvalue()
2781
+
2782
+ def read(self, path):
2783
+ """Read a designspace file from ``path`` and populates the fields of
2784
+ ``self`` with the data.
2785
+ """
2786
+ if hasattr(path, "__fspath__"): # support os.PathLike objects
2787
+ path = path.__fspath__()
2788
+ self.path = path
2789
+ self.filename = os.path.basename(path)
2790
+ reader = self.readerClass(path, self)
2791
+ reader.read()
2792
+ if self.sources:
2793
+ self.findDefault()
2794
+
2795
+ def write(self, path):
2796
+ """Write this designspace to ``path``."""
2797
+ if hasattr(path, "__fspath__"): # support os.PathLike objects
2798
+ path = path.__fspath__()
2799
+ self.path = path
2800
+ self.filename = os.path.basename(path)
2801
+ self.updatePaths()
2802
+ writer = self.writerClass(path, self)
2803
+ writer.write()
2804
+
2805
+ def _posixRelativePath(self, otherPath):
2806
+ relative = os.path.relpath(otherPath, os.path.dirname(self.path))
2807
+ return posix(relative)
2808
+
2809
+ def updatePaths(self):
2810
+ """
2811
+ Right before we save we need to identify and respond to the following situations:
2812
+ In each descriptor, we have to do the right thing for the filename attribute.
2813
+
2814
+ ::
2815
+
2816
+ case 1.
2817
+ descriptor.filename == None
2818
+ descriptor.path == None
2819
+
2820
+ -- action:
2821
+ write as is, descriptors will not have a filename attr.
2822
+ useless, but no reason to interfere.
2823
+
2824
+
2825
+ case 2.
2826
+ descriptor.filename == "../something"
2827
+ descriptor.path == None
2828
+
2829
+ -- action:
2830
+ write as is. The filename attr should not be touched.
2831
+
2832
+
2833
+ case 3.
2834
+ descriptor.filename == None
2835
+ descriptor.path == "~/absolute/path/there"
2836
+
2837
+ -- action:
2838
+ calculate the relative path for filename.
2839
+ We're not overwriting some other value for filename, it should be fine
2840
+
2841
+
2842
+ case 4.
2843
+ descriptor.filename == '../somewhere'
2844
+ descriptor.path == "~/absolute/path/there"
2845
+
2846
+ -- action:
2847
+ there is a conflict between the given filename, and the path.
2848
+ So we know where the file is relative to the document.
2849
+ Can't guess why they're different, we just choose for path to be correct and update filename.
2850
+ """
2851
+ assert self.path is not None
2852
+ for descriptor in self.sources + self.instances:
2853
+ if descriptor.path is not None:
2854
+ # case 3 and 4: filename gets updated and relativized
2855
+ descriptor.filename = self._posixRelativePath(descriptor.path)
2856
+
2857
+ def addSource(self, sourceDescriptor: SourceDescriptor):
2858
+ """Add the given ``sourceDescriptor`` to ``doc.sources``."""
2859
+ self.sources.append(sourceDescriptor)
2860
+
2861
+ def addSourceDescriptor(self, **kwargs):
2862
+ """Instantiate a new :class:`SourceDescriptor` using the given
2863
+ ``kwargs`` and add it to ``doc.sources``.
2864
+ """
2865
+ source = self.writerClass.sourceDescriptorClass(**kwargs)
2866
+ self.addSource(source)
2867
+ return source
2868
+
2869
+ def addInstance(self, instanceDescriptor: InstanceDescriptor):
2870
+ """Add the given ``instanceDescriptor`` to :attr:`instances`."""
2871
+ self.instances.append(instanceDescriptor)
2872
+
2873
+ def addInstanceDescriptor(self, **kwargs):
2874
+ """Instantiate a new :class:`InstanceDescriptor` using the given
2875
+ ``kwargs`` and add it to :attr:`instances`.
2876
+ """
2877
+ instance = self.writerClass.instanceDescriptorClass(**kwargs)
2878
+ self.addInstance(instance)
2879
+ return instance
2880
+
2881
+ def addAxis(self, axisDescriptor: Union[AxisDescriptor, DiscreteAxisDescriptor]):
2882
+ """Add the given ``axisDescriptor`` to :attr:`axes`."""
2883
+ self.axes.append(axisDescriptor)
2884
+
2885
+ def addAxisDescriptor(self, **kwargs):
2886
+ """Instantiate a new :class:`AxisDescriptor` using the given
2887
+ ``kwargs`` and add it to :attr:`axes`.
2888
+
2889
+ The axis will be and instance of :class:`DiscreteAxisDescriptor` if
2890
+ the ``kwargs`` provide a ``value``, or a :class:`AxisDescriptor` otherwise.
2891
+ """
2892
+ if "values" in kwargs:
2893
+ axis = self.writerClass.discreteAxisDescriptorClass(**kwargs)
2894
+ else:
2895
+ axis = self.writerClass.axisDescriptorClass(**kwargs)
2896
+ self.addAxis(axis)
2897
+ return axis
2898
+
2899
+ def addAxisMapping(self, axisMappingDescriptor: AxisMappingDescriptor):
2900
+ """Add the given ``axisMappingDescriptor`` to :attr:`axisMappings`."""
2901
+ self.axisMappings.append(axisMappingDescriptor)
2902
+
2903
+ def addAxisMappingDescriptor(self, **kwargs):
2904
+ """Instantiate a new :class:`AxisMappingDescriptor` using the given
2905
+ ``kwargs`` and add it to :attr:`rules`.
2906
+ """
2907
+ axisMapping = self.writerClass.axisMappingDescriptorClass(**kwargs)
2908
+ self.addAxisMapping(axisMapping)
2909
+ return axisMapping
2910
+
2911
+ def addRule(self, ruleDescriptor: RuleDescriptor):
2912
+ """Add the given ``ruleDescriptor`` to :attr:`rules`."""
2913
+ self.rules.append(ruleDescriptor)
2914
+
2915
+ def addRuleDescriptor(self, **kwargs):
2916
+ """Instantiate a new :class:`RuleDescriptor` using the given
2917
+ ``kwargs`` and add it to :attr:`rules`.
2918
+ """
2919
+ rule = self.writerClass.ruleDescriptorClass(**kwargs)
2920
+ self.addRule(rule)
2921
+ return rule
2922
+
2923
+ def addVariableFont(self, variableFontDescriptor: VariableFontDescriptor):
2924
+ """Add the given ``variableFontDescriptor`` to :attr:`variableFonts`.
2925
+
2926
+ .. versionadded:: 5.0
2927
+ """
2928
+ self.variableFonts.append(variableFontDescriptor)
2929
+
2930
+ def addVariableFontDescriptor(self, **kwargs):
2931
+ """Instantiate a new :class:`VariableFontDescriptor` using the given
2932
+ ``kwargs`` and add it to :attr:`variableFonts`.
2933
+
2934
+ .. versionadded:: 5.0
2935
+ """
2936
+ variableFont = self.writerClass.variableFontDescriptorClass(**kwargs)
2937
+ self.addVariableFont(variableFont)
2938
+ return variableFont
2939
+
2940
+ def addLocationLabel(self, locationLabelDescriptor: LocationLabelDescriptor):
2941
+ """Add the given ``locationLabelDescriptor`` to :attr:`locationLabels`.
2942
+
2943
+ .. versionadded:: 5.0
2944
+ """
2945
+ self.locationLabels.append(locationLabelDescriptor)
2946
+
2947
+ def addLocationLabelDescriptor(self, **kwargs):
2948
+ """Instantiate a new :class:`LocationLabelDescriptor` using the given
2949
+ ``kwargs`` and add it to :attr:`locationLabels`.
2950
+
2951
+ .. versionadded:: 5.0
2952
+ """
2953
+ locationLabel = self.writerClass.locationLabelDescriptorClass(**kwargs)
2954
+ self.addLocationLabel(locationLabel)
2955
+ return locationLabel
2956
+
2957
+ def newDefaultLocation(self):
2958
+ """Return a dict with the default location in design space coordinates."""
2959
+ # Without OrderedDict, output XML would be non-deterministic.
2960
+ # https://github.com/LettError/designSpaceDocument/issues/10
2961
+ loc = collections.OrderedDict()
2962
+ for axisDescriptor in self.axes:
2963
+ loc[axisDescriptor.name] = axisDescriptor.map_forward(
2964
+ axisDescriptor.default
2965
+ )
2966
+ return loc
2967
+
2968
+ def labelForUserLocation(
2969
+ self, userLocation: SimpleLocationDict
2970
+ ) -> Optional[LocationLabelDescriptor]:
2971
+ """Return the :class:`LocationLabel` that matches the given
2972
+ ``userLocation``, or ``None`` if no such label exists.
2973
+
2974
+ .. versionadded:: 5.0
2975
+ """
2976
+ return next(
2977
+ (
2978
+ label
2979
+ for label in self.locationLabels
2980
+ if label.userLocation == userLocation
2981
+ ),
2982
+ None,
2983
+ )
2984
+
2985
+ def updateFilenameFromPath(self, masters=True, instances=True, force=False):
2986
+ """Set a descriptor filename attr from the path and this document path.
2987
+
2988
+ If the filename attribute is not None: skip it.
2989
+ """
2990
+ if masters:
2991
+ for descriptor in self.sources:
2992
+ if descriptor.filename is not None and not force:
2993
+ continue
2994
+ if self.path is not None:
2995
+ descriptor.filename = self._posixRelativePath(descriptor.path)
2996
+ if instances:
2997
+ for descriptor in self.instances:
2998
+ if descriptor.filename is not None and not force:
2999
+ continue
3000
+ if self.path is not None:
3001
+ descriptor.filename = self._posixRelativePath(descriptor.path)
3002
+
3003
+ def newAxisDescriptor(self):
3004
+ """Ask the writer class to make us a new axisDescriptor."""
3005
+ return self.writerClass.getAxisDecriptor()
3006
+
3007
+ def newSourceDescriptor(self):
3008
+ """Ask the writer class to make us a new sourceDescriptor."""
3009
+ return self.writerClass.getSourceDescriptor()
3010
+
3011
+ def newInstanceDescriptor(self):
3012
+ """Ask the writer class to make us a new instanceDescriptor."""
3013
+ return self.writerClass.getInstanceDescriptor()
3014
+
3015
+ def getAxisOrder(self):
3016
+ """Return a list of axis names, in the same order as defined in the document."""
3017
+ names = []
3018
+ for axisDescriptor in self.axes:
3019
+ names.append(axisDescriptor.name)
3020
+ return names
3021
+
3022
+ def getAxis(self, name: str) -> AxisDescriptor | DiscreteAxisDescriptor | None:
3023
+ """Return the axis with the given ``name``, or ``None`` if no such axis exists."""
3024
+ return next((axis for axis in self.axes if axis.name == name), None)
3025
+
3026
+ def getAxisByTag(self, tag: str) -> AxisDescriptor | DiscreteAxisDescriptor | None:
3027
+ """Return the axis with the given ``tag``, or ``None`` if no such axis exists."""
3028
+ return next((axis for axis in self.axes if axis.tag == tag), None)
3029
+
3030
+ def getLocationLabel(self, name: str) -> Optional[LocationLabelDescriptor]:
3031
+ """Return the top-level location label with the given ``name``, or
3032
+ ``None`` if no such label exists.
3033
+
3034
+ .. versionadded:: 5.0
3035
+ """
3036
+ for label in self.locationLabels:
3037
+ if label.name == name:
3038
+ return label
3039
+ return None
3040
+
3041
+ def map_forward(self, userLocation: SimpleLocationDict) -> SimpleLocationDict:
3042
+ """Map a user location to a design location.
3043
+
3044
+ Assume that missing coordinates are at the default location for that axis.
3045
+
3046
+ Note: the output won't be anisotropic, only the xvalue is set.
3047
+
3048
+ .. versionadded:: 5.0
3049
+ """
3050
+ return {
3051
+ axis.name: axis.map_forward(userLocation.get(axis.name, axis.default))
3052
+ for axis in self.axes
3053
+ }
3054
+
3055
+ def map_backward(
3056
+ self, designLocation: AnisotropicLocationDict
3057
+ ) -> SimpleLocationDict:
3058
+ """Map a design location to a user location.
3059
+
3060
+ Assume that missing coordinates are at the default location for that axis.
3061
+
3062
+ When the input has anisotropic locations, only the xvalue is used.
3063
+
3064
+ .. versionadded:: 5.0
3065
+ """
3066
+ return {
3067
+ axis.name: (
3068
+ axis.map_backward(designLocation[axis.name])
3069
+ if axis.name in designLocation
3070
+ else axis.default
3071
+ )
3072
+ for axis in self.axes
3073
+ }
3074
+
3075
+ def findDefault(self):
3076
+ """Set and return SourceDescriptor at the default location or None.
3077
+
3078
+ The default location is the set of all `default` values in user space
3079
+ of all axes.
3080
+
3081
+ This function updates the document's :attr:`default` value.
3082
+
3083
+ .. versionchanged:: 5.0
3084
+ Allow the default source to not specify some of the axis values, and
3085
+ they are assumed to be the default.
3086
+ See :meth:`SourceDescriptor.getFullDesignLocation()`
3087
+ """
3088
+ self.default = None
3089
+
3090
+ # Convert the default location from user space to design space before comparing
3091
+ # it against the SourceDescriptor locations (always in design space).
3092
+ defaultDesignLocation = self.newDefaultLocation()
3093
+
3094
+ for sourceDescriptor in self.sources:
3095
+ if sourceDescriptor.getFullDesignLocation(self) == defaultDesignLocation:
3096
+ self.default = sourceDescriptor
3097
+ return sourceDescriptor
3098
+
3099
+ return None
3100
+
3101
+ def normalizeLocation(self, location):
3102
+ """Return a dict with normalized axis values."""
3103
+ from fontTools.varLib.models import normalizeValue
3104
+
3105
+ new = {}
3106
+ for axis in self.axes:
3107
+ if axis.name not in location:
3108
+ # skipping this dimension it seems
3109
+ continue
3110
+ value = location[axis.name]
3111
+ # 'anisotropic' location, take first coord only
3112
+ if isinstance(value, tuple):
3113
+ value = value[0]
3114
+ triple = [
3115
+ axis.map_forward(v) for v in (axis.minimum, axis.default, axis.maximum)
3116
+ ]
3117
+ new[axis.name] = normalizeValue(value, triple)
3118
+ return new
3119
+
3120
+ def normalize(self):
3121
+ """
3122
+ Normalise the geometry of this designspace:
3123
+
3124
+ - scale all the locations of all masters and instances to the -1 - 0 - 1 value.
3125
+ - we need the axis data to do the scaling, so we do those last.
3126
+ """
3127
+ # masters
3128
+ for item in self.sources:
3129
+ item.location = self.normalizeLocation(item.location)
3130
+ # instances
3131
+ for item in self.instances:
3132
+ # glyph masters for this instance
3133
+ for _, glyphData in item.glyphs.items():
3134
+ glyphData["instanceLocation"] = self.normalizeLocation(
3135
+ glyphData["instanceLocation"]
3136
+ )
3137
+ for glyphMaster in glyphData["masters"]:
3138
+ glyphMaster["location"] = self.normalizeLocation(
3139
+ glyphMaster["location"]
3140
+ )
3141
+ item.location = self.normalizeLocation(item.location)
3142
+ # the axes
3143
+ for axis in self.axes:
3144
+ # scale the map first
3145
+ newMap = []
3146
+ for inputValue, outputValue in axis.map:
3147
+ newOutputValue = self.normalizeLocation({axis.name: outputValue}).get(
3148
+ axis.name
3149
+ )
3150
+ newMap.append((inputValue, newOutputValue))
3151
+ if newMap:
3152
+ axis.map = newMap
3153
+ # finally the axis values
3154
+ minimum = self.normalizeLocation({axis.name: axis.minimum}).get(axis.name)
3155
+ maximum = self.normalizeLocation({axis.name: axis.maximum}).get(axis.name)
3156
+ default = self.normalizeLocation({axis.name: axis.default}).get(axis.name)
3157
+ # and set them in the axis.minimum
3158
+ axis.minimum = minimum
3159
+ axis.maximum = maximum
3160
+ axis.default = default
3161
+ # now the rules
3162
+ for rule in self.rules:
3163
+ newConditionSets = []
3164
+ for conditions in rule.conditionSets:
3165
+ newConditions = []
3166
+ for cond in conditions:
3167
+ if cond.get("minimum") is not None:
3168
+ minimum = self.normalizeLocation(
3169
+ {cond["name"]: cond["minimum"]}
3170
+ ).get(cond["name"])
3171
+ else:
3172
+ minimum = None
3173
+ if cond.get("maximum") is not None:
3174
+ maximum = self.normalizeLocation(
3175
+ {cond["name"]: cond["maximum"]}
3176
+ ).get(cond["name"])
3177
+ else:
3178
+ maximum = None
3179
+ newConditions.append(
3180
+ dict(name=cond["name"], minimum=minimum, maximum=maximum)
3181
+ )
3182
+ newConditionSets.append(newConditions)
3183
+ rule.conditionSets = newConditionSets
3184
+
3185
+ def loadSourceFonts(self, opener, **kwargs):
3186
+ """Ensure SourceDescriptor.font attributes are loaded, and return list of fonts.
3187
+
3188
+ Takes a callable which initializes a new font object (e.g. TTFont, or
3189
+ defcon.Font, etc.) from the SourceDescriptor.path, and sets the
3190
+ SourceDescriptor.font attribute.
3191
+ If the font attribute is already not None, it is not loaded again.
3192
+ Fonts with the same path are only loaded once and shared among SourceDescriptors.
3193
+
3194
+ For example, to load UFO sources using defcon:
3195
+
3196
+ designspace = DesignSpaceDocument.fromfile("path/to/my.designspace")
3197
+ designspace.loadSourceFonts(defcon.Font)
3198
+
3199
+ Or to load masters as FontTools binary fonts, including extra options:
3200
+
3201
+ designspace.loadSourceFonts(ttLib.TTFont, recalcBBoxes=False)
3202
+
3203
+ Args:
3204
+ opener (Callable): takes one required positional argument, the source.path,
3205
+ and an optional list of keyword arguments, and returns a new font object
3206
+ loaded from the path.
3207
+ **kwargs: extra options passed on to the opener function.
3208
+
3209
+ Returns:
3210
+ List of font objects in the order they appear in the sources list.
3211
+ """
3212
+ # we load fonts with the same source.path only once
3213
+ loaded = {}
3214
+ fonts = []
3215
+ for source in self.sources:
3216
+ if source.font is not None: # font already loaded
3217
+ fonts.append(source.font)
3218
+ continue
3219
+ if source.path in loaded:
3220
+ source.font = loaded[source.path]
3221
+ else:
3222
+ if source.path is None:
3223
+ raise DesignSpaceDocumentError(
3224
+ "Designspace source '%s' has no 'path' attribute"
3225
+ % (source.name or "<Unknown>")
3226
+ )
3227
+ source.font = opener(source.path, **kwargs)
3228
+ loaded[source.path] = source.font
3229
+ fonts.append(source.font)
3230
+ return fonts
3231
+
3232
+ @property
3233
+ def formatTuple(self):
3234
+ """Return the formatVersion as a tuple of (major, minor).
3235
+
3236
+ .. versionadded:: 5.0
3237
+ """
3238
+ if self.formatVersion is None:
3239
+ return (5, 0)
3240
+ numbers = (int(i) for i in self.formatVersion.split("."))
3241
+ major = next(numbers)
3242
+ minor = next(numbers, 0)
3243
+ return (major, minor)
3244
+
3245
+ def getVariableFonts(self) -> List[VariableFontDescriptor]:
3246
+ """Return all variable fonts defined in this document, or implicit
3247
+ variable fonts that can be built from the document's continuous axes.
3248
+
3249
+ In the case of Designspace documents before version 5, the whole
3250
+ document was implicitly describing a variable font that covers the
3251
+ whole space.
3252
+
3253
+ In version 5 and above documents, there can be as many variable fonts
3254
+ as there are locations on discrete axes.
3255
+
3256
+ .. seealso:: :func:`splitInterpolable`
3257
+
3258
+ .. versionadded:: 5.0
3259
+ """
3260
+ if self.variableFonts:
3261
+ return self.variableFonts
3262
+
3263
+ variableFonts = []
3264
+ discreteAxes = []
3265
+ rangeAxisSubsets: List[
3266
+ Union[RangeAxisSubsetDescriptor, ValueAxisSubsetDescriptor]
3267
+ ] = []
3268
+ for axis in self.axes:
3269
+ if hasattr(axis, "values"):
3270
+ # Mypy doesn't support narrowing union types via hasattr()
3271
+ # TODO(Python 3.10): use TypeGuard
3272
+ # https://mypy.readthedocs.io/en/stable/type_narrowing.html
3273
+ axis = cast(DiscreteAxisDescriptor, axis)
3274
+ discreteAxes.append(axis) # type: ignore
3275
+ else:
3276
+ rangeAxisSubsets.append(RangeAxisSubsetDescriptor(name=axis.name))
3277
+ valueCombinations = itertools.product(*[axis.values for axis in discreteAxes])
3278
+ for values in valueCombinations:
3279
+ basename = None
3280
+ if self.filename is not None:
3281
+ basename = os.path.splitext(self.filename)[0] + "-VF"
3282
+ if self.path is not None:
3283
+ basename = os.path.splitext(os.path.basename(self.path))[0] + "-VF"
3284
+ if basename is None:
3285
+ basename = "VF"
3286
+ axisNames = "".join(
3287
+ [f"-{axis.tag}{value}" for axis, value in zip(discreteAxes, values)]
3288
+ )
3289
+ variableFonts.append(
3290
+ VariableFontDescriptor(
3291
+ name=f"{basename}{axisNames}",
3292
+ axisSubsets=rangeAxisSubsets
3293
+ + [
3294
+ ValueAxisSubsetDescriptor(name=axis.name, userValue=value)
3295
+ for axis, value in zip(discreteAxes, values)
3296
+ ],
3297
+ )
3298
+ )
3299
+ return variableFonts
3300
+
3301
+ def deepcopyExceptFonts(self):
3302
+ """Allow deep-copying a DesignSpace document without deep-copying
3303
+ attached UFO fonts or TTFont objects. The :attr:`font` attribute
3304
+ is shared by reference between the original and the copy.
3305
+
3306
+ .. versionadded:: 5.0
3307
+ """
3308
+ fonts = [source.font for source in self.sources]
3309
+ try:
3310
+ for source in self.sources:
3311
+ source.font = None
3312
+ res = copy.deepcopy(self)
3313
+ for source, font in zip(res.sources, fonts):
3314
+ source.font = font
3315
+ return res
3316
+ finally:
3317
+ for source, font in zip(self.sources, fonts):
3318
+ source.font = font
3319
+
3320
+
3321
+ def main(args=None):
3322
+ """Roundtrip .designspace file through the DesignSpaceDocument class"""
3323
+
3324
+ if args is None:
3325
+ import sys
3326
+
3327
+ args = sys.argv[1:]
3328
+
3329
+ from argparse import ArgumentParser
3330
+
3331
+ parser = ArgumentParser(prog="designspaceLib", description=main.__doc__)
3332
+ parser.add_argument("input")
3333
+ parser.add_argument("output")
3334
+
3335
+ options = parser.parse_args(args)
3336
+
3337
+ ds = DesignSpaceDocument.fromfile(options.input)
3338
+ ds.write(options.output)