__init__.py 53 KB

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