def __exit__(self, _, __, ___): kb.release(self.key_name) kb.unhook_key(self.key_name) for _ in range(self.status): kb.press(self.key_name) for _ in range(-self.status): kb.release(self.key_name)
def play_file(filename, playpause_key=None, delete_mp3=True): # Проверяем существование файлика if os.path.exists(filename): # Подгружаем в плеер и запускаем mixer.music.load(filename) mixer.music.play() # Событие по завершению аудиодорожки mixer.music.set_endevent(SONG_END) # Переменная для цикла is_music_over = False # Play/Пауза pause_key_hook = None if (playpause_key != None): pause_key_hook = keyboard.hook_key(playpause_key, on_pause_down) print(f"hook added on key {playpause_key}") # Ждём... while not is_music_over: # Если вдруг в событиях обнаружится, что... for event in pygame.event.get(): # ... песня закончилась, то ... if event.type == SONG_END: # записываем это и завершаем цикл is_music_over = True time.sleep(0.01) # Останавливаем if (pause_key_hook != None): keyboard.unhook_key(pause_key_hook) print("hook removed") mixer.music.stop() time.sleep(0.01) # Удаляем файл по окончанию, если надо if (delete_mp3) and (os.path.exists(filename)): os.remove(filename) time.sleep(0.01)
def return_callback(event): global init_done, calibration_done # ignore space keystroke when not asked to if not init_done: return calibration_done = True keyboard.unhook_key('space')
def capture_input_select(self, box, card): """ responsible for menu input captures :param box: specifies the box options to be passed to callback """ key_a = keyboard.on_press_key( "a", lambda e: self.draw_selection("a", box, card)) key_d = keyboard.on_press_key( "d", lambda e: self.draw_selection("d", box, card)) keyboard.wait(" ") keyboard.unhook_key(key_a) keyboard.unhook_key(key_d) self.draw_selection(key=" ", box_options=box)
def deregister_hotkey(self): """Remove any other action that currently has this hotkey""" try: if self.modifier: keyboard.remove_hotkey(self.modifier + '+' + self.hotkey) _hotkey = self.modifier + '+' + self.hotkey else: keyboard.unhook_key(self.hotkey, ) _hotkey = self.hotkey except Exception as e: return logging.debug("Hotkey {} de-registered for {}".format(_hotkey, \ self.name))
def test_hook_key_nonblocking(self): self.i = 0 def count(event): self.i += 1 hook = keyboard.hook_key('A', count) self.do(d_a) self.assertEqual(self.i, 1) self.do(u_a+d_b) self.assertEqual(self.i, 2) self.do([make_event(KEY_DOWN, 'A', -1)]) self.assertEqual(self.i, 3) keyboard.unhook_key(hook) self.do(d_a) self.assertEqual(self.i, 3)
def test_hook_key_blocking(self): self.i = 0 def count(event): self.i += 1 return event.scan_code == 1 hook = keyboard.hook_key('A', count, suppress=True) self.do(d_a, d_a) self.assertEqual(self.i, 1) self.do(u_a+d_b, u_a+d_b) self.assertEqual(self.i, 2) self.do([make_event(KEY_DOWN, 'A', -1)], []) self.assertEqual(self.i, 3) keyboard.unhook_key(hook) self.do([make_event(KEY_DOWN, 'A', -1)], [make_event(KEY_DOWN, 'A', -1)]) self.assertEqual(self.i, 3)
def callback(hotkey): # try to remove the previously set hotkey if there is one. try: keyboard.unhook_key(hotkey) # KeyError was coming up when loading the program and # the lineEdit area was empty (no hotkey set), then you # set one, reload the setting once back to blank works, # but if you click reload settings again, it errors # we can just have it pass, but don't want to throw in # generic exception here in case another one of these # pops up somewhere. except (AttributeError, KeyError): pass # wait until user presses the hotkey, then keyboard module reads the input key_name = __get_key_name(keyboard.read_event(True)) try: # If the key the user presses is equal to itself or another hotkey already set, # this causes issues. so here, it catches that, and will make no changes to the hotkey. # or # keyboard module allows you to hit multiple keys for a hotkey. they are joined # together by +. If user hits two keys at the same time, make no changes to the # hotkey. A try and except is needed if a hotkey hasn't been set yet. I'm not # allowing for these multiple-key hotkeys because it can cause crashes, and # not many people are going to really use or need this. if __is_key_already_set(self, key_name) or (key_name != '+' and '+' in key_name): self.afterSettingHotkeySignal.emit() return except AttributeError: self.afterSettingHotkeySignal.emit() return # add the key as the hotkey, set the text into the LineEdit, set it as old_xxx_key, # then emite a signal to re-enable some buttons and change some text in GUI. # We need to inspect the event to know if it comes from numpad because of _canonial_names. # See: https://github.com/boppreh/keyboard/issues/161#issuecomment-386825737 # The best way to achieve this is make our own hotkey handling on top of hook # See: https://github.com/boppreh/keyboard/issues/216#issuecomment-431999553 self.split_hotkey = keyboard.hook_key( key_name, lambda e: _hotkey_action(e, key_name, self.startAutoSplitter)) self.splitLineEdit.setText(key_name) self.split_key = key_name self.afterSettingHotkeySignal.emit()
def test_hook_key_nonblocking(self): self.i = 0 def count(event): self.i += 1 hook = keyboard.hook_key('A', count) self.do(d_a) self.assertEqual(self.i, 1) self.do(u_a + d_b) self.assertEqual(self.i, 2) self.do([make_event(KEY_DOWN, 'A', -1)]) self.assertEqual(self.i, 3) keyboard.unhook_key(hook) self.do(d_a) self.assertEqual(self.i, 3)
def test_hook_key_blocking(self): self.i = 0 def count(event): self.i += 1 return event.scan_code == 1 hook = keyboard.hook_key('A', count, suppress=True) self.do(d_a, d_a) self.assertEqual(self.i, 1) self.do(u_a + d_b, u_a + d_b) self.assertEqual(self.i, 2) self.do([make_event(KEY_DOWN, 'A', -1)], []) self.assertEqual(self.i, 3) keyboard.unhook_key(hook) self.do([make_event(KEY_DOWN, 'A', -1)], [make_event(KEY_DOWN, 'A', -1)]) self.assertEqual(self.i, 3)
def test_hook_key(self): self.i = 0 def count(): self.i += 1 keyboard.hook_key('a', keyup_callback=count) self.press('a') self.assertEqual(self.i, 0) self.release('a') self.click('b') self.assertEqual(self.i, 1) keyboard.hook_key('b', keydown_callback=count) self.press('b') self.assertEqual(self.i, 2) keyboard.unhook_key('a') keyboard.unhook_key('b') self.click('a') self.assertEqual(self.i, 2)
def test_hook_key(self): self.i = 0 def count(): self.i += 1 keyboard.hook_key("a", keyup_callback=count) self.press("a") self.assertEqual(self.i, 0) self.release("a") self.click("b") self.assertEqual(self.i, 1) keyboard.hook_key("b", keydown_callback=count) self.press("b") self.assertEqual(self.i, 2) keyboard.unhook_key("a") keyboard.unhook_key("b") self.click("a") self.assertEqual(self.i, 2)
def callback(hotkey): try: keyboard.unhook_key(hotkey) except (AttributeError, KeyError): pass key_name = __get_key_name(keyboard.read_event(True)) try: if __is_key_already_set(self, key_name) or (key_name != '+' and '+' in key_name): self.afterSettingHotkeySignal.emit() return except AttributeError: self.afterSettingHotkeySignal.emit() return self.pause_hotkey = keyboard.hook_key( key_name, lambda e: _hotkey_action(e, key_name, self.startPause)) self.pausehotkeyLineEdit.setText(key_name) self.pause_key = key_name self.afterSettingHotkeySignal.emit()
def on_activate_exit(): print('exit') global times print(times) if times==1 or times==4: keyboard.unhook_key('h') keyboard.unhook_key('j') keyboard.unhook_key('k') keyboard.unhook_key('l') times=2 return if times==2 or times == 3: keyboard.remap_key('h','left') keyboard.remap_key('j','down') keyboard.remap_key('k','up') keyboard.remap_key('l','right') times=4 return
def captive_pause(self): """ holds the player captive in pause menu and allows pause menu functionality """ #keyboard handling key_1 = keyboard.on_press_key("1", lambda e: self.set_pause_mode(1)) key_2 = keyboard.on_press_key("2", lambda e: self.set_pause_mode(2)) key_3 = keyboard.on_press_key("3", lambda e: self.set_pause_mode(3)) keyboard.wait(" ") keyboard.unhook_key(key_1) keyboard.unhook_key(key_2) keyboard.unhook_key(key_3) keyboard.send(0x0E) if self.pause_mode == 3: clear_console() sys.exit() elif self.pause_mode == 2: self.save_exit = True
def loadSettings(self: AutoSplit, load_settings_on_open: bool = False, load_settings_from_livesplit: bool = False): if load_settings_on_open: settings_files = [] for file in os.listdir(auto_split_directory): if file.endswith(".pkl"): settings_files.append(file) # find all .pkls in AutoSplit folder, error if there is none or more than 1 if len(settings_files) < 1: error_messages.noSettingsFileOnOpenError() self.last_loaded_settings = None return elif len(settings_files) > 1: error_messages.tooManySettingsFilesOnOpenError() self.last_loaded_settings = None return else: self.load_settings_file_path = os.path.join( auto_split_directory, settings_files[0]) elif not load_settings_on_open and not load_settings_from_livesplit: self.load_settings_file_path = QtWidgets.QFileDialog.getOpenFileName( self, "Load Settings", os.path.join(auto_split_directory, "settings.pkl"), "PKL (*.pkl)")[0] if self.load_settings_file_path == '': return try: with open(self.load_settings_file_path, 'rb') as f: settings: List[Union[str, int]] = pickle.load(f) settings_count = len(settings) if settings_count < 18: if not load_settings_from_livesplit: error_messages.oldVersionSettingsFileError() return # v1.3-1.4 settings. Add default pause_key and auto_start_on_reset_setting if settings_count == 18: settings.insert(9, '') settings.insert(20, 0) # v1.5 settings elif settings_count != 20: if not load_settings_from_livesplit: error_messages.invalidSettingsError() return self.last_loaded_settings = [ self.split_image_directory, self.similarity_threshold, self.comparison_index, self.pause, self.fps_limit, self.split_key, self.reset_key, self.skip_split_key, self.undo_split_key, self.pause_key, self.x, self.y, self.width, self.height, self.hwnd_title, _, _, self.group_dummy_splits_undo_skip_setting, self.loop_setting, self.auto_start_on_reset_setting ] = settings except (FileNotFoundError, MemoryError, pickle.UnpicklingError): # HACK / Workaround: Executing the error QMessageBox from the auto-controlled Worker Thread makes it hangs. # I don't like this solution as we should probably ensure the Worker works nicely with PyQt instead, # but in the mean time, this will do. if not load_settings_from_livesplit: error_messages.invalidSettingsError() return self.splitimagefolderLineEdit.setText(self.split_image_directory) self.similaritythresholdDoubleSpinBox.setValue(self.similarity_threshold) self.pauseDoubleSpinBox.setValue(self.pause) self.fpslimitSpinBox.setValue(self.fps_limit) self.xSpinBox.setValue(self.x) self.ySpinBox.setValue(self.y) self.widthSpinBox.setValue(self.width) self.heightSpinBox.setValue(self.height) self.comparisonmethodComboBox.setCurrentIndex(self.comparison_index) self.hwnd = win32gui.FindWindow(None, self.hwnd_title) # set custom checkbox's accordingly self.groupDummySplitsCheckBox.setChecked( self.group_dummy_splits_undo_skip_setting == 1) self.loopCheckBox.setChecked(self.loop_setting == 1) self.autostartonresetCheckBox.setChecked( self.auto_start_on_reset_setting == 1) self.autostartonresetCheckBox.setChecked( self.auto_start_on_reset_setting == 1) # TODO: Reuse code from hotkeys rather than duplicating here # try to set hotkeys from when user last closed the window try: keyboard.unhook_key(self.split_hotkey) # pass if the key is an empty string (hotkey was never set) except (AttributeError, KeyError): pass try: self.splitLineEdit.setText(self.split_key) if not self.is_auto_controlled: self.split_hotkey = keyboard.hook_key( self.split_key, lambda e: _hotkey_action( e, self.split_key, self.startAutoSplitter)) except (ValueError, KeyError): pass try: keyboard.unhook_key(self.reset_hotkey) except (AttributeError, KeyError): pass try: self.resetLineEdit.setText(self.reset_key) if not self.is_auto_controlled: self.reset_hotkey = keyboard.hook_key( self.reset_key, lambda e: _hotkey_action(e, self.reset_key, self.startReset)) except (ValueError, KeyError): pass try: keyboard.unhook_key(self.skip_split_hotkey) except (AttributeError, KeyError): pass try: self.skipsplitLineEdit.setText(self.skip_split_key) if not self.is_auto_controlled: self.skip_split_hotkey = keyboard.hook_key( self.skip_split_key, lambda e: _hotkey_action( e, self.skip_split_key, self.startSkipSplit)) except (ValueError, KeyError): pass try: keyboard.unhook_key(self.undo_split_hotkey) except (AttributeError, KeyError): pass try: self.undosplitLineEdit.setText(self.undo_split_key) if not self.is_auto_controlled: self.undo_split_hotkey = keyboard.hook_key( self.undo_split_key, lambda e: _hotkey_action( e, self.undo_split_key, self.startUndoSplit)) except (ValueError, KeyError): pass try: keyboard.unhook_key(self.pause_hotkey) except (AttributeError, KeyError): pass try: self.pausehotkeyLineEdit.setText(self.pause_key) if not self.is_auto_controlled: self.pause_hotkey = keyboard.hook_key( self.pause_key, lambda e: _hotkey_action(e, self.pause_key, self.startPause)) except (ValueError, KeyError): pass self.last_successfully_loaded_settings_file_path = self.load_settings_file_path self.checkLiveImage()
def capture_input_shoot(self): """ method which captures inputs for shooting cursor until space is pressed """ if not self.save_exit: key_w = keyboard.on_press_key("w", lambda e: self.complete_shoot("w")) key_a = keyboard.on_press_key("a", lambda e: self.complete_shoot("a")) key_s = keyboard.on_press_key("s", lambda e: self.complete_shoot("s")) key_d = keyboard.on_press_key("d", lambda e: self.complete_shoot("d")) key_q = keyboard.on_press_key("q", lambda e: self.complete_shoot("q")) key_p = keyboard.on_press_key("p", self.set_pause_mode) two_wait(" ", "p") keyboard.unhook_key(key_w) keyboard.unhook_key(key_a) keyboard.unhook_key(key_s) keyboard.unhook_key(key_d) keyboard.unhook_key(key_q) keyboard.unhook_key(key_p) if self.pause_mode: self.captive_pause() self.set_pause_mode(0) if not self.save_exit: self.complete_shoot() self.capture_input_shoot() else: self.target.save_exit = True else: self.complete_shoot(" ")
def capture_input_place(self, shipper): """ method which captures inputs for ship placement until space is pressed :param shipper: ship object passed through to draw_place_ships method """ if not self.save_exit: key_w = keyboard.on_press_key( "w", lambda e: self.draw_place_ships("w", shipper)) key_a = keyboard.on_press_key( "a", lambda e: self.draw_place_ships("a", shipper)) key_s = keyboard.on_press_key( "s", lambda e: self.draw_place_ships("s", shipper)) key_d = keyboard.on_press_key( "d", lambda e: self.draw_place_ships("d", shipper)) key_r = keyboard.on_press_key( "r", lambda e: self.draw_place_ships("r", shipper)) key_p = keyboard.on_press_key("p", self.set_pause_mode) two_wait(" ", "p") keyboard.unhook_key(key_w) keyboard.unhook_key(key_a) keyboard.unhook_key(key_s) keyboard.unhook_key(key_d) keyboard.unhook_key(key_r) keyboard.unhook_key(key_p) keyboard.send(0x0E) if self.pause_mode: self.captive_pause() self.set_pause_mode(0) if not self.save_exit: self.draw_place_ships(shipper=shipper) self.capture_input_place(shipper) else: self.target.save_exit = True else: self.draw_place_ships(" ", shipper)
def __exit__(self, exc_type, exc_value, exc_trace): keyboard.unhook_key(self.hook_handler)
def unhook_arrow(): keyboard.unhook_key('h') keyboard.unhook_key('j') keyboard.unhook_key('k') keyboard.unhook_key('l')