| 1 |
from collections import defaultdict |
| 2 |
import logging |
| 3 |
|
| 4 |
from fontTools.feaLib import ast |
| 5 |
from fontTools.misc.visitor import Visitor |
| 6 |
|
| 7 |
from babelfont.Font import Font |
| 8 |
|
| 9 |
logger = logging.getLogger(__name__) |
| 10 |
|
| 11 |
|
| 12 |
def drop_unexported_glyphs(font: Font, _args=None): |
| 13 |
logger.info("Dropping unexported glyphs") |
| 14 |
unexported = set(glyph.name for glyph in font.glyphs if not glyph.exported) |
| 15 |
# Safety check one: look in components: |
| 16 |
appearances = defaultdict(set) |
| 17 |
for glyph in font.glyphs: |
| 18 |
for layer in glyph.layers: |
| 19 |
for c in layer.components: |
| 20 |
if c.ref in unexported: |
| 21 |
appearances[c.ref].add(glyph.name) |
| 22 |
if appearances: |
| 23 |
logger.warning( |
| 24 |
"Unexported glyphs are used in components, use decomposeMixed first:" |
| 25 |
) |
| 26 |
for glyph, refs in appearances.items(): |
| 27 |
logger.warning(f" {glyph} -> {', '.join(refs)}") |
| 28 |
logger.warning("Will not drop these glyphs.") |
| 29 |
unexported -= set(appearances.keys()) |
| 30 |
# Safety check two: look in features |
| 31 |
parsed_features = font.features.as_ast(font) |
| 32 |
|
| 33 |
for featurename, parsed in parsed_features["features"]: |
| 34 |
visitor = FeaAppearsVisitor() |
| 35 |
visitor.visit(parsed) |
| 36 |
for glyph in visitor.appearances: |
| 37 |
if glyph in unexported: |
| 38 |
logger.warning( |
| 39 |
f"Unexported glyph {glyph} is used in feature {featurename}, will not drop it." |
| 40 |
) |
| 41 |
unexported.remove(glyph) |
| 42 |
for classname, glyphs in font.features.classes.items(): |
| 43 |
for glyph in glyphs: |
| 44 |
if glyph in unexported: |
| 45 |
logger.warning( |
| 46 |
f"Unexported glyph {glyph} is used in class @{classname}, will not drop it." |
| 47 |
) |
| 48 |
unexported.remove(glyph) |
| 49 |
for prefix, parsed in parsed_features["prefixes"].items(): |
| 50 |
visitor = FeaAppearsVisitor() |
| 51 |
visitor.visit(parsed) |
| 52 |
for glyph in visitor.appearances: |
| 53 |
if glyph in unexported: |
| 54 |
logger.warning( |
| 55 |
f"Unexported glyph {glyph} is used in prefix {prefix}, will not drop it." |
| 56 |
) |
| 57 |
unexported.remove(glyph) |
| 58 |
|
| 59 |
# Now we are good to go |
| 60 |
for glyph in unexported: |
| 61 |
font.glyphs.pop(glyph) |
| 62 |
|
| 63 |
|
| 64 |
class FeaAppearsVisitor(Visitor): |
| 65 |
def __init__(self): |
| 66 |
self.appearances = set() |
| 67 |
|
| 68 |
|
| 69 |
@FeaAppearsVisitor.register(ast.GlyphName) |
| 70 |
def visit(visitor, gn, *args, **kwargs): |
| 71 |
visitor.appearances.add(gn.glyph) |
| 72 |
return False |
| 73 |
|
| 74 |
|
| 75 |
@FeaAppearsVisitor.register(ast.MarkClassDefinition) |
| 76 |
def visit(visitor, mcd, *args, **kwargs): |
| 77 |
visitor.visitAttr(mcd, "glyphs", mcd.glyphs, *args, **kwargs) |
| 78 |
return False |