Debian Codegraph @

Lib/fontFeatures/ttLib/Routine.py

raw
1 """Convert fontFeatures.Routine objects to binary GPOS/GSUB lookups."""
2 import fontTools.otlLib.builder as otl
3 from fontTools.varLib.builder import buildVarDevTable
4 from fontTools.feaLib.variableScalar import VariableScalar
5 import itertools
6
7
8 def toOTLookup(self, font, ff):
9 """Converts a fontFeatures.Routine object to binary.
10
11 Args:
12 font: A ``TTFont`` object.
13 ff: The parent ``FontFeatures`` object containing this routine.
14
15 Returns a list of ``fontTools.otlLib.builder`` Builder objects allowing this
16 routine to be converted to binary layout format.
17 """
18
19 lookuptypes = [x.lookup_type() for x in self.rules]
20 if not all([lu == lookuptypes[0] for lu in lookuptypes]):
21 raise ValueError("For now, a routine can only contain rules of the same type")
22
23 if not all([self.rules[0].flags == rule.flags for rule in self.rules]):
24 raise ValueError("For now, a routine can only contain rules of the same flags")
25 self.flags = self.rules[0].flags
26
27 if self.stage == "pos":
28 return buildPos(self, font, lookuptypes[0], ff)
29 if self.stage == "sub":
30 return buildSub(self, font, lookuptypes[0], ff)
31
32
33 def makeAnchor(anchor, ff):
34 """Creates an OpenType anchor object from. If the anchor position contains
35 a variable scalar, these variable scalars are saved in the ``GDEF`` variation
36 store.
37
38 Args:
39 anchor: a tuple of x,y position. These elements may be numbers or
40 :py:class:`VariableScalar` objects.
41
42 Returns: an ``otTables.Anchor`` object.
43 """
44 x, y = anchor
45 if isinstance(x, VariableScalar):
46 x_def, x_index = x.add_to_variation_store(ff.varstorebuilder)
47 else:
48 x_def, x_index = int(x), None
49 if isinstance(y, VariableScalar):
50 y_def, y_index = y.add_to_variation_store(ff.varstorebuilder)
51 else:
52 y_def, y_index = int(y), None
53 anchor = otl.buildAnchor(x_def, y_def)
54 if x_index is not None and x_index != 0xFFFFFFFF:
55 anchor.XDeviceTable = buildVarDevTable(x_index)
56 anchor.Format = 3
57 if y_index is not None and x_index != 0xFFFFFFFF:
58 anchor.YDeviceTable = buildVarDevTable(y_index)
59 anchor.Format = 3
60 return anchor
61
62
63 def buildPos(self, font, lookuptype, ff):
64 """Build a GPOS subtable."""
65 builders = []
66 if lookuptype == 1:
67 builder = otl.SinglePosBuilder(font, self.address)
68 for rule in self.rules:
69 ot_valuerecs = [
70 x.toOTValueRecord(ff, pairPosContext=False) for x in rule.valuerecords
71 ]
72 for glyph in rule.glyphs[0]:
73 builder.add_pos(rule.address, glyph, ot_valuerecs[0])
74 elif lookuptype == 2:
75 builder = otl.PairPosBuilder(font, self.address)
76 for rule in self.rules:
77 ot_valuerecs = [
78 x.toOTValueRecord(ff, pairPosContext=True) for x in rule.valuerecords
79 ]
80 if len(rule.glyphs[0]) == 1 and len(rule.glyphs[1]) == 1:
81 builder.addGlyphPair(
82 rule.address,
83 rule.glyphs[0][0],
84 ot_valuerecs[0],
85 rule.glyphs[1][0],
86 ot_valuerecs[1],
87 )
88 else:
89 builder.addClassPair(
90 rule.address,
91 tuple(rule.glyphs[0]),
92 ot_valuerecs[0],
93 tuple(rule.glyphs[1]),
94 ot_valuerecs[1],
95 )
96 elif lookuptype == 3:
97 builder = otl.CursivePosBuilder(font, self.address)
98 for rule in self.rules:
99 allglyphs = set(rule.bases.keys()) | set(rule.marks.keys())
100 for g in allglyphs:
101 builder.attachments[g] = (
102 g in rule.bases and makeAnchor(rule.bases[g], ff) or None,
103 g in rule.marks and makeAnchor(rule.marks[g], ff) or None,
104 )
105 elif lookuptype == 4 or lookuptype == 6:
106 if lookuptype == 4:
107 builder = otl.MarkBasePosBuilder(font, self.address)
108 baseholder = builder.bases
109 else:
110 builder = otl.MarkMarkPosBuilder(font, self.address)
111 baseholder = builder.baseMarks
112 for r in self.rules:
113 for mark, anchor in r.marks.items():
114 if mark in builder.marks:
115 raise ValueError(
116 "A mark glyph %s tried to be in two categories (%s, %s)"
117 % (mark, r.mark_name, builder.marks[mark][0])
118 )
119 builder.marks[mark] = (r.mark_name, makeAnchor(anchor, ff))
120 for base, anchor in r.bases.items():
121 if base not in baseholder:
122 baseholder[base] = {}
123 baseholder[base][r.mark_name] = makeAnchor(anchor, ff)
124 # XXX. We may need to express this as multiple lookups
125 elif lookuptype == 8:
126 builder = otl.ChainContextPosBuilder(font, self.address)
127 for r in self.rules:
128 new_lookup_list = []
129 import fontFeatures
130
131 if isinstance(r, fontFeatures.Positioning):
132 for glyphs, vr in zip(r.glyphs, r.valuerecords):
133 # Make a fake pos routine
134 subbuilder = buildPos(
135 fontFeatures.Routine(
136 rules=[
137 fontFeatures.Positioning([glyphs], valuerecords=[vr])
138 ]
139 ),
140 font,
141 1,
142 ff,
143 )
144 builders.extend(subbuilder)
145 new_lookup_list.append(subbuilder)
146 glyphs = r.glyphs
147 else:
148 for list_of_lookups in r.lookups:
149 new_lookup_list.append(
150 [lu.routine.__builder for lu in (list_of_lookups or [])]
151 )
152 glyphs = r.input
153 builder.rules.append(
154 otl.ChainContextualRule(
155 r.precontext or [],
156 glyphs or [],
157 r.postcontext or [],
158 new_lookup_list,
159 )
160 )
161 else:
162 raise ValueError("Don't know how to build a POS type %i lookup" % lookuptype)
163 builder.lookupflag = self.flags
164 # XXX mark filtering set
165 self.__builder = builder
166 builders.append(builder)
167 return builders
168
169
170 def buildSub(self, font, lookuptype, ff):
171 """Build a GSUB subtable."""
172 builders = []
173 if lookuptype == 1:
174 builder = otl.SingleSubstBuilder(font, self.address)
175 for rule in self.rules:
176 for left, right in zip(rule.input[0], rule.replacement[0]):
177 builder.mapping[left] = right
178 elif lookuptype == 2:
179 builder = otl.MultipleSubstBuilder(font, self.address)
180 for rule in self.rules:
181 builder.mapping[rule.input[0][0]] = [x[0] for x in rule.replacement]
182 elif lookuptype == 4:
183 builder = otl.LigatureSubstBuilder(font, self.address)
184 for rule in self.rules:
185 for sequence in itertools.product(*rule.input):
186 builder.ligatures[sequence] = rule.replacement[0][0]
187 elif lookuptype == 6:
188 builder = otl.ChainContextSubstBuilder(font, self.address)
189 for r in self.rules:
190 import fontFeatures
191
192 if isinstance(r, fontFeatures.Substitution) and r.replacement:
193 lookups = []
194 for left, right in zip(r.input, r.replacement):
195 # Make a fake sub routine
196
197 subbuilder = buildSub(
198 fontFeatures.Routine(
199 rules=[
200 fontFeatures.Substitution([left], replacement=[right])
201 ]
202 ),
203 font,
204 1,
205 ff,
206 )
207 builders.extend(subbuilder)
208 lookups.append(subbuilder)
209 else:
210 lookups = []
211 for list_of_lookups in r.lookups:
212 lookups.append(
213 [lu.routine.__builder for lu in (list_of_lookups or [])]
214 )
215 builder.rules.append(
216 otl.ChainContextualRule(
217 r.precontext or [],
218 r.input or [],
219 r.postcontext or [],
220 lookups,
221 )
222 )
223 elif lookuptype == 8:
224 builder = otl.ReverseChainSingleSubstBuilder(font, self.address)
225 for rule in self.rules:
226 mapping = {l[0]: r[0] for l, r in zip(rule.input, rule.replacement)}
227 builder.rules.append((rule.precontext, rule.postcontext, mapping))
228 else:
229 raise ValueError("Don't know how to build a SUB type %i lookup" % lookuptype)
230
231 builder.lookupflag = self.flags
232 # XXX mark filtering set
233 self.__builder = builder
234 builders.append(builder)
235 return builders