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