-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwinscp_widget.py
More file actions
2303 lines (2037 loc) · 89.1 KB
/
Copy pathwinscp_widget.py
File metadata and controls
2303 lines (2037 loc) · 89.1 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 — Finestra SFTP stile WinSCP per PCM.
Layout:
┌────────────────────────────────────────────────────────────┐
│ Toolbar: Upload ▲ Download ▼ Sync Delete Properties │
├───────────────────────┬────────────────────────────────────┤
│ LOCALE │ REMOTO │
│ path bar + nav │ path bar + nav │
│ [tabella file] │ [tabella file] │
├───────────────────────┴────────────────────────────────────┤
│ Coda trasferimenti (Operation | Source | Dest | % | ETA) │
└────────────────────────────────────────────────────────────┘
Supporta:
- navigazione locale e remota con doppio clic
- upload (locale→remoto) e download (remoto→locale) con progress bar
- trasferimento cartelle ricorsivo
- coda trasferimenti con thread dedicato
- rinomina, elimina, nuova cartella, proprietà (remoto)
- drag & drop tra i due pannelli
- barra stato con dimensioni selezione
"""
import os
import stat
import shutil
import threading
import time
from pathlib import Path
from datetime import datetime
from PyQt6.QtWidgets import (
QWidget, QVBoxLayout, QHBoxLayout, QSplitter, QLabel, QLineEdit,
QToolButton, QPushButton, QTableWidget, QTableWidgetItem, QHeaderView,
QAbstractItemView, QMenu, QMessageBox, QInputDialog, QProgressBar,
QFrame, QStatusBar, QApplication, QFileDialog, QSizePolicy,
QToolBar, QStyle
)
from PyQt6.QtCore import (
Qt, QThread, QObject, pyqtSignal, QTimer, QMimeData, QSize
)
from PyQt6.QtGui import QFont, QColor, QDrag, QKeySequence, QAction
try:
import paramiko
PARAMIKO_OK = True
except ImportError:
PARAMIKO_OK = False
from translations import t
def _fmt_size(n: int) -> str:
"""Formatta dimensione in byte in stringa leggibile."""
if n is None:
return ""
n = int(n)
if n < 1024:
return f"{n} B"
elif n < 1024 ** 2:
return f"{n/1024:.1f} KB"
elif n < 1024 ** 3:
return f"{n/1024**2:.1f} MB"
return f"{n/1024**3:.2f} GB"
# ============================================================================
# Thread di trasferimento
# ============================================================================
class TransferJob:
"""Rappresenta un singolo job di trasferimento."""
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") # In attesa | In corso | Completato | Errore
self.errore = ""
self.velocita = 0
self.t_inizio = 0.0
class TransferWorker(QObject):
"""Worker che esegue i trasferimenti SFTP in un thread separato."""
job_iniziato = pyqtSignal(int) # indice job
job_progress = pyqtSignal(int, int, int) # indice, trasferito, totale
job_finito = pyqtSignal(int, bool, str) # indice, ok, msg
tutti_finiti = pyqtSignal()
def __init__(self, sftp):
super().__init__()
self._sftp = sftp
self._jobs = []
self._stop = False
self._lock = threading.Lock()
def aggiungi(self, job: TransferJob) -> int:
with self._lock:
self._jobs.append(job)
return len(self._jobs) - 1
def stop(self):
self._stop = True
def run(self):
for idx, job in enumerate(self._jobs):
if self._stop:
break
job.stato = t("winscp.status_running")
job.t_inizio = time.time()
self.job_iniziato.emit(idx)
try:
if job.op == "download":
self._download(idx, job)
else:
self._upload(idx, job)
job.stato = t("winscp.status_done")
self.job_finito.emit(idx, True, "")
except Exception as e:
job.stato = t("winscp.status_err")
job.errore = str(e)
self.job_finito.emit(idx, False, str(e))
self.tutti_finiti.emit()
def _download(self, idx, job):
def cb(tx, tot):
job.trasferito = tx
dt = time.time() - job.t_inizio
job.velocita = int(tx / dt) if dt > 0 else 0
self.job_progress.emit(idx, tx, tot or job.size)
self._sftp.get(job.src, job.dst, callback=cb)
def _upload(self, idx, job):
def cb(tx, tot):
job.trasferito = tx
dt = time.time() - job.t_inizio
job.velocita = int(tx / dt) if dt > 0 else 0
self.job_progress.emit(idx, tx, tot or job.size)
self._sftp.put(job.src, job.dst, callback=cb)
# ============================================================================
# Pannello file (locale o remoto)
# ============================================================================
COL_NOME, COL_EXT, COL_SIZE, COL_DATA, COL_ATTR = 0, 1, 2, 3, 4
COLONNE = [t("winscp.col_name"), t("winscp.col_ext"), t("winscp.col_size"), t("winscp.col_modified"), t("winscp.col_attrs")]
class FilePanel(QWidget):
"""
Singolo pannello file (locale o remoto).
Emette segnali per navigazione e selezione.
"""
navigato = pyqtSignal(str) # nuovo path
selezione_cambiata = pyqtSignal(list) # lista nomi selezionati
def __init__(self, titolo="Locale", parent=None):
super().__init__(parent)
self.titolo = titolo
self.path = ""
self._voci = [] # lista di dict con info file
self._init_ui()
# ------------------------------------------------------------------
# UI
# ------------------------------------------------------------------
def _init_ui(self):
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
# Header titolo
hdr = QLabel(f" {self.titolo}")
hdr.setFixedHeight(24)
hdr.setStyleSheet(
"background:#f0f0f0; color:#4e7abc; font-weight:bold; "
"font-size:12px; padding:0 6px; border-bottom:1px solid #ccc;"
)
layout.addWidget(hdr)
# Barra navigazione
nav = QHBoxLayout()
nav.setContentsMargins(3, 2, 3, 2)
nav.setSpacing(2)
self.btn_su = QToolButton()
self.btn_su.setText("⬆")
self.btn_su.setToolTip(t("sftp.parent_folder"))
self.btn_su.setFixedHeight(22)
self.btn_su.clicked.connect(self.vai_su)
self.btn_su.setStyleSheet(self._btn_stile())
self.btn_home = QToolButton()
self.btn_home.setText("🏠")
self.btn_home.setToolTip(t("winscp.tooltip_home"))
self.btn_home.setFixedHeight(22)
self.btn_home.clicked.connect(self.vai_home)
self.btn_home.setStyleSheet(self._btn_stile())
self.btn_aggiorna = QToolButton()
self.btn_aggiorna.setText("↺")
self.btn_aggiorna.setToolTip(t("winscp.tooltip_refresh"))
self.btn_aggiorna.setFixedHeight(22)
self.btn_aggiorna.clicked.connect(self.aggiorna)
self.btn_aggiorna.setStyleSheet(self._btn_stile())
self.edit_path = QLineEdit()
self.edit_path.setFixedHeight(22)
self.edit_path.setStyleSheet(
"background:#ffffff; color:#4e7abc; font-family:monospace; "
"font-size:11px; border:1px solid #ccc; padding:0 4px;"
)
self.edit_path.returnPressed.connect(
lambda: self.naviga(self.edit_path.text().strip())
)
nav.addWidget(self.btn_su)
nav.addWidget(self.btn_home)
nav.addWidget(self.btn_aggiorna)
nav.addWidget(self.edit_path, 1)
layout.addLayout(nav)
# Tabella file
self.tabella = QTableWidget(0, len(COLONNE))
self.tabella.setHorizontalHeaderLabels(COLONNE)
self.tabella.horizontalHeader().setSectionResizeMode(COL_NOME, QHeaderView.ResizeMode.Stretch)
self.tabella.horizontalHeader().setSectionResizeMode(COL_EXT, QHeaderView.ResizeMode.ResizeToContents)
self.tabella.horizontalHeader().setSectionResizeMode(COL_SIZE, QHeaderView.ResizeMode.ResizeToContents)
self.tabella.horizontalHeader().setSectionResizeMode(COL_DATA, QHeaderView.ResizeMode.ResizeToContents)
self.tabella.horizontalHeader().setSectionResizeMode(COL_ATTR, QHeaderView.ResizeMode.ResizeToContents)
self.tabella.verticalHeader().setVisible(False)
self.tabella.verticalHeader().setDefaultSectionSize(20)
self.tabella.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
self.tabella.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.tabella.setAlternatingRowColors(True)
self.tabella.setSortingEnabled(True)
self.tabella.setStyleSheet(
"QTableWidget { background:#ffffff; color:#111111; "
" gridline-color:#dddddd; border:none; font-size:12px; }"
"QTableWidget::item { padding:1px 4px; color:#111111; }"
"QTableWidget::item:selected { background:#4e7abc; color:#ffffff; }"
"QTableWidget::item:selected:active { background:#4e7abc; color:#ffffff; }"
"QTableWidget::item:selected:!active { background:#b0c4de; color:#ffffff; }"
"QTableWidget::item:alternate { background:#f5f5f5; color:#111111; }"
"QHeaderView::section { background:#e8e8e8; color:#333333; "
" border:1px solid #ccc; padding:3px; font-size:11px; }"
)
self.tabella.itemDoubleClicked.connect(self._doppio_clic)
self.tabella.itemSelectionChanged.connect(self._selezione_cambiata)
self.tabella.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.tabella.customContextMenuRequested.connect(self._menu_contestuale)
# Drag & Drop
self.tabella.setDragEnabled(True)
self.tabella.setAcceptDrops(True)
self.tabella.setDropIndicatorShown(True)
self.tabella.dragEnterEvent = self._drag_enter
self.tabella.dragMoveEvent = self._drag_move
self.tabella.dropEvent = self._drop_event
layout.addWidget(self.tabella, 1)
# Status bar locale al pannello
self.lbl_status = QLabel()
self.lbl_status.setFixedHeight(18)
self.lbl_status.setStyleSheet(
"background:#f0f0f0; color:#555555; font-size:10px; padding:0 6px; border-top:1px solid #ccc;"
)
layout.addWidget(self.lbl_status)
# ------------------------------------------------------------------
# Navigazione (da implementare nelle sottoclassi)
# ------------------------------------------------------------------
def naviga(self, path):
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 tabella
# ------------------------------------------------------------------
def _popola(self, voci: list):
"""voci: lista di dict {nome, is_dir, size, mtime, attr}"""
self._voci = voci
self.tabella.setSortingEnabled(False)
self.tabella.setRowCount(0)
for v in voci:
r = self.tabella.rowCount()
self.tabella.insertRow(r)
nome = v["nome"]
is_dir = v["is_dir"]
# Icona cartella/file via Qt standard icons (nessun emoji → nessun quadratino)
col_nome = QTableWidgetItem(nome)
style = QApplication.style()
ico = style.standardIcon(
QStyle.StandardPixmap.SP_DirIcon if is_dir
else QStyle.StandardPixmap.SP_FileIcon
)
col_nome.setIcon(ico)
col_nome.setData(Qt.ItemDataRole.UserRole, v)
if is_dir:
# Colore blu solo quando NON selezionato; la selezione usa lo stylesheet
col_nome.setData(Qt.ItemDataRole.ForegroundRole, QColor("#1a5ca8"))
ext = "" if is_dir else (Path(nome).suffix.lstrip(".") or "")
col_ext = QTableWidgetItem(ext)
col_size = QTableWidgetItem("" if is_dir else self._fmt_size(v.get("size", 0)))
col_size.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
col_data = QTableWidgetItem(v.get("mtime", ""))
col_attr = QTableWidgetItem(v.get("attr", ""))
# Dati numerici per sort corretto
col_size.setData(Qt.ItemDataRole.UserRole + 1, v.get("size", 0))
self.tabella.setItem(r, COL_NOME, col_nome)
self.tabella.setItem(r, COL_EXT, col_ext)
self.tabella.setItem(r, COL_SIZE, col_size)
self.tabella.setItem(r, COL_DATA, col_data)
self.tabella.setItem(r, COL_ATTR, col_attr)
self.tabella.setSortingEnabled(True)
self.tabella.sortItems(COL_NOME, Qt.SortOrder.AscendingOrder)
self._aggiorna_status()
def _aggiorna_status(self):
n = self.tabella.rowCount()
self.lbl_status.setText(
f" {n} elementi | {self.path}"
)
# ------------------------------------------------------------------
# Selezione
# ------------------------------------------------------------------
def selezione(self) -> list:
"""Restituisce lista di dict delle voci selezionate."""
righe = set(i.row() for i in self.tabella.selectedItems())
result = []
for r in sorted(righe):
item = self.tabella.item(r, COL_NOME)
if item:
v = item.data(Qt.ItemDataRole.UserRole)
if v:
result.append(v)
return result
def _selezione_cambiata(self):
self.selezione_cambiata.emit([v["nome"] for v in self.selezione()])
# ------------------------------------------------------------------
# Doppio clic
# ------------------------------------------------------------------
def _doppio_clic(self, item):
v = self.tabella.item(item.row(), COL_NOME).data(Qt.ItemDataRole.UserRole)
if not v:
return
if v["nome"] == "..":
self.vai_su()
elif v["is_dir"]:
self.naviga(v["path"])
# ------------------------------------------------------------------
# Drag source: avvia drag dalla tabella con lista file selezionati
# ------------------------------------------------------------------
def _init_drag_source(self):
"""Attiva il pannello come sorgente drag."""
self.tabella.setDragEnabled(True)
self.tabella.setDragDropMode(QAbstractItemView.DragDropMode.DragOnly)
def _init_drop_target(self):
"""Attiva il pannello come destinazione drop."""
self.tabella.setAcceptDrops(True)
self.tabella.setDragDropMode(QAbstractItemView.DragDropMode.DragDrop)
self.tabella.dragEnterEvent = self._drag_enter
self.tabella.dragMoveEvent = self._drag_move
self.tabella.dropEvent = self._drop_event
def _start_drag(self):
"""Chiamato da mouseMoveEvent — avvia il drag con la selezione corrente."""
sel = self.selezione()
if not sel:
return
nomi = "\n".join(v["path"] for v in sel)
mime = QMimeData()
mime.setText(f"pcm_files:{self._panel_tipo()}\n{nomi}")
drag = QDrag(self.tabella)
drag.setMimeData(mime)
drag.exec(Qt.DropAction.CopyAction | Qt.DropAction.MoveAction)
def _panel_tipo(self) -> str:
return t("winscp.local_panel") # override nelle sottoclassi
# ------------------------------------------------------------------
# Drag & Drop (overridati nelle sottoclassi)
# ------------------------------------------------------------------
def _drag_enter(self, ev):
if ev.mimeData().hasText() and ev.mimeData().text().startswith("pcm_files:"):
ev.acceptProposedAction()
else:
ev.ignore()
def _drag_move(self, ev):
if ev.mimeData().hasText() and ev.mimeData().text().startswith("pcm_files:"):
ev.acceptProposedAction()
else:
ev.ignore()
def _drop_event(self, ev):
ev.ignore() # override nelle sottoclassi
# ------------------------------------------------------------------
# Menu contestuale stub
# ------------------------------------------------------------------
def _menu_contestuale(self, pos):
pass
# ------------------------------------------------------------------
# Utility
# ------------------------------------------------------------------
@staticmethod
def _fmt_size(n: int) -> str:
if n is None:
return ""
if n < 1024:
return f"{n} B"
elif n < 1024 ** 2:
return f"{n/1024:.1f} KB"
elif n < 1024 ** 3:
return f"{n/1024**2:.1f} MB"
return f"{n/1024**3:.2f} GB"
@staticmethod
def _btn_stile():
return (
"QToolButton { background:transparent; color:#444444; border:none; "
"font-size:13px; padding:0 3px; }"
"QToolButton:hover { color:#fff; background:#4e7abc; border-radius:3px; }"
)
# ============================================================================
# Pannello LOCALE
# ============================================================================
class LocalPanel(FilePanel):
def __init__(self, parent=None):
super().__init__("💻 Locale", parent)
self._init_drag_source()
self._init_drop_target()
# Avvia drag su mouseMove con tasto sinistro premuto
self.tabella.mouseMoveEvent = self._tabella_mouse_move
self._drag_pos = None
self.naviga(os.path.expanduser("~"))
def _panel_tipo(self) -> str:
return "locale"
def _tabella_mouse_move(self, ev):
if ev.buttons() & Qt.MouseButton.LeftButton:
if self._drag_pos is None:
self._drag_pos = ev.pos()
elif (ev.pos() - self._drag_pos).manhattanLength() > 20:
self._drag_pos = None
self._start_drag()
return
else:
self._drag_pos = None
QAbstractItemView.mouseMoveEvent(self.tabella, ev)
def _drop_event(self, ev):
"""Drop sul pannello locale = download dal remoto."""
txt = ev.mimeData().text() if ev.mimeData().hasText() else ""
if not txt.startswith("pcm_files:remoto"):
ev.ignore()
return
righe = txt.split("\n")[1:]
paths_remoti = [r for r in righe if r.strip()]
if paths_remoti:
winscp = self._trova_winscp()
if winscp:
jobs = []
for rpath in paths_remoti:
nome = os.path.basename(rpath)
lpath = os.path.join(self.path, nome)
jobs.append(TransferJob("download", rpath, lpath, nome=nome))
winscp._esegui_jobs(jobs)
ev.acceptProposedAction()
def _trova_winscp(self):
p = self.parent()
while p:
if hasattr(p, '_esegui_jobs'):
return p
p = p.parent() if hasattr(p, 'parent') else None
return None
def vai_home(self):
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.edit_path.setText(path)
voci = [{"nome": "..", "is_dir": True, "path": str(Path(path).parent),
"size": 0, "mtime": "", "attr": ""}]
try:
# follow_symlinks=False per evitare crash su symlink rotti
raw = list(os.scandir(path))
except (PermissionError, OSError):
raw = []
# Ordina: cartelle prima, poi file, alfabetico
raw.sort(key=lambda e: (not e.is_dir(follow_symlinks=False), e.name.lower()))
for e in raw:
try:
# stat senza seguire symlink per evitare [Errno 2] su link rotti
st = e.stat(follow_symlinks=False)
is_dir = e.is_dir(follow_symlinks=False)
# Se è un symlink valido, segui per la dimensione reale
if e.is_symlink():
try:
st_real = e.stat(follow_symlinks=True)
is_dir = os.path.isdir(e.path)
size = 0 if is_dir else st_real.st_size
mtime = datetime.fromtimestamp(st_real.st_mtime).strftime("%d.%m.%Y %H:%M:%S")
except OSError:
# Symlink rotto: mostra comunque il file con indicatore
size = 0
mtime = datetime.fromtimestamp(st.st_mtime).strftime("%d.%m.%Y %H:%M:%S")
e_nome = f"⚠ {e.name}"
voci.append({"nome": e_nome, "is_dir": False,
"path": e.path, "size": 0, "mtime": mtime, "attr": "link?"})
continue
else:
is_dir = e.is_dir()
size = 0 if is_dir else st.st_size
mtime = datetime.fromtimestamp(st.st_mtime).strftime("%d.%m.%Y %H:%M:%S")
voci.append({
"nome": e.name,
"is_dir": is_dir,
"path": e.path,
"size": size,
"mtime": mtime,
"attr": self._attrs_locali(e),
})
except (PermissionError, OSError):
voci.append({"nome": e.name, "is_dir": False,
"path": e.path, "size": 0, "mtime": "", "attr": "?"})
self._popola(voci)
self.navigato.emit(path)
@staticmethod
def _attrs_locali(entry) -> str:
try:
m = entry.stat().st_mode
r = "r" if m & 0o444 else "-"
w = "w" if m & 0o222 else "-"
x = "x" if m & 0o111 else "-"
return f"{r}{w}{x}"
except Exception:
return ""
def _menu_contestuale(self, pos):
sel = self.selezione()
menu = QMenu(self)
menu.setStyleSheet(
"QMenu { background:#ffffff; color:#111111; border:1px solid #ccc; }"
"QMenu::item:selected { background:#4e7abc; color:#fff; }"
)
if sel:
menu.addAction(f"⬆ Carica su remoto ({len(sel)} elementi)",
lambda: self.parent().parent()._upload_selezione())
menu.addSeparator()
menu.addAction(t("winscp.new_folder"), self._nuova_cartella_locale)
if sel and not sel[0]["is_dir"]:
menu.addAction(t("winscp.ctx_delete"), lambda: self._elimina_locale(sel))
menu.addSeparator()
menu.addAction(t("winscp.ctx_refresh"), self.aggiorna)
menu.exec(self.tabella.mapToGlobal(pos))
def _nuova_cartella_locale(self):
nome, ok = QInputDialog.getText(self, t("winscp.new_folder"), t("winscp.field_name"))
if ok and nome:
try:
os.makedirs(os.path.join(self.path, nome), exist_ok=True)
self.aggiorna()
except Exception as e:
QMessageBox.critical(self, "Errore", str(e))
def _elimina_locale(self, sel):
nomi = ", ".join(v["nome"] for v in sel)
if QMessageBox.question(self, t("winscp.dlg_delete"), t("winscp.dlg_delete_confirm").format(names=nomi)) \
== QMessageBox.StandardButton.Yes:
for v in sel:
try:
if v["is_dir"]:
shutil.rmtree(v["path"])
else:
os.remove(v["path"])
except Exception as e:
QMessageBox.critical(self, t("winscp.err_generic2"), str(e))
self.aggiorna()
# ============================================================================
# Pannello REMOTO
# ============================================================================
class RemotePanel(FilePanel):
def __init__(self, sftp, parent=None):
super().__init__("🌐 Remoto", parent)
self._sftp = sftp
self._init_drag_source()
self._init_drop_target()
self.tabella.mouseMoveEvent = self._tabella_mouse_move
self._drag_pos = None
try:
home = sftp.normalize(".")
except Exception:
home = "/"
try:
self.naviga(home)
except Exception as e:
self.lbl_status.setText(t("winscp.err_nav").format(e=e))
def _panel_tipo(self) -> str:
return "remoto"
def _tabella_mouse_move(self, ev):
if ev.buttons() & Qt.MouseButton.LeftButton:
if self._drag_pos is None:
self._drag_pos = ev.pos()
elif (ev.pos() - self._drag_pos).manhattanLength() > 20:
self._drag_pos = None
self._start_drag()
return
else:
self._drag_pos = None
QAbstractItemView.mouseMoveEvent(self.tabella, ev)
def _drop_event(self, ev):
"""Drop sul pannello remoto = upload dal locale."""
txt = ev.mimeData().text() if ev.mimeData().hasText() else ""
if not txt.startswith("pcm_files:" + t("winscp.local_panel")):
ev.ignore()
return
righe = txt.split("\n")[1:]
paths_locali = [r for r in righe if r.strip()]
if paths_locali:
winscp = self._trova_winscp()
if winscp:
jobs = []
for lpath in paths_locali:
nome = os.path.basename(lpath)
rpath = self.path.rstrip("/") + "/" + nome
size = os.path.getsize(lpath) if os.path.isfile(lpath) else 0
if os.path.isdir(lpath):
jobs += winscp._jobs_upload_dir(lpath, rpath)
else:
jobs.append(TransferJob("upload", lpath, rpath, size=size, nome=nome))
winscp._esegui_jobs(jobs)
ev.acceptProposedAction()
def _trova_winscp(self):
p = self.parent()
while p:
if hasattr(p, '_esegui_jobs'):
return p
p = p.parent() if hasattr(p, 'parent') else None
return None
def vai_home(self):
try:
home = self._sftp.normalize(".")
self.naviga(home)
except Exception:
pass
def naviga(self, path: str):
try:
self._sftp.chdir(path)
self.path = self._sftp.getcwd() or path
except Exception:
self.path = path
self.edit_path.setText(self.path)
voci = [{"nome": "..", "is_dir": True,
"path": str(Path(self.path).parent), "size": 0, "mtime": "", "attr": ""}]
try:
entries = self._sftp.listdir_attr(self.path)
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 ""
attr = self._fmt_attr(e.st_mode)
voci.append({
"nome": e.filename,
"is_dir": stat.S_ISDIR(e.st_mode),
"path": self.path.rstrip("/") + "/" + e.filename,
"size": e.st_size or 0,
"mtime": mtime,
"attr": attr,
})
except Exception as e:
self.lbl_status.setText(f" ✖ {e}")
self._popola(voci)
self.navigato.emit(self.path)
@staticmethod
def _fmt_attr(mode) -> str:
chars = ""
for who in [(0o400, 0o200, 0o100), (0o040, 0o020, 0o010), (0o004, 0o002, 0o001)]:
chars += "r" if mode & who[0] else "-"
chars += "w" if mode & who[1] else "-"
chars += "x" if mode & who[2] else "-"
return chars
def _menu_contestuale(self, pos):
sel = self.selezione()
menu = QMenu(self)
menu.setStyleSheet(
"QMenu { background:#ffffff; color:#111111; border:1px solid #ccc; }"
"QMenu::item:selected { background:#4e7abc; color:#fff; }"
)
if sel:
menu.addAction(t("winscp.ctx_dl_local").format(n=len(sel)),
lambda: self.parent().parent()._download_selezione())
menu.addSeparator()
menu.addAction(t("winscp.new_folder"), self._nuova_cartella_remota)
if sel:
menu.addAction(t("winscp.ctx_rename"), lambda: self._rinomina(sel[0]))
menu.addAction(t("winscp.ctx_delete"), lambda: self._elimina(sel))
menu.addSeparator()
menu.addAction(t("winscp.ctx_refresh"), self.aggiorna)
menu.exec(self.tabella.mapToGlobal(pos))
def _nuova_cartella_remota(self):
nome, ok = QInputDialog.getText(self, t("winscp.new_folder"), t("winscp.field_name"))
if ok and nome:
try:
self._sftp.mkdir(self.path.rstrip("/") + "/" + nome)
self.aggiorna()
except Exception as e:
QMessageBox.critical(self, t("winscp.err_generic2"), str(e))
def _rinomina(self, v):
nuovo, ok = QInputDialog.getText(self, t("winscp.rename"), t("winscp.dlg_rename_input"), text=v["nome"])
if ok and nuovo and nuovo != v["nome"]:
src = v["path"]
dst = self.path.rstrip("/") + "/" + nuovo
try:
self._sftp.rename(src, dst)
self.aggiorna()
except Exception as e:
QMessageBox.critical(self, t("winscp.err_rename"), str(e))
def _elimina(self, sel):
nomi = ", ".join(v["nome"] for v in sel)
if QMessageBox.question(self, t("winscp.dlg_delete_remote"), t("winscp.dlg_delete_confirm").format(names=nomi)) \
!= QMessageBox.StandardButton.Yes:
return
for v in sel:
try:
if v["is_dir"]:
self._rmdir_ricorsivo(v["path"])
else:
self._sftp.remove(v["path"])
except Exception as e:
QMessageBox.critical(self, t("winscp.err_generic2"), str(e))
self.aggiorna()
def _rmdir_ricorsivo(self, path):
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)
# ============================================================================
# Coda trasferimenti
# ============================================================================
class CodaWidget(QWidget):
"""Tabella in basso con la coda dei trasferimenti."""
COLONNE = ["", t("winscp.col_operation"), t("winscp.col_src"), t("winscp.col_dst"),
t("winscp.col_transferred"), t("winscp.col_time_speed"), t("winscp.col_progress")]
def __init__(self, parent=None):
super().__init__(parent)
self._jobs = []
self._jobs_in_attesa: list[TransferJob] = [] # accodati, non ancora avviati
self._init_ui()
def _init_ui(self):
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
hdr = QLabel(f" {t('winscp.queue_title')}")
hdr.setFixedHeight(22)
hdr.setStyleSheet(
"background:#f0f0f0; color:#555555; font-size:11px; "
"padding:0 6px; border-top:1px solid #ccc; border-bottom:1px solid #ccc;"
)
layout.addWidget(hdr)
self.tabella = QTableWidget(0, len(self.COLONNE))
self.tabella.setHorizontalHeaderLabels(self.COLONNE)
self.tabella.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
self.tabella.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)
self.tabella.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
self.tabella.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch)
self.tabella.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeMode.ResizeToContents)
self.tabella.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeMode.ResizeToContents)
self.tabella.horizontalHeader().setSectionResizeMode(6, QHeaderView.ResizeMode.ResizeToContents)
self.tabella.verticalHeader().setVisible(False)
self.tabella.verticalHeader().setDefaultSectionSize(20)
self.tabella.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
self.tabella.setStyleSheet(
"QTableWidget { background:#ffffff; color:#333333; gridline-color:#dddddd; "
"border:none; font-size:11px; }"
"QTableWidget::item:selected { background:#4e7abc; color:#fff; }"
"QHeaderView::section { background:#e8e8e8; color:#333333; "
"border:1px solid #ccc; padding:2px; font-size:10px; }"
)
self.tabella.setMaximumHeight(160)
layout.addWidget(self.tabella)
def aggiungi_job(self, job: TransferJob) -> int:
self._jobs.append(job)
r = self.tabella.rowCount()
self.tabella.insertRow(r)
icona = "⬆" if job.op == "upload" else "⬇"
self.tabella.setItem(r, 0, QTableWidgetItem(icona))
self.tabella.setItem(r, 1, QTableWidgetItem(job.op.capitalize()))
self.tabella.setItem(r, 2, QTableWidgetItem(job.src))
self.tabella.setItem(r, 3, QTableWidgetItem(job.dst))
self.tabella.setItem(r, 4, QTableWidgetItem("—"))
self.tabella.setItem(r, 5, QTableWidgetItem(t("winscp.status_wait_lbl")))
bar = QProgressBar()
bar.setRange(0, 100)
bar.setValue(0)
bar.setTextVisible(True)
bar.setStyleSheet(
"QProgressBar { border:1px solid #ccc; border-radius:2px; "
"background:#f0f0f0; color:#111; text-align:center; font-size:10px; }"
"QProgressBar::chunk { background:#4e7abc; }"
)
self.tabella.setCellWidget(r, 6, bar)
return r
def aggiorna_progress(self, idx: int, tx: int, tot: int):
if idx >= self.tabella.rowCount():
return
pct = int(tx * 100 / tot) if tot > 0 else 0
bar = self.tabella.cellWidget(idx, 6)
if bar:
bar.setValue(pct)
self.tabella.item(idx, 4).setText(_fmt_size(tx))
job = self._jobs[idx] if idx < len(self._jobs) else None
if job and job.velocita > 0:
eta = int((tot - tx) / job.velocita) if tot > tx else 0
vel = _fmt_size(job.velocita) + "/s"
self.tabella.item(idx, 5).setText(f"{vel} ETA {eta}s")
def segna_completato(self, idx: int, ok: bool, msg: str):
if idx >= self.tabella.rowCount():
return
bar = self.tabella.cellWidget(idx, 6)
if bar:
bar.setValue(100 if ok else bar.value())
if ok:
bar.setStyleSheet(bar.styleSheet().replace("#4e7abc", "#2d7a2d"))
else:
bar.setStyleSheet(bar.styleSheet().replace("#4e7abc", "#7a2d2d"))
stato = "✔ " + t("winscp.status_done") if ok else f"✖ {msg}"
self.tabella.item(idx, 5).setText(stato)
def aggiungi_in_attesa(self, job: TransferJob) -> int:
"""Aggiunge il job alla coda visuale in stato 'In attesa' senza avviarlo."""
self._jobs_in_attesa.append(job)
r = self.aggiungi_job(job)
job._coda_idx = r # salva indice nel job per recuperarlo in _esegui_jobs
# Evidenzia in grigio chiaro per distinguerlo da quelli in esecuzione
for col in range(len(self.COLONNE) - 1):
item = self.tabella.item(r, col)
if item:
item.setForeground(QColor("#888888"))
return r
def prendi_jobs_in_attesa(self) -> list:
"""Restituisce e svuota la lista dei job accodati in attesa."""
jobs = list(self._jobs_in_attesa)
self._jobs_in_attesa.clear()
return jobs
def n_in_attesa(self) -> int:
return len(self._jobs_in_attesa)
def pulisci(self):
self.tabella.setRowCount(0)
self._jobs.clear()
self._jobs_in_attesa.clear()
# ============================================================================
# Finestra WinSCP principale
# ============================================================================
class WinScpWidget(QWidget):
"""
Finestra SFTP completa stile WinSCP.
Da usare come tab nell'area principale di PCM.
"""
def __init__(self, ssh_client, sftp_client, host="", user="", parent=None):
super().__init__(parent)
self._ssh = ssh_client
self._sftp = sftp_client
self._host = host
self._user = user
self._transfer_thread = None
self._worker = None
self._job_indices = {} # job_locale_idx -> riga coda
self._init_ui()
# ------------------------------------------------------------------
# UI
# ------------------------------------------------------------------
def _init_ui(self):
root = QVBoxLayout(self)
root.setContentsMargins(0, 0, 0, 0)
root.setSpacing(0)
# ---- 1) Pannelli (referenziati dalla toolbar) ----
self.panel_locale = LocalPanel(self)
self.panel_remoto = RemotePanel(self._sftp, self)
splitter = QSplitter(Qt.Orientation.Horizontal)
splitter.setHandleWidth(4)
splitter.setStyleSheet("QSplitter::handle { background:#cccccc; }")
splitter.addWidget(self.panel_locale)
splitter.addWidget(self.panel_remoto)
splitter.setSizes([500, 500])
# ---- 2) Coda (referenziata dalla toolbar) ----
self.coda = CodaWidget(self)
# ---- 3) Status bar (referenziata dalla toolbar) ----
self.lbl_globale = QLabel(
f" 🔐 Connesso: {self._user}@{self._host} (SFTP)"
)
self.lbl_globale.setFixedHeight(18)
self.lbl_globale.setStyleSheet(
"background:#f0f0f0; color:#4e7abc; font-size:11px; "
"padding:0 6px; border-top:1px solid #ccc;"
)