| 1 |
from io import StringIO |
| 2 |
import re |
| 3 |
from dataclasses import dataclass, field |
| 4 |
from typing import Any, Dict, List, Tuple |
| 5 |
|
| 6 |
from babelfont import Font |
| 7 |
from fontTools.feaLib import ast |
| 8 |
from fontTools.feaLib.parser import Parser, SymbolTable |
| 9 |
|
| 10 |
from .BaseObject import BaseObject |
| 11 |
|
| 12 |
PREFIX_MARKER = "# Prefix: " |
| 13 |
PREFIX_RE = re.compile(r"# Prefix: (.*)") |
| 14 |
|
| 15 |
|
| 16 |
@dataclass |
| 17 |
class Features(BaseObject): |
| 18 |
"""A representation of the OpenType feature code.""" |
| 19 |
|
| 20 |
classes: Dict[str, List[str]] = field( |
| 21 |
default_factory=dict, |
| 22 |
metadata={ |
| 23 |
"separate_items": True, |
| 24 |
"description": "A dictionary of classes. Each group is a list of glyph names or class names. The key should not start with @.", |
| 25 |
}, |
| 26 |
) |
| 27 |
prefixes: Dict[str, str] = field( |
| 28 |
default_factory=dict, |
| 29 |
metadata={ |
| 30 |
"separate_items": True, |
| 31 |
"description": "A dictionary of OpenType lookups and other feature code to be placed before features are defined. The keys are user-defined names, the values are AFDKO feature code.", |
| 32 |
}, |
| 33 |
) |
| 34 |
features: List[Tuple[str, str]] = field( |
| 35 |
default_factory=list, |
| 36 |
metadata={ |
| 37 |
"separate_items": True, |
| 38 |
"description": "A list of OpenType feature code, expressed as a tuple (feature tag, code).", |
| 39 |
}, |
| 40 |
) |
| 41 |
|
| 42 |
@classmethod |
| 43 |
def from_fea(cls, fea: str, glyphNames=()) -> "Features": |
| 44 |
"""Load features from a .fea file.""" |
| 45 |
parsed = Parser( |
| 46 |
StringIO(fea), followIncludes=False, glyphNames=glyphNames |
| 47 |
).parse() |
| 48 |
features = Features() |
| 49 |
currentPrefix = "anonymous" |
| 50 |
for statement in parsed.statements: |
| 51 |
if isinstance(statement, ast.GlyphClassDefinition): |
| 52 |
statement.glyphs.asFea() # This builds .original |
| 53 |
if statement.glyphs.original: |
| 54 |
features.classes[statement.name] = [ |
| 55 |
ast.asFea(x) for x in statement.glyphs.original |
| 56 |
] |
| 57 |
else: |
| 58 |
features.classes[statement.name] = list(statement.glyphs.glyphs) |
| 59 |
elif isinstance(statement, ast.FeatureBlock): |
| 60 |
features.features.append((statement.name, ast.Block.asFea(statement))) |
| 61 |
elif isinstance(statement, ast.Comment) and ( |
| 62 |
m := re.match(PREFIX_RE, statement.text) |
| 63 |
): |
| 64 |
currentPrefix = m.group(1) |
| 65 |
else: |
| 66 |
if currentPrefix not in features.prefixes: |
| 67 |
features.prefixes[currentPrefix] = "" |
| 68 |
features.prefixes[currentPrefix] += statement.asFea() |
| 69 |
return features |
| 70 |
|
| 71 |
def to_fea(self) -> str: |
| 72 |
"""Dump features to a .fea file.""" |
| 73 |
fea = "" |
| 74 |
for name, glyphs in self.classes.items(): |
| 75 |
fea += f"@{name} = [{' '.join(glyphs)}];\n" |
| 76 |
for prefix, code in self.prefixes.items(): |
| 77 |
if prefix != "anonymous": |
| 78 |
fea += f"# Prefix: {prefix}\n" |
| 79 |
fea += code + "\n" |
| 80 |
for name, code in self.features: |
| 81 |
fea += f"feature {name} {{\n{code}\n}} {name};\n" |
| 82 |
return fea |
| 83 |
|
| 84 |
def as_ast(self, font: Font) -> Dict[str, Any]: |
| 85 |
rv = { |
| 86 |
"prefixes": {}, |
| 87 |
"features": [], |
| 88 |
} |
| 89 |
glyphnames = font.glyphs.keys() |
| 90 |
lookups = SymbolTable() |
| 91 |
glyphclasses = SymbolTable() |
| 92 |
for name, glyphs in self.classes.items(): |
| 93 |
glyphcls = ast.GlyphClass(glyphs=[ast.GlyphName(g) for g in glyphs]) |
| 94 |
glyphclass = ast.GlyphClassDefinition(name, glyphcls) |
| 95 |
glyphclasses.define(name, glyphclass) |
| 96 |
|
| 97 |
for prefix, code in self.prefixes.items(): |
| 98 |
parser = Parser(StringIO(code), followIncludes=False, glyphNames=glyphnames) |
| 99 |
parser.lookups_ = lookups |
| 100 |
parser.glyphclasses_ = glyphclasses |
| 101 |
try: |
| 102 |
file = parser.parse() |
| 103 |
except Exception as e: |
| 104 |
raise ValueError(f"Error parsing feature code: {e}\n\nCode was: {code}") |
| 105 |
rv["prefixes"][prefix] = file |
| 106 |
|
| 107 |
for name, code in self.features: |
| 108 |
if name is not None and not code.startswith("feature " + name): |
| 109 |
code = f"feature {name} {{\n{code}\n}} {name};" |
| 110 |
parser = Parser(StringIO(code), followIncludes=False, glyphNames=glyphnames) |
| 111 |
parser.lookups_ = lookups |
| 112 |
parser.glyphclasses_ = glyphclasses |
| 113 |
try: |
| 114 |
file = parser.parse() |
| 115 |
except Exception as e: |
| 116 |
raise ValueError(f"Error parsing feature code: {e}\n\nCode was: {code}") |
| 117 |
rv["features"].append((name, file)) |
| 118 |
|
| 119 |
return rv |