tags:

views:

42

answers:

2

I'd like to be able to track which application is currently focused on my X11 display from Python. The intent is to tie it into a timetracking tool so that I can keep track of how much time I spend being unproductive.

I already found this code at http://thpinfo.com/2007/09/x11-idle-time-and-focused-window-in.html:

import Xlib.display
display = Xlib.display.Display()
focus = display.get_input_focus()
print "WM Class: %s" % ( focus.focus.get_wm_class(), )
print "WM Name: %s" % ( focus.focus.get_wm_name(), )

However, it doesn't seem to work for me. Apparently, no matter which application is focused, both get_wm_class() and get_wm_name() just return None.

Of course the solution needs to work with all these new fangled window managers like Compiz and such.

+1  A: 

Whoo! I figured it out myself:

import Xlib.display
display = Xlib.display.Display()
window = display.get_input_focus().focus
wmname = window.get_wm_name()
wmclass = window.get_wm_class()
if wmclass is None and wmname is None:
    window = window.query_tree().parent
    wmname = window.get_wm_name()
print "WM Name: %s" % ( wmname, )
Soren
A: 

A somewhat nicer solution, especially for a long-running app rather than a script, would use libwnck to track the _NET_ACTIVE_WINDOW hint. (See the EWMH specification for the definition of the hint.)

Havoc P