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