| 1 |
""" |
| 2 |
GTableUnparser: Base class for reading binary GSUB/GPOS tables |
| 3 |
============================================================== |
| 4 |
""" |
| 5 |
from collections import OrderedDict |
| 6 |
from fontTools.misc.xmlWriter import XMLWriter |
| 7 |
import fontFeatures |
| 8 |
from io import BytesIO |
| 9 |
import warnings |
| 10 |
|
| 11 |
|
| 12 |
def glyph(x): |
| 13 |
"""Helper routine to document that a glyph name goes in a slot.""" |
| 14 |
assert isinstance(x, str) |
| 15 |
return [x] |
| 16 |
|
| 17 |
|
| 18 |
class GTableUnparser: |
| 19 |
"""Base class for reading binary GSUB/GPOS tables.""" |
| 20 |
|
| 21 |
def __init__(self, table, ff, languageSystems, font=None, config={}): |
| 22 |
"""Create a new unparser |
| 23 |
|
| 24 |
Args: |
| 25 |
table: An object returned by ``font["GSUB"]`` or ``font["GPOS"]``. |
| 26 |
ff: A fontFeatures object in which to return the output. |
| 27 |
font: A ``TTFont`` object (optional). |
| 28 |
config: A dictionary mapping generated names to friendly names. |
| 29 |
|
| 30 |
The config dictionary is used to make the output more human readable. |
| 31 |
For example, after dumping a binary TTF and reading the output, you might |
| 32 |
discover that what we are calling ``SingleSubstitution1`` would be better |
| 33 |
named ``fiLigature``. Passing ``{"SingleSubstitution1": "fiLigature"}`` |
| 34 |
to the call will cause the routine to be renamed appropriately.""" |
| 35 |
|
| 36 |
self.table = table.table |
| 37 |
self.font = font |
| 38 |
self.fontFeatures = ff |
| 39 |
self.config = config |
| 40 |
self.index = 0 |
| 41 |
self.lookups = [] # We keep a separate list because this is per-table |
| 42 |
self.sharedClasses = {} |
| 43 |
self.languageSystems = languageSystems |
| 44 |
self.sharedLookups = OrderedDict() |
| 45 |
|
| 46 |
def _unparse_lookups(self, slr, inputs, in_lookups=None): |
| 47 |
lookups = [] |
| 48 |
note = None |
| 49 |
if in_lookups: |
| 50 |
lookups = in_lookups |
| 51 |
indices = [sl.SequenceIndex for sl in slr] |
| 52 |
if indices != list(sorted(indices)): |
| 53 |
# https://github.com/adobe-type-tools/afdko/issues/1167 |
| 54 |
note = ( |
| 55 |
f"Out-of-order lookup application in lookup {self.currentLookup}\n" |
| 56 |
f" A chaining rule calls lookups in the order {indices}\n" |
| 57 |
" This cannot be directly expressed in Adobe FEA syntax;\n" |
| 58 |
" asFea() output will be incorrect" |
| 59 |
) |
| 60 |
warnings.warn(note) |
| 61 |
for sl in slr: |
| 62 |
if len(lookups) <= sl.SequenceIndex: |
| 63 |
lookups.extend([None] * (1 + sl.SequenceIndex - len(lookups))) |
| 64 |
if not lookups[sl.SequenceIndex]: |
| 65 |
lookups[sl.SequenceIndex] = [] |
| 66 |
if sl.LookupListIndex >= len(self.lookups): |
| 67 |
raise ValueError( |
| 68 |
"Lookups unparsed out of order: unparse %i first!" |
| 69 |
% sl.LookupListIndex |
| 70 |
) |
| 71 |
rr = fontFeatures.RoutineReference(routine=self.lookups[sl.LookupListIndex]) |
| 72 |
lookups[sl.SequenceIndex].append(rr) |
| 73 |
if len(lookups) < len(inputs): |
| 74 |
lookups.extend([None] * (len(inputs) - len(lookups))) |
| 75 |
assert len(lookups) == len(inputs) |
| 76 |
return lookups, note |
| 77 |
|
| 78 |
def _invertClassDef(self, a, font): |
| 79 |
classes = {} |
| 80 |
for glyph, klass in a.items(): |
| 81 |
if klass not in classes: |
| 82 |
classes[klass] = [] |
| 83 |
classes[klass].append(glyph) |
| 84 |
glyphset = set(font.getGlyphOrder()) |
| 85 |
classes[0] = glyphset - set(a.keys()) |
| 86 |
return classes |
| 87 |
|
| 88 |
def getname(self, n): |
| 89 |
"""Renames its input using the configuration dictionary""" |
| 90 |
return self.config.get(n, n) |
| 91 |
|
| 92 |
def gensym(self): |
| 93 |
"""Generates a new unique name""" |
| 94 |
self.index = self.index + 1 |
| 95 |
return str(self.index) |
| 96 |
|
| 97 |
def unparse(self, doLookups=True): |
| 98 |
"""Unparse the table to the fontFeatures object.""" |
| 99 |
if not self.table.ScriptList: |
| 100 |
return |
| 101 |
self.unparseLookups() |
| 102 |
self.collectFeatures() |
| 103 |
self.fontFeatures.resolveAllRoutines() |
| 104 |
|
| 105 |
def _prepareFeatureLangSys(self, langTag, langSys, table, features, scriptTag): |
| 106 |
# This is a part of prepareFeatures |
| 107 |
for featureIdx in langSys.FeatureIndex: |
| 108 |
featureRecord = self.table.FeatureList.FeatureRecord[featureIdx] |
| 109 |
featureTag = featureRecord.FeatureTag |
| 110 |
scripts = features.get(featureTag, None) |
| 111 |
if scripts is None: |
| 112 |
scripts = OrderedDict() |
| 113 |
features[featureTag] = scripts |
| 114 |
|
| 115 |
languages = scripts.get(scriptTag, None) |
| 116 |
if languages is None: |
| 117 |
languages = OrderedDict() |
| 118 |
scripts[scriptTag] = languages |
| 119 |
|
| 120 |
lookups = languages.get(langTag, None) |
| 121 |
if lookups is None: |
| 122 |
lookups = [] |
| 123 |
languages[langTag] = lookups |
| 124 |
|
| 125 |
for lookupIdx in featureRecord.Feature.LookupListIndex: |
| 126 |
if (scriptTag, langTag) not in self.lookups[lookupIdx].languages: |
| 127 |
self.lookups[lookupIdx].languages.append((scriptTag, langTag)) |
| 128 |
# Add reference if there isn't one |
| 129 |
if featureTag not in self.fontFeatures.features: |
| 130 |
self.fontFeatures.features[featureTag] = [] |
| 131 |
if not any( |
| 132 |
r.routine == self.lookups[lookupIdx] |
| 133 |
for r in self.fontFeatures.features[featureTag] |
| 134 |
): |
| 135 |
self.fontFeatures.addFeature( |
| 136 |
featureTag, |
| 137 |
[self.lookups[lookupIdx]], |
| 138 |
) |
| 139 |
lookups.append(lookupIdx) |
| 140 |
|
| 141 |
def collectFeatures(self): |
| 142 |
"""Traverse the script/language table looking for features.""" |
| 143 |
features = OrderedDict() |
| 144 |
for scriptRecord in self.table.ScriptList.ScriptRecord: |
| 145 |
scriptTag = scriptRecord.ScriptTag |
| 146 |
if scriptRecord.Script.DefaultLangSys is not None: |
| 147 |
self._prepareFeatureLangSys( |
| 148 |
"dflt", |
| 149 |
scriptRecord.Script.DefaultLangSys, |
| 150 |
self.table, |
| 151 |
features, |
| 152 |
scriptTag, |
| 153 |
) |
| 154 |
for langSysRecord in scriptRecord.Script.LangSysRecord: |
| 155 |
self._prepareFeatureLangSys( |
| 156 |
langSysRecord.LangSysTag, |
| 157 |
langSysRecord.LangSys, |
| 158 |
self.table, |
| 159 |
features, |
| 160 |
scriptTag, |
| 161 |
) |
| 162 |
self.features = features |
| 163 |
|
| 164 |
def unparseLookups(self): |
| 165 |
"""Unparses the lookups to fontFeatures routines.""" |
| 166 |
if not self.table.LookupList: |
| 167 |
return |
| 168 |
# Create a dummy list first, to allow resolving chained lookups |
| 169 |
for _ in self.table.LookupList.Lookup: |
| 170 |
r = fontFeatures.Routine() |
| 171 |
self.lookups.append(r) |
| 172 |
self.fontFeatures.routines.append(r) |
| 173 |
|
| 174 |
for lookupIdx, lookup in enumerate(self.table.LookupList.Lookup): |
| 175 |
routine, deps = self.unparseLookup(lookup, lookupIdx) |
| 176 |
debug = self.getDebugInfo(self._table, lookupIdx) |
| 177 |
if debug: |
| 178 |
routine.address = (self._table, lookupIdx, *debug) |
| 179 |
if debug[1]: |
| 180 |
routine.name = debug[1] |
| 181 |
self._copyRoutineToRoutine(routine, self.lookups[lookupIdx]) |
| 182 |
|
| 183 |
def _copyRoutineToRoutine(self, src, dst): |
| 184 |
dst.name = src.name |
| 185 |
dst.rules = src.rules |
| 186 |
dst.flags = src.flags |
| 187 |
dst.address = src.address |
| 188 |
dst.comments = src.comments |
| 189 |
dst.inlined = src.inlined |
| 190 |
dst.languages = src.languages |
| 191 |
dst.parent = src.parent |
| 192 |
dst.flags = src.flags |
| 193 |
dst.markFilteringSet = src.markFilteringSet |
| 194 |
dst.markAttachmentSet = src.markAttachmentSet |
| 195 |
|
| 196 |
def unparseLookup(self, lookup, lookupIdx): |
| 197 |
"""Dispatches to the appropriate lookup unparser.""" |
| 198 |
self.currentLookup = lookupIdx |
| 199 |
unparser = getattr(self, "unparse" + self.lookupTypes[lookup.LookupType]) |
| 200 |
return unparser(lookup) |
| 201 |
|
| 202 |
def unparseExtension(self, lookup): |
| 203 |
"""Handles extension lookups by recursing into them.""" |
| 204 |
routines = [] |
| 205 |
dependencies = [] |
| 206 |
for xt in lookup.SubTable: |
| 207 |
xt.SubTable = [xt.ExtSubTable] |
| 208 |
xt.LookupType = xt.ExtSubTable.LookupType |
| 209 |
xt.LookupFlag = lookup.LookupFlag |
| 210 |
if hasattr(lookup, "MarkFilteringSet"): |
| 211 |
xt.MarkFilteringSet = lookup.MarkFilteringSet |
| 212 |
routine, deps = self.unparseLookup(xt, self.currentLookup) |
| 213 |
routines.append(routine) |
| 214 |
dependencies.extend(deps) |
| 215 |
extension = fontFeatures.ExtensionRoutine( |
| 216 |
routines=routines, |
| 217 |
name=self.getname("Extension" + self.gensym()), |
| 218 |
) |
| 219 |
self._fix_flags(extension, lookup) |
| 220 |
return extension, dependencies |
| 221 |
|
| 222 |
def getDebugInfo(self, table, ix): |
| 223 |
"""If information is present in the font's Debg table, use that to |
| 224 |
retrieve the original address and routine names.""" |
| 225 |
if not self.font or "Debg" not in self.font: |
| 226 |
return None |
| 227 |
debug_data = self.font["Debg"].data |
| 228 |
if "com.github.fonttools.feaLib" not in debug_data: |
| 229 |
return None |
| 230 |
debug_data = debug_data["com.github.fonttools.feaLib"][table][str(ix)] |
| 231 |
return debug_data[0], debug_data[1].replace("-", "_") |
| 232 |
|
| 233 |
def _asXML(self, sub): |
| 234 |
writer = XMLWriter(BytesIO()) |
| 235 |
sub.toXML(writer, self.font) |
| 236 |
out = writer.file.getvalue().decode("utf-8") |
| 237 |
return out |
| 238 |
|
| 239 |
def unparsable(self, b, e, sub): |
| 240 |
"""Warn about an unparsable lookup.""" |
| 241 |
import warnings |
| 242 |
|
| 243 |
warnings.warn( |
| 244 |
"# XXX Unparsable rule: " + str(e) + " in " + str(self.currentLookup) |
| 245 |
) |
| 246 |
b.addComment("# ----") |
| 247 |
out = self._asXML(sub).splitlines() |
| 248 |
for ln in out: |
| 249 |
b.addComment("# " + ln) |
| 250 |
b.addComment("# ----\n") |
| 251 |
|
| 252 |
def _fix_flags(self, routine, lookup): |
| 253 |
routine.flags = lookup.LookupFlag |
| 254 |
mat = lookup.LookupFlag & 0xFF00 |
| 255 |
if mat: |
| 256 |
mat = mat >> 8 |
| 257 |
classDefs = self.font["GDEF"].table.MarkAttachClassDef.classDefs |
| 258 |
glyphs = [g for g in classDefs.keys() if classDefs[g] == mat] |
| 259 |
routine.markAttachmentSet = glyphs |
| 260 |
if lookup.LookupFlag & 0x10 and hasattr(lookup, "MarkFilteringSet"): |
| 261 |
routine.markFilteringSet = ( |
| 262 |
self.font["GDEF"] |
| 263 |
.table.MarkGlyphSetsDef.Coverage[lookup.MarkFilteringSet] |
| 264 |
.glyphs |
| 265 |
) |
| 266 |
|
| 267 |
if routine.flags & 0x10: |
| 268 |
assert routine.markFilteringSet is not None |
| 269 |
|
| 270 |
def unparseContextual(self, lookup): |
| 271 |
"""Handles a generic contextual lookup, in various formats.""" |
| 272 |
b = fontFeatures.Routine( |
| 273 |
name=self.getname("Contextual" + self._table + self.gensym()) |
| 274 |
) |
| 275 |
self._fix_flags(b, lookup) |
| 276 |
for sub in lookup.SubTable: |
| 277 |
if sub.Format == 1: |
| 278 |
self._unparse_contextual_format1(sub, b, lookup) |
| 279 |
elif sub.Format == 2: |
| 280 |
self._unparse_contextual_format2(sub, b, lookup) |
| 281 |
elif sub.Format == 3: |
| 282 |
self._unparse_contextual_format3(sub, b, lookup) |
| 283 |
else: |
| 284 |
raise ValueError |
| 285 |
return b, [] |
| 286 |
|
| 287 |
def _unparse_contextual_format1(self, sub, b, lookup): |
| 288 |
lookups = [] |
| 289 |
rulesetattr, ruleattr, lookupattr = [ |
| 290 |
self._attrs[x] for x in ["format1_ruleset", "format1_rule", "lookup"] |
| 291 |
] |
| 292 |
|
| 293 |
for subrulesets, input_ in zip(getattr(sub, rulesetattr), sub.Coverage.glyphs): |
| 294 |
for subrule in getattr(subrulesets, ruleattr): |
| 295 |
lookups = [] |
| 296 |
allinput = [glyph(x) for x in ([input_] + subrule.Input)] |
| 297 |
lookups, note = self._unparse_lookups( |
| 298 |
getattr(subrule, lookupattr), allinput |
| 299 |
) |
| 300 |
rule = fontFeatures.Chaining( |
| 301 |
allinput, |
| 302 |
lookups=lookups, |
| 303 |
address=self.currentLookup, |
| 304 |
flags=lookup.LookupFlag, |
| 305 |
) |
| 306 |
if note: |
| 307 |
rule.note = note |
| 308 |
b.addRule(rule) |
| 309 |
return |
| 310 |
|
| 311 |
def _unparse_contextual_format2(self, sub, b, lookup): |
| 312 |
return self._unparse_contextual_chain_format2(sub, b, lookup, chain=False) |
| 313 |
|
| 314 |
def _unparse_contextual_format3(self, sub, b, lookup): |
| 315 |
return self._unparse_contextual_chain_format3(sub, b, lookup, chain=False) |
| 316 |
|
| 317 |
def unparseChainedContextual(self, lookup): |
| 318 |
"""Handles a generic chained contextual lookup, in various formats.""" |
| 319 |
b = fontFeatures.Routine( |
| 320 |
name=self.getname("ChainedContextual" + self._table + self.gensym()) |
| 321 |
) |
| 322 |
self._fix_flags(b, lookup) |
| 323 |
for sub in lookup.SubTable: |
| 324 |
if sub.Format == 1: |
| 325 |
self._unparse_contextual_chain_format1(sub, b, lookup) |
| 326 |
elif sub.Format == 2: |
| 327 |
self._unparse_contextual_chain_format2(sub, b, lookup) |
| 328 |
elif sub.Format == 3: |
| 329 |
self._unparse_contextual_chain_format3(sub, b, lookup) |
| 330 |
else: |
| 331 |
raise ValueError |
| 332 |
return b, [] |
| 333 |
|
| 334 |
def _unparse_contextual_chain_format1(self, sub, b, lookup): |
| 335 |
rulesetattr, ruleattr, lookupattr = [ |
| 336 |
self._attrs[x] |
| 337 |
for x in ["chain_format1_ruleset", "chain_format1_rule", "lookup"] |
| 338 |
] |
| 339 |
|
| 340 |
for subrulesets, input_ in zip(getattr(sub, rulesetattr), sub.Coverage.glyphs): |
| 341 |
for subrule in getattr(subrulesets, ruleattr): |
| 342 |
lookups = [] |
| 343 |
inputs = [glyph(x) for x in ([input_] + subrule.Input)] |
| 344 |
prefix = [glyph(x) for x in reversed(subrule.Backtrack)] |
| 345 |
suffix = [glyph(x) for x in subrule.LookAhead] |
| 346 |
lookups, note = self._unparse_lookups( |
| 347 |
getattr(subrule, lookupattr), inputs |
| 348 |
) |
| 349 |
rule = fontFeatures.Chaining( |
| 350 |
inputs, |
| 351 |
prefix, |
| 352 |
suffix, |
| 353 |
lookups=lookups, |
| 354 |
address=self.currentLookup, |
| 355 |
flags=lookup.LookupFlag, |
| 356 |
) |
| 357 |
if note: |
| 358 |
rule.note = note |
| 359 |
b.addRule(rule) |
| 360 |
|
| 361 |
def _unparse_contextual_chain_format2(self, sub, b, lookup, chain=True): |
| 362 |
if chain: |
| 363 |
rulesetattr, ruleattr, lookupattr = [ |
| 364 |
self._attrs[x] |
| 365 |
for x in ["chain_format2_classset", "chain_format2_rule", "lookup"] |
| 366 |
] |
| 367 |
else: |
| 368 |
rulesetattr, ruleattr, lookupattr = [ |
| 369 |
self._attrs[x] for x in ["format2_classset", "format2_rule", "lookup"] |
| 370 |
] |
| 371 |
|
| 372 |
if chain: |
| 373 |
backtrack = {} |
| 374 |
if sub.BacktrackClassDef: |
| 375 |
backtrack = self._invertClassDef( |
| 376 |
sub.BacktrackClassDef.classDefs, self.font |
| 377 |
) |
| 378 |
lookahead = {} |
| 379 |
if sub.LookAheadClassDef: |
| 380 |
lookahead = self._invertClassDef( |
| 381 |
sub.LookAheadClassDef.classDefs, self.font |
| 382 |
) |
| 383 |
inputs = {} |
| 384 |
inputs = self._invertClassDef(sub.InputClassDef.classDefs, self.font) |
| 385 |
else: |
| 386 |
inputs = self._invertClassDef(sub.ClassDef.classDefs, self.font) |
| 387 |
|
| 388 |
rulesets = getattr(sub, rulesetattr) |
| 389 |
for classId, ruleset in enumerate(rulesets): |
| 390 |
if not ruleset: |
| 391 |
continue |
| 392 |
rules = getattr(ruleset, ruleattr) |
| 393 |
inputclass = inputs.get(classId, []) |
| 394 |
# The coverage filters the input class... |
| 395 |
inputclass = [g for g in inputclass if g in sub.Coverage.glyphs] |
| 396 |
for r in rules: |
| 397 |
if chain: |
| 398 |
prefix = list(reversed([backtrack[x] for x in r.Backtrack])) |
| 399 |
suffix = [lookahead[x] for x in r.LookAhead] |
| 400 |
input_ = [inputclass] + [inputs[x] for x in r.Input] |
| 401 |
else: |
| 402 |
prefix, suffix = [], [] |
| 403 |
input_ = [inputclass] + [inputs[x] for x in r.Class] |
| 404 |
lookups, note = self._unparse_lookups(getattr(r, lookupattr), input_) |
| 405 |
rule = fontFeatures.Chaining( |
| 406 |
input_, |
| 407 |
prefix, |
| 408 |
suffix, |
| 409 |
lookups=lookups, |
| 410 |
address=self.currentLookup, |
| 411 |
flags=lookup.LookupFlag, |
| 412 |
) |
| 413 |
if note: |
| 414 |
rule.note = note |
| 415 |
b.addRule(rule) |
| 416 |
|
| 417 |
def _unparse_contextual_chain_format3(self, sub, b, lookup, chain=True): |
| 418 |
lookupattr = self._attrs["lookup"] |
| 419 |
prefix, suffix, inputs = [], [], [] |
| 420 |
|
| 421 |
if chain: |
| 422 |
for coverage in reversed(sub.BacktrackCoverage): |
| 423 |
prefix.append(coverage.glyphs) |
| 424 |
for coverage in sub.LookAheadCoverage: |
| 425 |
suffix.append(coverage.glyphs) |
| 426 |
for coverage in sub.InputCoverage: |
| 427 |
inputs.append(coverage.glyphs) |
| 428 |
else: |
| 429 |
for coverage in sub.Coverage: |
| 430 |
inputs.append(coverage.glyphs) |
| 431 |
|
| 432 |
lookups, note = self._unparse_lookups(getattr(sub, lookupattr), inputs) |
| 433 |
rule = fontFeatures.Chaining( |
| 434 |
inputs, |
| 435 |
prefix, |
| 436 |
suffix, |
| 437 |
lookups=lookups, |
| 438 |
address=self.currentLookup, |
| 439 |
flags=lookup.LookupFlag, |
| 440 |
) |
| 441 |
if note: |
| 442 |
rule.note = note |
| 443 |
b.addRule(rule) |