June 1, 2008
Blogroll, GNOME, General, PyGTK, Python, olpc
7 Comments
This was also sent to gtk-devel today:
== Introduction ==
GObject-introspection is a package which will collect and extend the API
metadata for GObject based libraries. The main motivation of this work is to
centralize all introspection information required to write a language binding.
There are many other use cases as well, some of them are described at:
http://live.gnome.org/GObjectIntrospection/
== Current status ==
The GObject-Introspection module/tarball contains the following:
* An XML format called GIR containing introspection information
* python package to create and parse the GIR format
* scanner to generate GIR format from C source and headers
These components are also included, but needs to be ported to the GIR format:
* a typelib similar to xpcom/msole which stores the information
on disk in a binary format
* a compiler to compile the typelib from a xml format (and vice versa)
* C library to read the typelib
A separate SVN module called gir-repository has been created.
The idea is to create .gir files of all libraries available in the
the whole stack which language bindings can depend on.
Eventually the plan is to move the .gir files into the upstream projects
themselves, but that’s likely to be a long process.
== GIR XML Format ==
The core of the GObject-introspection is an XML format which is called GIR (
GObject Introspection Repository) which contains the API introspection
metadata for a library or interface entity.
GIR currently contains three different XML namespaces:
- core: contains features available in popular programming languages: classes, methods, functions, interfaces, properties, strings, enums etc.
- c: contains features specific to the C language: identifiers, symbol names, C types
- glib: contains features specific to GLib/GObject: signal, GType, flags, paramspec
The separation of different data in different namespaces allow you
to reuse it allows you to arbitrarily extend the metadata available
in different languages.
== Scanner ==
To be able to bootstrap the effort and make something which will be
available in a reasonable timeframe we’ve been working on a scanner
which parsers C sources and headers and extracts the metadata and
generates a GIR file.
This is likely to be used by most of the Gtk/GNOME stack, as it would
require the least amount of work, however it’s not the only way to
use the GIR format nor GObject-Introspection.
In the future we might use something similar to CORBA IDL to define
the interface, as GIR is not meant to human editable.
In addition to the parsing the C headers, additional metadata will
be provided, likely by using source annotations in gtk-doc comments.
== Typelib ==
To be able to create efficient read introspection data we need a typelib, eg
an efficent disk format with a C API to access the internal data.
Matthias wrote one based on the XPCOM typelib which has not yet been
updated to the GIR format, it’s instead the tools to compile it are still
using an older XML format.
The work on finishing the typelib is depending on having the GIR format
somewhat stable and at that point updating the existing tools to understand it.
== How can I help? ==
At this point I’d like to get more eyes at the current GIR format to make
sure that it contains the necessary information and in a way which will
be easy to parse/access.
I am currently working mainly on the scanner to be able to quickly get
a large amount API expressed in GIR files.
For more information, check out the wiki page:
http://live.gnome.org/GObjectIntrospection/
And the gobject-introspection and gir-repository modules in GNOME SVN.
May 6, 2008
GNOME, General, PyGTK, Python, olpc
19 Comments
I have the pleasure of knowing the great mpt. He actually spent a couple of months in Brazil back in 2006 and we ended up sharing the same apartment during this period. One of the great things he masters is the art of writing ascii art mockups of user interfaces As I am a mere beginner might not be the best person to explain this. However I will make an attempt to explain the basic principles, in the effort of having this written down somewhere.
In this blog post I will focus on commonly used interactive widgets available in Gtk+, since these are the ones I tend to care the most about.
GtkEntry
An entry is straight forward, you use brackets in the beginning and the end and underscores to fill up the allocated width of the widget:
[____________]
If you want a text, just replace the underscores with letters
[Hello World____]
GtkButton
Buttons are similar to entries, the main difference is the lack of underscores and the use of capital letters. Icons are usually ignored as they often are rather tricky to represent using the ASCII alphabet. A cancel button looks like this:
[ CANCEL ]
GtkToggleButton and GtkRadioButton
Toggle buttons uses brackets around the toggle part and no brackets around the rest. If the value of the radio should be active, use a lowercase x to say so:
[ ] Buy milk and cheese for breakfast
[x] Eat strawberries after lunch
Radio buttons are similar but uses parenthesis and o, eg:
(o) Fresh fish
( ) Rotten eggs
GtkSpinButton
Spin buttons are similar to entries, but they have two small arrows on the right hand side. To represent the arrows, use H:
[1234 H]
This might not look good in all fonts, but it’s the best that can be done, at least as far as I know.
GtkComboBox
A combobox tend to be represented again by using brackes in the beginning and the end. To represent the arrow, use a lower case v and separate it from the text by using a | (pipe) sign.
[ Stockholm | v]
GtkDialog
Prett simple, use _ (underscore) and | (pipe) for the borders, titles and window manager buttons can usually be skipped since they are mostly noise to us in this context:
________________________________
| |
| Do you want to close the open |
| document and lose the changes |
| made to it? |
| [ CONTINUE ] [ QUIT ] |
|________________________________|
These are the widgets I usually end up using in my mockups. Have any missed any important onces? Or I have I done any serious mistakes? Comments appreciated!
Read the rest…
May 6, 2008
GNOME, General, PyGTK, Python
4 Comments
I often end up reading code using GtkListStore in Python, either in existing projects or on irc when someone asks me to fix their program. It’s pretty straight-forward to using the GtkTreeModel interface and it’s various implementations such as GtkListStore and GtkTreeStore. However, due to lack of proper documentation, the small pieces of Python sugar on top of the raw C wrappers is seldomly used. In this blog post I will attempt to document the most useful one in hope that some popular search engines will pick this up and help someone in the future.
Construction
For starters, let’s look into construction of GtkListStores:
model = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_INT, gobject.TYPE_FLOAT)
This creates a liststore with three columns, a string, an integer and a float. The column types are specified using the constants available in the gobject python module. Since I’m hardly a normal person, I’ll immediatelly get frustrated when I see that kind of code. Instead, I wish people could write the following code instead, which is shorter and thus easier to parse:
model = gtk.ListStore(str, int, float)
It does exactly the same things, interally str is mapped to the gobject.TYPE_STRING constant and so on.
Appending data
At some point during the life time of a program you want to insert data into a model. A common way of doing is that is
the following:
iter = model.append()
model.set(iter, 0, “foobar”)
model.set(iter, 1, 1138)
model.set(iter, 2, 3.14)
This appends a new row and sets the values”foobar”,1138 and 3.14 to the three columns. You can avoid the three different calls by sending in a list to append as the first argument, eg:
model.append([”foobar”, 1138, 3.14])
Which again, is the exact same thing. (Modula saving a reference to the inserted tree iter of course)
Fetching values
To fetch a value from the a model you usually get an iter, for example from a selection:
model, path = selection.get_selected()
value = model.get_value(model.get_iter(path) , 0)
Two things can be simplified here: First of all we take advantage that model implementes a list like api, you can just access the model list a list, eg: model[n]. Secondly you can send in either an index, path or iter as n, so the example above is simplified to:
model, path = selection.get_selected()
value = model[path][0]
Iteration
Iteration over all the values in the model is usually done something like this:
iter = model.get_iter_first()
while True:
value = model.get_value(iter, 0)
iter = model.iter_next(iter)
if iter is None:
break
Which can also be considerably simplified:
for row in model:
value = row[0]
Also note that using the variable name iter in a python program is always wrong, since there is a builtin variable with the same name. Avoid the name iter, and use for instance titer instead, which is almost as short and a bit clearer.
January 4, 2008
Blogroll, GNOME, General, PyGTK, Python, olpc
3 Comments
Yesterday I released two new releases of PyGObject and PyGTK. The most important change in both of releases is the support of a new API, available only in the svn version of Python which will prevent gobject and gtk from waking up once every 100 ms.
This should allow the CPU to be idle longer and thus save battery life, for your desktop and for children.
I would like to thank Guido van Rossum, Adam Olsen and Gustavo Carneiro for making sure that Python has enough support for this to be possible.
Unfortunately, it will take some time before this is widely used because it will only be included in Python 2.6. However, for OLPC the best option is probably to apply the patch from python issue 1583. Perhaps Linux distributors could do the same?
November 30, 2007
Blogroll, GNOME, General, PyGTK, Python, olpc
13 Comments
First of all, let me show you a screenshot showing what have been hacking on in my spare time over the last two weeks or so:
.
It’s showing a simple web browser written in python using WebKit, this is the code for that:
import bank
import Gtk, WebKit
win = Gtk.Window(Gtk.WindowType.TOPLEVEL)
p = WebKit.Page()
p.open(”http://www.google.com/”)
win.add(p)
win.show_all()
Gtk.main()
There are no specific bindings for WebKit, or even Gtk in this case. It’s all done using the introspection information available through gobject-introspection. I am not using the existing python bindings for GObject and GTK, I am instead using pybank, the python bindings for gobject-introspection.
The bank module, our interface to pybank differ from most (all?) GNOME language bindings written today by constructing the bindings in runtime. The bank module loads and interprets the metadata repository compiled using the g-idl-compiler tool. When you first access the Page class in WebKit it generates the Page class, and because it’s a GtkContainer subclass it imports the Gtk bindings and eventually the GObject ones as it’s also a subclass of GObject. When calling the constructors and methods it’s using libffi.
Before you’re all getting too excited, this is just a proof of concept, you won’t be able to build real applications based on pybank, you can’t even listen to signals yet. The only supported parameter types at the moment are int, str, enum and object. It’s mainly used a testcase for the introspection framework, to be able to make sure that the information available through introspection is going to work for this kind of language/binding.
The idea behind gobject-introspection is that each C library itself will generate and install the metadata at compile time. The metadata represents what you see in the C headers and a little bit extra which is already available through introspection in GObject such as properties, signals and class inheritence.
So what’s missing before we can start using this?
Jürg of Vala fame has written a header parser which will generate the metadata by scanning the headers. It’s in a pretty good state already, but not good enough to generate good enough metadata, it still needs to be tweaked a bit. The metadata in gobject-introspection needs a few additions such as typedefs, default values, a module/metdata mapping and a few other things.
In the screenshot attached below you can see that this is using about 6M of memory. Right, the bindings are not finished and the application is rather trivial, but I don’t expect this to go up significantly as I add more features for pybank, I expect it to go down as I can remove a couple of dependencies when gobject-introspection will be nearer to competition.
GObject-introspection goals:
- Provide all information necessary to generate language bindings
- Consolidate this information, to avoid duplication between all languages
- Encourage upstream projects to include the metadata
August 8, 2007
Blogroll, GNOME, General, PyGTK, Python, olpc
4 Comments
This blog post will give you an introduction to the ObjectList widget which is a part of the kiwi library.
* Rationale
Creating graphical user interfaces which displays a sequence of objects is a common task. In the GTK+ toolkit you will normally use a GtkTreeView for this. GtkTreeView is a very flexible and extensible widget, for instance it allows you to separate the data storage from the representation. However the disadvantage of using the GtkTreeView is that it’s a little bit too complicated to use, especially for beginners.
The ObjectList aims to provide a familiar API to create, manipulate and access sequences of objects. It builds on top of GtkTreeView, and allows you to access the “raw” objects (view, columns, model, cellrenderers, selection) in case you want to do something which is not directly supported by the ObjectList.
Kiwi and ObjectList are tied to the Python programming language and depends heavily on PyGTK (and thus CPython). However the concepts introduced in the widget are usually not specific to Python, it’s very possible to implement similar high level wrappers on top of GtkTreeView for C#, Java etc.
* Simple ObjectList example
Here is the source code and the output of a simple ObjectList example

Let’s walk through the example and explain what it does.
- The class Fruit is defined with two attributes; name and price.
- An ObjectList called fruits is created which has two columns, name and price
- 5 objects are created and inserted into the list.
The example is concluded by creating a PyGTK window, adding the objectlist to it and running the main loop.
The data displayed in the ObjectList is stored in normal python instances, there is no need to create and set column types for a GtkTreeModel and extract the data from your python objects and insert it into the model. The model / view separation is kept while still keeping it easy to use.
Notice that the data is appended to the list by calling the append() method of the ObjectList, this is intentionally similar to the append method of the builtin list type of python. If you wanted you could use the extend() method to insert a list of object at one go.
The objects inserted into the list can be modified by using standard python list concepts:
- iteration: for item in list
- accessing an individual item: list[n]
- removing an item: del list[n] or list.remove(item)
- accessing parts of the item: list[n:m]
There are also methods beyond a normal python list routines which only makes sense in graphical interfaces:
- selecting an item: list.select(item)
- getting the selected item: list.get_selected()
- changing the columns: list.set_columns(columns)
- getting the columsn: list.get_columns()
- etc…
* Columns
When you create a column you define how the data is going to be displayed. Column width, sorting, justification, markup and so on. Here is an incomplete list of the support column attributes:
- title: the text will be used in the column header
- justify: the justification, eg left or right aligned
- format: printf style format string
- width: width in pixels of the column
- sorted: if we should sort the data after the content in this column
- editable: is the column editable?
- use_markup: should the content be interpreted as markup?
- use_stock: treat the content as stock icon names and display icons
Here is a more complicated, real world example from Stoq, a Retail Management System written on top of Kiwi.


The interface shows the accounts payable application which lists outgoing payments.
What we can see from the screenshot is:
- The first column is sorted and it has the title “#”
- The third column is the supplier name which is a bit too wide to fit and uses ellipsize
- The fourth column is the date the purchase was sold and is formatted according to the current locale
- The last column uses the special datatype currency which formats a number according to the monetary rules defined for the current locale, with thousand separators, decimal points and currency symbols set right.
This is all for now, for more information about Kiwi check out Howto, the API reference and the source code repository
June 24, 2007
Blogroll, GNOME, General, PyGTK, Python
8 Comments
Yesterday I on a bus ride from São Paulo I had the opportunity to see some of the developments tools available on OSX. Shark and mallocdebug are quite interesting, bling-bling for the developer masses.
When I woke up this morning I realized that it shouldn’t be too difficult to do something similar on top of valgrind.
[…later in the evening and 500 lines typed down…]

It’s quite useful already, it groups all the leaks by the topmost function which is a bit easier to follow than the output valgrind usually gives us.
You can find a tarball here if you want to play around with it.
Update: I uploaded a bzr branch to launchpad:
bzr branch http://code.launchpad.net/~jdahlin/andvare/main/
June 15, 2007
Blogroll, GNOME, General, olpc
15 Comments
Today, after more than 2 years and 120 comments I could finally close #172535, adding support for loading interfaces created by UI designers in Gtk+.
GtkBuilder replaces libglade, it uses a similar XML format but also supports the following:
- GtkTreeViews including columns and cell renderers
- Menus and toolbars created using GtkUIManager, including actions & actiongroups.
- TreeModels, it’s possible to define the data used by treemodels. It’s used by treeviews, iconviews, comboboxes, and entries.
- SizeGroups, align all these widgets without using tables!
I’d like to especially thank Matthias Clasen for reviewing the beast, it was over 6500 lines in the end! Henrique Romano helped me to implement parts of it and Tristan Van Berkom, Tim Janik, Kalle Vahlman, Christian Perch, Dan Winship, Owen Taylor, Behdad Esfahbod and Havoc Pennington also helped out with suggestions and improvements to the patch.There are a couple of things that needs to be done to simplify the transition from libglade to gtkbuilder though:
- Add support in UI designers. Gazpacho mostly supports it already, it’ll be easy to fix. glade-2 is out of the question and I expect glade-3 to at least partially support GtkBuilder before GNOME 2.20 is released
- Improve migration from libglade files. There’s a script in bugzilla which converts old libglade files to files which gtkbuilder can load. It needs to be improved and tested, especially menus and toolbars
- Some libglade features are not supported yet, such as loading only a part of a glade file and pixbuf properties. These will be fixed before the final Gtk+ 2.12 release
Now, time to party!
May 7, 2007
GNOME, PyGTK, Python
2 Comments
I’m very pleased to see that no less than 8 posts on Gnome are about PyGTK or applications using PyGTK. And does not count OLPC, which is also using it.
Very few of the posts are explicitly mentioning Python or PyGTK, it’s such a well accepted platform that there’s really no need to.
This the result of many years of hard work. I’d like to acknowledge the following people who have made it possible:
Gnome hackers, keep on being productive, use high level languages, spread the word and don’t forget to let us know what you’!
April 30, 2007
GNOME, PyGTK, Python
4 Comments
Today I spent most of the day to finish off an implementation of bug 338098, adding a property helper to the python gobject bindings.
The support for defining your own GObject properties in PyGObject/PyGTK has always been a nail in my eye:
- You need to create a dictionary filled with crazy options
- You need to implement get_property and set_property to store/retrieve the values for each property.
- There’s very little help if you do a mistake, a cryptic error message will be displayed which gives you insufficient clues to figure out what you’ve done wrong.
A long time ago I solved this in kiwi. But I never quite got around to submit these helpers to pygobject where they belong.
With the new property helper it gets much simpler. Let’s say you want to create a new object called Color which has the three integer properties called red, green and blue:
class Color(gobject.GObject):
red = gobject.property(type=int)
green = gobject.property(type=int)
blue = gobject.property(type=int)
That’s it!
Easy to read and understand.
If you want to set a property, just modify the properties as if they were a normal python attribute:
color = Color()
color.red = 10
color.green = 20
color.blue = 300
Same goes for access:
>>> color.green
20
Now, suppose you want a read-only property, then you can use the “new” python 2.4 decorator syntax:
@gobject.property
def fnorb(self):
return 'fnuffra'
Which will add a fnorb property which will always return the string ‘fnuffra’ and raise an exception if your try to modify it.
The patch has not yet landed in pygobject’s SVN repository, but it’ll probably go in shortly, assuming nobody have any objections.
Once this is done I intend to work on a similar solution for signals.
« Previous Entries