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,884 @@
1
+ from fontTools.misc.fixedTools import (
2
+ fixedToFloat as fi2fl,
3
+ floatToFixed as fl2fi,
4
+ floatToFixedToStr as fl2str,
5
+ strToFixedToFloat as str2fl,
6
+ otRound,
7
+ )
8
+ from fontTools.misc.textTools import safeEval
9
+ import array
10
+ from collections import Counter, defaultdict
11
+ import io
12
+ import logging
13
+ import struct
14
+ import sys
15
+
16
+
17
+ # https://www.microsoft.com/typography/otspec/otvarcommonformats.htm
18
+
19
+ EMBEDDED_PEAK_TUPLE = 0x8000
20
+ INTERMEDIATE_REGION = 0x4000
21
+ PRIVATE_POINT_NUMBERS = 0x2000
22
+
23
+ DELTAS_ARE_ZERO = 0x80
24
+ DELTAS_ARE_WORDS = 0x40
25
+ DELTAS_ARE_LONGS = 0xC0
26
+ DELTAS_SIZE_MASK = 0xC0
27
+ DELTA_RUN_COUNT_MASK = 0x3F
28
+
29
+ POINTS_ARE_WORDS = 0x80
30
+ POINT_RUN_COUNT_MASK = 0x7F
31
+
32
+ TUPLES_SHARE_POINT_NUMBERS = 0x8000
33
+ TUPLE_COUNT_MASK = 0x0FFF
34
+ TUPLE_INDEX_MASK = 0x0FFF
35
+
36
+ log = logging.getLogger(__name__)
37
+
38
+
39
+ class TupleVariation(object):
40
+ def __init__(self, axes, coordinates):
41
+ self.axes = axes.copy()
42
+ self.coordinates = list(coordinates)
43
+
44
+ def __repr__(self):
45
+ axes = ",".join(
46
+ sorted(["%s=%s" % (name, value) for (name, value) in self.axes.items()])
47
+ )
48
+ return "<TupleVariation %s %s>" % (axes, self.coordinates)
49
+
50
+ def __eq__(self, other):
51
+ return self.coordinates == other.coordinates and self.axes == other.axes
52
+
53
+ def getUsedPoints(self):
54
+ # Empty set means "all points used".
55
+ if None not in self.coordinates:
56
+ return frozenset()
57
+ used = frozenset([i for i, p in enumerate(self.coordinates) if p is not None])
58
+ # Return None if no points used.
59
+ return used if used else None
60
+
61
+ def hasImpact(self):
62
+ """Returns True if this TupleVariation has any visible impact.
63
+
64
+ If the result is False, the TupleVariation can be omitted from the font
65
+ without making any visible difference.
66
+ """
67
+ return any(c is not None for c in self.coordinates)
68
+
69
+ def toXML(self, writer, axisTags):
70
+ writer.begintag("tuple")
71
+ writer.newline()
72
+ for axis in axisTags:
73
+ value = self.axes.get(axis)
74
+ if value is not None:
75
+ minValue, value, maxValue = value
76
+ defaultMinValue = min(value, 0.0) # -0.3 --> -0.3; 0.7 --> 0.0
77
+ defaultMaxValue = max(value, 0.0) # -0.3 --> 0.0; 0.7 --> 0.7
78
+ if minValue == defaultMinValue and maxValue == defaultMaxValue:
79
+ writer.simpletag("coord", axis=axis, value=fl2str(value, 14))
80
+ else:
81
+ attrs = [
82
+ ("axis", axis),
83
+ ("min", fl2str(minValue, 14)),
84
+ ("value", fl2str(value, 14)),
85
+ ("max", fl2str(maxValue, 14)),
86
+ ]
87
+ writer.simpletag("coord", attrs)
88
+ writer.newline()
89
+ wrote_any_deltas = False
90
+ for i, delta in enumerate(self.coordinates):
91
+ if type(delta) == tuple and len(delta) == 2:
92
+ writer.simpletag("delta", pt=i, x=delta[0], y=delta[1])
93
+ writer.newline()
94
+ wrote_any_deltas = True
95
+ elif type(delta) == int:
96
+ writer.simpletag("delta", cvt=i, value=delta)
97
+ writer.newline()
98
+ wrote_any_deltas = True
99
+ elif delta is not None:
100
+ log.error("bad delta format")
101
+ writer.comment("bad delta #%d" % i)
102
+ writer.newline()
103
+ wrote_any_deltas = True
104
+ if not wrote_any_deltas:
105
+ writer.comment("no deltas")
106
+ writer.newline()
107
+ writer.endtag("tuple")
108
+ writer.newline()
109
+
110
+ def fromXML(self, name, attrs, _content):
111
+ if name == "coord":
112
+ axis = attrs["axis"]
113
+ value = str2fl(attrs["value"], 14)
114
+ defaultMinValue = min(value, 0.0) # -0.3 --> -0.3; 0.7 --> 0.0
115
+ defaultMaxValue = max(value, 0.0) # -0.3 --> 0.0; 0.7 --> 0.7
116
+ minValue = str2fl(attrs.get("min", defaultMinValue), 14)
117
+ maxValue = str2fl(attrs.get("max", defaultMaxValue), 14)
118
+ self.axes[axis] = (minValue, value, maxValue)
119
+ elif name == "delta":
120
+ if "pt" in attrs:
121
+ point = safeEval(attrs["pt"])
122
+ x = safeEval(attrs["x"])
123
+ y = safeEval(attrs["y"])
124
+ self.coordinates[point] = (x, y)
125
+ elif "cvt" in attrs:
126
+ cvt = safeEval(attrs["cvt"])
127
+ value = safeEval(attrs["value"])
128
+ self.coordinates[cvt] = value
129
+ else:
130
+ log.warning("bad delta format: %s" % ", ".join(sorted(attrs.keys())))
131
+
132
+ def compile(
133
+ self, axisTags, sharedCoordIndices={}, pointData=None, *, optimizeSize=True
134
+ ):
135
+ assert set(self.axes.keys()) <= set(axisTags), (
136
+ "Unknown axis tag found.",
137
+ self.axes.keys(),
138
+ axisTags,
139
+ )
140
+
141
+ tupleData = []
142
+ auxData = []
143
+
144
+ if pointData is None:
145
+ usedPoints = self.getUsedPoints()
146
+ if usedPoints is None: # Nothing to encode
147
+ return b"", b""
148
+ pointData = self.compilePoints(usedPoints)
149
+
150
+ coord = self.compileCoord(axisTags)
151
+ flags = sharedCoordIndices.get(coord)
152
+ if flags is None:
153
+ flags = EMBEDDED_PEAK_TUPLE
154
+ tupleData.append(coord)
155
+
156
+ intermediateCoord = self.compileIntermediateCoord(axisTags)
157
+ if intermediateCoord is not None:
158
+ flags |= INTERMEDIATE_REGION
159
+ tupleData.append(intermediateCoord)
160
+
161
+ # pointData of b'' implies "use shared points".
162
+ if pointData:
163
+ flags |= PRIVATE_POINT_NUMBERS
164
+ auxData.append(pointData)
165
+
166
+ auxData.append(self.compileDeltas(optimizeSize=optimizeSize))
167
+ auxData = b"".join(auxData)
168
+
169
+ tupleData.insert(0, struct.pack(">HH", len(auxData), flags))
170
+ return b"".join(tupleData), auxData
171
+
172
+ def compileCoord(self, axisTags):
173
+ result = []
174
+ axes = self.axes
175
+ for axis in axisTags:
176
+ triple = axes.get(axis)
177
+ if triple is None:
178
+ result.append(b"\0\0")
179
+ else:
180
+ result.append(struct.pack(">h", fl2fi(triple[1], 14)))
181
+ return b"".join(result)
182
+
183
+ def compileIntermediateCoord(self, axisTags):
184
+ needed = False
185
+ for axis in axisTags:
186
+ minValue, value, maxValue = self.axes.get(axis, (0.0, 0.0, 0.0))
187
+ defaultMinValue = min(value, 0.0) # -0.3 --> -0.3; 0.7 --> 0.0
188
+ defaultMaxValue = max(value, 0.0) # -0.3 --> 0.0; 0.7 --> 0.7
189
+ if (minValue != defaultMinValue) or (maxValue != defaultMaxValue):
190
+ needed = True
191
+ break
192
+ if not needed:
193
+ return None
194
+ minCoords = []
195
+ maxCoords = []
196
+ for axis in axisTags:
197
+ minValue, value, maxValue = self.axes.get(axis, (0.0, 0.0, 0.0))
198
+ minCoords.append(struct.pack(">h", fl2fi(minValue, 14)))
199
+ maxCoords.append(struct.pack(">h", fl2fi(maxValue, 14)))
200
+ return b"".join(minCoords + maxCoords)
201
+
202
+ @staticmethod
203
+ def decompileCoord_(axisTags, data, offset):
204
+ coord = {}
205
+ pos = offset
206
+ for axis in axisTags:
207
+ coord[axis] = fi2fl(struct.unpack(">h", data[pos : pos + 2])[0], 14)
208
+ pos += 2
209
+ return coord, pos
210
+
211
+ @staticmethod
212
+ def compilePoints(points):
213
+ # If the set consists of all points in the glyph, it gets encoded with
214
+ # a special encoding: a single zero byte.
215
+ #
216
+ # To use this optimization, points passed in must be empty set.
217
+ # The following two lines are not strictly necessary as the main code
218
+ # below would emit the same. But this is most common and faster.
219
+ if not points:
220
+ return b"\0"
221
+
222
+ # In the 'gvar' table, the packing of point numbers is a little surprising.
223
+ # It consists of multiple runs, each being a delta-encoded list of integers.
224
+ # For example, the point set {17, 18, 19, 20, 21, 22, 23} gets encoded as
225
+ # [6, 17, 1, 1, 1, 1, 1, 1]. The first value (6) is the run length minus 1.
226
+ # There are two types of runs, with values being either 8 or 16 bit unsigned
227
+ # integers.
228
+ points = list(points)
229
+ points.sort()
230
+ numPoints = len(points)
231
+
232
+ result = bytearray()
233
+ # The binary representation starts with the total number of points in the set,
234
+ # encoded into one or two bytes depending on the value.
235
+ if numPoints < 0x80:
236
+ result.append(numPoints)
237
+ else:
238
+ result.append((numPoints >> 8) | 0x80)
239
+ result.append(numPoints & 0xFF)
240
+
241
+ MAX_RUN_LENGTH = 127
242
+ pos = 0
243
+ lastValue = 0
244
+ while pos < numPoints:
245
+ runLength = 0
246
+
247
+ headerPos = len(result)
248
+ result.append(0)
249
+
250
+ useByteEncoding = None
251
+ while pos < numPoints and runLength <= MAX_RUN_LENGTH:
252
+ curValue = points[pos]
253
+ delta = curValue - lastValue
254
+ if useByteEncoding is None:
255
+ useByteEncoding = 0 <= delta <= 0xFF
256
+ if useByteEncoding and (delta > 0xFF or delta < 0):
257
+ # we need to start a new run (which will not use byte encoding)
258
+ break
259
+ # TODO This never switches back to a byte-encoding from a short-encoding.
260
+ # That's suboptimal.
261
+ if useByteEncoding:
262
+ result.append(delta)
263
+ else:
264
+ result.append(delta >> 8)
265
+ result.append(delta & 0xFF)
266
+ lastValue = curValue
267
+ pos += 1
268
+ runLength += 1
269
+ if useByteEncoding:
270
+ result[headerPos] = runLength - 1
271
+ else:
272
+ result[headerPos] = (runLength - 1) | POINTS_ARE_WORDS
273
+
274
+ return result
275
+
276
+ @staticmethod
277
+ def decompilePoints_(numPoints, data, offset, tableTag):
278
+ """(numPoints, data, offset, tableTag) --> ([point1, point2, ...], newOffset)"""
279
+ assert tableTag in ("cvar", "gvar")
280
+ pos = offset
281
+ numPointsInData = data[pos]
282
+ pos += 1
283
+ if (numPointsInData & POINTS_ARE_WORDS) != 0:
284
+ numPointsInData = (numPointsInData & POINT_RUN_COUNT_MASK) << 8 | data[pos]
285
+ pos += 1
286
+ if numPointsInData == 0:
287
+ return (range(numPoints), pos)
288
+
289
+ result = []
290
+ while len(result) < numPointsInData:
291
+ runHeader = data[pos]
292
+ pos += 1
293
+ numPointsInRun = (runHeader & POINT_RUN_COUNT_MASK) + 1
294
+ point = 0
295
+ if (runHeader & POINTS_ARE_WORDS) != 0:
296
+ points = array.array("H")
297
+ pointsSize = numPointsInRun * 2
298
+ else:
299
+ points = array.array("B")
300
+ pointsSize = numPointsInRun
301
+ points.frombytes(data[pos : pos + pointsSize])
302
+ if sys.byteorder != "big":
303
+ points.byteswap()
304
+
305
+ assert len(points) == numPointsInRun
306
+ pos += pointsSize
307
+
308
+ result.extend(points)
309
+
310
+ # Convert relative to absolute
311
+ absolute = []
312
+ current = 0
313
+ for delta in result:
314
+ current += delta
315
+ absolute.append(current)
316
+ result = absolute
317
+ del absolute
318
+
319
+ badPoints = {str(p) for p in result if p < 0 or p >= numPoints}
320
+ if badPoints:
321
+ log.warning(
322
+ "point %s out of range in '%s' table"
323
+ % (",".join(sorted(badPoints)), tableTag)
324
+ )
325
+ return (result, pos)
326
+
327
+ def compileDeltas(self, optimizeSize=True):
328
+ deltaX = []
329
+ deltaY = []
330
+ if self.getCoordWidth() == 2:
331
+ for c in self.coordinates:
332
+ if c is None:
333
+ continue
334
+ deltaX.append(c[0])
335
+ deltaY.append(c[1])
336
+ else:
337
+ for c in self.coordinates:
338
+ if c is None:
339
+ continue
340
+ deltaX.append(c)
341
+ bytearr = bytearray()
342
+ self.compileDeltaValues_(deltaX, bytearr, optimizeSize=optimizeSize)
343
+ self.compileDeltaValues_(deltaY, bytearr, optimizeSize=optimizeSize)
344
+ return bytearr
345
+
346
+ @staticmethod
347
+ def compileDeltaValues_(deltas, bytearr=None, *, optimizeSize=True):
348
+ """[value1, value2, value3, ...] --> bytearray
349
+
350
+ Emits a sequence of runs. Each run starts with a
351
+ byte-sized header whose 6 least significant bits
352
+ (header & 0x3F) indicate how many values are encoded
353
+ in this run. The stored length is the actual length
354
+ minus one; run lengths are thus in the range [1..64].
355
+ If the header byte has its most significant bit (0x80)
356
+ set, all values in this run are zero, and no data
357
+ follows. Otherwise, the header byte is followed by
358
+ ((header & 0x3F) + 1) signed values. If (header &
359
+ 0x40) is clear, the delta values are stored as signed
360
+ bytes; if (header & 0x40) is set, the delta values are
361
+ signed 16-bit integers.
362
+ """ # Explaining the format because the 'gvar' spec is hard to understand.
363
+ if bytearr is None:
364
+ bytearr = bytearray()
365
+
366
+ pos = 0
367
+ numDeltas = len(deltas)
368
+
369
+ if optimizeSize:
370
+ while pos < numDeltas:
371
+ value = deltas[pos]
372
+ if value == 0:
373
+ pos = TupleVariation.encodeDeltaRunAsZeroes_(deltas, pos, bytearr)
374
+ elif -128 <= value <= 127:
375
+ pos = TupleVariation.encodeDeltaRunAsBytes_(deltas, pos, bytearr)
376
+ elif -32768 <= value <= 32767:
377
+ pos = TupleVariation.encodeDeltaRunAsWords_(deltas, pos, bytearr)
378
+ else:
379
+ pos = TupleVariation.encodeDeltaRunAsLongs_(deltas, pos, bytearr)
380
+ else:
381
+ minVal, maxVal = min(deltas), max(deltas)
382
+ if minVal == 0 == maxVal:
383
+ pos = TupleVariation.encodeDeltaRunAsZeroes_(deltas, pos, bytearr)
384
+ elif -128 <= minVal <= maxVal <= 127:
385
+ pos = TupleVariation.encodeDeltaRunAsBytes_(
386
+ deltas, pos, bytearr, optimizeSize=False
387
+ )
388
+ elif -32768 <= minVal <= maxVal <= 32767:
389
+ pos = TupleVariation.encodeDeltaRunAsWords_(
390
+ deltas, pos, bytearr, optimizeSize=False
391
+ )
392
+ else:
393
+ pos = TupleVariation.encodeDeltaRunAsLongs_(
394
+ deltas, pos, bytearr, optimizeSize=False
395
+ )
396
+
397
+ assert pos == numDeltas, (pos, numDeltas)
398
+
399
+ return bytearr
400
+
401
+ @staticmethod
402
+ def encodeDeltaRunAsZeroes_(deltas, offset, bytearr):
403
+ pos = offset
404
+ numDeltas = len(deltas)
405
+ while pos < numDeltas and deltas[pos] == 0:
406
+ pos += 1
407
+ runLength = pos - offset
408
+ while runLength >= 64:
409
+ bytearr.append(DELTAS_ARE_ZERO | 63)
410
+ runLength -= 64
411
+ if runLength:
412
+ bytearr.append(DELTAS_ARE_ZERO | (runLength - 1))
413
+ return pos
414
+
415
+ @staticmethod
416
+ def encodeDeltaRunAsBytes_(deltas, offset, bytearr, optimizeSize=True):
417
+ pos = offset
418
+ numDeltas = len(deltas)
419
+ while pos < numDeltas:
420
+ value = deltas[pos]
421
+ if not (-128 <= value <= 127):
422
+ break
423
+ # Within a byte-encoded run of deltas, a single zero
424
+ # is best stored literally as 0x00 value. However,
425
+ # if are two or more zeroes in a sequence, it is
426
+ # better to start a new run. For example, the sequence
427
+ # of deltas [15, 15, 0, 15, 15] becomes 6 bytes
428
+ # (04 0F 0F 00 0F 0F) when storing the zero value
429
+ # literally, but 7 bytes (01 0F 0F 80 01 0F 0F)
430
+ # when starting a new run.
431
+ if (
432
+ optimizeSize
433
+ and value == 0
434
+ and pos + 1 < numDeltas
435
+ and deltas[pos + 1] == 0
436
+ ):
437
+ break
438
+ pos += 1
439
+ runLength = pos - offset
440
+ while runLength >= 64:
441
+ bytearr.append(63)
442
+ bytearr.extend(array.array("b", deltas[offset : offset + 64]))
443
+ offset += 64
444
+ runLength -= 64
445
+ if runLength:
446
+ bytearr.append(runLength - 1)
447
+ bytearr.extend(array.array("b", deltas[offset:pos]))
448
+ return pos
449
+
450
+ @staticmethod
451
+ def encodeDeltaRunAsWords_(deltas, offset, bytearr, optimizeSize=True):
452
+ pos = offset
453
+ numDeltas = len(deltas)
454
+ while pos < numDeltas:
455
+ value = deltas[pos]
456
+
457
+ # Within a word-encoded run of deltas, it is easiest
458
+ # to start a new run (with a different encoding)
459
+ # whenever we encounter a zero value. For example,
460
+ # the sequence [0x6666, 0, 0x7777] needs 7 bytes when
461
+ # storing the zero literally (42 66 66 00 00 77 77),
462
+ # and equally 7 bytes when starting a new run
463
+ # (40 66 66 80 40 77 77).
464
+ if optimizeSize and value == 0:
465
+ break
466
+
467
+ # Within a word-encoded run of deltas, a single value
468
+ # in the range (-128..127) should be encoded literally
469
+ # because it is more compact. For example, the sequence
470
+ # [0x6666, 2, 0x7777] becomes 7 bytes when storing
471
+ # the value literally (42 66 66 00 02 77 77), but 8 bytes
472
+ # when starting a new run (40 66 66 00 02 40 77 77).
473
+ if (
474
+ optimizeSize
475
+ and (-128 <= value <= 127)
476
+ and pos + 1 < numDeltas
477
+ and (-128 <= deltas[pos + 1] <= 127)
478
+ ):
479
+ break
480
+
481
+ if not (-32768 <= value <= 32767):
482
+ break
483
+
484
+ pos += 1
485
+ runLength = pos - offset
486
+ while runLength >= 64:
487
+ bytearr.append(DELTAS_ARE_WORDS | 63)
488
+ a = array.array("h", deltas[offset : offset + 64])
489
+ if sys.byteorder != "big":
490
+ a.byteswap()
491
+ bytearr.extend(a)
492
+ offset += 64
493
+ runLength -= 64
494
+ if runLength:
495
+ bytearr.append(DELTAS_ARE_WORDS | (runLength - 1))
496
+ a = array.array("h", deltas[offset:pos])
497
+ if sys.byteorder != "big":
498
+ a.byteswap()
499
+ bytearr.extend(a)
500
+ return pos
501
+
502
+ @staticmethod
503
+ def encodeDeltaRunAsLongs_(deltas, offset, bytearr, optimizeSize=True):
504
+ pos = offset
505
+ numDeltas = len(deltas)
506
+ while pos < numDeltas:
507
+ value = deltas[pos]
508
+ if optimizeSize and -32768 <= value <= 32767:
509
+ break
510
+ pos += 1
511
+ runLength = pos - offset
512
+ while runLength >= 64:
513
+ bytearr.append(DELTAS_ARE_LONGS | 63)
514
+ a = array.array("i", deltas[offset : offset + 64])
515
+ if sys.byteorder != "big":
516
+ a.byteswap()
517
+ bytearr.extend(a)
518
+ offset += 64
519
+ runLength -= 64
520
+ if runLength:
521
+ bytearr.append(DELTAS_ARE_LONGS | (runLength - 1))
522
+ a = array.array("i", deltas[offset:pos])
523
+ if sys.byteorder != "big":
524
+ a.byteswap()
525
+ bytearr.extend(a)
526
+ return pos
527
+
528
+ @staticmethod
529
+ def decompileDeltas_(numDeltas, data, offset=0):
530
+ """(numDeltas, data, offset) --> ([delta, delta, ...], newOffset)"""
531
+ result = []
532
+ pos = offset
533
+ while len(result) < numDeltas if numDeltas is not None else pos < len(data):
534
+ runHeader = data[pos]
535
+ pos += 1
536
+ numDeltasInRun = (runHeader & DELTA_RUN_COUNT_MASK) + 1
537
+ if (runHeader & DELTAS_SIZE_MASK) == DELTAS_ARE_ZERO:
538
+ result.extend([0] * numDeltasInRun)
539
+ else:
540
+ if (runHeader & DELTAS_SIZE_MASK) == DELTAS_ARE_LONGS:
541
+ deltas = array.array("i")
542
+ deltasSize = numDeltasInRun * 4
543
+ elif (runHeader & DELTAS_SIZE_MASK) == DELTAS_ARE_WORDS:
544
+ deltas = array.array("h")
545
+ deltasSize = numDeltasInRun * 2
546
+ else:
547
+ deltas = array.array("b")
548
+ deltasSize = numDeltasInRun
549
+ deltas.frombytes(data[pos : pos + deltasSize])
550
+ if sys.byteorder != "big":
551
+ deltas.byteswap()
552
+ assert len(deltas) == numDeltasInRun, (len(deltas), numDeltasInRun)
553
+ pos += deltasSize
554
+ result.extend(deltas)
555
+ assert numDeltas is None or len(result) == numDeltas
556
+ return (result, pos)
557
+
558
+ @staticmethod
559
+ def getTupleSize_(flags, axisCount):
560
+ size = 4
561
+ if (flags & EMBEDDED_PEAK_TUPLE) != 0:
562
+ size += axisCount * 2
563
+ if (flags & INTERMEDIATE_REGION) != 0:
564
+ size += axisCount * 4
565
+ return size
566
+
567
+ def getCoordWidth(self):
568
+ """Return 2 if coordinates are (x, y) as in gvar, 1 if single values
569
+ as in cvar, or 0 if empty.
570
+ """
571
+ firstDelta = next((c for c in self.coordinates if c is not None), None)
572
+ if firstDelta is None:
573
+ return 0 # empty or has no impact
574
+ if type(firstDelta) in (int, float):
575
+ return 1
576
+ if type(firstDelta) is tuple and len(firstDelta) == 2:
577
+ return 2
578
+ raise TypeError(
579
+ "invalid type of delta; expected (int or float) number, or "
580
+ "Tuple[number, number]: %r" % firstDelta
581
+ )
582
+
583
+ def scaleDeltas(self, scalar):
584
+ if scalar == 1.0:
585
+ return # no change
586
+ coordWidth = self.getCoordWidth()
587
+ self.coordinates = [
588
+ (
589
+ None
590
+ if d is None
591
+ else d * scalar if coordWidth == 1 else (d[0] * scalar, d[1] * scalar)
592
+ )
593
+ for d in self.coordinates
594
+ ]
595
+
596
+ def roundDeltas(self):
597
+ coordWidth = self.getCoordWidth()
598
+ self.coordinates = [
599
+ (
600
+ None
601
+ if d is None
602
+ else otRound(d) if coordWidth == 1 else (otRound(d[0]), otRound(d[1]))
603
+ )
604
+ for d in self.coordinates
605
+ ]
606
+
607
+ def calcInferredDeltas(self, origCoords, endPts):
608
+ from fontTools.varLib.iup import iup_delta
609
+
610
+ if self.getCoordWidth() == 1:
611
+ raise TypeError("Only 'gvar' TupleVariation can have inferred deltas")
612
+ if None in self.coordinates:
613
+ if len(self.coordinates) != len(origCoords):
614
+ raise ValueError(
615
+ "Expected len(origCoords) == %d; found %d"
616
+ % (len(self.coordinates), len(origCoords))
617
+ )
618
+ self.coordinates = iup_delta(self.coordinates, origCoords, endPts)
619
+
620
+ def optimize(self, origCoords, endPts, tolerance=0.5, isComposite=False):
621
+ from fontTools.varLib.iup import iup_delta_optimize
622
+
623
+ if None in self.coordinates:
624
+ return # already optimized
625
+
626
+ deltaOpt = iup_delta_optimize(
627
+ self.coordinates, origCoords, endPts, tolerance=tolerance
628
+ )
629
+ if None in deltaOpt:
630
+ if isComposite and all(d is None for d in deltaOpt):
631
+ # Fix for macOS composites
632
+ # https://github.com/fonttools/fonttools/issues/1381
633
+ deltaOpt = [(0, 0)] + [None] * (len(deltaOpt) - 1)
634
+ # Use "optimized" version only if smaller...
635
+ varOpt = TupleVariation(self.axes, deltaOpt)
636
+
637
+ # Shouldn't matter that this is different from fvar...?
638
+ axisTags = sorted(self.axes.keys())
639
+ tupleData, auxData = self.compile(axisTags)
640
+ unoptimizedLength = len(tupleData) + len(auxData)
641
+ tupleData, auxData = varOpt.compile(axisTags)
642
+ optimizedLength = len(tupleData) + len(auxData)
643
+
644
+ if optimizedLength < unoptimizedLength:
645
+ self.coordinates = varOpt.coordinates
646
+
647
+ def __imul__(self, scalar):
648
+ self.scaleDeltas(scalar)
649
+ return self
650
+
651
+ def __iadd__(self, other):
652
+ if not isinstance(other, TupleVariation):
653
+ return NotImplemented
654
+ deltas1 = self.coordinates
655
+ length = len(deltas1)
656
+ deltas2 = other.coordinates
657
+ if len(deltas2) != length:
658
+ raise ValueError("cannot sum TupleVariation deltas with different lengths")
659
+ # 'None' values have different meanings in gvar vs cvar TupleVariations:
660
+ # within the gvar, when deltas are not provided explicitly for some points,
661
+ # they need to be inferred; whereas for the 'cvar' table, if deltas are not
662
+ # provided for some CVT values, then no adjustments are made (i.e. None == 0).
663
+ # Thus, we cannot sum deltas for gvar TupleVariations if they contain
664
+ # inferred inferred deltas (the latter need to be computed first using
665
+ # 'calcInferredDeltas' method), but we can treat 'None' values in cvar
666
+ # deltas as if they are zeros.
667
+ if self.getCoordWidth() == 2:
668
+ for i, d2 in zip(range(length), deltas2):
669
+ d1 = deltas1[i]
670
+ try:
671
+ deltas1[i] = (d1[0] + d2[0], d1[1] + d2[1])
672
+ except TypeError:
673
+ raise ValueError("cannot sum gvar deltas with inferred points")
674
+ else:
675
+ for i, d2 in zip(range(length), deltas2):
676
+ d1 = deltas1[i]
677
+ if d1 is not None and d2 is not None:
678
+ deltas1[i] = d1 + d2
679
+ elif d1 is None and d2 is not None:
680
+ deltas1[i] = d2
681
+ # elif d2 is None do nothing
682
+ return self
683
+
684
+
685
+ def decompileSharedTuples(axisTags, sharedTupleCount, data, offset):
686
+ result = []
687
+ for _ in range(sharedTupleCount):
688
+ t, offset = TupleVariation.decompileCoord_(axisTags, data, offset)
689
+ result.append(t)
690
+ return result
691
+
692
+
693
+ def compileSharedTuples(
694
+ axisTags, variations, MAX_NUM_SHARED_COORDS=TUPLE_INDEX_MASK + 1
695
+ ):
696
+ coordCount = Counter()
697
+ for var in variations:
698
+ coord = var.compileCoord(axisTags)
699
+ coordCount[coord] += 1
700
+ # In python < 3.7, most_common() ordering is non-deterministic
701
+ # so apply a sort to make sure the ordering is consistent.
702
+ sharedCoords = sorted(
703
+ coordCount.most_common(MAX_NUM_SHARED_COORDS),
704
+ key=lambda item: (-item[1], item[0]),
705
+ )
706
+ return [c[0] for c in sharedCoords if c[1] > 1]
707
+
708
+
709
+ def compileTupleVariationStore(
710
+ variations,
711
+ pointCount,
712
+ axisTags,
713
+ sharedTupleIndices,
714
+ useSharedPoints=True,
715
+ *,
716
+ optimizeSize=True,
717
+ ):
718
+ # pointCount is actually unused. Keeping for API compat.
719
+ del pointCount
720
+ newVariations = []
721
+ pointDatas = []
722
+ # Compile all points and figure out sharing if desired
723
+ sharedPoints = None
724
+
725
+ # Collect, count, and compile point-sets for all variation sets
726
+ pointSetCount = defaultdict(int)
727
+ for v in variations:
728
+ points = v.getUsedPoints()
729
+ if points is None: # Empty variations
730
+ continue
731
+ pointSetCount[points] += 1
732
+ newVariations.append(v)
733
+ pointDatas.append(points)
734
+ variations = newVariations
735
+ del newVariations
736
+
737
+ if not variations:
738
+ return (0, b"", b"")
739
+
740
+ n = len(variations[0].coordinates)
741
+ assert all(
742
+ len(v.coordinates) == n for v in variations
743
+ ), "Variation sets have different sizes"
744
+
745
+ compiledPoints = {
746
+ pointSet: TupleVariation.compilePoints(pointSet) for pointSet in pointSetCount
747
+ }
748
+
749
+ tupleVariationCount = len(variations)
750
+ tuples = []
751
+ data = []
752
+
753
+ if useSharedPoints:
754
+ # Find point-set which saves most bytes.
755
+ def key(pn):
756
+ pointSet = pn[0]
757
+ count = pn[1]
758
+ return len(compiledPoints[pointSet]) * (count - 1)
759
+
760
+ sharedPoints = max(pointSetCount.items(), key=key)[0]
761
+
762
+ data.append(compiledPoints[sharedPoints])
763
+ tupleVariationCount |= TUPLES_SHARE_POINT_NUMBERS
764
+
765
+ # b'' implies "use shared points"
766
+ pointDatas = [
767
+ compiledPoints[points] if points != sharedPoints else b""
768
+ for points in pointDatas
769
+ ]
770
+
771
+ for v, p in zip(variations, pointDatas):
772
+ thisTuple, thisData = v.compile(
773
+ axisTags, sharedTupleIndices, pointData=p, optimizeSize=optimizeSize
774
+ )
775
+
776
+ tuples.append(thisTuple)
777
+ data.append(thisData)
778
+
779
+ tuples = b"".join(tuples)
780
+ data = b"".join(data)
781
+ return tupleVariationCount, tuples, data
782
+
783
+
784
+ def decompileTupleVariationStore(
785
+ tableTag,
786
+ axisTags,
787
+ tupleVariationCount,
788
+ pointCount,
789
+ sharedTuples,
790
+ data,
791
+ pos,
792
+ dataPos,
793
+ ):
794
+ numAxes = len(axisTags)
795
+ result = []
796
+ if (tupleVariationCount & TUPLES_SHARE_POINT_NUMBERS) != 0:
797
+ sharedPoints, dataPos = TupleVariation.decompilePoints_(
798
+ pointCount, data, dataPos, tableTag
799
+ )
800
+ else:
801
+ sharedPoints = []
802
+ for _ in range(tupleVariationCount & TUPLE_COUNT_MASK):
803
+ dataSize, flags = struct.unpack(">HH", data[pos : pos + 4])
804
+ tupleSize = TupleVariation.getTupleSize_(flags, numAxes)
805
+ tupleData = data[pos : pos + tupleSize]
806
+ pointDeltaData = data[dataPos : dataPos + dataSize]
807
+ result.append(
808
+ decompileTupleVariation_(
809
+ pointCount,
810
+ sharedTuples,
811
+ sharedPoints,
812
+ tableTag,
813
+ axisTags,
814
+ tupleData,
815
+ pointDeltaData,
816
+ )
817
+ )
818
+ pos += tupleSize
819
+ dataPos += dataSize
820
+ return result
821
+
822
+
823
+ def decompileTupleVariation_(
824
+ pointCount, sharedTuples, sharedPoints, tableTag, axisTags, data, tupleData
825
+ ):
826
+ assert tableTag in ("cvar", "gvar"), tableTag
827
+ flags = struct.unpack(">H", data[2:4])[0]
828
+ pos = 4
829
+ if (flags & EMBEDDED_PEAK_TUPLE) == 0:
830
+ peak = sharedTuples[flags & TUPLE_INDEX_MASK]
831
+ else:
832
+ peak, pos = TupleVariation.decompileCoord_(axisTags, data, pos)
833
+ if (flags & INTERMEDIATE_REGION) != 0:
834
+ start, pos = TupleVariation.decompileCoord_(axisTags, data, pos)
835
+ end, pos = TupleVariation.decompileCoord_(axisTags, data, pos)
836
+ else:
837
+ start, end = inferRegion_(peak)
838
+ axes = {}
839
+ for axis in axisTags:
840
+ region = start[axis], peak[axis], end[axis]
841
+ if region != (0.0, 0.0, 0.0):
842
+ axes[axis] = region
843
+ pos = 0
844
+ if (flags & PRIVATE_POINT_NUMBERS) != 0:
845
+ points, pos = TupleVariation.decompilePoints_(
846
+ pointCount, tupleData, pos, tableTag
847
+ )
848
+ else:
849
+ points = sharedPoints
850
+
851
+ deltas = [None] * pointCount
852
+
853
+ if tableTag == "cvar":
854
+ deltas_cvt, pos = TupleVariation.decompileDeltas_(len(points), tupleData, pos)
855
+ for p, delta in zip(points, deltas_cvt):
856
+ if 0 <= p < pointCount:
857
+ deltas[p] = delta
858
+
859
+ elif tableTag == "gvar":
860
+ deltas_x, pos = TupleVariation.decompileDeltas_(len(points), tupleData, pos)
861
+ deltas_y, pos = TupleVariation.decompileDeltas_(len(points), tupleData, pos)
862
+ for p, x, y in zip(points, deltas_x, deltas_y):
863
+ if 0 <= p < pointCount:
864
+ deltas[p] = (x, y)
865
+
866
+ return TupleVariation(axes, deltas)
867
+
868
+
869
+ def inferRegion_(peak):
870
+ """Infer start and end for a (non-intermediate) region
871
+
872
+ This helper function computes the applicability region for
873
+ variation tuples whose INTERMEDIATE_REGION flag is not set in the
874
+ TupleVariationHeader structure. Variation tuples apply only to
875
+ certain regions of the variation space; outside that region, the
876
+ tuple has no effect. To make the binary encoding more compact,
877
+ TupleVariationHeaders can omit the intermediateStartTuple and
878
+ intermediateEndTuple fields.
879
+ """
880
+ start, end = {}, {}
881
+ for axis, value in peak.items():
882
+ start[axis] = min(value, 0.0) # -0.3 --> -0.3; 0.7 --> 0.0
883
+ end[axis] = max(value, 0.0) # -0.3 --> 0.0; 0.7 --> 0.7
884
+ return (start, end)