mirror-chatterino2/setting.h

84 lines
1.5 KiB
C
Raw Normal View History

2017-01-18 21:30:23 +01:00
#ifndef SETTING_H
#define SETTING_H
2017-01-20 06:10:28 +01:00
#include <QSettings>
2017-01-18 21:30:23 +01:00
#include <QString>
#include <boost/signals2.hpp>
2017-01-18 21:30:23 +01:00
namespace chatterino {
class BaseSetting
2017-01-18 21:30:23 +01:00
{
public:
BaseSetting(const QString &_name)
: name(_name)
{
}
virtual void save(QSettings &settings) = 0;
virtual void load(const QSettings &settings) = 0;
const QString &
getName() const
{
return this->name;
}
private:
QString name;
};
template <typename T>
class Setting : public BaseSetting
{
2017-01-18 21:30:23 +01:00
public:
Setting(std::vector<std::reference_wrapper<BaseSetting>> &settingItems,
const QString &_name, const T &defaultValue)
: BaseSetting(_name)
, value(defaultValue)
2017-01-18 21:30:23 +01:00
{
settingItems.push_back(*this);
2017-01-18 21:30:23 +01:00
}
const T &
get() const
{
return this->value;
}
void
set(const T &newValue)
{
if (this->value != newValue) {
this->value = newValue;
this->valueChanged(newValue);
}
}
virtual void
save(QSettings &settings) final
{
settings.setValue(this->getName(), QVariant::fromValue(this->value));
}
virtual void
load(const QSettings &settings) final
{
QVariant newValue = settings.value(this->getName(), QVariant());
if (newValue.isValid()) {
assert(newValue.canConvert<T>());
this->set(newValue.value<T>());
}
}
boost::signals2::signal<void(const T &newValue)> valueChanged;
2017-01-20 06:10:28 +01:00
2017-01-18 21:30:23 +01:00
private:
T value;
2017-01-18 21:30:23 +01:00
};
} // namespace chatterino
2017-01-18 21:30:23 +01:00
#endif // SETTING_H