-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwinscp_widget.py
More file actions
2179 lines (1863 loc) · 82.7 KB
/
Copy pathwinscp_widget.py
File metadata and controls
2179 lines (1863 loc) · 82.7 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
"""
winscp_widget.py — Browser SFTP dual-pane stile WinSCP per PCM (GTK3)
Layout:
┌────────────────────────────────────────────────────────────┐
│ Toolbar: Upload ▲ Download ▼ Sincronizza Elimina │
├───────────────────────┬────────────────────────────────────┤
│ LOCALE │ REMOTO │
│ path bar + nav │ path bar + nav │
│ [TreeView file] │ [TreeView file] │
├───────────────────────┴────────────────────────────────────┤
│ Coda trasferimenti (Op | Src | Dst | % | Velocità) │
└────────────────────────────────────────────────────────────┘
Thread GTK-safe: tutti gli aggiornamenti UI via GLib.idle_add().
"""
import os
import stat
import shutil
import threading
import time
from pathlib import Path
from datetime import datetime
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, GLib, GdkPixbuf, Pango, GObject
try:
import paramiko
PARAMIKO_OK = True
except ImportError:
PARAMIKO_OK = False
from translations import t
# ---------------------------------------------------------------------------
# Utility
# ---------------------------------------------------------------------------
def _fmt_size(n) -> str:
if n is None:
return ""
n = int(n)
if n < 1024: return f"{n} B"
if n < 1024**2: return f"{n/1024:.1f} KB"
if n < 1024**3: return f"{n/1024**2:.1f} MB"
return f"{n/1024**3:.2f} GB"
def _fmt_attr(mode: int) -> str:
chars = ""
for r, w, x in [(0o400,0o200,0o100),(0o040,0o020,0o010),(0o004,0o002,0o001)]:
chars += "r" if mode & r else "-"
chars += "w" if mode & w else "-"
chars += "x" if mode & x else "-"
return chars
# ---------------------------------------------------------------------------
# TransferJob — un singolo elemento di coda
# ---------------------------------------------------------------------------
CHUNK_SIZE = 32768 # 32 KB per chunk — permette controllo pausa/annulla
class TransferJob:
def __init__(self, op, src, dst, size=0, nome=""):
self.op = op # 'upload' | 'download'
self.src = src
self.dst = dst
self.size = size
self.nome = nome or os.path.basename(src)
self.trasferito = 0
self.stato = t("winscp.status_wait")
self.errore = ""
self.velocita = 0
self.t_inizio = 0.0
self.annulla = False # flag: interrompi trasferimento in corso
# ---------------------------------------------------------------------------
# Pannello file (base) — Gtk.TreeView
# ---------------------------------------------------------------------------
# Colonne store: nome_display, nome_raw, ext, size_str, mtime, attr, is_dir, path, size_int
C_NOME_D, C_NOME, C_EXT, C_SIZE, C_MTIME, C_ATTR, C_ISDIR, C_PATH, C_SIZE_INT = range(9)
class FilePanel(Gtk.Box):
"""
Singolo pannello file (locale o remoto).
Emette segnali GObject per navigazione.
"""
def __init__(self, titolo: str):
super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=0)
self.titolo = titolo
self.path = ""
self._init_ui()
def _init_ui(self):
# Header
hdr = Gtk.Label(label=f" {self.titolo}")
hdr.set_xalign(0.0)
hdr.get_style_context().add_class("section-header")
self.pack_start(hdr, False, False, 0)
# Barra navigazione
nav = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=2)
nav.set_margin_start(4)
nav.set_margin_end(4)
nav.set_margin_top(2)
nav.set_margin_bottom(2)
self.btn_su = Gtk.Button(label="⬆")
self.btn_home = Gtk.Button(label="🏠")
self.btn_ref = Gtk.Button(label="↺")
for btn, tip in [(self.btn_su, t("winscp.tooltip_up")), (self.btn_home, t("winscp.tooltip_home")), (self.btn_ref, t("winscp.tooltip_refresh"))]:
btn.set_relief(Gtk.ReliefStyle.NONE)
btn.set_tooltip_text(tip)
nav.pack_start(btn, False, False, 0)
self.path_entry = Gtk.Entry()
self.path_entry.set_hexpand(True)
self.path_entry.connect("activate", lambda e: self.naviga(e.get_text().strip()))
nav.pack_start(self.path_entry, True, True, 0)
self.pack_start(nav, False, False, 0)
sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
self.pack_start(sep, False, False, 0)
# TreeView
# Store: nome_display, nome_raw, ext, size, mtime, attr, is_dir, path, size_int
self._store = Gtk.ListStore(str, str, str, str, str, str, bool, str, GObject.TYPE_INT64)
self._sorted = Gtk.TreeModelSort(model=self._store)
self._view = Gtk.TreeView(model=self._sorted)
self._view.set_headers_visible(True)
self._view.set_headers_clickable(True)
self._view.get_selection().set_mode(Gtk.SelectionMode.MULTIPLE)
col_defs = [
(t("winscp.col_name"), C_NOME_D, True),
(t("winscp.col_ext"), C_EXT, False),
(t("winscp.col_size"), C_SIZE, False),
(t("winscp.col_modified"), C_MTIME, False),
(t("winscp.col_attrs"), C_ATTR, False),
]
sort_cols = [C_NOME, C_EXT, C_SIZE_INT, C_MTIME, C_ATTR]
for i, (h, data_col, expand) in enumerate(col_defs):
cell = Gtk.CellRendererText()
cell.set_property("ellipsize", Pango.EllipsizeMode.END)
col = Gtk.TreeViewColumn(h, cell, text=data_col)
col.set_resizable(True)
col.set_expand(expand)
col.set_sort_column_id(sort_cols[i])
self._view.append_column(col)
self._view.connect("row-activated", self._on_row_activated)
self._view.connect("button-press-event", self._on_button_press)
scroll = Gtk.ScrolledWindow()
scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
scroll.set_vexpand(True)
scroll.add(self._view)
self.pack_start(scroll, True, True, 0)
# Status
self._status = Gtk.Label(label="")
self._status.set_xalign(0.0)
self._status.set_margin_start(6)
self.pack_start(self._status, False, False, 0)
# Connetti bottoni nav
self.btn_su.connect("clicked", lambda b: self._vai_su())
self.btn_home.connect("clicked", lambda b: self._vai_home())
self.btn_ref.connect("clicked", lambda b: self.aggiorna())
# ------------------------------------------------------------------
# Navigazione (da implementare nelle sottoclassi)
# ------------------------------------------------------------------
def naviga(self, path: str):
raise NotImplementedError
def aggiorna(self):
self.naviga(self.path)
def _vai_su(self):
parent = str(Path(self.path).parent)
if parent != self.path:
self.naviga(parent)
def _vai_home(self):
self.naviga(os.path.expanduser("~"))
# ------------------------------------------------------------------
# Popolamento
# ------------------------------------------------------------------
def _popola(self, voci: list):
"""voci: lista di dict {nome, is_dir, path, size, mtime, attr}"""
self._store.clear()
for v in voci:
nome = v["nome"]
is_dir = v.get("is_dir", False)
icona = "📁 " if is_dir else "📄 "
ext = "" if is_dir else (Path(nome).suffix.lstrip(".") or "")
size_s = "" if is_dir else _fmt_size(v.get("size", 0))
self._store.append([
icona + nome,
nome,
ext,
size_s,
v.get("mtime", ""),
v.get("attr", ""),
is_dir,
v.get("path", ""),
v.get("size", 0) or 0,
])
self._status.set_text(f" {len(voci)} elementi | {self.path}")
# ------------------------------------------------------------------
# Selezione
# ------------------------------------------------------------------
def selezione(self) -> list:
"""Lista di dict per le righe selezionate."""
sel = self._view.get_selection()
model, paths = sel.get_selected_rows()
result = []
for p in paths:
it = model.get_iter(p)
result.append({
"nome": model.get_value(it, C_NOME),
"is_dir": model.get_value(it, C_ISDIR),
"path": model.get_value(it, C_PATH),
"size": model.get_value(it, C_SIZE_INT),
})
return result
# ------------------------------------------------------------------
# Interazioni
# ------------------------------------------------------------------
def _on_row_activated(self, view, path, column):
it = self._sorted.get_iter(path)
if it is None:
return
nome = self._sorted.get_value(it, C_NOME)
is_dir = self._sorted.get_value(it, C_ISDIR)
fpath = self._sorted.get_value(it, C_PATH)
if nome == "..":
self._vai_su()
elif is_dir:
self.naviga(fpath)
def _on_button_press(self, view, event):
if event.button != 3:
return False
info = view.get_path_at_pos(int(event.x), int(event.y))
if info:
path, col, _, _ = info
sel = view.get_selection()
if not sel.path_is_selected(path):
sel.unselect_all()
sel.select_path(path)
self._menu_contestuale(event)
return True
def _menu_contestuale(self, event):
pass # override nelle sottoclassi
# ------------------------------------------------------------------
# Helper dialog
# ------------------------------------------------------------------
def _chiedi_nome(self, titolo: str, default: str = "") -> str | None:
dlg = Gtk.Dialog(
title=titolo,
transient_for=self.get_toplevel(),
modal=True
)
entry = Gtk.Entry()
entry.set_text(default)
entry.set_margin_start(12); entry.set_margin_end(12)
entry.set_margin_top(8); entry.set_margin_bottom(8)
dlg.get_content_area().add(entry)
dlg.add_buttons(t("sd.cancel"), Gtk.ResponseType.CANCEL, "OK", Gtk.ResponseType.OK)
dlg.show_all()
resp = dlg.run()
result = entry.get_text().strip() if resp == Gtk.ResponseType.OK else None
dlg.destroy()
return result
def _conferma(self, msg: str) -> bool:
dlg = Gtk.MessageDialog(
transient_for=self.get_toplevel(), modal=True,
message_type=Gtk.MessageType.QUESTION,
buttons=Gtk.ButtonsType.YES_NO, text=msg
)
resp = dlg.run()
dlg.destroy()
return resp == Gtk.ResponseType.YES
def _trova_winscp(self):
"""Risale la gerarchia widget per trovare il WinScpWidget padre."""
w = self.get_parent()
while w:
if hasattr(w, "_esegui_jobs"):
return w
w = w.get_parent()
return None
# ---------------------------------------------------------------------------
# Pannello LOCALE
# ---------------------------------------------------------------------------
class LocalPanel(FilePanel):
def __init__(self):
super().__init__("💻 Locale")
self.naviga(os.path.expanduser("~"))
def naviga(self, path: str):
path = os.path.expanduser(path)
if not os.path.isdir(path):
return
self.path = path
self.path_entry.set_text(path)
voci = [{"nome": "..", "is_dir": True,
"path": str(Path(path).parent), "size": 0, "mtime": "", "attr": ""}]
try:
raw = list(os.scandir(path))
except (PermissionError, OSError):
raw = []
raw.sort(key=lambda e: (not e.is_dir(follow_symlinks=False), e.name.lower()))
for e in raw:
try:
st = e.stat(follow_symlinks=False)
is_dir = e.is_dir(follow_symlinks=False)
if e.is_symlink():
try:
st = e.stat(follow_symlinks=True)
is_dir = os.path.isdir(e.path)
except OSError:
voci.append({"nome": f"⚠ {e.name}", "is_dir": False,
"path": e.path, "size": 0, "mtime": "", "attr": "link?"})
continue
size = 0 if is_dir else st.st_size
mtime = datetime.fromtimestamp(st.st_mtime).strftime("%d.%m.%Y %H:%M:%S")
m = st.st_mode
attr = ("r" if m & 0o444 else "-") + ("w" if m & 0o222 else "-") + ("x" if m & 0o111 else "-")
voci.append({"nome": e.name, "is_dir": is_dir,
"path": e.path, "size": size, "mtime": mtime, "attr": attr})
except (PermissionError, OSError):
voci.append({"nome": e.name, "is_dir": False,
"path": e.path, "size": 0, "mtime": "", "attr": "?"})
self._popola(voci)
def _menu_contestuale(self, event):
sel = self.selezione()
menu = Gtk.Menu()
def _mi(label, cb):
mi = Gtk.MenuItem(label=label)
mi.connect("activate", lambda _: cb())
menu.append(mi)
if sel:
ws = self._trova_winscp()
_mi(t("winscp.ctx_ul_remote").format(n=len(sel)),
lambda: ws._upload_selezione() if ws else None)
_mi(t("winscp.queue_add").format(n=len(sel)),
lambda: ws._accoda_upload(sel) if ws else None)
menu.append(Gtk.SeparatorMenuItem())
_mi(t("winscp.new_folder"), self._nuova_cartella)
if sel and not sel[0]["is_dir"]:
_mi(t("winscp.ctx_delete"), lambda: self._elimina(sel))
menu.append(Gtk.SeparatorMenuItem())
_mi(t("winscp.ctx_refresh"), self.aggiorna)
menu.show_all()
menu.popup_at_pointer(event)
def _nuova_cartella(self):
nome = self._chiedi_nome(t("winscp.new_folder"))
if nome:
try:
os.makedirs(os.path.join(self.path, nome), exist_ok=True)
self.aggiorna()
except Exception as e:
self._errore(str(e))
def _elimina(self, sel: list):
nomi = ", ".join(v["nome"] for v in sel)
if self._conferma(f"Eliminare: {nomi}?"):
for v in sel:
try:
if v["is_dir"]: shutil.rmtree(v["path"])
else: os.remove(v["path"])
except Exception as e:
self._errore(str(e))
self.aggiorna()
def _errore(self, msg: str):
dlg = Gtk.MessageDialog(
transient_for=self.get_toplevel(), modal=True,
message_type=Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.OK, text=msg
)
dlg.run()
dlg.destroy()
# ---------------------------------------------------------------------------
# Pannello REMOTO
# ---------------------------------------------------------------------------
class RemotePanel(FilePanel):
def __init__(self, sftp):
super().__init__("🌐 Remoto")
self._sftp = sftp
try:
home = sftp.normalize(".")
except Exception:
home = "/"
self.naviga(home)
def naviga(self, path: str):
self.path = path
self.path_entry.set_text(path)
threading.Thread(target=self._list_thread, args=(path,), daemon=True).start()
def _list_thread(self, path: str):
try:
entries = self._sftp.listdir_attr(path)
voci = [{"nome": "..", "is_dir": True,
"path": str(Path(path).parent), "size": 0, "mtime": "", "attr": ""}]
dirs = sorted([e for e in entries if stat.S_ISDIR(e.st_mode)],
key=lambda e: e.filename.lower())
files = sorted([e for e in entries if not stat.S_ISDIR(e.st_mode)],
key=lambda e: e.filename.lower())
for e in dirs + files:
mtime = datetime.fromtimestamp(e.st_mtime).strftime("%d.%m.%Y %H:%M:%S") \
if e.st_mtime else ""
voci.append({
"nome": e.filename,
"is_dir": stat.S_ISDIR(e.st_mode),
"path": path.rstrip("/") + "/" + e.filename,
"size": e.st_size or 0,
"mtime": mtime,
"attr": _fmt_attr(e.st_mode),
})
GLib.idle_add(self._popola, voci)
except Exception as e:
GLib.idle_add(self._status.set_text, f" ✖ {e}")
def _vai_home(self):
try:
home = self._sftp.normalize(".")
except Exception:
home = "/"
self.naviga(home)
def _menu_contestuale(self, event):
sel = self.selezione()
menu = Gtk.Menu()
def _mi(label, cb):
mi = Gtk.MenuItem(label=label)
mi.connect("activate", lambda _: cb())
menu.append(mi)
if sel:
ws = self._trova_winscp()
_mi(t("winscp.ctx_dl_local").format(n=len(sel)),
lambda: ws._download_selezione() if ws else None)
_mi(t("winscp.queue_add").format(n=len(sel)),
lambda: ws._accoda_download(sel) if ws else None)
menu.append(Gtk.SeparatorMenuItem())
_mi(t("winscp.new_folder"), self._nuova_cartella)
if sel:
_mi(t("winscp.rename"), lambda: self._rinomina(sel[0]))
_mi(t("winscp.ctx_delete"), lambda: self._elimina(sel))
menu.append(Gtk.SeparatorMenuItem())
_mi(t("winscp.ctx_refresh"), self.aggiorna)
menu.show_all()
menu.popup_at_pointer(event)
def _nuova_cartella(self):
nome = self._chiedi_nome(t("winscp.new_folder_remote"))
if nome:
try:
self._sftp.mkdir(self.path.rstrip("/") + "/" + nome)
self.aggiorna()
except Exception as e:
self._errore_ui(str(e))
def _rinomina(self, v: dict):
nuovo = self._chiedi_nome(t("winscp.rename"), default=v["nome"])
if nuovo and nuovo != v["nome"]:
try:
self._sftp.rename(v["path"], self.path.rstrip("/") + "/" + nuovo)
self.aggiorna()
except Exception as e:
self._errore_ui(str(e))
def _elimina(self, sel: list):
nomi = ", ".join(v["nome"] for v in sel)
if self._conferma(f"Eliminare dal remoto: {nomi}?"):
for v in sel:
try:
if v["is_dir"]: self._rmdir_ricorsivo(v["path"])
else: self._sftp.remove(v["path"])
except Exception as e:
self._errore_ui(str(e))
self.aggiorna()
def _rmdir_ricorsivo(self, path: str):
for attr in self._sftp.listdir_attr(path):
fp = path.rstrip("/") + "/" + attr.filename
if stat.S_ISDIR(attr.st_mode):
self._rmdir_ricorsivo(fp)
else:
self._sftp.remove(fp)
self._sftp.rmdir(path)
def _errore_ui(self, msg: str):
GLib.idle_add(self._mostra_errore, msg)
def _mostra_errore(self, msg: str):
dlg = Gtk.MessageDialog(
transient_for=self.get_toplevel(), modal=True,
message_type=Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.OK, text=msg
)
dlg.run()
dlg.destroy()
# ---------------------------------------------------------------------------
# Coda trasferimenti
# ---------------------------------------------------------------------------
class CodaWidget(Gtk.Box):
"""Pannello inferiore con la lista dei trasferimenti."""
def __init__(self):
super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=0)
self._jobs: list[TransferJob] = []
self._init_ui()
def _init_ui(self):
# Header + toolbar coda
hdr_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=4)
hdr_box.set_margin_start(4); hdr_box.set_margin_end(4)
hdr_box.set_margin_top(2); hdr_box.set_margin_bottom(2)
hdr = Gtk.Label(label=f" {t('winscp.queue_title')}")
hdr.set_xalign(0.0)
hdr.get_style_context().add_class("section-header")
hdr.set_hexpand(True)
hdr_box.pack_start(hdr, True, True, 0)
self._btn_pausa = Gtk.Button(label=t("winscp.btn_pause"))
self._btn_pausa.set_relief(Gtk.ReliefStyle.NONE)
self._btn_pausa.set_tooltip_text(t("winscp.transfer_running"))
self._btn_pausa.connect("clicked", self._on_pausa_riprendi)
hdr_box.pack_start(self._btn_pausa, False, False, 0)
btn_annulla = Gtk.Button(label=t("winscp.btn_cancel"))
btn_annulla.set_relief(Gtk.ReliefStyle.NONE)
btn_annulla.set_tooltip_text(t("winscp.tooltip_cancel_all"))
btn_annulla.connect("clicked", self._on_annulla)
hdr_box.pack_start(btn_annulla, False, False, 0)
btn_pulisci = Gtk.Button(label=t("winscp.btn_clear"))
btn_pulisci.set_relief(Gtk.ReliefStyle.NONE)
btn_pulisci.set_tooltip_text(t("winscp.tooltip_clear_queue"))
btn_pulisci.connect("clicked", self._on_pulisci)
hdr_box.pack_start(btn_pulisci, False, False, 0)
self.pack_start(hdr_box, False, False, 0)
self._in_pausa = False
# Store: icona, op, src, dst, trasferito, velocità, pct(int)
self._store = Gtk.ListStore(str, str, str, str, str, str, int)
self._view = Gtk.TreeView(model=self._store)
self._view.set_headers_visible(True)
headers = ["", t("winscp.col_op"), t("winscp.col_src"), t("winscp.col_dst"), t("winscp.col_transferred"), t("winscp.col_speed")]
widths = [24, 60, 0, 0, 80, 100]
expand = [False, False, True, True, False, False]
for i, (h, w, ex) in enumerate(zip(headers, widths, expand)):
cell = Gtk.CellRendererText()
cell.set_property("ellipsize", Pango.EllipsizeMode.END)
col = Gtk.TreeViewColumn(h, cell, text=i)
col.set_resizable(True)
col.set_expand(ex)
if w:
col.set_min_width(w)
self._view.append_column(col)
# Colonna progress bar
cell_pb = Gtk.CellRendererProgress()
col_pb = Gtk.TreeViewColumn(t("winscp.col_pct"), cell_pb, value=6)
col_pb.set_min_width(80)
self._view.append_column(col_pb)
scroll = Gtk.ScrolledWindow()
scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
scroll.set_min_content_height(110)
scroll.set_max_content_height(130)
scroll.add(self._view)
self.pack_start(scroll, False, False, 0)
def aggiungi_job(self, job: TransferJob) -> int:
self._jobs.append(job)
icona = "⬆" if job.op == "upload" else "⬇"
self._store.append([icona, job.op.capitalize(),
job.src, job.dst, "—", t("winscp.status_wait_lbl"), 0])
return len(self._jobs) - 1
def aggiorna_progress(self, idx: int, tx: int, tot: int):
if idx >= len(self._store):
return
pct = int(tx * 100 / tot) if tot > 0 else 0
it = self._store.get_iter_from_string(str(idx))
if it is None:
return
job = self._jobs[idx] if idx < len(self._jobs) else None
self._store.set_value(it, 4, _fmt_size(tx))
self._store.set_value(it, 6, pct)
if job and job.velocita > 0:
eta = int((tot - tx) / job.velocita) if tot > tx else 0
vel = f"{_fmt_size(job.velocita)}/s ETA {eta}s"
self._store.set_value(it, 5, vel)
def segna_completato(self, idx: int, ok: bool, msg: str):
if idx >= len(self._store):
return
it = self._store.get_iter_from_string(str(idx))
if it is None:
return
self._store.set_value(it, 5, "✓ OK" if ok else f"✖ {msg}")
self._store.set_value(it, 6, 100 if ok else 0)
def _on_pausa_riprendi(self, btn):
self._in_pausa = not self._in_pausa
self._btn_pausa.set_label(t("winscp.btn_resume") if self._in_pausa else t("winscp.btn_pause"))
def _on_annulla(self, btn):
"""Annulla il job in corso e tutti quelli in attesa."""
stato_in_corso = t("winscp.status_running")
stato_in_attesa = t("winscp.status_wait")
stato_annullato = t("winscp.status_cancelled")
for i, job in enumerate(self._jobs):
if job.stato in (stato_in_corso, stato_in_attesa):
job.annulla = True
job.stato = stato_annullato
it = self._store.get_iter_from_string(str(i))
if it:
self._store.set_value(it, 5, f"✖ {stato_annullato}")
def _on_pulisci(self, btn):
"""Rimuove dalla coda tutti i job non in esecuzione (completati, errore, annullati, in attesa)."""
stato_running = t("winscp.status_running")
to_remove = [i for i, job in enumerate(self._jobs)
if job.stato != stato_running]
for i in reversed(to_remove):
it = self._store.get_iter_from_string(str(i))
if it:
self._store.remove(it)
self._jobs.pop(i)
def is_in_pausa(self) -> bool:
return self._in_pausa
# ---------------------------------------------------------------------------
# WinScpWidget — widget principale dual-pane
# ---------------------------------------------------------------------------
class WinScpWidget(Gtk.Box):
"""
Browser SFTP dual-pane stile WinSCP (GTK3).
Riceve un profilo sessione SSH e apre la connessione SFTP.
"""
def __init__(self, profilo: dict):
super().__init__(orientation=Gtk.Orientation.VERTICAL, spacing=0)
self._profilo = profilo
self._sftp = None
self._sftp_transfer = None # Connessione SFTP separata per i trasferimenti
self._ssh = None
self._ssh_transfer = None # Connessione SSH separata per i trasferimenti
self._worker_thread = None
self._init_ui()
if PARAMIKO_OK:
threading.Thread(target=self._connetti, daemon=True).start()
else:
GLib.idle_add(self._mostra_errore_init, "paramiko non installato.\npip install paramiko")
def _init_ui(self):
# --- Toolbar ---
tb = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=4)
tb.set_margin_start(8)
tb.set_margin_end(8)
tb.set_margin_top(6)
tb.set_margin_bottom(6)
self.pack_start(tb, False, False, 0)
for label, tip, cb in [
(t("winscp.btn_upload"), t("winscp.tooltip_upload"), self._upload_selezione),
(t("winscp.btn_download"), t("winscp.tooltip_download"), self._download_selezione),
(t("winscp.tooltip_btn_start"), t("winscp.tooltip_start_all"), self._avvia_coda),
(t("sync.btn"), t("sync.tooltip"), self._on_sincronizza),
(t("winscp.btn_delete"), t("winscp.tooltip_delete"), self._elimina_selezione),
(t("winscp.btn_refresh"), t("winscp.tooltip_refresh_both"), self._aggiorna_tutto),
(t("winscp.btn_clear"), t("winscp.tooltip_clear_queue"), self._pulisci_coda),
]:
btn = Gtk.Button(label=label)
btn.set_tooltip_text(tip)
btn.connect("clicked", lambda b, c=cb: c())
tb.pack_start(btn, False, False, 0)
sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
self.pack_start(sep, False, False, 0)
# --- Pannello caricamento (mostrato finché SFTP non è pronto) ---
self._loading_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
self._loading_box.set_halign(Gtk.Align.CENTER)
self._loading_box.set_valign(Gtk.Align.CENTER)
self._loading_lbl = Gtk.Label(label=t("winscp.connecting"))
self._loading_spinner = Gtk.Spinner()
self._loading_spinner.start()
self._loading_box.pack_start(self._loading_spinner, False, False, 0)
self._loading_box.pack_start(self._loading_lbl, False, False, 0)
self.pack_start(self._loading_box, True, True, 0)
# --- Dual-pane (nascosto finché non connesso) ---
self._dual_pane = Gtk.Paned(orientation=Gtk.Orientation.HORIZONTAL)
self._local_panel = LocalPanel()
self._remote_panel = None # creato dopo connessione
self._dual_pane.pack1(self._local_panel, True, True)
self._dual_pane.set_no_show_all(True)
self.pack_start(self._dual_pane, True, True, 0)
sep2 = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL)
self.pack_start(sep2, False, False, 0)
# --- Coda trasferimenti ---
self._coda = CodaWidget()
self.pack_start(self._coda, False, False, 0)
# ------------------------------------------------------------------
# Connessione SFTP
# ------------------------------------------------------------------
def _connetti(self):
try:
host = self._profilo.get("host", "")
port = int(self._profilo.get("port", 22))
user = self._profilo.get("user", "")
pwd = self._profilo.get("password", "")
pkey = self._profilo.get("private_key", "")
# Connessione principale per navigazione
self._ssh = paramiko.SSHClient()
self._ssh.load_system_host_keys()
self._ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
kw = {"hostname": host, "port": port, "username": user, "timeout": 15}
if pkey and os.path.isfile(pkey):
kw["key_filename"] = pkey
elif pwd:
kw["password"] = pwd
self._ssh.connect(**kw)
self._sftp = self._ssh.open_sftp()
# Connessione separata per trasferimenti
self._ssh_transfer = paramiko.SSHClient()
self._ssh_transfer.load_system_host_keys()
self._ssh_transfer.set_missing_host_key_policy(paramiko.RejectPolicy())
self._ssh_transfer.connect(**kw)
self._sftp_transfer = self._ssh_transfer.open_sftp()
GLib.idle_add(self._on_connesso)
except Exception as e:
GLib.idle_add(self._mostra_errore_init, str(e))
def _on_connesso(self):
"""Chiamato sul thread principale dopo connessione riuscita."""
self._remote_panel = RemotePanel(self._sftp)
self._dual_pane.pack2(self._remote_panel, True, True)
self._dual_pane.set_position(500)
self._loading_box.hide()
self._loading_spinner.stop()
self._dual_pane.set_no_show_all(False)
self._dual_pane.show_all()
def _mostra_errore_init(self, msg: str):
self._loading_spinner.stop()
self._loading_lbl.set_text(f"✖ Errore connessione:\n{msg}")
# ------------------------------------------------------------------
# Operazioni toolbar
# ------------------------------------------------------------------
def _upload_selezione(self):
if not self._sftp or not self._remote_panel:
return
sel = self._local_panel.selezione()
if not sel:
return
jobs = []
for v in sel:
rpath = self._remote_panel.path.rstrip("/") + "/" + v["nome"]
if v["is_dir"]:
jobs += self._jobs_upload_dir(v["path"], rpath)
else:
jobs.append(TransferJob("upload", v["path"], rpath,
size=v["size"], nome=v["nome"]))
self._esegui_jobs(jobs)
def _download_selezione(self):
if not self._sftp or not self._remote_panel:
return
sel = self._remote_panel.selezione()
if not sel:
return
jobs = []
for v in sel:
lpath = os.path.join(self._local_panel.path, v["nome"])
if v["is_dir"]:
jobs += self._jobs_download_dir(v["path"], lpath)
else:
jobs.append(TransferJob("download", v["path"], lpath,
size=v["size"], nome=v["nome"]))
self._esegui_jobs(jobs)
def _elimina_selezione(self):
"""Elimina la selezione nel pannello attivo (tenta remoto, poi locale)."""
if self._remote_panel:
sel = self._remote_panel.selezione()
if sel:
self._remote_panel._elimina(sel)
return
sel = self._local_panel.selezione()
if sel:
self._local_panel._elimina(sel)
def _aggiorna_tutto(self):
self._local_panel.aggiorna()
if self._remote_panel:
self._remote_panel.aggiorna()
def _accoda_download(self, sel: list):
"""Aggiunge i file selezionati dal pannello remoto alla coda senza avviarli."""
if not self._sftp or not self._remote_panel:
return
for v in sel:
lpath = os.path.join(self._local_panel.path, v["nome"])
if v["is_dir"]:
for job in self._jobs_download_dir(v["path"], lpath):
self._coda.aggiungi_in_attesa(job)
else:
self._coda.aggiungi_in_attesa(
TransferJob("download", v["path"], lpath,
size=v["size"], nome=v["nome"]))
def _accoda_upload(self, sel: list):
"""Aggiunge i file selezionati dal pannello locale alla coda senza avviarli."""
if not self._sftp or not self._remote_panel:
return
n = 0
for v in sel:
if not v["is_dir"]:
rpath = self._remote_panel.path.rstrip("/") + "/" + v["nome"]
self._coda.aggiungi_in_attesa(
TransferJob("upload", v["path"], rpath,
size=v["size"], nome=v["nome"]))
n += 1
def _avvia_coda(self):
"""Avvia tutti i job in attesa nella coda (chiamato dal pulsante ▶)."""
self._avvia_coda_se_idle()
def _pulisci_coda(self):
self._coda.pulisci()
# ------------------------------------------------------------------
# Sincronizzazione directory locale ↔ remota
# ------------------------------------------------------------------
def _on_sincronizza(self):
if not self._sftp or not self._remote_panel:
return
local_path = self._local_panel.path
remote_path = self._remote_panel.path
if not local_path or not remote_path:
return
dlg = _SyncDialog(
parent=self.get_toplevel(),
sftp=self._sftp,
local_path=local_path,
remote_path=remote_path,
)
if dlg.run() == Gtk.ResponseType.OK:
jobs = dlg.get_jobs()
self._esegui_jobs(jobs)
dlg.destroy()
def _avvia_coda_se_idle(self):
"""Avvia il worker solo se non è già in esecuzione."""
if self._worker_thread and self._worker_thread.is_alive():
return
stato_attesa = t("winscp.status_wait")
jobs_in_attesa = [(i, j) for i, j in enumerate(self._coda._jobs)
if j.stato == stato_attesa]
if not jobs_in_attesa:
return
def run():
_annullato = t("winscp.status_cancelled")
for idx, job in jobs_in_attesa:
while self._coda.is_in_pausa():
time.sleep(0.3)
if job.annulla or job.stato == _annullato:
continue
job.stato = t("winscp.status_running")
job.t_inizio = time.time()
try:
self._trasferisci_chunk(job, idx)
if job.annulla:
job.stato = _annullato
GLib.idle_add(self._coda.segna_completato, idx, False, _annullato)
else:
job.stato = t("winscp.status_done")
GLib.idle_add(self._coda.segna_completato, idx, True, "")
except Exception as e:
job.stato = t("winscp.status_err")
job.errore = str(e)
GLib.idle_add(self._coda.segna_completato, idx, False, str(e))
GLib.idle_add(self._aggiorna_tutto)
self._worker_thread = threading.Thread(target=run, daemon=True)
self._worker_thread.start()
# ------------------------------------------------------------------
# Esecuzione job in thread
# ------------------------------------------------------------------
def _jobs_upload_dir(self, local_dir: str, remote_dir: str) -> list:
"""Espande una cartella locale in lista di TransferJob ricorsivi."""
jobs = []
try:
self._sftp.mkdir(remote_dir)
except Exception:
pass
for entry in os.scandir(local_dir):
rp = remote_dir.rstrip("/") + "/" + entry.name
if entry.is_dir(follow_symlinks=False):
jobs += self._jobs_upload_dir(entry.path, rp)
else:
sz = entry.stat().st_size
jobs.append(TransferJob("upload", entry.path, rp,
size=sz, nome=entry.name))
return jobs
def _jobs_download_dir(self, remote_dir: str, local_dir: str) -> list:
"""Espande una cartella remota in lista di TransferJob ricorsivi."""
jobs = []
try:
os.makedirs(local_dir, exist_ok=True)
except Exception:
pass
for attr in self._sftp.listdir_attr(remote_dir):
rp = remote_dir.rstrip("/") + "/" + attr.filename
lp = os.path.join(local_dir, attr.filename)