featureVars.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. """Module to build FeatureVariation tables:
  2. https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#featurevariations-table
  3. NOTE: The API is experimental and subject to change.
  4. """
  5. from fontTools.misc.dictTools import hashdict
  6. from fontTools.misc.intTools import bit_count
  7. from fontTools.ttLib import newTable
  8. from fontTools.ttLib.tables import otTables as ot
  9. from fontTools.ttLib.ttVisitor import TTVisitor
  10. from fontTools.otlLib.builder import buildLookup, buildSingleSubstSubtable
  11. from collections import OrderedDict
  12. from .errors import VarLibError, VarLibValidationError
  13. def addFeatureVariations(font, conditionalSubstitutions, featureTag="rvrn"):
  14. """Add conditional substitutions to a Variable Font.
  15. The `conditionalSubstitutions` argument is a list of (Region, Substitutions)
  16. tuples.
  17. A Region is a list of Boxes. A Box is a dict mapping axisTags to
  18. (minValue, maxValue) tuples. Irrelevant axes may be omitted and they are
  19. interpretted as extending to end of axis in each direction. A Box represents
  20. an orthogonal 'rectangular' subset of an N-dimensional design space.
  21. A Region represents a more complex subset of an N-dimensional design space,
  22. ie. the union of all the Boxes in the Region.
  23. For efficiency, Boxes within a Region should ideally not overlap, but
  24. functionality is not compromised if they do.
  25. The minimum and maximum values are expressed in normalized coordinates.
  26. A Substitution is a dict mapping source glyph names to substitute glyph names.
  27. Example:
  28. # >>> f = TTFont(srcPath)
  29. # >>> condSubst = [
  30. # ... # A list of (Region, Substitution) tuples.
  31. # ... ([{"wdth": (0.5, 1.0)}], {"cent": "cent.rvrn"}),
  32. # ... ([{"wght": (0.5, 1.0)}], {"dollar": "dollar.rvrn"}),
  33. # ... ]
  34. # >>> addFeatureVariations(f, condSubst)
  35. # >>> f.save(dstPath)
  36. The `featureTag` parameter takes either a str or a iterable of str (the single str
  37. is kept for backwards compatibility), and defines which feature(s) will be
  38. associated with the feature variations.
  39. Note, if this is "rvrn", then the substitution lookup will be inserted at the
  40. beginning of the lookup list so that it is processed before others, otherwise
  41. for any other feature tags it will be appended last.
  42. """
  43. # process first when "rvrn" is the only listed tag
  44. featureTags = [featureTag] if isinstance(featureTag, str) else sorted(featureTag)
  45. processLast = "rvrn" not in featureTags or len(featureTags) > 1
  46. _checkSubstitutionGlyphsExist(
  47. glyphNames=set(font.getGlyphOrder()),
  48. substitutions=conditionalSubstitutions,
  49. )
  50. substitutions = overlayFeatureVariations(conditionalSubstitutions)
  51. # turn substitution dicts into tuples of tuples, so they are hashable
  52. conditionalSubstitutions, allSubstitutions = makeSubstitutionsHashable(
  53. substitutions
  54. )
  55. if "GSUB" not in font:
  56. font["GSUB"] = buildGSUB()
  57. else:
  58. existingTags = _existingVariableFeatures(font["GSUB"].table).intersection(
  59. featureTags
  60. )
  61. if existingTags:
  62. raise VarLibError(
  63. f"FeatureVariations already exist for feature tag(s): {existingTags}"
  64. )
  65. # setup lookups
  66. lookupMap = buildSubstitutionLookups(
  67. font["GSUB"].table, allSubstitutions, processLast
  68. )
  69. # addFeatureVariationsRaw takes a list of
  70. # ( {condition}, [ lookup indices ] )
  71. # so rearrange our lookups to match
  72. conditionsAndLookups = []
  73. for conditionSet, substitutions in conditionalSubstitutions:
  74. conditionsAndLookups.append(
  75. (conditionSet, [lookupMap[s] for s in substitutions])
  76. )
  77. addFeatureVariationsRaw(font, font["GSUB"].table, conditionsAndLookups, featureTags)
  78. def _existingVariableFeatures(table):
  79. existingFeatureVarsTags = set()
  80. if hasattr(table, "FeatureVariations") and table.FeatureVariations is not None:
  81. features = table.FeatureList.FeatureRecord
  82. for fvr in table.FeatureVariations.FeatureVariationRecord:
  83. for ftsr in fvr.FeatureTableSubstitution.SubstitutionRecord:
  84. existingFeatureVarsTags.add(features[ftsr.FeatureIndex].FeatureTag)
  85. return existingFeatureVarsTags
  86. def _checkSubstitutionGlyphsExist(glyphNames, substitutions):
  87. referencedGlyphNames = set()
  88. for _, substitution in substitutions:
  89. referencedGlyphNames |= substitution.keys()
  90. referencedGlyphNames |= set(substitution.values())
  91. missing = referencedGlyphNames - glyphNames
  92. if missing:
  93. raise VarLibValidationError(
  94. "Missing glyphs are referenced in conditional substitution rules:"
  95. f" {', '.join(missing)}"
  96. )
  97. def overlayFeatureVariations(conditionalSubstitutions):
  98. """Compute overlaps between all conditional substitutions.
  99. The `conditionalSubstitutions` argument is a list of (Region, Substitutions)
  100. tuples.
  101. A Region is a list of Boxes. A Box is a dict mapping axisTags to
  102. (minValue, maxValue) tuples. Irrelevant axes may be omitted and they are
  103. interpretted as extending to end of axis in each direction. A Box represents
  104. an orthogonal 'rectangular' subset of an N-dimensional design space.
  105. A Region represents a more complex subset of an N-dimensional design space,
  106. ie. the union of all the Boxes in the Region.
  107. For efficiency, Boxes within a Region should ideally not overlap, but
  108. functionality is not compromised if they do.
  109. The minimum and maximum values are expressed in normalized coordinates.
  110. A Substitution is a dict mapping source glyph names to substitute glyph names.
  111. Returns data is in similar but different format. Overlaps of distinct
  112. substitution Boxes (*not* Regions) are explicitly listed as distinct rules,
  113. and rules with the same Box merged. The more specific rules appear earlier
  114. in the resulting list. Moreover, instead of just a dictionary of substitutions,
  115. a list of dictionaries is returned for substitutions corresponding to each
  116. unique space, with each dictionary being identical to one of the input
  117. substitution dictionaries. These dictionaries are not merged to allow data
  118. sharing when they are converted into font tables.
  119. Example::
  120. >>> condSubst = [
  121. ... # A list of (Region, Substitution) tuples.
  122. ... ([{"wght": (0.5, 1.0)}], {"dollar": "dollar.rvrn"}),
  123. ... ([{"wght": (0.5, 1.0)}], {"dollar": "dollar.rvrn"}),
  124. ... ([{"wdth": (0.5, 1.0)}], {"cent": "cent.rvrn"}),
  125. ... ([{"wght": (0.5, 1.0), "wdth": (-1, 1.0)}], {"dollar": "dollar.rvrn"}),
  126. ... ]
  127. >>> from pprint import pprint
  128. >>> pprint(overlayFeatureVariations(condSubst))
  129. [({'wdth': (0.5, 1.0), 'wght': (0.5, 1.0)},
  130. [{'dollar': 'dollar.rvrn'}, {'cent': 'cent.rvrn'}]),
  131. ({'wdth': (0.5, 1.0)}, [{'cent': 'cent.rvrn'}]),
  132. ({'wght': (0.5, 1.0)}, [{'dollar': 'dollar.rvrn'}])]
  133. """
  134. # Merge same-substitutions rules, as this creates fewer number oflookups.
  135. merged = OrderedDict()
  136. for value, key in conditionalSubstitutions:
  137. key = hashdict(key)
  138. if key in merged:
  139. merged[key].extend(value)
  140. else:
  141. merged[key] = value
  142. conditionalSubstitutions = [(v, dict(k)) for k, v in merged.items()]
  143. del merged
  144. # Merge same-region rules, as this is cheaper.
  145. # Also convert boxes to hashdict()
  146. #
  147. # Reversing is such that earlier entries win in case of conflicting substitution
  148. # rules for the same region.
  149. merged = OrderedDict()
  150. for key, value in reversed(conditionalSubstitutions):
  151. key = tuple(
  152. sorted(
  153. (hashdict(cleanupBox(k)) for k in key),
  154. key=lambda d: tuple(sorted(d.items())),
  155. )
  156. )
  157. if key in merged:
  158. merged[key].update(value)
  159. else:
  160. merged[key] = dict(value)
  161. conditionalSubstitutions = list(reversed(merged.items()))
  162. del merged
  163. # Overlay
  164. #
  165. # Rank is the bit-set of the index of all contributing layers.
  166. initMapInit = ((hashdict(), 0),) # Initializer representing the entire space
  167. boxMap = OrderedDict(initMapInit) # Map from Box to Rank
  168. for i, (currRegion, _) in enumerate(conditionalSubstitutions):
  169. newMap = OrderedDict(initMapInit)
  170. currRank = 1 << i
  171. for box, rank in boxMap.items():
  172. for currBox in currRegion:
  173. intersection, remainder = overlayBox(currBox, box)
  174. if intersection is not None:
  175. intersection = hashdict(intersection)
  176. newMap[intersection] = newMap.get(intersection, 0) | rank | currRank
  177. if remainder is not None:
  178. remainder = hashdict(remainder)
  179. newMap[remainder] = newMap.get(remainder, 0) | rank
  180. boxMap = newMap
  181. # Generate output
  182. items = []
  183. for box, rank in sorted(
  184. boxMap.items(), key=(lambda BoxAndRank: -bit_count(BoxAndRank[1]))
  185. ):
  186. # Skip any box that doesn't have any substitution.
  187. if rank == 0:
  188. continue
  189. substsList = []
  190. i = 0
  191. while rank:
  192. if rank & 1:
  193. substsList.append(conditionalSubstitutions[i][1])
  194. rank >>= 1
  195. i += 1
  196. items.append((dict(box), substsList))
  197. return items
  198. #
  199. # Terminology:
  200. #
  201. # A 'Box' is a dict representing an orthogonal "rectangular" bit of N-dimensional space.
  202. # The keys in the dict are axis tags, the values are (minValue, maxValue) tuples.
  203. # Missing dimensions (keys) are substituted by the default min and max values
  204. # from the corresponding axes.
  205. #
  206. def overlayBox(top, bot):
  207. """Overlays ``top`` box on top of ``bot`` box.
  208. Returns two items:
  209. * Box for intersection of ``top`` and ``bot``, or None if they don't intersect.
  210. * Box for remainder of ``bot``. Remainder box might not be exact (since the
  211. remainder might not be a simple box), but is inclusive of the exact
  212. remainder.
  213. """
  214. # Intersection
  215. intersection = {}
  216. intersection.update(top)
  217. intersection.update(bot)
  218. for axisTag in set(top) & set(bot):
  219. min1, max1 = top[axisTag]
  220. min2, max2 = bot[axisTag]
  221. minimum = max(min1, min2)
  222. maximum = min(max1, max2)
  223. if not minimum < maximum:
  224. return None, bot # Do not intersect
  225. intersection[axisTag] = minimum, maximum
  226. # Remainder
  227. #
  228. # Remainder is empty if bot's each axis range lies within that of intersection.
  229. #
  230. # Remainder is shrank if bot's each, except for exactly one, axis range lies
  231. # within that of intersection, and that one axis, it extrudes out of the
  232. # intersection only on one side.
  233. #
  234. # Bot is returned in full as remainder otherwise, as true remainder is not
  235. # representable as a single box.
  236. remainder = dict(bot)
  237. extruding = False
  238. fullyInside = True
  239. for axisTag in top:
  240. if axisTag in bot:
  241. continue
  242. extruding = True
  243. fullyInside = False
  244. break
  245. for axisTag in bot:
  246. if axisTag not in top:
  247. continue # Axis range lies fully within
  248. min1, max1 = intersection[axisTag]
  249. min2, max2 = bot[axisTag]
  250. if min1 <= min2 and max2 <= max1:
  251. continue # Axis range lies fully within
  252. # Bot's range doesn't fully lie within that of top's for this axis.
  253. # We know they intersect, so it cannot lie fully without either; so they
  254. # overlap.
  255. # If we have had an overlapping axis before, remainder is not
  256. # representable as a box, so return full bottom and go home.
  257. if extruding:
  258. return intersection, bot
  259. extruding = True
  260. fullyInside = False
  261. # Otherwise, cut remainder on this axis and continue.
  262. if min1 <= min2:
  263. # Right side survives.
  264. minimum = max(max1, min2)
  265. maximum = max2
  266. elif max2 <= max1:
  267. # Left side survives.
  268. minimum = min2
  269. maximum = min(min1, max2)
  270. else:
  271. # Remainder leaks out from both sides. Can't cut either.
  272. return intersection, bot
  273. remainder[axisTag] = minimum, maximum
  274. if fullyInside:
  275. # bot is fully within intersection. Remainder is empty.
  276. return intersection, None
  277. return intersection, remainder
  278. def cleanupBox(box):
  279. """Return a sparse copy of `box`, without redundant (default) values.
  280. >>> cleanupBox({})
  281. {}
  282. >>> cleanupBox({'wdth': (0.0, 1.0)})
  283. {'wdth': (0.0, 1.0)}
  284. >>> cleanupBox({'wdth': (-1.0, 1.0)})
  285. {}
  286. """
  287. return {tag: limit for tag, limit in box.items() if limit != (-1.0, 1.0)}
  288. #
  289. # Low level implementation
  290. #
  291. def addFeatureVariationsRaw(font, table, conditionalSubstitutions, featureTag="rvrn"):
  292. """Low level implementation of addFeatureVariations that directly
  293. models the possibilities of the FeatureVariations table."""
  294. featureTags = [featureTag] if isinstance(featureTag, str) else sorted(featureTag)
  295. processLast = "rvrn" not in featureTags or len(featureTags) > 1
  296. #
  297. # if a <featureTag> feature is not present:
  298. # make empty <featureTag> feature
  299. # sort features, get <featureTag> feature index
  300. # add <featureTag> feature to all scripts
  301. # if a <featureTag> feature is present:
  302. # reuse <featureTag> feature index
  303. # make lookups
  304. # add feature variations
  305. #
  306. if table.Version < 0x00010001:
  307. table.Version = 0x00010001 # allow table.FeatureVariations
  308. varFeatureIndices = set()
  309. existingTags = {
  310. feature.FeatureTag
  311. for feature in table.FeatureList.FeatureRecord
  312. if feature.FeatureTag in featureTags
  313. }
  314. newTags = set(featureTags) - existingTags
  315. if newTags:
  316. varFeatures = []
  317. for featureTag in sorted(newTags):
  318. varFeature = buildFeatureRecord(featureTag, [])
  319. table.FeatureList.FeatureRecord.append(varFeature)
  320. varFeatures.append(varFeature)
  321. table.FeatureList.FeatureCount = len(table.FeatureList.FeatureRecord)
  322. sortFeatureList(table)
  323. for varFeature in varFeatures:
  324. varFeatureIndex = table.FeatureList.FeatureRecord.index(varFeature)
  325. for scriptRecord in table.ScriptList.ScriptRecord:
  326. if scriptRecord.Script.DefaultLangSys is None:
  327. raise VarLibError(
  328. "Feature variations require that the script "
  329. f"'{scriptRecord.ScriptTag}' defines a default language system."
  330. )
  331. langSystems = [lsr.LangSys for lsr in scriptRecord.Script.LangSysRecord]
  332. for langSys in [scriptRecord.Script.DefaultLangSys] + langSystems:
  333. langSys.FeatureIndex.append(varFeatureIndex)
  334. langSys.FeatureCount = len(langSys.FeatureIndex)
  335. varFeatureIndices.add(varFeatureIndex)
  336. if existingTags:
  337. # indices may have changed if we inserted new features and sorted feature list
  338. # so we must do this after the above
  339. varFeatureIndices.update(
  340. index
  341. for index, feature in enumerate(table.FeatureList.FeatureRecord)
  342. if feature.FeatureTag in existingTags
  343. )
  344. axisIndices = {
  345. axis.axisTag: axisIndex for axisIndex, axis in enumerate(font["fvar"].axes)
  346. }
  347. hasFeatureVariations = (
  348. hasattr(table, "FeatureVariations") and table.FeatureVariations is not None
  349. )
  350. featureVariationRecords = []
  351. for conditionSet, lookupIndices in conditionalSubstitutions:
  352. conditionTable = []
  353. for axisTag, (minValue, maxValue) in sorted(conditionSet.items()):
  354. if minValue > maxValue:
  355. raise VarLibValidationError(
  356. "A condition set has a minimum value above the maximum value."
  357. )
  358. ct = buildConditionTable(axisIndices[axisTag], minValue, maxValue)
  359. conditionTable.append(ct)
  360. records = []
  361. for varFeatureIndex in sorted(varFeatureIndices):
  362. existingLookupIndices = table.FeatureList.FeatureRecord[
  363. varFeatureIndex
  364. ].Feature.LookupListIndex
  365. combinedLookupIndices = (
  366. existingLookupIndices + lookupIndices
  367. if processLast
  368. else lookupIndices + existingLookupIndices
  369. )
  370. records.append(
  371. buildFeatureTableSubstitutionRecord(
  372. varFeatureIndex, combinedLookupIndices
  373. )
  374. )
  375. if hasFeatureVariations and (
  376. fvr := findFeatureVariationRecord(table.FeatureVariations, conditionTable)
  377. ):
  378. fvr.FeatureTableSubstitution.SubstitutionRecord.extend(records)
  379. fvr.FeatureTableSubstitution.SubstitutionCount = len(
  380. fvr.FeatureTableSubstitution.SubstitutionRecord
  381. )
  382. else:
  383. featureVariationRecords.append(
  384. buildFeatureVariationRecord(conditionTable, records)
  385. )
  386. if hasFeatureVariations:
  387. if table.FeatureVariations.Version != 0x00010000:
  388. raise VarLibError(
  389. "Unsupported FeatureVariations table version: "
  390. f"0x{table.FeatureVariations.Version:08x} (expected 0x00010000)."
  391. )
  392. table.FeatureVariations.FeatureVariationRecord.extend(featureVariationRecords)
  393. table.FeatureVariations.FeatureVariationCount = len(
  394. table.FeatureVariations.FeatureVariationRecord
  395. )
  396. else:
  397. table.FeatureVariations = buildFeatureVariations(featureVariationRecords)
  398. #
  399. # Building GSUB/FeatureVariations internals
  400. #
  401. def buildGSUB():
  402. """Build a GSUB table from scratch."""
  403. fontTable = newTable("GSUB")
  404. gsub = fontTable.table = ot.GSUB()
  405. gsub.Version = 0x00010001 # allow gsub.FeatureVariations
  406. gsub.ScriptList = ot.ScriptList()
  407. gsub.ScriptList.ScriptRecord = []
  408. gsub.FeatureList = ot.FeatureList()
  409. gsub.FeatureList.FeatureRecord = []
  410. gsub.LookupList = ot.LookupList()
  411. gsub.LookupList.Lookup = []
  412. srec = ot.ScriptRecord()
  413. srec.ScriptTag = "DFLT"
  414. srec.Script = ot.Script()
  415. srec.Script.DefaultLangSys = None
  416. srec.Script.LangSysRecord = []
  417. srec.Script.LangSysCount = 0
  418. langrec = ot.LangSysRecord()
  419. langrec.LangSys = ot.LangSys()
  420. langrec.LangSys.ReqFeatureIndex = 0xFFFF
  421. langrec.LangSys.FeatureIndex = []
  422. srec.Script.DefaultLangSys = langrec.LangSys
  423. gsub.ScriptList.ScriptRecord.append(srec)
  424. gsub.ScriptList.ScriptCount = 1
  425. gsub.FeatureVariations = None
  426. return fontTable
  427. def makeSubstitutionsHashable(conditionalSubstitutions):
  428. """Turn all the substitution dictionaries in sorted tuples of tuples so
  429. they are hashable, to detect duplicates so we don't write out redundant
  430. data."""
  431. allSubstitutions = set()
  432. condSubst = []
  433. for conditionSet, substitutionMaps in conditionalSubstitutions:
  434. substitutions = []
  435. for substitutionMap in substitutionMaps:
  436. subst = tuple(sorted(substitutionMap.items()))
  437. substitutions.append(subst)
  438. allSubstitutions.add(subst)
  439. condSubst.append((conditionSet, substitutions))
  440. return condSubst, sorted(allSubstitutions)
  441. class ShifterVisitor(TTVisitor):
  442. def __init__(self, shift):
  443. self.shift = shift
  444. @ShifterVisitor.register_attr(ot.Feature, "LookupListIndex") # GSUB/GPOS
  445. def visit(visitor, obj, attr, value):
  446. shift = visitor.shift
  447. value = [l + shift for l in value]
  448. setattr(obj, attr, value)
  449. @ShifterVisitor.register_attr(
  450. (ot.SubstLookupRecord, ot.PosLookupRecord), "LookupListIndex"
  451. )
  452. def visit(visitor, obj, attr, value):
  453. setattr(obj, attr, visitor.shift + value)
  454. def buildSubstitutionLookups(gsub, allSubstitutions, processLast=False):
  455. """Build the lookups for the glyph substitutions, return a dict mapping
  456. the substitution to lookup indices."""
  457. # Insert lookups at the beginning of the lookup vector
  458. # https://github.com/googlefonts/fontmake/issues/950
  459. firstIndex = len(gsub.LookupList.Lookup) if processLast else 0
  460. lookupMap = {}
  461. for i, substitutionMap in enumerate(allSubstitutions):
  462. lookupMap[substitutionMap] = firstIndex + i
  463. if not processLast:
  464. # Shift all lookup indices in gsub by len(allSubstitutions)
  465. shift = len(allSubstitutions)
  466. visitor = ShifterVisitor(shift)
  467. visitor.visit(gsub.FeatureList.FeatureRecord)
  468. visitor.visit(gsub.LookupList.Lookup)
  469. for i, subst in enumerate(allSubstitutions):
  470. substMap = dict(subst)
  471. lookup = buildLookup([buildSingleSubstSubtable(substMap)])
  472. if processLast:
  473. gsub.LookupList.Lookup.append(lookup)
  474. else:
  475. gsub.LookupList.Lookup.insert(i, lookup)
  476. assert gsub.LookupList.Lookup[lookupMap[subst]] is lookup
  477. gsub.LookupList.LookupCount = len(gsub.LookupList.Lookup)
  478. return lookupMap
  479. def buildFeatureVariations(featureVariationRecords):
  480. """Build the FeatureVariations subtable."""
  481. fv = ot.FeatureVariations()
  482. fv.Version = 0x00010000
  483. fv.FeatureVariationRecord = featureVariationRecords
  484. fv.FeatureVariationCount = len(featureVariationRecords)
  485. return fv
  486. def buildFeatureRecord(featureTag, lookupListIndices):
  487. """Build a FeatureRecord."""
  488. fr = ot.FeatureRecord()
  489. fr.FeatureTag = featureTag
  490. fr.Feature = ot.Feature()
  491. fr.Feature.LookupListIndex = lookupListIndices
  492. fr.Feature.populateDefaults()
  493. return fr
  494. def buildFeatureVariationRecord(conditionTable, substitutionRecords):
  495. """Build a FeatureVariationRecord."""
  496. fvr = ot.FeatureVariationRecord()
  497. fvr.ConditionSet = ot.ConditionSet()
  498. fvr.ConditionSet.ConditionTable = conditionTable
  499. fvr.ConditionSet.ConditionCount = len(conditionTable)
  500. fvr.FeatureTableSubstitution = ot.FeatureTableSubstitution()
  501. fvr.FeatureTableSubstitution.Version = 0x00010000
  502. fvr.FeatureTableSubstitution.SubstitutionRecord = substitutionRecords
  503. fvr.FeatureTableSubstitution.SubstitutionCount = len(substitutionRecords)
  504. return fvr
  505. def buildFeatureTableSubstitutionRecord(featureIndex, lookupListIndices):
  506. """Build a FeatureTableSubstitutionRecord."""
  507. ftsr = ot.FeatureTableSubstitutionRecord()
  508. ftsr.FeatureIndex = featureIndex
  509. ftsr.Feature = ot.Feature()
  510. ftsr.Feature.LookupListIndex = lookupListIndices
  511. ftsr.Feature.LookupCount = len(lookupListIndices)
  512. return ftsr
  513. def buildConditionTable(axisIndex, filterRangeMinValue, filterRangeMaxValue):
  514. """Build a ConditionTable."""
  515. ct = ot.ConditionTable()
  516. ct.Format = 1
  517. ct.AxisIndex = axisIndex
  518. ct.FilterRangeMinValue = filterRangeMinValue
  519. ct.FilterRangeMaxValue = filterRangeMaxValue
  520. return ct
  521. def findFeatureVariationRecord(featureVariations, conditionTable):
  522. """Find a FeatureVariationRecord that has the same conditionTable."""
  523. if featureVariations.Version != 0x00010000:
  524. raise VarLibError(
  525. "Unsupported FeatureVariations table version: "
  526. f"0x{featureVariations.Version:08x} (expected 0x00010000)."
  527. )
  528. for fvr in featureVariations.FeatureVariationRecord:
  529. if conditionTable == fvr.ConditionSet.ConditionTable:
  530. return fvr
  531. return None
  532. def sortFeatureList(table):
  533. """Sort the feature list by feature tag, and remap the feature indices
  534. elsewhere. This is needed after the feature list has been modified.
  535. """
  536. # decorate, sort, undecorate, because we need to make an index remapping table
  537. tagIndexFea = [
  538. (fea.FeatureTag, index, fea)
  539. for index, fea in enumerate(table.FeatureList.FeatureRecord)
  540. ]
  541. tagIndexFea.sort()
  542. table.FeatureList.FeatureRecord = [fea for tag, index, fea in tagIndexFea]
  543. featureRemap = dict(
  544. zip([index for tag, index, fea in tagIndexFea], range(len(tagIndexFea)))
  545. )
  546. # Remap the feature indices
  547. remapFeatures(table, featureRemap)
  548. def remapFeatures(table, featureRemap):
  549. """Go through the scripts list, and remap feature indices."""
  550. for scriptIndex, script in enumerate(table.ScriptList.ScriptRecord):
  551. defaultLangSys = script.Script.DefaultLangSys
  552. if defaultLangSys is not None:
  553. _remapLangSys(defaultLangSys, featureRemap)
  554. for langSysRecordIndex, langSysRec in enumerate(script.Script.LangSysRecord):
  555. langSys = langSysRec.LangSys
  556. _remapLangSys(langSys, featureRemap)
  557. if hasattr(table, "FeatureVariations") and table.FeatureVariations is not None:
  558. for fvr in table.FeatureVariations.FeatureVariationRecord:
  559. for ftsr in fvr.FeatureTableSubstitution.SubstitutionRecord:
  560. ftsr.FeatureIndex = featureRemap[ftsr.FeatureIndex]
  561. def _remapLangSys(langSys, featureRemap):
  562. if langSys.ReqFeatureIndex != 0xFFFF:
  563. langSys.ReqFeatureIndex = featureRemap[langSys.ReqFeatureIndex]
  564. langSys.FeatureIndex = [featureRemap[index] for index in langSys.FeatureIndex]
  565. if __name__ == "__main__":
  566. import doctest, sys
  567. sys.exit(doctest.testmod().failed)