Exemplo n.º 1
0
    def __init__(self,
                 func: callable,
                 quit_key: str = 'ctrl+q',
                 pause_key: str = 'ctrl+p'):
        self.main_loop_thread = None
        self.main_loop_thread_exc = None

        self.func = func

        self.quit_key = quit_key
        self.pause_key = pause_key

        self.pause = Event()
        self._exit = False

        # remove previous hotkeys to prevent multiple of those in case of a restart
        try:
            keyboard.unhook_all_hotkeys()
        except AttributeError:
            pass

        keyboard.add_hotkey(quit_key, lambda: self.exit())
        keyboard.add_hotkey(pause_key, lambda: self.pause_or_resume())

        # start
        self.pause.set()
Exemplo n.º 2
0
def main():
    global options, page

    path = "C:\\Users\\danie\\Documents\\AutoInterface\\scripts"

    options = get_list(path)
    folders[""] = options

    show_options(options, page)
    print("press option: ")

    keyboard.add_hotkey('f', nextpage, suppress=True)
    keyboard.add_hotkey('a', prevpage, suppress=True)
    keyboard.add_hotkey('b', home_folder, suppress=True)

    for i in range(-1, 9):
        keyboard.add_hotkey(str(i + 1),
                            push_command,
                            args=[i + 1],
                            suppress=True)

    keyboard.wait('esc')

    keyboard.unhook_all()
    keyboard.unhook_all_hotkeys()
Exemplo n.º 3
0
def heroKeyBind(count, name):
    keyboard.unhook_all_hotkeys()
    for i in range(count):
        for extra_key in key_list:
            keyboard.add_hotkey('Ctrl + {}{}'.format(i, extra_key),
                                lambda i=i: threading.Thread(
                                    target=heroSound, args=(name, i)).start())
Exemplo n.º 4
0
 def _selectHK3(self):
     print("_selectHK3")
     hkey = keyboard.read_hotkey()
     print("_selectHK3: hkey", hkey)
     self.config['Capture']['Hotkey AWindow'] = hkey
     self.saveini()
     self.hk3txt.set(self.config['Capture']['Hotkey AWindow'])
     keyboard.unhook_all_hotkeys()
Exemplo n.º 5
0
 def _selectHK2(self):
     print("_selectHK2")
     hkey = keyboard.read_hotkey()
     print("_selectHK2: hkey", hkey)
     self.config['Capture']['Hotkey FullScr'] = hkey
     self.saveini()
     self.hk2txt.set(self.config['Capture']['Hotkey FullScr'])
     keyboard.unhook_all_hotkeys()
Exemplo n.º 6
0
 def _selectHK1(self):
     print("_selectHK1")
     # self.hk1txt.set("<Press HotKey>")
     hkey = keyboard.read_hotkey()
     print("_selectHK1: hkey", hkey)
     self.config['Capture']['Hotkey Return'] = hkey
     self.saveini()
     self.hk1txt.set(self.config['Capture']['Hotkey Return'])
     keyboard.unhook_all_hotkeys()
Exemplo n.º 7
0
def start_client(name, ip, port):
    Running = Bucket(1)

    hotkey_to_mute = read_str('client-hotkey-to-mute.txt')
    hotkey_to_unmute = read_str('client-hotkey-to-unmute.txt')

    s = socket.socket()
    print(f'connecting to: {name}@{ip}#{port}')
    try:
        s.connect((ip, port))
    except TimeoutError:
        print('computer is on, but doesnt respond')
        return
    except KeyboardInterrupt:
        return
    except socket.gaierror:
        print('invalid ip')
        return

    thread_counter = Bucket(0)
    user_is_muted = Bucket(0)

    args = (Running, s)
    thr(play_recived_audio, args, thread_counter)
    thr(send_recorded_audio, args + (user_is_muted, ), thread_counter)
    print('connected')

    def on_mute(muted):
        muted.new(1)
        print('muted')

    def on_unmute(muted):
        muted.new(0)
        print('unmuted')

    #hotkeys = []
    #hotkeys.append (keyboard.add_hotkey( hotkey_to_mute, lambda:on_mute(user_is_muted) ))
    #hotkeys.append (keyboard.add_hotkey( hotkey_to_unmute, lambda:on_unmute(user_is_muted) ))
    keyboard.add_hotkey(hotkey_to_mute, lambda: on_mute(user_is_muted))
    keyboard.add_hotkey(hotkey_to_unmute, lambda: on_unmute(user_is_muted))

    try:
        while Running:
            sleep(50)
    except KeyboardInterrupt:
        pass

    #for hotkey in hotkeys:
    #	keyboard.remove_hotkey(hotkey)
    keyboard.unhook_all_hotkeys()
    print('hotkeys fixed')

    stop_client(Running, s)

    wait_for_the_end(thread_counter)
    print('END')
Exemplo n.º 8
0
 def destroy_img(self, openimg, file):
     print("into destroy img")
     openimg.terminate()
     openimg.kill()
     try:
         os.remove(file)
     except:
         pass
     keyboard.unhook_all_hotkeys()
     keyboard.add_hotkey(self.hotkey, self.capture, args=())
Exemplo n.º 9
0
def GetRoll():
    kb.add_hotkey(
        'r',
        AddToRoll)  # Calls the AddToRoll method when user presses the 'r' key
    for i in range(dice):
        print(('| Press \'r\' to roll die #' + str(i + 1) +
               '. (Don\'t hit enter)').ljust(pad_amount, ' ') + '|')
        kb.wait('r')  # Halts the program until the user rolls
        kb.send('del')  # Deletes the r the user typed
    kb.unhook_all_hotkeys()  # Stops listening for keystrokes
 def set_mode(self, mode):
     try:
         self.current_mode = list_modes[int(mode)]
         keyboard.unhook_all_hotkeys()
         if int(mode) == 1:
             self.init_move()
         else:
             self.init_pump()
     except KeyError:
         print("Invalid command! select a mode with keys [1,2 or 3] ")
Exemplo n.º 11
0
def KBinput(
    title, lcd
):  #gets a number by keyboard input, live input and title are displayed on the LCD.

    #use global variables:
    global InputString
    global available

    lcd.display_string(title, 1)  #write title to first line of LCD

    keyboard.unhook_all_hotkeys()  #stop listening to any previous hotkeys

    #attach InputNumber function to all number keys
    keyboard.on_press_key("0", InputNumber)
    keyboard.on_press_key("1", InputNumber)
    keyboard.on_press_key("2", InputNumber)
    keyboard.on_press_key("3", InputNumber)
    keyboard.on_press_key("4", InputNumber)
    keyboard.on_press_key("5", InputNumber)
    keyboard.on_press_key("6", InputNumber)
    keyboard.on_press_key("7", InputNumber)
    keyboard.on_press_key("8", InputNumber)
    keyboard.on_press_key("9", InputNumber)
    keyboard.on_press_key("num lock", InputNumber)
    keyboard.on_press_key("enter", InputNumber)
    keyboard.on_press_key("backspace", InputNumber)

    while 1:  #wait for end of input

        if available:
            if InputString != "":  #a number has been typed

                lcd.clear()
                keyboard.unhook_all()  #stop listening to number keys
                out = InputString  #store input string
                InputString = ""  #reset InputString variable for next input
                available = False  #reset state variable

                return (out)  #return result, end function

            else:  #no number has been typed
                #display error message, reset state variable, then continue as before
                lcd.display_string("Bitte gueltige", 1)
                lcd.display_string("Zahl eingeben!", 2)
                time.sleep(0.75)
                available = False

        #update LCD with currently typed numbers and title of Input
        lcd.clear()
        if InputString != -1:
            lcd.display_string(title, 1)
            lcd.display_string(InputString, 2)
            time.sleep(0.2)
Exemplo n.º 12
0
def registe_click_pop_cart_hotkey(hotkey='alt+c',
                                  callback=_registed_click_pop_cart):
    k = U.get(hotkey)
    # if k:
    # print(U.stime(),'using registed hotkey',hotkey)
    # return k
    import keyboard

    keyboard.unhook_all_hotkeys()  #

    k = keyboard.add_hotkey(hotkey, callback)
    return hotkey, U.set(hotkey, k), id(k)
    def hook_callback(self, *args):
        #print((name,scan_code,time))
        #print("event.name:",event.name, "\t\t\t\t",event.scan_code, event.time)
        #print(dir(args))
        #print(args[0].event_type)

        if self.wait_for_keypress:
            event = args[0]
            if event.event_type == "down":
                # keypress done!
                self.measurements[-1]["key_pressed_at"] = time.time()
                self.measurements[-1]["reaction_time"] = self.measurements[-1][
                    "key_pressed_at"] - self.measurements[-1]["shown_at"]
                self.wait_for_keypress = False

                self.counter += 1

                if self.counter > self.num_measurements:  #finish if counter exceeded planned measurements amount
                    print("Unhooking ... ")
                    keyboard.unhook_all()
                    keyboard.unhook_all_hotkeys()
                    num_files = len(os.listdir())

                    #print(self.measurements[:-1])
                    reaction_times = [
                        measurement['reaction_time']
                        for measurement in self.measurements[:-1]
                    ]
                    reaction_time_min = min(reaction_times)
                    reaction_time_max = max(reaction_times)
                    reaction_time_avg = sum(reaction_times) / len(
                        self.measurements[:-1])

                    with open("measurement_" + str(num_files + 1) + ".txt",
                              "a+") as report:
                        report.write(time.ctime() + "\n")
                        report.write(self.signal_info + "\n")
                        report.write("reaction_time_min:\t" +
                                     str(reaction_time_min) + "\n")
                        report.write("reaction_time_max:\t" +
                                     str(reaction_time_max) + "\n")
                        report.write("reaction_time_avg:\t" +
                                     str(reaction_time_avg) + "\n")
                        report.write("### DATA: ###\n")
                        for item in self.measurements[:-1]:  #drop last record
                            for k, v in item.items():
                                report.write(str(k) + "\t" + str(v))
                                report.write("\n")
                            report.write("\n")
                        report.write("#" * 12 + "\n")
                    self.close()
                else:
                    self.new_measurement()
Exemplo n.º 14
0
    def capture(self):
        if self.setting_frame_combo_box.get() == '':
            monitor = self.sct.monitors[int(self.screen)]
        else:
            monitor = self.sct.monitors[int(
                self.setting_frame_combo_box.get())]
        sct_img = self.sct.grab(monitor)
        im = Image.frombytes("RGB", sct_img.size, sct_img.bgra, "raw", "BGRX")
        im = im.transpose(Image.FLIP_LEFT_RIGHT)
        print("to here")
        im.save('Mirrored.png')
        path = os.path.join(os.getcwd(), "Mirrored.png")
        openimg = None

        if sys.platform == "win32":
            openimg = subprocess.Popen(
                ["rundll32.exe", "shimgvw.dll,ImageView_Fullscreen", path])
        ### NEED FIXING
        elif sys.platform == "darwin":
            with open(path, "r") as f:
                openimg = subprocess.Popen(
                    [
                        "im=$(cat); open -a Preview.app $im; sleep 20; rm -f $im"
                    ],
                    shell=True,
                    stdin=f,
                )
        ### NEED FIXING
        else:
            with open(path, "r") as f:
                if shutil.which("display"):
                    openimg = subprocess.Popen(
                        ["im=$(cat);" + "display" + " $im; rm -f $im"],
                        shell=True,
                        stdin=f)
                if shutil.which("eog"):
                    openimg = subprocess.Popen(
                        ["im=$(cat);" + "eog" + " $im; rm -f $im"],
                        shell=True,
                        stdin=f)
                if shutil.which("xv"):
                    openimg = subprocess.Popen(
                        ["im=$(cat);" + "xv" + " $im; rm -f $im"],
                        shell=True,
                        stdin=f)

        keyboard.unhook_all_hotkeys()
        keyboard.add_hotkey(self.hotkey,
                            self.destroy_img,
                            args=(openimg, path))
Exemplo n.º 15
0
 def reload_binds(self):
     """
     Reloads binds from the default file into the program
     """
     logging.info("Attempting to reload keybinds")
     self.binds = self.load_binds("binds.csv")
     self.wait_thread_active = False
     keyboard.unhook_all_hotkeys()
     self.wait_thread = threading.Thread(target=self.start_wait_thread,
                                         args=(
                                             self.plugins,
                                             self.binds,
                                         ),
                                         daemon=True).start()
     self.wait_thread_active = True
Exemplo n.º 16
0
 def set_hotkey2(self, event):
     event.widget.config(state=NORMAL)
     event.widget.delete(0, END)
     try:
         keyboard.unhook_all_hotkeys()
     except:
         pass
     self.hotkey = keyboard.read_hotkey()
     keyboard.stash_state()
     keyboard.add_hotkey(self.hotkey, self.capture, args=())
     self.write_file()
     self.start_frame_label_2['text'] = self.hotkey.upper()
     event.widget.delete(0, END)
     event.widget.insert(0, self.hotkey.upper())
     event.widget.config(state=DISABLED)
     self.calculate_width()
Exemplo n.º 17
0
    def __init__(self):
        super().__init__()
        self.time_completed = None
        print("starting time: ", time.time())
        self.window_getter = WindowInfoGetter().start()
        # self.screen_recorder = ScreenRecorder().start()
        self.video_getter = VideoGet().start()
        self.df = pd.DataFrame()
        self.listener_mouse = mouse.Listener(on_move=self.on_move,
                                             on_click=self.on_click,
                                             on_scroll=self.on_scroll,
                                             suppress=False)
        self.listener_mouse.start()
        self.LEFT_KEY_PRESSED_FLAG = False
        self.SCREEN_WIDTH, self.SCREEN_HEIGHT = auto.size()

        try:
            recorded_events_queue, hooked = keyboard._recording
            keyboard.unhook(hooked)
            keyboard.unhook_all_hotkeys()
        except:
            pass

        try:
            keyboard.add_hotkey('Esc+q', self.endProgram, suppress=True)
            keyboard.start_recording()  # Don't put anythiing below this line
        except:
            recorded_events_queue, hooked = keyboard._recording
            try:
                keyboard.unhook(hooked)
                print("unhooked")
            except:
                print("unable to call keyboard.unhook")
                pass

            self.stop_event_recording(exceptionFlag=True)

        self.MAIN_PROCESS_RUNNING_FLAG = True
        # variables related to frameExtractor
        self.frameExtractorStopped = False
        self.frameExtractorDfIndexSeen = 0
        Thread(target=self.frameExtractor, args=(), daemon=True).start()
        print("completed init")
Exemplo n.º 18
0
def deactivate():
    try:
        kb.unhook_all_hotkeys()
    except:
        pass

    try:
        active_square['state'] = 'normal'
        active_square.note_button0.destroy()
        active_square.note_button1.destroy()
        active_square.note_button2.destroy()
        active_square.note_button3.destroy()
        active_square.note_button4.destroy()
        active_square.note_button5.destroy()
        active_square.note_button6.destroy()
        active_square.note_button7.destroy()
        active_square.note_button8.destroy()
    except:
        pass
Exemplo n.º 19
0
    async def run(self,
                  server_class=HTTPServer,
                  handler_class=Server,
                  port=3000):
        await self.bot.wait_until_ready()
        server_address = ('', port)
        httpd = server_class(server_address, handler_class)

        httpd.socket.settimeout(1)

        print('Launched Dota GSI')
        enabled_first_time = False
        while True:
            httpd.handle_request()
            if DotaGSI.dmap is not None:
                DotaGSI.des_map = Map(DotaGSI.dmap)
                if not enabled_first_time:
                    enabled_first_time = True
                    print('adding hotkeys')
                    keyboard.add_hotkey('shift+k',
                                        Map.rosh_is_killed,
                                        args=[self.bot])
                    keyboard.add_hotkey('shift+c',
                                        Map.time_before_aegis_expires,
                                        args=[self.bot])
                    keyboard.add_hotkey('shift+l',
                                        Map.disable_roshan_timer,
                                        args=[self.bot])
                    keyboard.add_hotkey('shift+v',
                                        Map.time_before_roshan_respawns,
                                        args=[self.bot])

                await DotaGSI.des_map.manage_runes_warning(self.bot)
                await DotaGSI.des_map.manage_pause(self.bot)
                await DotaGSI.des_map.manage_roshan_timing(self.bot)
            else:
                if enabled_first_time:
                    keyboard.unhook_all_hotkeys()
                    enabled_first_time = False

            await asyncio.sleep(1)
Exemplo n.º 20
0
 def onQuit(self):
     """退出函数"""
     keyboard.unhook_all_hotkeys()  # 取消所有热键
     QApplication.instance().quit()
Exemplo n.º 21
0
Arquivo: Run.py Projeto: kc0zhq/rxbot3
if SHUFFLE_ON_START == True: #Playlist Shuffler
    db = sqlite3.connect('songqueue.db')
    cursor = db.cursor()
    cursor.execute('''SELECT * FROM playlist ORDER BY RANDOM()''')
    listSongs = cursor.fetchall()
    shuffle(listSongs)
    sqlcommand = '''DELETE FROM playlist'''
    cursor.execute(sqlcommand)
    for item in listSongs:
        cursor.execute('''INSERT INTO playlist(song, key) VALUES("{song_name}", "{key}");'''.format(song_name=item[1], key=item[2]))
    db.commit()
    db.close()
    print(">> Backup Playlist has been shuffled.")
if ENABLE_HOTKEYS:
    keyboard.add_hotkey(HK_VOLUP, srcontrol.volumeup, args=(None, None))
    keyboard.unhook_all_hotkeys() #Currently the best way to allow the hotkeys access to the p. class is to redefine them every time a new song is played.
    keyboard.add_hotkey(HK_VOLUP, srcontrol.volumeup, args=(None, None))
    keyboard.add_hotkey(HK_VOLDN, srcontrol.volumedown, args=(None, None))
    keyboard.add_hotkey(HK_PAUSE, togglepause)
    keyboard.add_hotkey(HK_VETO, veto, args=(None, None))
    keyboard.add_hotkey(HK_CLRSONG, sendMessage, args=(s, sr.clearsong(None, "STREAMER")))

'''END INIT'''



def getUser(line):
    seperate = line.split(":", 2)
    user = seperate[1].split("!", 1)[0]
    return user
Exemplo n.º 22
0
def teardown ():

    keyboard.unhook_all_hotkeys()
Exemplo n.º 23
0
def shutdown():

    keyboard.unhook_all_hotkeys()
    exit()
Exemplo n.º 24
0
 def quit(self):
     "保险起见,为了完整的退出"
     keyboard.unhook_all_hotkeys()
     self.setVisible(False)
     qApp.quit()
     sys.exit()
Exemplo n.º 25
0
 def closeEvent(self, event):
     self.keeper.server.stop_heartbeat()
     keyboard.unhook_all_hotkeys()
Exemplo n.º 26
0
def toDo():
    global selected
    global submenu
    global control

    if control: 
        r_menu()
        control = False
        return
    clear()

    keyboard.unhook_all_hotkeys()
    input()

    if submenu == 0:
        if selected == 1: 
            selected = 1
            submenu = 1
            show_sm1()
        elif selected == 2: 
            selected = 1
            submenu = 2
            show_sm2()

        elif selected == 3: 
            selected = 1
            submenu = 3
            show_sm3()

        elif selected == 4: 
            selected = 1
            submenu = 4
            show_sm4()
        elif selected == 5:
            selected = 1
            submenu = 0
            show_menu()

    elif submenu == 1:
        control = True
        if selected == 1: 
            ac.ver(True, False)
        elif selected == 2: 
            ac.ver(True, True)
        elif selected == 3: 
            ac.ver(False, False)
        elif selected == 4: 
            ac.ver(False, False)
        os.system("pause")

    elif submenu == 2:
        control = True
        if selected == 1: 
            ac.insertar(True)
        elif selected == 2: 
            ac.insertar(False)
        elif selected == 3: 
            while True:
                p = input(c.Fore.CYAN + "¿Cuántos profesores? \n")
                print("")
                a = input(c.Fore.CYAN + "¿Cuántos alumnos? \n")
                try:
                    p = int(p)
                    a = int(a)
                    break
                except: print(c.Fore.YELLOW + "Formato incorrecto, intente otra vez")
            ac.gen_a_lot(p, a)
            #try:
               # ac.gen_a_lot(p, a)
            #except: print(c.Fore.RED + "Un error ha suscedido, cancelando...")
        os.system("pause")
    
    elif submenu == 3:
        control = True
        if selected == 1: 
            ac.borrar(True)
        elif selected == 2: 
            ac.borrar(False)
        elif selected == 3: 
            ac.reset_database()
        os.system("pause")

    elif submenu == 4:
        control = True
        if selected == 1: 
            ac.modificar(True)
        elif selected == 2: 
            ac.modificar(False)
        os.system("pause")
        
    
    basic()
Exemplo n.º 27
0
 def endProgram():
     keyboard.unhook_all_hotkeys()
     print('Ending program in between')
     os._exit(0)
Exemplo n.º 28
0
 def on_terminate_signal(self):
     self.process = None
     self.enable_ui(True)
     keyboard.unhook_all_hotkeys()
     self.sb_print('Terminated')
Exemplo n.º 29
0
def update_hotkeys():
    keyboard.unhook_all_hotkeys()
    config_hotkeys()
Exemplo n.º 30
0
            key = spec[key_color]
            keyboard.send(key)


def start_key(key1, key2):  #hotkey config
    keyboard.add_hotkey(key1,
                        single_press,
                        suppress=False,
                        timeout=0.1,
                        trigger_on_release=False)
    keyboard.add_hotkey(key2,
                        aoe_press,
                        suppress=False,
                        timeout=0.1,
                        trigger_on_release=False)


config_open()
while True:
    a = 0
    if a == 0:  #start recive from socket
        start_key(config['single_key'], config['aoe_key'])
        a = 1
    message = socket.recv()
    if message == 'reset':  #reset config, and start new recive cycle
        a = 0
        keyboard.unhook_all_hotkeys()
        config_open()
    else:
        pass