/
MainWindow.cpp
836 lines (676 loc) · 23.1 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
#include <QFileDialog>
#include <QStandardPaths>
#include <QCloseEvent>
#include <QtDebug>
#include <QFuture>
#include <QtConcurrent>
#include <QMessageBox>
#include <QAction>
#include "Logger.h"
#include "crypto/FilesEncrypt.h"
#include "crypto/SessionKey.h"
#include "MainWindow.h"
#include "ui/ui_MainWindow.h"
#include "utilities.h"
#include <QDesktopServices>
#include <QDesktopWidget>
#include <cassert>
#include <iostream>
#define BASE_DIR_PARAM_NAME "BASE_DIRECTORY"
#define UPDATE_FETCH_URL "https://www.filesencrypt.com/update/current.xml"
#define UPDATE_DOWNLOAD_URL "https://www.filesencrypt.com/update/"
QMutex MainWindow::s_encryptMutex;
unsigned MainWindow::s_current_guess_encrypted_watchers = 0;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
m_update{UPDATE_FETCH_URL, UPDATE_DOWNLOAD_URL}
{
ui->setupUi(this);
setAcceptDrops(true);
setWindowTitle(qApp->applicationName() + " v" + Version{qApp->applicationVersion()}.getVersionStr().c_str());
m_settings = new QSettings;
updateAvailableButtons();
ui->filesList->setModel(&m_filesListModel);
ui->filesList->horizontalHeader()->setSectionResizeMode(
0, QHeaderView::Stretch);
ui->filesList->horizontalHeader()->setSectionResizeMode(
1, QHeaderView::Stretch);
ui->filesList->horizontalHeader()->setSectionResizeMode(
2, QHeaderView::Stretch);
ui->filesList->setSelectionBehavior(QTableView::SelectRows);
// Center item
setGeometry(
QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
size(),
qApp->desktop()->availableGeometry()
)
);
m_choose_key = new ChooseKey(&m_filesEncrypt, this);
connect(m_choose_key, SIGNAL(keyDone()), this, SLOT(keySelected()));
m_choose_key->setWindowModality(Qt::WindowModal);
correctResize();
connect(ui->action_retrieveKey, SIGNAL(triggered(bool)), this, SLOT(displayKey()));
connect(ui->action_openSettings, SIGNAL(triggered(bool)), this, SLOT(openSettings()));
connect(ui->action_checkForUpdates, &QAction::triggered, [this]{
m_update.showUpdateDialogIfUpdateAvailable(m_settings->value("check_beta", SettingsWindow::getDefaultSetting("check_beta")).toBool(), true, this);
});
m_statusBarLabel = new QLabel{statusBar()};
m_statusBarLabel->setStyleSheet("*{"
"margin-left: 15px;"
"}");
m_statusBarLabel->setAlignment(Qt::AlignLeft);
statusBar()->addPermanentWidget(m_statusBarLabel, 1);
updateStatusBar();
statusBar()->show();
m_addWhateverMenu = new QMenu(this);
QAction* dir = new QAction(tr("Importer des dossiers"), m_addWhateverMenu);
QAction* file = new QAction(tr("Importer des fichiers"), m_addWhateverMenu);
connect(dir, SIGNAL(triggered(bool)), this, SLOT(select_dir()));
connect(file, SIGNAL(triggered(bool)), this, SLOT(select_file()));
m_addWhateverMenu->addAction(dir);
m_addWhateverMenu->addAction(file);
m_listRowMenu = new QMenu(this);
QAction* openDir = new QAction(tr("Ouvrir le dossier"), m_listRowMenu);
connect(openDir, SIGNAL(triggered(bool)), this, SLOT(openSelectedRowInDir()));
ui->filesList->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->filesList, &QTableView::customContextMenuRequested, [this](const QPoint &p){
Q_UNUSED(p);
m_listRowMenu->exec(QCursor::pos());
});
m_listRowMenu->addAction(openDir);
_sessionKey = new SessionKey{this};
if(_sessionKey->sessionKeyExists()){
ui->action_saveSessionKey->setEnabled(false);
}
m_update.showUpdateDialogIfUpdateAvailable(m_settings->value("check_beta", SettingsWindow::getDefaultSetting("check_beta")).toBool(), false, this);
}
MainWindow::~MainWindow(){
delete _sessionKey;
delete m_progress;
delete m_choose_key;
delete m_filesEncrypt;
delete m_settings;
delete ui;
}
void MainWindow::updateStatusBar(){
if(m_filesEncrypt == nullptr){
m_statusBarLabel->setText(tr("Clé non chargée"));
}else if(!m_filesEncrypt->isFileKeyLoaded()){
m_statusBarLabel->setText(tr("Clé aes brute chargée"));
}else if(m_filesEncrypt->isAesDecrypted()){
m_statusBarLabel->setText(tr("Clé chargée, prêt"));
}else{
m_statusBarLabel->setText(tr("Clé chargée mais encryptée"));
}
}
void MainWindow::openSelectedRowInDir(){
showInGraphicalShell(getCurrentDir());
}
void MainWindow::showInGraphicalShell(const QString &pathIn){
#if defined(Q_OS_WIN)
openInExplorer(pathIn);
#elif defined(Q_OS_LINUX)
openInNautilus(pathIn);
#else
QMessageBox::warning(this, "Not supported yet", "Sorry, but this functionnality is not supported yet for other than Windows and Linux Systems", QMessageBox::Ok);
#endif
}
void MainWindow::openInNautilus(const QString &pathIn){
QStringList args;
args << QDir::toNativeSeparators(pathIn);
QProcess *process = new QProcess(this);
process->start("nautilus", args);
}
void MainWindow::openInExplorer(const QString &pathIn){
QStringList args;
args << "/select," << QDir::toNativeSeparators(pathIn);
QProcess *process = new QProcess(this);
process->start("explorer.exe", args);
}
bool MainWindow::beSureKeyIsSelectedAndValid(std::function<void()> func, bool forceAskKey){
// If a key is properly loaded (decrypted aes can be accessed)
if(m_filesEncrypt != nullptr && m_filesEncrypt->isAesDecrypted() && (!m_filesEncrypt->isFileKeyLoaded() || !forceAskKey))
return true;
// Key is still encrypted
if(m_filesEncrypt != nullptr){
bool passOk{false};
while(!passOk){
bool ok;
activateWindow();
QString const pass{ChooseKey::askPassword(false, &ok, this)};
if(!ok) return false;
m_filesEncrypt->requestAesDecrypt(pass.toStdString(), &passOk);
}
return true;
}else{ // There is no key
static QMetaObject::Connection oldConnection;
disconnect(oldConnection);
oldConnection = connect(m_choose_key, &ChooseKey::keyDone, [this, func]{
func();
disconnect(oldConnection);
});
m_choose_key->show();
}
return false;
}
void MainWindow::updateAvailableButtons(){
// No key loaded
if(m_filesEncrypt == nullptr){
ui->action_saveKey->setEnabled(false);
}else{
ui->action_saveKey->setEnabled(true);
}
unsigned decrypted{0};
unsigned encrypted{0};
// If no entries, all buttons must be greyed out
if(m_filesListModel.rowCount() == 0){
ui->remove->setEnabled(false);
ui->cryptAll->setEnabled(false);
ui->decryptAll->setEnabled(false);
return;
}
ui->remove->setEnabled(true);
// if there are workers guessing the entries's state, some entries might have a NOT_FINISHED state so we can't change the buttons state
if(s_current_guess_encrypted_watchers > 0) return;
unsigned totalSize = 0;
for(auto const& dir : m_filesListModel.getDirs()){
// If at least one entry is partially encrypted, all the buttons have to be enabled so we can return after
totalSize += dir.sizeBytes;
if(*dir.state == PARTIAL){
ui->cryptAll->setEnabled(true);
ui->decryptAll->setEnabled(true);
return;
}else if(*dir.state == ENCRYPT){
encrypted++;
}else if(*dir.state == DECRYPT){
decrypted++;
}else{
assert(false && "This function must be called only when the state of each entry is known");
}
}
// All are encrypted
if(totalSize == 0){
ui->cryptAll->setEnabled(false);
ui->decryptAll->setEnabled(false);
}else if(decrypted == 0){
ui->cryptAll->setEnabled(false);
ui->decryptAll->setEnabled(true);
}else if(encrypted == 0){
// All are decrypted
ui->cryptAll->setEnabled(true);
ui->decryptAll->setEnabled(false);
}else{
// Some are encrypted, some are decrypted, no partial
ui->cryptAll->setEnabled(true);
ui->decryptAll->setEnabled(true);
}
}
void MainWindow::displayKey(bool forceAsk){
if(!beSureKeyIsSelectedAndValid([this]{displayKey(false);}, forceAsk && (m_filesEncrypt != nullptr && m_filesEncrypt->isFileKeyLoaded()))) return;
SecureMemBlock aes = m_filesEncrypt->getAES();
QString key;
for(quint8 i(0); i < 32; ++i){
key += QString{"%1"}.arg(*(aes.getData() + i), 2, 16, QChar{'0'}).toUpper() + " ";
}
QMessageBox keyBox{this};
keyBox.setDefaultButton(QMessageBox::Ok);
keyBox.setText(tr("Votre clé est ") + key);
keyBox.setWindowTitle("Your key");
keyBox.setStyleSheet("*{ messagebox-text-interaction-flags: 5 }");
keyBox.exec();
}
void MainWindow::openSettings(){
m_settings_window = new SettingsWindow(this);
connect(m_settings_window, SIGNAL(closed()), this, SLOT(closeSettings()));
m_settings_window->setWindowModality(Qt::WindowModal);
m_settings_window->show();
}
void MainWindow::closeSettings(){
m_settings_window->deleteLater();
}
void MainWindow::keySelected(){
updateStatusBar();
if(m_filesEncrypt == nullptr) return;
connect(m_filesEncrypt, SIGNAL(keyDecrypted()), this, SLOT(updateStatusBar()));
connect(m_filesEncrypt, SIGNAL(keyEncrypted()), this, SLOT(updateStatusBar()));
delete m_progress;
m_progress = new Progress(&m_filesEncrypt, this);
m_progress->setFixedSize(m_progress->size());
updateAvailableButtons();
}
void MainWindow::closeEvent(QCloseEvent *event){
QMainWindow::closeEvent(event);
if(FilesEncrypt::getPendingCrypt() != 0){
event->ignore();
return;
}
QMainWindow::closeEvent(event);
EVP_cleanup();
QApplication::quit();
}
void MainWindow::dragEnterEvent(QDragEnterEvent * event){
event->accept();
}
void MainWindow::dragLeaveEvent(QDragLeaveEvent *event){
event->accept();
}
void MainWindow::dragMoveEvent(QDragMoveEvent *event){
event->accept();
}
/**
* Called when a/some file(s)/directory(ies) is/are dropped in the mainwindow
* Adds the entries in the list and process them
* @brief MainWindow::dropEvent
* @param event
*/
void MainWindow::dropEvent(QDropEvent *event){
event->accept();
if(event->mimeData()->hasUrls()){
auto urls = event->mimeData()->urls();
for(QUrl const& url : urls){
QString urlStr{url.path()};
#ifdef Q_OS_WIN
urlStr = urlStr.remove(0, 1);
#endif
if(urls.length() == 1){ // If there is only one single file, it might be the key
QFile f{urlStr};
// File can be opened & this is actually a key & we may remove the key
if(f.open(QFile::ReadOnly) && FilesEncrypt::isValidKey(f) && deleteKey()){
m_filesEncrypt = new FilesEncrypt{urlStr.toStdString()};
beSureKeyIsSelectedAndValid([](){}, true);
keySelected();
return;
}
}
addWhateverToList(urlStr);
}
}
}
void MainWindow::correctResize(){
ui->filesList->setColumnWidth(3, ui->filesList->width() * 0.65);
}
void MainWindow::resizeEvent(QResizeEvent *event){
Q_UNUSED(event);
correctResize();
}
void MainWindow::showEvent(QShowEvent *event){
Q_UNUSED(event);
correctResize();
}
void MainWindow::guessEncryptedFinished(QFutureWatcher<QPAIR_CRYPT_DEF>* watcher, CryptInfos &item) const{
// Retrieve results
QList<QPAIR_CRYPT_DEF> res{watcher->future().results()};
Q_FOREACH(auto const i, res){
EncryptDecrypt_light& fInfo{item.files[i.first]};
fInfo.offsetBeforeContent = i.second.offsetBeforeContent;
*(fInfo.state) = i.second.state;
}
changeRootState(item);
}
void MainWindow::changeRootState(CryptInfos &item, bool fileModified) const{
auto length = item.isFile ? 1 : item.files.size();
unsigned crypted = 0;
unsigned uncrypted = 0;
if(!item.isFile){
for(auto const& i : item.files){
if(*(i.state) == EncryptDecrypt::ENCRYPT){
++crypted;
}else if(*(i.state) == EncryptDecrypt::DECRYPT){
++uncrypted;
}
if(crypted != 0 && uncrypted != 0){
crypted = 1;
uncrypted = 1;
break;
}
}
}else{
if(*item.state == EncryptDecrypt::ENCRYPT){
crypted = 1;
}else if(*item.state == EncryptDecrypt::DECRYPT){
uncrypted = 1;
}
}
if(length == 0 || uncrypted == length){
item.stateStr = tr("Non");
*item.state = DECRYPT;
}else if(crypted == length){
item.stateStr = tr("Oui");
*item.state = ENCRYPT;
}else{
item.stateStr = "-";
*item.state = PARTIAL;
}
if(fileModified)
Q_EMIT root_done();
}
QPAIR_CRYPT_DEF MainWindow::guessEncrypted(QString const& file){
QFileInfo fInfo(file);
QFile f(fInfo.absoluteFilePath());
f.open(QFile::ReadOnly);
auto res = FilesEncrypt::guessEncrypted(f);
if(res.state == EncryptDecrypt::ENCRYPT){
Logging::Logger::debug(tr("Le fichier %1 est encrypté").arg(fInfo.absoluteFilePath()));
}
return QPAIR_CRYPT_DEF{file, res};
}
finfo_s MainWindow::encrypt(QString const &file, EncryptDecrypt action) const{
QFile f(file);
finfo_s res;
res.success = false;
if(f.open(QFile::ReadWrite)){
res = m_filesEncrypt->encryptFile(&f, action, m_settings->value("encrypt_filenames", SettingsWindow::getDefaultSetting("encrypt_filenames")).toBool());
f.close();
}else{
Logging::Logger::error("Can't open file " + file);
}
return res;
}
/**
* Emits finishedDiscover when all the files added with addWhateverToList have been processed
* @brief MainWindow::checkNoFilesProcessingToList
*/
void MainWindow::checkNoFilesProcessingToList() const{
if(_current_adding_items == 0){
Q_EMIT finishedDiscover();
}
}
void MainWindow::addWhateverToList(QStringList const& items){
_current_adding_items += items.length();
Q_FOREACH(const auto& item, items){
addWhateverToList(item, true);
}
}
void MainWindow::addWhateverToList(QString const& item, bool fromMany){
if(!fromMany) _current_adding_items++;
if(!item.isEmpty() && !m_filesListModel.getDirs().contains(item)){ // Pre-conditions
CryptInfos infos; // All the informations about an entry (a complete recursive directory or a file)
QFileInfo info(item);
// Will be directly filled with one file if item is not a directory or with a thread if it is a directory
QMap<QString, EncryptDecrypt_light> filesAndState;
// Store items to re-use them later
infos.stateStr = "...";
infos.name = item;
infos.size = "...";
infos.sizeBytes = 0;
infos.isFile = false;
infos.watcher = nullptr;
infos.recursiveWatcher = nullptr;
if(info.isDir()){
// Create the watchers
QFutureWatcher<QPAIR_CRYPT_DEF>* watcher = new QFutureWatcher<QPAIR_CRYPT_DEF>;
s_current_guess_encrypted_watchers++;
QFutureWatcher<FilesAndSize>* watcherRecursiveFilesDiscover = new QFutureWatcher<FilesAndSize>;
// Attach the watchers
infos.watcher = watcher;
infos.recursiveWatcher = watcherRecursiveFilesDiscover;
connect(watcher, &QFutureWatcher<QPAIR_CRYPT_DEF>::finished, [this, watcher, item](){
s_current_guess_encrypted_watchers--;
_current_adding_items--;
if(!watcher->isCanceled()){
auto &infos{m_filesListModel.getDir(item)};
guessEncryptedFinished(watcher, infos);
m_filesListModel.update(item);
updateAvailableButtons();
infos.watcher = nullptr;
}else{
Logging::Logger::debug("Encrypted guess watcher canceled");
}
checkNoFilesProcessingToList();
watcher->deleteLater();
});
connect(watcherRecursiveFilesDiscover, &QFutureWatcher<FilesAndSize>::finished, [this, item, watcher, watcherRecursiveFilesDiscover](){
if(!watcherRecursiveFilesDiscover->isCanceled()){
CryptInfos &infos{m_filesListModel.getDir(item)};
FilesAndSize res{watcherRecursiveFilesDiscover->result()};
infos.size = utilities::speed_to_human(res.size);
infos.sizeBytes = res.size;
QStringList &files = res.files;
Q_FOREACH(auto const& file, files){
EncryptDecrypt_light state;
state.offsetBeforeContent = 0; // Will be set in guessEncryptedFinished
state.state = new EncryptDecrypt{NOT_FINISHED};
infos.files[file] = state;
}
QFuture<QPAIR_CRYPT_DEF> future = QtConcurrent::mapped(infos.files.keys(), &MainWindow::guessEncrypted);
watcher->setFuture(future);
infos.recursiveWatcher = nullptr;
m_filesListModel.update(item);
}
watcherRecursiveFilesDiscover->deleteLater();
});
// Add the files to the list
QFuture<FilesAndSize> future{QtConcurrent::run(FilesEncrypt::getFilesFromDirRecursive, QDir{item})};
watcherRecursiveFilesDiscover->setFuture(future);
infos.type = tr("Dossier");
infos.state = new EncryptDecrypt(NOT_FINISHED);
}else{
infos.isFile = true;
// Add the single file to the list
QPAIR_CRYPT_DEF guess{guessEncrypted(item)};
EncryptDecrypt_light state;
state.offsetBeforeContent = guess.second.offsetBeforeContent;
state.state = new EncryptDecrypt{guess.second.state};
filesAndState[info.absoluteFilePath()] = state;
infos.state = new EncryptDecrypt{guess.second.state};
changeRootState(infos);
// Show the type
infos.type = tr("Fichier");
infos.size = utilities::speed_to_human(info.size());
infos.sizeBytes = info.size();
}
infos.files = filesAndState;
m_filesListModel.insert(item, infos);
m_filesListModel.update(item);
if(infos.isFile){
updateAvailableButtons();
_current_adding_items--;
checkNoFilesProcessingToList();
}
}else{
Q_EMIT finishedDiscover();
}
}
void MainWindow::select_file(){
QStringList list = QFileDialog::getOpenFileNames(
this,
tr("Sélectionner des fichiers"),
get_base_dir()
);
if(!list.isEmpty())
set_base_dir(list[0]);
addWhateverToList(list);
}
void MainWindow::select_dir(){
QString name = QFileDialog::getExistingDirectory(
this,
tr("Sélectionner des dossiers"),
get_base_dir()
);
set_base_dir(name);
addWhateverToList(name);
}
QString MainWindow::get_base_dir() const{
return m_settings->value(BASE_DIR_PARAM_NAME, QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)).toString();
}
void MainWindow::set_base_dir(QString const &dir){
m_settings->setValue(BASE_DIR_PARAM_NAME, dir);
}
void MainWindow::on_importButton_clicked(){
m_addWhateverMenu->exec(QCursor::pos());
}
void MainWindow::on_decryptAll_clicked(){
action(EncryptDecrypt::DECRYPT);
}
void MainWindow::on_cryptAll_clicked(){
action(EncryptDecrypt::ENCRYPT);
}
bool MainWindow::allTasksDone(EncryptDecrypt action){
if(action == PARTIAL) throw std::runtime_error("Action can not be partial");
for(QMap<QString, CryptInfos>::const_iterator it = m_filesListModel.getDirs().constBegin(); it != m_filesListModel.getDirs().constEnd(); ++it){
if(*(it.value().state) != action) return false;
}
return true;
}
void MainWindow::action(EncryptDecrypt action){
if(m_encrypting || m_filesListModel.rowCount() == 0 || _current_adding_items > 0) return;
_lastAction = action;
if(!beSureKeyIsSelectedAndValid([this, action]{
this->action(action);
})) return;
m_encrypting = true;
qint64 max{0};
qint64 items_number{0};
qint64 item_does_not_need_action{0};
// Ask password to decrypt aes if aes has been deleted
if(!m_filesEncrypt->isAesDecrypted()){
bool passOk{false};
while(!passOk){
bool ok;
QString const pass(ChooseKey::askPassword(false, &ok, this));
if(!ok) return;
passOk = m_filesEncrypt->requestAesDecrypt(pass.toStdString());
}
}
for(auto const& item : m_filesListModel.getDirs().values()){
bool problemWrite{false};
// For each file in the dir, or one file
for(QMap<QString, EncryptDecrypt_light>::const_iterator it = item.files.constBegin(); it != item.files.constEnd(); ++it) {
++items_number;
QFileInfo f{it.key()};
EncryptDecrypt_light const& state{it.value()};
// If current state != from what you'd do
if(*state.state != action && f.isWritable()){
if(action == EncryptDecrypt::ENCRYPT){
max += f.size();
}else{
max += f.size() - state.offsetBeforeContent;
}
}else{
if(!f.isWritable()){
qDebug() << "!!!" << it.key();
problemWrite = true;
}
++item_does_not_need_action;
}
QCoreApplication::processEvents();
}
if(problemWrite){
QMessageBox::warning(
this,
tr("Write protection"),
tr("Some files are write protected (perhaps privileges too low), they won't be encrypted/decrypted")
);
}
}
// If at least one op is necessary
if(item_does_not_need_action != items_number){
// Show the progress bar and set the max
m_progress->setFileMax(items_number - item_does_not_need_action);
m_progress->setMax(max);
for(QMap<QString, CryptInfos>::const_iterator it{m_filesListModel.getDirs().constBegin()}; it != m_filesListModel.getDirs().constEnd(); ++it){
CryptInfos& item{m_filesListModel.getDir(it.key())};
QString orig_name{it.key()};
if(*item.state != action){ // Check again and avoid to do any action if it's not needed
item.stateStr = tr("En cours...");
QFutureWatcher<void>* watcher = new QFutureWatcher<void>;
QStringList const *l = new QStringList{item.files.keys()};
connect(watcher, &QFutureWatcher<void>::finished, [this, watcher, &item, l, orig_name](){
delete l;
changeRootState(item, true);
m_encrypting = false;
Q_EMIT file_done();
if(FilesEncrypt::getPendingCrypt() == 0){
Crypt::setAborted(false);
Crypt::setPaused(false);
updateAvailableButtons();
}
m_filesListModel.update(orig_name);
watcher->deleteLater();
});
std::function<void(QString const &)> func = [this, action, &item](QString const &file){
s_encryptMutex.lock(); // Lock this
EncryptDecrypt_light state = item.files[file]; // Current infos of the file
s_encryptMutex.unlock();
if(*state.state != action){
finfo_s encrypt_result = encrypt(file, action);
*state.state = encrypt_result.state;
// If single file, also change global state
if(item.isFile)
*item.state = encrypt_result.state;
if(encrypt_result.success){
s_encryptMutex.lock(); // Lock this
// Because the filename changed, we delete the concerned file and recreate it with the appropriate name
item.files.remove(file);
item.files.insert(encrypt_result.name, {state.state, encrypt_result.offsetBeforeContent});
if(item.isFile){
item.name = encrypt_result.name;
}
s_encryptMutex.unlock();
}
}
};
QFuture<void> future = QtConcurrent::map(*l, func);
watcher->setFuture(future);
m_progress->encryptionStarted();
m_progress->show();
}
}
}else{
m_encrypting = false;
}
}
QString MainWindow::getCurrentDir() const{
int const row{ui->filesList->currentIndex().row()};
return m_filesListModel.getDirs().keys().at(row);
}
void MainWindow::on_remove_clicked(){
int const row{ ui->filesList->currentIndex().row() };
if(row >= 0){
CryptInfos const& c{m_filesListModel.getDir(getCurrentDir())};
if(c.recursiveWatcher != nullptr){
c.recursiveWatcher->cancel();
c.recursiveWatcher->waitForFinished();
}
if(c.watcher != nullptr){
c.watcher->cancel();
c.watcher->waitForFinished();
}
for(QMap<QString, EncryptDecrypt_light>::const_iterator it{c.files.constBegin()}; it != c.files.constEnd(); ++it){
delete it.value().state;
}
delete c.state;
m_filesListModel.remove(getCurrentDir());
updateAvailableButtons();
}else if(m_filesListModel.getDirs().size() > 0){
m_filesListModel.removeLast();
}
}
bool MainWindow::deleteKey(){
if(FilesEncrypt::getPendingCrypt() > 0) return false;
delete m_filesEncrypt;
m_filesEncrypt = nullptr;
return true;
}
void MainWindow::on_action_newKey_triggered(){
if(deleteKey())
beSureKeyIsSelectedAndValid([](){}, false);
}
void MainWindow::on_action_saveKey_triggered(){
if(beSureKeyIsSelectedAndValid([](){}, true)){
m_choose_key->saveAESToFile();
}
}
void MainWindow::on_action_saveSessionKey_triggered(){
#ifndef Q_OS_WIN
QMessageBox::information(this, tr("Non disponible"), tr("Cette fonction n'est uniquement disponible que pour les systemes Windows"), QMessageBox::Ok);
#else
connect(_sessionKey, &SessionKey::keyReady, [this](){
ui->action_saveSessionKey->setEnabled(false);
});
_sessionKey->checkForSessionKey(false);
#endif
}