-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatasetProject.cpp
94 lines (79 loc) · 2.29 KB
/
DatasetProject.cpp
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "DatasetProject.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QString>
#include <QFile>
#include <QDebug>
namespace {
auto loadJsonObjectFromFile(QString const& filePath) -> QJsonObject
{
QJsonObject jsonObjectProject;
QFile projectFile(filePath);
if (projectFile.open(QIODevice::ReadOnly))
{
QJsonParseError parseError{};
jsonObjectProject = QJsonDocument::fromJson(projectFile.readAll(), &parseError).object();
if (parseError.error)
{
qDebug() << "File " << filePath << " is empty, return an empty object";
}
}
return jsonObjectProject;
}
bool saveJsonObjectToFile(QString const& filePath, QJsonObject const& jsonObject)
{
QFile projectFile(filePath);
if (projectFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
{
return projectFile.write(QJsonDocument{jsonObject}.toJson()) != -1;
}
return false;
}
} /// end namespace anonymous
class DatasetProject::Impl
{
public:
Impl(QString const& filePath)
: _projectFilePath{filePath}
, _projectJsonObject{loadJsonObjectFromFile(_projectFilePath)}
{
}
~Impl()
{
if (!saveJsonObjectToFile(_projectFilePath, _projectJsonObject))
{
qDebug() << "An error occured during saving to file";
}
}
auto get(QString const& key) -> QVariantMap
{
return _projectJsonObject[key].toObject().toVariantMap();
}
void set(QString const& key, QVariantMap const& data)
{
_projectJsonObject[key] = QJsonObject::fromVariantMap(data);
}
private:
QString _projectFilePath;
QJsonObject _projectJsonObject;
};
DatasetProject::DatasetProject() = default;
DatasetProject::~DatasetProject() = default;
void DatasetProject::loadFromFile(const QString &filePath)
{
_impl = std::make_unique<Impl>(filePath);
}
auto DatasetProject::get(QString const& key, std::function<QVariantMap()>&& defaultGetter) -> QVariantMap
{
auto data = _impl->get(key);
if (data.isEmpty())
{
data = defaultGetter();
set(key, data);
}
return data;
}
void DatasetProject::set(QString const& key, QVariantMap const& data)
{
_impl->set(key, data);
}