-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
1622 lines (1408 loc) · 53.5 KB
/
Copy pathmainwindow.cpp
File metadata and controls
1622 lines (1408 loc) · 53.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 <QCryptographicHash>
#include <QDir>
#include <QFile>
#include <QFileDialog>
#include <QFileSystemModel>
#include <QImageReader>
#include <QMessageBox>
#include <QProcess>
#include "language.h"
#include <QSettings>
#include <QStorageInfo>
#include "aboutdialog.h"
#if defined(__APPLE__)
#include "externalDriveFetcher.h"
#endif
#include "filecopydialog.h"
#include "fileinfomodel.h"
#include "presetdialog.h"
#include "qborderlessdialog.h"
#include "selectcarddialog.h"
#include "ui_mainwindow.h"
#include <libraw/libraw.h>
#include <QJsonDocument>
#include <QShortcut>
#include <QTimer>
QFileInfoList MainWindow::getFileListFromDir(const QString &directory) {
QDir qdir(directory);
// Files only, readable, do not follow symlinks (prevents odd loops)
qdir.setFilter(QDir::Files | QDir::NoSymLinks | QDir::Readable);
const QStringList patterns = QStringList()
<< "*.3fr" << "*.ari" << "*.arw" << "*.arq" << "*.bay"
<< "*.braw" << "*.crw" << "*.cr2" << "*.cr3" << "*.cap"
<< "*.data" << "*.dcs" << "*.dcr" << "*.dng" << "*.drf"
<< "*.eip" << "*.erf" << "*.fff" << "*.gpr" << "*.heic"
<< "*.iiq" << "*.k25" << "*.kdc" << "*.mdc" << "*.mef"
<< "*.mos" << "*.mrw" << "*.nef" << "*.nrw" << "*.obm"
<< "*.orf" << "*.pef" << "*.ptx" << "*.pxn" << "*.r3d"
<< "*.raf" << "*.raw" << "*.rwl" << "*.rw2" << "*.rwz"
<< "*.sr2" << "*.srf" << "*.srw" << "*.tif" << "*.x3f"
<< "*.jpg" << "*.jpeg" << "*.mov" << "*.mp4" << "*.flv"
<< "*.avi" << "*.wmv" << "*.wav" << "*.avchd" << "*.srt";
QFileInfoList fileList = qdir.entryInfoList(patterns, QDir::Files);
// Recurse into subdirectories (no dot entries, no symlinks)
QDir subdirIter(directory);
const QFileInfoList subdirs = subdirIter.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks | QDir::Readable);
for (const QFileInfo &subdir : subdirs) {
fileList << getFileListFromDir(subdir.absoluteFilePath());
}
return fileList;
}
// Tint a monochrome glyph (black with alpha) to the given colour, so icons
// stay visible in both light and dark mode.
static QIcon tintedIcon(const QString &resourcePath, const QColor &color)
{
QPixmap pixmap(resourcePath);
QPainter painter(&pixmap);
painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
painter.fillRect(pixmap.rect(), color);
painter.end();
return QIcon(pixmap);
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow) {
m_appStartTimer.start();
ui->setupUi(this);
ui->menubar->hide();
ui->presets->hide();
updateThemedIcons();
// The preview label must not claim its pixmap size as minimum size,
// otherwise the splitter cannot move and the window cannot shrink. The
// explicit 1x1 minimum overrides the pixmap-based minimumSizeHint;
// Expanding lets it take the available space (Ignored would let the
// spacers collapse it to zero height). The pixmap is rescaled to the
// label in rescalePreview().
ui->image->setMinimumSize(1, 1);
ui->image->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
// All extra vertical space in the right pane goes to the preview group
ui->verticalLayout_2->setStretchFactor(ui->groupBox_2, 1);
// Labels with long dynamic text (card name, example output path) must not
// dictate the pane's minimum width; an explicit minimum lets them be
// clipped instead of blocking the splitter.
ui->cardLabel->setMinimumWidth(50);
ui->importToLabel->setMinimumWidth(50);
// Divider between the file table and the preview/settings pane; the
// position is restored from the previous session.
ui->mainSplitter->setStretchFactor(0, 1);
ui->mainSplitter->setStretchFactor(1, 1);
connect(ui->mainSplitter, &QSplitter::splitterMoved, this,
[this](int, int) { rescalePreview(); });
{
QSettings uiSettings;
const QByteArray state = uiSettings.value("mainSplitterState").toByteArray();
if (!state.isEmpty())
ui->mainSplitter->restoreState(state);
const QByteArray geometry = uiSettings.value("mainWindowGeometry").toByteArray();
if (!geometry.isEmpty())
restoreGeometry(geometry);
}
QSettings settings;
loadPresetsLocations();
loadProjectName();
loadFileNameFormat();
// updateImportToLabel();
setWindowTitle(QString("QuickImport %1").arg(QCoreApplication::applicationVersion()));
md5Check = settings.value("md5Check", false).toBool();
ejectAfterImport = settings.value("ejectAfterImport", false).toBool();
deleteAfterImport = settings.value("deleteAfterImport", false).toBool();
previewImage = settings.value("previewImage", true).toBool();
deleteExisting = settings.value("deleteExisting", false).toBool();
quitEmptyCard = settings.value("quitEmptyCard", false).toBool();
quitAfterImport = settings.value("quitAfterImport", false).toBool();
ejectIfEmpty = settings.value("ejectIfEmpty", false).toBool();
doBackupImport = settings.value("doBackupImport", false).toBool();
openApplicationAfterImport = settings.value("openApplicationAfterImport", false).toBool();
ui->OpenApplicationLocation->setEnabled(openApplicationAfterImport);
ui->openApplicationAfterImport->setCheckState(openApplicationAfterImport ? Qt::Checked
: Qt::Unchecked);
openApplicationLocation = settings.value("openApplicationLocation", "").toString();
updateOpenApplicationLabel();
populateLanguageComboBox();
ui->deleteAfterImportBox->setCheckState(deleteAfterImport ? Qt::Checked : Qt::Unchecked);
ui->ejectBox->setCheckState(ejectAfterImport ? Qt::Checked : Qt::Unchecked);
ui->mdCheckBox->setCheckState(md5Check ? Qt::Checked : Qt::Unchecked);
ui->previewImageCheckBox->setCheckState(previewImage ? Qt::Checked
: Qt::Unchecked);
ui->deleteExistingBox->setCheckState(deleteExisting ? Qt::Checked
: Qt::Unchecked);
ui->quitEmptyCardBox->setCheckState(quitEmptyCard ? Qt::Checked
: Qt::Unchecked);
ui->quitAfterImportBox->setCheckState(quitAfterImport ? Qt::Checked
: Qt::Unchecked);
ui->ejectIfEmptyBox->setCheckState(ejectIfEmpty ? Qt::Checked
: Qt::Unchecked);
ui->backupBox->setCheckState(doBackupImport ? Qt::Checked : Qt::Unchecked);
connect(ui->deviceWidget, &deviceList::selectedUpdated, this, &MainWindow::selectedUpdated);
connect(ui->deviceWidget, &deviceList::spaceButtonPressed, this, &MainWindow::spaceButtonPressed);
connect(ui->deviceWidget,
&deviceList::returnButtonPressed,
this,
&MainWindow::returnButtonPressed);
connect(ui->deviceWidget, &deviceList::doneLoading, this, &MainWindow::doneLoadingCard);
connect(ui->deviceWidget, &deviceList::selectedNode, this, &MainWindow::selectedNode);
// One persistent preview loader thread for the lifetime of the window
m_previewThread = new QThread(this);
m_previewLoader = new imageLoader();
m_previewLoader->moveToThread(m_previewThread);
connect(m_previewLoader, &imageLoader::imageLoaded, this, &MainWindow::previewLoaded);
connect(m_previewThread, &QThread::finished, m_previewLoader, &QObject::deleteLater);
m_previewThread->start();
QKeySequence shortcutKey(Qt::CTRL | Qt::Key_I);
// Create a shortcut with the specified key sequence
QShortcut *shortcut = new QShortcut(shortcutKey, this);
// Connect the activated() signal of the shortcut to your function
connect(shortcut, &QShortcut::activated, this,
&MainWindow::on_moveButton_clicked);
QKeySequence selectCardKey(Qt::CTRL | Qt::Key_S);
QShortcut *selectCard = new QShortcut(selectCardKey, this);
connect(selectCard, &QShortcut::activated, this,
&MainWindow::on_selectCard_clicked);
QKeySequence ejectCardKey(Qt::CTRL | Qt::Key_E);
QShortcut *ejectCard = new QShortcut(ejectCardKey, this);
connect(ejectCard, &QShortcut::activated, this,
&MainWindow::on_ejectButton_clicked);
QKeySequence reloadKey(Qt::CTRL | Qt::Key_R);
QShortcut *reloadCard = new QShortcut(reloadKey, this);
connect(reloadCard, &QShortcut::activated, this,
&MainWindow::on_reloadButton_clicked);
QMenu *aboutMenu = new QMenu("&About");
QAction *aboutAction = aboutMenu->addAction("About QuickImport", this,
&MainWindow::showAboutDialog);
aboutAction->setMenuRole(QAction::ApplicationSpecificRole);
setMenuBar(ui->menubar);
ui->menubar->addMenu(aboutMenu);
emptyMainWindow();
loadPresets();
const bool showAbout = !settings.value("dontShowAboutDialog", false).toBool();
QTimer::singleShot(0, this, [this, showAbout]() {
if (showAbout) {
showAboutDialog();
}
this->raise();
this->activateWindow();
this->setFocus(Qt::ActiveWindowFocusReason);
on_selectCard_clicked();
});
// XMPEngine test;
}
void MainWindow::updatePresetList() {
ui->presetComboBox->clear();
// Only delete models we created; never delete Qt's internal default model
QAbstractItemModel *old = ui->presetComboBox->model();
ui->presetComboBox->setModel(nullptr);
if (qobject_cast<presetListModel *>(old)) {
delete old;
}
auto *model = new presetListModel(presetList);
ui->presetComboBox->setModel(model);
ui->presetComboBox->setPlaceholderText(tr("--Select to load preset--"));
ui->presetComboBox->setCurrentIndex(-1);
}
void MainWindow::loadPresets() {
QSettings settings;
// Retrieve the stored QByteArray
QByteArray storedByteArray = settings.value("presetSettings").toByteArray();
// Convert the QByteArray back to QJsonArray
QJsonArray storedJsonArray = QJsonDocument::fromJson(storedByteArray).array();
// Convert QJsonArray back to QList<presetSetting>
presetList.clear();
presetList = jsonArrayToPresetSettings(storedJsonArray);
updatePresetList();
}
void MainWindow::loadPresetsLocations() {
QSettings settings;
// settings.setValue("locationPresets", QStringList());
// settings.setValue("PresetLocationLastUsed", -1);
importLocationList = settings.value("locationPresets", QStringList()).toStringList();
importBackupLocationList = settings.value("backupLocationPresets", QStringList()).toStringList();
int sel = settings.value("PresetLocationLastUsed").toInt();
qDebug() << "Import Locatiom Sel" << sel;
resetLocationPreset(sel);
sel = settings.value("PresetBackupLocationLastUsed").toInt();
resetBackupLocationPreset(sel);
}
void MainWindow::savePresetsLocations(int sel = -1) {
QSettings settings;
settings.setValue("locationPresets", importLocationList);
settings.setValue("PresetLocationLastUsed", sel);
}
void MainWindow::saveBackupPresetsLocations(int sel = -1)
{
QSettings settings;
settings.setValue("backupLocationPresets", importBackupLocationList);
settings.setValue("PresetBackupLocationLastUsed", sel);
}
void MainWindow::savePresets() {
qDebug() << "save Presets";
QSettings settings;
// Convert QList<presetSetting> to QJsonArray
QJsonArray jsonArray = presetSettingsToJsonArray(presetList);
// Convert QJsonArray to QByteArray
QByteArray byteArray = QJsonDocument(jsonArray).toJson();
settings.setValue("presetSettings", byteArray);
}
void MainWindow::slotDeviceAdded(const QString &dev) {
qDebug() << "Device added:" << dev;
const QString devicePath = QStringLiteral("/dev/") + dev;
// The disk-appeared event fires when the *device* shows up, usually
// before macOS has mounted the volume. On startup the watcher also
// enumerates the disks that are already present — ignore those, the
// constructor opens the card selection itself.
if (m_appStartTimer.isValid() && m_appStartTimer.elapsed() < 5000)
return;
if (m_pendingInsertedDevices.contains(devicePath))
return;
m_pendingInsertedDevices.insert(devicePath);
waitForVolumeMount(devicePath, 20); // poll up to ~10 s for the mount
}
// Poll until the freshly inserted device is mounted, then ask to open it.
void MainWindow::waitForVolumeMount(const QString &devicePath, int attemptsLeft)
{
if (!m_pendingInsertedDevices.contains(devicePath))
return; // device was removed again in the meantime
for (const QStorageInfo &storage : QStorageInfo::mountedVolumes()) {
if (!storage.isValid() || !storage.isReady())
continue;
const QString mountedDevice = QString::fromUtf8(storage.device());
// Match the device itself or one of its partitions (disk4 -> disk4s1)
if (mountedDevice != devicePath
&& !mountedDevice.startsWith(devicePath + QStringLiteral("s")))
continue;
m_pendingInsertedDevices.remove(devicePath);
if (storage.isReadOnly())
return;
const QString fs = storage.fileSystemType().toLower();
if (!(fs.contains("exfat") || fs.contains("fat") || fs.contains("msdos")))
return; // not a memory card filesystem
if (selectedCard.isValid() && selectedCard.rootPath() == storage.rootPath())
return; // this card is already loaded
askToOpenInsertedCard();
return;
}
if (attemptsLeft <= 0) {
// Never mounted (unformatted disk, mount refused, ...) — give up
m_pendingInsertedDevices.remove(devicePath);
return;
}
QTimer::singleShot(500, this, [this, devicePath, attemptsLeft]() {
waitForVolumeMount(devicePath, attemptsLeft - 1);
});
}
void MainWindow::askToOpenInsertedCard()
{
if (m_insertPromptOpen)
return; // one question at a time
m_insertPromptOpen = true;
const QMessageBox::StandardButton reply
= QMessageBox::question(this,
tr("Card inserted"),
tr("Do you want to open the newly inserted card?"),
QMessageBox::Yes | QMessageBox::No);
m_insertPromptOpen = false;
if (reply == QMessageBox::Yes)
on_selectCard_clicked();
}
void MainWindow::slotDeviceChanged(const QString &dev) {
qDebug("change %s", qPrintable(dev));
}
void MainWindow::slotDeviceRemoved(const QString &dev) {
qDebug() << "Device removed:" << dev;
QString devicePath = QStringLiteral("/dev/") + dev;
m_pendingInsertedDevices.remove(devicePath);
if (selectedCard.device() == devicePath) {
qDebug() << "reload card";
selectedCard = QStorageInfo();
reloadCard();
}
}
void MainWindow::showAboutDialog() {
aboutDialog about;
about.exec();
}
MainWindow::~MainWindow() {
savePresets();
{
QSettings settings;
settings.setValue("mainSplitterState", ui->mainSplitter->saveState());
settings.setValue("mainWindowGeometry", saveGeometry());
}
if (m_previewThread) {
m_previewThread->quit();
m_previewThread->wait();
}
delete ui;
}
void MainWindow::selectedUpdated(int cnt, qint64 size) {
totalSelectedSize = size;
m_selectedCount = cnt;
ui->spaceFilesCopy->setText(
QString(tr("%1 GB")).arg(((float)size / 1000 / 1000 / 1000), 0, 'f', 2));
ui->updateLabel->setText(QString(tr("%1 selected photos")).arg(cnt));
if (cnt <= 0)
ui->moveButton->setDisabled(true);
else {
if (importFolder.size() > 0 && projectName.size() > 0 &&
fileNameFormat.size() > 0) {
ui->moveButton->setDisabled(false);
}
else {
ui->moveButton->setDisabled(true);
}
}
}
void MainWindow::applyCheckToSelection(CheckAction action) {
auto *model = qobject_cast<FileInfoModel *>(ui->deviceWidget->model());
if (!model)
return;
QItemSelectionModel *selectionModel = ui->deviceWidget->selectionModel();
if (!selectionModel)
return;
// For Flip, the first item decides the target state for the whole selection
bool flipTarget = true;
bool flipTargetSet = false;
const QModelIndexList selectedIndexes = selectionModel->selectedIndexes();
for (const QModelIndex &index : selectedIndexes) {
if (!index.isValid())
continue;
const QModelIndex sourceIndex = model->index(index.row(), 0, index.parent());
if (!sourceIndex.isValid())
continue;
TreeNode *node = static_cast<TreeNode *>(sourceIndex.internalPointer());
bool selected = true;
switch (action) {
case CheckAction::Check:
selected = true;
break;
case CheckAction::Uncheck:
selected = false;
break;
case CheckAction::Flip:
if (!flipTargetSet) {
flipTargetSet = true;
flipTarget = !node->isSelected;
}
selected = flipTarget;
break;
}
node->isSelected = selected;
if (!node->isFile) {
if (selected)
model->setSelect(node);
else
model->setDeselect(node);
}
}
model->refreshChecks();
}
void MainWindow::on_checkSelected_clicked() {
applyCheckToSelection(CheckAction::Check);
}
void MainWindow::on_uncheckSelected_clicked() {
applyCheckToSelection(CheckAction::Uncheck);
}
void MainWindow::flipSelectedItems() {
applyCheckToSelection(CheckAction::Flip);
}
QList<QFileInfo> MainWindow::getFiles(QString map) {
QList<QFileInfo> files;
files = getFileListFromDir(map);
qDebug() << "Found # files:" << files.count();
return files;
}
void MainWindow::displayNoCardDialog()
{
QMessageBox msgBox(this);
msgBox.setText(tr("No Card found, please insert card."));
msgBox.setIcon(QMessageBox::Critical);
msgBox.exec();
}
void MainWindow::setBackupUiEnabled(bool enabled)
{
ui->importBackupLocation->setEnabled(enabled);
ui->deleteBackupLocationButton->setEnabled(enabled);
ui->selectBackupLocation->setEnabled(enabled);
ui->freeSpaceBackupLabel->setEnabled(enabled);
ui->freeSpaceBackup->setEnabled(enabled);
}
void MainWindow::saveBoolSetting(const QString &key, bool &member, int state)
{
member = (state == Qt::Checked);
QSettings settings;
settings.setValue(key, member);
}
void MainWindow::on_selectCard_clicked() {
QList<QStorageInfo> cardList;
ui->deviceWidget->setEnabled(false);
foreach (const QStorageInfo &storage, QStorageInfo::mountedVolumes()) {
if (storage.isReadOnly())
{
qDebug() << "isReadOnly:" << storage.isReadOnly();
continue;
}
qDebug() << "name:" << storage.name();
qDebug() << "fileSystemType:" << storage.fileSystemType();
qDebug() << "size:" << storage.bytesTotal() / 1000 / 1000 << "MB";
qDebug() << "availableSize:" << storage.bytesAvailable() / 1000 / 1000
<< "MB";
QString fs = storage.fileSystemType().toLower();
if ((fs.contains("exfat") ||
fs.contains("fat") || // fat, fat32, vfat, msdos
fs.contains("vfat") ||
fs.contains("msdos"))
// && !storage.isReadOnly()
) {
cardList.append(storage);
}
}
if (cardList.count() < 1) {
displayNoCardDialog();
return;
}
if (cardList.count() == 1) {
selectedCard = cardList.at(0);
} else {
SelectCardDialog window;
window.setCards(cardList);
if (window.exec()) {
selectedCard = window.getSelected();
}
}
reloadCard();
raise();
activateWindow();
setFocus(Qt::ActiveWindowFocusReason);
}
void MainWindow::doneLoadingCard()
{
ui->deviceWidget->setEnabled(true);
statusBar()->showMessage(tr("Done loading card."), 5000);
selectedUpdated(0, 0);
totalSelectedSize = 0;
}
void MainWindow::updateProcessStatus(QString str)
{
statusBar()->showMessage(tr("Loading card...") + str);
}
void MainWindow::reloadCard() {
qDebug() << "Reload Card";
emptyMainWindow();
m_lastCardFileCount = 0; // no card = treat as empty
if (selectedCard.isValid()) {
QList<QFileInfo> files;
statusBar()->showMessage(tr("Loading card..."));
updateCardLabel();
files = getFiles(selectedCard.rootPath());
m_lastCardFileCount = files.count();
ui->deviceWidget->setFiles(files);
connect(ui->deviceWidget->fileModel,
&FileInfoModel::updateProcessStatus,
this,
&MainWindow::updateProcessStatus,
Qt::UniqueConnection);
ui->deviceWidget->setEnabled(false);
#if defined(__APPLE__)
try {
QPixmap pixmap = ExternalDriveIconFetcher::getExternalDrivePixmap(
selectedCard.rootPath());
ui->pixmapLabel->setPixmap(pixmap.scaled(32, 32, Qt::KeepAspectRatio));
} catch (...) {
}
#endif
ui->moveButton->setDisabled(true);
ui->ejectButton->setEnabled(true);
ui->reloadButton->setEnabled(true);
}
}
QImage requestImage(const QString &id, int height = 0, int width = 0) {
LibRaw rawProc;
auto state = rawProc.open_file(QFile::encodeName(id).constData());
qDebug() << "State loading Image:" << state;
QImage thumbnail;
if (LIBRAW_SUCCESS == state) {
if (LIBRAW_SUCCESS == rawProc.unpack_thumb()) {
if (LIBRAW_THUMBNAIL_JPEG == rawProc.imgdata.thumbnail.tformat) {
thumbnail.loadFromData((unsigned char *)rawProc.imgdata.thumbnail.thumb,
rawProc.imgdata.thumbnail.tlength, "JPEG");
}
}
// rawProc.recycle();
}
QScreen *screen = QGuiApplication::primaryScreen();
QRect screenGeometry = screen->geometry();
if (width == 0 && height == 0) {
height = screenGeometry.height();
width = screenGeometry.width();
}
return thumbnail.scaled(width / 2, height / 2, Qt::KeepAspectRatio);
}
void MainWindow::displayImage(QString rawFilePath, bool window = true,
int h = 0, int w = 0) {
statusBar()->showMessage(tr("Loading image, please wait."));
QImage image = requestImage(rawFilePath, h, w);
if (window) {
BorderlessDialog dialog2(image);
statusBar()->clearMessage();
dialog2.exec();
int lastKey = dialog2.lastKey;
if (lastKey == Qt::Key_Up || lastKey == Qt::Key_Down ||
lastKey == Qt::Key_Space) {
ui->deviceWidget->setFocus();
QString keyStr(
QKeySequence(lastKey).toString()); // key is int with keycode
QKeyEvent *key_press =
new QKeyEvent(QKeyEvent::KeyPress, lastKey, Qt::NoModifier, keyStr);
QApplication::sendEvent(ui->deviceWidget, key_press);
delete key_press;
}
} else {
ui->image->setPixmap(QPixmap::fromImage(image));
}
// Create a QDialog and set the label as its central widget
}
void MainWindow::emptyMainWindow() {
ui->deviceWidget->setModel(nullptr);
// The tree nodes are about to be deleted; drop our pointer and any cached
// previews of the (possibly re-inserted, modified) card.
currentSelectedImage = nullptr;
if (m_previewLoader)
QMetaObject::invokeMethod(m_previewLoader, &imageLoader::clearCache, Qt::QueuedConnection);
selectedUpdated(0, 0);
ui->ejectButton->setDisabled(true);
ui->reloadButton->setDisabled(true);
ui->moveButton->setDisabled(true);
ui->pixmapLabel->setPixmap(QPixmap());
ui->deviceWidget->setEnabled(false);
updateCardLabel();
ui->image->setPixmap(QPixmap());
m_currentPreviewImage = QImage();
setBackupUiEnabled(doBackupImport);
}
// SLOT for selection of node on ListWidget
void MainWindow::selectedNode(TreeNode *image) {
if (!image || !previewImage)
return;
if (!image->isFile) {
// Not a file: preview the first child instead (guard against empty list)
if (image->children.isEmpty())
return;
selectedNode(image->children.first());
return;
}
currentSelectedImage = image;
updateImportToLabel();
// The persistent loader coalesces requests (latest wins) and serves
// repeats from its cache; stale results are dropped in previewLoaded().
m_previewLoader->requestImage(image->filePath);
// Prefetch neighbours in the same group so arrow-key browsing is instant
QStringList prefetch;
if (TreeNode *parent = image->parent) {
const int idx = parent->children.indexOf(image);
for (int offset : {1, -1, 2}) {
const int i = idx + offset;
if (i >= 0 && i < parent->children.count()) {
TreeNode *sibling = parent->children.at(i);
if (sibling && sibling->isFile)
prefetch << sibling->filePath;
}
}
}
m_previewLoader->requestPrefetch(prefetch);
}
void MainWindow::previewLoaded(const QString &path, const QImage &image, bool failed)
{
// Drop results that no longer match the current selection
if (!currentSelectedImage || currentSelectedImage->filePath != path)
return;
showImage(image, failed);
}
void MainWindow::showImage(const QImage &image, bool failed)
{
if (!currentSelectedImage) {
qWarning() << "showImage(): currentSelectedImage is null";
return;
}
// label.resize(image.size());
QImage img(image);
QPainter painter(&img);
// Set font, size, and color
QFont font("Arial", 30); // You can customize the font and size
painter.setFont(font);
// QPoint point(50, 50);
painter.setPen(QColor(Qt::white)); // You can customize the text color
// Draw text at the specified position
const double shutterSpeed = currentSelectedImage->imageInfo.shutterSpeed;
QString shutterStr;
if (shutterSpeed >= 1.0) {
shutterStr = QString("%1s").arg(shutterSpeed, 0, 'f', 1);
} else if (shutterSpeed > 0.0) {
shutterStr = QString("1/%1s").arg(qRound(1.0 / shutterSpeed));
} else {
shutterStr = QStringLiteral("-");
}
painter.drawText(10,
10,
1024,
1024,
Qt::AlignLeft,
QString("%1\nf %2 - %3\nISO %4\n%5 mm")
.arg(currentSelectedImage->info.fileName())
.arg(currentSelectedImage->imageInfo.aperture, 0, 'f', 1)
.arg(shutterStr)
.arg(currentSelectedImage->imageInfo.isoValue)
.arg(currentSelectedImage->imageInfo.focalLength)
);
painter.drawText(10,
10,
1004,
1004,
Qt::AlignRight,
QString("%1\n%2\n#%3\n%4 %5")
.arg(currentSelectedImage->imageInfo.ownerName,
currentSelectedImage->imageInfo.cameraName,
currentSelectedImage->imageInfo.serialNumber,
currentSelectedImage->imageInfo.lensMake,
currentSelectedImage->imageInfo.lensModel)
);
if (failed) {
painter.drawText(0,
0,
img.width(),
img.height(),
Qt::AlignCenter,
QString(tr("Failed to load image.")));
}
// Keep the full-size overlaid image so the preview can rescale when the
// splitter or the window is resized.
m_currentPreviewImage = img;
rescalePreview();
}
void MainWindow::rescalePreview()
{
if (m_currentPreviewImage.isNull())
return;
const QSize target = ui->image->size();
if (target.width() < 2 || target.height() < 2)
return;
ui->image->setPixmap(QPixmap::fromImage(
m_currentPreviewImage.scaled(target, Qt::KeepAspectRatio, Qt::SmoothTransformation)));
}
void MainWindow::updateThemedIcons()
{
ui->reloadButton->setIcon(
tintedIcon(QStringLiteral(":/icons8-Refresh-64.png"),
palette().color(QPalette::ButtonText)));
}
void MainWindow::changeEvent(QEvent *event)
{
QMainWindow::changeEvent(event);
// Re-tint icons when the system switches between light and dark mode
if (event->type() == QEvent::PaletteChange
|| event->type() == QEvent::ApplicationPaletteChange) {
updateThemedIcons();
}
if (event->type() == QEvent::LanguageChange) {
ui->retranslateUi(this);
retranslateDynamicText();
}
}
void MainWindow::populateLanguageComboBox()
{
const QSignalBlocker blocker(ui->languageComboBox);
const QString current = AppLanguage::currentCode();
ui->languageComboBox->clear();
ui->languageComboBox->addItem(tr("System language"), AppLanguage::systemCode());
for (const QString &code : AppLanguage::availableCodes())
ui->languageComboBox->addItem(AppLanguage::nativeName(code), code);
const int index = ui->languageComboBox->findData(current);
ui->languageComboBox->setCurrentIndex(index >= 0 ? index : 0);
}
void MainWindow::on_languageComboBox_activated(int index)
{
const QString code = ui->languageComboBox->itemData(index).toString();
if (code.isEmpty() || code == AppLanguage::currentCode())
return;
AppLanguage::setCurrentCode(code);
// Installing/removing a translator posts a LanguageChange event to every
// widget, which is what drives retranslateDynamicText() below.
AppLanguage::install();
}
// retranslateUi() only covers strings that came from the .ui file. Everything
// that is set from code has to be re-applied by hand after a language change.
void MainWindow::retranslateDynamicText()
{
// retranslateUi() resets the title to the designer placeholder
setWindowTitle(QString("QuickImport %1").arg(QCoreApplication::applicationVersion()));
populateLanguageComboBox();
ui->presetComboBox->setPlaceholderText(tr("--Select to load preset--"));
if (importLocationList.isEmpty())
ui->importLocation->setPlaceholderText(tr("--Location not set--"));
if (importBackupLocationList.isEmpty())
ui->importBackupLocation->setPlaceholderText(tr("--Back-up location not set--"));
if (projectNameList.isEmpty())
ui->projectName->setPlaceholderText(tr("-- set project name --"));
updateCardLabel();
updateOpenApplicationLabel();
selectedUpdated(m_selectedCount, totalSelectedSize);
updateImportToLabel();
if (auto *model = qobject_cast<FileInfoModel *>(ui->deviceWidget->model()))
model->retranslate();
}
// The .ui leaves this label empty, so retranslateUi() blanks it on a language
// change; it has to be re-filled from the stored setting.
void MainWindow::updateOpenApplicationLabel()
{
ui->openApplicationText->setText(QFileInfo(openApplicationLocation).fileName());
}
void MainWindow::updateCardLabel()
{
if (!selectedCard.isValid()) {
ui->cardLabel->setText(tr("No card loaded."));
return;
}
const float usedGb = (float) (selectedCard.bytesTotal() - selectedCard.bytesAvailable())
/ 1000 / 1000 / 1000;
ui->cardLabel->setText(selectedCard.name()
+ QString(tr(" (Used space: %1 GB)")).arg(usedGb, 0, 'f', 2));
}
void MainWindow::resizeEvent(QResizeEvent *event) {
QMainWindow::resizeEvent(event);
rescalePreview();
}
void MainWindow::on_checkAll_clicked() {
if (auto *model = qobject_cast<FileInfoModel *>(ui->deviceWidget->model()))
model->selectAll();
}
void MainWindow::on_uncheckAll_clicked() {
if (auto *model = qobject_cast<FileInfoModel *>(ui->deviceWidget->model()))
model->deSelectAll();
}
void MainWindow::updateImportToLabel() {
imageInfoStruct imageInfo;
imageInfo.cameraName = "Test Camera";
imageInfo.serialNumber = "1233445";
imageInfo.isoValue = 800;
QDateTime now = QDateTime::currentDateTime();
QFileInfo fileinfo;
if (currentSelectedImage) {
imageInfo = currentSelectedImage->imageInfo;
now = fileCopyWorker::captureTimestamp(currentSelectedImage->info,
currentSelectedImage->imageInfo);
fileinfo = currentSelectedImage->info;
}
QString example =
fileCopyWorker::processNewFileName(importFolder, projectName, now,
imageInfo, fileinfo, fileNameFormat)
.at(2);
ui->importToLabel->setText(example);
// QStorageInfo does real disk I/O and this function runs on every
// keystroke; refresh the free-space values at most every few seconds
// (or when the folders/backup setting change).
const bool refreshFreeSpace = !m_freeSpaceTimer.isValid()
|| m_freeSpaceTimer.elapsed() > 3000
|| importFolder != m_freeSpaceFolder
|| importBackupFolder != m_freeSpaceBackupFolder
|| doBackupImport != m_freeSpaceBackupEnabled;
// Free space of the volume the folder lives on. When the folder itself
// does not exist yet, walk up to the nearest existing parent — that is
// where mkpath will create it, so its volume is the right one (and
// QStorageInfo on a missing path would report -1 → "-0.00 GB").
auto availableForPath = [](const QString &path) -> qint64 {
QString probe = QDir::cleanPath(path);
while (!probe.isEmpty() && !QFileInfo::exists(probe)) {
const int idx = probe.lastIndexOf(QLatin1Char('/'));
if (idx <= 0) {
probe = QStringLiteral("/");
break;
}
probe = probe.left(idx);
}
return QStorageInfo(probe).bytesAvailable();
};
if (refreshFreeSpace) {
m_freeSpaceTimer.start();
m_freeSpaceFolder = importFolder;
m_freeSpaceBackupFolder = importBackupFolder;
m_freeSpaceBackupEnabled = doBackupImport;
freeProjectSpace = availableForPath(importFolder);
m_freeBackupSpace = doBackupImport ? availableForPath(importBackupFolder) : -1;
}
const bool importFolderMissing = !importFolder.isEmpty() && !QDir(importFolder).exists();
QString freeText = QString("%1 GB").arg(
((float)freeProjectSpace / 1000 / 1000 / 1000), 0, 'f', 2);
if (importFolderMissing)
freeText += tr(" (new folder)");
ui->freeDiskSpace->setText(freeText);
if (doBackupImport) {
QString backupText = QString("%1 GB").arg(((float) m_freeBackupSpace / 1000 / 1000 / 1000),
0, 'f', 2);
if (!importBackupFolder.isEmpty() && !QDir(importBackupFolder).exists())
backupText += tr(" (new folder)");
ui->freeSpaceBackup->setText(backupText);
} else {
ui->freeSpaceBackup->setText("");
}
if (totalSelectedSize <= 0)
ui->moveButton->setDisabled(true);
else {
if (importFolder.size() > 0 && projectName.size() > 0 &&
fileNameFormat.size() > 0) {
ui->moveButton->setDisabled(false);
}
else {
ui->moveButton->setDisabled(true);
}
}
}
// Ask to create a missing destination folder; returns false when the user
// declines or creation fails.
bool MainWindow::ensureFolderExists(const QString &folder, const QString &description)
{
if (folder.isEmpty() || QDir(folder).exists())
return !folder.isEmpty();