gui comunication reworked, now using function_queue and event_buffer

This commit is contained in:
DESKTOP-JVKHS7I\Adam 2020-04-18 09:51:18 +05:30
parent e474fb0280
commit 9a6f46f02d
2 changed files with 76 additions and 107 deletions

View File

@ -1,18 +1,3 @@
"""Fishy
Usage:
fishy.py -h | --help
fishy.py -v | --version
fishy.py [--debug] [--ip=<ipv4>] [--collect-r] [--borderless]
Options:
-h, --help Show this screen.
-v, --version Show version.
--ip=<ipv4> Local Ip Address of the android phone.
--debug Start program in debug controls.
--borderless Use if the game is in fullscreen or borderless window
"""
import cv2
from docopt import docopt
from pynput.keyboard import Listener
@ -21,7 +6,7 @@ from fishy.systems import *
import logging
from fishy.systems.config import Config
from fishy.systems.gui import GUI, GUIStreamHandler
from fishy.systems.gui import GUI, GUIStreamHandler, GUICallback
"""
Start reading from `init.py`
@ -67,25 +52,22 @@ def hsv2rgb(img):
return cv2.cvtColor(img, cv2.COLOR_HSV2RGB)
def startFishing():
def startFishing(ip: str, action_key: str, borderless: bool):
"""
Starts the fishing
code explained in comments in detail
"""
Control.current = 1 if G.arguments["--debug"] else 0
use_net = G.arguments["--ip"] is not None
if use_net:
net.initialize(G.arguments["--ip"])
if ip != "":
net.initialize(ip)
# initializes fishing modes and their callbacks
FishingMode("hook", 0, HookEvent())
FishingMode("stick", 1, StickEvent())
FishingMode("look", 2, LookEvent())
FishingMode("idle", 3, IdleEvent(use_net))
FishingMode("idle", 3, IdleEvent(ip != ""))
logging.info(Control.getControlHelp())
logging.info("Starting the bot engine, look at the fishing hole to start fishing")
fishPixWindow = Window(color=cv2.COLOR_RGB2HSV)
@ -113,19 +95,16 @@ def startFishing():
def main():
events_buffer = []
rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.DEBUG)
gui = GUI(Config())
gui = GUI(Config(), lambda a, b: events_buffer.append((a, b)))
gui.start()
new_console = GUIStreamHandler(gui)
rootLogger.addHandler(new_console)
logging.info("yo")
G.arguments = docopt(__doc__)
if G.arguments["--version"]:
quit()
startFishing()
if __name__ == "__main__":

View File

@ -4,6 +4,8 @@ from enum import Enum
from logging import StreamHandler
from tkinter import *
from tkinter.ttk import *
from typing import Tuple, List, Callable
from ttkthemes import ThemedTk
from waiting import wait
import threading
@ -18,54 +20,34 @@ class GUIStreamHandler(StreamHandler):
def emit(self, record):
msg = self.format(record)
self.gui.writeToLog(msg)
self.gui.call(GUIFunction.LOG, (msg,))
class Callback(Enum):
START = 0,
SHORTCUT = 1,
CHECK_PIXELVAL = 2,
LOG_DUMP = 3
class GUIEvent(Enum):
START_BUTTON = 0 # args: ip: str, action_key: str, fullscreen: bool
CHECK_PIXELVAL = 1
class GUICallback:
def __init__(self, start_callback=None,
shortcut_callback=None,
check_pixelval_callback=None,
log_dump_callback=None
):
self.start_callback = start_callback
self.shortcut_callback = shortcut_callback
self.check_pixelval_callback = check_pixelval_callback
self.log_dump_callback = log_dump_callback
def call(self, callback_enum, args=None):
to_call = None
if callback_enum == Callback.START:
to_call = self.start_callback
elif callback_enum == Callback.SHORTCUT:
to_call = self.shortcut_callback
elif callback_enum == Callback.CHECK_PIXELVAL:
to_call = self.check_pixelval_callback
elif callback_enum == Callback.LOG_DUMP:
to_call = self.log_dump_callback
if to_call is None:
return
threading.Thread(target=to_call, args=(*args,)).start()
class GUIFunction(Enum):
LOG = 0 # args: str
STARTED = 1 # args: bool
class GUI:
def __init__(self,config: Config, gui_callback=None):
self.callbacks = GUICallback() if gui_callback is None else gui_callback
def __init__(self, config: Config, event_trigger: Callable[[GUIEvent, Tuple], None]):
self.config = config
self.start_restart = False
self.destroyed = True
self.root = None
self._log_strings = []
self._function_queue: List[Tuple[GUIFunction, Tuple]] = []
self._event_trigger = event_trigger
self._bot_running = False
# UI items
self.root = None
self.console = None
self.start_button = None
def create(self):
self.root = ThemedTk(theme="equilux", background=True)
@ -76,16 +58,16 @@ class GUI:
menubar = Menu(self.root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Create Shortcut", command=lambda: self.callbacks.call(Callback.SHORTCUT))
filemenu.add_command(label="Create Shortcut", command=lambda: logging.error("Not Implemented"))
filemenu.add_command(label="{} Dark Mode".format("Disable" if self.config.get("dark_mode", True) else "Enable"),
command=self._toggle_mode)
menubar.add_cascade(label="File", menu=filemenu)
debug_menu = Menu(menubar, tearoff=0)
debug_menu.add_command(label="Check PixelVal",
command=lambda: self.callbacks.call(Callback.CHECK_PIXELVAL))
command=lambda: logging.error("Not Implemented"))
debug_menu.add_command(label="Log Dump")
menubar.add_cascade(label="Debug", menu=debug_menu, command=lambda: self.callbacks.call(Callback.LOG_DUMP))
menubar.add_cascade(label="Debug", menu=debug_menu, command=lambda: logging.error("Not Implemented"))
self.root.config(menu=menubar)
# endregion
@ -124,10 +106,12 @@ class GUI:
controls_frame.pack()
Button(self.root, text="START", width=25,
command=lambda: self.callbacks.call(Callback.START,
(ip.get(), action_key_entry.get(), borderless.instate(['selected'])))
).pack(pady=(15, 15))
self.start_button = Button(self.root, text="START", width=25)
self.start_button["command"] = lambda: self._event_trigger(GUIEvent.START_BUTTON, (ip.get(),
action_key_entry.get(),
borderless.instate(
['selected'])))
self.start_button.pack(pady=(15, 15))
# endregion
self._apply_theme(self.config.get("dark_mode", True))
@ -135,10 +119,10 @@ class GUI:
self.root.minsize(self.root.winfo_width(), self.root.winfo_height())
self.root.protocol("WM_DELETE_WINDOW", self._set_destroyed)
self.destroyed = False
while True:
self.root.update()
self._update_console()
self._clear_function_queue()
if self.start_restart:
self.root.destroy()
self.root.quit()
@ -148,14 +132,20 @@ class GUI:
break
time.sleep(0.01)
def _clear_function_queue(self):
while len(self._function_queue) > 0:
func = self._function_queue.pop(0)
if func[0] == GUIFunction.LOG:
self._write_to_console(func[1][0])
elif func[1] == GUIFunction.STARTED:
self.start_button["text"] = "STOP" if func[1][0] else "START"
def _apply_theme(self, dark):
self.root["theme"] = "equilux" if dark else "breeze"
self.console["background"] = "#707070" if dark else "#ffffff"
self.console["fg"] = "#ffffff" if dark else "#000000"
def start(self):
threading.Thread(target=self.create, args=()).start()
def _toggle_mode(self):
self.config.set("dark_mode", not self.config.get("dark_mode", True))
self.start_restart = True
@ -163,36 +153,36 @@ class GUI:
def _set_destroyed(self):
self.destroyed = True
def writeToLog(self, msg):
self._log_strings.append(msg)
def _write_to_console(self, msg):
numlines = self.console.index('end - 1 line').split('.')[0]
self.console['state'] = 'normal'
if int(numlines) >= 50: # delete old lines
self.console.delete(1.0, 2.0)
if self.console.index('end-1c') != '1.0': # new line for each log
self.console.insert('end', '\n')
self.console.insert('end', msg)
self.console.see("end") # scroll to bottom
self.console['state'] = 'disabled'
def _update_console(self):
while len(self._log_strings) > 0:
msg = self._log_strings.pop(0)
numlines = self.console.index('end - 1 line').split('.')[0]
self.console['state'] = 'normal'
if int(numlines) >= 50: # delete old lines
self.console.delete(1.0, 2.0)
if self.console.index('end-1c') != '1.0': # new line for each log
self.console.insert('end', '\n')
self.console.insert('end', msg)
self.console.see("end") # scroll to bottom
self.console['state'] = 'disabled'
def start(self):
threading.Thread(target=self.create, args=()).start()
def call(self, gui_func: GUIFunction, args):
self._function_queue.append((gui_func, args))
def start(ip, actionkey, fullscreen):
logging.info(f"{ip}, {actionkey}, {fullscreen}")
def main():
config = Config()
gui = GUI(config=config, gui_callback=GUICallback(start_callback=start))
gui.start()
wait(lambda: not gui.destroyed)
while not gui.destroyed:
gui.writeToLog("yo")
time.sleep(1)
if __name__ == '__main__':
main()
# def start(ip, actionkey, fullscreen):
# logging.info(f"{ip}, {actionkey}, {fullscreen}")
#
#
# def main():
# config = Config()
# gui = GUI(config=config, gui_callback=GUICallback(start_callback=start))
# gui.start()
# wait(lambda: not gui.destroyed)
# while not gui.destroyed:
# gui.writeToLog("yo")
# time.sleep(1)
#
#
# if __name__ == '__main__':
# main()