builder.py 69 KB

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