__init__.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  1. """
  2. Module for dealing with 'gvar'-style font variations, also known as run-time
  3. interpolation.
  4. The ideas here are very similar to MutatorMath. There is even code to read
  5. MutatorMath .designspace files in the varLib.designspace module.
  6. For now, if you run this file on a designspace file, it tries to find
  7. ttf-interpolatable files for the masters and build a variable-font from
  8. them. Such ttf-interpolatable and designspace files can be generated from
  9. a Glyphs source, eg., using noto-source as an example:
  10. .. code-block:: sh
  11. $ fontmake -o ttf-interpolatable -g NotoSansArabic-MM.glyphs
  12. Then you can make a variable-font this way:
  13. .. code-block:: sh
  14. $ fonttools varLib master_ufo/NotoSansArabic.designspace
  15. API *will* change in near future.
  16. """
  17. from typing import List
  18. from fontTools.misc.vector import Vector
  19. from fontTools.misc.roundTools import noRound, otRound
  20. from fontTools.misc.fixedTools import floatToFixed as fl2fi
  21. from fontTools.misc.textTools import Tag, tostr
  22. from fontTools.ttLib import TTFont, newTable
  23. from fontTools.ttLib.tables._f_v_a_r import Axis, NamedInstance
  24. from fontTools.ttLib.tables._g_l_y_f import GlyphCoordinates, dropImpliedOnCurvePoints
  25. from fontTools.ttLib.tables.ttProgram import Program
  26. from fontTools.ttLib.tables.TupleVariation import TupleVariation
  27. from fontTools.ttLib.tables import otTables as ot
  28. from fontTools.ttLib.tables.otBase import OTTableWriter
  29. from fontTools.varLib import builder, models, varStore
  30. from fontTools.varLib.merger import VariationMerger, COLRVariationMerger
  31. from fontTools.varLib.mvar import MVAR_ENTRIES
  32. from fontTools.varLib.iup import iup_delta_optimize
  33. from fontTools.varLib.featureVars import addFeatureVariations
  34. from fontTools.designspaceLib import DesignSpaceDocument, InstanceDescriptor
  35. from fontTools.designspaceLib.split import splitInterpolable, splitVariableFonts
  36. from fontTools.varLib.stat import buildVFStatTable
  37. from fontTools.colorLib.builder import buildColrV1
  38. from fontTools.colorLib.unbuilder import unbuildColrV1
  39. from functools import partial
  40. from collections import OrderedDict, defaultdict, namedtuple
  41. import os.path
  42. import logging
  43. from copy import deepcopy
  44. from pprint import pformat
  45. from re import fullmatch
  46. from .errors import VarLibError, VarLibValidationError
  47. log = logging.getLogger("fontTools.varLib")
  48. # This is a lib key for the designspace document. The value should be
  49. # a comma-separated list of OpenType feature tag(s), to be used as the
  50. # FeatureVariations feature.
  51. # If present, the DesignSpace <rules processing="..."> flag is ignored.
  52. FEAVAR_FEATURETAG_LIB_KEY = "com.github.fonttools.varLib.featureVarsFeatureTag"
  53. #
  54. # Creation routines
  55. #
  56. def _add_fvar(font, axes, instances: List[InstanceDescriptor]):
  57. """
  58. Add 'fvar' table to font.
  59. axes is an ordered dictionary of DesignspaceAxis objects.
  60. instances is list of dictionary objects with 'location', 'stylename',
  61. and possibly 'postscriptfontname' entries.
  62. """
  63. assert axes
  64. assert isinstance(axes, OrderedDict)
  65. log.info("Generating fvar")
  66. fvar = newTable("fvar")
  67. nameTable = font["name"]
  68. for a in axes.values():
  69. axis = Axis()
  70. axis.axisTag = Tag(a.tag)
  71. # TODO Skip axes that have no variation.
  72. axis.minValue, axis.defaultValue, axis.maxValue = (
  73. a.minimum,
  74. a.default,
  75. a.maximum,
  76. )
  77. axis.axisNameID = nameTable.addMultilingualName(
  78. a.labelNames, font, minNameID=256
  79. )
  80. axis.flags = int(a.hidden)
  81. fvar.axes.append(axis)
  82. for instance in instances:
  83. # Filter out discrete axis locations
  84. coordinates = {
  85. name: value for name, value in instance.location.items() if name in axes
  86. }
  87. if "en" not in instance.localisedStyleName:
  88. if not instance.styleName:
  89. raise VarLibValidationError(
  90. f"Instance at location '{coordinates}' must have a default English "
  91. "style name ('stylename' attribute on the instance element or a "
  92. "stylename element with an 'xml:lang=\"en\"' attribute)."
  93. )
  94. localisedStyleName = dict(instance.localisedStyleName)
  95. localisedStyleName["en"] = tostr(instance.styleName)
  96. else:
  97. localisedStyleName = instance.localisedStyleName
  98. psname = instance.postScriptFontName
  99. inst = NamedInstance()
  100. inst.subfamilyNameID = nameTable.addMultilingualName(localisedStyleName)
  101. if psname is not None:
  102. psname = tostr(psname)
  103. inst.postscriptNameID = nameTable.addName(psname)
  104. inst.coordinates = {
  105. axes[k].tag: axes[k].map_backward(v) for k, v in coordinates.items()
  106. }
  107. # inst.coordinates = {axes[k].tag:v for k,v in coordinates.items()}
  108. fvar.instances.append(inst)
  109. assert "fvar" not in font
  110. font["fvar"] = fvar
  111. return fvar
  112. def _add_avar(font, axes, mappings, axisTags):
  113. """
  114. Add 'avar' table to font.
  115. axes is an ordered dictionary of AxisDescriptor objects.
  116. """
  117. assert axes
  118. assert isinstance(axes, OrderedDict)
  119. log.info("Generating avar")
  120. avar = newTable("avar")
  121. interesting = False
  122. vals_triples = {}
  123. for axis in axes.values():
  124. # Currently, some rasterizers require that the default value maps
  125. # (-1 to -1, 0 to 0, and 1 to 1) be present for all the segment
  126. # maps, even when the default normalization mapping for the axis
  127. # was not modified.
  128. # https://github.com/googlei18n/fontmake/issues/295
  129. # https://github.com/fonttools/fonttools/issues/1011
  130. # TODO(anthrotype) revert this (and 19c4b37) when issue is fixed
  131. curve = avar.segments[axis.tag] = {-1.0: -1.0, 0.0: 0.0, 1.0: 1.0}
  132. keys_triple = (axis.minimum, axis.default, axis.maximum)
  133. vals_triple = tuple(axis.map_forward(v) for v in keys_triple)
  134. vals_triples[axis.tag] = vals_triple
  135. if not axis.map:
  136. continue
  137. items = sorted(axis.map)
  138. keys = [item[0] for item in items]
  139. vals = [item[1] for item in items]
  140. # Current avar requirements. We don't have to enforce
  141. # these on the designer and can deduce some ourselves,
  142. # but for now just enforce them.
  143. if axis.minimum != min(keys):
  144. raise VarLibValidationError(
  145. f"Axis '{axis.name}': there must be a mapping for the axis minimum "
  146. f"value {axis.minimum} and it must be the lowest input mapping value."
  147. )
  148. if axis.maximum != max(keys):
  149. raise VarLibValidationError(
  150. f"Axis '{axis.name}': there must be a mapping for the axis maximum "
  151. f"value {axis.maximum} and it must be the highest input mapping value."
  152. )
  153. if axis.default not in keys:
  154. raise VarLibValidationError(
  155. f"Axis '{axis.name}': there must be a mapping for the axis default "
  156. f"value {axis.default}."
  157. )
  158. # No duplicate input values (output values can be >= their preceeding value).
  159. if len(set(keys)) != len(keys):
  160. raise VarLibValidationError(
  161. f"Axis '{axis.name}': All axis mapping input='...' values must be "
  162. "unique, but we found duplicates."
  163. )
  164. # Ascending values
  165. if sorted(vals) != vals:
  166. raise VarLibValidationError(
  167. f"Axis '{axis.name}': mapping output values must be in ascending order."
  168. )
  169. keys = [models.normalizeValue(v, keys_triple) for v in keys]
  170. vals = [models.normalizeValue(v, vals_triple) for v in vals]
  171. if all(k == v for k, v in zip(keys, vals)):
  172. continue
  173. interesting = True
  174. curve.update(zip(keys, vals))
  175. assert 0.0 in curve and curve[0.0] == 0.0
  176. assert -1.0 not in curve or curve[-1.0] == -1.0
  177. assert +1.0 not in curve or curve[+1.0] == +1.0
  178. # curve.update({-1.0: -1.0, 0.0: 0.0, 1.0: 1.0})
  179. if mappings:
  180. interesting = True
  181. inputLocations = [
  182. {
  183. axes[name].tag: models.normalizeValue(v, vals_triples[axes[name].tag])
  184. for name, v in mapping.inputLocation.items()
  185. }
  186. for mapping in mappings
  187. ]
  188. outputLocations = [
  189. {
  190. axes[name].tag: models.normalizeValue(v, vals_triples[axes[name].tag])
  191. for name, v in mapping.outputLocation.items()
  192. }
  193. for mapping in mappings
  194. ]
  195. assert len(inputLocations) == len(outputLocations)
  196. # If base-master is missing, insert it at zero location.
  197. if not any(all(v == 0 for k, v in loc.items()) for loc in inputLocations):
  198. inputLocations.insert(0, {})
  199. outputLocations.insert(0, {})
  200. model = models.VariationModel(inputLocations, axisTags)
  201. storeBuilder = varStore.OnlineVarStoreBuilder(axisTags)
  202. storeBuilder.setModel(model)
  203. varIdxes = {}
  204. for tag in axisTags:
  205. masterValues = []
  206. for vo, vi in zip(outputLocations, inputLocations):
  207. if tag not in vo:
  208. masterValues.append(0)
  209. continue
  210. v = vo[tag] - vi.get(tag, 0)
  211. masterValues.append(fl2fi(v, 14))
  212. varIdxes[tag] = storeBuilder.storeMasters(masterValues)[1]
  213. store = storeBuilder.finish()
  214. optimized = store.optimize()
  215. varIdxes = {axis: optimized[value] for axis, value in varIdxes.items()}
  216. varIdxMap = builder.buildDeltaSetIndexMap(varIdxes[t] for t in axisTags)
  217. avar.majorVersion = 2
  218. avar.table = ot.avar()
  219. avar.table.VarIdxMap = varIdxMap
  220. avar.table.VarStore = store
  221. assert "avar" not in font
  222. if not interesting:
  223. log.info("No need for avar")
  224. avar = None
  225. else:
  226. font["avar"] = avar
  227. return avar
  228. def _add_stat(font):
  229. # Note: this function only gets called by old code that calls `build()`
  230. # directly. Newer code that wants to benefit from STAT data from the
  231. # designspace should call `build_many()`
  232. if "STAT" in font:
  233. return
  234. from ..otlLib.builder import buildStatTable
  235. fvarTable = font["fvar"]
  236. axes = [dict(tag=a.axisTag, name=a.axisNameID) for a in fvarTable.axes]
  237. buildStatTable(font, axes)
  238. _MasterData = namedtuple("_MasterData", ["glyf", "hMetrics", "vMetrics"])
  239. def _add_gvar(font, masterModel, master_ttfs, tolerance=0.5, optimize=True):
  240. if tolerance < 0:
  241. raise ValueError("`tolerance` must be a positive number.")
  242. log.info("Generating gvar")
  243. assert "gvar" not in font
  244. gvar = font["gvar"] = newTable("gvar")
  245. glyf = font["glyf"]
  246. defaultMasterIndex = masterModel.reverseMapping[0]
  247. master_datas = [
  248. _MasterData(
  249. m["glyf"], m["hmtx"].metrics, getattr(m.get("vmtx"), "metrics", None)
  250. )
  251. for m in master_ttfs
  252. ]
  253. for glyph in font.getGlyphOrder():
  254. log.debug("building gvar for glyph '%s'", glyph)
  255. isComposite = glyf[glyph].isComposite()
  256. allData = [
  257. m.glyf._getCoordinatesAndControls(glyph, m.hMetrics, m.vMetrics)
  258. for m in master_datas
  259. ]
  260. if allData[defaultMasterIndex][1].numberOfContours != 0:
  261. # If the default master is not empty, interpret empty non-default masters
  262. # as missing glyphs from a sparse master
  263. allData = [
  264. d if d is not None and d[1].numberOfContours != 0 else None
  265. for d in allData
  266. ]
  267. model, allData = masterModel.getSubModel(allData)
  268. allCoords = [d[0] for d in allData]
  269. allControls = [d[1] for d in allData]
  270. control = allControls[0]
  271. if not models.allEqual(allControls):
  272. log.warning("glyph %s has incompatible masters; skipping" % glyph)
  273. continue
  274. del allControls
  275. # Update gvar
  276. gvar.variations[glyph] = []
  277. deltas = model.getDeltas(
  278. allCoords, round=partial(GlyphCoordinates.__round__, round=round)
  279. )
  280. supports = model.supports
  281. assert len(deltas) == len(supports)
  282. # Prepare for IUP optimization
  283. origCoords = deltas[0]
  284. endPts = control.endPts
  285. for i, (delta, support) in enumerate(zip(deltas[1:], supports[1:])):
  286. if all(v == 0 for v in delta.array) and not isComposite:
  287. continue
  288. var = TupleVariation(support, delta)
  289. if optimize:
  290. delta_opt = iup_delta_optimize(
  291. delta, origCoords, endPts, tolerance=tolerance
  292. )
  293. if None in delta_opt:
  294. """In composite glyphs, there should be one 0 entry
  295. to make sure the gvar entry is written to the font.
  296. This is to work around an issue with macOS 10.14 and can be
  297. removed once the behaviour of macOS is changed.
  298. https://github.com/fonttools/fonttools/issues/1381
  299. """
  300. if all(d is None for d in delta_opt):
  301. delta_opt = [(0, 0)] + [None] * (len(delta_opt) - 1)
  302. # Use "optimized" version only if smaller...
  303. var_opt = TupleVariation(support, delta_opt)
  304. axis_tags = sorted(
  305. support.keys()
  306. ) # Shouldn't matter that this is different from fvar...?
  307. tupleData, auxData = var.compile(axis_tags)
  308. unoptimized_len = len(tupleData) + len(auxData)
  309. tupleData, auxData = var_opt.compile(axis_tags)
  310. optimized_len = len(tupleData) + len(auxData)
  311. if optimized_len < unoptimized_len:
  312. var = var_opt
  313. gvar.variations[glyph].append(var)
  314. def _remove_TTHinting(font):
  315. for tag in ("cvar", "cvt ", "fpgm", "prep"):
  316. if tag in font:
  317. del font[tag]
  318. maxp = font["maxp"]
  319. for attr in (
  320. "maxTwilightPoints",
  321. "maxStorage",
  322. "maxFunctionDefs",
  323. "maxInstructionDefs",
  324. "maxStackElements",
  325. "maxSizeOfInstructions",
  326. ):
  327. setattr(maxp, attr, 0)
  328. maxp.maxZones = 1
  329. font["glyf"].removeHinting()
  330. # TODO: Modify gasp table to deactivate gridfitting for all ranges?
  331. def _merge_TTHinting(font, masterModel, master_ttfs):
  332. log.info("Merging TT hinting")
  333. assert "cvar" not in font
  334. # Check that the existing hinting is compatible
  335. # fpgm and prep table
  336. for tag in ("fpgm", "prep"):
  337. all_pgms = [m[tag].program for m in master_ttfs if tag in m]
  338. if not all_pgms:
  339. continue
  340. font_pgm = getattr(font.get(tag), "program", None)
  341. if any(pgm != font_pgm for pgm in all_pgms):
  342. log.warning(
  343. "Masters have incompatible %s tables, hinting is discarded." % tag
  344. )
  345. _remove_TTHinting(font)
  346. return
  347. # glyf table
  348. font_glyf = font["glyf"]
  349. master_glyfs = [m["glyf"] for m in master_ttfs]
  350. for name, glyph in font_glyf.glyphs.items():
  351. all_pgms = [getattr(glyf.get(name), "program", None) for glyf in master_glyfs]
  352. if not any(all_pgms):
  353. continue
  354. glyph.expand(font_glyf)
  355. font_pgm = getattr(glyph, "program", None)
  356. if any(pgm != font_pgm for pgm in all_pgms if pgm):
  357. log.warning(
  358. "Masters have incompatible glyph programs in glyph '%s', hinting is discarded."
  359. % name
  360. )
  361. # TODO Only drop hinting from this glyph.
  362. _remove_TTHinting(font)
  363. return
  364. # cvt table
  365. all_cvs = [Vector(m["cvt "].values) if "cvt " in m else None for m in master_ttfs]
  366. nonNone_cvs = models.nonNone(all_cvs)
  367. if not nonNone_cvs:
  368. # There is no cvt table to make a cvar table from, we're done here.
  369. return
  370. if not models.allEqual(len(c) for c in nonNone_cvs):
  371. log.warning("Masters have incompatible cvt tables, hinting is discarded.")
  372. _remove_TTHinting(font)
  373. return
  374. variations = []
  375. deltas, supports = masterModel.getDeltasAndSupports(
  376. all_cvs, round=round
  377. ) # builtin round calls into Vector.__round__, which uses builtin round as we like
  378. for i, (delta, support) in enumerate(zip(deltas[1:], supports[1:])):
  379. if all(v == 0 for v in delta):
  380. continue
  381. var = TupleVariation(support, delta)
  382. variations.append(var)
  383. # We can build the cvar table now.
  384. if variations:
  385. cvar = font["cvar"] = newTable("cvar")
  386. cvar.version = 1
  387. cvar.variations = variations
  388. _MetricsFields = namedtuple(
  389. "_MetricsFields",
  390. ["tableTag", "metricsTag", "sb1", "sb2", "advMapping", "vOrigMapping"],
  391. )
  392. HVAR_FIELDS = _MetricsFields(
  393. tableTag="HVAR",
  394. metricsTag="hmtx",
  395. sb1="LsbMap",
  396. sb2="RsbMap",
  397. advMapping="AdvWidthMap",
  398. vOrigMapping=None,
  399. )
  400. VVAR_FIELDS = _MetricsFields(
  401. tableTag="VVAR",
  402. metricsTag="vmtx",
  403. sb1="TsbMap",
  404. sb2="BsbMap",
  405. advMapping="AdvHeightMap",
  406. vOrigMapping="VOrgMap",
  407. )
  408. def _add_HVAR(font, masterModel, master_ttfs, axisTags):
  409. _add_VHVAR(font, masterModel, master_ttfs, axisTags, HVAR_FIELDS)
  410. def _add_VVAR(font, masterModel, master_ttfs, axisTags):
  411. _add_VHVAR(font, masterModel, master_ttfs, axisTags, VVAR_FIELDS)
  412. def _add_VHVAR(font, masterModel, master_ttfs, axisTags, tableFields):
  413. tableTag = tableFields.tableTag
  414. assert tableTag not in font
  415. log.info("Generating " + tableTag)
  416. VHVAR = newTable(tableTag)
  417. tableClass = getattr(ot, tableTag)
  418. vhvar = VHVAR.table = tableClass()
  419. vhvar.Version = 0x00010000
  420. glyphOrder = font.getGlyphOrder()
  421. # Build list of source font advance widths for each glyph
  422. metricsTag = tableFields.metricsTag
  423. advMetricses = [m[metricsTag].metrics for m in master_ttfs]
  424. # Build list of source font vertical origin coords for each glyph
  425. if tableTag == "VVAR" and "VORG" in master_ttfs[0]:
  426. vOrigMetricses = [m["VORG"].VOriginRecords for m in master_ttfs]
  427. defaultYOrigs = [m["VORG"].defaultVertOriginY for m in master_ttfs]
  428. vOrigMetricses = list(zip(vOrigMetricses, defaultYOrigs))
  429. else:
  430. vOrigMetricses = None
  431. metricsStore, advanceMapping, vOrigMapping = _get_advance_metrics(
  432. font,
  433. masterModel,
  434. master_ttfs,
  435. axisTags,
  436. glyphOrder,
  437. advMetricses,
  438. vOrigMetricses,
  439. )
  440. vhvar.VarStore = metricsStore
  441. if advanceMapping is None:
  442. setattr(vhvar, tableFields.advMapping, None)
  443. else:
  444. setattr(vhvar, tableFields.advMapping, advanceMapping)
  445. if vOrigMapping is not None:
  446. setattr(vhvar, tableFields.vOrigMapping, vOrigMapping)
  447. setattr(vhvar, tableFields.sb1, None)
  448. setattr(vhvar, tableFields.sb2, None)
  449. font[tableTag] = VHVAR
  450. return
  451. def _get_advance_metrics(
  452. font,
  453. masterModel,
  454. master_ttfs,
  455. axisTags,
  456. glyphOrder,
  457. advMetricses,
  458. vOrigMetricses=None,
  459. ):
  460. vhAdvanceDeltasAndSupports = {}
  461. vOrigDeltasAndSupports = {}
  462. # HACK: we treat width 65535 as a sentinel value to signal that a glyph
  463. # from a non-default master should not participate in computing {H,V}VAR,
  464. # as if it were missing. Allows to variate other glyph-related data independently
  465. # from glyph metrics
  466. sparse_advance = 0xFFFF
  467. for glyph in glyphOrder:
  468. vhAdvances = [
  469. (
  470. metrics[glyph][0]
  471. if glyph in metrics and metrics[glyph][0] != sparse_advance
  472. else None
  473. )
  474. for metrics in advMetricses
  475. ]
  476. vhAdvanceDeltasAndSupports[glyph] = masterModel.getDeltasAndSupports(
  477. vhAdvances, round=round
  478. )
  479. singleModel = models.allEqual(id(v[1]) for v in vhAdvanceDeltasAndSupports.values())
  480. if vOrigMetricses:
  481. singleModel = False
  482. for glyph in glyphOrder:
  483. # We need to supply a vOrigs tuple with non-None default values
  484. # for each glyph. vOrigMetricses contains values only for those
  485. # glyphs which have a non-default vOrig.
  486. vOrigs = [
  487. metrics[glyph] if glyph in metrics else defaultVOrig
  488. for metrics, defaultVOrig in vOrigMetricses
  489. ]
  490. vOrigDeltasAndSupports[glyph] = masterModel.getDeltasAndSupports(
  491. vOrigs, round=round
  492. )
  493. directStore = None
  494. if singleModel:
  495. # Build direct mapping
  496. supports = next(iter(vhAdvanceDeltasAndSupports.values()))[1][1:]
  497. varTupleList = builder.buildVarRegionList(supports, axisTags)
  498. varTupleIndexes = list(range(len(supports)))
  499. varData = builder.buildVarData(varTupleIndexes, [], optimize=False)
  500. for glyphName in glyphOrder:
  501. varData.addItem(vhAdvanceDeltasAndSupports[glyphName][0], round=noRound)
  502. varData.optimize()
  503. directStore = builder.buildVarStore(varTupleList, [varData])
  504. # Build optimized indirect mapping
  505. storeBuilder = varStore.OnlineVarStoreBuilder(axisTags)
  506. advMapping = {}
  507. for glyphName in glyphOrder:
  508. deltas, supports = vhAdvanceDeltasAndSupports[glyphName]
  509. storeBuilder.setSupports(supports)
  510. advMapping[glyphName] = storeBuilder.storeDeltas(deltas, round=noRound)
  511. if vOrigMetricses:
  512. vOrigMap = {}
  513. for glyphName in glyphOrder:
  514. deltas, supports = vOrigDeltasAndSupports[glyphName]
  515. storeBuilder.setSupports(supports)
  516. vOrigMap[glyphName] = storeBuilder.storeDeltas(deltas, round=noRound)
  517. indirectStore = storeBuilder.finish()
  518. mapping2 = indirectStore.optimize(use_NO_VARIATION_INDEX=False)
  519. advMapping = [mapping2[advMapping[g]] for g in glyphOrder]
  520. advanceMapping = builder.buildVarIdxMap(advMapping, glyphOrder)
  521. if vOrigMetricses:
  522. vOrigMap = [mapping2[vOrigMap[g]] for g in glyphOrder]
  523. useDirect = False
  524. vOrigMapping = None
  525. if directStore:
  526. # Compile both, see which is more compact
  527. writer = OTTableWriter()
  528. directStore.compile(writer, font)
  529. directSize = len(writer.getAllData())
  530. writer = OTTableWriter()
  531. indirectStore.compile(writer, font)
  532. advanceMapping.compile(writer, font)
  533. indirectSize = len(writer.getAllData())
  534. useDirect = directSize < indirectSize
  535. if useDirect:
  536. metricsStore = directStore
  537. advanceMapping = None
  538. else:
  539. metricsStore = indirectStore
  540. if vOrigMetricses:
  541. vOrigMapping = builder.buildVarIdxMap(vOrigMap, glyphOrder)
  542. return metricsStore, advanceMapping, vOrigMapping
  543. def _add_MVAR(font, masterModel, master_ttfs, axisTags):
  544. log.info("Generating MVAR")
  545. store_builder = varStore.OnlineVarStoreBuilder(axisTags)
  546. records = []
  547. lastTableTag = None
  548. fontTable = None
  549. tables = None
  550. # HACK: we need to special-case post.underlineThickness and .underlinePosition
  551. # and unilaterally/arbitrarily define a sentinel value to distinguish the case
  552. # when a post table is present in a given master simply because that's where
  553. # the glyph names in TrueType must be stored, but the underline values are not
  554. # meant to be used for building MVAR's deltas. The value of -0x8000 (-36768)
  555. # the minimum FWord (int16) value, was chosen for its unlikelyhood to appear
  556. # in real-world underline position/thickness values.
  557. specialTags = {"unds": -0x8000, "undo": -0x8000}
  558. for tag, (tableTag, itemName) in sorted(MVAR_ENTRIES.items(), key=lambda kv: kv[1]):
  559. # For each tag, fetch the associated table from all fonts (or not when we are
  560. # still looking at a tag from the same tables) and set up the variation model
  561. # for them.
  562. if tableTag != lastTableTag:
  563. tables = fontTable = None
  564. if tableTag in font:
  565. fontTable = font[tableTag]
  566. tables = []
  567. for master in master_ttfs:
  568. if tableTag not in master or (
  569. tag in specialTags
  570. and getattr(master[tableTag], itemName) == specialTags[tag]
  571. ):
  572. tables.append(None)
  573. else:
  574. tables.append(master[tableTag])
  575. model, tables = masterModel.getSubModel(tables)
  576. store_builder.setModel(model)
  577. lastTableTag = tableTag
  578. if tables is None: # Tag not applicable to the master font.
  579. continue
  580. # TODO support gasp entries
  581. master_values = [getattr(table, itemName) for table in tables]
  582. if models.allEqual(master_values):
  583. base, varIdx = master_values[0], None
  584. else:
  585. base, varIdx = store_builder.storeMasters(master_values)
  586. setattr(fontTable, itemName, base)
  587. if varIdx is None:
  588. continue
  589. log.info(" %s: %s.%s %s", tag, tableTag, itemName, master_values)
  590. rec = ot.MetricsValueRecord()
  591. rec.ValueTag = tag
  592. rec.VarIdx = varIdx
  593. records.append(rec)
  594. assert "MVAR" not in font
  595. if records:
  596. store = store_builder.finish()
  597. # Optimize
  598. mapping = store.optimize()
  599. for rec in records:
  600. rec.VarIdx = mapping[rec.VarIdx]
  601. MVAR = font["MVAR"] = newTable("MVAR")
  602. mvar = MVAR.table = ot.MVAR()
  603. mvar.Version = 0x00010000
  604. mvar.Reserved = 0
  605. mvar.VarStore = store
  606. # XXX these should not be hard-coded but computed automatically
  607. mvar.ValueRecordSize = 8
  608. mvar.ValueRecordCount = len(records)
  609. mvar.ValueRecord = sorted(records, key=lambda r: r.ValueTag)
  610. def _add_BASE(font, masterModel, master_ttfs, axisTags):
  611. log.info("Generating BASE")
  612. merger = VariationMerger(masterModel, axisTags, font)
  613. merger.mergeTables(font, master_ttfs, ["BASE"])
  614. store = merger.store_builder.finish()
  615. if not store:
  616. return
  617. base = font["BASE"].table
  618. assert base.Version == 0x00010000
  619. base.Version = 0x00010001
  620. base.VarStore = store
  621. def _merge_OTL(font, model, master_fonts, axisTags):
  622. otl_tags = ["GSUB", "GDEF", "GPOS"]
  623. if not any(tag in font for tag in otl_tags):
  624. return
  625. log.info("Merging OpenType Layout tables")
  626. merger = VariationMerger(model, axisTags, font)
  627. merger.mergeTables(font, master_fonts, otl_tags)
  628. store = merger.store_builder.finish()
  629. if not store:
  630. return
  631. try:
  632. GDEF = font["GDEF"].table
  633. assert GDEF.Version <= 0x00010002
  634. except KeyError:
  635. font["GDEF"] = newTable("GDEF")
  636. GDEFTable = font["GDEF"] = newTable("GDEF")
  637. GDEF = GDEFTable.table = ot.GDEF()
  638. GDEF.GlyphClassDef = None
  639. GDEF.AttachList = None
  640. GDEF.LigCaretList = None
  641. GDEF.MarkAttachClassDef = None
  642. GDEF.MarkGlyphSetsDef = None
  643. GDEF.Version = 0x00010003
  644. GDEF.VarStore = store
  645. # Optimize
  646. varidx_map = store.optimize()
  647. GDEF.remap_device_varidxes(varidx_map)
  648. if "GPOS" in font:
  649. font["GPOS"].table.remap_device_varidxes(varidx_map)
  650. def _add_GSUB_feature_variations(
  651. font, axes, internal_axis_supports, rules, featureTags
  652. ):
  653. def normalize(name, value):
  654. return models.normalizeLocation({name: value}, internal_axis_supports)[name]
  655. log.info("Generating GSUB FeatureVariations")
  656. axis_tags = {name: axis.tag for name, axis in axes.items()}
  657. conditional_subs = []
  658. for rule in rules:
  659. region = []
  660. for conditions in rule.conditionSets:
  661. space = {}
  662. for condition in conditions:
  663. axis_name = condition["name"]
  664. if condition["minimum"] is not None:
  665. minimum = normalize(axis_name, condition["minimum"])
  666. else:
  667. minimum = -1.0
  668. if condition["maximum"] is not None:
  669. maximum = normalize(axis_name, condition["maximum"])
  670. else:
  671. maximum = 1.0
  672. tag = axis_tags[axis_name]
  673. space[tag] = (minimum, maximum)
  674. region.append(space)
  675. subs = {k: v for k, v in rule.subs}
  676. conditional_subs.append((region, subs))
  677. addFeatureVariations(font, conditional_subs, featureTags)
  678. _DesignSpaceData = namedtuple(
  679. "_DesignSpaceData",
  680. [
  681. "axes",
  682. "axisMappings",
  683. "internal_axis_supports",
  684. "base_idx",
  685. "normalized_master_locs",
  686. "masters",
  687. "instances",
  688. "rules",
  689. "rulesProcessingLast",
  690. "lib",
  691. ],
  692. )
  693. def _add_CFF2(varFont, model, master_fonts):
  694. from .cff import merge_region_fonts
  695. glyphOrder = varFont.getGlyphOrder()
  696. if "CFF2" not in varFont:
  697. from fontTools.cffLib.CFFToCFF2 import convertCFFToCFF2
  698. convertCFFToCFF2(varFont)
  699. ordered_fonts_list = model.reorderMasters(master_fonts, model.reverseMapping)
  700. # re-ordering the master list simplifies building the CFF2 data item lists.
  701. merge_region_fonts(varFont, model, ordered_fonts_list, glyphOrder)
  702. def _add_COLR(font, model, master_fonts, axisTags, colr_layer_reuse=True):
  703. merger = COLRVariationMerger(
  704. model, axisTags, font, allowLayerReuse=colr_layer_reuse
  705. )
  706. merger.mergeTables(font, master_fonts)
  707. store = merger.store_builder.finish()
  708. colr = font["COLR"].table
  709. if store:
  710. mapping = store.optimize()
  711. colr.VarStore = store
  712. varIdxes = [mapping[v] for v in merger.varIdxes]
  713. colr.VarIndexMap = builder.buildDeltaSetIndexMap(varIdxes)
  714. def load_designspace(designspace, log_enabled=True, *, require_sources=True):
  715. # TODO: remove this and always assume 'designspace' is a DesignSpaceDocument,
  716. # never a file path, as that's already handled by caller
  717. if hasattr(designspace, "sources"): # Assume a DesignspaceDocument
  718. ds = designspace
  719. else: # Assume a file path
  720. ds = DesignSpaceDocument.fromfile(designspace)
  721. masters = ds.sources
  722. if require_sources and not masters:
  723. raise VarLibValidationError("Designspace must have at least one source.")
  724. instances = ds.instances
  725. # TODO: Use fontTools.designspaceLib.tagForAxisName instead.
  726. standard_axis_map = OrderedDict(
  727. [
  728. ("weight", ("wght", {"en": "Weight"})),
  729. ("width", ("wdth", {"en": "Width"})),
  730. ("slant", ("slnt", {"en": "Slant"})),
  731. ("optical", ("opsz", {"en": "Optical Size"})),
  732. ("italic", ("ital", {"en": "Italic"})),
  733. ]
  734. )
  735. # Setup axes
  736. if not ds.axes:
  737. raise VarLibValidationError(f"Designspace must have at least one axis.")
  738. axes = OrderedDict()
  739. for axis_index, axis in enumerate(ds.axes):
  740. axis_name = axis.name
  741. if not axis_name:
  742. if not axis.tag:
  743. raise VarLibValidationError(f"Axis at index {axis_index} needs a tag.")
  744. axis_name = axis.name = axis.tag
  745. if axis_name in standard_axis_map:
  746. if axis.tag is None:
  747. axis.tag = standard_axis_map[axis_name][0]
  748. if not axis.labelNames:
  749. axis.labelNames.update(standard_axis_map[axis_name][1])
  750. else:
  751. if not axis.tag:
  752. raise VarLibValidationError(f"Axis at index {axis_index} needs a tag.")
  753. if not axis.labelNames:
  754. axis.labelNames["en"] = tostr(axis_name)
  755. axes[axis_name] = axis
  756. if log_enabled:
  757. log.info("Axes:\n%s", pformat([axis.asdict() for axis in axes.values()]))
  758. axisMappings = ds.axisMappings
  759. if axisMappings and log_enabled:
  760. log.info("Mappings:\n%s", pformat(axisMappings))
  761. # Check all master and instance locations are valid and fill in defaults
  762. for obj in masters + instances:
  763. obj_name = obj.name or obj.styleName or ""
  764. loc = obj.getFullDesignLocation(ds)
  765. obj.designLocation = loc
  766. if loc is None:
  767. raise VarLibValidationError(
  768. f"Source or instance '{obj_name}' has no location."
  769. )
  770. for axis_name in loc.keys():
  771. if axis_name not in axes:
  772. raise VarLibValidationError(
  773. f"Location axis '{axis_name}' unknown for '{obj_name}'."
  774. )
  775. for axis_name, axis in axes.items():
  776. v = axis.map_backward(loc[axis_name])
  777. if not (axis.minimum <= v <= axis.maximum):
  778. raise VarLibValidationError(
  779. f"Source or instance '{obj_name}' has out-of-range location "
  780. f"for axis '{axis_name}': is mapped to {v} but must be in "
  781. f"mapped range [{axis.minimum}..{axis.maximum}] (NOTE: all "
  782. "values are in user-space)."
  783. )
  784. # Normalize master locations
  785. internal_master_locs = [o.getFullDesignLocation(ds) for o in masters]
  786. if log_enabled:
  787. log.info("Internal master locations:\n%s", pformat(internal_master_locs))
  788. # TODO This mapping should ideally be moved closer to logic in _add_fvar/avar
  789. internal_axis_supports = {}
  790. for axis in axes.values():
  791. triple = (axis.minimum, axis.default, axis.maximum)
  792. internal_axis_supports[axis.name] = [axis.map_forward(v) for v in triple]
  793. if log_enabled:
  794. log.info("Internal axis supports:\n%s", pformat(internal_axis_supports))
  795. normalized_master_locs = [
  796. models.normalizeLocation(m, internal_axis_supports)
  797. for m in internal_master_locs
  798. ]
  799. if log_enabled:
  800. log.info("Normalized master locations:\n%s", pformat(normalized_master_locs))
  801. # Find base master
  802. base_idx = None
  803. for i, m in enumerate(normalized_master_locs):
  804. if all(v == 0 for v in m.values()):
  805. if base_idx is not None:
  806. raise VarLibValidationError(
  807. "More than one base master found in Designspace."
  808. )
  809. base_idx = i
  810. if require_sources and base_idx is None:
  811. raise VarLibValidationError(
  812. "Base master not found; no master at default location?"
  813. )
  814. if log_enabled:
  815. log.info("Index of base master: %s", base_idx)
  816. return _DesignSpaceData(
  817. axes,
  818. axisMappings,
  819. internal_axis_supports,
  820. base_idx,
  821. normalized_master_locs,
  822. masters,
  823. instances,
  824. ds.rules,
  825. ds.rulesProcessingLast,
  826. ds.lib,
  827. )
  828. # https://docs.microsoft.com/en-us/typography/opentype/spec/os2#uswidthclass
  829. WDTH_VALUE_TO_OS2_WIDTH_CLASS = {
  830. 50: 1,
  831. 62.5: 2,
  832. 75: 3,
  833. 87.5: 4,
  834. 100: 5,
  835. 112.5: 6,
  836. 125: 7,
  837. 150: 8,
  838. 200: 9,
  839. }
  840. def set_default_weight_width_slant(font, location):
  841. if "OS/2" in font:
  842. if "wght" in location:
  843. weight_class = otRound(max(1, min(location["wght"], 1000)))
  844. if font["OS/2"].usWeightClass != weight_class:
  845. log.info("Setting OS/2.usWeightClass = %s", weight_class)
  846. font["OS/2"].usWeightClass = weight_class
  847. if "wdth" in location:
  848. # map 'wdth' axis (50..200) to OS/2.usWidthClass (1..9), rounding to closest
  849. widthValue = min(max(location["wdth"], 50), 200)
  850. widthClass = otRound(
  851. models.piecewiseLinearMap(widthValue, WDTH_VALUE_TO_OS2_WIDTH_CLASS)
  852. )
  853. if font["OS/2"].usWidthClass != widthClass:
  854. log.info("Setting OS/2.usWidthClass = %s", widthClass)
  855. font["OS/2"].usWidthClass = widthClass
  856. if "slnt" in location and "post" in font:
  857. italicAngle = max(-90, min(location["slnt"], 90))
  858. if font["post"].italicAngle != italicAngle:
  859. log.info("Setting post.italicAngle = %s", italicAngle)
  860. font["post"].italicAngle = italicAngle
  861. def drop_implied_oncurve_points(*masters: TTFont) -> int:
  862. """Drop impliable on-curve points from all the simple glyphs in masters.
  863. In TrueType glyf outlines, on-curve points can be implied when they are located
  864. exactly at the midpoint of the line connecting two consecutive off-curve points.
  865. The input masters' glyf tables are assumed to contain same-named glyphs that are
  866. interpolatable. Oncurve points are only dropped if they can be implied for all
  867. the masters. The fonts are modified in-place.
  868. Args:
  869. masters: The TTFont(s) to modify
  870. Returns:
  871. The total number of points that were dropped if any.
  872. Reference:
  873. https://developer.apple.com/fonts/TrueType-Reference-Manual/RM01/Chap1.html
  874. """
  875. count = 0
  876. glyph_masters = defaultdict(list)
  877. # multiple DS source may point to the same TTFont object and we want to
  878. # avoid processing the same glyph twice as they are modified in-place
  879. for font in {id(m): m for m in masters}.values():
  880. glyf = font["glyf"]
  881. for glyphName in glyf.keys():
  882. glyph_masters[glyphName].append(glyf[glyphName])
  883. count = 0
  884. for glyphName, glyphs in glyph_masters.items():
  885. try:
  886. dropped = dropImpliedOnCurvePoints(*glyphs)
  887. except ValueError as e:
  888. # we don't fail for incompatible glyphs in _add_gvar so we shouldn't here
  889. log.warning("Failed to drop implied oncurves for %r: %s", glyphName, e)
  890. else:
  891. count += len(dropped)
  892. return count
  893. def build_many(
  894. designspace: DesignSpaceDocument,
  895. master_finder=lambda s: s,
  896. exclude=[],
  897. optimize=True,
  898. skip_vf=lambda vf_name: False,
  899. colr_layer_reuse=True,
  900. drop_implied_oncurves=False,
  901. ):
  902. """
  903. Build variable fonts from a designspace file, version 5 which can define
  904. several VFs, or version 4 which has implicitly one VF covering the whole doc.
  905. If master_finder is set, it should be a callable that takes master
  906. filename as found in designspace file and map it to master font
  907. binary as to be opened (eg. .ttf or .otf).
  908. skip_vf can be used to skip building some of the variable fonts defined in
  909. the input designspace. It's a predicate that takes as argument the name
  910. of the variable font and returns `bool`.
  911. Always returns a Dict[str, TTFont] keyed by VariableFontDescriptor.name
  912. """
  913. res = {}
  914. # varLib.build (used further below) by default only builds an incomplete 'STAT'
  915. # with an empty AxisValueArray--unless the VF inherited 'STAT' from its base master.
  916. # Designspace version 5 can also be used to define 'STAT' labels or customize
  917. # axes ordering, etc. To avoid overwriting a pre-existing 'STAT' or redoing the
  918. # same work twice, here we check if designspace contains any 'STAT' info before
  919. # proceeding to call buildVFStatTable for each VF.
  920. # https://github.com/fonttools/fonttools/pull/3024
  921. # https://github.com/fonttools/fonttools/issues/3045
  922. doBuildStatFromDSv5 = (
  923. "STAT" not in exclude
  924. and designspace.formatTuple >= (5, 0)
  925. and (
  926. any(a.axisLabels or a.axisOrdering is not None for a in designspace.axes)
  927. or designspace.locationLabels
  928. )
  929. )
  930. for _location, subDoc in splitInterpolable(designspace):
  931. for name, vfDoc in splitVariableFonts(subDoc):
  932. if skip_vf(name):
  933. log.debug(f"Skipping variable TTF font: {name}")
  934. continue
  935. vf = build(
  936. vfDoc,
  937. master_finder,
  938. exclude=exclude,
  939. optimize=optimize,
  940. colr_layer_reuse=colr_layer_reuse,
  941. drop_implied_oncurves=drop_implied_oncurves,
  942. )[0]
  943. if doBuildStatFromDSv5:
  944. buildVFStatTable(vf, designspace, name)
  945. res[name] = vf
  946. return res
  947. def build(
  948. designspace,
  949. master_finder=lambda s: s,
  950. exclude=[],
  951. optimize=True,
  952. colr_layer_reuse=True,
  953. drop_implied_oncurves=False,
  954. ):
  955. """
  956. Build variation font from a designspace file.
  957. If master_finder is set, it should be a callable that takes master
  958. filename as found in designspace file and map it to master font
  959. binary as to be opened (eg. .ttf or .otf).
  960. """
  961. if hasattr(designspace, "sources"): # Assume a DesignspaceDocument
  962. pass
  963. else: # Assume a file path
  964. designspace = DesignSpaceDocument.fromfile(designspace)
  965. ds = load_designspace(designspace)
  966. log.info("Building variable font")
  967. log.info("Loading master fonts")
  968. master_fonts = load_masters(designspace, master_finder)
  969. # TODO: 'master_ttfs' is unused except for return value, remove later
  970. master_ttfs = []
  971. for master in master_fonts:
  972. try:
  973. master_ttfs.append(master.reader.file.name)
  974. except AttributeError:
  975. master_ttfs.append(None) # in-memory fonts have no path
  976. if drop_implied_oncurves and "glyf" in master_fonts[ds.base_idx]:
  977. drop_count = drop_implied_oncurve_points(*master_fonts)
  978. log.info(
  979. "Dropped %s on-curve points from simple glyphs in the 'glyf' table",
  980. drop_count,
  981. )
  982. # Copy the base master to work from it
  983. vf = deepcopy(master_fonts[ds.base_idx])
  984. if "DSIG" in vf:
  985. del vf["DSIG"]
  986. # TODO append masters as named-instances as well; needs .designspace change.
  987. fvar = _add_fvar(vf, ds.axes, ds.instances)
  988. if "STAT" not in exclude:
  989. _add_stat(vf)
  990. # Map from axis names to axis tags...
  991. normalized_master_locs = [
  992. {ds.axes[k].tag: v for k, v in loc.items()} for loc in ds.normalized_master_locs
  993. ]
  994. # From here on, we use fvar axes only
  995. axisTags = [axis.axisTag for axis in fvar.axes]
  996. # Assume single-model for now.
  997. model = models.VariationModel(normalized_master_locs, axisOrder=axisTags)
  998. assert 0 == model.mapping[ds.base_idx]
  999. log.info("Building variations tables")
  1000. if "avar" not in exclude:
  1001. _add_avar(vf, ds.axes, ds.axisMappings, axisTags)
  1002. if "BASE" not in exclude and "BASE" in vf:
  1003. _add_BASE(vf, model, master_fonts, axisTags)
  1004. if "MVAR" not in exclude:
  1005. _add_MVAR(vf, model, master_fonts, axisTags)
  1006. if "HVAR" not in exclude:
  1007. _add_HVAR(vf, model, master_fonts, axisTags)
  1008. if "VVAR" not in exclude and "vmtx" in vf:
  1009. _add_VVAR(vf, model, master_fonts, axisTags)
  1010. if "GDEF" not in exclude or "GPOS" not in exclude:
  1011. _merge_OTL(vf, model, master_fonts, axisTags)
  1012. if "gvar" not in exclude and "glyf" in vf:
  1013. _add_gvar(vf, model, master_fonts, optimize=optimize)
  1014. if "cvar" not in exclude and "glyf" in vf:
  1015. _merge_TTHinting(vf, model, master_fonts)
  1016. if "GSUB" not in exclude and ds.rules:
  1017. featureTags = _feature_variations_tags(ds)
  1018. _add_GSUB_feature_variations(
  1019. vf, ds.axes, ds.internal_axis_supports, ds.rules, featureTags
  1020. )
  1021. if "CFF2" not in exclude and ("CFF " in vf or "CFF2" in vf):
  1022. _add_CFF2(vf, model, master_fonts)
  1023. if "post" in vf:
  1024. # set 'post' to format 2 to keep the glyph names dropped from CFF2
  1025. post = vf["post"]
  1026. if post.formatType != 2.0:
  1027. post.formatType = 2.0
  1028. post.extraNames = []
  1029. post.mapping = {}
  1030. if "COLR" not in exclude and "COLR" in vf and vf["COLR"].version > 0:
  1031. _add_COLR(vf, model, master_fonts, axisTags, colr_layer_reuse)
  1032. set_default_weight_width_slant(
  1033. vf, location={axis.axisTag: axis.defaultValue for axis in vf["fvar"].axes}
  1034. )
  1035. for tag in exclude:
  1036. if tag in vf:
  1037. del vf[tag]
  1038. # TODO: Only return vf for 4.0+, the rest is unused.
  1039. return vf, model, master_ttfs
  1040. def _open_font(path, master_finder=lambda s: s):
  1041. # load TTFont masters from given 'path': this can be either a .TTX or an
  1042. # OpenType binary font; or if neither of these, try use the 'master_finder'
  1043. # callable to resolve the path to a valid .TTX or OpenType font binary.
  1044. from fontTools.ttx import guessFileType
  1045. master_path = os.path.normpath(path)
  1046. tp = guessFileType(master_path)
  1047. if tp is None:
  1048. # not an OpenType binary/ttx, fall back to the master finder.
  1049. master_path = master_finder(master_path)
  1050. tp = guessFileType(master_path)
  1051. if tp in ("TTX", "OTX"):
  1052. font = TTFont()
  1053. font.importXML(master_path)
  1054. elif tp in ("TTF", "OTF", "WOFF", "WOFF2"):
  1055. font = TTFont(master_path)
  1056. else:
  1057. raise VarLibValidationError("Invalid master path: %r" % master_path)
  1058. return font
  1059. def load_masters(designspace, master_finder=lambda s: s):
  1060. """Ensure that all SourceDescriptor.font attributes have an appropriate TTFont
  1061. object loaded, or else open TTFont objects from the SourceDescriptor.path
  1062. attributes.
  1063. The paths can point to either an OpenType font, a TTX file, or a UFO. In the
  1064. latter case, use the provided master_finder callable to map from UFO paths to
  1065. the respective master font binaries (e.g. .ttf, .otf or .ttx).
  1066. Return list of master TTFont objects in the same order they are listed in the
  1067. DesignSpaceDocument.
  1068. """
  1069. for master in designspace.sources:
  1070. # If a SourceDescriptor has a layer name, demand that the compiled TTFont
  1071. # be supplied by the caller. This spares us from modifying MasterFinder.
  1072. if master.layerName and master.font is None:
  1073. raise VarLibValidationError(
  1074. f"Designspace source '{master.name or '<Unknown>'}' specified a "
  1075. "layer name but lacks the required TTFont object in the 'font' "
  1076. "attribute."
  1077. )
  1078. return designspace.loadSourceFonts(_open_font, master_finder=master_finder)
  1079. class MasterFinder(object):
  1080. def __init__(self, template):
  1081. self.template = template
  1082. def __call__(self, src_path):
  1083. fullname = os.path.abspath(src_path)
  1084. dirname, basename = os.path.split(fullname)
  1085. stem, ext = os.path.splitext(basename)
  1086. path = self.template.format(
  1087. fullname=fullname,
  1088. dirname=dirname,
  1089. basename=basename,
  1090. stem=stem,
  1091. ext=ext,
  1092. )
  1093. return os.path.normpath(path)
  1094. def _feature_variations_tags(ds):
  1095. raw_tags = ds.lib.get(
  1096. FEAVAR_FEATURETAG_LIB_KEY,
  1097. "rclt" if ds.rulesProcessingLast else "rvrn",
  1098. )
  1099. return sorted({t.strip() for t in raw_tags.split(",")})
  1100. def addGSUBFeatureVariations(vf, designspace, featureTags=(), *, log_enabled=False):
  1101. """Add GSUB FeatureVariations table to variable font, based on DesignSpace rules.
  1102. Args:
  1103. vf: A TTFont object representing the variable font.
  1104. designspace: A DesignSpaceDocument object.
  1105. featureTags: Optional feature tag(s) to use for the FeatureVariations records.
  1106. If unset, the key 'com.github.fonttools.varLib.featureVarsFeatureTag' is
  1107. looked up in the DS <lib> and used; otherwise the default is 'rclt' if
  1108. the <rules processing="last"> attribute is set, else 'rvrn'.
  1109. See <https://fonttools.readthedocs.io/en/latest/designspaceLib/xml.html#rules-element>
  1110. log_enabled: If True, log info about DS axes and sources. Default is False, as
  1111. the same info may have already been logged as part of varLib.build.
  1112. """
  1113. ds = load_designspace(designspace, log_enabled=log_enabled)
  1114. if not ds.rules:
  1115. return
  1116. if not featureTags:
  1117. featureTags = _feature_variations_tags(ds)
  1118. _add_GSUB_feature_variations(
  1119. vf, ds.axes, ds.internal_axis_supports, ds.rules, featureTags
  1120. )
  1121. def main(args=None):
  1122. """Build variable fonts from a designspace file and masters"""
  1123. from argparse import ArgumentParser
  1124. from fontTools import configLogger
  1125. parser = ArgumentParser(prog="varLib", description=main.__doc__)
  1126. parser.add_argument("designspace")
  1127. output_group = parser.add_mutually_exclusive_group()
  1128. output_group.add_argument(
  1129. "-o", metavar="OUTPUTFILE", dest="outfile", default=None, help="output file"
  1130. )
  1131. output_group.add_argument(
  1132. "-d",
  1133. "--output-dir",
  1134. metavar="OUTPUTDIR",
  1135. default=None,
  1136. help="output dir (default: same as input designspace file)",
  1137. )
  1138. parser.add_argument(
  1139. "-x",
  1140. metavar="TAG",
  1141. dest="exclude",
  1142. action="append",
  1143. default=[],
  1144. help="exclude table",
  1145. )
  1146. parser.add_argument(
  1147. "--disable-iup",
  1148. dest="optimize",
  1149. action="store_false",
  1150. help="do not perform IUP optimization",
  1151. )
  1152. parser.add_argument(
  1153. "--no-colr-layer-reuse",
  1154. dest="colr_layer_reuse",
  1155. action="store_false",
  1156. help="do not rebuild variable COLR table to optimize COLR layer reuse",
  1157. )
  1158. parser.add_argument(
  1159. "--drop-implied-oncurves",
  1160. action="store_true",
  1161. help=(
  1162. "drop on-curve points that can be implied when exactly in the middle of "
  1163. "two off-curve points (only applies to TrueType fonts)"
  1164. ),
  1165. )
  1166. parser.add_argument(
  1167. "--master-finder",
  1168. default="master_ttf_interpolatable/{stem}.ttf",
  1169. help=(
  1170. "templated string used for finding binary font "
  1171. "files given the source file names defined in the "
  1172. "designspace document. The following special strings "
  1173. "are defined: {fullname} is the absolute source file "
  1174. "name; {basename} is the file name without its "
  1175. "directory; {stem} is the basename without the file "
  1176. "extension; {ext} is the source file extension; "
  1177. "{dirname} is the directory of the absolute file "
  1178. 'name. The default value is "%(default)s".'
  1179. ),
  1180. )
  1181. parser.add_argument(
  1182. "--variable-fonts",
  1183. default=".*",
  1184. metavar="VF_NAME",
  1185. help=(
  1186. "Filter the list of variable fonts produced from the input "
  1187. "Designspace v5 file. By default all listed variable fonts are "
  1188. "generated. To generate a specific variable font (or variable fonts) "
  1189. 'that match a given "name" attribute, you can pass as argument '
  1190. "the full name or a regular expression. E.g.: --variable-fonts "
  1191. '"MyFontVF_WeightOnly"; or --variable-fonts "MyFontVFItalic_.*".'
  1192. ),
  1193. )
  1194. logging_group = parser.add_mutually_exclusive_group(required=False)
  1195. logging_group.add_argument(
  1196. "-v", "--verbose", action="store_true", help="Run more verbosely."
  1197. )
  1198. logging_group.add_argument(
  1199. "-q", "--quiet", action="store_true", help="Turn verbosity off."
  1200. )
  1201. options = parser.parse_args(args)
  1202. configLogger(
  1203. level=("DEBUG" if options.verbose else "ERROR" if options.quiet else "INFO")
  1204. )
  1205. designspace_filename = options.designspace
  1206. designspace = DesignSpaceDocument.fromfile(designspace_filename)
  1207. vf_descriptors = designspace.getVariableFonts()
  1208. if not vf_descriptors:
  1209. parser.error(f"No variable fonts in given designspace {designspace.path!r}")
  1210. vfs_to_build = []
  1211. for vf in vf_descriptors:
  1212. # Skip variable fonts that do not match the user's inclusion regex if given.
  1213. if not fullmatch(options.variable_fonts, vf.name):
  1214. continue
  1215. vfs_to_build.append(vf)
  1216. if not vfs_to_build:
  1217. parser.error(f"No variable fonts matching {options.variable_fonts!r}")
  1218. if options.outfile is not None and len(vfs_to_build) > 1:
  1219. parser.error(
  1220. "can't specify -o because there are multiple VFs to build; "
  1221. "use --output-dir, or select a single VF with --variable-fonts"
  1222. )
  1223. output_dir = options.output_dir
  1224. if output_dir is None:
  1225. output_dir = os.path.dirname(designspace_filename)
  1226. vf_name_to_output_path = {}
  1227. if len(vfs_to_build) == 1 and options.outfile is not None:
  1228. vf_name_to_output_path[vfs_to_build[0].name] = options.outfile
  1229. else:
  1230. for vf in vfs_to_build:
  1231. filename = vf.filename if vf.filename is not None else vf.name + ".{ext}"
  1232. vf_name_to_output_path[vf.name] = os.path.join(output_dir, filename)
  1233. finder = MasterFinder(options.master_finder)
  1234. vfs = build_many(
  1235. designspace,
  1236. finder,
  1237. exclude=options.exclude,
  1238. optimize=options.optimize,
  1239. colr_layer_reuse=options.colr_layer_reuse,
  1240. drop_implied_oncurves=options.drop_implied_oncurves,
  1241. )
  1242. for vf_name, vf in vfs.items():
  1243. ext = "otf" if vf.sfntVersion == "OTTO" else "ttf"
  1244. output_path = vf_name_to_output_path[vf_name].format(ext=ext)
  1245. output_dir = os.path.dirname(output_path)
  1246. if output_dir:
  1247. os.makedirs(output_dir, exist_ok=True)
  1248. log.info("Saving variation font %s", output_path)
  1249. vf.save(output_path)
  1250. if __name__ == "__main__":
  1251. import sys
  1252. if len(sys.argv) > 1:
  1253. sys.exit(main())
  1254. import doctest
  1255. sys.exit(doctest.testmod().failed)