Repository navigation
Expand file tree
/
Copy pathfolderitemwidget.cpp
More file actions
1111 lines (1003 loc) · 35.9 KB
/
Copy pathfolderitemwidget.cpp
File metadata and controls
1111 lines (1003 loc) · 35.9 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
#include "folderitemwidget.h"
#ifdef WIN32
#pragma execution_character_set("utf-8")
#endif
#include <QAction>
#include <QComboBox>
#include <QCursor>
#include <QDir>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QFileDialog>
#include <QFileInfo>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QKeyEvent>
#include <QLabel>
#include <QLineEdit>
#include <QMenu>
#include <QMimeData>
#include <QMouseEvent>
#include <QPushButton>
#include <QResizeEvent>
#include <QSettings>
#include <QSignalBlocker>
#include <QTimer>
#include <QTreeWidget>
#include <QUrl>
#include <QVBoxLayout>
#include "components/confirmdialog.h"
#include "components/transferpanel.h"
#include "sftpclient.h"
#include "components/messagedialog.h"
namespace {
const char kTransferProtocolKey[] = "fileManager/transferProtocol";
// 速率标签:每 500ms 检查一次“是否还在动”,1.5 秒没有新样本就认为卡住。
const int kSpeedRefreshMs = 500;
const int kStallTimeoutMs = 1500;
QIcon iconForFile(int fileType, int targetFileType) {
if (fileType == RemoteFileDirectory ||
(fileType == RemoteFileSymlink &&
targetFileType == RemoteFileDirectory)) {
return QIcon(QStringLiteral(":/icons/folder.png"));
}
return QIcon(QStringLiteral(":/icons/file.png"));
}
QString fileTypeText(int fileType) {
switch (fileType) {
case RemoteFileDirectory:
return QObject::tr("目录");
case RemoteFileRegular:
return QObject::tr("文件");
case RemoteFileSymlink:
return QObject::tr("符号链接");
case RemoteFileFifo:
return QObject::tr("管道");
case RemoteFileSocket:
return QObject::tr("套接字");
case RemoteFileCharDevice:
return QObject::tr("字符设备");
case RemoteFileBlockDevice:
return QObject::tr("块设备");
default:
return QObject::tr("未知");
}
}
bool isNavigableDirectory(const FileInfo_S &info) {
return info.fileType == RemoteFileDirectory ||
(info.fileType == RemoteFileSymlink &&
info.targetFileType == RemoteFileDirectory);
}
} // namespace
FolderItemWidget::FolderItemWidget(QWidget *parent, SFTPClient *client)
: QWidget(parent), sftpClient(client) {
setAcceptDrops(true);
initUi();
connectClient();
}
FolderItemWidget::~FolderItemWidget() = default;
void FolderItemWidget::initUi() {
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
QHBoxLayout *titleLayout = new QHBoxLayout;
returnButton = new QPushButton(tr("返回上一级"), this);
returnButton->setFixedHeight(30);
connect(returnButton, &QPushButton::clicked, this,
[this]() { navigateTo(parentRemotePath(currentDirPath)); });
titleLayout->addWidget(returnButton);
currentDirEdit = new QLineEdit(this);
currentDirEdit->setFixedHeight(30);
connect(currentDirEdit, &QLineEdit::returnPressed, this,
&FolderItemWidget::jumpDir);
titleLayout->addWidget(currentDirEdit);
gotoButton = new QPushButton(tr("跳转"), this);
gotoButton->setFixedHeight(30);
gotoButton->setDefault(true);
connect(gotoButton, &QPushButton::clicked, this, &FolderItemWidget::jumpDir);
titleLayout->addWidget(gotoButton);
protocolLabel_ = new QLabel(tr("传输方式"), this);
titleLayout->addWidget(protocolLabel_);
protocolCombo_ = new QComboBox(this);
protocolCombo_->setObjectName(QStringLiteral("transferProtocolCombo"));
protocolCombo_->setFixedHeight(30);
protocolCombo_->addItem(tr("SFTP"), QStringLiteral("sftp"));
protocolCombo_->addItem(tr("SCP"), QStringLiteral("scp"));
const QString savedProtocol =
QSettings().value(QLatin1String(kTransferProtocolKey),
QStringLiteral("sftp")).toString();
transferProtocol_ = savedProtocol.compare(QStringLiteral("scp"),
Qt::CaseInsensitive) == 0
? TransferProtocol::Scp
: TransferProtocol::Sftp;
protocolCombo_->setCurrentIndex(transferProtocol_ == TransferProtocol::Scp
? 1
: 0);
protocolCombo_->setToolTip(
tr("SFTP:通过 SFTP 子系统传输,功能完整;SCP:调用远端 scp 命令,"
"仅支持单个文件"));
connect(protocolCombo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, [this](int index) {
transferProtocol_ = index == 1 ? TransferProtocol::Scp
: TransferProtocol::Sftp;
QSettings().setValue(
QLatin1String(kTransferProtocolKey),
transferProtocol_ == TransferProtocol::Scp
? QStringLiteral("scp")
: QStringLiteral("sftp"));
});
titleLayout->addWidget(protocolCombo_);
transferToggleButton = new QPushButton(tr("传输队列"), this);
transferToggleButton->setObjectName(QStringLiteral("transferToggleButton"));
transferToggleButton->setCheckable(true);
transferToggleButton->setFixedHeight(30);
transferToggleButton->setIcon(
QIcon(QStringLiteral(":/icons/chevron-up.png")));
transferToggleButton->setIconSize(QSize(14, 14));
transferToggleButton->setToolTip(tr("显示底部的传输队列"));
connect(transferToggleButton, &QPushButton::toggled, this,
&FolderItemWidget::setTransferPanelVisible);
titleLayout->addWidget(transferToggleButton);
layout->addLayout(titleLayout);
treeView = new QTreeWidget(this);
treeView->setColumnCount(ColumnCount);
treeView->setHeaderLabels(QStringList() << tr("文件名") << tr("大小")
<< tr("目录/链接个数") << tr("类型")
<< tr("权限") << tr("用户/用户组")
<< tr("父路径") << tr("修改时间"));
treeView->hideColumn(PathColumn);
treeView->setColumnWidth(NameColumn, 240);
treeView->setColumnWidth(SizeColumn, 90);
treeView->setColumnWidth(LinkCountColumn, 100);
treeView->setColumnWidth(TypeColumn, 90);
treeView->setColumnWidth(PermissionColumn, 110);
treeView->setColumnWidth(OwnerColumn, 140);
treeView->setColumnWidth(ModifiedColumn, 160);
treeView->setRootIsDecorated(false);
treeView->setSortingEnabled(true);
treeView->sortByColumn(NameColumn, Qt::AscendingOrder);
treeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
treeView->setContextMenuPolicy(Qt::CustomContextMenu);
treeView->installEventFilter(this);
treeView->setIconSize(QSize(18, 18));
QFont font;
font.setPointSize(10);
treeView->setFont(font);
connect(treeView, &QTreeWidget::itemDoubleClicked, this,
[this](QTreeWidgetItem *item, int) {
if (!item) {
return;
}
const FileInfo_S info =
item->data(NameColumn, Qt::UserRole + 1).value<FileInfo_S>();
if (isNavigableDirectory(info)) {
navigateTo(info.filePath);
}
});
connect(treeView, &QTreeWidget::customContextMenuRequested, this,
&FolderItemWidget::popMenu);
layout->addWidget(treeView, 1);
// 传输面板嵌在文件列表下方:默认收起,有任务时从底部滑出。
transferPanel = new TransferPanel(this);
transferPanel->setExpanded(false, false);
layout->addWidget(transferPanel);
connect(transferPanel, &TransferPanel::addFilesRequested, this,
&FolderItemWidget::chooseFilesAndUpload);
connect(transferPanel, &TransferPanel::startRequested, this,
&FolderItemWidget::startPendingUploads);
connect(transferPanel, &TransferPanel::cancelRequested, this,
&FolderItemWidget::cancelActiveTransfer);
connect(transferPanel, &TransferPanel::clearRequested, this,
&FolderItemWidget::clearTasks);
connect(transferPanel, &TransferPanel::collapseRequested, this,
[this]() { setTransferPanelVisible(false); });
speedWatchdog = new QTimer(this);
speedWatchdog->setInterval(kSpeedRefreshMs);
connect(speedWatchdog, &QTimer::timeout, this, [this]() {
if (!transferInProgress || !lastSampleClock.isValid()) {
return;
}
// 超过 kStallTimeoutMs 没有新样本说明传输卡住了,别把旧速率一直挂着。
if (lastSampleClock.elapsed() >= kStallTimeoutMs && lastRate != 0) {
lastRate = 0;
updateSpeedLabel();
}
});
setLayout(layout);
updateToolbarForWidth();
confirmDialog = new ConfirmDialog(this);
connect(confirmDialog, &ConfirmDialog::confirmEditEvent, this,
[this](QString input) {
const FileOption option = fileOption;
fileOption = FileOption::DEFAULT;
const QString newName = input.trimmed();
if (newName.isEmpty() || newName.contains(QLatin1Char('/')) ||
newName == QLatin1String(".") ||
newName == QLatin1String("..")) {
MessageDialog::warning(
this, tr("提示"), tr("文件名不能为空,且不能包含 /"));
return;
}
if (option == FileOption::RENAME) {
QTreeWidgetItem *item = treeView->currentItem();
if (!item) {
return;
}
FileInfo_S info =
item->data(NameColumn, Qt::UserRole + 1).value<FileInfo_S>();
if (newName == info.fileName) {
return;
}
const QString targetPath =
joinRemotePath(parentRemotePath(info.filePath), newName);
if (!sftpClient->rename(info.filePath, targetPath)) {
return;
}
info.fileName = newName;
info.filePath = targetPath;
item->setText(NameColumn, newName);
item->setText(PathColumn, targetPath);
item->setToolTip(NameColumn, targetPath);
item->setData(NameColumn, Qt::UserRole + 1,
QVariant::fromValue(info));
if (treeView->isSortingEnabled()) {
treeView->sortItems(
treeView->header()->sortIndicatorSection(),
treeView->header()->sortIndicatorOrder());
}
} else if (option == FileOption::MKDIR) {
if (sftpClient->mkdir(joinRemotePath(currentDirPath, newName))) {
refresh();
}
}
});
}
void FolderItemWidget::connectClient() {
connect(sftpClient, &SFTPClient::directoryLoaded, this,
&FolderItemWidget::onDirectoryLoaded);
connect(sftpClient, &SFTPClient::directoryLoadFailed, this,
[this](const QString &dirPath, const QString &message) {
if (normalizeRemotePath(dirPath) != currentDirPath) {
return;
}
// 下次成功加载同一目录时仍要通知左侧目录树,避免失败后
// 再跳回该目录时选中状态不恢复。
notifiedDirPath.clear();
MessageDialog::warning(this, tr("错误"), message);
});
connect(sftpClient, &SFTPClient::fileUploadProgress, this,
[this](qint64 totalSize, qint64 currentSize, qint64 bytesPerSecond) {
updateProgress(totalSize, currentSize, bytesPerSecond);
});
connect(sftpClient, &SFTPClient::fileUploadSuccess, this, [this]() {
completeActiveTask(TransferDone, QString());
finishBatch();
});
connect(sftpClient, &SFTPClient::fileUploadFailed, this,
[this](const QString &message) {
// 用户主动取消不是错误:不算失败,也不再弹失败框。
const bool cancelled =
cancelRequested ||
message == SFTPClient::transferCancelledMessage();
if (cancelled) {
completeActiveTask(TransferCancelled, QString());
markPendingCancelled();
} else {
completeActiveTask(TransferFailed, message);
// 只跳过这一个文件,队列里的其余文件继续传。
}
finishBatch();
});
connect(sftpClient, &SFTPClient::fileDownloadProgress, this,
[this](qint64 totalSize, qint64 currentSize, qint64 bytesPerSecond) {
updateProgress(totalSize, currentSize, bytesPerSecond);
});
connect(sftpClient, &SFTPClient::fileDownloadSuccess, this, [this]() {
completeActiveTask(TransferDone, QString());
finishBatch();
});
connect(sftpClient, &SFTPClient::fileDownloadFailed, this,
[this](const QString &message) {
const bool cancelled =
cancelRequested ||
message == SFTPClient::transferCancelledMessage();
if (cancelled) {
completeActiveTask(TransferCancelled, QString());
markPendingCancelled();
} else {
completeActiveTask(TransferFailed, message);
}
finishBatch();
});
connect(sftpClient, &SFTPClient::disconnected, this, [this]() {
// 连接已断开,工作线程不会再有响应:把未完成的任务标红,别让界面
// 一直停在“传输中”。
if (activeTask >= 0 && activeTask < transferTasks.size() &&
transferTasks.at(activeTask).state == TransferRunning) {
completeActiveTask(TransferFailed, tr("连接已断开"));
}
for (int i = 0; i < transferTasks.size(); ++i) {
if (transferTasks.at(i).state == TransferPending) {
transferTasks[i].state = TransferFailed;
transferTasks[i].message = tr("连接已断开");
updateTaskRow(i);
}
}
activeTask = -1;
transferInProgress = false;
setTransferBusy(false);
setEnabled(false);
});
}
void FolderItemWidget::navigateTo(const QString &dirPath) {
const QString normalized = normalizeRemotePath(dirPath);
currentDirPath = normalized;
currentDirEdit->setText(normalized);
treeView->clear();
sftpClient->asyncOpendir(normalized);
}
void FolderItemWidget::refresh() {
sftpClient->asyncOpendir(currentDirPath);
}
void FolderItemWidget::jumpDir() {
navigateTo(currentDirEdit->text());
}
void FolderItemWidget::setTransferPanelVisible(bool visible) {
if (!transferPanel) {
return;
}
transferPanel->setExpanded(visible);
// 面板也可能由任务入队、清空等操作自动展开/收起,这里同步工具栏开关。
if (transferToggleButton) {
transferToggleButton->setIcon(QIcon(
visible ? QStringLiteral(":/icons/chevron-down.png")
: QStringLiteral(":/icons/chevron-up.png")));
transferToggleButton->setToolTip(
visible ? tr("隐藏底部的传输队列") : tr("显示底部的传输队列"));
if (transferToggleButton->isChecked() != visible) {
const QSignalBlocker blocker(transferToggleButton);
transferToggleButton->setChecked(visible);
}
}
}
void FolderItemWidget::updateToolbarForWidth() {
if (!transferToggleButton) {
return;
}
// SSH 会话里的文件面板允许拖到 400px 宽:放不下完整按钮时只留图标,
// 并隐藏“传输方式”文字标签,给路径输入框腾出空间。
const bool compact = width() < 560;
transferToggleButton->setText(compact ? QString() : tr("传输队列"));
if (compact) {
transferToggleButton->setFixedWidth(36);
} else {
transferToggleButton->setMinimumWidth(0);
transferToggleButton->setMaximumWidth(QWIDGETSIZE_MAX);
}
if (protocolLabel_) {
// 阈值要略高于隐藏标签后的最小宽度,否则窗口收缩不到阈值以下。
protocolLabel_->setVisible(width() >= 520);
}
}
void FolderItemWidget::resetTransferState() {
transferTasks.clear();
activeTask = -1;
batchArmed = false;
lastRate = -1;
if (transferPanel) {
transferPanel->clearRows();
transferPanel->setOverallProgress(0, 0);
transferPanel->clearSpeed();
}
updateStartButton();
}
void FolderItemWidget::cancelActiveTransfer() {
if (!transferInProgress || cancelRequested) {
return;
}
cancelRequested = true;
if (transferPanel) {
transferPanel->setCancelPending(true);
}
sftpClient->cancelTransfer();
}
void FolderItemWidget::startPendingUploads() {
if (transferInProgress || !hasPendingTask()) {
return;
}
batchArmed = true;
if (startNextPendingTask() < 0) {
batchArmed = false; // 起不动(会话未就绪等),别卡在“已开始”
}
updateStartButton();
}
bool FolderItemWidget::hasPendingTask() const {
for (const TransferTask &task : transferTasks) {
if (task.state == TransferPending) {
return true;
}
}
return false;
}
void FolderItemWidget::updateStartButton() {
if (transferPanel) {
transferPanel->setStartEnabled(!transferInProgress && hasPendingTask());
}
}
void FolderItemWidget::setTransferBusy(bool busy) {
// 传输期间禁用目录树等操作:删除/新建走的是阻塞式调用,会和正在传输的
// 工作线程抢同一个 libssh2 会话。传输面板里的“添加文件”仍然可用。
treeView->setEnabled(!busy);
returnButton->setEnabled(!busy);
gotoButton->setEnabled(!busy);
currentDirEdit->setEnabled(!busy);
protocolCombo_->setEnabled(!busy);
if (!busy) {
endTransfer();
}
if (transferPanel) {
transferPanel->setTransferring(busy);
}
}
void FolderItemWidget::beginTransfer(bool upload) {
progressIsUpload = upload;
cancelRequested = false;
lastRate = -1;
lastSampleClock.invalidate();
if (transferPanel) {
transferPanel->setCancelPending(false);
}
updateSpeedLabel();
speedWatchdog->start();
}
void FolderItemWidget::endTransfer() {
speedWatchdog->stop();
cancelRequested = false;
lastRate = -1;
lastSampleClock.invalidate();
if (transferPanel) {
transferPanel->clearSpeed();
}
}
void FolderItemWidget::updateSpeedLabel() {
if (!transferPanel) {
return;
}
if (!transferInProgress) {
transferPanel->clearSpeed();
return;
}
transferPanel->setSpeed(lastRate, lastRate >= 0, progressIsUpload);
}
TransferItem FolderItemWidget::toTransferItem(const TransferTask &task) const {
TransferItem item;
item.upload = task.upload;
item.name = task.name;
item.totalSize = task.totalSize;
item.doneSize = task.doneSize;
item.message = task.message;
switch (task.state) {
case TransferRunning:
item.state = TransferItem::Running;
break;
case TransferDone:
item.state = TransferItem::Done;
break;
case TransferFailed:
item.state = TransferItem::Failed;
break;
case TransferCancelled:
item.state = TransferItem::Cancelled;
break;
case TransferPending:
default:
item.state = TransferItem::Pending;
break;
}
return item;
}
void FolderItemWidget::appendTask(const TransferTask &task) {
transferTasks.append(task);
transferPanel->appendRow(toTransferItem(transferTasks.last()));
updateStartButton();
// 有新任务时自动从底部滑出,用户手动收起后下次入队仍会再显示。
setTransferPanelVisible(true);
}
void FolderItemWidget::updateTaskRow(int index) {
if (!transferPanel || index < 0 || index >= transferTasks.size()) {
return;
}
transferPanel->updateRow(index, toTransferItem(transferTasks.at(index)));
}
void FolderItemWidget::updateOverallProgress() {
// 总进度按字节算:已完成任务计满,正在传的按已传字节,排队的不计。
// 大小未知(0)的任务不参与,避免把总进度拉偏。
qint64 total = 0;
qint64 done = 0;
for (const TransferTask &task : transferTasks) {
if (task.totalSize <= 0) {
continue;
}
total += task.totalSize;
done += (task.state == TransferDone) ? task.totalSize : task.doneSize;
}
if (transferPanel) {
transferPanel->setOverallProgress(done, total);
}
}
int FolderItemWidget::startNextPendingTask() {
int index = -1;
for (int i = 0; i < transferTasks.size(); ++i) {
if (transferTasks.at(i).state == TransferPending) {
index = i;
break;
}
}
if (index < 0) {
return -1;
}
if (!sftpClient->isReady()) {
// 会话没了:剩下的任务直接判失败,不要再一个个试。
for (int i = 0; i < transferTasks.size(); ++i) {
if (transferTasks.at(i).state == TransferPending) {
transferTasks[i].state = TransferFailed;
transferTasks[i].message = tr("SFTP 会话未就绪");
updateTaskRow(i);
}
}
return -1;
}
startTask(index);
return index;
}
void FolderItemWidget::startTask(int index) {
if (index < 0 || index >= transferTasks.size()) {
return;
}
TransferTask &task = transferTasks[index];
task.state = TransferRunning;
task.doneSize = 0;
task.message.clear();
activeTask = index;
transferInProgress = true;
cancelRequested = false;
updateTaskRow(index);
setTransferBusy(true);
beginTransfer(task.upload);
updateOverallProgress();
// 路径先拷出来:下面调用不会改 transferTasks,但避免长引用跨调用。
const QString localPath = task.localPath;
const QString remotePath = task.remotePath;
if (task.upload) {
if (transferProtocol_ == TransferProtocol::Scp) {
sftpClient->asyncScpUpload(localPath, remotePath);
} else {
sftpClient->asyncSftpUpload(localPath, remotePath);
}
return;
}
if (transferProtocol_ == TransferProtocol::Scp) {
sftpClient->asyncScpDownload(remotePath, localPath);
} else {
sftpClient->asyncSftpDownload(remotePath, localPath);
}
updateStartButton();
}
void FolderItemWidget::completeActiveTask(TransferState state,
const QString &message) {
if (activeTask < 0 || activeTask >= transferTasks.size()) {
return;
}
const int index = activeTask;
activeTask = -1;
TransferTask &task = transferTasks[index];
task.state = state;
if (state == TransferDone && task.totalSize > 0) {
task.doneSize = task.totalSize;
}
task.message = message;
transferInProgress = false;
updateTaskRow(index);
updateOverallProgress();
endTransfer();
updateStartButton();
}
void FolderItemWidget::finishBatch() {
// 只有被“开始上传”放行过的批次才会自动接着传下一个;否则文件停在等待状态。
if (batchArmed && startNextPendingTask() >= 0) {
return;
}
batchArmed = false;
transferInProgress = false;
activeTask = -1;
setTransferBusy(false);
updateOverallProgress();
updateStartButton();
refresh();
int done = 0;
int failed = 0;
int cancelled = 0;
QStringList failedNames;
for (const TransferTask &task : transferTasks) {
if (task.state == TransferDone) {
++done;
} else if (task.state == TransferFailed) {
++failed;
failedNames << task.name;
} else if (task.state == TransferCancelled) {
++cancelled;
}
}
// 用户主动取消不是错误:列表里已经标了“已取消”,不再弹框。
if (cancelled > 0 && failed == 0) {
return;
}
if (failed > 0) {
MessageDialog::warning(
this, tr("传输完成,但部分文件失败"),
tr("成功 %1 个,失败 %2 个:\n%3")
.arg(done)
.arg(failed)
.arg(failedNames.join(QLatin1Char('\n'))));
} else if (done > 0) {
MessageDialog::success(this, tr("提示"),
tr("传输完成(%1 个文件)").arg(done));
}
}
void FolderItemWidget::markPendingCancelled() {
for (int i = 0; i < transferTasks.size(); ++i) {
if (transferTasks.at(i).state == TransferPending) {
transferTasks[i].state = TransferCancelled;
updateTaskRow(i);
}
}
updateStartButton();
}
void FolderItemWidget::clearTasks() {
if (transferInProgress) {
return; // 传输中不清,避免任务和列表行的下标错位
}
resetTransferState();
// 用户点“清空”时连面板一起收回到文件列表下方。
setTransferPanelVisible(false);
}
void FolderItemWidget::updateProgress(qint64 totalSize, qint64 currentSize,
qint64 bytesPerSecond) {
if (activeTask >= 0 && activeTask < transferTasks.size()) {
TransferTask &task = transferTasks[activeTask];
if (totalSize > 0) {
task.totalSize = totalSize;
}
task.doneSize = currentSize;
updateTaskRow(activeTask);
updateOverallProgress();
}
lastRate = bytesPerSecond;
lastSampleClock.restart();
updateSpeedLabel();
}
void FolderItemWidget::onDirectoryLoaded(
const QString &dirPath, const QList<FileInfo_S> &entries) {
const QString normalized = normalizeRemotePath(dirPath);
// 快速切换目录时,丢弃已经过期的请求结果,避免旧目录内容混入新目录。
if (normalized != currentDirPath) {
return;
}
currentDirEdit->setText(normalized);
treeView->setSortingEnabled(false);
treeView->clear();
for (const FileInfo_S &info : entries) {
createFileItem(treeView->invisibleRootItem(), info);
}
treeView->setSortingEnabled(true);
treeView->sortItems(treeView->header()->sortIndicatorSection(),
treeView->header()->sortIndicatorOrder());
// 刷新同一目录时不重复通知,避免左侧目录树把用户刚收起的节点又展开。
if (normalized != notifiedDirPath) {
notifiedDirPath = normalized;
emit directoryChanged(normalized);
}
}
QTreeWidgetItem *FolderItemWidget::createFileItem(QTreeWidgetItem *parent,
const FileInfo_S &info) {
if (!parent) {
return nullptr;
}
QTreeWidgetItem *item = new QTreeWidgetItem(parent);
item->setText(NameColumn, info.fileName);
item->setToolTip(NameColumn, info.filePath);
item->setIcon(NameColumn, iconForFile(info.fileType, info.targetFileType));
item->setText(SizeColumn, info.fileType == RemoteFileDirectory
? QStringLiteral("-")
: formatFileSize(info.fileSize));
item->setText(LinkCountColumn, info.fileNum);
item->setText(TypeColumn, fileTypeText(info.fileType));
item->setText(PermissionColumn, info.permission.isEmpty()
? QStringLiteral("-")
: info.permission);
item->setText(OwnerColumn, info.userOrGroup.isEmpty()
? QStringLiteral("-")
: info.userOrGroup);
item->setText(PathColumn, info.filePath);
item->setText(ModifiedColumn, info.updateTime.isEmpty()
? QStringLiteral("-")
: info.updateTime);
item->setData(NameColumn, Qt::UserRole + 1, QVariant::fromValue(info));
return item;
}
void FolderItemWidget::popMenu(const QPoint &position) {
QTreeWidgetItem *clicked = treeView->itemAt(position);
if (clicked && !clicked->isSelected()) {
treeView->clearSelection();
clicked->setSelected(true);
treeView->setCurrentItem(clicked);
}
const QList<QTreeWidgetItem *> items = treeView->selectedItems();
QMenu menu(treeView);
if (items.size() > 1) {
QAction *deleteAction = menu.addAction(tr("删除"));
connect(deleteAction, &QAction::triggered, this,
[this, items]() { deleteItems(items); });
menu.exec(QCursor::pos());
return;
}
if (items.isEmpty()) {
QAction *refreshAction = menu.addAction(tr("刷新"));
connect(refreshAction, &QAction::triggered, this,
&FolderItemWidget::refresh);
QAction *mkdirAction = menu.addAction(tr("新建文件夹"));
connect(mkdirAction, &QAction::triggered, this,
&FolderItemWidget::createFolder);
QAction *uploadAction = menu.addAction(tr("上传文件"));
connect(uploadAction, &QAction::triggered, this,
&FolderItemWidget::chooseFilesAndUpload);
} else {
QTreeWidgetItem *item = items.first();
const FileInfo_S info =
item->data(NameColumn, Qt::UserRole + 1).value<FileInfo_S>();
QAction *renameAction = menu.addAction(tr("重命名"));
connect(renameAction, &QAction::triggered, this,
&FolderItemWidget::renameSelected);
QAction *deleteAction = menu.addAction(tr("删除"));
connect(deleteAction, &QAction::triggered, this,
[this, items]() { deleteItems(items); });
const bool isDirectory =
info.fileType == RemoteFileDirectory ||
(info.fileType == RemoteFileSymlink &&
info.targetFileType == RemoteFileDirectory);
if (!isDirectory) {
QAction *downloadAction = menu.addAction(tr("下载"));
const QString remotePath = info.filePath;
connect(downloadAction, &QAction::triggered, this,
[this, remotePath]() { fileDownload(remotePath); });
}
}
menu.exec(QCursor::pos());
}
void FolderItemWidget::createFolder() {
confirmDialog->setTitleText(tr("请输入文件夹名"));
confirmDialog->setEditText(QString());
confirmDialog->setOkButtonName(tr("新建"));
fileOption = FileOption::MKDIR;
confirmDialog->show();
}
void FolderItemWidget::renameSelected() {
const QList<QTreeWidgetItem *> items = treeView->selectedItems();
if (items.size() != 1) {
return;
}
QTreeWidgetItem *item = items.first();
treeView->setCurrentItem(item);
const FileInfo_S info =
item->data(NameColumn, Qt::UserRole + 1).value<FileInfo_S>();
confirmDialog->setTitleText(tr("请输入文件名"));
confirmDialog->setEditText(info.fileName);
confirmDialog->setOkButtonName(tr("修改"));
fileOption = FileOption::RENAME;
confirmDialog->show();
}
void FolderItemWidget::deleteSelected() {
deleteItems(treeView->selectedItems());
}
void FolderItemWidget::deleteItems(
const QList<QTreeWidgetItem *> &items) {
if (items.isEmpty() || transferInProgress) {
return;
}
QStringList names;
bool hasDirectory = false;
for (QTreeWidgetItem *item : items) {
const FileInfo_S info =
item->data(NameColumn, Qt::UserRole + 1).value<FileInfo_S>();
names << info.fileName;
if (info.fileType == RemoteFileDirectory) {
hasDirectory = true;
}
}
QString message =
tr("确定要删除以下内容吗?\n\n%1").arg(names.join(QLatin1Char('\n')));
if (hasDirectory) {
message += tr("\n\n文件夹中的内容将被递归删除。");
}
if (!MessageDialog::confirm(this, tr("删除确认"), message, tr("删除"),
tr("取消"), true)) {
return;
}
int deletedCount = 0;
QStringList failedNames;
for (QTreeWidgetItem *item : items) {
const FileInfo_S info =
item->data(NameColumn, Qt::UserRole + 1).value<FileInfo_S>();
bool succeeded = false;
if (info.fileType == RemoteFileDirectory) {
// reportError 为 false:批量删除时只汇总提示,避免弹出多个错误框。
succeeded = sftpClient->rmdir(info.filePath, false);
} else {
// 符号链接只删除链接本身,绝不递归目标目录。
succeeded = sftpClient->removeFile(info.filePath);
}
if (succeeded) {
++deletedCount;
delete item;
} else {
failedNames << info.fileName;
}
}
if (!failedNames.isEmpty()) {
MessageDialog::warning(
this, tr("删除失败"),
tr("以下项目删除失败:\n%1").arg(failedNames.join(QLatin1Char('\n'))));
} else if (deletedCount > 1) {
MessageDialog::success(this, tr("提示"),
tr("已删除 %1 项").arg(deletedCount));
}
refresh();
}
void FolderItemWidget::chooseFilesAndUpload() {
const QStringList files = QFileDialog::getOpenFileNames(
this, tr("选择文件"), QString(), tr("所有文件 (*)"), nullptr,
QFileDialog::DontUseNativeDialog);
enqueueUploads(files);
}
void FolderItemWidget::enqueueUploads(const QStringList &localPaths) {
QList<TransferTask> accepted;
QStringList skipped;
for (const QString &path : localPaths) {
const QFileInfo info(path);
if (!info.isFile()) {
skipped << info.fileName();
continue;
}
TransferTask task;
task.upload = true;
task.name = info.fileName();
task.localPath = info.absoluteFilePath();
task.remotePath = joinRemotePath(currentDirPath, info.fileName());
task.totalSize = info.size();
accepted.append(task);
}
// 空闲且队列里没有待传文件时才算“新一批”:清掉上一批记录。
// 已有排队文件时继续追加,不能把用户还没开始传的文件清掉。
if (!accepted.isEmpty() && !transferInProgress && !hasPendingTask()) {
// 新一批任务覆盖旧记录;走 reset 而不是 clearTasks,避免面板先收起再弹出。
resetTransferState();
}
for (const TransferTask &task : accepted) {
appendTask(task);
}
if (!skipped.isEmpty()) {
MessageDialog::warning(
this, tr("提示"),
tr("只支持上传文件,以下项目已跳过:\n%1")
.arg(skipped.join(QLatin1Char('\n'))));
}
// 默认不自动开始:文件停在“等待中”,由“开始上传”按钮放行。
updateStartButton();
}
void FolderItemWidget::fileDownload(const QString &remotePath) {
if (transferInProgress) {
MessageDialog::information(this, tr("提示"), tr("正在传输文件,请稍候"));
return;
}
if (!sftpClient->isReady()) {
MessageDialog::warning(this, tr("下载失败"), tr("SFTP 会话未就绪"));
return;