mirror-chatterino2/setting.h

78 lines
1.3 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)
2017-04-12 17:46:44 +02:00
: _name(_name)
{
}
2017-01-24 19:51:57 +01:00
virtual QVariant getVariant() = 0;
virtual void setVariant(QVariant value) = 0;
2017-04-12 17:46:44 +02:00
const QString &getName() const
{
2017-04-12 17:46:44 +02:00
return _name;
}
private:
2017-04-12 17:46:44 +02:00
QString _name;
};
template <typename T>
class Setting : public BaseSetting
{
2017-01-18 21:30:23 +01:00
public:
2017-04-12 17:46:44 +02:00
Setting(std::vector<std::reference_wrapper<BaseSetting>> &settingItems, const QString &_name,
const T &defaultValue)
: BaseSetting(_name)
2017-04-12 17:46:44 +02:00
, _value(defaultValue)
2017-01-18 21:30:23 +01:00
{
settingItems.push_back(*this);
2017-01-18 21:30:23 +01:00
}
2017-04-12 17:46:44 +02:00
const T &get() const
{
2017-04-12 17:46:44 +02:00
return _value;
}
2017-04-12 17:46:44 +02:00
void set(const T &newValue)
{
2017-04-12 17:46:44 +02:00
if (_value != newValue) {
_value = newValue;
2017-04-12 17:46:44 +02:00
valueChanged(newValue);
}
}
2017-04-12 17:46:44 +02:00
virtual QVariant getVariant() final
{
2017-04-12 17:46:44 +02:00
return QVariant::fromValue(_value);
}
2017-04-12 17:46:44 +02:00
virtual void setVariant(QVariant value) final
{
2017-01-24 19:51:57 +01:00
if (value.isValid()) {
assert(value.canConvert<T>());
2017-04-12 17:46:44 +02:00
set(value.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:
2017-04-12 17:46:44 +02:00
T _value;
2017-01-18 21:30:23 +01:00
};
2017-04-14 17:52:22 +02:00
} // namespace chatterino
2017-01-18 21:30:23 +01:00
#endif // SETTING_H