fonttools 4.55.6__cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

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

Potentially problematic release.


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

Files changed (329) hide show
  1. fontTools/__init__.py +8 -0
  2. fontTools/__main__.py +35 -0
  3. fontTools/afmLib.py +439 -0
  4. fontTools/agl.py +5233 -0
  5. fontTools/cffLib/CFF2ToCFF.py +203 -0
  6. fontTools/cffLib/CFFToCFF2.py +305 -0
  7. fontTools/cffLib/__init__.py +3659 -0
  8. fontTools/cffLib/specializer.py +924 -0
  9. fontTools/cffLib/transforms.py +490 -0
  10. fontTools/cffLib/width.py +210 -0
  11. fontTools/colorLib/__init__.py +0 -0
  12. fontTools/colorLib/builder.py +664 -0
  13. fontTools/colorLib/errors.py +2 -0
  14. fontTools/colorLib/geometry.py +143 -0
  15. fontTools/colorLib/table_builder.py +223 -0
  16. fontTools/colorLib/unbuilder.py +81 -0
  17. fontTools/config/__init__.py +75 -0
  18. fontTools/cu2qu/__init__.py +15 -0
  19. fontTools/cu2qu/__main__.py +6 -0
  20. fontTools/cu2qu/benchmark.py +54 -0
  21. fontTools/cu2qu/cli.py +198 -0
  22. fontTools/cu2qu/cu2qu.c +14829 -0
  23. fontTools/cu2qu/cu2qu.cpython-39-x86_64-linux-gnu.so +0 -0
  24. fontTools/cu2qu/cu2qu.py +531 -0
  25. fontTools/cu2qu/errors.py +77 -0
  26. fontTools/cu2qu/ufo.py +349 -0
  27. fontTools/designspaceLib/__init__.py +3338 -0
  28. fontTools/designspaceLib/__main__.py +6 -0
  29. fontTools/designspaceLib/split.py +475 -0
  30. fontTools/designspaceLib/statNames.py +253 -0
  31. fontTools/designspaceLib/types.py +147 -0
  32. fontTools/encodings/MacRoman.py +258 -0
  33. fontTools/encodings/StandardEncoding.py +258 -0
  34. fontTools/encodings/__init__.py +1 -0
  35. fontTools/encodings/codecs.py +135 -0
  36. fontTools/feaLib/__init__.py +4 -0
  37. fontTools/feaLib/__main__.py +78 -0
  38. fontTools/feaLib/ast.py +2134 -0
  39. fontTools/feaLib/builder.py +1747 -0
  40. fontTools/feaLib/error.py +22 -0
  41. fontTools/feaLib/lexer.c +17986 -0
  42. fontTools/feaLib/lexer.cpython-39-x86_64-linux-gnu.so +0 -0
  43. fontTools/feaLib/lexer.py +287 -0
  44. fontTools/feaLib/location.py +12 -0
  45. fontTools/feaLib/lookupDebugInfo.py +12 -0
  46. fontTools/feaLib/parser.py +2359 -0
  47. fontTools/feaLib/variableScalar.py +113 -0
  48. fontTools/fontBuilder.py +1008 -0
  49. fontTools/help.py +36 -0
  50. fontTools/merge/__init__.py +248 -0
  51. fontTools/merge/__main__.py +6 -0
  52. fontTools/merge/base.py +81 -0
  53. fontTools/merge/cmap.py +141 -0
  54. fontTools/merge/layout.py +526 -0
  55. fontTools/merge/options.py +85 -0
  56. fontTools/merge/tables.py +341 -0
  57. fontTools/merge/unicode.py +78 -0
  58. fontTools/merge/util.py +143 -0
  59. fontTools/misc/__init__.py +1 -0
  60. fontTools/misc/arrayTools.py +424 -0
  61. fontTools/misc/bezierTools.c +41831 -0
  62. fontTools/misc/bezierTools.cpython-39-x86_64-linux-gnu.so +0 -0
  63. fontTools/misc/bezierTools.py +1497 -0
  64. fontTools/misc/classifyTools.py +170 -0
  65. fontTools/misc/cliTools.py +53 -0
  66. fontTools/misc/configTools.py +349 -0
  67. fontTools/misc/cython.py +27 -0
  68. fontTools/misc/dictTools.py +83 -0
  69. fontTools/misc/eexec.py +119 -0
  70. fontTools/misc/encodingTools.py +72 -0
  71. fontTools/misc/etree.py +479 -0
  72. fontTools/misc/filenames.py +245 -0
  73. fontTools/misc/fixedTools.py +253 -0
  74. fontTools/misc/intTools.py +25 -0
  75. fontTools/misc/iterTools.py +12 -0
  76. fontTools/misc/lazyTools.py +42 -0
  77. fontTools/misc/loggingTools.py +543 -0
  78. fontTools/misc/macCreatorType.py +56 -0
  79. fontTools/misc/macRes.py +261 -0
  80. fontTools/misc/plistlib/__init__.py +681 -0
  81. fontTools/misc/plistlib/py.typed +0 -0
  82. fontTools/misc/psCharStrings.py +1496 -0
  83. fontTools/misc/psLib.py +398 -0
  84. fontTools/misc/psOperators.py +572 -0
  85. fontTools/misc/py23.py +96 -0
  86. fontTools/misc/roundTools.py +110 -0
  87. fontTools/misc/sstruct.py +231 -0
  88. fontTools/misc/symfont.py +244 -0
  89. fontTools/misc/testTools.py +229 -0
  90. fontTools/misc/textTools.py +154 -0
  91. fontTools/misc/timeTools.py +88 -0
  92. fontTools/misc/transform.py +516 -0
  93. fontTools/misc/treeTools.py +45 -0
  94. fontTools/misc/vector.py +147 -0
  95. fontTools/misc/visitor.py +142 -0
  96. fontTools/misc/xmlReader.py +188 -0
  97. fontTools/misc/xmlWriter.py +204 -0
  98. fontTools/mtiLib/__init__.py +1402 -0
  99. fontTools/mtiLib/__main__.py +5 -0
  100. fontTools/otlLib/__init__.py +1 -0
  101. fontTools/otlLib/builder.py +3221 -0
  102. fontTools/otlLib/error.py +11 -0
  103. fontTools/otlLib/maxContextCalc.py +96 -0
  104. fontTools/otlLib/optimize/__init__.py +53 -0
  105. fontTools/otlLib/optimize/__main__.py +6 -0
  106. fontTools/otlLib/optimize/gpos.py +453 -0
  107. fontTools/pens/__init__.py +1 -0
  108. fontTools/pens/areaPen.py +52 -0
  109. fontTools/pens/basePen.py +475 -0
  110. fontTools/pens/boundsPen.py +98 -0
  111. fontTools/pens/cairoPen.py +26 -0
  112. fontTools/pens/cocoaPen.py +26 -0
  113. fontTools/pens/cu2quPen.py +325 -0
  114. fontTools/pens/explicitClosingLinePen.py +101 -0
  115. fontTools/pens/filterPen.py +241 -0
  116. fontTools/pens/freetypePen.py +462 -0
  117. fontTools/pens/hashPointPen.py +89 -0
  118. fontTools/pens/momentsPen.c +13448 -0
  119. fontTools/pens/momentsPen.cpython-39-x86_64-linux-gnu.so +0 -0
  120. fontTools/pens/momentsPen.py +879 -0
  121. fontTools/pens/perimeterPen.py +69 -0
  122. fontTools/pens/pointInsidePen.py +192 -0
  123. fontTools/pens/pointPen.py +600 -0
  124. fontTools/pens/qtPen.py +29 -0
  125. fontTools/pens/qu2cuPen.py +105 -0
  126. fontTools/pens/quartzPen.py +43 -0
  127. fontTools/pens/recordingPen.py +335 -0
  128. fontTools/pens/reportLabPen.py +79 -0
  129. fontTools/pens/reverseContourPen.py +96 -0
  130. fontTools/pens/roundingPen.py +130 -0
  131. fontTools/pens/statisticsPen.py +312 -0
  132. fontTools/pens/svgPathPen.py +310 -0
  133. fontTools/pens/t2CharStringPen.py +68 -0
  134. fontTools/pens/teePen.py +55 -0
  135. fontTools/pens/transformPen.py +115 -0
  136. fontTools/pens/ttGlyphPen.py +335 -0
  137. fontTools/pens/wxPen.py +29 -0
  138. fontTools/qu2cu/__init__.py +15 -0
  139. fontTools/qu2cu/__main__.py +7 -0
  140. fontTools/qu2cu/benchmark.py +56 -0
  141. fontTools/qu2cu/cli.py +125 -0
  142. fontTools/qu2cu/qu2cu.c +16269 -0
  143. fontTools/qu2cu/qu2cu.cpython-39-x86_64-linux-gnu.so +0 -0
  144. fontTools/qu2cu/qu2cu.py +405 -0
  145. fontTools/subset/__init__.py +3838 -0
  146. fontTools/subset/__main__.py +6 -0
  147. fontTools/subset/cff.py +184 -0
  148. fontTools/subset/svg.py +253 -0
  149. fontTools/subset/util.py +25 -0
  150. fontTools/svgLib/__init__.py +3 -0
  151. fontTools/svgLib/path/__init__.py +65 -0
  152. fontTools/svgLib/path/arc.py +154 -0
  153. fontTools/svgLib/path/parser.py +322 -0
  154. fontTools/svgLib/path/shapes.py +183 -0
  155. fontTools/t1Lib/__init__.py +648 -0
  156. fontTools/tfmLib.py +460 -0
  157. fontTools/ttLib/__init__.py +26 -0
  158. fontTools/ttLib/__main__.py +109 -0
  159. fontTools/ttLib/macUtils.py +54 -0
  160. fontTools/ttLib/removeOverlaps.py +393 -0
  161. fontTools/ttLib/reorderGlyphs.py +284 -0
  162. fontTools/ttLib/scaleUpem.py +436 -0
  163. fontTools/ttLib/sfnt.py +662 -0
  164. fontTools/ttLib/standardGlyphOrder.py +271 -0
  165. fontTools/ttLib/tables/B_A_S_E_.py +14 -0
  166. fontTools/ttLib/tables/BitmapGlyphMetrics.py +64 -0
  167. fontTools/ttLib/tables/C_B_D_T_.py +113 -0
  168. fontTools/ttLib/tables/C_B_L_C_.py +19 -0
  169. fontTools/ttLib/tables/C_F_F_.py +61 -0
  170. fontTools/ttLib/tables/C_F_F__2.py +26 -0
  171. fontTools/ttLib/tables/C_O_L_R_.py +165 -0
  172. fontTools/ttLib/tables/C_P_A_L_.py +305 -0
  173. fontTools/ttLib/tables/D_S_I_G_.py +158 -0
  174. fontTools/ttLib/tables/D__e_b_g.py +17 -0
  175. fontTools/ttLib/tables/DefaultTable.py +49 -0
  176. fontTools/ttLib/tables/E_B_D_T_.py +835 -0
  177. fontTools/ttLib/tables/E_B_L_C_.py +718 -0
  178. fontTools/ttLib/tables/F_F_T_M_.py +52 -0
  179. fontTools/ttLib/tables/F__e_a_t.py +149 -0
  180. fontTools/ttLib/tables/G_D_E_F_.py +13 -0
  181. fontTools/ttLib/tables/G_M_A_P_.py +148 -0
  182. fontTools/ttLib/tables/G_P_K_G_.py +133 -0
  183. fontTools/ttLib/tables/G_P_O_S_.py +14 -0
  184. fontTools/ttLib/tables/G_S_U_B_.py +13 -0
  185. fontTools/ttLib/tables/G__l_a_t.py +235 -0
  186. fontTools/ttLib/tables/G__l_o_c.py +85 -0
  187. fontTools/ttLib/tables/H_V_A_R_.py +13 -0
  188. fontTools/ttLib/tables/J_S_T_F_.py +13 -0
  189. fontTools/ttLib/tables/L_T_S_H_.py +58 -0
  190. fontTools/ttLib/tables/M_A_T_H_.py +13 -0
  191. fontTools/ttLib/tables/M_E_T_A_.py +352 -0
  192. fontTools/ttLib/tables/M_V_A_R_.py +13 -0
  193. fontTools/ttLib/tables/O_S_2f_2.py +752 -0
  194. fontTools/ttLib/tables/S_I_N_G_.py +99 -0
  195. fontTools/ttLib/tables/S_T_A_T_.py +15 -0
  196. fontTools/ttLib/tables/S_V_G_.py +223 -0
  197. fontTools/ttLib/tables/S__i_l_f.py +1040 -0
  198. fontTools/ttLib/tables/S__i_l_l.py +92 -0
  199. fontTools/ttLib/tables/T_S_I_B_.py +13 -0
  200. fontTools/ttLib/tables/T_S_I_C_.py +14 -0
  201. fontTools/ttLib/tables/T_S_I_D_.py +13 -0
  202. fontTools/ttLib/tables/T_S_I_J_.py +13 -0
  203. fontTools/ttLib/tables/T_S_I_P_.py +13 -0
  204. fontTools/ttLib/tables/T_S_I_S_.py +13 -0
  205. fontTools/ttLib/tables/T_S_I_V_.py +26 -0
  206. fontTools/ttLib/tables/T_S_I__0.py +59 -0
  207. fontTools/ttLib/tables/T_S_I__1.py +166 -0
  208. fontTools/ttLib/tables/T_S_I__2.py +17 -0
  209. fontTools/ttLib/tables/T_S_I__3.py +22 -0
  210. fontTools/ttLib/tables/T_S_I__5.py +49 -0
  211. fontTools/ttLib/tables/T_T_F_A_.py +14 -0
  212. fontTools/ttLib/tables/TupleVariation.py +884 -0
  213. fontTools/ttLib/tables/V_A_R_C_.py +12 -0
  214. fontTools/ttLib/tables/V_D_M_X_.py +249 -0
  215. fontTools/ttLib/tables/V_O_R_G_.py +165 -0
  216. fontTools/ttLib/tables/V_V_A_R_.py +13 -0
  217. fontTools/ttLib/tables/__init__.py +97 -0
  218. fontTools/ttLib/tables/_a_n_k_r.py +15 -0
  219. fontTools/ttLib/tables/_a_v_a_r.py +191 -0
  220. fontTools/ttLib/tables/_b_s_l_n.py +15 -0
  221. fontTools/ttLib/tables/_c_i_d_g.py +24 -0
  222. fontTools/ttLib/tables/_c_m_a_p.py +1578 -0
  223. fontTools/ttLib/tables/_c_v_a_r.py +94 -0
  224. fontTools/ttLib/tables/_c_v_t.py +55 -0
  225. fontTools/ttLib/tables/_f_e_a_t.py +15 -0
  226. fontTools/ttLib/tables/_f_p_g_m.py +60 -0
  227. fontTools/ttLib/tables/_f_v_a_r.py +261 -0
  228. fontTools/ttLib/tables/_g_a_s_p.py +63 -0
  229. fontTools/ttLib/tables/_g_c_i_d.py +13 -0
  230. fontTools/ttLib/tables/_g_l_y_f.py +2311 -0
  231. fontTools/ttLib/tables/_g_v_a_r.py +292 -0
  232. fontTools/ttLib/tables/_h_d_m_x.py +127 -0
  233. fontTools/ttLib/tables/_h_e_a_d.py +130 -0
  234. fontTools/ttLib/tables/_h_h_e_a.py +147 -0
  235. fontTools/ttLib/tables/_h_m_t_x.py +160 -0
  236. fontTools/ttLib/tables/_k_e_r_n.py +289 -0
  237. fontTools/ttLib/tables/_l_c_a_r.py +13 -0
  238. fontTools/ttLib/tables/_l_o_c_a.py +70 -0
  239. fontTools/ttLib/tables/_l_t_a_g.py +72 -0
  240. fontTools/ttLib/tables/_m_a_x_p.py +147 -0
  241. fontTools/ttLib/tables/_m_e_t_a.py +112 -0
  242. fontTools/ttLib/tables/_m_o_r_t.py +14 -0
  243. fontTools/ttLib/tables/_m_o_r_x.py +15 -0
  244. fontTools/ttLib/tables/_n_a_m_e.py +1237 -0
  245. fontTools/ttLib/tables/_o_p_b_d.py +14 -0
  246. fontTools/ttLib/tables/_p_o_s_t.py +317 -0
  247. fontTools/ttLib/tables/_p_r_e_p.py +16 -0
  248. fontTools/ttLib/tables/_p_r_o_p.py +12 -0
  249. fontTools/ttLib/tables/_s_b_i_x.py +129 -0
  250. fontTools/ttLib/tables/_t_r_a_k.py +332 -0
  251. fontTools/ttLib/tables/_v_h_e_a.py +139 -0
  252. fontTools/ttLib/tables/_v_m_t_x.py +19 -0
  253. fontTools/ttLib/tables/asciiTable.py +20 -0
  254. fontTools/ttLib/tables/grUtils.py +92 -0
  255. fontTools/ttLib/tables/otBase.py +1465 -0
  256. fontTools/ttLib/tables/otConverters.py +2065 -0
  257. fontTools/ttLib/tables/otData.py +6400 -0
  258. fontTools/ttLib/tables/otTables.py +2700 -0
  259. fontTools/ttLib/tables/otTraverse.py +162 -0
  260. fontTools/ttLib/tables/sbixGlyph.py +149 -0
  261. fontTools/ttLib/tables/sbixStrike.py +177 -0
  262. fontTools/ttLib/tables/table_API_readme.txt +91 -0
  263. fontTools/ttLib/tables/ttProgram.py +594 -0
  264. fontTools/ttLib/ttCollection.py +125 -0
  265. fontTools/ttLib/ttFont.py +1155 -0
  266. fontTools/ttLib/ttGlyphSet.py +500 -0
  267. fontTools/ttLib/ttVisitor.py +32 -0
  268. fontTools/ttLib/woff2.py +1683 -0
  269. fontTools/ttx.py +467 -0
  270. fontTools/ufoLib/__init__.py +2477 -0
  271. fontTools/ufoLib/converters.py +334 -0
  272. fontTools/ufoLib/errors.py +22 -0
  273. fontTools/ufoLib/etree.py +6 -0
  274. fontTools/ufoLib/filenames.py +291 -0
  275. fontTools/ufoLib/glifLib.py +2022 -0
  276. fontTools/ufoLib/kerning.py +91 -0
  277. fontTools/ufoLib/plistlib.py +47 -0
  278. fontTools/ufoLib/pointPen.py +6 -0
  279. fontTools/ufoLib/utils.py +76 -0
  280. fontTools/ufoLib/validators.py +1186 -0
  281. fontTools/unicode.py +50 -0
  282. fontTools/unicodedata/Blocks.py +802 -0
  283. fontTools/unicodedata/OTTags.py +50 -0
  284. fontTools/unicodedata/ScriptExtensions.py +806 -0
  285. fontTools/unicodedata/Scripts.py +3618 -0
  286. fontTools/unicodedata/__init__.py +298 -0
  287. fontTools/varLib/__init__.py +1511 -0
  288. fontTools/varLib/__main__.py +6 -0
  289. fontTools/varLib/avar.py +260 -0
  290. fontTools/varLib/avarPlanner.py +1004 -0
  291. fontTools/varLib/builder.py +215 -0
  292. fontTools/varLib/cff.py +631 -0
  293. fontTools/varLib/errors.py +219 -0
  294. fontTools/varLib/featureVars.py +689 -0
  295. fontTools/varLib/instancer/__init__.py +1937 -0
  296. fontTools/varLib/instancer/__main__.py +5 -0
  297. fontTools/varLib/instancer/featureVars.py +190 -0
  298. fontTools/varLib/instancer/names.py +388 -0
  299. fontTools/varLib/instancer/solver.py +309 -0
  300. fontTools/varLib/interpolatable.py +1209 -0
  301. fontTools/varLib/interpolatableHelpers.py +396 -0
  302. fontTools/varLib/interpolatablePlot.py +1269 -0
  303. fontTools/varLib/interpolatableTestContourOrder.py +82 -0
  304. fontTools/varLib/interpolatableTestStartingPoint.py +107 -0
  305. fontTools/varLib/interpolate_layout.py +124 -0
  306. fontTools/varLib/iup.c +19154 -0
  307. fontTools/varLib/iup.cpython-39-x86_64-linux-gnu.so +0 -0
  308. fontTools/varLib/iup.py +490 -0
  309. fontTools/varLib/merger.py +1717 -0
  310. fontTools/varLib/models.py +642 -0
  311. fontTools/varLib/multiVarStore.py +253 -0
  312. fontTools/varLib/mutator.py +518 -0
  313. fontTools/varLib/mvar.py +40 -0
  314. fontTools/varLib/plot.py +238 -0
  315. fontTools/varLib/stat.py +149 -0
  316. fontTools/varLib/varStore.py +767 -0
  317. fontTools/voltLib/__init__.py +5 -0
  318. fontTools/voltLib/ast.py +448 -0
  319. fontTools/voltLib/error.py +12 -0
  320. fontTools/voltLib/lexer.py +99 -0
  321. fontTools/voltLib/parser.py +656 -0
  322. fontTools/voltLib/voltToFea.py +730 -0
  323. fonttools-4.55.6.data/data/share/man/man1/ttx.1 +225 -0
  324. fonttools-4.55.6.dist-info/LICENSE +21 -0
  325. fonttools-4.55.6.dist-info/METADATA +3413 -0
  326. fonttools-4.55.6.dist-info/RECORD +329 -0
  327. fonttools-4.55.6.dist-info/WHEEL +6 -0
  328. fonttools-4.55.6.dist-info/entry_points.txt +5 -0
  329. fonttools-4.55.6.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2022 @@
1
+ """
2
+ glifLib.py -- Generic module for reading and writing the .glif format.
3
+
4
+ More info about the .glif format (GLyphInterchangeFormat) can be found here:
5
+
6
+ http://unifiedfontobject.org
7
+
8
+ The main class in this module is GlyphSet. It manages a set of .glif files
9
+ in a folder. It offers two ways to read glyph data, and one way to write
10
+ glyph data. See the class doc string for details.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ import enum
17
+ from warnings import warn
18
+ from collections import OrderedDict
19
+ import fs
20
+ import fs.base
21
+ import fs.errors
22
+ import fs.osfs
23
+ import fs.path
24
+ from fontTools.misc.textTools import tobytes
25
+ from fontTools.misc import plistlib
26
+ from fontTools.pens.pointPen import AbstractPointPen, PointToSegmentPen
27
+ from fontTools.ufoLib.errors import GlifLibError
28
+ from fontTools.ufoLib.filenames import userNameToFileName
29
+ from fontTools.ufoLib.validators import (
30
+ genericTypeValidator,
31
+ colorValidator,
32
+ guidelinesValidator,
33
+ anchorsValidator,
34
+ identifierValidator,
35
+ imageValidator,
36
+ glyphLibValidator,
37
+ )
38
+ from fontTools.misc import etree
39
+ from fontTools.ufoLib import _UFOBaseIO, UFOFormatVersion
40
+ from fontTools.ufoLib.utils import numberTypes, _VersionTupleEnumMixin
41
+
42
+
43
+ __all__ = [
44
+ "GlyphSet",
45
+ "GlifLibError",
46
+ "readGlyphFromString",
47
+ "writeGlyphToString",
48
+ "glyphNameToFileName",
49
+ ]
50
+
51
+ logger = logging.getLogger(__name__)
52
+
53
+
54
+ # ---------
55
+ # Constants
56
+ # ---------
57
+
58
+ CONTENTS_FILENAME = "contents.plist"
59
+ LAYERINFO_FILENAME = "layerinfo.plist"
60
+
61
+
62
+ class GLIFFormatVersion(tuple, _VersionTupleEnumMixin, enum.Enum):
63
+ FORMAT_1_0 = (1, 0)
64
+ FORMAT_2_0 = (2, 0)
65
+
66
+ @classmethod
67
+ def default(cls, ufoFormatVersion=None):
68
+ if ufoFormatVersion is not None:
69
+ return max(cls.supported_versions(ufoFormatVersion))
70
+ return super().default()
71
+
72
+ @classmethod
73
+ def supported_versions(cls, ufoFormatVersion=None):
74
+ if ufoFormatVersion is None:
75
+ # if ufo format unspecified, return all the supported GLIF formats
76
+ return super().supported_versions()
77
+ # else only return the GLIF formats supported by the given UFO format
78
+ versions = {cls.FORMAT_1_0}
79
+ if ufoFormatVersion >= UFOFormatVersion.FORMAT_3_0:
80
+ versions.add(cls.FORMAT_2_0)
81
+ return frozenset(versions)
82
+
83
+
84
+ # workaround for py3.11, see https://github.com/fonttools/fonttools/pull/2655
85
+ GLIFFormatVersion.__str__ = _VersionTupleEnumMixin.__str__
86
+
87
+
88
+ # ------------
89
+ # Simple Glyph
90
+ # ------------
91
+
92
+
93
+ class Glyph:
94
+ """
95
+ Minimal glyph object. It has no glyph attributes until either
96
+ the draw() or the drawPoints() method has been called.
97
+ """
98
+
99
+ def __init__(self, glyphName, glyphSet):
100
+ self.glyphName = glyphName
101
+ self.glyphSet = glyphSet
102
+
103
+ def draw(self, pen, outputImpliedClosingLine=False):
104
+ """
105
+ Draw this glyph onto a *FontTools* Pen.
106
+ """
107
+ pointPen = PointToSegmentPen(
108
+ pen, outputImpliedClosingLine=outputImpliedClosingLine
109
+ )
110
+ self.drawPoints(pointPen)
111
+
112
+ def drawPoints(self, pointPen):
113
+ """
114
+ Draw this glyph onto a PointPen.
115
+ """
116
+ self.glyphSet.readGlyph(self.glyphName, self, pointPen)
117
+
118
+
119
+ # ---------
120
+ # Glyph Set
121
+ # ---------
122
+
123
+
124
+ class GlyphSet(_UFOBaseIO):
125
+ """
126
+ GlyphSet manages a set of .glif files inside one directory.
127
+
128
+ GlyphSet's constructor takes a path to an existing directory as it's
129
+ first argument. Reading glyph data can either be done through the
130
+ readGlyph() method, or by using GlyphSet's dictionary interface, where
131
+ the keys are glyph names and the values are (very) simple glyph objects.
132
+
133
+ To write a glyph to the glyph set, you use the writeGlyph() method.
134
+ The simple glyph objects returned through the dict interface do not
135
+ support writing, they are just a convenient way to get at the glyph data.
136
+ """
137
+
138
+ glyphClass = Glyph
139
+
140
+ def __init__(
141
+ self,
142
+ path,
143
+ glyphNameToFileNameFunc=None,
144
+ ufoFormatVersion=None,
145
+ validateRead=True,
146
+ validateWrite=True,
147
+ expectContentsFile=False,
148
+ ):
149
+ """
150
+ 'path' should be a path (string) to an existing local directory, or
151
+ an instance of fs.base.FS class.
152
+
153
+ The optional 'glyphNameToFileNameFunc' argument must be a callback
154
+ function that takes two arguments: a glyph name and a list of all
155
+ existing filenames (if any exist). It should return a file name
156
+ (including the .glif extension). The glyphNameToFileName function
157
+ is called whenever a file name is created for a given glyph name.
158
+
159
+ ``validateRead`` will validate read operations. Its default is ``True``.
160
+ ``validateWrite`` will validate write operations. Its default is ``True``.
161
+ ``expectContentsFile`` will raise a GlifLibError if a contents.plist file is
162
+ not found on the glyph set file system. This should be set to ``True`` if you
163
+ are reading an existing UFO and ``False`` if you create a fresh glyph set.
164
+ """
165
+ try:
166
+ ufoFormatVersion = UFOFormatVersion(ufoFormatVersion)
167
+ except ValueError as e:
168
+ from fontTools.ufoLib.errors import UnsupportedUFOFormat
169
+
170
+ raise UnsupportedUFOFormat(
171
+ f"Unsupported UFO format: {ufoFormatVersion!r}"
172
+ ) from e
173
+
174
+ if hasattr(path, "__fspath__"): # support os.PathLike objects
175
+ path = path.__fspath__()
176
+
177
+ if isinstance(path, str):
178
+ try:
179
+ filesystem = fs.osfs.OSFS(path)
180
+ except fs.errors.CreateFailed:
181
+ raise GlifLibError("No glyphs directory '%s'" % path)
182
+ self._shouldClose = True
183
+ elif isinstance(path, fs.base.FS):
184
+ filesystem = path
185
+ try:
186
+ filesystem.check()
187
+ except fs.errors.FilesystemClosed:
188
+ raise GlifLibError("the filesystem '%s' is closed" % filesystem)
189
+ self._shouldClose = False
190
+ else:
191
+ raise TypeError(
192
+ "Expected a path string or fs object, found %s" % type(path).__name__
193
+ )
194
+ try:
195
+ path = filesystem.getsyspath("/")
196
+ except fs.errors.NoSysPath:
197
+ # network or in-memory FS may not map to the local one
198
+ path = str(filesystem)
199
+ # 'dirName' is kept for backward compatibility only, but it's DEPRECATED
200
+ # as it's not guaranteed that it maps to an existing OSFS directory.
201
+ # Client could use the FS api via the `self.fs` attribute instead.
202
+ self.dirName = fs.path.parts(path)[-1]
203
+ self.fs = filesystem
204
+ # if glyphSet contains no 'contents.plist', we consider it empty
205
+ self._havePreviousFile = filesystem.exists(CONTENTS_FILENAME)
206
+ if expectContentsFile and not self._havePreviousFile:
207
+ raise GlifLibError(f"{CONTENTS_FILENAME} is missing.")
208
+ # attribute kept for backward compatibility
209
+ self.ufoFormatVersion = ufoFormatVersion.major
210
+ self.ufoFormatVersionTuple = ufoFormatVersion
211
+ if glyphNameToFileNameFunc is None:
212
+ glyphNameToFileNameFunc = glyphNameToFileName
213
+ self.glyphNameToFileName = glyphNameToFileNameFunc
214
+ self._validateRead = validateRead
215
+ self._validateWrite = validateWrite
216
+ self._existingFileNames: set[str] | None = None
217
+ self._reverseContents = None
218
+
219
+ self.rebuildContents()
220
+
221
+ def rebuildContents(self, validateRead=None):
222
+ """
223
+ Rebuild the contents dict by loading contents.plist.
224
+
225
+ ``validateRead`` will validate the data, by default it is set to the
226
+ class's ``validateRead`` value, can be overridden.
227
+ """
228
+ if validateRead is None:
229
+ validateRead = self._validateRead
230
+ contents = self._getPlist(CONTENTS_FILENAME, {})
231
+ # validate the contents
232
+ if validateRead:
233
+ invalidFormat = False
234
+ if not isinstance(contents, dict):
235
+ invalidFormat = True
236
+ else:
237
+ for name, fileName in contents.items():
238
+ if not isinstance(name, str):
239
+ invalidFormat = True
240
+ if not isinstance(fileName, str):
241
+ invalidFormat = True
242
+ elif not self.fs.exists(fileName):
243
+ raise GlifLibError(
244
+ "%s references a file that does not exist: %s"
245
+ % (CONTENTS_FILENAME, fileName)
246
+ )
247
+ if invalidFormat:
248
+ raise GlifLibError("%s is not properly formatted" % CONTENTS_FILENAME)
249
+ self.contents = contents
250
+ self._existingFileNames = None
251
+ self._reverseContents = None
252
+
253
+ def getReverseContents(self):
254
+ """
255
+ Return a reversed dict of self.contents, mapping file names to
256
+ glyph names. This is primarily an aid for custom glyph name to file
257
+ name schemes that want to make sure they don't generate duplicate
258
+ file names. The file names are converted to lowercase so we can
259
+ reliably check for duplicates that only differ in case, which is
260
+ important for case-insensitive file systems.
261
+ """
262
+ if self._reverseContents is None:
263
+ d = {}
264
+ for k, v in self.contents.items():
265
+ d[v.lower()] = k
266
+ self._reverseContents = d
267
+ return self._reverseContents
268
+
269
+ def writeContents(self):
270
+ """
271
+ Write the contents.plist file out to disk. Call this method when
272
+ you're done writing glyphs.
273
+ """
274
+ self._writePlist(CONTENTS_FILENAME, self.contents)
275
+
276
+ # layer info
277
+
278
+ def readLayerInfo(self, info, validateRead=None):
279
+ """
280
+ ``validateRead`` will validate the data, by default it is set to the
281
+ class's ``validateRead`` value, can be overridden.
282
+ """
283
+ if validateRead is None:
284
+ validateRead = self._validateRead
285
+ infoDict = self._getPlist(LAYERINFO_FILENAME, {})
286
+ if validateRead:
287
+ if not isinstance(infoDict, dict):
288
+ raise GlifLibError("layerinfo.plist is not properly formatted.")
289
+ infoDict = validateLayerInfoVersion3Data(infoDict)
290
+ # populate the object
291
+ for attr, value in infoDict.items():
292
+ try:
293
+ setattr(info, attr, value)
294
+ except AttributeError:
295
+ raise GlifLibError(
296
+ "The supplied layer info object does not support setting a necessary attribute (%s)."
297
+ % attr
298
+ )
299
+
300
+ def writeLayerInfo(self, info, validateWrite=None):
301
+ """
302
+ ``validateWrite`` will validate the data, by default it is set to the
303
+ class's ``validateWrite`` value, can be overridden.
304
+ """
305
+ if validateWrite is None:
306
+ validateWrite = self._validateWrite
307
+ if self.ufoFormatVersionTuple.major < 3:
308
+ raise GlifLibError(
309
+ "layerinfo.plist is not allowed in UFO %d."
310
+ % self.ufoFormatVersionTuple.major
311
+ )
312
+ # gather data
313
+ infoData = {}
314
+ for attr in layerInfoVersion3ValueData.keys():
315
+ if hasattr(info, attr):
316
+ try:
317
+ value = getattr(info, attr)
318
+ except AttributeError:
319
+ raise GlifLibError(
320
+ "The supplied info object does not support getting a necessary attribute (%s)."
321
+ % attr
322
+ )
323
+ if value is None or (attr == "lib" and not value):
324
+ continue
325
+ infoData[attr] = value
326
+ if infoData:
327
+ # validate
328
+ if validateWrite:
329
+ infoData = validateLayerInfoVersion3Data(infoData)
330
+ # write file
331
+ self._writePlist(LAYERINFO_FILENAME, infoData)
332
+ elif self._havePreviousFile and self.fs.exists(LAYERINFO_FILENAME):
333
+ # data empty, remove existing file
334
+ self.fs.remove(LAYERINFO_FILENAME)
335
+
336
+ def getGLIF(self, glyphName):
337
+ """
338
+ Get the raw GLIF text for a given glyph name. This only works
339
+ for GLIF files that are already on disk.
340
+
341
+ This method is useful in situations when the raw XML needs to be
342
+ read from a glyph set for a particular glyph before fully parsing
343
+ it into an object structure via the readGlyph method.
344
+
345
+ Raises KeyError if 'glyphName' is not in contents.plist, or
346
+ GlifLibError if the file associated with can't be found.
347
+ """
348
+ fileName = self.contents[glyphName]
349
+ try:
350
+ return self.fs.readbytes(fileName)
351
+ except fs.errors.ResourceNotFound:
352
+ raise GlifLibError(
353
+ "The file '%s' associated with glyph '%s' in contents.plist "
354
+ "does not exist on %s" % (fileName, glyphName, self.fs)
355
+ )
356
+
357
+ def getGLIFModificationTime(self, glyphName):
358
+ """
359
+ Returns the modification time for the GLIF file with 'glyphName', as
360
+ a floating point number giving the number of seconds since the epoch.
361
+ Return None if the associated file does not exist or the underlying
362
+ filesystem does not support getting modified times.
363
+ Raises KeyError if the glyphName is not in contents.plist.
364
+ """
365
+ fileName = self.contents[glyphName]
366
+ return self.getFileModificationTime(fileName)
367
+
368
+ # reading/writing API
369
+
370
+ def readGlyph(self, glyphName, glyphObject=None, pointPen=None, validate=None):
371
+ """
372
+ Read a .glif file for 'glyphName' from the glyph set. The
373
+ 'glyphObject' argument can be any kind of object (even None);
374
+ the readGlyph() method will attempt to set the following
375
+ attributes on it:
376
+
377
+ width
378
+ the advance width of the glyph
379
+ height
380
+ the advance height of the glyph
381
+ unicodes
382
+ a list of unicode values for this glyph
383
+ note
384
+ a string
385
+ lib
386
+ a dictionary containing custom data
387
+ image
388
+ a dictionary containing image data
389
+ guidelines
390
+ a list of guideline data dictionaries
391
+ anchors
392
+ a list of anchor data dictionaries
393
+
394
+ All attributes are optional, in two ways:
395
+
396
+ 1) An attribute *won't* be set if the .glif file doesn't
397
+ contain data for it. 'glyphObject' will have to deal
398
+ with default values itself.
399
+ 2) If setting the attribute fails with an AttributeError
400
+ (for example if the 'glyphObject' attribute is read-
401
+ only), readGlyph() will not propagate that exception,
402
+ but ignore that attribute.
403
+
404
+ To retrieve outline information, you need to pass an object
405
+ conforming to the PointPen protocol as the 'pointPen' argument.
406
+ This argument may be None if you don't need the outline data.
407
+
408
+ readGlyph() will raise KeyError if the glyph is not present in
409
+ the glyph set.
410
+
411
+ ``validate`` will validate the data, by default it is set to the
412
+ class's ``validateRead`` value, can be overridden.
413
+ """
414
+ if validate is None:
415
+ validate = self._validateRead
416
+ text = self.getGLIF(glyphName)
417
+ try:
418
+ tree = _glifTreeFromString(text)
419
+ formatVersions = GLIFFormatVersion.supported_versions(
420
+ self.ufoFormatVersionTuple
421
+ )
422
+ _readGlyphFromTree(
423
+ tree,
424
+ glyphObject,
425
+ pointPen,
426
+ formatVersions=formatVersions,
427
+ validate=validate,
428
+ )
429
+ except GlifLibError as glifLibError:
430
+ # Re-raise with a note that gives extra context, describing where
431
+ # the error occurred.
432
+ fileName = self.contents[glyphName]
433
+ try:
434
+ glifLocation = f"'{self.fs.getsyspath(fileName)}'"
435
+ except fs.errors.NoSysPath:
436
+ # Network or in-memory FS may not map to a local path, so use
437
+ # the best string representation we have.
438
+ glifLocation = f"'{fileName}' from '{str(self.fs)}'"
439
+
440
+ glifLibError._add_note(
441
+ f"The issue is in glyph '{glyphName}', located in {glifLocation}."
442
+ )
443
+ raise
444
+
445
+ def writeGlyph(
446
+ self,
447
+ glyphName,
448
+ glyphObject=None,
449
+ drawPointsFunc=None,
450
+ formatVersion=None,
451
+ validate=None,
452
+ ):
453
+ """
454
+ Write a .glif file for 'glyphName' to the glyph set. The
455
+ 'glyphObject' argument can be any kind of object (even None);
456
+ the writeGlyph() method will attempt to get the following
457
+ attributes from it:
458
+
459
+ width
460
+ the advance width of the glyph
461
+ height
462
+ the advance height of the glyph
463
+ unicodes
464
+ a list of unicode values for this glyph
465
+ note
466
+ a string
467
+ lib
468
+ a dictionary containing custom data
469
+ image
470
+ a dictionary containing image data
471
+ guidelines
472
+ a list of guideline data dictionaries
473
+ anchors
474
+ a list of anchor data dictionaries
475
+
476
+ All attributes are optional: if 'glyphObject' doesn't
477
+ have the attribute, it will simply be skipped.
478
+
479
+ To write outline data to the .glif file, writeGlyph() needs
480
+ a function (any callable object actually) that will take one
481
+ argument: an object that conforms to the PointPen protocol.
482
+ The function will be called by writeGlyph(); it has to call the
483
+ proper PointPen methods to transfer the outline to the .glif file.
484
+
485
+ The GLIF format version will be chosen based on the ufoFormatVersion
486
+ passed during the creation of this object. If a particular format
487
+ version is desired, it can be passed with the formatVersion argument.
488
+ The formatVersion argument accepts either a tuple of integers for
489
+ (major, minor), or a single integer for the major digit only (with
490
+ minor digit implied as 0).
491
+
492
+ An UnsupportedGLIFFormat exception is raised if the requested GLIF
493
+ formatVersion is not supported.
494
+
495
+ ``validate`` will validate the data, by default it is set to the
496
+ class's ``validateWrite`` value, can be overridden.
497
+ """
498
+ if formatVersion is None:
499
+ formatVersion = GLIFFormatVersion.default(self.ufoFormatVersionTuple)
500
+ else:
501
+ try:
502
+ formatVersion = GLIFFormatVersion(formatVersion)
503
+ except ValueError as e:
504
+ from fontTools.ufoLib.errors import UnsupportedGLIFFormat
505
+
506
+ raise UnsupportedGLIFFormat(
507
+ f"Unsupported GLIF format version: {formatVersion!r}"
508
+ ) from e
509
+ if formatVersion not in GLIFFormatVersion.supported_versions(
510
+ self.ufoFormatVersionTuple
511
+ ):
512
+ from fontTools.ufoLib.errors import UnsupportedGLIFFormat
513
+
514
+ raise UnsupportedGLIFFormat(
515
+ f"Unsupported GLIF format version ({formatVersion!s}) "
516
+ f"for UFO format version {self.ufoFormatVersionTuple!s}."
517
+ )
518
+ if validate is None:
519
+ validate = self._validateWrite
520
+ fileName = self.contents.get(glyphName)
521
+ if fileName is None:
522
+ if self._existingFileNames is None:
523
+ self._existingFileNames = {
524
+ fileName.lower() for fileName in self.contents.values()
525
+ }
526
+ fileName = self.glyphNameToFileName(glyphName, self._existingFileNames)
527
+ self.contents[glyphName] = fileName
528
+ self._existingFileNames.add(fileName.lower())
529
+ if self._reverseContents is not None:
530
+ self._reverseContents[fileName.lower()] = glyphName
531
+ data = _writeGlyphToBytes(
532
+ glyphName,
533
+ glyphObject,
534
+ drawPointsFunc,
535
+ formatVersion=formatVersion,
536
+ validate=validate,
537
+ )
538
+ if (
539
+ self._havePreviousFile
540
+ and self.fs.exists(fileName)
541
+ and data == self.fs.readbytes(fileName)
542
+ ):
543
+ return
544
+ self.fs.writebytes(fileName, data)
545
+
546
+ def deleteGlyph(self, glyphName):
547
+ """Permanently delete the glyph from the glyph set on disk. Will
548
+ raise KeyError if the glyph is not present in the glyph set.
549
+ """
550
+ fileName = self.contents[glyphName]
551
+ self.fs.remove(fileName)
552
+ if self._existingFileNames is not None:
553
+ self._existingFileNames.remove(fileName.lower())
554
+ if self._reverseContents is not None:
555
+ del self._reverseContents[fileName.lower()]
556
+ del self.contents[glyphName]
557
+
558
+ # dict-like support
559
+
560
+ def keys(self):
561
+ return list(self.contents.keys())
562
+
563
+ def has_key(self, glyphName):
564
+ return glyphName in self.contents
565
+
566
+ __contains__ = has_key
567
+
568
+ def __len__(self):
569
+ return len(self.contents)
570
+
571
+ def __getitem__(self, glyphName):
572
+ if glyphName not in self.contents:
573
+ raise KeyError(glyphName)
574
+ return self.glyphClass(glyphName, self)
575
+
576
+ # quickly fetch unicode values
577
+
578
+ def getUnicodes(self, glyphNames=None):
579
+ """
580
+ Return a dictionary that maps glyph names to lists containing
581
+ the unicode value[s] for that glyph, if any. This parses the .glif
582
+ files partially, so it is a lot faster than parsing all files completely.
583
+ By default this checks all glyphs, but a subset can be passed with glyphNames.
584
+ """
585
+ unicodes = {}
586
+ if glyphNames is None:
587
+ glyphNames = self.contents.keys()
588
+ for glyphName in glyphNames:
589
+ text = self.getGLIF(glyphName)
590
+ unicodes[glyphName] = _fetchUnicodes(text)
591
+ return unicodes
592
+
593
+ def getComponentReferences(self, glyphNames=None):
594
+ """
595
+ Return a dictionary that maps glyph names to lists containing the
596
+ base glyph name of components in the glyph. This parses the .glif
597
+ files partially, so it is a lot faster than parsing all files completely.
598
+ By default this checks all glyphs, but a subset can be passed with glyphNames.
599
+ """
600
+ components = {}
601
+ if glyphNames is None:
602
+ glyphNames = self.contents.keys()
603
+ for glyphName in glyphNames:
604
+ text = self.getGLIF(glyphName)
605
+ components[glyphName] = _fetchComponentBases(text)
606
+ return components
607
+
608
+ def getImageReferences(self, glyphNames=None):
609
+ """
610
+ Return a dictionary that maps glyph names to the file name of the image
611
+ referenced by the glyph. This parses the .glif files partially, so it is a
612
+ lot faster than parsing all files completely.
613
+ By default this checks all glyphs, but a subset can be passed with glyphNames.
614
+ """
615
+ images = {}
616
+ if glyphNames is None:
617
+ glyphNames = self.contents.keys()
618
+ for glyphName in glyphNames:
619
+ text = self.getGLIF(glyphName)
620
+ images[glyphName] = _fetchImageFileName(text)
621
+ return images
622
+
623
+ def close(self):
624
+ if self._shouldClose:
625
+ self.fs.close()
626
+
627
+ def __enter__(self):
628
+ return self
629
+
630
+ def __exit__(self, exc_type, exc_value, exc_tb):
631
+ self.close()
632
+
633
+
634
+ # -----------------------
635
+ # Glyph Name to File Name
636
+ # -----------------------
637
+
638
+
639
+ def glyphNameToFileName(glyphName, existingFileNames):
640
+ """
641
+ Wrapper around the userNameToFileName function in filenames.py
642
+
643
+ Note that existingFileNames should be a set for large glyphsets
644
+ or performance will suffer.
645
+ """
646
+ if existingFileNames is None:
647
+ existingFileNames = set()
648
+ return userNameToFileName(glyphName, existing=existingFileNames, suffix=".glif")
649
+
650
+
651
+ # -----------------------
652
+ # GLIF To and From String
653
+ # -----------------------
654
+
655
+
656
+ def readGlyphFromString(
657
+ aString,
658
+ glyphObject=None,
659
+ pointPen=None,
660
+ formatVersions=None,
661
+ validate=True,
662
+ ):
663
+ """
664
+ Read .glif data from a string into a glyph object.
665
+
666
+ The 'glyphObject' argument can be any kind of object (even None);
667
+ the readGlyphFromString() method will attempt to set the following
668
+ attributes on it:
669
+
670
+ width
671
+ the advance width of the glyph
672
+ height
673
+ the advance height of the glyph
674
+ unicodes
675
+ a list of unicode values for this glyph
676
+ note
677
+ a string
678
+ lib
679
+ a dictionary containing custom data
680
+ image
681
+ a dictionary containing image data
682
+ guidelines
683
+ a list of guideline data dictionaries
684
+ anchors
685
+ a list of anchor data dictionaries
686
+
687
+ All attributes are optional, in two ways:
688
+
689
+ 1) An attribute *won't* be set if the .glif file doesn't
690
+ contain data for it. 'glyphObject' will have to deal
691
+ with default values itself.
692
+ 2) If setting the attribute fails with an AttributeError
693
+ (for example if the 'glyphObject' attribute is read-
694
+ only), readGlyphFromString() will not propagate that
695
+ exception, but ignore that attribute.
696
+
697
+ To retrieve outline information, you need to pass an object
698
+ conforming to the PointPen protocol as the 'pointPen' argument.
699
+ This argument may be None if you don't need the outline data.
700
+
701
+ The formatVersions optional argument define the GLIF format versions
702
+ that are allowed to be read.
703
+ The type is Optional[Iterable[Tuple[int, int], int]]. It can contain
704
+ either integers (for the major versions to be allowed, with minor
705
+ digits defaulting to 0), or tuples of integers to specify both
706
+ (major, minor) versions.
707
+ By default when formatVersions is None all the GLIF format versions
708
+ currently defined are allowed to be read.
709
+
710
+ ``validate`` will validate the read data. It is set to ``True`` by default.
711
+ """
712
+ tree = _glifTreeFromString(aString)
713
+
714
+ if formatVersions is None:
715
+ validFormatVersions = GLIFFormatVersion.supported_versions()
716
+ else:
717
+ validFormatVersions, invalidFormatVersions = set(), set()
718
+ for v in formatVersions:
719
+ try:
720
+ formatVersion = GLIFFormatVersion(v)
721
+ except ValueError:
722
+ invalidFormatVersions.add(v)
723
+ else:
724
+ validFormatVersions.add(formatVersion)
725
+ if not validFormatVersions:
726
+ raise ValueError(
727
+ "None of the requested GLIF formatVersions are supported: "
728
+ f"{formatVersions!r}"
729
+ )
730
+
731
+ _readGlyphFromTree(
732
+ tree,
733
+ glyphObject,
734
+ pointPen,
735
+ formatVersions=validFormatVersions,
736
+ validate=validate,
737
+ )
738
+
739
+
740
+ def _writeGlyphToBytes(
741
+ glyphName,
742
+ glyphObject=None,
743
+ drawPointsFunc=None,
744
+ writer=None,
745
+ formatVersion=None,
746
+ validate=True,
747
+ ):
748
+ """Return .glif data for a glyph as a UTF-8 encoded bytes string."""
749
+ try:
750
+ formatVersion = GLIFFormatVersion(formatVersion)
751
+ except ValueError:
752
+ from fontTools.ufoLib.errors import UnsupportedGLIFFormat
753
+
754
+ raise UnsupportedGLIFFormat(
755
+ "Unsupported GLIF format version: {formatVersion!r}"
756
+ )
757
+ # start
758
+ if validate and not isinstance(glyphName, str):
759
+ raise GlifLibError("The glyph name is not properly formatted.")
760
+ if validate and len(glyphName) == 0:
761
+ raise GlifLibError("The glyph name is empty.")
762
+ glyphAttrs = OrderedDict(
763
+ [("name", glyphName), ("format", repr(formatVersion.major))]
764
+ )
765
+ if formatVersion.minor != 0:
766
+ glyphAttrs["formatMinor"] = repr(formatVersion.minor)
767
+ root = etree.Element("glyph", glyphAttrs)
768
+ identifiers = set()
769
+ # advance
770
+ _writeAdvance(glyphObject, root, validate)
771
+ # unicodes
772
+ if getattr(glyphObject, "unicodes", None):
773
+ _writeUnicodes(glyphObject, root, validate)
774
+ # note
775
+ if getattr(glyphObject, "note", None):
776
+ _writeNote(glyphObject, root, validate)
777
+ # image
778
+ if formatVersion.major >= 2 and getattr(glyphObject, "image", None):
779
+ _writeImage(glyphObject, root, validate)
780
+ # guidelines
781
+ if formatVersion.major >= 2 and getattr(glyphObject, "guidelines", None):
782
+ _writeGuidelines(glyphObject, root, identifiers, validate)
783
+ # anchors
784
+ anchors = getattr(glyphObject, "anchors", None)
785
+ if formatVersion.major >= 2 and anchors:
786
+ _writeAnchors(glyphObject, root, identifiers, validate)
787
+ # outline
788
+ if drawPointsFunc is not None:
789
+ outline = etree.SubElement(root, "outline")
790
+ pen = GLIFPointPen(outline, identifiers=identifiers, validate=validate)
791
+ drawPointsFunc(pen)
792
+ if formatVersion.major == 1 and anchors:
793
+ _writeAnchorsFormat1(pen, anchors, validate)
794
+ # prevent lxml from writing self-closing tags
795
+ if not len(outline):
796
+ outline.text = "\n "
797
+ # lib
798
+ if getattr(glyphObject, "lib", None):
799
+ _writeLib(glyphObject, root, validate)
800
+ # return the text
801
+ data = etree.tostring(
802
+ root, encoding="UTF-8", xml_declaration=True, pretty_print=True
803
+ )
804
+ return data
805
+
806
+
807
+ def writeGlyphToString(
808
+ glyphName,
809
+ glyphObject=None,
810
+ drawPointsFunc=None,
811
+ formatVersion=None,
812
+ validate=True,
813
+ ):
814
+ """
815
+ Return .glif data for a glyph as a string. The XML declaration's
816
+ encoding is always set to "UTF-8".
817
+ The 'glyphObject' argument can be any kind of object (even None);
818
+ the writeGlyphToString() method will attempt to get the following
819
+ attributes from it:
820
+
821
+ width
822
+ the advance width of the glyph
823
+ height
824
+ the advance height of the glyph
825
+ unicodes
826
+ a list of unicode values for this glyph
827
+ note
828
+ a string
829
+ lib
830
+ a dictionary containing custom data
831
+ image
832
+ a dictionary containing image data
833
+ guidelines
834
+ a list of guideline data dictionaries
835
+ anchors
836
+ a list of anchor data dictionaries
837
+
838
+ All attributes are optional: if 'glyphObject' doesn't
839
+ have the attribute, it will simply be skipped.
840
+
841
+ To write outline data to the .glif file, writeGlyphToString() needs
842
+ a function (any callable object actually) that will take one
843
+ argument: an object that conforms to the PointPen protocol.
844
+ The function will be called by writeGlyphToString(); it has to call the
845
+ proper PointPen methods to transfer the outline to the .glif file.
846
+
847
+ The GLIF format version can be specified with the formatVersion argument.
848
+ This accepts either a tuple of integers for (major, minor), or a single
849
+ integer for the major digit only (with minor digit implied as 0).
850
+ By default when formatVesion is None the latest GLIF format version will
851
+ be used; currently it's 2.0, which is equivalent to formatVersion=(2, 0).
852
+
853
+ An UnsupportedGLIFFormat exception is raised if the requested UFO
854
+ formatVersion is not supported.
855
+
856
+ ``validate`` will validate the written data. It is set to ``True`` by default.
857
+ """
858
+ data = _writeGlyphToBytes(
859
+ glyphName,
860
+ glyphObject=glyphObject,
861
+ drawPointsFunc=drawPointsFunc,
862
+ formatVersion=formatVersion,
863
+ validate=validate,
864
+ )
865
+ return data.decode("utf-8")
866
+
867
+
868
+ def _writeAdvance(glyphObject, element, validate):
869
+ width = getattr(glyphObject, "width", None)
870
+ if width is not None:
871
+ if validate and not isinstance(width, numberTypes):
872
+ raise GlifLibError("width attribute must be int or float")
873
+ if width == 0:
874
+ width = None
875
+ height = getattr(glyphObject, "height", None)
876
+ if height is not None:
877
+ if validate and not isinstance(height, numberTypes):
878
+ raise GlifLibError("height attribute must be int or float")
879
+ if height == 0:
880
+ height = None
881
+ if width is not None and height is not None:
882
+ etree.SubElement(
883
+ element,
884
+ "advance",
885
+ OrderedDict([("height", repr(height)), ("width", repr(width))]),
886
+ )
887
+ elif width is not None:
888
+ etree.SubElement(element, "advance", dict(width=repr(width)))
889
+ elif height is not None:
890
+ etree.SubElement(element, "advance", dict(height=repr(height)))
891
+
892
+
893
+ def _writeUnicodes(glyphObject, element, validate):
894
+ unicodes = getattr(glyphObject, "unicodes", None)
895
+ if validate and isinstance(unicodes, int):
896
+ unicodes = [unicodes]
897
+ seen = set()
898
+ for code in unicodes:
899
+ if validate and not isinstance(code, int):
900
+ raise GlifLibError("unicode values must be int")
901
+ if code in seen:
902
+ continue
903
+ seen.add(code)
904
+ hexCode = "%04X" % code
905
+ etree.SubElement(element, "unicode", dict(hex=hexCode))
906
+
907
+
908
+ def _writeNote(glyphObject, element, validate):
909
+ note = getattr(glyphObject, "note", None)
910
+ if validate and not isinstance(note, str):
911
+ raise GlifLibError("note attribute must be str")
912
+ note = note.strip()
913
+ note = "\n" + note + "\n"
914
+ etree.SubElement(element, "note").text = note
915
+
916
+
917
+ def _writeImage(glyphObject, element, validate):
918
+ image = getattr(glyphObject, "image", None)
919
+ if validate and not imageValidator(image):
920
+ raise GlifLibError(
921
+ "image attribute must be a dict or dict-like object with the proper structure."
922
+ )
923
+ attrs = OrderedDict([("fileName", image["fileName"])])
924
+ for attr, default in _transformationInfo:
925
+ value = image.get(attr, default)
926
+ if value != default:
927
+ attrs[attr] = repr(value)
928
+ color = image.get("color")
929
+ if color is not None:
930
+ attrs["color"] = color
931
+ etree.SubElement(element, "image", attrs)
932
+
933
+
934
+ def _writeGuidelines(glyphObject, element, identifiers, validate):
935
+ guidelines = getattr(glyphObject, "guidelines", [])
936
+ if validate and not guidelinesValidator(guidelines):
937
+ raise GlifLibError("guidelines attribute does not have the proper structure.")
938
+ for guideline in guidelines:
939
+ attrs = OrderedDict()
940
+ x = guideline.get("x")
941
+ if x is not None:
942
+ attrs["x"] = repr(x)
943
+ y = guideline.get("y")
944
+ if y is not None:
945
+ attrs["y"] = repr(y)
946
+ angle = guideline.get("angle")
947
+ if angle is not None:
948
+ attrs["angle"] = repr(angle)
949
+ name = guideline.get("name")
950
+ if name is not None:
951
+ attrs["name"] = name
952
+ color = guideline.get("color")
953
+ if color is not None:
954
+ attrs["color"] = color
955
+ identifier = guideline.get("identifier")
956
+ if identifier is not None:
957
+ if validate and identifier in identifiers:
958
+ raise GlifLibError("identifier used more than once: %s" % identifier)
959
+ attrs["identifier"] = identifier
960
+ identifiers.add(identifier)
961
+ etree.SubElement(element, "guideline", attrs)
962
+
963
+
964
+ def _writeAnchorsFormat1(pen, anchors, validate):
965
+ if validate and not anchorsValidator(anchors):
966
+ raise GlifLibError("anchors attribute does not have the proper structure.")
967
+ for anchor in anchors:
968
+ attrs = {}
969
+ x = anchor["x"]
970
+ attrs["x"] = repr(x)
971
+ y = anchor["y"]
972
+ attrs["y"] = repr(y)
973
+ name = anchor.get("name")
974
+ if name is not None:
975
+ attrs["name"] = name
976
+ pen.beginPath()
977
+ pen.addPoint((x, y), segmentType="move", name=name)
978
+ pen.endPath()
979
+
980
+
981
+ def _writeAnchors(glyphObject, element, identifiers, validate):
982
+ anchors = getattr(glyphObject, "anchors", [])
983
+ if validate and not anchorsValidator(anchors):
984
+ raise GlifLibError("anchors attribute does not have the proper structure.")
985
+ for anchor in anchors:
986
+ attrs = OrderedDict()
987
+ x = anchor["x"]
988
+ attrs["x"] = repr(x)
989
+ y = anchor["y"]
990
+ attrs["y"] = repr(y)
991
+ name = anchor.get("name")
992
+ if name is not None:
993
+ attrs["name"] = name
994
+ color = anchor.get("color")
995
+ if color is not None:
996
+ attrs["color"] = color
997
+ identifier = anchor.get("identifier")
998
+ if identifier is not None:
999
+ if validate and identifier in identifiers:
1000
+ raise GlifLibError("identifier used more than once: %s" % identifier)
1001
+ attrs["identifier"] = identifier
1002
+ identifiers.add(identifier)
1003
+ etree.SubElement(element, "anchor", attrs)
1004
+
1005
+
1006
+ def _writeLib(glyphObject, element, validate):
1007
+ lib = getattr(glyphObject, "lib", None)
1008
+ if not lib:
1009
+ # don't write empty lib
1010
+ return
1011
+ if validate:
1012
+ valid, message = glyphLibValidator(lib)
1013
+ if not valid:
1014
+ raise GlifLibError(message)
1015
+ if not isinstance(lib, dict):
1016
+ lib = dict(lib)
1017
+ # plist inside GLIF begins with 2 levels of indentation
1018
+ e = plistlib.totree(lib, indent_level=2)
1019
+ etree.SubElement(element, "lib").append(e)
1020
+
1021
+
1022
+ # -----------------------
1023
+ # layerinfo.plist Support
1024
+ # -----------------------
1025
+
1026
+ layerInfoVersion3ValueData = {
1027
+ "color": dict(type=str, valueValidator=colorValidator),
1028
+ "lib": dict(type=dict, valueValidator=genericTypeValidator),
1029
+ }
1030
+
1031
+
1032
+ def validateLayerInfoVersion3ValueForAttribute(attr, value):
1033
+ """
1034
+ This performs very basic validation of the value for attribute
1035
+ following the UFO 3 fontinfo.plist specification. The results
1036
+ of this should not be interpretted as *correct* for the font
1037
+ that they are part of. This merely indicates that the value
1038
+ is of the proper type and, where the specification defines
1039
+ a set range of possible values for an attribute, that the
1040
+ value is in the accepted range.
1041
+ """
1042
+ if attr not in layerInfoVersion3ValueData:
1043
+ return False
1044
+ dataValidationDict = layerInfoVersion3ValueData[attr]
1045
+ valueType = dataValidationDict.get("type")
1046
+ validator = dataValidationDict.get("valueValidator")
1047
+ valueOptions = dataValidationDict.get("valueOptions")
1048
+ # have specific options for the validator
1049
+ if valueOptions is not None:
1050
+ isValidValue = validator(value, valueOptions)
1051
+ # no specific options
1052
+ else:
1053
+ if validator == genericTypeValidator:
1054
+ isValidValue = validator(value, valueType)
1055
+ else:
1056
+ isValidValue = validator(value)
1057
+ return isValidValue
1058
+
1059
+
1060
+ def validateLayerInfoVersion3Data(infoData):
1061
+ """
1062
+ This performs very basic validation of the value for infoData
1063
+ following the UFO 3 layerinfo.plist specification. The results
1064
+ of this should not be interpretted as *correct* for the font
1065
+ that they are part of. This merely indicates that the values
1066
+ are of the proper type and, where the specification defines
1067
+ a set range of possible values for an attribute, that the
1068
+ value is in the accepted range.
1069
+ """
1070
+ for attr, value in infoData.items():
1071
+ if attr not in layerInfoVersion3ValueData:
1072
+ raise GlifLibError("Unknown attribute %s." % attr)
1073
+ isValidValue = validateLayerInfoVersion3ValueForAttribute(attr, value)
1074
+ if not isValidValue:
1075
+ raise GlifLibError(f"Invalid value for attribute {attr} ({value!r}).")
1076
+ return infoData
1077
+
1078
+
1079
+ # -----------------
1080
+ # GLIF Tree Support
1081
+ # -----------------
1082
+
1083
+
1084
+ def _glifTreeFromFile(aFile):
1085
+ if etree._have_lxml:
1086
+ tree = etree.parse(aFile, parser=etree.XMLParser(remove_comments=True))
1087
+ else:
1088
+ tree = etree.parse(aFile)
1089
+ root = tree.getroot()
1090
+ if root.tag != "glyph":
1091
+ raise GlifLibError("The GLIF is not properly formatted.")
1092
+ if root.text and root.text.strip() != "":
1093
+ raise GlifLibError("Invalid GLIF structure.")
1094
+ return root
1095
+
1096
+
1097
+ def _glifTreeFromString(aString):
1098
+ data = tobytes(aString, encoding="utf-8")
1099
+ try:
1100
+ if etree._have_lxml:
1101
+ root = etree.fromstring(data, parser=etree.XMLParser(remove_comments=True))
1102
+ else:
1103
+ root = etree.fromstring(data)
1104
+ except Exception as etree_exception:
1105
+ raise GlifLibError("GLIF contains invalid XML.") from etree_exception
1106
+
1107
+ if root.tag != "glyph":
1108
+ raise GlifLibError("The GLIF is not properly formatted.")
1109
+ if root.text and root.text.strip() != "":
1110
+ raise GlifLibError("Invalid GLIF structure.")
1111
+ return root
1112
+
1113
+
1114
+ def _readGlyphFromTree(
1115
+ tree,
1116
+ glyphObject=None,
1117
+ pointPen=None,
1118
+ formatVersions=GLIFFormatVersion.supported_versions(),
1119
+ validate=True,
1120
+ ):
1121
+ # check the format version
1122
+ formatVersionMajor = tree.get("format")
1123
+ if validate and formatVersionMajor is None:
1124
+ raise GlifLibError("Unspecified format version in GLIF.")
1125
+ formatVersionMinor = tree.get("formatMinor", 0)
1126
+ try:
1127
+ formatVersion = GLIFFormatVersion(
1128
+ (int(formatVersionMajor), int(formatVersionMinor))
1129
+ )
1130
+ except ValueError as e:
1131
+ msg = "Unsupported GLIF format: %s.%s" % (
1132
+ formatVersionMajor,
1133
+ formatVersionMinor,
1134
+ )
1135
+ if validate:
1136
+ from fontTools.ufoLib.errors import UnsupportedGLIFFormat
1137
+
1138
+ raise UnsupportedGLIFFormat(msg) from e
1139
+ # warn but continue using the latest supported format
1140
+ formatVersion = GLIFFormatVersion.default()
1141
+ logger.warning(
1142
+ "%s. Assuming the latest supported version (%s). "
1143
+ "Some data may be skipped or parsed incorrectly.",
1144
+ msg,
1145
+ formatVersion,
1146
+ )
1147
+
1148
+ if validate and formatVersion not in formatVersions:
1149
+ raise GlifLibError(f"Forbidden GLIF format version: {formatVersion!s}")
1150
+
1151
+ try:
1152
+ readGlyphFromTree = _READ_GLYPH_FROM_TREE_FUNCS[formatVersion]
1153
+ except KeyError:
1154
+ raise NotImplementedError(formatVersion)
1155
+
1156
+ readGlyphFromTree(
1157
+ tree=tree,
1158
+ glyphObject=glyphObject,
1159
+ pointPen=pointPen,
1160
+ validate=validate,
1161
+ formatMinor=formatVersion.minor,
1162
+ )
1163
+
1164
+
1165
+ def _readGlyphFromTreeFormat1(
1166
+ tree, glyphObject=None, pointPen=None, validate=None, **kwargs
1167
+ ):
1168
+ # get the name
1169
+ _readName(glyphObject, tree, validate)
1170
+ # populate the sub elements
1171
+ unicodes = []
1172
+ haveSeenAdvance = haveSeenOutline = haveSeenLib = haveSeenNote = False
1173
+ for element in tree:
1174
+ if element.tag == "outline":
1175
+ if validate:
1176
+ if haveSeenOutline:
1177
+ raise GlifLibError("The outline element occurs more than once.")
1178
+ if element.attrib:
1179
+ raise GlifLibError(
1180
+ "The outline element contains unknown attributes."
1181
+ )
1182
+ if element.text and element.text.strip() != "":
1183
+ raise GlifLibError("Invalid outline structure.")
1184
+ haveSeenOutline = True
1185
+ buildOutlineFormat1(glyphObject, pointPen, element, validate)
1186
+ elif glyphObject is None:
1187
+ continue
1188
+ elif element.tag == "advance":
1189
+ if validate and haveSeenAdvance:
1190
+ raise GlifLibError("The advance element occurs more than once.")
1191
+ haveSeenAdvance = True
1192
+ _readAdvance(glyphObject, element)
1193
+ elif element.tag == "unicode":
1194
+ v = element.get("hex")
1195
+ if v is None:
1196
+ raise GlifLibError(
1197
+ "A unicode element is missing its required hex attribute."
1198
+ )
1199
+ try:
1200
+ v = int(v, 16)
1201
+ if v not in unicodes:
1202
+ unicodes.append(v)
1203
+ except ValueError:
1204
+ raise GlifLibError(
1205
+ "Illegal value for hex attribute of unicode element."
1206
+ )
1207
+ elif element.tag == "note":
1208
+ if validate and haveSeenNote:
1209
+ raise GlifLibError("The note element occurs more than once.")
1210
+ haveSeenNote = True
1211
+ _readNote(glyphObject, element)
1212
+ elif element.tag == "lib":
1213
+ if validate and haveSeenLib:
1214
+ raise GlifLibError("The lib element occurs more than once.")
1215
+ haveSeenLib = True
1216
+ _readLib(glyphObject, element, validate)
1217
+ else:
1218
+ raise GlifLibError("Unknown element in GLIF: %s" % element)
1219
+ # set the collected unicodes
1220
+ if unicodes:
1221
+ _relaxedSetattr(glyphObject, "unicodes", unicodes)
1222
+
1223
+
1224
+ def _readGlyphFromTreeFormat2(
1225
+ tree, glyphObject=None, pointPen=None, validate=None, formatMinor=0
1226
+ ):
1227
+ # get the name
1228
+ _readName(glyphObject, tree, validate)
1229
+ # populate the sub elements
1230
+ unicodes = []
1231
+ guidelines = []
1232
+ anchors = []
1233
+ haveSeenAdvance = haveSeenImage = haveSeenOutline = haveSeenLib = haveSeenNote = (
1234
+ False
1235
+ )
1236
+ identifiers = set()
1237
+ for element in tree:
1238
+ if element.tag == "outline":
1239
+ if validate:
1240
+ if haveSeenOutline:
1241
+ raise GlifLibError("The outline element occurs more than once.")
1242
+ if element.attrib:
1243
+ raise GlifLibError(
1244
+ "The outline element contains unknown attributes."
1245
+ )
1246
+ if element.text and element.text.strip() != "":
1247
+ raise GlifLibError("Invalid outline structure.")
1248
+ haveSeenOutline = True
1249
+ if pointPen is not None:
1250
+ buildOutlineFormat2(
1251
+ glyphObject, pointPen, element, identifiers, validate
1252
+ )
1253
+ elif glyphObject is None:
1254
+ continue
1255
+ elif element.tag == "advance":
1256
+ if validate and haveSeenAdvance:
1257
+ raise GlifLibError("The advance element occurs more than once.")
1258
+ haveSeenAdvance = True
1259
+ _readAdvance(glyphObject, element)
1260
+ elif element.tag == "unicode":
1261
+ v = element.get("hex")
1262
+ if v is None:
1263
+ raise GlifLibError(
1264
+ "A unicode element is missing its required hex attribute."
1265
+ )
1266
+ try:
1267
+ v = int(v, 16)
1268
+ if v not in unicodes:
1269
+ unicodes.append(v)
1270
+ except ValueError:
1271
+ raise GlifLibError(
1272
+ "Illegal value for hex attribute of unicode element."
1273
+ )
1274
+ elif element.tag == "guideline":
1275
+ if validate and len(element):
1276
+ raise GlifLibError("Unknown children in guideline element.")
1277
+ attrib = dict(element.attrib)
1278
+ for attr in ("x", "y", "angle"):
1279
+ if attr in attrib:
1280
+ attrib[attr] = _number(attrib[attr])
1281
+ guidelines.append(attrib)
1282
+ elif element.tag == "anchor":
1283
+ if validate and len(element):
1284
+ raise GlifLibError("Unknown children in anchor element.")
1285
+ attrib = dict(element.attrib)
1286
+ for attr in ("x", "y"):
1287
+ if attr in element.attrib:
1288
+ attrib[attr] = _number(attrib[attr])
1289
+ anchors.append(attrib)
1290
+ elif element.tag == "image":
1291
+ if validate:
1292
+ if haveSeenImage:
1293
+ raise GlifLibError("The image element occurs more than once.")
1294
+ if len(element):
1295
+ raise GlifLibError("Unknown children in image element.")
1296
+ haveSeenImage = True
1297
+ _readImage(glyphObject, element, validate)
1298
+ elif element.tag == "note":
1299
+ if validate and haveSeenNote:
1300
+ raise GlifLibError("The note element occurs more than once.")
1301
+ haveSeenNote = True
1302
+ _readNote(glyphObject, element)
1303
+ elif element.tag == "lib":
1304
+ if validate and haveSeenLib:
1305
+ raise GlifLibError("The lib element occurs more than once.")
1306
+ haveSeenLib = True
1307
+ _readLib(glyphObject, element, validate)
1308
+ else:
1309
+ raise GlifLibError("Unknown element in GLIF: %s" % element)
1310
+ # set the collected unicodes
1311
+ if unicodes:
1312
+ _relaxedSetattr(glyphObject, "unicodes", unicodes)
1313
+ # set the collected guidelines
1314
+ if guidelines:
1315
+ if validate and not guidelinesValidator(guidelines, identifiers):
1316
+ raise GlifLibError("The guidelines are improperly formatted.")
1317
+ _relaxedSetattr(glyphObject, "guidelines", guidelines)
1318
+ # set the collected anchors
1319
+ if anchors:
1320
+ if validate and not anchorsValidator(anchors, identifiers):
1321
+ raise GlifLibError("The anchors are improperly formatted.")
1322
+ _relaxedSetattr(glyphObject, "anchors", anchors)
1323
+
1324
+
1325
+ _READ_GLYPH_FROM_TREE_FUNCS = {
1326
+ GLIFFormatVersion.FORMAT_1_0: _readGlyphFromTreeFormat1,
1327
+ GLIFFormatVersion.FORMAT_2_0: _readGlyphFromTreeFormat2,
1328
+ }
1329
+
1330
+
1331
+ def _readName(glyphObject, root, validate):
1332
+ glyphName = root.get("name")
1333
+ if validate and not glyphName:
1334
+ raise GlifLibError("Empty glyph name in GLIF.")
1335
+ if glyphName and glyphObject is not None:
1336
+ _relaxedSetattr(glyphObject, "name", glyphName)
1337
+
1338
+
1339
+ def _readAdvance(glyphObject, advance):
1340
+ width = _number(advance.get("width", 0))
1341
+ _relaxedSetattr(glyphObject, "width", width)
1342
+ height = _number(advance.get("height", 0))
1343
+ _relaxedSetattr(glyphObject, "height", height)
1344
+
1345
+
1346
+ def _readNote(glyphObject, note):
1347
+ lines = note.text.split("\n")
1348
+ note = "\n".join(line.strip() for line in lines if line.strip())
1349
+ _relaxedSetattr(glyphObject, "note", note)
1350
+
1351
+
1352
+ def _readLib(glyphObject, lib, validate):
1353
+ assert len(lib) == 1
1354
+ child = lib[0]
1355
+ plist = plistlib.fromtree(child)
1356
+ if validate:
1357
+ valid, message = glyphLibValidator(plist)
1358
+ if not valid:
1359
+ raise GlifLibError(message)
1360
+ _relaxedSetattr(glyphObject, "lib", plist)
1361
+
1362
+
1363
+ def _readImage(glyphObject, image, validate):
1364
+ imageData = dict(image.attrib)
1365
+ for attr, default in _transformationInfo:
1366
+ value = imageData.get(attr, default)
1367
+ imageData[attr] = _number(value)
1368
+ if validate and not imageValidator(imageData):
1369
+ raise GlifLibError("The image element is not properly formatted.")
1370
+ _relaxedSetattr(glyphObject, "image", imageData)
1371
+
1372
+
1373
+ # ----------------
1374
+ # GLIF to PointPen
1375
+ # ----------------
1376
+
1377
+ contourAttributesFormat2 = {"identifier"}
1378
+ componentAttributesFormat1 = {
1379
+ "base",
1380
+ "xScale",
1381
+ "xyScale",
1382
+ "yxScale",
1383
+ "yScale",
1384
+ "xOffset",
1385
+ "yOffset",
1386
+ }
1387
+ componentAttributesFormat2 = componentAttributesFormat1 | {"identifier"}
1388
+ pointAttributesFormat1 = {"x", "y", "type", "smooth", "name"}
1389
+ pointAttributesFormat2 = pointAttributesFormat1 | {"identifier"}
1390
+ pointSmoothOptions = {"no", "yes"}
1391
+ pointTypeOptions = {"move", "line", "offcurve", "curve", "qcurve"}
1392
+
1393
+ # format 1
1394
+
1395
+
1396
+ def buildOutlineFormat1(glyphObject, pen, outline, validate):
1397
+ anchors = []
1398
+ for element in outline:
1399
+ if element.tag == "contour":
1400
+ if len(element) == 1:
1401
+ point = element[0]
1402
+ if point.tag == "point":
1403
+ anchor = _buildAnchorFormat1(point, validate)
1404
+ if anchor is not None:
1405
+ anchors.append(anchor)
1406
+ continue
1407
+ if pen is not None:
1408
+ _buildOutlineContourFormat1(pen, element, validate)
1409
+ elif element.tag == "component":
1410
+ if pen is not None:
1411
+ _buildOutlineComponentFormat1(pen, element, validate)
1412
+ else:
1413
+ raise GlifLibError("Unknown element in outline element: %s" % element)
1414
+ if glyphObject is not None and anchors:
1415
+ if validate and not anchorsValidator(anchors):
1416
+ raise GlifLibError("GLIF 1 anchors are not properly formatted.")
1417
+ _relaxedSetattr(glyphObject, "anchors", anchors)
1418
+
1419
+
1420
+ def _buildAnchorFormat1(point, validate):
1421
+ if point.get("type") != "move":
1422
+ return None
1423
+ name = point.get("name")
1424
+ if name is None:
1425
+ return None
1426
+ x = point.get("x")
1427
+ y = point.get("y")
1428
+ if validate and x is None:
1429
+ raise GlifLibError("Required x attribute is missing in point element.")
1430
+ if validate and y is None:
1431
+ raise GlifLibError("Required y attribute is missing in point element.")
1432
+ x = _number(x)
1433
+ y = _number(y)
1434
+ anchor = dict(x=x, y=y, name=name)
1435
+ return anchor
1436
+
1437
+
1438
+ def _buildOutlineContourFormat1(pen, contour, validate):
1439
+ if validate and contour.attrib:
1440
+ raise GlifLibError("Unknown attributes in contour element.")
1441
+ pen.beginPath()
1442
+ if len(contour):
1443
+ massaged = _validateAndMassagePointStructures(
1444
+ contour,
1445
+ pointAttributesFormat1,
1446
+ openContourOffCurveLeniency=True,
1447
+ validate=validate,
1448
+ )
1449
+ _buildOutlinePointsFormat1(pen, massaged)
1450
+ pen.endPath()
1451
+
1452
+
1453
+ def _buildOutlinePointsFormat1(pen, contour):
1454
+ for point in contour:
1455
+ x = point["x"]
1456
+ y = point["y"]
1457
+ segmentType = point["segmentType"]
1458
+ smooth = point["smooth"]
1459
+ name = point["name"]
1460
+ pen.addPoint((x, y), segmentType=segmentType, smooth=smooth, name=name)
1461
+
1462
+
1463
+ def _buildOutlineComponentFormat1(pen, component, validate):
1464
+ if validate:
1465
+ if len(component):
1466
+ raise GlifLibError("Unknown child elements of component element.")
1467
+ for attr in component.attrib.keys():
1468
+ if attr not in componentAttributesFormat1:
1469
+ raise GlifLibError("Unknown attribute in component element: %s" % attr)
1470
+ baseGlyphName = component.get("base")
1471
+ if validate and baseGlyphName is None:
1472
+ raise GlifLibError("The base attribute is not defined in the component.")
1473
+ transformation = []
1474
+ for attr, default in _transformationInfo:
1475
+ value = component.get(attr)
1476
+ if value is None:
1477
+ value = default
1478
+ else:
1479
+ value = _number(value)
1480
+ transformation.append(value)
1481
+ pen.addComponent(baseGlyphName, tuple(transformation))
1482
+
1483
+
1484
+ # format 2
1485
+
1486
+
1487
+ def buildOutlineFormat2(glyphObject, pen, outline, identifiers, validate):
1488
+ for element in outline:
1489
+ if element.tag == "contour":
1490
+ _buildOutlineContourFormat2(pen, element, identifiers, validate)
1491
+ elif element.tag == "component":
1492
+ _buildOutlineComponentFormat2(pen, element, identifiers, validate)
1493
+ else:
1494
+ raise GlifLibError("Unknown element in outline element: %s" % element.tag)
1495
+
1496
+
1497
+ def _buildOutlineContourFormat2(pen, contour, identifiers, validate):
1498
+ if validate:
1499
+ for attr in contour.attrib.keys():
1500
+ if attr not in contourAttributesFormat2:
1501
+ raise GlifLibError("Unknown attribute in contour element: %s" % attr)
1502
+ identifier = contour.get("identifier")
1503
+ if identifier is not None:
1504
+ if validate:
1505
+ if identifier in identifiers:
1506
+ raise GlifLibError(
1507
+ "The identifier %s is used more than once." % identifier
1508
+ )
1509
+ if not identifierValidator(identifier):
1510
+ raise GlifLibError(
1511
+ "The contour identifier %s is not valid." % identifier
1512
+ )
1513
+ identifiers.add(identifier)
1514
+ try:
1515
+ pen.beginPath(identifier=identifier)
1516
+ except TypeError:
1517
+ pen.beginPath()
1518
+ warn(
1519
+ "The beginPath method needs an identifier kwarg. The contour's identifier value has been discarded.",
1520
+ DeprecationWarning,
1521
+ )
1522
+ if len(contour):
1523
+ massaged = _validateAndMassagePointStructures(
1524
+ contour, pointAttributesFormat2, validate=validate
1525
+ )
1526
+ _buildOutlinePointsFormat2(pen, massaged, identifiers, validate)
1527
+ pen.endPath()
1528
+
1529
+
1530
+ def _buildOutlinePointsFormat2(pen, contour, identifiers, validate):
1531
+ for point in contour:
1532
+ x = point["x"]
1533
+ y = point["y"]
1534
+ segmentType = point["segmentType"]
1535
+ smooth = point["smooth"]
1536
+ name = point["name"]
1537
+ identifier = point.get("identifier")
1538
+ if identifier is not None:
1539
+ if validate:
1540
+ if identifier in identifiers:
1541
+ raise GlifLibError(
1542
+ "The identifier %s is used more than once." % identifier
1543
+ )
1544
+ if not identifierValidator(identifier):
1545
+ raise GlifLibError("The identifier %s is not valid." % identifier)
1546
+ identifiers.add(identifier)
1547
+ try:
1548
+ pen.addPoint(
1549
+ (x, y),
1550
+ segmentType=segmentType,
1551
+ smooth=smooth,
1552
+ name=name,
1553
+ identifier=identifier,
1554
+ )
1555
+ except TypeError:
1556
+ pen.addPoint((x, y), segmentType=segmentType, smooth=smooth, name=name)
1557
+ warn(
1558
+ "The addPoint method needs an identifier kwarg. The point's identifier value has been discarded.",
1559
+ DeprecationWarning,
1560
+ )
1561
+
1562
+
1563
+ def _buildOutlineComponentFormat2(pen, component, identifiers, validate):
1564
+ if validate:
1565
+ if len(component):
1566
+ raise GlifLibError("Unknown child elements of component element.")
1567
+ for attr in component.attrib.keys():
1568
+ if attr not in componentAttributesFormat2:
1569
+ raise GlifLibError("Unknown attribute in component element: %s" % attr)
1570
+ baseGlyphName = component.get("base")
1571
+ if validate and baseGlyphName is None:
1572
+ raise GlifLibError("The base attribute is not defined in the component.")
1573
+ transformation = []
1574
+ for attr, default in _transformationInfo:
1575
+ value = component.get(attr)
1576
+ if value is None:
1577
+ value = default
1578
+ else:
1579
+ value = _number(value)
1580
+ transformation.append(value)
1581
+ identifier = component.get("identifier")
1582
+ if identifier is not None:
1583
+ if validate:
1584
+ if identifier in identifiers:
1585
+ raise GlifLibError(
1586
+ "The identifier %s is used more than once." % identifier
1587
+ )
1588
+ if validate and not identifierValidator(identifier):
1589
+ raise GlifLibError("The identifier %s is not valid." % identifier)
1590
+ identifiers.add(identifier)
1591
+ try:
1592
+ pen.addComponent(baseGlyphName, tuple(transformation), identifier=identifier)
1593
+ except TypeError:
1594
+ pen.addComponent(baseGlyphName, tuple(transformation))
1595
+ warn(
1596
+ "The addComponent method needs an identifier kwarg. The component's identifier value has been discarded.",
1597
+ DeprecationWarning,
1598
+ )
1599
+
1600
+
1601
+ # all formats
1602
+
1603
+
1604
+ def _validateAndMassagePointStructures(
1605
+ contour, pointAttributes, openContourOffCurveLeniency=False, validate=True
1606
+ ):
1607
+ if not len(contour):
1608
+ return
1609
+ # store some data for later validation
1610
+ lastOnCurvePoint = None
1611
+ haveOffCurvePoint = False
1612
+ # validate and massage the individual point elements
1613
+ massaged = []
1614
+ for index, element in enumerate(contour):
1615
+ # not <point>
1616
+ if element.tag != "point":
1617
+ raise GlifLibError(
1618
+ "Unknown child element (%s) of contour element." % element.tag
1619
+ )
1620
+ point = dict(element.attrib)
1621
+ massaged.append(point)
1622
+ if validate:
1623
+ # unknown attributes
1624
+ for attr in point.keys():
1625
+ if attr not in pointAttributes:
1626
+ raise GlifLibError("Unknown attribute in point element: %s" % attr)
1627
+ # search for unknown children
1628
+ if len(element):
1629
+ raise GlifLibError("Unknown child elements in point element.")
1630
+ # x and y are required
1631
+ for attr in ("x", "y"):
1632
+ try:
1633
+ point[attr] = _number(point[attr])
1634
+ except KeyError as e:
1635
+ raise GlifLibError(
1636
+ f"Required {attr} attribute is missing in point element."
1637
+ ) from e
1638
+ # segment type
1639
+ pointType = point.pop("type", "offcurve")
1640
+ if validate and pointType not in pointTypeOptions:
1641
+ raise GlifLibError("Unknown point type: %s" % pointType)
1642
+ if pointType == "offcurve":
1643
+ pointType = None
1644
+ point["segmentType"] = pointType
1645
+ if pointType is None:
1646
+ haveOffCurvePoint = True
1647
+ else:
1648
+ lastOnCurvePoint = index
1649
+ # move can only occur as the first point
1650
+ if validate and pointType == "move" and index != 0:
1651
+ raise GlifLibError(
1652
+ "A move point occurs after the first point in the contour."
1653
+ )
1654
+ # smooth is optional
1655
+ smooth = point.get("smooth", "no")
1656
+ if validate and smooth is not None:
1657
+ if smooth not in pointSmoothOptions:
1658
+ raise GlifLibError("Unknown point smooth value: %s" % smooth)
1659
+ smooth = smooth == "yes"
1660
+ point["smooth"] = smooth
1661
+ # smooth can only be applied to curve and qcurve
1662
+ if validate and smooth and pointType is None:
1663
+ raise GlifLibError("smooth attribute set in an offcurve point.")
1664
+ # name is optional
1665
+ if "name" not in element.attrib:
1666
+ point["name"] = None
1667
+ if openContourOffCurveLeniency:
1668
+ # remove offcurves that precede a move. this is technically illegal,
1669
+ # but we let it slide because there are fonts out there in the wild like this.
1670
+ if massaged[0]["segmentType"] == "move":
1671
+ count = 0
1672
+ for point in reversed(massaged):
1673
+ if point["segmentType"] is None:
1674
+ count += 1
1675
+ else:
1676
+ break
1677
+ if count:
1678
+ massaged = massaged[:-count]
1679
+ # validate the off-curves in the segments
1680
+ if validate and haveOffCurvePoint and lastOnCurvePoint is not None:
1681
+ # we only care about how many offCurves there are before an onCurve
1682
+ # filter out the trailing offCurves
1683
+ offCurvesCount = len(massaged) - 1 - lastOnCurvePoint
1684
+ for point in massaged:
1685
+ segmentType = point["segmentType"]
1686
+ if segmentType is None:
1687
+ offCurvesCount += 1
1688
+ else:
1689
+ if offCurvesCount:
1690
+ # move and line can't be preceded by off-curves
1691
+ if segmentType == "move":
1692
+ # this will have been filtered out already
1693
+ raise GlifLibError("move can not have an offcurve.")
1694
+ elif segmentType == "line":
1695
+ raise GlifLibError("line can not have an offcurve.")
1696
+ elif segmentType == "curve":
1697
+ if offCurvesCount > 2:
1698
+ raise GlifLibError("Too many offcurves defined for curve.")
1699
+ elif segmentType == "qcurve":
1700
+ pass
1701
+ else:
1702
+ # unknown segment type. it'll be caught later.
1703
+ pass
1704
+ offCurvesCount = 0
1705
+ return massaged
1706
+
1707
+
1708
+ # ---------------------
1709
+ # Misc Helper Functions
1710
+ # ---------------------
1711
+
1712
+
1713
+ def _relaxedSetattr(object, attr, value):
1714
+ try:
1715
+ setattr(object, attr, value)
1716
+ except AttributeError:
1717
+ pass
1718
+
1719
+
1720
+ def _number(s):
1721
+ """
1722
+ Given a numeric string, return an integer or a float, whichever
1723
+ the string indicates. _number("1") will return the integer 1,
1724
+ _number("1.0") will return the float 1.0.
1725
+
1726
+ >>> _number("1")
1727
+ 1
1728
+ >>> _number("1.0")
1729
+ 1.0
1730
+ >>> _number("a") # doctest: +IGNORE_EXCEPTION_DETAIL
1731
+ Traceback (most recent call last):
1732
+ ...
1733
+ GlifLibError: Could not convert a to an int or float.
1734
+ """
1735
+ try:
1736
+ n = int(s)
1737
+ return n
1738
+ except ValueError:
1739
+ pass
1740
+ try:
1741
+ n = float(s)
1742
+ return n
1743
+ except ValueError:
1744
+ raise GlifLibError("Could not convert %s to an int or float." % s)
1745
+
1746
+
1747
+ # --------------------
1748
+ # Rapid Value Fetching
1749
+ # --------------------
1750
+
1751
+ # base
1752
+
1753
+
1754
+ class _DoneParsing(Exception):
1755
+ pass
1756
+
1757
+
1758
+ class _BaseParser:
1759
+ def __init__(self):
1760
+ self._elementStack = []
1761
+
1762
+ def parse(self, text):
1763
+ from xml.parsers.expat import ParserCreate
1764
+
1765
+ parser = ParserCreate()
1766
+ parser.StartElementHandler = self.startElementHandler
1767
+ parser.EndElementHandler = self.endElementHandler
1768
+ parser.Parse(text, 1)
1769
+
1770
+ def startElementHandler(self, name, attrs):
1771
+ self._elementStack.append(name)
1772
+
1773
+ def endElementHandler(self, name):
1774
+ other = self._elementStack.pop(-1)
1775
+ assert other == name
1776
+
1777
+
1778
+ # unicodes
1779
+
1780
+
1781
+ def _fetchUnicodes(glif):
1782
+ """
1783
+ Get a list of unicodes listed in glif.
1784
+ """
1785
+ parser = _FetchUnicodesParser()
1786
+ parser.parse(glif)
1787
+ return parser.unicodes
1788
+
1789
+
1790
+ class _FetchUnicodesParser(_BaseParser):
1791
+ def __init__(self):
1792
+ self.unicodes = []
1793
+ super().__init__()
1794
+
1795
+ def startElementHandler(self, name, attrs):
1796
+ if (
1797
+ name == "unicode"
1798
+ and self._elementStack
1799
+ and self._elementStack[-1] == "glyph"
1800
+ ):
1801
+ value = attrs.get("hex")
1802
+ if value is not None:
1803
+ try:
1804
+ value = int(value, 16)
1805
+ if value not in self.unicodes:
1806
+ self.unicodes.append(value)
1807
+ except ValueError:
1808
+ pass
1809
+ super().startElementHandler(name, attrs)
1810
+
1811
+
1812
+ # image
1813
+
1814
+
1815
+ def _fetchImageFileName(glif):
1816
+ """
1817
+ The image file name (if any) from glif.
1818
+ """
1819
+ parser = _FetchImageFileNameParser()
1820
+ try:
1821
+ parser.parse(glif)
1822
+ except _DoneParsing:
1823
+ pass
1824
+ return parser.fileName
1825
+
1826
+
1827
+ class _FetchImageFileNameParser(_BaseParser):
1828
+ def __init__(self):
1829
+ self.fileName = None
1830
+ super().__init__()
1831
+
1832
+ def startElementHandler(self, name, attrs):
1833
+ if name == "image" and self._elementStack and self._elementStack[-1] == "glyph":
1834
+ self.fileName = attrs.get("fileName")
1835
+ raise _DoneParsing
1836
+ super().startElementHandler(name, attrs)
1837
+
1838
+
1839
+ # component references
1840
+
1841
+
1842
+ def _fetchComponentBases(glif):
1843
+ """
1844
+ Get a list of component base glyphs listed in glif.
1845
+ """
1846
+ parser = _FetchComponentBasesParser()
1847
+ try:
1848
+ parser.parse(glif)
1849
+ except _DoneParsing:
1850
+ pass
1851
+ return list(parser.bases)
1852
+
1853
+
1854
+ class _FetchComponentBasesParser(_BaseParser):
1855
+ def __init__(self):
1856
+ self.bases = []
1857
+ super().__init__()
1858
+
1859
+ def startElementHandler(self, name, attrs):
1860
+ if (
1861
+ name == "component"
1862
+ and self._elementStack
1863
+ and self._elementStack[-1] == "outline"
1864
+ ):
1865
+ base = attrs.get("base")
1866
+ if base is not None:
1867
+ self.bases.append(base)
1868
+ super().startElementHandler(name, attrs)
1869
+
1870
+ def endElementHandler(self, name):
1871
+ if name == "outline":
1872
+ raise _DoneParsing
1873
+ super().endElementHandler(name)
1874
+
1875
+
1876
+ # --------------
1877
+ # GLIF Point Pen
1878
+ # --------------
1879
+
1880
+ _transformationInfo = [
1881
+ # field name, default value
1882
+ ("xScale", 1),
1883
+ ("xyScale", 0),
1884
+ ("yxScale", 0),
1885
+ ("yScale", 1),
1886
+ ("xOffset", 0),
1887
+ ("yOffset", 0),
1888
+ ]
1889
+
1890
+
1891
+ class GLIFPointPen(AbstractPointPen):
1892
+ """
1893
+ Helper class using the PointPen protocol to write the <outline>
1894
+ part of .glif files.
1895
+ """
1896
+
1897
+ def __init__(self, element, formatVersion=None, identifiers=None, validate=True):
1898
+ if identifiers is None:
1899
+ identifiers = set()
1900
+ self.formatVersion = GLIFFormatVersion(formatVersion)
1901
+ self.identifiers = identifiers
1902
+ self.outline = element
1903
+ self.contour = None
1904
+ self.prevOffCurveCount = 0
1905
+ self.prevPointTypes = []
1906
+ self.validate = validate
1907
+
1908
+ def beginPath(self, identifier=None, **kwargs):
1909
+ attrs = OrderedDict()
1910
+ if identifier is not None and self.formatVersion.major >= 2:
1911
+ if self.validate:
1912
+ if identifier in self.identifiers:
1913
+ raise GlifLibError(
1914
+ "identifier used more than once: %s" % identifier
1915
+ )
1916
+ if not identifierValidator(identifier):
1917
+ raise GlifLibError(
1918
+ "identifier not formatted properly: %s" % identifier
1919
+ )
1920
+ attrs["identifier"] = identifier
1921
+ self.identifiers.add(identifier)
1922
+ self.contour = etree.SubElement(self.outline, "contour", attrs)
1923
+ self.prevOffCurveCount = 0
1924
+
1925
+ def endPath(self):
1926
+ if self.prevPointTypes and self.prevPointTypes[0] == "move":
1927
+ if self.validate and self.prevPointTypes[-1] == "offcurve":
1928
+ raise GlifLibError("open contour has loose offcurve point")
1929
+ # prevent lxml from writing self-closing tags
1930
+ if not len(self.contour):
1931
+ self.contour.text = "\n "
1932
+ self.contour = None
1933
+ self.prevPointType = None
1934
+ self.prevOffCurveCount = 0
1935
+ self.prevPointTypes = []
1936
+
1937
+ def addPoint(
1938
+ self, pt, segmentType=None, smooth=None, name=None, identifier=None, **kwargs
1939
+ ):
1940
+ attrs = OrderedDict()
1941
+ # coordinates
1942
+ if pt is not None:
1943
+ if self.validate:
1944
+ for coord in pt:
1945
+ if not isinstance(coord, numberTypes):
1946
+ raise GlifLibError("coordinates must be int or float")
1947
+ attrs["x"] = repr(pt[0])
1948
+ attrs["y"] = repr(pt[1])
1949
+ # segment type
1950
+ if segmentType == "offcurve":
1951
+ segmentType = None
1952
+ if self.validate:
1953
+ if segmentType == "move" and self.prevPointTypes:
1954
+ raise GlifLibError(
1955
+ "move occurs after a point has already been added to the contour."
1956
+ )
1957
+ if (
1958
+ segmentType in ("move", "line")
1959
+ and self.prevPointTypes
1960
+ and self.prevPointTypes[-1] == "offcurve"
1961
+ ):
1962
+ raise GlifLibError("offcurve occurs before %s point." % segmentType)
1963
+ if segmentType == "curve" and self.prevOffCurveCount > 2:
1964
+ raise GlifLibError("too many offcurve points before curve point.")
1965
+ if segmentType is not None:
1966
+ attrs["type"] = segmentType
1967
+ else:
1968
+ segmentType = "offcurve"
1969
+ if segmentType == "offcurve":
1970
+ self.prevOffCurveCount += 1
1971
+ else:
1972
+ self.prevOffCurveCount = 0
1973
+ self.prevPointTypes.append(segmentType)
1974
+ # smooth
1975
+ if smooth:
1976
+ if self.validate and segmentType == "offcurve":
1977
+ raise GlifLibError("can't set smooth in an offcurve point.")
1978
+ attrs["smooth"] = "yes"
1979
+ # name
1980
+ if name is not None:
1981
+ attrs["name"] = name
1982
+ # identifier
1983
+ if identifier is not None and self.formatVersion.major >= 2:
1984
+ if self.validate:
1985
+ if identifier in self.identifiers:
1986
+ raise GlifLibError(
1987
+ "identifier used more than once: %s" % identifier
1988
+ )
1989
+ if not identifierValidator(identifier):
1990
+ raise GlifLibError(
1991
+ "identifier not formatted properly: %s" % identifier
1992
+ )
1993
+ attrs["identifier"] = identifier
1994
+ self.identifiers.add(identifier)
1995
+ etree.SubElement(self.contour, "point", attrs)
1996
+
1997
+ def addComponent(self, glyphName, transformation, identifier=None, **kwargs):
1998
+ attrs = OrderedDict([("base", glyphName)])
1999
+ for (attr, default), value in zip(_transformationInfo, transformation):
2000
+ if self.validate and not isinstance(value, numberTypes):
2001
+ raise GlifLibError("transformation values must be int or float")
2002
+ if value != default:
2003
+ attrs[attr] = repr(value)
2004
+ if identifier is not None and self.formatVersion.major >= 2:
2005
+ if self.validate:
2006
+ if identifier in self.identifiers:
2007
+ raise GlifLibError(
2008
+ "identifier used more than once: %s" % identifier
2009
+ )
2010
+ if self.validate and not identifierValidator(identifier):
2011
+ raise GlifLibError(
2012
+ "identifier not formatted properly: %s" % identifier
2013
+ )
2014
+ attrs["identifier"] = identifier
2015
+ self.identifiers.add(identifier)
2016
+ etree.SubElement(self.outline, "component", attrs)
2017
+
2018
+
2019
+ if __name__ == "__main__":
2020
+ import doctest
2021
+
2022
+ doctest.testmod()