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,2472 @@
1
+ """
2
+ A library for importing .ufo files and their descendants.
3
+ Refer to http://unifiedfontobject.org for the UFO specification.
4
+
5
+ The main interfaces are the :class:`.UFOReader` and :class:`.UFOWriter`
6
+ classes, which support versions 1, 2, and 3 of the UFO specification.
7
+
8
+ Set variables are available for external use that list the font
9
+ info attribute names for the `fontinfo.plist` formats. These are:
10
+
11
+ - :obj:`.fontInfoAttributesVersion1`
12
+ - :obj:`.fontInfoAttributesVersion2`
13
+ - :obj:`.fontInfoAttributesVersion3`
14
+
15
+ A set listing the `fontinfo.plist` attributes that were deprecated
16
+ in version 2 is available for external use:
17
+
18
+ - :obj:`.deprecatedFontInfoAttributesVersion2`
19
+
20
+ Functions that do basic validation on values for `fontinfo.plist`
21
+ are available for external use. These are
22
+
23
+ - :func:`.validateFontInfoVersion2ValueForAttribute`
24
+ - :func:`.validateFontInfoVersion3ValueForAttribute`
25
+
26
+ Value conversion functions are available for converting
27
+ `fontinfo.plist` values between the possible format versions.
28
+
29
+ - :func:`.convertFontInfoValueForAttributeFromVersion1ToVersion2`
30
+ - :func:`.convertFontInfoValueForAttributeFromVersion2ToVersion1`
31
+ - :func:`.convertFontInfoValueForAttributeFromVersion2ToVersion3`
32
+ - :func:`.convertFontInfoValueForAttributeFromVersion3ToVersion2`
33
+ """
34
+
35
+ import enum
36
+ import logging
37
+ import os
38
+ import zipfile
39
+ from collections import OrderedDict
40
+ from copy import deepcopy
41
+ from os import fsdecode
42
+
43
+ from fontTools.misc import filesystem as fs
44
+ from fontTools.misc import plistlib
45
+ from fontTools.ufoLib.converters import convertUFO1OrUFO2KerningToUFO3Kerning
46
+ from fontTools.ufoLib.errors import UFOLibError
47
+ from fontTools.ufoLib.filenames import userNameToFileName
48
+ from fontTools.ufoLib.utils import _VersionTupleEnumMixin, numberTypes
49
+ from fontTools.ufoLib.validators import *
50
+
51
+ # client code can check this to see if the upstream `fs` package is being used
52
+ haveFS = fs._haveFS
53
+
54
+ __all__ = [
55
+ "haveFS",
56
+ "makeUFOPath",
57
+ "UFOLibError",
58
+ "UFOReader",
59
+ "UFOWriter",
60
+ "UFOReaderWriter",
61
+ "UFOFileStructure",
62
+ "fontInfoAttributesVersion1",
63
+ "fontInfoAttributesVersion2",
64
+ "fontInfoAttributesVersion3",
65
+ "deprecatedFontInfoAttributesVersion2",
66
+ "validateFontInfoVersion2ValueForAttribute",
67
+ "validateFontInfoVersion3ValueForAttribute",
68
+ "convertFontInfoValueForAttributeFromVersion1ToVersion2",
69
+ "convertFontInfoValueForAttributeFromVersion2ToVersion1",
70
+ ]
71
+
72
+ __version__ = "3.0.0"
73
+
74
+
75
+ logger = logging.getLogger(__name__)
76
+
77
+
78
+ # ---------
79
+ # Constants
80
+ # ---------
81
+
82
+ DEFAULT_GLYPHS_DIRNAME = "glyphs"
83
+ DATA_DIRNAME = "data"
84
+ IMAGES_DIRNAME = "images"
85
+ METAINFO_FILENAME = "metainfo.plist"
86
+ FONTINFO_FILENAME = "fontinfo.plist"
87
+ LIB_FILENAME = "lib.plist"
88
+ GROUPS_FILENAME = "groups.plist"
89
+ KERNING_FILENAME = "kerning.plist"
90
+ FEATURES_FILENAME = "features.fea"
91
+ LAYERCONTENTS_FILENAME = "layercontents.plist"
92
+ LAYERINFO_FILENAME = "layerinfo.plist"
93
+
94
+ DEFAULT_LAYER_NAME = "public.default"
95
+
96
+
97
+ class UFOFormatVersion(tuple, _VersionTupleEnumMixin, enum.Enum):
98
+ FORMAT_1_0 = (1, 0)
99
+ FORMAT_2_0 = (2, 0)
100
+ FORMAT_3_0 = (3, 0)
101
+
102
+
103
+ # python 3.11 doesn't like when a mixin overrides a dunder method like __str__
104
+ # for some reasons it keep using Enum.__str__, see
105
+ # https://github.com/fonttools/fonttools/pull/2655
106
+ UFOFormatVersion.__str__ = _VersionTupleEnumMixin.__str__
107
+
108
+
109
+ class UFOFileStructure(enum.Enum):
110
+ ZIP = "zip"
111
+ PACKAGE = "package"
112
+
113
+
114
+ # --------------
115
+ # Shared Methods
116
+ # --------------
117
+
118
+
119
+ class _UFOBaseIO:
120
+ def getFileModificationTime(self, path):
121
+ """
122
+ Returns the modification time for the file at the given path, as a
123
+ floating point number giving the number of seconds since the epoch.
124
+ The path must be relative to the UFO path.
125
+ Returns None if the file does not exist.
126
+ """
127
+ try:
128
+ dt = self.fs.getinfo(fsdecode(path), namespaces=["details"]).modified
129
+ except (fs.errors.MissingInfoNamespace, fs.errors.ResourceNotFound):
130
+ return None
131
+ else:
132
+ return dt.timestamp()
133
+
134
+ def _getPlist(self, fileName, default=None):
135
+ """
136
+ Read a property list relative to the UFO filesystem's root.
137
+ Raises UFOLibError if the file is missing and default is None,
138
+ otherwise default is returned.
139
+
140
+ The errors that could be raised during the reading of a plist are
141
+ unpredictable and/or too large to list, so, a blind try: except:
142
+ is done. If an exception occurs, a UFOLibError will be raised.
143
+ """
144
+ try:
145
+ with self.fs.open(fileName, "rb") as f:
146
+ return plistlib.load(f)
147
+ except fs.errors.ResourceNotFound:
148
+ if default is None:
149
+ raise UFOLibError(
150
+ "'%s' is missing on %s. This file is required" % (fileName, self.fs)
151
+ )
152
+ else:
153
+ return default
154
+ except Exception as e:
155
+ # TODO(anthrotype): try to narrow this down a little
156
+ raise UFOLibError(f"'{fileName}' could not be read on {self.fs}: {e}")
157
+
158
+ def _writePlist(self, fileName, obj):
159
+ """
160
+ Write a property list to a file relative to the UFO filesystem's root.
161
+
162
+ Do this sort of atomically, making it harder to corrupt existing files,
163
+ for example when plistlib encounters an error halfway during write.
164
+ This also checks to see if text matches the text that is already in the
165
+ file at path. If so, the file is not rewritten so that the modification
166
+ date is preserved.
167
+
168
+ The errors that could be raised during the writing of a plist are
169
+ unpredictable and/or too large to list, so, a blind try: except: is done.
170
+ If an exception occurs, a UFOLibError will be raised.
171
+ """
172
+ if self._havePreviousFile:
173
+ try:
174
+ data = plistlib.dumps(obj)
175
+ except Exception as e:
176
+ raise UFOLibError(
177
+ "'%s' could not be written on %s because "
178
+ "the data is not properly formatted: %s" % (fileName, self.fs, e)
179
+ )
180
+ if self.fs.exists(fileName) and data == self.fs.readbytes(fileName):
181
+ return
182
+ self.fs.writebytes(fileName, data)
183
+ else:
184
+ with self.fs.open(fileName, mode="wb") as fp:
185
+ try:
186
+ plistlib.dump(obj, fp)
187
+ except Exception as e:
188
+ raise UFOLibError(
189
+ "'%s' could not be written on %s because "
190
+ "the data is not properly formatted: %s"
191
+ % (fileName, self.fs, e)
192
+ )
193
+
194
+
195
+ # ----------
196
+ # UFO Reader
197
+ # ----------
198
+
199
+
200
+ class UFOReader(_UFOBaseIO):
201
+ """Read the various components of a .ufo.
202
+
203
+ Attributes:
204
+ path: An :class:`os.PathLike` object pointing to the .ufo.
205
+ validate: A boolean indicating if the data read should be
206
+ validated. Defaults to `True`.
207
+
208
+ By default read data is validated. Set ``validate`` to
209
+ ``False`` to not validate the data.
210
+ """
211
+
212
+ def __init__(self, path, validate=True):
213
+ if hasattr(path, "__fspath__"): # support os.PathLike objects
214
+ path = path.__fspath__()
215
+
216
+ if isinstance(path, str):
217
+ structure = _sniffFileStructure(path)
218
+ try:
219
+ if structure is UFOFileStructure.ZIP:
220
+ parentFS = fs.zipfs.ZipFS(path, write=False, encoding="utf-8")
221
+ else:
222
+ parentFS = fs.osfs.OSFS(path)
223
+ except fs.errors.CreateFailed as e:
224
+ raise UFOLibError(f"unable to open '{path}': {e}")
225
+
226
+ if structure is UFOFileStructure.ZIP:
227
+ # .ufoz zip files must contain a single root directory, with arbitrary
228
+ # name, containing all the UFO files
229
+ rootDirs = [
230
+ p.name
231
+ for p in parentFS.scandir("/")
232
+ # exclude macOS metadata contained in zip file
233
+ if p.is_dir and p.name != "__MACOSX"
234
+ ]
235
+ if len(rootDirs) == 1:
236
+ # 'ClosingSubFS' ensures that the parent zip file is closed when
237
+ # its root subdirectory is closed
238
+ self.fs = parentFS.opendir(
239
+ rootDirs[0], factory=fs.subfs.ClosingSubFS
240
+ )
241
+ else:
242
+ raise UFOLibError(
243
+ "Expected exactly 1 root directory, found %d" % len(rootDirs)
244
+ )
245
+ else:
246
+ # normal UFO 'packages' are just a single folder
247
+ self.fs = parentFS
248
+ # when passed a path string, we make sure we close the newly opened fs
249
+ # upon calling UFOReader.close method or context manager's __exit__
250
+ self._shouldClose = True
251
+ self._fileStructure = structure
252
+ elif isinstance(path, fs.base.FS):
253
+ filesystem = path
254
+ try:
255
+ filesystem.check()
256
+ except fs.errors.FilesystemClosed:
257
+ raise UFOLibError("the filesystem '%s' is closed" % path)
258
+ else:
259
+ self.fs = filesystem
260
+ try:
261
+ path = filesystem.getsyspath("/")
262
+ except fs.errors.NoSysPath:
263
+ # network or in-memory FS may not map to the local one
264
+ path = str(filesystem)
265
+ # when user passed an already initialized fs instance, it is her
266
+ # responsibility to close it, thus UFOReader.close/__exit__ are no-op
267
+ self._shouldClose = False
268
+ # default to a 'package' structure
269
+ self._fileStructure = UFOFileStructure.PACKAGE
270
+ else:
271
+ raise TypeError(
272
+ "Expected a path string or fs.base.FS object, found '%s'"
273
+ % type(path).__name__
274
+ )
275
+ self._path = fsdecode(path)
276
+ self._validate = validate
277
+ self._upConvertedKerningData = None
278
+
279
+ try:
280
+ self.readMetaInfo(validate=validate)
281
+ except UFOLibError:
282
+ self.close()
283
+ raise
284
+
285
+ # properties
286
+
287
+ def _get_path(self):
288
+ import warnings
289
+
290
+ warnings.warn(
291
+ "The 'path' attribute is deprecated; use the 'fs' attribute instead",
292
+ DeprecationWarning,
293
+ stacklevel=2,
294
+ )
295
+ return self._path
296
+
297
+ path = property(_get_path, doc="The path of the UFO (DEPRECATED).")
298
+
299
+ def _get_formatVersion(self):
300
+ import warnings
301
+
302
+ warnings.warn(
303
+ "The 'formatVersion' attribute is deprecated; use the 'formatVersionTuple'",
304
+ DeprecationWarning,
305
+ stacklevel=2,
306
+ )
307
+ return self._formatVersion.major
308
+
309
+ formatVersion = property(
310
+ _get_formatVersion,
311
+ doc="The (major) format version of the UFO. DEPRECATED: Use formatVersionTuple",
312
+ )
313
+
314
+ @property
315
+ def formatVersionTuple(self):
316
+ """The (major, minor) format version of the UFO.
317
+ This is determined by reading metainfo.plist during __init__.
318
+ """
319
+ return self._formatVersion
320
+
321
+ def _get_fileStructure(self):
322
+ return self._fileStructure
323
+
324
+ fileStructure = property(
325
+ _get_fileStructure,
326
+ doc=(
327
+ "The file structure of the UFO: "
328
+ "either UFOFileStructure.ZIP or UFOFileStructure.PACKAGE"
329
+ ),
330
+ )
331
+
332
+ # up conversion
333
+
334
+ def _upConvertKerning(self, validate):
335
+ """
336
+ Up convert kerning and groups in UFO 1 and 2.
337
+ The data will be held internally until each bit of data
338
+ has been retrieved. The conversion of both must be done
339
+ at once, so the raw data is cached and an error is raised
340
+ if one bit of data becomes obsolete before it is called.
341
+
342
+ ``validate`` will validate the data.
343
+ """
344
+ if self._upConvertedKerningData:
345
+ testKerning = self._readKerning()
346
+ if testKerning != self._upConvertedKerningData["originalKerning"]:
347
+ raise UFOLibError(
348
+ "The data in kerning.plist has been modified since it was converted to UFO 3 format."
349
+ )
350
+ testGroups = self._readGroups()
351
+ if testGroups != self._upConvertedKerningData["originalGroups"]:
352
+ raise UFOLibError(
353
+ "The data in groups.plist has been modified since it was converted to UFO 3 format."
354
+ )
355
+ else:
356
+ groups = self._readGroups()
357
+ if validate:
358
+ invalidFormatMessage = "groups.plist is not properly formatted."
359
+ if not isinstance(groups, dict):
360
+ raise UFOLibError(invalidFormatMessage)
361
+ for groupName, glyphList in groups.items():
362
+ if not isinstance(groupName, str):
363
+ raise UFOLibError(invalidFormatMessage)
364
+ elif not isinstance(glyphList, list):
365
+ raise UFOLibError(invalidFormatMessage)
366
+ for glyphName in glyphList:
367
+ if not isinstance(glyphName, str):
368
+ raise UFOLibError(invalidFormatMessage)
369
+ self._upConvertedKerningData = dict(
370
+ kerning={},
371
+ originalKerning=self._readKerning(),
372
+ groups={},
373
+ originalGroups=groups,
374
+ )
375
+ # convert kerning and groups
376
+ kerning, groups, conversionMaps = convertUFO1OrUFO2KerningToUFO3Kerning(
377
+ self._upConvertedKerningData["originalKerning"],
378
+ deepcopy(self._upConvertedKerningData["originalGroups"]),
379
+ self.getGlyphSet(),
380
+ )
381
+ # store
382
+ self._upConvertedKerningData["kerning"] = kerning
383
+ self._upConvertedKerningData["groups"] = groups
384
+ self._upConvertedKerningData["groupRenameMaps"] = conversionMaps
385
+
386
+ # support methods
387
+
388
+ def readBytesFromPath(self, path):
389
+ """
390
+ Returns the bytes in the file at the given path.
391
+ The path must be relative to the UFO's filesystem root.
392
+ Returns None if the file does not exist.
393
+ """
394
+ try:
395
+ return self.fs.readbytes(fsdecode(path))
396
+ except fs.errors.ResourceNotFound:
397
+ return None
398
+
399
+ def getReadFileForPath(self, path, encoding=None):
400
+ """
401
+ Returns a file (or file-like) object for the file at the given path.
402
+ The path must be relative to the UFO path.
403
+ Returns None if the file does not exist.
404
+ By default the file is opened in binary mode (reads bytes).
405
+ If encoding is passed, the file is opened in text mode (reads str).
406
+
407
+ Note: The caller is responsible for closing the open file.
408
+ """
409
+ path = fsdecode(path)
410
+ try:
411
+ if encoding is None:
412
+ return self.fs.open(path, mode="rb")
413
+ else:
414
+ return self.fs.open(path, mode="r", encoding=encoding)
415
+ except fs.errors.ResourceNotFound:
416
+ return None
417
+
418
+ # metainfo.plist
419
+
420
+ def _readMetaInfo(self, validate=None):
421
+ """
422
+ Read metainfo.plist and return raw data. Only used for internal operations.
423
+
424
+ ``validate`` will validate the read data, by default it is set
425
+ to the class's validate value, can be overridden.
426
+ """
427
+ if validate is None:
428
+ validate = self._validate
429
+ data = self._getPlist(METAINFO_FILENAME)
430
+ if validate and not isinstance(data, dict):
431
+ raise UFOLibError("metainfo.plist is not properly formatted.")
432
+ try:
433
+ formatVersionMajor = data["formatVersion"]
434
+ except KeyError:
435
+ raise UFOLibError(
436
+ f"Missing required formatVersion in '{METAINFO_FILENAME}' on {self.fs}"
437
+ )
438
+ formatVersionMinor = data.setdefault("formatVersionMinor", 0)
439
+
440
+ try:
441
+ formatVersion = UFOFormatVersion((formatVersionMajor, formatVersionMinor))
442
+ except ValueError as e:
443
+ unsupportedMsg = (
444
+ f"Unsupported UFO format ({formatVersionMajor}.{formatVersionMinor}) "
445
+ f"in '{METAINFO_FILENAME}' on {self.fs}"
446
+ )
447
+ if validate:
448
+ from fontTools.ufoLib.errors import UnsupportedUFOFormat
449
+
450
+ raise UnsupportedUFOFormat(unsupportedMsg) from e
451
+
452
+ formatVersion = UFOFormatVersion.default()
453
+ logger.warning(
454
+ "%s. Assuming the latest supported version (%s). "
455
+ "Some data may be skipped or parsed incorrectly",
456
+ unsupportedMsg,
457
+ formatVersion,
458
+ )
459
+ data["formatVersionTuple"] = formatVersion
460
+ return data
461
+
462
+ def readMetaInfo(self, validate=None):
463
+ """
464
+ Read metainfo.plist and set formatVersion. Only used for internal operations.
465
+
466
+ ``validate`` will validate the read data, by default it is set
467
+ to the class's validate value, can be overridden.
468
+ """
469
+ data = self._readMetaInfo(validate=validate)
470
+ self._formatVersion = data["formatVersionTuple"]
471
+
472
+ # groups.plist
473
+
474
+ def _readGroups(self):
475
+ groups = self._getPlist(GROUPS_FILENAME, {})
476
+ # remove any duplicate glyphs in a kerning group
477
+ for groupName, glyphList in groups.items():
478
+ if groupName.startswith(("public.kern1.", "public.kern2.")):
479
+ groups[groupName] = list(OrderedDict.fromkeys(glyphList))
480
+ return groups
481
+
482
+ def readGroups(self, validate=None):
483
+ """
484
+ Read groups.plist. Returns a dict.
485
+ ``validate`` will validate the read data, by default it is set to the
486
+ class's validate value, can be overridden.
487
+ """
488
+ if validate is None:
489
+ validate = self._validate
490
+ # handle up conversion
491
+ if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
492
+ self._upConvertKerning(validate)
493
+ groups = self._upConvertedKerningData["groups"]
494
+ # normal
495
+ else:
496
+ groups = self._readGroups()
497
+ if validate:
498
+ valid, message = groupsValidator(groups)
499
+ if not valid:
500
+ raise UFOLibError(message)
501
+ return groups
502
+
503
+ def getKerningGroupConversionRenameMaps(self, validate=None):
504
+ """
505
+ Get maps defining the renaming that was done during any
506
+ needed kerning group conversion. This method returns a
507
+ dictionary of this form::
508
+
509
+ {
510
+ "side1" : {"old group name" : "new group name"},
511
+ "side2" : {"old group name" : "new group name"}
512
+ }
513
+
514
+ When no conversion has been performed, the side1 and side2
515
+ dictionaries will be empty.
516
+
517
+ ``validate`` will validate the groups, by default it is set to the
518
+ class's validate value, can be overridden.
519
+ """
520
+ if validate is None:
521
+ validate = self._validate
522
+ if self._formatVersion >= UFOFormatVersion.FORMAT_3_0:
523
+ return dict(side1={}, side2={})
524
+ # use the public group reader to force the load and
525
+ # conversion of the data if it hasn't happened yet.
526
+ self.readGroups(validate=validate)
527
+ return self._upConvertedKerningData["groupRenameMaps"]
528
+
529
+ # fontinfo.plist
530
+
531
+ def _readInfo(self, validate):
532
+ data = self._getPlist(FONTINFO_FILENAME, {})
533
+ if validate and not isinstance(data, dict):
534
+ raise UFOLibError("fontinfo.plist is not properly formatted.")
535
+ return data
536
+
537
+ def readInfo(self, info, validate=None):
538
+ """
539
+ Read fontinfo.plist. It requires an object that allows
540
+ setting attributes with names that follow the fontinfo.plist
541
+ version 3 specification. This will write the attributes
542
+ defined in the file into the object.
543
+
544
+ ``validate`` will validate the read data, by default it is set to the
545
+ class's validate value, can be overridden.
546
+ """
547
+ if validate is None:
548
+ validate = self._validate
549
+ infoDict = self._readInfo(validate)
550
+ infoDataToSet = {}
551
+ # version 1
552
+ if self._formatVersion == UFOFormatVersion.FORMAT_1_0:
553
+ for attr in fontInfoAttributesVersion1:
554
+ value = infoDict.get(attr)
555
+ if value is not None:
556
+ infoDataToSet[attr] = value
557
+ infoDataToSet = _convertFontInfoDataVersion1ToVersion2(infoDataToSet)
558
+ infoDataToSet = _convertFontInfoDataVersion2ToVersion3(infoDataToSet)
559
+ # version 2
560
+ elif self._formatVersion == UFOFormatVersion.FORMAT_2_0:
561
+ for attr, dataValidationDict in list(
562
+ fontInfoAttributesVersion2ValueData.items()
563
+ ):
564
+ value = infoDict.get(attr)
565
+ if value is None:
566
+ continue
567
+ infoDataToSet[attr] = value
568
+ infoDataToSet = _convertFontInfoDataVersion2ToVersion3(infoDataToSet)
569
+ # version 3.x
570
+ elif self._formatVersion.major == UFOFormatVersion.FORMAT_3_0.major:
571
+ for attr, dataValidationDict in list(
572
+ fontInfoAttributesVersion3ValueData.items()
573
+ ):
574
+ value = infoDict.get(attr)
575
+ if value is None:
576
+ continue
577
+ infoDataToSet[attr] = value
578
+ # unsupported version
579
+ else:
580
+ raise NotImplementedError(self._formatVersion)
581
+ # validate data
582
+ if validate:
583
+ infoDataToSet = validateInfoVersion3Data(infoDataToSet)
584
+ # populate the object
585
+ for attr, value in list(infoDataToSet.items()):
586
+ try:
587
+ setattr(info, attr, value)
588
+ except AttributeError:
589
+ raise UFOLibError(
590
+ "The supplied info object does not support setting a necessary attribute (%s)."
591
+ % attr
592
+ )
593
+
594
+ # kerning.plist
595
+
596
+ def _readKerning(self):
597
+ data = self._getPlist(KERNING_FILENAME, {})
598
+ return data
599
+
600
+ def readKerning(self, validate=None):
601
+ """
602
+ Read kerning.plist. Returns a dict.
603
+
604
+ ``validate`` will validate the kerning data, by default it is set to the
605
+ class's validate value, can be overridden.
606
+ """
607
+ if validate is None:
608
+ validate = self._validate
609
+ # handle up conversion
610
+ if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
611
+ self._upConvertKerning(validate)
612
+ kerningNested = self._upConvertedKerningData["kerning"]
613
+ # normal
614
+ else:
615
+ kerningNested = self._readKerning()
616
+ if validate:
617
+ valid, message = kerningValidator(kerningNested)
618
+ if not valid:
619
+ raise UFOLibError(message)
620
+ # flatten
621
+ kerning = {}
622
+ for left in kerningNested:
623
+ for right in kerningNested[left]:
624
+ value = kerningNested[left][right]
625
+ kerning[left, right] = value
626
+ return kerning
627
+
628
+ # lib.plist
629
+
630
+ def readLib(self, validate=None):
631
+ """
632
+ Read lib.plist. Returns a dict.
633
+
634
+ ``validate`` will validate the data, by default it is set to the
635
+ class's validate value, can be overridden.
636
+ """
637
+ if validate is None:
638
+ validate = self._validate
639
+ data = self._getPlist(LIB_FILENAME, {})
640
+ if validate:
641
+ valid, message = fontLibValidator(data)
642
+ if not valid:
643
+ raise UFOLibError(message)
644
+ return data
645
+
646
+ # features.fea
647
+
648
+ def readFeatures(self):
649
+ """
650
+ Read features.fea. Return a string.
651
+ The returned string is empty if the file is missing.
652
+ """
653
+ try:
654
+ with self.fs.open(FEATURES_FILENAME, "r", encoding="utf-8-sig") as f:
655
+ return f.read()
656
+ except fs.errors.ResourceNotFound:
657
+ return ""
658
+
659
+ # glyph sets & layers
660
+
661
+ def _readLayerContents(self, validate):
662
+ """
663
+ Rebuild the layer contents list by checking what glyphsets
664
+ are available on disk.
665
+
666
+ ``validate`` will validate the layer contents.
667
+ """
668
+ if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
669
+ return [(DEFAULT_LAYER_NAME, DEFAULT_GLYPHS_DIRNAME)]
670
+ contents = self._getPlist(LAYERCONTENTS_FILENAME)
671
+ if validate:
672
+ valid, error = layerContentsValidator(contents, self.fs)
673
+ if not valid:
674
+ raise UFOLibError(error)
675
+ return contents
676
+
677
+ def getLayerNames(self, validate=None):
678
+ """
679
+ Get the ordered layer names from layercontents.plist.
680
+
681
+ ``validate`` will validate the data, by default it is set to the
682
+ class's validate value, can be overridden.
683
+ """
684
+ if validate is None:
685
+ validate = self._validate
686
+ layerContents = self._readLayerContents(validate)
687
+ layerNames = [layerName for layerName, directoryName in layerContents]
688
+ return layerNames
689
+
690
+ def getDefaultLayerName(self, validate=None):
691
+ """
692
+ Get the default layer name from layercontents.plist.
693
+
694
+ ``validate`` will validate the data, by default it is set to the
695
+ class's validate value, can be overridden.
696
+ """
697
+ if validate is None:
698
+ validate = self._validate
699
+ layerContents = self._readLayerContents(validate)
700
+ for layerName, layerDirectory in layerContents:
701
+ if layerDirectory == DEFAULT_GLYPHS_DIRNAME:
702
+ return layerName
703
+ # this will already have been raised during __init__
704
+ raise UFOLibError("The default layer is not defined in layercontents.plist.")
705
+
706
+ def getGlyphSet(self, layerName=None, validateRead=None, validateWrite=None):
707
+ """
708
+ Return the GlyphSet associated with the
709
+ glyphs directory mapped to layerName
710
+ in the UFO. If layerName is not provided,
711
+ the name retrieved with getDefaultLayerName
712
+ will be used.
713
+
714
+ ``validateRead`` will validate the read data, by default it is set to the
715
+ class's validate value, can be overridden.
716
+ ``validateWrite`` will validate the written data, by default it is set to the
717
+ class's validate value, can be overridden.
718
+ """
719
+ from fontTools.ufoLib.glifLib import GlyphSet
720
+
721
+ if validateRead is None:
722
+ validateRead = self._validate
723
+ if validateWrite is None:
724
+ validateWrite = self._validate
725
+ if layerName is None:
726
+ layerName = self.getDefaultLayerName(validate=validateRead)
727
+ directory = None
728
+ layerContents = self._readLayerContents(validateRead)
729
+ for storedLayerName, storedLayerDirectory in layerContents:
730
+ if layerName == storedLayerName:
731
+ directory = storedLayerDirectory
732
+ break
733
+ if directory is None:
734
+ raise UFOLibError('No glyphs directory is mapped to "%s".' % layerName)
735
+ try:
736
+ glyphSubFS = self.fs.opendir(directory)
737
+ except fs.errors.ResourceNotFound:
738
+ raise UFOLibError(f"No '{directory}' directory for layer '{layerName}'")
739
+ return GlyphSet(
740
+ glyphSubFS,
741
+ ufoFormatVersion=self._formatVersion,
742
+ validateRead=validateRead,
743
+ validateWrite=validateWrite,
744
+ expectContentsFile=True,
745
+ )
746
+
747
+ def getCharacterMapping(self, layerName=None, validate=None):
748
+ """
749
+ Return a dictionary that maps unicode values (ints) to
750
+ lists of glyph names.
751
+ """
752
+ if validate is None:
753
+ validate = self._validate
754
+ glyphSet = self.getGlyphSet(
755
+ layerName, validateRead=validate, validateWrite=True
756
+ )
757
+ allUnicodes = glyphSet.getUnicodes()
758
+ cmap = {}
759
+ for glyphName, unicodes in allUnicodes.items():
760
+ for code in unicodes:
761
+ if code in cmap:
762
+ cmap[code].append(glyphName)
763
+ else:
764
+ cmap[code] = [glyphName]
765
+ return cmap
766
+
767
+ # /data
768
+
769
+ def getDataDirectoryListing(self):
770
+ """
771
+ Returns a list of all files in the data directory.
772
+ The returned paths will be relative to the UFO.
773
+ This will not list directory names, only file names.
774
+ Thus, empty directories will be skipped.
775
+ """
776
+ try:
777
+ self._dataFS = self.fs.opendir(DATA_DIRNAME)
778
+ except fs.errors.ResourceNotFound:
779
+ return []
780
+ except fs.errors.DirectoryExpected:
781
+ raise UFOLibError('The UFO contains a "data" file instead of a directory.')
782
+ try:
783
+ # fs Walker.files method returns "absolute" paths (in terms of the
784
+ # root of the 'data' SubFS), so we strip the leading '/' to make
785
+ # them relative
786
+ return [p.lstrip("/") for p in self._dataFS.walk.files()]
787
+ except fs.errors.ResourceError:
788
+ return []
789
+
790
+ def getImageDirectoryListing(self, validate=None):
791
+ """
792
+ Returns a list of all image file names in
793
+ the images directory. Each of the images will
794
+ have been verified to have the PNG signature.
795
+
796
+ ``validate`` will validate the data, by default it is set to the
797
+ class's validate value, can be overridden.
798
+ """
799
+ if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
800
+ return []
801
+ if validate is None:
802
+ validate = self._validate
803
+ try:
804
+ self._imagesFS = imagesFS = self.fs.opendir(IMAGES_DIRNAME)
805
+ except fs.errors.ResourceNotFound:
806
+ return []
807
+ except fs.errors.DirectoryExpected:
808
+ raise UFOLibError(
809
+ 'The UFO contains an "images" file instead of a directory.'
810
+ )
811
+ result = []
812
+ for path in imagesFS.scandir("/"):
813
+ if path.is_dir:
814
+ # silently skip this as version control
815
+ # systems often have hidden directories
816
+ continue
817
+ if validate:
818
+ with imagesFS.open(path.name, "rb") as fp:
819
+ valid, error = pngValidator(fileObj=fp)
820
+ if valid:
821
+ result.append(path.name)
822
+ else:
823
+ result.append(path.name)
824
+ return result
825
+
826
+ def readData(self, fileName):
827
+ """
828
+ Return bytes for the file named 'fileName' inside the 'data/' directory.
829
+ """
830
+ fileName = fsdecode(fileName)
831
+ try:
832
+ try:
833
+ dataFS = self._dataFS
834
+ except AttributeError:
835
+ # in case readData is called before getDataDirectoryListing
836
+ dataFS = self.fs.opendir(DATA_DIRNAME)
837
+ data = dataFS.readbytes(fileName)
838
+ except fs.errors.ResourceNotFound:
839
+ raise UFOLibError(f"No data file named '{fileName}' on {self.fs}")
840
+ return data
841
+
842
+ def readImage(self, fileName, validate=None):
843
+ """
844
+ Return image data for the file named fileName.
845
+
846
+ ``validate`` will validate the data, by default it is set to the
847
+ class's validate value, can be overridden.
848
+ """
849
+ if validate is None:
850
+ validate = self._validate
851
+ if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
852
+ raise UFOLibError(
853
+ f"Reading images is not allowed in UFO {self._formatVersion.major}."
854
+ )
855
+ fileName = fsdecode(fileName)
856
+ try:
857
+ try:
858
+ imagesFS = self._imagesFS
859
+ except AttributeError:
860
+ # in case readImage is called before getImageDirectoryListing
861
+ imagesFS = self.fs.opendir(IMAGES_DIRNAME)
862
+ data = imagesFS.readbytes(fileName)
863
+ except fs.errors.ResourceNotFound:
864
+ raise UFOLibError(f"No image file named '{fileName}' on {self.fs}")
865
+ if validate:
866
+ valid, error = pngValidator(data=data)
867
+ if not valid:
868
+ raise UFOLibError(error)
869
+ return data
870
+
871
+ def close(self):
872
+ if self._shouldClose:
873
+ self.fs.close()
874
+
875
+ def __enter__(self):
876
+ return self
877
+
878
+ def __exit__(self, exc_type, exc_value, exc_tb):
879
+ self.close()
880
+
881
+
882
+ # ----------
883
+ # UFO Writer
884
+ # ----------
885
+
886
+
887
+ class UFOWriter(UFOReader):
888
+ """Write the various components of a .ufo.
889
+
890
+ Attributes:
891
+ path: An :class:`os.PathLike` object pointing to the .ufo.
892
+ formatVersion: the UFO format version as a tuple of integers (major, minor),
893
+ or as a single integer for the major digit only (minor is implied to be 0).
894
+ By default, the latest formatVersion will be used; currently it is 3.0,
895
+ which is equivalent to formatVersion=(3, 0).
896
+ fileCreator: The creator of the .ufo file. Defaults to
897
+ `com.github.fonttools.ufoLib`.
898
+ structure: The internal structure of the .ufo file: either `ZIP` or `PACKAGE`.
899
+ validate: A boolean indicating if the data read should be validated. Defaults
900
+ to `True`.
901
+
902
+ By default, the written data will be validated before writing. Set ``validate`` to
903
+ ``False`` if you do not want to validate the data. Validation can also be overriden
904
+ on a per-method level if desired.
905
+
906
+ Raises:
907
+ UnsupportedUFOFormat: An exception indicating that the requested UFO
908
+ formatVersion is not supported.
909
+ """
910
+
911
+ def __init__(
912
+ self,
913
+ path,
914
+ formatVersion=None,
915
+ fileCreator="com.github.fonttools.ufoLib",
916
+ structure=None,
917
+ validate=True,
918
+ ):
919
+ try:
920
+ formatVersion = UFOFormatVersion(formatVersion)
921
+ except ValueError as e:
922
+ from fontTools.ufoLib.errors import UnsupportedUFOFormat
923
+
924
+ raise UnsupportedUFOFormat(
925
+ f"Unsupported UFO format: {formatVersion!r}"
926
+ ) from e
927
+
928
+ if hasattr(path, "__fspath__"): # support os.PathLike objects
929
+ path = path.__fspath__()
930
+
931
+ if isinstance(path, str):
932
+ # normalize path by removing trailing or double slashes
933
+ path = os.path.normpath(path)
934
+ havePreviousFile = os.path.exists(path)
935
+ if havePreviousFile:
936
+ # ensure we use the same structure as the destination
937
+ existingStructure = _sniffFileStructure(path)
938
+ if structure is not None:
939
+ try:
940
+ structure = UFOFileStructure(structure)
941
+ except ValueError:
942
+ raise UFOLibError(
943
+ "Invalid or unsupported structure: '%s'" % structure
944
+ )
945
+ if structure is not existingStructure:
946
+ raise UFOLibError(
947
+ "A UFO with a different structure (%s) already exists "
948
+ "at the given path: '%s'" % (existingStructure, path)
949
+ )
950
+ else:
951
+ structure = existingStructure
952
+ else:
953
+ # if not exists, default to 'package' structure
954
+ if structure is None:
955
+ structure = UFOFileStructure.PACKAGE
956
+ dirName = os.path.dirname(path)
957
+ if dirName and not os.path.isdir(dirName):
958
+ raise UFOLibError(
959
+ "Cannot write to '%s': directory does not exist" % path
960
+ )
961
+ if structure is UFOFileStructure.ZIP:
962
+ if havePreviousFile:
963
+ # we can't write a zip in-place, so we have to copy its
964
+ # contents to a temporary location and work from there, then
965
+ # upon closing UFOWriter we create the final zip file
966
+ parentFS = fs.tempfs.TempFS()
967
+ with fs.zipfs.ZipFS(path, encoding="utf-8") as origFS:
968
+ fs.copy.copy_fs(origFS, parentFS)
969
+ # if output path is an existing zip, we require that it contains
970
+ # one, and only one, root directory (with arbitrary name), in turn
971
+ # containing all the existing UFO contents
972
+ rootDirs = [
973
+ p.name
974
+ for p in parentFS.scandir("/")
975
+ # exclude macOS metadata contained in zip file
976
+ if p.is_dir and p.name != "__MACOSX"
977
+ ]
978
+ if len(rootDirs) != 1:
979
+ raise UFOLibError(
980
+ "Expected exactly 1 root directory, found %d"
981
+ % len(rootDirs)
982
+ )
983
+ else:
984
+ rootDir = rootDirs[0]
985
+ else:
986
+ # if the output zip file didn't exist, we create the root folder;
987
+ # we name it the same as input 'path', but with '.ufo' extension
988
+ rootDir = os.path.splitext(os.path.basename(path))[0] + ".ufo"
989
+ parentFS = fs.zipfs.ZipFS(path, write=True, encoding="utf-8")
990
+ parentFS.makedir(rootDir)
991
+ # 'ClosingSubFS' ensures that the parent filesystem is closed
992
+ # when its root subdirectory is closed
993
+ self.fs = parentFS.opendir(rootDir, factory=fs.subfs.ClosingSubFS)
994
+ else:
995
+ self.fs = fs.osfs.OSFS(path, create=True)
996
+ self._fileStructure = structure
997
+ self._havePreviousFile = havePreviousFile
998
+ self._shouldClose = True
999
+ elif isinstance(path, fs.base.FS):
1000
+ filesystem = path
1001
+ try:
1002
+ filesystem.check()
1003
+ except fs.errors.FilesystemClosed:
1004
+ raise UFOLibError("the filesystem '%s' is closed" % path)
1005
+ else:
1006
+ self.fs = filesystem
1007
+ try:
1008
+ path = filesystem.getsyspath("/")
1009
+ except fs.errors.NoSysPath:
1010
+ # network or in-memory FS may not map to the local one
1011
+ path = str(filesystem)
1012
+ # if passed an FS object, always use 'package' structure
1013
+ if structure and structure is not UFOFileStructure.PACKAGE:
1014
+ import warnings
1015
+
1016
+ warnings.warn(
1017
+ "The 'structure' argument is not used when input is an FS object",
1018
+ UserWarning,
1019
+ stacklevel=2,
1020
+ )
1021
+ self._fileStructure = UFOFileStructure.PACKAGE
1022
+ # if FS contains a "metainfo.plist", we consider it non-empty
1023
+ self._havePreviousFile = filesystem.exists(METAINFO_FILENAME)
1024
+ # the user is responsible for closing the FS object
1025
+ self._shouldClose = False
1026
+ else:
1027
+ raise TypeError(
1028
+ "Expected a path string or fs object, found %s" % type(path).__name__
1029
+ )
1030
+
1031
+ # establish some basic stuff
1032
+ self._path = fsdecode(path)
1033
+ self._formatVersion = formatVersion
1034
+ self._fileCreator = fileCreator
1035
+ self._downConversionKerningData = None
1036
+ self._validate = validate
1037
+ # if the file already exists, get the format version.
1038
+ # this will be needed for up and down conversion.
1039
+ previousFormatVersion = None
1040
+ if self._havePreviousFile:
1041
+ metaInfo = self._readMetaInfo(validate=validate)
1042
+ previousFormatVersion = metaInfo["formatVersionTuple"]
1043
+ # catch down conversion
1044
+ if previousFormatVersion > formatVersion:
1045
+ from fontTools.ufoLib.errors import UnsupportedUFOFormat
1046
+
1047
+ raise UnsupportedUFOFormat(
1048
+ "The UFO located at this path is a higher version "
1049
+ f"({previousFormatVersion}) than the version ({formatVersion}) "
1050
+ "that is trying to be written. This is not supported."
1051
+ )
1052
+ # handle the layer contents
1053
+ self.layerContents = {}
1054
+ if previousFormatVersion is not None and previousFormatVersion.major >= 3:
1055
+ # already exists
1056
+ self.layerContents = OrderedDict(self._readLayerContents(validate))
1057
+ else:
1058
+ # previous < 3
1059
+ # imply the layer contents
1060
+ if self.fs.exists(DEFAULT_GLYPHS_DIRNAME):
1061
+ self.layerContents = {DEFAULT_LAYER_NAME: DEFAULT_GLYPHS_DIRNAME}
1062
+ # write the new metainfo
1063
+ self._writeMetaInfo()
1064
+
1065
+ # properties
1066
+
1067
+ def _get_fileCreator(self):
1068
+ return self._fileCreator
1069
+
1070
+ fileCreator = property(
1071
+ _get_fileCreator,
1072
+ doc="The file creator of the UFO. This is set into metainfo.plist during __init__.",
1073
+ )
1074
+
1075
+ # support methods for file system interaction
1076
+
1077
+ def copyFromReader(self, reader, sourcePath, destPath):
1078
+ """
1079
+ Copy the sourcePath in the provided UFOReader to destPath
1080
+ in this writer. The paths must be relative. This works with
1081
+ both individual files and directories.
1082
+ """
1083
+ if not isinstance(reader, UFOReader):
1084
+ raise UFOLibError("The reader must be an instance of UFOReader.")
1085
+ sourcePath = fsdecode(sourcePath)
1086
+ destPath = fsdecode(destPath)
1087
+ if not reader.fs.exists(sourcePath):
1088
+ raise UFOLibError(
1089
+ 'The reader does not have data located at "%s".' % sourcePath
1090
+ )
1091
+ if self.fs.exists(destPath):
1092
+ raise UFOLibError('A file named "%s" already exists.' % destPath)
1093
+ # create the destination directory if it doesn't exist
1094
+ self.fs.makedirs(fs.path.dirname(destPath), recreate=True)
1095
+ if reader.fs.isdir(sourcePath):
1096
+ fs.copy.copy_dir(reader.fs, sourcePath, self.fs, destPath)
1097
+ else:
1098
+ fs.copy.copy_file(reader.fs, sourcePath, self.fs, destPath)
1099
+
1100
+ def writeBytesToPath(self, path, data):
1101
+ """
1102
+ Write bytes to a path relative to the UFO filesystem's root.
1103
+ If writing to an existing UFO, check to see if data matches the data
1104
+ that is already in the file at path; if so, the file is not rewritten
1105
+ so that the modification date is preserved.
1106
+ If needed, the directory tree for the given path will be built.
1107
+ """
1108
+ path = fsdecode(path)
1109
+ if self._havePreviousFile:
1110
+ if self.fs.isfile(path) and data == self.fs.readbytes(path):
1111
+ return
1112
+ try:
1113
+ self.fs.writebytes(path, data)
1114
+ except fs.errors.FileExpected:
1115
+ raise UFOLibError("A directory exists at '%s'" % path)
1116
+ except fs.errors.ResourceNotFound:
1117
+ self.fs.makedirs(fs.path.dirname(path), recreate=True)
1118
+ self.fs.writebytes(path, data)
1119
+
1120
+ def getFileObjectForPath(self, path, mode="w", encoding=None):
1121
+ """
1122
+ Returns a file (or file-like) object for the
1123
+ file at the given path. The path must be relative
1124
+ to the UFO path. Returns None if the file does
1125
+ not exist and the mode is "r" or "rb.
1126
+ An encoding may be passed if the file is opened in text mode.
1127
+
1128
+ Note: The caller is responsible for closing the open file.
1129
+ """
1130
+ path = fsdecode(path)
1131
+ try:
1132
+ return self.fs.open(path, mode=mode, encoding=encoding)
1133
+ except fs.errors.ResourceNotFound as e:
1134
+ m = mode[0]
1135
+ if m == "r":
1136
+ # XXX I think we should just let it raise. The docstring,
1137
+ # however, says that this returns None if mode is 'r'
1138
+ return None
1139
+ elif m == "w" or m == "a" or m == "x":
1140
+ self.fs.makedirs(fs.path.dirname(path), recreate=True)
1141
+ return self.fs.open(path, mode=mode, encoding=encoding)
1142
+ except fs.errors.ResourceError as e:
1143
+ return UFOLibError(f"unable to open '{path}' on {self.fs}: {e}")
1144
+
1145
+ def removePath(self, path, force=False, removeEmptyParents=True):
1146
+ """
1147
+ Remove the file (or directory) at path. The path
1148
+ must be relative to the UFO.
1149
+ Raises UFOLibError if the path doesn't exist.
1150
+ If force=True, ignore non-existent paths.
1151
+ If the directory where 'path' is located becomes empty, it will
1152
+ be automatically removed, unless 'removeEmptyParents' is False.
1153
+ """
1154
+ path = fsdecode(path)
1155
+ try:
1156
+ self.fs.remove(path)
1157
+ except fs.errors.FileExpected:
1158
+ self.fs.removetree(path)
1159
+ except fs.errors.ResourceNotFound:
1160
+ if not force:
1161
+ raise UFOLibError(f"'{path}' does not exist on {self.fs}")
1162
+ if removeEmptyParents:
1163
+ parent = fs.path.dirname(path)
1164
+ if parent:
1165
+ fs.tools.remove_empty(self.fs, parent)
1166
+
1167
+ # alias kept for backward compatibility with old API
1168
+ removeFileForPath = removePath
1169
+
1170
+ # UFO mod time
1171
+
1172
+ def setModificationTime(self):
1173
+ """
1174
+ Set the UFO modification time to the current time.
1175
+ This is never called automatically. It is up to the
1176
+ caller to call this when finished working on the UFO.
1177
+ """
1178
+ path = self._path
1179
+ if path is not None and os.path.exists(path):
1180
+ try:
1181
+ # this may fail on some filesystems (e.g. SMB servers)
1182
+ os.utime(path, None)
1183
+ except OSError as e:
1184
+ logger.warning("Failed to set modified time: %s", e)
1185
+
1186
+ # metainfo.plist
1187
+
1188
+ def _writeMetaInfo(self):
1189
+ metaInfo = dict(
1190
+ creator=self._fileCreator,
1191
+ formatVersion=self._formatVersion.major,
1192
+ )
1193
+ if self._formatVersion.minor != 0:
1194
+ metaInfo["formatVersionMinor"] = self._formatVersion.minor
1195
+ self._writePlist(METAINFO_FILENAME, metaInfo)
1196
+
1197
+ # groups.plist
1198
+
1199
+ def setKerningGroupConversionRenameMaps(self, maps):
1200
+ """
1201
+ Set maps defining the renaming that should be done
1202
+ when writing groups and kerning in UFO 1 and UFO 2.
1203
+ This will effectively undo the conversion done when
1204
+ UFOReader reads this data. The dictionary should have
1205
+ this form::
1206
+
1207
+ {
1208
+ "side1" : {"group name to use when writing" : "group name in data"},
1209
+ "side2" : {"group name to use when writing" : "group name in data"}
1210
+ }
1211
+
1212
+ This is the same form returned by UFOReader's
1213
+ getKerningGroupConversionRenameMaps method.
1214
+ """
1215
+ if self._formatVersion >= UFOFormatVersion.FORMAT_3_0:
1216
+ return # XXX raise an error here
1217
+ # flip the dictionaries
1218
+ remap = {}
1219
+ for side in ("side1", "side2"):
1220
+ for writeName, dataName in list(maps[side].items()):
1221
+ remap[dataName] = writeName
1222
+ self._downConversionKerningData = dict(groupRenameMap=remap)
1223
+
1224
+ def writeGroups(self, groups, validate=None):
1225
+ """
1226
+ Write groups.plist. This method requires a
1227
+ dict of glyph groups as an argument.
1228
+
1229
+ ``validate`` will validate the data, by default it is set to the
1230
+ class's validate value, can be overridden.
1231
+ """
1232
+ if validate is None:
1233
+ validate = self._validate
1234
+ # validate the data structure
1235
+ if validate:
1236
+ valid, message = groupsValidator(groups)
1237
+ if not valid:
1238
+ raise UFOLibError(message)
1239
+ # down convert
1240
+ if (
1241
+ self._formatVersion < UFOFormatVersion.FORMAT_3_0
1242
+ and self._downConversionKerningData is not None
1243
+ ):
1244
+ remap = self._downConversionKerningData["groupRenameMap"]
1245
+ remappedGroups = {}
1246
+ # there are some edge cases here that are ignored:
1247
+ # 1. if a group is being renamed to a name that
1248
+ # already exists, the existing group is always
1249
+ # overwritten. (this is why there are two loops
1250
+ # below.) there doesn't seem to be a logical
1251
+ # solution to groups mismatching and overwriting
1252
+ # with the specifiecd group seems like a better
1253
+ # solution than throwing an error.
1254
+ # 2. if side 1 and side 2 groups are being renamed
1255
+ # to the same group name there is no check to
1256
+ # ensure that the contents are identical. that
1257
+ # is left up to the caller.
1258
+ for name, contents in list(groups.items()):
1259
+ if name in remap:
1260
+ continue
1261
+ remappedGroups[name] = contents
1262
+ for name, contents in list(groups.items()):
1263
+ if name not in remap:
1264
+ continue
1265
+ name = remap[name]
1266
+ remappedGroups[name] = contents
1267
+ groups = remappedGroups
1268
+ # pack and write
1269
+ groupsNew = {}
1270
+ for key, value in groups.items():
1271
+ groupsNew[key] = list(value)
1272
+ if groupsNew:
1273
+ self._writePlist(GROUPS_FILENAME, groupsNew)
1274
+ elif self._havePreviousFile:
1275
+ self.removePath(GROUPS_FILENAME, force=True, removeEmptyParents=False)
1276
+
1277
+ # fontinfo.plist
1278
+
1279
+ def writeInfo(self, info, validate=None):
1280
+ """
1281
+ Write info.plist. This method requires an object
1282
+ that supports getting attributes that follow the
1283
+ fontinfo.plist version 2 specification. Attributes
1284
+ will be taken from the given object and written
1285
+ into the file.
1286
+
1287
+ ``validate`` will validate the data, by default it is set to the
1288
+ class's validate value, can be overridden.
1289
+ """
1290
+ if validate is None:
1291
+ validate = self._validate
1292
+ # gather version 3 data
1293
+ infoData = {}
1294
+ for attr in list(fontInfoAttributesVersion3ValueData.keys()):
1295
+ if hasattr(info, attr):
1296
+ try:
1297
+ value = getattr(info, attr)
1298
+ except AttributeError:
1299
+ raise UFOLibError(
1300
+ "The supplied info object does not support getting a necessary attribute (%s)."
1301
+ % attr
1302
+ )
1303
+ if value is None:
1304
+ continue
1305
+ infoData[attr] = value
1306
+ # down convert data if necessary and validate
1307
+ if self._formatVersion == UFOFormatVersion.FORMAT_3_0:
1308
+ if validate:
1309
+ infoData = validateInfoVersion3Data(infoData)
1310
+ elif self._formatVersion == UFOFormatVersion.FORMAT_2_0:
1311
+ infoData = _convertFontInfoDataVersion3ToVersion2(infoData)
1312
+ if validate:
1313
+ infoData = validateInfoVersion2Data(infoData)
1314
+ elif self._formatVersion == UFOFormatVersion.FORMAT_1_0:
1315
+ infoData = _convertFontInfoDataVersion3ToVersion2(infoData)
1316
+ if validate:
1317
+ infoData = validateInfoVersion2Data(infoData)
1318
+ infoData = _convertFontInfoDataVersion2ToVersion1(infoData)
1319
+ # write file if there is anything to write
1320
+ if infoData:
1321
+ self._writePlist(FONTINFO_FILENAME, infoData)
1322
+
1323
+ # kerning.plist
1324
+
1325
+ def writeKerning(self, kerning, validate=None):
1326
+ """
1327
+ Write kerning.plist. This method requires a
1328
+ dict of kerning pairs as an argument.
1329
+
1330
+ This performs basic structural validation of the kerning,
1331
+ but it does not check for compliance with the spec in
1332
+ regards to conflicting pairs. The assumption is that the
1333
+ kerning data being passed is standards compliant.
1334
+
1335
+ ``validate`` will validate the data, by default it is set to the
1336
+ class's validate value, can be overridden.
1337
+ """
1338
+ if validate is None:
1339
+ validate = self._validate
1340
+ # validate the data structure
1341
+ if validate:
1342
+ invalidFormatMessage = "The kerning is not properly formatted."
1343
+ if not isDictEnough(kerning):
1344
+ raise UFOLibError(invalidFormatMessage)
1345
+ for pair, value in list(kerning.items()):
1346
+ if not isinstance(pair, (list, tuple)):
1347
+ raise UFOLibError(invalidFormatMessage)
1348
+ if not len(pair) == 2:
1349
+ raise UFOLibError(invalidFormatMessage)
1350
+ if not isinstance(pair[0], str):
1351
+ raise UFOLibError(invalidFormatMessage)
1352
+ if not isinstance(pair[1], str):
1353
+ raise UFOLibError(invalidFormatMessage)
1354
+ if not isinstance(value, numberTypes):
1355
+ raise UFOLibError(invalidFormatMessage)
1356
+ # down convert
1357
+ if (
1358
+ self._formatVersion < UFOFormatVersion.FORMAT_3_0
1359
+ and self._downConversionKerningData is not None
1360
+ ):
1361
+ remap = self._downConversionKerningData["groupRenameMap"]
1362
+ remappedKerning = {}
1363
+ for (side1, side2), value in list(kerning.items()):
1364
+ side1 = remap.get(side1, side1)
1365
+ side2 = remap.get(side2, side2)
1366
+ remappedKerning[side1, side2] = value
1367
+ kerning = remappedKerning
1368
+ # pack and write
1369
+ kerningDict = {}
1370
+ for left, right in kerning.keys():
1371
+ value = kerning[left, right]
1372
+ if left not in kerningDict:
1373
+ kerningDict[left] = {}
1374
+ kerningDict[left][right] = value
1375
+ if kerningDict:
1376
+ self._writePlist(KERNING_FILENAME, kerningDict)
1377
+ elif self._havePreviousFile:
1378
+ self.removePath(KERNING_FILENAME, force=True, removeEmptyParents=False)
1379
+
1380
+ # lib.plist
1381
+
1382
+ def writeLib(self, libDict, validate=None):
1383
+ """
1384
+ Write lib.plist. This method requires a
1385
+ lib dict as an argument.
1386
+
1387
+ ``validate`` will validate the data, by default it is set to the
1388
+ class's validate value, can be overridden.
1389
+ """
1390
+ if validate is None:
1391
+ validate = self._validate
1392
+ if validate:
1393
+ valid, message = fontLibValidator(libDict)
1394
+ if not valid:
1395
+ raise UFOLibError(message)
1396
+ if libDict:
1397
+ self._writePlist(LIB_FILENAME, libDict)
1398
+ elif self._havePreviousFile:
1399
+ self.removePath(LIB_FILENAME, force=True, removeEmptyParents=False)
1400
+
1401
+ # features.fea
1402
+
1403
+ def writeFeatures(self, features, validate=None):
1404
+ """
1405
+ Write features.fea. This method requires a
1406
+ features string as an argument.
1407
+ """
1408
+ if validate is None:
1409
+ validate = self._validate
1410
+ if self._formatVersion == UFOFormatVersion.FORMAT_1_0:
1411
+ raise UFOLibError("features.fea is not allowed in UFO Format Version 1.")
1412
+ if validate:
1413
+ if not isinstance(features, str):
1414
+ raise UFOLibError("The features are not text.")
1415
+ if features:
1416
+ self.writeBytesToPath(FEATURES_FILENAME, features.encode("utf8"))
1417
+ elif self._havePreviousFile:
1418
+ self.removePath(FEATURES_FILENAME, force=True, removeEmptyParents=False)
1419
+
1420
+ # glyph sets & layers
1421
+
1422
+ def writeLayerContents(self, layerOrder=None, validate=None):
1423
+ """
1424
+ Write the layercontents.plist file. This method *must* be called
1425
+ after all glyph sets have been written.
1426
+ """
1427
+ if validate is None:
1428
+ validate = self._validate
1429
+ if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
1430
+ return
1431
+ if layerOrder is not None:
1432
+ newOrder = []
1433
+ for layerName in layerOrder:
1434
+ if layerName is None:
1435
+ layerName = DEFAULT_LAYER_NAME
1436
+ newOrder.append(layerName)
1437
+ layerOrder = newOrder
1438
+ else:
1439
+ layerOrder = list(self.layerContents.keys())
1440
+ if validate and set(layerOrder) != set(self.layerContents.keys()):
1441
+ raise UFOLibError(
1442
+ "The layer order content does not match the glyph sets that have been created."
1443
+ )
1444
+ layerContents = [
1445
+ (layerName, self.layerContents[layerName]) for layerName in layerOrder
1446
+ ]
1447
+ self._writePlist(LAYERCONTENTS_FILENAME, layerContents)
1448
+
1449
+ def _findDirectoryForLayerName(self, layerName):
1450
+ foundDirectory = None
1451
+ for existingLayerName, directoryName in list(self.layerContents.items()):
1452
+ if layerName is None and directoryName == DEFAULT_GLYPHS_DIRNAME:
1453
+ foundDirectory = directoryName
1454
+ break
1455
+ elif existingLayerName == layerName:
1456
+ foundDirectory = directoryName
1457
+ break
1458
+ if not foundDirectory:
1459
+ raise UFOLibError(
1460
+ "Could not locate a glyph set directory for the layer named %s."
1461
+ % layerName
1462
+ )
1463
+ return foundDirectory
1464
+
1465
+ def getGlyphSet(
1466
+ self,
1467
+ layerName=None,
1468
+ defaultLayer=True,
1469
+ glyphNameToFileNameFunc=None,
1470
+ validateRead=None,
1471
+ validateWrite=None,
1472
+ expectContentsFile=False,
1473
+ ):
1474
+ """
1475
+ Return the GlyphSet object associated with the
1476
+ appropriate glyph directory in the .ufo.
1477
+ If layerName is None, the default glyph set
1478
+ will be used. The defaultLayer flag indictes
1479
+ that the layer should be saved into the default
1480
+ glyphs directory.
1481
+
1482
+ ``validateRead`` will validate the read data, by default it is set to the
1483
+ class's validate value, can be overridden.
1484
+ ``validateWrte`` will validate the written data, by default it is set to the
1485
+ class's validate value, can be overridden.
1486
+ ``expectContentsFile`` will raise a GlifLibError if a contents.plist file is
1487
+ not found on the glyph set file system. This should be set to ``True`` if you
1488
+ are reading an existing UFO and ``False`` if you use ``getGlyphSet`` to create
1489
+ a fresh glyph set.
1490
+ """
1491
+ if validateRead is None:
1492
+ validateRead = self._validate
1493
+ if validateWrite is None:
1494
+ validateWrite = self._validate
1495
+ # only default can be written in < 3
1496
+ if self._formatVersion < UFOFormatVersion.FORMAT_3_0 and (
1497
+ not defaultLayer or layerName is not None
1498
+ ):
1499
+ raise UFOLibError(
1500
+ f"Only the default layer can be writen in UFO {self._formatVersion.major}."
1501
+ )
1502
+ # locate a layer name when None has been given
1503
+ if layerName is None and defaultLayer:
1504
+ for existingLayerName, directory in self.layerContents.items():
1505
+ if directory == DEFAULT_GLYPHS_DIRNAME:
1506
+ layerName = existingLayerName
1507
+ if layerName is None:
1508
+ layerName = DEFAULT_LAYER_NAME
1509
+ elif layerName is None and not defaultLayer:
1510
+ raise UFOLibError("A layer name must be provided for non-default layers.")
1511
+ # move along to format specific writing
1512
+ if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
1513
+ return self._getDefaultGlyphSet(
1514
+ validateRead,
1515
+ validateWrite,
1516
+ glyphNameToFileNameFunc=glyphNameToFileNameFunc,
1517
+ expectContentsFile=expectContentsFile,
1518
+ )
1519
+ elif self._formatVersion.major == UFOFormatVersion.FORMAT_3_0.major:
1520
+ return self._getGlyphSetFormatVersion3(
1521
+ validateRead,
1522
+ validateWrite,
1523
+ layerName=layerName,
1524
+ defaultLayer=defaultLayer,
1525
+ glyphNameToFileNameFunc=glyphNameToFileNameFunc,
1526
+ expectContentsFile=expectContentsFile,
1527
+ )
1528
+ else:
1529
+ raise NotImplementedError(self._formatVersion)
1530
+
1531
+ def _getDefaultGlyphSet(
1532
+ self,
1533
+ validateRead,
1534
+ validateWrite,
1535
+ glyphNameToFileNameFunc=None,
1536
+ expectContentsFile=False,
1537
+ ):
1538
+ from fontTools.ufoLib.glifLib import GlyphSet
1539
+
1540
+ glyphSubFS = self.fs.makedir(DEFAULT_GLYPHS_DIRNAME, recreate=True)
1541
+ return GlyphSet(
1542
+ glyphSubFS,
1543
+ glyphNameToFileNameFunc=glyphNameToFileNameFunc,
1544
+ ufoFormatVersion=self._formatVersion,
1545
+ validateRead=validateRead,
1546
+ validateWrite=validateWrite,
1547
+ expectContentsFile=expectContentsFile,
1548
+ )
1549
+
1550
+ def _getGlyphSetFormatVersion3(
1551
+ self,
1552
+ validateRead,
1553
+ validateWrite,
1554
+ layerName=None,
1555
+ defaultLayer=True,
1556
+ glyphNameToFileNameFunc=None,
1557
+ expectContentsFile=False,
1558
+ ):
1559
+ from fontTools.ufoLib.glifLib import GlyphSet
1560
+
1561
+ # if the default flag is on, make sure that the default in the file
1562
+ # matches the default being written. also make sure that this layer
1563
+ # name is not already linked to a non-default layer.
1564
+ if defaultLayer:
1565
+ for existingLayerName, directory in self.layerContents.items():
1566
+ if directory == DEFAULT_GLYPHS_DIRNAME:
1567
+ if existingLayerName != layerName:
1568
+ raise UFOLibError(
1569
+ "Another layer ('%s') is already mapped to the default directory."
1570
+ % existingLayerName
1571
+ )
1572
+ elif existingLayerName == layerName:
1573
+ raise UFOLibError(
1574
+ "The layer name is already mapped to a non-default layer."
1575
+ )
1576
+ # get an existing directory name
1577
+ if layerName in self.layerContents:
1578
+ directory = self.layerContents[layerName]
1579
+ # get a new directory name
1580
+ else:
1581
+ if defaultLayer:
1582
+ directory = DEFAULT_GLYPHS_DIRNAME
1583
+ else:
1584
+ # not caching this could be slightly expensive,
1585
+ # but caching it will be cumbersome
1586
+ existing = {d.lower() for d in self.layerContents.values()}
1587
+ directory = userNameToFileName(
1588
+ layerName, existing=existing, prefix="glyphs."
1589
+ )
1590
+ # make the directory
1591
+ glyphSubFS = self.fs.makedir(directory, recreate=True)
1592
+ # store the mapping
1593
+ self.layerContents[layerName] = directory
1594
+ # load the glyph set
1595
+ return GlyphSet(
1596
+ glyphSubFS,
1597
+ glyphNameToFileNameFunc=glyphNameToFileNameFunc,
1598
+ ufoFormatVersion=self._formatVersion,
1599
+ validateRead=validateRead,
1600
+ validateWrite=validateWrite,
1601
+ expectContentsFile=expectContentsFile,
1602
+ )
1603
+
1604
+ def renameGlyphSet(self, layerName, newLayerName, defaultLayer=False):
1605
+ """
1606
+ Rename a glyph set.
1607
+
1608
+ Note: if a GlyphSet object has already been retrieved for
1609
+ layerName, it is up to the caller to inform that object that
1610
+ the directory it represents has changed.
1611
+ """
1612
+ if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
1613
+ # ignore renaming glyph sets for UFO1 UFO2
1614
+ # just write the data from the default layer
1615
+ return
1616
+ # the new and old names can be the same
1617
+ # as long as the default is being switched
1618
+ if layerName == newLayerName:
1619
+ # if the default is off and the layer is already not the default, skip
1620
+ if (
1621
+ self.layerContents[layerName] != DEFAULT_GLYPHS_DIRNAME
1622
+ and not defaultLayer
1623
+ ):
1624
+ return
1625
+ # if the default is on and the layer is already the default, skip
1626
+ if self.layerContents[layerName] == DEFAULT_GLYPHS_DIRNAME and defaultLayer:
1627
+ return
1628
+ else:
1629
+ # make sure the new layer name doesn't already exist
1630
+ if newLayerName is None:
1631
+ newLayerName = DEFAULT_LAYER_NAME
1632
+ if newLayerName in self.layerContents:
1633
+ raise UFOLibError("A layer named %s already exists." % newLayerName)
1634
+ # make sure the default layer doesn't already exist
1635
+ if defaultLayer and DEFAULT_GLYPHS_DIRNAME in self.layerContents.values():
1636
+ raise UFOLibError("A default layer already exists.")
1637
+ # get the paths
1638
+ oldDirectory = self._findDirectoryForLayerName(layerName)
1639
+ if defaultLayer:
1640
+ newDirectory = DEFAULT_GLYPHS_DIRNAME
1641
+ else:
1642
+ existing = {name.lower() for name in self.layerContents.values()}
1643
+ newDirectory = userNameToFileName(
1644
+ newLayerName, existing=existing, prefix="glyphs."
1645
+ )
1646
+ # update the internal mapping
1647
+ del self.layerContents[layerName]
1648
+ self.layerContents[newLayerName] = newDirectory
1649
+ # do the file system copy
1650
+ self.fs.movedir(oldDirectory, newDirectory, create=True)
1651
+
1652
+ def deleteGlyphSet(self, layerName):
1653
+ """
1654
+ Remove the glyph set matching layerName.
1655
+ """
1656
+ if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
1657
+ # ignore deleting glyph sets for UFO1 UFO2 as there are no layers
1658
+ # just write the data from the default layer
1659
+ return
1660
+ foundDirectory = self._findDirectoryForLayerName(layerName)
1661
+ self.removePath(foundDirectory, removeEmptyParents=False)
1662
+ del self.layerContents[layerName]
1663
+
1664
+ def writeData(self, fileName, data):
1665
+ """
1666
+ Write data to fileName in the 'data' directory.
1667
+ The data must be a bytes string.
1668
+ """
1669
+ self.writeBytesToPath(f"{DATA_DIRNAME}/{fsdecode(fileName)}", data)
1670
+
1671
+ def removeData(self, fileName):
1672
+ """
1673
+ Remove the file named fileName from the data directory.
1674
+ """
1675
+ self.removePath(f"{DATA_DIRNAME}/{fsdecode(fileName)}")
1676
+
1677
+ # /images
1678
+
1679
+ def writeImage(self, fileName, data, validate=None):
1680
+ """
1681
+ Write data to fileName in the images directory.
1682
+ The data must be a valid PNG.
1683
+ """
1684
+ if validate is None:
1685
+ validate = self._validate
1686
+ if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
1687
+ raise UFOLibError(
1688
+ f"Images are not allowed in UFO {self._formatVersion.major}."
1689
+ )
1690
+ fileName = fsdecode(fileName)
1691
+ if validate:
1692
+ valid, error = pngValidator(data=data)
1693
+ if not valid:
1694
+ raise UFOLibError(error)
1695
+ self.writeBytesToPath(f"{IMAGES_DIRNAME}/{fileName}", data)
1696
+
1697
+ def removeImage(self, fileName, validate=None): # XXX remove unused 'validate'?
1698
+ """
1699
+ Remove the file named fileName from the
1700
+ images directory.
1701
+ """
1702
+ if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
1703
+ raise UFOLibError(
1704
+ f"Images are not allowed in UFO {self._formatVersion.major}."
1705
+ )
1706
+ self.removePath(f"{IMAGES_DIRNAME}/{fsdecode(fileName)}")
1707
+
1708
+ def copyImageFromReader(self, reader, sourceFileName, destFileName, validate=None):
1709
+ """
1710
+ Copy the sourceFileName in the provided UFOReader to destFileName
1711
+ in this writer. This uses the most memory efficient method possible
1712
+ for copying the data possible.
1713
+ """
1714
+ if validate is None:
1715
+ validate = self._validate
1716
+ if self._formatVersion < UFOFormatVersion.FORMAT_3_0:
1717
+ raise UFOLibError(
1718
+ f"Images are not allowed in UFO {self._formatVersion.major}."
1719
+ )
1720
+ sourcePath = f"{IMAGES_DIRNAME}/{fsdecode(sourceFileName)}"
1721
+ destPath = f"{IMAGES_DIRNAME}/{fsdecode(destFileName)}"
1722
+ self.copyFromReader(reader, sourcePath, destPath)
1723
+
1724
+ def close(self):
1725
+ if self._havePreviousFile and self._fileStructure is UFOFileStructure.ZIP:
1726
+ # if we are updating an existing zip file, we can now compress the
1727
+ # contents of the temporary filesystem in the destination path
1728
+ rootDir = os.path.splitext(os.path.basename(self._path))[0] + ".ufo"
1729
+ with fs.zipfs.ZipFS(self._path, write=True, encoding="utf-8") as destFS:
1730
+ fs.copy.copy_fs(self.fs, destFS.makedir(rootDir))
1731
+ super().close()
1732
+
1733
+
1734
+ # just an alias, makes it more explicit
1735
+ UFOReaderWriter = UFOWriter
1736
+
1737
+
1738
+ # ----------------
1739
+ # Helper Functions
1740
+ # ----------------
1741
+
1742
+
1743
+ def _sniffFileStructure(ufo_path):
1744
+ """Return UFOFileStructure.ZIP if the UFO at path 'ufo_path' (str)
1745
+ is a zip file, else return UFOFileStructure.PACKAGE if 'ufo_path' is a
1746
+ directory.
1747
+ Raise UFOLibError if it is a file with unknown structure, or if the path
1748
+ does not exist.
1749
+ """
1750
+ if zipfile.is_zipfile(ufo_path):
1751
+ return UFOFileStructure.ZIP
1752
+ elif os.path.isdir(ufo_path):
1753
+ return UFOFileStructure.PACKAGE
1754
+ elif os.path.isfile(ufo_path):
1755
+ raise UFOLibError(
1756
+ "The specified UFO does not have a known structure: '%s'" % ufo_path
1757
+ )
1758
+ else:
1759
+ raise UFOLibError("No such file or directory: '%s'" % ufo_path)
1760
+
1761
+
1762
+ def makeUFOPath(path):
1763
+ """
1764
+ Return a .ufo pathname.
1765
+
1766
+ >>> makeUFOPath("directory/something.ext") == (
1767
+ ... os.path.join('directory', 'something.ufo'))
1768
+ True
1769
+ >>> makeUFOPath("directory/something.another.thing.ext") == (
1770
+ ... os.path.join('directory', 'something.another.thing.ufo'))
1771
+ True
1772
+ """
1773
+ dir, name = os.path.split(path)
1774
+ name = ".".join([".".join(name.split(".")[:-1]), "ufo"])
1775
+ return os.path.join(dir, name)
1776
+
1777
+
1778
+ # ----------------------
1779
+ # fontinfo.plist Support
1780
+ # ----------------------
1781
+
1782
+ # Version Validators
1783
+
1784
+ # There is no version 1 validator and there shouldn't be.
1785
+ # The version 1 spec was very loose and there were numerous
1786
+ # cases of invalid values.
1787
+
1788
+
1789
+ def validateFontInfoVersion2ValueForAttribute(attr, value):
1790
+ """
1791
+ This performs very basic validation of the value for attribute
1792
+ following the UFO 2 fontinfo.plist specification. The results
1793
+ of this should not be interpretted as *correct* for the font
1794
+ that they are part of. This merely indicates that the value
1795
+ is of the proper type and, where the specification defines
1796
+ a set range of possible values for an attribute, that the
1797
+ value is in the accepted range.
1798
+ """
1799
+ dataValidationDict = fontInfoAttributesVersion2ValueData[attr]
1800
+ valueType = dataValidationDict.get("type")
1801
+ validator = dataValidationDict.get("valueValidator")
1802
+ valueOptions = dataValidationDict.get("valueOptions")
1803
+ # have specific options for the validator
1804
+ if valueOptions is not None:
1805
+ isValidValue = validator(value, valueOptions)
1806
+ # no specific options
1807
+ else:
1808
+ if validator == genericTypeValidator:
1809
+ isValidValue = validator(value, valueType)
1810
+ else:
1811
+ isValidValue = validator(value)
1812
+ return isValidValue
1813
+
1814
+
1815
+ def validateInfoVersion2Data(infoData):
1816
+ """
1817
+ This performs very basic validation of the value for infoData
1818
+ following the UFO 2 fontinfo.plist specification. The results
1819
+ of this should not be interpretted as *correct* for the font
1820
+ that they are part of. This merely indicates that the values
1821
+ are of the proper type and, where the specification defines
1822
+ a set range of possible values for an attribute, that the
1823
+ value is in the accepted range.
1824
+ """
1825
+ validInfoData = {}
1826
+ for attr, value in list(infoData.items()):
1827
+ isValidValue = validateFontInfoVersion2ValueForAttribute(attr, value)
1828
+ if not isValidValue:
1829
+ raise UFOLibError(f"Invalid value for attribute {attr} ({value!r}).")
1830
+ else:
1831
+ validInfoData[attr] = value
1832
+ return validInfoData
1833
+
1834
+
1835
+ def validateFontInfoVersion3ValueForAttribute(attr, value):
1836
+ """
1837
+ This performs very basic validation of the value for attribute
1838
+ following the UFO 3 fontinfo.plist specification. The results
1839
+ of this should not be interpretted as *correct* for the font
1840
+ that they are part of. This merely indicates that the value
1841
+ is of the proper type and, where the specification defines
1842
+ a set range of possible values for an attribute, that the
1843
+ value is in the accepted range.
1844
+ """
1845
+ dataValidationDict = fontInfoAttributesVersion3ValueData[attr]
1846
+ valueType = dataValidationDict.get("type")
1847
+ validator = dataValidationDict.get("valueValidator")
1848
+ valueOptions = dataValidationDict.get("valueOptions")
1849
+ # have specific options for the validator
1850
+ if valueOptions is not None:
1851
+ isValidValue = validator(value, valueOptions)
1852
+ # no specific options
1853
+ else:
1854
+ if validator == genericTypeValidator:
1855
+ isValidValue = validator(value, valueType)
1856
+ else:
1857
+ isValidValue = validator(value)
1858
+ return isValidValue
1859
+
1860
+
1861
+ def validateInfoVersion3Data(infoData):
1862
+ """
1863
+ This performs very basic validation of the value for infoData
1864
+ following the UFO 3 fontinfo.plist specification. The results
1865
+ of this should not be interpretted as *correct* for the font
1866
+ that they are part of. This merely indicates that the values
1867
+ are of the proper type and, where the specification defines
1868
+ a set range of possible values for an attribute, that the
1869
+ value is in the accepted range.
1870
+ """
1871
+ validInfoData = {}
1872
+ for attr, value in list(infoData.items()):
1873
+ isValidValue = validateFontInfoVersion3ValueForAttribute(attr, value)
1874
+ if not isValidValue:
1875
+ raise UFOLibError(f"Invalid value for attribute {attr} ({value!r}).")
1876
+ else:
1877
+ validInfoData[attr] = value
1878
+ return validInfoData
1879
+
1880
+
1881
+ # Value Options
1882
+
1883
+ fontInfoOpenTypeHeadFlagsOptions = list(range(0, 15))
1884
+ fontInfoOpenTypeOS2SelectionOptions = [1, 2, 3, 4, 7, 8, 9]
1885
+ fontInfoOpenTypeOS2UnicodeRangesOptions = list(range(0, 128))
1886
+ fontInfoOpenTypeOS2CodePageRangesOptions = list(range(0, 64))
1887
+ fontInfoOpenTypeOS2TypeOptions = [0, 1, 2, 3, 8, 9]
1888
+
1889
+ # Version Attribute Definitions
1890
+ # This defines the attributes, types and, in some
1891
+ # cases the possible values, that can exist is
1892
+ # fontinfo.plist.
1893
+
1894
+ fontInfoAttributesVersion1 = {
1895
+ "familyName",
1896
+ "styleName",
1897
+ "fullName",
1898
+ "fontName",
1899
+ "menuName",
1900
+ "fontStyle",
1901
+ "note",
1902
+ "versionMajor",
1903
+ "versionMinor",
1904
+ "year",
1905
+ "copyright",
1906
+ "notice",
1907
+ "trademark",
1908
+ "license",
1909
+ "licenseURL",
1910
+ "createdBy",
1911
+ "designer",
1912
+ "designerURL",
1913
+ "vendorURL",
1914
+ "unitsPerEm",
1915
+ "ascender",
1916
+ "descender",
1917
+ "capHeight",
1918
+ "xHeight",
1919
+ "defaultWidth",
1920
+ "slantAngle",
1921
+ "italicAngle",
1922
+ "widthName",
1923
+ "weightName",
1924
+ "weightValue",
1925
+ "fondName",
1926
+ "otFamilyName",
1927
+ "otStyleName",
1928
+ "otMacName",
1929
+ "msCharSet",
1930
+ "fondID",
1931
+ "uniqueID",
1932
+ "ttVendor",
1933
+ "ttUniqueID",
1934
+ "ttVersion",
1935
+ }
1936
+
1937
+ fontInfoAttributesVersion2ValueData = {
1938
+ "familyName": dict(type=str),
1939
+ "styleName": dict(type=str),
1940
+ "styleMapFamilyName": dict(type=str),
1941
+ "styleMapStyleName": dict(
1942
+ type=str, valueValidator=fontInfoStyleMapStyleNameValidator
1943
+ ),
1944
+ "versionMajor": dict(type=int),
1945
+ "versionMinor": dict(type=int),
1946
+ "year": dict(type=int),
1947
+ "copyright": dict(type=str),
1948
+ "trademark": dict(type=str),
1949
+ "unitsPerEm": dict(type=(int, float)),
1950
+ "descender": dict(type=(int, float)),
1951
+ "xHeight": dict(type=(int, float)),
1952
+ "capHeight": dict(type=(int, float)),
1953
+ "ascender": dict(type=(int, float)),
1954
+ "italicAngle": dict(type=(float, int)),
1955
+ "note": dict(type=str),
1956
+ "openTypeHeadCreated": dict(
1957
+ type=str, valueValidator=fontInfoOpenTypeHeadCreatedValidator
1958
+ ),
1959
+ "openTypeHeadLowestRecPPEM": dict(type=(int, float)),
1960
+ "openTypeHeadFlags": dict(
1961
+ type="integerList",
1962
+ valueValidator=genericIntListValidator,
1963
+ valueOptions=fontInfoOpenTypeHeadFlagsOptions,
1964
+ ),
1965
+ "openTypeHheaAscender": dict(type=(int, float)),
1966
+ "openTypeHheaDescender": dict(type=(int, float)),
1967
+ "openTypeHheaLineGap": dict(type=(int, float)),
1968
+ "openTypeHheaCaretSlopeRise": dict(type=int),
1969
+ "openTypeHheaCaretSlopeRun": dict(type=int),
1970
+ "openTypeHheaCaretOffset": dict(type=(int, float)),
1971
+ "openTypeNameDesigner": dict(type=str),
1972
+ "openTypeNameDesignerURL": dict(type=str),
1973
+ "openTypeNameManufacturer": dict(type=str),
1974
+ "openTypeNameManufacturerURL": dict(type=str),
1975
+ "openTypeNameLicense": dict(type=str),
1976
+ "openTypeNameLicenseURL": dict(type=str),
1977
+ "openTypeNameVersion": dict(type=str),
1978
+ "openTypeNameUniqueID": dict(type=str),
1979
+ "openTypeNameDescription": dict(type=str),
1980
+ "openTypeNamePreferredFamilyName": dict(type=str),
1981
+ "openTypeNamePreferredSubfamilyName": dict(type=str),
1982
+ "openTypeNameCompatibleFullName": dict(type=str),
1983
+ "openTypeNameSampleText": dict(type=str),
1984
+ "openTypeNameWWSFamilyName": dict(type=str),
1985
+ "openTypeNameWWSSubfamilyName": dict(type=str),
1986
+ "openTypeOS2WidthClass": dict(
1987
+ type=int, valueValidator=fontInfoOpenTypeOS2WidthClassValidator
1988
+ ),
1989
+ "openTypeOS2WeightClass": dict(
1990
+ type=int, valueValidator=fontInfoOpenTypeOS2WeightClassValidator
1991
+ ),
1992
+ "openTypeOS2Selection": dict(
1993
+ type="integerList",
1994
+ valueValidator=genericIntListValidator,
1995
+ valueOptions=fontInfoOpenTypeOS2SelectionOptions,
1996
+ ),
1997
+ "openTypeOS2VendorID": dict(type=str),
1998
+ "openTypeOS2Panose": dict(
1999
+ type="integerList", valueValidator=fontInfoVersion2OpenTypeOS2PanoseValidator
2000
+ ),
2001
+ "openTypeOS2FamilyClass": dict(
2002
+ type="integerList", valueValidator=fontInfoOpenTypeOS2FamilyClassValidator
2003
+ ),
2004
+ "openTypeOS2UnicodeRanges": dict(
2005
+ type="integerList",
2006
+ valueValidator=genericIntListValidator,
2007
+ valueOptions=fontInfoOpenTypeOS2UnicodeRangesOptions,
2008
+ ),
2009
+ "openTypeOS2CodePageRanges": dict(
2010
+ type="integerList",
2011
+ valueValidator=genericIntListValidator,
2012
+ valueOptions=fontInfoOpenTypeOS2CodePageRangesOptions,
2013
+ ),
2014
+ "openTypeOS2TypoAscender": dict(type=(int, float)),
2015
+ "openTypeOS2TypoDescender": dict(type=(int, float)),
2016
+ "openTypeOS2TypoLineGap": dict(type=(int, float)),
2017
+ "openTypeOS2WinAscent": dict(type=(int, float)),
2018
+ "openTypeOS2WinDescent": dict(type=(int, float)),
2019
+ "openTypeOS2Type": dict(
2020
+ type="integerList",
2021
+ valueValidator=genericIntListValidator,
2022
+ valueOptions=fontInfoOpenTypeOS2TypeOptions,
2023
+ ),
2024
+ "openTypeOS2SubscriptXSize": dict(type=(int, float)),
2025
+ "openTypeOS2SubscriptYSize": dict(type=(int, float)),
2026
+ "openTypeOS2SubscriptXOffset": dict(type=(int, float)),
2027
+ "openTypeOS2SubscriptYOffset": dict(type=(int, float)),
2028
+ "openTypeOS2SuperscriptXSize": dict(type=(int, float)),
2029
+ "openTypeOS2SuperscriptYSize": dict(type=(int, float)),
2030
+ "openTypeOS2SuperscriptXOffset": dict(type=(int, float)),
2031
+ "openTypeOS2SuperscriptYOffset": dict(type=(int, float)),
2032
+ "openTypeOS2StrikeoutSize": dict(type=(int, float)),
2033
+ "openTypeOS2StrikeoutPosition": dict(type=(int, float)),
2034
+ "openTypeVheaVertTypoAscender": dict(type=(int, float)),
2035
+ "openTypeVheaVertTypoDescender": dict(type=(int, float)),
2036
+ "openTypeVheaVertTypoLineGap": dict(type=(int, float)),
2037
+ "openTypeVheaCaretSlopeRise": dict(type=int),
2038
+ "openTypeVheaCaretSlopeRun": dict(type=int),
2039
+ "openTypeVheaCaretOffset": dict(type=(int, float)),
2040
+ "postscriptFontName": dict(type=str),
2041
+ "postscriptFullName": dict(type=str),
2042
+ "postscriptSlantAngle": dict(type=(float, int)),
2043
+ "postscriptUniqueID": dict(type=int),
2044
+ "postscriptUnderlineThickness": dict(type=(int, float)),
2045
+ "postscriptUnderlinePosition": dict(type=(int, float)),
2046
+ "postscriptIsFixedPitch": dict(type=bool),
2047
+ "postscriptBlueValues": dict(
2048
+ type="integerList", valueValidator=fontInfoPostscriptBluesValidator
2049
+ ),
2050
+ "postscriptOtherBlues": dict(
2051
+ type="integerList", valueValidator=fontInfoPostscriptOtherBluesValidator
2052
+ ),
2053
+ "postscriptFamilyBlues": dict(
2054
+ type="integerList", valueValidator=fontInfoPostscriptBluesValidator
2055
+ ),
2056
+ "postscriptFamilyOtherBlues": dict(
2057
+ type="integerList", valueValidator=fontInfoPostscriptOtherBluesValidator
2058
+ ),
2059
+ "postscriptStemSnapH": dict(
2060
+ type="integerList", valueValidator=fontInfoPostscriptStemsValidator
2061
+ ),
2062
+ "postscriptStemSnapV": dict(
2063
+ type="integerList", valueValidator=fontInfoPostscriptStemsValidator
2064
+ ),
2065
+ "postscriptBlueFuzz": dict(type=(int, float)),
2066
+ "postscriptBlueShift": dict(type=(int, float)),
2067
+ "postscriptBlueScale": dict(type=(float, int)),
2068
+ "postscriptForceBold": dict(type=bool),
2069
+ "postscriptDefaultWidthX": dict(type=(int, float)),
2070
+ "postscriptNominalWidthX": dict(type=(int, float)),
2071
+ "postscriptWeightName": dict(type=str),
2072
+ "postscriptDefaultCharacter": dict(type=str),
2073
+ "postscriptWindowsCharacterSet": dict(
2074
+ type=int, valueValidator=fontInfoPostscriptWindowsCharacterSetValidator
2075
+ ),
2076
+ "macintoshFONDFamilyID": dict(type=int),
2077
+ "macintoshFONDName": dict(type=str),
2078
+ }
2079
+ fontInfoAttributesVersion2 = set(fontInfoAttributesVersion2ValueData.keys())
2080
+
2081
+ fontInfoAttributesVersion3ValueData = deepcopy(fontInfoAttributesVersion2ValueData)
2082
+ fontInfoAttributesVersion3ValueData.update(
2083
+ {
2084
+ "versionMinor": dict(type=int, valueValidator=genericNonNegativeIntValidator),
2085
+ "unitsPerEm": dict(
2086
+ type=(int, float), valueValidator=genericNonNegativeNumberValidator
2087
+ ),
2088
+ "openTypeHeadLowestRecPPEM": dict(
2089
+ type=int, valueValidator=genericNonNegativeNumberValidator
2090
+ ),
2091
+ "openTypeHheaAscender": dict(type=int),
2092
+ "openTypeHheaDescender": dict(type=int),
2093
+ "openTypeHheaLineGap": dict(type=int),
2094
+ "openTypeHheaCaretOffset": dict(type=int),
2095
+ "openTypeOS2Panose": dict(
2096
+ type="integerList",
2097
+ valueValidator=fontInfoVersion3OpenTypeOS2PanoseValidator,
2098
+ ),
2099
+ "openTypeOS2TypoAscender": dict(type=int),
2100
+ "openTypeOS2TypoDescender": dict(type=int),
2101
+ "openTypeOS2TypoLineGap": dict(type=int),
2102
+ "openTypeOS2WinAscent": dict(
2103
+ type=int, valueValidator=genericNonNegativeNumberValidator
2104
+ ),
2105
+ "openTypeOS2WinDescent": dict(
2106
+ type=int, valueValidator=genericNonNegativeNumberValidator
2107
+ ),
2108
+ "openTypeOS2SubscriptXSize": dict(type=int),
2109
+ "openTypeOS2SubscriptYSize": dict(type=int),
2110
+ "openTypeOS2SubscriptXOffset": dict(type=int),
2111
+ "openTypeOS2SubscriptYOffset": dict(type=int),
2112
+ "openTypeOS2SuperscriptXSize": dict(type=int),
2113
+ "openTypeOS2SuperscriptYSize": dict(type=int),
2114
+ "openTypeOS2SuperscriptXOffset": dict(type=int),
2115
+ "openTypeOS2SuperscriptYOffset": dict(type=int),
2116
+ "openTypeOS2StrikeoutSize": dict(type=int),
2117
+ "openTypeOS2StrikeoutPosition": dict(type=int),
2118
+ "openTypeGaspRangeRecords": dict(
2119
+ type="dictList", valueValidator=fontInfoOpenTypeGaspRangeRecordsValidator
2120
+ ),
2121
+ "openTypeNameRecords": dict(
2122
+ type="dictList", valueValidator=fontInfoOpenTypeNameRecordsValidator
2123
+ ),
2124
+ "openTypeVheaVertTypoAscender": dict(type=int),
2125
+ "openTypeVheaVertTypoDescender": dict(type=int),
2126
+ "openTypeVheaVertTypoLineGap": dict(type=int),
2127
+ "openTypeVheaCaretOffset": dict(type=int),
2128
+ "woffMajorVersion": dict(
2129
+ type=int, valueValidator=genericNonNegativeIntValidator
2130
+ ),
2131
+ "woffMinorVersion": dict(
2132
+ type=int, valueValidator=genericNonNegativeIntValidator
2133
+ ),
2134
+ "woffMetadataUniqueID": dict(
2135
+ type=dict, valueValidator=fontInfoWOFFMetadataUniqueIDValidator
2136
+ ),
2137
+ "woffMetadataVendor": dict(
2138
+ type=dict, valueValidator=fontInfoWOFFMetadataVendorValidator
2139
+ ),
2140
+ "woffMetadataCredits": dict(
2141
+ type=dict, valueValidator=fontInfoWOFFMetadataCreditsValidator
2142
+ ),
2143
+ "woffMetadataDescription": dict(
2144
+ type=dict, valueValidator=fontInfoWOFFMetadataDescriptionValidator
2145
+ ),
2146
+ "woffMetadataLicense": dict(
2147
+ type=dict, valueValidator=fontInfoWOFFMetadataLicenseValidator
2148
+ ),
2149
+ "woffMetadataCopyright": dict(
2150
+ type=dict, valueValidator=fontInfoWOFFMetadataCopyrightValidator
2151
+ ),
2152
+ "woffMetadataTrademark": dict(
2153
+ type=dict, valueValidator=fontInfoWOFFMetadataTrademarkValidator
2154
+ ),
2155
+ "woffMetadataLicensee": dict(
2156
+ type=dict, valueValidator=fontInfoWOFFMetadataLicenseeValidator
2157
+ ),
2158
+ "woffMetadataExtensions": dict(
2159
+ type=list, valueValidator=fontInfoWOFFMetadataExtensionsValidator
2160
+ ),
2161
+ "guidelines": dict(type=list, valueValidator=guidelinesValidator),
2162
+ }
2163
+ )
2164
+ fontInfoAttributesVersion3 = set(fontInfoAttributesVersion3ValueData.keys())
2165
+
2166
+ # insert the type validator for all attrs that
2167
+ # have no defined validator.
2168
+ for attr, dataDict in list(fontInfoAttributesVersion2ValueData.items()):
2169
+ if "valueValidator" not in dataDict:
2170
+ dataDict["valueValidator"] = genericTypeValidator
2171
+
2172
+ for attr, dataDict in list(fontInfoAttributesVersion3ValueData.items()):
2173
+ if "valueValidator" not in dataDict:
2174
+ dataDict["valueValidator"] = genericTypeValidator
2175
+
2176
+ # Version Conversion Support
2177
+ # These are used from converting from version 1
2178
+ # to version 2 or vice-versa.
2179
+
2180
+
2181
+ def _flipDict(d):
2182
+ flipped = {}
2183
+ for key, value in list(d.items()):
2184
+ flipped[value] = key
2185
+ return flipped
2186
+
2187
+
2188
+ fontInfoAttributesVersion1To2 = {
2189
+ "menuName": "styleMapFamilyName",
2190
+ "designer": "openTypeNameDesigner",
2191
+ "designerURL": "openTypeNameDesignerURL",
2192
+ "createdBy": "openTypeNameManufacturer",
2193
+ "vendorURL": "openTypeNameManufacturerURL",
2194
+ "license": "openTypeNameLicense",
2195
+ "licenseURL": "openTypeNameLicenseURL",
2196
+ "ttVersion": "openTypeNameVersion",
2197
+ "ttUniqueID": "openTypeNameUniqueID",
2198
+ "notice": "openTypeNameDescription",
2199
+ "otFamilyName": "openTypeNamePreferredFamilyName",
2200
+ "otStyleName": "openTypeNamePreferredSubfamilyName",
2201
+ "otMacName": "openTypeNameCompatibleFullName",
2202
+ "weightName": "postscriptWeightName",
2203
+ "weightValue": "openTypeOS2WeightClass",
2204
+ "ttVendor": "openTypeOS2VendorID",
2205
+ "uniqueID": "postscriptUniqueID",
2206
+ "fontName": "postscriptFontName",
2207
+ "fondID": "macintoshFONDFamilyID",
2208
+ "fondName": "macintoshFONDName",
2209
+ "defaultWidth": "postscriptDefaultWidthX",
2210
+ "slantAngle": "postscriptSlantAngle",
2211
+ "fullName": "postscriptFullName",
2212
+ # require special value conversion
2213
+ "fontStyle": "styleMapStyleName",
2214
+ "widthName": "openTypeOS2WidthClass",
2215
+ "msCharSet": "postscriptWindowsCharacterSet",
2216
+ }
2217
+ fontInfoAttributesVersion2To1 = _flipDict(fontInfoAttributesVersion1To2)
2218
+ deprecatedFontInfoAttributesVersion2 = set(fontInfoAttributesVersion1To2.keys())
2219
+
2220
+ _fontStyle1To2 = {64: "regular", 1: "italic", 32: "bold", 33: "bold italic"}
2221
+ _fontStyle2To1 = _flipDict(_fontStyle1To2)
2222
+ # Some UFO 1 files have 0
2223
+ _fontStyle1To2[0] = "regular"
2224
+
2225
+ _widthName1To2 = {
2226
+ "Ultra-condensed": 1,
2227
+ "Extra-condensed": 2,
2228
+ "Condensed": 3,
2229
+ "Semi-condensed": 4,
2230
+ "Medium (normal)": 5,
2231
+ "Semi-expanded": 6,
2232
+ "Expanded": 7,
2233
+ "Extra-expanded": 8,
2234
+ "Ultra-expanded": 9,
2235
+ }
2236
+ _widthName2To1 = _flipDict(_widthName1To2)
2237
+ # FontLab's default width value is "Normal".
2238
+ # Many format version 1 UFOs will have this.
2239
+ _widthName1To2["Normal"] = 5
2240
+ # FontLab has an "All" width value. In UFO 1
2241
+ # move this up to "Normal".
2242
+ _widthName1To2["All"] = 5
2243
+ # "medium" appears in a lot of UFO 1 files.
2244
+ _widthName1To2["medium"] = 5
2245
+ # "Medium" appears in a lot of UFO 1 files.
2246
+ _widthName1To2["Medium"] = 5
2247
+
2248
+ _msCharSet1To2 = {
2249
+ 0: 1,
2250
+ 1: 2,
2251
+ 2: 3,
2252
+ 77: 4,
2253
+ 128: 5,
2254
+ 129: 6,
2255
+ 130: 7,
2256
+ 134: 8,
2257
+ 136: 9,
2258
+ 161: 10,
2259
+ 162: 11,
2260
+ 163: 12,
2261
+ 177: 13,
2262
+ 178: 14,
2263
+ 186: 15,
2264
+ 200: 16,
2265
+ 204: 17,
2266
+ 222: 18,
2267
+ 238: 19,
2268
+ 255: 20,
2269
+ }
2270
+ _msCharSet2To1 = _flipDict(_msCharSet1To2)
2271
+
2272
+ # 1 <-> 2
2273
+
2274
+
2275
+ def convertFontInfoValueForAttributeFromVersion1ToVersion2(attr, value):
2276
+ """
2277
+ Convert value from version 1 to version 2 format.
2278
+ Returns the new attribute name and the converted value.
2279
+ If the value is None, None will be returned for the new value.
2280
+ """
2281
+ # convert floats to ints if possible
2282
+ if isinstance(value, float):
2283
+ if int(value) == value:
2284
+ value = int(value)
2285
+ if value is not None:
2286
+ if attr == "fontStyle":
2287
+ v = _fontStyle1To2.get(value)
2288
+ if v is None:
2289
+ raise UFOLibError(
2290
+ f"Cannot convert value ({value!r}) for attribute {attr}."
2291
+ )
2292
+ value = v
2293
+ elif attr == "widthName":
2294
+ v = _widthName1To2.get(value)
2295
+ if v is None:
2296
+ raise UFOLibError(
2297
+ f"Cannot convert value ({value!r}) for attribute {attr}."
2298
+ )
2299
+ value = v
2300
+ elif attr == "msCharSet":
2301
+ v = _msCharSet1To2.get(value)
2302
+ if v is None:
2303
+ raise UFOLibError(
2304
+ f"Cannot convert value ({value!r}) for attribute {attr}."
2305
+ )
2306
+ value = v
2307
+ attr = fontInfoAttributesVersion1To2.get(attr, attr)
2308
+ return attr, value
2309
+
2310
+
2311
+ def convertFontInfoValueForAttributeFromVersion2ToVersion1(attr, value):
2312
+ """
2313
+ Convert value from version 2 to version 1 format.
2314
+ Returns the new attribute name and the converted value.
2315
+ If the value is None, None will be returned for the new value.
2316
+ """
2317
+ if value is not None:
2318
+ if attr == "styleMapStyleName":
2319
+ value = _fontStyle2To1.get(value)
2320
+ elif attr == "openTypeOS2WidthClass":
2321
+ value = _widthName2To1.get(value)
2322
+ elif attr == "postscriptWindowsCharacterSet":
2323
+ value = _msCharSet2To1.get(value)
2324
+ attr = fontInfoAttributesVersion2To1.get(attr, attr)
2325
+ return attr, value
2326
+
2327
+
2328
+ def _convertFontInfoDataVersion1ToVersion2(data):
2329
+ converted = {}
2330
+ for attr, value in list(data.items()):
2331
+ # FontLab gives -1 for the weightValue
2332
+ # for fonts wil no defined value. Many
2333
+ # format version 1 UFOs will have this.
2334
+ if attr == "weightValue" and value == -1:
2335
+ continue
2336
+ newAttr, newValue = convertFontInfoValueForAttributeFromVersion1ToVersion2(
2337
+ attr, value
2338
+ )
2339
+ # skip if the attribute is not part of version 2
2340
+ if newAttr not in fontInfoAttributesVersion2:
2341
+ continue
2342
+ # catch values that can't be converted
2343
+ if value is None:
2344
+ raise UFOLibError(
2345
+ f"Cannot convert value ({value!r}) for attribute {newAttr}."
2346
+ )
2347
+ # store
2348
+ converted[newAttr] = newValue
2349
+ return converted
2350
+
2351
+
2352
+ def _convertFontInfoDataVersion2ToVersion1(data):
2353
+ converted = {}
2354
+ for attr, value in list(data.items()):
2355
+ newAttr, newValue = convertFontInfoValueForAttributeFromVersion2ToVersion1(
2356
+ attr, value
2357
+ )
2358
+ # only take attributes that are registered for version 1
2359
+ if newAttr not in fontInfoAttributesVersion1:
2360
+ continue
2361
+ # catch values that can't be converted
2362
+ if value is None:
2363
+ raise UFOLibError(
2364
+ f"Cannot convert value ({value!r}) for attribute {newAttr}."
2365
+ )
2366
+ # store
2367
+ converted[newAttr] = newValue
2368
+ return converted
2369
+
2370
+
2371
+ # 2 <-> 3
2372
+
2373
+ _ufo2To3NonNegativeInt = {
2374
+ "versionMinor",
2375
+ "openTypeHeadLowestRecPPEM",
2376
+ "openTypeOS2WinAscent",
2377
+ "openTypeOS2WinDescent",
2378
+ }
2379
+ _ufo2To3NonNegativeIntOrFloat = {
2380
+ "unitsPerEm",
2381
+ }
2382
+ _ufo2To3FloatToInt = {
2383
+ "openTypeHeadLowestRecPPEM",
2384
+ "openTypeHheaAscender",
2385
+ "openTypeHheaDescender",
2386
+ "openTypeHheaLineGap",
2387
+ "openTypeHheaCaretOffset",
2388
+ "openTypeOS2TypoAscender",
2389
+ "openTypeOS2TypoDescender",
2390
+ "openTypeOS2TypoLineGap",
2391
+ "openTypeOS2WinAscent",
2392
+ "openTypeOS2WinDescent",
2393
+ "openTypeOS2SubscriptXSize",
2394
+ "openTypeOS2SubscriptYSize",
2395
+ "openTypeOS2SubscriptXOffset",
2396
+ "openTypeOS2SubscriptYOffset",
2397
+ "openTypeOS2SuperscriptXSize",
2398
+ "openTypeOS2SuperscriptYSize",
2399
+ "openTypeOS2SuperscriptXOffset",
2400
+ "openTypeOS2SuperscriptYOffset",
2401
+ "openTypeOS2StrikeoutSize",
2402
+ "openTypeOS2StrikeoutPosition",
2403
+ "openTypeVheaVertTypoAscender",
2404
+ "openTypeVheaVertTypoDescender",
2405
+ "openTypeVheaVertTypoLineGap",
2406
+ "openTypeVheaCaretOffset",
2407
+ }
2408
+
2409
+
2410
+ def convertFontInfoValueForAttributeFromVersion2ToVersion3(attr, value):
2411
+ """
2412
+ Convert value from version 2 to version 3 format.
2413
+ Returns the new attribute name and the converted value.
2414
+ If the value is None, None will be returned for the new value.
2415
+ """
2416
+ if attr in _ufo2To3FloatToInt:
2417
+ try:
2418
+ value = round(value)
2419
+ except (ValueError, TypeError):
2420
+ raise UFOLibError("Could not convert value for %s." % attr)
2421
+ if attr in _ufo2To3NonNegativeInt:
2422
+ try:
2423
+ value = int(abs(value))
2424
+ except (ValueError, TypeError):
2425
+ raise UFOLibError("Could not convert value for %s." % attr)
2426
+ elif attr in _ufo2To3NonNegativeIntOrFloat:
2427
+ try:
2428
+ v = float(abs(value))
2429
+ except (ValueError, TypeError):
2430
+ raise UFOLibError("Could not convert value for %s." % attr)
2431
+ if v == int(v):
2432
+ v = int(v)
2433
+ if v != value:
2434
+ value = v
2435
+ return attr, value
2436
+
2437
+
2438
+ def convertFontInfoValueForAttributeFromVersion3ToVersion2(attr, value):
2439
+ """
2440
+ Convert value from version 3 to version 2 format.
2441
+ Returns the new attribute name and the converted value.
2442
+ If the value is None, None will be returned for the new value.
2443
+ """
2444
+ return attr, value
2445
+
2446
+
2447
+ def _convertFontInfoDataVersion3ToVersion2(data):
2448
+ converted = {}
2449
+ for attr, value in list(data.items()):
2450
+ newAttr, newValue = convertFontInfoValueForAttributeFromVersion3ToVersion2(
2451
+ attr, value
2452
+ )
2453
+ if newAttr not in fontInfoAttributesVersion2:
2454
+ continue
2455
+ converted[newAttr] = newValue
2456
+ return converted
2457
+
2458
+
2459
+ def _convertFontInfoDataVersion2ToVersion3(data):
2460
+ converted = {}
2461
+ for attr, value in list(data.items()):
2462
+ attr, value = convertFontInfoValueForAttributeFromVersion2ToVersion3(
2463
+ attr, value
2464
+ )
2465
+ converted[attr] = value
2466
+ return converted
2467
+
2468
+
2469
+ if __name__ == "__main__":
2470
+ import doctest
2471
+
2472
+ doctest.testmod()