1 #!/usr/bin/python 2 # -*- coding: utf-8 -*- 3 4 from __future__ import print_function 5 import sys 6 import array 7 from gi.repository import HarfBuzz as hb 8 from gi.repository import GLib 9 10 # Python 2/3 compatibility 11 try: 12 unicode 13 except NameError: 14 unicode = str 15 16 def tounicode(s, encoding='utf-8'): 17 if not isinstance(s, unicode): 18 return s.decode(encoding) 19 else: 20 return s 21 22 fontdata = open (sys.argv[1], 'rb').read () 23 text = 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 26 blob = hb.glib_blob_create (GLib.Bytes.new (fontdata)) 27 face = hb.face_create (blob, 0) 28 del blob 29 font = hb.font_create (face) 30 upem = hb.face_get_upem (face) 31 del face 32 hb.font_set_scale (font, upem, upem) 33 #hb.ft_font_set_funcs (font) 34 hb.ot_font_set_funcs (font) 35 36 buf = hb.buffer_create () 37 class Debugger(object): 38 def message (self, buf, font, msg, data, _x_what_is_this): 39 print(msg) 40 return True 41 debugger = Debugger() 42 hb.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 # 50 if 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: 57 elif sys.maxunicode == 0x10FFFF: 58 hb.buffer_add_utf32 (buf, array.array('I', text.encode('utf-32')), 0, -1) 59 else: 60 hb.buffer_add_utf16 (buf, array.array('H', text.encode('utf-16')), 0, -1) 61 62 63 hb.buffer_guess_segment_properties (buf) 64 65 hb.shape (font, buf, []) 66 del font 67 68 infos = hb.buffer_get_glyph_infos (buf) 69 positions = hb.buffer_get_glyph_positions (buf) 70 71 for 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