1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
#include "levelpacks.h"
#include "levelpack.h"
#include <QCoreApplication>
#include <QDir>
#include <QJsonDocument>
#include <QDebug>
LevelPacks::LevelPacks(Engine *engine, QObject *parent) :
QAbstractListModel(parent),
m_engine(engine)
{
QDir dir(QCoreApplication::applicationDirPath() + "/data/levelpacks/");
qDebug() << "Loading level packs from:" << dir.path();
QStringList levelPacks = dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name);
foreach (const QString &levelPackDir, levelPacks) {
QFileInfo fi(dir.absolutePath() + "/" + levelPackDir + "/levelpack.json");
if (!fi.exists()) {
qDebug() << "Level pack directory" << levelPackDir << "does not contain a levelpack.json file.";
continue;
}
QFile jsonFile(fi.absoluteFilePath());
if (!jsonFile.open(QFile::ReadOnly)) {
qDebug() << "Cannot open level pack file for reading:" << fi.absoluteFilePath();
continue;
}
QJsonParseError error;
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonFile.readAll(), &error);
if (error.error != QJsonParseError::NoError) {
qDebug() << "Cannot parse level pack file:" << error.errorString();
continue;
}
QVariantMap jsonMap = jsonDoc.toVariant().toMap();
QString name = jsonMap.value("name").toString();
QString levelSelectBackground = "image://packdata/" + levelPackDir + "/" + jsonMap.value("levelSelectBackground").toString();
LevelPack *pack = new LevelPack(m_engine, levelPackDir, name, levelSelectBackground, this);
qDebug() << "Loaded level pack:" << pack->id() << pack->name() << pack->levelSelectBackground();
m_list.append(pack);
}
}
QVariant LevelPacks::data(const QModelIndex &index, int role) const
{
switch(role) {
case RoleId:
return m_list.at(index.row())->id();
case RoleName:
return m_list.at(index.row())->name();
case RoleLevelSelectBackground:
return m_list.at(index.row())->levelSelectBackground();
}
return QVariant();
}
int LevelPacks::rowCount(const QModelIndex &parent) const
{
return m_list.count();
}
LevelPack *LevelPacks::levelPack(const QString &id) const
{
foreach (LevelPack *pack, m_list) {
if (pack->id() == id) {
return pack;
}
}
return nullptr;
}
|