Sunday, November 8, 2009

Using WNCK for capturing Gnome window events

For those new to WNCK (that includes me as well), it stands for Window Navigation Construction Kit and is used for capturing all window based events in GNOME. You could use python's pygtk to do some window management logic. For e.g. Find below some snippets about capturing when a window got switched. The below snippet will print the name of the application whenever any of the GNOME Windows switches (from Alt-Tab or clicking on window on the taskbar)
   import wnck
   import gtk
   scr = wnck.screen_get_default()
   while gtk.events_pending():    # This is required to capture all existing events
       gtk.main_iteration()
   
   def window_switch_handler(screen,window):
      # Get Current window, then the application and the name from it
      cur_win = screen.get_active_window().get_application().get_name()
      print "Currently showing %s" %cur_win

   scr.connect("active-window-changed", window_switch_handler)
   gtk.main()
After the last line "gtk.main()", the python interpreter will hang waiting for events to be serviced. Now if you switch any of the windows, you would see the name of the application displayed on the console. Im working on a similar setup for KDE (using PyQT). I will post a similar setup after I try it at work tomorrow (I dont have a KDE Setup at home). As for Windows, it turns out to be much more difficult. The PyAA seems to have stuff for WM_ACTIVATE and WM_DEACTIVATE but its compiled against Python 2.4 and noone has a later version available (unless its built). Im going to try 2 things. * Compile PyAA with Python 2.5 or Python 2.6 * Use AutoIT for automating windows tasks. Its non-python and could be an issue when I compile all three interfaces together, but atleast it would provide some way to do it. I dont know of any such automation for Mac OSX, but thats partly due to my lack of knowledge on that OS.

2 comments:

  1. Thanks, I was curious how to get events when the window manager noticed changes.

    ReplyDelete
  2. I modified it a bit to use python 3 and it works as expected when I switch windows. Thanks! You saved a lot of time for me.

    When I close a window, if there have been previously active windows, those windows will be activated. But this seems to be different from switching windows by hand; window_switch_handler gets called twice. For the first time, screen.get_active_window() returns None; for the second time, it works as expected.
    There is probably a short period when a window is closed and another window is not yet activated. Could you share some thoughts on how to deal with this situation?

    ReplyDelete