1
0
mirror of https://github.com/vcmi/vcmi.git synced 2024-11-28 08:48:48 +02:00

Code style: formatting and refactoring of launcher code

This commit is contained in:
Arseniy Shestakov 2018-04-13 12:34:58 +07:00 committed by ArseniyShestakov
parent d9d5b7b6e5
commit 9da3f48274
18 changed files with 449 additions and 406 deletions

View File

@ -14,7 +14,7 @@
static QVariantMap JsonToMap(const JsonMap & json)
{
QVariantMap map;
for (auto & entry : json)
for(auto & entry : json)
{
map.insert(QString::fromUtf8(entry.first.c_str()), JsonUtils::toVariant(entry.second));
}
@ -24,7 +24,7 @@ static QVariantMap JsonToMap(const JsonMap & json)
static QVariantList JsonToList(const JsonVector & json)
{
QVariantList list;
for (auto & entry : json)
for(auto & entry : json)
{
list.push_back(JsonUtils::toVariant(entry));
}
@ -34,7 +34,7 @@ static QVariantList JsonToList(const JsonVector & json)
static JsonVector VariantToList(QVariantList variant)
{
JsonVector vector;
for (auto & entry : variant)
for(auto & entry : variant)
{
vector.push_back(JsonUtils::toJson(entry));
}
@ -44,7 +44,7 @@ static JsonVector VariantToList(QVariantList variant)
static JsonMap VariantToMap(QVariantMap variant)
{
JsonMap map;
for (auto & entry : variant.toStdMap())
for(auto & entry : variant.toStdMap())
{
map[entry.first.toUtf8().data()] = JsonUtils::toJson(entry.second);
}
@ -56,14 +56,26 @@ namespace JsonUtils
QVariant toVariant(const JsonNode & node)
{
switch (node.getType())
switch(node.getType())
{
break; case JsonNode::JsonType::DATA_NULL: return QVariant();
break; case JsonNode::JsonType::DATA_BOOL: return QVariant(node.Bool());
break; case JsonNode::JsonType::DATA_FLOAT: return QVariant(node.Float());
break; case JsonNode::JsonType::DATA_STRING: return QVariant(QString::fromUtf8(node.String().c_str()));
break; case JsonNode::JsonType::DATA_VECTOR: return JsonToList(node.Vector());
break; case JsonNode::JsonType::DATA_STRUCT: return JsonToMap(node.Struct());
break;
case JsonNode::JsonType::DATA_NULL:
return QVariant();
break;
case JsonNode::JsonType::DATA_BOOL:
return QVariant(node.Bool());
break;
case JsonNode::JsonType::DATA_FLOAT:
return QVariant(node.Float());
break;
case JsonNode::JsonType::DATA_STRING:
return QVariant(QString::fromUtf8(node.String().c_str()));
break;
case JsonNode::JsonType::DATA_VECTOR:
return JsonToList(node.Vector());
break;
case JsonNode::JsonType::DATA_STRUCT:
return JsonToMap(node.Struct());
}
return QVariant();
}
@ -74,7 +86,7 @@ QVariant JsonFromFile(QString filename)
file.open(QFile::ReadOnly);
auto data = file.readAll();
if (data.size() == 0)
if(data.size() == 0)
{
logGlobal->error("Failed to open file %s", filename.toUtf8().data());
return QVariant();
@ -90,15 +102,15 @@ JsonNode toJson(QVariant object)
{
JsonNode ret;
if (object.canConvert<QVariantMap>())
if(object.canConvert<QVariantMap>())
ret.Struct() = VariantToMap(object.toMap());
else if (object.canConvert<QVariantList>())
else if(object.canConvert<QVariantList>())
ret.Vector() = VariantToList(object.toList());
else if (static_cast<QMetaType::Type>(object.type()) == QMetaType::QString)
else if(static_cast<QMetaType::Type>(object.type()) == QMetaType::QString)
ret.String() = object.toString().toUtf8().data();
else if (static_cast<QMetaType::Type>(object.type()) == QMetaType::Bool)
else if(static_cast<QMetaType::Type>(object.type()) == QMetaType::Bool)
ret.Bool() = object.toBool();
else if (object.canConvert<double>())
else if(object.canConvert<double>())
ret.Float() = object.toFloat();
return ret;

View File

@ -14,9 +14,9 @@
namespace JsonUtils
{
QVariant toVariant(const JsonNode & node);
QVariant JsonFromFile(QString filename);
QVariant toVariant(const JsonNode & node);
QVariant JsonFromFile(QString filename);
JsonNode toJson(QVariant object);
void JsonToFile(QString filename, QVariant object);
JsonNode toJson(QVariant object);
void JsonToFile(QString filename, QVariant object);
}

View File

@ -32,31 +32,28 @@ void MainWindow::load()
CResourceHandler::initialize();
CResourceHandler::load("config/filesystem.json");
for (auto & string : VCMIDirs::get().dataPaths())
for(auto & string : VCMIDirs::get().dataPaths())
QDir::addSearchPath("icons", pathToQString(string / "launcher" / "icons"));
QDir::addSearchPath("icons", pathToQString(VCMIDirs::get().userDataPath() / "launcher" / "icons"));
settings.init(true);
}
MainWindow::MainWindow(QWidget * parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
MainWindow::MainWindow(QWidget * parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
load(); // load FS before UI
ui->setupUi(this);
auto width = ui->startGameTitle->fontMetrics().boundingRect(ui->startGameTitle->text()).width();
if (ui->startGameButton->iconSize().width() < width)
if(ui->startGameButton->iconSize().width() < width)
{
ui->startGameButton->setIconSize(QSize(width, width));
}
auto tab_icon_size = ui->tabSelectList->iconSize();
if (tab_icon_size.width() < width)
if(tab_icon_size.width() < width)
{
ui->tabSelectList->setIconSize(QSize(
width,
width + tab_icon_size.height() - tab_icon_size.width()));
ui->tabSelectList->setIconSize(QSize(width, width + tab_icon_size.height() - tab_icon_size.width()));
ui->tabSelectList->setGridSize(QSize(width, width));
// 4 is a dirty hack to make it look right
ui->tabSelectList->setMaximumWidth(width + 4);
@ -65,7 +62,7 @@ MainWindow::MainWindow(QWidget * parent) :
ui->settingsView->setDisplayList();
connect(ui->tabSelectList, SIGNAL(currentRowChanged(int)),
ui->tabListWidget, SLOT(setCurrentIndex(int)));
ui->tabListWidget, SLOT(setCurrentIndex(int)));
}
MainWindow::~MainWindow()
@ -83,7 +80,7 @@ void MainWindow::startExecutable(QString name)
QProcess process;
// Start the executable
if (process.startDetached(name))
if(process.startDetached(name))
{
close(); // exit launcher
}

View File

@ -11,8 +11,9 @@
#include <QMainWindow>
#include <QStringList>
namespace Ui {
class MainWindow;
namespace Ui
{
class MainWindow;
}
class QTableWidgetItem;
@ -20,10 +21,12 @@ class QTableWidgetItem;
class MainWindow : public QMainWindow
{
Q_OBJECT
private:
Ui::MainWindow *ui;
Ui::MainWindow * ui;
void load();
void startExecutable(QString name);
public:
explicit MainWindow(QWidget * parent = 0);
~MainWindow();

View File

@ -14,11 +14,11 @@
CDownloadManager::CDownloadManager()
{
connect(&manager, SIGNAL(finished(QNetworkReply*)),
SLOT(downloadFinished(QNetworkReply*)));
connect(&manager, SIGNAL(finished(QNetworkReply *)),
SLOT(downloadFinished(QNetworkReply *)));
}
void CDownloadManager::downloadFile(const QUrl &url, const QString &file)
void CDownloadManager::downloadFile(const QUrl & url, const QString & file)
{
QNetworkRequest request(url);
FileEntry entry;
@ -26,18 +26,18 @@ void CDownloadManager::downloadFile(const QUrl &url, const QString &file)
entry.bytesReceived = 0;
entry.totalSize = 0;
if (entry.file->open(QIODevice::WriteOnly | QIODevice::Truncate))
if(entry.file->open(QIODevice::WriteOnly | QIODevice::Truncate))
{
entry.status = FileEntry::IN_PROGRESS;
entry.reply = manager.get(request);
connect(entry.reply, SIGNAL(downloadProgress(qint64, qint64)),
SLOT(downloadProgressChanged(qint64, qint64)));
connect(entry.reply, SIGNAL(downloadProgress(qint64,qint64)),
SLOT(downloadProgressChanged(qint64,qint64)));
}
else
{
entry.status = FileEntry::FAILED;
entry.reply = nullptr;
entry.reply = nullptr;
encounteredErrors += entry.file->errorString();
}
@ -48,9 +48,9 @@ void CDownloadManager::downloadFile(const QUrl &url, const QString &file)
CDownloadManager::FileEntry & CDownloadManager::getEntry(QNetworkReply * reply)
{
assert(reply);
for (auto & entry : currentDownloads)
for(auto & entry : currentDownloads)
{
if (entry.reply == reply)
if(entry.reply == reply)
return entry;
}
assert(0);
@ -58,11 +58,11 @@ CDownloadManager::FileEntry & CDownloadManager::getEntry(QNetworkReply * reply)
return errorValue;
}
void CDownloadManager::downloadFinished(QNetworkReply *reply)
void CDownloadManager::downloadFinished(QNetworkReply * reply)
{
FileEntry & file = getEntry(reply);
if (file.reply->error())
if(file.reply->error())
{
encounteredErrors += file.reply->errorString();
file.file->remove();
@ -76,9 +76,9 @@ void CDownloadManager::downloadFinished(QNetworkReply *reply)
}
bool downloadComplete = true;
for (auto & entry : currentDownloads)
for(auto & entry : currentDownloads)
{
if (entry.status == FileEntry::IN_PROGRESS)
if(entry.status == FileEntry::IN_PROGRESS)
{
downloadComplete = false;
break;
@ -88,15 +88,15 @@ void CDownloadManager::downloadFinished(QNetworkReply *reply)
QStringList successful;
QStringList failed;
for (auto & entry : currentDownloads)
for(auto & entry : currentDownloads)
{
if (entry.status == FileEntry::FINISHED)
if(entry.status == FileEntry::FINISHED)
successful += entry.file->fileName();
else
failed += entry.file->fileName();
}
if (downloadComplete)
if(downloadComplete)
emit finished(successful, failed, encounteredErrors);
file.reply->deleteLater();
@ -113,21 +113,21 @@ void CDownloadManager::downloadProgressChanged(qint64 bytesReceived, qint64 byte
entry.totalSize = bytesTotal;
quint64 total = 0;
for (auto & entry : currentDownloads)
for(auto & entry : currentDownloads)
total += entry.totalSize > 0 ? entry.totalSize : 0;
quint64 received = 0;
for (auto & entry : currentDownloads)
for(auto & entry : currentDownloads)
received += entry.bytesReceived > 0 ? entry.bytesReceived : 0;
emit downloadProgress(received, total);
}
bool CDownloadManager::downloadInProgress(const QUrl &url)
bool CDownloadManager::downloadInProgress(const QUrl & url)
{
for (auto & entry : currentDownloads)
for(auto & entry : currentDownloads)
{
if (entry.reply->url() == url)
if(entry.reply->url() == url)
return true;
}
return false;

View File

@ -14,7 +14,7 @@
class QFile;
class CDownloadManager: public QObject
class CDownloadManager : public QObject
{
Q_OBJECT
@ -41,18 +41,19 @@ class CDownloadManager: public QObject
QList<FileEntry> currentDownloads;
FileEntry & getEntry(QNetworkReply * reply);
public:
CDownloadManager();
// returns true if download with such URL is in progress/queued
// FIXME: not sure what's right place for "mod download in progress" check
bool downloadInProgress(const QUrl &url);
bool downloadInProgress(const QUrl & url);
// returns network reply so caller can connect to required signals
void downloadFile(const QUrl &url, const QString &file);
void downloadFile(const QUrl & url, const QString & file);
public slots:
void downloadFinished(QNetworkReply *reply);
void downloadFinished(QNetworkReply * reply);
void downloadProgressChanged(qint64 bytesReceived, qint64 bytesTotal);
signals:

View File

@ -23,15 +23,15 @@ bool CModEntry::compareVersions(QString lesser, QString greater)
assert(lesserList.size() <= maxSections);
assert(greaterList.size() <= maxSections);
for (int i=0; i< maxSections; i++)
for(int i = 0; i < maxSections; i++)
{
if (greaterList.size() <= i) // 1.1.1 > 1.1
if(greaterList.size() <= i) // 1.1.1 > 1.1
return false;
if (lesserList.size() <= i) // 1.1 < 1.1.1
if(lesserList.size() <= i) // 1.1 < 1.1.1
return true;
if (lesserList[i].toInt() != greaterList[i].toInt())
if(lesserList[i].toInt() != greaterList[i].toInt())
return lesserList[i].toInt() < greaterList[i].toInt(); // 1.1 < 1.2
}
return false;
@ -41,10 +41,10 @@ QString CModEntry::sizeToString(double size)
{
static const QString sizes[] =
{
/*"%1 B", */"%1 KiB", "%1 MiB", "%1 GiB", "%1 TiB"
/*"%1 B", */ "%1 KiB", "%1 MiB", "%1 GiB", "%1 TiB"
};
size_t index = 0;
while (size > 1024 && index < 4)
while(size > 1024 && index < 4)
{
size /= 1024;
index++;
@ -52,17 +52,14 @@ QString CModEntry::sizeToString(double size)
return sizes[index].arg(QString::number(size, 'f', 1));
}
CModEntry::CModEntry(QVariantMap repository, QVariantMap localData, QVariantMap modSettings, QString modname):
repository(repository),
localData(localData),
modSettings(modSettings),
modname(modname)
CModEntry::CModEntry(QVariantMap repository, QVariantMap localData, QVariantMap modSettings, QString modname)
: repository(repository), localData(localData), modSettings(modSettings), modname(modname)
{
}
bool CModEntry::isEnabled() const
{
if (!isInstalled())
if(!isInstalled())
return false;
return modSettings["active"].toBool();
@ -70,27 +67,27 @@ bool CModEntry::isEnabled() const
bool CModEntry::isDisabled() const
{
if (!isInstalled())
if(!isInstalled())
return false;
return !isEnabled();
}
bool CModEntry::isAvailable() const
{
if (isInstalled())
if(isInstalled())
return false;
return !repository.isEmpty();
}
bool CModEntry::isUpdateable() const
{
if (!isInstalled())
if(!isInstalled())
return false;
QString installedVer = localData["installedVersion"].toString();
QString availableVer = repository["latestVersion"].toString();
if (compareVersions(installedVer, availableVer))
if(compareVersions(installedVer, availableVer))
return true;
return false;
}
@ -102,10 +99,15 @@ bool CModEntry::isInstalled() const
int CModEntry::getModStatus() const
{
return
(isEnabled() ? ModStatus::ENABLED : 0) |
(isInstalled() ? ModStatus::INSTALLED : 0) |
(isUpdateable()? ModStatus::UPDATEABLE : 0);
int status = 0;
if(isEnabled())
status |= ModStatus::ENABLED;
if(isInstalled())
status |= ModStatus::INSTALLED;
if(isUpdateable())
status |= ModStatus::UPDATEABLE;
return status;
}
QString CModEntry::getName() const
@ -115,22 +117,22 @@ QString CModEntry::getName() const
QVariant CModEntry::getValue(QString value) const
{
if (repository.contains(value) && localData.contains(value))
if(repository.contains(value) && localData.contains(value))
{
// value is present in both repo and locally installed. Select one from latest version
QString installedVer = localData["installedVersion"].toString();
QString availableVer = repository["latestVersion"].toString();
if (compareVersions(installedVer, availableVer))
if(compareVersions(installedVer, availableVer))
return repository[value];
else
return localData[value];
}
if (repository.contains(value))
if(repository.contains(value))
return repository[value];
if (localData.contains(value))
if(localData.contains(value))
return localData[value];
return QVariant();
@ -140,7 +142,7 @@ QVariantMap CModList::copyField(QVariantMap data, QString from, QString to)
{
QVariantMap renamed;
for (auto it = data.begin(); it != data.end(); it++)
for(auto it = data.begin(); it != data.end(); it++)
{
QVariantMap modConf = it.value().toMap();
@ -176,7 +178,7 @@ void CModList::modChanged(QString modID)
static QVariant getValue(QVariantMap input, QString path)
{
if (path.size() > 1)
if(path.size() > 1)
{
QString entryName = path.section('/', 0, 1);
QString remainder = "/" + path.section('/', 2, -1);
@ -200,28 +202,30 @@ CModEntry CModList::getMod(QString modname) const
path = "/" + path.replace(".", "/mods/");
QVariant conf = getValue(modSettings, path);
if (conf.isNull())
if(conf.isNull())
{
settings["active"] = true; // default
}
else
{
if (conf.canConvert<QVariantMap>())
if(conf.canConvert<QVariantMap>())
settings = conf.toMap();
else
settings.insert("active", conf);
}
for (auto entry : repositories)
for(auto entry : repositories)
{
QVariant repoVal = getValue(entry, path);
if (repoVal.isValid())
if(repoVal.isValid())
{
if (repo.empty())
if(repo.empty())
{
repo = repoVal.toMap();
}
else
{
if (CModEntry::compareVersions(repo["version"].toString(), repoVal.toMap()["version"].toString()))
if(CModEntry::compareVersions(repo["version"].toString(), repoVal.toMap()["version"].toString()))
repo = repoVal.toMap();
}
}
@ -232,11 +236,11 @@ CModEntry CModList::getMod(QString modname) const
bool CModList::hasMod(QString modname) const
{
if (localModList.contains(modname))
if(localModList.contains(modname))
return true;
for (auto entry : repositories)
if (entry.contains(modname))
for(auto entry : repositories)
if(entry.contains(modname))
return true;
return false;
@ -246,11 +250,11 @@ QStringList CModList::getRequirements(QString modname)
{
QStringList ret;
if (hasMod(modname))
if(hasMod(modname))
{
auto mod = getMod(modname);
for (auto entry : mod.getValue("depends").toStringList())
for(auto entry : mod.getValue("depends").toStringList())
ret += getRequirements(entry);
}
ret += modname;
@ -262,19 +266,19 @@ QVector<QString> CModList::getModList() const
{
QSet<QString> knownMods;
QVector<QString> modList;
for (auto repo : repositories)
for(auto repo : repositories)
{
for (auto it = repo.begin(); it != repo.end(); it++)
for(auto it = repo.begin(); it != repo.end(); it++)
{
knownMods.insert(it.key());
}
}
for (auto it = localModList.begin(); it != localModList.end(); it++)
for(auto it = localModList.begin(); it != localModList.end(); it++)
{
knownMods.insert(it.key());
}
for (auto entry : knownMods)
for(auto entry : knownMods)
{
modList.push_back(entry);
}
@ -286,9 +290,9 @@ QVector<QString> CModList::getChildren(QString parent) const
QVector<QString> children;
int depth = parent.count('.') + 1;
for (const QString & mod : getModList())
for(const QString & mod : getModList())
{
if (mod.count('.') == depth && mod.startsWith(parent))
if(mod.count('.') == depth && mod.startsWith(parent))
children.push_back(mod);
}
return children;

View File

@ -17,14 +17,14 @@ class JsonNode;
namespace ModStatus
{
enum EModStatus
{
MASK_NONE = 0,
ENABLED = 1,
INSTALLED = 2,
UPDATEABLE = 4,
MASK_ALL = 255
};
enum EModStatus
{
MASK_NONE = 0,
ENABLED = 1,
INSTALLED = 2,
UPDATEABLE = 4,
MASK_ALL = 255
};
}
class CModEntry
@ -35,6 +35,7 @@ class CModEntry
QVariantMap modSettings;
QString modname;
public:
CModEntry(QVariantMap repository, QVariantMap localData, QVariantMap modSettings, QString modname);
@ -70,6 +71,7 @@ class CModList
QVariantMap modSettings;
QVariantMap copyField(QVariantMap data, QString from, QString to);
public:
virtual void resetRepositories();
virtual void addRepository(QVariantMap data);

View File

@ -14,64 +14,64 @@
namespace ModFields
{
static const QString names [ModFields::COUNT] =
{
"name",
"",
"",
"modType",
"version",
"size",
"author"
};
static const QString names[ModFields::COUNT] =
{
"name",
"",
"",
"modType",
"version",
"size",
"author"
};
static const QString header [ModFields::COUNT] =
{
"Name",
"", // status icon
"", // status icon
"Type",
"Version",
"Size",
"Author"
};
static const QString header[ModFields::COUNT] =
{
"Name",
"", // status icon
"", // status icon
"Type",
"Version",
"Size",
"Author"
};
}
namespace ModStatus
{
static const QString iconDelete = "icons:mod-delete.png";
static const QString iconDisabled = "icons:mod-disabled.png";
static const QString iconDownload = "icons:mod-download.png";
static const QString iconEnabled = "icons:mod-enabled.png";
static const QString iconUpdate = "icons:mod-update.png";
static const QString iconDelete = "icons:mod-delete.png";
static const QString iconDisabled = "icons:mod-disabled.png";
static const QString iconDownload = "icons:mod-download.png";
static const QString iconEnabled = "icons:mod-enabled.png";
static const QString iconUpdate = "icons:mod-update.png";
}
CModListModel::CModListModel(QObject *parent) :
QAbstractItemModel(parent)
CModListModel::CModListModel(QObject * parent)
: QAbstractItemModel(parent)
{
}
QString CModListModel::modIndexToName(const QModelIndex & index) const
{
if (index.isValid())
if(index.isValid())
{
return modNameToID.at(index.internalId());
}
return "";
}
QVariant CModListModel::getValue(const CModEntry &mod, int field) const
QVariant CModListModel::getValue(const CModEntry & mod, int field) const
{
switch(field)
{
case ModFields::STATUS_ENABLED:
return mod.getModStatus() & (ModStatus::ENABLED | ModStatus::INSTALLED);
case ModFields::STATUS_ENABLED:
return mod.getModStatus() & (ModStatus::ENABLED | ModStatus::INSTALLED);
case ModFields::STATUS_UPDATE:
return mod.getModStatus() & (ModStatus::UPDATEABLE | ModStatus::INSTALLED);
case ModFields::STATUS_UPDATE:
return mod.getModStatus() & (ModStatus::UPDATEABLE | ModStatus::INSTALLED);
default:
return mod.getValue(ModFields::names[field]);
default:
return mod.getValue(ModFields::names[field]);
}
}
@ -79,26 +79,26 @@ QVariant CModListModel::getText(const CModEntry & mod, int field) const
{
switch(field)
{
case ModFields::STATUS_ENABLED:
case ModFields::STATUS_UPDATE:
return "";
case ModFields::SIZE:
return CModEntry::sizeToString(getValue(mod, field).toDouble());
default:
return getValue(mod, field);
case ModFields::STATUS_ENABLED:
case ModFields::STATUS_UPDATE:
return "";
case ModFields::SIZE:
return CModEntry::sizeToString(getValue(mod, field).toDouble());
default:
return getValue(mod, field);
}
}
QVariant CModListModel::getIcon(const CModEntry & mod, int field) const
{
if (field == ModFields::STATUS_ENABLED && mod.isEnabled())
if(field == ModFields::STATUS_ENABLED && mod.isEnabled())
return QIcon(ModStatus::iconEnabled);
if (field == ModFields::STATUS_ENABLED && mod.isDisabled())
if(field == ModFields::STATUS_ENABLED && mod.isDisabled())
return QIcon(ModStatus::iconDisabled);
if (field == ModFields::STATUS_UPDATE && mod.isUpdateable())
if(field == ModFields::STATUS_UPDATE && mod.isUpdateable())
return QIcon(ModStatus::iconUpdate);
if (field == ModFields::STATUS_UPDATE && !mod.isInstalled())
if(field == ModFields::STATUS_UPDATE && !mod.isInstalled())
return QIcon(ModStatus::iconDownload);
return QVariant();
@ -106,26 +106,31 @@ QVariant CModListModel::getIcon(const CModEntry & mod, int field) const
QVariant CModListModel::getTextAlign(int field) const
{
if (field == ModFields::SIZE)
if(field == ModFields::SIZE)
return QVariant(Qt::AlignRight | Qt::AlignVCenter);
//if (field == ModFields::NAME)
// return QVariant(Qt::AlignHCenter | Qt::AlignVCenter);
return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
return QVariant(Qt::AlignLeft | Qt::AlignVCenter);
}
QVariant CModListModel::data(const QModelIndex &index, int role) const
QVariant CModListModel::data(const QModelIndex & index, int role) const
{
if (index.isValid())
if(index.isValid())
{
auto mod = getMod(modIndexToName(index));
switch (role)
switch(role)
{
case Qt::DecorationRole: return getIcon(mod, index.column());
case Qt::DisplayRole: return getText(mod, index.column());
case Qt::TextAlignmentRole: return getTextAlign(index.column());
case ModRoles::ValueRole: return getValue(mod, index.column());
case ModRoles::ModNameRole: return mod.getName();
case Qt::DecorationRole:
return getIcon(mod, index.column());
case Qt::DisplayRole:
return getText(mod, index.column());
case Qt::TextAlignmentRole:
return getTextAlign(index.column());
case ModRoles::ValueRole:
return getValue(mod, index.column());
case ModRoles::ModNameRole:
return mod.getName();
}
}
return QVariant();
@ -133,7 +138,7 @@ QVariant CModListModel::data(const QModelIndex &index, int role) const
int CModListModel::rowCount(const QModelIndex & index) const
{
if (index.isValid())
if(index.isValid())
return modIndex[modIndexToName(index)].size();
return modIndex[""].size();
}
@ -150,7 +155,7 @@ Qt::ItemFlags CModListModel::flags(const QModelIndex &) const
QVariant CModListModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal)
if(role == Qt::DisplayRole && orientation == Qt::Horizontal)
return ModFields::header[section];
return QVariant();
}
@ -172,7 +177,7 @@ void CModListModel::addRepository(QVariantMap data)
void CModListModel::modChanged(QString modID)
{
int index = modNameToID.indexOf(modID);
QModelIndex parent = this->parent(createIndex(0, 0, index));
QModelIndex parent = this->parent(createIndex(0, 0, index));
int row = modIndex[modIndexToName(parent)].indexOf(modID);
emit dataChanged(createIndex(row, 0, index), createIndex(row, 4, index));
}
@ -181,9 +186,9 @@ void CModListModel::endResetModel()
{
modNameToID = getModList();
modIndex.clear();
for (const QString & str : modNameToID)
for(const QString & str : modNameToID)
{
if (str.contains('.'))
if(str.contains('.'))
{
modIndex[str.section('.', 0, -2)].append(str);
}
@ -195,27 +200,27 @@ void CModListModel::endResetModel()
QAbstractItemModel::endResetModel();
}
QModelIndex CModListModel::index(int row, int column, const QModelIndex &parent) const
QModelIndex CModListModel::index(int row, int column, const QModelIndex & parent) const
{
if (parent.isValid())
if(parent.isValid())
{
if (modIndex[modIndexToName(parent)].size() > row)
if(modIndex[modIndexToName(parent)].size() > row)
return createIndex(row, column, modNameToID.indexOf(modIndex[modIndexToName(parent)][row]));
}
else
{
if (modIndex[""].size() > row)
if(modIndex[""].size() > row)
return createIndex(row, column, modNameToID.indexOf(modIndex[""][row]));
}
return QModelIndex();
}
QModelIndex CModListModel::parent(const QModelIndex &child) const
QModelIndex CModListModel::parent(const QModelIndex & child) const
{
QString modID = modNameToID[child.internalId()];
for (auto entry = modIndex.begin(); entry != modIndex.end(); entry++) // because using range-for entry type is QMap::value_type oO
for(auto entry = modIndex.begin(); entry != modIndex.end(); entry++) // because using range-for entry type is QMap::value_type oO
{
if (entry.key() != "" && entry.value().indexOf(modID) != -1)
if(entry.key() != "" && entry.value().indexOf(modID) != -1)
{
return createIndex(entry.value().indexOf(modID), child.column(), modNameToID.indexOf(entry.key()));
}
@ -230,43 +235,40 @@ void CModFilterModel::setTypeFilter(int filteredType, int filterMask)
invalidateFilter();
}
bool CModFilterModel::filterMatchesThis(const QModelIndex &source) const
bool CModFilterModel::filterMatchesThis(const QModelIndex & source) const
{
CModEntry mod = base->getMod(source.data(ModRoles::ModNameRole).toString());
return (mod.getModStatus() & filterMask) == filteredType &&
QSortFilterProxyModel::filterAcceptsRow(source.row(), source.parent());
QSortFilterProxyModel::filterAcceptsRow(source.row(), source.parent());
}
bool CModFilterModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
bool CModFilterModel::filterAcceptsRow(int source_row, const QModelIndex & source_parent) const
{
QModelIndex index = base->index(source_row, 0, source_parent);
if (filterMatchesThis(index))
if(filterMatchesThis(index))
{
return true;
}
for (size_t i=0; i<base->rowCount(index); i++)
for(size_t i = 0; i < base->rowCount(index); i++)
{
if (filterMatchesThis(index.child(i, 0)))
if(filterMatchesThis(index.child(i, 0)))
return true;
}
QModelIndex parent = source_parent;
while (parent.isValid())
while(parent.isValid())
{
if (filterMatchesThis(parent))
if(filterMatchesThis(parent))
return true;
parent = parent.parent();
}
return false;
}
CModFilterModel::CModFilterModel(CModListModel * model, QObject * parent):
QSortFilterProxyModel(parent),
base(model),
filteredType(ModStatus::MASK_NONE),
filterMask(ModStatus::MASK_NONE)
CModFilterModel::CModFilterModel(CModListModel * model, QObject * parent)
: QSortFilterProxyModel(parent), base(model), filteredType(ModStatus::MASK_NONE), filterMask(ModStatus::MASK_NONE)
{
setSourceModel(model);
setSortRole(ModRoles::ValueRole);

View File

@ -16,26 +16,26 @@
namespace ModFields
{
enum EModFields
{
NAME,
STATUS_ENABLED,
STATUS_UPDATE,
TYPE,
VERSION,
SIZE,
AUTHOR,
COUNT
};
enum EModFields
{
NAME,
STATUS_ENABLED,
STATUS_UPDATE,
TYPE,
VERSION,
SIZE,
AUTHOR,
COUNT
};
}
namespace ModRoles
{
enum EModRoles
{
ValueRole = Qt::UserRole,
ModNameRole
};
enum EModRoles
{
ValueRole = Qt::UserRole,
ModNameRole
};
}
class CModListModel : public QAbstractItemModel, public CModList
@ -55,28 +55,30 @@ class CModListModel : public QAbstractItemModel, public CModList
QVariant getValue(const CModEntry & mod, int field) const;
QVariant getText(const CModEntry & mod, int field) const;
QVariant getIcon(const CModEntry & mod, int field) const;
public:
explicit CModListModel(QObject *parent = 0);
explicit CModListModel(QObject * parent = 0);
/// CModListContainer overrides
void resetRepositories() override;
void addRepository(QVariantMap data) override;
void modChanged(QString modID) override;
QVariant data(const QModelIndex &index, int role) const override;
QVariant data(const QModelIndex & index, int role) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
int rowCount(const QModelIndex &parent) const override;
int columnCount(const QModelIndex &parent) const override;
int rowCount(const QModelIndex & parent) const override;
int columnCount(const QModelIndex & parent) const override;
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex &child) const override;
QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex & child) const override;
Qt::ItemFlags flags(const QModelIndex & index) const override;
Qt::ItemFlags flags(const QModelIndex &index) const override;
signals:
public slots:
};
class CModFilterModel : public QSortFilterProxyModel
@ -87,9 +89,10 @@ class CModFilterModel : public QSortFilterProxyModel
bool filterMatchesThis(const QModelIndex & source) const;
bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override;
bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const override;
public:
void setTypeFilter(int filteredType, int filterMask);
CModFilterModel(CModListModel * model, QObject *parent = 0);
CModFilterModel(CModListModel * model, QObject * parent = 0);
};

View File

@ -50,24 +50,22 @@ void CModListView::setupModsView()
ui->allModsView->setColumnWidth(ModFields::VERSION, 60);
ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_ENABLED, QHeaderView::Fixed);
ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_UPDATE, QHeaderView::Fixed);
ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_UPDATE, QHeaderView::Fixed);
ui->allModsView->setUniformRowHeights(true);
connect( ui->allModsView->selectionModel(), SIGNAL( currentRowChanged( const QModelIndex &, const QModelIndex & )),
this, SLOT( modSelected( const QModelIndex &, const QModelIndex & )));
connect(ui->allModsView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&,const QModelIndex&)),
this, SLOT(modSelected(const QModelIndex&,const QModelIndex&)));
connect( filterModel, SIGNAL( modelReset()),
this, SLOT( modelReset()));
connect(filterModel, SIGNAL(modelReset()),
this, SLOT(modelReset()));
connect( modModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(dataChanged(QModelIndex,QModelIndex)));
connect(modModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(dataChanged(QModelIndex,QModelIndex)));
}
CModListView::CModListView(QWidget *parent) :
QWidget(parent),
settingsListener(settings.listen["launcher"]["repositoryURL"]),
ui(new Ui::CModListView)
CModListView::CModListView(QWidget * parent)
: QWidget(parent), settingsListener(settings.listen["launcher"]["repositoryURL"]), ui(new Ui::CModListView)
{
settingsListener([&](const JsonNode &){ repositoriesChanged = true; });
ui->setupUi(this);
@ -79,7 +77,7 @@ CModListView::CModListView(QWidget *parent) :
ui->progressWidget->setVisible(false);
dlManager = nullptr;
disableModInfo();
if (settings["launcher"]["autoCheckRepositories"].Bool())
if(settings["launcher"]["autoCheckRepositories"].Bool())
{
loadRepositories();
}
@ -92,7 +90,7 @@ CModListView::CModListView(QWidget *parent) :
void CModListView::loadRepositories()
{
manager->resetRepositories();
for (auto entry : settings["launcher"]["repositoryURL"].Vector())
for(auto entry : settings["launcher"]["repositoryURL"].Vector())
{
QString str = QString::fromUtf8(entry.String().c_str());
@ -112,10 +110,10 @@ CModListView::~CModListView()
void CModListView::showEvent(QShowEvent * event)
{
QWidget::showEvent(event);
if (repositoriesChanged)
if(repositoriesChanged)
{
repositoriesChanged = false;
if (settings["launcher"]["autoCheckRepositories"].Bool())
if(settings["launcher"]["autoCheckRepositories"].Bool())
{
loadRepositories();
}
@ -141,10 +139,10 @@ void CModListView::hideModInfo()
static QString replaceIfNotEmpty(QVariant value, QString pattern)
{
if (value.canConvert<QStringList>())
if(value.canConvert<QStringList>())
return pattern.arg(value.toStringList().join(", "));
if (value.canConvert<QString>())
if(value.canConvert<QString>())
return pattern.arg(value.toString());
// all valid types of data should have been filtered by code above
@ -155,12 +153,12 @@ static QString replaceIfNotEmpty(QVariant value, QString pattern)
static QString replaceIfNotEmpty(QStringList value, QString pattern)
{
if (!value.empty())
if(!value.empty())
return pattern.arg(value.join(", "));
return "";
}
QString CModListView::genChangelogText(CModEntry &mod)
QString CModListView::genChangelogText(CModEntry & mod)
{
QString headerTemplate = "<p><span style=\" font-weight:600;\">%1: </span></p>";
QString entryBegin = "<p align=\"justify\"><ul>";
@ -178,22 +176,22 @@ QString CModListView::genChangelogText(CModEntry &mod)
return !CModEntry::compareVersions(lesser, greater);
});
for (auto & version : versions)
for(auto & version : versions)
{
result += headerTemplate.arg(version);
result += entryBegin;
for (auto & line : changelog.value(version).toStringList())
for(auto & line : changelog.value(version).toStringList())
result += entryLine.arg(line);
result += entryEnd;
}
return result;
}
QString CModListView::genModInfoText(CModEntry &mod)
QString CModListView::genModInfoText(CModEntry & mod)
{
QString prefix = "<p><span style=\" font-weight:600;\">%1: </span>"; // shared prefix
QString lineTemplate = prefix + "%2</p>";
QString urlTemplate = prefix + "<a href=\"%2\">%3</a></p>";
QString urlTemplate = prefix + "<a href=\"%2\">%3</a></p>";
QString textTemplate = prefix + "</p><p align=\"justify\">%2</p>";
QString listTemplate = "<p align=\"justify\">%1: %2</p>";
QString noteTemplate = "<p align=\"justify\">%1</p>";
@ -204,14 +202,14 @@ QString CModListView::genModInfoText(CModEntry &mod)
result += replaceIfNotEmpty(mod.getValue("installedVersion"), lineTemplate.arg(tr("Installed version")));
result += replaceIfNotEmpty(mod.getValue("latestVersion"), lineTemplate.arg(tr("Latest version")));
if (mod.getValue("size").isValid())
if(mod.getValue("size").isValid())
result += replaceIfNotEmpty(CModEntry::sizeToString(mod.getValue("size").toDouble()), lineTemplate.arg(tr("Download size")));
result += replaceIfNotEmpty(mod.getValue("author"), lineTemplate.arg(tr("Authors")));
if (mod.getValue("licenseURL").isValid())
if(mod.getValue("licenseURL").isValid())
result += urlTemplate.arg(tr("License")).arg(mod.getValue("licenseURL").toString()).arg(mod.getValue("licenseName").toString());
if (mod.getValue("contact").isValid())
if(mod.getValue("contact").isValid())
result += urlTemplate.arg(tr("Home")).arg(mod.getValue("contact").toString()).arg(mod.getValue("contact").toString());
result += replaceIfNotEmpty(mod.getValue("depends"), lineTemplate.arg(tr("Required mods")));
@ -220,7 +218,7 @@ QString CModListView::genModInfoText(CModEntry &mod)
result += "<p></p>"; // to get some empty space
QString unknownDeps = tr("This mod can not be installed or enabled because following dependencies are not present");
QString unknownDeps = tr("This mod can not be installed or enabled because following dependencies are not present");
QString blockingMods = tr("This mod can not be enabled because following mods are incompatible with this mod");
QString hasActiveDependentMods = tr("This mod can not be disabled because it is required to run following mods");
QString hasDependentMods = tr("This mod can not be uninstalled or updated because it is required to run following mods");
@ -230,15 +228,15 @@ QString CModListView::genModInfoText(CModEntry &mod)
notes += replaceIfNotEmpty(findInvalidDependencies(mod.getName()), listTemplate.arg(unknownDeps));
notes += replaceIfNotEmpty(findBlockingMods(mod.getName()), listTemplate.arg(blockingMods));
if (mod.isEnabled())
if(mod.isEnabled())
notes += replaceIfNotEmpty(findDependentMods(mod.getName(), true), listTemplate.arg(hasActiveDependentMods));
if (mod.isInstalled())
if(mod.isInstalled())
notes += replaceIfNotEmpty(findDependentMods(mod.getName(), false), listTemplate.arg(hasDependentMods));
if (mod.getName().contains('.'))
if(mod.getName().contains('.'))
notes += noteTemplate.arg(thisIsSubmod);
if (notes.size())
if(notes.size())
result += textTemplate.arg(tr("Notes")).arg(notes);
return result;
@ -270,7 +268,7 @@ void CModListView::dataChanged(const QModelIndex & topleft, const QModelIndex &
void CModListView::selectMod(const QModelIndex & index)
{
if (!index.isValid())
if(!index.isValid())
{
disableModInfo();
}
@ -308,7 +306,7 @@ void CModListView::selectMod(const QModelIndex & index)
void CModListView::keyPressEvent(QKeyEvent * event)
{
if (event->key() == Qt::Key_Escape && ui->modInfoWidget->isVisible() )
if(event->key() == Qt::Key_Escape && ui->modInfoWidget->isVisible())
{
hideModInfo();
}
@ -318,26 +316,26 @@ void CModListView::keyPressEvent(QKeyEvent * event)
}
}
void CModListView::modSelected(const QModelIndex & current, const QModelIndex & )
void CModListView::modSelected(const QModelIndex & current, const QModelIndex &)
{
selectMod(current);
}
void CModListView::on_hideModInfoButton_clicked()
{
if (ui->modInfoWidget->isVisible())
if(ui->modInfoWidget->isVisible())
hideModInfo();
else
showModInfo();
}
void CModListView::on_allModsView_activated(const QModelIndex &index)
void CModListView::on_allModsView_activated(const QModelIndex & index)
{
showModInfo();
selectMod(index);
}
void CModListView::on_lineEdit_textChanged(const QString &arg1)
void CModListView::on_lineEdit_textChanged(const QString & arg1)
{
QRegExp regExp(arg1, Qt::CaseInsensitive, QRegExp::Wildcard);
filterModel->setFilterRegExp(regExp);
@ -345,23 +343,35 @@ void CModListView::on_lineEdit_textChanged(const QString &arg1)
void CModListView::on_comboBox_currentIndexChanged(int index)
{
switch (index)
switch(index)
{
break; case 0: filterModel->setTypeFilter(ModStatus::MASK_NONE, ModStatus::MASK_NONE);
break; case 1: filterModel->setTypeFilter(ModStatus::MASK_NONE, ModStatus::INSTALLED);
break; case 2: filterModel->setTypeFilter(ModStatus::INSTALLED, ModStatus::INSTALLED);
break; case 3: filterModel->setTypeFilter(ModStatus::UPDATEABLE, ModStatus::UPDATEABLE);
break; case 4: filterModel->setTypeFilter(ModStatus::ENABLED | ModStatus::INSTALLED, ModStatus::ENABLED | ModStatus::INSTALLED);
break; case 5: filterModel->setTypeFilter(ModStatus::INSTALLED, ModStatus::ENABLED | ModStatus::INSTALLED);
case 0:
filterModel->setTypeFilter(ModStatus::MASK_NONE, ModStatus::MASK_NONE);
break;
case 1:
filterModel->setTypeFilter(ModStatus::MASK_NONE, ModStatus::INSTALLED);
break;
case 2:
filterModel->setTypeFilter(ModStatus::INSTALLED, ModStatus::INSTALLED);
break;
case 3:
filterModel->setTypeFilter(ModStatus::UPDATEABLE, ModStatus::UPDATEABLE);
break;
case 4:
filterModel->setTypeFilter(ModStatus::ENABLED | ModStatus::INSTALLED, ModStatus::ENABLED | ModStatus::INSTALLED);
break;
case 5:
filterModel->setTypeFilter(ModStatus::INSTALLED, ModStatus::ENABLED | ModStatus::INSTALLED);
break;
}
}
QStringList CModListView::findInvalidDependencies(QString mod)
{
QStringList ret;
for (QString requrement : modModel->getRequirements(mod))
for(QString requrement : modModel->getRequirements(mod))
{
if (!modModel->hasMod(requrement))
if(!modModel->hasMod(requrement))
ret += requrement;
}
return ret;
@ -372,16 +382,18 @@ QStringList CModListView::findBlockingMods(QString mod)
QStringList ret;
auto required = modModel->getRequirements(mod);
for (QString name : modModel->getModList())
for(QString name : modModel->getModList())
{
auto mod = modModel->getMod(name);
if (mod.isEnabled())
if(mod.isEnabled())
{
// one of enabled mods have requirement (or this mod) marked as conflict
for (auto conflict : mod.getValue("conflicts").toStringList())
if (required.contains(conflict))
for(auto conflict : mod.getValue("conflicts").toStringList())
{
if(required.contains(conflict))
ret.push_back(name);
}
}
}
@ -391,16 +403,18 @@ QStringList CModListView::findBlockingMods(QString mod)
QStringList CModListView::findDependentMods(QString mod, bool excludeDisabled)
{
QStringList ret;
for (QString modName : modModel->getModList())
for(QString modName : modModel->getModList())
{
auto current = modModel->getMod(modName);
if (!current.isInstalled())
if(!current.isInstalled())
continue;
if (current.getValue("depends").toStringList().contains(mod) &&
!(current.isDisabled() && excludeDisabled))
ret += modName;
if(current.getValue("depends").toStringList().contains(mod))
{
if(!(current.isDisabled() && excludeDisabled))
ret += modName;
}
}
return ret;
}
@ -412,9 +426,11 @@ void CModListView::on_enableButton_clicked()
assert(findBlockingMods(modName).empty());
assert(findInvalidDependencies(modName).empty());
for (auto & name : modModel->getRequirements(modName))
if (modModel->getMod(name).isDisabled())
for(auto & name : modModel->getRequirements(modName))
{
if(modModel->getMod(name).isDisabled())
manager->enableMod(name);
}
checkManagerErrors();
}
@ -422,9 +438,8 @@ void CModListView::on_disableButton_clicked()
{
QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
if (modModel->hasMod(modName) &&
modModel->getMod(modName).isEnabled())
manager->disableMod(modName);
if(modModel->hasMod(modName) && modModel->getMod(modName).isEnabled())
manager->disableMod(modName);
checkManagerErrors();
}
@ -435,11 +450,11 @@ void CModListView::on_updateButton_clicked()
assert(findInvalidDependencies(modName).empty());
for (auto & name : modModel->getRequirements(modName))
for(auto & name : modModel->getRequirements(modName))
{
auto mod = modModel->getMod(name);
// update required mod, install missing (can be new dependency)
if (mod.isUpdateable() || !mod.isInstalled())
if(mod.isUpdateable() || !mod.isInstalled())
downloadFile(name + ".zip", mod.getValue("download").toString(), "mods");
}
}
@ -449,10 +464,9 @@ void CModListView::on_uninstallButton_clicked()
QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
// NOTE: perhaps add "manually installed" flag and uninstall those dependencies that don't have it?
if (modModel->hasMod(modName) &&
modModel->getMod(modName).isInstalled())
if(modModel->hasMod(modName) && modModel->getMod(modName).isInstalled())
{
if (modModel->getMod(modName).isEnabled())
if(modModel->getMod(modName).isEnabled())
manager->disableMod(modName);
manager->uninstallMod(modName);
}
@ -465,25 +479,25 @@ void CModListView::on_installButton_clicked()
assert(findInvalidDependencies(modName).empty());
for (auto & name : modModel->getRequirements(modName))
for(auto & name : modModel->getRequirements(modName))
{
auto mod = modModel->getMod(name);
if (!mod.isInstalled())
if(!mod.isInstalled())
downloadFile(name + ".zip", mod.getValue("download").toString(), "mods");
}
}
void CModListView::downloadFile(QString file, QString url, QString description)
{
if (!dlManager)
if(!dlManager)
{
dlManager = new CDownloadManager();
ui->progressWidget->setVisible(true);
connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(downloadProgress(qint64,qint64)));
this, SLOT(downloadProgress(qint64,qint64)));
connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
QString progressBarFormat = "Downloading %s%. %p% (%v KB out of %m KB) finished";
@ -498,8 +512,8 @@ void CModListView::downloadFile(QString file, QString url, QString description)
void CModListView::downloadProgress(qint64 current, qint64 max)
{
// display progress, in kilobytes
ui->progressBar->setValue(current/1024);
ui->progressBar->setMaximum(max/1024);
ui->progressBar->setValue(current / 1024);
ui->progressBar->setMaximum(max / 1024);
}
void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
@ -511,18 +525,18 @@ void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFi
// if all files were d/loaded there should be no errors. And on failure there must be an error
assert(failedFiles.empty() == errors.empty());
if (savedFiles.empty())
if(savedFiles.empty())
{
// no successfully downloaded mods
QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok );
QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok);
}
else if (!failedFiles.empty())
else if(!failedFiles.empty())
{
// some mods were not downloaded
int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
if (result == QMessageBox::Yes)
if(result == QMessageBox::Yes)
installFiles(savedFiles);
}
else
@ -532,7 +546,7 @@ void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFi
}
// remove progress bar after some delay so user can see that download was complete and not interrupted.
QTimer::singleShot(1000, this, SLOT(hideProgressBar()));
QTimer::singleShot(1000, this, SLOT(hideProgressBar()));
dlManager->deleteLater();
dlManager = nullptr;
@ -540,7 +554,7 @@ void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFi
void CModListView::hideProgressBar()
{
if (dlManager == nullptr) // it was not recreated meanwhile
if(dlManager == nullptr) // it was not recreated meanwhile
{
ui->progressWidget->setVisible(false);
ui->progressBar->setMaximum(0);
@ -554,19 +568,19 @@ void CModListView::installFiles(QStringList files)
QStringList images;
// TODO: some better way to separate zip's with mods and downloaded repository files
for (QString filename : files)
for(QString filename : files)
{
if (filename.endsWith(".zip"))
if(filename.endsWith(".zip"))
mods.push_back(filename);
if (filename.endsWith(".json"))
if(filename.endsWith(".json"))
manager->loadRepository(filename);
if (filename.endsWith(".png"))
if(filename.endsWith(".png"))
images.push_back(filename);
}
if (!mods.empty())
if(!mods.empty())
installMods(mods);
if (!images.empty())
if(!images.empty())
loadScreenshots();
}
@ -574,7 +588,7 @@ void CModListView::installMods(QStringList archives)
{
QStringList modNames;
for (QString archive : archives)
for(QString archive : archives)
{
// get basename out of full file name
// remove path remove extension
@ -586,31 +600,31 @@ void CModListView::installMods(QStringList archives)
QStringList modsToEnable;
// disable mod(s), to properly recalculate dependencies, if changed
for (QString mod : boost::adaptors::reverse(modNames))
for(QString mod : boost::adaptors::reverse(modNames))
{
CModEntry entry = modModel->getMod(mod);
if (entry.isInstalled())
if(entry.isInstalled())
{
// enable mod if installed and enabled
if (entry.isEnabled())
if(entry.isEnabled())
modsToEnable.push_back(mod);
}
else
{
// enable mod if m
if (settings["launcher"]["enableInstalledMods"].Bool())
if(settings["launcher"]["enableInstalledMods"].Bool())
modsToEnable.push_back(mod);
}
}
// uninstall old version of mod, if installed
for (QString mod : boost::adaptors::reverse(modNames))
for(QString mod : boost::adaptors::reverse(modNames))
{
if (modModel->getMod(mod).isInstalled())
if(modModel->getMod(mod).isInstalled())
manager->uninstallMod(mod);
}
for (int i=0; i<modNames.size(); i++)
for(int i = 0; i < modNames.size(); i++)
manager->installMod(modNames[i], archives[i]);
std::function<void(QString)> enableMod;
@ -618,22 +632,22 @@ void CModListView::installMods(QStringList archives)
enableMod = [&](QString modName)
{
auto mod = modModel->getMod(modName);
if (mod.isInstalled() && !mod.getValue("keepDisabled").toBool())
if(mod.isInstalled() && !mod.getValue("keepDisabled").toBool())
{
if (manager->enableMod(modName))
if(manager->enableMod(modName))
{
for (QString child : modModel->getChildren(modName))
for(QString child : modModel->getChildren(modName))
enableMod(child);
}
}
};
for (QString mod : modsToEnable)
for(QString mod : modsToEnable)
{
enableMod(mod);
}
for (QString archive : archives)
for(QString archive : archives)
QFile::remove(archive);
checkManagerErrors();
@ -653,18 +667,18 @@ void CModListView::on_pushButton_clicked()
void CModListView::modelReset()
{
if (ui->modInfoWidget->isVisible())
selectMod(filterModel->rowCount() > 0 ? filterModel->index(0,0) : QModelIndex());
if(ui->modInfoWidget->isVisible())
selectMod(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
}
void CModListView::checkManagerErrors()
{
QString errors = manager->getErrors().join('\n');
if (errors.size() != 0)
if(errors.size() != 0)
{
QString title = "Operation failed";
QString description = "Encountered errors:\n" + errors;
QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok );
QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
}
}
@ -675,13 +689,13 @@ void CModListView::on_tabWidget_currentChanged(int index)
void CModListView::loadScreenshots()
{
if (ui->tabWidget->currentIndex() == 2 && ui->modInfoWidget->isVisible())
if(ui->tabWidget->currentIndex() == 2 && ui->modInfoWidget->isVisible())
{
ui->screenshotsList->clear();
QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
assert(modModel->hasMod(modName)); //should be filtered out by check above
for (QString & url : modModel->getMod(modName).getValue("screenshots").toStringList())
for(QString & url : modModel->getMod(modName).getValue("screenshots").toStringList())
{
// URL must be encoded to something else to get rid of symbols illegal in file names
auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
@ -689,7 +703,7 @@ void CModListView::loadScreenshots()
QString fullPath = CLauncherDirs::get().downloadsPath() + '/' + hashedStr + ".png";
QPixmap pixmap(fullPath);
if (pixmap.isNull())
if(pixmap.isNull())
{
// image file not exists or corrupted - try to redownload
downloadFile(hashedStr + ".png", url, "screenshots");
@ -705,9 +719,9 @@ void CModListView::loadScreenshots()
}
}
void CModListView::on_screenshotsList_clicked(const QModelIndex &index)
void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
{
if (index.isValid())
if(index.isValid())
{
QIcon icon = ui->screenshotsList->item(index.row())->icon();
auto pixmap = icon.pixmap(icon.availableSizes()[0]);

View File

@ -12,8 +12,9 @@
#include "../StdInc.h"
#include "../../lib/CConfigHandler.h"
namespace Ui {
class CModListView;
namespace Ui
{
class CModListView;
}
class CModManager;
@ -61,8 +62,9 @@ class CModListView : public QWidget
QString genChangelogText(CModEntry & mod);
QString genModInfoText(CModEntry & mod);
public:
explicit CModListView(QWidget *parent = 0);
explicit CModListView(QWidget * parent = 0);
~CModListView();
void showModInfo();
@ -79,12 +81,12 @@ private slots:
void modSelected(const QModelIndex & current, const QModelIndex & previous);
void downloadProgress(qint64 current, qint64 max);
void downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors);
void modelReset ();
void modelReset();
void hideProgressBar();
void on_hideModInfoButton_clicked();
void on_lineEdit_textChanged(const QString &arg1);
void on_lineEdit_textChanged(const QString & arg1);
void on_comboBox_currentIndexChanged(int index);
@ -102,14 +104,14 @@ private slots:
void on_refreshButton_clicked();
void on_allModsView_activated(const QModelIndex &index);
void on_allModsView_activated(const QModelIndex & index);
void on_tabWidget_currentChanged(int index);
void on_screenshotsList_clicked(const QModelIndex &index);
void on_screenshotsList_clicked(const QModelIndex & index);
void on_showInfoButton_clicked();
private:
Ui::CModListView *ui;
Ui::CModListView * ui;
};

View File

@ -24,23 +24,25 @@ static QString detectModArchive(QString path, QString modName)
QString modDirName;
for (auto file : files)
for(auto file : files)
{
QString filename = QString::fromUtf8(file.c_str());
if (filename.toLower().startsWith(modName))
if(filename.toLower().startsWith(modName))
{
// archive must contain mod.json file
if (filename.toLower() == modName + "/mod.json")
if(filename.toLower() == modName + "/mod.json")
modDirName = filename.section('/', 0, 0);
}
else // all files must be in <modname> directory
{
return "";
}
}
return modDirName;
}
CModManager::CModManager(CModList * modList):
modList(modList)
CModManager::CModManager(CModList * modList)
: modList(modList)
{
loadMods();
loadModSettings();
@ -73,10 +75,10 @@ void CModManager::loadMods()
handler.loadMods();
auto installedMods = handler.getAllMods();
for (auto modname : installedMods)
for(auto modname : installedMods)
{
ResourceID resID(CModInfo::getModFile(modname));
if (CResourceHandler::get()->existsResource(resID))
if(CResourceHandler::get()->existsResource(resID))
{
boost::filesystem::path name = *CResourceHandler::get()->getResourceName(resID);
auto mod = JsonUtils::JsonFromFile(pathToQString(name));
@ -123,13 +125,13 @@ bool CModManager::canInstallMod(QString modname)
{
auto mod = modList->getMod(modname);
if (mod.getName().contains('.'))
if(mod.getName().contains('.'))
return addError(modname, "Can not install submod");
if (mod.isInstalled())
if(mod.isInstalled())
return addError(modname, "Mod is already installed");
if (!mod.isAvailable())
if(!mod.isAvailable())
return addError(modname, "Mod is not available");
return true;
}
@ -138,13 +140,13 @@ bool CModManager::canUninstallMod(QString modname)
{
auto mod = modList->getMod(modname);
if (mod.getName().contains('.'))
if(mod.getName().contains('.'))
return addError(modname, "Can not uninstall submod");
if (!mod.isInstalled())
if(!mod.isInstalled())
return addError(modname, "Mod is not installed");
if (mod.isEnabled())
if(mod.isEnabled())
return addError(modname, "Mod must be disabled first");
return true;
}
@ -153,33 +155,33 @@ bool CModManager::canEnableMod(QString modname)
{
auto mod = modList->getMod(modname);
if (mod.isEnabled())
if(mod.isEnabled())
return addError(modname, "Mod is already enabled");
if (!mod.isInstalled())
if(!mod.isInstalled())
return addError(modname, "Mod must be installed first");
for (auto modEntry : mod.getValue("depends").toStringList())
for(auto modEntry : mod.getValue("depends").toStringList())
{
if (!modList->hasMod(modEntry)) // required mod is not available
if(!modList->hasMod(modEntry)) // required mod is not available
return addError(modname, QString("Required mod %1 is missing").arg(modEntry));
if (!modList->getMod(modEntry).isEnabled())
if(!modList->getMod(modEntry).isEnabled())
return addError(modname, QString("Required mod %1 is not enabled").arg(modEntry));
}
for (QString modEntry : modList->getModList())
for(QString modEntry : modList->getModList())
{
auto mod = modList->getMod(modEntry);
// "reverse conflict" - enabled mod has this one as conflict
if (mod.isEnabled() && mod.getValue("conflicts").toStringList().contains(modname))
if(mod.isEnabled() && mod.getValue("conflicts").toStringList().contains(modname))
return addError(modname, QString("This mod conflicts with %1").arg(modEntry));
}
for (auto modEntry : mod.getValue("conflicts").toStringList())
for(auto modEntry : mod.getValue("conflicts").toStringList())
{
if (modList->hasMod(modEntry) &&
modList->getMod(modEntry).isEnabled()) // conflicting mod installed and enabled
// check if conflicting mod installed and enabled
if(modList->hasMod(modEntry) && modList->getMod(modEntry).isEnabled())
return addError(modname, QString("This mod conflicts with %1").arg(modEntry));
}
return true;
@ -189,18 +191,17 @@ bool CModManager::canDisableMod(QString modname)
{
auto mod = modList->getMod(modname);
if (mod.isDisabled())
if(mod.isDisabled())
return addError(modname, "Mod is already disabled");
if (!mod.isInstalled())
if(!mod.isInstalled())
return addError(modname, "Mod must be installed first");
for (QString modEntry : modList->getModList())
for(QString modEntry : modList->getModList())
{
auto current = modList->getMod(modEntry);
if (current.getValue("depends").toStringList().contains(modname) &&
current.isEnabled())
if(current.getValue("depends").toStringList().contains(modname) && current.isEnabled())
return addError(modname, QString("This mod is needed to run %1").arg(modEntry));
}
return true;
@ -208,7 +209,7 @@ bool CModManager::canDisableMod(QString modname)
static QVariant writeValue(QString path, QVariantMap input, QVariant value)
{
if (path.size() > 1)
if(path.size() > 1)
{
QString entryName = path.section('/', 0, 1);
@ -242,17 +243,17 @@ bool CModManager::doInstallMod(QString modname, QString archivePath)
{
QString destDir = CLauncherDirs::get().modsPath() + "/";
if (!QFile(archivePath).exists())
if(!QFile(archivePath).exists())
return addError(modname, "Mod archive is missing");
if (localMods.contains(modname))
if(localMods.contains(modname))
return addError(modname, "Mod with such name is already installed");
QString modDirName = detectModArchive(archivePath, modname);
if (!modDirName.size())
if(!modDirName.size())
return addError(modname, "Mod archive is invalid or corrupted");
if (!ZipArchive::extract(qstringToPath(archivePath), qstringToPath(destDir)))
if(!ZipArchive::extract(qstringToPath(archivePath), qstringToPath(destDir)))
{
removeModDir(destDir + modDirName);
return addError(modname, "Failed to extract mod data");
@ -273,13 +274,13 @@ bool CModManager::doUninstallMod(QString modname)
// Get location of the mod, in case-insensitive way
QString modDir = pathToQString(*CResourceHandler::get()->getResourceName(resID));
if (!QDir(modDir).exists())
if(!QDir(modDir).exists())
return addError(modname, "Data with this mod was not found");
if (!localMods.contains(modname))
if(!localMods.contains(modname))
return addError(modname, "Data with this mod was not found");
if (!removeModDir(modDir))
if(!removeModDir(modDir))
return addError(modname, "Failed to delete mod data");
localMods.remove(modname);

View File

@ -28,6 +28,7 @@ class CModManager
QStringList recentErrors;
bool addError(QString modname, QString message);
bool removeModDir(QString mod);
public:
CModManager(CModList * modList);

View File

@ -14,9 +14,8 @@
#include "imageviewer_moc.h"
#include "ui_imageviewer_moc.h"
ImageViewer::ImageViewer(QWidget *parent) :
QDialog(parent),
ui(new Ui::ImageViewer)
ImageViewer::ImageViewer(QWidget * parent)
: QDialog(parent), ui(new Ui::ImageViewer)
{
ui->setupUi(this);
}
@ -32,7 +31,7 @@ QSize ImageViewer::calculateWindowSize()
return desktop.availableGeometry(desktop.primaryScreen()).size() * 0.8;
}
void ImageViewer::showPixmap(QPixmap & pixmap, QWidget *parent)
void ImageViewer::showPixmap(QPixmap & pixmap, QWidget * parent)
{
assert(!pixmap.isNull());

View File

@ -12,29 +12,30 @@
#include <QDialog>
namespace Ui {
class ImageViewer;
namespace Ui
{
class ImageViewer;
}
class ImageViewer : public QDialog
{
Q_OBJECT
public:
explicit ImageViewer(QWidget *parent = 0);
explicit ImageViewer(QWidget * parent = 0);
~ImageViewer();
void setPixmap(QPixmap & pixmap);
static void showPixmap(QPixmap & pixmap, QWidget *parent = 0);
static void showPixmap(QPixmap & pixmap, QWidget * parent = 0);
protected:
void mousePressEvent(QMouseEvent * event) override;
void keyPressEvent(QKeyEvent * event) override;
QSize calculateWindowSize();
private:
Ui::ImageViewer *ui;
Ui::ImageViewer * ui;
};
#endif // IMAGEVIEWER_H

View File

@ -20,13 +20,13 @@
/// Note that it is possible to specify enconding manually in settings.json
static const std::string knownEncodingsList[] = //TODO: remove hardcode
{
// European Windows-125X encodings
"CP1250", // West European, covers mostly Slavic languages that use latin script
"CP1251", // Covers languages that use cyrillic scrypt
"CP1252", // Latin/East European, covers most of latin languages
// Chinese encodings
"GBK", // extension of GB2312, also known as CP936
"GB2312" // basic set for Simplified Chinese. Separate from GBK to allow proper detection of H3 fonts
// European Windows-125X encodings
"CP1250", // West European, covers mostly Slavic languages that use latin script
"CP1251", // Covers languages that use cyrillic scrypt
"CP1252", // Latin/East European, covers most of latin languages
// Chinese encodings
"GBK", // extension of GB2312, also known as CP936
"GB2312" // basic set for Simplified Chinese. Separate from GBK to allow proper detection of H3 fonts
};
void CSettingsView::setDisplayList()
@ -83,7 +83,7 @@ void CSettingsView::loadSettings()
JsonNode urls = settings["launcher"]["repositoryURL"];
ui->plainTextEditRepos->clear();
for (auto entry : urls.Vector())
for(auto entry : urls.Vector())
ui->plainTextEditRepos->appendPlainText(QString::fromUtf8(entry.String().c_str()));
ui->lineEditUserDataDir->setText(pathToQString(VCMIDirs::get().userDataPath()));
@ -92,14 +92,13 @@ void CSettingsView::loadSettings()
std::string encoding = settings["general"]["encoding"].String();
size_t encodingIndex = boost::range::find(knownEncodingsList, encoding) - knownEncodingsList;
if (encodingIndex < ui->comboBoxEncoding->count())
if(encodingIndex < ui->comboBoxEncoding->count())
ui->comboBoxEncoding->setCurrentIndex(encodingIndex);
ui->comboBoxAutoSave->setCurrentIndex(settings["general"]["saveFrequency"].Integer() > 0 ? 1 : 0);
}
CSettingsView::CSettingsView(QWidget *parent) :
QWidget(parent),
ui(new Ui::CSettingsView)
CSettingsView::CSettingsView(QWidget * parent)
: QWidget(parent), ui(new Ui::CSettingsView)
{
ui->setupUi(this);
@ -112,7 +111,7 @@ CSettingsView::~CSettingsView()
}
void CSettingsView::on_comboBoxResolution_currentIndexChanged(const QString &arg1)
void CSettingsView::on_comboBoxResolution_currentIndexChanged(const QString & arg1)
{
QStringList list = arg1.split("x");
@ -145,7 +144,7 @@ void CSettingsView::on_comboBoxDisplayIndex_currentIndexChanged(int index)
node["displayIndex"].Float() = index;
}
void CSettingsView::on_comboBoxPlayerAI_currentIndexChanged(const QString &arg1)
void CSettingsView::on_comboBoxPlayerAI_currentIndexChanged(const QString & arg1)
{
Settings node = settings.write["server"]["playerAI"];
node->String() = arg1.toUtf8().data();
@ -157,7 +156,7 @@ void CSettingsView::on_comboBoxFriendlyAI_currentIndexChanged(const QString & ar
node->String() = arg1.toUtf8().data();
}
void CSettingsView::on_comboBoxNeutralAI_currentIndexChanged(const QString &arg1)
void CSettingsView::on_comboBoxNeutralAI_currentIndexChanged(const QString & arg1)
{
Settings node = settings.write["server"]["neutralAI"];
node->String() = arg1.toUtf8().data();
@ -182,9 +181,9 @@ void CSettingsView::on_plainTextEditRepos_textChanged()
QStringList list = ui->plainTextEditRepos->toPlainText().split('\n');
node->Vector().clear();
for (QString line : list)
for(QString line : list)
{
if (line.trimmed().size() > 0)
if(line.trimmed().size() > 0)
{
JsonNode entry;
entry.String() = line.trimmed().toUtf8().data();

View File

@ -10,15 +10,17 @@
#pragma once
#include "../StdInc.h"
namespace Ui {
class CSettingsView;
namespace Ui
{
class CSettingsView;
}
class CSettingsView : public QWidget
{
Q_OBJECT
public:
explicit CSettingsView(QWidget *parent = 0);
explicit CSettingsView(QWidget * parent = 0);
~CSettingsView();
void loadSettings();
@ -27,17 +29,17 @@ public:
private slots:
void on_checkBoxFullScreen_stateChanged(int state);
void on_comboBoxResolution_currentIndexChanged(const QString &arg1);
void on_comboBoxResolution_currentIndexChanged(const QString & arg1);
void on_comboBoxFullScreen_currentIndexChanged(int index);
void on_comboBoxPlayerAI_currentIndexChanged(const QString &arg1);
void on_comboBoxPlayerAI_currentIndexChanged(const QString & arg1);
void on_comboBoxFriendlyAI_currentIndexChanged(const QString &arg1);
void on_comboBoxFriendlyAI_currentIndexChanged(const QString & arg1);
void on_comboBoxNeutralAI_currentIndexChanged(const QString &arg1);
void on_comboBoxNeutralAI_currentIndexChanged(const QString & arg1);
void on_comboBoxEnemyAI_currentIndexChanged(const QString &arg1);
void on_comboBoxEnemyAI_currentIndexChanged(const QString & arg1);
void on_spinBoxNetworkPort_valueChanged(int arg1);
@ -62,5 +64,5 @@ private slots:
void on_comboBoxAutoSave_currentIndexChanged(int index);
private:
Ui::CSettingsView *ui;
Ui::CSettingsView * ui;
};