Example #1
0
def gen_glyphs(ttfont, out):
    math = ttfont['MATH'].table
    cmap = ttfont['cmap'].getcmap(3, 10).cmap
    glyphs = ttfont.getGlyphSet()
    metrics = { name: {
        "usv": codepoint,
        "xmin": 0,
        "ymin": 0,
        "xmax": 0,
        "ymax": 0,
        "attachment": 0,
        "italics": 0,
        "advance": 0,
        "lsb": 0,
    } for codepoint, name in cmap.items() }

    # Gather bounding box information
    pen = BoundsPen(None)
    for glyph in cmap.values():
        bbox = (0, 0, 0, 0)
        glyphs.get(glyph).draw(pen)

        if pen.bounds is not None:
            (xmin, ymin, xmax, ymax) = pen.bounds
            bbox = (int(xmin), int(ymin), int(xmax), int(ymax))

        metrics[glyph]['xmin'] = bbox[0]
        metrics[glyph]['ymin'] = bbox[1]
        metrics[glyph]['xmax'] = bbox[2]
        metrics[glyph]['ymax'] = bbox[3]

        pen.bounds = None
        pen._start = None

    # Gather accent attachment
    accent_table = math.MathGlyphInfo.MathTopAccentAttachment
    accent_coverage = accent_table.TopAccentCoverage.glyphs
    for glyph in accent_coverage:
        value = accent_table \
            .TopAccentAttachment[accent_coverage.index(glyph)] \
            .Value
        metrics[glyph]["attachment"] = value

    # Gather italics offsets
    italics_table = math.MathGlyphInfo.MathItalicsCorrectionInfo
    italics_coverage = italics_table.Coverage.glyphs
    for glyph in italics_coverage:
        value = italics_table \
            .ItalicsCorrection[italics_coverage.index(glyph)] \
            .Value
        metrics[glyph]["italics"] = value

    # Gather advance and left side bearing
    hmtx = ttfont['hmtx'].metrics
    for glyph in cmap.values():
        (advance, lsb) = hmtx[glyph]
        metrics[glyph]["advance"] = advance
        metrics[glyph]["lsb"]     = lsb

    # Insert shim
    shim = []
    cmap = ttfont['cmap'].getcmap(3, 10).cmap
    for (new, old) in SHIM:
        if old in cmap:
            name = cmap[old]
            data = deepcopy(metrics[name])
            shim.append((new, data))
        else:
            print("Ignoring shim for", hex(old))

    template = Template(filename="tools/mako/glyphs.mako.rs")
    with open(out + "glyphs.rs", 'w') as file:
        file.write(template.render(glyphs=metrics, shim=shim))