fonttools 4.58.3__cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of fonttools might be problematic. Click here for more details.

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