xref: /aosp_15_r20/external/fonttools/Snippets/decompose-ttf.py (revision e1fe3e4ad2793916b15cccdc4a7da52a7e1dd0e9)
1*e1fe3e4aSElliott Hughes#! /usr/bin/env python3
2*e1fe3e4aSElliott Hughes
3*e1fe3e4aSElliott Hughes# Example script to decompose the composite glyphs in a TTF into
4*e1fe3e4aSElliott Hughes# non-composite outlines.
5*e1fe3e4aSElliott Hughes
6*e1fe3e4aSElliott Hughes
7*e1fe3e4aSElliott Hughesimport sys
8*e1fe3e4aSElliott Hughesfrom fontTools.ttLib import TTFont
9*e1fe3e4aSElliott Hughesfrom fontTools.pens.recordingPen import DecomposingRecordingPen
10*e1fe3e4aSElliott Hughesfrom fontTools.pens.ttGlyphPen import TTGlyphPen
11*e1fe3e4aSElliott Hughes
12*e1fe3e4aSElliott Hughestry:
13*e1fe3e4aSElliott Hughes    import pathops
14*e1fe3e4aSElliott Hughesexcept ImportError:
15*e1fe3e4aSElliott Hughes    sys.exit(
16*e1fe3e4aSElliott Hughes        "This script requires the skia-pathops module. "
17*e1fe3e4aSElliott Hughes        "`pip install skia-pathops` and then retry."
18*e1fe3e4aSElliott Hughes    )
19*e1fe3e4aSElliott Hughes
20*e1fe3e4aSElliott Hughes
21*e1fe3e4aSElliott Hughesif len(sys.argv) != 3:
22*e1fe3e4aSElliott Hughes    print("usage: decompose-ttf.py fontfile.ttf outfile.ttf")
23*e1fe3e4aSElliott Hughes    sys.exit(1)
24*e1fe3e4aSElliott Hughes
25*e1fe3e4aSElliott Hughessrc = sys.argv[1]
26*e1fe3e4aSElliott Hughesdst = sys.argv[2]
27*e1fe3e4aSElliott Hughes
28*e1fe3e4aSElliott Hugheswith TTFont(src) as f:
29*e1fe3e4aSElliott Hughes    glyfTable = f["glyf"]
30*e1fe3e4aSElliott Hughes    glyphSet = f.getGlyphSet()
31*e1fe3e4aSElliott Hughes
32*e1fe3e4aSElliott Hughes    for glyphName in glyphSet.keys():
33*e1fe3e4aSElliott Hughes        if not glyfTable[glyphName].isComposite():
34*e1fe3e4aSElliott Hughes            continue
35*e1fe3e4aSElliott Hughes
36*e1fe3e4aSElliott Hughes        # record TTGlyph outlines without components
37*e1fe3e4aSElliott Hughes        dcPen = DecomposingRecordingPen(glyphSet)
38*e1fe3e4aSElliott Hughes        glyphSet[glyphName].draw(dcPen)
39*e1fe3e4aSElliott Hughes
40*e1fe3e4aSElliott Hughes        # replay recording onto a skia-pathops Path
41*e1fe3e4aSElliott Hughes        path = pathops.Path()
42*e1fe3e4aSElliott Hughes        pathPen = path.getPen()
43*e1fe3e4aSElliott Hughes        dcPen.replay(pathPen)
44*e1fe3e4aSElliott Hughes
45*e1fe3e4aSElliott Hughes        # remove overlaps
46*e1fe3e4aSElliott Hughes        path.simplify()
47*e1fe3e4aSElliott Hughes
48*e1fe3e4aSElliott Hughes        # create new TTGlyph from Path
49*e1fe3e4aSElliott Hughes        ttPen = TTGlyphPen(None)
50*e1fe3e4aSElliott Hughes        path.draw(ttPen)
51*e1fe3e4aSElliott Hughes        glyfTable[glyphName] = ttPen.glyph()
52*e1fe3e4aSElliott Hughes
53*e1fe3e4aSElliott Hughes    f.save(dst)
54