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,927 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ """T2CharString operator specializer and generalizer.
4
+
5
+ PostScript glyph drawing operations can be expressed in multiple different
6
+ ways. For example, as well as the ``lineto`` operator, there is also a
7
+ ``hlineto`` operator which draws a horizontal line, removing the need to
8
+ specify a ``dx`` coordinate, and a ``vlineto`` operator which draws a
9
+ vertical line, removing the need to specify a ``dy`` coordinate. As well
10
+ as decompiling :class:`fontTools.misc.psCharStrings.T2CharString` objects
11
+ into lists of operations, this module allows for conversion between general
12
+ and specific forms of the operation.
13
+
14
+ """
15
+
16
+ from fontTools.cffLib import maxStackLimit
17
+
18
+
19
+ def stringToProgram(string):
20
+ if isinstance(string, str):
21
+ string = string.split()
22
+ program = []
23
+ for token in string:
24
+ try:
25
+ token = int(token)
26
+ except ValueError:
27
+ try:
28
+ token = float(token)
29
+ except ValueError:
30
+ pass
31
+ program.append(token)
32
+ return program
33
+
34
+
35
+ def programToString(program):
36
+ return " ".join(str(x) for x in program)
37
+
38
+
39
+ def programToCommands(program, getNumRegions=None):
40
+ """Takes a T2CharString program list and returns list of commands.
41
+ Each command is a two-tuple of commandname,arg-list. The commandname might
42
+ be empty string if no commandname shall be emitted (used for glyph width,
43
+ hintmask/cntrmask argument, as well as stray arguments at the end of the
44
+ program (🤷).
45
+ 'getNumRegions' may be None, or a callable object. It must return the
46
+ number of regions. 'getNumRegions' takes a single argument, vsindex. It
47
+ returns the numRegions for the vsindex.
48
+ The Charstring may or may not start with a width value. If the first
49
+ non-blend operator has an odd number of arguments, then the first argument is
50
+ a width, and is popped off. This is complicated with blend operators, as
51
+ there may be more than one before the first hint or moveto operator, and each
52
+ one reduces several arguments to just one list argument. We have to sum the
53
+ number of arguments that are not part of the blend arguments, and all the
54
+ 'numBlends' values. We could instead have said that by definition, if there
55
+ is a blend operator, there is no width value, since CFF2 Charstrings don't
56
+ have width values. I discussed this with Behdad, and we are allowing for an
57
+ initial width value in this case because developers may assemble a CFF2
58
+ charstring from CFF Charstrings, which could have width values.
59
+ """
60
+
61
+ seenWidthOp = False
62
+ vsIndex = 0
63
+ lenBlendStack = 0
64
+ lastBlendIndex = 0
65
+ commands = []
66
+ stack = []
67
+ it = iter(program)
68
+
69
+ for token in it:
70
+ if not isinstance(token, str):
71
+ stack.append(token)
72
+ continue
73
+
74
+ if token == "blend":
75
+ assert getNumRegions is not None
76
+ numSourceFonts = 1 + getNumRegions(vsIndex)
77
+ # replace the blend op args on the stack with a single list
78
+ # containing all the blend op args.
79
+ numBlends = stack[-1]
80
+ numBlendArgs = numBlends * numSourceFonts + 1
81
+ # replace first blend op by a list of the blend ops.
82
+ stack[-numBlendArgs:] = [stack[-numBlendArgs:]]
83
+ lenStack = len(stack)
84
+ lenBlendStack += numBlends + lenStack - 1
85
+ lastBlendIndex = lenStack
86
+ # if a blend op exists, this is or will be a CFF2 charstring.
87
+ continue
88
+
89
+ elif token == "vsindex":
90
+ vsIndex = stack[-1]
91
+ assert type(vsIndex) is int
92
+
93
+ elif (not seenWidthOp) and token in {
94
+ "hstem",
95
+ "hstemhm",
96
+ "vstem",
97
+ "vstemhm",
98
+ "cntrmask",
99
+ "hintmask",
100
+ "hmoveto",
101
+ "vmoveto",
102
+ "rmoveto",
103
+ "endchar",
104
+ }:
105
+ seenWidthOp = True
106
+ parity = token in {"hmoveto", "vmoveto"}
107
+ if lenBlendStack:
108
+ # lenBlendStack has the number of args represented by the last blend
109
+ # arg and all the preceding args. We need to now add the number of
110
+ # args following the last blend arg.
111
+ numArgs = lenBlendStack + len(stack[lastBlendIndex:])
112
+ else:
113
+ numArgs = len(stack)
114
+ if numArgs and (numArgs % 2) ^ parity:
115
+ width = stack.pop(0)
116
+ commands.append(("", [width]))
117
+
118
+ if token in {"hintmask", "cntrmask"}:
119
+ if stack:
120
+ commands.append(("", stack))
121
+ commands.append((token, []))
122
+ commands.append(("", [next(it)]))
123
+ else:
124
+ commands.append((token, stack))
125
+ stack = []
126
+ if stack:
127
+ commands.append(("", stack))
128
+ return commands
129
+
130
+
131
+ def _flattenBlendArgs(args):
132
+ token_list = []
133
+ for arg in args:
134
+ if isinstance(arg, list):
135
+ token_list.extend(arg)
136
+ token_list.append("blend")
137
+ else:
138
+ token_list.append(arg)
139
+ return token_list
140
+
141
+
142
+ def commandsToProgram(commands):
143
+ """Takes a commands list as returned by programToCommands() and converts
144
+ it back to a T2CharString program list."""
145
+ program = []
146
+ for op, args in commands:
147
+ if any(isinstance(arg, list) for arg in args):
148
+ args = _flattenBlendArgs(args)
149
+ program.extend(args)
150
+ if op:
151
+ program.append(op)
152
+ return program
153
+
154
+
155
+ def _everyN(el, n):
156
+ """Group the list el into groups of size n"""
157
+ l = len(el)
158
+ if l % n != 0:
159
+ raise ValueError(el)
160
+ for i in range(0, l, n):
161
+ yield el[i : i + n]
162
+
163
+
164
+ class _GeneralizerDecombinerCommandsMap(object):
165
+ @staticmethod
166
+ def rmoveto(args):
167
+ if len(args) != 2:
168
+ raise ValueError(args)
169
+ yield ("rmoveto", args)
170
+
171
+ @staticmethod
172
+ def hmoveto(args):
173
+ if len(args) != 1:
174
+ raise ValueError(args)
175
+ yield ("rmoveto", [args[0], 0])
176
+
177
+ @staticmethod
178
+ def vmoveto(args):
179
+ if len(args) != 1:
180
+ raise ValueError(args)
181
+ yield ("rmoveto", [0, args[0]])
182
+
183
+ @staticmethod
184
+ def rlineto(args):
185
+ if not args:
186
+ raise ValueError(args)
187
+ for args in _everyN(args, 2):
188
+ yield ("rlineto", args)
189
+
190
+ @staticmethod
191
+ def hlineto(args):
192
+ if not args:
193
+ raise ValueError(args)
194
+ it = iter(args)
195
+ try:
196
+ while True:
197
+ yield ("rlineto", [next(it), 0])
198
+ yield ("rlineto", [0, next(it)])
199
+ except StopIteration:
200
+ pass
201
+
202
+ @staticmethod
203
+ def vlineto(args):
204
+ if not args:
205
+ raise ValueError(args)
206
+ it = iter(args)
207
+ try:
208
+ while True:
209
+ yield ("rlineto", [0, next(it)])
210
+ yield ("rlineto", [next(it), 0])
211
+ except StopIteration:
212
+ pass
213
+
214
+ @staticmethod
215
+ def rrcurveto(args):
216
+ if not args:
217
+ raise ValueError(args)
218
+ for args in _everyN(args, 6):
219
+ yield ("rrcurveto", args)
220
+
221
+ @staticmethod
222
+ def hhcurveto(args):
223
+ l = len(args)
224
+ if l < 4 or l % 4 > 1:
225
+ raise ValueError(args)
226
+ if l % 2 == 1:
227
+ yield ("rrcurveto", [args[1], args[0], args[2], args[3], args[4], 0])
228
+ args = args[5:]
229
+ for args in _everyN(args, 4):
230
+ yield ("rrcurveto", [args[0], 0, args[1], args[2], args[3], 0])
231
+
232
+ @staticmethod
233
+ def vvcurveto(args):
234
+ l = len(args)
235
+ if l < 4 or l % 4 > 1:
236
+ raise ValueError(args)
237
+ if l % 2 == 1:
238
+ yield ("rrcurveto", [args[0], args[1], args[2], args[3], 0, args[4]])
239
+ args = args[5:]
240
+ for args in _everyN(args, 4):
241
+ yield ("rrcurveto", [0, args[0], args[1], args[2], 0, args[3]])
242
+
243
+ @staticmethod
244
+ def hvcurveto(args):
245
+ l = len(args)
246
+ if l < 4 or l % 8 not in {0, 1, 4, 5}:
247
+ raise ValueError(args)
248
+ last_args = None
249
+ if l % 2 == 1:
250
+ lastStraight = l % 8 == 5
251
+ args, last_args = args[:-5], args[-5:]
252
+ it = _everyN(args, 4)
253
+ try:
254
+ while True:
255
+ args = next(it)
256
+ yield ("rrcurveto", [args[0], 0, args[1], args[2], 0, args[3]])
257
+ args = next(it)
258
+ yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], 0])
259
+ except StopIteration:
260
+ pass
261
+ if last_args:
262
+ args = last_args
263
+ if lastStraight:
264
+ yield ("rrcurveto", [args[0], 0, args[1], args[2], args[4], args[3]])
265
+ else:
266
+ yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], args[4]])
267
+
268
+ @staticmethod
269
+ def vhcurveto(args):
270
+ l = len(args)
271
+ if l < 4 or l % 8 not in {0, 1, 4, 5}:
272
+ raise ValueError(args)
273
+ last_args = None
274
+ if l % 2 == 1:
275
+ lastStraight = l % 8 == 5
276
+ args, last_args = args[:-5], args[-5:]
277
+ it = _everyN(args, 4)
278
+ try:
279
+ while True:
280
+ args = next(it)
281
+ yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], 0])
282
+ args = next(it)
283
+ yield ("rrcurveto", [args[0], 0, args[1], args[2], 0, args[3]])
284
+ except StopIteration:
285
+ pass
286
+ if last_args:
287
+ args = last_args
288
+ if lastStraight:
289
+ yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], args[4]])
290
+ else:
291
+ yield ("rrcurveto", [args[0], 0, args[1], args[2], args[4], args[3]])
292
+
293
+ @staticmethod
294
+ def rcurveline(args):
295
+ l = len(args)
296
+ if l < 8 or l % 6 != 2:
297
+ raise ValueError(args)
298
+ args, last_args = args[:-2], args[-2:]
299
+ for args in _everyN(args, 6):
300
+ yield ("rrcurveto", args)
301
+ yield ("rlineto", last_args)
302
+
303
+ @staticmethod
304
+ def rlinecurve(args):
305
+ l = len(args)
306
+ if l < 8 or l % 2 != 0:
307
+ raise ValueError(args)
308
+ args, last_args = args[:-6], args[-6:]
309
+ for args in _everyN(args, 2):
310
+ yield ("rlineto", args)
311
+ yield ("rrcurveto", last_args)
312
+
313
+
314
+ def _convertBlendOpToArgs(blendList):
315
+ # args is list of blend op args. Since we are supporting
316
+ # recursive blend op calls, some of these args may also
317
+ # be a list of blend op args, and need to be converted before
318
+ # we convert the current list.
319
+ if any([isinstance(arg, list) for arg in blendList]):
320
+ args = [
321
+ i
322
+ for e in blendList
323
+ for i in (_convertBlendOpToArgs(e) if isinstance(e, list) else [e])
324
+ ]
325
+ else:
326
+ args = blendList
327
+
328
+ # We now know that blendList contains a blend op argument list, even if
329
+ # some of the args are lists that each contain a blend op argument list.
330
+ # Convert from:
331
+ # [default font arg sequence x0,...,xn] + [delta tuple for x0] + ... + [delta tuple for xn]
332
+ # to:
333
+ # [ [x0] + [delta tuple for x0],
334
+ # ...,
335
+ # [xn] + [delta tuple for xn] ]
336
+ numBlends = args[-1]
337
+ # Can't use args.pop() when the args are being used in a nested list
338
+ # comprehension. See calling context
339
+ args = args[:-1]
340
+
341
+ l = len(args)
342
+ numRegions = l // numBlends - 1
343
+ if not (numBlends * (numRegions + 1) == l):
344
+ raise ValueError(blendList)
345
+
346
+ defaultArgs = [[arg] for arg in args[:numBlends]]
347
+ deltaArgs = args[numBlends:]
348
+ numDeltaValues = len(deltaArgs)
349
+ deltaList = [
350
+ deltaArgs[i : i + numRegions] for i in range(0, numDeltaValues, numRegions)
351
+ ]
352
+ blend_args = [a + b + [1] for a, b in zip(defaultArgs, deltaList)]
353
+ return blend_args
354
+
355
+
356
+ def generalizeCommands(commands, ignoreErrors=False):
357
+ result = []
358
+ mapping = _GeneralizerDecombinerCommandsMap
359
+ for op, args in commands:
360
+ # First, generalize any blend args in the arg list.
361
+ if any([isinstance(arg, list) for arg in args]):
362
+ try:
363
+ args = [
364
+ n
365
+ for arg in args
366
+ for n in (
367
+ _convertBlendOpToArgs(arg) if isinstance(arg, list) else [arg]
368
+ )
369
+ ]
370
+ except ValueError:
371
+ if ignoreErrors:
372
+ # Store op as data, such that consumers of commands do not have to
373
+ # deal with incorrect number of arguments.
374
+ result.append(("", args))
375
+ result.append(("", [op]))
376
+ else:
377
+ raise
378
+
379
+ func = getattr(mapping, op, None)
380
+ if func is None:
381
+ result.append((op, args))
382
+ continue
383
+ try:
384
+ for command in func(args):
385
+ result.append(command)
386
+ except ValueError:
387
+ if ignoreErrors:
388
+ # Store op as data, such that consumers of commands do not have to
389
+ # deal with incorrect number of arguments.
390
+ result.append(("", args))
391
+ result.append(("", [op]))
392
+ else:
393
+ raise
394
+ return result
395
+
396
+
397
+ def generalizeProgram(program, getNumRegions=None, **kwargs):
398
+ return commandsToProgram(
399
+ generalizeCommands(programToCommands(program, getNumRegions), **kwargs)
400
+ )
401
+
402
+
403
+ def _categorizeVector(v):
404
+ """
405
+ Takes X,Y vector v and returns one of r, h, v, or 0 depending on which
406
+ of X and/or Y are zero, plus tuple of nonzero ones. If both are zero,
407
+ it returns a single zero still.
408
+
409
+ >>> _categorizeVector((0,0))
410
+ ('0', (0,))
411
+ >>> _categorizeVector((1,0))
412
+ ('h', (1,))
413
+ >>> _categorizeVector((0,2))
414
+ ('v', (2,))
415
+ >>> _categorizeVector((1,2))
416
+ ('r', (1, 2))
417
+ """
418
+ if not v[0]:
419
+ if not v[1]:
420
+ return "0", v[:1]
421
+ else:
422
+ return "v", v[1:]
423
+ else:
424
+ if not v[1]:
425
+ return "h", v[:1]
426
+ else:
427
+ return "r", v
428
+
429
+
430
+ def _mergeCategories(a, b):
431
+ if a == "0":
432
+ return b
433
+ if b == "0":
434
+ return a
435
+ if a == b:
436
+ return a
437
+ return None
438
+
439
+
440
+ def _negateCategory(a):
441
+ if a == "h":
442
+ return "v"
443
+ if a == "v":
444
+ return "h"
445
+ assert a in "0r"
446
+ return a
447
+
448
+
449
+ def _convertToBlendCmds(args):
450
+ # return a list of blend commands, and
451
+ # the remaining non-blended args, if any.
452
+ num_args = len(args)
453
+ stack_use = 0
454
+ new_args = []
455
+ i = 0
456
+ while i < num_args:
457
+ arg = args[i]
458
+ i += 1
459
+ if not isinstance(arg, list):
460
+ new_args.append(arg)
461
+ stack_use += 1
462
+ else:
463
+ prev_stack_use = stack_use
464
+ # The arg is a tuple of blend values.
465
+ # These are each (master 0,delta 1..delta n, 1)
466
+ # Combine as many successive tuples as we can,
467
+ # up to the max stack limit.
468
+ num_sources = len(arg) - 1
469
+ blendlist = [arg]
470
+ stack_use += 1 + num_sources # 1 for the num_blends arg
471
+
472
+ # if we are here, max stack is the CFF2 max stack.
473
+ # I use the CFF2 max stack limit here rather than
474
+ # the 'maxstack' chosen by the client, as the default
475
+ # maxstack may have been used unintentionally. For all
476
+ # the other operators, this just produces a little less
477
+ # optimization, but here it puts a hard (and low) limit
478
+ # on the number of source fonts that can be used.
479
+ #
480
+ # Make sure the stack depth does not exceed (maxstack - 1), so
481
+ # that subroutinizer can insert subroutine calls at any point.
482
+ while (
483
+ (i < num_args)
484
+ and isinstance(args[i], list)
485
+ and stack_use + num_sources < maxStackLimit
486
+ ):
487
+ blendlist.append(args[i])
488
+ i += 1
489
+ stack_use += num_sources
490
+ # blendList now contains as many single blend tuples as can be
491
+ # combined without exceeding the CFF2 stack limit.
492
+ num_blends = len(blendlist)
493
+ # append the 'num_blends' default font values
494
+ blend_args = []
495
+ for arg in blendlist:
496
+ blend_args.append(arg[0])
497
+ for arg in blendlist:
498
+ assert arg[-1] == 1
499
+ blend_args.extend(arg[1:-1])
500
+ blend_args.append(num_blends)
501
+ new_args.append(blend_args)
502
+ stack_use = prev_stack_use + num_blends
503
+
504
+ return new_args
505
+
506
+
507
+ def _addArgs(a, b):
508
+ if isinstance(b, list):
509
+ if isinstance(a, list):
510
+ if len(a) != len(b) or a[-1] != b[-1]:
511
+ raise ValueError()
512
+ return [_addArgs(va, vb) for va, vb in zip(a[:-1], b[:-1])] + [a[-1]]
513
+ else:
514
+ a, b = b, a
515
+ if isinstance(a, list):
516
+ assert a[-1] == 1
517
+ return [_addArgs(a[0], b)] + a[1:]
518
+ return a + b
519
+
520
+
521
+ def _argsStackUse(args):
522
+ stackLen = 0
523
+ maxLen = 0
524
+ for arg in args:
525
+ if type(arg) is list:
526
+ # Blended arg
527
+ maxLen = max(maxLen, stackLen + _argsStackUse(arg))
528
+ stackLen += arg[-1]
529
+ else:
530
+ stackLen += 1
531
+ return max(stackLen, maxLen)
532
+
533
+
534
+ def specializeCommands(
535
+ commands,
536
+ ignoreErrors=False,
537
+ generalizeFirst=True,
538
+ preserveTopology=False,
539
+ maxstack=48,
540
+ ):
541
+ # We perform several rounds of optimizations. They are carefully ordered and are:
542
+ #
543
+ # 0. Generalize commands.
544
+ # This ensures that they are in our expected simple form, with each line/curve only
545
+ # having arguments for one segment, and using the generic form (rlineto/rrcurveto).
546
+ # If caller is sure the input is in this form, they can turn off generalization to
547
+ # save time.
548
+ #
549
+ # 1. Combine successive rmoveto operations.
550
+ #
551
+ # 2. Specialize rmoveto/rlineto/rrcurveto operators into horizontal/vertical variants.
552
+ # We specialize into some, made-up, variants as well, which simplifies following
553
+ # passes.
554
+ #
555
+ # 3. Merge or delete redundant operations, to the extent requested.
556
+ # OpenType spec declares point numbers in CFF undefined. As such, we happily
557
+ # change topology. If client relies on point numbers (in GPOS anchors, or for
558
+ # hinting purposes(what?)) they can turn this off.
559
+ #
560
+ # 4. Peephole optimization to revert back some of the h/v variants back into their
561
+ # original "relative" operator (rline/rrcurveto) if that saves a byte.
562
+ #
563
+ # 5. Combine adjacent operators when possible, minding not to go over max stack size.
564
+ #
565
+ # 6. Resolve any remaining made-up operators into real operators.
566
+ #
567
+ # I have convinced myself that this produces optimal bytecode (except for, possibly
568
+ # one byte each time maxstack size prohibits combining.) YMMV, but you'd be wrong. :-)
569
+ # A dynamic-programming approach can do the same but would be significantly slower.
570
+ #
571
+ # 7. For any args which are blend lists, convert them to a blend command.
572
+
573
+ # 0. Generalize commands.
574
+ if generalizeFirst:
575
+ commands = generalizeCommands(commands, ignoreErrors=ignoreErrors)
576
+ else:
577
+ commands = list(commands) # Make copy since we modify in-place later.
578
+
579
+ # 1. Combine successive rmoveto operations.
580
+ for i in range(len(commands) - 1, 0, -1):
581
+ if "rmoveto" == commands[i][0] == commands[i - 1][0]:
582
+ v1, v2 = commands[i - 1][1], commands[i][1]
583
+ commands[i - 1] = (
584
+ "rmoveto",
585
+ [_addArgs(v1[0], v2[0]), _addArgs(v1[1], v2[1])],
586
+ )
587
+ del commands[i]
588
+
589
+ # 2. Specialize rmoveto/rlineto/rrcurveto operators into horizontal/vertical variants.
590
+ #
591
+ # We, in fact, specialize into more, made-up, variants that special-case when both
592
+ # X and Y components are zero. This simplifies the following optimization passes.
593
+ # This case is rare, but OCD does not let me skip it.
594
+ #
595
+ # After this round, we will have four variants that use the following mnemonics:
596
+ #
597
+ # - 'r' for relative, ie. non-zero X and non-zero Y,
598
+ # - 'h' for horizontal, ie. zero X and non-zero Y,
599
+ # - 'v' for vertical, ie. non-zero X and zero Y,
600
+ # - '0' for zeros, ie. zero X and zero Y.
601
+ #
602
+ # The '0' pseudo-operators are not part of the spec, but help simplify the following
603
+ # optimization rounds. We resolve them at the end. So, after this, we will have four
604
+ # moveto and four lineto variants:
605
+ #
606
+ # - 0moveto, 0lineto
607
+ # - hmoveto, hlineto
608
+ # - vmoveto, vlineto
609
+ # - rmoveto, rlineto
610
+ #
611
+ # and sixteen curveto variants. For example, a '0hcurveto' operator means a curve
612
+ # dx0,dy0,dx1,dy1,dx2,dy2,dx3,dy3 where dx0, dx1, and dy3 are zero but not dx3.
613
+ # An 'rvcurveto' means dx3 is zero but not dx0,dy0,dy3.
614
+ #
615
+ # There are nine different variants of curves without the '0'. Those nine map exactly
616
+ # to the existing curve variants in the spec: rrcurveto, and the four variants hhcurveto,
617
+ # vvcurveto, hvcurveto, and vhcurveto each cover two cases, one with an odd number of
618
+ # arguments and one without. Eg. an hhcurveto with an extra argument (odd number of
619
+ # arguments) is in fact an rhcurveto. The operators in the spec are designed such that
620
+ # all four of rhcurveto, rvcurveto, hrcurveto, and vrcurveto are encodable for one curve.
621
+ #
622
+ # Of the curve types with '0', the 00curveto is equivalent to a lineto variant. The rest
623
+ # of the curve types with a 0 need to be encoded as a h or v variant. Ie. a '0' can be
624
+ # thought of a "don't care" and can be used as either an 'h' or a 'v'. As such, we always
625
+ # encode a number 0 as argument when we use a '0' variant. Later on, we can just substitute
626
+ # the '0' with either 'h' or 'v' and it works.
627
+ #
628
+ # When we get to curve splines however, things become more complicated... XXX finish this.
629
+ # There's one more complexity with splines. If one side of the spline is not horizontal or
630
+ # vertical (or zero), ie. if it's 'r', then it limits which spline types we can encode.
631
+ # Only hhcurveto and vvcurveto operators can encode a spline starting with 'r', and
632
+ # only hvcurveto and vhcurveto operators can encode a spline ending with 'r'.
633
+ # This limits our merge opportunities later.
634
+ #
635
+ for i in range(len(commands)):
636
+ op, args = commands[i]
637
+
638
+ if op in {"rmoveto", "rlineto"}:
639
+ c, args = _categorizeVector(args)
640
+ commands[i] = c + op[1:], args
641
+ continue
642
+
643
+ if op == "rrcurveto":
644
+ c1, args1 = _categorizeVector(args[:2])
645
+ c2, args2 = _categorizeVector(args[-2:])
646
+ commands[i] = c1 + c2 + "curveto", args1 + args[2:4] + args2
647
+ continue
648
+
649
+ # 3. Merge or delete redundant operations, to the extent requested.
650
+ #
651
+ # TODO
652
+ # A 0moveto that comes before all other path operations can be removed.
653
+ # though I find conflicting evidence for this.
654
+ #
655
+ # TODO
656
+ # "If hstem and vstem hints are both declared at the beginning of a
657
+ # CharString, and this sequence is followed directly by the hintmask or
658
+ # cntrmask operators, then the vstem hint operator (or, if applicable,
659
+ # the vstemhm operator) need not be included."
660
+ #
661
+ # "The sequence and form of a CFF2 CharString program may be represented as:
662
+ # {hs* vs* cm* hm* mt subpath}? {mt subpath}*"
663
+ #
664
+ # https://www.microsoft.com/typography/otspec/cff2charstr.htm#section3.1
665
+ #
666
+ # For Type2 CharStrings the sequence is:
667
+ # w? {hs* vs* cm* hm* mt subpath}? {mt subpath}* endchar"
668
+
669
+ # Some other redundancies change topology (point numbers).
670
+ if not preserveTopology:
671
+ for i in range(len(commands) - 1, -1, -1):
672
+ op, args = commands[i]
673
+
674
+ # A 00curveto is demoted to a (specialized) lineto.
675
+ if op == "00curveto":
676
+ assert len(args) == 4
677
+ c, args = _categorizeVector(args[1:3])
678
+ op = c + "lineto"
679
+ commands[i] = op, args
680
+ # and then...
681
+
682
+ # A 0lineto can be deleted.
683
+ if op == "0lineto":
684
+ del commands[i]
685
+ continue
686
+
687
+ # Merge adjacent hlineto's and vlineto's.
688
+ # In CFF2 charstrings from variable fonts, each
689
+ # arg item may be a list of blendable values, one from
690
+ # each source font.
691
+ if i and op in {"hlineto", "vlineto"} and (op == commands[i - 1][0]):
692
+ _, other_args = commands[i - 1]
693
+ assert len(args) == 1 and len(other_args) == 1
694
+ try:
695
+ new_args = [_addArgs(args[0], other_args[0])]
696
+ except ValueError:
697
+ continue
698
+ commands[i - 1] = (op, new_args)
699
+ del commands[i]
700
+ continue
701
+
702
+ # 4. Peephole optimization to revert back some of the h/v variants back into their
703
+ # original "relative" operator (rline/rrcurveto) if that saves a byte.
704
+ for i in range(1, len(commands) - 1):
705
+ op, args = commands[i]
706
+ prv, nxt = commands[i - 1][0], commands[i + 1][0]
707
+
708
+ if op in {"0lineto", "hlineto", "vlineto"} and prv == nxt == "rlineto":
709
+ assert len(args) == 1
710
+ args = [0, args[0]] if op[0] == "v" else [args[0], 0]
711
+ commands[i] = ("rlineto", args)
712
+ continue
713
+
714
+ if op[2:] == "curveto" and len(args) == 5 and prv == nxt == "rrcurveto":
715
+ assert (op[0] == "r") ^ (op[1] == "r")
716
+ if op[0] == "v":
717
+ pos = 0
718
+ elif op[0] != "r":
719
+ pos = 1
720
+ elif op[1] == "v":
721
+ pos = 4
722
+ else:
723
+ pos = 5
724
+ # Insert, while maintaining the type of args (can be tuple or list).
725
+ args = args[:pos] + type(args)((0,)) + args[pos:]
726
+ commands[i] = ("rrcurveto", args)
727
+ continue
728
+
729
+ # 5. Combine adjacent operators when possible, minding not to go over max stack size.
730
+ stackUse = _argsStackUse(commands[-1][1]) if commands else 0
731
+ for i in range(len(commands) - 1, 0, -1):
732
+ op1, args1 = commands[i - 1]
733
+ op2, args2 = commands[i]
734
+ new_op = None
735
+
736
+ # Merge logic...
737
+ if {op1, op2} <= {"rlineto", "rrcurveto"}:
738
+ if op1 == op2:
739
+ new_op = op1
740
+ else:
741
+ l = len(args2)
742
+ if op2 == "rrcurveto" and l == 6:
743
+ new_op = "rlinecurve"
744
+ elif l == 2:
745
+ new_op = "rcurveline"
746
+
747
+ elif (op1, op2) in {("rlineto", "rlinecurve"), ("rrcurveto", "rcurveline")}:
748
+ new_op = op2
749
+
750
+ elif {op1, op2} == {"vlineto", "hlineto"}:
751
+ new_op = op1
752
+
753
+ elif "curveto" == op1[2:] == op2[2:]:
754
+ d0, d1 = op1[:2]
755
+ d2, d3 = op2[:2]
756
+
757
+ if d1 == "r" or d2 == "r" or d0 == d3 == "r":
758
+ continue
759
+
760
+ d = _mergeCategories(d1, d2)
761
+ if d is None:
762
+ continue
763
+ if d0 == "r":
764
+ d = _mergeCategories(d, d3)
765
+ if d is None:
766
+ continue
767
+ new_op = "r" + d + "curveto"
768
+ elif d3 == "r":
769
+ d0 = _mergeCategories(d0, _negateCategory(d))
770
+ if d0 is None:
771
+ continue
772
+ new_op = d0 + "r" + "curveto"
773
+ else:
774
+ d0 = _mergeCategories(d0, d3)
775
+ if d0 is None:
776
+ continue
777
+ new_op = d0 + d + "curveto"
778
+
779
+ # Make sure the stack depth does not exceed (maxstack - 1), so
780
+ # that subroutinizer can insert subroutine calls at any point.
781
+ args1StackUse = _argsStackUse(args1)
782
+ combinedStackUse = max(args1StackUse, len(args1) + stackUse)
783
+ if new_op and combinedStackUse < maxstack:
784
+ commands[i - 1] = (new_op, args1 + args2)
785
+ del commands[i]
786
+ stackUse = combinedStackUse
787
+ else:
788
+ stackUse = args1StackUse
789
+
790
+ # 6. Resolve any remaining made-up operators into real operators.
791
+ for i in range(len(commands)):
792
+ op, args = commands[i]
793
+
794
+ if op in {"0moveto", "0lineto"}:
795
+ commands[i] = "h" + op[1:], args
796
+ continue
797
+
798
+ if op[2:] == "curveto" and op[:2] not in {"rr", "hh", "vv", "vh", "hv"}:
799
+ l = len(args)
800
+
801
+ op0, op1 = op[:2]
802
+ if (op0 == "r") ^ (op1 == "r"):
803
+ assert l % 2 == 1
804
+ if op0 == "0":
805
+ op0 = "h"
806
+ if op1 == "0":
807
+ op1 = "h"
808
+ if op0 == "r":
809
+ op0 = op1
810
+ if op1 == "r":
811
+ op1 = _negateCategory(op0)
812
+ assert {op0, op1} <= {"h", "v"}, (op0, op1)
813
+
814
+ if l % 2:
815
+ if op0 != op1: # vhcurveto / hvcurveto
816
+ if (op0 == "h") ^ (l % 8 == 1):
817
+ # Swap last two args order
818
+ args = args[:-2] + args[-1:] + args[-2:-1]
819
+ else: # hhcurveto / vvcurveto
820
+ if op0 == "h": # hhcurveto
821
+ # Swap first two args order
822
+ args = args[1:2] + args[:1] + args[2:]
823
+
824
+ commands[i] = op0 + op1 + "curveto", args
825
+ continue
826
+
827
+ # 7. For any series of args which are blend lists, convert the series to a single blend arg.
828
+ for i in range(len(commands)):
829
+ op, args = commands[i]
830
+ if any(isinstance(arg, list) for arg in args):
831
+ commands[i] = op, _convertToBlendCmds(args)
832
+
833
+ return commands
834
+
835
+
836
+ def specializeProgram(program, getNumRegions=None, **kwargs):
837
+ return commandsToProgram(
838
+ specializeCommands(programToCommands(program, getNumRegions), **kwargs)
839
+ )
840
+
841
+
842
+ if __name__ == "__main__":
843
+ import sys
844
+
845
+ if len(sys.argv) == 1:
846
+ import doctest
847
+
848
+ sys.exit(doctest.testmod().failed)
849
+
850
+ import argparse
851
+
852
+ parser = argparse.ArgumentParser(
853
+ "fonttools cffLib.specializer",
854
+ description="CFF CharString generalizer/specializer",
855
+ )
856
+ parser.add_argument("program", metavar="command", nargs="*", help="Commands.")
857
+ parser.add_argument(
858
+ "--num-regions",
859
+ metavar="NumRegions",
860
+ nargs="*",
861
+ default=None,
862
+ help="Number of variable-font regions for blend opertaions.",
863
+ )
864
+ parser.add_argument(
865
+ "--font",
866
+ metavar="FONTFILE",
867
+ default=None,
868
+ help="CFF2 font to specialize.",
869
+ )
870
+ parser.add_argument(
871
+ "-o",
872
+ "--output-file",
873
+ type=str,
874
+ help="Output font file name.",
875
+ )
876
+
877
+ options = parser.parse_args(sys.argv[1:])
878
+
879
+ if options.program:
880
+ getNumRegions = (
881
+ None
882
+ if options.num_regions is None
883
+ else lambda vsIndex: int(
884
+ options.num_regions[0 if vsIndex is None else vsIndex]
885
+ )
886
+ )
887
+
888
+ program = stringToProgram(options.program)
889
+ print("Program:")
890
+ print(programToString(program))
891
+ commands = programToCommands(program, getNumRegions)
892
+ print("Commands:")
893
+ print(commands)
894
+ program2 = commandsToProgram(commands)
895
+ print("Program from commands:")
896
+ print(programToString(program2))
897
+ assert program == program2
898
+ print("Generalized program:")
899
+ print(programToString(generalizeProgram(program, getNumRegions)))
900
+ print("Specialized program:")
901
+ print(programToString(specializeProgram(program, getNumRegions)))
902
+
903
+ if options.font:
904
+ from fontTools.ttLib import TTFont
905
+
906
+ font = TTFont(options.font)
907
+ cff2 = font["CFF2"].cff.topDictIndex[0]
908
+ charstrings = cff2.CharStrings
909
+ for glyphName in charstrings.keys():
910
+ charstring = charstrings[glyphName]
911
+ charstring.decompile()
912
+ getNumRegions = charstring.private.getNumRegions
913
+ charstring.program = specializeProgram(
914
+ charstring.program, getNumRegions, maxstack=maxStackLimit
915
+ )
916
+
917
+ if options.output_file is None:
918
+ from fontTools.misc.cliTools import makeOutputFileName
919
+
920
+ outfile = makeOutputFileName(
921
+ options.font, overWrite=True, suffix=".specialized"
922
+ )
923
+ else:
924
+ outfile = options.output_file
925
+ if outfile:
926
+ print("Saving", outfile)
927
+ font.save(outfile)