fonttools 4.60.2__cp311-cp311-win32.whl

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