48 lines
1.6 KiB
C++
48 lines
1.6 KiB
C++
#include "Config.h"
|
|
#include <QDir>
|
|
#include <QFile>
|
|
#include <QStandardPaths>
|
|
|
|
QString Config::escape(const QString &s) {
|
|
return QString(s).replace("\\","\\\\").replace("\"","\\\"");
|
|
}
|
|
QString Config::unescape(const QString &s) {
|
|
return QString(s).replace("\\\\","\\").replace("\\\"","\"").replace("\\/","/");
|
|
}
|
|
|
|
QString Config::extractString(const QString &json, const QString &key) {
|
|
QString needle = "\"" + key + "\"";
|
|
int ki = json.indexOf(needle);
|
|
if (ki < 0) return {};
|
|
int colon = json.indexOf(':', ki + needle.size());
|
|
if (colon < 0) return {};
|
|
int open = json.indexOf('"', colon + 1);
|
|
if (open < 0) return {};
|
|
int close = open + 1;
|
|
while (close < json.size()) {
|
|
if (json[close] == '\\') { close += 2; continue; }
|
|
if (json[close] == '"') break;
|
|
++close;
|
|
}
|
|
if (close >= json.size()) return {};
|
|
return unescape(json.mid(open + 1, close - open - 1));
|
|
}
|
|
|
|
QString Config::loadMusicRoot() {
|
|
QFile f(configFile());
|
|
if (f.open(QIODevice::ReadOnly)) {
|
|
QString json = QString::fromUtf8(f.readAll());
|
|
QString path = extractString(json, "musicRoot");
|
|
if (!path.isEmpty() && QDir(path).exists()) return path;
|
|
}
|
|
QString music = QStandardPaths::writableLocation(QStandardPaths::MusicLocation);
|
|
return music.isEmpty() ? QDir::homePath() : music;
|
|
}
|
|
|
|
void Config::saveMusicRoot(const QString &root) {
|
|
QDir().mkpath(configDir());
|
|
QFile f(configFile());
|
|
if (f.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
|
|
f.write(("{\n \"musicRoot\": \"" + escape(root) + "\"\n}\n").toUtf8());
|
|
}
|
|
} |