-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigStore.cpp
More file actions
109 lines (87 loc) · 2.21 KB
/
Copy pathConfigStore.cpp
File metadata and controls
109 lines (87 loc) · 2.21 KB
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
108
109
#include "ConfigStore.hpp"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMutexLocker>
ConfigStore &ConfigStore::get() {
static ConfigStore instance;
return instance;
}
ConfigStore::ConfigStore() : _flushed(false) { readFromFile(); }
ConfigStore::~ConfigStore() {
if (!_flushed) {
writeToFile();
}
}
void ConfigStore::flush() {
writeToFile();
_flushed = true;
}
QString ConfigStore::filePath() const {
return QCoreApplication::applicationDirPath() + "/task_config.json";
}
void ConfigStore::readFromFile() {
QFile file(filePath());
if (!file.open(QIODevice::ReadOnly)) {
return;
}
const QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
file.close();
if (!doc.isObject()) {
return;
}
const QJsonObject root = doc.object();
for (auto it = root.begin(); it != root.end(); ++it) {
if (it.value().isObject()) {
_data.insert(it.key(), it.value().toObject());
}
}
}
void ConfigStore::writeToFile() {
QJsonObject root;
for (auto it = _data.begin(); it != _data.end(); ++it) {
root.insert(it.key(), it.value());
}
QFile file(filePath());
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
return;
}
file.write(QJsonDocument(root).toJson(QJsonDocument::Indented));
file.close();
}
// ====== 单个键值操作 ======
void ConfigStore::save(const QString &key, const QJsonObject &value) {
QMutexLocker locker(&_mutex);
_data.insert(key, value);
writeToFile();
}
QJsonObject ConfigStore::load(const QString &key) const {
QMutexLocker locker(&_mutex);
return _data.value(key);
}
void ConfigStore::remove(const QString &key) {
QMutexLocker locker(&_mutex);
if (_data.remove(key) > 0) {
writeToFile();
}
}
bool ConfigStore::contains(const QString &key) const {
QMutexLocker locker(&_mutex);
return _data.contains(key);
}
// ====== 批量操作 ======
QHash<QString, QJsonObject> ConfigStore::loadAll() const {
QMutexLocker locker(&_mutex);
return _data;
}
QStringList ConfigStore::keys() const {
QMutexLocker locker(&_mutex);
return _data.keys();
}
void ConfigStore::clear() {
QMutexLocker locker(&_mutex);
_data.clear();
writeToFile();
}