Tuesday, the 29th of October, 2002

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 htmlscrolledwindow

# in a glade widget tree available

scrolledwindow = gladewidgettree.getwidget('htmlscrolledwindow')

htmlview = gtkhtml2.View()

document = gtkhtml2.Document()

scrolledwindow.sethadjustment(htmlview.gethadjustment())

scrolled
window.setvadjustment(htmlview.getvadjustment())

document.clear()

htmlview.setdocument(document)

scrolled
window.add(htmlview)

scrolledwindow.showall()

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", linkclicked)

# 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 onurl (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)

linkclicked receives the document object and link href as arguments. requesturl 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.openstream("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.

@ 00:00 +0200 [ ] archived