builder.py 117 KB

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