-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselection_menu.py
More file actions
78 lines (60 loc) · 2.64 KB
/
selection_menu.py
File metadata and controls
78 lines (60 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import ctypes
import os
import time
from ctypes import windll
import keyboard
import psutil
from colorama import Fore
from constants import selection_menu_additional_options
from helpers import helper
def can_handle_keyboard():
"""
Checks whether the current process or its parent process is equal to the process whose window is the active windows
"""
h_wnd = windll.user32.GetForegroundWindow()
lpdw_process_id = ctypes.c_ulong()
windll.user32.GetWindowThreadProcessId(h_wnd, ctypes.byref(lpdw_process_id))
focused_process_id = lpdw_process_id.value
focused_process = psutil.Process(focused_process_id)
recursive = 'explorer' not in focused_process.name().lower()
focused_process_children = [child.pid for child in focused_process.children(recursive=recursive)]
pid = os.getpid()
ppid = os.getppid()
result = pid in focused_process_children
result |= pid == focused_process_id
result |= ppid == focused_process_id
result |= 'pycharm' in focused_process.name().lower()
return result
def perform_action(action):
if can_handle_keyboard() is True:
action()
def __print_option(index, option):
print(f" {Fore.GREEN + str(index)}. {Fore.WHITE + option}")
def choose(title: str, options: list, show_turn_back: bool = True, show_start_over: bool = True) -> str:
"""
Shows menu, where user can choose one of the presented options
:param title: Menu title
:param options: List of options
:param show_turn_back: If True a 'Turn back' option will be shown
:param show_start_over: If True a 'Start over' option will be shown
:return: The option selected by user
"""
selected_options = []
print(f"{Fore.GREEN + chr(9679)} {Fore.WHITE + title}")
for i in range(0, len(options)):
keyboard.add_hotkey(str(i + 1), lambda index=i: perform_action(lambda: selected_options.append(options[index])))
__print_option(i + 1, options[i])
if show_turn_back:
__print_option(9, selection_menu_additional_options[0])
keyboard.add_hotkey('9', lambda: perform_action(
lambda: selected_options.append(selection_menu_additional_options[0])))
if show_start_over:
__print_option(0, selection_menu_additional_options[1])
keyboard.add_hotkey('0', lambda: perform_action(
lambda: selected_options.append(selection_menu_additional_options[1])))
while len(selected_options) == 0:
time.sleep(0.1)
print(f"You choose option '{Fore.GREEN + selected_options[0] + Fore.WHITE}'", '\n')
keyboard.clear_all_hotkeys()
helper.flush_input() # we should clear input buffer
return selected_options[0]