-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsyncXUi.py
More file actions
892 lines (795 loc) · 40 KB
/
syncXUi.py
File metadata and controls
892 lines (795 loc) · 40 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
# syncx_fixed.py
import sys
import os
import shutil
import time
import getpass
import socket
import hashlib
from pathlib import Path
from typing import Iterable, List, Dict, Set, Tuple
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QLineEdit, QLabel, QFileDialog, QFrame, QComboBox,
QPlainTextEdit, QTreeWidget, QTreeWidgetItem, QHeaderView, QStyle, QCheckBox, QMenu
)
from PySide6.QtCore import Qt, QThread, Signal, QObject, QTimer, QSize, QFileSystemWatcher
from PySide6.QtGui import QIcon, QPixmap, QPainter, QColor
# --- Configuration ---
APP_NAME = "syncX"
APP_VERSION = "2.2.9"
DEBOUNCE_DELAY_MS = 2500
HASH_BLOCK_SIZE = 65536 # 64 KB
# --- Stylesheet (Unchanged) ---
STYLESheet = """
QWidget { background-color: #3c3c3c; color: #f0f0f0; font-family: Segoe UI; font-size: 10pt; }
QMainWindow { border: 1px solid #2a2a2a; }
QLineEdit { background-color: #2a2a2a; border: 1px solid #555; padding: 5px; border-radius: 4px; }
QPushButton { background-color: #555; border: 1px solid #666; padding: 6px 12px; border-radius: 4px; }
QPushButton:hover { background-color: #7d4a1c; border: 1px solid #6a3e16; color: #fff; }
QPushButton:pressed { background-color: #d35400; border: 1px solid #b84a00; }
QTreeWidget { background-color: #2a2a2a; border: 1px solid #555; border-radius: 4px; alternate-background-color: #424242; }
QTreeWidget::item:hover { background-color: #4f4f4f; }
QTreeWidget::item:selected { background-color: #e67e22; color: #fff; }
QHeaderView::section { background-color: #4a4a4a; padding: 4px; border: 1px solid #2a2a2a; }
QLabel { font-weight: bold; }
QCheckBox::indicator { width: 18px; height: 18px; }
QPushButton:disabled, QComboBox:disabled, QCheckBox:disabled { background-color: #4a4a4a; color: #888; border: 1px solid #555; }
QLineEdit:disabled { background-color: #333; color: #777; }
"""
def create_status_icon(color: str) -> QIcon:
pixmap = QPixmap(16, 16)
pixmap.fill(Qt.transparent)
painter = QPainter(pixmap)
painter.setRenderHint(QPainter.Antialiasing)
painter.setBrush(QColor(color))
painter.setPen(Qt.NoPen)
painter.drawEllipse(0, 0, 16, 16)
painter.end()
return QIcon(pixmap)
# -------------------
# Worker: CheckWorker
# - Runs a pre-check of top-level items
# - Emits update_item_status(name, status) for UI updates
# - Supports cooperative cancellation via stop()
# -------------------
class CheckWorker(QObject):
update_item_status = Signal(str, str)
finished = Signal()
def __init__(self, source_dir: str, dest_dir: str, items_to_check: Iterable[str]):
super().__init__()
self.source_path = Path(source_dir)
self.dest_path = Path(dest_dir)
self.items = list(items_to_check)
self._running = True
def stop(self) -> None:
self._running = False
def _is_running(self) -> bool:
return self._running
def run(self) -> None:
try:
for item_name in self.items:
if not self._is_running():
break
source_item = self.source_path / item_name
dest_item = self.dest_path / item_name
# If source missing -> mark error (we're scanning from source perspective)
if not source_item.exists():
self.update_item_status.emit(item_name, "error")
continue
# If dest doesn't exist -> needs sync
if not dest_item.exists():
self.update_item_status.emit(item_name, "needs_sync")
continue
# If type mismatch -> needs sync (copy over)
if source_item.is_dir() != dest_item.is_dir():
self.update_item_status.emit(item_name, "needs_sync")
continue
# If files, compare timestamp
if source_item.is_file() and dest_item.is_file():
if source_item.stat().st_mtime > dest_item.stat().st_mtime:
self.update_item_status.emit(item_name, "needs_sync")
else:
self.update_item_status.emit(item_name, "synced")
continue
# If directories, compare mtime (coarse)
if source_item.is_dir() and dest_item.is_dir():
if source_item.stat().st_mtime > dest_item.stat().st_mtime:
self.update_item_status.emit(item_name, "needs_sync")
else:
self.update_item_status.emit(item_name, "synced")
continue
# Fallback
self.update_item_status.emit(item_name, "unknown")
finally:
self.finished.emit()
# -------------------
# Worker: SyncWorker
# - Robust, cancellable sync worker
# - Supports:
# * One-way sync (Source -> Dest)
# * Reverse (Dest -> Source) same codepath by swapping dirs
# * Two-way mirror: newer -> older; items only on one side are copied to the other (no auto-delete)
# - Emits:
# * log_message(str)
# * update_item_status(top_level_name, status)
# * sync_finished(message)
# - Cancellation: stop() sets running False and worker checks it frequently
# -------------------
class SyncWorker(QObject):
log_message = Signal(str)
update_item_status = Signal(str, str)
sync_finished = Signal(str)
progress = Signal(int) # percent (optional; emitted per top-level item)
def __init__(self):
super().__init__()
self._running = False
self.source_dir = ""
self.dest_dir = ""
self.speed_mode = "Fast (Timestamp)"
self.enable_deletions = False
self.top_level_items_to_sync: List[str] = []
self.mode = "Source to Destination" # or "Destination to Source" or "Mirroring Both"
# --- control ---
def stop(self) -> None:
self._running = False
def _is_running(self) -> bool:
return self._running
def calculate_hash(self, file_path: Path) -> str:
h = hashlib.sha256()
try:
with file_path.open("rb") as f:
for chunk in iter(lambda: f.read(HASH_BLOCK_SIZE), b""):
h.update(chunk)
return h.hexdigest()
except Exception:
return ""
def log_header(self, title: str) -> None:
header = f"\n{'='*60}\n{title} | {time.strftime('%Y-%m-%d %H:%M:%S')} | User: {getpass.getuser()} | Host: {socket.gethostname()}\n{'='*60}"
self.log_message.emit(header)
def run(self) -> None:
if self._is_running():
# already running - avoid concurrent runs
self.log_message.emit("SyncWorker already running")
return
self._running = True
try:
self.log_header("Sync Started")
if self.mode == "Mirroring Both":
self._run_mirror_mode()
else:
self._run_one_way_mode()
if self._is_running():
self.log_header("Sync Completed")
self.sync_finished.emit("Sync finished successfully.")
else:
self.log_header("Sync Stopped")
self.sync_finished.emit("Sync was stopped by user.")
except Exception as e:
self.log_message.emit(f"[FATAL] Sync worker raised: {e}")
self.sync_finished.emit(f"Sync failed: {e}")
finally:
self._running = False
# -------------------
# One-way sync: copy from source_dir -> dest_dir
# If enable_deletions True: delete items present in dest but not in source
# -------------------
def _run_one_way_mode(self) -> None:
source_root = Path(self.source_dir)
dest_root = Path(self.dest_dir)
total = len(self.top_level_items_to_sync) if self.top_level_items_to_sync else 0
processed = 0
# If there are no explicit top-level items, we'll sync everything under source_root
items = list(self.top_level_items_to_sync) if self.top_level_items_to_sync else [p.name for p in source_root.glob("*")]
for item_name in items:
if not self._is_running():
return
processed += 1
self.update_item_status.emit(item_name, "syncing")
source_item = source_root / item_name
dest_item = dest_root / item_name
try:
if not source_item.exists():
self.log_message.emit(f"[WARN] Source missing: {source_item}")
self.update_item_status.emit(item_name, "error")
continue
# Directory case: replicate recursively
if source_item.is_dir():
self._sync_directory_one_way(source_item, dest_item, top_level_name=item_name)
elif source_item.is_file():
self._sync_file(source_item, dest_item, top_level_name=item_name)
# mark synced if still running
if self._is_running():
self.update_item_status.emit(item_name, "synced")
except Exception as e:
self.log_message.emit(f"[ERROR] Top-level sync failed for {item_name}: {e}")
self.update_item_status.emit(item_name, "error")
# emit progress per-top-level
percent = int((processed / total) * 100) if total > 0 else 0
self.progress.emit(percent)
# deletion phase (only in one-way mode)
if self.enable_deletions and self._is_running():
self.log_message.emit("Checking for extra files to delete on destination...")
for dest_item in list(dest_root.rglob("*")):
if not self._is_running():
return
try:
rel = None
try:
rel = dest_item.relative_to(dest_root)
except Exception:
continue
source_counterpart = source_root / rel
if not source_counterpart.exists():
# safe deletion: remove files and empty dirs (try to remove dirs only if empty)
self.log_message.emit(f"Deleting (one-way): {dest_item}")
if dest_item.is_dir():
try:
shutil.rmtree(dest_item)
except Exception as e:
self.log_message.emit(f"[ERROR] Failed to delete directory {dest_item}: {e}")
else:
try:
dest_item.unlink()
except Exception as e:
self.log_message.emit(f"[ERROR] Failed to delete file {dest_item}: {e}")
except Exception as e:
self.log_message.emit(f"[ERROR] Deletion phase: {e}")
def _sync_directory_one_way(self, src_dir: Path, dst_dir: Path, top_level_name: str) -> None:
# Ensure base destination exists
if not dst_dir.exists():
self.log_message.emit(f"Creating directory: {dst_dir}")
dst_dir.mkdir(parents=True, exist_ok=True)
# Walk src_dir
for src in src_dir.rglob("*"):
if not self._is_running():
return
rel = src.relative_to(src_dir)
target = dst_dir / rel
try:
if src.is_dir():
if not target.exists():
self.log_message.emit(f"Creating subdirectory: {target}")
target.mkdir(parents=True, exist_ok=True)
elif src.is_file():
# decide whether to copy
should_copy = self._should_copy(src, target)
if should_copy:
self.update_item_status.emit(top_level_name, "syncing")
self.log_message.emit(f"Copying: {top_level_name}/{rel} ({src.stat().st_size / 1e6:.2f} MB)")
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, target)
except Exception as e:
self.log_message.emit(f"[ERROR] Failed to copy {src} -> {target}: {e}")
self.update_item_status.emit(top_level_name, "error")
def _sync_file(self, src_file: Path, dst_file: Path, top_level_name: str) -> None:
try:
if self._should_copy(src_file, dst_file):
self.log_message.emit(f"Copying: {src_file} ({src_file.stat().st_size / 1e6:.2f} MB)")
dst_file.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src_file, dst_file)
except Exception as e:
self.log_message.emit(f"[ERROR] Failed to copy file {src_file} -> {dst_file}: {e}")
self.update_item_status.emit(top_level_name, "error")
def _should_copy(self, src: Path, dst: Path) -> bool:
# If destination missing -> copy
if not dst.exists():
return True
# Timestamp mode
if self.speed_mode == "Fast (Timestamp)":
try:
return src.stat().st_mtime > dst.stat().st_mtime
except Exception:
return True
# Checksum mode
if self.speed_mode == "Slow (Checksum)":
try:
return self.calculate_hash(src) != self.calculate_hash(dst)
except Exception:
return True
# fallback: copy if sizes differ
try:
return src.stat().st_size != dst.stat().st_size
except Exception:
return True
# -------------------
# Mirror mode (two-way)
# Behavior:
# - Union of top-level items from both source and dest are processed.
# - For each file, the newer file (by mtime) is copied to the older side.
# - If a file exists only on one side -> it's copied to the other side.
# - NO deletions are performed in mirror mode by default (safer). If you really want deletions in mirror mode,
# enable_deletions will attempt to delete items present on one side only (USE WITH CAUTION).
# -------------------
def _run_mirror_mode(self) -> None:
path_a = Path(self.source_dir)
path_b = Path(self.dest_dir)
# Build top-level item set (union of both roots)
names_a = {p.name for p in path_a.glob("*") if p.exists()}
names_b = {p.name for p in path_b.glob("*") if p.exists()}
names_union = sorted(names_a.union(names_b))
total = len(names_union)
processed = 0
for top_name in names_union:
if not self._is_running():
return
processed += 1
self.update_item_status.emit(top_name, "syncing")
a_item = path_a / top_name
b_item = path_b / top_name
try:
# Both exist
if a_item.exists() and b_item.exists():
# Type mismatch -> choose to copy directory over file or vice versa (prefer directory as structure)
if a_item.is_dir() and b_item.is_file():
# remove b and copy directory from a
self.log_message.emit(f"[MIRROR] Replacing file with directory: {b_item} <- {a_item}")
try:
b_item.unlink()
except Exception:
pass
shutil.copytree(a_item, b_item, dirs_exist_ok=True)
elif a_item.is_file() and b_item.is_dir():
self.log_message.emit(f"[MIRROR] Replacing directory with file: {b_item} <- {a_item}")
try:
shutil.rmtree(b_item)
except Exception:
pass
b_item.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(a_item, b_item)
else:
# same type - sync recursively (files: newer->older; dirs: sync contents)
if a_item.is_dir() and b_item.is_dir():
self._sync_directory_two_way(a_item, b_item, top_level_name=top_name)
elif a_item.is_file() and b_item.is_file():
# choose newer -> older, or hash if in checksum mode
choose_a = False
if self.speed_mode == "Fast (Timestamp)":
choose_a = a_item.stat().st_mtime > b_item.stat().st_mtime
else:
choose_a = self.calculate_hash(a_item) != self.calculate_hash(b_item) and a_item.stat().st_mtime >= b_item.stat().st_mtime
if choose_a:
self.log_message.emit(f"[MIRROR] Copy newer A -> B: {a_item} -> {b_item}")
b_item.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(a_item, b_item)
else:
if b_item.stat().st_mtime > a_item.stat().st_mtime:
self.log_message.emit(f"[MIRROR] Copy newer B -> A: {b_item} -> {a_item}")
a_item.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(b_item, a_item)
# Only in A -> copy to B
elif a_item.exists() and not b_item.exists():
# copy file or dir
if a_item.is_dir():
self.log_message.emit(f"[MIRROR] Copying directory A -> B: {a_item} -> {b_item}")
shutil.copytree(a_item, b_item, dirs_exist_ok=True)
else:
self.log_message.emit(f"[MIRROR] Copying file A -> B: {a_item} -> {b_item}")
b_item.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(a_item, b_item)
# Only in B -> copy to A
elif b_item.exists() and not a_item.exists():
if b_item.is_dir():
self.log_message.emit(f"[MIRROR] Copying directory B -> A: {b_item} -> {a_item}")
shutil.copytree(b_item, a_item, dirs_exist_ok=True)
else:
self.log_message.emit(f"[MIRROR] Copying file B -> A: {b_item} -> {a_item}")
a_item.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(b_item, a_item)
# else: neither exists (shouldn't happen)
if self._is_running():
self.update_item_status.emit(top_name, "synced")
except Exception as e:
self.log_message.emit(f"[ERROR][MIRROR] Failed for {top_name}: {e}")
self.update_item_status.emit(top_name, "error")
percent = int((processed / total) * 100) if total > 0 else 0
self.progress.emit(percent)
# Optional dangerous deletion in mirror mode (explicit)
if self.enable_deletions and self._is_running():
self.log_message.emit("[MIRROR] Deletions are enabled in mirror mode - performing cautious cleanup...")
# Deletion policy: Only delete files that are *explicitly* marked as removed on one side AND older than counterpart.
# This is left intentionally conservative; implement only if you understand the risk.
# (To keep the worker safe and clear, we do not implement aggressive deletion here.)
def _sync_directory_two_way(self, dir_a: Path, dir_b: Path, top_level_name: str) -> None:
# Walk union of both directories
names_a = {p.relative_to(dir_a) for p in dir_a.rglob("*") if p.exists()}
names_b = {p.relative_to(dir_b) for p in dir_b.rglob("*") if p.exists()}
union = sorted(names_a.union(names_b))
for rel in union:
if not self._is_running():
return
a_path = dir_a / rel
b_path = dir_b / rel
try:
# Both exist -> handle by type and timestamp/hash
if a_path.exists() and b_path.exists():
# Type mismatch - prefer directory structure
if a_path.is_dir() and b_path.is_file():
try:
b_path.unlink()
except Exception:
pass
shutil.copytree(a_path, b_path, dirs_exist_ok=True)
elif a_path.is_file() and b_path.is_dir():
try:
shutil.rmtree(b_path)
except Exception:
pass
b_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(a_path, b_path)
else:
if a_path.is_file() and b_path.is_file():
if self.speed_mode == "Fast (Timestamp)":
if a_path.stat().st_mtime > b_path.stat().st_mtime:
b_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(a_path, b_path)
elif b_path.stat().st_mtime > a_path.stat().st_mtime:
a_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(b_path, a_path)
else:
hash_a = self.calculate_hash(a_path)
hash_b = self.calculate_hash(b_path)
if hash_a != hash_b:
if a_path.stat().st_mtime >= b_path.stat().st_mtime:
b_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(a_path, b_path)
else:
a_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(b_path, a_path)
elif a_path.exists() and not b_path.exists():
# create parent in B
if a_path.is_dir():
shutil.copytree(a_path, b_path, dirs_exist_ok=True)
else:
b_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(a_path, b_path)
elif b_path.exists() and not a_path.exists():
if b_path.is_dir():
shutil.copytree(b_path, a_path, dirs_exist_ok=True)
else:
a_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(b_path, a_path)
except Exception as e:
self.log_message.emit(f"[ERROR][MIRROR-REC] {rel}: {e}")
self.update_item_status.emit(top_level_name, "error")
# -------------------
# Main window: largely unchanged, but updated to use new worker signals cleanly
# -------------------
class SyncX(QMainWindow):
STATUS_PRIORITY = {"syncing": 0, "error": 1, "needs_sync": 2, "unknown": 3, "synced": 4}
PRIORITY_MAP = {"High": 0, "Normal": 1, "Low": 2}
def update_sync_button_state(self):
if self.fs_watcher.directories():
# Live sync active
self.sync_button.setText("Live Sync Active")
self.sync_button.setStyleSheet("background-color: #27ae60; color: white;") # green highlight
else:
# No live sync
self.sync_button.setText("Start Sync")
self.sync_button.setStyleSheet("") # reset to default
def __init__(self):
super().__init__()
self.setWindowTitle(f"{APP_NAME} v{APP_VERSION}")
self.setGeometry(100, 100, 1000, 700)
self.setStyleSheet(STYLESheet)
self.tree_items: Dict[str, QTreeWidgetItem] = {}
self.STATUS_ICONS = {
"synced": create_status_icon("#2ecc71"),
"needs_sync": create_status_icon("#3498db"),
"syncing": create_status_icon("#f1c40f"),
"error": create_status_icon("#e74c3c"),
"unknown": create_status_icon("#95a5a6"),
}
self.file_icon = QApplication.style().standardIcon(QStyle.SP_FileIcon)
self.folder_icon = QApplication.style().standardIcon(QStyle.SP_DirIcon)
self.fs_watcher = QFileSystemWatcher(self)
self.live_sync_timer = QTimer(self)
self.live_sync_timer.setSingleShot(True)
self.change_while_syncing = False
self.fs_watcher.directoryChanged.connect(self.schedule_live_sync)
self.live_sync_timer.timeout.connect(self.start_sync)
self.init_ui()
# Worker threads
self.sync_thread = QThread(self)
self.sync_worker = SyncWorker()
self.sync_worker.moveToThread(self.sync_thread)
self.sync_worker.log_message.connect(self.log)
self.sync_worker.update_item_status.connect(self.update_tree_item_status)
self.sync_worker.sync_finished.connect(self.on_sync_finished)
self.sync_worker.progress.connect(lambda p: self.log(f"Progress: {p}%"))
self.sync_thread.started.connect(self.sync_worker.run)
self.check_thread = QThread(self)
self.check_worker = None # created dynamically in start_pre_check
self._update_ui_state(is_launch=True)
def init_ui(self):
main_widget = QWidget()
main_layout = QVBoxLayout(main_widget)
dir_layout = QVBoxLayout()
dir_layout.setSpacing(10)
self.source_edit = self.create_dir_selector(dir_layout, "Source")
self.dest_edit = self.create_dir_selector(dir_layout, "Destination")
main_layout.addLayout(dir_layout)
controls_layout = QHBoxLayout()
self.speed_combo = QComboBox()
self.speed_combo.addItems(["Fast (Timestamp)", "Slow (Checksum)"])
controls_layout.addWidget(QLabel("Speed:"))
controls_layout.addWidget(self.speed_combo)
self.mode_combo = QComboBox()
self.mode_combo.addItems(["Source to Destination", "Destination to Source", "Mirroring Both"])
self.mode_combo.currentIndexChanged.connect(lambda: self._update_ui_state())
controls_layout.addWidget(QLabel("Mode:"))
controls_layout.addWidget(self.mode_combo)
self.delete_checkbox = QCheckBox("Delete extra files")
self.delete_checkbox.setChecked(False)
controls_layout.addWidget(self.delete_checkbox)
controls_layout.addStretch()
self.sync_button = QPushButton("Start Sync")
self.sync_button.clicked.connect(self.toggle_sync)
controls_layout.addWidget(self.sync_button)
main_layout.addLayout(controls_layout)
line = QFrame()
line.setFrameShape(QFrame.HLine)
line.setFrameShadow(QFrame.Sunken)
main_layout.addWidget(line)
data_layout = QHBoxLayout()
self.tree_widget = QTreeWidget()
self.tree_widget.setHeaderLabels(["File/Folder", "Priority", "Status"])
self.tree_widget.header().setSectionResizeMode(0, QHeaderView.Stretch)
self.tree_widget.header().setSectionResizeMode(1, QHeaderView.ResizeToContents)
self.tree_widget.header().setSectionResizeMode(2, QHeaderView.ResizeToContents)
self.tree_widget.setSortingEnabled(True)
self.tree_widget.sortByColumn(2, Qt.AscendingOrder)
self.tree_widget.setAlternatingRowColors(True)
self.tree_widget.setContextMenuPolicy(Qt.CustomContextMenu)
self.tree_widget.customContextMenuRequested.connect(self.show_context_menu)
data_layout.addWidget(self.tree_widget)
self.log_edit = QPlainTextEdit()
self.log_edit.setReadOnly(True)
data_layout.addWidget(self.log_edit)
data_layout.setStretchFactor(self.tree_widget, 2)
data_layout.setStretchFactor(self.log_edit, 1)
main_layout.addLayout(data_layout)
self.setCentralWidget(main_widget)
def create_dir_selector(self, p_layout, label):
layout = QHBoxLayout()
qlabel = QLabel(label)
qlabel.setFixedWidth(80)
line_edit = QLineEdit()
line_edit.setPlaceholderText(f"Path to {label} Directory")
line_edit.setClearButtonEnabled(True)
line_edit.textChanged.connect(lambda: self._update_ui_state())
browse_btn = QPushButton(self.folder_icon, "")
browse_btn.setFixedSize(QSize(40, 32))
browse_btn.setIconSize(QSize(20, 20))
browse_btn.clicked.connect(lambda: self.browse_directory(line_edit))
layout.addWidget(qlabel)
layout.addWidget(line_edit)
layout.addWidget(browse_btn)
p_layout.addLayout(layout)
return line_edit
def _update_ui_state(self, is_launch=False):
if is_launch:
self.speed_combo.setEnabled(False)
self.mode_combo.setEnabled(False)
self.delete_checkbox.setEnabled(False)
self.sync_button.setEnabled(False)
return
source_path = self.source_edit.text()
dest_path = self.dest_edit.text()
paths_are_valid = Path(source_path).is_dir() and Path(dest_path).is_dir()
self.speed_combo.setEnabled(paths_are_valid)
self.mode_combo.setEnabled(paths_are_valid)
self.sync_button.setEnabled(paths_are_valid)
is_mirror_mode = "Mirroring Both" in self.mode_combo.currentText()
self.delete_checkbox.setEnabled(paths_are_valid and not is_mirror_mode)
if paths_are_valid and is_mirror_mode:
# in mirror mode, deletion checkbox is enabled only if user explicitly wants dangerous behavior
pass
if paths_are_valid:
self.populate_tree()
else:
self.tree_widget.clear()
def browse_directory(self, line_edit):
d = QFileDialog.getExistingDirectory(self, "Select Directory")
if d:
line_edit.setText(d)
def log(self, message):
self.log_edit.appendPlainText(message)
def populate_tree(self):
# stop any running pre-check
if self.check_thread.isRunning() and self.check_worker is not None:
self.check_worker.stop()
self.check_thread.quit()
self.check_thread.wait()
self.tree_widget.clear()
self.tree_items.clear()
source_dir = self.source_edit.text()
dest_dir = self.dest_edit.text()
mode = self.mode_combo.currentText()
paths_to_scan = []
if mode == "Source to Destination":
if Path(source_dir).is_dir():
paths_to_scan.append(Path(source_dir))
elif mode == "Destination to Source":
if Path(dest_dir).is_dir():
paths_to_scan.append(Path(dest_dir))
elif mode == "Mirroring Both":
if Path(source_dir).is_dir():
paths_to_scan.append(Path(source_dir))
if Path(dest_dir).is_dir() and source_dir != dest_dir:
paths_to_scan.append(Path(dest_dir))
if not paths_to_scan:
return
all_items: Set[str] = set()
path_map: Dict[str, Path] = {}
for p_dir in paths_to_scan:
for p in p_dir.glob("*"):
all_items.add(p.name)
# prefer source mapping if collision; store first seen
if p.name not in path_map:
path_map[p.name] = p
for item_name in sorted(list(all_items)):
p = path_map[item_name]
item = QTreeWidgetItem([item_name, "Normal", "Unknown"])
item.setIcon(0, self.folder_icon if p.is_dir() else self.file_icon)
item.setIcon(2, self.STATUS_ICONS["unknown"])
item.setData(1, Qt.UserRole, self.PRIORITY_MAP["Normal"])
item.setData(2, Qt.UserRole, self.STATUS_PRIORITY["unknown"])
self.tree_widget.addTopLevelItem(item)
self.tree_items[item_name] = item
# Start pre-check only for one-way (or for mirror we can still pre-check, but logic differs)
if Path(source_dir).is_dir() and Path(dest_dir).is_dir() and mode != "Mirroring Both":
self.start_pre_check()
def start_pre_check(self):
source = self.source_edit.text()
dest = self.dest_edit.text()
# If mode is Destination->Source we invert the check (so items needing sync are detected relative to src->dest)
if self.mode_combo.currentText() == "Destination to Source":
source, dest = dest, source
# Create a new check worker each time (clean lifecycle)
self.check_worker = CheckWorker(source, dest, list(self.tree_items.keys()))
self.check_worker.moveToThread(self.check_thread)
self.check_worker.update_item_status.connect(self.update_tree_item_status)
self.check_worker.finished.connect(self.check_thread.quit)
self.check_thread.started.connect(self.check_worker.run)
self.check_thread.start()
def update_tree_item_status(self, path, status):
# Normalize display string
if path in self.tree_items:
item = self.tree_items[path]
icon = self.STATUS_ICONS.get(status)
status_text = status.replace("_", " ").capitalize()
if icon:
item.setText(2, status_text)
item.setIcon(2, icon)
item.setData(2, Qt.UserRole, self.STATUS_PRIORITY.get(status, 99))
def show_context_menu(self, position):
item = self.tree_widget.itemAt(position)
if not item or item.text(2) == "Syncing":
return
menu = QMenu()
for priority_text in self.PRIORITY_MAP.keys():
action = menu.addAction(f"Set Priority: {priority_text}")
action.triggered.connect(lambda checked, p=priority_text, it=item: self.set_item_priority(it, p))
menu.exec(self.tree_widget.viewport().mapToGlobal(position))
def set_item_priority(self, item, priority_text):
item.setText(1, priority_text)
item.setData(1, Qt.UserRole, self.PRIORITY_MAP[priority_text])
self.tree_widget.sortItems(1, Qt.AscendingOrder)
def toggle_sync(self):
if self.sync_button.text() == "Start Sync":
self.start_sync()
else:
self.stop_sync()
def start_sync(self):
if self.sync_thread.isRunning():
self.log("Sync already running")
return
source_dir = self.source_edit.text()
dest_dir = self.dest_edit.text()
mode_text = self.mode_combo.currentText()
# Collect only top-level items needing sync, with priority
items_to_process: List[Tuple[int, str]] = []
for i in range(self.tree_widget.topLevelItemCount()):
item = self.tree_widget.topLevelItem(i)
if item.text(2).lower() == "needs sync":
priority = item.data(1, Qt.UserRole)
filename = item.text(0)
items_to_process.append((priority, filename))
items_to_process.sort()
prioritized_top_level_items = [filename for _, filename in items_to_process]
# If nothing explicitly needs sync and no deletions requested, we still may want to run a full sync
if not prioritized_top_level_items and not self.delete_checkbox.isChecked() and mode_text != "Mirroring Both":
self.log("No files need syncing or deleting.")
return
self.sync_button.setText("Stop Sync")
# Configure worker
if mode_text == "Source to Destination":
self.sync_worker.source_dir = source_dir
self.sync_worker.dest_dir = dest_dir
elif mode_text == "Destination to Source":
self.sync_worker.source_dir = dest_dir
self.sync_worker.dest_dir = source_dir
elif mode_text == "Mirroring Both":
# For mirror, interpret source_dir and dest_dir literally (A <-> B)
self.sync_worker.source_dir = source_dir
self.sync_worker.dest_dir = dest_dir
self.sync_worker.enable_deletions = self.delete_checkbox.isChecked()
self.sync_worker.speed_mode = self.speed_combo.currentText()
self.sync_worker.top_level_items_to_sync = prioritized_top_level_items
self.sync_worker.mode = mode_text
# Start the thread (worker.run will be executed in thread)
self.sync_thread.start()
def stop_sync(self):
current_paths = self.fs_watcher.directories()
if current_paths:
self.fs_watcher.removePaths(current_paths)
self.update_sync_button_state()
if self.sync_thread.isRunning():
self.sync_worker.stop()
self.sync_thread.quit()
self.sync_thread.wait()
self.sync_button.setText("Start Sync")
self.log("Sync process stopped by user.")
self._update_ui_state()
def schedule_live_sync(self):
if self.sync_thread.isRunning():
self.change_while_syncing = True
self.log("Change detected during active sync. Will refresh when complete.")
return
self.log(f"Change detected. Refreshing list and scheduling sync in {DEBOUNCE_DELAY_MS / 1000:.1f}s...")
self._update_ui_state()
self.live_sync_timer.start(DEBOUNCE_DELAY_MS)
self.update_sync_button_state()
def on_sync_finished(self, message):
# Ensure thread lifecycle is cleaned
try:
if self.sync_thread.isRunning():
self.sync_thread.quit()
self.sync_thread.wait()
except Exception:
pass
self.log(message)
if self.change_while_syncing:
self.log("Refreshing file list due to changes during the last sync...")
self._update_ui_state()
self.change_while_syncing = False
# Reconfigure file system watch based on mode and valid paths
source_path = self.source_edit.text()
dest_path = self.dest_edit.text()
mode = self.mode_combo.currentText()
paths_to_watch = []
if mode == "Source to Destination" and Path(source_path).is_dir():
paths_to_watch.append(source_path)
elif mode == "Destination to Source" and Path(dest_path).is_dir():
paths_to_watch.append(dest_path)
elif mode == "Mirroring Both":
if Path(source_path).is_dir():
paths_to_watch.append(source_path)
if Path(dest_path).is_dir():
paths_to_watch.append(dest_path)
current_paths = self.fs_watcher.directories()
if current_paths:
try:
self.fs_watcher.removePaths(current_paths)
except Exception:
pass
if paths_to_watch:
try:
self.fs_watcher.addPaths(list(set(paths_to_watch)))
except Exception as e:
self.log(f"[WARN] Failed to add watch paths: {e}")
self.update_sync_button_state()
def closeEvent(self, event):
# Stop all background work cleanly
self.stop_sync()
if self.check_thread.isRunning() and self.check_worker is not None:
self.check_worker.stop()
self.check_thread.quit()
self.check_thread.wait()
event.accept()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = SyncX()
window.show()
sys.exit(app.exec())