def PlayFunc(bindings, recorded):
    if keyboard.is_pressed(',') == True and recorded != None:
        print("\nPlaying...")

        sharedData = multiprocessing.Queue()
        if isinstance(recorded[0], tuple):
            sharedData.put([
                keyboard.KeyboardEvent(x[0], x[1], x[6], x[2], x[3], x[5],
                                       x[4]) for x in recorded
            ])
        else:
            sharedData.put(recorded)

        p = multiprocessing.Process(target=PlayFromProcessQueue,
                                    args=(sharedData, ))
        p.start()
        time.sleep(1)
        print("Press [,] if would like stop playing recorded input...")
        while p.is_alive():
            if not sharedData.empty() and sharedData.get() == "stop":
                keyboard.unhook_all()
                p.terminate()
        p.join()
        time.sleep(1)

        ResetUserInput()

        ClearConsole()
        print("Done\n")
        ShowOptions(bindings, recorded)
예제 #2
0
async def record_keyboard(
    controller_state: ControllerState
):  #this method binds keyboard to conroller and records input for later playback
    if controller_state.get_controller() != Controller.PRO_CONTROLLER:
        raise ValueError('This script only works with the Pro Controller!')
    # waits until controller is fully connected
    await controller_state.connect()
    print('Using only letters and numbers, type a name for this recording')
    print('Then press <enter> to start recording keyboard control.')
    recordingName = await ainput(prompt='Recording name:')
    #pixels = neopixel.NeoPixel(board.D12, 6, auto_write=False)

    #button state handler callbacks
    savedRecordings = shelve.open('savedRecs', writeback=True)
    LeftStick = controller_state.l_stick_state
    RightStick = controller_state.r_stick_state
    bindKeyboard(controller_state)
    keyboard.start_recording()
    pixels.fill((0, 0, 0))
    pixels.fill((10, 0, 0))
    pixels.fill((10, 0, 0))
    await ainput(
        prompt='Press <enter> to stop recording and exit keyboard control.')
    recording = keyboard.stop_recording()
    pixels.fill((0, 0, 0))
    pixels.fill((0, 0, 0))

    keyboard.unhook_all()

    savedRecordings[recordingName] = recording
    savedRecordings.close()

    ControllerCLI._set_stick(RightStick, 'center', None)
    ControllerCLI._set_stick(LeftStick, 'center', None)
    await controller_state.send()
예제 #3
0
 def 停止引擎(self):
     self.取消监听大写锁定键()
     keyboard.unhook_all()
     self.setTerminationEnabled(True)
     self.terminate()
     print('引擎已停止\n\n')
     self.正在运行 = 0
예제 #4
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()
예제 #5
0
 def fire(self, new_value):
     '''
     Set <value> to <new_value>, unhooking hotkeys if this is "Exit".
     '''
     self.value = new_value
     if self.value == "Exit":
         keyboard.unhook_all()
예제 #6
0
 def pause(self):
     if self.paused:
         keyboard.unhook_all()
         self.start()
         self.gui_paused.setChecked(False)
         p = os.path.join(wd, './Compiled/active.png').replace('\\', '/')
         self.status_image.setStyleSheet(
             "background-image: url("
             + p
             + ");"
             + "background-repeat: no-repeat;"
             + "background-position: center;"
         )
     else:
         self.paused = True
         self.stop()
         keyboard.add_hotkey(
             self.settings.hotkeys['pause'], self.pause, suppress=True
         )
         self.gui_paused.setChecked(True)
         p = os.path.join(wd, './Compiled/inactive.png').replace('\\', '/')
         self.status_image.setStyleSheet(
             f"background-image: url("
             + p
             + ");"
             + "background-repeat: no-repeat;"
             + "background-position: center;"
         )
         [t.stop() for t in macros.timers]
         macros.timers = []
         macros.is_running = False
예제 #7
0
파일: engine.py 프로젝트: Wasymir/cpsfs
 def valid_fuel(self):
     if self.fuel <= 0:
         self.threading.stop_all()
         keyboard.unhook_all()
         os.system('cls')
         print("No Fuel".center(os.get_terminal_size()[0]))
         time.sleep(10)
def linux_keystroke_recorder():
    keyboard.hook(key_cb)
    while True:
        ch = sys.stdin.read(1)
        if ch == "q":
            keyboard.unhook_all()
            break
예제 #9
0
def main():
    keyboard.unhook_all()

    # Go to the Game
    #generic._set_focus()
    guard_dps = Guardian_DPS()
    #guard_aggro = Guardian_Aggro()
    #conq_dps = Conqueror_DPS()
    #conq_dps = Conqueror_DPS()
    #blank = Rotation()
    #blank.ability_list.append( TacticProvoke() )
    #blank.ability_list.append( TacticDefense() )
    # Set-up keyhooks
    try:
        hk2 = keyboard.add_hotkey('up', begin, args=[guard_dps, '-'])
        #hk3 = keyboard.add_hotkey('left', begin, args=[guard_aggro, '-'])
        #hk4 = keyboard.add_hotkey('right', do_rotation, args=[conq_dps, 79])
        #hk5 = keyboard.add_hotkey('down', do_rotation, args=[blank, 79])

        # keys = input()
        print("Press escape to exit.")
        keyboard.wait('escape')
    except Exception as e:
        print(e)
    finally:
        keyboard.unhook_all()
def stop_gethook():
    global script
    
    i = script
    keyboard.unhook_all()
    if actualLine is not None:
        i.append(actualLine)

    if output_log_file is not None:
        with open(output_log_file, "a") as af:
            af.write("{}]")
        if len(i) == 0:
            os.remove(output_log_file)
    if ducky_file is not None:
        with open(ducky_file, "w") as wf:
            for var in i:
                wf.write(var + "\n")
        if len(i) == 0:
            os.remove(ducky_file)
    
    with open("/tmp/.duckylog", "a") as af:
        af.write("{}]")
    x = output_log_file
    fromFile("/tmp/.duckylog", ducky_file)
    if x is not None:
        os.system("cp -f /tmp/.duckylog " + x)
    cleanup()
    return i
def key_events_callback(e):
    #for code in keyboard._pressed_events:
    #    print(code)
    k = list(keyboard._pressed_events.keys())
    # press q to unhook keyboard events
    if 16 in k:
        # stop the crazyflie flying
        cntr_object.keep_flying = False
        keyboard.unhook_all()
        
    # up key and not down key    
    if 72 in k and 80 not in k: # forward
        cntr_object.vector_x = 0.5
    elif  80 in k and 72 not in k: # back
        cntr_object.vector_x = -0.5
    else:
        cntr_object.vector_x = 0
    
    # left key and not right key
    if 75 in k and 77 not in k: # left
        cntr_object.vector_y = 0.5
    elif  77 in k and 75 not in k: # right
        cntr_object.vector_y = -0.5
    else:
        cntr_object.vector_y = 0
       
    # 'w' key and not 's' key
    if 17 in k and 31 not in k: #z up
        cntr_object.vector_z = 0.2
    elif  31 in k and 17 not in k: #z down
        cntr_object.vector_z = -0.2
    else:
        cntr_object.vector_z = 0
예제 #12
0
async def recording_playback(controller_state: ControllerState): #This method replays saved recordings
    if controller_state.get_controller() != Controller.PRO_CONTROLLER:
        raise ValueError('This script only works with the Pro Controller!')
    # waits until controller is fully connected
    await controller_state.connect()
    savedRecordings = shelve.open('savedRecs', writeback=True)
    LeftStick = controller_state.l_stick_state
    RightStick = controller_state.r_stick_state
    recList = list(savedRecordings.keys())
    print('Saved Recordings:')
    print(recList)
    print('Enter the name of the recording you want to playback')
    print('Then press <enter> to start playback.')
    recordingName = await ainput(prompt='Recording name:')
    if recordingName in recList:
        recording = savedRecordings[recordingName]
        speed_factor = 1
        last_time = None
        for event in recording:
            if speed_factor > 0 and last_time is not None:
                time.sleep((event.time - last_time) / speed_factor)
            last_time = event.time
            key = event.scan_code or event.name
            btnTrans = keyToConBtn(key)
            await directStateSet(btnTrans, controller_state) if event.event_type == keyboard.KEY_DOWN else  await directStateUNSet(btnTrans, controller_state)
        keyboard.unhook_all()
        ControllerCLI._set_stick(RightStick, 'center', None)
        ControllerCLI._set_stick(LeftStick, 'center', None)
        await controller_state.send()
    else:
        print('Recording name not recognized')
예제 #13
0
    def tearDown(self):
        self._rotation.do_terminate()

        if not self._rotation.stopped.wait(5):
            logging.error("Rotation was never brought down")

        keyboard.unhook_all()
예제 #14
0
 def up(event):
     #keyboard.send("backspace")
     print('up: {0}'.format(event.name))
     if (event.name == 'esc'):
         print('esc -- kill')
         keyboard.unhook_all()
         sys.exit()
예제 #15
0
def add_keyboard_hooks(keyboard_hooks):
    if sys.platform != "linux":
        import keyboard

        keyboard.unhook_all()
        for hotkey, func in keyboard_hooks.items():
            keyboard.add_hotkey(hotkey, func)
    def unregister_hotkeys(self, scope='', force=False):
        """Unregister hotkeys."""
        if not scope:
            for scope in self.hooked_keys:
                self.unregister_hotkeys(scope)
            if force:
                try:
                    keyboard.unhook_all()
                except Exception:
                    pass
            self.keyboard_state = dict()
        else:
            while self.hooked_keys[scope]:
                if scope == 'ctrlx':
                    try:
                        keyboard.remove_hotkey(self.hooked_keys[scope].pop())
                    except ValueError:
                        pass
                else:
                    try:
                        keyboard.unhook(self.hooked_keys[scope].pop())
                    except ValueError:
                        pass

            module_logger.info('Unregistered {} hotkeys.'.format(scope))
예제 #17
0
 def stop(self):
     with self._state_mutex:
         if self._state == AppState.Running:
             keyboard.unhook_all()
             self._client.stop()
             self._client_thread.join()
             self._logger.info('App stopped')
         self._state = AppState.Stopped
예제 #18
0
 def start(self):
     keyboard.wait('esc')
     mouse.on_click(self.add_mouse_left_click)
     keyboard.on_press(self.add_keypress)
     keyboard.wait('esc')
     mouse.unhook_all()
     keyboard.unhook_all()
     saver.save_file(self)
예제 #19
0
def stopHooks():
    """
	Removes keyboard hooks, stops listening. Pauses the program.
	"""
    kb.unhook_all()  # should do it, but it doesn't

    if config['printDebug']:
        printf("\nStopped all hooks/paused the program.")
예제 #20
0
파일: colsUI.py 프로젝트: pixelzery/cols
def quit():
    global quit_flag
    try:
        close()
        keyboard.unhook_all()
        print('Quit')
    finally:
        quit_flag = True
예제 #21
0
파일: engine.py 프로젝트: Wasymir/cpsfs
 def test_collision(self):
     if self.check_collision():
         self.threading.stop_all()
         keyboard.unhook_all()
         os.system('cls')
         print("You've crashed".center(os.get_terminal_size()[0]))
         time.sleep(10)
     time.sleep(0.1)
예제 #22
0
 def __toggle_keyboard(self):
     # register keyboard
     print("toggle keyboard:", self.use_keyboard.get())
     use = self.use_keyboard.get()
     if use:
         keyboard.add_hotkey('ctrl+f11', self.__take_screenshot)
     else:
         keyboard.unhook_all()
예제 #23
0
def unhook():
    try:
        global hook_status
        if hook_status:
            hook_status = False
            keyboard.unhook_all()
    except:
        return
예제 #24
0
    def _keyEvent(self, key):
        '''
		This method is the callback triggered if a key is pressed (if a scenario is provided).
		It calls the ``key`` method and pass a string as argument indicating the name of the pressed key.
		'''
        keyboard.unhook_all()
        self.key(key.name)
        keyboard.on_release(self._keyEvent)
예제 #25
0
def resetWasd(secondDuration):  #checks time passed and sends a message
    global timerCommandState
    global timerCommandName
    time.sleep(secondDuration)
    if timerCommandState == 1:
        keyboard.unhook_all()
        timerCommandState = 0
        chat(s, "The " + timerCommandName + " timer has ended.")
        timerCommandName = ""
예제 #26
0
 def verifPause(self):
     if self.status:
         self.status = False
         self.QBloqueia()
         self.QGrava(2)
     else:
         self.status = True
         key.unhook_all()
         print('desbloqueio')
예제 #27
0
def terminate_hotkey_hooks():
    """Release hotkey hooks for Freelancer. Should be run when, and only when, the Freelancer window is put into the
    background."""
    try:
        keyboard.remove_all_hotkeys()
    except AttributeError:
        pass  # a bug in keyboard (todo: submit PR)
    finally:
        keyboard.unhook_all()
예제 #28
0
def unlock():
    keyboard.unhook_all()
    listener.stop()

    q1.put("stop")
    q2.put("stop")

    print("[!] System unlocked")

    os._exit(0)
예제 #29
0
    def input_callback(self, key):
        if key.name == 'right':
            self.current_index += 1
            self.reload_text(self.current_index - 1)
            self.reload_text(self.current_index)
            if (self.current_index + 1) % self.options['max_num'] == 0:
                self.move_cursor(x=self.full_len *
                                 (self.options['max_num'] - 1) + 2,
                                 y=1)
            else:
                self.move_cursor(x=-self.full_len - 1)

        if key.name == 'left':
            self.current_index -= 1
            self.reload_text(self.current_index + 1)
            if (self.current_index + 2) % self.options['max_num'] == 0:
                self.move_cursor(x=self.full_len *
                                 (self.options['max_num'] - 2) + 1,
                                 y=1)
            elif (self.current_index + 1) % self.options['max_num'] == 0:
                self.move_cursor(x=self.full_len + 1, y=1)
            else:
                self.move_cursor(x=-self.full_len *
                                 (self.options['max_num'] - 1) - 2)
            self.reload_text(self.current_index)
            if (self.current_index + 1) % self.options['max_num'] == 0:
                self.move_cursor(x=self.full_len *
                                 (self.options['max_num'] - 1) + 2,
                                 y=1)
            else:
                self.move_cursor(x=-self.full_len - 1)

        if key.name == 'enter':
            current_column = ((self.current_index + 1) %
                              self.options['max_num'])
            current_row = (
                (self.current_index + 1) // self.options['max_num']) + 1
            self.move_cursor(x=-self.full_len * (current_column - 1) - 1,
                             y=self.rows % current_row)
            for _ in range(self.rows):
                sys.stdout.write('\033[K')
                self.move_cursor(y=-1)
            self.move_cursor(x=-self.full_len * self.rows, y=self.rows)
            keyboard.unhook_all()

            self.ctx.bot.paused = False
            try:
                import msvcrt
                while msvcrt.kbhit():
                    msvcrt.getch()
            except ImportError:
                import termios  #for linux/unix
                termios.tcflush(sys.stdin, termios.TCIOFLUSH)
            self.callback(self.ctx, self.items[self.current_index].strip())
예제 #30
0
 def read_keyboard(self, key):
     if key.name == "esc":
         self.game_on = False
     if key.name == "s":
         self.board.snake.go_down()
     if key.name == "w":
         self.board.snake.go_up()
     if key.name == "a":
         self.board.snake.go_left()
     if key.name == "d":
         self.board.snake.go_right()
     keyboard.unhook_all()
예제 #31
0
 def test_hook_nonblocking(self):
     self.i = 0
     def count(e):
         self.assertEqual(e.name, 'a')
         self.i += 1
     hook = keyboard.hook(count, suppress=False)
     self.do(d_a+u_a, d_a+u_a)
     self.assertEqual(self.i, 2)
     keyboard.unhook(hook)
     self.do(d_a+u_a, d_a+u_a)
     self.assertEqual(self.i, 2)
     keyboard.hook(count, suppress=False)
     self.do(d_a+u_a, d_a+u_a)
     self.assertEqual(self.i, 4)
     keyboard.unhook_all()
     self.do(d_a+u_a, d_a+u_a)
     self.assertEqual(self.i, 4)
예제 #32
0
 def test_hook_blocking(self):
     self.i = 0
     def count(e):
         self.assertIn(e.name, ['a', 'b'])
         self.i += 1
         return e.name == 'b'
     hook = keyboard.hook(count, suppress=True)
     self.do(d_a+d_b, d_b)
     self.assertEqual(self.i, 2)
     keyboard.unhook(hook)
     self.do(d_a+d_b, d_a+d_b)
     self.assertEqual(self.i, 2)
     keyboard.hook(count, suppress=True)
     self.do(d_a+d_b, d_b)
     self.assertEqual(self.i, 4)
     keyboard.unhook_all()
     self.do(d_a+d_b, d_a+d_b)
     self.assertEqual(self.i, 4)
예제 #33
0
 def tearDown(self):
     keyboard.unhook_all()
     # Make sure there's no spill over between tests.
     self.wait_for_events_queue()
예제 #34
0
 def tearDown(self):
     keyboard.unhook_all()