Skip to content

Instantly share code, notes, and snippets.

@razhangwei
Created September 3, 2024 02:02
Show Gist options
  • Save razhangwei/7978b2dc011abf7b31f026c6b94d636b to your computer and use it in GitHub Desktop.
Save razhangwei/7978b2dc011abf7b31f026c6b94d636b to your computer and use it in GitHub Desktop.
print feedback message to current text box via keyboard emulation #UI #keyboard #python
class FeedbackManager:
"""
Manage user feedback by printing a message and printing dots after it.
This class takes care of printing a message and then appending dots to it
until told to clear. It also handles clearing the feedback by deleting the
message and dots.
The printing of dots is done in a separate thread to avoid blocking.
"""
def __init__(self):
self.dot_thread = None
self.message = None
self.keyboard_controller = keyboard.Controller()
def provide_feedback(self, message):
"""
Print a message and then print dots after it until clear_feedback is called.
This function is non-blocking and runs in a separate thread.
Args:
message (str): The message to print before the dots.
"""
self.message = message
self.keyboard_controller = keyboard.Controller()
self.keyboard_controller.type(self.message)
dot_lock = threading.Lock()
self.dot_thread = threading.Thread(target=self._print_dots, args=(dot_lock,))
self.dot_thread.daemon = True
self.dot_thread.start()
def _print_dots(self, lock, every=2):
while getattr(self.dot_thread, "do_run", True):
self.keyboard_controller.type(".")
with lock:
self.message += "."
time.sleep(every)
def clear_feedback(self):
"""
Clear the feedback by deleting the message and dots.
This function stops the thread printing dots and deletes the message
from the console.
"""
if self.dot_thread:
self.dot_thread.do_run = False
self.dot_thread.join()
for _ in range(len(self.message)):
self.keyboard_controller.tap(keyboard.Key.backspace)
time.sleep(0.001)
self.dot_thread = None
self.message = None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment