~marnold128/magic-keyboard

8024a1307d3e62b61c4321572f7602b9abbe2f2c — Matt Arnold 2 months ago 331c54d
formating fixes mostly
5 files changed, 37 insertions(+), 42 deletions(-)

M mkd.py
M mkd/evdev.py
M mkd/fileutils.py
M mkd/misc.py
M mkd/statabuse.py
M mkd.py => mkd.py +17 -24
@@ 76,21 76,21 @@ def main():
        print("Config Syntax Error")
        exit(2)
    if cfig.get("layout_file"):
        status, errors  = read_script(cfig["layout_file"])
        status, errors = read_script(cfig["layout_file"])
        if status == 0:
        
            exec(compile(errors, "layout", 'exec'))

            exec(compile(errors, "layout", "exec"))
            print(vars)
            if 'mk_evread' in vars():
                dispatch_event = vars()['mk_evread']
            if "mk_evread" in vars():
                dispatch_event = vars()["mk_evread"]
            else:
                print("Script loader error revert")
                dispatch_event = default_evread 
                
                dispatch_event = default_evread

        else:
            print("Syntax error in script file\n" + errors)
            exit(status)
        

    else:
        print("layout file not found falling back to default")
        dispatch_event = default_evread


@@ 136,9 136,7 @@ def daemon_main(cfig):
    Notify.init("Magic Keyboard")
    active_config = cfig
    devices = [evdev.InputDevice(path) for path in evdev.list_devices()]
   
    
    

    if startup_proc(devices, active_config["grab_device"]):
        pidpath = os.path.expanduser("~/.mkd.pid")
        write_pid(pidpath)


@@ 159,21 157,19 @@ def daemon_main(cfig):
    lisnr.daemon = True
    vinput_t.daemon = True

    

    error_flag = 0
    while not stop_flag.is_set():
        script_context = ContextDict()
        script_context['evqueue'] = evqueue
        script_context['active_config'] = active_config
        script_context['send_notice'] = send_notice
        script_context["evqueue"] = evqueue
        script_context["active_config"] = active_config
        script_context["send_notice"] = send_notice
        if halt_in_progress.is_set():
            break
        if not lisnr.is_alive() and not halt_in_progress.is_set():
            lisnr.start()
        if not vinput_t.is_alive() and not halt_in_progress.is_set():
            vinput_t.start()
        

        ## Something is releasing grab, i can't figure out what
        ## py3-evdev doesn't provide EBUSY for iograbs
        ## so we make sure we are holding the grab before we read events


@@ 193,16 189,15 @@ def daemon_main(cfig):
        # Saint Thomas  is coming to town
        # he sees pids when they're sleeping
        # he knows they want to wake
        # he knows zombies are not good 
        # he knows zombies are not good
        # so a zombie let's not make
        try: 
        try:
            event = current_device.read_one()
        except OSError:
            sys.stderr.write("Lost Device")
            error_flag = 1
            break

        
        if event is not None:
            if event.type == ecodes.EV_KEY:
                dispatch_event(evdev.util.categorize(event), script_context)


@@ 221,12 216,12 @@ def daemon_main(cfig):
                    sys.stderr.write(str(e))
                    error_flag = 1
                    break
    

    if error_flag != 0:
        send_notice("breakout due to error, see log for more")
        halt_in_progress.set()
        stop_flag.set()
    

    send_notice("Shutting Down")
    Notify.uninit()
    vinput_t.join(5)


@@ 330,8 325,6 @@ def uds_thread(sock):
            connection.close()




def handle_sigterm(num, fr):
    global current_device
    halt_in_progress.set()

M mkd/evdev.py => mkd/evdev.py +1 -4
@@ 9,7 9,6 @@ from queue import Queue
from .misc import LostDeviceError



DOWN = 1
UP = 0
HOLD = 2


@@ 24,10 23,9 @@ STOCK_LEDS = [
]
from .misc import ContextDict


def default_evread(e: evdev.KeyEvent, ctx: ContextDict):

    
    
    if e.scancode == ecodes.KEY_UP:
        ctx.evqueue.put((ecodes.EV_KEY, ecodes.KEY_W, e.keystate))
    if e.scancode == ecodes.KEY_DOWN:


@@ 37,7 35,6 @@ def default_evread(e: evdev.KeyEvent, ctx: ContextDict):
    if e.scancode == ecodes.KEY_RIGHT:
        ctx.evqueue.put((ecodes.EV_KEY, ecodes.KEY_D, e.keystate))

    

## LED idle loop for anti cheat circumvention, and asthetics
## TODO: Make the time interval a gaussian distribution around mu of 0.25

M mkd/fileutils.py => mkd/fileutils.py +4 -3
@@ 40,17 40,18 @@ def get_config(U_path: str):
    else:
        return None


def read_script(u_path: str):

    with open(os.path.expanduser(u_path), "r") as f:
        code = f.read()
        

    try:
        ocode = compile(code, u_path, 'exec')
        ocode = compile(code, u_path, "exec")
        return 0, code
    except SyntaxError as e:
        return 1, str(e)
    except ValueError as e: 
    except ValueError as e:
        return 2, str(e)



M mkd/misc.py => mkd/misc.py +4 -2
@@ 2,14 2,16 @@
Misc objects that don't fall neatly into functional group yet
"""


class ContextDict(dict):
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__


def gaurd_call(ctx: callable, *args, **kwargs):
    try:
        ctx(args. kwargs)
        ctx(args.kwargs)
    except OSError as e:
        sys.stderr.write(str(e))
        return 1


@@ 21,4 23,4 @@ def gaurd_call(ctx: callable, *args, **kwargs):


class LostDeviceError(Exception):
    pass
\ No newline at end of file
    pass

M mkd/statabuse.py => mkd/statabuse.py +11 -9
@@ 11,37 11,39 @@ import math
import random
from enum import Enum


class Chaos(Enum):
    FAVOR = 1
    EVEN = 0
    UNLUCKY = -1


def calculate_clicks_persecond(mean_actions_per_min: int, odds: Chaos):
    """
    According to my research
    speed of input is messured in Actions per Minute by the gaming community
    Action refers to any action that the user performs. 
    Action refers to any action that the user performs.
    Like a mouse click or a key press. This is  a maddening imprecise unit as is.
    Add to that the articles i found cited no sources for the numbers they gave.

    This model makes *several* assumptions, which may not be accurate. Listed below
    

    * One action is one key press, mouse movement, or mouse click
    * actions per minute scores are Normally Distributed around their mean
        and a std div of about 25% of the mean. +/- three quaters of a percent
    * so to simulate human speeds we have to calculate the time delay, between 
    * so to simulate human speeds we have to calculate the time delay, between
        discrete key presses, following bell curve
    


    """
    if odds == Chaos.FAVOR:
        std_div = 25 + (random.randint(25, 75)/100)
        std_div = 25 + (random.randint(25, 75) / 100)
    elif odds == Chaos.EVEN:
        std_div = 25
    else: 
        std_div = 25 - (random.randint(25, 75)/100)
    else:
        std_div = 25 - (random.randint(25, 75) / 100)
    curve = random.gauss(mean_actions_per_min, std_div)
    if odds == Chaos.FAVOR:
        return math.ceil(curve)/60/60
        return math.ceil(curve) / 60 / 60
    else:
        return math.floor(curve)/60/60
        return math.floor(curve) / 60 / 60