Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect the currently focused application?

Tags:

python

x11

xlib

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.

like image 582
Soren Avatar asked Jun 28 '10 08:06

Soren


1 Answers

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, )
like image 170
Soren Avatar answered Nov 03 '22 12:11

Soren