Skip to content

Instantly share code, notes, and snippets.

@domasmar
Created June 15, 2014 17:02
Show Gist options
  • Save domasmar/ac8b5255f937d0a9144b to your computer and use it in GitHub Desktop.
Save domasmar/ac8b5255f937d0a9144b to your computer and use it in GitHub Desktop.
Simple mouse keys script for linux written in python
'''
Keyboard keys codes:
KEY_KP1 - 1
KEY_KP2 - 2
KEY_KP3 - 3
KEY_KP4 - 4
KEY_KP5 - 5
KEY_KP6 - 6
KEY_KP7 - 7
KEY_KP8 - 8
KEY_KP9 - 9
KEY_KP0 - 0
KEY_KPSLASH - /
KEY_KPASTERISK - *
KEY_KPMINUS - -
KEY_KPPLUS - +
KEY_DOWN - down arrow
KEY_LEFT - left arrow
KEY_RIGHT - right arrow
KEY_UP - up arrow
and so on...
'''
from evdev import UInput, AbsInfo, InputDevice, \
categorize, events, ecodes as e
from Xlib import display
# Init keyboard
# change '/dev/input/event*' according to your keyboard
dev = InputDevice('/dev/input/event4')
print dev
# Mouse capabilities
# EV_REL mouse relative movements
# EV_KEY mouse buttons
capabilities = {
e.EV_REL : (e.REL_X, e.REL_Y),
e.EV_KEY : (e.BTN_LEFT, e.BTN_RIGHT),
}
# Mouse movement obj
ui = UInput(capabilities)
# change first coordinates
# to item position in store
script = {
'KEY_1': ('MOVE', (1435, 239)),
'KEY_2': 'RCLICK',
'KEY_3': ('RMOVE', (0, 70)),
'KEY_4': 'LCLICK',
}
def mousepos():
data = display.Display().screen().root.query_pointer()._data
return data["root_x"], data["root_y"]
def movemouse(x, y, relative):
if relative:
print "Move mouse relative to: " + str(x) + " " + str(y)
ui.write(e.EV_REL, e.REL_X, x)
ui.write(e.EV_REL, e.REL_Y, y)
else:
m_pos = mousepos()
print "Move mouse to: " + str(x) + " " + str(y)
ui.write(e.EV_REL, e.REL_X, x - m_pos[0])
ui.write(e.EV_REL, e.REL_Y, y - m_pos[1])
ui.syn()
def rightclick():
print "Right mouse click"
ui.write(e.EV_KEY, e.BTN_RIGHT, 1)
ui.write(e.EV_KEY, e.BTN_RIGHT, 0)
ui.syn()
def leftclick():
print "Left mouse click"
ui.write(e.EV_KEY, e.BTN_LEFT, 1)
ui.write(e.EV_KEY, e.BTN_LEFT, 0)
ui.syn()
def checkkey(key):
if key in script:
row = script[key]
if row == 'RCLICK':
rightclick()
elif row == 'LCLICK':
leftclick()
elif row[0] == 'RMOVE':
movemouse(row[1][0], row[1][1], True)
elif row[0] == 'MOVE':
movemouse(row[1][0], row[1][1], False)
else:
print "Button " + key + " is not defined"
for event in dev.read_loop():
if event.type == e.EV_KEY:
if event.value == 1:
checkkey(e.KEY[event.code])
# Prints mouse position every second
from Xlib import display
import time
def mousepos():
data = display.Display().screen().root.query_pointer()._data
return data["root_x"], data["root_y"]
while 1:
print mousepos()
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment