Skip to content

Instantly share code, notes, and snippets.

@rebelliard
Last active December 7, 2017 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rebelliard/38574ec92f7d03e53b69b6b430dff1d4 to your computer and use it in GitHub Desktop.
Save rebelliard/38574ec92f7d03e53b69b6b430dff1d4 to your computer and use it in GitHub Desktop.
[Ubuntu] Cycle the mouse between displays
#!/usr/bin/python3
'''
[Ubuntu] Cycle the mouse between displays.
Suggestion: setup keyboard shortcuts such as:
- "super + tab" to "cycle_mouse_on_display.py"
- "super + shift + tab" to "cycle_mouse_on_display.py --reverse"
- Tested on Ubuntu 17.04.
- To make it work on Ubuntu 17.10, replace Wayland with Xorg:
Edit /etc/gdm3/custom.conf and uncomment `WaylandEnable=false`.
'''
import subprocess
import sys
# TODO: Determine dynamically.
DISPLAY_CENTER = [
[960, 838], # screen 1
[2460, 909], # screen 2
[3840, 1029] # screen 3
]
# TODO: Determine dynamically.
DISPLAY_X_BORDERS = [
[0, 1920], # screen 1: landscape
[1921, 2999], # screen 2: portrait
[3000, 4680] # screen 3: landscape
]
def get_mouse_location():
'''
Example location: "x:1004 y:858 screen:0 window:56623111"
'''
cmd = 'xdotool getmouselocation'
result = subprocess.run(cmd.split(), stdout=subprocess.PIPE).stdout.split()
return [int(coord.decode('utf-8').split(':')[1]) for coord in result]
def get_current_display():
'''
In order to get the current display, we use "getmouselocation",
which treats all displays as a single unit. Therefore, we use it
to calculate the display based on known borders.
'''
current_x = get_mouse_location()[0]
display_index = None
for index, borders in enumerate(DISPLAY_X_BORDERS):
border_left, border_right = borders
if (border_left <= current_x <= border_right):
display_index = index
break
return display_index
def cycle_mouse_on_display(reverse=False):
'''
Cycles mouse between displays.
'''
current_index = get_current_display()
display_len_0 = (len(DISPLAY_CENTER) - 1)
if reverse:
next_index = display_len_0 if current_index == 0 else current_index - 1
else:
next_index = 0 if current_index == display_len_0 else current_index + 1
next_display = DISPLAY_CENTER[next_index]
next_x, next_y = next_display
cmd = 'xdotool mousemove --sync {x} {y}'.format(x=next_x, y=next_y)
subprocess.run(cmd.split())
if __name__ == '__main__':
reverse = '--reverse' in sys.argv
cycle_mouse_on_display(reverse)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment