Debian Codegraph @

Lib/fontFeatures/feaLib/Chaining.py

raw
1 # Code for converting a Chaining object into feaLib statements
2 import fontTools.feaLib.ast as feaast
3
4
5 # Can we chain multiple lookups?
6
7
8 def glyphref(g):
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 def gensym(ff):
15 if "index" not in ff.scratch:
16 ff.scratch["index"] = 0
17 ff.scratch["index"] = ff.scratch["index"] + 1
18 return str(ff.scratch["index"])
19
20
21 def replaceLongWithClasses(i, ff):
22 for ix, gc in enumerate(i):
23 if len(gc) > 5:
24 classname = ff.getNamedClassFor(sorted(gc), "class" + gensym(ff))
25 i[ix] = ["@" + classname]
26
27
28 def feaPreamble(self, ff):
29 if "glyphclasses" not in ff.scratch:
30 ff.scratch["glyphclasses"] = {
31 tuple(sorted(ff.namedClasses[g])): g for g in ff.namedClasses.keys()
32 }
33 replaceLongWithClasses(self.input, ff)
34 replaceLongWithClasses(self.precontext, ff)
35 replaceLongWithClasses(self.postcontext, ff)
36 from fontFeatures import RoutineReference
37
38 # Ensure all linked routines have names
39 for lul in self.lookups:
40 for r in lul or []:
41 assert isinstance(r, RoutineReference)
42 assert r.routine
43 if not r.routine.name:
44 r.routine.name = "ChainedRoutine" + gensym(ff)
45 if not r.name:
46 r.name = r.routine.name
47
48 return []
49
50
51 def _complex(self):
52 if self.stage == "sub":
53 routine = feaast.ChainContextSubstStatement
54 else:
55 routine = feaast.ChainContextPosStatement
56
57 return routine(
58 [glyphref(x) for x in self.precontext],
59 [glyphref(x) for x in self.input],
60 [glyphref(x) for x in self.postcontext],
61 self.lookups,
62 )
63
64
65 def asFeaAST(self):
66 if len(self.lookups) > 0 and any([x is not None for x in self.lookups]):
67 # Fill in the blanks
68 if self.stage == "sub":
69 routine = feaast.ChainContextSubstStatement
70 else:
71 routine = feaast.ChainContextPosStatement
72 # Check for >1 lookups per position
73 if any([x and len(x) > 1 for x in self.lookups]):
74 return _complex(self)
75 lookups = self.lookups
76 return routine(
77 [glyphref(x) for x in self.precontext],
78 [glyphref(x) for x in self.input],
79 [glyphref(x) for x in self.postcontext],
80 lookups,
81 )
82 else:
83 return feaast.IgnoreSubstStatement(
84 chainContexts=[
85 [
86 [glyphref(x) for x in self.precontext],
87 [glyphref(x) for x in self.input],
88 [glyphref(x) for x in self.postcontext],
89 ]
90 ]
91 )