Преглед на файлове

Updated 'launch' scripts, plus refactored some

Tyrell now stops exposing imports (Making it more library not just it's
own thing)

Both the Windows batch file, and Linux bash script, have been cleaned up
to ensure they use the python virtual environment (Assuming there is
one, called 'env')
apollo преди 6 дни
родител
ревизия
9f9cb96072
променени са 3 файла, в които са добавени 111 реда и са изтрити 101 реда
  1. 1 2
      run.bat
  2. 1 4
      run.sh
  3. 109 95
      tyrell.py

+ 1 - 2
run.bat

@@ -1,2 +1 @@
-:: env\Scripts\activate.bat
-@env\Scripts\python tyrell.py %*
+@env\Scripts\python3 tyrell.py %*

+ 1 - 4
run.sh

@@ -2,8 +2,5 @@
 
 # This is used under Linux because Python's 'keyboard' module requires root
 # (Root is needed for 'keyboard' module to access dev)
-#
-# sudo ./run.sh
 
-. env/bin/activate
-python3 tyrell.py "$@"
+sudo env/bin/python3 tyrell.py "$@"

+ 109 - 95
tyrell.py

@@ -1,55 +1,55 @@
 
-from sys import exit, argv
+from sys import argv as _argv
 
-from os import name as OS_NAME
-from os import listdir
-from os.path import exists, join, isdir
+from os import name as _OS_NAME
+from os import listdir as _listdir
+from os.path import exists as _exists, join as _join, isdir as _isdir
 
-from time import sleep
+from time import sleep as _sleep
 
-from typing import Dict, Tuple
+from typing import Dict as _Dict, Tuple as _Tuple
 
 try:
-    from click import echo, style
+    from click import echo as _echo, style as _style
 except ImportError:
     print("ERROR Please activate a virtual environment and install requirements.txt")
     exit()
 
-from pyautogui import mouseDown as mouse_down, mouseUp as mouse_up
-from keyboard import press as key_down, release as key_up, KeyboardEvent, add_hotkey, hook as key_hook, write as key_write
+from pyautogui import mouseDown as _mouse_down, mouseUp as _mouse_up
+from keyboard import press as _key_down, release as _key_up, KeyboardEvent as _KeyboardEvent, add_hotkey as _add_hotkey, hook as _key_hook, write as _key_write
 # Not entirely sure why this doesn't work
 #from mouse import press as mouse_down, release as mouse_up, click as mouse_press, move as mouse_move
 
-from toml import load as toml_load
+from toml import load as _toml_load
 
-from asyncio import run, sleep as asleep
-from asyncio.tasks import gather as task_group
+from asyncio import run as _run, sleep as _asleep
+from asyncio.tasks import gather as _task_group
 
-def print_err(msg):
-    echo(style("ERROR", fg="bright_red") + " " + msg)
+def print_err(msg: str):
+    _echo(_style("ERROR", fg="bright_red") + " " + msg)
 
-def print_warn(msg):
-    echo(style("WARN ", fg="bright_yellow") + " " + msg)
+def print_warn(msg: str):
+    _echo(_style("WARN ", fg="bright_yellow") + " " + msg)
 
-def print_ok(msg):
-    echo(style(" OK  ", fg="bright_green") + " " + msg)
+def print_ok(msg: str):
+    _echo(_style(" OK  ", fg="bright_green") + " " + msg)
 
-def print_info(msg):
+def print_info(msg: str):
     print("      " + msg)
 
-def keyboard_output(msg: str, delay: int=50, hold: int=20):
-    key_write(msg, delay=hold)
-    sleep(delay/1000)
+def _keyboard_output(msg: str, delay: int=50, hold: int=20):
+    _key_write(msg, delay=hold)
+    _sleep(delay/1000)
 
-def mouse_output(button: str, delay: int=50, hold: int=20):
-    mouse_down(button=button)
-    sleep(hold / 1000)
-    mouse_up(button=button)
-    sleep(hold / 1000)
-    sleep(delay / 1000)
+def _mouse_output(button: str, delay: int=50, hold: int=20):
+    _mouse_down(button=button)
+    _sleep(hold / 1000)
+    _mouse_up(button=button)
+    _sleep(hold / 1000)
+    _sleep(delay / 1000)
 
 platform: str = ""
-os_name = OS_NAME.lower()
+os_name = _OS_NAME.lower()
 if "linux" in os_name or "posix" in os_name:
     platform = "LINUX"
 elif "windows" in os_name or "nt" in os_name:
@@ -58,7 +58,7 @@ elif "darwin" in os_name:
     platform = "MACOS"
 else:
     print_err("Platform 'Linux', 'Windows' or 'MacOS' expected")
-    print_info(f"Platform: {OS_NAME}")
+    print_info(f"Platform: {_OS_NAME}")
     exit()
 
 class ActionKind(int):
@@ -94,21 +94,35 @@ class ActionKind(int):
 
     They Mirror a key's state, if it's down: pressing or clicking down, if it's up: releasing up
     """
-    def __init__(self, kind: str):
+    def __init__(self, kind: str | int):
         # Unlike most __init__ methods, this converts a string into a ActionKind (returning the ActionKind)
-        k = kind.lower().strip()
-        if k == "click":
-            return ActionKind.CLICK
-        elif k == "click down":
-            return ActionKind.CLICK_DOWN
-        elif k == "key":
-            return ActionKind.KEY
-        elif k == "key down":
-            return ActionKind.KEY_DOWN
-        elif k == "mirror":
-            return ActionKind.MIRROR
-        else:
-            return ActionKind.NONE
+        if type(kind) is str:
+            k = kind.lower().strip()
+            if k == "click":
+                return ActionKind.CLICK
+            elif k == "click down":
+                return ActionKind.CLICK_DOWN
+            elif k == "key":
+                return ActionKind.KEY
+            elif k == "key down":
+                return ActionKind.KEY_DOWN
+            elif k == "mirror":
+                return ActionKind.MIRROR
+            else:
+                return ActionKind.NONE
+        elif type(kind) is int:
+            if kind == 1:
+                return ActionKind.CLICK
+            elif kind == 2:
+                return ActionKind.CLICK_DOWN
+            elif kind == 3:
+                return ActionKind.KEY
+            elif kind == 4:
+                return ActionKind.KEY_DOWN
+            elif kind == 5:
+                return ActionKind.MIRROR
+            else:
+                return ActionKind.NONE
     
     def __str__(self) -> str:
         # Converts the ActionKind into a string, mostly for debugging
@@ -154,11 +168,11 @@ class Action:
 
     See tyrell.ActionKind
     """
-    extra: Dict
+    extra: _Dict
     enabled: bool
     delay: int
     max_delay: int
-    def __init__(self, name: str, kind: str, extra: Dict, on: bool=False, delay: int=0):
+    def __init__(self, name: str, kind: str, extra: _Dict, on: bool=False, delay: int=0):
         self.name = name
         self.kind = ActionKind(kind)
         self.enabled = on
@@ -202,7 +216,7 @@ class Action:
             return True
         return False
     
-    def do(self, key: Tuple[str, int], delay: int=50, hold: int=20):
+    def do(self, key: _Tuple[str, int], delay: int=50, hold: int=20):
         if not self.enabled:
             return
         d = delay
@@ -212,24 +226,24 @@ class Action:
         if "hold" in self.extra:
             h = self.extra["hold"]
         if self.kind == ActionKind.CLICK:
-            mouse_output(self.extra["button"], d, h)
+            _mouse_output(self.extra["button"], d, h)
         elif self.kind == ActionKind.CLICK_DOWN:
-            mouse_down(button=self.extra["button"])
+            _mouse_down(button=self.extra["button"])
         elif self.kind == ActionKind.KEY:
-            keyboard_output(self.extra["write"], d, h)
+            _keyboard_output(self.extra["write"], d, h)
         elif self.kind == ActionKind.KEY_DOWN:
-            key_down(self.extra["write"])
+            _key_down(self.extra["write"])
         elif self.kind == ActionKind.MIRROR:
             if key[1] == 0: # Up
                 if "write" in self.extra: # Key Mirror
-                    key_up(self.extra["write"])
+                    _key_up(self.extra["write"])
                 elif "button" in self.extra: # Mouse Mirror
-                    mouse_up(button=self.extra["button"])
+                    _mouse_up(button=self.extra["button"])
             elif key[1] == 1: # Down
                 if "write" in self.extra: # Key Mirror
-                    key_down(self.extra["write"])
+                    _key_down(self.extra["write"])
                 elif "button" in self.extra: # Mouse Mirror
-                    mouse_down(button=self.extra["button"])
+                    _mouse_down(button=self.extra["button"])
     
     def do_tick(self, delay: int=50, hold: int=20):
         if self.tick():
@@ -241,7 +255,7 @@ class Tyrell:
 class OldAction():
     name: str
     kind: str
-    extra: Dict
+    extra: _Dict
     toggled: bool
     delay: int
     max_delay: int
@@ -283,17 +297,17 @@ class OldAction():
             if "hold" in self.extra:
                 h = self.extra["hold"]
         if self.kind == "click":
-            mouse_output(self.extra["button"], d, h)
+            _mouse_output(self.extra["button"], d, h)
         elif self.kind == "click down":
-            mouse_down(self.extra["button"])
+            _mouse_down(self.extra["button"])
         elif self.kind == "key":
-            keyboard_output(self.extra["write"], d, h)
+            _keyboard_output(self.extra["write"], d, h)
         elif self.kind == "key down":
-            key_down(self.extra["write"])
+            _key_down(self.extra["write"])
 
 class OldTyrell():
-    keybinds: Dict[str, OldAction]
-    mirrors: Dict[str, str] # mirror key -> key in keybinds
+    keybinds: _Dict[str, OldAction]
+    mirrors: _Dict[str, str] # mirror key -> key in keybinds
     toggled: bool
     delay: int
     hold: int
@@ -309,15 +323,15 @@ class OldTyrell():
         self.name = profile_name
         if profile_name.endswith(".toml"):
             self.name = profile_name.removesuffix(".toml")
-        if not exists(self.name) or not isdir(self.name):
+        if not _exists(self.name) or not _isdir(self.name):
             print_err(f"Invalid profile '{self.name}'")
             print_info(f"This should be a directory")
             exit()
-        profile_config = join(self.name, self.name+".toml")
-        if exists(profile_config):
+        profile_config = _join(self.name, self.name+".toml")
+        if _exists(profile_config):
             with open(profile_config, "r") as f:
                 try:
-                    t = toml_load(f)
+                    t = _toml_load(f)
                 except Exception as err:
                     print_err(f"Invalid profile '{self.name}'")
                     print_info(f"Invalid '{self.name+'.toml'}' config")
@@ -345,16 +359,16 @@ class OldTyrell():
         self.keybinds = {}
         self.mirrors = {}
         self.toggled = False
-        if not exists(join(self.name, 'keys')):
+        if not _exists(_join(self.name, 'keys')):
             print_err(f"Invalid profile '{self.name}'")
             print_info("Missing 'keys' directory (for keybinds)")
             exit()
         else:
-            for ent in listdir(join(self.name, "keys")):
-                if ent.startswith(".") or isdir(ent) or not ent.endswith(".toml"):
+            for ent in _listdir(_join(self.name, "keys")):
+                if ent.startswith(".") or _isdir(ent) or not ent.endswith(".toml"):
                     continue
-                with open(join(self.name, "keys", ent), "r") as f:
-                    t = toml_load(f)
+                with open(_join(self.name, "keys", ent), "r") as f:
+                    t = _toml_load(f)
                     if t["keybind"] == "?" or t["keybind"] == "`":
                         continue
                     if "duration" in t:
@@ -440,7 +454,7 @@ class OldTyrell():
                 print_info(f"{key} -> {act.name}")
             else:
                 print_info(f"{key} -> {act.name} = {act.toggled} ({act.max_delay} ticks)")
-        print_ok("Please use " + style("CTRL+C", fg="bright_yellow") + " to stop")
+        print_ok("Please use " + _style("CTRL+C", fg="bright_yellow") + " to stop")
 
     def tick(self):
         for key in self.keybinds:
@@ -489,9 +503,9 @@ class OldTyrell():
     def callback(self, bind, state=None, mirror_host=None):
         if bind == "__toggle__":
             if self.toggle():
-                print_info(style("ON", fg="bright_green"))
+                print_info(_style("ON", fg="bright_green"))
             else:
-                print_info(style("OFF", fg="bright_red"))
+                print_info(_style("OFF", fg="bright_red"))
             return
         if state == "up" or state == "down":
             act = self.keybinds[mirror_host]
@@ -499,24 +513,24 @@ class OldTyrell():
                 if act.extra["write"] != None or len(act.extra["write"]) != 0:
                     if state == "up":
                         print(f"'{bind}' -> {act.name} UP")
-                        key_up(act.extra["write"])
+                        _key_up(act.extra["write"])
                     elif state == "down":
                         print(f"'{bind}' -> {act.name} DOWN")
-                        key_down(act.extra["write"])
+                        _key_down(act.extra["write"])
                 elif act.extra["button"] != None or len(act.extra["button"]) != 0:
                     if state == "up":
                         print(f"'{bind}' -> {act.name} UP")
-                        mouse_up(button=act.extra["button"])
+                        _mouse_up(button=act.extra["button"])
                     elif state == "down":
                         print(f"'{bind}' -> {act.name} DOWN")
-                        mouse_down(button=act.extra["button"])
+                        _mouse_down(button=act.extra["button"])
             return
         if not self.toggled:
             return
         if bind == "__help__":
             self.print_help()
             self.disable()
-            print_info(style("OFF", fg="bright_red"))
+            print_info(_style("OFF", fg="bright_red"))
             return
         act = self.keybinds[bind]
         if act.toggled:
@@ -524,37 +538,37 @@ class OldTyrell():
             act.do(self.delay, self.hold)
         elif act.max_delay != 0 or act.kind == "mirror":
             if act.toggle():
-                print(f"'{bind}' -> {act.name} " + style("ON", fg="bright_green"))
+                print(f"'{bind}' -> {act.name} " + _style("ON", fg="bright_green"))
             else:
-                print(f"'{bind}' -> {act.name} " + style("OFF", fg="bright_red"))
+                print(f"'{bind}' -> {act.name} " + _style("OFF", fg="bright_red"))
         self.disable()
-        print_info(style("OFF", fg="bright_red"))
+        print_info(_style("OFF", fg="bright_red"))
 
     async def background(self):
         while True:
             self.tick()
-            await asleep(self.profile["tick"] / 1000) # 50 ms (20 per second, same as Minecraft)
+            await _asleep(self.profile["tick"] / 1000) # 50 ms (20 per second, same as Minecraft)
 
     async def mainloop(self):
         #keyboard_hook(self.callback)
-        add_hotkey(41, self.callback, args=["__toggle__"])
-        add_hotkey("shift+?", self.callback, args=["__help__"])
+        _add_hotkey(41, self.callback, args=["__toggle__"])
+        _add_hotkey("shift+?", self.callback, args=["__help__"])
         for bind in self.keybinds:
             act = self.keybinds[bind]
             if act.kind == "key" or act.kind == "key down":
                 print(f"hotkey -=> {bind}")
-                add_hotkey(bind, self.callback, args=[bind])
+                _add_hotkey(bind, self.callback, args=[bind])
             elif act.kind == "mirror":
                 print(f"hotkey -=> {bind} (mirror {act.extra['mirror']})")
-                add_hotkey(bind, self.callback, args=[bind])
-                add_hotkey(bind, self.callback, args=[act.extra["mirror"], "down", bind])
-                add_hotkey(bind, self.callback, args=[act.extra["mirror"], "up", bind], trigger_on_release=True)
-        await task_group(
+                _add_hotkey(bind, self.callback, args=[bind])
+                _add_hotkey(bind, self.callback, args=[act.extra["mirror"], "down", bind])
+                _add_hotkey(bind, self.callback, args=[act.extra["mirror"], "up", bind], trigger_on_release=True)
+        await _task_group(
             self.background()
         )
 
 if __name__ == "__main__":
-    if len(argv) == 1:
+    if len(_argv) == 1:
         print_err("Missing profile filename")
         print_info("Example: 'tyrell.py Apollo' would look for 'Apollo.toml'")
         print()
@@ -562,19 +576,19 @@ if __name__ == "__main__":
         print_info("And defines in a \"global\" sense key delay and hold delay.")
         print()
         exit()
-    ty = OldTyrell(",".join(argv[1:]))
+    ty = OldTyrell(",".join(_argv[1:]))
     if len(ty.keybinds) == 0:
         print_err("Missing keybinds")
         print_info("(Might want some keybinds, place them in a 'keys' directory)")
-        print_info(f"(  Need an example? Look at '{join('_example', 'keys', 'example.toml')}')")
+        print_info(f"(  Need an example? Look at '{_join('_example', 'keys', 'example.toml')}')")
         exit()
     ty.enable(all_notickers=True)
     ty.disable()
     ty.print_help()
     if ty.name == "_example":
-        print_warn("This is the " + style("example", fg="bright_yellow") + ", please define you're own profile")
+        print_warn("This is the " + _style("example", fg="bright_yellow") + ", please define you're own profile")
         print_info("Please DO NOT EDIT this example profile")
     try:
-        run(ty.mainloop())
+        _run(ty.mainloop())
     except KeyboardInterrupt:
         exit()