__main__.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import argparse
  2. import logging
  3. import sys
  4. from io import StringIO
  5. from pathlib import Path
  6. from fontTools import configLogger
  7. from fontTools.feaLib.builder import addOpenTypeFeaturesFromString
  8. from fontTools.feaLib.error import FeatureLibError
  9. from fontTools.feaLib.lexer import Lexer
  10. from fontTools.misc.cliTools import makeOutputFileName
  11. from fontTools.ttLib import TTFont, TTLibError
  12. from fontTools.voltLib.parser import Parser
  13. from fontTools.voltLib.voltToFea import TABLES, VoltToFea
  14. log = logging.getLogger("fontTools.feaLib")
  15. SUPPORTED_TABLES = TABLES + ["cmap"]
  16. def invalid_fea_glyph_name(name):
  17. """Check if the glyph name is valid according to FEA syntax."""
  18. if name[0] not in Lexer.CHAR_NAME_START_:
  19. return True
  20. if any(c not in Lexer.CHAR_NAME_CONTINUATION_ for c in name[1:]):
  21. return True
  22. return False
  23. def sanitize_glyph_name(name):
  24. """Sanitize the glyph name to ensure it is valid according to FEA syntax."""
  25. sanitized = ""
  26. for i, c in enumerate(name):
  27. if i == 0 and c not in Lexer.CHAR_NAME_START_:
  28. sanitized += "a" + c
  29. elif c not in Lexer.CHAR_NAME_CONTINUATION_:
  30. sanitized += "_"
  31. else:
  32. sanitized += c
  33. return sanitized
  34. def main(args=None):
  35. """Build tables from a MS VOLT project into an OTF font"""
  36. parser = argparse.ArgumentParser(
  37. description="Use fontTools to compile MS VOLT projects."
  38. )
  39. parser.add_argument(
  40. "input",
  41. metavar="INPUT",
  42. help="Path to the input font/VTP file to process",
  43. type=Path,
  44. )
  45. parser.add_argument(
  46. "-f",
  47. "--font",
  48. metavar="INPUT_FONT",
  49. help="Path to the input font (if INPUT is a VTP file)",
  50. type=Path,
  51. )
  52. parser.add_argument(
  53. "-o",
  54. "--output",
  55. dest="output",
  56. metavar="OUTPUT",
  57. help="Path to the output font.",
  58. type=Path,
  59. )
  60. parser.add_argument(
  61. "-t",
  62. "--tables",
  63. metavar="TABLE_TAG",
  64. choices=SUPPORTED_TABLES,
  65. nargs="+",
  66. help="Specify the table(s) to be built.",
  67. )
  68. parser.add_argument(
  69. "-F",
  70. "--debug-feature-file",
  71. help="Write the generated feature file to disk.",
  72. action="store_true",
  73. )
  74. parser.add_argument(
  75. "--ship",
  76. help="Remove source VOLT tables from output font.",
  77. action="store_true",
  78. )
  79. parser.add_argument(
  80. "-v",
  81. "--verbose",
  82. help="Increase the logger verbosity. Multiple -v options are allowed.",
  83. action="count",
  84. default=0,
  85. )
  86. parser.add_argument(
  87. "-T",
  88. "--traceback",
  89. help="show traceback for exceptions.",
  90. action="store_true",
  91. )
  92. options = parser.parse_args(args)
  93. levels = ["WARNING", "INFO", "DEBUG"]
  94. configLogger(level=levels[min(len(levels) - 1, options.verbose)])
  95. output_font = options.output or Path(
  96. makeOutputFileName(options.font or options.input)
  97. )
  98. log.info(f"Compiling MS VOLT to '{output_font}'")
  99. file_or_path = options.input
  100. font = None
  101. # If the input is a font file, extract the VOLT data from the "TSIV" table
  102. try:
  103. font = TTFont(file_or_path)
  104. if "TSIV" in font:
  105. file_or_path = StringIO(font["TSIV"].data.decode("utf-8"))
  106. else:
  107. log.error('"TSIV" table is missing')
  108. return 1
  109. except TTLibError:
  110. pass
  111. # If input is not a font file, the font must be provided
  112. if font is None:
  113. if not options.font:
  114. log.error("Please provide an input font")
  115. return 1
  116. font = TTFont(options.font)
  117. # FEA syntax does not allow some glyph names that VOLT accepts, so if we
  118. # found such glyph name we will temporarily rename such glyphs.
  119. glyphOrder = font.getGlyphOrder()
  120. tempGlyphOrder = None
  121. if any(invalid_fea_glyph_name(n) for n in glyphOrder):
  122. tempGlyphOrder = []
  123. for n in glyphOrder:
  124. if invalid_fea_glyph_name(n):
  125. n = sanitize_glyph_name(n)
  126. existing = set(tempGlyphOrder) | set(glyphOrder)
  127. while n in existing:
  128. n = "a" + n
  129. tempGlyphOrder.append(n)
  130. font.setGlyphOrder(tempGlyphOrder)
  131. doc = Parser(file_or_path).parse()
  132. log.info("Converting VTP data to FEA")
  133. converter = VoltToFea(doc, font)
  134. try:
  135. fea = converter.convert(options.tables, ignore_unsupported_settings=True)
  136. except NotImplementedError as e:
  137. if options.traceback:
  138. raise
  139. location = getattr(e.args[0], "location", None)
  140. message = f'"{e}" is not supported'
  141. if location:
  142. path, line, column = location
  143. log.error(f"{path}:{line}:{column}: {message}")
  144. else:
  145. log.error(message)
  146. return 1
  147. fea_filename = options.input
  148. if options.debug_feature_file:
  149. fea_filename = output_font.with_suffix(".fea")
  150. log.info(f"Writing FEA to '{fea_filename}'")
  151. with open(fea_filename, "w") as fp:
  152. fp.write(fea)
  153. log.info("Compiling FEA to OpenType tables")
  154. try:
  155. addOpenTypeFeaturesFromString(
  156. font,
  157. fea,
  158. filename=fea_filename,
  159. tables=options.tables,
  160. )
  161. except FeatureLibError as e:
  162. if options.traceback:
  163. raise
  164. log.error(e)
  165. return 1
  166. if options.ship:
  167. for tag in ["TSIV", "TSIS", "TSIP", "TSID"]:
  168. if tag in font:
  169. del font[tag]
  170. # Restore original glyph names.
  171. if tempGlyphOrder:
  172. import io
  173. f = io.BytesIO()
  174. font.save(f)
  175. font = TTFont(f)
  176. font.setGlyphOrder(glyphOrder)
  177. font["post"].extraNames = []
  178. font.save(output_font)
  179. if __name__ == "__main__":
  180. sys.exit(main())