Inlined images

In the previous example we have shown how to display simple HTML document in GtkHTML widget. Now we modify this example so it could display HTML with inlined images. Lets modify html_source to:


const gchar *html_source = "<B><FONT COLOR=Blue>Hello world!</FONT></B>"
"<IMG SRC=file:smiley.png>"

If you try to compile and run the modified example, you will find out that instead of a smiley image, an empty rectangle is displayed. The GtkHTML widget itself does not handle loading of a data linked by an URL (i.e. file:smiley.png picture).

When GtkHTML requires data from an URL, it emits the url_requested signal. We need to provide a signal handler which will load data from the requested URL location. The following function handles retrieval of data from URLs in the form file:filename. In our case it will load a smiley PNG image.


/* url_requested signal handler which is able to provide data for file:* url's
 * in our case for inlined image(s)
 */
static void
url_requested (GtkHTML *html, const char *url, GtkHTMLStream *stream)
{
	int fd;

	if (url && !strncmp (url, "file:", 5)) {
		url += 5;
		fd = open (url, O_RDONLY);

		if (fd != -1) {
			gchar *buf;
			size_t size;

			buf = alloca (8192);
			while ((size = read (fd, buf, 8192)) > 0) {
				gtk_html_stream_write (stream, buf, size);
			}
			gtk_html_stream_close (stream,
					       size == -1
					       ? GTK_HTML_STREAM_ERROR
					       : GTK_HTML_STREAM_OK);
			close (fd);

			return;
		}
	}

	gtk_html_stream_close (stream, GTK_HTML_STREAM_ERROR);
}

The signal is connected after widget creation and before content loading:


	html = gtk_html_new ();
	gtk_signal_connect (GTK_OBJECT (html), "url_requested",
                            GTK_SIGNAL_FUNC (url_requested), NULL);
	gtk_html_load_from_string (GTK_HTML (html), html_source, -1);

Note that we have used the gtk_html_new constructor and to load content, we used the gtk_html_load_from_string function. The reason for this is that we want to have the url_request signal handler connected before the content is loaded. Definition of newly used functions:


GtkWidget * gtk_html_new              ();
void        gtk_html_load_from_string (GtkHTML     *html,
                                       const gchar *str,
                                       gint         len);

Additional header files to be included:


#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

With older version of GtkHTML, the following must also be called:


gdk_rgb_init ();
function.

Now our example is complete and the following picture shows Example 2 running.

Figure 2. Screenshot of running Example 2

Complete example sources are available at http://peabody.ximian.com/~rodo/gtkhtml/tutorial/