__init__.py 74 KB

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