fonttools 4.59.1__cp314-cp314-win32.whl

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

Potentially problematic release.


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

Files changed (346) 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 +233 -0
  6. fontTools/cffLib/CFFToCFF2.py +305 -0
  7. fontTools/cffLib/__init__.py +3694 -0
  8. fontTools/cffLib/specializer.py +927 -0
  9. fontTools/cffLib/transforms.py +495 -0
  10. fontTools/cffLib/width.py +210 -0
  11. fontTools/colorLib/__init__.py +0 -0
  12. fontTools/colorLib/builder.py +664 -0
  13. fontTools/colorLib/errors.py +2 -0
  14. fontTools/colorLib/geometry.py +143 -0
  15. fontTools/colorLib/table_builder.py +223 -0
  16. fontTools/colorLib/unbuilder.py +81 -0
  17. fontTools/config/__init__.py +90 -0
  18. fontTools/cu2qu/__init__.py +15 -0
  19. fontTools/cu2qu/__main__.py +6 -0
  20. fontTools/cu2qu/benchmark.py +54 -0
  21. fontTools/cu2qu/cli.py +198 -0
  22. fontTools/cu2qu/cu2qu.c +15559 -0
  23. fontTools/cu2qu/cu2qu.cp314-win32.pyd +0 -0
  24. fontTools/cu2qu/cu2qu.py +531 -0
  25. fontTools/cu2qu/errors.py +77 -0
  26. fontTools/cu2qu/ufo.py +349 -0
  27. fontTools/designspaceLib/__init__.py +3338 -0
  28. fontTools/designspaceLib/__main__.py +6 -0
  29. fontTools/designspaceLib/split.py +475 -0
  30. fontTools/designspaceLib/statNames.py +260 -0
  31. fontTools/designspaceLib/types.py +147 -0
  32. fontTools/encodings/MacRoman.py +258 -0
  33. fontTools/encodings/StandardEncoding.py +258 -0
  34. fontTools/encodings/__init__.py +1 -0
  35. fontTools/encodings/codecs.py +135 -0
  36. fontTools/feaLib/__init__.py +4 -0
  37. fontTools/feaLib/__main__.py +78 -0
  38. fontTools/feaLib/ast.py +2143 -0
  39. fontTools/feaLib/builder.py +1802 -0
  40. fontTools/feaLib/error.py +22 -0
  41. fontTools/feaLib/lexer.c +17350 -0
  42. fontTools/feaLib/lexer.cp314-win32.pyd +0 -0
  43. fontTools/feaLib/lexer.py +287 -0
  44. fontTools/feaLib/location.py +12 -0
  45. fontTools/feaLib/lookupDebugInfo.py +12 -0
  46. fontTools/feaLib/parser.py +2379 -0
  47. fontTools/feaLib/variableScalar.py +113 -0
  48. fontTools/fontBuilder.py +1014 -0
  49. fontTools/help.py +36 -0
  50. fontTools/merge/__init__.py +248 -0
  51. fontTools/merge/__main__.py +6 -0
  52. fontTools/merge/base.py +81 -0
  53. fontTools/merge/cmap.py +173 -0
  54. fontTools/merge/layout.py +526 -0
  55. fontTools/merge/options.py +85 -0
  56. fontTools/merge/tables.py +352 -0
  57. fontTools/merge/unicode.py +78 -0
  58. fontTools/merge/util.py +143 -0
  59. fontTools/misc/__init__.py +1 -0
  60. fontTools/misc/arrayTools.py +424 -0
  61. fontTools/misc/bezierTools.c +40150 -0
  62. fontTools/misc/bezierTools.cp314-win32.pyd +0 -0
  63. fontTools/misc/bezierTools.py +1497 -0
  64. fontTools/misc/classifyTools.py +170 -0
  65. fontTools/misc/cliTools.py +53 -0
  66. fontTools/misc/configTools.py +349 -0
  67. fontTools/misc/cython.py +27 -0
  68. fontTools/misc/dictTools.py +83 -0
  69. fontTools/misc/eexec.py +119 -0
  70. fontTools/misc/encodingTools.py +72 -0
  71. fontTools/misc/etree.py +456 -0
  72. fontTools/misc/filenames.py +245 -0
  73. fontTools/misc/filesystem/__init__.py +68 -0
  74. fontTools/misc/filesystem/_base.py +134 -0
  75. fontTools/misc/filesystem/_copy.py +45 -0
  76. fontTools/misc/filesystem/_errors.py +54 -0
  77. fontTools/misc/filesystem/_info.py +75 -0
  78. fontTools/misc/filesystem/_osfs.py +164 -0
  79. fontTools/misc/filesystem/_path.py +67 -0
  80. fontTools/misc/filesystem/_subfs.py +92 -0
  81. fontTools/misc/filesystem/_tempfs.py +34 -0
  82. fontTools/misc/filesystem/_tools.py +34 -0
  83. fontTools/misc/filesystem/_walk.py +55 -0
  84. fontTools/misc/filesystem/_zipfs.py +204 -0
  85. fontTools/misc/fixedTools.py +253 -0
  86. fontTools/misc/intTools.py +25 -0
  87. fontTools/misc/iterTools.py +12 -0
  88. fontTools/misc/lazyTools.py +42 -0
  89. fontTools/misc/loggingTools.py +543 -0
  90. fontTools/misc/macCreatorType.py +56 -0
  91. fontTools/misc/macRes.py +261 -0
  92. fontTools/misc/plistlib/__init__.py +681 -0
  93. fontTools/misc/plistlib/py.typed +0 -0
  94. fontTools/misc/psCharStrings.py +1511 -0
  95. fontTools/misc/psLib.py +398 -0
  96. fontTools/misc/psOperators.py +572 -0
  97. fontTools/misc/py23.py +96 -0
  98. fontTools/misc/roundTools.py +110 -0
  99. fontTools/misc/sstruct.py +227 -0
  100. fontTools/misc/symfont.py +242 -0
  101. fontTools/misc/testTools.py +233 -0
  102. fontTools/misc/textTools.py +154 -0
  103. fontTools/misc/timeTools.py +88 -0
  104. fontTools/misc/transform.py +516 -0
  105. fontTools/misc/treeTools.py +45 -0
  106. fontTools/misc/vector.py +147 -0
  107. fontTools/misc/visitor.py +150 -0
  108. fontTools/misc/xmlReader.py +188 -0
  109. fontTools/misc/xmlWriter.py +231 -0
  110. fontTools/mtiLib/__init__.py +1400 -0
  111. fontTools/mtiLib/__main__.py +5 -0
  112. fontTools/otlLib/__init__.py +1 -0
  113. fontTools/otlLib/builder.py +3465 -0
  114. fontTools/otlLib/error.py +11 -0
  115. fontTools/otlLib/maxContextCalc.py +96 -0
  116. fontTools/otlLib/optimize/__init__.py +53 -0
  117. fontTools/otlLib/optimize/__main__.py +6 -0
  118. fontTools/otlLib/optimize/gpos.py +439 -0
  119. fontTools/pens/__init__.py +1 -0
  120. fontTools/pens/areaPen.py +52 -0
  121. fontTools/pens/basePen.py +475 -0
  122. fontTools/pens/boundsPen.py +98 -0
  123. fontTools/pens/cairoPen.py +26 -0
  124. fontTools/pens/cocoaPen.py +26 -0
  125. fontTools/pens/cu2quPen.py +325 -0
  126. fontTools/pens/explicitClosingLinePen.py +101 -0
  127. fontTools/pens/filterPen.py +241 -0
  128. fontTools/pens/freetypePen.py +462 -0
  129. fontTools/pens/hashPointPen.py +89 -0
  130. fontTools/pens/momentsPen.c +13465 -0
  131. fontTools/pens/momentsPen.cp314-win32.pyd +0 -0
  132. fontTools/pens/momentsPen.py +879 -0
  133. fontTools/pens/perimeterPen.py +69 -0
  134. fontTools/pens/pointInsidePen.py +192 -0
  135. fontTools/pens/pointPen.py +609 -0
  136. fontTools/pens/qtPen.py +29 -0
  137. fontTools/pens/qu2cuPen.py +105 -0
  138. fontTools/pens/quartzPen.py +43 -0
  139. fontTools/pens/recordingPen.py +335 -0
  140. fontTools/pens/reportLabPen.py +79 -0
  141. fontTools/pens/reverseContourPen.py +96 -0
  142. fontTools/pens/roundingPen.py +130 -0
  143. fontTools/pens/statisticsPen.py +312 -0
  144. fontTools/pens/svgPathPen.py +310 -0
  145. fontTools/pens/t2CharStringPen.py +88 -0
  146. fontTools/pens/teePen.py +55 -0
  147. fontTools/pens/transformPen.py +115 -0
  148. fontTools/pens/ttGlyphPen.py +335 -0
  149. fontTools/pens/wxPen.py +29 -0
  150. fontTools/qu2cu/__init__.py +15 -0
  151. fontTools/qu2cu/__main__.py +7 -0
  152. fontTools/qu2cu/benchmark.py +56 -0
  153. fontTools/qu2cu/cli.py +125 -0
  154. fontTools/qu2cu/qu2cu.c +16752 -0
  155. fontTools/qu2cu/qu2cu.cp314-win32.pyd +0 -0
  156. fontTools/qu2cu/qu2cu.py +405 -0
  157. fontTools/subset/__init__.py +3929 -0
  158. fontTools/subset/__main__.py +6 -0
  159. fontTools/subset/cff.py +184 -0
  160. fontTools/subset/svg.py +253 -0
  161. fontTools/subset/util.py +25 -0
  162. fontTools/svgLib/__init__.py +3 -0
  163. fontTools/svgLib/path/__init__.py +65 -0
  164. fontTools/svgLib/path/arc.py +154 -0
  165. fontTools/svgLib/path/parser.py +322 -0
  166. fontTools/svgLib/path/shapes.py +183 -0
  167. fontTools/t1Lib/__init__.py +648 -0
  168. fontTools/tfmLib.py +460 -0
  169. fontTools/ttLib/__init__.py +30 -0
  170. fontTools/ttLib/__main__.py +148 -0
  171. fontTools/ttLib/macUtils.py +54 -0
  172. fontTools/ttLib/removeOverlaps.py +393 -0
  173. fontTools/ttLib/reorderGlyphs.py +285 -0
  174. fontTools/ttLib/scaleUpem.py +436 -0
  175. fontTools/ttLib/sfnt.py +661 -0
  176. fontTools/ttLib/standardGlyphOrder.py +271 -0
  177. fontTools/ttLib/tables/B_A_S_E_.py +14 -0
  178. fontTools/ttLib/tables/BitmapGlyphMetrics.py +64 -0
  179. fontTools/ttLib/tables/C_B_D_T_.py +113 -0
  180. fontTools/ttLib/tables/C_B_L_C_.py +19 -0
  181. fontTools/ttLib/tables/C_F_F_.py +61 -0
  182. fontTools/ttLib/tables/C_F_F__2.py +26 -0
  183. fontTools/ttLib/tables/C_O_L_R_.py +165 -0
  184. fontTools/ttLib/tables/C_P_A_L_.py +305 -0
  185. fontTools/ttLib/tables/D_S_I_G_.py +158 -0
  186. fontTools/ttLib/tables/D__e_b_g.py +35 -0
  187. fontTools/ttLib/tables/DefaultTable.py +49 -0
  188. fontTools/ttLib/tables/E_B_D_T_.py +835 -0
  189. fontTools/ttLib/tables/E_B_L_C_.py +718 -0
  190. fontTools/ttLib/tables/F_F_T_M_.py +52 -0
  191. fontTools/ttLib/tables/F__e_a_t.py +149 -0
  192. fontTools/ttLib/tables/G_D_E_F_.py +13 -0
  193. fontTools/ttLib/tables/G_M_A_P_.py +148 -0
  194. fontTools/ttLib/tables/G_P_K_G_.py +133 -0
  195. fontTools/ttLib/tables/G_P_O_S_.py +14 -0
  196. fontTools/ttLib/tables/G_S_U_B_.py +13 -0
  197. fontTools/ttLib/tables/G_V_A_R_.py +5 -0
  198. fontTools/ttLib/tables/G__l_a_t.py +235 -0
  199. fontTools/ttLib/tables/G__l_o_c.py +85 -0
  200. fontTools/ttLib/tables/H_V_A_R_.py +13 -0
  201. fontTools/ttLib/tables/J_S_T_F_.py +13 -0
  202. fontTools/ttLib/tables/L_T_S_H_.py +58 -0
  203. fontTools/ttLib/tables/M_A_T_H_.py +13 -0
  204. fontTools/ttLib/tables/M_E_T_A_.py +352 -0
  205. fontTools/ttLib/tables/M_V_A_R_.py +13 -0
  206. fontTools/ttLib/tables/O_S_2f_2.py +752 -0
  207. fontTools/ttLib/tables/S_I_N_G_.py +99 -0
  208. fontTools/ttLib/tables/S_T_A_T_.py +15 -0
  209. fontTools/ttLib/tables/S_V_G_.py +223 -0
  210. fontTools/ttLib/tables/S__i_l_f.py +1040 -0
  211. fontTools/ttLib/tables/S__i_l_l.py +92 -0
  212. fontTools/ttLib/tables/T_S_I_B_.py +13 -0
  213. fontTools/ttLib/tables/T_S_I_C_.py +14 -0
  214. fontTools/ttLib/tables/T_S_I_D_.py +13 -0
  215. fontTools/ttLib/tables/T_S_I_J_.py +13 -0
  216. fontTools/ttLib/tables/T_S_I_P_.py +13 -0
  217. fontTools/ttLib/tables/T_S_I_S_.py +13 -0
  218. fontTools/ttLib/tables/T_S_I_V_.py +26 -0
  219. fontTools/ttLib/tables/T_S_I__0.py +70 -0
  220. fontTools/ttLib/tables/T_S_I__1.py +163 -0
  221. fontTools/ttLib/tables/T_S_I__2.py +17 -0
  222. fontTools/ttLib/tables/T_S_I__3.py +22 -0
  223. fontTools/ttLib/tables/T_S_I__5.py +60 -0
  224. fontTools/ttLib/tables/T_T_F_A_.py +14 -0
  225. fontTools/ttLib/tables/TupleVariation.py +884 -0
  226. fontTools/ttLib/tables/V_A_R_C_.py +12 -0
  227. fontTools/ttLib/tables/V_D_M_X_.py +249 -0
  228. fontTools/ttLib/tables/V_O_R_G_.py +165 -0
  229. fontTools/ttLib/tables/V_V_A_R_.py +13 -0
  230. fontTools/ttLib/tables/__init__.py +98 -0
  231. fontTools/ttLib/tables/_a_n_k_r.py +15 -0
  232. fontTools/ttLib/tables/_a_v_a_r.py +191 -0
  233. fontTools/ttLib/tables/_b_s_l_n.py +15 -0
  234. fontTools/ttLib/tables/_c_i_d_g.py +24 -0
  235. fontTools/ttLib/tables/_c_m_a_p.py +1591 -0
  236. fontTools/ttLib/tables/_c_v_a_r.py +94 -0
  237. fontTools/ttLib/tables/_c_v_t.py +56 -0
  238. fontTools/ttLib/tables/_f_e_a_t.py +15 -0
  239. fontTools/ttLib/tables/_f_p_g_m.py +62 -0
  240. fontTools/ttLib/tables/_f_v_a_r.py +261 -0
  241. fontTools/ttLib/tables/_g_a_s_p.py +63 -0
  242. fontTools/ttLib/tables/_g_c_i_d.py +13 -0
  243. fontTools/ttLib/tables/_g_l_y_f.py +2311 -0
  244. fontTools/ttLib/tables/_g_v_a_r.py +340 -0
  245. fontTools/ttLib/tables/_h_d_m_x.py +127 -0
  246. fontTools/ttLib/tables/_h_e_a_d.py +130 -0
  247. fontTools/ttLib/tables/_h_h_e_a.py +147 -0
  248. fontTools/ttLib/tables/_h_m_t_x.py +164 -0
  249. fontTools/ttLib/tables/_k_e_r_n.py +289 -0
  250. fontTools/ttLib/tables/_l_c_a_r.py +13 -0
  251. fontTools/ttLib/tables/_l_o_c_a.py +70 -0
  252. fontTools/ttLib/tables/_l_t_a_g.py +72 -0
  253. fontTools/ttLib/tables/_m_a_x_p.py +147 -0
  254. fontTools/ttLib/tables/_m_e_t_a.py +112 -0
  255. fontTools/ttLib/tables/_m_o_r_t.py +14 -0
  256. fontTools/ttLib/tables/_m_o_r_x.py +15 -0
  257. fontTools/ttLib/tables/_n_a_m_e.py +1237 -0
  258. fontTools/ttLib/tables/_o_p_b_d.py +14 -0
  259. fontTools/ttLib/tables/_p_o_s_t.py +319 -0
  260. fontTools/ttLib/tables/_p_r_e_p.py +16 -0
  261. fontTools/ttLib/tables/_p_r_o_p.py +12 -0
  262. fontTools/ttLib/tables/_s_b_i_x.py +129 -0
  263. fontTools/ttLib/tables/_t_r_a_k.py +332 -0
  264. fontTools/ttLib/tables/_v_h_e_a.py +139 -0
  265. fontTools/ttLib/tables/_v_m_t_x.py +19 -0
  266. fontTools/ttLib/tables/asciiTable.py +20 -0
  267. fontTools/ttLib/tables/grUtils.py +92 -0
  268. fontTools/ttLib/tables/otBase.py +1464 -0
  269. fontTools/ttLib/tables/otConverters.py +2068 -0
  270. fontTools/ttLib/tables/otData.py +6400 -0
  271. fontTools/ttLib/tables/otTables.py +2703 -0
  272. fontTools/ttLib/tables/otTraverse.py +163 -0
  273. fontTools/ttLib/tables/sbixGlyph.py +149 -0
  274. fontTools/ttLib/tables/sbixStrike.py +177 -0
  275. fontTools/ttLib/tables/table_API_readme.txt +91 -0
  276. fontTools/ttLib/tables/ttProgram.py +594 -0
  277. fontTools/ttLib/ttCollection.py +125 -0
  278. fontTools/ttLib/ttFont.py +1148 -0
  279. fontTools/ttLib/ttGlyphSet.py +490 -0
  280. fontTools/ttLib/ttVisitor.py +32 -0
  281. fontTools/ttLib/woff2.py +1680 -0
  282. fontTools/ttx.py +479 -0
  283. fontTools/ufoLib/__init__.py +2472 -0
  284. fontTools/ufoLib/converters.py +398 -0
  285. fontTools/ufoLib/errors.py +30 -0
  286. fontTools/ufoLib/etree.py +6 -0
  287. fontTools/ufoLib/filenames.py +346 -0
  288. fontTools/ufoLib/glifLib.py +2024 -0
  289. fontTools/ufoLib/kerning.py +121 -0
  290. fontTools/ufoLib/plistlib.py +47 -0
  291. fontTools/ufoLib/pointPen.py +6 -0
  292. fontTools/ufoLib/utils.py +79 -0
  293. fontTools/ufoLib/validators.py +1184 -0
  294. fontTools/unicode.py +50 -0
  295. fontTools/unicodedata/Blocks.py +801 -0
  296. fontTools/unicodedata/Mirrored.py +446 -0
  297. fontTools/unicodedata/OTTags.py +50 -0
  298. fontTools/unicodedata/ScriptExtensions.py +826 -0
  299. fontTools/unicodedata/Scripts.py +3617 -0
  300. fontTools/unicodedata/__init__.py +304 -0
  301. fontTools/varLib/__init__.py +1517 -0
  302. fontTools/varLib/__main__.py +6 -0
  303. fontTools/varLib/avar.py +260 -0
  304. fontTools/varLib/avarPlanner.py +1004 -0
  305. fontTools/varLib/builder.py +215 -0
  306. fontTools/varLib/cff.py +631 -0
  307. fontTools/varLib/errors.py +219 -0
  308. fontTools/varLib/featureVars.py +703 -0
  309. fontTools/varLib/hvar.py +113 -0
  310. fontTools/varLib/instancer/__init__.py +2014 -0
  311. fontTools/varLib/instancer/__main__.py +5 -0
  312. fontTools/varLib/instancer/featureVars.py +190 -0
  313. fontTools/varLib/instancer/names.py +388 -0
  314. fontTools/varLib/instancer/solver.py +309 -0
  315. fontTools/varLib/interpolatable.py +1209 -0
  316. fontTools/varLib/interpolatableHelpers.py +396 -0
  317. fontTools/varLib/interpolatablePlot.py +1269 -0
  318. fontTools/varLib/interpolatableTestContourOrder.py +82 -0
  319. fontTools/varLib/interpolatableTestStartingPoint.py +107 -0
  320. fontTools/varLib/interpolate_layout.py +124 -0
  321. fontTools/varLib/iup.c +19844 -0
  322. fontTools/varLib/iup.cp314-win32.pyd +0 -0
  323. fontTools/varLib/iup.py +490 -0
  324. fontTools/varLib/merger.py +1717 -0
  325. fontTools/varLib/models.py +642 -0
  326. fontTools/varLib/multiVarStore.py +253 -0
  327. fontTools/varLib/mutator.py +529 -0
  328. fontTools/varLib/mvar.py +40 -0
  329. fontTools/varLib/plot.py +238 -0
  330. fontTools/varLib/stat.py +149 -0
  331. fontTools/varLib/varStore.py +739 -0
  332. fontTools/voltLib/__init__.py +5 -0
  333. fontTools/voltLib/__main__.py +206 -0
  334. fontTools/voltLib/ast.py +452 -0
  335. fontTools/voltLib/error.py +12 -0
  336. fontTools/voltLib/lexer.py +99 -0
  337. fontTools/voltLib/parser.py +664 -0
  338. fontTools/voltLib/voltToFea.py +911 -0
  339. fonttools-4.59.1.data/data/share/man/man1/ttx.1 +225 -0
  340. fonttools-4.59.1.dist-info/METADATA +2175 -0
  341. fonttools-4.59.1.dist-info/RECORD +346 -0
  342. fonttools-4.59.1.dist-info/WHEEL +5 -0
  343. fonttools-4.59.1.dist-info/entry_points.txt +5 -0
  344. fonttools-4.59.1.dist-info/licenses/LICENSE +21 -0
  345. fonttools-4.59.1.dist-info/licenses/LICENSE.external +388 -0
  346. fonttools-4.59.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3929 @@
1
+ # Copyright 2013 Google, Inc. All Rights Reserved.
2
+ #
3
+ # Google Author(s): Behdad Esfahbod
4
+
5
+ from __future__ import annotations
6
+
7
+ from fontTools import config
8
+ from fontTools.misc.roundTools import otRound
9
+ from fontTools import ttLib
10
+ from fontTools.ttLib.tables import otTables
11
+ from fontTools.ttLib.tables.otBase import USE_HARFBUZZ_REPACKER
12
+ from fontTools.otlLib.maxContextCalc import maxCtxFont
13
+ from fontTools.pens.basePen import NullPen
14
+ from fontTools.misc.loggingTools import Timer
15
+ from fontTools.misc.cliTools import makeOutputFileName
16
+ from fontTools.subset.util import _add_method, _uniq_sort
17
+ from fontTools.subset.cff import *
18
+ from fontTools.subset.svg import *
19
+ from fontTools.varLib import varStore, multiVarStore # For monkey-patching
20
+ from fontTools.ttLib.tables._n_a_m_e import NameRecordVisitor, makeName
21
+ from fontTools.unicodedata import mirrored
22
+ import sys
23
+ import struct
24
+ import array
25
+ import logging
26
+ from collections import Counter, defaultdict
27
+ from functools import reduce
28
+ from types import MethodType
29
+
30
+ __usage__ = "fonttools subset font-file [glyph...] [--option=value]..."
31
+
32
+ __doc__ = (
33
+ """\
34
+ fonttools subset -- OpenType font subsetter and optimizer
35
+
36
+ fonttools subset is an OpenType font subsetter and optimizer, based on
37
+ fontTools. It accepts any TT- or CFF-flavored OpenType (.otf or .ttf)
38
+ or WOFF (.woff) font file. The subsetted glyph set is based on the
39
+ specified glyphs or characters, and specified OpenType layout features.
40
+
41
+ The tool also performs some size-reducing optimizations, aimed for using
42
+ subset fonts as webfonts. Individual optimizations can be enabled or
43
+ disabled, and are enabled by default when they are safe.
44
+
45
+ Usage: """
46
+ + __usage__
47
+ + """
48
+
49
+ At least one glyph or one of --gids, --gids-file, --glyphs, --glyphs-file,
50
+ --text, --text-file, --unicodes, or --unicodes-file, must be specified.
51
+
52
+ Args:
53
+
54
+ font-file
55
+ The input font file.
56
+ glyph
57
+ Specify one or more glyph identifiers to include in the subset. Must be
58
+ PS glyph names, or the special string '*' to keep the entire glyph set.
59
+
60
+ Initial glyph set specification
61
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
62
+
63
+ These options populate the initial glyph set. Same option can appear
64
+ multiple times, and the results are accummulated.
65
+
66
+ --gids=<NNN>[,<NNN>...]
67
+ Specify comma/whitespace-separated list of glyph IDs or ranges as decimal
68
+ numbers. For example, --gids=10-12,14 adds glyphs with numbers 10, 11,
69
+ 12, and 14.
70
+
71
+ --gids-file=<path>
72
+ Like --gids but reads from a file. Anything after a '#' on any line is
73
+ ignored as comments.
74
+
75
+ --glyphs=<glyphname>[,<glyphname>...]
76
+ Specify comma/whitespace-separated PS glyph names to add to the subset.
77
+ Note that only PS glyph names are accepted, not gidNNN, U+XXXX, etc
78
+ that are accepted on the command line. The special string '*' will keep
79
+ the entire glyph set.
80
+
81
+ --glyphs-file=<path>
82
+ Like --glyphs but reads from a file. Anything after a '#' on any line
83
+ is ignored as comments.
84
+
85
+ --text=<text>
86
+ Specify characters to include in the subset, as UTF-8 string.
87
+
88
+ --text-file=<path>
89
+ Like --text but reads from a file. Newline character are not added to
90
+ the subset.
91
+
92
+ --unicodes=<XXXX>[,<XXXX>...]
93
+ Specify comma/whitespace-separated list of Unicode codepoints or
94
+ ranges as hex numbers, optionally prefixed with 'U+', 'u', etc.
95
+ For example, --unicodes=41-5a,61-7a adds ASCII letters, so does
96
+ the more verbose --unicodes=U+0041-005A,U+0061-007A.
97
+ The special strings '*' will choose all Unicode characters mapped
98
+ by the font.
99
+
100
+ --unicodes-file=<path>
101
+ Like --unicodes, but reads from a file. Anything after a '#' on any
102
+ line in the file is ignored as comments.
103
+
104
+ --ignore-missing-glyphs
105
+ Do not fail if some requested glyphs or gids are not available in
106
+ the font.
107
+
108
+ --no-ignore-missing-glyphs
109
+ Stop and fail if some requested glyphs or gids are not available
110
+ in the font. [default]
111
+
112
+ --ignore-missing-unicodes [default]
113
+ Do not fail if some requested Unicode characters (including those
114
+ indirectly specified using --text or --text-file) are not available
115
+ in the font.
116
+
117
+ --no-ignore-missing-unicodes
118
+ Stop and fail if some requested Unicode characters are not available
119
+ in the font.
120
+ Note the default discrepancy between ignoring missing glyphs versus
121
+ unicodes. This is for historical reasons and in the future
122
+ --no-ignore-missing-unicodes might become default.
123
+
124
+ Other options
125
+ ^^^^^^^^^^^^^
126
+
127
+ For the other options listed below, to see the current value of the option,
128
+ pass a value of '?' to it, with or without a '='. In some environments,
129
+ you might need to escape the question mark, like this: '--glyph-names\\?'.
130
+
131
+ Examples::
132
+
133
+ $ fonttools subset --glyph-names?
134
+ Current setting for 'glyph-names' is: False
135
+ $ fonttools subset --name-IDs=?
136
+ Current setting for 'name-IDs' is: [0, 1, 2, 3, 4, 5, 6]
137
+ $ fonttools subset --hinting? --no-hinting --hinting?
138
+ Current setting for 'hinting' is: True
139
+ Current setting for 'hinting' is: False
140
+
141
+ Output options
142
+ ^^^^^^^^^^^^^^
143
+
144
+ --output-file=<path>
145
+ The output font file. If not specified, the subsetted font
146
+ will be saved in as font-file.subset.
147
+
148
+ --flavor=<type>
149
+ Specify flavor of output font file. May be 'woff' or 'woff2'.
150
+ Note that WOFF2 requires the Brotli Python extension, available
151
+ at https://github.com/google/brotli
152
+
153
+ --with-zopfli
154
+ Use the Google Zopfli algorithm to compress WOFF. The output is 3-8 %
155
+ smaller than pure zlib, but the compression speed is much slower.
156
+ The Zopfli Python bindings are available at:
157
+ https://pypi.python.org/pypi/zopfli
158
+
159
+ --harfbuzz-repacker
160
+ By default, we serialize GPOS/GSUB using the HarfBuzz Repacker when
161
+ uharfbuzz can be imported and is successful, otherwise fall back to
162
+ the pure-python serializer. Set the option to force using the HarfBuzz
163
+ Repacker (raises an error if uharfbuzz can't be found or fails).
164
+
165
+ --no-harfbuzz-repacker
166
+ Always use the pure-python serializer even if uharfbuzz is available.
167
+
168
+ Glyph set expansion
169
+ ^^^^^^^^^^^^^^^^^^^
170
+
171
+ These options control how additional glyphs are added to the subset.
172
+
173
+ --retain-gids
174
+ Retain glyph indices; just empty glyphs not needed in-place.
175
+
176
+ --notdef-glyph
177
+ Add the '.notdef' glyph to the subset (ie, keep it). [default]
178
+
179
+ --no-notdef-glyph
180
+ Drop the '.notdef' glyph unless specified in the glyph set. This
181
+ saves a few bytes, but is not possible for Postscript-flavored
182
+ fonts, as those require '.notdef'. For TrueType-flavored fonts,
183
+ this works fine as long as no unsupported glyphs are requested
184
+ from the font.
185
+
186
+ --notdef-outline
187
+ Keep the outline of '.notdef' glyph. The '.notdef' glyph outline is
188
+ used when glyphs not supported by the font are to be shown. It is not
189
+ needed otherwise.
190
+
191
+ --no-notdef-outline
192
+ When including a '.notdef' glyph, remove its outline. This saves
193
+ a few bytes. [default]
194
+
195
+ --recommended-glyphs
196
+ Add glyphs 0, 1, 2, and 3 to the subset, as recommended for
197
+ TrueType-flavored fonts: '.notdef', 'NULL' or '.null', 'CR', 'space'.
198
+ Some legacy software might require this, but no modern system does.
199
+
200
+ --no-recommended-glyphs
201
+ Do not add glyphs 0, 1, 2, and 3 to the subset, unless specified in
202
+ glyph set. [default]
203
+
204
+ --no-layout-closure
205
+ Do not expand glyph set to add glyphs produced by OpenType layout
206
+ features. Instead, OpenType layout features will be subset to only
207
+ rules that are relevant to the otherwise-specified glyph set.
208
+
209
+ --layout-features[+|-]=<feature>[,<feature>...]
210
+ Specify (=), add to (+=) or exclude from (-=) the comma-separated
211
+ set of OpenType layout feature tags that will be preserved.
212
+ Glyph variants used by the preserved features are added to the
213
+ specified subset glyph set. By default, 'calt', 'ccmp', 'clig', 'curs',
214
+ 'dnom', 'frac', 'kern', 'liga', 'locl', 'mark', 'mkmk', 'numr', 'rclt',
215
+ 'rlig', 'rvrn', and all features required for script shaping are
216
+ preserved. To see the full list, try '--layout-features=?'.
217
+ Use '*' to keep all features.
218
+ Multiple --layout-features options can be provided if necessary.
219
+ Examples:
220
+
221
+ --layout-features+=onum,pnum,ss01
222
+ * Keep the default set of features and 'onum', 'pnum', 'ss01'.
223
+ --layout-features-='mark','mkmk'
224
+ * Keep the default set of features but drop 'mark' and 'mkmk'.
225
+ --layout-features='kern'
226
+ * Only keep the 'kern' feature, drop all others.
227
+ --layout-features=''
228
+ * Drop all features.
229
+ --layout-features='*'
230
+ * Keep all features.
231
+ --layout-features+=aalt --layout-features-=vrt2
232
+ * Keep default set of features plus 'aalt', but drop 'vrt2'.
233
+
234
+ --layout-scripts[+|-]=<script>[,<script>...]
235
+ Specify (=), add to (+=) or exclude from (-=) the comma-separated
236
+ set of OpenType layout script tags that will be preserved. LangSys tags
237
+ can be appended to script tag, separated by '.', for example:
238
+ 'arab.dflt,arab.URD,latn.TRK'. By default all scripts are retained ('*').
239
+
240
+ Hinting options
241
+ ^^^^^^^^^^^^^^^
242
+
243
+ --hinting
244
+ Keep hinting [default]
245
+
246
+ --no-hinting
247
+ Drop glyph-specific hinting and font-wide hinting tables, as well
248
+ as remove hinting-related bits and pieces from other tables (eg. GPOS).
249
+ See --hinting-tables for list of tables that are dropped by default.
250
+ Instructions and hints are stripped from 'glyf' and 'CFF ' tables
251
+ respectively. This produces (sometimes up to 30%) smaller fonts that
252
+ are suitable for extremely high-resolution systems, like high-end
253
+ mobile devices and retina displays.
254
+
255
+ Optimization options
256
+ ^^^^^^^^^^^^^^^^^^^^
257
+
258
+ --desubroutinize
259
+ Remove CFF use of subroutinizes. Subroutinization is a way to make CFF
260
+ fonts smaller. For small subsets however, desubroutinizing might make
261
+ the font smaller. It has even been reported that desubroutinized CFF
262
+ fonts compress better (produce smaller output) WOFF and WOFF2 fonts.
263
+ Also see note under --no-hinting.
264
+
265
+ --no-desubroutinize [default]
266
+ Leave CFF subroutinizes as is, only throw away unused subroutinizes.
267
+
268
+ Font table options
269
+ ^^^^^^^^^^^^^^^^^^
270
+
271
+ --drop-tables[+|-]=<table>[,<table>...]
272
+ Specify (=), add to (+=) or exclude from (-=) the comma-separated
273
+ set of tables that will be be dropped.
274
+ By default, the following tables are dropped:
275
+ 'BASE', 'JSTF', 'DSIG', 'EBDT', 'EBLC', 'EBSC', 'PCLT', 'LTSH'
276
+ and Graphite tables: 'Feat', 'Glat', 'Gloc', 'Silf', 'Sill'.
277
+ The tool will attempt to subset the remaining tables.
278
+
279
+ Examples:
280
+
281
+ --drop-tables-=BASE
282
+ * Drop the default set of tables but keep 'BASE'.
283
+
284
+ --drop-tables+=GSUB
285
+ * Drop the default set of tables and 'GSUB'.
286
+
287
+ --drop-tables=DSIG
288
+ * Only drop the 'DSIG' table, keep all others.
289
+
290
+ --drop-tables=
291
+ * Keep all tables.
292
+
293
+ --no-subset-tables+=<table>[,<table>...]
294
+ Add to the set of tables that will not be subsetted.
295
+ By default, the following tables are included in this list, as
296
+ they do not need subsetting (ignore the fact that 'loca' is listed
297
+ here): 'gasp', 'head', 'hhea', 'maxp', 'vhea', 'OS/2', 'loca', 'name',
298
+ 'cvt ', 'fpgm', 'prep', 'VMDX', 'DSIG', 'CPAL', 'MVAR', 'cvar', 'STAT'.
299
+ By default, tables that the tool does not know how to subset and are not
300
+ specified here will be dropped from the font, unless --passthrough-tables
301
+ option is passed.
302
+
303
+ Example:
304
+
305
+ --no-subset-tables+=FFTM
306
+ * Keep 'FFTM' table in the font by preventing subsetting.
307
+
308
+ --passthrough-tables
309
+ Do not drop tables that the tool does not know how to subset.
310
+
311
+ --no-passthrough-tables
312
+ Tables that the tool does not know how to subset and are not specified
313
+ in --no-subset-tables will be dropped from the font. [default]
314
+
315
+ --hinting-tables[-]=<table>[,<table>...]
316
+ Specify (=), add to (+=) or exclude from (-=) the list of font-wide
317
+ hinting tables that will be dropped if --no-hinting is specified.
318
+
319
+ Examples:
320
+
321
+ --hinting-tables-=VDMX
322
+ * Drop font-wide hinting tables except 'VDMX'.
323
+ --hinting-tables=
324
+ * Keep all font-wide hinting tables (but strip hints from glyphs).
325
+
326
+ --legacy-kern
327
+ Keep TrueType 'kern' table even when OpenType 'GPOS' is available.
328
+
329
+ --no-legacy-kern
330
+ Drop TrueType 'kern' table if OpenType 'GPOS' is available. [default]
331
+
332
+ Font naming options
333
+ ^^^^^^^^^^^^^^^^^^^
334
+
335
+ These options control what is retained in the 'name' table. For numerical
336
+ codes, see: http://www.microsoft.com/typography/otspec/name.htm
337
+
338
+ --name-IDs[+|-]=<nameID>[,<nameID>...]
339
+ Specify (=), add to (+=) or exclude from (-=) the set of 'name' table
340
+ entry nameIDs that will be preserved. By default, only nameIDs between 0
341
+ and 6 are preserved, the rest are dropped. Use '*' to keep all entries.
342
+
343
+ Examples:
344
+
345
+ --name-IDs+=7,8,9
346
+ * Also keep Trademark, Manufacturer and Designer name entries.
347
+ --name-IDs=
348
+ * Drop all 'name' table entries.
349
+ --name-IDs=*
350
+ * keep all 'name' table entries
351
+
352
+ --name-legacy
353
+ Keep legacy (non-Unicode) 'name' table entries (0.x, 1.x etc.).
354
+ XXX Note: This might be needed for some fonts that have no Unicode name
355
+ entires for English. See: https://github.com/fonttools/fonttools/issues/146
356
+
357
+ --no-name-legacy
358
+ Drop legacy (non-Unicode) 'name' table entries [default]
359
+
360
+ --name-languages[+|-]=<langID>[,<langID>]
361
+ Specify (=), add to (+=) or exclude from (-=) the set of 'name' table
362
+ langIDs that will be preserved. By default only records with langID
363
+ 0x0409 (English) are preserved. Use '*' to keep all langIDs.
364
+
365
+ --obfuscate-names
366
+ Make the font unusable as a system font by replacing name IDs 1, 2, 3, 4,
367
+ and 6 with dummy strings (it is still fully functional as webfont).
368
+
369
+ Glyph naming and encoding options
370
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
371
+
372
+ --glyph-names
373
+ Keep PS glyph names in TT-flavored fonts. In general glyph names are
374
+ not needed for correct use of the font. However, some PDF generators
375
+ and PDF viewers might rely on glyph names to extract Unicode text
376
+ from PDF documents.
377
+ --no-glyph-names
378
+ Drop PS glyph names in TT-flavored fonts, by using 'post' table
379
+ version 3.0. [default]
380
+ --legacy-cmap
381
+ Keep the legacy 'cmap' subtables (0.x, 1.x, 4.x etc.).
382
+ --no-legacy-cmap
383
+ Drop the legacy 'cmap' subtables. [default]
384
+ --symbol-cmap
385
+ Keep the 3.0 symbol 'cmap'.
386
+ --no-symbol-cmap
387
+ Drop the 3.0 symbol 'cmap'. [default]
388
+
389
+ Other font-specific options
390
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
391
+
392
+ --recalc-bounds
393
+ Recalculate font bounding boxes.
394
+ --no-recalc-bounds
395
+ Keep original font bounding boxes. This is faster and still safe
396
+ for all practical purposes. [default]
397
+ --recalc-timestamp
398
+ Set font 'modified' timestamp to current time.
399
+ --no-recalc-timestamp
400
+ Do not modify font 'modified' timestamp. [default]
401
+ --canonical-order
402
+ Order tables as recommended in the OpenType standard. This is not
403
+ required by the standard, nor by any known implementation.
404
+ --no-canonical-order
405
+ Keep original order of font tables. This is faster. [default]
406
+ --prune-unicode-ranges
407
+ Update the 'OS/2 ulUnicodeRange*' bits after subsetting. The Unicode
408
+ ranges defined in the OpenType specification v1.7 are intersected with
409
+ the Unicode codepoints specified in the font's Unicode 'cmap' subtables:
410
+ when no overlap is found, the bit will be switched off. However, it will
411
+ *not* be switched on if an intersection is found. [default]
412
+ --no-prune-unicode-ranges
413
+ Don't change the 'OS/2 ulUnicodeRange*' bits.
414
+ --prune-codepage-ranges
415
+ Update the 'OS/2 ulCodePageRange*' bits after subsetting. [default]
416
+ --no-prune-codepage-ranges
417
+ Don't change the 'OS/2 ulCodePageRange*' bits.
418
+ --recalc-average-width
419
+ Update the 'OS/2 xAvgCharWidth' field after subsetting.
420
+ --no-recalc-average-width
421
+ Don't change the 'OS/2 xAvgCharWidth' field. [default]
422
+ --recalc-max-context
423
+ Update the 'OS/2 usMaxContext' field after subsetting.
424
+ --no-recalc-max-context
425
+ Don't change the 'OS/2 usMaxContext' field. [default]
426
+ --font-number=<number>
427
+ Select font number for TrueType Collection (.ttc/.otc), starting from 0.
428
+ --pretty-svg
429
+ When subsetting SVG table, use lxml pretty_print=True option to indent
430
+ the XML output (only recommended for debugging purposes).
431
+
432
+ Application options
433
+ ^^^^^^^^^^^^^^^^^^^
434
+
435
+ --verbose
436
+ Display verbose information of the subsetting process.
437
+ --timing
438
+ Display detailed timing information of the subsetting process.
439
+ --xml
440
+ Display the TTX XML representation of subsetted font.
441
+
442
+ Example
443
+ ^^^^^^^
444
+
445
+ Produce a subset containing the characters ' !"#$%' without performing
446
+ size-reducing optimizations::
447
+
448
+ $ fonttools subset font.ttf --unicodes="U+0020-0025" \\
449
+ --layout-features=* --glyph-names --symbol-cmap --legacy-cmap \\
450
+ --notdef-glyph --notdef-outline --recommended-glyphs \\
451
+ --name-IDs=* --name-legacy --name-languages=*
452
+ """
453
+ )
454
+
455
+
456
+ log = logging.getLogger("fontTools.subset")
457
+
458
+
459
+ def _log_glyphs(self, glyphs, font=None):
460
+ self.info("Glyph names: %s", sorted(glyphs))
461
+ if font:
462
+ reverseGlyphMap = font.getReverseGlyphMap()
463
+ self.info("Glyph IDs: %s", sorted(reverseGlyphMap[g] for g in glyphs))
464
+
465
+
466
+ # bind "glyphs" function to 'log' object
467
+ log.glyphs = MethodType(_log_glyphs, log)
468
+
469
+ # I use a different timing channel so I can configure it separately from the
470
+ # main module's logger
471
+ timer = Timer(logger=logging.getLogger("fontTools.subset.timer"))
472
+
473
+
474
+ def _dict_subset(d, glyphs):
475
+ return {g: d[g] for g in glyphs}
476
+
477
+
478
+ def _list_subset(l, indices):
479
+ count = len(l)
480
+ return [l[i] for i in indices if i < count]
481
+
482
+
483
+ @_add_method(otTables.Coverage)
484
+ def intersect(self, glyphs):
485
+ """Returns ascending list of matching coverage values."""
486
+ return [i for i, g in enumerate(self.glyphs) if g in glyphs]
487
+
488
+
489
+ @_add_method(otTables.Coverage)
490
+ def intersect_glyphs(self, glyphs):
491
+ """Returns set of intersecting glyphs."""
492
+ return set(g for g in self.glyphs if g in glyphs)
493
+
494
+
495
+ @_add_method(otTables.Coverage)
496
+ def subset(self, glyphs):
497
+ """Returns ascending list of remaining coverage values."""
498
+ indices = self.intersect(glyphs)
499
+ self.glyphs = [g for g in self.glyphs if g in glyphs]
500
+ return indices
501
+
502
+
503
+ @_add_method(otTables.Coverage)
504
+ def remap(self, coverage_map):
505
+ """Remaps coverage."""
506
+ self.glyphs = [self.glyphs[i] for i in coverage_map]
507
+
508
+
509
+ @_add_method(otTables.ClassDef)
510
+ def intersect(self, glyphs):
511
+ """Returns ascending list of matching class values."""
512
+ return _uniq_sort(
513
+ ([0] if any(g not in self.classDefs for g in glyphs) else [])
514
+ + [v for g, v in self.classDefs.items() if g in glyphs]
515
+ )
516
+
517
+
518
+ @_add_method(otTables.ClassDef)
519
+ def intersect_class(self, glyphs, klass):
520
+ """Returns set of glyphs matching class."""
521
+ if klass == 0:
522
+ return set(g for g in glyphs if g not in self.classDefs)
523
+ return set(g for g, v in self.classDefs.items() if v == klass and g in glyphs)
524
+
525
+
526
+ @_add_method(otTables.ClassDef)
527
+ def subset(self, glyphs, remap=False, useClass0=True):
528
+ """Returns ascending list of remaining classes."""
529
+ self.classDefs = {g: v for g, v in self.classDefs.items() if g in glyphs}
530
+ # Note: while class 0 has the special meaning of "not matched",
531
+ # if no glyph will ever /not match/, we can optimize class 0 out too.
532
+ # Only do this if allowed.
533
+ indices = _uniq_sort(
534
+ (
535
+ [0]
536
+ if ((not useClass0) or any(g not in self.classDefs for g in glyphs))
537
+ else []
538
+ )
539
+ + list(self.classDefs.values())
540
+ )
541
+ if remap:
542
+ self.remap(indices)
543
+ return indices
544
+
545
+
546
+ @_add_method(otTables.ClassDef)
547
+ def remap(self, class_map):
548
+ """Remaps classes."""
549
+ self.classDefs = {g: class_map.index(v) for g, v in self.classDefs.items()}
550
+
551
+
552
+ @_add_method(otTables.SingleSubst)
553
+ def closure_glyphs(self, s, cur_glyphs):
554
+ s.glyphs.update(v for g, v in self.mapping.items() if g in cur_glyphs)
555
+
556
+
557
+ @_add_method(otTables.SingleSubst)
558
+ def subset_glyphs(self, s):
559
+ self.mapping = {
560
+ g: v for g, v in self.mapping.items() if g in s.glyphs and v in s.glyphs
561
+ }
562
+ return bool(self.mapping)
563
+
564
+
565
+ @_add_method(otTables.MultipleSubst)
566
+ def closure_glyphs(self, s, cur_glyphs):
567
+ for glyph, subst in self.mapping.items():
568
+ if glyph in cur_glyphs:
569
+ s.glyphs.update(subst)
570
+
571
+
572
+ @_add_method(otTables.MultipleSubst)
573
+ def subset_glyphs(self, s):
574
+ self.mapping = {
575
+ g: v
576
+ for g, v in self.mapping.items()
577
+ if g in s.glyphs and all(sub in s.glyphs for sub in v)
578
+ }
579
+ return bool(self.mapping)
580
+
581
+
582
+ @_add_method(otTables.AlternateSubst)
583
+ def closure_glyphs(self, s, cur_glyphs):
584
+ s.glyphs.update(*(vlist for g, vlist in self.alternates.items() if g in cur_glyphs))
585
+
586
+
587
+ @_add_method(otTables.AlternateSubst)
588
+ def subset_glyphs(self, s):
589
+ self.alternates = {
590
+ g: [v for v in vlist if v in s.glyphs]
591
+ for g, vlist in self.alternates.items()
592
+ if g in s.glyphs and any(v in s.glyphs for v in vlist)
593
+ }
594
+ return bool(self.alternates)
595
+
596
+
597
+ @_add_method(otTables.LigatureSubst)
598
+ def closure_glyphs(self, s, cur_glyphs):
599
+ s.glyphs.update(
600
+ *(
601
+ [seq.LigGlyph for seq in seqs if all(c in s.glyphs for c in seq.Component)]
602
+ for g, seqs in self.ligatures.items()
603
+ if g in cur_glyphs
604
+ )
605
+ )
606
+
607
+
608
+ @_add_method(otTables.LigatureSubst)
609
+ def subset_glyphs(self, s):
610
+ self.ligatures = {g: v for g, v in self.ligatures.items() if g in s.glyphs}
611
+ self.ligatures = {
612
+ g: [
613
+ seq
614
+ for seq in seqs
615
+ if seq.LigGlyph in s.glyphs and all(c in s.glyphs for c in seq.Component)
616
+ ]
617
+ for g, seqs in self.ligatures.items()
618
+ }
619
+ self.ligatures = {g: v for g, v in self.ligatures.items() if v}
620
+ return bool(self.ligatures)
621
+
622
+
623
+ @_add_method(otTables.ReverseChainSingleSubst)
624
+ def closure_glyphs(self, s, cur_glyphs):
625
+ if self.Format == 1:
626
+ indices = self.Coverage.intersect(cur_glyphs)
627
+ if not indices or not all(
628
+ c.intersect(s.glyphs)
629
+ for c in self.LookAheadCoverage + self.BacktrackCoverage
630
+ ):
631
+ return
632
+ s.glyphs.update(self.Substitute[i] for i in indices)
633
+ else:
634
+ assert 0, "unknown format: %s" % self.Format
635
+
636
+
637
+ @_add_method(otTables.ReverseChainSingleSubst)
638
+ def subset_glyphs(self, s):
639
+ if self.Format == 1:
640
+ indices = self.Coverage.subset(s.glyphs)
641
+ self.Substitute = _list_subset(self.Substitute, indices)
642
+ # Now drop rules generating glyphs we don't want
643
+ indices = [i for i, sub in enumerate(self.Substitute) if sub in s.glyphs]
644
+ self.Substitute = _list_subset(self.Substitute, indices)
645
+ self.Coverage.remap(indices)
646
+ self.GlyphCount = len(self.Substitute)
647
+ return bool(
648
+ self.GlyphCount
649
+ and all(
650
+ c.subset(s.glyphs)
651
+ for c in self.LookAheadCoverage + self.BacktrackCoverage
652
+ )
653
+ )
654
+ else:
655
+ assert 0, "unknown format: %s" % self.Format
656
+
657
+
658
+ @_add_method(otTables.Device)
659
+ def is_hinting(self):
660
+ return self.DeltaFormat in (1, 2, 3)
661
+
662
+
663
+ @_add_method(otTables.ValueRecord)
664
+ def prune_hints(self):
665
+ for name in ["XPlaDevice", "YPlaDevice", "XAdvDevice", "YAdvDevice"]:
666
+ v = getattr(self, name, None)
667
+ if v is not None and v.is_hinting():
668
+ delattr(self, name)
669
+
670
+
671
+ @_add_method(otTables.SinglePos)
672
+ def subset_glyphs(self, s):
673
+ if self.Format == 1:
674
+ return len(self.Coverage.subset(s.glyphs))
675
+ elif self.Format == 2:
676
+ indices = self.Coverage.subset(s.glyphs)
677
+ values = self.Value
678
+ count = len(values)
679
+ self.Value = [values[i] for i in indices if i < count]
680
+ self.ValueCount = len(self.Value)
681
+ return bool(self.ValueCount)
682
+ else:
683
+ assert 0, "unknown format: %s" % self.Format
684
+
685
+
686
+ @_add_method(otTables.SinglePos)
687
+ def prune_post_subset(self, font, options):
688
+ if self.Value is None:
689
+ assert self.ValueFormat == 0
690
+ return True
691
+
692
+ # Shrink ValueFormat
693
+ if self.Format == 1:
694
+ if not options.hinting:
695
+ self.Value.prune_hints()
696
+ self.ValueFormat = self.Value.getEffectiveFormat()
697
+ elif self.Format == 2:
698
+ if None in self.Value:
699
+ assert self.ValueFormat == 0
700
+ assert all(v is None for v in self.Value)
701
+ else:
702
+ if not options.hinting:
703
+ for v in self.Value:
704
+ v.prune_hints()
705
+ self.ValueFormat = reduce(
706
+ int.__or__, [v.getEffectiveFormat() for v in self.Value], 0
707
+ )
708
+
709
+ # Downgrade to Format 1 if all ValueRecords are the same
710
+ if self.Format == 2 and all(v == self.Value[0] for v in self.Value):
711
+ self.Format = 1
712
+ self.Value = self.Value[0] if self.ValueFormat != 0 else None
713
+ del self.ValueCount
714
+
715
+ return True
716
+
717
+
718
+ @_add_method(otTables.PairPos)
719
+ def subset_glyphs(self, s):
720
+ if self.Format == 1:
721
+ indices = self.Coverage.subset(s.glyphs)
722
+ pairs = self.PairSet
723
+ count = len(pairs)
724
+ self.PairSet = [pairs[i] for i in indices if i < count]
725
+ for p in self.PairSet:
726
+ p.PairValueRecord = [
727
+ r for r in p.PairValueRecord if r.SecondGlyph in s.glyphs
728
+ ]
729
+ p.PairValueCount = len(p.PairValueRecord)
730
+ # Remove empty pairsets
731
+ indices = [i for i, p in enumerate(self.PairSet) if p.PairValueCount]
732
+ self.Coverage.remap(indices)
733
+ self.PairSet = _list_subset(self.PairSet, indices)
734
+ self.PairSetCount = len(self.PairSet)
735
+ return bool(self.PairSetCount)
736
+ elif self.Format == 2:
737
+ class1_map = [
738
+ c
739
+ for c in self.ClassDef1.subset(
740
+ s.glyphs.intersection(self.Coverage.glyphs), remap=True
741
+ )
742
+ if c < self.Class1Count
743
+ ]
744
+ class2_map = [
745
+ c
746
+ for c in self.ClassDef2.subset(s.glyphs, remap=True, useClass0=False)
747
+ if c < self.Class2Count
748
+ ]
749
+ self.Class1Record = [self.Class1Record[i] for i in class1_map]
750
+ for c in self.Class1Record:
751
+ c.Class2Record = [c.Class2Record[i] for i in class2_map]
752
+ self.Class1Count = len(class1_map)
753
+ self.Class2Count = len(class2_map)
754
+ # If only Class2 0 left, no need to keep anything.
755
+ return bool(
756
+ self.Class1Count
757
+ and (self.Class2Count > 1)
758
+ and self.Coverage.subset(s.glyphs)
759
+ )
760
+ else:
761
+ assert 0, "unknown format: %s" % self.Format
762
+
763
+
764
+ @_add_method(otTables.PairPos)
765
+ def prune_post_subset(self, font, options):
766
+ if not options.hinting:
767
+ attr1, attr2 = {
768
+ 1: ("PairSet", "PairValueRecord"),
769
+ 2: ("Class1Record", "Class2Record"),
770
+ }[self.Format]
771
+
772
+ self.ValueFormat1 = self.ValueFormat2 = 0
773
+ for row in getattr(self, attr1):
774
+ for r in getattr(row, attr2):
775
+ if r.Value1:
776
+ r.Value1.prune_hints()
777
+ self.ValueFormat1 |= r.Value1.getEffectiveFormat()
778
+ if r.Value2:
779
+ r.Value2.prune_hints()
780
+ self.ValueFormat2 |= r.Value2.getEffectiveFormat()
781
+
782
+ return bool(self.ValueFormat1 | self.ValueFormat2)
783
+
784
+
785
+ @_add_method(otTables.CursivePos)
786
+ def subset_glyphs(self, s):
787
+ if self.Format == 1:
788
+ indices = self.Coverage.subset(s.glyphs)
789
+ records = self.EntryExitRecord
790
+ count = len(records)
791
+ self.EntryExitRecord = [records[i] for i in indices if i < count]
792
+ self.EntryExitCount = len(self.EntryExitRecord)
793
+ return bool(self.EntryExitCount)
794
+ else:
795
+ assert 0, "unknown format: %s" % self.Format
796
+
797
+
798
+ @_add_method(otTables.Anchor)
799
+ def prune_hints(self):
800
+ if self.Format == 2:
801
+ self.Format = 1
802
+ elif self.Format == 3:
803
+ for name in ("XDeviceTable", "YDeviceTable"):
804
+ v = getattr(self, name, None)
805
+ if v is not None and v.is_hinting():
806
+ setattr(self, name, None)
807
+ if self.XDeviceTable is None and self.YDeviceTable is None:
808
+ self.Format = 1
809
+
810
+
811
+ @_add_method(otTables.CursivePos)
812
+ def prune_post_subset(self, font, options):
813
+ if not options.hinting:
814
+ for rec in self.EntryExitRecord:
815
+ if rec.EntryAnchor:
816
+ rec.EntryAnchor.prune_hints()
817
+ if rec.ExitAnchor:
818
+ rec.ExitAnchor.prune_hints()
819
+ return True
820
+
821
+
822
+ @_add_method(otTables.MarkBasePos)
823
+ def subset_glyphs(self, s):
824
+ if self.Format == 1:
825
+ mark_indices = self.MarkCoverage.subset(s.glyphs)
826
+ self.MarkArray.MarkRecord = _list_subset(
827
+ self.MarkArray.MarkRecord, mark_indices
828
+ )
829
+ self.MarkArray.MarkCount = len(self.MarkArray.MarkRecord)
830
+ base_indices = self.BaseCoverage.subset(s.glyphs)
831
+ self.BaseArray.BaseRecord = _list_subset(
832
+ self.BaseArray.BaseRecord, base_indices
833
+ )
834
+ self.BaseArray.BaseCount = len(self.BaseArray.BaseRecord)
835
+ # Prune empty classes
836
+ class_indices = _uniq_sort(v.Class for v in self.MarkArray.MarkRecord)
837
+ self.ClassCount = len(class_indices)
838
+ for m in self.MarkArray.MarkRecord:
839
+ m.Class = class_indices.index(m.Class)
840
+ for b in self.BaseArray.BaseRecord:
841
+ b.BaseAnchor = _list_subset(b.BaseAnchor, class_indices)
842
+ return bool(
843
+ self.ClassCount and self.MarkArray.MarkCount and self.BaseArray.BaseCount
844
+ )
845
+ else:
846
+ assert 0, "unknown format: %s" % self.Format
847
+
848
+
849
+ @_add_method(otTables.MarkBasePos)
850
+ def prune_post_subset(self, font, options):
851
+ if not options.hinting:
852
+ for m in self.MarkArray.MarkRecord:
853
+ if m.MarkAnchor:
854
+ m.MarkAnchor.prune_hints()
855
+ for b in self.BaseArray.BaseRecord:
856
+ for a in b.BaseAnchor:
857
+ if a:
858
+ a.prune_hints()
859
+ return True
860
+
861
+
862
+ @_add_method(otTables.MarkLigPos)
863
+ def subset_glyphs(self, s):
864
+ if self.Format == 1:
865
+ mark_indices = self.MarkCoverage.subset(s.glyphs)
866
+ self.MarkArray.MarkRecord = _list_subset(
867
+ self.MarkArray.MarkRecord, mark_indices
868
+ )
869
+ self.MarkArray.MarkCount = len(self.MarkArray.MarkRecord)
870
+ ligature_indices = self.LigatureCoverage.subset(s.glyphs)
871
+ self.LigatureArray.LigatureAttach = _list_subset(
872
+ self.LigatureArray.LigatureAttach, ligature_indices
873
+ )
874
+ self.LigatureArray.LigatureCount = len(self.LigatureArray.LigatureAttach)
875
+ # Prune empty classes
876
+ class_indices = _uniq_sort(v.Class for v in self.MarkArray.MarkRecord)
877
+ self.ClassCount = len(class_indices)
878
+ for m in self.MarkArray.MarkRecord:
879
+ m.Class = class_indices.index(m.Class)
880
+ for l in self.LigatureArray.LigatureAttach:
881
+ if l is None:
882
+ continue
883
+ for c in l.ComponentRecord:
884
+ c.LigatureAnchor = _list_subset(c.LigatureAnchor, class_indices)
885
+ return bool(
886
+ self.ClassCount
887
+ and self.MarkArray.MarkCount
888
+ and self.LigatureArray.LigatureCount
889
+ )
890
+ else:
891
+ assert 0, "unknown format: %s" % self.Format
892
+
893
+
894
+ @_add_method(otTables.MarkLigPos)
895
+ def prune_post_subset(self, font, options):
896
+ if not options.hinting:
897
+ for m in self.MarkArray.MarkRecord:
898
+ if m.MarkAnchor:
899
+ m.MarkAnchor.prune_hints()
900
+ for l in self.LigatureArray.LigatureAttach:
901
+ if l is None:
902
+ continue
903
+ for c in l.ComponentRecord:
904
+ for a in c.LigatureAnchor:
905
+ if a:
906
+ a.prune_hints()
907
+ return True
908
+
909
+
910
+ @_add_method(otTables.MarkMarkPos)
911
+ def subset_glyphs(self, s):
912
+ if self.Format == 1:
913
+ mark1_indices = self.Mark1Coverage.subset(s.glyphs)
914
+ self.Mark1Array.MarkRecord = _list_subset(
915
+ self.Mark1Array.MarkRecord, mark1_indices
916
+ )
917
+ self.Mark1Array.MarkCount = len(self.Mark1Array.MarkRecord)
918
+ mark2_indices = self.Mark2Coverage.subset(s.glyphs)
919
+ self.Mark2Array.Mark2Record = _list_subset(
920
+ self.Mark2Array.Mark2Record, mark2_indices
921
+ )
922
+ self.Mark2Array.MarkCount = len(self.Mark2Array.Mark2Record)
923
+ # Prune empty classes
924
+ class_indices = _uniq_sort(v.Class for v in self.Mark1Array.MarkRecord)
925
+ self.ClassCount = len(class_indices)
926
+ for m in self.Mark1Array.MarkRecord:
927
+ m.Class = class_indices.index(m.Class)
928
+ for b in self.Mark2Array.Mark2Record:
929
+ b.Mark2Anchor = _list_subset(b.Mark2Anchor, class_indices)
930
+ return bool(
931
+ self.ClassCount and self.Mark1Array.MarkCount and self.Mark2Array.MarkCount
932
+ )
933
+ else:
934
+ assert 0, "unknown format: %s" % self.Format
935
+
936
+
937
+ @_add_method(otTables.MarkMarkPos)
938
+ def prune_post_subset(self, font, options):
939
+ if not options.hinting:
940
+ for m in self.Mark1Array.MarkRecord:
941
+ if m.MarkAnchor:
942
+ m.MarkAnchor.prune_hints()
943
+ for b in self.Mark2Array.Mark2Record:
944
+ for m in b.Mark2Anchor:
945
+ if m:
946
+ m.prune_hints()
947
+ return True
948
+
949
+
950
+ @_add_method(
951
+ otTables.SingleSubst,
952
+ otTables.MultipleSubst,
953
+ otTables.AlternateSubst,
954
+ otTables.LigatureSubst,
955
+ otTables.ReverseChainSingleSubst,
956
+ otTables.SinglePos,
957
+ otTables.PairPos,
958
+ otTables.CursivePos,
959
+ otTables.MarkBasePos,
960
+ otTables.MarkLigPos,
961
+ otTables.MarkMarkPos,
962
+ )
963
+ def subset_lookups(self, lookup_indices):
964
+ pass
965
+
966
+
967
+ @_add_method(
968
+ otTables.SingleSubst,
969
+ otTables.MultipleSubst,
970
+ otTables.AlternateSubst,
971
+ otTables.LigatureSubst,
972
+ otTables.ReverseChainSingleSubst,
973
+ otTables.SinglePos,
974
+ otTables.PairPos,
975
+ otTables.CursivePos,
976
+ otTables.MarkBasePos,
977
+ otTables.MarkLigPos,
978
+ otTables.MarkMarkPos,
979
+ )
980
+ def collect_lookups(self):
981
+ return []
982
+
983
+
984
+ @_add_method(
985
+ otTables.SingleSubst,
986
+ otTables.MultipleSubst,
987
+ otTables.AlternateSubst,
988
+ otTables.LigatureSubst,
989
+ otTables.ReverseChainSingleSubst,
990
+ otTables.ContextSubst,
991
+ otTables.ChainContextSubst,
992
+ otTables.ContextPos,
993
+ otTables.ChainContextPos,
994
+ )
995
+ def prune_post_subset(self, font, options):
996
+ return True
997
+
998
+
999
+ @_add_method(
1000
+ otTables.SingleSubst, otTables.AlternateSubst, otTables.ReverseChainSingleSubst
1001
+ )
1002
+ def may_have_non_1to1(self):
1003
+ return False
1004
+
1005
+
1006
+ @_add_method(
1007
+ otTables.MultipleSubst,
1008
+ otTables.LigatureSubst,
1009
+ otTables.ContextSubst,
1010
+ otTables.ChainContextSubst,
1011
+ )
1012
+ def may_have_non_1to1(self):
1013
+ return True
1014
+
1015
+
1016
+ @_add_method(
1017
+ otTables.ContextSubst,
1018
+ otTables.ChainContextSubst,
1019
+ otTables.ContextPos,
1020
+ otTables.ChainContextPos,
1021
+ )
1022
+ def __subset_classify_context(self):
1023
+ class ContextHelper(object):
1024
+ def __init__(self, klass, Format):
1025
+ if klass.__name__.endswith("Subst"):
1026
+ Typ = "Sub"
1027
+ Type = "Subst"
1028
+ else:
1029
+ Typ = "Pos"
1030
+ Type = "Pos"
1031
+ if klass.__name__.startswith("Chain"):
1032
+ Chain = "Chain"
1033
+ InputIdx = 1
1034
+ DataLen = 3
1035
+ else:
1036
+ Chain = ""
1037
+ InputIdx = 0
1038
+ DataLen = 1
1039
+ ChainTyp = Chain + Typ
1040
+
1041
+ self.Typ = Typ
1042
+ self.Type = Type
1043
+ self.Chain = Chain
1044
+ self.ChainTyp = ChainTyp
1045
+ self.InputIdx = InputIdx
1046
+ self.DataLen = DataLen
1047
+
1048
+ self.LookupRecord = Type + "LookupRecord"
1049
+
1050
+ if Format == 1:
1051
+ Coverage = lambda r: r.Coverage
1052
+ ChainCoverage = lambda r: r.Coverage
1053
+ ContextData = lambda r: (None,)
1054
+ ChainContextData = lambda r: (None, None, None)
1055
+ SetContextData = None
1056
+ SetChainContextData = None
1057
+ RuleData = lambda r: (r.Input,)
1058
+ ChainRuleData = lambda r: (r.Backtrack, r.Input, r.LookAhead)
1059
+
1060
+ def SetRuleData(r, d):
1061
+ (r.Input,) = d
1062
+ (r.GlyphCount,) = (len(x) + 1 for x in d)
1063
+
1064
+ def ChainSetRuleData(r, d):
1065
+ (r.Backtrack, r.Input, r.LookAhead) = d
1066
+ (
1067
+ r.BacktrackGlyphCount,
1068
+ r.InputGlyphCount,
1069
+ r.LookAheadGlyphCount,
1070
+ ) = (len(d[0]), len(d[1]) + 1, len(d[2]))
1071
+
1072
+ elif Format == 2:
1073
+ Coverage = lambda r: r.Coverage
1074
+ ChainCoverage = lambda r: r.Coverage
1075
+ ContextData = lambda r: (r.ClassDef,)
1076
+ ChainContextData = lambda r: (
1077
+ r.BacktrackClassDef,
1078
+ r.InputClassDef,
1079
+ r.LookAheadClassDef,
1080
+ )
1081
+
1082
+ def SetContextData(r, d):
1083
+ (r.ClassDef,) = d
1084
+
1085
+ def SetChainContextData(r, d):
1086
+ (r.BacktrackClassDef, r.InputClassDef, r.LookAheadClassDef) = d
1087
+
1088
+ RuleData = lambda r: (r.Class,)
1089
+ ChainRuleData = lambda r: (r.Backtrack, r.Input, r.LookAhead)
1090
+
1091
+ def SetRuleData(r, d):
1092
+ (r.Class,) = d
1093
+ (r.GlyphCount,) = (len(x) + 1 for x in d)
1094
+
1095
+ def ChainSetRuleData(r, d):
1096
+ (r.Backtrack, r.Input, r.LookAhead) = d
1097
+ (
1098
+ r.BacktrackGlyphCount,
1099
+ r.InputGlyphCount,
1100
+ r.LookAheadGlyphCount,
1101
+ ) = (len(d[0]), len(d[1]) + 1, len(d[2]))
1102
+
1103
+ elif Format == 3:
1104
+ Coverage = lambda r: r.Coverage[0]
1105
+ ChainCoverage = lambda r: r.InputCoverage[0]
1106
+ ContextData = None
1107
+ ChainContextData = None
1108
+ SetContextData = None
1109
+ SetChainContextData = None
1110
+ RuleData = lambda r: r.Coverage
1111
+ ChainRuleData = lambda r: (
1112
+ r.BacktrackCoverage + r.InputCoverage + r.LookAheadCoverage
1113
+ )
1114
+
1115
+ def SetRuleData(r, d):
1116
+ (r.Coverage,) = d
1117
+ (r.GlyphCount,) = (len(x) for x in d)
1118
+
1119
+ def ChainSetRuleData(r, d):
1120
+ (r.BacktrackCoverage, r.InputCoverage, r.LookAheadCoverage) = d
1121
+ (
1122
+ r.BacktrackGlyphCount,
1123
+ r.InputGlyphCount,
1124
+ r.LookAheadGlyphCount,
1125
+ ) = (len(x) for x in d)
1126
+
1127
+ else:
1128
+ assert 0, "unknown format: %s" % Format
1129
+
1130
+ if Chain:
1131
+ self.Coverage = ChainCoverage
1132
+ self.ContextData = ChainContextData
1133
+ self.SetContextData = SetChainContextData
1134
+ self.RuleData = ChainRuleData
1135
+ self.SetRuleData = ChainSetRuleData
1136
+ else:
1137
+ self.Coverage = Coverage
1138
+ self.ContextData = ContextData
1139
+ self.SetContextData = SetContextData
1140
+ self.RuleData = RuleData
1141
+ self.SetRuleData = SetRuleData
1142
+
1143
+ if Format == 1:
1144
+ self.Rule = ChainTyp + "Rule"
1145
+ self.RuleCount = ChainTyp + "RuleCount"
1146
+ self.RuleSet = ChainTyp + "RuleSet"
1147
+ self.RuleSetCount = ChainTyp + "RuleSetCount"
1148
+ self.Intersect = lambda glyphs, c, r: [r] if r in glyphs else []
1149
+ elif Format == 2:
1150
+ self.Rule = ChainTyp + "ClassRule"
1151
+ self.RuleCount = ChainTyp + "ClassRuleCount"
1152
+ self.RuleSet = ChainTyp + "ClassSet"
1153
+ self.RuleSetCount = ChainTyp + "ClassSetCount"
1154
+ self.Intersect = lambda glyphs, c, r: (
1155
+ c.intersect_class(glyphs, r)
1156
+ if c
1157
+ else (set(glyphs) if r == 0 else set())
1158
+ )
1159
+
1160
+ self.ClassDef = "InputClassDef" if Chain else "ClassDef"
1161
+ self.ClassDefIndex = 1 if Chain else 0
1162
+ self.Input = "Input" if Chain else "Class"
1163
+ elif Format == 3:
1164
+ self.Input = "InputCoverage" if Chain else "Coverage"
1165
+
1166
+ if self.Format not in [1, 2, 3]:
1167
+ return None # Don't shoot the messenger; let it go
1168
+ if not hasattr(self.__class__, "_subset__ContextHelpers"):
1169
+ self.__class__._subset__ContextHelpers = {}
1170
+ if self.Format not in self.__class__._subset__ContextHelpers:
1171
+ helper = ContextHelper(self.__class__, self.Format)
1172
+ self.__class__._subset__ContextHelpers[self.Format] = helper
1173
+ return self.__class__._subset__ContextHelpers[self.Format]
1174
+
1175
+
1176
+ @_add_method(otTables.ContextSubst, otTables.ChainContextSubst)
1177
+ def closure_glyphs(self, s, cur_glyphs):
1178
+ c = self.__subset_classify_context()
1179
+
1180
+ indices = c.Coverage(self).intersect(cur_glyphs)
1181
+ if not indices:
1182
+ return []
1183
+ cur_glyphs = c.Coverage(self).intersect_glyphs(cur_glyphs)
1184
+
1185
+ if self.Format == 1:
1186
+ ContextData = c.ContextData(self)
1187
+ rss = getattr(self, c.RuleSet)
1188
+ rssCount = getattr(self, c.RuleSetCount)
1189
+ for i in indices:
1190
+ if i >= rssCount or not rss[i]:
1191
+ continue
1192
+ for r in getattr(rss[i], c.Rule):
1193
+ if not r:
1194
+ continue
1195
+ if not all(
1196
+ all(c.Intersect(s.glyphs, cd, k) for k in klist)
1197
+ for cd, klist in zip(ContextData, c.RuleData(r))
1198
+ ):
1199
+ continue
1200
+ chaos = set()
1201
+ for ll in getattr(r, c.LookupRecord):
1202
+ if not ll:
1203
+ continue
1204
+ seqi = ll.SequenceIndex
1205
+ if seqi in chaos:
1206
+ # TODO Can we improve this?
1207
+ pos_glyphs = None
1208
+ else:
1209
+ if seqi == 0:
1210
+ pos_glyphs = frozenset([c.Coverage(self).glyphs[i]])
1211
+ else:
1212
+ pos_glyphs = frozenset([r.Input[seqi - 1]])
1213
+ lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
1214
+ chaos.add(seqi)
1215
+ if lookup.may_have_non_1to1():
1216
+ chaos.update(range(seqi, len(r.Input) + 2))
1217
+ lookup.closure_glyphs(s, cur_glyphs=pos_glyphs)
1218
+ elif self.Format == 2:
1219
+ ClassDef = getattr(self, c.ClassDef)
1220
+ indices = ClassDef.intersect(cur_glyphs)
1221
+ ContextData = c.ContextData(self)
1222
+ rss = getattr(self, c.RuleSet)
1223
+ rssCount = getattr(self, c.RuleSetCount)
1224
+ for i in indices:
1225
+ if i >= rssCount or not rss[i]:
1226
+ continue
1227
+ for r in getattr(rss[i], c.Rule):
1228
+ if not r:
1229
+ continue
1230
+ if not all(
1231
+ all(c.Intersect(s.glyphs, cd, k) for k in klist)
1232
+ for cd, klist in zip(ContextData, c.RuleData(r))
1233
+ ):
1234
+ continue
1235
+ chaos = set()
1236
+ for ll in getattr(r, c.LookupRecord):
1237
+ if not ll:
1238
+ continue
1239
+ seqi = ll.SequenceIndex
1240
+ if seqi in chaos:
1241
+ # TODO Can we improve this?
1242
+ pos_glyphs = None
1243
+ else:
1244
+ if seqi == 0:
1245
+ pos_glyphs = frozenset(
1246
+ ClassDef.intersect_class(cur_glyphs, i)
1247
+ )
1248
+ else:
1249
+ pos_glyphs = frozenset(
1250
+ ClassDef.intersect_class(
1251
+ s.glyphs, getattr(r, c.Input)[seqi - 1]
1252
+ )
1253
+ )
1254
+ lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
1255
+ chaos.add(seqi)
1256
+ if lookup.may_have_non_1to1():
1257
+ chaos.update(range(seqi, len(getattr(r, c.Input)) + 2))
1258
+ lookup.closure_glyphs(s, cur_glyphs=pos_glyphs)
1259
+ elif self.Format == 3:
1260
+ if not all(x is not None and x.intersect(s.glyphs) for x in c.RuleData(self)):
1261
+ return []
1262
+ r = self
1263
+ input_coverages = getattr(r, c.Input)
1264
+ chaos = set()
1265
+ for ll in getattr(r, c.LookupRecord):
1266
+ if not ll:
1267
+ continue
1268
+ seqi = ll.SequenceIndex
1269
+ if seqi in chaos:
1270
+ # TODO Can we improve this?
1271
+ pos_glyphs = None
1272
+ else:
1273
+ if seqi == 0:
1274
+ pos_glyphs = frozenset(cur_glyphs)
1275
+ else:
1276
+ pos_glyphs = frozenset(
1277
+ input_coverages[seqi].intersect_glyphs(s.glyphs)
1278
+ )
1279
+ lookup = s.table.LookupList.Lookup[ll.LookupListIndex]
1280
+ chaos.add(seqi)
1281
+ if lookup.may_have_non_1to1():
1282
+ chaos.update(range(seqi, len(input_coverages) + 1))
1283
+ lookup.closure_glyphs(s, cur_glyphs=pos_glyphs)
1284
+ else:
1285
+ assert 0, "unknown format: %s" % self.Format
1286
+
1287
+
1288
+ @_add_method(
1289
+ otTables.ContextSubst,
1290
+ otTables.ContextPos,
1291
+ otTables.ChainContextSubst,
1292
+ otTables.ChainContextPos,
1293
+ )
1294
+ def subset_glyphs(self, s):
1295
+ c = self.__subset_classify_context()
1296
+
1297
+ if self.Format == 1:
1298
+ indices = self.Coverage.subset(s.glyphs)
1299
+ rss = getattr(self, c.RuleSet)
1300
+ rssCount = getattr(self, c.RuleSetCount)
1301
+ rss = [rss[i] for i in indices if i < rssCount]
1302
+ for rs in rss:
1303
+ if not rs:
1304
+ continue
1305
+ ss = getattr(rs, c.Rule)
1306
+ ss = [
1307
+ r
1308
+ for r in ss
1309
+ if r
1310
+ and all(all(g in s.glyphs for g in glist) for glist in c.RuleData(r))
1311
+ ]
1312
+ setattr(rs, c.Rule, ss)
1313
+ setattr(rs, c.RuleCount, len(ss))
1314
+ # Prune empty rulesets
1315
+ indices = [i for i, rs in enumerate(rss) if rs and getattr(rs, c.Rule)]
1316
+ self.Coverage.remap(indices)
1317
+ rss = _list_subset(rss, indices)
1318
+ setattr(self, c.RuleSet, rss)
1319
+ setattr(self, c.RuleSetCount, len(rss))
1320
+ return bool(rss)
1321
+ elif self.Format == 2:
1322
+ if not self.Coverage.subset(s.glyphs):
1323
+ return False
1324
+ ContextData = c.ContextData(self)
1325
+ klass_maps = [
1326
+ x.subset(s.glyphs, remap=True) if x else None for x in ContextData
1327
+ ]
1328
+
1329
+ # Keep rulesets for class numbers that survived.
1330
+ indices = klass_maps[c.ClassDefIndex]
1331
+ rss = getattr(self, c.RuleSet)
1332
+ rssCount = getattr(self, c.RuleSetCount)
1333
+ rss = [rss[i] for i in indices if i < rssCount]
1334
+ del rssCount
1335
+ # Delete, but not renumber, unreachable rulesets.
1336
+ indices = getattr(self, c.ClassDef).intersect(self.Coverage.glyphs)
1337
+ rss = [rss if i in indices else None for i, rss in enumerate(rss)]
1338
+
1339
+ for rs in rss:
1340
+ if not rs:
1341
+ continue
1342
+ ss = getattr(rs, c.Rule)
1343
+ ss = [
1344
+ r
1345
+ for r in ss
1346
+ if r
1347
+ and all(
1348
+ all(k in klass_map for k in klist)
1349
+ for klass_map, klist in zip(klass_maps, c.RuleData(r))
1350
+ )
1351
+ ]
1352
+ setattr(rs, c.Rule, ss)
1353
+ setattr(rs, c.RuleCount, len(ss))
1354
+
1355
+ # Remap rule classes
1356
+ for r in ss:
1357
+ c.SetRuleData(
1358
+ r,
1359
+ [
1360
+ [klass_map.index(k) for k in klist]
1361
+ for klass_map, klist in zip(klass_maps, c.RuleData(r))
1362
+ ],
1363
+ )
1364
+
1365
+ # Prune empty rulesets
1366
+ rss = [rs if rs and getattr(rs, c.Rule) else None for rs in rss]
1367
+ while rss and rss[-1] is None:
1368
+ del rss[-1]
1369
+ setattr(self, c.RuleSet, rss)
1370
+ setattr(self, c.RuleSetCount, len(rss))
1371
+
1372
+ # TODO: We can do a second round of remapping class values based
1373
+ # on classes that are actually used in at least one rule. Right
1374
+ # now we subset classes to c.glyphs only. Or better, rewrite
1375
+ # the above to do that.
1376
+
1377
+ return bool(rss)
1378
+ elif self.Format == 3:
1379
+ return all(x is not None and x.subset(s.glyphs) for x in c.RuleData(self))
1380
+ else:
1381
+ assert 0, "unknown format: %s" % self.Format
1382
+
1383
+
1384
+ @_add_method(
1385
+ otTables.ContextSubst,
1386
+ otTables.ChainContextSubst,
1387
+ otTables.ContextPos,
1388
+ otTables.ChainContextPos,
1389
+ )
1390
+ def subset_lookups(self, lookup_indices):
1391
+ c = self.__subset_classify_context()
1392
+
1393
+ if self.Format in [1, 2]:
1394
+ for rs in getattr(self, c.RuleSet):
1395
+ if not rs:
1396
+ continue
1397
+ for r in getattr(rs, c.Rule):
1398
+ if not r:
1399
+ continue
1400
+ setattr(
1401
+ r,
1402
+ c.LookupRecord,
1403
+ [
1404
+ ll
1405
+ for ll in getattr(r, c.LookupRecord)
1406
+ if ll and ll.LookupListIndex in lookup_indices
1407
+ ],
1408
+ )
1409
+ for ll in getattr(r, c.LookupRecord):
1410
+ if not ll:
1411
+ continue
1412
+ ll.LookupListIndex = lookup_indices.index(ll.LookupListIndex)
1413
+ elif self.Format == 3:
1414
+ setattr(
1415
+ self,
1416
+ c.LookupRecord,
1417
+ [
1418
+ ll
1419
+ for ll in getattr(self, c.LookupRecord)
1420
+ if ll and ll.LookupListIndex in lookup_indices
1421
+ ],
1422
+ )
1423
+ for ll in getattr(self, c.LookupRecord):
1424
+ if not ll:
1425
+ continue
1426
+ ll.LookupListIndex = lookup_indices.index(ll.LookupListIndex)
1427
+ else:
1428
+ assert 0, "unknown format: %s" % self.Format
1429
+
1430
+
1431
+ @_add_method(
1432
+ otTables.ContextSubst,
1433
+ otTables.ChainContextSubst,
1434
+ otTables.ContextPos,
1435
+ otTables.ChainContextPos,
1436
+ )
1437
+ def collect_lookups(self):
1438
+ c = self.__subset_classify_context()
1439
+
1440
+ if self.Format in [1, 2]:
1441
+ return [
1442
+ ll.LookupListIndex
1443
+ for rs in getattr(self, c.RuleSet)
1444
+ if rs
1445
+ for r in getattr(rs, c.Rule)
1446
+ if r
1447
+ for ll in getattr(r, c.LookupRecord)
1448
+ if ll
1449
+ ]
1450
+ elif self.Format == 3:
1451
+ return [ll.LookupListIndex for ll in getattr(self, c.LookupRecord) if ll]
1452
+ else:
1453
+ assert 0, "unknown format: %s" % self.Format
1454
+
1455
+
1456
+ @_add_method(otTables.ExtensionSubst)
1457
+ def closure_glyphs(self, s, cur_glyphs):
1458
+ if self.Format == 1:
1459
+ self.ExtSubTable.closure_glyphs(s, cur_glyphs)
1460
+ else:
1461
+ assert 0, "unknown format: %s" % self.Format
1462
+
1463
+
1464
+ @_add_method(otTables.ExtensionSubst)
1465
+ def may_have_non_1to1(self):
1466
+ if self.Format == 1:
1467
+ return self.ExtSubTable.may_have_non_1to1()
1468
+ else:
1469
+ assert 0, "unknown format: %s" % self.Format
1470
+
1471
+
1472
+ @_add_method(otTables.ExtensionSubst, otTables.ExtensionPos)
1473
+ def subset_glyphs(self, s):
1474
+ if self.Format == 1:
1475
+ return self.ExtSubTable.subset_glyphs(s)
1476
+ else:
1477
+ assert 0, "unknown format: %s" % self.Format
1478
+
1479
+
1480
+ @_add_method(otTables.ExtensionSubst, otTables.ExtensionPos)
1481
+ def prune_post_subset(self, font, options):
1482
+ if self.Format == 1:
1483
+ return self.ExtSubTable.prune_post_subset(font, options)
1484
+ else:
1485
+ assert 0, "unknown format: %s" % self.Format
1486
+
1487
+
1488
+ @_add_method(otTables.ExtensionSubst, otTables.ExtensionPos)
1489
+ def subset_lookups(self, lookup_indices):
1490
+ if self.Format == 1:
1491
+ return self.ExtSubTable.subset_lookups(lookup_indices)
1492
+ else:
1493
+ assert 0, "unknown format: %s" % self.Format
1494
+
1495
+
1496
+ @_add_method(otTables.ExtensionSubst, otTables.ExtensionPos)
1497
+ def collect_lookups(self):
1498
+ if self.Format == 1:
1499
+ return self.ExtSubTable.collect_lookups()
1500
+ else:
1501
+ assert 0, "unknown format: %s" % self.Format
1502
+
1503
+
1504
+ @_add_method(otTables.Lookup)
1505
+ def closure_glyphs(self, s, cur_glyphs=None):
1506
+ if cur_glyphs is None:
1507
+ cur_glyphs = frozenset(s.glyphs)
1508
+
1509
+ # Memoize
1510
+ key = id(self)
1511
+ doneLookups = s._doneLookups
1512
+ count, covered = doneLookups.get(key, (0, None))
1513
+ if count != len(s.glyphs):
1514
+ count, covered = doneLookups[key] = (len(s.glyphs), set())
1515
+ if cur_glyphs.issubset(covered):
1516
+ return
1517
+ covered.update(cur_glyphs)
1518
+
1519
+ for st in self.SubTable:
1520
+ if not st:
1521
+ continue
1522
+ st.closure_glyphs(s, cur_glyphs)
1523
+
1524
+
1525
+ @_add_method(otTables.Lookup)
1526
+ def subset_glyphs(self, s):
1527
+ self.SubTable = [st for st in self.SubTable if st and st.subset_glyphs(s)]
1528
+ self.SubTableCount = len(self.SubTable)
1529
+ if hasattr(self, "MarkFilteringSet") and self.MarkFilteringSet is not None:
1530
+ if self.MarkFilteringSet not in s.used_mark_sets:
1531
+ self.MarkFilteringSet = None
1532
+ self.LookupFlag &= ~0x10
1533
+ else:
1534
+ self.MarkFilteringSet = s.used_mark_sets.index(self.MarkFilteringSet)
1535
+ return bool(self.SubTableCount)
1536
+
1537
+
1538
+ @_add_method(otTables.Lookup)
1539
+ def prune_post_subset(self, font, options):
1540
+ ret = False
1541
+ for st in self.SubTable:
1542
+ if not st:
1543
+ continue
1544
+ if st.prune_post_subset(font, options):
1545
+ ret = True
1546
+ return ret
1547
+
1548
+
1549
+ @_add_method(otTables.Lookup)
1550
+ def subset_lookups(self, lookup_indices):
1551
+ for s in self.SubTable:
1552
+ s.subset_lookups(lookup_indices)
1553
+
1554
+
1555
+ @_add_method(otTables.Lookup)
1556
+ def collect_lookups(self):
1557
+ return sum((st.collect_lookups() for st in self.SubTable if st), [])
1558
+
1559
+
1560
+ @_add_method(otTables.Lookup)
1561
+ def may_have_non_1to1(self):
1562
+ return any(st.may_have_non_1to1() for st in self.SubTable if st)
1563
+
1564
+
1565
+ @_add_method(otTables.LookupList)
1566
+ def subset_glyphs(self, s):
1567
+ """Returns the indices of nonempty lookups."""
1568
+ return [i for i, l in enumerate(self.Lookup) if l and l.subset_glyphs(s)]
1569
+
1570
+
1571
+ @_add_method(otTables.LookupList)
1572
+ def prune_post_subset(self, font, options):
1573
+ ret = False
1574
+ for l in self.Lookup:
1575
+ if not l:
1576
+ continue
1577
+ if l.prune_post_subset(font, options):
1578
+ ret = True
1579
+ return ret
1580
+
1581
+
1582
+ @_add_method(otTables.LookupList)
1583
+ def subset_lookups(self, lookup_indices):
1584
+ self.ensureDecompiled()
1585
+ self.Lookup = [self.Lookup[i] for i in lookup_indices if i < self.LookupCount]
1586
+ self.LookupCount = len(self.Lookup)
1587
+ for l in self.Lookup:
1588
+ l.subset_lookups(lookup_indices)
1589
+
1590
+
1591
+ @_add_method(otTables.LookupList)
1592
+ def neuter_lookups(self, lookup_indices):
1593
+ """Sets lookups not in lookup_indices to None."""
1594
+ self.ensureDecompiled()
1595
+ self.Lookup = [
1596
+ l if i in lookup_indices else None for i, l in enumerate(self.Lookup)
1597
+ ]
1598
+
1599
+
1600
+ @_add_method(otTables.LookupList)
1601
+ def closure_lookups(self, lookup_indices):
1602
+ """Returns sorted index of all lookups reachable from lookup_indices."""
1603
+ lookup_indices = _uniq_sort(lookup_indices)
1604
+ recurse = lookup_indices
1605
+ while True:
1606
+ recurse_lookups = sum(
1607
+ (self.Lookup[i].collect_lookups() for i in recurse if i < self.LookupCount),
1608
+ [],
1609
+ )
1610
+ recurse_lookups = [
1611
+ l
1612
+ for l in recurse_lookups
1613
+ if l not in lookup_indices and l < self.LookupCount
1614
+ ]
1615
+ if not recurse_lookups:
1616
+ return _uniq_sort(lookup_indices)
1617
+ recurse_lookups = _uniq_sort(recurse_lookups)
1618
+ lookup_indices.extend(recurse_lookups)
1619
+ recurse = recurse_lookups
1620
+
1621
+
1622
+ @_add_method(otTables.Feature)
1623
+ def subset_lookups(self, lookup_indices):
1624
+ """ "Returns True if feature is non-empty afterwards."""
1625
+ self.LookupListIndex = [l for l in self.LookupListIndex if l in lookup_indices]
1626
+ # Now map them.
1627
+ self.LookupListIndex = [lookup_indices.index(l) for l in self.LookupListIndex]
1628
+ self.LookupCount = len(self.LookupListIndex)
1629
+ # keep 'size' feature even if it contains no lookups; but drop any other
1630
+ # empty feature (e.g. FeatureParams for stylistic set names)
1631
+ # https://github.com/fonttools/fonttools/issues/2324
1632
+ return self.LookupCount or isinstance(
1633
+ self.FeatureParams, otTables.FeatureParamsSize
1634
+ )
1635
+
1636
+
1637
+ @_add_method(otTables.FeatureList)
1638
+ def subset_lookups(self, lookup_indices):
1639
+ """Returns the indices of nonempty features."""
1640
+ # Note: Never ever drop feature 'pref', even if it's empty.
1641
+ # HarfBuzz chooses shaper for Khmer based on presence of this
1642
+ # feature. See thread at:
1643
+ # http://lists.freedesktop.org/archives/harfbuzz/2012-November/002660.html
1644
+ return [
1645
+ i
1646
+ for i, f in enumerate(self.FeatureRecord)
1647
+ if (f.Feature.subset_lookups(lookup_indices) or f.FeatureTag == "pref")
1648
+ ]
1649
+
1650
+
1651
+ @_add_method(otTables.FeatureList)
1652
+ def collect_lookups(self, feature_indices):
1653
+ return sum(
1654
+ (
1655
+ self.FeatureRecord[i].Feature.LookupListIndex
1656
+ for i in feature_indices
1657
+ if i < self.FeatureCount
1658
+ ),
1659
+ [],
1660
+ )
1661
+
1662
+
1663
+ @_add_method(otTables.FeatureList)
1664
+ def subset_features(self, feature_indices):
1665
+ self.ensureDecompiled()
1666
+ self.FeatureRecord = _list_subset(self.FeatureRecord, feature_indices)
1667
+ self.FeatureCount = len(self.FeatureRecord)
1668
+ return bool(self.FeatureCount)
1669
+
1670
+
1671
+ @_add_method(otTables.FeatureTableSubstitution)
1672
+ def subset_lookups(self, lookup_indices):
1673
+ """Returns the indices of nonempty features."""
1674
+ return [
1675
+ r.FeatureIndex
1676
+ for r in self.SubstitutionRecord
1677
+ if r.Feature.subset_lookups(lookup_indices)
1678
+ ]
1679
+
1680
+
1681
+ @_add_method(otTables.FeatureVariations)
1682
+ def subset_lookups(self, lookup_indices):
1683
+ """Returns the indices of nonempty features."""
1684
+ return sum(
1685
+ (
1686
+ f.FeatureTableSubstitution.subset_lookups(lookup_indices)
1687
+ for f in self.FeatureVariationRecord
1688
+ ),
1689
+ [],
1690
+ )
1691
+
1692
+
1693
+ @_add_method(otTables.FeatureVariations)
1694
+ def collect_lookups(self, feature_indices):
1695
+ return sum(
1696
+ (
1697
+ r.Feature.LookupListIndex
1698
+ for vr in self.FeatureVariationRecord
1699
+ for r in vr.FeatureTableSubstitution.SubstitutionRecord
1700
+ if r.FeatureIndex in feature_indices
1701
+ ),
1702
+ [],
1703
+ )
1704
+
1705
+
1706
+ @_add_method(otTables.FeatureTableSubstitution)
1707
+ def subset_features(self, feature_indices):
1708
+ self.ensureDecompiled()
1709
+ self.SubstitutionRecord = [
1710
+ r for r in self.SubstitutionRecord if r.FeatureIndex in feature_indices
1711
+ ]
1712
+ # remap feature indices
1713
+ for r in self.SubstitutionRecord:
1714
+ r.FeatureIndex = feature_indices.index(r.FeatureIndex)
1715
+ self.SubstitutionCount = len(self.SubstitutionRecord)
1716
+ return bool(self.SubstitutionCount)
1717
+
1718
+
1719
+ @_add_method(otTables.FeatureVariations)
1720
+ def subset_features(self, feature_indices):
1721
+ self.ensureDecompiled()
1722
+ for r in self.FeatureVariationRecord:
1723
+ r.FeatureTableSubstitution.subset_features(feature_indices)
1724
+ # Prune empty records at the end only
1725
+ # https://github.com/fonttools/fonttools/issues/1881
1726
+ while (
1727
+ self.FeatureVariationRecord
1728
+ and not self.FeatureVariationRecord[
1729
+ -1
1730
+ ].FeatureTableSubstitution.SubstitutionCount
1731
+ ):
1732
+ self.FeatureVariationRecord.pop()
1733
+ self.FeatureVariationCount = len(self.FeatureVariationRecord)
1734
+ return bool(self.FeatureVariationCount)
1735
+
1736
+
1737
+ @_add_method(otTables.DefaultLangSys, otTables.LangSys)
1738
+ def subset_features(self, feature_indices):
1739
+ if self.ReqFeatureIndex in feature_indices:
1740
+ self.ReqFeatureIndex = feature_indices.index(self.ReqFeatureIndex)
1741
+ else:
1742
+ self.ReqFeatureIndex = 65535
1743
+ self.FeatureIndex = [f for f in self.FeatureIndex if f in feature_indices]
1744
+ # Now map them.
1745
+ self.FeatureIndex = [
1746
+ feature_indices.index(f) for f in self.FeatureIndex if f in feature_indices
1747
+ ]
1748
+ self.FeatureCount = len(self.FeatureIndex)
1749
+ return bool(self.FeatureCount or self.ReqFeatureIndex != 65535)
1750
+
1751
+
1752
+ @_add_method(otTables.DefaultLangSys, otTables.LangSys)
1753
+ def collect_features(self):
1754
+ feature_indices = self.FeatureIndex[:]
1755
+ if self.ReqFeatureIndex != 65535:
1756
+ feature_indices.append(self.ReqFeatureIndex)
1757
+ return _uniq_sort(feature_indices)
1758
+
1759
+
1760
+ @_add_method(otTables.Script)
1761
+ def subset_features(self, feature_indices, keepEmptyDefaultLangSys=False):
1762
+ if (
1763
+ self.DefaultLangSys
1764
+ and not self.DefaultLangSys.subset_features(feature_indices)
1765
+ and not keepEmptyDefaultLangSys
1766
+ ):
1767
+ self.DefaultLangSys = None
1768
+ self.LangSysRecord = [
1769
+ l for l in self.LangSysRecord if l.LangSys.subset_features(feature_indices)
1770
+ ]
1771
+ self.LangSysCount = len(self.LangSysRecord)
1772
+ return bool(self.LangSysCount or self.DefaultLangSys)
1773
+
1774
+
1775
+ @_add_method(otTables.Script)
1776
+ def collect_features(self):
1777
+ feature_indices = [l.LangSys.collect_features() for l in self.LangSysRecord]
1778
+ if self.DefaultLangSys:
1779
+ feature_indices.append(self.DefaultLangSys.collect_features())
1780
+ return _uniq_sort(sum(feature_indices, []))
1781
+
1782
+
1783
+ @_add_method(otTables.ScriptList)
1784
+ def subset_features(self, feature_indices, retain_empty):
1785
+ # https://bugzilla.mozilla.org/show_bug.cgi?id=1331737#c32
1786
+ self.ScriptRecord = [
1787
+ s
1788
+ for s in self.ScriptRecord
1789
+ if s.Script.subset_features(feature_indices, s.ScriptTag == "DFLT")
1790
+ or retain_empty
1791
+ ]
1792
+ self.ScriptCount = len(self.ScriptRecord)
1793
+ return bool(self.ScriptCount)
1794
+
1795
+
1796
+ @_add_method(otTables.ScriptList)
1797
+ def collect_features(self):
1798
+ return _uniq_sort(sum((s.Script.collect_features() for s in self.ScriptRecord), []))
1799
+
1800
+
1801
+ # CBLC will inherit it
1802
+ @_add_method(ttLib.getTableClass("EBLC"))
1803
+ def subset_glyphs(self, s):
1804
+ for strike in self.strikes:
1805
+ for indexSubTable in strike.indexSubTables:
1806
+ indexSubTable.names = [n for n in indexSubTable.names if n in s.glyphs]
1807
+ strike.indexSubTables = [i for i in strike.indexSubTables if i.names]
1808
+ self.strikes = [s for s in self.strikes if s.indexSubTables]
1809
+
1810
+ return True
1811
+
1812
+
1813
+ # CBDT will inherit it
1814
+ @_add_method(ttLib.getTableClass("EBDT"))
1815
+ def subset_glyphs(self, s):
1816
+ strikeData = [
1817
+ {g: strike[g] for g in s.glyphs if g in strike} for strike in self.strikeData
1818
+ ]
1819
+ # Prune empty strikes
1820
+ # https://github.com/fonttools/fonttools/issues/1633
1821
+ self.strikeData = [strike for strike in strikeData if strike]
1822
+ return True
1823
+
1824
+
1825
+ @_add_method(ttLib.getTableClass("sbix"))
1826
+ def subset_glyphs(self, s):
1827
+ for strike in self.strikes.values():
1828
+ strike.glyphs = {g: strike.glyphs[g] for g in s.glyphs if g in strike.glyphs}
1829
+
1830
+ return True
1831
+
1832
+
1833
+ @_add_method(ttLib.getTableClass("GSUB"))
1834
+ def closure_glyphs(self, s):
1835
+ s.table = self.table
1836
+ if self.table.ScriptList:
1837
+ feature_indices = self.table.ScriptList.collect_features()
1838
+ else:
1839
+ feature_indices = []
1840
+ if self.table.FeatureList:
1841
+ lookup_indices = self.table.FeatureList.collect_lookups(feature_indices)
1842
+ else:
1843
+ lookup_indices = []
1844
+ if getattr(self.table, "FeatureVariations", None):
1845
+ lookup_indices += self.table.FeatureVariations.collect_lookups(feature_indices)
1846
+ lookup_indices = _uniq_sort(lookup_indices)
1847
+ if self.table.LookupList:
1848
+ s._doneLookups = {}
1849
+ while True:
1850
+ orig_glyphs = frozenset(s.glyphs)
1851
+ for i in lookup_indices:
1852
+ if i >= self.table.LookupList.LookupCount:
1853
+ continue
1854
+ if not self.table.LookupList.Lookup[i]:
1855
+ continue
1856
+ self.table.LookupList.Lookup[i].closure_glyphs(s)
1857
+ if orig_glyphs == s.glyphs:
1858
+ break
1859
+ del s._doneLookups
1860
+ del s.table
1861
+
1862
+
1863
+ @_add_method(ttLib.getTableClass("GSUB"), ttLib.getTableClass("GPOS"))
1864
+ def subset_glyphs(self, s):
1865
+ s.glyphs = s.glyphs_gsubed
1866
+ if self.table.LookupList:
1867
+ lookup_indices = self.table.LookupList.subset_glyphs(s)
1868
+ else:
1869
+ lookup_indices = []
1870
+ self.subset_lookups(lookup_indices)
1871
+ return True
1872
+
1873
+
1874
+ @_add_method(ttLib.getTableClass("GSUB"), ttLib.getTableClass("GPOS"))
1875
+ def retain_empty_scripts(self):
1876
+ # https://github.com/fonttools/fonttools/issues/518
1877
+ # https://bugzilla.mozilla.org/show_bug.cgi?id=1080739#c15
1878
+ return self.__class__ == ttLib.getTableClass("GSUB")
1879
+
1880
+
1881
+ @_add_method(ttLib.getTableClass("GSUB"), ttLib.getTableClass("GPOS"))
1882
+ def subset_lookups(self, lookup_indices):
1883
+ """Retains specified lookups, then removes empty features, language
1884
+ systems, and scripts."""
1885
+ if self.table.LookupList:
1886
+ self.table.LookupList.subset_lookups(lookup_indices)
1887
+ if self.table.FeatureList:
1888
+ feature_indices = self.table.FeatureList.subset_lookups(lookup_indices)
1889
+ else:
1890
+ feature_indices = []
1891
+ if getattr(self.table, "FeatureVariations", None):
1892
+ feature_indices += self.table.FeatureVariations.subset_lookups(lookup_indices)
1893
+ feature_indices = _uniq_sort(feature_indices)
1894
+ if self.table.FeatureList:
1895
+ self.table.FeatureList.subset_features(feature_indices)
1896
+ if getattr(self.table, "FeatureVariations", None):
1897
+ self.table.FeatureVariations.subset_features(feature_indices)
1898
+ if self.table.ScriptList:
1899
+ self.table.ScriptList.subset_features(
1900
+ feature_indices, self.retain_empty_scripts()
1901
+ )
1902
+
1903
+
1904
+ @_add_method(ttLib.getTableClass("GSUB"), ttLib.getTableClass("GPOS"))
1905
+ def neuter_lookups(self, lookup_indices):
1906
+ """Sets lookups not in lookup_indices to None."""
1907
+ if self.table.LookupList:
1908
+ self.table.LookupList.neuter_lookups(lookup_indices)
1909
+
1910
+
1911
+ @_add_method(ttLib.getTableClass("GSUB"), ttLib.getTableClass("GPOS"))
1912
+ def prune_lookups(self, remap=True):
1913
+ """Remove (default) or neuter unreferenced lookups"""
1914
+ if self.table.ScriptList:
1915
+ feature_indices = self.table.ScriptList.collect_features()
1916
+ else:
1917
+ feature_indices = []
1918
+ if self.table.FeatureList:
1919
+ lookup_indices = self.table.FeatureList.collect_lookups(feature_indices)
1920
+ else:
1921
+ lookup_indices = []
1922
+ if getattr(self.table, "FeatureVariations", None):
1923
+ lookup_indices += self.table.FeatureVariations.collect_lookups(feature_indices)
1924
+ lookup_indices = _uniq_sort(lookup_indices)
1925
+ if self.table.LookupList:
1926
+ lookup_indices = self.table.LookupList.closure_lookups(lookup_indices)
1927
+ else:
1928
+ lookup_indices = []
1929
+ if remap:
1930
+ self.subset_lookups(lookup_indices)
1931
+ else:
1932
+ self.neuter_lookups(lookup_indices)
1933
+
1934
+
1935
+ @_add_method(ttLib.getTableClass("GSUB"), ttLib.getTableClass("GPOS"))
1936
+ def subset_feature_tags(self, feature_tags):
1937
+ if self.table.FeatureList:
1938
+ feature_indices = [
1939
+ i
1940
+ for i, f in enumerate(self.table.FeatureList.FeatureRecord)
1941
+ if f.FeatureTag in feature_tags
1942
+ ]
1943
+ self.table.FeatureList.subset_features(feature_indices)
1944
+ if getattr(self.table, "FeatureVariations", None):
1945
+ self.table.FeatureVariations.subset_features(feature_indices)
1946
+ else:
1947
+ feature_indices = []
1948
+ if self.table.ScriptList:
1949
+ self.table.ScriptList.subset_features(
1950
+ feature_indices, self.retain_empty_scripts()
1951
+ )
1952
+
1953
+
1954
+ @_add_method(ttLib.getTableClass("GSUB"), ttLib.getTableClass("GPOS"))
1955
+ def subset_script_tags(self, tags):
1956
+ langsys = {}
1957
+ script_tags = set()
1958
+ for tag in tags:
1959
+ script_tag, lang_tag = tag.split(".") if "." in tag else (tag, "*")
1960
+ script_tags.add(script_tag.ljust(4))
1961
+ langsys.setdefault(script_tag, set()).add(lang_tag.ljust(4))
1962
+
1963
+ if self.table.ScriptList:
1964
+ self.table.ScriptList.ScriptRecord = [
1965
+ s for s in self.table.ScriptList.ScriptRecord if s.ScriptTag in script_tags
1966
+ ]
1967
+ self.table.ScriptList.ScriptCount = len(self.table.ScriptList.ScriptRecord)
1968
+
1969
+ for record in self.table.ScriptList.ScriptRecord:
1970
+ if record.ScriptTag in langsys and "* " not in langsys[record.ScriptTag]:
1971
+ record.Script.LangSysRecord = [
1972
+ l
1973
+ for l in record.Script.LangSysRecord
1974
+ if l.LangSysTag in langsys[record.ScriptTag]
1975
+ ]
1976
+ record.Script.LangSysCount = len(record.Script.LangSysRecord)
1977
+ if "dflt" not in langsys[record.ScriptTag]:
1978
+ record.Script.DefaultLangSys = None
1979
+
1980
+
1981
+ @_add_method(ttLib.getTableClass("GSUB"), ttLib.getTableClass("GPOS"))
1982
+ def prune_features(self):
1983
+ """Remove unreferenced features"""
1984
+ if self.table.ScriptList:
1985
+ feature_indices = self.table.ScriptList.collect_features()
1986
+ else:
1987
+ feature_indices = []
1988
+ if self.table.FeatureList:
1989
+ self.table.FeatureList.subset_features(feature_indices)
1990
+ if getattr(self.table, "FeatureVariations", None):
1991
+ self.table.FeatureVariations.subset_features(feature_indices)
1992
+ if self.table.ScriptList:
1993
+ self.table.ScriptList.subset_features(
1994
+ feature_indices, self.retain_empty_scripts()
1995
+ )
1996
+
1997
+
1998
+ @_add_method(ttLib.getTableClass("GSUB"), ttLib.getTableClass("GPOS"))
1999
+ def prune_pre_subset(self, font, options):
2000
+ # Drop undesired features
2001
+ if "*" not in options.layout_scripts:
2002
+ self.subset_script_tags(options.layout_scripts)
2003
+ if "*" not in options.layout_features:
2004
+ self.subset_feature_tags(options.layout_features)
2005
+ # Neuter unreferenced lookups
2006
+ self.prune_lookups(remap=False)
2007
+ return True
2008
+
2009
+
2010
+ @_add_method(ttLib.getTableClass("GSUB"), ttLib.getTableClass("GPOS"))
2011
+ def remove_redundant_langsys(self):
2012
+ table = self.table
2013
+ if not table.ScriptList or not table.FeatureList:
2014
+ return
2015
+
2016
+ features = table.FeatureList.FeatureRecord
2017
+
2018
+ for s in table.ScriptList.ScriptRecord:
2019
+ d = s.Script.DefaultLangSys
2020
+ if not d:
2021
+ continue
2022
+ for lr in s.Script.LangSysRecord[:]:
2023
+ l = lr.LangSys
2024
+ # Compare d and l
2025
+ if len(d.FeatureIndex) != len(l.FeatureIndex):
2026
+ continue
2027
+ if (d.ReqFeatureIndex == 65535) != (l.ReqFeatureIndex == 65535):
2028
+ continue
2029
+
2030
+ if d.ReqFeatureIndex != 65535:
2031
+ if features[d.ReqFeatureIndex] != features[l.ReqFeatureIndex]:
2032
+ continue
2033
+
2034
+ for i in range(len(d.FeatureIndex)):
2035
+ if features[d.FeatureIndex[i]] != features[l.FeatureIndex[i]]:
2036
+ break
2037
+ else:
2038
+ # LangSys and default are equal; delete LangSys
2039
+ s.Script.LangSysRecord.remove(lr)
2040
+
2041
+
2042
+ @_add_method(ttLib.getTableClass("GSUB"), ttLib.getTableClass("GPOS"))
2043
+ def prune_post_subset(self, font, options):
2044
+ table = self.table
2045
+
2046
+ self.prune_lookups() # XXX Is this actually needed?!
2047
+
2048
+ if table.LookupList:
2049
+ table.LookupList.prune_post_subset(font, options)
2050
+ # XXX Next two lines disabled because OTS is stupid and
2051
+ # doesn't like NULL offsets here.
2052
+ # if not table.LookupList.Lookup:
2053
+ # table.LookupList = None
2054
+
2055
+ if not table.LookupList:
2056
+ table.FeatureList = None
2057
+
2058
+ if table.FeatureList:
2059
+ self.remove_redundant_langsys()
2060
+ # Remove unreferenced features
2061
+ self.prune_features()
2062
+
2063
+ # XXX Next two lines disabled because OTS is stupid and
2064
+ # doesn't like NULL offsets here.
2065
+ # if table.FeatureList and not table.FeatureList.FeatureRecord:
2066
+ # table.FeatureList = None
2067
+
2068
+ # Never drop scripts themselves as them just being available
2069
+ # holds semantic significance.
2070
+ # XXX Next two lines disabled because OTS is stupid and
2071
+ # doesn't like NULL offsets here.
2072
+ # if table.ScriptList and not table.ScriptList.ScriptRecord:
2073
+ # table.ScriptList = None
2074
+
2075
+ if hasattr(table, "FeatureVariations"):
2076
+ # drop FeatureVariations if there are no features to substitute
2077
+ if table.FeatureVariations and not (
2078
+ table.FeatureList and table.FeatureVariations.FeatureVariationRecord
2079
+ ):
2080
+ table.FeatureVariations = None
2081
+
2082
+ # downgrade table version if there are no FeatureVariations
2083
+ if not table.FeatureVariations and table.Version == 0x00010001:
2084
+ table.Version = 0x00010000
2085
+
2086
+ return True
2087
+
2088
+
2089
+ @_add_method(ttLib.getTableClass("GDEF"))
2090
+ def subset_glyphs(self, s):
2091
+ glyphs = s.glyphs_gsubed
2092
+ table = self.table
2093
+ if table.LigCaretList:
2094
+ indices = table.LigCaretList.Coverage.subset(glyphs)
2095
+ table.LigCaretList.LigGlyph = _list_subset(table.LigCaretList.LigGlyph, indices)
2096
+ table.LigCaretList.LigGlyphCount = len(table.LigCaretList.LigGlyph)
2097
+ if table.MarkAttachClassDef:
2098
+ table.MarkAttachClassDef.classDefs = {
2099
+ g: v for g, v in table.MarkAttachClassDef.classDefs.items() if g in glyphs
2100
+ }
2101
+ if table.GlyphClassDef:
2102
+ table.GlyphClassDef.classDefs = {
2103
+ g: v for g, v in table.GlyphClassDef.classDefs.items() if g in glyphs
2104
+ }
2105
+ if table.AttachList:
2106
+ indices = table.AttachList.Coverage.subset(glyphs)
2107
+ GlyphCount = table.AttachList.GlyphCount
2108
+ table.AttachList.AttachPoint = [
2109
+ table.AttachList.AttachPoint[i] for i in indices if i < GlyphCount
2110
+ ]
2111
+ table.AttachList.GlyphCount = len(table.AttachList.AttachPoint)
2112
+ if hasattr(table, "MarkGlyphSetsDef") and table.MarkGlyphSetsDef:
2113
+ markGlyphSets = table.MarkGlyphSetsDef
2114
+ for coverage in markGlyphSets.Coverage:
2115
+ if coverage:
2116
+ coverage.subset(glyphs)
2117
+
2118
+ s.used_mark_sets = [i for i, c in enumerate(markGlyphSets.Coverage) if c.glyphs]
2119
+ markGlyphSets.Coverage = [c for c in markGlyphSets.Coverage if c.glyphs]
2120
+
2121
+ return True
2122
+
2123
+
2124
+ def _pruneGDEF(font):
2125
+ if "GDEF" not in font:
2126
+ return
2127
+ gdef = font["GDEF"]
2128
+ table = gdef.table
2129
+ if not hasattr(table, "VarStore"):
2130
+ return
2131
+
2132
+ store = table.VarStore
2133
+
2134
+ usedVarIdxes = set()
2135
+
2136
+ # Collect.
2137
+ table.collect_device_varidxes(usedVarIdxes)
2138
+ if "GPOS" in font:
2139
+ font["GPOS"].table.collect_device_varidxes(usedVarIdxes)
2140
+
2141
+ # Subset.
2142
+ varidx_map = store.subset_varidxes(usedVarIdxes)
2143
+
2144
+ # Map.
2145
+ table.remap_device_varidxes(varidx_map)
2146
+ if "GPOS" in font:
2147
+ font["GPOS"].table.remap_device_varidxes(varidx_map)
2148
+
2149
+
2150
+ @_add_method(ttLib.getTableClass("GDEF"))
2151
+ def prune_post_subset(self, font, options):
2152
+ table = self.table
2153
+ # XXX check these against OTS
2154
+ if table.LigCaretList and not table.LigCaretList.LigGlyphCount:
2155
+ table.LigCaretList = None
2156
+ if table.MarkAttachClassDef and not table.MarkAttachClassDef.classDefs:
2157
+ table.MarkAttachClassDef = None
2158
+ if table.GlyphClassDef and not table.GlyphClassDef.classDefs:
2159
+ table.GlyphClassDef = None
2160
+ if table.AttachList and not table.AttachList.GlyphCount:
2161
+ table.AttachList = None
2162
+ if hasattr(table, "VarStore"):
2163
+ _pruneGDEF(font)
2164
+ if table.VarStore.VarDataCount == 0:
2165
+ if table.Version == 0x00010003:
2166
+ table.Version = 0x00010002
2167
+ if (
2168
+ not hasattr(table, "MarkGlyphSetsDef")
2169
+ or not table.MarkGlyphSetsDef
2170
+ or not table.MarkGlyphSetsDef.Coverage
2171
+ ):
2172
+ table.MarkGlyphSetsDef = None
2173
+ if table.Version == 0x00010002:
2174
+ table.Version = 0x00010000
2175
+ return bool(
2176
+ table.LigCaretList
2177
+ or table.MarkAttachClassDef
2178
+ or table.GlyphClassDef
2179
+ or table.AttachList
2180
+ or (table.Version >= 0x00010002 and table.MarkGlyphSetsDef)
2181
+ or (table.Version >= 0x00010003 and table.VarStore)
2182
+ )
2183
+
2184
+
2185
+ @_add_method(ttLib.getTableClass("kern"))
2186
+ def prune_pre_subset(self, font, options):
2187
+ # Prune unknown kern table types
2188
+ self.kernTables = [t for t in self.kernTables if hasattr(t, "kernTable")]
2189
+ return bool(self.kernTables)
2190
+
2191
+
2192
+ @_add_method(ttLib.getTableClass("kern"))
2193
+ def subset_glyphs(self, s):
2194
+ glyphs = s.glyphs_gsubed
2195
+ for t in self.kernTables:
2196
+ t.kernTable = {
2197
+ (a, b): v
2198
+ for (a, b), v in t.kernTable.items()
2199
+ if a in glyphs and b in glyphs
2200
+ }
2201
+ self.kernTables = [t for t in self.kernTables if t.kernTable]
2202
+ return bool(self.kernTables)
2203
+
2204
+
2205
+ @_add_method(ttLib.getTableClass("vmtx"))
2206
+ def subset_glyphs(self, s):
2207
+ self.metrics = _dict_subset(self.metrics, s.glyphs)
2208
+ for g in s.glyphs_emptied:
2209
+ self.metrics[g] = (0, 0)
2210
+ return bool(self.metrics)
2211
+
2212
+
2213
+ @_add_method(ttLib.getTableClass("hmtx"))
2214
+ def subset_glyphs(self, s):
2215
+ self.metrics = _dict_subset(self.metrics, s.glyphs)
2216
+ for g in s.glyphs_emptied:
2217
+ self.metrics[g] = (0, 0)
2218
+ return True # Required table
2219
+
2220
+
2221
+ @_add_method(ttLib.getTableClass("hdmx"))
2222
+ def subset_glyphs(self, s):
2223
+ self.hdmx = {sz: _dict_subset(l, s.glyphs) for sz, l in self.hdmx.items()}
2224
+ for sz in self.hdmx:
2225
+ for g in s.glyphs_emptied:
2226
+ self.hdmx[sz][g] = 0
2227
+ return bool(self.hdmx)
2228
+
2229
+
2230
+ @_add_method(ttLib.getTableClass("ankr"))
2231
+ def subset_glyphs(self, s):
2232
+ table = self.table.AnchorPoints
2233
+ assert table.Format == 0, "unknown 'ankr' format %s" % table.Format
2234
+ table.Anchors = {
2235
+ glyph: table.Anchors[glyph] for glyph in s.glyphs if glyph in table.Anchors
2236
+ }
2237
+ return len(table.Anchors) > 0
2238
+
2239
+
2240
+ @_add_method(ttLib.getTableClass("bsln"))
2241
+ def closure_glyphs(self, s):
2242
+ table = self.table.Baseline
2243
+ if table.Format in (2, 3):
2244
+ s.glyphs.add(table.StandardGlyph)
2245
+
2246
+
2247
+ @_add_method(ttLib.getTableClass("bsln"))
2248
+ def subset_glyphs(self, s):
2249
+ table = self.table.Baseline
2250
+ if table.Format in (1, 3):
2251
+ baselines = {
2252
+ glyph: table.BaselineValues.get(glyph, table.DefaultBaseline)
2253
+ for glyph in s.glyphs
2254
+ }
2255
+ if len(baselines) > 0:
2256
+ mostCommon, _cnt = Counter(baselines.values()).most_common(1)[0]
2257
+ table.DefaultBaseline = mostCommon
2258
+ baselines = {glyph: b for glyph, b in baselines.items() if b != mostCommon}
2259
+ if len(baselines) > 0:
2260
+ table.BaselineValues = baselines
2261
+ else:
2262
+ table.Format = {1: 0, 3: 2}[table.Format]
2263
+ del table.BaselineValues
2264
+ return True
2265
+
2266
+
2267
+ @_add_method(ttLib.getTableClass("lcar"))
2268
+ def subset_glyphs(self, s):
2269
+ table = self.table.LigatureCarets
2270
+ if table.Format in (0, 1):
2271
+ table.Carets = {
2272
+ glyph: table.Carets[glyph] for glyph in s.glyphs if glyph in table.Carets
2273
+ }
2274
+ return len(table.Carets) > 0
2275
+ else:
2276
+ assert False, "unknown 'lcar' format %s" % table.Format
2277
+
2278
+
2279
+ @_add_method(ttLib.getTableClass("gvar"))
2280
+ def prune_pre_subset(self, font, options):
2281
+ if options.notdef_glyph and not options.notdef_outline:
2282
+ self.variations[font.glyphOrder[0]] = []
2283
+ return True
2284
+
2285
+
2286
+ @_add_method(ttLib.getTableClass("gvar"))
2287
+ def subset_glyphs(self, s):
2288
+ self.variations = _dict_subset(self.variations, s.glyphs)
2289
+ self.glyphCount = len(self.variations)
2290
+ return bool(self.variations)
2291
+
2292
+
2293
+ def _remap_index_map(s, varidx_map, table_map):
2294
+ map_ = {k: varidx_map[v] for k, v in table_map.mapping.items()}
2295
+ # Emptied glyphs are remapped to:
2296
+ # if GID <= last retained GID, 0/0: delta set for 0/0 is expected to exist & zeros compress well
2297
+ # if GID > last retained GID, major/minor of the last retained glyph: will be optimized out by table compiler
2298
+ last_idx = varidx_map[table_map.mapping[s.last_retained_glyph]]
2299
+ for g, i in s.reverseEmptiedGlyphMap.items():
2300
+ map_[g] = last_idx if i > s.last_retained_order else 0
2301
+ return map_
2302
+
2303
+
2304
+ @_add_method(ttLib.getTableClass("HVAR"))
2305
+ def subset_glyphs(self, s):
2306
+ table = self.table
2307
+
2308
+ used = set()
2309
+ advIdxes_ = set()
2310
+ retainAdvMap = False
2311
+
2312
+ if table.AdvWidthMap:
2313
+ table.AdvWidthMap.mapping = _dict_subset(table.AdvWidthMap.mapping, s.glyphs)
2314
+ used.update(table.AdvWidthMap.mapping.values())
2315
+ else:
2316
+ used.update(s.reverseOrigGlyphMap.values())
2317
+ advIdxes_ = used.copy()
2318
+ retainAdvMap = s.options.retain_gids
2319
+
2320
+ if table.LsbMap:
2321
+ table.LsbMap.mapping = _dict_subset(table.LsbMap.mapping, s.glyphs)
2322
+ used.update(table.LsbMap.mapping.values())
2323
+ if table.RsbMap:
2324
+ table.RsbMap.mapping = _dict_subset(table.RsbMap.mapping, s.glyphs)
2325
+ used.update(table.RsbMap.mapping.values())
2326
+
2327
+ varidx_map = table.VarStore.subset_varidxes(
2328
+ used, retainFirstMap=retainAdvMap, advIdxes=advIdxes_
2329
+ )
2330
+
2331
+ if table.AdvWidthMap:
2332
+ table.AdvWidthMap.mapping = _remap_index_map(s, varidx_map, table.AdvWidthMap)
2333
+ if table.LsbMap:
2334
+ table.LsbMap.mapping = _remap_index_map(s, varidx_map, table.LsbMap)
2335
+ if table.RsbMap:
2336
+ table.RsbMap.mapping = _remap_index_map(s, varidx_map, table.RsbMap)
2337
+
2338
+ # TODO Return emptiness...
2339
+ return True
2340
+
2341
+
2342
+ @_add_method(ttLib.getTableClass("VVAR"))
2343
+ def subset_glyphs(self, s):
2344
+ table = self.table
2345
+
2346
+ used = set()
2347
+ advIdxes_ = set()
2348
+ retainAdvMap = False
2349
+
2350
+ if table.AdvHeightMap:
2351
+ table.AdvHeightMap.mapping = _dict_subset(table.AdvHeightMap.mapping, s.glyphs)
2352
+ used.update(table.AdvHeightMap.mapping.values())
2353
+ else:
2354
+ used.update(s.reverseOrigGlyphMap.values())
2355
+ advIdxes_ = used.copy()
2356
+ retainAdvMap = s.options.retain_gids
2357
+
2358
+ if table.TsbMap:
2359
+ table.TsbMap.mapping = _dict_subset(table.TsbMap.mapping, s.glyphs)
2360
+ used.update(table.TsbMap.mapping.values())
2361
+ if table.BsbMap:
2362
+ table.BsbMap.mapping = _dict_subset(table.BsbMap.mapping, s.glyphs)
2363
+ used.update(table.BsbMap.mapping.values())
2364
+ if table.VOrgMap:
2365
+ table.VOrgMap.mapping = _dict_subset(table.VOrgMap.mapping, s.glyphs)
2366
+ used.update(table.VOrgMap.mapping.values())
2367
+
2368
+ varidx_map = table.VarStore.subset_varidxes(
2369
+ used, retainFirstMap=retainAdvMap, advIdxes=advIdxes_
2370
+ )
2371
+
2372
+ if table.AdvHeightMap:
2373
+ table.AdvHeightMap.mapping = _remap_index_map(s, varidx_map, table.AdvHeightMap)
2374
+ if table.TsbMap:
2375
+ table.TsbMap.mapping = _remap_index_map(s, varidx_map, table.TsbMap)
2376
+ if table.BsbMap:
2377
+ table.BsbMap.mapping = _remap_index_map(s, varidx_map, table.BsbMap)
2378
+ if table.VOrgMap:
2379
+ table.VOrgMap.mapping = _remap_index_map(s, varidx_map, table.VOrgMap)
2380
+
2381
+ # TODO Return emptiness...
2382
+ return True
2383
+
2384
+
2385
+ @_add_method(ttLib.getTableClass("VORG"))
2386
+ def subset_glyphs(self, s):
2387
+ self.VOriginRecords = {
2388
+ g: v for g, v in self.VOriginRecords.items() if g in s.glyphs
2389
+ }
2390
+ self.numVertOriginYMetrics = len(self.VOriginRecords)
2391
+ return True # Never drop; has default metrics
2392
+
2393
+
2394
+ @_add_method(ttLib.getTableClass("opbd"))
2395
+ def subset_glyphs(self, s):
2396
+ table = self.table.OpticalBounds
2397
+ if table.Format == 0:
2398
+ table.OpticalBoundsDeltas = {
2399
+ glyph: table.OpticalBoundsDeltas[glyph]
2400
+ for glyph in s.glyphs
2401
+ if glyph in table.OpticalBoundsDeltas
2402
+ }
2403
+ return len(table.OpticalBoundsDeltas) > 0
2404
+ elif table.Format == 1:
2405
+ table.OpticalBoundsPoints = {
2406
+ glyph: table.OpticalBoundsPoints[glyph]
2407
+ for glyph in s.glyphs
2408
+ if glyph in table.OpticalBoundsPoints
2409
+ }
2410
+ return len(table.OpticalBoundsPoints) > 0
2411
+ else:
2412
+ assert False, "unknown 'opbd' format %s" % table.Format
2413
+
2414
+
2415
+ @_add_method(ttLib.getTableClass("post"))
2416
+ def prune_pre_subset(self, font, options):
2417
+ if not options.glyph_names:
2418
+ self.formatType = 3.0
2419
+ return True # Required table
2420
+
2421
+
2422
+ @_add_method(ttLib.getTableClass("post"))
2423
+ def subset_glyphs(self, s):
2424
+ self.extraNames = [] # This seems to do it
2425
+ return True # Required table
2426
+
2427
+
2428
+ @_add_method(ttLib.getTableClass("prop"))
2429
+ def subset_glyphs(self, s):
2430
+ prop = self.table.GlyphProperties
2431
+ if prop.Format == 0:
2432
+ return prop.DefaultProperties != 0
2433
+ elif prop.Format == 1:
2434
+ prop.Properties = {
2435
+ g: prop.Properties.get(g, prop.DefaultProperties) for g in s.glyphs
2436
+ }
2437
+ mostCommon, _cnt = Counter(prop.Properties.values()).most_common(1)[0]
2438
+ prop.DefaultProperties = mostCommon
2439
+ prop.Properties = {
2440
+ g: prop for g, prop in prop.Properties.items() if prop != mostCommon
2441
+ }
2442
+ if len(prop.Properties) == 0:
2443
+ del prop.Properties
2444
+ prop.Format = 0
2445
+ return prop.DefaultProperties != 0
2446
+ return True
2447
+ else:
2448
+ assert False, "unknown 'prop' format %s" % prop.Format
2449
+
2450
+
2451
+ def _paint_glyph_names(paint, colr):
2452
+ result = set()
2453
+
2454
+ def callback(paint):
2455
+ if paint.Format in {
2456
+ otTables.PaintFormat.PaintGlyph,
2457
+ otTables.PaintFormat.PaintColrGlyph,
2458
+ }:
2459
+ result.add(paint.Glyph)
2460
+
2461
+ paint.traverse(colr, callback)
2462
+ return result
2463
+
2464
+
2465
+ @_add_method(ttLib.getTableClass("COLR"))
2466
+ def closure_glyphs(self, s):
2467
+ if self.version > 0:
2468
+ # on decompiling COLRv1, we only keep around the raw otTables
2469
+ # but for subsetting we need dicts with fully decompiled layers;
2470
+ # we store them temporarily in the C_O_L_R_ instance and delete
2471
+ # them after we have finished subsetting.
2472
+ self.ColorLayers = self._decompileColorLayersV0(self.table)
2473
+ self.ColorLayersV1 = {
2474
+ rec.BaseGlyph: rec.Paint
2475
+ for rec in self.table.BaseGlyphList.BaseGlyphPaintRecord
2476
+ }
2477
+
2478
+ decompose = s.glyphs
2479
+ while decompose:
2480
+ layers = set()
2481
+ for g in decompose:
2482
+ for layer in self.ColorLayers.get(g, []):
2483
+ layers.add(layer.name)
2484
+
2485
+ if self.version > 0:
2486
+ paint = self.ColorLayersV1.get(g)
2487
+ if paint is not None:
2488
+ layers.update(_paint_glyph_names(paint, self.table))
2489
+
2490
+ layers -= s.glyphs
2491
+ s.glyphs.update(layers)
2492
+ decompose = layers
2493
+
2494
+
2495
+ @_add_method(ttLib.getTableClass("COLR"))
2496
+ def subset_glyphs(self, s):
2497
+ from fontTools.colorLib.unbuilder import unbuildColrV1
2498
+ from fontTools.colorLib.builder import buildColrV1, populateCOLRv0
2499
+
2500
+ # only include glyphs after COLR closure, which in turn comes after cmap and GSUB
2501
+ # closure, but importantly before glyf/CFF closures. COLR layers can refer to
2502
+ # composite glyphs, and that's ok, since glyf/CFF closures happen after COLR closure
2503
+ # and take care of those. If we also included glyphs resulting from glyf/CFF closures
2504
+ # when deciding which COLR base glyphs to retain, then we may end up with a situation
2505
+ # whereby a COLR base glyph is kept, not because directly requested (cmap)
2506
+ # or substituted (GSUB) or referenced by another COLRv1 PaintColrGlyph, but because
2507
+ # it corresponds to (has same GID as) a non-COLR glyph that happens to be used as a
2508
+ # component in glyf or CFF table. Best case scenario we retain more glyphs than
2509
+ # required; worst case we retain incomplete COLR records that try to reference
2510
+ # glyphs that are no longer in the final subset font.
2511
+ # https://github.com/fonttools/fonttools/issues/2461
2512
+ s.glyphs = s.glyphs_colred
2513
+
2514
+ self.ColorLayers = {
2515
+ g: self.ColorLayers[g] for g in s.glyphs if g in self.ColorLayers
2516
+ }
2517
+ if self.version == 0:
2518
+ return bool(self.ColorLayers)
2519
+
2520
+ colorGlyphsV1 = unbuildColrV1(self.table.LayerList, self.table.BaseGlyphList)
2521
+ self.table.LayerList, self.table.BaseGlyphList = buildColrV1(
2522
+ {g: colorGlyphsV1[g] for g in colorGlyphsV1 if g in s.glyphs}
2523
+ )
2524
+ del self.ColorLayersV1
2525
+
2526
+ if self.table.ClipList is not None:
2527
+ clips = self.table.ClipList.clips
2528
+ self.table.ClipList.clips = {g: clips[g] for g in clips if g in s.glyphs}
2529
+
2530
+ layersV0 = self.ColorLayers
2531
+ if not self.table.BaseGlyphList.BaseGlyphPaintRecord:
2532
+ # no more COLRv1 glyphs: downgrade to version 0
2533
+ self.version = 0
2534
+ del self.table
2535
+ return bool(layersV0)
2536
+
2537
+ populateCOLRv0(
2538
+ self.table,
2539
+ {g: [(layer.name, layer.colorID) for layer in layersV0[g]] for g in layersV0},
2540
+ )
2541
+ del self.ColorLayers
2542
+
2543
+ # TODO: also prune ununsed varIndices in COLR.VarStore
2544
+ return True
2545
+
2546
+
2547
+ @_add_method(ttLib.getTableClass("CPAL"))
2548
+ def prune_post_subset(self, font, options):
2549
+ # Keep whole "CPAL" if "SVG " is present as it may be referenced by the latter
2550
+ # via 'var(--color{palette_entry_index}, ...)' CSS color variables.
2551
+ # For now we just assume this is the case by the mere presence of "SVG " table,
2552
+ # for parsing SVG to collect all the used indices is too much work...
2553
+ # TODO(anthrotype): Do The Right Thing (TM).
2554
+ if "SVG " in font:
2555
+ return True
2556
+
2557
+ colr = font.get("COLR")
2558
+ if not colr: # drop CPAL if COLR was subsetted to empty
2559
+ return False
2560
+
2561
+ colors_by_index = defaultdict(list)
2562
+
2563
+ def collect_colors_by_index(paint):
2564
+ if hasattr(paint, "PaletteIndex"): # either solid colors...
2565
+ colors_by_index[paint.PaletteIndex].append(paint)
2566
+ elif hasattr(paint, "ColorLine"): # ... or gradient color stops
2567
+ for stop in paint.ColorLine.ColorStop:
2568
+ colors_by_index[stop.PaletteIndex].append(stop)
2569
+
2570
+ if colr.version == 0:
2571
+ for layers in colr.ColorLayers.values():
2572
+ for layer in layers:
2573
+ colors_by_index[layer.colorID].append(layer)
2574
+ else:
2575
+ if colr.table.LayerRecordArray:
2576
+ for layer in colr.table.LayerRecordArray.LayerRecord:
2577
+ colors_by_index[layer.PaletteIndex].append(layer)
2578
+ for record in colr.table.BaseGlyphList.BaseGlyphPaintRecord:
2579
+ record.Paint.traverse(colr.table, collect_colors_by_index)
2580
+
2581
+ # don't remap palette entry index 0xFFFF, this is always the foreground color
2582
+ # https://github.com/fonttools/fonttools/issues/2257
2583
+ retained_palette_indices = set(colors_by_index.keys()) - {0xFFFF}
2584
+ for palette in self.palettes:
2585
+ palette[:] = [c for i, c in enumerate(palette) if i in retained_palette_indices]
2586
+ assert len(palette) == len(retained_palette_indices)
2587
+
2588
+ for new_index, old_index in enumerate(sorted(retained_palette_indices)):
2589
+ for record in colors_by_index[old_index]:
2590
+ if hasattr(record, "colorID"): # v0
2591
+ record.colorID = new_index
2592
+ elif hasattr(record, "PaletteIndex"): # v1
2593
+ record.PaletteIndex = new_index
2594
+ else:
2595
+ raise AssertionError(record)
2596
+
2597
+ self.numPaletteEntries = len(self.palettes[0])
2598
+
2599
+ if self.version == 1:
2600
+ kept_labels = []
2601
+ for i, label in enumerate(self.paletteEntryLabels):
2602
+ if i in retained_palette_indices:
2603
+ kept_labels.append(label)
2604
+ self.paletteEntryLabels = kept_labels
2605
+ return bool(self.numPaletteEntries)
2606
+
2607
+
2608
+ @_add_method(otTables.MathGlyphConstruction)
2609
+ def closure_glyphs(self, glyphs):
2610
+ variants = set()
2611
+ for v in self.MathGlyphVariantRecord:
2612
+ variants.add(v.VariantGlyph)
2613
+ if self.GlyphAssembly:
2614
+ for p in self.GlyphAssembly.PartRecords:
2615
+ variants.add(p.glyph)
2616
+ return variants
2617
+
2618
+
2619
+ @_add_method(otTables.MathVariants)
2620
+ def closure_glyphs(self, s):
2621
+ glyphs = frozenset(s.glyphs)
2622
+ variants = set()
2623
+
2624
+ if self.VertGlyphCoverage:
2625
+ indices = self.VertGlyphCoverage.intersect(glyphs)
2626
+ for i in indices:
2627
+ variants.update(self.VertGlyphConstruction[i].closure_glyphs(glyphs))
2628
+
2629
+ if self.HorizGlyphCoverage:
2630
+ indices = self.HorizGlyphCoverage.intersect(glyphs)
2631
+ for i in indices:
2632
+ variants.update(self.HorizGlyphConstruction[i].closure_glyphs(glyphs))
2633
+
2634
+ s.glyphs.update(variants)
2635
+
2636
+
2637
+ @_add_method(ttLib.getTableClass("VARC"))
2638
+ def subset_glyphs(self, s):
2639
+ indices = self.table.Coverage.subset(s.glyphs)
2640
+ self.table.VarCompositeGlyphs.VarCompositeGlyph = _list_subset(
2641
+ self.table.VarCompositeGlyphs.VarCompositeGlyph, indices
2642
+ )
2643
+ return bool(self.table.VarCompositeGlyphs.VarCompositeGlyph)
2644
+
2645
+
2646
+ @_add_method(ttLib.getTableClass("VARC"))
2647
+ def closure_glyphs(self, s):
2648
+ if self.table.VarCompositeGlyphs is None:
2649
+ return
2650
+
2651
+ glyphMap = {glyphName: i for i, glyphName in enumerate(self.table.Coverage.glyphs)}
2652
+ glyphRecords = self.table.VarCompositeGlyphs.VarCompositeGlyph
2653
+
2654
+ glyphs = s.glyphs
2655
+ covered = set()
2656
+ new = set(glyphs)
2657
+ while new:
2658
+ oldNew = new
2659
+ new = set()
2660
+ for glyphName in oldNew:
2661
+ if glyphName in covered:
2662
+ continue
2663
+ idx = glyphMap.get(glyphName)
2664
+ if idx is None:
2665
+ continue
2666
+ glyph = glyphRecords[idx]
2667
+ for comp in glyph.components:
2668
+ name = comp.glyphName
2669
+ glyphs.add(name)
2670
+ if name not in covered:
2671
+ new.add(name)
2672
+
2673
+
2674
+ @_add_method(ttLib.getTableClass("VARC"))
2675
+ def prune_post_subset(self, font, options):
2676
+ table = self.table
2677
+
2678
+ store = table.MultiVarStore
2679
+ if store is not None:
2680
+ usedVarIdxes = set()
2681
+ table.collect_varidxes(usedVarIdxes)
2682
+ varidx_map = store.subset_varidxes(usedVarIdxes)
2683
+ table.remap_varidxes(varidx_map)
2684
+
2685
+ axisIndicesList = table.AxisIndicesList.Item
2686
+ if axisIndicesList is not None:
2687
+ usedIndices = set()
2688
+ for glyph in table.VarCompositeGlyphs.VarCompositeGlyph:
2689
+ for comp in glyph.components:
2690
+ if comp.axisIndicesIndex is not None:
2691
+ usedIndices.add(comp.axisIndicesIndex)
2692
+ usedIndices = sorted(usedIndices)
2693
+ table.AxisIndicesList.Item = _list_subset(axisIndicesList, usedIndices)
2694
+ mapping = {old: new for new, old in enumerate(usedIndices)}
2695
+ for glyph in table.VarCompositeGlyphs.VarCompositeGlyph:
2696
+ for comp in glyph.components:
2697
+ if comp.axisIndicesIndex is not None:
2698
+ comp.axisIndicesIndex = mapping[comp.axisIndicesIndex]
2699
+
2700
+ conditionList = table.ConditionList
2701
+ if conditionList is not None:
2702
+ conditionTables = conditionList.ConditionTable
2703
+ usedIndices = set()
2704
+ for glyph in table.VarCompositeGlyphs.VarCompositeGlyph:
2705
+ for comp in glyph.components:
2706
+ if comp.conditionIndex is not None:
2707
+ usedIndices.add(comp.conditionIndex)
2708
+ usedIndices = sorted(usedIndices)
2709
+ conditionList.ConditionTable = _list_subset(conditionTables, usedIndices)
2710
+ mapping = {old: new for new, old in enumerate(usedIndices)}
2711
+ for glyph in table.VarCompositeGlyphs.VarCompositeGlyph:
2712
+ for comp in glyph.components:
2713
+ if comp.conditionIndex is not None:
2714
+ comp.conditionIndex = mapping[comp.conditionIndex]
2715
+
2716
+ return True
2717
+
2718
+
2719
+ @_add_method(ttLib.getTableClass("MATH"))
2720
+ def closure_glyphs(self, s):
2721
+ if self.table.MathVariants:
2722
+ self.table.MathVariants.closure_glyphs(s)
2723
+
2724
+
2725
+ @_add_method(otTables.MathItalicsCorrectionInfo)
2726
+ def subset_glyphs(self, s):
2727
+ indices = self.Coverage.subset(s.glyphs)
2728
+ self.ItalicsCorrection = _list_subset(self.ItalicsCorrection, indices)
2729
+ self.ItalicsCorrectionCount = len(self.ItalicsCorrection)
2730
+ return bool(self.ItalicsCorrectionCount)
2731
+
2732
+
2733
+ @_add_method(otTables.MathTopAccentAttachment)
2734
+ def subset_glyphs(self, s):
2735
+ indices = self.TopAccentCoverage.subset(s.glyphs)
2736
+ self.TopAccentAttachment = _list_subset(self.TopAccentAttachment, indices)
2737
+ self.TopAccentAttachmentCount = len(self.TopAccentAttachment)
2738
+ return bool(self.TopAccentAttachmentCount)
2739
+
2740
+
2741
+ @_add_method(otTables.MathKernInfo)
2742
+ def subset_glyphs(self, s):
2743
+ indices = self.MathKernCoverage.subset(s.glyphs)
2744
+ self.MathKernInfoRecords = _list_subset(self.MathKernInfoRecords, indices)
2745
+ self.MathKernCount = len(self.MathKernInfoRecords)
2746
+ return bool(self.MathKernCount)
2747
+
2748
+
2749
+ @_add_method(otTables.MathGlyphInfo)
2750
+ def subset_glyphs(self, s):
2751
+ if self.MathItalicsCorrectionInfo:
2752
+ self.MathItalicsCorrectionInfo.subset_glyphs(s)
2753
+ if self.MathTopAccentAttachment:
2754
+ self.MathTopAccentAttachment.subset_glyphs(s)
2755
+ if self.MathKernInfo:
2756
+ self.MathKernInfo.subset_glyphs(s)
2757
+ if self.ExtendedShapeCoverage:
2758
+ self.ExtendedShapeCoverage.subset(s.glyphs)
2759
+ return True
2760
+
2761
+
2762
+ @_add_method(otTables.MathVariants)
2763
+ def subset_glyphs(self, s):
2764
+ if self.VertGlyphCoverage:
2765
+ indices = self.VertGlyphCoverage.subset(s.glyphs)
2766
+ self.VertGlyphConstruction = _list_subset(self.VertGlyphConstruction, indices)
2767
+ self.VertGlyphCount = len(self.VertGlyphConstruction)
2768
+
2769
+ if self.HorizGlyphCoverage:
2770
+ indices = self.HorizGlyphCoverage.subset(s.glyphs)
2771
+ self.HorizGlyphConstruction = _list_subset(self.HorizGlyphConstruction, indices)
2772
+ self.HorizGlyphCount = len(self.HorizGlyphConstruction)
2773
+
2774
+ return True
2775
+
2776
+
2777
+ @_add_method(ttLib.getTableClass("MATH"))
2778
+ def subset_glyphs(self, s):
2779
+ s.glyphs = s.glyphs_mathed
2780
+ if self.table.MathGlyphInfo:
2781
+ self.table.MathGlyphInfo.subset_glyphs(s)
2782
+ if self.table.MathVariants:
2783
+ self.table.MathVariants.subset_glyphs(s)
2784
+ return True
2785
+
2786
+
2787
+ @_add_method(ttLib.getTableModule("glyf").Glyph)
2788
+ def remapComponentsFast(self, glyphidmap):
2789
+ if not self.data or struct.unpack(">h", self.data[:2])[0] >= 0:
2790
+ return # Not composite
2791
+ data = self.data = bytearray(self.data)
2792
+ i = 10
2793
+ more = 1
2794
+ while more:
2795
+ flags = (data[i] << 8) | data[i + 1]
2796
+ glyphID = (data[i + 2] << 8) | data[i + 3]
2797
+ # Remap
2798
+ glyphID = glyphidmap[glyphID]
2799
+ data[i + 2] = glyphID >> 8
2800
+ data[i + 3] = glyphID & 0xFF
2801
+ i += 4
2802
+ flags = int(flags)
2803
+
2804
+ if flags & 0x0001:
2805
+ i += 4 # ARG_1_AND_2_ARE_WORDS
2806
+ else:
2807
+ i += 2
2808
+ if flags & 0x0008:
2809
+ i += 2 # WE_HAVE_A_SCALE
2810
+ elif flags & 0x0040:
2811
+ i += 4 # WE_HAVE_AN_X_AND_Y_SCALE
2812
+ elif flags & 0x0080:
2813
+ i += 8 # WE_HAVE_A_TWO_BY_TWO
2814
+ more = flags & 0x0020 # MORE_COMPONENTS
2815
+
2816
+
2817
+ @_add_method(ttLib.getTableClass("glyf"))
2818
+ def closure_glyphs(self, s):
2819
+ glyphSet = self.glyphs
2820
+ decompose = s.glyphs
2821
+ while decompose:
2822
+ components = set()
2823
+ for g in decompose:
2824
+ if g not in glyphSet:
2825
+ continue
2826
+ gl = glyphSet[g]
2827
+ for c in gl.getComponentNames(self):
2828
+ components.add(c)
2829
+ components -= s.glyphs
2830
+ s.glyphs.update(components)
2831
+ decompose = components
2832
+
2833
+
2834
+ @_add_method(ttLib.getTableClass("glyf"))
2835
+ def prune_pre_subset(self, font, options):
2836
+ if options.notdef_glyph and not options.notdef_outline:
2837
+ g = self[self.glyphOrder[0]]
2838
+ # Yay, easy!
2839
+ g.__dict__.clear()
2840
+ g.data = b""
2841
+ return True
2842
+
2843
+
2844
+ @_add_method(ttLib.getTableClass("glyf"))
2845
+ def subset_glyphs(self, s):
2846
+ self.glyphs = _dict_subset(self.glyphs, s.glyphs)
2847
+ if not s.options.retain_gids:
2848
+ indices = [i for i, g in enumerate(self.glyphOrder) if g in s.glyphs]
2849
+ glyphmap = {o: n for n, o in enumerate(indices)}
2850
+ for v in self.glyphs.values():
2851
+ if hasattr(v, "data"):
2852
+ v.remapComponentsFast(glyphmap)
2853
+ Glyph = ttLib.getTableModule("glyf").Glyph
2854
+ for g in s.glyphs_emptied:
2855
+ self.glyphs[g] = Glyph()
2856
+ self.glyphs[g].data = b""
2857
+ self.glyphOrder = [
2858
+ g for g in self.glyphOrder if g in s.glyphs or g in s.glyphs_emptied
2859
+ ]
2860
+ # Don't drop empty 'glyf' tables, otherwise 'loca' doesn't get subset.
2861
+ return True
2862
+
2863
+
2864
+ @_add_method(ttLib.getTableClass("glyf"))
2865
+ def prune_post_subset(self, font, options):
2866
+ remove_hinting = not options.hinting
2867
+ for v in self.glyphs.values():
2868
+ v.trim(remove_hinting=remove_hinting)
2869
+ return True
2870
+
2871
+
2872
+ @_add_method(ttLib.getTableClass("cmap"))
2873
+ def closure_glyphs(self, s):
2874
+ tables = [t for t in self.tables if t.isUnicode()]
2875
+
2876
+ # Closure unicodes, which for now is pulling in bidi mirrored variants
2877
+ if s.options.bidi_closure:
2878
+ additional_unicodes = set()
2879
+ for u in s.unicodes_requested:
2880
+ mirror_u = mirrored(u)
2881
+ if mirror_u is not None:
2882
+ additional_unicodes.add(mirror_u)
2883
+ s.unicodes_requested.update(additional_unicodes)
2884
+
2885
+ # Close glyphs
2886
+ for table in tables:
2887
+ if table.format == 14:
2888
+ for varSelector, cmap in table.uvsDict.items():
2889
+ if varSelector not in s.unicodes_requested:
2890
+ continue
2891
+ glyphs = {g for u, g in cmap if u in s.unicodes_requested}
2892
+ if None in glyphs:
2893
+ glyphs.remove(None)
2894
+ s.glyphs.update(glyphs)
2895
+ else:
2896
+ cmap = table.cmap
2897
+ intersection = s.unicodes_requested.intersection(cmap.keys())
2898
+ s.glyphs.update(cmap[u] for u in intersection)
2899
+
2900
+ # Calculate unicodes_missing
2901
+ s.unicodes_missing = s.unicodes_requested.copy()
2902
+ for table in tables:
2903
+ s.unicodes_missing.difference_update(table.cmap)
2904
+
2905
+
2906
+ @_add_method(ttLib.getTableClass("cmap"))
2907
+ def prune_pre_subset(self, font, options):
2908
+ if not options.legacy_cmap:
2909
+ # Drop non-Unicode / non-Symbol cmaps
2910
+ self.tables = [t for t in self.tables if t.isUnicode() or t.isSymbol()]
2911
+ if not options.symbol_cmap:
2912
+ self.tables = [t for t in self.tables if not t.isSymbol()]
2913
+ # TODO(behdad) Only keep one subtable?
2914
+ # For now, drop format=0 which can't be subset_glyphs easily?
2915
+ self.tables = [t for t in self.tables if t.format != 0]
2916
+ self.numSubTables = len(self.tables)
2917
+ return True # Required table
2918
+
2919
+
2920
+ @_add_method(ttLib.getTableClass("cmap"))
2921
+ def subset_glyphs(self, s):
2922
+ s.glyphs = None # We use s.glyphs_requested and s.unicodes_requested only
2923
+
2924
+ tables_format12_bmp = []
2925
+ table_plat0_enc3 = {} # Unicode platform, Unicode BMP only, keyed by language
2926
+ table_plat3_enc1 = {} # Windows platform, Unicode BMP, keyed by language
2927
+
2928
+ for t in self.tables:
2929
+ if t.platformID == 0 and t.platEncID == 3:
2930
+ table_plat0_enc3[t.language] = t
2931
+ if t.platformID == 3 and t.platEncID == 1:
2932
+ table_plat3_enc1[t.language] = t
2933
+
2934
+ if t.format == 14:
2935
+ # TODO(behdad) We drop all the default-UVS mappings
2936
+ # for glyphs_requested. So it's the caller's responsibility to make
2937
+ # sure those are included.
2938
+ t.uvsDict = {
2939
+ v: [
2940
+ (u, g)
2941
+ for u, g in l
2942
+ if g in s.glyphs_requested or u in s.unicodes_requested
2943
+ ]
2944
+ for v, l in t.uvsDict.items()
2945
+ if v in s.unicodes_requested
2946
+ }
2947
+ t.uvsDict = {v: l for v, l in t.uvsDict.items() if l}
2948
+ elif t.isUnicode():
2949
+ t.cmap = {
2950
+ u: g
2951
+ for u, g in t.cmap.items()
2952
+ if g in s.glyphs_requested or u in s.unicodes_requested
2953
+ }
2954
+ # Collect format 12 tables that hold only basic multilingual plane
2955
+ # codepoints.
2956
+ if t.format == 12 and t.cmap and max(t.cmap.keys()) < 0x10000:
2957
+ tables_format12_bmp.append(t)
2958
+ else:
2959
+ t.cmap = {u: g for u, g in t.cmap.items() if g in s.glyphs_requested}
2960
+
2961
+ # Fomat 12 tables are redundant if they contain just the same BMP codepoints
2962
+ # their little BMP-only encoding siblings contain.
2963
+ for t in tables_format12_bmp:
2964
+ if (
2965
+ t.platformID == 0 # Unicode platform
2966
+ and t.platEncID == 4 # Unicode full repertoire
2967
+ and t.language in table_plat0_enc3 # Have a BMP-only sibling?
2968
+ and table_plat0_enc3[t.language].cmap == t.cmap
2969
+ ):
2970
+ t.cmap.clear()
2971
+ elif (
2972
+ t.platformID == 3 # Windows platform
2973
+ and t.platEncID == 10 # Unicode full repertoire
2974
+ and t.language in table_plat3_enc1 # Have a BMP-only sibling?
2975
+ and table_plat3_enc1[t.language].cmap == t.cmap
2976
+ ):
2977
+ t.cmap.clear()
2978
+
2979
+ self.tables = [t for t in self.tables if (t.cmap if t.format != 14 else t.uvsDict)]
2980
+ self.numSubTables = len(self.tables)
2981
+ # TODO(behdad) Convert formats when needed.
2982
+ # In particular, if we have a format=12 without non-BMP
2983
+ # characters, convert it to format=4 if there's not one.
2984
+ return True # Required table
2985
+
2986
+
2987
+ @_add_method(ttLib.getTableClass("DSIG"))
2988
+ def prune_pre_subset(self, font, options):
2989
+ # Drop all signatures since they will be invalid
2990
+ self.usNumSigs = 0
2991
+ self.signatureRecords = []
2992
+ return True
2993
+
2994
+
2995
+ @_add_method(ttLib.getTableClass("maxp"))
2996
+ def prune_pre_subset(self, font, options):
2997
+ if not options.hinting:
2998
+ if self.tableVersion == 0x00010000:
2999
+ self.maxZones = 1
3000
+ self.maxTwilightPoints = 0
3001
+ self.maxStorage = 0
3002
+ self.maxFunctionDefs = 0
3003
+ self.maxInstructionDefs = 0
3004
+ self.maxStackElements = 0
3005
+ self.maxSizeOfInstructions = 0
3006
+ return True
3007
+
3008
+
3009
+ NAME_IDS_TO_OBFUSCATE = {1, 2, 3, 4, 6, 16, 17, 18}
3010
+
3011
+
3012
+ @_add_method(ttLib.getTableClass("name"))
3013
+ def prune_post_subset(self, font, options):
3014
+ visitor = NameRecordVisitor()
3015
+ visitor.visit(font)
3016
+ nameIDs = set(options.name_IDs) | visitor.seen
3017
+ if "*" in options.name_IDs:
3018
+ nameIDs |= {n.nameID for n in self.names if n.nameID < 256}
3019
+ self.names = [n for n in self.names if n.nameID in nameIDs]
3020
+ if not options.name_legacy:
3021
+ # TODO(behdad) Sometimes (eg Apple Color Emoji) there's only a macroman
3022
+ # entry for Latin and no Unicode names.
3023
+ self.names = [n for n in self.names if n.isUnicode()]
3024
+ # TODO(behdad) Option to keep only one platform's
3025
+ if "*" not in options.name_languages:
3026
+ # TODO(behdad) This is Windows-platform specific!
3027
+ self.names = [n for n in self.names if n.langID in options.name_languages]
3028
+ if options.obfuscate_names:
3029
+ namerecs = []
3030
+ # Preserve names to be scrambled or dropped elsewhere so that other
3031
+ # parts of the font don't break.
3032
+ needRemapping = visitor.seen.intersection(NAME_IDS_TO_OBFUSCATE)
3033
+ if needRemapping:
3034
+ _remap_select_name_ids(font, needRemapping)
3035
+ for n in self.names:
3036
+ if n.nameID in [1, 4]:
3037
+ n.string = ".\x7f".encode("utf_16_be") if n.isUnicode() else ".\x7f"
3038
+ elif n.nameID in [2, 6]:
3039
+ n.string = "\x7f".encode("utf_16_be") if n.isUnicode() else "\x7f"
3040
+ elif n.nameID == 3:
3041
+ n.string = ""
3042
+ elif n.nameID in [16, 17, 18]:
3043
+ continue
3044
+ namerecs.append(n)
3045
+ self.names = namerecs
3046
+ return True # Required table
3047
+
3048
+
3049
+ def _remap_select_name_ids(font: ttLib.TTFont, needRemapping: set[int]) -> None:
3050
+ """Remap a set of IDs so that the originals can be safely scrambled or
3051
+ dropped.
3052
+
3053
+ For each name record whose name id is in the `needRemapping` set, make a copy
3054
+ and allocate a new unused name id in the font-specific range (> 255).
3055
+
3056
+ Finally update references to these in the `fvar` and `STAT` tables.
3057
+ """
3058
+
3059
+ if "fvar" not in font and "STAT" not in font:
3060
+ return
3061
+
3062
+ name = font["name"]
3063
+
3064
+ # 1. Assign new IDs for names to be preserved.
3065
+ existingIds = {record.nameID for record in name.names}
3066
+ remapping = {}
3067
+ nextId = name._findUnusedNameID() - 1 # Should skip gaps in name IDs.
3068
+ for nameId in needRemapping:
3069
+ nextId += 1 # We should have complete freedom until 32767.
3070
+ assert nextId not in existingIds, "_findUnusedNameID did not skip gaps"
3071
+ if nextId > 32767:
3072
+ raise ValueError("Ran out of name IDs while trying to remap existing ones.")
3073
+ remapping[nameId] = nextId
3074
+
3075
+ # 2. Copy records to use the new ID. We can't rewrite them in place, because
3076
+ # that could make IDs 1 to 6 "disappear" from code that follows. Some
3077
+ # tools that produce EOT fonts expect them to exist, even when they're
3078
+ # scrambled. See https://github.com/fonttools/fonttools/issues/165.
3079
+ copiedRecords = []
3080
+ for record in name.names:
3081
+ if record.nameID not in needRemapping:
3082
+ continue
3083
+ recordCopy = makeName(
3084
+ record.string,
3085
+ remapping[record.nameID],
3086
+ record.platformID,
3087
+ record.platEncID,
3088
+ record.langID,
3089
+ )
3090
+ copiedRecords.append(recordCopy)
3091
+ name.names.extend(copiedRecords)
3092
+
3093
+ # 3. Rewrite the corresponding IDs in other tables. For now, care only about
3094
+ # STAT and fvar. If more tables need to be changed, consider adapting
3095
+ # NameRecordVisitor to rewrite IDs wherever it finds them.
3096
+ fvar = font.get("fvar")
3097
+ if fvar is not None:
3098
+ for axis in fvar.axes:
3099
+ axis.axisNameID = remapping.get(axis.axisNameID, axis.axisNameID)
3100
+ for instance in fvar.instances:
3101
+ nameID = instance.subfamilyNameID
3102
+ instance.subfamilyNameID = remapping.get(nameID, nameID)
3103
+ nameID = instance.postscriptNameID
3104
+ instance.postscriptNameID = remapping.get(nameID, nameID)
3105
+
3106
+ stat = font.get("STAT")
3107
+ if stat is None:
3108
+ return
3109
+ elidedNameID = stat.table.ElidedFallbackNameID
3110
+ stat.table.ElidedFallbackNameID = remapping.get(elidedNameID, elidedNameID)
3111
+ if stat.table.DesignAxisRecord:
3112
+ for axis in stat.table.DesignAxisRecord.Axis:
3113
+ axis.AxisNameID = remapping.get(axis.AxisNameID, axis.AxisNameID)
3114
+ if stat.table.AxisValueArray:
3115
+ for value in stat.table.AxisValueArray.AxisValue:
3116
+ value.ValueNameID = remapping.get(value.ValueNameID, value.ValueNameID)
3117
+
3118
+
3119
+ @_add_method(ttLib.getTableClass("head"))
3120
+ def prune_post_subset(self, font, options):
3121
+ # Force re-compiling head table, to update any recalculated values.
3122
+ return True
3123
+
3124
+
3125
+ # TODO(behdad) OS/2 ulCodePageRange?
3126
+ # TODO(behdad) Drop AAT tables.
3127
+ # TODO(behdad) Drop unneeded GSUB/GPOS Script/LangSys entries.
3128
+ # TODO(behdad) Drop empty GSUB/GPOS, and GDEF if no GSUB/GPOS left
3129
+ # TODO(behdad) Drop GDEF subitems if unused by lookups
3130
+ # TODO(behdad) Avoid recursing too much (in GSUB/GPOS and in CFF)
3131
+ # TODO(behdad) Text direction considerations.
3132
+ # TODO(behdad) Text script / language considerations.
3133
+ # TODO(behdad) Optionally drop 'kern' table if GPOS available
3134
+ # TODO(behdad) Implement --unicode='*' to choose all cmap'ed
3135
+ # TODO(behdad) Drop old-spec Indic scripts
3136
+
3137
+
3138
+ class Options(object):
3139
+ class OptionError(Exception):
3140
+ pass
3141
+
3142
+ class UnknownOptionError(OptionError):
3143
+ pass
3144
+
3145
+ # spaces in tag names (e.g. "SVG ", "cvt ") are stripped by the argument parser
3146
+ _drop_tables_default = [
3147
+ "BASE",
3148
+ "JSTF",
3149
+ "DSIG",
3150
+ "EBDT",
3151
+ "EBLC",
3152
+ "EBSC",
3153
+ "PCLT",
3154
+ "LTSH",
3155
+ ]
3156
+ _drop_tables_default += ["Feat", "Glat", "Gloc", "Silf", "Sill"] # Graphite
3157
+ _no_subset_tables_default = [
3158
+ "avar",
3159
+ "fvar",
3160
+ "gasp",
3161
+ "head",
3162
+ "hhea",
3163
+ "maxp",
3164
+ "vhea",
3165
+ "OS/2",
3166
+ "loca",
3167
+ "name",
3168
+ "cvt",
3169
+ "fpgm",
3170
+ "prep",
3171
+ "VDMX",
3172
+ "DSIG",
3173
+ "CPAL",
3174
+ "MVAR",
3175
+ "cvar",
3176
+ "STAT",
3177
+ ]
3178
+ _hinting_tables_default = ["cvt", "cvar", "fpgm", "prep", "hdmx", "VDMX"]
3179
+
3180
+ # Based on HarfBuzz shapers
3181
+ _layout_features_groups = {
3182
+ # Default shaper
3183
+ "common": ["rvrn", "ccmp", "liga", "locl", "mark", "mkmk", "rlig"],
3184
+ "fractions": ["frac", "numr", "dnom"],
3185
+ "horizontal": ["calt", "clig", "curs", "kern", "rclt"],
3186
+ "vertical": ["valt", "vert", "vkrn", "vpal", "vrt2"],
3187
+ "ltr": ["ltra", "ltrm"],
3188
+ "rtl": ["rtla", "rtlm"],
3189
+ "rand": ["rand"],
3190
+ "justify": ["jalt"],
3191
+ "private": ["Harf", "HARF", "Buzz", "BUZZ"],
3192
+ "east_asian_spacing": ["chws", "vchw", "halt", "vhal"],
3193
+ # Complex shapers
3194
+ "arabic": [
3195
+ "init",
3196
+ "medi",
3197
+ "fina",
3198
+ "isol",
3199
+ "med2",
3200
+ "fin2",
3201
+ "fin3",
3202
+ "cswh",
3203
+ "mset",
3204
+ "stch",
3205
+ ],
3206
+ "hangul": ["ljmo", "vjmo", "tjmo"],
3207
+ "tibetan": ["abvs", "blws", "abvm", "blwm"],
3208
+ "indic": [
3209
+ "nukt",
3210
+ "akhn",
3211
+ "rphf",
3212
+ "rkrf",
3213
+ "pref",
3214
+ "blwf",
3215
+ "half",
3216
+ "abvf",
3217
+ "pstf",
3218
+ "cfar",
3219
+ "vatu",
3220
+ "cjct",
3221
+ "init",
3222
+ "pres",
3223
+ "abvs",
3224
+ "blws",
3225
+ "psts",
3226
+ "haln",
3227
+ "dist",
3228
+ "abvm",
3229
+ "blwm",
3230
+ ],
3231
+ }
3232
+ _layout_features_default = _uniq_sort(
3233
+ sum(iter(_layout_features_groups.values()), [])
3234
+ )
3235
+
3236
+ def __init__(self, **kwargs):
3237
+ self.drop_tables = self._drop_tables_default[:]
3238
+ self.no_subset_tables = self._no_subset_tables_default[:]
3239
+ self.passthrough_tables = False # keep/drop tables we can't subset
3240
+ self.hinting_tables = self._hinting_tables_default[:]
3241
+ self.legacy_kern = False # drop 'kern' table if GPOS available
3242
+ self.layout_closure = True
3243
+ self.layout_features = self._layout_features_default[:]
3244
+ self.layout_scripts = ["*"]
3245
+ self.ignore_missing_glyphs = False
3246
+ self.ignore_missing_unicodes = True
3247
+ self.hinting = True
3248
+ self.glyph_names = False
3249
+ self.legacy_cmap = False
3250
+ self.symbol_cmap = False
3251
+ self.name_IDs = [
3252
+ 0,
3253
+ 1,
3254
+ 2,
3255
+ 3,
3256
+ 4,
3257
+ 5,
3258
+ 6,
3259
+ ] # https://github.com/fonttools/fonttools/issues/1170#issuecomment-364631225
3260
+ self.name_legacy = False
3261
+ self.name_languages = [0x0409] # English
3262
+ self.obfuscate_names = False # to make webfont unusable as a system font
3263
+ self.retain_gids = False
3264
+ self.notdef_glyph = True # gid0 for TrueType / .notdef for CFF
3265
+ self.notdef_outline = False # No need for notdef to have an outline really
3266
+ self.recommended_glyphs = False # gid1, gid2, gid3 for TrueType
3267
+ self.recalc_bounds = False # Recalculate font bounding boxes
3268
+ self.recalc_timestamp = False # Recalculate font modified timestamp
3269
+ self.prune_unicode_ranges = True # Clear unused 'ulUnicodeRange' bits
3270
+ self.prune_codepage_ranges = True # Clear unused 'ulCodePageRange' bits
3271
+ self.recalc_average_width = False # update 'xAvgCharWidth'
3272
+ self.recalc_max_context = False # update 'usMaxContext'
3273
+ self.canonical_order = None # Order tables as recommended
3274
+ self.flavor = None # May be 'woff' or 'woff2'
3275
+ self.with_zopfli = False # use zopfli instead of zlib for WOFF 1.0
3276
+ self.desubroutinize = False # Desubroutinize CFF CharStrings
3277
+ self.harfbuzz_repacker = USE_HARFBUZZ_REPACKER.default
3278
+ self.verbose = False
3279
+ self.timing = False
3280
+ self.xml = False
3281
+ self.font_number = -1
3282
+ self.pretty_svg = False
3283
+ self.lazy = True
3284
+ self.bidi_closure = True
3285
+
3286
+ self.set(**kwargs)
3287
+
3288
+ def set(self, **kwargs):
3289
+ for k, v in kwargs.items():
3290
+ if not hasattr(self, k):
3291
+ raise self.UnknownOptionError("Unknown option '%s'" % k)
3292
+ setattr(self, k, v)
3293
+
3294
+ def parse_opts(self, argv, ignore_unknown=[]):
3295
+ posargs = []
3296
+ passthru_options = []
3297
+ for a in argv:
3298
+ orig_a = a
3299
+ if not a.startswith("--"):
3300
+ posargs.append(a)
3301
+ continue
3302
+ a = a[2:]
3303
+ i = a.find("=")
3304
+ op = "="
3305
+ if i == -1:
3306
+ if a.startswith("no-"):
3307
+ k = a[3:]
3308
+ if k == "canonical-order":
3309
+ # reorderTables=None is faster than False (the latter
3310
+ # still reorders to "keep" the original table order)
3311
+ v = None
3312
+ else:
3313
+ v = False
3314
+ else:
3315
+ k = a
3316
+ v = True
3317
+ if k.endswith("?"):
3318
+ k = k[:-1]
3319
+ v = "?"
3320
+ else:
3321
+ k = a[:i]
3322
+ if k[-1] in "-+":
3323
+ op = k[-1] + "=" # Op is '-=' or '+=' now.
3324
+ k = k[:-1]
3325
+ v = a[i + 1 :]
3326
+ ok = k
3327
+ k = k.replace("-", "_")
3328
+ if not hasattr(self, k):
3329
+ if ignore_unknown is True or ok in ignore_unknown:
3330
+ passthru_options.append(orig_a)
3331
+ continue
3332
+ else:
3333
+ raise self.UnknownOptionError("Unknown option '%s'" % a)
3334
+
3335
+ ov = getattr(self, k)
3336
+ if v == "?":
3337
+ print("Current setting for '%s' is: %s" % (ok, ov))
3338
+ continue
3339
+ if isinstance(ov, bool):
3340
+ v = bool(v)
3341
+ elif isinstance(ov, int):
3342
+ v = int(v)
3343
+ elif isinstance(ov, str):
3344
+ v = str(v) # redundant
3345
+ elif isinstance(ov, list):
3346
+ if isinstance(v, bool):
3347
+ raise self.OptionError(
3348
+ "Option '%s' requires values to be specified using '='" % a
3349
+ )
3350
+ vv = v.replace(",", " ").split()
3351
+ if vv == [""]:
3352
+ vv = []
3353
+ vv = [int(x, 0) if len(x) and x[0] in "0123456789" else x for x in vv]
3354
+ if op == "=":
3355
+ v = vv
3356
+ elif op == "+=":
3357
+ v = ov
3358
+ v.extend(vv)
3359
+ elif op == "-=":
3360
+ v = ov
3361
+ for x in vv:
3362
+ if x in v:
3363
+ v.remove(x)
3364
+ else:
3365
+ assert False
3366
+
3367
+ setattr(self, k, v)
3368
+
3369
+ return posargs + passthru_options
3370
+
3371
+
3372
+ class Subsetter(object):
3373
+ class SubsettingError(Exception):
3374
+ pass
3375
+
3376
+ class MissingGlyphsSubsettingError(SubsettingError):
3377
+ pass
3378
+
3379
+ class MissingUnicodesSubsettingError(SubsettingError):
3380
+ pass
3381
+
3382
+ def __init__(self, options=None):
3383
+ if not options:
3384
+ options = Options()
3385
+
3386
+ self.options = options
3387
+ self.unicodes_requested = set()
3388
+ self.glyph_names_requested = set()
3389
+ self.glyph_ids_requested = set()
3390
+
3391
+ def populate(self, glyphs=[], gids=[], unicodes=[], text=""):
3392
+ self.unicodes_requested.update(unicodes)
3393
+ if isinstance(text, bytes):
3394
+ text = text.decode("utf_8")
3395
+ text_utf32 = text.encode("utf-32-be")
3396
+ nchars = len(text_utf32) // 4
3397
+ for u in struct.unpack(">%dL" % nchars, text_utf32):
3398
+ self.unicodes_requested.add(u)
3399
+ self.glyph_names_requested.update(glyphs)
3400
+ self.glyph_ids_requested.update(gids)
3401
+
3402
+ def _prune_pre_subset(self, font):
3403
+ for tag in self._sort_tables(font):
3404
+ if (
3405
+ tag.strip() in self.options.drop_tables
3406
+ or (
3407
+ tag.strip() in self.options.hinting_tables
3408
+ and not self.options.hinting
3409
+ )
3410
+ or (tag == "kern" and (not self.options.legacy_kern and "GPOS" in font))
3411
+ ):
3412
+ log.info("%s dropped", tag)
3413
+ del font[tag]
3414
+ continue
3415
+
3416
+ clazz = ttLib.getTableClass(tag)
3417
+
3418
+ if hasattr(clazz, "prune_pre_subset"):
3419
+ with timer("load '%s'" % tag):
3420
+ table = font[tag]
3421
+ with timer("prune '%s'" % tag):
3422
+ retain = table.prune_pre_subset(font, self.options)
3423
+ if not retain:
3424
+ log.info("%s pruned to empty; dropped", tag)
3425
+ del font[tag]
3426
+ continue
3427
+ else:
3428
+ log.info("%s pruned", tag)
3429
+
3430
+ def _closure_glyphs(self, font):
3431
+ realGlyphs = set(font.getGlyphOrder())
3432
+ self.orig_glyph_order = glyph_order = font.getGlyphOrder()
3433
+
3434
+ self.glyphs_requested = set()
3435
+ self.glyphs_requested.update(self.glyph_names_requested)
3436
+ self.glyphs_requested.update(
3437
+ glyph_order[i] for i in self.glyph_ids_requested if i < len(glyph_order)
3438
+ )
3439
+
3440
+ self.glyphs_missing = set()
3441
+ self.glyphs_missing.update(self.glyphs_requested.difference(realGlyphs))
3442
+ self.glyphs_missing.update(
3443
+ i for i in self.glyph_ids_requested if i >= len(glyph_order)
3444
+ )
3445
+ if self.glyphs_missing:
3446
+ log.info("Missing requested glyphs: %s", self.glyphs_missing)
3447
+ if not self.options.ignore_missing_glyphs:
3448
+ raise self.MissingGlyphsSubsettingError(self.glyphs_missing)
3449
+
3450
+ self.glyphs = self.glyphs_requested.copy()
3451
+
3452
+ self.unicodes_missing = set()
3453
+ if "cmap" in font:
3454
+ with timer("close glyph list over 'cmap'"):
3455
+ font["cmap"].closure_glyphs(self)
3456
+ self.glyphs.intersection_update(realGlyphs)
3457
+ self.glyphs_cmaped = frozenset(self.glyphs)
3458
+ if self.unicodes_missing:
3459
+ missing = ["U+%04X" % u for u in self.unicodes_missing]
3460
+ log.info("Missing glyphs for requested Unicodes: %s", missing)
3461
+ if not self.options.ignore_missing_unicodes:
3462
+ raise self.MissingUnicodesSubsettingError(missing)
3463
+ del missing
3464
+
3465
+ if self.options.notdef_glyph:
3466
+ if "glyf" in font:
3467
+ self.glyphs.add(font.getGlyphName(0))
3468
+ log.info("Added gid0 to subset")
3469
+ else:
3470
+ self.glyphs.add(".notdef")
3471
+ log.info("Added .notdef to subset")
3472
+ if self.options.recommended_glyphs:
3473
+ if "glyf" in font:
3474
+ for i in range(min(4, len(font.getGlyphOrder()))):
3475
+ self.glyphs.add(font.getGlyphName(i))
3476
+ log.info("Added first four glyphs to subset")
3477
+
3478
+ if "MATH" in font:
3479
+ with timer("close glyph list over 'MATH'"):
3480
+ log.info(
3481
+ "Closing glyph list over 'MATH': %d glyphs before", len(self.glyphs)
3482
+ )
3483
+ log.glyphs(self.glyphs, font=font)
3484
+ font["MATH"].closure_glyphs(self)
3485
+ self.glyphs.intersection_update(realGlyphs)
3486
+ log.info(
3487
+ "Closed glyph list over 'MATH': %d glyphs after", len(self.glyphs)
3488
+ )
3489
+ log.glyphs(self.glyphs, font=font)
3490
+ self.glyphs_mathed = frozenset(self.glyphs)
3491
+
3492
+ if self.options.layout_closure and "GSUB" in font:
3493
+ with timer("close glyph list over 'GSUB'"):
3494
+ log.info(
3495
+ "Closing glyph list over 'GSUB': %d glyphs before", len(self.glyphs)
3496
+ )
3497
+ log.glyphs(self.glyphs, font=font)
3498
+ font["GSUB"].closure_glyphs(self)
3499
+ self.glyphs.intersection_update(realGlyphs)
3500
+ log.info(
3501
+ "Closed glyph list over 'GSUB': %d glyphs after", len(self.glyphs)
3502
+ )
3503
+ log.glyphs(self.glyphs, font=font)
3504
+ self.glyphs_gsubed = frozenset(self.glyphs)
3505
+
3506
+ for table in ("COLR", "bsln"):
3507
+ if table in font:
3508
+ with timer("close glyph list over '%s'" % table):
3509
+ log.info(
3510
+ "Closing glyph list over '%s': %d glyphs before",
3511
+ table,
3512
+ len(self.glyphs),
3513
+ )
3514
+ log.glyphs(self.glyphs, font=font)
3515
+ font[table].closure_glyphs(self)
3516
+ self.glyphs.intersection_update(realGlyphs)
3517
+ log.info(
3518
+ "Closed glyph list over '%s': %d glyphs after",
3519
+ table,
3520
+ len(self.glyphs),
3521
+ )
3522
+ log.glyphs(self.glyphs, font=font)
3523
+ setattr(self, f"glyphs_{table.lower()}ed", frozenset(self.glyphs))
3524
+
3525
+ if "VARC" in font:
3526
+ with timer("close glyph list over 'VARC'"):
3527
+ log.info(
3528
+ "Closing glyph list over 'VARC': %d glyphs before", len(self.glyphs)
3529
+ )
3530
+ log.glyphs(self.glyphs, font=font)
3531
+ font["VARC"].closure_glyphs(self)
3532
+ self.glyphs.intersection_update(realGlyphs)
3533
+ log.info(
3534
+ "Closed glyph list over 'VARC': %d glyphs after", len(self.glyphs)
3535
+ )
3536
+ log.glyphs(self.glyphs, font=font)
3537
+ self.glyphs_glyfed = frozenset(self.glyphs)
3538
+
3539
+ if "glyf" in font:
3540
+ with timer("close glyph list over 'glyf'"):
3541
+ log.info(
3542
+ "Closing glyph list over 'glyf': %d glyphs before", len(self.glyphs)
3543
+ )
3544
+ log.glyphs(self.glyphs, font=font)
3545
+ font["glyf"].closure_glyphs(self)
3546
+ self.glyphs.intersection_update(realGlyphs)
3547
+ log.info(
3548
+ "Closed glyph list over 'glyf': %d glyphs after", len(self.glyphs)
3549
+ )
3550
+ log.glyphs(self.glyphs, font=font)
3551
+ self.glyphs_glyfed = frozenset(self.glyphs)
3552
+
3553
+ if "CFF " in font:
3554
+ with timer("close glyph list over 'CFF '"):
3555
+ log.info(
3556
+ "Closing glyph list over 'CFF ': %d glyphs before", len(self.glyphs)
3557
+ )
3558
+ log.glyphs(self.glyphs, font=font)
3559
+ font["CFF "].closure_glyphs(self)
3560
+ self.glyphs.intersection_update(realGlyphs)
3561
+ log.info(
3562
+ "Closed glyph list over 'CFF ': %d glyphs after", len(self.glyphs)
3563
+ )
3564
+ log.glyphs(self.glyphs, font=font)
3565
+ self.glyphs_cffed = frozenset(self.glyphs)
3566
+
3567
+ self.glyphs_retained = frozenset(self.glyphs)
3568
+
3569
+ order = font.getReverseGlyphMap()
3570
+ self.reverseOrigGlyphMap = {g: order[g] for g in self.glyphs_retained}
3571
+
3572
+ self.last_retained_order = max(self.reverseOrigGlyphMap.values())
3573
+ self.last_retained_glyph = font.getGlyphOrder()[self.last_retained_order]
3574
+
3575
+ self.glyphs_emptied = frozenset()
3576
+ if self.options.retain_gids:
3577
+ self.glyphs_emptied = {
3578
+ g
3579
+ for g in realGlyphs - self.glyphs_retained
3580
+ if order[g] <= self.last_retained_order
3581
+ }
3582
+
3583
+ self.reverseEmptiedGlyphMap = {g: order[g] for g in self.glyphs_emptied}
3584
+
3585
+ if not self.options.retain_gids:
3586
+ new_glyph_order = [g for g in glyph_order if g in self.glyphs_retained]
3587
+ else:
3588
+ new_glyph_order = [
3589
+ g for g in glyph_order if font.getGlyphID(g) <= self.last_retained_order
3590
+ ]
3591
+ # We'll call font.setGlyphOrder() at the end of _subset_glyphs when all
3592
+ # tables have been subsetted. Below, we use the new glyph order to get
3593
+ # a map from old to new glyph indices, which can be useful when
3594
+ # subsetting individual tables (e.g. SVG) that refer to GIDs.
3595
+ self.new_glyph_order = new_glyph_order
3596
+ self.glyph_index_map = {
3597
+ order[new_glyph_order[i]]: i for i in range(len(new_glyph_order))
3598
+ }
3599
+
3600
+ log.info("Retaining %d glyphs", len(self.glyphs_retained))
3601
+
3602
+ del self.glyphs
3603
+
3604
+ def _subset_glyphs(self, font):
3605
+ self.used_mark_sets = []
3606
+ for tag in self._sort_tables(font):
3607
+ clazz = ttLib.getTableClass(tag)
3608
+
3609
+ if tag.strip() in self.options.no_subset_tables:
3610
+ log.info("%s subsetting not needed", tag)
3611
+ elif hasattr(clazz, "subset_glyphs"):
3612
+ with timer("subset '%s'" % tag):
3613
+ table = font[tag]
3614
+ self.glyphs = self.glyphs_retained
3615
+ retain = table.subset_glyphs(self)
3616
+ del self.glyphs
3617
+ if not retain:
3618
+ log.info("%s subsetted to empty; dropped", tag)
3619
+ del font[tag]
3620
+ else:
3621
+ log.info("%s subsetted", tag)
3622
+ elif self.options.passthrough_tables:
3623
+ log.info("%s NOT subset; don't know how to subset", tag)
3624
+ else:
3625
+ log.warning("%s NOT subset; don't know how to subset; dropped", tag)
3626
+ del font[tag]
3627
+
3628
+ with timer("subset GlyphOrder"):
3629
+ font.setGlyphOrder(self.new_glyph_order)
3630
+
3631
+ def _prune_post_subset(self, font):
3632
+ tableTags = font.keys()
3633
+ # Prune the name table last because when we're pruning the name table,
3634
+ # we visit each table in the font to see what name table records are
3635
+ # still in use.
3636
+ if "name" in tableTags:
3637
+ tableTags.remove("name")
3638
+ tableTags.append("name")
3639
+ for tag in tableTags:
3640
+ if tag == "GlyphOrder":
3641
+ continue
3642
+ if tag == "OS/2":
3643
+ if self.options.prune_unicode_ranges:
3644
+ old_uniranges = font[tag].getUnicodeRanges()
3645
+ new_uniranges = font[tag].recalcUnicodeRanges(font, pruneOnly=True)
3646
+ if old_uniranges != new_uniranges:
3647
+ log.info(
3648
+ "%s Unicode ranges pruned: %s", tag, sorted(new_uniranges)
3649
+ )
3650
+ if self.options.prune_codepage_ranges and font[tag].version >= 1:
3651
+ # codepage range fields were added with OS/2 format 1
3652
+ # https://learn.microsoft.com/en-us/typography/opentype/spec/os2#version-1
3653
+ old_codepages = font[tag].getCodePageRanges()
3654
+ new_codepages = font[tag].recalcCodePageRanges(font, pruneOnly=True)
3655
+ if old_codepages != new_codepages:
3656
+ log.info(
3657
+ "%s CodePage ranges pruned: %s",
3658
+ tag,
3659
+ sorted(new_codepages),
3660
+ )
3661
+ if self.options.recalc_average_width:
3662
+ old_avg_width = font[tag].xAvgCharWidth
3663
+ new_avg_width = font[tag].recalcAvgCharWidth(font)
3664
+ if old_avg_width != new_avg_width:
3665
+ log.info("%s xAvgCharWidth updated: %d", tag, new_avg_width)
3666
+ if self.options.recalc_max_context:
3667
+ max_context = maxCtxFont(font)
3668
+ if max_context != font[tag].usMaxContext:
3669
+ font[tag].usMaxContext = max_context
3670
+ log.info("%s usMaxContext updated: %d", tag, max_context)
3671
+ clazz = ttLib.getTableClass(tag)
3672
+ if hasattr(clazz, "prune_post_subset"):
3673
+ with timer("prune '%s'" % tag):
3674
+ table = font[tag]
3675
+ retain = table.prune_post_subset(font, self.options)
3676
+ if not retain:
3677
+ log.info("%s pruned to empty; dropped", tag)
3678
+ del font[tag]
3679
+ else:
3680
+ log.info("%s pruned", tag)
3681
+
3682
+ def _sort_tables(self, font):
3683
+ tagOrder = ["GDEF", "GPOS", "GSUB", "fvar", "avar", "gvar", "name", "glyf"]
3684
+ tagOrder = {t: i + 1 for i, t in enumerate(tagOrder)}
3685
+ tags = sorted(font.keys(), key=lambda tag: tagOrder.get(tag, 0))
3686
+ return [t for t in tags if t != "GlyphOrder"]
3687
+
3688
+ def subset(self, font):
3689
+ self._prune_pre_subset(font)
3690
+ self._closure_glyphs(font)
3691
+ self._subset_glyphs(font)
3692
+ self._prune_post_subset(font)
3693
+
3694
+
3695
+ @timer("load font")
3696
+ def load_font(fontFile, options, checkChecksums=0, dontLoadGlyphNames=False, lazy=True):
3697
+ font = ttLib.TTFont(
3698
+ fontFile,
3699
+ checkChecksums=checkChecksums,
3700
+ recalcBBoxes=options.recalc_bounds,
3701
+ recalcTimestamp=options.recalc_timestamp,
3702
+ lazy=lazy,
3703
+ fontNumber=options.font_number,
3704
+ )
3705
+
3706
+ # Hack:
3707
+ #
3708
+ # If we don't need glyph names, change 'post' class to not try to
3709
+ # load them. It avoid lots of headache with broken fonts as well
3710
+ # as loading time.
3711
+ #
3712
+ # Ideally ttLib should provide a way to ask it to skip loading
3713
+ # glyph names. But it currently doesn't provide such a thing.
3714
+ #
3715
+ if dontLoadGlyphNames:
3716
+ post = ttLib.getTableClass("post")
3717
+ saved = post.decode_format_2_0
3718
+ post.decode_format_2_0 = post.decode_format_3_0
3719
+ f = font["post"]
3720
+ if f.formatType == 2.0:
3721
+ f.formatType = 3.0
3722
+ post.decode_format_2_0 = saved
3723
+
3724
+ return font
3725
+
3726
+
3727
+ @timer("compile and save font")
3728
+ def save_font(font, outfile, options):
3729
+ if options.with_zopfli and options.flavor == "woff":
3730
+ from fontTools.ttLib import sfnt
3731
+
3732
+ sfnt.USE_ZOPFLI = True
3733
+ font.flavor = options.flavor
3734
+ font.cfg[USE_HARFBUZZ_REPACKER] = options.harfbuzz_repacker
3735
+ font.save(outfile, reorderTables=options.canonical_order)
3736
+
3737
+
3738
+ def parse_unicodes(s):
3739
+ import re
3740
+
3741
+ s = re.sub(r"0[xX]", " ", s)
3742
+ s = re.sub(r"[<+>,;&#\\xXuU\n ]", " ", s)
3743
+ l = []
3744
+ for item in s.split():
3745
+ fields = item.split("-")
3746
+ if len(fields) == 1:
3747
+ l.append(int(item, 16))
3748
+ else:
3749
+ start, end = fields
3750
+ l.extend(range(int(start, 16), int(end, 16) + 1))
3751
+ return l
3752
+
3753
+
3754
+ def parse_gids(s):
3755
+ l = []
3756
+ for item in s.replace(",", " ").split():
3757
+ fields = item.split("-")
3758
+ if len(fields) == 1:
3759
+ l.append(int(fields[0]))
3760
+ else:
3761
+ l.extend(range(int(fields[0]), int(fields[1]) + 1))
3762
+ return l
3763
+
3764
+
3765
+ def parse_glyphs(s):
3766
+ return s.replace(",", " ").split()
3767
+
3768
+
3769
+ def usage():
3770
+ print("usage:", __usage__, file=sys.stderr)
3771
+ print("Try fonttools subset --help for more information.\n", file=sys.stderr)
3772
+
3773
+
3774
+ @timer("make one with everything (TOTAL TIME)")
3775
+ def main(args=None):
3776
+ """OpenType font subsetter and optimizer"""
3777
+ from os.path import splitext
3778
+ from fontTools import configLogger
3779
+
3780
+ if args is None:
3781
+ args = sys.argv[1:]
3782
+
3783
+ if "--help" in args:
3784
+ print(__doc__)
3785
+ return 0
3786
+
3787
+ options = Options()
3788
+ try:
3789
+ args = options.parse_opts(
3790
+ args,
3791
+ ignore_unknown=[
3792
+ "gids",
3793
+ "gids-file",
3794
+ "glyphs",
3795
+ "glyphs-file",
3796
+ "text",
3797
+ "text-file",
3798
+ "unicodes",
3799
+ "unicodes-file",
3800
+ "output-file",
3801
+ ],
3802
+ )
3803
+ except options.OptionError as e:
3804
+ usage()
3805
+ print("ERROR:", e, file=sys.stderr)
3806
+ return 2
3807
+
3808
+ if len(args) < 2:
3809
+ usage()
3810
+ return 1
3811
+
3812
+ configLogger(level=logging.INFO if options.verbose else logging.WARNING)
3813
+ if options.timing:
3814
+ timer.logger.setLevel(logging.DEBUG)
3815
+ else:
3816
+ timer.logger.disabled = True
3817
+
3818
+ fontfile = args[0]
3819
+ args = args[1:]
3820
+
3821
+ subsetter = Subsetter(options=options)
3822
+ outfile = None
3823
+ glyphs = []
3824
+ gids = []
3825
+ unicodes = []
3826
+ wildcard_glyphs = False
3827
+ wildcard_unicodes = False
3828
+ text = ""
3829
+ for g in args:
3830
+ if g == "*":
3831
+ wildcard_glyphs = True
3832
+ continue
3833
+ if g.startswith("--output-file="):
3834
+ outfile = g[14:]
3835
+ continue
3836
+ if g.startswith("--text="):
3837
+ text += g[7:]
3838
+ continue
3839
+ if g.startswith("--text-file="):
3840
+ with open(g[12:], encoding="utf-8-sig") as f:
3841
+ text += f.read().replace("\n", "")
3842
+ continue
3843
+ if g.startswith("--unicodes="):
3844
+ if g[11:] == "*":
3845
+ wildcard_unicodes = True
3846
+ else:
3847
+ unicodes.extend(parse_unicodes(g[11:]))
3848
+ continue
3849
+ if g.startswith("--unicodes-file="):
3850
+ with open(g[16:]) as f:
3851
+ for line in f.readlines():
3852
+ unicodes.extend(parse_unicodes(line.split("#")[0]))
3853
+ continue
3854
+ if g.startswith("--gids="):
3855
+ gids.extend(parse_gids(g[7:]))
3856
+ continue
3857
+ if g.startswith("--gids-file="):
3858
+ with open(g[12:]) as f:
3859
+ for line in f.readlines():
3860
+ gids.extend(parse_gids(line.split("#")[0]))
3861
+ continue
3862
+ if g.startswith("--glyphs="):
3863
+ if g[9:] == "*":
3864
+ wildcard_glyphs = True
3865
+ else:
3866
+ glyphs.extend(parse_glyphs(g[9:]))
3867
+ continue
3868
+ if g.startswith("--glyphs-file="):
3869
+ with open(g[14:]) as f:
3870
+ for line in f.readlines():
3871
+ glyphs.extend(parse_glyphs(line.split("#")[0]))
3872
+ continue
3873
+ glyphs.append(g)
3874
+
3875
+ dontLoadGlyphNames = not options.glyph_names and not glyphs
3876
+ lazy = options.lazy
3877
+ font = load_font(
3878
+ fontfile, options, dontLoadGlyphNames=dontLoadGlyphNames, lazy=lazy
3879
+ )
3880
+
3881
+ if outfile is None:
3882
+ ext = "." + options.flavor.lower() if options.flavor is not None else None
3883
+ outfile = makeOutputFileName(
3884
+ fontfile, extension=ext, overWrite=True, suffix=".subset"
3885
+ )
3886
+
3887
+ with timer("compile glyph list"):
3888
+ if wildcard_glyphs:
3889
+ glyphs.extend(font.getGlyphOrder())
3890
+ if wildcard_unicodes:
3891
+ for t in font["cmap"].tables:
3892
+ if t.isUnicode():
3893
+ unicodes.extend(t.cmap.keys())
3894
+ if t.format == 14:
3895
+ unicodes.extend(t.uvsDict.keys())
3896
+ assert "" not in glyphs
3897
+
3898
+ log.info("Text: '%s'" % text)
3899
+ log.info("Unicodes: %s", unicodes)
3900
+ log.info("Glyphs: %s", glyphs)
3901
+ log.info("Gids: %s", gids)
3902
+
3903
+ subsetter.populate(glyphs=glyphs, gids=gids, unicodes=unicodes, text=text)
3904
+ subsetter.subset(font)
3905
+
3906
+ save_font(font, outfile, options)
3907
+
3908
+ if options.verbose:
3909
+ import os
3910
+
3911
+ log.info("Input font:% 7d bytes: %s" % (os.path.getsize(fontfile), fontfile))
3912
+ log.info("Subset font:% 7d bytes: %s" % (os.path.getsize(outfile), outfile))
3913
+
3914
+ if options.xml:
3915
+ font.saveXML(sys.stdout)
3916
+
3917
+ font.close()
3918
+
3919
+
3920
+ __all__ = [
3921
+ "Options",
3922
+ "Subsetter",
3923
+ "load_font",
3924
+ "save_font",
3925
+ "parse_gids",
3926
+ "parse_glyphs",
3927
+ "parse_unicodes",
3928
+ "main",
3929
+ ]