Short gtkhtml2 tutorial

GtkHTML2 is a sorely undocumented widget. I still occasionally get trouble with it, and I know I'm not the only one. While its future may be in question — gtkhtml1 replacing it is still a possibility, because the Ximian hackers are committed to maintaining it — it's the HTML widget of choice for Gtk2/GNOME 2 hacking today. Few notes on it follow, examples in Python:

Initializing the widget.

# I assume there's a scrolledwindow widget called html_scrolled_window

# in a glade widget tree available

scrolled_window = glade_widget_tree.get_widget('html_scrolled_window')

htmlview = gtkhtml2.View()

document = gtkhtml2.Document()

scrolled_window.set_hadjustment(htmlview.get_hadjustment())

scrolled_window.set_vadjustment(htmlview.get_vadjustment())

document.clear()

htmlview.set_document(document)

scrolled_window.add(htmlview)

scrolled_window.show_all()

IIRC doing things in the wrong sequence could cause segfaults.

There are a few signals that are useful to connect to:

# The document object's link-clicked signal is emitted when the user

# clicks a link.

document.connect("link-clicked", link_clicked)

# The document emits request-url when it needs data from an url.

# This is used for at least image fetching.

document.connect("request-url", request_url)

# Htmlview emits on_url (yes, this is spelled with an underscore

# unlike the two others) when the mouse is on an url. This is useful for

# displaying the URL somewhere.

htmlview.connect("on_url", on_url)

link_clicked receives the document object and link href as arguments. request_url receives the document, URL and a stream to write the data to. You should just fetch the data from the URL and write it to the stream. on_url receives the htmlview object and the url.

To display data in the widget, you need to write to the document object's stream. Something like this:

document.clear()

document.open_stream("text/html") # this is the only mime type recognized

document.write_stream("<html><head><title>title</title>" +

"</head><body>body</body></html>")

document.close_stream()

Note that this — I think — assumes ISO 8859-1 encoding. If you want something different, you have to specify that... wait for it, try to guess... with a meta header. There is apparently no API to do that; it must be specified in the document stream itself. So, for UTF-8, you want to add this to the head part:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

That's it. Now you can display HTML documents in your GNOME 2 applications. I'll probably write some more once I have something to tell about using CSS with gtkhtml2.

© Juri Pakaste 2023