From be0d6aef00891286f33242073627611413ad79c4 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Sat, 26 Dec 2020 20:48:38 +0100 Subject: Start working on collapsible separators. --- src/mainwindow.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index cfce9bef..ddde1d9b 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -87,6 +87,7 @@ along with Mod Organizer. If not, see . #include "listdialog.h" #include "envshortcut.h" #include "browserdialog.h" +#include "modlistbypriorityproxy.h" #include "directoryrefresher.h" #include "shared/directoryentry.h" @@ -543,6 +544,8 @@ MainWindow::MainWindow(Settings &settings processUpdates(); ui->statusBar->updateNormalMessage(m_OrganizerCore); + + on_groupCombo_currentIndexChanged(0); } void MainWindow::setupModList() @@ -5935,7 +5938,7 @@ void MainWindow::on_groupCombo_currentIndexChanged(int index) Qt::UserRole + 2); } break; default: { - newModel = nullptr; + newModel = nullptr; } break; } @@ -5948,7 +5951,8 @@ void MainWindow::on_groupCombo_currentIndexChanged(int index) connect(ui->modList, SIGNAL(collapsed(QModelIndex)), newModel, SLOT(collapsed(QModelIndex))); connect(newModel, SIGNAL(expandItem(QModelIndex)), this, SLOT(expandModList(QModelIndex))); } else { - m_ModListSortProxy->setSourceModel(m_OrganizerCore.modList()); + m_ModListSortProxy->setSourceModel(new ModListByPriorityProxy(m_OrganizerCore.modList(), this)); + // m_ModListSortProxy->setSourceModel(m_OrganizerCore.modList()); } modFilterActive(m_ModListSortProxy->isFilterActive()); } -- cgit v1.3.1 From d0512da75805be194d949a6d6bac8184314da0e6 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Sun, 27 Dec 2020 14:55:20 +0100 Subject: Use an intermediate structure to store the separator tree. --- src/mainwindow.cpp | 29 ++--- src/mainwindow.h | 2 + src/modinfo.h | 10 +- src/modinfoseparator.h | 2 +- src/modlist.cpp | 2 +- src/modlistbypriorityproxy.cpp | 236 ++++++++++++++++++++--------------------- src/modlistbypriorityproxy.h | 51 +++++++-- 7 files changed, 179 insertions(+), 153 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index ddde1d9b..be879dc6 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -544,14 +544,22 @@ MainWindow::MainWindow(Settings &settings processUpdates(); ui->statusBar->updateNormalMessage(m_OrganizerCore); - - on_groupCombo_currentIndexChanged(0); } void MainWindow::setupModList() { - m_ModListSortProxy = m_OrganizerCore.createModListProxyModel(); + m_ModListByPriorityProxy = new ModListByPriorityProxy(m_OrganizerCore.currentProfile(), &m_OrganizerCore); + connect(ui->modList, SIGNAL(expanded(QModelIndex)), m_ModListByPriorityProxy, SLOT(expanded(QModelIndex))); + connect(ui->modList, SIGNAL(collapsed(QModelIndex)), m_ModListByPriorityProxy, SLOT(collapsed(QModelIndex))); + connect(m_ModListByPriorityProxy, SIGNAL(expandItem(QModelIndex)), this, SLOT(expandModList(QModelIndex))); + + m_ModListSortProxy = new ModListSortProxy(m_OrganizerCore.currentProfile(), &m_OrganizerCore); ui->modList->setModel(m_ModListSortProxy); + + m_ModListByPriorityProxy->setSourceModel(m_OrganizerCore.modList()); + m_ModListSortProxy->setSourceModel(m_ModListByPriorityProxy); + emit m_OrganizerCore.modList()->layoutChanged(); + ui->modList->sortByColumn(ModList::COL_PRIORITY, Qt::AscendingOrder); @@ -1267,15 +1275,7 @@ void MainWindow::espFilterChanged(const QString &filter) void MainWindow::expandModList(const QModelIndex &index) { - QAbstractItemModel *model = ui->modList->model(); - - for (int i = 0; i < model->rowCount(); ++i) { - QModelIndex targetIdx = model->index(i, 0); - if (model->data(targetIdx).toString() == index.data().toString()) { - ui->modList->expand(targetIdx); - break; - } - } + ui->modList->expand(m_ModListSortProxy->mapFromSource(index)); } @@ -1679,6 +1679,7 @@ void MainWindow::activateSelectedProfile() m_OrganizerCore.setCurrentProfile(ui->profileBox->currentText()); m_ModListSortProxy->setProfile(m_OrganizerCore.currentProfile()); + m_ModListByPriorityProxy->setProfile(m_OrganizerCore.currentProfile()); m_SavesTab->refreshSaveList(); m_OrganizerCore.refresh(); @@ -5951,8 +5952,8 @@ void MainWindow::on_groupCombo_currentIndexChanged(int index) connect(ui->modList, SIGNAL(collapsed(QModelIndex)), newModel, SLOT(collapsed(QModelIndex))); connect(newModel, SIGNAL(expandItem(QModelIndex)), this, SLOT(expandModList(QModelIndex))); } else { - m_ModListSortProxy->setSourceModel(new ModListByPriorityProxy(m_OrganizerCore.modList(), this)); - // m_ModListSortProxy->setSourceModel(m_OrganizerCore.modList()); + m_ModListSortProxy->setSourceModel(m_ModListByPriorityProxy); + emit m_OrganizerCore.modList()->layoutChanged(); } modFilterActive(m_ModListSortProxy->isFilterActive()); } diff --git a/src/mainwindow.h b/src/mainwindow.h index f8910361..19a1b179 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -26,6 +26,7 @@ along with Mod Organizer. If not, see . #include "imoinfo.h" #include "iuserinterface.h" #include "modinfo.h" +#include "modlistbypriorityproxy.h" #include "modlistsortproxy.h" #include "tutorialcontrol.h" #include "plugincontainer.h" //class PluginContainer; @@ -297,6 +298,7 @@ private: QStringList m_DefaultArchives; ModListSortProxy *m_ModListSortProxy; + ModListByPriorityProxy *m_ModListByPriorityProxy; PluginListSortProxy *m_PluginListSortProxy; diff --git a/src/modinfo.h b/src/modinfo.h index 42abe51e..d04f6657 100644 --- a/src/modinfo.h +++ b/src/modinfo.h @@ -378,6 +378,11 @@ public: // IModInterface implementations / Re-declaration */ virtual std::shared_ptr fileTree() const = 0; + /** + * @return true if this object represents a regular mod. + */ + virtual bool isRegular() const { return false; } + /** * @return true if this object represents the overwrite mod. */ @@ -491,11 +496,6 @@ public: // Mutable operations: public: // Methods after this do not come from IModInterface: - /** - * @return true if this mod is a regular mod, false otherwise. - */ - virtual bool isRegular() const { return false; } - /** * @return true if this mod is empty, false otherwise. */ diff --git a/src/modinfoseparator.h b/src/modinfoseparator.h index 88262f37..c7df7184 100644 --- a/src/modinfoseparator.h +++ b/src/modinfoseparator.h @@ -55,7 +55,7 @@ protected: private: ModInfoSeparator( - PluginContainer* pluginContainer, + PluginContainer* pluginContainer, const MOBase::IPluginGame* game, const QDir& path, MOShared::DirectoryEntry** directoryStructure); }; diff --git a/src/modlist.cpp b/src/modlist.cpp index c8056140..4191e2db 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -1236,8 +1236,8 @@ void ModList::removeRowForce(int row, const QModelIndex &parent) m_Profile->cancelModlistWrite(); beginRemoveRows(parent, row, row); ModInfo::removeMod(row); - endRemoveRows(); m_Profile->refreshModStatus(); // removes the mod from the status list + endRemoveRows(); m_Profile->writeModlist(); // this ensures the modified list gets written back before new mods can be installed notifyModRemoved(modInfo->name()); diff --git a/src/modlistbypriorityproxy.cpp b/src/modlistbypriorityproxy.cpp index 69c6ff88..77b7262a 100644 --- a/src/modlistbypriorityproxy.cpp +++ b/src/modlistbypriorityproxy.cpp @@ -1,12 +1,13 @@ #include "modlistbypriorityproxy.h" #include "modinfo.h" +#include "profile.h" #include "modlist.h" +#include "log.h" -ModListByPriorityProxy::ModListByPriorityProxy(ModList* modList, QObject* parent) : - QAbstractProxyModel(parent), m_ModList(modList) +ModListByPriorityProxy::ModListByPriorityProxy(Profile* profile, QObject* parent) : + QAbstractProxyModel(parent), m_Profile(profile) { - setSourceModel(modList); } ModListByPriorityProxy::~ModListByPriorityProxy() @@ -16,7 +17,14 @@ ModListByPriorityProxy::~ModListByPriorityProxy() void ModListByPriorityProxy::setSourceModel(QAbstractItemModel* model) { QAbstractProxyModel::setSourceModel(model); - // connect(sourceModel(), &QAbstractItemModel::layoutChanged, this, &ModListByPriorityProxy::buildTree); + + if (sourceModel()) { + m_CollapsedItems.clear(); + connect(sourceModel(), &QAbstractItemModel::layoutChanged, this, &ModListByPriorityProxy::buildTree, Qt::UniqueConnection); + connect(sourceModel(), &QAbstractItemModel::rowsRemoved, this, [this]() { buildTree(); }, Qt::UniqueConnection); + connect(sourceModel(), &QAbstractItemModel::modelReset, this, &ModListByPriorityProxy::buildTree, Qt::UniqueConnection); + buildTree(); + } } void ModListByPriorityProxy::buildTree() @@ -25,73 +33,48 @@ void ModListByPriorityProxy::buildTree() beginResetModel(); - endResetModel(); - -} + // reset the root + m_Root = { }; + m_IndexToItem.clear(); -std::vector ModListByPriorityProxy::topLevelItems() const -{ - std::vector items; - bool separator = false; - for (auto& [priority, index] : m_ModList->m_Profile->getAllIndexesByPriority()) { + TreeItem* root = &m_Root; + for (auto& [priority, index] : m_Profile->getAllIndexesByPriority()) { ModInfo::Ptr modInfo = ModInfo::getByIndex(index); + + TreeItem* item; + if (modInfo->isSeparator()) { - items.emplace_back(modInfo, priority); - separator = true; + m_Root.children.push_back(std::make_unique(modInfo, index, &m_Root)); + item = m_Root.children.back().get(); + root = item; } - else if (modInfo->isOverwrite() || !separator) { - items.emplace_back(modInfo, priority); + else if (modInfo->isOverwrite()) { + m_Root.children.push_back(std::make_unique(modInfo, index, &m_Root)); + item = m_Root.children.back().get(); } - } - - return items; -} - -std::vector ModListByPriorityProxy::childItems(int priority) const -{ - std::vector children; - for (auto& [p, index] : m_ModList->m_Profile->getAllIndexesByPriority()) { - if (p > priority) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(index); - if (modInfo->isSeparator()) { - break; - } - children.emplace_back(modInfo, p); + else { + root->children.push_back(std::make_unique(modInfo, index, root)); + item = root->children.back().get(); } - } - return children; -} + m_IndexToItem[index] = item; -std::optional ModListByPriorityProxy::separator(int priority) const -{ - // overwrites - if (priority == ULONG_MAX) { - return {}; } - auto& indexByPriority = m_ModList->m_Profile->getAllIndexesByPriority(); - - auto it = indexByPriority.find(priority); - if (it == std::end(indexByPriority)) { - return {}; - } + endResetModel(); - { - ModInfo::Ptr modInfo = ModInfo::getByIndex(it->second); - if (modInfo->isSeparator() || modInfo->isOverwrite()) { - return {}; - } - } + // restore expand-state + expandItems(QModelIndex()); +} - auto rit = std::reverse_iterator{ it }; - for (; rit != std::rend(indexByPriority); ++rit) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(rit->second); - if (modInfo->isSeparator()) { - return ModInfoWithPriority{ modInfo, rit->first }; +void ModListByPriorityProxy::expandItems(const QModelIndex& index) +{ + for (int row = 0; row < rowCount(index); row++) { + QModelIndex idx = this->index(row, 0, QModelIndex()); + if (!m_CollapsedItems.contains(idx.data(Qt::DisplayRole).toString())) { + emit expandItem(idx); } + expandItems(idx); } - - return {}; } QModelIndex ModListByPriorityProxy::mapFromSource(const QModelIndex& sourceIndex) const @@ -100,24 +83,8 @@ QModelIndex ModListByPriorityProxy::mapFromSource(const QModelIndex& sourceIndex return QModelIndex(); } - auto topItems = topLevelItems(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(sourceIndex.row()); - - for (std::size_t i = 0; i < topItems.size(); ++i) { - if (topItems[i].mod == modInfo) { - return createIndex(i, sourceIndex.column(), modInfo.get()); - } - } - - auto sep = separator(m_ModList->priority(modInfo->name())); - auto children = childItems(sep->priority); - for (std::size_t i = 0; i < children.size(); ++i) { - if (children[i].mod == modInfo) { - return createIndex(i, sourceIndex.column(), modInfo.get()); - } - } - - return QModelIndex(); + auto* item = m_IndexToItem.at(sourceIndex.row()); + return createIndex(item->parent->childIndex(item), sourceIndex.column(), item); } QModelIndex ModListByPriorityProxy::mapToSource(const QModelIndex& proxyIndex) const @@ -125,32 +92,23 @@ QModelIndex ModListByPriorityProxy::mapToSource(const QModelIndex& proxyIndex) c if (!proxyIndex.isValid()) { return QModelIndex(); } - auto topItems = topLevelItems(); - ModInfo::Ptr modInfo; - if (proxyIndex.parent().isValid()) { - ModInfo::Ptr parentInfo = topItems[proxyIndex.parent().row()].mod; - modInfo = childItems(m_ModList->priority(parentInfo->name()))[proxyIndex.row()].mod; - } - else { - modInfo = topItems[proxyIndex.row()].mod; - } - return sourceModel()->index(ModInfo::getIndex(modInfo->name()), proxyIndex.column(), mapToSource(proxyIndex.parent())); + auto* item = static_cast(proxyIndex.internalPointer()); + return sourceModel()->index(item->index, proxyIndex.column()); } int ModListByPriorityProxy::rowCount(const QModelIndex& parent) const { - auto topItems = topLevelItems(); if (!parent.isValid()) { - return topItems.size(); + return m_Root.children.size(); } - ModInfo::Ptr modInfo = topItems[parent.row()].mod; - if (!modInfo->isSeparator()) { - return 0; + auto* item = static_cast(parent.internalPointer()); + + if (item->mod->isSeparator()) { + return item->children.size(); } - auto priority = m_ModList->priority(modInfo->name()); - return childItems(priority).size(); + return 0; } int ModListByPriorityProxy::columnCount(const QModelIndex& index) const @@ -161,54 +119,90 @@ int ModListByPriorityProxy::columnCount(const QModelIndex& index) const QModelIndex ModListByPriorityProxy::parent(const QModelIndex& child) const { - - auto topItems = topLevelItems(); - ModInfo::Ptr modInfo; - if (child.parent().isValid()) { - ModInfo::Ptr parentInfo = topItems[child.parent().row()].mod; - modInfo = childItems(m_ModList->priority(parentInfo->name()))[child.row()].mod; - } - else { - modInfo = topItems[child.row()].mod; + if (!child.isValid()) { + return QModelIndex(); } - auto sep = separator(m_ModList->priority(modInfo->name())); + auto* item = static_cast(child.internalPointer()); - if (!sep) { + if (!item->parent || item->parent == &m_Root) { return QModelIndex(); } - for (std::size_t i = 0; i < topItems.size(); ++i) { - if (topItems[i].mod == sep->mod) { - return createIndex(i, child.column(), sep->mod.get()); - } - } - - return QModelIndex(); + return createIndex(item->parent->parent->childIndex(item->parent), 0, item->parent); } bool ModListByPriorityProxy::hasChildren(const QModelIndex& parent) const { if (!parent.isValid()) { - return false; + return m_Root.children.size() > 0; } - ModInfo* modInfo = static_cast(parent.internalPointer()); - for (auto& item : topLevelItems()) { - if (modInfo == item.mod) { - return modInfo->isSeparator() && !childItems(item.priority).empty(); + auto* item = static_cast(parent.internalPointer()); + return item->children.size() > 0; +} + +bool ModListByPriorityProxy::setData(const QModelIndex& index, const QVariant& value, int role) +{ + // only care about the "name" column + if (index.column() == 0 && role == Qt::EditRole) { + QString oldValue = data(index, role).toString(); + if (m_CollapsedItems.contains(oldValue)) { + m_CollapsedItems.erase(oldValue); + m_CollapsedItems.insert(value.toString()); } } - return false; + return QAbstractProxyModel::setData(index, value, role); +} + + +Qt::ItemFlags ModListByPriorityProxy::flags(const QModelIndex& idx) const +{ + if (!idx.isValid()) { + return sourceModel()->flags(QModelIndex()); + } + + // we check the flags of the root node and if drop is not enabled, it + // means we are dragging files. + Qt::ItemFlags rootFlags = sourceModel()->flags(QModelIndex()); + if (!rootFlags.testFlag(Qt::ItemIsDropEnabled)) { + return sourceModel()->flags(mapToSource(idx)); + } + + auto flags = sourceModel()->flags(mapToSource(idx)); + auto* item = static_cast(idx.internalPointer()); + + if (item->mod->isSeparator()) { + flags |= Qt::ItemIsDropEnabled; + } + + return flags; } QModelIndex ModListByPriorityProxy::index(int row, int column, const QModelIndex& parent) const { - auto topItems = topLevelItems(); + if (!hasIndex(row, column, parent)) { + return QModelIndex(); + } + + const TreeItem* parentItem; if (!parent.isValid()) { - return createIndex(row, column, topItems[row].mod.get()); + parentItem = &m_Root; } else { - auto children = childItems(topItems[parent.row()].priority); - return createIndex(row, column, children[row].mod.get()); + parentItem = static_cast(parent.internalPointer()); + } + return createIndex(row, column, parentItem->children[row].get()); +} + +void ModListByPriorityProxy::expanded(const QModelIndex& index) +{ + auto it = m_CollapsedItems.find(index.data(Qt::DisplayRole).toString()); + if (it != m_CollapsedItems.end()) { + m_CollapsedItems.erase(it); } } + +void ModListByPriorityProxy::collapsed(const QModelIndex& index) +{ + m_CollapsedItems.insert(index.data(Qt::DisplayRole).toString()); +} diff --git a/src/modlistbypriorityproxy.h b/src/modlistbypriorityproxy.h index 6ec04b9b..d5f59f4c 100644 --- a/src/modlistbypriorityproxy.h +++ b/src/modlistbypriorityproxy.h @@ -2,6 +2,7 @@ #define MODLISBYPRIORITYPROXY_H #include +#include #include #include @@ -14,43 +15,71 @@ #include "modinfo.h" class ModList; +class Profile; class ModListByPriorityProxy : public QAbstractProxyModel { Q_OBJECT public: - explicit ModListByPriorityProxy(ModList* modList, QObject* parent = nullptr); + explicit ModListByPriorityProxy(Profile* profile, QObject* parent = nullptr); ~ModListByPriorityProxy(); + void setProfile(Profile* profile) { m_Profile = profile; } + void setSourceModel(QAbstractItemModel* sourceModel) override; int rowCount(const QModelIndex& parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex& child) const override; + Qt::ItemFlags flags(const QModelIndex& idx) const override; QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; int columnCount(const QModelIndex& index) const override; bool hasChildren(const QModelIndex& parent) const override; + bool setData(const QModelIndex& index, const QVariant& value, int role) override; + QModelIndex mapFromSource(const QModelIndex& sourceIndex) const override; QModelIndex mapToSource(const QModelIndex& proxyIndex) const override; +signals: + void expandItem(const QModelIndex& index); + +public slots: + + void expanded(const QModelIndex& index); + void collapsed(const QModelIndex& index); + private: void buildTree(); - - struct ModInfoWithPriority { - const ModInfo::Ptr mod; - const int priority; + void expandItems(const QModelIndex& index); + + struct TreeItem { + ModInfo::Ptr mod; + unsigned int index; + std::vector> children; + TreeItem* parent; + + std::size_t childIndex(TreeItem* child) const { + for (std::size_t i = 0; i < children.size(); ++i) { + if (children[i].get() == child) { + return i; + } + } + return -1; + } + + TreeItem() : TreeItem(nullptr, -1) { } + TreeItem(ModInfo::Ptr mod, unsigned int index, TreeItem* parent = nullptr) : + mod(mod), index(index), parent(parent) { } }; - std::vector topLevelItems() const; - std::vector childItems(int priority) const; - std::optional separator(int priority) const; + TreeItem m_Root; + std::map m_IndexToItem; + std::set m_CollapsedItems; private: - - ModList* m_ModList; - + Profile* m_Profile; }; #endif //GROUPINGPROXY_H -- cgit v1.3.1 From c778f01c895d3c09ceff779dc782fd221186c587 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Sun, 27 Dec 2020 17:45:04 +0100 Subject: Only expand if model is correct. --- src/mainwindow.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index be879dc6..5fe1b39d 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1275,10 +1275,11 @@ void MainWindow::espFilterChanged(const QString &filter) void MainWindow::expandModList(const QModelIndex &index) { - ui->modList->expand(m_ModListSortProxy->mapFromSource(index)); + if (index.model() == m_ModListSortProxy->sourceModel()) { + ui->modList->expand(m_ModListSortProxy->mapFromSource(index)); + } } - bool MainWindow::addProfile() { QComboBox *profileBox = findChild("profileBox"); -- cgit v1.3.1 From e4473d8fd500cd8af2f5131a0a22deb4697846d7 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Sun, 27 Dec 2020 18:43:30 +0100 Subject: Restrict collapsible separators to sort-by-priority. --- src/mainwindow.cpp | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 5fe1b39d..173dc53d 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -557,8 +557,19 @@ void MainWindow::setupModList() ui->modList->setModel(m_ModListSortProxy); m_ModListByPriorityProxy->setSourceModel(m_OrganizerCore.modList()); - m_ModListSortProxy->setSourceModel(m_ModListByPriorityProxy); - emit m_OrganizerCore.modList()->layoutChanged(); + + connect(m_ModListSortProxy, &QAbstractItemModel::layoutAboutToBeChanged, + this, [this](const QList& parents, QAbstractItemModel::LayoutChangeHint hint) { + if (hint == QAbstractItemModel::VerticalSortHint) { + if (m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY) { + m_ModListSortProxy->setSourceModel(m_ModListByPriorityProxy); + emit m_OrganizerCore.modList()->layoutChanged(); + } + else { + m_ModListSortProxy->setSourceModel(m_OrganizerCore.modList()); + } + } + }); ui->modList->sortByColumn(ModList::COL_PRIORITY, Qt::AscendingOrder); @@ -5953,8 +5964,13 @@ void MainWindow::on_groupCombo_currentIndexChanged(int index) connect(ui->modList, SIGNAL(collapsed(QModelIndex)), newModel, SLOT(collapsed(QModelIndex))); connect(newModel, SIGNAL(expandItem(QModelIndex)), this, SLOT(expandModList(QModelIndex))); } else { - m_ModListSortProxy->setSourceModel(m_ModListByPriorityProxy); - emit m_OrganizerCore.modList()->layoutChanged(); + if (m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY) { + m_ModListSortProxy->setSourceModel(m_ModListByPriorityProxy); + emit m_OrganizerCore.modList()->layoutChanged(); + } + else { + m_ModListSortProxy->setSourceModel(m_OrganizerCore.modList()); + } } modFilterActive(m_ModListSortProxy->isFilterActive()); } -- cgit v1.3.1 From 1e2297604b797f1ea15d91b43f227114deedaeb0 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Sun, 27 Dec 2020 18:45:06 +0100 Subject: Restrict collapsible separators to sort-by-priority in ascending order. --- src/mainwindow.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 173dc53d..15564c21 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -561,7 +561,7 @@ void MainWindow::setupModList() connect(m_ModListSortProxy, &QAbstractItemModel::layoutAboutToBeChanged, this, [this](const QList& parents, QAbstractItemModel::LayoutChangeHint hint) { if (hint == QAbstractItemModel::VerticalSortHint) { - if (m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY) { + if (m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY && m_ModListSortProxy->sortOrder() == Qt::AscendingOrder) { m_ModListSortProxy->setSourceModel(m_ModListByPriorityProxy); emit m_OrganizerCore.modList()->layoutChanged(); } @@ -5964,7 +5964,7 @@ void MainWindow::on_groupCombo_currentIndexChanged(int index) connect(ui->modList, SIGNAL(collapsed(QModelIndex)), newModel, SLOT(collapsed(QModelIndex))); connect(newModel, SIGNAL(expandItem(QModelIndex)), this, SLOT(expandModList(QModelIndex))); } else { - if (m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY) { + if (m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY && m_ModListSortProxy->sortOrder() == Qt::AscendingOrder) { m_ModListSortProxy->setSourceModel(m_ModListByPriorityProxy); emit m_OrganizerCore.modList()->layoutChanged(); } -- cgit v1.3.1 From 14bdef9ea68ce1dd8945113f1dece595adf4f013 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Sun, 27 Dec 2020 19:44:14 +0100 Subject: Add collapse/expand all actions. --- src/mainwindow.cpp | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 15564c21..7f9e81fc 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -4555,7 +4555,11 @@ void MainWindow::initModListContextMenu(QMenu *menu) { menu->addAction(tr("Install Mod..."), this, SLOT(installMod_clicked())); menu->addAction(tr("Create empty mod"), this, SLOT(createEmptyMod_clicked())); + + menu->addSeparator(); menu->addAction(tr("Create Separator"), this, SLOT(createSeparator_clicked())); + menu->addAction(tr("Collapse all"), ui->modList, &QTreeView::collapseAll); + menu->addAction(tr("Expand all"), ui->modList, &QTreeView::expandAll); menu->addSeparator(); -- cgit v1.3.1 From c46432cc2ef4a108557c1405a0f9c01616bc176e Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Sun, 27 Dec 2020 20:01:41 +0100 Subject: Move common code to method. --- src/mainwindow.cpp | 27 +++++++++++++-------------- src/mainwindow.h | 1 + 2 files changed, 14 insertions(+), 14 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 7f9e81fc..74f3fd62 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -546,6 +546,17 @@ MainWindow::MainWindow(Settings &settings ui->statusBar->updateNormalMessage(m_OrganizerCore); } +void MainWindow::updateModListByPriorityProxy() +{ + if (m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY && m_ModListSortProxy->sortOrder() == Qt::AscendingOrder) { + m_ModListSortProxy->setSourceModel(m_ModListByPriorityProxy); + emit m_OrganizerCore.modList()->layoutChanged(); + } + else { + m_ModListSortProxy->setSourceModel(m_OrganizerCore.modList()); + } +} + void MainWindow::setupModList() { m_ModListByPriorityProxy = new ModListByPriorityProxy(m_OrganizerCore.currentProfile(), &m_OrganizerCore); @@ -561,13 +572,7 @@ void MainWindow::setupModList() connect(m_ModListSortProxy, &QAbstractItemModel::layoutAboutToBeChanged, this, [this](const QList& parents, QAbstractItemModel::LayoutChangeHint hint) { if (hint == QAbstractItemModel::VerticalSortHint) { - if (m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY && m_ModListSortProxy->sortOrder() == Qt::AscendingOrder) { - m_ModListSortProxy->setSourceModel(m_ModListByPriorityProxy); - emit m_OrganizerCore.modList()->layoutChanged(); - } - else { - m_ModListSortProxy->setSourceModel(m_OrganizerCore.modList()); - } + updateModListByPriorityProxy(); } }); @@ -5968,13 +5973,7 @@ void MainWindow::on_groupCombo_currentIndexChanged(int index) connect(ui->modList, SIGNAL(collapsed(QModelIndex)), newModel, SLOT(collapsed(QModelIndex))); connect(newModel, SIGNAL(expandItem(QModelIndex)), this, SLOT(expandModList(QModelIndex))); } else { - if (m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY && m_ModListSortProxy->sortOrder() == Qt::AscendingOrder) { - m_ModListSortProxy->setSourceModel(m_ModListByPriorityProxy); - emit m_OrganizerCore.modList()->layoutChanged(); - } - else { - m_ModListSortProxy->setSourceModel(m_OrganizerCore.modList()); - } + updateModListByPriorityProxy(); } modFilterActive(m_ModListSortProxy->isFilterActive()); } diff --git a/src/mainwindow.h b/src/mainwindow.h index 19a1b179..ccfd4881 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -608,6 +608,7 @@ private slots: // ui slots void storeSettings(); void readSettings(); void setupModList(); + void updateModListByPriorityProxy(); }; #endif // MAINWINDOW_H -- cgit v1.3.1 From cc5f0c8555fbbcc4b6d0dc29a42b8c7869df1859 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Sun, 27 Dec 2020 23:23:56 +0100 Subject: Drag and drop from download view to install + Expand and scroll to mod on install. --- src/downloadlist.cpp | 12 +++++++ src/downloadlist.h | 3 +- src/downloadstab.cpp | 3 ++ src/mainwindow.cpp | 24 ++++++++++---- src/modlist.cpp | 88 +++++++++++++++++++++++++++++++++++++++------------ src/modlist.h | 18 ++++++++--- src/organizercore.cpp | 14 ++++++-- src/organizercore.h | 2 +- 8 files changed, 128 insertions(+), 36 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/downloadlist.cpp b/src/downloadlist.cpp index a5c284e6..78e5fd24 100644 --- a/src/downloadlist.cpp +++ b/src/downloadlist.cpp @@ -90,6 +90,18 @@ QVariant DownloadList::headerData(int section, Qt::Orientation orientation, int } } +Qt::ItemFlags DownloadList::flags(const QModelIndex& idx) const +{ + return QAbstractTableModel::flags(idx) | Qt::ItemIsDragEnabled; +} + +QMimeData* DownloadList::mimeData(const QModelIndexList& indexes) const +{ + QMimeData* result = QAbstractItemModel::mimeData(indexes); + result->setData("text/plain", "archive"); + return result; +} + QVariant DownloadList::data(const QModelIndex &index, int role) const { bool pendingDownload = index.row() >= m_Manager->numTotalDownloads(); diff --git a/src/downloadlist.h b/src/downloadlist.h index 2171c013..65d03ab9 100644 --- a/src/downloadlist.h +++ b/src/downloadlist.h @@ -68,11 +68,12 @@ public: * @return number of rows to display **/ virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; - virtual int columnCount(const QModelIndex &parent) const; QModelIndex index(int row, int column, const QModelIndex &parent) const; QModelIndex parent(const QModelIndex &child) const; + Qt::ItemFlags flags(const QModelIndex& idx) const override; + QMimeData* mimeData(const QModelIndexList& indexes) const override; virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const; diff --git a/src/downloadstab.cpp b/src/downloadstab.cpp index a0602ede..e04799ec 100644 --- a/src/downloadstab.cpp +++ b/src/downloadstab.cpp @@ -17,6 +17,9 @@ DownloadsTab::DownloadsTab(OrganizerCore& core, Ui::MainWindow* mwui) ui.list->setItemDelegate(new DownloadProgressDelegate( m_core.downloadManager(), ui.list)); + ui.list->setDragEnabled(true); + ui.list->setDragDropMode(QAbstractItemView::DragDropMode::DragDrop); + update(); m_filter.setEdit(ui.filter); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 74f3fd62..ea7d5967 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -578,7 +578,6 @@ void MainWindow::setupModList() ui->modList->sortByColumn(ModList::COL_PRIORITY, Qt::AscendingOrder); - connect( ui->modList, SIGNAL(dropModeUpdate(bool)), m_OrganizerCore.modList(), SLOT(dropModeUpdate(bool))); @@ -653,6 +652,10 @@ void MainWindow::setupModList() ui->modList->header()->setSectionHidden(ModList::COL_NAME, false); ui->modList->installEventFilter(m_OrganizerCore.modList()); + + connect(m_OrganizerCore.modList(), &ModList::downloadArchiveDropped, this, [this](int row, int priority) { + m_OrganizerCore.installDownload(row, priority); + }); } void MainWindow::resetActionIcons() @@ -743,6 +746,7 @@ MainWindow::~MainWindow() } } + void MainWindow::updateWindowTitle(const APIUserAccount& user) { //"\xe2\x80\x93" is an "em dash", a longer "-" @@ -2483,15 +2487,23 @@ void MainWindow::modorder_changed() void MainWindow::modInstalled(const QString &modName) { - QModelIndexList posList = - m_OrganizerCore.modList()->match(m_OrganizerCore.modList()->index(0, 0), Qt::DisplayRole, modName); - if (posList.count() == 1) { - ui->modList->scrollTo(posList.at(0)); + unsigned int index = ModInfo::getIndex(modName); + + if (index == UINT_MAX) { + return; + } + + QModelIndex qIndex = m_OrganizerCore.modList()->index(index, 0); + + if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy) { + qIndex = m_ModListByPriorityProxy->mapFromSource(qIndex); + ui->modList->expand(m_ModListSortProxy->mapFromSource(qIndex)); } + ui->modList->scrollTo(m_ModListSortProxy->mapFromSource(qIndex)); // force an update to happen std::multimap IDs; - ModInfo::Ptr info = ModInfo::getByIndex(ModInfo::getIndex(modName)); + ModInfo::Ptr info = ModInfo::getByIndex(index); IDs.insert(std::make_pair(info->gameName(), info->nexusId())); modUpdateCheck(IDs); } diff --git a/src/modlist.cpp b/src/modlist.cpp index 4191e2db..ca4741e6 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -1087,6 +1087,32 @@ boost::signals2::connection ModList::onModMoved(const std::function(row) >= ModInfo::getNumMods())) { + return -1; + } + + int newPriority = 0; + { + if ((row < 0) || (row > static_cast(m_Profile->numRegularMods()))) { + newPriority = m_Profile->numRegularMods() + 1; + } + else { + newPriority = m_Profile->getModPriority(row); + } + if (newPriority == -1) { + newPriority = m_Profile->numRegularMods() + 1; + } + } + + return newPriority; +} + bool ModList::dropURLs(const QMimeData *mimeData, int row, const QModelIndex &parent) { if (row == -1) { @@ -1160,7 +1186,6 @@ bool ModList::dropURLs(const QMimeData *mimeData, int row, const QModelIndex &pa bool ModList::dropMod(const QMimeData *mimeData, int row, const QModelIndex &parent) { - try { QByteArray encoded = mimeData->data("application/x-qabstractitemmodeldatalist"); QDataStream stream(&encoded, QIODevice::ReadOnly); @@ -1175,26 +1200,12 @@ bool ModList::dropMod(const QMimeData *mimeData, int row, const QModelIndex &par } } - if (row == -1) { - row = parent.row(); - } - - if ((row < 0) || (static_cast(row) >= ModInfo::getNumMods())) { + int newPriority = dropPriority(row, parent); + if (newPriority == -1) { return false; } - - int newPriority = 0; - { - if ((row < 0) || (row > static_cast(m_Profile->numRegularMods()))) { - newPriority = m_Profile->numRegularMods() + 1; - } else { - newPriority = m_Profile->getModPriority(row); - } - if (newPriority == -1) { - newPriority = m_Profile->numRegularMods() + 1; - } - } changeModPriority(sourceRows, newPriority); + } catch (const std::exception &e) { reportError(tr("drag&drop failed: %1").arg(e.what())); } @@ -1202,6 +1213,37 @@ bool ModList::dropMod(const QMimeData *mimeData, int row, const QModelIndex &par return false; } +bool ModList::dropArchive(const QMimeData* mimeData, int row, const QModelIndex& parent) +{ + int priority = dropPriority(row, parent); + if (priority == -1) { + return false; + } + + try { + QByteArray encoded = mimeData->data("application/x-qabstractitemmodeldatalist"); + QDataStream stream(&encoded, QIODevice::ReadOnly); + std::vector sourceRows; + + while (!stream.atEnd()) { + int sourceRow, col; + QMap roleDataMap; + stream >> sourceRow >> col >> roleDataMap; + if (col == 0) { + sourceRows.push_back(sourceRow); + } + } + + if (sourceRows.size() == 1) { + emit downloadArchiveDropped(sourceRows[0], priority); + } + } + catch (const std::exception& e) { + reportError(tr("drag&drop failed: %1").arg(e.what())); + } + + return false; +} bool ModList::dropMimeData(const QMimeData *mimeData, Qt::DropAction action, int row, int, const QModelIndex &parent) { @@ -1214,10 +1256,14 @@ bool ModList::dropMimeData(const QMimeData *mimeData, Qt::DropAction action, int if (mimeData->hasUrls()) { return dropURLs(mimeData, row, parent); } else if (mimeData->hasText()) { - return dropMod(mimeData, row, parent); - } else { - return false; + if (mimeData->text() == "mod") { + return dropMod(mimeData, row, parent); + } + else if (mimeData->text() == "archive") { + return dropArchive(mimeData, row, parent); + } } + return false; } void ModList::removeRowForce(int row, const QModelIndex &parent) diff --git a/src/modlist.h b/src/modlist.h index fad53755..2ca2fff1 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -310,6 +310,10 @@ signals: void postDataChanged(); + // emitted when an item is dropped from the download list, the row is from the + // download list + void downloadArchiveDropped(int row, int priority); + protected: // event filter, handles event from the header and the tree view itself @@ -336,10 +340,6 @@ private: bool renameMod(int index, const QString &newName); - bool dropURLs(const QMimeData *mimeData, int row, const QModelIndex &parent); - - bool dropMod(const QMimeData *mimeData, int row, const QModelIndex &parent); - MOBase::IModList::ModStates state(unsigned int modIndex) const; bool moveSelection(QAbstractItemView *itemView, int direction); @@ -367,6 +367,16 @@ private: QFlags state; }; +private: + + bool dropURLs(const QMimeData* mimeData, int row, const QModelIndex& parent); + bool dropMod(const QMimeData* mimeData, int row, const QModelIndex& parent); + bool dropArchive(const QMimeData* mimeData, int row, const QModelIndex& parent); + + // return the priority of the mod for a drop event + // + int dropPriority(int row, const QModelIndex& parent) const; + private: friend class ModListByPriorityProxy; diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 74b6ed08..454247b6 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -830,13 +830,13 @@ MOBase::IModInterface *OrganizerCore::installMod(const QString &fileName, return nullptr; } -void OrganizerCore::installDownload(int index) +ModInfo::Ptr OrganizerCore::installDownload(int index, int priority) { if (m_InstallationManager.isRunning()) { QMessageBox::information( qApp->activeWindow(), tr("Installation cancelled"), tr("Another installation is currently in progress."), QMessageBox::Ok); - return; + return nullptr; } try { @@ -873,10 +873,15 @@ void OrganizerCore::installDownload(int index) refresh(); int modIndex = ModInfo::getIndex(modName); + ModInfo::Ptr modInfo = nullptr; if (modIndex != UINT_MAX) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + modInfo = ModInfo::getByIndex(modIndex); modInfo->addInstalledFile(modID, fileID); + if (priority != -1) { + m_ModList.changeModPriority(modIndex, priority); + } + if (hasIniTweaks && m_UserInterface != nullptr && (QMessageBox::question(qApp->activeWindow(), tr("Configure Mod"), tr("This mod contains ini tweaks. Do you " @@ -894,6 +899,7 @@ void OrganizerCore::installDownload(int index) } m_DownloadManager.markInstalled(index); emit modInstalled(modName); + return modInfo; } else { m_InstallationManager.notifyInstallationEnd(result, nullptr); @@ -909,6 +915,8 @@ void OrganizerCore::installDownload(int index) } catch (const std::exception &e) { reportError(e.what()); } + + return nullptr; } QString OrganizerCore::resolvePath(const QString &fileName) const diff --git a/src/organizercore.h b/src/organizercore.h index f2b904cd..cb577437 100644 --- a/src/organizercore.h +++ b/src/organizercore.h @@ -376,7 +376,7 @@ public slots: void refreshLists(); - void installDownload(int downloadIndex); + ModInfo::Ptr installDownload(int downloadIndex, int priority = -1); void modStatusChanged(unsigned int index); void modStatusChanged(QList index); -- cgit v1.3.1 From addb38645b41507ae8e0536bb83d3b99d365f664 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Mon, 28 Dec 2020 13:44:26 +0100 Subject: Clean drag&drop of URLs and mods/archives. --- src/mainwindow.cpp | 4 - src/modinfo.cpp | 15 ++-- src/modinfo.h | 8 +- src/modlist.cpp | 172 +++++++++++++++++++++++------------------ src/modlist.h | 26 ++++--- src/modlistbypriorityproxy.cpp | 72 +++++++---------- src/modlistbypriorityproxy.h | 1 - src/modlistview.cpp | 38 --------- src/modlistview.h | 6 -- 9 files changed, 156 insertions(+), 186 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index ea7d5967..df571a2d 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -578,10 +578,6 @@ void MainWindow::setupModList() ui->modList->sortByColumn(ModList::COL_PRIORITY, Qt::AscendingOrder); - connect( - ui->modList, SIGNAL(dropModeUpdate(bool)), - m_OrganizerCore.modList(), SLOT(dropModeUpdate(bool))); - connect( ui->modList->header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), this, SLOT(modListSortIndicatorChanged(int,Qt::SortOrder))); diff --git a/src/modinfo.cpp b/src/modinfo.cpp index a0382fe8..509c3837 100644 --- a/src/modinfo.cpp +++ b/src/modinfo.cpp @@ -47,6 +47,7 @@ using namespace MOShared; std::vector ModInfo::s_Collection; +ModInfo::Ptr ModInfo::s_Overwrite; std::map ModInfo::s_ModsByName; std::map, std::vector> ModInfo::s_ModsByModID; int ModInfo::s_NextID; @@ -108,13 +109,14 @@ ModInfo::Ptr ModInfo::createFromPlugin(const QString &modName, return result; } -void ModInfo::createFromOverwrite(PluginContainer *pluginContainer, - const MOBase::IPluginGame* game, - MOShared::DirectoryEntry **directoryStructure) +ModInfo::Ptr ModInfo::createFromOverwrite( + PluginContainer *pluginContainer, const MOBase::IPluginGame* game, + MOShared::DirectoryEntry **directoryStructure) { QMutexLocker locker(&s_Mutex); - - s_Collection.push_back(ModInfo::Ptr(new ModInfoOverwrite(pluginContainer, game, directoryStructure))); + ModInfo::Ptr overwrite = ModInfo::Ptr(new ModInfoOverwrite(pluginContainer, game, directoryStructure)); + s_Collection.push_back(overwrite); + return overwrite; } unsigned int ModInfo::getNumMods() @@ -237,6 +239,7 @@ void ModInfo::updateFromDisc(const QString &modDirectory, QMutexLocker lock(&s_Mutex); s_Collection.clear(); s_NextID = 0; + s_Overwrite = nullptr; { // list all directories in the mod directory and make a mod out of each QDir mods(QDir::fromNativeSeparators(modDirectory)); @@ -263,7 +266,7 @@ void ModInfo::updateFromDisc(const QString &modDirectory, } } - createFromOverwrite(pluginContainer, game, directoryStructure); + s_Overwrite = createFromOverwrite(pluginContainer, game, directoryStructure); std::sort(s_Collection.begin(), s_Collection.end(), ModInfo::ByName); diff --git a/src/modinfo.h b/src/modinfo.h index d04f6657..3981be18 100644 --- a/src/modinfo.h +++ b/src/modinfo.h @@ -177,6 +177,11 @@ public: // Static functions: */ static unsigned int getIndex(const QString &name); + /** + * @brief Retrieve the overwrite mod. + */ + static ModInfo::Ptr getOverwrite() { return s_Overwrite; } + /** * @brief Find the first mod that fulfills the filter function (after no particular order). * @@ -981,6 +986,7 @@ protected: protected: static std::vector s_Collection; + static ModInfo::Ptr s_Overwrite; static std::map s_ModsByName; int m_PrimaryCategory; @@ -992,7 +998,7 @@ protected: private: - static void createFromOverwrite(PluginContainer* pluginContainer, + static ModInfo::Ptr createFromOverwrite(PluginContainer* pluginContainer, const MOBase::IPluginGame* game, MOShared::DirectoryEntry** directoryStructure); diff --git a/src/modlist.cpp b/src/modlist.cpp index ca4741e6..b79f0b0e 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -69,7 +69,6 @@ ModList::ModList(PluginContainer *pluginContainer, OrganizerCore *organizer) , m_Modified(false) , m_InNotifyChange(false) , m_FontMetrics(QFont()) - , m_DropOnItems(false) , m_PluginContainer(pluginContainer) { m_LastCheck.start(); @@ -689,14 +688,10 @@ Qt::ItemFlags ModList::flags(const QModelIndex &modelIndex) const result |= Qt::ItemIsEditable; } } - if (m_DropOnItems - && (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) == flags.end())) { - result |= Qt::ItemIsDropEnabled; - } - } else { - if (!m_DropOnItems) result |= Qt::ItemIsDropEnabled; } - return result; + + // drop check is handled by canDropMimeData + return result | Qt::ItemIsDropEnabled; } @@ -1113,6 +1108,52 @@ int ModList::dropPriority(int row, const QModelIndex& parent) const return newPriority; } +std::vector ModList::sourceRows(const QMimeData* mimeData) const +{ + QByteArray encoded = mimeData->data("application/x-qabstractitemmodeldatalist"); + QDataStream stream(&encoded, QIODevice::ReadOnly); + std::vector sourceRows; + + while (!stream.atEnd()) { + int sourceRow, col; + QMap roleDataMap; + stream >> sourceRow >> col >> roleDataMap; + if (col == 0) { + sourceRows.push_back(sourceRow); + } + } + return sourceRows; +} + +std::optional> ModList::relativeUrl(const QUrl& url) const +{ + if (!url.isLocalFile()) { + return {}; + } + + QDir allModsDir(Settings::instance().paths().mods()); + QDir overwriteDir(Settings::instance().paths().overwrite()); + + QFileInfo sourceInfo(url.toLocalFile()); + QString sourceFile = sourceInfo.canonicalFilePath(); + + QString relativePath; + QString originName; + + if (sourceFile.startsWith(allModsDir.canonicalPath())) { + QDir relativeDir(allModsDir.relativeFilePath(sourceFile)); + QStringList splitPath = relativeDir.path().split("/"); + originName = splitPath[0]; + splitPath.pop_front(); + return { { splitPath.join("/"), originName } }; + } + else if (sourceFile.startsWith(overwriteDir.canonicalPath())) { + return { { overwriteDir.relativeFilePath(sourceFile), ModInfo::getOverwrite()->name() } }; + } + + return {}; +} + bool ModList::dropURLs(const QMimeData *mimeData, int row, const QModelIndex &parent) { if (row == -1) { @@ -1121,45 +1162,23 @@ bool ModList::dropURLs(const QMimeData *mimeData, int row, const QModelIndex &pa ModInfo::Ptr modInfo = ModInfo::getByIndex(row); QDir modDir = QDir(modInfo->absolutePath()); - QDir allModsDir(Settings::instance().paths().mods()); - QDir overwriteDir(Settings::instance().paths().overwrite()); - QStringList sourceList; QStringList targetList; QList> relativePathList; - unsigned int overwriteIndex = ModInfo::findMod([] (ModInfo::Ptr mod) -> bool { - std::vector flags = mod->getFlags(); - return std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end(); }); - - QString overwriteName = ModInfo::getByIndex(overwriteIndex)->name(); - for (auto url : mimeData->urls()) { - if (!url.isLocalFile()) { - log::debug("URL drop ignored: \"{}\" is not a local file", url.url()); + auto p = relativeUrl(url); + + if (!p) { + log::debug("URL drop ignored: \"{}\" is not a local file or not a known file to MO", url.url()); continue; } + auto [relativePath, originName] = *p; + QFileInfo sourceInfo(url.toLocalFile()); QString sourceFile = sourceInfo.canonicalFilePath(); - QString relativePath; - QString originName; - - if (sourceFile.startsWith(allModsDir.canonicalPath())) { - QDir relativeDir(allModsDir.relativeFilePath(sourceFile)); - QStringList splitPath = relativeDir.path().split("/"); - originName = splitPath[0]; - splitPath.pop_front(); - relativePath = splitPath.join("/"); - } else if (sourceFile.startsWith(overwriteDir.canonicalPath())) { - originName = overwriteName; - relativePath = overwriteDir.relativeFilePath(sourceFile); - } else { - log::debug("URL drop ignored: \"{}\" is not a known file to MO", sourceFile); - continue; - } - QFileInfo targetInfo(modDir.absoluteFilePath(relativePath)); sourceList << sourceFile; targetList << targetInfo.absoluteFilePath(); @@ -1186,24 +1205,13 @@ bool ModList::dropURLs(const QMimeData *mimeData, int row, const QModelIndex &pa bool ModList::dropMod(const QMimeData *mimeData, int row, const QModelIndex &parent) { - try { - QByteArray encoded = mimeData->data("application/x-qabstractitemmodeldatalist"); - QDataStream stream(&encoded, QIODevice::ReadOnly); - std::vector sourceRows; - - while (!stream.atEnd()) { - int sourceRow, col; - QMap roleDataMap; - stream >> sourceRow >> col >> roleDataMap; - if (col == 0) { - sourceRows.push_back(sourceRow); - } - } + int newPriority = dropPriority(row, parent); + if (newPriority == -1) { + return false; + } - int newPriority = dropPriority(row, parent); - if (newPriority == -1) { - return false; - } + try { + std::vector sourceRows = this->sourceRows(mimeData); changeModPriority(sourceRows, newPriority); } catch (const std::exception &e) { @@ -1221,19 +1229,7 @@ bool ModList::dropArchive(const QMimeData* mimeData, int row, const QModelIndex& } try { - QByteArray encoded = mimeData->data("application/x-qabstractitemmodeldatalist"); - QDataStream stream(&encoded, QIODevice::ReadOnly); - std::vector sourceRows; - - while (!stream.atEnd()) { - int sourceRow, col; - QMap roleDataMap; - stream >> sourceRow >> col >> roleDataMap; - if (col == 0) { - sourceRows.push_back(sourceRow); - } - } - + std::vector sourceRows = this->sourceRows(mimeData); if (sourceRows.size() == 1) { emit downloadArchiveDropped(sourceRows[0], priority); } @@ -1245,6 +1241,41 @@ bool ModList::dropArchive(const QMimeData* mimeData, int row, const QModelIndex& return false; } +bool ModList::canDropMimeData(const QMimeData* mimeData, Qt::DropAction action, int row, int column, const QModelIndex& parent) const +{ + if (action == Qt::IgnoreAction) { + return false; + } + + if (mimeData->hasUrls()) { + for (auto& url : mimeData->urls()) { + if (!relativeUrl(url)) { + return false; + } + } + if (row == -1 && parent.isValid()) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(parent.row()); + return modInfo->isRegular() && !modInfo->isSeparator(); + } + } + else if (mimeData->hasText()) { + // drop on item + if (row == -1 && parent.isValid()) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(parent.row()); + return modInfo->isSeparator(); + } + else if (hasIndex(row, column, parent)) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(row); + return modInfo->isSeparator() || !parent.isValid(); + } + else { + return true; + } + } + + return false; +} + bool ModList::dropMimeData(const QMimeData *mimeData, Qt::DropAction action, int row, int, const QModelIndex &parent) { if (action == Qt::IgnoreAction) { @@ -1407,15 +1438,6 @@ QMap ModList::itemData(const QModelIndex &index) const return result; } - -void ModList::dropModeUpdate(bool dropOnItems) -{ - if (m_DropOnItems != dropOnItems) { - m_DropOnItems = dropOnItems; - } -} - - QString ModList::getColumnName(int column) { switch (column) { diff --git a/src/modlist.h b/src/modlist.h index 2ca2fff1..b2eb6be6 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -199,11 +199,13 @@ public: // implementation of virtual functions of QAbstractItemModel virtual bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; virtual Qt::ItemFlags flags(const QModelIndex &modelIndex) const; - virtual Qt::DropActions supportedDropActions() const { return Qt::MoveAction | Qt::CopyAction; } - virtual QStringList mimeTypes() const; - virtual QMimeData *mimeData(const QModelIndexList &indexes) const; - virtual bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent); - virtual bool removeRows(int row, int count, const QModelIndex &parent); + virtual bool removeRows(int row, int count, const QModelIndex& parent); + + Qt::DropActions supportedDropActions() const override { return Qt::MoveAction | Qt::CopyAction; } + QStringList mimeTypes() const override; + QMimeData *mimeData(const QModelIndexList &indexes) const override; + bool canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) const override; + bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override; virtual QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; @@ -213,10 +215,8 @@ public: // implementation of virtual functions of QAbstractItemModel public slots: - void dropModeUpdate(bool dropOnItems); void enableSelected(const QItemSelectionModel *selectionModel); - void disableSelected(const QItemSelectionModel *selectionModel); signals: @@ -369,6 +369,16 @@ private: private: + // retrieve the relative path of file and its origin given a URL from Mime data + // returns an empty optional if the URL is not a valid file for dropping + // + std::optional> relativeUrl(const QUrl&) const; + + // return the source rows from the given mime data for drag&drop of mods or + // installation archives + // + std::vector sourceRows(const QMimeData* mimeData) const; + bool dropURLs(const QMimeData* mimeData, int row, const QModelIndex& parent); bool dropMod(const QMimeData* mimeData, int row, const QModelIndex& parent); bool dropArchive(const QMimeData* mimeData, int row, const QModelIndex& parent); @@ -392,8 +402,6 @@ private: QFontMetrics m_FontMetrics; - bool m_DropOnItems; - std::set m_Overwrite; std::set m_Overwritten; std::set m_ArchiveOverwrite; diff --git a/src/modlistbypriorityproxy.cpp b/src/modlistbypriorityproxy.cpp index 1bbf9459..dc51617e 100644 --- a/src/modlistbypriorityproxy.cpp +++ b/src/modlistbypriorityproxy.cpp @@ -210,64 +210,44 @@ bool ModListByPriorityProxy::canDropMimeData(const QMimeData* data, Qt::DropActi bool ModListByPriorityProxy::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) { - // we need to fix the source row + // we need to fix the source model row int sourceRow = -1; - if (row >= 0) { - if (!parent.isValid()) { - if (row < m_Root.children.size()) { - sourceRow = m_Root.children[row]->index; - } - else { - sourceRow = ModInfo::getNumMods(); - } + if (data->hasUrls()) { + if (parent.isValid()) { + sourceRow = static_cast(parent.internalPointer())->index; } - else { - auto* item = static_cast(parent.internalPointer()); - QStringList what; - for (auto& child : item->children) { - what.append(QString::number(child->index)); + } + else { + if (row >= 0) { + if (!parent.isValid()) { + if (row < m_Root.children.size()) { + sourceRow = m_Root.children[row]->index; + } + else { + sourceRow = ModInfo::getNumMods(); + } } + else { + auto* item = static_cast(parent.internalPointer()); - if (row < item->children.size()) { - sourceRow = item->children[row]->index; - } - else if (parent.row() + 1 < m_Root.children.size()) { - sourceRow = m_Root.children[parent.row() + 1]->index; + if (row < item->children.size()) { + sourceRow = item->children[row]->index; + } + else if (parent.row() + 1 < m_Root.children.size()) { + sourceRow = m_Root.children[parent.row() + 1]->index; + } } } - } - else if (parent.isValid()) { - // this is a drop in a separator - sourceRow = m_Root.children[parent.row() + 1]->index; + else if (parent.isValid()) { + // this is a drop in a separator + sourceRow = m_Root.children[parent.row() + 1]->index; + } } return sourceModel()->dropMimeData(data, action, sourceRow, column, QModelIndex()); } -Qt::ItemFlags ModListByPriorityProxy::flags(const QModelIndex& idx) const -{ - if (!idx.isValid()) { - return sourceModel()->flags(QModelIndex()); - } - - // we check the flags of the root node and if drop is not enabled, it - // means we are dragging files. - Qt::ItemFlags rootFlags = sourceModel()->flags(QModelIndex()); - if (!rootFlags.testFlag(Qt::ItemIsDropEnabled)) { - return sourceModel()->flags(mapToSource(idx)); - } - - auto flags = sourceModel()->flags(mapToSource(idx)); - auto* item = static_cast(idx.internalPointer()); - - if (item->mod->isSeparator()) { - flags |= Qt::ItemIsDropEnabled; - } - - return flags; -} - QModelIndex ModListByPriorityProxy::index(int row, int column, const QModelIndex& parent) const { if (!hasIndex(row, column, parent)) { diff --git a/src/modlistbypriorityproxy.h b/src/modlistbypriorityproxy.h index fdf59182..725a3242 100644 --- a/src/modlistbypriorityproxy.h +++ b/src/modlistbypriorityproxy.h @@ -31,7 +31,6 @@ public: int rowCount(const QModelIndex& parent = QModelIndex()) const override; QModelIndex parent(const QModelIndex& child) const override; - Qt::ItemFlags flags(const QModelIndex& idx) const override; QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; int columnCount(const QModelIndex& index) const override; bool hasChildren(const QModelIndex& parent) const override; diff --git a/src/modlistview.cpp b/src/modlistview.cpp index fcf34749..27e23417 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -2,37 +2,6 @@ #include #include #include -#include - -class ModListViewStyle: public QProxyStyle { -public: - ModListViewStyle(QStyle *style, int indentation); - - void drawPrimitive (PrimitiveElement element, const QStyleOption *option, - QPainter *painter, const QWidget *widget = 0) const; -private: - int m_Indentation; -}; - -ModListViewStyle::ModListViewStyle(QStyle *style, int indentation) - : QProxyStyle(style), m_Indentation(indentation) -{ -} - -void ModListViewStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, - QPainter *painter, const QWidget *widget) const -{ - if (element == QStyle::PE_IndicatorItemViewItemDrop && !option->rect.isNull()) { - QStyleOption opt(*option); - opt.rect.setLeft(m_Indentation); - if (widget) { - opt.rect.setRight(widget->width() - 5); // 5 is an arbitrary value that seems to work ok - } - QProxyStyle::drawPrimitive(element, &opt, painter, widget); - } else { - QProxyStyle::drawPrimitive(element, option, painter, widget); - } -} ModListView::ModListView(QWidget *parent) : QTreeView(parent) @@ -43,13 +12,6 @@ ModListView::ModListView(QWidget *parent) setAutoExpandDelay(500); } -void ModListView::dragEnterEvent(QDragEnterEvent *event) -{ - emit dropModeUpdate(event->mimeData()->hasUrls()); - - QTreeView::dragEnterEvent(event); -} - void ModListView::setModel(QAbstractItemModel *model) { QTreeView::setModel(model); diff --git a/src/modlistview.h b/src/modlistview.h index 982591a3..bc5654ce 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -12,11 +12,6 @@ public: explicit ModListView(QWidget *parent = 0); void setModel(QAbstractItemModel *model) override; -signals: - void dropModeUpdate(bool dropOnRows); - -public slots: - protected: // replace the auto-expand timer from QTreeView to avoid @@ -25,7 +20,6 @@ protected: void timerEvent(QTimerEvent* event) override; void dragMoveEvent(QDragMoveEvent* event) override; - void dragEnterEvent(QDragEnterEvent* event) override; private: -- cgit v1.3.1 From 9db6a9d7931edbb08e74cd1e110794f47d46df3e Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Mon, 28 Dec 2020 14:25:47 +0100 Subject: Save collapse state of separator. --- src/mainwindow.cpp | 2 ++ src/settings.cpp | 35 +++++++++++++++++++++++++++++++++++ src/settings.h | 6 ++++++ src/settingsutilities.h | 8 ++++++++ 4 files changed, 51 insertions(+) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index df571a2d..65ab368d 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2103,6 +2103,7 @@ void MainWindow::readSettings() s.widgets().restoreIndex(ui->groupCombo); s.widgets().restoreIndex(ui->tabWidget); + s.widgets().restoreTreeState(ui->modList); m_Filters->restoreState(s); @@ -2177,6 +2178,7 @@ void MainWindow::storeSettings() s.geometry().saveState(ui->downloadView->header()); s.geometry().saveState(ui->modList->header()); + s.widgets().saveTreeState(ui->modList); s.widgets().saveIndex(ui->groupCombo); s.widgets().saveIndex(ui->executablesListBox); s.widgets().saveIndex(ui->tabWidget); diff --git a/src/settings.cpp b/src/settings.cpp index f5ad83a7..04cfafc9 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1063,6 +1063,41 @@ WidgetSettings::WidgetSettings(QSettings& s, bool globalInstance) } } +std::vector WidgetSettings::allIndex(const QAbstractItemModel* model, int column, const QModelIndex& parent) const +{ + std::vector index; + for (std::size_t i = 0; i < model->rowCount(parent); ++i) { + index.push_back(model->index(i, column, parent)); + + auto cindex = allIndex(model, column, index.back()); + index.insert(index.end(), cindex.begin(), cindex.end()); + } + return index; +} + +void WidgetSettings::saveTreeState(const QTreeView* tv, int role) +{ + QVariantList expanded; + for (auto index : allIndex(tv->model())) { + if (tv->isExpanded(index)) { + expanded.append(index.data(role)); + } + } + set(m_Settings, "Widgets", indexSettingName(tv), expanded); +} + +void WidgetSettings::restoreTreeState(QTreeView* tv, int role) const +{ + if (auto expanded = getOptional(m_Settings, "Widgets", indexSettingName(tv))) { + tv->collapseAll(); + for (auto index : allIndex(tv->model())) { + if (expanded->contains(index.data(role))) { + tv->expand(index); + } + } + } +} + std::optional WidgetSettings::index(const QComboBox* cb) const { return getOptional(m_Settings, "Widgets", indexSettingName(cb)); diff --git a/src/settings.h b/src/settings.h index 4d1258bf..3f60fc7b 100644 --- a/src/settings.h +++ b/src/settings.h @@ -202,6 +202,12 @@ public: // WidgetSettings(QSettings& s, bool globalInstance); + // tree state - this saves the list of expanded items based on the given role + // + std::vector allIndex(const QAbstractItemModel* model, int column = 0, const QModelIndex& parent = QModelIndex()) const; + void saveTreeState(const QTreeView* tv, int role = Qt::DisplayRole); + void restoreTreeState(QTreeView* tv, int role = Qt::DisplayRole) const; + // selected index for a combobox // std::optional index(const QComboBox* cb) const; diff --git a/src/settingsutilities.h b/src/settingsutilities.h index ac6aeb29..53eeff87 100644 --- a/src/settingsutilities.h +++ b/src/settingsutilities.h @@ -25,6 +25,14 @@ struct ValueConverter>> } }; +template <> +struct ValueConverter +{ + static QString convert(const QVariantList& t) + { + return QString("%1").arg(QVariant(t).toStringList().join(",")); + } +}; bool shouldLogSetting(const QString& displayName); -- cgit v1.3.1 From 9d8c64dccbdb5144c6496cbd9ef4eb636f6b4ace Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Mon, 28 Dec 2020 15:20:37 +0100 Subject: Do not set Qt::ItemIsDropEnabled all the time. --- src/mainwindow.cpp | 2 ++ src/modlist.cpp | 18 +++++++++++++----- src/modlist.h | 3 ++- src/modlistview.cpp | 6 ++++++ src/modlistview.h | 5 +++++ 5 files changed, 28 insertions(+), 6 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 65ab368d..48a935ae 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -578,6 +578,8 @@ void MainWindow::setupModList() ui->modList->sortByColumn(ModList::COL_PRIORITY, Qt::AscendingOrder); + connect(ui->modList, &ModListView::dragEntered, m_OrganizerCore.modList(), &ModList::onDragEnter); + connect( ui->modList->header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), this, SLOT(modListSortIndicatorChanged(int,Qt::SortOrder))); diff --git a/src/modlist.cpp b/src/modlist.cpp index a058e71c..79dbf815 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -664,7 +664,6 @@ QVariant ModList::headerData(int section, Qt::Orientation orientation, return QAbstractItemModel::headerData(section, orientation, role); } - Qt::ItemFlags ModList::flags(const QModelIndex &modelIndex) const { Qt::ItemFlags result = QAbstractItemModel::flags(modelIndex); @@ -688,10 +687,15 @@ Qt::ItemFlags ModList::flags(const QModelIndex &modelIndex) const result |= Qt::ItemIsEditable; } } + if (modInfo->isSeparator() || m_DropOnMod) { + result |= Qt::ItemIsDropEnabled; + } + } + else if (!m_DropOnMod) { + result |= Qt::ItemIsDropEnabled; } - // drop check is handled by canDropMimeData - return result | Qt::ItemIsDropEnabled; + return result; } @@ -1241,6 +1245,11 @@ bool ModList::dropArchive(const QMimeData* mimeData, int row, const QModelIndex& return false; } +void ModList::onDragEnter(const QMimeData* mimeData) +{ + m_DropOnMod = mimeData->hasUrls(); +} + bool ModList::canDropMimeData(const QMimeData* mimeData, Qt::DropAction action, int row, int column, const QModelIndex& parent) const { if (action == Qt::IgnoreAction) { @@ -1261,8 +1270,7 @@ bool ModList::canDropMimeData(const QMimeData* mimeData, Qt::DropAction action, else if (mimeData->hasText()) { // drop on item if (row == -1 && parent.isValid()) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(parent.row()); - return modInfo->isSeparator(); + return true; } else if (hasIndex(row, column, parent)) { ModInfo::Ptr modInfo = ModInfo::getByIndex(row); diff --git a/src/modlist.h b/src/modlist.h index eebb1105..4e50c959 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -215,7 +215,7 @@ public: // implementation of virtual functions of QAbstractItemModel public slots: - + void onDragEnter(const QMimeData* data); void enableSelected(const QItemSelectionModel *selectionModel); void disableSelected(const QItemSelectionModel *selectionModel); @@ -399,6 +399,7 @@ private: mutable bool m_Modified; bool m_InNotifyChange; + bool m_DropOnMod = false; QFontMetrics m_FontMetrics; diff --git a/src/modlistview.cpp b/src/modlistview.cpp index 27e23417..91bdced3 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -18,6 +18,12 @@ void ModListView::setModel(QAbstractItemModel *model) setVerticalScrollBar(new ViewMarkingScrollBar(model, this)); } +void ModListView::dragEnterEvent(QDragEnterEvent* event) +{ + emit dragEntered(event->mimeData()); + QTreeView::dragEnterEvent(event); +} + void ModListView::dragMoveEvent(QDragMoveEvent* event) { if (autoExpandDelay() >= 0) { diff --git a/src/modlistview.h b/src/modlistview.h index bc5654ce..9546321e 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -12,6 +12,10 @@ public: explicit ModListView(QWidget *parent = 0); void setModel(QAbstractItemModel *model) override; +signals: + + void dragEntered(const QMimeData* mimeData); + protected: // replace the auto-expand timer from QTreeView to avoid @@ -19,6 +23,7 @@ protected: QBasicTimer openTimer; void timerEvent(QTimerEvent* event) override; + void dragEnterEvent(QDragEnterEvent* event) override; void dragMoveEvent(QDragMoveEvent* event) override; private: -- cgit v1.3.1 From b340c564cfd151540bf5b03f3f878153b8f120ee Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Mon, 28 Dec 2020 17:15:22 +0100 Subject: Fix keyboard move selection. --- src/mainwindow.cpp | 115 +++++++++++++++++++++++++++++++---------- src/mainwindow.h | 7 ++- src/modlist.cpp | 29 +++++------ src/modlist.h | 15 +++--- src/modlistbypriorityproxy.cpp | 10 ++-- src/modlistbypriorityproxy.h | 1 + src/organizercore.cpp | 2 - 7 files changed, 125 insertions(+), 54 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 48a935ae..61d0e5bb 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -548,9 +548,12 @@ MainWindow::MainWindow(Settings &settings void MainWindow::updateModListByPriorityProxy() { + if (ui->groupCombo->currentIndex() != 0) { + return; + } if (m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY && m_ModListSortProxy->sortOrder() == Qt::AscendingOrder) { m_ModListSortProxy->setSourceModel(m_ModListByPriorityProxy); - emit m_OrganizerCore.modList()->layoutChanged(); + m_ModListByPriorityProxy->refresh(); } else { m_ModListSortProxy->setSourceModel(m_OrganizerCore.modList()); @@ -579,6 +582,7 @@ void MainWindow::setupModList() ui->modList->sortByColumn(ModList::COL_PRIORITY, Qt::AscendingOrder); connect(ui->modList, &ModListView::dragEntered, m_OrganizerCore.modList(), &ModList::onDragEnter); + connect(m_OrganizerCore.modList(), &ModList::modPrioritiesChanged, this, &MainWindow::onModPrioritiesChanged); connect( ui->modList->header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), @@ -2435,8 +2439,58 @@ void MainWindow::esplist_changed() updatePluginCount(); } -void MainWindow::modorder_changed() +QModelIndex MainWindow::modViewIndexToModel(const QModelIndex& index) const +{ + auto sindex = index; + + // remove the sort proxy. + sindex = m_ModListSortProxy->mapToSource(index); + + // if there is another proxy + if (auto* proxy = qobject_cast(m_ModListSortProxy->sourceModel())) { + sindex = proxy->mapToSource(sindex); + } + + return sindex; +} + +QModelIndex MainWindow::modModelIndexToView(const QModelIndex& index) const +{ + auto dindex = index; + + // if there is another proxy than the sort + if (auto* proxy = qobject_cast(m_ModListSortProxy->sourceModel())) { + dindex = proxy->mapFromSource(dindex); + } + + // add the sort proxy + dindex = m_ModListSortProxy->mapFromSource(dindex); + + return dindex; + +} + +void MainWindow::onModPrioritiesChanged(std::vector const& indices) { + // if we have collapsible separators, we need to refresh, expand if necessary, + // and recreate the selection + if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy) { + + // manually retain the selection and restore it after + QModelIndex current = modViewIndexToModel(ui->modList->currentIndex()); + std::vector selected; + for (const auto& idx : ui->modList->selectionModel()->selectedRows()) { + selected.push_back(modViewIndexToModel(idx)); + } + + m_ModListByPriorityProxy->refresh(); + + ui->modList->setCurrentIndex(modModelIndexToView(current)); + for (auto idx : selected) { + ui->modList->selectionModel()->select(modModelIndexToView(idx), QItemSelectionModel::Select | QItemSelectionModel::Rows); + } + } + for (unsigned int i = 0; i < m_OrganizerCore.currentProfile()->numMods(); ++i) { int priority = m_OrganizerCore.currentProfile()->getModPriority(i); if (m_OrganizerCore.currentProfile()->modEnabled(i)) { @@ -2453,7 +2507,7 @@ void MainWindow::modorder_changed() { // refresh selection QModelIndex current = ui->modList->currentIndex(); if (current.isValid()) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(current.data(Qt::UserRole + 1).toInt()); + ModInfo::Ptr modInfo = ModInfo::getByIndex(current.data(ModList::IndexRole).toInt()); // clear caches on all mods conflicting with the moved mod for (int i : modInfo->getModOverwrite()) { ModInfo::getByIndex(i)->clearCaches(); @@ -2478,8 +2532,9 @@ void MainWindow::modorder_changed() m_OrganizerCore.modList()->setOverwriteMarkers(modInfo->getModOverwrite(), modInfo->getModOverwritten()); m_OrganizerCore.modList()->setArchiveOverwriteMarkers(modInfo->getModArchiveOverwrite(), modInfo->getModArchiveOverwritten()); m_OrganizerCore.modList()->setArchiveLooseOverwriteMarkers(modInfo->getModArchiveLooseOverwrite(), modInfo->getModArchiveLooseOverwritten()); - if (m_ModListSortProxy != nullptr) + if (m_ModListSortProxy != nullptr) { m_ModListSortProxy->invalidate(); + } ui->modList->verticalScrollBar()->repaint(); } } @@ -2624,7 +2679,7 @@ void MainWindow::modlistSelectionsChanged(const QItemSelection &selected) if (selected.count()) { auto selection = selected.last(); auto index = selection.indexes().last(); - ModInfo::Ptr selectedMod = ModInfo::getByIndex(index.data(Qt::UserRole + 1).toInt()); + ModInfo::Ptr selectedMod = ModInfo::getByIndex(index.data(ModList::IndexRole).toInt()); m_OrganizerCore.modList()->setOverwriteMarkers(selectedMod->getModOverwrite(), selectedMod->getModOverwritten()); m_OrganizerCore.modList()->setArchiveOverwriteMarkers(selectedMod->getModArchiveOverwrite(), selectedMod->getModArchiveOverwritten()); m_OrganizerCore.modList()->setArchiveLooseOverwriteMarkers(selectedMod->getModArchiveLooseOverwrite(), selectedMod->getModArchiveLooseOverwritten()); @@ -2669,7 +2724,7 @@ void MainWindow::removeMod_clicked() int i = 0; for (QModelIndex idx : selection->selectedRows()) { QString name = idx.data().toString(); - if (!ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->isRegular()) { + if (!ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->isRegular()) { continue; } @@ -2684,7 +2739,7 @@ void MainWindow::removeMod_clicked() mods += "
  • ...
  • "; } - modNames.append(ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->name()); + modNames.append(ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->name()); ++i; } if (QMessageBox::question(this, tr("Confirm"), @@ -2776,7 +2831,7 @@ void MainWindow::endorse_clicked() } for (QModelIndex idx : selection->selectedRows()) { - ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->endorse(true); + ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->endorse(true); } }); } @@ -2786,7 +2841,7 @@ void MainWindow::dontendorse_clicked() QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { for (QModelIndex idx : selection->selectedRows()) { - ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->setNeverEndorse(); + ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->setNeverEndorse(); } } else { @@ -2812,7 +2867,7 @@ void MainWindow::unendorse_clicked() } for (QModelIndex idx : selection->selectedRows()) { - ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->endorse(false); + ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->endorse(false); } }); } @@ -2831,7 +2886,7 @@ void MainWindow::track_clicked() m_OrganizerCore.loggedInAction(this, [this] { QItemSelectionModel *selection = ui->modList->selectionModel(); for (auto idx : selection->selectedRows()) { - ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->track(true); + ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->track(true); } }); } @@ -2841,7 +2896,7 @@ void MainWindow::untrack_clicked() m_OrganizerCore.loggedInAction(this, [this] { QItemSelectionModel *selection = ui->modList->selectionModel(); for (auto idx : selection->selectedRows()) { - ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->track(false); + ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->track(false); } }); } @@ -3033,7 +3088,7 @@ void MainWindow::ignoreMissingData_clicked() std::vector changed; for (QModelIndex idx : rows) { - int row_idx = idx.data(Qt::UserRole + 1).toInt(); + int row_idx = idx.data(ModList::IndexRole).toInt(); ModInfo::Ptr info = ModInfo::getByIndex(row_idx); info->markValidated(true); changed.push_back(info); @@ -3058,7 +3113,7 @@ void MainWindow::markConverted_clicked() std::vector changed; for (QModelIndex idx : rows) { - int row_idx = idx.data(Qt::UserRole + 1).toInt(); + int row_idx = idx.data(ModList::IndexRole).toInt(); ModInfo::Ptr info = ModInfo::getByIndex(row_idx); info->markConverted(true); changed.push_back(info); @@ -3097,7 +3152,7 @@ void MainWindow::restoreHiddenFiles_clicked() for (QModelIndex idx : selection->selectedRows()) { QString name = idx.data().toString(); - int row_idx = idx.data(Qt::UserRole + 1).toInt(); + int row_idx = idx.data(ModList::IndexRole).toInt(); ModInfo::Ptr modInfo = ModInfo::getByIndex(row_idx); const auto flags = modInfo->getFlags(); @@ -3116,7 +3171,7 @@ void MainWindow::restoreHiddenFiles_clicked() mods += "
  • ...
  • "; } - modNames.append(ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt())->name()); + modNames.append(ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->name()); ++i; } if (QMessageBox::question(this, tr("Confirm"), @@ -3125,7 +3180,7 @@ void MainWindow::restoreHiddenFiles_clicked() for (QModelIndex idx : selection->selectedRows()) { - int row_idx = idx.data(Qt::UserRole + 1).toInt(); + int row_idx = idx.data(ModList::IndexRole).toInt(); ModInfo::Ptr modInfo = ModInfo::getByIndex(row_idx); const auto flags = modInfo->getFlags(); @@ -3186,7 +3241,7 @@ void MainWindow::visitOnNexus_clicked() QString gameName; for (QModelIndex idx : selection->selectedRows()) { - row_idx = idx.data(Qt::UserRole + 1).toInt(); + row_idx = idx.data(ModList::IndexRole).toInt(); info = ModInfo::getByIndex(row_idx); int modID = info->nexusId(); gameName = info->gameName(); @@ -3224,7 +3279,7 @@ void MainWindow::visitWebPage_clicked() ModInfo::Ptr info; QString gameName; for (QModelIndex idx : selection->selectedRows()) { - row_idx = idx.data(Qt::UserRole + 1).toInt(); + row_idx = idx.data(ModList::IndexRole).toInt(); info = ModInfo::getByIndex(row_idx); const auto url = info->parseCustomURL(); @@ -3245,7 +3300,7 @@ void MainWindow::visitWebPage_clicked() void MainWindow::visitNexusOrWebPage(const QModelIndex& idx) { - int row_idx = idx.data(Qt::UserRole + 1).toInt(); + int row_idx = idx.data(ModList::IndexRole).toInt(); ModInfo::Ptr info = ModInfo::getByIndex(row_idx); if (!info) { @@ -3293,7 +3348,7 @@ void MainWindow::openExplorer_clicked() QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); shell::Explore(info->absolutePath()); } } @@ -3332,7 +3387,7 @@ void MainWindow::openExplorer_activated() if (selection->hasSelection() && selection->selectedRows().count() == 1 ) { QModelIndex idx = selection->currentIndex(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + ModInfo::Ptr modInfo = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); std::vector flags = modInfo->getFlags(); if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { @@ -3621,7 +3676,7 @@ void MainWindow::setColor_clicked() QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); info->setColor(currentColor); } } @@ -3637,7 +3692,7 @@ void MainWindow::resetColor_clicked() QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); info->setColor(color); } } @@ -4196,7 +4251,7 @@ void MainWindow::ignoreUpdate() { QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); info->ignoreUpdate(true); } } @@ -4214,7 +4269,7 @@ void MainWindow::checkModUpdates_clicked() QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); IDs.insert(std::make_pair(info->gameName(), info->nexusId())); } } else { @@ -4229,7 +4284,7 @@ void MainWindow::unignoreUpdate() QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(Qt::UserRole + 1).toInt()); + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); info->ignoreUpdate(false); } } @@ -4640,6 +4695,12 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) initModListContextMenu(allMods); allMods->setTitle(tr("All Mods")); menu.addMenu(allMods); + + if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy) { + menu.addAction(tr("Collapse all"), ui->modList, &QTreeView::collapseAll); + menu.addAction(tr("Expand all"), ui->modList, &QTreeView::expandAll); + } + menu.addSeparator(); ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); diff --git a/src/mainwindow.h b/src/mainwindow.h index ccfd4881..61a8b5e3 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -148,7 +148,7 @@ public: ModInfo::Ptr previousModInList(); public slots: - void modorder_changed(); + void onModPrioritiesChanged(std::vector const& indices); void esplist_changed(); void refresherProgress(const DirectoryRefreshProgress* p); @@ -607,8 +607,13 @@ private slots: // ui slots void storeSettings(); void readSettings(); + void setupModList(); void updateModListByPriorityProxy(); + + // map index from the modlist view to the modlist model, handling proxy + QModelIndex modViewIndexToModel(const QModelIndex& index) const; + QModelIndex modModelIndexToView(const QModelIndex& index) const; }; #endif // MAINWINDOW_H diff --git a/src/modlist.cpp b/src/modlist.cpp index 79dbf815..a6286007 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -336,7 +336,7 @@ QVariant ModList::data(const QModelIndex &modelIndex, int role) const } else { return modInfo->nexusId(); } - } else if (role == Qt::UserRole + 1) { + } else if (role == IndexRole) { return modIndex; } else if (role == Qt::UserRole + 2) { switch (column) { @@ -592,8 +592,7 @@ bool ModList::setData(const QModelIndex &index, const QVariant &value, int role) } if (ok) { m_Profile->setModPriority(modID, newPriority); - - emit modorder_changed(); + emit modPrioritiesChanged({ modID }); result = true; } else { result = false; @@ -765,7 +764,7 @@ void ModList::changeModPriority(std::vector sourceIndices, int newPriority) emit layoutChanged(); - emit modorder_changed(); + emit modPrioritiesChanged(sourceIndices); } @@ -777,8 +776,7 @@ void ModList::changeModPriority(int sourceIndex, int newPriority) m_Profile->setModPriority(sourceIndex, newPriority); emit layoutChanged(); - - emit modorder_changed(); + emit modPrioritiesChanged({ sourceIndex }); } void ModList::setOverwriteMarkers(const std::set &overwrite, const std::set &overwritten) @@ -1525,17 +1523,18 @@ bool ModList::moveSelection(QAbstractItemView *itemView, int direction) rows.swapItemsAt(i, rows.size() - i - 1); } } + std::vector allIndex; for (QModelIndex idx : rows) { - if (filterModel != nullptr) { - idx = filterModel->mapToSource(idx); - } - int newPriority = m_Profile->getModPriority(idx.row()) + offset; + auto index = idx.data(IndexRole).toInt(); + allIndex.push_back(index); + int newPriority = m_Profile->getModPriority(index) + offset; if ((newPriority >= 0) && (newPriority < static_cast(m_Profile->numRegularMods()))) { - m_Profile->setModPriority(idx.row(), newPriority); - notifyChange(idx.row()); + m_Profile->setModPriority(index, newPriority); + notifyChange(index); } } - emit modorder_changed(); + + emit modPrioritiesChanged(allIndex); return true; } @@ -1547,7 +1546,7 @@ bool ModList::deleteSelection(QAbstractItemView *itemView) if (rows.count() > 1) { emit removeSelectedMods(); } else if (rows.count() == 1) { - removeRow(rows[0].data(Qt::UserRole + 1).toInt(), QModelIndex()); + removeRow(rows[0].data(IndexRole).toInt(), QModelIndex()); } return true; } @@ -1562,7 +1561,7 @@ bool ModList::toggleSelection(QAbstractItemView *itemView) QList modsToDisable; QModelIndexList dirtyMods; for (QModelIndex idx : selectionModel->selectedRows()) { - int modId = idx.data(Qt::UserRole + 1).toInt(); + int modId = idx.data(IndexRole).toInt(); if (m_Profile->modEnabled(modId)) { modsToDisable.append(modId); dirtyMods.append(idx); diff --git a/src/modlist.h b/src/modlist.h index 4e50c959..83e8ec9c 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -55,6 +55,10 @@ class ModList : public QAbstractItemModel public: + // role of the index of the mod + // + constexpr static int IndexRole = Qt::UserRole + 1; + enum EColumn { COL_NAME, COL_CONFLICTFLAGS, @@ -70,8 +74,6 @@ public: COL_LASTCOLUMN = COL_NOTES, }; - friend class ModListProxy; - using SignalModInstalled = boost::signals2::signal; using SignalModRemoved = boost::signals2::signal; using SignalModStateChanged = boost::signals2::signal&)>; @@ -222,12 +224,12 @@ public slots: signals: /** - * @brief emitted whenever the sorting in the list was changed by the user + * @brief Emitted whenever the priority of mods changes * - * the sorting of the list can only be manually changed if the list is sorted by priority - * in which case the move is intended to change the priority of a mod + * The sorting of the list can only be manually changed if the list is sorted by priority + * in which case the move is intended to change the priority of a mod. **/ - void modorder_changed(); + void modPrioritiesChanged(std::vector const& index); /** * @brief emitted when the model wants a text to be displayed by the UI @@ -389,6 +391,7 @@ private: private: + friend class ModListProxy; friend class ModListByPriorityProxy; OrganizerCore *m_Organizer; diff --git a/src/modlistbypriorityproxy.cpp b/src/modlistbypriorityproxy.cpp index eb931aa9..c4eb14b3 100644 --- a/src/modlistbypriorityproxy.cpp +++ b/src/modlistbypriorityproxy.cpp @@ -20,13 +20,17 @@ void ModListByPriorityProxy::setSourceModel(QAbstractItemModel* model) if (sourceModel()) { m_CollapsedItems.clear(); - connect(sourceModel(), &QAbstractItemModel::layoutChanged, this, &ModListByPriorityProxy::buildTree, Qt::UniqueConnection); connect(sourceModel(), &QAbstractItemModel::rowsRemoved, this, [this]() { buildTree(); }, Qt::UniqueConnection); - connect(sourceModel(), &QAbstractItemModel::modelReset, this, &ModListByPriorityProxy::buildTree, Qt::UniqueConnection); - buildTree(); + // connect(sourceModel(), &QAbstractItemModel::modelReset, this, &ModListByPriorityProxy::buildTree, Qt::UniqueConnection); + refresh(); } } +void ModListByPriorityProxy::refresh() +{ + buildTree(); +} + void ModListByPriorityProxy::buildTree() { if (!sourceModel()) return; diff --git a/src/modlistbypriorityproxy.h b/src/modlistbypriorityproxy.h index 725a3242..19d79f7f 100644 --- a/src/modlistbypriorityproxy.h +++ b/src/modlistbypriorityproxy.h @@ -26,6 +26,7 @@ public: ~ModListByPriorityProxy(); void setProfile(Profile* profile) { m_Profile = profile; } + void refresh(); void setSourceModel(QAbstractItemModel* sourceModel) override; diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 454247b6..159296b7 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -255,8 +255,6 @@ void OrganizerCore::setUserInterface(IUserInterface* ui) SLOT(clearOverwrite())); connect(&m_ModList, SIGNAL(fileMoved(QString, QString, QString)), w, SLOT(fileMoved(QString, QString, QString))); - connect(&m_ModList, SIGNAL(modorder_changed()), w, - SLOT(modorder_changed())); connect(&m_PluginList, SIGNAL(writePluginsList()), w, SLOT(esplist_changed())); connect(&m_PluginList, SIGNAL(esplist_changed()), w, -- cgit v1.3.1 From 64f771bc1f974c60c508a65b7a0d0e412a27fb04 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Mon, 28 Dec 2020 19:28:16 +0100 Subject: Refresh by-priority proxy after install and focus on the newly installed mod. --- src/mainwindow.cpp | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 61d0e5bb..9ca7e534 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2551,10 +2551,14 @@ void MainWindow::modInstalled(const QString &modName) QModelIndex qIndex = m_OrganizerCore.modList()->index(index, 0); if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy) { + m_ModListByPriorityProxy->refresh(); qIndex = m_ModListByPriorityProxy->mapFromSource(qIndex); ui->modList->expand(m_ModListSortProxy->mapFromSource(qIndex)); } + + ui->modList->setCurrentIndex(m_ModListSortProxy->mapFromSource(qIndex)); ui->modList->scrollTo(m_ModListSortProxy->mapFromSource(qIndex)); + ui->modList->setFocus(Qt::OtherFocusReason); // force an update to happen std::multimap IDs; -- cgit v1.3.1 From d979e60aed14b368ac9badf0b88c06f61c17893b Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Tue, 29 Dec 2020 01:35:02 +0100 Subject: Fix automatic refresh of the collapsible separator proxy. --- src/mainwindow.cpp | 50 ------------------------------------------ src/mainwindow.h | 4 ---- src/modlist.cpp | 30 +++++++++++++++++++++++++ src/modlist.h | 5 +++++ src/modlistbypriorityproxy.cpp | 3 ++- 5 files changed, 37 insertions(+), 55 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 9ca7e534..1891e496 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2439,58 +2439,8 @@ void MainWindow::esplist_changed() updatePluginCount(); } -QModelIndex MainWindow::modViewIndexToModel(const QModelIndex& index) const -{ - auto sindex = index; - - // remove the sort proxy. - sindex = m_ModListSortProxy->mapToSource(index); - - // if there is another proxy - if (auto* proxy = qobject_cast(m_ModListSortProxy->sourceModel())) { - sindex = proxy->mapToSource(sindex); - } - - return sindex; -} - -QModelIndex MainWindow::modModelIndexToView(const QModelIndex& index) const -{ - auto dindex = index; - - // if there is another proxy than the sort - if (auto* proxy = qobject_cast(m_ModListSortProxy->sourceModel())) { - dindex = proxy->mapFromSource(dindex); - } - - // add the sort proxy - dindex = m_ModListSortProxy->mapFromSource(dindex); - - return dindex; - -} - void MainWindow::onModPrioritiesChanged(std::vector const& indices) { - // if we have collapsible separators, we need to refresh, expand if necessary, - // and recreate the selection - if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy) { - - // manually retain the selection and restore it after - QModelIndex current = modViewIndexToModel(ui->modList->currentIndex()); - std::vector selected; - for (const auto& idx : ui->modList->selectionModel()->selectedRows()) { - selected.push_back(modViewIndexToModel(idx)); - } - - m_ModListByPriorityProxy->refresh(); - - ui->modList->setCurrentIndex(modModelIndexToView(current)); - for (auto idx : selected) { - ui->modList->selectionModel()->select(modModelIndexToView(idx), QItemSelectionModel::Select | QItemSelectionModel::Rows); - } - } - for (unsigned int i = 0; i < m_OrganizerCore.currentProfile()->numMods(); ++i) { int priority = m_OrganizerCore.currentProfile()->getModPriority(i); if (m_OrganizerCore.currentProfile()->modEnabled(i)) { diff --git a/src/mainwindow.h b/src/mainwindow.h index 61a8b5e3..8dd72174 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -610,10 +610,6 @@ private slots: // ui slots void setupModList(); void updateModListByPriorityProxy(); - - // map index from the modlist view to the modlist model, handling proxy - QModelIndex modViewIndexToModel(const QModelIndex& index) const; - QModelIndex modModelIndexToView(const QModelIndex& index) const; }; #endif // MAINWINDOW_H diff --git a/src/modlist.cpp b/src/modlist.cpp index 8c14d509..1f2f1171 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -1493,14 +1493,33 @@ QString ModList::getColumnToolTip(int column) const } } +QModelIndex ModList::indexToProxy(QAbstractItemModel* proxyModel, const QModelIndex& index) +{ + if (!proxyModel) { + return QModelIndex(); + } + + if (proxyModel == this) { + return index; + } + + if (auto* proxy = qobject_cast(proxyModel)) { + return proxy->mapFromSource(indexToProxy(proxy->sourceModel(), index)); + } + + return QModelIndex(); +} bool ModList::moveSelection(QAbstractItemView *itemView, int direction) { QItemSelectionModel *selectionModel = itemView->selectionModel(); + int currentIndex = itemView->currentIndex().data(IndexRole).toInt(); const QAbstractProxyModel *proxyModel = qobject_cast(selectionModel->model()); const QSortFilterProxyModel *filterModel = nullptr; + emit layoutAboutToBeChanged(); + while ((filterModel == nullptr) && (proxyModel != nullptr)) { filterModel = qobject_cast(proxyModel); if (filterModel == nullptr) { @@ -1534,7 +1553,18 @@ bool ModList::moveSelection(QAbstractItemView *itemView, int direction) } } + emit layoutChanged(); + emit modPrioritiesChanged(allIndex); + + // reset the selection and the index + itemView->setCurrentIndex(indexToProxy(itemView->model(), index(currentIndex, 0))); + for (auto idx : allIndex) { + itemView->selectionModel()->select( + indexToProxy(itemView->selectionModel()->model(), index(idx, 0)), + QItemSelectionModel::Select | QItemSelectionModel::Rows); + } + return true; } diff --git a/src/modlist.h b/src/modlist.h index 83e8ec9c..edf7d53a 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -371,6 +371,11 @@ private: private: + // convert an index of the modlist to an index for the given model, assuming + // the given model is a proxy (of a proxy (of... )) the modlist + // + QModelIndex indexToProxy(QAbstractItemModel* proxyModel, const QModelIndex& index); + // retrieve the relative path of file and its origin given a URL from Mime data // returns an empty optional if the URL is not a valid file for dropping // diff --git a/src/modlistbypriorityproxy.cpp b/src/modlistbypriorityproxy.cpp index a5f8667f..0b73ba78 100644 --- a/src/modlistbypriorityproxy.cpp +++ b/src/modlistbypriorityproxy.cpp @@ -20,8 +20,9 @@ void ModListByPriorityProxy::setSourceModel(QAbstractItemModel* model) if (sourceModel()) { m_CollapsedItems.clear(); + connect(sourceModel(), &QAbstractItemModel::layoutChanged, this, [this]() { buildTree(); }, Qt::UniqueConnection); connect(sourceModel(), &QAbstractItemModel::rowsRemoved, this, [this]() { buildTree(); }, Qt::UniqueConnection); - // connect(sourceModel(), &QAbstractItemModel::modelReset, this, &ModListByPriorityProxy::buildTree, Qt::UniqueConnection); + connect(sourceModel(), &QAbstractItemModel::modelReset, this, &ModListByPriorityProxy::buildTree, Qt::UniqueConnection); refresh(); } } -- cgit v1.3.1 From 48fc724a0dba83874b431bd3f90ed061db64b3f7 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Tue, 29 Dec 2020 12:15:40 +0100 Subject: Remove non-necessary refresh() of the proxy on mod installed. --- src/mainwindow.cpp | 1 - 1 file changed, 1 deletion(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 1891e496..d083330f 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2501,7 +2501,6 @@ void MainWindow::modInstalled(const QString &modName) QModelIndex qIndex = m_OrganizerCore.modList()->index(index, 0); if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy) { - m_ModListByPriorityProxy->refresh(); qIndex = m_ModListByPriorityProxy->mapFromSource(qIndex); ui->modList->expand(m_ModListSortProxy->mapFromSource(qIndex)); } -- cgit v1.3.1 From e5744941aed23a160c7329be0f2cb79af7d3a928 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Tue, 29 Dec 2020 12:18:40 +0100 Subject: Fix dropping below/above separators. --- src/mainwindow.cpp | 1 + src/modlistbypriorityproxy.cpp | 18 +++++++++++++++++- src/modlistbypriorityproxy.h | 3 +++ src/modlistview.cpp | 10 ++++++---- src/modlistview.h | 24 +++++++++++++++++++----- 5 files changed, 46 insertions(+), 10 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index d083330f..7c72f132 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -582,6 +582,7 @@ void MainWindow::setupModList() ui->modList->sortByColumn(ModList::COL_PRIORITY, Qt::AscendingOrder); connect(ui->modList, &ModListView::dragEntered, m_OrganizerCore.modList(), &ModList::onDragEnter); + connect(ui->modList, &ModListView::dropEntered, m_ModListByPriorityProxy, &ModListByPriorityProxy::onDropEnter); connect(m_OrganizerCore.modList(), &ModList::modPrioritiesChanged, this, &MainWindow::onModPrioritiesChanged); connect( diff --git a/src/modlistbypriorityproxy.cpp b/src/modlistbypriorityproxy.cpp index 0b73ba78..756d3bcf 100644 --- a/src/modlistbypriorityproxy.cpp +++ b/src/modlistbypriorityproxy.cpp @@ -215,8 +215,13 @@ bool ModListByPriorityProxy::canDropMimeData(const QMimeData* data, Qt::DropActi return false; } + // if the previous row is a collapsed separator, disable dropping if (row > 0 && m_Root.children[row - 1]->mod->isSeparator()) { - if (m_Root.children[row]->mod->isSeparator() || m_Root.children[row]->mod->isOverwrite()) { + // we cannot use the name of the mod directly because it does not exactly + // match the display value (e.g. for separators) + QString display = sourceModel()->index(m_Root.children[row - 1]->index, ModList::COL_NAME).data(Qt::DisplayRole).toString(); + if (m_CollapsedItems.contains(display) + && (m_Root.children[row]->mod->isSeparator() || m_Root.children[row]->mod->isOverwrite())) { return false; } } @@ -240,6 +245,12 @@ bool ModListByPriorityProxy::dropMimeData(const QMimeData* data, Qt::DropAction if (!parent.isValid()) { if (row < m_Root.children.size()) { sourceRow = m_Root.children[row]->index; + if (row > 0 + && m_Root.children[row - 1]->mod->isSeparator() + && !m_Root.children[row - 1]->children.empty() + && m_DropPosition == ModListView::DropPosition::BelowItem) { + sourceRow = m_Root.children[row - 1]->children[0]->index; + } } else { sourceRow = ModInfo::getNumMods(); @@ -282,6 +293,11 @@ QModelIndex ModListByPriorityProxy::index(int row, int column, const QModelIndex return createIndex(row, column, parentItem->children[row].get()); } +void ModListByPriorityProxy::onDropEnter(const QMimeData*, ModListView::DropPosition dropPosition) +{ + m_DropPosition = dropPosition; +} + void ModListByPriorityProxy::expanded(const QModelIndex& index) { auto it = m_CollapsedItems.find(index.data(Qt::DisplayRole).toString()); diff --git a/src/modlistbypriorityproxy.h b/src/modlistbypriorityproxy.h index 19d79f7f..cb50352f 100644 --- a/src/modlistbypriorityproxy.h +++ b/src/modlistbypriorityproxy.h @@ -13,6 +13,7 @@ #include #include "modinfo.h" +#include "modlistview.h" class ModList; class Profile; @@ -48,6 +49,7 @@ signals: public slots: + void onDropEnter(const QMimeData* data, ModListView::DropPosition dropPosition); void expanded(const QModelIndex& index); void collapsed(const QModelIndex& index); @@ -82,6 +84,7 @@ private: private: Profile* m_Profile; + ModListView::DropPosition m_DropPosition = ModListView::DropPosition::OnItem; }; #endif //GROUPINGPROXY_H diff --git a/src/modlistview.cpp b/src/modlistview.cpp index e966ce4e..b1cce82e 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -3,16 +3,16 @@ #include #include -ModListView::ModListView(QWidget *parent) +ModListView::ModListView(QWidget* parent) : QTreeView(parent) - , m_Scrollbar(new ViewMarkingScrollBar(this->model(), this)) + , m_scrollbar(new ViewMarkingScrollBar(this->model(), this)) { - setVerticalScrollBar(m_Scrollbar); + setVerticalScrollBar(m_scrollbar); MOBase::setCustomizableColumns(this); setAutoExpandDelay(500); } -void ModListView::setModel(QAbstractItemModel *model) +void ModListView::setModel(QAbstractItemModel* model) { QTreeView::setModel(model); setVerticalScrollBar(new ViewMarkingScrollBar(model, this)); @@ -38,6 +38,8 @@ void ModListView::dragMoveEvent(QDragMoveEvent* event) void ModListView::dropEvent(QDropEvent* event) { + emit dropEntered(event->mimeData(), static_cast(dropIndicatorPosition())); + m_inDragMoveEvent = true; QTreeView::dropEvent(event); m_inDragMoveEvent = false; diff --git a/src/modlistview.h b/src/modlistview.h index c6d42d2d..af608427 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -8,19 +8,32 @@ class ModListView : public QTreeView { Q_OBJECT + public: - explicit ModListView(QWidget *parent = 0); - void setModel(QAbstractItemModel *model) override; - QModelIndexList selectedIndexes() const; + // this is a public version of DropIndicatorPosition + enum DropPosition { + OnItem = DropIndicatorPosition::OnItem, + AboveItem = DropIndicatorPosition::AboveItem, + BelowItem = DropIndicatorPosition::BelowItem, + OnViewport = DropIndicatorPosition::OnViewport + }; + +public: + explicit ModListView(QWidget* parent = 0); + void setModel(QAbstractItemModel* model) override; signals: void dragEntered(const QMimeData* mimeData); + void dropEntered(const QMimeData* mimeData, DropPosition position); protected: - bool m_inDragMoveEvent = false; + // re-implemented to fake the return value to allow drag-and-drop on + // itself for separators + // + QModelIndexList selectedIndexes() const; void dragEnterEvent(QDragEnterEvent* event) override; void dragMoveEvent(QDragMoveEvent* event) override; @@ -28,7 +41,8 @@ protected: private: - ViewMarkingScrollBar *m_Scrollbar; + ViewMarkingScrollBar* m_scrollbar; + bool m_inDragMoveEvent = false; }; -- cgit v1.3.1 From f923de39e071b48bc1437fa4c79c22b3bc9b0583 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Tue, 29 Dec 2020 13:27:29 +0100 Subject: Maintain selection while filtering. --- src/mainwindow.cpp | 14 +++++++++----- src/modlistbypriorityproxy.cpp | 7 ++++++- src/modlistbypriorityproxy.h | 9 +++++++-- 3 files changed, 22 insertions(+), 8 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 7c72f132..69e2d989 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -422,10 +422,6 @@ MainWindow::MainWindow(Settings &settings connect(&m_PluginContainer, SIGNAL(diagnosisUpdate()), this, SLOT(scheduleCheckForProblems())); - connect(m_ModListSortProxy, SIGNAL(filterActive(bool)), this, SLOT(modFilterActive(bool))); - connect(m_ModListSortProxy, SIGNAL(layoutChanged()), this, SLOT(updateModCount())); - connect(ui->modFilterEdit, SIGNAL(textChanged(QString)), m_ModListSortProxy, SLOT(updateFilter(QString))); - connect(ui->espFilterEdit, SIGNAL(textChanged(QString)), m_PluginListSortProxy, SLOT(updateFilter(QString))); connect(ui->espFilterEdit, SIGNAL(textChanged(QString)), this, SLOT(espFilterChanged(QString))); @@ -659,6 +655,15 @@ void MainWindow::setupModList() connect(m_OrganizerCore.modList(), &ModList::downloadArchiveDropped, this, [this](int row, int priority) { m_OrganizerCore.installDownload(row, priority); }); + + connect(m_ModListSortProxy, &ModListSortProxy::filterActive, this, &MainWindow::modFilterActive); + connect(ui->modFilterEdit, &QLineEdit::textChanged, m_ModListSortProxy, &ModListSortProxy::updateFilter); + connect(m_ModListSortProxy, &QAbstractItemModel::layoutChanged, this, &MainWindow::updateModCount); + connect(m_ModListSortProxy, &QAbstractItemModel::layoutChanged, this, [&]() { + if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy) { + m_ModListByPriorityProxy->refreshExpandedItems(); + } + }); } void MainWindow::resetActionIcons() @@ -5835,7 +5840,6 @@ void MainWindow::onFiltersCriteria(const std::vector } ui->currentCategoryLabel->setText(label); - ui->modList->reset(); } void MainWindow::onFiltersOptions( diff --git a/src/modlistbypriorityproxy.cpp b/src/modlistbypriorityproxy.cpp index 756d3bcf..86664213 100644 --- a/src/modlistbypriorityproxy.cpp +++ b/src/modlistbypriorityproxy.cpp @@ -82,7 +82,7 @@ void ModListByPriorityProxy::buildTree() expandItems(QModelIndex()); } -void ModListByPriorityProxy::expandItems(const QModelIndex& index) +void ModListByPriorityProxy::expandItems(const QModelIndex& index) const { for (int row = 0; row < rowCount(index); row++) { QModelIndex idx = this->index(row, 0, index); @@ -298,6 +298,11 @@ void ModListByPriorityProxy::onDropEnter(const QMimeData*, ModListView::DropPosi m_DropPosition = dropPosition; } +void ModListByPriorityProxy::refreshExpandedItems() const +{ + expandItems(QModelIndex()); +} + void ModListByPriorityProxy::expanded(const QModelIndex& index) { auto it = m_CollapsedItems.find(index.data(Qt::DisplayRole).toString()); diff --git a/src/modlistbypriorityproxy.h b/src/modlistbypriorityproxy.h index cb50352f..26f60bc7 100644 --- a/src/modlistbypriorityproxy.h +++ b/src/modlistbypriorityproxy.h @@ -44,8 +44,13 @@ public: QModelIndex mapFromSource(const QModelIndex& sourceIndex) const override; QModelIndex mapToSource(const QModelIndex& proxyIndex) const override; + // check the internal state for expanded/collapse items and emit a expandItem + // signal for each of the expanded item, useful to refresh the tree state after + // layout modification + void refreshExpandedItems() const; + signals: - void expandItem(const QModelIndex& index); + void expandItem(const QModelIndex& index) const; public slots: @@ -56,7 +61,7 @@ public slots: private: void buildTree(); - void expandItems(const QModelIndex& index); + void expandItems(const QModelIndex& index) const; struct TreeItem { ModInfo::Ptr mod; -- cgit v1.3.1 From 7c073f74c2700ba5555a501ffaa6e24e1dc81f7c Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Tue, 29 Dec 2020 13:50:59 +0100 Subject: Toggle expanded state on double-click. --- src/mainwindow.cpp | 36 +++++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 13 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 69e2d989..3ab61f98 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2447,6 +2447,16 @@ void MainWindow::esplist_changed() void MainWindow::onModPrioritiesChanged(std::vector const& indices) { + // expand separator whose priority has changed + if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy) { + for (auto index : indices) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(index); + if (modInfo->isSeparator()) { + ui->modList->expand(m_ModListSortProxy->mapFromSource(m_ModListByPriorityProxy->mapFromSource(m_OrganizerCore.modList()->index(index, 0)))); + } + } + } + for (unsigned int i = 0; i < m_OrganizerCore.currentProfile()->numMods(); ++i) { int priority = m_OrganizerCore.currentProfile()->getModPriority(i); if (m_OrganizerCore.currentProfile()->modEnabled(i)) { @@ -3800,17 +3810,18 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) return; } - QModelIndex sourceIdx = mapToModel(m_OrganizerCore.modList(), index); - if (!sourceIdx.isValid()) { + bool indexOk = false; + int modIndex = index.data(ModList::IndexRole).toInt(&indexOk); + + if (!indexOk || modIndex < 0 || modIndex >= ModInfo::getNumMods()) { return; } + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + Qt::KeyboardModifiers modifiers = QApplication::queryKeyboardModifiers(); if (modifiers.testFlag(Qt::ControlModifier)) { try { - m_ContextRow = m_ModListSortProxy->mapToSource(index).row(); - - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); shell::Explore(modInfo->absolutePath()); // workaround to cancel the editor that might have opened because of @@ -3823,8 +3834,7 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) } else if (modifiers.testFlag(Qt::ShiftModifier)) { try { - m_ContextRow = m_ModListSortProxy->mapToSource(index).row(); - QModelIndex idx = m_OrganizerCore.modList()->index(m_ContextRow, 0); + QModelIndex idx = m_OrganizerCore.modList()->index(modIndex, 0); visitNexusOrWebPage(idx); ui->modList->closePersistentEditor(index); } @@ -3832,14 +3842,14 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) reportError(e.what()); } } - else{ + else if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy && modInfo->isSeparator()) { + ui->modList->setExpanded(index, !ui->modList->isExpanded(index)); + } + else { try { - m_ContextRow = m_ModListSortProxy->mapToSource(index).row(); - sourceIdx.column(); - auto tab = ModInfoTabIDs::None; - switch (sourceIdx.column()) { + switch (index.column()) { case ModList::COL_NOTES: tab = ModInfoTabIDs::Notes; break; case ModList::COL_VERSION: tab = ModInfoTabIDs::Nexus; break; case ModList::COL_MODID: tab = ModInfoTabIDs::Nexus; break; @@ -3848,7 +3858,7 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) case ModList::COL_CONFLICTFLAGS: tab = ModInfoTabIDs::Conflicts; break; } - displayModInformation(sourceIdx.row(), tab); + displayModInformation(modIndex, tab); // workaround to cancel the editor that might have opened because of // selection-click ui->modList->closePersistentEditor(index); -- cgit v1.3.1 From de87a105b0cbcc73440a2613af6446d0e8819fb6 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Tue, 29 Dec 2020 14:24:33 +0100 Subject: Fix indentation and drop indicator. --- src/mainwindow.cpp | 11 ++++++++--- src/modlistview.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++ src/modlistview.h | 3 +++ 3 files changed, 58 insertions(+), 3 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 3ab61f98..3fdaa6d8 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -558,6 +558,8 @@ void MainWindow::updateModListByPriorityProxy() void MainWindow::setupModList() { + ui->modList->setIndentation(0); + m_ModListByPriorityProxy = new ModListByPriorityProxy(m_OrganizerCore.currentProfile(), &m_OrganizerCore); connect(ui->modList, SIGNAL(expanded(QModelIndex)), m_ModListByPriorityProxy, SLOT(expanded(QModelIndex))); connect(ui->modList, SIGNAL(collapsed(QModelIndex)), m_ModListByPriorityProxy, SLOT(collapsed(QModelIndex))); @@ -2521,15 +2523,18 @@ void MainWindow::modInstalled(const QString &modName) ui->modList->expand(m_ModListSortProxy->mapFromSource(qIndex)); } - ui->modList->setCurrentIndex(m_ModListSortProxy->mapFromSource(qIndex)); - ui->modList->scrollTo(m_ModListSortProxy->mapFromSource(qIndex)); - ui->modList->setFocus(Qt::OtherFocusReason); + qIndex = m_ModListSortProxy->mapFromSource(qIndex); // force an update to happen std::multimap IDs; ModInfo::Ptr info = ModInfo::getByIndex(index); IDs.insert(std::make_pair(info->gameName(), info->nexusId())); modUpdateCheck(IDs); + + ui->modList->setFocus(Qt::OtherFocusReason); + ui->modList->scrollTo(qIndex); + // ui->modList->setCurrentIndex(qIndex); + ui->modList->selectionModel()->select(qIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows); } void MainWindow::showMessage(const QString &message) diff --git a/src/modlistview.cpp b/src/modlistview.cpp index bfc8e385..593d3772 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -2,6 +2,49 @@ #include #include #include +#include + +class ModListProxyStyle : public QProxyStyle { +public: + + using QProxyStyle::QProxyStyle; + + void drawPrimitive(PrimitiveElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const + { + if (element == QStyle::PE_IndicatorItemViewItemDrop) + { + QStyleOption opt(*option); + opt.rect.setLeft(20); + if (auto* view = qobject_cast(widget)) { + opt.rect.setRight(widget->width()); + } + QProxyStyle::drawPrimitive(element, &opt, painter, widget); + } + else { + QProxyStyle::drawPrimitive(element, option, painter, widget); + } + } +}; + +class ModListStyledItemDelegated : public QStyledItemDelegate +{ +public: + using QStyledItemDelegate::QStyledItemDelegate; + void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override { + QStyleOptionViewItem opt(option); + if (index.column() == 0) + opt.rect.adjust(opt.rect.height(), 0, 0, 0); + QStyledItemDelegate::paint(painter, opt, index); + if (index.column() == 0) { + QStyleOptionViewItem branch; + branch.rect = QRect(0, opt.rect.y(), opt.rect.height(), opt.rect.height()); + branch.state = option.state; + const QWidget* widget = option.widget; + QStyle* style = widget ? widget->style() : QApplication::style(); + style->drawPrimitive(QStyle::PE_IndicatorBranch, &branch, painter, widget); + } + } +}; ModListView::ModListView(QWidget* parent) : QTreeView(parent) @@ -10,6 +53,10 @@ ModListView::ModListView(QWidget* parent) setVerticalScrollBar(m_scrollbar); MOBase::setCustomizableColumns(this); setAutoExpandDelay(1000); + + setIndentation(0); + setStyle(new ModListProxyStyle(style())); + setItemDelegate(new ModListStyledItemDelegated(this)); } void ModListView::setModel(QAbstractItemModel* model) diff --git a/src/modlistview.h b/src/modlistview.h index 0ded8f1d..438ed8a4 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -5,6 +5,9 @@ #include #include "viewmarkingscrollbar.h" +namespace Ui { class MainWindow; } +class OrganizerCore; + class ModListView : public QTreeView { Q_OBJECT -- cgit v1.3.1 From a67fca47600d9e3e6e43a93511182396c2f292d9 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Tue, 29 Dec 2020 15:43:15 +0100 Subject: Tentative fix for the indentation. --- src/mainwindow.cpp | 2 -- src/modlistview.cpp | 46 ++++++++++++++++++++++++++++++++++------------ 2 files changed, 34 insertions(+), 14 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 3fdaa6d8..39ecfa95 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -558,8 +558,6 @@ void MainWindow::updateModListByPriorityProxy() void MainWindow::setupModList() { - ui->modList->setIndentation(0); - m_ModListByPriorityProxy = new ModListByPriorityProxy(m_OrganizerCore.currentProfile(), &m_OrganizerCore); connect(ui->modList, SIGNAL(expanded(QModelIndex)), m_ModListByPriorityProxy, SLOT(expanded(QModelIndex))); connect(ui->modList, SIGNAL(collapsed(QModelIndex)), m_ModListByPriorityProxy, SLOT(collapsed(QModelIndex))); diff --git a/src/modlistview.cpp b/src/modlistview.cpp index 593d3772..be7471aa 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -4,18 +4,22 @@ #include #include +#include "modlist.h" +#include "log.h" + class ModListProxyStyle : public QProxyStyle { public: using QProxyStyle::QProxyStyle; - void drawPrimitive(PrimitiveElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const + void drawPrimitive(PrimitiveElement element, const QStyleOption* option, QPainter* painter, const QWidget* widget) const override { if (element == QStyle::PE_IndicatorItemViewItemDrop) { QStyleOption opt(*option); - opt.rect.setLeft(20); + opt.rect.setLeft(0); if (auto* view = qobject_cast(widget)) { + opt.rect.setLeft(view->indentation()); opt.rect.setRight(widget->width()); } QProxyStyle::drawPrimitive(element, &opt, painter, widget); @@ -24,25 +28,43 @@ public: QProxyStyle::drawPrimitive(element, option, painter, widget); } } + + QRect subElementRect(QStyle::SubElement element, const QStyleOption* option, const QWidget* widget) const override + { + QRect rect = QProxyStyle::subElementRect(element, option, widget); + switch (element) { + case SE_ItemViewItemCheckIndicator: + case SE_ItemViewItemDecoration: + case SE_ItemViewItemText: + case SE_ItemViewItemFocusRect: + rect.adjust(-20, 0, 0, 0); + break; + } + return rect; + } }; class ModListStyledItemDelegated : public QStyledItemDelegate { + QTreeView* m_view; + public: + + ModListStyledItemDelegated(QTreeView* view) : + QStyledItemDelegate(view), m_view(view) { } + using QStyledItemDelegate::QStyledItemDelegate; void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override { QStyleOptionViewItem opt(option); - if (index.column() == 0) - opt.rect.adjust(opt.rect.height(), 0, 0, 0); - QStyledItemDelegate::paint(painter, opt, index); if (index.column() == 0) { - QStyleOptionViewItem branch; - branch.rect = QRect(0, opt.rect.y(), opt.rect.height(), opt.rect.height()); - branch.state = option.state; - const QWidget* widget = option.widget; - QStyle* style = widget ? widget->style() : QApplication::style(); - style->drawPrimitive(QStyle::PE_IndicatorBranch, &branch, painter, widget); + if (!index.model()->hasChildren(index) && index.parent().isValid()) { + auto parentIndex = index.parent().data(ModList::IndexRole).toInt(); + if (ModInfo::getByIndex(parentIndex)->isSeparator()) { + opt.rect.adjust(-m_view->indentation(), 0, 0, 0); + } + } } + QStyledItemDelegate::paint(painter, opt, index); } }; @@ -54,11 +76,11 @@ ModListView::ModListView(QWidget* parent) MOBase::setCustomizableColumns(this); setAutoExpandDelay(1000); - setIndentation(0); setStyle(new ModListProxyStyle(style())); setItemDelegate(new ModListStyledItemDelegated(this)); } + void ModListView::setModel(QAbstractItemModel* model) { QTreeView::setModel(model); -- cgit v1.3.1 From 7e2c52133960b7d1bbb0fe72a37cee1c2b67c0ec Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Tue, 29 Dec 2020 19:36:17 +0100 Subject: Refactoring and fixes. - Move codes from MainWindow to ModListView. - Fix enable/disable all visible. - Fix changing style of the mod list. --- src/mainwindow.cpp | 465 ++++-------------------------------------- src/mainwindow.h | 14 -- src/modlistsortproxy.cpp | 26 --- src/modlistsortproxy.h | 11 - src/modlistview.cpp | 519 ++++++++++++++++++++++++++++++++++++++++++++++- src/modlistview.h | 119 +++++++++++ 6 files changed, 679 insertions(+), 475 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 39ecfa95..99c5293d 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -47,6 +47,7 @@ along with Mod Organizer. If not, see . #include "editexecutablesdialog.h" #include "categories.h" #include "categoriesdialog.h" +#include "genericicondelegate.h" #include "modinfodialog.h" #include "overwriteinfodialog.h" #include "downloadlist.h" @@ -56,9 +57,6 @@ along with Mod Organizer. If not, see . #include "motddialog.h" #include "filedialogmemory.h" #include "tutorialmanager.h" -#include "modflagicondelegate.h" -#include "modconflicticondelegate.h" -#include "genericicondelegate.h" #include "selectiondialog.h" #include "csvbuilder.h" #include "savetextasdialog.h" @@ -255,7 +253,6 @@ MainWindow::MainWindow(Settings &settings , m_linksSeparator(nullptr) , m_Tutorial(this, "MainWindow") , m_OldProfileIndex(-1) - , m_ModListSortProxy(nullptr) , m_OldExecutableIndex(-1) , m_CategoryFactory(CategoryFactory::instance()) , m_ContextItem(nullptr) @@ -484,6 +481,7 @@ MainWindow::MainWindow(Settings &settings new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Enter), this, SLOT(openExplorer_activated())); new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return), this, SLOT(openExplorer_activated())); + new QShortcut(QKeySequence::Refresh, this, SLOT(refreshProfile_activated())); setFilterShortcuts(ui->modList, ui->modFilterEdit); setFilterShortcuts(ui->espList, ui->espFilterEdit); @@ -536,134 +534,19 @@ MainWindow::MainWindow(Settings &settings updatePinnedExecutables(); resetActionIcons(); updatePluginCount(); - updateModCount(); processUpdates(); + ui->modList->updateModCount(); ui->statusBar->updateNormalMessage(m_OrganizerCore); } -void MainWindow::updateModListByPriorityProxy() -{ - if (ui->groupCombo->currentIndex() != 0) { - return; - } - if (m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY && m_ModListSortProxy->sortOrder() == Qt::AscendingOrder) { - m_ModListSortProxy->setSourceModel(m_ModListByPriorityProxy); - m_ModListByPriorityProxy->refresh(); - } - else { - m_ModListSortProxy->setSourceModel(m_OrganizerCore.modList()); - } -} - void MainWindow::setupModList() { - m_ModListByPriorityProxy = new ModListByPriorityProxy(m_OrganizerCore.currentProfile(), &m_OrganizerCore); - connect(ui->modList, SIGNAL(expanded(QModelIndex)), m_ModListByPriorityProxy, SLOT(expanded(QModelIndex))); - connect(ui->modList, SIGNAL(collapsed(QModelIndex)), m_ModListByPriorityProxy, SLOT(collapsed(QModelIndex))); - connect(m_ModListByPriorityProxy, SIGNAL(expandItem(QModelIndex)), this, SLOT(expandModList(QModelIndex))); - - m_ModListSortProxy = new ModListSortProxy(m_OrganizerCore.currentProfile(), &m_OrganizerCore); - ui->modList->setModel(m_ModListSortProxy); - - m_ModListByPriorityProxy->setSourceModel(m_OrganizerCore.modList()); - - connect(m_ModListSortProxy, &QAbstractItemModel::layoutAboutToBeChanged, - this, [this](const QList& parents, QAbstractItemModel::LayoutChangeHint hint) { - if (hint == QAbstractItemModel::VerticalSortHint) { - updateModListByPriorityProxy(); - } - }); - - ui->modList->sortByColumn(ModList::COL_PRIORITY, Qt::AscendingOrder); - - connect(ui->modList, &ModListView::dragEntered, m_OrganizerCore.modList(), &ModList::onDragEnter); - connect(ui->modList, &ModListView::dropEntered, m_ModListByPriorityProxy, &ModListByPriorityProxy::onDropEnter); - connect(m_OrganizerCore.modList(), &ModList::modPrioritiesChanged, this, &MainWindow::onModPrioritiesChanged); - - connect( - ui->modList->header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), - this, SLOT(modListSortIndicatorChanged(int,Qt::SortOrder))); - - connect( - ui->modList->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), - this, SLOT(modlistSelectionsChanged(QItemSelection))); - - connect( - ui->modList->header(), SIGNAL(sectionResized(int, int, int)), - this, SLOT(modListSectionResized(int, int, int))); - - - GenericIconDelegate *contentDelegate = new GenericIconDelegate( - ui->modList, Qt::UserRole + 3, ModList::COL_CONTENT, 150); - - connect( - ui->modList->header(), SIGNAL(sectionResized(int,int,int)), - contentDelegate, SLOT(columnResized(int,int,int))); - - - ModFlagIconDelegate *flagDelegate = new ModFlagIconDelegate( - ui->modList, ModList::COL_FLAGS, 120); - - connect( - ui->modList->header(), SIGNAL(sectionResized(int,int,int)), - flagDelegate, SLOT(columnResized(int,int,int))); - - - ModConflictIconDelegate* conflictFlagDelegate = new ModConflictIconDelegate( - ui->modList, ModList::COL_CONFLICTFLAGS, 80); - - connect( - ui->modList->header(), SIGNAL(sectionResized(int, int, int)), - conflictFlagDelegate, SLOT(columnResized(int, int, int))); - - - ui->modList->setItemDelegateForColumn(ModList::COL_FLAGS, flagDelegate); - ui->modList->setItemDelegateForColumn(ModList::COL_CONFLICTFLAGS, conflictFlagDelegate); - ui->modList->setItemDelegateForColumn(ModList::COL_CONTENT, contentDelegate); - ui->modList->header()->installEventFilter(m_OrganizerCore.modList()); - - - if (m_OrganizerCore.settings().geometry().restoreState(ui->modList->header())) { - // hack: force the resize-signal to be triggered because restoreState doesn't seem to do that - for (int column = 0; column <= ModList::COL_LASTCOLUMN; ++column) { - int sectionSize = ui->modList->header()->sectionSize(column); - ui->modList->header()->resizeSection(column, sectionSize + 1); - ui->modList->header()->resizeSection(column, sectionSize); - } - } else { - // hide these columns by default - ui->modList->header()->setSectionHidden(ModList::COL_CONTENT, true); - ui->modList->header()->setSectionHidden(ModList::COL_MODID, true); - ui->modList->header()->setSectionHidden(ModList::COL_GAME, true); - ui->modList->header()->setSectionHidden(ModList::COL_INSTALLTIME, true); - ui->modList->header()->setSectionHidden(ModList::COL_NOTES, true); - - // resize mod list to fit content - for (int i = 0; i < ui->modList->header()->count(); ++i) { - ui->modList->header()->setSectionResizeMode(i, QHeaderView::ResizeToContents); - } - - ui->modList->header()->setSectionResizeMode(ModList::COL_NAME, QHeaderView::Stretch); - } - - // prevent the name-column from being hidden - ui->modList->header()->setSectionHidden(ModList::COL_NAME, false); - - ui->modList->installEventFilter(m_OrganizerCore.modList()); - - connect(m_OrganizerCore.modList(), &ModList::downloadArchiveDropped, this, [this](int row, int priority) { - m_OrganizerCore.installDownload(row, priority); - }); + ui->modList->setup(m_OrganizerCore, ui); - connect(m_ModListSortProxy, &ModListSortProxy::filterActive, this, &MainWindow::modFilterActive); - connect(ui->modFilterEdit, &QLineEdit::textChanged, m_ModListSortProxy, &ModListSortProxy::updateFilter); - connect(m_ModListSortProxy, &QAbstractItemModel::layoutChanged, this, &MainWindow::updateModCount); - connect(m_ModListSortProxy, &QAbstractItemModel::layoutChanged, this, [&]() { - if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy) { - m_ModListByPriorityProxy->refreshExpandedItems(); - } - }); + // keep here for now + connect(ui->modList->selectionModel(), &QItemSelectionModel::selectionChanged, + this, &MainWindow::modlistSelectionsChanged); } void MainWindow::resetActionIcons() @@ -733,7 +616,6 @@ void MainWindow::resetActionIcons() updateProblemsButton(); } - MainWindow::~MainWindow() { try { @@ -814,6 +696,7 @@ void MainWindow::allowListResize() void MainWindow::updateStyle(const QString&) { resetActionIcons(); + ui->modList->refreshStyle(); } void MainWindow::resizeEvent(QResizeEvent *event) @@ -1273,22 +1156,6 @@ void MainWindow::createHelpMenu() menu->addAction(tr("About Qt"), qApp, SLOT(aboutQt())); } -void MainWindow::modFilterActive(bool filterActive) -{ - ui->clearFiltersButton->setVisible(filterActive); - if (filterActive) { -// m_OrganizerCore.modList()->setOverwriteMarkers(std::set(), std::set()); - ui->modList->setStyleSheet("QTreeView { border: 2px ridge #f00; }"); - ui->activeModsCounter->setStyleSheet("QLCDNumber { border: 2px ridge #f00; }"); - } else if (ui->groupCombo->currentIndex() != 0) { - ui->modList->setStyleSheet("QTreeView { border: 2px ridge #337733; }"); - ui->activeModsCounter->setStyleSheet(""); - } else { - ui->modList->setStyleSheet(""); - ui->activeModsCounter->setStyleSheet(""); - } -} - void MainWindow::espFilterChanged(const QString &filter) { if (!filter.isEmpty()) { @@ -1301,13 +1168,6 @@ void MainWindow::espFilterChanged(const QString &filter) updatePluginCount(); } -void MainWindow::expandModList(const QModelIndex &index) -{ - if (index.model() == m_ModListSortProxy->sourceModel()) { - ui->modList->expand(m_ModListSortProxy->mapFromSource(index)); - } -} - bool MainWindow::addProfile() { QComboBox *profileBox = findChild("profileBox"); @@ -1706,13 +1566,11 @@ void MainWindow::startExeAction() void MainWindow::activateSelectedProfile() { m_OrganizerCore.setCurrentProfile(ui->profileBox->currentText()); - - m_ModListSortProxy->setProfile(m_OrganizerCore.currentProfile()); - m_ModListByPriorityProxy->setProfile(m_OrganizerCore.currentProfile()); + ui->modList->setProfile(m_OrganizerCore.currentProfile()); m_SavesTab->refreshSaveList(); m_OrganizerCore.refresh(); - updateModCount(); + ui->modList->updateModCount(); updatePluginCount(); ui->statusBar->updateNormalMessage(m_OrganizerCore); } @@ -1746,22 +1604,9 @@ void MainWindow::on_profileBox_currentIndexChanged(int index) if (ui->profileBox->currentIndex() == 0) { ui->profileBox->setCurrentIndex(previousIndex); - - std::optional newSelection; - - ProfilesDialog dlg(ui->profileBox->currentText(), m_OrganizerCore, this); - dlg.exec(); - newSelection = dlg.selectedProfile(); - + ProfilesDialog(ui->profileBox->currentText(), m_OrganizerCore, this).exec(); while (!refreshProfiles()) { - ProfilesDialog dlg(ui->profileBox->currentText(), m_OrganizerCore, this); - dlg.exec(); - newSelection = dlg.selectedProfile(); - } - - if (newSelection) { - ui->profileBox->setCurrentText(*newSelection); - activateSelectedProfile(); + ProfilesDialog(ui->profileBox->currentText(), m_OrganizerCore, this).exec(); } } else { activateSelectedProfile(); @@ -2339,11 +2184,6 @@ void MainWindow::on_actionInstallMod_triggered() installMod(); } -void MainWindow::on_action_Refresh_triggered() -{ - refreshProfile_activated(); -} - void MainWindow::on_actionAdd_Profile_triggered() { for (;;) { @@ -2447,16 +2287,6 @@ void MainWindow::esplist_changed() void MainWindow::onModPrioritiesChanged(std::vector const& indices) { - // expand separator whose priority has changed - if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy) { - for (auto index : indices) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(index); - if (modInfo->isSeparator()) { - ui->modList->expand(m_ModListSortProxy->mapFromSource(m_ModListByPriorityProxy->mapFromSource(m_OrganizerCore.modList()->index(index, 0)))); - } - } - } - for (unsigned int i = 0; i < m_OrganizerCore.currentProfile()->numMods(); ++i) { int priority = m_OrganizerCore.currentProfile()->getModPriority(i); if (m_OrganizerCore.currentProfile()->modEnabled(i)) { @@ -2498,9 +2328,6 @@ void MainWindow::onModPrioritiesChanged(std::vector const& indices) m_OrganizerCore.modList()->setOverwriteMarkers(modInfo->getModOverwrite(), modInfo->getModOverwritten()); m_OrganizerCore.modList()->setArchiveOverwriteMarkers(modInfo->getModArchiveOverwrite(), modInfo->getModArchiveOverwritten()); m_OrganizerCore.modList()->setArchiveLooseOverwriteMarkers(modInfo->getModArchiveLooseOverwrite(), modInfo->getModArchiveLooseOverwritten()); - if (m_ModListSortProxy != nullptr) { - m_ModListSortProxy->invalidate(); - } ui->modList->verticalScrollBar()->repaint(); } } @@ -2514,25 +2341,11 @@ void MainWindow::modInstalled(const QString &modName) return; } - QModelIndex qIndex = m_OrganizerCore.modList()->index(index, 0); - - if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy) { - qIndex = m_ModListByPriorityProxy->mapFromSource(qIndex); - ui->modList->expand(m_ModListSortProxy->mapFromSource(qIndex)); - } - - qIndex = m_ModListSortProxy->mapFromSource(qIndex); - // force an update to happen std::multimap IDs; ModInfo::Ptr info = ModInfo::getByIndex(index); IDs.insert(std::make_pair(info->gameName(), info->nexusId())); modUpdateCheck(IDs); - - ui->modList->setFocus(Qt::OtherFocusReason); - ui->modList->scrollTo(qIndex); - // ui->modList->setCurrentIndex(qIndex); - ui->modList->selectionModel()->select(qIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows); } void MainWindow::showMessage(const QString &message) @@ -2626,9 +2439,7 @@ void MainWindow::restoreBackup_clicked() if (!modDir.rename(modInfo->absolutePath(), destinationPath)) { reportError(tr("failed to rename \"%1\" to \"%2\"").arg(modInfo->absolutePath()).arg(destinationPath)); } - m_OrganizerCore.refresh(); - updateModCount(); } } } @@ -2637,13 +2448,13 @@ void MainWindow::restoreBackup_clicked() void MainWindow::modlistChanged(const QModelIndex&, int) { m_OrganizerCore.currentProfile()->writeModlist(); - updateModCount(); + ui->modList->updateModCount(); } void MainWindow::modlistChanged(const QModelIndexList&, int) { m_OrganizerCore.currentProfile()->writeModlist(); - updateModCount(); + ui->modList->updateModCount(); } void MainWindow::modlistSelectionsChanged(const QItemSelection &selected) @@ -2672,17 +2483,6 @@ void MainWindow::esplistSelectionsChanged(const QItemSelection &selected) ui->modList->verticalScrollBar()->repaint(); } -void MainWindow::modListSortIndicatorChanged(int, Qt::SortOrder) -{ - ui->modList->verticalScrollBar()->repaint(); -} - -void MainWindow::modListSectionResized(int logicalIndex, int oldSize, int newSize) -{ - bool enabled = (newSize != 0); - qobject_cast(ui->modList->model())->setColumnVisible(logicalIndex, enabled); -} - void MainWindow::removeMod_clicked() { const int max_items = 20; @@ -2727,7 +2527,7 @@ void MainWindow::removeMod_clicked() } else { m_OrganizerCore.modList()->removeRow(m_ContextRow, QModelIndex()); } - updateModCount(); + ui->modList->updateModCount(); updatePluginCount(); } catch (const std::exception &e) { reportError(tr("failed to remove mod: %1").arg(e.what())); @@ -2778,9 +2578,7 @@ void MainWindow::backupMod_clicked() QMessageBox::information(this, tr("Failed"), tr("Failed to create backup.")); } - m_OrganizerCore.refresh(); - updateModCount(); } @@ -2964,72 +2762,22 @@ void MainWindow::setWindowEnabled(bool enabled) setEnabled(enabled); } - ModInfo::Ptr MainWindow::nextModInList() { - const QModelIndex start = m_ModListSortProxy->mapFromSource( - m_OrganizerCore.modList()->index(m_ContextRow, 0)); - - auto index = start; - - for (;;) { - index = m_ModListSortProxy->index((index.row() + 1) % m_ModListSortProxy->rowCount(), 0); - m_ContextRow = m_ModListSortProxy->mapToSource(index).row(); - - if (index == start || !index.isValid()) { - // wrapped around, give up - break; - } - - ModInfo::Ptr mod = ModInfo::getByIndex(m_ContextRow); - - // skip overwrite and backups and separators - if (mod->hasFlag(ModInfo::FLAG_OVERWRITE) || - mod->hasFlag(ModInfo::FLAG_BACKUP) || - mod->hasFlag(ModInfo::FLAG_SEPARATOR)) { - continue; - } - - return mod; + int index = ui->modList->nextMod(m_ContextRow); + if (index == -1) { + return {}; } - - return {}; + return ModInfo::getByIndex(index); } ModInfo::Ptr MainWindow::previousModInList() { - const QModelIndex start = m_ModListSortProxy->mapFromSource( - m_OrganizerCore.modList()->index(m_ContextRow, 0)); - - auto index = start; - - for (;;) { - int row = index.row() - 1; - if (row == -1) { - row = m_ModListSortProxy->rowCount() - 1; - } - - index = m_ModListSortProxy->index(row, 0); - m_ContextRow = m_ModListSortProxy->mapToSource(index).row(); - - if (index == start || !index.isValid()) { - // wrapped around, give up - break; - } - - // skip overwrite and backups and separators - ModInfo::Ptr mod = ModInfo::getByIndex(m_ContextRow); - - if (mod->hasFlag(ModInfo::FLAG_OVERWRITE) || - mod->hasFlag(ModInfo::FLAG_BACKUP) || - mod->hasFlag(ModInfo::FLAG_SEPARATOR)) { - continue; - } - - return mod; + int index = ui->modList->prevMod(m_ContextRow); + if (index == -1) { + return {}; } - - return {}; + return ModInfo::getByIndex(index); } void MainWindow::displayModInformation(const QString &modName, ModInfoTabIDs tabID) @@ -3396,89 +3144,6 @@ void MainWindow::refreshProfile_activated() m_OrganizerCore.profileRefresh(); } -void MainWindow::updateModCount() -{ - TimeThis tt("updateModCount"); - - int activeCount = 0; - int visActiveCount = 0; - int backupCount = 0; - int visBackupCount = 0; - int foreignCount = 0; - int visForeignCount = 0; - int separatorCount = 0; - int visSeparatorCount = 0; - int regularCount = 0; - int visRegularCount = 0; - - QStringList allMods = m_OrganizerCore.modList()->allMods(); - - auto hasFlag = [](std::vector flags, ModInfo::EFlag filter) { - return std::find(flags.begin(), flags.end(), filter) != flags.end(); - }; - - bool isEnabled; - bool isVisible; - for (QString mod : allMods) { - int modIndex = ModInfo::getIndex(mod); - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - std::vector modFlags = modInfo->getFlags(); - isEnabled = m_OrganizerCore.currentProfile()->modEnabled(modIndex); - isVisible = m_ModListSortProxy->filterMatchesMod(modInfo, isEnabled); - - for (auto flag : modFlags) { - switch (flag) { - case ModInfo::FLAG_BACKUP: backupCount++; - if (isVisible) - visBackupCount++; - break; - case ModInfo::FLAG_FOREIGN: foreignCount++; - if (isVisible) - visForeignCount++; - break; - case ModInfo::FLAG_SEPARATOR: separatorCount++; - if (isVisible) - visSeparatorCount++; - break; - } - } - - if (!hasFlag(modFlags, ModInfo::FLAG_BACKUP) && - !hasFlag(modFlags, ModInfo::FLAG_FOREIGN) && - !hasFlag(modFlags, ModInfo::FLAG_SEPARATOR) && - !hasFlag(modFlags, ModInfo::FLAG_OVERWRITE)) { - if (isEnabled) { - activeCount++; - if (isVisible) - visActiveCount++; - } - if (isVisible) - visRegularCount++; - regularCount++; - } - } - - ui->activeModsCounter->display(visActiveCount); - ui->activeModsCounter->setToolTip(tr("" - "" - "" - "" - "" - "" - "
    TypeAllVisible
    Enabled mods: %1 / %2%3 / %4
    Unmanaged/DLCs: %5%6
    Mod backups: %7%8
    Separators: %9%10
    ") - .arg(activeCount) - .arg(regularCount) - .arg(visActiveCount) - .arg(visRegularCount) - .arg(foreignCount) - .arg(visForeignCount) - .arg(backupCount) - .arg(visBackupCount) - .arg(separatorCount) - .arg(visSeparatorCount) - ); -} - void MainWindow::updatePluginCount() { int activeMasterCount = 0; @@ -3561,7 +3226,7 @@ void MainWindow::createEmptyMod_clicked() } int newPriority = -1; - if (m_ContextRow >= 0 && m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY) { + if (m_ContextRow >= 0 && ui->modList->sortColumn() == ModList::COL_PRIORITY) { newPriority = m_OrganizerCore.currentProfile()->getModPriority(m_ContextRow); } @@ -3602,7 +3267,7 @@ void MainWindow::createSeparator_clicked() } int newPriority = -1; - if (m_ContextRow >= 0 && m_ModListSortProxy->sortColumn() == ModList::COL_PRIORITY) + if (m_ContextRow >= 0 && ui->modList->sortColumn() == ModList::COL_PRIORITY) { newPriority = m_OrganizerCore.currentProfile()->getModPriority(m_ContextRow); } @@ -3845,7 +3510,7 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) reportError(e.what()); } } - else if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy && modInfo->isSeparator()) { + else if (ui->modList->hasCollapsibleSeparators() && modInfo->isSeparator()) { ui->modList->setExpanded(index, !ui->modList->isExpanded(index)); } else { @@ -4176,7 +3841,7 @@ void MainWindow::checkModsForUpdates() } if (updatesAvailable || checkingModsForUpdate) { - m_ModListSortProxy->setCriteria({{ + ui->modList->setFilterCriteria({{ ModListSortProxy::TypeSpecial, CategoryFactory::UpdateAvailable, false} @@ -4231,8 +3896,7 @@ void MainWindow::ignoreUpdate() { ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); info->ignoreUpdate(true); } - if (m_ModListSortProxy != nullptr) - m_ModListSortProxy->invalidate(); + ui->modList->invalidate(); } void MainWindow::checkModUpdates_clicked() @@ -4264,8 +3928,7 @@ void MainWindow::unignoreUpdate() ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); info->ignoreUpdate(false); } - if (m_ModListSortProxy != nullptr) - m_ModListSortProxy->invalidate(); + ui->modList->invalidate(); } void MainWindow::addPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, @@ -4311,7 +3974,7 @@ void MainWindow::enableVisibleMods() { if (QMessageBox::question(nullptr, tr("Confirm"), tr("Really enable all visible mods?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - m_ModListSortProxy->enableAllVisible(); + ui->modList->enableAllVisible(); } } @@ -4319,7 +3982,7 @@ void MainWindow::disableVisibleMods() { if (QMessageBox::question(nullptr, tr("Confirm"), tr("Really disable all visible mods?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - m_ModListSortProxy->disableAllVisible(); + ui->modList->disableAllVisible(); } } @@ -4516,7 +4179,7 @@ void MainWindow::exportModListCSV() if ((selectedRowID == 1) && !enabled) { continue; } - else if ((selectedRowID == 2) && !m_ModListSortProxy->filterMatchesMod(info, enabled)) { + else if ((selectedRowID == 2) && !ui->modList->isModVisible(iter.second)) { continue; } std::vector flags = info->getFlags(); @@ -4616,7 +4279,7 @@ void MainWindow::initModListContextMenu(QMenu *menu) void MainWindow::addModSendToContextMenu(QMenu *menu) { - if (m_ModListSortProxy->sortColumn() != ModList::COL_PRIORITY) + if (ui->modList->sortColumn() != ModList::COL_PRIORITY) return; QMenu *sub_menu = new QMenu(menu); @@ -4668,7 +4331,7 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) allMods->setTitle(tr("All Mods")); menu.addMenu(allMods); - if (m_ModListSortProxy->sourceModel() == m_ModListByPriorityProxy) { + if (ui->modList->hasCollapsibleSeparators()) { menu.addAction(tr("Collapse all"), ui->modList, &QTreeView::collapseAll); menu.addAction(tr("Expand all"), ui->modList, &QTreeView::expandAll); } @@ -5147,19 +4810,13 @@ void MainWindow::sendSelectedPluginsToPriority_clicked() void MainWindow::enableSelectedMods_clicked() { - m_OrganizerCore.modList()->enableSelected(ui->modList->selectionModel()); - if (m_ModListSortProxy != nullptr) { - m_ModListSortProxy->invalidate(); - } + ui->modList->enableSelected(); } void MainWindow::disableSelectedMods_clicked() { - m_OrganizerCore.modList()->disableSelected(ui->modList->selectionModel()); - if (m_ModListSortProxy != nullptr) { - m_ModListSortProxy->invalidate(); - } + ui->modList->disableSelected(); } void MainWindow::updateAvailable() @@ -5363,8 +5020,7 @@ void MainWindow::nxmUpdateInfoAvailable(QString gameName, QVariant userData, QVa return std::make_pair(gameNameReal, ModInfo::filteredMods(gameNameReal, resultList, userData.toBool(), true)); }); watcher->setFuture(future); - if (m_ModListSortProxy != nullptr) - m_ModListSortProxy->invalidate(); + ui->modList->invalidate(); } void MainWindow::finishUpdateInfo() @@ -5467,8 +5123,7 @@ void MainWindow::nxmUpdatesAvailable(QString gameName, int modID, QVariant userD if (foundUpdate) { // Just get the standard data updates for endorsements and descriptions mod->setLastNexusUpdate(QDateTime::currentDateTimeUtc()); - if (m_ModListSortProxy != nullptr) - m_ModListSortProxy->invalidate(); + ui->modList->invalidate(); } else { // Scrape mod data here so we can use the mod version if no file update was located requiresInfo = true; @@ -5519,8 +5174,9 @@ void MainWindow::nxmModInfoAvailable(QString gameName, int modID, QVariant userD mod->setNexusLastModified(QDateTime::fromSecsSinceEpoch(result["updated_timestamp"].toInt(), Qt::UTC)); mod->saveMeta(); } - if (foundUpdate && m_ModListSortProxy != nullptr) - m_ModListSortProxy->invalidate(); + if (foundUpdate) { + ui->modList->invalidate(); + } } void MainWindow::nxmEndorsementToggled(QString, int, QVariant, QVariant resultData, int) @@ -5829,7 +5485,7 @@ void MainWindow::refreshFilters() void MainWindow::onFiltersCriteria(const std::vector& criteria) { - m_ModListSortProxy->setCriteria(criteria); + ui->modList->setFilterCriteria(criteria); QString label = "?"; @@ -5858,7 +5514,7 @@ void MainWindow::onFiltersCriteria(const std::vector void MainWindow::onFiltersOptions( ModListSortProxy::FilterMode mode, ModListSortProxy::SeparatorsMode sep) { - m_ModListSortProxy->setOptions(mode, sep); + ui->modList->setFilterOptions(mode, sep); } void MainWindow::updateESPLock(bool locked) @@ -5987,41 +5643,6 @@ void MainWindow::on_espList_customContextMenuRequested(const QPoint &pos) } } -void MainWindow::on_groupCombo_currentIndexChanged(int index) -{ - if (m_ModListSortProxy == nullptr) { - return; - } - QAbstractProxyModel *newModel = nullptr; - switch (index) { - case 1: { - newModel = new QtGroupingProxy(m_OrganizerCore.modList(), QModelIndex(), ModList::COL_CATEGORY, Qt::UserRole, - 0, Qt::UserRole + 2); - } break; - case 2: { - newModel = new QtGroupingProxy(m_OrganizerCore.modList(), QModelIndex(), ModList::COL_MODID, Qt::DisplayRole, - QtGroupingProxy::FLAG_NOGROUPNAME | QtGroupingProxy::FLAG_NOSINGLE, - Qt::UserRole + 2); - } break; - default: { - newModel = nullptr; - } break; - } - - if (newModel != nullptr) { -#ifdef TEST_MODELS - new ModelTest(newModel, this); -#endif // TEST_MODELS - m_ModListSortProxy->setSourceModel(newModel); - connect(ui->modList, SIGNAL(expanded(QModelIndex)),newModel, SLOT(expanded(QModelIndex))); - connect(ui->modList, SIGNAL(collapsed(QModelIndex)), newModel, SLOT(collapsed(QModelIndex))); - connect(newModel, SIGNAL(expandItem(QModelIndex)), this, SLOT(expandModList(QModelIndex))); - } else { - updateModListByPriorityProxy(); - } - modFilterActive(m_ModListSortProxy->isFilterActive()); -} - Executable* MainWindow::getSelectedExecutable() { const QString name = ui->executablesListBox->itemText( diff --git a/src/mainwindow.h b/src/mainwindow.h index 8dd72174..dbd44688 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -297,9 +297,6 @@ private: QStringList m_DefaultArchives; - ModListSortProxy *m_ModListSortProxy; - ModListByPriorityProxy *m_ModListByPriorityProxy; - PluginListSortProxy *m_PluginListSortProxy; int m_OldExecutableIndex; @@ -521,12 +518,7 @@ private slots: void modlistChanged(const QModelIndexList &indicies, int role); void fileMoved(const QString &filePath, const QString &oldOriginName, const QString &newOriginName); - - void modFilterActive(bool active); void espFilterChanged(const QString &filter); - - void expandModList(const QModelIndex &index); - void resizeLists(bool pluginListCustom); /** @@ -545,14 +537,10 @@ private slots: void about(); - void modListSortIndicatorChanged(int column, Qt::SortOrder order); - void modListSectionResized(int logicalIndex, int oldSize, int newSize); - void modlistSelectionsChanged(const QItemSelection ¤t); void esplistSelectionsChanged(const QItemSelection ¤t); void resetActionIcons(); - void updateModCount(); void updatePluginCount(); private slots: // ui slots @@ -591,7 +579,6 @@ private slots: // ui slots void on_espList_customContextMenuRequested(const QPoint &pos); void on_displayCategoriesBtn_toggled(bool checked); - void on_groupCombo_currentIndexChanged(int index); void on_linkButton_pressed(); void on_showHiddenBox_toggled(bool checked); void on_bsaList_itemChanged(QTreeWidgetItem *item, int column); @@ -609,7 +596,6 @@ private slots: // ui slots void readSettings(); void setupModList(); - void updateModListByPriorityProxy(); }; #endif // MAINWINDOW_H diff --git a/src/modlistsortproxy.cpp b/src/modlistsortproxy.cpp index daa1478d..a7d0b27a 100644 --- a/src/modlistsortproxy.cpp +++ b/src/modlistsortproxy.cpp @@ -80,32 +80,6 @@ Qt::ItemFlags ModListSortProxy::flags(const QModelIndex &modelIndex) const return flags; } -void ModListSortProxy::enableAllVisible() -{ - if (m_Profile == nullptr) return; - - QList modsToEnable; - for (int i = 0; i < this->rowCount(); ++i) { - int modID = mapToSource(index(i, 0)).data(Qt::UserRole + 1).toInt(); - modsToEnable.append(modID); - } - m_Profile->setModsEnabled(modsToEnable, QList()); - invalidate(); -} - -void ModListSortProxy::disableAllVisible() -{ - if (m_Profile == nullptr) return; - - QList modsToDisable; - for (int i = 0; i < this->rowCount(); ++i) { - int modID = mapToSource(index(i, 0)).data(Qt::UserRole + 1).toInt(); - modsToDisable.append(modID); - } - m_Profile->setModsEnabled(QList(), modsToDisable); - invalidate(); -} - unsigned long ModListSortProxy::flagsId(const std::vector &flags) const { unsigned long result = 0; diff --git a/src/modlistsortproxy.h b/src/modlistsortproxy.h index 811aec66..9a4140f6 100644 --- a/src/modlistsortproxy.h +++ b/src/modlistsortproxy.h @@ -84,17 +84,6 @@ public: virtual void setSourceModel(QAbstractItemModel *sourceModel) override; - - /** - * @brief enable all mods visible under the current filter - **/ - void enableAllVisible(); - - /** - * @brief disable all mods visible under the current filter - **/ - void disableAllVisible(); - /** * @brief tests if a filtere matches for a mod * @param info mod information diff --git a/src/modlistview.cpp b/src/modlistview.cpp index 9192c01a..bccacb24 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -1,11 +1,20 @@ #include "modlistview.h" -#include #include #include #include +#include + +#include "ui_mainwindow.h" + +#include "organizercore.h" #include "modlist.h" +#include "modlistsortproxy.h" +#include "modlistbypriorityproxy.h" #include "log.h" +#include "modflagicondelegate.h" +#include "modconflicticondelegate.h" +#include "genericicondelegate.h" class ModListProxyStyle : public QProxyStyle { public: @@ -63,10 +72,516 @@ ModListView::ModListView(QWidget* parent) MOBase::setCustomizableColumns(this); setAutoExpandDelay(1000); - setStyle(new ModListProxyStyle(style())); + setStyle(new ModListProxyStyle()); setItemDelegate(new ModListStyledItemDelegated(this)); } +void ModListView::refreshStyle() +{ + // maybe there is a better way but I did not find one + QString sheet = styleSheet(); + setStyleSheet("QTreeView { }"); + setStyleSheet(sheet); +} + +void ModListView::setProfile(Profile* profile) +{ + m_sortProxy->setProfile(profile); + m_byPriorityProxy->setProfile(profile); +} + +bool ModListView::hasCollapsibleSeparators() const +{ + return m_sortProxy != nullptr && m_sortProxy->sourceModel() == m_byPriorityProxy; +} + +int ModListView::sortColumn() const +{ + return m_sortProxy ? m_sortProxy->sortColumn() : -1; +} + +int ModListView::nextMod(int modIndex) const +{ + const QModelIndex start = indexModelToView(m_core->modList()->index(modIndex, 0)); + + auto index = start; + + for (;;) { + index = model()->index((index.row() + 1) % model()->rowCount(), 0); + modIndex = indexViewToModel(index).data(ModList::IndexRole).toInt(); + + if (index == start || !index.isValid()) { + // wrapped around, give up + break; + } + + ModInfo::Ptr mod = ModInfo::getByIndex(modIndex); + + // skip overwrite and backups and separators + if (mod->hasFlag(ModInfo::FLAG_OVERWRITE) || + mod->hasFlag(ModInfo::FLAG_BACKUP) || + mod->hasFlag(ModInfo::FLAG_SEPARATOR)) { + continue; + } + + return modIndex; + } + + return -1; +} + +int ModListView::prevMod(int modIndex) const +{ + const QModelIndex start = indexModelToView(m_core->modList()->index(modIndex, 0)); + + auto index = start; + + for (;;) { + int row = index.row() - 1; + if (row == -1) { + row = model()->rowCount() - 1; + } + + index = model()->index(row, 0); + modIndex = indexViewToModel(index).data(ModList::IndexRole).toInt(); + + if (index == start || !index.isValid()) { + // wrapped around, give up + break; + } + + // skip overwrite and backups and separators + ModInfo::Ptr mod = ModInfo::getByIndex(modIndex); + + if (mod->hasFlag(ModInfo::FLAG_OVERWRITE) || + mod->hasFlag(ModInfo::FLAG_BACKUP) || + mod->hasFlag(ModInfo::FLAG_SEPARATOR)) { + continue; + } + + return modIndex; + } + + return -1; +} + +void ModListView::invalidate() +{ + if (m_sortProxy) { + m_sortProxy->invalidate(); + } +} + +void ModListView::enableAllVisible() +{ + Profile* profile = m_core->currentProfile(); + + QList modsToEnable; + for (auto& index : allIndex(model())) { + modsToEnable.append(index.data(ModList::IndexRole).toInt()); + } + profile->setModsEnabled(modsToEnable, {}); + invalidate(); +} + +void ModListView::disableAllVisible() +{ + MOBase::log::debug("disableAllVisible: {}", model()->rowCount()); + Profile* profile = m_core->currentProfile(); + + QList modsToDisable; + for (auto& index : allIndex(model())) { + modsToDisable.append(index.data(ModList::IndexRole).toInt()); + } + profile->setModsEnabled({}, modsToDisable); + invalidate(); +} + +void ModListView::enableSelected() +{ + Profile* profile = m_core->currentProfile(); + if (selectionModel()->hasSelection()) { + QList modsToEnable; + for (auto row : selectionModel()->selectedRows(ModList::COL_PRIORITY)) { + int modID = profile->modIndexByPriority(row.data().toInt()); + modsToEnable.append(modID); + } + profile->setModsEnabled(modsToEnable, {}); + } + invalidate(); +} + +void ModListView::disableSelected() +{ + Profile* profile = m_core->currentProfile(); + if (selectionModel()->hasSelection()) { + QList modsToDisable; + for (auto row : selectionModel()->selectedRows(ModList::COL_PRIORITY)) { + int modID = profile->modIndexByPriority(row.data().toInt()); + modsToDisable.append(modID); + } + profile->setModsEnabled({}, modsToDisable); + } + invalidate(); +} + +void ModListView::setFilterCriteria(const std::vector& criteria) +{ + m_sortProxy->setCriteria(criteria); +} + +void ModListView::setFilterOptions(ModListSortProxy::FilterMode mode, ModListSortProxy::SeparatorsMode sep) +{ + m_sortProxy->setOptions(mode, sep); +} + +bool ModListView::isModVisible(unsigned int index) const +{ + return m_sortProxy->filterMatchesMod(ModInfo::getByIndex(index), m_core->currentProfile()->modEnabled(index)); +} + +bool ModListView::isModVisible(ModInfo::Ptr mod) const +{ + return m_sortProxy->filterMatchesMod(mod, m_core->currentProfile()->modEnabled(ModInfo::getIndex(mod->name()))); +} + +QModelIndex ModListView::indexModelToView(const QModelIndex& index) const +{ + if (index.model() != m_core->modList()) { + return QModelIndex(); + } + + // we need to stack the proxy + std::vector proxies; + { + auto* currentModel = model(); + while (auto* proxy = qobject_cast(currentModel)) { + proxies.push_back(proxy); + currentModel = proxy->sourceModel(); + } + } + + if (proxies.empty() || proxies.back()->sourceModel() != m_core->modList()) { + return QModelIndex(); + } + + auto qindex = index; + for (auto rit = proxies.rbegin(); rit != proxies.rend(); ++rit) { + qindex = (*rit)->mapFromSource(qindex); + } + + return qindex; +} + +QModelIndex ModListView::indexViewToModel(const QModelIndex& index) const +{ + if (index.model() == m_core->modList()) { + return index; + } + else if (auto* proxy = qobject_cast(index.model())) { + return indexViewToModel(proxy->mapToSource(index)); + } + else { + return QModelIndex(); + } +} + +std::vector ModListView::allIndex( + const QAbstractItemModel* model, int column, const QModelIndex& parent) const +{ + std::vector index; + for (std::size_t i = 0; i < model->rowCount(parent); ++i) { + index.push_back(model->index(i, column, parent)); + + auto cindex = allIndex(model, column, index.back()); + index.insert(index.end(), cindex.begin(), cindex.end()); + } + return index; +} + +void ModListView::expandItem(const QModelIndex& index) { + if (index.model() == m_sortProxy->sourceModel()) { + expand(m_sortProxy->mapFromSource(index)); + } + else if (index.model() == model()) { + expand(index); + } +} + +void ModListView::onModPrioritiesChanged(std::vector const& indices) +{ + if (m_sortProxy != nullptr) { + // expand separator whose priority has changed + if (hasCollapsibleSeparators()) { + for (auto index : indices) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(index); + if (modInfo->isSeparator()) { + expand(indexModelToView(m_core->modList()->index(index, 0))); + } + } + } + m_sortProxy->invalidate(); + } +} + +void ModListView::onModInstalled(const QString& modName) +{ + unsigned int index = ModInfo::getIndex(modName); + + if (index == UINT_MAX) { + return; + } + + QModelIndex qIndex = indexModelToView(m_core->modList()->index(index, 0)); + + if (hasCollapsibleSeparators()) { + expand(qIndex); + } + + // focus, scroll to and select + setFocus(Qt::OtherFocusReason); + scrollTo(qIndex); + setCurrentIndex(qIndex); + selectionModel()->select(qIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows); +} + +void ModListView::onModFilterActive(bool filterActive) +{ + ui.clearFilters->setVisible(filterActive); + if (filterActive) { + setStyleSheet("QTreeView { border: 2px ridge #f00; }"); + ui.counter->setStyleSheet("QLCDNumber { border: 2px ridge #f00; }"); + } + else if (ui.groupBy->currentIndex() != GroupBy::NONE) { + setStyleSheet("QTreeView { border: 2px ridge #337733; }"); + ui.counter->setStyleSheet(""); + } + else { + setStyleSheet(""); + ui.counter->setStyleSheet(""); + } +} + +void ModListView::updateModCount() +{ + int activeCount = 0; + int visActiveCount = 0; + int backupCount = 0; + int visBackupCount = 0; + int foreignCount = 0; + int visForeignCount = 0; + int separatorCount = 0; + int visSeparatorCount = 0; + int regularCount = 0; + int visRegularCount = 0; + + QStringList allMods = m_core->modList()->allMods(); + + auto hasFlag = [](std::vector flags, ModInfo::EFlag filter) { + return std::find(flags.begin(), flags.end(), filter) != flags.end(); + }; + + bool isEnabled; + bool isVisible; + for (QString mod : allMods) { + int modIndex = ModInfo::getIndex(mod); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + std::vector modFlags = modInfo->getFlags(); + isEnabled = m_core->currentProfile()->modEnabled(modIndex); + isVisible = m_sortProxy->filterMatchesMod(modInfo, isEnabled); + + for (auto flag : modFlags) { + switch (flag) { + case ModInfo::FLAG_BACKUP: backupCount++; + if (isVisible) + visBackupCount++; + break; + case ModInfo::FLAG_FOREIGN: foreignCount++; + if (isVisible) + visForeignCount++; + break; + case ModInfo::FLAG_SEPARATOR: separatorCount++; + if (isVisible) + visSeparatorCount++; + break; + } + } + + if (!hasFlag(modFlags, ModInfo::FLAG_BACKUP) && + !hasFlag(modFlags, ModInfo::FLAG_FOREIGN) && + !hasFlag(modFlags, ModInfo::FLAG_SEPARATOR) && + !hasFlag(modFlags, ModInfo::FLAG_OVERWRITE)) { + if (isEnabled) { + activeCount++; + if (isVisible) + visActiveCount++; + } + if (isVisible) + visRegularCount++; + regularCount++; + } + } + + ui.counter->display(visActiveCount); + ui.counter->setToolTip(tr("" + "" + "" + "" + "" + "" + "
    TypeAllVisible
    Enabled mods: %1 / %2%3 / %4
    Unmanaged/DLCs: %5%6
    Mod backups: %7%8
    Separators: %9%10
    ") + .arg(activeCount) + .arg(regularCount) + .arg(visActiveCount) + .arg(visRegularCount) + .arg(foreignCount) + .arg(visForeignCount) + .arg(backupCount) + .arg(visBackupCount) + .arg(separatorCount) + .arg(visSeparatorCount) + ); +} + +void ModListView::updateGroupByProxy(int groupIndex) +{ + // if the index is -1, we do not refresh unless we are grouping + // by separator + if (groupIndex == -1) { + if (ui.groupBy->currentIndex() != GroupBy::NONE) { + return; + } + groupIndex = ui.groupBy->currentIndex(); + } + + if (groupIndex == GroupBy::CATEGORY) { + m_byCategoryProxy->setGroupedColumn(ModList::COL_CATEGORY); + m_sortProxy->setSourceModel(m_byCategoryProxy); + } + else if (groupIndex == GroupBy::NEXUS_ID) { + m_byNexusIdProxy->setGroupedColumn(ModList::COL_MODID); + m_sortProxy->setSourceModel(m_byNexusIdProxy); + } + else if (m_sortProxy->sortColumn() == ModList::COL_PRIORITY + && m_sortProxy->sortOrder() == Qt::AscendingOrder) { + m_sortProxy->setSourceModel(m_byPriorityProxy); + m_byPriorityProxy->refresh(); + } + else { + m_sortProxy->setSourceModel(m_core->modList()); + } +} + +void ModListView::setup(OrganizerCore& core, Ui::MainWindow* mwui) +{ + // attributes + m_core = &core; + ui = { mwui->groupCombo, mwui->activeModsCounter, mwui->modFilterEdit, mwui->clearFiltersButton }; + + connect(m_core, &OrganizerCore::modInstalled, this, &ModListView::onModInstalled); + connect(core.modList(), &ModList::modPrioritiesChanged, this, &ModListView::onModPrioritiesChanged); + + m_byPriorityProxy = new ModListByPriorityProxy(core.currentProfile(), &core); + m_byPriorityProxy->setSourceModel(core.modList()); + connect(this, &QTreeView::expanded, m_byPriorityProxy, &ModListByPriorityProxy::expanded); + connect(this, &QTreeView::collapsed, m_byPriorityProxy, &ModListByPriorityProxy::collapsed); + connect(m_byPriorityProxy, &ModListByPriorityProxy::expandItem, this, &ModListView::expandItem); + + m_byCategoryProxy = new QtGroupingProxy(core.modList(), QModelIndex(), ModList::COL_CATEGORY, + Qt::UserRole, 0, Qt::UserRole + 2); + connect(this, &QTreeView::expanded, m_byCategoryProxy, &QtGroupingProxy::expanded); + connect(this, &QTreeView::collapsed, m_byCategoryProxy, &QtGroupingProxy::collapsed); + connect(m_byCategoryProxy, &QtGroupingProxy::expandItem, this, &ModListView::expandItem); + m_byNexusIdProxy = new QtGroupingProxy(core.modList(), QModelIndex(), ModList::COL_MODID, Qt::DisplayRole, + QtGroupingProxy::FLAG_NOGROUPNAME | QtGroupingProxy::FLAG_NOSINGLE, Qt::UserRole + 2); + connect(this, &QTreeView::expanded, m_byNexusIdProxy, &QtGroupingProxy::expanded); + connect(this, &QTreeView::collapsed, m_byNexusIdProxy, &QtGroupingProxy::collapsed); + connect(m_byNexusIdProxy, &QtGroupingProxy::expandItem, this, &ModListView::expandItem); + + m_sortProxy = new ModListSortProxy(core.currentProfile(), &core); + setModel(m_sortProxy); + + connect(m_sortProxy, &QAbstractItemModel::layoutAboutToBeChanged, + this, [this](const QList& parents, QAbstractItemModel::LayoutChangeHint hint) { + if (hint == QAbstractItemModel::VerticalSortHint) { + updateGroupByProxy(-1); + } + }); + sortByColumn(ModList::COL_PRIORITY, Qt::AscendingOrder); + + connect(ui.groupBy, QOverload::of(&QComboBox::currentIndexChanged), this, [&](int index) { + updateGroupByProxy(index); + onModFilterActive(m_sortProxy->isFilterActive()); + }); + + connect(this, &ModListView::dragEntered, core.modList(), &ModList::onDragEnter); + connect(this, &ModListView::dropEntered, m_byPriorityProxy, &ModListByPriorityProxy::onDropEnter); + + connect(model(), &QAbstractItemModel::layoutChanged, this, &ModListView::updateModCount); + + connect(header(), &QHeaderView::sortIndicatorChanged, this, [&](int, Qt::SortOrder) { + verticalScrollBar()->repaint(); }); + connect(header(), &QHeaderView::sectionResized, this, [&](int logicalIndex, int oldSize, int newSize) { + m_sortProxy->setColumnVisible(logicalIndex, newSize != 0); }); + + GenericIconDelegate* contentDelegate = new GenericIconDelegate(this, Qt::UserRole + 3, ModList::COL_CONTENT, 150); + ModFlagIconDelegate* flagDelegate = new ModFlagIconDelegate(this, ModList::COL_FLAGS, 120); + ModConflictIconDelegate* conflictFlagDelegate = new ModConflictIconDelegate(this, ModList::COL_CONFLICTFLAGS, 80); + + connect(header(), &QHeaderView::sectionResized, contentDelegate, &GenericIconDelegate::columnResized); + connect(header(), &QHeaderView::sectionResized, flagDelegate, &ModFlagIconDelegate::columnResized); + connect(header(), &QHeaderView::sectionResized, conflictFlagDelegate, &ModConflictIconDelegate::columnResized); + + setItemDelegateForColumn(ModList::COL_FLAGS, flagDelegate); + setItemDelegateForColumn(ModList::COL_CONFLICTFLAGS, conflictFlagDelegate); + setItemDelegateForColumn(ModList::COL_CONTENT, contentDelegate); + + // TODO: Check if this is really useful. + header()->installEventFilter(m_core->modList()); + + if (m_core->settings().geometry().restoreState(header())) { + // hack: force the resize-signal to be triggered because restoreState doesn't seem to do that + for (int column = 0; column <= ModList::COL_LASTCOLUMN; ++column) { + int sectionSize = header()->sectionSize(column); + header()->resizeSection(column, sectionSize + 1); + header()->resizeSection(column, sectionSize); + } + } + else { + // hide these columns by default + header()->setSectionHidden(ModList::COL_CONTENT, true); + header()->setSectionHidden(ModList::COL_MODID, true); + header()->setSectionHidden(ModList::COL_GAME, true); + header()->setSectionHidden(ModList::COL_INSTALLTIME, true); + header()->setSectionHidden(ModList::COL_NOTES, true); + + // resize mod list to fit content + for (int i = 0; i < header()->count(); ++i) { + header()->setSectionResizeMode(i, QHeaderView::ResizeToContents); + } + + header()->setSectionResizeMode(ModList::COL_NAME, QHeaderView::Stretch); + } + + // prevent the name-column from being hidden + header()->setSectionHidden(ModList::COL_NAME, false); + + // TODO: Move the event filter in ModListView. + installEventFilter(core.modList()); + + connect(m_core->modList(), &ModList::downloadArchiveDropped, this, [this](int row, int priority) { + m_core->installDownload(row, priority); + }); + + connect(m_sortProxy, &ModListSortProxy::filterActive, this, &ModListView::onModFilterActive); + connect(ui.filter, &QLineEdit::textChanged, m_sortProxy, &ModListSortProxy::updateFilter); + connect(m_sortProxy, &QAbstractItemModel::layoutChanged, this, [&]() { + if (hasCollapsibleSeparators()) { + m_byPriorityProxy->refreshExpandedItems(); + } + }); +} + QRect ModListView::visualRect(const QModelIndex& index) const { QRect rect = QTreeView::visualRect(index); diff --git a/src/modlistview.h b/src/modlistview.h index 9cf1c0d9..1e6c5ceb 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -1,12 +1,21 @@ #ifndef MODLISTVIEW_H #define MODLISTVIEW_H +#include + #include #include +#include + +#include "qtgroupingproxy.h" #include "viewmarkingscrollbar.h" +#include "modlistsortproxy.h" namespace Ui { class MainWindow; } + class OrganizerCore; +class Profile; +class ModListByPriorityProxy; class ModListView : public QTreeView { @@ -26,15 +35,81 @@ public: explicit ModListView(QWidget* parent = 0); void setModel(QAbstractItemModel* model) override; + void setup(OrganizerCore& core, Ui::MainWindow* mwui); + + // set the current profile + // + void setProfile(Profile* profile); + + // check if collapsible separators are currently used + // + bool hasCollapsibleSeparators() const; + + // the column by which the mod list is currently sorted + // + int sortColumn() const; + + // retrieve the next/previous mod in the current view, the given index + // should be a mod index (not a model row), and the return value will be + // a mod index or -1 if no mod was found + // + int nextMod(int index) const; + int prevMod(int index) const; + + // invalidate the top-level model + // + void invalidate(); + + // enable/disable all visible mods + // + void enableAllVisible(); + void disableAllVisible(); + + // enable/disable all selected mods + // + void enableSelected(); + void disableSelected(); + + // set the filter criteria/options for mods + // + void setFilterCriteria(const std::vector& criteria); + void setFilterOptions(ModListSortProxy::FilterMode mode, ModListSortProxy::SeparatorsMode sep); + + // check if the given mod is visible + // + bool isModVisible(unsigned int index) const; + bool isModVisible(ModInfo::Ptr mod) const; + + // re-implemented to fix indentation with collapsible separators + // QRect visualRect(const QModelIndex& index) const override; + // refresh the style of the mod list, this needs to be called when the + // stylesheet is changed + // + void refreshStyle(); + signals: void dragEntered(const QMimeData* mimeData); void dropEntered(const QMimeData* mimeData, DropPosition position); +public slots: + + void updateModCount(); + protected: + // map from/to the view indexes to the model + // + QModelIndex indexModelToView(const QModelIndex& index) const; + QModelIndex indexViewToModel(const QModelIndex& index) const; + + // all index for the given model under the given index, recursively + // + std::vector allIndex( + const QAbstractItemModel* model, int column = 0, const QModelIndex& index = QModelIndex()) const; + // re-implemented to fake the return value to allow drag-and-drop on // itself for separators // @@ -47,6 +122,50 @@ protected: private: + void onModPrioritiesChanged(std::vector const& indices); + void onModInstalled(const QString& modName); + void onModFilterActive(bool filterActive); + + // call expand() after fixing the index if it comes from the source + // of the proxy + // + void expandItem(const QModelIndex& index); + + // refresh the group-by proxy, if the index is -1 will refresh the + // current one (e.g. when changing the sort column) + // + void updateGroupByProxy(int groupIndex); + + enum GroupBy { + NONE = 0, + CATEGORY = 1, + NEXUS_ID = 2 + }; + +private: + + struct ModListViewUi + { + // the group by combo box + QComboBox* groupBy; + + // the mod counter + QLCDNumber* counter; + + // the text filter and clear filter button + QLineEdit* filter; + QPushButton* clearFilters; + }; + + OrganizerCore* m_core; + ModListViewUi ui; + + ModListSortProxy* m_sortProxy; + ModListByPriorityProxy* m_byPriorityProxy; + + QtGroupingProxy* m_byCategoryProxy; + QtGroupingProxy* m_byNexusIdProxy; + ViewMarkingScrollBar* m_scrollbar; bool m_inDragMoveEvent = false; -- cgit v1.3.1 From 6e803a35226980a135d8837898345b38675e3188 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Tue, 29 Dec 2020 20:29:00 +0100 Subject: Fix prev/next button in mod info dialog. --- src/mainwindow.cpp | 22 +++++++++++----------- src/modlistview.cpp | 52 +++++++++++++++++++++++++++++++++++++++++++--------- src/modlistview.h | 5 +++++ 3 files changed, 59 insertions(+), 20 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 99c5293d..c6c4e562 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2764,20 +2764,20 @@ void MainWindow::setWindowEnabled(bool enabled) ModInfo::Ptr MainWindow::nextModInList() { - int index = ui->modList->nextMod(m_ContextRow); - if (index == -1) { + m_ContextRow = ui->modList->nextMod(m_ContextRow); + if (m_ContextRow == -1) { return {}; } - return ModInfo::getByIndex(index); + return ModInfo::getByIndex(m_ContextRow); } ModInfo::Ptr MainWindow::previousModInList() { - int index = ui->modList->prevMod(m_ContextRow); - if (index == -1) { + m_ContextRow = ui->modList->prevMod(m_ContextRow); + if (m_ContextRow == -1) { return {}; } - return ModInfo::getByIndex(index); + return ModInfo::getByIndex(m_ContextRow); } void MainWindow::displayModInformation(const QString &modName, ModInfoTabIDs tabID) @@ -3479,13 +3479,13 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) } bool indexOk = false; - int modIndex = index.data(ModList::IndexRole).toInt(&indexOk); + m_ContextRow = index.data(ModList::IndexRole).toInt(&indexOk); - if (!indexOk || modIndex < 0 || modIndex >= ModInfo::getNumMods()) { + if (!indexOk || m_ContextRow < 0 || m_ContextRow >= ModInfo::getNumMods()) { return; } - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); Qt::KeyboardModifiers modifiers = QApplication::queryKeyboardModifiers(); if (modifiers.testFlag(Qt::ControlModifier)) { @@ -3502,7 +3502,7 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) } else if (modifiers.testFlag(Qt::ShiftModifier)) { try { - QModelIndex idx = m_OrganizerCore.modList()->index(modIndex, 0); + QModelIndex idx = m_OrganizerCore.modList()->index(m_ContextRow, 0); visitNexusOrWebPage(idx); ui->modList->closePersistentEditor(index); } @@ -3526,7 +3526,7 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) case ModList::COL_CONFLICTFLAGS: tab = ModInfoTabIDs::Conflicts; break; } - displayModInformation(modIndex, tab); + displayModInformation(m_ContextRow, tab); // workaround to cancel the editor that might have opened because of // selection-click ui->modList->closePersistentEditor(index); diff --git a/src/modlistview.cpp b/src/modlistview.cpp index bccacb24..643b1971 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -107,14 +107,15 @@ int ModListView::nextMod(int modIndex) const auto index = start; for (;;) { - index = model()->index((index.row() + 1) % model()->rowCount(), 0); - modIndex = indexViewToModel(index).data(ModList::IndexRole).toInt(); + index = nextIndex(index); if (index == start || !index.isValid()) { // wrapped around, give up break; } + modIndex = index.data(ModList::IndexRole).toInt(); + ModInfo::Ptr mod = ModInfo::getByIndex(modIndex); // skip overwrite and backups and separators @@ -137,19 +138,15 @@ int ModListView::prevMod(int modIndex) const auto index = start; for (;;) { - int row = index.row() - 1; - if (row == -1) { - row = model()->rowCount() - 1; - } - - index = model()->index(row, 0); - modIndex = indexViewToModel(index).data(ModList::IndexRole).toInt(); + index = prevIndex(index); if (index == start || !index.isValid()) { // wrapped around, give up break; } + modIndex = index.data(ModList::IndexRole).toInt(); + // skip overwrite and backups and separators ModInfo::Ptr mod = ModInfo::getByIndex(modIndex); @@ -286,6 +283,43 @@ QModelIndex ModListView::indexViewToModel(const QModelIndex& index) const } } +QModelIndex ModListView::nextIndex(const QModelIndex& index) const +{ + auto* model = index.model(); + + if (model->rowCount(index) > 0) { + return model->index(0, index.column(), index); + } + + if (index.parent().isValid()) { + if (index.row() + 1 < model->rowCount(index.parent())) { + return index.model()->index(index.row() + 1, index.column(), index.parent()); + } + else { + return index.model()->index((index.parent().row() + 1) % model->rowCount(index.parent().parent()), index.column(), index.parent().parent());; + } + } + else { + return index.model()->index((index.row() + 1) % model->rowCount(index.parent()), index.column(), index.parent()); + } +} + +QModelIndex ModListView::prevIndex(const QModelIndex& index) const +{ + if (index.row() == 0 && index.parent().isValid()) { + return index.parent(); + } + + auto* model = index.model(); + auto prev = model->index((index.row() - 1) % model->rowCount(index.parent()), index.column(), index.parent()); + + if (model->rowCount(prev) > 0) { + return model->index(model->rowCount(prev) - 1, index.column(), prev); + } + + return prev; +} + std::vector ModListView::allIndex( const QAbstractItemModel* model, int column, const QModelIndex& parent) const { diff --git a/src/modlistview.h b/src/modlistview.h index 1e6c5ceb..7e6b29bb 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -105,6 +105,11 @@ protected: QModelIndex indexModelToView(const QModelIndex& index) const; QModelIndex indexViewToModel(const QModelIndex& index) const; + // returns the next/previous index of the given index + // + QModelIndex nextIndex(const QModelIndex& index) const; + QModelIndex prevIndex(const QModelIndex& index) const; + // all index for the given model under the given index, recursively // std::vector allIndex( -- cgit v1.3.1 From 44e846cf18d2e46b471183fd1d5ba81a4b7a312d Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Tue, 29 Dec 2020 21:23:23 +0100 Subject: Remove context attribute from MainWindow. --- src/mainwindow.cpp | 421 ++++++++++++++++++++++++-------------------------- src/mainwindow.h | 67 ++++---- src/modinfodialog.cpp | 4 +- src/modlistview.h | 40 ++--- 4 files changed, 257 insertions(+), 275 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index c6c4e562..e54c24e1 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -255,9 +255,6 @@ MainWindow::MainWindow(Settings &settings , m_OldProfileIndex(-1) , m_OldExecutableIndex(-1) , m_CategoryFactory(CategoryFactory::instance()) - , m_ContextItem(nullptr) - , m_ContextAction(nullptr) - , m_ContextRow(-1) , m_OrganizerCore(organizerCore) , m_PluginContainer(pluginContainer) , m_DidUpdateMasterList(false) @@ -398,7 +395,6 @@ MainWindow::MainWindow(Settings &settings QMenu *listOptionsMenu = new QMenu(ui->listOptionsBtn); initModListContextMenu(listOptionsMenu); ui->listOptionsBtn->setMenu(listOptionsMenu); - connect(ui->listOptionsBtn, SIGNAL(pressed()), this, SLOT(on_listOptionsBtn_pressed())); ui->openFolderMenu->setMenu(openFolderMenu()); @@ -2421,10 +2417,10 @@ void MainWindow::renameMod_clicked() } -void MainWindow::restoreBackup_clicked() +void MainWindow::restoreBackup_clicked(int modIndex) { QRegExp backupRegEx("(.*)_backup[0-9]*$"); - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); if (backupRegEx.indexIn(modInfo->name()) != -1) { QString regName = backupRegEx.cap(1); QDir modDir(QDir::fromNativeSeparators(m_OrganizerCore.settings().paths().mods())); @@ -2483,7 +2479,7 @@ void MainWindow::esplistSelectionsChanged(const QItemSelection &selected) ui->modList->verticalScrollBar()->repaint(); } -void MainWindow::removeMod_clicked() +void MainWindow::removeMod_clicked(int modIndex) { const int max_items = 20; @@ -2525,7 +2521,7 @@ void MainWindow::removeMod_clicked() DownloadManager::endDisableDirWatcher(); } } else { - m_OrganizerCore.modList()->removeRow(m_ContextRow, QModelIndex()); + m_OrganizerCore.modList()->removeRow(modIndex, QModelIndex()); } ui->modList->updateModCount(); updatePluginCount(); @@ -2543,9 +2539,9 @@ void MainWindow::modRemoved(const QString &fileName) } -void MainWindow::reinstallMod_clicked() +void MainWindow::reinstallMod_clicked(int modIndex) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); QString installationFile = modInfo->installationFile(); if (installationFile.length() != 0) { QString fullInstallationFile; @@ -2570,9 +2566,9 @@ void MainWindow::reinstallMod_clicked() } } -void MainWindow::backupMod_clicked() +void MainWindow::backupMod_clicked(int modIndex) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); QString backupDirectory = m_OrganizerCore.installationManager()->generateBackupName(modInfo->absolutePath()); if (!copyDir(modInfo->absolutePath(), backupDirectory, false)) { QMessageBox::information(this, tr("Failed"), @@ -2606,7 +2602,7 @@ void MainWindow::endorse_clicked() }); } -void MainWindow::dontendorse_clicked() +void MainWindow::dontendorse_clicked(int modIndex) { QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { @@ -2615,7 +2611,7 @@ void MainWindow::dontendorse_clicked() } } else { - ModInfo::getByIndex(m_ContextRow)->setNeverEndorse(); + ModInfo::getByIndex(modIndex)->setNeverEndorse(); } } @@ -2762,22 +2758,22 @@ void MainWindow::setWindowEnabled(bool enabled) setEnabled(enabled); } -ModInfo::Ptr MainWindow::nextModInList() +ModInfo::Ptr MainWindow::nextModInList(int modIndex) { - m_ContextRow = ui->modList->nextMod(m_ContextRow); - if (m_ContextRow == -1) { + modIndex = ui->modList->nextMod(modIndex); + if (modIndex == -1) { return {}; } - return ModInfo::getByIndex(m_ContextRow); + return ModInfo::getByIndex(modIndex); } -ModInfo::Ptr MainWindow::previousModInList() +ModInfo::Ptr MainWindow::previousModInList(int modIndex) { - m_ContextRow = ui->modList->prevMod(m_ContextRow); - if (m_ContextRow == -1) { + modIndex = ui->modList->prevMod(modIndex); + if (modIndex == -1) { return {}; } - return ModInfo::getByIndex(m_ContextRow); + return ModInfo::getByIndex(modIndex); } void MainWindow::displayModInformation(const QString &modName, ModInfoTabIDs tabID) @@ -2800,7 +2796,7 @@ void MainWindow::displayModInformation(int row, ModInfoTabIDs tabID) } -void MainWindow::ignoreMissingData_clicked() +void MainWindow::ignoreMissingData_clicked(int modIndex) { const auto rows = ui->modList->selectionModel()->selectedRows(); @@ -2819,13 +2815,13 @@ void MainWindow::ignoreMissingData_clicked() m_OrganizerCore.modList()->notifyChange(row_idx); } } else { - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr info = ModInfo::getByIndex(modIndex); info->markValidated(true); - m_OrganizerCore.modList()->notifyChange(m_ContextRow); + m_OrganizerCore.modList()->notifyChange(modIndex); } } -void MainWindow::markConverted_clicked() +void MainWindow::markConverted_clicked(int modIndex) { const auto rows = ui->modList->selectionModel()->selectedRows(); @@ -2844,14 +2840,14 @@ void MainWindow::markConverted_clicked() m_OrganizerCore.modList()->notifyChange(row_idx); } } else { - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr info = ModInfo::getByIndex(modIndex); info->markConverted(true); - m_OrganizerCore.modList()->notifyChange(m_ContextRow); + m_OrganizerCore.modList()->notifyChange(modIndex); } } -void MainWindow::restoreHiddenFiles_clicked() +void MainWindow::restoreHiddenFiles_clicked(int modIndex) { const int max_items = 20; QItemSelectionModel* selection = ui->modList->selectionModel(); @@ -2921,7 +2917,7 @@ void MainWindow::restoreHiddenFiles_clicked() } else { //single selection - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); const QString modDir = modInfo->absolutePath(); if (QMessageBox::question(this, tr("Are you sure?"), @@ -2944,7 +2940,7 @@ void MainWindow::restoreHiddenFiles_clicked() } -void MainWindow::visitOnNexus_clicked() +void MainWindow::visitOnNexus_clicked(int modIndex) { QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { @@ -2973,8 +2969,8 @@ void MainWindow::visitOnNexus_clicked() } } else { - int modID = m_OrganizerCore.modList()->data(m_OrganizerCore.modList()->index(m_ContextRow, 0), Qt::UserRole).toInt(); - QString gameName = m_OrganizerCore.modList()->data(m_OrganizerCore.modList()->index(m_ContextRow, 0), Qt::UserRole + 4).toString(); + int modID = m_OrganizerCore.modList()->data(m_OrganizerCore.modList()->index(modIndex, 0), Qt::UserRole).toInt(); + QString gameName = m_OrganizerCore.modList()->data(m_OrganizerCore.modList()->index(modIndex, 0), Qt::UserRole + 4).toString(); if (modID > 0) { linkClicked(NexusInterface::instance().getModURL(modID, gameName)); } else { @@ -2983,7 +2979,7 @@ void MainWindow::visitOnNexus_clicked() } } -void MainWindow::visitWebPage_clicked() +void MainWindow::visitWebPage_clicked(int index) { QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { @@ -3009,7 +3005,7 @@ void MainWindow::visitWebPage_clicked() } } else { - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr info = ModInfo::getByIndex(index); const auto url = info->parseCustomURL(); if (url.isValid()) { @@ -3041,7 +3037,7 @@ void MainWindow::visitNexusOrWebPage(const QModelIndex& idx) } } -void MainWindow::visitNexusOrWebPage_clicked() { +void MainWindow::visitNexusOrWebPage_clicked(int index) { QItemSelectionModel* selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { int count = selection->selectedRows().count(); @@ -3058,12 +3054,12 @@ void MainWindow::visitNexusOrWebPage_clicked() { } } else { - QModelIndex idx = m_OrganizerCore.modList()->index(m_ContextRow, 0); + QModelIndex idx = m_OrganizerCore.modList()->index(index, 0); visitNexusOrWebPage(idx); } } -void MainWindow::openExplorer_clicked() +void MainWindow::openExplorer_clicked(int index) { QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { @@ -3073,7 +3069,7 @@ void MainWindow::openExplorer_clicked() } } else { - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr modInfo = ModInfo::getByIndex(index); shell::Explore(modInfo->absolutePath()); } } @@ -3195,16 +3191,16 @@ void MainWindow::updatePluginCount() ); } -void MainWindow::information_clicked() +void MainWindow::information_clicked(int modIndex) { try { - displayModInformation(m_ContextRow); + displayModInformation(modIndex); } catch (const std::exception &e) { reportError(e.what()); } } -void MainWindow::createEmptyMod_clicked() +void MainWindow::createEmptyMod_clicked(int modIndex) { GuessedValue name; name.setFilter(&fixDirectoryName); @@ -3226,8 +3222,8 @@ void MainWindow::createEmptyMod_clicked() } int newPriority = -1; - if (m_ContextRow >= 0 && ui->modList->sortColumn() == ModList::COL_PRIORITY) { - newPriority = m_OrganizerCore.currentProfile()->getModPriority(m_ContextRow); + if (modIndex >= 0 && ui->modList->sortColumn() == ModList::COL_PRIORITY) { + newPriority = m_OrganizerCore.currentProfile()->getModPriority(modIndex); } IModInterface *newMod = m_OrganizerCore.createMod(name); @@ -3242,7 +3238,7 @@ void MainWindow::createEmptyMod_clicked() } } -void MainWindow::createSeparator_clicked() +void MainWindow::createSeparator_clicked(int modIndex) { GuessedValue name; name.setFilter(&fixDirectoryName); @@ -3267,9 +3263,9 @@ void MainWindow::createSeparator_clicked() } int newPriority = -1; - if (m_ContextRow >= 0 && ui->modList->sortColumn() == ModList::COL_PRIORITY) + if (modIndex >= 0 && ui->modList->sortColumn() == ModList::COL_PRIORITY) { - newPriority = m_OrganizerCore.currentProfile()->getModPriority(m_ContextRow); + newPriority = m_OrganizerCore.currentProfile()->getModPriority(modIndex); } if (m_OrganizerCore.createMod(name) == nullptr) { return; } @@ -3285,10 +3281,10 @@ void MainWindow::createSeparator_clicked() } } -void MainWindow::setColor_clicked() +void MainWindow::setColor_clicked(int modIndex) { auto& settings = m_OrganizerCore.settings(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); QColorDialog dialog(this); dialog.setOption(QColorDialog::ShowAlphaChannel); @@ -3322,9 +3318,9 @@ void MainWindow::setColor_clicked() } } -void MainWindow::resetColor_clicked() +void MainWindow::resetColor_clicked(int modIndex) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); QColor color = QColor(); QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { @@ -3479,13 +3475,13 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) } bool indexOk = false; - m_ContextRow = index.data(ModList::IndexRole).toInt(&indexOk); + int modIndex = index.data(ModList::IndexRole).toInt(&indexOk); - if (!indexOk || m_ContextRow < 0 || m_ContextRow >= ModInfo::getNumMods()) { + if (!indexOk || modIndex < 0 || modIndex >= ModInfo::getNumMods()) { return; } - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); Qt::KeyboardModifiers modifiers = QApplication::queryKeyboardModifiers(); if (modifiers.testFlag(Qt::ControlModifier)) { @@ -3502,7 +3498,7 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) } else if (modifiers.testFlag(Qt::ShiftModifier)) { try { - QModelIndex idx = m_OrganizerCore.modList()->index(m_ContextRow, 0); + QModelIndex idx = m_OrganizerCore.modList()->index(modIndex, 0); visitNexusOrWebPage(idx); ui->modList->closePersistentEditor(index); } @@ -3526,7 +3522,7 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) case ModList::COL_CONFLICTFLAGS: tab = ModInfoTabIDs::Conflicts; break; } - displayModInformation(m_ContextRow, tab); + displayModInformation(modIndex, tab); // workaround to cancel the editor that might have opened because of // selection-click ui->modList->closePersistentEditor(index); @@ -3537,11 +3533,6 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) } } -void MainWindow::on_listOptionsBtn_pressed() -{ - m_ContextRow = -1; -} - void MainWindow::openOriginInformation_clicked() { try { @@ -3629,9 +3620,9 @@ void MainWindow::on_espList_doubleClicked(const QModelIndex &index) } } -bool MainWindow::populateMenuCategories(QMenu *menu, int targetID) +bool MainWindow::populateMenuCategories(int modIndex, QMenu *menu, int targetID) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); const std::set &categories = modInfo->getCategories(); bool childEnabled = false; @@ -3658,7 +3649,7 @@ bool MainWindow::populateMenuCategories(QMenu *menu, int targetID) targetMenu->addAction(checkableAction.take()); if (m_CategoryFactory.hasChildren(i)) { - if (populateMenuCategories(targetMenu, m_CategoryFactory.getCategoryID(i)) || enabled) { + if (populateMenuCategories(modIndex, targetMenu, m_CategoryFactory.getCategoryID(i)) || enabled) { targetMenu->setIcon(QIcon(":/MO/gui/resources/check.png")); } } @@ -3710,7 +3701,7 @@ void MainWindow::addRemoveCategoriesFromMenu(QMenu *menu, int modRow, int refere } } -void MainWindow::addRemoveCategories_MenuHandler() { +void MainWindow::addRemoveCategories_MenuHandler(int modIndex, const QModelIndex& rowIdx) { QMenu *menu = qobject_cast(sender()); if (menu == nullptr) { log::error("not a menu?"); @@ -3729,13 +3720,13 @@ void MainWindow::addRemoveCategories_MenuHandler() { for (const QPersistentModelIndex &idx : selected) { log::debug("change categories on: {}", idx.data().toString()); QModelIndex modIdx = mapToModel(m_OrganizerCore.modList(), idx); - if (modIdx.row() != m_ContextIdx.row()) { - addRemoveCategoriesFromMenu(menu, modIdx.row(), m_ContextIdx.row()); + if (modIdx.row() != rowIdx.row()) { + addRemoveCategoriesFromMenu(menu, modIdx.row(), rowIdx.row()); } if (idx.row() < minRow) minRow = idx.row(); if (idx.row() > maxRow) maxRow = idx.row(); } - replaceCategoriesFromMenu(menu, m_ContextIdx.row()); + replaceCategoriesFromMenu(menu, rowIdx.row()); m_OrganizerCore.modList()->notifyChange(minRow, maxRow + 1); @@ -3744,14 +3735,14 @@ void MainWindow::addRemoveCategories_MenuHandler() { } } else { //For single mod selections, just do a replace - replaceCategoriesFromMenu(menu, m_ContextRow); - m_OrganizerCore.modList()->notifyChange(m_ContextRow); + replaceCategoriesFromMenu(menu, modIndex); + m_OrganizerCore.modList()->notifyChange(modIndex); } refreshFilters(); } -void MainWindow::replaceCategories_MenuHandler() { +void MainWindow::replaceCategories_MenuHandler(int modIndex) { QMenu *menu = qobject_cast(sender()); if (menu == nullptr) { log::error("not a menu?"); @@ -3788,8 +3779,8 @@ void MainWindow::replaceCategories_MenuHandler() { } } else { //For single mod selections, just do a replace - replaceCategoriesFromMenu(menu, m_ContextRow); - m_OrganizerCore.modList()->notifyChange(m_ContextRow); + replaceCategoriesFromMenu(menu, modIndex); + m_OrganizerCore.modList()->notifyChange(modIndex); } refreshFilters(); @@ -3855,13 +3846,13 @@ void MainWindow::checkModsForUpdates() } } -void MainWindow::changeVersioningScheme() { +void MainWindow::changeVersioningScheme(int modIndex) { if (QMessageBox::question(this, 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(m_ContextRow); + ModInfo::Ptr info = ModInfo::getByIndex(modIndex); bool success = false; @@ -3884,7 +3875,8 @@ void MainWindow::changeVersioningScheme() { } } -void MainWindow::ignoreUpdate() { +void MainWindow::ignoreUpdate(int modIndex) +{ QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { for (QModelIndex idx : selection->selectedRows()) { @@ -3893,13 +3885,13 @@ void MainWindow::ignoreUpdate() { } } else { - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr info = ModInfo::getByIndex(modIndex); info->ignoreUpdate(true); } ui->modList->invalidate(); } -void MainWindow::checkModUpdates_clicked() +void MainWindow::checkModUpdates_clicked(int modIndex) { std::multimap IDs; QItemSelectionModel *selection = ui->modList->selectionModel(); @@ -3909,13 +3901,13 @@ void MainWindow::checkModUpdates_clicked() IDs.insert(std::make_pair(info->gameName(), info->nexusId())); } } else { - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr info = ModInfo::getByIndex(modIndex); IDs.insert(std::make_pair(info->gameName(), info->nexusId())); } modUpdateCheck(IDs); } -void MainWindow::unignoreUpdate() +void MainWindow::unignoreUpdate(int modIndex) { QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { @@ -3925,7 +3917,7 @@ void MainWindow::unignoreUpdate() } } else { - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr info = ModInfo::getByIndex(modIndex); info->ignoreUpdate(false); } ui->modList->invalidate(); @@ -3957,7 +3949,7 @@ void MainWindow::addPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, } } -void MainWindow::addPrimaryCategoryCandidates() +void MainWindow::addPrimaryCategoryCandidates(int modIndex) { QMenu *menu = qobject_cast(sender()); if (menu == nullptr) { @@ -3965,7 +3957,7 @@ void MainWindow::addPrimaryCategoryCandidates() return; } menu->clear(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); addPrimaryCategoryCandidates(menu, modInfo); } @@ -4260,21 +4252,21 @@ QMenu *MainWindow::openFolderMenu() void MainWindow::initModListContextMenu(QMenu *menu) { - menu->addAction(tr("Install Mod..."), this, SLOT(installMod_clicked())); - menu->addAction(tr("Create empty mod"), this, SLOT(createEmptyMod_clicked())); + menu->addAction(tr("Install Mod..."), [&]() { installMod_clicked(); }); + menu->addAction(tr("Create empty mod"), [&]() { createEmptyMod_clicked(-1); }); menu->addSeparator(); - menu->addAction(tr("Create Separator"), this, SLOT(createSeparator_clicked())); + menu->addAction(tr("Create Separator"), [&]() { createSeparator_clicked(-1); }); menu->addAction(tr("Collapse all"), ui->modList, &QTreeView::collapseAll); menu->addAction(tr("Expand all"), ui->modList, &QTreeView::expandAll); menu->addSeparator(); - menu->addAction(tr("Enable all visible"), this, SLOT(enableVisibleMods())); - menu->addAction(tr("Disable all visible"), this, SLOT(disableVisibleMods())); - menu->addAction(tr("Check for updates"), this, SLOT(checkModsForUpdates())); - menu->addAction(tr("Refresh"), &m_OrganizerCore, SLOT(profileRefresh())); - menu->addAction(tr("Export to csv..."), this, SLOT(exportModListCSV())); + menu->addAction(tr("Enable all visible"), [&]() { enableVisibleMods(); }); + menu->addAction(tr("Disable all visible"), [&]() { disableVisibleMods(); }); + menu->addAction(tr("Check for updates"), [&]() { checkModsForUpdates(); }); + menu->addAction(tr("Refresh"), &m_OrganizerCore, &OrganizerCore::profileRefresh); + menu->addAction(tr("Export to csv..."), [&]() { exportModListCSV(); }); } void MainWindow::addModSendToContextMenu(QMenu *menu) @@ -4284,10 +4276,10 @@ void MainWindow::addModSendToContextMenu(QMenu *menu) QMenu *sub_menu = new QMenu(menu); sub_menu->setTitle(tr("Send to")); - sub_menu->addAction(tr("Top"), this, SLOT(sendSelectedModsToTop_clicked())); - sub_menu->addAction(tr("Bottom"), this, SLOT(sendSelectedModsToBottom_clicked())); - sub_menu->addAction(tr("Priority..."), this, SLOT(sendSelectedModsToPriority_clicked())); - sub_menu->addAction(tr("Separator..."), this, SLOT(sendSelectedModsToSeparator_clicked())); + sub_menu->addAction(tr("Top"), [&]() { sendSelectedModsToTop_clicked(); }); + sub_menu->addAction(tr("Bottom"), [&]() { sendSelectedModsToBottom_clicked(); }); + sub_menu->addAction(tr("Priority..."), [&]() { sendSelectedModsToPriority_clicked(); }); + sub_menu->addAction(tr("Separator..."), [&]() { sendSelectedModsToSeparator_clicked(); }); menu->addMenu(sub_menu); menu->addSeparator(); @@ -4300,9 +4292,9 @@ void MainWindow::addPluginSendToContextMenu(QMenu *menu) QMenu *sub_menu = new QMenu(this); sub_menu->setTitle(tr("Send to")); - sub_menu->addAction(tr("Top"), this, SLOT(sendSelectedPluginsToTop_clicked())); - sub_menu->addAction(tr("Bottom"), this, SLOT(sendSelectedPluginsToBottom_clicked())); - sub_menu->addAction(tr("Priority..."), this, SLOT(sendSelectedPluginsToPriority_clicked())); + sub_menu->addAction(tr("Top"), [&]() { sendSelectedPluginsToTop_clicked(); }); + sub_menu->addAction(tr("Bottom"), [&]() { sendSelectedPluginsToBottom_clicked(); }); + sub_menu->addAction(tr("Priority..."), [&]() { sendSelectedPluginsToPriority_clicked(); }); menu->addMenu(sub_menu); menu->addSeparator(); @@ -4313,11 +4305,12 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) try { QTreeView *modList = findChild("modList"); - m_ContextIdx = mapToModel(m_OrganizerCore.modList(), modList->indexAt(pos)); - m_ContextRow = m_ContextIdx.row(); - int contextColumn = m_ContextIdx.column(); + QModelIndex contextIdx = mapToModel(m_OrganizerCore.modList(), ui->modList->indexAt(pos)); + int modIndex = ui->modList->indexAt(pos).data(ModList::IndexRole).toInt(); - if (m_ContextRow == -1) { + int contextColumn = contextIdx.column(); + + if (modIndex == -1) { // no selection QMenu menu(this); initModListContextMenu(&menu); @@ -4338,61 +4331,64 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) menu.addSeparator(); - ModInfo::Ptr info = ModInfo::getByIndex(m_ContextRow); + ModInfo::Ptr info = ModInfo::getByIndex(modIndex); std::vector flags = info->getFlags(); + // Context menu for overwrites if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) { if (QDir(info->absolutePath()).count() > 2) { menu.addAction(tr("Sync to Mods..."), &m_OrganizerCore, SLOT(syncOverwrite())); - menu.addAction(tr("Create Mod..."), this, SLOT(createModFromOverwrite())); - menu.addAction(tr("Move content to Mod..."), this, SLOT(moveOverwriteContentToExistingMod())); - menu.addAction(tr("Clear Overwrite..."), this, SLOT(clearOverwrite())); + menu.addAction(tr("Create Mod..."), [=]() { createModFromOverwrite(); }); + menu.addAction(tr("Move content to Mod..."), [=]() { moveOverwriteContentToExistingMod(); }); + menu.addAction(tr("Clear Overwrite..."), [=]() { clearOverwrite(); }); } - menu.addAction(tr("Open in Explorer"), this, SLOT(openExplorer_clicked())); + menu.addAction(tr("Open in Explorer"), [=]() { openExplorer_clicked(modIndex); }); } + // Context menu for mod backups else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) != flags.end()) { - menu.addAction(tr("Restore Backup"), this, SLOT(restoreBackup_clicked())); - menu.addAction(tr("Remove Backup..."), this, SLOT(removeMod_clicked())); - menu.addSeparator(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_INVALID) != flags.end()) { - menu.addAction(tr("Ignore missing data"), this, SLOT(ignoreMissingData_clicked())); - } - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_ALTERNATE_GAME) != flags.end()) { - menu.addAction(tr("Mark as converted/working"), this, SLOT(markConverted_clicked())); - } - menu.addSeparator(); - if (info->nexusId() > 0) { - menu.addAction(tr("Visit on Nexus"), this, SLOT(visitOnNexus_clicked())); - } + menu.addAction(tr("Restore Backup"), [=]() { restoreBackup_clicked(modIndex); }); + menu.addAction(tr("Remove Backup..."), [=]() { removeMod_clicked(modIndex); }); + menu.addSeparator(); + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_INVALID) != flags.end()) { + menu.addAction(tr("Ignore missing data"), [=]() { ignoreMissingData_clicked(modIndex); }); + } + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_ALTERNATE_GAME) != flags.end()) { + menu.addAction(tr("Mark as converted/working"), [=]() { markConverted_clicked(modIndex); }); + } + menu.addSeparator(); + if (info->nexusId() > 0) { + menu.addAction(tr("Visit on Nexus"), [=]() { visitOnNexus_clicked(modIndex); }); + } - const auto url = info->parseCustomURL(); - if (url.isValid()) { - menu.addAction( - tr("Visit on %1").arg(url.host()), - this, SLOT(visitWebPage_clicked())); - } + const auto url = info->parseCustomURL(); + if (url.isValid()) { + menu.addAction(tr("Visit on %1").arg(url.host()), [=]() { visitWebPage_clicked(modIndex); }); + } - menu.addAction(tr("Open in Explorer"), this, SLOT(openExplorer_clicked())); + menu.addAction(tr("Open in Explorer"), [=]() { openExplorer_clicked(modIndex); }); } + + // separator else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end()){ menu.addSeparator(); QMenu *addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); - populateMenuCategories(addRemoveCategoriesMenu, 0); - connect(addRemoveCategoriesMenu, SIGNAL(aboutToHide()), this, SLOT(addRemoveCategories_MenuHandler())); + populateMenuCategories(modIndex, addRemoveCategoriesMenu, 0); + connect(addRemoveCategoriesMenu, &QMenu::aboutToHide, [=]() { addRemoveCategories_MenuHandler(modIndex, contextIdx); }); addMenuAsPushButton(&menu, addRemoveCategoriesMenu); QMenu *primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); - connect(primaryCategoryMenu, SIGNAL(aboutToShow()), this, SLOT(addPrimaryCategoryCandidates())); + connect(primaryCategoryMenu, &QMenu::aboutToShow, [=]() { addPrimaryCategoryCandidates(modIndex); }); addMenuAsPushButton(&menu, primaryCategoryMenu); menu.addSeparator(); - menu.addAction(tr("Rename Separator..."), this, SLOT(renameMod_clicked())); - menu.addAction(tr("Remove Separator..."), this, SLOT(removeMod_clicked())); + menu.addAction(tr("Rename Separator..."), [=]() { renameMod_clicked(); }); + menu.addAction(tr("Remove Separator..."), [=]() { removeMod_clicked(modIndex); }); menu.addSeparator(); addModSendToContextMenu(&menu); - menu.addAction(tr("Select Color..."), this, SLOT(setColor_clicked())); + menu.addAction(tr("Select Color..."), [=]() { setColor_clicked(modIndex); }); - if(info->color().isValid()) - menu.addAction(tr("Reset Color"), this, SLOT(resetColor_clicked())); + if (info->color().isValid()) { + menu.addAction(tr("Reset Color"), [=]() { resetColor_clicked(modIndex); }); + } menu.addSeparator(); } @@ -4400,70 +4396,70 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) addModSendToContextMenu(&menu); } else { - QMenu *addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); - populateMenuCategories(addRemoveCategoriesMenu, 0); - connect(addRemoveCategoriesMenu, SIGNAL(aboutToHide()), this, SLOT(addRemoveCategories_MenuHandler())); + QMenu* addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); + populateMenuCategories(modIndex, addRemoveCategoriesMenu, 0); + connect(addRemoveCategoriesMenu, &QMenu::aboutToHide, [=]() { addRemoveCategories_MenuHandler(modIndex, contextIdx); }); addMenuAsPushButton(&menu, addRemoveCategoriesMenu); - QMenu *primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); - connect(primaryCategoryMenu, SIGNAL(aboutToShow()), this, SLOT(addPrimaryCategoryCandidates())); + QMenu* primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); + connect(primaryCategoryMenu, &QMenu::aboutToShow, [=]() { addPrimaryCategoryCandidates(modIndex); }); addMenuAsPushButton(&menu, primaryCategoryMenu); menu.addSeparator(); if (info->downgradeAvailable()) { - menu.addAction(tr("Change versioning scheme"), this, SLOT(changeVersioningScheme())); + menu.addAction(tr("Change versioning scheme"), [=]() { changeVersioningScheme(modIndex); }); } if (info->nexusId() > 0) - menu.addAction(tr("Force-check updates"), this, SLOT(checkModUpdates_clicked())); + menu.addAction(tr("Force-check updates"), [=]() { checkModUpdates_clicked(modIndex); }); if (info->updateIgnored()) { - menu.addAction(tr("Un-ignore update"), this, SLOT(unignoreUpdate())); - } else { + menu.addAction(tr("Un-ignore update"), [=]() { unignoreUpdate(modIndex); }); + } + else { if (info->updateAvailable() || info->downgradeAvailable()) { - menu.addAction(tr("Ignore update"), this, SLOT(ignoreUpdate())); + menu.addAction(tr("Ignore update"), [=]() { ignoreUpdate(modIndex); }); } } menu.addSeparator(); - menu.addAction(tr("Enable selected"), this, SLOT(enableSelectedMods_clicked())); - menu.addAction(tr("Disable selected"), this, SLOT(disableSelectedMods_clicked())); + menu.addAction(tr("Enable selected"), [=]() { enableSelectedMods_clicked(); }); + menu.addAction(tr("Disable selected"), [=]() { disableSelectedMods_clicked(); }); menu.addSeparator(); addModSendToContextMenu(&menu); - menu.addAction(tr("Rename Mod..."), this, SLOT(renameMod_clicked())); - menu.addAction(tr("Reinstall Mod"), this, SLOT(reinstallMod_clicked())); - menu.addAction(tr("Remove Mod..."), this, SLOT(removeMod_clicked())); - menu.addAction(tr("Create Backup"), this, SLOT(backupMod_clicked())); + menu.addAction(tr("Rename Mod..."), [=]() { renameMod_clicked(); }); + menu.addAction(tr("Reinstall Mod"), [=]() { reinstallMod_clicked(modIndex); }); + menu.addAction(tr("Remove Mod..."), [=]() { removeMod_clicked(modIndex); }); + menu.addAction(tr("Create Backup"), [=]() { backupMod_clicked(modIndex); }); if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_HIDDEN_FILES) != flags.end()) { - menu.addAction(tr("Restore hidden files"), this, SLOT(restoreHiddenFiles_clicked())); + menu.addAction(tr("Restore hidden files"), [=]() { restoreHiddenFiles_clicked(modIndex); }); } menu.addSeparator(); if (contextColumn == ModList::COL_NOTES) { - menu.addAction(tr("Select Color..."), this, SLOT(setColor_clicked())); - - if (info->color().isValid()) - menu.addAction(tr("Reset Color"), this, SLOT(resetColor_clicked())); - + menu.addAction(tr("Select Color..."), [=]() { setColor_clicked(modIndex); }); + if (info->color().isValid()) { + menu.addAction(tr("Reset Color"), [=]() { resetColor_clicked(modIndex); }); + } menu.addSeparator(); } if (info->nexusId() > 0 && Settings::instance().nexus().endorsementIntegration()) { switch (info->endorsedState()) { case EndorsedState::ENDORSED_TRUE: { - menu.addAction(tr("Un-Endorse"), this, SLOT(unendorse_clicked())); + menu.addAction(tr("Un-Endorse"), [=]() { unendorse_clicked(); }); } break; case EndorsedState::ENDORSED_FALSE: { - menu.addAction(tr("Endorse"), this, SLOT(endorse_clicked())); - menu.addAction(tr("Won't endorse"), this, SLOT(dontendorse_clicked())); + menu.addAction(tr("Endorse"), [=]() { endorse_clicked(); }); + menu.addAction(tr("Won't endorse"), [=]() { dontendorse_clicked(modIndex); }); } break; case EndorsedState::ENDORSED_NEVER: { - menu.addAction(tr("Endorse"), this, SLOT(endorse_clicked())); + menu.addAction(tr("Endorse"), [=]() { endorse_clicked(); }); } break; default: { QAction *action = new QAction(tr("Endorsement state unknown"), &menu); @@ -4476,10 +4472,10 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) if (info->nexusId() > 0 && Settings::instance().nexus().trackedIntegration()) { switch (info->trackedState()) { case TrackedState::TRACKED_FALSE: { - menu.addAction(tr("Start tracking"), this, SLOT(track_clicked())); + menu.addAction(tr("Start tracking"), [=]() { track_clicked(); }); } break; case TrackedState::TRACKED_TRUE: { - menu.addAction(tr("Stop tracking"), this, SLOT(untrack_clicked())); + menu.addAction(tr("Stop tracking"), [=]() { untrack_clicked(); }); } break; default: { QAction *action = new QAction(tr("Tracked state unknown"), &menu); @@ -4493,31 +4489,29 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) std::vector flags = info->getFlags(); if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_INVALID) != flags.end()) { - menu.addAction(tr("Ignore missing data"), this, SLOT(ignoreMissingData_clicked())); + menu.addAction(tr("Ignore missing data"), [=]() { ignoreMissingData_clicked(modIndex); }); } if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_ALTERNATE_GAME) != flags.end()) { - menu.addAction(tr("Mark as converted/working"), this, SLOT(markConverted_clicked())); + menu.addAction(tr("Mark as converted/working"), [=]() { markConverted_clicked(modIndex); }); } menu.addSeparator(); if (info->nexusId() > 0) { - menu.addAction(tr("Visit on Nexus"), this, SLOT(visitOnNexus_clicked())); + menu.addAction(tr("Visit on Nexus"), [=]() { visitOnNexus_clicked(modIndex); }); } const auto url = info->parseCustomURL(); if (url.isValid()) { - menu.addAction( - tr("Visit on %1").arg(url.host()), - this, SLOT(visitWebPage_clicked())); + menu.addAction(tr("Visit on %1").arg(url.host()), [=]() { visitWebPage_clicked(modIndex); }); } - menu.addAction(tr("Open in Explorer"), this, SLOT(openExplorer_clicked())); + menu.addAction(tr("Open in Explorer"), [&, modIndex]() { openExplorer_clicked(modIndex); }); } if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) == flags.end()) { - QAction *infoAction = menu.addAction(tr("Information..."), this, SLOT(information_clicked())); + QAction* infoAction = menu.addAction(tr("Information..."), [=]() { information_clicked(modIndex); }); menu.setDefaultAction(infoAction); } @@ -5358,11 +5352,10 @@ bool MainWindow::extractProgress(QProgressDialog &progress, int percentage, std: } -void MainWindow::extractBSATriggered() +void MainWindow::extractBSATriggered(QTreeWidgetItem* item) { using namespace boost::placeholders; - QTreeWidgetItem *item = m_ContextItem; QString origin; QString targetFolder = FileDialogMemory::getExistingDirectory("extractBSA", this, tr("Extract BSA")); @@ -5401,14 +5394,11 @@ void MainWindow::extractBSATriggered() } } -void MainWindow::on_bsaList_customContextMenuRequested(const QPoint &pos) +void MainWindow::on_bsaList_customContextMenuRequested(const QPoint& pos) { - m_ContextItem = ui->bsaList->itemAt(pos); - -// m_ContextRow = ui->bsaList->indexOfTopLevelItem(ui->bsaList->itemAt(pos)); - QMenu menu; - menu.addAction(tr("Extract..."), this, SLOT(extractBSATriggered())); + menu.addAction(tr("Extract..."), + [=, item = ui->bsaList->itemAt(pos)]() { extractBSATriggered(item); }); menu.exec(ui->bsaList->viewport()->mapToGlobal(pos)); } @@ -5517,12 +5507,12 @@ void MainWindow::onFiltersOptions( ui->modList->setFilterOptions(mode, sep); } -void MainWindow::updateESPLock(bool locked) +void MainWindow::updateESPLock(int espIndex, bool locked) { QItemSelection currentSelection = ui->espList->selectionModel()->selection(); if (currentSelection.count() == 0) { // this path is probably useless - m_OrganizerCore.pluginList()->lockESPIndex(m_ContextRow, locked); + m_OrganizerCore.pluginList()->lockESPIndex(espIndex, locked); } else { Q_FOREACH (const QModelIndex &idx, currentSelection.indexes()) { if (m_OrganizerCore.pluginList()->isEnabled(mapToModel(m_OrganizerCore.pluginList(), idx).row())) { @@ -5532,21 +5522,9 @@ void MainWindow::updateESPLock(bool locked) } } - -void MainWindow::lockESPIndex() -{ - updateESPLock(true); -} - -void MainWindow::unlockESPIndex() -{ - updateESPLock(false); -} - - -void MainWindow::removeFromToolbar() +void MainWindow::removeFromToolbar(QAction* action) { - const auto& title = m_ContextAction->text(); + const auto& title = action->text(); auto& list = *m_OrganizerCore.executablesList(); auto itor = list.find(title); @@ -5566,9 +5544,10 @@ void MainWindow::toolBar_customContextMenuRequested(const QPoint &point) if (action != nullptr) { if (action->objectName().startsWith("custom_")) { - m_ContextAction = action; QMenu menu; - menu.addAction(tr("Remove '%1' from the toolbar").arg(action->text()), this, SLOT(removeFromToolbar())); + menu.addAction( + tr("Remove '%1' from the toolbar").arg(action->text()), + [&, action]() { removeFromToolbar(action); }); menu.exec(ui->toolBar->mapToGlobal(point)); return; } @@ -5581,16 +5560,17 @@ void MainWindow::toolBar_customContextMenuRequested(const QPoint &point) void MainWindow::on_espList_customContextMenuRequested(const QPoint &pos) { - m_ContextRow = m_PluginListSortProxy->mapToSource(ui->espList->indexAt(pos)).row(); + + int espIndex = m_PluginListSortProxy->mapToSource(ui->espList->indexAt(pos)).row(); QMenu menu; - menu.addAction(tr("Enable selected"), this, SLOT(enableSelectedPlugins_clicked())); - menu.addAction(tr("Disable selected"), this, SLOT(disableSelectedPlugins_clicked())); + menu.addAction(tr("Enable selected"), [=]() { enableSelectedPlugins_clicked(); }); + menu.addAction(tr("Disable selected"), [=]() { disableSelectedPlugins_clicked(); }); menu.addSeparator(); - menu.addAction(tr("Enable all"), m_OrganizerCore.pluginList(), SLOT(enableAll())); - menu.addAction(tr("Disable all"), m_OrganizerCore.pluginList(), SLOT(disableAll())); + menu.addAction(tr("Enable all"), m_OrganizerCore.pluginList(), &PluginList::enableAll); + menu.addAction(tr("Disable all"), m_OrganizerCore.pluginList(), &PluginList::disableAll); menu.addSeparator(); @@ -5611,10 +5591,10 @@ void MainWindow::on_espList_customContextMenuRequested(const QPoint &pos) } if (hasLocked) { - menu.addAction(tr("Unlock load order"), this, SLOT(unlockESPIndex())); + menu.addAction(tr("Unlock load order"), [&, espIndex]() { updateESPLock(espIndex, false); }); } if (hasUnlocked) { - menu.addAction(tr("Lock load order"), this, SLOT(lockESPIndex())); + menu.addAction(tr("Lock load order"), [&, espIndex]() { updateESPLock(espIndex, true); }); } menu.addSeparator(); @@ -5624,12 +5604,12 @@ void MainWindow::on_espList_customContextMenuRequested(const QPoint &pos) unsigned int modInfoIndex = ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(idx.data().toString())); //this is to avoid showing the option on game files like skyrim.esm if (modInfoIndex != UINT_MAX) { - menu.addAction(tr("Open Origin in Explorer"), this, SLOT(openPluginOriginExplorer_clicked())); + menu.addAction(tr("Open Origin in Explorer"), [=]() { openPluginOriginExplorer_clicked(); }); ModInfo::Ptr modInfo = ModInfo::getByIndex(modInfoIndex); std::vector flags = modInfo->getFlags(); if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) == flags.end()) { - QAction *infoAction = menu.addAction(tr("Open Origin Info..."), this, SLOT(openOriginInformation_clicked())); + QAction* infoAction = menu.addAction(tr("Open Origin Info..."), [=]() { openOriginInformation_clicked(); }); menu.setDefaultAction(infoAction); } } @@ -5949,14 +5929,18 @@ void MainWindow::on_clearFiltersButton_clicked() void MainWindow::sendSelectedModsToPriority(int newPriority) { QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { + if (selection->hasSelection()) { std::vector modsToMove; for (auto idx : selection->selectedRows(ModList::COL_PRIORITY)) { modsToMove.push_back(m_OrganizerCore.currentProfile()->modIndexByPriority(idx.data().toInt())); } - m_OrganizerCore.modList()->changeModPriority(modsToMove, newPriority); - } else { - m_OrganizerCore.modList()->changeModPriority(m_ContextRow, newPriority); + + if (modsToMove.size() == 1) { + m_OrganizerCore.modList()->changeModPriority(modsToMove[0], newPriority); + } + else { + m_OrganizerCore.modList()->changeModPriority(modsToMove, newPriority); + } } } @@ -6017,17 +6001,20 @@ void MainWindow::sendSelectedModsToSeparator_clicked() } QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { + if (selection->hasSelection()) { std::vector modsToMove; for (QModelIndex idx : selection->selectedRows(ModList::COL_PRIORITY)) { modsToMove.push_back(m_OrganizerCore.currentProfile()->modIndexByPriority(idx.data().toInt())); } - m_OrganizerCore.modList()->changeModPriority(modsToMove, newPriority); - } else { - int oldPriority = m_OrganizerCore.currentProfile()->getModPriority(m_ContextRow); - if (oldPriority < newPriority) - --newPriority; - m_OrganizerCore.modList()->changeModPriority(m_ContextRow, newPriority); + if (modsToMove.size() == 1) { + int oldPriority = m_OrganizerCore.currentProfile()->getModPriority(modsToMove[0]); + if (oldPriority < newPriority) + --newPriority; + m_OrganizerCore.modList()->changeModPriority(modsToMove[0], newPriority); + } + else { + m_OrganizerCore.modList()->changeModPriority(modsToMove, newPriority); + } } } } diff --git a/src/mainwindow.h b/src/mainwindow.h index dbd44688..26355153 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -144,8 +144,8 @@ public: virtual MOBase::DelayedFileWriterBase &archivesWriter() override { return m_ArchiveListWriter; } - ModInfo::Ptr nextModInList(); - ModInfo::Ptr previousModInList(); + ModInfo::Ptr nextModInList(int modIndex); + ModInfo::Ptr previousModInList(int modIndex); public slots: void onModPrioritiesChanged(std::vector const& indices); @@ -232,7 +232,7 @@ private: */ void replaceCategoriesFromMenu(QMenu *menu, int modRow); - bool populateMenuCategories(QMenu *menu, int targetID); + bool populateMenuCategories(int modIndex, QMenu *menu, int targetID); // remove invalid category-references from mods void fixCategories(); @@ -246,7 +246,7 @@ private: bool errorReported(QString &logFile); - void updateESPLock(bool locked); + void updateESPLock(int espIndex, bool locked); static void setupNetworkProxy(bool activate); void activateProxy(bool activate); @@ -301,9 +301,6 @@ private: int m_OldExecutableIndex; - int m_ContextRow; - QPersistentModelIndex m_ContextIdx; - QTreeWidgetItem *m_ContextItem; QAction *m_ContextAction; CategoryFactory &m_CategoryFactory; @@ -356,7 +353,7 @@ private slots: void wikiTriggered(); void discordTriggered(); void tutorialTriggered(); - void extractBSATriggered(); + void extractBSATriggered(QTreeWidgetItem* item); //modlist shortcuts void openExplorer_activated(); @@ -364,30 +361,30 @@ private slots: // modlist context menu void installMod_clicked(); - void createEmptyMod_clicked(); - void createSeparator_clicked(); - void restoreBackup_clicked(); + void createEmptyMod_clicked(int modIndex); + void createSeparator_clicked(int modIndex); + void restoreBackup_clicked(int modIndex); void renameMod_clicked(); - void removeMod_clicked(); - void setColor_clicked(); - void resetColor_clicked(); - void backupMod_clicked(); - void reinstallMod_clicked(); + void removeMod_clicked(int modIndex); + void setColor_clicked(int modIndex); + void resetColor_clicked(int modIndex); + void backupMod_clicked(int modIndex); + void reinstallMod_clicked(int modIndex); void endorse_clicked(); - void dontendorse_clicked(); + void dontendorse_clicked(int modIndex); void unendorse_clicked(); void track_clicked(); void untrack_clicked(); - void ignoreMissingData_clicked(); - void markConverted_clicked(); - void restoreHiddenFiles_clicked(); - void visitOnNexus_clicked(); - void visitWebPage_clicked(); - void visitNexusOrWebPage_clicked(); - void openExplorer_clicked(); + void ignoreMissingData_clicked(int modIndex); + void markConverted_clicked(int modIndex); + void restoreHiddenFiles_clicked(int modIndex); + void visitOnNexus_clicked(int modIndex); + void visitWebPage_clicked(int modIndex); + void visitNexusOrWebPage_clicked(int modIndex); + void openExplorer_clicked(int modIndex); void openPluginOriginExplorer_clicked(); void openOriginInformation_clicked(); - void information_clicked(); + void information_clicked(int modIndex); void enableSelectedMods_clicked(); void disableSelectedMods_clicked(); void sendSelectedModsToTop_clicked(); @@ -438,10 +435,10 @@ private slots: void originModified(int originID); - void addRemoveCategories_MenuHandler(); - void replaceCategories_MenuHandler(); + void addRemoveCategories_MenuHandler(int modIndex, const QModelIndex& rowIdx); + void replaceCategories_MenuHandler(int modIndex); - void addPrimaryCategoryCandidates(); + void addPrimaryCategoryCandidates(int modIndex); void modInstalled(const QString &modName); @@ -480,9 +477,6 @@ private slots: void trackMod(ModInfo::Ptr mod, bool doTrack); void cancelModListEditor(); - void lockESPIndex(); - void unlockESPIndex(); - void enableVisibleMods(); void disableVisibleMods(); void exportModListCSV(); @@ -527,13 +521,13 @@ private slots: void allowListResize(); void toolBar_customContextMenuRequested(const QPoint &point); - void removeFromToolbar(); + void removeFromToolbar(QAction* action); void overwriteClosed(int); - void changeVersioningScheme(); - void checkModUpdates_clicked(); - void ignoreUpdate(); - void unignoreUpdate(); + void changeVersioningScheme(int modIndex); + void checkModUpdates_clicked(int modIndex); + void ignoreUpdate(int modIndex); + void unignoreUpdate(int modIndex); void about(); @@ -571,7 +565,6 @@ private slots: // ui slots void on_executablesListBox_currentIndexChanged(int index); void on_modList_customContextMenuRequested(const QPoint &pos); void on_modList_doubleClicked(const QModelIndex &index); - void on_listOptionsBtn_pressed(); void on_espList_doubleClicked(const QModelIndex &index); void on_profileBox_currentIndexChanged(int index); void on_startButton_clicked(); diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index cc50d446..cb282195 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -776,7 +776,7 @@ void ModInfoDialog::onTabMoved() void ModInfoDialog::onNextMod() { - auto mod = m_mainWindow->nextModInList(); + auto mod = m_mainWindow->nextModInList(ModInfo::getIndex(m_mod->name())); if (!mod || mod == m_mod) { return; } @@ -787,7 +787,7 @@ void ModInfoDialog::onNextMod() void ModInfoDialog::onPreviousMod() { - auto mod = m_mainWindow->previousModInList(); + auto mod = m_mainWindow->previousModInList(ModInfo::getIndex(m_mod->name())); if (!mod || mod == m_mod) { return; } diff --git a/src/modlistview.h b/src/modlistview.h index 7e6b29bb..3520bfc4 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -56,25 +56,6 @@ public: int nextMod(int index) const; int prevMod(int index) const; - // invalidate the top-level model - // - void invalidate(); - - // enable/disable all visible mods - // - void enableAllVisible(); - void disableAllVisible(); - - // enable/disable all selected mods - // - void enableSelected(); - void disableSelected(); - - // set the filter criteria/options for mods - // - void setFilterCriteria(const std::vector& criteria); - void setFilterOptions(ModListSortProxy::FilterMode mode, ModListSortProxy::SeparatorsMode sep); - // check if the given mod is visible // bool isModVisible(unsigned int index) const; @@ -96,6 +77,27 @@ signals: public slots: + // invalidate the top-level model + // + void invalidate(); + + // enable/disable all visible mods + // + void enableAllVisible(); + void disableAllVisible(); + + // enable/disable all selected mods + // + void enableSelected(); + void disableSelected(); + + // set the filter criteria/options for mods + // + void setFilterCriteria(const std::vector& criteria); + void setFilterOptions(ModListSortProxy::FilterMode mode, ModListSortProxy::SeparatorsMode sep); + + // update the mod counter + // void updateModCount(); protected: -- cgit v1.3.1 From 095348c16f58d757f2d9549d06fd12d5ed14a1d2 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Tue, 29 Dec 2020 21:40:22 +0100 Subject: Add option to disable collapsible separators. --- src/mainwindow.cpp | 2 +- src/modlistview.cpp | 7 +++++-- src/modlistview.h | 5 ++--- src/settings.cpp | 10 ++++++++++ src/settings.h | 5 +++++ src/settingsdialog.ui | 37 +++++++++++++++++++++++++++++++++++++ src/settingsdialoggeneral.cpp | 2 ++ 7 files changed, 62 insertions(+), 6 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index e54c24e1..63c9a8be 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -692,7 +692,6 @@ void MainWindow::allowListResize() void MainWindow::updateStyle(const QString&) { resetActionIcons(); - ui->modList->refreshStyle(); } void MainWindow::resizeEvent(QResizeEvent *event) @@ -4619,6 +4618,7 @@ void MainWindow::on_actionSettings_triggered() fixCategories(); refreshFilters(); + ui->modList->refresh(); if (settings.paths().profiles() != oldProfilesDirectory) { refreshProfiles(); diff --git a/src/modlistview.cpp b/src/modlistview.cpp index 643b1971..dbd09884 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -76,8 +76,10 @@ ModListView::ModListView(QWidget* parent) setItemDelegate(new ModListStyledItemDelegated(this)); } -void ModListView::refreshStyle() +void ModListView::refresh() { + updateGroupByProxy(-1); + // maybe there is a better way but I did not find one QString sheet = styleSheet(); setStyleSheet("QTreeView { }"); @@ -496,7 +498,8 @@ void ModListView::updateGroupByProxy(int groupIndex) m_byNexusIdProxy->setGroupedColumn(ModList::COL_MODID); m_sortProxy->setSourceModel(m_byNexusIdProxy); } - else if (m_sortProxy->sortColumn() == ModList::COL_PRIORITY + else if (m_core->settings().interface().collapsibleSeparators() + && m_sortProxy->sortColumn() == ModList::COL_PRIORITY && m_sortProxy->sortOrder() == Qt::AscendingOrder) { m_sortProxy->setSourceModel(m_byPriorityProxy); m_byPriorityProxy->refresh(); diff --git a/src/modlistview.h b/src/modlistview.h index 3520bfc4..2ea5891c 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -65,10 +65,9 @@ public: // QRect visualRect(const QModelIndex& index) const override; - // refresh the style of the mod list, this needs to be called when the - // stylesheet is changed + // refresh the view (to call when settings have been changed) // - void refreshStyle(); + void refresh(); signals: diff --git a/src/settings.cpp b/src/settings.cpp index 04cfafc9..b6961807 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -2162,6 +2162,16 @@ void InterfaceSettings::setStyleName(const QString& name) set(m_Settings, "Settings", "style", name); } +bool InterfaceSettings::collapsibleSeparators() const +{ + return get(m_Settings, "Settings", "collapsible_separators", true); +} + +void InterfaceSettings::setCollapsibleSeparators(bool b) +{ + set(m_Settings, "Settings", "collapsible_separators", b); +} + bool InterfaceSettings::compactDownloads() const { return get(m_Settings, "Settings", "compact_downloads", false); diff --git a/src/settings.h b/src/settings.h index 3f60fc7b..5506bbf8 100644 --- a/src/settings.h +++ b/src/settings.h @@ -617,6 +617,11 @@ public: std::optional styleName() const; void setStyleName(const QString& name); + // whether to use collapsible separators when possible + // + bool collapsibleSeparators() const; + void setCollapsibleSeparators(bool b); + // whether to show compact downloads // bool compactDownloads() const; diff --git a/src/settingsdialog.ui b/src/settingsdialog.ui index 43af5e9f..6d62228d 100644 --- a/src/settingsdialog.ui +++ b/src/settingsdialog.ui @@ -338,6 +338,43 @@ + + + + + 0 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Use collapsible separators + + + true + + + false + + + + + + diff --git a/src/settingsdialoggeneral.cpp b/src/settingsdialoggeneral.cpp index f29e1d24..47388c96 100644 --- a/src/settingsdialoggeneral.cpp +++ b/src/settingsdialoggeneral.cpp @@ -27,6 +27,7 @@ GeneralSettingsTab::GeneralSettingsTab(Settings& s, SettingsDialog& d) ui->checkForUpdates->setChecked(settings().checkForUpdates()); ui->usePrereleaseBox->setChecked(settings().usePrereleases()); ui->colorSeparatorsBox->setChecked(settings().colors().colorSeparatorScrollbar()); + ui->collapsibleSeparatorsBox->setChecked(settings().interface().collapsibleSeparators()); QObject::connect(ui->exploreStyles, &QPushButton::clicked, [&]{ onExploreStyles(); }); @@ -70,6 +71,7 @@ void GeneralSettingsTab::update() settings().setCheckForUpdates(ui->checkForUpdates->isChecked()); settings().setUsePrereleases(ui->usePrereleaseBox->isChecked()); settings().colors().setColorSeparatorScrollbar(ui->colorSeparatorsBox->isChecked()); + settings().interface().setCollapsibleSeparators(ui->collapsibleSeparatorsBox->isChecked()); } void GeneralSettingsTab::addLanguages() -- cgit v1.3.1 From 373b659dcbcac5dfc081ca7fa5f78788166a4e39 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Wed, 30 Dec 2020 00:28:48 +0100 Subject: Fix and move stuff around. - Move selection-related code from ModList to ModListView. - Fix move-selection for multi-selection. - Fix refresh of mod list on toggle selection. --- src/mainwindow.cpp | 52 +-------------- src/mainwindow.h | 1 - src/modlist.cpp | 112 +++++++------------------------ src/modlist.h | 19 +----- src/modlistbypriorityproxy.cpp | 17 +++++ src/modlistbypriorityproxy.h | 4 ++ src/modlistsortproxy.cpp | 7 -- src/modlistsortproxy.h | 2 - src/modlistview.cpp | 145 +++++++++++++++++++++++++++++++++++++---- src/modlistview.h | 11 ++++ src/organizercore.cpp | 2 - 11 files changed, 195 insertions(+), 177 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 63c9a8be..519799d2 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -540,9 +540,12 @@ void MainWindow::setupModList() { ui->modList->setup(m_OrganizerCore, ui); + connect(ui->modList, &ModListView::removeSelectedMods, [=]() { removeMod_clicked(-1); }); + // keep here for now connect(ui->modList->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::modlistSelectionsChanged); + connect(m_OrganizerCore.modList(), &ModList::modPrioritiesChanged, [&]() { m_ArchiveListWriter.write(); }); } void MainWindow::resetActionIcons() @@ -2280,54 +2283,6 @@ void MainWindow::esplist_changed() updatePluginCount(); } -void MainWindow::onModPrioritiesChanged(std::vector const& indices) -{ - for (unsigned int i = 0; i < m_OrganizerCore.currentProfile()->numMods(); ++i) { - int priority = m_OrganizerCore.currentProfile()->getModPriority(i); - if (m_OrganizerCore.currentProfile()->modEnabled(i)) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(i); - // priorities in the directory structure are one higher because data is 0 - m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(modInfo->internalName())).setPriority(priority + 1); - } - } - m_OrganizerCore.refreshBSAList(); - m_OrganizerCore.currentProfile()->writeModlist(); - m_ArchiveListWriter.write(); - m_OrganizerCore.directoryStructure()->getFileRegister()->sortOrigins(); - - { // refresh selection - QModelIndex current = ui->modList->currentIndex(); - if (current.isValid()) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(current.data(ModList::IndexRole).toInt()); - // clear caches on all mods conflicting with the moved mod - for (int i : modInfo->getModOverwrite()) { - ModInfo::getByIndex(i)->clearCaches(); - } - for (int i : modInfo->getModOverwritten()) { - ModInfo::getByIndex(i)->clearCaches(); - } - for (int i : modInfo->getModArchiveOverwrite()) { - ModInfo::getByIndex(i)->clearCaches(); - } - for (int i : modInfo->getModArchiveOverwritten()) { - ModInfo::getByIndex(i)->clearCaches(); - } - for (int i : modInfo->getModArchiveLooseOverwrite()) { - ModInfo::getByIndex(i)->clearCaches(); - } - for (int i : modInfo->getModArchiveLooseOverwritten()) { - ModInfo::getByIndex(i)->clearCaches(); - } - // update conflict check on the moved mod - modInfo->doConflictCheck(); - m_OrganizerCore.modList()->setOverwriteMarkers(modInfo->getModOverwrite(), modInfo->getModOverwritten()); - m_OrganizerCore.modList()->setArchiveOverwriteMarkers(modInfo->getModArchiveOverwrite(), modInfo->getModArchiveOverwritten()); - m_OrganizerCore.modList()->setArchiveLooseOverwriteMarkers(modInfo->getModArchiveLooseOverwrite(), modInfo->getModArchiveLooseOverwritten()); - ui->modList->verticalScrollBar()->repaint(); - } - } -} - void MainWindow::modInstalled(const QString &modName) { unsigned int index = ModInfo::getIndex(modName); @@ -2529,7 +2484,6 @@ void MainWindow::removeMod_clicked(int modIndex) } } - void MainWindow::modRemoved(const QString &fileName) { if (!fileName.isEmpty() && !QFileInfo(fileName).isAbsolute()) { diff --git a/src/mainwindow.h b/src/mainwindow.h index 26355153..97bca68b 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -148,7 +148,6 @@ public: ModInfo::Ptr previousModInList(int modIndex); public slots: - void onModPrioritiesChanged(std::vector const& indices); void esplist_changed(); void refresherProgress(const DirectoryRefreshProgress* p); diff --git a/src/modlist.cpp b/src/modlist.cpp index 1f2f1171..a192390d 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -1510,100 +1510,58 @@ QModelIndex ModList::indexToProxy(QAbstractItemModel* proxyModel, const QModelIn return QModelIndex(); } -bool ModList::moveSelection(QAbstractItemView *itemView, int direction) +void ModList::moveMods(const QModelIndexList& indices, int offset) { - QItemSelectionModel *selectionModel = itemView->selectionModel(); - int currentIndex = itemView->currentIndex().data(IndexRole).toInt(); - - const QAbstractProxyModel *proxyModel = qobject_cast(selectionModel->model()); - const QSortFilterProxyModel *filterModel = nullptr; - - emit layoutAboutToBeChanged(); - - while ((filterModel == nullptr) && (proxyModel != nullptr)) { - filterModel = qobject_cast(proxyModel); - if (filterModel == nullptr) { - proxyModel = qobject_cast(proxyModel->sourceModel()); - } - } - if (filterModel == nullptr) { - return true; - } - - int offset = -1; - if (((direction < 0) && (filterModel->sortOrder() == Qt::DescendingOrder)) || - ((direction > 0) && (filterModel->sortOrder() == Qt::AscendingOrder))) { - offset = 1; - } - - QModelIndexList rows = selectionModel->selectedRows(); - if (direction > 0) { - for (int i = 0; i < rows.size() / 2; ++i) { - rows.swapItemsAt(i, rows.size() - i - 1); - } - } + // retrieve the mod index and sort them by priority to avoid issue + // when moving them std::vector allIndex; - for (QModelIndex idx : rows) { + for (auto& idx : indices) { auto index = idx.data(IndexRole).toInt(); allIndex.push_back(index); + } + std::sort(allIndex.begin(), allIndex.end(), [=](int lhs, int rhs) { + bool cmp = m_Profile->getModPriority(lhs) < m_Profile->getModPriority(rhs); + return offset > 0 ? !cmp : cmp; + }); + + emit layoutAboutToBeChanged(); + + std::vector notify; + for (auto index : allIndex) { int newPriority = m_Profile->getModPriority(index) + offset; if ((newPriority >= 0) && (newPriority < static_cast(m_Profile->numRegularMods()))) { m_Profile->setModPriority(index, newPriority); - notifyChange(index); + notify.push_back(index); } } emit layoutChanged(); - emit modPrioritiesChanged(allIndex); - - // reset the selection and the index - itemView->setCurrentIndex(indexToProxy(itemView->model(), index(currentIndex, 0))); - for (auto idx : allIndex) { - itemView->selectionModel()->select( - indexToProxy(itemView->selectionModel()->model(), index(idx, 0)), - QItemSelectionModel::Select | QItemSelectionModel::Rows); + for (auto index : notify) { + notifyChange(index); } - return true; -} - -bool ModList::deleteSelection(QAbstractItemView *itemView) -{ - QItemSelectionModel *selectionModel = itemView->selectionModel(); - - QModelIndexList rows = selectionModel->selectedRows(); - if (rows.count() > 1) { - emit removeSelectedMods(); - } else if (rows.count() == 1) { - removeRow(rows[0].data(IndexRole).toInt(), QModelIndex()); - } - return true; + emit modPrioritiesChanged(allIndex); } -bool ModList::toggleSelection(QAbstractItemView *itemView) +bool ModList::toggleState(const QModelIndexList& indices) { emit aboutToChangeData(); - QItemSelectionModel *selectionModel = itemView->selectionModel(); - QList modsToEnable; QList modsToDisable; - QModelIndexList dirtyMods; - for (QModelIndex idx : selectionModel->selectedRows()) { - int modId = idx.data(IndexRole).toInt(); - if (m_Profile->modEnabled(modId)) { - modsToDisable.append(modId); - dirtyMods.append(idx); + for (auto index : indices) { + auto idx = index.data(IndexRole).toInt(); + if (m_Profile->modEnabled(idx)) { + modsToDisable.append(idx); } else { - modsToEnable.append(modId); - dirtyMods.append(idx); + modsToEnable.append(idx); } } m_Profile->setModsEnabled(modsToEnable, modsToDisable); - emit modlistChanged(dirtyMods, 0); + emit modlistChanged(indices, 0); emit tutorialModlistUpdate(); m_Modified = true; @@ -1616,26 +1574,6 @@ bool ModList::toggleSelection(QAbstractItemView *itemView) return true; } -bool ModList::eventFilter(QObject *obj, QEvent *event) -{ - if ((event->type() == QEvent::KeyPress) && (m_Profile != nullptr)) { - QAbstractItemView *itemView = qobject_cast(obj); - QKeyEvent *keyEvent = static_cast(event); - - if ((itemView != nullptr) - && (keyEvent->modifiers() == Qt::ControlModifier) - && ((keyEvent->key() == Qt::Key_Up) || (keyEvent->key() == Qt::Key_Down))) { - return moveSelection(itemView, keyEvent->key() == Qt::Key_Up ? -1 : 1); - } else if (keyEvent->key() == Qt::Key_Delete) { - return deleteSelection(itemView); - } else if (keyEvent->key() == Qt::Key_Space) { - return toggleSelection(itemView); - } - return QAbstractItemModel::eventFilter(obj, event); - } - return QAbstractItemModel::eventFilter(obj, event); -} - //note: caller needs to make sure sort proxy is updated void ModList::enableSelected(const QItemSelectionModel *selectionModel) { diff --git a/src/modlist.h b/src/modlist.h index edf7d53a..778f1fee 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -221,6 +221,9 @@ public slots: void enableSelected(const QItemSelectionModel *selectionModel); void disableSelected(const QItemSelectionModel *selectionModel); + void moveMods(const QModelIndexList& indices, int offset); + bool toggleState(const QModelIndexList& indices); + signals: /** @@ -290,11 +293,6 @@ signals: */ void tutorialModlistUpdate(); - /** - * @brief emitted to have all selected mods deleted - */ - void removeSelectedMods(); - /** * @brief fileMoved emitted when a file is moved from one mod to another * @param relativePath relative path of the file moved @@ -316,11 +314,6 @@ signals: // download list void downloadArchiveDropped(int row, int priority); -protected: - - // event filter, handles event from the header and the tree view itself - bool eventFilter(QObject *obj, QEvent *event); - private: QVariant getOverwriteData(int column, int role) const; @@ -344,12 +337,6 @@ private: MOBase::IModList::ModStates state(unsigned int modIndex) const; - bool moveSelection(QAbstractItemView *itemView, int direction); - - bool deleteSelection(QAbstractItemView *itemView); - - bool toggleSelection(QAbstractItemView *itemView); - private slots: private: diff --git a/src/modlistbypriorityproxy.cpp b/src/modlistbypriorityproxy.cpp index f898b85b..dc16d8ea 100644 --- a/src/modlistbypriorityproxy.cpp +++ b/src/modlistbypriorityproxy.cpp @@ -23,6 +23,7 @@ void ModListByPriorityProxy::setSourceModel(QAbstractItemModel* model) connect(sourceModel(), &QAbstractItemModel::layoutChanged, this, [this]() { buildTree(); }, Qt::UniqueConnection); connect(sourceModel(), &QAbstractItemModel::rowsRemoved, this, [this]() { buildTree(); }, Qt::UniqueConnection); connect(sourceModel(), &QAbstractItemModel::modelReset, this, &ModListByPriorityProxy::buildTree, Qt::UniqueConnection); + connect(sourceModel(), &QAbstractItemModel::dataChanged, this, &ModListByPriorityProxy::modelDataChanged, Qt::UniqueConnection); refresh(); } } @@ -93,6 +94,22 @@ void ModListByPriorityProxy::expandItems(const QModelIndex& index) const } } +void ModListByPriorityProxy::modelDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector& roles) +{ + QModelIndex proxyTopLeft = mapFromSource(topLeft); + if (!proxyTopLeft.isValid()) { + return; + } + + if (topLeft == bottomRight) { + emit dataChanged(proxyTopLeft, proxyTopLeft); + } + else { + QModelIndex proxyBottomRight = mapFromSource(bottomRight); + emit dataChanged(proxyTopLeft, proxyBottomRight); + } +} + QModelIndex ModListByPriorityProxy::mapFromSource(const QModelIndex& sourceIndex) const { if (!sourceIndex.isValid()) { diff --git a/src/modlistbypriorityproxy.h b/src/modlistbypriorityproxy.h index 26f60bc7..00848e2a 100644 --- a/src/modlistbypriorityproxy.h +++ b/src/modlistbypriorityproxy.h @@ -58,6 +58,10 @@ public slots: void expanded(const QModelIndex& index); void collapsed(const QModelIndex& index); +protected: + + void modelDataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector& roles = QVector()); + private: void buildTree(); diff --git a/src/modlistsortproxy.cpp b/src/modlistsortproxy.cpp index a7d0b27a..ed752d7a 100644 --- a/src/modlistsortproxy.cpp +++ b/src/modlistsortproxy.cpp @@ -73,13 +73,6 @@ void ModListSortProxy::setCriteria(const std::vector& criteria) } } -Qt::ItemFlags ModListSortProxy::flags(const QModelIndex &modelIndex) const -{ - Qt::ItemFlags flags = sourceModel()->flags(mapToSource(modelIndex)); - - return flags; -} - unsigned long ModListSortProxy::flagsId(const std::vector &flags) const { unsigned long result = 0; diff --git a/src/modlistsortproxy.h b/src/modlistsortproxy.h index 9a4140f6..fed05188 100644 --- a/src/modlistsortproxy.h +++ b/src/modlistsortproxy.h @@ -77,8 +77,6 @@ public: void setProfile(Profile *profile); - - Qt::ItemFlags flags(const QModelIndex &modelIndex) const override; bool canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) const override; bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override; diff --git a/src/modlistview.cpp b/src/modlistview.cpp index dbd09884..bda7ac4d 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -5,6 +5,8 @@ #include +#include + #include "ui_mainwindow.h" #include "organizercore.h" @@ -15,6 +17,8 @@ #include "modflagicondelegate.h" #include "modconflicticondelegate.h" #include "genericicondelegate.h" +#include "shared/directoryentry.h" +#include "shared/filesorigin.h" class ModListProxyStyle : public QProxyStyle { public: @@ -346,18 +350,63 @@ void ModListView::expandItem(const QModelIndex& index) { void ModListView::onModPrioritiesChanged(std::vector const& indices) { - if (m_sortProxy != nullptr) { // expand separator whose priority has changed - if (hasCollapsibleSeparators()) { - for (auto index : indices) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(index); - if (modInfo->isSeparator()) { - expand(indexModelToView(m_core->modList()->index(index, 0))); - } + if (hasCollapsibleSeparators()) { + for (auto index : indices) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(index); + if (modInfo->isSeparator()) { + expand(indexModelToView(m_core->modList()->index(index, 0))); } } + } + + for (unsigned int i = 0; i < m_core->currentProfile()->numMods(); ++i) { + int priority = m_core->currentProfile()->getModPriority(i); + if (m_core->currentProfile()->modEnabled(i)) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(i); + // priorities in the directory structure are one higher because data is 0 + m_core->directoryStructure()->getOriginByName(MOBase::ToWString(modInfo->internalName())).setPriority(priority + 1); + } + } + m_core->refreshBSAList(); + m_core->currentProfile()->writeModlist(); + m_core->directoryStructure()->getFileRegister()->sortOrigins(); + + if (m_sortProxy) { m_sortProxy->invalidate(); } + + { // refresh selection + QModelIndex current = currentIndex(); + if (current.isValid()) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(current.data(ModList::IndexRole).toInt()); + // clear caches on all mods conflicting with the moved mod + for (int i : modInfo->getModOverwrite()) { + ModInfo::getByIndex(i)->clearCaches(); + } + for (int i : modInfo->getModOverwritten()) { + ModInfo::getByIndex(i)->clearCaches(); + } + for (int i : modInfo->getModArchiveOverwrite()) { + ModInfo::getByIndex(i)->clearCaches(); + } + for (int i : modInfo->getModArchiveOverwritten()) { + ModInfo::getByIndex(i)->clearCaches(); + } + for (int i : modInfo->getModArchiveLooseOverwrite()) { + ModInfo::getByIndex(i)->clearCaches(); + } + for (int i : modInfo->getModArchiveLooseOverwritten()) { + ModInfo::getByIndex(i)->clearCaches(); + } + // update conflict check on the moved mod + modInfo->doConflictCheck(); + m_core->modList()->setOverwriteMarkers(modInfo->getModOverwrite(), modInfo->getModOverwritten()); + m_core->modList()->setArchiveOverwriteMarkers(modInfo->getModArchiveOverwrite(), modInfo->getModArchiveOverwritten()); + m_core->modList()->setArchiveLooseOverwriteMarkers(modInfo->getModArchiveLooseOverwrite(), modInfo->getModArchiveLooseOverwritten()); + verticalScrollBar()->repaint(); + } + } } void ModListView::onModInstalled(const QString& modName) @@ -573,9 +622,6 @@ void ModListView::setup(OrganizerCore& core, Ui::MainWindow* mwui) setItemDelegateForColumn(ModList::COL_CONFLICTFLAGS, conflictFlagDelegate); setItemDelegateForColumn(ModList::COL_CONTENT, contentDelegate); - // TODO: Check if this is really useful. - header()->installEventFilter(m_core->modList()); - if (m_core->settings().geometry().restoreState(header())) { // hack: force the resize-signal to be triggered because restoreState doesn't seem to do that for (int column = 0; column <= ModList::COL_LASTCOLUMN; ++column) { @@ -603,9 +649,6 @@ void ModListView::setup(OrganizerCore& core, Ui::MainWindow* mwui) // prevent the name-column from being hidden header()->setSectionHidden(ModList::COL_NAME, false); - // TODO: Move the event filter in ModListView. - installEventFilter(core.modList()); - connect(m_core->modList(), &ModList::downloadArchiveDropped, this, [this](int row, int priority) { m_core->installDownload(row, priority); }); @@ -684,3 +727,79 @@ void ModListView::timerEvent(QTimerEvent* event) QTreeView::timerEvent(event); } } + +bool ModListView::moveSelection(int key) +{ + QModelIndex cindex = indexViewToModel(currentIndex()); + QModelIndexList sourceRows; + for (auto& index : selectionModel()->selectedRows()) { + sourceRows.append(indexViewToModel(index)); + } + + int offset = key == Qt::Key_Up ? -1 : 1; + if (m_sortProxy->sortOrder() == Qt::DescendingOrder) { + offset = -offset; + } + + m_core->modList()->moveMods(sourceRows, offset); + + // reset the selection and the index + setCurrentIndex(indexModelToView(cindex)); + for (auto idx : sourceRows) { + selectionModel()->select(indexModelToView(idx), QItemSelectionModel::Select | QItemSelectionModel::Rows); + } + + return true; +} + +bool ModListView::removeSelection() +{ + if (selectionModel()->hasSelection()) { + QModelIndexList rows = selectionModel()->selectedRows(); + if (rows.count() > 1) { + emit removeSelectedMods(); + } + else if (rows.count() == 1) { + // this does not work, I don't know why + // model()->removeRow(rows[0].row(), rows[0].parent()); + m_core->modList()->removeRow(indexViewToModel(rows[0]).row()); + } + } + return true; +} + +bool ModListView::toggleSelectionState() +{ + if (!selectionModel()->hasSelection()) { + return true; + } + + QModelIndexList selected; + for (QModelIndex idx : selectionModel()->selectedRows()) { + selected.append(indexViewToModel(idx)); + } + + return m_core->modList()->toggleState(selected); +} + +bool ModListView::event(QEvent* event) +{ + Profile* profile = m_core->currentProfile(); + if (event->type() == QEvent::KeyPress && profile) { + QKeyEvent* keyEvent = static_cast(event); + + if (keyEvent->modifiers() == Qt::ControlModifier + && sortColumn() == ModList::COL_PRIORITY + && (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down)) { + return moveSelection(keyEvent->key()); + } + else if (keyEvent->key() == Qt::Key_Delete) { + return removeSelection(); + } + else if (keyEvent->key() == Qt::Key_Space) { + return toggleSelectionState(); + } + return QTreeView::event(event); + } + return QTreeView::event(event); +} diff --git a/src/modlistview.h b/src/modlistview.h index 2ea5891c..88028428 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -74,6 +74,10 @@ signals: void dragEntered(const QMimeData* mimeData); void dropEntered(const QMimeData* mimeData, DropPosition position); + // emitted when selected mods must be removed + // + void removeSelectedMods(); + public slots: // invalidate the top-level model @@ -121,10 +125,17 @@ protected: // QModelIndexList selectedIndexes() const; + bool moveSelection(int key); + bool removeSelection(); + bool toggleSelectionState(); + void timerEvent(QTimerEvent* event) override; void dragEnterEvent(QDragEnterEvent* event) override; void dragMoveEvent(QDragMoveEvent* event) override; void dropEvent(QDropEvent* event) override; + bool event(QEvent* event) override; + +protected slots: private: diff --git a/src/organizercore.cpp b/src/organizercore.cpp index ecd4b34e..334a02de 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -249,8 +249,6 @@ void OrganizerCore::setUserInterface(IUserInterface* ui) SLOT(modRemoved(QString))); connect(&m_InstallationManager, SIGNAL(modReplaced(QString)), w, SLOT(modRemoved(QString))); - connect(&m_ModList, SIGNAL(removeSelectedMods()), w, - SLOT(removeMod_clicked())); connect(&m_ModList, SIGNAL(clearOverwrite()), w, SLOT(clearOverwrite())); connect(&m_ModList, SIGNAL(fileMoved(QString, QString, QString)), w, -- cgit v1.3.1 From 41467d8e217da31cdd99c6dde76429d97b99cb7a Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Wed, 30 Dec 2020 00:41:24 +0100 Subject: Conditional collapse/expand all item in 'all mods' menu. --- src/mainwindow.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 519799d2..df227aab 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -4207,11 +4207,13 @@ void MainWindow::initModListContextMenu(QMenu *menu) { menu->addAction(tr("Install Mod..."), [&]() { installMod_clicked(); }); menu->addAction(tr("Create empty mod"), [&]() { createEmptyMod_clicked(-1); }); - - menu->addSeparator(); menu->addAction(tr("Create Separator"), [&]() { createSeparator_clicked(-1); }); - menu->addAction(tr("Collapse all"), ui->modList, &QTreeView::collapseAll); - menu->addAction(tr("Expand all"), ui->modList, &QTreeView::expandAll); + + if (ui->modList->hasCollapsibleSeparators()) { + menu->addSeparator(); + menu->addAction(tr("Collapse all"), ui->modList, &QTreeView::collapseAll); + menu->addAction(tr("Expand all"), ui->modList, &QTreeView::expandAll); + } menu->addSeparator(); -- cgit v1.3.1 From 8eb59316f9140a621bc4cf0d06d7b5b898b50972 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Wed, 30 Dec 2020 14:39:57 +0100 Subject: Do not invalidate the sort proxy when not required (keep selection). --- src/mainwindow.cpp | 22 +++++++----- src/modlist.cpp | 31 ++++++---------- src/modlist.h | 13 +++++-- src/modlistsortproxy.cpp | 6 ++-- src/modlistview.cpp | 92 ++++++++++++++++++------------------------------ src/modlistview.h | 8 ++--- 6 files changed, 73 insertions(+), 99 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index df227aab..e01f984a 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -3833,15 +3833,17 @@ void MainWindow::ignoreUpdate(int modIndex) QItemSelectionModel *selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); + auto index = idx.data(ModList::IndexRole).toInt(); + ModInfo::Ptr info = ModInfo::getByIndex(index); info->ignoreUpdate(true); + m_OrganizerCore.modList()->notifyChange(index); } } else { ModInfo::Ptr info = ModInfo::getByIndex(modIndex); info->ignoreUpdate(true); + m_OrganizerCore.modList()->notifyChange(modIndex); } - ui->modList->invalidate(); } void MainWindow::checkModUpdates_clicked(int modIndex) @@ -3867,13 +3869,14 @@ void MainWindow::unignoreUpdate(int modIndex) for (QModelIndex idx : selection->selectedRows()) { ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); info->ignoreUpdate(false); + m_OrganizerCore.modList()->notifyChange(idx.data(ModList::IndexRole).toInt()); } } else { ModInfo::Ptr info = ModInfo::getByIndex(modIndex); info->ignoreUpdate(false); + m_OrganizerCore.modList()->notifyChange(modIndex); } - ui->modList->invalidate(); } void MainWindow::addPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, @@ -4970,7 +4973,6 @@ void MainWindow::nxmUpdateInfoAvailable(QString gameName, QVariant userData, QVa return std::make_pair(gameNameReal, ModInfo::filteredMods(gameNameReal, resultList, userData.toBool(), true)); }); watcher->setFuture(future); - ui->modList->invalidate(); } void MainWindow::finishUpdateInfo() @@ -4989,6 +4991,7 @@ void MainWindow::finishUpdateInfo() if (mod->canBeUpdated()) { organizedGames.insert(std::make_pair(mod->gameName().toLower(), mod->nexusId())); } + m_OrganizerCore.modList()->notifyChange(ModInfo::getIndex(mod->name())); } if (!finalMods.empty() && organizedGames.empty()) @@ -5073,7 +5076,7 @@ void MainWindow::nxmUpdatesAvailable(QString gameName, int modID, QVariant userD if (foundUpdate) { // Just get the standard data updates for endorsements and descriptions mod->setLastNexusUpdate(QDateTime::currentDateTimeUtc()); - ui->modList->invalidate(); + m_OrganizerCore.modList()->notifyChange(ModInfo::getIndex(mod->name())); } else { // Scrape mod data here so we can use the mod version if no file update was located requiresInfo = true; @@ -5087,7 +5090,6 @@ void MainWindow::nxmUpdatesAvailable(QString gameName, int modID, QVariant userD void MainWindow::nxmModInfoAvailable(QString gameName, int modID, QVariant userData, QVariant resultData, int requestID) { QVariantMap result = resultData.toMap(); - bool foundUpdate = false; QString gameNameReal; for (IPluginGame *game : m_PluginContainer.plugins()) { if (game->gameNexusName() == gameName) { @@ -5097,6 +5099,7 @@ void MainWindow::nxmModInfoAvailable(QString gameName, int modID, QVariant userD } std::vector modsList = ModInfo::getByModID(gameNameReal, modID); for (auto mod : modsList) { + bool foundUpdate = false; QDateTime now = QDateTime::currentDateTimeUtc(); QDateTime updateTarget = mod->getExpires(); if (now >= updateTarget) { @@ -5123,9 +5126,10 @@ void MainWindow::nxmModInfoAvailable(QString gameName, int modID, QVariant userD mod->setLastNexusQuery(QDateTime::currentDateTimeUtc()); mod->setNexusLastModified(QDateTime::fromSecsSinceEpoch(result["updated_timestamp"].toInt(), Qt::UTC)); mod->saveMeta(); - } - if (foundUpdate) { - ui->modList->invalidate(); + + if (foundUpdate) { + m_OrganizerCore.modList()->notifyChange(ModInfo::getIndex(mod->name())); + } } } diff --git a/src/modlist.cpp b/src/modlist.cpp index a192390d..608a26b4 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -1510,7 +1510,7 @@ QModelIndex ModList::indexToProxy(QAbstractItemModel* proxyModel, const QModelIn return QModelIndex(); } -void ModList::moveMods(const QModelIndexList& indices, int offset) +void ModList::shiftMods(const QModelIndexList& indices, int offset) { // retrieve the mod index and sort them by priority to avoid issue // when moving them @@ -1574,28 +1574,17 @@ bool ModList::toggleState(const QModelIndexList& indices) return true; } -//note: caller needs to make sure sort proxy is updated -void ModList::enableSelected(const QItemSelectionModel *selectionModel) +void ModList::setActive(const QModelIndexList& indices, bool active) { - if (selectionModel->hasSelection()) { - QList modsToEnable; - for (auto row : selectionModel->selectedRows(COL_PRIORITY)) { - int modID = m_Profile->modIndexByPriority(row.data().toInt()); - modsToEnable.append(modID); - } - m_Profile->setModsEnabled(modsToEnable, QList()); + QList mods; + for (auto& index : indices) { + mods.append(index.data(IndexRole).toInt()); } -} -//note: caller needs to make sure sort proxy is updated -void ModList::disableSelected(const QItemSelectionModel *selectionModel) -{ - if (selectionModel->hasSelection()) { - QList modsToDisable; - for (auto row : selectionModel->selectedRows(COL_PRIORITY)) { - int modID = m_Profile->modIndexByPriority(row.data().toInt()); - modsToDisable.append(modID); - } - m_Profile->setModsEnabled(QList(), modsToDisable); + if (active) { + m_Profile->setModsEnabled(mods, {}); + } + else { + m_Profile->setModsEnabled({}, mods); } } diff --git a/src/modlist.h b/src/modlist.h index 778f1fee..913d2ea8 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -218,10 +218,17 @@ public: // implementation of virtual functions of QAbstractItemModel public slots: void onDragEnter(const QMimeData* data); - void enableSelected(const QItemSelectionModel *selectionModel); - void disableSelected(const QItemSelectionModel *selectionModel); - void moveMods(const QModelIndexList& indices, int offset); + // enable/disable mods at the given indices. + // + void setActive(const QModelIndexList& indices, bool active); + + // shift the priority of mods at the given indices by the given offset + // + void shiftMods(const QModelIndexList& indices, int offset); + + // toggle the active state of mods at the given indices + // bool toggleState(const QModelIndexList& indices); signals: diff --git a/src/modlistsortproxy.cpp b/src/modlistsortproxy.cpp index ed752d7a..93f97895 100644 --- a/src/modlistsortproxy.cpp +++ b/src/modlistsortproxy.cpp @@ -69,7 +69,7 @@ void ModListSortProxy::setCriteria(const std::vector& criteria) if (changed || isForUpdates) { m_Criteria = criteria; updateFilterActive(); - invalidate(); + invalidateFilter(); } } @@ -236,7 +236,7 @@ void ModListSortProxy::updateFilter(const QString& filter) { m_Filter = filter; updateFilterActive(); - invalidate(); + invalidateFilter(); } bool ModListSortProxy::hasConflictFlag(const std::vector &flags) const @@ -555,7 +555,7 @@ void ModListSortProxy::setOptions( if (m_FilterMode != mode || separators != m_FilterSeparators) { m_FilterMode = mode; m_FilterSeparators = separators; - this->invalidate(); + invalidateFilter(); } } diff --git a/src/modlistview.cpp b/src/modlistview.cpp index 74f4b566..c4641934 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -171,64 +171,28 @@ int ModListView::prevMod(int modIndex) const return -1; } -void ModListView::invalidate() -{ - if (m_sortProxy) { - m_sortProxy->invalidate(); - } -} - void ModListView::enableAllVisible() { - Profile* profile = m_core->currentProfile(); - - QList modsToEnable; - for (auto& index : allIndex(model())) { - modsToEnable.append(index.data(ModList::IndexRole).toInt()); - } - profile->setModsEnabled(modsToEnable, {}); - invalidate(); + m_core->modList()->setActive(indexViewToModel(allIndex(model())), true); } void ModListView::disableAllVisible() { - MOBase::log::debug("disableAllVisible: {}", model()->rowCount()); - Profile* profile = m_core->currentProfile(); - - QList modsToDisable; - for (auto& index : allIndex(model())) { - modsToDisable.append(index.data(ModList::IndexRole).toInt()); - } - profile->setModsEnabled({}, modsToDisable); - invalidate(); + m_core->modList()->setActive(indexViewToModel(allIndex(model())), false); } void ModListView::enableSelected() { - Profile* profile = m_core->currentProfile(); if (selectionModel()->hasSelection()) { - QList modsToEnable; - for (auto row : selectionModel()->selectedRows(ModList::COL_PRIORITY)) { - int modID = profile->modIndexByPriority(row.data().toInt()); - modsToEnable.append(modID); - } - profile->setModsEnabled(modsToEnable, {}); + m_core->modList()->setActive(indexViewToModel(selectionModel()->selectedRows()), true); } - invalidate(); } void ModListView::disableSelected() { - Profile* profile = m_core->currentProfile(); if (selectionModel()->hasSelection()) { - QList modsToDisable; - for (auto row : selectionModel()->selectedRows(ModList::COL_PRIORITY)) { - int modID = profile->modIndexByPriority(row.data().toInt()); - modsToDisable.append(modID); - } - profile->setModsEnabled({}, modsToDisable); + m_core->modList()->setActive(indexViewToModel(selectionModel()->selectedRows()), false); } - invalidate(); } void ModListView::setFilterCriteria(const std::vector& criteria) @@ -279,6 +243,15 @@ QModelIndex ModListView::indexModelToView(const QModelIndex& index) const return qindex; } +QModelIndexList ModListView::indexModelToView(const QModelIndexList& index) const +{ + QModelIndexList result; + for (auto& idx : index) { + result.append(indexModelToView(idx)); + } + return result; +} + QModelIndex ModListView::indexViewToModel(const QModelIndex& index) const { if (index.model() == m_core->modList()) { @@ -292,6 +265,15 @@ QModelIndex ModListView::indexViewToModel(const QModelIndex& index) const } } +QModelIndexList ModListView::indexViewToModel(const QModelIndexList& index) const +{ + QModelIndexList result; + for (auto& idx : index) { + result.append(indexViewToModel(idx)); + } + return result; +} + QModelIndex ModListView::nextIndex(const QModelIndex& index) const { auto* model = index.model(); @@ -329,15 +311,13 @@ QModelIndex ModListView::prevIndex(const QModelIndex& index) const return prev; } -std::vector ModListView::allIndex( +QModelIndexList ModListView::allIndex( const QAbstractItemModel* model, int column, const QModelIndex& parent) const { - std::vector index; + QModelIndexList index; for (std::size_t i = 0; i < model->rowCount(parent); ++i) { - index.push_back(model->index(i, column, parent)); - - auto cindex = allIndex(model, column, index.back()); - index.insert(index.end(), cindex.begin(), cindex.end()); + index.append(model->index(i, column, parent)); + index.append(allIndex(model, column, index.back())); } return index; } @@ -376,10 +356,6 @@ void ModListView::onModPrioritiesChanged(std::vector const& indices) m_core->currentProfile()->writeModlist(); m_core->directoryStructure()->getFileRegister()->sortOrigins(); - if (m_sortProxy) { - m_sortProxy->invalidate(); - } - { // refresh selection QModelIndex current = currentIndex(); if (current.isValid()) { @@ -431,7 +407,7 @@ void ModListView::onModInstalled(const QString& modName) setFocus(Qt::OtherFocusReason); scrollTo(qIndex); setCurrentIndex(qIndex); - selectionModel()->select(qIndex, QItemSelectionModel::Select | QItemSelectionModel::Rows); + selectionModel()->select(qIndex, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); } void ModListView::onModFilterActive(bool filterActive) @@ -666,6 +642,12 @@ void ModListView::setup(OrganizerCore& core, Ui::MainWindow* mwui) }); } +void ModListView::setModel(QAbstractItemModel* model) +{ + QTreeView::setModel(model); + setVerticalScrollBar(new ViewMarkingScrollBar(model, this)); +} + QRect ModListView::visualRect(const QModelIndex& index) const { QRect rect = QTreeView::visualRect(index); @@ -680,12 +662,6 @@ QRect ModListView::visualRect(const QModelIndex& index) const return rect; } -void ModListView::setModel(QAbstractItemModel* model) -{ - QTreeView::setModel(model); - setVerticalScrollBar(new ViewMarkingScrollBar(model, this)); -} - QModelIndexList ModListView::selectedIndexes() const { return m_inDragMoveEvent ? QModelIndexList() : QTreeView::selectedIndexes(); @@ -747,7 +723,7 @@ bool ModListView::moveSelection(int key) offset = -offset; } - m_core->modList()->moveMods(sourceRows, offset); + m_core->modList()->shiftMods(sourceRows, offset); // reset the selection and the index setCurrentIndex(indexModelToView(cindex)); diff --git a/src/modlistview.h b/src/modlistview.h index 88028428..1d8a9b49 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -80,10 +80,6 @@ signals: public slots: - // invalidate the top-level model - // - void invalidate(); - // enable/disable all visible mods // void enableAllVisible(); @@ -108,7 +104,9 @@ protected: // map from/to the view indexes to the model // QModelIndex indexModelToView(const QModelIndex& index) const; + QModelIndexList indexModelToView(const QModelIndexList& index) const; QModelIndex indexViewToModel(const QModelIndex& index) const; + QModelIndexList indexViewToModel(const QModelIndexList& index) const; // returns the next/previous index of the given index // @@ -117,7 +115,7 @@ protected: // all index for the given model under the given index, recursively // - std::vector allIndex( + QModelIndexList allIndex( const QAbstractItemModel* model, int column = 0, const QModelIndex& index = QModelIndex()) const; // re-implemented to fake the return value to allow drag-and-drop on -- cgit v1.3.1 From 6443fa4c0e027faced0af9539533e1c404badf3b Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Wed, 30 Dec 2020 17:21:20 +0100 Subject: Fix category management. --- src/mainwindow.cpp | 53 +++++++++++++++++---------------------------------- src/mainwindow.h | 9 +++------ src/organizercore.cpp | 8 +------- 3 files changed, 22 insertions(+), 48 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index e01f984a..3af7079f 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -3654,12 +3654,7 @@ void MainWindow::addRemoveCategoriesFromMenu(QMenu *menu, int modRow, int refere } } -void MainWindow::addRemoveCategories_MenuHandler(int modIndex, const QModelIndex& rowIdx) { - QMenu *menu = qobject_cast(sender()); - if (menu == nullptr) { - log::error("not a menu?"); - return; - } +void MainWindow::addRemoveCategories_MenuHandler(QMenu* menu, int modIndex, const QModelIndex& rowIdx) { QList selected; for (const QModelIndex &idx : ui->modList->selectionModel()->selectedRows()) { @@ -3695,13 +3690,8 @@ void MainWindow::addRemoveCategories_MenuHandler(int modIndex, const QModelIndex refreshFilters(); } -void MainWindow::replaceCategories_MenuHandler(int modIndex) { - QMenu *menu = qobject_cast(sender()); - if (menu == nullptr) { - log::error("not a menu?"); - return; - } - +void MainWindow::replaceCategories_MenuHandler(QMenu* menu, int modIndex) +{ QList selected; for (const QModelIndex &idx : ui->modList->selectionModel()->selectedRows()) { selected.append(QPersistentModelIndex(idx)); @@ -3879,8 +3869,10 @@ void MainWindow::unignoreUpdate(int modIndex) } } -void MainWindow::addPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, - ModInfo::Ptr info) { +void MainWindow::setPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, + ModInfo::Ptr info) +{ + primaryCategoryMenu->clear(); const std::set &categories = info->getCategories(); for (int categoryID : categories) { int catIdx = m_CategoryFactory.getCategoryIndex(categoryID); @@ -3905,19 +3897,6 @@ void MainWindow::addPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, } } -void MainWindow::addPrimaryCategoryCandidates(int modIndex) -{ - QMenu *menu = qobject_cast(sender()); - if (menu == nullptr) { - log::error("not a menu?"); - return; - } - menu->clear(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - - addPrimaryCategoryCandidates(menu, modInfo); -} - void MainWindow::enableVisibleMods() { if (QMessageBox::question(nullptr, tr("Confirm"), tr("Really enable all visible mods?"), @@ -4292,10 +4271,10 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) ModInfo::Ptr info = ModInfo::getByIndex(modIndex); std::vector flags = info->getFlags(); - // Context menu for overwrites + // context menu for overwrites if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) { if (QDir(info->absolutePath()).count() > 2) { - menu.addAction(tr("Sync to Mods..."), &m_OrganizerCore, SLOT(syncOverwrite())); + menu.addAction(tr("Sync to Mods..."), [=]() { m_OrganizerCore.syncOverwrite(); }); menu.addAction(tr("Create Mod..."), [=]() { createModFromOverwrite(); }); menu.addAction(tr("Move content to Mod..."), [=]() { moveOverwriteContentToExistingMod(); }); menu.addAction(tr("Clear Overwrite..."), [=]() { clearOverwrite(); }); @@ -4303,7 +4282,7 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) menu.addAction(tr("Open in Explorer"), [=]() { openExplorer_clicked(modIndex); }); } - // Context menu for mod backups + // context menu for mod backups else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) != flags.end()) { menu.addAction(tr("Restore Backup"), [=]() { restoreBackup_clicked(modIndex); }); menu.addAction(tr("Remove Backup..."), [=]() { removeMod_clicked(modIndex); }); @@ -4332,10 +4311,10 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) menu.addSeparator(); QMenu *addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); populateMenuCategories(modIndex, addRemoveCategoriesMenu, 0); - connect(addRemoveCategoriesMenu, &QMenu::aboutToHide, [=]() { addRemoveCategories_MenuHandler(modIndex, contextIdx); }); + connect(addRemoveCategoriesMenu, &QMenu::aboutToHide, [=]() { addRemoveCategories_MenuHandler(addRemoveCategoriesMenu, modIndex, contextIdx); }); addMenuAsPushButton(&menu, addRemoveCategoriesMenu); QMenu *primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); - connect(primaryCategoryMenu, &QMenu::aboutToShow, [=]() { addPrimaryCategoryCandidates(modIndex); }); + connect(primaryCategoryMenu, &QMenu::aboutToShow, [=]() { setPrimaryCategoryCandidates(primaryCategoryMenu, info); }); addMenuAsPushButton(&menu, primaryCategoryMenu); menu.addSeparator(); menu.addAction(tr("Rename Separator..."), [=]() { renameMod_clicked(); }); @@ -4350,17 +4329,21 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) menu.addSeparator(); } + + // foregin else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) != flags.end()) { addModSendToContextMenu(&menu); } + + // regular else { QMenu* addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); populateMenuCategories(modIndex, addRemoveCategoriesMenu, 0); - connect(addRemoveCategoriesMenu, &QMenu::aboutToHide, [=]() { addRemoveCategories_MenuHandler(modIndex, contextIdx); }); + connect(addRemoveCategoriesMenu, &QMenu::aboutToHide, [=]() { addRemoveCategories_MenuHandler(addRemoveCategoriesMenu, modIndex, contextIdx); }); addMenuAsPushButton(&menu, addRemoveCategoriesMenu); QMenu* primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); - connect(primaryCategoryMenu, &QMenu::aboutToShow, [=]() { addPrimaryCategoryCandidates(modIndex); }); + connect(primaryCategoryMenu, &QMenu::aboutToShow, [=]() { setPrimaryCategoryCandidates(primaryCategoryMenu, info); }); addMenuAsPushButton(&menu, primaryCategoryMenu); menu.addSeparator(); diff --git a/src/mainwindow.h b/src/mainwindow.h index 97bca68b..9e9e9591 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -129,8 +129,6 @@ public: void saveArchiveList(); - void addPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, ModInfo::Ptr info); - void installTranslator(const QString &name); void displayModInformation( @@ -434,10 +432,9 @@ private slots: void originModified(int originID); - void addRemoveCategories_MenuHandler(int modIndex, const QModelIndex& rowIdx); - void replaceCategories_MenuHandler(int modIndex); - - void addPrimaryCategoryCandidates(int modIndex); + void setPrimaryCategoryCandidates(QMenu* menu, ModInfo::Ptr info); + void addRemoveCategories_MenuHandler(QMenu* menu, int modIndex, const QModelIndex& rowIdx); + void replaceCategories_MenuHandler(QMenu* menu, int modIndex); void modInstalled(const QString &modName); diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 9e3528ef..1a6083b4 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -1785,13 +1785,7 @@ void OrganizerCore::loginFailedUpdate(const QString &message) void OrganizerCore::syncOverwrite() { - unsigned int overwriteIndex = ModInfo::findMod([](ModInfo::Ptr mod) -> bool { - std::vector flags = mod->getFlags(); - return std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) - != flags.end(); - }); - - ModInfo::Ptr modInfo = ModInfo::getByIndex(overwriteIndex); + ModInfo::Ptr modInfo = ModInfo::getOverwrite(); SyncOverwriteDialog syncDialog(modInfo->absolutePath(), m_DirectoryStructure, qApp->activeWindow()); if (syncDialog.exec() == QDialog::Accepted) { -- cgit v1.3.1 From 07c2badd174059f7cc4ca404c22c6741b679cc7f Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Wed, 30 Dec 2020 20:24:34 +0100 Subject: Fix rebase from 54736a6. --- src/mainwindow.cpp | 42 +++++++++++++++++++++++++++++++----------- src/modlistview.cpp | 2 ++ 2 files changed, 33 insertions(+), 11 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 3af7079f..bafe05f5 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -477,7 +477,6 @@ MainWindow::MainWindow(Settings &settings new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Enter), this, SLOT(openExplorer_activated())); new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return), this, SLOT(openExplorer_activated())); - new QShortcut(QKeySequence::Refresh, this, SLOT(refreshProfile_activated())); setFilterShortcuts(ui->modList, ui->modFilterEdit); setFilterShortcuts(ui->espList, ui->espFilterEdit); @@ -1580,17 +1579,17 @@ void MainWindow::on_profileBox_currentIndexChanged(int index) m_OldProfileIndex = index; if ((previousIndex != -1) && - (m_OrganizerCore.currentProfile() != nullptr) && - m_OrganizerCore.currentProfile()->exists()) { + (m_OrganizerCore.currentProfile() != nullptr) && + m_OrganizerCore.currentProfile()->exists()) { m_OrganizerCore.saveCurrentLists(); } // Avoid doing any refresh if currentProfile is already set but previous index was -1 // as it means that this is happening during initialization so everything has already been set. if (previousIndex == -1 - && m_OrganizerCore.currentProfile() != nullptr - && m_OrganizerCore.currentProfile()->exists() - && ui->profileBox->currentText() == m_OrganizerCore.currentProfile()->name()){ + && m_OrganizerCore.currentProfile() != nullptr + && m_OrganizerCore.currentProfile()->exists() + && ui->profileBox->currentText() == m_OrganizerCore.currentProfile()->name()) { return; } @@ -1602,22 +1601,36 @@ void MainWindow::on_profileBox_currentIndexChanged(int index) if (ui->profileBox->currentIndex() == 0) { ui->profileBox->setCurrentIndex(previousIndex); - ProfilesDialog(ui->profileBox->currentText(), m_OrganizerCore, this).exec(); + + std::optional newSelection; + + ProfilesDialog dlg(ui->profileBox->currentText(), m_OrganizerCore, this); + dlg.exec(); + newSelection = dlg.selectedProfile(); + while (!refreshProfiles()) { - ProfilesDialog(ui->profileBox->currentText(), m_OrganizerCore, this).exec(); + ProfilesDialog dlg(ui->profileBox->currentText(), m_OrganizerCore, this); + dlg.exec(); + newSelection = dlg.selectedProfile(); } - } else { + + if (newSelection) { + ui->profileBox->setCurrentText(*newSelection); + activateSelectedProfile(); + } + } + else { activateSelectedProfile(); } - LocalSavegames *saveGames = m_OrganizerCore.managedGame()->feature(); + LocalSavegames* saveGames = m_OrganizerCore.managedGame()->feature(); if (saveGames != nullptr) { if (saveGames->prepareProfile(m_OrganizerCore.currentProfile())) { m_SavesTab->refreshSaveList(); } } - BSAInvalidation *invalidation = m_OrganizerCore.managedGame()->feature(); + BSAInvalidation* invalidation = m_OrganizerCore.managedGame()->feature(); if (invalidation != nullptr) { if (invalidation->prepareProfile(m_OrganizerCore.currentProfile())) { QTimer::singleShot(5, &m_OrganizerCore, SLOT(profileRefresh())); @@ -2182,6 +2195,11 @@ void MainWindow::on_actionInstallMod_triggered() installMod(); } +void MainWindow::on_action_Refresh_triggered() +{ + refreshProfile_activated(); +} + void MainWindow::on_actionAdd_Profile_triggered() { for (;;) { @@ -2390,6 +2408,7 @@ void MainWindow::restoreBackup_clicked(int modIndex) reportError(tr("failed to rename \"%1\" to \"%2\"").arg(modInfo->absolutePath()).arg(destinationPath)); } m_OrganizerCore.refresh(); + ui->modList->updateModCount(); } } } @@ -2528,6 +2547,7 @@ void MainWindow::backupMod_clicked(int modIndex) tr("Failed to create backup.")); } m_OrganizerCore.refresh(); + ui->modList->updateModCount(); } diff --git a/src/modlistview.cpp b/src/modlistview.cpp index be173478..b36a77d9 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -438,6 +438,8 @@ void ModListView::onModFilterActive(bool filterActive) void ModListView::updateModCount() { + TimeThis tt("updateModCount"); + int activeCount = 0; int visActiveCount = 0; int backupCount = 0; -- cgit v1.3.1 From 8a88421fd9748f64163f18d8b89ea9d651402014 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Wed, 30 Dec 2020 22:56:34 +0100 Subject: Start moving modlist context menu actions to separate structures. --- src/CMakeLists.txt | 2 + src/mainwindow.cpp | 337 ++------------------------------------------ src/mainwindow.h | 7 - src/modlistcontextmenu.cpp | 273 ++++++++++++++++++++++++++++++++++++ src/modlistcontextmenu.h | 39 ++++++ src/modlistview.cpp | 9 +- src/modlistview.h | 9 +- src/modlistviewactions.cpp | 339 +++++++++++++++++++++++++++++++++++++++++++++ src/modlistviewactions.h | 55 ++++++++ src/organizercore.cpp | 12 +- src/organizercore.h | 5 +- 11 files changed, 742 insertions(+), 345 deletions(-) create mode 100644 src/modlistcontextmenu.cpp create mode 100644 src/modlistcontextmenu.h create mode 100644 src/modlistviewactions.cpp create mode 100644 src/modlistviewactions.h (limited to 'src/mainwindow.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 93b9e768..4c7bcd46 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -138,6 +138,8 @@ add_filter(NAME src/modlist GROUPS modlistsortproxy modlistbypriorityproxy modlistview + modlistviewactions + modlistcontextmenu ) add_filter(NAME src/plugins GROUPS diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index bafe05f5..58061c96 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -58,8 +58,6 @@ along with Mod Organizer. If not, see . #include "filedialogmemory.h" #include "tutorialmanager.h" #include "selectiondialog.h" -#include "csvbuilder.h" -#include "savetextasdialog.h" #include "problemsdialog.h" #include "previewdialog.h" #include "browserdialog.h" @@ -86,6 +84,8 @@ along with Mod Organizer. If not, see . #include "envshortcut.h" #include "browserdialog.h" #include "modlistbypriorityproxy.h" +#include "modlistviewactions.h" +#include "modlistcontextmenu.h" #include "directoryrefresher.h" #include "shared/directoryentry.h" @@ -392,9 +392,7 @@ MainWindow::MainWindow(Settings &settings m_LinkStartMenu = linkMenu->addAction(QIcon(":/MO/gui/link"), tr("Start Menu"), this, SLOT(linkMenu())); ui->linkButton->setMenu(linkMenu); - QMenu *listOptionsMenu = new QMenu(ui->listOptionsBtn); - initModListContextMenu(listOptionsMenu); - ui->listOptionsBtn->setMenu(listOptionsMenu); + ui->listOptionsBtn->setMenu(new ModListGlobalContextMenu(m_OrganizerCore, ui->modList, ui->listOptionsBtn)); ui->openFolderMenu->setMenu(openFolderMenu()); @@ -537,7 +535,7 @@ MainWindow::MainWindow(Settings &settings void MainWindow::setupModList() { - ui->modList->setup(m_OrganizerCore, ui); + ui->modList->setup(m_OrganizerCore, new ModListViewActions(m_OrganizerCore, *m_Filters, m_CategoryFactory, this, ui->modList), ui); connect(ui->modList, &ModListView::removeSelectedMods, [=]() { removeMod_clicked(-1); }); @@ -2076,30 +2074,6 @@ void MainWindow::on_tabWidget_currentChanged(int index) } } - -void MainWindow::installMod(QString fileName) -{ - try { - if (fileName.isEmpty()) { - QStringList extensions = m_OrganizerCore.installationManager()->getSupportedExtensions(); - for (auto iter = extensions.begin(); iter != extensions.end(); ++iter) { - *iter = "*." + *iter; - } - - fileName = FileDialogMemory::getOpenFileName("installMod", this, tr("Choose Mod"), QString(), - tr("Mod Archive").append(QString(" (%1)").arg(extensions.join(" ")))); - } - - if (fileName.isEmpty()) { - return; - } else { - m_OrganizerCore.installMod(fileName, false, nullptr, QString()); - } - } catch (const std::exception &e) { - reportError(e.what()); - } -} - void MainWindow::on_startButton_clicked() { const Executable* selectedExecutable = getSelectedExecutable(); @@ -2192,7 +2166,7 @@ void MainWindow::tutorialTriggered() void MainWindow::on_actionInstallMod_triggered() { - installMod(); + ui->modList->actions().installMod(); } void MainWindow::on_action_Refresh_triggered() @@ -2328,7 +2302,7 @@ void MainWindow::showError(const QString &message) void MainWindow::installMod_clicked() { - installMod(); + ui->modList->actions().installMod(); } void MainWindow::modRenamed(const QString &oldName, const QString &newName) @@ -3173,87 +3147,6 @@ void MainWindow::information_clicked(int modIndex) } } -void MainWindow::createEmptyMod_clicked(int modIndex) -{ - GuessedValue name; - name.setFilter(&fixDirectoryName); - - while (name->isEmpty()) { - bool ok; - name.update(QInputDialog::getText(this, 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_OrganizerCore.modList()->getMod(name) != nullptr) { - reportError(tr("A mod with this name already exists")); - return; - } - - int newPriority = -1; - if (modIndex >= 0 && ui->modList->sortColumn() == ModList::COL_PRIORITY) { - newPriority = m_OrganizerCore.currentProfile()->getModPriority(modIndex); - } - - IModInterface *newMod = m_OrganizerCore.createMod(name); - if (newMod == nullptr) { - return; - } - - m_OrganizerCore.refresh(); - - if (newPriority >= 0) { - m_OrganizerCore.modList()->changeModPriority(ModInfo::getIndex(name), newPriority); - } -} - -void MainWindow::createSeparator_clicked(int modIndex) -{ - GuessedValue name; - name.setFilter(&fixDirectoryName); - while (name->isEmpty()) - { - bool ok; - name.update(QInputDialog::getText(this, 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_OrganizerCore.modList()->getMod(name) != nullptr) - { - reportError(tr("A separator with this name already exists")); - return; - } - name->append("_separator"); - if (m_OrganizerCore.modList()->getMod(name) != nullptr) - { - return; - } - - int newPriority = -1; - if (modIndex >= 0 && ui->modList->sortColumn() == ModList::COL_PRIORITY) - { - newPriority = m_OrganizerCore.currentProfile()->getModPriority(modIndex); - } - - if (m_OrganizerCore.createMod(name) == nullptr) { return; } - m_OrganizerCore.refresh(); - - if (newPriority >= 0) - { - m_OrganizerCore.modList()->changeModPriority(ModInfo::getIndex(name), newPriority); - } - - if (auto c=m_OrganizerCore.settings().colors().previousSeparatorColor()) { - ModInfo::getByIndex(ModInfo::getIndex(name))->setColor(*c); - } -} - void MainWindow::setColor_clicked(int modIndex) { auto& settings = m_OrganizerCore.settings(); @@ -3917,22 +3810,6 @@ void MainWindow::setPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, } } -void MainWindow::enableVisibleMods() -{ - if (QMessageBox::question(nullptr, tr("Confirm"), tr("Really enable all visible mods?"), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - ui->modList->enableAllVisible(); - } -} - -void MainWindow::disableVisibleMods() -{ - if (QMessageBox::question(nullptr, tr("Confirm"), tr("Really disable all visible mods?"), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - ui->modList->disableAllVisible(); - } -} - void MainWindow::openInstanceFolder() { QString dataPath = qApp->property("dataPath").toString(); @@ -3998,175 +3875,6 @@ void MainWindow::openMyGamesFolder() shell::Explore(m_OrganizerCore.managedGame()->documentsDirectory()); } - -void MainWindow::exportModListCSV() -{ - //SelectionDialog selection(tr("Choose what to export")); - - //selection.addChoice(tr("Everything"), tr("All installed mods are included in the list"), 0); - //selection.addChoice(tr("Active Mods"), tr("Only active (checked) mods from your current profile are included"), 1); - //selection.addChoice(tr("Visible"), tr("All mods visible in the mod list are included"), 2); - - QDialog selection(this); - 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 > 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_OrganizerCore.currentProfile()->getAllIndexesByPriority(); - for (auto& iter : indexesByPriority) { - ModInfo::Ptr info = ModInfo::getByIndex(iter.second); - bool enabled = m_OrganizerCore.currentProfile()->modEnabled(iter.second); - if ((selectedRowID == 1) && !enabled) { - continue; - } - else if ((selectedRowID == 2) && !ui->modList->isModVisible(iter.second)) { - continue; - } - std::vector 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_CategoryFactory.categoryExists(info->primaryCategory())) ? m_CategoryFactory.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(this); - saveDialog.setText(buffer.data()); - saveDialog.exec(); - } - catch (const std::exception &e) { - reportError(tr("export failed: %1").arg(e.what())); - } - } -} - static void addMenuAsPushButton(QMenu *menu, QMenu *subMenu) { QPushButton *pushBtn = new QPushButton(subMenu->title()); @@ -4205,27 +3913,6 @@ QMenu *MainWindow::openFolderMenu() return FolderMenu; } -void MainWindow::initModListContextMenu(QMenu *menu) -{ - menu->addAction(tr("Install Mod..."), [&]() { installMod_clicked(); }); - menu->addAction(tr("Create empty mod"), [&]() { createEmptyMod_clicked(-1); }); - menu->addAction(tr("Create Separator"), [&]() { createSeparator_clicked(-1); }); - - if (ui->modList->hasCollapsibleSeparators()) { - menu->addSeparator(); - menu->addAction(tr("Collapse all"), ui->modList, &QTreeView::collapseAll); - menu->addAction(tr("Expand all"), ui->modList, &QTreeView::expandAll); - } - - menu->addSeparator(); - - menu->addAction(tr("Enable all visible"), [&]() { enableVisibleMods(); }); - menu->addAction(tr("Disable all visible"), [&]() { disableVisibleMods(); }); - menu->addAction(tr("Check for updates"), [&]() { checkModsForUpdates(); }); - menu->addAction(tr("Refresh"), &m_OrganizerCore, &OrganizerCore::profileRefresh); - menu->addAction(tr("Export to csv..."), [&]() { exportModListCSV(); }); -} - void MainWindow::addModSendToContextMenu(QMenu *menu) { if (ui->modList->sortColumn() != ModList::COL_PRIORITY) @@ -4269,15 +3956,12 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) if (modIndex == -1) { // no selection - QMenu menu(this); - initModListContextMenu(&menu); - menu.exec(modList->viewport()->mapToGlobal(pos)); + ModListGlobalContextMenu(m_OrganizerCore, ui->modList).exec(modList->viewport()->mapToGlobal(pos)); } else { QMenu menu(this); - QMenu *allMods = new QMenu(&menu); - initModListContextMenu(allMods); + QMenu *allMods = new ModListGlobalContextMenu(m_OrganizerCore, ui->modList, this); allMods->setTitle(tr("All Mods")); menu.addMenu(allMods); @@ -4711,10 +4395,7 @@ void MainWindow::languageChange(const QString &newLanguage) m_DownloadsTab->update(); } - QMenu *listOptionsMenu = new QMenu(ui->listOptionsBtn); - initModListContextMenu(listOptionsMenu); - ui->listOptionsBtn->setMenu(listOptionsMenu); - + ui->listOptionsBtn->setMenu(new ModListGlobalContextMenu(m_OrganizerCore, ui->modList, this)); ui->openFolderMenu->setMenu(openFolderMenu()); } diff --git a/src/mainwindow.h b/src/mainwindow.h index 9e9e9591..a49c12fe 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -207,7 +207,6 @@ private: bool refreshProfiles(bool selectProfile = true); void refreshExecutablesList(); - void installMod(QString fileName = ""); bool modifyExecutablesDialog(int selection); void displayModInformation(int row, ModInfoTabIDs tab=ModInfoTabIDs::None); @@ -251,7 +250,6 @@ private: bool createBackup(const QString &filePath, const QDateTime &time); QString queryRestore(const QString &filePath); - void initModListContextMenu(QMenu *menu); void addModSendToContextMenu(QMenu *menu); void addPluginSendToContextMenu(QMenu *menu); @@ -358,8 +356,6 @@ private slots: // modlist context menu void installMod_clicked(); - void createEmptyMod_clicked(int modIndex); - void createSeparator_clicked(int modIndex); void restoreBackup_clicked(int modIndex); void renameMod_clicked(); void removeMod_clicked(int modIndex); @@ -473,9 +469,6 @@ private slots: void trackMod(ModInfo::Ptr mod, bool doTrack); void cancelModListEditor(); - void enableVisibleMods(); - void disableVisibleMods(); - void exportModListCSV(); void openInstanceFolder(); void openLogsFolder(); void openInstallFolder(); diff --git a/src/modlistcontextmenu.cpp b/src/modlistcontextmenu.cpp new file mode 100644 index 00000000..5b45a217 --- /dev/null +++ b/src/modlistcontextmenu.cpp @@ -0,0 +1,273 @@ +#include "modlistcontextmenu.h" + +#include + +#include "modlist.h" +#include "modlistview.h" +#include "modlistviewactions.h" +#include "organizercore.h" + +using namespace MOBase; + +ModListGlobalContextMenu::ModListGlobalContextMenu(OrganizerCore& core, ModListView* view, QWidget* parent) + : QMenu(parent) +{ + addAction(tr("Install Mod..."), [=]() { view->actions().installMod(); }); + addAction(tr("Create empty mod"), [=]() { view->actions().createEmptyMod(-1); }); + addAction(tr("Create Separator"), [=]() { view->actions().createSeparator(-1); }); + + if (view->hasCollapsibleSeparators()) { + addSeparator(); + addAction(tr("Collapse all"), view, &QTreeView::collapseAll); + addAction(tr("Expand all"), view, &QTreeView::expandAll); + } + + addSeparator(); + + addAction(tr("Enable all visible"), [=]() { + if (QMessageBox::question(view, tr("Confirm"), tr("Really enable all visible mods?"), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + view->enableAllVisible(); + } + }); + addAction(tr("Disable all visible"), [=]() { + if (QMessageBox::question(view, tr("Confirm"), tr("Really disable all visible mods?"), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + view->disableAllVisible(); + } + }); + addAction(tr("Check for updates"), [=]() { view->actions().checkModsForUpdates(); }); + addAction(tr("Refresh"), &core, &OrganizerCore::profileRefresh); + addAction(tr("Export to csv..."), [=]() { view->actions().exportModListCSV(); }); +} + +ModListContextMenu::ModListContextMenu(OrganizerCore& core, const QModelIndexList& index, ModListView* modListView) : + QMenu(modListView) + , m_core(core) + , m_index(index) +{ + // TODO: Change this. + QModelIndex contextIdx = index.at(0); + int contextColumn = contextIdx.column(); + int modIndex = contextIdx.data(ModList::IndexRole).toInt(); + + try { + /* + if (modIndex == -1) { + // no selection + QMenu menu(this); + initModListContextMenu(&menu); + menu.exec(modList->viewport()->mapToGlobal(pos)); + } + else { + QMenu menu(this); + + QMenu* allMods = new QMenu(&menu); + initModListContextMenu(allMods); + allMods->setTitle(tr("All Mods")); + menu.addMenu(allMods); + + if (ui->modList->hasCollapsibleSeparators()) { + menu.addAction(tr("Collapse all"), ui->modList, &QTreeView::collapseAll); + menu.addAction(tr("Expand all"), ui->modList, &QTreeView::expandAll); + } + + menu.addSeparator(); + + ModInfo::Ptr info = ModInfo::getByIndex(modIndex); + std::vector flags = info->getFlags(); + + // context menu for overwrites + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) { + if (QDir(info->absolutePath()).count() > 2) { + menu.addAction(tr("Sync to Mods..."), [=]() { m_OrganizerCore.syncOverwrite(); }); + menu.addAction(tr("Create Mod..."), [=]() { createModFromOverwrite(); }); + menu.addAction(tr("Move content to Mod..."), [=]() { moveOverwriteContentToExistingMod(); }); + menu.addAction(tr("Clear Overwrite..."), [=]() { clearOverwrite(); }); + } + menu.addAction(tr("Open in Explorer"), [=]() { openExplorer_clicked(modIndex); }); + } + + // context menu for mod backups + else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) != flags.end()) { + menu.addAction(tr("Restore Backup"), [=]() { restoreBackup_clicked(modIndex); }); + menu.addAction(tr("Remove Backup..."), [=]() { removeMod_clicked(modIndex); }); + menu.addSeparator(); + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_INVALID) != flags.end()) { + menu.addAction(tr("Ignore missing data"), [=]() { ignoreMissingData_clicked(modIndex); }); + } + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_ALTERNATE_GAME) != flags.end()) { + menu.addAction(tr("Mark as converted/working"), [=]() { markConverted_clicked(modIndex); }); + } + menu.addSeparator(); + if (info->nexusId() > 0) { + menu.addAction(tr("Visit on Nexus"), [=]() { visitOnNexus_clicked(modIndex); }); + } + + const auto url = info->parseCustomURL(); + if (url.isValid()) { + menu.addAction(tr("Visit on %1").arg(url.host()), [=]() { visitWebPage_clicked(modIndex); }); + } + + menu.addAction(tr("Open in Explorer"), [=]() { openExplorer_clicked(modIndex); }); + } + + // separator + else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end()) { + menu.addSeparator(); + QMenu* addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); + populateMenuCategories(modIndex, addRemoveCategoriesMenu, 0); + connect(addRemoveCategoriesMenu, &QMenu::aboutToHide, [=]() { addRemoveCategories_MenuHandler(addRemoveCategoriesMenu, modIndex, contextIdx); }); + addMenuAsPushButton(&menu, addRemoveCategoriesMenu); + QMenu* primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); + connect(primaryCategoryMenu, &QMenu::aboutToShow, [=]() { setPrimaryCategoryCandidates(primaryCategoryMenu, info); }); + addMenuAsPushButton(&menu, primaryCategoryMenu); + menu.addSeparator(); + menu.addAction(tr("Rename Separator..."), [=]() { renameMod_clicked(); }); + menu.addAction(tr("Remove Separator..."), [=]() { removeMod_clicked(modIndex); }); + menu.addSeparator(); + addModSendToContextMenu(&menu); + menu.addAction(tr("Select Color..."), [=]() { setColor_clicked(modIndex); }); + + if (info->color().isValid()) { + menu.addAction(tr("Reset Color"), [=]() { resetColor_clicked(modIndex); }); + } + + menu.addSeparator(); + } + + // foregin + else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) != flags.end()) { + addModSendToContextMenu(&menu); + } + + // regular + else { + QMenu* addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); + populateMenuCategories(modIndex, addRemoveCategoriesMenu, 0); + connect(addRemoveCategoriesMenu, &QMenu::aboutToHide, [=]() { addRemoveCategories_MenuHandler(addRemoveCategoriesMenu, modIndex, contextIdx); }); + addMenuAsPushButton(&menu, addRemoveCategoriesMenu); + + QMenu* primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); + connect(primaryCategoryMenu, &QMenu::aboutToShow, [=]() { setPrimaryCategoryCandidates(primaryCategoryMenu, info); }); + addMenuAsPushButton(&menu, primaryCategoryMenu); + + menu.addSeparator(); + + if (info->downgradeAvailable()) { + menu.addAction(tr("Change versioning scheme"), [=]() { changeVersioningScheme(modIndex); }); + } + + if (info->nexusId() > 0) + menu.addAction(tr("Force-check updates"), [=]() { checkModUpdates_clicked(modIndex); }); + if (info->updateIgnored()) { + menu.addAction(tr("Un-ignore update"), [=]() { unignoreUpdate(modIndex); }); + } + else { + if (info->updateAvailable() || info->downgradeAvailable()) { + menu.addAction(tr("Ignore update"), [=]() { ignoreUpdate(modIndex); }); + } + } + menu.addSeparator(); + + menu.addAction(tr("Enable selected"), [=]() { enableSelectedMods_clicked(); }); + menu.addAction(tr("Disable selected"), [=]() { disableSelectedMods_clicked(); }); + + menu.addSeparator(); + + addModSendToContextMenu(&menu); + + menu.addAction(tr("Rename Mod..."), [=]() { renameMod_clicked(); }); + menu.addAction(tr("Reinstall Mod"), [=]() { reinstallMod_clicked(modIndex); }); + menu.addAction(tr("Remove Mod..."), [=]() { removeMod_clicked(modIndex); }); + menu.addAction(tr("Create Backup"), [=]() { backupMod_clicked(modIndex); }); + + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_HIDDEN_FILES) != flags.end()) { + menu.addAction(tr("Restore hidden files"), [=]() { restoreHiddenFiles_clicked(modIndex); }); + } + + menu.addSeparator(); + + if (contextColumn == ModList::COL_NOTES) { + menu.addAction(tr("Select Color..."), [=]() { setColor_clicked(modIndex); }); + if (info->color().isValid()) { + menu.addAction(tr("Reset Color"), [=]() { resetColor_clicked(modIndex); }); + } + menu.addSeparator(); + } + + if (info->nexusId() > 0 && Settings::instance().nexus().endorsementIntegration()) { + switch (info->endorsedState()) { + case EndorsedState::ENDORSED_TRUE: { + menu.addAction(tr("Un-Endorse"), [=]() { unendorse_clicked(); }); + } break; + case EndorsedState::ENDORSED_FALSE: { + menu.addAction(tr("Endorse"), [=]() { endorse_clicked(); }); + menu.addAction(tr("Won't endorse"), [=]() { dontendorse_clicked(modIndex); }); + } break; + case EndorsedState::ENDORSED_NEVER: { + menu.addAction(tr("Endorse"), [=]() { endorse_clicked(); }); + } break; + default: { + QAction* action = new QAction(tr("Endorsement state unknown"), &menu); + action->setEnabled(false); + menu.addAction(action); + } break; + } + } + + if (info->nexusId() > 0 && Settings::instance().nexus().trackedIntegration()) { + switch (info->trackedState()) { + case TrackedState::TRACKED_FALSE: { + menu.addAction(tr("Start tracking"), [=]() { track_clicked(); }); + } break; + case TrackedState::TRACKED_TRUE: { + menu.addAction(tr("Stop tracking"), [=]() { untrack_clicked(); }); + } break; + default: { + QAction* action = new QAction(tr("Tracked state unknown"), &menu); + action->setEnabled(false); + menu.addAction(action); + } break; + } + } + + menu.addSeparator(); + + std::vector flags = info->getFlags(); + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_INVALID) != flags.end()) { + menu.addAction(tr("Ignore missing data"), [=]() { ignoreMissingData_clicked(modIndex); }); + } + + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_ALTERNATE_GAME) != flags.end()) { + menu.addAction(tr("Mark as converted/working"), [=]() { markConverted_clicked(modIndex); }); + } + + menu.addSeparator(); + + if (info->nexusId() > 0) { + menu.addAction(tr("Visit on Nexus"), [=]() { visitOnNexus_clicked(modIndex); }); + } + + const auto url = info->parseCustomURL(); + if (url.isValid()) { + menu.addAction(tr("Visit on %1").arg(url.host()), [=]() { visitWebPage_clicked(modIndex); }); + } + + menu.addAction(tr("Open in Explorer"), [&, modIndex]() { openExplorer_clicked(modIndex); }); + } + + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) == flags.end()) { + QAction* infoAction = menu.addAction(tr("Information..."), [=]() { information_clicked(modIndex); }); + menu.setDefaultAction(infoAction); + } + } + */ + } + catch (const std::exception& e) { + reportError(tr("Exception: ").arg(e.what())); + } + catch (...) { + reportError(tr("Unknown exception")); + } +} diff --git a/src/modlistcontextmenu.h b/src/modlistcontextmenu.h new file mode 100644 index 00000000..bc72fbdf --- /dev/null +++ b/src/modlistcontextmenu.h @@ -0,0 +1,39 @@ +#ifndef MODLISTCONTEXTMENU_H +#define MODLISTCONTEXTMENU_H + +#include + +#include +#include +#include + +class ModListView; +class OrganizerCore; + +class ModListGlobalContextMenu : public QMenu +{ + Q_OBJECT +public: + + ModListGlobalContextMenu(OrganizerCore& core, ModListView* modListView, QWidget* parent = nullptr); + +}; + +class ModListContextMenu : public QMenu +{ + Q_OBJECT + +private: + + friend class ModListView; + + // creates a new context menu that will act on the given mod list + // index (those should be index from the modlist) + ModListContextMenu(OrganizerCore& core, const QModelIndexList& index, ModListView* modListView); + + OrganizerCore& m_core; + QModelIndexList m_index; + +}; + +#endif diff --git a/src/modlistview.cpp b/src/modlistview.cpp index b36a77d9..f8192758 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -17,6 +17,7 @@ #include "log.h" #include "modflagicondelegate.h" #include "modconflicticondelegate.h" +#include "modlistviewactions.h" #include "modlistdropinfo.h" #include "genericicondelegate.h" #include "shared/directoryentry.h" @@ -118,6 +119,11 @@ int ModListView::sortColumn() const return m_sortProxy ? m_sortProxy->sortColumn() : -1; } +ModListViewActions& ModListView::actions() const +{ + return *m_actions; +} + int ModListView::nextMod(int modIndex) const { const QModelIndex start = indexModelToView(m_core->modList()->index(modIndex, 0)); @@ -634,10 +640,11 @@ void ModListView::updateGroupByProxy(int groupIndex) } } -void ModListView::setup(OrganizerCore& core, Ui::MainWindow* mwui) +void ModListView::setup(OrganizerCore& core, ModListViewActions* actions, Ui::MainWindow* mwui) { // attributes m_core = &core; + m_actions = actions; ui = { mwui->groupCombo, mwui->activeModsCounter, mwui->modFilterEdit, mwui->clearFiltersButton }; connect(m_core, &OrganizerCore::modInstalled, this, &ModListView::onModInstalled); diff --git a/src/modlistview.h b/src/modlistview.h index 8e37161b..d5eea54f 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -13,9 +13,11 @@ namespace Ui { class MainWindow; } +class FilterList; class OrganizerCore; class Profile; class ModListByPriorityProxy; +class ModListViewActions; class ModListView : public QTreeView { @@ -35,7 +37,7 @@ public: explicit ModListView(QWidget* parent = 0); void setModel(QAbstractItemModel* model) override; - void setup(OrganizerCore& core, Ui::MainWindow* mwui); + void setup(OrganizerCore& core, ModListViewActions* actions, Ui::MainWindow* mwui); // set the current profile // @@ -49,6 +51,10 @@ public: // int sortColumn() const; + // retrieve the actions from the view + // + ModListViewActions& actions() const; + // retrieve the next/previous mod in the current view, the given index // should be a mod index (not a model row), and the return value will be // a mod index or -1 if no mod was found @@ -180,6 +186,7 @@ private: OrganizerCore* m_core; ModListViewUi ui; + ModListViewActions* m_actions; ModListSortProxy* m_sortProxy; ModListByPriorityProxy* m_byPriorityProxy; diff --git a/src/modlistviewactions.cpp b/src/modlistviewactions.cpp new file mode 100644 index 00000000..8b234b81 --- /dev/null +++ b/src/modlistviewactions.cpp @@ -0,0 +1,339 @@ +#include "modlistviewactions.h" + +#include +#include +#include +#include + +#include + +#include "categories.h" +#include "filedialogmemory.h" +#include "filterlist.h" +#include "modlist.h" +#include "modlistview.h" +#include "nexusinterface.h" +#include "nxmaccessmanager.h" +#include "savetextasdialog.h" +#include "organizercore.h" +#include "csvbuilder.h" + +using namespace MOBase; + +ModListViewActions::ModListViewActions( + OrganizerCore& core, FilterList& filters, CategoryFactory& categoryFactory, QObject* nxmReceiver, ModListView* view) : + QObject(view) + , m_core(core) + , m_filters(filters) + , m_categories(categoryFactory) + , m_receiver(nxmReceiver) + , m_view(view) +{ + +} + +void ModListViewActions::installMod(const QString& archivePath) 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_view, tr("Choose Mod"), QString(), + tr("Mod Archive").append(QString(" (%1)").arg(extensions.join(" ")))); + } + + if (path.isEmpty()) { + return; + } + else { + m_core.installMod(path, false, nullptr, QString()); + } + } + catch (const std::exception& e) { + reportError(e.what()); + } +} + +void ModListViewActions::createEmptyMod(int modIndex) const +{ + GuessedValue name; + name.setFilter(&fixDirectoryName); + + while (name->isEmpty()) { + bool ok; + name.update(QInputDialog::getText(m_view, 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; + } + + int newPriority = -1; + if (modIndex >= 0 && m_view->sortColumn() == ModList::COL_PRIORITY) { + newPriority = m_core.currentProfile()->getModPriority(modIndex); + } + + IModInterface* newMod = m_core.createMod(name); + if (newMod == nullptr) { + return; + } + + m_core.refresh(); + + if (newPriority >= 0) { + m_core.modList()->changeModPriority(ModInfo::getIndex(name), newPriority); + } +} + +void ModListViewActions::createSeparator(int modIndex) const +{ + GuessedValue name; + name.setFilter(&fixDirectoryName); + while (name->isEmpty()) + { + bool ok; + name.update(QInputDialog::getText(m_view, 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 (modIndex >= 0 && m_view->sortColumn() == ModList::COL_PRIORITY) + { + newPriority = m_core.currentProfile()->getModPriority(modIndex); + } + + if (m_core.createMod(name) == nullptr) { return; } + m_core.refresh(); + + if (newPriority >= 0) + { + m_core.modList()->changeModPriority(ModInfo::getIndex(name), newPriority); + } + + if (auto c = m_core.settings().colors().previousSeparatorColor()) { + ModInfo::getByIndex(ModInfo::getIndex(name))->setColor(*c); + } +} + +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::exportModListCSV() const +{ + QDialog selection(m_view); + 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 > 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 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_view); + saveDialog.setText(buffer.data()); + saveDialog.exec(); + } + catch (const std::exception& e) { + reportError(tr("export failed: %1").arg(e.what())); + } + } +} diff --git a/src/modlistviewactions.h b/src/modlistviewactions.h new file mode 100644 index 00000000..49cffaef --- /dev/null +++ b/src/modlistviewactions.h @@ -0,0 +1,55 @@ +#ifndef MODLISTVIEWACTIONS_H +#define MODLISTVIEWACTIONS_H + +#include +#include + +class CategoryFactory; +class FilterList; +class ModListView; +class OrganizerCore; + +class ModListViewActions : public QObject +{ + Q_OBJECT + +public: + + // the nxmReceiver is a (hopefully temporary) "hack" because it would require a lots of change + // to do otherwise since NXM is mostly based on the old Qt signal-slot system + // + ModListViewActions( + OrganizerCore& core, + FilterList& filters, + CategoryFactory& categoryFactory, + QObject* nxmReceiver, + ModListView* view); + + // install the mod from the given archive + // + void installMod(const QString& archivePath = "") const; + + // create an empty mod/a separator before the given mod or at + // the end of the list if the index is -1 + // + void createEmptyMod(int modIndex) const; + void createSeparator(int modIndex) const; + + // check all mods for update + // + void checkModsForUpdates() const; + + // start the "Export Mod List" dialog + // + void exportModListCSV() const; + +private: + + OrganizerCore& m_core; + FilterList& m_filters; + CategoryFactory& m_categories; + QObject* m_receiver; // receiver for NXM signals (temporary) + ModListView* m_view; +}; + +#endif diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 1a6083b4..986b6fbb 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -1510,13 +1510,6 @@ void OrganizerCore::requestDownload(const QUrl &url, QNetworkReply *reply) } } -ModListSortProxy *OrganizerCore::createModListProxyModel() -{ - ModListSortProxy *result = new ModListSortProxy(m_CurrentProfile.get(), this); - result->setSourceModel(&m_ModList); - return result; -} - PluginListSortProxy *OrganizerCore::createPluginListProxyModel() { PluginListSortProxy *result = new PluginListSortProxy(this); @@ -1524,6 +1517,11 @@ PluginListSortProxy *OrganizerCore::createPluginListProxyModel() return result; } +PluginContainer& OrganizerCore::pluginContainer() const +{ + return *m_PluginContainer; +} + IPluginGame const *OrganizerCore::managedGame() const { return m_GamePlugin; diff --git a/src/organizercore.h b/src/organizercore.h index 3fb4f20e..e060fbcb 100644 --- a/src/organizercore.h +++ b/src/organizercore.h @@ -227,9 +227,12 @@ public: MOBase::VersionInfo getVersion() const { return m_Updater.getVersion(); } - ModListSortProxy *createModListProxyModel(); PluginListSortProxy *createPluginListProxyModel(); + // return the plugin container + // + PluginContainer& pluginContainer() const; + MOBase::IPluginGame const *managedGame() const; /** -- cgit v1.3.1 From e8c2d9cd29967be928b8649fd580a3be9cae3684 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Wed, 30 Dec 2020 23:35:44 +0100 Subject: More context menu stuff moved. --- src/mainwindow.cpp | 112 ++----------------- src/mainwindow.h | 7 -- src/modlistcontextmenu.cpp | 264 ++++++++++----------------------------------- src/modlistcontextmenu.h | 18 +++- src/modlistview.h | 4 +- src/modlistviewactions.cpp | 103 +++++++++++++++++- src/modlistviewactions.h | 19 +++- 7 files changed, 192 insertions(+), 335 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 58061c96..265cc5c2 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2629,70 +2629,9 @@ void MainWindow::overwriteClosed(int) m_OrganizerCore.refreshDirectoryStructure(); } - -void MainWindow::displayModInformation( - ModInfo::Ptr modInfo, unsigned int modIndex, ModInfoTabIDs tabID) +void MainWindow::displayModInformation(ModInfo::Ptr modInfo, unsigned int modIndex, ModInfoTabIDs tabID) { - if (!m_OrganizerCore.modList()->modInfoAboutToChange(modInfo)) { - log::debug("A different mod information dialog is open. If this is incorrect, please restart MO"); - return; - } - std::vector flags = modInfo->getFlags(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) { - QDialog *dialog = this->findChild("__overwriteDialog"); - try { - if (dialog == nullptr) { - dialog = new OverwriteInfoDialog(modInfo, this); - dialog->setObjectName("__overwriteDialog"); - } else { - qobject_cast(dialog)->setModInfo(modInfo); - } - - dialog->show(); - dialog->raise(); - dialog->activateWindow(); - connect(dialog, SIGNAL(finished(int)), this, SLOT(overwriteClosed(int))); - } catch (const std::exception &e) { - reportError(tr("Failed to display overwrite dialog: %1").arg(e.what())); - } - } else { - modInfo->saveMeta(); - - ModInfoDialog dialog(this, &m_OrganizerCore, &m_PluginContainer, modInfo); - connect(&dialog, SIGNAL(originModified(int)), this, SLOT(originModified(int))); - - //Open the tab first if we want to use the standard indexes of the tabs. - if (tabID != ModInfoTabIDs::None) { - dialog.selectTab(tabID); - } - - dialog.exec(); - - modInfo->saveMeta(); - emit modInfoDisplayed(); - m_OrganizerCore.modList()->modInfoChanged(modInfo); - } - - if (m_OrganizerCore.currentProfile()->modEnabled(modIndex) - && !modInfo->hasFlag(ModInfo::FLAG_FOREIGN)) { - FilesOrigin& origin = m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(modInfo->name())); - origin.enable(false); - - if (m_OrganizerCore.directoryStructure()->originExists(ToWString(modInfo->name()))) { - FilesOrigin& origin = m_OrganizerCore.directoryStructure()->getOriginByName(ToWString(modInfo->name())); - origin.enable(false); - - m_OrganizerCore.directoryRefresher()->addModToStructure(m_OrganizerCore.directoryStructure() - , modInfo->name() - , m_OrganizerCore.currentProfile()->getModPriority(modIndex) - , modInfo->absolutePath() - , modInfo->stealFiles() - , modInfo->archives()); - DirectoryRefresher::cleanStructure(m_OrganizerCore.directoryStructure()); - m_OrganizerCore.directoryStructure()->getFileRegister()->sortOrigins(); - m_OrganizerCore.refreshLists(); - } - } + ui->modList->actions().displayModInformation(modInfo, modIndex, tabID); } bool MainWindow::closeWindow() @@ -2723,26 +2662,6 @@ ModInfo::Ptr MainWindow::previousModInList(int modIndex) return ModInfo::getByIndex(modIndex); } -void MainWindow::displayModInformation(const QString &modName, ModInfoTabIDs tabID) -{ - 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, tabID); -} - - -void MainWindow::displayModInformation(int row, ModInfoTabIDs tabID) -{ - ModInfo::Ptr modInfo = ModInfo::getByIndex(row); - displayModInformation(modInfo, row, tabID); -} - - void MainWindow::ignoreMissingData_clicked(int modIndex) { const auto rows = ui->modList->selectionModel()->selectedRows(); @@ -3141,7 +3060,7 @@ void MainWindow::updatePluginCount() void MainWindow::information_clicked(int modIndex) { try { - displayModInformation(modIndex); + ui->modList->actions().displayModInformation(modIndex); } catch (const std::exception &e) { reportError(e.what()); } @@ -3388,7 +3307,7 @@ void MainWindow::on_modList_doubleClicked(const QModelIndex &index) case ModList::COL_CONFLICTFLAGS: tab = ModInfoTabIDs::Conflicts; break; } - displayModInformation(modIndex, tab); + ui->modList->actions().displayModInformation(modIndex, tab); // workaround to cancel the editor that might have opened because of // selection-click ui->modList->closePersistentEditor(index); @@ -3424,7 +3343,7 @@ void MainWindow::openOriginInformation_clicked() std::vector flags = modInfo->getFlags(); if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { - displayModInformation(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); + ui->modList->actions().displayModInformation(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); } } catch (const std::exception &e) { @@ -3473,7 +3392,7 @@ void MainWindow::on_espList_doubleClicked(const QModelIndex &index) } else { - displayModInformation(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); + ui->modList->actions().displayModInformation(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); // workaround to cancel the editor that might have opened because of // selection-click ui->espList->closePersistentEditor(index); @@ -3950,27 +3869,16 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) QTreeView *modList = findChild("modList"); QModelIndex contextIdx = mapToModel(m_OrganizerCore.modList(), ui->modList->indexAt(pos)); - int modIndex = ui->modList->indexAt(pos).data(ModList::IndexRole).toInt(); - - int contextColumn = contextIdx.column(); - if (modIndex == -1) { + if (!contextIdx.isValid()) { // no selection ModListGlobalContextMenu(m_OrganizerCore, ui->modList).exec(modList->viewport()->mapToGlobal(pos)); } else { - QMenu menu(this); - - QMenu *allMods = new ModListGlobalContextMenu(m_OrganizerCore, ui->modList, this); - allMods->setTitle(tr("All Mods")); - menu.addMenu(allMods); - - if (ui->modList->hasCollapsibleSeparators()) { - menu.addAction(tr("Collapse all"), ui->modList, &QTreeView::collapseAll); - menu.addAction(tr("Expand all"), ui->modList, &QTreeView::expandAll); - } + int modIndex = ui->modList->indexAt(pos).data(ModList::IndexRole).toInt(); + int contextColumn = contextIdx.column(); - menu.addSeparator(); + ModListContextMenu menu(m_OrganizerCore, contextIdx, ui->modList); ModInfo::Ptr info = ModInfo::getByIndex(modIndex); std::vector flags = info->getFlags(); diff --git a/src/mainwindow.h b/src/mainwindow.h index a49c12fe..57f26220 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -153,11 +153,6 @@ public slots: signals: - /** - * @brief emitted after the information dialog has been closed - */ - void modInfoDisplayed(); - /** * @brief emitted when the selected style changes */ @@ -209,7 +204,6 @@ private: void refreshExecutablesList(); bool modifyExecutablesDialog(int selection); - void displayModInformation(int row, ModInfoTabIDs tab=ModInfoTabIDs::None); /** * Sets category selections from menu; for multiple mods, this will only apply @@ -455,7 +449,6 @@ private slots: void onFiltersOptions( ModListSortProxy::FilterMode mode, ModListSortProxy::SeparatorsMode sep); - void displayModInformation(const QString &modName, ModInfoTabIDs tabID); void visitNexusOrWebPage(const QModelIndex& idx); void modRenamed(const QString &oldName, const QString &newName); diff --git a/src/modlistcontextmenu.cpp b/src/modlistcontextmenu.cpp index 5b45a217..41031eaa 100644 --- a/src/modlistcontextmenu.cpp +++ b/src/modlistcontextmenu.cpp @@ -41,233 +41,77 @@ ModListGlobalContextMenu::ModListGlobalContextMenu(OrganizerCore& core, ModListV addAction(tr("Export to csv..."), [=]() { view->actions().exportModListCSV(); }); } -ModListContextMenu::ModListContextMenu(OrganizerCore& core, const QModelIndexList& index, ModListView* modListView) : - QMenu(modListView) +ModListContextMenu::ModListContextMenu(OrganizerCore& core, const QModelIndex& index, ModListView* view) : + QMenu(view) , m_core(core) - , m_index(index) + , m_index() { - // TODO: Change this. - QModelIndex contextIdx = index.at(0); - int contextColumn = contextIdx.column(); - int modIndex = contextIdx.data(ModList::IndexRole).toInt(); - - try { - /* - if (modIndex == -1) { - // no selection - QMenu menu(this); - initModListContextMenu(&menu); - menu.exec(modList->viewport()->mapToGlobal(pos)); - } - else { - QMenu menu(this); - - QMenu* allMods = new QMenu(&menu); - initModListContextMenu(allMods); - allMods->setTitle(tr("All Mods")); - menu.addMenu(allMods); - - if (ui->modList->hasCollapsibleSeparators()) { - menu.addAction(tr("Collapse all"), ui->modList, &QTreeView::collapseAll); - menu.addAction(tr("Expand all"), ui->modList, &QTreeView::expandAll); - } - - menu.addSeparator(); - - ModInfo::Ptr info = ModInfo::getByIndex(modIndex); - std::vector flags = info->getFlags(); - - // context menu for overwrites - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) { - if (QDir(info->absolutePath()).count() > 2) { - menu.addAction(tr("Sync to Mods..."), [=]() { m_OrganizerCore.syncOverwrite(); }); - menu.addAction(tr("Create Mod..."), [=]() { createModFromOverwrite(); }); - menu.addAction(tr("Move content to Mod..."), [=]() { moveOverwriteContentToExistingMod(); }); - menu.addAction(tr("Clear Overwrite..."), [=]() { clearOverwrite(); }); - } - menu.addAction(tr("Open in Explorer"), [=]() { openExplorer_clicked(modIndex); }); - } - - // context menu for mod backups - else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) != flags.end()) { - menu.addAction(tr("Restore Backup"), [=]() { restoreBackup_clicked(modIndex); }); - menu.addAction(tr("Remove Backup..."), [=]() { removeMod_clicked(modIndex); }); - menu.addSeparator(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_INVALID) != flags.end()) { - menu.addAction(tr("Ignore missing data"), [=]() { ignoreMissingData_clicked(modIndex); }); - } - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_ALTERNATE_GAME) != flags.end()) { - menu.addAction(tr("Mark as converted/working"), [=]() { markConverted_clicked(modIndex); }); - } - menu.addSeparator(); - if (info->nexusId() > 0) { - menu.addAction(tr("Visit on Nexus"), [=]() { visitOnNexus_clicked(modIndex); }); - } - - const auto url = info->parseCustomURL(); - if (url.isValid()) { - menu.addAction(tr("Visit on %1").arg(url.host()), [=]() { visitWebPage_clicked(modIndex); }); - } - - menu.addAction(tr("Open in Explorer"), [=]() { openExplorer_clicked(modIndex); }); - } - - // separator - else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end()) { - menu.addSeparator(); - QMenu* addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); - populateMenuCategories(modIndex, addRemoveCategoriesMenu, 0); - connect(addRemoveCategoriesMenu, &QMenu::aboutToHide, [=]() { addRemoveCategories_MenuHandler(addRemoveCategoriesMenu, modIndex, contextIdx); }); - addMenuAsPushButton(&menu, addRemoveCategoriesMenu); - QMenu* primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); - connect(primaryCategoryMenu, &QMenu::aboutToShow, [=]() { setPrimaryCategoryCandidates(primaryCategoryMenu, info); }); - addMenuAsPushButton(&menu, primaryCategoryMenu); - menu.addSeparator(); - menu.addAction(tr("Rename Separator..."), [=]() { renameMod_clicked(); }); - menu.addAction(tr("Remove Separator..."), [=]() { removeMod_clicked(modIndex); }); - menu.addSeparator(); - addModSendToContextMenu(&menu); - menu.addAction(tr("Select Color..."), [=]() { setColor_clicked(modIndex); }); - - if (info->color().isValid()) { - menu.addAction(tr("Reset Color"), [=]() { resetColor_clicked(modIndex); }); - } - - menu.addSeparator(); - } - - // foregin - else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) != flags.end()) { - addModSendToContextMenu(&menu); - } - - // regular - else { - QMenu* addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); - populateMenuCategories(modIndex, addRemoveCategoriesMenu, 0); - connect(addRemoveCategoriesMenu, &QMenu::aboutToHide, [=]() { addRemoveCategories_MenuHandler(addRemoveCategoriesMenu, modIndex, contextIdx); }); - addMenuAsPushButton(&menu, addRemoveCategoriesMenu); - - QMenu* primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); - connect(primaryCategoryMenu, &QMenu::aboutToShow, [=]() { setPrimaryCategoryCandidates(primaryCategoryMenu, info); }); - addMenuAsPushButton(&menu, primaryCategoryMenu); - - menu.addSeparator(); - - if (info->downgradeAvailable()) { - menu.addAction(tr("Change versioning scheme"), [=]() { changeVersioningScheme(modIndex); }); - } - - if (info->nexusId() > 0) - menu.addAction(tr("Force-check updates"), [=]() { checkModUpdates_clicked(modIndex); }); - if (info->updateIgnored()) { - menu.addAction(tr("Un-ignore update"), [=]() { unignoreUpdate(modIndex); }); - } - else { - if (info->updateAvailable() || info->downgradeAvailable()) { - menu.addAction(tr("Ignore update"), [=]() { ignoreUpdate(modIndex); }); - } - } - menu.addSeparator(); + if (view->selectionModel()->hasSelection()) { + m_index = view->indexViewToModel(view->selectionModel()->selectedRows()); + } + else { + m_index = { index }; + } - menu.addAction(tr("Enable selected"), [=]() { enableSelectedMods_clicked(); }); - menu.addAction(tr("Disable selected"), [=]() { disableSelectedMods_clicked(); }); - menu.addSeparator(); + QMenu* allMods = new ModListGlobalContextMenu(core, view, view); + allMods->setTitle(tr("All Mods")); + addMenu(allMods); - addModSendToContextMenu(&menu); + if (view->hasCollapsibleSeparators()) { + addAction(tr("Collapse all"), view, &QTreeView::collapseAll); + addAction(tr("Expand all"), view, &QTreeView::expandAll); + } - menu.addAction(tr("Rename Mod..."), [=]() { renameMod_clicked(); }); - menu.addAction(tr("Reinstall Mod"), [=]() { reinstallMod_clicked(modIndex); }); - menu.addAction(tr("Remove Mod..."), [=]() { removeMod_clicked(modIndex); }); - menu.addAction(tr("Create Backup"), [=]() { backupMod_clicked(modIndex); }); + addSeparator(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_HIDDEN_FILES) != flags.end()) { - menu.addAction(tr("Restore hidden files"), [=]() { restoreHiddenFiles_clicked(modIndex); }); - } + // Add type-specific items + ModInfo::Ptr info = ModInfo::getByIndex(index.data(ModList::IndexRole).toInt()); - menu.addSeparator(); + if (info->isOverwrite()) { + addOverwriteActions(core, view); + } + else if (info->isBackup()) { + addBackupActions(core, view); + } + else if (info->isSeparator()) { + addSeparatorActions(core, view); + } + else if (info->isForeign()) { + addForeignActions(core, view); + } + else { + addRegularActions(core, view); + } - if (contextColumn == ModList::COL_NOTES) { - menu.addAction(tr("Select Color..."), [=]() { setColor_clicked(modIndex); }); - if (info->color().isValid()) { - menu.addAction(tr("Reset Color"), [=]() { resetColor_clicked(modIndex); }); - } - menu.addSeparator(); - } + // add information for all except foreign + if (!info->isForeign()) { + QAction* infoAction = addAction(tr("Information..."), [=]() { view->actions().displayModInformation(m_index[0].row()); }); + setDefaultAction(infoAction); + } +} - if (info->nexusId() > 0 && Settings::instance().nexus().endorsementIntegration()) { - switch (info->endorsedState()) { - case EndorsedState::ENDORSED_TRUE: { - menu.addAction(tr("Un-Endorse"), [=]() { unendorse_clicked(); }); - } break; - case EndorsedState::ENDORSED_FALSE: { - menu.addAction(tr("Endorse"), [=]() { endorse_clicked(); }); - menu.addAction(tr("Won't endorse"), [=]() { dontendorse_clicked(modIndex); }); - } break; - case EndorsedState::ENDORSED_NEVER: { - menu.addAction(tr("Endorse"), [=]() { endorse_clicked(); }); - } break; - default: { - QAction* action = new QAction(tr("Endorsement state unknown"), &menu); - action->setEnabled(false); - menu.addAction(action); - } break; - } - } +void ModListContextMenu::addOverwriteActions(OrganizerCore& core, ModListView* modListView) +{ - if (info->nexusId() > 0 && Settings::instance().nexus().trackedIntegration()) { - switch (info->trackedState()) { - case TrackedState::TRACKED_FALSE: { - menu.addAction(tr("Start tracking"), [=]() { track_clicked(); }); - } break; - case TrackedState::TRACKED_TRUE: { - menu.addAction(tr("Stop tracking"), [=]() { untrack_clicked(); }); - } break; - default: { - QAction* action = new QAction(tr("Tracked state unknown"), &menu); - action->setEnabled(false); - menu.addAction(action); - } break; - } - } +} - menu.addSeparator(); +void ModListContextMenu::addSeparatorActions(OrganizerCore& core, ModListView* modListView) +{ - std::vector flags = info->getFlags(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_INVALID) != flags.end()) { - menu.addAction(tr("Ignore missing data"), [=]() { ignoreMissingData_clicked(modIndex); }); - } +} - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_ALTERNATE_GAME) != flags.end()) { - menu.addAction(tr("Mark as converted/working"), [=]() { markConverted_clicked(modIndex); }); - } +void ModListContextMenu::addForeignActions(OrganizerCore& core, ModListView* modListView) +{ - menu.addSeparator(); +} - if (info->nexusId() > 0) { - menu.addAction(tr("Visit on Nexus"), [=]() { visitOnNexus_clicked(modIndex); }); - } +void ModListContextMenu::addBackupActions(OrganizerCore& core, ModListView* modListView) +{ - const auto url = info->parseCustomURL(); - if (url.isValid()) { - menu.addAction(tr("Visit on %1").arg(url.host()), [=]() { visitWebPage_clicked(modIndex); }); - } +} - menu.addAction(tr("Open in Explorer"), [&, modIndex]() { openExplorer_clicked(modIndex); }); - } +void ModListContextMenu::addRegularActions(OrganizerCore& core, ModListView* modListView) +{ - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) == flags.end()) { - QAction* infoAction = menu.addAction(tr("Information..."), [=]() { information_clicked(modIndex); }); - menu.setDefaultAction(infoAction); - } - } - */ - } - catch (const std::exception& e) { - reportError(tr("Exception: ").arg(e.what())); - } - catch (...) { - reportError(tr("Unknown exception")); - } } diff --git a/src/modlistcontextmenu.h b/src/modlistcontextmenu.h index bc72fbdf..9d015afc 100644 --- a/src/modlistcontextmenu.h +++ b/src/modlistcontextmenu.h @@ -23,13 +23,21 @@ class ModListContextMenu : public QMenu { Q_OBJECT -private: +public: - friend class ModListView; + // creates a new context menu, the given index is the one for the click and should be valid + // + ModListContextMenu(OrganizerCore& core, const QModelIndex& index, ModListView* modListView); + +private: - // creates a new context menu that will act on the given mod list - // index (those should be index from the modlist) - ModListContextMenu(OrganizerCore& core, const QModelIndexList& index, ModListView* modListView); + // add actions/menus to this menu for each type of mod + // + void addOverwriteActions(OrganizerCore& core, ModListView* modListView); + void addSeparatorActions(OrganizerCore& core, ModListView* modListView); + void addForeignActions(OrganizerCore& core, ModListView* modListView); + void addBackupActions(OrganizerCore& core, ModListView* modListView); + void addRegularActions(OrganizerCore& core, ModListView* modListView); OrganizerCore& m_core; QModelIndexList m_index; diff --git a/src/modlistview.h b/src/modlistview.h index d5eea54f..0f131631 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -105,8 +105,6 @@ public slots: // void updateModCount(); -protected: - // map from/to the view indexes to the model // QModelIndex indexModelToView(const QModelIndex& index) const; @@ -114,6 +112,8 @@ protected: QModelIndex indexViewToModel(const QModelIndex& index) const; QModelIndexList indexViewToModel(const QModelIndexList& index) const; +protected: + // returns the next/previous index of the given index // QModelIndex nextIndex(const QModelIndex& index) const; diff --git a/src/modlistviewactions.cpp b/src/modlistviewactions.cpp index 8b234b81..6faebc15 100644 --- a/src/modlistviewactions.cpp +++ b/src/modlistviewactions.cpp @@ -5,28 +5,37 @@ #include #include +#include #include #include "categories.h" #include "filedialogmemory.h" #include "filterlist.h" +#include "modinfodialog.h" #include "modlist.h" #include "modlistview.h" +#include "mainwindow.h" #include "nexusinterface.h" #include "nxmaccessmanager.h" #include "savetextasdialog.h" #include "organizercore.h" +#include "overwriteinfodialog.h" #include "csvbuilder.h" +#include "shared/filesorigin.h" +#include "shared/directoryentry.h" +#include "shared/fileregister.h" +#include "directoryrefresher.h" using namespace MOBase; +using namespace MOShared; ModListViewActions::ModListViewActions( - OrganizerCore& core, FilterList& filters, CategoryFactory& categoryFactory, QObject* nxmReceiver, ModListView* view) : + OrganizerCore& core, FilterList& filters, CategoryFactory& categoryFactory, MainWindow* mainWindow, ModListView* view) : QObject(view) , m_core(core) , m_filters(filters) , m_categories(categoryFactory) - , m_receiver(nxmReceiver) + , m_main(mainWindow) , m_view(view) { @@ -143,9 +152,9 @@ 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()); + checkingModsForUpdate = ModInfo::checkAllForUpdate(&m_core.pluginContainer(), m_main); + NexusInterface::instance().requestEndorsementInfo(m_main, QVariant(), QString()); + NexusInterface::instance().requestTrackingInfo(m_main, QVariant(), QString()); } else { QString apiKey; if (GlobalSettings::nexusApiKey(apiKey)) { @@ -337,3 +346,87 @@ void ModListViewActions::exportModListCSV() const } } } + +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 flags = modInfo->getFlags(); + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) { + QDialog* dialog = m_main->findChild("__overwriteDialog"); + try { + if (dialog == nullptr) { + dialog = new OverwriteInfoDialog(modInfo, m_main); + dialog->setObjectName("__overwriteDialog"); + } + else { + qobject_cast(dialog)->setModInfo(modInfo); + } + + dialog->show(); + dialog->raise(); + dialog->activateWindow(); + connect(dialog, SIGNAL(finished(int)), this, SLOT(overwriteClosed(int))); + } + catch (const std::exception& e) { + reportError(tr("Failed to display overwrite dialog: %1").arg(e.what())); + } + } + else { + modInfo->saveMeta(); + + ModInfoDialog dialog(m_main, &m_core, &m_core.pluginContainer(), modInfo); + connect(&dialog, SIGNAL(originModified(int)), this, SLOT(originModified(int))); + + //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); + } + + if (m_core.currentProfile()->modEnabled(modIndex) + && !modInfo->hasFlag(ModInfo::FLAG_FOREIGN)) { + 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); + + m_core.directoryRefresher()->addModToStructure(m_core.directoryStructure() + , modInfo->name() + , m_core.currentProfile()->getModPriority(modIndex) + , modInfo->absolutePath() + , modInfo->stealFiles() + , modInfo->archives()); + DirectoryRefresher::cleanStructure(m_core.directoryStructure()); + m_core.directoryStructure()->getFileRegister()->sortOrigins(); + m_core.refreshLists(); + } + } +} diff --git a/src/modlistviewactions.h b/src/modlistviewactions.h index 49cffaef..b01b8e79 100644 --- a/src/modlistviewactions.h +++ b/src/modlistviewactions.h @@ -4,8 +4,12 @@ #include #include +#include "modinfo.h" +#include "modinfodialogfwd.h" + class CategoryFactory; class FilterList; +class MainWindow; class ModListView; class OrganizerCore; @@ -15,14 +19,14 @@ class ModListViewActions : public QObject public: - // the nxmReceiver is a (hopefully temporary) "hack" because it would require a lots of change - // to do otherwise since NXM is mostly based on the old Qt signal-slot system + // currently passing the main window itself because a lots of stuff needs it but + // it would be nice to avoid passing it at some point // ModListViewActions( OrganizerCore& core, FilterList& filters, CategoryFactory& categoryFactory, - QObject* nxmReceiver, + MainWindow* mainWindow, ModListView* view); // install the mod from the given archive @@ -43,12 +47,19 @@ public: // void exportModListCSV() const; + // display mod information + // + void displayModInformation(const QString& modName, ModInfoTabIDs tabID = ModInfoTabIDs::None) const; + void displayModInformation(unsigned int index, ModInfoTabIDs tab = ModInfoTabIDs::None) const; + void displayModInformation(ModInfo::Ptr modInfo, unsigned int modIndex, ModInfoTabIDs tabID = ModInfoTabIDs::None) const; + + private: OrganizerCore& m_core; FilterList& m_filters; CategoryFactory& m_categories; - QObject* m_receiver; // receiver for NXM signals (temporary) + MainWindow* m_main; ModListView* m_view; }; -- cgit v1.3.1 From fb52a129b3a878511cf754daed433d9a789689c8 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 00:06:12 +0100 Subject: More stuff moved to mod list context. --- src/mainwindow.cpp | 121 +++------------------------------------------ src/mainwindow.h | 7 --- src/modlist.cpp | 22 ++++++++- src/modlist.h | 6 ++- src/modlistcontextmenu.cpp | 39 ++++++++++----- src/modlistcontextmenu.h | 17 ++++--- src/modlistview.cpp | 2 +- src/modlistviewactions.cpp | 68 +++++++++++++++++++++++++ src/modlistviewactions.h | 6 +++ 9 files changed, 148 insertions(+), 140 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 265cc5c2..91897d2f 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -3832,22 +3832,6 @@ QMenu *MainWindow::openFolderMenu() return FolderMenu; } -void MainWindow::addModSendToContextMenu(QMenu *menu) -{ - if (ui->modList->sortColumn() != ModList::COL_PRIORITY) - return; - - QMenu *sub_menu = new QMenu(menu); - sub_menu->setTitle(tr("Send to")); - sub_menu->addAction(tr("Top"), [&]() { sendSelectedModsToTop_clicked(); }); - sub_menu->addAction(tr("Bottom"), [&]() { sendSelectedModsToBottom_clicked(); }); - sub_menu->addAction(tr("Priority..."), [&]() { sendSelectedModsToPriority_clicked(); }); - sub_menu->addAction(tr("Separator..."), [&]() { sendSelectedModsToSeparator_clicked(); }); - - menu->addMenu(sub_menu); - menu->addSeparator(); -} - void MainWindow::addPluginSendToContextMenu(QMenu *menu) { if (m_PluginListSortProxy->sortColumn() != PluginList::COL_PRIORITY) @@ -3932,7 +3916,10 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) menu.addAction(tr("Rename Separator..."), [=]() { renameMod_clicked(); }); menu.addAction(tr("Remove Separator..."), [=]() { removeMod_clicked(modIndex); }); menu.addSeparator(); - addModSendToContextMenu(&menu); + if (ui->modList->sortColumn() == ModList::COL_PRIORITY) { + menu.addMenu(menu.createSendToContextMenu()); + menu.addSeparator(); + } menu.addAction(tr("Select Color..."), [=]() { setColor_clicked(modIndex); }); if (info->color().isValid()) { @@ -3944,7 +3931,6 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) // foregin else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) != flags.end()) { - addModSendToContextMenu(&menu); } // regular @@ -3981,7 +3967,10 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) menu.addSeparator(); - addModSendToContextMenu(&menu); + if (ui->modList->sortColumn() == ModList::COL_PRIORITY) { + menu.addMenu(menu.createSendToContextMenu()); + menu.addSeparator(); + } menu.addAction(tr("Rename Mod..."), [=]() { renameMod_clicked(); }); menu.addAction(tr("Reinstall Mod"), [=]() { reinstallMod_clicked(modIndex); }); @@ -5477,97 +5466,3 @@ void MainWindow::on_clearFiltersButton_clicked() ui->modFilterEdit->clear(); deselectFilters(); } - -void MainWindow::sendSelectedModsToPriority(int newPriority) -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection()) { - std::vector modsToMove; - for (auto idx : selection->selectedRows(ModList::COL_PRIORITY)) { - modsToMove.push_back(m_OrganizerCore.currentProfile()->modIndexByPriority(idx.data().toInt())); - } - - if (modsToMove.size() == 1) { - m_OrganizerCore.modList()->changeModPriority(modsToMove[0], newPriority); - } - else { - m_OrganizerCore.modList()->changeModPriority(modsToMove, newPriority); - } - } -} - -void MainWindow::sendSelectedModsToTop_clicked() -{ - sendSelectedModsToPriority(0); -} - -void MainWindow::sendSelectedModsToBottom_clicked() -{ - sendSelectedModsToPriority(INT_MAX); -} - -void MainWindow::sendSelectedModsToPriority_clicked() -{ - bool ok; - int newPriority = QInputDialog::getInt(this, - tr("Set Priority"), tr("Set the priority of the selected mods"), - 0, 0, INT_MAX, 1, &ok); - if (!ok) return; - - sendSelectedModsToPriority(newPriority); -} - -void MainWindow::sendSelectedModsToSeparator_clicked() -{ - QStringList separators; - auto indexesByPriority = m_OrganizerCore.currentProfile()->getAllIndexesByPriority(); - for (auto iter = indexesByPriority.begin(); iter != indexesByPriority.end(); iter++) { - if ((iter->second != UINT_MAX)) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(iter->second); - if (modInfo->hasFlag(ModInfo::FLAG_SEPARATOR)) { - separators << modInfo->name().chopped(10); // Chops the "_separator" away from the name - } - } - } - - ListDialog dialog(this); - dialog.setWindowTitle("Select a separator..."); - dialog.setChoices(separators); - - if (dialog.exec() == QDialog::Accepted) { - QString result = dialog.getChoice(); - if (!result.isEmpty()) { - result += "_separator"; - - int newPriority = INT_MAX; - bool foundSection = false; - for (auto mod : m_OrganizerCore.modsSortedByProfilePriority(m_OrganizerCore.currentProfile())) { - unsigned int modIndex = ModInfo::getIndex(mod); - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - if (!foundSection && result.compare(mod) == 0) { - foundSection = true; - } else if (foundSection && modInfo->hasFlag(ModInfo::FLAG_SEPARATOR)) { - newPriority = m_OrganizerCore.currentProfile()->getModPriority(modIndex); - break; - } - } - - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection()) { - std::vector modsToMove; - for (QModelIndex idx : selection->selectedRows(ModList::COL_PRIORITY)) { - modsToMove.push_back(m_OrganizerCore.currentProfile()->modIndexByPriority(idx.data().toInt())); - } - if (modsToMove.size() == 1) { - int oldPriority = m_OrganizerCore.currentProfile()->getModPriority(modsToMove[0]); - if (oldPriority < newPriority) - --newPriority; - m_OrganizerCore.modList()->changeModPriority(modsToMove[0], newPriority); - } - else { - m_OrganizerCore.modList()->changeModPriority(modsToMove, newPriority); - } - } - } - } -} diff --git a/src/mainwindow.h b/src/mainwindow.h index 57f26220..790960e1 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -244,15 +244,12 @@ private: bool createBackup(const QString &filePath, const QDateTime &time); QString queryRestore(const QString &filePath); - void addModSendToContextMenu(QMenu *menu); void addPluginSendToContextMenu(QMenu *menu); QMenu *openFolderMenu(); void dropLocalFile(const QUrl &url, const QString &outputDir, bool move); - void sendSelectedModsToPriority(int newPriority); - void toggleMO2EndorseState(); void toggleUpdateAction(); @@ -374,10 +371,6 @@ private slots: void information_clicked(int modIndex); void enableSelectedMods_clicked(); void disableSelectedMods_clicked(); - void sendSelectedModsToTop_clicked(); - void sendSelectedModsToBottom_clicked(); - void sendSelectedModsToPriority_clicked(); - void sendSelectedModsToSeparator_clicked(); // data-tree context menu // pluginlist context menu diff --git a/src/modlist.cpp b/src/modlist.cpp index 7da6fe3b..22899aaa 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -1417,7 +1417,7 @@ QString ModList::getColumnToolTip(int column) const } } -void ModList::shiftMods(const QModelIndexList& indices, int offset) +void ModList::shiftModsPriority(const QModelIndexList& indices, int offset) { // retrieve the mod index and sort them by priority to avoid issue // when moving them @@ -1451,6 +1451,26 @@ void ModList::shiftMods(const QModelIndexList& indices, int offset) emit modPrioritiesChanged(allIndex); } +void ModList::changeModsPriority(const QModelIndexList& indices, int priority) +{ + if (indices.isEmpty()) { + return; + } + + std::vector allIndex; + for (auto& idx : indices) { + auto index = idx.data(IndexRole).toInt(); + allIndex.push_back(index); + } + + if (allIndex.size() == 1) { + changeModPriority(allIndex[0], priority); + } + else { + changeModPriority(allIndex, priority); + } +} + bool ModList::toggleState(const QModelIndexList& indices) { emit aboutToChangeData(); diff --git a/src/modlist.h b/src/modlist.h index 870978f9..cabd1f32 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -226,7 +226,11 @@ public slots: // shift the priority of mods at the given indices by the given offset // - void shiftMods(const QModelIndexList& indices, int offset); + void shiftModsPriority(const QModelIndexList& indices, int offset); + + // change the priority of the mods specified by the given indices + // + void changeModsPriority(const QModelIndexList& indices, int priority); // toggle the active state of mods at the given indices // diff --git a/src/modlistcontextmenu.cpp b/src/modlistcontextmenu.cpp index 41031eaa..c4a82e46 100644 --- a/src/modlistcontextmenu.cpp +++ b/src/modlistcontextmenu.cpp @@ -45,6 +45,7 @@ ModListContextMenu::ModListContextMenu(OrganizerCore& core, const QModelIndex& i QMenu(view) , m_core(core) , m_index() + , m_view(view) { if (view->selectionModel()->hasSelection()) { m_index = view->indexViewToModel(view->selectionModel()->selectedRows()); @@ -68,20 +69,23 @@ ModListContextMenu::ModListContextMenu(OrganizerCore& core, const QModelIndex& i // Add type-specific items ModInfo::Ptr info = ModInfo::getByIndex(index.data(ModList::IndexRole).toInt()); + // TODO: + // - Don't forget to check for the sort priority for "Send To... " + if (info->isOverwrite()) { - addOverwriteActions(core, view); + addOverwriteActions(); } else if (info->isBackup()) { - addBackupActions(core, view); + addBackupActions(); } else if (info->isSeparator()) { - addSeparatorActions(core, view); + addSeparatorActions(); } else if (info->isForeign()) { - addForeignActions(core, view); + addForeignActions(); } else { - addRegularActions(core, view); + addRegularActions(); } // add information for all except foreign @@ -91,27 +95,40 @@ ModListContextMenu::ModListContextMenu(OrganizerCore& core, const QModelIndex& i } } -void ModListContextMenu::addOverwriteActions(OrganizerCore& core, ModListView* modListView) +QMenu* ModListContextMenu::createSendToContextMenu() { - + QMenu* menu = new QMenu(m_view); + menu->setTitle(tr("Send to... ")); + menu->addAction(tr("Top"), [=]() { m_view->actions().sendModsToTop(m_index); }); + menu->addAction(tr("Bottom"), [=]() { m_view->actions().sendModsToBottom(m_index); }); + menu->addAction(tr("Priority..."), [=]() { m_view->actions().sendModsToPriority(m_index); }); + menu->addAction(tr("Separator..."), [=]() { m_view->actions().sendModsToSeparator(m_index); }); + return menu; } -void ModListContextMenu::addSeparatorActions(OrganizerCore& core, ModListView* modListView) +void ModListContextMenu::addOverwriteActions() { } -void ModListContextMenu::addForeignActions(OrganizerCore& core, ModListView* modListView) +void ModListContextMenu::addSeparatorActions() { } -void ModListContextMenu::addBackupActions(OrganizerCore& core, ModListView* modListView) +void ModListContextMenu::addForeignActions() +{ + if (m_view->sortColumn() == ModList::COL_PRIORITY) { + addMenu(createSendToContextMenu()); + } +} + +void ModListContextMenu::addBackupActions() { } -void ModListContextMenu::addRegularActions(OrganizerCore& core, ModListView* modListView) +void ModListContextMenu::addRegularActions() { } diff --git a/src/modlistcontextmenu.h b/src/modlistcontextmenu.h index 9d015afc..3bc15c57 100644 --- a/src/modlistcontextmenu.h +++ b/src/modlistcontextmenu.h @@ -29,18 +29,23 @@ public: // ModListContextMenu(OrganizerCore& core, const QModelIndex& index, ModListView* modListView); -private: +public: // TODO: Move this to private when all is done + + // create the "Send to... " context menu + // + QMenu* createSendToContextMenu(); // add actions/menus to this menu for each type of mod // - void addOverwriteActions(OrganizerCore& core, ModListView* modListView); - void addSeparatorActions(OrganizerCore& core, ModListView* modListView); - void addForeignActions(OrganizerCore& core, ModListView* modListView); - void addBackupActions(OrganizerCore& core, ModListView* modListView); - void addRegularActions(OrganizerCore& core, ModListView* modListView); + void addOverwriteActions(); + void addSeparatorActions(); + void addForeignActions(); + void addBackupActions(); + void addRegularActions(); OrganizerCore& m_core; QModelIndexList m_index; + ModListView* m_view; }; diff --git a/src/modlistview.cpp b/src/modlistview.cpp index f8192758..8c826882 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -575,7 +575,7 @@ bool ModListView::moveSelection(int key) offset = -offset; } - m_core->modList()->shiftMods(sourceRows, offset); + m_core->modList()->shiftModsPriority(sourceRows, offset); // reset the selection and the index setCurrentIndex(indexModelToView(cindex)); diff --git a/src/modlistviewactions.cpp b/src/modlistviewactions.cpp index 6faebc15..0d556e64 100644 --- a/src/modlistviewactions.cpp +++ b/src/modlistviewactions.cpp @@ -11,6 +11,7 @@ #include "categories.h" #include "filedialogmemory.h" #include "filterlist.h" +#include "listdialog.h" #include "modinfodialog.h" #include "modlist.h" #include "modlistview.h" @@ -430,3 +431,70 @@ void ModListViewActions::displayModInformation(ModInfo::Ptr modInfo, unsigned in } } } + +void ModListViewActions::sendModsToTop(const QModelIndexList& index) const +{ + m_core.modList()->changeModsPriority(index, 0); +} + +void ModListViewActions::sendModsToBottom(const QModelIndexList& index) const +{ + m_core.modList()->changeModsPriority(index, std::numeric_limits::max()); +} + +void ModListViewActions::sendModsToPriority(const QModelIndexList& index) const +{ + bool ok; + int priority = QInputDialog::getInt(m_view, + tr("Set Priority"), tr("Set the priority of the selected mods"), + 0, 0, std::numeric_limits::max(), 1, &ok); + if (!ok) return; + + m_core.modList()->changeModsPriority(index, priority); +} + +void ModListViewActions::sendModsToSeparator(const QModelIndexList& index) const +{ + QStringList separators; + auto indexesByPriority = m_core.currentProfile()->getAllIndexesByPriority(); + for (auto iter = indexesByPriority.begin(); iter != indexesByPriority.end(); iter++) { + if ((iter->second != UINT_MAX)) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(iter->second); + if (modInfo->hasFlag(ModInfo::FLAG_SEPARATOR)) { + separators << modInfo->name().chopped(10); // Chops the "_separator" away from the name + } + } + } + + ListDialog dialog(m_view); + dialog.setWindowTitle("Select a separator..."); + dialog.setChoices(separators); + + if (dialog.exec() == QDialog::Accepted) { + QString result = dialog.getChoice(); + if (!result.isEmpty()) { + result += "_separator"; + + int newPriority = std::numeric_limits::max(); + bool foundSection = false; + for (auto mod : m_core.modsSortedByProfilePriority(m_core.currentProfile())) { + unsigned int modIndex = ModInfo::getIndex(mod); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + if (!foundSection && result.compare(mod) == 0) { + foundSection = true; + } + else if (foundSection && modInfo->isSeparator()) { + newPriority = m_core.currentProfile()->getModPriority(modIndex); + break; + } + } + + if (index.size() == 1 + && m_core.currentProfile()->getModPriority(index[0].data(ModList::IndexRole).toInt()) < newPriority) { + --newPriority; + } + + m_core.modList()->changeModsPriority(index, newPriority); + } + } +} diff --git a/src/modlistviewactions.h b/src/modlistviewactions.h index b01b8e79..d8e1a3d0 100644 --- a/src/modlistviewactions.h +++ b/src/modlistviewactions.h @@ -53,6 +53,12 @@ public: void displayModInformation(unsigned int index, ModInfoTabIDs tab = ModInfoTabIDs::None) const; void displayModInformation(ModInfo::Ptr modInfo, unsigned int modIndex, ModInfoTabIDs tabID = ModInfoTabIDs::None) const; + // move mods to top/bottom, start the "Send to priority" and "Send to separator" dialog + // + void sendModsToTop(const QModelIndexList& index) const; + void sendModsToBottom(const QModelIndexList& index) const; + void sendModsToPriority(const QModelIndexList& index) const; + void sendModsToSeparator(const QModelIndexList& index) const; private: -- cgit v1.3.1 From 7f0c9b8d8278f14754b375967267ff67d6fdb6ee Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 00:32:15 +0100 Subject: Move the overwrite context menu. --- src/mainwindow.cpp | 154 +++------------------------------------------ src/mainwindow.h | 12 ---- src/modlistcontextmenu.cpp | 44 +++++++------ src/modlistcontextmenu.h | 15 +++-- src/modlistviewactions.cpp | 128 ++++++++++++++++++++++++++++++++++++- src/modlistviewactions.h | 20 ++++++ src/organizercore.cpp | 2 - 7 files changed, 188 insertions(+), 187 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 91897d2f..056eeef7 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -535,14 +535,17 @@ MainWindow::MainWindow(Settings &settings void MainWindow::setupModList() { - ui->modList->setup(m_OrganizerCore, new ModListViewActions(m_OrganizerCore, *m_Filters, m_CategoryFactory, this, ui->modList), ui); + auto* actions = new ModListViewActions(m_OrganizerCore, *m_Filters, m_CategoryFactory, this, ui->modList); + ui->modList->setup(m_OrganizerCore, actions, ui); + connect(actions, &ModListViewActions::overwriteCleared, [=]() { scheduleCheckForProblems(); }); connect(ui->modList, &ModListView::removeSelectedMods, [=]() { removeMod_clicked(-1); }); + connect(m_OrganizerCore.modList(), &ModList::clearOverwrite, actions, &ModListViewActions::clearOverwrite); + connect(m_OrganizerCore.modList(), &ModList::modPrioritiesChanged, [&]() { m_ArchiveListWriter.write(); }); // keep here for now connect(ui->modList->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::modlistSelectionsChanged); - connect(m_OrganizerCore.modList(), &ModList::modPrioritiesChanged, [&]() { m_ArchiveListWriter.write(); }); } void MainWindow::resetActionIcons() @@ -2925,21 +2928,6 @@ void MainWindow::visitNexusOrWebPage_clicked(int index) { } } -void MainWindow::openExplorer_clicked(int index) -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); - shell::Explore(info->absolutePath()); - } - } - else { - ModInfo::Ptr modInfo = ModInfo::getByIndex(index); - shell::Explore(modInfo->absolutePath()); - } -} - void MainWindow::openPluginOriginExplorer_clicked() { QItemSelectionModel *selection = ui->espList->selectionModel(); @@ -3121,127 +3109,6 @@ void MainWindow::resetColor_clicked(int modIndex) m_OrganizerCore.settings().colors().removePreviousSeparatorColor(); } -void MainWindow::createModFromOverwrite() -{ - GuessedValue name; - name.setFilter(&fixDirectoryName); - - while (name->isEmpty()) { - bool ok; - name.update(QInputDialog::getText(this, tr("Create Mod..."), - tr("This will move all files from overwrite into a new, regular mod.\n" - "Please enter a name:"), QLineEdit::Normal, "", &ok), - GUESS_USER); - if (!ok) { - return; - } - } - - if (m_OrganizerCore.modList()->getMod(name) != nullptr) { - reportError(tr("A mod with this name already exists")); - return; - } - - const IModInterface *newMod = m_OrganizerCore.createMod(name); - if (newMod == nullptr) { - return; - } - - doMoveOverwriteContentToMod(newMod->absolutePath()); -} - -void MainWindow::moveOverwriteContentToExistingMod() -{ - QStringList mods; - auto indexesByPriority = m_OrganizerCore.currentProfile()->getAllIndexesByPriority(); - for (auto & iter : indexesByPriority) { - if ((iter.second != UINT_MAX)) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(iter.second); - if (!modInfo->hasFlag(ModInfo::FLAG_SEPARATOR) && !modInfo->hasFlag(ModInfo::FLAG_FOREIGN) && !modInfo->hasFlag(ModInfo::FLAG_OVERWRITE)) { - mods << modInfo->name(); - } - } - } - - ListDialog dialog(this); - dialog.setWindowTitle("Select a mod..."); - dialog.setChoices(mods); - - if (dialog.exec() == QDialog::Accepted) { - QString result = dialog.getChoice(); - if (!result.isEmpty()) { - - QString modAbsolutePath; - - for (const auto& mod : m_OrganizerCore.modsSortedByProfilePriority(m_OrganizerCore.currentProfile())) { - if (result.compare(mod) == 0) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(mod)); - modAbsolutePath = modInfo->absolutePath(); - break; - } - } - - if (modAbsolutePath.isNull()) { - log::warn("Mod {} has not been found, for some reason", result); - return; - } - - doMoveOverwriteContentToMod(modAbsolutePath); - } - } -} - -void MainWindow::doMoveOverwriteContentToMod(const QString &modAbsolutePath) -{ - unsigned int overwriteIndex = ModInfo::findMod([](ModInfo::Ptr mod) -> bool { - std::vector flags = mod->getFlags(); - return std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end(); }); - - ModInfo::Ptr overwriteInfo = ModInfo::getByIndex(overwriteIndex); - bool successful = shellMove((QDir::toNativeSeparators(overwriteInfo->absolutePath()) + "\\*"), - (QDir::toNativeSeparators(modAbsolutePath)), false, this); - - if (successful) { - MessageDialog::showMessage(tr("Move successful."), this); - } - else { - const auto e = GetLastError(); - log::error("Move operation failed: {}", formatSystemMessage(e)); - } - - m_OrganizerCore.refresh(); -} - -void MainWindow::clearOverwrite() -{ - unsigned int overwriteIndex = ModInfo::findMod([](ModInfo::Ptr mod) -> bool { - std::vector flags = mod->getFlags(); - return std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) - != flags.end(); - }); - - ModInfo::Ptr modInfo = ModInfo::getByIndex(overwriteIndex); - if (modInfo) - { - QDir overwriteDir(modInfo->absolutePath()); - if (QMessageBox::question(this, tr("Are you sure?"), - tr("About to recursively delete:\n") + overwriteDir.absolutePath(), - QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok) - { - QStringList delList; - for (auto f : overwriteDir.entryList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot)) - delList.push_back(overwriteDir.absoluteFilePath(f)); - if (shellDelete(delList, true)) { - scheduleCheckForProblems(); - m_OrganizerCore.refresh(); - } else { - const auto e = GetLastError(); - log::error("Delete operation failed: {}", formatSystemMessage(e)); - } - } - } -} - void MainWindow::cancelModListEditor() { ui->modList->setEnabled(false); @@ -3869,13 +3736,6 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) // context menu for overwrites if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) { - if (QDir(info->absolutePath()).count() > 2) { - menu.addAction(tr("Sync to Mods..."), [=]() { m_OrganizerCore.syncOverwrite(); }); - menu.addAction(tr("Create Mod..."), [=]() { createModFromOverwrite(); }); - menu.addAction(tr("Move content to Mod..."), [=]() { moveOverwriteContentToExistingMod(); }); - menu.addAction(tr("Clear Overwrite..."), [=]() { clearOverwrite(); }); - } - menu.addAction(tr("Open in Explorer"), [=]() { openExplorer_clicked(modIndex); }); } // context menu for mod backups @@ -3899,7 +3759,7 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) menu.addAction(tr("Visit on %1").arg(url.host()), [=]() { visitWebPage_clicked(modIndex); }); } - menu.addAction(tr("Open in Explorer"), [=]() { openExplorer_clicked(modIndex); }); + menu.addAction(tr("Open in Explorer"), [=]() { ui->modList->actions().openExplorer({ contextIdx }); }); } // separator @@ -4049,7 +3909,7 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) menu.addAction(tr("Visit on %1").arg(url.host()), [=]() { visitWebPage_clicked(modIndex); }); } - menu.addAction(tr("Open in Explorer"), [&, modIndex]() { openExplorer_clicked(modIndex); }); + menu.addAction(tr("Open in Explorer"), [=]() { ui->modList->actions().openExplorer({ contextIdx }); }); } if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) == flags.end()) { diff --git a/src/mainwindow.h b/src/mainwindow.h index 790960e1..21c8f2aa 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -365,7 +365,6 @@ private slots: void visitOnNexus_clicked(int modIndex); void visitWebPage_clicked(int modIndex); void visitNexusOrWebPage_clicked(int modIndex); - void openExplorer_clicked(int modIndex); void openPluginOriginExplorer_clicked(); void openOriginInformation_clicked(); void information_clicked(int modIndex); @@ -390,17 +389,6 @@ private slots: BSA::EErrorCode extractBSA(BSA::Archive &archive, BSA::Folder::Ptr folder, const QString &destination, QProgressDialog &extractProgress); - void createModFromOverwrite(); - /** - * @brief sends the content of the overwrite folder to an already existing mod - */ - void moveOverwriteContentToExistingMod(); - /** - * @brief actually sends the content of the overwrite folder to specified mod - */ - void doMoveOverwriteContentToMod(const QString &modAbsolutePath); - void clearOverwrite(); - // nexus related void checkModsForUpdates(); diff --git a/src/modlistcontextmenu.cpp b/src/modlistcontextmenu.cpp index c4a82e46..dda88735 100644 --- a/src/modlistcontextmenu.cpp +++ b/src/modlistcontextmenu.cpp @@ -44,14 +44,14 @@ ModListGlobalContextMenu::ModListGlobalContextMenu(OrganizerCore& core, ModListV ModListContextMenu::ModListContextMenu(OrganizerCore& core, const QModelIndex& index, ModListView* view) : QMenu(view) , m_core(core) - , m_index() + , m_index(index) , m_view(view) { if (view->selectionModel()->hasSelection()) { - m_index = view->indexViewToModel(view->selectionModel()->selectedRows()); + m_selected = view->indexViewToModel(view->selectionModel()->selectedRows()); } else { - m_index = { index }; + m_selected = { index }; } @@ -73,24 +73,24 @@ ModListContextMenu::ModListContextMenu(OrganizerCore& core, const QModelIndex& i // - Don't forget to check for the sort priority for "Send To... " if (info->isOverwrite()) { - addOverwriteActions(); + addOverwriteActions(info); } else if (info->isBackup()) { - addBackupActions(); + addBackupActions(info); } else if (info->isSeparator()) { - addSeparatorActions(); + addSeparatorActions(info); } else if (info->isForeign()) { - addForeignActions(); + addForeignActions(info); } else { - addRegularActions(); + addRegularActions(info); } // add information for all except foreign if (!info->isForeign()) { - QAction* infoAction = addAction(tr("Information..."), [=]() { view->actions().displayModInformation(m_index[0].row()); }); + QAction* infoAction = addAction(tr("Information..."), [=]() { view->actions().displayModInformation(m_index.data(ModList::IndexRole).toInt()); }); setDefaultAction(infoAction); } } @@ -99,36 +99,42 @@ QMenu* ModListContextMenu::createSendToContextMenu() { QMenu* menu = new QMenu(m_view); menu->setTitle(tr("Send to... ")); - menu->addAction(tr("Top"), [=]() { m_view->actions().sendModsToTop(m_index); }); - menu->addAction(tr("Bottom"), [=]() { m_view->actions().sendModsToBottom(m_index); }); - menu->addAction(tr("Priority..."), [=]() { m_view->actions().sendModsToPriority(m_index); }); - menu->addAction(tr("Separator..."), [=]() { m_view->actions().sendModsToSeparator(m_index); }); + menu->addAction(tr("Top"), [=]() { m_view->actions().sendModsToTop(m_selected); }); + menu->addAction(tr("Bottom"), [=]() { m_view->actions().sendModsToBottom(m_selected); }); + menu->addAction(tr("Priority..."), [=]() { m_view->actions().sendModsToPriority(m_selected); }); + menu->addAction(tr("Separator..."), [=]() { m_view->actions().sendModsToSeparator(m_selected); }); return menu; } -void ModListContextMenu::addOverwriteActions() +void ModListContextMenu::addOverwriteActions(ModInfo::Ptr mod) { - + if (QDir(mod->absolutePath()).count() > 2) { + addAction(tr("Sync to Mods..."), [=]() { m_core.syncOverwrite(); }); + addAction(tr("Create Mod..."), [=]() { m_view->actions().createModFromOverwrite(); }); + addAction(tr("Move content to Mod..."), [=]() { m_view->actions().moveOverwriteContentToExistingMod(); }); + addAction(tr("Clear Overwrite..."), [=]() { m_view->actions().clearOverwrite(); }); + } + addAction(tr("Open in Explorer"), [=]() { m_view->actions().openExplorer(m_selected); }); } -void ModListContextMenu::addSeparatorActions() +void ModListContextMenu::addSeparatorActions(ModInfo::Ptr mod) { } -void ModListContextMenu::addForeignActions() +void ModListContextMenu::addForeignActions(ModInfo::Ptr mod) { if (m_view->sortColumn() == ModList::COL_PRIORITY) { addMenu(createSendToContextMenu()); } } -void ModListContextMenu::addBackupActions() +void ModListContextMenu::addBackupActions(ModInfo::Ptr mod) { } -void ModListContextMenu::addRegularActions() +void ModListContextMenu::addRegularActions(ModInfo::Ptr mod) { } diff --git a/src/modlistcontextmenu.h b/src/modlistcontextmenu.h index 3bc15c57..22318575 100644 --- a/src/modlistcontextmenu.h +++ b/src/modlistcontextmenu.h @@ -7,6 +7,8 @@ #include #include +#include "modinfo.h" + class ModListView; class OrganizerCore; @@ -37,14 +39,15 @@ public: // TODO: Move this to private when all is done // add actions/menus to this menu for each type of mod // - void addOverwriteActions(); - void addSeparatorActions(); - void addForeignActions(); - void addBackupActions(); - void addRegularActions(); + void addOverwriteActions(ModInfo::Ptr mod); + void addSeparatorActions(ModInfo::Ptr mod); + void addForeignActions(ModInfo::Ptr mod); + void addBackupActions(ModInfo::Ptr mod); + void addRegularActions(ModInfo::Ptr mod); OrganizerCore& m_core; - QModelIndexList m_index; + QModelIndex m_index; + QModelIndexList m_selected; ModListView* m_view; }; diff --git a/src/modlistviewactions.cpp b/src/modlistviewactions.cpp index 0d556e64..a07fb27c 100644 --- a/src/modlistviewactions.cpp +++ b/src/modlistviewactions.cpp @@ -7,6 +7,7 @@ #include #include +#include #include "categories.h" #include "filedialogmemory.h" @@ -16,6 +17,7 @@ #include "modlist.h" #include "modlistview.h" #include "mainwindow.h" +#include "messagedialog.h" #include "nexusinterface.h" #include "nxmaccessmanager.h" #include "savetextasdialog.h" @@ -387,7 +389,11 @@ void ModListViewActions::displayModInformation(ModInfo::Ptr modInfo, unsigned in dialog->show(); dialog->raise(); dialog->activateWindow(); - connect(dialog, SIGNAL(finished(int)), this, SLOT(overwriteClosed(int))); + 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())); @@ -498,3 +504,123 @@ void ModListViewActions::sendModsToSeparator(const QModelIndexList& index) const } } } + +void ModListViewActions::openExplorer(const QModelIndexList& index) const +{ + for (auto& idx : index) { + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); + shell::Explore(info->absolutePath()); + } +} + +void ModListViewActions::moveOverwriteContentsTo(const QString& absolutePath) const +{ + ModInfo::Ptr overwriteInfo = ModInfo::getOverwrite(); + bool successful = shellMove((QDir::toNativeSeparators(overwriteInfo->absolutePath()) + "\\*"), + (QDir::toNativeSeparators(absolutePath)), false, m_view); + + if (successful) { + MessageDialog::showMessage(tr("Move successful."), m_view); + } + else { + const auto e = GetLastError(); + log::error("Move operation failed: {}", formatSystemMessage(e)); + } + + m_core.refresh(); +} + +void ModListViewActions::createModFromOverwrite() const +{ + GuessedValue name; + name.setFilter(&fixDirectoryName); + + while (name->isEmpty()) { + bool ok; + name.update(QInputDialog::getText(m_view, tr("Create Mod..."), + tr("This will move all files from overwrite into a new, regular 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; + } + + const IModInterface* newMod = m_core.createMod(name); + if (newMod == nullptr) { + return; + } + + moveOverwriteContentsTo(newMod->absolutePath()); +} + +void ModListViewActions::moveOverwriteContentToExistingMod() const +{ + QStringList mods; + auto indexesByPriority = m_core.currentProfile()->getAllIndexesByPriority(); + for (auto& iter : indexesByPriority) { + if ((iter.second != UINT_MAX)) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(iter.second); + if (!modInfo->hasFlag(ModInfo::FLAG_SEPARATOR) && !modInfo->hasFlag(ModInfo::FLAG_FOREIGN) && !modInfo->hasFlag(ModInfo::FLAG_OVERWRITE)) { + mods << modInfo->name(); + } + } + } + + ListDialog dialog(m_view); + dialog.setWindowTitle("Select a mod..."); + dialog.setChoices(mods); + + if (dialog.exec() == QDialog::Accepted) { + QString result = dialog.getChoice(); + if (!result.isEmpty()) { + + QString modAbsolutePath; + + for (const auto& mod : m_core.modsSortedByProfilePriority(m_core.currentProfile())) { + if (result.compare(mod) == 0) { + ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(mod)); + modAbsolutePath = modInfo->absolutePath(); + break; + } + } + + if (modAbsolutePath.isNull()) { + log::warn("Mod {} has not been found, for some reason", result); + return; + } + + moveOverwriteContentsTo(modAbsolutePath); + } + } +} + +void ModListViewActions::clearOverwrite() const +{ + ModInfo::Ptr modInfo = ModInfo::getOverwrite(); + if (modInfo) + { + QDir overwriteDir(modInfo->absolutePath()); + if (QMessageBox::question(m_view, tr("Are you sure?"), + tr("About to recursively delete:\n") + overwriteDir.absolutePath(), + QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok) + { + QStringList delList; + for (auto f : overwriteDir.entryList(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot)) + delList.push_back(overwriteDir.absoluteFilePath(f)); + if (shellDelete(delList, true)) { + emit overwriteCleared(); + m_core.refresh(); + } + else { + const auto e = GetLastError(); + log::error("Delete operation failed: {}", formatSystemMessage(e)); + } + } + } +} diff --git a/src/modlistviewactions.h b/src/modlistviewactions.h index d8e1a3d0..10aa6c39 100644 --- a/src/modlistviewactions.h +++ b/src/modlistviewactions.h @@ -60,6 +60,26 @@ public: void sendModsToPriority(const QModelIndexList& index) const; void sendModsToSeparator(const QModelIndexList& index) const; + // open the Windows explorer for the specified mods + // + void openExplorer(const QModelIndexList& index) const; + + // overwrite-specific actions + // + void createModFromOverwrite() const; + void moveOverwriteContentToExistingMod() const; + void clearOverwrite() const; + +signals: + + // emitted when the overwrite mod has been clear + // + void overwriteCleared() const; + +private: + + void moveOverwriteContentsTo(const QString& absolutePath) const; + private: OrganizerCore& m_core; diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 986b6fbb..507932e2 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -249,8 +249,6 @@ void OrganizerCore::setUserInterface(IUserInterface* ui) SLOT(modRemoved(QString))); connect(&m_InstallationManager, SIGNAL(modReplaced(QString)), w, SLOT(modRemoved(QString))); - connect(&m_ModList, SIGNAL(clearOverwrite()), w, - SLOT(clearOverwrite())); connect(&m_ModList, SIGNAL(fileMoved(QString, QString, QString)), w, SLOT(fileMoved(QString, QString, QString))); connect(&m_PluginList, SIGNAL(writePluginsList()), w, -- cgit v1.3.1 From 4ee929b68a5ba3f622fd6cecf37f61b983eb0874 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 00:55:49 +0100 Subject: Move the backup context menu. --- src/mainwindow.cpp | 48 +------------ src/mainwindow.h | 4 +- src/modlistcontextmenu.cpp | 37 +++++++--- src/modlistcontextmenu.h | 2 + src/modlistviewactions.cpp | 171 +++++++++++++++++++++++++++++++++++++++++++++ src/modlistviewactions.h | 11 +++ 6 files changed, 216 insertions(+), 57 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 056eeef7..6942f83b 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2365,32 +2365,6 @@ void MainWindow::renameMod_clicked() } } - -void MainWindow::restoreBackup_clicked(int modIndex) -{ - QRegExp backupRegEx("(.*)_backup[0-9]*$"); - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - if (backupRegEx.indexIn(modInfo->name()) != -1) { - QString regName = backupRegEx.cap(1); - QDir modDir(QDir::fromNativeSeparators(m_OrganizerCore.settings().paths().mods())); - if (!modDir.exists(regName) || - (QMessageBox::question(this, tr("Overwrite?"), - tr("This will replace the existing mod \"%1\". Continue?").arg(regName), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)) { - if (modDir.exists(regName) && !shellDelete(QStringList(modDir.absoluteFilePath(regName)))) { - reportError(tr("failed to remove mod \"%1\"").arg(regName)); - } else { - QString destinationPath = QDir::fromNativeSeparators(m_OrganizerCore.settings().paths().mods()) + "/" + regName; - if (!modDir.rename(modInfo->absolutePath(), destinationPath)) { - reportError(tr("failed to rename \"%1\" to \"%2\"").arg(modInfo->absolutePath()).arg(destinationPath)); - } - m_OrganizerCore.refresh(); - ui->modList->updateModCount(); - } - } - } -} - void MainWindow::modlistChanged(const QModelIndex&, int) { m_OrganizerCore.currentProfile()->writeModlist(); @@ -2850,7 +2824,7 @@ void MainWindow::visitOnNexus_clicked(int modIndex) void MainWindow::visitWebPage_clicked(int index) { - QItemSelectionModel *selection = ui->modList->selectionModel(); + QItemSelectionModel* selection = ui->modList->selectionModel(); if (selection->hasSelection() && selection->selectedRows().count() > 1) { int count = selection->selectedRows().count(); if (count > 10) { @@ -3740,26 +3714,6 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) // context menu for mod backups else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) != flags.end()) { - menu.addAction(tr("Restore Backup"), [=]() { restoreBackup_clicked(modIndex); }); - menu.addAction(tr("Remove Backup..."), [=]() { removeMod_clicked(modIndex); }); - menu.addSeparator(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_INVALID) != flags.end()) { - menu.addAction(tr("Ignore missing data"), [=]() { ignoreMissingData_clicked(modIndex); }); - } - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_ALTERNATE_GAME) != flags.end()) { - menu.addAction(tr("Mark as converted/working"), [=]() { markConverted_clicked(modIndex); }); - } - menu.addSeparator(); - if (info->nexusId() > 0) { - menu.addAction(tr("Visit on Nexus"), [=]() { visitOnNexus_clicked(modIndex); }); - } - - const auto url = info->parseCustomURL(); - if (url.isValid()) { - menu.addAction(tr("Visit on %1").arg(url.host()), [=]() { visitWebPage_clicked(modIndex); }); - } - - menu.addAction(tr("Open in Explorer"), [=]() { ui->modList->actions().openExplorer({ contextIdx }); }); } // separator diff --git a/src/mainwindow.h b/src/mainwindow.h index 21c8f2aa..49ecee32 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -151,6 +151,8 @@ public slots: void directory_refreshed(); + void updatePluginCount(); + signals: /** @@ -347,7 +349,6 @@ private slots: // modlist context menu void installMod_clicked(); - void restoreBackup_clicked(int modIndex); void renameMod_clicked(); void removeMod_clicked(int modIndex); void setColor_clicked(int modIndex); @@ -498,7 +499,6 @@ private slots: void esplistSelectionsChanged(const QItemSelection ¤t); void resetActionIcons(); - void updatePluginCount(); private slots: // ui slots // actions diff --git a/src/modlistcontextmenu.cpp b/src/modlistcontextmenu.cpp index dda88735..df80f0d9 100644 --- a/src/modlistcontextmenu.cpp +++ b/src/modlistcontextmenu.cpp @@ -46,6 +46,7 @@ ModListContextMenu::ModListContextMenu(OrganizerCore& core, const QModelIndex& i , m_core(core) , m_index(index) , m_view(view) + , m_actions(view->actions()) { if (view->selectionModel()->hasSelection()) { m_selected = view->indexViewToModel(view->selectionModel()->selectedRows()); @@ -99,10 +100,10 @@ QMenu* ModListContextMenu::createSendToContextMenu() { QMenu* menu = new QMenu(m_view); menu->setTitle(tr("Send to... ")); - menu->addAction(tr("Top"), [=]() { m_view->actions().sendModsToTop(m_selected); }); - menu->addAction(tr("Bottom"), [=]() { m_view->actions().sendModsToBottom(m_selected); }); - menu->addAction(tr("Priority..."), [=]() { m_view->actions().sendModsToPriority(m_selected); }); - menu->addAction(tr("Separator..."), [=]() { m_view->actions().sendModsToSeparator(m_selected); }); + menu->addAction(tr("Top"), [=]() { m_actions.sendModsToTop(m_selected); }); + menu->addAction(tr("Bottom"), [=]() { m_actions.sendModsToBottom(m_selected); }); + menu->addAction(tr("Priority..."), [=]() { m_actions.sendModsToPriority(m_selected); }); + menu->addAction(tr("Separator..."), [=]() { m_actions.sendModsToSeparator(m_selected); }); return menu; } @@ -110,11 +111,11 @@ void ModListContextMenu::addOverwriteActions(ModInfo::Ptr mod) { if (QDir(mod->absolutePath()).count() > 2) { addAction(tr("Sync to Mods..."), [=]() { m_core.syncOverwrite(); }); - addAction(tr("Create Mod..."), [=]() { m_view->actions().createModFromOverwrite(); }); - addAction(tr("Move content to Mod..."), [=]() { m_view->actions().moveOverwriteContentToExistingMod(); }); - addAction(tr("Clear Overwrite..."), [=]() { m_view->actions().clearOverwrite(); }); + addAction(tr("Create Mod..."), [=]() { m_actions.createModFromOverwrite(); }); + addAction(tr("Move content to Mod..."), [=]() { m_actions.moveOverwriteContentToExistingMod(); }); + addAction(tr("Clear Overwrite..."), [=]() { m_actions.clearOverwrite(); }); } - addAction(tr("Open in Explorer"), [=]() { m_view->actions().openExplorer(m_selected); }); + addAction(tr("Open in Explorer"), [=]() { m_actions.openExplorer(m_selected); }); } void ModListContextMenu::addSeparatorActions(ModInfo::Ptr mod) @@ -131,7 +132,27 @@ void ModListContextMenu::addForeignActions(ModInfo::Ptr mod) void ModListContextMenu::addBackupActions(ModInfo::Ptr mod) { + auto flags = mod->getFlags(); + addAction(tr("Restore Backup"), [=]() { m_actions.restoreBackup(m_index); }); + addAction(tr("Remove Backup..."), [=]() { m_actions.removeMods(m_selected); }); + addSeparator(); + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_INVALID) != flags.end()) { + addAction(tr("Ignore missing data"), [=]() { m_actions.ignoreMissingData(m_selected); }); + } + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_ALTERNATE_GAME) != flags.end()) { + addAction(tr("Mark as converted/working"), [=]() { m_actions.markConverted(m_selected); }); + } + addSeparator(); + if (mod->nexusId() > 0) { + addAction(tr("Visit on Nexus"), [=]() { m_actions.visitOnNexus(m_selected); }); + } + + const auto url = mod->parseCustomURL(); + if (url.isValid()) { + addAction(tr("Visit on %1").arg(url.host()), [=]() { m_actions.visitWebPage(m_selected); }); + } + addAction(tr("Open in Explorer"), [=]() { m_actions.openExplorer(m_selected); }); } void ModListContextMenu::addRegularActions(ModInfo::Ptr mod) diff --git a/src/modlistcontextmenu.h b/src/modlistcontextmenu.h index 22318575..05e6b601 100644 --- a/src/modlistcontextmenu.h +++ b/src/modlistcontextmenu.h @@ -10,6 +10,7 @@ #include "modinfo.h" class ModListView; +class ModListViewActions; class OrganizerCore; class ModListGlobalContextMenu : public QMenu @@ -49,6 +50,7 @@ public: // TODO: Move this to private when all is done QModelIndex m_index; QModelIndexList m_selected; ModListView* m_view; + ModListViewActions& m_actions; // shortcut for m_view->actions() }; diff --git a/src/modlistviewactions.cpp b/src/modlistviewactions.cpp index a07fb27c..53c29a5d 100644 --- a/src/modlistviewactions.cpp +++ b/src/modlistviewactions.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -505,6 +506,150 @@ void ModListViewActions::sendModsToSeparator(const QModelIndexList& index) const } } +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 += "
  • " + name + "
  • "; + } + else if (i == max_items) { + mods += "
  • ...
  • "; + } + + modNames.append(ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->name()); + ++i; + } + if (QMessageBox::question(m_view, tr("Confirm"), + tr("Remove the following mods?
      %1
    ").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_main->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::markConverted(const QModelIndexList& indices) const +{ + for (auto& idx : indices) { + int row_idx = idx.data(ModList::IndexRole).toInt(); + ModInfo::Ptr info = ModInfo::getByIndex(row_idx); + info->markConverted(true); + m_core.modList()->notifyChange(row_idx); + } +} + +void ModListViewActions::visitOnNexus(const QModelIndexList& indices) const +{ + if (indices.size() > 1) { + if (indices.size() > 10) { + if (QMessageBox::question(m_view, 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; + } + } + int row_idx; + ModInfo::Ptr info; + QString gameName; + + for (auto& idx : indices) { + row_idx = idx.data(ModList::IndexRole).toInt(); + info = ModInfo::getByIndex(row_idx); + int modID = info->nexusId(); + gameName = info->gameName(); + if (modID > 0) { + shell::Open(QUrl(NexusInterface::instance().getModURL(modID, gameName))); + } + else { + log::error("mod '{}' has no nexus id", info->name()); + } + } + } + else if (!indices.isEmpty()) { + int modID = indices[0].data(Qt::UserRole).toInt(); + QString gameName = indices[0].data(Qt::UserRole + 4).toString(); + if (modID > 0) { + shell::Open(QUrl(NexusInterface::instance().getModURL(modID, gameName))); + } + else { + MessageDialog::showMessage(tr("Nexus ID for this mod is unknown"), m_view); + } + } +} + +void ModListViewActions::visitWebPage(const QModelIndexList& indices) const +{ + if (indices.size() > 1) { + if (indices.size() > 10) { + if (QMessageBox::question(m_view, 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; + } + } + int row_idx; + ModInfo::Ptr info; + QString gameName; + for (auto& idx : indices) { + row_idx = idx.data(ModList::IndexRole).toInt(); + info = ModInfo::getByIndex(row_idx); + + const auto url = info->parseCustomURL(); + if (url.isValid()) { + shell::Open(url); + } + } + } + else if (!indices.isEmpty()) { + ModInfo::Ptr info = ModInfo::getByIndex(indices[0].data(ModList::IndexRole).toInt()); + + const auto url = info->parseCustomURL(); + if (url.isValid()) { + shell::Open(url); + } + } +} + void ModListViewActions::openExplorer(const QModelIndexList& index) const { for (auto& idx : index) { @@ -513,6 +658,32 @@ void ModListViewActions::openExplorer(const QModelIndexList& index) const } } +void ModListViewActions::restoreBackup(const QModelIndex& index) const +{ + QRegExp backupRegEx("(.*)_backup[0-9]*$"); + ModInfo::Ptr modInfo = ModInfo::getByIndex(index.data(ModList::IndexRole).toInt()); + if (backupRegEx.indexIn(modInfo->name()) != -1) { + QString regName = backupRegEx.cap(1); + QDir modDir(QDir::fromNativeSeparators(m_core.settings().paths().mods())); + if (!modDir.exists(regName) || + (QMessageBox::question(m_view, tr("Overwrite?"), + tr("This will replace the existing mod \"%1\". Continue?").arg(regName), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)) { + if (modDir.exists(regName) && !shellDelete(QStringList(modDir.absoluteFilePath(regName)))) { + reportError(tr("failed to remove mod \"%1\"").arg(regName)); + } + else { + QString destinationPath = QDir::fromNativeSeparators(m_core.settings().paths().mods()) + "/" + regName; + if (!modDir.rename(modInfo->absolutePath(), destinationPath)) { + reportError(tr("failed to rename \"%1\" to \"%2\"").arg(modInfo->absolutePath()).arg(destinationPath)); + } + m_core.refresh(); + m_view->updateModCount(); + } + } + } +} + void ModListViewActions::moveOverwriteContentsTo(const QString& absolutePath) const { ModInfo::Ptr overwriteInfo = ModInfo::getOverwrite(); diff --git a/src/modlistviewactions.h b/src/modlistviewactions.h index 10aa6c39..05994813 100644 --- a/src/modlistviewactions.h +++ b/src/modlistviewactions.h @@ -60,10 +60,21 @@ public: void sendModsToPriority(const QModelIndexList& index) const; void sendModsToSeparator(const QModelIndexList& index) const; + // actions for most type of mods + void removeMods(const QModelIndexList& indices) const; + void ignoreMissingData(const QModelIndexList& indices) const; + void markConverted(const QModelIndexList& indices) const; + void visitOnNexus(const QModelIndexList& indices) const; + void visitWebPage(const QModelIndexList& indices) const; + // open the Windows explorer for the specified mods // void openExplorer(const QModelIndexList& index) const; + // backup-specific actions + // + void restoreBackup(const QModelIndex& index) const; + // overwrite-specific actions // void createModFromOverwrite() const; -- cgit v1.3.1 From 6e4b1790ae4057dfafd39dadff04c8d9b5f2eaeb Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 02:29:31 +0100 Subject: Move the separator context menu. --- src/mainwindow.cpp | 66 +------------------- src/mainwindow.h | 3 +- src/modlist.h | 2 + src/modlistcontextmenu.cpp | 150 +++++++++++++++++++++++++++++++++++++++++++-- src/modlistcontextmenu.h | 52 +++++++++++++++- src/modlistviewactions.cpp | 98 +++++++++++++++++++++++++++++ src/modlistviewactions.h | 29 ++++++++- 7 files changed, 325 insertions(+), 75 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 6942f83b..cd31a0bf 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -3363,45 +3363,6 @@ void MainWindow::addRemoveCategories_MenuHandler(QMenu* menu, int modIndex, cons refreshFilters(); } -void MainWindow::replaceCategories_MenuHandler(QMenu* menu, int modIndex) -{ - QList selected; - for (const QModelIndex &idx : ui->modList->selectionModel()->selectedRows()) { - selected.append(QPersistentModelIndex(idx)); - } - - if (selected.size() > 0) { - QStringList selectedMods; - int minRow = INT_MAX; - int maxRow = -1; - for (int i = 0; i < selected.size(); ++i) { - QModelIndex temp = mapToModel(m_OrganizerCore.modList(), selected.at(i)); - selectedMods.append(temp.data().toString()); - replaceCategoriesFromMenu(menu, mapToModel(m_OrganizerCore.modList(), selected.at(i)).row()); - if (temp.row() < minRow) minRow = temp.row(); - if (temp.row() > maxRow) maxRow = temp.row(); - } - - m_OrganizerCore.modList()->notifyChange(minRow, maxRow + 1); - - // find mods by their name because indices are invalidated - QAbstractItemModel *model = ui->modList->model(); - for (const QString &mod : selectedMods) { - QModelIndexList matches = model->match(model->index(0, 0), Qt::DisplayRole, mod, 1, - Qt::MatchFixedString | Qt::MatchCaseSensitive | Qt::MatchRecursive); - if (matches.size() > 0) { - ui->modList->selectionModel()->select(matches.at(0), QItemSelectionModel::Select | QItemSelectionModel::Rows); - } - } - } else { - //For single mod selections, just do a replace - replaceCategoriesFromMenu(menu, modIndex); - m_OrganizerCore.modList()->notifyChange(modIndex); - } - - refreshFilters(); -} - void MainWindow::saveArchiveList() { if (m_OrganizerCore.isArchivesInit()) { @@ -3703,7 +3664,7 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) int modIndex = ui->modList->indexAt(pos).data(ModList::IndexRole).toInt(); int contextColumn = contextIdx.column(); - ModListContextMenu menu(m_OrganizerCore, contextIdx, ui->modList); + ModListContextMenu menu(contextIdx, m_OrganizerCore, m_CategoryFactory, ui->modList); ModInfo::Ptr info = ModInfo::getByIndex(modIndex); std::vector flags = info->getFlags(); @@ -3718,29 +3679,6 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) // separator else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end()){ - menu.addSeparator(); - QMenu *addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); - populateMenuCategories(modIndex, addRemoveCategoriesMenu, 0); - connect(addRemoveCategoriesMenu, &QMenu::aboutToHide, [=]() { addRemoveCategories_MenuHandler(addRemoveCategoriesMenu, modIndex, contextIdx); }); - addMenuAsPushButton(&menu, addRemoveCategoriesMenu); - QMenu *primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); - connect(primaryCategoryMenu, &QMenu::aboutToShow, [=]() { setPrimaryCategoryCandidates(primaryCategoryMenu, info); }); - addMenuAsPushButton(&menu, primaryCategoryMenu); - menu.addSeparator(); - menu.addAction(tr("Rename Separator..."), [=]() { renameMod_clicked(); }); - menu.addAction(tr("Remove Separator..."), [=]() { removeMod_clicked(modIndex); }); - menu.addSeparator(); - if (ui->modList->sortColumn() == ModList::COL_PRIORITY) { - menu.addMenu(menu.createSendToContextMenu()); - menu.addSeparator(); - } - menu.addAction(tr("Select Color..."), [=]() { setColor_clicked(modIndex); }); - - if (info->color().isValid()) { - menu.addAction(tr("Reset Color"), [=]() { resetColor_clicked(modIndex); }); - } - - menu.addSeparator(); } // foregin @@ -3864,9 +3802,7 @@ void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) } menu.addAction(tr("Open in Explorer"), [=]() { ui->modList->actions().openExplorer({ contextIdx }); }); - } - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) == flags.end()) { QAction* infoAction = menu.addAction(tr("Information..."), [=]() { information_clicked(modIndex); }); menu.setDefaultAction(infoAction); } diff --git a/src/mainwindow.h b/src/mainwindow.h index 49ecee32..440e39cc 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -152,6 +152,7 @@ public slots: void directory_refreshed(); void updatePluginCount(); + void refreshFilters(); signals: @@ -406,7 +407,6 @@ private slots: void setPrimaryCategoryCandidates(QMenu* menu, ModInfo::Ptr info); void addRemoveCategories_MenuHandler(QMenu* menu, int modIndex, const QModelIndex& rowIdx); - void replaceCategories_MenuHandler(QMenu* menu, int modIndex); void modInstalled(const QString &modName); @@ -426,7 +426,6 @@ private slots: void onRequestsChanged(const APIStats& stats, const APIUserAccount& user); void deselectFilters(); - void refreshFilters(); void onFiltersCriteria(const std::vector& filters); void onFiltersOptions( ModListSortProxy::FilterMode mode, ModListSortProxy::SeparatorsMode sep); diff --git a/src/modlist.h b/src/modlist.h index cabd1f32..e4f4dfab 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -131,6 +131,8 @@ public: void highlightMods(const QItemSelectionModel *selection, const MOShared::DirectoryEntry &directoryEntry); +public: + /** * @brief Notify the mod list that the given mod has been installed. This is used * to notify the plugin that registered through onModInstalled(). diff --git a/src/modlistcontextmenu.cpp b/src/modlistcontextmenu.cpp index df80f0d9..05c2eebf 100644 --- a/src/modlistcontextmenu.cpp +++ b/src/modlistcontextmenu.cpp @@ -29,22 +29,126 @@ ModListGlobalContextMenu::ModListGlobalContextMenu(OrganizerCore& core, ModListV QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { view->enableAllVisible(); } - }); + }); addAction(tr("Disable all visible"), [=]() { if (QMessageBox::question(view, tr("Confirm"), tr("Really disable all visible mods?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { view->disableAllVisible(); } - }); + }); addAction(tr("Check for updates"), [=]() { view->actions().checkModsForUpdates(); }); addAction(tr("Refresh"), &core, &OrganizerCore::profileRefresh); addAction(tr("Export to csv..."), [=]() { view->actions().exportModListCSV(); }); } -ModListContextMenu::ModListContextMenu(OrganizerCore& core, const QModelIndex& index, ModListView* view) : + +ModListChangeCategoryMenu::ModListChangeCategoryMenu(CategoryFactory& categories, ModInfo::Ptr mod, QMenu* parent) + : QMenu(tr("Change Categories"), parent) +{ + populate(this, categories, mod); +} + +std::vector> ModListChangeCategoryMenu::categories() const +{ + return categories(this); +} + +std::vector> ModListChangeCategoryMenu::categories(const QMenu* menu) const +{ + std::vector> cats; + for (QAction* action : menu->actions()) { + if (action->menu() != nullptr) { + auto pcats = categories(action->menu()); + cats.insert(cats.end(), pcats.begin(), pcats.end()); + } + else { + QWidgetAction* widgetAction = qobject_cast(action); + if (widgetAction != nullptr) { + QCheckBox* checkbox = qobject_cast(widgetAction->defaultWidget()); + cats.emplace_back(widgetAction->data().toInt(), checkbox->isChecked()); + } + } + } + return cats; +} + +bool ModListChangeCategoryMenu::populate(QMenu* menu, CategoryFactory& factory, ModInfo::Ptr mod, int targetId) +{ + const std::set& categories = mod->getCategories(); + + bool childEnabled = false; + + for (unsigned int i = 1; i < factory.numCategories(); ++i) { + if (factory.getParentID(i) == targetId) { + QMenu* targetMenu = menu; + if (factory.hasChildren(i)) { + targetMenu = menu->addMenu(factory.getCategoryName(i).replace('&', "&&")); + } + + int id = factory.getCategoryID(i); + QScopedPointer checkBox(new QCheckBox(targetMenu)); + bool enabled = categories.find(id) != categories.end(); + checkBox->setText(factory.getCategoryName(i).replace('&', "&&")); + if (enabled) { + childEnabled = true; + } + checkBox->setChecked(enabled ? Qt::Checked : Qt::Unchecked); + + QScopedPointer checkableAction(new QWidgetAction(targetMenu)); + checkableAction->setDefaultWidget(checkBox.take()); + checkableAction->setData(id); + targetMenu->addAction(checkableAction.take()); + + if (factory.hasChildren(i)) { + if (populate(targetMenu, factory, mod, factory.getCategoryID(i)) || enabled) { + targetMenu->setIcon(QIcon(":/MO/gui/resources/check.png")); + } + } + } + } + return childEnabled; +} + +ModListPrimaryCategoryMenu::ModListPrimaryCategoryMenu(CategoryFactory& categories, ModInfo::Ptr mod, QMenu* parent) + : QMenu(tr("Primary Category"), parent) +{ + connect(this, &QMenu::aboutToShow, [=]() { populate(categories, mod); }); +} + +void ModListPrimaryCategoryMenu::populate(const CategoryFactory& factory, ModInfo::Ptr mod) +{ + clear(); + const std::set& categories = mod->getCategories(); + for (int categoryID : categories) { + int catIdx = factory.getCategoryIndex(categoryID); + QWidgetAction* action = new QWidgetAction(this); + try { + QRadioButton* categoryBox = new QRadioButton( + factory.getCategoryName(catIdx).replace('&', "&&"), + this); + connect(categoryBox, &QRadioButton::toggled, [mod, categoryID](bool enable) { + if (enable) { + mod->setPrimaryCategory(categoryID); + } + }); + categoryBox->setChecked(categoryID == mod->primaryCategory()); + action->setDefaultWidget(categoryBox); + } + catch (const std::exception& e) { + log::error("failed to create category checkbox: {}", e.what()); + } + + action->setData(categoryID); + addAction(action); + } +} + +ModListContextMenu::ModListContextMenu( + const QModelIndex& index, OrganizerCore& core, CategoryFactory& categories, ModListView* view) : QMenu(view) , m_core(core) - , m_index(index) + , m_categories(categories) + , m_index(index.model() == view->model() ? view->indexViewToModel(index) : index) , m_view(view) , m_actions(view->actions()) { @@ -55,7 +159,6 @@ ModListContextMenu::ModListContextMenu(OrganizerCore& core, const QModelIndex& i m_selected = { index }; } - QMenu* allMods = new ModListGlobalContextMenu(core, view, view); allMods->setTitle(tr("All Mods")); addMenu(allMods); @@ -96,6 +199,15 @@ ModListContextMenu::ModListContextMenu(OrganizerCore& core, const QModelIndex& i } } +void ModListContextMenu::addMenuAsPushButton(QMenu* menu) +{ + QPushButton* pushBtn = new QPushButton(menu->title()); + pushBtn->setMenu(menu); + QWidgetAction* action = new QWidgetAction(this); + action->setDefaultWidget(pushBtn); + addAction(action); +} + QMenu* ModListContextMenu::createSendToContextMenu() { QMenu* menu = new QMenu(m_view); @@ -120,7 +232,35 @@ void ModListContextMenu::addOverwriteActions(ModInfo::Ptr mod) void ModListContextMenu::addSeparatorActions(ModInfo::Ptr mod) { + addSeparator(); + + // categories + ModListChangeCategoryMenu* categoriesMenu = new ModListChangeCategoryMenu(m_categories, mod, this); + connect(categoriesMenu, &QMenu::aboutToHide, [=]() { + m_actions.setCategories(m_selected, m_index, categoriesMenu->categories()); + }); + addMenuAsPushButton(categoriesMenu); + ModListPrimaryCategoryMenu* primaryCategoryMenu = new ModListPrimaryCategoryMenu(m_categories, mod, this); + addMenuAsPushButton(primaryCategoryMenu); + addSeparator(); + + + addAction(tr("Rename Separator..."), [=]() { m_actions.renameMod(m_index); }); + addAction(tr("Remove Separator..."), [=]() { m_actions.removeMods(m_selected); }); + addSeparator(); + + if (m_view->sortColumn() == ModList::COL_PRIORITY) { + addMenu(createSendToContextMenu()); + addSeparator(); + } + addAction(tr("Select Color..."), [=]() { m_actions.setColor(m_selected, m_index); }); + + if (mod->color().isValid()) { + addAction(tr("Reset Color"), [=]() { m_actions.resetColor(m_selected, m_index); }); + } + + addSeparator(); } void ModListContextMenu::addForeignActions(ModInfo::Ptr mod) diff --git a/src/modlistcontextmenu.h b/src/modlistcontextmenu.h index 05e6b601..8452bc65 100644 --- a/src/modlistcontextmenu.h +++ b/src/modlistcontextmenu.h @@ -9,6 +9,7 @@ #include "modinfo.h" +class CategoryFactory; class ModListView; class ModListViewActions; class OrganizerCore; @@ -18,7 +19,47 @@ class ModListGlobalContextMenu : public QMenu Q_OBJECT public: - ModListGlobalContextMenu(OrganizerCore& core, ModListView* modListView, QWidget* parent = nullptr); + ModListGlobalContextMenu( + OrganizerCore& core, ModListView* modListView, QWidget* parent = nullptr); + +}; + +class ModListChangeCategoryMenu : public QMenu +{ + Q_OBJECT +public: + + ModListChangeCategoryMenu( + CategoryFactory& categories, ModInfo::Ptr mod, QMenu* parent = nullptr); + + // return a list of pair from the menu + // + std::vector> categories() const; + +private: + + // populate the tree with the category, using the enabled/disabled state from the + // given mod + // + bool populate(QMenu* menu, CategoryFactory& categories, ModInfo::Ptr mod, int targetId = 0); + + // internal implementation of categories() for recursion + // + std::vector> categories(const QMenu* menu) const; +}; + +class ModListPrimaryCategoryMenu : public QMenu +{ + Q_OBJECT +public: + + ModListPrimaryCategoryMenu(CategoryFactory& categories, ModInfo::Ptr mod, QMenu* parent = nullptr); + +private: + + // populate the categories + // + void populate(const CategoryFactory& categories, ModInfo::Ptr mod); }; @@ -30,7 +71,8 @@ public: // creates a new context menu, the given index is the one for the click and should be valid // - ModListContextMenu(OrganizerCore& core, const QModelIndex& index, ModListView* modListView); + ModListContextMenu( + const QModelIndex& index, OrganizerCore& core, CategoryFactory& categories, ModListView* modListView); public: // TODO: Move this to private when all is done @@ -38,6 +80,11 @@ public: // TODO: Move this to private when all is done // QMenu* createSendToContextMenu(); + // special menu for categories + // + void addMenuAsPushButton(QMenu* menu); + + // add actions/menus to this menu for each type of mod // void addOverwriteActions(ModInfo::Ptr mod); @@ -47,6 +94,7 @@ public: // TODO: Move this to private when all is done void addRegularActions(ModInfo::Ptr mod); OrganizerCore& m_core; + CategoryFactory& m_categories; QModelIndex m_index; QModelIndexList m_selected; ModListView* m_view; diff --git a/src/modlistviewactions.cpp b/src/modlistviewactions.cpp index 53c29a5d..9a00353f 100644 --- a/src/modlistviewactions.cpp +++ b/src/modlistviewactions.cpp @@ -506,6 +506,16 @@ void ModListViewActions::sendModsToSeparator(const QModelIndexList& index) const } } +void ModListViewActions::renameMod(const QModelIndex& index) const +{ + try { + m_view->edit(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; @@ -650,6 +660,94 @@ void ModListViewActions::visitWebPage(const QModelIndexList& indices) const } } +void ModListViewActions::setColor(const QModelIndexList& indices, const QModelIndex& refIndex) const +{ + auto& settings = m_core.settings(); + ModInfo::Ptr modInfo = ModInfo::getByIndex(refIndex.data(ModList::IndexRole).toInt()); + + QColorDialog dialog(m_view); + dialog.setOption(QColorDialog::ShowAlphaChannel); + + QColor currentColor = modInfo->color(); + if (currentColor.isValid()) { + dialog.setCurrentColor(currentColor); + } + else if (auto c = settings.colors().previousSeparatorColor()) { + dialog.setCurrentColor(*c); + } + + if (!dialog.exec()) + return; + + currentColor = dialog.currentColor(); + if (!currentColor.isValid()) + return; + + settings.colors().setPreviousSeparatorColor(currentColor); + + for (auto& idx : indices) { + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); + info->setColor(currentColor); + } + +} + +void ModListViewActions::resetColor(const QModelIndexList& indices, const QModelIndex& refIndex) const +{ + for (auto& idx : indices) { + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); + info->setColor(QColor()); + } + m_core.settings().colors().removePreviousSeparatorColor(); +} + +void ModListViewActions::setCategories(ModInfo::Ptr mod, const std::vector>& categories) const +{ + for (auto& [id, enabled] : categories) { + mod->setCategory(id, enabled); + } +} + +void ModListViewActions::setCategoriesIf(ModInfo::Ptr mod, ModInfo::Ptr ref, const std::vector>& categories) const +{ + for (auto& [id, enabled] : categories) { + if (ref->categorySet(id) != enabled) { + mod->setCategory(id, enabled); + } + } +} + +void ModListViewActions::setCategories(const QModelIndexList& selected, const QModelIndex& ref, + const std::vector>& categories) const +{ + ModInfo::Ptr refMod = ModInfo::getByIndex(ref.data(ModList::IndexRole).toInt()); + if (selected.size() > 1) { + + for (auto& idx : selected) { + if (idx.row() != ref.row()) { + setCategoriesIf( + ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()), + refMod, categories); + } + } + setCategories(refMod, categories); + } + else if (!selected.isEmpty()) { + // for single mod selections, just do a replace + setCategories(refMod, categories); + } + + for (auto& idx : selected) { + m_core.modList()->notifyChange(idx.data(ModList::IndexRole).toInt()); + } + + // reset the selection manually - still needed + auto viewIndices = m_view->indexModelToView(selected); + for (auto& idx : viewIndices) { + m_view->selectionModel()->select(idx, QItemSelectionModel::Select | QItemSelectionModel::Rows); + } +} + void ModListViewActions::openExplorer(const QModelIndexList& index) const { for (auto& idx : index) { diff --git a/src/modlistviewactions.h b/src/modlistviewactions.h index 05994813..33442ce7 100644 --- a/src/modlistviewactions.h +++ b/src/modlistviewactions.h @@ -60,13 +60,29 @@ public: void sendModsToPriority(const QModelIndexList& index) const; void sendModsToSeparator(const QModelIndexList& index) const; - // actions for most type of mods + // actions for most regular mods + // + void renameMod(const QModelIndex& index) const; void removeMods(const QModelIndexList& indices) const; void ignoreMissingData(const QModelIndexList& indices) const; void markConverted(const QModelIndexList& indices) const; void visitOnNexus(const QModelIndexList& indices) const; void visitWebPage(const QModelIndexList& indices) const; + // set/reset color of the given selection, using the given reference index (index + // at which the context menu was shown) + // + void setColor(const QModelIndexList& indices, const QModelIndex& refIndex) const; + void resetColor(const QModelIndexList& indices, const QModelIndex& refIndex) const; + + // set the category of the mod in the given list, using the given index as reference + // - the categories are set as-is on the refernce mod + // - for the other mods, the category is only set if the current state of the category + // on the reference is different + // + void setCategories(const QModelIndexList& selected, const QModelIndex& ref, + const std::vector>& categories) const; + // open the Windows explorer for the specified mods // void openExplorer(const QModelIndexList& index) const; @@ -89,8 +105,19 @@ signals: private: + // move the contents of the overwrite to the given path + // void moveOverwriteContentsTo(const QString& absolutePath) const; + // set the category of the given mod based on the given array + // + void setCategories(ModInfo::Ptr mod, const std::vector>& categories) const; + + // set the category of the given mod if the category from the reference mod does not match + // the one in the array of categories + // + void setCategoriesIf(ModInfo::Ptr mod, ModInfo::Ptr ref, const std::vector>& categories) const; + private: OrganizerCore& m_core; -- cgit v1.3.1 From 4f89665056b2256ca353bc27314cd025db2f554c Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 03:28:18 +0100 Subject: Move the regular context menu. --- src/mainwindow.cpp | 233 +-------------------------------------------- src/mainwindow.h | 6 -- src/modlistcontextmenu.cpp | 118 ++++++++++++++++++++++- src/modlistview.cpp | 14 --- src/modlistview.h | 5 - src/modlistviewactions.cpp | 232 +++++++++++++++++++++++++++++++++++++++++++- src/modlistviewactions.h | 19 +++- 7 files changed, 366 insertions(+), 261 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index cd31a0bf..1475be50 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -539,6 +539,7 @@ void MainWindow::setupModList() ui->modList->setup(m_OrganizerCore, actions, ui); connect(actions, &ModListViewActions::overwriteCleared, [=]() { scheduleCheckForProblems(); }); + connect(actions, &ModListViewActions::originModified, this, &MainWindow::originModified); connect(ui->modList, &ModListView::removeSelectedMods, [=]() { removeMod_clicked(-1); }); connect(m_OrganizerCore.modList(), &ModList::clearOverwrite, actions, &ModListViewActions::clearOverwrite); connect(m_OrganizerCore.modList(), &ModList::modPrioritiesChanged, [&]() { m_ArchiveListWriter.write(); }); @@ -2287,10 +2288,7 @@ void MainWindow::modInstalled(const QString &modName) } // force an update to happen - std::multimap IDs; - ModInfo::Ptr info = ModInfo::getByIndex(index); - IDs.insert(std::make_pair(info->gameName(), info->nexusId())); - modUpdateCheck(IDs); + ui->modList->actions().checkModsForUpdates({ m_OrganizerCore.modList()->index(index, 0) }); } void MainWindow::showMessage(const QString &message) @@ -3423,35 +3421,6 @@ void MainWindow::checkModsForUpdates() } } -void MainWindow::changeVersioningScheme(int modIndex) { - if (QMessageBox::question(this, 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(modIndex); - - 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(this, 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 MainWindow::ignoreUpdate(int modIndex) { QItemSelectionModel *selection = ui->modList->selectionModel(); @@ -3470,22 +3439,6 @@ void MainWindow::ignoreUpdate(int modIndex) } } -void MainWindow::checkModUpdates_clicked(int modIndex) -{ - std::multimap IDs; - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); - IDs.insert(std::make_pair(info->gameName(), info->nexusId())); - } - } else { - ModInfo::Ptr info = ModInfo::getByIndex(modIndex); - IDs.insert(std::make_pair(info->gameName(), info->nexusId())); - } - modUpdateCheck(IDs); -} - void MainWindow::unignoreUpdate(int modIndex) { QItemSelectionModel *selection = ui->modList->selectionModel(); @@ -3652,162 +3605,14 @@ void MainWindow::addPluginSendToContextMenu(QMenu *menu) void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) { try { - QTreeView *modList = findChild("modList"); - QModelIndex contextIdx = mapToModel(m_OrganizerCore.modList(), ui->modList->indexAt(pos)); if (!contextIdx.isValid()) { // no selection - ModListGlobalContextMenu(m_OrganizerCore, ui->modList).exec(modList->viewport()->mapToGlobal(pos)); + ModListGlobalContextMenu(m_OrganizerCore, ui->modList).exec(ui->modList->viewport()->mapToGlobal(pos)); } else { - int modIndex = ui->modList->indexAt(pos).data(ModList::IndexRole).toInt(); - int contextColumn = contextIdx.column(); - - ModListContextMenu menu(contextIdx, m_OrganizerCore, m_CategoryFactory, ui->modList); - - ModInfo::Ptr info = ModInfo::getByIndex(modIndex); - std::vector flags = info->getFlags(); - - // context menu for overwrites - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end()) { - } - - // context menu for mod backups - else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) != flags.end()) { - } - - // separator - else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_SEPARATOR) != flags.end()){ - } - - // foregin - else if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) != flags.end()) { - } - - // regular - else { - QMenu* addRemoveCategoriesMenu = new QMenu(tr("Change Categories"), &menu); - populateMenuCategories(modIndex, addRemoveCategoriesMenu, 0); - connect(addRemoveCategoriesMenu, &QMenu::aboutToHide, [=]() { addRemoveCategories_MenuHandler(addRemoveCategoriesMenu, modIndex, contextIdx); }); - addMenuAsPushButton(&menu, addRemoveCategoriesMenu); - - QMenu* primaryCategoryMenu = new QMenu(tr("Primary Category"), &menu); - connect(primaryCategoryMenu, &QMenu::aboutToShow, [=]() { setPrimaryCategoryCandidates(primaryCategoryMenu, info); }); - addMenuAsPushButton(&menu, primaryCategoryMenu); - - menu.addSeparator(); - - if (info->downgradeAvailable()) { - menu.addAction(tr("Change versioning scheme"), [=]() { changeVersioningScheme(modIndex); }); - } - - if (info->nexusId() > 0) - menu.addAction(tr("Force-check updates"), [=]() { checkModUpdates_clicked(modIndex); }); - if (info->updateIgnored()) { - menu.addAction(tr("Un-ignore update"), [=]() { unignoreUpdate(modIndex); }); - } - else { - if (info->updateAvailable() || info->downgradeAvailable()) { - menu.addAction(tr("Ignore update"), [=]() { ignoreUpdate(modIndex); }); - } - } - menu.addSeparator(); - - menu.addAction(tr("Enable selected"), [=]() { enableSelectedMods_clicked(); }); - menu.addAction(tr("Disable selected"), [=]() { disableSelectedMods_clicked(); }); - - menu.addSeparator(); - - if (ui->modList->sortColumn() == ModList::COL_PRIORITY) { - menu.addMenu(menu.createSendToContextMenu()); - menu.addSeparator(); - } - - menu.addAction(tr("Rename Mod..."), [=]() { renameMod_clicked(); }); - menu.addAction(tr("Reinstall Mod"), [=]() { reinstallMod_clicked(modIndex); }); - menu.addAction(tr("Remove Mod..."), [=]() { removeMod_clicked(modIndex); }); - menu.addAction(tr("Create Backup"), [=]() { backupMod_clicked(modIndex); }); - - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_HIDDEN_FILES) != flags.end()) { - menu.addAction(tr("Restore hidden files"), [=]() { restoreHiddenFiles_clicked(modIndex); }); - } - - menu.addSeparator(); - - if (contextColumn == ModList::COL_NOTES) { - menu.addAction(tr("Select Color..."), [=]() { setColor_clicked(modIndex); }); - if (info->color().isValid()) { - menu.addAction(tr("Reset Color"), [=]() { resetColor_clicked(modIndex); }); - } - menu.addSeparator(); - } - - if (info->nexusId() > 0 && Settings::instance().nexus().endorsementIntegration()) { - switch (info->endorsedState()) { - case EndorsedState::ENDORSED_TRUE: { - menu.addAction(tr("Un-Endorse"), [=]() { unendorse_clicked(); }); - } break; - case EndorsedState::ENDORSED_FALSE: { - menu.addAction(tr("Endorse"), [=]() { endorse_clicked(); }); - menu.addAction(tr("Won't endorse"), [=]() { dontendorse_clicked(modIndex); }); - } break; - case EndorsedState::ENDORSED_NEVER: { - menu.addAction(tr("Endorse"), [=]() { endorse_clicked(); }); - } break; - default: { - QAction *action = new QAction(tr("Endorsement state unknown"), &menu); - action->setEnabled(false); - menu.addAction(action); - } break; - } - } - - if (info->nexusId() > 0 && Settings::instance().nexus().trackedIntegration()) { - switch (info->trackedState()) { - case TrackedState::TRACKED_FALSE: { - menu.addAction(tr("Start tracking"), [=]() { track_clicked(); }); - } break; - case TrackedState::TRACKED_TRUE: { - menu.addAction(tr("Stop tracking"), [=]() { untrack_clicked(); }); - } break; - default: { - QAction *action = new QAction(tr("Tracked state unknown"), &menu); - action->setEnabled(false); - menu.addAction(action); - } break; - } - } - - menu.addSeparator(); - - std::vector flags = info->getFlags(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_INVALID) != flags.end()) { - menu.addAction(tr("Ignore missing data"), [=]() { ignoreMissingData_clicked(modIndex); }); - } - - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_ALTERNATE_GAME) != flags.end()) { - menu.addAction(tr("Mark as converted/working"), [=]() { markConverted_clicked(modIndex); }); - } - - menu.addSeparator(); - - if (info->nexusId() > 0) { - menu.addAction(tr("Visit on Nexus"), [=]() { visitOnNexus_clicked(modIndex); }); - } - - const auto url = info->parseCustomURL(); - if (url.isValid()) { - menu.addAction(tr("Visit on %1").arg(url.host()), [=]() { visitWebPage_clicked(modIndex); }); - } - - menu.addAction(tr("Open in Explorer"), [=]() { ui->modList->actions().openExplorer({ contextIdx }); }); - - QAction* infoAction = menu.addAction(tr("Information..."), [=]() { information_clicked(modIndex); }); - menu.setDefaultAction(infoAction); - } - - menu.exec(modList->viewport()->mapToGlobal(pos)); + ModListContextMenu(contextIdx, m_OrganizerCore, m_CategoryFactory, ui->modList).exec(ui->modList->viewport()->mapToGlobal(pos)); } } catch (const std::exception &e) { reportError(tr("Exception: ").arg(e.what())); @@ -4091,18 +3896,6 @@ void MainWindow::sendSelectedPluginsToPriority_clicked() m_OrganizerCore.pluginList()->sendToPriority(ui->espList->selectionModel(), newPriority); } - -void MainWindow::enableSelectedMods_clicked() -{ - ui->modList->enableSelected(); -} - - -void MainWindow::disableSelectedMods_clicked() -{ - ui->modList->disableSelected(); -} - void MainWindow::updateAvailable() { ui->actionUpdate->setEnabled(true); @@ -4166,24 +3959,6 @@ void MainWindow::actionWontEndorseMO() } } -void MainWindow::modUpdateCheck(std::multimap IDs) -{ - if (m_OrganizerCore.settings().network().offlineMode()) { - return; - } - - if (NexusInterface::instance().getAccessManager()->validated()) { - ModInfo::manualUpdateCheck(this, IDs); - } else { - QString apiKey; - if (GlobalSettings::nexusApiKey(apiKey)) { - m_OrganizerCore.doAfterLogin([=]() { this->modUpdateCheck(IDs); }); - NexusInterface::instance().getAccessManager()->apiCheck(apiKey); - } else - log::warn("{}", tr("You are not currently authenticated with Nexus. Please do so under Settings -> Nexus.")); - } -} - void MainWindow::toggleMO2EndorseState() { const auto& s = m_OrganizerCore.settings(); diff --git a/src/mainwindow.h b/src/mainwindow.h index 440e39cc..61bd9326 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -370,8 +370,6 @@ private slots: void openPluginOriginExplorer_clicked(); void openOriginInformation_clicked(); void information_clicked(int modIndex); - void enableSelectedMods_clicked(); - void disableSelectedMods_clicked(); // data-tree context menu // pluginlist context menu @@ -410,8 +408,6 @@ private slots: void modInstalled(const QString &modName); - void modUpdateCheck(std::multimap IDs); - void finishUpdateInfo(); void nxmEndorsementsAvailable(QVariant userData, QVariant resultData, int); @@ -487,8 +483,6 @@ private slots: void removeFromToolbar(QAction* action); void overwriteClosed(int); - void changeVersioningScheme(int modIndex); - void checkModUpdates_clicked(int modIndex); void ignoreUpdate(int modIndex); void unignoreUpdate(int modIndex); diff --git a/src/modlistcontextmenu.cpp b/src/modlistcontextmenu.cpp index 05c2eebf..303362ba 100644 --- a/src/modlistcontextmenu.cpp +++ b/src/modlistcontextmenu.cpp @@ -257,7 +257,7 @@ void ModListContextMenu::addSeparatorActions(ModInfo::Ptr mod) addAction(tr("Select Color..."), [=]() { m_actions.setColor(m_selected, m_index); }); if (mod->color().isValid()) { - addAction(tr("Reset Color"), [=]() { m_actions.resetColor(m_selected, m_index); }); + addAction(tr("Reset Color"), [=]() { m_actions.resetColor(m_selected); }); } addSeparator(); @@ -297,5 +297,121 @@ void ModListContextMenu::addBackupActions(ModInfo::Ptr mod) void ModListContextMenu::addRegularActions(ModInfo::Ptr mod) { + auto flags = mod->getFlags(); + + // categories + ModListChangeCategoryMenu* categoriesMenu = new ModListChangeCategoryMenu(m_categories, mod, this); + connect(categoriesMenu, &QMenu::aboutToHide, [=]() { + m_actions.setCategories(m_selected, m_index, categoriesMenu->categories()); + }); + addMenuAsPushButton(categoriesMenu); + + ModListPrimaryCategoryMenu* primaryCategoryMenu = new ModListPrimaryCategoryMenu(m_categories, mod, this); + addMenuAsPushButton(primaryCategoryMenu); + addSeparator(); + + if (mod->downgradeAvailable()) { + addAction(tr("Change versioning scheme"), [=]() { m_actions.changeVersioningScheme(m_index); }); + } + + if (mod->nexusId() > 0) + addAction(tr("Force-check updates"), [=]() { m_actions.checkModsForUpdates(m_selected); }); + if (mod->updateIgnored()) { + addAction(tr("Un-ignore update"), [=]() { m_actions.setIgnoreUpdate(m_selected, false); }); + } + else { + if (mod->updateAvailable() || mod->downgradeAvailable()) { + addAction(tr("Ignore update"), [=]() { m_actions.setIgnoreUpdate(m_selected, true); }); + } + } + addSeparator(); + + addAction(tr("Enable selected"), [=]() { m_core.modList()->setActive(m_selected, true); }); + addAction(tr("Disable selected"), [=]() { m_core.modList()->setActive(m_selected, false); }); + + addSeparator(); + + + if (m_view->sortColumn() == ModList::COL_PRIORITY) { + addMenu(createSendToContextMenu()); + addSeparator(); + } + + addAction(tr("Rename Mod..."), [=]() { m_actions.renameMod(m_index); }); + addAction(tr("Reinstall Mod"), [=]() { m_actions.reinstallMod(m_index); }); + addAction(tr("Remove Mod..."), [=]() { m_actions.removeMods(m_selected); }); + addAction(tr("Create Backup"), [=]() { m_actions.createBackup(m_index); }); + + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_HIDDEN_FILES) != flags.end()) { + addAction(tr("Restore hidden files"), [=]() { m_actions.restoreHiddenFiles(m_selected); }); + } + + addSeparator(); + + if (m_index.column() == ModList::COL_NOTES) { + addAction(tr("Select Color..."), [=]() { m_actions.setColor(m_selected, m_index); }); + if (mod->color().isValid()) { + addAction(tr("Reset Color"), [=]() { m_actions.resetColor(m_selected); }); + } + addSeparator(); + } + + if (mod->nexusId() > 0 && Settings::instance().nexus().endorsementIntegration()) { + switch (mod->endorsedState()) { + case EndorsedState::ENDORSED_TRUE: { + addAction(tr("Un-Endorse"), [=]() { m_actions.setEndorsed(m_selected, false); }); + } break; + case EndorsedState::ENDORSED_FALSE: { + addAction(tr("Endorse"), [=]() { m_actions.setEndorsed(m_selected, true); }); + addAction(tr("Won't endorse"), [=]() { m_actions.willNotEndorsed(m_selected); }); + } break; + case EndorsedState::ENDORSED_NEVER: { + addAction(tr("Endorse"), [=]() { m_actions.setEndorsed(m_selected, true); }); + } break; + default: { + QAction* action = new QAction(tr("Endorsement state unknown"), this); + action->setEnabled(false); + addAction(action); + } break; + } + } + + if (mod->nexusId() > 0 && Settings::instance().nexus().trackedIntegration()) { + switch (mod->trackedState()) { + case TrackedState::TRACKED_FALSE: { + addAction(tr("Start tracking"), [=]() { m_actions.setTracked(m_selected, true); }); + } break; + case TrackedState::TRACKED_TRUE: { + addAction(tr("Stop tracking"), [=]() { m_actions.setTracked(m_selected, false); }); + } break; + default: { + QAction* action = new QAction(tr("Tracked state unknown"), this); + action->setEnabled(false); + addAction(action); + } break; + } + } + + addSeparator(); + + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_INVALID) != flags.end()) { + addAction(tr("Ignore missing data"), [=]() { m_actions.ignoreMissingData(m_selected); }); + } + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_ALTERNATE_GAME) != flags.end()) { + addAction(tr("Mark as converted/working"), [=]() { m_actions.markConverted(m_selected); }); + } + + addSeparator(); + + if (mod->nexusId() > 0) { + addAction(tr("Visit on Nexus"), [=]() { m_actions.visitOnNexus(m_selected); }); + } + + const auto url = mod->parseCustomURL(); + if (url.isValid()) { + addAction(tr("Visit on %1").arg(url.host()), [=]() { m_actions.visitWebPage(m_selected); }); + } + + addAction(tr("Open in Explorer"), [=]() { m_actions.openExplorer(m_selected); }); } diff --git a/src/modlistview.cpp b/src/modlistview.cpp index 8c826882..cf35abdd 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -196,20 +196,6 @@ void ModListView::disableAllVisible() m_core->modList()->setActive(indexViewToModel(allIndex(model())), false); } -void ModListView::enableSelected() -{ - if (selectionModel()->hasSelection()) { - m_core->modList()->setActive(indexViewToModel(selectionModel()->selectedRows()), true); - } -} - -void ModListView::disableSelected() -{ - if (selectionModel()->hasSelection()) { - m_core->modList()->setActive(indexViewToModel(selectionModel()->selectedRows()), false); - } -} - void ModListView::setFilterCriteria(const std::vector& criteria) { m_sortProxy->setCriteria(criteria); diff --git a/src/modlistview.h b/src/modlistview.h index 0f131631..4f27769c 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -91,11 +91,6 @@ public slots: void enableAllVisible(); void disableAllVisible(); - // enable/disable all selected mods - // - void enableSelected(); - void disableSelected(); - // set the filter criteria/options for mods // void setFilterCriteria(const std::vector& criteria); diff --git a/src/modlistviewactions.cpp b/src/modlistviewactions.cpp index f8fd0e4c..5b9c07bc 100644 --- a/src/modlistviewactions.cpp +++ b/src/modlistviewactions.cpp @@ -193,6 +193,36 @@ void ModListViewActions::checkModsForUpdates() const } } +void ModListViewActions::checkModsForUpdates(std::multimap const& IDs) const +{ + if (m_core.settings().network().offlineMode()) { + return; + } + + if (NexusInterface::instance().getAccessManager()->validated()) { + ModInfo::manualUpdateCheck(m_main, 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 ids; + for (auto& idx : indices) { + ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); + ids.insert(std::make_pair(info->gameName(), info->nexusId())); + } + checkModsForUpdates(ids); +} + void ModListViewActions::exportModListCSV() const { QDialog selection(m_view); @@ -509,7 +539,7 @@ void ModListViewActions::sendModsToSeparator(const QModelIndexList& index) const void ModListViewActions::renameMod(const QModelIndex& index) const { try { - m_view->edit(index); + m_view->edit(m_view->indexModelToView(index)); } catch (const std::exception& e) { reportError(tr("failed to rename mod: %1").arg(e.what())); @@ -578,13 +608,52 @@ void ModListViewActions::ignoreMissingData(const QModelIndexList& indices) const } } +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_view, 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_view, 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 row_idx = idx.data(ModList::IndexRole).toInt(); - ModInfo::Ptr info = ModInfo::getByIndex(row_idx); + int modIdx = idx.data(ModList::IndexRole).toInt(); + ModInfo::Ptr info = ModInfo::getByIndex(modIdx); info->markConverted(true); - m_core.modList()->notifyChange(row_idx); + m_core.modList()->notifyChange(modIdx); } } @@ -664,6 +733,159 @@ void ModListViewActions::visitNexusOrWebPage(const QModelIndexList& indices) con } } +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, true, modInfo, modInfo->name()); + } + else { + QMessageBox::information(m_view, tr("Failed"), tr("Installation file no longer exists")); + } + } + else { + QMessageBox::information(m_view, 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 = m_core.installationManager()->generateBackupName(modInfo->absolutePath()); + if (!copyDir(modInfo->absolutePath(), backupDirectory, false)) { + QMessageBox::information(m_view, tr("Failed"), + tr("Failed to create backup.")); + } + m_core.refresh(); + m_view->updateModCount(); +} + +void ModListViewActions::restoreHiddenFiles(const QModelIndexList& indices) const +{ + const int max_items = 20; + + QFlags flags = FileRenamer::UNHIDE; + flags |= FileRenamer::MULTIPLE; + + FileRenamer renamer(m_view, flags); + + FileRenamer::RenameResults result = FileRenamer::RESULT_OK; + + // multi selection + if (indices.size() > 1) { + + QStringList modNames; + for (auto& idx : indices) { + + ModInfo::Ptr modInfo = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); + const auto flags = modInfo->getFlags(); + + if (!modInfo->isRegular() || + std::find(flags.begin(), flags.end(), ModInfo::FLAG_HIDDEN_FILES) == flags.end()) { + continue; + } + + modNames.append(idx.data(Qt::DisplayRole).toString()); + } + + QString mods = "
  • " + modNames.mid(0, max_items).join("
  • ") + "
  • "; + if (modNames.size() > max_items) { + mods += "
  • ...
  • "; + } + + if (QMessageBox::question(m_view, tr("Confirm"), + tr("Restore all hidden files in the following mods?
      %1
    ").arg(mods), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { + + for (auto& idx : indices) { + + ModInfo::Ptr modInfo = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); + + const auto flags = modInfo->getFlags(); + if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_HIDDEN_FILES) != flags.end()) { + const QString modDir = modInfo->absolutePath(); + + auto partialResult = restoreHiddenFilesRecursive(renamer, modDir); + + if (partialResult == FileRenamer::RESULT_CANCEL) { + result = FileRenamer::RESULT_CANCEL; + break; + } + emit originModified((m_core.directoryStructure()->getOriginByName( + ToWString(modInfo->internalName()))).getID()); + } + } + } + } + else if (!indices.isEmpty()) { + //single selection + ModInfo::Ptr modInfo = ModInfo::getByIndex(indices[0].data(ModList::IndexRole).toInt()); + const QString modDir = modInfo->absolutePath(); + + if (QMessageBox::question(m_view, tr("Are you sure?"), + tr("About to restore all hidden files in:\n") + modInfo->name(), + QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok) { + + result = restoreHiddenFilesRecursive(renamer, modDir); + + emit originModified((m_core.directoryStructure()->getOriginByName( + ToWString(modInfo->internalName()))).getID()); + } + } + + if (result == FileRenamer::RESULT_CANCEL) { + log::debug("Restoring hidden files operation cancelled"); + } + else { + log::debug("Finished restoring hidden files"); + } +} + +void ModListViewActions::setTracked(const QModelIndexList& indices, bool tracked) const +{ + m_core.loggedInAction(m_view, [=] { + for (auto& idx : indices) { + ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->track(tracked); + } + }); +} + +void ModListViewActions::setEndorsed(const QModelIndexList& indices, bool endorsed) const +{ + m_core.loggedInAction(m_view, [=] { + if (indices.size() > 1) { + MessageDialog::showMessage(tr("Endorsing multiple mods will take a while. Please wait..."), m_view); + } + + for (auto& idx : indices) { + ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->endorse(endorsed); + } + }); +} + +void ModListViewActions::willNotEndorsed(const QModelIndexList& indices) const +{ + for (auto& idx : indices) { + ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->setNeverEndorse(); + } +} + void ModListViewActions::setColor(const QModelIndexList& indices, const QModelIndex& refIndex) const { auto& settings = m_core.settings(); @@ -696,7 +918,7 @@ void ModListViewActions::setColor(const QModelIndexList& indices, const QModelIn } -void ModListViewActions::resetColor(const QModelIndexList& indices, const QModelIndex& refIndex) const +void ModListViewActions::resetColor(const QModelIndexList& indices) const { for (auto& idx : indices) { ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); diff --git a/src/modlistviewactions.h b/src/modlistviewactions.h index 52db019c..26efde47 100644 --- a/src/modlistviewactions.h +++ b/src/modlistviewactions.h @@ -42,6 +42,7 @@ public: // check all mods for update // void checkModsForUpdates() const; + void checkModsForUpdates(const QModelIndexList& indices) const; // start the "Export Mod List" dialog // @@ -65,16 +66,24 @@ public: void renameMod(const QModelIndex& index) const; void removeMods(const QModelIndexList& indices) const; void ignoreMissingData(const QModelIndexList& indices) const; + void setIgnoreUpdate(const QModelIndexList& indices, bool ignore) const; + void changeVersioningScheme(const QModelIndex& indices) const; void markConverted(const QModelIndexList& indices) const; void visitOnNexus(const QModelIndexList& indices) const; void visitWebPage(const QModelIndexList& indices) const; void visitNexusOrWebPage(const QModelIndexList& indices) const; + void reinstallMod(const QModelIndex& index) const; + void createBackup(const QModelIndex& index) const; + void restoreHiddenFiles(const QModelIndexList& indices) const; + void setTracked(const QModelIndexList& indices, bool tracked) const; + void setEndorsed(const QModelIndexList& indices, bool endorsed) const; + void willNotEndorsed(const QModelIndexList& indices) const; // set/reset color of the given selection, using the given reference index (index // at which the context menu was shown) // void setColor(const QModelIndexList& indices, const QModelIndex& refIndex) const; - void resetColor(const QModelIndexList& indices, const QModelIndex& refIndex) const; + void resetColor(const QModelIndexList& indices) const; // set the category of the mod in the given list, using the given index as reference // - the categories are set as-is on the refernce mod @@ -104,6 +113,10 @@ signals: // void overwriteCleared() const; + // emitted when the origin of a file is modified + // + void originModified(int originId) const; + private: // move the contents of the overwrite to the given path @@ -119,6 +132,10 @@ private: // void setCategoriesIf(ModInfo::Ptr mod, ModInfo::Ptr ref, const std::vector>& categories) const; + // check the given mods from update, the map should map game names to nexus ID + // + void checkModsForUpdates(std::multimap const& IDs) const; + private: OrganizerCore& m_core; -- cgit v1.3.1 From a27656dc7bd14d22d0d8f9fe04f0365f95d81906 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 03:56:58 +0100 Subject: Move click event to ModListView. Remove unused slots from MainWindow. --- src/aboutdialog.cpp | 2 +- src/aboutdialog.h | 4 - src/mainwindow.cpp | 879 +--------------------------------------------------- src/mainwindow.h | 62 +--- src/modlistview.cpp | 110 ++++++- src/modlistview.h | 11 +- 6 files changed, 109 insertions(+), 959 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/aboutdialog.cpp b/src/aboutdialog.cpp index 03663cf8..98743e05 100644 --- a/src/aboutdialog.cpp +++ b/src/aboutdialog.cpp @@ -120,5 +120,5 @@ void AboutDialog::on_creditsList_currentItemChanged(QListWidgetItem *current, QL void AboutDialog::on_sourceText_linkActivated(const QString &link) { - emit linkClicked(link); + MOBase::shell::Open(QUrl(link)); } diff --git a/src/aboutdialog.h b/src/aboutdialog.h index 9b9b6102..02d840ec 100644 --- a/src/aboutdialog.h +++ b/src/aboutdialog.h @@ -40,10 +40,6 @@ public: explicit AboutDialog(const QString &version, QWidget *parent = 0); ~AboutDialog(); -signals: - - void linkClicked(QString link); - private: enum Licenses { diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 1475be50..caf533f2 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -206,7 +206,6 @@ QString UnmanagedModName() bool runLoot(QWidget* parent, OrganizerCore& core, bool didUpdateMasterList); - void setFilterShortcuts(QWidget* widget, QLineEdit* edit) { auto activate = [=] { @@ -241,7 +240,6 @@ void setFilterShortcuts(QWidget* widget, QLineEdit* edit) hookReset(edit); } - MainWindow::MainWindow(Settings &settings , OrganizerCore &organizerCore , PluginContainer &pluginContainer @@ -536,11 +534,10 @@ MainWindow::MainWindow(Settings &settings void MainWindow::setupModList() { auto* actions = new ModListViewActions(m_OrganizerCore, *m_Filters, m_CategoryFactory, this, ui->modList); - ui->modList->setup(m_OrganizerCore, actions, ui); + ui->modList->setup(m_OrganizerCore, m_CategoryFactory, actions, ui); connect(actions, &ModListViewActions::overwriteCleared, [=]() { scheduleCheckForProblems(); }); connect(actions, &ModListViewActions::originModified, this, &MainWindow::originModified); - connect(ui->modList, &ModListView::removeSelectedMods, [=]() { removeMod_clicked(-1); }); connect(m_OrganizerCore.modList(), &ModList::clearOverwrite, actions, &ModListViewActions::clearOverwrite); connect(m_OrganizerCore.modList(), &ModList::modPrioritiesChanged, [&]() { m_ArchiveListWriter.write(); }); @@ -636,7 +633,6 @@ MainWindow::~MainWindow() } } - void MainWindow::updateWindowTitle(const APIUserAccount& user) { //"\xe2\x80\x93" is an "em dash", a longer "-" @@ -652,13 +648,11 @@ void MainWindow::updateWindowTitle(const APIUserAccount& user) this->setWindowTitle(title); } - void MainWindow::onRequestsChanged(const APIStats& stats, const APIUserAccount& user) { ui->statusBar->setAPI(stats, user); } - void MainWindow::resizeLists(bool pluginListCustom) { // ensure the columns aren't so small you can't see them any more @@ -677,7 +671,6 @@ void MainWindow::resizeLists(bool pluginListCustom) } } - void MainWindow::allowListResize() { // allow resize on mod list @@ -704,7 +697,6 @@ void MainWindow::resizeEvent(QResizeEvent *event) QMainWindow::resizeEvent(event); } - static QModelIndex mapToModel(const QAbstractItemModel *targetModel, QModelIndex idx) { QModelIndex result = idx; @@ -997,7 +989,6 @@ void MainWindow::updateProblemsButton() } } - bool MainWindow::errorReported(QString &logFile) { QDir dir(qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::logPath())); @@ -1059,12 +1050,9 @@ void MainWindow::checkForProblemsImpl() void MainWindow::about() { - AboutDialog dialog(m_OrganizerCore.getVersion().displayString(3), this); - connect(&dialog, SIGNAL(linkClicked(QString)), this, SLOT(linkClicked(QString))); - dialog.exec(); + AboutDialog(m_OrganizerCore.getVersion().displayString(3), this).exec(); } - void MainWindow::createEndorseMenu() { auto* menu = ui->actionEndorseMO->menu(); @@ -1084,7 +1072,6 @@ void MainWindow::createEndorseMenu() menu->addAction(wontEndorseAction); } - void MainWindow::createHelpMenu() { auto* menu = ui->actionHelp->menu(); @@ -1679,7 +1666,6 @@ bool MainWindow::refreshProfiles(bool selectProfile) return profileBox->count() > 1; } - void MainWindow::refreshExecutablesList() { QAbstractItemModel *model = ui->executablesListBox->model(); @@ -1913,13 +1899,11 @@ void MainWindow::fixCategories() } } - void MainWindow::setupNetworkProxy(bool activate) { QNetworkProxyFactory::setUseSystemConfiguration(activate); } - void MainWindow::activateProxy(bool activate) { QProgressDialog busyDialog(tr("Activating Network Proxy"), QString(), 0, 0, parentWidget()); @@ -2167,7 +2151,6 @@ void MainWindow::tutorialTriggered() } } - void MainWindow::on_actionInstallMod_triggered() { ui->modList->actions().installMod(); @@ -2225,7 +2208,6 @@ void MainWindow::on_actionModify_Executables_triggered() } } - void MainWindow::setModListSorting(int index) { Qt::SortOrder order = ((index & 0x01) != 0) ? Qt::DescendingOrder : Qt::AscendingOrder; @@ -2233,7 +2215,6 @@ void MainWindow::setModListSorting(int index) ui->modList->header()->setSortIndicator(column, order); } - void MainWindow::setESPListSorting(int index) { switch (index) { @@ -2301,11 +2282,6 @@ void MainWindow::showError(const QString &message) reportError(message); } -void MainWindow::installMod_clicked() -{ - ui->modList->actions().installMod(); -} - void MainWindow::modRenamed(const QString &oldName, const QString &newName) { Profile::renameModInAllProfiles(oldName, newName); @@ -2353,16 +2329,6 @@ void MainWindow::fileMoved(const QString &filePath, const QString &oldOriginName } } - -void MainWindow::renameMod_clicked() -{ - try { - ui->modList->edit(ui->modList->currentIndex()); - } catch (const std::exception &e) { - reportError(tr("failed to rename mod: %1").arg(e.what())); - } -} - void MainWindow::modlistChanged(const QModelIndex&, int) { m_OrganizerCore.currentProfile()->writeModlist(); @@ -2401,57 +2367,6 @@ void MainWindow::esplistSelectionsChanged(const QItemSelection &selected) ui->modList->verticalScrollBar()->repaint(); } -void MainWindow::removeMod_clicked(int modIndex) -{ - const int max_items = 20; - - try { - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - QString mods; - QStringList modNames; - - int i = 0; - for (QModelIndex idx : selection->selectedRows()) { - 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 += "
  • " + name + "
  • "; - } - else if (i == max_items) { - mods += "
  • ...
  • "; - } - - modNames.append(ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->name()); - ++i; - } - if (QMessageBox::question(this, tr("Confirm"), - tr("Remove the following mods?
      %1
    ").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_OrganizerCore.modList()->removeRowForce(ModInfo::getIndex(name), QModelIndex()); - } - DownloadManager::endDisableDirWatcher(); - } - } else { - m_OrganizerCore.modList()->removeRow(modIndex, QModelIndex()); - } - ui->modList->updateModCount(); - updatePluginCount(); - } catch (const std::exception &e) { - reportError(tr("failed to remove mod: %1").arg(e.what())); - } -} - void MainWindow::modRemoved(const QString &fileName) { if (!fileName.isEmpty() && !QFileInfo(fileName).isAbsolute()) { @@ -2459,136 +2374,6 @@ void MainWindow::modRemoved(const QString &fileName) } } - -void MainWindow::reinstallMod_clicked(int modIndex) -{ - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - QString installationFile = modInfo->installationFile(); - if (installationFile.length() != 0) { - QString fullInstallationFile; - QFileInfo fileInfo(installationFile); - if (fileInfo.isAbsolute()) { - if (fileInfo.exists()) { - fullInstallationFile = installationFile; - } else { - fullInstallationFile = m_OrganizerCore.downloadManager()->getOutputDirectory() + "/" + fileInfo.fileName(); - } - } else { - fullInstallationFile = m_OrganizerCore.downloadManager()->getOutputDirectory() + "/" + installationFile; - } - if (QFile::exists(fullInstallationFile)) { - m_OrganizerCore.installMod(fullInstallationFile, true, modInfo, modInfo->name()); - } else { - QMessageBox::information(this, tr("Failed"), tr("Installation file no longer exists")); - } - } else { - QMessageBox::information(this, tr("Failed"), - tr("Mods installed with old versions of MO can't be reinstalled in this way.")); - } -} - -void MainWindow::backupMod_clicked(int modIndex) -{ - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - QString backupDirectory = m_OrganizerCore.installationManager()->generateBackupName(modInfo->absolutePath()); - if (!copyDir(modInfo->absolutePath(), backupDirectory, false)) { - QMessageBox::information(this, tr("Failed"), - tr("Failed to create backup.")); - } - m_OrganizerCore.refresh(); - ui->modList->updateModCount(); -} - - -void MainWindow::endorseMod(ModInfo::Ptr mod) -{ - m_OrganizerCore.loggedInAction(this, [this, mod] { - mod->endorse(true); - }); -} - - -void MainWindow::endorse_clicked() -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - - m_OrganizerCore.loggedInAction(this, [this] { - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - MessageDialog::showMessage(tr("Endorsing multiple mods will take a while. Please wait..."), this); - } - - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->endorse(true); - } - }); -} - -void MainWindow::dontendorse_clicked(int modIndex) -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->setNeverEndorse(); - } - } - else { - ModInfo::getByIndex(modIndex)->setNeverEndorse(); - } -} - - -void MainWindow::unendorseMod(ModInfo::Ptr mod) -{ - m_OrganizerCore.loggedInAction(this, [mod] { - mod->endorse(false); - }); -} - - -void MainWindow::unendorse_clicked() -{ - m_OrganizerCore.loggedInAction(this, [this] { - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - MessageDialog::showMessage(tr("Unendorsing multiple mods will take a while. Please wait..."), this); - } - - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->endorse(false); - } - }); -} - - -void MainWindow::trackMod(ModInfo::Ptr mod, bool doTrack) -{ - m_OrganizerCore.loggedInAction(this, [mod, doTrack] { - mod->track(doTrack); - }); -} - - -void MainWindow::track_clicked() -{ - m_OrganizerCore.loggedInAction(this, [this] { - QItemSelectionModel *selection = ui->modList->selectionModel(); - for (auto idx : selection->selectedRows()) { - ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->track(true); - } - }); -} - -void MainWindow::untrack_clicked() -{ - m_OrganizerCore.loggedInAction(this, [this] { - QItemSelectionModel *selection = ui->modList->selectionModel(); - for (auto idx : selection->selectedRows()) { - ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->track(false); - } - }); -} - void MainWindow::windowTutorialFinished(const QString &windowName) { m_OrganizerCore.settings().interface().setTutorialCompleted(windowName); @@ -2637,269 +2422,6 @@ ModInfo::Ptr MainWindow::previousModInList(int modIndex) return ModInfo::getByIndex(modIndex); } -void MainWindow::ignoreMissingData_clicked(int modIndex) -{ - const auto rows = ui->modList->selectionModel()->selectedRows(); - - if (rows.count() > 1) { - std::vector changed; - - for (QModelIndex idx : rows) { - int row_idx = idx.data(ModList::IndexRole).toInt(); - ModInfo::Ptr info = ModInfo::getByIndex(row_idx); - info->markValidated(true); - changed.push_back(info); - } - - for (auto&& m : changed) { - int row_idx = ModInfo::getIndex(m->internalName()); - m_OrganizerCore.modList()->notifyChange(row_idx); - } - } else { - ModInfo::Ptr info = ModInfo::getByIndex(modIndex); - info->markValidated(true); - m_OrganizerCore.modList()->notifyChange(modIndex); - } -} - -void MainWindow::markConverted_clicked(int modIndex) -{ - const auto rows = ui->modList->selectionModel()->selectedRows(); - - if (rows.count() > 1) { - std::vector changed; - - for (QModelIndex idx : rows) { - int row_idx = idx.data(ModList::IndexRole).toInt(); - ModInfo::Ptr info = ModInfo::getByIndex(row_idx); - info->markConverted(true); - changed.push_back(info); - } - - for (auto&& m : changed) { - int row_idx = ModInfo::getIndex(m->internalName()); - m_OrganizerCore.modList()->notifyChange(row_idx); - } - } else { - ModInfo::Ptr info = ModInfo::getByIndex(modIndex); - info->markConverted(true); - m_OrganizerCore.modList()->notifyChange(modIndex); - } -} - - -void MainWindow::restoreHiddenFiles_clicked(int modIndex) -{ - const int max_items = 20; - QItemSelectionModel* selection = ui->modList->selectionModel(); - - QFlags flags = FileRenamer::UNHIDE; - flags |= FileRenamer::MULTIPLE; - - FileRenamer renamer(this, flags); - - FileRenamer::RenameResults result = FileRenamer::RESULT_OK; - - // multi selection - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - QString mods; - QStringList modNames; - int i = 0; - - for (QModelIndex idx : selection->selectedRows()) { - - QString name = idx.data().toString(); - int row_idx = idx.data(ModList::IndexRole).toInt(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(row_idx); - const auto flags = modInfo->getFlags(); - - if (!modInfo->isRegular() || - std::find(flags.begin(), flags.end(), ModInfo::FLAG_HIDDEN_FILES) == flags.end()) { - 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 += "
  • " + name + "
  • "; - } - else if (i == max_items) { - mods += "
  • ...
  • "; - } - - modNames.append(ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt())->name()); - ++i; - } - if (QMessageBox::question(this, tr("Confirm"), - tr("Restore all hidden files in the following mods?
      %1
    ").arg(mods), - QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { - - for (QModelIndex idx : selection->selectedRows()) { - - int row_idx = idx.data(ModList::IndexRole).toInt(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(row_idx); - - const auto flags = modInfo->getFlags(); - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_HIDDEN_FILES) != flags.end()) { - const QString modDir = modInfo->absolutePath(); - - auto partialResult = restoreHiddenFilesRecursive(renamer, modDir); - - if (partialResult == FileRenamer::RESULT_CANCEL) { - result = FileRenamer::RESULT_CANCEL; - break; - } - originModified((m_OrganizerCore.directoryStructure()->getOriginByName( - ToWString(modInfo->internalName()))).getID()); - } - } - } - } - else { - //single selection - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - const QString modDir = modInfo->absolutePath(); - - if (QMessageBox::question(this, tr("Are you sure?"), - tr("About to restore all hidden files in:\n") + modInfo->name(), - QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Ok) { - - result = restoreHiddenFilesRecursive(renamer, modDir); - - originModified((m_OrganizerCore.directoryStructure()->getOriginByName( - ToWString(modInfo->internalName()))).getID()); - } - } - - if (result == FileRenamer::RESULT_CANCEL){ - log::debug("Restoring hidden files operation cancelled"); - } - else { - log::debug("Finished restoring hidden files"); - } -} - - -void MainWindow::visitOnNexus_clicked(int modIndex) -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - int count = selection->selectedRows().count(); - if (count > 10) { - if (QMessageBox::question(this, tr("Opening Nexus Links"), - tr("You are trying to open %1 links to Nexus Mods. Are you sure you want to do this?").arg(count), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { - return; - } - } - int row_idx; - ModInfo::Ptr info; - QString gameName; - - for (QModelIndex idx : selection->selectedRows()) { - row_idx = idx.data(ModList::IndexRole).toInt(); - info = ModInfo::getByIndex(row_idx); - int modID = info->nexusId(); - gameName = info->gameName(); - if (modID > 0) { - linkClicked(NexusInterface::instance().getModURL(modID, gameName)); - } else { - log::error("mod '{}' has no nexus id", info->name()); - } - } - } - else { - int modID = m_OrganizerCore.modList()->data(m_OrganizerCore.modList()->index(modIndex, 0), Qt::UserRole).toInt(); - QString gameName = m_OrganizerCore.modList()->data(m_OrganizerCore.modList()->index(modIndex, 0), Qt::UserRole + 4).toString(); - if (modID > 0) { - linkClicked(NexusInterface::instance().getModURL(modID, gameName)); - } else { - MessageDialog::showMessage(tr("Nexus ID for this mod is unknown"), this); - } - } -} - -void MainWindow::visitWebPage_clicked(int index) -{ - QItemSelectionModel* selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - int count = selection->selectedRows().count(); - if (count > 10) { - if (QMessageBox::question(this, tr("Opening Web Pages"), - tr("You are trying to open %1 Web Pages. Are you sure you want to do this?").arg(count), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { - return; - } - } - int row_idx; - ModInfo::Ptr info; - QString gameName; - for (QModelIndex idx : selection->selectedRows()) { - row_idx = idx.data(ModList::IndexRole).toInt(); - info = ModInfo::getByIndex(row_idx); - - const auto url = info->parseCustomURL(); - if (url.isValid()) { - linkClicked(url.toString()); - } - } - } - else { - ModInfo::Ptr info = ModInfo::getByIndex(index); - - const auto url = info->parseCustomURL(); - if (url.isValid()) { - linkClicked(url.toString()); - } - } -} - -void MainWindow::visitNexusOrWebPage(const QModelIndex& idx) -{ - int row_idx = idx.data(ModList::IndexRole).toInt(); - - ModInfo::Ptr info = ModInfo::getByIndex(row_idx); - if (!info) { - log::error("mod {} not found", row_idx); - return; - } - - int modID = info->nexusId(); - QString gameName = info->gameName(); - const auto url = info->parseCustomURL(); - - if (modID > 0) { - linkClicked(NexusInterface::instance().getModURL(modID, gameName)); - } else if (url.isValid()) { - linkClicked(url.toString()); - } else { - log::error("mod '{}' has no valid link", info->name()); - } -} - -void MainWindow::visitNexusOrWebPage_clicked(int index) { - QItemSelectionModel* selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - int count = selection->selectedRows().count(); - if (count > 10) { - if (QMessageBox::question(this, tr("Opening Web Pages"), - tr("You are trying to open %1 Web Pages. Are you sure you want to do this?").arg(count), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) { - return; - } - } - - for (QModelIndex idx : selection->selectedRows()) { - visitNexusOrWebPage(idx); - } - } - else { - QModelIndex idx = m_OrganizerCore.modList()->index(index, 0); - visitNexusOrWebPage(idx); - } -} - void MainWindow::openPluginOriginExplorer_clicked() { QItemSelectionModel *selection = ui->espList->selectionModel(); @@ -3017,146 +2539,12 @@ void MainWindow::updatePluginCount() ); } -void MainWindow::information_clicked(int modIndex) -{ - try { - ui->modList->actions().displayModInformation(modIndex); - } catch (const std::exception &e) { - reportError(e.what()); - } -} - -void MainWindow::setColor_clicked(int modIndex) -{ - auto& settings = m_OrganizerCore.settings(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - - QColorDialog dialog(this); - dialog.setOption(QColorDialog::ShowAlphaChannel); - - QColor currentColor = modInfo->color(); - if (currentColor.isValid()) { - dialog.setCurrentColor(currentColor); - } - else if (auto c=settings.colors().previousSeparatorColor()) { - dialog.setCurrentColor(*c); - } - - if (!dialog.exec()) - return; - - currentColor = dialog.currentColor(); - if (!currentColor.isValid()) - return; - - settings.colors().setPreviousSeparatorColor(currentColor); - - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); - info->setColor(currentColor); - } - } - else { - modInfo->setColor(currentColor); - } -} - -void MainWindow::resetColor_clicked(int modIndex) -{ - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - QColor color = QColor(); - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); - info->setColor(color); - } - } - else { - modInfo->setColor(color); - } - - m_OrganizerCore.settings().colors().removePreviousSeparatorColor(); -} - void MainWindow::cancelModListEditor() { ui->modList->setEnabled(false); ui->modList->setEnabled(true); } -void MainWindow::on_modList_doubleClicked(const QModelIndex &index) -{ - if (!index.isValid()) { - return; - } - - if (m_OrganizerCore.modList()->timeElapsedSinceLastChecked() <= QApplication::doubleClickInterval()) { - // don't interpret double click if we only just checked a mod - return; - } - - bool indexOk = false; - int modIndex = index.data(ModList::IndexRole).toInt(&indexOk); - - if (!indexOk || modIndex < 0 || modIndex >= ModInfo::getNumMods()) { - return; - } - - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - - Qt::KeyboardModifiers modifiers = QApplication::queryKeyboardModifiers(); - if (modifiers.testFlag(Qt::ControlModifier)) { - try { - shell::Explore(modInfo->absolutePath()); - - // workaround to cancel the editor that might have opened because of - // selection-click - ui->modList->closePersistentEditor(index); - } - catch (const std::exception &e) { - reportError(e.what()); - } - } - else if (modifiers.testFlag(Qt::ShiftModifier)) { - try { - QModelIndex idx = m_OrganizerCore.modList()->index(modIndex, 0); - visitNexusOrWebPage(idx); - ui->modList->closePersistentEditor(index); - } - catch (const std::exception & e) { - reportError(e.what()); - } - } - else if (ui->modList->hasCollapsibleSeparators() && modInfo->isSeparator()) { - ui->modList->setExpanded(index, !ui->modList->isExpanded(index)); - } - else { - try { - auto tab = ModInfoTabIDs::None; - - switch (index.column()) { - case ModList::COL_NOTES: tab = ModInfoTabIDs::Notes; break; - case ModList::COL_VERSION: tab = ModInfoTabIDs::Nexus; break; - case ModList::COL_MODID: tab = ModInfoTabIDs::Nexus; break; - case ModList::COL_GAME: tab = ModInfoTabIDs::Nexus; break; - case ModList::COL_CATEGORY: tab = ModInfoTabIDs::Categories; break; - case ModList::COL_CONFLICTFLAGS: tab = ModInfoTabIDs::Conflicts; break; - } - - ui->modList->actions().displayModInformation(modIndex, tab); - // workaround to cancel the editor that might have opened because of - // selection-click - ui->modList->closePersistentEditor(index); - } - catch (const std::exception &e) { - reportError(e.what()); - } - } -} - void MainWindow::openOriginInformation_clicked() { try { @@ -3244,123 +2632,6 @@ void MainWindow::on_espList_doubleClicked(const QModelIndex &index) } } -bool MainWindow::populateMenuCategories(int modIndex, QMenu *menu, int targetID) -{ - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - const std::set &categories = modInfo->getCategories(); - - bool childEnabled = false; - - for (unsigned int i = 1; i < m_CategoryFactory.numCategories(); ++i) { - if (m_CategoryFactory.getParentID(i) == targetID) { - QMenu *targetMenu = menu; - if (m_CategoryFactory.hasChildren(i)) { - targetMenu = menu->addMenu(m_CategoryFactory.getCategoryName(i).replace('&', "&&")); - } - - int id = m_CategoryFactory.getCategoryID(i); - QScopedPointer checkBox(new QCheckBox(targetMenu)); - bool enabled = categories.find(id) != categories.end(); - checkBox->setText(m_CategoryFactory.getCategoryName(i).replace('&', "&&")); - if (enabled) { - childEnabled = true; - } - checkBox->setChecked(enabled ? Qt::Checked : Qt::Unchecked); - - QScopedPointer checkableAction(new QWidgetAction(targetMenu)); - checkableAction->setDefaultWidget(checkBox.take()); - checkableAction->setData(id); - targetMenu->addAction(checkableAction.take()); - - if (m_CategoryFactory.hasChildren(i)) { - if (populateMenuCategories(modIndex, targetMenu, m_CategoryFactory.getCategoryID(i)) || enabled) { - targetMenu->setIcon(QIcon(":/MO/gui/resources/check.png")); - } - } - } - } - return childEnabled; -} - -void MainWindow::replaceCategoriesFromMenu(QMenu *menu, int modRow) -{ - ModInfo::Ptr modInfo = ModInfo::getByIndex(modRow); - for (QAction* action : menu->actions()) { - if (action->menu() != nullptr) { - replaceCategoriesFromMenu(action->menu(), modRow); - } else { - QWidgetAction *widgetAction = qobject_cast(action); - if (widgetAction != nullptr) { - QCheckBox *checkbox = qobject_cast(widgetAction->defaultWidget()); - modInfo->setCategory(widgetAction->data().toInt(), checkbox->isChecked()); - } - } - } -} - -void MainWindow::addRemoveCategoriesFromMenu(QMenu *menu, int modRow, int referenceRow) -{ - if (referenceRow != -1 && referenceRow != modRow) { - ModInfo::Ptr editedModInfo = ModInfo::getByIndex(referenceRow); - for (QAction* action : menu->actions()) { - if (action->menu() != nullptr) { - addRemoveCategoriesFromMenu(action->menu(), modRow, referenceRow); - } else { - QWidgetAction *widgetAction = qobject_cast(action); - if (widgetAction != nullptr) { - QCheckBox *checkbox = qobject_cast(widgetAction->defaultWidget()); - int categoryId = widgetAction->data().toInt(); - bool checkedBefore = editedModInfo->categorySet(categoryId); - bool checkedAfter = checkbox->isChecked(); - - if (checkedBefore != checkedAfter) { // only update if the category was changed on the edited mod - ModInfo::Ptr currentModInfo = ModInfo::getByIndex(modRow); - currentModInfo->setCategory(categoryId, checkedAfter); - } - } - } - } - } else { - replaceCategoriesFromMenu(menu, modRow); - } -} - -void MainWindow::addRemoveCategories_MenuHandler(QMenu* menu, int modIndex, const QModelIndex& rowIdx) { - - QList selected; - for (const QModelIndex &idx : ui->modList->selectionModel()->selectedRows()) { - selected.append(QPersistentModelIndex(idx)); - } - - if (selected.size() > 0) { - int minRow = INT_MAX; - int maxRow = -1; - - for (const QPersistentModelIndex &idx : selected) { - log::debug("change categories on: {}", idx.data().toString()); - QModelIndex modIdx = mapToModel(m_OrganizerCore.modList(), idx); - if (modIdx.row() != rowIdx.row()) { - addRemoveCategoriesFromMenu(menu, modIdx.row(), rowIdx.row()); - } - if (idx.row() < minRow) minRow = idx.row(); - if (idx.row() > maxRow) maxRow = idx.row(); - } - replaceCategoriesFromMenu(menu, rowIdx.row()); - - m_OrganizerCore.modList()->notifyChange(minRow, maxRow + 1); - - for (const QPersistentModelIndex &idx : selected) { - ui->modList->selectionModel()->select(idx, QItemSelectionModel::Select | QItemSelectionModel::Rows); - } - } else { - //For single mod selections, just do a replace - replaceCategoriesFromMenu(menu, modIndex); - m_OrganizerCore.modList()->notifyChange(modIndex); - } - - refreshFilters(); -} - void MainWindow::saveArchiveList() { if (m_OrganizerCore.isArchivesInit()) { @@ -3380,110 +2651,6 @@ void MainWindow::saveArchiveList() } } -void MainWindow::checkModsForUpdates() -{ - bool checkingModsForUpdate = false; - if (NexusInterface::instance().getAccessManager()->validated()) { - checkingModsForUpdate = ModInfo::checkAllForUpdate(&m_PluginContainer, this); - NexusInterface::instance().requestEndorsementInfo(this, QVariant(), QString()); - NexusInterface::instance().requestTrackingInfo(this, QVariant(), QString()); - } else { - QString apiKey; - if (GlobalSettings::nexusApiKey(apiKey)) { - m_OrganizerCore.doAfterLogin([this] () { this->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_OrganizerCore.modList()->allMods()) { - ModInfo::Ptr modInfo = ModInfo::getByName(mod); - if (modInfo->updateAvailable()) { - updatesAvailable = true; - break; - } - } - - if (updatesAvailable || checkingModsForUpdate) { - ui->modList->setFilterCriteria({{ - ModListSortProxy::TypeSpecial, - CategoryFactory::UpdateAvailable, - false} - }); - - m_Filters->setSelection({{ - ModListSortProxy::TypeSpecial, - CategoryFactory::UpdateAvailable, - false - }}); - } -} - -void MainWindow::ignoreUpdate(int modIndex) -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - auto index = idx.data(ModList::IndexRole).toInt(); - ModInfo::Ptr info = ModInfo::getByIndex(index); - info->ignoreUpdate(true); - m_OrganizerCore.modList()->notifyChange(index); - } - } - else { - ModInfo::Ptr info = ModInfo::getByIndex(modIndex); - info->ignoreUpdate(true); - m_OrganizerCore.modList()->notifyChange(modIndex); - } -} - -void MainWindow::unignoreUpdate(int modIndex) -{ - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 1) { - for (QModelIndex idx : selection->selectedRows()) { - ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); - info->ignoreUpdate(false); - m_OrganizerCore.modList()->notifyChange(idx.data(ModList::IndexRole).toInt()); - } - } - else { - ModInfo::Ptr info = ModInfo::getByIndex(modIndex); - info->ignoreUpdate(false); - m_OrganizerCore.modList()->notifyChange(modIndex); - } -} - -void MainWindow::setPrimaryCategoryCandidates(QMenu *primaryCategoryMenu, - ModInfo::Ptr info) -{ - primaryCategoryMenu->clear(); - const std::set &categories = info->getCategories(); - for (int categoryID : categories) { - int catIdx = m_CategoryFactory.getCategoryIndex(categoryID); - QWidgetAction *action = new QWidgetAction(primaryCategoryMenu); - try { - QRadioButton *categoryBox = new QRadioButton( - m_CategoryFactory.getCategoryName(catIdx).replace('&', "&&"), - primaryCategoryMenu); - connect(categoryBox, &QRadioButton::toggled, [info, categoryID](bool enable) { - if (enable) { - info->setPrimaryCategory(categoryID); - } - }); - categoryBox->setChecked(categoryID == info->primaryCategory()); - action->setDefaultWidget(categoryBox); - } catch (const std::exception &e) { - log::error("failed to create category checkbox: {}", e.what()); - } - - action->setData(categoryID); - primaryCategoryMenu->addAction(action); - } -} - void MainWindow::openInstanceFolder() { QString dataPath = qApp->property("dataPath").toString(); @@ -3549,15 +2716,6 @@ void MainWindow::openMyGamesFolder() shell::Explore(m_OrganizerCore.managedGame()->documentsDirectory()); } -static void addMenuAsPushButton(QMenu *menu, QMenu *subMenu) -{ - QPushButton *pushBtn = new QPushButton(subMenu->title()); - pushBtn->setMenu(subMenu); - QWidgetAction *action = new QWidgetAction(menu); - action->setDefaultWidget(pushBtn); - menu->addAction(action); -} - QMenu *MainWindow::openFolderMenu() { QMenu *FolderMenu = new QMenu(this); @@ -3602,25 +2760,6 @@ void MainWindow::addPluginSendToContextMenu(QMenu *menu) menu->addSeparator(); } -void MainWindow::on_modList_customContextMenuRequested(const QPoint &pos) -{ - try { - QModelIndex contextIdx = mapToModel(m_OrganizerCore.modList(), ui->modList->indexAt(pos)); - - if (!contextIdx.isValid()) { - // no selection - ModListGlobalContextMenu(m_OrganizerCore, ui->modList).exec(ui->modList->viewport()->mapToGlobal(pos)); - } - else { - ModListContextMenu(contextIdx, m_OrganizerCore, m_CategoryFactory, ui->modList).exec(ui->modList->viewport()->mapToGlobal(pos)); - } - } catch (const std::exception &e) { - reportError(tr("Exception: ").arg(e.what())); - } catch (...) { - reportError(tr("Unknown exception")); - } -} - void MainWindow::linkToolbar() { Executable* exe = getSelectedExecutable(); @@ -3799,13 +2938,6 @@ void MainWindow::on_actionNexus_triggered() shell::Open(QUrl(NexusInterface::instance().getGameURL(gameName))); } - -void MainWindow::linkClicked(const QString &url) -{ - shell::Open(QUrl(url)); -} - - void MainWindow::installTranslator(const QString &name) { QTranslator *translator = new QTranslator(this); @@ -3820,7 +2952,6 @@ void MainWindow::installTranslator(const QString &name) m_Translators.push_back(translator); } - void MainWindow::languageChange(const QString &newLanguage) { for (QTranslator *trans : m_Translators) { @@ -3903,7 +3034,6 @@ void MainWindow::updateAvailable() ui->statusBar->setUpdateAvailable(true); } - void MainWindow::motdReceived(const QString &motd) { // don't show motd after 5 seconds, may be annoying. Hopefully the user's @@ -4343,7 +3473,6 @@ void MainWindow::nxmDownloadURLs(QString, int, int, QVariant, QVariant resultDat m_OrganizerCore.settings().network().updateServers(servers); } - void MainWindow::nxmRequestFailed(QString gameName, int modID, int, QVariant, int, QNetworkReply::NetworkError error, const QString &errorString) { if (error == QNetworkReply::ContentAccessDenied || error == QNetworkReply::ContentNotFoundError) { @@ -4367,7 +3496,6 @@ void MainWindow::nxmRequestFailed(QString gameName, int modID, int, QVariant, in } } - BSA::EErrorCode MainWindow::extractBSA(BSA::Archive &archive, BSA::Folder::Ptr folder, const QString &destination, QProgressDialog &progress) { @@ -4732,7 +3860,6 @@ void MainWindow::on_bossButton_clicked() return; } - m_OrganizerCore.savePluginList(); setEnabled(false); @@ -4752,12 +3879,10 @@ void MainWindow::on_bossButton_clicked() } } - const char *MainWindow::PATTERN_BACKUP_GLOB = ".????_??_??_??_??_??"; const char *MainWindow::PATTERN_BACKUP_REGEX = "\\.(\\d\\d\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d)"; const char *MainWindow::PATTERN_BACKUP_DATE = "yyyy_MM_dd_hh_mm_ss"; - bool MainWindow::createBackup(const QString &filePath, const QDateTime &time) { QString outPath = filePath + "." + time.toString(PATTERN_BACKUP_DATE); diff --git a/src/mainwindow.h b/src/mainwindow.h index 61bd9326..1beed2f2 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -208,25 +208,6 @@ private: bool modifyExecutablesDialog(int selection); - /** - * Sets category selections from menu; for multiple mods, this will only apply - * the changes made in the menu (which is the delta between the current menu selection and the reference mod) - * @param menu the menu after editing by the user - * @param modRow index of the mod to edit - * @param referenceRow row of the reference mod - */ - void addRemoveCategoriesFromMenu(QMenu *menu, int modRow, int referenceRow); - - /** - * Sets category selections from menu; for multiple mods, this will completely - * replace the current set of categories on each selected with those selected in the menu - * @param menu the menu after editing by the user - * @param modRow index of the mod to edit - */ - void replaceCategoriesFromMenu(QMenu *menu, int modRow); - - bool populateMenuCategories(int modIndex, QMenu *menu, int targetID); - // remove invalid category-references from mods void fixCategories(); @@ -348,36 +329,14 @@ private slots: void openExplorer_activated(); void refreshProfile_activated(); - // modlist context menu - void installMod_clicked(); - void renameMod_clicked(); - void removeMod_clicked(int modIndex); - void setColor_clicked(int modIndex); - void resetColor_clicked(int modIndex); - void backupMod_clicked(int modIndex); - void reinstallMod_clicked(int modIndex); - void endorse_clicked(); - void dontendorse_clicked(int modIndex); - void unendorse_clicked(); - void track_clicked(); - void untrack_clicked(); - void ignoreMissingData_clicked(int modIndex); - void markConverted_clicked(int modIndex); - void restoreHiddenFiles_clicked(int modIndex); - void visitOnNexus_clicked(int modIndex); - void visitWebPage_clicked(int modIndex); - void visitNexusOrWebPage_clicked(int modIndex); - void openPluginOriginExplorer_clicked(); - void openOriginInformation_clicked(); - void information_clicked(int modIndex); - // data-tree context menu - // pluginlist context menu void enableSelectedPlugins_clicked(); void disableSelectedPlugins_clicked(); void sendSelectedPluginsToTop_clicked(); void sendSelectedPluginsToBottom_clicked(); void sendSelectedPluginsToPriority_clicked(); + void openOriginInformation_clicked(); + void openPluginOriginExplorer_clicked(); void linkToolbar(); void linkDesktop(); @@ -390,10 +349,6 @@ private slots: BSA::EErrorCode extractBSA(BSA::Archive &archive, BSA::Folder::Ptr folder, const QString &destination, QProgressDialog &extractProgress); // nexus related - void checkModsForUpdates(); - - void linkClicked(const QString &url); - void updateAvailable(); void actionEndorseMO(); @@ -403,9 +358,6 @@ private slots: void originModified(int originID); - void setPrimaryCategoryCandidates(QMenu* menu, ModInfo::Ptr info); - void addRemoveCategories_MenuHandler(QMenu* menu, int modIndex, const QModelIndex& rowIdx); - void modInstalled(const QString &modName); void finishUpdateInfo(); @@ -426,17 +378,12 @@ private slots: void onFiltersOptions( ModListSortProxy::FilterMode mode, ModListSortProxy::SeparatorsMode sep); - void visitNexusOrWebPage(const QModelIndex& idx); - void modRenamed(const QString &oldName, const QString &newName); void modRemoved(const QString &fileName); void hookUpWindowTutorials(); bool shouldStartTutorial() const; - void endorseMod(ModInfo::Ptr mod); - void unendorseMod(ModInfo::Ptr mod); - void trackMod(ModInfo::Ptr mod, bool doTrack); void cancelModListEditor(); void openInstanceFolder(); @@ -483,9 +430,6 @@ private slots: void removeFromToolbar(QAction* action); void overwriteClosed(int); - void ignoreUpdate(int modIndex); - void unignoreUpdate(int modIndex); - void about(); void modlistSelectionsChanged(const QItemSelection ¤t); @@ -519,8 +463,6 @@ private slots: // ui slots void on_bsaList_customContextMenuRequested(const QPoint &pos); void on_clearFiltersButton_clicked(); void on_executablesListBox_currentIndexChanged(int index); - void on_modList_customContextMenuRequested(const QPoint &pos); - void on_modList_doubleClicked(const QModelIndex &index); void on_espList_doubleClicked(const QModelIndex &index); void on_profileBox_currentIndexChanged(int index); void on_startButton_clicked(); diff --git a/src/modlistview.cpp b/src/modlistview.cpp index cf35abdd..092ded09 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -19,6 +19,7 @@ #include "modconflicticondelegate.h" #include "modlistviewactions.h" #include "modlistdropinfo.h" +#include "modlistcontextmenu.h" #include "genericicondelegate.h" #include "shared/directoryentry.h" #include "shared/filesorigin.h" @@ -88,6 +89,9 @@ ModListView::ModListView(QWidget* parent) setStyle(new ModListProxyStyle(style())); setItemDelegate(new ModListStyledItemDelegated(this)); + + connect(this, &ModListView::doubleClicked, this, &ModListView::onDoubleClicked); + connect(this, &ModListView::customContextMenuRequested, this, &ModListView::onCustomContextMenuRequested); } void ModListView::refresh() @@ -574,17 +578,7 @@ bool ModListView::moveSelection(int key) bool ModListView::removeSelection() { - if (selectionModel()->hasSelection()) { - QModelIndexList rows = selectionModel()->selectedRows(); - if (rows.count() > 1) { - emit removeSelectedMods(); - } - else if (rows.count() == 1) { - // this does not work, I don't know why - // model()->removeRow(rows[0].row(), rows[0].parent()); - m_core->modList()->removeRow(indexViewToModel(rows[0]).row()); - } - } + m_actions->removeMods(indexViewToModel(selectionModel()->selectedRows())); return true; } @@ -626,10 +620,11 @@ void ModListView::updateGroupByProxy(int groupIndex) } } -void ModListView::setup(OrganizerCore& core, ModListViewActions* actions, Ui::MainWindow* mwui) +void ModListView::setup(OrganizerCore& core, CategoryFactory& factory, ModListViewActions* actions, Ui::MainWindow* mwui) { // attributes m_core = &core; + m_categories = &factory; m_actions = actions; ui = { mwui->groupCombo, mwui->activeModsCounter, mwui->modFilterEdit, mwui->clearFiltersButton }; @@ -760,6 +755,97 @@ QModelIndexList ModListView::selectedIndexes() const return m_inDragMoveEvent ? QModelIndexList() : QTreeView::selectedIndexes(); } +void ModListView::onCustomContextMenuRequested(const QPoint& pos) +{ + try { + QModelIndex contextIdx = indexViewToModel(indexAt(pos)); + + if (!contextIdx.isValid()) { + // no selection + ModListGlobalContextMenu(*m_core, this).exec(viewport()->mapToGlobal(pos)); + } + else { + ModListContextMenu(contextIdx, *m_core, *m_categories, this).exec(viewport()->mapToGlobal(pos)); + } + } + catch (const std::exception& e) { + reportError(tr("Exception: ").arg(e.what())); + } + catch (...) { + reportError(tr("Unknown exception")); + } +} + +void ModListView::onDoubleClicked(const QModelIndex& index) +{ + if (!index.isValid()) { + return; + } + + if (m_core->modList()->timeElapsedSinceLastChecked() <= QApplication::doubleClickInterval()) { + // don't interpret double click if we only just checked a mod + return; + } + + bool indexOk = false; + int modIndex = index.data(ModList::IndexRole).toInt(&indexOk); + + if (!indexOk || modIndex < 0 || modIndex >= ModInfo::getNumMods()) { + return; + } + + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + + Qt::KeyboardModifiers modifiers = QApplication::queryKeyboardModifiers(); + if (modifiers.testFlag(Qt::ControlModifier)) { + try { + shell::Explore(modInfo->absolutePath()); + + // workaround to cancel the editor that might have opened because of + // selection-click + closePersistentEditor(index); + } + catch (const std::exception& e) { + reportError(e.what()); + } + } + else if (modifiers.testFlag(Qt::ShiftModifier)) { + try { + QModelIndex idx = m_core->modList()->index(modIndex, 0); + actions().visitNexusOrWebPage({ idx }); + closePersistentEditor(index); + } + catch (const std::exception& e) { + reportError(e.what()); + } + } + else if (hasCollapsibleSeparators() && modInfo->isSeparator()) { + setExpanded(index, !isExpanded(index)); + } + else { + try { + auto tab = ModInfoTabIDs::None; + + switch (index.column()) { + case ModList::COL_NOTES: tab = ModInfoTabIDs::Notes; break; + case ModList::COL_VERSION: tab = ModInfoTabIDs::Nexus; break; + case ModList::COL_MODID: tab = ModInfoTabIDs::Nexus; break; + case ModList::COL_GAME: tab = ModInfoTabIDs::Nexus; break; + case ModList::COL_CATEGORY: tab = ModInfoTabIDs::Categories; break; + case ModList::COL_CONFLICTFLAGS: tab = ModInfoTabIDs::Conflicts; break; + } + + actions().displayModInformation(modIndex, tab); + // workaround to cancel the editor that might have opened because of + // selection-click + closePersistentEditor(index); + } + catch (const std::exception& e) { + reportError(e.what()); + } + } +} + void ModListView::dragEnterEvent(QDragEnterEvent* event) { emit dragEntered(event->mimeData()); diff --git a/src/modlistview.h b/src/modlistview.h index 4f27769c..e9387cfd 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -13,6 +13,7 @@ namespace Ui { class MainWindow; } +class CategoryFactory; class FilterList; class OrganizerCore; class Profile; @@ -37,7 +38,7 @@ public: explicit ModListView(QWidget* parent = 0); void setModel(QAbstractItemModel* model) override; - void setup(OrganizerCore& core, ModListViewActions* actions, Ui::MainWindow* mwui); + void setup(OrganizerCore& core, CategoryFactory& factory, ModListViewActions* actions, Ui::MainWindow* mwui); // set the current profile // @@ -80,10 +81,6 @@ signals: void dragEntered(const QMimeData* mimeData); void dropEntered(const QMimeData* mimeData, DropPosition position); - // emitted when selected mods must be removed - // - void removeSelectedMods(); - public slots: // enable/disable all visible mods @@ -142,6 +139,9 @@ protected: protected slots: + void onCustomContextMenuRequested(const QPoint& pos); + void onDoubleClicked(const QModelIndex& index); + private: void onModPrioritiesChanged(std::vector const& indices); @@ -180,6 +180,7 @@ private: }; OrganizerCore* m_core; + CategoryFactory* m_categories; ModListViewUi ui; ModListViewActions* m_actions; -- cgit v1.3.1 From 2ed9db7aab5d60bc419787dad53a491a62ef15e7 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 11:50:02 +0100 Subject: Move creations of actions to ModListView. --- src/mainwindow.cpp | 8 +++----- src/modlistview.cpp | 6 ++++-- src/modlistview.h | 3 ++- 3 files changed, 9 insertions(+), 8 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index caf533f2..2ca15b00 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -533,12 +533,10 @@ MainWindow::MainWindow(Settings &settings void MainWindow::setupModList() { - auto* actions = new ModListViewActions(m_OrganizerCore, *m_Filters, m_CategoryFactory, this, ui->modList); - ui->modList->setup(m_OrganizerCore, m_CategoryFactory, actions, ui); + ui->modList->setup(m_OrganizerCore, m_CategoryFactory, *m_Filters, this, ui); - connect(actions, &ModListViewActions::overwriteCleared, [=]() { scheduleCheckForProblems(); }); - connect(actions, &ModListViewActions::originModified, this, &MainWindow::originModified); - connect(m_OrganizerCore.modList(), &ModList::clearOverwrite, actions, &ModListViewActions::clearOverwrite); + connect(&ui->modList->actions(), &ModListViewActions::overwriteCleared, [=]() { scheduleCheckForProblems(); }); + connect(&ui->modList->actions(), &ModListViewActions::originModified, this, &MainWindow::originModified); connect(m_OrganizerCore.modList(), &ModList::modPrioritiesChanged, [&]() { m_ArchiveListWriter.write(); }); // keep here for now diff --git a/src/modlistview.cpp b/src/modlistview.cpp index 092ded09..40959e6d 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -620,16 +620,18 @@ void ModListView::updateGroupByProxy(int groupIndex) } } -void ModListView::setup(OrganizerCore& core, CategoryFactory& factory, ModListViewActions* actions, Ui::MainWindow* mwui) + +void ModListView::setup(OrganizerCore& core, CategoryFactory& factory, FilterList& filters, MainWindow* mw, Ui::MainWindow* mwui) { // attributes m_core = &core; m_categories = &factory; - m_actions = actions; + m_actions = new ModListViewActions(core, filters, factory, mw, this); ui = { mwui->groupCombo, mwui->activeModsCounter, mwui->modFilterEdit, mwui->clearFiltersButton }; connect(m_core, &OrganizerCore::modInstalled, this, &ModListView::onModInstalled); connect(core.modList(), &ModList::modPrioritiesChanged, this, &ModListView::onModPrioritiesChanged); + connect(core.modList(), &ModList::clearOverwrite, m_actions, &ModListViewActions::clearOverwrite); m_byPriorityProxy = new ModListByPriorityProxy(core.currentProfile(), core, this); m_byPriorityProxy->setSourceModel(core.modList()); diff --git a/src/modlistview.h b/src/modlistview.h index e9387cfd..1678d01e 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -16,6 +16,7 @@ namespace Ui { class MainWindow; } class CategoryFactory; class FilterList; class OrganizerCore; +class MainWindow; class Profile; class ModListByPriorityProxy; class ModListViewActions; @@ -38,7 +39,7 @@ public: explicit ModListView(QWidget* parent = 0); void setModel(QAbstractItemModel* model) override; - void setup(OrganizerCore& core, CategoryFactory& factory, ModListViewActions* actions, Ui::MainWindow* mwui); + void setup(OrganizerCore& core, CategoryFactory& factory, FilterList& filters, MainWindow* mw, Ui::MainWindow* mwui); // set the current profile // -- cgit v1.3.1 From a105e4c8c881ac720c41ef342769adee14caca47 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 12:34:17 +0100 Subject: Move more stuff from MainWindow. Minor improvements for prev/next button in ModInfoDialog. --- src/mainwindow.cpp | 29 ---------------------------- src/mainwindow.h | 4 ---- src/modinfodialog.cpp | 48 +++++++++++++++++++++++++++++----------------- src/modinfodialog.h | 16 ++++++++++------ src/modlistview.cpp | 20 +++++++++++++++---- src/modlistview.h | 8 ++++---- src/modlistviewactions.cpp | 7 ++++++- src/organizercore.cpp | 1 - 8 files changed, 66 insertions(+), 67 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 2ca15b00..3d509379 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -48,7 +48,6 @@ along with Mod Organizer. If not, see . #include "categories.h" #include "categoriesdialog.h" #include "genericicondelegate.h" -#include "modinfodialog.h" #include "overwriteinfodialog.h" #include "downloadlist.h" #include "downloadlistwidget.h" @@ -2377,16 +2376,6 @@ void MainWindow::windowTutorialFinished(const QString &windowName) m_OrganizerCore.settings().interface().setTutorialCompleted(windowName); } -void MainWindow::overwriteClosed(int) -{ - OverwriteInfoDialog *dialog = this->findChild("__overwriteDialog"); - if (dialog != nullptr) { - m_OrganizerCore.modList()->modInfoChanged(dialog->modInfo()); - dialog->deleteLater(); - } - m_OrganizerCore.refreshDirectoryStructure(); -} - void MainWindow::displayModInformation(ModInfo::Ptr modInfo, unsigned int modIndex, ModInfoTabIDs tabID) { ui->modList->actions().displayModInformation(modInfo, modIndex, tabID); @@ -2402,24 +2391,6 @@ void MainWindow::setWindowEnabled(bool enabled) setEnabled(enabled); } -ModInfo::Ptr MainWindow::nextModInList(int modIndex) -{ - modIndex = ui->modList->nextMod(modIndex); - if (modIndex == -1) { - return {}; - } - return ModInfo::getByIndex(modIndex); -} - -ModInfo::Ptr MainWindow::previousModInList(int modIndex) -{ - modIndex = ui->modList->prevMod(modIndex); - if (modIndex == -1) { - return {}; - } - return ModInfo::getByIndex(modIndex); -} - void MainWindow::openPluginOriginExplorer_clicked() { QItemSelectionModel *selection = ui->espList->selectionModel(); diff --git a/src/mainwindow.h b/src/mainwindow.h index 1beed2f2..d80f4f63 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -142,9 +142,6 @@ public: virtual MOBase::DelayedFileWriterBase &archivesWriter() override { return m_ArchiveListWriter; } - ModInfo::Ptr nextModInList(int modIndex); - ModInfo::Ptr previousModInList(int modIndex); - public slots: void esplist_changed(); void refresherProgress(const DirectoryRefreshProgress* p); @@ -428,7 +425,6 @@ private slots: void toolBar_customContextMenuRequested(const QPoint &point); void removeFromToolbar(QAction* action); - void overwriteClosed(int); void about(); diff --git a/src/modinfodialog.cpp b/src/modinfodialog.cpp index cb282195..54c97406 100644 --- a/src/modinfodialog.cpp +++ b/src/modinfodialog.cpp @@ -21,7 +21,7 @@ along with Mod Organizer. If not, see . #include "ui_modinfodialog.h" #include "plugincontainer.h" #include "organizercore.h" -#include "mainwindow.h" +#include "modlistview.h" #include "modinfodialogtextfiles.h" #include "modinfodialogimages.h" #include "modinfodialogesps.h" @@ -176,11 +176,14 @@ bool ModInfoDialog::TabInfo::isVisible() const ModInfoDialog::ModInfoDialog( - MainWindow* mw, OrganizerCore* core, PluginContainer* plugin, - ModInfo::Ptr mod) : - TutorableDialog("ModInfoDialog", mw), - ui(new Ui::ModInfoDialog), m_mainWindow(mw), - m_core(core), m_plugin(plugin), m_initialTab(ModInfoTabIDs::None), + OrganizerCore& core, PluginContainer& plugin, + ModInfo::Ptr mod, ModListView* modListView) : + TutorableDialog("ModInfoDialog", modListView), + ui(new Ui::ModInfoDialog), + m_core(core), + m_plugin(plugin), + m_modListView(modListView), + m_initialTab(ModInfoTabIDs::None), m_arrangingTabs(false) { ui->setupUi(this); @@ -204,7 +207,7 @@ template std::unique_ptr createTab(ModInfoDialog& d, ModInfoTabIDs id) { return std::make_unique(ModInfoDialogTabContext( - *d.m_core, *d.m_plugin, &d, d.ui.get(), id, d.m_mod, d.getOrigin())); + d.m_core, d.m_plugin, &d, d.ui.get(), id, d.m_mod, d.getOrigin())); } void ModInfoDialog::createTabs() @@ -269,7 +272,7 @@ int ModInfoDialog::exec() update(true); if (noCustomTabRequested) { - m_core->settings().widgets().restoreIndex(ui->tabWidget); + m_core.settings().widgets().restoreIndex(ui->tabWidget); } const int r = TutorableDialog::exec(); @@ -430,7 +433,7 @@ void ModInfoDialog::reAddTabs( Q_ASSERT(visibility.size() == m_tabs.size()); // ordered tab names from settings - const auto orderedNames = m_core->settings().geometry().modInfoTabOrder(); + const auto orderedNames = m_core.settings().geometry().modInfoTabOrder(); // whether the tabs can be sorted // @@ -586,7 +589,7 @@ void ModInfoDialog::feedFiles(std::vector& interestedTabs) void ModInfoDialog::setTabsColors() { - const auto p = m_mainWindow->palette(); + const auto p = m_modListView->parentWidget()->palette(); for (const auto& tabInfo : m_tabs) { if (!tabInfo.isVisible()) { @@ -619,7 +622,7 @@ void ModInfoDialog::switchToTab(ModInfoTabIDs id) MOShared::FilesOrigin* ModInfoDialog::getOrigin() { - auto* ds = m_core->directoryStructure(); + auto* ds = m_core.directoryStructure(); if (!ds->originExists(m_mod->name().toStdWString())) { return nullptr; @@ -639,7 +642,7 @@ void ModInfoDialog::saveState() const // save state for each tab for (const auto& tabInfo : m_tabs) { - tabInfo.tab->saveState(m_core->settings()); + tabInfo.tab->saveState(m_core.settings()); } } @@ -650,7 +653,7 @@ void ModInfoDialog::restoreState() // restore state for each tab for (const auto& tabInfo : m_tabs) { - tabInfo.tab->restoreState(m_core->settings()); + tabInfo.tab->restoreState(m_core.settings()); } } @@ -678,9 +681,9 @@ void ModInfoDialog::saveTabOrder() const names += ui->tabWidget->widget(i)->objectName(); } - m_core->settings().geometry().setModInfoTabOrder(names); + m_core.settings().geometry().setModInfoTabOrder(names); // save last opened index - m_core->settings().widgets().saveIndex(ui->tabWidget); + m_core.settings().widgets().saveIndex(ui->tabWidget); } void ModInfoDialog::onOriginModified(int originID) @@ -776,22 +779,31 @@ void ModInfoDialog::onTabMoved() void ModInfoDialog::onNextMod() { - auto mod = m_mainWindow->nextModInList(ModInfo::getIndex(m_mod->name())); + auto index = m_modListView->nextMod(ModInfo::getIndex(m_mod->name())); + if (!index) { + return; + } + auto mod = ModInfo::getByIndex(*index); if (!mod || mod == m_mod) { return; } setMod(mod); update(); + + emit modChanged(*index); } void ModInfoDialog::onPreviousMod() { - auto mod = m_mainWindow->previousModInList(ModInfo::getIndex(m_mod->name())); - if (!mod || mod == m_mod) { + auto index = m_modListView->prevMod(ModInfo::getIndex(m_mod->name())); + if (!index) { return; } + auto mod = ModInfo::getByIndex(*index); setMod(mod); update(); + + emit modChanged(*index); } diff --git a/src/modinfodialog.h b/src/modinfodialog.h index 48680ca4..a3b6ffdb 100644 --- a/src/modinfodialog.h +++ b/src/modinfodialog.h @@ -33,7 +33,7 @@ class PluginContainer; class OrganizerCore; class Settings; class ModInfoDialogTab; -class MainWindow; +class ModListView; /** * this is a larger dialog used to visualise information about the mod. @@ -52,8 +52,8 @@ class ModInfoDialog : public MOBase::TutorableDialog public: ModInfoDialog( - MainWindow* mw, OrganizerCore* core, PluginContainer* plugin, - ModInfo::Ptr mod); + OrganizerCore& core, PluginContainer& plugin, + ModInfo::Ptr mod, ModListView* view); ~ModInfoDialog(); @@ -71,6 +71,10 @@ signals: // void originModified(int originID); + // emitted when the mod of the dialog is changed + // + void modChanged(unsigned int modIndex); + protected: // forwards to tryClose() // @@ -115,10 +119,10 @@ private: }; std::unique_ptr ui; - MainWindow* m_mainWindow; + OrganizerCore& m_core; + PluginContainer& m_plugin; + ModListView* m_modListView; ModInfo::Ptr m_mod; - OrganizerCore* m_core; - PluginContainer* m_plugin; std::vector m_tabs; // initial tab requested by the main window when the dialog is opened; whether diff --git a/src/modlistview.cpp b/src/modlistview.cpp index 40959e6d..f2b83beb 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -128,7 +128,7 @@ ModListViewActions& ModListView::actions() const return *m_actions; } -int ModListView::nextMod(int modIndex) const +std::optional ModListView::nextMod(unsigned int modIndex) const { const QModelIndex start = indexModelToView(m_core->modList()->index(modIndex, 0)); @@ -156,10 +156,10 @@ int ModListView::nextMod(int modIndex) const return modIndex; } - return -1; + return {}; } -int ModListView::prevMod(int modIndex) const +std::optional ModListView::prevMod(unsigned int modIndex) const { const QModelIndex start = indexModelToView(m_core->modList()->index(modIndex, 0)); @@ -187,7 +187,7 @@ int ModListView::prevMod(int modIndex) const return modIndex; } - return -1; + return {}; } void ModListView::enableAllVisible() @@ -730,6 +730,7 @@ void ModListView::setup(OrganizerCore& core, CategoryFactory& factory, FilterLis m_byPriorityProxy->refreshExpandedItems(); } }); + connect(selectionModel(), &QItemSelectionModel::selectionChanged, this, &ModListView::onSelectionChanged); } void ModListView::setModel(QAbstractItemModel* model) @@ -848,6 +849,17 @@ void ModListView::onDoubleClicked(const QModelIndex& index) } } +void ModListView::onSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected) +{ + if (hasCollapsibleSeparators()) { + for (auto& idx : selected.indexes()) { + if (idx.parent().isValid() && !isExpanded(idx.parent())) { + setExpanded(idx.parent(), true); + } + } + } +} + void ModListView::dragEnterEvent(QDragEnterEvent* event) { emit dragEntered(event->mimeData()); diff --git a/src/modlistview.h b/src/modlistview.h index 1678d01e..c7f4e5f0 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -58,11 +58,10 @@ public: ModListViewActions& actions() const; // retrieve the next/previous mod in the current view, the given index - // should be a mod index (not a model row), and the return value will be - // a mod index or -1 if no mod was found + // should be a mod index (not a model row) // - int nextMod(int index) const; - int prevMod(int index) const; + std::optional nextMod(unsigned int index) const; + std::optional prevMod(unsigned int index) const; // check if the given mod is visible // @@ -142,6 +141,7 @@ protected slots: void onCustomContextMenuRequested(const QPoint& pos); void onDoubleClicked(const QModelIndex& index); + void onSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); private: diff --git a/src/modlistviewactions.cpp b/src/modlistviewactions.cpp index 2b5bf026..3cc2a841 100644 --- a/src/modlistviewactions.cpp +++ b/src/modlistviewactions.cpp @@ -433,8 +433,13 @@ void ModListViewActions::displayModInformation(ModInfo::Ptr modInfo, unsigned in else { modInfo->saveMeta(); - ModInfoDialog dialog(m_main, &m_core, &m_core.pluginContainer(), modInfo); + ModInfoDialog dialog(m_core, m_core.pluginContainer(), modInfo, m_view); 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) { diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 507932e2..17cd80c2 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -15,7 +15,6 @@ #include "profile.h" #include "credentialsdialog.h" #include "filedialogmemory.h" -#include "modinfodialog.h" #include "spawn.h" #include "syncoverwritedialog.h" #include "nxmaccessmanager.h" -- cgit v1.3.1 From a19ede5b6faaf8bf5299ae02da92e8d604e39468 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 13:25:42 +0100 Subject: Move filter list to ModListView. --- src/filterlist.cpp | 6 +-- src/filterlist.h | 4 +- src/mainwindow.cpp | 109 ++-------------------------------------------- src/mainwindow.h | 8 ---- src/modlistview.cpp | 122 ++++++++++++++++++++++++++++++++++++++++++++++------ src/modlistview.h | 23 +++++++++- 6 files changed, 140 insertions(+), 132 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/filterlist.cpp b/src/filterlist.cpp index 2b72c152..c3f169a6 100644 --- a/src/filterlist.cpp +++ b/src/filterlist.cpp @@ -181,8 +181,8 @@ private: }; -FilterList::FilterList(Ui::MainWindow* ui, OrganizerCore* organizer, CategoryFactory& factory) - : ui(ui), m_Organizer(organizer), m_factory(factory) +FilterList::FilterList(Ui::MainWindow* ui, OrganizerCore& core, CategoryFactory& factory) + : ui(ui), m_core(core), m_factory(factory) { auto* eventFilter = new CriteriaItemFilter( ui->filters, [&](auto* item, int dir){ return cycleItem(item, dir); }); @@ -234,7 +234,7 @@ QTreeWidgetItem* FilterList::addCriteriaItem( void FilterList::addContentCriteria() { - m_Organizer->modDataContents().forEachContent([this](auto const& content) { + m_core.modDataContents().forEachContent([this](auto const& content) { addCriteriaItem( nullptr, QString("<%1>").arg(tr("Contains %1").arg(content.name())), content.id(), ModListSortProxy::TypeContent); diff --git a/src/filterlist.h b/src/filterlist.h index ba9dc71c..0788d224 100644 --- a/src/filterlist.h +++ b/src/filterlist.h @@ -14,7 +14,7 @@ class FilterList : public QObject Q_OBJECT; public: - FilterList(Ui::MainWindow* ui, OrganizerCore *organizer, CategoryFactory& factory); + FilterList(Ui::MainWindow* ui, OrganizerCore& organizer, CategoryFactory& factory); void restoreState(const Settings& s); void saveState(Settings& s) const; @@ -32,7 +32,7 @@ private: class CriteriaItem; Ui::MainWindow* ui; - OrganizerCore* m_Organizer; + OrganizerCore& m_core; CategoryFactory& m_factory; bool onClick(QMouseEvent* e); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 3d509379..df4a875e 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -310,16 +310,6 @@ MainWindow::MainWindow(Settings &settings ui->statusBar->setAPI(ni.getAPIStats(), ni.getAPIUserAccount()); } - m_Filters.reset(new FilterList(ui, &m_OrganizerCore, m_CategoryFactory)); - - connect( - m_Filters.get(), &FilterList::criteriaChanged, - [&](auto&& v) { onFiltersCriteria(v); }); - - connect( - m_Filters.get(), &FilterList::optionsChanged, - [&](auto&& mode, auto&& sep) { onFiltersOptions(mode, sep); }); - ui->logList->setCore(m_OrganizerCore); @@ -532,7 +522,7 @@ MainWindow::MainWindow(Settings &settings void MainWindow::setupModList() { - ui->modList->setup(m_OrganizerCore, m_CategoryFactory, *m_Filters, this, ui); + 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); @@ -1224,7 +1214,7 @@ void MainWindow::showEvent(QShowEvent *event) if (!m_WasVisible) { readSettings(); - refreshFilters(); + ui->modList->refreshFilters(); // this needs to be connected here instead of in the constructor because the // actual changing of the stylesheet is done by MOApplication, which @@ -1952,11 +1942,9 @@ void MainWindow::readSettings() ui->executablesListBox->setCurrentIndex(*v); } - s.widgets().restoreIndex(ui->groupCombo); s.widgets().restoreIndex(ui->tabWidget); - s.widgets().restoreTreeState(ui->modList); - m_Filters->restoreState(s); + ui->modList->restoreState(s); { s.geometry().restoreVisibility(ui->categoriesGroup, false); @@ -2027,14 +2015,10 @@ void MainWindow::storeSettings() s.geometry().saveState(ui->espList->header()); s.geometry().saveState(ui->downloadView->header()); - s.geometry().saveState(ui->modList->header()); - s.widgets().saveTreeState(ui->modList); - s.widgets().saveIndex(ui->groupCombo); s.widgets().saveIndex(ui->executablesListBox); s.widgets().saveIndex(ui->tabWidget); - m_Filters->saveState(s); m_DataTab->saveState(s); s.interface().setFilterOptions(FilterWidget::options()); @@ -2340,20 +2324,6 @@ void MainWindow::modlistChanged(const QModelIndexList&, int) void MainWindow::modlistSelectionsChanged(const QItemSelection &selected) { - if (selected.count()) { - auto selection = selected.last(); - auto index = selection.indexes().last(); - ModInfo::Ptr selectedMod = ModInfo::getByIndex(index.data(ModList::IndexRole).toInt()); - m_OrganizerCore.modList()->setOverwriteMarkers(selectedMod->getModOverwrite(), selectedMod->getModOverwritten()); - m_OrganizerCore.modList()->setArchiveOverwriteMarkers(selectedMod->getModArchiveOverwrite(), selectedMod->getModArchiveOverwritten()); - m_OrganizerCore.modList()->setArchiveLooseOverwriteMarkers(selectedMod->getModArchiveLooseOverwrite(), selectedMod->getModArchiveLooseOverwritten()); - } else { - m_OrganizerCore.modList()->setOverwriteMarkers(std::set(), std::set()); - m_OrganizerCore.modList()->setArchiveOverwriteMarkers(std::set(), std::set()); - m_OrganizerCore.modList()->setArchiveLooseOverwriteMarkers(std::set(), std::set()); - } - ui->modList->verticalScrollBar()->repaint(); - m_OrganizerCore.pluginList()->highlightPlugins(ui->modList->selectionModel(), *m_OrganizerCore.directoryStructure(), *m_OrganizerCore.currentProfile()); ui->espList->verticalScrollBar()->repaint(); } @@ -2823,7 +2793,7 @@ void MainWindow::on_actionSettings_triggered() scheduleCheckForProblems(); fixCategories(); - refreshFilters(); + ui->modList->refreshFilters(); ui->modList->refresh(); if (settings.paths().profiles() != oldProfilesDirectory) { @@ -2963,7 +2933,6 @@ void MainWindow::originModified(int originID) DirectoryRefresher::cleanStructure(m_OrganizerCore.directoryStructure()); } - void MainWindow::enableSelectedPlugins_clicked() { m_OrganizerCore.pluginList()->enableSelected(ui->espList->selectionModel()); @@ -3606,70 +3575,6 @@ void MainWindow::on_displayCategoriesBtn_toggled(bool checked) setCategoryListVisible(checked); } -void MainWindow::deselectFilters() -{ - m_Filters->clearSelection(); -} - -void MainWindow::refreshFilters() -{ - QItemSelection currentSelection = ui->modList->selectionModel()->selection(); - - int idxRow = ui->modList->currentIndex().row(); - QVariant currentIndexName = ui->modList->model()->index(idxRow, 0).data(); - ui->modList->setCurrentIndex(QModelIndex()); - - m_Filters->refresh(); - - ui->modList->selectionModel()->select(currentSelection, QItemSelectionModel::Select); - - QModelIndexList matchList; - if (currentIndexName.isValid()) { - matchList = ui->modList->model()->match( - ui->modList->model()->index(0, 0), - Qt::DisplayRole, - currentIndexName); - } - - if (matchList.size() > 0) { - ui->modList->setCurrentIndex(matchList.at(0)); - } -} - -void MainWindow::onFiltersCriteria(const std::vector& criteria) -{ - ui->modList->setFilterCriteria(criteria); - - QString label = "?"; - - if (criteria.empty()) { - label = ""; - } else if (criteria.size() == 1) { - const auto& c = criteria[0]; - - if (c.type == ModListSortProxy::TypeContent) { - const auto *content = m_OrganizerCore.modDataContents().findById(c.id); - label = content ? content->name() : QString(); - } else { - label = m_CategoryFactory.getCategoryNameByID(c.id); - } - - if (label.isEmpty()) { - log::error("category {}:{} not found", c.type, c.id); - } - } else { - label = tr(""); - } - - ui->currentCategoryLabel->setText(label); -} - -void MainWindow::onFiltersOptions( - ModListSortProxy::FilterMode mode, ModListSortProxy::SeparatorsMode sep) -{ - ui->modList->setFilterOptions(mode, sep); -} - void MainWindow::updateESPLock(int espIndex, bool locked) { QItemSelection currentSelection = ui->espList->selectionModel()->selection(); @@ -4079,9 +3984,3 @@ void MainWindow::keyReleaseEvent(QKeyEvent *event) QMainWindow::keyReleaseEvent(event); } - -void MainWindow::on_clearFiltersButton_clicked() -{ - ui->modFilterEdit->clear(); - deselectFilters(); -} diff --git a/src/mainwindow.h b/src/mainwindow.h index d80f4f63..d07fe54c 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -149,7 +149,6 @@ public slots: void directory_refreshed(); void updatePluginCount(); - void refreshFilters(); signals: @@ -253,7 +252,6 @@ private: MOBase::TutorialControl m_Tutorial; - std::unique_ptr m_Filters; std::unique_ptr m_DataTab; std::unique_ptr m_DownloadsTab; std::unique_ptr m_SavesTab; @@ -370,11 +368,6 @@ private slots: void onRequestsChanged(const APIStats& stats, const APIUserAccount& user); - void deselectFilters(); - void onFiltersCriteria(const std::vector& filters); - void onFiltersOptions( - ModListSortProxy::FilterMode mode, ModListSortProxy::SeparatorsMode sep); - void modRenamed(const QString &oldName, const QString &newName); void modRemoved(const QString &fileName); @@ -457,7 +450,6 @@ private slots: // ui slots void on_centralWidget_customContextMenuRequested(const QPoint &pos); void on_bsaList_customContextMenuRequested(const QPoint &pos); - void on_clearFiltersButton_clicked(); void on_executablesListBox_currentIndexChanged(int index); void on_espList_doubleClicked(const QModelIndex &index); void on_profileBox_currentIndexChanged(int index); diff --git a/src/modlistview.cpp b/src/modlistview.cpp index f2b83beb..fe2517c2 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -10,6 +10,7 @@ #include "ui_mainwindow.h" +#include "filterlist.h" #include "organizercore.h" #include "modlist.h" #include "modlistsortproxy.h" @@ -327,6 +328,20 @@ QModelIndexList ModListView::allIndex( return index; } +std::pair ModListView::selected() const +{ + return { indexViewToModel(currentIndex()), indexViewToModel(selectionModel()->selectedRows()) }; +} + +void ModListView::setSelected(const QModelIndex& current, const QModelIndexList& selected) +{ + // reset the selection and the index + setCurrentIndex(indexModelToView(current)); + for (auto idx : selected) { + selectionModel()->select(indexModelToView(idx), QItemSelectionModel::Select | QItemSelectionModel::Rows); + } +} + void ModListView::expandItem(const QModelIndex& index) { if (index.model() == m_sortProxy->sourceModel()) { expand(m_sortProxy->mapFromSource(index)); @@ -515,6 +530,19 @@ void ModListView::updateModCount() ); } +void ModListView::refreshFilters() +{ + auto [current, sourceRows] = selected(); + + int idxRow = currentIndex().row(); + QVariant currentIndexName = model()->index(idxRow, 0).data(); + setCurrentIndex(QModelIndex()); + + m_filters->refresh(); + + setSelected(current, sourceRows); +} + void ModListView::onExternalFolderDropped(const QUrl& url, int priority) { QFileInfo fileInfo(url.toLocalFile()); @@ -557,8 +585,7 @@ void ModListView::onExternalFolderDropped(const QUrl& url, int priority) bool ModListView::moveSelection(int key) { - QModelIndex cindex = indexViewToModel(currentIndex()); - QModelIndexList sourceRows = indexViewToModel(selectionModel()->selectedRows()); + auto [cindex, sourceRows] = selected(); int offset = key == Qt::Key_Up ? -1 : 1; if (m_sortProxy->sortOrder() == Qt::DescendingOrder) { @@ -568,10 +595,7 @@ bool ModListView::moveSelection(int key) m_core->modList()->shiftModsPriority(sourceRows, offset); // reset the selection and the index - setCurrentIndex(indexModelToView(cindex)); - for (auto idx : sourceRows) { - selectionModel()->select(indexModelToView(idx), QItemSelectionModel::Select | QItemSelectionModel::Rows); - } + setSelected(cindex, sourceRows); return true; } @@ -620,14 +644,14 @@ void ModListView::updateGroupByProxy(int groupIndex) } } - -void ModListView::setup(OrganizerCore& core, CategoryFactory& factory, FilterList& filters, MainWindow* mw, Ui::MainWindow* mwui) +void ModListView::setup(OrganizerCore& core, CategoryFactory& factory, MainWindow* mw, Ui::MainWindow* mwui) { // attributes m_core = &core; + m_filters.reset(new FilterList(mwui, core, factory)); m_categories = &factory; - m_actions = new ModListViewActions(core, filters, factory, mw, this); - ui = { mwui->groupCombo, mwui->activeModsCounter, mwui->modFilterEdit, mwui->clearFiltersButton }; + m_actions = new ModListViewActions(core, *m_filters, factory, mw, this); + ui = { mwui->groupCombo, mwui->activeModsCounter, mwui->modFilterEdit, mwui->currentCategoryLabel, mwui->clearFiltersButton }; connect(m_core, &OrganizerCore::modInstalled, this, &ModListView::onModInstalled); connect(core.modList(), &ModList::modPrioritiesChanged, this, &ModListView::onModPrioritiesChanged); @@ -724,13 +748,41 @@ void ModListView::setup(OrganizerCore& core, CategoryFactory& factory, FilterLis connect(m_core->modList(), &ModList::externalFolderDropped, this, &ModListView::onExternalFolderDropped); connect(m_sortProxy, &ModListSortProxy::filterActive, this, &ModListView::onModFilterActive); - connect(ui.filter, &QLineEdit::textChanged, m_sortProxy, &ModListSortProxy::updateFilter); connect(m_sortProxy, &QAbstractItemModel::layoutChanged, this, [&]() { if (hasCollapsibleSeparators()) { m_byPriorityProxy->refreshExpandedItems(); } - }); + }); connect(selectionModel(), &QItemSelectionModel::selectionChanged, this, &ModListView::onSelectionChanged); + + // filters + connect(m_filters.get(), &FilterList::criteriaChanged, [=](auto&& v) { onFiltersCriteria(v); }); + connect(m_filters.get(), &FilterList::optionsChanged, [=](auto&& mode, auto&& sep) { setFilterOptions(mode, sep); }); + connect(ui.filter, &QLineEdit::textChanged, m_sortProxy, &ModListSortProxy::updateFilter); + connect(ui.clearFilters, &QPushButton::clicked, [=]() { + ui.filter->clear(); + m_filters->clearSelection(); + }); +} + +void ModListView::restoreState(const Settings& s) +{ + s.geometry().restoreState(header()); + + s.widgets().restoreIndex(ui.groupBy); + s.widgets().restoreTreeState(this); + + m_filters->restoreState(s); +} + +void ModListView::saveState(Settings& s) const +{ + s.geometry().saveState(header()); + + s.widgets().saveIndex(ui.groupBy); + s.widgets().saveTreeState(this); + + m_filters->saveState(s); } void ModListView::setModel(QAbstractItemModel* model) @@ -858,6 +910,52 @@ void ModListView::onSelectionChanged(const QItemSelection& selected, const QItem } } } + + if (selected.count()) { + auto index = selected.indexes().last(); + ModInfo::Ptr selectedMod = ModInfo::getByIndex(index.data(ModList::IndexRole).toInt()); + m_core->modList()->setOverwriteMarkers(selectedMod->getModOverwrite(), selectedMod->getModOverwritten()); + m_core->modList()->setArchiveOverwriteMarkers(selectedMod->getModArchiveOverwrite(), selectedMod->getModArchiveOverwritten()); + m_core->modList()->setArchiveLooseOverwriteMarkers(selectedMod->getModArchiveLooseOverwrite(), selectedMod->getModArchiveLooseOverwritten()); + } + else { + m_core->modList()->setOverwriteMarkers({}, {}); + m_core->modList()->setArchiveOverwriteMarkers({}, {}); + m_core->modList()->setArchiveLooseOverwriteMarkers({}, {}); + } + verticalScrollBar()->repaint(); + +} + +void ModListView::onFiltersCriteria(const std::vector& criteria) +{ + setFilterCriteria(criteria); + + QString label = "?"; + + if (criteria.empty()) { + label = ""; + } + else if (criteria.size() == 1) { + const auto& c = criteria[0]; + + if (c.type == ModListSortProxy::TypeContent) { + const auto* content = m_core->modDataContents().findById(c.id); + label = content ? content->name() : QString(); + } + else { + label = m_categories->getCategoryNameByID(c.id); + } + + if (label.isEmpty()) { + log::error("category {}:{} not found", c.type, c.id); + } + } + else { + label = tr(""); + } + + ui.currentCategory->setText(label); } void ModListView::dragEnterEvent(QDragEnterEvent* event) diff --git a/src/modlistview.h b/src/modlistview.h index c7f4e5f0..87d8eac5 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -3,6 +3,7 @@ #include +#include #include #include #include @@ -39,7 +40,12 @@ public: explicit ModListView(QWidget* parent = 0); void setModel(QAbstractItemModel* model) override; - void setup(OrganizerCore& core, CategoryFactory& factory, FilterList& filters, MainWindow* mw, Ui::MainWindow* mwui); + void setup(OrganizerCore& core, CategoryFactory& factory, MainWindow* mw, Ui::MainWindow* mwui); + + // restore/save the state between session + // + void restoreState(const Settings& s); + void saveState(Settings& s) const; // set the current profile // @@ -97,6 +103,10 @@ public slots: // void updateModCount(); + // refresh the filters + // + void refreshFilters(); + // map from/to the view indexes to the model // QModelIndex indexModelToView(const QModelIndex& index) const; @@ -142,6 +152,7 @@ protected slots: void onCustomContextMenuRequested(const QPoint& pos); void onDoubleClicked(const QModelIndex& index); void onSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); + void onFiltersCriteria(const std::vector& filters); private: @@ -149,6 +160,12 @@ private: void onModInstalled(const QString& modName); void onModFilterActive(bool filterActive); + // get/set the selected items on the view, this method return/take indices + // from the mod list model, not the view, so it's safe to restore + // + std::pair selected() const; + void setSelected(const QModelIndex& current, const QModelIndexList& selected); + // call expand() after fixing the index if it comes from the source // of the proxy // @@ -175,12 +192,14 @@ private: // the mod counter QLCDNumber* counter; - // the text filter and clear filter button + // filters related QLineEdit* filter; + QLabel* currentCategory; QPushButton* clearFilters; }; OrganizerCore* m_core; + std::unique_ptr m_filters; CategoryFactory* m_categories; ModListViewUi ui; ModListViewActions* m_actions; -- cgit v1.3.1 From ca5beac25189f0512d3f5c32e8d075ddba97fead Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 17:16:15 +0100 Subject: Remove cancelModListEditor (unused). --- src/mainwindow.cpp | 6 ------ src/mainwindow.h | 2 -- 2 files changed, 8 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index df4a875e..b000ba57 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2478,12 +2478,6 @@ void MainWindow::updatePluginCount() ); } -void MainWindow::cancelModListEditor() -{ - ui->modList->setEnabled(false); - ui->modList->setEnabled(true); -} - void MainWindow::openOriginInformation_clicked() { try { diff --git a/src/mainwindow.h b/src/mainwindow.h index d07fe54c..75e7124c 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -374,8 +374,6 @@ private slots: void hookUpWindowTutorials(); bool shouldStartTutorial() const; - void cancelModListEditor(); - void openInstanceFolder(); void openLogsFolder(); void openInstallFolder(); -- cgit v1.3.1 From f2d8469ed6cd0fafc22097cdba2ee8f325f00513 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 21:02:04 +0100 Subject: Start moving stuff from MainWindow to PluginListView. --- src/CMakeLists.txt | 1 + src/mainwindow.cpp | 88 +++----------------------- src/mainwindow.h | 5 -- src/modelutils.cpp | 58 ++++++++++++++++++ src/modelutils.h | 14 +++++ src/modlistview.cpp | 51 +++------------ src/modlistviewactions.cpp | 23 ++++--- src/modlistviewactions.h | 12 ++-- src/organizercore.cpp | 8 --- src/organizercore.h | 2 - src/pluginlistview.cpp | 150 ++++++++++++++++++++++++++++++++++----------- src/pluginlistview.h | 55 ++++++++++++++--- 12 files changed, 270 insertions(+), 197 deletions(-) create mode 100644 src/modelutils.cpp create mode 100644 src/modelutils.h (limited to 'src/mainwindow.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 4c7bcd46..7773e845 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -227,6 +227,7 @@ add_filter(NAME src/widgets GROUPS qtgroupingproxy texteditor viewmarkingscrollbar + modelutils ) diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index b000ba57..60e2a1e0 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -320,14 +320,7 @@ MainWindow::MainWindow(Settings &settings TaskProgressManager::instance().tryCreateTaskbar(); setupModList(); - - // set up plugin list - m_PluginListSortProxy = m_OrganizerCore.createPluginListProxyModel(); - - ui->espList->setModel(m_PluginListSortProxy); - ui->espList->sortByColumn(PluginList::COL_PRIORITY, Qt::AscendingOrder); - ui->espList->setItemDelegateForColumn(PluginList::COL_FLAGS, new GenericIconDelegate(ui->espList)); - ui->espList->installEventFilter(m_OrganizerCore.pluginList()); + ui->espList->setup(m_OrganizerCore, this, ui); ui->bsaList->setLocalMoveOnly(true); ui->bsaList->setHeaderHidden(true); @@ -400,9 +393,6 @@ MainWindow::MainWindow(Settings &settings connect(&m_PluginContainer, SIGNAL(diagnosisUpdate()), this, SLOT(scheduleCheckForProblems())); - connect(ui->espFilterEdit, SIGNAL(textChanged(QString)), m_PluginListSortProxy, SLOT(updateFilter(QString))); - connect(ui->espFilterEdit, SIGNAL(textChanged(QString)), this, SLOT(espFilterChanged(QString))); - connect(m_OrganizerCore.directoryRefresher(), SIGNAL(refreshed()), this, SLOT(directory_refreshed())); connect( m_OrganizerCore.directoryRefresher(), @@ -513,10 +503,10 @@ MainWindow::MainWindow(Settings &settings refreshExecutablesList(); updatePinnedExecutables(); resetActionIcons(); - updatePluginCount(); processUpdates(); ui->modList->updateModCount(); + ui->espList->updatePluginCount(); ui->statusBar->updateNormalMessage(m_OrganizerCore); } @@ -1129,18 +1119,6 @@ void MainWindow::createHelpMenu() menu->addAction(tr("About Qt"), qApp, SLOT(aboutQt())); } -void MainWindow::espFilterChanged(const QString &filter) -{ - if (!filter.isEmpty()) { - ui->espList->setStyleSheet("QTreeView { border: 2px ridge #f00; }"); - ui->activePluginsCounter->setStyleSheet("QLCDNumber { border: 2px ridge #f00; }"); - } else { - ui->espList->setStyleSheet(""); - ui->activePluginsCounter->setStyleSheet(""); - } - updatePluginCount(); -} - bool MainWindow::addProfile() { QComboBox *profileBox = findChild("profileBox"); @@ -1544,7 +1522,7 @@ void MainWindow::activateSelectedProfile() m_SavesTab->refreshSaveList(); m_OrganizerCore.refresh(); ui->modList->updateModCount(); - updatePluginCount(); + ui->espList->updatePluginCount(); ui->statusBar->updateNormalMessage(m_OrganizerCore); } @@ -2238,7 +2216,7 @@ void MainWindow::directory_refreshed() void MainWindow::esplist_changed() { - updatePluginCount(); + ui->espList->updatePluginCount(); } void MainWindow::modInstalled(const QString &modName) @@ -2332,6 +2310,7 @@ void MainWindow::esplistSelectionsChanged(const QItemSelection &selected) { m_OrganizerCore.modList()->highlightMods(ui->espList->selectionModel(), *m_OrganizerCore.directoryStructure()); ui->modList->verticalScrollBar()->repaint(); + ui->modList->repaint(); } void MainWindow::modRemoved(const QString &fileName) @@ -2427,57 +2406,6 @@ void MainWindow::refreshProfile_activated() m_OrganizerCore.profileRefresh(); } -void MainWindow::updatePluginCount() -{ - int activeMasterCount = 0; - int activeLightMasterCount = 0; - int activeRegularCount = 0; - int masterCount = 0; - int lightMasterCount = 0; - int regularCount = 0; - int activeVisibleCount = 0; - - PluginList *list = m_OrganizerCore.pluginList(); - QString filter = ui->espFilterEdit->text(); - - for (QString plugin : list->pluginNames()) { - bool active = list->isEnabled(plugin); - bool visible = m_PluginListSortProxy->filterMatchesPlugin(plugin); - if (list->isLight(plugin) || list->isLightFlagged(plugin)) { - lightMasterCount++; - activeLightMasterCount += active; - activeVisibleCount += visible && active; - } else if (list->isMaster(plugin)) { - masterCount++; - activeMasterCount += active; - activeVisibleCount += visible && active; - } else { - regularCount++; - activeRegularCount += active; - activeVisibleCount += visible && active; - } - } - - int activeCount = activeMasterCount + activeLightMasterCount + activeRegularCount; - int totalCount = masterCount + lightMasterCount + regularCount; - - ui->activePluginsCounter->display(activeVisibleCount); - ui->activePluginsCounter->setToolTip(tr("" - "" - "" - "" - "" - "" - "" - "
    TypeActive Total
    All plugins:%1 %2
    ESMs:%3 %4
    ESPs:%7 %8
    ESMs+ESPs:%9 %10
    ESLs:%5 %6
    ") - .arg(activeCount).arg(totalCount) - .arg(activeMasterCount).arg(masterCount) - .arg(activeLightMasterCount).arg(lightMasterCount) - .arg(activeRegularCount).arg(regularCount) - .arg(activeMasterCount+activeRegularCount).arg(masterCount+regularCount) - ); -} - void MainWindow::openOriginInformation_clicked() { try { @@ -2680,7 +2608,7 @@ QMenu *MainWindow::openFolderMenu() void MainWindow::addPluginSendToContextMenu(QMenu *menu) { - if (m_PluginListSortProxy->sortColumn() != PluginList::COL_PRIORITY) + if (ui->espList->sortColumn() != PluginList::COL_PRIORITY) return; QMenu *sub_menu = new QMenu(this); @@ -3623,7 +3551,7 @@ void MainWindow::toolBar_customContextMenuRequested(const QPoint &point) void MainWindow::on_espList_customContextMenuRequested(const QPoint &pos) { - int espIndex = m_PluginListSortProxy->mapToSource(ui->espList->indexAt(pos)).row(); + int espIndex = ui->espList->indexViewToModel(ui->espList->indexAt(pos)).row(); QMenu menu; menu.addAction(tr("Enable selected"), [=]() { enableSelectedPlugins_clicked(); }); @@ -3642,7 +3570,7 @@ void MainWindow::on_espList_customContextMenuRequested(const QPoint &pos) bool hasLocked = false; bool hasUnlocked = false; for (const QModelIndex &idx : currentSelection.indexes()) { - int row = m_PluginListSortProxy->mapToSource(idx).row(); + int row = ui->espList->indexViewToModel(idx).row(); if (m_OrganizerCore.pluginList()->isEnabled(row)) { if (m_OrganizerCore.pluginList()->isESPLocked(row)) { hasLocked = true; diff --git a/src/mainwindow.h b/src/mainwindow.h index 75e7124c..71845874 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -148,8 +148,6 @@ public slots: void directory_refreshed(); - void updatePluginCount(); - signals: /** @@ -262,8 +260,6 @@ private: QStringList m_DefaultArchives; - PluginListSortProxy *m_PluginListSortProxy; - int m_OldExecutableIndex; QAction *m_ContextAction; @@ -406,7 +402,6 @@ private slots: void modlistChanged(const QModelIndexList &indicies, int role); void fileMoved(const QString &filePath, const QString &oldOriginName, const QString &newOriginName); - void espFilterChanged(const QString &filter); void resizeLists(bool pluginListCustom); /** diff --git a/src/modelutils.cpp b/src/modelutils.cpp new file mode 100644 index 00000000..43aa6b99 --- /dev/null +++ b/src/modelutils.cpp @@ -0,0 +1,58 @@ +#include "modelutils.h" + +#include + +QModelIndex indexModelToView(const QModelIndex& index, const QAbstractItemView* view) +{ + // we need to stack the proxy + std::vector proxies; + { + auto* currentModel = view->model(); + while (auto* proxy = qobject_cast(currentModel)) { + proxies.push_back(proxy); + currentModel = proxy->sourceModel(); + } + } + + if (proxies.empty() || proxies.back()->sourceModel() != index.model()) { + return QModelIndex(); + } + + auto qindex = index; + for (auto rit = proxies.rbegin(); rit != proxies.rend(); ++rit) { + qindex = (*rit)->mapFromSource(qindex); + } + + return qindex; +} + +QModelIndexList indexModelToView(const QModelIndexList& index, const QAbstractItemView* view) +{ + QModelIndexList result; + for (auto& idx : index) { + result.append(indexModelToView(idx, view)); + } + return result; +} + +QModelIndex indexViewToModel(const QModelIndex& index, const QAbstractItemModel* model) +{ + if (index.model() == model) { + return index; + } + else if (auto* proxy = qobject_cast(index.model())) { + return indexViewToModel(proxy->mapToSource(index), model); + } + else { + return QModelIndex(); + } +} + +QModelIndexList indexViewToModel(const QModelIndexList& index, const QAbstractItemModel* model) +{ + QModelIndexList result; + for (auto& idx : index) { + result.append(indexViewToModel(idx, model)); + } + return result; +} diff --git a/src/modelutils.h b/src/modelutils.h new file mode 100644 index 00000000..f355c0d6 --- /dev/null +++ b/src/modelutils.h @@ -0,0 +1,14 @@ +#ifndef MODELUTILS_H +#define MODELUTILS_H + +#include +#include + +// convert back-and-forth through model proxies +QModelIndex indexModelToView(const QModelIndex& index, const QAbstractItemView* view); +QModelIndexList indexModelToView(const QModelIndexList& index, const QAbstractItemView* view); +QModelIndex indexViewToModel(const QModelIndex& index, const QAbstractItemModel* model); +QModelIndexList indexViewToModel(const QModelIndexList& index, const QAbstractItemModel* model); + + +#endif diff --git a/src/modlistview.cpp b/src/modlistview.cpp index 99cc4c4c..082d947e 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -24,6 +24,8 @@ #include "genericicondelegate.h" #include "shared/directoryentry.h" #include "shared/filesorigin.h" +#include "mainwindow.h" +#include "modelutils.h" using namespace MOBase; @@ -197,61 +199,22 @@ bool ModListView::isModVisible(ModInfo::Ptr mod) const QModelIndex ModListView::indexModelToView(const QModelIndex& index) const { - if (index.model() != m_core->modList()) { - return QModelIndex(); - } - - // we need to stack the proxy - std::vector proxies; - { - auto* currentModel = model(); - while (auto* proxy = qobject_cast(currentModel)) { - proxies.push_back(proxy); - currentModel = proxy->sourceModel(); - } - } - - if (proxies.empty() || proxies.back()->sourceModel() != m_core->modList()) { - return QModelIndex(); - } - - auto qindex = index; - for (auto rit = proxies.rbegin(); rit != proxies.rend(); ++rit) { - qindex = (*rit)->mapFromSource(qindex); - } - - return qindex; + return ::indexModelToView(index, this); } QModelIndexList ModListView::indexModelToView(const QModelIndexList& index) const { - QModelIndexList result; - for (auto& idx : index) { - result.append(indexModelToView(idx)); - } - return result; + return ::indexModelToView(index, this); } QModelIndex ModListView::indexViewToModel(const QModelIndex& index) const { - if (index.model() == m_core->modList()) { - return index; - } - else if (auto* proxy = qobject_cast(index.model())) { - return indexViewToModel(proxy->mapToSource(index)); - } - else { - return QModelIndex(); - } + return ::indexViewToModel(index, m_core->modList()); } QModelIndexList ModListView::indexViewToModel(const QModelIndexList& index) const { - QModelIndexList result; - for (auto& idx : index) { - result.append(indexViewToModel(idx)); - } - return result; + return ::indexViewToModel(index, m_core->modList()); } QModelIndex ModListView::nextIndex(const QModelIndex& index) const @@ -625,7 +588,7 @@ void ModListView::setup(OrganizerCore& core, CategoryFactory& factory, MainWindo m_core = &core; m_filters.reset(new FilterList(mwui, core, factory)); m_categories = &factory; - m_actions = new ModListViewActions(core, *m_filters, factory, mw, this); + m_actions = new ModListViewActions(core, *m_filters, factory, this, mwui->espList, mw, mw); ui = { mwui->groupCombo, mwui->activeModsCounter, mwui->modFilterEdit, mwui->currentCategoryLabel, mwui->clearFiltersButton }; connect(m_core, &OrganizerCore::modInstalled, this, &ModListView::onModInstalled); diff --git a/src/modlistviewactions.cpp b/src/modlistviewactions.cpp index d9841517..f0d4c4c7 100644 --- a/src/modlistviewactions.cpp +++ b/src/modlistviewactions.cpp @@ -17,7 +17,6 @@ #include "modinfodialog.h" #include "modlist.h" #include "modlistview.h" -#include "mainwindow.h" #include "messagedialog.h" #include "nexusinterface.h" #include "nxmaccessmanager.h" @@ -25,6 +24,7 @@ #include "organizercore.h" #include "overwriteinfodialog.h" #include "csvbuilder.h" +#include "pluginlistview.h" #include "shared/filesorigin.h" #include "shared/directoryentry.h" #include "shared/fileregister.h" @@ -33,15 +33,18 @@ using namespace MOBase; using namespace MOShared; + ModListViewActions::ModListViewActions( - OrganizerCore& core, FilterList& filters, CategoryFactory& categoryFactory, MainWindow* mainWindow, ModListView* view) : - QObject(view) + OrganizerCore& core, FilterList& filters, CategoryFactory& categoryFactory, + ModListView* view, PluginListView* pluginView, QObject* nxmReceiver, QWidget* parent) : + QObject(parent) , m_core(core) , m_filters(filters) , m_categories(categoryFactory) , m_view(view) - , m_parent(mainWindow) - , m_main(mainWindow) + , m_pluginView(pluginView) + , m_parent(parent) + , m_receiver(nxmReceiver) { } @@ -157,9 +160,9 @@ void ModListViewActions::checkModsForUpdates() const { bool checkingModsForUpdate = false; if (NexusInterface::instance().getAccessManager()->validated()) { - checkingModsForUpdate = ModInfo::checkAllForUpdate(&m_core.pluginContainer(), m_main); - NexusInterface::instance().requestEndorsementInfo(m_main, QVariant(), QString()); - NexusInterface::instance().requestTrackingInfo(m_main, QVariant(), QString()); + 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)) { @@ -201,7 +204,7 @@ void ModListViewActions::checkModsForUpdates(std::multimap const& } if (NexusInterface::instance().getAccessManager()->validated()) { - ModInfo::manualUpdateCheck(m_main, IDs); + ModInfo::manualUpdateCheck(m_receiver, IDs); } else { QString apiKey; @@ -596,7 +599,7 @@ void ModListViewActions::removeMods(const QModelIndexList& indices) const m_core.modList()->removeRow(indices[0].data(ModList::IndexRole).toInt(), QModelIndex()); } m_view->updateModCount(); - m_main->updatePluginCount(); + m_pluginView->updatePluginCount(); } catch (const std::exception& e) { reportError(tr("failed to remove mod: %1").arg(e.what())); diff --git a/src/modlistviewactions.h b/src/modlistviewactions.h index 135b3035..cb7cdbda 100644 --- a/src/modlistviewactions.h +++ b/src/modlistviewactions.h @@ -11,6 +11,7 @@ class CategoryFactory; class FilterList; class MainWindow; class ModListView; +class PluginListView; class OrganizerCore; class ModListViewActions : public QObject @@ -26,8 +27,10 @@ public: OrganizerCore& core, FilterList& filters, CategoryFactory& categoryFactory, - MainWindow* mainWindow, - ModListView* view); + ModListView* view, + PluginListView* pluginView, + QObject* nxmReceiver, + QWidget* parent); // install the mod from the given archive // @@ -142,10 +145,9 @@ private: FilterList& m_filters; CategoryFactory& m_categories; ModListView* m_view; + PluginListView* m_pluginView; + QObject* m_receiver; QWidget* m_parent; - - // hope to get rid of this some day - MainWindow* m_main; }; #endif diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 17cd80c2..a8911d4f 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -11,7 +11,6 @@ #include "modrepositoryfileinfo.h" #include "nexusinterface.h" #include "plugincontainer.h" -#include "pluginlistsortproxy.h" #include "profile.h" #include "credentialsdialog.h" #include "filedialogmemory.h" @@ -1507,13 +1506,6 @@ void OrganizerCore::requestDownload(const QUrl &url, QNetworkReply *reply) } } -PluginListSortProxy *OrganizerCore::createPluginListProxyModel() -{ - PluginListSortProxy *result = new PluginListSortProxy(this); - result->setSourceModel(&m_PluginList); - return result; -} - PluginContainer& OrganizerCore::pluginContainer() const { return *m_PluginContainer; diff --git a/src/organizercore.h b/src/organizercore.h index e060fbcb..24de26ee 100644 --- a/src/organizercore.h +++ b/src/organizercore.h @@ -227,8 +227,6 @@ public: MOBase::VersionInfo getVersion() const { return m_Updater.getVersion(); } - PluginListSortProxy *createPluginListProxyModel(); - // return the plugin container // PluginContainer& pluginContainer() const; diff --git a/src/pluginlistview.cpp b/src/pluginlistview.cpp index a265d5d4..a401ab06 100644 --- a/src/pluginlistview.cpp +++ b/src/pluginlistview.cpp @@ -1,58 +1,136 @@ #include "pluginlistview.h" -#include + #include #include -#include +#include -class PluginListViewStyle : public QProxyStyle { -public: - PluginListViewStyle(QStyle *style, int indentation); +#include "mainwindow.h" +#include "ui_mainwindow.h" +#include "organizercore.h" +#include "pluginlistsortproxy.h" +#include "genericicondelegate.h" +#include "modelutils.h" - void drawPrimitive(PrimitiveElement element, const QStyleOption *option, - QPainter *painter, const QWidget *widget = 0) const; -private: - int m_Indentation; -}; +PluginListView::PluginListView(QWidget *parent) + : QTreeView(parent) + , m_Scrollbar(new ViewMarkingScrollBar(this->model(), this)) +{ + setVerticalScrollBar(m_Scrollbar); + MOBase::setCustomizableColumns(this); +} -PluginListViewStyle::PluginListViewStyle(QStyle *style, int indentation) - : QProxyStyle(style), m_Indentation(indentation) +void PluginListView::setModel(QAbstractItemModel *model) { + QTreeView::setModel(model); + setVerticalScrollBar(new ViewMarkingScrollBar(model, this)); } -void PluginListViewStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, - QPainter *painter, const QWidget *widget) const +int PluginListView::sortColumn() const { - if (element == QStyle::PE_IndicatorItemViewItemDrop && !option->rect.isNull()) { - QStyleOption opt(*option); - opt.rect.setLeft(m_Indentation); - if (widget) { - opt.rect.setRight(widget->width() - 5); // 5 is an arbitrary value that seems to work ok - } - QProxyStyle::drawPrimitive(element, &opt, painter, widget); - } - else { - QProxyStyle::drawPrimitive(element, option, painter, widget); - } + return m_sortProxy ? m_sortProxy->sortColumn() : -1; } -PluginListView::PluginListView(QWidget *parent) - : QTreeView(parent) - , m_Scrollbar(new ViewMarkingScrollBar(this->model(), this)) +QModelIndex PluginListView::indexModelToView(const QModelIndex& index) const { - setVerticalScrollBar(m_Scrollbar); - MOBase::setCustomizableColumns(this); + return ::indexModelToView(index, this); } -void PluginListView::dragEnterEvent(QDragEnterEvent *event) +QModelIndexList PluginListView::indexModelToView(const QModelIndexList& index) const { - emit dropModeUpdate(event->mimeData()->hasUrls()); + return ::indexModelToView(index, this); +} - QTreeView::dragEnterEvent(event); +QModelIndex PluginListView::indexViewToModel(const QModelIndex& index) const +{ + return ::indexViewToModel(index, m_core->pluginList()); } -void PluginListView::setModel(QAbstractItemModel *model) +QModelIndexList PluginListView::indexViewToModel(const QModelIndexList& index) const { - QTreeView::setModel(model); - setVerticalScrollBar(new ViewMarkingScrollBar(model, this)); + return ::indexViewToModel(index, m_core->pluginList()); +} + +void PluginListView::updatePluginCount() +{ + int activeMasterCount = 0; + int activeLightMasterCount = 0; + int activeRegularCount = 0; + int masterCount = 0; + int lightMasterCount = 0; + int regularCount = 0; + int activeVisibleCount = 0; + + PluginList* list = m_core->pluginList(); + QString filter = ui.filter->text(); + + for (QString plugin : list->pluginNames()) { + bool active = list->isEnabled(plugin); + bool visible = m_sortProxy->filterMatchesPlugin(plugin); + if (list->isLight(plugin) || list->isLightFlagged(plugin)) { + lightMasterCount++; + activeLightMasterCount += active; + activeVisibleCount += visible && active; + } + else if (list->isMaster(plugin)) { + masterCount++; + activeMasterCount += active; + activeVisibleCount += visible && active; + } + else { + regularCount++; + activeRegularCount += active; + activeVisibleCount += visible && active; + } + } + + int activeCount = activeMasterCount + activeLightMasterCount + activeRegularCount; + int totalCount = masterCount + lightMasterCount + regularCount; + + ui.counter->display(activeVisibleCount); + ui.counter->setToolTip(tr("" + "" + "" + "" + "" + "" + "" + "
    TypeActive Total
    All plugins:%1 %2
    ESMs:%3 %4
    ESPs:%7 %8
    ESMs+ESPs:%9 %10
    ESLs:%5 %6
    ") + .arg(activeCount).arg(totalCount) + .arg(activeMasterCount).arg(masterCount) + .arg(activeLightMasterCount).arg(lightMasterCount) + .arg(activeRegularCount).arg(regularCount) + .arg(activeMasterCount + activeRegularCount).arg(masterCount + regularCount) + ); +} + +void PluginListView::onFilterChanged(const QString& filter) +{ + if (!filter.isEmpty()) { + setStyleSheet("QTreeView { border: 2px ridge #f00; }"); + ui.counter->setStyleSheet("QLCDNumber { border: 2px ridge #f00; }"); + } + else { + setStyleSheet(""); + ui.counter->setStyleSheet(""); + } + updatePluginCount(); +} + +void PluginListView::setup(OrganizerCore& core, MainWindow* mw, Ui::MainWindow* mwui) +{ + m_core = &core; + ui = { mwui->activePluginsCounter, mwui->espFilterEdit }; + + m_sortProxy = new PluginListSortProxy(&core); + m_sortProxy->setSourceModel(core.pluginList()); + setModel(m_sortProxy); + + sortByColumn(PluginList::COL_PRIORITY, Qt::AscendingOrder); + setItemDelegateForColumn(PluginList::COL_FLAGS, new GenericIconDelegate(this)); + installEventFilter(core.pluginList()); + + connect(ui.filter, &QLineEdit::textChanged, m_sortProxy, &PluginListSortProxy::updateFilter); + connect(ui.filter, &QLineEdit::textChanged, this, &PluginListView::onFilterChanged); + } diff --git a/src/pluginlistview.h b/src/pluginlistview.h index bdd4ee61..95450ffd 100644 --- a/src/pluginlistview.h +++ b/src/pluginlistview.h @@ -5,20 +5,61 @@ #include #include "viewmarkingscrollbar.h" +namespace Ui { + class MainWindow; +} + +class OrganizerCore; +class MainWindow; +class PluginListSortProxy; + class PluginListView : public QTreeView { Q_OBJECT public: - explicit PluginListView(QWidget *parent = 0); - virtual void dragEnterEvent(QDragEnterEvent *event); - virtual void setModel(QAbstractItemModel *model); -signals: - void dropModeUpdate(bool dropOnRows); + explicit PluginListView(QWidget* parent = nullptr); + void setModel(QAbstractItemModel* model) override; + + void setup(OrganizerCore& core, MainWindow* mw, Ui::MainWindow* mwui); + + // the column by which the plugin list is currently sorted + // + int sortColumn() const; + + // update the plugin counter + // + void updatePluginCount(); + + // TODO: Move these to private when possible. + // map from/to the view indexes to the model + // + QModelIndex indexModelToView(const QModelIndex& index) const; + QModelIndexList indexModelToView(const QModelIndexList& index) const; + QModelIndex indexViewToModel(const QModelIndex& index) const; + QModelIndexList indexViewToModel(const QModelIndexList& index) const; + + +protected slots: + + void onFilterChanged(const QString& filter); - public slots: private: - ViewMarkingScrollBar *m_Scrollbar; + struct PluginListViewUi + { + // the plguin counter + QLCDNumber* counter; + + // the filter + QLineEdit* filter; + }; + + OrganizerCore* m_core; + PluginListViewUi ui; + + PluginListSortProxy* m_sortProxy; + + ViewMarkingScrollBar* m_Scrollbar; }; #endif // PLUGINLISTVIEW_H -- cgit v1.3.1 From 25a2123e5ffe66715d0a1ec09297ee91a9fcbe1c Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 21:24:29 +0100 Subject: Move keyboard event to PluginListView. --- src/mainwindow.cpp | 9 ++- src/pluginlist.cpp | 145 +++++++++++++++++-------------------------------- src/pluginlist.h | 17 ++++-- src/pluginlistview.cpp | 60 +++++++++++++++++++- src/pluginlistview.h | 15 +++++ 5 files changed, 141 insertions(+), 105 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 60e2a1e0..38417df5 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2868,12 +2868,14 @@ void MainWindow::disableSelectedPlugins_clicked() void MainWindow::sendSelectedPluginsToTop_clicked() { - m_OrganizerCore.pluginList()->sendToPriority(ui->espList->selectionModel(), 0); + m_OrganizerCore.pluginList()->sendToPriority( + ui->espList->indexViewToModel(ui->espList->selectionModel()->selectedRows()), 0); } void MainWindow::sendSelectedPluginsToBottom_clicked() { - m_OrganizerCore.pluginList()->sendToPriority(ui->espList->selectionModel(), INT_MAX); + m_OrganizerCore.pluginList()->sendToPriority( + ui->espList->indexViewToModel(ui->espList->selectionModel()->selectedRows()), INT_MAX); } void MainWindow::sendSelectedPluginsToPriority_clicked() @@ -2884,7 +2886,8 @@ void MainWindow::sendSelectedPluginsToPriority_clicked() 0, 0, INT_MAX, 1, &ok); if (!ok) return; - m_OrganizerCore.pluginList()->sendToPriority(ui->espList->selectionModel(), newPriority); + m_OrganizerCore.pluginList()->sendToPriority( + ui->espList->indexViewToModel(ui->espList->selectionModel()->selectedRows()), newPriority); } void MainWindow::updateAvailable() diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index 504b17c5..053f91b3 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -412,20 +412,60 @@ void PluginList::disableAll() } } -void PluginList::sendToPriority(const QItemSelectionModel *selectionModel, int newPriority) +void PluginList::sendToPriority(const QModelIndexList& indices, int newPriority) { - if (selectionModel->hasSelection()) { - std::vector pluginsToMove; - for (auto row: selectionModel->selectedRows(COL_PRIORITY)) { - int rowIndex = findPluginByPriority(row.data().toInt()); - if (!m_ESPs[rowIndex].forceEnabled) { - pluginsToMove.push_back(rowIndex); - } + std::vector pluginsToMove; + for (auto& idx : indices) { + int rowIndex = findPluginByPriority(idx.row()); + if (!m_ESPs[rowIndex].forceEnabled) { + pluginsToMove.push_back(rowIndex); + } + } + if (pluginsToMove.size()) { + changePluginPriority(pluginsToMove, newPriority); + } +} + +void PluginList::shiftPluginsPriority(const QModelIndexList& indices, int offset) +{ + // retrieve the mod index and sort them by priority to avoid issue + // when moving them + std::vector allIndex; + for (auto& idx : indices) { + allIndex.push_back(idx.row()); + } + std::sort(allIndex.begin(), allIndex.end(), [=](int lhs, int rhs) { + bool cmp = m_ESPs[lhs].priority < m_ESPs[rhs].priority; + return offset > 0 ? !cmp : cmp; + }); + + emit layoutAboutToBeChanged(); + for (auto index : allIndex) { + int newPriority = m_ESPs[index].priority + offset; + if (newPriority >= 0 && newPriority < rowCount()) { + setPluginPriority(index, newPriority); + } + } + emit layoutChanged(); + + refreshLoadOrder(); +} + +void PluginList::toggleState(const QModelIndexList& indices) +{ + QModelIndex minRow, maxRow; + for (auto& idx : indices) { + if (!minRow.isValid() || (idx.row() < minRow.row())) { + minRow = idx; } - if (pluginsToMove.size()) { - changePluginPriority(pluginsToMove, newPriority); + if (!maxRow.isValid() || (idx.row() > maxRow.row())) { + maxRow = idx; } + int oldState = idx.data(Qt::CheckStateRole).toInt(); + setData(idx, oldState == Qt::Unchecked ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole); } + + emit dataChanged(minRow, maxRow); } bool PluginList::isEnabled(const QString &name) @@ -541,7 +581,6 @@ void PluginList::writeLockedOrder(const QString &fileName) const file.commit(); } - void PluginList::saveTo(const QString &lockedOrderFileName , const QString& deleterFileName , bool hideUnchecked) const @@ -898,13 +937,11 @@ boost::signals2::connection PluginList::onRefreshed(const std::function return m_Refreshed.connect(callback); } - boost::signals2::connection PluginList::onPluginMoved(const std::function &func) { return m_PluginMoved.connect(func); } - void PluginList::updateIndices() { m_ESPsByName.clear(); @@ -951,7 +988,6 @@ void PluginList::generatePluginIndexes() emit esplist_changed(); } - int PluginList::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) { @@ -966,7 +1002,6 @@ int PluginList::columnCount(const QModelIndex &) const return COL_LASTCOLUMN + 1; } - void PluginList::testMasters() { std::set enabledMasters; @@ -1371,7 +1406,6 @@ bool PluginList::setData(const QModelIndex &modIndex, const QVariant &value, int return result; } - QVariant PluginList::headerData(int section, Qt::Orientation orientation, int role) const { @@ -1385,7 +1419,6 @@ QVariant PluginList::headerData(int section, Qt::Orientation orientation, return QAbstractItemModel::headerData(section, orientation, role); } - Qt::ItemFlags PluginList::flags(const QModelIndex &modelIndex) const { int index = modelIndex.row(); @@ -1406,7 +1439,6 @@ Qt::ItemFlags PluginList::flags(const QModelIndex &modelIndex) const return result; } - void PluginList::setPluginPriority(int row, int &newPriority) { int newPriorityTemp = newPriority; @@ -1464,7 +1496,6 @@ void PluginList::setPluginPriority(int row, int &newPriority) updateIndices(); } - void PluginList::changePluginPriority(std::vector rows, int newPriority) { ChangeBracket layoutChange(this); @@ -1562,82 +1593,6 @@ QModelIndex PluginList::parent(const QModelIndex&) const return QModelIndex(); } - -bool PluginList::eventFilter(QObject *obj, QEvent *event) -{ - if (event->type() == QEvent::KeyPress) { - QAbstractItemView *itemView = qobject_cast(obj); - - if (itemView == nullptr) { - return QAbstractItemModel::eventFilter(obj, event); - } - - QKeyEvent *keyEvent = static_cast(event); - // ctrl+up and ctrl+down -> increase or decrease priority of selected plugins - if ((keyEvent->modifiers() == Qt::ControlModifier) && - ((keyEvent->key() == Qt::Key_Up) || (keyEvent->key() == Qt::Key_Down))) { - QItemSelectionModel *selectionModel = itemView->selectionModel(); - const QSortFilterProxyModel *proxyModel = qobject_cast(selectionModel->model()); - if (proxyModel != nullptr) { - int diff = -1; - if (((keyEvent->key() == Qt::Key_Up) && (proxyModel->sortOrder() == Qt::DescendingOrder)) || - ((keyEvent->key() == Qt::Key_Down) && (proxyModel->sortOrder() == Qt::AscendingOrder))) { - diff = 1; - } - QModelIndexList rows = selectionModel->selectedRows(); - // remove elements that aren't supposed to be movable - QMutableListIterator iter(rows); - while (iter.hasNext()) { - if ((iter.next().flags() & Qt::ItemIsDragEnabled) == 0) { - iter.remove(); - } - } - if (keyEvent->key() == Qt::Key_Down) { - for (int i = 0; i < rows.size() / 2; ++i) { - rows.swapItemsAt(i, rows.size() - i - 1); - } - } - for (QModelIndex idx : rows) { - idx = proxyModel->mapToSource(idx); - int newPriority = m_ESPs[idx.row()].priority + diff; - if ((newPriority >= 0) && (newPriority < rowCount())) { - setPluginPriority(idx.row(), newPriority); - } - } - refreshLoadOrder(); - } - return true; - } else if (keyEvent->key() == Qt::Key_Space) { - QItemSelectionModel *selectionModel = itemView->selectionModel(); - const QSortFilterProxyModel *proxyModel = qobject_cast(selectionModel->model()); - QList indices; - for (QModelIndex idx : selectionModel->selectedRows()) { - indices.append(idx); - } - - QModelIndex minRow, maxRow; - for (QModelIndex idx : indices) { - if (proxyModel != nullptr) { - idx = proxyModel->mapToSource(idx); - } - if (!minRow.isValid() || (idx.row() < minRow.row())) { - minRow = idx; - } - if (!maxRow.isValid() || (idx.row() > maxRow.row())) { - maxRow = idx; - } - int oldState = idx.data(Qt::CheckStateRole).toInt(); - setData(idx, oldState == Qt::Unchecked ? Qt::Checked : Qt::Unchecked, Qt::CheckStateRole); - } - emit dataChanged(minRow, maxRow); - - return true; - } - } - return QAbstractItemModel::eventFilter(obj, event); -} - - PluginList::ESPInfo::ESPInfo(const QString &name, bool enabled, const QString &originName, const QString &fullPath, bool hasIni, std::set archives, bool lightPluginsAreSupported) diff --git a/src/pluginlist.h b/src/pluginlist.h index 5f0cef3d..3a5f5412 100644 --- a/src/pluginlist.h +++ b/src/pluginlist.h @@ -214,8 +214,6 @@ public: bool isESPLocked(int index) const; void lockESPIndex(int index, bool lock); - bool eventFilter(QObject *obj, QEvent *event); - static QString getColumnName(int column); static QString getColumnToolTip(int column); @@ -279,10 +277,17 @@ public slots: **/ void disableAll(); - /** - * @brief moves selected plugins to specified priority - **/ - void sendToPriority(const QItemSelectionModel *selectionModel, int priority); + // send plugins to the given priority + // + void sendToPriority(const QModelIndexList& selectionModel, int priority); + + // shift the priority of mods at the given indices by the given offset + // + void shiftPluginsPriority(const QModelIndexList& indices, int offset); + + // toggle the active state of mods at the given indices + // + void toggleState(const QModelIndexList& indices); /** * @brief The currently managed game has changed diff --git a/src/pluginlistview.cpp b/src/pluginlistview.cpp index a401ab06..70b3ebc1 100644 --- a/src/pluginlistview.cpp +++ b/src/pluginlistview.cpp @@ -117,6 +117,20 @@ void PluginListView::onFilterChanged(const QString& filter) updatePluginCount(); } +std::pair PluginListView::selected() const +{ + return { indexViewToModel(currentIndex()), indexViewToModel(selectionModel()->selectedRows()) }; +} + +void PluginListView::setSelected(const QModelIndex& current, const QModelIndexList& selected) +{ + setCurrentIndex(indexModelToView(current)); + for (auto idx : selected) { + selectionModel()->select(indexModelToView(idx), QItemSelectionModel::Select | QItemSelectionModel::Rows); + } +} + + void PluginListView::setup(OrganizerCore& core, MainWindow* mw, Ui::MainWindow* mwui) { m_core = &core; @@ -128,9 +142,53 @@ void PluginListView::setup(OrganizerCore& core, MainWindow* mw, Ui::MainWindow* sortByColumn(PluginList::COL_PRIORITY, Qt::AscendingOrder); setItemDelegateForColumn(PluginList::COL_FLAGS, new GenericIconDelegate(this)); - installEventFilter(core.pluginList()); connect(ui.filter, &QLineEdit::textChanged, m_sortProxy, &PluginListSortProxy::updateFilter); connect(ui.filter, &QLineEdit::textChanged, this, &PluginListView::onFilterChanged); } + +bool PluginListView::moveSelection(int key) +{ + auto [cindex, sourceRows] = selected(); + + int offset = key == Qt::Key_Up ? -1 : 1; + if (m_sortProxy->sortOrder() == Qt::DescendingOrder) { + offset = -offset; + } + + m_core->pluginList()->shiftPluginsPriority(sourceRows, offset); + + // reset the selection and the index + setSelected(cindex, sourceRows); + + return true; +} + +bool PluginListView::toggleSelectionState() +{ + if (!selectionModel()->hasSelection()) { + return true; + } + m_core->pluginList()->toggleState(indexViewToModel(selectionModel()->selectedRows())); + return true; +} + +bool PluginListView::event(QEvent* event) +{ + Profile* profile = m_core->currentProfile(); + if (event->type() == QEvent::KeyPress && profile) { + QKeyEvent* keyEvent = static_cast(event); + + if (keyEvent->modifiers() == Qt::ControlModifier + && (sortColumn() == PluginList::COL_PRIORITY || sortColumn() == PluginList::COL_MODINDEX) + && (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down)) { + return moveSelection(keyEvent->key()); + } + else if (keyEvent->key() == Qt::Key_Space) { + return toggleSelectionState(); + } + return QTreeView::event(event); + } + return QTreeView::event(event); +} diff --git a/src/pluginlistview.h b/src/pluginlistview.h index 95450ffd..92f03588 100644 --- a/src/pluginlistview.h +++ b/src/pluginlistview.h @@ -43,6 +43,21 @@ protected slots: void onFilterChanged(const QString& filter); +protected: + + // method to react to various key events + // + bool moveSelection(int key); + bool toggleSelectionState(); + + // get/set the selected items on the view, this method return/take indices + // from the mod list model, not the view, so it's safe to restore + // + std::pair selected() const; + void setSelected(const QModelIndex& current, const QModelIndexList& selected); + + bool event(QEvent* event) override; + private: struct PluginListViewUi -- cgit v1.3.1 From bd34b532230d92bd6232ceb1ab2b0092cac79d22 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 22:18:11 +0100 Subject: Move plugin list context menu to its own class and to PluginListView. --- src/CMakeLists.txt | 1 + src/mainwindow.cpp | 224 ------------------------------------------ src/mainwindow.h | 11 --- src/modlistcontextmenu.h | 2 +- src/pluginlist.cpp | 46 +++------ src/pluginlist.h | 14 +-- src/pluginlistcontextmenu.cpp | 132 +++++++++++++++++++++++++ src/pluginlistcontextmenu.h | 54 ++++++++++ src/pluginlistview.cpp | 71 +++++++++++++ src/pluginlistview.h | 6 ++ 10 files changed, 280 insertions(+), 281 deletions(-) create mode 100644 src/pluginlistcontextmenu.cpp create mode 100644 src/pluginlistcontextmenu.h (limited to 'src/mainwindow.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 7773e845..ecb95c9e 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -146,6 +146,7 @@ add_filter(NAME src/plugins GROUPS pluginlist pluginlistsortproxy pluginlistview + pluginlistcontextmenu ) add_filter(NAME src/previews GROUPS diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 38417df5..a530fbf4 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2340,28 +2340,6 @@ void MainWindow::setWindowEnabled(bool enabled) setEnabled(enabled); } -void MainWindow::openPluginOriginExplorer_clicked() -{ - QItemSelectionModel *selection = ui->espList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() > 0) { - for (QModelIndex idx : selection->selectedRows()) { - QString fileName = idx.data().toString(); - unsigned int modIndex = ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName)); - if (modIndex == UINT_MAX) { - continue; - } - ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); - shell::Explore(modInfo->absolutePath()); - } - } - else { - QModelIndex idx = selection->currentIndex(); - QString fileName = idx.data().toString(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - shell::Explore(modInfo->absolutePath()); - } -} - void MainWindow::openExplorer_activated() { if (ui->modList->hasFocus()) { @@ -2406,93 +2384,6 @@ void MainWindow::refreshProfile_activated() m_OrganizerCore.profileRefresh(); } -void MainWindow::openOriginInformation_clicked() -{ - try { - QItemSelectionModel *selection = ui->espList->selectionModel(); - //we don't want to open multiple modinfodialogs. - /*if (selection->hasSelection() && selection->selectedRows().count() > 0) { - - for (QModelIndex idx : selection->selectedRows()) { - QString fileName = idx.data().toString(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - std::vector flags = modInfo->getFlags(); - - if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { - displayModInformation(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - } - } - } - else {}*/ - QModelIndex idx = selection->currentIndex(); - QString fileName = idx.data().toString(); - - ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - std::vector flags = modInfo->getFlags(); - - if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { - ui->modList->actions().displayModInformation(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - } - } - catch (const std::exception &e) { - reportError(e.what()); - } -} - -void MainWindow::on_espList_doubleClicked(const QModelIndex &index) -{ - if (!index.isValid()) { - return; - } - - if (m_OrganizerCore.pluginList()->timeElapsedSinceLastChecked() <= QApplication::doubleClickInterval()) { - // don't interpret double click if we only just checked a plugin - return; - } - - QModelIndex sourceIdx = mapToModel(m_OrganizerCore.pluginList(), index); - if (!sourceIdx.isValid()) { - return; - } - try { - - QItemSelectionModel *selection = ui->espList->selectionModel(); - - if (selection->hasSelection() && selection->selectedRows().count() == 1) { - - QModelIndex idx = selection->currentIndex(); - QString fileName = idx.data().toString(); - - if (ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName)) == UINT_MAX) - return; - - ModInfo::Ptr modInfo = ModInfo::getByIndex(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - std::vector flags = modInfo->getFlags(); - - if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { - - Qt::KeyboardModifiers modifiers = QApplication::queryKeyboardModifiers(); - if (modifiers.testFlag(Qt::ControlModifier)) { - openExplorer_activated(); - // workaround to cancel the editor that might have opened because of - // selection-click - ui->espList->closePersistentEditor(index); - } - else { - - ui->modList->actions().displayModInformation(ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName))); - // workaround to cancel the editor that might have opened because of - // selection-click - ui->espList->closePersistentEditor(index); - } - } - } - } - catch (const std::exception &e) { - reportError(e.what()); - } -} - void MainWindow::saveArchiveList() { if (m_OrganizerCore.isArchivesInit()) { @@ -2606,21 +2497,6 @@ QMenu *MainWindow::openFolderMenu() return FolderMenu; } -void MainWindow::addPluginSendToContextMenu(QMenu *menu) -{ - if (ui->espList->sortColumn() != PluginList::COL_PRIORITY) - return; - - QMenu *sub_menu = new QMenu(this); - sub_menu->setTitle(tr("Send to")); - sub_menu->addAction(tr("Top"), [&]() { sendSelectedPluginsToTop_clicked(); }); - sub_menu->addAction(tr("Bottom"), [&]() { sendSelectedPluginsToBottom_clicked(); }); - sub_menu->addAction(tr("Priority..."), [&]() { sendSelectedPluginsToPriority_clicked(); }); - - menu->addMenu(sub_menu); - menu->addSeparator(); -} - void MainWindow::linkToolbar() { Executable* exe = getSelectedExecutable(); @@ -2855,41 +2731,6 @@ void MainWindow::originModified(int originID) DirectoryRefresher::cleanStructure(m_OrganizerCore.directoryStructure()); } -void MainWindow::enableSelectedPlugins_clicked() -{ - m_OrganizerCore.pluginList()->enableSelected(ui->espList->selectionModel()); -} - - -void MainWindow::disableSelectedPlugins_clicked() -{ - m_OrganizerCore.pluginList()->disableSelected(ui->espList->selectionModel()); -} - -void MainWindow::sendSelectedPluginsToTop_clicked() -{ - m_OrganizerCore.pluginList()->sendToPriority( - ui->espList->indexViewToModel(ui->espList->selectionModel()->selectedRows()), 0); -} - -void MainWindow::sendSelectedPluginsToBottom_clicked() -{ - m_OrganizerCore.pluginList()->sendToPriority( - ui->espList->indexViewToModel(ui->espList->selectionModel()->selectedRows()), INT_MAX); -} - -void MainWindow::sendSelectedPluginsToPriority_clicked() -{ - bool ok; - int newPriority = QInputDialog::getInt(this, - tr("Set Priority"), tr("Set the priority of the selected plugins"), - 0, 0, INT_MAX, 1, &ok); - if (!ok) return; - - m_OrganizerCore.pluginList()->sendToPriority( - ui->espList->indexViewToModel(ui->espList->selectionModel()->selectedRows()), newPriority); -} - void MainWindow::updateAvailable() { ui->actionUpdate->setEnabled(true); @@ -3551,71 +3392,6 @@ void MainWindow::toolBar_customContextMenuRequested(const QPoint &point) m->exec(ui->toolBar->mapToGlobal(point)); } -void MainWindow::on_espList_customContextMenuRequested(const QPoint &pos) -{ - - int espIndex = ui->espList->indexViewToModel(ui->espList->indexAt(pos)).row(); - - QMenu menu; - menu.addAction(tr("Enable selected"), [=]() { enableSelectedPlugins_clicked(); }); - menu.addAction(tr("Disable selected"), [=]() { disableSelectedPlugins_clicked(); }); - - menu.addSeparator(); - - menu.addAction(tr("Enable all"), m_OrganizerCore.pluginList(), &PluginList::enableAll); - menu.addAction(tr("Disable all"), m_OrganizerCore.pluginList(), &PluginList::disableAll); - - menu.addSeparator(); - - addPluginSendToContextMenu(&menu); - - QItemSelection currentSelection = ui->espList->selectionModel()->selection(); - bool hasLocked = false; - bool hasUnlocked = false; - for (const QModelIndex &idx : currentSelection.indexes()) { - int row = ui->espList->indexViewToModel(idx).row(); - if (m_OrganizerCore.pluginList()->isEnabled(row)) { - if (m_OrganizerCore.pluginList()->isESPLocked(row)) { - hasLocked = true; - } else { - hasUnlocked = true; - } - } - } - - if (hasLocked) { - menu.addAction(tr("Unlock load order"), [&, espIndex]() { updateESPLock(espIndex, false); }); - } - if (hasUnlocked) { - menu.addAction(tr("Lock load order"), [&, espIndex]() { updateESPLock(espIndex, true); }); - } - - menu.addSeparator(); - - - QModelIndex idx = ui->espList->selectionModel()->currentIndex(); - unsigned int modInfoIndex = ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(idx.data().toString())); - //this is to avoid showing the option on game files like skyrim.esm - if (modInfoIndex != UINT_MAX) { - menu.addAction(tr("Open Origin in Explorer"), [=]() { openPluginOriginExplorer_clicked(); }); - ModInfo::Ptr modInfo = ModInfo::getByIndex(modInfoIndex); - std::vector flags = modInfo->getFlags(); - - if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_FOREIGN) == flags.end()) { - QAction* infoAction = menu.addAction(tr("Open Origin Info..."), [=]() { openOriginInformation_clicked(); }); - menu.setDefaultAction(infoAction); - } - } - - try { - menu.exec(ui->espList->viewport()->mapToGlobal(pos)); - } catch (const std::exception &e) { - reportError(tr("Exception: ").arg(e.what())); - } catch (...) { - reportError(tr("Unknown exception")); - } -} - Executable* MainWindow::getSelectedExecutable() { const QString name = ui->executablesListBox->itemText( diff --git a/src/mainwindow.h b/src/mainwindow.h index 71845874..5e3cc798 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -320,15 +320,6 @@ private slots: void openExplorer_activated(); void refreshProfile_activated(); - // pluginlist context menu - void enableSelectedPlugins_clicked(); - void disableSelectedPlugins_clicked(); - void sendSelectedPluginsToTop_clicked(); - void sendSelectedPluginsToBottom_clicked(); - void sendSelectedPluginsToPriority_clicked(); - void openOriginInformation_clicked(); - void openPluginOriginExplorer_clicked(); - void linkToolbar(); void linkDesktop(); void linkMenu(); @@ -444,12 +435,10 @@ private slots: // ui slots void on_centralWidget_customContextMenuRequested(const QPoint &pos); void on_bsaList_customContextMenuRequested(const QPoint &pos); void on_executablesListBox_currentIndexChanged(int index); - void on_espList_doubleClicked(const QModelIndex &index); void on_profileBox_currentIndexChanged(int index); void on_startButton_clicked(); void on_tabWidget_currentChanged(int index); - void on_espList_customContextMenuRequested(const QPoint &pos); void on_displayCategoriesBtn_toggled(bool checked); void on_linkButton_pressed(); void on_showHiddenBox_toggled(bool checked); diff --git a/src/modlistcontextmenu.h b/src/modlistcontextmenu.h index 8452bc65..d009c9d8 100644 --- a/src/modlistcontextmenu.h +++ b/src/modlistcontextmenu.h @@ -74,7 +74,7 @@ public: ModListContextMenu( const QModelIndex& index, OrganizerCore& core, CategoryFactory& categories, ModListView* modListView); -public: // TODO: Move this to private when all is done +private: // create the "Send to... " context menu // diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index 053f91b3..f6a52a80 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -338,43 +338,21 @@ int PluginList::findPluginByPriority(int priority) return -1; } -void PluginList::enableSelected(const QItemSelectionModel *selectionModel) +void PluginList::setEnabled(const QModelIndexList& indices, bool enabled) { - if (selectionModel->hasSelection()) { - QStringList dirty; - for (auto row : selectionModel->selectedRows(COL_PRIORITY)) { - int rowIndex = findPluginByPriority(row.data().toInt()); - if (!m_ESPs[rowIndex].enabled) { - m_ESPs[rowIndex].enabled = true; - dirty.append(m_ESPs[rowIndex].name); - } - } - if (!dirty.isEmpty()) { - emit writePluginsList(); - pluginStatesChanged(dirty, IPluginList::PluginState::STATE_ACTIVE); + QStringList dirty; + for (auto& idx : indices) { + if (m_ESPs[idx.row()].enabled != enabled) { + m_ESPs[idx.row()].enabled = enabled; + dirty.append(m_ESPs[idx.row()].name); } } -} - -void PluginList::disableSelected(const QItemSelectionModel *selectionModel) -{ - if (selectionModel->hasSelection()) { - QStringList dirty; - for (auto row : selectionModel->selectedRows(COL_PRIORITY)) { - int rowIndex = findPluginByPriority(row.data().toInt()); - if (!m_ESPs[rowIndex].forceEnabled && m_ESPs[rowIndex].enabled) { - m_ESPs[rowIndex].enabled = false; - dirty.append(m_ESPs[rowIndex].name); - } - } - if (!dirty.isEmpty()) { - emit writePluginsList(); - pluginStatesChanged(dirty, IPluginList::PluginState::STATE_INACTIVE); - } + if (!dirty.isEmpty()) { + emit writePluginsList(); + pluginStatesChanged(dirty, IPluginList::PluginState::STATE_ACTIVE); } } - void PluginList::enableAll() { if (QMessageBox::question(nullptr, tr("Confirm"), tr("Really enable all plugins?"), @@ -393,7 +371,6 @@ void PluginList::enableAll() } } - void PluginList::disableAll() { if (QMessageBox::question(nullptr, tr("Confirm"), tr("Really disable all plugins?"), @@ -416,9 +393,8 @@ void PluginList::sendToPriority(const QModelIndexList& indices, int newPriority) { std::vector pluginsToMove; for (auto& idx : indices) { - int rowIndex = findPluginByPriority(idx.row()); - if (!m_ESPs[rowIndex].forceEnabled) { - pluginsToMove.push_back(rowIndex); + if (!m_ESPs[idx.row()].forceEnabled) { + pluginsToMove.push_back(idx.row()); } } if (pluginsToMove.size()) { diff --git a/src/pluginlist.h b/src/pluginlist.h index 3a5f5412..6b0f584c 100644 --- a/src/pluginlist.h +++ b/src/pluginlist.h @@ -257,16 +257,6 @@ public: // implementation of the QAbstractTableModel interface public slots: - /** - * @brief enables selected plugins - **/ - void enableSelected(const QItemSelectionModel *selectionModel); - - /** - * @brief disables selected plugins - **/ - void disableSelected(const QItemSelectionModel *selectionModel); - /** * @brief enables ALL plugins **/ @@ -277,6 +267,10 @@ public slots: **/ void disableAll(); + // enable/disable plugins at the given indices. + // + void setEnabled(const QModelIndexList& indices, bool enabled); + // send plugins to the given priority // void sendToPriority(const QModelIndexList& selectionModel, int priority); diff --git a/src/pluginlistcontextmenu.cpp b/src/pluginlistcontextmenu.cpp new file mode 100644 index 00000000..787e5c0c --- /dev/null +++ b/src/pluginlistcontextmenu.cpp @@ -0,0 +1,132 @@ +#include "pluginlistcontextmenu.h" + +#include +#include + +#include "pluginlistview.h" +#include "organizercore.h" + +using namespace MOBase; + +PluginListContextMenu::PluginListContextMenu( + const QModelIndex& index, OrganizerCore& core, PluginListView* view) : + QMenu(view) + , m_core(core) + , m_index(index.model() == view->model() ? view->indexViewToModel(index) : index) + , m_view(view) +{ + if (view->selectionModel()->hasSelection()) { + m_selected = view->indexViewToModel(view->selectionModel()->selectedRows()); + } + else { + m_selected = { index }; + } + + addAction(tr("Enable selected"), [=]() { m_core.pluginList()->setEnabled(m_selected, true); }); + addAction(tr("Disable selected"), [=]() { m_core.pluginList()->setEnabled(m_selected, false); }); + + addSeparator(); + + addAction(tr("Enable all"), m_core.pluginList(), &PluginList::enableAll); + addAction(tr("Disable all"), m_core.pluginList(), &PluginList::disableAll); + + addSeparator(); + + addMenu(createSendToContextMenu()); + addSeparator(); + + bool hasLocked = false; + bool hasUnlocked = false; + for (auto& idx : m_selected) { + if (m_core.pluginList()->isEnabled(idx.row())) { + if (m_core.pluginList()->isESPLocked(idx.row())) { + hasLocked = true; + } + else { + hasUnlocked = true; + } + } + } + + if (hasLocked) { + addAction(tr("Unlock load order"), [=]() { setESPLock(m_selected, false); }); + } + if (hasUnlocked) { + addAction(tr("Lock load order"), [=]() { setESPLock(m_selected, true); }); + } + + addSeparator(); + + unsigned int modInfoIndex = ModInfo::getIndex(m_core.pluginList()->origin(m_index.data().toString())); + // this is to avoid showing the option on game files like skyrim.esm + if (modInfoIndex != UINT_MAX) { + addAction(tr("Open Origin in Explorer"), [=]() { openOriginExplorer(m_selected); }); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modInfoIndex); + std::vector flags = modInfo->getFlags(); + + if (!modInfo->isForeign() && m_selected.size() == 1) { + QAction* infoAction = addAction(tr("Open Origin Info..."), [=]() { openOriginInformation(index); }); + setDefaultAction(infoAction); + } + } + +} + +QMenu* PluginListContextMenu::createSendToContextMenu() +{ + QMenu* menu = new QMenu(m_view); + menu->setTitle(tr("Send to... ")); + menu->addAction(tr("Top"), [=]() { m_core.pluginList()->sendToPriority(m_selected, 0); }); + menu->addAction(tr("Bottom"), [=]() { m_core.pluginList()->sendToPriority(m_selected, INT_MAX); }); + menu->addAction(tr("Priority..."), [=]() { sendPluginsToPriority(m_selected); }); + return menu; +} + +void PluginListContextMenu::sendPluginsToPriority(const QModelIndexList& indices) +{ + bool ok; + int newPriority = QInputDialog::getInt(m_view->topLevelWidget(), + tr("Set Priority"), tr("Set the priority of the selected plugins"), + 0, 0, INT_MAX, 1, &ok); + if (!ok) return; + + m_core.pluginList()->sendToPriority(m_selected, newPriority); +} + +void PluginListContextMenu::setESPLock(const QModelIndexList& indices, bool locked) +{ + for (auto& idx : indices) { + if (m_core.pluginList()->isEnabled(idx.row())) { + m_core.pluginList()->lockESPIndex(idx.row(), locked); + } + } +} + +void PluginListContextMenu::openOriginExplorer(const QModelIndexList& indices) +{ + for (auto& idx : indices) { + QString fileName = idx.data().toString(); + unsigned int modIndex = ModInfo::getIndex(m_core.pluginList()->origin(fileName)); + if (modIndex == UINT_MAX) { + continue; + } + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + shell::Explore(modInfo->absolutePath()); + } +} + +void PluginListContextMenu::openOriginInformation(const QModelIndex& index) +{ + try { + QString fileName = index.data().toString(); + unsigned int modIndex = ModInfo::getIndex(m_core.pluginList()->origin(fileName)); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + + if (modInfo->isRegular() || modInfo->isOverwrite()) { + emit openModInformation(modIndex); + } + } + catch (const std::exception& e) { + reportError(e.what()); + } +} diff --git a/src/pluginlistcontextmenu.h b/src/pluginlistcontextmenu.h new file mode 100644 index 00000000..0a9a01fe --- /dev/null +++ b/src/pluginlistcontextmenu.h @@ -0,0 +1,54 @@ +#ifndef PLUGINLISTCONTEXTMENU_H +#define PLUGINLISTCONTEXTMENU_H + +#include +#include +#include + +#include "modinfo.h" + +class PluginListView; +class OrganizerCore; + +class PluginListContextMenu : public QMenu +{ + Q_OBJECT + +public: + + // creates a new context menu, the given index is the one for the click and should be valid + // + PluginListContextMenu( + const QModelIndex& index, OrganizerCore& core, PluginListView* modListView); + +signals: + + // emitted to open a mod information + // + void openModInformation(unsigned int modIndex); + +public: + + // create the "Send to... " context menu + // + QMenu* createSendToContextMenu(); + void sendPluginsToPriority(const QModelIndexList& indices); + + // set ESP lock on the given plugins + // + void setESPLock(const QModelIndexList& indices, bool locked); + + // open explorer or mod information for the origin of the plugins + // + void openOriginExplorer(const QModelIndexList& indices); + void openOriginInformation(const QModelIndex& index); + + + OrganizerCore& m_core; + QModelIndex m_index; + QModelIndexList m_selected; + PluginListView* m_view; + +}; + +#endif diff --git a/src/pluginlistview.cpp b/src/pluginlistview.cpp index 70b3ebc1..16e3dac0 100644 --- a/src/pluginlistview.cpp +++ b/src/pluginlistview.cpp @@ -3,15 +3,21 @@ #include #include +#include #include #include "mainwindow.h" #include "ui_mainwindow.h" #include "organizercore.h" #include "pluginlistsortproxy.h" +#include "pluginlistcontextmenu.h" +#include "modlistview.h" +#include "modlistviewactions.h" #include "genericicondelegate.h" #include "modelutils.h" +using namespace MOBase; + PluginListView::PluginListView(QWidget *parent) : QTreeView(parent) , m_Scrollbar(new ViewMarkingScrollBar(this->model(), this)) @@ -135,6 +141,7 @@ void PluginListView::setup(OrganizerCore& core, MainWindow* mw, Ui::MainWindow* { m_core = &core; ui = { mwui->activePluginsCounter, mwui->espFilterEdit }; + m_modActions = &mwui->modList->actions(); m_sortProxy = new PluginListSortProxy(&core); m_sortProxy->setSourceModel(core.pluginList()); @@ -146,6 +153,70 @@ void PluginListView::setup(OrganizerCore& core, MainWindow* mw, Ui::MainWindow* connect(ui.filter, &QLineEdit::textChanged, m_sortProxy, &PluginListSortProxy::updateFilter); connect(ui.filter, &QLineEdit::textChanged, this, &PluginListView::onFilterChanged); + // using a lambda here to avoid storing the mod list actions + connect(this, &QTreeView::customContextMenuRequested, [=](auto&& pos) { onCustomContextMenuRequested(pos); }); + connect(this, &QTreeView::doubleClicked, [=](auto&& index) { onDoubleClicked(index); }); +} + +void PluginListView::onCustomContextMenuRequested(const QPoint& pos) +{ + try { + PluginListContextMenu menu(indexViewToModel(indexAt(pos)), *m_core, this); + connect(&menu, &PluginListContextMenu::openModInformation, [=](auto&& modIndex) { + m_modActions->displayModInformation(modIndex); }); + menu.exec(viewport()->mapToGlobal(pos)); + } + catch (const std::exception& e) { + reportError(tr("Exception: ").arg(e.what())); + } + catch (...) { + reportError(tr("Unknown exception")); + } +} + +void PluginListView::onDoubleClicked(const QModelIndex& index) +{ + if (!index.isValid()) { + return; + } + + if (m_core->pluginList()->timeElapsedSinceLastChecked() <= QApplication::doubleClickInterval()) { + // don't interpret double click if we only just checked a plugin + return; + } + + try { + if (selectionModel()->hasSelection() && selectionModel()->selectedRows().count() == 1) { + + QModelIndex idx = selectionModel()->currentIndex(); + QString fileName = idx.data().toString(); + + if (ModInfo::getIndex(m_core->pluginList()->origin(fileName)) == UINT_MAX) { + return; + } + + auto modIndex = ModInfo::getIndex(m_core->pluginList()->origin(fileName)); + ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); + + if (modInfo->isRegular() || modInfo->isOverwrite()) { + + Qt::KeyboardModifiers modifiers = QApplication::queryKeyboardModifiers(); + if (modifiers.testFlag(Qt::ControlModifier)) { + m_modActions->openExplorer({ m_core->modList()->index(modIndex, 0) }); + } + else { + m_modActions->displayModInformation(ModInfo::getIndex(m_core->pluginList()->origin(fileName))); + } + + // workaround to cancel the editor that might have opened because of + // selection-click + closePersistentEditor(index); + } + } + } + catch (const std::exception& e) { + reportError(e.what()); + } } bool PluginListView::moveSelection(int key) diff --git a/src/pluginlistview.h b/src/pluginlistview.h index 92f03588..4a637bd1 100644 --- a/src/pluginlistview.h +++ b/src/pluginlistview.h @@ -11,6 +11,7 @@ namespace Ui { class OrganizerCore; class MainWindow; +class ModListViewActions; class PluginListSortProxy; class PluginListView : public QTreeView @@ -41,6 +42,9 @@ public: protected slots: + void onCustomContextMenuRequested(const QPoint& pos); + void onDoubleClicked(const QModelIndex& index); + void onFilterChanged(const QString& filter); protected: @@ -74,6 +78,8 @@ private: PluginListSortProxy* m_sortProxy; + ModListViewActions* m_modActions; + ViewMarkingScrollBar* m_Scrollbar; }; -- cgit v1.3.1 From b5ce6eb8e7ba67f15dcffe0639d7012088c53ebe Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 22:30:19 +0100 Subject: Move open-explorer key combination to views. --- src/mainwindow.cpp | 42 ------------------------------------------ src/mainwindow.h | 3 +-- src/modlistview.cpp | 28 ++++++++++++++++++---------- src/modlistviewactions.cpp | 4 +++- src/pluginlistview.cpp | 17 ++++++++++++++++- 5 files changed, 38 insertions(+), 56 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index a530fbf4..9b254250 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -450,9 +450,6 @@ MainWindow::MainWindow(Settings &settings connect(ui->espList->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(esplistSelectionsChanged(QItemSelection))); - new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Enter), this, SLOT(openExplorer_activated())); - new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return), this, SLOT(openExplorer_activated())); - setFilterShortcuts(ui->modList, ui->modFilterEdit); setFilterShortcuts(ui->espList, ui->espFilterEdit); setFilterShortcuts(ui->downloadView, ui->downloadFilterEdit); @@ -2340,45 +2337,6 @@ void MainWindow::setWindowEnabled(bool enabled) setEnabled(enabled); } -void MainWindow::openExplorer_activated() -{ - if (ui->modList->hasFocus()) { - QItemSelectionModel *selection = ui->modList->selectionModel(); - if (selection->hasSelection() && selection->selectedRows().count() == 1 ) { - - QModelIndex idx = selection->currentIndex(); - ModInfo::Ptr modInfo = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); - std::vector flags = modInfo->getFlags(); - - if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { - shell::Explore(modInfo->absolutePath()); - } - - } - } - - if (ui->espList->hasFocus()) { - QItemSelectionModel *selection = ui->espList->selectionModel(); - - if (selection->hasSelection() && selection->selectedRows().count() == 1) { - - QModelIndex idx = selection->currentIndex(); - QString fileName = idx.data().toString(); - - - unsigned int modInfoIndex = ModInfo::getIndex(m_OrganizerCore.pluginList()->origin(fileName)); - if (modInfoIndex != UINT_MAX) { - ModInfo::Ptr modInfo = ModInfo::getByIndex(modInfoIndex); - std::vector flags = modInfo->getFlags(); - - if (modInfo->isRegular() || (std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end())) { - shell::Explore(modInfo->absolutePath()); - } - } - } - } -} - void MainWindow::refreshProfile_activated() { m_OrganizerCore.profileRefresh(); diff --git a/src/mainwindow.h b/src/mainwindow.h index 5e3cc798..404df36b 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -316,8 +316,7 @@ private slots: void tutorialTriggered(); void extractBSATriggered(QTreeWidgetItem* item); - //modlist shortcuts - void openExplorer_activated(); + // modlist shortcuts void refreshProfile_activated(); void linkToolbar(); diff --git a/src/modlistview.cpp b/src/modlistview.cpp index 082d947e..22a673d1 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -964,20 +964,28 @@ void ModListView::timerEvent(QTimerEvent* event) bool ModListView::event(QEvent* event) { - Profile* profile = m_core->currentProfile(); - if (event->type() == QEvent::KeyPress && profile) { + if (event->type() == QEvent::KeyPress) { QKeyEvent* keyEvent = static_cast(event); if (keyEvent->modifiers() == Qt::ControlModifier - && sortColumn() == ModList::COL_PRIORITY - && (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down)) { - return moveSelection(keyEvent->key()); - } - else if (keyEvent->key() == Qt::Key_Delete) { - return removeSelection(); + && (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter)) { + if (selectionModel()->hasSelection() && selectionModel()->selectedRows().count() == 1) { + m_actions->openExplorer({ indexViewToModel(selectionModel()->currentIndex()) }); + return true; + } } - else if (keyEvent->key() == Qt::Key_Space) { - return toggleSelectionState(); + else if (m_core->currentProfile()) { + if (keyEvent->modifiers() == Qt::ControlModifier + && sortColumn() == ModList::COL_PRIORITY + && (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down)) { + return moveSelection(keyEvent->key()); + } + else if (keyEvent->key() == Qt::Key_Delete) { + return removeSelection(); + } + else if (keyEvent->key() == Qt::Key_Space) { + return toggleSelectionState(); + } } return QTreeView::event(event); } diff --git a/src/modlistviewactions.cpp b/src/modlistviewactions.cpp index f0d4c4c7..83133404 100644 --- a/src/modlistviewactions.cpp +++ b/src/modlistviewactions.cpp @@ -986,7 +986,9 @@ void ModListViewActions::openExplorer(const QModelIndexList& index) const { for (auto& idx : index) { ModInfo::Ptr info = ModInfo::getByIndex(idx.data(ModList::IndexRole).toInt()); - shell::Explore(info->absolutePath()); + if (!info->isForeign()) { + shell::Explore(info->absolutePath()); + } } } diff --git a/src/pluginlistview.cpp b/src/pluginlistview.cpp index 16e3dac0..4bf91c0a 100644 --- a/src/pluginlistview.cpp +++ b/src/pluginlistview.cpp @@ -247,11 +247,26 @@ bool PluginListView::toggleSelectionState() bool PluginListView::event(QEvent* event) { - Profile* profile = m_core->currentProfile(); + auto* profile = m_core->currentProfile(); if (event->type() == QEvent::KeyPress && profile) { QKeyEvent* keyEvent = static_cast(event); if (keyEvent->modifiers() == Qt::ControlModifier + && (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter)) { + if (selectionModel()->hasSelection() && selectionModel()->selectedRows().count() == 1) { + QModelIndex idx = selectionModel()->currentIndex(); + QString fileName = idx.data().toString(); + + if (ModInfo::getIndex(m_core->pluginList()->origin(fileName)) == UINT_MAX) { + return false; + } + + auto modIndex = ModInfo::getIndex(m_core->pluginList()->origin(fileName)); + m_modActions->openExplorer({ m_core->modList()->index(modIndex, 0) }); + return true; + } + } + else if (keyEvent->modifiers() == Qt::ControlModifier && (sortColumn() == PluginList::COL_PRIORITY || sortColumn() == PluginList::COL_MODINDEX) && (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down)) { return moveSelection(keyEvent->key()); -- cgit v1.3.1 From 91081315cf7b654f5defe855dea3dc1f71b0962c Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 22:45:57 +0100 Subject: Remove unused methods. --- src/mainwindow.cpp | 44 ++------------------------------------------ src/mainwindow.h | 7 ------- 2 files changed, 2 insertions(+), 49 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 9b254250..033bb0e0 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -321,6 +321,8 @@ MainWindow::MainWindow(Settings &settings setupModList(); ui->espList->setup(m_OrganizerCore, this, ui); + connect(ui->espList->selectionModel(), &QItemSelectionModel::selectionChanged, + [=](auto&& selection) { esplistSelectionsChanged(selection); }); ui->bsaList->setLocalMoveOnly(true); ui->bsaList->setHeaderHidden(true); @@ -448,8 +450,6 @@ MainWindow::MainWindow(Settings &settings m_CheckBSATimer.setSingleShot(true); connect(&m_CheckBSATimer, SIGNAL(timeout()), this, SLOT(checkBSAList())); - connect(ui->espList->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(esplistSelectionsChanged(QItemSelection))); - setFilterShortcuts(ui->modList, ui->modFilterEdit); setFilterShortcuts(ui->espList, ui->espFilterEdit); setFilterShortcuts(ui->downloadView, ui->downloadFilterEdit); @@ -2164,31 +2164,6 @@ void MainWindow::on_actionModify_Executables_triggered() } } -void MainWindow::setModListSorting(int index) -{ - Qt::SortOrder order = ((index & 0x01) != 0) ? Qt::DescendingOrder : Qt::AscendingOrder; - int column = index >> 1; - ui->modList->header()->setSortIndicator(column, order); -} - -void MainWindow::setESPListSorting(int index) -{ - switch (index) { - case 0: { - ui->espList->header()->setSortIndicator(1, Qt::AscendingOrder); - } break; - case 1: { - ui->espList->header()->setSortIndicator(1, Qt::DescendingOrder); - } break; - case 2: { - ui->espList->header()->setSortIndicator(0, Qt::AscendingOrder); - } break; - case 3: { - ui->espList->header()->setSortIndicator(0, Qt::DescendingOrder); - } break; - } -} - void MainWindow::refresherProgress(const DirectoryRefreshProgress* p) { if (p->finished()) { @@ -3299,21 +3274,6 @@ void MainWindow::on_displayCategoriesBtn_toggled(bool checked) setCategoryListVisible(checked); } -void MainWindow::updateESPLock(int espIndex, bool locked) -{ - QItemSelection currentSelection = ui->espList->selectionModel()->selection(); - if (currentSelection.count() == 0) { - // this path is probably useless - m_OrganizerCore.pluginList()->lockESPIndex(espIndex, locked); - } else { - Q_FOREACH (const QModelIndex &idx, currentSelection.indexes()) { - if (m_OrganizerCore.pluginList()->isEnabled(mapToModel(m_OrganizerCore.pluginList(), idx).row())) { - m_OrganizerCore.pluginList()->lockESPIndex(mapToModel(m_OrganizerCore.pluginList(), idx).row(), locked); - } - } - } -} - void MainWindow::removeFromToolbar(QAction* action) { const auto& title = action->text(); diff --git a/src/mainwindow.h b/src/mainwindow.h index 404df36b..c6e94aa9 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -124,9 +124,6 @@ public: bool addProfile(); void updateBSAList(const QStringList &defaultArchives, const QStringList &activeArchives); - void setModListSorting(int index); - void setESPListSorting(int index); - void saveArchiveList(); void installTranslator(const QString &name); @@ -214,16 +211,12 @@ private: bool errorReported(QString &logFile); - void updateESPLock(int espIndex, bool locked); - static void setupNetworkProxy(bool activate); void activateProxy(bool activate); bool createBackup(const QString &filePath, const QDateTime &time); QString queryRestore(const QString &filePath); - void addPluginSendToContextMenu(QMenu *menu); - QMenu *openFolderMenu(); void dropLocalFile(const QUrl &url, const QString &outputDir, bool move); -- cgit v1.3.1 From fff41be8455e588d181c7349678dff6fe29be76b Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 23:26:14 +0100 Subject: Remove selection-related stuff from plugin/mod lists. --- src/mainwindow.cpp | 26 -------------------------- src/mainwindow.h | 4 ---- src/modlist.cpp | 8 +++++--- src/modlist.h | 6 +++++- src/modlistview.cpp | 12 ++++++++++++ src/organizercore.cpp | 4 ---- src/pluginlist.cpp | 14 +++++++------- src/pluginlist.h | 6 +++++- src/pluginlistview.cpp | 16 ++++++++++++++++ 9 files changed, 50 insertions(+), 46 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 033bb0e0..55019a44 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -321,8 +321,6 @@ MainWindow::MainWindow(Settings &settings setupModList(); ui->espList->setup(m_OrganizerCore, this, ui); - connect(ui->espList->selectionModel(), &QItemSelectionModel::selectionChanged, - [=](auto&& selection) { esplistSelectionsChanged(selection); }); ui->bsaList->setLocalMoveOnly(true); ui->bsaList->setHeaderHidden(true); @@ -514,10 +512,6 @@ void MainWindow::setupModList() connect(&ui->modList->actions(), &ModListViewActions::overwriteCleared, [=]() { scheduleCheckForProblems(); }); connect(&ui->modList->actions(), &ModListViewActions::originModified, this, &MainWindow::originModified); connect(m_OrganizerCore.modList(), &ModList::modPrioritiesChanged, [&]() { m_ArchiveListWriter.write(); }); - - // keep here for now - connect(ui->modList->selectionModel(), &QItemSelectionModel::selectionChanged, - this, &MainWindow::modlistSelectionsChanged); } void MainWindow::resetActionIcons() @@ -2186,11 +2180,6 @@ void MainWindow::directory_refreshed() } } -void MainWindow::esplist_changed() -{ - ui->espList->updatePluginCount(); -} - void MainWindow::modInstalled(const QString &modName) { unsigned int index = ModInfo::getIndex(modName); @@ -2263,26 +2252,11 @@ void MainWindow::fileMoved(const QString &filePath, const QString &oldOriginName void MainWindow::modlistChanged(const QModelIndex&, int) { m_OrganizerCore.currentProfile()->writeModlist(); - ui->modList->updateModCount(); } void MainWindow::modlistChanged(const QModelIndexList&, int) { m_OrganizerCore.currentProfile()->writeModlist(); - ui->modList->updateModCount(); -} - -void MainWindow::modlistSelectionsChanged(const QItemSelection &selected) -{ - m_OrganizerCore.pluginList()->highlightPlugins(ui->modList->selectionModel(), *m_OrganizerCore.directoryStructure(), *m_OrganizerCore.currentProfile()); - ui->espList->verticalScrollBar()->repaint(); -} - -void MainWindow::esplistSelectionsChanged(const QItemSelection &selected) -{ - m_OrganizerCore.modList()->highlightMods(ui->espList->selectionModel(), *m_OrganizerCore.directoryStructure()); - ui->modList->verticalScrollBar()->repaint(); - ui->modList->repaint(); } void MainWindow::modRemoved(const QString &fileName) diff --git a/src/mainwindow.h b/src/mainwindow.h index c6e94aa9..5fa61c24 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -140,7 +140,6 @@ public: virtual MOBase::DelayedFileWriterBase &archivesWriter() override { return m_ArchiveListWriter; } public slots: - void esplist_changed(); void refresherProgress(const DirectoryRefreshProgress* p); void directory_refreshed(); @@ -397,9 +396,6 @@ private slots: void about(); - void modlistSelectionsChanged(const QItemSelection ¤t); - void esplistSelectionsChanged(const QItemSelection ¤t); - void resetActionIcons(); private slots: // ui slots diff --git a/src/modlist.cpp b/src/modlist.cpp index 22899aaa..077f4af3 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -845,13 +845,15 @@ int ModList::timeElapsedSinceLastChecked() const return m_LastCheck.elapsed(); } -void ModList::highlightMods(const QItemSelectionModel *selection, const MOShared::DirectoryEntry &directoryEntry) +void ModList::highlightMods( + const std::vector& pluginIndices, + const MOShared::DirectoryEntry &directoryEntry) { for (unsigned int i = 0; i < ModInfo::getNumMods(); ++i) { ModInfo::getByIndex(i)->setPluginSelected(false); } - for (QModelIndex idx : selection->selectedRows(PluginList::COL_NAME)) { - QString pluginName = idx.data().toString(); + for (auto idx : pluginIndices) { + QString pluginName = m_Organizer->pluginList()->getName(idx); const MOShared::FileEntryPtr fileEntry = directoryEntry.findFile(pluginName.toStdWString()); if (fileEntry.get() != nullptr) { diff --git a/src/modlist.h b/src/modlist.h index e4f4dfab..4b0e0157 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -129,7 +129,11 @@ public: int timeElapsedSinceLastChecked() const; - void highlightMods(const QItemSelectionModel *selection, const MOShared::DirectoryEntry &directoryEntry); + // highlight mods containing the plugins at the given indices + // + void highlightMods( + const std::vector& pluginIndices, + const MOShared::DirectoryEntry &directoryEntry); public: diff --git a/src/modlistview.cpp b/src/modlistview.cpp index f23e84fe..42627e3f 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -594,6 +594,8 @@ void ModListView::setup(OrganizerCore& core, CategoryFactory& factory, MainWindo connect(m_core, &OrganizerCore::modInstalled, this, &ModListView::onModInstalled); connect(core.modList(), &ModList::modPrioritiesChanged, this, &ModListView::onModPrioritiesChanged); connect(core.modList(), &ModList::clearOverwrite, m_actions, &ModListViewActions::clearOverwrite); + connect(core.modList(), qOverload(&ModList::modlistChanged), [=]() { updateModCount(); }); + connect(core.modList(), qOverload(&ModList::modlistChanged), [=]() { updateModCount(); }); m_byPriorityProxy = new ModListByPriorityProxy(core.currentProfile(), core, this); m_byPriorityProxy->setSourceModel(core.modList()); @@ -672,6 +674,16 @@ void ModListView::setup(OrganizerCore& core, CategoryFactory& factory, MainWindo header()->setSectionResizeMode(ModList::COL_NAME, QHeaderView::Stretch); } + // highligth plugins + connect(selectionModel(), &QItemSelectionModel::selectionChanged, [=](auto&& selected) { + std::vector modIndices; + for (auto& idx : selectionModel()->selectedRows()) { + modIndices.push_back(idx.data(ModList::IndexRole).toInt()); + } + m_core->pluginList()->highlightPlugins(modIndices, *m_core->directoryStructure()); + mwui->espList->verticalScrollBar()->repaint(); + }); + // prevent the name-column from being hidden header()->setSectionHidden(ModList::COL_NAME, false); diff --git a/src/organizercore.cpp b/src/organizercore.cpp index a8911d4f..4113607c 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -249,10 +249,6 @@ void OrganizerCore::setUserInterface(IUserInterface* ui) SLOT(modRemoved(QString))); connect(&m_ModList, SIGNAL(fileMoved(QString, QString, QString)), w, SLOT(fileMoved(QString, QString, QString))); - connect(&m_PluginList, SIGNAL(writePluginsList()), w, - SLOT(esplist_changed())); - connect(&m_PluginList, SIGNAL(esplist_changed()), w, - SLOT(esplist_changed())); connect(&m_DownloadManager, SIGNAL(showMessage(QString)), w, SLOT(showMessage(QString))); } diff --git a/src/pluginlist.cpp b/src/pluginlist.cpp index a2e485ee..4d648a46 100644 --- a/src/pluginlist.cpp +++ b/src/pluginlist.cpp @@ -135,19 +135,19 @@ QString PluginList::getColumnToolTip(int column) } } -void PluginList::highlightPlugins(const QItemSelectionModel *selection, const MOShared::DirectoryEntry &directoryEntry, const Profile &profile) +void PluginList::highlightPlugins( + const std::vector& modIndices, + const MOShared::DirectoryEntry &directoryEntry) { + auto* profile = m_Organizer.currentProfile(); + for (auto &esp : m_ESPs) { esp.modSelected = false; } - for (QModelIndex idx : selection->selectedRows(ModList::COL_PRIORITY)) { - int modIndex = idx.data(Qt::UserRole + 1).toInt(); - if (modIndex == UINT_MAX) - continue; - + for (auto& modIndex : modIndices) { ModInfo::Ptr selectedMod = ModInfo::getByIndex(modIndex); - if (!selectedMod.isNull() && profile.modEnabled(modIndex)) { + if (!selectedMod.isNull() && profile->modEnabled(modIndex)) { QDir dir(selectedMod->absolutePath()); QStringList plugins = dir.entryList(QStringList() << "*.esp" << "*.esm" << "*.esl"); const MOShared::FilesOrigin& origin = directoryEntry.getOriginByName(selectedMod->internalName().toStdWString()); diff --git a/src/pluginlist.h b/src/pluginlist.h index c93ce5cb..c16bfc98 100644 --- a/src/pluginlist.h +++ b/src/pluginlist.h @@ -217,7 +217,11 @@ public: static QString getColumnName(int column); static QString getColumnToolTip(int column); - void highlightPlugins(const QItemSelectionModel *selection, const MOShared::DirectoryEntry &directoryEntry, const Profile &profile); + // highlight plugins contained in the mods at the given indices + // + void highlightPlugins( + const std::vector& modIndices, + const MOShared::DirectoryEntry &directoryEntry); void refreshLoadOrder(); diff --git a/src/pluginlistview.cpp b/src/pluginlistview.cpp index 4bf91c0a..39db7163 100644 --- a/src/pluginlistview.cpp +++ b/src/pluginlistview.cpp @@ -150,9 +150,25 @@ void PluginListView::setup(OrganizerCore& core, MainWindow* mw, Ui::MainWindow* sortByColumn(PluginList::COL_PRIORITY, Qt::AscendingOrder); setItemDelegateForColumn(PluginList::COL_FLAGS, new GenericIconDelegate(this)); + // counter + connect(core.pluginList(), &PluginList::writePluginsList, [=]() { updatePluginCount(); }); + connect(core.pluginList(), &PluginList::esplist_changed, [=]() { updatePluginCount(); }); + + // filter connect(ui.filter, &QLineEdit::textChanged, m_sortProxy, &PluginListSortProxy::updateFilter); connect(ui.filter, &QLineEdit::textChanged, this, &PluginListView::onFilterChanged); + // highligth mod list when selected + connect(selectionModel(), &QItemSelectionModel::selectionChanged, [=](auto&& selected) { + std::vector pluginIndices; + for (auto& idx : indexViewToModel(selectionModel()->selectedRows())) { + pluginIndices.push_back(idx.row()); + } + m_core->modList()->highlightMods(pluginIndices, *m_core->directoryStructure()); + mwui->modList->verticalScrollBar()->repaint(); + mwui->modList->repaint(); + }); + // using a lambda here to avoid storing the mod list actions connect(this, &QTreeView::customContextMenuRequested, [=](auto&& pos) { onCustomContextMenuRequested(pos); }); connect(this, &QTreeView::doubleClicked, [=](auto&& index) { onDoubleClicked(index); }); -- cgit v1.3.1 From 33860662c1cd5d39cf51d411870a84b9081c8427 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Thu, 31 Dec 2020 23:44:45 +0100 Subject: Move sort plugins handler to PluginListView. --- src/mainwindow.cpp | 43 ----------------------------------------- src/mainwindow.h | 3 --- src/pluginlistview.cpp | 52 ++++++++++++++++++++++++++++++++++++++++++++++++-- src/pluginlistview.h | 5 +++-- 4 files changed, 53 insertions(+), 50 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 55019a44..2068b476 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -254,7 +254,6 @@ MainWindow::MainWindow(Settings &settings , m_CategoryFactory(CategoryFactory::instance()) , m_OrganizerCore(organizerCore) , m_PluginContainer(pluginContainer) - , m_DidUpdateMasterList(false) , m_ArchiveListWriter(std::bind(&MainWindow::saveArchiveList, this)) , m_LinkToolbar(nullptr) , m_LinkDesktop(nullptr) @@ -3304,48 +3303,6 @@ void MainWindow::on_showHiddenBox_toggled(bool checked) m_OrganizerCore.downloadManager()->setShowHidden(checked); } -void MainWindow::on_bossButton_clicked() -{ - const bool offline = m_OrganizerCore.settings().network().offlineMode(); - - auto r = QMessageBox::No; - - if (offline) { - r = QMessageBox::question( - this, tr("Sorting plugins"), - tr("Are you sure you want to sort your plugins list?") + "\r\n\r\n" + - tr("Note: You are currently in offline mode and LOOT will not update the master list."), - QMessageBox::Yes | QMessageBox::No); - } else { - r = QMessageBox::question( - this, tr("Sorting plugins"), - tr("Are you sure you want to sort your plugins list?"), - QMessageBox::Yes | QMessageBox::No); - } - - if (r != QMessageBox::Yes) { - return; - } - - m_OrganizerCore.savePluginList(); - - setEnabled(false); - ON_BLOCK_EXIT([&] () { setEnabled(true); }); - - // don't try to update the master list in offline mode - const bool didUpdateMasterList = offline ? true : m_DidUpdateMasterList; - - if (runLoot(this, m_OrganizerCore, didUpdateMasterList)) { - // don't assume the master list was updated in offline mode - if (!offline) { - m_DidUpdateMasterList = true; - } - - m_OrganizerCore.refreshESPList(false); - m_OrganizerCore.savePluginList(); - } -} - const char *MainWindow::PATTERN_BACKUP_GLOB = ".????_??_??_??_??_??"; const char *MainWindow::PATTERN_BACKUP_REGEX = "\\.(\\d\\d\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d)"; const char *MainWindow::PATTERN_BACKUP_DATE = "yyyy_MM_dd_hh_mm_ss"; diff --git a/src/mainwindow.h b/src/mainwindow.h index 5fa61c24..0db339f2 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -276,8 +276,6 @@ private: QByteArray m_ArchiveListHash; - bool m_DidUpdateMasterList; - MOBase::DelayedFileWriter m_ArchiveListWriter; QAction* m_LinkToolbar; @@ -431,7 +429,6 @@ private slots: // ui slots void on_linkButton_pressed(); void on_showHiddenBox_toggled(bool checked); void on_bsaList_itemChanged(QTreeWidgetItem *item, int column); - void on_bossButton_clicked(); void on_saveButton_clicked(); void on_restoreButton_clicked(); diff --git a/src/pluginlistview.cpp b/src/pluginlistview.cpp index 39db7163..f95226fc 100644 --- a/src/pluginlistview.cpp +++ b/src/pluginlistview.cpp @@ -20,7 +20,9 @@ using namespace MOBase; PluginListView::PluginListView(QWidget *parent) : QTreeView(parent) + , m_sortProxy(nullptr) , m_Scrollbar(new ViewMarkingScrollBar(this->model(), this)) + , m_didUpdateMasterList(false) { setVerticalScrollBar(m_Scrollbar); MOBase::setCustomizableColumns(this); @@ -123,6 +125,49 @@ void PluginListView::onFilterChanged(const QString& filter) updatePluginCount(); } +void PluginListView::onSortButtonClicked() +{ + const bool offline = m_core->settings().network().offlineMode(); + + auto r = QMessageBox::No; + + if (offline) { + r = QMessageBox::question( + topLevelWidget(), tr("Sorting plugins"), + tr("Are you sure you want to sort your plugins list?") + "\r\n\r\n" + + tr("Note: You are currently in offline mode and LOOT will not update the master list."), + QMessageBox::Yes | QMessageBox::No); + } + else { + r = QMessageBox::question( + topLevelWidget(), tr("Sorting plugins"), + tr("Are you sure you want to sort your plugins list?"), + QMessageBox::Yes | QMessageBox::No); + } + + if (r != QMessageBox::Yes) { + return; + } + + m_core->savePluginList(); + + topLevelWidget()->setEnabled(false); + Guard g([=]() { topLevelWidget()->setEnabled(true); }); + + // don't try to update the master list in offline mode + const bool didUpdateMasterList = offline ? true : m_didUpdateMasterList; + + if (runLoot(topLevelWidget(), *m_core, didUpdateMasterList)) { + // don't assume the master list was updated in offline mode + if (!offline) { + m_didUpdateMasterList = true; + } + + m_core->refreshESPList(false); + m_core->savePluginList(); + } +} + std::pair PluginListView::selected() const { return { indexViewToModel(currentIndex()), indexViewToModel(selectionModel()->selectedRows()) }; @@ -151,8 +196,11 @@ void PluginListView::setup(OrganizerCore& core, MainWindow* mw, Ui::MainWindow* setItemDelegateForColumn(PluginList::COL_FLAGS, new GenericIconDelegate(this)); // counter - connect(core.pluginList(), &PluginList::writePluginsList, [=]() { updatePluginCount(); }); - connect(core.pluginList(), &PluginList::esplist_changed, [=]() { updatePluginCount(); }); + connect(core.pluginList(), &PluginList::writePluginsList, [=]{ updatePluginCount(); }); + connect(core.pluginList(), &PluginList::esplist_changed, [=]{ updatePluginCount(); }); + + // sort + connect(mwui->bossButton, &QPushButton::clicked, [=]{ onSortButtonClicked(); }); // filter connect(ui.filter, &QLineEdit::textChanged, m_sortProxy, &PluginListSortProxy::updateFilter); diff --git a/src/pluginlistview.h b/src/pluginlistview.h index 4a637bd1..e5dc15e7 100644 --- a/src/pluginlistview.h +++ b/src/pluginlistview.h @@ -46,6 +46,7 @@ protected slots: void onDoubleClicked(const QModelIndex& index); void onFilterChanged(const QString& filter); + void onSortButtonClicked(); protected: @@ -77,10 +78,10 @@ private: PluginListViewUi ui; PluginListSortProxy* m_sortProxy; - ModListViewActions* m_modActions; - ViewMarkingScrollBar* m_Scrollbar; + + bool m_didUpdateMasterList; }; #endif // PLUGINLISTVIEW_H -- cgit v1.3.1 From 73490b3fdd8998a7c116d5c99d2ead4582dfc834 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Fri, 1 Jan 2021 12:29:49 +0100 Subject: Remove unused stuff from MainWindow. --- src/mainwindow.cpp | 23 ----------------------- 1 file changed, 23 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 2068b476..f583f72b 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -30,7 +30,6 @@ along with Mod Organizer. If not, see . #include "isavegameinfowidget.h" #include "nexusinterface.h" #include "organizercore.h" -#include "pluginlistsortproxy.h" #include "previewgenerator.h" #include "serverinfo.h" #include "savegameinfo.h" @@ -39,8 +38,6 @@ along with Mod Organizer. If not, see . #include "instancemanager.h" #include "report.h" #include "modlist.h" -#include "modlistsortproxy.h" -#include "qtgroupingproxy.h" #include "profile.h" #include "pluginlist.h" #include "profilesdialog.h" @@ -82,7 +79,6 @@ along with Mod Organizer. If not, see . #include "listdialog.h" #include "envshortcut.h" #include "browserdialog.h" -#include "modlistbypriorityproxy.h" #include "modlistviewactions.h" #include "modlistcontextmenu.h" @@ -92,7 +88,6 @@ along with Mod Organizer. If not, see . #include "shared/filesorigin.h" #include -#include #include #include #include @@ -664,24 +659,6 @@ void MainWindow::resizeEvent(QResizeEvent *event) QMainWindow::resizeEvent(event); } -static QModelIndex mapToModel(const QAbstractItemModel *targetModel, QModelIndex idx) -{ - QModelIndex result = idx; - const QAbstractItemModel *model = idx.model(); - while (model != targetModel) { - if (model == nullptr) { - return QModelIndex(); - } - const QAbstractProxyModel *proxyModel = qobject_cast(model); - if (proxyModel == nullptr) { - return QModelIndex(); - } - result = proxyModel->mapToSource(result); - model = proxyModel->sourceModel(); - } - return result; -} - void MainWindow::setupToolbar() { setupActionMenu(ui->actionModPage); -- cgit v1.3.1 From f36c68332019ec68a713b21519c0439039845fa1 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Fri, 1 Jan 2021 13:47:17 +0100 Subject: Save the state of the mod list properly. --- src/mainwindow.cpp | 1 + 1 file changed, 1 insertion(+) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index f583f72b..10de1b84 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1965,6 +1965,7 @@ void MainWindow::storeSettings() s.widgets().saveIndex(ui->tabWidget); m_DataTab->saveState(s); + ui->modList->saveState(s); s.interface().setFilterOptions(FilterWidget::options()); } -- cgit v1.3.1 From c0ac46d5c020bfb9292a812b2c52dc3c6236c7b3 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Fri, 1 Jan 2021 20:59:30 +0100 Subject: Fix create empty mod/separator position. --- src/mainwindow.cpp | 2 +- src/modlistcontextmenu.cpp | 15 ++++++++++----- src/modlistcontextmenu.h | 10 ++++++++-- src/modlistviewactions.cpp | 25 ++++++++++--------------- src/modlistviewactions.h | 6 +++--- 5 files changed, 32 insertions(+), 26 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 10de1b84..23050467 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -366,7 +366,7 @@ MainWindow::MainWindow(Settings &settings 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, ui->listOptionsBtn)); + ui->listOptionsBtn->setMenu(new ModListGlobalContextMenu(m_OrganizerCore, ui->modList, this)); ui->openFolderMenu->setMenu(openFolderMenu()); diff --git a/src/modlistcontextmenu.cpp b/src/modlistcontextmenu.cpp index e557d7a0..f20586c4 100644 --- a/src/modlistcontextmenu.cpp +++ b/src/modlistcontextmenu.cpp @@ -10,11 +10,16 @@ using namespace MOBase; ModListGlobalContextMenu::ModListGlobalContextMenu(OrganizerCore& core, ModListView* view, QWidget* parent) + : ModListGlobalContextMenu(core, view, QModelIndex(), parent) +{ +} + +ModListGlobalContextMenu::ModListGlobalContextMenu(OrganizerCore& core, ModListView* view, const QModelIndex& index, QWidget* parent) : QMenu(parent) { addAction(tr("Install Mod..."), [=]() { view->actions().installMod(); }); - addAction(tr("Create empty mod"), [=]() { view->actions().createEmptyMod(-1); }); - addAction(tr("Create Separator"), [=]() { view->actions().createSeparator(-1); }); + addAction(tr("Create empty mod"), [=]() { view->actions().createEmptyMod(index); }); + addAction(tr("Create Separator"), [=]() { view->actions().createSeparator(index); }); if (view->hasCollapsibleSeparators()) { addSeparator(); @@ -24,14 +29,14 @@ ModListGlobalContextMenu::ModListGlobalContextMenu(OrganizerCore& core, ModListV addSeparator(); - addAction(tr("Enable all visible"), [=]() { + addAction(tr("Enable all parent"), [=]() { if (QMessageBox::question(view, tr("Confirm"), tr("Really enable all visible mods?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { view->enableAllVisible(); } }); addAction(tr("Disable all visible"), [=]() { - if (QMessageBox::question(view, tr("Confirm"), tr("Really disable all visible mods?"), + if (QMessageBox::question(parent, tr("Confirm"), tr("Really disable all visible mods?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { view->disableAllVisible(); } @@ -171,7 +176,7 @@ ModListContextMenu::ModListContextMenu( ModInfo::Ptr info = ModInfo::getByIndex(index.data(ModList::IndexRole).toInt()); - QMenu* allMods = new ModListGlobalContextMenu(core, view, view); + QMenu* allMods = new ModListGlobalContextMenu(core, view, m_index, view->topLevelWidget()); allMods->setTitle(tr("All Mods")); addMenu(allMods); diff --git a/src/modlistcontextmenu.h b/src/modlistcontextmenu.h index 565aac97..2b3f9dcd 100644 --- a/src/modlistcontextmenu.h +++ b/src/modlistcontextmenu.h @@ -19,8 +19,14 @@ class ModListGlobalContextMenu : public QMenu Q_OBJECT public: - ModListGlobalContextMenu( - OrganizerCore& core, ModListView* modListView, QWidget* parent = nullptr); + ModListGlobalContextMenu(OrganizerCore& core, ModListView* view, QWidget* parent = nullptr); + +protected: + + friend class ModListContextMenu; + + // creates a "All mods" context menu for the given index (can be invalid). + ModListGlobalContextMenu(OrganizerCore& core, ModListView* view, const QModelIndex& index, QWidget* parent = nullptr); }; diff --git a/src/modlistviewactions.cpp b/src/modlistviewactions.cpp index cb212e0b..9957618a 100644 --- a/src/modlistviewactions.cpp +++ b/src/modlistviewactions.cpp @@ -75,7 +75,7 @@ void ModListViewActions::installMod(const QString& archivePath) const } } -void ModListViewActions::createEmptyMod(int modIndex) const +void ModListViewActions::createEmptyMod(const QModelIndex& index) const { GuessedValue name; name.setFilter(&fixDirectoryName); @@ -97,8 +97,8 @@ void ModListViewActions::createEmptyMod(int modIndex) const } int newPriority = -1; - if (modIndex >= 0 && m_view->sortColumn() == ModList::COL_PRIORITY) { - newPriority = m_core.currentProfile()->getModPriority(modIndex); + if (index.isValid() && m_view->sortColumn() == ModList::COL_PRIORITY) { + newPriority = m_core.currentProfile()->getModPriority(index.data(ModList::IndexRole).toInt()); } IModInterface* newMod = m_core.createMod(name); @@ -113,12 +113,11 @@ void ModListViewActions::createEmptyMod(int modIndex) const } } -void ModListViewActions::createSeparator(int modIndex) const +void ModListViewActions::createSeparator(const QModelIndex& index) const { GuessedValue name; name.setFilter(&fixDirectoryName); - while (name->isEmpty()) - { + while (name->isEmpty()) { bool ok; name.update(QInputDialog::getText(m_parent, tr("Create Separator..."), tr("This will create a new separator.\n" @@ -126,28 +125,24 @@ void ModListViewActions::createSeparator(int modIndex) const GUESS_USER); if (!ok) { return; } } - if (m_core.modList()->getMod(name) != nullptr) - { + 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) - { + if (m_core.modList()->getMod(name) != nullptr) { return; } int newPriority = -1; - if (modIndex >= 0 && m_view->sortColumn() == ModList::COL_PRIORITY) - { - newPriority = m_core.currentProfile()->getModPriority(modIndex); + if (index.isValid() && m_view->sortColumn() == ModList::COL_PRIORITY) { + newPriority = m_core.currentProfile()->getModPriority(index.data(ModList::IndexRole).toInt()); } if (m_core.createMod(name) == nullptr) { return; } m_core.refresh(); - if (newPriority >= 0) - { + if (newPriority >= 0) { m_core.modList()->changeModPriority(ModInfo::getIndex(name), newPriority); } diff --git a/src/modlistviewactions.h b/src/modlistviewactions.h index 2850d30a..f1215cec 100644 --- a/src/modlistviewactions.h +++ b/src/modlistviewactions.h @@ -36,10 +36,10 @@ public: void installMod(const QString& archivePath = "") const; // create an empty mod/a separator before the given mod or at - // the end of the list if the index is -1 + // the end of the list if the index is invalid // - void createEmptyMod(int modIndex) const; - void createSeparator(int modIndex) const; + void createEmptyMod(const QModelIndex& index = QModelIndex()) const; + void createSeparator(const QModelIndex& index = QModelIndex()) const; // check all mods for update // -- cgit v1.3.1 From d86dec53822e049954d03ba18473dae08d74040f Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Sat, 2 Jan 2021 13:03:51 +0100 Subject: Minor refactoring. --- src/mainwindow.cpp | 10 ---------- src/mainwindow.h | 6 ++---- src/modlist.cpp | 36 ++++++++++++++++++++---------------- src/modlist.h | 37 ++++++++++--------------------------- src/modlistview.cpp | 19 +++++++++---------- src/modlistview.h | 2 +- src/organizercore.cpp | 5 +---- 7 files changed, 43 insertions(+), 72 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 23050467..b979be86 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -2226,16 +2226,6 @@ void MainWindow::fileMoved(const QString &filePath, const QString &oldOriginName } } -void MainWindow::modlistChanged(const QModelIndex&, int) -{ - m_OrganizerCore.currentProfile()->writeModlist(); -} - -void MainWindow::modlistChanged(const QModelIndexList&, int) -{ - m_OrganizerCore.currentProfile()->writeModlist(); -} - void MainWindow::modRemoved(const QString &fileName) { if (!fileName.isEmpty() && !QFileInfo(fileName).isAbsolute()) { diff --git a/src/mainwindow.h b/src/mainwindow.h index 0db339f2..b8474bac 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -378,12 +378,10 @@ private slots: void updateStyle(const QString &style); - void modlistChanged(const QModelIndex &index, int role); - void modlistChanged(const QModelIndexList &indicies, int role); - void fileMoved(const QString &filePath, const QString &oldOriginName, const QString &newOriginName); - void resizeLists(bool pluginListCustom); + void fileMoved(const QString& filePath, const QString& oldOriginName, const QString& newOriginName); + /** * @brief allow columns in mod list and plugin list to be resized */ diff --git a/src/modlist.cpp b/src/modlist.cpp index b88c6a01..cae40962 100644 --- a/src/modlist.cpp +++ b/src/modlist.cpp @@ -588,7 +588,7 @@ bool ModList::setData(const QModelIndex &index, const QVariant &value, int role) m_Profile->setModEnabled(modID, enabled); m_Modified = true; m_LastCheck.restart(); - emit modlistChanged(index, role); + emit modStatesChanged({ index }); emit tutorialModlistUpdate(); } result = true; @@ -613,7 +613,7 @@ bool ModList::setData(const QModelIndex &index, const QVariant &value, int role) } if (ok) { m_Profile->setModPriority(modID, newPriority); - emit modPrioritiesChanged({ modID }); + emit modPrioritiesChanged({ index }); result = true; } else { result = false; @@ -737,35 +737,34 @@ void ModList::changeModPriority(std::vector sourceIndices, int newPriority) if (m_Profile == nullptr) return; emit layoutAboutToBeChanged(); - Profile *profile = m_Profile; // sort the moving mods by ascending priorities std::sort(sourceIndices.begin(), sourceIndices.end(), - [profile](const int &LHS, const int &RHS) { - return profile->getModPriority(LHS) > profile->getModPriority(RHS); + [=](const int &LHS, const int &RHS) { + return m_Profile->getModPriority(LHS) > m_Profile->getModPriority(RHS); }); // move mods that are decreasing in priority for (std::vector::const_iterator iter = sourceIndices.begin(); iter != sourceIndices.end(); ++iter) { - int oldPriority = profile->getModPriority(*iter); + int oldPriority = m_Profile->getModPriority(*iter); if (oldPriority > newPriority) { - profile->setModPriority(*iter, newPriority); + m_Profile->setModPriority(*iter, newPriority); m_ModMoved(ModInfo::getByIndex(*iter)->name(), oldPriority, newPriority); } } // sort the moving mods by descending priorities std::sort(sourceIndices.begin(), sourceIndices.end(), - [profile](const int &LHS, const int &RHS) { - return profile->getModPriority(LHS) < profile->getModPriority(RHS); + [=](const int &LHS, const int &RHS) { + return m_Profile->getModPriority(LHS) < m_Profile->getModPriority(RHS); }); // if at least one mod is increasing in priority, the target index is // that of the row BELOW the dropped location, otherwise it's the one above for (std::vector::const_iterator iter = sourceIndices.begin(); iter != sourceIndices.end(); ++iter) { - int oldPriority = profile->getModPriority(*iter); + int oldPriority = m_Profile->getModPriority(*iter); if (oldPriority < newPriority) { --newPriority; break; @@ -775,16 +774,21 @@ void ModList::changeModPriority(std::vector sourceIndices, int newPriority) // move mods that are increasing in priority for (std::vector::const_iterator iter = sourceIndices.begin(); iter != sourceIndices.end(); ++iter) { - int oldPriority = profile->getModPriority(*iter); + int oldPriority = m_Profile->getModPriority(*iter); if (oldPriority < newPriority) { - profile->setModPriority(*iter, newPriority); + m_Profile->setModPriority(*iter, newPriority); m_ModMoved(ModInfo::getByIndex(*iter)->name(), oldPriority, newPriority); } } emit layoutChanged(); - emit modPrioritiesChanged(sourceIndices); + QModelIndexList indices; + for (auto& idx : sourceIndices) { + indices.append(index(idx, 0, QModelIndex())); + } + + emit modPrioritiesChanged(indices); } @@ -796,7 +800,7 @@ void ModList::changeModPriority(int sourceIndex, int newPriority) m_Profile->setModPriority(sourceIndex, newPriority); emit layoutChanged(); - emit modPrioritiesChanged({ sourceIndex }); + emit modPrioritiesChanged({ index(sourceIndex, 0) }); } void ModList::setOverwriteMarkers(const std::set &overwrite, const std::set &overwritten) @@ -1473,7 +1477,7 @@ void ModList::shiftModsPriority(const QModelIndexList& indices, int offset) notifyChange(index); } - emit modPrioritiesChanged(allIndex); + emit modPrioritiesChanged(indices); } void ModList::changeModsPriority(const QModelIndexList& indices, int priority) @@ -1513,7 +1517,7 @@ bool ModList::toggleState(const QModelIndexList& indices) m_Profile->setModsEnabled(modsToEnable, modsToDisable); - emit modlistChanged(indices, 0); + emit modStatesChanged(indices); emit tutorialModlistUpdate(); m_Modified = true; diff --git a/src/modlist.h b/src/modlist.h index e77ceb1f..6d4e0e91 100644 --- a/src/modlist.h +++ b/src/modlist.h @@ -270,13 +270,16 @@ public slots: signals: - /** - * @brief Emitted whenever the priority of mods changes - * - * The sorting of the list can only be manually changed if the list is sorted by priority - * in which case the move is intended to change the priority of a mod. - **/ - void modPrioritiesChanged(std::vector const& index); + // emitted when the priority of one or multiple mods have changed + // + // the sorting of the list can only be manually changed if the list is sorted by priority + // in which case the move is intended to change the priority of a mod. + // + void modPrioritiesChanged(const QModelIndexList& indices); + + // emitted when the state (active/inactive) of one or multiple mods have changed + // + void modStatesChanged(const QModelIndexList& indices); /** * @brief emitted when the model wants a text to be displayed by the UI @@ -312,26 +315,6 @@ signals: */ void modUninstalled(const QString &fileName); - /** - * @brief emitted whenever a row in the list has changed - * - * @param index the index of the changed field - * @param role role of the field that changed - * @note this signal must only be emitted if the row really did change. - * Slots handling this signal therefore do not have to verify that a change has happened - **/ - void modlistChanged(const QModelIndex &index, int role); - - /** - * @brief emitted whenever multiple row sin the list has changed - * - * @param indicies the list of indicies of the changed field - * @param role role of the field that changed - * @note this signal must only be emitted if the row really did change. - * Slots handling this signal therefore do not have to verify that a change has happened - **/ - void modlistChanged(const QModelIndexList &indicies, int role); - /** * @brief QML seems to handle overloaded signals poorly - create unique signal for tutorials */ diff --git a/src/modlistview.cpp b/src/modlistview.cpp index c334db93..f304a1b0 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -336,11 +336,11 @@ void ModListView::expandItem(const QModelIndex& index) } } -void ModListView::onModPrioritiesChanged(std::vector const& indices) +void ModListView::onModPrioritiesChanged(const QModelIndexList& indices) { // expand separator whose priority has changed and parents for (auto index : indices) { - auto idx = indexModelToView(m_core->modList()->index(index, 0)); + auto idx = indexModelToView(index); if (hasCollapsibleSeparators() && model()->hasChildren(idx)) { setExpanded(idx, true); } @@ -648,17 +648,16 @@ void ModListView::setup(OrganizerCore& core, CategoryFactory& factory, MainWindo mwui->currentCategoryLabel, mwui->clearFiltersButton, mwui->filtersSeparators }; - connect(m_core, &OrganizerCore::modInstalled, this, &ModListView::onModInstalled); - connect(core.modList(), &ModList::modPrioritiesChanged, this, &ModListView::onModPrioritiesChanged); - connect(core.modList(), &ModList::clearOverwrite, m_actions, &ModListViewActions::clearOverwrite); - connect(core.modList(), qOverload(&ModList::modlistChanged), [=]() { updateModCount(); }); - connect(core.modList(), qOverload(&ModList::modlistChanged), [=]() { updateModCount(); }); + connect(m_core, &OrganizerCore::modInstalled, [=](auto&& name) { onModInstalled(name); }); + connect(core.modList(), &ModList::modPrioritiesChanged, [=](auto&& indices) { onModPrioritiesChanged(indices); }); + connect(core.modList(), &ModList::clearOverwrite, [=] { m_actions->clearOverwrite(); }); + connect(core.modList(), &ModList::modStatesChanged, [=] { updateModCount(); }); m_byPriorityProxy = new ModListByPriorityProxy(core.currentProfile(), core, this); m_byPriorityProxy->setSourceModel(core.modList()); - connect(this, &QTreeView::expanded, m_byPriorityProxy, &ModListByPriorityProxy::expanded); - connect(this, &QTreeView::collapsed, m_byPriorityProxy, &ModListByPriorityProxy::collapsed); - connect(m_byPriorityProxy, &ModListByPriorityProxy::expandItem, this, &ModListView::expandItem); + connect(this, &QTreeView::expanded, [=](auto&& name) { m_byPriorityProxy->expanded(name); }); + connect(this, &QTreeView::collapsed, [=](auto&& name) { m_byPriorityProxy->collapsed(name); }); + connect(m_byPriorityProxy, &ModListByPriorityProxy::expandItem, [=](auto&& index) { expandItem(index); }); m_byCategoryProxy = new QtGroupingProxy(core.modList(), QModelIndex(), ModList::COL_CATEGORY, ModList::GroupingRole, 0, ModList::AggrRole); diff --git a/src/modlistview.h b/src/modlistview.h index a2e8505d..92b53960 100644 --- a/src/modlistview.h +++ b/src/modlistview.h @@ -165,7 +165,7 @@ protected slots: private: - void onModPrioritiesChanged(std::vector const& indices); + void onModPrioritiesChanged(const QModelIndexList& indices); void onModInstalled(const QString& modName); void onModFilterActive(bool filterActive); diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 4113607c..2b1cbdc6 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -118,6 +118,7 @@ OrganizerCore::OrganizerCore(Settings &settings) connect(&m_ModList, SIGNAL(removeOrigin(QString)), this, SLOT(removeOrigin(QString))); + connect(&m_ModList, &ModList::modStatesChanged, [=] { currentProfile()->writeModlist(); }); connect(NexusInterface::instance().getAccessManager(), SIGNAL(validateSuccessful(bool)), this, SLOT(loginSuccessful(bool))); @@ -235,10 +236,6 @@ void OrganizerCore::setUserInterface(IUserInterface* ui) } if (w) { - connect(&m_ModList, SIGNAL(modlistChanged(QModelIndex, int)), w, - SLOT(modlistChanged(QModelIndex, int))); - connect(&m_ModList, SIGNAL(modlistChanged(QModelIndexList, int)), w, - SLOT(modlistChanged(QModelIndexList, int))); connect(&m_ModList, SIGNAL(showMessage(QString)), w, SLOT(showMessage(QString))); connect(&m_ModList, SIGNAL(modRenamed(QString, QString)), w, -- cgit v1.3.1 From 42586639a8f17a19779cb646f1327dd92b18d135 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Sat, 2 Jan 2021 13:27:21 +0100 Subject: Move connection from organizer to mainwindow. --- src/mainwindow.cpp | 12 ++++++++++++ src/organizercore.cpp | 15 --------------- 2 files changed, 12 insertions(+), 15 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index b979be86..6929a009 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -464,6 +464,18 @@ MainWindow::MainWindow(Settings &settings 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()); } diff --git a/src/organizercore.cpp b/src/organizercore.cpp index 2b1cbdc6..6eb81792 100644 --- a/src/organizercore.cpp +++ b/src/organizercore.cpp @@ -235,21 +235,6 @@ void OrganizerCore::setUserInterface(IUserInterface* ui) w = m_UserInterface->mainWindow(); } - if (w) { - connect(&m_ModList, SIGNAL(showMessage(QString)), w, - SLOT(showMessage(QString))); - connect(&m_ModList, SIGNAL(modRenamed(QString, QString)), w, - SLOT(modRenamed(QString, QString))); - connect(&m_ModList, SIGNAL(modUninstalled(QString)), w, - SLOT(modRemoved(QString))); - connect(&m_InstallationManager, SIGNAL(modReplaced(QString)), w, - SLOT(modRemoved(QString))); - connect(&m_ModList, SIGNAL(fileMoved(QString, QString, QString)), w, - SLOT(fileMoved(QString, QString, QString))); - connect(&m_DownloadManager, SIGNAL(showMessage(QString)), w, - SLOT(showMessage(QString))); - } - m_InstallationManager.setParentWidget(w); m_Updater.setUserInterface(w); m_UILocker.setUserInterface(w); -- cgit v1.3.1 From 071974c243d97a19e5a73f368ce25f8decd00183 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Sat, 2 Jan 2021 17:14:09 +0100 Subject: Save/restore filter list state between run. --- src/filterlist.cpp | 50 +++++++++++++++++++++++++++++++++++++++----------- src/mainwindow.cpp | 2 +- src/modlistview.cpp | 4 ++-- src/settings.cpp | 27 +++++++++++++++++++++++++-- src/settings.h | 10 +++++++--- 5 files changed, 74 insertions(+), 19 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/filterlist.cpp b/src/filterlist.cpp index c3f169a6..14813312 100644 --- a/src/filterlist.cpp +++ b/src/filterlist.cpp @@ -12,7 +12,14 @@ using Criteria = ModListSortProxy::Criteria; class FilterList::CriteriaItem : public QTreeWidgetItem { + + static constexpr int IDRole = Qt::UserRole; + static constexpr int TypeRole = Qt::UserRole + 1; + public: + + static constexpr int StateRole = Qt::UserRole + 2; + enum States { FirstState = 0, @@ -58,27 +65,41 @@ public: void nextState() { - m_state = static_cast(m_state + 1); - if (m_state > LastState) { - m_state = FirstState; + auto s = static_cast(m_state + 1); + if (s > LastState) { + s = FirstState; } - - updateState(); + setState(s); } void previousState() { - m_state = static_cast(m_state - 1); - if (m_state < FirstState) { - m_state = LastState; + auto s = static_cast(m_state - 1); + if (s < FirstState) { + s = LastState; } + setState(s); + } - updateState(); + QVariant data(int column, int role) const + { + if (role == StateRole) { + return m_state; + } + return QTreeWidgetItem::data(column, role); + } + + void setData(int column, int role, const QVariant& value) { + if (role == StateRole) { + MOBase::log::debug("setData: {}, {}, {}", column, role, value.toInt()); + setState(static_cast(value.toInt())); + } + else { + QTreeWidgetItem::setData(column, role, value); + } } private: - const int IDRole = Qt::UserRole; - const int TypeRole = Qt::UserRole + 1; FilterList* m_list; States m_state; @@ -212,10 +233,17 @@ FilterList::FilterList(Ui::MainWindow* ui, OrganizerCore& core, CategoryFactory& void FilterList::restoreState(const Settings& s) { s.widgets().restoreIndex(ui->filtersSeparators); + s.widgets().restoreChecked(ui->filtersAnd); + s.widgets().restoreChecked(ui->filtersOr); + s.widgets().restoreTreeCheckState(ui->filters, CriteriaItem::StateRole); + checkCriteria(); } void FilterList::saveState(Settings& s) const { + s.widgets().saveTreeCheckState(ui->filters, CriteriaItem::StateRole); + s.widgets().saveChecked(ui->filtersAnd); + s.widgets().saveChecked(ui->filtersOr); s.widgets().saveIndex(ui->filtersSeparators); } diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 6929a009..2b2685c4 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1170,8 +1170,8 @@ void MainWindow::showEvent(QShowEvent *event) QMainWindow::showEvent(event); if (!m_WasVisible) { - readSettings(); ui->modList->refreshFilters(); + readSettings(); // this needs to be connected here instead of in the constructor because the // actual changing of the stylesheet is done by MOApplication, which diff --git a/src/modlistview.cpp b/src/modlistview.cpp index 0898fe3c..a460e4a4 100644 --- a/src/modlistview.cpp +++ b/src/modlistview.cpp @@ -804,7 +804,7 @@ void ModListView::restoreState(const Settings& s) s.geometry().restoreState(header()); s.widgets().restoreIndex(ui.groupBy); - s.widgets().restoreTreeState(this); + s.widgets().restoreTreeExpandState(this); m_filters->restoreState(s); } @@ -814,7 +814,7 @@ void ModListView::saveState(Settings& s) const s.geometry().saveState(header()); s.widgets().saveIndex(ui.groupBy); - s.widgets().saveTreeState(this); + s.widgets().saveTreeExpandState(this); m_filters->saveState(s); } diff --git a/src/settings.cpp b/src/settings.cpp index e379a819..3cc026cf 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1065,7 +1065,30 @@ WidgetSettings::WidgetSettings(QSettings& s, bool globalInstance) } } -void WidgetSettings::saveTreeState(const QTreeView* tv, int role) +void WidgetSettings::saveTreeCheckState(const QTreeView* tv, int role) +{ + QVariantList data; + for (auto index : flatIndex(tv->model())) { + data.append(index.data(role)); + } + set(m_Settings, "Widgets", indexSettingName(tv), data); +} + +void WidgetSettings::restoreTreeCheckState(QTreeView* tv, int role) const +{ + if (auto states = getOptional(m_Settings, "Widgets", indexSettingName(tv))) { + auto allIndex = flatIndex(tv->model()); + MOBase::log::debug("restoreTreeCheckState: {}, {}", states->size(), allIndex.size()); + if (states->size() != allIndex.size()) { + return; + } + for (int i = 0; i < states->size(); ++i) { + tv->model()->setData(allIndex[i], states->at(i), role); + } + } +} + +void WidgetSettings::saveTreeExpandState(const QTreeView* tv, int role) { QVariantList expanded; for (auto index : flatIndex(tv->model())) { @@ -1076,7 +1099,7 @@ void WidgetSettings::saveTreeState(const QTreeView* tv, int role) set(m_Settings, "Widgets", indexSettingName(tv), expanded); } -void WidgetSettings::restoreTreeState(QTreeView* tv, int role) const +void WidgetSettings::restoreTreeExpandState(QTreeView* tv, int role) const { if (auto expanded = getOptional(m_Settings, "Widgets", indexSettingName(tv))) { tv->collapseAll(); diff --git a/src/settings.h b/src/settings.h index 5506bbf8..9c3765c2 100644 --- a/src/settings.h +++ b/src/settings.h @@ -202,11 +202,15 @@ public: // WidgetSettings(QSettings& s, bool globalInstance); + // tree item check - this saves the list of expanded items based on the given role + // + void saveTreeCheckState(const QTreeView* tv, int role = Qt::CheckStateRole); + void restoreTreeCheckState(QTreeView* tv, int role = Qt::CheckStateRole) const; + // tree state - this saves the list of expanded items based on the given role // - std::vector allIndex(const QAbstractItemModel* model, int column = 0, const QModelIndex& parent = QModelIndex()) const; - void saveTreeState(const QTreeView* tv, int role = Qt::DisplayRole); - void restoreTreeState(QTreeView* tv, int role = Qt::DisplayRole) const; + void saveTreeExpandState(const QTreeView* tv, int role = Qt::DisplayRole); + void restoreTreeExpandState(QTreeView* tv, int role = Qt::DisplayRole) const; // selected index for a combobox // -- cgit v1.3.1 From 3d176cf01e402897c7ab880170dbe0d0b11292c4 Mon Sep 17 00:00:00 2001 From: Mikaël Capelle Date: Sun, 3 Jan 2021 11:59:27 +0100 Subject: Reorganizer ModList filters. --- src/CMakeLists.txt | 6 +++--- src/mainwindow.cpp | 1 - 2 files changed, 3 insertions(+), 4 deletions(-) (limited to 'src/mainwindow.cpp') diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index da317309..663ebcbc 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -142,12 +142,12 @@ add_filter(NAME src/modlist GROUPS modlistdropinfo modlistsortproxy modlistbypriorityproxy +) + +add_filter(NAME src/modlist/view GROUPS modlistview modlistviewactions modlistcontextmenu -) - -add_filter(NAME src/delegates GROUPS modflagicondelegate modconflicticondelegate ) diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 2b2685c4..ee25fc61 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -44,7 +44,6 @@ along with Mod Organizer. If not, see . #include "editexecutablesdialog.h" #include "categories.h" #include "categoriesdialog.h" -#include "genericicondelegate.h" #include "overwriteinfodialog.h" #include "downloadlist.h" #include "downloadlistwidget.h" -- cgit v1.3.1