Debian Codegraph @

src/babelfont/fontFilters/glyphs3fea.py

raw
1 import logging
2 import re
3
4 from babelfont import Font
5
6 logger = logging.getLogger(__name__)
7
8
9 class NibbleParser:
10 def __init__(self, target):
11 self.string = target
12
13 def __call__(self, regex):
14 if m := re.match(regex, self.string):
15 self.string = re.sub(regex, "", self.string)
16 return m
17 return None
18
19
20 def translate_glyphs3_fea(font: Font, args=None):
21 font.features.features = [
22 (key, _translate(code, {"index": 0, "font": font, "tag": key}))
23 for key, code in font.features.features
24 ]
25
26
27 def _translate(code, state):
28 return re.sub(
29 "#ifdef VARIABLE(.*)#endif",
30 lambda m: __translate(m, state),
31 code,
32 flags=re.DOTALL,
33 ).replace("{;", "{")
34
35
36 def __translate(match, state):
37 newstatements = []
38
39 def name():
40 return f"__condition_{state['tag']}_{state['index']}"
41
42 axis_map = {a.tag: a for a in state["font"].axes}
43
44 for statement in match.group(1).split(";"):
45 p = NibbleParser(statement)
46 if p(r"^\s*condition\s+"):
47 axes = []
48 while axis := p(
49 r"""(?x)
50 (?:([\d.]+)\s*<)? # Axis minimum value
51 \s*(\w+)\s* # Axis tag
52 (?:<\s*([\d.]+))? # Axis maximum value
53 ,?\s* # Optional comma
54 """
55 ):
56 min_v, tag, max_v = axis.groups()
57 if tag not in axis_map:
58 raise ValueError(f"Axis {tag} not found in condition statement")
59 if min_v is None:
60 min_v = axis_map[tag].minimum
61 if max_v is None:
62 max_v = axis_map[tag].maximum
63 axes.append(f"{tag} {min_v} {max_v}")
64 if not axes:
65 raise ValueError("No axis definition found for condition")
66
67 if not newstatements:
68 newstatements.append("")
69 newstatements.append(f"}} {state['tag']}")
70 state["index"] += 1
71 newstatements.append(f"conditionset {name()} {{")
72 newstatements.extend(axes)
73 newstatements.append(f"}} {name()}")
74 newstatements.append(f"variation {state['tag']} {name()} {{")
75 else:
76 newstatements.append(statement)
77 return ";".join(newstatements)