How can I programatically show/hide my app window with global shortcut key?

I'm writing a Notational Velocity clone for Gnome/Ubuntu using Quickly (PyGI) and I want to allow users to set a global shortcut key that will toggle the visibility of the app window when the app is running (something like Tilda does for its terminal emulator). I.e., once the app is launched, a user could press F2 to hide the window, and then press F2 again to make it visible and bring it to the front. I don't want to use an external hotkey app or anything that requires out-of-app settings. How would I go about this?

There's a similar question here: How can I listen on global keypress event? but the main answer there is a cludgy non-programmatic solution. One commenter mentions "grabbing the keyboard with an X api call" but I'm not sure where to start with that.


Solution 1:

The Keybinder library does exactly this. If you check pull requests there are requests in for examples using pygi, one of which is me for py3k.

Solution 2:

I realize this is an external setting, not in app, but I thought I'd write how to do this since I couldn't find documentation online.

I needed to read some compiz settings recently for my program, so figuring out how to change them was fairly straightforward. You can programatically set compiz settings in python using python-compizconfig. I've played with it a little bit and you can set values like so:

import compizconfig
context=compizconfig.Context()
commandplugin=context.Plugins['commands']
c0=commandplugin.Screen['command0']
c0.Value='xeyes'
key0=commandplugin.Screen['run_command0_key']
key0.Value='<Control><Primary>g'
context.Write()   #Note that sometimes you have to pass False to get it to update settings

The above sets the commands plugin of compiz to run xeyes using control-g keycombination. You'd probably have to do a check to make sure that the plugin was running (mine was off in ccsm by default). Note that to get many of the settings you can use the keys() function to list them (i.e.) context.Plugins.keys()

Here's a link to code that helped me figure out how this works, since I can't find any documentation: http://bazaar.launchpad.net/~ubuntu-branches/ubuntu/precise/compizconfig-python/precise/view/head:/src/compizconfig.pyx