__init__.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052
  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. isComposite = glyf[glyphname].isComposite()
  771. for var in tupleVarStore:
  772. var.optimize(coordinates, endPts, isComposite=isComposite)
  773. def instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True):
  774. """Remove?
  775. https://github.com/fonttools/fonttools/pull/2266"""
  776. gvar = varfont["gvar"]
  777. glyf = varfont["glyf"]
  778. hMetrics = varfont["hmtx"].metrics
  779. vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
  780. _instantiateGvarGlyph(
  781. glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
  782. )
  783. def instantiateGvar(varfont, axisLimits, optimize=True):
  784. log.info("Instantiating glyf/gvar tables")
  785. gvar = varfont["gvar"]
  786. glyf = varfont["glyf"]
  787. hMetrics = varfont["hmtx"].metrics
  788. vMetrics = getattr(varfont.get("vmtx"), "metrics", None)
  789. # Get list of glyph names sorted by component depth.
  790. # If a composite glyph is processed before its base glyph, the bounds may
  791. # be calculated incorrectly because deltas haven't been applied to the
  792. # base glyph yet.
  793. glyphnames = sorted(
  794. glyf.glyphOrder,
  795. key=lambda name: (
  796. (
  797. glyf[name].getCompositeMaxpValues(glyf).maxComponentDepth
  798. if glyf[name].isComposite()
  799. else 0
  800. ),
  801. name,
  802. ),
  803. )
  804. for glyphname in glyphnames:
  805. _instantiateGvarGlyph(
  806. glyphname, glyf, gvar, hMetrics, vMetrics, axisLimits, optimize=optimize
  807. )
  808. if not gvar.variations:
  809. del varfont["gvar"]
  810. def setCvarDeltas(cvt, deltas):
  811. for i, delta in enumerate(deltas):
  812. if delta:
  813. cvt[i] += otRound(delta)
  814. def instantiateCvar(varfont, axisLimits):
  815. log.info("Instantiating cvt/cvar tables")
  816. cvar = varfont["cvar"]
  817. defaultDeltas = instantiateTupleVariationStore(cvar.variations, axisLimits)
  818. if defaultDeltas:
  819. setCvarDeltas(varfont["cvt "], defaultDeltas)
  820. if not cvar.variations:
  821. del varfont["cvar"]
  822. def setMvarDeltas(varfont, deltas):
  823. mvar = varfont["MVAR"].table
  824. records = mvar.ValueRecord
  825. for rec in records:
  826. mvarTag = rec.ValueTag
  827. if mvarTag not in MVAR_ENTRIES:
  828. continue
  829. tableTag, itemName = MVAR_ENTRIES[mvarTag]
  830. delta = deltas[rec.VarIdx]
  831. if delta != 0:
  832. setattr(
  833. varfont[tableTag],
  834. itemName,
  835. getattr(varfont[tableTag], itemName) + otRound(delta),
  836. )
  837. @contextmanager
  838. def verticalMetricsKeptInSync(varfont):
  839. """Ensure hhea vertical metrics stay in sync with OS/2 ones after instancing.
  840. When applying MVAR deltas to the OS/2 table, if the ascender, descender and
  841. line gap change but they were the same as the respective hhea metrics in the
  842. original font, this context manager ensures that hhea metrcs also get updated
  843. accordingly.
  844. The MVAR spec only has tags for the OS/2 metrics, but it is common in fonts
  845. to have the hhea metrics be equal to those for compat reasons.
  846. https://learn.microsoft.com/en-us/typography/opentype/spec/mvar
  847. https://googlefonts.github.io/gf-guide/metrics.html#7-hhea-and-typo-metrics-should-be-equal
  848. https://github.com/fonttools/fonttools/issues/3297
  849. """
  850. current_os2_vmetrics = [
  851. getattr(varfont["OS/2"], attr)
  852. for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap")
  853. ]
  854. metrics_are_synced = current_os2_vmetrics == [
  855. getattr(varfont["hhea"], attr) for attr in ("ascender", "descender", "lineGap")
  856. ]
  857. yield metrics_are_synced
  858. if metrics_are_synced:
  859. new_os2_vmetrics = [
  860. getattr(varfont["OS/2"], attr)
  861. for attr in ("sTypoAscender", "sTypoDescender", "sTypoLineGap")
  862. ]
  863. if current_os2_vmetrics != new_os2_vmetrics:
  864. for attr, value in zip(
  865. ("ascender", "descender", "lineGap"), new_os2_vmetrics
  866. ):
  867. setattr(varfont["hhea"], attr, value)
  868. def instantiateMVAR(varfont, axisLimits):
  869. log.info("Instantiating MVAR table")
  870. mvar = varfont["MVAR"].table
  871. fvarAxes = varfont["fvar"].axes
  872. varStore = mvar.VarStore
  873. defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
  874. with verticalMetricsKeptInSync(varfont):
  875. setMvarDeltas(varfont, defaultDeltas)
  876. if varStore.VarRegionList.Region:
  877. varIndexMapping = varStore.optimize()
  878. for rec in mvar.ValueRecord:
  879. rec.VarIdx = varIndexMapping[rec.VarIdx]
  880. else:
  881. del varfont["MVAR"]
  882. def _remapVarIdxMap(table, attrName, varIndexMapping, glyphOrder):
  883. oldMapping = getattr(table, attrName).mapping
  884. newMapping = [varIndexMapping[oldMapping[glyphName]] for glyphName in glyphOrder]
  885. setattr(table, attrName, builder.buildVarIdxMap(newMapping, glyphOrder))
  886. # TODO(anthrotype) Add support for HVAR/VVAR in CFF2
  887. def _instantiateVHVAR(varfont, axisLimits, tableFields, *, round=round):
  888. location = axisLimits.pinnedLocation()
  889. tableTag = tableFields.tableTag
  890. fvarAxes = varfont["fvar"].axes
  891. log.info("Instantiating %s table", tableTag)
  892. vhvar = varfont[tableTag].table
  893. varStore = vhvar.VarStore
  894. if "glyf" in varfont:
  895. # Deltas from gvar table have already been applied to the hmtx/vmtx. For full
  896. # instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return
  897. if set(location).issuperset(axis.axisTag for axis in fvarAxes):
  898. log.info("Dropping %s table", tableTag)
  899. del varfont[tableTag]
  900. return
  901. defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
  902. if "glyf" not in varfont:
  903. # CFF2 fonts need hmtx/vmtx updated here. For glyf fonts, the instantiateGvar
  904. # function already updated the hmtx/vmtx from phantom points. Maybe remove
  905. # that and do it here for both CFF2 and glyf fonts?
  906. #
  907. # Specially, if a font has glyf but not gvar, the hmtx/vmtx will not have been
  908. # updated by instantiateGvar. Though one can call that a faulty font.
  909. metricsTag = "vmtx" if tableTag == "VVAR" else "hmtx"
  910. if metricsTag in varfont:
  911. advMapping = getattr(vhvar, tableFields.advMapping)
  912. metricsTable = varfont[metricsTag]
  913. metrics = metricsTable.metrics
  914. for glyphName, (advanceWidth, sb) in metrics.items():
  915. if advMapping:
  916. varIdx = advMapping.mapping[glyphName]
  917. else:
  918. varIdx = varfont.getGlyphID(glyphName)
  919. delta = round(defaultDeltas[varIdx])
  920. metrics[glyphName] = (max(0, advanceWidth + delta), sb)
  921. if (
  922. tableTag == "VVAR"
  923. and getattr(vhvar, tableFields.vOrigMapping) is not None
  924. ):
  925. log.warning(
  926. "VORG table not yet updated to reflect changes in VVAR table"
  927. )
  928. # For full instances (i.e. all axes pinned), we can simply drop HVAR/VVAR and return
  929. if set(location).issuperset(axis.axisTag for axis in fvarAxes):
  930. log.info("Dropping %s table", tableTag)
  931. del varfont[tableTag]
  932. return
  933. if varStore.VarRegionList.Region:
  934. # Only re-optimize VarStore if the HVAR/VVAR already uses indirect AdvWidthMap
  935. # or AdvHeightMap. If a direct, implicit glyphID->VariationIndex mapping is
  936. # used for advances, skip re-optimizing and maintain original VariationIndex.
  937. if getattr(vhvar, tableFields.advMapping):
  938. varIndexMapping = varStore.optimize(use_NO_VARIATION_INDEX=False)
  939. glyphOrder = varfont.getGlyphOrder()
  940. _remapVarIdxMap(vhvar, tableFields.advMapping, varIndexMapping, glyphOrder)
  941. if getattr(vhvar, tableFields.sb1): # left or top sidebearings
  942. _remapVarIdxMap(vhvar, tableFields.sb1, varIndexMapping, glyphOrder)
  943. if getattr(vhvar, tableFields.sb2): # right or bottom sidebearings
  944. _remapVarIdxMap(vhvar, tableFields.sb2, varIndexMapping, glyphOrder)
  945. if tableTag == "VVAR" and getattr(vhvar, tableFields.vOrigMapping):
  946. _remapVarIdxMap(
  947. vhvar, tableFields.vOrigMapping, varIndexMapping, glyphOrder
  948. )
  949. def instantiateHVAR(varfont, axisLimits):
  950. return _instantiateVHVAR(varfont, axisLimits, varLib.HVAR_FIELDS)
  951. def instantiateVVAR(varfont, axisLimits):
  952. return _instantiateVHVAR(varfont, axisLimits, varLib.VVAR_FIELDS)
  953. class _TupleVarStoreAdapter(object):
  954. def __init__(self, regions, axisOrder, tupleVarData, itemCounts):
  955. self.regions = regions
  956. self.axisOrder = axisOrder
  957. self.tupleVarData = tupleVarData
  958. self.itemCounts = itemCounts
  959. @classmethod
  960. def fromItemVarStore(cls, itemVarStore, fvarAxes):
  961. axisOrder = [axis.axisTag for axis in fvarAxes]
  962. regions = [
  963. region.get_support(fvarAxes) for region in itemVarStore.VarRegionList.Region
  964. ]
  965. tupleVarData = []
  966. itemCounts = []
  967. for varData in itemVarStore.VarData:
  968. variations = []
  969. varDataRegions = (regions[i] for i in varData.VarRegionIndex)
  970. for axes, coordinates in zip(varDataRegions, zip(*varData.Item)):
  971. variations.append(TupleVariation(axes, list(coordinates)))
  972. tupleVarData.append(variations)
  973. itemCounts.append(varData.ItemCount)
  974. return cls(regions, axisOrder, tupleVarData, itemCounts)
  975. def rebuildRegions(self):
  976. # Collect the set of all unique region axes from the current TupleVariations.
  977. # We use an OrderedDict to de-duplicate regions while keeping the order.
  978. uniqueRegions = collections.OrderedDict.fromkeys(
  979. (
  980. frozenset(var.axes.items())
  981. for variations in self.tupleVarData
  982. for var in variations
  983. )
  984. )
  985. # Maintain the original order for the regions that pre-existed, appending
  986. # the new regions at the end of the region list.
  987. newRegions = []
  988. for region in self.regions:
  989. regionAxes = frozenset(region.items())
  990. if regionAxes in uniqueRegions:
  991. newRegions.append(region)
  992. del uniqueRegions[regionAxes]
  993. if uniqueRegions:
  994. newRegions.extend(dict(region) for region in uniqueRegions)
  995. self.regions = newRegions
  996. def instantiate(self, axisLimits):
  997. defaultDeltaArray = []
  998. for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
  999. defaultDeltas = instantiateTupleVariationStore(variations, axisLimits)
  1000. if not defaultDeltas:
  1001. defaultDeltas = [0] * itemCount
  1002. defaultDeltaArray.append(defaultDeltas)
  1003. # rebuild regions whose axes were dropped or limited
  1004. self.rebuildRegions()
  1005. pinnedAxes = set(axisLimits.pinnedLocation())
  1006. self.axisOrder = [
  1007. axisTag for axisTag in self.axisOrder if axisTag not in pinnedAxes
  1008. ]
  1009. return defaultDeltaArray
  1010. def asItemVarStore(self):
  1011. regionOrder = [frozenset(axes.items()) for axes in self.regions]
  1012. varDatas = []
  1013. for variations, itemCount in zip(self.tupleVarData, self.itemCounts):
  1014. if variations:
  1015. assert len(variations[0].coordinates) == itemCount
  1016. varRegionIndices = [
  1017. regionOrder.index(frozenset(var.axes.items())) for var in variations
  1018. ]
  1019. varDataItems = list(zip(*(var.coordinates for var in variations)))
  1020. varDatas.append(
  1021. builder.buildVarData(varRegionIndices, varDataItems, optimize=False)
  1022. )
  1023. else:
  1024. varDatas.append(
  1025. builder.buildVarData([], [[] for _ in range(itemCount)])
  1026. )
  1027. regionList = builder.buildVarRegionList(self.regions, self.axisOrder)
  1028. itemVarStore = builder.buildVarStore(regionList, varDatas)
  1029. # remove unused regions from VarRegionList
  1030. itemVarStore.prune_regions()
  1031. return itemVarStore
  1032. def instantiateItemVariationStore(
  1033. itemVarStore, fvarAxes, axisLimits, hierarchical=False
  1034. ):
  1035. """Compute deltas at partial location, and update varStore in-place.
  1036. Remove regions in which all axes were instanced, or fall outside the new axis
  1037. limits. Scale the deltas of the remaining regions where only some of the axes
  1038. were instanced.
  1039. The number of VarData subtables, and the number of items within each, are
  1040. not modified, in order to keep the existing VariationIndex valid.
  1041. One may call VarStore.optimize() method after this to further optimize those.
  1042. Args:
  1043. varStore: An otTables.VarStore object (Item Variation Store)
  1044. fvarAxes: list of fvar's Axis objects
  1045. axisLimits: NormalizedAxisLimits: mapping axis tags to normalized
  1046. min/default/max axis coordinates. May not specify coordinates/ranges for
  1047. all the fvar axes.
  1048. Returns:
  1049. defaultDeltas: to be added to the default instance, of type dict of floats
  1050. keyed by VariationIndex compound values: i.e. (outer << 16) + inner.
  1051. """
  1052. tupleVarStore = _TupleVarStoreAdapter.fromItemVarStore(itemVarStore, fvarAxes)
  1053. defaultDeltaArray = tupleVarStore.instantiate(axisLimits)
  1054. newItemVarStore = tupleVarStore.asItemVarStore()
  1055. itemVarStore.VarRegionList = newItemVarStore.VarRegionList
  1056. if not hasattr(itemVarStore, "VarDataCount"): # Happens fromXML
  1057. itemVarStore.VarDataCount = len(newItemVarStore.VarData)
  1058. assert itemVarStore.VarDataCount == newItemVarStore.VarDataCount
  1059. itemVarStore.VarData = newItemVarStore.VarData
  1060. if not hierarchical:
  1061. defaultDeltas = {
  1062. ((major << 16) + minor): delta
  1063. for major, deltas in enumerate(defaultDeltaArray)
  1064. for minor, delta in enumerate(deltas)
  1065. }
  1066. defaultDeltas[itemVarStore.NO_VARIATION_INDEX] = 0
  1067. else:
  1068. defaultDeltas = {0xFFFF: {0xFFFF: 0}} # NO_VARIATION_INDEX
  1069. for major, deltas in enumerate(defaultDeltaArray):
  1070. defaultDeltasForMajor = defaultDeltas.setdefault(major, {})
  1071. for minor, delta in enumerate(deltas):
  1072. defaultDeltasForMajor[minor] = delta
  1073. return defaultDeltas
  1074. def instantiateOTL(varfont, axisLimits):
  1075. # TODO(anthrotype) Support partial instancing of JSTF and BASE tables
  1076. if (
  1077. "GDEF" not in varfont
  1078. or varfont["GDEF"].table.Version < 0x00010003
  1079. or not varfont["GDEF"].table.VarStore
  1080. ):
  1081. return
  1082. if "GPOS" in varfont:
  1083. msg = "Instantiating GDEF and GPOS tables"
  1084. else:
  1085. msg = "Instantiating GDEF table"
  1086. log.info(msg)
  1087. gdef = varfont["GDEF"].table
  1088. varStore = gdef.VarStore
  1089. fvarAxes = varfont["fvar"].axes
  1090. defaultDeltas = instantiateItemVariationStore(varStore, fvarAxes, axisLimits)
  1091. # When VF are built, big lookups may overflow and be broken into multiple
  1092. # subtables. MutatorMerger (which inherits from AligningMerger) reattaches
  1093. # them upon instancing, in case they can now fit a single subtable (if not,
  1094. # they will be split again upon compilation).
  1095. # This 'merger' also works as a 'visitor' that traverses the OTL tables and
  1096. # calls specific methods when instances of a given type are found.
  1097. # Specifically, it adds default deltas to GPOS Anchors/ValueRecords and GDEF
  1098. # LigatureCarets, and optionally deletes all VariationIndex tables if the
  1099. # VarStore is fully instanced.
  1100. merger = MutatorMerger(
  1101. varfont, defaultDeltas, deleteVariations=(not varStore.VarRegionList.Region)
  1102. )
  1103. merger.mergeTables(varfont, [varfont], ["GDEF", "GPOS"])
  1104. if varStore.VarRegionList.Region:
  1105. varIndexMapping = varStore.optimize()
  1106. gdef.remap_device_varidxes(varIndexMapping)
  1107. if "GPOS" in varfont:
  1108. varfont["GPOS"].table.remap_device_varidxes(varIndexMapping)
  1109. else:
  1110. # Downgrade GDEF.
  1111. del gdef.VarStore
  1112. gdef.Version = 0x00010002
  1113. if gdef.MarkGlyphSetsDef is None:
  1114. del gdef.MarkGlyphSetsDef
  1115. gdef.Version = 0x00010000
  1116. if not (
  1117. gdef.LigCaretList
  1118. or gdef.MarkAttachClassDef
  1119. or gdef.GlyphClassDef
  1120. or gdef.AttachList
  1121. or (gdef.Version >= 0x00010002 and gdef.MarkGlyphSetsDef)
  1122. ):
  1123. del varfont["GDEF"]
  1124. def _isValidAvarSegmentMap(axisTag, segmentMap):
  1125. if not segmentMap:
  1126. return True
  1127. if not {(-1.0, -1.0), (0, 0), (1.0, 1.0)}.issubset(segmentMap.items()):
  1128. log.warning(
  1129. f"Invalid avar SegmentMap record for axis '{axisTag}': does not "
  1130. "include all required value maps {-1.0: -1.0, 0: 0, 1.0: 1.0}"
  1131. )
  1132. return False
  1133. previousValue = None
  1134. for fromCoord, toCoord in sorted(segmentMap.items()):
  1135. if previousValue is not None and previousValue > toCoord:
  1136. log.warning(
  1137. f"Invalid avar AxisValueMap({fromCoord}, {toCoord}) record "
  1138. f"for axis '{axisTag}': the toCoordinate value must be >= to "
  1139. f"the toCoordinate value of the preceding record ({previousValue})."
  1140. )
  1141. return False
  1142. previousValue = toCoord
  1143. return True
  1144. def downgradeCFF2ToCFF(varfont):
  1145. # Save these properties
  1146. recalcTimestamp = varfont.recalcTimestamp
  1147. recalcBBoxes = varfont.recalcBBoxes
  1148. # Disable them
  1149. varfont.recalcTimestamp = False
  1150. varfont.recalcBBoxes = False
  1151. # Save to memory, reload, downgrade and save again, reload.
  1152. # We do this dance because the convertCFF2ToCFF changes glyph
  1153. # names, so following save would fail if any other table was
  1154. # loaded and referencing glyph names.
  1155. #
  1156. # The second save+load is unfortunate but also necessary.
  1157. stream = io.BytesIO()
  1158. log.info("Saving CFF2 font to memory for downgrade")
  1159. varfont.save(stream)
  1160. stream.seek(0)
  1161. varfont = TTFont(stream, recalcTimestamp=False, recalcBBoxes=False)
  1162. convertCFF2ToCFF(varfont)
  1163. stream = io.BytesIO()
  1164. log.info("Saving downgraded CFF font to memory")
  1165. varfont.save(stream)
  1166. stream.seek(0)
  1167. varfont = TTFont(stream, recalcTimestamp=False, recalcBBoxes=False)
  1168. # Uncomment, to see test all tables can be loaded. This fails without
  1169. # the extra save+load above.
  1170. """
  1171. for tag in varfont.keys():
  1172. print("Loading", tag)
  1173. varfont[tag]
  1174. """
  1175. # Restore them
  1176. varfont.recalcTimestamp = recalcTimestamp
  1177. varfont.recalcBBoxes = recalcBBoxes
  1178. return varfont
  1179. def instantiateAvar(varfont, axisLimits):
  1180. # 'axisLimits' dict must contain user-space (non-normalized) coordinates.
  1181. avar = varfont["avar"]
  1182. segments = avar.segments
  1183. # drop table if we instantiate all the axes
  1184. pinnedAxes = set(axisLimits.pinnedLocation())
  1185. if pinnedAxes.issuperset(segments):
  1186. log.info("Dropping avar table")
  1187. del varfont["avar"]
  1188. return
  1189. if getattr(avar, "majorVersion", 1) >= 2 and avar.table.VarStore:
  1190. raise NotImplementedError("avar table with VarStore is not supported")
  1191. log.info("Instantiating avar table")
  1192. for axis in pinnedAxes:
  1193. if axis in segments:
  1194. del segments[axis]
  1195. # First compute the default normalization for axisLimits coordinates: i.e.
  1196. # min = -1.0, default = 0, max = +1.0, and in between values interpolated linearly,
  1197. # without using the avar table's mappings.
  1198. # Then, for each SegmentMap, if we are restricting its axis, compute the new
  1199. # mappings by dividing the key/value pairs by the desired new min/max values,
  1200. # dropping any mappings that fall outside the restricted range.
  1201. # The keys ('fromCoord') are specified in default normalized coordinate space,
  1202. # whereas the values ('toCoord') are "mapped forward" using the SegmentMap.
  1203. normalizedRanges = axisLimits.normalize(varfont, usingAvar=False)
  1204. newSegments = {}
  1205. for axisTag, mapping in segments.items():
  1206. if not _isValidAvarSegmentMap(axisTag, mapping):
  1207. continue
  1208. if mapping and axisTag in normalizedRanges:
  1209. axisRange = normalizedRanges[axisTag]
  1210. mappedMin = floatToFixedToFloat(
  1211. piecewiseLinearMap(axisRange.minimum, mapping), 14
  1212. )
  1213. mappedDef = floatToFixedToFloat(
  1214. piecewiseLinearMap(axisRange.default, mapping), 14
  1215. )
  1216. mappedMax = floatToFixedToFloat(
  1217. piecewiseLinearMap(axisRange.maximum, mapping), 14
  1218. )
  1219. mappedAxisLimit = NormalizedAxisTripleAndDistances(
  1220. mappedMin,
  1221. mappedDef,
  1222. mappedMax,
  1223. axisRange.distanceNegative,
  1224. axisRange.distancePositive,
  1225. )
  1226. newMapping = {}
  1227. for fromCoord, toCoord in mapping.items():
  1228. if fromCoord < axisRange.minimum or fromCoord > axisRange.maximum:
  1229. continue
  1230. fromCoord = axisRange.renormalizeValue(fromCoord)
  1231. assert mappedMin <= toCoord <= mappedMax
  1232. toCoord = mappedAxisLimit.renormalizeValue(toCoord)
  1233. fromCoord = floatToFixedToFloat(fromCoord, 14)
  1234. toCoord = floatToFixedToFloat(toCoord, 14)
  1235. newMapping[fromCoord] = toCoord
  1236. newMapping.update({-1.0: -1.0, 0.0: 0.0, 1.0: 1.0})
  1237. newSegments[axisTag] = newMapping
  1238. else:
  1239. newSegments[axisTag] = mapping
  1240. avar.segments = newSegments
  1241. def isInstanceWithinAxisRanges(location, axisRanges):
  1242. for axisTag, coord in location.items():
  1243. if axisTag in axisRanges:
  1244. axisRange = axisRanges[axisTag]
  1245. if coord < axisRange.minimum or coord > axisRange.maximum:
  1246. return False
  1247. return True
  1248. def instantiateFvar(varfont, axisLimits):
  1249. # 'axisLimits' dict must contain user-space (non-normalized) coordinates
  1250. location = axisLimits.pinnedLocation()
  1251. fvar = varfont["fvar"]
  1252. # drop table if we instantiate all the axes
  1253. if set(location).issuperset(axis.axisTag for axis in fvar.axes):
  1254. log.info("Dropping fvar table")
  1255. del varfont["fvar"]
  1256. return
  1257. log.info("Instantiating fvar table")
  1258. axes = []
  1259. for axis in fvar.axes:
  1260. axisTag = axis.axisTag
  1261. if axisTag in location:
  1262. continue
  1263. if axisTag in axisLimits:
  1264. triple = axisLimits[axisTag]
  1265. if triple.default is None:
  1266. triple = (triple.minimum, axis.defaultValue, triple.maximum)
  1267. axis.minValue, axis.defaultValue, axis.maxValue = triple
  1268. axes.append(axis)
  1269. fvar.axes = axes
  1270. # only keep NamedInstances whose coordinates == pinned axis location
  1271. instances = []
  1272. for instance in fvar.instances:
  1273. if any(instance.coordinates[axis] != value for axis, value in location.items()):
  1274. continue
  1275. for axisTag in location:
  1276. del instance.coordinates[axisTag]
  1277. if not isInstanceWithinAxisRanges(instance.coordinates, axisLimits):
  1278. continue
  1279. instances.append(instance)
  1280. fvar.instances = instances
  1281. def instantiateSTAT(varfont, axisLimits):
  1282. # 'axisLimits' dict must contain user-space (non-normalized) coordinates
  1283. stat = varfont["STAT"].table
  1284. if not stat.DesignAxisRecord or not (
  1285. stat.AxisValueArray and stat.AxisValueArray.AxisValue
  1286. ):
  1287. return # STAT table empty, nothing to do
  1288. log.info("Instantiating STAT table")
  1289. newAxisValueTables = axisValuesFromAxisLimits(stat, axisLimits)
  1290. stat.AxisValueCount = len(newAxisValueTables)
  1291. if stat.AxisValueCount:
  1292. stat.AxisValueArray.AxisValue = newAxisValueTables
  1293. else:
  1294. stat.AxisValueArray = None
  1295. def axisValuesFromAxisLimits(stat, axisLimits):
  1296. def isAxisValueOutsideLimits(axisTag, axisValue):
  1297. if axisTag in axisLimits:
  1298. triple = axisLimits[axisTag]
  1299. if axisValue < triple.minimum or axisValue > triple.maximum:
  1300. return True
  1301. return False
  1302. # only keep AxisValues whose axis is not pinned nor restricted, or is pinned at the
  1303. # exact (nominal) value, or is restricted but the value is within the new range
  1304. designAxes = stat.DesignAxisRecord.Axis
  1305. newAxisValueTables = []
  1306. for axisValueTable in stat.AxisValueArray.AxisValue:
  1307. axisValueFormat = axisValueTable.Format
  1308. if axisValueFormat in (1, 2, 3):
  1309. axisTag = designAxes[axisValueTable.AxisIndex].AxisTag
  1310. if axisValueFormat == 2:
  1311. axisValue = axisValueTable.NominalValue
  1312. else:
  1313. axisValue = axisValueTable.Value
  1314. if isAxisValueOutsideLimits(axisTag, axisValue):
  1315. continue
  1316. elif axisValueFormat == 4:
  1317. # drop 'non-analytic' AxisValue if _any_ AxisValueRecord doesn't match
  1318. # the pinned location or is outside range
  1319. dropAxisValueTable = False
  1320. for rec in axisValueTable.AxisValueRecord:
  1321. axisTag = designAxes[rec.AxisIndex].AxisTag
  1322. axisValue = rec.Value
  1323. if isAxisValueOutsideLimits(axisTag, axisValue):
  1324. dropAxisValueTable = True
  1325. break
  1326. if dropAxisValueTable:
  1327. continue
  1328. else:
  1329. log.warning("Unknown AxisValue table format (%s); ignored", axisValueFormat)
  1330. newAxisValueTables.append(axisValueTable)
  1331. return newAxisValueTables
  1332. def setMacOverlapFlags(glyfTable):
  1333. flagOverlapCompound = _g_l_y_f.OVERLAP_COMPOUND
  1334. flagOverlapSimple = _g_l_y_f.flagOverlapSimple
  1335. for glyphName in glyfTable.keys():
  1336. glyph = glyfTable[glyphName]
  1337. # Set OVERLAP_COMPOUND bit for compound glyphs
  1338. if glyph.isComposite():
  1339. glyph.components[0].flags |= flagOverlapCompound
  1340. # Set OVERLAP_SIMPLE bit for simple glyphs
  1341. elif glyph.numberOfContours > 0:
  1342. glyph.flags[0] |= flagOverlapSimple
  1343. def normalize(value, triple, avarMapping):
  1344. value = normalizeValue(value, triple)
  1345. if avarMapping:
  1346. value = piecewiseLinearMap(value, avarMapping)
  1347. # Quantize to F2Dot14, to avoid surprise interpolations.
  1348. return floatToFixedToFloat(value, 14)
  1349. def sanityCheckVariableTables(varfont):
  1350. if "fvar" not in varfont:
  1351. raise ValueError("Missing required table fvar")
  1352. if "gvar" in varfont:
  1353. if "glyf" not in varfont:
  1354. raise ValueError("Can't have gvar without glyf")
  1355. def instantiateVariableFont(
  1356. varfont,
  1357. axisLimits,
  1358. inplace=False,
  1359. optimize=True,
  1360. overlap=OverlapMode.KEEP_AND_SET_FLAGS,
  1361. updateFontNames=False,
  1362. *,
  1363. downgradeCFF2=False,
  1364. static=False,
  1365. ):
  1366. """Instantiate variable font, either fully or partially.
  1367. Depending on whether the `axisLimits` dictionary references all or some of the
  1368. input varfont's axes, the output font will either be a full instance (static
  1369. font) or a variable font with possibly less variation data.
  1370. Args:
  1371. varfont: a TTFont instance, which must contain at least an 'fvar' table.
  1372. axisLimits: a dict keyed by axis tags (str) containing the coordinates (float)
  1373. along one or more axes where the desired instance will be located.
  1374. If the value is `None`, the default coordinate as per 'fvar' table for
  1375. that axis is used.
  1376. The limit values can also be (min, max) tuples for restricting an
  1377. axis's variation range. The default axis value must be included in
  1378. the new range.
  1379. inplace (bool): whether to modify input TTFont object in-place instead of
  1380. returning a distinct object.
  1381. optimize (bool): if False, do not perform IUP-delta optimization on the
  1382. remaining 'gvar' table's deltas. Possibly faster, and might work around
  1383. rendering issues in some buggy environments, at the cost of a slightly
  1384. larger file size.
  1385. overlap (OverlapMode): variable fonts usually contain overlapping contours, and
  1386. some font rendering engines on Apple platforms require that the
  1387. `OVERLAP_SIMPLE` and `OVERLAP_COMPOUND` flags in the 'glyf' table be set to
  1388. force rendering using a non-zero fill rule. Thus we always set these flags
  1389. on all glyphs to maximise cross-compatibility of the generated instance.
  1390. You can disable this by passing OverlapMode.KEEP_AND_DONT_SET_FLAGS.
  1391. If you want to remove the overlaps altogether and merge overlapping
  1392. contours and components, you can pass OverlapMode.REMOVE (or
  1393. REMOVE_AND_IGNORE_ERRORS to not hard-fail on tricky glyphs). Note that this
  1394. requires the skia-pathops package (available to pip install).
  1395. The overlap parameter only has effect when generating full static instances.
  1396. updateFontNames (bool): if True, update the instantiated font's name table using
  1397. the Axis Value Tables from the STAT table. The name table and the style bits
  1398. in the head and OS/2 table will be updated so they conform to the R/I/B/BI
  1399. model. If the STAT table is missing or an Axis Value table is missing for
  1400. a given axis coordinate, a ValueError will be raised.
  1401. downgradeCFF2 (bool): if True, downgrade the CFF2 table to CFF table when possible
  1402. ie. full instancing of all axes. This is useful for compatibility with older
  1403. software that does not support CFF2. Defaults to False. Note that this
  1404. operation also removes overlaps within glyph shapes, as CFF does not support
  1405. overlaps but CFF2 does.
  1406. static (bool): if True, generate a full instance (static font) instead of a partial
  1407. instance (variable font).
  1408. """
  1409. # 'overlap' used to be bool and is now enum; for backward compat keep accepting bool
  1410. overlap = OverlapMode(int(overlap))
  1411. sanityCheckVariableTables(varfont)
  1412. if static:
  1413. unspecified = []
  1414. for axis in varfont["fvar"].axes:
  1415. if axis.axisTag not in axisLimits:
  1416. axisLimits[axis.axisTag] = None
  1417. unspecified.append(axis.axisTag)
  1418. if unspecified:
  1419. log.info("Pinning unspecified axes to default: %s", unspecified)
  1420. axisLimits = AxisLimits(axisLimits).limitAxesAndPopulateDefaults(varfont)
  1421. log.info("Restricted limits: %s", axisLimits)
  1422. normalizedLimits = axisLimits.normalize(varfont)
  1423. log.info("Normalized limits: %s", normalizedLimits)
  1424. if not inplace:
  1425. varfont = deepcopy(varfont)
  1426. if "DSIG" in varfont:
  1427. del varfont["DSIG"]
  1428. if updateFontNames:
  1429. log.info("Updating name table")
  1430. names.updateNameTable(varfont, axisLimits)
  1431. if "VARC" in varfont:
  1432. instantiateVARC(varfont, normalizedLimits)
  1433. if "CFF2" in varfont:
  1434. downgradeCFF2 = instantiateCFF2(
  1435. varfont, normalizedLimits, downgrade=downgradeCFF2
  1436. )
  1437. if "gvar" in varfont:
  1438. instantiateGvar(varfont, normalizedLimits, optimize=optimize)
  1439. if "cvar" in varfont:
  1440. instantiateCvar(varfont, normalizedLimits)
  1441. if "MVAR" in varfont:
  1442. instantiateMVAR(varfont, normalizedLimits)
  1443. if "HVAR" in varfont:
  1444. instantiateHVAR(varfont, normalizedLimits)
  1445. if "VVAR" in varfont:
  1446. instantiateVVAR(varfont, normalizedLimits)
  1447. instantiateOTL(varfont, normalizedLimits)
  1448. instantiateFeatureVariations(varfont, normalizedLimits)
  1449. if "avar" in varfont:
  1450. instantiateAvar(varfont, axisLimits)
  1451. with names.pruningUnusedNames(varfont):
  1452. if "STAT" in varfont:
  1453. instantiateSTAT(varfont, axisLimits)
  1454. instantiateFvar(varfont, axisLimits)
  1455. if "OS/2" in varfont:
  1456. varfont["OS/2"].recalcAvgCharWidth(varfont)
  1457. varLib.set_default_weight_width_slant(
  1458. varfont, location=axisLimits.defaultLocation()
  1459. )
  1460. if updateFontNames:
  1461. # Set Regular/Italic/Bold/Bold Italic bits as appropriate, after the
  1462. # name table has been updated.
  1463. setRibbiBits(varfont)
  1464. if downgradeCFF2:
  1465. origVarfont = varfont
  1466. varfont = downgradeCFF2ToCFF(varfont)
  1467. if inplace:
  1468. origVarfont.__dict__ = varfont.__dict__.copy()
  1469. if "fvar" not in varfont:
  1470. if overlap == OverlapMode.KEEP_AND_SET_FLAGS:
  1471. if "glyf" in varfont:
  1472. setMacOverlapFlags(varfont["glyf"])
  1473. elif overlap in (OverlapMode.REMOVE, OverlapMode.REMOVE_AND_IGNORE_ERRORS):
  1474. from fontTools.ttLib.removeOverlaps import removeOverlaps
  1475. log.info("Removing glyph outlines overlaps")
  1476. removeOverlaps(
  1477. varfont,
  1478. ignoreErrors=(overlap == OverlapMode.REMOVE_AND_IGNORE_ERRORS),
  1479. )
  1480. return varfont
  1481. def setRibbiBits(font):
  1482. """Set the `head.macStyle` and `OS/2.fsSelection` style bits
  1483. appropriately."""
  1484. english_ribbi_style = font["name"].getName(names.NameID.SUBFAMILY_NAME, 3, 1, 0x409)
  1485. if english_ribbi_style is None:
  1486. return
  1487. styleMapStyleName = english_ribbi_style.toStr().lower()
  1488. if styleMapStyleName not in {"regular", "bold", "italic", "bold italic"}:
  1489. return
  1490. if styleMapStyleName == "bold":
  1491. font["head"].macStyle = 0b01
  1492. elif styleMapStyleName == "bold italic":
  1493. font["head"].macStyle = 0b11
  1494. elif styleMapStyleName == "italic":
  1495. font["head"].macStyle = 0b10
  1496. selection = font["OS/2"].fsSelection
  1497. # First clear...
  1498. selection &= ~(1 << 0)
  1499. selection &= ~(1 << 5)
  1500. selection &= ~(1 << 6)
  1501. # ...then re-set the bits.
  1502. if styleMapStyleName == "regular":
  1503. selection |= 1 << 6
  1504. elif styleMapStyleName == "bold":
  1505. selection |= 1 << 5
  1506. elif styleMapStyleName == "italic":
  1507. selection |= 1 << 0
  1508. elif styleMapStyleName == "bold italic":
  1509. selection |= 1 << 0
  1510. selection |= 1 << 5
  1511. font["OS/2"].fsSelection = selection
  1512. def parseLimits(limits: Iterable[str]) -> Dict[str, Optional[AxisTriple]]:
  1513. result = {}
  1514. for limitString in limits:
  1515. match = re.match(
  1516. r"^(\w{1,4})=(?:(drop)|(?:([^:]*)(?:[:]([^:]*))?(?:[:]([^:]*))?))$",
  1517. limitString,
  1518. )
  1519. if not match:
  1520. raise ValueError("invalid location format: %r" % limitString)
  1521. tag = match.group(1).ljust(4)
  1522. if match.group(2): # 'drop'
  1523. result[tag] = None
  1524. continue
  1525. triple = match.group(3, 4, 5)
  1526. if triple[1] is None: # "value" syntax
  1527. triple = (triple[0], triple[0], triple[0])
  1528. elif triple[2] is None: # "min:max" syntax
  1529. triple = (triple[0], None, triple[1])
  1530. triple = tuple(float(v) if v else None for v in triple)
  1531. result[tag] = AxisTriple(*triple)
  1532. return result
  1533. def parseArgs(args):
  1534. """Parse argv.
  1535. Returns:
  1536. 3-tuple (infile, axisLimits, options)
  1537. axisLimits is either a Dict[str, Optional[float]], for pinning variation axes
  1538. to specific coordinates along those axes (with `None` as a placeholder for an
  1539. axis' default value); or a Dict[str, Tuple(float, float)], meaning limit this
  1540. axis to min/max range.
  1541. Axes locations are in user-space coordinates, as defined in the "fvar" table.
  1542. """
  1543. from fontTools import configLogger
  1544. import argparse
  1545. parser = argparse.ArgumentParser(
  1546. "fonttools varLib.instancer",
  1547. description="Partially instantiate a variable font",
  1548. )
  1549. parser.add_argument("input", metavar="INPUT.ttf", help="Input variable TTF file.")
  1550. parser.add_argument(
  1551. "locargs",
  1552. metavar="AXIS=LOC",
  1553. nargs="*",
  1554. help="List of space separated locations. A location consists of "
  1555. "the tag of a variation axis, followed by '=' and the literal, "
  1556. "string 'drop', or colon-separated list of one to three values, "
  1557. "each of which is the empty string, or a number. "
  1558. "E.g.: wdth=100 or wght=75.0:125.0 or wght=100:400:700 or wght=:500: "
  1559. "or wght=drop",
  1560. )
  1561. parser.add_argument(
  1562. "-o",
  1563. "--output",
  1564. metavar="OUTPUT.ttf",
  1565. default=None,
  1566. help="Output instance TTF file (default: INPUT-instance.ttf).",
  1567. )
  1568. parser.add_argument(
  1569. "--static",
  1570. dest="static",
  1571. action="store_true",
  1572. help="Make a static font: pin unspecified axes to their default location.",
  1573. )
  1574. parser.add_argument(
  1575. "--no-optimize",
  1576. dest="optimize",
  1577. action="store_false",
  1578. help="Don't perform IUP optimization on the remaining gvar TupleVariations",
  1579. )
  1580. parser.add_argument(
  1581. "--no-overlap-flag",
  1582. dest="overlap",
  1583. action="store_false",
  1584. help="Don't set OVERLAP_SIMPLE/OVERLAP_COMPOUND glyf flags (only applicable "
  1585. "when generating a full instance)",
  1586. )
  1587. parser.add_argument(
  1588. "--remove-overlaps",
  1589. dest="remove_overlaps",
  1590. action="store_true",
  1591. help="Merge overlapping contours and components (only applicable "
  1592. "when generating a full instance). Requires skia-pathops",
  1593. )
  1594. parser.add_argument(
  1595. "--ignore-overlap-errors",
  1596. dest="ignore_overlap_errors",
  1597. action="store_true",
  1598. help="Don't crash if the remove-overlaps operation fails for some glyphs.",
  1599. )
  1600. parser.add_argument(
  1601. "--update-name-table",
  1602. action="store_true",
  1603. help="Update the instantiated font's `name` table. Input font must have "
  1604. "a STAT table with Axis Value Tables",
  1605. )
  1606. parser.add_argument(
  1607. "--downgrade-cff2",
  1608. action="store_true",
  1609. help="If all axes are pinned, downgrade CFF2 to CFF table format",
  1610. )
  1611. parser.add_argument(
  1612. "--no-recalc-timestamp",
  1613. dest="recalc_timestamp",
  1614. action="store_false",
  1615. help="Don't set the output font's timestamp to the current time.",
  1616. )
  1617. parser.add_argument(
  1618. "--no-recalc-bounds",
  1619. dest="recalc_bounds",
  1620. action="store_false",
  1621. help="Don't recalculate font bounding boxes",
  1622. )
  1623. loggingGroup = parser.add_mutually_exclusive_group(required=False)
  1624. loggingGroup.add_argument(
  1625. "-v", "--verbose", action="store_true", help="Run more verbosely."
  1626. )
  1627. loggingGroup.add_argument(
  1628. "-q", "--quiet", action="store_true", help="Turn verbosity off."
  1629. )
  1630. options = parser.parse_args(args)
  1631. if options.remove_overlaps:
  1632. if options.ignore_overlap_errors:
  1633. options.overlap = OverlapMode.REMOVE_AND_IGNORE_ERRORS
  1634. else:
  1635. options.overlap = OverlapMode.REMOVE
  1636. else:
  1637. options.overlap = OverlapMode(int(options.overlap))
  1638. infile = options.input
  1639. if not os.path.isfile(infile):
  1640. parser.error("No such file '{}'".format(infile))
  1641. configLogger(
  1642. level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
  1643. )
  1644. try:
  1645. axisLimits = parseLimits(options.locargs)
  1646. except ValueError as e:
  1647. parser.error(str(e))
  1648. if len(axisLimits) != len(options.locargs):
  1649. parser.error("Specified multiple limits for the same axis")
  1650. return (infile, axisLimits, options)
  1651. def main(args=None):
  1652. """Partially instantiate a variable font"""
  1653. infile, axisLimits, options = parseArgs(args)
  1654. log.info("Restricting axes: %s", axisLimits)
  1655. log.info("Loading variable font")
  1656. varfont = TTFont(
  1657. infile,
  1658. recalcTimestamp=options.recalc_timestamp,
  1659. recalcBBoxes=options.recalc_bounds,
  1660. )
  1661. isFullInstance = options.static or {
  1662. axisTag
  1663. for axisTag, limit in axisLimits.items()
  1664. if limit is None or limit[0] == limit[2]
  1665. }.issuperset(axis.axisTag for axis in varfont["fvar"].axes)
  1666. varfont = instantiateVariableFont(
  1667. varfont,
  1668. axisLimits,
  1669. inplace=True,
  1670. optimize=options.optimize,
  1671. overlap=options.overlap,
  1672. updateFontNames=options.update_name_table,
  1673. downgradeCFF2=options.downgrade_cff2,
  1674. static=options.static,
  1675. )
  1676. suffix = "-instance" if isFullInstance else "-partial"
  1677. outfile = (
  1678. makeOutputFileName(infile, overWrite=True, suffix=suffix)
  1679. if not options.output
  1680. else options.output
  1681. )
  1682. log.info(
  1683. "Saving %s font %s",
  1684. "instance" if isFullInstance else "partial variable",
  1685. outfile,
  1686. )
  1687. varfont.save(outfile)