builder.py 126 KB

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