builder.py 107 KB

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