From 21552196c529cdc4e7112d2f09a80ab81c71207a Mon Sep 17 00:00:00 2001 From: Aqua-sama Date: Fri, 24 Feb 2017 02:06:20 +0100 Subject: Settings class rework Using toml as format --- src/settings.cpp | 80 +++++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 62 insertions(+), 18 deletions(-) (limited to 'src/settings.cpp') diff --git a/src/settings.cpp b/src/settings.cpp index f030dfd..edbecc0 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -21,41 +21,85 @@ #include "settings.h" #include -QString Settings::_path = QString(""); +#include -Settings::Settings(QObject *parent) : - QSettings(_path, QSettings::IniFormat, parent) +Settings::Settings(const QString &configFile) { - setIniCodec("UTF-8"); + path = configFile; + std::ifstream ifs(configFile.toStdString().c_str()); + toml::ParseResult pr = toml::parse(ifs); + + if(!pr.valid()) { + qWarning("Invalid configuration: %s", pr.errorReason.c_str()); + return; + } + + v = pr.value; } -void Settings::setFilePath(const QString &path) +Settings::~Settings() { - qDebug("config=[%s]", qUtf8Printable(path)); - _path = path; } -QString Settings::staticFilePath() +QString Settings::filePath() const { - return _path; + return path; +} + +bool Settings::isEmpty() const +{ + return v.empty(); +} + +bool Settings::contains(const QString &key) +{ + const toml::Value *x = v.find(key.toStdString()); + if(x) { + return true; + } else { + return false; + } } QVariant Settings::value(const QString &key, const QVariant &defaultValue) const { - // get the actual value - QString value = QSettings::value(key, defaultValue).toString(); - - // check if there is a reference - QRegularExpressionMatch referenceMatch = referencePattern.match(value); - if(referenceMatch.hasMatch()) { - QString pattern = referenceMatch.capturedTexts().first(); - value.replace(pattern, this->value(pattern.mid(1, pattern.length()-2)).toString()); + const toml::Value *x = v.find(key.toStdString()); + + // check if value exists + if(!x) { + return defaultValue; + } + + QVariant r; + switch (x->type()) { + case toml::Value::NULL_TYPE: + r = defaultValue; + break; + + case toml::Value::BOOL_TYPE: + r = QVariant(x->as()); + break; + + case toml::Value::INT_TYPE: + r = QVariant(x->as()); + break; + + case toml::Value::STRING_TYPE: + r = QVariant(QString::fromStdString(x->as())); + break; + + default: + qWarning("Unhandled type in configuration"); + r = defaultValue; + break; } // check if key is a path, in which case replace '~' with the home location if(key.endsWith(QLatin1String("path"), Qt::CaseInsensitive)) { + QString value = r.toString(); value.replace('~', QStandardPaths::writableLocation(QStandardPaths::HomeLocation)); + r = QVariant(value); } - return QVariant(value); + return r; } -- cgit v1.2.1