-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
1742 lines (1522 loc) · 72.6 KB
/
Copy pathgui.py
File metadata and controls
1742 lines (1522 loc) · 72.6 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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# gui.py
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import json
import re
import threading
import keyboard
import ctypes
import time
from pynput import mouse
from mapper import KeyMapper
from utils import (
KEY_ALIASES, MOUSE_EVENTS, VK_CODES,
ensure_user_config_path, normalize_key_name, validate_config_name,
is_game_window_foreground,
DEFAULT_CONFIG_NAME, list_configs, get_config_path_for,
create_config, delete_config_file, rename_config_file
)
# ---------- Windows API 用于输入法禁用 ----------
user32 = ctypes.windll.user32
imm32 = ctypes.windll.imm32
def disable_ime():
imm32.ImmDisableIME(0)
def enable_ime():
imm32.ImmDisableIME(-1)
def center_window(window, width=None, height=None):
window.update_idletasks()
w = width or window.winfo_width()
h = height or window.winfo_height()
parent = window.master
if parent:
x = parent.winfo_x() + (parent.winfo_width() - w) // 2
y = parent.winfo_y() + (parent.winfo_height() - h) // 2
else:
x = (window.winfo_screenwidth() - w) // 2
y = (window.winfo_screenheight() - h) // 2
window.geometry(f"{w}x{h}+{x}+{y}")
class ToolTip:
def __init__(self, widget, text, delay=450):
self.widget = widget
self.text = text
self.delay = delay
self._after_id = None
self._tip = None
widget.bind('<Enter>', self._schedule, add='+')
widget.bind('<Leave>', self._hide, add='+')
widget.bind('<ButtonPress>', self._hide, add='+')
def _schedule(self, event=None):
self._cancel()
self._after_id = self.widget.after(self.delay, self._show)
def _cancel(self):
if self._after_id:
self.widget.after_cancel(self._after_id)
self._after_id = None
def _show(self):
if self._tip or not self.text:
return
x = self.widget.winfo_rootx() + 18
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 8
self._tip = tk.Toplevel(self.widget)
self._tip.wm_overrideredirect(True)
self._tip.wm_geometry(f"+{x}+{y}")
label = tk.Label(
self._tip,
text=self.text,
bg='#111827',
fg='#f8fafc',
padx=10,
pady=6,
font=('Microsoft YaHei UI', 9),
relief='flat'
)
label.pack()
def _hide(self, event=None):
self._cancel()
if self._tip:
self._tip.destroy()
self._tip = None
# ---------- 按键捕获弹窗 ----------
class KeyCaptureDialog:
def __init__(self, parent, callback, capture_mouse=True, on_close=None):
self.parent = parent
self.top = tk.Toplevel(parent)
self.top.title("按下任意键或鼠标按键")
self.top.geometry("350x180")
self.top.resizable(False, False)
self.top.transient(parent)
self.top.grab_set()
self.callback = callback
self.on_close = on_close
self.captured_key = None
self.capture_mouse = capture_mouse
self._closed = False
label = ttk.Label(self.top, text="请按下要绑定的按键...\n(支持键盘按键、鼠标左/右/中/侧键)",
font=("微软雅黑", 11), justify='center')
label.pack(expand=True, pady=20)
self.listener_keyboard = None
self.listener_mouse = None
disable_ime()
self.top.protocol("WM_DELETE_WINDOW", self._on_cancel)
self.start_listeners()
center_window(self.top)
def start_listeners(self):
self.listener_keyboard = None
def on_key(event):
if event.event_type == 'down':
self.captured_key = normalize_key_name(event.name)
self.top.after(10, self._close)
self._kb_hook_id = keyboard.hook(on_key, suppress=True)
if self.capture_mouse:
def on_click(x, y, button, pressed):
if pressed and self.capture_mouse:
btn_name = str(button).replace('Button.', '').lower()
if btn_name == 'left':
self.captured_key = 'mouse_left'
elif btn_name == 'right':
self.captured_key = 'mouse_right'
elif btn_name == 'middle':
self.captured_key = 'mouse_middle'
elif btn_name in ('x1', 'x2'):
self.captured_key = f'mouse_{btn_name}'
else:
self.captured_key = btn_name
self.top.after(10, self._close)
return False
self.listener_mouse = mouse.Listener(on_click=on_click)
self.listener_mouse.start()
def _close(self):
if self._closed:
return
self._closed = True
self.stop_listeners()
if self.captured_key:
self.callback(self.captured_key)
try:
self.top.grab_release()
except Exception:
pass
self.top.destroy()
enable_ime()
self.parent.after(20, self.parent.focus_force)
if self.on_close:
self.on_close()
def _on_cancel(self):
if self._closed:
return
self._closed = True
self.stop_listeners()
try:
self.top.grab_release()
except Exception:
pass
self.top.destroy()
enable_ime()
self.parent.after(20, self.parent.focus_force)
if self.on_close:
self.on_close()
def stop_listeners(self):
if hasattr(self, '_kb_hook_id') and self._kb_hook_id is not None:
try:
keyboard.unhook(self._kb_hook_id)
except Exception:
pass
self._kb_hook_id = None
if self.listener_keyboard:
try:
self.listener_keyboard.stop()
self.listener_keyboard.join(0.2)
except Exception:
pass
self.listener_keyboard = None
if self.listener_mouse:
try:
self.listener_mouse.stop()
self.listener_mouse.join(0.2)
except Exception:
pass
self.listener_mouse = None
class HotkeyCaptureDialog(KeyCaptureDialog):
def __init__(self, parent, callback, on_close=None):
super().__init__(parent, callback, capture_mouse=False, on_close=on_close)
self.top.title("按下热键(可单键或组合键)")
self.pressed_keys = set()
self.modifier_map = {
'ctrl': 'ctrl', 'alt': 'alt', 'shift': 'shift',
'cmd': 'cmd', 'win': 'win', 'ctrl_l': 'ctrl',
'ctrl_r': 'ctrl', 'alt_l': 'alt', 'alt_r': 'alt',
'shift_l': 'shift', 'shift_r': 'shift'
}
self.stop_listeners()
def kb_handler(event):
k = normalize_key_name(event.name)
k = self.modifier_map.get(k, k)
if event.event_type == 'down':
self.pressed_keys.add(k)
combo = '+'.join(sorted(self.pressed_keys))
for child in self.top.winfo_children():
if isinstance(child, ttk.Label):
child.config(text=f"当前按下: {combo}")
elif event.event_type == 'up' and self.pressed_keys:
combo = '+'.join(sorted(self.pressed_keys))
self.captured_key = combo
self.top.after(10, self._close)
self._kb_hook_id = keyboard.hook(kb_handler, suppress=True)
for child in self.top.winfo_children():
if isinstance(child, ttk.Label):
child.config(text="请按下热键... (支持单键如 F5,或组合键如 Ctrl+Shift+F12)")
class EditMappingDialog:
def __init__(self, parent, mapping, existing_triggers, callback, on_close=None):
self.top = tk.Toplevel(parent)
self.top.title("编辑映射")
self.top.geometry("520x280")
self.top.resizable(False, False)
self.top.transient(parent)
self.top.grab_set()
self.mapping = dict(mapping)
self.existing_triggers = {normalize_key_name(trigger) for trigger in existing_triggers}
self.callback = callback
self.on_close = on_close
self._closed = False
self._capture_active = False
self._capture_cooldown_until = 0
self.script = self.mapping.get('script', '')
main = ttk.Frame(self.top, padding=16)
main.pack(fill='both', expand=True)
main.columnconfigure(1, weight=1)
ttk.Label(main, text="触发键").grid(row=0, column=0, sticky='e', padx=(0, 10), pady=8)
self.trigger_var = tk.StringVar(value=normalize_key_name(self.mapping.get('trigger', '')))
ttk.Entry(main, textvariable=self.trigger_var, state='readonly').grid(row=0, column=1, sticky='ew', pady=8)
ttk.Button(main, text="重新捕获", command=lambda: self._capture_to(self.trigger_var)).grid(
row=0, column=2, padx=(10, 0), pady=8)
self.mapping_type = self.mapping.get('type', 'simple')
if self.mapping_type == 'simple':
ttk.Label(main, text="目标键").grid(row=1, column=0, sticky='e', padx=(0, 10), pady=8)
self.target_var = tk.StringVar(value=normalize_key_name(self.mapping.get('target', '')))
ttk.Entry(main, textvariable=self.target_var, state='readonly').grid(row=1, column=1, sticky='ew', pady=8)
ttk.Button(main, text="重新捕获", command=lambda: self._capture_to(self.target_var)).grid(
row=1, column=2, padx=(10, 0), pady=8)
ttk.Label(main, text="模式").grid(row=2, column=0, sticky='e', padx=(0, 10), pady=8)
self.mode_var = tk.StringVar(value=self.mapping.get('mode', 'hold'))
ttk.Combobox(
main,
textvariable=self.mode_var,
values=['hold', 'tap'],
state='readonly',
width=12
).grid(row=2, column=1, sticky='w', pady=8)
else:
ttk.Label(main, text="宏脚本").grid(row=1, column=0, sticky='e', padx=(0, 10), pady=8)
self.script_preview_var = tk.StringVar()
ttk.Entry(main, textvariable=self.script_preview_var, state='readonly').grid(row=1, column=1, sticky='ew', pady=8)
ttk.Button(main, text="编辑脚本", command=self._edit_script).grid(row=1, column=2, padx=(10, 0), pady=8)
self._refresh_script_preview()
btn_frame = ttk.Frame(self.top)
btn_frame.pack(fill='x', padx=16, pady=(0, 16))
ttk.Button(btn_frame, text="保存", command=self._on_ok, width=10).pack(side='right', padx=(8, 0))
ttk.Button(btn_frame, text="取消", command=self._on_cancel, width=10).pack(side='right')
self.top.protocol("WM_DELETE_WINDOW", self._on_cancel)
center_window(self.top, 520, 280)
def _capture_to(self, variable):
if self._capture_active or time.perf_counter() < self._capture_cooldown_until:
return
self._capture_active = True
def set_key(key_name):
variable.set(normalize_key_name(key_name))
def on_close():
self._capture_active = False
self._capture_cooldown_until = time.perf_counter() + 0.25
if self.top.winfo_exists():
self.top.grab_set()
self.top.focus_force()
KeyCaptureDialog(self.top, set_key, capture_mouse=True, on_close=on_close)
def _refresh_script_preview(self):
preview = self.script.strip().replace('\n', ' / ')
self.script_preview_var.set(preview[:56] + ('...' if len(preview) > 56 else ''))
def _edit_script(self):
def save_script(script):
self.script = script
self._refresh_script_preview()
try:
self.top.grab_release()
except Exception:
pass
def restore_grab():
if self.top.winfo_exists():
self.top.grab_set()
self.top.focus_force()
MacroEditorDialog(self.top, self.script, save_script, on_close=restore_grab)
def _on_ok(self):
new_trigger = normalize_key_name(self.trigger_var.get())
if not new_trigger:
messagebox.showerror("错误", "请先设置触发键", parent=self.top)
return
if new_trigger in self.existing_triggers:
messagebox.showerror("错误", f"触发键 {new_trigger} 已存在映射", parent=self.top)
return
updated = dict(self.mapping)
updated['trigger'] = new_trigger
if self.mapping_type == 'simple':
target = normalize_key_name(self.target_var.get())
if not target:
messagebox.showerror("错误", "请先设置目标键", parent=self.top)
return
updated['target'] = target
updated['mode'] = self.mode_var.get()
else:
if not self.script.strip():
messagebox.showerror("错误", "宏脚本不能为空", parent=self.top)
return
updated['script'] = self.script
self.callback(updated)
self._close()
def _on_cancel(self):
self._close()
def _close(self):
if self._closed:
return
self._closed = True
try:
self.top.grab_release()
except Exception:
pass
self.top.destroy()
if self.on_close:
self.on_close()
class LineNumberCanvas(tk.Canvas):
"""行号显示画布"""
def __init__(self, master, text_widget, **kwargs):
super().__init__(master, width=40, **kwargs)
self.text_widget = text_widget
self.text_widget.bind('<KeyRelease>', self.redraw)
self.text_widget.bind('<MouseWheel>', self.redraw)
self.text_widget.bind('<Button-4>', self.redraw)
self.text_widget.bind('<Button-5>', self.redraw)
self.redraw()
def redraw(self, event=None):
self.delete('all')
i = self.text_widget.index("@0,0")
while True:
dline = self.text_widget.dlineinfo(i)
if dline is None:
break
y = dline[1]
linenum = str(i).split('.')[0]
self.create_text(35, y, anchor='ne', text=linenum, font=('Consolas', 10), fill='#666')
i = self.text_widget.index(f"{i}+1line")
class AutocompleteListbox(tk.Toplevel):
"""自动补全下拉列表"""
def __init__(self, parent, text_widget, commands, on_select_callback=None):
super().__init__(parent)
self.text_widget = text_widget
self.commands = commands
self.prefix = ''
self.on_select_callback = on_select_callback
self.overrideredirect(True) # 无边框
self.withdraw()
self.listbox = tk.Listbox(self, font=('Consolas', 10), height=6, exportselection=False)
self.listbox.pack(fill='both', expand=True)
self.listbox.bind('<ButtonRelease-1>', self.on_select)
self.listbox.bind('<Return>', self.on_select)
self.listbox.bind('<Tab>', self.on_select)
self.listbox.bind('<Escape>', lambda e: self.withdraw())
def show(self, x, y, prefix, candidates=None):
self.prefix = prefix
source = self.commands if candidates is None else candidates
filtered = [cmd for cmd in source if cmd.startswith(prefix)]
if not filtered:
self.withdraw()
return
self.listbox.delete(0, tk.END)
for cmd in filtered[:12]:
self.listbox.insert(tk.END, cmd)
self.listbox.selection_set(0)
self.geometry(f"+{x}+{y}")
self.deiconify()
self.lift()
def on_select(self, event=None):
if self.listbox.curselection():
selected = self.listbox.get(self.listbox.curselection())
if self.prefix:
self.text_widget.delete(f'insert-{len(self.prefix)}c', 'insert')
self.text_widget.insert('insert', selected)
self.withdraw()
self.text_widget.focus()
if self.on_select_callback:
self.on_select_callback()
return 'break'
def move_selection(self, delta):
if not self.winfo_viewable() or self.listbox.size() == 0:
return False
current = self.listbox.curselection()
index = current[0] if current else 0
index = max(0, min(self.listbox.size() - 1, index + delta))
self.listbox.selection_clear(0, tk.END)
self.listbox.selection_set(index)
self.listbox.activate(index)
return True
class MacroEditorDialog:
"""增强型宏脚本编辑器(语法高亮、行号、实时错误检查、自动补全)"""
HELP_TEMPLATE = (
"# ========== 指令参考 ==========\n"
"# press <键名> - 按下并按住键\n"
"# release <键名> - 松开键\n"
"# tap <键名> - 点击键(按下后立即松开)\n"
"# wait <毫秒> - 等待指定时间\n"
"# loop <次数> - 开始循环(0 或 infinite 无限循环)\n"
"# end - 结束循环\n"
"# drag <x> <y> [mouse] [按键] - 从当前位置拖拽到目标坐标\n"
"# drag_rel <dx> <dy> [按键] - 相对拖拽\n"
"# setpos <x> <y> [mouse] - 移动光标\n"
"# setpos_rel <dx> <dy> - 相对移动光标\n"
"# combo <键1> <键2> ... - 同时按下多个键\n"
"# 常用键名: esc, tab, enter, space, q, w, e, 1, 2, 3, mouse_left, mouse_right\n"
"# 注释用 # 开头\n"
"# ===============================\n\n"
)
def __init__(self, parent, initial_script="", callback=None, on_close=None):
self.top = tk.Toplevel(parent)
self.top.title("编辑宏脚本")
self.top.geometry("700x500")
self.top.minsize(600, 400)
self.top.transient(parent)
self.callback = callback
self.on_close = on_close
self._closed = False
# 指令列表(用于自动补全和高亮)
self.keywords = [
'press', 'release', 'tap', 'wait', 'loop', 'end',
'drag', 'drag_rel', 'setpos', 'setpos_rel', 'combo'
]
self.modifiers = ['mouse', 'left', 'right', 'middle', 'infinite']
self.key_names = sorted(set(VK_CODES) | set(KEY_ALIASES) | set(MOUSE_EVENTS))
# 主框架
main_frame = ttk.Frame(self.top)
main_frame.pack(fill='both', expand=True, padx=10, pady=10)
# 文本编辑区与行号
text_frame = ttk.Frame(main_frame)
text_frame.pack(fill='both', expand=True)
self.text = tk.Text(text_frame, wrap=tk.WORD, font=('Consolas', 10), undo=True)
self.text.pack(side='right', fill='both', expand=True)
self.line_numbers = LineNumberCanvas(text_frame, self.text, bg='#f0f0f0', highlightthickness=0)
self.line_numbers.pack(side='left', fill='y')
self._syntax_after_id = None
# 垂直滚动条
scrollbar = ttk.Scrollbar(main_frame, orient='vertical', command=self.text.yview)
self.text.configure(yscrollcommand=lambda *args: (scrollbar.set(*args), self.line_numbers.redraw()))
scrollbar.pack(side='right', fill='y')
# 状态栏(显示错误信息)
self.status_var = tk.StringVar(value="就绪")
status_bar = ttk.Label(main_frame, textvariable=self.status_var, relief='sunken', anchor='w', font=('微软雅黑', 9))
status_bar.pack(side='bottom', fill='x', pady=(5, 0))
# 按钮栏
btn_frame = ttk.Frame(main_frame)
btn_frame.pack(side='bottom', fill='x', pady=(5, 0))
ttk.Button(btn_frame, text="保存", command=self._on_save).pack(side='right', padx=5)
ttk.Button(btn_frame, text="取消", command=self._on_cancel).pack(side='right', padx=5)
ttk.Button(btn_frame, text="检查语法", command=self.check_syntax).pack(side='left', padx=5)
# 设置语法高亮标签
self.text.tag_configure('keyword', foreground='#0000cc', font=('Consolas', 10, 'bold'))
self.text.tag_configure('comment', foreground='#008000')
self.text.tag_configure('error', underline=True, underlinefg='red')
self.text.tag_configure('modifier', foreground='#aa5500')
# 绑定事件
self.text.bind('<KeyRelease>', self.on_key_release)
self.text.bind('<Return>', self.handle_return)
self.text.bind('<space>', self.on_key_release)
self.text.bind('<Control-space>', self.show_autocomplete)
self.text.bind('<Tab>', self.handle_tab)
self.text.bind('<Down>', self.handle_down)
self.text.bind('<Up>', self.handle_up)
self.top.protocol("WM_DELETE_WINDOW", self._on_cancel)
# 自动补全实例
self.autocomplete = AutocompleteListbox(
self.top,
self.text,
self.keywords + self.modifiers + self.key_names,
on_select_callback=self.after_programmatic_edit
)
# 插入帮助模板
self.insert_help_template(initial_script)
# 初始语法检查
self.top.after(100, self.check_syntax)
center_window(self.top, 700, 500)
@classmethod
def strip_help_template(cls, script):
cleaned = script or ''
marker_start = "# ========== 指令参考 =========="
marker_end = "# ==============================="
while cleaned.lstrip().startswith(marker_start):
leading_spaces = len(cleaned) - len(cleaned.lstrip())
end_idx = cleaned.find(marker_end)
if end_idx == -1:
break
end_idx += len(marker_end)
if end_idx < len(cleaned) and cleaned[end_idx:end_idx + 2] == '\r\n':
end_idx += 2
elif end_idx < len(cleaned) and cleaned[end_idx] == '\n':
end_idx += 1
cleaned = cleaned[:leading_spaces] + cleaned[end_idx:].lstrip('\r\n')
return cleaned
def insert_help_template(self, initial_script):
clean_script = self.strip_help_template(initial_script).strip()
if clean_script:
self.text.insert('1.0', clean_script)
else:
self.text.insert('1.0', self.HELP_TEMPLATE)
self.text.insert(tk.END, "# 示例:\n# tap e\n# wait 100\n# loop 3\n# combo ctrl c\n# wait 50\n# end\n")
self.highlight_syntax()
def on_key_release(self, event=None):
self.highlight_syntax()
self.line_numbers.redraw()
if self._syntax_after_id is not None:
self.top.after_cancel(self._syntax_after_id)
self._syntax_after_id = self.top.after(300, self._check_syntax_scheduled)
ignored = {'Escape', 'Return', 'Tab', 'Up', 'Down', 'Left', 'Right'}
if event is None or event.keysym not in ignored:
self.top.after(1, self.show_autocomplete)
def _check_syntax_scheduled(self):
self._syntax_after_id = None
self.check_syntax()
def after_programmatic_edit(self):
self.highlight_syntax()
self.line_numbers.redraw()
self.check_syntax()
def highlight_syntax(self):
# 清除所有标签
for tag in ('keyword', 'comment', 'modifier'):
self.text.tag_remove(tag, '1.0', tk.END)
content = self.text.get('1.0', tk.END)
lines = content.splitlines()
for i, line in enumerate(lines):
line_num = i + 1
# 注释高亮
if '#' in line:
idx = line.index('#')
start = f"{line_num}.{idx}"
end = f"{line_num}.end"
self.text.tag_add('comment', start, end)
# 关键字高亮
words = line.split()
col = 0
for word in words:
# 忽略注释部分
if '#' in word:
break
clean_word = word.strip('(),:')
if clean_word in self.keywords:
# 找到单词在行中的准确位置
start_col = line.find(clean_word, col)
if start_col != -1:
start = f"{line_num}.{start_col}"
end = f"{line_num}.{start_col + len(clean_word)}"
self.text.tag_add('keyword', start, end)
elif clean_word in self.modifiers:
start_col = line.find(clean_word, col)
if start_col != -1:
start = f"{line_num}.{start_col}"
end = f"{line_num}.{start_col + len(clean_word)}"
self.text.tag_add('modifier', start, end)
col += len(word) + 1
def check_syntax(self):
"""实时编译检查,标记错误行"""
self.text.tag_remove('error', '1.0', tk.END)
script = self.text.get('1.0', tk.END).strip()
if not script:
self.status_var.set("就绪")
return
from script_compiler import ScriptCompiler
compiler = ScriptCompiler()
_, errors = compiler.compile(script)
if errors:
# 解析错误行号
for err in errors:
# 错误格式: "第 X 行: ..."
match = re.search(r'第 (\d+) 行', err)
if match:
line_num = int(match.group(1))
start = f"{line_num}.0"
end = f"{line_num}.end"
self.text.tag_add('error', start, end)
self.status_var.set(errors[0] if errors else "语法错误")
else:
self.status_var.set("语法正确")
def get_autocomplete_context(self):
cursor_pos = self.text.index('insert')
line_start = cursor_pos.split('.')[0] + '.0'
line_text = self.text.get(line_start, cursor_pos)
trailing_space = bool(line_text) and line_text[-1].isspace()
tokens = line_text.split()
prefix = '' if trailing_space or not tokens else tokens[-1].lower()
command = tokens[0].lower() if tokens else ''
if not tokens or (len(tokens) == 1 and not trailing_space):
candidates = self.keywords
elif command in ('press', 'release', 'tap', 'combo'):
candidates = self.key_names
elif command == 'wait':
candidates = ['10', '20', '30', '50', '100', '200', '500', '1000']
elif command == 'loop':
candidates = ['0', 'infinite', '1', '2', '3', '5', '10']
elif command in ('drag', 'drag_rel'):
candidates = ['left', 'right', 'middle', 'mouse']
elif command == 'setpos':
candidates = ['mouse']
elif command in ('end',):
candidates = []
else:
candidates = self.keywords + self.modifiers + self.key_names
return cursor_pos, prefix, candidates
def show_autocomplete(self, event=None):
cursor_pos, prefix, candidates = self.get_autocomplete_context()
# 获取光标屏幕坐标
bbox = self.text.bbox(cursor_pos)
if bbox:
x, y, width, height = bbox
x_root = self.text.winfo_rootx() + x
y_root = self.text.winfo_rooty() + y + height
self.autocomplete.show(x_root, y_root, prefix, candidates)
return 'break'
def handle_tab(self, event):
# 如果有自动补全显示,则选择第一项
if self.autocomplete.winfo_viewable():
self.autocomplete.on_select()
return 'break'
# 否则插入制表符
self.text.insert('insert', ' ')
return 'break'
def handle_return(self, event):
self.autocomplete.withdraw()
def handle_down(self, event):
if self.autocomplete.move_selection(1):
return 'break'
def handle_up(self, event):
if self.autocomplete.move_selection(-1):
return 'break'
def _on_save(self):
self.check_syntax()
if '错误' in self.status_var.get() or '语法错误' in self.status_var.get():
messagebox.showerror("语法错误", "脚本存在语法错误,请修正后再保存。")
return
script = self.strip_help_template(self.text.get('1.0', tk.END)).strip()
if self.callback:
self.callback(script)
self._close()
def _on_cancel(self):
self._close()
def _close(self):
if self._closed:
return
self._closed = True
try:
self.autocomplete.destroy()
except Exception:
pass
self.top.destroy()
if self.on_close:
self.on_close()
class LogWindow:
def __init__(self, parent):
self.top = tk.Toplevel(parent)
self.top.title("运行日志")
self.top.geometry("500x300")
self.top.transient(parent)
self.log_text = scrolledtext.ScrolledText(self.top, state='disabled', wrap=tk.WORD)
self.log_text.pack(fill='both', expand=True)
center_window(self.top, 500, 300)
def log(self, message):
self.log_text.config(state='normal')
self.log_text.insert(tk.END, f"[{time.strftime('%H:%M:%S')}] {message}\n")
self.log_text.see(tk.END)
self.log_text.config(state='disabled')
class MapperGUI:
def __init__(self):
self.mapper = KeyMapper()
self.mapper_thread = None
self.hotkey = 'ctrl+shift+f12'
self.log_window = None
self._capture_dialog_active = False
self._capture_dialog_cooldown_until = 0
self._dialog_pause_depth = 0
self._dialog_pause_previous_enabled = None
self._config_load_error = None
self._config_migrated_from = None
self._game_status_after_id = None
self.config_name = DEFAULT_CONFIG_NAME
_, self._config_migrated_from = ensure_user_config_path()
self.config_path = get_config_path_for(self.config_name)
self.load_config()
self.root = tk.Tk()
self.root.title("BA KeySmith")
self.root.geometry("960x680")
self.root.minsize(880, 620)
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.setup_styles()
self.create_widgets()
self.refresh_config_list()
self.refresh_table()
center_window(self.root, 960, 680)
if self._config_load_error:
self.root.after(100, lambda: messagebox.showwarning("配置读取失败", self._config_load_error))
if self._config_migrated_from:
self.root.after(150, lambda: messagebox.showinfo(
"配置已迁移",
"已将旧配置迁移到用户数据目录。\n"
f"新位置:{self.config_path}"
))
self.update_game_status()
def setup_styles(self):
style = ttk.Style()
style.theme_use('clam')
self.colors = {
'bg': '#eef3f8',
'surface': '#ffffff',
'surface_soft': '#f8fafc',
'ink': '#172033',
'muted': '#64748b',
'border': '#dbe5ef',
'accent': '#2563eb',
'accent_hover': '#1d4ed8',
'success': '#16a34a',
'warning': '#d97706',
'danger': '#dc2626',
}
base_font = ('Microsoft YaHei UI', 9)
title_font = ('Microsoft YaHei UI', 18, 'bold')
section_font = ('Microsoft YaHei UI', 10, 'bold')
self.root.configure(bg=self.colors['bg'])
style.configure('.', font=base_font)
style.configure('TFrame', background=self.colors['bg'])
style.configure('App.TFrame', background=self.colors['bg'])
style.configure('Surface.TFrame', background=self.colors['surface'])
style.configure('TLabel', background=self.colors['bg'], foreground=self.colors['ink'], font=base_font)
style.configure('Card.TLabel', background=self.colors['surface'], foreground=self.colors['ink'], font=base_font)
style.configure('Title.TLabel', background=self.colors['bg'], foreground=self.colors['ink'], font=title_font)
style.configure('Subtitle.TLabel', background=self.colors['bg'], foreground=self.colors['muted'], font=('Microsoft YaHei UI', 9))
style.configure('Muted.TLabel', background=self.colors['surface'], foreground=self.colors['muted'], font=('Microsoft YaHei UI', 8))
style.configure('TLabelframe', background=self.colors['surface'], foreground=self.colors['ink'], borderwidth=1, relief='solid')
style.configure('TLabelframe.Label', background=self.colors['surface'], foreground=self.colors['ink'], font=section_font)
style.configure('Card.TLabelframe', background=self.colors['surface'], foreground=self.colors['ink'], borderwidth=1, relief='solid')
style.configure('Card.TLabelframe.Label', background=self.colors['surface'], foreground=self.colors['ink'], font=section_font)
style.configure('TButton', font=base_font, padding=(12, 7), borderwidth=0)
style.configure('Accent.TButton', background=self.colors['accent'], foreground='white')
style.map('Accent.TButton', background=[('active', self.colors['accent_hover']), ('disabled', '#a7b8d8')], foreground=[('disabled', '#eef2ff')])
style.configure('Ghost.TButton', background=self.colors['surface_soft'], foreground=self.colors['ink'])
style.map('Ghost.TButton', background=[('active', '#e2e8f0'), ('disabled', '#f1f5f9')])
style.configure('Danger.TButton', background='#fee2e2', foreground=self.colors['danger'])
style.map('Danger.TButton', background=[('active', '#fecaca'), ('disabled', '#f8fafc')])
style.configure('Status.TLabel', background=self.colors['surface'], foreground=self.colors['muted'], padding=(10, 5), font=('Microsoft YaHei UI', 9, 'bold'))
style.configure('Idle.Status.TLabel', background='#e2e8f0', foreground='#334155', padding=(10, 5), font=('Microsoft YaHei UI', 9, 'bold'))
style.configure('Running.Status.TLabel', background='#dcfce7', foreground='#166534', padding=(10, 5), font=('Microsoft YaHei UI', 9, 'bold'))
style.configure('Paused.Status.TLabel', background='#fee2e2', foreground='#991b1b', padding=(10, 5), font=('Microsoft YaHei UI', 9, 'bold'))
style.configure('Editing.Status.TLabel', background='#fef3c7', foreground='#92400e', padding=(10, 5), font=('Microsoft YaHei UI', 9, 'bold'))
style.configure('Treeview', background=self.colors['surface'], fieldbackground=self.colors['surface'], foreground=self.colors['ink'], rowheight=32, borderwidth=0, font=('Microsoft YaHei UI', 9))
style.configure('Treeview.Heading', background='#e8f0fb', foreground=self.colors['ink'], font=('Microsoft YaHei UI', 9, 'bold'), padding=(8, 8))
style.map('Treeview', background=[('selected', '#dbeafe')], foreground=[('selected', '#1e3a8a')])
style.configure('TEntry', fieldbackground='white', padding=(8, 5))
style.configure('TCombobox', fieldbackground='white', padding=(8, 5))
def load_config(self):
try:
with open(self.config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
self.mappings = [
self.normalize_mapping_entry(mapping)
for mapping in config.get('mappings', [])
if isinstance(mapping, dict) and mapping.get('trigger')
]
self.hotkey = config.get('hotkey', 'ctrl+shift+f12')
except FileNotFoundError:
self.mappings = []
self.hotkey = 'ctrl+shift+f12'
except json.JSONDecodeError as e:
self.mappings = []
self.hotkey = 'ctrl+shift+f12'
self._config_load_error = (
f"{self.config_path} 格式有误,已临时使用空配置。\n"
f"错误位置:第 {e.lineno} 行,第 {e.colno} 列。"
)
@staticmethod
def normalize_mapping_entry(mapping):
normalized = dict(mapping)
if 'trigger' in normalized:
normalized['trigger'] = normalize_key_name(normalized['trigger'])
if normalized.get('type', 'simple') == 'simple' and 'target' in normalized:
normalized['target'] = normalize_key_name(normalized['target'])
return normalized
def refresh_config_list(self):
configs = list_configs()
current_value = self.config_name
names = [name for name, _ in configs]
self.config_combo['values'] = names
if current_value in names:
self.config_combo.set(current_value)
else:
self.config_combo.set(DEFAULT_CONFIG_NAME)
self.config_name = DEFAULT_CONFIG_NAME
self.config_path = get_config_path_for(self.config_name)
self.load_config()
self.refresh_table()
self._update_config_btns()
def _update_config_btns(self):
is_default = self.config_name == DEFAULT_CONFIG_NAME
new_state = 'disabled' if is_default else 'normal'
self.btn_rename_config.config(state=new_state)
self.btn_delete_config.config(state=new_state)
def on_config_selected(self, event=None):
selected = self.config_combo.get()
if not selected or selected == self.config_name:
return
self.switch_config(selected)
def switch_config(self, name):
if name == self.config_name:
return
was_running = self.mapper.running
if was_running:
self.stop_mapper()
self.save_config()
self.config_name = name
self.config_path = get_config_path_for(self.config_name)
self._config_load_error = None
self.mappings = []
self.load_config()
self.refresh_table()
self.hotkey_label.config(text=f"开关热键: {self.hotkey}")
self.log(f"已切换到配置方案: {self.config_name}")
if self._config_load_error:
self.root.after(50, lambda: messagebox.showwarning("配置读取失败", self._config_load_error))
if was_running:
self.start_mapper()
self._update_config_btns()
def create_new_config(self):
pause_token = self._pause_mapper_for_dialog()
dialog = tk.Toplevel(self.root)
dialog.title("新建配置方案")
dialog.resizable(False, False)
dialog.transient(self.root)
dialog.grab_set()
main = ttk.Frame(dialog, padding=20)
main.pack(fill='both', expand=True)
ttk.Label(main, text="请输入新配置方案的名称", font=('Microsoft YaHei UI', 10, 'bold')).pack(anchor='w', pady=(0, 10))
name_var = tk.StringVar()
name_entry = ttk.Entry(main, textvariable=name_var, width=36)
name_entry.pack(fill='x', pady=(0, 10))
existing = [name for name, _ in list_configs()]
BLANK_OPTION = "-- 空白方案 --"
ttk.Label(main, text="基于现有方案复制(可选):", style='Card.TLabel').pack(anchor='w', pady=(0, 4))
source_var = tk.StringVar(value=BLANK_OPTION)
source_combo_values = [BLANK_OPTION] + existing
source_combo = ttk.Combobox(main, textvariable=source_var, values=source_combo_values, state='readonly', width=34)
source_combo.pack(fill='x', pady=(0, 14))
def on_ok():
name = name_var.get().strip()
if not name:
messagebox.showerror("错误", "名称不能为空", parent=dialog)
return
if name in existing:
messagebox.showerror("错误", f"配置方案 '{name}' 已存在", parent=dialog)
return
try:
source = None if source_var.get() == BLANK_OPTION else source_var.get().strip()
create_config(name, source_name=source)
self.refresh_config_list()
self.switch_config(name)
dialog.destroy()
except ValueError as e:
messagebox.showerror("错误", str(e), parent=dialog)
sep = ttk.Separator(main, orient='horizontal')
sep.pack(fill='x', pady=(6, 10))
btn_frame = ttk.Frame(main)
btn_frame.pack(fill='x')
ttk.Button(btn_frame, text="创建方案", command=on_ok, style='Accent.TButton', width=14).pack(side='right', padx=(10, 0))
ttk.Button(btn_frame, text="取消", command=dialog.destroy, width=10).pack(side='right')
dialog.update_idletasks()
w = max(400, dialog.winfo_reqwidth() + 20)
h = max(220, dialog.winfo_reqheight() + 20)
dialog.minsize(w, h)
center_window(dialog, w, h)