featureVars.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. featureVariationRecords = []
  348. for conditionSet, lookupIndices in conditionalSubstitutions:
  349. conditionTable = []
  350. for axisTag, (minValue, maxValue) in sorted(conditionSet.items()):
  351. if minValue > maxValue:
  352. raise VarLibValidationError(
  353. "A condition set has a minimum value above the maximum value."
  354. )
  355. ct = buildConditionTable(axisIndices[axisTag], minValue, maxValue)
  356. conditionTable.append(ct)
  357. records = []
  358. for varFeatureIndex in sorted(varFeatureIndices):
  359. existingLookupIndices = table.FeatureList.FeatureRecord[
  360. varFeatureIndex
  361. ].Feature.LookupListIndex
  362. combinedLookupIndices = (
  363. existingLookupIndices + lookupIndices
  364. if processLast
  365. else lookupIndices + existingLookupIndices
  366. )
  367. records.append(
  368. buildFeatureTableSubstitutionRecord(
  369. varFeatureIndex, combinedLookupIndices
  370. )
  371. )
  372. featureVariationRecords.append(
  373. buildFeatureVariationRecord(conditionTable, records)
  374. )
  375. if hasattr(table, "FeatureVariations") and table.FeatureVariations is not None:
  376. if table.FeatureVariations.Version != 0x00010000:
  377. raise VarLibError(
  378. "Unsupported FeatureVariations table version: "
  379. f"0x{table.FeatureVariations.Version:08x} (expected 0x00010000)."
  380. )
  381. table.FeatureVariations.FeatureVariationRecord.extend(featureVariationRecords)
  382. table.FeatureVariations.FeatureVariationCount = len(
  383. table.FeatureVariations.FeatureVariationRecord
  384. )
  385. else:
  386. table.FeatureVariations = buildFeatureVariations(featureVariationRecords)
  387. #
  388. # Building GSUB/FeatureVariations internals
  389. #
  390. def buildGSUB():
  391. """Build a GSUB table from scratch."""
  392. fontTable = newTable("GSUB")
  393. gsub = fontTable.table = ot.GSUB()
  394. gsub.Version = 0x00010001 # allow gsub.FeatureVariations
  395. gsub.ScriptList = ot.ScriptList()
  396. gsub.ScriptList.ScriptRecord = []
  397. gsub.FeatureList = ot.FeatureList()
  398. gsub.FeatureList.FeatureRecord = []
  399. gsub.LookupList = ot.LookupList()
  400. gsub.LookupList.Lookup = []
  401. srec = ot.ScriptRecord()
  402. srec.ScriptTag = "DFLT"
  403. srec.Script = ot.Script()
  404. srec.Script.DefaultLangSys = None
  405. srec.Script.LangSysRecord = []
  406. srec.Script.LangSysCount = 0
  407. langrec = ot.LangSysRecord()
  408. langrec.LangSys = ot.LangSys()
  409. langrec.LangSys.ReqFeatureIndex = 0xFFFF
  410. langrec.LangSys.FeatureIndex = []
  411. srec.Script.DefaultLangSys = langrec.LangSys
  412. gsub.ScriptList.ScriptRecord.append(srec)
  413. gsub.ScriptList.ScriptCount = 1
  414. gsub.FeatureVariations = None
  415. return fontTable
  416. def makeSubstitutionsHashable(conditionalSubstitutions):
  417. """Turn all the substitution dictionaries in sorted tuples of tuples so
  418. they are hashable, to detect duplicates so we don't write out redundant
  419. data."""
  420. allSubstitutions = set()
  421. condSubst = []
  422. for conditionSet, substitutionMaps in conditionalSubstitutions:
  423. substitutions = []
  424. for substitutionMap in substitutionMaps:
  425. subst = tuple(sorted(substitutionMap.items()))
  426. substitutions.append(subst)
  427. allSubstitutions.add(subst)
  428. condSubst.append((conditionSet, substitutions))
  429. return condSubst, sorted(allSubstitutions)
  430. class ShifterVisitor(TTVisitor):
  431. def __init__(self, shift):
  432. self.shift = shift
  433. @ShifterVisitor.register_attr(ot.Feature, "LookupListIndex") # GSUB/GPOS
  434. def visit(visitor, obj, attr, value):
  435. shift = visitor.shift
  436. value = [l + shift for l in value]
  437. setattr(obj, attr, value)
  438. @ShifterVisitor.register_attr(
  439. (ot.SubstLookupRecord, ot.PosLookupRecord), "LookupListIndex"
  440. )
  441. def visit(visitor, obj, attr, value):
  442. setattr(obj, attr, visitor.shift + value)
  443. def buildSubstitutionLookups(gsub, allSubstitutions, processLast=False):
  444. """Build the lookups for the glyph substitutions, return a dict mapping
  445. the substitution to lookup indices."""
  446. # Insert lookups at the beginning of the lookup vector
  447. # https://github.com/googlefonts/fontmake/issues/950
  448. firstIndex = len(gsub.LookupList.Lookup) if processLast else 0
  449. lookupMap = {}
  450. for i, substitutionMap in enumerate(allSubstitutions):
  451. lookupMap[substitutionMap] = firstIndex + i
  452. if not processLast:
  453. # Shift all lookup indices in gsub by len(allSubstitutions)
  454. shift = len(allSubstitutions)
  455. visitor = ShifterVisitor(shift)
  456. visitor.visit(gsub.FeatureList.FeatureRecord)
  457. visitor.visit(gsub.LookupList.Lookup)
  458. for i, subst in enumerate(allSubstitutions):
  459. substMap = dict(subst)
  460. lookup = buildLookup([buildSingleSubstSubtable(substMap)])
  461. if processLast:
  462. gsub.LookupList.Lookup.append(lookup)
  463. else:
  464. gsub.LookupList.Lookup.insert(i, lookup)
  465. assert gsub.LookupList.Lookup[lookupMap[subst]] is lookup
  466. gsub.LookupList.LookupCount = len(gsub.LookupList.Lookup)
  467. return lookupMap
  468. def buildFeatureVariations(featureVariationRecords):
  469. """Build the FeatureVariations subtable."""
  470. fv = ot.FeatureVariations()
  471. fv.Version = 0x00010000
  472. fv.FeatureVariationRecord = featureVariationRecords
  473. fv.FeatureVariationCount = len(featureVariationRecords)
  474. return fv
  475. def buildFeatureRecord(featureTag, lookupListIndices):
  476. """Build a FeatureRecord."""
  477. fr = ot.FeatureRecord()
  478. fr.FeatureTag = featureTag
  479. fr.Feature = ot.Feature()
  480. fr.Feature.LookupListIndex = lookupListIndices
  481. fr.Feature.populateDefaults()
  482. return fr
  483. def buildFeatureVariationRecord(conditionTable, substitutionRecords):
  484. """Build a FeatureVariationRecord."""
  485. fvr = ot.FeatureVariationRecord()
  486. fvr.ConditionSet = ot.ConditionSet()
  487. fvr.ConditionSet.ConditionTable = conditionTable
  488. fvr.ConditionSet.ConditionCount = len(conditionTable)
  489. fvr.FeatureTableSubstitution = ot.FeatureTableSubstitution()
  490. fvr.FeatureTableSubstitution.Version = 0x00010000
  491. fvr.FeatureTableSubstitution.SubstitutionRecord = substitutionRecords
  492. fvr.FeatureTableSubstitution.SubstitutionCount = len(substitutionRecords)
  493. return fvr
  494. def buildFeatureTableSubstitutionRecord(featureIndex, lookupListIndices):
  495. """Build a FeatureTableSubstitutionRecord."""
  496. ftsr = ot.FeatureTableSubstitutionRecord()
  497. ftsr.FeatureIndex = featureIndex
  498. ftsr.Feature = ot.Feature()
  499. ftsr.Feature.LookupListIndex = lookupListIndices
  500. ftsr.Feature.LookupCount = len(lookupListIndices)
  501. return ftsr
  502. def buildConditionTable(axisIndex, filterRangeMinValue, filterRangeMaxValue):
  503. """Build a ConditionTable."""
  504. ct = ot.ConditionTable()
  505. ct.Format = 1
  506. ct.AxisIndex = axisIndex
  507. ct.FilterRangeMinValue = filterRangeMinValue
  508. ct.FilterRangeMaxValue = filterRangeMaxValue
  509. return ct
  510. def sortFeatureList(table):
  511. """Sort the feature list by feature tag, and remap the feature indices
  512. elsewhere. This is needed after the feature list has been modified.
  513. """
  514. # decorate, sort, undecorate, because we need to make an index remapping table
  515. tagIndexFea = [
  516. (fea.FeatureTag, index, fea)
  517. for index, fea in enumerate(table.FeatureList.FeatureRecord)
  518. ]
  519. tagIndexFea.sort()
  520. table.FeatureList.FeatureRecord = [fea for tag, index, fea in tagIndexFea]
  521. featureRemap = dict(
  522. zip([index for tag, index, fea in tagIndexFea], range(len(tagIndexFea)))
  523. )
  524. # Remap the feature indices
  525. remapFeatures(table, featureRemap)
  526. def remapFeatures(table, featureRemap):
  527. """Go through the scripts list, and remap feature indices."""
  528. for scriptIndex, script in enumerate(table.ScriptList.ScriptRecord):
  529. defaultLangSys = script.Script.DefaultLangSys
  530. if defaultLangSys is not None:
  531. _remapLangSys(defaultLangSys, featureRemap)
  532. for langSysRecordIndex, langSysRec in enumerate(script.Script.LangSysRecord):
  533. langSys = langSysRec.LangSys
  534. _remapLangSys(langSys, featureRemap)
  535. if hasattr(table, "FeatureVariations") and table.FeatureVariations is not None:
  536. for fvr in table.FeatureVariations.FeatureVariationRecord:
  537. for ftsr in fvr.FeatureTableSubstitution.SubstitutionRecord:
  538. ftsr.FeatureIndex = featureRemap[ftsr.FeatureIndex]
  539. def _remapLangSys(langSys, featureRemap):
  540. if langSys.ReqFeatureIndex != 0xFFFF:
  541. langSys.ReqFeatureIndex = featureRemap[langSys.ReqFeatureIndex]
  542. langSys.FeatureIndex = [featureRemap[index] for index in langSys.FeatureIndex]
  543. if __name__ == "__main__":
  544. import doctest, sys
  545. sys.exit(doctest.testmod().failed)