-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafekeep_gui.pyw
More file actions
967 lines (865 loc) · 38.3 KB
/
Copy pathsafekeep_gui.pyw
File metadata and controls
967 lines (865 loc) · 38.3 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
#!/usr/bin/env pythonw
"""SafeKeep GUI - a point-and-click front end for safekeep.py.
Double-click this file (or "Start SafeKeep.bat") to launch. It drives the exact
same engine as the command-line tool, so behaviour is identical. Standard library
only (tkinter) - no pip installs.
"""
from __future__ import annotations
import ctypes
import logging
import os
import queue
import re
import subprocess
import sys
import threading
from pathlib import Path
from types import SimpleNamespace
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, simpledialog
# Make sure we can import the engine sitting next to this file.
SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))
import safekeep as sk # noqa: E402
CONFIG_PATH = sk.DEFAULT_CONFIG
SCRIPT_PATH = Path(__file__).resolve()
def is_admin() -> bool:
if os.name != "nt":
return False
try:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except Exception:
return False
def relaunch_elevated(extra_args=None) -> bool:
"""Relaunch this GUI elevated (triggers a UAC prompt). True if launched."""
params = f'"{SCRIPT_PATH}"'
if extra_args:
params += " " + " ".join(extra_args)
try:
rc = ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, params, None, 1)
return int(rc) > 32
except Exception:
return False
def ensure_shortcut() -> None:
"""Create a SafeKeep.lnk double-click launcher next to the script if absent.
The shortcut isn't shipped in the repo (it's machine-specific), so the app
recreates it on first run for convenience.
"""
lnk = SCRIPT_DIR / "SafeKeep.lnk"
if lnk.exists():
return
pyw = sk._find_pythonw()
ps = (
"$ws = New-Object -ComObject WScript.Shell; "
f"$s = $ws.CreateShortcut('{lnk}'); "
f"$s.TargetPath = '{pyw}'; "
f"$s.Arguments = '\"{SCRIPT_PATH}\"'; "
f"$s.WorkingDirectory = '{SCRIPT_DIR}'; "
f"$s.IconLocation = '{pyw},0'; "
"$s.Description = 'SafeKeep Backup GUI'; "
"$s.Save()"
)
try:
subprocess.run(
["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", ps],
capture_output=True, creationflags=getattr(sk, "_NO_WINDOW", 0), timeout=10,
)
except Exception:
pass
# --------------------------------------------------------------------------- #
# Logging bridge: engine records -> queue -> GUI text widget (main thread)
# --------------------------------------------------------------------------- #
class QueueHandler(logging.Handler):
def __init__(self, q: queue.Queue):
super().__init__()
self.q = q
def emit(self, record):
try:
self.q.put_nowait(self.format(record))
except Exception:
pass
def _human(n: int) -> str:
return sk._human_bytes(n) if isinstance(n, (int, float)) else str(n)
# --------------------------------------------------------------------------- #
# Main application
# --------------------------------------------------------------------------- #
class SafeKeepApp:
def __init__(self, root: tk.Tk):
self.root = root
self.root.title("SafeKeep Backup" + (" (Administrator)" if is_admin() else ""))
self.root.geometry("900x640")
self.root.minsize(720, 520)
self.log_queue: queue.Queue = queue.Queue()
self.running = False
self._prog_started = False
self._on_done = None
self._after = None
self.cfg: sk.Config | None = None
self._config_error: str | None = None
self.action_buttons: list[ttk.Widget] = []
self._restore_dialog_open = False
# engine logging -> file (no console, we're pythonw) + our queue
sk.setup_logging(enable_console=False)
qh = QueueHandler(self.log_queue)
qh.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s", "%H:%M:%S"))
qh.setLevel(logging.INFO) # per-file DEBUG noise stays in the file log only
sk.log.addHandler(qh)
self._load_config()
self._maybe_persist_unc()
self._build_ui()
self._refresh_all()
self._poll_log()
self.root.protocol("WM_DELETE_WINDOW", self._on_close)
# If relaunched elevated to run a backup, kick it off automatically.
if "--backup" in sys.argv:
self.root.after(800, self.do_backup)
# Best-effort: ensure a double-click launcher shortcut exists.
ensure_shortcut()
# ------------------------------------------------------------------ config
def _maybe_persist_unc(self) -> None:
"""Self-heal mapped drive letters (U:\\) to UNC (\\\\server\\share) in config.
Mapped letters belong to a user's non-elevated session, so a backup that
runs elevated (backup mode) can't see U:\\. We resolve and persist UNC
here, on a normal (non-elevated) launch, so the config works everywhere.
"""
if is_admin():
return # mappings aren't visible when elevated - nothing to do
try:
raw = CONFIG_PATH.read_text(encoding="utf-8") if CONFIG_PATH.exists() else ""
except Exception:
raw = ""
if not re.search(r'(?m)^\s*path\s*=\s*"[A-Za-z]:[\\/]', raw):
return # no mapped-letter destination path - nothing to fix
try:
sk.save_config(self.cfg, CONFIG_PATH) # self.cfg already holds UNC from load
sk.log.info("auto-converted mapped-drive destination to UNC in config.toml")
except Exception as exc:
sk.log.warning("could not persist UNC path: %s", exc)
def _load_config(self) -> None:
try:
self.cfg = sk.load_config(CONFIG_PATH)
self._config_error = None
except Exception as exc:
# No config yet (fresh install) or it's invalid: start empty and let
# the user configure via the GUI.
self._config_error = str(exc)
self.cfg = sk.Config(
retention=14,
use_hardlinks=True,
copy_security=False,
daily_time="03:00",
default_exclude=list(sk.DEFAULT_EXCLUDES),
sources=[],
destinations=[],
)
def _save_silent(self) -> bool:
try:
self.cfg.retention = int(self.var_retention.get())
except ValueError:
self.cfg.retention = 14
self.cfg.daily_time = (self.var_time.get() or "03:00").strip()
self.cfg.use_hardlinks = bool(self.var_hardlinks.get())
self.cfg.copy_security = bool(self.var_security.get())
self.cfg.backup_mode = bool(self.var_backup_mode.get())
self.cfg.restartable = bool(self.var_restartable.get())
self.cfg.ignore_access_errors = bool(self.var_ignore_access.get())
try:
sk.save_config(self.cfg, CONFIG_PATH)
self.cfg = sk.load_config(CONFIG_PATH)
self._config_error = None
return True
except Exception as exc:
self._config_error = str(exc)
return False
# -------------------------------------------------------------------- UI
def _build_ui(self) -> None:
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(fill="both", expand=True, padx=8, pady=8)
self.var_retention = tk.StringVar(value=str(self.cfg.retention))
self.var_time = tk.StringVar(value=self.cfg.daily_time)
self.var_hardlinks = tk.BooleanVar(value=self.cfg.use_hardlinks)
self.var_security = tk.BooleanVar(value=self.cfg.copy_security)
self.var_backup_mode = tk.BooleanVar(value=self.cfg.backup_mode)
self.var_restartable = tk.BooleanVar(value=self.cfg.restartable)
self.var_ignore_access = tk.BooleanVar(value=self.cfg.ignore_access_errors)
self.var_dry = tk.BooleanVar(value=False)
self.status_var = tk.StringVar(value="Ready")
self._build_backup_tab()
self._build_folders_tab()
self._build_snapshots_tab()
self._build_schedule_tab()
bar = ttk.Frame(self.root, relief="sunken")
bar.pack(fill="x", side="bottom")
ttk.Label(bar, textvariable=self.status_var, anchor="w").pack(side="left", padx=8, pady=3)
def _build_backup_tab(self) -> None:
tab = ttk.Frame(self.notebook)
self.notebook.add(tab, text="Backup")
top = ttk.Frame(tab)
top.pack(fill="x", padx=8, pady=8)
self.btn_run = ttk.Button(top, text="▶ Back up now", command=self.do_backup)
self.btn_run.pack(side="left")
ttk.Checkbutton(top, text="Dry run (copy nothing)", variable=self.var_dry).pack(side="left", padx=12)
ttk.Button(top, text="Open log folder", command=self._open_logs).pack(side="right")
pf = ttk.Frame(tab)
pf.pack(fill="x", padx=8)
self.prog_var = tk.StringVar(value="")
ttk.Label(pf, textvariable=self.prog_var, anchor="w",
font=("TkDefaultFont", 9)).pack(fill="x")
self.progress = ttk.Progressbar(pf, mode="determinate", maximum=100)
self.progress.pack(fill="x", pady=(2, 6))
ttk.Label(tab, text="Activity log:").pack(anchor="w", padx=8)
self.log_text = tk.Text(
tab, wrap="none", state="disabled", background="#1e1e1e", foreground="#d4d4d4",
insertbackground="#d4d4d4", font=("Consolas", 9),
)
self.log_text.pack(fill="both", expand=True, padx=8, pady=(0, 8))
self.log_text.tag_config("warn", foreground="#f1c40f")
self.log_text.tag_config("err", foreground="#e74c3c")
self.log_text.tag_config("ok", foreground="#2ecc71")
def _build_folders_tab(self) -> None:
tab = ttk.Frame(self.notebook)
self.notebook.add(tab, text="Folders & Settings")
if self._config_error:
ttk.Label(
tab,
text=f"Note: couldn't read the existing config ({self._config_error}). "
"Starting with defaults - add your folders below and click Save.",
foreground="#b8860b", wraplength=820, justify="left",
).pack(anchor="w", padx=8, pady=8)
split = ttk.Frame(tab)
split.pack(fill="both", expand=True, padx=8)
split.columnconfigure(0, weight=1)
split.columnconfigure(1, weight=1)
# --- sources (left) ---
slf = ttk.LabelFrame(split, text="Sources (folders to back up)")
slf.grid(row=0, column=0, sticky="nsew", padx=(0, 4))
self.src_tree = ttk.Treeview(slf, columns=("label", "path"), show="headings", height=10)
self.src_tree.heading("label", text="Label")
self.src_tree.heading("path", text="Folder")
self.src_tree.column("label", width=120, anchor="w")
self.src_tree.column("path", width=320, anchor="w")
self.src_tree.pack(fill="both", expand=True, padx=6, pady=6)
self.src_tree.bind("<Double-1>", lambda e: self._edit_source())
sb = ttk.Frame(slf); sb.pack(fill="x", padx=6, pady=(0, 6))
ttk.Button(sb, text="Add…", command=self.add_source).pack(side="left")
ttk.Button(sb, text="Edit…", command=self._edit_source).pack(side="left", padx=4)
ttk.Button(sb, text="Remove", command=self.remove_source).pack(side="left")
# --- destinations (right) ---
dlf = ttk.LabelFrame(split, text="Destinations (where snapshots are stored)")
dlf.grid(row=0, column=1, sticky="nsew", padx=(4, 0))
self.dest_tree = ttk.Treeview(
dlf, columns=("name", "type", "path", "ret"), show="headings", height=10
)
self.dest_tree.heading("name", text="Name")
self.dest_tree.heading("type", text="Type")
self.dest_tree.heading("path", text="Folder / remote")
self.dest_tree.heading("ret", text="Keep")
self.dest_tree.column("name", width=110, anchor="w")
self.dest_tree.column("type", width=60, anchor="w")
self.dest_tree.column("path", width=240, anchor="w")
self.dest_tree.column("ret", width=50, anchor="e")
self.dest_tree.pack(fill="both", expand=True, padx=6, pady=6)
self.dest_tree.bind("<Double-1>", lambda e: self._edit_dest())
db = ttk.Frame(dlf); db.pack(fill="x", padx=6, pady=(0, 6))
ttk.Button(db, text="Add…", command=self.add_dest).pack(side="left")
ttk.Button(db, text="Edit…", command=self._edit_dest).pack(side="left", padx=4)
ttk.Button(db, text="Remove", command=self.remove_dest).pack(side="left")
# --- options ---
of = ttk.LabelFrame(tab, text="Settings")
of.pack(fill="x", padx=8, pady=8)
ttk.Label(of, text="Keep last").grid(row=0, column=0, sticky="w", padx=6, pady=6)
ttk.Spinbox(of, from_=1, to=365, width=5, textvariable=self.var_retention).grid(
row=0, column=1, sticky="w", padx=4
)
ttk.Label(of, text="snapshots per destination").grid(row=0, column=2, sticky="w")
ttk.Label(of, text="Daily run time (HH:MM):").grid(row=0, column=3, sticky="w", padx=(20, 4))
ttk.Entry(of, textvariable=self.var_time, width=6).grid(row=0, column=4, sticky="w")
ttk.Checkbutton(of, text="Hardlink dedup (saves space)", variable=self.var_hardlinks).grid(
row=1, column=0, columnspan=2, sticky="w", padx=6, pady=4
)
ttk.Checkbutton(of, text="Copy security/ACLs (NTFS only)", variable=self.var_security).grid(
row=1, column=2, columnspan=3, sticky="w", padx=6
)
ttk.Checkbutton(
of, text="Backup mode — read all files (needs admin)",
variable=self.var_backup_mode,
).grid(row=2, column=0, columnspan=3, sticky="w", padx=6, pady=4)
ttk.Checkbutton(
of, text="Skip files I can't read instead of failing",
variable=self.var_ignore_access,
).grid(row=2, column=3, columnspan=2, sticky="w", padx=6)
ttk.Checkbutton(
of, text="Restartable copy — resilient on flaky networks (slower)",
variable=self.var_restartable,
).grid(row=3, column=0, columnspan=5, sticky="w", padx=6, pady=4)
sf = ttk.Frame(tab)
sf.pack(fill="x", padx=8, pady=(0, 8))
self.save_btn = ttk.Button(sf, text="💾 Save configuration", command=self.save_config)
self.save_btn.pack(side="left")
self.folder_status = tk.StringVar(value="")
ttk.Label(sf, textvariable=self.folder_status, foreground="#555").pack(side="left", padx=10)
def _build_snapshots_tab(self) -> None:
tab = ttk.Frame(self.notebook)
self.notebook.add(tab, text="Snapshots")
top = ttk.Frame(tab)
top.pack(fill="x", padx=8, pady=8)
ttk.Label(top, text="Destination:").pack(side="left")
self.snap_dest_var = tk.StringVar()
self.snap_dest = ttk.Combobox(top, textvariable=self.snap_dest_var, state="readonly", width=24)
self.snap_dest.pack(side="left", padx=6)
self.snap_dest.bind("<<ComboboxSelected>>", lambda e: self.refresh_snapshots())
ttk.Button(top, text="Refresh", command=self.refresh_snapshots).pack(side="left", padx=4)
ttk.Button(top, text="Verify latest", command=self.do_verify).pack(side="left", padx=4)
ttk.Button(top, text="Restore…", command=self.do_restore).pack(side="left", padx=4)
ttk.Button(top, text="Prune to retention", command=self.do_prune).pack(side="left", padx=4)
cols = ("stamp", "files", "size")
self.snap_tree = ttk.Treeview(tab, columns=cols, show="headings", height=14)
self.snap_tree.heading("stamp", text="Snapshot")
self.snap_tree.heading("files", text="Files")
self.snap_tree.heading("size", text="Size")
self.snap_tree.column("stamp", width=220, anchor="w")
self.snap_tree.column("files", width=100, anchor="e")
self.snap_tree.column("size", width=120, anchor="e")
self.snap_tree.pack(fill="both", expand=True, padx=8, pady=(0, 8))
def _build_schedule_tab(self) -> None:
tab = ttk.Frame(self.notebook)
self.notebook.add(tab, text="Schedule")
f = ttk.LabelFrame(tab, text="Daily automatic backup (Windows Task Scheduler)")
f.pack(fill="x", padx=8, pady=8)
self.sched_status = tk.StringVar(value="Checking…")
ttk.Label(f, textvariable=self.sched_status, wraplength=760, justify="left").pack(
anchor="w", padx=10, pady=10
)
b = ttk.Frame(f); b.pack(fill="x", padx=10, pady=(0, 10))
ttk.Button(b, text="Install daily task", command=self.do_install).pack(side="left")
ttk.Button(b, text="Uninstall", command=self.do_uninstall).pack(side="left", padx=6)
ttk.Button(b, text="Refresh status", command=self.refresh_schedule).pack(side="left", padx=6)
info = ttk.LabelFrame(tab, text="How it works")
info.pack(fill="both", expand=True, padx=8, pady=8)
ttk.Label(
info,
text=(
"When installed, Windows runs SafeKeep every day at the configured time\n"
"(set under “Folders & Settings”). The task:\n"
" • catches up after a missed run (PC was off / asleep)\n"
" • can wake a sleeping machine\n"
" • never starts a second copy while one is running\n\n"
"You can still launch a backup any time from the “Backup” tab."
),
justify="left",
).pack(anchor="w", padx=10, pady=10)
self.root.after(300, self.refresh_schedule)
# ------------------------------------------------------------- refreshes
def _refresh_all(self) -> None:
self.var_retention.set(str(self.cfg.retention))
self.var_time.set(self.cfg.daily_time)
self.var_hardlinks.set(self.cfg.use_hardlinks)
self.var_security.set(self.cfg.copy_security)
self.var_backup_mode.set(self.cfg.backup_mode)
self.var_restartable.set(self.cfg.restartable)
self.var_ignore_access.set(self.cfg.ignore_access_errors)
self._refresh_sources()
self._refresh_dests()
self._refresh_snap_dest_combo()
self.refresh_snapshots()
def _refresh_sources(self) -> None:
self.src_tree.delete(*self.src_tree.get_children())
for s in self.cfg.sources:
self.src_tree.insert("", "end", iid=s.label, values=(s.label, str(s.path)))
def _refresh_dests(self) -> None:
self.dest_tree.delete(*self.dest_tree.get_children())
for d in self.cfg.destinations:
loc = str(d.path or d.remote or "")
ret = d.retention if d.retention is not None else self.cfg.retention
self.dest_tree.insert("", "end", iid=d.name, values=(d.name, d.type, loc, ret))
def _refresh_snap_dest_combo(self) -> None:
names = [d.name for d in self.cfg.destinations]
self.snap_dest["values"] = names
if names and (not self.snap_dest_var.get() or self.snap_dest_var.get() not in names):
self.snap_dest_var.set(names[0])
def refresh_snapshots(self) -> None:
self.snap_tree.delete(*self.snap_tree.get_children())
name = self.snap_dest_var.get()
if not name:
return
spec = next((d for d in self.cfg.destinations if d.name == name), None)
if not spec:
return
try:
dest = sk.make_destination(spec, self.cfg)
snaps = dest.list_snapshots()
except Exception as exc:
self._status(f"Could not list snapshots: {exc}")
return
for stamp in snaps:
files, size = 0, 0
mpath = getattr(dest, "manifest_path", None)
mpath = mpath(stamp) if callable(mpath) else None
if mpath and Path(mpath).exists():
try:
m = json_load(mpath)
for src in m.get("sources", []):
files += src.get("files", 0)
size += src.get("bytes", 0)
except Exception:
pass
self.snap_tree.insert("", "end", values=(stamp, files, _human(size)))
if not snaps:
self._status("No snapshots yet at '%s'." % name)
def refresh_schedule(self) -> None:
try:
exists = sk.task_exists()
except Exception as exc:
self.sched_status.set(f"Could not query Task Scheduler: {exc}")
return
when = self.cfg.daily_time
if exists:
self.sched_status.set(
f"● Installed. SafeKeep runs daily at {when} (task “{sk.TASK_NAME}”)."
)
else:
self.sched_status.set(
f"○ Not installed. Click “Install daily task” to run SafeKeep "
f"automatically every day at {when}."
)
# ------------------------------------------------------- source editing
def add_source(self) -> None:
if self._busy():
return
d = filedialog.askdirectory(
title="Select a source folder to back up", initialdir=self._pick_initialdir()
)
if not d:
return
label = simpledialog.askstring(
"Source label", "Label (folder name used inside each snapshot):",
initialvalue=Path(d).name, parent=self.root,
)
if not label:
return
if any(s.label == label for s in self.cfg.sources):
messagebox.showwarning("Duplicate", f"A source labelled '{label}' already exists.", parent=self.root)
return
self.cfg.sources.append(
sk.SourceSpec(path=Path(d), label=label, exclude=list(self.cfg.default_exclude))
)
self._refresh_sources()
self._dirty("Source added (remember to Save).")
def _edit_source(self) -> None:
if self._busy():
return
sel = self.src_tree.focus()
if not sel:
return
spec = next((s for s in self.cfg.sources if s.label == sel), None)
if not spec:
return
label = simpledialog.askstring(
"Source label", "Label:", initialvalue=spec.label, parent=self.root
)
if not label:
return
spec.label = label
self._refresh_sources()
self._dirty("Edited (remember to Save).")
def remove_source(self) -> None:
if self._busy():
return
sel = self.src_tree.focus()
if not sel:
return
if not messagebox.askyesno("Remove", f"Remove source '{sel}'?", parent=self.root):
return
self.cfg.sources = [s for s in self.cfg.sources if s.label != sel]
self._refresh_sources()
self._dirty("Source removed (remember to Save).")
# -------------------------------------------------- destination editing
def add_dest(self) -> None:
if self._busy():
return
d = filedialog.askdirectory(
title="Select a destination folder (where snapshots are stored)", initialdir="U:/"
)
if not d:
return
name = simpledialog.askstring(
"Destination name", "Name:", initialvalue=Path(d).name, parent=self.root
) or Path(d).name
if any(dd.name == name for dd in self.cfg.destinations):
messagebox.showwarning("Duplicate", f"Destination '{name}' already exists.", parent=self.root)
return
self.cfg.destinations.append(sk.DestinationSpec(name=name, type="local", path=Path(d)))
self._refresh_dests()
self._refresh_snap_dest_combo()
self._dirty("Destination added (remember to Save).")
def _edit_dest(self) -> None:
if self._busy():
return
sel = self.dest_tree.focus()
if not sel:
return
spec = next((d for d in self.cfg.destinations if d.name == sel), None)
if not spec:
return
name = simpledialog.askstring("Name", "Name:", initialvalue=spec.name, parent=self.root)
if name:
spec.name = name
ans = simpledialog.askinteger(
"Retention", "Snapshots to keep (blank/0 = use global setting):",
initialvalue=spec.retention, parent=self.root,
)
spec.retention = ans if ans else None
self._refresh_dests()
self._refresh_snap_dest_combo()
self._dirty("Edited (remember to Save).")
def remove_dest(self) -> None:
if self._busy():
return
sel = self.dest_tree.focus()
if not sel:
return
if not messagebox.askyesno("Remove", f"Remove destination '{sel}'?\n(existing snapshots on disk are kept.)", parent=self.root):
return
self.cfg.destinations = [d for d in self.cfg.destinations if d.name != sel]
self._refresh_dests()
self._refresh_snap_dest_combo()
self._dirty("Destination removed (remember to Save).")
# ------------------------------------------------------------- actions
def save_config(self) -> None:
if self._save_silent():
self._refresh_all()
self.folder_status.set("Saved.")
self._status("Configuration saved.")
else:
messagebox.showerror(
"Save failed", self._config_error or "Unknown error", parent=self.root
)
def do_backup(self) -> None:
if self.running:
return
if not self.cfg.sources:
messagebox.showinfo(
"No sources",
"Add at least one source folder under “Folders & Settings” first.",
parent=self.root,
)
self.notebook.select(1)
return
if not self._save_silent():
if not messagebox.askyesno(
"Config not saved", f"Save failed: {self._config_error}\nRun anyway?", parent=self.root
):
return
self._refresh_all()
# Backup mode needs elevated rights; prompt to relaunch as admin.
effective = self.cfg
if self.cfg.backup_mode and not is_admin():
import copy
choice = self._prompt_elevate()
if choice == "cancel":
return
if choice == "elevate":
return # elevated instance (auto-starts the backup) takes over
# "noadmin": run this once without backup mode
effective = copy.copy(self.cfg)
effective.backup_mode = False
sk.log.info("backup mode disabled for this run (not elevated)")
dry = bool(self.var_dry.get())
self._start_op(
lambda: sk.run_backup(effective, dry, progress=self._progress),
label=("Dry run" if dry else "Backup") + " running…",
done=(None if dry else "Backup finished."),
)
def _prompt_elevate(self) -> str:
"""Ask the user how to handle backup-mode-without-admin. Returns cancel|elevate|noadmin."""
ans = messagebox.askyesnocancel(
"Administrator rights needed",
"Backup mode is ON, but SafeKeep isn’t running as administrator.\n\n"
" Yes — relaunch as administrator now (you’ll get a UAC prompt,\n"
" then the backup starts automatically)\n"
" No — run this backup WITHOUT backup mode (may skip files you\n"
" can’t read)\n"
" Cancel — do nothing",
parent=self.root,
)
if ans is None:
return "cancel"
if ans:
if relaunch_elevated(["--backup"]):
self.root.after(500, self.root.destroy)
return "elevate"
return "cancel" if not messagebox.askyesno(
"Elevation failed",
"Could not start SafeKeep as administrator.\nRun without backup mode instead?",
parent=self.root,
) else "noadmin"
return "noadmin"
def do_verify(self) -> None:
name = self.snap_dest_var.get()
if not name:
return
self.notebook.select(0)
self._start_op(
lambda: sk.cmd_verify(
self.cfg, SimpleNamespace(dest=name, snapshot=None, hash=False)
),
label=f"Verifying '{name}'…",
done="Verify complete (see log).",
)
def do_prune(self) -> None:
name = self.snap_dest_var.get()
if not name:
return
if not messagebox.askyesno(
"Prune", f"Delete snapshots beyond retention at '{name}'?", parent=self.root
):
return
self._start_op(
lambda: sk.cmd_prune(self.cfg, SimpleNamespace(dest=name, keep=None)),
label=f"Pruning '{name}'…",
done="Prune complete.",
after=self.refresh_snapshots,
)
def do_restore(self) -> None:
if self._restore_dialog_open:
return
name = self.snap_dest_var.get()
spec = next((d for d in self.cfg.destinations if d.name == name), None)
if not spec:
return
try:
snaps = sk.make_destination(spec, self.cfg).list_snapshots()
except Exception as exc:
messagebox.showerror("Error", str(exc), parent=self.root)
return
if not snaps:
messagebox.showinfo("Restore", "No snapshots to restore from.", parent=self.root)
return
labels = [s.label for s in self.cfg.sources] or ["(no sources)"]
self._restore_dialog_open = True
win = tk.Toplevel(self.root)
win.title("Restore")
win.transient(self.root)
win.grab_set()
win.protocol("WM_DELETE_WINDOW", lambda: self._close_restore(win))
ttk.Label(win, text="Restore a snapshot back to a folder.").pack(anchor="w", padx=10, pady=(10, 4))
form = ttk.Frame(win); form.pack(padx=10, pady=6)
ttk.Label(form, text="Snapshot:").grid(row=0, column=0, sticky="w", pady=4)
snap_var = tk.StringVar(value=snaps[-1])
ttk.Combobox(form, textvariable=snap_var, values=snaps, state="readonly", width=26).grid(
row=0, column=1, sticky="w", padx=6
)
ttk.Label(form, text="Source:").grid(row=1, column=0, sticky="w", pady=4)
src_var = tk.StringVar(value=labels[0])
ttk.Combobox(form, textvariable=src_var, values=labels, state="readonly", width=26).grid(
row=1, column=1, sticky="w", padx=6
)
ttk.Label(form, text="Restore into:").grid(row=2, column=0, sticky="w", pady=4)
to_var = tk.StringVar()
row3 = ttk.Frame(form); row3.grid(row=2, column=1, sticky="w", padx=6)
ttk.Entry(row3, textvariable=to_var, width=28).pack(side="left")
def browse():
d = filedialog.askdirectory(title="Choose restore target", parent=win)
if d:
to_var.set(d)
ttk.Button(row3, text="…", width=3, command=browse).pack(side="left", padx=4)
def go():
snap = snap_var.get(); src = src_var.get(); to = to_var.get().strip()
if not to:
messagebox.showwarning("Restore", "Choose a target folder.", parent=win)
return
self._close_restore(win)
self.notebook.select(0)
self._start_op(
lambda: sk.cmd_restore(
self.cfg,
SimpleNamespace(dest=name, snapshot=snap, source=src, to=to, yes=True),
),
label="Restoring…",
done="Restore complete (see log).",
)
bf = ttk.Frame(win); bf.pack(pady=10)
ttk.Button(bf, text="Restore", command=go).pack(side="left", padx=6)
ttk.Button(bf, text="Cancel", command=lambda: self._close_restore(win)).pack(side="left")
def _close_restore(self, win):
self._restore_dialog_open = False
win.destroy()
def do_install(self) -> None:
if not self._save_silent():
messagebox.showerror("Save failed", self._config_error or "error", parent=self.root)
return
self._refresh_all()
self._start_op(
lambda: sk.cmd_install(self.cfg, SimpleNamespace(config=None)),
label="Installing scheduled task…",
done="Task installed.",
after=self.refresh_schedule,
)
def do_uninstall(self) -> None:
self._start_op(
lambda: sk.cmd_uninstall(self.cfg, SimpleNamespace()),
label="Removing scheduled task…",
done="Task removed.",
after=self.refresh_schedule,
)
# --------------------------------------------------------- op machinery
def _start_op(self, target, label: str, done: str | None = None, after=None) -> None:
if self.running:
return
self.running = True
self._after = after
for b in self.action_buttons + [
self.btn_run, getattr(self, "save_btn", None),
]:
if b is not None:
try:
b.state(["disabled"])
except tk.TclError:
pass
self.status_var.set(label)
self.prog_var.set(label)
try:
self.progress.config(mode="indeterminate")
self.progress.start(15)
self._prog_started = True
except tk.TclError:
pass
sk.log.info(label)
def worker():
try:
target()
except Exception:
sk.log.exception("operation failed")
finally:
self.log_queue.put(None) # sentinel
threading.Thread(target=worker, daemon=True).start()
def _op_done(self) -> None:
self.running = False
for b in self.action_buttons + [self.btn_run, getattr(self, "save_btn", None)]:
if b is not None:
try:
b.state(["!disabled"])
except tk.TclError:
pass
if self._after:
try:
self._after()
except Exception:
sk.log.exception("post-op callback failed")
try:
self.progress.stop()
self.progress.config(mode="determinate", value=0)
except tk.TclError:
pass
self._prog_started = False
self.prog_var.set("")
self._status("Ready")
def _poll_log(self) -> None:
try:
while True:
item = self.log_queue.get_nowait()
if item is None:
self._op_done()
elif isinstance(item, tuple) and item and item[0] == "prog":
self._apply_progress(item[2], item[3])
else:
self._append_log(item)
except queue.Empty:
pass
self.root.after(120, self._poll_log)
def _progress(self, stage, frac, msg) -> None:
"""Engine progress callback (runs on the worker thread) -> main via queue."""
self.log_queue.put(("prog", stage, frac, msg))
def _apply_progress(self, frac, msg) -> None:
short = msg if len(msg) <= 96 else msg[:93] + "…"
try:
self.prog_var.set(short)
except tk.TclError:
pass
self.status_var.set(short)
try:
if frac is None:
if str(self.progress.cget("mode")) != "indeterminate":
self.progress.config(mode="indeterminate")
if not self._prog_started:
self.progress.start(15)
self._prog_started = True
else:
if self._prog_started:
self.progress.stop()
self._prog_started = False
self.progress.config(mode="determinate")
self.progress.config(value=max(0.0, min(1.0, float(frac))) * 100)
except tk.TclError:
pass
def _append_log(self, line: str) -> None:
low = line.lower()
tag = "err" if "[error]" in low else ("warn" if "[warning]" in low or "[warn]" in low else None)
self.log_text.config(state="normal")
self.log_text.insert("end", line + "\n", (tag,) if tag else ())
self.log_text.see("end")
self.log_text.config(state="disabled")
# ------------------------------------------------------------- helpers
def _status(self, msg: str) -> None:
self.status_var.set(msg)
def _busy(self) -> bool:
if self.running:
messagebox.showinfo(
"Busy", "Please wait for the current operation to finish.", parent=self.root
)
return True
return False
def _dirty(self, msg: str) -> None:
self.folder_status.set(msg)
def _pick_initialdir(self) -> str:
if self.cfg.sources:
p = self.cfg.sources[-1].path
return str(p.parent if p.parent.exists() else p)
return str(Path.home())
def _open_logs(self) -> None:
try:
os.startfile(str(sk.LOG_DIR)) # type: ignore[attr-defined]
except Exception as exc:
messagebox.showinfo("Logs", f"Log folder: {sk.LOG_DIR}\n({exc})", parent=self.root)
def _on_close(self) -> None:
if self.running:
if not messagebox.askyesno(
"Quit?", "A backup is still running. Quit anyway?", parent=self.root
):
return
self.root.destroy()
def json_load(path) -> dict:
import json
return json.loads(Path(path).read_text(encoding="utf-8"))
def _report_crash() -> None:
"""Write the current exception to logs/gui_error.log (pythonw has no console)."""
import traceback as _tb
try:
logdir = SCRIPT_DIR / "logs"
logdir.mkdir(parents=True, exist_ok=True)
(logdir / "gui_error.log").write_text(_tb.format_exc(), encoding="utf-8")
except Exception:
pass
def main() -> int:
try:
root = tk.Tk()
SafeKeepApp(root)
root.mainloop()
except Exception:
_report_crash()
try:
from tkinter import messagebox
messagebox.showerror(
"SafeKeep failed to start",
"SafeKeep hit an error while starting.\n\n"
"Details were written to logs\\gui_error.log.\n\n"
"Tip: this can happen if the 'py' launcher is misconfigured. "
"Run 'Start SafeKeep.bat' instead, which calls Python directly.",
)
except Exception:
pass
return 1
return 0
if __name__ == "__main__":
sys.exit(main())