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,3465 @@
1
+ from __future__ import annotations
2
+
3
+ from collections import namedtuple, OrderedDict
4
+ import itertools
5
+ from typing import Dict, Union
6
+ from fontTools.misc.fixedTools import fixedToFloat
7
+ from fontTools.misc.roundTools import otRound
8
+ from fontTools import ttLib
9
+ from fontTools.ttLib.tables import otTables as ot
10
+ from fontTools.ttLib.tables.otBase import (
11
+ ValueRecord,
12
+ valueRecordFormatDict,
13
+ OTLOffsetOverflowError,
14
+ OTTableWriter,
15
+ )
16
+ from fontTools.ttLib.ttFont import TTFont
17
+ from fontTools.feaLib.ast import STATNameStatement
18
+ from fontTools.otlLib.optimize.gpos import (
19
+ _compression_level_from_env,
20
+ compact_lookup,
21
+ )
22
+ from fontTools.otlLib.error import OpenTypeLibError
23
+ from fontTools.misc.loggingTools import deprecateFunction
24
+ from functools import reduce
25
+ import logging
26
+ import copy
27
+
28
+
29
+ log = logging.getLogger(__name__)
30
+
31
+
32
+ def buildCoverage(glyphs, glyphMap):
33
+ """Builds a coverage table.
34
+
35
+ Coverage tables (as defined in the `OpenType spec <https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#coverage-table>`__)
36
+ are used in all OpenType Layout lookups apart from the Extension type, and
37
+ define the glyphs involved in a layout subtable. This allows shaping engines
38
+ to compare the glyph stream with the coverage table and quickly determine
39
+ whether a subtable should be involved in a shaping operation.
40
+
41
+ This function takes a list of glyphs and a glyphname-to-ID map, and
42
+ returns a ``Coverage`` object representing the coverage table.
43
+
44
+ Example::
45
+
46
+ glyphMap = font.getReverseGlyphMap()
47
+ glyphs = [ "A", "B", "C" ]
48
+ coverage = buildCoverage(glyphs, glyphMap)
49
+
50
+ Args:
51
+ glyphs: a sequence of glyph names.
52
+ glyphMap: a glyph name to ID map, typically returned from
53
+ ``font.getReverseGlyphMap()``.
54
+
55
+ Returns:
56
+ An ``otTables.Coverage`` object or ``None`` if there are no glyphs
57
+ supplied.
58
+ """
59
+
60
+ if not glyphs:
61
+ return None
62
+ self = ot.Coverage()
63
+ try:
64
+ self.glyphs = sorted(set(glyphs), key=glyphMap.__getitem__)
65
+ except KeyError as e:
66
+ raise ValueError(f"Could not find glyph {e} in font") from e
67
+
68
+ return self
69
+
70
+
71
+ LOOKUP_FLAG_RIGHT_TO_LEFT = 0x0001
72
+ LOOKUP_FLAG_IGNORE_BASE_GLYPHS = 0x0002
73
+ LOOKUP_FLAG_IGNORE_LIGATURES = 0x0004
74
+ LOOKUP_FLAG_IGNORE_MARKS = 0x0008
75
+ LOOKUP_FLAG_USE_MARK_FILTERING_SET = 0x0010
76
+
77
+
78
+ def buildLookup(subtables, flags=0, markFilterSet=None, table=None, extension=False):
79
+ """Turns a collection of rules into a lookup.
80
+
81
+ A Lookup (as defined in the `OpenType Spec <https://docs.microsoft.com/en-gb/typography/opentype/spec/chapter2#lookupTbl>`__)
82
+ wraps the individual rules in a layout operation (substitution or
83
+ positioning) in a data structure expressing their overall lookup type -
84
+ for example, single substitution, mark-to-base attachment, and so on -
85
+ as well as the lookup flags and any mark filtering sets. You may import
86
+ the following constants to express lookup flags:
87
+
88
+ - ``LOOKUP_FLAG_RIGHT_TO_LEFT``
89
+ - ``LOOKUP_FLAG_IGNORE_BASE_GLYPHS``
90
+ - ``LOOKUP_FLAG_IGNORE_LIGATURES``
91
+ - ``LOOKUP_FLAG_IGNORE_MARKS``
92
+ - ``LOOKUP_FLAG_USE_MARK_FILTERING_SET``
93
+
94
+ Args:
95
+ subtables: A list of layout subtable objects (e.g.
96
+ ``MultipleSubst``, ``PairPos``, etc.) or ``None``.
97
+ flags (int): This lookup's flags.
98
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
99
+ an integer representing the filtering set to be used for this
100
+ lookup. If a mark filtering set is provided,
101
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
102
+ flags.
103
+ table (str): The name of the table this lookup belongs to, e.g. "GPOS" or "GSUB".
104
+ extension (bool): ``True`` if this is an extension lookup, ``False`` otherwise.
105
+
106
+ Returns:
107
+ An ``otTables.Lookup`` object or ``None`` if there are no subtables
108
+ supplied.
109
+ """
110
+ if subtables is None:
111
+ return None
112
+ subtables = [st for st in subtables if st is not None]
113
+ if not subtables:
114
+ return None
115
+ assert all(
116
+ t.LookupType == subtables[0].LookupType for t in subtables
117
+ ), "all subtables must have the same LookupType; got %s" % repr(
118
+ [t.LookupType for t in subtables]
119
+ )
120
+
121
+ if extension:
122
+ assert table in ("GPOS", "GSUB")
123
+ lookupType = 7 if table == "GSUB" else 9
124
+ extSubTableClass = ot.lookupTypes[table][lookupType]
125
+ for i, st in enumerate(subtables):
126
+ subtables[i] = extSubTableClass()
127
+ subtables[i].Format = 1
128
+ subtables[i].ExtSubTable = st
129
+ subtables[i].ExtensionLookupType = st.LookupType
130
+ else:
131
+ lookupType = subtables[0].LookupType
132
+
133
+ self = ot.Lookup()
134
+ self.LookupType = lookupType
135
+ self.LookupFlag = flags
136
+ self.SubTable = subtables
137
+ self.SubTableCount = len(self.SubTable)
138
+ if markFilterSet is not None:
139
+ self.LookupFlag |= LOOKUP_FLAG_USE_MARK_FILTERING_SET
140
+ assert isinstance(markFilterSet, int), markFilterSet
141
+ self.MarkFilteringSet = markFilterSet
142
+ else:
143
+ assert (self.LookupFlag & LOOKUP_FLAG_USE_MARK_FILTERING_SET) == 0, (
144
+ "if markFilterSet is None, flags must not set "
145
+ "LOOKUP_FLAG_USE_MARK_FILTERING_SET; flags=0x%04x" % flags
146
+ )
147
+ return self
148
+
149
+
150
+ class LookupBuilder(object):
151
+ SUBTABLE_BREAK_ = "SUBTABLE_BREAK"
152
+
153
+ def __init__(self, font, location, table, lookup_type, extension=False):
154
+ self.font = font
155
+ self.glyphMap = font.getReverseGlyphMap()
156
+ self.location = location
157
+ self.table, self.lookup_type = table, lookup_type
158
+ self.lookupflag = 0
159
+ self.markFilterSet = None
160
+ self.lookup_index = None # assigned when making final tables
161
+ self.extension = extension
162
+ assert table in ("GPOS", "GSUB")
163
+
164
+ def equals(self, other):
165
+ return (
166
+ isinstance(other, self.__class__)
167
+ and self.table == other.table
168
+ and self.lookupflag == other.lookupflag
169
+ and self.markFilterSet == other.markFilterSet
170
+ and self.extension == other.extension
171
+ )
172
+
173
+ def promote_lookup_type(self, is_named_lookup):
174
+ return [self]
175
+
176
+ def inferGlyphClasses(self):
177
+ """Infers glyph glasses for the GDEF table, such as {"cedilla":3}."""
178
+ return {}
179
+
180
+ def getAlternateGlyphs(self):
181
+ """Helper for building 'aalt' features."""
182
+ return {}
183
+
184
+ def buildLookup_(self, subtables):
185
+ return buildLookup(
186
+ subtables,
187
+ self.lookupflag,
188
+ self.markFilterSet,
189
+ self.table,
190
+ self.extension,
191
+ )
192
+
193
+ def buildMarkClasses_(self, marks):
194
+ """{"cedilla": ("BOTTOM", ast.Anchor), ...} --> {"BOTTOM":0, "TOP":1}
195
+
196
+ Helper for MarkBasePostBuilder, MarkLigPosBuilder, and
197
+ MarkMarkPosBuilder. Seems to return the same numeric IDs
198
+ for mark classes as the AFDKO makeotf tool.
199
+ """
200
+ ids = {}
201
+ for mark in sorted(marks.keys(), key=self.font.getGlyphID):
202
+ markClassName, _markAnchor = marks[mark]
203
+ if markClassName not in ids:
204
+ ids[markClassName] = len(ids)
205
+ return ids
206
+
207
+ def setBacktrackCoverage_(self, prefix, subtable):
208
+ subtable.BacktrackGlyphCount = len(prefix)
209
+ subtable.BacktrackCoverage = []
210
+ for p in reversed(prefix):
211
+ coverage = buildCoverage(p, self.glyphMap)
212
+ subtable.BacktrackCoverage.append(coverage)
213
+
214
+ def setLookAheadCoverage_(self, suffix, subtable):
215
+ subtable.LookAheadGlyphCount = len(suffix)
216
+ subtable.LookAheadCoverage = []
217
+ for s in suffix:
218
+ coverage = buildCoverage(s, self.glyphMap)
219
+ subtable.LookAheadCoverage.append(coverage)
220
+
221
+ def setInputCoverage_(self, glyphs, subtable):
222
+ subtable.InputGlyphCount = len(glyphs)
223
+ subtable.InputCoverage = []
224
+ for g in glyphs:
225
+ coverage = buildCoverage(g, self.glyphMap)
226
+ subtable.InputCoverage.append(coverage)
227
+
228
+ def setCoverage_(self, glyphs, subtable):
229
+ subtable.GlyphCount = len(glyphs)
230
+ subtable.Coverage = []
231
+ for g in glyphs:
232
+ coverage = buildCoverage(g, self.glyphMap)
233
+ subtable.Coverage.append(coverage)
234
+
235
+ def build_subst_subtables(self, mapping, klass):
236
+ substitutions = [{}]
237
+ for key in mapping:
238
+ if key[0] == self.SUBTABLE_BREAK_:
239
+ substitutions.append({})
240
+ else:
241
+ substitutions[-1][key] = mapping[key]
242
+ subtables = [klass(s) for s in substitutions]
243
+ return subtables
244
+
245
+ def add_subtable_break(self, location):
246
+ """Add an explicit subtable break.
247
+
248
+ Args:
249
+ location: A string or tuple representing the location in the
250
+ original source which produced this break, or ``None`` if
251
+ no location is provided.
252
+ """
253
+ log.warning(
254
+ OpenTypeLibError(
255
+ 'unsupported "subtable" statement for lookup type', location
256
+ )
257
+ )
258
+
259
+ def can_add_mapping(self, _mapping) -> bool:
260
+ # used by AnySubstBuilder, below
261
+ return True
262
+
263
+
264
+ class AlternateSubstBuilder(LookupBuilder):
265
+ """Builds an Alternate Substitution (GSUB3) lookup.
266
+
267
+ Users are expected to manually add alternate glyph substitutions to
268
+ the ``alternates`` attribute after the object has been initialized,
269
+ e.g.::
270
+
271
+ builder.alternates["A"] = ["A.alt1", "A.alt2"]
272
+
273
+ Attributes:
274
+ font (``fontTools.TTLib.TTFont``): A font object.
275
+ location: A string or tuple representing the location in the original
276
+ source which produced this lookup.
277
+ alternates: An ordered dictionary of alternates, mapping glyph names
278
+ to a list of names of alternates.
279
+ lookupflag (int): The lookup's flag
280
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
281
+ an integer representing the filtering set to be used for this
282
+ lookup. If a mark filtering set is provided,
283
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
284
+ flags.
285
+ """
286
+
287
+ def __init__(self, font, location):
288
+ LookupBuilder.__init__(self, font, location, "GSUB", 3)
289
+ self.alternates = OrderedDict()
290
+
291
+ def equals(self, other):
292
+ return LookupBuilder.equals(self, other) and self.alternates == other.alternates
293
+
294
+ def build(self):
295
+ """Build the lookup.
296
+
297
+ Returns:
298
+ An ``otTables.Lookup`` object representing the alternate
299
+ substitution lookup.
300
+ """
301
+ subtables = self.build_subst_subtables(
302
+ self.alternates, buildAlternateSubstSubtable
303
+ )
304
+ return self.buildLookup_(subtables)
305
+
306
+ def getAlternateGlyphs(self):
307
+ return self.alternates
308
+
309
+ def add_subtable_break(self, location):
310
+ self.alternates[(self.SUBTABLE_BREAK_, location)] = self.SUBTABLE_BREAK_
311
+
312
+
313
+ class ChainContextualRule(
314
+ namedtuple("ChainContextualRule", ["prefix", "glyphs", "suffix", "lookups"])
315
+ ):
316
+ @property
317
+ def is_subtable_break(self):
318
+ return self.prefix == LookupBuilder.SUBTABLE_BREAK_
319
+
320
+
321
+ class ChainContextualRuleset:
322
+ def __init__(self):
323
+ self.rules = []
324
+
325
+ def addRule(self, rule):
326
+ self.rules.append(rule)
327
+
328
+ @property
329
+ def hasPrefixOrSuffix(self):
330
+ # Do we have any prefixes/suffixes? If this is False for all
331
+ # rulesets, we can express the whole lookup as GPOS5/GSUB7.
332
+ for rule in self.rules:
333
+ if len(rule.prefix) > 0 or len(rule.suffix) > 0:
334
+ return True
335
+ return False
336
+
337
+ @property
338
+ def hasAnyGlyphClasses(self):
339
+ # Do we use glyph classes anywhere in the rules? If this is False
340
+ # we can express this subtable as a Format 1.
341
+ for rule in self.rules:
342
+ for coverage in (rule.prefix, rule.glyphs, rule.suffix):
343
+ if any(len(x) > 1 for x in coverage):
344
+ return True
345
+ return False
346
+
347
+ def format2ClassDefs(self):
348
+ PREFIX, GLYPHS, SUFFIX = 0, 1, 2
349
+ classDefBuilders = []
350
+ for ix in [PREFIX, GLYPHS, SUFFIX]:
351
+ context = []
352
+ for r in self.rules:
353
+ context.append(r[ix])
354
+ classes = self._classBuilderForContext(context)
355
+ if not classes:
356
+ return None
357
+ classDefBuilders.append(classes)
358
+ return classDefBuilders
359
+
360
+ def _classBuilderForContext(self, context):
361
+ classdefbuilder = ClassDefBuilder(useClass0=False)
362
+ for position in context:
363
+ for glyphset in position:
364
+ glyphs = set(glyphset)
365
+ if not classdefbuilder.canAdd(glyphs):
366
+ return None
367
+ classdefbuilder.add(glyphs)
368
+ return classdefbuilder
369
+
370
+
371
+ class ChainContextualBuilder(LookupBuilder):
372
+ def equals(self, other):
373
+ return LookupBuilder.equals(self, other) and self.rules == other.rules
374
+
375
+ def rulesets(self):
376
+ # Return a list of ChainContextRuleset objects, taking explicit
377
+ # subtable breaks into account
378
+ ruleset = [ChainContextualRuleset()]
379
+ for rule in self.rules:
380
+ if rule.is_subtable_break:
381
+ ruleset.append(ChainContextualRuleset())
382
+ continue
383
+ ruleset[-1].addRule(rule)
384
+ # Squish any empty subtables
385
+ return [x for x in ruleset if len(x.rules) > 0]
386
+
387
+ def getCompiledSize_(self, subtables):
388
+ if not subtables:
389
+ return 0
390
+ # We need to make a copy here because compiling
391
+ # modifies the subtable (finalizing formats etc.)
392
+ table = self.buildLookup_(copy.deepcopy(subtables))
393
+ w = OTTableWriter()
394
+ table.compile(w, self.font)
395
+ size = len(w.getAllData())
396
+ return size
397
+
398
+ def build(self):
399
+ """Build the lookup.
400
+
401
+ Returns:
402
+ An ``otTables.Lookup`` object representing the chained
403
+ contextual positioning lookup.
404
+ """
405
+ subtables = []
406
+
407
+ rulesets = self.rulesets()
408
+ chaining = any(ruleset.hasPrefixOrSuffix for ruleset in rulesets)
409
+
410
+ # https://github.com/fonttools/fonttools/issues/2539
411
+ #
412
+ # Unfortunately, as of 2022-03-07, Apple's CoreText renderer does not
413
+ # correctly process GPOS7 lookups, so for now we force contextual
414
+ # positioning lookups to be chaining (GPOS8).
415
+ #
416
+ # This seems to be fixed as of macOS 13.2, but we keep disabling this
417
+ # for now until we are no longer concerned about old macOS versions.
418
+ # But we allow people to opt-out of this with the config key below.
419
+ write_gpos7 = self.font.cfg.get("fontTools.otlLib.builder:WRITE_GPOS7")
420
+ # horrible separation of concerns breach
421
+ if not write_gpos7 and self.subtable_type == "Pos":
422
+ chaining = True
423
+
424
+ for ruleset in rulesets:
425
+ # Determine format strategy. We try to build formats 1, 2 and 3
426
+ # subtables and then work out which is best. candidates list holds
427
+ # the subtables in each format for this ruleset (including a dummy
428
+ # "format 0" to make the addressing match the format numbers).
429
+
430
+ # We can always build a format 3 lookup by accumulating each of
431
+ # the rules into a list, so start with that.
432
+ candidates = [None, None, None, []]
433
+ for rule in ruleset.rules:
434
+ candidates[3].append(self.buildFormat3Subtable(rule, chaining))
435
+
436
+ # Can we express the whole ruleset as a format 2 subtable?
437
+ classdefs = ruleset.format2ClassDefs()
438
+ if classdefs:
439
+ candidates[2] = [
440
+ self.buildFormat2Subtable(ruleset, classdefs, chaining)
441
+ ]
442
+
443
+ if not ruleset.hasAnyGlyphClasses:
444
+ candidates[1] = [self.buildFormat1Subtable(ruleset, chaining)]
445
+
446
+ candidates_by_size = []
447
+ for i in [1, 2, 3]:
448
+ if candidates[i]:
449
+ try:
450
+ size = self.getCompiledSize_(candidates[i])
451
+ except OTLOffsetOverflowError as e:
452
+ log.warning(
453
+ "Contextual format %i at %s overflowed (%s)"
454
+ % (i, str(self.location), e)
455
+ )
456
+ else:
457
+ candidates_by_size.append((size, candidates[i]))
458
+
459
+ if not candidates_by_size:
460
+ raise OpenTypeLibError("All candidates overflowed", self.location)
461
+
462
+ _min_size, winner = min(candidates_by_size, key=lambda x: x[0])
463
+ subtables.extend(winner)
464
+
465
+ # If we are not chaining, lookup type will be automatically fixed by
466
+ # buildLookup_
467
+ return self.buildLookup_(subtables)
468
+
469
+ def buildFormat1Subtable(self, ruleset, chaining=True):
470
+ st = self.newSubtable_(chaining=chaining)
471
+ st.Format = 1
472
+ st.populateDefaults()
473
+ coverage = set()
474
+ rulesetsByFirstGlyph = {}
475
+ ruleAttr = self.ruleAttr_(format=1, chaining=chaining)
476
+
477
+ for rule in ruleset.rules:
478
+ ruleAsSubtable = self.newRule_(format=1, chaining=chaining)
479
+
480
+ if chaining:
481
+ ruleAsSubtable.BacktrackGlyphCount = len(rule.prefix)
482
+ ruleAsSubtable.LookAheadGlyphCount = len(rule.suffix)
483
+ ruleAsSubtable.Backtrack = [list(x)[0] for x in reversed(rule.prefix)]
484
+ ruleAsSubtable.LookAhead = [list(x)[0] for x in rule.suffix]
485
+
486
+ ruleAsSubtable.InputGlyphCount = len(rule.glyphs)
487
+ else:
488
+ ruleAsSubtable.GlyphCount = len(rule.glyphs)
489
+
490
+ ruleAsSubtable.Input = [list(x)[0] for x in rule.glyphs[1:]]
491
+
492
+ self.buildLookupList(rule, ruleAsSubtable)
493
+
494
+ firstGlyph = list(rule.glyphs[0])[0]
495
+ if firstGlyph not in rulesetsByFirstGlyph:
496
+ coverage.add(firstGlyph)
497
+ rulesetsByFirstGlyph[firstGlyph] = []
498
+ rulesetsByFirstGlyph[firstGlyph].append(ruleAsSubtable)
499
+
500
+ st.Coverage = buildCoverage(coverage, self.glyphMap)
501
+ ruleSets = []
502
+ for g in st.Coverage.glyphs:
503
+ ruleSet = self.newRuleSet_(format=1, chaining=chaining)
504
+ setattr(ruleSet, ruleAttr, rulesetsByFirstGlyph[g])
505
+ setattr(ruleSet, f"{ruleAttr}Count", len(rulesetsByFirstGlyph[g]))
506
+ ruleSets.append(ruleSet)
507
+
508
+ setattr(st, self.ruleSetAttr_(format=1, chaining=chaining), ruleSets)
509
+ setattr(
510
+ st, self.ruleSetAttr_(format=1, chaining=chaining) + "Count", len(ruleSets)
511
+ )
512
+
513
+ return st
514
+
515
+ def buildFormat2Subtable(self, ruleset, classdefs, chaining=True):
516
+ st = self.newSubtable_(chaining=chaining)
517
+ st.Format = 2
518
+ st.populateDefaults()
519
+
520
+ if chaining:
521
+ (
522
+ st.BacktrackClassDef,
523
+ st.InputClassDef,
524
+ st.LookAheadClassDef,
525
+ ) = [c.build() for c in classdefs]
526
+ else:
527
+ st.ClassDef = classdefs[1].build()
528
+
529
+ inClasses = classdefs[1].classes()
530
+
531
+ classSets = []
532
+ for _ in inClasses:
533
+ classSet = self.newRuleSet_(format=2, chaining=chaining)
534
+ classSets.append(classSet)
535
+
536
+ coverage = set()
537
+ classRuleAttr = self.ruleAttr_(format=2, chaining=chaining)
538
+
539
+ for rule in ruleset.rules:
540
+ ruleAsSubtable = self.newRule_(format=2, chaining=chaining)
541
+ if chaining:
542
+ ruleAsSubtable.BacktrackGlyphCount = len(rule.prefix)
543
+ ruleAsSubtable.LookAheadGlyphCount = len(rule.suffix)
544
+ # The glyphs in the rule may be list, tuple, odict_keys...
545
+ # Order is not important anyway because they are guaranteed
546
+ # to be members of the same class.
547
+ ruleAsSubtable.Backtrack = [
548
+ st.BacktrackClassDef.classDefs[list(x)[0]]
549
+ for x in reversed(rule.prefix)
550
+ ]
551
+ ruleAsSubtable.LookAhead = [
552
+ st.LookAheadClassDef.classDefs[list(x)[0]] for x in rule.suffix
553
+ ]
554
+
555
+ ruleAsSubtable.InputGlyphCount = len(rule.glyphs)
556
+ ruleAsSubtable.Input = [
557
+ st.InputClassDef.classDefs[list(x)[0]] for x in rule.glyphs[1:]
558
+ ]
559
+ setForThisRule = classSets[
560
+ st.InputClassDef.classDefs[list(rule.glyphs[0])[0]]
561
+ ]
562
+ else:
563
+ ruleAsSubtable.GlyphCount = len(rule.glyphs)
564
+ ruleAsSubtable.Class = [ # The spec calls this InputSequence
565
+ st.ClassDef.classDefs[list(x)[0]] for x in rule.glyphs[1:]
566
+ ]
567
+ setForThisRule = classSets[
568
+ st.ClassDef.classDefs[list(rule.glyphs[0])[0]]
569
+ ]
570
+
571
+ self.buildLookupList(rule, ruleAsSubtable)
572
+ coverage |= set(rule.glyphs[0])
573
+
574
+ getattr(setForThisRule, classRuleAttr).append(ruleAsSubtable)
575
+ setattr(
576
+ setForThisRule,
577
+ f"{classRuleAttr}Count",
578
+ getattr(setForThisRule, f"{classRuleAttr}Count") + 1,
579
+ )
580
+ for i, classSet in enumerate(classSets):
581
+ if not getattr(classSet, classRuleAttr):
582
+ # class sets can be null so replace nop sets with None
583
+ classSets[i] = None
584
+ setattr(st, self.ruleSetAttr_(format=2, chaining=chaining), classSets)
585
+ setattr(
586
+ st, self.ruleSetAttr_(format=2, chaining=chaining) + "Count", len(classSets)
587
+ )
588
+ st.Coverage = buildCoverage(coverage, self.glyphMap)
589
+ return st
590
+
591
+ def buildFormat3Subtable(self, rule, chaining=True):
592
+ st = self.newSubtable_(chaining=chaining)
593
+ st.Format = 3
594
+ if chaining:
595
+ self.setBacktrackCoverage_(rule.prefix, st)
596
+ self.setLookAheadCoverage_(rule.suffix, st)
597
+ self.setInputCoverage_(rule.glyphs, st)
598
+ else:
599
+ self.setCoverage_(rule.glyphs, st)
600
+ self.buildLookupList(rule, st)
601
+ return st
602
+
603
+ def buildLookupList(self, rule, st):
604
+ for sequenceIndex, lookupList in enumerate(rule.lookups):
605
+ if lookupList is not None:
606
+ if not isinstance(lookupList, list):
607
+ # Can happen with synthesised lookups
608
+ lookupList = [lookupList]
609
+ for l in lookupList:
610
+ if l.lookup_index is None:
611
+ if isinstance(self, ChainContextPosBuilder):
612
+ other = "substitution"
613
+ else:
614
+ other = "positioning"
615
+ raise OpenTypeLibError(
616
+ "Missing index of the specified "
617
+ f"lookup, might be a {other} lookup",
618
+ self.location,
619
+ )
620
+ rec = self.newLookupRecord_(st)
621
+ rec.SequenceIndex = sequenceIndex
622
+ rec.LookupListIndex = l.lookup_index
623
+
624
+ def add_subtable_break(self, location):
625
+ self.rules.append(
626
+ ChainContextualRule(
627
+ self.SUBTABLE_BREAK_,
628
+ self.SUBTABLE_BREAK_,
629
+ self.SUBTABLE_BREAK_,
630
+ [self.SUBTABLE_BREAK_],
631
+ )
632
+ )
633
+
634
+ def newSubtable_(self, chaining=True):
635
+ subtablename = f"Context{self.subtable_type}"
636
+ if chaining:
637
+ subtablename = "Chain" + subtablename
638
+ st = getattr(ot, subtablename)() # ot.ChainContextPos()/ot.ChainSubst()/etc.
639
+ setattr(st, f"{self.subtable_type}Count", 0)
640
+ setattr(st, f"{self.subtable_type}LookupRecord", [])
641
+ return st
642
+
643
+ # Format 1 and format 2 GSUB5/GSUB6/GPOS7/GPOS8 rulesets and rules form a family:
644
+ #
645
+ # format 1 ruleset format 1 rule format 2 ruleset format 2 rule
646
+ # GSUB5 SubRuleSet SubRule SubClassSet SubClassRule
647
+ # GSUB6 ChainSubRuleSet ChainSubRule ChainSubClassSet ChainSubClassRule
648
+ # GPOS7 PosRuleSet PosRule PosClassSet PosClassRule
649
+ # GPOS8 ChainPosRuleSet ChainPosRule ChainPosClassSet ChainPosClassRule
650
+ #
651
+ # The following functions generate the attribute names and subtables according
652
+ # to this naming convention.
653
+ def ruleSetAttr_(self, format=1, chaining=True):
654
+ if format == 1:
655
+ formatType = "Rule"
656
+ elif format == 2:
657
+ formatType = "Class"
658
+ else:
659
+ raise AssertionError(formatType)
660
+ subtablename = f"{self.subtable_type[0:3]}{formatType}Set" # Sub, not Subst.
661
+ if chaining:
662
+ subtablename = "Chain" + subtablename
663
+ return subtablename
664
+
665
+ def ruleAttr_(self, format=1, chaining=True):
666
+ if format == 1:
667
+ formatType = ""
668
+ elif format == 2:
669
+ formatType = "Class"
670
+ else:
671
+ raise AssertionError(formatType)
672
+ subtablename = f"{self.subtable_type[0:3]}{formatType}Rule" # Sub, not Subst.
673
+ if chaining:
674
+ subtablename = "Chain" + subtablename
675
+ return subtablename
676
+
677
+ def newRuleSet_(self, format=1, chaining=True):
678
+ st = getattr(
679
+ ot, self.ruleSetAttr_(format, chaining)
680
+ )() # ot.ChainPosRuleSet()/ot.SubRuleSet()/etc.
681
+ st.populateDefaults()
682
+ return st
683
+
684
+ def newRule_(self, format=1, chaining=True):
685
+ st = getattr(
686
+ ot, self.ruleAttr_(format, chaining)
687
+ )() # ot.ChainPosClassRule()/ot.SubClassRule()/etc.
688
+ st.populateDefaults()
689
+ return st
690
+
691
+ def attachSubtableWithCount_(
692
+ self, st, subtable_name, count_name, existing=None, index=None, chaining=False
693
+ ):
694
+ if chaining:
695
+ subtable_name = "Chain" + subtable_name
696
+ count_name = "Chain" + count_name
697
+
698
+ if not hasattr(st, count_name):
699
+ setattr(st, count_name, 0)
700
+ setattr(st, subtable_name, [])
701
+
702
+ if existing:
703
+ new_subtable = existing
704
+ else:
705
+ # Create a new, empty subtable from otTables
706
+ new_subtable = getattr(ot, subtable_name)()
707
+
708
+ setattr(st, count_name, getattr(st, count_name) + 1)
709
+
710
+ if index:
711
+ getattr(st, subtable_name).insert(index, new_subtable)
712
+ else:
713
+ getattr(st, subtable_name).append(new_subtable)
714
+
715
+ return new_subtable
716
+
717
+ def newLookupRecord_(self, st):
718
+ return self.attachSubtableWithCount_(
719
+ st,
720
+ f"{self.subtable_type}LookupRecord",
721
+ f"{self.subtable_type}Count",
722
+ chaining=False,
723
+ ) # Oddly, it isn't ChainSubstLookupRecord
724
+
725
+
726
+ class ChainContextPosBuilder(ChainContextualBuilder):
727
+ """Builds a Chained Contextual Positioning (GPOS8) lookup.
728
+
729
+ Users are expected to manually add rules to the ``rules`` attribute after
730
+ the object has been initialized, e.g.::
731
+
732
+ # pos [A B] [C D] x' lookup lu1 y' z' lookup lu2 E;
733
+
734
+ prefix = [ ["A", "B"], ["C", "D"] ]
735
+ suffix = [ ["E"] ]
736
+ glyphs = [ ["x"], ["y"], ["z"] ]
737
+ lookups = [ [lu1], None, [lu2] ]
738
+ builder.rules.append( (prefix, glyphs, suffix, lookups) )
739
+
740
+ Attributes:
741
+ font (``fontTools.TTLib.TTFont``): A font object.
742
+ location: A string or tuple representing the location in the original
743
+ source which produced this lookup.
744
+ rules: A list of tuples representing the rules in this lookup.
745
+ lookupflag (int): The lookup's flag
746
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
747
+ an integer representing the filtering set to be used for this
748
+ lookup. If a mark filtering set is provided,
749
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
750
+ flags.
751
+ """
752
+
753
+ def __init__(self, font, location):
754
+ LookupBuilder.__init__(self, font, location, "GPOS", 8)
755
+ self.rules = []
756
+ self.subtable_type = "Pos"
757
+
758
+ def find_chainable_single_pos(self, lookups, glyphs, value):
759
+ """Helper for add_single_pos_chained_()"""
760
+ res = None
761
+ for lookup in lookups[::-1]:
762
+ if lookup == self.SUBTABLE_BREAK_:
763
+ return res
764
+ if isinstance(lookup, SinglePosBuilder) and all(
765
+ lookup.can_add(glyph, value) for glyph in glyphs
766
+ ):
767
+ res = lookup
768
+ return res
769
+
770
+
771
+ class ChainContextSubstBuilder(ChainContextualBuilder):
772
+ """Builds a Chained Contextual Substitution (GSUB6) lookup.
773
+
774
+ Users are expected to manually add rules to the ``rules`` attribute after
775
+ the object has been initialized, e.g.::
776
+
777
+ # sub [A B] [C D] x' lookup lu1 y' z' lookup lu2 E;
778
+
779
+ prefix = [ ["A", "B"], ["C", "D"] ]
780
+ suffix = [ ["E"] ]
781
+ glyphs = [ ["x"], ["y"], ["z"] ]
782
+ lookups = [ [lu1], None, [lu2] ]
783
+ builder.rules.append( (prefix, glyphs, suffix, lookups) )
784
+
785
+ Attributes:
786
+ font (``fontTools.TTLib.TTFont``): A font object.
787
+ location: A string or tuple representing the location in the original
788
+ source which produced this lookup.
789
+ rules: A list of tuples representing the rules in this lookup.
790
+ lookupflag (int): The lookup's flag
791
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
792
+ an integer representing the filtering set to be used for this
793
+ lookup. If a mark filtering set is provided,
794
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
795
+ flags.
796
+ """
797
+
798
+ def __init__(self, font, location):
799
+ LookupBuilder.__init__(self, font, location, "GSUB", 6)
800
+ self.rules = [] # (prefix, input, suffix, lookups)
801
+ self.subtable_type = "Subst"
802
+
803
+ def getAlternateGlyphs(self):
804
+ result = {}
805
+ for rule in self.rules:
806
+ if rule.is_subtable_break:
807
+ continue
808
+ for lookups in rule.lookups:
809
+ if not isinstance(lookups, list):
810
+ lookups = [lookups]
811
+ for lookup in lookups:
812
+ if lookup is not None:
813
+ alts = lookup.getAlternateGlyphs()
814
+ for glyph, replacements in alts.items():
815
+ alts_for_glyph = result.setdefault(glyph, [])
816
+ alts_for_glyph.extend(
817
+ g for g in replacements if g not in alts_for_glyph
818
+ )
819
+ return result
820
+
821
+ def find_chainable_subst(self, mapping, builder_class):
822
+ """Helper for add_{single,multi}_subst_chained_()"""
823
+ res = None
824
+ for rule in self.rules[::-1]:
825
+ if rule.is_subtable_break:
826
+ return res
827
+ for sub in rule.lookups:
828
+ if isinstance(sub, builder_class) and not any(
829
+ g in mapping and mapping[g] != sub.mapping[g] for g in sub.mapping
830
+ ):
831
+ res = sub
832
+ return res
833
+
834
+ def find_chainable_ligature_subst(self, glyphs, replacement):
835
+ """Helper for add_ligature_subst_chained_()"""
836
+ res = None
837
+ for rule in self.rules[::-1]:
838
+ if rule.is_subtable_break:
839
+ return res
840
+ for sub in rule.lookups:
841
+ if not isinstance(sub, LigatureSubstBuilder):
842
+ continue
843
+ if all(
844
+ sub.ligatures.get(seq, replacement) == replacement
845
+ for seq in itertools.product(*glyphs)
846
+ ):
847
+ res = sub
848
+ return res
849
+
850
+
851
+ class LigatureSubstBuilder(LookupBuilder):
852
+ """Builds a Ligature Substitution (GSUB4) lookup.
853
+
854
+ Users are expected to manually add ligatures to the ``ligatures``
855
+ attribute after the object has been initialized, e.g.::
856
+
857
+ # sub f i by f_i;
858
+ builder.ligatures[("f","f","i")] = "f_f_i"
859
+
860
+ Attributes:
861
+ font (``fontTools.TTLib.TTFont``): A font object.
862
+ location: A string or tuple representing the location in the original
863
+ source which produced this lookup.
864
+ ligatures: An ordered dictionary mapping a tuple of glyph names to the
865
+ ligature glyphname.
866
+ lookupflag (int): The lookup's flag
867
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
868
+ an integer representing the filtering set to be used for this
869
+ lookup. If a mark filtering set is provided,
870
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
871
+ flags.
872
+ """
873
+
874
+ def __init__(self, font, location):
875
+ LookupBuilder.__init__(self, font, location, "GSUB", 4)
876
+ self.ligatures = OrderedDict() # {('f','f','i'): 'f_f_i'}
877
+
878
+ def equals(self, other):
879
+ return LookupBuilder.equals(self, other) and self.ligatures == other.ligatures
880
+
881
+ def build(self):
882
+ """Build the lookup.
883
+
884
+ Returns:
885
+ An ``otTables.Lookup`` object representing the ligature
886
+ substitution lookup.
887
+ """
888
+ subtables = self.build_subst_subtables(
889
+ self.ligatures, buildLigatureSubstSubtable
890
+ )
891
+ return self.buildLookup_(subtables)
892
+
893
+ def getAlternateGlyphs(self):
894
+ # https://github.com/fonttools/fonttools/issues/3845
895
+ return {
896
+ components[0]: [ligature]
897
+ for components, ligature in self.ligatures.items()
898
+ if len(components) == 1
899
+ }
900
+
901
+ def add_subtable_break(self, location):
902
+ self.ligatures[(self.SUBTABLE_BREAK_, location)] = self.SUBTABLE_BREAK_
903
+
904
+
905
+ class MultipleSubstBuilder(LookupBuilder):
906
+ """Builds a Multiple Substitution (GSUB2) lookup.
907
+
908
+ Users are expected to manually add substitutions to the ``mapping``
909
+ attribute after the object has been initialized, e.g.::
910
+
911
+ # sub uni06C0 by uni06D5.fina hamza.above;
912
+ builder.mapping["uni06C0"] = [ "uni06D5.fina", "hamza.above"]
913
+
914
+ Attributes:
915
+ font (``fontTools.TTLib.TTFont``): A font object.
916
+ location: A string or tuple representing the location in the original
917
+ source which produced this lookup.
918
+ mapping: An ordered dictionary mapping a glyph name to a list of
919
+ substituted glyph names.
920
+ lookupflag (int): The lookup's flag
921
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
922
+ an integer representing the filtering set to be used for this
923
+ lookup. If a mark filtering set is provided,
924
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
925
+ flags.
926
+ """
927
+
928
+ def __init__(self, font, location):
929
+ LookupBuilder.__init__(self, font, location, "GSUB", 2)
930
+ self.mapping = OrderedDict()
931
+
932
+ def equals(self, other):
933
+ return LookupBuilder.equals(self, other) and self.mapping == other.mapping
934
+
935
+ def build(self):
936
+ subtables = self.build_subst_subtables(self.mapping, buildMultipleSubstSubtable)
937
+ return self.buildLookup_(subtables)
938
+
939
+ def getAlternateGlyphs(self):
940
+ # https://github.com/fonttools/fonttools/issues/3845
941
+ return {
942
+ glyph: replacements
943
+ for glyph, replacements in self.mapping.items()
944
+ if len(replacements) == 1
945
+ }
946
+
947
+ def add_subtable_break(self, location):
948
+ self.mapping[(self.SUBTABLE_BREAK_, location)] = self.SUBTABLE_BREAK_
949
+
950
+
951
+ class CursivePosBuilder(LookupBuilder):
952
+ """Builds a Cursive Positioning (GPOS3) lookup.
953
+
954
+ Attributes:
955
+ font (``fontTools.TTLib.TTFont``): A font object.
956
+ location: A string or tuple representing the location in the original
957
+ source which produced this lookup.
958
+ attachments: An ordered dictionary mapping a glyph name to a two-element
959
+ tuple of ``otTables.Anchor`` objects.
960
+ lookupflag (int): The lookup's flag
961
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
962
+ an integer representing the filtering set to be used for this
963
+ lookup. If a mark filtering set is provided,
964
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
965
+ flags.
966
+ """
967
+
968
+ def __init__(self, font, location):
969
+ LookupBuilder.__init__(self, font, location, "GPOS", 3)
970
+ self.attachments = {}
971
+
972
+ def equals(self, other):
973
+ return (
974
+ LookupBuilder.equals(self, other) and self.attachments == other.attachments
975
+ )
976
+
977
+ def add_attachment(self, location, glyphs, entryAnchor, exitAnchor):
978
+ """Adds attachment information to the cursive positioning lookup.
979
+
980
+ Args:
981
+ location: A string or tuple representing the location in the
982
+ original source which produced this lookup. (Unused.)
983
+ glyphs: A list of glyph names sharing these entry and exit
984
+ anchor locations.
985
+ entryAnchor: A ``otTables.Anchor`` object representing the
986
+ entry anchor, or ``None`` if no entry anchor is present.
987
+ exitAnchor: A ``otTables.Anchor`` object representing the
988
+ exit anchor, or ``None`` if no exit anchor is present.
989
+ """
990
+ for glyph in glyphs:
991
+ self.attachments[glyph] = (entryAnchor, exitAnchor)
992
+
993
+ def build(self):
994
+ """Build the lookup.
995
+
996
+ Returns:
997
+ An ``otTables.Lookup`` object representing the cursive
998
+ positioning lookup.
999
+ """
1000
+ attachments = [{}]
1001
+ for key in self.attachments:
1002
+ if key[0] == self.SUBTABLE_BREAK_:
1003
+ attachments.append({})
1004
+ else:
1005
+ attachments[-1][key] = self.attachments[key]
1006
+ subtables = [buildCursivePosSubtable(s, self.glyphMap) for s in attachments]
1007
+ return self.buildLookup_(subtables)
1008
+
1009
+ def add_subtable_break(self, location):
1010
+ self.attachments[(self.SUBTABLE_BREAK_, location)] = (
1011
+ self.SUBTABLE_BREAK_,
1012
+ self.SUBTABLE_BREAK_,
1013
+ )
1014
+
1015
+
1016
+ class MarkBasePosBuilder(LookupBuilder):
1017
+ """Builds a Mark-To-Base Positioning (GPOS4) lookup.
1018
+
1019
+ Users are expected to manually add marks and bases to the ``marks``
1020
+ and ``bases`` attributes after the object has been initialized, e.g.::
1021
+
1022
+ builder.marks["acute"] = (0, a1)
1023
+ builder.marks["grave"] = (0, a1)
1024
+ builder.marks["cedilla"] = (1, a2)
1025
+ builder.bases["a"] = {0: a3, 1: a5}
1026
+ builder.bases["b"] = {0: a4, 1: a5}
1027
+
1028
+ Attributes:
1029
+ font (``fontTools.TTLib.TTFont``): A font object.
1030
+ location: A string or tuple representing the location in the original
1031
+ source which produced this lookup.
1032
+ marks: An dictionary mapping a glyph name to a two-element
1033
+ tuple containing a mark class ID and ``otTables.Anchor`` object.
1034
+ bases: An dictionary mapping a glyph name to a dictionary of
1035
+ mark class IDs and ``otTables.Anchor`` object.
1036
+ lookupflag (int): The lookup's flag
1037
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
1038
+ an integer representing the filtering set to be used for this
1039
+ lookup. If a mark filtering set is provided,
1040
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
1041
+ flags.
1042
+ """
1043
+
1044
+ def __init__(self, font, location):
1045
+ LookupBuilder.__init__(self, font, location, "GPOS", 4)
1046
+ self.marks = {} # glyphName -> (markClassName, anchor)
1047
+ self.bases = {} # glyphName -> {markClassName: anchor}
1048
+ self.subtables_ = []
1049
+
1050
+ def get_subtables_(self):
1051
+ subtables_ = self.subtables_
1052
+ if self.bases or self.marks:
1053
+ subtables_.append((self.marks, self.bases))
1054
+ return subtables_
1055
+
1056
+ def equals(self, other):
1057
+ return (
1058
+ LookupBuilder.equals(self, other)
1059
+ and self.get_subtables_() == other.get_subtables_()
1060
+ )
1061
+
1062
+ def inferGlyphClasses(self):
1063
+ result = {}
1064
+ for marks, bases in self.get_subtables_():
1065
+ result.update({glyph: 1 for glyph in bases})
1066
+ result.update({glyph: 3 for glyph in marks})
1067
+ return result
1068
+
1069
+ def build(self):
1070
+ """Build the lookup.
1071
+
1072
+ Returns:
1073
+ An ``otTables.Lookup`` object representing the mark-to-base
1074
+ positioning lookup.
1075
+ """
1076
+ subtables = []
1077
+ for subtable in self.get_subtables_():
1078
+ markClasses = self.buildMarkClasses_(subtable[0])
1079
+ marks = {}
1080
+ for mark, (mc, anchor) in subtable[0].items():
1081
+ if mc not in markClasses:
1082
+ raise ValueError(
1083
+ "Mark class %s not found for mark glyph %s" % (mc, mark)
1084
+ )
1085
+ marks[mark] = (markClasses[mc], anchor)
1086
+ bases = {}
1087
+ for glyph, anchors in subtable[1].items():
1088
+ bases[glyph] = {}
1089
+ for mc, anchor in anchors.items():
1090
+ if mc not in markClasses:
1091
+ raise ValueError(
1092
+ "Mark class %s not found for base glyph %s" % (mc, glyph)
1093
+ )
1094
+ bases[glyph][markClasses[mc]] = anchor
1095
+ subtables.append(buildMarkBasePosSubtable(marks, bases, self.glyphMap))
1096
+ return self.buildLookup_(subtables)
1097
+
1098
+ def add_subtable_break(self, location):
1099
+ self.subtables_.append((self.marks, self.bases))
1100
+ self.marks = {}
1101
+ self.bases = {}
1102
+
1103
+
1104
+ class MarkLigPosBuilder(LookupBuilder):
1105
+ """Builds a Mark-To-Ligature Positioning (GPOS5) lookup.
1106
+
1107
+ Users are expected to manually add marks and bases to the ``marks``
1108
+ and ``ligatures`` attributes after the object has been initialized, e.g.::
1109
+
1110
+ builder.marks["acute"] = (0, a1)
1111
+ builder.marks["grave"] = (0, a1)
1112
+ builder.marks["cedilla"] = (1, a2)
1113
+ builder.ligatures["f_i"] = [
1114
+ { 0: a3, 1: a5 }, # f
1115
+ { 0: a4, 1: a5 } # i
1116
+ ]
1117
+
1118
+ Attributes:
1119
+ font (``fontTools.TTLib.TTFont``): A font object.
1120
+ location: A string or tuple representing the location in the original
1121
+ source which produced this lookup.
1122
+ marks: An dictionary mapping a glyph name to a two-element
1123
+ tuple containing a mark class ID and ``otTables.Anchor`` object.
1124
+ ligatures: An dictionary mapping a glyph name to an array with one
1125
+ element for each ligature component. Each array element should be
1126
+ a dictionary mapping mark class IDs to ``otTables.Anchor`` objects.
1127
+ lookupflag (int): The lookup's flag
1128
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
1129
+ an integer representing the filtering set to be used for this
1130
+ lookup. If a mark filtering set is provided,
1131
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
1132
+ flags.
1133
+ """
1134
+
1135
+ def __init__(self, font, location):
1136
+ LookupBuilder.__init__(self, font, location, "GPOS", 5)
1137
+ self.marks = {} # glyphName -> (markClassName, anchor)
1138
+ self.ligatures = {} # glyphName -> [{markClassName: anchor}, ...]
1139
+ self.subtables_ = []
1140
+
1141
+ def get_subtables_(self):
1142
+ subtables_ = self.subtables_
1143
+ if self.ligatures or self.marks:
1144
+ subtables_.append((self.marks, self.ligatures))
1145
+ return subtables_
1146
+
1147
+ def equals(self, other):
1148
+ return (
1149
+ LookupBuilder.equals(self, other)
1150
+ and self.get_subtables_() == other.get_subtables_()
1151
+ )
1152
+
1153
+ def inferGlyphClasses(self):
1154
+ result = {}
1155
+ for marks, ligatures in self.get_subtables_():
1156
+ result.update({glyph: 2 for glyph in ligatures})
1157
+ result.update({glyph: 3 for glyph in marks})
1158
+ return result
1159
+
1160
+ def build(self):
1161
+ """Build the lookup.
1162
+
1163
+ Returns:
1164
+ An ``otTables.Lookup`` object representing the mark-to-ligature
1165
+ positioning lookup.
1166
+ """
1167
+ subtables = []
1168
+ for subtable in self.get_subtables_():
1169
+ markClasses = self.buildMarkClasses_(subtable[0])
1170
+ marks = {
1171
+ mark: (markClasses[mc], anchor)
1172
+ for mark, (mc, anchor) in subtable[0].items()
1173
+ }
1174
+ ligs = {}
1175
+ for lig, components in subtable[1].items():
1176
+ ligs[lig] = []
1177
+ for c in components:
1178
+ ligs[lig].append({markClasses[mc]: a for mc, a in c.items()})
1179
+ subtables.append(buildMarkLigPosSubtable(marks, ligs, self.glyphMap))
1180
+ return self.buildLookup_(subtables)
1181
+
1182
+ def add_subtable_break(self, location):
1183
+ self.subtables_.append((self.marks, self.ligatures))
1184
+ self.marks = {}
1185
+ self.ligatures = {}
1186
+
1187
+
1188
+ class MarkMarkPosBuilder(LookupBuilder):
1189
+ """Builds a Mark-To-Mark Positioning (GPOS6) lookup.
1190
+
1191
+ Users are expected to manually add marks and bases to the ``marks``
1192
+ and ``baseMarks`` attributes after the object has been initialized, e.g.::
1193
+
1194
+ builder.marks["acute"] = (0, a1)
1195
+ builder.marks["grave"] = (0, a1)
1196
+ builder.marks["cedilla"] = (1, a2)
1197
+ builder.baseMarks["acute"] = {0: a3}
1198
+
1199
+ Attributes:
1200
+ font (``fontTools.TTLib.TTFont``): A font object.
1201
+ location: A string or tuple representing the location in the original
1202
+ source which produced this lookup.
1203
+ marks: An dictionary mapping a glyph name to a two-element
1204
+ tuple containing a mark class ID and ``otTables.Anchor`` object.
1205
+ baseMarks: An dictionary mapping a glyph name to a dictionary
1206
+ containing one item: a mark class ID and a ``otTables.Anchor`` object.
1207
+ lookupflag (int): The lookup's flag
1208
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
1209
+ an integer representing the filtering set to be used for this
1210
+ lookup. If a mark filtering set is provided,
1211
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
1212
+ flags.
1213
+ """
1214
+
1215
+ def __init__(self, font, location):
1216
+ LookupBuilder.__init__(self, font, location, "GPOS", 6)
1217
+ self.marks = {} # glyphName -> (markClassName, anchor)
1218
+ self.baseMarks = {} # glyphName -> {markClassName: anchor}
1219
+ self.subtables_ = []
1220
+
1221
+ def get_subtables_(self):
1222
+ subtables_ = self.subtables_
1223
+ if self.baseMarks or self.marks:
1224
+ subtables_.append((self.marks, self.baseMarks))
1225
+ return subtables_
1226
+
1227
+ def equals(self, other):
1228
+ return (
1229
+ LookupBuilder.equals(self, other)
1230
+ and self.get_subtables_() == other.get_subtables_()
1231
+ )
1232
+
1233
+ def inferGlyphClasses(self):
1234
+ result = {}
1235
+ for marks, baseMarks in self.get_subtables_():
1236
+ result.update({glyph: 3 for glyph in baseMarks})
1237
+ result.update({glyph: 3 for glyph in marks})
1238
+ return result
1239
+
1240
+ def build(self):
1241
+ """Build the lookup.
1242
+
1243
+ Returns:
1244
+ An ``otTables.Lookup`` object representing the mark-to-mark
1245
+ positioning lookup.
1246
+ """
1247
+ subtables = []
1248
+ for subtable in self.get_subtables_():
1249
+ markClasses = self.buildMarkClasses_(subtable[0])
1250
+ markClassList = sorted(markClasses.keys(), key=markClasses.get)
1251
+ marks = {
1252
+ mark: (markClasses[mc], anchor)
1253
+ for mark, (mc, anchor) in subtable[0].items()
1254
+ }
1255
+
1256
+ st = ot.MarkMarkPos()
1257
+ st.Format = 1
1258
+ st.ClassCount = len(markClasses)
1259
+ st.Mark1Coverage = buildCoverage(marks, self.glyphMap)
1260
+ st.Mark2Coverage = buildCoverage(subtable[1], self.glyphMap)
1261
+ st.Mark1Array = buildMarkArray(marks, self.glyphMap)
1262
+ st.Mark2Array = ot.Mark2Array()
1263
+ st.Mark2Array.Mark2Count = len(st.Mark2Coverage.glyphs)
1264
+ st.Mark2Array.Mark2Record = []
1265
+ for base in st.Mark2Coverage.glyphs:
1266
+ anchors = [subtable[1][base].get(mc) for mc in markClassList]
1267
+ st.Mark2Array.Mark2Record.append(buildMark2Record(anchors))
1268
+ subtables.append(st)
1269
+ return self.buildLookup_(subtables)
1270
+
1271
+ def add_subtable_break(self, location):
1272
+ self.subtables_.append((self.marks, self.baseMarks))
1273
+ self.marks = {}
1274
+ self.baseMarks = {}
1275
+
1276
+
1277
+ class ReverseChainSingleSubstBuilder(LookupBuilder):
1278
+ """Builds a Reverse Chaining Contextual Single Substitution (GSUB8) lookup.
1279
+
1280
+ Users are expected to manually add substitutions to the ``substitutions``
1281
+ attribute after the object has been initialized, e.g.::
1282
+
1283
+ # reversesub [a e n] d' by d.alt;
1284
+ prefix = [ ["a", "e", "n"] ]
1285
+ suffix = []
1286
+ mapping = { "d": "d.alt" }
1287
+ builder.substitutions.append( (prefix, suffix, mapping) )
1288
+
1289
+ Attributes:
1290
+ font (``fontTools.TTLib.TTFont``): A font object.
1291
+ location: A string or tuple representing the location in the original
1292
+ source which produced this lookup.
1293
+ substitutions: A three-element tuple consisting of a prefix sequence,
1294
+ a suffix sequence, and a dictionary of single substitutions.
1295
+ lookupflag (int): The lookup's flag
1296
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
1297
+ an integer representing the filtering set to be used for this
1298
+ lookup. If a mark filtering set is provided,
1299
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
1300
+ flags.
1301
+ """
1302
+
1303
+ def __init__(self, font, location):
1304
+ LookupBuilder.__init__(self, font, location, "GSUB", 8)
1305
+ self.rules = [] # (prefix, suffix, mapping)
1306
+
1307
+ def equals(self, other):
1308
+ return LookupBuilder.equals(self, other) and self.rules == other.rules
1309
+
1310
+ def build(self):
1311
+ """Build the lookup.
1312
+
1313
+ Returns:
1314
+ An ``otTables.Lookup`` object representing the chained
1315
+ contextual substitution lookup.
1316
+ """
1317
+ subtables = []
1318
+ for prefix, suffix, mapping in self.rules:
1319
+ st = ot.ReverseChainSingleSubst()
1320
+ st.Format = 1
1321
+ self.setBacktrackCoverage_(prefix, st)
1322
+ self.setLookAheadCoverage_(suffix, st)
1323
+ st.Coverage = buildCoverage(mapping.keys(), self.glyphMap)
1324
+ st.GlyphCount = len(mapping)
1325
+ st.Substitute = [mapping[g] for g in st.Coverage.glyphs]
1326
+ subtables.append(st)
1327
+ return self.buildLookup_(subtables)
1328
+
1329
+ def add_subtable_break(self, location):
1330
+ # Nothing to do here, each substitution is in its own subtable.
1331
+ pass
1332
+
1333
+
1334
+ class AnySubstBuilder(LookupBuilder):
1335
+ """A temporary builder for Single, Multiple, or Ligature substitution lookup.
1336
+
1337
+ Users are expected to manually add substitutions to the ``mapping``
1338
+ attribute after the object has been initialized, e.g.::
1339
+
1340
+ # sub x by y;
1341
+ builder.mapping[("x",)] = ("y",)
1342
+ # sub a by b c;
1343
+ builder.mapping[("a",)] = ("b", "c")
1344
+ # sub f i by f_i;
1345
+ builder.mapping[("f", "i")] = ("f_i",)
1346
+
1347
+ Then call `promote_lookup_type()` to convert this builder into the
1348
+ appropriate type of substitution lookup builder. This would promote single
1349
+ substitutions to either multiple or ligature substitutions, depending on the
1350
+ rest of the rules in the mapping.
1351
+
1352
+ Attributes:
1353
+ font (``fontTools.TTLib.TTFont``): A font object.
1354
+ location: A string or tuple representing the location in the original
1355
+ source which produced this lookup.
1356
+ mapping: An ordered dictionary mapping a tuple of glyph names to another
1357
+ tuple of glyph names.
1358
+ lookupflag (int): The lookup's flag
1359
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
1360
+ an integer representing the filtering set to be used for this
1361
+ lookup. If a mark filtering set is provided,
1362
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
1363
+ flags.
1364
+ """
1365
+
1366
+ def __init__(self, font, location):
1367
+ LookupBuilder.__init__(self, font, location, "GSUB", 0)
1368
+ self.mapping = OrderedDict()
1369
+
1370
+ def _add_to_single_subst(self, builder, key, value):
1371
+ if key[0] != self.SUBTABLE_BREAK_:
1372
+ key = key[0]
1373
+ builder.mapping[key] = value[0]
1374
+
1375
+ def _add_to_multiple_subst(self, builder, key, value):
1376
+ if key[0] != self.SUBTABLE_BREAK_:
1377
+ key = key[0]
1378
+ builder.mapping[key] = value
1379
+
1380
+ def _add_to_ligature_subst(self, builder, key, value):
1381
+ builder.ligatures[key] = value[0]
1382
+
1383
+ def can_add_mapping(self, mapping) -> bool:
1384
+ if mapping is None:
1385
+ return True
1386
+ # single sub rules can be treated as (degenerate) liga-or-multi sub
1387
+ # rules, but multi and liga sub rules themselves have incompatible
1388
+ # representations. It is uncommon that these are in the same set of
1389
+ # rules, but it happens.
1390
+ is_multi = any(len(v) > 1 for v in mapping.values())
1391
+ is_liga = any(len(k) > 1 for k in mapping.keys())
1392
+
1393
+ has_existing_multi = False
1394
+ has_existing_liga = False
1395
+
1396
+ for k, v in self.mapping.items():
1397
+ if k[0] == self.SUBTABLE_BREAK_:
1398
+ continue
1399
+ if len(k) > 1:
1400
+ has_existing_liga = True
1401
+ if len(v) > 1:
1402
+ has_existing_multi = True
1403
+
1404
+ can_reuse = not (has_existing_multi and is_liga) and not (
1405
+ has_existing_liga and is_multi
1406
+ )
1407
+ return can_reuse
1408
+
1409
+ def promote_lookup_type(self, is_named_lookup):
1410
+ # https://github.com/fonttools/fonttools/issues/612
1411
+ # A multiple substitution may have a single destination, in which case
1412
+ # it will look just like a single substitution. So if there are both
1413
+ # multiple and single substitutions, upgrade all the single ones to
1414
+ # multiple substitutions. Similarly, a ligature substitution may have a
1415
+ # single source glyph, so if there are both ligature and single
1416
+ # substitutions, upgrade all the single ones to ligature substitutions.
1417
+ builder_classes = []
1418
+ for key, value in self.mapping.items():
1419
+ if key[0] == self.SUBTABLE_BREAK_:
1420
+ builder_classes.append(None)
1421
+ elif len(key) == 1 and len(value) == 1:
1422
+ builder_classes.append(SingleSubstBuilder)
1423
+ elif len(key) == 1 and len(value) != 1:
1424
+ builder_classes.append(MultipleSubstBuilder)
1425
+ elif len(key) > 1 and len(value) == 1:
1426
+ builder_classes.append(LigatureSubstBuilder)
1427
+ else:
1428
+ assert False, "Should not happen"
1429
+
1430
+ has_multiple = any(b is MultipleSubstBuilder for b in builder_classes)
1431
+ has_ligature = any(b is LigatureSubstBuilder for b in builder_classes)
1432
+
1433
+ # If we have mixed single and multiple substitutions,
1434
+ # upgrade all single substitutions to multiple substitutions.
1435
+ to_multiple = has_multiple and not has_ligature
1436
+
1437
+ # If we have mixed single and ligature substitutions,
1438
+ # upgrade all single substitutions to ligature substitutions.
1439
+ to_ligature = has_ligature and not has_multiple
1440
+
1441
+ # If we have only single substitutions, we can keep them as is.
1442
+ to_single = not has_ligature and not has_multiple
1443
+
1444
+ ret = []
1445
+ if to_single:
1446
+ builder = SingleSubstBuilder(self.font, self.location)
1447
+ for key, value in self.mapping.items():
1448
+ self._add_to_single_subst(builder, key, value)
1449
+ ret = [builder]
1450
+ elif to_multiple:
1451
+ builder = MultipleSubstBuilder(self.font, self.location)
1452
+ for key, value in self.mapping.items():
1453
+ self._add_to_multiple_subst(builder, key, value)
1454
+ ret = [builder]
1455
+ elif to_ligature:
1456
+ builder = LigatureSubstBuilder(self.font, self.location)
1457
+ for key, value in self.mapping.items():
1458
+ self._add_to_ligature_subst(builder, key, value)
1459
+ ret = [builder]
1460
+ elif is_named_lookup:
1461
+ # This is a named lookup with mixed substitutions that can’t be promoted,
1462
+ # since we can’t split it into multiple lookups, we return None here to
1463
+ # signal that to the caller
1464
+ return None
1465
+ else:
1466
+ curr_builder = None
1467
+ for builder_class, (key, value) in zip(
1468
+ builder_classes, self.mapping.items()
1469
+ ):
1470
+ if curr_builder is None or type(curr_builder) is not builder_class:
1471
+ curr_builder = builder_class(self.font, self.location)
1472
+ ret.append(curr_builder)
1473
+ if builder_class is SingleSubstBuilder:
1474
+ self._add_to_single_subst(curr_builder, key, value)
1475
+ elif builder_class is MultipleSubstBuilder:
1476
+ self._add_to_multiple_subst(curr_builder, key, value)
1477
+ elif builder_class is LigatureSubstBuilder:
1478
+ self._add_to_ligature_subst(curr_builder, key, value)
1479
+ else:
1480
+ assert False, "Should not happen"
1481
+
1482
+ for builder in ret:
1483
+ builder.extension = self.extension
1484
+ builder.lookupflag = self.lookupflag
1485
+ builder.markFilterSet = self.markFilterSet
1486
+ return ret
1487
+
1488
+ def equals(self, other):
1489
+ return LookupBuilder.equals(self, other) and self.mapping == other.mapping
1490
+
1491
+ def build(self):
1492
+ assert False
1493
+
1494
+ def getAlternateGlyphs(self):
1495
+ return {
1496
+ key[0]: value
1497
+ for key, value in self.mapping.items()
1498
+ if len(key) == 1 and len(value) == 1
1499
+ }
1500
+
1501
+ def add_subtable_break(self, location):
1502
+ self.mapping[(self.SUBTABLE_BREAK_, location)] = self.SUBTABLE_BREAK_
1503
+
1504
+
1505
+ class SingleSubstBuilder(LookupBuilder):
1506
+ """Builds a Single Substitution (GSUB1) lookup.
1507
+
1508
+ Users are expected to manually add substitutions to the ``mapping``
1509
+ attribute after the object has been initialized, e.g.::
1510
+
1511
+ # sub x by y;
1512
+ builder.mapping["x"] = "y"
1513
+
1514
+ Attributes:
1515
+ font (``fontTools.TTLib.TTFont``): A font object.
1516
+ location: A string or tuple representing the location in the original
1517
+ source which produced this lookup.
1518
+ mapping: A dictionary mapping a single glyph name to another glyph name.
1519
+ lookupflag (int): The lookup's flag
1520
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
1521
+ an integer representing the filtering set to be used for this
1522
+ lookup. If a mark filtering set is provided,
1523
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
1524
+ flags.
1525
+ """
1526
+
1527
+ def __init__(self, font, location):
1528
+ LookupBuilder.__init__(self, font, location, "GSUB", 1)
1529
+ self.mapping = OrderedDict()
1530
+
1531
+ def equals(self, other):
1532
+ return LookupBuilder.equals(self, other) and self.mapping == other.mapping
1533
+
1534
+ def build(self):
1535
+ """Build the lookup.
1536
+
1537
+ Returns:
1538
+ An ``otTables.Lookup`` object representing the multiple
1539
+ substitution lookup.
1540
+ """
1541
+ subtables = self.build_subst_subtables(self.mapping, buildSingleSubstSubtable)
1542
+ return self.buildLookup_(subtables)
1543
+
1544
+ def getAlternateGlyphs(self):
1545
+ return {glyph: [repl] for glyph, repl in self.mapping.items()}
1546
+
1547
+ def add_subtable_break(self, location):
1548
+ self.mapping[(self.SUBTABLE_BREAK_, location)] = self.SUBTABLE_BREAK_
1549
+
1550
+
1551
+ class ClassPairPosSubtableBuilder(object):
1552
+ """Builds class-based Pair Positioning (GPOS2 format 2) subtables.
1553
+
1554
+ Note that this does *not* build a GPOS2 ``otTables.Lookup`` directly,
1555
+ but builds a list of ``otTables.PairPos`` subtables. It is used by the
1556
+ :class:`PairPosBuilder` below.
1557
+
1558
+ Attributes:
1559
+ builder (PairPosBuilder): A pair positioning lookup builder.
1560
+ """
1561
+
1562
+ def __init__(self, builder):
1563
+ self.builder_ = builder
1564
+ self.classDef1_, self.classDef2_ = None, None
1565
+ self.values_ = {} # (glyphclass1, glyphclass2) --> (value1, value2)
1566
+ self.forceSubtableBreak_ = False
1567
+ self.subtables_ = []
1568
+
1569
+ def addPair(self, gc1, value1, gc2, value2):
1570
+ """Add a pair positioning rule.
1571
+
1572
+ Args:
1573
+ gc1: A set of glyph names for the "left" glyph
1574
+ value1: An ``otTables.ValueRecord`` object for the left glyph's
1575
+ positioning.
1576
+ gc2: A set of glyph names for the "right" glyph
1577
+ value2: An ``otTables.ValueRecord`` object for the right glyph's
1578
+ positioning.
1579
+ """
1580
+ mergeable = (
1581
+ not self.forceSubtableBreak_
1582
+ and self.classDef1_ is not None
1583
+ and self.classDef1_.canAdd(gc1)
1584
+ and self.classDef2_ is not None
1585
+ and self.classDef2_.canAdd(gc2)
1586
+ )
1587
+ if not mergeable:
1588
+ self.flush_()
1589
+ self.classDef1_ = ClassDefBuilder(useClass0=True)
1590
+ self.classDef2_ = ClassDefBuilder(useClass0=False)
1591
+ self.values_ = {}
1592
+ self.classDef1_.add(gc1)
1593
+ self.classDef2_.add(gc2)
1594
+ self.values_[(gc1, gc2)] = (value1, value2)
1595
+
1596
+ def addSubtableBreak(self):
1597
+ """Add an explicit subtable break at this point."""
1598
+ self.forceSubtableBreak_ = True
1599
+
1600
+ def subtables(self):
1601
+ """Return the list of ``otTables.PairPos`` subtables constructed."""
1602
+ self.flush_()
1603
+ return self.subtables_
1604
+
1605
+ def flush_(self):
1606
+ if self.classDef1_ is None or self.classDef2_ is None:
1607
+ return
1608
+ st = buildPairPosClassesSubtable(self.values_, self.builder_.glyphMap)
1609
+ if st.Coverage is None:
1610
+ return
1611
+ self.subtables_.append(st)
1612
+ self.forceSubtableBreak_ = False
1613
+
1614
+
1615
+ class PairPosBuilder(LookupBuilder):
1616
+ """Builds a Pair Positioning (GPOS2) lookup.
1617
+
1618
+ Attributes:
1619
+ font (``fontTools.TTLib.TTFont``): A font object.
1620
+ location: A string or tuple representing the location in the original
1621
+ source which produced this lookup.
1622
+ pairs: An array of class-based pair positioning tuples. Usually
1623
+ manipulated with the :meth:`addClassPair` method below.
1624
+ glyphPairs: A dictionary mapping a tuple of glyph names to a tuple
1625
+ of ``otTables.ValueRecord`` objects. Usually manipulated with the
1626
+ :meth:`addGlyphPair` method below.
1627
+ lookupflag (int): The lookup's flag
1628
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
1629
+ an integer representing the filtering set to be used for this
1630
+ lookup. If a mark filtering set is provided,
1631
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
1632
+ flags.
1633
+ """
1634
+
1635
+ def __init__(self, font, location):
1636
+ LookupBuilder.__init__(self, font, location, "GPOS", 2)
1637
+ self.pairs = [] # [(gc1, value1, gc2, value2)*]
1638
+ self.glyphPairs = {} # (glyph1, glyph2) --> (value1, value2)
1639
+ self.locations = {} # (gc1, gc2) --> (filepath, line, column)
1640
+
1641
+ def addClassPair(self, location, glyphclass1, value1, glyphclass2, value2):
1642
+ """Add a class pair positioning rule to the current lookup.
1643
+
1644
+ Args:
1645
+ location: A string or tuple representing the location in the
1646
+ original source which produced this rule. Unused.
1647
+ glyphclass1: A set of glyph names for the "left" glyph in the pair.
1648
+ value1: A ``otTables.ValueRecord`` for positioning the left glyph.
1649
+ glyphclass2: A set of glyph names for the "right" glyph in the pair.
1650
+ value2: A ``otTables.ValueRecord`` for positioning the right glyph.
1651
+ """
1652
+ self.pairs.append((glyphclass1, value1, glyphclass2, value2))
1653
+
1654
+ def addGlyphPair(self, location, glyph1, value1, glyph2, value2):
1655
+ """Add a glyph pair positioning rule to the current lookup.
1656
+
1657
+ Args:
1658
+ location: A string or tuple representing the location in the
1659
+ original source which produced this rule.
1660
+ glyph1: A glyph name for the "left" glyph in the pair.
1661
+ value1: A ``otTables.ValueRecord`` for positioning the left glyph.
1662
+ glyph2: A glyph name for the "right" glyph in the pair.
1663
+ value2: A ``otTables.ValueRecord`` for positioning the right glyph.
1664
+ """
1665
+ key = (glyph1, glyph2)
1666
+ oldValue = self.glyphPairs.get(key, None)
1667
+ if oldValue is not None:
1668
+ # the Feature File spec explicitly allows specific pairs generated
1669
+ # by an 'enum' rule to be overridden by preceding single pairs
1670
+ otherLoc = self.locations[key]
1671
+ log.debug(
1672
+ "Already defined position for pair %s %s at %s; "
1673
+ "choosing the first value",
1674
+ glyph1,
1675
+ glyph2,
1676
+ otherLoc,
1677
+ )
1678
+ else:
1679
+ self.glyphPairs[key] = (value1, value2)
1680
+ self.locations[key] = location
1681
+
1682
+ def add_subtable_break(self, location):
1683
+ self.pairs.append(
1684
+ (
1685
+ self.SUBTABLE_BREAK_,
1686
+ self.SUBTABLE_BREAK_,
1687
+ self.SUBTABLE_BREAK_,
1688
+ self.SUBTABLE_BREAK_,
1689
+ )
1690
+ )
1691
+
1692
+ def equals(self, other):
1693
+ return (
1694
+ LookupBuilder.equals(self, other)
1695
+ and self.glyphPairs == other.glyphPairs
1696
+ and self.pairs == other.pairs
1697
+ )
1698
+
1699
+ def build(self):
1700
+ """Build the lookup.
1701
+
1702
+ Returns:
1703
+ An ``otTables.Lookup`` object representing the pair positioning
1704
+ lookup.
1705
+ """
1706
+ builders = {}
1707
+ builder = ClassPairPosSubtableBuilder(self)
1708
+ for glyphclass1, value1, glyphclass2, value2 in self.pairs:
1709
+ if glyphclass1 is self.SUBTABLE_BREAK_:
1710
+ builder.addSubtableBreak()
1711
+ continue
1712
+ builder.addPair(glyphclass1, value1, glyphclass2, value2)
1713
+ subtables = []
1714
+ if self.glyphPairs:
1715
+ subtables.extend(buildPairPosGlyphs(self.glyphPairs, self.glyphMap))
1716
+ subtables.extend(builder.subtables())
1717
+ lookup = self.buildLookup_(subtables)
1718
+
1719
+ # Compact the lookup
1720
+ # This is a good moment to do it because the compaction should create
1721
+ # smaller subtables, which may prevent overflows from happening.
1722
+ # Keep reading the value from the ENV until ufo2ft switches to the config system
1723
+ level = self.font.cfg.get(
1724
+ "fontTools.otlLib.optimize.gpos:COMPRESSION_LEVEL",
1725
+ default=_compression_level_from_env(),
1726
+ )
1727
+ if level != 0:
1728
+ log.info("Compacting GPOS...")
1729
+ compact_lookup(self.font, level, lookup)
1730
+
1731
+ return lookup
1732
+
1733
+
1734
+ class SinglePosBuilder(LookupBuilder):
1735
+ """Builds a Single Positioning (GPOS1) lookup.
1736
+
1737
+ Attributes:
1738
+ font (``fontTools.TTLib.TTFont``): A font object.
1739
+ location: A string or tuple representing the location in the original
1740
+ source which produced this lookup.
1741
+ mapping: A dictionary mapping a glyph name to a ``otTables.ValueRecord``
1742
+ objects. Usually manipulated with the :meth:`add_pos` method below.
1743
+ lookupflag (int): The lookup's flag
1744
+ markFilterSet: Either ``None`` if no mark filtering set is used, or
1745
+ an integer representing the filtering set to be used for this
1746
+ lookup. If a mark filtering set is provided,
1747
+ `LOOKUP_FLAG_USE_MARK_FILTERING_SET` will be set on the lookup's
1748
+ flags.
1749
+ """
1750
+
1751
+ def __init__(self, font, location):
1752
+ LookupBuilder.__init__(self, font, location, "GPOS", 1)
1753
+ self.locations = {} # glyph -> (filename, line, column)
1754
+ self.mapping = {} # glyph -> ot.ValueRecord
1755
+
1756
+ def add_pos(self, location, glyph, otValueRecord):
1757
+ """Add a single positioning rule.
1758
+
1759
+ Args:
1760
+ location: A string or tuple representing the location in the
1761
+ original source which produced this lookup.
1762
+ glyph: A glyph name.
1763
+ otValueRection: A ``otTables.ValueRecord`` used to position the
1764
+ glyph.
1765
+ """
1766
+ if otValueRecord is None:
1767
+ otValueRecord = ValueRecord()
1768
+ if not self.can_add(glyph, otValueRecord):
1769
+ otherLoc = self.locations[glyph]
1770
+ raise OpenTypeLibError(
1771
+ 'Already defined different position for glyph "%s" at %s'
1772
+ % (glyph, otherLoc),
1773
+ location,
1774
+ )
1775
+ if otValueRecord:
1776
+ self.mapping[glyph] = otValueRecord
1777
+ self.locations[glyph] = location
1778
+
1779
+ def can_add(self, glyph, value):
1780
+ assert isinstance(value, ValueRecord)
1781
+ curValue = self.mapping.get(glyph)
1782
+ return curValue is None or curValue == value
1783
+
1784
+ def equals(self, other):
1785
+ return LookupBuilder.equals(self, other) and self.mapping == other.mapping
1786
+
1787
+ def build(self):
1788
+ """Build the lookup.
1789
+
1790
+ Returns:
1791
+ An ``otTables.Lookup`` object representing the single positioning
1792
+ lookup.
1793
+ """
1794
+ subtables = buildSinglePos(self.mapping, self.glyphMap)
1795
+ return self.buildLookup_(subtables)
1796
+
1797
+
1798
+ # GSUB
1799
+
1800
+
1801
+ def buildSingleSubstSubtable(mapping):
1802
+ """Builds a single substitution (GSUB1) subtable.
1803
+
1804
+ Note that if you are implementing a layout compiler, you may find it more
1805
+ flexible to use
1806
+ :py:class:`fontTools.otlLib.lookupBuilders.SingleSubstBuilder` instead.
1807
+
1808
+ Args:
1809
+ mapping: A dictionary mapping input glyph names to output glyph names.
1810
+
1811
+ Returns:
1812
+ An ``otTables.SingleSubst`` object, or ``None`` if the mapping dictionary
1813
+ is empty.
1814
+ """
1815
+ if not mapping:
1816
+ return None
1817
+ self = ot.SingleSubst()
1818
+ self.mapping = dict(mapping)
1819
+ return self
1820
+
1821
+
1822
+ def buildMultipleSubstSubtable(mapping):
1823
+ """Builds a multiple substitution (GSUB2) subtable.
1824
+
1825
+ Note that if you are implementing a layout compiler, you may find it more
1826
+ flexible to use
1827
+ :py:class:`fontTools.otlLib.lookupBuilders.MultipleSubstBuilder` instead.
1828
+
1829
+ Example::
1830
+
1831
+ # sub uni06C0 by uni06D5.fina hamza.above
1832
+ # sub uni06C2 by uni06C1.fina hamza.above;
1833
+
1834
+ subtable = buildMultipleSubstSubtable({
1835
+ "uni06C0": [ "uni06D5.fina", "hamza.above"],
1836
+ "uni06C2": [ "uni06D1.fina", "hamza.above"]
1837
+ })
1838
+
1839
+ Args:
1840
+ mapping: A dictionary mapping input glyph names to a list of output
1841
+ glyph names.
1842
+
1843
+ Returns:
1844
+ An ``otTables.MultipleSubst`` object or ``None`` if the mapping dictionary
1845
+ is empty.
1846
+ """
1847
+ if not mapping:
1848
+ return None
1849
+ self = ot.MultipleSubst()
1850
+ self.mapping = dict(mapping)
1851
+ return self
1852
+
1853
+
1854
+ def buildAlternateSubstSubtable(mapping):
1855
+ """Builds an alternate substitution (GSUB3) subtable.
1856
+
1857
+ Note that if you are implementing a layout compiler, you may find it more
1858
+ flexible to use
1859
+ :py:class:`fontTools.otlLib.lookupBuilders.AlternateSubstBuilder` instead.
1860
+
1861
+ Args:
1862
+ mapping: A dictionary mapping input glyph names to a list of output
1863
+ glyph names.
1864
+
1865
+ Returns:
1866
+ An ``otTables.AlternateSubst`` object or ``None`` if the mapping dictionary
1867
+ is empty.
1868
+ """
1869
+ if not mapping:
1870
+ return None
1871
+ self = ot.AlternateSubst()
1872
+ self.alternates = dict(mapping)
1873
+ return self
1874
+
1875
+
1876
+ def buildLigatureSubstSubtable(mapping):
1877
+ """Builds a ligature substitution (GSUB4) subtable.
1878
+
1879
+ Note that if you are implementing a layout compiler, you may find it more
1880
+ flexible to use
1881
+ :py:class:`fontTools.otlLib.lookupBuilders.LigatureSubstBuilder` instead.
1882
+
1883
+ Example::
1884
+
1885
+ # sub f f i by f_f_i;
1886
+ # sub f i by f_i;
1887
+
1888
+ subtable = buildLigatureSubstSubtable({
1889
+ ("f", "f", "i"): "f_f_i",
1890
+ ("f", "i"): "f_i",
1891
+ })
1892
+
1893
+ Args:
1894
+ mapping: A dictionary mapping tuples of glyph names to output
1895
+ glyph names.
1896
+
1897
+ Returns:
1898
+ An ``otTables.LigatureSubst`` object or ``None`` if the mapping dictionary
1899
+ is empty.
1900
+ """
1901
+
1902
+ if not mapping:
1903
+ return None
1904
+ self = ot.LigatureSubst()
1905
+ # The following single line can replace the rest of this function
1906
+ # with fontTools >= 3.1:
1907
+ # self.ligatures = dict(mapping)
1908
+ self.ligatures = {}
1909
+ for components in sorted(mapping.keys(), key=self._getLigatureSortKey):
1910
+ ligature = ot.Ligature()
1911
+ ligature.Component = components[1:]
1912
+ ligature.CompCount = len(ligature.Component) + 1
1913
+ ligature.LigGlyph = mapping[components]
1914
+ firstGlyph = components[0]
1915
+ self.ligatures.setdefault(firstGlyph, []).append(ligature)
1916
+ return self
1917
+
1918
+
1919
+ # GPOS
1920
+
1921
+
1922
+ def buildAnchor(x, y, point=None, deviceX=None, deviceY=None):
1923
+ """Builds an Anchor table.
1924
+
1925
+ This determines the appropriate anchor format based on the passed parameters.
1926
+
1927
+ Args:
1928
+ x (int): X coordinate.
1929
+ y (int): Y coordinate.
1930
+ point (int): Index of glyph contour point, if provided.
1931
+ deviceX (``otTables.Device``): X coordinate device table, if provided.
1932
+ deviceY (``otTables.Device``): Y coordinate device table, if provided.
1933
+
1934
+ Returns:
1935
+ An ``otTables.Anchor`` object.
1936
+ """
1937
+ self = ot.Anchor()
1938
+ self.XCoordinate, self.YCoordinate = x, y
1939
+ self.Format = 1
1940
+ if point is not None:
1941
+ self.AnchorPoint = point
1942
+ self.Format = 2
1943
+ if deviceX is not None or deviceY is not None:
1944
+ assert (
1945
+ self.Format == 1
1946
+ ), "Either point, or both of deviceX/deviceY, must be None."
1947
+ self.XDeviceTable = deviceX
1948
+ self.YDeviceTable = deviceY
1949
+ self.Format = 3
1950
+ return self
1951
+
1952
+
1953
+ def buildBaseArray(bases, numMarkClasses, glyphMap):
1954
+ """Builds a base array record.
1955
+
1956
+ As part of building mark-to-base positioning rules, you will need to define
1957
+ a ``BaseArray`` record, which "defines for each base glyph an array of
1958
+ anchors, one for each mark class." This function builds the base array
1959
+ subtable.
1960
+
1961
+ Example::
1962
+
1963
+ bases = {"a": {0: a3, 1: a5}, "b": {0: a4, 1: a5}}
1964
+ basearray = buildBaseArray(bases, 2, font.getReverseGlyphMap())
1965
+
1966
+ Args:
1967
+ bases (dict): A dictionary mapping anchors to glyphs; the keys being
1968
+ glyph names, and the values being dictionaries mapping mark class ID
1969
+ to the appropriate ``otTables.Anchor`` object used for attaching marks
1970
+ of that class.
1971
+ numMarkClasses (int): The total number of mark classes for which anchors
1972
+ are defined.
1973
+ glyphMap: a glyph name to ID map, typically returned from
1974
+ ``font.getReverseGlyphMap()``.
1975
+
1976
+ Returns:
1977
+ An ``otTables.BaseArray`` object.
1978
+ """
1979
+ self = ot.BaseArray()
1980
+ self.BaseRecord = []
1981
+ for base in sorted(bases, key=glyphMap.__getitem__):
1982
+ b = bases[base]
1983
+ anchors = [b.get(markClass) for markClass in range(numMarkClasses)]
1984
+ self.BaseRecord.append(buildBaseRecord(anchors))
1985
+ self.BaseCount = len(self.BaseRecord)
1986
+ return self
1987
+
1988
+
1989
+ def buildBaseRecord(anchors):
1990
+ # [otTables.Anchor, otTables.Anchor, ...] --> otTables.BaseRecord
1991
+ self = ot.BaseRecord()
1992
+ self.BaseAnchor = anchors
1993
+ return self
1994
+
1995
+
1996
+ def buildComponentRecord(anchors):
1997
+ """Builds a component record.
1998
+
1999
+ As part of building mark-to-ligature positioning rules, you will need to
2000
+ define ``ComponentRecord`` objects, which contain "an array of offsets...
2001
+ to the Anchor tables that define all the attachment points used to attach
2002
+ marks to the component." This function builds the component record.
2003
+
2004
+ Args:
2005
+ anchors: A list of ``otTables.Anchor`` objects or ``None``.
2006
+
2007
+ Returns:
2008
+ A ``otTables.ComponentRecord`` object or ``None`` if no anchors are
2009
+ supplied.
2010
+ """
2011
+ if not anchors:
2012
+ return None
2013
+ self = ot.ComponentRecord()
2014
+ self.LigatureAnchor = anchors
2015
+ return self
2016
+
2017
+
2018
+ def buildCursivePosSubtable(attach, glyphMap):
2019
+ """Builds a cursive positioning (GPOS3) subtable.
2020
+
2021
+ Cursive positioning lookups are made up of a coverage table of glyphs,
2022
+ and a set of ``EntryExitRecord`` records containing the anchors for
2023
+ each glyph. This function builds the cursive positioning subtable.
2024
+
2025
+ Example::
2026
+
2027
+ subtable = buildCursivePosSubtable({
2028
+ "AlifIni": (None, buildAnchor(0, 50)),
2029
+ "BehMed": (buildAnchor(500,250), buildAnchor(0,50)),
2030
+ # ...
2031
+ }, font.getReverseGlyphMap())
2032
+
2033
+ Args:
2034
+ attach (dict): A mapping between glyph names and a tuple of two
2035
+ ``otTables.Anchor`` objects representing entry and exit anchors.
2036
+ glyphMap: a glyph name to ID map, typically returned from
2037
+ ``font.getReverseGlyphMap()``.
2038
+
2039
+ Returns:
2040
+ An ``otTables.CursivePos`` object, or ``None`` if the attachment
2041
+ dictionary was empty.
2042
+ """
2043
+ if not attach:
2044
+ return None
2045
+ self = ot.CursivePos()
2046
+ self.Format = 1
2047
+ self.Coverage = buildCoverage(attach.keys(), glyphMap)
2048
+ self.EntryExitRecord = []
2049
+ for glyph in self.Coverage.glyphs:
2050
+ entryAnchor, exitAnchor = attach[glyph]
2051
+ rec = ot.EntryExitRecord()
2052
+ rec.EntryAnchor = entryAnchor
2053
+ rec.ExitAnchor = exitAnchor
2054
+ self.EntryExitRecord.append(rec)
2055
+ self.EntryExitCount = len(self.EntryExitRecord)
2056
+ return self
2057
+
2058
+
2059
+ def buildDevice(deltas):
2060
+ """Builds a Device record as part of a ValueRecord or Anchor.
2061
+
2062
+ Device tables specify size-specific adjustments to value records
2063
+ and anchors to reflect changes based on the resolution of the output.
2064
+ For example, one could specify that an anchor's Y position should be
2065
+ increased by 1 pixel when displayed at 8 pixels per em. This routine
2066
+ builds device records.
2067
+
2068
+ Args:
2069
+ deltas: A dictionary mapping pixels-per-em sizes to the delta
2070
+ adjustment in pixels when the font is displayed at that size.
2071
+
2072
+ Returns:
2073
+ An ``otTables.Device`` object if any deltas were supplied, or
2074
+ ``None`` otherwise.
2075
+ """
2076
+ if not deltas:
2077
+ return None
2078
+ self = ot.Device()
2079
+ keys = deltas.keys()
2080
+ self.StartSize = startSize = min(keys)
2081
+ self.EndSize = endSize = max(keys)
2082
+ assert 0 <= startSize <= endSize
2083
+ self.DeltaValue = deltaValues = [
2084
+ deltas.get(size, 0) for size in range(startSize, endSize + 1)
2085
+ ]
2086
+ maxDelta = max(deltaValues)
2087
+ minDelta = min(deltaValues)
2088
+ assert minDelta > -129 and maxDelta < 128
2089
+ if minDelta > -3 and maxDelta < 2:
2090
+ self.DeltaFormat = 1
2091
+ elif minDelta > -9 and maxDelta < 8:
2092
+ self.DeltaFormat = 2
2093
+ else:
2094
+ self.DeltaFormat = 3
2095
+ return self
2096
+
2097
+
2098
+ def buildLigatureArray(ligs, numMarkClasses, glyphMap):
2099
+ """Builds a LigatureArray subtable.
2100
+
2101
+ As part of building a mark-to-ligature lookup, you will need to define
2102
+ the set of anchors (for each mark class) on each component of the ligature
2103
+ where marks can be attached. For example, for an Arabic divine name ligature
2104
+ (lam lam heh), you may want to specify mark attachment positioning for
2105
+ superior marks (fatha, etc.) and inferior marks (kasra, etc.) on each glyph
2106
+ of the ligature. This routine builds the ligature array record.
2107
+
2108
+ Example::
2109
+
2110
+ buildLigatureArray({
2111
+ "lam-lam-heh": [
2112
+ { 0: superiorAnchor1, 1: inferiorAnchor1 }, # attach points for lam1
2113
+ { 0: superiorAnchor2, 1: inferiorAnchor2 }, # attach points for lam2
2114
+ { 0: superiorAnchor3, 1: inferiorAnchor3 }, # attach points for heh
2115
+ ]
2116
+ }, 2, font.getReverseGlyphMap())
2117
+
2118
+ Args:
2119
+ ligs (dict): A mapping of ligature names to an array of dictionaries:
2120
+ for each component glyph in the ligature, an dictionary mapping
2121
+ mark class IDs to anchors.
2122
+ numMarkClasses (int): The number of mark classes.
2123
+ glyphMap: a glyph name to ID map, typically returned from
2124
+ ``font.getReverseGlyphMap()``.
2125
+
2126
+ Returns:
2127
+ An ``otTables.LigatureArray`` object if deltas were supplied.
2128
+ """
2129
+ self = ot.LigatureArray()
2130
+ self.LigatureAttach = []
2131
+ for lig in sorted(ligs, key=glyphMap.__getitem__):
2132
+ anchors = []
2133
+ for component in ligs[lig]:
2134
+ anchors.append([component.get(mc) for mc in range(numMarkClasses)])
2135
+ self.LigatureAttach.append(buildLigatureAttach(anchors))
2136
+ self.LigatureCount = len(self.LigatureAttach)
2137
+ return self
2138
+
2139
+
2140
+ def buildLigatureAttach(components):
2141
+ # [[Anchor, Anchor], [Anchor, Anchor, Anchor]] --> LigatureAttach
2142
+ self = ot.LigatureAttach()
2143
+ self.ComponentRecord = [buildComponentRecord(c) for c in components]
2144
+ self.ComponentCount = len(self.ComponentRecord)
2145
+ return self
2146
+
2147
+
2148
+ def buildMarkArray(marks, glyphMap):
2149
+ """Builds a mark array subtable.
2150
+
2151
+ As part of building mark-to-* positioning rules, you will need to define
2152
+ a MarkArray subtable, which "defines the class and the anchor point
2153
+ for a mark glyph." This function builds the mark array subtable.
2154
+
2155
+ Example::
2156
+
2157
+ mark = {
2158
+ "acute": (0, buildAnchor(300,712)),
2159
+ # ...
2160
+ }
2161
+ markarray = buildMarkArray(marks, font.getReverseGlyphMap())
2162
+
2163
+ Args:
2164
+ marks (dict): A dictionary mapping anchors to glyphs; the keys being
2165
+ glyph names, and the values being a tuple of mark class number and
2166
+ an ``otTables.Anchor`` object representing the mark's attachment
2167
+ point.
2168
+ glyphMap: a glyph name to ID map, typically returned from
2169
+ ``font.getReverseGlyphMap()``.
2170
+
2171
+ Returns:
2172
+ An ``otTables.MarkArray`` object.
2173
+ """
2174
+ self = ot.MarkArray()
2175
+ self.MarkRecord = []
2176
+ for mark in sorted(marks.keys(), key=glyphMap.__getitem__):
2177
+ markClass, anchor = marks[mark]
2178
+ markrec = buildMarkRecord(markClass, anchor)
2179
+ self.MarkRecord.append(markrec)
2180
+ self.MarkCount = len(self.MarkRecord)
2181
+ return self
2182
+
2183
+
2184
+ @deprecateFunction(
2185
+ "use buildMarkBasePosSubtable() instead", category=DeprecationWarning
2186
+ )
2187
+ def buildMarkBasePos(marks, bases, glyphMap):
2188
+ """Build a list of MarkBasePos (GPOS4) subtables.
2189
+
2190
+ .. deprecated:: 4.58.0
2191
+ Use :func:`buildMarkBasePosSubtable` instead.
2192
+ """
2193
+ return [buildMarkBasePosSubtable(marks, bases, glyphMap)]
2194
+
2195
+
2196
+ def buildMarkBasePosSubtable(marks, bases, glyphMap):
2197
+ """Build a single MarkBasePos (GPOS4) subtable.
2198
+
2199
+ This builds a mark-to-base lookup subtable containing all of the referenced
2200
+ marks and bases.
2201
+
2202
+ Example::
2203
+
2204
+ # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ...
2205
+
2206
+ marks = {"acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2)}
2207
+ bases = {"a": {0: a3, 1: a5}, "b": {0: a4, 1: a5}}
2208
+ markbaseposes = [buildMarkBasePosSubtable(marks, bases, font.getReverseGlyphMap())]
2209
+
2210
+ Args:
2211
+ marks (dict): A dictionary mapping anchors to glyphs; the keys being
2212
+ glyph names, and the values being a tuple of mark class number and
2213
+ an ``otTables.Anchor`` object representing the mark's attachment
2214
+ point. (See :func:`buildMarkArray`.)
2215
+ bases (dict): A dictionary mapping anchors to glyphs; the keys being
2216
+ glyph names, and the values being dictionaries mapping mark class ID
2217
+ to the appropriate ``otTables.Anchor`` object used for attaching marks
2218
+ of that class. (See :func:`buildBaseArray`.)
2219
+ glyphMap: a glyph name to ID map, typically returned from
2220
+ ``font.getReverseGlyphMap()``.
2221
+
2222
+ Returns:
2223
+ A ``otTables.MarkBasePos`` object.
2224
+ """
2225
+ self = ot.MarkBasePos()
2226
+ self.Format = 1
2227
+ self.MarkCoverage = buildCoverage(marks, glyphMap)
2228
+ self.MarkArray = buildMarkArray(marks, glyphMap)
2229
+ self.ClassCount = max([mc for mc, _ in marks.values()]) + 1
2230
+ self.BaseCoverage = buildCoverage(bases, glyphMap)
2231
+ self.BaseArray = buildBaseArray(bases, self.ClassCount, glyphMap)
2232
+ return self
2233
+
2234
+
2235
+ @deprecateFunction("use buildMarkLigPosSubtable() instead", category=DeprecationWarning)
2236
+ def buildMarkLigPos(marks, ligs, glyphMap):
2237
+ """Build a list of MarkLigPos (GPOS5) subtables.
2238
+
2239
+ .. deprecated:: 4.58.0
2240
+ Use :func:`buildMarkLigPosSubtable` instead.
2241
+ """
2242
+ return [buildMarkLigPosSubtable(marks, ligs, glyphMap)]
2243
+
2244
+
2245
+ def buildMarkLigPosSubtable(marks, ligs, glyphMap):
2246
+ """Build a single MarkLigPos (GPOS5) subtable.
2247
+
2248
+ This builds a mark-to-base lookup subtable containing all of the referenced
2249
+ marks and bases.
2250
+
2251
+ Note that if you are implementing a layout compiler, you may find it more
2252
+ flexible to use
2253
+ :py:class:`fontTools.otlLib.lookupBuilders.MarkLigPosBuilder` instead.
2254
+
2255
+ Example::
2256
+
2257
+ # a1, a2, a3, a4, a5 = buildAnchor(500, 100), ...
2258
+ marks = {
2259
+ "acute": (0, a1),
2260
+ "grave": (0, a1),
2261
+ "cedilla": (1, a2)
2262
+ }
2263
+ ligs = {
2264
+ "f_i": [
2265
+ { 0: a3, 1: a5 }, # f
2266
+ { 0: a4, 1: a5 } # i
2267
+ ],
2268
+ # "c_t": [{...}, {...}]
2269
+ }
2270
+ markligpose = buildMarkLigPosSubtable(marks, ligs,
2271
+ font.getReverseGlyphMap())
2272
+
2273
+ Args:
2274
+ marks (dict): A dictionary mapping anchors to glyphs; the keys being
2275
+ glyph names, and the values being a tuple of mark class number and
2276
+ an ``otTables.Anchor`` object representing the mark's attachment
2277
+ point. (See :func:`buildMarkArray`.)
2278
+ ligs (dict): A mapping of ligature names to an array of dictionaries:
2279
+ for each component glyph in the ligature, an dictionary mapping
2280
+ mark class IDs to anchors. (See :func:`buildLigatureArray`.)
2281
+ glyphMap: a glyph name to ID map, typically returned from
2282
+ ``font.getReverseGlyphMap()``.
2283
+
2284
+ Returns:
2285
+ A ``otTables.MarkLigPos`` object.
2286
+ """
2287
+ self = ot.MarkLigPos()
2288
+ self.Format = 1
2289
+ self.MarkCoverage = buildCoverage(marks, glyphMap)
2290
+ self.MarkArray = buildMarkArray(marks, glyphMap)
2291
+ self.ClassCount = max([mc for mc, _ in marks.values()]) + 1
2292
+ self.LigatureCoverage = buildCoverage(ligs, glyphMap)
2293
+ self.LigatureArray = buildLigatureArray(ligs, self.ClassCount, glyphMap)
2294
+ return self
2295
+
2296
+
2297
+ def buildMarkRecord(classID, anchor):
2298
+ assert isinstance(classID, int)
2299
+ assert isinstance(anchor, ot.Anchor)
2300
+ self = ot.MarkRecord()
2301
+ self.Class = classID
2302
+ self.MarkAnchor = anchor
2303
+ return self
2304
+
2305
+
2306
+ def buildMark2Record(anchors):
2307
+ # [otTables.Anchor, otTables.Anchor, ...] --> otTables.Mark2Record
2308
+ self = ot.Mark2Record()
2309
+ self.Mark2Anchor = anchors
2310
+ return self
2311
+
2312
+
2313
+ def _getValueFormat(f, values, i):
2314
+ # Helper for buildPairPos{Glyphs|Classes}Subtable.
2315
+ if f is not None:
2316
+ return f
2317
+ mask = 0
2318
+ for value in values:
2319
+ if value is not None and value[i] is not None:
2320
+ mask |= value[i].getFormat()
2321
+ return mask
2322
+
2323
+
2324
+ def buildPairPosClassesSubtable(pairs, glyphMap, valueFormat1=None, valueFormat2=None):
2325
+ """Builds a class pair adjustment (GPOS2 format 2) subtable.
2326
+
2327
+ Kerning tables are generally expressed as pair positioning tables using
2328
+ class-based pair adjustments. This routine builds format 2 PairPos
2329
+ subtables.
2330
+
2331
+ Note that if you are implementing a layout compiler, you may find it more
2332
+ flexible to use
2333
+ :py:class:`fontTools.otlLib.lookupBuilders.ClassPairPosSubtableBuilder`
2334
+ instead, as this takes care of ensuring that the supplied pairs can be
2335
+ formed into non-overlapping classes and emitting individual subtables
2336
+ whenever the non-overlapping requirement means that a new subtable is
2337
+ required.
2338
+
2339
+ Example::
2340
+
2341
+ pairs = {}
2342
+
2343
+ pairs[(
2344
+ [ "K", "X" ],
2345
+ [ "W", "V" ]
2346
+ )] = ( buildValue(xAdvance=+5), buildValue() )
2347
+ # pairs[(... , ...)] = (..., ...)
2348
+
2349
+ pairpos = buildPairPosClassesSubtable(pairs, font.getReverseGlyphMap())
2350
+
2351
+ Args:
2352
+ pairs (dict): Pair positioning data; the keys being a two-element
2353
+ tuple of lists of glyphnames, and the values being a two-element
2354
+ tuple of ``otTables.ValueRecord`` objects.
2355
+ glyphMap: a glyph name to ID map, typically returned from
2356
+ ``font.getReverseGlyphMap()``.
2357
+ valueFormat1: Force the "left" value records to the given format.
2358
+ valueFormat2: Force the "right" value records to the given format.
2359
+
2360
+ Returns:
2361
+ A ``otTables.PairPos`` object.
2362
+ """
2363
+ coverage = set()
2364
+ classDef1 = ClassDefBuilder(useClass0=True)
2365
+ classDef2 = ClassDefBuilder(useClass0=False)
2366
+ for gc1, gc2 in sorted(pairs):
2367
+ coverage.update(gc1)
2368
+ classDef1.add(gc1)
2369
+ classDef2.add(gc2)
2370
+ self = ot.PairPos()
2371
+ self.Format = 2
2372
+ valueFormat1 = self.ValueFormat1 = _getValueFormat(valueFormat1, pairs.values(), 0)
2373
+ valueFormat2 = self.ValueFormat2 = _getValueFormat(valueFormat2, pairs.values(), 1)
2374
+ self.Coverage = buildCoverage(coverage, glyphMap)
2375
+ self.ClassDef1 = classDef1.build()
2376
+ self.ClassDef2 = classDef2.build()
2377
+ classes1 = classDef1.classes()
2378
+ classes2 = classDef2.classes()
2379
+ self.Class1Record = []
2380
+ for c1 in classes1:
2381
+ rec1 = ot.Class1Record()
2382
+ rec1.Class2Record = []
2383
+ self.Class1Record.append(rec1)
2384
+ for c2 in classes2:
2385
+ rec2 = ot.Class2Record()
2386
+ val1, val2 = pairs.get((c1, c2), (None, None))
2387
+ rec2.Value1 = (
2388
+ ValueRecord(src=val1, valueFormat=valueFormat1)
2389
+ if valueFormat1
2390
+ else None
2391
+ )
2392
+ rec2.Value2 = (
2393
+ ValueRecord(src=val2, valueFormat=valueFormat2)
2394
+ if valueFormat2
2395
+ else None
2396
+ )
2397
+ rec1.Class2Record.append(rec2)
2398
+ self.Class1Count = len(self.Class1Record)
2399
+ self.Class2Count = len(classes2)
2400
+ return self
2401
+
2402
+
2403
+ def buildPairPosGlyphs(pairs, glyphMap):
2404
+ """Builds a list of glyph-based pair adjustment (GPOS2 format 1) subtables.
2405
+
2406
+ This organises a list of pair positioning adjustments into subtables based
2407
+ on common value record formats.
2408
+
2409
+ Note that if you are implementing a layout compiler, you may find it more
2410
+ flexible to use
2411
+ :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder`
2412
+ instead.
2413
+
2414
+ Example::
2415
+
2416
+ pairs = {
2417
+ ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ),
2418
+ ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ),
2419
+ # ...
2420
+ }
2421
+
2422
+ subtables = buildPairPosGlyphs(pairs, font.getReverseGlyphMap())
2423
+
2424
+ Args:
2425
+ pairs (dict): Pair positioning data; the keys being a two-element
2426
+ tuple of glyphnames, and the values being a two-element
2427
+ tuple of ``otTables.ValueRecord`` objects.
2428
+ glyphMap: a glyph name to ID map, typically returned from
2429
+ ``font.getReverseGlyphMap()``.
2430
+
2431
+ Returns:
2432
+ A list of ``otTables.PairPos`` objects.
2433
+ """
2434
+
2435
+ p = {} # (formatA, formatB) --> {(glyphA, glyphB): (valA, valB)}
2436
+ for (glyphA, glyphB), (valA, valB) in pairs.items():
2437
+ formatA = valA.getFormat() if valA is not None else 0
2438
+ formatB = valB.getFormat() if valB is not None else 0
2439
+ pos = p.setdefault((formatA, formatB), {})
2440
+ pos[(glyphA, glyphB)] = (valA, valB)
2441
+ return [
2442
+ buildPairPosGlyphsSubtable(pos, glyphMap, formatA, formatB)
2443
+ for ((formatA, formatB), pos) in sorted(p.items())
2444
+ ]
2445
+
2446
+
2447
+ def buildPairPosGlyphsSubtable(pairs, glyphMap, valueFormat1=None, valueFormat2=None):
2448
+ """Builds a single glyph-based pair adjustment (GPOS2 format 1) subtable.
2449
+
2450
+ This builds a PairPos subtable from a dictionary of glyph pairs and
2451
+ their positioning adjustments. See also :func:`buildPairPosGlyphs`.
2452
+
2453
+ Note that if you are implementing a layout compiler, you may find it more
2454
+ flexible to use
2455
+ :py:class:`fontTools.otlLib.lookupBuilders.PairPosBuilder` instead.
2456
+
2457
+ Example::
2458
+
2459
+ pairs = {
2460
+ ("K", "W"): ( buildValue(xAdvance=+5), buildValue() ),
2461
+ ("K", "V"): ( buildValue(xAdvance=+5), buildValue() ),
2462
+ # ...
2463
+ }
2464
+
2465
+ pairpos = buildPairPosGlyphsSubtable(pairs, font.getReverseGlyphMap())
2466
+
2467
+ Args:
2468
+ pairs (dict): Pair positioning data; the keys being a two-element
2469
+ tuple of glyphnames, and the values being a two-element
2470
+ tuple of ``otTables.ValueRecord`` objects.
2471
+ glyphMap: a glyph name to ID map, typically returned from
2472
+ ``font.getReverseGlyphMap()``.
2473
+ valueFormat1: Force the "left" value records to the given format.
2474
+ valueFormat2: Force the "right" value records to the given format.
2475
+
2476
+ Returns:
2477
+ A ``otTables.PairPos`` object.
2478
+ """
2479
+ self = ot.PairPos()
2480
+ self.Format = 1
2481
+ valueFormat1 = self.ValueFormat1 = _getValueFormat(valueFormat1, pairs.values(), 0)
2482
+ valueFormat2 = self.ValueFormat2 = _getValueFormat(valueFormat2, pairs.values(), 1)
2483
+ p = {}
2484
+ for (glyphA, glyphB), (valA, valB) in pairs.items():
2485
+ p.setdefault(glyphA, []).append((glyphB, valA, valB))
2486
+ self.Coverage = buildCoverage({g for g, _ in pairs.keys()}, glyphMap)
2487
+ self.PairSet = []
2488
+ for glyph in self.Coverage.glyphs:
2489
+ ps = ot.PairSet()
2490
+ ps.PairValueRecord = []
2491
+ self.PairSet.append(ps)
2492
+ for glyph2, val1, val2 in sorted(p[glyph], key=lambda x: glyphMap[x[0]]):
2493
+ pvr = ot.PairValueRecord()
2494
+ pvr.SecondGlyph = glyph2
2495
+ pvr.Value1 = (
2496
+ ValueRecord(src=val1, valueFormat=valueFormat1)
2497
+ if valueFormat1
2498
+ else None
2499
+ )
2500
+ pvr.Value2 = (
2501
+ ValueRecord(src=val2, valueFormat=valueFormat2)
2502
+ if valueFormat2
2503
+ else None
2504
+ )
2505
+ ps.PairValueRecord.append(pvr)
2506
+ ps.PairValueCount = len(ps.PairValueRecord)
2507
+ self.PairSetCount = len(self.PairSet)
2508
+ return self
2509
+
2510
+
2511
+ def buildSinglePos(mapping, glyphMap):
2512
+ """Builds a list of single adjustment (GPOS1) subtables.
2513
+
2514
+ This builds a list of SinglePos subtables from a dictionary of glyph
2515
+ names and their positioning adjustments. The format of the subtables are
2516
+ determined to optimize the size of the resulting subtables.
2517
+ See also :func:`buildSinglePosSubtable`.
2518
+
2519
+ Note that if you are implementing a layout compiler, you may find it more
2520
+ flexible to use
2521
+ :py:class:`fontTools.otlLib.lookupBuilders.SinglePosBuilder` instead.
2522
+
2523
+ Example::
2524
+
2525
+ mapping = {
2526
+ "V": buildValue({ "xAdvance" : +5 }),
2527
+ # ...
2528
+ }
2529
+
2530
+ subtables = buildSinglePos(pairs, font.getReverseGlyphMap())
2531
+
2532
+ Args:
2533
+ mapping (dict): A mapping between glyphnames and
2534
+ ``otTables.ValueRecord`` objects.
2535
+ glyphMap: a glyph name to ID map, typically returned from
2536
+ ``font.getReverseGlyphMap()``.
2537
+
2538
+ Returns:
2539
+ A list of ``otTables.SinglePos`` objects.
2540
+ """
2541
+ result, handled = [], set()
2542
+ # In SinglePos format 1, the covered glyphs all share the same ValueRecord.
2543
+ # In format 2, each glyph has its own ValueRecord, but these records
2544
+ # all have the same properties (eg., all have an X but no Y placement).
2545
+ coverages, masks, values = {}, {}, {}
2546
+ for glyph, value in mapping.items():
2547
+ key = _getSinglePosValueKey(value)
2548
+ coverages.setdefault(key, []).append(glyph)
2549
+ masks.setdefault(key[0], []).append(key)
2550
+ values[key] = value
2551
+
2552
+ # If a ValueRecord is shared between multiple glyphs, we generate
2553
+ # a SinglePos format 1 subtable; that is the most compact form.
2554
+ for key, glyphs in coverages.items():
2555
+ # 5 ushorts is the length of introducing another sublookup
2556
+ if len(glyphs) * _getSinglePosValueSize(key) > 5:
2557
+ format1Mapping = {g: values[key] for g in glyphs}
2558
+ result.append(buildSinglePosSubtable(format1Mapping, glyphMap))
2559
+ handled.add(key)
2560
+
2561
+ # In the remaining ValueRecords, look for those whose valueFormat
2562
+ # (the set of used properties) is shared between multiple records.
2563
+ # These will get encoded in format 2.
2564
+ for valueFormat, keys in masks.items():
2565
+ f2 = [k for k in keys if k not in handled]
2566
+ if len(f2) > 1:
2567
+ format2Mapping = {}
2568
+ for k in f2:
2569
+ format2Mapping.update((g, values[k]) for g in coverages[k])
2570
+ result.append(buildSinglePosSubtable(format2Mapping, glyphMap))
2571
+ handled.update(f2)
2572
+
2573
+ # The remaining ValueRecords are only used by a few glyphs, normally
2574
+ # one. We encode these in format 1 again.
2575
+ for key, glyphs in coverages.items():
2576
+ if key not in handled:
2577
+ for g in glyphs:
2578
+ st = buildSinglePosSubtable({g: values[key]}, glyphMap)
2579
+ result.append(st)
2580
+
2581
+ # When the OpenType layout engine traverses the subtables, it will
2582
+ # stop after the first matching subtable. Therefore, we sort the
2583
+ # resulting subtables by decreasing coverage size; this increases
2584
+ # the chance that the layout engine can do an early exit. (Of course,
2585
+ # this would only be true if all glyphs were equally frequent, which
2586
+ # is not really the case; but we do not know their distribution).
2587
+ # If two subtables cover the same number of glyphs, we sort them
2588
+ # by glyph ID so that our output is deterministic.
2589
+ result.sort(key=lambda t: _getSinglePosTableKey(t, glyphMap))
2590
+ return result
2591
+
2592
+
2593
+ def buildSinglePosSubtable(values, glyphMap):
2594
+ """Builds a single adjustment (GPOS1) subtable.
2595
+
2596
+ This builds a list of SinglePos subtables from a dictionary of glyph
2597
+ names and their positioning adjustments. The format of the subtable is
2598
+ determined to optimize the size of the output.
2599
+ See also :func:`buildSinglePos`.
2600
+
2601
+ Note that if you are implementing a layout compiler, you may find it more
2602
+ flexible to use
2603
+ :py:class:`fontTools.otlLib.lookupBuilders.SinglePosBuilder` instead.
2604
+
2605
+ Example::
2606
+
2607
+ mapping = {
2608
+ "V": buildValue({ "xAdvance" : +5 }),
2609
+ # ...
2610
+ }
2611
+
2612
+ subtable = buildSinglePos(pairs, font.getReverseGlyphMap())
2613
+
2614
+ Args:
2615
+ mapping (dict): A mapping between glyphnames and
2616
+ ``otTables.ValueRecord`` objects.
2617
+ glyphMap: a glyph name to ID map, typically returned from
2618
+ ``font.getReverseGlyphMap()``.
2619
+
2620
+ Returns:
2621
+ A ``otTables.SinglePos`` object.
2622
+ """
2623
+ self = ot.SinglePos()
2624
+ self.Coverage = buildCoverage(values.keys(), glyphMap)
2625
+ valueFormat = self.ValueFormat = reduce(
2626
+ int.__or__, [v.getFormat() for v in values.values()], 0
2627
+ )
2628
+ valueRecords = [
2629
+ ValueRecord(src=values[g], valueFormat=valueFormat)
2630
+ for g in self.Coverage.glyphs
2631
+ ]
2632
+ if all(v == valueRecords[0] for v in valueRecords):
2633
+ self.Format = 1
2634
+ if self.ValueFormat != 0:
2635
+ self.Value = valueRecords[0]
2636
+ else:
2637
+ self.Value = None
2638
+ else:
2639
+ self.Format = 2
2640
+ self.Value = valueRecords
2641
+ self.ValueCount = len(self.Value)
2642
+ return self
2643
+
2644
+
2645
+ def _getSinglePosTableKey(subtable, glyphMap):
2646
+ assert isinstance(subtable, ot.SinglePos), subtable
2647
+ glyphs = subtable.Coverage.glyphs
2648
+ return (-len(glyphs), glyphMap[glyphs[0]])
2649
+
2650
+
2651
+ def _getSinglePosValueKey(valueRecord):
2652
+ # otBase.ValueRecord --> (2, ("YPlacement": 12))
2653
+ assert isinstance(valueRecord, ValueRecord), valueRecord
2654
+ valueFormat, result = 0, []
2655
+ for name, value in valueRecord.__dict__.items():
2656
+ if isinstance(value, ot.Device):
2657
+ result.append((name, _makeDeviceTuple(value)))
2658
+ else:
2659
+ result.append((name, value))
2660
+ valueFormat |= valueRecordFormatDict[name][0]
2661
+ result.sort()
2662
+ result.insert(0, valueFormat)
2663
+ return tuple(result)
2664
+
2665
+
2666
+ _DeviceTuple = namedtuple("_DeviceTuple", "DeltaFormat StartSize EndSize DeltaValue")
2667
+
2668
+
2669
+ def _makeDeviceTuple(device):
2670
+ # otTables.Device --> tuple, for making device tables unique
2671
+ return _DeviceTuple(
2672
+ device.DeltaFormat,
2673
+ device.StartSize,
2674
+ device.EndSize,
2675
+ () if device.DeltaFormat & 0x8000 else tuple(device.DeltaValue),
2676
+ )
2677
+
2678
+
2679
+ def _getSinglePosValueSize(valueKey):
2680
+ # Returns how many ushorts this valueKey (short form of ValueRecord) takes up
2681
+ count = 0
2682
+ for _, v in valueKey[1:]:
2683
+ if isinstance(v, _DeviceTuple):
2684
+ count += len(v.DeltaValue) + 3
2685
+ else:
2686
+ count += 1
2687
+ return count
2688
+
2689
+
2690
+ def buildValue(value):
2691
+ """Builds a positioning value record.
2692
+
2693
+ Value records are used to specify coordinates and adjustments for
2694
+ positioning and attaching glyphs. Many of the positioning functions
2695
+ in this library take ``otTables.ValueRecord`` objects as arguments.
2696
+ This function builds value records from dictionaries.
2697
+
2698
+ Args:
2699
+ value (dict): A dictionary with zero or more of the following keys:
2700
+ - ``xPlacement``
2701
+ - ``yPlacement``
2702
+ - ``xAdvance``
2703
+ - ``yAdvance``
2704
+ - ``xPlaDevice``
2705
+ - ``yPlaDevice``
2706
+ - ``xAdvDevice``
2707
+ - ``yAdvDevice``
2708
+
2709
+ Returns:
2710
+ An ``otTables.ValueRecord`` object.
2711
+ """
2712
+ self = ValueRecord()
2713
+ for k, v in value.items():
2714
+ setattr(self, k, v)
2715
+ return self
2716
+
2717
+
2718
+ # GDEF
2719
+
2720
+
2721
+ def buildAttachList(attachPoints, glyphMap):
2722
+ """Builds an AttachList subtable.
2723
+
2724
+ A GDEF table may contain an Attachment Point List table (AttachList)
2725
+ which stores the contour indices of attachment points for glyphs with
2726
+ attachment points. This routine builds AttachList subtables.
2727
+
2728
+ Args:
2729
+ attachPoints (dict): A mapping between glyph names and a list of
2730
+ contour indices.
2731
+
2732
+ Returns:
2733
+ An ``otTables.AttachList`` object if attachment points are supplied,
2734
+ or ``None`` otherwise.
2735
+ """
2736
+ if not attachPoints:
2737
+ return None
2738
+ self = ot.AttachList()
2739
+ self.Coverage = buildCoverage(attachPoints.keys(), glyphMap)
2740
+ self.AttachPoint = [buildAttachPoint(attachPoints[g]) for g in self.Coverage.glyphs]
2741
+ self.GlyphCount = len(self.AttachPoint)
2742
+ return self
2743
+
2744
+
2745
+ def buildAttachPoint(points):
2746
+ # [4, 23, 41] --> otTables.AttachPoint
2747
+ # Only used by above.
2748
+ if not points:
2749
+ return None
2750
+ self = ot.AttachPoint()
2751
+ self.PointIndex = sorted(set(points))
2752
+ self.PointCount = len(self.PointIndex)
2753
+ return self
2754
+
2755
+
2756
+ def buildCaretValueForCoord(coord):
2757
+ # 500 --> otTables.CaretValue, format 1
2758
+ # (500, DeviceTable) --> otTables.CaretValue, format 3
2759
+ self = ot.CaretValue()
2760
+ if isinstance(coord, tuple):
2761
+ self.Format = 3
2762
+ self.Coordinate, self.DeviceTable = coord
2763
+ else:
2764
+ self.Format = 1
2765
+ self.Coordinate = coord
2766
+ return self
2767
+
2768
+
2769
+ def buildCaretValueForPoint(point):
2770
+ # 4 --> otTables.CaretValue, format 2
2771
+ self = ot.CaretValue()
2772
+ self.Format = 2
2773
+ self.CaretValuePoint = point
2774
+ return self
2775
+
2776
+
2777
+ def buildLigCaretList(coords, points, glyphMap):
2778
+ """Builds a ligature caret list table.
2779
+
2780
+ Ligatures appear as a single glyph representing multiple characters; however
2781
+ when, for example, editing text containing a ``f_i`` ligature, the user may
2782
+ want to place the cursor between the ``f`` and the ``i``. The ligature caret
2783
+ list in the GDEF table specifies the position to display the "caret" (the
2784
+ character insertion indicator, typically a flashing vertical bar) "inside"
2785
+ the ligature to represent an insertion point. The insertion positions may
2786
+ be specified either by coordinate or by contour point.
2787
+
2788
+ Example::
2789
+
2790
+ coords = {
2791
+ "f_f_i": [300, 600] # f|fi cursor at 300 units, ff|i cursor at 600.
2792
+ }
2793
+ points = {
2794
+ "c_t": [28] # c|t cursor appears at coordinate of contour point 28.
2795
+ }
2796
+ ligcaretlist = buildLigCaretList(coords, points, font.getReverseGlyphMap())
2797
+
2798
+ Args:
2799
+ coords: A mapping between glyph names and a list of coordinates for
2800
+ the insertion point of each ligature component after the first one.
2801
+ points: A mapping between glyph names and a list of contour points for
2802
+ the insertion point of each ligature component after the first one.
2803
+ glyphMap: a glyph name to ID map, typically returned from
2804
+ ``font.getReverseGlyphMap()``.
2805
+
2806
+ Returns:
2807
+ A ``otTables.LigCaretList`` object if any carets are present, or
2808
+ ``None`` otherwise."""
2809
+ glyphs = set(coords.keys()) if coords else set()
2810
+ if points:
2811
+ glyphs.update(points.keys())
2812
+ carets = {g: buildLigGlyph(coords.get(g), points.get(g)) for g in glyphs}
2813
+ carets = {g: c for g, c in carets.items() if c is not None}
2814
+ if not carets:
2815
+ return None
2816
+ self = ot.LigCaretList()
2817
+ self.Coverage = buildCoverage(carets.keys(), glyphMap)
2818
+ self.LigGlyph = [carets[g] for g in self.Coverage.glyphs]
2819
+ self.LigGlyphCount = len(self.LigGlyph)
2820
+ return self
2821
+
2822
+
2823
+ def buildLigGlyph(coords, points):
2824
+ # ([500], [4]) --> otTables.LigGlyph; None for empty coords/points
2825
+ carets = []
2826
+ if coords:
2827
+ coords = sorted(coords, key=lambda c: c[0] if isinstance(c, tuple) else c)
2828
+ carets.extend([buildCaretValueForCoord(c) for c in coords])
2829
+ if points:
2830
+ carets.extend([buildCaretValueForPoint(p) for p in sorted(points)])
2831
+ if not carets:
2832
+ return None
2833
+ self = ot.LigGlyph()
2834
+ self.CaretValue = carets
2835
+ self.CaretCount = len(self.CaretValue)
2836
+ return self
2837
+
2838
+
2839
+ def buildMarkGlyphSetsDef(markSets, glyphMap):
2840
+ """Builds a mark glyph sets definition table.
2841
+
2842
+ OpenType Layout lookups may choose to use mark filtering sets to consider
2843
+ or ignore particular combinations of marks. These sets are specified by
2844
+ setting a flag on the lookup, but the mark filtering sets are defined in
2845
+ the ``GDEF`` table. This routine builds the subtable containing the mark
2846
+ glyph set definitions.
2847
+
2848
+ Example::
2849
+
2850
+ set0 = set("acute", "grave")
2851
+ set1 = set("caron", "grave")
2852
+
2853
+ markglyphsets = buildMarkGlyphSetsDef([set0, set1], font.getReverseGlyphMap())
2854
+
2855
+ Args:
2856
+
2857
+ markSets: A list of sets of glyphnames.
2858
+ glyphMap: a glyph name to ID map, typically returned from
2859
+ ``font.getReverseGlyphMap()``.
2860
+
2861
+ Returns
2862
+ An ``otTables.MarkGlyphSetsDef`` object.
2863
+ """
2864
+ if not markSets:
2865
+ return None
2866
+ self = ot.MarkGlyphSetsDef()
2867
+ self.MarkSetTableFormat = 1
2868
+ self.Coverage = [buildCoverage(m, glyphMap) for m in markSets]
2869
+ self.MarkSetCount = len(self.Coverage)
2870
+ return self
2871
+
2872
+
2873
+ class ClassDefBuilder(object):
2874
+ """Helper for building ClassDef tables."""
2875
+
2876
+ def __init__(self, useClass0):
2877
+ self.classes_ = set()
2878
+ self.glyphs_ = {}
2879
+ self.useClass0_ = useClass0
2880
+
2881
+ def canAdd(self, glyphs):
2882
+ if isinstance(glyphs, (set, frozenset)):
2883
+ glyphs = sorted(glyphs)
2884
+ glyphs = tuple(glyphs)
2885
+ if glyphs in self.classes_:
2886
+ return True
2887
+ for glyph in glyphs:
2888
+ if glyph in self.glyphs_:
2889
+ return False
2890
+ return True
2891
+
2892
+ def add(self, glyphs):
2893
+ if isinstance(glyphs, (set, frozenset)):
2894
+ glyphs = sorted(glyphs)
2895
+ glyphs = tuple(glyphs)
2896
+ if glyphs in self.classes_:
2897
+ return
2898
+ self.classes_.add(glyphs)
2899
+ for glyph in glyphs:
2900
+ if glyph in self.glyphs_:
2901
+ raise OpenTypeLibError(
2902
+ f"Glyph {glyph} is already present in class.", None
2903
+ )
2904
+ self.glyphs_[glyph] = glyphs
2905
+
2906
+ def classes(self):
2907
+ # In ClassDef1 tables, class id #0 does not need to be encoded
2908
+ # because zero is the default. Therefore, we use id #0 for the
2909
+ # glyph class that has the largest number of members. However,
2910
+ # in other tables than ClassDef1, 0 means "every other glyph"
2911
+ # so we should not use that ID for any real glyph classes;
2912
+ # we implement this by inserting an empty set at position 0.
2913
+ #
2914
+ # TODO: Instead of counting the number of glyphs in each class,
2915
+ # we should determine the encoded size. If the glyphs in a large
2916
+ # class form a contiguous range, the encoding is actually quite
2917
+ # compact, whereas a non-contiguous set might need a lot of bytes
2918
+ # in the output file. We don't get this right with the key below.
2919
+ result = sorted(self.classes_, key=lambda s: (-len(s), s))
2920
+ if not self.useClass0_:
2921
+ result.insert(0, frozenset())
2922
+ return result
2923
+
2924
+ def build(self):
2925
+ glyphClasses = {}
2926
+ for classID, glyphs in enumerate(self.classes()):
2927
+ if classID == 0:
2928
+ continue
2929
+ for glyph in glyphs:
2930
+ glyphClasses[glyph] = classID
2931
+ classDef = ot.ClassDef()
2932
+ classDef.classDefs = glyphClasses
2933
+ return classDef
2934
+
2935
+
2936
+ AXIS_VALUE_NEGATIVE_INFINITY = fixedToFloat(-0x80000000, 16)
2937
+ AXIS_VALUE_POSITIVE_INFINITY = fixedToFloat(0x7FFFFFFF, 16)
2938
+
2939
+ STATName = Union[int, str, Dict[str, str]]
2940
+ """A raw name ID, English name, or multilingual name."""
2941
+
2942
+
2943
+ def buildStatTable(
2944
+ ttFont: TTFont,
2945
+ axes,
2946
+ locations=None,
2947
+ elidedFallbackName: Union[STATName, STATNameStatement] = 2,
2948
+ windowsNames: bool = True,
2949
+ macNames: bool = True,
2950
+ ) -> None:
2951
+ """Add a 'STAT' table to 'ttFont'.
2952
+
2953
+ 'axes' is a list of dictionaries describing axes and their
2954
+ values.
2955
+
2956
+ Example::
2957
+
2958
+ axes = [
2959
+ dict(
2960
+ tag="wght",
2961
+ name="Weight",
2962
+ ordering=0, # optional
2963
+ values=[
2964
+ dict(value=100, name='Thin'),
2965
+ dict(value=300, name='Light'),
2966
+ dict(value=400, name='Regular', flags=0x2),
2967
+ dict(value=900, name='Black'),
2968
+ ],
2969
+ )
2970
+ ]
2971
+
2972
+ Each axis dict must have 'tag' and 'name' items. 'tag' maps
2973
+ to the 'AxisTag' field. 'name' can be a name ID (int), a string,
2974
+ or a dictionary containing multilingual names (see the
2975
+ addMultilingualName() name table method), and will translate to
2976
+ the AxisNameID field.
2977
+
2978
+ An axis dict may contain an 'ordering' item that maps to the
2979
+ AxisOrdering field. If omitted, the order of the axes list is
2980
+ used to calculate AxisOrdering fields.
2981
+
2982
+ The axis dict may contain a 'values' item, which is a list of
2983
+ dictionaries describing AxisValue records belonging to this axis.
2984
+
2985
+ Each value dict must have a 'name' item, which can be a name ID
2986
+ (int), a string, or a dictionary containing multilingual names,
2987
+ like the axis name. It translates to the ValueNameID field.
2988
+
2989
+ Optionally the value dict can contain a 'flags' item. It maps to
2990
+ the AxisValue Flags field, and will be 0 when omitted.
2991
+
2992
+ The format of the AxisValue is determined by the remaining contents
2993
+ of the value dictionary:
2994
+
2995
+ If the value dict contains a 'value' item, an AxisValue record
2996
+ Format 1 is created. If in addition to the 'value' item it contains
2997
+ a 'linkedValue' item, an AxisValue record Format 3 is built.
2998
+
2999
+ If the value dict contains a 'nominalValue' item, an AxisValue
3000
+ record Format 2 is built. Optionally it may contain 'rangeMinValue'
3001
+ and 'rangeMaxValue' items. These map to -Infinity and +Infinity
3002
+ respectively if omitted.
3003
+
3004
+ You cannot specify Format 4 AxisValue tables this way, as they are
3005
+ not tied to a single axis, and specify a name for a location that
3006
+ is defined by multiple axes values. Instead, you need to supply the
3007
+ 'locations' argument.
3008
+
3009
+ The optional 'locations' argument specifies AxisValue Format 4
3010
+ tables. It should be a list of dicts, where each dict has a 'name'
3011
+ item, which works just like the value dicts above, an optional
3012
+ 'flags' item (defaulting to 0x0), and a 'location' dict. A
3013
+ location dict key is an axis tag, and the associated value is the
3014
+ location on the specified axis. They map to the AxisIndex and Value
3015
+ fields of the AxisValueRecord.
3016
+
3017
+ Example::
3018
+
3019
+ locations = [
3020
+ dict(name='Regular ABCD', location=dict(wght=300, ABCD=100)),
3021
+ dict(name='Bold ABCD XYZ', location=dict(wght=600, ABCD=200)),
3022
+ ]
3023
+
3024
+ The optional 'elidedFallbackName' argument can be a name ID (int),
3025
+ a string, a dictionary containing multilingual names, or a list of
3026
+ STATNameStatements. It translates to the ElidedFallbackNameID field.
3027
+
3028
+ The 'ttFont' argument must be a TTFont instance that already has a
3029
+ 'name' table. If a 'STAT' table already exists, it will be
3030
+ overwritten by the newly created one.
3031
+ """
3032
+ ttFont["STAT"] = ttLib.newTable("STAT")
3033
+ statTable = ttFont["STAT"].table = ot.STAT()
3034
+ statTable.ElidedFallbackNameID = _addName(
3035
+ ttFont, elidedFallbackName, windows=windowsNames, mac=macNames
3036
+ )
3037
+
3038
+ # 'locations' contains data for AxisValue Format 4
3039
+ axisRecords, axisValues = _buildAxisRecords(
3040
+ axes, ttFont, windowsNames=windowsNames, macNames=macNames
3041
+ )
3042
+ if not locations:
3043
+ statTable.Version = 0x00010001
3044
+ else:
3045
+ # We'll be adding Format 4 AxisValue records, which
3046
+ # requires a higher table version
3047
+ statTable.Version = 0x00010002
3048
+ multiAxisValues = _buildAxisValuesFormat4(
3049
+ locations, axes, ttFont, windowsNames=windowsNames, macNames=macNames
3050
+ )
3051
+ axisValues = multiAxisValues + axisValues
3052
+ ttFont["name"].names.sort()
3053
+
3054
+ # Store AxisRecords
3055
+ axisRecordArray = ot.AxisRecordArray()
3056
+ axisRecordArray.Axis = axisRecords
3057
+ # XXX these should not be hard-coded but computed automatically
3058
+ statTable.DesignAxisRecordSize = 8
3059
+ statTable.DesignAxisRecord = axisRecordArray
3060
+ statTable.DesignAxisCount = len(axisRecords)
3061
+
3062
+ statTable.AxisValueCount = 0
3063
+ statTable.AxisValueArray = None
3064
+ if axisValues:
3065
+ # Store AxisValueRecords
3066
+ axisValueArray = ot.AxisValueArray()
3067
+ axisValueArray.AxisValue = axisValues
3068
+ statTable.AxisValueArray = axisValueArray
3069
+ statTable.AxisValueCount = len(axisValues)
3070
+
3071
+
3072
+ def _buildAxisRecords(axes, ttFont, windowsNames=True, macNames=True):
3073
+ axisRecords = []
3074
+ axisValues = []
3075
+ for axisRecordIndex, axisDict in enumerate(axes):
3076
+ axis = ot.AxisRecord()
3077
+ axis.AxisTag = axisDict["tag"]
3078
+ axis.AxisNameID = _addName(
3079
+ ttFont, axisDict["name"], 256, windows=windowsNames, mac=macNames
3080
+ )
3081
+ axis.AxisOrdering = axisDict.get("ordering", axisRecordIndex)
3082
+ axisRecords.append(axis)
3083
+
3084
+ for axisVal in axisDict.get("values", ()):
3085
+ axisValRec = ot.AxisValue()
3086
+ axisValRec.AxisIndex = axisRecordIndex
3087
+ axisValRec.Flags = axisVal.get("flags", 0)
3088
+ axisValRec.ValueNameID = _addName(
3089
+ ttFont, axisVal["name"], windows=windowsNames, mac=macNames
3090
+ )
3091
+
3092
+ if "value" in axisVal:
3093
+ axisValRec.Value = axisVal["value"]
3094
+ if "linkedValue" in axisVal:
3095
+ axisValRec.Format = 3
3096
+ axisValRec.LinkedValue = axisVal["linkedValue"]
3097
+ else:
3098
+ axisValRec.Format = 1
3099
+ elif "nominalValue" in axisVal:
3100
+ axisValRec.Format = 2
3101
+ axisValRec.NominalValue = axisVal["nominalValue"]
3102
+ axisValRec.RangeMinValue = axisVal.get(
3103
+ "rangeMinValue", AXIS_VALUE_NEGATIVE_INFINITY
3104
+ )
3105
+ axisValRec.RangeMaxValue = axisVal.get(
3106
+ "rangeMaxValue", AXIS_VALUE_POSITIVE_INFINITY
3107
+ )
3108
+ else:
3109
+ raise ValueError("Can't determine format for AxisValue")
3110
+
3111
+ axisValues.append(axisValRec)
3112
+ return axisRecords, axisValues
3113
+
3114
+
3115
+ def _buildAxisValuesFormat4(locations, axes, ttFont, windowsNames=True, macNames=True):
3116
+ axisTagToIndex = {}
3117
+ for axisRecordIndex, axisDict in enumerate(axes):
3118
+ axisTagToIndex[axisDict["tag"]] = axisRecordIndex
3119
+
3120
+ axisValues = []
3121
+ for axisLocationDict in locations:
3122
+ axisValRec = ot.AxisValue()
3123
+ axisValRec.Format = 4
3124
+ axisValRec.ValueNameID = _addName(
3125
+ ttFont, axisLocationDict["name"], windows=windowsNames, mac=macNames
3126
+ )
3127
+ axisValRec.Flags = axisLocationDict.get("flags", 0)
3128
+ axisValueRecords = []
3129
+ for tag, value in axisLocationDict["location"].items():
3130
+ avr = ot.AxisValueRecord()
3131
+ avr.AxisIndex = axisTagToIndex[tag]
3132
+ avr.Value = value
3133
+ axisValueRecords.append(avr)
3134
+ axisValueRecords.sort(key=lambda avr: avr.AxisIndex)
3135
+ axisValRec.AxisCount = len(axisValueRecords)
3136
+ axisValRec.AxisValueRecord = axisValueRecords
3137
+ axisValues.append(axisValRec)
3138
+ return axisValues
3139
+
3140
+
3141
+ def _addName(
3142
+ ttFont: TTFont,
3143
+ value: Union[STATName, STATNameStatement],
3144
+ minNameID: int = 0,
3145
+ windows: bool = True,
3146
+ mac: bool = True,
3147
+ ) -> int:
3148
+ nameTable = ttFont["name"]
3149
+ if isinstance(value, int):
3150
+ # Already a nameID
3151
+ return value
3152
+ if isinstance(value, str):
3153
+ names = dict(en=value)
3154
+ elif isinstance(value, dict):
3155
+ names = value
3156
+ elif isinstance(value, list):
3157
+ nameID = nameTable._findUnusedNameID()
3158
+ for nameRecord in value:
3159
+ if isinstance(nameRecord, STATNameStatement):
3160
+ nameTable.setName(
3161
+ nameRecord.string,
3162
+ nameID,
3163
+ nameRecord.platformID,
3164
+ nameRecord.platEncID,
3165
+ nameRecord.langID,
3166
+ )
3167
+ else:
3168
+ raise TypeError("value must be a list of STATNameStatements")
3169
+ return nameID
3170
+ else:
3171
+ raise TypeError("value must be int, str, dict or list")
3172
+ return nameTable.addMultilingualName(
3173
+ names, ttFont=ttFont, windows=windows, mac=mac, minNameID=minNameID
3174
+ )
3175
+
3176
+
3177
+ def buildMathTable(
3178
+ ttFont,
3179
+ constants=None,
3180
+ italicsCorrections=None,
3181
+ topAccentAttachments=None,
3182
+ extendedShapes=None,
3183
+ mathKerns=None,
3184
+ minConnectorOverlap=0,
3185
+ vertGlyphVariants=None,
3186
+ horizGlyphVariants=None,
3187
+ vertGlyphAssembly=None,
3188
+ horizGlyphAssembly=None,
3189
+ ):
3190
+ """
3191
+ Add a 'MATH' table to 'ttFont'.
3192
+
3193
+ 'constants' is a dictionary of math constants. The keys are the constant
3194
+ names from the MATH table specification (with capital first letter), and the
3195
+ values are the constant values as numbers.
3196
+
3197
+ 'italicsCorrections' is a dictionary of italic corrections. The keys are the
3198
+ glyph names, and the values are the italic corrections as numbers.
3199
+
3200
+ 'topAccentAttachments' is a dictionary of top accent attachments. The keys
3201
+ are the glyph names, and the values are the top accent horizontal positions
3202
+ as numbers.
3203
+
3204
+ 'extendedShapes' is a set of extended shape glyphs.
3205
+
3206
+ 'mathKerns' is a dictionary of math kerns. The keys are the glyph names, and
3207
+ the values are dictionaries. The keys of these dictionaries are the side
3208
+ names ('TopRight', 'TopLeft', 'BottomRight', 'BottomLeft'), and the values
3209
+ are tuples of two lists. The first list contains the correction heights as
3210
+ numbers, and the second list contains the kern values as numbers.
3211
+
3212
+ 'minConnectorOverlap' is the minimum connector overlap as a number.
3213
+
3214
+ 'vertGlyphVariants' is a dictionary of vertical glyph variants. The keys are
3215
+ the glyph names, and the values are tuples of glyph name and full advance height.
3216
+
3217
+ 'horizGlyphVariants' is a dictionary of horizontal glyph variants. The keys
3218
+ are the glyph names, and the values are tuples of glyph name and full
3219
+ advance width.
3220
+
3221
+ 'vertGlyphAssembly' is a dictionary of vertical glyph assemblies. The keys
3222
+ are the glyph names, and the values are tuples of assembly parts and italics
3223
+ correction. The assembly parts are tuples of glyph name, flags, start
3224
+ connector length, end connector length, and full advance height.
3225
+
3226
+ 'horizGlyphAssembly' is a dictionary of horizontal glyph assemblies. The
3227
+ keys are the glyph names, and the values are tuples of assembly parts
3228
+ and italics correction. The assembly parts are tuples of glyph name, flags,
3229
+ start connector length, end connector length, and full advance width.
3230
+
3231
+ Where a number is expected, an integer or a float can be used. The floats
3232
+ will be rounded.
3233
+
3234
+ Example::
3235
+
3236
+ constants = {
3237
+ "ScriptPercentScaleDown": 70,
3238
+ "ScriptScriptPercentScaleDown": 50,
3239
+ "DelimitedSubFormulaMinHeight": 24,
3240
+ "DisplayOperatorMinHeight": 60,
3241
+ ...
3242
+ }
3243
+ italicsCorrections = {
3244
+ "fitalic-math": 100,
3245
+ "fbolditalic-math": 120,
3246
+ ...
3247
+ }
3248
+ topAccentAttachments = {
3249
+ "circumflexcomb": 500,
3250
+ "acutecomb": 400,
3251
+ "A": 300,
3252
+ "B": 340,
3253
+ ...
3254
+ }
3255
+ extendedShapes = {"parenleft", "parenright", ...}
3256
+ mathKerns = {
3257
+ "A": {
3258
+ "TopRight": ([-50, -100], [10, 20, 30]),
3259
+ "TopLeft": ([50, 100], [10, 20, 30]),
3260
+ ...
3261
+ },
3262
+ ...
3263
+ }
3264
+ vertGlyphVariants = {
3265
+ "parenleft": [("parenleft", 700), ("parenleft.size1", 1000), ...],
3266
+ "parenright": [("parenright", 700), ("parenright.size1", 1000), ...],
3267
+ ...
3268
+ }
3269
+ vertGlyphAssembly = {
3270
+ "braceleft": [
3271
+ (
3272
+ ("braceleft.bottom", 0, 0, 200, 500),
3273
+ ("braceleft.extender", 1, 200, 200, 200)),
3274
+ ("braceleft.middle", 0, 100, 100, 700),
3275
+ ("braceleft.extender", 1, 200, 200, 200),
3276
+ ("braceleft.top", 0, 200, 0, 500),
3277
+ ),
3278
+ 100,
3279
+ ],
3280
+ ...
3281
+ }
3282
+ """
3283
+ glyphMap = ttFont.getReverseGlyphMap()
3284
+
3285
+ ttFont["MATH"] = math = ttLib.newTable("MATH")
3286
+ math.table = table = ot.MATH()
3287
+ table.Version = 0x00010000
3288
+ table.populateDefaults()
3289
+
3290
+ table.MathConstants = _buildMathConstants(constants)
3291
+ table.MathGlyphInfo = _buildMathGlyphInfo(
3292
+ glyphMap,
3293
+ italicsCorrections,
3294
+ topAccentAttachments,
3295
+ extendedShapes,
3296
+ mathKerns,
3297
+ )
3298
+ table.MathVariants = _buildMathVariants(
3299
+ glyphMap,
3300
+ minConnectorOverlap,
3301
+ vertGlyphVariants,
3302
+ horizGlyphVariants,
3303
+ vertGlyphAssembly,
3304
+ horizGlyphAssembly,
3305
+ )
3306
+
3307
+
3308
+ def _buildMathConstants(constants):
3309
+ if not constants:
3310
+ return None
3311
+
3312
+ mathConstants = ot.MathConstants()
3313
+ for conv in mathConstants.getConverters():
3314
+ value = otRound(constants.get(conv.name, 0))
3315
+ if conv.tableClass:
3316
+ assert issubclass(conv.tableClass, ot.MathValueRecord)
3317
+ value = _mathValueRecord(value)
3318
+ setattr(mathConstants, conv.name, value)
3319
+ return mathConstants
3320
+
3321
+
3322
+ def _buildMathGlyphInfo(
3323
+ glyphMap,
3324
+ italicsCorrections,
3325
+ topAccentAttachments,
3326
+ extendedShapes,
3327
+ mathKerns,
3328
+ ):
3329
+ if not any([extendedShapes, italicsCorrections, topAccentAttachments, mathKerns]):
3330
+ return None
3331
+
3332
+ info = ot.MathGlyphInfo()
3333
+ info.populateDefaults()
3334
+
3335
+ if italicsCorrections:
3336
+ coverage = buildCoverage(italicsCorrections.keys(), glyphMap)
3337
+ info.MathItalicsCorrectionInfo = ot.MathItalicsCorrectionInfo()
3338
+ info.MathItalicsCorrectionInfo.Coverage = coverage
3339
+ info.MathItalicsCorrectionInfo.ItalicsCorrectionCount = len(coverage.glyphs)
3340
+ info.MathItalicsCorrectionInfo.ItalicsCorrection = [
3341
+ _mathValueRecord(italicsCorrections[n]) for n in coverage.glyphs
3342
+ ]
3343
+
3344
+ if topAccentAttachments:
3345
+ coverage = buildCoverage(topAccentAttachments.keys(), glyphMap)
3346
+ info.MathTopAccentAttachment = ot.MathTopAccentAttachment()
3347
+ info.MathTopAccentAttachment.TopAccentCoverage = coverage
3348
+ info.MathTopAccentAttachment.TopAccentAttachmentCount = len(coverage.glyphs)
3349
+ info.MathTopAccentAttachment.TopAccentAttachment = [
3350
+ _mathValueRecord(topAccentAttachments[n]) for n in coverage.glyphs
3351
+ ]
3352
+
3353
+ if extendedShapes:
3354
+ info.ExtendedShapeCoverage = buildCoverage(extendedShapes, glyphMap)
3355
+
3356
+ if mathKerns:
3357
+ coverage = buildCoverage(mathKerns.keys(), glyphMap)
3358
+ info.MathKernInfo = ot.MathKernInfo()
3359
+ info.MathKernInfo.MathKernCoverage = coverage
3360
+ info.MathKernInfo.MathKernCount = len(coverage.glyphs)
3361
+ info.MathKernInfo.MathKernInfoRecords = []
3362
+ for glyph in coverage.glyphs:
3363
+ record = ot.MathKernInfoRecord()
3364
+ for side in {"TopRight", "TopLeft", "BottomRight", "BottomLeft"}:
3365
+ if side in mathKerns[glyph]:
3366
+ correctionHeights, kernValues = mathKerns[glyph][side]
3367
+ assert len(correctionHeights) == len(kernValues) - 1
3368
+ kern = ot.MathKern()
3369
+ kern.HeightCount = len(correctionHeights)
3370
+ kern.CorrectionHeight = [
3371
+ _mathValueRecord(h) for h in correctionHeights
3372
+ ]
3373
+ kern.KernValue = [_mathValueRecord(v) for v in kernValues]
3374
+ setattr(record, f"{side}MathKern", kern)
3375
+ info.MathKernInfo.MathKernInfoRecords.append(record)
3376
+
3377
+ return info
3378
+
3379
+
3380
+ def _buildMathVariants(
3381
+ glyphMap,
3382
+ minConnectorOverlap,
3383
+ vertGlyphVariants,
3384
+ horizGlyphVariants,
3385
+ vertGlyphAssembly,
3386
+ horizGlyphAssembly,
3387
+ ):
3388
+ if not any(
3389
+ [vertGlyphVariants, horizGlyphVariants, vertGlyphAssembly, horizGlyphAssembly]
3390
+ ):
3391
+ return None
3392
+
3393
+ variants = ot.MathVariants()
3394
+ variants.populateDefaults()
3395
+
3396
+ variants.MinConnectorOverlap = minConnectorOverlap
3397
+
3398
+ if vertGlyphVariants or vertGlyphAssembly:
3399
+ variants.VertGlyphCoverage, variants.VertGlyphConstruction = (
3400
+ _buildMathGlyphConstruction(
3401
+ glyphMap,
3402
+ vertGlyphVariants,
3403
+ vertGlyphAssembly,
3404
+ )
3405
+ )
3406
+
3407
+ if horizGlyphVariants or horizGlyphAssembly:
3408
+ variants.HorizGlyphCoverage, variants.HorizGlyphConstruction = (
3409
+ _buildMathGlyphConstruction(
3410
+ glyphMap,
3411
+ horizGlyphVariants,
3412
+ horizGlyphAssembly,
3413
+ )
3414
+ )
3415
+
3416
+ return variants
3417
+
3418
+
3419
+ def _buildMathGlyphConstruction(glyphMap, variants, assemblies):
3420
+ glyphs = set()
3421
+ if variants:
3422
+ glyphs.update(variants.keys())
3423
+ if assemblies:
3424
+ glyphs.update(assemblies.keys())
3425
+ coverage = buildCoverage(glyphs, glyphMap)
3426
+ constructions = []
3427
+
3428
+ for glyphName in coverage.glyphs:
3429
+ construction = ot.MathGlyphConstruction()
3430
+ construction.populateDefaults()
3431
+
3432
+ if variants and glyphName in variants:
3433
+ construction.VariantCount = len(variants[glyphName])
3434
+ construction.MathGlyphVariantRecord = []
3435
+ for variantName, advance in variants[glyphName]:
3436
+ record = ot.MathGlyphVariantRecord()
3437
+ record.VariantGlyph = variantName
3438
+ record.AdvanceMeasurement = otRound(advance)
3439
+ construction.MathGlyphVariantRecord.append(record)
3440
+
3441
+ if assemblies and glyphName in assemblies:
3442
+ parts, ic = assemblies[glyphName]
3443
+ construction.GlyphAssembly = ot.GlyphAssembly()
3444
+ construction.GlyphAssembly.ItalicsCorrection = _mathValueRecord(ic)
3445
+ construction.GlyphAssembly.PartCount = len(parts)
3446
+ construction.GlyphAssembly.PartRecords = []
3447
+ for part in parts:
3448
+ part_name, flags, start, end, advance = part
3449
+ record = ot.GlyphPartRecord()
3450
+ record.glyph = part_name
3451
+ record.PartFlags = int(flags)
3452
+ record.StartConnectorLength = otRound(start)
3453
+ record.EndConnectorLength = otRound(end)
3454
+ record.FullAdvance = otRound(advance)
3455
+ construction.GlyphAssembly.PartRecords.append(record)
3456
+
3457
+ constructions.append(construction)
3458
+
3459
+ return coverage, constructions
3460
+
3461
+
3462
+ def _mathValueRecord(value):
3463
+ value_record = ot.MathValueRecord()
3464
+ value_record.Value = otRound(value)
3465
+ return value_record