├── src └── ion │ ├── util │ ├── stuff │ │ ├── focus_checker │ │ │ ├── __init__.py │ │ │ ├── darwin.py │ │ │ ├── darwin_GetWindowID.py │ │ │ ├── win32.py │ │ │ ├── base.py │ │ │ └── linux.py │ │ ├── common.py │ │ ├── pynput_patcher.py │ │ ├── keys.py │ │ └── keylogger.py │ └── ion.py │ ├── __init__.pyi │ ├── __init__.py │ └── README.md ├── setup.py ├── README.md └── LICENSE /src/ion/util/stuff/focus_checker/__init__.py: -------------------------------------------------------------------------------- 1 | from .base import NoopFocusChecker, prettywarn, GET_INPUT_EVERYWHERE 2 | import sys 3 | 4 | __all__ = ["FocusChecker"] 5 | 6 | 7 | if GET_INPUT_EVERYWHERE: 8 | class FocusChecker(NoopFocusChecker): ... 9 | 10 | elif sys.platform.startswith("win"): 11 | from .win32 import FocusChecker 12 | 13 | elif sys.platform.startswith("linux"): 14 | from .linux import FocusChecker 15 | 16 | elif sys.platform.startswith("darwin"): 17 | #from .darwin import FocusChecker 18 | prettywarn("MacOS support is not finished, some features will be not present", ImportWarning) 19 | class FocusChecker(NoopFocusChecker): ... 20 | 21 | else: 22 | # Platform not supported for focus, create an fake FocusChecker class 23 | # The 'focus on only window' will be disabled 24 | prettywarn(f"platform {sys.platform!r} not supported for focussed window inputs. " 25 | "Inputs will be gets on entire system", ImportWarning) 26 | class FocusChecker(NoopFocusChecker): ... 27 | -------------------------------------------------------------------------------- /src/ion/util/stuff/common.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | warnings.filters = [] # Reset filters because some default appear in, and HIS DON'T PRINT MY WARNINGS!! 3 | 4 | WARNINGS = False 5 | def set_warnings(enabled): 6 | global WARNINGS 7 | WARNINGS = enabled 8 | 9 | # prettywarn method of pysdl2 10 | def prettywarn(message, warntype=None): 11 | """Prints a suppressable warning without stack or line info.""" 12 | if not WARNINGS: return 13 | original = warnings.formatwarning 14 | warnings.formatwarning = lambda message, category, *_: f"{category.__name__}: {message}\n" 15 | warnings.warn(message, warntype) 16 | warnings.formatwarning = original 17 | 18 | DEBUG = False 19 | def set_debug(enabled): 20 | global DEBUG 21 | DEBUG = enabled 22 | 23 | def is_debug(): 24 | return DEBUG 25 | 26 | def print_debug(type, *msgs, **print_args): 27 | if DEBUG: 28 | if "end" in print_args and not print_args["end"].startswith('\n'): print_args["end"] += '\n' 29 | print(f"DEBUG: {type}: ", end='') 30 | print(*msgs, **print_args) -------------------------------------------------------------------------------- /src/ion/__init__.pyi: -------------------------------------------------------------------------------- 1 | KEY_LEFT: int = 0 2 | KEY_UP: int = 1 3 | KEY_DOWN: int = 2 4 | KEY_RIGHT: int = 3 5 | KEY_OK: int = 4 6 | KEY_BACK: int = 5 7 | KEY_HOME: int = 6 8 | KEY_ONOFF: int = 7 9 | KEY_SHIFT: int = 12 10 | KEY_ALPHA: int = 13 11 | KEY_XNT: int = 14 12 | KEY_VAR: int = 15 13 | KEY_TOOLBOX: int = 16 14 | KEY_BACKSPACE: int = 17 15 | KEY_EXP: int = 18 16 | KEY_LN: int = 19 17 | KEY_LOG: int = 20 18 | KEY_IMAGINARY: int = 21 19 | KEY_COMMA: int = 22 20 | KEY_POWER: int = 23 21 | KEY_SINE: int = 24 22 | KEY_COSINE: int = 25 23 | KEY_TANGENT: int = 26 24 | KEY_PI: int = 27 25 | KEY_SQRT: int = 28 26 | KEY_SQUARE: int = 29 27 | KEY_SEVEN: int = 30 28 | KEY_EIGHT: int = 31 29 | KEY_NINE: int = 32 30 | KEY_LEFTPARENTHESIS: int = 33 31 | KEY_RIGHTPARENTHESIS: int = 34 32 | KEY_FOUR: int = 36 33 | KEY_FIVE: int = 37 34 | KEY_SIX: int = 38 35 | KEY_MULTIPLICATION: int = 39 36 | KEY_DIVISION: int = 40 37 | KEY_ONE: int = 42 38 | KEY_TWO: int = 43 39 | KEY_THREE: int = 44 40 | KEY_PLUS: int = 45 41 | KEY_MINUS: int = 46 42 | KEY_ZERO: int = 48 43 | KEY_DOT: int = 49 44 | KEY_EE: int = 50 45 | KEY_ANS: int = 51 46 | KEY_EXE: int = 52 47 | 48 | def keydown(k: int, /) -> bool: ... 49 | def get_keys() -> set[str]: ... 50 | def battery() -> int: ... 51 | def battery_level() -> int: ... 52 | def battery_ischarging() -> int: ... 53 | def set_brightness(level: int, /) -> None: ... 54 | def get_brightness() -> int: ... 55 | 56 | class file: 57 | SEEK_SET: int = 0 58 | SEEK_CUR: int = 1 59 | SEEK_END: int = 2 60 | def __init__() -> None: ... 61 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | def clean_pycache(path="."): 4 | """Clean __pycache__ directories recursively. Call this before setup().""" 5 | import os 6 | for file in os.listdir(path): 7 | new_path = os.path.join(path, file) 8 | if os.path.isdir(new_path): 9 | if file == "__pycache__": 10 | # Remove a file or a directory recursively using terminal commands. 11 | # This way avoid some permissions errors. 12 | if os.name == "nt": os.system(("rd /s" if os.path.isdir(new_path) else "del /f") + " /q \"" + new_path.replace('/', '\\') + "\"") 13 | else: os.system("rm -rf \"" + new_path.replace('\\', '/') + "\"") 14 | else: clean_pycache(new_path) 15 | 16 | with open("src/ion/README.md", "rt", encoding="utf-8") as f: 17 | long_description = f.read() 18 | with open("README.md", "wt", encoding="utf-8") as f: f.write(long_description) 19 | 20 | clean_pycache(__file__[:__file__.rfind("\\")+1 or __file__.rfind("/")+1]) 21 | setup( 22 | name="ion-numworks", 23 | version="2.1", 24 | author="ZetaMap", 25 | description="The porting of 'Ion module, from Numworks, for PC.", 26 | license='MIT', 27 | long_description=long_description, 28 | long_description_content_type='text/markdown', 29 | url="https://github.com/ZetaMap/Ion-Numworks", 30 | project_urls={ 31 | "Bug Tracker": "https://github.com/ZetaMap/Ion-Numworks/issues", 32 | }, 33 | classifiers=[ 34 | 'Programming Language :: Python :: 3', 35 | 'Operating System :: Microsoft :: Windows', 36 | 'Operating System :: Unix', 37 | 'Operating System :: MacOS :: MacOS X', # not fully compatible 38 | ], 39 | package_dir={"": "src"}, 40 | packages=[ 41 | "ion", 42 | "ion.util", 43 | "ion.util.stuff", 44 | "ion.util.stuff.focus_checker" 45 | ], 46 | package_data={"": ["**"]}, 47 | install_requires=["pynput"], 48 | python_requires= '>=3.6', 49 | ) 50 | -------------------------------------------------------------------------------- /src/ion/util/stuff/focus_checker/darwin.py: -------------------------------------------------------------------------------- 1 | from .base import * 2 | from threading import Thread 3 | 4 | import subprocess 5 | 6 | try: 7 | from AppKit import NSWorkspace 8 | from Quartz import CGWindowListCopyWindowInfo, kCGWindowListOptionOnScreenOnly, kCGNullWindowID 9 | from .darwin_GetWindowID import get_window_id 10 | except ImportError as e: 11 | e.msg = ("pyobjc module and/or the Quartz extension are not installed. \n" 12 | "Please install them with command: pip install pyobjc-core pyobjc-framework-Quartz") 13 | raise 14 | 15 | 16 | class FocusChecker(BaseFocusChecker): 17 | #classnames is the window owner 18 | classnames = ("Python",) 19 | #CGWindowListCreateDescriptionFromArray 20 | 21 | def check_window(self, wid, pid=0, classname=None, not_classname=False, contains_title=None): 22 | # get window object 23 | win = ... 24 | 25 | if pid == 0 or win['kCGWindowOwnerPID'] == pid: 26 | if classname: 27 | return get_window_id(win, classname[0], not_classname, contains_title) != 0 28 | return True 29 | return False 30 | 31 | def search_window(self, pid=0, classname=None, not_classname=False, contains_title=None): 32 | # kCGWindowListExcludeDesktopElements 33 | for win in CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID): 34 | if self.check_window(win, pid, classname, not_classname, contains_title): 35 | return win['kCGWindowNumber'] 36 | return 0 37 | 38 | def register_window_callbacks(self): 39 | ... 40 | 41 | def get_ppid(self, pid): 42 | try: result = subprocess.check_output(f"ps -o ppid= {pid}".split(' ')).decode().strip() 43 | except subprocess.CalledProcessError: return -1 44 | 45 | # check the return value 46 | if not result: return -2 47 | return int(result) 48 | 49 | def get_focussed_window(self): 50 | front_app_pid = NSWorkspace.sharedWorkspace().frontmostApplication().processIdentifier() 51 | return self.search_window(front_app_pid) # 0 cannot happening 52 | -------------------------------------------------------------------------------- /src/ion/util/ion.py: -------------------------------------------------------------------------------- 1 | from os import environ 2 | from random import randint, random 3 | 4 | from .stuff.keylogger import * 5 | from .stuff.keys import ALL_KEYS 6 | from .stuff.common import * 7 | 8 | 9 | # Enable debug 10 | DEBUG = "ION_ENABLE_DEBUG" in environ 11 | set_debug(DEBUG) 12 | 13 | # Disable warnings 14 | WARNINGS = "ION_DISABLE_WARNINGS" not in environ 15 | set_warnings(WARNINGS) 16 | 17 | # '0': PC, '1': Numworks, '2': Omega, '3': Upsilon 18 | OS_MODE = environ.get('KANDINSKY_OS_MODE') or environ.get('ION_OS_MODE') 19 | OS_MODE = (int(OS_MODE) if 0 <= int(OS_MODE) < 4 else 1) if OS_MODE and OS_MODE.isdecimal() else 1 20 | 21 | # Check version of kandinsky to print an warning if is 'too old' 22 | try: 23 | import importlib.metadata 24 | kandinsky_version = importlib.metadata.metadata("kandinsky").get_all("version") 25 | if kandinsky_version is None: 26 | prettywarn("invalid kandinsky metadata, are you sure the right library is installed?", DeprecationWarning) 27 | elif tuple([int(i) for i in kandinsky_version[0].split('.') if i.isdecimal()]) < (2, 5): 28 | prettywarn("for more stability, is recommended to upgrade kandinsky", DeprecationWarning) 29 | del importlib 30 | except: pass 31 | 32 | 33 | __all__ = ["Ion"] 34 | 35 | class Ion: 36 | KeyLogger.start() 37 | 38 | @staticmethod 39 | def keydown(k): 40 | if type(k) != int: raise TypeError(f"can't convert {type(k).__name__} to int") 41 | try: return KeyLogger.is_pressed(k) 42 | except IndexError: return False 43 | 44 | @staticmethod 45 | def get_keys(): 46 | return set(k["name"] for k in ALL_KEYS if KeyLogger.is_pressed(k["code"])) 47 | 48 | # All the following functions give a fake result, to have a real look of the library 49 | @staticmethod 50 | def battery(): return 4.20+randint(900, 1500)/10**5+random()/10**5 51 | @staticmethod 52 | def battery_level(): return 3 53 | @staticmethod 54 | def battery_ischarging(): return True 55 | _brightness = 240 56 | @staticmethod 57 | def set_brightness(level): 58 | if type(level) != int: raise TypeError(f"can't convert {type(level).__name__} to int") 59 | Ion._brightness = 240 if level%256 > 240 else level%256 60 | @staticmethod 61 | def get_brightness(): return Ion._brightness 62 | 63 | # Wrapped caller 64 | @staticmethod 65 | def call(method, *args, **kwargs): 66 | try: 67 | if is_debug(): # To avoid making unnecessary work 68 | print_debug("Event", method.__name__, (*args, *[f"{k}={repr(v)}" for k, v in kwargs.items()]), sep='') 69 | KeyLogger.raise_if_error() # raise the last KeyLogger error to the main thread 70 | return method(*args, **kwargs), None 71 | except BaseException as e: 72 | return None, Exception.with_traceback( 73 | KeyboardInterrupt(type(e).__name__+": "+' '.join(e.args)) if isinstance(e, RuntimeError) else e, 74 | e.__traceback__.tb_next if DEBUG else None) 75 | -------------------------------------------------------------------------------- /src/ion/util/stuff/focus_checker/darwin_GetWindowID.py: -------------------------------------------------------------------------------- 1 | """ 2 | Source: https://github.com/smokris/GetWindowID 3 | Converted in Python by CodeConvert.ai 4 | And modified for my own use 5 | """ 6 | 7 | import sys 8 | if not sys.platform.startswith("darwin"): 9 | file_name = __file__[__file__.rfind("/")+1 or __file__.rfind("\\")+1:] 10 | raise ImportError(file_name + " can only be used on MacOS") 11 | del sys 12 | 13 | import Quartz 14 | 15 | 16 | def search_window_id(requested_app, requested_window="", ignore_requested_app=False): 17 | session = Quartz.CGSessionCopyCurrentDictionary() 18 | if session: session.release() 19 | 20 | for window in Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListExcludeDesktopElements, Quartz.kCGNullWindowID): 21 | wid = get_window_id(window, requested_app, requested_window, ignore_requested_app) 22 | if wid != 0: 23 | return wid 24 | return 0 25 | 26 | def get_window_id(window, requested_app, requested_window="", ignore_requested_app=False): 27 | """Return 0 if window is not the right, else his window id""" 28 | app = window.get("kCGWindowOwnerName", None) 29 | window_title = window.get("kCGWindowName", "") or window.get("kCGWindowTitle", "") 30 | bounds = window["kCGWindowBounds"] 31 | 32 | if (app != requested_app if ignore_requested_app else app == requested_app): 33 | aspect = bounds["Width"] / bounds["Height"] 34 | if aspect > 30: 35 | # If it's that wide and short, it's probably the system menu bar, so ignore it. 36 | return 0 37 | 38 | if requested_window: 39 | if not window_title: 40 | # If CGWindowListCopyWindowInfo didn't give us the window title, try to extract it from the Accessibility API. 41 | window_title = get_window_title_from_accessibility(window) 42 | 43 | if (window_title != requested_window or 44 | (window_title == "Focus Proxy" 45 | and bounds["Width"] == 1 and bounds["Height"] == 1)): 46 | return 0 47 | return window["kCGWindowNumber"] 48 | return 0 49 | 50 | def get_window_title_from_accessibility(window): 51 | ax_app = Quartz.AXUIElementCreateApplication(window["kCGWindowOwnerPID"]) 52 | windows = Quartz.AXUIElementCopyAttributeValue(ax_app, Quartz.kAXWindowsAttribute) 53 | 54 | if windows == Quartz.kAXErrorSuccess: 55 | for ax_window in windows: 56 | # The Accessibility API doesn't expose a unique identifier for the window, so guess based on its frame. 57 | position = Quartz.AXUIElementCopyAttributeValue(ax_window, Quartz.kAXPositionAttribute) 58 | size = Quartz.AXUIElementCopyAttributeValue(ax_window, Quartz.kAXSizeAttribute) 59 | bounds = window["kCGWindowBounds"] 60 | 61 | if position == Quartz.kAXErrorSuccess and size == Quartz.kAXErrorSuccess: 62 | ax_position = Quartz.AXValueGetValue(position, Quartz.kAXValueTypeCGPoint) 63 | ax_size = Quartz.AXValueGetValue(size, Quartz.kAXValueTypeCGSize) 64 | 65 | if (ax_position.x == bounds.origin.x and ax_position.y == bounds.origin.y and 66 | ax_size.width == bounds.size.width and ax_size.height == bounds.size.height): 67 | return Quartz.AXUIElementCopyAttributeValue(ax_window, Quartz.kAXTitleAttribute) 68 | 69 | return "" 70 | -------------------------------------------------------------------------------- /src/ion/util/stuff/pynput_patcher.py: -------------------------------------------------------------------------------- 1 | """ 2 | Patch Pynput to add support of Caps Lock modifier. 3 | """ 4 | 5 | import sys, os 6 | 7 | __all__ = [] 8 | 9 | pynput_backend = os.environ.get( 10 | 'PYNPUT_BACKEND_{}'.format(__name__.rsplit('.')[-1].upper()), 11 | os.environ.get('PYNPUT_BACKEND', None)) 12 | if not pynput_backend: pynput_backend = sys.platform 13 | 14 | 15 | if pynput_backend == "dummy": 16 | # No patch 17 | pass 18 | 19 | 20 | elif pynput_backend == "uinput": 21 | # Idk how to test this but I hope this work 22 | from pynput.keyboard._uinput import Listener, Key, KeyEvent 23 | 24 | Listener.last_capslock_state = KeyEvent.key_up 25 | Listener__handle_original = Listener._handle 26 | 27 | def Listener__handle(self, event): 28 | if event.code == Key.caps_lock.value.vk: 29 | if event.value == KeyEvent.key_down and Listener.last_capslock_state == KeyEvent.key_up: 30 | if Key.shift in self._modifiers: self._modifiers.remove(Key.shift) 31 | else: self._modifiers.add(Key.shift) 32 | Listener.last_capslock_state = event.value 33 | Listener__handle_original(self, event) 34 | 35 | Listener._handle = Listener__handle 36 | 37 | 38 | elif pynput_backend == "darwin": 39 | # TODO: make support 40 | ... 41 | 42 | 43 | elif pynput_backend == "win32": 44 | # It's really poorly coded but it does the job, so I'm keeping it for now 45 | from pynput._util.win32 import KeyTranslator, VK, ctypes 46 | from pynput.keyboard._win32 import Listener 47 | 48 | class Capslock: 49 | """Class to store temporary variables for caps lock patch""" 50 | last_code = Listener._WM_KEYUP 51 | 52 | keyboard = (ctypes.c_ubyte * 255)() 53 | KeyTranslator._GetKeyboardState(ctypes.byref(keyboard)) 54 | enabled = bool(keyboard[VK.CAPITAL]) 55 | del keyboard 56 | 57 | Listener__convert_original = Listener._convert 58 | KeyTranslator__modifier_state_original = KeyTranslator._modifier_state 59 | 60 | def Listener__convert(self, code, msg, lpdata): 61 | """Wrap the hook callback to handle caps lock key code""" 62 | converted = Listener__convert_original(self, code, msg, lpdata) 63 | if converted and converted[1] == VK.CAPITAL: 64 | if converted[0] in Listener._PRESS_MESSAGES and converted[0] != Capslock.last_code: 65 | Capslock.enabled = not Capslock.enabled 66 | Capslock.last_code = converted[0] 67 | return converted 68 | 69 | def KeyTranslator__modifier_state(self): 70 | """Wrap the method to add the check of caps lock""" 71 | shift, ctrl, alt = KeyTranslator__modifier_state_original(self) 72 | if Capslock.enabled: shift = not shift 73 | return shift, ctrl, alt 74 | 75 | Listener._convert = Listener__convert 76 | KeyTranslator._modifier_state = KeyTranslator__modifier_state 77 | 78 | 79 | else: # linux/xorg backend 80 | # For linux, this is more simple, just need to redefine one function to handle caps lock bit-mask 81 | import pynput.keyboard._xorg as xorg 82 | 83 | def shift_to_index(display, shift): 84 | return ( # |added thing| 85 | (1 if shift & 1 or shift & 3 else 0) + 86 | (2 if shift & xorg.alt_gr_mask(display) else 0)) 87 | 88 | xorg.shift_to_index = shift_to_index 89 | -------------------------------------------------------------------------------- /src/ion/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is just a little low level library for fetching keyboard input. 3 | This is a porting of the Numworks module, and add other methods created by others OS (like Omega or Upsilon). 4 | """ 5 | 6 | try: 7 | from .util.ion import Ion as __Ion, OS_MODE 8 | from .util.stuff.keys import * 9 | from .util.stuff.keys import ALL_KEYS 10 | except ImportError as e: 11 | if "relative import" not in e.msg: 12 | raise 13 | from util.ion import Ion as __Ion, OS_MODE 14 | from util.stuff.keys import * 15 | from util.stuff.keys import ALL_KEYS 16 | 17 | __name__ = "ion" 18 | __version__ = "2.1" 19 | try: 20 | with open("README.md", encoding="utf-8") as f: __doc__ = f.read() 21 | del f 22 | except (FileNotFoundError, OSError): __doc__ = "" 23 | __all__ = [ 24 | "keydown", 25 | "get_keys", 26 | "battery", 27 | "battery_level", 28 | "battery_ischarging", 29 | "set_brightness", 30 | "get_brightness", 31 | "file", # idk what is this 32 | ] 33 | __all__.extend(n["field"] for n in ALL_KEYS) 34 | 35 | 36 | ### Methods 37 | def keydown(k, /): 38 | """Return True if the k key is pressed (not release)""" 39 | key, err = __Ion.call(__Ion.keydown, k) 40 | if err != None: 41 | raise err 42 | return key 43 | 44 | def get_keys(): 45 | """Get name of pressed keys""" 46 | keys, err = __Ion.call(__Ion.get_keys) 47 | if err != None: 48 | raise err 49 | return keys 50 | 51 | # All the following functions only give a fake result to give a real look of library 52 | def battery(): 53 | """Return battery voltage""" 54 | voltage, err = __Ion.call(__Ion.battery) 55 | if err != None: 56 | raise err 57 | return voltage 58 | 59 | def battery_level(): 60 | """Return battery level""" 61 | level, err = __Ion.call(__Ion.battery_level) 62 | if err != None: 63 | raise err 64 | return level 65 | 66 | def battery_ischarging(): 67 | """Return True if the battery is charging""" 68 | charging, err = __Ion.call(__Ion.battery_ischarging) 69 | if err != None: 70 | raise err 71 | return charging 72 | 73 | def set_brightness(level, /): 74 | """Set brightness level of screen""" 75 | _, err = __Ion.call(__Ion.set_brightness, level) 76 | if err != None: 77 | raise err 78 | 79 | def get_brightness(): 80 | """Get brightness level of screen""" 81 | brightness, err = __Ion.call(__Ion.get_brightness) 82 | if err != None: 83 | raise err 84 | return brightness 85 | 86 | # I don't know why this exist, but is in source code of Omega and Upsilon 87 | class file: 88 | SEEK_SET = 0 89 | SEEK_CUR = 1 90 | SEEK_END = 2 91 | def __init__(self, *_, **__): 92 | raise \ 93 | TypeError(f"cannot create '{self.__class__.__name__}' instances") 94 | 95 | 96 | ### Cleanup 97 | if OS_MODE: 98 | if OS_MODE < 3: 99 | del get_keys, battery, battery_level, battery_ischarging, set_brightness, get_brightness 100 | __all__.remove("get_keys") 101 | __all__.remove("battery") 102 | __all__.remove("battery_level") 103 | __all__.remove("battery_ischarging") 104 | __all__.remove("set_brightness") 105 | __all__.remove("get_brightness") 106 | 107 | if OS_MODE == 1: 108 | del file 109 | __all__.remove("file") 110 | del OS_MODE, ALL_KEYS 111 | -------------------------------------------------------------------------------- /src/ion/util/stuff/focus_checker/win32.py: -------------------------------------------------------------------------------- 1 | from .base import * 2 | from threading import Thread 3 | 4 | import ctypes, ctypes.wintypes, time, subprocess 5 | 6 | class FocusChecker(BaseFocusChecker): 7 | def check_window(self, wid, pid=0, classname=None, not_classname=False, contains_title=None): 8 | if pid == 0: raise ValueError("a pid is needed") 9 | 10 | lpdw = ctypes.c_uint() 11 | ctypes.windll.user32.GetWindowThreadProcessId(wid, ctypes.byref(lpdw)) 12 | 13 | if lpdw.value == pid and ctypes.windll.user32.IsWindowVisible(wid): 14 | if classname: 15 | buff = ctypes.create_unicode_buffer(256) 16 | ctypes.windll.user32.GetClassNameW(wid, buff) 17 | 18 | if not ((not_classname and any([buff.value != name for name in classname])) or 19 | (not not_classname and any([buff.value == name for name in classname]))): 20 | return False 21 | 22 | if contains_title: 23 | buff = ctypes.create_unicode_buffer(256) 24 | ctypes.windll.user32.GetWindowTextW(wid, buff, 256) 25 | 26 | if contains_title not in buff.value.lower(): 27 | return False 28 | return True 29 | return False 30 | 31 | def search_window(self, pid=0, classname=None, not_classname=False, contains_title=None): 32 | if pid == 0: raise ValueError("a pid is needed") 33 | 34 | def foreach_window(hwnd, _): 35 | if self.check_window(hwnd, pid, classname, not_classname, contains_title): 36 | window.value = hwnd 37 | return False 38 | return True 39 | 40 | window = ctypes.c_uint(0) 41 | ctypes.windll.user32.EnumWindows(ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_uint, ctypes.c_uint)(foreach_window), 0) 42 | return window.value 43 | 44 | def register_window_callbacks(self): 45 | def window_state(hWinEventHook, event, hwnd, idObject, idChild, dwEventThread, dwmsEventTime): 46 | if idChild == idObject: 47 | if hwnd == self.kandinsky_window_id: self.kandinsky_window_id = -1 48 | elif hwnd == self.python_window_id: self.python_window_id = -1 49 | 50 | def register_hook(): 51 | hook = ctypes.WINFUNCTYPE( 52 | ctypes.wintypes.HANDLE, 53 | ctypes.wintypes.HANDLE, 54 | ctypes.wintypes.DWORD, 55 | ctypes.wintypes.HWND, 56 | ctypes.wintypes.LONG, 57 | ctypes.wintypes.LONG, 58 | ctypes.wintypes.DWORD, 59 | ctypes.wintypes.DWORD 60 | )(window_state) 61 | search_windows = True 62 | hook_id = ctypes.windll.user32.SetWinEventHook(0x8001, 0x8001, None, hook, 0, 0, 0) 63 | 64 | if hook_id: 65 | msg = ctypes.wintypes.MSG() 66 | while (self.kandinsky_window_id != -1 or 67 | (DISABLE_KANDINSKY_INPUT_ONLY and self.python_window_id != -1)): 68 | time.sleep(0.1) 69 | r = ctypes.windll.user32.PeekMessageW(ctypes.byref(msg), None, 0, 0, 0) 70 | 71 | if r == 0: 72 | ctypes.windll.user32.TranslateMessage(msg) 73 | ctypes.windll.user32.DispatchMessageW(msg) 74 | elif r <=0 or msg.message == 0x0401: 75 | prettywarn("window destroy detector has been broken", RuntimeWarning) 76 | break 77 | 78 | if search_windows: 79 | self.bind_windows() 80 | if self.kandinsky_window_id and self.python_window_id: search_windows = False 81 | 82 | ctypes.windll.user32.UnhookWinEvent(hook_id) 83 | else: prettywarn("cannot hook the window destroy detector", RuntimeWarning) 84 | 85 | 86 | self.thread = Thread(name="WindowDestroyDetector", target=register_hook, daemon=True) 87 | self.thread.start() 88 | 89 | def get_ppid(self, pid): 90 | # TODO: idk how to get this information better than that 91 | # Use 'wmic' command to get ppid of process 92 | try: result = [i.strip() for i in subprocess.check_output(f"wmic process where ProcessId={pid} get ParentProcessId".split(' '), stderr=subprocess.PIPE).decode().splitlines() if i.strip() != ''] 93 | except subprocess.CalledProcessError: return -1 94 | 95 | if len(result) < 2: return -2 96 | return int(result[1].strip()) 97 | 98 | def get_focussed_window(self): 99 | return ctypes.windll.user32.GetForegroundWindow() 100 | -------------------------------------------------------------------------------- /src/ion/util/stuff/keys.py: -------------------------------------------------------------------------------- 1 | from pynput.keyboard import Key 2 | import sys # for macos compatibility 3 | 4 | KEY_LEFT: int = {'code': 0, 'name': 'left', 'key': Key.left} 5 | KEY_UP: int = {'code': 1, 'name': 'up', 'key': Key.up} 6 | KEY_DOWN: int = {'code': 2, 'name': 'down', 'key': Key.down} 7 | KEY_RIGHT: int = {'code': 3, 'name': 'right', 'key': Key.right} 8 | KEY_OK: int = {'code': 4, 'name': 'OK', 'key': Key.enter} 9 | KEY_BACK: int = {'code': 5, 'name': 'back', 'key': Key.delete} 10 | KEY_HOME: int = {'code': 6, 'name': 'home', 'key': Key.esc} 11 | KEY_ONOFF: int = {'code': 7, 'name': 'onOff', 'key': Key.end} 12 | KEY_SHIFT: int = {'code': 12, 'name': 'shift', 'key': Key.shift} 13 | KEY_ALPHA: int = {'code': 13, 'name': 'alpha', 'key': Key.ctrl} 14 | KEY_XNT: int = {'code': 14, 'name': 'xnt', 'key': 'x'} 15 | KEY_VAR: int = {'code': 15, 'name': 'var', 'key': 'v'} 16 | KEY_TOOLBOX: int = {'code': 16, 'name': 'toolbox', 'key': '"'} 17 | KEY_BACKSPACE: int = {'code': 17, 'name': 'backspace', 'key': Key.backspace} 18 | KEY_EXP: int = {'code': 18, 'name': 'exp', 'key': 'e'} 19 | KEY_LN: int = {'code': 19, 'name': 'ln', 'key': 'n'} 20 | KEY_LOG: int = {'code': 20, 'name': 'log', 'key': 'l'} 21 | KEY_IMAGINARY: int = {'code': 21, 'name': 'imaginary', 'key': 'i'} 22 | KEY_COMMA: int = {'code': 22, 'name': 'comma', 'key': ','} 23 | KEY_POWER: int = {'code': 23, 'name': 'power', 'key': '^'} 24 | KEY_SINE: int = {'code': 24, 'name': 'sin', 'key': 's'} 25 | KEY_COSINE: int = {'code': 25, 'name': 'cos', 'key': 'c'} 26 | KEY_TANGENT: int = {'code': 26, 'name': 'tan', 'key': 't'} 27 | KEY_PI: int = {'code': 27, 'name': 'pi', 'key': 'p'} 28 | KEY_SQRT: int = {'code': 28, 'name': 'sqrt', 'key': 'r'} 29 | KEY_SQUARE: int = {'code': 29, 'name': 'square', 'key': '>'} 30 | KEY_SEVEN: int = {'code': 30, 'name': '7', 'key': '7'} 31 | KEY_EIGHT: int = {'code': 31, 'name': '8', 'key': '8'} 32 | KEY_NINE: int = {'code': 32, 'name': '9', 'key': '9'} 33 | KEY_LEFTPARENTHESIS: int = {'code': 33, 'name': '(', 'key': '('} 34 | KEY_RIGHTPARENTHESIS: int = {'code': 34, 'name': ')', 'key': ')'} 35 | KEY_FOUR: int = {'code': 36, 'name': '4', 'key': '4'} 36 | KEY_FIVE: int = {'code': 37, 'name': '5', 'key': '5'} 37 | KEY_SIX: int = {'code': 38, 'name': '6', 'key': '6'} 38 | KEY_MULTIPLICATION: int = {'code': 39, 'name': '*', 'key': '*'} 39 | KEY_DIVISION: int = {'code': 40, 'name': '/', 'key': '/'} 40 | KEY_ONE: int = {'code': 42, 'name': '1', 'key': '1'} 41 | KEY_TWO: int = {'code': 43, 'name': '2', 'key': '2'} 42 | KEY_THREE: int = {'code': 44, 'name': '3', 'key': '3'} 43 | KEY_PLUS: int = {'code': 45, 'name': '+', 'key': '+'} 44 | KEY_MINUS: int = {'code': 46, 'name': '-', 'key': '-'} 45 | KEY_ZERO: int = {'code': 48, 'name': '0', 'key': '0'} 46 | KEY_DOT: int = {'code': 49, 'name': '.', 'key': '.'} 47 | KEY_EE: int = {'code': 50, 'name': 'EE', 'key': '!'} 48 | KEY_ANS: int = {'code': 51, 'name': 'Ans', 'key': 'a'} # vv Insert doesn't exists on mac keyboards, so use shift+enter 49 | KEY_EXE: int = {'code': 52, 'name': 'EXE', 'key': (Key.shift, Key.enter) if sys.platform.startswith("darwin") else Key.insert} 50 | 51 | # Put all keys in ALL_KEYS and redefine each key only by its code 52 | ALL_KEYS = [] 53 | ALL_KEYS_UNORDERED = {} 54 | ALL_HOTKEYS = [] 55 | 56 | for n, k in locals().copy().items(): 57 | # Avoid to re-replace variable if file is imported at multiple times 58 | if n.startswith("KEY_") and type(k) == dict: 59 | k.update({'field': n}) 60 | locals()[n] = k['code'] # TODO: it's a good way to do that? 61 | ALL_KEYS.append(k) 62 | ALL_KEYS_UNORDERED[k['key']] = k 63 | if type(k['key']) in (tuple, list): ALL_HOTKEYS.append(k) 64 | 65 | NUMBER_OF_KEYS = len(ALL_KEYS) 66 | 67 | __all__ = [k['field'] for k in ALL_KEYS] 68 | -------------------------------------------------------------------------------- /src/ion/util/stuff/keylogger.py: -------------------------------------------------------------------------------- 1 | from pynput.keyboard import Listener, Key, KeyCode, _NORMAL_MODIFIERS # hidden by __init__.py 2 | 3 | from .pynput_patcher import * 4 | from .keys import ALL_KEYS, ALL_KEYS_UNORDERED, ALL_HOTKEYS 5 | from .focus_checker import FocusChecker 6 | from .common import print_debug 7 | 8 | # NOTE: the 'keycode' means the Numworks keyboard keycode, not a real keyboard keycode 9 | 10 | 11 | class KeyLogger: 12 | _listener: Listener = None 13 | _check_focus: FocusChecker = None 14 | _focused = False 15 | _keyboard_state: dict[int, bool] = {} 16 | _error = None 17 | 18 | def __init__(self): 19 | raise NotImplementedError("singleton class") 20 | 21 | @staticmethod 22 | def _normalize_key(key): 23 | # We `.lower()` it, so that holding shift or having caplock enabled does not disable letter-binded keys. 24 | if type(key) == KeyCode and key.char is not None: return key.char.lower() 25 | # Try to normalize the modifier. E.g. Key.ctrl_r -> Key.ctrl 26 | elif type(key) == Key: return _NORMAL_MODIFIERS.get(key.value, key) 27 | return key 28 | 29 | @staticmethod 30 | def _on_press(key): 31 | try: 32 | if key is None: return # because the key can be None in some cases 33 | print_debug("Pressed", key) 34 | key = KeyLogger._normalize_key(key) 35 | 36 | KeyLogger._focused = KeyLogger._check_focus() 37 | if not KeyLogger._focused: return 38 | 39 | k = ALL_KEYS_UNORDERED.get(key) 40 | if k is None: return 41 | KeyLogger.set_pressed(k["code"], True) 42 | 43 | # Handle hotkeys 44 | for h in ALL_HOTKEYS: 45 | if all(KeyLogger.is_pressed(ALL_KEYS_UNORDERED.get(k)["code"], no_check=True) for k in h["key"]): 46 | KeyLogger.set_pressed(h["code"], True, no_check=True) 47 | # Suppress the binded keys 48 | for k in h["key"]: KeyLogger.set_pressed(ALL_KEYS_UNORDERED.get(k)["code"], False, no_check=True) 49 | 50 | except BaseException as e: 51 | KeyLogger._error = e 52 | KeyLogger.stop() 53 | return 54 | 55 | @staticmethod 56 | def _on_release(key): 57 | try: 58 | if key is None: return # because the key can be None is some cases 59 | print_debug("Released", key) 60 | key = KeyLogger._normalize_key(key) 61 | 62 | k = ALL_KEYS_UNORDERED.get(key) 63 | if k is None: return 64 | KeyLogger.set_pressed(k["code"], False) 65 | 66 | # Handle hotkeys 67 | for h in ALL_HOTKEYS: 68 | if KeyLogger.is_pressed(h["code"], no_check=True) and key in h["key"]: 69 | KeyLogger.set_pressed(h["code"], False, no_check=True) 70 | # Restore the binded keys 71 | for k in h["key"]: 72 | if k != key: KeyLogger.set_pressed(ALL_KEYS_UNORDERED.get(k)["code"], True, no_check=True) 73 | 74 | except BaseException as e: 75 | KeyLogger._error = e 76 | KeyLogger.stop() 77 | return 78 | 79 | @staticmethod 80 | def start(): 81 | """ 82 | Start the KeyLogger. 83 | Cannot be called twice without calling .stop() first. 84 | """ 85 | 86 | if KeyLogger.is_running(): raise RuntimeError("KeyLogger is already running") 87 | 88 | KeyLogger._error = None # remove last error 89 | KeyLogger._keyboard_state = {k["code"]: False for k in ALL_KEYS} 90 | KeyLogger._check_focus = FocusChecker() 91 | KeyLogger._listener = Listener(KeyLogger._on_press, KeyLogger._on_release) 92 | KeyLogger._listener.start() 93 | 94 | @staticmethod 95 | def stop(): 96 | """Stop the KeyLogger""" 97 | 98 | if not KeyLogger.is_running(): return 99 | if KeyLogger._listener: KeyLogger._listener.stop() 100 | KeyLogger._listener = None 101 | KeyLogger._check_focus = None 102 | KeyLogger._focused = False 103 | KeyLogger._keyboard_state = {} 104 | 105 | @staticmethod 106 | def is_running(): 107 | """Return whether the KeyLogger is running""" 108 | 109 | return KeyLogger._listener and KeyLogger._listener.is_alive() 110 | 111 | def raise_if_error(): 112 | """Raise the last error""" 113 | 114 | if KeyLogger._error: 115 | error = KeyLogger._error 116 | KeyLogger._error = None # remove the last error after raised it 117 | raise error 118 | 119 | @staticmethod 120 | def check_ok(code): 121 | """Check the Keylogger state, the keycode and the focus""" 122 | 123 | KeyLogger.raise_if_error() 124 | if not KeyLogger.is_running(): raise RuntimeError("KeyLogger not running") 125 | elif type(code) != int: raise TypeError(f"keycode must be an integer, not {type(code).__name__}") 126 | elif code not in KeyLogger._keyboard_state: raise IndexError(f"key with code '{code}' not found") 127 | try: KeyLogger._check_focus.available() 128 | except: 129 | KeyLogger.stop() 130 | raise 131 | 132 | @staticmethod 133 | def is_pressed(code, *, no_check=False): 134 | """ 135 | Get state of a key (is pressed or not) with his keycode. 136 | 137 | Note: using no_check is insecure 138 | """ 139 | 140 | if not no_check: KeyLogger.check_ok(code) 141 | return KeyLogger._focused and KeyLogger._keyboard_state[code] 142 | 143 | @staticmethod 144 | def set_pressed(code, is_pressed, *, no_check=False): 145 | """ 146 | Set state of a key with his keycode. 147 | 148 | Note: using no_check is insecure 149 | """ 150 | 151 | if not no_check: KeyLogger.check_ok(code) 152 | KeyLogger._keyboard_state[code] = bool(is_pressed) 153 | -------------------------------------------------------------------------------- /src/ion/util/stuff/focus_checker/base.py: -------------------------------------------------------------------------------- 1 | from ..common import prettywarn, print_debug 2 | import sys, os 3 | 4 | # By default it just read kandinsky window (only if is focused) 5 | DISABLE_KANDINSKY_INPUT_ONLY = 'ION_DISABLE_KANDINSKY_INPUT_ONLY' in os.environ 6 | # Option to get input everywhere on system 7 | GET_INPUT_EVERYWHERE = 'ION_ENABLE_GET_INPUT_EVERYWHERE' in os.environ 8 | 9 | 10 | class BaseFocusChecker: 11 | """ 12 | Base class for FocusChecker 13 | 14 | following methods must be overrides: 15 | - check_window(wid, pid, classname, not_classname, contains_title) 16 | - search_window(pid, classname, not_classname, contains_title) 17 | - get_focussed_window() 18 | - get_ppid(pid) 19 | """ 20 | 21 | kandinsky_window_id = 0 22 | kandinsky_not_found_error_printed = False 23 | python_window_id = 0 24 | python_not_found_error_printed = False 25 | script_pid = os.getpid() 26 | # used for a more specific search 27 | script_filename = os.path.basename(sys.argv[0]) 28 | 29 | # must contains this name 30 | winname = "kandinsky" 31 | # 'TkTopLevel' is the class name of root tkinter window, 'pygame' because in old releases of kandinsky i used pygame 32 | classnames = ("TkTopLevel", "pygame") 33 | 34 | def __init__(self): 35 | self.bind_windows() 36 | self.register_window_callbacks() 37 | 38 | def __call__(self): 39 | self.available() 40 | self.bind_windows() 41 | focussed = self.get_focussed_window() 42 | 43 | return ((self.python_window_id and focussed == self.python_window_id) or 44 | (self.kandinsky_window_id and focussed == self.kandinsky_window_id)) 45 | 46 | def available(self): 47 | """Check if windows still exists, to stop the KeyLogger properly""" 48 | self.check_windows_availability() 49 | 50 | ### Internal api 51 | 52 | def bind_windows(self): 53 | if (DISABLE_KANDINSKY_INPUT_ONLY or self.kandinsky_window_id == 0) and self.python_window_id == 0: 54 | # Find python console window and ignore the top level of tkinter 55 | self.python_window_id = self.get_python_console_window() 56 | 57 | if self.python_window_id == 0: 58 | # No valid (parent) window found! 59 | # Python probably started in no-shell-mode and/or by a task 60 | # So will not log python console inputs 61 | if not self.python_not_found_error_printed: 62 | prettywarn("unable to find an valid window to get inputs from python console.", RuntimeWarning) 63 | self.python_not_found_error_printed = True 64 | else: print_debug("FocusChecker", f"found the window '{self.python_window_id}' as python console") 65 | 66 | # Verify is kandinsky is imported 67 | if self.kandinsky_window_id == 0 and "kandinsky" in sys.modules: 68 | # To find kandinsky is more simple, no need to find parent processes with a valid window 69 | self.kandinsky_window_id = self.get_kandinsky_window() 70 | 71 | if self.kandinsky_window_id == 0: 72 | # Kandinsky window not found 73 | if not self.kandinsky_not_found_error_printed: 74 | prettywarn("could not find the kandinsky window to get inputs.", RuntimeWarning) 75 | self.kandinsky_not_found_error_printed = True 76 | else: print_debug("FocusChecker", f"found the window '{self.kandinsky_window_id}' as kandinsky") 77 | 78 | if self.kandinsky_window_id and not DISABLE_KANDINSKY_INPUT_ONLY: 79 | self.python_window_id = 0 80 | 81 | def check_windows_availability(self): 82 | if self.kandinsky_window_id == -1: 83 | raise RuntimeError(f"Kandinsky window destroyed. Unable to locate it.") 84 | if self.python_window_id == -1: 85 | raise RuntimeError(f"Python console window destroyed. Unable to locate it.") 86 | 87 | def check_window(self, wid, pid=0, classname=None, not_classname=False, contains_title=None): 88 | raise NotImplementedError 89 | 90 | def search_window(self, pid=0, classname=None, not_classname=False, contains_title=None): 91 | raise NotImplementedError 92 | 93 | def get_window(self, pid=0, classname=None, not_classname=False, contains_title=None, wid=0): 94 | if type(wid) != int: raise ValueError("invalid wid") 95 | if type(pid) != int or pid < 0: raise ValueError("invalid pid") 96 | if not pid and not classname and not contains_title: raise ValueError("pid, classname or contains_title must be specified") 97 | if classname: 98 | if type(classname) in (list, tuple): pass 99 | elif type(classname) == str: classname = (classname,) 100 | else: raise TypeError("invalid type for classname") 101 | if contains_title: 102 | if type(contains_title) != str: raise TypeError("invalid type for contains_title") 103 | contains_title = contains_title.lower() 104 | 105 | if wid == 0: return self.search_window(pid, classname, not_classname, contains_title) 106 | return wid if self.check_window(wid, pid, classname, not_classname, contains_title) else 0 107 | 108 | def get_ppid(self, pid): 109 | raise NotImplementedError 110 | 111 | def get_kandinsky_window(self, wid=0): 112 | return self.get_window(self.script_pid, self.classnames, False, self.winname, wid) 113 | 114 | def get_python_console_window(self, wid=0): 115 | wid = self.get_window(self.script_pid, self.classnames, True, self.script_filename, wid) 116 | if wid == 0: wid = self.get_window(self.script_pid, self.classnames, True, wid=wid) 117 | 118 | if wid == 0: 119 | # Python probably started by another process, in this mode, python don't have 'real' window 120 | # So try going back in the parent processes to find a valid window 121 | ppid = os.getppid() 122 | for _ in range(20): # Loop limit to avoid infinite loop 123 | wid = self.get_window(ppid, self.classnames, True, self.script_filename, wid) 124 | if wid == 0: wid = self.get_window(ppid, self.classnames, True, wid=wid) 125 | 126 | # Found an valid window 127 | if wid: break 128 | 129 | # Not found at this time, try with his ppid 130 | found_ppid = self.get_ppid(ppid) 131 | if found_ppid < 0: continue # error happening, will try again in the next iteration 132 | if found_ppid == 0: break # 0 is not a valid PID (0 is the kernel itself) 133 | ppid = found_ppid 134 | 135 | return wid 136 | 137 | def get_focussed_window(self): 138 | raise NotImplementedError 139 | 140 | def register_window_callbacks(self): 141 | return 142 | 143 | 144 | # Fake FocusChecker class, will always return True 145 | class NoopFocusChecker(BaseFocusChecker): 146 | def __init__(self): return 147 | def __call__(self): return True 148 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Visitor Badge](https://visitor-badge.laobi.icu/badge?page_id=ZetaMap.Ion-Numworks) ![Downloads](https://shields.io/github/downloads/ZetaMap/Ion-Numworks/total) ![pip](https://img.shields.io/pypi/dm/ion-numworks?label=pip_downloads) 2 | 3 | # Ion-numworks 4 | This is just a little low level library for fetching keyboard input.
5 | This is a porting of the Numworks module, and add other methods created by others OS (like Omega or Upsilon). 6 | 7 | 8 | ### Installation 9 | You can download it on [pypi.org](https://pypi.org/project/ion-numworks), download files of the [latest release](https://github.com/ZetaMap/Ion-numworks/releases/latest), or simply run this command to install library: ``pip install ion-numworks``.
10 | To install from local folder, use: ``pip install .`` 11 | 12 | 13 | ### More 14 | I also created the porting of the [Numworks' Kandinsky module](https://github.com/ZetaMap/Kandinsky-Numworks) 15 | 16 | 17 | ### API methods 18 | *Numworks and Omega methods* 19 | 20 | #### keydown(): 21 | * Parameters: ``k`` 22 | * Description: Return True if the ``k`` key is pressed (not release) 23 | 24 |
25 | 26 | *Upsilon-specific methods (previous are also added)* 27 | 28 | #### get_keys(): 29 | * Parameters: **No parameters** 30 | * Description: Get name of pressed keys 31 | 32 | #### battery(): 33 | * Parameters: **No parameters** 34 | * Description: Return battery voltage *(give a fake result)* 35 | 36 | #### battery_level(): 37 | * Parameters: **No parameters** 38 | * Description: Return battery level *(give a fake result)* 39 | 40 | #### battery_ischarging(): 41 | * Parameters: **No parameters** 42 | * Description: Return True if the battery is charging *(give a fake result)* 43 | 44 | #### set_brightness(): 45 | * Parameters: ``level`` 46 | * Description: Set brightness level of screen *(do nothing)* 47 | 48 | #### get_brightness(): 49 | * Parameters: **No parameters** 50 | * Description: Get brightness level of screen 51 | 52 | 53 | ### Numworks keyboard association 54 | | Numworks key | Computer key | Field name | Field value 55 | |:-------------|:------------------|:---------------------|:------------ 56 | | left | ⯇ (Left) | KEY_LEFT | 0 57 | | up | ⯅ (Up) | KEY_UP | 1 58 | | down | ⯆ (Down) | KEY_DOWN | 2 59 | | right | ⯈ (Right) | KEY_RIGHT | 3 60 | | OK | **⮠** (Return) | KEY_OK | 4 61 | | back | Delete | KEY_BACK | 5 62 | | home | Escape | KEY_HOME | 6 63 | | onOff | End | KEY_ONOFF | 7 64 | | shift | **⇧** (Shift) | KEY_SHIFT | 12 65 | | alpha | CTRL | KEY_ALPHA | 13 66 | | xnt | X | KEY_XNT | 14 67 | | var | V | KEY_VAR | 15 68 | | toolbox | " | KEY_TOOLBOX | 16 69 | | backspace | **🠄** (Backspace) | KEY_BACKSPACE | 17 70 | | exp | E | KEY_EXP | 18 71 | | ln | N | KEY_LN | 19 72 | | log | L | KEY_LOG | 20 73 | | imaginary | I | KEY_IMAGINARY | 21 74 | | comma | , | KEY_COMMA | 22 75 | | power | ^ | KEY_POWER | 23 76 | | sin | S | KEY_SINE | 24 77 | | cos | C | KEY_COSINE | 25 78 | | tan | T | KEY_TANGENT | 26 79 | | pi | P | KEY_PI | 27 80 | | sqrt | R | KEY_SQRT | 28 81 | | square | > | KEY_SQUARE | 29 82 | | 7 | 7 | KEY_SEVEN | 30 83 | | 8 | 8 | KEY_EIGHT | 31 84 | | 9 | 9 | KEY_NINE | 32 85 | | ( | ( | KEY_LEFTPARENTHESIS | 33 86 | | ) | ) | KEY_RIGHTPARENTHESIS | 34 87 | | 4 | 4 | KEY_FOUR | 36 88 | | 5 | 5 | KEY_FIVE | 37 89 | | 6 | 6 | KEY_SIX | 38 90 | | * | * | KEY_MULTIPLICATION | 39 91 | | / | / | KEY_DIVISION | 40 92 | | 1 | 1 | KEY_ONE | 42 93 | | 2 | 2 | KEY_TWO | 43 94 | | 3 | 3 | KEY_THREE | 44 95 | | + | + | KEY_PLUS | 45 96 | | - | - | KEY_MINUS | 46 97 | | 0 | 0 | KEY_ZERO | 48 98 | | . | . | KEY_DOT | 49 99 | | EE | ! | KEY_EE | 50 100 | | Ans | A | KEY_ANS | 51 101 | | EXE | Insert *(For MacOS: Shift+Return)* | KEY_EXE | 52 102 | 103 | 104 | ### Environ variables 105 | > [!IMPORTANT] 106 | > You must make these additions before importing the ion module, otherwise the changes will not take effect. 107 | 108 | Some library options can be modified by environ variables.
109 | To do so, add a compatibility check and place the environ variables into: 110 | ```python 111 | try: 112 | import os 113 | "" 114 | except: pass 115 | ``` 116 | 117 |
118 | 119 | * Change starting OS (methods according to the selected os will be created):
120 | *(Option name is same as Kandinsky so that, if both libraries are present, they are synchronized)* 121 | ```python 122 | # '0': All methods 123 | # '1': Numworks methods 124 | # '2': Omega method 125 | # '3': Upsilon methods 126 | os.environ['KANDINSKY_OS_MODE'] = '' 127 | ``` 128 | 129 | * Or if you don't want to synchronize the library with kandinsky, use this environ name: 130 | ```python 131 | os.environ['ION_OS_MODE'] = '' 132 | ``` 133 | 134 | * Enable debug mode: 135 | ```python 136 | # Print full error stacktrace, the pressed key and methods calls 137 | os.environ['ION_ENABLE_DEBUG'] = '' 138 | ``` 139 | 140 | * Disable warnings: 141 | ```python 142 | # Will disable all ion warnings, like not found windows or incompatibilities. 143 | os.environ['ION_DISABLE_WARNINGS'] = '' 144 | ``` 145 | 146 | * Disable inputs reading only from the kandinsky window: 147 | ```python 148 | # This options allow keyboard inputs reading from the python console and the kandinsky window 149 | # By default it only reads the kandinsky window (only if focused by user) 150 | # Note: if kandinsky is not imported globally, this option is enabled by default 151 | os.environ['ION_DISABLE_KANDINSKY_INPUT_ONLY'] = '' 152 | ``` 153 | 154 | * Get keyboard inputs everywhere (not only from kandinsky window or python console): 155 | ```python 156 | # Allow to get inputs from entire system, like previous version of library 157 | os.environ['ION_ENABLE_GET_INPUT_EVERYWHERE'] = '' 158 | ``` 159 | -------------------------------------------------------------------------------- /src/ion/README.md: -------------------------------------------------------------------------------- 1 | ![Visitor Badge](https://visitor-badge.laobi.icu/badge?page_id=ZetaMap.Ion-Numworks) ![Downloads](https://shields.io/github/downloads/ZetaMap/Ion-Numworks/total) ![pip](https://img.shields.io/pypi/dm/ion-numworks?label=pip_downloads) 2 | 3 | # Ion-numworks 4 | This is just a little low level library for fetching keyboard input.
5 | This is a porting of the Numworks module, and add other methods created by others OS (like Omega or Upsilon). 6 | 7 | 8 | ### Installation 9 | You can download it on [pypi.org](https://pypi.org/project/ion-numworks), download files of the [latest release](https://github.com/ZetaMap/Ion-numworks/releases/latest), or simply run this command to install library: ``pip install ion-numworks``.
10 | To install from local folder, use: ``pip install .`` 11 | 12 | 13 | ### More 14 | I also created the porting of the [Numworks' Kandinsky module](https://github.com/ZetaMap/Kandinsky-Numworks) 15 | 16 | 17 | ### API methods 18 | *Numworks and Omega methods* 19 | 20 | #### keydown(): 21 | * Parameters: ``k`` 22 | * Description: Return True if the ``k`` key is pressed (not release) 23 | 24 |
25 | 26 | *Upsilon-specific methods (previous are also added)* 27 | 28 | #### get_keys(): 29 | * Parameters: **No parameters** 30 | * Description: Get name of pressed keys 31 | 32 | #### battery(): 33 | * Parameters: **No parameters** 34 | * Description: Return battery voltage *(give a fake result)* 35 | 36 | #### battery_level(): 37 | * Parameters: **No parameters** 38 | * Description: Return battery level *(give a fake result)* 39 | 40 | #### battery_ischarging(): 41 | * Parameters: **No parameters** 42 | * Description: Return True if the battery is charging *(give a fake result)* 43 | 44 | #### set_brightness(): 45 | * Parameters: ``level`` 46 | * Description: Set brightness level of screen *(do nothing)* 47 | 48 | #### get_brightness(): 49 | * Parameters: **No parameters** 50 | * Description: Get brightness level of screen 51 | 52 | 53 | ### Numworks keyboard association 54 | | Numworks key | Computer key | Field name | Field value 55 | |:-------------|:------------------|:---------------------|:------------ 56 | | left | ⯇ (Left) | KEY_LEFT | 0 57 | | up | ⯅ (Up) | KEY_UP | 1 58 | | down | ⯆ (Down) | KEY_DOWN | 2 59 | | right | ⯈ (Right) | KEY_RIGHT | 3 60 | | OK | **⮠** (Return) | KEY_OK | 4 61 | | back | Delete | KEY_BACK | 5 62 | | home | Escape | KEY_HOME | 6 63 | | onOff | End | KEY_ONOFF | 7 64 | | shift | **⇧** (Shift) | KEY_SHIFT | 12 65 | | alpha | CTRL | KEY_ALPHA | 13 66 | | xnt | X | KEY_XNT | 14 67 | | var | V | KEY_VAR | 15 68 | | toolbox | " | KEY_TOOLBOX | 16 69 | | backspace | **🠄** (Backspace) | KEY_BACKSPACE | 17 70 | | exp | E | KEY_EXP | 18 71 | | ln | N | KEY_LN | 19 72 | | log | L | KEY_LOG | 20 73 | | imaginary | I | KEY_IMAGINARY | 21 74 | | comma | , | KEY_COMMA | 22 75 | | power | ^ | KEY_POWER | 23 76 | | sin | S | KEY_SINE | 24 77 | | cos | C | KEY_COSINE | 25 78 | | tan | T | KEY_TANGENT | 26 79 | | pi | P | KEY_PI | 27 80 | | sqrt | R | KEY_SQRT | 28 81 | | square | > | KEY_SQUARE | 29 82 | | 7 | 7 | KEY_SEVEN | 30 83 | | 8 | 8 | KEY_EIGHT | 31 84 | | 9 | 9 | KEY_NINE | 32 85 | | ( | ( | KEY_LEFTPARENTHESIS | 33 86 | | ) | ) | KEY_RIGHTPARENTHESIS | 34 87 | | 4 | 4 | KEY_FOUR | 36 88 | | 5 | 5 | KEY_FIVE | 37 89 | | 6 | 6 | KEY_SIX | 38 90 | | * | * | KEY_MULTIPLICATION | 39 91 | | / | / | KEY_DIVISION | 40 92 | | 1 | 1 | KEY_ONE | 42 93 | | 2 | 2 | KEY_TWO | 43 94 | | 3 | 3 | KEY_THREE | 44 95 | | + | + | KEY_PLUS | 45 96 | | - | - | KEY_MINUS | 46 97 | | 0 | 0 | KEY_ZERO | 48 98 | | . | . | KEY_DOT | 49 99 | | EE | ! | KEY_EE | 50 100 | | Ans | A | KEY_ANS | 51 101 | | EXE | Insert *(For MacOS: Shift+Return)* | KEY_EXE | 52 102 | 103 | 104 | ### Environ variables 105 | > [!IMPORTANT] 106 | > You must make these additions before importing the ion module, otherwise the changes will not take effect. 107 | 108 | Some library options can be modified by environ variables.
109 | To do so, add a compatibility check and place the environ variables into: 110 | ```python 111 | try: 112 | import os 113 | "" 114 | except: pass 115 | ``` 116 | 117 |
118 | 119 | * Change starting OS (methods according to the selected os will be created):
120 | *(Option name is same as Kandinsky so that, if both libraries are present, they are synchronized)* 121 | ```python 122 | # '0': All methods 123 | # '1': Numworks methods 124 | # '2': Omega method 125 | # '3': Upsilon methods 126 | os.environ['KANDINSKY_OS_MODE'] = '' 127 | ``` 128 | 129 | * Or if you don't want to synchronize the library with kandinsky, use this environ name: 130 | ```python 131 | os.environ['ION_OS_MODE'] = '' 132 | ``` 133 | 134 | * Enable debug mode: 135 | ```python 136 | # Print full error stacktrace, the pressed key and methods calls 137 | os.environ['ION_ENABLE_DEBUG'] = '' 138 | ``` 139 | 140 | * Disable warnings: 141 | ```python 142 | # Will disable all ion warnings, like not found windows or incompatibilities. 143 | os.environ['ION_DISABLE_WARNINGS'] = '' 144 | ``` 145 | 146 | * Disable inputs reading only from the kandinsky window: 147 | ```python 148 | # This options allow keyboard inputs reading from the python console and the kandinsky window 149 | # By default it only reads the kandinsky window (only if focused by user) 150 | # Note: if kandinsky is not imported globally, this option is enabled by default 151 | os.environ['ION_DISABLE_KANDINSKY_INPUT_ONLY'] = '' 152 | ``` 153 | 154 | * Get keyboard inputs everywhere (not only from kandinsky window or python console): 155 | ```python 156 | # Allow to get inputs from entire system, like previous version of library 157 | os.environ['ION_ENABLE_GET_INPUT_EVERYWHERE'] = '' 158 | ``` 159 | -------------------------------------------------------------------------------- /src/ion/util/stuff/focus_checker/linux.py: -------------------------------------------------------------------------------- 1 | from .base import * 2 | from threading import Thread 3 | 4 | import signal, warnings, subprocess 5 | 6 | try: 7 | import Xlib 8 | import Xlib.xobject.drawable 9 | except ImportError as e: 10 | e.msg = "Xlib module not installed. Please install it with command 'pip install python-xlib'" 11 | raise 12 | 13 | 14 | # Check graphical server type 15 | try: graphical_server_type = subprocess.check_output("loginctl show-session $(loginctl | awk '/'$(whoami)'/ {print $1}') -p Type --value", shell=True, stderr=subprocess.STDOUT).decode().strip() 16 | except subprocess.CalledProcessError as e: 17 | if "not been booted" in e.stdout.decode().strip(): # propably a non graphical system or no login manager 18 | prettywarn("no graphical server instance detected, falling back to x11 support", RuntimeWarning) 19 | else: prettywarn("unable to get the graphical server type, falling back to x11 support", RuntimeWarning) 20 | # Fall baack to x11 support 21 | graphical_server_type = "x11" 22 | else: 23 | if "not been booted" in graphical_server_type: 24 | prettywarn("no graphical server instance detected, falling back to x11 support", RuntimeWarning) 25 | graphical_server_type = "x11" 26 | 27 | # x11 or wayland, or... other? can be? 28 | if graphical_server_type not in ("x11", "wayland"): 29 | prettywarn(f"graphical server {graphical_server_type!r} not supported, falling back to x11 support", RuntimeWarning) 30 | 31 | # TODO: complete support of wayland 32 | is_wayland = graphical_server_type == "wayland" 33 | 34 | # remove the resource warning 35 | if ("ignore", None, ResourceWarning, None, 0) not in warnings.filters: 36 | warnings.simplefilter("ignore", ResourceWarning) 37 | 38 | 39 | class FocusChecker(BaseFocusChecker): 40 | # Use sys.argv[0] because the window classname of pygame if file name of script 41 | classnames = ("Tk", BaseFocusChecker.script_filename) 42 | 43 | def __init__(self): 44 | self.display = Xlib.display.Display() 45 | # Close the socket when script is finished 46 | signal.signal(signal.SIGINT|signal.SIGTERM|signal.SIGKILL|signal.SIGQUIT, 47 | lambda: self.display.display.close_internal("client")) 48 | super().__init__() 49 | 50 | def __del__(self): 51 | try: self.display.close() 52 | except Xlib.error.ConnectionClosedError: pass # already closed 53 | __exit__ = __del__ 54 | 55 | def get_wm_pid(self, window): 56 | p = window.get_full_property(window.display.get_atom('_NET_WM_PID'), Xlib.X.AnyPropertyType) 57 | if p is None: return None 58 | return p.value[0] 59 | 60 | def check_window(self, wid, pid=0, classname=None, not_classname=False, contains_title=None): 61 | # get the window object by his id 62 | if isinstance(wid, Xlib.xobject.drawable.Window): win = wid 63 | else: win = self.display.create_resource_object('window', wid) 64 | 65 | wpid = self.get_wm_pid(win) 66 | found = False 67 | 68 | if (pid == 0 or (wpid and pid == wpid)) and win.get_attributes().map_state == Xlib.X.IsViewable: 69 | found = True 70 | 71 | if found and classname: 72 | wclass = win.get_wm_class() 73 | if not wclass or not ((not_classname and any([wclass[1] != name for name in classname])) or 74 | (not not_classname and any([wclass[1] == name for name in classname]))): 75 | found = False 76 | 77 | if found and contains_title: 78 | wtitle = win.get_wm_name() 79 | # check the value because some window return an empty title with this method 80 | if wtitle == b'': 81 | wtitle = win.get_full_property(self.display.get_atom('_NET_WM_NAME'), Xlib.X.AnyPropertyType) 82 | if wtitle: wtitle = wtitle.value.decode() 83 | if not wtitle or contains_title not in wtitle.lower(): found = False 84 | 85 | return found 86 | 87 | def search_window(self, pid=0, classname=None, not_classname=False, contains_title=None): 88 | wins = [self.display.screen().root] # should loop over all screens 89 | 90 | while len(wins) != 0: 91 | win = wins.pop(0) 92 | try: 93 | if self.check_window(win, pid, classname, not_classname, contains_title): 94 | return win.id 95 | 96 | subwins = win.query_tree().children 97 | if subwins != None: wins += subwins 98 | 99 | except (Xlib.error.BadWindow, TypeError): pass # catch the case of a not valid window or invalid reply 100 | except Xlib.error.ConnectionClosedError: break # connection closed, no need to continue to search the window 101 | return 0 102 | 103 | def register_window_callbacks(self): 104 | def event_loop(): 105 | # grab events 106 | self.display.screen().root.change_attributes(event_mask=Xlib.X.SubstructureNotifyMask) 107 | 108 | search_windows = True 109 | event = None 110 | 111 | while (self.kandinsky_window_id != -1 or 112 | (DISABLE_KANDINSKY_INPUT_ONLY and self.python_window_id != -1)): 113 | event = self.display.next_event() 114 | 115 | if event.type == Xlib.X.DestroyNotify: 116 | wid = event.window.id + 1 # idk why, i never the exact window id 117 | if wid == self.kandinsky_window_id: self.kandinsky_window_id = -1 118 | elif wid == self.python_window_id: self.python_window_id = -1 119 | 120 | if search_windows: 121 | self.bind_windows() 122 | if self.kandinsky_window_id and self.python_window_id: search_windows = False 123 | 124 | self.thread = Thread(name="WindowDestroyDetector", target=event_loop, daemon=True) 125 | self.thread.start() 126 | 127 | def get_kandinsky_window(self, wid=0): 128 | wid = super().get_kandinsky_window(wid) 129 | 130 | # In some linux distributions, Tkinter do not set window property '_NET_WM_PID'. 131 | # So try to find the window with a less reliable method. 132 | # EDIT: is in all linux distributions 133 | # EDIT2: Fixed in version 2.7.1 of kandinsky 134 | if not wid: wid = self.get_window(0, self.classnames[0], False, self.winname, wid) 135 | 136 | return wid 137 | 138 | def get_python_console_window(self, wid=0): 139 | # Check if is wayland because we cannot locate all windows due to "security reasons" 140 | if is_wayland and not self.kandinsky_not_found_error_printed: 141 | prettywarn("Wayland (used by most recent distributions) is not fully supported. " 142 | "The python console window will probably not be localized correctly. " 143 | "To avoid this problem, please restart your session in X11 mode.", UserWarning) 144 | 145 | return super().get_python_console_window(wid) 146 | 147 | def get_ppid(self, pid): 148 | # TODO: idk how to get this information better than that 149 | try: result = subprocess.check_output(f"ps -o ppid= {pid}".split(' ')).decode().strip() 150 | except subprocess.CalledProcessError: return -1 151 | 152 | # check the return value 153 | if not result: return -2 154 | try: return int(result) 155 | except ValueError: return -3 156 | 157 | def get_focussed_window(self): 158 | return self.display.screen().root.get_full_property(self.display.get_atom('_NET_ACTIVE_WINDOW'), Xlib.X.AnyPropertyType).value[0] 159 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------