__init__.py 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565
  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 (i.e. doesn't participate),
  419. lower, peak, upper = var.axes.get(axisTag, (-1, 0, 1))
  420. if peak == 0:
  421. return [var]
  422. # Drop if the var 'tent' isn't well-formed
  423. if not (lower <= peak <= upper) or (lower < 0 and upper > 0):
  424. return []
  425. if axisTag not in var.axes:
  426. return [var]
  427. tent = var.axes[axisTag]
  428. solutions = solver.rebaseTent(tent, axisLimit)
  429. out = []
  430. for scalar, tent in solutions:
  431. newVar = (
  432. TupleVariation(var.axes, var.coordinates) if len(solutions) > 1 else var
  433. )
  434. if tent is None:
  435. newVar.axes.pop(axisTag)
  436. else:
  437. assert tent[1] != 0, tent
  438. newVar.axes[axisTag] = tent
  439. newVar *= scalar
  440. out.append(newVar)
  441. return out
  442. def _instantiateGvarGlyph(
  443. glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=True
  444. ):
  445. coordinates, ctrl = glyf._getCoordinatesAndControls(glyphname, hMetrics, vMetrics)
  446. endPts = ctrl.endPts
  447. # Not every glyph may have variations
  448. tupleVarStore = gvar.variations.get(glyphname)
  449. if tupleVarStore:
  450. defaultDeltas = instantiateTupleVariationStore(
  451. tupleVarStore, axisLimits, coordinates, endPts
  452. )
  453. if defaultDeltas:
  454. coordinates += _g_l_y_f.GlyphCoordinates(defaultDeltas)
  455. glyph = glyf[glyphname]
  456. if glyph.isVarComposite():
  457. for component in glyph.components:
  458. newLocation = {}
  459. for tag, loc in component.location.items():
  460. if tag not in axisLimits:
  461. newLocation[tag] = loc
  462. continue
  463. if component.flags & _g_l_y_f.VarComponentFlags.AXES_HAVE_VARIATION:
  464. raise NotImplementedError(
  465. "Instancing accross VarComposite axes with variation is not supported."
  466. )
  467. limits = axisLimits[tag]
  468. loc = limits.renormalizeValue(loc, extrapolate=False)
  469. newLocation[tag] = loc
  470. component.location = newLocation
  471. # _setCoordinates also sets the hmtx/vmtx advance widths and sidebearings from
  472. # the four phantom points and glyph bounding boxes.
  473. # We call it unconditionally even if a glyph has no variations or no deltas are
  474. # applied at this location, in case the glyph's xMin and in turn its sidebearing
  475. # have changed. E.g. a composite glyph has no deltas for the component's (x, y)
  476. # offset nor for the 4 phantom points (e.g. it's monospaced). Thus its entry in
  477. # gvar table is empty; however, the composite's base glyph may have deltas
  478. # applied, hence the composite's bbox and left/top sidebearings may need updating
  479. # in the instanced font.
  480. glyf._setCoordinates(glyphname, coordinates, hMetrics, vMetrics)
  481. if not tupleVarStore:
  482. if glyphname in gvar.variations:
  483. del gvar.variations[glyphname]
  484. return
  485. if optimize:
  486. isComposite = glyf[glyphname].isComposite()
  487. for var in tupleVarStore:
  488. var.optimize(coordinates, endPts, isComposite)
  489. def instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True):
  490. """Remove?
  491. https://github.com/fonttools/fonttools/pull/2266"""
  492. gvar = varfont["gvar"]
  493. glyf = varfont["glyf"]
  494. hMetrics = varfont["hmtx"].metrics
  495. vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
  496. _instantiateGvarGlyph(
  497. glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
  498. )
  499. def instantiateGvar(varfont, axisLimits, optimize=True):
  500. log.info("Instantiating glyf/gvar tables")
  501. gvar = varfont["gvar"]
  502. glyf = varfont["glyf"]
  503. hMetrics = varfont["hmtx"].metrics
  504. vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
  505. # Get list of glyph names sorted by component depth.
  506. # If a composite glyph is processed before its base glyph, the bounds may
  507. # be calculated incorrectly because deltas haven't been applied to the
  508. # base glyph yet.
  509. glyphnames = sorted(
  510. glyf.glyphOrder,
  511. key=lambda name: (
  512. glyf[name].getCompositeMaxpValues(glyf).maxComponentDepth
  513. if glyf[name].isComposite() or glyf[name].isVarComposite()
  514. else 0,
  515. name,
  516. ),
  517. )
  518. for glyphname in glyphnames:
  519. _instantiateGvarGlyph(
  520. glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
  521. )
  522. if not gvar.variations:
  523. del varfont["gvar"]
  524. def setCvarDeltas(cvt, deltas):
  525. for i, delta in enumerate(deltas):
  526. if delta:
  527. cvt[i] += otRound(delta)
  528. def instantiateCvar(varfont, axisLimits):
  529. log.info("Instantiating cvt/cvar tables")
  530. cvar = varfont["cvar"]
  531. defaultDeltas = instantiateTupleVariationStore(cvar.variations, axisLimits)
  532. if defaultDeltas:
  533. setCvarDeltas(varfont["cvt "], defaultDeltas)
  534. if not cvar.variations:
  535. del varfont["cvar"]
  536. def setMvarDeltas(varfont, deltas):
  537. mvar = varfont["MVAR"].table
  538. records = mvar.ValueRecord
  539. for rec in records:
  540. mvarTag = rec.ValueTag
  541. if mvarTag not in MVAR_ENTRIES:
  542. continue
  543. tableTag, itemName = MVAR_ENTRIES[mvarTag]
  544. delta = deltas[rec.VarIdx]
  545. if delta != 0:
  546. setattr(
  547. varfont[tableTag],
  548. itemName,
  549. getattr(varfont[tableTag], itemName) + otRound(delta),
  550. )
  551. @contextmanager
  552. def verticalMetricsKeptInSync(varfont):
  553. """Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing.
  554. When applying MVAR deltas to the OS/2 table, if the ascender, descender and
  555. line gap change but they were the same as the respective hhea metrics in the
  556. original font, this context manager ensures that hhea metrcs also get updated
  557. accordingly.
  558. The MVAR spec only has tags for the OS/2 metrics, but it is common in fonts
  559. to have the hhea metrics be equal to those for compat reasons.
  560. https://learn.microsoft.com/en-us/typography/opentype/spec/mvar
  561. https://googlefonts.github.io/gf-guide/metrics.html#7-hhea-and-typo-metrics-should-be-equal
  562. https://github.com/fonttools/fonttools/issues/3297
  563. """
  564. current_os2_vmetrics = [
  565. getattr(varfont["OS/2"], attr)
  566. for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap")
  567. ]
  568. metrics_are_synced = current_os2_vmetrics == [
  569. getattr(varfont["hhea"], attr) for attr in ("ascender", "descender", "lineGap")
  570. ]
  571. yield metrics_are_synced
  572. if metrics_are_synced:
  573. new_os2_vmetrics = [
  574. getattr(varfont["OS/2"], attr)
  575. for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap")
  576. ]
  577. if current_os2_vmetrics != new_os2_vmetrics:
  578. for attr, value in zip(
  579. ("ascender", "descender", "lineGap"), new_os2_vmetrics
  580. ):
  581. setattr(varfont["hhea"], attr, value)
  582. def instantiateMVAR(varfont, axisLimits):
  583. log.info("Instantiating MVAR table")
  584. mvar = varfont["MVAR"].table
  585. fvarAxes = varfont["fvar"].axes
  586. varStore = mvar.VarStore
  587. defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
  588. with verticalMetricsKeptInSync(varfont):
  589. setMvarDeltas(varfont, defaultDeltas)
  590. if varStore.VarRegionList.Region:
  591. varIndexMapping = varStore.optimize()
  592. for rec in mvar.ValueRecord:
  593. rec.VarIdx = varIndexMapping[rec.VarIdx]
  594. else:
  595. del varfont["MVAR"]
  596. def _remapVarIdxMap(table, attrName, varIndexMapping, glyphOrder):
  597. oldMapping = getattr(table, attrName).mapping
  598. newMapping = [varIndexMapping[oldMapping[glyphName]] for glyphName in glyphOrder]
  599. setattr(table, attrName, builder.buildVarIdxMap(newMapping, glyphOrder))
  600. # TODO(anthrotype) Add support for HVAR/VVAR in CFF2
  601. def _instantiateVHVAR(varfont, axisLimits, tableFields):
  602. location = axisLimits.pinnedLocation()
  603. tableTag = tableFields.tableTag
  604. fvarAxes = varfont["fvar"].axes
  605. # Deltas from gvar table have already been applied to the hmtx/vmtx. For full
  606. # instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return
  607. if set(location).issuperset(axis.axisTag for axis in fvarAxes):
  608. log.info("Dropping %s table", tableTag)
  609. del varfont[tableTag]
  610. return
  611. log.info("Instantiating %s table", tableTag)
  612. vhvar = varfont[tableTag].table
  613. varStore = vhvar.VarStore
  614. # since deltas were already applied, the return value here is ignored
  615. instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
  616. if varStore.VarRegionList.Region:
  617. # Only re-optimize VarStore if the HVAR/VVAR already uses indirect AdvWidthMap
  618. # or AdvHeightMap. If a direct, implicit glyphID->VariationIndex mapping is
  619. # used for advances, skip re-optimizing and maintain original VariationIndex.
  620. if getattr(vhvar, tableFields.advMapping):
  621. varIndexMapping = varStore.optimize(use_NO_VARIATION_INDEX=False)
  622. glyphOrder = varfont.getGlyphOrder()
  623. _remapVarIdxMap(vhvar, tableFields.advMapping, varIndexMapping, glyphOrder)
  624. if getattr(vhvar, tableFields.sb1): # left or top sidebearings
  625. _remapVarIdxMap(vhvar, tableFields.sb1, varIndexMapping, glyphOrder)
  626. if getattr(vhvar, tableFields.sb2): # right or bottom sidebearings
  627. _remapVarIdxMap(vhvar, tableFields.sb2, varIndexMapping, glyphOrder)
  628. if tableTag == "VVAR" and getattr(vhvar, tableFields.vOrigMapping):
  629. _remapVarIdxMap(
  630. vhvar, tableFields.vOrigMapping, varIndexMapping, glyphOrder
  631. )
  632. def instantiateHVAR(varfont, axisLimits):
  633. return _instantiateVHVAR(varfont, axisLimits, varLib.HVAR_FIELDS)
  634. def instantiateVVAR(varfont, axisLimits):
  635. return _instantiateVHVAR(varfont, axisLimits, varLib.VVAR_FIELDS)
  636. class _TupleVarStoreAdapter(object):
  637. def __init__(self, regions, axisOrder, tupleVarData, itemCounts):
  638. self.regions = regions
  639. self.axisOrder = axisOrder
  640. self.tupleVarData = tupleVarData
  641. self.itemCounts = itemCounts
  642. @classmethod
  643. def fromItemVarStore(cls, itemVarStore, fvarAxes):
  644. axisOrder = [axis.axisTag for axis in fvarAxes]
  645. regions = [
  646. region.get_support(fvarAxes) for region in itemVarStore.VarRegionList.Region
  647. ]
  648. tupleVarData = []
  649. itemCounts = []
  650. for varData in itemVarStore.VarData:
  651. variations = []
  652. varDataRegions = (regions[i] for i in varData.VarRegionIndex)
  653. for axes, coordinates in zip(varDataRegions, zip(*varData.Item)):
  654. variations.append(TupleVariation(axes, list(coordinates)))
  655. tupleVarData.append(variations)
  656. itemCounts.append(varData.ItemCount)
  657. return cls(regions, axisOrder, tupleVarData, itemCounts)
  658. def rebuildRegions(self):
  659. # Collect the set of all unique region axes from the current TupleVariations.
  660. # We use an OrderedDict to de-duplicate regions while keeping the order.
  661. uniqueRegions = collections.OrderedDict.fromkeys(
  662. (
  663. frozenset(var.axes.items())
  664. for variations in self.tupleVarData
  665. for var in variations
  666. )
  667. )
  668. # Maintain the original order for the regions that pre-existed, appending
  669. # the new regions at the end of the region list.
  670. newRegions = []
  671. for region in self.regions:
  672. regionAxes = frozenset(region.items())
  673. if regionAxes in uniqueRegions:
  674. newRegions.append(region)
  675. del uniqueRegions[regionAxes]
  676. if uniqueRegions:
  677. newRegions.extend(dict(region) for region in uniqueRegions)
  678. self.regions = newRegions
  679. def instantiate(self, axisLimits):
  680. defaultDeltaArray = []
  681. for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
  682. defaultDeltas = instantiateTupleVariationStore(variations, axisLimits)
  683. if not defaultDeltas:
  684. defaultDeltas = [0] * itemCount
  685. defaultDeltaArray.append(defaultDeltas)
  686. # rebuild regions whose axes were dropped or limited
  687. self.rebuildRegions()
  688. pinnedAxes = set(axisLimits.pinnedLocation())
  689. self.axisOrder = [
  690. axisTag for axisTag in self.axisOrder if axisTag not in pinnedAxes
  691. ]
  692. return defaultDeltaArray
  693. def asItemVarStore(self):
  694. regionOrder = [frozenset(axes.items()) for axes in self.regions]
  695. varDatas = []
  696. for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
  697. if variations:
  698. assert len(variations[0].coordinates) == itemCount
  699. varRegionIndices = [
  700. regionOrder.index(frozenset(var.axes.items())) for var in variations
  701. ]
  702. varDataItems = list(zip(*(var.coordinates for var in variations)))
  703. varDatas.append(
  704. builder.buildVarData(varRegionIndices, varDataItems, optimize=False)
  705. )
  706. else:
  707. varDatas.append(
  708. builder.buildVarData([], [[] for _ in range(itemCount)])
  709. )
  710. regionList = builder.buildVarRegionList(self.regions, self.axisOrder)
  711. itemVarStore = builder.buildVarStore(regionList, varDatas)
  712. # remove unused regions from VarRegionList
  713. itemVarStore.prune_regions()
  714. return itemVarStore
  715. def instantiateItemVariationStore(itemVarStore, fvarAxes, axisLimits):
  716. """Compute deltas at partial location, and update varStore in-place.
  717. Remove regions in which all axes were instanced, or fall outside the new axis
  718. limits. Scale the deltas of the remaining regions where only some of the axes
  719. were instanced.
  720. The number of VarData subtables, and the number of items within each, are
  721. not modified, in order to keep the existing VariationIndex valid.
  722. One may call VarStore.optimize() method after this to further optimize those.
  723. Args:
  724. varStore: An otTables.VarStore object (Item Variation Store)
  725. fvarAxes: list of fvar's Axis objects
  726. axisLimits: NormalizedAxisLimits: mapping axis tags to normalized
  727. min/default/max axis coordinates. May not specify coordinates/ranges for
  728. all the fvar axes.
  729. Returns:
  730. defaultDeltas: to be added to the default instance, of type dict of floats
  731. keyed by VariationIndex compound values: i.e. (outer << 16) + inner.
  732. """
  733. tupleVarStore = _TupleVarStoreAdapter.fromItemVarStore(itemVarStore, fvarAxes)
  734. defaultDeltaArray = tupleVarStore.instantiate(axisLimits)
  735. newItemVarStore = tupleVarStore.asItemVarStore()
  736. itemVarStore.VarRegionList = newItemVarStore.VarRegionList
  737. assert itemVarStore.VarDataCount == newItemVarStore.VarDataCount
  738. itemVarStore.VarData = newItemVarStore.VarData
  739. defaultDeltas = {
  740. ((major << 16) + minor): delta
  741. for major, deltas in enumerate(defaultDeltaArray)
  742. for minor, delta in enumerate(deltas)
  743. }
  744. defaultDeltas[itemVarStore.NO_VARIATION_INDEX] = 0
  745. return defaultDeltas
  746. def instantiateOTL(varfont, axisLimits):
  747. # TODO(anthrotype) Support partial instancing of JSTF and BASE tables
  748. if (
  749. "GDEF" not in varfont
  750. or varfont["GDEF"].table.Version < 0x00010003
  751. or not varfont["GDEF"].table.VarStore
  752. ):
  753. return
  754. if "GPOS" in varfont:
  755. msg = "Instantiating GDEF and GPOS tables"
  756. else:
  757. msg = "Instantiating GDEF table"
  758. log.info(msg)
  759. gdef = varfont["GDEF"].table
  760. varStore = gdef.VarStore
  761. fvarAxes = varfont["fvar"].axes
  762. defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
  763. # When VF are built, big lookups may overflow and be broken into multiple
  764. # subtables. MutatorMerger (which inherits from AligningMerger) reattaches
  765. # them upon instancing, in case they can now fit a single subtable (if not,
  766. # they will be split again upon compilation).
  767. # This 'merger' also works as a 'visitor' that traverses the OTL tables and
  768. # calls specific methods when instances of a given type are found.
  769. # Specifically, it adds default deltas to GPOS Anchors/ValueRecords and GDEF
  770. # LigatureCarets, and optionally deletes all VariationIndex tables if the
  771. # VarStore is fully instanced.
  772. merger = MutatorMerger(
  773. varfont, defaultDeltas, deleteVariations=(not varStore.VarRegionList.Region)
  774. )
  775. merger.mergeTables(varfont, [varfont], ["GDEF", "GPOS"])
  776. if varStore.VarRegionList.Region:
  777. varIndexMapping = varStore.optimize()
  778. gdef.remap_device_varidxes(varIndexMapping)
  779. if "GPOS" in varfont:
  780. varfont["GPOS"].table.remap_device_varidxes(varIndexMapping)
  781. else:
  782. # Downgrade GDEF.
  783. del gdef.VarStore
  784. gdef.Version = 0x00010002
  785. if gdef.MarkGlyphSetsDef is None:
  786. del gdef.MarkGlyphSetsDef
  787. gdef.Version = 0x00010000
  788. if not (
  789. gdef.LigCaretList
  790. or gdef.MarkAttachClassDef
  791. or gdef.GlyphClassDef
  792. or gdef.AttachList
  793. or (gdef.Version >= 0x00010002 and gdef.MarkGlyphSetsDef)
  794. ):
  795. del varfont["GDEF"]
  796. def _isValidAvarSegmentMap(axisTag, segmentMap):
  797. if not segmentMap:
  798. return True
  799. if not {(-1.0, -1.0), (0, 0), (1.0, 1.0)}.issubset(segmentMap.items()):
  800. log.warning(
  801. f"Invalid avar SegmentMap record for axis '{axisTag}': does not "
  802. "include all required value maps {-1.0: -1.0, 0: 0, 1.0: 1.0}"
  803. )
  804. return False
  805. previousValue = None
  806. for fromCoord, toCoord in sorted(segmentMap.items()):
  807. if previousValue is not None and previousValue > toCoord:
  808. log.warning(
  809. f"Invalid avar AxisValueMap({fromCoord}, {toCoord}) record "
  810. f"for axis '{axisTag}': the toCoordinate value must be >= to "
  811. f"the toCoordinate value of the preceding record ({previousValue})."
  812. )
  813. return False
  814. previousValue = toCoord
  815. return True
  816. def instantiateAvar(varfont, axisLimits):
  817. # 'axisLimits' dict must contain user-space (non-normalized) coordinates.
  818. segments = varfont["avar"].segments
  819. # drop table if we instantiate all the axes
  820. pinnedAxes = set(axisLimits.pinnedLocation())
  821. if pinnedAxes.issuperset(segments):
  822. log.info("Dropping avar table")
  823. del varfont["avar"]
  824. return
  825. log.info("Instantiating avar table")
  826. for axis in pinnedAxes:
  827. if axis in segments:
  828. del segments[axis]
  829. # First compute the default normalization for axisLimits coordinates: i.e.
  830. # min = -1.0, default = 0, max = +1.0, and in between values interpolated linearly,
  831. # without using the avar table's mappings.
  832. # Then, for each SegmentMap, if we are restricting its axis, compute the new
  833. # mappings by dividing the key/value pairs by the desired new min/max values,
  834. # dropping any mappings that fall outside the restricted range.
  835. # The keys ('fromCoord') are specified in default normalized coordinate space,
  836. # whereas the values ('toCoord') are "mapped forward" using the SegmentMap.
  837. normalizedRanges = axisLimits.normalize(varfont, usingAvar=False)
  838. newSegments = {}
  839. for axisTag, mapping in segments.items():
  840. if not _isValidAvarSegmentMap(axisTag, mapping):
  841. continue
  842. if mapping and axisTag in normalizedRanges:
  843. axisRange = normalizedRanges[axisTag]
  844. mappedMin = floatToFixedToFloat(
  845. piecewiseLinearMap(axisRange.minimum, mapping), 14
  846. )
  847. mappedDef = floatToFixedToFloat(
  848. piecewiseLinearMap(axisRange.default, mapping), 14
  849. )
  850. mappedMax = floatToFixedToFloat(
  851. piecewiseLinearMap(axisRange.maximum, mapping), 14
  852. )
  853. mappedAxisLimit = NormalizedAxisTripleAndDistances(
  854. mappedMin,
  855. mappedDef,
  856. mappedMax,
  857. axisRange.distanceNegative,
  858. axisRange.distancePositive,
  859. )
  860. newMapping = {}
  861. for fromCoord, toCoord in mapping.items():
  862. if fromCoord < axisRange.minimum or fromCoord > axisRange.maximum:
  863. continue
  864. fromCoord = axisRange.renormalizeValue(fromCoord)
  865. assert mappedMin <= toCoord <= mappedMax
  866. toCoord = mappedAxisLimit.renormalizeValue(toCoord)
  867. fromCoord = floatToFixedToFloat(fromCoord, 14)
  868. toCoord = floatToFixedToFloat(toCoord, 14)
  869. newMapping[fromCoord] = toCoord
  870. newMapping.update({-1.0: -1.0, 0.0: 0.0, 1.0: 1.0})
  871. newSegments[axisTag] = newMapping
  872. else:
  873. newSegments[axisTag] = mapping
  874. varfont["avar"].segments = newSegments
  875. def isInstanceWithinAxisRanges(location, axisRanges):
  876. for axisTag, coord in location.items():
  877. if axisTag in axisRanges:
  878. axisRange = axisRanges[axisTag]
  879. if coord < axisRange.minimum or coord > axisRange.maximum:
  880. return False
  881. return True
  882. def instantiateFvar(varfont, axisLimits):
  883. # 'axisLimits' dict must contain user-space (non-normalized) coordinates
  884. location = axisLimits.pinnedLocation()
  885. fvar = varfont["fvar"]
  886. # drop table if we instantiate all the axes
  887. if set(location).issuperset(axis.axisTag for axis in fvar.axes):
  888. log.info("Dropping fvar table")
  889. del varfont["fvar"]
  890. return
  891. log.info("Instantiating fvar table")
  892. axes = []
  893. for axis in fvar.axes:
  894. axisTag = axis.axisTag
  895. if axisTag in location:
  896. continue
  897. if axisTag in axisLimits:
  898. triple = axisLimits[axisTag]
  899. if triple.default is None:
  900. triple = (triple.minimum, axis.defaultValue, triple.maximum)
  901. axis.minValue, axis.defaultValue, axis.maxValue = triple
  902. axes.append(axis)
  903. fvar.axes = axes
  904. # only keep NamedInstances whose coordinates == pinned axis location
  905. instances = []
  906. for instance in fvar.instances:
  907. if any(instance.coordinates[axis] != value for axis, value in location.items()):
  908. continue
  909. for axisTag in location:
  910. del instance.coordinates[axisTag]
  911. if not isInstanceWithinAxisRanges(instance.coordinates, axisLimits):
  912. continue
  913. instances.append(instance)
  914. fvar.instances = instances
  915. def instantiateSTAT(varfont, axisLimits):
  916. # 'axisLimits' dict must contain user-space (non-normalized) coordinates
  917. stat = varfont["STAT"].table
  918. if not stat.DesignAxisRecord or not (
  919. stat.AxisValueArray and stat.AxisValueArray.AxisValue
  920. ):
  921. return # STAT table empty, nothing to do
  922. log.info("Instantiating STAT table")
  923. newAxisValueTables = axisValuesFromAxisLimits(stat, axisLimits)
  924. stat.AxisValueCount = len(newAxisValueTables)
  925. if stat.AxisValueCount:
  926. stat.AxisValueArray.AxisValue = newAxisValueTables
  927. else:
  928. stat.AxisValueArray = None
  929. def axisValuesFromAxisLimits(stat, axisLimits):
  930. def isAxisValueOutsideLimits(axisTag, axisValue):
  931. if axisTag in axisLimits:
  932. triple = axisLimits[axisTag]
  933. if axisValue < triple.minimum or axisValue > triple.maximum:
  934. return True
  935. return False
  936. # only keep AxisValues whose axis is not pinned nor restricted, or is pinned at the
  937. # exact (nominal) value, or is restricted but the value is within the new range
  938. designAxes = stat.DesignAxisRecord.Axis
  939. newAxisValueTables = []
  940. for axisValueTable in stat.AxisValueArray.AxisValue:
  941. axisValueFormat = axisValueTable.Format
  942. if axisValueFormat in (1, 2, 3):
  943. axisTag = designAxes[axisValueTable.AxisIndex].AxisTag
  944. if axisValueFormat == 2:
  945. axisValue = axisValueTable.NominalValue
  946. else:
  947. axisValue = axisValueTable.Value
  948. if isAxisValueOutsideLimits(axisTag, axisValue):
  949. continue
  950. elif axisValueFormat == 4:
  951. # drop 'non-analytic' AxisValue if _any_ AxisValueRecord doesn't match
  952. # the pinned location or is outside range
  953. dropAxisValueTable = False
  954. for rec in axisValueTable.AxisValueRecord:
  955. axisTag = designAxes[rec.AxisIndex].AxisTag
  956. axisValue = rec.Value
  957. if isAxisValueOutsideLimits(axisTag, axisValue):
  958. dropAxisValueTable = True
  959. break
  960. if dropAxisValueTable:
  961. continue
  962. else:
  963. log.warning("Unknown AxisValue table format (%s); ignored", axisValueFormat)
  964. newAxisValueTables.append(axisValueTable)
  965. return newAxisValueTables
  966. def setMacOverlapFlags(glyfTable):
  967. flagOverlapCompound = _g_l_y_f.OVERLAP_COMPOUND
  968. flagOverlapSimple = _g_l_y_f.flagOverlapSimple
  969. for glyphName in glyfTable.keys():
  970. glyph = glyfTable[glyphName]
  971. # Set OVERLAP_COMPOUND bit for compound glyphs
  972. if glyph.isComposite():
  973. glyph.components[0].flags |= flagOverlapCompound
  974. # Set OVERLAP_SIMPLE bit for simple glyphs
  975. elif glyph.numberOfContours > 0:
  976. glyph.flags[0] |= flagOverlapSimple
  977. def normalize(value, triple, avarMapping):
  978. value = normalizeValue(value, triple)
  979. if avarMapping:
  980. value = piecewiseLinearMap(value, avarMapping)
  981. # Quantize to F2Dot14, to avoid surprise interpolations.
  982. return floatToFixedToFloat(value, 14)
  983. def sanityCheckVariableTables(varfont):
  984. if "fvar" not in varfont:
  985. raise ValueError("Missing required table fvar")
  986. if "gvar" in varfont:
  987. if "glyf" not in varfont:
  988. raise ValueError("Can't have gvar without glyf")
  989. # TODO(anthrotype) Remove once we do support partial instancing CFF2
  990. if "CFF2" in varfont:
  991. raise NotImplementedError("Instancing CFF2 variable fonts is not supported yet")
  992. def instantiateVariableFont(
  993. varfont,
  994. axisLimits,
  995. inplace=False,
  996. optimize=True,
  997. overlap=OverlapMode.KEEP_AND_SET_FLAGS,
  998. updateFontNames=False,
  999. ):
  1000. """Instantiate variable font, either fully or partially.
  1001. Depending on whether the `axisLimits` dictionary references all or some of the
  1002. input varfont's axes, the output font will either be a full instance (static
  1003. font) or a variable font with possibly less variation data.
  1004. Args:
  1005. varfont: a TTFont instance, which must contain at least an 'fvar' table.
  1006. Note that variable fonts with 'CFF2' table are not supported yet.
  1007. axisLimits: a dict keyed by axis tags (str) containing the coordinates (float)
  1008. along one or more axes where the desired instance will be located.
  1009. If the value is `None`, the default coordinate as per 'fvar' table for
  1010. that axis is used.
  1011. The limit values can also be (min, max) tuples for restricting an
  1012. axis's variation range. The default axis value must be included in
  1013. the new range.
  1014. inplace (bool): whether to modify input TTFont object in-place instead of
  1015. returning a distinct object.
  1016. optimize (bool): if False, do not perform IUP-delta optimization on the
  1017. remaining 'gvar' table's deltas. Possibly faster, and might work around
  1018. rendering issues in some buggy environments, at the cost of a slightly
  1019. larger file size.
  1020. overlap (OverlapMode): variable fonts usually contain overlapping contours, and
  1021. some font rendering engines on Apple platforms require that the
  1022. `OVERLAP_SIMPLE` and `OVERLAP_COMPOUND` flags in the 'glyf' table be set to
  1023. force rendering using a non-zero fill rule. Thus we always set these flags
  1024. on all glyphs to maximise cross-compatibility of the generated instance.
  1025. You can disable this by passing OverlapMode.KEEP_AND_DONT_SET_FLAGS.
  1026. If you want to remove the overlaps altogether and merge overlapping
  1027. contours and components, you can pass OverlapMode.REMOVE (or
  1028. REMOVE_AND_IGNORE_ERRORS to not hard-fail on tricky glyphs). Note that this
  1029. requires the skia-pathops package (available to pip install).
  1030. The overlap parameter only has effect when generating full static instances.
  1031. updateFontNames (bool): if True, update the instantiated font's name table using
  1032. the Axis Value Tables from the STAT table. The name table and the style bits
  1033. in the head and OS/2 table will be updated so they conform to the R/I/B/BI
  1034. model. If the STAT table is missing or an Axis Value table is missing for
  1035. a given axis coordinate, a ValueError will be raised.
  1036. """
  1037. # 'overlap' used to be bool and is now enum; for backward compat keep accepting bool
  1038. overlap = OverlapMode(int(overlap))
  1039. sanityCheckVariableTables(varfont)
  1040. axisLimits = AxisLimits(axisLimits).limitAxesAndPopulateDefaults(varfont)
  1041. log.info("Restricted limits: %s", axisLimits)
  1042. normalizedLimits = axisLimits.normalize(varfont)
  1043. log.info("Normalized limits: %s", normalizedLimits)
  1044. if not inplace:
  1045. varfont = deepcopy(varfont)
  1046. if "DSIG" in varfont:
  1047. del varfont["DSIG"]
  1048. if updateFontNames:
  1049. log.info("Updating name table")
  1050. names.updateNameTable(varfont, axisLimits)
  1051. if "gvar" in varfont:
  1052. instantiateGvar(varfont, normalizedLimits, optimize=optimize)
  1053. if "cvar" in varfont:
  1054. instantiateCvar(varfont, normalizedLimits)
  1055. if "MVAR" in varfont:
  1056. instantiateMVAR(varfont, normalizedLimits)
  1057. if "HVAR" in varfont:
  1058. instantiateHVAR(varfont, normalizedLimits)
  1059. if "VVAR" in varfont:
  1060. instantiateVVAR(varfont, normalizedLimits)
  1061. instantiateOTL(varfont, normalizedLimits)
  1062. instantiateFeatureVariations(varfont, normalizedLimits)
  1063. if "avar" in varfont:
  1064. instantiateAvar(varfont, axisLimits)
  1065. with names.pruningUnusedNames(varfont):
  1066. if "STAT" in varfont:
  1067. instantiateSTAT(varfont, axisLimits)
  1068. instantiateFvar(varfont, axisLimits)
  1069. if "fvar" not in varfont:
  1070. if "glyf" in varfont:
  1071. if overlap == OverlapMode.KEEP_AND_SET_FLAGS:
  1072. setMacOverlapFlags(varfont["glyf"])
  1073. elif overlap in (OverlapMode.REMOVE, OverlapMode.REMOVE_AND_IGNORE_ERRORS):
  1074. from fontTools.ttLib.removeOverlaps import removeOverlaps
  1075. log.info("Removing overlaps from glyf table")
  1076. removeOverlaps(
  1077. varfont,
  1078. ignoreErrors=(overlap == OverlapMode.REMOVE_AND_IGNORE_ERRORS),
  1079. )
  1080. if "OS/2" in varfont:
  1081. varfont["OS/2"].recalcAvgCharWidth(varfont)
  1082. varLib.set_default_weight_width_slant(
  1083. varfont, location=axisLimits.defaultLocation()
  1084. )
  1085. if updateFontNames:
  1086. # Set Regular/Italic/Bold/Bold Italic bits as appropriate, after the
  1087. # name table has been updated.
  1088. setRibbiBits(varfont)
  1089. return varfont
  1090. def setRibbiBits(font):
  1091. """Set the `head.macStyle` and `OS/2.fsSelection` style bits
  1092. appropriately."""
  1093. english_ribbi_style = font["name"].getName(names.NameID.SUBFAMILY_NAME, 3, 1, 0x409)
  1094. if english_ribbi_style is None:
  1095. return
  1096. styleMapStyleName = english_ribbi_style.toStr().lower()
  1097. if styleMapStyleName not in {"regular", "bold", "italic", "bold italic"}:
  1098. return
  1099. if styleMapStyleName == "bold":
  1100. font["head"].macStyle = 0b01
  1101. elif styleMapStyleName == "bold italic":
  1102. font["head"].macStyle = 0b11
  1103. elif styleMapStyleName == "italic":
  1104. font["head"].macStyle = 0b10
  1105. selection = font["OS/2"].fsSelection
  1106. # First clear...
  1107. selection &= ~(1 << 0)
  1108. selection &= ~(1 << 5)
  1109. selection &= ~(1 << 6)
  1110. # ...then re-set the bits.
  1111. if styleMapStyleName == "regular":
  1112. selection |= 1 << 6
  1113. elif styleMapStyleName == "bold":
  1114. selection |= 1 << 5
  1115. elif styleMapStyleName == "italic":
  1116. selection |= 1 << 0
  1117. elif styleMapStyleName == "bold italic":
  1118. selection |= 1 << 0
  1119. selection |= 1 << 5
  1120. font["OS/2"].fsSelection = selection
  1121. def parseLimits(limits: Iterable[str]) -> Dict[str, Optional[AxisTriple]]:
  1122. result = {}
  1123. for limitString in limits:
  1124. match = re.match(
  1125. r"^(\w{1,4})=(?:(drop)|(?:([^:]*)(?:[:]([^:]*))?(?:[:]([^:]*))?))$",
  1126. limitString,
  1127. )
  1128. if not match:
  1129. raise ValueError("invalid location format: %r" % limitString)
  1130. tag = match.group(1).ljust(4)
  1131. if match.group(2): # 'drop'
  1132. result[tag] = None
  1133. continue
  1134. triple = match.group(3, 4, 5)
  1135. if triple[1] is None: # "value" syntax
  1136. triple = (triple[0], triple[0], triple[0])
  1137. elif triple[2] is None: # "min:max" syntax
  1138. triple = (triple[0], None, triple[1])
  1139. triple = tuple(float(v) if v else None for v in triple)
  1140. result[tag] = AxisTriple(*triple)
  1141. return result
  1142. def parseArgs(args):
  1143. """Parse argv.
  1144. Returns:
  1145. 3-tuple (infile, axisLimits, options)
  1146. axisLimits is either a Dict[str, Optional[float]], for pinning variation axes
  1147. to specific coordinates along those axes (with `None` as a placeholder for an
  1148. axis' default value); or a Dict[str, Tuple(float, float)], meaning limit this
  1149. axis to min/max range.
  1150. Axes locations are in user-space coordinates, as defined in the "fvar" table.
  1151. """
  1152. from fontTools import configLogger
  1153. import argparse
  1154. parser = argparse.ArgumentParser(
  1155. "fonttools varLib.instancer",
  1156. description="Partially instantiate a variable font",
  1157. )
  1158. parser.add_argument("input", metavar="INPUT.ttf", help="Input variable TTF file.")
  1159. parser.add_argument(
  1160. "locargs",
  1161. metavar="AXIS=LOC",
  1162. nargs="*",
  1163. help="List of space separated locations. A location consists of "
  1164. "the tag of a variation axis, followed by '=' and the literal, "
  1165. "string 'drop', or comma-separate list of one to three values, "
  1166. "each of which is the empty string, or a number. "
  1167. "E.g.: wdth=100 or wght=75.0:125.0 or wght=100:400:700 or wght=:500: "
  1168. "or wght=drop",
  1169. )
  1170. parser.add_argument(
  1171. "-o",
  1172. "--output",
  1173. metavar="OUTPUT.ttf",
  1174. default=None,
  1175. help="Output instance TTF file (default: INPUT-instance.ttf).",
  1176. )
  1177. parser.add_argument(
  1178. "--no-optimize",
  1179. dest="optimize",
  1180. action="store_false",
  1181. help="Don't perform IUP optimization on the remaining gvar TupleVariations",
  1182. )
  1183. parser.add_argument(
  1184. "--no-overlap-flag",
  1185. dest="overlap",
  1186. action="store_false",
  1187. help="Don't set OVERLAP_SIMPLE/OVERLAP_COMPOUND glyf flags (only applicable "
  1188. "when generating a full instance)",
  1189. )
  1190. parser.add_argument(
  1191. "--remove-overlaps",
  1192. dest="remove_overlaps",
  1193. action="store_true",
  1194. help="Merge overlapping contours and components (only applicable "
  1195. "when generating a full instance). Requires skia-pathops",
  1196. )
  1197. parser.add_argument(
  1198. "--ignore-overlap-errors",
  1199. dest="ignore_overlap_errors",
  1200. action="store_true",
  1201. help="Don't crash if the remove-overlaps operation fails for some glyphs.",
  1202. )
  1203. parser.add_argument(
  1204. "--update-name-table",
  1205. action="store_true",
  1206. help="Update the instantiated font's `name` table. Input font must have "
  1207. "a STAT table with Axis Value Tables",
  1208. )
  1209. parser.add_argument(
  1210. "--no-recalc-timestamp",
  1211. dest="recalc_timestamp",
  1212. action="store_false",
  1213. help="Don't set the output font's timestamp to the current time.",
  1214. )
  1215. parser.add_argument(
  1216. "--no-recalc-bounds",
  1217. dest="recalc_bounds",
  1218. action="store_false",
  1219. help="Don't recalculate font bounding boxes",
  1220. )
  1221. loggingGroup = parser.add_mutually_exclusive_group(required=False)
  1222. loggingGroup.add_argument(
  1223. "-v", "--verbose", action="store_true", help="Run more verbosely."
  1224. )
  1225. loggingGroup.add_argument(
  1226. "-q", "--quiet", action="store_true", help="Turn verbosity off."
  1227. )
  1228. options = parser.parse_args(args)
  1229. if options.remove_overlaps:
  1230. if options.ignore_overlap_errors:
  1231. options.overlap = OverlapMode.REMOVE_AND_IGNORE_ERRORS
  1232. else:
  1233. options.overlap = OverlapMode.REMOVE
  1234. else:
  1235. options.overlap = OverlapMode(int(options.overlap))
  1236. infile = options.input
  1237. if not os.path.isfile(infile):
  1238. parser.error("No such file '{}'".format(infile))
  1239. configLogger(
  1240. level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
  1241. )
  1242. try:
  1243. axisLimits = parseLimits(options.locargs)
  1244. except ValueError as e:
  1245. parser.error(str(e))
  1246. if len(axisLimits) != len(options.locargs):
  1247. parser.error("Specified multiple limits for the same axis")
  1248. return (infile, axisLimits, options)
  1249. def main(args=None):
  1250. """Partially instantiate a variable font"""
  1251. infile, axisLimits, options = parseArgs(args)
  1252. log.info("Restricting axes: %s", axisLimits)
  1253. log.info("Loading variable font")
  1254. varfont = TTFont(
  1255. infile,
  1256. recalcTimestamp=options.recalc_timestamp,
  1257. recalcBBoxes=options.recalc_bounds,
  1258. )
  1259. isFullInstance = {
  1260. axisTag for axisTag, limit in axisLimits.items() if not isinstance(limit, tuple)
  1261. }.issuperset(axis.axisTag for axis in varfont["fvar"].axes)
  1262. instantiateVariableFont(
  1263. varfont,
  1264. axisLimits,
  1265. inplace=True,
  1266. optimize=options.optimize,
  1267. overlap=options.overlap,
  1268. updateFontNames=options.update_name_table,
  1269. )
  1270. suffix = "-instance" if isFullInstance else "-partial"
  1271. outfile = (
  1272. makeOutputFileName(infile, overWrite=True, suffix=suffix)
  1273. if not options.output
  1274. else options.output
  1275. )
  1276. log.info(
  1277. "Saving %s font %s",
  1278. "instance" if isFullInstance else "partial variable",
  1279. outfile,
  1280. )
  1281. varfont.save(outfile)