| Summary: | show_text() requires a (UTF-8) str | ||
|---|---|---|---|
| Product: | pycairo | Reporter: | Ken Harris <kengruven> |
| Component: | general | Assignee: | Steve Chaplin <d74n5pohf9> |
| Status: | RESOLVED FIXED | QA Contact: | |
| Severity: | minor | ||
| Priority: | high | ||
| Version: | unspecified | ||
| Hardware: | x86 (IA32) | ||
| OS: | Linux (All) | ||
| Whiteboard: | |||
| i915 platform: | i915 features: | ||
I tried show_text() with a unicode string and it worked OK. Could you attach a minimal example which calls show_text() and raises an exception, and calls PyGTK/gtk.Button and works OK, so I can see the problem. Sure. (FYI, this is with Cairo and PyCairo 1.0.2 in Debian unstable.)
Here's my sample program:
import cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 400)
c = cairo.Context(surface)
c.set_source_rgb(1.0, 0.0, 0.0)
c.select_font_face("FreeSerif", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORM\AL)
c.set_font_size(72)
c.move_to(100, 200)
c.show_text("hello") # ***
c.stroke()
surface.write_to_png("cairotext.png")
The line marked *** is the interesting one:
- as written above, with "hello" (a str, all ASCII chars) it works fine
- with u"\u0633" (a unicode string with non-ASCII chars), it gives this error:
Traceback (most recent call last):
File "cairotext.py", line 11, in ?
c.show_text(u"\u0633")
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0633' in position
0: ordinal not in range(128)
- with u"\u0633".encode("UTF-8") it works fine
In PyGTK, this works fine:
import gtk
w = gtk.Window()
b = gtk.Button(u"hello, world! \u0633")
w.add(b)
w.show_all()
gtk.main()
Fixed show_text() to accept string or unicode objects. Also did the same for some other cairo functions that accept UTF-8 format strings. * cairo/pycairo-context.c (__PyBaseString_AsUTF8): new function. (pycairo_select_font_face, pycairo_show_text, pycairo_text_extents) (pycairo_text_path): allow the string argument to be a unicode or string object, and convert to UTF-8 encoding. |
Use of freedesktop.org services, including Bugzilla, is subject to our Code of Conduct. How we collect and use information is described in our Privacy Policy.
Right now in PyCairo, the argument to show_text() is a UTF-8 str -- same as the C API. This means that if you have some Unicode text you want to display, you need to say context.show_text(foo.encode("UTF-8")). It raises an exception if you try to pass a unicode object directly to show_text(). In other Python bindings (e.g., PyGTK), this is done internally, so you can simply pass str or unicode objects (e.g., as the text of a GtkButton). PyCairo would be more fun if show_text() did this, too.