-
Notifications
You must be signed in to change notification settings - Fork 1
/
mainwindow.cpp
2542 lines (2340 loc) · 94 KB
/
mainwindow.cpp
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 <algorithm> // std::find_if_not
#include <chrono>
#include <optional>
#include <set>
#include <string>
#include <utility> // for std::pair
#include <vector>
#include <QtDebug>
#include <QObject>
#include <QTreeWidgetItem>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QMessageBox>
#include <QFileInfo>
#include <QStringView>
#include <QFileSystemModel>
#include <QFileSystemWatcher>
#include <QFont>
#include <QHeaderView>
#include <QPushButton>
#include <QTimer>
#include <QFontDatabase>
#include <QXmlStreamReader>
#include <QFileDialog>
#include <QMetaType>
#include <QStyledItemDelegate>
#include <QPainter>
#include <QMouseEvent>
#include <QProgressBar>
#include <QDateTime>
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QApplication>
#include <QFrame>
#include <QHBoxLayout>
#include <QLabel>
#include <QMainWindow>
#include <QMenu>
#include <QMenuBar>
#include <QScrollBar>
#include <QSplitter>
#include <QStatusBar>
#include <QToolBar>
#include <QVBoxLayout>
#include <QWidget>
#include <QThreadPool>
#include "directoryreader.h"
#include "itemdefaults.h"
#include "mainwindow.h"
#include "pathactiondialog.h"
#include "plistprocess.h"
#include "settings.h"
#include "settingsdialog.h"
#include "sortingdisabler.h"
namespace {
constexpr auto toolName = "Time Machine utility";
/// @note Toplevel key within the status plist dictionary.
constexpr auto backupPhaseKey = "BackupPhase";
constexpr auto destinationsKey = "Destinations";
/// @note Toplevel key within the status plist dictionary.
constexpr auto destinationMountPointKey = "DestinationMountPoint";
/// @note Toplevel key within the status plist dictionary.
constexpr auto destinationIdKey = "DestinationID";
constexpr auto dateStateChangeKey = "DateOfStateChange";
/// @note Toplevel key within the status plist dictionary. Its
/// entry value is another dictionary with progress related details.
constexpr auto progressKey = "Progress";
/// @note Key within the "Progress" entry's dictionary.
constexpr auto timeRemainingKey = "TimeRemaining";
/// @note Key within the "Progress" entry's dictionary.
constexpr auto percentKey = "Percent";
/// @note Key within the "Progress" entry's dictionary.
constexpr auto bytesKey = "bytes";
/// @note Key within the "Progress" entry's dictionary.
constexpr auto totalBytesKey = "totalBytes";
/// @note Key within the "Progress" entry's dictionary.
constexpr auto numFilesKey = "files";
/// @note Key within the "Progress" entry's dictionary.
constexpr auto totalFilesKey = "totalFiles";
constexpr auto timeMachineAttrPrefix = "com.apple.timemachine.";
constexpr auto backupAttrPrefix = "com.apple.backup.";
constexpr auto backupdAttrPrefix = "com.apple.backupd.";
// Content of this attribute seems to be comma separated list, where
// first element is one of the following:
// "SnapshotStorage","MachineStore", "Backup", "VolumeStore"
constexpr auto timeMachineMetaAttr =
"com.apple.timemachine.private.structure.metadata";
// Machine level attributes...
constexpr auto machineMacAddrAttr = "com.apple.backupd.BackupMachineAddress";
constexpr auto machineCompNameAttr = "com.apple.backupd.ComputerName";
constexpr auto machineUuidAttr = "com.apple.backupd.HostUUID";
constexpr auto machineModelAttr = "com.apple.backupd.ModelID";
// Backup level attributes...
constexpr auto snapshotTypeAttr = "com.apple.backupd.SnapshotType";
constexpr auto snapshotStartAttr = "com.apple.backupd.SnapshotStartDate";
constexpr auto snapshotFinishAttr = "com.apple.backupd.SnapshotCompletionDate";
constexpr auto totalBytesCopiedAttr = "com.apple.backupd.SnapshotTotalBytesCopied";
// version 4 appears to add "com.apple.backupd.fstypename" attr to volumes
constexpr auto snapshotVersionAttr = "com.apple.backup.SnapshotVersion";
constexpr auto snapshotStateAttr = "com.apple.backupd.SnapshotState";
constexpr auto snapshotNumberAttr = "com.apple.backup.SnapshotNumber";
// Volume level attributes...
constexpr auto fileSystemTypeAttr = "com.apple.backupd.fstypename";
constexpr auto volumeBytesUsedAttr = "com.apple.backupd.VolumeBytesUsed";
constexpr auto volumeUuidAttr = "com.apple.backupd.SnapshotVolumeUUID";
constexpr auto fullDiskAccessStr = "Full Disk Access";
constexpr auto systemSettingsStr = "System Settings";
constexpr auto privacySecurityStr = "Privacy & Security";
constexpr auto cantListDirWarning = "Warning: unable to list contents of this directory!";
constexpr auto tmutilDeleteVerb = "delete";
constexpr auto tmutilVerifyVerb = "verifychecksums";
constexpr auto tmutilUniqueSizeVerb = "uniquesize";
constexpr auto tmutilRestoreVerb = "restore";
constexpr auto tmutilStatusVerb = "status";
constexpr auto tmutilDestInfoVerb = "destinationinfo";
constexpr auto tmutilXmlOption = "-X";
constexpr auto pathInfoUpdateTime = 10000;
constexpr auto maxToolTipStringList = 10;
constexpr auto gigabyte = 1000 * 1000 * 1000;
constexpr auto defaultSectionSize = 80;
constexpr auto emptyTableMaxHeight = 50;
constexpr auto mainWindowSize = QSize{900, 900};
constexpr auto mainWindowMinimumSize = QSize{800, 400};
// A namespace scoped enum for the destinations table columns...
namespace DestsColumn {
enum Enum: int {
Name = 0,
ID,
Kind,
Mount,
Use,
Capacity,
Free,
Action,
BackupStat,
};
}
// A namespace scoped enum for the machines table columns...
namespace MachinesColumn {
enum Enum: int {
Name = 0,
Uuid,
Model,
Address,
Destinations,
Volumes,
Backups,
};
}
// A namespace scoped enum for the backups table columns...
namespace BackupsColumn {
enum Enum: int {
Name = 0,
Type,
State,
Version,
Number,
Duration,
Size,
Volumes,
Machine,
Destination,
};
}
namespace VolumesColumn {
enum Enum: int {
Name = 0,
Uuid,
Type,
MaxUsed,
Machines,
Destinations,
Backups,
};
}
constexpr auto itemFlags =
Qt::ItemIsSelectable|Qt::ItemIsEnabled|Qt::ItemIsUserCheckable;
constexpr auto enabledAdminButtonStyle =
"QPushButton {color: rgb(180, 0, 0);}";
constexpr auto disabledAdminButtonStyle =
"QPushButton {color: rgb(180, 100, 100);}";
auto toMegaBytes(const std::optional<std::int64_t>& value)
-> QString
{
if (value) {
const auto megaBytes = double(*value) / (1000 * 1000);
return QString::number(megaBytes, 'f', 2);
}
return {};
}
auto toStringList(const QList<QTableWidgetItem *> &items)
-> QStringList
{
QStringList result;
for (const auto* item: items) {
const auto string = item->data(Qt::UserRole).toString();
if (!string.isEmpty()) {
result += string;
}
}
return result;
}
auto toStringList(const QSet<QString>& strings,
const int max = -1,
const QString &etc = "...")
-> QStringList
{
QStringList result;
for (const auto& string: strings) {
if ((max >= 0) && (max <= result.size())) {
result << etc;
break;
}
result << string;
}
return result;
}
auto toStringList(const std::set<QString>& strings,
const int max = -1,
const QString &etc = "...")
-> QStringList
{
QStringList result;
for (const auto& string: strings) {
if ((max >= 0) && (max <= result.size())) {
result << etc;
break;
}
result << string;
}
return result;
}
auto anyStartsWith(const QMap<QString, QByteArray>& attrs,
const QStringList& prefices) -> bool
{
auto first = attrs.keyBegin();
const auto last = attrs.keyEnd();
for (auto it = first; it != last; ++it) {
for (const auto& prefix: prefices) {
if (it->startsWith(prefix)) {
return true;
}
}
}
return false;
}
auto toIndicatorPolicy(const std::filesystem::file_type& file_type)
-> QTreeWidgetItem::ChildIndicatorPolicy
{
using QTreeWidgetItem::ChildIndicatorPolicy::ShowIndicator;
using QTreeWidgetItem::ChildIndicatorPolicy::DontShowIndicator;
return (file_type == std::filesystem::file_type::directory)
? ShowIndicator
: DontShowIndicator;
}
auto get(const QMap<QString, QByteArray> &attrs, const QString &key)
-> std::optional<QByteArray>
{
const auto it = attrs.find(key);
if (it != attrs.end()) {
return {*it};
}
return {};
}
auto toLongLong(const std::optional<QByteArray>& value)
-> std::optional<std::int64_t>
{
auto okay = false;
const auto number = QString{value.value_or(QByteArray{})}.toLongLong(&okay);
return okay? std::optional<std::int64_t>{number}: std::optional<std::int64_t>{};
}
auto toMicroseconds(const std::optional<QByteArray>& value)
-> std::optional<std::chrono::microseconds>
{
const auto num = toLongLong(value);
using namespace std::chrono_literals;
return num
? std::optional<std::chrono::microseconds>{*num * 1us}
: std::optional<std::chrono::microseconds>{};
}
auto pathTooltip(const QMap<QString, QByteArray> &attrs) -> QString
{
if (const auto v = get(attrs, timeMachineMetaAttr)) {
if (v->startsWith("SnapshotStorage")) {
return "A \"backup store\".";
}
}
if (const auto v = get(attrs, machineUuidAttr)) {
return "This is a \"machine directory\".";
}
if (const auto v = get(attrs, machineCompNameAttr)) {
return "This is a \"machine directory\".";
}
if (const auto v = get(attrs, snapshotTypeAttr)) {
return "This is a \"backup\".";
}
if (const auto v = get(attrs, fileSystemTypeAttr)) {
return "This is a \"volume store\".";
}
return {};
}
auto findTopLevelItem(const QTreeWidget& tree, const QString& key)
-> QTreeWidgetItem*
{
const auto count = tree.topLevelItemCount();
for (auto i = 0; i < count; ++i) {
const auto item = tree.topLevelItem(i);
if (item->text(0) == key) {
return item;
}
}
return nullptr;
}
auto findAddableTopLevelItems(
const QTreeWidget& tree,
const auto& names) -> std::set<QString>
{
auto result = std::set<QString>{};
for (const auto& name: names) {
const auto key = QString::fromStdString(name);
const auto found = findTopLevelItem(tree, key);
if (!found) {
result.insert(key);
}
}
return result;
}
auto findDeletableTopLevelItems(
const QTreeWidget& tree,
const auto& names) -> std::set<QString>
{
auto result = std::set<QString>{};
const auto count = tree.topLevelItemCount();
for (auto i = 0; i < count; ++i) {
const auto key = tree.topLevelItem(i)->text(0);
const auto it = std::find(names.begin(), names.end(),
key.toStdString());
if (it == names.end()) {
result.insert(key);
}
}
return result;
}
auto findRow(const QTableWidget& table,
const std::initializer_list<std::pair<int, QString>>& keys)
-> int
{
const auto count = table.rowCount();
for (auto row = 0; row < count; ++row) {
auto found = true;
for (const auto& key: keys) {
const auto item = table.item(row, key.first);
if (!item || item->text() != key.second) {
found = false;
break;
}
}
if (found) {
return row;
}
}
return -1;
}
auto findChild(QTreeWidgetItem *parent,
const std::filesystem::path& path)
-> std::pair<QTreeWidgetItem*, int>
{
const auto count = parent->childCount();
for (auto i = 0; i < count; ++i) {
const auto child = parent->child(i);
const QString pathName =
child->data(0, Qt::UserRole).toString();
if (pathName == path.c_str()) {
return {child, i};
}
}
return {};
}
auto operator==(const std::filesystem::file_status& lhs,
const std::filesystem::file_status& rhs) noexcept
{
return (lhs.permissions() == rhs.permissions()) &&
(lhs.type() == rhs.type());
}
auto operator==(const PathInfo& lhs, const PathInfo& rhs)
{
return (lhs.status == rhs.status) &&
(lhs.attributes == rhs.attributes);
}
void remove(std::set<QTreeWidgetItem*>& items, QTreeWidgetItem* item)
{
if (!item) {
return;
}
items.erase(item);
const auto count = item->childCount();
for (auto i = 0; i < count; ++i) {
remove(items, item->child(i));
}
}
auto duration(const std::optional<std::chrono::microseconds>& t0,
const std::optional<std::chrono::microseconds>& t1)
-> std::optional<std::chrono::seconds>
{
if (t0 && t1) {
const auto minmax = std::minmax(*t0, *t1);
using namespace std::chrono_literals;
return {
std::chrono::duration_cast<std::chrono::seconds>(
(minmax.second - minmax.first))
};
}
return {};
}
auto toMilliseconds(const std::chrono::microseconds t)
-> std::chrono::milliseconds
{
using namespace std::chrono;
return duration_cast<milliseconds>(t);
}
auto durationToolTip(const std::optional<std::chrono::microseconds>& t0,
const std::optional<std::chrono::microseconds>& t1)
-> QString
{
using namespace std::chrono_literals;
using namespace std::chrono;
const auto unknown = QString{"unknown"};
const auto t0String = t0
? QDateTime::fromMSecsSinceEpoch(toMilliseconds(*t0).count()).toString()
: unknown;
const auto t1String = t1
? QDateTime::fromMSecsSinceEpoch(toMilliseconds(*t1).count()).toString()
: unknown;
return QString{"%1...%2"}.arg(t0String, t1String);
}
auto firstToLastToolTip(const std::set<QString>& set)
-> QString
{
if (set.empty()) {
return {};
}
return QString{"%1...%2"}.arg(*set.begin(), *set.rbegin());
}
auto concatenate(const std::filesystem::path::iterator& first,
const std::filesystem::path::iterator& last)
-> std::filesystem::path
{
auto result = std::filesystem::path{};
for (auto it = first; it != last; ++it) {
result /= *it;
}
return result;
}
auto removeLast(std::input_iterator auto first,
std::input_iterator auto& last)
{
using OT = decltype(*last);
if (last == first) {
return OT{};
}
--last;
return OT{*last};
}
auto isStorageDir(const QMap<QString, QByteArray>& attrs)
-> bool
{
const auto timeMachineMeta = get(attrs, timeMachineMetaAttr);
return timeMachineMeta &&
timeMachineMeta->startsWith("SnapshotStorage");
}
auto isMachineDir(const QMap<QString, QByteArray>& attrs)
-> bool
{
const auto machineUuid = get(attrs, machineUuidAttr);
const auto machineAddr = get(attrs, machineMacAddrAttr);
const auto machineModel = get(attrs, machineModelAttr);
const auto machineName = get(attrs, machineCompNameAttr);
return machineUuid || machineAddr || machineModel || machineName;
}
auto isVolumeDir(const QMap<QString, QByteArray>& attrs)
-> bool
{
return get(attrs, snapshotTypeAttr) ||
get(attrs, totalBytesCopiedAttr);
}
auto toString(const std::optional<QByteArray> &data)
-> std::optional<QString>
{
if (!data) {
return {};
}
auto first = data->rbegin();
const auto last = data->rend();
for (; first != last; ++first) {
if (*first != 0) {
break;
}
}
return {QString::fromUtf8(QByteArrayView{data->data(), &(*first) + 1})};
}
auto checkedTextStrings(const QTableWidget& tbl, int column)
-> QSet<QString>
{
auto strings = QSet<QString>{};
const auto count = tbl.rowCount();
for (auto row = 0; row < count; ++row) {
auto item = tbl.item(row, column);
if (!item) {
continue;
}
const auto checkState = item->checkState();
if (checkState != Qt::CheckState::Unchecked) {
strings.insert(item->text());
}
}
return strings;
}
template <class T>
auto toStdSet(const QSet<T>& set)
-> std::set<T>
{
auto result = std::set<T>{};
for (const auto& elem: set) {
result.insert(elem);
}
return result;
}
template <class T>
auto insert(std::set<T>& dst, const QSet<T>& src)
-> std::set<T>&
{
for (const auto& elem: src) {
dst.insert(elem);
}
return dst;
}
template <class T>
auto erase(std::set<T>& dst, const QSet<T>& src)
-> std::set<T>&
{
for (const auto& elem: src) {
dst.erase(elem);
}
return dst;
}
auto secondsToUserTime(plist_real value) -> QString
{
static constexpr auto secondsPerMinutes = 60;
return QString("~%1 minutes")
.arg(QString::number(value / secondsPerMinutes, 'f', 1));
}
auto decodeBackupPhase(const plist_string &name) -> QString
{
if (name == "ThinningPostBackup") {
// a.k.a. "Cleaning up"
return "Thinning Post Backup";
}
if (name == "FindingChanges") {
return "Finding Changes";
}
return QString::fromStdString(name);
}
auto createAboutDialog(QWidget *parent)
-> QMessageBox*
{
auto *dialog = new QMessageBox(parent);
dialog->setStandardButtons(QMessageBox::Close);
dialog->setWindowTitle("About");
dialog->setOptions(QMessageBox::Option::DontUseNativeDialog);
dialog->setWindowFlags(dialog->windowFlags()|
Qt::WindowTitleHint|Qt::WindowSystemMenuHint);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setIconPixmap(QPixmap{":/resources/icon_128x128.png"});
dialog->setModal(false);
dialog->setTextFormat(Qt::TextFormat::MarkdownText);
QString text;
text.append(QString("## %1 %2.%3")
.arg(parent->windowTitle())
.arg(VERSION_MAJOR)
.arg(VERSION_MINOR));
text.append("\n\n");
text.append(QString("Built on %1.").arg(BUILD_TIMESTAMP));
text.append("\n\n");
text.append(QString("Source code available from [GitHub](%1).")
.arg("https://github.com/louis-langholtz/time-machine-helper"));
text.append("\n\n");
text.append(QString("Copyright %1.").arg(COPYRIGHT));
text.append("\n\n");
text.append(QString("Compiled with Qt version %1. Running with Qt version %2.")
.arg(QT_VERSION_STR, qVersion()));
dialog->setStyleSheet("QMessageBox QLabel {font-weight: normal;}");
dialog->setText(text);
return dialog;
}
auto createdPushButton(QTableWidget* parent,
int row, int column,
const QString& text,
const std::function<void(QPushButton *pb)> &functor)
-> QPushButton*
{
auto result = qobject_cast<QPushButton*>(
parent->cellWidget(row, DestsColumn::Action));
if (!result) {
result = new QPushButton(text, parent);
result->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
parent->setCellWidget(row, column, result);
QObject::connect(result, &QPushButton::released,
parent, [functor,result](){
functor(result);
});
}
return result;
}
auto createNoDestinationsDialog(QWidget *parent = nullptr)
-> QMessageBox*
{
const auto dialog = new QMessageBox{parent};
dialog->setIcon(QMessageBox::Critical);
dialog->setText("No destination accessible!");
dialog->setInformativeText(
"No backups or restores are possible when no destinations are accessible!");
dialog->setModal(false);
return dialog;
}
auto createCantReadMountPointDialog(QWidget *parent = nullptr)
-> QMessageBox*
{
const auto dialog = new QMessageBox{parent};
return dialog;
}
auto usage(const std::filesystem::space_info& si)
-> std::uintmax_t
{
return si.capacity - si.free;
}
auto usageRatio(const std::filesystem::space_info& si)
-> double
{
return (si.capacity != 0u)
? double(usage(si)) / double(si.capacity)
: 0.0;
}
auto freeRatio(const std::filesystem::space_info& si)
-> double
{
return (si.capacity != 0u)
? double(si.free) / double(si.capacity)
: 0.0;
}
auto destsNameText(const plist_dict &destination)
{
return QString::fromStdString(
get<std::string>(destination, "Name").value_or(""));
}
auto destsBackupStatText(const plist_dict &status,
const std::optional<std::string> &mp)
-> QString
{
// When running...
const auto destMP = get<plist_string>(status, destinationMountPointKey);
if (destMP && mp && *destMP == *mp) {
auto result = QStringList{};
if (const auto v = get<plist_string>(status, backupPhaseKey)) {
result << decodeBackupPhase(*v);
}
if (const auto prog = get<plist_dict>(status, progressKey)) {
if (const auto v = get<plist_real>(*prog, percentKey)) {
result << QString("%1%")
.arg(QString::number(*v * 100.0, 'f', 1));
}
}
return result.join(' ');
}
return QString{};
}
auto destsActionText(const plist_dict &status,
const std::optional<std::string> &mp)
-> QString
{
const auto destMP = get<plist_string>(status, destinationMountPointKey);
return (destMP && mp && destMP == *mp) ? "Stop": "Start";
}
auto destsBackupStatToolTip(const plist_dict &status,
const std::optional<std::string> &mp)
-> QString
{
// When running...
const auto destMP =
get<plist_string>(status, destinationMountPointKey);
if (destMP && mp && *destMP == *mp) {
auto result = QStringList{};
if (const auto v = get<plist_date>(status, dateStateChangeKey)) {
const auto t = std::chrono::system_clock::to_time_t(*v);
result << QString("Since: %1...")
.arg(QDateTime::fromSecsSinceEpoch(t)
.toString());
}
if (const auto v = get<plist_string>(status, destinationIdKey)) {
result << QString("Destination ID: %1.").arg(v->c_str());
}
if (const auto prog = get<plist_dict>(status, progressKey)) {
if (const auto v = get<plist_integer>(*prog, bytesKey)) {
result << QString("Number of bytes: %1.").arg(*v);
}
if (const auto v = get<plist_integer>(*prog, totalBytesKey)) {
result << QString("Total bytes: %1.").arg(*v);
}
if (const auto v = get<plist_integer>(*prog, numFilesKey)) {
result << QString("Number of files: %1.").arg(*v);
}
if (const auto v = get<plist_integer>(*prog, totalFilesKey)) {
result << QString("Total files: %1.").arg(*v);
}
if (const auto v = get<plist_real>(*prog, timeRemainingKey)) {
result << QString("Allegedly, %1 remaining.")
.arg(secondsToUserTime(*v));
}
}
return result.join('\n');
}
return {};
}
auto destsCapacityData(const std::optional<std::string> &mp,
const std::error_code& ec,
const std::filesystem::space_info& si)
-> QVariant
{
return (mp && !ec)
? QVariant{(double(si.capacity) / gigabyte)}
: QVariant{};
}
auto destsCapacityToolTip(
const std::optional<std::string> &mp,
const std::error_code& ec,
const std::filesystem::space_info& si) -> QString
{
if (!mp) {
return QString{"No info available on capacity - no mount point for destination."};
}
if (ec) {
return QString{"Error reading mount point space info: %1"}
.arg(QString::fromStdString(ec.message()));
}
return QString{"%1 bytes capacity"}
.arg(si.capacity);
}
auto destsFreeData(const std::optional<std::string> &mp,
const std::error_code& ec,
const std::filesystem::space_info& si)
-> QVariant
{
return (mp && !ec)
? QVariant{(double(si.free) / gigabyte)}
: QVariant{};
}
auto destsFreeToolTip(
const std::optional<std::string> &mp,
const std::error_code& ec,
const std::filesystem::space_info& si) -> QString
{
if (!mp) {
return QString{"No info available on free space - no mount point for destination."};
}
if (ec) {
return QString{"Error reading mount point space info: %1"}
.arg(QString::fromStdString(ec.message()));
}
return QString{"%1 bytes free out of %2, %3%"}
.arg(si.free)
.arg(si.capacity)
.arg(static_cast<int>(freeRatio(si) * 100.0));
}
auto createdDestsNameItem(
QTableWidget *tbl,
int row,
const std::optional<std::string> &mp,
const std::error_code& ec) -> QTableWidgetItem*
{
const auto on = std::optional<Qt::CheckState>
{(mp && !ec)? Qt::Checked: Qt::Unchecked};
return createdItem(tbl, row, DestsColumn::Name,
ItemDefaults{}.use(on));
}
auto space(const std::optional<std::string> &mp,
std::error_code& ec)
-> std::filesystem::space_info
{
return mp ? std::filesystem::space(*mp, ec)
: std::filesystem::space_info{};
}
auto restoreDialogText(const QStringList& sources,
const QString& destination) -> QString
{
qDebug() << "linked to" << QUrl::fromLocalFile(destination).toString();
return QString("Are you sure that you want to restore to "
"<a href=\"%1\">%2</a> the following %3 selected %4?")
.arg(QUrl::fromLocalFile(destination).toEncoded(), destination)
.arg(sources.size())
.arg(sources.size() == 1? "path": "paths");
}
struct TableColumnData
{
const char *text{};
const char *toolTip{};
Qt::Alignment texAlignment{Qt::AlignCenter};
};
void setHorizontalHeaderItems(QTableWidget *tbl,
const std::map<int, TableColumnData> &columns)
{
tbl->setColumnCount(static_cast<int>(columns.size()));
for (const auto& [index, data]: columns) {
const auto item = new QTableWidgetItem;
item->setText(QCoreApplication::translate("MainWindow", data.text));
item->setToolTip(QCoreApplication::translate("MainWindow", data.toolTip));
item->setTextAlignment(data.texAlignment);
tbl->setHorizontalHeaderItem(index, item);
}
}
auto totalHeight(QTableWidget *tableView) -> int
{
auto result = 0;
const auto count = tableView->rowCount();
for (int i = 0; i < count; ++i) {
if (!tableView->isRowHidden(i)) {
result += tableView->rowHeight(i);
}
}
if (tableView->horizontalScrollBar()->isVisible()) {
result += tableView->horizontalScrollBar()->height();
}
if (tableView->horizontalHeader()->isVisible()) {
result += tableView->horizontalHeader()->height();
}
result += tableView->frameWidth() * 2;
return std::max(result, emptyTableMaxHeight);
}
}
MainWindow::MainWindow(QWidget *parent):
QMainWindow(parent),
directoryReaderThreadPool(new QThreadPool(this)),
actionAbout(new QAction(this)),
actionQuit(new QAction(this)),
actionSettings(new QAction(this)),
centralWidget(new QSplitter(this)),
destinationsFrame(new QFrame(this->centralWidget)),
destinationsLayout(new QVBoxLayout()),
destinationsLabel(new QLabel(this->destinationsFrame)),
destinationsTable(new QTableWidget(this->destinationsFrame)),
machinesFrame(new QFrame(this->centralWidget)),
machinesLabel(new QLabel(this->machinesFrame)),
machinesTable(new QTableWidget(this->machinesFrame)),
machinesLayout(new QVBoxLayout()),
volumesFrame(new QFrame(this->centralWidget)),
volumesLabel(new QLabel(this->volumesFrame)),
volumesTable(new QTableWidget(this->volumesFrame)),
volumesLayout(new QVBoxLayout()),
backupsFrame(new QFrame(this->centralWidget)),
backupsLabel(new QLabel(this->backupsFrame)),
backupsTable(new QTableWidget(this->backupsFrame)),
backupsActionsFrame(new QFrame(this->backupsFrame)),
deletingPushButton(new QPushButton(this->backupsActionsFrame)),
verifyingPushButton(new QPushButton(this->backupsActionsFrame)),
uniqueSizePushButton(new QPushButton(this->backupsActionsFrame)),
restoringPushButton(new QPushButton(this->backupsActionsFrame)),
backupsActionsLayout(new QHBoxLayout()),
backupsLayout(new QVBoxLayout()),
menubar(new QMenuBar(this)),
menuActions(new QMenu(this->menubar)),
statusbar(new QStatusBar(this)),
toolBar(new QToolBar(this)),
destinationsTimer(new QTimer(this)),
statusTimer(new QTimer(this)),
pathInfoTimer(new QTimer{this})
{
static const auto destinationsTableColumns = std::map<int, TableColumnData>{
{DestsColumn::Name, {"Name", "Destination name, also refered to as a volume name."}},
{DestsColumn::ID, {"ID", "Identifier for destination."}},
{DestsColumn::Kind, {"Kind", "The kind of the destination."}},
{DestsColumn::Mount, {"Mount Point", "Path at which the destination is mounted at."}},
{DestsColumn::Use, {"Usage", "Percent usage of the mounted destination."}},
{DestsColumn::Capacity,
{"Capacity",
"Capacity of the destination.",
Qt::AlignTrailing|Qt::AlignVCenter}},
{DestsColumn::Free,
{"Free",
"Free space within the destination.",
Qt::AlignTrailing|Qt::AlignVCenter}},
{DestsColumn::Action, {"Action", "Backup action for the destination."}},
{DestsColumn::BackupStat,
{"Backup Status",
"Backup phase & more when backup running."}},
};
static const auto machinesTableColumns = std::map<int, TableColumnData>{
{MachinesColumn::Name, {"Name", "Machine name."}},
{MachinesColumn::Uuid, {"UUID", "Universal unique ID of the named machine."}},
{MachinesColumn::Model, {"Model", "Model of the machine."}},
{MachinesColumn::Address, {"Address", "Primary MAC address of machine."}},
{MachinesColumn::Destinations,
{"Destinations",
"Number of destinations where backups for the machine can be found.",
Qt::AlignTrailing|Qt::AlignVCenter}},
{MachinesColumn::Volumes,
{"Volumes",
"Number of unique volumes in backups for the machines.",
Qt::AlignTrailing|Qt::AlignVCenter}},
{MachinesColumn::Backups,
{"Backups",
"Number of backups found for the machine.",
Qt::AlignTrailing|Qt::AlignVCenter}},
};
static const auto volumesTableColumns = std::map<int, TableColumnData>{