-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
668 lines (559 loc) · 27.9 KB
/
main.py
File metadata and controls
668 lines (559 loc) · 27.9 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
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
import threading
import os
import datetime
import json
from crypto_manager import CryptoManager
# Try to import tkinterdnd2 for Drag and Drop support
try:
from tkinterdnd2 import DND_FILES, TkinterDnD
HAS_DND = True
BaseWindow = TkinterDnD.Tk
except ImportError:
HAS_DND = False
BaseWindow = tk.Tk
print("Warning: tkinterdnd2 not found. Drag and drop will be disabled.")
TRANSLATIONS = {
"title": {"en": "Python Encryption Tool (PBKDF2 + AES)", "zh": "Python 加密工具 (PBKDF2 + AES)"},
"control_panel": {"en": "Control Panel", "zh": "控制面板"},
"password": {"en": "密码:", "zh": "密码:"},
"confirm_pwd": {"en": "confirm pwd", "zh": "确认密码"},
"algorithm": {"en": "Algorithm:", "zh": "算法:"},
"set_enc_out": {"en": "Set Enc Output Dir", "zh": "设置加密输出目录"},
"set_dec_out": {"en": "Set Dec Output Dir", "zh": "设置解密输出目录"},
"text_enc_title": {"en": "Text Encryption", "zh": "文本加密"},
"history": {"en": "History/Results:", "zh": "历史/结果:"},
"input_text": {"en": "Input Text:", "zh": "输入文本:"},
"btn_encrypt": {"en": "Encrypt", "zh": "加密"},
"text_dec_title": {"en": "Text Decryption", "zh": "文本解密"},
"btn_decrypt": {"en": "Decrypt", "zh": "解密"},
"file_ops_title": {"en": "File Operations", "zh": "文件操作"},
"file_enc_title": {"en": "File Encryption", "zh": "文件加密"},
"drag_info": {"en": "Drag file here or click Select:", "zh": "拖拽文件至此或点击选择:"},
"select_file": {"en": "Select File", "zh": "选择文件"},
"btn_enc_file": {"en": "Encrypt File", "zh": "加密文件"},
"file_dec_title": {"en": "File Decryption", "zh": "文件解密"},
"btn_dec_file": {"en": "Decrypt File", "zh": "解密文件"},
"ready": {"en": "Ready", "zh": "就绪"},
"processing": {"en": "Processing...", "zh": "处理中..."},
"done": {"en": "Done!", "zh": "完成!"},
"missing_pwd_title": {"en": "Missing Password", "zh": "缺少密码"},
"missing_pwd_msg": {"en": "Please enter a password first.", "zh": "请先输入密码。"},
"pwd_conf_title": {"en": "Password Confirmed", "zh": "密码已确认"},
"pwd_conf_msg": {"en": "Password captured.", "zh": "密码已捕获。"},
"pwd_empty_msg": {"en": "Password is empty!", "zh": "密码为空!"},
"warning": {"en": "Warning", "zh": "警告"},
"error": {"en": "Error", "zh": "错误"},
"file_error_title": {"en": "File Error", "zh": "文件错误"},
"file_error_msg": {"en": "Invalid input file.", "zh": "无效的输入文件。"},
"op_complete": {"en": "Complete", "zh": "完成"},
"saved_to": {"en": "Saved to:", "zh": "保存至:"},
"dec_fail_msg": {"en": "Decryption failed. Check Password or format.", "zh": "解密失败。请检查密码或格式。"},
"lang_label": {"en": "Language:", "zh": "语言:"},
"iterations": {"en": "Iterations(0<x<100000000):", "zh": "迭代次数(0<x<100000000):"},
"confirm_iterations": {"en": "Confirm Iterations", "zh": "确认迭代次数"},
"missing_iterations_title": {"en": "Missing Iterations", "zh": "缺少迭代次数"},
"missing_iterations_msg": {"en": "Iterations cannot be empty!", "zh": "迭代次数不能为空!"},
"iterations_conf_msg": {"en": "Iterations confirmed.", "zh": "迭代次数已确认。"},
"iterations_empty_msg": {"en": "Iterations is empty!", "zh": "迭代次数为空!"},
"iterations_max_restrict": {"en": "Iterations cannot exceed 100000000!", "zh": "迭代次数不能超过100000000!"},
"use_timestamp": {"en": "Timestamp filename", "zh": "时间戳文件名"},
"delete_original": {"en": "Delete original", "zh": "删除原文件"},
"confirm_delete_title": {"en": "Confirm Delete", "zh": "确认删除"},
"confirm_delete_msg": {"en": "Delete the original file?\n{path}", "zh": "删除原始文件?\n{path}"},
"batch_select": {"en": "Batch Select", "zh": "批量选择"},
"batch_files_selected": {"en": "{count} files selected", "zh": "已选择 {count} 个文件"},
"batch_file_status": {"en": "File {done}/{total}", "zh": "文件 {done}/{total}"},
"file_delete_failed": {"en": "Failed to delete original: {err}", "zh": "删除原文件失败:{err}"},
}
CONFIG_FILE = "settings.json"
class EncryptApp(BaseWindow):
# MAX_ITERATIONS
MAX_ITERATIONS = 100_000_000
def __init__(self):
super().__init__()
self.crypto = CryptoManager()
self.enc_output_path = tk.StringVar()
self.dec_output_path = tk.StringVar()
self.selected_enc_file = tk.StringVar()
self.selected_dec_file = tk.StringVar()
self.iterations_var = tk.StringVar()
self.lang_code = "en"
self.translatable_widgets = [] # List of (widget, key, attribute_name)
# Batch file lists for bulk operations
self.batch_enc_files = []
self.batch_dec_files = []
# Options for file operations
self.use_timestamp_enc = tk.BooleanVar()
self.use_timestamp_dec = tk.BooleanVar()
self.delete_original_enc = tk.BooleanVar()
self.delete_original_dec = tk.BooleanVar()
# Load settings before UI setup to apply language and paths
self.load_settings()
self.setup_ui()
self.update_language() # Apply language to UI
def load_settings(self):
"""Load settings from JSON file."""
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
settings = json.load(f)
self.enc_output_path.set(settings.get("enc_output_path", ""))
self.dec_output_path.set(settings.get("dec_output_path", ""))
self.lang_code = settings.get("language", "en")
self.iterations_var.set(settings.get("iterations", "100000"))
except Exception as e:
print(f"Failed to load settings: {e}")
def save_settings(self):
"""Save current settings to JSON file."""
settings = {
"enc_output_path": self.enc_output_path.get(),
"dec_output_path": self.dec_output_path.get(),
"language": self.lang_code,
"iterations": int(self.iterations_var.get())
}
try:
with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
json.dump(settings, f, ensure_ascii=False, indent=4)
except Exception as e:
print(f"Failed to save settings: {e}")
def tr(self, key):
"""Translate a key to the current language."""
return TRANSLATIONS.get(key, {}).get(self.lang_code, key)
def register_widget(self, widget, key, attr="text"):
"""Register a widget for automatic translation updates."""
self.translatable_widgets.append((widget, key, attr))
# Set initial value immediately
if attr == "title":
widget.title(self.tr(key))
else:
try:
widget.config(**{attr: self.tr(key)})
except:
pass # Ignore if config fails (e.g. some widgets might differ)
return widget
def update_language(self, event=None):
"""Update all registered widgets to the current language."""
# Update lang code from combobox if this is triggered by event
if hasattr(self, 'lang_combo'):
selection = self.lang_combo.get()
if "中文" in selection:
self.lang_code = "zh"
else:
self.lang_code = "en"
# Save new language preference
self.save_settings()
# Update registered widgets
for widget, key, attr in self.translatable_widgets:
val = self.tr(key)
if attr == "title":
widget.title(val)
else:
try:
widget.config(**{attr: val})
except Exception as e:
print(f"Failed to update widget {widget}: {e}")
# Update dynamic status labels if they are "Ready"
if self.enc_status.cget("text") in ["Ready", "就绪"]:
self.enc_status.config(text=self.tr("ready"))
if self.dec_status.cget("text") in ["Ready", "就绪"]:
self.dec_status.config(text=self.tr("ready"))
def setup_ui(self):
self.geometry("1200x800")
self.minsize(1000, 700)
self.register_widget(self, "title", "title")
# --- Top Control Bar ---
top_frame = ttk.LabelFrame(self, padding=10)
self.register_widget(top_frame, "control_panel", "text")
top_frame.pack(fill="x", padx=10, pady=5)
# password
lbl_pwd = ttk.Label(top_frame)
self.register_widget(lbl_pwd, "password")
lbl_pwd.pack(side="left", padx=5)
self.pwd_entry = ttk.Entry(top_frame, width=20, show="*")
self.pwd_entry.pack(side="left", padx=5)
self.btn_confirm_pwd = ttk.Button(top_frame, command=self.confirm_password)
self.register_widget(self.btn_confirm_pwd, "confirm_pwd")
self.btn_confirm_pwd.pack(side="left", padx=5)
# Algorithm
lbl_algo = ttk.Label(top_frame)
self.register_widget(lbl_algo, "algorithm")
lbl_algo.pack(side="left", padx=5)
self.algo_var = tk.StringVar(value="AES-256")
self.algo_combo = ttk.Combobox(top_frame, textvariable=self.algo_var,
values=["AES-128", "AES-192", "AES-256"], state="readonly", width=10)
self.algo_combo.pack(side="left", padx=5)
# Language Selector
lbl_lang = ttk.Label(top_frame)
self.register_widget(lbl_lang, "lang_label")
lbl_lang.pack(side="left", padx=5)
self.lang_combo = ttk.Combobox(top_frame, values=["English", "中文 (Chinese)"], state="readonly", width=15)
# Set initial selection based on loaded settings
if self.lang_code == "zh":
self.lang_combo.set("中文 (Chinese)")
else:
self.lang_combo.set("English")
self.lang_combo.pack(side="left", padx=5)
self.lang_combo.bind("<<ComboboxSelected>>", self.update_language)
#iterations
lbl_iter = ttk.Label(top_frame)
self.register_widget(lbl_iter, "iterations")
lbl_iter.pack(side="left", padx=5)
self.iter_entry = ttk.Entry(top_frame, width=20, textvariable=self.iterations_var)
self.iter_entry.pack(side="left", padx=5)
self.btn_confirm_iterations = ttk.Button(top_frame, command=self.confirm_iterations)
self.register_widget(self.btn_confirm_iterations, "confirm_iterations")
self.btn_confirm_iterations.pack(side="left", padx=5)
# Output Paths
btn_enc_out = ttk.Button(top_frame, command=self.select_enc_out_dir)
self.register_widget(btn_enc_out, "set_enc_out")
btn_enc_out.pack(side="left", padx=10)
self.lbl_enc_out = ttk.Label(top_frame, textvariable=self.enc_output_path, foreground="gray")
self.lbl_enc_out.pack(side="left", padx=2)
btn_dec_out = ttk.Button(top_frame, command=self.select_dec_out_dir)
self.register_widget(btn_dec_out, "set_dec_out")
btn_dec_out.pack(side="left", padx=10)
self.lbl_dec_out = ttk.Label(top_frame, textvariable=self.dec_output_path, foreground="gray")
self.lbl_dec_out.pack(side="left", padx=2)
# --- Main Grid ---
main_frame = ttk.Frame(self, padding=10)
main_frame.pack(fill="both", expand=True)
main_frame.columnconfigure(0, weight=1)
main_frame.columnconfigure(1, weight=1)
main_frame.columnconfigure(2, weight=1)
main_frame.rowconfigure(0, weight=1)
# 1. Left: Encrypt Text
self.create_text_section(main_frame, 0, "text_enc_title", "btn_encrypt", self.action_encrypt_text)
# 2. Middle: Decrypt Text
self.create_text_section(main_frame, 1, "text_dec_title", "btn_decrypt", self.action_decrypt_text)
# 3. Right: File Operations
self.create_file_section(main_frame, 2)
def create_text_section(self, parent, col, title_key, btn_text_key, btn_command):
frame = ttk.LabelFrame(parent, padding=5)
self.register_widget(frame, title_key, "text")
frame.grid(row=0, column=col, sticky="nsew", padx=5, pady=5)
# Top: Result/Log Area (Scrollable)
log_label = ttk.Label(frame)
self.register_widget(log_label, "history")
log_label.pack(anchor="w")
log_area = scrolledtext.ScrolledText(frame, height=15, state="disabled", font=("Consolas", 9))
log_area.pack(fill="both", expand=True, pady=(0, 5))
if "Encrypt" in self.tr(btn_text_key) or "加密" in self.tr(btn_text_key):
if btn_text_key == "btn_encrypt":
self.enc_log = log_area
else:
self.dec_log = log_area
else:
if btn_text_key == "btn_encrypt":
self.enc_log = log_area
else:
self.dec_log = log_area
# Bottom: Input Area
input_frame = ttk.Frame(frame)
input_frame.pack(fill="x", pady=5)
input_label = ttk.Label(input_frame)
self.register_widget(input_label, "input_text")
input_label.pack(anchor="w")
input_text = tk.Text(input_frame, height=8, font=("Arial", 10))
input_text.pack(fill="x", side="left", expand=True)
if btn_text_key == "btn_encrypt":
self.enc_input = input_text
else:
self.dec_input = input_text
# Action Button
btn = ttk.Button(input_frame, command=btn_command)
self.register_widget(btn, btn_text_key)
btn.pack(side="right", padx=5, fill="y")
def create_file_section(self, parent, col):
frame = ttk.LabelFrame(parent, padding=5)
self.register_widget(frame, "file_ops_title", "text")
frame.grid(row=0, column=col, sticky="nsew", padx=5, pady=5)
frame.rowconfigure(0, weight=1)
frame.rowconfigure(1, weight=1)
# Upper: Encrypt File
self.create_single_file_op(frame, 0, "file_enc_title", self.selected_enc_file, "btn_enc_file", self.action_encrypt_file, "enc")
# Lower: Decrypt File
self.create_single_file_op(frame, 1, "file_dec_title", self.selected_dec_file, "btn_dec_file", self.action_decrypt_file, "dec")
def create_single_file_op(self, parent, row, title_key, path_var, btn_text_key, btn_command, mode):
sub_frame = ttk.LabelFrame(parent, padding=5)
self.register_widget(sub_frame, title_key, "text")
sub_frame.grid(row=row, column=0, sticky="nsew", padx=2, pady=5)
# Path Display / Drop Zone
lbl_info = ttk.Label(sub_frame)
self.register_widget(lbl_info, "drag_info")
lbl_info.pack(anchor="w")
path_entry = ttk.Entry(sub_frame, textvariable=path_var, state="readonly")
path_entry.pack(fill="x", pady=5)
# DND
if HAS_DND:
path_entry.drop_target_register(DND_FILES)
path_entry.dnd_bind('<<Drop>>', lambda e: path_var.set(e.data.strip('{}')))
# Buttons
btn_frame = ttk.Frame(sub_frame)
btn_frame.pack(fill="x")
btn_sel = ttk.Button(btn_frame, command=lambda: self.select_file(path_var, mode))
self.register_widget(btn_sel, "select_file")
btn_sel.pack(side="left", padx=2)
btn_batch = ttk.Button(btn_frame, command=lambda: self.select_batch_files(path_var, mode))
self.register_widget(btn_batch, "batch_select")
btn_batch.pack(side="left", padx=2)
btn_do = ttk.Button(btn_frame, command=btn_command)
self.register_widget(btn_do, btn_text_key)
btn_do.pack(side="right", padx=2)
# Options: timestamp filename and delete original
options_frame = ttk.Frame(sub_frame)
options_frame.pack(fill="x", pady=(2, 0))
if mode == "enc":
ts_var = self.use_timestamp_enc
del_var = self.delete_original_enc
else:
ts_var = self.use_timestamp_dec
del_var = self.delete_original_dec
cb_ts = ttk.Checkbutton(options_frame, variable=ts_var)
self.register_widget(cb_ts, "use_timestamp")
cb_ts.pack(side="left", padx=2)
cb_del = ttk.Checkbutton(options_frame, variable=del_var)
self.register_widget(cb_del, "delete_original")
cb_del.pack(side="left", padx=2)
# Progress Bar
pb = ttk.Progressbar(sub_frame, orient="horizontal", mode="determinate")
pb.pack(fill="x", pady=5)
# Status Label
status_lbl = ttk.Label(sub_frame, text="Ready", font=("Arial", 8))
status_lbl.pack(anchor="w")
if mode == "enc":
self.enc_pb = pb
self.enc_status = status_lbl
else:
self.dec_pb = pb
self.dec_status = status_lbl
# --- Actions ---
def log(self, area, message):
area.config(state="normal")
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
area.insert("end", f"[{timestamp}] {message}\n")
area.insert("end", "-"*30 + "\n")
area.see("end")
area.config(state="disabled")
def get_password(self):
pwd = self.pwd_entry.get()
if not pwd:
messagebox.showwarning(self.tr("missing_pwd_title"), self.tr("missing_pwd_msg"))
return None
return pwd
def confirm_password(self):
pwd = self.pwd_entry.get()
if pwd:
messagebox.showinfo(self.tr("pwd_conf_title"), self.tr("pwd_conf_msg"))
else:
messagebox.showwarning(self.tr("warning"), self.tr("pwd_empty_msg"))
def check_iterations(self):
try:
iterations_str = self.iter_entry.get()
if not iterations_str:
messagebox.showwarning(self.tr("missing_iterations_title"), self.tr("missing_iterations_msg"))
return False
iterations = int(iterations_str)
if iterations <= 0:
messagebox.showwarning(self.tr("warning"), self.tr("iterations_empty_msg"))
return False
if iterations > self.MAX_ITERATIONS:
messagebox.showerror(self.tr("error"), self.tr("iterations_max_restrict"))
return False
return True
except ValueError:
messagebox.showerror(self.tr("error"), "Invalid number format!")
return False
def get_iterations(self):
is_valid_iterations = self.check_iterations()
if not is_valid_iterations:
return None
else:
iterations = int(self.iter_entry.get())
if not iterations:
messagebox.showwarning(self.tr("missing_iterations_title"), self.tr("missing_iterations_msg"))
return None
self.crypto.ITERATIONS = iterations
return iterations
def confirm_iterations(self):
is_valid_iterations = self.check_iterations()
if not is_valid_iterations:
return None
else:
iterations = int(self.iter_entry.get())
if iterations:
messagebox.showinfo(self.tr("iterations_conf_title"), self.tr("iterations_conf_msg"))
self.crypto.ITERATIONS = iterations
self.save_settings()
else:
messagebox.showwarning(self.tr("warning"), self.tr("iterations_empty_msg"))
def select_enc_out_dir(self):
d = filedialog.askdirectory()
if d:
self.enc_output_path.set(d)
self.save_settings()
def select_dec_out_dir(self):
d = filedialog.askdirectory()
if d:
self.dec_output_path.set(d)
self.save_settings()
def select_file(self, var, mode=None):
f = filedialog.askopenfilename()
if f:
var.set(f)
# Clear batch list when single file is selected
if mode == "enc":
self.batch_enc_files = []
elif mode == "dec":
self.batch_dec_files = []
def select_batch_files(self, path_var, mode):
files = filedialog.askopenfilenames()
if files:
files = list(files)
if mode == "enc":
self.batch_enc_files = files
else:
self.batch_dec_files = files
count = len(files)
if count == 1:
path_var.set(files[0])
else:
path_var.set(self.tr("batch_files_selected").format(count=count))
def action_encrypt_text(self):
pwd = self.get_password()
iterations = self.get_iterations()
if not iterations: return
if not pwd: return
text = self.enc_input.get("1.0", "end-1c")
if not text: return
try:
algo = self.algo_var.get()
result = self.crypto.encrypt_text(text, pwd, algo)
self.log(self.enc_log, f"Encrypted ({algo}):\n{result}")
except Exception as e:
messagebox.showerror(self.tr("error"), str(e))
def action_decrypt_text(self):
pwd = self.get_password()
iterations = self.get_iterations()
if not iterations: return
if not pwd: return
text = self.dec_input.get("1.0", "end-1c")
if not text: return
try:
algo = self.algo_var.get()
result = self.crypto.decrypt_text(text.strip(), pwd, algo)
self.log(self.dec_log, f"Decrypted ({algo}):\n{result}")
except Exception as e:
self.log(self.dec_log, f"Error: {str(e)}")
messagebox.showerror(self.tr("error"), self.tr("dec_fail_msg"))
def action_encrypt_file(self):
files = self.batch_enc_files if self.batch_enc_files else [self.selected_enc_file.get()]
self._run_file_ops(files, self.enc_output_path,
self.crypto.encrypt_file, self.enc_pb, self.enc_status, ".enc",
self.tr("file_enc_title"),
self.use_timestamp_enc.get(), self.delete_original_enc.get())
def action_decrypt_file(self):
files = self.batch_dec_files if self.batch_dec_files else [self.selected_dec_file.get()]
self._run_file_ops(files, self.dec_output_path,
self.crypto.decrypt_file, self.dec_pb, self.dec_status, ".dec",
self.tr("file_dec_title"),
self.use_timestamp_dec.get(), self.delete_original_dec.get())
def _run_file_ops(self, input_paths, output_dir_var, op_func, pb, status_lbl, suffix, op_name,
use_timestamp=False, delete_original=False):
"""Run file operation(s) on one or more files in a background thread."""
pwd = self.get_password()
iterations = self.get_iterations()
if not iterations: return
if not pwd: return
# Validate all input paths
valid_paths = [p for p in input_paths if p and os.path.exists(p)]
if not valid_paths:
messagebox.showwarning(self.tr("file_error_title"), self.tr("file_error_msg"))
return
out_dir = output_dir_var.get()
if out_dir and not os.path.exists(out_dir):
try:
os.makedirs(out_dir)
except OSError:
out_dir = ""
algo = self.algo_var.get()
total_files = len(valid_paths)
# Translate strings once before entering thread
str_processing = self.tr("processing")
str_done = self.tr("done")
str_complete = self.tr("op_complete")
str_saved = self.tr("saved_to")
str_error = self.tr("error")
str_file_status = self.tr("batch_file_status")
str_confirm_delete_title = self.tr("confirm_delete_title")
str_confirm_delete_msg = self.tr("confirm_delete_msg")
str_file_delete_failed = self.tr("file_delete_failed")
# Shared state for progress polling
progress_info = {"file_value": 0, "done": False}
def poll_progress():
pb.config(value=progress_info["file_value"])
if not progress_info["done"]:
self.after(50, poll_progress)
def worker():
try:
self.after(0, lambda: status_lbl.config(text=str_processing, foreground="blue"))
self.after(0, lambda: pb.config(value=0))
self.after(50, poll_progress)
saved_paths = []
completed_inputs = [] # collect originals for deferred deletion
start_time = datetime.datetime.now()
for idx, in_path in enumerate(valid_paths):
# Build output path
file_out_dir = out_dir if out_dir else os.path.dirname(in_path)
if use_timestamp:
ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f")
out_name = ts + suffix
else:
base_name = os.path.basename(in_path)
out_name = base_name + suffix
out_path = os.path.join(file_out_dir, out_name)
# Update status for batch
if total_files > 1:
status_text = str_file_status.format(done=idx + 1, total=total_files)
self.after(0, lambda t=status_text: status_lbl.config(text=t, foreground="blue"))
# progress_info is written here and read on main thread via poll_progress.
# Simple int assignment is atomic under CPython's GIL, so no lock needed.
progress_info["file_value"] = 0
def progress(current, total, pi=progress_info):
if total > 0:
pi["file_value"] = int((current / total) * 100)
op_func(in_path, out_path, pwd, algo, progress)
progress_info["file_value"] = 100
saved_paths.append(out_path)
if delete_original:
completed_inputs.append(in_path)
end_time = datetime.datetime.now()
elapsed = end_time - start_time
progress_info["done"] = True
done_text = f"{str_done} ({elapsed})"
self.after(0, lambda t=done_text: status_lbl.config(text=t, foreground="green"))
saved_msg = f"{str_saved}\n" + "\n".join(saved_paths)
self.after(0, lambda m=saved_msg: messagebox.showinfo(f"{op_name} {str_complete}", m))
# Prompt deletion for each completed original after all operations finish.
# Must run on the main thread since it shows dialogs.
def prompt_deletions(paths=completed_inputs):
for orig_path in paths:
msg = str_confirm_delete_msg.format(path=orig_path)
if messagebox.askyesno(str_confirm_delete_title, msg):
try:
os.remove(orig_path)
except Exception as del_err:
err_msg = str_file_delete_failed.format(err=str(del_err))
messagebox.showwarning(str_error, err_msg)
if completed_inputs:
self.after(0, prompt_deletions)
except Exception as e:
progress_info["done"] = True
err_text = f"{str_error}: {str(e)}"
self.after(0, lambda t=err_text: status_lbl.config(text=t, foreground="red"))
self.after(0, lambda m=str(e): messagebox.showerror(str_error, m))
threading.Thread(target=worker, daemon=True).start()
if __name__ == "__main__":
app = EncryptApp()
app.mainloop()