Sunday, December 21, 2008

Global keybinding on X

Hello,
lately I've been looking for a way to create a desktop-wide keybinding for FreeSpeak.
I first looked into Tomboy and Deskbar source codes but the egg was too huge to be adopted, and it would have brought C dependency which isn't always nice for a Python project.
Then fargiolas pointed me to a blog post where I could find about gnome keybindings owned by gnome control center. Well that was only a mirage as it doesn't really grab the key but it's only a visual entry in the keyboard shortcuts preferences.
After a few days I've finally found a not-so-hackish solution in about one hundred lines of Python code.

Here is the snippet (download), only using Xlib and GTK+ Python bindings.

Sample usage:

def callback (keybinding):
print 'Callback!'
gtk.main_quit ()

gtk.gdk.threads_init ()
keybinding = GlobalKeyBinding ("/apps/appdir", "key_binding")
keybinding.connect ('activate', callback)
keybinding.grab ()
keybinding.start ()
gtk.main ()


The only problem is that it doesn't make use of GDK filters because PyGTK doesn't provide such function wrappers and there's no GDK-to-Xlib mapping available.
But yes, it works very good.

3 comments:

Tommy said...

I'm not sure I understand the sample usage. Think you could explain it in more detail?

Luca Bruno said...

You're right, maybe I've not been clear on its usage, especially on the gconf part. That class is supposed to get the keybinding from a gconf option in a GTK style (like <Control>T, parseable by gtk_accelerator_parse). Then, every time you change the gconf value at the key given by you (dir + key) it willl regrab to the new keybinding. In that example, the gconf key was suppposed to be /apps/appdir/key_binding. I think the rest should be clear enough, tell me to explain again if it's not.

pandith13 said...

Nice pick. it's very Useful Article.

SRI ANNAPOORNESHAWARI ASTROLOGY CENTER.Best Astrologer In Pune