Exemplo n.º 1
0
def get_text_shape(text, font=None, weight=None, path=None, debug=False):
    if weight is not None:
        font = f'{font}:{weight}'
    if path is None:
        path = get_font_path(font)

    base, ext = os.path.splitext(path)
    ext = ext[1:]

    with open(path, 'rb') as fid:
        fontdata = fid.read()

    bdata = GLib.Bytes.new(fontdata)
    blob = hb.glib_blob_create(bdata)
    face = hb.face_create(blob, 0)

    font = hb.font_create(face)
    upem = hb.face_get_upem(face)
    hb.font_set_scale(font, upem, upem)
    # hb.font_set_ptem(font, font_size)

    if ext == 'woff':
        hb.ft_font_set_funcs(font)

    buf = hb.buffer_create()
    hb.buffer_add_utf8(buf, text.encode('utf-8'), 0, -1)

    hb.buffer_guess_segment_properties(buf)
    hb.shape(font, buf, [])
    infos = hb.buffer_get_glyph_infos(buf)
    positions = hb.buffer_get_glyph_positions(buf)
    extents = [hb.font_get_glyph_extents(font, i.codepoint) for i in infos]

    if debug:
        return font, infos, positions, extents

    norm = upem
    wh_extract = lambda ext: (ext.extents.width / norm, -ext.extents.height /
                              norm)

    cluster = [(i.codepoint, i.cluster) for i in infos]
    shapes = [wh_extract(e) for e in extents]
    deltas = [(p.x_advance / norm, p.y_advance / norm) for p in positions]
    offsets = [(p.x_offset / norm, p.y_offset / norm) for p in positions]

    return cluster, shapes, deltas, offsets
Exemplo n.º 2
0
text = tounicode(sys.argv[2])
# Need to create GLib.Bytes explicitly until this bug is fixed:
# https://bugzilla.gnome.org/show_bug.cgi?id=729541
blob = hb.glib_blob_create (GLib.Bytes.new (fontdata))
face = hb.face_create (blob, 0)
del blob
font = hb.font_create (face)
upem = hb.face_get_upem (face)
del face
hb.font_set_scale (font, upem, upem)
# select "ft" or "ot" for get the right margins - see:
# https://github.com/harfbuzz/harfbuzz/issues/1248
# https://github.com/harfbuzz/harfbuzz/issues/1262
# and also
# https://github.com/harfbuzz/harfbuzz/issues/537
hb.ft_font_set_funcs(font)
#hb.ot_font_set_funcs (font)

buf = hb.buffer_create ()
class Debugger(object):
    def message (self, buf, font, msg, data, _x_what_is_this):
        print(msg)
        return True
debugger = Debugger()
#hb.buffer_set_message_func (buf, debugger.message, 1, 0)

##
## Add text to buffer
##
#
# See https://github.com/harfbuzz/harfbuzz/pull/271