Debian Codegraph @

Lib/fontFeatures/optimizer/FontFeatures.py

raw
1 from fontFeatures import Chaining, Routine
2 import logging
3
4
5 class MergeNonOverlappingRoutines:
6 level = 2
7
8 def apply(self, ff):
9 logger = logging.getLogger("fontFeatures")
10 deadRoutine = Routine(name="dead")
11
12 def haschains(routine):
13 for r in routine.rules:
14 if isinstance(r, Chaining):
15 return True
16
17 routinelist = ff.routines
18 ff.markRoutineUseInChains()
19 for lix, l in enumerate(routinelist):
20 if haschains(l) or l == deadRoutine:
21 continue
22 for rix in range(lix + 1, len(routinelist)):
23 r = routinelist[rix]
24 if haschains(r) or r == deadRoutine:
25 continue
26 if self.nonOverlapping(ff, l, r):
27 logger.info(
28 "Merging nonoverlapping routines %s , %s" % (l.name, r.name)
29 )
30 self.merge(l, r)
31 routinelist[rix] = deadRoutine
32 ff.routines = list(filter(lambda r: r != deadRoutine, routinelist))
33
34 def whatuses(self, routine, ff):
35 # Compute the glyphs which are a context for a routine to be called
36 return set.union(set([]), *[c.involved_glyphs for c in list(routine.usedin)])
37
38 def replaceAllReferences(self, usedin, first, second):
39 for i in usedin:
40 for routinelist in i.lookups:
41 if not routinelist:
42 continue
43 for ix, routine in enumerate(routinelist):
44 if routine == first:
45 routinelist[ix] = second
46
47 def merge(self, l, r):
48 l.rules.extend(r.rules)
49 if l.name and r.name:
50 l.name = l.name + "_" + r.name
51 elif r.name:
52 l.name = r.name
53 l.comments.extend(r.comments)
54 l.usedin = set.union(l.usedin, r.usedin)
55 self.replaceAllReferences(l.usedin, r, l)
56
57 def nonOverlapping(self, ff, l, r):
58 return (
59 not (l.involved_glyphs & r.involved_glyphs)
60 and not (self.whatuses(l, ff) & self.whatuses(r, ff))
61 and self.compatibleRules(l, r)
62 )
63
64 def compatibleRules(self, l, r):
65 from fontFeatures.feaLib.Routine import (
66 arrange_by_type,
67 arrange_by_lookup_type,
68 arrange_by_flags,
69 )
70
71 testRoutine = Routine()
72 testRoutine.rules.extend(l.rules)
73 testRoutine.rules.extend(r.rules)
74 if arrange_by_type(testRoutine):
75 return False
76 if arrange_by_lookup_type(testRoutine):
77 return False
78 if arrange_by_flags(testRoutine):
79 return False
80 return True
81
82
83 optimizations = [MergeNonOverlappingRoutines]