__init__.py 70 KB

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