builder.py 117 KB

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