builder.py 126 KB

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