-
Notifications
You must be signed in to change notification settings - Fork 197
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
3987 lines (3358 loc) · 126 KB
/
mainwindow.cpp
File metadata and controls
3987 lines (3358 loc) · 126 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
/*
Copyright (C) 2012 Sebastian Herbord. All rights reserved.
This file is part of Mod Organizer.
Mod Organizer is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Mod Organizer is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "aboutdialog.h"
#include "browserdialog.h"
#include "categories.h"
#include "categoriesdialog.h"
#include "datatab.h"
#include "downloadlist.h"
#include "downloadstab.h"
#include "editexecutablesdialog.h"
#include "envshortcut.h"
#include "eventfilter.h"
#include "executableinfo.h"
#include "executableslist.h"
#include "filedialogmemory.h"
#include "filterlist.h"
#include "guessedvalue.h"
#include "imodinterface.h"
#include "installationmanager.h"
#include "instancemanager.h"
#include "instancemanagerdialog.h"
#include "iplugindiagnose.h"
#include "iplugingame.h"
#include "isavegame.h"
#include "isavegameinfowidget.h"
#include "listdialog.h"
#include "localsavegames.h"
#include "messagedialog.h"
#include "modlist.h"
#include "modlistcontextmenu.h"
#include "modlistviewactions.h"
#include "motddialog.h"
#include "nexusinterface.h"
#include "nxmaccessmanager.h"
#include "organizercore.h"
#include "overwriteinfodialog.h"
#include "pluginlist.h"
#include "previewdialog.h"
#include "previewgenerator.h"
#include "problemsdialog.h"
#include "profile.h"
#include "profilesdialog.h"
#include "report.h"
#include "savegameinfo.h"
#include "savestab.h"
#include "selectiondialog.h"
#include "serverinfo.h"
#include "settingsdialog.h"
#include "shared/appconfig.h"
#include "spawn.h"
#include "statusbar.h"
#include "tutorialmanager.h"
#include "versioninfo.h"
#include <bsainvalidation.h>
#include <dataarchives.h>
#include <safewritefile.h>
#include <scopeguard.h>
#include <taskprogressmanager.h>
#include <usvfs/usvfs.h>
#include <utility.h>
#include "directoryrefresher.h"
#include "shared/directoryentry.h"
#include "shared/fileentry.h"
#include "shared/filesorigin.h"
#include <QAbstractItemDelegate>
#include <QAction>
#include <QApplication>
#include <QBuffer>
#include <QButtonGroup>
#include <QCheckBox>
#include <QClipboard>
#include <QCloseEvent>
#include <QColor>
#include <QColorDialog>
#include <QCoreApplication>
#include <QCursor>
#include <QDebug>
#include <QDesktopServices>
#include <QDialog>
#include <QDialogButtonBox>
#include <QDirIterator>
#include <QDragEnterEvent>
#include <QDropEvent>
#include <QEvent>
#include <QFIleIconProvider>
#include <QFileDialog>
#include <QFont>
#include <QFuture>
#include <QHash>
#include <QIODevice>
#include <QIcon>
#include <QInputDialog>
#include <QItemSelection>
#include <QItemSelectionModel>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValueRef>
#include <QLineEdit>
#include <QListWidgetItem>
#include <QMenu>
#include <QMessageBox>
#include <QMimeData>
#include <QModelIndex>
#include <QNetworkProxyFactory>
#include <QPainter>
#include <QPixmap>
#include <QPoint>
#include <QProcess>
#include <QProgressDialog>
#include <QPushButton>
#include <QRadioButton>
#include <QRect>
#include <QResizeEvent>
#include <QScopedPointer>
#include <QShortcut>
#include <QSize>
#include <QSizePolicy>
#include <QTime>
#include <QTimer>
#include <QToolButton>
#include <QToolTip>
#include <QTranslator>
#include <QTreeWidget>
#include <QTreeWidgetItemIterator>
#include <QUrl>
#include <QVariantList>
#include <QVersionNumber>
#include <QWebEngineProfile>
#include <QWhatsThis>
#include <QWidgetAction>
#include <QDebug>
#include <QtGlobal>
#ifndef Q_MOC_RUN
#include <boost/algorithm/string.hpp>
#include <boost/assign.hpp>
#include <boost/bind/bind.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <boost/thread.hpp>
#endif
#include <shlobj.h>
#include <exception>
#include <functional>
#include <limits.h>
#include <map>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <utility>
#include "gameplugins.h"
#ifdef TEST_MODELS
#include "modeltest.h"
#endif // TEST_MODELS
#pragma warning(disable : 4428)
using namespace MOBase;
using namespace MOShared;
const QSize SmallToolbarSize(24, 24);
const QSize MediumToolbarSize(32, 32);
const QSize LargeToolbarSize(42, 36);
QString UnmanagedModName()
{
return QObject::tr("<Unmanaged>");
}
bool runLoot(QWidget* parent, OrganizerCore& core, bool didUpdateMasterList);
void setFilterShortcuts(QWidget* widget, QLineEdit* edit)
{
auto activate = [=] {
edit->setFocus();
edit->selectAll();
};
auto reset = [=] {
edit->clear();
widget->setFocus();
};
auto hookActivate = [activate](auto* w) {
auto* s = new QShortcut(QKeySequence::Find, w);
s->setAutoRepeat(false);
s->setContext(Qt::WidgetWithChildrenShortcut);
QObject::connect(s, &QShortcut::activated, activate);
};
auto hookReset = [reset](auto* w) {
auto* s = new QShortcut(QKeySequence(Qt::Key_Escape), w);
s->setAutoRepeat(false);
s->setContext(Qt::WidgetWithChildrenShortcut);
QObject::connect(s, &QShortcut::activated, reset);
};
hookActivate(widget);
hookReset(widget);
hookActivate(edit);
hookReset(edit);
}
MainWindow::MainWindow(Settings& settings, OrganizerCore& organizerCore,
PluginContainer& pluginContainer, QWidget* parent)
: QMainWindow(parent), ui(new Ui::MainWindow), m_WasVisible(false),
m_FirstPaint(true), m_linksSeparator(nullptr), m_Tutorial(this, "MainWindow"),
m_OldProfileIndex(-1), m_OldExecutableIndex(-1),
m_CategoryFactory(CategoryFactory::instance()), m_OrganizerCore(organizerCore),
m_PluginContainer(pluginContainer),
m_ArchiveListWriter(std::bind(&MainWindow::saveArchiveList, this)),
m_LinkToolbar(nullptr), m_LinkDesktop(nullptr), m_LinkStartMenu(nullptr),
m_NumberOfProblems(0), m_ProblemsCheckRequired(false)
{
// disables incredibly slow menu fade in effect that looks and feels like crap.
// this was only happening to users with the windows
// "Fade or slide menus into view" effect enabled.
// maybe in the future the effects will be better at this moment they aren't.
QApplication::setEffectEnabled(Qt::UI_FadeMenu, false);
QApplication::setEffectEnabled(Qt::UI_AnimateMenu, false);
QApplication::setEffectEnabled(Qt::UI_AnimateCombo, false);
QApplication::setEffectEnabled(Qt::UI_AnimateTooltip, false);
QApplication::setEffectEnabled(Qt::UI_FadeTooltip, false);
QWebEngineProfile::defaultProfile()->setPersistentCookiesPolicy(
QWebEngineProfile::NoPersistentCookies);
QWebEngineProfile::defaultProfile()->setHttpCacheMaximumSize(52428800);
QWebEngineProfile::defaultProfile()->setCachePath(settings.paths().cache());
QWebEngineProfile::defaultProfile()->setPersistentStoragePath(
settings.paths().cache());
// qt resets the thread name somewhere within the QWebEngineProfile calls
// above
MOShared::SetThisThreadName("main");
ui->setupUi(this);
languageChange(settings.interface().language());
ui->statusBar->setup(ui, settings);
{
auto& ni = NexusInterface::instance();
// there are two ways to get here:
// 1) the user just started MO, and
// 2) the user has changed some setting that required a restart
//
// "restarting" MO doesn't actually re-execute the binary, it just basically
// executes most of main() again, so a bunch of things are actually not
// reset
//
// one of these things is the api status, which will have fired its events
// long before the execution gets here because stuff is still cached and no
// real request to nexus is actually done
//
// therefore, when the user starts MO normally, the user account and stats
// will be empty (which is fine) and populated later on when the api key
// check has finished
//
// in the rare case where the user restarts MO through the settings, this
// will correctly pick up the previous values
updateWindowTitle(ni.getAPIUserAccount());
ui->statusBar->setAPI(ni.getAPIStats(), ni.getAPIUserAccount());
}
m_CategoryFactory.loadCategories();
ui->logList->setCore(m_OrganizerCore);
setupToolbar();
toggleMO2EndorseState();
toggleUpdateAction();
TaskProgressManager::instance().tryCreateTaskbar();
setupModList();
ui->espList->setup(m_OrganizerCore, this, ui);
ui->bsaList->setLocalMoveOnly(true);
ui->bsaList->setHeaderHidden(true);
const bool pluginListAdjusted =
settings.geometry().restoreState(ui->espList->header());
// data tab
m_DataTab.reset(new DataTab(m_OrganizerCore, m_PluginContainer, this, ui));
m_DataTab->restoreState(settings);
connect(m_DataTab.get(), &DataTab::executablesChanged, [&] {
refreshExecutablesList();
});
connect(m_DataTab.get(), &DataTab::originModified, [&](int id) {
originModified(id);
});
connect(m_DataTab.get(), &DataTab::displayModInformation,
[&](auto&& m, auto&& i, auto&& tab) {
displayModInformation(m, i, tab);
});
// downloads tab
m_DownloadsTab.reset(new DownloadsTab(m_OrganizerCore, ui));
// saves tab
m_SavesTab.reset(new SavesTab(this, m_OrganizerCore, ui));
// Hide stuff we do not need:
auto& features = m_OrganizerCore.gameFeatures();
if (!features.gameFeature<GamePlugins>()) {
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->espTab));
}
if (!features.gameFeature<DataArchives>()) {
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->bsaTab));
}
settings.geometry().restoreState(ui->downloadView->header());
settings.geometry().restoreState(ui->savegameList->header());
ui->splitter->setStretchFactor(0, 3);
ui->splitter->setStretchFactor(1, 2);
resizeLists(pluginListAdjusted);
QMenu* linkMenu = new QMenu(this);
m_LinkToolbar = linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Toolbar and Menu"),
this, SLOT(linkToolbar()));
m_LinkDesktop = linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Desktop"), this,
SLOT(linkDesktop()));
m_LinkStartMenu = linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Start Menu"), this,
SLOT(linkMenu()));
ui->linkButton->setMenu(linkMenu);
ui->listOptionsBtn->setMenu(
new ModListGlobalContextMenu(m_OrganizerCore, ui->modList, this));
ui->openFolderMenu->setMenu(openFolderMenu());
// don't allow mouse wheel to switch grouping, too many people accidentally
// turn on grouping and then don't understand what happened
EventFilter* noWheel = new EventFilter(this, [](QObject*, QEvent* event) -> bool {
return event->type() == QEvent::Wheel;
});
ui->groupCombo->installEventFilter(noWheel);
ui->profileBox->installEventFilter(noWheel);
updateSortButton();
connect(&m_PluginContainer, SIGNAL(diagnosisUpdate()), this,
SLOT(scheduleCheckForProblems()));
connect(&m_OrganizerCore, &OrganizerCore::directoryStructureReady, this,
&MainWindow::onDirectoryStructureChanged);
connect(m_OrganizerCore.directoryRefresher(),
SIGNAL(progress(const DirectoryRefreshProgress*)), this,
SLOT(refresherProgress(const DirectoryRefreshProgress*)));
connect(m_OrganizerCore.directoryRefresher(), SIGNAL(error(QString)), this,
SLOT(showError(QString)));
connect(&m_OrganizerCore.settings(), SIGNAL(languageChanged(QString)), this,
SLOT(languageChange(QString)));
connect(&m_OrganizerCore.settings(), SIGNAL(styleChanged(QString)), this,
SIGNAL(styleChanged(QString)));
connect(m_OrganizerCore.updater(), SIGNAL(restart()), this, SLOT(close()));
connect(m_OrganizerCore.updater(), SIGNAL(updateAvailable()), this,
SLOT(updateAvailable()));
connect(m_OrganizerCore.updater(), SIGNAL(motdAvailable(QString)), this,
SLOT(motdReceived(QString)));
connect(&m_OrganizerCore, &OrganizerCore::refreshTriggered, this, [this]() {
updateSortButton();
});
connect(&NexusInterface::instance(), SIGNAL(requestNXMDownload(QString)),
&m_OrganizerCore, SLOT(downloadRequestedNXM(QString)));
connect(&NexusInterface::instance(),
SIGNAL(nxmDownloadURLsAvailable(QString, int, int, QVariant, QVariant, int)),
this, SLOT(nxmDownloadURLs(QString, int, int, QVariant, QVariant, int)));
connect(&NexusInterface::instance(), SIGNAL(needLogin()), &m_OrganizerCore,
SLOT(nexusApi()));
connect(NexusInterface::instance().getAccessManager(),
&NXMAccessManager::credentialsReceived, this, &MainWindow::updateWindowTitle);
connect(&NexusInterface::instance(), &NexusInterface::requestsChanged, ui->statusBar,
&StatusBar::setAPI);
connect(&TutorialManager::instance(), SIGNAL(windowTutorialFinished(QString)), this,
SLOT(windowTutorialFinished(QString)));
connect(ui->tabWidget, SIGNAL(currentChanged(int)), &TutorialManager::instance(),
SIGNAL(tabChanged(int)));
connect(ui->toolBar, SIGNAL(customContextMenuRequested(QPoint)), this,
SLOT(toolBar_customContextMenuRequested(QPoint)));
connect(ui->menuToolbars, &QMenu::aboutToShow, [&] {
updateToolbarMenu();
});
connect(ui->menuView, &QMenu::aboutToShow, [&] {
updateViewMenu();
});
connect(ui->actionTool->menu(), &QMenu::aboutToShow, [&] {
updateToolMenu();
});
connect(&m_PluginContainer, &PluginContainer::pluginEnabled, this,
[this](IPlugin* plugin) {
if (m_PluginContainer.implementInterface<IPluginModPage>(plugin)) {
updateModPageMenu();
}
});
connect(&m_PluginContainer, &PluginContainer::pluginDisabled, this,
[this](IPlugin* plugin) {
if (m_PluginContainer.implementInterface<IPluginModPage>(plugin)) {
updateModPageMenu();
}
});
connect(&m_PluginContainer, &PluginContainer::pluginRegistered, this,
&MainWindow::onPluginRegistrationChanged);
connect(&m_PluginContainer, &PluginContainer::pluginUnregistered, this,
&MainWindow::onPluginRegistrationChanged);
connect(&m_OrganizerCore, &OrganizerCore::modInstalled, this,
&MainWindow::modInstalled);
connect(&m_CategoryFactory, SIGNAL(nexusCategoryRefresh(CategoriesDialog*)), this,
SLOT(refreshNexusCategories(CategoriesDialog*)));
connect(&m_CategoryFactory, SIGNAL(categoriesSaved()), this, SLOT(categoriesSaved()));
m_CheckBSATimer.setSingleShot(true);
connect(&m_CheckBSATimer, SIGNAL(timeout()), this, SLOT(checkBSAList()));
setFilterShortcuts(ui->modList, ui->modFilterEdit);
setFilterShortcuts(ui->espList, ui->espFilterEdit);
setFilterShortcuts(ui->downloadView, ui->downloadFilterEdit);
m_UpdateProblemsTimer.setSingleShot(true);
connect(&m_UpdateProblemsTimer, &QTimer::timeout, this,
&MainWindow::checkForProblemsAsync);
connect(this, &MainWindow::checkForProblemsDone, this,
&MainWindow::updateProblemsButton, Qt::ConnectionType::QueuedConnection);
m_SaveMetaTimer.setSingleShot(false);
connect(&m_SaveMetaTimer, SIGNAL(timeout()), this, SLOT(saveModMetas()));
m_SaveMetaTimer.start(5000);
FileDialogMemory::restore(settings);
fixCategories();
m_StartTime = QTime::currentTime();
m_Tutorial.expose("modList", m_OrganizerCore.modList());
m_Tutorial.expose("espList", m_OrganizerCore.pluginList());
m_OrganizerCore.setUserInterface(this);
connect(m_OrganizerCore.modList(), &ModList::showMessage, [=](auto&& message) {
showMessage(message);
});
connect(m_OrganizerCore.modList(), &ModList::modRenamed,
[=](auto&& oldName, auto&& newName) {
modRenamed(oldName, newName);
});
connect(m_OrganizerCore.modList(), &ModList::modUninstalled, [=](auto&& name) {
modRemoved(name);
});
connect(m_OrganizerCore.modList(), &ModList::fileMoved, [=](auto&&... args) {
fileMoved(args...);
});
connect(m_OrganizerCore.installationManager(), &InstallationManager::modReplaced,
[=](auto&& name) {
modRemoved(name);
});
connect(m_OrganizerCore.downloadManager(), &DownloadManager::showMessage,
[=](auto&& message) {
showMessage(message);
});
for (const QString& fileName : m_PluginContainer.pluginFileNames()) {
installTranslator(QFileInfo(fileName).baseName());
}
updateModPageMenu();
// refresh profiles so the current profile can be activated
refreshProfiles(false);
ui->profileBox->setCurrentText(m_OrganizerCore.currentProfile()->name());
if (settings.archiveParsing()) {
ui->dataTabShowFromArchives->setCheckState(Qt::Checked);
ui->dataTabShowFromArchives->setEnabled(true);
} else {
ui->dataTabShowFromArchives->setCheckState(Qt::Unchecked);
ui->dataTabShowFromArchives->setEnabled(false);
}
QApplication::instance()->installEventFilter(this);
scheduleCheckForProblems();
refreshExecutablesList();
updatePinnedExecutables();
resetActionIcons();
processUpdates();
ui->modList->updateModCount();
ui->espList->updatePluginCount();
ui->statusBar->updateNormalMessage(m_OrganizerCore);
}
void MainWindow::setupModList()
{
ui->modList->setup(m_OrganizerCore, m_CategoryFactory, this, ui);
connect(&ui->modList->actions(), &ModListViewActions::overwriteCleared, [=]() {
scheduleCheckForProblems();
});
connect(&ui->modList->actions(), &ModListViewActions::originModified, this,
&MainWindow::originModified);
connect(&ui->modList->actions(), &ModListViewActions::modInfoDisplayed, this,
&MainWindow::modInfoDisplayed);
connect(m_OrganizerCore.modList(), &ModList::modPrioritiesChanged, [&]() {
m_ArchiveListWriter.write();
});
}
void MainWindow::resetActionIcons()
{
// this is a bit of a hack
//
// the .qss files have historically set qproperty-icon by id and these ids
// correspond to the QActions created in the .ui file
//
// the problem is that QActions do not support having their icon property
// set from a .qss because they're not widgets (they don't inherit from
// QWidget), and styling only works on widget
//
// a QAction _does_ have an associated icon, it just can't be set from a .qss
// file
//
// so here, a dummy QToolButton widget is created for each QAction and is
// given the same name as the action, which makes it pick up the icon
// specified in the .qss file
//
// that icon is then given to the widget used by the QAction (if it's some
// sort of button, which typically happens on the toolbar) _and_ to the
// QAction itself, which is used in the menu bar
// clearing the notification, will be set below if the stylesheet has set
// anything for it
m_originalNotificationIcon = {};
// QActions created from the .ui file are children of the main window
for (QAction* action : findChildren<QAction*>()) {
// creating a dummy button
auto dummy = std::make_unique<QToolButton>();
// reusing the action name
dummy->setObjectName(action->objectName());
// styling the button, this has to be done manually because the button is
// never added anywhere
style()->polish(dummy.get());
// the button's icon may be null if it wasn't specified in the .qss file,
// which can happen if the stylesheet just doesn't override icons, or for
// other actions like the pinned custom executables
const auto icon = dummy->icon();
if (icon.isNull()) {
continue;
}
// button associated with the action on the toolbar
QWidget* actionWidget = ui->toolBar->widgetForAction(action);
if (auto* actionButton = dynamic_cast<QAbstractButton*>(actionWidget)) {
actionButton->setIcon(icon);
}
// the action's icon is used by the menu bar
action->setIcon(icon);
if (action == ui->actionNotifications) {
// if the stylesheet has set a notification icon, remember it here so it
// can be used in updateProblemsButton()
m_originalNotificationIcon = icon;
}
}
// update the button for the potentially new icon
updateProblemsButton();
}
MainWindow::~MainWindow()
{
try {
cleanup();
m_OrganizerCore.setUserInterface(nullptr);
if (m_IntegratedBrowser) {
m_IntegratedBrowser->close();
m_IntegratedBrowser.reset();
}
delete ui;
} catch (std::exception& e) {
QMessageBox::critical(
nullptr, tr("Crash on exit"),
tr("MO crashed while exiting. Some settings may not be saved.\n\nError: %1")
.arg(e.what()),
QMessageBox::Ok);
}
}
void MainWindow::updateWindowTitle(const APIUserAccount& user)
{
//"\xe2\x80\x93" is an "em dash", a longer "-"
QString title = QString("%1 \xe2\x80\x93 Mod Organizer v%2")
.arg(m_OrganizerCore.managedGame()->displayGameName(),
m_OrganizerCore.getVersion().displayString(3));
if (!user.name().isEmpty()) {
const QString premium = (user.type() == APIUserAccountTypes::Premium ? "*" : "");
title.append(QString(" (%1%2)").arg(user.name(), premium));
}
this->setWindowTitle(title);
}
void MainWindow::resizeLists(bool pluginListCustom)
{
// ensure the columns aren't so small you can't see them any more
for (int i = 0; i < ui->modList->header()->count(); ++i) {
if (ui->modList->header()->sectionSize(i) < 10) {
ui->modList->header()->resizeSection(i, 10);
}
}
if (!pluginListCustom) {
// resize plugin list to fit content
for (int i = 0; i < ui->espList->header()->count(); ++i) {
ui->espList->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents);
}
ui->espList->header()->setSectionResizeMode(0, QHeaderView::Stretch);
}
}
void MainWindow::allowListResize()
{
// allow resize on mod list
for (int i = 0; i < ui->modList->header()->count(); ++i) {
ui->modList->header()->setSectionResizeMode(i, QHeaderView::Interactive);
}
ui->modList->header()->setStretchLastSection(true);
// allow resize on plugin list
for (int i = 0; i < ui->espList->header()->count(); ++i) {
ui->espList->header()->setSectionResizeMode(i, QHeaderView::Interactive);
}
ui->espList->header()->setStretchLastSection(true);
}
void MainWindow::updateStyle(const QString&)
{
resetActionIcons();
}
void MainWindow::resizeEvent(QResizeEvent* event)
{
m_Tutorial.resize(event->size());
QMainWindow::resizeEvent(event);
}
void MainWindow::setupToolbar()
{
setupActionMenu(ui->actionModPage);
setupActionMenu(ui->actionTool);
setupActionMenu(ui->actionHelp);
setupActionMenu(ui->actionEndorseMO);
createHelpMenu();
createEndorseMenu();
// find last separator, add a spacer just before it so the icons are
// right-aligned
m_linksSeparator = nullptr;
for (auto* a : ui->toolBar->actions()) {
if (a->isSeparator()) {
m_linksSeparator = a;
}
}
if (m_linksSeparator) {
auto* spacer = new QWidget(ui->toolBar);
spacer->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
ui->toolBar->insertWidget(m_linksSeparator, spacer);
} else {
log::warn("no separator found on the toolbar, icons won't be right-aligned");
}
if (!InstanceManager::singleton().allowedToChangeInstance()) {
ui->actionChange_Game->setVisible(false);
}
}
void MainWindow::setupActionMenu(QAction* a)
{
a->setMenu(new QMenu(this));
auto* w = ui->toolBar->widgetForAction(a);
if (auto* tb = dynamic_cast<QToolButton*>(w))
tb->setPopupMode(QToolButton::InstantPopup);
}
void MainWindow::updatePinnedExecutables()
{
for (auto* a : ui->toolBar->actions()) {
if (a->objectName().startsWith("custom__")) {
ui->toolBar->removeAction(a);
a->deleteLater();
}
}
ui->menuRun->clear();
bool hasLinks = false;
for (const auto& exe : *m_OrganizerCore.executablesList()) {
if (!exe.hide() && exe.isShownOnToolbar()) {
hasLinks = true;
QAction* exeAction =
new QAction(iconForExecutable(exe.binaryInfo().filePath()), exe.title());
exeAction->setObjectName(QString("custom__") + exe.title());
exeAction->setStatusTip(exe.binaryInfo().filePath());
if (!connect(exeAction, SIGNAL(triggered()), this, SLOT(startExeAction()))) {
log::debug("failed to connect trigger?");
}
if (m_linksSeparator) {
ui->toolBar->insertAction(m_linksSeparator, exeAction);
} else {
// separator wasn't found, add it to the end
ui->toolBar->addAction(exeAction);
}
ui->menuRun->addAction(exeAction);
}
}
// don't show the menu if there are no links
ui->menuRun->menuAction()->setVisible(hasLinks);
}
void MainWindow::updateToolbarMenu()
{
ui->actionMainMenuToggle->setChecked(ui->menuBar->isVisible());
ui->actionToolBarMainToggle->setChecked(ui->toolBar->isVisible());
ui->actionStatusBarToggle->setChecked(ui->statusBar->isVisible());
ui->actionToolBarSmallIcons->setChecked(ui->toolBar->iconSize() == SmallToolbarSize);
ui->actionToolBarMediumIcons->setChecked(ui->toolBar->iconSize() ==
MediumToolbarSize);
ui->actionToolBarLargeIcons->setChecked(ui->toolBar->iconSize() == LargeToolbarSize);
ui->actionToolBarIconsOnly->setChecked(ui->toolBar->toolButtonStyle() ==
Qt::ToolButtonIconOnly);
ui->actionToolBarTextOnly->setChecked(ui->toolBar->toolButtonStyle() ==
Qt::ToolButtonTextOnly);
ui->actionToolBarIconsAndText->setChecked(ui->toolBar->toolButtonStyle() ==
Qt::ToolButtonTextUnderIcon);
}
void MainWindow::updateViewMenu()
{
ui->actionViewLog->setChecked(ui->logDock->isVisible());
}
QMenu* MainWindow::createPopupMenu()
{
auto* m = new QMenu;
// add all the actions from the toolbars menu
for (auto* a : ui->menuToolbars->actions()) {
m->addAction(a);
}
m->addSeparator();
// other actions
m->addAction(ui->actionViewLog);
// make sure the actions are updated
updateToolbarMenu();
updateViewMenu();
return m;
}
void MainWindow::on_actionMainMenuToggle_triggered()
{
ui->menuBar->setVisible(!ui->menuBar->isVisible());
}
void MainWindow::on_actionToolBarMainToggle_triggered()
{
ui->toolBar->setVisible(!ui->toolBar->isVisible());
}
void MainWindow::on_actionStatusBarToggle_triggered()
{
ui->statusBar->setVisible(!ui->statusBar->isVisible());
}
void MainWindow::on_actionToolBarSmallIcons_triggered()
{
setToolbarSize(SmallToolbarSize);
}
void MainWindow::on_actionToolBarMediumIcons_triggered()
{
setToolbarSize(MediumToolbarSize);
}
void MainWindow::on_actionToolBarLargeIcons_triggered()
{
setToolbarSize(LargeToolbarSize);
}
void MainWindow::on_actionToolBarIconsOnly_triggered()
{
setToolbarButtonStyle(Qt::ToolButtonIconOnly);
}
void MainWindow::on_actionToolBarTextOnly_triggered()
{
setToolbarButtonStyle(Qt::ToolButtonTextOnly);
}
void MainWindow::on_actionToolBarIconsAndText_triggered()
{
setToolbarButtonStyle(Qt::ToolButtonTextUnderIcon);
}
void MainWindow::on_actionViewLog_triggered()
{
ui->logDock->setVisible(!ui->logDock->isVisible());
}
void MainWindow::setToolbarSize(const QSize& s)
{
for (auto* tb : findChildren<QToolBar*>()) {
tb->setIconSize(s);
}
}
void MainWindow::setToolbarButtonStyle(Qt::ToolButtonStyle s)
{
for (auto* tb : findChildren<QToolBar*>()) {
tb->setToolButtonStyle(s);
}
}
void MainWindow::on_centralWidget_customContextMenuRequested(const QPoint& pos)
{
// this allows for getting the context menu even if both the menubar and all
// the toolbars are hidden; an alternative is the Alt key handled in
// keyPressEvent() below
// the custom context menu event bubbles up to here if widgets don't actually
// process this, which would show the menu when right-clicking button, labels,
// etc.
//
// only show the context menu when right-clicking on the central widget
// itself, which is basically just the outer edges of the main window
auto* w = childAt(pos);
if (w != ui->centralWidget) {
return;
}
createPopupMenu()->exec(ui->centralWidget->mapToGlobal(pos));
}
void MainWindow::scheduleCheckForProblems()
{
if (!m_UpdateProblemsTimer.isActive()) {
m_UpdateProblemsTimer.start(500);
}
}
void MainWindow::updateProblemsButton()
{
// if the current stylesheet doesn't provide an icon, this is used instead
const char* DefaultIconName = ":/MO/gui/warning";
const std::size_t numProblems = m_NumberOfProblems;
// original icon without a count painted on it
const QIcon original = m_originalNotificationIcon.isNull()
? QIcon(DefaultIconName)
: m_originalNotificationIcon;
// final icon
QIcon final;
if (numProblems > 0) {
ui->actionNotifications->setToolTip(tr("There are notifications to read"));
// will contain the original icon, plus a notification count; this also
// makes sure the pixmap is exactly 64x64 by requesting the icon that's
// as close to 64x64 as possible, and then scaling it up if it's too small
QPixmap merged = original.pixmap(64, 64).scaled(64, 64);
{
QPainter painter(&merged);
const std::string badgeName =
std::string(":/MO/gui/badge_") +
(numProblems < 10 ? std::to_string(static_cast<long long>(numProblems))
: "more");
painter.drawPixmap(32, 32, 32, 32, QPixmap(badgeName.c_str()));
}
final = QIcon(merged);
} else {
ui->actionNotifications->setToolTip(tr("There are no notifications"));
// no change
final = original;
}
ui->actionNotifications->setEnabled(numProblems > 0);
// setting the icon on the action (shown on the menu)
ui->actionNotifications->setIcon(final);
// setting the icon on the toolbar button
if (auto* actionWidget = ui->toolBar->widgetForAction(ui->actionNotifications)) {
if (auto* button = dynamic_cast<QAbstractButton*>(actionWidget)) {
button->setIcon(final);
}
}
// updating the status bar, may be null very early when MO is starting
if (ui->statusBar) {
ui->statusBar->setNotifications(numProblems > 0);
}
}
bool MainWindow::errorReported(QString& logFile)
{
QDir dir(qApp->property("dataPath").toString() + "/" +
QString::fromStdWString(AppConfig::logPath()));
QFileInfoList files =
dir.entryInfoList(QStringList("ModOrganizer_??_??_??_??_??.log"), QDir::Files,
QDir::Name | QDir::Reversed);
if (files.count() > 0) {
logFile = files.at(0).absoluteFilePath();
QFile file(logFile);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
char buffer[1024];
int line = 0;
while (!file.atEnd()) {
file.readLine(buffer, 1024);
if (strncmp(buffer, "ERROR", 5) == 0) {
return true;
}
// prevent this function from taking forever
if (line++ >= 50000) {
break;