2

I am writing a script recording how many time I spend on each applications every day. But I don't know how to get the process I am focusing on and its name. How can I achieve that? By the way, I see a lot of ways to get the focused window ID. Can I use it to get the process name?

MangoKing
  • 35
  • 6
  • so, it's not really a dup, but for reference: http://stackoverflow.com/questions/151407/how-to-get-an-x11-window-from-a-process-id and http://stackoverflow.com/questions/2041532/getting-pid-and-details-for-topmost-window – zmo Feb 28 '14 at 16:44

1 Answers1

2

What you want is to use python-xlib where you want to look up events.

As an example of usage, I used it to create kitt that handles multitouch gesture stuff on Xorg:

here's the code:

from Xlib import X, XK, protocol, display, Xcursorfont
from Xlib.ext import xtest
from Xlib.protocol import request

disp = display.Display()

root = disp.screen().root
pointer_info = request.QueryPointer(display = disp.display,
                                    window = root)
root_xpos, root_ypos = (pointer_info._data['root_x'], pointer_info._data['root_y'])
targetwindow = disp.get_input_focus().focus

now once you got the targetwindow, on which you can get many things like the id.

Now, to get back to your question "how to get the PID of a window", the answer is that it's not really possible, because of several reasons, though there are hacks around that.

The idea behind those hacks is that, though you can't tell what exact process (and thus its PID) is running the window, you can know its full name. You can't because Xorg is a client-server system where the application can be a process running on a distant machine that can have the same PID as a local process. But, the idea of the hack is to get the full name of the program (using the WM_CLASS property) and guess the PID from the process' list.

The most obvious ones, using xprop

ps -o pid,comm,args $(xprop -id $(xprop -root -f _NET_ACTIVE_WINDOW 0x " \$0\\n" _NET_ACTIVE_WINDOW | awk "{print \$2}") -f _NET_WM_PID 0c " \$0\\n" _NET_WM_PID | awk "{print \$2}")

or

xprop -id $(xprop -root _NET_ACTIVE_WINDOW | cut -d ' ' -f 5) _NET_WM_NAME WM_CLASS

or even using xdotool.

But, back to the Xlib we're using, I'm pretty sure it can be achieved using a code like that one, though I don't have a ready made code for that, but you'll have to check there for the WM_CLASS property. Which will contain the name of the application as shown in the process list... tada \o/

HTH

Community
  • 1
  • 1
zmo
  • 24,463
  • 4
  • 54
  • 90