__init__.py 69 KB

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