xref: /aosp_15_r20/external/harfbuzz_ng/src/sample.py (revision 2d1272b857b1f7575e6e246373e1cb218663db8a)
1#!/usr/bin/env python3
2
3import sys
4import array
5import gi
6gi.require_version('HarfBuzz', '0.0')
7from gi.repository import HarfBuzz as hb
8from gi.repository import GLib
9
10fontdata = open (sys.argv[1], 'rb').read ()
11text = sys.argv[2]
12# Need to create GLib.Bytes explicitly until this bug is fixed:
13# https://bugzilla.gnome.org/show_bug.cgi?id=729541
14blob = hb.glib_blob_create (GLib.Bytes.new (fontdata))
15face = hb.face_create (blob, 0)
16del blob
17font = hb.font_create (face)
18upem = hb.face_get_upem (face)
19del face
20hb.font_set_scale (font, upem, upem)
21#hb.ft_font_set_funcs (font)
22hb.ot_font_set_funcs (font)
23
24buf = hb.buffer_create ()
25class Debugger (object):
26	def message (self, buf, font, msg, data, _x_what_is_this):
27		print (msg)
28		return True
29debugger = Debugger ()
30hb.buffer_set_message_func (buf, debugger.message, 1, 0)
31
32##
33## Add text to buffer
34##
35#
36# See https://github.com/harfbuzz/harfbuzz/pull/271
37#
38# If you do not care about cluster values reflecting Python
39# string indices, then this is quickest way to add text to
40# buffer:
41# hb.buffer_add_utf8 (buf, text.encode('utf-8'), 0, -1)
42# Otherwise, then following handles both narrow and wide
43# Python builds (the first item in the array is BOM, so we skip it):
44if sys.maxunicode == 0x10FFFF:
45	hb.buffer_add_utf32 (buf, array.array ('I', text.encode ('utf-32'))[1:], 0, -1)
46else:
47	hb.buffer_add_utf16 (buf, array.array ('H', text.encode ('utf-16'))[1:], 0, -1)
48
49
50hb.buffer_guess_segment_properties (buf)
51
52hb.shape (font, buf, [])
53del font
54
55infos = hb.buffer_get_glyph_infos (buf)
56positions = hb.buffer_get_glyph_positions (buf)
57
58for info, pos in zip (infos, positions):
59	gid = info.codepoint
60	cluster = info.cluster
61	x_advance = pos.x_advance
62	x_offset = pos.x_offset
63	y_offset = pos.y_offset
64
65	print ("gid%d=%d@%d,%d+%d" % (gid, cluster, x_advance, x_offset, y_offset))
66