Search code examples
javalinuxxdotool

Check in Java if a certain application is in focus


I'd like to know whether a certain application is in focus in Linux. Say it is Google Chrome. To do so, I wrote a bash on-liner which does it correctly.

xdotool search --name --class 'google-chrome' | grep $(xdotool getactivewindow)

When this command is run in terminal, it will print the id of the terminal itself. To avoid that, run the following command and select Chrome in the three seconds time span.

sleep 3; xdotool search --name --class 'google-chrome' | grep $(xdotool getactivewindow)

The problem is that when I run the above-mentioned one-liner from Java, it seems to always print nothing. Here's my code:

String cmd = "xdotool search --name --class 'google-chrome' | grep $(xdotool getactivewindow)";
Process p = Runtime.getRuntime().exec(cmd);
String result = getCommandResult(p.getInputStream());

private static String getCommandResult(InputStream stream) throws IOException {

    StringBuilder sb = new StringBuilder();
    try (InputStreamReader isr = new InputStreamReader(stream);
         BufferedReader in = new BufferedReader(isr)) {

        String line;
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
    }
    return sb.toString().trim();
}

I'm open to different solutions to resolving this problem.


Solution

  • As barti_ddu said, this is not working because of the pipe in the command. You can workaround this by creating one sh process with your command passed as the argument:

        String cmd = "xdotool search --name --class 'google-chrome' | grep $(xdotool getactivewindow)";
        Process p = new ProcessBuilder("sh", "-c", cmd).start();
        String result = getCommandResult(p.getInputStream());