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