fonttools 4.55.6__cp311-cp311-musllinux_1_2_x86_64.whl

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

Potentially problematic release.


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

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