builder.py 117 KB

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