split_slnt_vf.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. """
  2. ...
  3. """
  4. import argparse
  5. import sys
  6. import os
  7. from fontTools.ttLib import TTFont
  8. from fontTools.ttLib.tables import otTables as ot
  9. from fontTools.otlLib.builder import buildStatTable, _addName
  10. from fontTools.varLib.instancer import (
  11. instantiateVariableFont,
  12. sanityCheckVariableTables
  13. )
  14. def split_slnt(ttfont, out_dir):
  15. """Use varlib instance to split a variable font if it contains a
  16. slnt or ital axis."""
  17. sanityCheckVariableTables(ttfont)
  18. axes = {a.axisTag: a for a in ttfont['fvar'].axes}
  19. ital_angle = axes['ital'].maxValue
  20. roman = instantiateVariableFont(ttfont, {"ital": 0}, updateFontNames=True)
  21. italic = instantiateVariableFont(ttfont, {"ital": ital_angle}, updateFontNames=True)
  22. _update_roman_stat(roman)
  23. _update_italic_stat(italic)
  24. roman_filename = os.path.join(
  25. out_dir,
  26. vf_filename(roman)
  27. )
  28. roman.save(roman_filename)
  29. italic_filename = os.path.join(
  30. out_dir,
  31. vf_filename(italic)
  32. )
  33. italic.save(italic_filename)
  34. def _update_roman_stat(ttfont):
  35. stat = ttfont['STAT'].table
  36. record = ot.AxisValue()
  37. record.AxisIndex = 2
  38. record.Flags = 2
  39. record.ValueNameID = 296 # Roman
  40. record.LinkedValue = 1
  41. record.Value = 0
  42. record.Format = 3
  43. stat.AxisValueArray.AxisValue[-1] = record
  44. def _update_italic_stat(ttfont):
  45. stat = ttfont['STAT'].table
  46. record = ot.AxisValue()
  47. record.AxisIndex = 2
  48. record.Flags = 0
  49. record.ValueNameID = 258 # Italic
  50. record.Value = 1.0
  51. record.Format = 1
  52. stat.AxisValueArray.AxisValue[-1] = record
  53. def vf_filename(ttfont):
  54. axes = sorted([a.axisTag for a in ttfont['fvar'].axes])
  55. axes = ",".join(axes)
  56. family_name = ttfont['name'].getName(1, 3, 1, 1033)
  57. name = family_name.toUnicode()
  58. if "Italic" in ttfont['name'].getName(2, 3, 1, 1033).toUnicode():
  59. return f"{name}-Italic[{axes}].ttf"
  60. return f"{name}[{axes}].ttf"
  61. def main():
  62. ttfont = TTFont(sys.argv[1])
  63. split_slnt(ttfont, sys.argv[2])
  64. if __name__ == "__main__":
  65. main()