voltToFea.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. """\
  2. MS VOLT ``.vtp`` to AFDKO ``.fea`` OpenType Layout converter.
  3. Usage
  4. -----
  5. To convert a VTP project file:
  6. $ fonttools voltLib.voltToFea input.vtp output.fea
  7. It is also possible convert font files with `TSIV` table (as saved from Volt),
  8. in this case the glyph names used in the Volt project will be mapped to the
  9. actual glyph names in the font files when written to the feature file:
  10. $ fonttools voltLib.voltToFea input.ttf output.fea
  11. The ``--quiet`` option can be used to suppress warnings.
  12. The ``--traceback`` can be used to get Python traceback in case of exceptions,
  13. instead of suppressing the traceback.
  14. Limitations
  15. -----------
  16. * Not all VOLT features are supported, the script will error if it it
  17. encounters something it does not understand. Please report an issue if this
  18. happens.
  19. * AFDKO feature file syntax for mark positioning is awkward and does not allow
  20. setting the mark coverage. It also defines mark anchors globally, as a result
  21. some mark positioning lookups might cover many marks than what was in the VOLT
  22. file. This should not be an issue in practice, but if it is then the only way
  23. is to modify the VOLT file or the generated feature file manually to use unique
  24. mark anchors for each lookup.
  25. * VOLT allows subtable breaks in any lookup type, but AFDKO feature file
  26. implementations vary in their support; currently AFDKO’s makeOTF supports
  27. subtable breaks in pair positioning lookups only, while FontTools’ feaLib
  28. support it for most substitution lookups and only some positioning lookups.
  29. """
  30. import logging
  31. import re
  32. from io import StringIO
  33. from fontTools.feaLib import ast
  34. from fontTools.ttLib import TTFont, TTLibError
  35. from fontTools.voltLib import ast as VAst
  36. from fontTools.voltLib.parser import Parser as VoltParser
  37. log = logging.getLogger("fontTools.voltLib.voltToFea")
  38. TABLES = ["GDEF", "GSUB", "GPOS"]
  39. class MarkClassDefinition(ast.MarkClassDefinition):
  40. def asFea(self, indent=""):
  41. res = ""
  42. if not getattr(self, "used", False):
  43. res += "#"
  44. res += ast.MarkClassDefinition.asFea(self, indent)
  45. return res
  46. # For sorting voltLib.ast.GlyphDefinition, see its use below.
  47. class Group:
  48. def __init__(self, group):
  49. self.name = group.name.lower()
  50. self.groups = [
  51. x.group.lower() for x in group.enum.enum if isinstance(x, VAst.GroupName)
  52. ]
  53. def __lt__(self, other):
  54. if self.name in other.groups:
  55. return True
  56. if other.name in self.groups:
  57. return False
  58. if self.groups and not other.groups:
  59. return False
  60. if not self.groups and other.groups:
  61. return True
  62. class VoltToFea:
  63. _NOT_LOOKUP_NAME_RE = re.compile(r"[^A-Za-z_0-9.]")
  64. _NOT_CLASS_NAME_RE = re.compile(r"[^A-Za-z_0-9.\-]")
  65. def __init__(self, file_or_path, font=None):
  66. self._file_or_path = file_or_path
  67. self._font = font
  68. self._glyph_map = {}
  69. self._glyph_order = None
  70. self._gdef = {}
  71. self._glyphclasses = {}
  72. self._features = {}
  73. self._lookups = {}
  74. self._marks = set()
  75. self._ligatures = {}
  76. self._markclasses = {}
  77. self._anchors = {}
  78. self._settings = {}
  79. self._lookup_names = {}
  80. self._class_names = {}
  81. def _lookupName(self, name):
  82. if name not in self._lookup_names:
  83. res = self._NOT_LOOKUP_NAME_RE.sub("_", name)
  84. while res in self._lookup_names.values():
  85. res += "_"
  86. self._lookup_names[name] = res
  87. return self._lookup_names[name]
  88. def _className(self, name):
  89. if name not in self._class_names:
  90. res = self._NOT_CLASS_NAME_RE.sub("_", name)
  91. while res in self._class_names.values():
  92. res += "_"
  93. self._class_names[name] = res
  94. return self._class_names[name]
  95. def _collectStatements(self, doc, tables):
  96. # Collect and sort group definitions first, to make sure a group
  97. # definition that references other groups comes after them since VOLT
  98. # does not enforce such ordering, and feature file require it.
  99. groups = [s for s in doc.statements if isinstance(s, VAst.GroupDefinition)]
  100. for statement in sorted(groups, key=lambda x: Group(x)):
  101. self._groupDefinition(statement)
  102. for statement in doc.statements:
  103. if isinstance(statement, VAst.GlyphDefinition):
  104. self._glyphDefinition(statement)
  105. elif isinstance(statement, VAst.AnchorDefinition):
  106. if "GPOS" in tables:
  107. self._anchorDefinition(statement)
  108. elif isinstance(statement, VAst.SettingDefinition):
  109. self._settingDefinition(statement)
  110. elif isinstance(statement, VAst.GroupDefinition):
  111. pass # Handled above
  112. elif isinstance(statement, VAst.ScriptDefinition):
  113. self._scriptDefinition(statement)
  114. elif not isinstance(statement, VAst.LookupDefinition):
  115. raise NotImplementedError(statement)
  116. # Lookup definitions need to be handled last as they reference glyph
  117. # and mark classes that might be defined after them.
  118. for statement in doc.statements:
  119. if isinstance(statement, VAst.LookupDefinition):
  120. if statement.pos and "GPOS" not in tables:
  121. continue
  122. if statement.sub and "GSUB" not in tables:
  123. continue
  124. self._lookupDefinition(statement)
  125. def _buildFeatureFile(self, tables):
  126. doc = ast.FeatureFile()
  127. statements = doc.statements
  128. if self._glyphclasses:
  129. statements.append(ast.Comment("# Glyph classes"))
  130. statements.extend(self._glyphclasses.values())
  131. if self._markclasses:
  132. statements.append(ast.Comment("\n# Mark classes"))
  133. statements.extend(c[1] for c in sorted(self._markclasses.items()))
  134. if self._lookups:
  135. statements.append(ast.Comment("\n# Lookups"))
  136. for lookup in self._lookups.values():
  137. statements.extend(getattr(lookup, "targets", []))
  138. statements.append(lookup)
  139. # Prune features
  140. features = self._features.copy()
  141. for ftag in features:
  142. scripts = features[ftag]
  143. for stag in scripts:
  144. langs = scripts[stag]
  145. for ltag in langs:
  146. langs[ltag] = [l for l in langs[ltag] if l.lower() in self._lookups]
  147. scripts[stag] = {t: l for t, l in langs.items() if l}
  148. features[ftag] = {t: s for t, s in scripts.items() if s}
  149. features = {t: f for t, f in features.items() if f}
  150. if features:
  151. statements.append(ast.Comment("# Features"))
  152. for ftag, scripts in features.items():
  153. feature = ast.FeatureBlock(ftag)
  154. stags = sorted(scripts, key=lambda k: 0 if k == "DFLT" else 1)
  155. for stag in stags:
  156. feature.statements.append(ast.ScriptStatement(stag))
  157. ltags = sorted(scripts[stag], key=lambda k: 0 if k == "dflt" else 1)
  158. for ltag in ltags:
  159. include_default = True if ltag == "dflt" else False
  160. feature.statements.append(
  161. ast.LanguageStatement(ltag, include_default=include_default)
  162. )
  163. for name in scripts[stag][ltag]:
  164. lookup = self._lookups[name.lower()]
  165. lookupref = ast.LookupReferenceStatement(lookup)
  166. feature.statements.append(lookupref)
  167. statements.append(feature)
  168. if self._gdef and "GDEF" in tables:
  169. classes = []
  170. for name in ("BASE", "MARK", "LIGATURE", "COMPONENT"):
  171. if name in self._gdef:
  172. classname = "GDEF_" + name.lower()
  173. glyphclass = ast.GlyphClassDefinition(classname, self._gdef[name])
  174. statements.append(glyphclass)
  175. classes.append(ast.GlyphClassName(glyphclass))
  176. else:
  177. classes.append(None)
  178. gdef = ast.TableBlock("GDEF")
  179. gdef.statements.append(ast.GlyphClassDefStatement(*classes))
  180. statements.append(gdef)
  181. return doc
  182. def convert(self, tables=None):
  183. doc = VoltParser(self._file_or_path).parse()
  184. if tables is None:
  185. tables = TABLES
  186. if self._font is not None:
  187. self._glyph_order = self._font.getGlyphOrder()
  188. self._collectStatements(doc, tables)
  189. fea = self._buildFeatureFile(tables)
  190. return fea.asFea()
  191. def _glyphName(self, glyph):
  192. try:
  193. name = glyph.glyph
  194. except AttributeError:
  195. name = glyph
  196. return ast.GlyphName(self._glyph_map.get(name, name))
  197. def _groupName(self, group):
  198. try:
  199. name = group.group
  200. except AttributeError:
  201. name = group
  202. return ast.GlyphClassName(self._glyphclasses[name.lower()])
  203. def _coverage(self, coverage):
  204. items = []
  205. for item in coverage:
  206. if isinstance(item, VAst.GlyphName):
  207. items.append(self._glyphName(item))
  208. elif isinstance(item, VAst.GroupName):
  209. items.append(self._groupName(item))
  210. elif isinstance(item, VAst.Enum):
  211. items.append(self._enum(item))
  212. elif isinstance(item, VAst.Range):
  213. items.append((item.start, item.end))
  214. else:
  215. raise NotImplementedError(item)
  216. return items
  217. def _enum(self, enum):
  218. return ast.GlyphClass(self._coverage(enum.enum))
  219. def _context(self, context):
  220. out = []
  221. for item in context:
  222. coverage = self._coverage(item)
  223. if not isinstance(coverage, (tuple, list)):
  224. coverage = [coverage]
  225. out.extend(coverage)
  226. return out
  227. def _groupDefinition(self, group):
  228. name = self._className(group.name)
  229. glyphs = self._enum(group.enum)
  230. glyphclass = ast.GlyphClassDefinition(name, glyphs)
  231. self._glyphclasses[group.name.lower()] = glyphclass
  232. def _glyphDefinition(self, glyph):
  233. try:
  234. self._glyph_map[glyph.name] = self._glyph_order[glyph.id]
  235. except TypeError:
  236. pass
  237. if glyph.type in ("BASE", "MARK", "LIGATURE", "COMPONENT"):
  238. if glyph.type not in self._gdef:
  239. self._gdef[glyph.type] = ast.GlyphClass()
  240. self._gdef[glyph.type].glyphs.append(self._glyphName(glyph.name))
  241. if glyph.type == "MARK":
  242. self._marks.add(glyph.name)
  243. elif glyph.type == "LIGATURE":
  244. self._ligatures[glyph.name] = glyph.components
  245. def _scriptDefinition(self, script):
  246. stag = script.tag
  247. for lang in script.langs:
  248. ltag = lang.tag
  249. for feature in lang.features:
  250. lookups = {l.split("\\")[0]: True for l in feature.lookups}
  251. ftag = feature.tag
  252. if ftag not in self._features:
  253. self._features[ftag] = {}
  254. if stag not in self._features[ftag]:
  255. self._features[ftag][stag] = {}
  256. assert ltag not in self._features[ftag][stag]
  257. self._features[ftag][stag][ltag] = lookups.keys()
  258. def _settingDefinition(self, setting):
  259. if setting.name.startswith("COMPILER_"):
  260. self._settings[setting.name] = setting.value
  261. else:
  262. log.warning(f"Unsupported setting ignored: {setting.name}")
  263. def _adjustment(self, adjustment):
  264. adv, dx, dy, adv_adjust_by, dx_adjust_by, dy_adjust_by = adjustment
  265. adv_device = adv_adjust_by and adv_adjust_by.items() or None
  266. dx_device = dx_adjust_by and dx_adjust_by.items() or None
  267. dy_device = dy_adjust_by and dy_adjust_by.items() or None
  268. return ast.ValueRecord(
  269. xPlacement=dx,
  270. yPlacement=dy,
  271. xAdvance=adv,
  272. xPlaDevice=dx_device,
  273. yPlaDevice=dy_device,
  274. xAdvDevice=adv_device,
  275. )
  276. def _anchor(self, adjustment):
  277. adv, dx, dy, adv_adjust_by, dx_adjust_by, dy_adjust_by = adjustment
  278. assert not adv_adjust_by
  279. dx_device = dx_adjust_by and dx_adjust_by.items() or None
  280. dy_device = dy_adjust_by and dy_adjust_by.items() or None
  281. return ast.Anchor(
  282. dx or 0,
  283. dy or 0,
  284. xDeviceTable=dx_device or None,
  285. yDeviceTable=dy_device or None,
  286. )
  287. def _anchorDefinition(self, anchordef):
  288. anchorname = anchordef.name
  289. glyphname = anchordef.glyph_name
  290. anchor = self._anchor(anchordef.pos)
  291. if anchorname.startswith("MARK_"):
  292. name = "_".join(anchorname.split("_")[1:])
  293. markclass = ast.MarkClass(self._className(name))
  294. glyph = self._glyphName(glyphname)
  295. markdef = MarkClassDefinition(markclass, anchor, glyph)
  296. self._markclasses[(glyphname, anchorname)] = markdef
  297. else:
  298. if glyphname not in self._anchors:
  299. self._anchors[glyphname] = {}
  300. if anchorname not in self._anchors[glyphname]:
  301. self._anchors[glyphname][anchorname] = {}
  302. self._anchors[glyphname][anchorname][anchordef.component] = anchor
  303. def _gposLookup(self, lookup, fealookup):
  304. statements = fealookup.statements
  305. pos = lookup.pos
  306. if isinstance(pos, VAst.PositionAdjustPairDefinition):
  307. for (idx1, idx2), (pos1, pos2) in pos.adjust_pair.items():
  308. coverage_1 = pos.coverages_1[idx1 - 1]
  309. coverage_2 = pos.coverages_2[idx2 - 1]
  310. # If not both are groups, use “enum pos” otherwise makeotf will
  311. # fail.
  312. enumerated = False
  313. for item in coverage_1 + coverage_2:
  314. if not isinstance(item, VAst.GroupName):
  315. enumerated = True
  316. glyphs1 = self._coverage(coverage_1)
  317. glyphs2 = self._coverage(coverage_2)
  318. record1 = self._adjustment(pos1)
  319. record2 = self._adjustment(pos2)
  320. assert len(glyphs1) == 1
  321. assert len(glyphs2) == 1
  322. statements.append(
  323. ast.PairPosStatement(
  324. glyphs1[0], record1, glyphs2[0], record2, enumerated=enumerated
  325. )
  326. )
  327. elif isinstance(pos, VAst.PositionAdjustSingleDefinition):
  328. for a, b in pos.adjust_single:
  329. glyphs = self._coverage(a)
  330. record = self._adjustment(b)
  331. assert len(glyphs) == 1
  332. statements.append(
  333. ast.SinglePosStatement([(glyphs[0], record)], [], [], False)
  334. )
  335. elif isinstance(pos, VAst.PositionAttachDefinition):
  336. anchors = {}
  337. for marks, classname in pos.coverage_to:
  338. for mark in marks:
  339. # Set actually used mark classes. Basically a hack to get
  340. # around the feature file syntax limitation of making mark
  341. # classes global and not allowing mark positioning to
  342. # specify mark coverage.
  343. for name in mark.glyphSet():
  344. key = (name, "MARK_" + classname)
  345. self._markclasses[key].used = True
  346. markclass = ast.MarkClass(self._className(classname))
  347. for base in pos.coverage:
  348. for name in base.glyphSet():
  349. if name not in anchors:
  350. anchors[name] = []
  351. if classname not in anchors[name]:
  352. anchors[name].append(classname)
  353. for name in anchors:
  354. components = 1
  355. if name in self._ligatures:
  356. components = self._ligatures[name]
  357. marks = []
  358. for mark in anchors[name]:
  359. markclass = ast.MarkClass(self._className(mark))
  360. for component in range(1, components + 1):
  361. if len(marks) < component:
  362. marks.append([])
  363. anchor = None
  364. if component in self._anchors[name][mark]:
  365. anchor = self._anchors[name][mark][component]
  366. marks[component - 1].append((anchor, markclass))
  367. base = self._glyphName(name)
  368. if name in self._marks:
  369. mark = ast.MarkMarkPosStatement(base, marks[0])
  370. elif name in self._ligatures:
  371. mark = ast.MarkLigPosStatement(base, marks)
  372. else:
  373. mark = ast.MarkBasePosStatement(base, marks[0])
  374. statements.append(mark)
  375. elif isinstance(pos, VAst.PositionAttachCursiveDefinition):
  376. # Collect enter and exit glyphs
  377. enter_coverage = []
  378. for coverage in pos.coverages_enter:
  379. for base in coverage:
  380. for name in base.glyphSet():
  381. enter_coverage.append(name)
  382. exit_coverage = []
  383. for coverage in pos.coverages_exit:
  384. for base in coverage:
  385. for name in base.glyphSet():
  386. exit_coverage.append(name)
  387. # Write enter anchors, also check if the glyph has exit anchor and
  388. # write it, too.
  389. for name in enter_coverage:
  390. glyph = self._glyphName(name)
  391. entry = self._anchors[name]["entry"][1]
  392. exit = None
  393. if name in exit_coverage:
  394. exit = self._anchors[name]["exit"][1]
  395. exit_coverage.pop(exit_coverage.index(name))
  396. statements.append(ast.CursivePosStatement(glyph, entry, exit))
  397. # Write any remaining exit anchors.
  398. for name in exit_coverage:
  399. glyph = self._glyphName(name)
  400. exit = self._anchors[name]["exit"][1]
  401. statements.append(ast.CursivePosStatement(glyph, None, exit))
  402. else:
  403. raise NotImplementedError(pos)
  404. def _gposContextLookup(
  405. self, lookup, prefix, suffix, ignore, fealookup, targetlookup
  406. ):
  407. statements = fealookup.statements
  408. assert not lookup.reversal
  409. pos = lookup.pos
  410. if isinstance(pos, VAst.PositionAdjustPairDefinition):
  411. for (idx1, idx2), (pos1, pos2) in pos.adjust_pair.items():
  412. glyphs1 = self._coverage(pos.coverages_1[idx1 - 1])
  413. glyphs2 = self._coverage(pos.coverages_2[idx2 - 1])
  414. assert len(glyphs1) == 1
  415. assert len(glyphs2) == 1
  416. glyphs = (glyphs1[0], glyphs2[0])
  417. if ignore:
  418. statement = ast.IgnorePosStatement([(prefix, glyphs, suffix)])
  419. else:
  420. lookups = (targetlookup, targetlookup)
  421. statement = ast.ChainContextPosStatement(
  422. prefix, glyphs, suffix, lookups
  423. )
  424. statements.append(statement)
  425. elif isinstance(pos, VAst.PositionAdjustSingleDefinition):
  426. glyphs = [ast.GlyphClass()]
  427. for a, b in pos.adjust_single:
  428. glyph = self._coverage(a)
  429. glyphs[0].extend(glyph)
  430. if ignore:
  431. statement = ast.IgnorePosStatement([(prefix, glyphs, suffix)])
  432. else:
  433. statement = ast.ChainContextPosStatement(
  434. prefix, glyphs, suffix, [targetlookup]
  435. )
  436. statements.append(statement)
  437. elif isinstance(pos, VAst.PositionAttachDefinition):
  438. glyphs = [ast.GlyphClass()]
  439. for coverage, _ in pos.coverage_to:
  440. glyphs[0].extend(self._coverage(coverage))
  441. if ignore:
  442. statement = ast.IgnorePosStatement([(prefix, glyphs, suffix)])
  443. else:
  444. statement = ast.ChainContextPosStatement(
  445. prefix, glyphs, suffix, [targetlookup]
  446. )
  447. statements.append(statement)
  448. else:
  449. raise NotImplementedError(pos)
  450. def _gsubLookup(self, lookup, prefix, suffix, ignore, chain, fealookup):
  451. statements = fealookup.statements
  452. sub = lookup.sub
  453. for key, val in sub.mapping.items():
  454. if not key or not val:
  455. path, line, column = sub.location
  456. log.warning(f"{path}:{line}:{column}: Ignoring empty substitution")
  457. continue
  458. statement = None
  459. glyphs = self._coverage(key)
  460. replacements = self._coverage(val)
  461. if ignore:
  462. chain_context = (prefix, glyphs, suffix)
  463. statement = ast.IgnoreSubstStatement([chain_context])
  464. elif isinstance(sub, VAst.SubstitutionSingleDefinition):
  465. assert len(glyphs) == 1
  466. assert len(replacements) == 1
  467. statement = ast.SingleSubstStatement(
  468. glyphs, replacements, prefix, suffix, chain
  469. )
  470. elif isinstance(sub, VAst.SubstitutionReverseChainingSingleDefinition):
  471. assert len(glyphs) == 1
  472. assert len(replacements) == 1
  473. statement = ast.ReverseChainSingleSubstStatement(
  474. prefix, suffix, glyphs, replacements
  475. )
  476. elif isinstance(sub, VAst.SubstitutionMultipleDefinition):
  477. assert len(glyphs) == 1
  478. statement = ast.MultipleSubstStatement(
  479. prefix, glyphs[0], suffix, replacements, chain
  480. )
  481. elif isinstance(sub, VAst.SubstitutionLigatureDefinition):
  482. assert len(replacements) == 1
  483. statement = ast.LigatureSubstStatement(
  484. prefix, glyphs, suffix, replacements[0], chain
  485. )
  486. else:
  487. raise NotImplementedError(sub)
  488. statements.append(statement)
  489. def _lookupDefinition(self, lookup):
  490. mark_attachement = None
  491. mark_filtering = None
  492. flags = 0
  493. if lookup.direction == "RTL":
  494. flags |= 1
  495. if not lookup.process_base:
  496. flags |= 2
  497. # FIXME: Does VOLT support this?
  498. # if not lookup.process_ligatures:
  499. # flags |= 4
  500. if not lookup.process_marks:
  501. flags |= 8
  502. elif isinstance(lookup.process_marks, str):
  503. mark_attachement = self._groupName(lookup.process_marks)
  504. elif lookup.mark_glyph_set is not None:
  505. mark_filtering = self._groupName(lookup.mark_glyph_set)
  506. lookupflags = None
  507. if flags or mark_attachement is not None or mark_filtering is not None:
  508. lookupflags = ast.LookupFlagStatement(
  509. flags, mark_attachement, mark_filtering
  510. )
  511. if "\\" in lookup.name:
  512. # Merge sub lookups as subtables (lookups named “base\sub”),
  513. # makeotf/feaLib will issue a warning and ignore the subtable
  514. # statement if it is not a pairpos lookup, though.
  515. name = lookup.name.split("\\")[0]
  516. if name.lower() not in self._lookups:
  517. fealookup = ast.LookupBlock(self._lookupName(name))
  518. if lookupflags is not None:
  519. fealookup.statements.append(lookupflags)
  520. fealookup.statements.append(ast.Comment("# " + lookup.name))
  521. else:
  522. fealookup = self._lookups[name.lower()]
  523. fealookup.statements.append(ast.SubtableStatement())
  524. fealookup.statements.append(ast.Comment("# " + lookup.name))
  525. self._lookups[name.lower()] = fealookup
  526. else:
  527. fealookup = ast.LookupBlock(self._lookupName(lookup.name))
  528. if lookupflags is not None:
  529. fealookup.statements.append(lookupflags)
  530. self._lookups[lookup.name.lower()] = fealookup
  531. if lookup.comments is not None:
  532. fealookup.statements.append(ast.Comment("# " + lookup.comments))
  533. contexts = []
  534. if lookup.context:
  535. for context in lookup.context:
  536. prefix = self._context(context.left)
  537. suffix = self._context(context.right)
  538. ignore = context.ex_or_in == "EXCEPT_CONTEXT"
  539. contexts.append([prefix, suffix, ignore, False])
  540. # It seems that VOLT will create contextual substitution using
  541. # only the input if there is no other contexts in this lookup.
  542. if ignore and len(lookup.context) == 1:
  543. contexts.append([[], [], False, True])
  544. else:
  545. contexts.append([[], [], False, False])
  546. targetlookup = None
  547. for prefix, suffix, ignore, chain in contexts:
  548. if lookup.sub is not None:
  549. self._gsubLookup(lookup, prefix, suffix, ignore, chain, fealookup)
  550. if lookup.pos is not None:
  551. if self._settings.get("COMPILER_USEEXTENSIONLOOKUPS"):
  552. fealookup.use_extension = True
  553. if prefix or suffix or chain or ignore:
  554. if not ignore and targetlookup is None:
  555. targetname = self._lookupName(lookup.name + " target")
  556. targetlookup = ast.LookupBlock(targetname)
  557. fealookup.targets = getattr(fealookup, "targets", [])
  558. fealookup.targets.append(targetlookup)
  559. self._gposLookup(lookup, targetlookup)
  560. self._gposContextLookup(
  561. lookup, prefix, suffix, ignore, fealookup, targetlookup
  562. )
  563. else:
  564. self._gposLookup(lookup, fealookup)
  565. def main(args=None):
  566. """Convert MS VOLT to AFDKO feature files."""
  567. import argparse
  568. from pathlib import Path
  569. from fontTools import configLogger
  570. parser = argparse.ArgumentParser(
  571. "fonttools voltLib.voltToFea", description=main.__doc__
  572. )
  573. parser.add_argument(
  574. "input", metavar="INPUT", type=Path, help="input font/VTP file to process"
  575. )
  576. parser.add_argument(
  577. "featurefile", metavar="OUTPUT", type=Path, help="output feature file"
  578. )
  579. parser.add_argument(
  580. "-t",
  581. "--table",
  582. action="append",
  583. choices=TABLES,
  584. dest="tables",
  585. help="List of tables to write, by default all tables are written",
  586. )
  587. parser.add_argument(
  588. "-q", "--quiet", action="store_true", help="Suppress non-error messages"
  589. )
  590. parser.add_argument(
  591. "--traceback", action="store_true", help="Don’t catch exceptions"
  592. )
  593. options = parser.parse_args(args)
  594. configLogger(level=("ERROR" if options.quiet else "INFO"))
  595. file_or_path = options.input
  596. font = None
  597. try:
  598. font = TTFont(file_or_path)
  599. if "TSIV" in font:
  600. file_or_path = StringIO(font["TSIV"].data.decode("utf-8"))
  601. else:
  602. log.error('"TSIV" table is missing, font was not saved from VOLT?')
  603. return 1
  604. except TTLibError:
  605. pass
  606. converter = VoltToFea(file_or_path, font)
  607. try:
  608. fea = converter.convert(options.tables)
  609. except NotImplementedError as e:
  610. if options.traceback:
  611. raise
  612. location = getattr(e.args[0], "location", None)
  613. message = f'"{e}" is not supported'
  614. if location:
  615. path, line, column = location
  616. log.error(f"{path}:{line}:{column}: {message}")
  617. else:
  618. log.error(message)
  619. return 1
  620. with open(options.featurefile, "w") as feafile:
  621. feafile.write(fea)
  622. if __name__ == "__main__":
  623. import sys
  624. sys.exit(main())