-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregion_selector.py
More file actions
518 lines (435 loc) · 20.2 KB
/
region_selector.py
File metadata and controls
518 lines (435 loc) · 20.2 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
"""区域选择器模块
这个模块提供了一个基于tkinter的区域选择器界面,用于通过键盘选择屏幕上的特定区域。
典型用法:
layout_data = load_layout() # 加载布局配置
coords_file = "coords.txt" # 指定坐标输出文件
selector = RegionSelector(layout_data, coords_file)
selector.mainloop()
"""
import tkinter as tk
import sys
import json
import os
import traceback
from typing import Dict, Set, List
import config_loader # 导入config_loader
import threading
import time
try:
import pynput.keyboard
PYNPUT_AVAILABLE = True
except ImportError:
PYNPUT_AVAILABLE = False
def log_to_file(message: str) -> None:
"""记录日志到文件。
Args:
message: 要记录的日志消息
"""
try:
# DEL: 旧的日志路径逻辑,依赖于脚本自身位置,打包后不可靠。
# log_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
# log_file = os.path.join(log_dir, "region_selector_runtime.log")
config = config_loader.AppConfig() # 临时创建AppConfig实例以获取路径
log_dir = config.TEMP_DATA_PATH
os.makedirs(log_dir, exist_ok=True) # 确保目录存在
log_file = os.path.join(log_dir, "region_selector_runtime.log")
with open(log_file, "a", encoding="utf-8") as f:
f.write(f"[{os.getpid()}] {message}\n")
except Exception:
pass
class RegionSelector(tk.Tk):
"""区域选择器的主窗口类。"""
def __init__(self, layout_data: List[List[str]], coords_file_path: str) -> None:
"""初始化区域选择器。
Args:
layout_data: 网格布局数据,二维列表
coords_file_path: 坐标输出文件路径
"""
super().__init__()
log_to_file(f"RegionSelector 初始化开始, layout_data: {layout_data}, coords_file_path: {coords_file_path}")
# 基础配置数据
self.layout_data = layout_data # 存储网格布局数据
self.coords_file_path = coords_file_path # 存储坐标文件的路径
self.screen_width = self.winfo_screenwidth() # 获取屏幕宽度
self.screen_height = self.winfo_screenheight() # 获取屏幕高度
# 状态变量
self.current_level: int = 0 # 当前选择层级(1:大区域选择, 2:小区域选择)
self.macro_bounds = None # 存储第一次选择的大区域边界坐标(x1,y1,x2,y2)
self.grid_rects: Dict[str, tuple] = {} # 存储网格中每个按键对应的矩形区域坐标
self.valid_keys: Set[str] = {key for row in self.layout_data for key in row} # 从布局数据中提取所有有效的按键
# pynput键盘监听器 - 用于更可靠的按键捕获
self.pynput_listener = None
self.running = True
# 初始化界面
self._setup_overlay_window() # 设置覆盖窗口
self.start() # 启动选择器
def _setup_overlay_window(self):
# 暂时隐藏窗口
self.withdraw()
# 设置窗口大小为全屏,并将位置设为左上角(0,0)
self.geometry(f"{self.screen_width}x{self.screen_height}+0+0")
# 移除窗口的标题栏和边框
self.overrideredirect(True)
# 设置窗口始终保持在最顶层
self.wm_attributes("-topmost", True)
# 设置窗口透明度为75%
self.wm_attributes("-alpha", 0.75)
# 创建一个黑色背景的画布,无边框
self.canvas = tk.Canvas(self, bg='black', highlightthickness=0)
# 使画布填充整个窗口
self.canvas.pack(fill=tk.BOTH, expand=True)
# 将黑色设置为透明色
self.wm_attributes("-transparentcolor", 'black')
# 增强焦点管理 - 确保窗口能够独占键盘事件
self.protocol("WM_DELETE_WINDOW", self.stop) # 防止用户直接关闭窗口
# 按键去重机制相关变量
self._last_key = None
self._last_key_time = 0.0
# 使用最通用的全局按键绑定方案
# bind_all提供最好的兼容性,能在各种情况下可靠工作
try:
self.bind_all('<Key>', self._on_key_press)
log_to_file("全局按键绑定成功: 使用bind_all方案")
except Exception as e:
log_to_file(f"全局按键绑定失败: {str(e)}")
log_to_file(f"绑定异常详情: {traceback.format_exc()}")
# 备用方案:窗口级绑定
try:
self.bind('<Key>', self._on_key_press)
log_to_file("备用按键绑定成功: 使用bind方案")
except Exception as e2:
log_to_file(f"!!! 严重警告: 所有按键绑定方案均失败: {str(e2)} !!!")
# 确保画布可以获得焦点 - 增强异常处理
focus_success = False
try:
self.canvas.focus_set()
focus_success = True
log_to_file("画布焦点设置成功")
except Exception as e:
log_to_file(f"画布焦点设置失败: {str(e)}")
log_to_file(f"画布焦点设置异常详情: {traceback.format_exc()}")
# 尝试备用焦点设置方案
try:
self.focus_set()
focus_success = True
log_to_file("窗口焦点设置成功(备用方案)")
except Exception as e2:
log_to_file(f"窗口焦点设置失败(备用方案): {str(e2)}")
log_to_file(f"窗口焦点设置异常详情: {traceback.format_exc()}")
# 如果焦点设置失败,记录警告
if not focus_success:
log_to_file("!!! 警告: 无法设置焦点,按键响应可能不稳定 !!!")
# 按ESC键退出程序 - 增强异常处理
try:
self.bind('<Escape>', lambda e: self.stop())
self.canvas.bind('<Escape>', lambda e: self.stop())
log_to_file("ESC键绑定成功")
except Exception as e:
log_to_file(f"ESC键绑定失败: {str(e)}")
log_to_file(f"ESC键绑定异常详情: {traceback.format_exc()}")
# 尝试单独绑定到窗口
try:
self.bind('<Escape>', lambda e: self.stop())
log_to_file("ESC键绑定成功(窗口级)")
except Exception as e2:
log_to_file(f"ESC键绑定失败(窗口级): {str(e2)}")
log_to_file(f"ESC键绑定异常详情: {traceback.format_exc()}")
# 鼠标左键点击退出程序 - 增强异常处理
try:
self.bind('<Button-1>', lambda e: self.stop())
self.canvas.bind('<Button-1>', lambda e: self.stop())
log_to_file("鼠标左键绑定成功")
except Exception as e:
log_to_file(f"鼠标左键绑定失败: {str(e)}")
log_to_file(f"鼠标左键绑定异常详情: {traceback.format_exc()}")
# 尝试单独绑定到窗口
try:
self.bind('<Button-1>', lambda e: self.stop())
log_to_file("鼠标左键绑定成功(窗口级)")
except Exception as e2:
log_to_file(f"鼠标左键绑定失败(窗口级): {str(e2)}")
log_to_file(f"鼠标左键绑定异常详情: {traceback.format_exc()}")
def start(self):
"""启动区域选择器。
设置初始状态并显示选择网格:
- current_level=1: 设置为第一层选择(大区域选择)
- _draw_grid: 在全屏范围内绘制选择网格
- deiconify: 显示之前隐藏的窗口
- focus_force: 强制窗口获得焦点
- after: 100ms后再次强制获得焦点,确保窗口处于最前
"""
log_to_file(">>> region_selector.start() 开始执行")
try:
# 设置为第一层选择状态(大区域选择)
self.current_level = 1
log_to_file(f"设置选择层级: {self.current_level}")
# 在全屏范围内绘制选择网格
self._draw_grid((0, 0, self.screen_width, self.screen_height), self.layout_data)
log_to_file(f"绘制网格完成,屏幕大小: {self.screen_width}x{self.screen_height}")
# 显示之前withdraw()隐藏的窗口
self.deiconify()
log_to_file("窗口显示完成 (deiconify)")
# 强制窗口获得键盘焦点
self.focus_force()
log_to_file("窗口焦点设置完成 (focus_force)")
# 捕获所有键盘事件,确保独占
self.grab_set()
log_to_file("键盘事件独占设置完成 (grab_set)")
# 确保窗口在最前
self.lift()
log_to_file("窗口置顶完成 (lift)")
# 100毫秒后再次强制获得焦点,确保窗口位于最前
self.after(100, self._ensure_focus)
log_to_file("延迟焦点检查已设置 (100ms)")
# 启动 pynput 键盘监听器作为备用方案 (如果可用)
if PYNPUT_AVAILABLE and self.pynput_listener is None:
self._start_pynput_listener()
log_to_file("pynput 键盘监听器启动完成")
else:
log_to_file(f"pynput 不可用或已启动,AVAILABLE={PYNPUT_AVAILABLE}, listener={self.pynput_listener is not None}")
log_to_file(">>> region_selector.start() 执行完成")
except Exception as e:
log_to_file(f"!!! region_selector.start() 发生异常: {str(e)}")
log_to_file(f"异常详情: {traceback.format_exc()}")
raise
def _ensure_focus(self):
"""确保窗口获得焦点和独占键盘事件 - 增强版"""
try:
# 多层次焦点强化机制
# 第一步:强制获取窗口焦点
self.focus_force()
log_to_file("步骤1: focus_force() 完成")
# 第二步:确保窗口在最前层
self.lift()
self.wm_attributes("-topmost", True) # 重新确保最顶层
log_to_file("步骤2: lift() 和 topmost 完成")
# 第三步:独占键盘事件
self.grab_set()
log_to_file("步骤3: grab_set() 完成")
# 第四步:画布焦点设置
self.canvas.focus_set()
log_to_file("步骤4: canvas.focus_set() 完成")
# 第五步:强制刷新显示
self.update()
log_to_file("步骤5: update() 完成")
log_to_file("多层次焦点确保完成")
# 延迟100ms后再次确保,防止焦点丢失
self.after(100, self._secondary_focus_ensure)
except Exception as e:
log_to_file(f"焦点确保失败: {e}")
def _secondary_focus_ensure(self):
"""二次焦点确保机制"""
try:
# 再次确保关键的焦点设置
self.grab_set() # 重新独占键盘
self.canvas.focus_set() # 重新设置画布焦点
log_to_file("二次焦点确保完成")
except Exception as e:
log_to_file(f"二次焦点确保失败: {e}")
def _start_pynput_listener(self):
"""启动pynput键盘监听器作为备用按键捕获方案"""
if not PYNPUT_AVAILABLE:
return
try:
def on_press(key):
if not self.running:
return False
try:
# 转换按键为字符
if hasattr(key, 'char') and key.char:
key_char = key.char.lower()
else:
# 处理特殊按键
key_str = str(key).lower()
if 'key.' in key_str:
key_char = key_str.split('.')[1]
else:
key_char = key_str
log_to_file(f"[PYNPUT] 捕获按键: {key_char}")
# 创建模拟事件对象
class MockEvent:
def __init__(self, keysym):
self.keysym = keysym
self.keycode = 0
# 调用按键处理方法
mock_event = MockEvent(key_char)
self.after_idle(lambda: self._on_key_press(mock_event))
except Exception as e:
log_to_file(f"[PYNPUT] 按键处理错误: {e}")
return True
self.pynput_listener = pynput.keyboard.Listener(on_press=on_press)
self.pynput_listener.start()
log_to_file("[PYNPUT] 键盘监听器启动成功")
except Exception as e:
log_to_file(f"[PYNPUT] 启动失败: {e}")
def _stop_pynput_listener(self):
"""停止pynput监听器"""
self.running = False
if PYNPUT_AVAILABLE and self.pynput_listener:
try:
self.pynput_listener.stop()
log_to_file("[PYNPUT] 键盘监听器已停止")
except Exception as e:
log_to_file(f"[PYNPUT] 停止监听器失败: {e}")
def _on_key_press(self, event):
key = event.keysym.lower()
current_time = time.time()
# 按键去重机制:防止多重绑定导致的重复触发
if (self._last_key == key and
current_time - self._last_key_time < 0.2): # 200ms去重窗口
log_to_file(f"重复按键被忽略: {key} (时间差: {current_time - self._last_key_time:.3f}s)")
return "break"
# 记录本次按键
self._last_key = key
self._last_key_time = current_time
log_to_file(f"按键按下: {key}, 当前层级: {self.current_level}")
# 特殊按键处理:退出按键
if key in ['escape', 'esc']:
log_to_file(f"按下退出键: {key}")
self.stop()
return "break"
# 按键映射处理
if key == 'semicolon': key = ';'
# 有效按键处理
if key in self.valid_keys:
if self.current_level == 1:
log_to_file(f"选择大区域: {key}, 边界: {self.grid_rects[key]}")
self.macro_bounds = self.grid_rects[key]
self.canvas.delete("all")
self.current_level = 2
self._draw_grid(self.macro_bounds, self.layout_data)
# 第二次选择时需要更强的焦点管理 - 延长延迟确保重绘完成
self.after(200, self._ensure_focus) # 增加延迟到200ms
log_to_file("已安排第二次选择的焦点重新获取")
elif self.current_level == 2:
log_to_file(f"选择小区域: {key}, 边界: {self.grid_rects[key]}")
micro_bounds = self.grid_rects[key]
target_x = micro_bounds[0] + (micro_bounds[2] - micro_bounds[0]) / 2
target_y = micro_bounds[1] + (micro_bounds[3] - micro_bounds[1]) / 2
try:
with open(self.coords_file_path, 'w', encoding='utf-8') as f:
f.write(f"{target_x},{target_y}")
log_to_file(f"坐标成功写入: {self.coords_file_path}, 坐标: ({target_x},{target_y})")
except Exception as e:
log_to_file(f"!!! 写入坐标文件失败: {e} !!!")
self.stop()
else:
# 无效按键:记录但不退出,让用户继续尝试
log_to_file(f"无效按键忽略: {key},有效按键为: {sorted(list(self.valid_keys))}")
# 确保事件不会继续传播
return "break"
def _draw_grid(self, bounds, layout):
"""在指定边界内绘制网格。
Args:
bounds: 边界坐标元组 (x1, y1, x2, y2)
layout: 网格布局数据
"""
# 解析边界坐标和计算基础尺寸
x1, y1, x2, y2 = bounds
region_width = x2 - x1
region_height = y2 - y1
# 计算网格尺寸
grid_size_y = len(layout)
grid_size_x = len(layout[0])
# 计算单元格尺寸
cell_width = region_width / grid_size_x
cell_height = region_height / grid_size_y
# 清除之前的网格记录
self.grid_rects.clear()
# 设置样式参数
font_size = max(8, int(cell_height * 0.6))
cell_bg_color = "#333333"
outline_color = "#FFD700"
text_color = "black"
grid_line_color = "#FFD700"
# 遍历布局绘制网格
for row_index, row in enumerate(layout):
for col_index, key in enumerate(row):
# 计算单元格坐标
cell_x1 = x1 + col_index * cell_width
cell_y1 = y1 + row_index * cell_height
cell_x2 = cell_x1 + cell_width
cell_y2 = cell_y1 + cell_height
# 绘制单元格背景
self.canvas.create_rectangle(
cell_x1, cell_y1, cell_x2, cell_y2,
fill=cell_bg_color,
outline=grid_line_color,
width=1
)
# 计算文本中心位置
center_x = cell_x1 + cell_width / 2
center_y = cell_y1 + cell_height / 2
text = key.upper()
# 绘制文本轮廓
offsets = [(-1, -1), (1, -1), (-1, 1), (1, 1)]
for ox, oy in offsets:
self.canvas.create_text(
center_x + ox,
center_y + oy,
text=text,
font=("Consolas", font_size, "bold"),
fill=outline_color
)
# 绘制文本主体
self.canvas.create_text(
center_x,
center_y,
text=text,
font=("Consolas", font_size, "bold"),
fill=text_color
)
# 记录单元格区域
self.grid_rects[key] = (cell_x1, cell_y1, cell_x2, cell_y2)
def stop(self):
log_to_file(">>> region_selector.stop() 开始执行")
try:
# 标记为停止状态
self.running = False
log_to_file("设置 running = False")
# 停止 pynput 监听器
try:
self._stop_pynput_listener()
log_to_file("pynput 监听器停止完成")
except Exception as e:
log_to_file(f"停止 pynput 监听器异常: {str(e)}")
# 释放键盘独占
try:
self.grab_release()
log_to_file("键盘独占释放完成 (grab_release)")
except Exception as e:
log_to_file(f"释放键盘独占异常: {str(e)}")
# 销毁窗口
try:
self.destroy()
log_to_file("窗口销毁完成 (destroy)")
except Exception as e:
log_to_file(f"窗口销毁异常: {str(e)}")
log_to_file(">>> region_selector.stop() 执行完成")
except Exception as e:
log_to_file(f"!!! region_selector.stop() 发生异常: {str(e)}")
log_to_file(f"异常详情: {traceback.format_exc()}")
# 强制退出,避免程序挂起
try:
self.quit()
log_to_file("强制退出 (quit) 完成")
except:
log_to_file("强制退出也失败,程序可能会挂起")
if __name__ == '__main__':
try:
log_to_file("\n--- region_selector.exe started ---")
log_to_file(f"sys.argv: {sys.argv}")
if len(sys.argv) < 3:
log_to_file("!!! 致命错误: 未提供布局文件和坐标文件路径。")
sys.exit(1)
layout_file_path = sys.argv[1]
coords_file_path = sys.argv[2]
with open(layout_file_path, 'r', encoding='utf-8') as f:
layout = json.load(f)
app = RegionSelector(layout, coords_file_path)
app.mainloop()
log_to_file("Exiting cleanly.")
sys.exit(0)
except Exception as e:
log_to_file(f"!!! 致命错误 !!!\nError: {e}\n{traceback.format_exc()}")
sys.exit(1)