8

I have a script which resets some things, and at the end of it I need it to set the cursor to certain coordinates, either to a custom set or to the centre of the screen (where it is reset to by default when restarting gnome-shell for instance).

How can this be achieved? The solution would have to work for all display sizes and be able to automatically get the data and do all the maths etc involved.

I am running Ubuntu GNOME 16.04 with GNOME 3.20.

3
  • I'd look into xdotool: semicomplete.com/projects/xdotool Jun 29, 2016 at 21:01
  • Do I understand that it symply needs to set the cursor in the middle op the screen? If so, which one if multiple? Jun 29, 2016 at 21:02
  • @JacobVlijm: That as well as being able to be given custom coordinates for where to reset it two. Perhaps it should be given the custom coordinates as arguments, but if there are no arguments given then it should assume the centre.
    – user364819
    Jun 29, 2016 at 21:16

1 Answer 1

15

Moving the mouse to a defined (absolute) position

..is simply done by the command (e.g.):

xdotool mousemove 200 200

To move the mouse to the centre of the screen however is a relative command, for which we need to read the screen's information and do some calculations. This is done in the two small scripts below.

Straightforward version (move cursor to the center of the left screen)

To move the mouse to the center of the (leftmost) screen, use the script below:

#!/usr/bin/env python3
import subprocess

xr = [s for s in subprocess.check_output("xrandr").decode("utf-8").split() if "+0+" in s]
scr = [int(n)/2 for n in xr[0].split("+")[0].split("x")]
subprocess.Popen(["xdotool", "mousemove", str(scr[0]), str(scr[1])])
  • install xdotool

    sudo apt-get install xdotool
    
  • Copy the script into an empty file, save it as center_screen.py

  • Run it:

    python3 /path/to/center_screen.py
    

Extended version (optional arguments x, y)

If arbitrary coordinates are optional, use:

#!/usr/bin/env python3
import subprocess
import sys

if sys.argv[1:]:
    scr = [sys.argv[1], sys.argv[2]]
else:
    xr = [s for s in subprocess.check_output("xrandr").decode("utf-8").split() if "+0+" in s]
    scr = [str(int(n)/2) for n in xr[0].split("+")[0].split("x")]

subprocess.Popen(["xdotool", "mousemove", scr[0], scr[1]])

This version will move the cursor to the center of the screen, when run without arguments, or to an arbitrary position, when run with arguments, e.g.:

python3 /path/to/center_screen.py 200 200

Explanation

In the output of the command: xrandr, all we need to find is the string like:

1680x1050+0+0

...which contains the data on the leftmost screen (+0+). both figures in 1680x1050 are then to be divided by two, to be used in:

xdotool mousemove <x> <y>

The line:

if sys.argv[1:]:

is then to decide wether the given arguments should be used or the calculated ones.

You must log in to answer this question.