Debian Codegraph @

Lib/fontFeatures/feaLib/Substitution.py

raw
1 # Code for converting a Substitution object into feaLib statements
2 import fontTools.feaLib.ast as feaast
3 from fontFeatures.ttLib.Substitution import lookup_type
4 from itertools import cycle
5 from typing import Union
6
7
8 def glyphref(g) -> Union[feaast.GlyphName, feaast.GlyphClass]:
9 if len(g) == 1:
10 return feaast.GlyphName(g[0])
11 return feaast.GlyphClass([feaast.GlyphName(x) for x in g])
12
13
14 # Whether or not the input or the replacement has classes (so, entire statement).
15 def has_classes(self) -> bool:
16 input_has_class = next(
17 (i for i, v in enumerate([len(x) for x in self.input]) if v > 1), None
18 )
19 replacement_has_class = next(
20 (i for i, v in enumerate([len(x) for x in self.replacement]) if v > 1), None
21 )
22
23 return input_has_class is not None or replacement_has_class is not None
24
25
26 # Excepting single glyphs, if classes are defined, the input and replacement
27 # all use classes of equal length.
28 def all_classes_equal(self) -> bool:
29 input_lengths = [len(x) for x in self.input if len(x) != 1]
30 replacement_lengths = [len(x) for x in self.replacement if len(x) != 1]
31
32 if len(input_lengths) == 0 and len(replacement_lengths) == 0:
33 return True
34
35 return len(set(input_lengths + replacement_lengths)) == 1
36
37
38 # One of the substitution/replacements has all-but-one arity one,
39 # and both arities are the same
40 def is_paired(self) -> bool:
41 input_lengths = [len(x) for x in self.input if len(x) != 1]
42 replacement_lengths = [len(x) for x in self.replacement if len(x) != 1]
43 if not (len(input_lengths) == 1 and len(replacement_lengths) == 1):
44 return False
45 if input_lengths[0] != replacement_lengths[0]:
46 import warnings
47
48 warnings.warn("Unbalanced paired substitution")
49 return False
50 return True
51
52
53 # Expand ligature substitutions ending in a class, such that:
54 # * Substitute [f f.ss01] i -> [f_i f_i.ss01];
55 # Expands to:
56 # * sub f i -> f_i;
57 # * sub f.ss01 i -> f_i.ss01;
58 # Likewise:
59 # * Substitute [f f.ss01] [i i.ss01] -> [f_i f_i.ss01];
60 # Expands to:
61 # * sub f i -> f_i;
62 # * sub f.ss01 i.ss01 -> f_i.ss01;
63 def paired_ligature(self) -> feaast.LigatureSubstStatement:
64 b = feaast.Block()
65 inputs = []
66 for i in self.input:
67 if len(i) == 1:
68 inputs.append(cycle(i))
69 else:
70 inputs.append(i)
71 lhs = zip(*inputs)
72 replacements = []
73 for j in self.replacement:
74 if len(j) == 1:
75 replacements.append(cycle(j))
76 else:
77 replacements.append(j)
78 rhs = zip(*replacements)
79
80 for l, r in zip(lhs, rhs):
81 stmt = feaast.LigatureSubstStatement(
82 [glyphref(x) for x in self.precontext],
83 [glyphref([x]) for x in l],
84 [glyphref(x) for x in self.postcontext],
85 glyphref([r[0]]),
86 False,
87 )
88 b.statements.append(stmt)
89 return b
90
91
92 # Expand multiple substitutions, such that:
93 # * Substitute [a b] -> before_tail [a.2 b.2] tail;
94 # Becomes in FEA:
95 # * sub a by before_tail a.2 tail;
96 # * sub b by before_tail b.2 tail;
97 def paired_mult(self) -> feaast.MultipleSubstStatement:
98 b = feaast.Block()
99
100 input_lengths = [len(x) for x in self.input]
101 replacement_lengths = [len(x) for x in self.replacement]
102
103 if len(input_lengths) != 1:
104 raise ValueError(
105 "Multiple substitution only valid on input of length one, use a Chain instead"
106 )
107
108 input_length = input_lengths[0]
109
110 if sum([l for l in replacement_lengths if l == 1]) not in [
111 len(replacement_lengths),
112 len(replacement_lengths) - 1,
113 ]:
114 raise ValueError(
115 "Cannot expand multiple glyph classes in a multiple substitution — creates ambiguity"
116 )
117
118 # Look for the glyph class in the replacement, or default to first glyph in replacement
119 glyphcls = next((i for i, v in enumerate(self.replacement) if len(v) > 1), 0)
120
121 if input_length != len(self.replacement[glyphcls]):
122 raise ValueError(
123 "Glyph class in input must be same length as that in replacement. {} != {}".format(
124 input_length, len(self.replacement[glyphcls])
125 )
126 )
127
128 zipped = zip(self.input[0], self.replacement[glyphcls])
129
130 prior_reps = self.replacement[:glyphcls]
131 after_reps = self.replacement[glyphcls + 1 :]
132
133 for f, t in zipped:
134 stmt = feaast.MultipleSubstStatement(
135 [glyphref(x) for x in self.precontext],
136 glyphref([f]),
137 [glyphref(x) for x in self.postcontext],
138 [glyphref(g) for g in prior_reps + [[t]] + after_reps],
139 )
140 b.statements.append(stmt)
141
142 return b
143
144
145 def asFeaAST(self):
146 lut = lookup_type(self, forFea=True)
147 if not lut:
148 return feaast.Comment("")
149
150 if not self.replacement: # Delete
151 return feaast.MultipleSubstStatement(
152 [glyphref(x) for x in self.precontext],
153 glyphref(self.input[0]),
154 [glyphref(x) for x in self.postcontext],
155 [],
156 )
157
158 if lut == 1: # GSUB 1 Single Substitution
159 return feaast.SingleSubstStatement(
160 [glyphref(x) for x in self.input],
161 [glyphref(x) for x in self.replacement],
162 [glyphref(x) for x in self.precontext],
163 [glyphref(x) for x in self.postcontext],
164 False,
165 )
166 elif lut == 2: # GSUB 2 Multiple Substitution
167 # Paired rules need to become a set of statements
168 if is_paired(self):
169 return paired_mult(self)
170
171 return feaast.MultipleSubstStatement(
172 [glyphref(x) for x in self.precontext],
173 glyphref(self.input[0]),
174 [glyphref(x) for x in self.postcontext],
175 [glyphref(x) for x in self.replacement],
176 )
177 elif lut == 3: # GSUB 3 Alternate Substitution
178 return feaast.AlternateSubstStatement(
179 [glyphref(x) for x in self.precontext],
180 glyphref(self.input[0]),
181 [glyphref(x) for x in self.postcontext],
182 feaast.GlyphClass([feaast.GlyphName(x) for x in self.replacement[0]]),
183 )
184 elif lut == 4: # GSUB 4 Ligature Substitution
185 # Some rules with classes need to become a set of statements.
186 if (
187 has_classes(self)
188 and all_classes_equal(self)
189 and not len(self.replacement[0]) == 1
190 ):
191 return paired_ligature(self)
192
193 return feaast.LigatureSubstStatement(
194 [glyphref(x) for x in self.precontext],
195 [glyphref(x) for x in self.input],
196 [glyphref(x) for x in self.postcontext],
197 glyphref(self.replacement[0]),
198 False,
199 )
200 elif lut in [5, 6, 7]: # GSUB 5, 6, 7 Different types of contextual substitutions
201 raise NotImplementedError("Use the Chain verb for this")
202 elif lut == 8: # GSUB 8 Reverse Chaining Single Substitution
203 return feaast.ReverseChainSingleSubstStatement(
204 [glyphref(x) for x in self.precontext],
205 [glyphref(x) for x in self.postcontext],
206 [glyphref(x) for x in self.input],
207 [glyphref(self.replacement[0])],
208 )
209 elif lut >= 9:
210 raise NotImplementedError("Invalid GSUB lookup type requested: {}".format(lut))
211
212 raise ValueError("LookupType must be a single positive integer")