featureVars.py 26 KB

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