Change pag thread to use an Event instead of sleep

This commit is contained in:
Kai Vogelgesang 2022-10-28 13:39:35 +02:00
parent eddd2b9739
commit 61b874f636

View File

@ -1,32 +1,36 @@
import pyautogui
from threading import Thread
from threading import Thread, Event
from time import sleep
from .input import KEYMAP, Input, Button, Event
from .input import KEYMAP, Input, Button, Event as InputEvent
EMPTY_INPUT = {button: False for button in Button}
class InputHandler:
def __init__(self):
self.current: Input = {button: False for button in Button}
self.previous: Input = {button: False for button in Button}
print(f"sanity check: {self.previous=}, {self.current=}")
self.current: Input = EMPTY_INPUT
self.previous: Input = EMPTY_INPUT
self.dirty = Event()
def set(self, input: Input):
# MUST NOT BLOCK
# to be called from asyncio context
self.current = input
self.dirty.set()
def get(self) -> list[Event]:
def get(self) -> list[InputEvent]:
self.dirty.wait()
events = []
for button in Button:
match (self.previous[button], self.current[button]):
case (True, False):
events.append(Event(button, "up"))
events.append(InputEvent(button, "up"))
case (False, True):
events.append(Event(button, "down"))
events.append(InputEvent(button, "down"))
self.previous = self.current
self.dirty.clear()
return events
@ -40,6 +44,7 @@ class Runner(Thread):
def stop(self):
self.running = False
input.set(EMPTY_INPUT)
def run(self):
while self.running:
@ -50,4 +55,3 @@ class Runner(Thread):
pyautogui.keyDown(KEYMAP[event.button])
else:
pyautogui.keyUp(KEYMAP[event.button])
sleep(0.05)