__init__.py 52 KB

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