Merge branch 'develop' of https://github.com/PrismLauncher/PrismLauncher into visit_mod_page
This commit is contained in:
commit
54d7477679
@ -362,6 +362,8 @@ set(MINECRAFT_SOURCES
|
||||
minecraft/mod/tasks/LocalWorldSaveParseTask.cpp
|
||||
minecraft/mod/tasks/LocalResourceParse.h
|
||||
minecraft/mod/tasks/LocalResourceParse.cpp
|
||||
minecraft/mod/tasks/GetModDependenciesTask.h
|
||||
minecraft/mod/tasks/GetModDependenciesTask.cpp
|
||||
|
||||
# Assets
|
||||
minecraft/AssetsUtils.h
|
||||
|
@ -3,6 +3,8 @@
|
||||
#include <QCoreApplication>
|
||||
#include <QPixmapCache>
|
||||
#include <QThread>
|
||||
#include <QTime>
|
||||
#include <QDebug>
|
||||
|
||||
#define GET_TYPE() \
|
||||
Qt::ConnectionType type; \
|
||||
@ -60,6 +62,8 @@ class PixmapCache final : public QObject {
|
||||
DEFINE_FUNC_ONE_PARAM(remove, bool, const QPixmapCache::Key&)
|
||||
DEFINE_FUNC_TWO_PARAM(replace, bool, const QPixmapCache::Key&, const QPixmap&)
|
||||
DEFINE_FUNC_ONE_PARAM(setCacheLimit, bool, int)
|
||||
DEFINE_FUNC_NO_PARAM(markCacheMissByEviciton, bool)
|
||||
DEFINE_FUNC_ONE_PARAM(setFastEvictionThreshold, bool, int)
|
||||
|
||||
// NOTE: Every function returns something non-void to simplify the macros.
|
||||
private slots:
|
||||
@ -90,6 +94,43 @@ class PixmapCache final : public QObject {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark that a cache miss occurred because of a eviction if too many of these occur too fast the cache size is increased
|
||||
* @return if the cache size was increased
|
||||
*/
|
||||
bool _markCacheMissByEviciton()
|
||||
{
|
||||
auto now = QTime::currentTime();
|
||||
if (!m_last_cache_miss_by_eviciton.isNull()) {
|
||||
auto diff = m_last_cache_miss_by_eviciton.msecsTo(now);
|
||||
if (diff < 1000) { // less than a second ago
|
||||
++m_consecutive_fast_evicitons;
|
||||
} else {
|
||||
m_consecutive_fast_evicitons = 0;
|
||||
}
|
||||
}
|
||||
m_last_cache_miss_by_eviciton = now;
|
||||
if (m_consecutive_fast_evicitons >= m_consecutive_fast_evicitons_threshold) {
|
||||
// double the cache size
|
||||
auto newSize = _cacheLimit() * 2;
|
||||
qDebug() << m_consecutive_fast_evicitons << "pixmap cache misses by eviction happened too fast, doubling cache size to"
|
||||
<< newSize;
|
||||
_setCacheLimit(newSize);
|
||||
m_consecutive_fast_evicitons = 0;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool _setFastEvictionThreshold(int threshold)
|
||||
{
|
||||
m_consecutive_fast_evicitons_threshold = threshold;
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
static PixmapCache* s_instance;
|
||||
QTime m_last_cache_miss_by_eviciton;
|
||||
int m_consecutive_fast_evicitons = 0;
|
||||
int m_consecutive_fast_evicitons_threshold = 15;
|
||||
};
|
||||
|
@ -38,6 +38,8 @@ class ResourceDownloadTask : public SequentialTask {
|
||||
const QString& getFilename() const { return m_pack_version.fileName; }
|
||||
const QString& getCustomPath() const { return m_custom_target_folder; }
|
||||
const QVariant& getVersionID() const { return m_pack_version.fileId; }
|
||||
const ModPlatform::IndexedVersion& getVersion() const { return m_pack_version; }
|
||||
const ModPlatform::ResourceProvider& getProvider() const { return m_pack->provider; }
|
||||
const QString& getName() const { return m_pack->name; }
|
||||
ModPlatform::IndexedPack::Ptr getPack() { return m_pack; }
|
||||
|
||||
|
@ -85,7 +85,7 @@ void JavaChecker::performCheck()
|
||||
process->setProgram(m_path);
|
||||
process->setProcessChannelMode(QProcess::SeparateChannels);
|
||||
process->setProcessEnvironment(CleanEnviroment());
|
||||
qDebug() << "Running java checker: " + m_path + args.join(" ");;
|
||||
qDebug() << "Running java checker:" << m_path << args.join(" ");
|
||||
|
||||
connect(process.get(), QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &JavaChecker::finished);
|
||||
connect(process.get(), &QProcess::errorOccurred, this, &JavaChecker::error);
|
||||
|
@ -41,9 +41,11 @@
|
||||
#include <QString>
|
||||
#include <QRegularExpression>
|
||||
|
||||
#include "MTPixmapCache.h"
|
||||
#include "MetadataHandler.h"
|
||||
#include "Version.h"
|
||||
#include "minecraft/mod/ModDetails.h"
|
||||
#include "minecraft/mod/tasks/LocalModParseTask.h"
|
||||
|
||||
static ModPlatform::ProviderCapabilities ProviderCaps;
|
||||
|
||||
@ -201,7 +203,10 @@ void Mod::finishResolvingWithDetails(ModDetails&& details)
|
||||
m_local_details = std::move(details);
|
||||
if (metadata)
|
||||
setMetadata(std::move(metadata));
|
||||
};
|
||||
if (!iconPath().isEmpty()) {
|
||||
m_pack_image_cache_key.was_read_attempt = false;
|
||||
}
|
||||
}
|
||||
|
||||
auto Mod::provider() const -> std::optional<QString>
|
||||
{
|
||||
@ -210,6 +215,56 @@ auto Mod::provider() const -> std::optional<QString>
|
||||
return {};
|
||||
}
|
||||
|
||||
auto Mod::licenses() const -> const QList<ModLicense>&
|
||||
{
|
||||
return details().licenses;
|
||||
}
|
||||
|
||||
auto Mod::issueTracker() const -> QString
|
||||
{
|
||||
return details().issue_tracker;
|
||||
}
|
||||
|
||||
void Mod::setIcon(QImage new_image) const
|
||||
{
|
||||
QMutexLocker locker(&m_data_lock);
|
||||
|
||||
Q_ASSERT(!new_image.isNull());
|
||||
|
||||
if (m_pack_image_cache_key.key.isValid())
|
||||
PixmapCache::remove(m_pack_image_cache_key.key);
|
||||
|
||||
// scale the image to avoid flooding the pixmapcache
|
||||
auto pixmap = QPixmap::fromImage(new_image.scaled({64, 64}, Qt::AspectRatioMode::KeepAspectRatioByExpanding));
|
||||
|
||||
m_pack_image_cache_key.key = PixmapCache::insert(pixmap);
|
||||
m_pack_image_cache_key.was_ever_used = true;
|
||||
m_pack_image_cache_key.was_read_attempt = true;
|
||||
}
|
||||
|
||||
QPixmap Mod::icon(QSize size, Qt::AspectRatioMode mode) const
|
||||
{
|
||||
QPixmap cached_image;
|
||||
if (PixmapCache::find(m_pack_image_cache_key.key, &cached_image)) {
|
||||
if (size.isNull())
|
||||
return cached_image;
|
||||
return cached_image.scaled(size, mode);
|
||||
}
|
||||
|
||||
// No valid image we can get
|
||||
if ((!m_pack_image_cache_key.was_ever_used && m_pack_image_cache_key.was_read_attempt) || iconPath().isEmpty())
|
||||
return {};
|
||||
|
||||
if (m_pack_image_cache_key.was_ever_used) {
|
||||
qDebug() << "Mod" << name() << "Had it's icon evicted form the cache. reloading...";
|
||||
PixmapCache::markCacheMissByEviciton();
|
||||
}
|
||||
// Image got evicted from the cache or an attempt to load it has not been made. load it and retry.
|
||||
m_pack_image_cache_key.was_read_attempt = true;
|
||||
ModUtils::loadIconFile(*this);
|
||||
return icon(size);
|
||||
}
|
||||
|
||||
bool Mod::valid() const
|
||||
{
|
||||
return !m_local_details.mod_id.isEmpty();
|
||||
|
@ -38,6 +38,10 @@
|
||||
#include <QDateTime>
|
||||
#include <QFileInfo>
|
||||
#include <QList>
|
||||
#include <QImage>
|
||||
#include <QMutex>
|
||||
#include <QPixmap>
|
||||
#include <QPixmapCache>
|
||||
|
||||
#include <optional>
|
||||
|
||||
@ -64,6 +68,15 @@ public:
|
||||
auto authors() const -> QStringList;
|
||||
auto status() const -> ModStatus;
|
||||
auto provider() const -> std::optional<QString>;
|
||||
auto licenses() const -> const QList<ModLicense>&;
|
||||
auto issueTracker() const -> QString;
|
||||
|
||||
/** Get the intneral path to the mod's icon file*/
|
||||
QString iconPath() const { return m_local_details.icon_file; };
|
||||
/** Gets the icon of the mod, converted to a QPixmap for drawing, and scaled to size. */
|
||||
[[nodiscard]] QPixmap icon(QSize size, Qt::AspectRatioMode mode = Qt::AspectRatioMode::IgnoreAspectRatio) const;
|
||||
/** Thread-safe. */
|
||||
void setIcon(QImage new_image) const;
|
||||
|
||||
auto metadata() -> std::shared_ptr<Metadata::ModStruct>;
|
||||
auto metadata() const -> const std::shared_ptr<Metadata::ModStruct>;
|
||||
@ -85,4 +98,13 @@ public:
|
||||
|
||||
protected:
|
||||
ModDetails m_local_details;
|
||||
|
||||
mutable QMutex m_data_lock;
|
||||
|
||||
struct {
|
||||
QPixmapCache::Key key;
|
||||
bool was_ever_used = false;
|
||||
bool was_read_attempt = false;
|
||||
} mutable m_pack_image_cache_key;
|
||||
|
||||
};
|
||||
|
@ -39,6 +39,7 @@
|
||||
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QUrl>
|
||||
|
||||
#include "minecraft/mod/MetadataHandler.h"
|
||||
|
||||
@ -49,6 +50,84 @@ enum class ModStatus {
|
||||
Unknown, // Default status
|
||||
};
|
||||
|
||||
struct ModLicense {
|
||||
QString name = {};
|
||||
QString id = {};
|
||||
QString url = {};
|
||||
QString description = {};
|
||||
|
||||
ModLicense() {}
|
||||
|
||||
ModLicense(const QString license) {
|
||||
// FIXME: come up with a better license parseing.
|
||||
// handle SPDX identifiers? https://spdx.org/licenses/
|
||||
auto parts = license.split(' ');
|
||||
QStringList notNameParts = {};
|
||||
for (auto part : parts) {
|
||||
auto url = QUrl(part);
|
||||
if (part.startsWith("(") && part.endsWith(")"))
|
||||
url = QUrl(part.mid(1, part.size() - 2));
|
||||
|
||||
if (url.isValid() && !url.scheme().isEmpty() && !url.host().isEmpty()) {
|
||||
this->url = url.toString();
|
||||
notNameParts.append(part);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
for (auto part : notNameParts) {
|
||||
parts.removeOne(part);
|
||||
}
|
||||
|
||||
auto licensePart = parts.join(' ');
|
||||
this->name = licensePart;
|
||||
this->description = licensePart;
|
||||
|
||||
if (parts.size() == 1) {
|
||||
this->id = parts.first();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
ModLicense(const QString name, const QString id, const QString url, const QString description) {
|
||||
this->name = name;
|
||||
this->id = id;
|
||||
this->url = url;
|
||||
this->description = description;
|
||||
}
|
||||
|
||||
ModLicense(const ModLicense& other)
|
||||
: name(other.name)
|
||||
, id(other.id)
|
||||
, url(other.url)
|
||||
, description(other.description)
|
||||
{}
|
||||
|
||||
ModLicense& operator=(const ModLicense& other)
|
||||
{
|
||||
this->name = other.name;
|
||||
this->id = other.id;
|
||||
this->url = other.url;
|
||||
this->description = other.description;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
ModLicense& operator=(const ModLicense&& other)
|
||||
{
|
||||
this->name = other.name;
|
||||
this->id = other.id;
|
||||
this->url = other.url;
|
||||
this->description = other.description;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool isEmpty() {
|
||||
return this->name.isEmpty() && this->id.isEmpty() && this->url.isEmpty() && this->description.isEmpty();
|
||||
}
|
||||
};
|
||||
|
||||
struct ModDetails
|
||||
{
|
||||
/* Mod ID as defined in the ModLoader-specific metadata */
|
||||
@ -72,6 +151,15 @@ struct ModDetails
|
||||
/* List of the author's names */
|
||||
QStringList authors = {};
|
||||
|
||||
/* Issue Tracker URL */
|
||||
QString issue_tracker = {};
|
||||
|
||||
/* License */
|
||||
QList<ModLicense> licenses = {};
|
||||
|
||||
/* Path of mod logo */
|
||||
QString icon_file = {};
|
||||
|
||||
/* Installation status of the mod */
|
||||
ModStatus status = ModStatus::Unknown;
|
||||
|
||||
@ -89,6 +177,9 @@ struct ModDetails
|
||||
, homeurl(other.homeurl)
|
||||
, description(other.description)
|
||||
, authors(other.authors)
|
||||
, issue_tracker(other.issue_tracker)
|
||||
, licenses(other.licenses)
|
||||
, icon_file(other.icon_file)
|
||||
, status(other.status)
|
||||
{}
|
||||
|
||||
@ -101,6 +192,9 @@ struct ModDetails
|
||||
this->homeurl = other.homeurl;
|
||||
this->description = other.description;
|
||||
this->authors = other.authors;
|
||||
this->issue_tracker = other.issue_tracker;
|
||||
this->licenses = other.licenses;
|
||||
this->icon_file = other.icon_file;
|
||||
this->status = other.status;
|
||||
|
||||
return *this;
|
||||
@ -115,6 +209,9 @@ struct ModDetails
|
||||
this->homeurl = other.homeurl;
|
||||
this->description = other.description;
|
||||
this->authors = other.authors;
|
||||
this->issue_tracker = other.issue_tracker;
|
||||
this->licenses = other.licenses;
|
||||
this->icon_file = other.icon_file;
|
||||
this->status = other.status;
|
||||
|
||||
return *this;
|
||||
|
@ -37,6 +37,7 @@
|
||||
#include "ModFolderModel.h"
|
||||
|
||||
#include <FileSystem.h>
|
||||
#include <qheaderview.h>
|
||||
#include <QDebug>
|
||||
#include <QFileSystemWatcher>
|
||||
#include <QIcon>
|
||||
@ -52,12 +53,14 @@
|
||||
|
||||
#include "minecraft/mod/tasks/LocalModParseTask.h"
|
||||
#include "minecraft/mod/tasks/ModFolderLoadTask.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
|
||||
ModFolderModel::ModFolderModel(const QString& dir, BaseInstance* instance, bool is_indexed, bool create_dir)
|
||||
: ResourceFolderModel(QDir(dir), instance, nullptr, create_dir), m_is_indexed(is_indexed)
|
||||
{
|
||||
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::VERSION, SortType::DATE, SortType::PROVIDER };
|
||||
m_column_names = QStringList({ "Enable", "Image", "Name", "Version", "Last Modified", "Provider" });
|
||||
m_column_names_translated = QStringList({ tr("Enable"), tr("Image"), tr("Name"), tr("Version"), tr("Last Modified"), tr("Provider") });
|
||||
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME , SortType::VERSION, SortType::DATE, SortType::PROVIDER};
|
||||
m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::ResizeToContents, QHeaderView::ResizeToContents, QHeaderView::ResizeToContents};
|
||||
}
|
||||
|
||||
QVariant ModFolderModel::data(const QModelIndex &index, int role) const
|
||||
@ -118,7 +121,9 @@ QVariant ModFolderModel::data(const QModelIndex &index, int role) const
|
||||
case Qt::DecorationRole: {
|
||||
if (column == NAME_COLUMN && (at(row)->isSymLinkUnder(instDirPath()) || at(row)->isMoreThanOneHardLink()))
|
||||
return APPLICATION->getThemedIcon("status-yellow");
|
||||
|
||||
if (column == ImageColumn) {
|
||||
return at(row)->icon({32, 32}, Qt::AspectRatioMode::KeepAspectRatioByExpanding);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
case Qt::CheckStateRole:
|
||||
@ -142,15 +147,12 @@ QVariant ModFolderModel::headerData(int section, Qt::Orientation orientation, in
|
||||
switch (section)
|
||||
{
|
||||
case ActiveColumn:
|
||||
return QString();
|
||||
case NameColumn:
|
||||
return tr("Name");
|
||||
case VersionColumn:
|
||||
return tr("Version");
|
||||
case DateColumn:
|
||||
return tr("Last changed");
|
||||
case ProviderColumn:
|
||||
return tr("Provider");
|
||||
case ImageColumn:
|
||||
return columnNames().at(section);
|
||||
default:
|
||||
return QVariant();
|
||||
}
|
||||
|
@ -64,6 +64,7 @@ public:
|
||||
enum Columns
|
||||
{
|
||||
ActiveColumn = 0,
|
||||
ImageColumn,
|
||||
NameColumn,
|
||||
VersionColumn,
|
||||
DateColumn,
|
||||
@ -77,6 +78,8 @@ public:
|
||||
};
|
||||
ModFolderModel(const QString &dir, BaseInstance* instance, bool is_indexed = false, bool create_dir = true);
|
||||
|
||||
virtual QString id() const override { return "mods"; }
|
||||
|
||||
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
|
||||
|
||||
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
|
||||
|
@ -8,12 +8,15 @@
|
||||
#include <QStyle>
|
||||
#include <QThreadPool>
|
||||
#include <QUrl>
|
||||
#include <QMenu>
|
||||
|
||||
#include "Application.h"
|
||||
#include "FileSystem.h"
|
||||
|
||||
#include "QVariantUtils.h"
|
||||
#include "minecraft/mod/tasks/BasicFolderLoadTask.h"
|
||||
|
||||
#include "settings/Setting.h"
|
||||
#include "tasks/Task.h"
|
||||
|
||||
ResourceFolderModel::ResourceFolderModel(QDir dir, BaseInstance* instance, QObject* parent, bool create_dir)
|
||||
@ -471,10 +474,10 @@ QVariant ResourceFolderModel::headerData(int section, Qt::Orientation orientatio
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
switch (section) {
|
||||
case ACTIVE_COLUMN:
|
||||
case NAME_COLUMN:
|
||||
return tr("Name");
|
||||
case DATE_COLUMN:
|
||||
return tr("Last modified");
|
||||
return columnNames().at(section);
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
@ -500,6 +503,75 @@ QVariant ResourceFolderModel::headerData(int section, Qt::Orientation orientatio
|
||||
return {};
|
||||
}
|
||||
|
||||
void ResourceFolderModel::setupHeaderAction(QAction* act, int column)
|
||||
{
|
||||
Q_ASSERT(act);
|
||||
|
||||
act->setText(columnNames().at(column));
|
||||
}
|
||||
|
||||
void ResourceFolderModel::saveHiddenColumn(int column, bool hidden)
|
||||
{
|
||||
auto const setting_name = QString("UI/%1_Page/HiddenColumns").arg(id());
|
||||
auto setting = (m_instance->settings()->contains(setting_name)) ?
|
||||
m_instance->settings()->getSetting(setting_name) : m_instance->settings()->registerSetting(setting_name);
|
||||
|
||||
auto hiddenColumns = setting->get().toStringList();
|
||||
auto name = columnNames(false).at(column);
|
||||
auto index = hiddenColumns.indexOf(name);
|
||||
if (index >= 0 && !hidden) {
|
||||
hiddenColumns.removeAt(index);
|
||||
} else if ( index < 0 && hidden) {
|
||||
hiddenColumns.append(name);
|
||||
}
|
||||
setting->set(hiddenColumns);
|
||||
}
|
||||
|
||||
void ResourceFolderModel::loadHiddenColumns(QTreeView *tree)
|
||||
{
|
||||
auto const setting_name = QString("UI/%1_Page/HiddenColumns").arg(id());
|
||||
auto setting = (m_instance->settings()->contains(setting_name)) ?
|
||||
m_instance->settings()->getSetting(setting_name) : m_instance->settings()->registerSetting(setting_name);
|
||||
|
||||
auto hiddenColumns = setting->get().toStringList();
|
||||
auto col_names = columnNames(false);
|
||||
for (auto col_name : hiddenColumns) {
|
||||
auto index = col_names.indexOf(col_name);
|
||||
if (index >= 0)
|
||||
tree->setColumnHidden(index, true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
QMenu* ResourceFolderModel::createHeaderContextMenu(QTreeView* tree)
|
||||
{
|
||||
auto menu = new QMenu(tree);
|
||||
|
||||
menu->addSeparator()->setText(tr("Show / Hide Columns"));
|
||||
|
||||
for (int col = 0; col < columnCount(); ++col) {
|
||||
auto act = new QAction(menu);
|
||||
setupHeaderAction(act, col);
|
||||
|
||||
act->setCheckable(true);
|
||||
act->setChecked(!tree->isColumnHidden(col));
|
||||
|
||||
connect(act, &QAction::toggled, tree, [this, col, tree](bool toggled){
|
||||
tree->setColumnHidden(col, !toggled);
|
||||
for(int c = 0; c < columnCount(); ++c) {
|
||||
if (m_column_resize_modes.at(c) == QHeaderView::ResizeToContents)
|
||||
tree->resizeColumnToContents(c);
|
||||
}
|
||||
saveHiddenColumn(col, !toggled);
|
||||
});
|
||||
|
||||
menu->addAction(act);
|
||||
|
||||
}
|
||||
|
||||
return menu;
|
||||
}
|
||||
|
||||
QSortFilterProxyModel* ResourceFolderModel::createFilterProxyModel(QObject* parent)
|
||||
{
|
||||
return new ProxyModel(parent);
|
||||
|
@ -1,5 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include <QHeaderView>
|
||||
#include <QAction>
|
||||
#include <QTreeView>
|
||||
#include <QAbstractListModel>
|
||||
#include <QDir>
|
||||
#include <QFileSystemWatcher>
|
||||
@ -29,6 +32,8 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
ResourceFolderModel(QDir, BaseInstance* instance, QObject* parent = nullptr, bool create_dir = true);
|
||||
~ResourceFolderModel() override;
|
||||
|
||||
virtual QString id() const { return "resource"; }
|
||||
|
||||
/** Starts watching the paths for changes.
|
||||
*
|
||||
* Returns whether starting to watch all the paths was successful.
|
||||
@ -92,6 +97,7 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
|
||||
/* Basic columns */
|
||||
enum Columns { ACTIVE_COLUMN = 0, NAME_COLUMN, DATE_COLUMN, NUM_COLUMNS };
|
||||
QStringList columnNames(bool translated = true) const { return translated ? m_column_names_translated : m_column_names; };
|
||||
|
||||
[[nodiscard]] int rowCount(const QModelIndex& parent = {}) const override { return parent.isValid() ? 0 : static_cast<int>(size()); }
|
||||
[[nodiscard]] int columnCount(const QModelIndex& parent = {}) const override { return parent.isValid() ? 0 : NUM_COLUMNS; };
|
||||
@ -110,6 +116,11 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
|
||||
[[nodiscard]] QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
|
||||
|
||||
void setupHeaderAction(QAction* act, int column);
|
||||
void saveHiddenColumn(int column, bool hidden);
|
||||
void loadHiddenColumns(QTreeView* tree);
|
||||
QMenu* createHeaderContextMenu(QTreeView* tree);
|
||||
|
||||
/** This creates a proxy model to filter / sort the model for a UI.
|
||||
*
|
||||
* The actual comparisons and filtering are done directly by the Resource, so to modify behavior go there instead!
|
||||
@ -117,6 +128,7 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
QSortFilterProxyModel* createFilterProxyModel(QObject* parent = nullptr);
|
||||
|
||||
[[nodiscard]] SortType columnToSortKey(size_t column) const;
|
||||
[[nodiscard]] QList<QHeaderView::ResizeMode> columnResizeModes() const { return m_column_resize_modes; }
|
||||
|
||||
class ProxyModel : public QSortFilterProxyModel {
|
||||
public:
|
||||
@ -187,6 +199,9 @@ class ResourceFolderModel : public QAbstractListModel {
|
||||
// Represents the relationship between a column's index (represented by the list index), and it's sorting key.
|
||||
// As such, the order in with they appear is very important!
|
||||
QList<SortType> m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::DATE };
|
||||
QStringList m_column_names = {"Enable", "Name", "Last Modified"};
|
||||
QStringList m_column_names_translated = {tr("Enable"), tr("Name"), tr("Last Modified")};
|
||||
QList<QHeaderView::ResizeMode> m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Stretch, QHeaderView::ResizeToContents };
|
||||
|
||||
bool m_can_interact = true;
|
||||
|
||||
|
@ -40,7 +40,7 @@ void ResourcePack::setDescription(QString new_description)
|
||||
m_description = new_description;
|
||||
}
|
||||
|
||||
void ResourcePack::setImage(QImage new_image)
|
||||
void ResourcePack::setImage(QImage new_image) const
|
||||
{
|
||||
QMutexLocker locker(&m_data_lock);
|
||||
|
||||
@ -49,7 +49,10 @@ void ResourcePack::setImage(QImage new_image)
|
||||
if (m_pack_image_cache_key.key.isValid())
|
||||
PixmapCache::instance().remove(m_pack_image_cache_key.key);
|
||||
|
||||
m_pack_image_cache_key.key = PixmapCache::instance().insert(QPixmap::fromImage(new_image));
|
||||
// scale the image to avoid flooding the pixmapcache
|
||||
auto pixmap = QPixmap::fromImage(new_image.scaled({64, 64}, Qt::AspectRatioMode::KeepAspectRatioByExpanding));
|
||||
|
||||
m_pack_image_cache_key.key = PixmapCache::instance().insert(pixmap);
|
||||
m_pack_image_cache_key.was_ever_used = true;
|
||||
|
||||
// This can happen if the pixmap is too big to fit in the cache :c
|
||||
@ -59,21 +62,25 @@ void ResourcePack::setImage(QImage new_image)
|
||||
}
|
||||
}
|
||||
|
||||
QPixmap ResourcePack::image(QSize size)
|
||||
QPixmap ResourcePack::image(QSize size, Qt::AspectRatioMode mode) const
|
||||
{
|
||||
QPixmap cached_image;
|
||||
if (PixmapCache::instance().find(m_pack_image_cache_key.key, &cached_image)) {
|
||||
if (size.isNull())
|
||||
return cached_image;
|
||||
return cached_image.scaled(size);
|
||||
return cached_image.scaled(size, mode);
|
||||
}
|
||||
|
||||
// No valid image we can get
|
||||
if (!m_pack_image_cache_key.was_ever_used)
|
||||
if (!m_pack_image_cache_key.was_ever_used) {
|
||||
return {};
|
||||
} else {
|
||||
qDebug() << "Resource Pack" << name() << "Had it's image evicted from the cache. reloading...";
|
||||
PixmapCache::markCacheMissByEviciton();
|
||||
}
|
||||
|
||||
// Imaged got evicted from the cache. Re-process it and retry.
|
||||
ResourcePackUtils::process(*this);
|
||||
ResourcePackUtils::processPackPNG(*this);
|
||||
return image(size);
|
||||
}
|
||||
|
||||
|
@ -31,7 +31,7 @@ class ResourcePack : public Resource {
|
||||
[[nodiscard]] QString description() const { return m_description; }
|
||||
|
||||
/** Gets the image of the resource pack, converted to a QPixmap for drawing, and scaled to size. */
|
||||
[[nodiscard]] QPixmap image(QSize size);
|
||||
[[nodiscard]] QPixmap image(QSize size, Qt::AspectRatioMode mode = Qt::AspectRatioMode::IgnoreAspectRatio) const;
|
||||
|
||||
/** Thread-safe. */
|
||||
void setPackFormat(int new_format_id);
|
||||
@ -40,7 +40,7 @@ class ResourcePack : public Resource {
|
||||
void setDescription(QString new_description);
|
||||
|
||||
/** Thread-safe. */
|
||||
void setImage(QImage new_image);
|
||||
void setImage(QImage new_image) const;
|
||||
|
||||
bool valid() const override;
|
||||
|
||||
@ -67,5 +67,5 @@ class ResourcePack : public Resource {
|
||||
struct {
|
||||
QPixmapCache::Key key;
|
||||
bool was_ever_used = false;
|
||||
} m_pack_image_cache_key;
|
||||
} mutable m_pack_image_cache_key;
|
||||
};
|
||||
|
@ -35,6 +35,8 @@
|
||||
*/
|
||||
|
||||
#include "ResourcePackFolderModel.h"
|
||||
#include <qnamespace.h>
|
||||
#include <qsize.h>
|
||||
|
||||
#include <QIcon>
|
||||
#include <QStyle>
|
||||
@ -48,7 +50,11 @@
|
||||
ResourcePackFolderModel::ResourcePackFolderModel(const QString& dir, BaseInstance* instance)
|
||||
: ResourceFolderModel(QDir(dir), instance)
|
||||
{
|
||||
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::PACK_FORMAT, SortType::DATE };
|
||||
m_column_names = QStringList({ "Enable", "Image", "Name", "Pack Format", "Last Modified" });
|
||||
m_column_names_translated = QStringList({ tr("Enable"), tr("Image"), tr("Name"), tr("Pack Format"), tr("Last Modified") });
|
||||
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME, SortType::PACK_FORMAT, SortType::DATE};
|
||||
m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::ResizeToContents, QHeaderView::ResizeToContents };
|
||||
|
||||
}
|
||||
|
||||
QVariant ResourcePackFolderModel::data(const QModelIndex& index, int role) const
|
||||
@ -84,9 +90,11 @@ QVariant ResourcePackFolderModel::data(const QModelIndex& index, int role) const
|
||||
return {};
|
||||
}
|
||||
case Qt::DecorationRole: {
|
||||
if (column == NAME_COLUMN && (at(row)->isSymLinkUnder(instDirPath()) || at(row)->isMoreThanOneHardLink()))
|
||||
if (column == NameColumn && (at(row)->isSymLinkUnder(instDirPath()) || at(row)->isMoreThanOneHardLink()))
|
||||
return APPLICATION->getThemedIcon("status-yellow");
|
||||
|
||||
if (column == ImageColumn) {
|
||||
return at(row)->image({32, 32}, Qt::AspectRatioMode::KeepAspectRatioByExpanding);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
case Qt::ToolTipRole: {
|
||||
@ -94,7 +102,7 @@ QVariant ResourcePackFolderModel::data(const QModelIndex& index, int role) const
|
||||
//: The string being explained by this is in the format: ID (Lower version - Upper version)
|
||||
return tr("The resource pack format ID, as well as the Minecraft versions it was designed for.");
|
||||
}
|
||||
if (column == NAME_COLUMN) {
|
||||
if (column == NameColumn) {
|
||||
if (at(row)->isSymLinkUnder(instDirPath())) {
|
||||
return m_resources[row]->internal_id() +
|
||||
tr("\nWarning: This resource is symbolically linked from elsewhere. Editing it will also change the original."
|
||||
@ -126,13 +134,11 @@ QVariant ResourcePackFolderModel::headerData(int section, Qt::Orientation orient
|
||||
case Qt::DisplayRole:
|
||||
switch (section) {
|
||||
case ActiveColumn:
|
||||
return QString();
|
||||
case NameColumn:
|
||||
return tr("Name");
|
||||
case PackFormatColumn:
|
||||
return tr("Pack Format");
|
||||
case DateColumn:
|
||||
return tr("Last changed");
|
||||
case ImageColumn:
|
||||
return columnNames().at(section);
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
@ -151,6 +157,11 @@ QVariant ResourcePackFolderModel::headerData(int section, Qt::Orientation orient
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
case Qt::SizeHintRole:
|
||||
if (section == ImageColumn) {
|
||||
return QSize(64,0);
|
||||
}
|
||||
return {};
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
|
@ -11,6 +11,7 @@ public:
|
||||
enum Columns
|
||||
{
|
||||
ActiveColumn = 0,
|
||||
ImageColumn,
|
||||
NameColumn,
|
||||
PackFormatColumn,
|
||||
DateColumn,
|
||||
@ -19,6 +20,8 @@ public:
|
||||
|
||||
explicit ResourcePackFolderModel(const QString &dir, BaseInstance* instance);
|
||||
|
||||
virtual QString id() const override { return "resourcepacks"; }
|
||||
|
||||
[[nodiscard]] QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
|
||||
|
||||
[[nodiscard]] QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
|
||||
|
@ -9,4 +9,6 @@ class ShaderPackFolderModel : public ResourceFolderModel {
|
||||
explicit ShaderPackFolderModel(const QString& dir, BaseInstance* instance)
|
||||
: ResourceFolderModel(QDir(dir), instance)
|
||||
{}
|
||||
|
||||
virtual QString id() const override { return "shaderpacks"; }
|
||||
};
|
||||
|
@ -23,6 +23,8 @@
|
||||
#include <QMap>
|
||||
#include <QRegularExpression>
|
||||
|
||||
#include "MTPixmapCache.h"
|
||||
|
||||
#include "minecraft/mod/tasks/LocalTexturePackParseTask.h"
|
||||
|
||||
void TexturePack::setDescription(QString new_description)
|
||||
@ -32,34 +34,41 @@ void TexturePack::setDescription(QString new_description)
|
||||
m_description = new_description;
|
||||
}
|
||||
|
||||
void TexturePack::setImage(QImage new_image)
|
||||
void TexturePack::setImage(QImage new_image) const
|
||||
{
|
||||
QMutexLocker locker(&m_data_lock);
|
||||
|
||||
Q_ASSERT(!new_image.isNull());
|
||||
|
||||
if (m_pack_image_cache_key.key.isValid())
|
||||
QPixmapCache::remove(m_pack_image_cache_key.key);
|
||||
PixmapCache::remove(m_pack_image_cache_key.key);
|
||||
|
||||
m_pack_image_cache_key.key = QPixmapCache::insert(QPixmap::fromImage(new_image));
|
||||
// scale the image to avoid flooding the pixmapcache
|
||||
auto pixmap = QPixmap::fromImage(new_image.scaled({64, 64}, Qt::AspectRatioMode::KeepAspectRatioByExpanding));
|
||||
|
||||
m_pack_image_cache_key.key = PixmapCache::insert(pixmap);
|
||||
m_pack_image_cache_key.was_ever_used = true;
|
||||
}
|
||||
|
||||
QPixmap TexturePack::image(QSize size)
|
||||
QPixmap TexturePack::image(QSize size, Qt::AspectRatioMode mode) const
|
||||
{
|
||||
QPixmap cached_image;
|
||||
if (QPixmapCache::find(m_pack_image_cache_key.key, &cached_image)) {
|
||||
if (PixmapCache::find(m_pack_image_cache_key.key, &cached_image)) {
|
||||
if (size.isNull())
|
||||
return cached_image;
|
||||
return cached_image.scaled(size);
|
||||
return cached_image.scaled(size, mode);
|
||||
}
|
||||
|
||||
// No valid image we can get
|
||||
if (!m_pack_image_cache_key.was_ever_used)
|
||||
if (!m_pack_image_cache_key.was_ever_used) {
|
||||
return {};
|
||||
} else {
|
||||
qDebug() << "Texture Pack" << name() << "Had it's image evicted from the cache. reloading...";
|
||||
PixmapCache::markCacheMissByEviciton();
|
||||
}
|
||||
|
||||
// Imaged got evicted from the cache. Re-process it and retry.
|
||||
TexturePackUtils::process(*this);
|
||||
TexturePackUtils::processPackPNG(*this);
|
||||
return image(size);
|
||||
}
|
||||
|
||||
|
@ -40,13 +40,13 @@ class TexturePack : public Resource {
|
||||
[[nodiscard]] QString description() const { return m_description; }
|
||||
|
||||
/** Gets the image of the texture pack, converted to a QPixmap for drawing, and scaled to size. */
|
||||
[[nodiscard]] QPixmap image(QSize size);
|
||||
[[nodiscard]] QPixmap image(QSize size, Qt::AspectRatioMode mode = Qt::AspectRatioMode::IgnoreAspectRatio) const;
|
||||
|
||||
/** Thread-safe. */
|
||||
void setDescription(QString new_description);
|
||||
|
||||
/** Thread-safe. */
|
||||
void setImage(QImage new_image);
|
||||
void setImage(QImage new_image) const;
|
||||
|
||||
bool valid() const override;
|
||||
|
||||
@ -65,5 +65,5 @@ class TexturePack : public Resource {
|
||||
struct {
|
||||
QPixmapCache::Key key;
|
||||
bool was_ever_used = false;
|
||||
} m_pack_image_cache_key;
|
||||
} mutable m_pack_image_cache_key;
|
||||
};
|
||||
|
@ -33,6 +33,9 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
#include <QCoreApplication>
|
||||
|
||||
#include "Application.h"
|
||||
|
||||
#include "TexturePackFolderModel.h"
|
||||
|
||||
@ -41,7 +44,13 @@
|
||||
|
||||
TexturePackFolderModel::TexturePackFolderModel(const QString& dir, BaseInstance* instance)
|
||||
: ResourceFolderModel(QDir(dir), instance)
|
||||
{}
|
||||
{
|
||||
m_column_names = QStringList({ "Enable", "Image", "Name", "Last Modified" });
|
||||
m_column_names_translated = QStringList({ tr("Enable"), tr("Image"), tr("Name"), tr("Last Modified") });
|
||||
m_column_sort_keys = { SortType::ENABLED, SortType::NAME, SortType::NAME, SortType::DATE };
|
||||
m_column_resize_modes = { QHeaderView::ResizeToContents, QHeaderView::Interactive, QHeaderView::Stretch, QHeaderView::ResizeToContents};
|
||||
|
||||
}
|
||||
|
||||
Task* TexturePackFolderModel::createUpdateTask()
|
||||
{
|
||||
@ -52,3 +61,96 @@ Task* TexturePackFolderModel::createParseTask(Resource& resource)
|
||||
{
|
||||
return new LocalTexturePackParseTask(m_next_resolution_ticket, static_cast<TexturePack&>(resource));
|
||||
}
|
||||
|
||||
|
||||
QVariant TexturePackFolderModel::data(const QModelIndex& index, int role) const
|
||||
{
|
||||
if (!validateIndex(index))
|
||||
return {};
|
||||
|
||||
int row = index.row();
|
||||
int column = index.column();
|
||||
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
switch (column) {
|
||||
case NameColumn:
|
||||
return m_resources[row]->name();
|
||||
case DateColumn:
|
||||
return m_resources[row]->dateTimeChanged();
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
case Qt::ToolTipRole:
|
||||
if (column == NameColumn) {
|
||||
if (at(row)->isSymLinkUnder(instDirPath())) {
|
||||
return m_resources[row]->internal_id() +
|
||||
tr("\nWarning: This resource is symbolically linked from elsewhere. Editing it will also change the original."
|
||||
"\nCanonical Path: %1")
|
||||
.arg(at(row)->fileinfo().canonicalFilePath());;
|
||||
}
|
||||
if (at(row)->isMoreThanOneHardLink()) {
|
||||
return m_resources[row]->internal_id() +
|
||||
tr("\nWarning: This resource is hard linked elsewhere. Editing it will also change the original.");
|
||||
}
|
||||
}
|
||||
|
||||
return m_resources[row]->internal_id();
|
||||
case Qt::DecorationRole: {
|
||||
if (column == NameColumn && (at(row)->isSymLinkUnder(instDirPath()) || at(row)->isMoreThanOneHardLink()))
|
||||
return APPLICATION->getThemedIcon("status-yellow");
|
||||
if (column == ImageColumn) {
|
||||
return at(row)->image({32, 32}, Qt::AspectRatioMode::KeepAspectRatioByExpanding);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
case Qt::CheckStateRole:
|
||||
if (column == ActiveColumn) {
|
||||
return m_resources[row]->enabled() ? Qt::Checked : Qt::Unchecked;
|
||||
}
|
||||
return {};
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
QVariant TexturePackFolderModel::headerData(int section, Qt::Orientation orientation, int role) const
|
||||
{
|
||||
switch (role) {
|
||||
case Qt::DisplayRole:
|
||||
switch (section) {
|
||||
case ActiveColumn:
|
||||
case NameColumn:
|
||||
case DateColumn:
|
||||
case ImageColumn:
|
||||
return columnNames().at(section);
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
case Qt::ToolTipRole: {
|
||||
switch (section) {
|
||||
case ActiveColumn:
|
||||
//: Here, resource is a generic term for external resources, like Mods, Resource Packs, Shader Packs, etc.
|
||||
return tr("Is the resource enabled?");
|
||||
case NameColumn:
|
||||
//: Here, resource is a generic term for external resources, like Mods, Resource Packs, Shader Packs, etc.
|
||||
return tr("The name of the resource.");
|
||||
case DateColumn:
|
||||
//: Here, resource is a generic term for external resources, like Mods, Resource Packs, Shader Packs, etc.
|
||||
return tr("The date and time this resource was last changed (or added).");
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
int TexturePackFolderModel::columnCount(const QModelIndex& parent) const
|
||||
{
|
||||
return parent.isValid() ? 0 : NUM_COLUMNS;
|
||||
}
|
||||
|
||||
|
@ -38,12 +38,35 @@
|
||||
|
||||
#include "ResourceFolderModel.h"
|
||||
|
||||
#include "TexturePack.h"
|
||||
|
||||
class TexturePackFolderModel : public ResourceFolderModel
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
|
||||
enum Columns
|
||||
{
|
||||
ActiveColumn = 0,
|
||||
ImageColumn,
|
||||
NameColumn,
|
||||
DateColumn,
|
||||
NUM_COLUMNS
|
||||
};
|
||||
|
||||
explicit TexturePackFolderModel(const QString &dir, std::shared_ptr<const BaseInstance> instance);
|
||||
|
||||
virtual QString id() const override { return "texturepacks"; }
|
||||
|
||||
[[nodiscard]] QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
|
||||
|
||||
[[nodiscard]] QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
|
||||
[[nodiscard]] int columnCount(const QModelIndex &parent) const override;
|
||||
|
||||
explicit TexturePackFolderModel(const QString &dir, BaseInstance* instance);
|
||||
[[nodiscard]] Task* createUpdateTask() override;
|
||||
[[nodiscard]] Task* createParseTask(Resource&) override;
|
||||
|
||||
RESOURCE_HELPERS(TexturePack)
|
||||
};
|
||||
|
252
launcher/minecraft/mod/tasks/GetModDependenciesTask.cpp
Normal file
252
launcher/minecraft/mod/tasks/GetModDependenciesTask.cpp
Normal file
@ -0,0 +1,252 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "GetModDependenciesTask.h"
|
||||
|
||||
#include <QDebug>
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include "Json.h"
|
||||
#include "QObjectPtr.h"
|
||||
#include "minecraft/mod/MetadataHandler.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
#include "modplatform/ResourceAPI.h"
|
||||
#include "modplatform/flame/FlameAPI.h"
|
||||
#include "modplatform/modrinth/ModrinthAPI.h"
|
||||
#include "tasks/ConcurrentTask.h"
|
||||
#include "tasks/SequentialTask.h"
|
||||
#include "ui/pages/modplatform/ModModel.h"
|
||||
#include "ui/pages/modplatform/flame/FlameResourceModels.h"
|
||||
#include "ui/pages/modplatform/modrinth/ModrinthResourceModels.h"
|
||||
|
||||
static Version mcVersion(BaseInstance* inst)
|
||||
{
|
||||
return static_cast<MinecraftInstance*>(inst)->getPackProfile()->getComponent("net.minecraft")->getVersion();
|
||||
}
|
||||
|
||||
static ResourceAPI::ModLoaderTypes mcLoaders(BaseInstance* inst)
|
||||
{
|
||||
return static_cast<MinecraftInstance*>(inst)->getPackProfile()->getModLoaders().value();
|
||||
}
|
||||
|
||||
GetModDependenciesTask::GetModDependenciesTask(QObject* parent,
|
||||
BaseInstance* instance,
|
||||
ModFolderModel* folder,
|
||||
QList<std::shared_ptr<PackDependency>> selected)
|
||||
: SequentialTask(parent, tr("Get dependencies"))
|
||||
, m_selected(selected)
|
||||
, m_flame_provider{ ModPlatform::ResourceProvider::FLAME, std::make_shared<ResourceDownload::FlameModModel>(*instance),
|
||||
std::make_shared<FlameAPI>() }
|
||||
, m_modrinth_provider{ ModPlatform::ResourceProvider::MODRINTH, std::make_shared<ResourceDownload::ModrinthModModel>(*instance),
|
||||
std::make_shared<ModrinthAPI>() }
|
||||
, m_version(mcVersion(instance))
|
||||
, m_loaderType(mcLoaders(instance))
|
||||
{
|
||||
for (auto mod : folder->allMods())
|
||||
if (auto meta = mod->metadata(); meta)
|
||||
m_mods.append(meta);
|
||||
prepare();
|
||||
};
|
||||
|
||||
void GetModDependenciesTask::prepare()
|
||||
{
|
||||
for (auto sel : m_selected) {
|
||||
for (auto dep : getDependenciesForVersion(sel->version, sel->pack->provider)) {
|
||||
addTask(prepareDependencyTask(dep, sel->pack->provider, 20));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ModPlatform::Dependency GetModDependenciesTask::getOverride(const ModPlatform::Dependency& dep,
|
||||
const ModPlatform::ResourceProvider providerName)
|
||||
{
|
||||
if (auto isQuilt = m_loaderType & ResourceAPI::Quilt; isQuilt || m_loaderType & ResourceAPI::Fabric) {
|
||||
auto overide = ModPlatform::getOverrideDeps();
|
||||
auto over = std::find_if(overide.cbegin(), overide.cend(), [dep, providerName, isQuilt](auto o) {
|
||||
return o.provider == providerName && dep.addonId == (isQuilt ? o.fabric : o.quilt);
|
||||
});
|
||||
if (over != overide.cend()) {
|
||||
return { isQuilt ? over->quilt : over->fabric, dep.type };
|
||||
}
|
||||
}
|
||||
return dep;
|
||||
}
|
||||
|
||||
QList<ModPlatform::Dependency> GetModDependenciesTask::getDependenciesForVersion(const ModPlatform::IndexedVersion& version,
|
||||
const ModPlatform::ResourceProvider providerName)
|
||||
{
|
||||
QList<ModPlatform::Dependency> c_dependencies;
|
||||
for (auto ver_dep : version.dependencies) {
|
||||
if (ver_dep.type != ModPlatform::DependencyType::REQUIRED)
|
||||
continue;
|
||||
|
||||
auto isOnlyVersion = providerName == ModPlatform::ResourceProvider::MODRINTH && ver_dep.addonId.toString().isEmpty();
|
||||
if (auto dep = std::find_if(c_dependencies.begin(), c_dependencies.end(),
|
||||
[&ver_dep, isOnlyVersion](const ModPlatform::Dependency& i) {
|
||||
return isOnlyVersion ? i.version == ver_dep.version : i.addonId == ver_dep.addonId;
|
||||
});
|
||||
dep != c_dependencies.end())
|
||||
continue; // check the current dependency list
|
||||
|
||||
if (auto dep = std::find_if(m_selected.begin(), m_selected.end(),
|
||||
[&ver_dep, providerName, isOnlyVersion](std::shared_ptr<PackDependency> i) {
|
||||
return i->pack->provider == providerName && (isOnlyVersion ? i->version.version == ver_dep.version
|
||||
: i->pack->addonId == ver_dep.addonId);
|
||||
});
|
||||
dep != m_selected.end())
|
||||
continue; // check the selected versions
|
||||
|
||||
if (auto dep = std::find_if(m_mods.begin(), m_mods.end(),
|
||||
[&ver_dep, providerName, isOnlyVersion](std::shared_ptr<Metadata::ModStruct> i) {
|
||||
return i->provider == providerName &&
|
||||
(isOnlyVersion ? i->file_id == ver_dep.version : i->project_id == ver_dep.addonId);
|
||||
});
|
||||
dep != m_mods.end())
|
||||
continue; // check the existing mods
|
||||
|
||||
if (auto dep = std::find_if(m_pack_dependencies.begin(), m_pack_dependencies.end(),
|
||||
[&ver_dep, providerName, isOnlyVersion](std::shared_ptr<PackDependency> i) {
|
||||
return i->pack->provider == providerName && (isOnlyVersion ? i->version.version == ver_dep.addonId
|
||||
: i->pack->addonId == ver_dep.addonId);
|
||||
});
|
||||
dep != m_pack_dependencies.end()) // check loaded dependencies
|
||||
continue;
|
||||
|
||||
c_dependencies.append(getOverride(ver_dep, providerName));
|
||||
}
|
||||
return c_dependencies;
|
||||
};
|
||||
|
||||
Task::Ptr GetModDependenciesTask::getProjectInfoTask(std::shared_ptr<PackDependency> pDep)
|
||||
{
|
||||
auto provider = pDep->pack->provider == m_flame_provider.name ? m_flame_provider : m_modrinth_provider;
|
||||
auto responseInfo = std::make_shared<QByteArray>();
|
||||
auto info = provider.api->getProject(pDep->pack->addonId.toString(), responseInfo);
|
||||
QObject::connect(info.get(), &NetJob::succeeded, [responseInfo, provider, pDep] {
|
||||
QJsonParseError parse_error{};
|
||||
QJsonDocument doc = QJsonDocument::fromJson(*responseInfo, &parse_error);
|
||||
if (parse_error.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response for mod info at " << parse_error.offset
|
||||
<< " reason: " << parse_error.errorString();
|
||||
qDebug() << *responseInfo;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
auto obj = provider.name == ModPlatform::ResourceProvider::FLAME ? Json::requireObject(Json::requireObject(doc), "data")
|
||||
: Json::requireObject(doc);
|
||||
provider.mod->loadIndexedPack(*pDep->pack, obj);
|
||||
} catch (const JSONValidationError& e) {
|
||||
qDebug() << doc;
|
||||
qWarning() << "Error while reading mod info: " << e.cause();
|
||||
}
|
||||
});
|
||||
return info;
|
||||
}
|
||||
|
||||
Task::Ptr GetModDependenciesTask::prepareDependencyTask(const ModPlatform::Dependency& dep,
|
||||
const ModPlatform::ResourceProvider providerName,
|
||||
int level)
|
||||
{
|
||||
auto pDep = std::make_shared<PackDependency>();
|
||||
pDep->dependency = dep;
|
||||
pDep->pack = std::make_shared<ModPlatform::IndexedPack>();
|
||||
pDep->pack->addonId = dep.addonId;
|
||||
pDep->pack->provider = providerName;
|
||||
|
||||
m_pack_dependencies.append(pDep);
|
||||
auto provider = providerName == m_flame_provider.name ? m_flame_provider : m_modrinth_provider;
|
||||
|
||||
auto tasks = makeShared<SequentialTask>(
|
||||
this, QString("DependencyInfo: %1").arg(dep.addonId.toString().isEmpty() ? dep.version : dep.addonId.toString()));
|
||||
|
||||
if (!dep.addonId.toString().isEmpty()) {
|
||||
tasks->addTask(getProjectInfoTask(pDep));
|
||||
}
|
||||
|
||||
ResourceAPI::DependencySearchArgs args = { dep, m_version, m_loaderType };
|
||||
ResourceAPI::DependencySearchCallbacks callbacks;
|
||||
|
||||
callbacks.on_succeed = [dep, provider, pDep, level, this](auto& doc, auto& pack) {
|
||||
try {
|
||||
QJsonArray arr;
|
||||
if (dep.version.length() != 0 && doc.isObject()) {
|
||||
arr.append(doc.object());
|
||||
} else {
|
||||
arr = doc.isObject() ? Json::ensureArray(doc.object(), "data") : doc.array();
|
||||
}
|
||||
pDep->version = provider.mod->loadDependencyVersions(dep, arr);
|
||||
if (!pDep->version.addonId.isValid()) {
|
||||
if (m_loaderType & ResourceAPI::Quilt) { // falback for quilt
|
||||
auto overide = ModPlatform::getOverrideDeps();
|
||||
auto over = std::find_if(overide.cbegin(), overide.cend(),
|
||||
[dep, provider](auto o) { return o.provider == provider.name && dep.addonId == o.quilt; });
|
||||
if (over != overide.cend()) {
|
||||
removePack(dep.addonId);
|
||||
addTask(prepareDependencyTask({ over->fabric, dep.type }, provider.name, level));
|
||||
return;
|
||||
}
|
||||
}
|
||||
qWarning() << "Error while reading mod version empty ";
|
||||
qDebug() << doc;
|
||||
return;
|
||||
}
|
||||
pDep->version.is_currently_selected = true;
|
||||
pDep->pack->versions = { pDep->version };
|
||||
pDep->pack->versionsLoaded = true;
|
||||
|
||||
} catch (const JSONValidationError& e) {
|
||||
qDebug() << doc;
|
||||
qWarning() << "Error while reading mod version: " << e.cause();
|
||||
return;
|
||||
}
|
||||
if (level == 0) {
|
||||
qWarning() << "Dependency cycle exeeded";
|
||||
return;
|
||||
}
|
||||
if (dep.addonId.toString().isEmpty() && !pDep->version.addonId.toString().isEmpty()) {
|
||||
pDep->pack->addonId = pDep->version.addonId;
|
||||
auto dep = getOverride({ pDep->version.addonId, pDep->dependency.type }, provider.name);
|
||||
if (dep.addonId != pDep->version.addonId) {
|
||||
removePack(pDep->version.addonId);
|
||||
addTask(prepareDependencyTask(dep, provider.name, level));
|
||||
} else
|
||||
addTask(getProjectInfoTask(pDep));
|
||||
}
|
||||
for (auto dep : getDependenciesForVersion(pDep->version, provider.name)) {
|
||||
addTask(prepareDependencyTask(dep, provider.name, level - 1));
|
||||
}
|
||||
};
|
||||
|
||||
auto version = provider.api->getDependencyVersion(std::move(args), std::move(callbacks));
|
||||
tasks->addTask(version);
|
||||
return tasks;
|
||||
};
|
||||
|
||||
void GetModDependenciesTask::removePack(const QVariant addonId)
|
||||
{
|
||||
auto pred = [addonId](const std::shared_ptr<PackDependency>& v) { return v->pack->addonId == addonId; };
|
||||
#if QT_VERSION >= QT_VERSION_CHECK(6, 1, 0)
|
||||
m_pack_dependencies.removeIf(pred);
|
||||
#else
|
||||
for (auto it = m_pack_dependencies.begin(); it != m_pack_dependencies.end();)
|
||||
if (pred(*it))
|
||||
it = m_pack_dependencies.erase(it);
|
||||
else
|
||||
++it;
|
||||
#endif
|
||||
}
|
84
launcher/minecraft/mod/tasks/GetModDependenciesTask.h
Normal file
84
launcher/minecraft/mod/tasks/GetModDependenciesTask.h
Normal file
@ -0,0 +1,84 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <QDir>
|
||||
#include <QEventLoop>
|
||||
#include <QList>
|
||||
#include <QVariant>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
#include "minecraft/mod/MetadataHandler.h"
|
||||
#include "minecraft/mod/ModFolderModel.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
#include "modplatform/ResourceAPI.h"
|
||||
#include "tasks/SequentialTask.h"
|
||||
#include "tasks/Task.h"
|
||||
#include "ui/pages/modplatform/ModModel.h"
|
||||
|
||||
class GetModDependenciesTask : public SequentialTask {
|
||||
Q_OBJECT
|
||||
public:
|
||||
using Ptr = shared_qobject_ptr<GetModDependenciesTask>;
|
||||
|
||||
struct PackDependency {
|
||||
ModPlatform::Dependency dependency;
|
||||
ModPlatform::IndexedPack::Ptr pack;
|
||||
ModPlatform::IndexedVersion version;
|
||||
PackDependency() = default;
|
||||
PackDependency(const ModPlatform::IndexedPack::Ptr p, const ModPlatform::IndexedVersion& v)
|
||||
{
|
||||
pack = p;
|
||||
version = v;
|
||||
}
|
||||
};
|
||||
|
||||
struct Provider {
|
||||
ModPlatform::ResourceProvider name;
|
||||
std::shared_ptr<ResourceDownload::ModModel> mod;
|
||||
std::shared_ptr<ResourceAPI> api;
|
||||
};
|
||||
|
||||
explicit GetModDependenciesTask(QObject* parent,
|
||||
BaseInstance* instance,
|
||||
ModFolderModel* folder,
|
||||
QList<std::shared_ptr<PackDependency>> selected);
|
||||
|
||||
auto getDependecies() const -> QList<std::shared_ptr<PackDependency>> { return m_pack_dependencies; }
|
||||
|
||||
protected slots:
|
||||
Task::Ptr prepareDependencyTask(const ModPlatform::Dependency&, const ModPlatform::ResourceProvider, int);
|
||||
QList<ModPlatform::Dependency> getDependenciesForVersion(const ModPlatform::IndexedVersion&,
|
||||
const ModPlatform::ResourceProvider providerName);
|
||||
void prepare();
|
||||
Task::Ptr getProjectInfoTask(std::shared_ptr<PackDependency> pDep);
|
||||
ModPlatform::Dependency getOverride(const ModPlatform::Dependency&, const ModPlatform::ResourceProvider providerName);
|
||||
void removePack(const QVariant addonId);
|
||||
|
||||
private:
|
||||
QList<std::shared_ptr<PackDependency>> m_pack_dependencies;
|
||||
QList<std::shared_ptr<Metadata::ModStruct>> m_mods;
|
||||
QList<std::shared_ptr<PackDependency>> m_selected;
|
||||
Provider m_flame_provider;
|
||||
Provider m_modrinth_provider;
|
||||
|
||||
Version m_version;
|
||||
ResourceAPI::ModLoaderTypes m_loaderType;
|
||||
};
|
@ -52,6 +52,10 @@ ModDetails ReadMCModInfo(QByteArray contents)
|
||||
authors = firstObj.value("authors").toArray();
|
||||
}
|
||||
|
||||
if (firstObj.contains("logoFile")) {
|
||||
details.icon_file = firstObj.value("logoFile").toString();
|
||||
}
|
||||
|
||||
for (auto author : authors) {
|
||||
details.authors.append(author.toString());
|
||||
}
|
||||
@ -166,6 +170,31 @@ ModDetails ReadMCModTOML(QByteArray contents)
|
||||
}
|
||||
details.homeurl = homeurl;
|
||||
|
||||
QString issueTrackerURL = "";
|
||||
if (auto issueTrackerURLDatum = tomlData["issueTrackerURL"].as_string()) {
|
||||
issueTrackerURL = QString::fromStdString(issueTrackerURLDatum->get());
|
||||
} else if (auto issueTrackerURLDatum = (*modsTable)["issueTrackerURL"].as_string()) {
|
||||
issueTrackerURL = QString::fromStdString(issueTrackerURLDatum->get());
|
||||
}
|
||||
details.issue_tracker = issueTrackerURL;
|
||||
|
||||
QString license = "";
|
||||
if (auto licenseDatum = tomlData["license"].as_string()) {
|
||||
license = QString::fromStdString(licenseDatum->get());
|
||||
} else if (auto licenseDatum =(*modsTable)["license"].as_string()) {
|
||||
license = QString::fromStdString(licenseDatum->get());
|
||||
}
|
||||
if (!license.isEmpty())
|
||||
details.licenses.append(ModLicense(license));
|
||||
|
||||
QString logoFile = "";
|
||||
if (auto logoFileDatum = tomlData["logoFile"].as_string()) {
|
||||
logoFile = QString::fromStdString(logoFileDatum->get());
|
||||
} else if (auto logoFileDatum =(*modsTable)["logoFile"].as_string()) {
|
||||
logoFile = QString::fromStdString(logoFileDatum->get());
|
||||
}
|
||||
details.icon_file = logoFile;
|
||||
|
||||
return details;
|
||||
}
|
||||
|
||||
@ -201,6 +230,57 @@ ModDetails ReadFabricModInfo(QByteArray contents)
|
||||
if (contact.contains("homepage")) {
|
||||
details.homeurl = contact.value("homepage").toString();
|
||||
}
|
||||
if (contact.contains("issues")) {
|
||||
details.issue_tracker = contact.value("issues").toString();
|
||||
}
|
||||
}
|
||||
|
||||
if (object.contains("license")) {
|
||||
auto license = object.value("license");
|
||||
if (license.isArray()) {
|
||||
for (auto l : license.toArray()) {
|
||||
if (l.isString()) {
|
||||
details.licenses.append(ModLicense(l.toString()));
|
||||
} else if (l.isObject()) {
|
||||
auto obj = l.toObject();
|
||||
details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(),
|
||||
obj.value("url").toString(), obj.value("description").toString()));
|
||||
}
|
||||
}
|
||||
} else if (license.isString()) {
|
||||
details.licenses.append(ModLicense(license.toString()));
|
||||
} else if (license.isObject()) {
|
||||
auto obj = license.toObject();
|
||||
details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(), obj.value("url").toString(),
|
||||
obj.value("description").toString()));
|
||||
}
|
||||
}
|
||||
|
||||
if (object.contains("icon")) {
|
||||
auto icon = object.value("icon");
|
||||
if (icon.isObject()) {
|
||||
auto obj = icon.toObject();
|
||||
// take the largest icon
|
||||
int largest = 0;
|
||||
for (auto key : obj.keys()) {
|
||||
auto size = key.split('x').first().toInt();
|
||||
if (size > largest) {
|
||||
largest = size;
|
||||
}
|
||||
}
|
||||
if (largest > 0) {
|
||||
auto key = QString::number(largest) + "x" + QString::number(largest);
|
||||
details.icon_file = obj.value(key).toString();
|
||||
} else { // parsing the sizes failed
|
||||
// take the first
|
||||
for (auto i : obj) {
|
||||
details.icon_file = i.toString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (icon.isString()) {
|
||||
details.icon_file = icon.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
return details;
|
||||
@ -238,6 +318,58 @@ ModDetails ReadQuiltModInfo(QByteArray contents)
|
||||
if (modContact.contains("homepage")) {
|
||||
details.homeurl = Json::requireString(modContact.value("homepage"));
|
||||
}
|
||||
if (modContact.contains("issues")) {
|
||||
details.issue_tracker = Json::requireString(modContact.value("issues"));
|
||||
}
|
||||
|
||||
if (modMetadata.contains("license")) {
|
||||
auto license = modMetadata.value("license");
|
||||
if (license.isArray()) {
|
||||
for (auto l : license.toArray()) {
|
||||
if (l.isString()) {
|
||||
details.licenses.append(ModLicense(l.toString()));
|
||||
} else if (l.isObject()) {
|
||||
auto obj = l.toObject();
|
||||
details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(),
|
||||
obj.value("url").toString(), obj.value("description").toString()));
|
||||
}
|
||||
}
|
||||
} else if (license.isString()) {
|
||||
details.licenses.append(ModLicense(license.toString()));
|
||||
} else if (license.isObject()) {
|
||||
auto obj = license.toObject();
|
||||
details.licenses.append(ModLicense(obj.value("name").toString(), obj.value("id").toString(), obj.value("url").toString(),
|
||||
obj.value("description").toString()));
|
||||
}
|
||||
}
|
||||
|
||||
if (modMetadata.contains("icon")) {
|
||||
auto icon = modMetadata.value("icon");
|
||||
if (icon.isObject()) {
|
||||
auto obj = icon.toObject();
|
||||
// take the largest icon
|
||||
int largest = 0;
|
||||
for (auto key : obj.keys()) {
|
||||
auto size = key.split('x').first().toInt();
|
||||
if (size > largest) {
|
||||
largest = size;
|
||||
}
|
||||
}
|
||||
if (largest > 0) {
|
||||
auto key = QString::number(largest) + "x" + QString::number(largest);
|
||||
details.icon_file = obj.value(key).toString();
|
||||
} else { // parsing the sizes failed
|
||||
// take the first
|
||||
for (auto i : obj) {
|
||||
details.icon_file = i.toString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (icon.isString()) {
|
||||
details.icon_file = icon.toString();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return details;
|
||||
}
|
||||
@ -515,6 +647,85 @@ bool validate(QFileInfo file)
|
||||
return ModUtils::process(mod, ProcessingLevel::BasicInfoOnly) && mod.valid();
|
||||
}
|
||||
|
||||
bool processIconPNG(const Mod& mod, QByteArray&& raw_data)
|
||||
{
|
||||
auto img = QImage::fromData(raw_data);
|
||||
if (!img.isNull()) {
|
||||
mod.setIcon(img);
|
||||
} else {
|
||||
qWarning() << "Failed to parse mod logo:" << mod.iconPath() << "from" << mod.name();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool loadIconFile(const Mod& mod) {
|
||||
if (mod.iconPath().isEmpty()) {
|
||||
qWarning() << "No Iconfile set, be sure to parse the mod first";
|
||||
return false;
|
||||
}
|
||||
|
||||
auto png_invalid = [&mod]() {
|
||||
qWarning() << "Mod at" << mod.fileinfo().filePath() << "does not have a valid icon";
|
||||
return false;
|
||||
};
|
||||
|
||||
switch (mod.type()) {
|
||||
case ResourceType::FOLDER:
|
||||
{
|
||||
QFileInfo icon_info(FS::PathCombine(mod.fileinfo().filePath(), mod.iconPath()));
|
||||
if (icon_info.exists() && icon_info.isFile()) {
|
||||
QFile icon(icon_info.filePath());
|
||||
if (!icon.open(QIODevice::ReadOnly))
|
||||
return false;
|
||||
auto data = icon.readAll();
|
||||
|
||||
bool icon_result = ModUtils::processIconPNG(mod, std::move(data));
|
||||
|
||||
icon.close();
|
||||
|
||||
if (!icon_result) {
|
||||
return png_invalid(); // icon invalid
|
||||
}
|
||||
}
|
||||
}
|
||||
case ResourceType::ZIPFILE:
|
||||
{
|
||||
QuaZip zip(mod.fileinfo().filePath());
|
||||
if (!zip.open(QuaZip::mdUnzip))
|
||||
return false;
|
||||
|
||||
QuaZipFile file(&zip);
|
||||
|
||||
if (zip.setCurrentFile(mod.iconPath())) {
|
||||
if (!file.open(QIODevice::ReadOnly)) {
|
||||
qCritical() << "Failed to open file in zip.";
|
||||
zip.close();
|
||||
return png_invalid();
|
||||
}
|
||||
|
||||
auto data = file.readAll();
|
||||
|
||||
bool icon_result = ModUtils::processIconPNG(mod, std::move(data));
|
||||
|
||||
file.close();
|
||||
if (!icon_result) {
|
||||
return png_invalid(); // icon png invalid
|
||||
}
|
||||
} else {
|
||||
return png_invalid(); // could not set icon as current file.
|
||||
}
|
||||
}
|
||||
case ResourceType::LITEMOD:
|
||||
{
|
||||
return false; // can lightmods even have icons?
|
||||
}
|
||||
default:
|
||||
qWarning() << "Invalid type for mod, can not load icon.";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace ModUtils
|
||||
|
||||
LocalModParseTask::LocalModParseTask(int token, ResourceType type, const QFileInfo& modFile)
|
||||
|
@ -25,6 +25,9 @@ bool processLitemod(Mod& mod, ProcessingLevel level = ProcessingLevel::Full);
|
||||
|
||||
/** Checks whether a file is valid as a mod or not. */
|
||||
bool validate(QFileInfo file);
|
||||
|
||||
bool processIconPNG(const Mod& mod, QByteArray&& raw_data);
|
||||
bool loadIconFile(const Mod& mod);
|
||||
} // namespace ModUtils
|
||||
|
||||
class LocalModParseTask : public Task {
|
||||
|
@ -1,6 +1,6 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* PolyMC - Minecraft Launcher
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
|
||||
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
|
||||
*
|
||||
@ -19,7 +19,6 @@
|
||||
|
||||
#include "LocalModUpdateTask.h"
|
||||
|
||||
#include "Application.h"
|
||||
#include "FileSystem.h"
|
||||
#include "minecraft/mod/MetadataHandler.h"
|
||||
|
||||
|
@ -165,15 +165,16 @@ bool processZIP(ResourcePack& pack, ProcessingLevel level)
|
||||
bool pack_png_result = ResourcePackUtils::processPackPNG(pack, std::move(data));
|
||||
|
||||
file.close();
|
||||
zip.close();
|
||||
if (!pack_png_result) {
|
||||
return png_invalid(); // pack.png invalid
|
||||
}
|
||||
} else {
|
||||
zip.close();
|
||||
return png_invalid(); // could not set pack.mcmeta as current file.
|
||||
}
|
||||
|
||||
zip.close();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -193,7 +194,7 @@ bool processMCMeta(ResourcePack& pack, QByteArray&& raw_data)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool processPackPNG(ResourcePack& pack, QByteArray&& raw_data)
|
||||
bool processPackPNG(const ResourcePack& pack, QByteArray&& raw_data)
|
||||
{
|
||||
auto img = QImage::fromData(raw_data);
|
||||
if (!img.isNull()) {
|
||||
@ -205,6 +206,68 @@ bool processPackPNG(ResourcePack& pack, QByteArray&& raw_data)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool processPackPNG(const ResourcePack& pack)
|
||||
{
|
||||
auto png_invalid = [&pack]() {
|
||||
qWarning() << "Resource pack at" << pack.fileinfo().filePath() << "does not have a valid pack.png";
|
||||
return false;
|
||||
};
|
||||
|
||||
switch (pack.type()) {
|
||||
case ResourceType::FOLDER:
|
||||
{
|
||||
QFileInfo image_file_info(FS::PathCombine(pack.fileinfo().filePath(), "pack.png"));
|
||||
if (image_file_info.exists() && image_file_info.isFile()) {
|
||||
QFile pack_png_file(image_file_info.filePath());
|
||||
if (!pack_png_file.open(QIODevice::ReadOnly))
|
||||
return png_invalid(); // can't open pack.png file
|
||||
|
||||
auto data = pack_png_file.readAll();
|
||||
|
||||
bool pack_png_result = ResourcePackUtils::processPackPNG(pack, std::move(data));
|
||||
|
||||
pack_png_file.close();
|
||||
if (!pack_png_result) {
|
||||
return png_invalid(); // pack.png invalid
|
||||
}
|
||||
} else {
|
||||
return png_invalid(); // pack.png does not exists or is not a valid file.
|
||||
}
|
||||
}
|
||||
case ResourceType::ZIPFILE:
|
||||
{
|
||||
Q_ASSERT(pack.type() == ResourceType::ZIPFILE);
|
||||
|
||||
QuaZip zip(pack.fileinfo().filePath());
|
||||
if (!zip.open(QuaZip::mdUnzip))
|
||||
return false; // can't open zip file
|
||||
|
||||
QuaZipFile file(&zip);
|
||||
if (zip.setCurrentFile("pack.png")) {
|
||||
if (!file.open(QIODevice::ReadOnly)) {
|
||||
qCritical() << "Failed to open file in zip.";
|
||||
zip.close();
|
||||
return png_invalid();
|
||||
}
|
||||
|
||||
auto data = file.readAll();
|
||||
|
||||
bool pack_png_result = ResourcePackUtils::processPackPNG(pack, std::move(data));
|
||||
|
||||
file.close();
|
||||
if (!pack_png_result) {
|
||||
return png_invalid(); // pack.png invalid
|
||||
}
|
||||
} else {
|
||||
return png_invalid(); // could not set pack.mcmeta as current file.
|
||||
}
|
||||
}
|
||||
default:
|
||||
qWarning() << "Invalid type for resource pack parse task!";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool validate(QFileInfo file)
|
||||
{
|
||||
ResourcePack rp{ file };
|
||||
|
@ -35,7 +35,10 @@ bool processZIP(ResourcePack& pack, ProcessingLevel level = ProcessingLevel::Ful
|
||||
bool processFolder(ResourcePack& pack, ProcessingLevel level = ProcessingLevel::Full);
|
||||
|
||||
bool processMCMeta(ResourcePack& pack, QByteArray&& raw_data);
|
||||
bool processPackPNG(ResourcePack& pack, QByteArray&& raw_data);
|
||||
bool processPackPNG(const ResourcePack& pack, QByteArray&& raw_data);
|
||||
|
||||
/// processes ONLY the pack.png (rest of the pack may be invalid)
|
||||
bool processPackPNG(const ResourcePack& pack);
|
||||
|
||||
/** Checks whether a file is valid as a resource pack or not. */
|
||||
bool validate(QFileInfo file);
|
||||
|
@ -131,6 +131,7 @@ bool processZIP(TexturePack& pack, ProcessingLevel level)
|
||||
bool packPNG_result = TexturePackUtils::processPackPNG(pack, std::move(data));
|
||||
|
||||
file.close();
|
||||
zip.close();
|
||||
if (!packPNG_result) {
|
||||
return false;
|
||||
}
|
||||
@ -147,7 +148,7 @@ bool processPackTXT(TexturePack& pack, QByteArray&& raw_data)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool processPackPNG(TexturePack& pack, QByteArray&& raw_data)
|
||||
bool processPackPNG(const TexturePack& pack, QByteArray&& raw_data)
|
||||
{
|
||||
auto img = QImage::fromData(raw_data);
|
||||
if (!img.isNull()) {
|
||||
@ -159,6 +160,70 @@ bool processPackPNG(TexturePack& pack, QByteArray&& raw_data)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool processPackPNG(const TexturePack& pack)
|
||||
{
|
||||
auto png_invalid = [&pack]() {
|
||||
qWarning() << "Texture pack at" << pack.fileinfo().filePath() << "does not have a valid pack.png";
|
||||
return false;
|
||||
};
|
||||
|
||||
switch (pack.type()) {
|
||||
case ResourceType::FOLDER:
|
||||
{
|
||||
QFileInfo image_file_info(FS::PathCombine(pack.fileinfo().filePath(), "pack.png"));
|
||||
if (image_file_info.exists() && image_file_info.isFile()) {
|
||||
QFile pack_png_file(image_file_info.filePath());
|
||||
if (!pack_png_file.open(QIODevice::ReadOnly))
|
||||
return png_invalid(); // can't open pack.png file
|
||||
|
||||
auto data = pack_png_file.readAll();
|
||||
|
||||
bool pack_png_result = TexturePackUtils::processPackPNG(pack, std::move(data));
|
||||
|
||||
pack_png_file.close();
|
||||
if (!pack_png_result) {
|
||||
return png_invalid(); // pack.png invalid
|
||||
}
|
||||
} else {
|
||||
return png_invalid(); // pack.png does not exists or is not a valid file.
|
||||
}
|
||||
}
|
||||
case ResourceType::ZIPFILE:
|
||||
{
|
||||
Q_ASSERT(pack.type() == ResourceType::ZIPFILE);
|
||||
|
||||
QuaZip zip(pack.fileinfo().filePath());
|
||||
if (!zip.open(QuaZip::mdUnzip))
|
||||
return false; // can't open zip file
|
||||
|
||||
QuaZipFile file(&zip);
|
||||
if (zip.setCurrentFile("pack.png")) {
|
||||
if (!file.open(QIODevice::ReadOnly)) {
|
||||
qCritical() << "Failed to open file in zip.";
|
||||
zip.close();
|
||||
return png_invalid();
|
||||
}
|
||||
|
||||
auto data = file.readAll();
|
||||
|
||||
bool pack_png_result = TexturePackUtils::processPackPNG(pack, std::move(data));
|
||||
|
||||
file.close();
|
||||
if (!pack_png_result) {
|
||||
zip.close();
|
||||
return png_invalid(); // pack.png invalid
|
||||
}
|
||||
} else {
|
||||
zip.close();
|
||||
return png_invalid(); // could not set pack.mcmeta as current file.
|
||||
}
|
||||
}
|
||||
default:
|
||||
qWarning() << "Invalid type for resource pack parse task!";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool validate(QFileInfo file)
|
||||
{
|
||||
TexturePack rp{ file };
|
||||
|
@ -36,7 +36,10 @@ bool processZIP(TexturePack& pack, ProcessingLevel level = ProcessingLevel::Full
|
||||
bool processFolder(TexturePack& pack, ProcessingLevel level = ProcessingLevel::Full);
|
||||
|
||||
bool processPackTXT(TexturePack& pack, QByteArray&& raw_data);
|
||||
bool processPackPNG(TexturePack& pack, QByteArray&& raw_data);
|
||||
bool processPackPNG(const TexturePack& pack, QByteArray&& raw_data);
|
||||
|
||||
/// processes ONLY the pack.png (rest of the pack may be invalid)
|
||||
bool processPackPNG(const TexturePack& pack);
|
||||
|
||||
/** Checks whether a file is valid as a texture pack or not. */
|
||||
bool validate(QFileInfo file);
|
||||
|
@ -10,6 +10,7 @@
|
||||
|
||||
#include "modplatform/flame/FlameAPI.h"
|
||||
#include "modplatform/flame/FlameModIndex.h"
|
||||
#include "modplatform/helpers/HashUtils.h"
|
||||
#include "modplatform/modrinth/ModrinthAPI.h"
|
||||
#include "modplatform/modrinth/ModrinthPackIndex.h"
|
||||
|
||||
@ -24,8 +25,8 @@ EnsureMetadataTask::EnsureMetadataTask(Mod* mod, QDir dir, ModPlatform::Resource
|
||||
auto hash_task = createNewHash(mod);
|
||||
if (!hash_task)
|
||||
return;
|
||||
connect(hash_task.get(), &Task::succeeded, [this, hash_task, mod] { m_mods.insert(hash_task->getResult(), mod); });
|
||||
connect(hash_task.get(), &Task::failed, [this, hash_task, mod] { emitFail(mod, "", RemoveFromList::No); });
|
||||
connect(hash_task.get(), &Hashing::Hasher::resultsReady, [this, mod](QString hash) { m_mods.insert(hash, mod); });
|
||||
connect(hash_task.get(), &Task::failed, [this, mod] { emitFail(mod, "", RemoveFromList::No); });
|
||||
hash_task->start();
|
||||
}
|
||||
|
||||
@ -37,8 +38,8 @@ EnsureMetadataTask::EnsureMetadataTask(QList<Mod*>& mods, QDir dir, ModPlatform:
|
||||
auto hash_task = createNewHash(mod);
|
||||
if (!hash_task)
|
||||
continue;
|
||||
connect(hash_task.get(), &Task::succeeded, [this, hash_task, mod] { m_mods.insert(hash_task->getResult(), mod); });
|
||||
connect(hash_task.get(), &Task::failed, [this, hash_task, mod] { emitFail(mod, "", RemoveFromList::No); });
|
||||
connect(hash_task.get(), &Hashing::Hasher::resultsReady, [this, mod](QString hash) { m_mods.insert(hash, mod); });
|
||||
connect(hash_task.get(), &Task::failed, [this, mod] { emitFail(mod, "", RemoveFromList::No); });
|
||||
m_hashing_task->addTask(hash_task);
|
||||
}
|
||||
}
|
||||
@ -212,7 +213,7 @@ Task::Ptr EnsureMetadataTask::modrinthVersionsTask()
|
||||
{
|
||||
auto hash_type = ProviderCaps.hashType(ModPlatform::ResourceProvider::MODRINTH).first();
|
||||
|
||||
auto* response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
auto ver_task = modrinth_api.currentVersions(m_mods.keys(), hash_type, response);
|
||||
|
||||
// Prevents unfortunate timings when aborting the task
|
||||
@ -264,7 +265,7 @@ Task::Ptr EnsureMetadataTask::modrinthProjectsTask()
|
||||
for (auto const& data : m_temp_versions)
|
||||
addonIds.insert(data.addonId.toString(), data.hash);
|
||||
|
||||
auto response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
Task::Ptr proj_task;
|
||||
|
||||
if (addonIds.isEmpty()) {
|
||||
@ -345,7 +346,7 @@ Task::Ptr EnsureMetadataTask::modrinthProjectsTask()
|
||||
// Flame
|
||||
Task::Ptr EnsureMetadataTask::flameVersionsTask()
|
||||
{
|
||||
auto* response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
|
||||
QList<uint> fingerprints;
|
||||
for (auto& murmur : m_mods.keys()) {
|
||||
@ -413,7 +414,7 @@ Task::Ptr EnsureMetadataTask::flameProjectsTask()
|
||||
QHash<QString, QString> addonIds;
|
||||
for (auto const& hash : m_mods.keys()) {
|
||||
if (m_temp_versions.contains(hash)) {
|
||||
auto const& data = m_temp_versions.find(hash).value();
|
||||
auto data = m_temp_versions.find(hash).value();
|
||||
|
||||
auto id_str = data.addonId.toString();
|
||||
if (!id_str.isEmpty())
|
||||
@ -421,7 +422,7 @@ Task::Ptr EnsureMetadataTask::flameProjectsTask()
|
||||
}
|
||||
}
|
||||
|
||||
auto response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
Task::Ptr proj_task;
|
||||
|
||||
if (addonIds.isEmpty()) {
|
||||
|
@ -1,7 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* PolyMC - Minecraft Launcher
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
@ -33,6 +34,8 @@ enum class ResourceProvider { MODRINTH, FLAME };
|
||||
|
||||
enum class ResourceType { MOD, RESOURCE_PACK, SHADER_PACK };
|
||||
|
||||
enum class DependencyType { REQUIRED, OPTIONAL, INCOMPATIBLE, EMBEDDED, TOOL, INCLUDE, UNKNOWN };
|
||||
|
||||
class ProviderCapabilities {
|
||||
public:
|
||||
auto name(ResourceProvider) -> const char*;
|
||||
@ -52,6 +55,12 @@ struct DonationData {
|
||||
QString url;
|
||||
};
|
||||
|
||||
struct Dependency {
|
||||
QVariant addonId;
|
||||
DependencyType type;
|
||||
QString version;
|
||||
};
|
||||
|
||||
struct IndexedVersion {
|
||||
QVariant addonId;
|
||||
QVariant fileId;
|
||||
@ -66,6 +75,7 @@ struct IndexedVersion {
|
||||
QString hash;
|
||||
bool is_preferred = true;
|
||||
QString changelog;
|
||||
QList<Dependency> dependencies;
|
||||
|
||||
// For internal use, not provided by APIs
|
||||
bool is_currently_selected = false;
|
||||
@ -119,6 +129,22 @@ struct IndexedPack {
|
||||
}
|
||||
};
|
||||
|
||||
struct OverrideDep {
|
||||
QString quilt;
|
||||
QString fabric;
|
||||
QString slug;
|
||||
ModPlatform::ResourceProvider provider;
|
||||
};
|
||||
|
||||
inline auto getOverrideDeps() -> QList<OverrideDep>
|
||||
{
|
||||
return { { "634179", "306612", "API", ModPlatform::ResourceProvider::FLAME },
|
||||
{ "720410", "308769", "KotlinLibraries", ModPlatform::ResourceProvider::FLAME },
|
||||
|
||||
{ "qvIfYCYJ", "P7dR8mSH", "API", ModPlatform::ResourceProvider::MODRINTH },
|
||||
{ "lwVhp9o5", "Ha28R6CL", "KotlinLibraries", ModPlatform::ResourceProvider::MODRINTH } };
|
||||
};
|
||||
|
||||
} // namespace ModPlatform
|
||||
|
||||
Q_DECLARE_METATYPE(ModPlatform::IndexedPack)
|
||||
|
@ -111,6 +111,16 @@ class ResourceAPI {
|
||||
std::function<void(QJsonDocument&, ModPlatform::IndexedPack)> on_succeed;
|
||||
};
|
||||
|
||||
struct DependencySearchArgs {
|
||||
ModPlatform::Dependency dependency;
|
||||
Version mcVersion;
|
||||
ModLoaderTypes loader;
|
||||
};
|
||||
|
||||
struct DependencySearchCallbacks {
|
||||
std::function<void(QJsonDocument&, const ModPlatform::Dependency&)> on_succeed;
|
||||
};
|
||||
|
||||
public:
|
||||
/** Gets a list of available sorting methods for this API. */
|
||||
[[nodiscard]] virtual auto getSortingMethods() const -> QList<SortingMethod> = 0;
|
||||
@ -121,12 +131,12 @@ class ResourceAPI {
|
||||
qWarning() << "TODO";
|
||||
return nullptr;
|
||||
}
|
||||
[[nodiscard]] virtual Task::Ptr getProject(QString addonId, QByteArray* response) const
|
||||
[[nodiscard]] virtual Task::Ptr getProject(QString addonId, std::shared_ptr<QByteArray> response) const
|
||||
{
|
||||
qWarning() << "TODO";
|
||||
return nullptr;
|
||||
}
|
||||
[[nodiscard]] virtual Task::Ptr getProjects(QStringList addonIds, QByteArray* response) const
|
||||
[[nodiscard]] virtual Task::Ptr getProjects(QStringList addonIds, std::shared_ptr<QByteArray> response) const
|
||||
{
|
||||
qWarning() << "TODO";
|
||||
return nullptr;
|
||||
@ -143,6 +153,12 @@ class ResourceAPI {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
[[nodiscard]] virtual Task::Ptr getDependencyVersion(DependencySearchArgs&&, DependencySearchCallbacks&&) const
|
||||
{
|
||||
qWarning() << "TODO";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static auto getModLoaderString(ModLoaderType type) -> const QString
|
||||
{
|
||||
switch (type) {
|
||||
|
@ -82,9 +82,9 @@ void PackInstallTask::executeTask()
|
||||
{
|
||||
qDebug() << "PackInstallTask::executeTask: " << QThread::currentThreadId();
|
||||
NetJob::Ptr netJob{ new NetJob("ATLauncher::VersionFetch", APPLICATION->network()) };
|
||||
auto searchUrl = QString(BuildConfig.ATL_DOWNLOAD_SERVER_URL + "packs/%1/versions/%2/Configs.json")
|
||||
.arg(m_pack_safe_name).arg(m_version_name);
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchUrl), &response));
|
||||
auto searchUrl =
|
||||
QString(BuildConfig.ATL_DOWNLOAD_SERVER_URL + "packs/%1/versions/%2/Configs.json").arg(m_pack_safe_name).arg(m_version_name);
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchUrl), response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, this, &PackInstallTask::onDownloadSucceeded);
|
||||
QObject::connect(netJob.get(), &NetJob::failed, this, &PackInstallTask::onDownloadFailed);
|
||||
@ -100,10 +100,11 @@ void PackInstallTask::onDownloadSucceeded()
|
||||
jobPtr.reset();
|
||||
|
||||
QJsonParseError parse_error{};
|
||||
QJsonDocument doc = QJsonDocument::fromJson(response, &parse_error);
|
||||
QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error);
|
||||
if (parse_error.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response from ATLauncher at " << parse_error.offset << " reason: " << parse_error.errorString();
|
||||
qWarning() << response;
|
||||
qWarning() << "Error while parsing JSON response from ATLauncher at " << parse_error.offset
|
||||
<< " reason: " << parse_error.errorString();
|
||||
qWarning() << *response.get();
|
||||
return;
|
||||
}
|
||||
auto obj = doc.object();
|
||||
|
@ -40,12 +40,13 @@
|
||||
#include "ATLPackManifest.h"
|
||||
|
||||
#include "InstanceTask.h"
|
||||
#include "net/NetJob.h"
|
||||
#include "settings/INISettingsObject.h"
|
||||
#include "meta/Version.h"
|
||||
#include "minecraft/MinecraftInstance.h"
|
||||
#include "minecraft/PackProfile.h"
|
||||
#include "meta/Version.h"
|
||||
#include "net/NetJob.h"
|
||||
#include "settings/INISettingsObject.h"
|
||||
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
|
||||
namespace ATLauncher {
|
||||
@ -57,7 +58,6 @@ enum class InstallMode {
|
||||
};
|
||||
|
||||
class UserInteractionSupport {
|
||||
|
||||
public:
|
||||
/**
|
||||
* Requests a user interaction to select which optional mods should be installed.
|
||||
@ -74,15 +74,19 @@ public:
|
||||
* Requests a user interaction to display a message.
|
||||
*/
|
||||
virtual void displayMessage(QString message) = 0;
|
||||
|
||||
virtual ~UserInteractionSupport() = default;
|
||||
};
|
||||
|
||||
class PackInstallTask : public InstanceTask
|
||||
{
|
||||
class PackInstallTask : public InstanceTask {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit PackInstallTask(UserInteractionSupport *support, QString packName, QString version, InstallMode installMode = InstallMode::Install);
|
||||
virtual ~PackInstallTask(){}
|
||||
explicit PackInstallTask(UserInteractionSupport* support,
|
||||
QString packName,
|
||||
QString version,
|
||||
InstallMode installMode = InstallMode::Install);
|
||||
virtual ~PackInstallTask() { delete m_support; }
|
||||
|
||||
bool canAbort() const override { return true; }
|
||||
bool abort() override;
|
||||
@ -110,11 +114,9 @@ private:
|
||||
void installConfigs();
|
||||
void extractConfigs();
|
||||
void downloadMods();
|
||||
bool extractMods(
|
||||
const QMap<QString, VersionMod> &toExtract,
|
||||
bool extractMods(const QMap<QString, VersionMod>& toExtract,
|
||||
const QMap<QString, VersionMod>& toDecomp,
|
||||
const QMap<QString, QString> &toCopy
|
||||
);
|
||||
const QMap<QString, QString>& toCopy);
|
||||
void install();
|
||||
|
||||
private:
|
||||
@ -123,7 +125,7 @@ private:
|
||||
bool abortable = false;
|
||||
|
||||
NetJob::Ptr jobPtr;
|
||||
QByteArray response;
|
||||
std::shared_ptr<QByteArray> response = std::make_shared<QByteArray>();
|
||||
|
||||
InstallMode m_install_mode;
|
||||
QString m_pack_name;
|
||||
@ -145,7 +147,6 @@ private:
|
||||
|
||||
QFuture<bool> m_modExtractFuture;
|
||||
QFutureWatcher<bool> m_modExtractFutureWatcher;
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace ATLauncher
|
||||
|
@ -28,12 +28,13 @@ void Flame::FileResolvingTask::executeTask()
|
||||
// build json data to send
|
||||
QJsonObject object;
|
||||
|
||||
object["fileIds"] = QJsonArray::fromVariantList(std::accumulate(m_toProcess.files.begin(), m_toProcess.files.end(), QVariantList(), [](QVariantList& l, const File& s) {
|
||||
object["fileIds"] = QJsonArray::fromVariantList(
|
||||
std::accumulate(m_toProcess.files.begin(), m_toProcess.files.end(), QVariantList(), [](QVariantList& l, const File& s) {
|
||||
l.push_back(s.fileId);
|
||||
return l;
|
||||
}));
|
||||
QByteArray data = Json::toText(object);
|
||||
auto dl = Net::Upload::makeByteArray(QUrl("https://api.curseforge.com/v1/mods/files"), result.get(), data);
|
||||
auto dl = Net::Upload::makeByteArray(QUrl("https://api.curseforge.com/v1/mods/files"), result, data);
|
||||
m_dljob->addNetAction(dl);
|
||||
|
||||
auto step_progress = std::make_shared<TaskStepProgress>();
|
||||
@ -94,10 +95,8 @@ void Flame::FileResolvingTask::netJobFinished()
|
||||
if (!hash.isEmpty()) {
|
||||
auto url = QString("https://api.modrinth.com/v2/version_file/%1?algorithm=sha1").arg(hash);
|
||||
auto output = std::make_shared<QByteArray>();
|
||||
auto dl = Net::Download::makeByteArray(QUrl(url), output.get());
|
||||
QObject::connect(dl.get(), &Net::Download::succeeded, [&out]() {
|
||||
out.resolved = true;
|
||||
});
|
||||
auto dl = Net::Download::makeByteArray(QUrl(url), output);
|
||||
QObject::connect(dl.get(), &Net::Download::succeeded, [&out]() { out.resolved = true; });
|
||||
|
||||
m_checkJob->addNetAction(dl);
|
||||
blockedProjects.insert(&out, output);
|
||||
@ -169,7 +168,7 @@ void Flame::FileResolvingTask::modrinthCheckFinished() {
|
||||
auto projectId = mod->projectId;
|
||||
auto output = std::make_shared<QByteArray>();
|
||||
auto url = QString("https://api.curseforge.com/v1/mods/%1").arg(projectId);
|
||||
auto dl = Net::Download::makeByteArray(url, output.get());
|
||||
auto dl = Net::Download::makeByteArray(url, output);
|
||||
qDebug() << "Fetching url slug for file:" << mod->fileName;
|
||||
QObject::connect(dl.get(), &Net::Download::succeeded, [block, index, output]() {
|
||||
auto mod = block->at(index); // use the shared_ptr so it is captured and only freed when we are done
|
||||
|
@ -11,7 +11,7 @@
|
||||
#include "net/NetJob.h"
|
||||
#include "net/Upload.h"
|
||||
|
||||
Task::Ptr FlameAPI::matchFingerprints(const QList<uint>& fingerprints, QByteArray* response)
|
||||
Task::Ptr FlameAPI::matchFingerprints(const QList<uint>& fingerprints, std::shared_ptr<QByteArray> response)
|
||||
{
|
||||
auto netJob = makeShared<NetJob>(QString("Flame::MatchFingerprints"), APPLICATION->network());
|
||||
|
||||
@ -28,8 +28,6 @@ Task::Ptr FlameAPI::matchFingerprints(const QList<uint>& fingerprints, QByteArra
|
||||
|
||||
netJob->addNetAction(Net::Upload::makeByteArray(QString("https://api.curseforge.com/v1/fingerprints"), response, body_raw));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response] { delete response; });
|
||||
|
||||
return netJob;
|
||||
}
|
||||
|
||||
@ -43,7 +41,7 @@ auto FlameAPI::getModFileChangelog(int modId, int fileId) -> QString
|
||||
netJob->addNetAction(Net::Download::makeByteArray(
|
||||
QString("https://api.curseforge.com/v1/mods/%1/files/%2/changelog")
|
||||
.arg(QString::fromStdString(std::to_string(modId)), QString::fromStdString(std::to_string(fileId))),
|
||||
response.get()));
|
||||
response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, [&netJob, response, &changelog] {
|
||||
QJsonParseError parse_error{};
|
||||
@ -75,8 +73,8 @@ auto FlameAPI::getModDescription(int modId) -> QString
|
||||
|
||||
auto netJob = makeShared<NetJob>(QString("Flame::ModDescription"), APPLICATION->network());
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
netJob->addNetAction(Net::Download::makeByteArray(
|
||||
QString("https://api.curseforge.com/v1/mods/%1/description").arg(QString::number(modId)), response.get()));
|
||||
netJob->addNetAction(
|
||||
Net::Download::makeByteArray(QString("https://api.curseforge.com/v1/mods/%1/description").arg(QString::number(modId)), response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, [&netJob, response, &description] {
|
||||
QJsonParseError parse_error{};
|
||||
@ -115,7 +113,7 @@ auto FlameAPI::getLatestVersion(VersionSearchArgs&& args) -> ModPlatform::Indexe
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
ModPlatform::IndexedVersion ver;
|
||||
|
||||
netJob->addNetAction(Net::Download::makeByteArray(versions_url, response.get()));
|
||||
netJob->addNetAction(Net::Download::makeByteArray(versions_url, response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, [response, args, &ver] {
|
||||
QJsonParseError parse_error{};
|
||||
@ -160,7 +158,7 @@ auto FlameAPI::getLatestVersion(VersionSearchArgs&& args) -> ModPlatform::Indexe
|
||||
return ver;
|
||||
}
|
||||
|
||||
Task::Ptr FlameAPI::getProjects(QStringList addonIds, QByteArray* response) const
|
||||
Task::Ptr FlameAPI::getProjects(QStringList addonIds, std::shared_ptr<QByteArray> response) const
|
||||
{
|
||||
auto netJob = makeShared<NetJob>(QString("Flame::GetProjects"), APPLICATION->network());
|
||||
|
||||
@ -177,13 +175,12 @@ Task::Ptr FlameAPI::getProjects(QStringList addonIds, QByteArray* response) cons
|
||||
|
||||
netJob->addNetAction(Net::Upload::makeByteArray(QString("https://api.curseforge.com/v1/mods"), response, body_raw));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response] { delete response; });
|
||||
QObject::connect(netJob.get(), &NetJob::failed, [body_raw] { qDebug() << body_raw; });
|
||||
|
||||
return netJob;
|
||||
}
|
||||
|
||||
Task::Ptr FlameAPI::getFiles(const QStringList& fileIds, QByteArray* response) const
|
||||
Task::Ptr FlameAPI::getFiles(const QStringList& fileIds, std::shared_ptr<QByteArray> response) const
|
||||
{
|
||||
auto netJob = makeShared<NetJob>(QString("Flame::GetFiles"), APPLICATION->network());
|
||||
|
||||
@ -200,7 +197,6 @@ Task::Ptr FlameAPI::getFiles(const QStringList& fileIds, QByteArray* response) c
|
||||
|
||||
netJob->addNetAction(Net::Upload::makeByteArray(QString("https://api.curseforge.com/v1/mods/files"), response, body_raw));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response] { delete response; });
|
||||
QObject::connect(netJob.get(), &NetJob::failed, [body_raw] { qDebug() << body_raw; });
|
||||
|
||||
return netJob;
|
||||
|
@ -4,7 +4,10 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <memory>
|
||||
#include "modplatform/ModIndex.h"
|
||||
#include "modplatform/ResourceAPI.h"
|
||||
#include "modplatform/helpers/NetworkResourceAPI.h"
|
||||
|
||||
class FlameAPI : public NetworkResourceAPI {
|
||||
@ -14,9 +17,9 @@ class FlameAPI : public NetworkResourceAPI {
|
||||
|
||||
auto getLatestVersion(VersionSearchArgs&& args) -> ModPlatform::IndexedVersion;
|
||||
|
||||
Task::Ptr getProjects(QStringList addonIds, QByteArray* response) const override;
|
||||
Task::Ptr matchFingerprints(const QList<uint>& fingerprints, QByteArray* response);
|
||||
Task::Ptr getFiles(const QStringList& fileIds, QByteArray* response) const;
|
||||
Task::Ptr getProjects(QStringList addonIds, std::shared_ptr<QByteArray> response) const override;
|
||||
Task::Ptr matchFingerprints(const QList<uint>& fingerprints, std::shared_ptr<QByteArray> response);
|
||||
Task::Ptr getFiles(const QStringList& fileIds, std::shared_ptr<QByteArray> response) const;
|
||||
|
||||
[[nodiscard]] auto getSortingMethods() const -> QList<ResourceAPI::SortingMethod> override;
|
||||
|
||||
@ -48,7 +51,8 @@ class FlameAPI : public NetworkResourceAPI {
|
||||
private:
|
||||
[[nodiscard]] std::optional<QString> getSearchURL(SearchArgs const& args) const override
|
||||
{
|
||||
auto gameVersionStr = args.versions.has_value() ? QString("gameVersion=%1").arg(args.versions.value().front().toString()) : QString();
|
||||
auto gameVersionStr =
|
||||
args.versions.has_value() ? QString("gameVersion=%1").arg(args.versions.value().front().toString()) : QString();
|
||||
|
||||
QStringList get_arguments;
|
||||
get_arguments.append(QString("classId=%1").arg(getClassId(args.type)));
|
||||
@ -73,14 +77,44 @@ class FlameAPI : public NetworkResourceAPI {
|
||||
|
||||
[[nodiscard]] std::optional<QString> getVersionsURL(VersionSearchArgs const& args) const override
|
||||
{
|
||||
QString url{QString("https://api.curseforge.com/v1/mods/%1/files?pageSize=10000&").arg(args.pack.addonId.toString())};
|
||||
auto mappedModLoader = getMappedModLoader(args.loaders.value());
|
||||
auto addonId = args.pack.addonId.toString();
|
||||
if (args.loaders.value() & Quilt) {
|
||||
auto overide = ModPlatform::getOverrideDeps();
|
||||
auto over = std::find_if(overide.cbegin(), overide.cend(), [addonId](auto dep) {
|
||||
return dep.provider == ModPlatform::ResourceProvider::FLAME && addonId == dep.quilt;
|
||||
});
|
||||
if (over != overide.cend()) {
|
||||
mappedModLoader = 5;
|
||||
}
|
||||
}
|
||||
QString url{ QString("https://api.curseforge.com/v1/mods/%1/files?pageSize=10000&").arg(addonId) };
|
||||
|
||||
QStringList get_parameters;
|
||||
if (args.mcVersions.has_value())
|
||||
get_parameters.append(QString("gameVersion=%1").arg(args.mcVersions.value().front().toString()));
|
||||
if (args.loaders.has_value())
|
||||
get_parameters.append(QString("modLoaderType=%1").arg(getMappedModLoader(args.loaders.value())));
|
||||
get_parameters.append(QString("modLoaderType=%1").arg(mappedModLoader));
|
||||
|
||||
return url + get_parameters.join('&');
|
||||
};
|
||||
|
||||
[[nodiscard]] std::optional<QString> getDependencyURL(DependencySearchArgs const& args) const override
|
||||
{
|
||||
auto mappedModLoader = getMappedModLoader(args.loader);
|
||||
auto addonId = args.dependency.addonId.toString();
|
||||
if (args.loader & Quilt) {
|
||||
auto overide = ModPlatform::getOverrideDeps();
|
||||
auto over = std::find_if(overide.cbegin(), overide.cend(), [addonId](auto dep) {
|
||||
return dep.provider == ModPlatform::ResourceProvider::FLAME && addonId == dep.quilt;
|
||||
});
|
||||
if (over != overide.cend()) {
|
||||
mappedModLoader = 5;
|
||||
}
|
||||
}
|
||||
return QString("https://api.curseforge.com/v1/mods/%1/files?pageSize=10000&gameVersion=%2&modLoaderType=%3")
|
||||
.arg(addonId)
|
||||
.arg(args.mcVersion.toString())
|
||||
.arg(mappedModLoader);
|
||||
};
|
||||
};
|
||||
|
@ -31,7 +31,7 @@ ModPlatform::IndexedPack getProjectInfo(ModPlatform::IndexedVersion& ver_info)
|
||||
|
||||
auto get_project_job = new NetJob("Flame::GetProjectJob", APPLICATION->network());
|
||||
|
||||
auto response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
auto url = QString("https://api.curseforge.com/v1/mods/%1").arg(ver_info.addonId.toString());
|
||||
auto dl = Net::Download::makeByteArray(url, response);
|
||||
get_project_job->addNetAction(dl);
|
||||
@ -75,7 +75,7 @@ ModPlatform::IndexedVersion getFileInfo(int addonId, int fileId)
|
||||
|
||||
auto get_file_info_job = new NetJob("Flame::GetFileInfoJob", APPLICATION->network());
|
||||
|
||||
auto response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
auto url = QString("https://api.curseforge.com/v1/mods/%1/files/%2").arg(QString::number(addonId), QString::number(fileId));
|
||||
auto dl = Net::Download::makeByteArray(url, response);
|
||||
get_file_info_job->addNetAction(dl);
|
||||
|
@ -182,7 +182,7 @@ bool FlameCreationTask::updateInstance()
|
||||
fileIds.append(QString::number(file.fileId));
|
||||
}
|
||||
|
||||
auto* raw_response = new QByteArray;
|
||||
auto raw_response = std::make_shared<QByteArray>();
|
||||
auto job = api.getFiles(fileIds, raw_response);
|
||||
|
||||
QEventLoop loop;
|
||||
|
@ -136,8 +136,61 @@ auto FlameMod::loadIndexedPackVersion(QJsonObject& obj, bool load_changelog) ->
|
||||
}
|
||||
}
|
||||
|
||||
auto dependencies = Json::ensureArray(obj, "dependencies");
|
||||
for (auto d : dependencies) {
|
||||
auto dep = Json::ensureObject(d);
|
||||
ModPlatform::Dependency dependency;
|
||||
dependency.addonId = Json::requireInteger(dep, "modId");
|
||||
switch (Json::requireInteger(dep, "relationType")) {
|
||||
case 1: // EmbeddedLibrary
|
||||
dependency.type = ModPlatform::DependencyType::EMBEDDED;
|
||||
break;
|
||||
case 2: // OptionalDependency
|
||||
dependency.type = ModPlatform::DependencyType::OPTIONAL;
|
||||
break;
|
||||
case 3: // RequiredDependency
|
||||
dependency.type = ModPlatform::DependencyType::REQUIRED;
|
||||
break;
|
||||
case 4: // Tool
|
||||
dependency.type = ModPlatform::DependencyType::TOOL;
|
||||
break;
|
||||
case 5: // Incompatible
|
||||
dependency.type = ModPlatform::DependencyType::INCOMPATIBLE;
|
||||
break;
|
||||
case 6: // Include
|
||||
dependency.type = ModPlatform::DependencyType::INCLUDE;
|
||||
break;
|
||||
default:
|
||||
dependency.type = ModPlatform::DependencyType::UNKNOWN;
|
||||
break;
|
||||
}
|
||||
file.dependencies.append(dependency);
|
||||
}
|
||||
|
||||
if (load_changelog)
|
||||
file.changelog = api.getModFileChangelog(file.addonId.toInt(), file.fileId.toInt());
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
ModPlatform::IndexedVersion FlameMod::loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr)
|
||||
{
|
||||
QVector<ModPlatform::IndexedVersion> versions;
|
||||
for (auto versionIter : arr) {
|
||||
auto obj = versionIter.toObject();
|
||||
|
||||
auto file = loadIndexedPackVersion(obj);
|
||||
if (!file.addonId.isValid())
|
||||
file.addonId = m.addonId;
|
||||
|
||||
if (file.fileId.isValid()) // Heuristic to check if the returned value is valid
|
||||
versions.append(file);
|
||||
}
|
||||
|
||||
auto orderSortPredicate = [](const ModPlatform::IndexedVersion& a, const ModPlatform::IndexedVersion& b) -> bool {
|
||||
// dates are in RFC 3339 format
|
||||
return a.date > b.date;
|
||||
};
|
||||
std::sort(versions.begin(), versions.end(), orderSortPredicate);
|
||||
return versions.front();
|
||||
};
|
||||
|
@ -6,8 +6,8 @@
|
||||
|
||||
#include "modplatform/ModIndex.h"
|
||||
|
||||
#include "BaseInstance.h"
|
||||
#include <QNetworkAccessManager>
|
||||
#include "BaseInstance.h"
|
||||
|
||||
namespace FlameMod {
|
||||
|
||||
@ -19,5 +19,5 @@ void loadIndexedPackVersions(ModPlatform::IndexedPack& pack,
|
||||
const shared_qobject_ptr<QNetworkAccessManager>& network,
|
||||
const BaseInstance* inst);
|
||||
auto loadIndexedPackVersion(QJsonObject& obj, bool load_changelog = false) -> ModPlatform::IndexedVersion;
|
||||
|
||||
auto loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr) -> ModPlatform::IndexedVersion;
|
||||
} // namespace FlameMod
|
@ -4,6 +4,7 @@
|
||||
#include <QMetaType>
|
||||
#include <QString>
|
||||
#include <QVector>
|
||||
#include "modplatform/ModIndex.h"
|
||||
|
||||
namespace Flame {
|
||||
|
||||
@ -27,8 +28,7 @@ struct ModpackExtra {
|
||||
QString sourceUrl;
|
||||
};
|
||||
|
||||
struct IndexedPack
|
||||
{
|
||||
struct IndexedPack {
|
||||
int addonId;
|
||||
QString name;
|
||||
QString description;
|
||||
@ -46,6 +46,6 @@ struct IndexedPack
|
||||
void loadIndexedPack(IndexedPack& m, QJsonObject& obj);
|
||||
void loadIndexedInfo(IndexedPack&, QJsonObject&);
|
||||
void loadIndexedPackVersions(IndexedPack& m, QJsonArray& arr);
|
||||
}
|
||||
} // namespace Flame
|
||||
|
||||
Q_DECLARE_METATYPE(Flame::IndexedPack)
|
||||
|
@ -71,6 +71,7 @@ void ModrinthHasher::executeTask()
|
||||
emitFailed("Empty hash!");
|
||||
} else {
|
||||
emitSucceeded();
|
||||
emit resultsReady(m_hash);
|
||||
}
|
||||
}
|
||||
|
||||
@ -88,12 +89,12 @@ void FlameHasher::executeTask()
|
||||
emitFailed("Empty hash!");
|
||||
} else {
|
||||
emitSucceeded();
|
||||
emit resultsReady(m_hash);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
BlockedModHasher::BlockedModHasher(QString file_path, ModPlatform::ResourceProvider provider)
|
||||
: Hasher(file_path), provider(provider) {
|
||||
BlockedModHasher::BlockedModHasher(QString file_path, ModPlatform::ResourceProvider provider) : Hasher(file_path), provider(provider)
|
||||
{
|
||||
setObjectName(QString("BlockedModHasher: %1").arg(file_path));
|
||||
hash_type = ProviderCaps.hashType(provider).first();
|
||||
}
|
||||
@ -120,14 +121,17 @@ void BlockedModHasher::executeTask()
|
||||
emitFailed("Empty hash!");
|
||||
} else {
|
||||
emitSucceeded();
|
||||
emit resultsReady(m_hash);
|
||||
}
|
||||
}
|
||||
|
||||
QStringList BlockedModHasher::getHashTypes() {
|
||||
QStringList BlockedModHasher::getHashTypes()
|
||||
{
|
||||
return ProviderCaps.hashType(provider);
|
||||
}
|
||||
|
||||
bool BlockedModHasher::useHashType(QString type) {
|
||||
bool BlockedModHasher::useHashType(QString type)
|
||||
{
|
||||
auto types = ProviderCaps.hashType(provider);
|
||||
if (types.contains(type)) {
|
||||
hash_type = type;
|
||||
|
@ -8,6 +8,7 @@
|
||||
namespace Hashing {
|
||||
|
||||
class Hasher : public Task {
|
||||
Q_OBJECT
|
||||
public:
|
||||
using Ptr = shared_qobject_ptr<Hasher>;
|
||||
|
||||
@ -21,6 +22,9 @@ class Hasher : public Task {
|
||||
QString getResult() const { return m_hash; };
|
||||
QString getPath() const { return m_path; };
|
||||
|
||||
signals:
|
||||
void resultsReady(QString hash);
|
||||
|
||||
protected:
|
||||
QString m_hash;
|
||||
QString m_path;
|
||||
@ -48,6 +52,7 @@ class BlockedModHasher : public Hasher {
|
||||
|
||||
QStringList getHashTypes();
|
||||
bool useHashType(QString type);
|
||||
|
||||
private:
|
||||
ModPlatform::ResourceProvider provider;
|
||||
QString hash_type;
|
||||
|
@ -3,6 +3,7 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
#include "NetworkResourceAPI.h"
|
||||
#include <memory>
|
||||
|
||||
#include "Application.h"
|
||||
#include "net/NetJob.h"
|
||||
@ -19,7 +20,7 @@ Task::Ptr NetworkResourceAPI::searchProjects(SearchArgs&& args, SearchCallbacks&
|
||||
|
||||
auto search_url = search_url_optional.value();
|
||||
|
||||
auto response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
auto netJob = makeShared<NetJob>(QString("%1::Search").arg(debugName()), APPLICATION->network());
|
||||
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(search_url), response));
|
||||
@ -47,20 +48,14 @@ Task::Ptr NetworkResourceAPI::searchProjects(SearchArgs&& args, SearchCallbacks&
|
||||
|
||||
callbacks.on_fail(reason, network_error_code);
|
||||
});
|
||||
QObject::connect(netJob.get(), &NetJob::aborted, [callbacks]{
|
||||
callbacks.on_abort();
|
||||
});
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response] {
|
||||
delete response;
|
||||
});
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::aborted, [callbacks] { callbacks.on_abort(); });
|
||||
|
||||
return netJob;
|
||||
}
|
||||
|
||||
Task::Ptr NetworkResourceAPI::getProjectInfo(ProjectInfoArgs&& args, ProjectInfoCallbacks&& callbacks) const
|
||||
{
|
||||
auto response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
auto job = getProject(args.pack.addonId.toString(), response);
|
||||
|
||||
QObject::connect(job.get(), &NetJob::succeeded, [response, callbacks, args] {
|
||||
@ -88,7 +83,7 @@ Task::Ptr NetworkResourceAPI::getProjectVersions(VersionSearchArgs&& args, Versi
|
||||
auto versions_url = versions_url_optional.value();
|
||||
|
||||
auto netJob = makeShared<NetJob>(QString("%1::Versions").arg(args.pack.name), APPLICATION->network());
|
||||
auto response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
|
||||
netJob->addNetAction(Net::Download::makeByteArray(versions_url, response));
|
||||
|
||||
@ -105,14 +100,10 @@ Task::Ptr NetworkResourceAPI::getProjectVersions(VersionSearchArgs&& args, Versi
|
||||
callbacks.on_succeed(doc, args.pack);
|
||||
});
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response] {
|
||||
delete response;
|
||||
});
|
||||
|
||||
return netJob;
|
||||
}
|
||||
|
||||
Task::Ptr NetworkResourceAPI::getProject(QString addonId, QByteArray* response) const
|
||||
Task::Ptr NetworkResourceAPI::getProject(QString addonId, std::shared_ptr<QByteArray> response) const
|
||||
{
|
||||
auto project_url_optional = getInfoURL(addonId);
|
||||
if (!project_url_optional.has_value())
|
||||
@ -124,9 +115,34 @@ Task::Ptr NetworkResourceAPI::getProject(QString addonId, QByteArray* response)
|
||||
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(project_url), response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response] {
|
||||
delete response;
|
||||
return netJob;
|
||||
}
|
||||
|
||||
Task::Ptr NetworkResourceAPI::getDependencyVersion(DependencySearchArgs&& args, DependencySearchCallbacks&& callbacks) const
|
||||
{
|
||||
auto versions_url_optional = getDependencyURL(args);
|
||||
if (!versions_url_optional.has_value())
|
||||
return nullptr;
|
||||
|
||||
auto versions_url = versions_url_optional.value();
|
||||
|
||||
auto netJob = makeShared<NetJob>(QString("%1::Dependency").arg(args.dependency.addonId.toString()), APPLICATION->network());
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
|
||||
netJob->addNetAction(Net::Download::makeByteArray(versions_url, response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, [=] {
|
||||
QJsonParseError parse_error{};
|
||||
QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error);
|
||||
if (parse_error.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response for getting versions at " << parse_error.offset
|
||||
<< " reason: " << parse_error.errorString();
|
||||
qWarning() << *response;
|
||||
return;
|
||||
}
|
||||
|
||||
callbacks.on_succeed(doc, args.dependency);
|
||||
});
|
||||
|
||||
return netJob;
|
||||
}
|
||||
};
|
||||
|
@ -4,19 +4,22 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include "modplatform/ResourceAPI.h"
|
||||
|
||||
class NetworkResourceAPI : public ResourceAPI {
|
||||
public:
|
||||
Task::Ptr searchProjects(SearchArgs&&, SearchCallbacks&&) const override;
|
||||
|
||||
Task::Ptr getProject(QString addonId, QByteArray* response) const override;
|
||||
Task::Ptr getProject(QString addonId, std::shared_ptr<QByteArray> response) const override;
|
||||
|
||||
Task::Ptr getProjectInfo(ProjectInfoArgs&&, ProjectInfoCallbacks&&) const override;
|
||||
Task::Ptr getProjectVersions(VersionSearchArgs&&, VersionSearchCallbacks&&) const override;
|
||||
Task::Ptr getDependencyVersion(DependencySearchArgs&&, DependencySearchCallbacks&&) const override;
|
||||
|
||||
protected:
|
||||
[[nodiscard]] virtual auto getSearchURL(SearchArgs const& args) const -> std::optional<QString> = 0;
|
||||
[[nodiscard]] virtual auto getInfoURL(QString const& id) const -> std::optional<QString> = 0;
|
||||
[[nodiscard]] virtual auto getVersionsURL(VersionSearchArgs const& args) const -> std::optional<QString> = 0;
|
||||
[[nodiscard]] virtual auto getDependencyURL(DependencySearchArgs const& args) const -> std::optional<QString> = 0;
|
||||
};
|
||||
|
@ -51,11 +51,11 @@ void PackFetchTask::fetch()
|
||||
|
||||
QUrl publicPacksUrl = QUrl(BuildConfig.LEGACY_FTB_CDN_BASE_URL + "static/modpacks.xml");
|
||||
qDebug() << "Downloading public version info from" << publicPacksUrl.toString();
|
||||
jobPtr->addNetAction(Net::Download::makeByteArray(publicPacksUrl, &publicModpacksXmlFileData));
|
||||
jobPtr->addNetAction(Net::Download::makeByteArray(publicPacksUrl, publicModpacksXmlFileData));
|
||||
|
||||
QUrl thirdPartyUrl = QUrl(BuildConfig.LEGACY_FTB_CDN_BASE_URL + "static/thirdparty.xml");
|
||||
qDebug() << "Downloading thirdparty version info from" << thirdPartyUrl.toString();
|
||||
jobPtr->addNetAction(Net::Download::makeByteArray(thirdPartyUrl, &thirdPartyModpacksXmlFileData));
|
||||
jobPtr->addNetAction(Net::Download::makeByteArray(thirdPartyUrl, thirdPartyModpacksXmlFileData));
|
||||
|
||||
QObject::connect(jobPtr.get(), &NetJob::succeeded, this, &PackFetchTask::fileDownloadFinished);
|
||||
QObject::connect(jobPtr.get(), &NetJob::failed, this, &PackFetchTask::fileDownloadFailed);
|
||||
@ -68,18 +68,15 @@ void PackFetchTask::fetchPrivate(const QStringList & toFetch)
|
||||
{
|
||||
QString privatePackBaseUrl = BuildConfig.LEGACY_FTB_CDN_BASE_URL + "static/%1.xml";
|
||||
|
||||
for (auto &packCode: toFetch)
|
||||
{
|
||||
QByteArray *data = new QByteArray();
|
||||
for (auto& packCode : toFetch) {
|
||||
auto data = std::make_shared<QByteArray>();
|
||||
NetJob* job = new NetJob("Fetching private pack", m_network);
|
||||
job->addNetAction(Net::Download::makeByteArray(privatePackBaseUrl.arg(packCode), data));
|
||||
|
||||
QObject::connect(job, &NetJob::succeeded, this, [this, job, data, packCode]
|
||||
{
|
||||
QObject::connect(job, &NetJob::succeeded, this, [this, job, data, packCode] {
|
||||
ModpackList packs;
|
||||
parseAndAddPacks(*data, PackType::Private, packs);
|
||||
foreach(Modpack currentPack, packs)
|
||||
{
|
||||
foreach (Modpack currentPack, packs) {
|
||||
currentPack.packCode = packCode;
|
||||
emit privateFileDownloadFinished(currentPack);
|
||||
}
|
||||
@ -87,16 +84,13 @@ void PackFetchTask::fetchPrivate(const QStringList & toFetch)
|
||||
job->deleteLater();
|
||||
|
||||
data->clear();
|
||||
delete data;
|
||||
});
|
||||
|
||||
QObject::connect(job, &NetJob::failed, this, [this, job, packCode, data](QString reason)
|
||||
{
|
||||
QObject::connect(job, &NetJob::failed, this, [this, job, packCode, data](QString reason) {
|
||||
emit privateFileDownloadFailed(reason, packCode);
|
||||
job->deleteLater();
|
||||
|
||||
data->clear();
|
||||
delete data;
|
||||
});
|
||||
|
||||
QObject::connect(job, &NetJob::aborted, this, [this, job, data] {
|
||||
@ -104,7 +98,6 @@ void PackFetchTask::fetchPrivate(const QStringList & toFetch)
|
||||
job->deleteLater();
|
||||
|
||||
data->clear();
|
||||
delete data;
|
||||
});
|
||||
|
||||
job->start();
|
||||
@ -117,22 +110,17 @@ void PackFetchTask::fileDownloadFinished()
|
||||
|
||||
QStringList failedLists;
|
||||
|
||||
if(!parseAndAddPacks(publicModpacksXmlFileData, PackType::Public, publicPacks))
|
||||
{
|
||||
if (!parseAndAddPacks(*publicModpacksXmlFileData, PackType::Public, publicPacks)) {
|
||||
failedLists.append(tr("Public Packs"));
|
||||
}
|
||||
|
||||
if(!parseAndAddPacks(thirdPartyModpacksXmlFileData, PackType::ThirdParty, thirdPartyPacks))
|
||||
{
|
||||
if (!parseAndAddPacks(*thirdPartyModpacksXmlFileData, PackType::ThirdParty, thirdPartyPacks)) {
|
||||
failedLists.append(tr("Third Party Packs"));
|
||||
}
|
||||
|
||||
if(failedLists.size() > 0)
|
||||
{
|
||||
if (failedLists.size() > 0) {
|
||||
emit failed(tr("Failed to download some pack lists: %1").arg(failedLists.join("\n- ")));
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
emit finished(publicPacks, thirdPartyPacks);
|
||||
}
|
||||
}
|
||||
@ -145,8 +133,7 @@ bool PackFetchTask::parseAndAddPacks(QByteArray &data, PackType packType, Modpac
|
||||
int errorLine = -1;
|
||||
int errorCol = -1;
|
||||
|
||||
if(!doc.setContent(data, false, &errorMsg, &errorLine, &errorCol))
|
||||
{
|
||||
if (!doc.setContent(data, false, &errorMsg, &errorLine, &errorCol)) {
|
||||
auto fullErrMsg = QString("Failed to fetch modpack data: %1 %2:%3!").arg(errorMsg).arg(errorLine).arg(errorCol);
|
||||
qWarning() << fullErrMsg;
|
||||
data.clear();
|
||||
@ -154,8 +141,7 @@ bool PackFetchTask::parseAndAddPacks(QByteArray &data, PackType packType, Modpac
|
||||
}
|
||||
|
||||
QDomNodeList nodes = doc.elementsByTagName("modpack");
|
||||
for(int i = 0; i < nodes.length(); i++)
|
||||
{
|
||||
for (int i = 0; i < nodes.length(); i++) {
|
||||
QDomElement element = nodes.at(i).toElement();
|
||||
|
||||
Modpack modpack;
|
||||
@ -170,25 +156,19 @@ bool PackFetchTask::parseAndAddPacks(QByteArray &data, PackType packType, Modpac
|
||||
modpack.bugged = false;
|
||||
|
||||
// remove empty if the xml is bugged
|
||||
for(QString curr : modpack.oldVersions)
|
||||
{
|
||||
if(curr.isNull() || curr.isEmpty())
|
||||
{
|
||||
for (QString curr : modpack.oldVersions) {
|
||||
if (curr.isNull() || curr.isEmpty()) {
|
||||
modpack.oldVersions.removeAll(curr);
|
||||
modpack.bugged = true;
|
||||
qWarning() << "Removed some empty versions from" << modpack.name;
|
||||
}
|
||||
}
|
||||
|
||||
if(modpack.oldVersions.size() < 1)
|
||||
{
|
||||
if(!modpack.currentVersion.isNull() && !modpack.currentVersion.isEmpty())
|
||||
{
|
||||
if (modpack.oldVersions.size() < 1) {
|
||||
if (!modpack.currentVersion.isNull() && !modpack.currentVersion.isEmpty()) {
|
||||
modpack.oldVersions.append(modpack.currentVersion);
|
||||
qWarning() << "Added current version to oldVersions because oldVersions was empty! (" + modpack.name + ")";
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
modpack.broken = true;
|
||||
qWarning() << "Broken pack:" << modpack.name << " => No valid version!";
|
||||
}
|
||||
@ -218,4 +198,4 @@ void PackFetchTask::fileDownloadAborted()
|
||||
emit aborted();
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace LegacyFTB
|
||||
|
@ -1,15 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include "net/NetJob.h"
|
||||
#include <QTemporaryDir>
|
||||
#include <QByteArray>
|
||||
#include <QObject>
|
||||
#include <QTemporaryDir>
|
||||
#include <memory>
|
||||
#include "PackHelpers.h"
|
||||
#include "net/NetJob.h"
|
||||
|
||||
namespace LegacyFTB {
|
||||
|
||||
class PackFetchTask : public QObject {
|
||||
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
@ -23,8 +23,8 @@ private:
|
||||
shared_qobject_ptr<QNetworkAccessManager> m_network;
|
||||
NetJob::Ptr jobPtr;
|
||||
|
||||
QByteArray publicModpacksXmlFileData;
|
||||
QByteArray thirdPartyModpacksXmlFileData;
|
||||
std::shared_ptr<QByteArray> publicModpacksXmlFileData = std::make_shared<QByteArray>();
|
||||
std::shared_ptr<QByteArray> thirdPartyModpacksXmlFileData = std::make_shared<QByteArray>();
|
||||
|
||||
bool parseAndAddPacks(QByteArray& data, PackType packType, ModpackList& list);
|
||||
ModpackList publicPacks;
|
||||
@ -44,4 +44,4 @@ signals:
|
||||
void privateFileDownloadFailed(QString reason, QString packCode);
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace LegacyFTB
|
||||
|
@ -9,19 +9,17 @@
|
||||
#include "net/NetJob.h"
|
||||
#include "net/Upload.h"
|
||||
|
||||
Task::Ptr ModrinthAPI::currentVersion(QString hash, QString hash_format, QByteArray* response)
|
||||
Task::Ptr ModrinthAPI::currentVersion(QString hash, QString hash_format, std::shared_ptr<QByteArray> response)
|
||||
{
|
||||
auto netJob = makeShared<NetJob>(QString("Modrinth::GetCurrentVersion"), APPLICATION->network());
|
||||
|
||||
netJob->addNetAction(Net::Download::makeByteArray(
|
||||
QString(BuildConfig.MODRINTH_PROD_URL + "/version_file/%1?algorithm=%2").arg(hash, hash_format), response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response] { delete response; });
|
||||
|
||||
return netJob;
|
||||
}
|
||||
|
||||
Task::Ptr ModrinthAPI::currentVersions(const QStringList& hashes, QString hash_format, QByteArray* response)
|
||||
Task::Ptr ModrinthAPI::currentVersions(const QStringList& hashes, QString hash_format, std::shared_ptr<QByteArray> response)
|
||||
{
|
||||
auto netJob = makeShared<NetJob>(QString("Modrinth::GetCurrentVersions"), APPLICATION->network());
|
||||
|
||||
@ -35,8 +33,6 @@ Task::Ptr ModrinthAPI::currentVersions(const QStringList& hashes, QString hash_f
|
||||
|
||||
netJob->addNetAction(Net::Upload::makeByteArray(QString(BuildConfig.MODRINTH_PROD_URL + "/version_files"), response, body_raw));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response] { delete response; });
|
||||
|
||||
return netJob;
|
||||
}
|
||||
|
||||
@ -44,7 +40,7 @@ Task::Ptr ModrinthAPI::latestVersion(QString hash,
|
||||
QString hash_format,
|
||||
std::optional<std::list<Version>> mcVersions,
|
||||
std::optional<ModLoaderTypes> loaders,
|
||||
QByteArray* response)
|
||||
std::shared_ptr<QByteArray> response)
|
||||
{
|
||||
auto netJob = makeShared<NetJob>(QString("Modrinth::GetLatestVersion"), APPLICATION->network());
|
||||
|
||||
@ -67,8 +63,6 @@ Task::Ptr ModrinthAPI::latestVersion(QString hash,
|
||||
netJob->addNetAction(Net::Upload::makeByteArray(
|
||||
QString(BuildConfig.MODRINTH_PROD_URL + "/version_file/%1/update?algorithm=%2").arg(hash, hash_format), response, body_raw));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response] { delete response; });
|
||||
|
||||
return netJob;
|
||||
}
|
||||
|
||||
@ -76,7 +70,7 @@ Task::Ptr ModrinthAPI::latestVersions(const QStringList& hashes,
|
||||
QString hash_format,
|
||||
std::optional<std::list<Version>> mcVersions,
|
||||
std::optional<ModLoaderTypes> loaders,
|
||||
QByteArray* response)
|
||||
std::shared_ptr<QByteArray> response)
|
||||
{
|
||||
auto netJob = makeShared<NetJob>(QString("Modrinth::GetLatestVersions"), APPLICATION->network());
|
||||
|
||||
@ -101,22 +95,16 @@ Task::Ptr ModrinthAPI::latestVersions(const QStringList& hashes,
|
||||
|
||||
netJob->addNetAction(Net::Upload::makeByteArray(QString(BuildConfig.MODRINTH_PROD_URL + "/version_files/update"), response, body_raw));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response] { delete response; });
|
||||
|
||||
return netJob;
|
||||
}
|
||||
|
||||
Task::Ptr ModrinthAPI::getProjects(QStringList addonIds, QByteArray* response) const
|
||||
Task::Ptr ModrinthAPI::getProjects(QStringList addonIds, std::shared_ptr<QByteArray> response) const
|
||||
{
|
||||
auto netJob = makeShared<NetJob>(QString("Modrinth::GetProjects"), APPLICATION->network());
|
||||
auto searchUrl = getMultipleModInfoURL(addonIds);
|
||||
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchUrl), response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::finished, [response, netJob] {
|
||||
delete response;
|
||||
});
|
||||
|
||||
return netJob;
|
||||
}
|
||||
|
||||
|
@ -12,27 +12,23 @@
|
||||
|
||||
class ModrinthAPI : public NetworkResourceAPI {
|
||||
public:
|
||||
auto currentVersion(QString hash,
|
||||
QString hash_format,
|
||||
QByteArray* response) -> Task::Ptr;
|
||||
auto currentVersion(QString hash, QString hash_format, std::shared_ptr<QByteArray> response) -> Task::Ptr;
|
||||
|
||||
auto currentVersions(const QStringList& hashes,
|
||||
QString hash_format,
|
||||
QByteArray* response) -> Task::Ptr;
|
||||
auto currentVersions(const QStringList& hashes, QString hash_format, std::shared_ptr<QByteArray> response) -> Task::Ptr;
|
||||
|
||||
auto latestVersion(QString hash,
|
||||
QString hash_format,
|
||||
std::optional<std::list<Version>> mcVersions,
|
||||
std::optional<ModLoaderTypes> loaders,
|
||||
QByteArray* response) -> Task::Ptr;
|
||||
std::shared_ptr<QByteArray> response) -> Task::Ptr;
|
||||
|
||||
auto latestVersions(const QStringList& hashes,
|
||||
QString hash_format,
|
||||
std::optional<std::list<Version>> mcVersions,
|
||||
std::optional<ModLoaderTypes> loaders,
|
||||
QByteArray* response) -> Task::Ptr;
|
||||
std::shared_ptr<QByteArray> response) -> Task::Ptr;
|
||||
|
||||
Task::Ptr getProjects(QStringList addonIds, QByteArray* response) const override;
|
||||
Task::Ptr getProjects(QStringList addonIds, std::shared_ptr<QByteArray> response) const override;
|
||||
|
||||
public:
|
||||
[[nodiscard]] auto getSortingMethods() const -> QList<ResourceAPI::SortingMethod> override;
|
||||
@ -55,8 +51,7 @@ class ModrinthAPI : public NetworkResourceAPI {
|
||||
static auto getModLoaderFilters(ModLoaderTypes types) -> const QString
|
||||
{
|
||||
QStringList l;
|
||||
for (auto loader : getModLoaderStrings(types))
|
||||
{
|
||||
for (auto loader : getModLoaderStrings(types)) {
|
||||
l << QString("\"categories:%1\"").arg(loader);
|
||||
}
|
||||
return l.join(',');
|
||||
@ -146,9 +141,15 @@ class ModrinthAPI : public NetworkResourceAPI {
|
||||
return s.isEmpty() ? QString() : s;
|
||||
}
|
||||
|
||||
inline auto validateModLoaders(ModLoaderTypes loaders) const -> bool
|
||||
{
|
||||
return loaders & (Forge | Fabric | Quilt);
|
||||
}
|
||||
inline auto validateModLoaders(ModLoaderTypes loaders) const -> bool { return loaders & (Forge | Fabric | Quilt); }
|
||||
|
||||
[[nodiscard]] std::optional<QString> getDependencyURL(DependencySearchArgs const& args) const override
|
||||
{
|
||||
return args.dependency.version.length() != 0 ? QString("%1/version/%2").arg(BuildConfig.MODRINTH_PROD_URL, args.dependency.version)
|
||||
: QString("%1/project/%2/version?game_versions=[\"%3\"]&loaders=[\"%4\"]")
|
||||
.arg(BuildConfig.MODRINTH_PROD_URL)
|
||||
.arg(args.dependency.addonId.toString())
|
||||
.arg(args.mcVersion.toString())
|
||||
.arg(getModLoaderStrings(args.loader).join("\",\""));
|
||||
};
|
||||
};
|
||||
|
@ -53,12 +53,11 @@ void ModrinthCheckUpdate::executeTask()
|
||||
// (though it will rarely happen, if at all)
|
||||
if (mod->metadata()->hash_format != best_hash_type) {
|
||||
auto hash_task = Hashing::createModrinthHasher(mod->fileinfo().absoluteFilePath());
|
||||
connect(hash_task.get(), &Task::succeeded, [&] {
|
||||
QString hash(hash_task->getResult());
|
||||
connect(hash_task.get(), &Hashing::Hasher::resultsReady, [&hashes, &mappings, mod](QString hash) {
|
||||
hashes.append(hash);
|
||||
mappings.insert(hash, mod);
|
||||
});
|
||||
connect(hash_task.get(), &Task::failed, [this, hash_task] { failed("Failed to generate hash"); });
|
||||
connect(hash_task.get(), &Task::failed, [this] { failed("Failed to generate hash"); });
|
||||
hashing_task.addTask(hash_task);
|
||||
} else {
|
||||
hashes.append(hash);
|
||||
@ -71,7 +70,7 @@ void ModrinthCheckUpdate::executeTask()
|
||||
hashing_task.start();
|
||||
loop.exec();
|
||||
|
||||
auto* response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
auto job = api.latestVersions(hashes, best_hash_type, m_game_versions, m_loaders, response);
|
||||
|
||||
QEventLoop lock;
|
||||
|
@ -214,7 +214,7 @@ bool ModrinthCreationTask::createInstance()
|
||||
|
||||
if (m_instIcon != "default") {
|
||||
instance.setIconKey(m_instIcon);
|
||||
} else {
|
||||
} else if (!m_managed_id.isEmpty()) {
|
||||
instance.setIconKey("modrinth");
|
||||
}
|
||||
|
||||
|
@ -134,8 +134,8 @@ void ModrinthPackExportTask::collectHashes()
|
||||
QCryptographicHash sha1(QCryptographicHash::Algorithm::Sha1);
|
||||
sha1.addData(data);
|
||||
|
||||
ResolvedFile file{ sha1.result().toHex(), sha512.result().toHex(), url.toString(), openFile.size() };
|
||||
resolvedFiles[relative] = file;
|
||||
ResolvedFile resolvedFile{ sha1.result().toHex(), sha512.result().toHex(), url.toEncoded(), openFile.size() };
|
||||
resolvedFiles[relative] = resolvedFile;
|
||||
|
||||
// nice! we've managed to resolve based on local metadata!
|
||||
// no need to enqueue it
|
||||
@ -157,7 +157,7 @@ void ModrinthPackExportTask::makeApiRequest()
|
||||
if (pendingHashes.isEmpty())
|
||||
buildZip();
|
||||
else {
|
||||
QByteArray* response = new QByteArray;
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
task = api.currentVersions(pendingHashes.values(), "sha512", response);
|
||||
connect(task.get(), &NetJob::succeeded, [this, response]() { parseApiResponse(response); });
|
||||
connect(task.get(), &NetJob::failed, this, &ModrinthPackExportTask::emitFailed);
|
||||
@ -165,7 +165,7 @@ void ModrinthPackExportTask::makeApiRequest()
|
||||
}
|
||||
}
|
||||
|
||||
void ModrinthPackExportTask::parseApiResponse(const QByteArray* response)
|
||||
void ModrinthPackExportTask::parseApiResponse(const std::shared_ptr<QByteArray> response)
|
||||
{
|
||||
task = nullptr;
|
||||
|
||||
|
@ -69,7 +69,7 @@ class ModrinthPackExportTask : public Task {
|
||||
void collectFiles();
|
||||
void collectHashes();
|
||||
void makeApiRequest();
|
||||
void parseApiResponse(const QByteArray* response);
|
||||
void parseApiResponse(const std::shared_ptr<QByteArray> response);
|
||||
void buildZip();
|
||||
void finish();
|
||||
|
||||
|
@ -22,7 +22,7 @@
|
||||
#include "Json.h"
|
||||
#include "minecraft/MinecraftInstance.h"
|
||||
#include "minecraft/PackProfile.h"
|
||||
#include "net/NetJob.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
|
||||
static ModrinthAPI api;
|
||||
static ModPlatform::ProviderCapabilities ProviderCaps;
|
||||
@ -140,6 +140,28 @@ auto Modrinth::loadIndexedPackVersion(QJsonObject& obj, QString preferred_hash_t
|
||||
file.version_number = Json::requireString(obj, "version_number");
|
||||
file.changelog = Json::requireString(obj, "changelog");
|
||||
|
||||
auto dependencies = Json::ensureArray(obj, "dependencies");
|
||||
for (auto d : dependencies) {
|
||||
auto dep = Json::ensureObject(d);
|
||||
ModPlatform::Dependency dependency;
|
||||
dependency.addonId = Json::ensureString(dep, "project_id");
|
||||
dependency.version = Json::ensureString(dep, "version_id");
|
||||
auto depType = Json::requireString(dep, "dependency_type");
|
||||
|
||||
if (depType == "required")
|
||||
dependency.type = ModPlatform::DependencyType::REQUIRED;
|
||||
else if (depType == "optional")
|
||||
dependency.type = ModPlatform::DependencyType::OPTIONAL;
|
||||
else if (depType == "incompatible")
|
||||
dependency.type = ModPlatform::DependencyType::INCOMPATIBLE;
|
||||
else if (depType == "embedded")
|
||||
dependency.type = ModPlatform::DependencyType::EMBEDDED;
|
||||
else
|
||||
dependency.type = ModPlatform::DependencyType::UNKNOWN;
|
||||
|
||||
file.dependencies.append(dependency);
|
||||
}
|
||||
|
||||
auto files = Json::requireArray(obj, "files");
|
||||
int i = 0;
|
||||
|
||||
@ -195,3 +217,22 @@ auto Modrinth::loadIndexedPackVersion(QJsonObject& obj, QString preferred_hash_t
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
auto Modrinth::loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr) -> ModPlatform::IndexedVersion
|
||||
{
|
||||
QVector<ModPlatform::IndexedVersion> versions;
|
||||
|
||||
for (auto versionIter : arr) {
|
||||
auto obj = versionIter.toObject();
|
||||
auto file = loadIndexedPackVersion(obj);
|
||||
|
||||
if (file.fileId.isValid()) // Heuristic to check if the returned value is valid
|
||||
versions.append(file);
|
||||
}
|
||||
auto orderSortPredicate = [](const ModPlatform::IndexedVersion& a, const ModPlatform::IndexedVersion& b) -> bool {
|
||||
// dates are in RFC 3339 format
|
||||
return a.date > b.date;
|
||||
};
|
||||
std::sort(versions.begin(), versions.end(), orderSortPredicate);
|
||||
return versions.length() != 0 ? versions.front() : ModPlatform::IndexedVersion();
|
||||
}
|
@ -19,8 +19,8 @@
|
||||
|
||||
#include "modplatform/ModIndex.h"
|
||||
|
||||
#include "BaseInstance.h"
|
||||
#include <QNetworkAccessManager>
|
||||
#include "BaseInstance.h"
|
||||
|
||||
namespace Modrinth {
|
||||
|
||||
@ -31,5 +31,6 @@ void loadIndexedPackVersions(ModPlatform::IndexedPack& pack,
|
||||
const shared_qobject_ptr<QNetworkAccessManager>& network,
|
||||
const BaseInstance* inst);
|
||||
auto loadIndexedPackVersion(QJsonObject& obj, QString hash_type = "sha512", QString filename_prefer = "") -> ModPlatform::IndexedVersion;
|
||||
auto loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr) -> ModPlatform::IndexedVersion;
|
||||
|
||||
} // namespace Modrinth
|
||||
|
@ -37,20 +37,19 @@
|
||||
|
||||
#include <FileSystem.h>
|
||||
#include <Json.h>
|
||||
#include <QtConcurrentRun>
|
||||
#include <MMCZip.h>
|
||||
#include <QtConcurrentRun>
|
||||
|
||||
#include "TechnicPackProcessor.h"
|
||||
#include "SolderPackManifest.h"
|
||||
#include "TechnicPackProcessor.h"
|
||||
#include "net/ChecksumValidator.h"
|
||||
|
||||
Technic::SolderPackInstallTask::SolderPackInstallTask(
|
||||
shared_qobject_ptr<QNetworkAccessManager> network,
|
||||
Technic::SolderPackInstallTask::SolderPackInstallTask(shared_qobject_ptr<QNetworkAccessManager> network,
|
||||
const QUrl& solderUrl,
|
||||
const QString& pack,
|
||||
const QString& version,
|
||||
const QString &minecraftVersion
|
||||
) {
|
||||
const QString& minecraftVersion)
|
||||
{
|
||||
m_solderUrl = solderUrl;
|
||||
m_pack = pack;
|
||||
m_version = version;
|
||||
@ -58,9 +57,9 @@ Technic::SolderPackInstallTask::SolderPackInstallTask(
|
||||
m_minecraftVersion = minecraftVersion;
|
||||
}
|
||||
|
||||
bool Technic::SolderPackInstallTask::abort() {
|
||||
if(m_abortable)
|
||||
bool Technic::SolderPackInstallTask::abort()
|
||||
{
|
||||
if (m_abortable) {
|
||||
return m_filesNetJob->abort();
|
||||
}
|
||||
return false;
|
||||
@ -72,7 +71,7 @@ void Technic::SolderPackInstallTask::executeTask()
|
||||
|
||||
m_filesNetJob.reset(new NetJob(tr("Resolving modpack files"), m_network));
|
||||
auto sourceUrl = QString("%1/modpack/%2/%3").arg(m_solderUrl.toString(), m_pack, m_version);
|
||||
m_filesNetJob->addNetAction(Net::Download::makeByteArray(sourceUrl, &m_response));
|
||||
m_filesNetJob->addNetAction(Net::Download::makeByteArray(sourceUrl, m_response));
|
||||
|
||||
auto job = m_filesNetJob.get();
|
||||
connect(job, &NetJob::succeeded, this, &Technic::SolderPackInstallTask::fileListSucceeded);
|
||||
@ -86,10 +85,10 @@ void Technic::SolderPackInstallTask::fileListSucceeded()
|
||||
setStatus(tr("Downloading modpack"));
|
||||
|
||||
QJsonParseError parse_error{};
|
||||
QJsonDocument doc = QJsonDocument::fromJson(m_response, &parse_error);
|
||||
QJsonDocument doc = QJsonDocument::fromJson(*m_response, &parse_error);
|
||||
if (parse_error.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response from Solder at " << parse_error.offset << " reason: " << parse_error.errorString();
|
||||
qWarning() << m_response;
|
||||
qWarning() << *m_response;
|
||||
return;
|
||||
}
|
||||
auto obj = doc.object();
|
||||
|
@ -40,14 +40,17 @@
|
||||
#include <tasks/Task.h>
|
||||
|
||||
#include <QUrl>
|
||||
#include <memory>
|
||||
|
||||
namespace Technic
|
||||
{
|
||||
class SolderPackInstallTask : public InstanceTask
|
||||
{
|
||||
namespace Technic {
|
||||
class SolderPackInstallTask : public InstanceTask {
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit SolderPackInstallTask(shared_qobject_ptr<QNetworkAccessManager> network, const QUrl &solderUrl, const QString& pack, const QString& version, const QString &minecraftVersion);
|
||||
explicit SolderPackInstallTask(shared_qobject_ptr<QNetworkAccessManager> network,
|
||||
const QUrl& solderUrl,
|
||||
const QString& pack,
|
||||
const QString& version,
|
||||
const QString& minecraftVersion);
|
||||
|
||||
bool canAbort() const override { return true; }
|
||||
bool abort() override;
|
||||
@ -75,10 +78,10 @@ namespace Technic
|
||||
QString m_pack;
|
||||
QString m_version;
|
||||
QString m_minecraftVersion;
|
||||
QByteArray m_response;
|
||||
std::shared_ptr<QByteArray> m_response = std::make_shared<QByteArray>();
|
||||
QTemporaryDir m_outputDir;
|
||||
int m_modCount;
|
||||
QFuture<bool> m_extractFuture;
|
||||
QFutureWatcher<bool> m_extractFutureWatcher;
|
||||
};
|
||||
}
|
||||
} // namespace Technic
|
||||
|
@ -1,7 +1,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
/*
|
||||
* PolyMC - Minecraft Launcher
|
||||
* Prism Launcher - Minecraft Launcher
|
||||
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
|
||||
* Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
@ -46,7 +47,7 @@ namespace Net {
|
||||
*/
|
||||
class ByteArraySink : public Sink {
|
||||
public:
|
||||
ByteArraySink(QByteArray* output) : m_output(output){};
|
||||
ByteArraySink(std::shared_ptr<QByteArray> output) : m_output(output){};
|
||||
|
||||
virtual ~ByteArraySink() = default;
|
||||
|
||||
@ -93,6 +94,6 @@ class ByteArraySink : public Sink {
|
||||
auto hasLocalData() -> bool override { return false; }
|
||||
|
||||
private:
|
||||
QByteArray* m_output;
|
||||
std::shared_ptr<QByteArray> m_output;
|
||||
};
|
||||
} // namespace Net
|
||||
|
@ -41,6 +41,7 @@
|
||||
|
||||
#include <QDateTime>
|
||||
#include <QFileInfo>
|
||||
#include <memory>
|
||||
|
||||
#include "ByteArraySink.h"
|
||||
#include "ChecksumValidator.h"
|
||||
@ -69,7 +70,7 @@ auto Download::makeCached(QUrl url, MetaEntryPtr entry, Options options) -> Down
|
||||
return dl;
|
||||
}
|
||||
|
||||
auto Download::makeByteArray(QUrl url, QByteArray* output, Options options) -> Download::Ptr
|
||||
auto Download::makeByteArray(QUrl url, std::shared_ptr<QByteArray> output, Options options) -> Download::Ptr
|
||||
{
|
||||
auto dl = makeShared<Download>();
|
||||
dl->m_url = url;
|
||||
|
@ -60,7 +60,7 @@ class Download : public NetAction {
|
||||
~Download() override = default;
|
||||
|
||||
static auto makeCached(QUrl url, MetaEntryPtr entry, Options options = Option::NoOptions) -> Download::Ptr;
|
||||
static auto makeByteArray(QUrl url, QByteArray* output, Options options = Option::NoOptions) -> Download::Ptr;
|
||||
static auto makeByteArray(QUrl url, std::shared_ptr<QByteArray> output, Options options = Option::NoOptions) -> Download::Ptr;
|
||||
static auto makeFile(QUrl url, QString path, Options options = Option::NoOptions) -> Download::Ptr;
|
||||
|
||||
public:
|
||||
|
@ -39,9 +39,9 @@
|
||||
#include "Upload.h"
|
||||
|
||||
#include <utility>
|
||||
#include "ByteArraySink.h"
|
||||
#include "BuildConfig.h"
|
||||
#include "Application.h"
|
||||
#include "BuildConfig.h"
|
||||
#include "ByteArraySink.h"
|
||||
|
||||
#include "net/Logging.h"
|
||||
|
||||
@ -57,11 +57,13 @@ namespace Net {
|
||||
return true;
|
||||
}
|
||||
|
||||
void Upload::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) {
|
||||
void Upload::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
|
||||
{
|
||||
setProgress(bytesReceived, bytesTotal);
|
||||
}
|
||||
|
||||
void Upload::downloadError(QNetworkReply::NetworkError error) {
|
||||
void Upload::downloadError(QNetworkReply::NetworkError error)
|
||||
{
|
||||
if (error == QNetworkReply::OperationCanceledError) {
|
||||
qCCritical(taskUploadLogC) << getUid().toString() << "Aborted " << m_url.toString();
|
||||
m_state = State::AbortedByUser;
|
||||
@ -72,10 +74,12 @@ namespace Net {
|
||||
}
|
||||
}
|
||||
|
||||
void Upload::sslErrors(const QList<QSslError> &errors) {
|
||||
void Upload::sslErrors(const QList<QSslError>& errors)
|
||||
{
|
||||
int i = 1;
|
||||
for (const auto& error : errors) {
|
||||
qCCritical(taskUploadLogC) << getUid().toString() << "Upload" << m_url.toString() << "SSL Error #" << i << " : " << error.errorString();
|
||||
qCCritical(taskUploadLogC) << getUid().toString() << "Upload" << m_url.toString() << "SSL Error #" << i << " : "
|
||||
<< error.errorString();
|
||||
auto cert = error.certificate();
|
||||
qCCritical(taskUploadLogC) << getUid().toString() << "Certificate in question:\n" << cert.toText();
|
||||
i++;
|
||||
@ -135,7 +139,8 @@ namespace Net {
|
||||
return true;
|
||||
}
|
||||
|
||||
void Upload::downloadFinished() {
|
||||
void Upload::downloadFinished()
|
||||
{
|
||||
// handle HTTP redirection first
|
||||
// very unlikely for post requests, still can happen
|
||||
if (handleRedirect()) {
|
||||
@ -185,14 +190,16 @@ namespace Net {
|
||||
emit succeeded();
|
||||
}
|
||||
|
||||
void Upload::downloadReadyRead() {
|
||||
void Upload::downloadReadyRead()
|
||||
{
|
||||
if (m_state == State::Running) {
|
||||
auto data = m_reply->readAll();
|
||||
m_state = m_sink->write(data);
|
||||
}
|
||||
}
|
||||
|
||||
void Upload::executeTask() {
|
||||
void Upload::executeTask()
|
||||
{
|
||||
setStatus(tr("Uploading %1").arg(m_url.toString()));
|
||||
|
||||
if (m_state == State::AbortedByUser) {
|
||||
@ -246,11 +253,12 @@ namespace Net {
|
||||
connect(rep, &QNetworkReply::readyRead, this, &Upload::downloadReadyRead);
|
||||
}
|
||||
|
||||
Upload::Ptr Upload::makeByteArray(QUrl url, QByteArray *output, QByteArray m_post_data) {
|
||||
Upload::Ptr Upload::makeByteArray(QUrl url, std::shared_ptr<QByteArray> output, QByteArray m_post_data)
|
||||
{
|
||||
auto up = makeShared<Upload>();
|
||||
up->m_url = std::move(url);
|
||||
up->m_sink.reset(new ByteArraySink(output));
|
||||
up->m_post_data = std::move(m_post_data);
|
||||
return up;
|
||||
}
|
||||
} // Net
|
||||
} // namespace Net
|
||||
|
@ -48,7 +48,7 @@ namespace Net {
|
||||
public:
|
||||
using Ptr = shared_qobject_ptr<Upload>;
|
||||
|
||||
static Upload::Ptr makeByteArray(QUrl url, QByteArray *output, QByteArray m_post_data);
|
||||
static Upload::Ptr makeByteArray(QUrl url, std::shared_ptr<QByteArray> output, QByteArray m_post_data);
|
||||
auto abort() -> bool override;
|
||||
auto canAbort() const -> bool override { return true; };
|
||||
|
||||
@ -61,6 +61,7 @@ namespace Net {
|
||||
|
||||
public slots:
|
||||
void executeTask() override;
|
||||
|
||||
private:
|
||||
std::unique_ptr<Sink> m_sink;
|
||||
QByteArray m_post_data;
|
||||
@ -68,5 +69,4 @@ namespace Net {
|
||||
bool handleRedirect();
|
||||
};
|
||||
|
||||
} // Net
|
||||
|
||||
} // namespace Net
|
||||
|
@ -58,7 +58,7 @@ void NewsChecker::reloadNews()
|
||||
qDebug() << "Reloading news.";
|
||||
|
||||
NetJob::Ptr job{ new NetJob("News RSS Feed", m_network) };
|
||||
job->addNetAction(Net::Download::makeByteArray(m_feedUrl, &newsData));
|
||||
job->addNetAction(Net::Download::makeByteArray(m_feedUrl, newsData));
|
||||
QObject::connect(job.get(), &NetJob::succeeded, this, &NewsChecker::rssDownloadFinished);
|
||||
QObject::connect(job.get(), &NetJob::failed, this, &NewsChecker::rssDownloadFailed);
|
||||
m_newsNetJob.reset(job);
|
||||
@ -79,32 +79,27 @@ void NewsChecker::rssDownloadFinished()
|
||||
int errorCol = -1;
|
||||
|
||||
// Parse the XML.
|
||||
if (!doc.setContent(newsData, false, &errorMsg, &errorLine, &errorCol))
|
||||
{
|
||||
if (!doc.setContent(*newsData, false, &errorMsg, &errorLine, &errorCol)) {
|
||||
QString fullErrorMsg = QString("Error parsing RSS feed XML. %1 at %2:%3.").arg(errorMsg).arg(errorLine).arg(errorCol);
|
||||
fail(fullErrorMsg);
|
||||
newsData.clear();
|
||||
newsData->clear();
|
||||
return;
|
||||
}
|
||||
newsData.clear();
|
||||
newsData->clear();
|
||||
}
|
||||
|
||||
// If the parsing succeeded, read it.
|
||||
QDomNodeList items = doc.elementsByTagName("entry");
|
||||
m_newsEntries.clear();
|
||||
for (int i = 0; i < items.length(); i++)
|
||||
{
|
||||
for (int i = 0; i < items.length(); i++) {
|
||||
QDomElement element = items.at(i).toElement();
|
||||
NewsEntryPtr entry;
|
||||
entry.reset(new NewsEntry());
|
||||
QString errorMsg = "An unknown error occurred.";
|
||||
if (NewsEntry::fromXmlElement(element, entry.get(), &errorMsg))
|
||||
{
|
||||
if (NewsEntry::fromXmlElement(element, entry.get(), &errorMsg)) {
|
||||
qDebug() << "Loaded news entry" << entry->title;
|
||||
m_newsEntries.append(entry);
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
qWarning() << "Failed to load news entry at index" << i << ":" << errorMsg;
|
||||
}
|
||||
}
|
||||
|
@ -85,7 +85,7 @@ protected: /* data */
|
||||
//! True if news has been loaded.
|
||||
bool m_loadedNews;
|
||||
|
||||
QByteArray newsData;
|
||||
std::shared_ptr<QByteArray> newsData = std::make_shared<QByteArray>();
|
||||
|
||||
/*!
|
||||
* Gets the error message that was given last time the news was loaded.
|
||||
|
@ -577,7 +577,7 @@
|
||||
<normaloff>.</normaloff>.</iconset>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>Report a &Bug...</string>
|
||||
<string>Report a Bug or Suggest a Feature</string>
|
||||
</property>
|
||||
<property name="toolTip">
|
||||
<string>Open the bug tracker to report a bug with %1.</string>
|
||||
|
@ -71,13 +71,18 @@ QString getCreditsHtml()
|
||||
//: %1 is the name of the launcher, determined at build time, e.g. "Prism Launcher Developers"
|
||||
stream << "<h3>" << QObject::tr("%1 Developers", "About Credits").arg(BuildConfig.LAUNCHER_DISPLAYNAME) << "</h3>\n";
|
||||
stream << QString("<p>Sefa Eyeoglu (Scrumplex) %1</p>\n") .arg(getWebsite("https://scrumplex.net"));
|
||||
stream << QString("<p>dada513 %1</p>\n") .arg(getGitHub("dada513"));
|
||||
stream << QString("<p>d-513 %1</p>\n") .arg(getGitHub("d-513"));
|
||||
stream << QString("<p>txtsd %1</p>\n") .arg(getWebsite("https://ihavea.quest"));
|
||||
stream << QString("<p>timoreo %1</p>\n") .arg(getGitHub("timoreo22"));
|
||||
stream << QString("<p>Ezekiel Smith (ZekeSmith) %1</p>\n") .arg(getGitHub("ZekeSmith"));
|
||||
stream << QString("<p>cozyGalvinism %1</p>\n") .arg(getGitHub("cozyGalvinism"));
|
||||
stream << QString("<p>DioEgizio %1</p>\n") .arg(getGitHub("DioEgizio"));
|
||||
stream << QString("<p>flowln %1</p>\n") .arg(getGitHub("flowln"));
|
||||
stream << QString("<p>ViRb3 %1</p>\n") .arg(getGitHub("ViRb3"));
|
||||
stream << QString("<p>Rachel Powers (Ryex) %1</p>\n") .arg(getGitHub("Ryex"));
|
||||
stream << QString("<p>TayouVR %1</p>\n") .arg(getGitHub("TayouVR"));
|
||||
stream << QString("<p>TheKodeToad %1</p>\n") .arg(getGitHub("TheKodeToad"));
|
||||
stream << QString("<p>getchoo %1</p>\n") .arg(getGitHub("getchoo"));
|
||||
stream << "<br />\n";
|
||||
|
||||
// TODO: possibly retrieve from git history at build time?
|
||||
|
@ -53,6 +53,7 @@ ExportMrPackDialog::ExportMrPackDialog(InstancePtr instance, QWidget* parent)
|
||||
const QDir root(instance->gameRoot());
|
||||
proxy = new FileIgnoreProxy(instance->gameRoot(), this);
|
||||
proxy->setSourceModel(model);
|
||||
proxy->setFilterRegularExpression("^(?!(\\.DS_Store)|([tT]humbs\\.db)).+$");
|
||||
|
||||
const QDir::Filters filter(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Hidden);
|
||||
|
||||
|
@ -32,7 +32,7 @@ NewsDialog::~NewsDialog()
|
||||
|
||||
void NewsDialog::selectedArticleChanged(const QString& new_title)
|
||||
{
|
||||
auto const& article_entry = m_entries.constFind(new_title).value();
|
||||
auto article_entry = m_entries.constFind(new_title).value();
|
||||
|
||||
ui->articleTitleLabel->setText(QString("<a href='%1'>%2</a>").arg(article_entry->link, new_title));
|
||||
|
||||
|
@ -18,6 +18,8 @@
|
||||
*/
|
||||
|
||||
#include "ResourceDownloadDialog.h"
|
||||
#include <QEventLoop>
|
||||
#include <QList>
|
||||
|
||||
#include <QPushButton>
|
||||
#include <algorithm>
|
||||
@ -30,6 +32,10 @@
|
||||
#include "minecraft/mod/ShaderPackFolderModel.h"
|
||||
#include "minecraft/mod/TexturePackFolderModel.h"
|
||||
|
||||
#include "minecraft/mod/tasks/GetModDependenciesTask.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
#include "ui/dialogs/CustomMessageBox.h"
|
||||
#include "ui/dialogs/ProgressDialog.h"
|
||||
#include "ui/dialogs/ReviewMessageBox.h"
|
||||
|
||||
#include "ui/pages/modplatform/ResourcePage.h"
|
||||
@ -117,18 +123,71 @@ void ResourceDownloadDialog::connectButtons()
|
||||
connect(HelpButton, &QPushButton::clicked, m_container, &PageContainer::help);
|
||||
}
|
||||
|
||||
static ModPlatform::ProviderCapabilities ProviderCaps;
|
||||
|
||||
QStringList getRequiredBy(QList<ResourceDownloadDialog::DownloadTaskPtr> tasks, ResourceDownloadDialog::DownloadTaskPtr pack)
|
||||
{
|
||||
auto addonId = pack->getPack()->addonId;
|
||||
auto provider = pack->getPack()->provider;
|
||||
auto version = pack->getVersionID();
|
||||
auto req = QStringList();
|
||||
for (auto& task : tasks) {
|
||||
if (provider != task->getPack()->provider)
|
||||
continue;
|
||||
auto deps = task->getVersion().dependencies;
|
||||
if (auto dep = std::find_if(deps.begin(), deps.end(),
|
||||
[addonId, provider, version](const ModPlatform::Dependency& d) {
|
||||
return d.type == ModPlatform::DependencyType::REQUIRED &&
|
||||
(provider == ModPlatform::ResourceProvider::MODRINTH && d.addonId.toString().isEmpty()
|
||||
? version == d.version
|
||||
: d.addonId == addonId);
|
||||
});
|
||||
dep != deps.end()) {
|
||||
req.append(task->getName());
|
||||
}
|
||||
}
|
||||
return req;
|
||||
}
|
||||
|
||||
void ResourceDownloadDialog::confirm()
|
||||
{
|
||||
auto confirm_dialog = ReviewMessageBox::create(this, tr("Confirm %1 to download").arg(resourcesString()));
|
||||
confirm_dialog->retranslateUi(resourcesString());
|
||||
|
||||
if (auto task = getModDependenciesTask(); task) {
|
||||
connect(task.get(), &Task::failed, this,
|
||||
[&](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->exec(); });
|
||||
|
||||
connect(task.get(), &Task::succeeded, this, [&]() {
|
||||
QStringList warnings = task->warnings();
|
||||
if (warnings.count()) {
|
||||
CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->exec();
|
||||
}
|
||||
});
|
||||
|
||||
// Check for updates
|
||||
ProgressDialog progress_dialog(this);
|
||||
progress_dialog.setSkipButton(true, tr("Abort"));
|
||||
progress_dialog.setWindowTitle(tr("Checking for dependencies..."));
|
||||
auto ret = progress_dialog.execWithTask(task.get());
|
||||
|
||||
// If the dialog was skipped / some download error happened
|
||||
if (ret == QDialog::DialogCode::Rejected) {
|
||||
QMetaObject::invokeMethod(this, "reject", Qt::QueuedConnection);
|
||||
return;
|
||||
} else {
|
||||
for (auto dep : task->getDependecies())
|
||||
addResource(dep->pack, dep->version);
|
||||
}
|
||||
}
|
||||
|
||||
auto selected = getTasks();
|
||||
std::sort(selected.begin(), selected.end(), [](const DownloadTaskPtr& a, const DownloadTaskPtr& b) {
|
||||
return QString::compare(a->getName(), b->getName(), Qt::CaseInsensitive) < 0;
|
||||
});
|
||||
|
||||
auto confirm_dialog = ReviewMessageBox::create(this, tr("Confirm %1 to download").arg(resourcesString()));
|
||||
confirm_dialog->retranslateUi(resourcesString());
|
||||
|
||||
for (auto& task : selected) {
|
||||
confirm_dialog->appendResource({ task->getName(), task->getFilename(), task->getCustomPath() });
|
||||
confirm_dialog->appendResource({ task->getName(), task->getFilename(), task->getCustomPath(),
|
||||
ProviderCaps.name(task->getProvider()), getRequiredBy(selected, task) });
|
||||
}
|
||||
|
||||
if (confirm_dialog->exec()) {
|
||||
@ -231,6 +290,19 @@ QList<BasePage*> ModDownloadDialog::getPages()
|
||||
return pages;
|
||||
}
|
||||
|
||||
GetModDependenciesTask::Ptr ModDownloadDialog::getModDependenciesTask()
|
||||
{
|
||||
if (auto model = dynamic_cast<ModFolderModel*>(getBaseModel().get()); model) {
|
||||
QList<std::shared_ptr<GetModDependenciesTask::PackDependency>> selectedVers;
|
||||
for (auto& selected : getTasks()) {
|
||||
selectedVers.append(std::make_shared<GetModDependenciesTask::PackDependency>(selected->getPack(), selected->getVersion()));
|
||||
}
|
||||
|
||||
return makeShared<GetModDependenciesTask>(this, m_instance, model, selectedVers);
|
||||
}
|
||||
return nullptr;
|
||||
};
|
||||
|
||||
ResourcePackDownloadDialog::ResourcePackDownloadDialog(QWidget* parent,
|
||||
const std::shared_ptr<ResourcePackFolderModel>& resource_packs,
|
||||
BaseInstance* instance)
|
||||
|
@ -25,6 +25,7 @@
|
||||
#include <QLayout>
|
||||
|
||||
#include "QObjectPtr.h"
|
||||
#include "minecraft/mod/tasks/GetModDependenciesTask.h"
|
||||
#include "modplatform/ModIndex.h"
|
||||
#include "ui/pages/BasePageProvider.h"
|
||||
|
||||
@ -81,6 +82,8 @@ class ResourceDownloadDialog : public QDialog, public BasePageProvider {
|
||||
[[nodiscard]] virtual QString geometrySaveKey() const { return ""; }
|
||||
void setButtonStatus();
|
||||
|
||||
[[nodiscard]] virtual GetModDependenciesTask::Ptr getModDependenciesTask() { return nullptr; }
|
||||
|
||||
protected:
|
||||
const std::shared_ptr<ResourceFolderModel> m_base_model;
|
||||
|
||||
@ -103,6 +106,7 @@ class ModDownloadDialog final : public ResourceDownloadDialog {
|
||||
[[nodiscard]] QString geometrySaveKey() const override { return "ModDownloadGeometry"; }
|
||||
|
||||
QList<BasePage*> getPages() override;
|
||||
GetModDependenciesTask::Ptr getModDependenciesTask() override;
|
||||
|
||||
private:
|
||||
BaseInstance* m_instance;
|
||||
|
@ -40,7 +40,8 @@ void ReviewMessageBox::appendResource(ResourceInformation&& info)
|
||||
auto filenameItem = new QTreeWidgetItem(itemTop);
|
||||
filenameItem->setText(0, tr("Filename: %1").arg(info.filename));
|
||||
|
||||
itemTop->insertChildren(0, { filenameItem });
|
||||
auto childIndx = 0;
|
||||
itemTop->insertChildren(childIndx++, { filenameItem });
|
||||
|
||||
if (!info.custom_file_path.isEmpty()) {
|
||||
auto customPathItem = new QTreeWidgetItem(itemTop);
|
||||
@ -49,7 +50,31 @@ void ReviewMessageBox::appendResource(ResourceInformation&& info)
|
||||
itemTop->insertChildren(1, { customPathItem });
|
||||
|
||||
itemTop->setIcon(1, QIcon(APPLICATION->getThemedIcon("status-yellow")));
|
||||
itemTop->setToolTip(1, tr("This file will be downloaded to a folder location different from the default, possibly due to its loader requiring it."));
|
||||
itemTop->setToolTip(
|
||||
childIndx++,
|
||||
tr("This file will be downloaded to a folder location different from the default, possibly due to its loader requiring it."));
|
||||
}
|
||||
|
||||
auto providerItem = new QTreeWidgetItem(itemTop);
|
||||
providerItem->setText(0, tr("Provider: %1").arg(info.provider));
|
||||
|
||||
itemTop->insertChildren(childIndx++, { providerItem });
|
||||
|
||||
if (!info.required_by.isEmpty()) {
|
||||
auto requiredByItem = new QTreeWidgetItem(itemTop);
|
||||
if (info.required_by.length() == 1) {
|
||||
requiredByItem->setText(0, tr("Required by: %1").arg(info.required_by.back()));
|
||||
} else {
|
||||
requiredByItem->setText(0, tr("Required by:"));
|
||||
auto i = 0;
|
||||
for (auto req : info.required_by) {
|
||||
auto reqItem = new QTreeWidgetItem(requiredByItem);
|
||||
reqItem->setText(0, req);
|
||||
reqItem->insertChildren(i++, { reqItem });
|
||||
}
|
||||
}
|
||||
|
||||
itemTop->insertChildren(childIndx++, { requiredByItem });
|
||||
}
|
||||
|
||||
ui->modTreeWidget->addTopLevelItem(itemTop);
|
||||
|
@ -16,6 +16,8 @@ class ReviewMessageBox : public QDialog {
|
||||
QString name;
|
||||
QString filename;
|
||||
QString custom_file_path{};
|
||||
QString provider;
|
||||
QStringList required_by;
|
||||
};
|
||||
|
||||
void appendResource(ResourceInformation&& info);
|
||||
|
@ -60,6 +60,8 @@ ExternalResourcesPage::ExternalResourcesPage(BaseInstance* instance, std::shared
|
||||
m_filterModel->setSourceModel(m_model.get());
|
||||
m_filterModel->setFilterKeyColumn(-1);
|
||||
ui->treeView->setModel(m_filterModel);
|
||||
// must come after setModel
|
||||
ui->treeView->setResizeModes(m_model->columnResizeModes());
|
||||
|
||||
ui->treeView->installEventFilter(this);
|
||||
ui->treeView->sortByColumn(1, Qt::AscendingOrder);
|
||||
@ -87,6 +89,13 @@ ExternalResourcesPage::ExternalResourcesPage(BaseInstance* instance, std::shared
|
||||
connect(model.get(), &ResourceFolderModel::updateFinished, this, updateExtra);
|
||||
|
||||
connect(ui->filterEdit, &QLineEdit::textChanged, this, &ExternalResourcesPage::filterTextChanged);
|
||||
|
||||
auto viewHeader = ui->treeView->header();
|
||||
viewHeader->setContextMenuPolicy(Qt::CustomContextMenu);
|
||||
|
||||
connect(viewHeader, &QHeaderView::customContextMenuRequested, this, &ExternalResourcesPage::ShowHeaderContextMenu);
|
||||
|
||||
m_model->loadHiddenColumns(ui->treeView);
|
||||
}
|
||||
|
||||
ExternalResourcesPage::~ExternalResourcesPage()
|
||||
@ -108,6 +117,13 @@ void ExternalResourcesPage::ShowContextMenu(const QPoint& pos)
|
||||
delete menu;
|
||||
}
|
||||
|
||||
void ExternalResourcesPage::ShowHeaderContextMenu(const QPoint& pos)
|
||||
{
|
||||
auto menu = m_model->createHeaderContextMenu(ui->treeView);
|
||||
menu->exec(ui->treeView->mapToGlobal(pos));
|
||||
menu->deleteLater();
|
||||
}
|
||||
|
||||
void ExternalResourcesPage::openedImpl()
|
||||
{
|
||||
m_model->startWatching();
|
||||
@ -139,7 +155,6 @@ void ExternalResourcesPage::itemActivated(const QModelIndex&)
|
||||
return;
|
||||
|
||||
auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection());
|
||||
m_model->setResourceEnabled(selection.indexes(), EnableAction::TOGGLE);
|
||||
}
|
||||
|
||||
void ExternalResourcesPage::filterTextChanged(const QString& newContents)
|
||||
|
@ -61,6 +61,7 @@ class ExternalResourcesPage : public QMainWindow, public BasePage {
|
||||
virtual void viewConfigs();
|
||||
|
||||
void ShowContextMenu(const QPoint& pos);
|
||||
void ShowHeaderContextMenu(const QPoint& pos);
|
||||
|
||||
protected:
|
||||
BaseInstance* m_instance = nullptr;
|
||||
|
@ -62,6 +62,9 @@
|
||||
<property name="dragDropMode">
|
||||
<enum>QAbstractItemView::DropOnly</enum>
|
||||
</property>
|
||||
<property name="uniformRowHeights">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
|
@ -226,7 +226,7 @@ void ModrinthManagedPackPage::parseManagedPack()
|
||||
|
||||
QString id = m_inst->getManagedPackID();
|
||||
|
||||
m_fetch_job->addNetAction(Net::Download::makeByteArray(QString("%1/project/%2/version").arg(BuildConfig.MODRINTH_PROD_URL, id), response.get()));
|
||||
m_fetch_job->addNetAction(Net::Download::makeByteArray(QString("%1/project/%2/version").arg(BuildConfig.MODRINTH_PROD_URL, id), response));
|
||||
|
||||
QObject::connect(m_fetch_job.get(), &NetJob::succeeded, this, [this, response, id] {
|
||||
QJsonParseError parse_error{};
|
||||
@ -369,7 +369,7 @@ void FlameManagedPackPage::parseManagedPack()
|
||||
|
||||
QString id = m_inst->getManagedPackID();
|
||||
|
||||
m_fetch_job->addNetAction(Net::Download::makeByteArray(QString("%1/mods/%2/files").arg(BuildConfig.FLAME_BASE_URL, id), response.get()));
|
||||
m_fetch_job->addNetAction(Net::Download::makeByteArray(QString("%1/mods/%2/files").arg(BuildConfig.FLAME_BASE_URL, id), response));
|
||||
|
||||
QObject::connect(m_fetch_job.get(), &NetJob::succeeded, this, [this, response, id] {
|
||||
QJsonParseError parse_error{};
|
||||
|
@ -57,7 +57,7 @@ public:
|
||||
virtual ~ImportPage();
|
||||
virtual QString displayName() const override
|
||||
{
|
||||
return tr("Import from zip");
|
||||
return tr("Import");
|
||||
}
|
||||
virtual QIcon icon() const override
|
||||
{
|
||||
|
@ -32,6 +32,7 @@ class ModModel : public ResourceModel {
|
||||
void loadIndexedPack(ModPlatform::IndexedPack& m, QJsonObject& obj) override = 0;
|
||||
void loadExtraPackInfo(ModPlatform::IndexedPack& m, QJsonObject& obj) override = 0;
|
||||
void loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJsonArray& arr) override = 0;
|
||||
virtual ModPlatform::IndexedVersion loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr) = 0;
|
||||
|
||||
void setFilter(std::shared_ptr<ModFilterWidget::Filter> filter) { m_filter = filter; }
|
||||
|
||||
|
@ -89,17 +89,13 @@ void ModPage::filterMods()
|
||||
|
||||
void ModPage::triggerSearch()
|
||||
{
|
||||
auto changed = m_filter_widget->changed();
|
||||
m_filter = m_filter_widget->getFilter();
|
||||
|
||||
if (changed) {
|
||||
m_ui->packView->clearSelection();
|
||||
m_ui->packDescription->clear();
|
||||
m_ui->versionSelectionBox->clear();
|
||||
updateSelectionButton();
|
||||
}
|
||||
|
||||
static_cast<ModModel*>(m_model)->searchWithTerm(getSearchTerm(), m_ui->sortByBox->currentData().toUInt(), changed);
|
||||
static_cast<ModModel*>(m_model)->searchWithTerm(getSearchTerm(), m_ui->sortByBox->currentData().toUInt(), m_filter_widget->changed());
|
||||
m_fetch_progress.watch(m_model->activeSearchJob().get());
|
||||
}
|
||||
|
||||
@ -122,6 +118,8 @@ void ModPage::updateVersionList()
|
||||
QString mcVersion = packProfile->getComponentVersion("net.minecraft");
|
||||
|
||||
auto current_pack = getCurrentPack();
|
||||
if (!current_pack)
|
||||
return;
|
||||
for (int i = 0; i < current_pack->versions.size(); i++) {
|
||||
auto version = current_pack->versions[i];
|
||||
bool valid = false;
|
||||
|
@ -174,7 +174,11 @@ ModPlatform::IndexedPack::Ptr ResourcePage::getCurrentPack() const
|
||||
void ResourcePage::updateUi()
|
||||
{
|
||||
auto current_pack = getCurrentPack();
|
||||
|
||||
if (!current_pack) {
|
||||
m_ui->packDescription->setHtml({});
|
||||
m_ui->packDescription->flush();
|
||||
return;
|
||||
}
|
||||
QString text = "";
|
||||
QString name = current_pack->name;
|
||||
|
||||
@ -240,8 +244,8 @@ void ResourcePage::updateSelectionButton()
|
||||
}
|
||||
|
||||
m_ui->resourceSelectionButton->setEnabled(true);
|
||||
if (getCurrentPack()) {
|
||||
if (!getCurrentPack()->isVersionSelected(m_selected_version_index))
|
||||
if (auto current_pack = getCurrentPack(); current_pack) {
|
||||
if (!current_pack->isVersionSelected(m_selected_version_index))
|
||||
m_ui->resourceSelectionButton->setText(tr("Select %1 for download").arg(resourceString()));
|
||||
else
|
||||
m_ui->resourceSelectionButton->setText(tr("Deselect %1 for download").arg(resourceString()));
|
||||
@ -258,6 +262,7 @@ void ResourcePage::updateVersionList()
|
||||
m_ui->versionSelectionBox->clear();
|
||||
m_ui->versionSelectionBox->blockSignals(false);
|
||||
|
||||
if (current_pack)
|
||||
for (int i = 0; i < current_pack->versions.size(); i++) {
|
||||
auto& version = current_pack->versions[i];
|
||||
if (optedOut(version))
|
||||
@ -283,7 +288,7 @@ void ResourcePage::onSelectionChanged(QModelIndex curr, QModelIndex prev)
|
||||
auto current_pack = getCurrentPack();
|
||||
|
||||
bool request_load = false;
|
||||
if (!current_pack->versionsLoaded) {
|
||||
if (!current_pack || !current_pack->versionsLoaded) {
|
||||
m_ui->resourceSelectionButton->setText(tr("Loading versions..."));
|
||||
m_ui->resourceSelectionButton->setEnabled(false);
|
||||
|
||||
@ -292,7 +297,7 @@ void ResourcePage::onSelectionChanged(QModelIndex curr, QModelIndex prev)
|
||||
updateVersionList();
|
||||
}
|
||||
|
||||
if (!current_pack->extraDataLoaded)
|
||||
if (current_pack && !current_pack->extraDataLoaded)
|
||||
request_load = true;
|
||||
|
||||
if (request_load)
|
||||
@ -340,7 +345,7 @@ void ResourcePage::onResourceSelected()
|
||||
return;
|
||||
|
||||
auto current_pack = getCurrentPack();
|
||||
if (!current_pack->versionsLoaded)
|
||||
if (!current_pack || !current_pack->versionsLoaded)
|
||||
return;
|
||||
|
||||
auto& version = current_pack->versions[m_selected_version_index];
|
||||
@ -386,7 +391,7 @@ void ResourcePage::openUrl(const QUrl& url)
|
||||
const QString slug = match.captured(1);
|
||||
|
||||
// ensure the user isn't opening the same mod
|
||||
if (slug != getCurrentPack()->slug) {
|
||||
if (auto current_pack = getCurrentPack(); current_pack && slug != current_pack->slug) {
|
||||
m_parent_dialog->selectPage(page);
|
||||
|
||||
auto newPage = m_parent_dialog->getSelectedPage();
|
||||
|
@ -16,19 +16,15 @@
|
||||
|
||||
#include "AtlListModel.h"
|
||||
|
||||
#include <BuildConfig.h>
|
||||
#include <Application.h>
|
||||
#include <BuildConfig.h>
|
||||
#include <Json.h>
|
||||
|
||||
namespace Atl {
|
||||
|
||||
ListModel::ListModel(QObject *parent) : QAbstractListModel(parent)
|
||||
{
|
||||
}
|
||||
ListModel::ListModel(QObject* parent) : QAbstractListModel(parent) {}
|
||||
|
||||
ListModel::~ListModel()
|
||||
{
|
||||
}
|
||||
ListModel::~ListModel() {}
|
||||
|
||||
int ListModel::rowCount(const QModelIndex& parent) const
|
||||
{
|
||||
@ -43,24 +39,17 @@ int ListModel::columnCount(const QModelIndex &parent) 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);
|
||||
}
|
||||
|
||||
ATLauncher::IndexedPack pack = modpacks.at(pos);
|
||||
if(role == Qt::DisplayRole)
|
||||
{
|
||||
if (role == Qt::DisplayRole) {
|
||||
return pack.name;
|
||||
}
|
||||
else if (role == Qt::ToolTipRole)
|
||||
{
|
||||
} else if (role == Qt::ToolTipRole) {
|
||||
return pack.name;
|
||||
}
|
||||
else if(role == Qt::DecorationRole)
|
||||
{
|
||||
if(m_logoMap.contains(pack.safeName))
|
||||
{
|
||||
} else if (role == Qt::DecorationRole) {
|
||||
if (m_logoMap.contains(pack.safeName)) {
|
||||
return (m_logoMap.value(pack.safeName));
|
||||
}
|
||||
auto icon = APPLICATION->getThemedIcon("atlauncher-placeholder");
|
||||
@ -69,9 +58,7 @@ QVariant ListModel::data(const QModelIndex &index, int role) const
|
||||
((ListModel*)this)->requestLogo(pack.safeName, url);
|
||||
|
||||
return icon;
|
||||
}
|
||||
else if(role == Qt::UserRole)
|
||||
{
|
||||
} else if (role == Qt::UserRole) {
|
||||
QVariant v;
|
||||
v.setValue(pack);
|
||||
return v;
|
||||
@ -88,7 +75,7 @@ void ListModel::request()
|
||||
|
||||
auto netJob = makeShared<NetJob>("Atl::Request", APPLICATION->network());
|
||||
auto url = QString(BuildConfig.ATL_DOWNLOAD_SERVER_URL + "launcher/json/packsnew.json");
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(url), &response));
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(url), response));
|
||||
jobPtr = netJob;
|
||||
jobPtr->start();
|
||||
|
||||
@ -101,10 +88,10 @@ void ListModel::requestFinished()
|
||||
jobPtr.reset();
|
||||
|
||||
QJsonParseError parse_error;
|
||||
QJsonDocument doc = QJsonDocument::fromJson(response, &parse_error);
|
||||
QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error);
|
||||
if (parse_error.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response from ATL at " << parse_error.offset << " reason: " << parse_error.errorString();
|
||||
qWarning() << response;
|
||||
qWarning() << *response;
|
||||
return;
|
||||
}
|
||||
|
||||
@ -118,19 +105,21 @@ void ListModel::requestFinished()
|
||||
|
||||
try {
|
||||
ATLauncher::loadIndexedPack(pack, packObj);
|
||||
}
|
||||
catch (const JSONValidationError &e) {
|
||||
qDebug() << QString::fromUtf8(response);
|
||||
} catch (const JSONValidationError& e) {
|
||||
qDebug() << QString::fromUtf8(*response);
|
||||
qWarning() << "Error while reading pack manifest from ATLauncher: " << e.cause();
|
||||
return;
|
||||
}
|
||||
|
||||
// ignore packs without a published version
|
||||
if(pack.versions.length() == 0) continue;
|
||||
if (pack.versions.length() == 0)
|
||||
continue;
|
||||
// only display public packs (for now)
|
||||
if(pack.type != ATLauncher::PackType::Public) continue;
|
||||
if (pack.type != ATLauncher::PackType::Public)
|
||||
continue;
|
||||
// ignore "system" packs (Vanilla, Vanilla with Forge, etc)
|
||||
if(pack.system) continue;
|
||||
if (pack.system)
|
||||
continue;
|
||||
|
||||
newList.append(pack);
|
||||
}
|
||||
@ -147,12 +136,10 @@ void ListModel::requestFailed(QString reason)
|
||||
|
||||
void ListModel::getLogo(const QString& logo, const QString& logoUrl, LogoCallback callback)
|
||||
{
|
||||
if(m_logoMap.contains(logo))
|
||||
{
|
||||
callback(APPLICATION->metacache()->resolveEntry("ATLauncherPacks", QString("logos/%1").arg(logo.section(".", 0, 0)))->getFullPath());
|
||||
}
|
||||
else
|
||||
{
|
||||
if (m_logoMap.contains(logo)) {
|
||||
callback(
|
||||
APPLICATION->metacache()->resolveEntry("ATLauncherPacks", QString("logos/%1").arg(logo.section(".", 0, 0)))->getFullPath());
|
||||
} else {
|
||||
requestLogo(logo, logoUrl);
|
||||
}
|
||||
}
|
||||
@ -177,27 +164,25 @@ void ListModel::logoLoaded(QString logo, QIcon out)
|
||||
|
||||
void ListModel::requestLogo(QString file, QString url)
|
||||
{
|
||||
if(m_loadingLogos.contains(file) || m_failedLogos.contains(file))
|
||||
{
|
||||
if (m_loadingLogos.contains(file) || m_failedLogos.contains(file)) {
|
||||
return;
|
||||
}
|
||||
|
||||
MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry("ATLauncherPacks", QString("logos/%1").arg(file.section(".", 0, 0)));
|
||||
NetJob *job = new NetJob(QString("ATLauncher Icon Download %1").arg(file), APPLICATION->network());
|
||||
auto job = new NetJob(QString("ATLauncher Icon Download %1").arg(file), APPLICATION->network());
|
||||
job->addNetAction(Net::Download::makeCached(QUrl(url), entry));
|
||||
|
||||
auto fullPath = entry->getFullPath();
|
||||
QObject::connect(job, &NetJob::succeeded, this, [this, file, fullPath]
|
||||
{
|
||||
QObject::connect(job, &NetJob::succeeded, this, [this, file, fullPath, job] {
|
||||
job->deleteLater();
|
||||
emit logoLoaded(file, QIcon(fullPath));
|
||||
if(waitingCallbacks.contains(file))
|
||||
{
|
||||
if (waitingCallbacks.contains(file)) {
|
||||
waitingCallbacks.value(file)(fullPath);
|
||||
}
|
||||
});
|
||||
|
||||
QObject::connect(job, &NetJob::failed, this, [this, file]
|
||||
{
|
||||
QObject::connect(job, &NetJob::failed, this, [this, file, job] {
|
||||
job->deleteLater();
|
||||
emit logoFailed(file);
|
||||
});
|
||||
|
||||
@ -206,4 +191,4 @@ void ListModel::requestLogo(QString file, QString url)
|
||||
m_loadingLogos.append(file);
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace Atl
|
||||
|
@ -18,17 +18,16 @@
|
||||
|
||||
#include <QAbstractListModel>
|
||||
|
||||
#include "net/NetJob.h"
|
||||
#include <QIcon>
|
||||
#include <modplatform/atlauncher/ATLPackIndex.h>
|
||||
#include <QIcon>
|
||||
#include "net/NetJob.h"
|
||||
|
||||
namespace Atl {
|
||||
|
||||
typedef QMap<QString, QIcon> LogoMap;
|
||||
typedef std::function<void(QString)> LogoCallback;
|
||||
|
||||
class ListModel : public QAbstractListModel
|
||||
{
|
||||
class ListModel : public QAbstractListModel {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
@ -62,7 +61,7 @@ private:
|
||||
QMap<QString, LogoCallback> waitingCallbacks;
|
||||
|
||||
NetJob::Ptr jobPtr;
|
||||
QByteArray response;
|
||||
std::shared_ptr<QByteArray> response = std::make_shared<QByteArray>();
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace Atl
|
||||
|
@ -152,7 +152,7 @@ Qt::ItemFlags AtlOptionalModListModel::flags(const QModelIndex &index) const {
|
||||
void AtlOptionalModListModel::useShareCode(const QString& code) {
|
||||
m_jobPtr.reset(new NetJob("Atl::Request", APPLICATION->network()));
|
||||
auto url = QString(BuildConfig.ATL_API_BASE_URL + "share-codes/" + code);
|
||||
m_jobPtr->addNetAction(Net::Download::makeByteArray(QUrl(url), &m_response));
|
||||
m_jobPtr->addNetAction(Net::Download::makeByteArray(QUrl(url), m_response));
|
||||
|
||||
connect(m_jobPtr.get(), &NetJob::succeeded,
|
||||
this, &AtlOptionalModListModel::shareCodeSuccess);
|
||||
@ -166,10 +166,10 @@ void AtlOptionalModListModel::shareCodeSuccess() {
|
||||
m_jobPtr.reset();
|
||||
|
||||
QJsonParseError parse_error {};
|
||||
auto doc = QJsonDocument::fromJson(m_response, &parse_error);
|
||||
auto doc = QJsonDocument::fromJson(*m_response, &parse_error);
|
||||
if (parse_error.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response from ATL at " << parse_error.offset << " reason: " << parse_error.errorString();
|
||||
qWarning() << m_response;
|
||||
qWarning() << *m_response;
|
||||
return;
|
||||
}
|
||||
auto obj = doc.object();
|
||||
@ -179,7 +179,7 @@ void AtlOptionalModListModel::shareCodeSuccess() {
|
||||
ATLauncher::loadShareCodeResponse(response, obj);
|
||||
}
|
||||
catch (const JSONValidationError& e) {
|
||||
qDebug() << QString::fromUtf8(m_response);
|
||||
qDebug() << QString::fromUtf8(*m_response);
|
||||
qWarning() << "Error while reading response from ATLauncher: " << e.cause();
|
||||
return;
|
||||
}
|
||||
|
@ -84,7 +84,7 @@ private:
|
||||
|
||||
private:
|
||||
NetJob::Ptr m_jobPtr;
|
||||
QByteArray m_response;
|
||||
std::shared_ptr<QByteArray> m_response = std::make_shared<QByteArray>();
|
||||
|
||||
ATLauncher::PackVersion m_version;
|
||||
QVector<ATLauncher::VersionMod> m_mods;
|
||||
|
@ -44,6 +44,7 @@ class AtlUserInteractionSupportImpl : public QObject, public ATLauncher::UserInt
|
||||
|
||||
public:
|
||||
AtlUserInteractionSupportImpl(QWidget* parent);
|
||||
virtual ~AtlUserInteractionSupportImpl() = default;
|
||||
|
||||
private:
|
||||
QString chooseVersion(Meta::VersionList::Ptr vlist, QString minecraftVersion) override;
|
||||
@ -52,5 +53,4 @@ private:
|
||||
|
||||
private:
|
||||
QWidget* m_parent;
|
||||
|
||||
};
|
||||
|
@ -171,7 +171,7 @@ void ListModel::performPaginatedSearch()
|
||||
.arg(currentSearchTerm)
|
||||
.arg(currentSort + 1);
|
||||
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchUrl), &response));
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchUrl), response));
|
||||
jobPtr = netJob;
|
||||
jobPtr->start();
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, this, &ListModel::searchRequestFinished);
|
||||
@ -204,11 +204,11 @@ void Flame::ListModel::searchRequestFinished()
|
||||
jobPtr.reset();
|
||||
|
||||
QJsonParseError parse_error;
|
||||
QJsonDocument doc = QJsonDocument::fromJson(response, &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();
|
||||
qWarning() << response;
|
||||
qWarning() << *response;
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -3,28 +3,26 @@
|
||||
#include <RWStorage.h>
|
||||
|
||||
#include <QAbstractListModel>
|
||||
#include <QSortFilterProxyModel>
|
||||
#include <QThreadPool>
|
||||
#include <QIcon>
|
||||
#include <QStyledItemDelegate>
|
||||
#include <QList>
|
||||
#include <QMetaType>
|
||||
#include <QSortFilterProxyModel>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QMetaType>
|
||||
#include <QStyledItemDelegate>
|
||||
#include <QThreadPool>
|
||||
|
||||
#include <functional>
|
||||
#include <net/NetJob.h>
|
||||
#include <functional>
|
||||
|
||||
#include <modplatform/flame/FlamePackIndex.h>
|
||||
|
||||
namespace Flame {
|
||||
|
||||
|
||||
typedef QMap<QString, QIcon> LogoMap;
|
||||
typedef std::function<void(QString)> LogoCallback;
|
||||
|
||||
class ListModel : public QAbstractListModel
|
||||
{
|
||||
class ListModel : public QAbstractListModel {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
@ -64,14 +62,9 @@ private:
|
||||
QString currentSearchTerm;
|
||||
int currentSort = 0;
|
||||
int nextSearchOffset = 0;
|
||||
enum SearchState {
|
||||
None,
|
||||
CanPossiblyFetchMore,
|
||||
ResetRequested,
|
||||
Finished
|
||||
} searchState = None;
|
||||
enum SearchState { None, CanPossiblyFetchMore, ResetRequested, Finished } searchState = None;
|
||||
NetJob::Ptr jobPtr;
|
||||
QByteArray response;
|
||||
std::shared_ptr<QByteArray> response = std::make_shared<QByteArray>();
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace Flame
|
||||
|
@ -130,7 +130,7 @@ void FlamePage::onSelectionChanged(QModelIndex curr, QModelIndex prev)
|
||||
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();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
int addonId = current.addonId;
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QString("https://api.curseforge.com/v1/mods/%1/files").arg(addonId), response));
|
||||
|
||||
@ -170,10 +170,7 @@ void FlamePage::onSelectionChanged(QModelIndex curr, QModelIndex prev)
|
||||
}
|
||||
suggestCurrent();
|
||||
});
|
||||
QObject::connect(netJob, &NetJob::finished, this, [response, netJob] {
|
||||
netJob->deleteLater();
|
||||
delete response;
|
||||
});
|
||||
QObject::connect(netJob, &NetJob::finished, this, [response, netJob] { netJob->deleteLater(); });
|
||||
netJob->start();
|
||||
} else {
|
||||
for (auto version : current.versions) {
|
||||
|
@ -29,6 +29,11 @@ void FlameModModel::loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJsonAr
|
||||
FlameMod::loadIndexedPackVersions(m, arr, APPLICATION->network(), &m_base_instance);
|
||||
}
|
||||
|
||||
auto FlameModModel::loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr) -> ModPlatform::IndexedVersion
|
||||
{
|
||||
return FlameMod::loadDependencyVersions(m, arr);
|
||||
};
|
||||
|
||||
auto FlameModModel::documentToArray(QJsonDocument& obj) const -> QJsonArray
|
||||
{
|
||||
return Json::ensureArray(obj.object(), "data");
|
||||
|
@ -24,6 +24,7 @@ class FlameModModel : public ModModel {
|
||||
void loadIndexedPack(ModPlatform::IndexedPack& m, QJsonObject& obj) override;
|
||||
void loadExtraPackInfo(ModPlatform::IndexedPack& m, QJsonObject& obj) override;
|
||||
void loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJsonArray& arr) override;
|
||||
auto loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr) -> ModPlatform::IndexedVersion override;
|
||||
|
||||
auto documentToArray(QJsonDocument& obj) const -> QJsonArray override;
|
||||
};
|
||||
|
@ -38,11 +38,11 @@
|
||||
#include "net/HttpMetaCache.h"
|
||||
#include "net/NetJob.h"
|
||||
|
||||
#include "StringUtils.h"
|
||||
#include <Version.h>
|
||||
#include "StringUtils.h"
|
||||
|
||||
#include <QtMath>
|
||||
#include <QLabel>
|
||||
#include <QtMath>
|
||||
|
||||
#include <RWStorage.h>
|
||||
|
||||
@ -102,18 +102,13 @@ FilterModel::Sorting FilterModel::getCurrentSorting()
|
||||
return currentSorting;
|
||||
}
|
||||
|
||||
ListModel::ListModel(QObject *parent) : QAbstractListModel(parent)
|
||||
{
|
||||
}
|
||||
ListModel::ListModel(QObject* parent) : QAbstractListModel(parent) {}
|
||||
|
||||
ListModel::~ListModel()
|
||||
{
|
||||
}
|
||||
ListModel::~ListModel() {}
|
||||
|
||||
QString ListModel::translatePackType(PackType type) const
|
||||
{
|
||||
switch(type)
|
||||
{
|
||||
switch (type) {
|
||||
case PackType::Public:
|
||||
return tr("Public Modpack");
|
||||
case PackType::ThirdParty:
|
||||
@ -138,54 +133,38 @@ int ListModel::columnCount(const QModelIndex &parent) 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);
|
||||
}
|
||||
|
||||
Modpack pack = modpacks.at(pos);
|
||||
if(role == Qt::DisplayRole)
|
||||
{
|
||||
if (role == Qt::DisplayRole) {
|
||||
return pack.name + "\n" + translatePackType(pack.type);
|
||||
}
|
||||
else if (role == Qt::ToolTipRole)
|
||||
{
|
||||
if(pack.description.length() > 100)
|
||||
{
|
||||
} 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.logo))
|
||||
{
|
||||
} else if (role == Qt::DecorationRole) {
|
||||
if (m_logoMap.contains(pack.logo)) {
|
||||
return (m_logoMap.value(pack.logo));
|
||||
}
|
||||
QIcon icon = APPLICATION->getThemedIcon("screenshot-placeholder");
|
||||
((ListModel*)this)->requestLogo(pack.logo);
|
||||
return icon;
|
||||
}
|
||||
else if(role == Qt::ForegroundRole)
|
||||
{
|
||||
if(pack.broken)
|
||||
{
|
||||
} else if (role == Qt::ForegroundRole) {
|
||||
if (pack.broken) {
|
||||
// FIXME: Hardcoded color
|
||||
return QColor(255, 0, 50);
|
||||
}
|
||||
else if(pack.bugged)
|
||||
{
|
||||
} else if (pack.bugged) {
|
||||
// FIXME: Hardcoded color
|
||||
// bugged pack, currently only indicates bugged xml
|
||||
return QColor(244, 229, 66);
|
||||
}
|
||||
}
|
||||
else if(role == Qt::UserRole)
|
||||
{
|
||||
} else if (role == Qt::UserRole) {
|
||||
QVariant v;
|
||||
v.setValue(pack);
|
||||
return v;
|
||||
@ -222,8 +201,7 @@ Modpack ListModel::at(int row)
|
||||
|
||||
void ListModel::remove(int row)
|
||||
{
|
||||
if(row < 0 || row >= modpacks.size())
|
||||
{
|
||||
if (row < 0 || row >= modpacks.size()) {
|
||||
qWarning() << "Attempt to remove FTB modpacks with invalid row" << row;
|
||||
return;
|
||||
}
|
||||
@ -247,8 +225,7 @@ void ListModel::logoFailed(QString logo)
|
||||
|
||||
void ListModel::requestLogo(QString file)
|
||||
{
|
||||
if(m_loadingLogos.contains(file) || m_failedLogos.contains(file))
|
||||
{
|
||||
if (m_loadingLogos.contains(file) || m_failedLogos.contains(file)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@ -257,17 +234,16 @@ void ListModel::requestLogo(QString file)
|
||||
job->addNetAction(Net::Download::makeCached(QUrl(QString(BuildConfig.LEGACY_FTB_CDN_BASE_URL + "static/%1").arg(file)), entry));
|
||||
|
||||
auto fullPath = entry->getFullPath();
|
||||
QObject::connect(job, &NetJob::finished, this, [this, file, fullPath]
|
||||
{
|
||||
QObject::connect(job, &NetJob::finished, this, [this, file, fullPath, job] {
|
||||
job->deleteLater();
|
||||
emit logoLoaded(file, QIcon(fullPath));
|
||||
if(waitingCallbacks.contains(file))
|
||||
{
|
||||
if (waitingCallbacks.contains(file)) {
|
||||
waitingCallbacks.value(file)(fullPath);
|
||||
}
|
||||
});
|
||||
|
||||
QObject::connect(job, &NetJob::failed, this, [this, file]
|
||||
{
|
||||
QObject::connect(job, &NetJob::failed, this, [this, file, job] {
|
||||
job->deleteLater();
|
||||
emit logoFailed(file);
|
||||
});
|
||||
|
||||
@ -278,12 +254,9 @@ void ListModel::requestLogo(QString file)
|
||||
|
||||
void ListModel::getLogo(const QString& logo, LogoCallback callback)
|
||||
{
|
||||
if(m_logoMap.contains(logo))
|
||||
{
|
||||
if (m_logoMap.contains(logo)) {
|
||||
callback(APPLICATION->metacache()->resolveEntry("FTBPacks", QString("logos/%1").arg(logo.section(".", 0, 0)))->getFullPath());
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
requestLogo(logo);
|
||||
}
|
||||
}
|
||||
@ -293,4 +266,4 @@ Qt::ItemFlags ListModel::flags(const QModelIndex &index) const
|
||||
return QAbstractListModel::flags(index);
|
||||
}
|
||||
|
||||
}
|
||||
} // namespace LegacyFTB
|
||||
|
@ -142,16 +142,16 @@ void ModpackListModel::performPaginatedSearch()
|
||||
.arg(currentSearchTerm)
|
||||
.arg(currentSort);
|
||||
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchAllUrl), &m_all_response));
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchAllUrl), m_all_response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, this, [this] {
|
||||
QJsonParseError parse_error_all{};
|
||||
|
||||
QJsonDocument doc_all = QJsonDocument::fromJson(m_all_response, &parse_error_all);
|
||||
QJsonDocument doc_all = QJsonDocument::fromJson(*m_all_response, &parse_error_all);
|
||||
if (parse_error_all.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response from " << debugName() << " at " << parse_error_all.offset
|
||||
<< " reason: " << parse_error_all.errorString();
|
||||
qWarning() << m_all_response;
|
||||
qWarning() << *m_all_response;
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -110,9 +110,9 @@ class ModpackListModel : public QAbstractListModel {
|
||||
|
||||
NetJob::Ptr jobPtr;
|
||||
|
||||
QByteArray m_all_response;
|
||||
std::shared_ptr<QByteArray> m_all_response = std::make_shared<QByteArray>();
|
||||
QByteArray m_specific_response;
|
||||
|
||||
int m_modpacks_per_page = 20;
|
||||
};
|
||||
} // namespace ModPlatform
|
||||
} // namespace Modrinth
|
||||
|
@ -123,7 +123,7 @@ void ModrinthPage::onSelectionChanged(QModelIndex curr, QModelIndex prev)
|
||||
qDebug() << "Loading modrinth modpack information";
|
||||
|
||||
auto netJob = new NetJob(QString("Modrinth::PackInformation(%1)").arg(current.name), APPLICATION->network());
|
||||
auto response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
|
||||
QString id = current.id;
|
||||
|
||||
@ -162,10 +162,7 @@ void ModrinthPage::onSelectionChanged(QModelIndex curr, QModelIndex prev)
|
||||
|
||||
suggestCurrent();
|
||||
});
|
||||
QObject::connect(netJob, &NetJob::finished, this, [response, netJob] {
|
||||
netJob->deleteLater();
|
||||
delete response;
|
||||
});
|
||||
QObject::connect(netJob, &NetJob::finished, this, [response, netJob] { netJob->deleteLater(); });
|
||||
netJob->start();
|
||||
} else
|
||||
updateUI();
|
||||
@ -174,7 +171,7 @@ void ModrinthPage::onSelectionChanged(QModelIndex curr, QModelIndex prev)
|
||||
qDebug() << "Loading modrinth modpack versions";
|
||||
|
||||
auto netJob = new NetJob(QString("Modrinth::PackVersions(%1)").arg(current.name), APPLICATION->network());
|
||||
auto response = new QByteArray();
|
||||
auto response = std::make_shared<QByteArray>();
|
||||
|
||||
QString id = current.id;
|
||||
|
||||
@ -217,10 +214,7 @@ void ModrinthPage::onSelectionChanged(QModelIndex curr, QModelIndex prev)
|
||||
|
||||
suggestCurrent();
|
||||
});
|
||||
QObject::connect(netJob, &NetJob::finished, this, [response, netJob] {
|
||||
netJob->deleteLater();
|
||||
delete response;
|
||||
});
|
||||
QObject::connect(netJob, &NetJob::finished, this, [response, netJob] { netJob->deleteLater(); });
|
||||
netJob->start();
|
||||
|
||||
} else {
|
||||
@ -260,10 +254,8 @@ void ModrinthPage::updateUI()
|
||||
text += donates.join(", ");
|
||||
}
|
||||
|
||||
if (!current.extra.issuesUrl.isEmpty()
|
||||
|| !current.extra.sourceUrl.isEmpty()
|
||||
|| !current.extra.wikiUrl.isEmpty()
|
||||
|| !current.extra.discordUrl.isEmpty()) {
|
||||
if (!current.extra.issuesUrl.isEmpty() || !current.extra.sourceUrl.isEmpty() || !current.extra.wikiUrl.isEmpty() ||
|
||||
!current.extra.discordUrl.isEmpty()) {
|
||||
text += "<br><br>" + tr("External links:") + "<br>";
|
||||
}
|
||||
|
||||
|
@ -42,6 +42,11 @@ void ModrinthModModel::loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJso
|
||||
::Modrinth::loadIndexedPackVersions(m, arr, APPLICATION->network(), &m_base_instance);
|
||||
}
|
||||
|
||||
auto ModrinthModModel::loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr) -> ModPlatform::IndexedVersion
|
||||
{
|
||||
return ::Modrinth::loadDependencyVersions(m, arr);
|
||||
};
|
||||
|
||||
auto ModrinthModModel::documentToArray(QJsonDocument& obj) const -> QJsonArray
|
||||
{
|
||||
return obj.object().value("hits").toArray();
|
||||
|
@ -40,6 +40,7 @@ class ModrinthModModel : public ModModel {
|
||||
void loadIndexedPack(ModPlatform::IndexedPack& m, QJsonObject& obj) override;
|
||||
void loadExtraPackInfo(ModPlatform::IndexedPack& m, QJsonObject& obj) override;
|
||||
void loadIndexedPackVersions(ModPlatform::IndexedPack& m, QJsonArray& arr) override;
|
||||
auto loadDependencyVersions(const ModPlatform::Dependency& m, QJsonArray& arr) -> ModPlatform::IndexedVersion override;
|
||||
|
||||
auto documentToArray(QJsonDocument& obj) const -> QJsonArray override;
|
||||
};
|
||||
|
@ -40,39 +40,28 @@
|
||||
|
||||
#include <QIcon>
|
||||
|
||||
Technic::ListModel::ListModel(QObject *parent) : QAbstractListModel(parent)
|
||||
{
|
||||
}
|
||||
Technic::ListModel::ListModel(QObject* parent) : QAbstractListModel(parent) {}
|
||||
|
||||
Technic::ListModel::~ListModel()
|
||||
{
|
||||
}
|
||||
Technic::ListModel::~ListModel() {}
|
||||
|
||||
QVariant Technic::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);
|
||||
}
|
||||
|
||||
Modpack pack = modpacks.at(pos);
|
||||
if(role == Qt::DisplayRole)
|
||||
{
|
||||
if (role == Qt::DisplayRole) {
|
||||
return pack.name;
|
||||
}
|
||||
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);
|
||||
return icon;
|
||||
}
|
||||
else if(role == Qt::UserRole)
|
||||
{
|
||||
} else if (role == Qt::UserRole) {
|
||||
QVariant v;
|
||||
v.setValue(pack);
|
||||
return v;
|
||||
@ -100,8 +89,7 @@ void Technic::ListModel::searchWithTerm(const QString& term)
|
||||
jobPtr->abort();
|
||||
searchState = ResetRequested;
|
||||
return;
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
beginResetModel();
|
||||
modpacks.clear();
|
||||
endResetModel();
|
||||
@ -115,26 +103,20 @@ void Technic::ListModel::performSearch()
|
||||
auto netJob = makeShared<NetJob>("Technic::Search", APPLICATION->network());
|
||||
QString searchUrl = "";
|
||||
if (currentSearchTerm.isEmpty()) {
|
||||
searchUrl = QString("%1trending?build=%2")
|
||||
.arg(BuildConfig.TECHNIC_API_BASE_URL, BuildConfig.TECHNIC_API_BUILD);
|
||||
searchUrl = QString("%1trending?build=%2").arg(BuildConfig.TECHNIC_API_BASE_URL, BuildConfig.TECHNIC_API_BUILD);
|
||||
searchMode = List;
|
||||
}
|
||||
else if (currentSearchTerm.startsWith("http://api.technicpack.net/modpack/")) {
|
||||
searchUrl = QString("https://%1?build=%2")
|
||||
.arg(currentSearchTerm.mid(7), BuildConfig.TECHNIC_API_BUILD);
|
||||
} else if (currentSearchTerm.startsWith("http://api.technicpack.net/modpack/")) {
|
||||
searchUrl = QString("https://%1?build=%2").arg(currentSearchTerm.mid(7), BuildConfig.TECHNIC_API_BUILD);
|
||||
searchMode = Single;
|
||||
}
|
||||
else if (currentSearchTerm.startsWith("https://api.technicpack.net/modpack/")) {
|
||||
} else if (currentSearchTerm.startsWith("https://api.technicpack.net/modpack/")) {
|
||||
searchUrl = QString("%1?build=%2").arg(currentSearchTerm, BuildConfig.TECHNIC_API_BUILD);
|
||||
searchMode = Single;
|
||||
}
|
||||
else {
|
||||
searchUrl = QString(
|
||||
"%1search?build=%2&q=%3"
|
||||
).arg(BuildConfig.TECHNIC_API_BASE_URL, BuildConfig.TECHNIC_API_BUILD, currentSearchTerm);
|
||||
} else {
|
||||
searchUrl =
|
||||
QString("%1search?build=%2&q=%3").arg(BuildConfig.TECHNIC_API_BASE_URL, BuildConfig.TECHNIC_API_BUILD, currentSearchTerm);
|
||||
searchMode = List;
|
||||
}
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchUrl), &response));
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(searchUrl), response));
|
||||
jobPtr = netJob;
|
||||
jobPtr->start();
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, this, &ListModel::searchRequestFinished);
|
||||
@ -146,11 +128,11 @@ void Technic::ListModel::searchRequestFinished()
|
||||
jobPtr.reset();
|
||||
|
||||
QJsonParseError parse_error;
|
||||
QJsonDocument doc = QJsonDocument::fromJson(response, &parse_error);
|
||||
if(parse_error.error != QJsonParseError::NoError)
|
||||
{
|
||||
qWarning() << "Error while parsing JSON response from Technic at " << parse_error.offset << " reason: " << parse_error.errorString();
|
||||
qWarning() << response;
|
||||
QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error);
|
||||
if (parse_error.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response from Technic at " << parse_error.offset
|
||||
<< " reason: " << parse_error.errorString();
|
||||
qWarning() << *response;
|
||||
return;
|
||||
}
|
||||
|
||||
@ -173,8 +155,7 @@ void Technic::ListModel::searchRequestFinished()
|
||||
if (rawURL == "null") {
|
||||
pack.logoUrl = "null";
|
||||
pack.logoName = "null";
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
pack.logoUrl = rawURL;
|
||||
pack.logoName = rawURL.section(QLatin1Char('/'), -1).section(QLatin1Char('.'), 0, 0);
|
||||
}
|
||||
@ -199,8 +180,7 @@ void Technic::ListModel::searchRequestFinished()
|
||||
|
||||
pack.logoUrl = iconUrl;
|
||||
pack.logoName = iconUrl.section(QLatin1Char('/'), -1).section(QLatin1Char('.'), 0, 0);
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
pack.logoUrl = "null";
|
||||
pack.logoName = "null";
|
||||
}
|
||||
@ -210,9 +190,7 @@ void Technic::ListModel::searchRequestFinished()
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (const JSONValidationError &err)
|
||||
{
|
||||
} catch (const JSONValidationError& err) {
|
||||
qCritical() << "Couldn't parse technic search results:" << err.cause();
|
||||
return;
|
||||
}
|
||||
@ -229,12 +207,9 @@ void Technic::ListModel::searchRequestFinished()
|
||||
|
||||
void Technic::ListModel::getLogo(const QString& logo, const QString& logoUrl, Technic::LogoCallback callback)
|
||||
{
|
||||
if(m_logoMap.contains(logo))
|
||||
{
|
||||
if (m_logoMap.contains(logo)) {
|
||||
callback(APPLICATION->metacache()->resolveEntry("TechnicPacks", QString("logos/%1").arg(logo))->getFullPath());
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
requestLogo(logo, logoUrl);
|
||||
}
|
||||
}
|
||||
@ -243,29 +218,23 @@ void Technic::ListModel::searchRequestFailed()
|
||||
{
|
||||
jobPtr.reset();
|
||||
|
||||
if(searchState == ResetRequested)
|
||||
{
|
||||
if (searchState == ResetRequested) {
|
||||
beginResetModel();
|
||||
modpacks.clear();
|
||||
endResetModel();
|
||||
|
||||
performSearch();
|
||||
}
|
||||
else
|
||||
{
|
||||
} else {
|
||||
searchState = Finished;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Technic::ListModel::logoLoaded(QString logo, QString out)
|
||||
{
|
||||
m_loadingLogos.removeAll(logo);
|
||||
m_logoMap.insert(logo, QIcon(out));
|
||||
for(int i = 0; i < modpacks.size(); i++)
|
||||
{
|
||||
if(modpacks[i].logoName == logo)
|
||||
{
|
||||
for (int i = 0; i < modpacks.size(); i++) {
|
||||
if (modpacks[i].logoName == logo) {
|
||||
emit dataChanged(createIndex(i, 0), createIndex(i, 0), { Qt::DecorationRole });
|
||||
}
|
||||
}
|
||||
@ -279,24 +248,23 @@ void Technic::ListModel::logoFailed(QString logo)
|
||||
|
||||
void Technic::ListModel::requestLogo(QString logo, QString url)
|
||||
{
|
||||
if(m_loadingLogos.contains(logo) || m_failedLogos.contains(logo) || logo == "null")
|
||||
{
|
||||
if (m_loadingLogos.contains(logo) || m_failedLogos.contains(logo) || logo == "null") {
|
||||
return;
|
||||
}
|
||||
|
||||
MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry("TechnicPacks", QString("logos/%1").arg(logo));
|
||||
NetJob *job = new NetJob(QString("Technic Icon Download %1").arg(logo), APPLICATION->network());
|
||||
auto job = new NetJob(QString("Technic Icon Download %1").arg(logo), APPLICATION->network());
|
||||
job->addNetAction(Net::Download::makeCached(QUrl(url), entry));
|
||||
|
||||
auto fullPath = entry->getFullPath();
|
||||
|
||||
QObject::connect(job, &NetJob::succeeded, this, [this, logo, fullPath]
|
||||
{
|
||||
QObject::connect(job, &NetJob::succeeded, this, [this, logo, fullPath, job] {
|
||||
job->deleteLater();
|
||||
logoLoaded(logo, fullPath);
|
||||
});
|
||||
|
||||
QObject::connect(job, &NetJob::failed, this, [this, logo]
|
||||
{
|
||||
QObject::connect(job, &NetJob::failed, this, [this, logo, job] {
|
||||
job->deleteLater();
|
||||
logoFailed(logo);
|
||||
});
|
||||
|
||||
|
@ -44,8 +44,7 @@ namespace Technic {
|
||||
|
||||
typedef std::function<void(QString)> LogoCallback;
|
||||
|
||||
class ListModel : public QAbstractListModel
|
||||
{
|
||||
class ListModel : public QAbstractListModel {
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
@ -78,17 +77,13 @@ private:
|
||||
QMap<QString, LogoCallback> waitingCallbacks;
|
||||
|
||||
QString currentSearchTerm;
|
||||
enum SearchState {
|
||||
None,
|
||||
ResetRequested,
|
||||
Finished
|
||||
} searchState = None;
|
||||
enum SearchState { None, ResetRequested, Finished } searchState = None;
|
||||
enum SearchMode {
|
||||
List,
|
||||
Single,
|
||||
} searchMode = List;
|
||||
NetJob::Ptr jobPtr;
|
||||
QByteArray response;
|
||||
std::shared_ptr<QByteArray> response = std::make_shared<QByteArray>();
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace Technic
|
||||
|
@ -143,7 +143,7 @@ void TechnicPage::suggestCurrent()
|
||||
|
||||
auto netJob = makeShared<NetJob>(QString("Technic::PackMeta(%1)").arg(current.name), APPLICATION->network());
|
||||
QString slug = current.slug;
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QString("%1modpack/%2?build=%3").arg(BuildConfig.TECHNIC_API_BASE_URL, slug, BuildConfig.TECHNIC_API_BUILD), &response));
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QString("%1modpack/%2?build=%3").arg(BuildConfig.TECHNIC_API_BASE_URL, slug, BuildConfig.TECHNIC_API_BUILD), response));
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, this, [this, slug]
|
||||
{
|
||||
jobPtr.reset();
|
||||
@ -154,7 +154,7 @@ void TechnicPage::suggestCurrent()
|
||||
}
|
||||
|
||||
QJsonParseError parse_error {};
|
||||
QJsonDocument doc = QJsonDocument::fromJson(response, &parse_error);
|
||||
QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error);
|
||||
QJsonObject obj = doc.object();
|
||||
if(parse_error.error != QJsonParseError::NoError)
|
||||
{
|
||||
@ -249,7 +249,7 @@ void TechnicPage::metadataLoaded()
|
||||
|
||||
auto netJob = makeShared<NetJob>(QString("Technic::SolderMeta(%1)").arg(current.name), APPLICATION->network());
|
||||
auto url = QString("%1/modpack/%2").arg(current.url, current.slug);
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(url), &response));
|
||||
netJob->addNetAction(Net::Download::makeByteArray(QUrl(url), response));
|
||||
|
||||
QObject::connect(netJob.get(), &NetJob::succeeded, this, &TechnicPage::onSolderLoaded);
|
||||
|
||||
@ -292,10 +292,10 @@ void TechnicPage::onSolderLoaded() {
|
||||
current.versions.clear();
|
||||
|
||||
QJsonParseError parse_error{};
|
||||
auto doc = QJsonDocument::fromJson(response, &parse_error);
|
||||
auto doc = QJsonDocument::fromJson(*response, &parse_error);
|
||||
if (parse_error.error != QJsonParseError::NoError) {
|
||||
qWarning() << "Error while parsing JSON response from Solder at " << parse_error.offset << " reason: " << parse_error.errorString();
|
||||
qWarning() << response;
|
||||
qWarning() << *response;
|
||||
fallback();
|
||||
return;
|
||||
}
|
||||
@ -304,8 +304,7 @@ void TechnicPage::onSolderLoaded() {
|
||||
TechnicSolder::Pack pack;
|
||||
try {
|
||||
TechnicSolder::loadPack(pack, obj);
|
||||
}
|
||||
catch (const JSONValidationError& err) {
|
||||
} catch (const JSONValidationError& err) {
|
||||
qCritical() << "Couldn't parse Solder pack metadata:" << err.cause();
|
||||
fallback();
|
||||
return;
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user