capybara/InputController.py

80 lines
2.5 KiB
Python

from pynput.mouse import Controller as MouseController
from pynput.keyboard import Controller as KeyboardController
import constants as c
from MessageParser import MessageParser
class InputController():
def __init__(self):
self.mouse_controller = MouseController()
self.keyboard_controller = KeyboardController()
self.parser = MessageParser()
# Keyboard key press
self.parser.add_handler("k", {
"key": "str"
})
# Relative mouse movement
self.parser.add_handler("r", {
"x": "float",
"y": "float"
})
# Mouse relative scroll
self.parser.add_handler("s", {
"x": "float",
"y": "float"
})
# Mouse button down
self.parser.add_handler("d", {
"button": "int"
})
# Mouse button up
self.parser.add_handler("u", {
"button": "int"
})
# Mouse button click
self.parser.add_handler("c", {
"button": "int"
})
def button_code_to_object(self, button_code: int):
# HACK
obj = None
try:
obj = c.button_code_lookup[button_code]
except IndexError:
return c.button_code_lookup[0]
return obj
def deserialize_key(self, key: str):
obj = None
try:
obj = c.keyboard_lookup[key]
except KeyError:
if len(key) != 1:
return None
return key
return obj
def process_message(self, message: str) -> bool:
code, args = self.parser.parse(message)
if code == None:
print("error while parsing message:", args)
return False
elif code == "r":
self.mouse_controller.move(args["x"], args["y"])
elif code == "d":
self.mouse_controller.press(self.button_code_to_object(args["button"]))
elif code == "u":
self.mouse_controller.release(self.button_code_to_object(args["button"]))
elif code == "c":
self.mouse_controller.click(self.button_code_to_object(args["button"]))
elif code == "s":
self.mouse_controller.scroll(args["x"], args["y"])
elif code == "k":
key = self.deserialize_key(args["key"])
if key:
self.keyboard_controller.tap(key)
else:
print("got invalid code from parser (is this a bug with the MessageParser?)")
return False
return True