Search code examples
javalinuxx11jnaxlib

Getting All Windows in the X11 environment with JNA XLib


Basically my goal is to get all the windows (I'm talking every single one, not the ones attached to my program) and compile them into a list. I'm trying to make my application as cross-platform-friendly as possible, so I'm porting JNA for Windows and Linux. Working with JNA in Windows was really simple and easy. However, the lack of documentation and examples with JNA utilizing the XLib isn't making the coding process any easier.

This question, regarding to coding with XLib in C++, does provide some light on how to get the windows in the X11 environment using XLib. I'm basically needing an implementation of XQueryTree in Java. My lack of knowledge prevents me from easily being able to use this code as I'm coding in Java. I've never coded in C++ or ever tried to code using XLib. Any ideas?


Solution

  • XQueryTree is defined in platform.jar.

    int XQueryTree(Display display, Window window, WindowByReference root, WindowByReference parent, PointerByReference children, IntByReference childCount);
    

    Obtain the display with XOpenDisplay().

    Since you want all windows, you should use the root window as the parent (use XRootWindow() to look it up).

    After the call, children.getValue() will have a pointer to a block of window IDs; at root, these are of type native long, so use Pointer.getIntArray(0, size) or Pointer.getLongArray(0, size) based on Native.LONG_SIZE, where size is the value returned in childCount. You can then use that array of IDs to initialize Window objects which may be passed on to other X11 functions.

    You'll need to manually free the returned array memory using XFree when you're done with it.