Debian Codegraph @

Lib/fontFeatures/optimizer/Routine.py

raw
1 from fontTools.otlLib.builder import ClassDefBuilder
2 from fontFeatures import Substitution, Positioning, Chaining
3 import logging
4 import copy
5
6
7 class MoveLongCoverageToClassDefinition:
8 level = 1
9
10 def gensym(self, ff):
11 if "index" not in ff.scratch:
12 ff.scratch["index"] = 0
13 ff.scratch["index"] = ff.scratch["index"] + 1
14 return str(ff.scratch["index"])
15
16 def replaceLongWithClasses(self, i, ff):
17 for ix, gc in enumerate(i):
18 if len(gc) > 5:
19 classname = ff.getNamedClassFor(gc, "class" + self.gensym(ff))
20 i[ix] = ["@" + classname]
21
22 def apply(self, routine, ff):
23 for rule in routine.rules:
24 if isinstance(rule, Substitution):
25 self.replaceLongWithClasses(rule.input, ff)
26 self.replaceLongWithClasses(rule.precontext, ff)
27 self.replaceLongWithClasses(rule.postcontext, ff)
28 self.replaceLongWithClasses(rule.replacement, ff)
29 if isinstance(rule, Positioning):
30 self.replaceLongWithClasses(rule.glyphs, ff)
31 self.replaceLongWithClasses(rule.precontext, ff)
32 self.replaceLongWithClasses(rule.postcontext, ff)
33
34 return []
35
36
37 class MergeMultipleSingleSubstitutions:
38 level = 1
39
40 def apply(self, routine, ff):
41 def _is_single_sub(rule):
42 (
43 isinstance(rule, Substitution)
44 and len(rule.input) == 1
45 and len(rule.replacement) == 1
46 )
47
48 if len(routine.rules) < 2:
49 return
50 new_rules = [routine.rules[0]]
51 for r in routine.rules[1:]:
52 previous = new_rules[-1]
53 if (
54 _is_single_sub(r)
55 and _is_single_sub(previous)
56 and r.precontext == previous.precontext
57 and r.postcontext == previous.postcontext
58 ):
59 new_rules.pop()
60 new_rules.append(self.merge_two(previous, r))
61 else:
62 new_rules.append(r)
63 routine.rules = new_rules
64 # It's possible to get clever later with non-adjacent substitutions
65 # if there's nothing in the middle that could affect the output
66
67 def merge_two(self, first, second):
68 assert len(first.input) == 1 and len(second.input) == 1
69 assert len(first.replacement) == 1 and len(second.replacement) == 1
70 assert first.precontext == second.precontext
71 assert first.postcontext == second.postcontext
72 firstmapping = {l: r for l, r in zip(first.input[0], first.replacement[0])}
73 secondmapping = {l: r for l, r in zip(second.input[0], second.replacement[0])}
74 for l, r in firstmapping.items():
75 if r in secondmapping:
76 firstmapping[l] = secondmapping[r]
77 for l, r in secondmapping.items():
78 if l not in firstmapping:
79 firstmapping[l] = r
80 logger = logging.getLogger("fontFeatures")
81 logger.info("Merging two adjacent single subs")
82 if logger.isEnabledFor(logging.DEBUG):
83 logger.debug(first.asFea())
84 logger.debug(second.asFea())
85 address = first.address or second.address
86 return Substitution(
87 [list(firstmapping.keys())],
88 [list(firstmapping.values())],
89 address=address,
90 precontext=first.precontext,
91 postcontext=first.postcontext,
92 )
93
94
95 class EnsureFormat2Chaining:
96 level = 1
97
98 def apply(self, routine, ff):
99 rules = routine.rules
100 if not all(isinstance(rule, Chaining) for rule in routine.rules):
101 return
102
103 while True:
104 if self._apply(rules):
105 break
106
107 def _apply(self, rules):
108 logger = logging.getLogger("fontFeatures")
109 logger.warn("Applying format 2 optimization round")
110
111 for which in ["input", "precontext", "postcontext"]:
112 classdefbuilder = ClassDefBuilder(useClass0=False)
113 for rule in rules:
114 for slot in getattr(rule, which):
115 if not classdefbuilder.canAdd(set(slot)):
116 logger.warn("Mitigating. Rule count before=%i", len(rules))
117 self.mitigate(
118 rules, which, classdefbuilder.classes(), set(slot)
119 )
120 logger.warn("Mitigating. Rule count after=%i", len(rules))
121 return False
122 classdefbuilder.add(set(slot))
123 return True
124
125 def mitigate(self, rules, which, rule_classes, failing_slot):
126 # What kind of fail is this?
127 problem = None
128 for klass in rule_classes[1:]:
129 if not set(klass).isdisjoint(failing_slot):
130 problem = klass
131 break
132 # Split both into two and try again
133 additional_rules = []
134 intersection = set(problem) & failing_slot
135 assert intersection
136 for rule in rules:
137 for ix, slot in enumerate(getattr(rule, which)):
138 if (set(slot) == set(problem) or set(slot) == failing_slot) and set(
139 slot
140 ) != intersection:
141 new_rule = Chaining(
142 copy.deepcopy(rule.input),
143 precontext=copy.deepcopy(rule.precontext),
144 postcontext=copy.deepcopy(rule.postcontext),
145 lookups=rule.lookups[:],
146 )
147 setattr(new_rule, which, getattr(new_rule, which)[:])
148 setattr(rule, which, getattr(rule, which)[:])
149 getattr(rule, which)[ix] = list(set(slot) - intersection)
150 getattr(new_rule, which)[ix] = list(intersection)
151 additional_rules.append(new_rule)
152 rules.extend(additional_rules)
153
154
155 optimizations = [
156 MergeMultipleSingleSubstitutions,
157 EnsureFormat2Chaining,
158 # MoveLongCoverageToClassDefinition, # Runs last
159 ]