-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmouse_input.py
More file actions
201 lines (165 loc) · 6.76 KB
/
Copy pathmouse_input.py
File metadata and controls
201 lines (165 loc) · 6.76 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# -*- coding: utf-8 -*-
"""控制台菜单: 基于 prompt_toolkit, 支持鼠标点击与键盘选择。
单选 click_select / 多选 click_select_multi 均使用 prompt_toolkit 渲染,
避免与 Windows 控制台原生实现混用导致的状态冲突。
当 prompt_toolkit 不可用时自动回退到普通 input()。
"""
import sys
def _plain_select(title, options, prompt):
"""回退: 无法使用 prompt_toolkit 时, 用普通 input()。"""
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
print("\n" + title)
for i, (_val, label) in enumerate(options):
print(f" [{i + 1}] {label}")
while True:
x = input(" " + prompt).strip()
if x == "":
continue
lower = x.lower()
if lower in ("q", "exit", "quit"):
return None
# 精确匹配选项 value
for val, _label in options:
if lower == val.lower():
return val
print(" [!] 无效输入,请重试")
def _plain_select_multi(title, options, prompt):
"""回退: 多选用编号逗号分隔输入。"""
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
print("\n" + title)
for i, (_val, label) in enumerate(options):
print(f" [{i + 1}] {label}")
print(f"\n {prompt}")
x = input(" 请选择(编号,可多选,逗号分隔,回车=全部): ").strip()
if not x:
return [str(i + 1) for i in range(len(options))]
return [t.strip() for t in x.split(",") if t.strip()]
def click_select(title, options, prompt="请选择: ", footer=""):
"""单选: 鼠标点击 / 数字键 / 上下+回车 选择, Esc/Ctrl+C 取消返回 None。"""
options = [(str(v), str(l)) for v, l in options]
try:
from prompt_toolkit import Application
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout import Layout, ScrollablePane, Window
from prompt_toolkit.layout.controls import FormattedTextControl
from prompt_toolkit.mouse_events import MouseEventType
except Exception:
return _plain_select(title, options, prompt)
# 等待 loguru 异步日志队列清空, 避免旧日志在菜单渲染期间插入
try:
from loguru import logger
logger.complete()
except Exception:
pass
state = {"current": 0}
def pick(i):
app.exit(result=options[i][0])
def on_click(i, event):
# 只在鼠标抬起(点击)时选中, 忽略移动/滚轮事件
if event.event_type == MouseEventType.MOUSE_UP:
pick(i)
def get_lines():
frags = [("", title + "\n"), ("", " " + "-" * 40 + "\n")]
for i, (_v, label) in enumerate(options):
cursor = ">" if i == state["current"] else " "
frags.append(("", f" {cursor} [{i + 1}] {label}\n", lambda e, i=i: on_click(i, e)))
if footer:
frags.append(("", footer + "\n"))
frags.append(("", "\n " + prompt))
return frags
kb = KeyBindings()
@kb.add(Keys.ControlC, eager=True)
@kb.add(Keys.Escape, eager=True)
def _cancel(event):
event.app.exit(result=None)
@kb.add(Keys.ControlM, eager=True) # Enter -> 确认当前高亮项
def _confirm(event):
event.app.exit(result=options[state["current"]][0])
@kb.add(Keys.Up, eager=True)
def _up(event):
state["current"] = (state["current"] - 1) % len(options)
app.invalidate()
@kb.add(Keys.Down, eager=True)
def _down(event):
state["current"] = (state["current"] + 1) % len(options)
app.invalidate()
for idx in range(min(9, len(options))):
@kb.add(str(idx + 1), eager=True)
def _digit(event, i=idx):
event.app.exit(result=options[i][0])
app = Application(
layout=Layout(ScrollablePane(Window(content=FormattedTextControl(get_lines), wrap_lines=False))),
key_bindings=kb,
mouse_support=True,
full_screen=False,
)
try:
result = app.run()
except (KeyboardInterrupt, EOFError):
return None
return result
def click_select_multi(title, options, prompt="可多选,点击切换勾选,回车确认,Esc 取消: ", default_all=True):
"""多选: 鼠标点击/数字键切换勾选, 回车确认(返回选中 value 列表), Esc/Ctrl+C 取消返回 None。
若 default_all 为 True, 回车且未选任何项时返回全选列表。
"""
options = [(str(v), str(l)) for v, l in options]
try:
from prompt_toolkit import Application
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout import Layout, ScrollablePane, Window
from prompt_toolkit.layout.controls import FormattedTextControl
from prompt_toolkit.mouse_events import MouseEventType
except Exception:
return _plain_select_multi(title, options, prompt)
# 等待 loguru 异步日志队列清空, 避免旧日志在菜单渲染期间插入
try:
from loguru import logger
logger.complete()
except Exception:
pass
sel = set()
def toggle(i):
sel.symmetric_difference_update({i})
app.invalidate()
def on_click(i, event):
# 只在鼠标抬起(点击)时切换, 忽略移动/滚轮事件
if event.event_type == MouseEventType.MOUSE_UP:
toggle(i)
def get_lines():
frags = [("", title + "\n"), ("", " " + "-" * 40 + "\n")]
for i, (_v, label) in enumerate(options):
mark = "[x]" if i in sel else "[ ]"
frags.append(("", f" {mark} {label}\n", lambda e, i=i: on_click(i, e)))
sel_txt = ", ".join(options[i][1] for i in sorted(sel)) if sel else "无"
frags.append(("", f" 已选: {sel_txt}\n"))
frags.append(("", "\n " + prompt + "\n"))
return frags
kb = KeyBindings()
@kb.add(Keys.ControlC, eager=True)
@kb.add(Keys.Escape, eager=True)
def _cancel(event):
event.app.exit(result=None)
@kb.add(Keys.ControlM, eager=True) # Enter -> 确认
def _confirm(event):
event.app.exit(result=[options[i][0] for i in sorted(sel)])
for idx in range(min(9, len(options))):
@kb.add(str(idx + 1), eager=True)
def _toggle_digit(event, idx=idx):
toggle(idx)
app = Application(
layout=Layout(ScrollablePane(Window(content=FormattedTextControl(get_lines), wrap_lines=False))),
key_bindings=kb,
mouse_support=True,
full_screen=False,
)
try:
result = app.run()
except (KeyboardInterrupt, EOFError):
return None
if result is None:
return None
if default_all and not result:
return [value for value, _ in options]
return result