fonttools 4.55.6__cp311-cp311-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 (329) hide show
  1. fontTools/__init__.py +8 -0
  2. fontTools/__main__.py +35 -0
  3. fontTools/afmLib.py +439 -0
  4. fontTools/agl.py +5233 -0
  5. fontTools/cffLib/CFF2ToCFF.py +203 -0
  6. fontTools/cffLib/CFFToCFF2.py +305 -0
  7. fontTools/cffLib/__init__.py +3659 -0
  8. fontTools/cffLib/specializer.py +924 -0
  9. fontTools/cffLib/transforms.py +490 -0
  10. fontTools/cffLib/width.py +210 -0
  11. fontTools/colorLib/__init__.py +0 -0
  12. fontTools/colorLib/builder.py +664 -0
  13. fontTools/colorLib/errors.py +2 -0
  14. fontTools/colorLib/geometry.py +143 -0
  15. fontTools/colorLib/table_builder.py +223 -0
  16. fontTools/colorLib/unbuilder.py +81 -0
  17. fontTools/config/__init__.py +75 -0
  18. fontTools/cu2qu/__init__.py +15 -0
  19. fontTools/cu2qu/__main__.py +6 -0
  20. fontTools/cu2qu/benchmark.py +54 -0
  21. fontTools/cu2qu/cli.py +198 -0
  22. fontTools/cu2qu/cu2qu.c +14829 -0
  23. fontTools/cu2qu/cu2qu.cpython-311-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 +253 -0
  31. fontTools/designspaceLib/types.py +147 -0
  32. fontTools/encodings/MacRoman.py +258 -0
  33. fontTools/encodings/StandardEncoding.py +258 -0
  34. fontTools/encodings/__init__.py +1 -0
  35. fontTools/encodings/codecs.py +135 -0
  36. fontTools/feaLib/__init__.py +4 -0
  37. fontTools/feaLib/__main__.py +78 -0
  38. fontTools/feaLib/ast.py +2134 -0
  39. fontTools/feaLib/builder.py +1747 -0
  40. fontTools/feaLib/error.py +22 -0
  41. fontTools/feaLib/lexer.c +17986 -0
  42. fontTools/feaLib/lexer.cpython-311-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 +2359 -0
  47. fontTools/feaLib/variableScalar.py +113 -0
  48. fontTools/fontBuilder.py +1008 -0
  49. fontTools/help.py +36 -0
  50. fontTools/merge/__init__.py +248 -0
  51. fontTools/merge/__main__.py +6 -0
  52. fontTools/merge/base.py +81 -0
  53. fontTools/merge/cmap.py +141 -0
  54. fontTools/merge/layout.py +526 -0
  55. fontTools/merge/options.py +85 -0
  56. fontTools/merge/tables.py +341 -0
  57. fontTools/merge/unicode.py +78 -0
  58. fontTools/merge/util.py +143 -0
  59. fontTools/misc/__init__.py +1 -0
  60. fontTools/misc/arrayTools.py +424 -0
  61. fontTools/misc/bezierTools.c +41831 -0
  62. fontTools/misc/bezierTools.cpython-311-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 +479 -0
  72. fontTools/misc/filenames.py +245 -0
  73. fontTools/misc/fixedTools.py +253 -0
  74. fontTools/misc/intTools.py +25 -0
  75. fontTools/misc/iterTools.py +12 -0
  76. fontTools/misc/lazyTools.py +42 -0
  77. fontTools/misc/loggingTools.py +543 -0
  78. fontTools/misc/macCreatorType.py +56 -0
  79. fontTools/misc/macRes.py +261 -0
  80. fontTools/misc/plistlib/__init__.py +681 -0
  81. fontTools/misc/plistlib/py.typed +0 -0
  82. fontTools/misc/psCharStrings.py +1496 -0
  83. fontTools/misc/psLib.py +398 -0
  84. fontTools/misc/psOperators.py +572 -0
  85. fontTools/misc/py23.py +96 -0
  86. fontTools/misc/roundTools.py +110 -0
  87. fontTools/misc/sstruct.py +231 -0
  88. fontTools/misc/symfont.py +244 -0
  89. fontTools/misc/testTools.py +229 -0
  90. fontTools/misc/textTools.py +154 -0
  91. fontTools/misc/timeTools.py +88 -0
  92. fontTools/misc/transform.py +516 -0
  93. fontTools/misc/treeTools.py +45 -0
  94. fontTools/misc/vector.py +147 -0
  95. fontTools/misc/visitor.py +142 -0
  96. fontTools/misc/xmlReader.py +188 -0
  97. fontTools/misc/xmlWriter.py +204 -0
  98. fontTools/mtiLib/__init__.py +1402 -0
  99. fontTools/mtiLib/__main__.py +5 -0
  100. fontTools/otlLib/__init__.py +1 -0
  101. fontTools/otlLib/builder.py +3221 -0
  102. fontTools/otlLib/error.py +11 -0
  103. fontTools/otlLib/maxContextCalc.py +96 -0
  104. fontTools/otlLib/optimize/__init__.py +53 -0
  105. fontTools/otlLib/optimize/__main__.py +6 -0
  106. fontTools/otlLib/optimize/gpos.py +453 -0
  107. fontTools/pens/__init__.py +1 -0
  108. fontTools/pens/areaPen.py +52 -0
  109. fontTools/pens/basePen.py +475 -0
  110. fontTools/pens/boundsPen.py +98 -0
  111. fontTools/pens/cairoPen.py +26 -0
  112. fontTools/pens/cocoaPen.py +26 -0
  113. fontTools/pens/cu2quPen.py +325 -0
  114. fontTools/pens/explicitClosingLinePen.py +101 -0
  115. fontTools/pens/filterPen.py +241 -0
  116. fontTools/pens/freetypePen.py +462 -0
  117. fontTools/pens/hashPointPen.py +89 -0
  118. fontTools/pens/momentsPen.c +13448 -0
  119. fontTools/pens/momentsPen.cpython-311-x86_64-linux-musl.so +0 -0
  120. fontTools/pens/momentsPen.py +879 -0
  121. fontTools/pens/perimeterPen.py +69 -0
  122. fontTools/pens/pointInsidePen.py +192 -0
  123. fontTools/pens/pointPen.py +600 -0
  124. fontTools/pens/qtPen.py +29 -0
  125. fontTools/pens/qu2cuPen.py +105 -0
  126. fontTools/pens/quartzPen.py +43 -0
  127. fontTools/pens/recordingPen.py +335 -0
  128. fontTools/pens/reportLabPen.py +79 -0
  129. fontTools/pens/reverseContourPen.py +96 -0
  130. fontTools/pens/roundingPen.py +130 -0
  131. fontTools/pens/statisticsPen.py +312 -0
  132. fontTools/pens/svgPathPen.py +310 -0
  133. fontTools/pens/t2CharStringPen.py +68 -0
  134. fontTools/pens/teePen.py +55 -0
  135. fontTools/pens/transformPen.py +115 -0
  136. fontTools/pens/ttGlyphPen.py +335 -0
  137. fontTools/pens/wxPen.py +29 -0
  138. fontTools/qu2cu/__init__.py +15 -0
  139. fontTools/qu2cu/__main__.py +7 -0
  140. fontTools/qu2cu/benchmark.py +56 -0
  141. fontTools/qu2cu/cli.py +125 -0
  142. fontTools/qu2cu/qu2cu.c +16269 -0
  143. fontTools/qu2cu/qu2cu.cpython-311-x86_64-linux-musl.so +0 -0
  144. fontTools/qu2cu/qu2cu.py +405 -0
  145. fontTools/subset/__init__.py +3838 -0
  146. fontTools/subset/__main__.py +6 -0
  147. fontTools/subset/cff.py +184 -0
  148. fontTools/subset/svg.py +253 -0
  149. fontTools/subset/util.py +25 -0
  150. fontTools/svgLib/__init__.py +3 -0
  151. fontTools/svgLib/path/__init__.py +65 -0
  152. fontTools/svgLib/path/arc.py +154 -0
  153. fontTools/svgLib/path/parser.py +322 -0
  154. fontTools/svgLib/path/shapes.py +183 -0
  155. fontTools/t1Lib/__init__.py +648 -0
  156. fontTools/tfmLib.py +460 -0
  157. fontTools/ttLib/__init__.py +26 -0
  158. fontTools/ttLib/__main__.py +109 -0
  159. fontTools/ttLib/macUtils.py +54 -0
  160. fontTools/ttLib/removeOverlaps.py +393 -0
  161. fontTools/ttLib/reorderGlyphs.py +284 -0
  162. fontTools/ttLib/scaleUpem.py +436 -0
  163. fontTools/ttLib/sfnt.py +662 -0
  164. fontTools/ttLib/standardGlyphOrder.py +271 -0
  165. fontTools/ttLib/tables/B_A_S_E_.py +14 -0
  166. fontTools/ttLib/tables/BitmapGlyphMetrics.py +64 -0
  167. fontTools/ttLib/tables/C_B_D_T_.py +113 -0
  168. fontTools/ttLib/tables/C_B_L_C_.py +19 -0
  169. fontTools/ttLib/tables/C_F_F_.py +61 -0
  170. fontTools/ttLib/tables/C_F_F__2.py +26 -0
  171. fontTools/ttLib/tables/C_O_L_R_.py +165 -0
  172. fontTools/ttLib/tables/C_P_A_L_.py +305 -0
  173. fontTools/ttLib/tables/D_S_I_G_.py +158 -0
  174. fontTools/ttLib/tables/D__e_b_g.py +17 -0
  175. fontTools/ttLib/tables/DefaultTable.py +49 -0
  176. fontTools/ttLib/tables/E_B_D_T_.py +835 -0
  177. fontTools/ttLib/tables/E_B_L_C_.py +718 -0
  178. fontTools/ttLib/tables/F_F_T_M_.py +52 -0
  179. fontTools/ttLib/tables/F__e_a_t.py +149 -0
  180. fontTools/ttLib/tables/G_D_E_F_.py +13 -0
  181. fontTools/ttLib/tables/G_M_A_P_.py +148 -0
  182. fontTools/ttLib/tables/G_P_K_G_.py +133 -0
  183. fontTools/ttLib/tables/G_P_O_S_.py +14 -0
  184. fontTools/ttLib/tables/G_S_U_B_.py +13 -0
  185. fontTools/ttLib/tables/G__l_a_t.py +235 -0
  186. fontTools/ttLib/tables/G__l_o_c.py +85 -0
  187. fontTools/ttLib/tables/H_V_A_R_.py +13 -0
  188. fontTools/ttLib/tables/J_S_T_F_.py +13 -0
  189. fontTools/ttLib/tables/L_T_S_H_.py +58 -0
  190. fontTools/ttLib/tables/M_A_T_H_.py +13 -0
  191. fontTools/ttLib/tables/M_E_T_A_.py +352 -0
  192. fontTools/ttLib/tables/M_V_A_R_.py +13 -0
  193. fontTools/ttLib/tables/O_S_2f_2.py +752 -0
  194. fontTools/ttLib/tables/S_I_N_G_.py +99 -0
  195. fontTools/ttLib/tables/S_T_A_T_.py +15 -0
  196. fontTools/ttLib/tables/S_V_G_.py +223 -0
  197. fontTools/ttLib/tables/S__i_l_f.py +1040 -0
  198. fontTools/ttLib/tables/S__i_l_l.py +92 -0
  199. fontTools/ttLib/tables/T_S_I_B_.py +13 -0
  200. fontTools/ttLib/tables/T_S_I_C_.py +14 -0
  201. fontTools/ttLib/tables/T_S_I_D_.py +13 -0
  202. fontTools/ttLib/tables/T_S_I_J_.py +13 -0
  203. fontTools/ttLib/tables/T_S_I_P_.py +13 -0
  204. fontTools/ttLib/tables/T_S_I_S_.py +13 -0
  205. fontTools/ttLib/tables/T_S_I_V_.py +26 -0
  206. fontTools/ttLib/tables/T_S_I__0.py +59 -0
  207. fontTools/ttLib/tables/T_S_I__1.py +166 -0
  208. fontTools/ttLib/tables/T_S_I__2.py +17 -0
  209. fontTools/ttLib/tables/T_S_I__3.py +22 -0
  210. fontTools/ttLib/tables/T_S_I__5.py +49 -0
  211. fontTools/ttLib/tables/T_T_F_A_.py +14 -0
  212. fontTools/ttLib/tables/TupleVariation.py +884 -0
  213. fontTools/ttLib/tables/V_A_R_C_.py +12 -0
  214. fontTools/ttLib/tables/V_D_M_X_.py +249 -0
  215. fontTools/ttLib/tables/V_O_R_G_.py +165 -0
  216. fontTools/ttLib/tables/V_V_A_R_.py +13 -0
  217. fontTools/ttLib/tables/__init__.py +97 -0
  218. fontTools/ttLib/tables/_a_n_k_r.py +15 -0
  219. fontTools/ttLib/tables/_a_v_a_r.py +191 -0
  220. fontTools/ttLib/tables/_b_s_l_n.py +15 -0
  221. fontTools/ttLib/tables/_c_i_d_g.py +24 -0
  222. fontTools/ttLib/tables/_c_m_a_p.py +1578 -0
  223. fontTools/ttLib/tables/_c_v_a_r.py +94 -0
  224. fontTools/ttLib/tables/_c_v_t.py +55 -0
  225. fontTools/ttLib/tables/_f_e_a_t.py +15 -0
  226. fontTools/ttLib/tables/_f_p_g_m.py +60 -0
  227. fontTools/ttLib/tables/_f_v_a_r.py +261 -0
  228. fontTools/ttLib/tables/_g_a_s_p.py +63 -0
  229. fontTools/ttLib/tables/_g_c_i_d.py +13 -0
  230. fontTools/ttLib/tables/_g_l_y_f.py +2311 -0
  231. fontTools/ttLib/tables/_g_v_a_r.py +292 -0
  232. fontTools/ttLib/tables/_h_d_m_x.py +127 -0
  233. fontTools/ttLib/tables/_h_e_a_d.py +130 -0
  234. fontTools/ttLib/tables/_h_h_e_a.py +147 -0
  235. fontTools/ttLib/tables/_h_m_t_x.py +160 -0
  236. fontTools/ttLib/tables/_k_e_r_n.py +289 -0
  237. fontTools/ttLib/tables/_l_c_a_r.py +13 -0
  238. fontTools/ttLib/tables/_l_o_c_a.py +70 -0
  239. fontTools/ttLib/tables/_l_t_a_g.py +72 -0
  240. fontTools/ttLib/tables/_m_a_x_p.py +147 -0
  241. fontTools/ttLib/tables/_m_e_t_a.py +112 -0
  242. fontTools/ttLib/tables/_m_o_r_t.py +14 -0
  243. fontTools/ttLib/tables/_m_o_r_x.py +15 -0
  244. fontTools/ttLib/tables/_n_a_m_e.py +1237 -0
  245. fontTools/ttLib/tables/_o_p_b_d.py +14 -0
  246. fontTools/ttLib/tables/_p_o_s_t.py +317 -0
  247. fontTools/ttLib/tables/_p_r_e_p.py +16 -0
  248. fontTools/ttLib/tables/_p_r_o_p.py +12 -0
  249. fontTools/ttLib/tables/_s_b_i_x.py +129 -0
  250. fontTools/ttLib/tables/_t_r_a_k.py +332 -0
  251. fontTools/ttLib/tables/_v_h_e_a.py +139 -0
  252. fontTools/ttLib/tables/_v_m_t_x.py +19 -0
  253. fontTools/ttLib/tables/asciiTable.py +20 -0
  254. fontTools/ttLib/tables/grUtils.py +92 -0
  255. fontTools/ttLib/tables/otBase.py +1465 -0
  256. fontTools/ttLib/tables/otConverters.py +2065 -0
  257. fontTools/ttLib/tables/otData.py +6400 -0
  258. fontTools/ttLib/tables/otTables.py +2700 -0
  259. fontTools/ttLib/tables/otTraverse.py +162 -0
  260. fontTools/ttLib/tables/sbixGlyph.py +149 -0
  261. fontTools/ttLib/tables/sbixStrike.py +177 -0
  262. fontTools/ttLib/tables/table_API_readme.txt +91 -0
  263. fontTools/ttLib/tables/ttProgram.py +594 -0
  264. fontTools/ttLib/ttCollection.py +125 -0
  265. fontTools/ttLib/ttFont.py +1155 -0
  266. fontTools/ttLib/ttGlyphSet.py +500 -0
  267. fontTools/ttLib/ttVisitor.py +32 -0
  268. fontTools/ttLib/woff2.py +1683 -0
  269. fontTools/ttx.py +467 -0
  270. fontTools/ufoLib/__init__.py +2477 -0
  271. fontTools/ufoLib/converters.py +334 -0
  272. fontTools/ufoLib/errors.py +22 -0
  273. fontTools/ufoLib/etree.py +6 -0
  274. fontTools/ufoLib/filenames.py +291 -0
  275. fontTools/ufoLib/glifLib.py +2022 -0
  276. fontTools/ufoLib/kerning.py +91 -0
  277. fontTools/ufoLib/plistlib.py +47 -0
  278. fontTools/ufoLib/pointPen.py +6 -0
  279. fontTools/ufoLib/utils.py +76 -0
  280. fontTools/ufoLib/validators.py +1186 -0
  281. fontTools/unicode.py +50 -0
  282. fontTools/unicodedata/Blocks.py +802 -0
  283. fontTools/unicodedata/OTTags.py +50 -0
  284. fontTools/unicodedata/ScriptExtensions.py +806 -0
  285. fontTools/unicodedata/Scripts.py +3618 -0
  286. fontTools/unicodedata/__init__.py +298 -0
  287. fontTools/varLib/__init__.py +1511 -0
  288. fontTools/varLib/__main__.py +6 -0
  289. fontTools/varLib/avar.py +260 -0
  290. fontTools/varLib/avarPlanner.py +1004 -0
  291. fontTools/varLib/builder.py +215 -0
  292. fontTools/varLib/cff.py +631 -0
  293. fontTools/varLib/errors.py +219 -0
  294. fontTools/varLib/featureVars.py +689 -0
  295. fontTools/varLib/instancer/__init__.py +1937 -0
  296. fontTools/varLib/instancer/__main__.py +5 -0
  297. fontTools/varLib/instancer/featureVars.py +190 -0
  298. fontTools/varLib/instancer/names.py +388 -0
  299. fontTools/varLib/instancer/solver.py +309 -0
  300. fontTools/varLib/interpolatable.py +1209 -0
  301. fontTools/varLib/interpolatableHelpers.py +396 -0
  302. fontTools/varLib/interpolatablePlot.py +1269 -0
  303. fontTools/varLib/interpolatableTestContourOrder.py +82 -0
  304. fontTools/varLib/interpolatableTestStartingPoint.py +107 -0
  305. fontTools/varLib/interpolate_layout.py +124 -0
  306. fontTools/varLib/iup.c +19154 -0
  307. fontTools/varLib/iup.cpython-311-x86_64-linux-musl.so +0 -0
  308. fontTools/varLib/iup.py +490 -0
  309. fontTools/varLib/merger.py +1717 -0
  310. fontTools/varLib/models.py +642 -0
  311. fontTools/varLib/multiVarStore.py +253 -0
  312. fontTools/varLib/mutator.py +518 -0
  313. fontTools/varLib/mvar.py +40 -0
  314. fontTools/varLib/plot.py +238 -0
  315. fontTools/varLib/stat.py +149 -0
  316. fontTools/varLib/varStore.py +767 -0
  317. fontTools/voltLib/__init__.py +5 -0
  318. fontTools/voltLib/ast.py +448 -0
  319. fontTools/voltLib/error.py +12 -0
  320. fontTools/voltLib/lexer.py +99 -0
  321. fontTools/voltLib/parser.py +656 -0
  322. fontTools/voltLib/voltToFea.py +730 -0
  323. fonttools-4.55.6.data/data/share/man/man1/ttx.1 +225 -0
  324. fonttools-4.55.6.dist-info/LICENSE +21 -0
  325. fonttools-4.55.6.dist-info/METADATA +3413 -0
  326. fonttools-4.55.6.dist-info/RECORD +329 -0
  327. fonttools-4.55.6.dist-info/WHEEL +5 -0
  328. fonttools-4.55.6.dist-info/entry_points.txt +5 -0
  329. fonttools-4.55.6.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1155 @@
1
+ from fontTools.config import Config
2
+ from fontTools.misc import xmlWriter
3
+ from fontTools.misc.configTools import AbstractConfig
4
+ from fontTools.misc.textTools import Tag, byteord, tostr
5
+ from fontTools.misc.loggingTools import deprecateArgument
6
+ from fontTools.ttLib import TTLibError
7
+ from fontTools.ttLib.ttGlyphSet import (
8
+ _TTGlyph,
9
+ _TTGlyphSetCFF,
10
+ _TTGlyphSetGlyf,
11
+ _TTGlyphSetVARC,
12
+ )
13
+ from fontTools.ttLib.sfnt import SFNTReader, SFNTWriter
14
+ from io import BytesIO, StringIO, UnsupportedOperation
15
+ import os
16
+ import logging
17
+ import traceback
18
+
19
+ log = logging.getLogger(__name__)
20
+
21
+
22
+ class TTFont(object):
23
+ """Represents a TrueType font.
24
+
25
+ The object manages file input and output, and offers a convenient way of
26
+ accessing tables. Tables will be only decompiled when necessary, ie. when
27
+ they're actually accessed. This means that simple operations can be extremely fast.
28
+
29
+ Example usage:
30
+ .. code-block:: pycon
31
+
32
+ >>>
33
+ >> from fontTools import ttLib
34
+ >> tt = ttLib.TTFont("afont.ttf") # Load an existing font file
35
+ >> tt['maxp'].numGlyphs
36
+ 242
37
+ >> tt['OS/2'].achVendID
38
+ 'B&H\000'
39
+ >> tt['head'].unitsPerEm
40
+ 2048
41
+
42
+ For details of the objects returned when accessing each table, see :ref:`tables`.
43
+ To add a table to the font, use the :py:func:`newTable` function:
44
+ .. code-block:: pycon
45
+
46
+ >>>
47
+ >> os2 = newTable("OS/2")
48
+ >> os2.version = 4
49
+ >> # set other attributes
50
+ >> font["OS/2"] = os2
51
+
52
+ TrueType fonts can also be serialized to and from XML format (see also the
53
+ :ref:`ttx` binary):
54
+ .. code-block:: pycon
55
+
56
+ >>
57
+ >> tt.saveXML("afont.ttx")
58
+ Dumping 'LTSH' table...
59
+ Dumping 'OS/2' table...
60
+ [...]
61
+
62
+ >> tt2 = ttLib.TTFont() # Create a new font object
63
+ >> tt2.importXML("afont.ttx")
64
+ >> tt2['maxp'].numGlyphs
65
+ 242
66
+
67
+ The TTFont object may be used as a context manager; this will cause the file
68
+ reader to be closed after the context ``with`` block is exited::
69
+
70
+ with TTFont(filename) as f:
71
+ # Do stuff
72
+
73
+ Args:
74
+ file: When reading a font from disk, either a pathname pointing to a file,
75
+ or a readable file object.
76
+ res_name_or_index: If running on a Macintosh, either a sfnt resource name or
77
+ an sfnt resource index number. If the index number is zero, TTLib will
78
+ autodetect whether the file is a flat file or a suitcase. (If it is a suitcase,
79
+ only the first 'sfnt' resource will be read.)
80
+ sfntVersion (str): When constructing a font object from scratch, sets the four-byte
81
+ sfnt magic number to be used. Defaults to ``\0\1\0\0`` (TrueType). To create
82
+ an OpenType file, use ``OTTO``.
83
+ flavor (str): Set this to ``woff`` when creating a WOFF file or ``woff2`` for a WOFF2
84
+ file.
85
+ checkChecksums (int): How checksum data should be treated. Default is 0
86
+ (no checking). Set to 1 to check and warn on wrong checksums; set to 2 to
87
+ raise an exception if any wrong checksums are found.
88
+ recalcBBoxes (bool): If true (the default), recalculates ``glyf``, ``CFF ``,
89
+ ``head`` bounding box values and ``hhea``/``vhea`` min/max values on save.
90
+ Also compiles the glyphs on importing, which saves memory consumption and
91
+ time.
92
+ ignoreDecompileErrors (bool): If true, exceptions raised during table decompilation
93
+ will be ignored, and the binary data will be returned for those tables instead.
94
+ recalcTimestamp (bool): If true (the default), sets the ``modified`` timestamp in
95
+ the ``head`` table on save.
96
+ fontNumber (int): The index of the font in a TrueType Collection file.
97
+ lazy (bool): If lazy is set to True, many data structures are loaded lazily, upon
98
+ access only. If it is set to False, many data structures are loaded immediately.
99
+ The default is ``lazy=None`` which is somewhere in between.
100
+ """
101
+
102
+ def __init__(
103
+ self,
104
+ file=None,
105
+ res_name_or_index=None,
106
+ sfntVersion="\000\001\000\000",
107
+ flavor=None,
108
+ checkChecksums=0,
109
+ verbose=None,
110
+ recalcBBoxes=True,
111
+ allowVID=NotImplemented,
112
+ ignoreDecompileErrors=False,
113
+ recalcTimestamp=True,
114
+ fontNumber=-1,
115
+ lazy=None,
116
+ quiet=None,
117
+ _tableCache=None,
118
+ cfg={},
119
+ ):
120
+ for name in ("verbose", "quiet"):
121
+ val = locals().get(name)
122
+ if val is not None:
123
+ deprecateArgument(name, "configure logging instead")
124
+ setattr(self, name, val)
125
+
126
+ self.lazy = lazy
127
+ self.recalcBBoxes = recalcBBoxes
128
+ self.recalcTimestamp = recalcTimestamp
129
+ self.tables = {}
130
+ self.reader = None
131
+ self.cfg = cfg.copy() if isinstance(cfg, AbstractConfig) else Config(cfg)
132
+ self.ignoreDecompileErrors = ignoreDecompileErrors
133
+
134
+ if not file:
135
+ self.sfntVersion = sfntVersion
136
+ self.flavor = flavor
137
+ self.flavorData = None
138
+ return
139
+ seekable = True
140
+ if not hasattr(file, "read"):
141
+ closeStream = True
142
+ # assume file is a string
143
+ if res_name_or_index is not None:
144
+ # see if it contains 'sfnt' resources in the resource or data fork
145
+ from . import macUtils
146
+
147
+ if res_name_or_index == 0:
148
+ if macUtils.getSFNTResIndices(file):
149
+ # get the first available sfnt font.
150
+ file = macUtils.SFNTResourceReader(file, 1)
151
+ else:
152
+ file = open(file, "rb")
153
+ else:
154
+ file = macUtils.SFNTResourceReader(file, res_name_or_index)
155
+ else:
156
+ file = open(file, "rb")
157
+ else:
158
+ # assume "file" is a readable file object
159
+ closeStream = False
160
+ # SFNTReader wants the input file to be seekable.
161
+ # SpooledTemporaryFile has no seekable() on < 3.11, but still can seek:
162
+ # https://github.com/fonttools/fonttools/issues/3052
163
+ if hasattr(file, "seekable"):
164
+ seekable = file.seekable()
165
+ elif hasattr(file, "seek"):
166
+ try:
167
+ file.seek(0)
168
+ except UnsupportedOperation:
169
+ seekable = False
170
+
171
+ if not self.lazy:
172
+ # read input file in memory and wrap a stream around it to allow overwriting
173
+ if seekable:
174
+ file.seek(0)
175
+ tmp = BytesIO(file.read())
176
+ if hasattr(file, "name"):
177
+ # save reference to input file name
178
+ tmp.name = file.name
179
+ if closeStream:
180
+ file.close()
181
+ file = tmp
182
+ elif not seekable:
183
+ raise TTLibError("Input file must be seekable when lazy=True")
184
+ self._tableCache = _tableCache
185
+ self.reader = SFNTReader(file, checkChecksums, fontNumber=fontNumber)
186
+ self.sfntVersion = self.reader.sfntVersion
187
+ self.flavor = self.reader.flavor
188
+ self.flavorData = self.reader.flavorData
189
+
190
+ def __enter__(self):
191
+ return self
192
+
193
+ def __exit__(self, type, value, traceback):
194
+ self.close()
195
+
196
+ def close(self):
197
+ """If we still have a reader object, close it."""
198
+ if self.reader is not None:
199
+ self.reader.close()
200
+
201
+ def save(self, file, reorderTables=True):
202
+ """Save the font to disk.
203
+
204
+ Args:
205
+ file: Similarly to the constructor, can be either a pathname or a writable
206
+ file object.
207
+ reorderTables (Option[bool]): If true (the default), reorder the tables,
208
+ sorting them by tag (recommended by the OpenType specification). If
209
+ false, retain the original font order. If None, reorder by table
210
+ dependency (fastest).
211
+ """
212
+ if not hasattr(file, "write"):
213
+ if self.lazy and self.reader.file.name == file:
214
+ raise TTLibError("Can't overwrite TTFont when 'lazy' attribute is True")
215
+ createStream = True
216
+ else:
217
+ # assume "file" is a writable file object
218
+ createStream = False
219
+
220
+ tmp = BytesIO()
221
+
222
+ writer_reordersTables = self._save(tmp)
223
+
224
+ if not (
225
+ reorderTables is None
226
+ or writer_reordersTables
227
+ or (reorderTables is False and self.reader is None)
228
+ ):
229
+ if reorderTables is False:
230
+ # sort tables using the original font's order
231
+ tableOrder = list(self.reader.keys())
232
+ else:
233
+ # use the recommended order from the OpenType specification
234
+ tableOrder = None
235
+ tmp.flush()
236
+ tmp2 = BytesIO()
237
+ reorderFontTables(tmp, tmp2, tableOrder)
238
+ tmp.close()
239
+ tmp = tmp2
240
+
241
+ if createStream:
242
+ # "file" is a path
243
+ with open(file, "wb") as file:
244
+ file.write(tmp.getvalue())
245
+ else:
246
+ file.write(tmp.getvalue())
247
+
248
+ tmp.close()
249
+
250
+ def _save(self, file, tableCache=None):
251
+ """Internal function, to be shared by save() and TTCollection.save()"""
252
+
253
+ if self.recalcTimestamp and "head" in self:
254
+ self[
255
+ "head"
256
+ ] # make sure 'head' is loaded so the recalculation is actually done
257
+
258
+ tags = list(self.keys())
259
+ if "GlyphOrder" in tags:
260
+ tags.remove("GlyphOrder")
261
+ numTables = len(tags)
262
+ # write to a temporary stream to allow saving to unseekable streams
263
+ writer = SFNTWriter(
264
+ file, numTables, self.sfntVersion, self.flavor, self.flavorData
265
+ )
266
+
267
+ done = []
268
+ for tag in tags:
269
+ self._writeTable(tag, writer, done, tableCache)
270
+
271
+ writer.close()
272
+
273
+ return writer.reordersTables()
274
+
275
+ def saveXML(self, fileOrPath, newlinestr="\n", **kwargs):
276
+ """Export the font as TTX (an XML-based text file), or as a series of text
277
+ files when splitTables is true. In the latter case, the 'fileOrPath'
278
+ argument should be a path to a directory.
279
+ The 'tables' argument must either be false (dump all tables) or a
280
+ list of tables to dump. The 'skipTables' argument may be a list of tables
281
+ to skip, but only when the 'tables' argument is false.
282
+ """
283
+
284
+ writer = xmlWriter.XMLWriter(fileOrPath, newlinestr=newlinestr)
285
+ self._saveXML(writer, **kwargs)
286
+ writer.close()
287
+
288
+ def _saveXML(
289
+ self,
290
+ writer,
291
+ writeVersion=True,
292
+ quiet=None,
293
+ tables=None,
294
+ skipTables=None,
295
+ splitTables=False,
296
+ splitGlyphs=False,
297
+ disassembleInstructions=True,
298
+ bitmapGlyphDataFormat="raw",
299
+ ):
300
+ if quiet is not None:
301
+ deprecateArgument("quiet", "configure logging instead")
302
+
303
+ self.disassembleInstructions = disassembleInstructions
304
+ self.bitmapGlyphDataFormat = bitmapGlyphDataFormat
305
+ if not tables:
306
+ tables = list(self.keys())
307
+ if "GlyphOrder" not in tables:
308
+ tables = ["GlyphOrder"] + tables
309
+ if skipTables:
310
+ for tag in skipTables:
311
+ if tag in tables:
312
+ tables.remove(tag)
313
+ numTables = len(tables)
314
+
315
+ if writeVersion:
316
+ from fontTools import version
317
+
318
+ version = ".".join(version.split(".")[:2])
319
+ writer.begintag(
320
+ "ttFont",
321
+ sfntVersion=repr(tostr(self.sfntVersion))[1:-1],
322
+ ttLibVersion=version,
323
+ )
324
+ else:
325
+ writer.begintag("ttFont", sfntVersion=repr(tostr(self.sfntVersion))[1:-1])
326
+ writer.newline()
327
+
328
+ # always splitTables if splitGlyphs is enabled
329
+ splitTables = splitTables or splitGlyphs
330
+
331
+ if not splitTables:
332
+ writer.newline()
333
+ else:
334
+ path, ext = os.path.splitext(writer.filename)
335
+
336
+ for i in range(numTables):
337
+ tag = tables[i]
338
+ if splitTables:
339
+ tablePath = path + "." + tagToIdentifier(tag) + ext
340
+ tableWriter = xmlWriter.XMLWriter(
341
+ tablePath, newlinestr=writer.newlinestr
342
+ )
343
+ tableWriter.begintag("ttFont", ttLibVersion=version)
344
+ tableWriter.newline()
345
+ tableWriter.newline()
346
+ writer.simpletag(tagToXML(tag), src=os.path.basename(tablePath))
347
+ writer.newline()
348
+ else:
349
+ tableWriter = writer
350
+ self._tableToXML(tableWriter, tag, splitGlyphs=splitGlyphs)
351
+ if splitTables:
352
+ tableWriter.endtag("ttFont")
353
+ tableWriter.newline()
354
+ tableWriter.close()
355
+ writer.endtag("ttFont")
356
+ writer.newline()
357
+
358
+ def _tableToXML(self, writer, tag, quiet=None, splitGlyphs=False):
359
+ if quiet is not None:
360
+ deprecateArgument("quiet", "configure logging instead")
361
+ if tag in self:
362
+ table = self[tag]
363
+ report = "Dumping '%s' table..." % tag
364
+ else:
365
+ report = "No '%s' table found." % tag
366
+ log.info(report)
367
+ if tag not in self:
368
+ return
369
+ xmlTag = tagToXML(tag)
370
+ attrs = dict()
371
+ if hasattr(table, "ERROR"):
372
+ attrs["ERROR"] = "decompilation error"
373
+ from .tables.DefaultTable import DefaultTable
374
+
375
+ if table.__class__ == DefaultTable:
376
+ attrs["raw"] = True
377
+ writer.begintag(xmlTag, **attrs)
378
+ writer.newline()
379
+ if tag == "glyf":
380
+ table.toXML(writer, self, splitGlyphs=splitGlyphs)
381
+ else:
382
+ table.toXML(writer, self)
383
+ writer.endtag(xmlTag)
384
+ writer.newline()
385
+ writer.newline()
386
+
387
+ def importXML(self, fileOrPath, quiet=None):
388
+ """Import a TTX file (an XML-based text format), so as to recreate
389
+ a font object.
390
+ """
391
+ if quiet is not None:
392
+ deprecateArgument("quiet", "configure logging instead")
393
+
394
+ if "maxp" in self and "post" in self:
395
+ # Make sure the glyph order is loaded, as it otherwise gets
396
+ # lost if the XML doesn't contain the glyph order, yet does
397
+ # contain the table which was originally used to extract the
398
+ # glyph names from (ie. 'post', 'cmap' or 'CFF ').
399
+ self.getGlyphOrder()
400
+
401
+ from fontTools.misc import xmlReader
402
+
403
+ reader = xmlReader.XMLReader(fileOrPath, self)
404
+ reader.read()
405
+
406
+ def isLoaded(self, tag):
407
+ """Return true if the table identified by ``tag`` has been
408
+ decompiled and loaded into memory."""
409
+ return tag in self.tables
410
+
411
+ def has_key(self, tag):
412
+ """Test if the table identified by ``tag`` is present in the font.
413
+
414
+ As well as this method, ``tag in font`` can also be used to determine the
415
+ presence of the table."""
416
+ if self.isLoaded(tag):
417
+ return True
418
+ elif self.reader and tag in self.reader:
419
+ return True
420
+ elif tag == "GlyphOrder":
421
+ return True
422
+ else:
423
+ return False
424
+
425
+ __contains__ = has_key
426
+
427
+ def keys(self):
428
+ """Returns the list of tables in the font, along with the ``GlyphOrder`` pseudo-table."""
429
+ keys = list(self.tables.keys())
430
+ if self.reader:
431
+ for key in list(self.reader.keys()):
432
+ if key not in keys:
433
+ keys.append(key)
434
+
435
+ if "GlyphOrder" in keys:
436
+ keys.remove("GlyphOrder")
437
+ keys = sortedTagList(keys)
438
+ return ["GlyphOrder"] + keys
439
+
440
+ def ensureDecompiled(self, recurse=None):
441
+ """Decompile all the tables, even if a TTFont was opened in 'lazy' mode."""
442
+ for tag in self.keys():
443
+ table = self[tag]
444
+ if recurse is None:
445
+ recurse = self.lazy is not False
446
+ if recurse and hasattr(table, "ensureDecompiled"):
447
+ table.ensureDecompiled(recurse=recurse)
448
+ self.lazy = False
449
+
450
+ def __len__(self):
451
+ return len(list(self.keys()))
452
+
453
+ def __getitem__(self, tag):
454
+ tag = Tag(tag)
455
+ table = self.tables.get(tag)
456
+ if table is None:
457
+ if tag == "GlyphOrder":
458
+ table = GlyphOrder(tag)
459
+ self.tables[tag] = table
460
+ elif self.reader is not None:
461
+ table = self._readTable(tag)
462
+ else:
463
+ raise KeyError("'%s' table not found" % tag)
464
+ return table
465
+
466
+ def _readTable(self, tag):
467
+ log.debug("Reading '%s' table from disk", tag)
468
+ data = self.reader[tag]
469
+ if self._tableCache is not None:
470
+ table = self._tableCache.get((tag, data))
471
+ if table is not None:
472
+ return table
473
+ tableClass = getTableClass(tag)
474
+ table = tableClass(tag)
475
+ self.tables[tag] = table
476
+ log.debug("Decompiling '%s' table", tag)
477
+ try:
478
+ table.decompile(data, self)
479
+ except Exception:
480
+ if not self.ignoreDecompileErrors:
481
+ raise
482
+ # fall back to DefaultTable, retaining the binary table data
483
+ log.exception(
484
+ "An exception occurred during the decompilation of the '%s' table", tag
485
+ )
486
+ from .tables.DefaultTable import DefaultTable
487
+
488
+ file = StringIO()
489
+ traceback.print_exc(file=file)
490
+ table = DefaultTable(tag)
491
+ table.ERROR = file.getvalue()
492
+ self.tables[tag] = table
493
+ table.decompile(data, self)
494
+ if self._tableCache is not None:
495
+ self._tableCache[(tag, data)] = table
496
+ return table
497
+
498
+ def __setitem__(self, tag, table):
499
+ self.tables[Tag(tag)] = table
500
+
501
+ def __delitem__(self, tag):
502
+ if tag not in self:
503
+ raise KeyError("'%s' table not found" % tag)
504
+ if tag in self.tables:
505
+ del self.tables[tag]
506
+ if self.reader and tag in self.reader:
507
+ del self.reader[tag]
508
+
509
+ def get(self, tag, default=None):
510
+ """Returns the table if it exists or (optionally) a default if it doesn't."""
511
+ try:
512
+ return self[tag]
513
+ except KeyError:
514
+ return default
515
+
516
+ def setGlyphOrder(self, glyphOrder):
517
+ """Set the glyph order
518
+
519
+ Args:
520
+ glyphOrder ([str]): List of glyph names in order.
521
+ """
522
+ self.glyphOrder = glyphOrder
523
+ if hasattr(self, "_reverseGlyphOrderDict"):
524
+ del self._reverseGlyphOrderDict
525
+ if self.isLoaded("glyf"):
526
+ self["glyf"].setGlyphOrder(glyphOrder)
527
+
528
+ def getGlyphOrder(self):
529
+ """Returns a list of glyph names ordered by their position in the font."""
530
+ try:
531
+ return self.glyphOrder
532
+ except AttributeError:
533
+ pass
534
+ if "CFF " in self:
535
+ cff = self["CFF "]
536
+ self.glyphOrder = cff.getGlyphOrder()
537
+ elif "post" in self:
538
+ # TrueType font
539
+ glyphOrder = self["post"].getGlyphOrder()
540
+ if glyphOrder is None:
541
+ #
542
+ # No names found in the 'post' table.
543
+ # Try to create glyph names from the unicode cmap (if available)
544
+ # in combination with the Adobe Glyph List (AGL).
545
+ #
546
+ self._getGlyphNamesFromCmap()
547
+ elif len(glyphOrder) < self["maxp"].numGlyphs:
548
+ #
549
+ # Not enough names found in the 'post' table.
550
+ # Can happen when 'post' format 1 is improperly used on a font that
551
+ # has more than 258 glyphs (the length of 'standardGlyphOrder').
552
+ #
553
+ log.warning(
554
+ "Not enough names found in the 'post' table, generating them from cmap instead"
555
+ )
556
+ self._getGlyphNamesFromCmap()
557
+ else:
558
+ self.glyphOrder = glyphOrder
559
+ else:
560
+ self._getGlyphNamesFromCmap()
561
+ return self.glyphOrder
562
+
563
+ def _getGlyphNamesFromCmap(self):
564
+ #
565
+ # This is rather convoluted, but then again, it's an interesting problem:
566
+ # - we need to use the unicode values found in the cmap table to
567
+ # build glyph names (eg. because there is only a minimal post table,
568
+ # or none at all).
569
+ # - but the cmap parser also needs glyph names to work with...
570
+ # So here's what we do:
571
+ # - make up glyph names based on glyphID
572
+ # - load a temporary cmap table based on those names
573
+ # - extract the unicode values, build the "real" glyph names
574
+ # - unload the temporary cmap table
575
+ #
576
+ if self.isLoaded("cmap"):
577
+ # Bootstrapping: we're getting called by the cmap parser
578
+ # itself. This means self.tables['cmap'] contains a partially
579
+ # loaded cmap, making it impossible to get at a unicode
580
+ # subtable here. We remove the partially loaded cmap and
581
+ # restore it later.
582
+ # This only happens if the cmap table is loaded before any
583
+ # other table that does f.getGlyphOrder() or f.getGlyphName().
584
+ cmapLoading = self.tables["cmap"]
585
+ del self.tables["cmap"]
586
+ else:
587
+ cmapLoading = None
588
+ # Make up glyph names based on glyphID, which will be used by the
589
+ # temporary cmap and by the real cmap in case we don't find a unicode
590
+ # cmap.
591
+ numGlyphs = int(self["maxp"].numGlyphs)
592
+ glyphOrder = [None] * numGlyphs
593
+ glyphOrder[0] = ".notdef"
594
+ for i in range(1, numGlyphs):
595
+ glyphOrder[i] = "glyph%.5d" % i
596
+ # Set the glyph order, so the cmap parser has something
597
+ # to work with (so we don't get called recursively).
598
+ self.glyphOrder = glyphOrder
599
+
600
+ # Make up glyph names based on the reversed cmap table. Because some
601
+ # glyphs (eg. ligatures or alternates) may not be reachable via cmap,
602
+ # this naming table will usually not cover all glyphs in the font.
603
+ # If the font has no Unicode cmap table, reversecmap will be empty.
604
+ if "cmap" in self:
605
+ reversecmap = self["cmap"].buildReversed()
606
+ else:
607
+ reversecmap = {}
608
+ useCount = {}
609
+ for i in range(numGlyphs):
610
+ tempName = glyphOrder[i]
611
+ if tempName in reversecmap:
612
+ # If a font maps both U+0041 LATIN CAPITAL LETTER A and
613
+ # U+0391 GREEK CAPITAL LETTER ALPHA to the same glyph,
614
+ # we prefer naming the glyph as "A".
615
+ glyphName = self._makeGlyphName(min(reversecmap[tempName]))
616
+ numUses = useCount[glyphName] = useCount.get(glyphName, 0) + 1
617
+ if numUses > 1:
618
+ glyphName = "%s.alt%d" % (glyphName, numUses - 1)
619
+ glyphOrder[i] = glyphName
620
+
621
+ if "cmap" in self:
622
+ # Delete the temporary cmap table from the cache, so it can
623
+ # be parsed again with the right names.
624
+ del self.tables["cmap"]
625
+ self.glyphOrder = glyphOrder
626
+ if cmapLoading:
627
+ # restore partially loaded cmap, so it can continue loading
628
+ # using the proper names.
629
+ self.tables["cmap"] = cmapLoading
630
+
631
+ @staticmethod
632
+ def _makeGlyphName(codepoint):
633
+ from fontTools import agl # Adobe Glyph List
634
+
635
+ if codepoint in agl.UV2AGL:
636
+ return agl.UV2AGL[codepoint]
637
+ elif codepoint <= 0xFFFF:
638
+ return "uni%04X" % codepoint
639
+ else:
640
+ return "u%X" % codepoint
641
+
642
+ def getGlyphNames(self):
643
+ """Get a list of glyph names, sorted alphabetically."""
644
+ glyphNames = sorted(self.getGlyphOrder())
645
+ return glyphNames
646
+
647
+ def getGlyphNames2(self):
648
+ """Get a list of glyph names, sorted alphabetically,
649
+ but not case sensitive.
650
+ """
651
+ from fontTools.misc import textTools
652
+
653
+ return textTools.caselessSort(self.getGlyphOrder())
654
+
655
+ def getGlyphName(self, glyphID):
656
+ """Returns the name for the glyph with the given ID.
657
+
658
+ If no name is available, synthesises one with the form ``glyphXXXXX``` where
659
+ ```XXXXX`` is the zero-padded glyph ID.
660
+ """
661
+ try:
662
+ return self.getGlyphOrder()[glyphID]
663
+ except IndexError:
664
+ return "glyph%.5d" % glyphID
665
+
666
+ def getGlyphNameMany(self, lst):
667
+ """Converts a list of glyph IDs into a list of glyph names."""
668
+ glyphOrder = self.getGlyphOrder()
669
+ cnt = len(glyphOrder)
670
+ return [glyphOrder[gid] if gid < cnt else "glyph%.5d" % gid for gid in lst]
671
+
672
+ def getGlyphID(self, glyphName):
673
+ """Returns the ID of the glyph with the given name."""
674
+ try:
675
+ return self.getReverseGlyphMap()[glyphName]
676
+ except KeyError:
677
+ if glyphName[:5] == "glyph":
678
+ try:
679
+ return int(glyphName[5:])
680
+ except (NameError, ValueError):
681
+ raise KeyError(glyphName)
682
+ raise
683
+
684
+ def getGlyphIDMany(self, lst):
685
+ """Converts a list of glyph names into a list of glyph IDs."""
686
+ d = self.getReverseGlyphMap()
687
+ try:
688
+ return [d[glyphName] for glyphName in lst]
689
+ except KeyError:
690
+ getGlyphID = self.getGlyphID
691
+ return [getGlyphID(glyphName) for glyphName in lst]
692
+
693
+ def getReverseGlyphMap(self, rebuild=False):
694
+ """Returns a mapping of glyph names to glyph IDs."""
695
+ if rebuild or not hasattr(self, "_reverseGlyphOrderDict"):
696
+ self._buildReverseGlyphOrderDict()
697
+ return self._reverseGlyphOrderDict
698
+
699
+ def _buildReverseGlyphOrderDict(self):
700
+ self._reverseGlyphOrderDict = d = {}
701
+ for glyphID, glyphName in enumerate(self.getGlyphOrder()):
702
+ d[glyphName] = glyphID
703
+ return d
704
+
705
+ def _writeTable(self, tag, writer, done, tableCache=None):
706
+ """Internal helper function for self.save(). Keeps track of
707
+ inter-table dependencies.
708
+ """
709
+ if tag in done:
710
+ return
711
+ tableClass = getTableClass(tag)
712
+ for masterTable in tableClass.dependencies:
713
+ if masterTable not in done:
714
+ if masterTable in self:
715
+ self._writeTable(masterTable, writer, done, tableCache)
716
+ else:
717
+ done.append(masterTable)
718
+ done.append(tag)
719
+ tabledata = self.getTableData(tag)
720
+ if tableCache is not None:
721
+ entry = tableCache.get((Tag(tag), tabledata))
722
+ if entry is not None:
723
+ log.debug("reusing '%s' table", tag)
724
+ writer.setEntry(tag, entry)
725
+ return
726
+ log.debug("Writing '%s' table to disk", tag)
727
+ writer[tag] = tabledata
728
+ if tableCache is not None:
729
+ tableCache[(Tag(tag), tabledata)] = writer[tag]
730
+
731
+ def getTableData(self, tag):
732
+ """Returns the binary representation of a table.
733
+
734
+ If the table is currently loaded and in memory, the data is compiled to
735
+ binary and returned; if it is not currently loaded, the binary data is
736
+ read from the font file and returned.
737
+ """
738
+ tag = Tag(tag)
739
+ if self.isLoaded(tag):
740
+ log.debug("Compiling '%s' table", tag)
741
+ return self.tables[tag].compile(self)
742
+ elif self.reader and tag in self.reader:
743
+ log.debug("Reading '%s' table from disk", tag)
744
+ return self.reader[tag]
745
+ else:
746
+ raise KeyError(tag)
747
+
748
+ def getGlyphSet(
749
+ self, preferCFF=True, location=None, normalized=False, recalcBounds=True
750
+ ):
751
+ """Return a generic GlyphSet, which is a dict-like object
752
+ mapping glyph names to glyph objects. The returned glyph objects
753
+ have a ``.draw()`` method that supports the Pen protocol, and will
754
+ have an attribute named 'width'.
755
+
756
+ If the font is CFF-based, the outlines will be taken from the ``CFF ``
757
+ or ``CFF2`` tables. Otherwise the outlines will be taken from the
758
+ ``glyf`` table.
759
+
760
+ If the font contains both a ``CFF ``/``CFF2`` and a ``glyf`` table, you
761
+ can use the ``preferCFF`` argument to specify which one should be taken.
762
+ If the font contains both a ``CFF `` and a ``CFF2`` table, the latter is
763
+ taken.
764
+
765
+ If the ``location`` parameter is set, it should be a dictionary mapping
766
+ four-letter variation tags to their float values, and the returned
767
+ glyph-set will represent an instance of a variable font at that
768
+ location.
769
+
770
+ If the ``normalized`` variable is set to True, that location is
771
+ interpreted as in the normalized (-1..+1) space, otherwise it is in the
772
+ font's defined axes space.
773
+ """
774
+ if location and "fvar" not in self:
775
+ location = None
776
+ if location and not normalized:
777
+ location = self.normalizeLocation(location)
778
+ glyphSet = None
779
+ if ("CFF " in self or "CFF2" in self) and (preferCFF or "glyf" not in self):
780
+ glyphSet = _TTGlyphSetCFF(self, location)
781
+ elif "glyf" in self:
782
+ glyphSet = _TTGlyphSetGlyf(self, location, recalcBounds=recalcBounds)
783
+ else:
784
+ raise TTLibError("Font contains no outlines")
785
+ if "VARC" in self:
786
+ glyphSet = _TTGlyphSetVARC(self, location, glyphSet)
787
+ return glyphSet
788
+
789
+ def normalizeLocation(self, location):
790
+ """Normalize a ``location`` from the font's defined axes space (also
791
+ known as user space) into the normalized (-1..+1) space. It applies
792
+ ``avar`` mapping if the font contains an ``avar`` table.
793
+
794
+ The ``location`` parameter should be a dictionary mapping four-letter
795
+ variation tags to their float values.
796
+
797
+ Raises ``TTLibError`` if the font is not a variable font.
798
+ """
799
+ from fontTools.varLib.models import normalizeLocation
800
+
801
+ if "fvar" not in self:
802
+ raise TTLibError("Not a variable font")
803
+
804
+ axes = self["fvar"].getAxes()
805
+ location = normalizeLocation(location, axes)
806
+ if "avar" in self:
807
+ location = self["avar"].renormalizeLocation(location, self)
808
+ return location
809
+
810
+ def getBestCmap(
811
+ self,
812
+ cmapPreferences=(
813
+ (3, 10),
814
+ (0, 6),
815
+ (0, 4),
816
+ (3, 1),
817
+ (0, 3),
818
+ (0, 2),
819
+ (0, 1),
820
+ (0, 0),
821
+ ),
822
+ ):
823
+ """Returns the 'best' Unicode cmap dictionary available in the font
824
+ or ``None``, if no Unicode cmap subtable is available.
825
+
826
+ By default it will search for the following (platformID, platEncID)
827
+ pairs in order::
828
+
829
+ (3, 10), # Windows Unicode full repertoire
830
+ (0, 6), # Unicode full repertoire (format 13 subtable)
831
+ (0, 4), # Unicode 2.0 full repertoire
832
+ (3, 1), # Windows Unicode BMP
833
+ (0, 3), # Unicode 2.0 BMP
834
+ (0, 2), # Unicode ISO/IEC 10646
835
+ (0, 1), # Unicode 1.1
836
+ (0, 0) # Unicode 1.0
837
+
838
+ This particular order matches what HarfBuzz uses to choose what
839
+ subtable to use by default. This order prefers the largest-repertoire
840
+ subtable, and among those, prefers the Windows-platform over the
841
+ Unicode-platform as the former has wider support.
842
+
843
+ This order can be customized via the ``cmapPreferences`` argument.
844
+ """
845
+ return self["cmap"].getBestCmap(cmapPreferences=cmapPreferences)
846
+
847
+ def reorderGlyphs(self, new_glyph_order):
848
+ from .reorderGlyphs import reorderGlyphs
849
+
850
+ reorderGlyphs(self, new_glyph_order)
851
+
852
+
853
+ class GlyphOrder(object):
854
+ """A pseudo table. The glyph order isn't in the font as a separate
855
+ table, but it's nice to present it as such in the TTX format.
856
+ """
857
+
858
+ def __init__(self, tag=None):
859
+ pass
860
+
861
+ def toXML(self, writer, ttFont):
862
+ glyphOrder = ttFont.getGlyphOrder()
863
+ writer.comment(
864
+ "The 'id' attribute is only for humans; " "it is ignored when parsed."
865
+ )
866
+ writer.newline()
867
+ for i in range(len(glyphOrder)):
868
+ glyphName = glyphOrder[i]
869
+ writer.simpletag("GlyphID", id=i, name=glyphName)
870
+ writer.newline()
871
+
872
+ def fromXML(self, name, attrs, content, ttFont):
873
+ if not hasattr(self, "glyphOrder"):
874
+ self.glyphOrder = []
875
+ if name == "GlyphID":
876
+ self.glyphOrder.append(attrs["name"])
877
+ ttFont.setGlyphOrder(self.glyphOrder)
878
+
879
+
880
+ def getTableModule(tag):
881
+ """Fetch the packer/unpacker module for a table.
882
+ Return None when no module is found.
883
+ """
884
+ from . import tables
885
+
886
+ pyTag = tagToIdentifier(tag)
887
+ try:
888
+ __import__("fontTools.ttLib.tables." + pyTag)
889
+ except ImportError as err:
890
+ # If pyTag is found in the ImportError message,
891
+ # means table is not implemented. If it's not
892
+ # there, then some other module is missing, don't
893
+ # suppress the error.
894
+ if str(err).find(pyTag) >= 0:
895
+ return None
896
+ else:
897
+ raise err
898
+ else:
899
+ return getattr(tables, pyTag)
900
+
901
+
902
+ # Registry for custom table packer/unpacker classes. Keys are table
903
+ # tags, values are (moduleName, className) tuples.
904
+ # See registerCustomTableClass() and getCustomTableClass()
905
+ _customTableRegistry = {}
906
+
907
+
908
+ def registerCustomTableClass(tag, moduleName, className=None):
909
+ """Register a custom packer/unpacker class for a table.
910
+
911
+ The 'moduleName' must be an importable module. If no 'className'
912
+ is given, it is derived from the tag, for example it will be
913
+ ``table_C_U_S_T_`` for a 'CUST' tag.
914
+
915
+ The registered table class should be a subclass of
916
+ :py:class:`fontTools.ttLib.tables.DefaultTable.DefaultTable`
917
+ """
918
+ if className is None:
919
+ className = "table_" + tagToIdentifier(tag)
920
+ _customTableRegistry[tag] = (moduleName, className)
921
+
922
+
923
+ def unregisterCustomTableClass(tag):
924
+ """Unregister the custom packer/unpacker class for a table."""
925
+ del _customTableRegistry[tag]
926
+
927
+
928
+ def getCustomTableClass(tag):
929
+ """Return the custom table class for tag, if one has been registered
930
+ with 'registerCustomTableClass()'. Else return None.
931
+ """
932
+ if tag not in _customTableRegistry:
933
+ return None
934
+ import importlib
935
+
936
+ moduleName, className = _customTableRegistry[tag]
937
+ module = importlib.import_module(moduleName)
938
+ return getattr(module, className)
939
+
940
+
941
+ def getTableClass(tag):
942
+ """Fetch the packer/unpacker class for a table."""
943
+ tableClass = getCustomTableClass(tag)
944
+ if tableClass is not None:
945
+ return tableClass
946
+ module = getTableModule(tag)
947
+ if module is None:
948
+ from .tables.DefaultTable import DefaultTable
949
+
950
+ return DefaultTable
951
+ pyTag = tagToIdentifier(tag)
952
+ tableClass = getattr(module, "table_" + pyTag)
953
+ return tableClass
954
+
955
+
956
+ def getClassTag(klass):
957
+ """Fetch the table tag for a class object."""
958
+ name = klass.__name__
959
+ assert name[:6] == "table_"
960
+ name = name[6:] # Chop 'table_'
961
+ return identifierToTag(name)
962
+
963
+
964
+ def newTable(tag):
965
+ """Return a new instance of a table."""
966
+ tableClass = getTableClass(tag)
967
+ return tableClass(tag)
968
+
969
+
970
+ def _escapechar(c):
971
+ """Helper function for tagToIdentifier()"""
972
+ import re
973
+
974
+ if re.match("[a-z0-9]", c):
975
+ return "_" + c
976
+ elif re.match("[A-Z]", c):
977
+ return c + "_"
978
+ else:
979
+ return hex(byteord(c))[2:]
980
+
981
+
982
+ def tagToIdentifier(tag):
983
+ """Convert a table tag to a valid (but UGLY) python identifier,
984
+ as well as a filename that's guaranteed to be unique even on a
985
+ caseless file system. Each character is mapped to two characters.
986
+ Lowercase letters get an underscore before the letter, uppercase
987
+ letters get an underscore after the letter. Trailing spaces are
988
+ trimmed. Illegal characters are escaped as two hex bytes. If the
989
+ result starts with a number (as the result of a hex escape), an
990
+ extra underscore is prepended. Examples:
991
+ .. code-block:: pycon
992
+
993
+ >>>
994
+ >> tagToIdentifier('glyf')
995
+ '_g_l_y_f'
996
+ >> tagToIdentifier('cvt ')
997
+ '_c_v_t'
998
+ >> tagToIdentifier('OS/2')
999
+ 'O_S_2f_2'
1000
+ """
1001
+ import re
1002
+
1003
+ tag = Tag(tag)
1004
+ if tag == "GlyphOrder":
1005
+ return tag
1006
+ assert len(tag) == 4, "tag should be 4 characters long"
1007
+ while len(tag) > 1 and tag[-1] == " ":
1008
+ tag = tag[:-1]
1009
+ ident = ""
1010
+ for c in tag:
1011
+ ident = ident + _escapechar(c)
1012
+ if re.match("[0-9]", ident):
1013
+ ident = "_" + ident
1014
+ return ident
1015
+
1016
+
1017
+ def identifierToTag(ident):
1018
+ """the opposite of tagToIdentifier()"""
1019
+ if ident == "GlyphOrder":
1020
+ return ident
1021
+ if len(ident) % 2 and ident[0] == "_":
1022
+ ident = ident[1:]
1023
+ assert not (len(ident) % 2)
1024
+ tag = ""
1025
+ for i in range(0, len(ident), 2):
1026
+ if ident[i] == "_":
1027
+ tag = tag + ident[i + 1]
1028
+ elif ident[i + 1] == "_":
1029
+ tag = tag + ident[i]
1030
+ else:
1031
+ # assume hex
1032
+ tag = tag + chr(int(ident[i : i + 2], 16))
1033
+ # append trailing spaces
1034
+ tag = tag + (4 - len(tag)) * " "
1035
+ return Tag(tag)
1036
+
1037
+
1038
+ def tagToXML(tag):
1039
+ """Similarly to tagToIdentifier(), this converts a TT tag
1040
+ to a valid XML element name. Since XML element names are
1041
+ case sensitive, this is a fairly simple/readable translation.
1042
+ """
1043
+ import re
1044
+
1045
+ tag = Tag(tag)
1046
+ if tag == "OS/2":
1047
+ return "OS_2"
1048
+ elif tag == "GlyphOrder":
1049
+ return tag
1050
+ if re.match("[A-Za-z_][A-Za-z_0-9]* *$", tag):
1051
+ return tag.strip()
1052
+ else:
1053
+ return tagToIdentifier(tag)
1054
+
1055
+
1056
+ def xmlToTag(tag):
1057
+ """The opposite of tagToXML()"""
1058
+ if tag == "OS_2":
1059
+ return Tag("OS/2")
1060
+ if len(tag) == 8:
1061
+ return identifierToTag(tag)
1062
+ else:
1063
+ return Tag(tag + " " * (4 - len(tag)))
1064
+
1065
+
1066
+ # Table order as recommended in the OpenType specification 1.4
1067
+ TTFTableOrder = [
1068
+ "head",
1069
+ "hhea",
1070
+ "maxp",
1071
+ "OS/2",
1072
+ "hmtx",
1073
+ "LTSH",
1074
+ "VDMX",
1075
+ "hdmx",
1076
+ "cmap",
1077
+ "fpgm",
1078
+ "prep",
1079
+ "cvt ",
1080
+ "loca",
1081
+ "glyf",
1082
+ "kern",
1083
+ "name",
1084
+ "post",
1085
+ "gasp",
1086
+ "PCLT",
1087
+ ]
1088
+
1089
+ OTFTableOrder = ["head", "hhea", "maxp", "OS/2", "name", "cmap", "post", "CFF "]
1090
+
1091
+
1092
+ def sortedTagList(tagList, tableOrder=None):
1093
+ """Return a sorted copy of tagList, sorted according to the OpenType
1094
+ specification, or according to a custom tableOrder. If given and not
1095
+ None, tableOrder needs to be a list of tag names.
1096
+ """
1097
+ tagList = sorted(tagList)
1098
+ if tableOrder is None:
1099
+ if "DSIG" in tagList:
1100
+ # DSIG should be last (XXX spec reference?)
1101
+ tagList.remove("DSIG")
1102
+ tagList.append("DSIG")
1103
+ if "CFF " in tagList:
1104
+ tableOrder = OTFTableOrder
1105
+ else:
1106
+ tableOrder = TTFTableOrder
1107
+ orderedTables = []
1108
+ for tag in tableOrder:
1109
+ if tag in tagList:
1110
+ orderedTables.append(tag)
1111
+ tagList.remove(tag)
1112
+ orderedTables.extend(tagList)
1113
+ return orderedTables
1114
+
1115
+
1116
+ def reorderFontTables(inFile, outFile, tableOrder=None, checkChecksums=False):
1117
+ """Rewrite a font file, ordering the tables as recommended by the
1118
+ OpenType specification 1.4.
1119
+ """
1120
+ inFile.seek(0)
1121
+ outFile.seek(0)
1122
+ reader = SFNTReader(inFile, checkChecksums=checkChecksums)
1123
+ writer = SFNTWriter(
1124
+ outFile,
1125
+ len(reader.tables),
1126
+ reader.sfntVersion,
1127
+ reader.flavor,
1128
+ reader.flavorData,
1129
+ )
1130
+ tables = list(reader.keys())
1131
+ for tag in sortedTagList(tables, tableOrder):
1132
+ writer[tag] = reader[tag]
1133
+ writer.close()
1134
+
1135
+
1136
+ def maxPowerOfTwo(x):
1137
+ """Return the highest exponent of two, so that
1138
+ (2 ** exponent) <= x. Return 0 if x is 0.
1139
+ """
1140
+ exponent = 0
1141
+ while x:
1142
+ x = x >> 1
1143
+ exponent = exponent + 1
1144
+ return max(exponent - 1, 0)
1145
+
1146
+
1147
+ def getSearchRange(n, itemSize=16):
1148
+ """Calculate searchRange, entrySelector, rangeShift."""
1149
+ # itemSize defaults to 16, for backward compatibility
1150
+ # with upstream fonttools.
1151
+ exponent = maxPowerOfTwo(n)
1152
+ searchRange = (2**exponent) * itemSize
1153
+ entrySelector = exponent
1154
+ rangeShift = max(0, n * itemSize - searchRange)
1155
+ return searchRange, entrySelector, rangeShift