__init__.py 51 KB

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