__init__.py 140 KB

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