adopt changes from #497 remapped

This commit is contained in:
Ryan Cao
2022-05-08 15:22:50 +08:00
parent ae1aa6f63e
commit 22f5128e39
13 changed files with 261 additions and 378 deletions

View File

@ -21,7 +21,8 @@ auto ListModel::debugName() const -> QString
void ListModel::fetchMore(const QModelIndex& parent)
{
if (parent.isValid()) return;
if (parent.isValid())
return;
if (nextSearchOffset == 0) {
qWarning() << "fetchMore with 0 offset is wrong...";
return;
@ -32,7 +33,9 @@ void ListModel::fetchMore(const QModelIndex& parent)
auto ListModel::data(const QModelIndex& index, int role) const -> QVariant
{
int pos = index.row();
if (pos >= modpacks.size() || pos < 0 || !index.isValid()) { return QString("INVALID INDEX %1").arg(pos); }
if (pos >= modpacks.size() || pos < 0 || !index.isValid()) {
return QString("INVALID INDEX %1").arg(pos);
}
ModPlatform::IndexedPack pack = modpacks.at(pos);
if (role == Qt::DisplayRole) {
@ -46,7 +49,9 @@ auto ListModel::data(const QModelIndex& index, int role) const -> QVariant
}
return pack.description;
} else if (role == Qt::DecorationRole) {
if (m_logoMap.contains(pack.logoName)) { return (m_logoMap.value(pack.logoName)); }
if (m_logoMap.contains(pack.logoName)) {
return (m_logoMap.value(pack.logoName));
}
QIcon icon = APPLICATION->getThemedIcon("screenshot-placeholder");
((ListModel*)this)->requestLogo(pack.logoName, pack.logoUrl);
return icon;
@ -63,16 +68,15 @@ void ListModel::requestModVersions(ModPlatform::IndexedPack const& current)
{
auto profile = (dynamic_cast<MinecraftInstance*>((dynamic_cast<ModPage*>(parent()))->m_instance))->getPackProfile();
m_parent->apiProvider()->getVersions(this,
{ current.addonId.toString(), getMineVersions(), profile->getModLoader() });
m_parent->apiProvider()->getVersions(this, { current.addonId.toString(), getMineVersions(), profile->getModLoader() });
}
void ListModel::performPaginatedSearch()
{
auto profile = (dynamic_cast<MinecraftInstance*>((dynamic_cast<ModPage*>(parent()))->m_instance))->getPackProfile();
m_parent->apiProvider()->searchMods(this,
{ nextSearchOffset, currentSearchTerm, getSorts()[currentSort], profile->getModLoader(), getMineVersions() });
m_parent->apiProvider()->searchMods(
this, { nextSearchOffset, currentSearchTerm, getSorts()[currentSort], profile->getModLoader(), getMineVersions() });
}
void ListModel::refresh()
@ -93,11 +97,9 @@ void ListModel::refresh()
void ListModel::searchWithTerm(const QString& term, const int sort, const bool filter_changed)
{
if (currentSearchTerm == term
&& currentSearchTerm.isNull() == term.isNull()
&& currentSort == sort
&& !filter_changed)
{ return; }
if (currentSearchTerm == term && currentSearchTerm.isNull() == term.isNull() && currentSort == sort && !filter_changed) {
return;
}
currentSearchTerm = term;
currentSort = sort;
@ -118,7 +120,9 @@ void ListModel::getLogo(const QString& logo, const QString& logoUrl, LogoCallbac
void ListModel::requestLogo(QString logo, QString url)
{
if (m_loadingLogos.contains(logo) || m_failedLogos.contains(logo)) { return; }
if (m_loadingLogos.contains(logo) || m_failedLogos.contains(logo)) {
return;
}
MetaEntryPtr entry =
APPLICATION->metacache()->resolveEntry(m_parent->metaEntryBase(), QString("logos/%1").arg(logo.section(".", 0, 0)));
@ -129,7 +133,9 @@ void ListModel::requestLogo(QString logo, QString url)
QObject::connect(job, &NetJob::succeeded, this, [this, logo, fullPath, job] {
job->deleteLater();
emit logoLoaded(logo, QIcon(fullPath));
if (waitingCallbacks.contains(logo)) { waitingCallbacks.value(logo)(fullPath); }
if (waitingCallbacks.contains(logo)) {
waitingCallbacks.value(logo)(fullPath);
}
});
QObject::connect(job, &NetJob::failed, this, [this, logo, job] {
@ -148,7 +154,9 @@ void ListModel::logoLoaded(QString logo, QIcon out)
m_loadingLogos.removeAll(logo);
m_logoMap.insert(logo, out);
for (int i = 0; i < modpacks.size(); i++) {
if (modpacks[i].logoName == logo) { emit dataChanged(createIndex(i, 0), createIndex(i, 0), { Qt::DecorationRole }); }
if (modpacks[i].logoName == logo) {
emit dataChanged(createIndex(i, 0), createIndex(i, 0), { Qt::DecorationRole });
}
}
}
@ -199,7 +207,9 @@ void ListModel::searchRequestFailed(QString reason)
// 409 Gone, notify user to update
QMessageBox::critical(nullptr, tr("Error"),
//: %1 refers to the launcher itself
QString("%1 %2").arg(m_parent->displayName()).arg(tr("API version too old!\nPlease update %1!").arg(BuildConfig.LAUNCHER_NAME)));
QString("%1 %2")
.arg(m_parent->displayName())
.arg(tr("API version too old!\nPlease update %1!").arg(BuildConfig.LAUNCHER_NAME)));
}
jobPtr.reset();
@ -218,9 +228,12 @@ void ListModel::searchRequestFailed(QString reason)
void ListModel::versionRequestSucceeded(QJsonDocument doc, QString addonId)
{
auto& current = m_parent->getCurrent();
if (addonId != current.addonId) { return; }
if (addonId != current.addonId) {
return;
}
auto arr = doc.isObject() ? Json::ensureArray(doc.object(), "data") : doc.array();
QJsonArray arr = doc.array();
try {
loadIndexedPackVersions(current, arr);
} catch (const JSONValidationError& e) {

View File

@ -1,5 +1,5 @@
#include "FlameModModel.h"
#include "Json.h"
#include "modplatform/flame/FlameModIndex.h"
namespace FlameMod {
@ -19,7 +19,7 @@ void ListModel::loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJsonArray&
auto ListModel::documentToArray(QJsonDocument& obj) const -> QJsonArray
{
return obj.array();
return Json::ensureArray(obj.object(), "data");
}
} // namespace FlameMod

View File

@ -1,6 +1,6 @@
#include "FlameModel.h"
#include "Application.h"
#include <Json.h>
#include "Application.h"
#include <MMCStrings.h>
#include <Version.h>
@ -9,61 +9,46 @@
namespace Flame {
ListModel::ListModel(QObject *parent) : QAbstractListModel(parent)
{
}
ListModel::ListModel(QObject* parent) : QAbstractListModel(parent) {}
ListModel::~ListModel()
{
}
ListModel::~ListModel() {}
int ListModel::rowCount(const QModelIndex &parent) const
int ListModel::rowCount(const QModelIndex& parent) const
{
return modpacks.size();
}
int ListModel::columnCount(const QModelIndex &parent) const
int ListModel::columnCount(const QModelIndex& parent) const
{
return 1;
}
QVariant ListModel::data(const QModelIndex &index, int role) const
QVariant ListModel::data(const QModelIndex& index, int role) const
{
int pos = index.row();
if(pos >= modpacks.size() || pos < 0 || !index.isValid())
{
if (pos >= modpacks.size() || pos < 0 || !index.isValid()) {
return QString("INVALID INDEX %1").arg(pos);
}
IndexedPack pack = modpacks.at(pos);
if(role == Qt::DisplayRole)
{
if (role == Qt::DisplayRole) {
return pack.name;
}
else if (role == Qt::ToolTipRole)
{
if(pack.description.length() > 100)
{
//some magic to prevent to long tooltips and replace html linebreaks
} else if (role == Qt::ToolTipRole) {
if (pack.description.length() > 100) {
// some magic to prevent to long tooltips and replace html linebreaks
QString edit = pack.description.left(97);
edit = edit.left(edit.lastIndexOf("<br>")).left(edit.lastIndexOf(" ")).append("...");
return edit;
}
return pack.description;
}
else if(role == Qt::DecorationRole)
{
if(m_logoMap.contains(pack.logoName))
{
} else if (role == Qt::DecorationRole) {
if (m_logoMap.contains(pack.logoName)) {
return (m_logoMap.value(pack.logoName));
}
QIcon icon = APPLICATION->getThemedIcon("screenshot-placeholder");
((ListModel *)this)->requestLogo(pack.logoName, pack.logoUrl);
((ListModel*)this)->requestLogo(pack.logoName, pack.logoUrl);
return icon;
}
else if(role == Qt::UserRole)
{
} else if (role == Qt::UserRole) {
QVariant v;
v.setValue(pack);
return v;
@ -76,9 +61,9 @@ void ListModel::logoLoaded(QString logo, QIcon out)
{
m_loadingLogos.removeAll(logo);
m_logoMap.insert(logo, out);
for(int i = 0; i < modpacks.size(); i++) {
if(modpacks[i].logoName == logo) {
emit dataChanged(createIndex(i, 0), createIndex(i, 0), {Qt::DecorationRole});
for (int i = 0; i < modpacks.size(); i++) {
if (modpacks[i].logoName == logo) {
emit dataChanged(createIndex(i, 0), createIndex(i, 0), { Qt::DecorationRole });
}
}
}
@ -91,8 +76,7 @@ void ListModel::logoFailed(QString logo)
void ListModel::requestLogo(QString logo, QString url)
{
if(m_loadingLogos.contains(logo) || m_failedLogos.contains(logo))
{
if (m_loadingLogos.contains(logo) || m_failedLogos.contains(logo)) {
return;
}
@ -101,18 +85,15 @@ void ListModel::requestLogo(QString logo, QString url)
job->addNetAction(Net::Download::makeCached(QUrl(url), entry));
auto fullPath = entry->getFullPath();
QObject::connect(job, &NetJob::succeeded, this, [this, logo, fullPath, job]
{
QObject::connect(job, &NetJob::succeeded, this, [this, logo, fullPath, job] {
job->deleteLater();
emit logoLoaded(logo, QIcon(fullPath));
if(waitingCallbacks.contains(logo))
{
if (waitingCallbacks.contains(logo)) {
waitingCallbacks.value(logo)(fullPath);
}
});
QObject::connect(job, &NetJob::failed, this, [this, logo, job]
{
QObject::connect(job, &NetJob::failed, this, [this, logo, job] {
job->deleteLater();
emit logoFailed(logo);
});
@ -122,19 +103,16 @@ void ListModel::requestLogo(QString logo, QString url)
m_loadingLogos.append(logo);
}
void ListModel::getLogo(const QString &logo, const QString &logoUrl, LogoCallback callback)
void ListModel::getLogo(const QString& logo, const QString& logoUrl, LogoCallback callback)
{
if(m_logoMap.contains(logo))
{
if (m_logoMap.contains(logo)) {
callback(APPLICATION->metacache()->resolveEntry("FlamePacks", QString("logos/%1").arg(logo.section(".", 0, 0)))->getFullPath());
}
else
{
} else {
requestLogo(logo, logoUrl);
}
}
Qt::ItemFlags ListModel::flags(const QModelIndex &index) const
Qt::ItemFlags ListModel::flags(const QModelIndex& index) const
{
return QAbstractListModel::flags(index);
}
@ -148,7 +126,7 @@ void ListModel::fetchMore(const QModelIndex& parent)
{
if (parent.isValid())
return;
if(nextSearchOffset == 0) {
if (nextSearchOffset == 0) {
qWarning() << "fetchMore with 0 offset is wrong...";
return;
}
@ -157,17 +135,20 @@ void ListModel::fetchMore(const QModelIndex& parent)
void ListModel::performPaginatedSearch()
{
NetJob *netJob = new NetJob("Flame::Search", APPLICATION->network());
NetJob* netJob = new NetJob("Flame::Search", APPLICATION->network());
auto searchUrl = QString(
"https://addons-ecs.forgesvc.net/api/v2/addon/search?"
"categoryId=0&"
"gameId=432&"
"index=%1&"
"pageSize=25&"
"searchFilter=%2&"
"sectionId=4471&"
"sort=%3"
).arg(nextSearchOffset).arg(currentSearchTerm).arg(currentSort);
"https://api.curseforge.com/v1/mods/search?"
"gameId=432&"
"classId=4471&"
"index=%1&"
"pageSize=25&"
"searchFilter=%2&"
"sortField=%3&"
"sortOrder=desc")
.arg(nextSearchOffset)
.arg(currentSearchTerm)
.arg(currentSort + 1);
netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchUrl), &response));
jobPtr = netJob;
jobPtr->start();
@ -177,17 +158,16 @@ void ListModel::performPaginatedSearch()
void ListModel::searchWithTerm(const QString& term, int sort)
{
if(currentSearchTerm == term && currentSearchTerm.isNull() == term.isNull() && currentSort == sort) {
if (currentSearchTerm == term && currentSearchTerm.isNull() == term.isNull() && currentSort == sort) {
return;
}
currentSearchTerm = term;
currentSort = sort;
if(jobPtr) {
if (jobPtr) {
jobPtr->abort();
searchState = ResetRequested;
return;
}
else {
} else {
beginResetModel();
modpacks.clear();
endResetModel();
@ -203,30 +183,28 @@ void Flame::ListModel::searchRequestFinished()
QJsonParseError parse_error;
QJsonDocument doc = QJsonDocument::fromJson(response, &parse_error);
if(parse_error.error != QJsonParseError::NoError) {
qWarning() << "Error while parsing JSON response from CurseForge at " << parse_error.offset << " reason: " << parse_error.errorString();
if (parse_error.error != QJsonParseError::NoError) {
qWarning() << "Error while parsing JSON response from CurseForge at " << parse_error.offset
<< " reason: " << parse_error.errorString();
qWarning() << response;
return;
}
QList<Flame::IndexedPack> newList;
auto packs = doc.array();
for(auto packRaw : packs) {
auto packs = Json::ensureArray(doc.object(), "data");
for (auto packRaw : packs) {
auto packObj = packRaw.toObject();
Flame::IndexedPack pack;
try
{
try {
Flame::loadIndexedPack(pack, packObj);
newList.append(pack);
}
catch(const JSONValidationError &e)
{
} catch (const JSONValidationError& e) {
qWarning() << "Error while loading pack from CurseForge: " << e.cause();
continue;
}
}
if(packs.size() < 25) {
if (packs.size() < 25) {
searchState = Finished;
} else {
nextSearchOffset += 25;
@ -241,7 +219,7 @@ void Flame::ListModel::searchRequestFailed(QString reason)
{
jobPtr.reset();
if(searchState == ResetRequested) {
if (searchState == ResetRequested) {
beginResetModel();
modpacks.clear();
endResetModel();
@ -253,5 +231,4 @@ void Flame::ListModel::searchRequestFailed(QString reason)
}
}
}
} // namespace Flame

View File

@ -39,13 +39,12 @@
#include <QKeyEvent>
#include "Application.h"
#include "FlameModel.h"
#include "InstanceImportTask.h"
#include "Json.h"
#include "ui/dialogs/NewInstanceDialog.h"
#include "InstanceImportTask.h"
#include "FlameModel.h"
FlamePage::FlamePage(NewInstanceDialog* dialog, QWidget *parent)
: QWidget(parent), ui(new Ui::FlamePage), dialog(dialog)
FlamePage::FlamePage(NewInstanceDialog* dialog, QWidget* parent) : QWidget(parent), ui(new Ui::FlamePage), dialog(dialog)
{
ui->setupUi(this);
connect(ui->searchButton, &QPushButton::clicked, this, &FlamePage::triggerSearch);
@ -112,10 +111,8 @@ void FlamePage::onSelectionChanged(QModelIndex first, QModelIndex second)
{
ui->versionSelectionBox->clear();
if(!first.isValid())
{
if(isOpened)
{
if (!first.isValid()) {
if (isOpened) {
dialog->setSuggestedPack();
}
return;
@ -130,14 +127,14 @@ void FlamePage::onSelectionChanged(QModelIndex first, QModelIndex second)
else
text = "<a href=\"" + current.websiteUrl + "\">" + name + "</a>";
if (!current.authors.empty()) {
auto authorToStr = [](Flame::ModpackAuthor & author) {
if(author.url.isEmpty()) {
auto authorToStr = [](Flame::ModpackAuthor& author) {
if (author.url.isEmpty()) {
return author.name;
}
return QString("<a href=\"%1\">%2</a>").arg(author.url, author.name);
};
QStringList authorStrs;
for(auto & author: current.authors) {
for (auto& author : current.authors) {
authorStrs.push_back(authorToStr(author));
}
text += "<br>" + tr(" by ") + authorStrs.join(", ");
@ -146,53 +143,46 @@ void FlamePage::onSelectionChanged(QModelIndex first, QModelIndex second)
ui->packDescription->setHtml(text + current.description);
if (current.versionsLoaded == false)
{
if (current.versionsLoaded == false) {
qDebug() << "Loading flame modpack versions";
auto netJob = new NetJob(QString("Flame::PackVersions(%1)").arg(current.name), APPLICATION->network());
auto response = new QByteArray();
int addonId = current.addonId;
netJob->addNetAction(Net::Download::makeByteArray(QString("https://addons-ecs.forgesvc.net/api/v2/addon/%1/files").arg(addonId), response));
netJob->addNetAction(Net::Download::makeByteArray(QString("https://api.curseforge.com/v1/mods/%1/files").arg(addonId), response));
QObject::connect(netJob, &NetJob::succeeded, this, [this, response, addonId]
{
if(addonId != current.addonId){
return; //wrong request
QObject::connect(netJob, &NetJob::succeeded, this, [this, response, addonId] {
if (addonId != current.addonId) {
return; // wrong request
}
QJsonParseError parse_error;
QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error);
if(parse_error.error != QJsonParseError::NoError) {
qWarning() << "Error while parsing JSON response from CurseForge at " << parse_error.offset << " reason: " << parse_error.errorString();
if (parse_error.error != QJsonParseError::NoError) {
qWarning() << "Error while parsing JSON response from CurseForge at " << parse_error.offset
<< " reason: " << parse_error.errorString();
qWarning() << *response;
return;
}
QJsonArray arr = doc.array();
try
{
auto arr = Json::ensureArray(doc.object(), "data");
try {
Flame::loadIndexedPackVersions(current, arr);
}
catch(const JSONValidationError &e)
{
} catch (const JSONValidationError& e) {
qDebug() << *response;
qWarning() << "Error while reading flame modpack version: " << e.cause();
}
for(auto version : current.versions) {
for (auto version : current.versions) {
ui->versionSelectionBox->addItem(version.version, QVariant(version.downloadUrl));
}
suggestCurrent();
});
QObject::connect(netJob, &NetJob::finished, this, [response, netJob]
{
QObject::connect(netJob, &NetJob::finished, this, [response, netJob] {
netJob->deleteLater();
delete response;
});
netJob->start();
}
else
{
for(auto version : current.versions) {
} else {
for (auto version : current.versions) {
ui->versionSelectionBox->addItem(version.version, QVariant(version.downloadUrl));
}
@ -202,13 +192,11 @@ void FlamePage::onSelectionChanged(QModelIndex first, QModelIndex second)
void FlamePage::suggestCurrent()
{
if(!isOpened)
{
if (!isOpened) {
return;
}
if (selectedVersion.isEmpty())
{
if (selectedVersion.isEmpty()) {
dialog->setSuggestedPack();
return;
}
@ -216,16 +204,13 @@ void FlamePage::suggestCurrent()
dialog->setSuggestedPack(current.name, new InstanceImportTask(selectedVersion));
QString editedLogoName;
editedLogoName = "curseforge_" + current.logoName.section(".", 0, 0);
listModel->getLogo(current.logoName, current.logoUrl, [this, editedLogoName](QString logo)
{
dialog->setSuggestedIconFromFile(logo, editedLogoName);
});
listModel->getLogo(current.logoName, current.logoUrl,
[this, editedLogoName](QString logo) { dialog->setSuggestedIconFromFile(logo, editedLogoName); });
}
void FlamePage::onVersionSelectionChanged(QString data)
{
if(data.isNull() || data.isEmpty())
{
if (data.isNull() || data.isEmpty()) {
selectedVersion = "";
return;
}