-
Notifications
You must be signed in to change notification settings - Fork 201
Expand file tree
/
Copy pathmodlistviewactions.cpp
More file actions
1456 lines (1277 loc) · 49.3 KB
/
modlistviewactions.cpp
File metadata and controls
1456 lines (1277 loc) · 49.3 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 "modlistviewactions.h"
#include <QGridLayout>
#include <QGroupBox>
#include <QInputDialog>
#include <QLabel>
#include "filesystemutilities.h"
#include <log.h>
#include <report.h>
#include "categories.h"
#include "csvbuilder.h"
#include "directoryrefresher.h"
#include "downloadmanager.h"
#include "filedialogmemory.h"
#include "filterlist.h"
#include "listdialog.h"
#include "messagedialog.h"
#include "modelutils.h"
#include "modinfodialog.h"
#include "modlist.h"
#include "modlistview.h"
#include "nexusinterface.h"
#include "nxmaccessmanager.h"
#include "organizercore.h"
#include "overwriteinfodialog.h"
#include "pluginlistview.h"
#include "savetextasdialog.h"
#include "shared/directoryentry.h"
#include "shared/fileregister.h"
#include "shared/filesorigin.h"
using namespace MOBase;
using namespace MOShared;
ModListViewActions::ModListViewActions(OrganizerCore& core, FilterList& filters,
CategoryFactory& categoryFactory,
ModListView* view, PluginListView* pluginView,
QObject* nxmReceiver)
: QObject(view), m_core(core), m_filters(filters), m_categories(categoryFactory),
m_view(view), m_pluginView(pluginView), m_parent(view->topLevelWidget()),
m_receiver(nxmReceiver)
{}
int ModListViewActions::findInstallPriority(const QModelIndex& index) const
{
int newPriority = -1;
if (index.isValid() && index.data(ModList::IndexRole).isValid() &&
m_view->sortColumn() == ModList::COL_PRIORITY) {
auto mIndex = index.data(ModList::IndexRole).toInt();
auto info = ModInfo::getByIndex(mIndex);
newPriority = m_core.currentProfile()->getModPriority(mIndex);
if (info->isSeparator()) {
auto isSeparator = [](const auto& p) {
return ModInfo::getByIndex(p.second)->isSeparator();
};
auto& ibp = m_core.currentProfile()->getAllIndexesByPriority();
// start right after/before the current priority and look for the next
// separator
if (m_view->sortOrder() == Qt::AscendingOrder) {
auto it = std::find_if(ibp.find(newPriority + 1), ibp.end(), isSeparator);
if (it != ibp.end()) {
newPriority = it->first;
} else {
newPriority = -1;
}
} else {
auto it = std::find_if(std::reverse_iterator{ibp.find(newPriority - 1)},
ibp.rend(), isSeparator);
if (it != ibp.rend()) {
newPriority = it->first + 1;
} else {
// create "before" priority 0, i.e. at the end in descending priority.
newPriority = 0;
}
}
}
}
return newPriority;
}
void ModListViewActions::installMod(const QString& archivePath,
const QModelIndex& index) const
{
try {
QString path = archivePath;
if (path.isEmpty()) {
QStringList extensions = m_core.installationManager()->getSupportedExtensions();
for (auto iter = extensions.begin(); iter != extensions.end(); ++iter) {
*iter = "*." + *iter;
}
path = FileDialogMemory::getOpenFileName(
"installMod", m_parent, tr("Choose Mod"), QString(),
tr("Mod Archive").append(QString(" (%1)").arg(extensions.join(" "))));
}
if (path.isEmpty()) {
return;
} else {
m_core.installMod(path, findInstallPriority(index), false, nullptr, QString());
}
} catch (const std::exception& e) {
reportError(e.what());
}
}
void ModListViewActions::createEmptyMod(const QModelIndex& index) const
{
GuessedValue<QString> name;
name.setFilter(&fixDirectoryName);
while (name->isEmpty()) {
bool ok;
name.update(QInputDialog::getText(m_parent, tr("Create Mod..."),
tr("This will create an empty mod.\n"
"Please enter a name:"),
QLineEdit::Normal, "", &ok),
GUESS_USER);
if (!ok) {
return;
}
}
if (m_core.modList()->getMod(name) != nullptr) {
reportError(tr("A mod with this name already exists"));
return;
}
if (m_core.createMod(name) == nullptr) {
return;
}
// find the priority before refresh() otherwise the index might not be valid
const int newPriority = findInstallPriority(index);
m_core.refresh();
const auto mIndex = ModInfo::getIndex(name);
if (newPriority >= 0) {
m_core.modList()->changeModPriority(mIndex, newPriority);
}
m_view->scrollToAndSelect(
m_view->indexModelToView(m_core.modList()->index(mIndex, 0)));
}
void ModListViewActions::createSeparator(const QModelIndex& index) const
{
GuessedValue<QString> name;
name.setFilter(&fixDirectoryName);
while (name->isEmpty()) {
bool ok;
name.update(QInputDialog::getText(m_parent, tr("Create Separator..."),
tr("This will create a new separator.\n"
"Please enter a name:"),
QLineEdit::Normal, "", &ok),
GUESS_USER);
if (!ok) {
return;
}
}
if (m_core.modList()->getMod(name) != nullptr) {
reportError(tr("A separator with this name already exists"));
return;
}
name->append("_separator");
if (m_core.modList()->getMod(name) != nullptr) {
return;
}
int newPriority = -1;
if (index.isValid() && m_view->sortColumn() == ModList::COL_PRIORITY) {
newPriority =
m_core.currentProfile()->getModPriority(index.data(ModList::IndexRole).toInt());
// descending order, we need to fix the priority
if (m_view->sortOrder() == Qt::DescendingOrder) {
newPriority++;
}
}
if (m_core.createMod(name) == nullptr) {
return;
}
m_core.refresh();
const auto mIndex = ModInfo::getIndex(name);
if (newPriority >= 0) {
m_core.modList()->changeModPriority(mIndex, newPriority);
}
if (auto c = m_core.settings().colors().previousSeparatorColor()) {
ModInfo::getByIndex(mIndex)->setColor(*c);
}
m_view->scrollToAndSelect(
m_view->indexModelToView(m_core.modList()->index(mIndex, 0)));
}
void ModListViewActions::setAllMatchingModsEnabled(bool enabled) const
{
// number of mods to enable / disable
const auto counters = m_view->counters();
const auto count = enabled ? counters.visible.regular - counters.visible.active
: counters.visible.active;
// retrieve visible mods from the model view
const auto allIndex = m_view->indexViewToModel(flatIndex(m_view->model()));
const QString message =
enabled ? tr("Really enable %1 mod(s)?") : tr("Really disable %1 mod(s)?");
if (QMessageBox::question(m_parent, tr("Confirm"), message.arg(count),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
m_core.modList()->setActive(allIndex, enabled);
}
}
void ModListViewActions::checkModsForUpdates() const
{
bool checkingModsForUpdate = false;
if (NexusInterface::instance().getAccessManager()->validated()) {
checkingModsForUpdate =
ModInfo::checkAllForUpdate(&m_core.pluginContainer(), m_receiver);
NexusInterface::instance().requestEndorsementInfo(m_receiver, QVariant(),
QString());
NexusInterface::instance().requestTrackingInfo(m_receiver, QVariant(), QString());
} else {
QString apiKey;
if (GlobalSettings::nexusApiKey(apiKey)) {
m_core.doAfterLogin([=]() {
checkModsForUpdates();
});
NexusInterface::instance().getAccessManager()->apiCheck(apiKey);
} else {
log::warn("{}", tr("You are not currently authenticated with Nexus. Please do so "
"under Settings -> Nexus."));
}
}
bool updatesAvailable = false;
for (auto mod : m_core.modList()->allMods()) {
ModInfo::Ptr modInfo = ModInfo::getByName(mod);
if (modInfo->updateAvailable()) {
updatesAvailable = true;
break;
}
}
if (updatesAvailable || checkingModsForUpdate) {
m_view->setFilterCriteria(
{{ModListSortProxy::TypeSpecial, CategoryFactory::UpdateAvailable, false}});
m_filters.setSelection(
{{ModListSortProxy::TypeSpecial, CategoryFactory::UpdateAvailable, false}});
}
}
void ModListViewActions::assignCategories() const
{
if (!GlobalSettings::hideAssignCategoriesQuestion()) {
QMessageBox warning;
warning.setWindowTitle(tr("Are you sure?"));
warning.setText(
tr("This action will remove any existing categories on any mod with a valid "
"Nexus category mapping. Are you certain you want to proceed?"));
warning.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
QCheckBox dontShow(tr("&Don't show this again"));
warning.setCheckBox(&dontShow);
auto result = warning.exec();
if (dontShow.isChecked())
GlobalSettings::setHideAssignCategoriesQuestion(true);
if (result == QMessageBox::Cancel)
return;
}
for (auto mod : m_core.modList()->allMods()) {
ModInfo::Ptr modInfo = ModInfo::getByName(mod);
if (modInfo->isSeparator())
continue;
int nexusCategory = modInfo->getNexusCategory();
if (!nexusCategory) {
QSettings downloadMeta(m_core.downloadsPath() + "/" +
modInfo->installationFile() + ".meta",
QSettings::IniFormat);
if (downloadMeta.contains("category")) {
nexusCategory = downloadMeta.value("category", 0).toInt();
}
}
int newCategory = CategoryFactory::instance().resolveNexusID(nexusCategory);
if (newCategory != 0) {
for (auto category : modInfo->categories()) {
modInfo->removeCategory(category);
}
}
modInfo->setCategory(CategoryFactory::instance().getCategoryID(newCategory), true);
}
}
void ModListViewActions::checkModsForUpdates(
std::multimap<QString, int> const& IDs) const
{
if (m_core.settings().network().offlineMode()) {
return;
}
if (NexusInterface::instance().getAccessManager()->validated()) {
ModInfo::manualUpdateCheck(m_receiver, IDs);
} else {
QString apiKey;
if (GlobalSettings::nexusApiKey(apiKey)) {
m_core.doAfterLogin([=]() {
checkModsForUpdates(IDs);
});
NexusInterface::instance().getAccessManager()->apiCheck(apiKey);
} else
log::warn("{}", tr("You are not currently authenticated with Nexus. Please do so "
"under Settings -> Nexus."));
}
}
void ModListViewActions::checkModsForUpdates(const QModelIndexList& indices) const
{
std::multimap<QString, int> ids;
for (auto& idx : indices) {
ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt());
ids.insert(std::make_pair<QString, int>(info->gameName(), info->nexusId()));
}
checkModsForUpdates(ids);
}
void ModListViewActions::exportModListCSV() const
{
QDialog selection(m_parent);
QGridLayout* grid = new QGridLayout;
selection.setWindowTitle(tr("Export to csv"));
QLabel* csvDescription = new QLabel();
csvDescription->setText(
tr("CSV (Comma Separated Values) is a format that can be imported in programs "
"like Excel to create a spreadsheet.\nYou can also use online editors and "
"converters instead."));
grid->addWidget(csvDescription);
QGroupBox* groupBoxRows = new QGroupBox(tr("Select what mods you want export:"));
QRadioButton* all = new QRadioButton(tr("All installed mods"));
QRadioButton* active =
new QRadioButton(tr("Only active (checked) mods from your current profile"));
QRadioButton* visible =
new QRadioButton(tr("All currently visible mods in the mod list"));
QVBoxLayout* vbox = new QVBoxLayout;
vbox->addWidget(all);
vbox->addWidget(active);
vbox->addWidget(visible);
vbox->addStretch(1);
groupBoxRows->setLayout(vbox);
grid->addWidget(groupBoxRows);
QButtonGroup* buttonGroupRows = new QButtonGroup();
buttonGroupRows->addButton(all, 0);
buttonGroupRows->addButton(active, 1);
buttonGroupRows->addButton(visible, 2);
buttonGroupRows->button(0)->setChecked(true);
QGroupBox* groupBoxColumns = new QGroupBox(tr("Choose what Columns to export:"));
groupBoxColumns->setFlat(true);
QCheckBox* mod_Priority = new QCheckBox(tr("Mod_Priority"));
mod_Priority->setChecked(true);
QCheckBox* mod_Name = new QCheckBox(tr("Mod_Name"));
mod_Name->setChecked(true);
QCheckBox* mod_Note = new QCheckBox(tr("Notes_column"));
QCheckBox* mod_Status = new QCheckBox(tr("Mod_Status"));
mod_Status->setChecked(true);
QCheckBox* primary_Category = new QCheckBox(tr("Primary_Category"));
QCheckBox* nexus_ID = new QCheckBox(tr("Nexus_ID"));
QCheckBox* mod_Nexus_URL = new QCheckBox(tr("Mod_Nexus_URL"));
QCheckBox* mod_Version = new QCheckBox(tr("Mod_Version"));
QCheckBox* install_Date = new QCheckBox(tr("Install_Date"));
QCheckBox* download_File_Name = new QCheckBox(tr("Download_File_Name"));
QVBoxLayout* vbox1 = new QVBoxLayout;
vbox1->addWidget(mod_Priority);
vbox1->addWidget(mod_Name);
vbox1->addWidget(mod_Status);
vbox1->addWidget(mod_Note);
vbox1->addWidget(primary_Category);
vbox1->addWidget(nexus_ID);
vbox1->addWidget(mod_Nexus_URL);
vbox1->addWidget(mod_Version);
vbox1->addWidget(install_Date);
vbox1->addWidget(download_File_Name);
groupBoxColumns->setLayout(vbox1);
grid->addWidget(groupBoxColumns);
QPushButton* ok = new QPushButton("Ok");
QPushButton* cancel = new QPushButton("Cancel");
QDialogButtonBox* buttons =
new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(buttons, SIGNAL(accepted()), &selection, SLOT(accept()));
connect(buttons, SIGNAL(rejected()), &selection, SLOT(reject()));
grid->addWidget(buttons);
selection.setLayout(grid);
if (selection.exec() == QDialog::Accepted) {
unsigned int numMods = ModInfo::getNumMods();
int selectedRowID = buttonGroupRows->checkedId();
try {
QBuffer buffer;
buffer.open(QIODevice::ReadWrite);
CSVBuilder builder(&buffer);
builder.setEscapeMode(CSVBuilder::TYPE_STRING, CSVBuilder::QUOTE_ALWAYS);
std::vector<std::pair<QString, CSVBuilder::EFieldType>> fields;
if (mod_Priority->isChecked())
fields.push_back(
std::make_pair(QString("#Mod_Priority"), CSVBuilder::TYPE_STRING));
if (mod_Status->isChecked())
fields.push_back(
std::make_pair(QString("#Mod_Status"), CSVBuilder::TYPE_STRING));
if (mod_Name->isChecked())
fields.push_back(std::make_pair(QString("#Mod_Name"), CSVBuilder::TYPE_STRING));
if (mod_Note->isChecked())
fields.push_back(std::make_pair(QString("#Note"), CSVBuilder::TYPE_STRING));
if (primary_Category->isChecked())
fields.push_back(
std::make_pair(QString("#Primary_Category"), CSVBuilder::TYPE_STRING));
if (nexus_ID->isChecked())
fields.push_back(
std::make_pair(QString("#Nexus_ID"), CSVBuilder::TYPE_INTEGER));
if (mod_Nexus_URL->isChecked())
fields.push_back(
std::make_pair(QString("#Mod_Nexus_URL"), CSVBuilder::TYPE_STRING));
if (mod_Version->isChecked())
fields.push_back(
std::make_pair(QString("#Mod_Version"), CSVBuilder::TYPE_STRING));
if (install_Date->isChecked())
fields.push_back(
std::make_pair(QString("#Install_Date"), CSVBuilder::TYPE_STRING));
if (download_File_Name->isChecked())
fields.push_back(
std::make_pair(QString("#Download_File_Name"), CSVBuilder::TYPE_STRING));
builder.setFields(fields);
builder.writeHeader();
auto indexesByPriority = m_core.currentProfile()->getAllIndexesByPriority();
for (auto& iter : indexesByPriority) {
ModInfo::Ptr info = ModInfo::getByIndex(iter.second);
bool enabled = m_core.currentProfile()->modEnabled(iter.second);
if ((selectedRowID == 1) && !enabled) {
continue;
} else if ((selectedRowID == 2) && !m_view->isModVisible(iter.second)) {
continue;
}
std::vector<ModInfo::EFlag> flags = info->getFlags();
if ((std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) ==
flags.end()) &&
(std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) ==
flags.end())) {
if (mod_Priority->isChecked())
builder.setRowField("#Mod_Priority",
QString("%1").arg(iter.first, 4, 10, QChar('0')));
if (mod_Status->isChecked())
builder.setRowField("#Mod_Status", (enabled) ? "+" : "-");
if (mod_Name->isChecked())
builder.setRowField("#Mod_Name", info->name());
if (mod_Note->isChecked())
builder.setRowField("#Note",
QString("%1").arg(info->comments().remove(',')));
if (primary_Category->isChecked())
builder.setRowField(
"#Primary_Category",
(m_categories.categoryExists(info->primaryCategory()))
? m_categories.getCategoryNameByID(info->primaryCategory())
: "");
if (nexus_ID->isChecked())
builder.setRowField("#Nexus_ID", info->nexusId());
if (mod_Nexus_URL->isChecked())
builder.setRowField("#Mod_Nexus_URL",
(info->nexusId() > 0)
? NexusInterface::instance().getModURL(
info->nexusId(), info->gameName())
: "");
if (mod_Version->isChecked())
builder.setRowField("#Mod_Version", info->version().canonicalString());
if (install_Date->isChecked())
builder.setRowField("#Install_Date",
info->creationTime().toString("yyyy/MM/dd HH:mm:ss"));
if (download_File_Name->isChecked())
builder.setRowField("#Download_File_Name", info->installationFile());
builder.writeRow();
}
}
SaveTextAsDialog saveDialog(m_parent);
saveDialog.setText(buffer.data());
saveDialog.exec();
} catch (const std::exception& e) {
reportError(tr("export failed: %1").arg(e.what()));
}
}
}
void ModListViewActions::displayModInformation(const QString& modName,
ModInfoTabIDs tab) const
{
unsigned int index = ModInfo::getIndex(modName);
if (index == UINT_MAX) {
log::error("failed to resolve mod name {}", modName);
return;
}
ModInfo::Ptr modInfo = ModInfo::getByIndex(index);
displayModInformation(modInfo, index, tab);
}
void ModListViewActions::displayModInformation(unsigned int index,
ModInfoTabIDs tab) const
{
ModInfo::Ptr modInfo = ModInfo::getByIndex(index);
displayModInformation(modInfo, index, tab);
}
void ModListViewActions::displayModInformation(ModInfo::Ptr modInfo,
unsigned int modIndex,
ModInfoTabIDs tab) const
{
if (!m_core.modList()->modInfoAboutToChange(modInfo)) {
log::debug("a different mod information dialog is open. If this is incorrect, "
"please restart MO");
return;
}
std::vector<ModInfo::EFlag> flags = modInfo->getFlags();
if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) {
QDialog* dialog = m_parent->findChild<QDialog*>("__overwriteDialog");
try {
if (dialog == nullptr) {
dialog = new OverwriteInfoDialog(modInfo, m_core, m_parent);
dialog->setObjectName("__overwriteDialog");
} else {
qobject_cast<OverwriteInfoDialog*>(dialog)->setModInfo(modInfo);
}
dialog->show();
dialog->raise();
dialog->activateWindow();
connect(dialog, &QDialog::finished, [=]() {
m_core.modList()->modInfoChanged(modInfo);
dialog->deleteLater();
m_core.refreshDirectoryStructure();
});
} catch (const std::exception& e) {
reportError(tr("Failed to display overwrite dialog: %1").arg(e.what()));
}
} else {
modInfo->saveMeta();
ModInfoDialog dialog(m_core, m_core.pluginContainer(), modInfo, m_view, m_parent);
connect(&dialog, &ModInfoDialog::originModified, this,
&ModListViewActions::originModified);
connect(&dialog, &ModInfoDialog::modChanged, [=](unsigned int index) {
auto idx = m_view->indexModelToView(m_core.modList()->index(index, 0));
m_view->selectionModel()->select(idx, QItemSelectionModel::ClearAndSelect |
QItemSelectionModel::Rows);
m_view->scrollTo(idx);
});
// Open the tab first if we want to use the standard indexes of the tabs.
if (tab != ModInfoTabIDs::None) {
dialog.selectTab(tab);
}
dialog.exec();
modInfo->saveMeta();
m_core.modList()->modInfoChanged(modInfo);
emit modInfoDisplayed();
}
if (m_core.currentProfile()->modEnabled(modIndex) && !modInfo->isForeign()) {
FilesOrigin& origin =
m_core.directoryStructure()->getOriginByName(ToWString(modInfo->name()));
origin.enable(false);
if (m_core.directoryStructure()->originExists(ToWString(modInfo->name()))) {
FilesOrigin& origin =
m_core.directoryStructure()->getOriginByName(ToWString(modInfo->name()));
origin.enable(false);
QString path = modInfo->absolutePath();
QString modDataDir = m_core.managedGame()->modDataDirectory();
path = modDataDir.isEmpty() ? path : path + "/" + modDataDir;
m_core.directoryRefresher()->addModToStructure(
m_core.directoryStructure(), modInfo->name(),
m_core.currentProfile()->getModPriority(modIndex), path,
modInfo->stealFiles(), modInfo->archives());
DirectoryRefresher::cleanStructure(m_core.directoryStructure());
m_core.directoryStructure()->getFileRegister()->sortOrigins();
m_core.refreshLists();
}
}
}
void ModListViewActions::sendModsToTop(const QModelIndexList& indexes) const
{
m_core.modList()->changeModsPriority(indexes, Profile::MinimumPriority);
}
void ModListViewActions::sendModsToBottom(const QModelIndexList& indexes) const
{
m_core.modList()->changeModsPriority(indexes, Profile::MaximumPriority);
}
void ModListViewActions::sendModsToPriority(const QModelIndexList& indexes) const
{
bool ok;
int priority = QInputDialog::getInt(m_parent, tr("Set Priority"),
tr("Set the priority of the selected mods"), 0, 0,
std::numeric_limits<int>::max(), 1, &ok);
if (!ok)
return;
m_core.modList()->changeModsPriority(indexes, priority);
}
void ModListViewActions::sendModsToSeparator(const QModelIndexList& indexes) const
{
QStringList separators;
const auto& ibp = m_core.currentProfile()->getAllIndexesByPriority();
for (const auto& [priority, index] : ibp) {
if (index < ModInfo::getNumMods()) {
ModInfo::Ptr modInfo = ModInfo::getByIndex(index);
if (modInfo->isSeparator()) {
separators << modInfo->name().chopped(
10); // chops the "_separator" away from the name
}
}
}
// in descending order, reverse the separator
if (m_view->sortOrder() == Qt::DescendingOrder) {
std::reverse(separators.begin(), separators.end());
}
ListDialog dialog(m_parent);
dialog.setWindowTitle("Select a separator...");
dialog.setChoices(separators);
if (dialog.exec() != QDialog::Accepted) {
return;
}
const QString result = dialog.getChoice();
if (result.isEmpty()) {
return;
}
const auto sepPriority =
m_core.currentProfile()->getModPriority(ModInfo::getIndex(result + "_separator"));
auto isSeparator = [](const auto& p) {
return ModInfo::getByIndex(p.second)->isSeparator();
};
// start right after/before the current priority and look for the next
// separator
int priority = -1;
if (m_view->sortOrder() == Qt::AscendingOrder) {
auto it = std::find_if(ibp.find(sepPriority + 1), ibp.end(), isSeparator);
if (it != ibp.end()) {
priority = it->first;
} else {
priority = Profile::MaximumPriority;
}
} else {
auto it = std::find_if(--std::reverse_iterator{ibp.find(sepPriority - 1)},
ibp.rend(), isSeparator);
if (it != ibp.rend()) {
priority = it->first + 1;
} else {
// create "before" priority 0, i.e. at the end in descending priority.
priority = Profile::MinimumPriority;
}
}
// when the priority of a single mod is incremented, we need to shift the
// target priority, otherwise we will miss the target by one
if (indexes.size() == 1 &&
indexes[0].data(ModList::PriorityRole).toInt() < sepPriority) {
priority--;
}
m_core.modList()->changeModsPriority(indexes, priority);
}
void ModListViewActions::sendModsToFirstConflict(const QModelIndexList& indexes) const
{
std::set<unsigned int> conflicts;
for (auto& idx : indexes) {
if (!idx.data(ModList::IndexRole).isValid()) {
continue;
}
auto info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt());
conflicts.insert(info->getModOverwrite().begin(), info->getModOverwrite().end());
}
std::set<int> priorities;
std::transform(conflicts.begin(), conflicts.end(),
std::inserter(priorities, priorities.end()), [=](auto index) {
return m_core.currentProfile()->getModPriority(index);
});
if (!priorities.empty()) {
m_core.modList()->changeModsPriority(indexes, *priorities.begin());
}
}
void ModListViewActions::sendModsToLastConflict(const QModelIndexList& indexes) const
{
std::set<unsigned int> conflicts;
for (auto& idx : indexes) {
if (!idx.data(ModList::IndexRole).isValid()) {
continue;
}
auto info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt());
conflicts.insert(info->getModOverwritten().begin(),
info->getModOverwritten().end());
}
std::set<int> priorities;
std::transform(conflicts.begin(), conflicts.end(),
std::inserter(priorities, priorities.end()), [=](auto index) {
return m_core.currentProfile()->getModPriority(index);
});
if (!priorities.empty()) {
m_core.modList()->changeModsPriority(indexes, *priorities.rbegin());
}
}
void ModListViewActions::renameMod(const QModelIndex& index) const
{
try {
m_view->edit(m_view->indexModelToView(index));
} catch (const std::exception& e) {
reportError(tr("failed to rename mod: %1").arg(e.what()));
}
}
void ModListViewActions::removeMods(const QModelIndexList& indices) const
{
const int max_items = 20;
try {
if (indices.size() > 1) {
QString mods;
QStringList modNames;
int i = 0;
for (auto& idx : indices) {
QString name = idx.data().toString();
if (!ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->isRegular()) {
continue;
}
// adds an item for the mod name until `i` reaches `max_items`, which
// adds one "..." item; subsequent mods are not shown on the list but
// are still added to `modNames` below so they can be removed correctly
if (i < max_items) {
mods += "<li>" + name + "</li>";
} else if (i == max_items) {
mods += "<li>...</li>";
}
modNames.append(
ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->name());
++i;
}
if (QMessageBox::question(
m_parent, tr("Confirm"),
tr("Remove the following mods?<br><ul>%1</ul>").arg(mods),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
// use mod names instead of indexes because those become invalid during the
// removal
DownloadManager::startDisableDirWatcher();
for (QString name : modNames) {
m_core.modList()->removeRowForce(ModInfo::getIndex(name), QModelIndex());
}
DownloadManager::endDisableDirWatcher();
}
} else if (!indices.isEmpty()) {
m_core.modList()->removeRow(indices[0].data(ModList::IndexRole).toInt(),
QModelIndex());
}
m_view->updateModCount();
m_pluginView->updatePluginCount();
} catch (const std::exception& e) {
reportError(tr("failed to remove mod: %1").arg(e.what()));
}
}
void ModListViewActions::ignoreMissingData(const QModelIndexList& indices) const
{
for (auto& idx : indices) {
int row_idx = idx.data(ModList::IndexRole).toInt();
ModInfo::Ptr info = ModInfo::getByIndex(row_idx);
info->markValidated(true);
m_core.modList()->notifyChange(row_idx);
}
}
void ModListViewActions::setIgnoreUpdate(const QModelIndexList& indices,
bool ignore) const
{
for (auto& idx : indices) {
int modIdx = idx.data(ModList::IndexRole).toInt();
ModInfo::Ptr info = ModInfo::getByIndex(modIdx);
info->ignoreUpdate(ignore);
m_core.modList()->notifyChange(modIdx);
}
}
void ModListViewActions::changeVersioningScheme(const QModelIndex& index) const
{
if (QMessageBox::question(
m_parent, tr("Continue?"),
tr("The versioning scheme decides which version is considered newer than "
"another.\n"
"This function will guess the versioning scheme under the assumption that "
"the installed version is outdated."),
QMessageBox::Yes | QMessageBox::Cancel) == QMessageBox::Yes) {
ModInfo::Ptr info = ModInfo::getByIndex(index.data(ModList::IndexRole).toInt());
bool success = false;
static VersionInfo::VersionScheme schemes[] = {
VersionInfo::SCHEME_REGULAR, VersionInfo::SCHEME_DECIMALMARK,
VersionInfo::SCHEME_NUMBERSANDLETTERS};
for (int i = 0;
i < sizeof(schemes) / sizeof(VersionInfo::VersionScheme) && !success; ++i) {
VersionInfo verOld(info->version().canonicalString(), schemes[i]);
VersionInfo verNew(info->newestVersion().canonicalString(), schemes[i]);
if (verOld < verNew) {
info->setVersion(verOld);
info->setNewestVersion(verNew);
success = true;
}
}
if (!success) {
QMessageBox::information(
m_parent, tr("Sorry"),
tr("I don't know a versioning scheme where %1 is newer than %2.")
.arg(info->newestVersion().canonicalString())
.arg(info->version().canonicalString()),
QMessageBox::Ok);
}
}
}
void ModListViewActions::markConverted(const QModelIndexList& indices) const
{
for (auto& idx : indices) {
int modIdx = idx.data(ModList::IndexRole).toInt();
ModInfo::Ptr info = ModInfo::getByIndex(modIdx);
info->markConverted(true);
m_core.modList()->notifyChange(modIdx);
}
}
void ModListViewActions::visitOnNexus(const QModelIndexList& indices) const
{
if (indices.size() > 10) {
if (QMessageBox::question(m_parent, tr("Opening Nexus Links"),
tr("You are trying to open %1 links to Nexus Mods. Are "
"you sure you want to do this?")
.arg(indices.size()),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
return;
}
}
for (auto& idx : indices) {
ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt());
int modID = info->nexusId();
QString gameName = info->gameName();
if (modID > 0) {
shell::Open(QUrl(NexusInterface::instance().getModURL(modID, gameName)));
} else {
log::error("mod '{}' has no nexus id", info->name());
}
}
}
void ModListViewActions::visitWebPage(const QModelIndexList& indices) const
{
if (indices.size() > 10) {
if (QMessageBox::question(m_parent, tr("Opening Web Pages"),
tr("You are trying to open %1 Web Pages. Are you sure "
"you want to do this?")
.arg(indices.size()),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
return;
}
}
for (auto& idx : indices) {
ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt());
const auto url = info->parseCustomURL();
if (url.isValid()) {
shell::Open(url);
}
}
}
void ModListViewActions::visitNexusOrWebPage(const QModelIndexList& indices) const
{
if (indices.size() > 10) {
if (QMessageBox::question(m_parent, tr("Opening Web Pages"),
tr("You are trying to open %1 Web Pages. Are you sure "
"you want to do this?")
.arg(indices.size()),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
return;
}
}
for (auto& idx : indices) {
ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt());
if (!info) {
log::error("mod {} not found", idx.data(ModList::IndexRole).toInt());
continue;
}
int modID = info->nexusId();
QString gameName = info->gameName();
const auto url = info->parseCustomURL();
if (modID > 0) {
shell::Open(QUrl(NexusInterface::instance().getModURL(modID, gameName)));
} else if (url.isValid()) {
shell::Open(url);
} else {
log::error("mod '{}' has no valid link", info->name());
}
}
}
void ModListViewActions::reinstallMod(const QModelIndex& index) const
{
ModInfo::Ptr modInfo = ModInfo::getByIndex(index.data(ModList::IndexRole).toInt());
QString installationFile = modInfo->installationFile();
if (installationFile.length() != 0) {
QString fullInstallationFile;
QFileInfo fileInfo(installationFile);
if (fileInfo.isAbsolute()) {
if (fileInfo.exists()) {
fullInstallationFile = installationFile;
} else {
fullInstallationFile =
m_core.downloadManager()->getOutputDirectory() + "/" + fileInfo.fileName();
}
} else {
fullInstallationFile =
m_core.downloadManager()->getOutputDirectory() + "/" + installationFile;
}
if (QFile::exists(fullInstallationFile)) {
m_core.installMod(fullInstallationFile, -1, true, modInfo, modInfo->name());
} else {
QMessageBox::information(m_parent, tr("Failed"),
tr("Installation file no longer exists"));
}
} else {
QMessageBox::information(
m_parent, tr("Failed"),
tr("Mods installed with old versions of MO can't be reinstalled in this way."));
}
}
void ModListViewActions::createBackup(const QModelIndex& index) const
{
ModInfo::Ptr modInfo = ModInfo::getByIndex(index.data(ModList::IndexRole).toInt());
QString backupDirectory =