Monday, January 26, 2009

Embedding Mozilla

To finish this series on embedding existing GNOME stuff in new apps, this is one of the design mockups of the browser in Sugar:


We are implementing it with Mozilla for now (though would love to have an alternative in WebKit as well, code welcome) and after some time using gtkmozembed, Marco decided that we would be better off with something lighter (read less buggy), with less amount of C code and with easy access to PyXPCOM. Then hulahop was born.

This is the simplest snippet that will bring you an embedded instance of mozilla into your pygtk app:

import os

import gobject
gobject.threads_init()
import gtk

import hulahop
hulahop.startup(os.path.expanduser('~/.hulahop_test_profile'))
from hulahop.webview import WebView

w = gtk.Window()
w.show()

v = WebView()
w.add(v)
v.show()

v.load_uri('http://planet.gnome.org')

gtk.main()


But that isn't anything that gtkmozembed cannot do, so if you add the following snippet just before the call to gtk.main(), you will get something more interesting ;)

import xpcom
from xpcom.components import interfaces

class ProgressListener(object):
_com_interfaces_ = interfaces.nsIWebProgressListener

def onStateChange(self, webProgress, request, stateFlags, status):
if not (stateFlags & interfaces.nsIWebProgressListener.STATE_IS_NETWORK and \
stateFlags & interfaces.nsIWebProgressListener.STATE_STOP):
return

images = v.dom_window.document.documentElement.getElementsByTagName('IMG')
for i in range(images.length):
image = images.item(i)
if image.src.startswith('http://planet.gnome.org/heads'):
image.height *= 3
image.width /= 3

listener = ProgressListener()
wrapped_listener = xpcom.server.WrapObject(listener,
interfaces.nsIWebProgressListener)
v.web_progress.addProgressListener(wrapped_listener,
interfaces.nsIWebProgress.NOTIFY_STATE_ALL)

As you can see, with hulahop you have ready access to most mozilla internals, in the example above we are manipulating the document DOM, but you can also access network stuff, security, user events, etc

Right now, those snippets will work only on Fedora 10 unless you build your own stuff. But as in the abiword case, people are already working on packaging hulahop for all the major distros.

And what about the future? I would love to see more applications to provide their canvases as proper gtk widgets and moving them to libraries. The ones on the top of my list are gnumeric and inkscape, any suggestion?

1 comment:

Lucian said...

Thanks a lot! I got userscripts working.

Greasepython FTW!