avarPlanner.py 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. from fontTools.ttLib import newTable
  2. from fontTools.ttLib.tables._f_v_a_r import Axis as fvarAxis
  3. from fontTools.pens.areaPen import AreaPen
  4. from fontTools.pens.basePen import NullPen
  5. from fontTools.pens.statisticsPen import StatisticsPen
  6. from fontTools.varLib.models import piecewiseLinearMap, normalizeValue
  7. from fontTools.misc.cliTools import makeOutputFileName
  8. import math
  9. import logging
  10. from pprint import pformat
  11. __all__ = [
  12. "planWeightAxis",
  13. "planWidthAxis",
  14. "planSlantAxis",
  15. "planOpticalSizeAxis",
  16. "planAxis",
  17. "sanitizeWeight",
  18. "sanitizeWidth",
  19. "sanitizeSlant",
  20. "measureWeight",
  21. "measureWidth",
  22. "measureSlant",
  23. "normalizeLinear",
  24. "normalizeLog",
  25. "normalizeDegrees",
  26. "interpolateLinear",
  27. "interpolateLog",
  28. "processAxis",
  29. "makeDesignspaceSnippet",
  30. "addEmptyAvar",
  31. "main",
  32. ]
  33. log = logging.getLogger("fontTools.varLib.avarPlanner")
  34. WEIGHTS = [
  35. 50,
  36. 100,
  37. 150,
  38. 200,
  39. 250,
  40. 300,
  41. 350,
  42. 400,
  43. 450,
  44. 500,
  45. 550,
  46. 600,
  47. 650,
  48. 700,
  49. 750,
  50. 800,
  51. 850,
  52. 900,
  53. 950,
  54. ]
  55. WIDTHS = [
  56. 25.0,
  57. 37.5,
  58. 50.0,
  59. 62.5,
  60. 75.0,
  61. 87.5,
  62. 100.0,
  63. 112.5,
  64. 125.0,
  65. 137.5,
  66. 150.0,
  67. 162.5,
  68. 175.0,
  69. 187.5,
  70. 200.0,
  71. ]
  72. SLANTS = list(math.degrees(math.atan(d / 20.0)) for d in range(-20, 21))
  73. SIZES = [
  74. 5,
  75. 6,
  76. 7,
  77. 8,
  78. 9,
  79. 10,
  80. 11,
  81. 12,
  82. 14,
  83. 18,
  84. 24,
  85. 30,
  86. 36,
  87. 48,
  88. 60,
  89. 72,
  90. 96,
  91. 120,
  92. 144,
  93. 192,
  94. 240,
  95. 288,
  96. ]
  97. SAMPLES = 8
  98. def normalizeLinear(value, rangeMin, rangeMax):
  99. """Linearly normalize value in [rangeMin, rangeMax] to [0, 1], with extrapolation."""
  100. return (value - rangeMin) / (rangeMax - rangeMin)
  101. def interpolateLinear(t, a, b):
  102. """Linear interpolation between a and b, with t typically in [0, 1]."""
  103. return a + t * (b - a)
  104. def normalizeLog(value, rangeMin, rangeMax):
  105. """Logarithmically normalize value in [rangeMin, rangeMax] to [0, 1], with extrapolation."""
  106. logMin = math.log(rangeMin)
  107. logMax = math.log(rangeMax)
  108. return (math.log(value) - logMin) / (logMax - logMin)
  109. def interpolateLog(t, a, b):
  110. """Logarithmic interpolation between a and b, with t typically in [0, 1]."""
  111. logA = math.log(a)
  112. logB = math.log(b)
  113. return math.exp(logA + t * (logB - logA))
  114. def normalizeDegrees(value, rangeMin, rangeMax):
  115. """Angularly normalize value in [rangeMin, rangeMax] to [0, 1], with extrapolation."""
  116. tanMin = math.tan(math.radians(rangeMin))
  117. tanMax = math.tan(math.radians(rangeMax))
  118. return (math.tan(math.radians(value)) - tanMin) / (tanMax - tanMin)
  119. def measureWeight(glyphset, glyphs=None):
  120. """Measure the perceptual average weight of the given glyphs."""
  121. if isinstance(glyphs, dict):
  122. frequencies = glyphs
  123. else:
  124. frequencies = {g: 1 for g in glyphs}
  125. wght_sum = wdth_sum = 0
  126. for glyph_name in glyphs:
  127. if frequencies is not None:
  128. frequency = frequencies.get(glyph_name, 0)
  129. if frequency == 0:
  130. continue
  131. else:
  132. frequency = 1
  133. glyph = glyphset[glyph_name]
  134. pen = AreaPen(glyphset=glyphset)
  135. glyph.draw(pen)
  136. mult = glyph.width * frequency
  137. wght_sum += mult * abs(pen.value)
  138. wdth_sum += mult
  139. return wght_sum / wdth_sum
  140. def measureWidth(glyphset, glyphs=None):
  141. """Measure the average width of the given glyphs."""
  142. if isinstance(glyphs, dict):
  143. frequencies = glyphs
  144. else:
  145. frequencies = {g: 1 for g in glyphs}
  146. wdth_sum = 0
  147. freq_sum = 0
  148. for glyph_name in glyphs:
  149. if frequencies is not None:
  150. frequency = frequencies.get(glyph_name, 0)
  151. if frequency == 0:
  152. continue
  153. else:
  154. frequency = 1
  155. glyph = glyphset[glyph_name]
  156. pen = NullPen()
  157. glyph.draw(pen)
  158. wdth_sum += glyph.width * frequency
  159. freq_sum += frequency
  160. return wdth_sum / freq_sum
  161. def measureSlant(glyphset, glyphs=None):
  162. """Measure the perceptual average slant angle of the given glyphs."""
  163. if isinstance(glyphs, dict):
  164. frequencies = glyphs
  165. else:
  166. frequencies = {g: 1 for g in glyphs}
  167. slnt_sum = 0
  168. freq_sum = 0
  169. for glyph_name in glyphs:
  170. if frequencies is not None:
  171. frequency = frequencies.get(glyph_name, 0)
  172. if frequency == 0:
  173. continue
  174. else:
  175. frequency = 1
  176. glyph = glyphset[glyph_name]
  177. pen = StatisticsPen(glyphset=glyphset)
  178. glyph.draw(pen)
  179. mult = glyph.width * frequency
  180. slnt_sum += mult * pen.slant
  181. freq_sum += mult
  182. return -math.degrees(math.atan(slnt_sum / freq_sum))
  183. def sanitizeWidth(userTriple, designTriple, pins, measurements):
  184. """Sanitize the width axis limits."""
  185. minVal, defaultVal, maxVal = (
  186. measurements[designTriple[0]],
  187. measurements[designTriple[1]],
  188. measurements[designTriple[2]],
  189. )
  190. calculatedMinVal = userTriple[1] * (minVal / defaultVal)
  191. calculatedMaxVal = userTriple[1] * (maxVal / defaultVal)
  192. log.info("Original width axis limits: %g:%g:%g", *userTriple)
  193. log.info(
  194. "Calculated width axis limits: %g:%g:%g",
  195. calculatedMinVal,
  196. userTriple[1],
  197. calculatedMaxVal,
  198. )
  199. if (
  200. abs(calculatedMinVal - userTriple[0]) / userTriple[1] > 0.05
  201. or abs(calculatedMaxVal - userTriple[2]) / userTriple[1] > 0.05
  202. ):
  203. log.warning("Calculated width axis min/max do not match user input.")
  204. log.warning(
  205. " Current width axis limits: %g:%g:%g",
  206. *userTriple,
  207. )
  208. log.warning(
  209. " Suggested width axis limits: %g:%g:%g",
  210. calculatedMinVal,
  211. userTriple[1],
  212. calculatedMaxVal,
  213. )
  214. return False
  215. return True
  216. def sanitizeWeight(userTriple, designTriple, pins, measurements):
  217. """Sanitize the weight axis limits."""
  218. if len(set(userTriple)) < 3:
  219. return True
  220. minVal, defaultVal, maxVal = (
  221. measurements[designTriple[0]],
  222. measurements[designTriple[1]],
  223. measurements[designTriple[2]],
  224. )
  225. logMin = math.log(minVal)
  226. logDefault = math.log(defaultVal)
  227. logMax = math.log(maxVal)
  228. t = (userTriple[1] - userTriple[0]) / (userTriple[2] - userTriple[0])
  229. y = math.exp(logMin + t * (logMax - logMin))
  230. t = (y - minVal) / (maxVal - minVal)
  231. calculatedDefaultVal = userTriple[0] + t * (userTriple[2] - userTriple[0])
  232. log.info("Original weight axis limits: %g:%g:%g", *userTriple)
  233. log.info(
  234. "Calculated weight axis limits: %g:%g:%g",
  235. userTriple[0],
  236. calculatedDefaultVal,
  237. userTriple[2],
  238. )
  239. if abs(calculatedDefaultVal - userTriple[1]) / userTriple[1] > 0.05:
  240. log.warning("Calculated weight axis default does not match user input.")
  241. log.warning(
  242. " Current weight axis limits: %g:%g:%g",
  243. *userTriple,
  244. )
  245. log.warning(
  246. " Suggested weight axis limits, changing default: %g:%g:%g",
  247. userTriple[0],
  248. calculatedDefaultVal,
  249. userTriple[2],
  250. )
  251. t = (userTriple[2] - userTriple[0]) / (userTriple[1] - userTriple[0])
  252. y = math.exp(logMin + t * (logDefault - logMin))
  253. t = (y - minVal) / (defaultVal - minVal)
  254. calculatedMaxVal = userTriple[0] + t * (userTriple[1] - userTriple[0])
  255. log.warning(
  256. " Suggested weight axis limits, changing maximum: %g:%g:%g",
  257. userTriple[0],
  258. userTriple[1],
  259. calculatedMaxVal,
  260. )
  261. t = (userTriple[0] - userTriple[2]) / (userTriple[1] - userTriple[2])
  262. y = math.exp(logMax + t * (logDefault - logMax))
  263. t = (y - maxVal) / (defaultVal - maxVal)
  264. calculatedMinVal = userTriple[2] + t * (userTriple[1] - userTriple[2])
  265. log.warning(
  266. " Suggested weight axis limits, changing minimum: %g:%g:%g",
  267. calculatedMinVal,
  268. userTriple[1],
  269. userTriple[2],
  270. )
  271. return False
  272. return True
  273. def sanitizeSlant(userTriple, designTriple, pins, measurements):
  274. """Sanitize the slant axis limits."""
  275. log.info("Original slant axis limits: %g:%g:%g", *userTriple)
  276. log.info(
  277. "Calculated slant axis limits: %g:%g:%g",
  278. measurements[designTriple[0]],
  279. measurements[designTriple[1]],
  280. measurements[designTriple[2]],
  281. )
  282. if (
  283. abs(measurements[designTriple[0]] - userTriple[0]) > 1
  284. or abs(measurements[designTriple[1]] - userTriple[1]) > 1
  285. or abs(measurements[designTriple[2]] - userTriple[2]) > 1
  286. ):
  287. log.warning("Calculated slant axis min/default/max do not match user input.")
  288. log.warning(
  289. " Current slant axis limits: %g:%g:%g",
  290. *userTriple,
  291. )
  292. log.warning(
  293. " Suggested slant axis limits: %g:%g:%g",
  294. measurements[designTriple[0]],
  295. measurements[designTriple[1]],
  296. measurements[designTriple[2]],
  297. )
  298. return False
  299. return True
  300. def planAxis(
  301. measureFunc,
  302. normalizeFunc,
  303. interpolateFunc,
  304. glyphSetFunc,
  305. axisTag,
  306. axisLimits,
  307. values,
  308. samples=None,
  309. glyphs=None,
  310. designLimits=None,
  311. pins=None,
  312. sanitizeFunc=None,
  313. ):
  314. """Plan an axis.
  315. measureFunc: callable that takes a glyphset and an optional
  316. list of glyphnames, and returns the glyphset-wide measurement
  317. to be used for the axis.
  318. normalizeFunc: callable that takes a measurement and a minimum
  319. and maximum, and normalizes the measurement into the range 0..1,
  320. possibly extrapolating too.
  321. interpolateFunc: callable that takes a normalized t value, and a
  322. minimum and maximum, and returns the interpolated value,
  323. possibly extrapolating too.
  324. glyphSetFunc: callable that takes a variations "location" dictionary,
  325. and returns a glyphset.
  326. axisTag: the axis tag string.
  327. axisLimits: a triple of minimum, default, and maximum values for
  328. the axis. Or an `fvar` Axis object.
  329. values: a list of output values to map for this axis.
  330. samples: the number of samples to use when sampling. Default 8.
  331. glyphs: a list of glyph names to use when sampling. Defaults to None,
  332. which will process all glyphs.
  333. designLimits: an optional triple of minimum, default, and maximum values
  334. represenging the "design" limits for the axis. If not provided, the
  335. axisLimits will be used.
  336. pins: an optional dictionary of before/after mapping entries to pin in
  337. the output.
  338. sanitizeFunc: an optional callable to call to sanitize the axis limits.
  339. """
  340. if isinstance(axisLimits, fvarAxis):
  341. axisLimits = (axisLimits.minValue, axisLimits.defaultValue, axisLimits.maxValue)
  342. minValue, defaultValue, maxValue = axisLimits
  343. if samples is None:
  344. samples = SAMPLES
  345. if glyphs is None:
  346. glyphs = glyphSetFunc({}).keys()
  347. if pins is None:
  348. pins = {}
  349. else:
  350. pins = pins.copy()
  351. log.info(
  352. "Axis limits min %g / default %g / max %g", minValue, defaultValue, maxValue
  353. )
  354. triple = (minValue, defaultValue, maxValue)
  355. if designLimits is not None:
  356. log.info("Axis design-limits min %g / default %g / max %g", *designLimits)
  357. else:
  358. designLimits = triple
  359. if pins:
  360. log.info("Pins %s", sorted(pins.items()))
  361. pins.update(
  362. {
  363. minValue: designLimits[0],
  364. defaultValue: designLimits[1],
  365. maxValue: designLimits[2],
  366. }
  367. )
  368. out = {}
  369. outNormalized = {}
  370. axisMeasurements = {}
  371. for value in sorted({minValue, defaultValue, maxValue} | set(pins.keys())):
  372. glyphset = glyphSetFunc(location={axisTag: value})
  373. designValue = pins[value]
  374. axisMeasurements[designValue] = measureFunc(glyphset, glyphs)
  375. if sanitizeFunc is not None:
  376. log.info("Sanitizing axis limit values for the `%s` axis.", axisTag)
  377. sanitizeFunc(triple, designLimits, pins, axisMeasurements)
  378. log.debug("Calculated average value:\n%s", pformat(axisMeasurements))
  379. for (rangeMin, targetMin), (rangeMax, targetMax) in zip(
  380. list(sorted(pins.items()))[:-1],
  381. list(sorted(pins.items()))[1:],
  382. ):
  383. targetValues = {w for w in values if rangeMin < w < rangeMax}
  384. if not targetValues:
  385. continue
  386. normalizedMin = normalizeValue(rangeMin, triple)
  387. normalizedMax = normalizeValue(rangeMax, triple)
  388. normalizedTargetMin = normalizeValue(targetMin, designLimits)
  389. normalizedTargetMax = normalizeValue(targetMax, designLimits)
  390. log.info("Planning target values %s.", sorted(targetValues))
  391. log.info("Sampling %u points in range %g,%g.", samples, rangeMin, rangeMax)
  392. valueMeasurements = axisMeasurements.copy()
  393. for sample in range(1, samples + 1):
  394. value = rangeMin + (rangeMax - rangeMin) * sample / (samples + 1)
  395. log.debug("Sampling value %g.", value)
  396. glyphset = glyphSetFunc(location={axisTag: value})
  397. designValue = piecewiseLinearMap(value, pins)
  398. valueMeasurements[designValue] = measureFunc(glyphset, glyphs)
  399. log.debug("Sampled average value:\n%s", pformat(valueMeasurements))
  400. measurementValue = {}
  401. for value in sorted(valueMeasurements):
  402. measurementValue[valueMeasurements[value]] = value
  403. out[rangeMin] = targetMin
  404. outNormalized[normalizedMin] = normalizedTargetMin
  405. for value in sorted(targetValues):
  406. t = normalizeFunc(value, rangeMin, rangeMax)
  407. targetMeasurement = interpolateFunc(
  408. t, valueMeasurements[targetMin], valueMeasurements[targetMax]
  409. )
  410. targetValue = piecewiseLinearMap(targetMeasurement, measurementValue)
  411. log.debug("Planned mapping value %g to %g." % (value, targetValue))
  412. out[value] = targetValue
  413. valueNormalized = normalizedMin + (value - rangeMin) / (
  414. rangeMax - rangeMin
  415. ) * (normalizedMax - normalizedMin)
  416. outNormalized[valueNormalized] = normalizedTargetMin + (
  417. targetValue - targetMin
  418. ) / (targetMax - targetMin) * (normalizedTargetMax - normalizedTargetMin)
  419. out[rangeMax] = targetMax
  420. outNormalized[normalizedMax] = normalizedTargetMax
  421. log.info("Planned mapping for the `%s` axis:\n%s", axisTag, pformat(out))
  422. log.info(
  423. "Planned normalized mapping for the `%s` axis:\n%s",
  424. axisTag,
  425. pformat(outNormalized),
  426. )
  427. if all(abs(k - v) < 0.01 for k, v in outNormalized.items()):
  428. log.info("Detected identity mapping for the `%s` axis. Dropping.", axisTag)
  429. out = {}
  430. outNormalized = {}
  431. return out, outNormalized
  432. def planWeightAxis(
  433. glyphSetFunc,
  434. axisLimits,
  435. weights=None,
  436. samples=None,
  437. glyphs=None,
  438. designLimits=None,
  439. pins=None,
  440. sanitize=False,
  441. ):
  442. """Plan a weight (`wght`) axis.
  443. weights: A list of weight values to plan for. If None, the default
  444. values are used.
  445. This function simply calls planAxis with values=weights, and the appropriate
  446. arguments. See documenation for planAxis for more information.
  447. """
  448. if weights is None:
  449. weights = WEIGHTS
  450. return planAxis(
  451. measureWeight,
  452. normalizeLinear,
  453. interpolateLog,
  454. glyphSetFunc,
  455. "wght",
  456. axisLimits,
  457. values=weights,
  458. samples=samples,
  459. glyphs=glyphs,
  460. designLimits=designLimits,
  461. pins=pins,
  462. sanitizeFunc=sanitizeWeight if sanitize else None,
  463. )
  464. def planWidthAxis(
  465. glyphSetFunc,
  466. axisLimits,
  467. widths=None,
  468. samples=None,
  469. glyphs=None,
  470. designLimits=None,
  471. pins=None,
  472. sanitize=False,
  473. ):
  474. """Plan a width (`wdth`) axis.
  475. widths: A list of width values (percentages) to plan for. If None, the default
  476. values are used.
  477. This function simply calls planAxis with values=widths, and the appropriate
  478. arguments. See documenation for planAxis for more information.
  479. """
  480. if widths is None:
  481. widths = WIDTHS
  482. return planAxis(
  483. measureWidth,
  484. normalizeLinear,
  485. interpolateLinear,
  486. glyphSetFunc,
  487. "wdth",
  488. axisLimits,
  489. values=widths,
  490. samples=samples,
  491. glyphs=glyphs,
  492. designLimits=designLimits,
  493. pins=pins,
  494. sanitizeFunc=sanitizeWidth if sanitize else None,
  495. )
  496. def planSlantAxis(
  497. glyphSetFunc,
  498. axisLimits,
  499. slants=None,
  500. samples=None,
  501. glyphs=None,
  502. designLimits=None,
  503. pins=None,
  504. sanitize=False,
  505. ):
  506. """Plan a slant (`slnt`) axis.
  507. slants: A list slant angles to plan for. If None, the default
  508. values are used.
  509. This function simply calls planAxis with values=slants, and the appropriate
  510. arguments. See documenation for planAxis for more information.
  511. """
  512. if slants is None:
  513. slants = SLANTS
  514. return planAxis(
  515. measureSlant,
  516. normalizeDegrees,
  517. interpolateLinear,
  518. glyphSetFunc,
  519. "slnt",
  520. axisLimits,
  521. values=slants,
  522. samples=samples,
  523. glyphs=glyphs,
  524. designLimits=designLimits,
  525. pins=pins,
  526. sanitizeFunc=sanitizeSlant if sanitize else None,
  527. )
  528. def planOpticalSizeAxis(
  529. glyphSetFunc,
  530. axisLimits,
  531. sizes=None,
  532. samples=None,
  533. glyphs=None,
  534. designLimits=None,
  535. pins=None,
  536. sanitize=False,
  537. ):
  538. """Plan a optical-size (`opsz`) axis.
  539. sizes: A list of optical size values to plan for. If None, the default
  540. values are used.
  541. This function simply calls planAxis with values=sizes, and the appropriate
  542. arguments. See documenation for planAxis for more information.
  543. """
  544. if sizes is None:
  545. sizes = SIZES
  546. return planAxis(
  547. measureWeight,
  548. normalizeLog,
  549. interpolateLog,
  550. glyphSetFunc,
  551. "opsz",
  552. axisLimits,
  553. values=sizes,
  554. samples=samples,
  555. glyphs=glyphs,
  556. designLimits=designLimits,
  557. pins=pins,
  558. )
  559. def makeDesignspaceSnippet(axisTag, axisName, axisLimit, mapping):
  560. """Make a designspace snippet for a single axis."""
  561. designspaceSnippet = (
  562. ' <axis tag="%s" name="%s" minimum="%g" default="%g" maximum="%g"'
  563. % ((axisTag, axisName) + axisLimit)
  564. )
  565. if mapping:
  566. designspaceSnippet += ">\n"
  567. else:
  568. designspaceSnippet += "/>"
  569. for key, value in mapping.items():
  570. designspaceSnippet += ' <map input="%g" output="%g"/>\n' % (key, value)
  571. if mapping:
  572. designspaceSnippet += " </axis>"
  573. return designspaceSnippet
  574. def addEmptyAvar(font):
  575. """Add an empty `avar` table to the font."""
  576. font["avar"] = avar = newTable("avar")
  577. for axis in fvar.axes:
  578. avar.segments[axis.axisTag] = {}
  579. def processAxis(
  580. font,
  581. planFunc,
  582. axisTag,
  583. axisName,
  584. values,
  585. samples=None,
  586. glyphs=None,
  587. designLimits=None,
  588. pins=None,
  589. sanitize=False,
  590. plot=False,
  591. ):
  592. """Process a single axis."""
  593. axisLimits = None
  594. for axis in font["fvar"].axes:
  595. if axis.axisTag == axisTag:
  596. axisLimits = axis
  597. break
  598. if axisLimits is None:
  599. return ""
  600. axisLimits = (axisLimits.minValue, axisLimits.defaultValue, axisLimits.maxValue)
  601. log.info("Planning %s axis.", axisName)
  602. if "avar" in font:
  603. existingMapping = font["avar"].segments[axisTag]
  604. font["avar"].segments[axisTag] = {}
  605. else:
  606. existingMapping = None
  607. if values is not None and isinstance(values, str):
  608. values = [float(w) for w in values.split()]
  609. if designLimits is not None and isinstance(designLimits, str):
  610. designLimits = [float(d) for d in options.designLimits.split(":")]
  611. assert (
  612. len(designLimits) == 3
  613. and designLimits[0] <= designLimits[1] <= designLimits[2]
  614. )
  615. else:
  616. designLimits = None
  617. if pins is not None and isinstance(pins, str):
  618. newPins = {}
  619. for pin in pins.split():
  620. before, after = pin.split(":")
  621. newPins[float(before)] = float(after)
  622. pins = newPins
  623. del newPins
  624. mapping, mappingNormalized = planFunc(
  625. font.getGlyphSet,
  626. axisLimits,
  627. values,
  628. samples=samples,
  629. glyphs=glyphs,
  630. designLimits=designLimits,
  631. pins=pins,
  632. sanitize=sanitize,
  633. )
  634. if plot:
  635. from matplotlib import pyplot
  636. pyplot.plot(
  637. sorted(mappingNormalized),
  638. [mappingNormalized[k] for k in sorted(mappingNormalized)],
  639. )
  640. pyplot.show()
  641. if existingMapping is not None:
  642. log.info("Existing %s mapping:\n%s", axisName, pformat(existingMapping))
  643. if mapping:
  644. if "avar" not in font:
  645. addEmptyAvar(font)
  646. font["avar"].segments[axisTag] = mappingNormalized
  647. else:
  648. if "avar" in font:
  649. font["avar"].segments[axisTag] = {}
  650. designspaceSnippet = makeDesignspaceSnippet(
  651. axisTag,
  652. axisName,
  653. axisLimits,
  654. mapping,
  655. )
  656. return designspaceSnippet
  657. def main(args=None):
  658. """Plan the standard axis mappings for a variable font"""
  659. if args is None:
  660. import sys
  661. args = sys.argv[1:]
  662. from fontTools import configLogger
  663. from fontTools.ttLib import TTFont
  664. import argparse
  665. parser = argparse.ArgumentParser(
  666. "fonttools varLib.avarPlanner",
  667. description="Plan `avar` table for variable font",
  668. )
  669. parser.add_argument("font", metavar="varfont.ttf", help="Variable-font file.")
  670. parser.add_argument(
  671. "-o",
  672. "--output-file",
  673. type=str,
  674. help="Output font file name.",
  675. )
  676. parser.add_argument(
  677. "--weights", type=str, help="Space-separate list of weights to generate."
  678. )
  679. parser.add_argument(
  680. "--widths", type=str, help="Space-separate list of widths to generate."
  681. )
  682. parser.add_argument(
  683. "--slants", type=str, help="Space-separate list of slants to generate."
  684. )
  685. parser.add_argument(
  686. "--sizes", type=str, help="Space-separate list of optical-sizes to generate."
  687. )
  688. parser.add_argument("--samples", type=int, help="Number of samples.")
  689. parser.add_argument(
  690. "-s", "--sanitize", action="store_true", help="Sanitize axis limits"
  691. )
  692. parser.add_argument(
  693. "-g",
  694. "--glyphs",
  695. type=str,
  696. help="Space-separate list of glyphs to use for sampling.",
  697. )
  698. parser.add_argument(
  699. "--weight-design-limits",
  700. type=str,
  701. help="min:default:max in design units for the `wght` axis.",
  702. )
  703. parser.add_argument(
  704. "--width-design-limits",
  705. type=str,
  706. help="min:default:max in design units for the `wdth` axis.",
  707. )
  708. parser.add_argument(
  709. "--slant-design-limits",
  710. type=str,
  711. help="min:default:max in design units for the `slnt` axis.",
  712. )
  713. parser.add_argument(
  714. "--optical-size-design-limits",
  715. type=str,
  716. help="min:default:max in design units for the `opsz` axis.",
  717. )
  718. parser.add_argument(
  719. "--weight-pins",
  720. type=str,
  721. help="Space-separate list of before:after pins for the `wght` axis.",
  722. )
  723. parser.add_argument(
  724. "--width-pins",
  725. type=str,
  726. help="Space-separate list of before:after pins for the `wdth` axis.",
  727. )
  728. parser.add_argument(
  729. "--slant-pins",
  730. type=str,
  731. help="Space-separate list of before:after pins for the `slnt` axis.",
  732. )
  733. parser.add_argument(
  734. "--optical-size-pins",
  735. type=str,
  736. help="Space-separate list of before:after pins for the `opsz` axis.",
  737. )
  738. parser.add_argument(
  739. "-p", "--plot", action="store_true", help="Plot the resulting mapping."
  740. )
  741. logging_group = parser.add_mutually_exclusive_group(required=False)
  742. logging_group.add_argument(
  743. "-v", "--verbose", action="store_true", help="Run more verbosely."
  744. )
  745. logging_group.add_argument(
  746. "-q", "--quiet", action="store_true", help="Turn verbosity off."
  747. )
  748. options = parser.parse_args(args)
  749. configLogger(
  750. level=("DEBUG" if options.verbose else "WARNING" if options.quiet else "INFO")
  751. )
  752. font = TTFont(options.font)
  753. if not "fvar" in font:
  754. log.error("Not a variable font.")
  755. return 1
  756. if options.glyphs is not None:
  757. glyphs = options.glyphs.split()
  758. if ":" in options.glyphs:
  759. glyphs = {}
  760. for g in options.glyphs.split():
  761. if ":" in g:
  762. glyph, frequency = g.split(":")
  763. glyphs[glyph] = float(frequency)
  764. else:
  765. glyphs[g] = 1.0
  766. else:
  767. glyphs = None
  768. designspaceSnippets = []
  769. designspaceSnippets.append(
  770. processAxis(
  771. font,
  772. planWeightAxis,
  773. "wght",
  774. "Weight",
  775. values=options.weights,
  776. samples=options.samples,
  777. glyphs=glyphs,
  778. designLimits=options.weight_design_limits,
  779. pins=options.weight_pins,
  780. sanitize=options.sanitize,
  781. plot=options.plot,
  782. )
  783. )
  784. designspaceSnippets.append(
  785. processAxis(
  786. font,
  787. planWidthAxis,
  788. "wdth",
  789. "Width",
  790. values=options.widths,
  791. samples=options.samples,
  792. glyphs=glyphs,
  793. designLimits=options.width_design_limits,
  794. pins=options.width_pins,
  795. sanitize=options.sanitize,
  796. plot=options.plot,
  797. )
  798. )
  799. designspaceSnippets.append(
  800. processAxis(
  801. font,
  802. planSlantAxis,
  803. "slnt",
  804. "Slant",
  805. values=options.slants,
  806. samples=options.samples,
  807. glyphs=glyphs,
  808. designLimits=options.slant_design_limits,
  809. pins=options.slant_pins,
  810. sanitize=options.sanitize,
  811. plot=options.plot,
  812. )
  813. )
  814. designspaceSnippets.append(
  815. processAxis(
  816. font,
  817. planOpticalSizeAxis,
  818. "opsz",
  819. "OpticalSize",
  820. values=options.sizes,
  821. samples=options.samples,
  822. glyphs=glyphs,
  823. designLimits=options.optical_size_design_limits,
  824. pins=options.optical_size_pins,
  825. sanitize=options.sanitize,
  826. plot=options.plot,
  827. )
  828. )
  829. log.info("Designspace snippet:")
  830. for snippet in designspaceSnippets:
  831. if snippet:
  832. print(snippet)
  833. if options.output_file is None:
  834. outfile = makeOutputFileName(options.font, overWrite=True, suffix=".avar")
  835. else:
  836. outfile = options.output_file
  837. if outfile:
  838. log.info("Saving %s", outfile)
  839. font.save(outfile)
  840. if __name__ == "__main__":
  841. import sys
  842. sys.exit(main())