1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3
4from __future__ import print_function
5import sys
6import array
7from gi.repository import HarfBuzz as hb
8from gi.repository import GLib
9
10# Python 2/3 compatibility
11try:
12	unicode
13except NameError:
14	unicode = str
15
16def tounicode(s, encoding='utf-8'):
17	if not isinstance(s, unicode):
18		return s.decode(encoding)
19	else:
20		return s
21
22fontdata = open (sys.argv[1], 'rb').read ()
23text = tounicode(sys.argv[2])
24# Need to create GLib.Bytes explicitly until this bug is fixed:
25# https://bugzilla.gnome.org/show_bug.cgi?id=729541
26blob = hb.glib_blob_create (GLib.Bytes.new (fontdata))
27face = hb.face_create (blob, 0)
28del blob
29font = hb.font_create (face)
30upem = hb.face_get_upem (face)
31del face
32hb.font_set_scale (font, upem, upem)
33#hb.ft_font_set_funcs (font)
34hb.ot_font_set_funcs (font)
35
36buf = hb.buffer_create ()
37class Debugger(object):
38	def message (self, buf, font, msg, data, _x_what_is_this):
39		print(msg)
40		return True
41debugger = Debugger()
42hb.buffer_set_message_func (buf, debugger.message, 1, 0)
43
44##
45## Add text to buffer
46##
47#
48# See https://github.com/behdad/harfbuzz/pull/271
49#
50if False:
51	# If you do not care about cluster values reflecting Python
52	# string indices, then this is quickest way to add text to
53	# buffer:
54	hb.buffer_add_utf8 (buf, text.encode('utf-8'), 0, -1)
55	# Otherwise, then following handles both narrow and wide
56	# Python builds:
57elif sys.maxunicode == 0x10FFFF:
58	hb.buffer_add_utf32 (buf, array.array('I', text.encode('utf-32')), 0, -1)
59else:
60	hb.buffer_add_utf16 (buf, array.array('H', text.encode('utf-16')), 0, -1)
61
62
63hb.buffer_guess_segment_properties (buf)
64
65hb.shape (font, buf, [])
66del font
67
68infos = hb.buffer_get_glyph_infos (buf)
69positions = hb.buffer_get_glyph_positions (buf)
70
71for info,pos in zip(infos, positions):
72	gid = info.codepoint
73	cluster = info.cluster
74	x_advance = pos.x_advance
75	x_offset = pos.x_offset
76	y_offset = pos.y_offset
77
78	print("gid%d=%d@%d,%d+%d" % (gid, cluster, x_advance, x_offset, y_offset))
79