Debian Codegraph @

Lib/fontFeatures/ttLib/FontFeatures.py

raw
1 """Convert a fontFeatures object to GPOS/GSUB/GDEF tables
2
3 This module contains routines for building binary layout tables from a
4 fontFeatures object. These are implemented as mixins loaded into the
5 fontFeatures object. e.g. instead of::
6
7 fontFeatures.ttLib.FontFeatures.buildBinaryFeatures(ff, font)
8
9 call::
10
11 ff.buildBinaryFeatures(font)
12
13 """
14 from fontTools.ttLib.tables import otTables
15 from fontTools.ttLib import newTable
16 from collections import OrderedDict
17 from fontTools.varLib.varStore import OnlineVarStoreBuilder
18
19
20 def buildBinaryFeatures(self, font, axes=[]):
21 """Adds GDEF, GSUB and GPOS tables to a font object.
22
23 Args:
24 font: a fontTools ``ttFont`` object.
25 axes: an optional list of objects conforming to the
26 ``fontTools.designspaceLib.AxisDescriptor`` protocol.
27 """
28 self.resolveAllRoutines()
29 reorderRoutines(self)
30
31 # Partition rules based on lookup types
32 for r in self.routines:
33 self.partitionRoutine(r, lambda rule: rule.lookup_type())
34
35 # XXX first build gdef for mark attachment classes
36 if axes:
37 self.varstorebuilder = OnlineVarStoreBuilder([ax.tag for ax in axes])
38 self.axes = axes
39 buildGDEF(self, font)
40 buildGPOSGSUB(self, font)
41 if axes:
42 store = self.varstorebuilder.finish()
43 if store.VarData:
44 font["GDEF"].table.Version = 0x00010003
45 font["GDEF"].table.VarStore = store
46 varidx_map = store.optimize()
47
48 font["GDEF"].table.remap_device_varidxes(varidx_map)
49 if "GPOS" in font:
50 font["GPOS"].table.remap_device_varidxes(varidx_map)
51
52
53 def reorderRoutines(self):
54 """Reorders the routines table to ensure that all routines which are
55 referenced in chaining rules appear before the routines which reference them."""
56 newroutines = []
57 i = 0
58 while i < len(self.routines):
59 r = self.routines[i]
60 if r in newroutines:
61 i = i + 1
62 continue
63 for dep in r.dependencies:
64 if dep not in newroutines:
65 newroutines.append(dep)
66 newroutines.append(r)
67 i = i + 1
68 self.routines = newroutines
69
70
71 # I am stealing the fontTools.feaLib.builder stuff here
72 def buildGDEF(self, font):
73 """Build a GDEF table and add it to the ``ttFont`` object."""
74 gdef = otTables.GDEF()
75 gdef.GlyphClassDef = _buildGDEFGlyphClassDef(self)
76
77 # gdef.AttachList = otl.buildAttachList(self.attachPoints_, self.glyphMap)
78 # gdef.LigCaretList = otl.buildLigCaretList(
79 # self.ligCaretCoords_, self.ligCaretPoints_, self.glyphMap
80 # )
81 # gdef.MarkAttachClassDef = self.buildGDEFMarkAttachClassDef_()
82 # gdef.MarkGlyphSetsDef = self.buildGDEFMarkGlyphSetsDef_()
83 # gdef.Version = 0x00010002 if gdef.MarkGlyphSetsDef else 0x00010000
84 gdef.Version = 0x00010000
85 if any(
86 (
87 gdef.GlyphClassDef,
88 # gdef.AttachList,
89 # gdef.LigCaretList,
90 # gdef.MarkAttachClassDef,
91 # gdef.MarkGlyphSetsDef,
92 )
93 ):
94 font["GDEF"] = newTable("GDEF")
95 font["GDEF"].table = gdef
96
97
98 classnames = ["", "base", "ligature", "mark", "component"]
99
100
101 def _buildGDEFGlyphClassDef(self):
102 classes = {}
103 for g, c in self.glyphclasses.items():
104 classes[g] = classnames.index(c)
105 if classes:
106 result = otTables.GlyphClassDef()
107 result.classDefs = classes
108 return result
109 else:
110 return None
111
112
113 def buildGPOSGSUB(self, font):
114 """Builds GSUB and GPOS tables and adds them to the ``ttFont`` object."""
115 for tag in ["GSUB", "GPOS"]:
116 table = makeTable(self, tag, font)
117 fontTable = font[tag] = newTable(tag)
118 fontTable.table = table
119
120
121 def arrangeByScripts(self):
122 """Hoists script/language data from rules into routines, and builds a
123 map of which routines apply to each script/language pair.
124
125 Returns an ordered dictionary; the keys are tuples of
126 ``(feature_tag, script_tag, language_tag))``, and the values are a list of
127 routines."""
128 for r in self.routines:
129 if any(rule.languages for rule in r.rules):
130 self.partitionRoutine(r, lambda rule: tuple(rule.languages or []))
131
132 for r in self.routines:
133 if not r.rules:
134 continue
135 r.languages = r.rules[0].languages # Guaranteed to be the same
136 if r.languages:
137 for ix, langpair in enumerate(r.languages):
138 if langpair[1] == "*":
139 r.languages[ix] = (langpair[0], "dflt")
140 if langpair[0] == "*":
141 r.languages[ix] = ("DFLT", langpair[1])
142 else:
143 r.languages = [("DFLT", "dflt")]
144
145 self.hoist_languages()
146 script_lang_pairs = []
147 for script in self.scripts_and_languages.keys():
148 if (script, "dflt") not in script_lang_pairs:
149 script_lang_pairs.append((script, "dflt"))
150 for lang in self.scripts_and_languages[script]:
151 script_lang_pairs.append((script, lang))
152
153 the_big_map = OrderedDict()
154
155 def put_in_map(tag, script, lang, routine):
156 key = (tag, script, lang)
157 if key not in the_big_map:
158 the_big_map[key] = []
159 if routine not in the_big_map[key]:
160 the_big_map[key].append(routine)
161
162 def put_in_map_with_default(tag, script, lang, routine):
163 put_in_map(tag, script, lang, routine)
164 for script2, lang2 in script_lang_pairs:
165 if script == "DFLT" and lang == "dflt":
166 put_in_map(tag, script2, lang2, routine)
167 elif script == script2 and lang == "dflt":
168 put_in_map(tag, script2, lang2, routine)
169
170 for tag, routinereferences in self.features.items():
171 for r in routinereferences:
172 for script, lang in r.routine.languages:
173 put_in_map_with_default(tag, script, lang, r)
174 return the_big_map
175
176
177 def separate_by_stage(the_big_map, stage):
178 """Splits up the routine map into GSUB/GPOS routines."""
179 stage_map = OrderedDict()
180 for k, v in the_big_map.items():
181 v = [r for r in v if r.stage == stage]
182 if v:
183 stage_map[k] = v
184 return stage_map
185
186
187 def makeTable(self, tag, font):
188 """Compiles a binary GSUB/GPOS table."""
189 table = getattr(otTables, tag, None)()
190 table.Version = 0x00010000
191 table.ScriptList = otTables.ScriptList()
192 table.ScriptList.ScriptRecord = []
193 table.FeatureList = otTables.FeatureList()
194 table.FeatureList.FeatureRecord = []
195 table.LookupList = otTables.LookupList()
196
197 stage_map = separate_by_stage(arrangeByScripts(self), tag[1:].lower())
198 stage_routines = [x for x in self.routines if x.stage == tag[1:].lower()]
199 buildersset = [x.toOTLookup(font, self) for x in stage_routines]
200 lookups = []
201 builderlist = []
202 for builders in buildersset:
203 for builder in builders:
204 builder.lookup_index = len(lookups)
205 builderlist.append(builder)
206 lookups.append(builder.build())
207
208 table.LookupList.Lookup = lookups
209
210 # Build a table for mapping (tag, lookup_indices) to feature_index.
211 # For example, ('liga', (2,3,7)) --> 23.
212 feature_indices = {}
213 scripts = {} # 'latn' --> {'DEU': [23, 24]} for feature #23,24
214 # Sort the feature table by feature tag:
215 # https://github.com/fonttools/fonttools/issues/568
216 sortFeatureTag = lambda f: (f[0][2], f[0][1], f[0][0], f[1])
217 for key, lookups in sorted(stage_map.items(), key=sortFeatureTag):
218 feature_tag, script, lang = key
219 # l.lookup_index will be None when a lookup is not needed
220 # for the table under construction. For example, substitution
221 # rules will have no lookup_index while building GPOS tables.
222 lookup_indices = tuple(
223 [builderlist.index(x.routine.__builder) for x in lookups]
224 )
225
226 size_feature = tag == "GPOS" and feature_tag == "size"
227 if len(lookup_indices) == 0 and not size_feature:
228 continue
229
230 feature_key = (feature_tag, lookup_indices)
231 feature_index = feature_indices.get(feature_key)
232 if feature_index is None:
233 feature_index = len(table.FeatureList.FeatureRecord)
234 frec = otTables.FeatureRecord()
235 frec.FeatureTag = feature_tag
236 frec.Feature = otTables.Feature()
237 # frec.Feature.FeatureParams = self.buildFeatureParams(feature_tag)
238 frec.Feature.LookupListIndex = list(lookup_indices)
239 frec.Feature.LookupCount = len(lookup_indices)
240 table.FeatureList.FeatureRecord.append(frec)
241 feature_indices[feature_key] = feature_index
242 scripts.setdefault(script, {}).setdefault(lang, []).append(feature_index)
243
244 # Build ScriptList.
245 for script, lang_features in sorted(scripts.items()):
246 srec = otTables.ScriptRecord()
247 srec.ScriptTag = script
248 srec.Script = otTables.Script()
249 srec.Script.DefaultLangSys = None
250 srec.Script.LangSysRecord = []
251 for lang, feature_indices in sorted(lang_features.items()):
252 langrec = otTables.LangSysRecord()
253 langrec.LangSys = otTables.LangSys()
254 langrec.LangSys.LookupOrder = None
255 langrec.LangSys.ReqFeatureIndex = 0xFFFF
256 langrec.LangSys.FeatureIndex = [i for i in feature_indices]
257 langrec.LangSys.FeatureCount = len(langrec.LangSys.FeatureIndex)
258 if lang == "dflt":
259 srec.Script.DefaultLangSys = langrec.LangSys
260 else:
261 langrec.LangSysTag = lang
262 srec.Script.LangSysRecord.append(langrec)
263 srec.Script.LangSysCount = len(srec.Script.LangSysRecord)
264 table.ScriptList.ScriptRecord.append(srec)
265
266 table.ScriptList.ScriptCount = len(table.ScriptList.ScriptRecord)
267 table.FeatureList.FeatureCount = len(table.FeatureList.FeatureRecord)
268 table.LookupList.LookupCount = len(table.LookupList.Lookup)
269 return table