__init__.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  1. """ Partially instantiate a variable font.
  2. The module exports an `instantiateVariableFont` function and CLI that allow to
  3. create full instances (i.e. static fonts) from variable fonts, as well as "partial"
  4. variable fonts that only contain a subset of the original variation space.
  5. For example, if you wish to pin the width axis to a given location while also
  6. restricting the weight axis to 400..700 range, you can do::
  7. $ fonttools varLib.instancer ./NotoSans-VF.ttf wdth=85 wght=400:700
  8. See `fonttools varLib.instancer --help` for more info on the CLI options.
  9. The module's entry point is the `instantiateVariableFont` function, which takes
  10. a TTFont object and a dict specifying either axis coodinates or (min, max) ranges,
  11. and returns a new TTFont representing either a partial VF, or full instance if all
  12. the VF axes were given an explicit coordinate.
  13. E.g. here's how to pin the wght axis at a given location in a wght+wdth variable
  14. font, keeping only the deltas associated with the wdth axis::
  15. | >>> from fontTools import ttLib
  16. | >>> from fontTools.varLib import instancer
  17. | >>> varfont = ttLib.TTFont("path/to/MyVariableFont.ttf")
  18. | >>> [a.axisTag for a in varfont["fvar"].axes] # the varfont's current axes
  19. | ['wght', 'wdth']
  20. | >>> partial = instancer.instantiateVariableFont(varfont, {"wght": 300})
  21. | >>> [a.axisTag for a in partial["fvar"].axes] # axes left after pinning 'wght'
  22. | ['wdth']
  23. If the input location specifies all the axes, the resulting instance is no longer
  24. 'variable' (same as using fontools varLib.mutator):
  25. | >>> instance = instancer.instantiateVariableFont(
  26. | ... varfont, {"wght": 700, "wdth": 67.5}
  27. | ... )
  28. | >>> "fvar" not in instance
  29. | True
  30. If one just want to drop an axis at the default location, without knowing in
  31. advance what the default value for that axis is, one can pass a `None` value:
  32. | >>> instance = instancer.instantiateVariableFont(varfont, {"wght": None})
  33. | >>> len(varfont["fvar"].axes)
  34. | 1
  35. From the console script, this is equivalent to passing `wght=drop` as input.
  36. This module is similar to fontTools.varLib.mutator, which it's intended to supersede.
  37. Note that, unlike varLib.mutator, when an axis is not mentioned in the input
  38. location, the varLib.instancer will keep the axis and the corresponding deltas,
  39. whereas mutator implicitly drops the axis at its default coordinate.
  40. The module supports all the following "levels" of instancing, which can of
  41. course be combined:
  42. L1
  43. dropping one or more axes while leaving the default tables unmodified;
  44. | >>> font = instancer.instantiateVariableFont(varfont, {"wght": None})
  45. L2
  46. dropping one or more axes while pinning them at non-default locations;
  47. | >>> font = instancer.instantiateVariableFont(varfont, {"wght": 700})
  48. L3
  49. restricting the range of variation of one or more axes, by setting either
  50. a new minimum or maximum, potentially -- though not necessarily -- dropping
  51. entire regions of variations that fall completely outside this new range.
  52. | >>> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300)})
  53. L4
  54. moving the default location of an axis, by specifying (min,defalt,max) values:
  55. | >>> font = instancer.instantiateVariableFont(varfont, {"wght": (100, 300, 700)})
  56. Currently only TrueType-flavored variable fonts (i.e. containing 'glyf' table)
  57. are supported, but support for CFF2 variable fonts will be added soon.
  58. The discussion and implementation of these features are tracked at
  59. https://github.com/fonttools/fonttools/issues/1537
  60. """
  61. from fontTools.misc.fixedTools import (
  62. floatToFixedToFloat,
  63. strToFixedToFloat,
  64. otRound,
  65. )
  66. from fontTools.varLib.models import normalizeValue, piecewiseLinearMap
  67. from fontTools.ttLib import TTFont
  68. from fontTools.ttLib.tables.TupleVariation import TupleVariation
  69. from fontTools.ttLib.tables import _g_l_y_f
  70. from fontTools import varLib
  71. # we import the `subset` module because we use the `prune_lookups` method on the GSUB
  72. # table class, and that method is only defined dynamically upon importing `subset`
  73. from fontTools import subset # noqa: F401
  74. from fontTools.varLib import builder
  75. from fontTools.varLib.mvar import MVAR_ENTRIES
  76. from fontTools.varLib.merger import MutatorMerger
  77. from fontTools.varLib.instancer import names
  78. from .featureVars import instantiateFeatureVariations
  79. from fontTools.misc.cliTools import makeOutputFileName
  80. from fontTools.varLib.instancer import solver
  81. import collections
  82. import dataclasses
  83. from contextlib import contextmanager
  84. from copy import deepcopy
  85. from enum import IntEnum
  86. import logging
  87. import os
  88. import re
  89. from typing import Dict, Iterable, Mapping, Optional, Sequence, Tuple, Union
  90. import warnings
  91. log = logging.getLogger("fontTools.varLib.instancer")
  92. def AxisRange(minimum, maximum):
  93. warnings.warn(
  94. "AxisRange is deprecated; use AxisTriple instead",
  95. DeprecationWarning,
  96. stacklevel=2,
  97. )
  98. return AxisTriple(minimum, None, maximum)
  99. def NormalizedAxisRange(minimum, maximum):
  100. warnings.warn(
  101. "NormalizedAxisRange is deprecated; use AxisTriple instead",
  102. DeprecationWarning,
  103. stacklevel=2,
  104. )
  105. return NormalizedAxisTriple(minimum, None, maximum)
  106. @dataclasses.dataclass(frozen=True, order=True, repr=False)
  107. class AxisTriple(Sequence):
  108. """A triple of (min, default, max) axis values.
  109. Any of the values can be None, in which case the limitRangeAndPopulateDefaults()
  110. method can be used to fill in the missing values based on the fvar axis values.
  111. """
  112. minimum: Optional[float]
  113. default: Optional[float]
  114. maximum: Optional[float]
  115. def __post_init__(self):
  116. if self.default is None and self.minimum == self.maximum:
  117. object.__setattr__(self, "default", self.minimum)
  118. if (
  119. (
  120. self.minimum is not None
  121. and self.default is not None
  122. and self.minimum > self.default
  123. )
  124. or (
  125. self.default is not None
  126. and self.maximum is not None
  127. and self.default > self.maximum
  128. )
  129. or (
  130. self.minimum is not None
  131. and self.maximum is not None
  132. and self.minimum > self.maximum
  133. )
  134. ):
  135. raise ValueError(
  136. f"{type(self).__name__} minimum ({self.minimum}), default ({self.default}), maximum ({self.maximum}) must be in sorted order"
  137. )
  138. def __getitem__(self, i):
  139. fields = dataclasses.fields(self)
  140. return getattr(self, fields[i].name)
  141. def __len__(self):
  142. return len(dataclasses.fields(self))
  143. def _replace(self, **kwargs):
  144. return dataclasses.replace(self, **kwargs)
  145. def __repr__(self):
  146. return (
  147. f"({', '.join(format(v, 'g') if v is not None else 'None' for v in self)})"
  148. )
  149. @classmethod
  150. def expand(
  151. cls,
  152. v: Union[
  153. "AxisTriple",
  154. float, # pin axis at single value, same as min==default==max
  155. Tuple[float, float], # (min, max), restrict axis and keep default
  156. Tuple[float, float, float], # (min, default, max)
  157. ],
  158. ) -> "AxisTriple":
  159. """Convert a single value or a tuple into an AxisTriple.
  160. If the input is a single value, it is interpreted as a pin at that value.
  161. If the input is a tuple, it is interpreted as (min, max) or (min, default, max).
  162. """
  163. if isinstance(v, cls):
  164. return v
  165. if isinstance(v, (int, float)):
  166. return cls(v, v, v)
  167. try:
  168. n = len(v)
  169. except TypeError as e:
  170. raise ValueError(
  171. f"expected float, 2- or 3-tuple of floats; got {type(v)}: {v!r}"
  172. ) from e
  173. default = None
  174. if n == 2:
  175. minimum, maximum = v
  176. elif n >= 3:
  177. return cls(*v)
  178. else:
  179. raise ValueError(f"expected sequence of 2 or 3; got {n}: {v!r}")
  180. return cls(minimum, default, maximum)
  181. def limitRangeAndPopulateDefaults(self, fvarTriple) -> "AxisTriple":
  182. """Return a new AxisTriple with the default value filled in.
  183. Set default to fvar axis default if the latter is within the min/max range,
  184. otherwise set default to the min or max value, whichever is closer to the
  185. fvar axis default.
  186. If the default value is already set, return self.
  187. """
  188. minimum = self.minimum
  189. if minimum is None:
  190. minimum = fvarTriple[0]
  191. default = self.default
  192. if default is None:
  193. default = fvarTriple[1]
  194. maximum = self.maximum
  195. if maximum is None:
  196. maximum = fvarTriple[2]
  197. minimum = max(minimum, fvarTriple[0])
  198. maximum = max(maximum, fvarTriple[0])
  199. minimum = min(minimum, fvarTriple[2])
  200. maximum = min(maximum, fvarTriple[2])
  201. default = max(minimum, min(maximum, default))
  202. return AxisTriple(minimum, default, maximum)
  203. @dataclasses.dataclass(frozen=True, order=True, repr=False)
  204. class NormalizedAxisTriple(AxisTriple):
  205. """A triple of (min, default, max) normalized axis values."""
  206. minimum: float
  207. default: float
  208. maximum: float
  209. def __post_init__(self):
  210. if self.default is None:
  211. object.__setattr__(self, "default", max(self.minimum, min(self.maximum, 0)))
  212. if not (-1.0 <= self.minimum <= self.default <= self.maximum <= 1.0):
  213. raise ValueError(
  214. "Normalized axis values not in -1..+1 range; got "
  215. f"minimum={self.minimum:g}, default={self.default:g}, maximum={self.maximum:g})"
  216. )
  217. @dataclasses.dataclass(frozen=True, order=True, repr=False)
  218. class NormalizedAxisTripleAndDistances(AxisTriple):
  219. """A triple of (min, default, max) normalized axis values,
  220. with distances between min and default, and default and max,
  221. in the *pre-normalized* space."""
  222. minimum: float
  223. default: float
  224. maximum: float
  225. distanceNegative: Optional[float] = 1
  226. distancePositive: Optional[float] = 1
  227. def __post_init__(self):
  228. if self.default is None:
  229. object.__setattr__(self, "default", max(self.minimum, min(self.maximum, 0)))
  230. if not (-1.0 <= self.minimum <= self.default <= self.maximum <= 1.0):
  231. raise ValueError(
  232. "Normalized axis values not in -1..+1 range; got "
  233. f"minimum={self.minimum:g}, default={self.default:g}, maximum={self.maximum:g})"
  234. )
  235. def reverse_negate(self):
  236. v = self
  237. return self.__class__(-v[2], -v[1], -v[0], v[4], v[3])
  238. def renormalizeValue(self, v, extrapolate=True):
  239. """Renormalizes a normalized value v to the range of this axis,
  240. considering the pre-normalized distances as well as the new
  241. axis limits."""
  242. lower, default, upper, distanceNegative, distancePositive = self
  243. assert lower <= default <= upper
  244. if not extrapolate:
  245. v = max(lower, min(upper, v))
  246. if v == default:
  247. return 0
  248. if default < 0:
  249. return -self.reverse_negate().renormalizeValue(-v, extrapolate=extrapolate)
  250. # default >= 0 and v != default
  251. if v > default:
  252. return (v - default) / (upper - default)
  253. # v < default
  254. if lower >= 0:
  255. return (v - default) / (default - lower)
  256. # lower < 0 and v < default
  257. totalDistance = distanceNegative * -lower + distancePositive * default
  258. if v >= 0:
  259. vDistance = (default - v) * distancePositive
  260. else:
  261. vDistance = -v * distanceNegative + distancePositive * default
  262. return -vDistance / totalDistance
  263. class _BaseAxisLimits(Mapping[str, AxisTriple]):
  264. def __getitem__(self, key: str) -> AxisTriple:
  265. return self._data[key]
  266. def __iter__(self) -> Iterable[str]:
  267. return iter(self._data)
  268. def __len__(self) -> int:
  269. return len(self._data)
  270. def __repr__(self) -> str:
  271. return f"{type(self).__name__}({self._data!r})"
  272. def __str__(self) -> str:
  273. return str(self._data)
  274. def defaultLocation(self) -> Dict[str, float]:
  275. """Return a dict of default axis values."""
  276. return {k: v.default for k, v in self.items()}
  277. def pinnedLocation(self) -> Dict[str, float]:
  278. """Return a location dict with only the pinned axes."""
  279. return {k: v.default for k, v in self.items() if v.minimum == v.maximum}
  280. class AxisLimits(_BaseAxisLimits):
  281. """Maps axis tags (str) to AxisTriple values."""
  282. def __init__(self, *args, **kwargs):
  283. self._data = data = {}
  284. for k, v in dict(*args, **kwargs).items():
  285. if v is None:
  286. # will be filled in by limitAxesAndPopulateDefaults
  287. data[k] = v
  288. else:
  289. try:
  290. triple = AxisTriple.expand(v)
  291. except ValueError as e:
  292. raise ValueError(f"Invalid axis limits for {k!r}: {v!r}") from e
  293. data[k] = triple
  294. def limitAxesAndPopulateDefaults(self, varfont) -> "AxisLimits":
  295. """Return a new AxisLimits with defaults filled in from fvar table.
  296. If all axis limits already have defaults, return self.
  297. """
  298. fvar = varfont["fvar"]
  299. fvarTriples = {
  300. a.axisTag: (a.minValue, a.defaultValue, a.maxValue) for a in fvar.axes
  301. }
  302. newLimits = {}
  303. for axisTag, triple in self.items():
  304. fvarTriple = fvarTriples[axisTag]
  305. default = fvarTriple[1]
  306. if triple is None:
  307. newLimits[axisTag] = AxisTriple(default, default, default)
  308. else:
  309. newLimits[axisTag] = triple.limitRangeAndPopulateDefaults(fvarTriple)
  310. return type(self)(newLimits)
  311. def normalize(self, varfont, usingAvar=True) -> "NormalizedAxisLimits":
  312. """Return a new NormalizedAxisLimits with normalized -1..0..+1 values.
  313. If usingAvar is True, the avar table is used to warp the default normalization.
  314. """
  315. fvar = varfont["fvar"]
  316. badLimits = set(self.keys()).difference(a.axisTag for a in fvar.axes)
  317. if badLimits:
  318. raise ValueError("Cannot limit: {} not present in fvar".format(badLimits))
  319. axes = {
  320. a.axisTag: (a.minValue, a.defaultValue, a.maxValue)
  321. for a in fvar.axes
  322. if a.axisTag in self
  323. }
  324. avarSegments = {}
  325. if usingAvar and "avar" in varfont:
  326. avarSegments = varfont["avar"].segments
  327. normalizedLimits = {}
  328. for axis_tag, triple in axes.items():
  329. distanceNegative = triple[1] - triple[0]
  330. distancePositive = triple[2] - triple[1]
  331. if self[axis_tag] is None:
  332. normalizedLimits[axis_tag] = NormalizedAxisTripleAndDistances(
  333. 0, 0, 0, distanceNegative, distancePositive
  334. )
  335. continue
  336. minV, defaultV, maxV = self[axis_tag]
  337. if defaultV is None:
  338. defaultV = triple[1]
  339. avarMapping = avarSegments.get(axis_tag, None)
  340. normalizedLimits[axis_tag] = NormalizedAxisTripleAndDistances(
  341. *(normalize(v, triple, avarMapping) for v in (minV, defaultV, maxV)),
  342. distanceNegative,
  343. distancePositive,
  344. )
  345. return NormalizedAxisLimits(normalizedLimits)
  346. class NormalizedAxisLimits(_BaseAxisLimits):
  347. """Maps axis tags (str) to NormalizedAxisTriple values."""
  348. def __init__(self, *args, **kwargs):
  349. self._data = data = {}
  350. for k, v in dict(*args, **kwargs).items():
  351. try:
  352. triple = NormalizedAxisTripleAndDistances.expand(v)
  353. except ValueError as e:
  354. raise ValueError(f"Invalid axis limits for {k!r}: {v!r}") from e
  355. data[k] = triple
  356. class OverlapMode(IntEnum):
  357. KEEP_AND_DONT_SET_FLAGS = 0
  358. KEEP_AND_SET_FLAGS = 1
  359. REMOVE = 2
  360. REMOVE_AND_IGNORE_ERRORS = 3
  361. def instantiateTupleVariationStore(
  362. variations, axisLimits, origCoords=None, endPts=None
  363. ):
  364. """Instantiate TupleVariation list at the given location, or limit axes' min/max.
  365. The 'variations' list of TupleVariation objects is modified in-place.
  366. The 'axisLimits' (dict) maps axis tags (str) to NormalizedAxisTriple namedtuples
  367. specifying (minimum, default, maximum) in the -1,0,+1 normalized space. Pinned axes
  368. have minimum == default == maximum.
  369. A 'full' instance (i.e. static font) is produced when all the axes are pinned to
  370. single coordinates; a 'partial' instance (i.e. a less variable font) is produced
  371. when some of the axes are omitted, or restricted with a new range.
  372. Tuples that do not participate are kept as they are. Those that have 0 influence
  373. at the given location are removed from the variation store.
  374. Those that are fully instantiated (i.e. all their axes are being pinned) are also
  375. removed from the variation store, their scaled deltas accummulated and returned, so
  376. that they can be added by the caller to the default instance's coordinates.
  377. Tuples that are only partially instantiated (i.e. not all the axes that they
  378. participate in are being pinned) are kept in the store, and their deltas multiplied
  379. by the scalar support of the axes to be pinned at the desired location.
  380. Args:
  381. variations: List[TupleVariation] from either 'gvar' or 'cvar'.
  382. axisLimits: NormalizedAxisLimits: map from axis tags to (min, default, max)
  383. normalized coordinates for the full or partial instance.
  384. origCoords: GlyphCoordinates: default instance's coordinates for computing 'gvar'
  385. inferred points (cf. table__g_l_y_f._getCoordinatesAndControls).
  386. endPts: List[int]: indices of contour end points, for inferring 'gvar' deltas.
  387. Returns:
  388. List[float]: the overall delta adjustment after applicable deltas were summed.
  389. """
  390. newVariations = changeTupleVariationsAxisLimits(variations, axisLimits)
  391. mergedVariations = collections.OrderedDict()
  392. for var in newVariations:
  393. # compute inferred deltas only for gvar ('origCoords' is None for cvar)
  394. if origCoords is not None:
  395. var.calcInferredDeltas(origCoords, endPts)
  396. # merge TupleVariations with overlapping "tents"
  397. axes = frozenset(var.axes.items())
  398. if axes in mergedVariations:
  399. mergedVariations[axes] += var
  400. else:
  401. mergedVariations[axes] = var
  402. # drop TupleVariation if all axes have been pinned (var.axes.items() is empty);
  403. # its deltas will be added to the default instance's coordinates
  404. defaultVar = mergedVariations.pop(frozenset(), None)
  405. for var in mergedVariations.values():
  406. var.roundDeltas()
  407. variations[:] = list(mergedVariations.values())
  408. return defaultVar.coordinates if defaultVar is not None else []
  409. def changeTupleVariationsAxisLimits(variations, axisLimits):
  410. for axisTag, axisLimit in sorted(axisLimits.items()):
  411. newVariations = []
  412. for var in variations:
  413. newVariations.extend(changeTupleVariationAxisLimit(var, axisTag, axisLimit))
  414. variations = newVariations
  415. return variations
  416. def changeTupleVariationAxisLimit(var, axisTag, axisLimit):
  417. assert isinstance(axisLimit, NormalizedAxisTripleAndDistances)
  418. # Skip when current axis is missing or peaks at 0 (i.e. doesn't participate)
  419. lower, peak, upper = var.axes.get(axisTag, (-1, 0, 1))
  420. if peak == 0:
  421. # explicitly defined, no-op axes can be omitted
  422. # https://github.com/fonttools/fonttools/issues/3453
  423. if axisTag in var.axes:
  424. del var.axes[axisTag]
  425. return [var]
  426. # Drop if the var 'tent' isn't well-formed
  427. if not (lower <= peak <= upper) or (lower < 0 and upper > 0):
  428. return []
  429. if axisTag not in var.axes:
  430. return [var]
  431. tent = var.axes[axisTag]
  432. solutions = solver.rebaseTent(tent, axisLimit)
  433. out = []
  434. for scalar, tent in solutions:
  435. newVar = (
  436. TupleVariation(var.axes, var.coordinates) if len(solutions) > 1 else var
  437. )
  438. if tent is None:
  439. newVar.axes.pop(axisTag)
  440. else:
  441. assert tent[1] != 0, tent
  442. newVar.axes[axisTag] = tent
  443. newVar *= scalar
  444. out.append(newVar)
  445. return out
  446. def _instantiateGvarGlyph(
  447. glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=True
  448. ):
  449. coordinates, ctrl = glyf._getCoordinatesAndControls(glyphname, hMetrics, vMetrics)
  450. endPts = ctrl.endPts
  451. # Not every glyph may have variations
  452. tupleVarStore = gvar.variations.get(glyphname)
  453. if tupleVarStore:
  454. defaultDeltas = instantiateTupleVariationStore(
  455. tupleVarStore, axisLimits, coordinates, endPts
  456. )
  457. if defaultDeltas:
  458. coordinates += _g_l_y_f.GlyphCoordinates(defaultDeltas)
  459. glyph = glyf[glyphname]
  460. if glyph.isVarComposite():
  461. for component in glyph.components:
  462. newLocation = {}
  463. for tag, loc in component.location.items():
  464. if tag not in axisLimits:
  465. newLocation[tag] = loc
  466. continue
  467. if component.flags & _g_l_y_f.VarComponentFlags.AXES_HAVE_VARIATION:
  468. raise NotImplementedError(
  469. "Instancing accross VarComposite axes with variation is not supported."
  470. )
  471. limits = axisLimits[tag]
  472. loc = limits.renormalizeValue(loc, extrapolate=False)
  473. newLocation[tag] = loc
  474. component.location = newLocation
  475. # _setCoordinates also sets the hmtx/vmtx advance widths and sidebearings from
  476. # the four phantom points and glyph bounding boxes.
  477. # We call it unconditionally even if a glyph has no variations or no deltas are
  478. # applied at this location, in case the glyph's xMin and in turn its sidebearing
  479. # have changed. E.g. a composite glyph has no deltas for the component's (x, y)
  480. # offset nor for the 4 phantom points (e.g. it's monospaced). Thus its entry in
  481. # gvar table is empty; however, the composite's base glyph may have deltas
  482. # applied, hence the composite's bbox and left/top sidebearings may need updating
  483. # in the instanced font.
  484. glyf._setCoordinates(glyphname, coordinates, hMetrics, vMetrics)
  485. if not tupleVarStore:
  486. if glyphname in gvar.variations:
  487. del gvar.variations[glyphname]
  488. return
  489. if optimize:
  490. isComposite = glyf[glyphname].isComposite()
  491. for var in tupleVarStore:
  492. var.optimize(coordinates, endPts, isComposite=isComposite)
  493. def instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True):
  494. """Remove?
  495. https://github.com/fonttools/fonttools/pull/2266"""
  496. gvar = varfont["gvar"]
  497. glyf = varfont["glyf"]
  498. hMetrics = varfont["hmtx"].metrics
  499. vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
  500. _instantiateGvarGlyph(
  501. glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
  502. )
  503. def instantiateGvar(varfont, axisLimits, optimize=True):
  504. log.info("Instantiating glyf/gvar tables")
  505. gvar = varfont["gvar"]
  506. glyf = varfont["glyf"]
  507. hMetrics = varfont["hmtx"].metrics
  508. vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
  509. # Get list of glyph names sorted by component depth.
  510. # If a composite glyph is processed before its base glyph, the bounds may
  511. # be calculated incorrectly because deltas haven't been applied to the
  512. # base glyph yet.
  513. glyphnames = sorted(
  514. glyf.glyphOrder,
  515. key=lambda name: (
  516. (
  517. glyf[name].getCompositeMaxpValues(glyf).maxComponentDepth
  518. if glyf[name].isComposite() or glyf[name].isVarComposite()
  519. else 0
  520. ),
  521. name,
  522. ),
  523. )
  524. for glyphname in glyphnames:
  525. _instantiateGvarGlyph(
  526. glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
  527. )
  528. if not gvar.variations:
  529. del varfont["gvar"]
  530. def setCvarDeltas(cvt, deltas):
  531. for i, delta in enumerate(deltas):
  532. if delta:
  533. cvt[i] += otRound(delta)
  534. def instantiateCvar(varfont, axisLimits):
  535. log.info("Instantiating cvt/cvar tables")
  536. cvar = varfont["cvar"]
  537. defaultDeltas = instantiateTupleVariationStore(cvar.variations, axisLimits)
  538. if defaultDeltas:
  539. setCvarDeltas(varfont["cvt "], defaultDeltas)
  540. if not cvar.variations:
  541. del varfont["cvar"]
  542. def setMvarDeltas(varfont, deltas):
  543. mvar = varfont["MVAR"].table
  544. records = mvar.ValueRecord
  545. for rec in records:
  546. mvarTag = rec.ValueTag
  547. if mvarTag not in MVAR_ENTRIES:
  548. continue
  549. tableTag, itemName = MVAR_ENTRIES[mvarTag]
  550. delta = deltas[rec.VarIdx]
  551. if delta != 0:
  552. setattr(
  553. varfont[tableTag],
  554. itemName,
  555. getattr(varfont[tableTag], itemName) + otRound(delta),
  556. )
  557. @contextmanager
  558. def verticalMetricsKeptInSync(varfont):
  559. """Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing.
  560. When applying MVAR deltas to the OS/2 table, if the ascender, descender and
  561. line gap change but they were the same as the respective hhea metrics in the
  562. original font, this context manager ensures that hhea metrcs also get updated
  563. accordingly.
  564. The MVAR spec only has tags for the OS/2 metrics, but it is common in fonts
  565. to have the hhea metrics be equal to those for compat reasons.
  566. https://learn.microsoft.com/en-us/typography/opentype/spec/mvar
  567. https://googlefonts.github.io/gf-guide/metrics.html#7-hhea-and-typo-metrics-should-be-equal
  568. https://github.com/fonttools/fonttools/issues/3297
  569. """
  570. current_os2_vmetrics = [
  571. getattr(varfont["OS/2"], attr)
  572. for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap")
  573. ]
  574. metrics_are_synced = current_os2_vmetrics == [
  575. getattr(varfont["hhea"], attr) for attr in ("ascender", "descender", "lineGap")
  576. ]
  577. yield metrics_are_synced
  578. if metrics_are_synced:
  579. new_os2_vmetrics = [
  580. getattr(varfont["OS/2"], attr)
  581. for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap")
  582. ]
  583. if current_os2_vmetrics != new_os2_vmetrics:
  584. for attr, value in zip(
  585. ("ascender", "descender", "lineGap"), new_os2_vmetrics
  586. ):
  587. setattr(varfont["hhea"], attr, value)
  588. def instantiateMVAR(varfont, axisLimits):
  589. log.info("Instantiating MVAR table")
  590. mvar = varfont["MVAR"].table
  591. fvarAxes = varfont["fvar"].axes
  592. varStore = mvar.VarStore
  593. defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
  594. with verticalMetricsKeptInSync(varfont):
  595. setMvarDeltas(varfont, defaultDeltas)
  596. if varStore.VarRegionList.Region:
  597. varIndexMapping = varStore.optimize()
  598. for rec in mvar.ValueRecord:
  599. rec.VarIdx = varIndexMapping[rec.VarIdx]
  600. else:
  601. del varfont["MVAR"]
  602. def _remapVarIdxMap(table, attrName, varIndexMapping, glyphOrder):
  603. oldMapping = getattr(table, attrName).mapping
  604. newMapping = [varIndexMapping[oldMapping[glyphName]] for glyphName in glyphOrder]
  605. setattr(table, attrName, builder.buildVarIdxMap(newMapping, glyphOrder))
  606. # TODO(anthrotype) Add support for HVAR/VVAR in CFF2
  607. def _instantiateVHVAR(varfont, axisLimits, tableFields):
  608. location = axisLimits.pinnedLocation()
  609. tableTag = tableFields.tableTag
  610. fvarAxes = varfont["fvar"].axes
  611. # Deltas from gvar table have already been applied to the hmtx/vmtx. For full
  612. # instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return
  613. if set(location).issuperset(axis.axisTag for axis in fvarAxes):
  614. log.info("Dropping %s table", tableTag)
  615. del varfont[tableTag]
  616. return
  617. log.info("Instantiating %s table", tableTag)
  618. vhvar = varfont[tableTag].table
  619. varStore = vhvar.VarStore
  620. # since deltas were already applied, the return value here is ignored
  621. instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
  622. if varStore.VarRegionList.Region:
  623. # Only re-optimize VarStore if the HVAR/VVAR already uses indirect AdvWidthMap
  624. # or AdvHeightMap. If a direct, implicit glyphID->VariationIndex mapping is
  625. # used for advances, skip re-optimizing and maintain original VariationIndex.
  626. if getattr(vhvar, tableFields.advMapping):
  627. varIndexMapping = varStore.optimize(use_NO_VARIATION_INDEX=False)
  628. glyphOrder = varfont.getGlyphOrder()
  629. _remapVarIdxMap(vhvar, tableFields.advMapping, varIndexMapping, glyphOrder)
  630. if getattr(vhvar, tableFields.sb1): # left or top sidebearings
  631. _remapVarIdxMap(vhvar, tableFields.sb1, varIndexMapping, glyphOrder)
  632. if getattr(vhvar, tableFields.sb2): # right or bottom sidebearings
  633. _remapVarIdxMap(vhvar, tableFields.sb2, varIndexMapping, glyphOrder)
  634. if tableTag == "VVAR" and getattr(vhvar, tableFields.vOrigMapping):
  635. _remapVarIdxMap(
  636. vhvar, tableFields.vOrigMapping, varIndexMapping, glyphOrder
  637. )
  638. def instantiateHVAR(varfont, axisLimits):
  639. return _instantiateVHVAR(varfont, axisLimits, varLib.HVAR_FIELDS)
  640. def instantiateVVAR(varfont, axisLimits):
  641. return _instantiateVHVAR(varfont, axisLimits, varLib.VVAR_FIELDS)
  642. class _TupleVarStoreAdapter(object):
  643. def __init__(self, regions, axisOrder, tupleVarData, itemCounts):
  644. self.regions = regions
  645. self.axisOrder = axisOrder
  646. self.tupleVarData = tupleVarData
  647. self.itemCounts = itemCounts
  648. @classmethod
  649. def fromItemVarStore(cls, itemVarStore, fvarAxes):
  650. axisOrder = [axis.axisTag for axis in fvarAxes]
  651. regions = [
  652. region.get_support(fvarAxes) for region in itemVarStore.VarRegionList.Region
  653. ]
  654. tupleVarData = []
  655. itemCounts = []
  656. for varData in itemVarStore.VarData:
  657. variations = []
  658. varDataRegions = (regions[i] for i in varData.VarRegionIndex)
  659. for axes, coordinates in zip(varDataRegions, zip(*varData.Item)):
  660. variations.append(TupleVariation(axes, list(coordinates)))
  661. tupleVarData.append(variations)
  662. itemCounts.append(varData.ItemCount)
  663. return cls(regions, axisOrder, tupleVarData, itemCounts)
  664. def rebuildRegions(self):
  665. # Collect the set of all unique region axes from the current TupleVariations.
  666. # We use an OrderedDict to de-duplicate regions while keeping the order.
  667. uniqueRegions = collections.OrderedDict.fromkeys(
  668. (
  669. frozenset(var.axes.items())
  670. for variations in self.tupleVarData
  671. for var in variations
  672. )
  673. )
  674. # Maintain the original order for the regions that pre-existed, appending
  675. # the new regions at the end of the region list.
  676. newRegions = []
  677. for region in self.regions:
  678. regionAxes = frozenset(region.items())
  679. if regionAxes in uniqueRegions:
  680. newRegions.append(region)
  681. del uniqueRegions[regionAxes]
  682. if uniqueRegions:
  683. newRegions.extend(dict(region) for region in uniqueRegions)
  684. self.regions = newRegions
  685. def instantiate(self, axisLimits):
  686. defaultDeltaArray = []
  687. for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
  688. defaultDeltas = instantiateTupleVariationStore(variations, axisLimits)
  689. if not defaultDeltas:
  690. defaultDeltas = [0] * itemCount
  691. defaultDeltaArray.append(defaultDeltas)
  692. # rebuild regions whose axes were dropped or limited
  693. self.rebuildRegions()
  694. pinnedAxes = set(axisLimits.pinnedLocation())
  695. self.axisOrder = [
  696. axisTag for axisTag in self.axisOrder if axisTag not in pinnedAxes
  697. ]
  698. return defaultDeltaArray
  699. def asItemVarStore(self):
  700. regionOrder = [frozenset(axes.items()) for axes in self.regions]
  701. varDatas = []
  702. for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
  703. if variations:
  704. assert len(variations[0].coordinates) == itemCount
  705. varRegionIndices = [
  706. regionOrder.index(frozenset(var.axes.items())) for var in variations
  707. ]
  708. varDataItems = list(zip(*(var.coordinates for var in variations)))
  709. varDatas.append(
  710. builder.buildVarData(varRegionIndices, varDataItems, optimize=False)
  711. )
  712. else:
  713. varDatas.append(
  714. builder.buildVarData([], [[] for _ in range(itemCount)])
  715. )
  716. regionList = builder.buildVarRegionList(self.regions, self.axisOrder)
  717. itemVarStore = builder.buildVarStore(regionList, varDatas)
  718. # remove unused regions from VarRegionList
  719. itemVarStore.prune_regions()
  720. return itemVarStore
  721. def instantiateItemVariationStore(itemVarStore, fvarAxes, axisLimits):
  722. """Compute deltas at partial location, and update varStore in-place.
  723. Remove regions in which all axes were instanced, or fall outside the new axis
  724. limits. Scale the deltas of the remaining regions where only some of the axes
  725. were instanced.
  726. The number of VarData subtables, and the number of items within each, are
  727. not modified, in order to keep the existing VariationIndex valid.
  728. One may call VarStore.optimize() method after this to further optimize those.
  729. Args:
  730. varStore: An otTables.VarStore object (Item Variation Store)
  731. fvarAxes: list of fvar's Axis objects
  732. axisLimits: NormalizedAxisLimits: mapping axis tags to normalized
  733. min/default/max axis coordinates. May not specify coordinates/ranges for
  734. all the fvar axes.
  735. Returns:
  736. defaultDeltas: to be added to the default instance, of type dict of floats
  737. keyed by VariationIndex compound values: i.e. (outer << 16) + inner.
  738. """
  739. tupleVarStore = _TupleVarStoreAdapter.fromItemVarStore(itemVarStore, fvarAxes)
  740. defaultDeltaArray = tupleVarStore.instantiate(axisLimits)
  741. newItemVarStore = tupleVarStore.asItemVarStore()
  742. itemVarStore.VarRegionList = newItemVarStore.VarRegionList
  743. assert itemVarStore.VarDataCount == newItemVarStore.VarDataCount
  744. itemVarStore.VarData = newItemVarStore.VarData
  745. defaultDeltas = {
  746. ((major << 16) + minor): delta
  747. for major, deltas in enumerate(defaultDeltaArray)
  748. for minor, delta in enumerate(deltas)
  749. }
  750. defaultDeltas[itemVarStore.NO_VARIATION_INDEX] = 0
  751. return defaultDeltas
  752. def instantiateOTL(varfont, axisLimits):
  753. # TODO(anthrotype) Support partial instancing of JSTF and BASE tables
  754. if (
  755. "GDEF" not in varfont
  756. or varfont["GDEF"].table.Version < 0x00010003
  757. or not varfont["GDEF"].table.VarStore
  758. ):
  759. return
  760. if "GPOS" in varfont:
  761. msg = "Instantiating GDEF and GPOS tables"
  762. else:
  763. msg = "Instantiating GDEF table"
  764. log.info(msg)
  765. gdef = varfont["GDEF"].table
  766. varStore = gdef.VarStore
  767. fvarAxes = varfont["fvar"].axes
  768. defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
  769. # When VF are built, big lookups may overflow and be broken into multiple
  770. # subtables. MutatorMerger (which inherits from AligningMerger) reattaches
  771. # them upon instancing, in case they can now fit a single subtable (if not,
  772. # they will be split again upon compilation).
  773. # This 'merger' also works as a 'visitor' that traverses the OTL tables and
  774. # calls specific methods when instances of a given type are found.
  775. # Specifically, it adds default deltas to GPOS Anchors/ValueRecords and GDEF
  776. # LigatureCarets, and optionally deletes all VariationIndex tables if the
  777. # VarStore is fully instanced.
  778. merger = MutatorMerger(
  779. varfont, defaultDeltas, deleteVariations=(not varStore.VarRegionList.Region)
  780. )
  781. merger.mergeTables(varfont, [varfont], ["GDEF", "GPOS"])
  782. if varStore.VarRegionList.Region:
  783. varIndexMapping = varStore.optimize()
  784. gdef.remap_device_varidxes(varIndexMapping)
  785. if "GPOS" in varfont:
  786. varfont["GPOS"].table.remap_device_varidxes(varIndexMapping)
  787. else:
  788. # Downgrade GDEF.
  789. del gdef.VarStore
  790. gdef.Version = 0x00010002
  791. if gdef.MarkGlyphSetsDef is None:
  792. del gdef.MarkGlyphSetsDef
  793. gdef.Version = 0x00010000
  794. if not (
  795. gdef.LigCaretList
  796. or gdef.MarkAttachClassDef
  797. or gdef.GlyphClassDef
  798. or gdef.AttachList
  799. or (gdef.Version >= 0x00010002 and gdef.MarkGlyphSetsDef)
  800. ):
  801. del varfont["GDEF"]
  802. def _isValidAvarSegmentMap(axisTag, segmentMap):
  803. if not segmentMap:
  804. return True
  805. if not {(-1.0, -1.0), (0, 0), (1.0, 1.0)}.issubset(segmentMap.items()):
  806. log.warning(
  807. f"Invalid avar SegmentMap record for axis '{axisTag}': does not "
  808. "include all required value maps {-1.0: -1.0, 0: 0, 1.0: 1.0}"
  809. )
  810. return False
  811. previousValue = None
  812. for fromCoord, toCoord in sorted(segmentMap.items()):
  813. if previousValue is not None and previousValue > toCoord:
  814. log.warning(
  815. f"Invalid avar AxisValueMap({fromCoord}, {toCoord}) record "
  816. f"for axis '{axisTag}': the toCoordinate value must be >= to "
  817. f"the toCoordinate value of the preceding record ({previousValue})."
  818. )
  819. return False
  820. previousValue = toCoord
  821. return True
  822. def instantiateAvar(varfont, axisLimits):
  823. # 'axisLimits' dict must contain user-space (non-normalized) coordinates.
  824. segments = varfont["avar"].segments
  825. # drop table if we instantiate all the axes
  826. pinnedAxes = set(axisLimits.pinnedLocation())
  827. if pinnedAxes.issuperset(segments):
  828. log.info("Dropping avar table")
  829. del varfont["avar"]
  830. return
  831. log.info("Instantiating avar table")
  832. for axis in pinnedAxes:
  833. if axis in segments:
  834. del segments[axis]
  835. # First compute the default normalization for axisLimits coordinates: i.e.
  836. # min = -1.0, default = 0, max = +1.0, and in between values interpolated linearly,
  837. # without using the avar table's mappings.
  838. # Then, for each SegmentMap, if we are restricting its axis, compute the new
  839. # mappings by dividing the key/value pairs by the desired new min/max values,
  840. # dropping any mappings that fall outside the restricted range.
  841. # The keys ('fromCoord') are specified in default normalized coordinate space,
  842. # whereas the values ('toCoord') are "mapped forward" using the SegmentMap.
  843. normalizedRanges = axisLimits.normalize(varfont, usingAvar=False)
  844. newSegments = {}
  845. for axisTag, mapping in segments.items():
  846. if not _isValidAvarSegmentMap(axisTag, mapping):
  847. continue
  848. if mapping and axisTag in normalizedRanges:
  849. axisRange = normalizedRanges[axisTag]
  850. mappedMin = floatToFixedToFloat(
  851. piecewiseLinearMap(axisRange.minimum, mapping), 14
  852. )
  853. mappedDef = floatToFixedToFloat(
  854. piecewiseLinearMap(axisRange.default, mapping), 14
  855. )
  856. mappedMax = floatToFixedToFloat(
  857. piecewiseLinearMap(axisRange.maximum, mapping), 14
  858. )
  859. mappedAxisLimit = NormalizedAxisTripleAndDistances(
  860. mappedMin,
  861. mappedDef,
  862. mappedMax,
  863. axisRange.distanceNegative,
  864. axisRange.distancePositive,
  865. )
  866. newMapping = {}
  867. for fromCoord, toCoord in mapping.items():
  868. if fromCoord < axisRange.minimum or fromCoord > axisRange.maximum:
  869. continue
  870. fromCoord = axisRange.renormalizeValue(fromCoord)
  871. assert mappedMin <= toCoord <= mappedMax
  872. toCoord = mappedAxisLimit.renormalizeValue(toCoord)
  873. fromCoord = floatToFixedToFloat(fromCoord, 14)
  874. toCoord = floatToFixedToFloat(toCoord, 14)
  875. newMapping[fromCoord] = toCoord
  876. newMapping.update({-1.0: -1.0, 0.0: 0.0, 1.0: 1.0})
  877. newSegments[axisTag] = newMapping
  878. else:
  879. newSegments[axisTag] = mapping
  880. varfont["avar"].segments = newSegments
  881. def isInstanceWithinAxisRanges(location, axisRanges):
  882. for axisTag, coord in location.items():
  883. if axisTag in axisRanges:
  884. axisRange = axisRanges[axisTag]
  885. if coord < axisRange.minimum or coord > axisRange.maximum:
  886. return False
  887. return True
  888. def instantiateFvar(varfont, axisLimits):
  889. # 'axisLimits' dict must contain user-space (non-normalized) coordinates
  890. location = axisLimits.pinnedLocation()
  891. fvar = varfont["fvar"]
  892. # drop table if we instantiate all the axes
  893. if set(location).issuperset(axis.axisTag for axis in fvar.axes):
  894. log.info("Dropping fvar table")
  895. del varfont["fvar"]
  896. return
  897. log.info("Instantiating fvar table")
  898. axes = []
  899. for axis in fvar.axes:
  900. axisTag = axis.axisTag
  901. if axisTag in location:
  902. continue
  903. if axisTag in axisLimits:
  904. triple = axisLimits[axisTag]
  905. if triple.default is None:
  906. triple = (triple.minimum, axis.defaultValue, triple.maximum)
  907. axis.minValue, axis.defaultValue, axis.maxValue = triple
  908. axes.append(axis)
  909. fvar.axes = axes
  910. # only keep NamedInstances whose coordinates == pinned axis location
  911. instances = []
  912. for instance in fvar.instances:
  913. if any(instance.coordinates[axis] != value for axis, value in location.items()):
  914. continue
  915. for axisTag in location:
  916. del instance.coordinates[axisTag]
  917. if not isInstanceWithinAxisRanges(instance.coordinates, axisLimits):
  918. continue
  919. instances.append(instance)
  920. fvar.instances = instances
  921. def instantiateSTAT(varfont, axisLimits):
  922. # 'axisLimits' dict must contain user-space (non-normalized) coordinates
  923. stat = varfont["STAT"].table
  924. if not stat.DesignAxisRecord or not (
  925. stat.AxisValueArray and stat.AxisValueArray.AxisValue
  926. ):
  927. return # STAT table empty, nothing to do
  928. log.info("Instantiating STAT table")
  929. newAxisValueTables = axisValuesFromAxisLimits(stat, axisLimits)
  930. stat.AxisValueCount = len(newAxisValueTables)
  931. if stat.AxisValueCount:
  932. stat.AxisValueArray.AxisValue = newAxisValueTables
  933. else:
  934. stat.AxisValueArray = None
  935. def axisValuesFromAxisLimits(stat, axisLimits):
  936. def isAxisValueOutsideLimits(axisTag, axisValue):
  937. if axisTag in axisLimits:
  938. triple = axisLimits[axisTag]
  939. if axisValue < triple.minimum or axisValue > triple.maximum:
  940. return True
  941. return False
  942. # only keep AxisValues whose axis is not pinned nor restricted, or is pinned at the
  943. # exact (nominal) value, or is restricted but the value is within the new range
  944. designAxes = stat.DesignAxisRecord.Axis
  945. newAxisValueTables = []
  946. for axisValueTable in stat.AxisValueArray.AxisValue:
  947. axisValueFormat = axisValueTable.Format
  948. if axisValueFormat in (1, 2, 3):
  949. axisTag = designAxes[axisValueTable.AxisIndex].AxisTag
  950. if axisValueFormat == 2:
  951. axisValue = axisValueTable.NominalValue
  952. else:
  953. axisValue = axisValueTable.Value
  954. if isAxisValueOutsideLimits(axisTag, axisValue):
  955. continue
  956. elif axisValueFormat == 4:
  957. # drop 'non-analytic' AxisValue if _any_ AxisValueRecord doesn't match
  958. # the pinned location or is outside range
  959. dropAxisValueTable = False
  960. for rec in axisValueTable.AxisValueRecord:
  961. axisTag = designAxes[rec.AxisIndex].AxisTag
  962. axisValue = rec.Value
  963. if isAxisValueOutsideLimits(axisTag, axisValue):
  964. dropAxisValueTable = True
  965. break
  966. if dropAxisValueTable:
  967. continue
  968. else:
  969. log.warning("Unknown AxisValue table format (%s); ignored", axisValueFormat)
  970. newAxisValueTables.append(axisValueTable)
  971. return newAxisValueTables
  972. def setMacOverlapFlags(glyfTable):
  973. flagOverlapCompound = _g_l_y_f.OVERLAP_COMPOUND
  974. flagOverlapSimple = _g_l_y_f.flagOverlapSimple
  975. for glyphName in glyfTable.keys():
  976. glyph = glyfTable[glyphName]
  977. # Set OVERLAP_COMPOUND bit for compound glyphs
  978. if glyph.isComposite():
  979. glyph.components[0].flags |= flagOverlapCompound
  980. # Set OVERLAP_SIMPLE bit for simple glyphs
  981. elif glyph.numberOfContours > 0:
  982. glyph.flags[0] |= flagOverlapSimple
  983. def normalize(value, triple, avarMapping):
  984. value = normalizeValue(value, triple)
  985. if avarMapping:
  986. value = piecewiseLinearMap(value, avarMapping)
  987. # Quantize to F2Dot14, to avoid surprise interpolations.
  988. return floatToFixedToFloat(value, 14)
  989. def sanityCheckVariableTables(varfont):
  990. if "fvar" not in varfont:
  991. raise ValueError("Missing required table fvar")
  992. if "gvar" in varfont:
  993. if "glyf" not in varfont:
  994. raise ValueError("Can't have gvar without glyf")
  995. # TODO(anthrotype) Remove once we do support partial instancing CFF2
  996. if "CFF2" in varfont:
  997. raise NotImplementedError("Instancing CFF2 variable fonts is not supported yet")
  998. def instantiateVariableFont(
  999. varfont,
  1000. axisLimits,
  1001. inplace=False,
  1002. optimize=True,
  1003. overlap=OverlapMode.KEEP_AND_SET_FLAGS,
  1004. updateFontNames=False,
  1005. ):
  1006. """Instantiate variable font, either fully or partially.
  1007. Depending on whether the `axisLimits` dictionary references all or some of the
  1008. input varfont's axes, the output font will either be a full instance (static
  1009. font) or a variable font with possibly less variation data.
  1010. Args:
  1011. varfont: a TTFont instance, which must contain at least an 'fvar' table.
  1012. Note that variable fonts with 'CFF2' table are not supported yet.
  1013. axisLimits: a dict keyed by axis tags (str) containing the coordinates (float)
  1014. along one or more axes where the desired instance will be located.
  1015. If the value is `None`, the default coordinate as per 'fvar' table for
  1016. that axis is used.
  1017. The limit values can also be (min, max) tuples for restricting an
  1018. axis's variation range. The default axis value must be included in
  1019. the new range.
  1020. inplace (bool): whether to modify input TTFont object in-place instead of
  1021. returning a distinct object.
  1022. optimize (bool): if False, do not perform IUP-delta optimization on the
  1023. remaining 'gvar' table's deltas. Possibly faster, and might work around
  1024. rendering issues in some buggy environments, at the cost of a slightly
  1025. larger file size.
  1026. overlap (OverlapMode): variable fonts usually contain overlapping contours, and
  1027. some font rendering engines on Apple platforms require that the
  1028. `OVERLAP_SIMPLE` and `OVERLAP_COMPOUND` flags in the 'glyf' table be set to
  1029. force rendering using a non-zero fill rule. Thus we always set these flags
  1030. on all glyphs to maximise cross-compatibility of the generated instance.
  1031. You can disable this by passing OverlapMode.KEEP_AND_DONT_SET_FLAGS.
  1032. If you want to remove the overlaps altogether and merge overlapping
  1033. contours and components, you can pass OverlapMode.REMOVE (or
  1034. REMOVE_AND_IGNORE_ERRORS to not hard-fail on tricky glyphs). Note that this
  1035. requires the skia-pathops package (available to pip install).
  1036. The overlap parameter only has effect when generating full static instances.
  1037. updateFontNames (bool): if True, update the instantiated font's name table using
  1038. the Axis Value Tables from the STAT table. The name table and the style bits
  1039. in the head and OS/2 table will be updated so they conform to the R/I/B/BI
  1040. model. If the STAT table is missing or an Axis Value table is missing for
  1041. a given axis coordinate, a ValueError will be raised.
  1042. """
  1043. # 'overlap' used to be bool and is now enum; for backward compat keep accepting bool
  1044. overlap = OverlapMode(int(overlap))
  1045. sanityCheckVariableTables(varfont)
  1046. axisLimits = AxisLimits(axisLimits).limitAxesAndPopulateDefaults(varfont)
  1047. log.info("Restricted limits: %s", axisLimits)
  1048. normalizedLimits = axisLimits.normalize(varfont)
  1049. log.info("Normalized limits: %s", normalizedLimits)
  1050. if not inplace:
  1051. varfont = deepcopy(varfont)
  1052. if "DSIG" in varfont:
  1053. del varfont["DSIG"]
  1054. if updateFontNames:
  1055. log.info("Updating name table")
  1056. names.updateNameTable(varfont, axisLimits)
  1057. if "gvar" in varfont:
  1058. instantiateGvar(varfont, normalizedLimits, optimize=optimize)
  1059. if "cvar" in varfont:
  1060. instantiateCvar(varfont, normalizedLimits)
  1061. if "MVAR" in varfont:
  1062. instantiateMVAR(varfont, normalizedLimits)
  1063. if "HVAR" in varfont:
  1064. instantiateHVAR(varfont, normalizedLimits)
  1065. if "VVAR" in varfont:
  1066. instantiateVVAR(varfont, normalizedLimits)
  1067. instantiateOTL(varfont, normalizedLimits)
  1068. instantiateFeatureVariations(varfont, normalizedLimits)
  1069. if "avar" in varfont:
  1070. instantiateAvar(varfont, axisLimits)
  1071. with names.pruningUnusedNames(varfont):
  1072. if "STAT" in varfont:
  1073. instantiateSTAT(varfont, axisLimits)
  1074. instantiateFvar(varfont, axisLimits)
  1075. if "fvar" not in varfont:
  1076. if "glyf" in varfont:
  1077. if overlap == OverlapMode.KEEP_AND_SET_FLAGS:
  1078. setMacOverlapFlags(varfont["glyf"])
  1079. elif overlap in (OverlapMode.REMOVE, OverlapMode.REMOVE_AND_IGNORE_ERRORS):
  1080. from fontTools.ttLib.removeOverlaps import removeOverlaps
  1081. log.info("Removing overlaps from glyf table")
  1082. removeOverlaps(
  1083. varfont,
  1084. ignoreErrors=(overlap == OverlapMode.REMOVE_AND_IGNORE_ERRORS),
  1085. )
  1086. if "OS/2" in varfont:
  1087. varfont["OS/2"].recalcAvgCharWidth(varfont)
  1088. varLib.set_default_weight_width_slant(
  1089. varfont, location=axisLimits.defaultLocation()
  1090. )
  1091. if updateFontNames:
  1092. # Set Regular/Italic/Bold/Bold Italic bits as appropriate, after the
  1093. # name table has been updated.
  1094. setRibbiBits(varfont)
  1095. return varfont
  1096. def setRibbiBits(font):
  1097. """Set the `head.macStyle` and `OS/2.fsSelection` style bits
  1098. appropriately."""
  1099. english_ribbi_style = font["name"].getName(names.NameID.SUBFAMILY_NAME, 3, 1, 0x409)
  1100. if english_ribbi_style is None:
  1101. return
  1102. styleMapStyleName = english_ribbi_style.toStr().lower()
  1103. if styleMapStyleName not in {"regular", "bold", "italic", "bold italic"}:
  1104. return
  1105. if styleMapStyleName == "bold":
  1106. font["head"].macStyle = 0b01
  1107. elif styleMapStyleName == "bold italic":
  1108. font["head"].macStyle = 0b11
  1109. elif styleMapStyleName == "italic":
  1110. font["head"].macStyle = 0b10
  1111. selection = font["OS/2"].fsSelection
  1112. # First clear...
  1113. selection &= ~(1 << 0)
  1114. selection &= ~(1 << 5)
  1115. selection &= ~(1 << 6)
  1116. # ...then re-set the bits.
  1117. if styleMapStyleName == "regular":
  1118. selection |= 1 << 6
  1119. elif styleMapStyleName == "bold":
  1120. selection |= 1 << 5
  1121. elif styleMapStyleName == "italic":
  1122. selection |= 1 << 0
  1123. elif styleMapStyleName == "bold italic":
  1124. selection |= 1 << 0
  1125. selection |= 1 << 5
  1126. font["OS/2"].fsSelection = selection
  1127. def parseLimits(limits: Iterable[str]) -> Dict[str, Optional[AxisTriple]]:
  1128. result = {}
  1129. for limitString in limits:
  1130. match = re.match(
  1131. r"^(\w{1,4})=(?:(drop)|(?:([^:]*)(?:[:]([^:]*))?(?:[:]([^:]*))?))$",
  1132. limitString,
  1133. )
  1134. if not match:
  1135. raise ValueError("invalid location format: %r" % limitString)
  1136. tag = match.group(1).ljust(4)
  1137. if match.group(2): # 'drop'
  1138. result[tag] = None
  1139. continue
  1140. triple = match.group(3, 4, 5)
  1141. if triple[1] is None: # "value" syntax
  1142. triple = (triple[0], triple[0], triple[0])
  1143. elif triple[2] is None: # "min:max" syntax
  1144. triple = (triple[0], None, triple[1])
  1145. triple = tuple(float(v) if v else None for v in triple)
  1146. result[tag] = AxisTriple(*triple)
  1147. return result
  1148. def parseArgs(args):
  1149. """Parse argv.
  1150. Returns:
  1151. 3-tuple (infile, axisLimits, options)
  1152. axisLimits is either a Dict[str, Optional[float]], for pinning variation axes
  1153. to specific coordinates along those axes (with `None` as a placeholder for an
  1154. axis' default value); or a Dict[str, Tuple(float, float)], meaning limit this
  1155. axis to min/max range.
  1156. Axes locations are in user-space coordinates, as defined in the "fvar" table.
  1157. """
  1158. from fontTools import configLogger
  1159. import argparse
  1160. parser = argparse.ArgumentParser(
  1161. "fonttools varLib.instancer",
  1162. description="Partially instantiate a variable font",
  1163. )
  1164. parser.add_argument("input", metavar="INPUT.ttf", help="Input variable TTF file.")
  1165. parser.add_argument(
  1166. "locargs",
  1167. metavar="AXIS=LOC",
  1168. nargs="*",
  1169. help="List of space separated locations. A location consists of "
  1170. "the tag of a variation axis, followed by '=' and the literal, "
  1171. "string 'drop', or colon-separated list of one to three values, "
  1172. "each of which is the empty string, or a number. "
  1173. "E.g.: wdth=100 or wght=75.0:125.0 or wght=100:400:700 or wght=:500: "
  1174. "or wght=drop",
  1175. )
  1176. parser.add_argument(
  1177. "-o",
  1178. "--output",
  1179. metavar="OUTPUT.ttf",
  1180. default=None,
  1181. help="Output instance TTF file (default: INPUT-instance.ttf).",
  1182. )
  1183. parser.add_argument(
  1184. "--no-optimize",
  1185. dest="optimize",
  1186. action="store_false",
  1187. help="Don't perform IUP optimization on the remaining gvar TupleVariations",
  1188. )
  1189. parser.add_argument(
  1190. "--no-overlap-flag",
  1191. dest="overlap",
  1192. action="store_false",
  1193. help="Don't set OVERLAP_SIMPLE/OVERLAP_COMPOUND glyf flags (only applicable "
  1194. "when generating a full instance)",
  1195. )
  1196. parser.add_argument(
  1197. "--remove-overlaps",
  1198. dest="remove_overlaps",
  1199. action="store_true",
  1200. help="Merge overlapping contours and components (only applicable "
  1201. "when generating a full instance). Requires skia-pathops",
  1202. )
  1203. parser.add_argument(
  1204. "--ignore-overlap-errors",
  1205. dest="ignore_overlap_errors",
  1206. action="store_true",
  1207. help="Don't crash if the remove-overlaps operation fails for some glyphs.",
  1208. )
  1209. parser.add_argument(
  1210. "--update-name-table",
  1211. action="store_true",
  1212. help="Update the instantiated font's `name` table. Input font must have "
  1213. "a STAT table with Axis Value Tables",
  1214. )
  1215. parser.add_argument(
  1216. "--no-recalc-timestamp",
  1217. dest="recalc_timestamp",
  1218. action="store_false",
  1219. help="Don't set the output font's timestamp to the current time.",
  1220. )
  1221. parser.add_argument(
  1222. "--no-recalc-bounds",
  1223. dest="recalc_bounds",
  1224. action="store_false",
  1225. help="Don't recalculate font bounding boxes",
  1226. )
  1227. loggingGroup = parser.add_mutually_exclusive_group(required=False)
  1228. loggingGroup.add_argument(
  1229. "-v", "--verbose", action="store_true", help="Run more verbosely."
  1230. )
  1231. loggingGroup.add_argument(
  1232. "-q", "--quiet", action="store_true", help="Turn verbosity off."
  1233. )
  1234. options = parser.parse_args(args)
  1235. if options.remove_overlaps:
  1236. if options.ignore_overlap_errors:
  1237. options.overlap = OverlapMode.REMOVE_AND_IGNORE_ERRORS
  1238. else:
  1239. options.overlap = OverlapMode.REMOVE
  1240. else:
  1241. options.overlap = OverlapMode(int(options.overlap))
  1242. infile = options.input
  1243. if not os.path.isfile(infile):
  1244. parser.error("No such file '{}'".format(infile))
  1245. configLogger(
  1246. level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
  1247. )
  1248. try:
  1249. axisLimits = parseLimits(options.locargs)
  1250. except ValueError as e:
  1251. parser.error(str(e))
  1252. if len(axisLimits) != len(options.locargs):
  1253. parser.error("Specified multiple limits for the same axis")
  1254. return (infile, axisLimits, options)
  1255. def main(args=None):
  1256. """Partially instantiate a variable font"""
  1257. infile, axisLimits, options = parseArgs(args)
  1258. log.info("Restricting axes: %s", axisLimits)
  1259. log.info("Loading variable font")
  1260. varfont = TTFont(
  1261. infile,
  1262. recalcTimestamp=options.recalc_timestamp,
  1263. recalcBBoxes=options.recalc_bounds,
  1264. )
  1265. isFullInstance = {
  1266. axisTag for axisTag, limit in axisLimits.items() if not isinstance(limit, tuple)
  1267. }.issuperset(axis.axisTag for axis in varfont["fvar"].axes)
  1268. instantiateVariableFont(
  1269. varfont,
  1270. axisLimits,
  1271. inplace=True,
  1272. optimize=options.optimize,
  1273. overlap=options.overlap,
  1274. updateFontNames=options.update_name_table,
  1275. )
  1276. suffix = "-instance" if isFullInstance else "-partial"
  1277. outfile = (
  1278. makeOutputFileName(infile, overWrite=True, suffix=suffix)
  1279. if not options.output
  1280. else options.output
  1281. )
  1282. log.info(
  1283. "Saving %s font %s",
  1284. "instance" if isFullInstance else "partial variable",
  1285. outfile,
  1286. )
  1287. varfont.save(outfile)