__init__.py 52 KB

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