Company Calls Epilogue

Today I gave the final touches to a patch based upon the patch for search capabilities in the GtkFileChooser embeddable widget, adding the “Recently Used” shortcut:

File Chooser Support for Recently Used Files

there are still a few missing bits (the icon for the shortcut is one of them) but it’s already working remarkably well. I’ll work toward implementing what’s left in the next few days, while I also fix some of the warts of the search support.

Company Calls

Search support for the GtkFileChooser (#344785) landed in GTK+ trunk. It’s a patch written by Federico and updated by Matthias Clasen (I merely kept it in sync with trunk). The patch adds a private search engine abstraction object and three implementations, using libbeagle, libtracker and a simple file-tree-walking search. There’s no hard dependency on Beagle or Tracker: the libraries are opened using g_module_open() if they are found installed on your system, otherwise it’ll all fall back to the simple search backend (it’s the same solution used by Nautilus for its search support).

The file chooser now has a “Search” shortcut:

GtkFileChooser Search Support/1

If you double click it, you’ll get a search pane:

GtkFileChooser Search Support/2

Where you can search for “foo” and get the matching results:

GtkFileChooser Search Support/3

Next stop: fix all the missing bits (#435343) and add a “Recently Used” shortcut showing the list of recently used files (bug #435342).

By the way: libbeagle has an incredibly nice API, whereas libtracker doesn’t. Please, Tracker developers: instead patching projects or writing a GTK+ widgets library which only new projects can use, focus on writing a nice, GObject-based API for all the existing projects out there. Pretty please, with the sugar on top.

Of Angels And Angles

GtkApplication class: I’ve updated the application class page on the wiki. Now, it has an updated layout of the API (which is what I’m currently working on) and the design requirements it should fulfil. While writing it I had some sort of epiphany about the whole library consolidation effort and its perception among the platform developers. Project Ridley as it stands is a double-edged sword: on one hand we’d like to have more functionalities moved from external libraries to GLib and GTK+; on the other hand, the size of the platform libraries maintainer teams is not growing at the same rate. If we are to move widgets, features and whatnot to GTK+ we must be sure not only that someone is actively working on them after inclusion, but also that someone is willing to work on the rest of the codebase, in order to review the patches leading to the inclusion of new functionalities. So, waiting for Project Ridley to come to the rescue is not going to cut it anymore: if you are proposing to move some functionality from a library to GLib or GTK+ be prepared to work on the whole code and not only on your pet feature.

GtkUnique: since a “single instance application class” doesn’t really make any sense without an “application class” to make it inherit from, I’m punting the GtkUnique inclusion in GTK+ until the application class lands in first – and that makes it part of the post-2.12 masterplan; hence, I’m going to remove the gtk namespace from gtkunique and releasing it as a standalone library for the time being. I’ll commit the namespace switch before this weekend: it’ll switch from GtkUnique to Unique; everything else will stay the same. Remember to check it out from GNOME SVN server:

  svn co http://svn.gnome.org/svn/gtkunique/trunk

GConfig: as I mentioned in the last blog post, I’m working on the next iteration of GConf. Aside from ongoing design and API churning, I’ve also submitted a talk proposal for the next GUADEC about how to tackle the whole ‘GConf issue’. GConf is part of the core GNOME platform, and it has been so since 2000; it’s almost seven years old, and now it begins to show its age. Since 2001, Havoc has been asking the community to implement the same set of (five) features; no one has answered his call yet. Maybe the community is to be blamed for this; maybe we need to rethink part of the GConf design to allow someone other than ‘the usual suspects’ to fix GConf shortcomings and add new features. For instance: the backend API is a really nasty piece of code and it’s not easy to drop a new backend into an existing GConf installation; probably, that’s also why, after all these years, we still have only the XML and had to wait a long time for the evo-ldap backends. I’m going to put a page on the wiki with what kind of API I’m thinking about.

talks: aside from the GConf talk, I’ve also proposed a talk/tutorial about the Perl bindings for GTK+. I’ll also do two talks about Perl, GObject and GTK+ at this year’s Nordic Perl Workshop which will be held at the end of April in Copenhagen.

Live Wire

Back from FOSDEM 2007, after a little detour in Helsinki.

I’ve opened a bug for the places support in GtkFileChooser: #413076. Attached to it you’ll find a patch; it should be taken with a grain of salt: it’s still a work in progress, but implements the main features and shows how the new API should work. In short, if your application need to use some predefined, user visible folder and you want to provide a link inside the file chooser, you need to create your bookmark file, drop it somewhere and call:

gtk_file_chooser_add_shortcuts_from_file (file_chooser
                                          "/path/to/bookmarks.xbel",
                                          NULL);

We’d need an intltool able to recognise the title (and eventually description) markup elements of the bookmark files and merge them into the translation pool, so that you can have the places already localised (the machinery is already in place in the patch). I’ll keep working on it, and finish up the implementation of the automagic places that applications can install in a common place and have it appear in every file chooser, based on the group or application name used in the bookmark.

I’m also working again on the Application class (the wiki page is really out of date with the current iteration I have been workin on – I’ll update it as soon as possible); now that the session management code has landed in libegg I will add hooks into the application class to have it do The Right Thing®. Other than an application class, GTK+ really needs a desktop abstraction – a simple API to know whether we are connected to a network, or to control the screensaver, or to launch the default browser/mailer/editor/whatever. For that to work properly we should really have a working configuration system like GConf moved below GTK+. I did some prototype API for a configuration engine, mostly stealing^Wtaking inspiration from alexl work on GVFS (which already has a nice and clean API); will probably have something usable soon.

Like Eating Glass

Desktop-devel-list (d-d-l) is an interesting place. You follow discussions that usually tend to fork off, moving through tangential arguments; but, in the end, some stuff keeps turning up. Lately, for instance, every thread seems to end up on discussing about Tracker.

Let’s take the discussion about having a GNOME “media center version”; you could think that such a discussion will end up laying out some ideas about a media center. Wrong: we ended up discussing about special folders – an argument that has already been discussed to the death. Obviously, if you read d-d-l all day you can’t really expect having time to actually work on the features (or the crack) proposed on the list. So, for a change, I decided to do stuff after saying what could be done. I decided to take an idea that has been floating around for ages and implement it.

This is a simple FileChooserDialog, but the places list have been generated using a bookmark file (read using GBookmarkFile) in $HOME/.local/share/places/gtk-bookmarks.xbel instead of $HOME/.gtk-bookmarks:

FileChooser using bookmark file
It’s completely identical to the FileChooser in trunk, really, but the places on the left are parsed using this.

The code, obviously, merges the places saved using the old format.

This, instead, is a trivial Perl application that can read all the places; it can also edit them, add new places and remove old ones:

GTK+ shortcuts editor

The fun part about switching the file chooser to the bookmark files is that it’s public API, so everyone can read, change and write these locations. We can add new locations to an application like we add Glade files, and let the file chooser populate itself by loading a file; so, instead of using:

  gtk_file_chooser_add_shortcut_folder (file_chooser, some_location);

we could use:

  gtk_file_chooser_add_shortcuts (file_chooser, PKGDATADIR "/shortcuts.xbel");

But wait, the keen reader familiar with the issue will interrupt, the whole point of this mess is localising the name the user sees in the interface. Indeed, that’s why the bookmarks have a title and a description; through intltool we can extract those two and put them into the po file for the translators to work on – exactly like we do for the Glade files. Before displaying the bookmark will pass the string through gettext, which will return the localised alias using the application’s domain – or we could add domain argument to the gtk_file_chooser_add_shortcuts() function above.

The file chooser can also load shortcuts automatically, using the application name to filter out what’s interesting.

Is this the most correct solution for this problem? I don’t really know, even though using bookmarks and applications make more sense than using dot-desktop files and MIME types (come on? MIME types? Like I should bind a directory to specific types of content and not to the applications that are most likely to use them – and what are “MIME types” anyway?). At least, however, this is a start and there’s some code to comment on.

The patches are roughly done, but the real treat would be to split the places section of the file chooser widget into its own widget and let other applications, like nautilus, use it directly without having to cut and past tons of code out of GTK+.

Little Earthquakes

After two weeks without working on it, this evening I finally returned to GtkUnique and finished the bacon-like backend. Now, beside using D-Bus and Xlibs, you can use Un*x sockets as an IPC method to send a command to a running instance of an application which is using GtkUnique.

Next items in the TODO are:

  • Add more documentation on the protocol used in the three backends;
  • Fix the Perl bindings;
  • Finish and publish the Python bindings;

In the meantime, you can grab GtkUnique 0.5.0 here or pull it from the bazaar repository.

Boogie Woogie Bugle Boy

Lately there has been some activity in projects moving from EggRecent to GtkRecent. Obviously, this led to questions and bugs opened about the API.

One of the questions is: if I had a EggRecentModel singleton what should I use now?. Since EggRecent needed a EggRecentModel around for the entire lifetime of the recently used files list, you had to keep at least a singleton around; you also had to pass it to the objects (not widgets) displaying the list, because each istance of the objects would modify the list itself. GtkRecentManager does not need that, since the widgets usually use their own internal instance of the manager and they don’t change the list in any way. So you can create a new GtkRecentManager and keep it around as a singleton (remember to call g_object_unref() on it when finished, otherwise you’ll leak it):

GtkRecentManager *manager_singleton = gtk_recent_manager_new ();

and then pass it to the widgets:

GtkWidget *dialog =
  gtk_recent_chooser_dialog_new_with_manager ("Recent Documents"
                                              parent,
                                              manager_singleton,
                                              GTK_STOCK_CLOSE,  GTK_RESPONSE_CLOSE,
                                              GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                              NULL);

Nevertheless, you should really use gtk_recent_manager_get_default() which will do the right thing, and pass you a per-process instance and you won’t have to care about its memory management (no g_object_unref() when quitting). Also, using gtk_recent_manager_get_default() means that you don’t have to use the _with_manager variant of the widgets constructor, as they will use the per-process GtkRecentManager by default. Using your own GtkRecentManager makes sense only if you want to use the “filename” constructor-only property to specify your own storage file (and you should do that only if you know what you are doing):

GtkRecentManager *manager = gtk_recent_manager_get_default ();

  ...

GtkWidget *dialog =
  gtk_recent_chooser_dialog_new ("Recent Documents"
                                 parent,
                                 GTK_STOCK_CLOSE,  GTK_RESPONSE_CLOSE,
                                 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                 NULL);

Another question is the dreaded I want an inline list of recent files in the File menu; I’ll redirect you to the bug report linked for the rationales about why I think the inline list sucks, and should be removed from the UIs of GNOME applications in favour of the sub-menu. Anyhow, for those Unbelievers still using this Windows-cloned relic of the past, here’s a simple function for adding an inline list to an existing GtkUIManager instance; it’s part of a example of integration between GtkRecent and the UI manager I sent to the gtk-devel mailing list before GUADEC.

static void
add_inline_recent_items (guint         merge_id,
                         GtkUIManager *ui_manager)
{
  GtkActionGroup *action_group;
  GtkRecentManager *manager;
  GList *items, *l;
  guint i;

  action_group = gtk_action_group_new ("recent-info");
  gtk_ui_manager_insert_action_group (ui_manager, action_group, 0);

  manager = gtk_recent_manager_get_default ();

  /* we don't care about sorting and filtering, but it can
   * be done using g_list_sort_with_data() and clamping the
   * resulting list to the desired length
   */
  gtk_recent_manager_set_limit (manager, 4);
  items = gtk_recent_manager_get_items (manager);

  /* no items: attach an insensitive place holder */
  if (!items)
    {
      GtkAction *action;

      action = g_object_new (GTK_TYPE_ACTION,
      			     "name", "recent-info-empty",
			     "label", "No recently used files",
			     "sensitive", FALSE,
			     NULL);
      gtk_action_group_add_action (action_group, action);
      g_object_unref (action);

      gtk_ui_manager_add_ui (ui_manager, merge_id,
  			     "/MenuBar/FileMenu/RecentFiles",
			     "recent-info-empty",
			     "recent-info-empty",
			     GTK_UI_MANAGER_MENUITEM,
			     FALSE);

      return;
    }

  for (i = 0, l = items;
       l != NULL;
       i += 1, l = l->next)
    {
      GtkRecentInfo *info = l->data;
      gchar *name = g_strdup_printf ("recent-info-%d-%lu",
      				     i,
				     (gulong) time (NULL));
      gchar *action_name = g_strdup (name);
      GtkAction *action;

      action = g_object_new (GTK_TYPE_ACTION,
      			     "name", action_name,
			     "label", gtk_recent_info_get_display_name (info),
			     "stock_id", NULL,
			     NULL);
      g_object_set_data_full (G_OBJECT (action), "gtk-recent-info",
                              gtk_recent_info_ref (info),
			      (GDestroyNotify) gtk_recent_info_unref);
      g_signal_connect (action, "activate",
                        G_CALLBACK (recent_activate_cb), NULL);
      gtk_action_group_add_action (action_group, action);
      g_object_unref (action);

      /* all you need is a UI definition with a "placeholder" element called
       * "RecentFiles" under a "menu" element called "FileMenu".
       */
      gtk_ui_manager_add_ui (ui_manager, merge_id,
  			     "/MenuBar/FileMenu/RecentFiles",
			     name,
			     action_name,
			     GTK_UI_MANAGER_MENUITEM,
			     FALSE);

      g_print ("* adding action `%s'\n", action_name);

      g_free (action_name);
      g_free (name);
    }

  /* unref the info objects so that they will be destroyed when
   * the actions to which they are bound are destroyed with the
   * UIManager instance
   */
  g_list_foreach (items, (GFunc) gtk_recent_info_unref, NULL);
  g_list_free (items);
}

This code should give you an idea on how to implement your own version. Making the menu reloading the inline list means removing the UI definitions using the merge_id integer and calling this function again inside a callback attached to the “changed” signal of a GtkRecentManager instance, and it is left as an exercise for the reader. ;-)

GtkRecent and GtkUIManager

I’m really sorry that the UIManager integration did not happen in time for 2.10; it means that some applications will have to implement it by themselves until GTK+ 2.12 is out with a common implementation. In the meantime, continue asking me or opening bugs in Bugzilla.

Update@2006-08-02T09:51+0100: the complete code now has the “reload-when-list-change” feature. Remember: you may cut and paste this code for a basic support of recent files inside an inline menu; there are at least another couple of ways to implement the same level of support, and mostly it depends on how you handle your own documents. I’d like for GTK+ or libgnome or GLib to have a “document” class abstracting most of this and other stuff, like Cocoa on OSX has the NSDocument class.

Update@2006-08-02T16:05+0100: another update – I’ve fixed a couple of leaks (a GtkAction is a GObject and not a GtkObject) and added the sorting function for the inlined list.

Ride on a White Horse

Filed under the category: “useful programming tips for problems that bit my ass”

The wise men from old said: Thou shalt not check if a directory or file existeth before creating it.

Well, or something like that.

I often see code that looks like this:

if (!g_file_test (some_directory, G_FILE_TEST_EXISTS))
  {
    if (g_mkdir (some_directory, 0700) != 0)
      {
        g_warning ("Unable to create `%s'", some_directory);
        return;
      }
  }
else
  do_something_with_some_directory (some_directory);

or, worse, code that looks like this:

if (!g_file_test (some_file, G_FILE_TEST_EXISTS))
  {
    symlink (some_other_file, some_file);
  }

Despite a BFW on the g_file_test() API reference page.

These code snippes are wrong, because they contains an implicit race: what if the directory/file you are checking suddenly disappears (or is created)? Also, blindly invoking functions like g_mkdir() or symlink without checking the returned value (“hey, I just checked so how can it fail?”) is looking for troubles; finally: when a system call fails, you should always report the error message the OS sets: too many things can go wrong, and if you can get a meaningful message then you’ll be able to debug faster.

The solution for these problems is: shoot first, then ask the questions. Or, in other words, execute the function inside the if block and act according to the results. For this to happen, you’ll often need to rely on errno.h and g_strerror():

#include <errno.h>

...

if (g_mkdir (some_directory, 0700) == -1)
  {
    if (errno != EEXIST)
      {
        g_warning ("Unable to create `%s': %s",
                   some_directory,
                   g_strerror (errno));
        return;
      }
  }

do_something_with_some_directory (some_directory);

and:

#include <errno.h>

...

if (symlink (some_other_file, some_file) == -1)
  {
    if (errno != EEXIST)
      {
        g_warning ("Unable to create a link from`%s' to `%s': %s",
                   some_other_file,
                   some_file,
                   g_strerror (errno));
        return;
      }
  }

At the end of the if block we are guaranteed that the file or the directory does indeed exist either because we successfully created it or because the system call failed and errno was set to EEXIST; inside the if, instead, we can deal with failures, using various error trapping branches based on the value of errno (just remember to store it if you’re going to use it multiple times).

Tides that I tried to swim against

gtk-recent: For those who missed the mail on gtk-devel-list, language-bindings and desktop-devel:

Unfortunately, when importing the GtkRecent API in GTK+ I made a mistake and these two functions have been erroneously left inside the GtkRecentChooser interface API:


  gtk_recent_chooser_set_show_numbers()
  gtk_recent_chooser_get_show_numbers()

These two functions try to set the “show-numbers” property, which is installed only by GtkRecentChooserMenu and it’s not one of the properties defined by the GtkRecentChooser interface. Using these functions on a GtkRecentChooserMenu (or any other custom GtkRecentChooser implementation which defines a boolean “show-numbers” property) will yield the expected results, while using them on a GtkRecentChooser implementation that does not support the “show-numbers” property will result in a warning.

Since we are in a stable release we can’t mark those functions as deprecated, and we cannot remove them without breaking the API. You are advised not to use these functions: use the GtkRecentChooserMenu functions instead:


  gtk_recent_chooser_menu_set_show_numbers()
  gtk_recent_chooser_menu_get_show_numbers()

Language binding authors should not bind those functions, but bind the GtkRecentChooserMenu functions instead.

These functions will be marked as deprecated as soon as GTK+ will branch off for the 2.11/2.12 cycle, so you’ll have to bear with this inconsistency for a short period of time.

language-bindings/1: By the way, gtk2-perl now supports the GtkRecent code in HEAD, thanks to the hard work of Torsten kaffee Schoenfeld who fixed most of my first iteration binding code and wrote the tests for it.

language-bindings/2: I also finished the Perl bindings for Clutter, as well as the Python ones. As I changed Clutter to behave like GTK, with the ClutterActor objects being created with a “floating” reference count, you’ll have to update Clutter to HEAD if you want to test the bindings. Beware that Clutter’s API is still a bit fuzzy at the moment. Of course, if you find bugs in the library or in the bindings, be sure to report them.

Now Listening: Last-exit, Neighbour radio

You got me all wrong

This is actually a mail I sent on gtk-devel-list. Obligatory disclaimer: this is not a proposal for getting gnome-vfs inside GLib, or for making GTK depend on gnome-vfs or for replacing gnome-vfs entirely; please, read on before commenting.

A while ago, on IRC, Christian Persch made the request that the monitoring of the storage file used by the GtkRecentManager could be overridden by libgnome, so that every application using the GnomeProgram API would automagically have notifications of file changes using gnome-vfs, instead of the default implementation which stat()s the file once in a while.

This spawned a more interesting discussion about how to implement a simple file monitoring API inside GLib; my approach and Christian’s were equivalent, and resolved in a new object with a vtable to be overridden per-process. Matthias, instead, suggested using a GSource, and having the file monitor to play nice with the main loop. Thus GFileMonitor was born.

Continue reading “You got me all wrong”