-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslation_workbench.py
More file actions
3672 lines (3065 loc) · 163 KB
/
translation_workbench.py
File metadata and controls
3672 lines (3065 loc) · 163 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
import tkinter as tk
from tkinter import scrolledtext, messagebox, filedialog, simpledialog
from tkinter import ttk as tk_ttk
import ttkbootstrap as ttk
from collections import defaultdict
import json
from datetime import datetime
from pathlib import Path
import threading
import itertools
from concurrent.futures import ThreadPoolExecutor, as_completed
import logging
import re
import copy
import uuid
from utils import config_manager
from services.ai_translator import AITranslator
from gui import ui_utils
from gui.custom_widgets import ToolTip
from gui.find_replace_dialog import FindReplaceDialog
from core.term_database import TermDatabase
class TranslationWorkbench(ttk.Frame):
def __init__(self, parent_frame, initial_data: dict, namespace_formats: dict, raw_english_files: dict, current_settings: dict, log_callback=None, project_path: str | None = None, finish_button_text: str = "完成", finish_callback=None, cancel_callback=None, project_name: str = "Unnamed_Project", main_window_instance=None, undo_history: dict = None, module_names: list = None):
super().__init__(parent_frame)
self.translation_data = initial_data
self.namespace_formats = namespace_formats
self.raw_english_files = raw_english_files
self.current_settings = current_settings
self.module_names = module_names or []
self.log_callback = log_callback or (lambda msg, lvl: None)
self.finish_callback = finish_callback
self.cancel_callback = cancel_callback
self.project_name = project_name
self.main_window = main_window_instance
# 初始化术语库
self.term_db = TermDatabase()
# 术语提示优化:防抖机制
self._term_update_id = None
self._last_term_update_time = 0
self._term_update_delay = 100 # 延迟100ms执行术语匹配
# 术语匹配结果缓存 - 使用OrderedDict实现LRU缓存
from collections import OrderedDict
self._term_match_cache = OrderedDict()
self._term_cache_max_size = 1000 # 缓存最大条目数
# 术语搜索线程控制
self._current_term_thread = None
self._term_search_cancelled = False
self._current_search_id = 0
# AI翻译取消控制
self._ai_translation_cancelled = False
# 当前的AI翻译器实例
self._current_translator = None
# 当前的AI翻译线程池
self._current_ai_executor = None
# 线程池管理
from concurrent.futures import ThreadPoolExecutor
self._thread_pool = ThreadPoolExecutor(max_workers=2, thread_name_prefix="ModpackLocalizer")
self.final_translations = None
self.current_selection_info = None
self.sort_column = '#0'
self.sort_reverse = False
self.original_headings = {}
self.current_project_path = project_path
self.is_dirty = False
# 操作记录系统
self.operation_history = [] # 操作历史记录
self.max_history_size = 100 # 最大历史记录数量
self.last_operation_time = 0 # 上次操作时间
self.operation_merge_window = 2.0 # 操作合并窗口(秒)
self.current_state_index = 0 # 当前状态在操作历史中的索引
# 操作类型定义
self.OPERATION_TYPES = {
'INIT': '初始化',
'EDIT': '文本编辑',
'REPLACE': '替换操作',
'REPLACE_ALL': '全部替换',
'IMPORT': '导入数据',
'AI_TRANSLATION': 'AI翻译',
'BATCH_PROCESS': '批量处理',
'DICTIONARY_ADD': '添加词典',
'REDO': '重做操作',
'OTHER': '其他操作'
}
self.finish_button_text = finish_button_text
# 新增UI优化相关状态
self._is_navigating = False
self._last_navigation_time = 0
self._keyboard_shortcuts_enabled = True
self._double_click_to_approve = self.current_settings.get('double_click_to_approve', True)
self._enter_to_navigate = self.current_settings.get('enter_to_navigate', True)
self._focus_on_translate = self.current_settings.get('focus_on_translate', True)
# 翻译控制台功能整合相关变量
self._current_mode = "workbench" # "workbench" 或 "comprehensive"
self._comprehensive_ui = None
self._create_widgets()
# 立即设置初始sash位置,确保在所有情况下都能保持1:3的比例
self._set_initial_sash_position()
# 同时在idle时再次检查,确保窗口完全初始化后比例正确
self.after_idle(self._set_initial_sash_position)
# 初始化操作历史(不记录为用户操作)
# 添加初始状态作为历史记录的基础
import uuid
initial_state = {
'id': str(uuid.uuid4()),
'type': 'INIT',
'description': '初始化',
'timestamp': datetime.now().isoformat(),
'target_iid': None,
'details': {'project_name': self.project_name},
'state': copy.deepcopy(self.translation_data)
}
self.operation_history = [initial_state]
self._update_history_buttons()
self.bind_all("<Control-z>", self.undo)
self.bind_all("<Control-y>", self.redo)
self.bind_all("<Control-s>", lambda e: self._save_project())
self._setup_treeview_tags()
self._populate_namespace_tree()
self._update_ui_state(interactive=True, item_selected=False)
self._set_dirty(False)
self.bind("<Map>", self._on_mapped, add="+")
def get_state(self):
return {
"project_name": self.project_name,
"workbench_data": self.translation_data,
"namespace_formats": self.namespace_formats,
"raw_english_files": self.raw_english_files,
"current_project_path": self.current_project_path,
}
def _set_initial_sash_position(self):
try:
self.update_idletasks()
width = self.winfo_width()
# 设置为窗口宽度的25%,保持1:3的比例,但不小于330像素,确保能显示所有列
initial_pos = max(int(width * 0.25), 330)
if initial_pos > 50:
self.main_pane.sashpos(0, initial_pos)
except tk.TclError:
pass
def _on_mapped(self, event=None):
"""工作台映射到屏幕时,根据真实宽度修正分割条。"""
try:
self._set_initial_sash_position()
except Exception:
pass
def _create_widgets(self):
self.main_pane = tk_ttk.PanedWindow(self, orient=tk.HORIZONTAL)
self.main_pane.pack(fill="both", expand=True, padx=5, pady=(5, 0))
self.left_frame = ttk.Frame(self.main_pane, padding=5)
ttk.Label(self.left_frame, text="模组/任务列表", bootstyle="primary").pack(anchor="w", pady=(0, 5))
# 创建左侧项目列表
self.ns_tree = ttk.Treeview(self.left_frame, columns=("pending", "completed"), show="tree headings")
# 添加垂直滚动条
v_scrollbar = ttk.Scrollbar(self.left_frame, orient=tk.VERTICAL, command=self.ns_tree.yview)
self.ns_tree.configure(yscrollcommand=v_scrollbar.set)
# 定义列配置,调整项目列宽度,让已翻译列能正常显示
column_config = {
"#0": {"text": "项目", "width": 150, "minwidth": 120, "stretch": True},
"pending": {"text": "待翻译", "width": 80, "minwidth": 80, "stretch": False, "anchor": "center"},
"completed": {"text": "已翻译", "width": 80, "minwidth": 80, "stretch": False, "anchor": "center"}
}
# 配置列标题和属性
for col, config in column_config.items():
self.original_headings[col] = config["text"]
self.ns_tree.heading(col, text=config["text"], command=lambda c=col: self._sort_by_column(c))
column_kwargs = {
'minwidth': config["minwidth"],
'stretch': config["stretch"],
'anchor': config.get("anchor", "w")
}
if config.get("width") is not None:
column_kwargs['width'] = config["width"]
self.ns_tree.column(col, **column_kwargs)
# 布局Treeview和滚动条
self.ns_tree.pack(side="left", fill="both", expand=True)
v_scrollbar.pack(side="right", fill="y")
# 初始绑定事件处理函数
self.ns_tree.bind("<<TreeviewSelect>>", self._on_namespace_selected)
# 添加到主面板
self.main_pane.add(self.left_frame, weight=1)
right_frame_container = ttk.Frame(self.main_pane)
self.main_pane.add(right_frame_container, weight=3)
# 保存右侧容器引用,用于切换
self.right_frame_container = right_frame_container
# 创建工作区UI容器
self.workbench_ui_container = ttk.Frame(right_frame_container)
self.workbench_ui_container.pack(fill="both", expand=True)
right_pane = tk_ttk.PanedWindow(self.workbench_ui_container, orient=tk.VERTICAL)
right_pane.pack(fill="both", expand=True)
table_container = ttk.Frame(right_pane, padding=5)
self.trans_tree = ttk.Treeview(table_container, columns=("key", "english", "chinese", "source"), show="headings")
self.trans_tree.heading("key", text="原文键", command=lambda: self._sort_items_by_default_order())
self.trans_tree.column("key", width=200, stretch=False)
self.trans_tree.heading("english", text="原文"); self.trans_tree.column("english", width=250, stretch=True)
self.trans_tree.heading("chinese", text="译文"); self.trans_tree.column("chinese", width=250, stretch=True)
self.trans_tree.heading("source", text="来源", command=lambda: self._sort_items_by_source())
self.trans_tree.column("source", width=120, stretch=False)
self.trans_items_sort_reverse = False
self.source_sort_reverse = False
scrollbar = ttk.Scrollbar(table_container, orient="vertical", command=self.trans_tree.yview)
self.trans_tree.configure(yscrollcommand=scrollbar.set)
scrollbar.pack(side="right", fill="y"); self.trans_tree.pack(fill="both", expand=True)
self.trans_tree.bind("<<TreeviewSelect>>", self._on_item_selected)
right_pane.add(table_container, weight=3)
editor_frame = tk_ttk.LabelFrame(right_pane, text="翻译编辑器", padding=10)
editor_frame.columnconfigure(1, weight=1)
# 创建原文和术语提示的并列布局
content_frame = ttk.Frame(editor_frame)
content_frame.grid(row=0, column=1, sticky="nsew", padx=5, pady=5)
content_frame.columnconfigure(0, weight=1)
content_frame.columnconfigure(1, weight=1)
content_frame.rowconfigure(0, weight=1)
# 左侧:原文显示
en_container = ttk.Frame(content_frame)
en_container.grid(row=0, column=0, sticky="nsew", padx=(0, 5))
en_container.rowconfigure(1, weight=1)
en_container.columnconfigure(0, weight=1)
ttk.Label(en_container, text="原文:", anchor="nw").grid(row=0, column=0, sticky="nw", padx=0, pady=0)
style = ttk.Style.get_instance()
theme_bg_color = style.lookup('TFrame', 'background')
theme_fg_color = style.lookup('TLabel', 'foreground')
self.en_text_display = scrolledtext.ScrolledText(
en_container, height=5, wrap=tk.WORD, relief="flat",
background=theme_bg_color, foreground=theme_fg_color
)
self.en_text_display.bind("<KeyPress>", lambda e: "break")
# 添加复制事件处理,允许复制原文
self.en_text_display.bind("<Control-c>", self._on_copy_en)
self.en_text_display.bind("<Control-C>", self._on_copy_en)
self.en_text_display.grid(row=1, column=0, sticky="nsew", padx=0, pady=5)
# 右侧:术语提示
term_container = ttk.Frame(content_frame)
term_container.grid(row=0, column=1, sticky="nsew", padx=(5, 0))
term_container.rowconfigure(1, weight=1)
term_container.columnconfigure(0, weight=1)
ttk.Label(term_container, text="术语提示:", anchor="nw").grid(row=0, column=0, sticky="nw", padx=0, pady=0)
self.term_text = scrolledtext.ScrolledText(
term_container, height=5, wrap=tk.WORD, relief="flat",
background=theme_bg_color, foreground=theme_fg_color, state="disabled"
)
self.term_text.grid(row=1, column=0, sticky="nsew", padx=0, pady=5)
# 译文输入区域
zh_header_frame = ttk.Frame(editor_frame); zh_header_frame.grid(row=1, column=1, sticky="ew", padx=5, pady=(5,0))
ttk.Label(zh_header_frame, text="译文:", anchor="nw").pack(side="left")
shortcut_info_label = ttk.Label(zh_header_frame, text="快捷键: Enter 跳转到下一条, Ctrl+Enter 跳转到下一条待翻译")
shortcut_info_label.pack(side="right")
self.zh_text_input = scrolledtext.ScrolledText(editor_frame, height=5, wrap=tk.WORD, state="disabled")
# 确保译文栏水平填充整个可用空间
self.zh_text_input.grid(row=2, column=1, sticky="nsew", padx=5, pady=5)
# 延迟保存机制
self._text_modified_timer = None
self._text_modified_delay = 500 # 延迟500ms执行保存
def _on_key_release(event):
"""合并的按键释放事件处理函数"""
self._on_text_modified_delayed(event)
self._update_term_suggestions(event)
self.zh_text_input.bind("<KeyRelease>", _on_key_release)
self.zh_text_input.bind("<FocusOut>", lambda e: self._save_current_edit())
self.zh_text_input.bind("<Return>", self._save_and_jump_sequential)
self.zh_text_input.bind("<Control-Return>", self._save_and_jump_pending)
# 添加复制事件处理,确保只复制实际文本
self.zh_text_input.bind("<Control-c>", self._on_copy)
self.zh_text_input.bind("<Control-C>", self._on_copy)
editor_btn_frame = ttk.Frame(editor_frame); editor_btn_frame.grid(row=3, column=1, sticky="ew", pady=(5,0))
editor_btn_frame.columnconfigure(0, weight=1)
# 右侧框架 - 放置其他按钮
right_frame = ttk.Frame(editor_btn_frame)
right_frame.grid(row=0, column=0, sticky="e")
# 优化按钮布局,按操作频率和逻辑顺序排列
btn_padding = 5 # 按钮间距
# 其他按钮(居右)
self.add_to_dict_btn = ttk.Button(right_frame, text="添加到词典", command=self._add_to_user_dictionary, state="disabled", bootstyle="info-outline")
self.add_to_dict_btn.pack(side="right", padx=(btn_padding, 0))
# 添加分隔符
separator3 = ttk.Separator(right_frame, orient="vertical")
separator3.pack(side="right", fill="y", padx=(btn_padding, btn_padding))
self.history_btn = ttk.Button(right_frame, text="操作历史", command=self._show_operation_history, bootstyle="info-outline")
self.history_btn.pack(side="right", padx=(btn_padding, btn_padding))
ToolTip(self.history_btn, "查看和管理操作历史")
# 导入 JSON 按钮(与操作历史同一列,居左)
self.import_json_button = ttk.Button(right_frame, text="导入 JSON", command=self._import_current_namespace_json, bootstyle="info-outline")
self.import_json_button.pack(side="left", padx=(btn_padding, btn_padding))
ToolTip(self.import_json_button, "从 JSON 文件导入翻译到当前模组")
# 导出 JSON 按钮(与操作历史同一列,居左)
self.export_json_button = ttk.Button(right_frame, text="导出 JSON", command=self._export_current_namespace_json, bootstyle="info-outline")
self.export_json_button.pack(side="left", padx=(btn_padding, btn_padding))
ToolTip(self.export_json_button, "导出当前模组的语言文件为 JSON 格式")
# 添加分隔符
separator2 = ttk.Separator(right_frame, orient="vertical")
separator2.pack(side="right", fill="y", padx=(btn_padding, btn_padding))
self.redo_btn = ttk.Button(right_frame, text="重做", command=self.redo, bootstyle="info-outline")
self.redo_btn.pack(side="right", padx=(btn_padding, btn_padding))
ToolTip(self.redo_btn, "重做已撤销的操作 (Ctrl+Y)")
self.undo_btn = ttk.Button(right_frame, text="撤销", command=self.undo, bootstyle="info-outline")
self.undo_btn.pack(side="right", padx=(0, btn_padding))
ToolTip(self.undo_btn, "撤销上一步操作 (Ctrl+Z)")
# 添加分隔符
separator1 = ttk.Separator(right_frame, orient="vertical")
separator1.pack(side="right", fill="y", padx=(btn_padding, btn_padding))
right_pane.add(editor_frame, weight=1)
# 创建翻译控制台UI容器,初始隐藏
self.comprehensive_ui_container = ttk.Frame(self.right_frame_container)
self.comprehensive_ui_container.pack(fill="both", expand=True)
self.comprehensive_ui_container.pack_forget()
# 创建上传到汉化仓库UI容器,初始隐藏
self.github_upload_ui_container = ttk.Frame(self.right_frame_container)
self.github_upload_ui_container.pack(fill="both", expand=True)
self.github_upload_ui_container.pack_forget()
btn_frame = ttk.Frame(self, padding=10)
btn_frame.pack(fill="x")
# 左侧状态显示区域
status_container = ttk.Frame(btn_frame)
status_container.pack(side="left", fill="x", expand=True)
# 主状态标签
self.status_label = ttk.Label(status_container, text="请选择一个项目以开始")
self.status_label.pack(side="left", fill="x", expand=True)
# 翻译状态显示标签
# 功能切换按钮
self.mode_switch_btn = ttk.Button(btn_frame, text="进入翻译控制台", command=self._toggle_mode, state="disabled", bootstyle="primary")
self.mode_switch_btn.pack(side="right")
ToolTip(self.mode_switch_btn, "在翻译工作台和翻译控制台功能之间切换")
self.save_button = ttk.Button(btn_frame, text="保存项目", command=self._save_project, bootstyle="primary-outline")
self.save_button.pack(side="right", padx=5)
self.finish_button = ttk.Button(btn_frame, text=self.finish_button_text, command=self._on_finish, bootstyle="success")
self.finish_button.pack(side="right", padx=5)
# 上传到汉化仓库按钮 - 放在最左边
self.github_upload_button = ttk.Button(btn_frame, text="上传到 GitHub", command=self._on_github_upload, bootstyle="warning")
self.github_upload_button.pack(side="right")
ToolTip(self.github_upload_button, "进入 GitHub 汉化仓库上传界面")
def _update_theme_colors(self):
style = ttk.Style.get_instance()
theme_bg_color = style.lookup('TFrame', 'background')
theme_fg_color = style.lookup('TLabel', 'foreground')
self.en_text_display.config(background=theme_bg_color, foreground=theme_fg_color)
def _get_searchable_items(self, scope):
if scope == 'current':
selection = self.ns_tree.selection()
if not selection:
messagebox.showwarning("范围错误", "请先在左侧选择一个项目以确定搜索范围。", parent=self)
return []
return self.trans_tree.get_children()
else:
# 使用列表推导式代替显式循环,提高性能
return [
f"{ns_iid}___{idx}"
for ns_iid in self.ns_tree.get_children()
for idx, item in enumerate(self.translation_data.get(ns_iid, {}).get('items', []))
if item.get('en', '').strip()
]
def _safe_select_item(self, iid):
if self.trans_tree.exists(iid):
self.trans_tree.selection_set(iid)
def _safe_select_item_and_update_ui(self, iid):
"""安全地选择项目并更新UI"""
if self.trans_tree.exists(iid):
# 先获取条目信息
ns, idx = self._get_ns_idx_from_iid(iid)
if ns is not None:
item_data = self.translation_data[ns]['items'][idx]
# 先更新当前选择信息
self.current_selection_info = {'ns': ns, 'idx': idx, 'row_id': iid}
# 解绑文本修改事件,避免设置编辑器内容时触发保存逻辑
self.zh_text_input.unbind("<KeyRelease>")
self.zh_text_input.unbind("<FocusOut>")
# 先更新编辑器内容,避免触发保存逻辑
self._set_editor_content(item_data['en'], item_data.get('zh', ''))
# 清除编辑器的修改标记
self.zh_text_input.edit_modified(False)
# 重新绑定文本修改事件
def _on_key_release(event):
"""合并的按键释放事件处理函数"""
self._on_text_modified(event)
self._update_term_suggestions(event)
self.zh_text_input.bind("<KeyRelease>", _on_key_release)
self.zh_text_input.bind("<FocusOut>", lambda e: self._save_current_edit())
# 选择项目
self.trans_tree.selection_set(iid)
self.trans_tree.focus(iid)
self.trans_tree.see(iid)
# 更新UI状态,确保按钮可用
self._update_ui_state(interactive=True, item_selected=True)
self.zh_text_input.focus_set()
# 显示匹配的术语
self._show_matching_terms(item_data['en'])
def _restore_item_selection(self):
"""根据保存的信息重新选中条目"""
if not hasattr(self, '_workbench_item_selection') or not self._workbench_item_selection:
return
selection_info = self._workbench_item_selection
ns = selection_info['ns']
idx = selection_info['idx']
# 检查命名空间是否存在
if not self.ns_tree.exists(ns):
return
# 确保当前选中的命名空间是保存的命名空间
current_ns_selection = self.ns_tree.selection()
if not current_ns_selection or current_ns_selection[0] != ns:
# 切换到保存的命名空间
self.ns_tree.selection_set(ns)
self.ns_tree.focus(ns)
self.ns_tree.see(ns)
# 重新填充项目列表
self._populate_item_list()
# 重新构建正确的条目ID
target_iid = f"{ns}___{idx}"
# 检查条目是否存在
if self.trans_tree.exists(target_iid):
# 直接选择项目,不触发保存逻辑
self.trans_tree.selection_set(target_iid)
self.trans_tree.focus(target_iid)
self.trans_tree.see(target_iid)
# 直接更新当前选择信息和编辑器内容
if ns is not None:
item_data = self.translation_data[ns]['items'][idx]
# 更新当前选择信息
self.current_selection_info = {'ns': ns, 'idx': idx, 'row_id': target_iid}
# 解绑文本修改事件,避免设置编辑器内容时触发保存逻辑
self.zh_text_input.unbind("<KeyRelease>")
self.zh_text_input.unbind("<FocusOut>")
# 更新编辑器内容
self._set_editor_content(item_data['en'], item_data.get('zh', ''))
# 清除编辑器的修改标记
self.zh_text_input.edit_modified(False)
# 重新绑定文本修改事件
def _on_key_release(event):
"""合并的按键释放事件处理函数"""
self._on_text_modified(event)
self._update_term_suggestions(event)
self.zh_text_input.bind("<KeyRelease>", _on_key_release)
self.zh_text_input.bind("<FocusOut>", lambda e: self._save_current_edit())
# 更新UI状态
self._update_ui_state(interactive=True, item_selected=True)
self.zh_text_input.focus_set()
# 显示匹配的术语
self._show_matching_terms(item_data['en'])
def find_next(self, params):
find_text = params["find_text"]
if not find_text:
return
direction = 1 if params["direction"] == "down" else -1
all_items = self._get_searchable_items(params["scope"])
if not all_items:
# 检查当前项目是否选中但无条目,或无项目
if params["scope"] == 'current' and self.ns_tree.selection():
messagebox.showinfo("搜索提示", "当前项目中没有可搜索的条目。", parent=self)
elif params["scope"] == 'all':
messagebox.showinfo("搜索提示", "没有可搜索的项目或条目。", parent=self)
return
# 获取当前选中的项目
current_selection = self.trans_tree.selection()
start_index = -1
if current_selection:
selected_item = current_selection[0]
# 使用字典加速查找,时间复杂度O(1) instead of O(n)
item_to_index = {item: idx for idx, item in enumerate(all_items)}
start_index = item_to_index.get(selected_item, -1)
# 计算搜索顺序
if direction == 1: # 向下搜索
ordered_items = all_items[start_index+1:] + (all_items if params["wrap"] else [])
else: # 向上搜索
ordered_items = all_items[:start_index][::-1] + (all_items[::-1] if params["wrap"] else [])
# 获取要搜索的列
column_map = {"en": "en", "zh": "zh", "all": "all"}
search_column = column_map.get(params["search_column"], "all")
match_case = params["match_case"]
# 执行搜索
for iid in ordered_items:
ns, idx = self._get_ns_idx_from_iid(iid)
if ns is None or idx is None:
continue
item = self.translation_data[ns]['items'][idx]
key = item.get('key', '')
en_text = item.get('en', '')
zh_text = item.get('zh', '')
# 根据搜索列进行匹配
found = False
if search_column == "en" or search_column == "all":
if match_case:
if find_text in en_text:
found = True
else:
if find_text.lower() in en_text.lower():
found = True
if not found and (search_column == "zh" or search_column == "all"):
if match_case:
if find_text in zh_text:
found = True
else:
if find_text.lower() in zh_text.lower():
found = True
if not found and search_column == "all":
if match_case:
if find_text in key:
found = True
else:
if find_text.lower() in key.lower():
found = True
if found:
# 保存当前编辑
self._save_current_edit()
# 切换到对应的命名空间
current_ns_selection = self.ns_tree.selection()
if not current_ns_selection or current_ns_selection[0] != ns:
# 切换命名空间并重新填充条目
self.ns_tree.selection_set(ns)
self.ns_tree.focus(ns)
self.ns_tree.see(ns)
self.update_idletasks()
self._populate_item_list()
# 直接使用_iid重新构建当前模组下的正确ID
current_mod_items = self.trans_tree.get_children()
target_iid = f"{ns}___{idx}"
# 选中并滚动到找到的项目
if target_iid in current_mod_items:
self.trans_tree.selection_set(target_iid)
self.trans_tree.focus(target_iid)
self.trans_tree.see(target_iid)
# 触发项目选中事件,更新编辑器内容
self._on_item_selected()
return
# 如果没有找到匹配项
messagebox.showinfo("搜索完成", f"未找到更多包含 '{find_text}' 的条目。", parent=self)
def replace_current_and_find_next(self, params):
find_text = params["find_text"]
replace_text = params["replace_text"]
if not find_text:
return
# 获取当前选中的项目
selection = self.trans_tree.selection()
if not selection:
# 如果没有选中项目,先查找第一个匹配项
self.find_next(params)
return
iid = selection[0]
ns, idx = self._get_ns_idx_from_iid(iid)
if ns is None or idx is None:
return
item = self.translation_data[ns]['items'][idx]
match_case = params["match_case"]
search_column = params.get("search_column", "all")
# 获取要替换的文本
key = item.get('key', '')
en_text = item.get('en', '')
zh_text = item.get('zh', '')
# 检查当前项目是否包含要查找的内容
found = False
target_text = None
target_field = None
# 先检查当前选中字段是否包含要查找的内容
current_selection = self.trans_tree.selection()
if current_selection:
# 检查每个可能的字段
if search_column == "en" or search_column == "all":
if match_case:
if find_text in en_text:
found = True
target_text = en_text
target_field = "en"
else:
if find_text.lower() in en_text.lower():
found = True
target_text = en_text
target_field = "en"
if not found and (search_column == "zh" or search_column == "all"):
if match_case:
if find_text in zh_text:
found = True
target_text = zh_text
target_field = "zh"
else:
if find_text.lower() in zh_text.lower():
found = True
target_text = zh_text
target_field = "zh"
if not found and search_column == "all":
if match_case:
if find_text in key:
found = True
target_text = key
target_field = "key"
else:
if find_text.lower() in key.lower():
found = True
target_text = key
target_field = "key"
if not found:
# 如果当前项目不包含要查找的内容,直接查找下一个
self.find_next(params)
return
# 执行替换
new_text = None
if match_case:
new_text = target_text.replace(find_text, replace_text)
else:
# 不区分大小写替换
new_text = re.sub(re.escape(find_text), replace_text, target_text, flags=re.IGNORECASE)
if new_text != target_text:
# 更新项目数据
if target_field == "en":
item['en'] = new_text
elif target_field == "zh":
item['zh'] = new_text
elif target_field == "key":
item['key'] = new_text
item['source'] = '手动校对'
# 更新UI
self._update_item_in_tree(iid, item)
# 如果替换的是当前编辑的字段,更新编辑器内容
if target_field == "zh":
self.zh_text_input.delete("1.0", tk.END)
self.zh_text_input.insert("1.0", new_text)
elif target_field == "en":
# 更新原文显示
self.en_text_display.delete("1.0", tk.END)
self.en_text_display.insert("1.0", new_text)
self._set_dirty(True)
# 保存状态用于撤销/重做,与编辑操作使用相同的details结构
# 注意:这里在执行替换操作后调用record_operation,与编辑操作的行为保持一致
details = {
'key': item.get('key', ''),
'original_text': target_text,
'new_text': new_text,
'namespace': ns,
'index': idx
}
self.record_operation('REPLACE', details, target_iid=iid)
# 如果当前项目包含要查找的内容并执行了替换,保持在当前项目
# 只有当当前项目不包含要查找的内容时,才查找下一个
if not found:
self.find_next(params)
def _update_item_in_tree(self, iid, item):
"""更新树视图中的项目"""
if self.trans_tree.exists(iid):
# 前台显示时将 _comment_* 格式的键显示为 _comment
display_key = item['key']
if display_key.startswith('_comment_'):
display_key = '_comment'
# 准备新的条目数据
new_values = (display_key, item['en'], item.get('zh', ''), item['source'])
# 检查当前条目数据是否与新数据相同
current_values = self.trans_tree.item(iid, 'values')
if current_values != new_values:
# 只有当数据实际发生变化时才更新UI
self.trans_tree.item(iid, values=new_values)
def replace_all(self, params):
find_text = params["find_text"]
replace_text = params["replace_text"]
if not find_text:
return
# 确认替换操作
if not messagebox.askyesno("全部替换", f"您确定要将所有 '{find_text}' 替换为 '{replace_text}' 吗?\n此操作可以被撤销。", parent=self):
return
# 保存当前编辑
self._save_current_edit(record_undo=False)
# 保存当前选中信息
saved_selection = self.current_selection_info.copy() if self.current_selection_info else None
saved_ns_selection = self.ns_tree.selection()[0] if self.ns_tree.selection() else None
# 取消当前选中状态,确保当前条目也能被替换
self.trans_tree.selection_remove(self.trans_tree.selection())
self.current_selection_info = None
# 获取替换参数
match_case = params["match_case"]
scope = params["scope"]
search_column = params.get("search_column", "all")
# 获取要搜索的命名空间
namespaces_to_search = []
if scope == "current":
selection = self.ns_tree.selection()
if selection:
namespaces_to_search.append(selection[0])
else:
namespaces_to_search.extend(self.translation_data.keys())
if not namespaces_to_search:
messagebox.showwarning("范围错误", "请先在左侧选择一个项目以确定替换范围。", parent=self)
return
# 保存当前状态用于撤销/重做(在执行替换操作前保存)
target_iid = saved_selection['row_id'] if saved_selection else None
details = {
'find_text': find_text,
'replace_text': replace_text,
'match_case': match_case,
'scope': scope,
'search_column': search_column,
'namespaces': namespaces_to_search
}
self.record_operation('REPLACE_ALL', details, target_iid=target_iid)
replacement_count = 0
# 编译正则表达式(带转义),只编译一次
escaped_find = re.escape(find_text)
flags = 0 if match_case else re.IGNORECASE
compiled_re = re.compile(escaped_find, flags)
# 执行替换
for ns in namespaces_to_search:
for idx, item in enumerate(self.translation_data[ns]['items']):
key = item.get('key', '')
en_text = item.get('en', '')
zh_text = item.get('zh', '')
# 检查是否匹配
found = False
fields_to_replace = []
# 根据搜索列检查匹配
if search_column == "en" or search_column == "all":
if compiled_re.search(en_text):
found = True
fields_to_replace.append("en")
if search_column == "zh" or search_column == "all":
if compiled_re.search(zh_text):
found = True
fields_to_replace.append("zh")
if search_column == "all":
if compiled_re.search(key):
found = True
fields_to_replace.append("key")
# 执行替换
if found:
changed = False
for field in fields_to_replace:
original_text = item.get(field, '')
new_text = compiled_re.sub(replace_text, original_text)
if new_text != original_text:
item[field] = new_text
changed = True
if changed:
item['source'] = '手动校对'
replacement_count += 1
# 更新UI状态
self._set_dirty(True)
# 更新树视图
self._populate_namespace_tree()
self._populate_item_list()
# 显示替换结果
messagebox.showinfo("替换完成", f"已完成 {replacement_count} 处替换。", parent=self)
# 恢复选中状态并更新编辑器内容
if saved_selection:
ns = saved_selection['ns']
idx = saved_selection['idx']
# 确保左侧模组树选中正确的模组
if saved_ns_selection and self.ns_tree.exists(saved_ns_selection):
self.ns_tree.selection_set(saved_ns_selection)
self.ns_tree.focus(saved_ns_selection)
self.ns_tree.see(saved_ns_selection)
# 重新构建正确的ID
new_iid = f"{ns}___{idx}"
if self.trans_tree.exists(new_iid):
# 重新选择项目
self.trans_tree.selection_set(new_iid)
self.trans_tree.focus(new_iid)
self.trans_tree.see(new_iid)
# 更新当前选择信息
self.current_selection_info = {
'ns': ns,
'idx': idx,
'row_id': new_iid
}
# 更新编辑器内容
item = self.translation_data[ns]['items'][idx]
self._set_editor_content(item['en'], item.get('zh', ''))
# 更新UI状态
self._update_ui_state(interactive=True, item_selected=True)
def _get_ns_idx_from_iid(self, iid):
try:
ns, idx_str = iid.rsplit('___', 1)
return ns, int(idx_str)
except (ValueError, IndexError):
return None, None
def record_operation(self, operation_type, details=None, target_iid=None):
"""记录操作到历史
Args:
operation_type: 操作类型
details: 操作详细信息
target_iid: 目标条目ID
"""
import uuid
import time
current_time = time.time()
# 检查是否可以合并操作
can_merge = False
if (operation_type == 'EDIT' or operation_type == 'REPLACE') and self.operation_history:
last_op = self.operation_history[-1]
time_diff = current_time - self.last_operation_time
if ((last_op['type'] == 'EDIT' or last_op['type'] == 'REPLACE') and
last_op['target_iid'] == target_iid and
time_diff < self.operation_merge_window):
# 合并连续的编辑或替换操作
last_op['timestamp'] = datetime.now().isoformat()
last_op['details'] = details or {}
# 对于编辑或替换操作,只保存被修改的命名空间
ns, idx = self._get_ns_idx_from_iid(target_iid)
if ns is not None:
last_op['state'] = {
ns: copy.deepcopy(self.translation_data.get(ns, {}))
}
else:
last_op['state'] = copy.deepcopy(self.translation_data)
can_merge = True
if not can_merge:
# 创建操作记录
# 对于编辑和替换操作,只保存被修改条目的状态,而不是整个translation_data
state_to_save = None
if (operation_type == 'EDIT' or operation_type == 'REPLACE') and target_iid:
# 解析目标条目ID,获取命名空间和索引
ns, idx = self._get_ns_idx_from_iid(target_iid)
if ns is not None and idx is not None:
# 只保存被修改的命名空间的数据
state_to_save = {
ns: copy.deepcopy(self.translation_data.get(ns, {}))
}
# 如果不是编辑操作或无法获取目标条目,保存整个translation_data
if state_to_save is None:
state_to_save = copy.deepcopy(self.translation_data)
operation = {
'id': str(uuid.uuid4()),
'type': operation_type,
'description': self.OPERATION_TYPES.get(operation_type, '其他操作'),
'timestamp': datetime.now().isoformat(),
'target_iid': target_iid,
'details': details or {},
'state': state_to_save
}
# 当添加新操作时,截断操作历史到当前状态索引
# 这样之前的灰色重做条目就会被移除
if self.current_state_index < len(self.operation_history) - 1:
self.operation_history = self.operation_history[:self.current_state_index + 1]
# 添加到历史记录
self.operation_history.append(operation)
# 更新当前状态索引,使其指向最后一个操作
self.current_state_index = len(self.operation_history) - 1
# 限制历史记录大小
if len(self.operation_history) > self.max_history_size:
self.operation_history.pop(0)
# 当删除最早的记录后,更新当前状态索引
self.current_state_index = len(self.operation_history) - 1