Newer
Older
#include <QDebug>
#include <QStandardPaths>
#include <QCoreApplication>
#include <QDir>
#include "configstorage.h"
#define CHECK_INTERVAL 300
//-------------------------------------------------------------------------------------------------
ConfigStorage::ConfigStorage()
: mConfigFile(nullptr)
{
connect(&mWatchTimer, &QTimer::timeout, this, &ConfigStorage::checkConfigUpdate);
}
//-------------------------------------------------------------------------------------------------
bool ConfigStorage::init()
{
Q_ASSERT(!mConfigFile); // call init only once
QString cfgPath = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)
+ "/" + qApp->applicationName();
if (!QDir(cfgPath).mkpath(cfgPath)) {
qWarning() << "Failed to create path" << cfgPath;
return false;
}
cfgPath.append("/config.json");
mConfigFile = new QFile(cfgPath);
bool useDefaults = !mConfigFile->exists() || mConfigFile->size() == 0;
if (!mConfigFile->open(QIODevice::ReadWrite)) {
qWarning() << "Could not open" << cfgPath << "with read/write mode";
return false;
}
if (useDefaults)
revertToDefaults();
updateConfig();
mWatchTimer.start(CHECK_INTERVAL);
//-------------------------------------------------------------------------------------------------
void ConfigStorage::checkConfigUpdate()
{
Q_ASSERT(mConfigFile);
if (QFileInfo(*mConfigFile).lastModified() > mLastUpdate)
updateConfig();
}
//-------------------------------------------------------------------------------------------------
void ConfigStorage::updateConfig()
{
Q_ASSERT(mConfigFile->isOpen());
mLastUpdate = QDateTime::currentDateTime();
qDebug() << "update config";
}
//-------------------------------------------------------------------------------------------------
void ConfigStorage::revertToDefaults()
{
Q_ASSERT(mConfigFile && mConfigFile->isOpen()); // call init first
QFile defaults(":/config/install/default.json");
Q_ASSERT(defaults.exists());
bool open = defaults.open(QIODevice::ReadOnly);
Q_ASSERT(open);
mConfigFile->write(defaults.readAll());
mConfigFile->flush();
}