voltToFea.py 28 KB

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