Exemplo n.º 1
0
 def cancel(event=None):
     nonlocal done
     self.reset_key.unbind("<Button-1>", click_id)
     self.reset_key.unbind("<FocusOut>", focus_id)
     keyboard.unhook(key_hook)
     self.reset_key.config(text=lastkey)
     done = "Cancel"
    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))
Exemplo n.º 3
0
def onKeyPress(key):
    global EscPressed, keysHooked
    if key.name == 'esc':
        EscPressed = True
        keyboard.unhook(onKeyPress)
        keysHooked = False
        return False  # stop listener
Exemplo n.º 4
0
    def _stop_recording(self):
        keyboard.unhook(self.keyboard_hook)
        mouse.unhook(self.mouse_hook)

        # Reset control flags
        self.keyboard_hook = None
        self.mouse_hook = None
        self.recording = False
Exemplo n.º 5
0
 def reset(self):
     self.canvas.reset()
     self.centers = {}
     self.selection = ''
     try:
         keyboard.unhook(self.keyboard_hook)
     except KeyError:
         pass
Exemplo n.º 6
0
 def _stop(self):
     controller = self.name.lower()
     if controller in ["mouse", "fare"]:
         mouse.unhook(self.add_event)
     elif controller in ["keyboard", "klavye"]:
         keyboard.unhook(self.add_event)
     else:
         raise ValueError(
             f"Hatalı değer: {controller} 'mouse' veya 'keyboard' olmalı")
Exemplo n.º 7
0
 def export(key):
     print("Exporting replay")
     file.pack_replay_file(
         recent,
         f"{user_name} - {level.creator_name} - {level.name}.gdr"
     )
     try:
         keyboard.unhook("f2")
     except KeyError:
         pass
Exemplo n.º 8
0
def record_both(button='esc'):
    print("recording")
    keyboard_record = []
    mouse_record = []
    keyboard.hook(keyboard_record.append)
    mouse.hook(mouse_record.append)
    keyboard.wait('esc')
    keyboard.unhook(keyboard_record.append)
    mouse.unhook(mouse_record.append)
    print("done!")
    return keyboard_record, mouse_record
Exemplo n.º 9
0
def toggleKeySound(_trayCall):
    global keySoundOn, icon
    keySoundOn = not keySoundOn
    if keySoundOn == True:
        keyboard.hook(onKeyPress)
        icon.icon = getOnIcon()
        playSound(hv.onEnableFile, _trayCall)
    else:
        keyboard.unhook(onKeyPress)
        icon.icon = getOffIcon()
        playSound(hv.onDisableFile, _trayCall)
    setIconMenu()
Exemplo n.º 10
0
def unlockAllWindows(*hooks):
    """
    Unhook the keyboard, reactivate the task manager and remove the fullscreen image
    Take the list of hooks in argument
    :return:
    """
    for hook in hooks:
        keyboard.unhook(hook)
    oKey = winreg.CreateKeyEx(
        winreg.HKEY_CURRENT_USER,
        'Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System', 0,
        winreg.KEY_SET_VALUE)
    winreg.SetValueEx(oKey, 'DisableTaskMgr', 0, winreg.REG_DWORD, 0)
    keyboard.send("esc")
Exemplo n.º 11
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)
Exemplo n.º 12
0
def record_keyboard(duration=5, filename='vpt-keyboard.json'):
    '''Record all keyboard events and save them to a json file
       Note that it currently blocks the main thread for the given duration.'''
    events = []

    def callback(event: keyboard.KeyboardEvent):
        events.append({
            'character': event.name,
            'key_code': event.scan_code,
            'time': event.time,
        })

    keyboard.hook(callback)
    time.sleep(duration)
    keyboard.unhook(callback)
    with open(filename, 'w') as file:
        json.dump(events, file, indent=4)
Exemplo n.º 13
0
    def _setupKeybinds(self):
        self.ctrlDown = False
        self.shiftDown = False

        if (self.prevKeyHook):
            keyboard.unhook(self.prevKeyHook)
        # threading.Thread(target=lambda:keyboard.hook(self.keyEvent, suppress=True), daemon=True).start()
        self.prevKeyHook = keyboard.hook(self.keyEvent, suppress=True)

        self.keybinds["f"] = self.doSearch

        self.keybinds["space"] = self.togglePlaying
        self.keybinds[","] = self.playPrev
        self.keybinds["."] = self.playNext
        self.keybinds["z"] = self.playPrev
        self.keybinds["x"] = self.playNext

        self.keybinds["-"] = self.decrementVolume
        self.keybinds["="] = self.incrementVolume

        self.keybinds["["] = self.decrementTime
        self.keybinds["]"] = self.incrementTime

        self.keybinds["0"] = lambda: self.seekPercent(0)
        self.keybinds["1"] = lambda: self.seekPercent(10)
        self.keybinds["2"] = lambda: self.seekPercent(20)
        self.keybinds["3"] = lambda: self.seekPercent(30)
        self.keybinds["4"] = lambda: self.seekPercent(40)
        self.keybinds["5"] = lambda: self.seekPercent(50)
        self.keybinds["6"] = lambda: self.seekPercent(60)
        self.keybinds["7"] = lambda: self.seekPercent(70)
        self.keybinds["8"] = lambda: self.seekPercent(80)
        self.keybinds["9"] = lambda: self.seekPercent(90)

        self.keybinds["a"] = self.toggleAutoplay
        self.keybinds["l"] = self.toggleLooping
        self.keybinds["c"] = self.clearQueue

        self.keybinds["q"] = self.doQuit
        self.keybinds["r"] = self.reboot
        self.keybinds["t"] = lambda: threading.Thread(
            target=lambda: osascript.run(
                f"return display alert \"Threads: {threading.active_count()}\""
            ),
            daemon=True).start()
Exemplo n.º 14
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)
Exemplo n.º 15
0
    def unregister_hotkeys(self, scope='', force=False):
        if not scope:
            for scope in self.hooked_keys:
                self.unregister_hotkeys(scope)
            if force:
                try:
                    keyboard.unhook_all()
                except AttributeError:
                    pass
            self.keyboard_state = dict()
        else:
            while self.hooked_keys[scope]:
                try:
                    keyboard.unhook(self.hooked_keys[scope].pop())
                except ValueError:
                    pass

            module_logger.info('Unregistered {} hotkeys.'.format(scope))
Exemplo n.º 16
0
def userActions(event):
    allEvents = mouseEvents + keyboardEvents
    sortedEvents = sorted(allEvents, key=lambda x: x[-1])
    finalEvents = filterEvents(mouseEvents)
    global kUnhooked
    global mouseClickLocations

    if keyboard.is_pressed('a'):
        document = None
        title = ''
        for item in finalEvents:
            if item == "OPEN PDF":
                document = openPDF()
            elif item == "COPY TITLE":
                title = getTitle(document)
            elif item == "PASTE TITLE":
                pasteTitle(title)
            elif item == "CLOSE PDF":
                closePDF()
    if keyboard.is_pressed('esc'):
        print("unhooking keyboard")
        keyboard.unhook(userActions)
        kUnhooked = True

        if kUnhooked and mUnhooked:
            endOrRestart()

    if keyboard.is_pressed('space'):
        for location in list(set(mouseClickLocations)):
            win32api.SetCursorPos((location[0], location[1]))
            document = None
            title = ''
            for item in finalEvents:
                if item == "OPEN PDF":
                    document = openPDF()
                elif item == "COPY TITLE":
                    title = getTitle(document)
                elif item == "PASTE TITLE":
                    pasteTitle(title)
                elif item == "CLOSE PDF":
                    closePDF()

        ### clear the mouseClickLocations
        mouseClickLocations = []
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 test_hook(self):
        self.i = 0

        def count(e):
            self.assertEqual(e.name, "a")
            self.i += 1

        keyboard.hook(count)
        self.click("a")
        self.assertEqual(self.i, 2)
        keyboard.hook(count)
        self.click("a")
        self.assertEqual(self.i, 6)
        keyboard.unhook(count)
        self.click("a")
        self.assertEqual(self.i, 8)
        keyboard.unhook(count)
        self.click("a")
        self.assertEqual(self.i, 8)
Exemplo n.º 19
0
    def test_hook(self):
        self.i = 0

        def count(e):
            self.assertEqual(e.name, 'a')
            self.i += 1

        keyboard.hook(count)
        self.click('a')
        self.assertEqual(self.i, 2)
        keyboard.hook(count)
        self.click('a')
        self.assertEqual(self.i, 6)
        keyboard.unhook(count)
        self.click('a')
        self.assertEqual(self.i, 8)
        keyboard.unhook(count)
        self.click('a')
        self.assertEqual(self.i, 8)
Exemplo n.º 20
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)
Exemplo n.º 21
0
    def __runLoop(self, icon):
        icon.visible = True
        ActorSystem().tell(self.dnaref, {
            "title": "KS Collector",
            "text": "Collector Enabled"
        })
        keyboard.hook(self.__key_press_handler)

        tnow = time.perf_counter()

        # Main Loop
        while not self.stop_event.isSet():
            tend = time.perf_counter()
            if (tend - tnow) > 15:
                for actor in self.actors:
                    ActorSystem().tell(actor["aref"],
                                       {"save": "{}_data".format(self.user)})
                    ActorSystem().tell(actor["aref"], {"stats": None})
                tnow = time.perf_counter()
            time.sleep(0.5)

        # Begin Clean Shutdown Procedure
        print("Shutting down...")
        ActorSystem().tell(self.dnaref, {
            "title": "KS Collector",
            "text": "Collector Shutting Down..."
        })
        keyboard.unhook(self.__key_press_handler)
        # Tell all the actors to save their current data
        for actor in self.actors:
            ActorSystem().tell(actor["aref"],
                               {"save": "{}_data".format(self.user)})
        time.sleep(3)  # Time to allow actors to save
        for actor in self.actors:
            ActorSystem().tell(
                actor["aref"],
                ActorExitRequest())  # Shutdown all actor threads
        ActorSystem().tell(self.dnaref, ActorExitRequest())

        print("Shutdown Complete...")

        icon.visible = False
        icon.stop()
Exemplo n.º 22
0
def OnKeyboardEvent(event):
    if keyboard.is_pressed('esc'):
        print("unhooking keyboard")
        keyboard.unhook(OnKeyboardEvent)
        global keyboardStatus
        keyboardStatus = True

        if (mouseStatus and keyboardStatus):
            MainLoop()

    elif type(
            event).__name__ == 'KeyboardEvent' and event.event_type == 'down':
        key = event.name
        eventType = 'down'
        window = GetWindowText(GetForegroundWindow())
        eventTime = event.time
        keyboardEvents.append(('key', key, eventType, window, eventTime))

    return True
Exemplo n.º 23
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)
Exemplo n.º 24
0
    def stop_event_recording(self, exceptionFlag=False):
        self.video_getter.stop()
        print("stopped screen_recorder")

        while self.frameExtractorDfIndexSeen != self.df.shape[0] - 1:
            time.sleep(0.1)
        print("line 133")
        self.frameExtractorStopped = True

        self.window_getter.stop()
        print("stopped window_getter")

        self.listener_mouse.stop()

        try:
            recorded_events_queue, hooked = keyboard._recording
            # print(recorded_events_queue, hooked)
            try:
                keyboard.unhook(hooked)
            except:
                # print("unable to call keyboard.unhook")
                pass

            rk = list(recorded_events_queue.queue)
            if not exceptionFlag:
                self.save_keyboard_events_to_df(rk)
        except:
            raise
        try:
            self.df = self.df.sort_values(by=["time"])
            print(self.df)
        except:
            pass

        if self.time_completed is not None:
            self.df = self.df[self.df.time < self.time_completed]
        self.df.to_csv("saved_snips_for_cliks/commands.csv")
        utils.add_windoInfo_and_save_image_from_timer_csv()
        print("STOPPED THE PROCESS")
        print("SUCCESSFULLY")
        self.MAIN_PROCESS_RUNNING_FLAG = False
Exemplo n.º 25
0
def enter_change_mode(from_hotkey=False):
    global in_change_mode

    if from_hotkey:
        keyboard.release(RELEASE_KEY)

    if curr_layout:
        keyboard.unhook(curr_layout)
        print("Normal keyboard.")

    if in_change_mode:
        in_change_mode = False
        keyboard.unhook(change_mode)
        return

    else:
        in_change_mode = True
        keyboard.hook(change_mode, suppress=True)
        change_to = ""
        print("Type layout name/command: ", end="", flush=True)
        return
Exemplo n.º 26
0
def record():

    recorded = queue.Queue()
    m_button_state = checkMouseState(
        0x04)  # middle button down = 0 or 1. Button up = -127 or -128
    macroStart = False

    print('press middle btn to start recording')
    while not macroStart:
        new_m_button_state = checkMouseState(0x04)
        if new_m_button_state != m_button_state:
            m_button_state = new_m_button_state

            if new_m_button_state == '':

                print('Macro Recording ...')
                macroStart = True

    # global mouse 이벤트를 후킹
    mo.hook(recorded.put)
    # global Keyboard 이벤트를 후킹
    keyHooked = key.hook(recorded.put)

    until = False
    while not until:
        new_m_button_state = checkMouseState(0x04)
        if new_m_button_state != m_button_state:
            m_button_state = new_m_button_state
            if new_m_button_state == '':
                print('Macro Recording End')
                until = True

    # 후킹 종료
    mo.unhook(recorded.put)
    key.unhook(keyHooked)

    #return_list = [mo_first_pos] + list(recorded.queue)
    return_list = list(recorded.queue)
    return return_list
Exemplo n.º 27
0
    def loop(self):
        """a
        F10 to start recording
        F10 again to end recording
        :return:
        """
        while True:
            keyboard.wait("ctrl + F10")  # Waiting for 'F10' to be pressed
            self.begin()
            self.events = [
            ]  # This is the list where all the events will be stored
            mouse.hook(self.record_mouse)  # starting the mouse recording
            keyboard.hook(self.record_keyboard)  # starting the mouse recording
            keyboard.wait("ctrl + F10")  # Waiting for 'a' to be pressed
            mouse.unhook(self.record_mouse)  # Stopping the mouse recording
            keyboard.unhook(
                self.record_keyboard)  # starting the mouse recording
            self.end()


#
#
# a = ActionRecorder()
# a.loop()
Exemplo n.º 28
0
 def 取消监听大写锁定键(self):
     try:
         keyboard.unhook('caps lock')
     except:
         pass
Exemplo n.º 29
0
 def resetKeyboardHook(self):
     try:
         keyboard.unhook(self.keyCheck)
     except:
         pass
     keyboard.hook(self.keyCheck)
Exemplo n.º 30
0
 def back(key):
     try:
         keyboard.unhook("f2")
     except KeyError:
         if not playing_replay:
             pass
Exemplo n.º 31
0
 def unhook_keyboard(self):
     if self.hook:
         keyboard.unhook(self.hook)
         self.hook = None
Exemplo n.º 32
0
 def unhook(self):
     import keyboard
     try:
         keyboard.unhook(self.hooked)
     except KeyError:
         pass
Exemplo n.º 33
0
 def __exit__(self, _, __, ___):
     kb.unhook(self.hook_returned)
     self.holdKeyContext = self.notReady