Skip to content
Advertisement

Use terminal to display image without losing focus

I have a bash-script in which I want to display an image to the user. This is possible using ImageMagick’s display.

display image.png

But now the focus of the terminal window is lost, and is placed to the image. To continue my bash-script I have to ask the user to click on the terminal before continuing. This is unwanted behaviour.

Is there a way to display an image without losing the focus of my bash terminal? I want it to get it work on Ubuntu Linux (12.04).

Focus lost

Advertisement

Answer

Here is a not-too-awkward solution using wmctrl:

wmctrl -T master$$ -r :ACTIVE: ; display image.png & sleep 0.1 ; wmctrl -a master$$

To explain, I’ll break it down into steps:

  1. wmctrl -T master$$ -r :ACTIVE:

    To control a window, wmctrl needs to know its name, which by default is its window title. So, this step assigns the current window to a unique name master$$ where the shell will expand $$ to a process ID number. You may want to choose a different name.

  2. display image.png &

    This step displays your image as a “background” process. The image window will grab focus.

  3. sleep 0.1

    We need to wait enough time for display to open its window.

  4. wmctrl -a master$$

    Now, we grab focus back from display. If you chose a different name for your master window in step 1, use that name here in place of master$$.

If wmctrl is not installed on your system, you will need to install it. On debian-like systems, run:

apt-get install wmctrl

wmctrl supports Enlightenment, icewm, kwin, metacity, sawfish, and all other EWMH/NetWM compatible X-window managers.

Alternative approach that doesn’t require knowing the window title

First, get the ID of the current window:

my_id=$(wmctrl -l -p | awk -v pid=$PPID '$3 == pid {print $1}')

We can now use this ID in place of a window title. To launch display while maintaining focus in the current window:

display image.png & sleep 0.1 ; wmctrl -i -a "$my_id"
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement