builder.py 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814
  1. from fontTools.misc import sstruct
  2. from fontTools.misc.textTools import Tag, tostr, binary2num, safeEval
  3. from fontTools.feaLib.error import FeatureLibError
  4. from fontTools.feaLib.lookupDebugInfo import (
  5. LookupDebugInfo,
  6. LOOKUP_DEBUG_INFO_KEY,
  7. LOOKUP_DEBUG_ENV_VAR,
  8. )
  9. from fontTools.feaLib.parser import Parser
  10. from fontTools.feaLib.ast import FeatureFile
  11. from fontTools.feaLib.variableScalar import VariableScalar
  12. from fontTools.otlLib import builder as otl
  13. from fontTools.otlLib.maxContextCalc import maxCtxFont
  14. from fontTools.ttLib import newTable, getTableModule
  15. from fontTools.ttLib.tables import otBase, otTables
  16. from fontTools.otlLib.builder import (
  17. AlternateSubstBuilder,
  18. ChainContextPosBuilder,
  19. ChainContextSubstBuilder,
  20. LigatureSubstBuilder,
  21. MultipleSubstBuilder,
  22. CursivePosBuilder,
  23. MarkBasePosBuilder,
  24. MarkLigPosBuilder,
  25. MarkMarkPosBuilder,
  26. ReverseChainSingleSubstBuilder,
  27. SingleSubstBuilder,
  28. ClassPairPosSubtableBuilder,
  29. PairPosBuilder,
  30. SinglePosBuilder,
  31. ChainContextualRule,
  32. AnySubstBuilder,
  33. )
  34. from fontTools.otlLib.error import OpenTypeLibError
  35. from fontTools.varLib.errors import VarLibError
  36. from fontTools.varLib.varStore import OnlineVarStoreBuilder
  37. from fontTools.varLib.builder import buildVarDevTable
  38. from fontTools.varLib.featureVars import addFeatureVariationsRaw
  39. from fontTools.varLib.models import normalizeValue, piecewiseLinearMap
  40. from collections import defaultdict
  41. import copy
  42. import itertools
  43. from io import StringIO
  44. import logging
  45. import warnings
  46. import os
  47. log = logging.getLogger(__name__)
  48. def addOpenTypeFeatures(font, featurefile, tables=None, debug=False):
  49. """Add features from a file to a font. Note that this replaces any features
  50. currently present.
  51. Args:
  52. font (feaLib.ttLib.TTFont): The font object.
  53. featurefile: Either a path or file object (in which case we
  54. parse it into an AST), or a pre-parsed AST instance.
  55. tables: If passed, restrict the set of affected tables to those in the
  56. list.
  57. debug: Whether to add source debugging information to the font in the
  58. ``Debg`` table
  59. """
  60. builder = Builder(font, featurefile)
  61. builder.build(tables=tables, debug=debug)
  62. def addOpenTypeFeaturesFromString(
  63. font, features, filename=None, tables=None, debug=False
  64. ):
  65. """Add features from a string to a font. Note that this replaces any
  66. features currently present.
  67. Args:
  68. font (feaLib.ttLib.TTFont): The font object.
  69. features: A string containing feature code.
  70. filename: The directory containing ``filename`` is used as the root of
  71. relative ``include()`` paths; if ``None`` is provided, the current
  72. directory is assumed.
  73. tables: If passed, restrict the set of affected tables to those in the
  74. list.
  75. debug: Whether to add source debugging information to the font in the
  76. ``Debg`` table
  77. """
  78. featurefile = StringIO(tostr(features))
  79. if filename:
  80. featurefile.name = filename
  81. addOpenTypeFeatures(font, featurefile, tables=tables, debug=debug)
  82. class Builder(object):
  83. supportedTables = frozenset(
  84. Tag(tag)
  85. for tag in [
  86. "BASE",
  87. "GDEF",
  88. "GPOS",
  89. "GSUB",
  90. "OS/2",
  91. "head",
  92. "hhea",
  93. "name",
  94. "vhea",
  95. "STAT",
  96. ]
  97. )
  98. def __init__(self, font, featurefile):
  99. self.font = font
  100. # 'featurefile' can be either a path or file object (in which case we
  101. # parse it into an AST), or a pre-parsed AST instance
  102. if isinstance(featurefile, FeatureFile):
  103. self.parseTree, self.file = featurefile, None
  104. else:
  105. self.parseTree, self.file = None, featurefile
  106. self.glyphMap = font.getReverseGlyphMap()
  107. self.varstorebuilder = None
  108. if "fvar" in font:
  109. self.axes = font["fvar"].axes
  110. self.varstorebuilder = OnlineVarStoreBuilder(
  111. [ax.axisTag for ax in self.axes]
  112. )
  113. self.default_language_systems_ = set()
  114. self.script_ = None
  115. self.lookupflag_ = 0
  116. self.lookupflag_markFilterSet_ = None
  117. self.use_extension_ = False
  118. self.language_systems = set()
  119. self.seen_non_DFLT_script_ = False
  120. self.named_lookups_ = {}
  121. self.cur_lookup_ = None
  122. self.cur_lookup_name_ = None
  123. self.cur_feature_name_ = None
  124. self.lookups_ = []
  125. self.lookup_locations = {"GSUB": {}, "GPOS": {}}
  126. self.features_ = {} # ('latn', 'DEU ', 'smcp') --> [LookupBuilder*]
  127. self.required_features_ = {} # ('latn', 'DEU ') --> 'scmp'
  128. self.feature_variations_ = {}
  129. # for feature 'aalt'
  130. self.aalt_features_ = [] # [(location, featureName)*], for 'aalt'
  131. self.aalt_location_ = None
  132. self.aalt_alternates_ = {}
  133. self.aalt_use_extension_ = False
  134. # for 'featureNames'
  135. self.featureNames_ = set()
  136. self.featureNames_ids_ = {}
  137. # for 'cvParameters'
  138. self.cv_parameters_ = set()
  139. self.cv_parameters_ids_ = {}
  140. self.cv_num_named_params_ = {}
  141. self.cv_characters_ = defaultdict(list)
  142. # for feature 'size'
  143. self.size_parameters_ = None
  144. # for table 'head'
  145. self.fontRevision_ = None # 2.71
  146. # for table 'name'
  147. self.names_ = []
  148. # for table 'BASE'
  149. self.base_horiz_axis_ = None
  150. self.base_vert_axis_ = None
  151. # for table 'GDEF'
  152. self.attachPoints_ = {} # "a" --> {3, 7}
  153. self.ligCaretCoords_ = {} # "f_f_i" --> {300, 600}
  154. self.ligCaretPoints_ = {} # "f_f_i" --> {3, 7}
  155. self.glyphClassDefs_ = {} # "fi" --> (2, (file, line, column))
  156. self.markAttach_ = {} # "acute" --> (4, (file, line, column))
  157. self.markAttachClassID_ = {} # frozenset({"acute", "grave"}) --> 4
  158. self.markFilterSets_ = {} # frozenset({"acute", "grave"}) --> 4
  159. # for table 'OS/2'
  160. self.os2_ = {}
  161. # for table 'hhea'
  162. self.hhea_ = {}
  163. # for table 'vhea'
  164. self.vhea_ = {}
  165. # for table 'STAT'
  166. self.stat_ = {}
  167. # for conditionsets
  168. self.conditionsets_ = {}
  169. # We will often use exactly the same locations (i.e. the font's masters)
  170. # for a large number of variable scalars. Instead of creating a model
  171. # for each, let's share the models.
  172. self.model_cache = {}
  173. def build(self, tables=None, debug=False):
  174. if self.parseTree is None:
  175. self.parseTree = Parser(self.file, self.glyphMap).parse()
  176. self.parseTree.build(self)
  177. # by default, build all the supported tables
  178. if tables is None:
  179. tables = self.supportedTables
  180. else:
  181. tables = frozenset(tables)
  182. unsupported = tables - self.supportedTables
  183. if unsupported:
  184. unsupported_string = ", ".join(sorted(unsupported))
  185. raise NotImplementedError(
  186. "The following tables were requested but are unsupported: "
  187. f"{unsupported_string}."
  188. )
  189. if "GSUB" in tables:
  190. self.build_feature_aalt_()
  191. if "head" in tables:
  192. self.build_head()
  193. if "hhea" in tables:
  194. self.build_hhea()
  195. if "vhea" in tables:
  196. self.build_vhea()
  197. if "name" in tables:
  198. self.build_name()
  199. if "OS/2" in tables:
  200. self.build_OS_2()
  201. if "STAT" in tables:
  202. self.build_STAT()
  203. for tag in ("GPOS", "GSUB"):
  204. if tag not in tables:
  205. continue
  206. table = self.makeTable(tag)
  207. if self.feature_variations_:
  208. self.makeFeatureVariations(table, tag)
  209. if (
  210. table.ScriptList.ScriptCount > 0
  211. or table.FeatureList.FeatureCount > 0
  212. or table.LookupList.LookupCount > 0
  213. ):
  214. fontTable = self.font[tag] = newTable(tag)
  215. fontTable.table = table
  216. elif tag in self.font:
  217. del self.font[tag]
  218. if any(tag in self.font for tag in ("GPOS", "GSUB")) and "OS/2" in self.font:
  219. self.font["OS/2"].usMaxContext = maxCtxFont(self.font)
  220. if "GDEF" in tables:
  221. gdef = self.buildGDEF()
  222. if gdef:
  223. self.font["GDEF"] = gdef
  224. elif "GDEF" in self.font:
  225. del self.font["GDEF"]
  226. if "BASE" in tables:
  227. base = self.buildBASE()
  228. if base:
  229. self.font["BASE"] = base
  230. elif "BASE" in self.font:
  231. del self.font["BASE"]
  232. if debug or os.environ.get(LOOKUP_DEBUG_ENV_VAR):
  233. self.buildDebg()
  234. def get_chained_lookup_(self, location, builder_class):
  235. result = builder_class(self.font, location)
  236. result.lookupflag = self.lookupflag_
  237. result.markFilterSet = self.lookupflag_markFilterSet_
  238. result.extension = self.use_extension_
  239. self.lookups_.append(result)
  240. return result
  241. def add_lookup_to_feature_(self, lookup, feature_name):
  242. for script, lang in self.language_systems:
  243. key = (script, lang, feature_name)
  244. self.features_.setdefault(key, []).append(lookup)
  245. def get_lookup_(self, location, builder_class, mapping=None):
  246. if (
  247. self.cur_lookup_
  248. and type(self.cur_lookup_) == builder_class
  249. and self.cur_lookup_.lookupflag == self.lookupflag_
  250. and self.cur_lookup_.markFilterSet == self.lookupflag_markFilterSet_
  251. and self.cur_lookup_.can_add_mapping(mapping)
  252. ):
  253. return self.cur_lookup_
  254. if self.cur_lookup_name_ and self.cur_lookup_:
  255. raise FeatureLibError(
  256. "Within a named lookup block, all rules must be of "
  257. "the same lookup type and flag",
  258. location,
  259. )
  260. self.cur_lookup_ = builder_class(self.font, location)
  261. self.cur_lookup_.lookupflag = self.lookupflag_
  262. self.cur_lookup_.markFilterSet = self.lookupflag_markFilterSet_
  263. self.cur_lookup_.extension = self.use_extension_
  264. self.lookups_.append(self.cur_lookup_)
  265. if self.cur_lookup_name_:
  266. # We are starting a lookup rule inside a named lookup block.
  267. self.named_lookups_[self.cur_lookup_name_] = self.cur_lookup_
  268. if self.cur_feature_name_:
  269. # We are starting a lookup rule inside a feature. This includes
  270. # lookup rules inside named lookups inside features.
  271. self.add_lookup_to_feature_(self.cur_lookup_, self.cur_feature_name_)
  272. return self.cur_lookup_
  273. def build_feature_aalt_(self):
  274. if not self.aalt_features_ and not self.aalt_alternates_:
  275. return
  276. # > alternate glyphs will be sorted in the order that the source features
  277. # > are named in the aalt definition, not the order of the feature definitions
  278. # > in the file. Alternates defined explicitly ... will precede all others.
  279. # https://github.com/fonttools/fonttools/issues/836
  280. alternates = {g: list(a) for g, a in self.aalt_alternates_.items()}
  281. for location, name in self.aalt_features_ + [(None, "aalt")]:
  282. feature = [
  283. (script, lang, feature, lookups)
  284. for (script, lang, feature), lookups in self.features_.items()
  285. if feature == name
  286. ]
  287. # "aalt" does not have to specify its own lookups, but it might.
  288. if not feature and name != "aalt":
  289. warnings.warn("%s: Feature %s has not been defined" % (location, name))
  290. continue
  291. for script, lang, feature, lookups in feature:
  292. for lookuplist in lookups:
  293. if not isinstance(lookuplist, list):
  294. lookuplist = [lookuplist]
  295. for lookup in lookuplist:
  296. for glyph, alts in lookup.getAlternateGlyphs().items():
  297. alts_for_glyph = alternates.setdefault(glyph, [])
  298. alts_for_glyph.extend(
  299. g for g in alts if g not in alts_for_glyph
  300. )
  301. single = {
  302. glyph: repl[0] for glyph, repl in alternates.items() if len(repl) == 1
  303. }
  304. multi = {glyph: repl for glyph, repl in alternates.items() if len(repl) > 1}
  305. if not single and not multi:
  306. return
  307. self.features_ = {
  308. (script, lang, feature): lookups
  309. for (script, lang, feature), lookups in self.features_.items()
  310. if feature != "aalt"
  311. }
  312. old_lookups = self.lookups_
  313. self.lookups_ = []
  314. self.start_feature(self.aalt_location_, "aalt", self.aalt_use_extension_)
  315. if single:
  316. single_lookup = self.get_lookup_(location, SingleSubstBuilder)
  317. single_lookup.mapping = single
  318. if multi:
  319. multi_lookup = self.get_lookup_(location, AlternateSubstBuilder)
  320. multi_lookup.alternates = multi
  321. self.end_feature()
  322. self.lookups_.extend(old_lookups)
  323. def build_head(self):
  324. if not self.fontRevision_:
  325. return
  326. table = self.font.get("head")
  327. if not table: # this only happens for unit tests
  328. table = self.font["head"] = newTable("head")
  329. table.decompile(b"\0" * 54, self.font)
  330. table.tableVersion = 1.0
  331. table.magicNumber = 0x5F0F3CF5
  332. table.created = table.modified = 3406620153 # 2011-12-13 11:22:33
  333. table.fontRevision = self.fontRevision_
  334. def build_hhea(self):
  335. if not self.hhea_:
  336. return
  337. table = self.font.get("hhea")
  338. if not table: # this only happens for unit tests
  339. table = self.font["hhea"] = newTable("hhea")
  340. table.decompile(b"\0" * 36, self.font)
  341. table.tableVersion = 0x00010000
  342. if "caretoffset" in self.hhea_:
  343. table.caretOffset = self.hhea_["caretoffset"]
  344. if "ascender" in self.hhea_:
  345. table.ascent = self.hhea_["ascender"]
  346. if "descender" in self.hhea_:
  347. table.descent = self.hhea_["descender"]
  348. if "linegap" in self.hhea_:
  349. table.lineGap = self.hhea_["linegap"]
  350. def build_vhea(self):
  351. if not self.vhea_:
  352. return
  353. table = self.font.get("vhea")
  354. if not table: # this only happens for unit tests
  355. table = self.font["vhea"] = newTable("vhea")
  356. table.decompile(b"\0" * 36, self.font)
  357. table.tableVersion = 0x00011000
  358. if "verttypoascender" in self.vhea_:
  359. table.ascent = self.vhea_["verttypoascender"]
  360. if "verttypodescender" in self.vhea_:
  361. table.descent = self.vhea_["verttypodescender"]
  362. if "verttypolinegap" in self.vhea_:
  363. table.lineGap = self.vhea_["verttypolinegap"]
  364. def get_user_name_id(self, table):
  365. # Try to find first unused font-specific name id
  366. nameIDs = [name.nameID for name in table.names]
  367. for user_name_id in range(256, 32767):
  368. if user_name_id not in nameIDs:
  369. return user_name_id
  370. def buildFeatureParams(self, tag):
  371. params = None
  372. if tag == "size":
  373. params = otTables.FeatureParamsSize()
  374. (
  375. params.DesignSize,
  376. params.SubfamilyID,
  377. params.RangeStart,
  378. params.RangeEnd,
  379. ) = self.size_parameters_
  380. if tag in self.featureNames_ids_:
  381. params.SubfamilyNameID = self.featureNames_ids_[tag]
  382. else:
  383. params.SubfamilyNameID = 0
  384. elif tag in self.featureNames_:
  385. if not self.featureNames_ids_:
  386. # name table wasn't selected among the tables to build; skip
  387. pass
  388. else:
  389. assert tag in self.featureNames_ids_
  390. params = otTables.FeatureParamsStylisticSet()
  391. params.Version = 0
  392. params.UINameID = self.featureNames_ids_[tag]
  393. elif tag in self.cv_parameters_:
  394. params = otTables.FeatureParamsCharacterVariants()
  395. params.Format = 0
  396. params.FeatUILabelNameID = self.cv_parameters_ids_.get(
  397. (tag, "FeatUILabelNameID"), 0
  398. )
  399. params.FeatUITooltipTextNameID = self.cv_parameters_ids_.get(
  400. (tag, "FeatUITooltipTextNameID"), 0
  401. )
  402. params.SampleTextNameID = self.cv_parameters_ids_.get(
  403. (tag, "SampleTextNameID"), 0
  404. )
  405. params.NumNamedParameters = self.cv_num_named_params_.get(tag, 0)
  406. params.FirstParamUILabelNameID = self.cv_parameters_ids_.get(
  407. (tag, "ParamUILabelNameID_0"), 0
  408. )
  409. params.CharCount = len(self.cv_characters_[tag])
  410. params.Character = self.cv_characters_[tag]
  411. return params
  412. def build_name(self):
  413. if not self.names_:
  414. return
  415. table = self.font.get("name")
  416. if not table: # this only happens for unit tests
  417. table = self.font["name"] = newTable("name")
  418. table.names = []
  419. for name in self.names_:
  420. nameID, platformID, platEncID, langID, string = name
  421. # For featureNames block, nameID is 'feature tag'
  422. # For cvParameters blocks, nameID is ('feature tag', 'block name')
  423. if not isinstance(nameID, int):
  424. tag = nameID
  425. if tag in self.featureNames_:
  426. if tag not in self.featureNames_ids_:
  427. self.featureNames_ids_[tag] = self.get_user_name_id(table)
  428. assert self.featureNames_ids_[tag] is not None
  429. nameID = self.featureNames_ids_[tag]
  430. elif tag[0] in self.cv_parameters_:
  431. if tag not in self.cv_parameters_ids_:
  432. self.cv_parameters_ids_[tag] = self.get_user_name_id(table)
  433. assert self.cv_parameters_ids_[tag] is not None
  434. nameID = self.cv_parameters_ids_[tag]
  435. table.setName(string, nameID, platformID, platEncID, langID)
  436. table.names.sort()
  437. def build_OS_2(self):
  438. if not self.os2_:
  439. return
  440. table = self.font.get("OS/2")
  441. if not table: # this only happens for unit tests
  442. table = self.font["OS/2"] = newTable("OS/2")
  443. data = b"\0" * sstruct.calcsize(getTableModule("OS/2").OS2_format_0)
  444. table.decompile(data, self.font)
  445. version = 0
  446. if "fstype" in self.os2_:
  447. table.fsType = self.os2_["fstype"]
  448. if "panose" in self.os2_:
  449. panose = getTableModule("OS/2").Panose()
  450. (
  451. panose.bFamilyType,
  452. panose.bSerifStyle,
  453. panose.bWeight,
  454. panose.bProportion,
  455. panose.bContrast,
  456. panose.bStrokeVariation,
  457. panose.bArmStyle,
  458. panose.bLetterForm,
  459. panose.bMidline,
  460. panose.bXHeight,
  461. ) = self.os2_["panose"]
  462. table.panose = panose
  463. if "typoascender" in self.os2_:
  464. table.sTypoAscender = self.os2_["typoascender"]
  465. if "typodescender" in self.os2_:
  466. table.sTypoDescender = self.os2_["typodescender"]
  467. if "typolinegap" in self.os2_:
  468. table.sTypoLineGap = self.os2_["typolinegap"]
  469. if "winascent" in self.os2_:
  470. table.usWinAscent = self.os2_["winascent"]
  471. if "windescent" in self.os2_:
  472. table.usWinDescent = self.os2_["windescent"]
  473. if "vendor" in self.os2_:
  474. table.achVendID = safeEval("'''" + self.os2_["vendor"] + "'''")
  475. if "weightclass" in self.os2_:
  476. table.usWeightClass = self.os2_["weightclass"]
  477. if "widthclass" in self.os2_:
  478. table.usWidthClass = self.os2_["widthclass"]
  479. if "unicoderange" in self.os2_:
  480. table.setUnicodeRanges(self.os2_["unicoderange"])
  481. if "codepagerange" in self.os2_:
  482. pages = self.build_codepages_(self.os2_["codepagerange"])
  483. table.ulCodePageRange1, table.ulCodePageRange2 = pages
  484. version = 1
  485. if "xheight" in self.os2_:
  486. table.sxHeight = self.os2_["xheight"]
  487. version = 2
  488. if "capheight" in self.os2_:
  489. table.sCapHeight = self.os2_["capheight"]
  490. version = 2
  491. if "loweropsize" in self.os2_:
  492. table.usLowerOpticalPointSize = self.os2_["loweropsize"]
  493. version = 5
  494. if "upperopsize" in self.os2_:
  495. table.usUpperOpticalPointSize = self.os2_["upperopsize"]
  496. version = 5
  497. def checkattr(table, attrs):
  498. for attr in attrs:
  499. if not hasattr(table, attr):
  500. setattr(table, attr, 0)
  501. table.version = max(version, table.version)
  502. # this only happens for unit tests
  503. if version >= 1:
  504. checkattr(table, ("ulCodePageRange1", "ulCodePageRange2"))
  505. if version >= 2:
  506. checkattr(
  507. table,
  508. (
  509. "sxHeight",
  510. "sCapHeight",
  511. "usDefaultChar",
  512. "usBreakChar",
  513. "usMaxContext",
  514. ),
  515. )
  516. if version >= 5:
  517. checkattr(table, ("usLowerOpticalPointSize", "usUpperOpticalPointSize"))
  518. def setElidedFallbackName(self, value, location):
  519. # ElidedFallbackName is a convenience method for setting
  520. # ElidedFallbackNameID so only one can be allowed
  521. for token in ("ElidedFallbackName", "ElidedFallbackNameID"):
  522. if token in self.stat_:
  523. raise FeatureLibError(
  524. f"{token} is already set.",
  525. location,
  526. )
  527. if isinstance(value, int):
  528. self.stat_["ElidedFallbackNameID"] = value
  529. elif isinstance(value, list):
  530. self.stat_["ElidedFallbackName"] = value
  531. else:
  532. raise AssertionError(value)
  533. def addDesignAxis(self, designAxis, location):
  534. if "DesignAxes" not in self.stat_:
  535. self.stat_["DesignAxes"] = []
  536. if designAxis.tag in (r.tag for r in self.stat_["DesignAxes"]):
  537. raise FeatureLibError(
  538. f'DesignAxis already defined for tag "{designAxis.tag}".',
  539. location,
  540. )
  541. if designAxis.axisOrder in (r.axisOrder for r in self.stat_["DesignAxes"]):
  542. raise FeatureLibError(
  543. f"DesignAxis already defined for axis number {designAxis.axisOrder}.",
  544. location,
  545. )
  546. self.stat_["DesignAxes"].append(designAxis)
  547. def addAxisValueRecord(self, axisValueRecord, location):
  548. if "AxisValueRecords" not in self.stat_:
  549. self.stat_["AxisValueRecords"] = []
  550. # Check for duplicate AxisValueRecords
  551. for record_ in self.stat_["AxisValueRecords"]:
  552. if (
  553. {n.asFea() for n in record_.names}
  554. == {n.asFea() for n in axisValueRecord.names}
  555. and {n.asFea() for n in record_.locations}
  556. == {n.asFea() for n in axisValueRecord.locations}
  557. and record_.flags == axisValueRecord.flags
  558. ):
  559. raise FeatureLibError(
  560. "An AxisValueRecord with these values is already defined.",
  561. location,
  562. )
  563. self.stat_["AxisValueRecords"].append(axisValueRecord)
  564. def build_STAT(self):
  565. if not self.stat_:
  566. return
  567. axes = self.stat_.get("DesignAxes")
  568. if not axes:
  569. raise FeatureLibError("DesignAxes not defined", None)
  570. axisValueRecords = self.stat_.get("AxisValueRecords")
  571. axisValues = {}
  572. format4_locations = []
  573. for tag in axes:
  574. axisValues[tag.tag] = []
  575. if axisValueRecords is not None:
  576. for avr in axisValueRecords:
  577. valuesDict = {}
  578. if avr.flags > 0:
  579. valuesDict["flags"] = avr.flags
  580. if len(avr.locations) == 1:
  581. location = avr.locations[0]
  582. values = location.values
  583. if len(values) == 1: # format1
  584. valuesDict.update({"value": values[0], "name": avr.names})
  585. if len(values) == 2: # format3
  586. valuesDict.update(
  587. {
  588. "value": values[0],
  589. "linkedValue": values[1],
  590. "name": avr.names,
  591. }
  592. )
  593. if len(values) == 3: # format2
  594. nominal, minVal, maxVal = values
  595. valuesDict.update(
  596. {
  597. "nominalValue": nominal,
  598. "rangeMinValue": minVal,
  599. "rangeMaxValue": maxVal,
  600. "name": avr.names,
  601. }
  602. )
  603. axisValues[location.tag].append(valuesDict)
  604. else:
  605. valuesDict.update(
  606. {
  607. "location": {i.tag: i.values[0] for i in avr.locations},
  608. "name": avr.names,
  609. }
  610. )
  611. format4_locations.append(valuesDict)
  612. designAxes = [
  613. {
  614. "ordering": a.axisOrder,
  615. "tag": a.tag,
  616. "name": a.names,
  617. "values": axisValues[a.tag],
  618. }
  619. for a in axes
  620. ]
  621. nameTable = self.font.get("name")
  622. if not nameTable: # this only happens for unit tests
  623. nameTable = self.font["name"] = newTable("name")
  624. nameTable.names = []
  625. if "ElidedFallbackNameID" in self.stat_:
  626. nameID = self.stat_["ElidedFallbackNameID"]
  627. name = nameTable.getDebugName(nameID)
  628. if not name:
  629. raise FeatureLibError(
  630. f"ElidedFallbackNameID {nameID} points "
  631. "to a nameID that does not exist in the "
  632. '"name" table',
  633. None,
  634. )
  635. elif "ElidedFallbackName" in self.stat_:
  636. nameID = self.stat_["ElidedFallbackName"]
  637. otl.buildStatTable(
  638. self.font,
  639. designAxes,
  640. locations=format4_locations,
  641. elidedFallbackName=nameID,
  642. )
  643. def build_codepages_(self, pages):
  644. pages2bits = {
  645. 1252: 0,
  646. 1250: 1,
  647. 1251: 2,
  648. 1253: 3,
  649. 1254: 4,
  650. 1255: 5,
  651. 1256: 6,
  652. 1257: 7,
  653. 1258: 8,
  654. 874: 16,
  655. 932: 17,
  656. 936: 18,
  657. 949: 19,
  658. 950: 20,
  659. 1361: 21,
  660. 869: 48,
  661. 866: 49,
  662. 865: 50,
  663. 864: 51,
  664. 863: 52,
  665. 862: 53,
  666. 861: 54,
  667. 860: 55,
  668. 857: 56,
  669. 855: 57,
  670. 852: 58,
  671. 775: 59,
  672. 737: 60,
  673. 708: 61,
  674. 850: 62,
  675. 437: 63,
  676. }
  677. bits = [pages2bits[p] for p in pages if p in pages2bits]
  678. pages = []
  679. for i in range(2):
  680. pages.append("")
  681. for j in range(i * 32, (i + 1) * 32):
  682. if j in bits:
  683. pages[i] += "1"
  684. else:
  685. pages[i] += "0"
  686. return [binary2num(p[::-1]) for p in pages]
  687. def buildBASE(self):
  688. if not self.base_horiz_axis_ and not self.base_vert_axis_:
  689. return None
  690. base = otTables.BASE()
  691. base.Version = 0x00010000
  692. base.HorizAxis = self.buildBASEAxis(self.base_horiz_axis_)
  693. base.VertAxis = self.buildBASEAxis(self.base_vert_axis_)
  694. result = newTable("BASE")
  695. result.table = base
  696. return result
  697. def buildBASECoord(self, c):
  698. coord = otTables.BaseCoord()
  699. coord.Format = 1
  700. coord.Coordinate = c
  701. return coord
  702. def buildBASEAxis(self, axis):
  703. if not axis:
  704. return
  705. bases, scripts, minmax = axis
  706. axis = otTables.Axis()
  707. axis.BaseTagList = otTables.BaseTagList()
  708. axis.BaseTagList.BaselineTag = bases
  709. axis.BaseTagList.BaseTagCount = len(bases)
  710. axis.BaseScriptList = otTables.BaseScriptList()
  711. axis.BaseScriptList.BaseScriptRecord = []
  712. axis.BaseScriptList.BaseScriptCount = len(scripts)
  713. for script in sorted(scripts):
  714. minmax_for_script = [
  715. record[1:] for record in minmax if record[0] == script[0]
  716. ]
  717. record = otTables.BaseScriptRecord()
  718. record.BaseScriptTag = script[0]
  719. record.BaseScript = otTables.BaseScript()
  720. record.BaseScript.BaseValues = otTables.BaseValues()
  721. record.BaseScript.BaseValues.DefaultIndex = bases.index(script[1])
  722. record.BaseScript.BaseValues.BaseCoord = []
  723. record.BaseScript.BaseValues.BaseCoordCount = len(script[2])
  724. record.BaseScript.BaseLangSysRecord = []
  725. for c in script[2]:
  726. record.BaseScript.BaseValues.BaseCoord.append(self.buildBASECoord(c))
  727. for language, min_coord, max_coord in sorted(minmax_for_script):
  728. minmax_record = otTables.MinMax()
  729. minmax_record.MinCoord = self.buildBASECoord(min_coord)
  730. minmax_record.MaxCoord = self.buildBASECoord(max_coord)
  731. minmax_record.FeatMinMaxCount = 0
  732. if language == "dflt":
  733. record.BaseScript.DefaultMinMax = minmax_record
  734. else:
  735. lang_record = otTables.BaseLangSysRecord()
  736. lang_record.BaseLangSysTag = language
  737. lang_record.MinMax = minmax_record
  738. record.BaseScript.BaseLangSysRecord.append(lang_record)
  739. record.BaseScript.BaseLangSysCount = len(
  740. record.BaseScript.BaseLangSysRecord
  741. )
  742. axis.BaseScriptList.BaseScriptRecord.append(record)
  743. return axis
  744. def buildGDEF(self):
  745. gdef = otTables.GDEF()
  746. gdef.GlyphClassDef = self.buildGDEFGlyphClassDef_()
  747. gdef.AttachList = otl.buildAttachList(self.attachPoints_, self.glyphMap)
  748. gdef.LigCaretList = otl.buildLigCaretList(
  749. self.ligCaretCoords_, self.ligCaretPoints_, self.glyphMap
  750. )
  751. gdef.MarkAttachClassDef = self.buildGDEFMarkAttachClassDef_()
  752. gdef.MarkGlyphSetsDef = self.buildGDEFMarkGlyphSetsDef_()
  753. gdef.Version = 0x00010002 if gdef.MarkGlyphSetsDef else 0x00010000
  754. if self.varstorebuilder:
  755. store = self.varstorebuilder.finish()
  756. if store:
  757. gdef.Version = 0x00010003
  758. gdef.VarStore = store
  759. varidx_map = store.optimize()
  760. gdef.remap_device_varidxes(varidx_map)
  761. if "GPOS" in self.font:
  762. self.font["GPOS"].table.remap_device_varidxes(varidx_map)
  763. self.model_cache.clear()
  764. if any(
  765. (
  766. gdef.GlyphClassDef,
  767. gdef.AttachList,
  768. gdef.LigCaretList,
  769. gdef.MarkAttachClassDef,
  770. gdef.MarkGlyphSetsDef,
  771. )
  772. ) or hasattr(gdef, "VarStore"):
  773. result = newTable("GDEF")
  774. result.table = gdef
  775. return result
  776. else:
  777. return None
  778. def buildGDEFGlyphClassDef_(self):
  779. if self.glyphClassDefs_:
  780. classes = {g: c for (g, (c, _)) in self.glyphClassDefs_.items()}
  781. else:
  782. classes = {}
  783. for lookup in self.lookups_:
  784. classes.update(lookup.inferGlyphClasses())
  785. for markClass in self.parseTree.markClasses.values():
  786. for markClassDef in markClass.definitions:
  787. for glyph in markClassDef.glyphSet():
  788. classes[glyph] = 3
  789. if classes:
  790. result = otTables.GlyphClassDef()
  791. result.classDefs = classes
  792. return result
  793. else:
  794. return None
  795. def buildGDEFMarkAttachClassDef_(self):
  796. classDefs = {g: c for g, (c, _) in self.markAttach_.items()}
  797. if not classDefs:
  798. return None
  799. result = otTables.MarkAttachClassDef()
  800. result.classDefs = classDefs
  801. return result
  802. def buildGDEFMarkGlyphSetsDef_(self):
  803. sets = []
  804. for glyphs, id_ in sorted(
  805. self.markFilterSets_.items(), key=lambda item: item[1]
  806. ):
  807. sets.append(glyphs)
  808. return otl.buildMarkGlyphSetsDef(sets, self.glyphMap)
  809. def buildDebg(self):
  810. if "Debg" not in self.font:
  811. self.font["Debg"] = newTable("Debg")
  812. self.font["Debg"].data = {}
  813. self.font["Debg"].data[LOOKUP_DEBUG_INFO_KEY] = self.lookup_locations
  814. def buildLookups_(self, tag):
  815. assert tag in ("GPOS", "GSUB"), tag
  816. for lookup in self.lookups_:
  817. lookup.lookup_index = None
  818. lookups = []
  819. for lookup in self.lookups_:
  820. if lookup.table != tag:
  821. continue
  822. name = self.get_lookup_name_(lookup)
  823. resolved = lookup.promote_lookup_type(is_named_lookup=name is not None)
  824. if resolved is None:
  825. raise FeatureLibError(
  826. "Within a named lookup block, all rules must be of "
  827. "the same lookup type and flag",
  828. lookup.location,
  829. )
  830. for l in resolved:
  831. lookup.lookup_index = len(lookups)
  832. self.lookup_locations[tag][str(lookup.lookup_index)] = LookupDebugInfo(
  833. location=str(lookup.location),
  834. name=name,
  835. feature=None,
  836. )
  837. lookups.append(l)
  838. otLookups = []
  839. for l in lookups:
  840. try:
  841. otLookups.append(l.build())
  842. except OpenTypeLibError as e:
  843. raise FeatureLibError(str(e), e.location) from e
  844. except Exception as e:
  845. location = self.lookup_locations[tag][str(l.lookup_index)].location
  846. raise FeatureLibError(str(e), location) from e
  847. return otLookups
  848. def makeTable(self, tag):
  849. table = getattr(otTables, tag, None)()
  850. table.Version = 0x00010000
  851. table.ScriptList = otTables.ScriptList()
  852. table.ScriptList.ScriptRecord = []
  853. table.FeatureList = otTables.FeatureList()
  854. table.FeatureList.FeatureRecord = []
  855. table.LookupList = otTables.LookupList()
  856. table.LookupList.Lookup = self.buildLookups_(tag)
  857. # Build a table for mapping (tag, lookup_indices) to feature_index.
  858. # For example, ('liga', (2,3,7)) --> 23.
  859. feature_indices = {}
  860. required_feature_indices = {} # ('latn', 'DEU') --> 23
  861. scripts = {} # 'latn' --> {'DEU': [23, 24]} for feature #23,24
  862. # Sort the feature table by feature tag:
  863. # https://github.com/fonttools/fonttools/issues/568
  864. sortFeatureTag = lambda f: (f[0][2], f[0][1], f[0][0], f[1])
  865. for key, lookups in sorted(self.features_.items(), key=sortFeatureTag):
  866. script, lang, feature_tag = key
  867. # l.lookup_index will be None when a lookup is not needed
  868. # for the table under construction. For example, substitution
  869. # rules will have no lookup_index while building GPOS tables.
  870. # We also deduplicate lookup indices, as they only get applied once
  871. # within a given feature:
  872. # https://github.com/fonttools/fonttools/issues/2946
  873. lookup_indices = tuple(
  874. dict.fromkeys(
  875. l.lookup_index for l in lookups if l.lookup_index is not None
  876. )
  877. )
  878. # order doesn't matter, but lookup_indices preserves it.
  879. # We want to combine identical sets of lookups (order doesn't matter)
  880. # but also respect the order provided by the user (although there's
  881. # a reasonable argument to just sort and dedupe, which fontc does)
  882. lookup_key = frozenset(lookup_indices)
  883. size_feature = tag == "GPOS" and feature_tag == "size"
  884. force_feature = self.any_feature_variations(feature_tag, tag)
  885. if len(lookup_indices) == 0 and not size_feature and not force_feature:
  886. continue
  887. for ix in lookup_indices:
  888. try:
  889. self.lookup_locations[tag][str(ix)] = self.lookup_locations[tag][
  890. str(ix)
  891. ]._replace(feature=key)
  892. except KeyError:
  893. warnings.warn(
  894. "feaLib.Builder subclass needs upgrading to "
  895. "stash debug information. See fonttools#2065."
  896. )
  897. feature_key = (feature_tag, lookup_key)
  898. feature_index = feature_indices.get(feature_key)
  899. if feature_index is None:
  900. feature_index = len(table.FeatureList.FeatureRecord)
  901. frec = otTables.FeatureRecord()
  902. frec.FeatureTag = feature_tag
  903. frec.Feature = otTables.Feature()
  904. frec.Feature.FeatureParams = self.buildFeatureParams(feature_tag)
  905. frec.Feature.LookupListIndex = list(lookup_indices)
  906. frec.Feature.LookupCount = len(lookup_indices)
  907. table.FeatureList.FeatureRecord.append(frec)
  908. feature_indices[feature_key] = feature_index
  909. scripts.setdefault(script, {}).setdefault(lang, []).append(feature_index)
  910. if self.required_features_.get((script, lang)) == feature_tag:
  911. required_feature_indices[(script, lang)] = feature_index
  912. # Build ScriptList.
  913. for script, lang_features in sorted(scripts.items()):
  914. srec = otTables.ScriptRecord()
  915. srec.ScriptTag = script
  916. srec.Script = otTables.Script()
  917. srec.Script.DefaultLangSys = None
  918. srec.Script.LangSysRecord = []
  919. for lang, feature_indices in sorted(lang_features.items()):
  920. langrec = otTables.LangSysRecord()
  921. langrec.LangSys = otTables.LangSys()
  922. langrec.LangSys.LookupOrder = None
  923. req_feature_index = required_feature_indices.get((script, lang))
  924. if req_feature_index is None:
  925. langrec.LangSys.ReqFeatureIndex = 0xFFFF
  926. else:
  927. langrec.LangSys.ReqFeatureIndex = req_feature_index
  928. langrec.LangSys.FeatureIndex = [
  929. i for i in feature_indices if i != req_feature_index
  930. ]
  931. langrec.LangSys.FeatureCount = len(langrec.LangSys.FeatureIndex)
  932. if lang == "dflt":
  933. srec.Script.DefaultLangSys = langrec.LangSys
  934. else:
  935. langrec.LangSysTag = lang
  936. srec.Script.LangSysRecord.append(langrec)
  937. srec.Script.LangSysCount = len(srec.Script.LangSysRecord)
  938. table.ScriptList.ScriptRecord.append(srec)
  939. table.ScriptList.ScriptCount = len(table.ScriptList.ScriptRecord)
  940. table.FeatureList.FeatureCount = len(table.FeatureList.FeatureRecord)
  941. table.LookupList.LookupCount = len(table.LookupList.Lookup)
  942. return table
  943. def makeFeatureVariations(self, table, table_tag):
  944. feature_vars = {}
  945. has_any_variations = False
  946. # Sort out which lookups to build, gather their indices
  947. for (_, _, feature_tag), variations in self.feature_variations_.items():
  948. feature_vars[feature_tag] = []
  949. for conditionset, builders in variations.items():
  950. raw_conditionset = self.conditionsets_[conditionset]
  951. indices = []
  952. for b in builders:
  953. if b.table != table_tag:
  954. continue
  955. assert b.lookup_index is not None
  956. indices.append(b.lookup_index)
  957. has_any_variations = True
  958. feature_vars[feature_tag].append((raw_conditionset, indices))
  959. if has_any_variations:
  960. for feature_tag, conditions_and_lookups in feature_vars.items():
  961. addFeatureVariationsRaw(
  962. self.font, table, conditions_and_lookups, feature_tag
  963. )
  964. def any_feature_variations(self, feature_tag, table_tag):
  965. for (_, _, feature), variations in self.feature_variations_.items():
  966. if feature != feature_tag:
  967. continue
  968. for conditionset, builders in variations.items():
  969. if any(b.table == table_tag for b in builders):
  970. return True
  971. return False
  972. def get_lookup_name_(self, lookup):
  973. rev = {v: k for k, v in self.named_lookups_.items()}
  974. if lookup in rev:
  975. return rev[lookup]
  976. return None
  977. def add_language_system(self, location, script, language):
  978. # OpenType Feature File Specification, section 4.b.i
  979. if script == "DFLT" and language == "dflt" and self.default_language_systems_:
  980. raise FeatureLibError(
  981. 'If "languagesystem DFLT dflt" is present, it must be '
  982. "the first of the languagesystem statements",
  983. location,
  984. )
  985. if script == "DFLT":
  986. if self.seen_non_DFLT_script_:
  987. raise FeatureLibError(
  988. 'languagesystems using the "DFLT" script tag must '
  989. "precede all other languagesystems",
  990. location,
  991. )
  992. else:
  993. self.seen_non_DFLT_script_ = True
  994. if (script, language) in self.default_language_systems_:
  995. raise FeatureLibError(
  996. '"languagesystem %s %s" has already been specified'
  997. % (script.strip(), language.strip()),
  998. location,
  999. )
  1000. self.default_language_systems_.add((script, language))
  1001. def get_default_language_systems_(self):
  1002. # OpenType Feature File specification, 4.b.i. languagesystem:
  1003. # If no "languagesystem" statement is present, then the
  1004. # implementation must behave exactly as though the following
  1005. # statement were present at the beginning of the feature file:
  1006. # languagesystem DFLT dflt;
  1007. if self.default_language_systems_:
  1008. return frozenset(self.default_language_systems_)
  1009. else:
  1010. return frozenset({("DFLT", "dflt")})
  1011. def start_feature(self, location, name, use_extension=False):
  1012. if use_extension and name != "aalt":
  1013. raise FeatureLibError(
  1014. "'useExtension' keyword for feature blocks is allowed only for 'aalt' feature",
  1015. location,
  1016. )
  1017. self.language_systems = self.get_default_language_systems_()
  1018. self.script_ = "DFLT"
  1019. self.cur_lookup_ = None
  1020. self.cur_feature_name_ = name
  1021. self.lookupflag_ = 0
  1022. self.lookupflag_markFilterSet_ = None
  1023. self.use_extension_ = use_extension
  1024. if name == "aalt":
  1025. self.aalt_location_ = location
  1026. self.aalt_use_extension_ = use_extension
  1027. def end_feature(self):
  1028. assert self.cur_feature_name_ is not None
  1029. self.cur_feature_name_ = None
  1030. self.language_systems = None
  1031. self.cur_lookup_ = None
  1032. self.lookupflag_ = 0
  1033. self.lookupflag_markFilterSet_ = None
  1034. self.use_extension_ = False
  1035. def start_lookup_block(self, location, name, use_extension=False):
  1036. if name in self.named_lookups_:
  1037. raise FeatureLibError(
  1038. 'Lookup "%s" has already been defined' % name, location
  1039. )
  1040. if self.cur_feature_name_ == "aalt":
  1041. raise FeatureLibError(
  1042. "Lookup blocks cannot be placed inside 'aalt' features; "
  1043. "move it out, and then refer to it with a lookup statement",
  1044. location,
  1045. )
  1046. self.cur_lookup_name_ = name
  1047. self.named_lookups_[name] = None
  1048. self.cur_lookup_ = None
  1049. self.use_extension_ = use_extension
  1050. if self.cur_feature_name_ is None:
  1051. self.lookupflag_ = 0
  1052. self.lookupflag_markFilterSet_ = None
  1053. def end_lookup_block(self):
  1054. assert self.cur_lookup_name_ is not None
  1055. self.cur_lookup_name_ = None
  1056. self.cur_lookup_ = None
  1057. self.use_extension_ = False
  1058. if self.cur_feature_name_ is None:
  1059. self.lookupflag_ = 0
  1060. self.lookupflag_markFilterSet_ = None
  1061. def add_lookup_call(self, lookup_name):
  1062. assert lookup_name in self.named_lookups_, lookup_name
  1063. self.cur_lookup_ = None
  1064. lookup = self.named_lookups_[lookup_name]
  1065. if lookup is not None: # skip empty named lookup
  1066. self.add_lookup_to_feature_(lookup, self.cur_feature_name_)
  1067. def set_font_revision(self, location, revision):
  1068. self.fontRevision_ = revision
  1069. def set_language(self, location, language, include_default, required):
  1070. assert len(language) == 4
  1071. if self.cur_feature_name_ in ("aalt", "size"):
  1072. raise FeatureLibError(
  1073. "Language statements are not allowed "
  1074. 'within "feature %s"' % self.cur_feature_name_,
  1075. location,
  1076. )
  1077. if self.cur_feature_name_ is None:
  1078. raise FeatureLibError(
  1079. "Language statements are not allowed "
  1080. "within standalone lookup blocks",
  1081. location,
  1082. )
  1083. self.cur_lookup_ = None
  1084. key = (self.script_, language, self.cur_feature_name_)
  1085. lookups = self.features_.get((key[0], "dflt", key[2]))
  1086. if (language == "dflt" or include_default) and lookups:
  1087. self.features_[key] = lookups[:]
  1088. else:
  1089. # if we aren't including default we need to manually remove the
  1090. # default lookups, which were added to all declared langsystems
  1091. # as they were encountered (we don't remove all lookups because
  1092. # we want to allow duplicate script/lang statements;
  1093. # see https://github.com/fonttools/fonttools/issues/3748
  1094. cur_lookups = self.features_.get(key, [])
  1095. self.features_[key] = [x for x in cur_lookups if x not in lookups]
  1096. self.language_systems = frozenset([(self.script_, language)])
  1097. if required:
  1098. key = (self.script_, language)
  1099. if key in self.required_features_:
  1100. raise FeatureLibError(
  1101. "Language %s (script %s) has already "
  1102. "specified feature %s as its required feature"
  1103. % (
  1104. language.strip(),
  1105. self.script_.strip(),
  1106. self.required_features_[key].strip(),
  1107. ),
  1108. location,
  1109. )
  1110. self.required_features_[key] = self.cur_feature_name_
  1111. def getMarkAttachClass_(self, location, glyphs):
  1112. glyphs = frozenset(glyphs)
  1113. id_ = self.markAttachClassID_.get(glyphs)
  1114. if id_ is not None:
  1115. return id_
  1116. id_ = len(self.markAttachClassID_) + 1
  1117. self.markAttachClassID_[glyphs] = id_
  1118. for glyph in glyphs:
  1119. if glyph in self.markAttach_:
  1120. _, loc = self.markAttach_[glyph]
  1121. raise FeatureLibError(
  1122. "Glyph %s already has been assigned "
  1123. "a MarkAttachmentType at %s" % (glyph, loc),
  1124. location,
  1125. )
  1126. self.markAttach_[glyph] = (id_, location)
  1127. return id_
  1128. def getMarkFilterSet_(self, location, glyphs):
  1129. glyphs = frozenset(glyphs)
  1130. id_ = self.markFilterSets_.get(glyphs)
  1131. if id_ is not None:
  1132. return id_
  1133. id_ = len(self.markFilterSets_)
  1134. self.markFilterSets_[glyphs] = id_
  1135. return id_
  1136. def set_lookup_flag(self, location, value, markAttach, markFilter):
  1137. value = value & 0xFF
  1138. if markAttach is not None:
  1139. markAttachClass = self.getMarkAttachClass_(location, markAttach)
  1140. value = value | (markAttachClass << 8)
  1141. if markFilter is not None:
  1142. markFilterSet = self.getMarkFilterSet_(location, markFilter)
  1143. value = value | 0x10
  1144. self.lookupflag_markFilterSet_ = markFilterSet
  1145. else:
  1146. self.lookupflag_markFilterSet_ = None
  1147. self.lookupflag_ = value
  1148. def set_script(self, location, script):
  1149. if self.cur_feature_name_ in ("aalt", "size"):
  1150. raise FeatureLibError(
  1151. "Script statements are not allowed "
  1152. 'within "feature %s"' % self.cur_feature_name_,
  1153. location,
  1154. )
  1155. if self.cur_feature_name_ is None:
  1156. raise FeatureLibError(
  1157. "Script statements are not allowed " "within standalone lookup blocks",
  1158. location,
  1159. )
  1160. if self.language_systems == {(script, "dflt")}:
  1161. # Nothing to do.
  1162. return
  1163. self.cur_lookup_ = None
  1164. self.script_ = script
  1165. self.lookupflag_ = 0
  1166. self.lookupflag_markFilterSet_ = None
  1167. self.set_language(location, "dflt", include_default=True, required=False)
  1168. def find_lookup_builders_(self, lookups):
  1169. """Helper for building chain contextual substitutions
  1170. Given a list of lookup names, finds the LookupBuilder for each name.
  1171. If an input name is None, it gets mapped to a None LookupBuilder.
  1172. """
  1173. lookup_builders = []
  1174. for lookuplist in lookups:
  1175. if lookuplist is not None:
  1176. lookup_builders.append(
  1177. [self.named_lookups_.get(l.name) for l in lookuplist]
  1178. )
  1179. else:
  1180. lookup_builders.append(None)
  1181. return lookup_builders
  1182. def add_attach_points(self, location, glyphs, contourPoints):
  1183. for glyph in glyphs:
  1184. self.attachPoints_.setdefault(glyph, set()).update(contourPoints)
  1185. def add_feature_reference(self, location, featureName):
  1186. if self.cur_feature_name_ != "aalt":
  1187. raise FeatureLibError(
  1188. 'Feature references are only allowed inside "feature aalt"', location
  1189. )
  1190. self.aalt_features_.append((location, featureName))
  1191. def add_featureName(self, tag):
  1192. self.featureNames_.add(tag)
  1193. def add_cv_parameter(self, tag):
  1194. self.cv_parameters_.add(tag)
  1195. def add_to_cv_num_named_params(self, tag):
  1196. """Adds new items to ``self.cv_num_named_params_``
  1197. or increments the count of existing items."""
  1198. if tag in self.cv_num_named_params_:
  1199. self.cv_num_named_params_[tag] += 1
  1200. else:
  1201. self.cv_num_named_params_[tag] = 1
  1202. def add_cv_character(self, character, tag):
  1203. self.cv_characters_[tag].append(character)
  1204. def set_base_axis(self, bases, scripts, vertical, minmax=[]):
  1205. if vertical:
  1206. self.base_vert_axis_ = (bases, scripts, minmax)
  1207. else:
  1208. self.base_horiz_axis_ = (bases, scripts, minmax)
  1209. def set_size_parameters(
  1210. self, location, DesignSize, SubfamilyID, RangeStart, RangeEnd
  1211. ):
  1212. if self.cur_feature_name_ != "size":
  1213. raise FeatureLibError(
  1214. "Parameters statements are not allowed "
  1215. 'within "feature %s"' % self.cur_feature_name_,
  1216. location,
  1217. )
  1218. self.size_parameters_ = [DesignSize, SubfamilyID, RangeStart, RangeEnd]
  1219. for script, lang in self.language_systems:
  1220. key = (script, lang, self.cur_feature_name_)
  1221. self.features_.setdefault(key, [])
  1222. # GSUB rules
  1223. def add_any_subst_(self, location, mapping):
  1224. lookup = self.get_lookup_(location, AnySubstBuilder, mapping=mapping)
  1225. for key, value in mapping.items():
  1226. if key in lookup.mapping:
  1227. if value == lookup.mapping[key]:
  1228. log.info(
  1229. 'Removing duplicate substitution from "%s" to "%s" at %s',
  1230. ", ".join(key),
  1231. ", ".join(value),
  1232. location,
  1233. )
  1234. else:
  1235. raise FeatureLibError(
  1236. 'Already defined substitution for "%s"' % ", ".join(key),
  1237. location,
  1238. )
  1239. lookup.mapping[key] = value
  1240. # GSUB 1
  1241. def add_single_subst(self, location, prefix, suffix, mapping, forceChain):
  1242. if self.cur_feature_name_ == "aalt":
  1243. for from_glyph, to_glyph in mapping.items():
  1244. alts = self.aalt_alternates_.setdefault(from_glyph, [])
  1245. if to_glyph not in alts:
  1246. alts.append(to_glyph)
  1247. return
  1248. if prefix or suffix or forceChain:
  1249. self.add_single_subst_chained_(location, prefix, suffix, mapping)
  1250. return
  1251. self.add_any_subst_(
  1252. location,
  1253. {(key,): (value,) for key, value in mapping.items()},
  1254. )
  1255. # GSUB 2
  1256. def add_multiple_subst(
  1257. self, location, prefix, glyph, suffix, replacements, forceChain=False
  1258. ):
  1259. if prefix or suffix or forceChain:
  1260. self.add_multi_subst_chained_(location, prefix, glyph, suffix, replacements)
  1261. return
  1262. self.add_any_subst_(
  1263. location,
  1264. {(glyph,): tuple(replacements)},
  1265. )
  1266. # GSUB 3
  1267. def add_alternate_subst(self, location, prefix, glyph, suffix, replacement):
  1268. if self.cur_feature_name_ == "aalt":
  1269. alts = self.aalt_alternates_.setdefault(glyph, [])
  1270. alts.extend(g for g in replacement if g not in alts)
  1271. return
  1272. if prefix or suffix:
  1273. chain = self.get_lookup_(location, ChainContextSubstBuilder)
  1274. lookup = self.get_chained_lookup_(location, AlternateSubstBuilder)
  1275. chain.rules.append(ChainContextualRule(prefix, [{glyph}], suffix, [lookup]))
  1276. else:
  1277. lookup = self.get_lookup_(location, AlternateSubstBuilder)
  1278. if glyph in lookup.alternates:
  1279. raise FeatureLibError(
  1280. 'Already defined alternates for glyph "%s"' % glyph, location
  1281. )
  1282. # We allow empty replacement glyphs here.
  1283. lookup.alternates[glyph] = replacement
  1284. # GSUB 4
  1285. def add_ligature_subst(
  1286. self, location, prefix, glyphs, suffix, replacement, forceChain
  1287. ):
  1288. if prefix or suffix or forceChain:
  1289. self.add_ligature_subst_chained_(
  1290. location, prefix, glyphs, suffix, replacement
  1291. )
  1292. return
  1293. if not all(glyphs):
  1294. raise FeatureLibError("Empty glyph class in substitution", location)
  1295. # OpenType feature file syntax, section 5.d, "Ligature substitution":
  1296. # "Since the OpenType specification does not allow ligature
  1297. # substitutions to be specified on target sequences that contain
  1298. # glyph classes, the implementation software will enumerate
  1299. # all specific glyph sequences if glyph classes are detected"
  1300. self.add_any_subst_(
  1301. location,
  1302. {g: (replacement,) for g in itertools.product(*glyphs)},
  1303. )
  1304. # GSUB 5/6
  1305. def add_chain_context_subst(self, location, prefix, glyphs, suffix, lookups):
  1306. if not all(glyphs) or not all(prefix) or not all(suffix):
  1307. raise FeatureLibError(
  1308. "Empty glyph class in contextual substitution", location
  1309. )
  1310. lookup = self.get_lookup_(location, ChainContextSubstBuilder)
  1311. lookup.rules.append(
  1312. ChainContextualRule(
  1313. prefix, glyphs, suffix, self.find_lookup_builders_(lookups)
  1314. )
  1315. )
  1316. def add_single_subst_chained_(self, location, prefix, suffix, mapping):
  1317. if not mapping or not all(prefix) or not all(suffix):
  1318. raise FeatureLibError(
  1319. "Empty glyph class in contextual substitution", location
  1320. )
  1321. # https://github.com/fonttools/fonttools/issues/512
  1322. # https://github.com/fonttools/fonttools/issues/2150
  1323. chain = self.get_lookup_(location, ChainContextSubstBuilder)
  1324. sub = chain.find_chainable_subst(mapping, SingleSubstBuilder)
  1325. if sub is None:
  1326. sub = self.get_chained_lookup_(location, SingleSubstBuilder)
  1327. sub.mapping.update(mapping)
  1328. chain.rules.append(
  1329. ChainContextualRule(prefix, [list(mapping.keys())], suffix, [sub])
  1330. )
  1331. def add_multi_subst_chained_(self, location, prefix, glyph, suffix, replacements):
  1332. if not all(prefix) or not all(suffix):
  1333. raise FeatureLibError(
  1334. "Empty glyph class in contextual substitution", location
  1335. )
  1336. # https://github.com/fonttools/fonttools/issues/3551
  1337. chain = self.get_lookup_(location, ChainContextSubstBuilder)
  1338. sub = chain.find_chainable_subst({glyph: replacements}, MultipleSubstBuilder)
  1339. if sub is None:
  1340. sub = self.get_chained_lookup_(location, MultipleSubstBuilder)
  1341. sub.mapping[glyph] = replacements
  1342. chain.rules.append(ChainContextualRule(prefix, [{glyph}], suffix, [sub]))
  1343. def add_ligature_subst_chained_(
  1344. self, location, prefix, glyphs, suffix, replacement
  1345. ):
  1346. # https://github.com/fonttools/fonttools/issues/3701
  1347. if not all(prefix) or not all(suffix):
  1348. raise FeatureLibError(
  1349. "Empty glyph class in contextual substitution", location
  1350. )
  1351. chain = self.get_lookup_(location, ChainContextSubstBuilder)
  1352. sub = chain.find_chainable_ligature_subst(glyphs, replacement)
  1353. if sub is None:
  1354. sub = self.get_chained_lookup_(location, LigatureSubstBuilder)
  1355. for g in itertools.product(*glyphs):
  1356. existing = sub.ligatures.get(g, replacement)
  1357. if existing != replacement:
  1358. raise FeatureLibError(
  1359. f"Conflicting ligature sub rules: '{g}' maps to '{existing}' and '{replacement}'",
  1360. location,
  1361. )
  1362. sub.ligatures[g] = replacement
  1363. chain.rules.append(ChainContextualRule(prefix, glyphs, suffix, [sub]))
  1364. # GSUB 8
  1365. def add_reverse_chain_single_subst(self, location, old_prefix, old_suffix, mapping):
  1366. if not mapping:
  1367. raise FeatureLibError("Empty glyph class in substitution", location)
  1368. lookup = self.get_lookup_(location, ReverseChainSingleSubstBuilder)
  1369. lookup.rules.append((old_prefix, old_suffix, mapping))
  1370. # GPOS rules
  1371. # GPOS 1
  1372. def add_single_pos(self, location, prefix, suffix, pos, forceChain):
  1373. if prefix or suffix or forceChain:
  1374. self.add_single_pos_chained_(location, prefix, suffix, pos)
  1375. else:
  1376. lookup = self.get_lookup_(location, SinglePosBuilder)
  1377. for glyphs, value in pos:
  1378. if not glyphs:
  1379. raise FeatureLibError(
  1380. "Empty glyph class in positioning rule", location
  1381. )
  1382. otValueRecord = self.makeOpenTypeValueRecord(
  1383. location, value, pairPosContext=False
  1384. )
  1385. for glyph in glyphs:
  1386. try:
  1387. lookup.add_pos(location, glyph, otValueRecord)
  1388. except OpenTypeLibError as e:
  1389. raise FeatureLibError(str(e), e.location) from e
  1390. # GPOS 2
  1391. def add_class_pair_pos(self, location, glyphclass1, value1, glyphclass2, value2):
  1392. if not glyphclass1 or not glyphclass2:
  1393. raise FeatureLibError("Empty glyph class in positioning rule", location)
  1394. lookup = self.get_lookup_(location, PairPosBuilder)
  1395. v1 = self.makeOpenTypeValueRecord(location, value1, pairPosContext=True)
  1396. v2 = self.makeOpenTypeValueRecord(location, value2, pairPosContext=True)
  1397. cls1 = tuple(sorted(set(glyphclass1)))
  1398. cls2 = tuple(sorted(set(glyphclass2)))
  1399. lookup.addClassPair(location, cls1, v1, cls2, v2)
  1400. def add_specific_pair_pos(self, location, glyph1, value1, glyph2, value2):
  1401. if not glyph1 or not glyph2:
  1402. raise FeatureLibError("Empty glyph class in positioning rule", location)
  1403. lookup = self.get_lookup_(location, PairPosBuilder)
  1404. v1 = self.makeOpenTypeValueRecord(location, value1, pairPosContext=True)
  1405. v2 = self.makeOpenTypeValueRecord(location, value2, pairPosContext=True)
  1406. lookup.addGlyphPair(location, glyph1, v1, glyph2, v2)
  1407. # GPOS 3
  1408. def add_cursive_pos(self, location, glyphclass, entryAnchor, exitAnchor):
  1409. if not glyphclass:
  1410. raise FeatureLibError("Empty glyph class in positioning rule", location)
  1411. lookup = self.get_lookup_(location, CursivePosBuilder)
  1412. lookup.add_attachment(
  1413. location,
  1414. glyphclass,
  1415. self.makeOpenTypeAnchor(location, entryAnchor),
  1416. self.makeOpenTypeAnchor(location, exitAnchor),
  1417. )
  1418. # GPOS 4
  1419. def add_mark_base_pos(self, location, bases, marks):
  1420. builder = self.get_lookup_(location, MarkBasePosBuilder)
  1421. self.add_marks_(location, builder, marks)
  1422. if not bases:
  1423. raise FeatureLibError("Empty glyph class in positioning rule", location)
  1424. for baseAnchor, markClass in marks:
  1425. otBaseAnchor = self.makeOpenTypeAnchor(location, baseAnchor)
  1426. for base in bases:
  1427. builder.bases.setdefault(base, {})[markClass.name] = otBaseAnchor
  1428. # GPOS 5
  1429. def add_mark_lig_pos(self, location, ligatures, components):
  1430. builder = self.get_lookup_(location, MarkLigPosBuilder)
  1431. componentAnchors = []
  1432. if not ligatures:
  1433. raise FeatureLibError("Empty glyph class in positioning rule", location)
  1434. for marks in components:
  1435. anchors = {}
  1436. self.add_marks_(location, builder, marks)
  1437. for ligAnchor, markClass in marks:
  1438. anchors[markClass.name] = self.makeOpenTypeAnchor(location, ligAnchor)
  1439. componentAnchors.append(anchors)
  1440. for glyph in ligatures:
  1441. builder.ligatures[glyph] = componentAnchors
  1442. # GPOS 6
  1443. def add_mark_mark_pos(self, location, baseMarks, marks):
  1444. builder = self.get_lookup_(location, MarkMarkPosBuilder)
  1445. self.add_marks_(location, builder, marks)
  1446. if not baseMarks:
  1447. raise FeatureLibError("Empty glyph class in positioning rule", location)
  1448. for baseAnchor, markClass in marks:
  1449. otBaseAnchor = self.makeOpenTypeAnchor(location, baseAnchor)
  1450. for baseMark in baseMarks:
  1451. builder.baseMarks.setdefault(baseMark, {})[
  1452. markClass.name
  1453. ] = otBaseAnchor
  1454. # GPOS 7/8
  1455. def add_chain_context_pos(self, location, prefix, glyphs, suffix, lookups):
  1456. if not all(glyphs) or not all(prefix) or not all(suffix):
  1457. raise FeatureLibError(
  1458. "Empty glyph class in contextual positioning rule", location
  1459. )
  1460. lookup = self.get_lookup_(location, ChainContextPosBuilder)
  1461. lookup.rules.append(
  1462. ChainContextualRule(
  1463. prefix, glyphs, suffix, self.find_lookup_builders_(lookups)
  1464. )
  1465. )
  1466. def add_single_pos_chained_(self, location, prefix, suffix, pos):
  1467. if not pos or not all(prefix) or not all(suffix):
  1468. raise FeatureLibError(
  1469. "Empty glyph class in contextual positioning rule", location
  1470. )
  1471. # https://github.com/fonttools/fonttools/issues/514
  1472. chain = self.get_lookup_(location, ChainContextPosBuilder)
  1473. targets = []
  1474. for _, _, _, lookups in chain.rules:
  1475. targets.extend(lookups)
  1476. subs = []
  1477. for glyphs, value in pos:
  1478. if value is None:
  1479. subs.append(None)
  1480. continue
  1481. otValue = self.makeOpenTypeValueRecord(
  1482. location, value, pairPosContext=False
  1483. )
  1484. sub = chain.find_chainable_single_pos(targets, glyphs, otValue)
  1485. if sub is None:
  1486. sub = self.get_chained_lookup_(location, SinglePosBuilder)
  1487. targets.append(sub)
  1488. for glyph in glyphs:
  1489. sub.add_pos(location, glyph, otValue)
  1490. subs.append(sub)
  1491. assert len(pos) == len(subs), (pos, subs)
  1492. chain.rules.append(
  1493. ChainContextualRule(prefix, [g for g, v in pos], suffix, subs)
  1494. )
  1495. def add_marks_(self, location, lookupBuilder, marks):
  1496. """Helper for add_mark_{base,liga,mark}_pos."""
  1497. for _, markClass in marks:
  1498. for markClassDef in markClass.definitions:
  1499. for mark in markClassDef.glyphs.glyphSet():
  1500. if mark not in lookupBuilder.marks:
  1501. otMarkAnchor = self.makeOpenTypeAnchor(
  1502. location, copy.deepcopy(markClassDef.anchor)
  1503. )
  1504. lookupBuilder.marks[mark] = (markClass.name, otMarkAnchor)
  1505. else:
  1506. existingMarkClass = lookupBuilder.marks[mark][0]
  1507. if markClass.name != existingMarkClass:
  1508. raise FeatureLibError(
  1509. "Glyph %s cannot be in both @%s and @%s"
  1510. % (mark, existingMarkClass, markClass.name),
  1511. location,
  1512. )
  1513. def add_subtable_break(self, location):
  1514. self.cur_lookup_.add_subtable_break(location)
  1515. def setGlyphClass_(self, location, glyph, glyphClass):
  1516. oldClass, oldLocation = self.glyphClassDefs_.get(glyph, (None, None))
  1517. if oldClass and oldClass != glyphClass:
  1518. raise FeatureLibError(
  1519. "Glyph %s was assigned to a different class at %s"
  1520. % (glyph, oldLocation),
  1521. location,
  1522. )
  1523. self.glyphClassDefs_[glyph] = (glyphClass, location)
  1524. def add_glyphClassDef(
  1525. self, location, baseGlyphs, ligatureGlyphs, markGlyphs, componentGlyphs
  1526. ):
  1527. for glyph in baseGlyphs:
  1528. self.setGlyphClass_(location, glyph, 1)
  1529. for glyph in ligatureGlyphs:
  1530. self.setGlyphClass_(location, glyph, 2)
  1531. for glyph in markGlyphs:
  1532. self.setGlyphClass_(location, glyph, 3)
  1533. for glyph in componentGlyphs:
  1534. self.setGlyphClass_(location, glyph, 4)
  1535. def add_ligatureCaretByIndex_(self, location, glyphs, carets):
  1536. for glyph in glyphs:
  1537. if glyph not in self.ligCaretPoints_:
  1538. self.ligCaretPoints_[glyph] = carets
  1539. def makeLigCaret(self, location, caret):
  1540. if not isinstance(caret, VariableScalar):
  1541. return caret
  1542. default, device = self.makeVariablePos(location, caret)
  1543. if device is not None:
  1544. return (default, device)
  1545. return default
  1546. def add_ligatureCaretByPos_(self, location, glyphs, carets):
  1547. carets = [self.makeLigCaret(location, caret) for caret in carets]
  1548. for glyph in glyphs:
  1549. if glyph not in self.ligCaretCoords_:
  1550. self.ligCaretCoords_[glyph] = carets
  1551. def add_name_record(self, location, nameID, platformID, platEncID, langID, string):
  1552. self.names_.append([nameID, platformID, platEncID, langID, string])
  1553. def add_os2_field(self, key, value):
  1554. self.os2_[key] = value
  1555. def add_hhea_field(self, key, value):
  1556. self.hhea_[key] = value
  1557. def add_vhea_field(self, key, value):
  1558. self.vhea_[key] = value
  1559. def add_conditionset(self, location, key, value):
  1560. if "fvar" not in self.font:
  1561. raise FeatureLibError(
  1562. "Cannot add feature variations to a font without an 'fvar' table",
  1563. location,
  1564. )
  1565. if key in self.conditionsets_:
  1566. raise FeatureLibError(
  1567. f"Condition set '{key}' has the same name as a previous condition set",
  1568. location,
  1569. )
  1570. # Normalize
  1571. axisMap = {
  1572. axis.axisTag: (axis.minValue, axis.defaultValue, axis.maxValue)
  1573. for axis in self.axes
  1574. }
  1575. value = {
  1576. tag: (
  1577. normalizeValue(bottom, axisMap[tag]),
  1578. normalizeValue(top, axisMap[tag]),
  1579. )
  1580. for tag, (bottom, top) in value.items()
  1581. }
  1582. # NOTE: This might result in rounding errors (off-by-ones) compared to
  1583. # rules in Designspace files, since we're working with what's in the
  1584. # `avar` table rather than the original values.
  1585. if "avar" in self.font:
  1586. mapping = self.font["avar"].segments
  1587. value = {
  1588. axis: tuple(
  1589. piecewiseLinearMap(v, mapping[axis]) if axis in mapping else v
  1590. for v in condition_range
  1591. )
  1592. for axis, condition_range in value.items()
  1593. }
  1594. self.conditionsets_[key] = value
  1595. def makeVariablePos(self, location, varscalar):
  1596. if not self.varstorebuilder:
  1597. raise FeatureLibError(
  1598. "Can't define a variable scalar in a non-variable font", location
  1599. )
  1600. varscalar.axes = self.axes
  1601. if not varscalar.does_vary:
  1602. return varscalar.default, None
  1603. try:
  1604. default, index = varscalar.add_to_variation_store(
  1605. self.varstorebuilder, self.model_cache, self.font.get("avar")
  1606. )
  1607. except VarLibError as e:
  1608. raise FeatureLibError(
  1609. "Failed to compute deltas for variable scalar", location
  1610. ) from e
  1611. device = None
  1612. if index is not None and index != 0xFFFFFFFF:
  1613. device = buildVarDevTable(index)
  1614. return default, device
  1615. def makeAnchorPos(self, varscalar, deviceTable, location):
  1616. device = None
  1617. if not isinstance(varscalar, VariableScalar):
  1618. if deviceTable is not None:
  1619. device = otl.buildDevice(dict(deviceTable))
  1620. return varscalar, device
  1621. default, device = self.makeVariablePos(location, varscalar)
  1622. if device is not None and deviceTable is not None:
  1623. raise FeatureLibError(
  1624. "Can't define a device coordinate and variable scalar", location
  1625. )
  1626. return default, device
  1627. def makeOpenTypeAnchor(self, location, anchor):
  1628. """ast.Anchor --> otTables.Anchor"""
  1629. if anchor is None:
  1630. return None
  1631. deviceX, deviceY = None, None
  1632. if anchor.xDeviceTable is not None:
  1633. deviceX = otl.buildDevice(dict(anchor.xDeviceTable))
  1634. if anchor.yDeviceTable is not None:
  1635. deviceY = otl.buildDevice(dict(anchor.yDeviceTable))
  1636. x, deviceX = self.makeAnchorPos(anchor.x, anchor.xDeviceTable, location)
  1637. y, deviceY = self.makeAnchorPos(anchor.y, anchor.yDeviceTable, location)
  1638. otlanchor = otl.buildAnchor(x, y, anchor.contourpoint, deviceX, deviceY)
  1639. return otlanchor
  1640. _VALUEREC_ATTRS = {
  1641. name[0].lower() + name[1:]: (name, isDevice)
  1642. for _, name, isDevice, _ in otBase.valueRecordFormat
  1643. if not name.startswith("Reserved")
  1644. }
  1645. def makeOpenTypeValueRecord(self, location, v, pairPosContext):
  1646. """ast.ValueRecord --> otBase.ValueRecord"""
  1647. if not v:
  1648. return None
  1649. vr = {}
  1650. for astName, (otName, isDevice) in self._VALUEREC_ATTRS.items():
  1651. val = getattr(v, astName, None)
  1652. if not val:
  1653. continue
  1654. if isDevice:
  1655. vr[otName] = otl.buildDevice(dict(val))
  1656. elif isinstance(val, VariableScalar):
  1657. otDeviceName = otName[0:4] + "Device"
  1658. feaDeviceName = otDeviceName[0].lower() + otDeviceName[1:]
  1659. if getattr(v, feaDeviceName):
  1660. raise FeatureLibError(
  1661. "Can't define a device coordinate and variable scalar", location
  1662. )
  1663. vr[otName], device = self.makeVariablePos(location, val)
  1664. if device is not None:
  1665. vr[otDeviceName] = device
  1666. else:
  1667. vr[otName] = val
  1668. if pairPosContext and not vr:
  1669. vr = {"YAdvance": 0} if v.vertical else {"XAdvance": 0}
  1670. valRec = otl.buildValue(vr)
  1671. return valRec