-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.cpp
107 lines (95 loc) · 2.37 KB
/
config.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
95
96
97
98
99
100
101
102
103
104
105
106
107
#include "config.h"
#include <QDir>
#include <QDebug>
#include <QRegularExpression>
#include <functional>
#include <iterator>
Config::Config(QString file, bool autosave, QObject *parent)
: QObject(parent)
, updateInPlace(autosave)
, sourceFile(file)
{
update();
}
void Config::update()
{
data.clear();
// opening for read-write so it will create the file if it doesn't exist
sourceFile.open(QIODevice::ReadWrite);
for (QByteArray k = sourceFile.readLine(); k.length() > 0; k = sourceFile.readLine())
{
QRegularExpression re{"^([a-zA-Z_\\.\\-]+) +(.+)$"};
auto t = QString(k).trimmed();
if (t.length() == 0) // ignore empty lines
continue;
auto match = re.match(t);
if (!match.hasMatch())
{
qDebug() << "Could not match line" << QString(k);
}
data[match.captured(1)] = parse(match.captured(2));
}
sourceFile.close();
}
void Config::save()
{
sourceFile.open(QIODevice::WriteOnly);
for (auto k : data.keys())
{
auto str = QString("%1 %2\n").arg(k).arg(stringify(data[k])).toUtf8();
qDebug() << str;
sourceFile.write(str);
}
sourceFile.flush();
sourceFile.close();
}
QVariant Config::parse(QString stuff)
{
bool ok = true;
int i = stuff.toInt(&ok);
if (ok)
return QVariant(i);
double d = stuff.toDouble(&ok);
if (ok)
return QVariant(d);
if (stuff == "true" || stuff == "false")
// ? true : false is needed so it's not an int.
return QVariant(stuff == "true" ? true : false);
return QVariant(stuff);
}
QString Config::stringify(QVariant var)
{
switch (var.type())
{
case QVariant::Type::Int:
return QString::number(var.toInt());
case QVariant::Type::Double:
return QString::number(var.toDouble());
case QVariant::Type::Bool:
return QString(var.toBool());
case QVariant::Type::String:
return var.toString();
default:
return "#INVALID_DATA#";
}
}
QVariant &Config::get(QString key)
{
return data[key];
}
void Config::set(QString key, QVariant val)
{
data[key] = val;
if (updateInPlace)
save();
}
QVariant Config::getOrSet(QString key, QVariant val)
{
if (!data.contains(key))
set(key, val);
return get(key);
}
bool Config::exists(QString key)
{
return data.contains(key);
}