-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharc_gui.py
More file actions
1905 lines (1627 loc) · 84.8 KB
/
Copy patharc_gui.py
File metadata and controls
1905 lines (1627 loc) · 84.8 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 os
import sys
# import threading # PySide6 will use QThread
import subprocess
import shutil
from pathlib import Path
from PySide6.QtCore import QThread, Signal, Qt, QTimer, QUrl, QObject
from PySide6.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QHBoxLayout,
QPushButton, QLabel, QLineEdit, QTextEdit, QProgressBar,
QTabWidget, QWidget, QGroupBox, QListWidget, QListWidgetItem,
QFileDialog, QCheckBox, QComboBox, QFrame, QMessageBox, QMenu)
from PySide6.QtGui import QDragEnterEvent, QDropEvent, QPalette, QPixmap
from qfluentwidgets import *
from con import CON
from support.toggle import ThemeManager
# Add the current directory to Python path to import convertzip module
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from support.archive_manager import create_archive, extract_archive, add_to_archive, list_archive_contents, SUPPORTED_ARCHIVE_FORMATS
from support.password_detector import PasswordDetector, detect_password_protection
# Remove the problematic reconfigure calls
# sys.stdout.reconfigure(encoding='utf-8')
# sys.stderr.reconfigure(encoding='utf-8')
# --- Worker Classes for QThread ---
class CreateZipWorker(QObject):
finished = Signal()
progress_updated = Signal(str, int)
conversion_error = Signal(str)
def __init__(self, output_path, sources, archive_format, password=None):
super().__init__()
self.output_path = output_path
self.sources = sources
self.archive_format = archive_format
self.password = password
def run(self):
try:
# Validate input parameters
if not self.output_path:
raise ValueError("Output path is empty")
if not self.sources:
raise ValueError("No source files specified")
if not self.archive_format:
raise ValueError("Archive format is not specified")
# Check if source files exist
for source in self.sources:
if not os.path.exists(source):
raise ValueError(f"Source file does not exist: {source}")
create_archive(self.output_path, self.sources, self.archive_format, self._update_progress_callback, self.password)
self.finished.emit()
except ValueError as e:
# Handle value errors
self.conversion_error.emit(f"Input error: {str(e)}")
except FileNotFoundError as e:
# Handle file not found errors
self.conversion_error.emit(f"File not found: {str(e)}")
except PermissionError as e:
# Handle permission errors
self.conversion_error.emit(f"Permission denied: {str(e)}")
except OSError as e:
# Handle OS errors
self.conversion_error.emit(f"System error: {str(e)}")
except NotImplementedError as e:
# Handle not implemented errors
self.conversion_error.emit(str(e))
except Exception as e:
# Handle all other exceptions
import traceback
error_msg = f"Unexpected error: {str(e)}\n{traceback.format_exc()}"
self.conversion_error.emit(error_msg)
def _update_progress_callback(self, message, percentage):
self.progress_updated.emit(message, percentage)
class ExtractZipWorker(QObject):
finished = Signal()
progress_updated = Signal(str, int)
conversion_error = Signal(str)
password_required = Signal(str) # Emits error message when password is required
def __init__(self, zip_path, dest_path, password=None):
super().__init__()
self.archive_path = zip_path # Renamed for clarity with generic archive_manager
self.extract_to = dest_path
self.password = password
def run(self):
try:
extract_archive(self.archive_path, self.extract_to, self._update_progress_callback, self.password)
self.finished.emit()
except RuntimeError as e:
# Handle password required case
if "password" in str(e).lower() or "encrypted" in str(e).lower():
self.password_required.emit(str(e))
else:
self.conversion_error.emit(str(e))
except Exception as e:
self.conversion_error.emit(str(e))
def _update_progress_callback(self, message, percentage):
self.progress_updated.emit(message, percentage)
class AddToZipWorker(QObject):
finished = Signal()
progress_updated = Signal(str, int)
conversion_error = Signal(str)
def __init__(self, zip_path, file_paths):
super().__init__()
self.archive_path = zip_path # Renamed for clarity with generic archive_manager
self.files_to_add = file_paths if isinstance(file_paths, list) else [file_paths]
def run(self):
try:
# Handle multiple files
total_files = len(self.files_to_add)
for i, file_path in enumerate(self.files_to_add):
self._update_progress_callback(f"Adding file {i+1}/{total_files}: {os.path.basename(file_path)}", (i/total_files)*100)
add_to_archive(self.archive_path, file_path, None) # No individual progress for each file
self._update_progress_callback(f"Added {total_files} files to archive", 100)
self.finished.emit()
except NotImplementedError as e:
self.conversion_error.emit(str(e))
except Exception as e:
self.conversion_error.emit(str(e))
def _update_progress_callback(self, message, percentage):
self.progress_updated.emit(message, percentage)
class ListZipContentsWorker(QObject):
finished = Signal(list) # Emits list of contents
conversion_error = Signal(str)
password_required = Signal(str) # Emits error message when password is required
def __init__(self, zip_path, password=None):
super().__init__()
self.archive_path = zip_path # Renamed for clarity with generic archive_manager
self.password = password
self.result = None # Add result attribute to store results
def run(self):
try:
print(f"[DEBUG] ListZipContentsWorker: Starting to list contents of {self.archive_path}")
contents = list_archive_contents(self.archive_path, password=self.password)
print(f"[DEBUG] ListZipContentsWorker: Got {len(contents) if contents else 0} items")
self.result = contents # 设置result属性
self.finished.emit(contents)
except RuntimeError as e:
# Handle password required case
print(f"[DEBUG] ListZipContentsWorker: RuntimeError - {str(e)}")
if "password" in str(e).lower() or "encrypted" in str(e).lower():
self.password_required.emit(str(e))
else:
self.conversion_error.emit(str(e))
except Exception as e:
print(f"[DEBUG] ListZipContentsWorker: Exception - {str(e)}")
import traceback
traceback.print_exc()
self.conversion_error.emit(str(e))
class ZipGUI(QMainWindow):
def _load_qss_file(self, filename):
"""Load QSS content from external file"""
qss_path = os.path.join(os.path.dirname(__file__), 'qss', filename)
try:
with open(qss_path, 'r', encoding='utf-8') as f:
return f.read()
except FileNotFoundError:
print(f"Warning: QSS file not found: {qss_path}")
return ""
except Exception as e:
print(f"Error loading QSS file {qss_path}: {e}")
return ""
def _show_popup(self, target, icon, title, content, duration=2000):
"""Display popup and print message to console"""
print(f"[{title}] {content}") # Print message to console
PopupTeachingTip.create(
target=target,
icon=icon,
title=title,
content=content,
isClosable=True,
tailPosition=TeachingTipTailPosition.TOP,
duration=duration,
parent=self
)
def _show_info_bar(self, title, content, icon=InfoBarIcon.SUCCESS, duration=2000):
"""Display info bar and print message to console"""
print(f"[{title}] {content}") # Print message to console
InfoBar.success(
title=title,
content=content,
orient=Qt.Orientation.Horizontal,
isClosable=True,
position=InfoBarPosition.TOP,
duration=duration,
parent=self
)
@property
def LIGHT_QSS(self):
"""Load light theme QSS from external file"""
return self._load_qss_file('zip_light.qss')
@property
def DARK_QSS(self):
"""Load dark theme QSS from external file"""
return self._load_qss_file('zip_dark.qss')
def __init__(self, initial_dark_mode=False):
super().__init__()
self.setWindowTitle("Archive File Processing Tool")
self.setGeometry(200, 200, 800, 600)
self.setMinimumSize(600, 780)
# Enable drag and drop for the main window
self.setAcceptDrops(True)
self.themeListener = SystemThemeListener(self)
self.init_variables()
self.setup_ui()
self._apply_theme(initial_dark_mode)
self.center_window() # Center the window after UI setup
self.qss_combo=CON.qss_combo
setTheme(Theme.AUTO)
self.themeListener.start()
qconfig.themeChanged.connect(self._onThemeChanged)
def closeEvent(self, event):
"""Window close event"""
# Stop listener thread
if hasattr(self, 'themeListener'):
self.themeListener.terminate()
self.themeListener.deleteLater()
super().closeEvent(event)
def _onThemeChanged(self, theme: Theme):
"""Theme change handling"""
# Update interface to respond to theme changes
self.update()
setTheme(Theme.AUTO)
def init_variables(self):
# Variables for Create ZIP tab
self.create_sources = []
self.create_output_path = ""
self.create_archive_format = "zip" # Default to zip
self.create_zip_worker_thread = None # Renamed to generic for clarity
self.create_zip_worker = None # Renamed to generic for clarity
# Variables for Extract ZIP tab
self.extract_zip_path = ""
self.extract_dest_path = ""
self.extract_zip_worker_thread = None # Renamed to generic for clarity
self.extract_zip_worker = None # Renamed to generic for clarity
# Variables for Add to ZIP tab
self.add_zip_path = ""
self.add_file_path = ""
self.add_to_zip_worker_thread = None # Renamed to generic for clarity
self.add_to_zip_worker = None # Renamed to generic for clarity
# Variables for List Contents tab
self.list_zip_path = ""
self.list_zip_worker_thread = None # Renamed to generic for clarity
self.list_zip_worker = None # Renamed to generic for clarity
# Password protection status for archive contents
self.is_password_protected = False
self._current_password = None
def setup_ui(self):
self.main_widget = QWidget(self)
self.setCentralWidget(self.main_widget)
self.main_layout = QVBoxLayout(self.main_widget)
# Initialize status bar
self.status_bar = self.statusBar()
self.status_bar.showMessage("Ready")
self.notebook = QTabWidget(self.main_widget)
self.main_layout.addWidget(self.notebook, 1) # Add notebook with stretch
self.create_create_tab()
self.create_extract_tab()
self.create_add_tab()
self.create_list_tab()
# Connect tab change event
self.notebook.currentChanged.connect(self.on_tab_changed)
# Add a stretch to the main_layout to push everything to the top
self.main_layout.addStretch(1)
# Apply custom stylesheets to all buttons after UI creation
self.apply_custom_styles()
def _apply_theme(self, is_dark_mode):
if is_dark_mode:
self.setStyleSheet(self.DARK_QSS)
else:
self.setStyleSheet(self.LIGHT_QSS)
def _apply_system_theme(self, is_dark_mode):
self._apply_theme(is_dark_mode)
def center_window(self):
qr = self.frameGeometry()
cp = self.screen().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def apply_custom_styles(self):
"""Apply custom stylesheets to all buttons after UI creation"""
try:
# Find all PushButton and PrimaryPushButton widgets and apply custom styles
for button in self.findChildren(PushButton):
setCustomStyleSheet(button, CON.qss, CON.qss)
for button in self.findChildren(PrimaryPushButton):
setCustomStyleSheet(button, CON.qss, CON.qss)
except Exception as e:
print(f"Warning: Could not apply custom stylesheets: {e}")
# --- Tab creation methods (to be implemented with PySide6 widgets) ---
def create_create_tab(self):
tab_panel = QWidget()
tab_sizer = QVBoxLayout(tab_panel)
self.notebook.addTab(tab_panel, "Create Archive") # Changed tab title
# Output file selection
output_box = QGroupBox("Output Archive File") # Changed group box title
output_box_sizer = QHBoxLayout(output_box)
self.create_output_text = LineEdit()
setCustomStyleSheet(self.create_output_text, CON.qss_line, CON.qss_line)
# self.create_output_text.setReadOnly(True) # Allow users to manually input path
output_box_sizer.addWidget(self.create_output_text, 1)
output_button = PushButton("Browse...")
output_button.clicked.connect(self.browse_create_output)
output_box_sizer.addWidget(output_button)
tab_sizer.addWidget(output_box)
# Archive Format Selection (new)
format_layout = QHBoxLayout()
format_label = QLabel("Archive Format:")
self.create_format_combo = ModelComboBox()
# Filter formats to only allow creation of supported types
creation_formats = []
for fmt in SUPPORTED_ARCHIVE_FORMATS:
if fmt != 'tgz':
creation_formats.append(fmt.upper())
self.create_format_combo.addItems(creation_formats)
self.create_format_combo.setCurrentText("ZIP")
setCustomStyleSheet(self.create_format_combo, CON.qss_combo, CON.qss_combo)
format_layout.addWidget(format_label)
format_layout.addWidget(self.create_format_combo, 1)
tab_sizer.addLayout(format_layout)
# Source files list
sources_box = QGroupBox("Source Files/Directories")
sources_box_sizer = QVBoxLayout(sources_box)
self.sources_listbox = ListWidget()
self.sources_listbox.setMinimumHeight(280) # Set minimum height
sources_box_sizer.addWidget(self.sources_listbox, 1) # Increase stretch weight
# Set right-click to immediately select
self.sources_listbox.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
# Context menu functionality removed
# self.sources_listbox.customContextMenuRequested.connect(self.show_sources_context_menu)
# Buttons to add/remove sources
button_sizer = QHBoxLayout()
add_files_button = PushButton("Add Files...")
add_files_button.clicked.connect(self.add_source_files)
button_sizer.addWidget(add_files_button)
add_folder_button = PushButton("Add Folder...")
add_folder_button.clicked.connect(self.add_source_folder)
button_sizer.addWidget(add_folder_button)
remove_button = PushButton("Remove Selected")
remove_button.clicked.connect(self.remove_source)
button_sizer.addWidget(remove_button)
button_sizer.addStretch(1) # Push buttons to left
sources_box_sizer.addLayout(button_sizer)
tab_sizer.addWidget(sources_box, 1) # Give sources box more stretch
# Progress bar
self.create_progress_label = QLabel("")
tab_sizer.addWidget(self.create_progress_label)
self.create_progress = ProgressBar()
self.create_progress.setRange(0, 100)
self.create_progress.setValue(0)
tab_sizer.addWidget(self.create_progress)
# Create button
self.create_button = PrimaryPushButton("Create Archive") # Changed button text
self.create_button.clicked.connect(self.start_create_archive) # Changed signal
tab_sizer.addWidget(self.create_button, 0, Qt.AlignmentFlag.AlignCenter)
tab_sizer.addStretch(1) # Push content to top
def create_extract_tab(self):
tab_panel = QWidget()
tab_sizer = QVBoxLayout(tab_panel)
self.notebook.addTab(tab_panel, "Extract Archive") # Changed tab title
# Archive file selection (changed title)
zip_box = QGroupBox("Archive File to Extract")
zip_box_sizer = QHBoxLayout(zip_box)
self.extract_zip_text = LineEdit()
setCustomStyleSheet(self.extract_zip_text, CON.qss_line, CON.qss_line)
# self.extract_zip_text.setReadOnly(True) # Allow users to manually input path
zip_box_sizer.addWidget(self.extract_zip_text, 1)
zip_button = PushButton("Browse...")
zip_button.clicked.connect(self.browse_extract_archive) # Changed signal
zip_box_sizer.addWidget(zip_button)
tab_sizer.addWidget(zip_box)
# Destination folder selection
dest_box = QGroupBox("Destination Folder")
dest_box_sizer = QHBoxLayout(dest_box)
self.extract_dest_text = LineEdit()
setCustomStyleSheet(self.extract_dest_text, CON.qss_line, CON.qss_line)
# self.extract_dest_text.setReadOnly(True) # Allow users to manually input path
dest_box_sizer.addWidget(self.extract_dest_text, 1)
dest_button = PushButton("Browse...")
dest_button.clicked.connect(self.browse_extract_dest)
dest_box_sizer.addWidget(dest_button)
tab_sizer.addWidget(dest_box)
# Password status indicator
password_status_box = QHBoxLayout()
self.extract_password_status_label = QLabel("Archive Status: Unknown")
self.extract_password_status_icon = QLabel()
self.extract_password_status_icon.setFixedSize(16, 16)
password_status_box.addWidget(self.extract_password_status_label)
password_status_box.addWidget(self.extract_password_status_icon)
password_status_box.addStretch()
tab_sizer.addLayout(password_status_box)
# Progress bar
self.extract_progress_label = QLabel("")
tab_sizer.addWidget(self.extract_progress_label)
self.extract_progress = ProgressBar()
self.extract_progress.setRange(0, 100)
self.extract_progress.setValue(0)
tab_sizer.addWidget(self.extract_progress)
# Extract button
self.extract_button = PrimaryPushButton("Extract Archive") # Changed button text
self.extract_button.clicked.connect(self.start_extract_archive) # Changed signal
tab_sizer.addWidget(self.extract_button, 0, Qt.AlignmentFlag.AlignCenter)
tab_sizer.addStretch(1) # Push content to top
def create_add_tab(self):
tab_panel = QWidget()
tab_sizer = QVBoxLayout(tab_panel)
self.notebook.addTab(tab_panel, "Add to Archive") # Changed tab title
# Existing Archive file selection
zip_box = QGroupBox("Existing Archive File") # Changed group box title
zip_box_sizer = QHBoxLayout(zip_box)
self.add_zip_text = LineEdit()
setCustomStyleSheet(self.add_zip_text, CON.qss_line, CON.qss_line)
# self.add_zip_text.setReadOnly(True) # Allow users to manually input path
zip_box_sizer.addWidget(self.add_zip_text, 1)
zip_button = PushButton("Browse...")
zip_button.clicked.connect(self.browse_add_archive) # Changed signal
zip_box_sizer.addWidget(zip_button)
tab_sizer.addWidget(zip_box)
# File to add selection
file_box = QGroupBox("Files to Add")
file_box_sizer = QVBoxLayout(file_box)
# File list for multiple files (always visible)
self.add_files_listbox = ListWidget()
self.add_files_listbox.setMinimumHeight(150)
self.add_files_listbox.setVisible(True) # Always visible
file_box_sizer.addWidget(self.add_files_listbox)
# Browse button
file_button = PushButton("Browse...")
file_button.clicked.connect(self.browse_add_file)
file_box_sizer.addWidget(file_button)
tab_sizer.addWidget(file_box)
# Progress bar
self.add_progress_label = QLabel("")
tab_sizer.addWidget(self.add_progress_label)
self.add_progress = ProgressBar()
self.add_progress.setRange(0, 100)
self.add_progress.setValue(0)
tab_sizer.addWidget(self.add_progress)
# Add button
self.add_button = PrimaryPushButton("Add to Archive") # Changed button text
self.add_button.clicked.connect(self.start_add_to_archive) # Changed signal
tab_sizer.addWidget(self.add_button, 0, Qt.AlignmentFlag.AlignCenter)
tab_sizer.addStretch(1) # Push content to top
def create_list_tab(self):
tab_panel = QWidget()
tab_sizer = QVBoxLayout(tab_panel)
self.notebook.addTab(tab_panel, "List Contents")
# Archive file selection (changed title)
zip_box = QGroupBox("Archive File")
zip_box_sizer = QHBoxLayout(zip_box)
self.list_zip_text = LineEdit()
setCustomStyleSheet(self.list_zip_text, CON.qss_line, CON.qss_line)
# self.list_zip_text.setReadOnly(True) # Allow users to manually input path
zip_box_sizer.addWidget(self.list_zip_text, 1)
zip_button = PushButton("Browse...")
zip_button.clicked.connect(self.browse_list_archive) # Changed signal
zip_box_sizer.addWidget(zip_button)
tab_sizer.addWidget(zip_box)
# Password status indicator
password_status_box = QHBoxLayout()
self.password_status_label = QLabel("Archive Status: Unknown")
self.password_status_icon = QLabel()
self.password_status_icon.setFixedSize(16, 16)
password_status_box.addWidget(self.password_status_label)
password_status_box.addWidget(self.password_status_icon)
password_status_box.addStretch()
tab_sizer.addLayout(password_status_box)
# Listbox for contents
contents_box = QGroupBox("Archive Contents") # Changed group box title
contents_box_sizer = QVBoxLayout(contents_box)
self.contents_listbox = ListWidget()
self.contents_listbox.setMinimumHeight(250) # Set larger minimum height
self.contents_listbox.setDragEnabled(True) # Enable drag functionality
contents_box_sizer.addWidget(self.contents_listbox, 3) # Increase stretch weight
# Set right-click menu
self.contents_listbox.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
# Context menu functionality removed
# self.contents_listbox.customContextMenuRequested.connect(self.show_contents_context_menu)
tab_sizer.addWidget(contents_box, 2) # Give contents box more stretch
# List button
self.list_button = PrimaryPushButton("List Contents")
self.list_button.clicked.connect(self.start_list_archive_contents) # Changed signal
tab_sizer.addWidget(self.list_button, 0, Qt.AlignmentFlag.AlignCenter)
tab_sizer.addStretch(1) # Push content to top
# --- Event handlers (converted to PySide6) ---
def update_password_status(self, is_protected, status_text=None, tab="list"):
"""Update the password status indicator with improved visual feedback
Args:
is_protected: Whether the archive is password protected
status_text: Optional custom status text
tab: Which tab to update ('list' or 'extract')
"""
# Update the password protection status attribute
self.is_password_protected = is_protected
# Determine which label and icon to update based on the tab
if tab == "list":
status_label = getattr(self, 'password_status_label', None)
status_icon = getattr(self, 'password_status_icon', None)
elif tab == "extract":
status_label = getattr(self, 'extract_password_status_label', None)
status_icon = getattr(self, 'extract_password_status_icon', None)
else:
return # Invalid tab specified
if not status_label or not status_icon:
return # UI elements not available
if is_protected:
status_label.setText("Archive Status: Password Protected")
# Set icon to locked - use our new SVG icon
icon_path = os.path.join(os.path.dirname(__file__), "assets", "lock.svg")
if os.path.exists(icon_path):
try:
# Use SVG icon with proper scaling
pixmap = QPixmap(icon_path)
scaled_pixmap = pixmap.scaled(16, 16, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
status_icon.setPixmap(scaled_pixmap)
# Set a tooltip for additional information
status_icon.setToolTip("This archive is password protected")
except:
# Fallback to text indicator if GUI is not available
status_icon.setText("🔒")
status_icon.setToolTip("This archive is password protected")
else:
# Fallback to text indicator if icon not available
status_icon.setText("🔒")
status_icon.setToolTip("This archive is password protected")
# Set label style to indicate password protection
status_label.setStyleSheet("color: #e67e22; font-weight: bold;")
else:
if status_text:
status_label.setText(f"Archive Status: {status_text}")
else:
status_label.setText("Archive Status: No Password Protection")
# Set icon to unlocked - use our new SVG icon
icon_path = os.path.join(os.path.dirname(__file__), "assets", "unlock.svg")
if os.path.exists(icon_path):
try:
# Use SVG icon with proper scaling
pixmap = QPixmap(icon_path)
scaled_pixmap = pixmap.scaled(16, 16, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)
status_icon.setPixmap(scaled_pixmap)
# Set a tooltip for additional information
status_icon.setToolTip("This archive is not password protected")
except:
# Fallback to text indicator if GUI is not available
status_icon.setText("🔓")
status_icon.setToolTip("This archive is not password protected")
else:
# Fallback to text indicator if icon not available
status_icon.setText("🔓")
status_icon.setToolTip("This archive is not password protected")
# Reset label style to normal
status_label.setStyleSheet("color: #27ae60; font-weight: normal;")
def update_password_status_list(self, is_protected, status_text=None):
"""Convenience method to update password status in the List tab"""
self.update_password_status(is_protected, status_text, "list")
def update_password_status_extract(self, is_protected, status_text=None):
"""Convenience method to update password status in the Extract tab"""
self.update_password_status(is_protected, status_text, "extract")
def update_archive_status(self, status_text, is_success=True):
"""Update the archive status indicator with visual feedback
Args:
status_text: Status text to display
is_success: Whether the operation was successful
"""
# Update the create progress label with the status
if hasattr(self, 'create_progress_label'):
self.create_progress_label.setText(status_text)
# Set style based on success/failure
if is_success:
self.create_progress_label.setStyleSheet("color: #27ae60; font-weight: bold;")
else:
self.create_progress_label.setStyleSheet("color: #e74c3c; font-weight: bold;")
# Reset style after a delay
QTimer.singleShot(5000, lambda: self.create_progress_label.setStyleSheet(""))
def _verify_password_strength(self, password):
"""Verify password strength for archive creation
Args:
password: Password to verify
Returns:
bool: True if password meets minimum requirements, False otherwise
"""
if not password:
return False
# Basic password strength check
if len(password) < 6:
return False
# Password is considered valid for archive creation
# We don't need to verify it against an existing archive since we're creating a new one
return True
def on_tab_changed(self, index):
"""Handle tab change with optional slide animation effect based on UI_FLUENT environment variable"""
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'support'))
from support.check_flag import check_flag
# Check if UI_FLUENT environment variable is set to YES using check_flag function
ui_fluent_enabled = check_flag("UI_FLUENT")
# Skip animation if UI_FLUENT is not enabled
if not ui_fluent_enabled:
self._previous_tab_index = index
# Force layout update when animation is disabled
self.notebook.currentWidget().updateGeometry()
if self.notebook.currentWidget().layout():
self.notebook.currentWidget().layout().update()
self.notebook.currentWidget().layout().activate()
return
# Proceed with animation if UI_FLUENT is enabled
from PySide6.QtCore import QPropertyAnimation, QEasingCurve, QRect
# Get current tab widget
current_widget = self.notebook.currentWidget()
if not current_widget:
return
# Skip animation during initial startup to prevent layout issues
if not hasattr(self, '_previous_tab_index') and not self.notebook.isVisible():
self._previous_tab_index = index
return
# Get tab widget dimensions
tab_width = self.notebook.width()
tab_height = self.notebook.height()
# Skip animation if window is not yet properly sized
if tab_width <= 0 or tab_height <= 0:
self._previous_tab_index = index
return
# Determine slide direction based on tab index
if hasattr(self, '_previous_tab_index'):
if index > self._previous_tab_index:
# Sliding from right to left - start from 80% of width to prevent going out of bounds
start_pos = QRect(int(tab_width * 0.8), 0, tab_width, tab_height)
else:
# Sliding from left to right - start from -80% of width to prevent going out of bounds
start_pos = QRect(int(-tab_width * 0.8), 0, tab_width, tab_height)
else:
# First time, slide from right - start from 80% of width
start_pos = QRect(int(tab_width * 0.8), 0, tab_width, tab_height)
# Set initial position
current_widget.setGeometry(start_pos)
# Create slide animation
self.slide_animation = QPropertyAnimation(current_widget, b"geometry")
self.slide_animation.setDuration(300) # 300ms animation for smooth slide
self.slide_animation.setStartValue(start_pos)
self.slide_animation.setEndValue(QRect(0, 0, tab_width, tab_height))
self.slide_animation.setEasingCurve(QEasingCurve.Type.OutCubic)
# Store current tab index for next animation
self._previous_tab_index = index
# Connect animation finished signal to update layout
self.slide_animation.finished.connect(lambda: self._update_tab_layout(current_widget))
# Start the animation
self.slide_animation.start()
def _update_tab_layout(self, widget):
"""Update widget layout after animation completes"""
# Force layout update to prevent layout issues
if widget and widget.layout():
widget.layout().update()
widget.layout().activate()
widget.updateGeometry()
# Repaint the widget to ensure all elements are properly displayed
widget.repaint()
def browse_create_output(self):
file_dialog = QFileDialog(self)
selected_format = self.create_archive_format
# Generate wildcard for creation, excluding formats not supported for creation
creation_formats = [f.upper() for f in SUPPORTED_ARCHIVE_FORMATS if f != 'tgz']
wildcard_parts = [f"{fmt} files (*.{fmt.lower()})" for fmt in creation_formats]
wildcard = ";;".join(wildcard_parts) + ";;All files (*.*)"
file_dialog.setNameFilter(wildcard)
file_dialog.setAcceptMode(QFileDialog.AcceptMode.AcceptSave)
file_dialog.setDefaultSuffix(selected_format)
if file_dialog.exec():
self.create_output_path = file_dialog.selectedFiles()[0]
if not self.create_output_path.lower().endswith(f".{selected_format}"):
self.create_output_path += f".{selected_format}"
self.create_output_text.setText(self.create_output_path)
def add_source_files(self):
file_dialog = QFileDialog(self)
file_dialog.setNameFilter("All files (*.*)")
file_dialog.setFileMode(QFileDialog.FileMode.ExistingFiles)
if file_dialog.exec():
paths = file_dialog.selectedFiles()
for path in paths:
if path not in self.create_sources:
self.create_sources.append(path)
self.sources_listbox.addItem(path)
def add_source_folder(self):
dir_dialog = QFileDialog(self)
dir_dialog.setFileMode(QFileDialog.FileMode.Directory)
dir_dialog.setOption(QFileDialog.Option.ShowDirsOnly, True)
if dir_dialog.exec():
folder_path = dir_dialog.selectedFiles()[0]
if folder_path not in self.create_sources:
self.create_sources.append(folder_path)
self.sources_listbox.addItem(f"[FOLDER] {folder_path}")
def remove_source(self):
"""Remove selected source files"""
if not self.sources_listbox.selectedIndexes():
self._show_popup(
target=self.sources_listbox,
icon=InfoBarIcon.WARNING,
title='Warning',
content='Please select items to remove first',
duration=3000
)
return
# Get selected rows
selected_rows = sorted(set(index.row() for index in self.sources_listbox.selectedIndexes()), reverse=True)
# Remove from back to front to avoid index changes
for row in selected_rows:
self.sources_listbox.takeItem(row)
if row < len(self.create_sources):
self.create_sources.pop(row)
# Show removal success message
self._show_info_bar(
icon=InfoBarIcon.SUCCESS,
title='Removal Successful',
content=f'Removed {len(selected_rows)} items',
duration=2000
)
def update_create_progress(self, message, progress):
self.create_progress_label.setText(message)
print(f"[Create Progress] {message}") # Print progress information to console
if progress >= 0:
self.create_progress.setValue(int(progress))
def start_create_archive(self):
# Check if output file is specified
if not self.create_output_path:
self._show_popup(
target=self.create_output_text,
icon=InfoBarIcon.WARNING,
title='Warning',
content='Please specify output file path',
duration=3000
)
return
# Check if source files are added
if not self.create_sources:
self._show_popup(
target=self.sources_listbox,
icon=InfoBarIcon.WARNING,
title='Warning',
content='Please add files or folders to compress',
duration=3000
)
return
# RAR format is now supported through external rar command
# No need to show error message
# Check if password protection is needed
password = None
max_password_attempts = 3
password_attempt = 0
if self.create_archive_format in ['zip', 'rar', '7z']:
# Ask user if they want to add password protection
from qfluentwidgets import MessageBox, FluentIcon
box = MessageBox(
'Password Protection',
f'Do you want to add password protection to the {self.create_archive_format.upper()} archive?',
self
)
box.yesButton.setText('Yes, add password')
box.cancelButton.setText('No, create without password')
if box.exec():
# User wants to add password protection
while password_attempt < max_password_attempts:
password_attempt += 1
from password_dialog import get_password
prompt_text = f"Enter password for the {self.create_archive_format.upper()} archive:"
if password_attempt >=2:
prompt_text = f"Password verification failed. Please try again ({password_attempt}/{max_password_attempts}):"
password = get_password(self, "Set Password", prompt_text)
if not password:
# User cancelled password entry
self._show_popup(
target=self.create_progress,
icon=InfoBarIcon.WARNING,
title='Cancelled',
content='Archive creation cancelled.',
duration=2000
)
return
# Verify password by creating a small test archive
if self._verify_password_strength(password):
# Password is valid, break the loop
break
else:
# Password is too weak or invalid
if password_attempt >= max_password_attempts:
self._show_popup(
target=self.create_progress,
icon=InfoBarIcon.ERROR,
title='Password Verification Failed',
content=f'Failed to verify password after {max_password_attempts} attempts. Archive creation cancelled.',
duration=3000
)
return
else:
self._show_popup(
target=self.create_progress,
icon=InfoBarIcon.WARNING,
title='Weak Password',
content='Please enter a stronger password (at least 6 characters).',
duration=2000
)
password = None # Reset password to try again
self.create_progress_label.setText("Starting archive creation...")
self.create_progress.setValue(0)
self.create_zip_worker = CreateZipWorker(self.create_output_path, self.create_sources, self.create_archive_format, password)
self.create_zip_worker_thread = QThread()
self.create_zip_worker.moveToThread(self.create_zip_worker_thread)
self.create_zip_worker.finished.connect(self.on_create_archive_finished)
self.create_zip_worker.progress_updated.connect(self.update_create_progress)
self.create_zip_worker.conversion_error.connect(self.on_create_archive_error)
self.create_zip_worker_thread.started.connect(self.create_zip_worker.run)
self.create_zip_worker_thread.start()
def on_create_archive_finished(self):
# 使用强制线程清理方法
self._force_cleanup_create_thread()
# Update archive status
archive_info = f"Archive created successfully: {os.path.basename(self.create_output_path)}"
if self.create_zip_worker and hasattr(self.create_zip_worker, 'password') and self.create_zip_worker.password:
archive_info += " (Password Protected)"
# Show success notification at the top
self._show_info_bar(
title='Success',
content=archive_info,
duration=2000
)
# Update archive status display
self.update_archive_status(archive_info, True)
def on_create_archive_error(self, error_message):
# 使用强制线程清理方法
self._force_cleanup_create_thread()
# Update archive status
archive_info = f"Archive creation failed: {str(error_message)}"
self._show_popup(
target=self.create_progress,
icon=InfoBarIcon.ERROR,
title='Error',
content=f'Error creating archive: {str(error_message)}',
duration=3000
)
self.create_progress_label.setText("Archive creation failed.")
# Update archive status display
self.update_archive_status(archive_info, False)