-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
1480 lines (1258 loc) · 59.5 KB
/
mainwindow.cpp
File metadata and controls
1480 lines (1258 loc) · 59.5 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 "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
m_showAllDevices(true) // По умолчанию показываем все устройства
{
ui->setupUi(this);
// Создаем менеджер дисков
m_diskManager = new DiskManager(this);
// Подключаем сигналы
connect(m_diskManager, &DiskManager::devicesRefreshed,
this, &MainWindow::onDevicesRefreshed);
connect(m_diskManager, &DiskManager::commandOutput,
this, &MainWindow::onCommandOutput);
connect(m_diskManager, &DiskManager::partitionTableCreated,
this, [this](bool success) {
if (success) {
ui->statusBar->showMessage(tr("Partition table created successfully"), 3000);
} else {
ui->statusBar->showMessage(tr("Failed to create partition table"), 3000);
}
});
connect(m_diskManager, &DiskManager::partitionCreated,
this, [this](bool success) {
if (success) {
ui->statusBar->showMessage(tr("Partition created successfully"), 3000);
} else {
ui->statusBar->showMessage(tr("Failed to create partition"), 3000);
}
});
connect(m_diskManager, &DiskManager::partitionDeleted,
this, [this](bool success) {
if (success) {
ui->statusBar->showMessage(tr("Partition deleted successfully"), 3000);
} else {
ui->statusBar->showMessage(tr("Failed to delete partition"), 3000);
}
});
connect(m_diskManager, &DiskManager::partitionFormatted,
this, [this](bool success) {
if (success) {
ui->statusBar->showMessage(tr("Partition formatted successfully"), 3000);
} else {
ui->statusBar->showMessage(tr("Failed to format partition"), 3000);
}
});
connect(m_diskManager, &DiskManager::deviceMounted,
this, &MainWindow::onDeviceMounted);
connect(m_diskManager, &DiskManager::deviceUnmounted,
this, &MainWindow::onDeviceUnmounted);
connect(m_diskManager, &DiskManager::raidStopProgress,
this, [this](const QString &message) {
ui->statusBar->showMessage(message, 3000);
});
connect(m_diskManager, &DiskManager::raidStopCompleted,
this, [this](bool success, const QString &raidDevice) {
if (success) {
ui->statusBar->showMessage(tr("RAID %1 stopped successfully").arg(raidDevice), 3000);
} else {
ui->statusBar->showMessage(tr("Failed to stop RAID %1").arg(raidDevice), 3000);
}
});
connect(m_diskManager, &DiskManager::raidDeletionCompleted,
this, [this](bool success, const QString &raidDevice) {
if (success) {
ui->statusBar->showMessage(tr("RAID %1 deleted successfully").arg(raidDevice), 5000);
onRefreshDevices();
} else {
ui->statusBar->showMessage(tr("Failed to delete RAID %1").arg(raidDevice), 5000);
}
});
connect(m_diskManager, &DiskManager::deviceMarkedFaulty,
this, [this](bool success, const QString &raidDevice, const QString &memberDevice) {
if (success) {
ui->statusBar->showMessage(tr("Device %1 marked as faulty in RAID %2")
.arg(memberDevice).arg(raidDevice), 5000);
onRefreshDevices();
} else {
ui->statusBar->showMessage(tr("Failed to mark device %1 as faulty")
.arg(memberDevice), 5000);
}
});
connect(m_diskManager, &DiskManager::deviceRemovedFromRaid,
this, [this](bool success, const QString &raidDevice, const QString &memberDevice) {
if (success) {
ui->statusBar->showMessage(tr("Device %1 removed from RAID %2 successfully")
.arg(memberDevice).arg(raidDevice), 5000);
onRefreshDevices();
} else {
ui->statusBar->showMessage(tr("Failed to remove device %1 from RAID %2")
.arg(memberDevice).arg(raidDevice), 5000);
}
});
connect(m_diskManager, &DiskManager::deviceAddedToRaid,
this, [this](bool success, const QString &raidDevice, const QString &memberDevice) {
if (success) {
ui->statusBar->showMessage(tr("Device %1 added to RAID %2 successfully. "
"Rebuilding/syncing started.")
.arg(memberDevice).arg(raidDevice), 5000);
onRefreshDevices();
} else {
ui->statusBar->showMessage(tr("Failed to add device %1 to RAID %2")
.arg(memberDevice).arg(raidDevice), 5000);
}
});
connect(m_diskManager, &DiskManager::spareActivationCompleted,
this, [this](bool success, const QString &raidDevice, const QString &spareDevice) {
if (success) {
ui->statusBar->showMessage(tr("Spare device %1 activated in RAID %2 successfully")
.arg(spareDevice).arg(raidDevice), 5000);
onRefreshDevices();
} else {
ui->statusBar->showMessage(tr("Failed to activate spare device %1 in RAID %2")
.arg(spareDevice).arg(raidDevice), 5000);
}
});
// Подключаем сигналы интерфейса
connect(ui->btnRefreshDevices, &QPushButton::clicked,
this, &MainWindow::onRefreshDevices);
connect(ui->actionRefresh, &QAction::triggered,
this, &MainWindow::onRefreshDevices);
connect(ui->cmbViewMode, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &MainWindow::onViewModeChanged);
connect(ui->actionCreatePartitionTable, &QAction::triggered,
this, &MainWindow::onCreatePartitionTableClicked);
connect(ui->actionCreatePartition, &QAction::triggered,
this, &MainWindow::onCreatePartitionClicked);
connect(ui->actionDeletePartition, &QAction::triggered,
this, &MainWindow::onDeletePartitionClicked);
connect(ui->actionFormatPartition, &QAction::triggered,
this, &MainWindow::onFormatPartitionClicked);
connect(ui->actionMountPartition, &QAction::triggered,
this, &MainWindow::onMountPartitionClicked);
connect(ui->actionUnmountPartition, &QAction::triggered,
this, &MainWindow::onUnmountPartitionClicked);
connect(ui->actionCreateRaid, &QAction::triggered,
this, &MainWindow::onCreateRaidClicked);
connect(ui->actionDestroyRaid, &QAction::triggered,
this, &MainWindow::onDeleteRaidClicked);
// Подключаем кнопки управления RAID
connect(ui->btnMarkFaulty, &QPushButton::clicked,
this, &MainWindow::onMarkFaultyClicked);
connect(ui->btnAddToRaid, &QPushButton::clicked,
this, &MainWindow::onAddToRaidClicked);
connect(ui->btnRemoveFromRaid, &QPushButton::clicked,
this, &MainWindow::onRemoveFromRaidClicked);
connect(ui->btnActivateSpare, &QPushButton::clicked,
this, &MainWindow::onActivateSpareClicked);
// Подключаем сигнал изменения выбора в дереве для обновления кнопок
connect(ui->treeDevices, &QTreeWidget::currentItemChanged,
this, &MainWindow::updateButtonState);
// Настраиваем интерфейс
setupInitialInterface();
// Обновляем список устройств при запуске
onRefreshDevices();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::setupInitialInterface()
{
ui->treeDevices->setHeaderLabels(QStringList()
<< tr("Device") << tr("Size") << tr("Filesystem")
<< tr("Used") << tr("Free") << tr("Mount Point")
<< tr("Flags") << tr("Status"));
updateButtonState();
}
void MainWindow::onActivateSpareClicked()
{
// Получаем выбранный элемент
QTreeWidgetItem *item = ui->treeDevices->currentItem();
if (!item) {
QMessageBox::warning(this, tr("No Device Selected"),
tr("Please select a spare device to activate."));
return;
}
// Проверяем, является ли выбранное устройство членом RAID
if (!isSelectedItemRaidMember()) {
QMessageBox::warning(this, tr("Invalid Selection"),
tr("Please select a spare device that is a member of a RAID array."));
return;
}
QString memberDevice = getSelectedDevicePath();
QString raidDevice = getSelectedRaidDevice();
if (memberDevice.isEmpty() || raidDevice.isEmpty()) {
QMessageBox::warning(this, tr("Invalid Device"),
tr("Cannot determine device or RAID array path."));
return;
}
// Проверяем, что устройство действительно spare
QString deviceStatus = item->text(3); // Колонка Status
if (!deviceStatus.contains("spare", Qt::CaseInsensitive)) {
QMessageBox::warning(this, tr("Not a Spare Device"),
tr("Selected device %1 is not a spare device.\n\n"
"Only spare devices can be activated.")
.arg(memberDevice));
return;
}
// Определяем тип RAID для специального предупреждения для RAID5
QString raidType = item->parent()->text(2); // Тип RAID родительского элемента
// Формируем сообщение подтверждения
QString confirmMessage = tr("Activate spare device %1 in RAID array %2?\n\n"
"This will:\n"
"1) Promote the spare device to an active member\n"
"2) Start automatic rebuilding/syncing process\n"
"3) The RAID array will operate normally during rebuild\n\n")
.arg(memberDevice)
.arg(raidDevice);
// Добавляем специальное предупреждение для RAID5
if (raidType == "RAID5") {
confirmMessage += tr("<b>Important for RAID5:</b>\n"
"After the rebuild is complete, you will need to manually "
"expand the filesystem to use the additional space. "
"The RAID array size will increase, but the filesystem "
"will remain at its original size until manually resized.\n\n");
}
confirmMessage += tr("Do you want to continue?");
// Запрашиваем подтверждение
QMessageBox msgBox(this);
msgBox.setWindowTitle(tr("Confirm Activate Spare"));
msgBox.setText(confirmMessage);
msgBox.setIcon(QMessageBox::Question);
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
// Для RAID5 делаем текст более заметным
if (raidType == "RAID5") {
msgBox.setStyleSheet("QMessageBox { background-color: #fff3cd; }");
}
if (msgBox.exec() == QMessageBox::Yes) {
// Активируем spare устройство
m_diskManager->activateSpareDevice(raidDevice, memberDevice);
ui->statusBar->showMessage(tr("Activating spare device %1...")
.arg(memberDevice), 3000);
}
}
void MainWindow::onCreateRaidClicked()
{
// Проверяем, есть ли доступные устройства для RAID
DiskStructure diskStructure = m_diskManager->getDiskStructure();
// Подсчитываем доступные устройства
int availableDevices = 0;
// Считаем разделы, которые не смонтированы и не в RAID
for (const DiskInfo &disk : diskStructure.getDisks()) {
for (const PartitionInfo &partition : disk.partitions) {
if (partition.mountPoint.isEmpty() && !partition.isRaidMember) {
availableDevices++;
}
}
}
// Считаем неразмеченные диски
for (const DiskInfo &disk : diskStructure.getDisks()) {
if (disk.partitions.isEmpty()) {
// Проверяем, не используется ли диск в RAID
bool isInRaid = false;
for (const RaidInfo &raid : diskStructure.getRaids()) {
for (const RaidMemberInfo &member : raid.members) {
if (member.devicePath == disk.devicePath) {
isInRaid = true;
break;
}
}
if (isInRaid) break;
}
if (!isInRaid) {
availableDevices++;
}
}
}
if (availableDevices < 2) {
QMessageBox::warning(this, tr("Insufficient Devices"),
tr("At least 2 unmounted devices or partitions are required to create a RAID array.\n\n"
"Available devices: %1\n"
"Required: 2 or more").arg(availableDevices));
return;
}
// Создаем и показываем диалог создания RAID
CreateRaidArrayDialog *dialog = new CreateRaidArrayDialog(diskStructure, this);
// Подключаем сигналы диалога к DiskManager
connect(dialog, &CreateRaidArrayDialog::createRaidRequested,
m_diskManager, &DiskManager::createRaidArray);
// Подключаем сигналы DiskManager к диалогу
connect(m_diskManager, &DiskManager::deviceWipeCompleted,
dialog, &CreateRaidArrayDialog::onWipeProgressUpdate);
connect(m_diskManager, &DiskManager::raidCreationProgress,
dialog, &CreateRaidArrayDialog::onRaidCreationProgress);
connect(m_diskManager, &DiskManager::raidCreationCompleted,
dialog, &CreateRaidArrayDialog::onRaidCreationCompleted);
// Показываем диалог
if (dialog->exec() == QDialog::Accepted) {
ui->statusBar->showMessage(tr("RAID array creation completed"), 5000);
// Обновляем отображение устройств
onRefreshDevices();
}
dialog->deleteLater();
}
void MainWindow::onDeleteRaidClicked()
{
// Получаем выбранный элемент
QTreeWidgetItem *item = ui->treeDevices->currentItem();
if (!item) {
QMessageBox::warning(this, tr("No RAID Selected"),
tr("Please select a RAID array to delete."));
return;
}
bool isMounted = m_diskManager->isDeviceMounted(item->text(0));
// Проверяем, является ли выбранное устройство RAID массивом
if (!isSelectedItemRaid()) {
QMessageBox::warning(this, tr("Invalid Selection"),
tr("Please select a RAID array, not a disk or partition."));
return;
}
if (isMounted) {
QMessageBox::warning(this, tr("Device is mounted"),
tr("Please unmount device."));
return;
}
QString raidPath = getSelectedDevicePath();
if (raidPath.isEmpty()) {
QMessageBox::warning(this, tr("Invalid RAID"),
tr("Cannot determine RAID array path."));
return;
}
// Находим информацию о RAID массиве
const DiskStructure& diskStructure = m_diskManager->getDiskStructure();
RaidInfo selectedRaid;
bool raidFound = false;
for (const RaidInfo &raid : diskStructure.getRaids()) {
if (raid.devicePath == raidPath) {
selectedRaid = raid;
raidFound = true;
break;
}
}
if (!raidFound) {
QMessageBox::warning(this, tr("RAID Not Found"),
tr("Could not find information about RAID array %1.")
.arg(raidPath));
return;
}
// Создаем и показываем диалог удаления RAID
DeleteRaidDialog *dialog = new DeleteRaidDialog(selectedRaid, this);
// Подключаем сигналы диалога к DiskManager
connect(dialog, &DeleteRaidDialog::deleteRaidRequested,
m_diskManager, &DiskManager::deleteRaidArray);
// Подключаем сигналы DiskManager к диалогу
connect(m_diskManager, &DiskManager::raidStopProgress,
dialog, &DeleteRaidDialog::onRaidStopProgress);
connect(m_diskManager, &DiskManager::raidStopCompleted,
dialog, &DeleteRaidDialog::onRaidStopCompleted);
connect(m_diskManager, &DiskManager::superblockCleanProgress,
dialog, &DeleteRaidDialog::onSuperblockCleanProgress);
connect(m_diskManager, &DiskManager::deviceWipeCompleted,
dialog, &DeleteRaidDialog::onWipeProgressUpdate);
connect(m_diskManager, &DiskManager::raidDeletionCompleted,
dialog, &DeleteRaidDialog::onRaidDeletionCompleted);
// Показываем диалог
if (dialog->exec() == QDialog::Accepted) {
ui->statusBar->showMessage(tr("RAID array deletion completed"), 5000);
}
dialog->deleteLater();
}
void MainWindow::onMountPartitionClicked()
{
// Получаем выбранный элемент
QTreeWidgetItem *item = ui->treeDevices->currentItem();
if (!item) {
QMessageBox::warning(this, tr("No Device Selected"),
tr("Please select a partition or RAID array to mount."));
return;
}
// Проверяем, можно ли монтировать выбранное устройство
if (!isSelectedItemMountable()) {
QMessageBox::warning(this, tr("Invalid Selection"),
tr("Please select a partition or RAID array, not a disk."));
return;
}
QString devicePath = getSelectedDevicePath();
if (devicePath.isEmpty()) {
QMessageBox::warning(this, tr("Invalid Device"),
tr("Cannot determine device path."));
return;
}
// Проверяем, не смонтировано ли уже устройство
if (m_diskManager->isDeviceMounted(devicePath)) {
QMessageBox::information(this, tr("Already Mounted"),
tr("Device %1 is already mounted at %2.")
.arg(devicePath)
.arg(m_diskManager->getMountPoint(devicePath)));
return;
}
// Проверяем наличие файловой системы
QString filesystem = m_diskManager->getDeviceFilesystem(devicePath);
if (filesystem.isEmpty() || filesystem == "unknown") {
QMessageBox::warning(this, tr("No Filesystem"),
tr("Device %1 has no recognizable filesystem.\n\n"
"Please format the device before mounting.")
.arg(devicePath));
return;
}
// Создаем диалог выбора папки для монтирования
FlyDirDialog *dirDialog = new FlyDirDialog(this,
tr("Select Mount Point"),
"/mnt");
// Подключаем сигналы диалога
connect(dirDialog, &FlyDirDialog::accepted, [this, dirDialog, devicePath, filesystem]() {
QString mountPoint = dirDialog->directory();
if (mountPoint.isEmpty()) {
QMessageBox::warning(this, tr("No Mount Point"),
tr("Please select a valid mount point."));
dirDialog->deleteLater();
return;
}
// Запрашиваем подтверждение
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, tr("Confirm Mount"),
tr("Mount device %1 (%2) at %3?")
.arg(devicePath)
.arg(filesystem.toUpper())
.arg(mountPoint),
QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes) {
// Монтируем устройство
m_diskManager->mountDevice(devicePath, mountPoint);
}
dirDialog->deleteLater();
});
connect(dirDialog, &FlyDirDialog::rejected, [dirDialog]() {
dirDialog->deleteLater();
});
// Показываем диалог
dirDialog->exec();
}
void MainWindow::onUnmountPartitionClicked()
{
// Получаем выбранный элемент
QTreeWidgetItem *item = ui->treeDevices->currentItem();
if (!item) {
QMessageBox::warning(this, tr("No Device Selected"),
tr("Please select a partition or RAID array to unmount."));
return;
}
// Проверяем, можно ли размонтировать выбранное устройство
if (!isSelectedItemMountable()) {
QMessageBox::warning(this, tr("Invalid Selection"),
tr("Please select a partition or RAID array, not a disk."));
return;
}
QString devicePath = getSelectedDevicePath();
if (devicePath.isEmpty()) {
QMessageBox::warning(this, tr("Invalid Device"),
tr("Cannot determine device path."));
return;
}
// Проверяем, смонтировано ли устройство
if (!m_diskManager->isDeviceMounted(devicePath)) {
QMessageBox::information(this, tr("Not Mounted"),
tr("Device %1 is not mounted.")
.arg(devicePath));
return;
}
QString mountPoint = m_diskManager->getMountPoint(devicePath);
// Запрашиваем подтверждение
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, tr("Confirm Unmount"),
tr("Unmount device %1 from %2?\n\n"
"Make sure all applications using this device are closed.")
.arg(devicePath)
.arg(mountPoint),
QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes) {
// Размонтируем устройство
m_diskManager->unmountDevice(devicePath);
}
}
void MainWindow::onDeviceMounted(bool success, const QString &devicePath, const QString &mountPoint)
{
if (success) {
ui->statusBar->showMessage(tr("Device %1 mounted successfully at %2")
.arg(devicePath)
.arg(mountPoint), 5000);
} else {
ui->statusBar->showMessage(tr("Failed to mount device %1")
.arg(devicePath), 5000);
}
}
void MainWindow::onDeviceUnmounted(bool success, const QString &devicePath)
{
if (success) {
ui->statusBar->showMessage(tr("Device %1 unmounted successfully")
.arg(devicePath), 5000);
} else {
ui->statusBar->showMessage(tr("Failed to unmount device %1")
.arg(devicePath), 5000);
}
}
bool MainWindow::isSelectedItemRaid() const
{
QTreeWidgetItem *item = ui->treeDevices->currentItem();
if (!item) {
return false;
}
QString devicePath = item->text(0);
return devicePath.contains("/dev/md") && item->parent() == nullptr;
}
bool MainWindow::isSelectedItemMountable() const
{
return isSelectedItemPartition() || isSelectedItemRaid();
}
QString MainWindow::getSelectedDevicePath() const
{
QTreeWidgetItem *item = ui->treeDevices->currentItem();
if (!item) {
return QString();
}
return item->text(0);
}
void MainWindow::onRefreshDevices()
{
// Показываем сообщение о начале обновления в статусной строке
ui->statusBar->showMessage(tr("Refreshing device list..."));
// Очищаем таблицу
ui->treeDevices->clear();
// Запускаем обновление списка устройств
m_diskManager->refreshDevices();
}
void MainWindow::onViewModeChanged(int index)
{
// Обновляем режим отображения
m_showAllDevices = (index == 0); // 0 = All Devices, 1 = RAID Only
// Обновляем интерфейс
updateInterface();
}
void MainWindow::onDevicesRefreshed(bool success)
{
if (success) {
ui->statusBar->showMessage(tr("Device list updated successfully"), 3000);
// Обновляем таблицу
updateInterface();
} else {
ui->statusBar->showMessage(tr("Failed to update device list"), 3000);
}
}
void MainWindow::onCommandOutput(const QString &output)
{
// Добавляем вывод в лог
ui->txtOperationLog->append(output);
}
void MainWindow::onMarkFaultyClicked()
{
// Получаем выбранный элемент
QTreeWidgetItem *item = ui->treeDevices->currentItem();
if (!item) {
QMessageBox::warning(this, tr("No Device Selected"),
tr("Please select a RAID member device to mark as faulty."));
return;
}
// Проверяем, является ли выбранное устройство членом RAID
if (!isSelectedItemRaidMember()) {
QMessageBox::warning(this, tr("Invalid Selection"),
tr("Please select a device that is a member of a RAID array."));
return;
}
if (item->parent()->text(2) == "RAID0") {
QMessageBox::warning(this, tr("Invalid Selection"),
tr("Cannot mark faulty a RAID0 member."));
return;
}
QString memberDevice = getSelectedDevicePath();
QString raidDevice = getSelectedRaidDevice();
if (memberDevice.isEmpty() || raidDevice.isEmpty()) {
QMessageBox::warning(this, tr("Invalid Device"),
tr("Cannot determine device or RAID array path."));
return;
}
// Запрашиваем подтверждение
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, tr("Confirm Mark Faulty"),
tr("Mark device %1 as faulty in RAID array %2?\n\n"
"This will cause the RAID array to operate in degraded mode "
"and the device will be excluded from the array.\n\n")
.arg(memberDevice)
.arg(raidDevice),
QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes) {
// Помечаем устройство как сбойное
m_diskManager->markDeviceAsFaulty(raidDevice, memberDevice);
}
}
void MainWindow::onAddToRaidClicked()
{
// Получаем выбранный элемент
QTreeWidgetItem *item = ui->treeDevices->currentItem();
if (!item) {
QMessageBox::warning(this, tr("No Device Selected"),
tr("Please select a partition or disk to add to a RAID array."));
return;
}
QString devicePath = getSelectedDevicePath();
if (devicePath.isEmpty()) {
QMessageBox::warning(this, tr("Invalid Device"),
tr("Cannot determine device path."));
return;
}
bool isDisk = (devicePath.contains("/dev/sd") || devicePath.contains("/dev/nvme") ||
devicePath.contains("/dev/vd") || devicePath.contains("/dev/hd")) &&
item->parent() == nullptr;
// Проверяем, можно ли добавить выбранное устройство в RAID
if (!isSelectedItemPartition() && !isDisk) {
QMessageBox::warning(this, tr("Invalid Selection"),
tr("Please select a partition or unpartitioned disk."));
return;
}
// Проверяем, что устройство не смонтировано и не в RAID
if (m_diskManager->isDeviceMounted(devicePath)) {
QMessageBox::warning(this, tr("Device Mounted"),
tr("Device %1 is currently mounted. Please unmount it first.")
.arg(devicePath));
return;
}
const DiskStructure& diskStructure = m_diskManager->getDiskStructure();
// Для разделов проверяем, не является ли он членом RAID
if (isSelectedItemPartition()) {
for (const DiskInfo &disk : diskStructure.getDisks()) {
for (const PartitionInfo &partition : disk.partitions) {
if (partition.devicePath == devicePath && partition.isRaidMember) {
QMessageBox::warning(this, tr("Already in RAID"),
tr("Device %1 is already a member of a RAID array.")
.arg(devicePath));
return;
}
}
}
}
// Получаем список доступных RAID массивов
QStringList availableRaids;
for (const RaidInfo &raid : diskStructure.getRaids()) {
// Добавляем только активные RAID массивы
if ((raid.state.contains("active", Qt::CaseInsensitive) || raid.state.contains("clean", Qt::CaseInsensitive)) && raid.type != RaidType::RAID0) {
QString raidInfo = tr("%1 (%2, %3)")
.arg(raid.devicePath)
.arg(DiskUtils::raidTypeToString(raid.type))
.arg(raid.size);
availableRaids.append(raidInfo);
}
}
if (availableRaids.isEmpty()) {
QMessageBox::information(this, tr("No RAID Arrays"),
tr("No active RAID arrays available to add devices to."));
return;
}
// Показываем диалог выбора RAID массива
bool ok;
QString selectedRaidInfo = QInputDialog::getItem(this, tr("Select RAID Array"),
tr("Select RAID array to add device %1 to:")
.arg(devicePath),
availableRaids, 0, false, &ok);
if (!ok || selectedRaidInfo.isEmpty()) {
return;
}
// Извлекаем путь к RAID устройству из выбранной строки
QString raidDevice = selectedRaidInfo.split(' ').first();
// Запрашиваем финальное подтверждение
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, tr("Confirm Add Device"),
tr("Add device %1 to RAID array %2?\n\n"
"This will:\n"
"1) Wipe all data from %1\n"
"2) Add it as a member of the RAID array\n"
"3) Start automatic rebuilding/syncing process\n\n"
"All data on %1 will be permanently lost!")
.arg(devicePath)
.arg(raidDevice),
QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes) {
// Добавляем устройство в RAID
m_diskManager->addDeviceToRaid(raidDevice, devicePath);
}
}
void MainWindow::onRemoveFromRaidClicked()
{
// Получаем выбранный элемент
QTreeWidgetItem *item = ui->treeDevices->currentItem();
if (!item) {
QMessageBox::warning(this, tr("No Device Selected"),
tr("Please select a RAID member device to remove from the array."));
return;
}
// Проверяем, является ли выбранное устройство членом RAID
if (!isSelectedItemRaidMember()) {
QMessageBox::warning(this, tr("Invalid Selection"),
tr("Please select a device that is a member of a RAID array."));
return;
}
if (item->parent()->text(2) == "RAID0") {
QMessageBox::warning(this, tr("Invalid Selection"),
tr("Cannot remove a RAID0 member."));
return;
}
QString memberDevice = getSelectedDevicePath();
QString raidDevice = getSelectedRaidDevice();
if (memberDevice.isEmpty() || raidDevice.isEmpty()) {
QMessageBox::warning(this, tr("Invalid Device"),
tr("Cannot determine device or RAID array path."));
return;
}
// Запрашиваем подтверждение
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, tr("Confirm Remove Device"),
tr("Remove device %1 from RAID array %2?\n\n"
"This will:\n"
"1) Remove it from the RAID array\n"
"2) The device will become available for other uses\n\n"
"The RAID array will continue operating in degraded mode "
"until a replacement device is added.")
.arg(memberDevice)
.arg(raidDevice),
QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes) {
// Удаляем устройство из RAID
m_diskManager->removeDeviceFromRaid(raidDevice, memberDevice);
}
}
void MainWindow::onCreatePartitionTableClicked()
{
// Получаем выбранный элемент
QTreeWidgetItem *item = ui->treeDevices->currentItem();
if (!item) {
QMessageBox::warning(this, tr("No Device Selected"),
tr("Please select a disk to create a partition table."));
return;
}
// Получаем путь к устройству
QString devicePath = item->text(0);
// Проверяем, является ли выбранное устройство диском
bool isDisk = devicePath.contains("/dev/sd") || devicePath.contains("/dev/nvme") ||
devicePath.contains("/dev/vd") || devicePath.contains("/dev/hd");
if (!isDisk || item->parent() != nullptr) {
QMessageBox::warning(this, tr("Invalid Selection"),
tr("Please select a disk, not a partition or RAID array."));
return;
}
// Создаем и показываем диалог
PartitionTableDialog *dialog = new PartitionTableDialog(devicePath, this);
if (dialog->exec() == QDialog::Accepted) {
// Получаем выбранный тип таблицы разделов
QString tableType = dialog->selectedTableType();
// Запрашиваем подтверждение
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, tr("Confirm Action"),
tr("Are you sure you want to create a new %1 partition table on %2?\n\n"
"All existing data on the disk will be lost!")
.arg(tableType.toUpper())
.arg(devicePath),
QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes) {
// Создаем таблицу разделов
m_diskManager->createPartitionTable(devicePath, tableType);
}
}
dialog->deleteLater();
}
void MainWindow::onCreatePartitionClicked()
{
// Получаем выбранный элемент
QTreeWidgetItem *item = ui->treeDevices->currentItem();
if (!item) {
QMessageBox::warning(this, tr("No Device Selected"),
tr("Please select a disk to create a partition."));
return;
}
// Получаем путь к устройству
QString devicePath = item->text(0);
// Проверяем, является ли выбранное устройство диском
bool isDisk = devicePath.contains("/dev/sd") || devicePath.contains("/dev/nvme") ||
devicePath.contains("/dev/vd") || devicePath.contains("/dev/hd");
if (!isDisk || item->parent() != nullptr) {
QMessageBox::warning(this, tr("Invalid Selection"),
tr("Please select a disk, not a partition or RAID array."));
return;
}
// Создаем диалог создания раздела
CreatePartitionDialog *dialog = new CreatePartitionDialog(devicePath, this);
// Подключаем сигнал для получения информации о свободном пространстве
connect(m_diskManager, &DiskManager::freeSpaceOnDeviceInfoReceived,
dialog, &CreatePartitionDialog::onFreeSpaceInfoOnDeviceReceived);
// Запрашиваем информацию о свободном пространстве
m_diskManager->getFreeSpaceOnDeviceInfo(devicePath);
// Показываем диалог
if (dialog->exec() == QDialog::Accepted) {
// Дополнительная валидация перед созданием раздела
if (dialog->validateInput()) {
// Получаем данные из диалога
QString partitionType = dialog->getPartitionType();
QString filesystemType = dialog->getFilesystemType();
QString startSize = dialog->getStartSize();
QString endSize = dialog->getEndSize();
// Запрашиваем подтверждение
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, tr("Confirm Partition Creation"),
tr("Create %1 partition from %2 to %3?\n\n"
"Partition type: %4\n"
"Filesystem: %5")
.arg(partitionType)
.arg(startSize)
.arg(endSize)
.arg(partitionType)
.arg(filesystemType),
QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes) {
// Создаем раздел
m_diskManager->createPartition(devicePath, partitionType, filesystemType,
startSize, endSize);
}
}
}
dialog->deleteLater();
}
void MainWindow::onDeletePartitionClicked()
{
// Получаем выбранный элемент
QTreeWidgetItem *item = ui->treeDevices->currentItem();
if (!item) {
QMessageBox::warning(this, tr("No Partition Selected"),
tr("Please select a partition to delete."));
return;
}
// Проверяем, является ли выбранное устройство разделом
if (!isSelectedItemPartition()) {
QMessageBox::warning(this, tr("Invalid Selection"),
tr("Please select a partition, not a disk or RAID array."));
return;
}
QString partitionPath = getSelectedPartitionPath();
if (partitionPath.isEmpty()) {
QMessageBox::warning(this, tr("Invalid Partition"),
tr("Cannot determine partition path."));
return;
}
// Проверяем, не смонтирован ли раздел
QString mountPoint = item->text(5); // Колонка Mount Point
if (!mountPoint.isEmpty()) {
QMessageBox::warning(this, tr("Partition is Mounted"),
tr("Cannot delete partition %1 because it is currently mounted at %2.\n\n"
"Please unmount the partition first.")
.arg(partitionPath)
.arg(mountPoint));
return;
}
// Создаем и показываем диалог подтверждения
DeletePartitionDialog *dialog = new DeletePartitionDialog(partitionPath, this);
if (dialog->exec() == QDialog::Accepted && dialog->isConfirmed()) {
// Удаляем раздел
m_diskManager->deletePartition(partitionPath);
}
dialog->deleteLater();
}
void MainWindow::onFormatPartitionClicked()
{
// Получаем выбранный элемент
QTreeWidgetItem *item = ui->treeDevices->currentItem();