How to remotely send a keypress to an X11 application

keyboardx11

I've got an X11 program (Mathematica/Linux) running which contains unsaved data (calculated after I left; unfortunately I didn't have the foresight to programmatically save the data). Now I've gotten an email that the power will be switched off, unfortunately before I'm back. Therefore I want to save the data, which I could do by simply sending a CtrlS to the right window (I know how to find the window ID). Unfortunately there's no xdotool or autokey installed, and I don't have root rights to install one of them. So is there a way to do it?

Of course one way would be to write a C program to do it (since the functionality must be there, or those other programs couldn't work), but I've never written anything for X11, so I don't think I'll get it written in time …

I've got access to the machine with ssh, and can access the display (I can do a screenshot – which shows the lock screen – and I can obtain a window list using xwininfo). So all I need is a way to send a single CtrlS to a specific window without previously installing something.

Best Answer

I solved the problem.

The first part of the solution was the information by Gilles that xdotool is just a binary, so there's no need to install it. Just copying the executable to the remote machine (on which I have permission to run executables stored in my own directories) was sufficient.

Note that when below I mention any command, I assume that the DISPLAY variable is set to the display where Mathematica runs (which in my case was :0.0). This is what I did first after logging into the machine using ssh, before doing any of the commands below.

The next step was recognizing that when the screen is locked, the Gnome screensaver grabs the keyboard events, so any keypresses sent to the Mathematica window ended up at the screensaver instead. Fortunately the Gnome screensaver is easy to unlock from the command line. The command is

gnome-screensaver-command -d

which I found here.

After that, I identified the Mathematica window using the command

xwininfo -root -tree | grep Mathematica

which I found here. The correct Mathematica window was easy to identify because it contained in the title the notebook's file name ("notebook" is the Mathematica name for a specific type of Mathematica document, the one you usually use for calculations) and a star to indicate that it was unsaved. Each line starts with the corresponding window ID (a hex number like 0x13371d)

After having identified the window, I then set focus to it using

xdotool windowactivate 0x13371d

(where the hex number was of course the window ID obtained previously) and finally sent it the Control-S using

xdotool key ctrl+s

Then I used xwininfo again to check that the star indeed disappeared in the window title, indicating that the notebook had really been saved.

Related Question