Allow the use of synonyms in settings. Refactor settings.

Remove a bunch of obsolete/unused code.
This commit is contained in:
Petr Mrázek 2014-01-01 15:08:40 +01:00
parent 6648c7ad90
commit 396e63500e
24 changed files with 232 additions and 643 deletions

View File

@ -166,7 +166,7 @@ MultiMC::MultiMC(int &argc, char **argv, const QString &root)
m_instances.reset(new InstanceList(InstDirSetting->get().toString(), this)); m_instances.reset(new InstanceList(InstDirSetting->get().toString(), this));
QLOG_INFO() << "Loading Instances..."; QLOG_INFO() << "Loading Instances...";
m_instances->loadList(); m_instances->loadList();
connect(InstDirSetting, SIGNAL(settingChanged(const Setting &, QVariant)), connect(InstDirSetting.get(), SIGNAL(settingChanged(const Setting &, QVariant)),
m_instances.get(), SLOT(on_InstFolderChanged(const Setting &, QVariant))); m_instances.get(), SLOT(on_InstFolderChanged(const Setting &, QVariant)));
// and accounts // and accounts
@ -324,23 +324,22 @@ void MultiMC::initGlobalSettings()
{ {
m_settings.reset(new INISettingsObject("multimc.cfg", this)); m_settings.reset(new INISettingsObject("multimc.cfg", this));
// Updates // Updates
m_settings->registerSetting(new Setting("UseDevBuilds", false)); m_settings->registerSetting("UseDevBuilds", false);
m_settings->registerSetting(new Setting("AutoUpdate", true)); m_settings->registerSetting("AutoUpdate", true);
// FTB // FTB
m_settings->registerSetting(new Setting("TrackFTBInstances", false)); m_settings->registerSetting("TrackFTBInstances", false);
m_settings->registerSetting(new Setting(
"FTBLauncherRoot",
#ifdef Q_OS_LINUX #ifdef Q_OS_LINUX
QDir::home().absoluteFilePath(".ftblauncher") QString ftbDefault = QDir::home().absoluteFilePath(".ftblauncher");
#elif defined(Q_OS_WIN32) #elif defined(Q_OS_WIN32)
PathCombine(QDir::homePath(), "AppData/Roaming/ftblauncher") QString ftbDefault = PathCombine(QDir::homePath(), "AppData/Roaming/ftblauncher");
#elif defined(Q_OS_MAC) #elif defined(Q_OS_MAC)
PathCombine(QDir::homePath(), "Library/Application Support/ftblauncher") QString ftbDefault =
PathCombine(QDir::homePath(), "Library/Application Support/ftblauncher");
#endif #endif
)); m_settings->registerSetting("FTBLauncherRoot", ftbDefault);
m_settings->registerSetting(new Setting("FTBRoot")); m_settings->registerSetting("FTBRoot");
if (m_settings->get("FTBRoot").isNull()) if (m_settings->get("FTBRoot").isNull())
{ {
QString ftbRoot; QString ftbRoot;
@ -379,54 +378,54 @@ void MultiMC::initGlobalSettings()
} }
// Folders // Folders
m_settings->registerSetting(new Setting("InstanceDir", "instances")); m_settings->registerSetting("InstanceDir", "instances");
m_settings->registerSetting(new Setting("CentralModsDir", "mods")); m_settings->registerSetting({"CentralModsDir", "ModsDir"}, "mods");
m_settings->registerSetting(new Setting("LWJGLDir", "lwjgl")); m_settings->registerSetting({"LWJGLDir", "LwjglDir"}, "lwjgl");
m_settings->registerSetting(new Setting("IconsDir", "icons")); m_settings->registerSetting("IconsDir", "icons");
// Editors // Editors
m_settings->registerSetting(new Setting("JsonEditor", QString())); m_settings->registerSetting("JsonEditor", QString());
// Console // Console
m_settings->registerSetting(new Setting("ShowConsole", true)); m_settings->registerSetting("ShowConsole", true);
m_settings->registerSetting(new Setting("AutoCloseConsole", true)); m_settings->registerSetting("AutoCloseConsole", true);
// Console Colors // Console Colors
// m_settings->registerSetting(new Setting("SysMessageColor", QColor(Qt::blue))); // m_settings->registerSetting("SysMessageColor", QColor(Qt::blue));
// m_settings->registerSetting(new Setting("StdOutColor", QColor(Qt::black))); // m_settings->registerSetting("StdOutColor", QColor(Qt::black));
// m_settings->registerSetting(new Setting("StdErrColor", QColor(Qt::red))); // m_settings->registerSetting("StdErrColor", QColor(Qt::red));
// Window Size // Window Size
m_settings->registerSetting(new Setting("LaunchMaximized", false)); m_settings->registerSetting({"LaunchMaximized", "MCWindowMaximize"}, false);
m_settings->registerSetting(new Setting("MinecraftWinWidth", 854)); m_settings->registerSetting({"MinecraftWinWidth", "MCWindowWidth"}, 854);
m_settings->registerSetting(new Setting("MinecraftWinHeight", 480)); m_settings->registerSetting({"MinecraftWinHeight", "MCWindowHeight"}, 480);
// Memory // Memory
m_settings->registerSetting(new Setting("MinMemAlloc", 512)); m_settings->registerSetting({"MinMemAlloc", "MinMemoryAlloc"}, 512);
m_settings->registerSetting(new Setting("MaxMemAlloc", 1024)); m_settings->registerSetting({"MaxMemAlloc", "MaxMemoryAlloc"}, 1024);
m_settings->registerSetting(new Setting("PermGen", 64)); m_settings->registerSetting("PermGen", 64);
// Java Settings // Java Settings
m_settings->registerSetting(new Setting("JavaPath", "")); m_settings->registerSetting("JavaPath", "");
m_settings->registerSetting(new Setting("LastHostname", "")); m_settings->registerSetting("LastHostname", "");
m_settings->registerSetting(new Setting("JvmArgs", "")); m_settings->registerSetting("JvmArgs", "");
// Custom Commands // Custom Commands
m_settings->registerSetting(new Setting("PreLaunchCommand", "")); m_settings->registerSetting({"PreLaunchCommand", "PreLaunchCmd"}, "");
m_settings->registerSetting(new Setting("PostExitCommand", "")); m_settings->registerSetting({"PostExitCommand", "PostLaunchCmd"}, "");
// The cat // The cat
m_settings->registerSetting(new Setting("TheCat", false)); m_settings->registerSetting("TheCat", false);
m_settings->registerSetting(new Setting("InstSortMode", "Name")); m_settings->registerSetting("InstSortMode", "Name");
m_settings->registerSetting(new Setting("SelectedInstance", QString())); m_settings->registerSetting("SelectedInstance", QString());
// Window state and geometry // Window state and geometry
m_settings->registerSetting(new Setting("MainWindowState", "")); m_settings->registerSetting("MainWindowState", "");
m_settings->registerSetting(new Setting("MainWindowGeometry", "")); m_settings->registerSetting("MainWindowGeometry", "");
m_settings->registerSetting(new Setting("ConsoleWindowState", "")); m_settings->registerSetting("ConsoleWindowState", "");
m_settings->registerSetting(new Setting("ConsoleWindowGeometry", "")); m_settings->registerSetting("ConsoleWindowGeometry", "");
} }
void MultiMC::initHttpMetaCache() void MultiMC::initHttpMetaCache()
@ -524,9 +523,9 @@ void MultiMC::installUpdates(const QString &updateFilesDir, bool restartOnFinish
args << "--finish-cmd" << finishCmd; args << "--finish-cmd" << finishCmd;
QLOG_INFO() << "Running updater with command" << updaterBinary << args.join(" "); QLOG_INFO() << "Running updater with command" << updaterBinary << args.join(" ");
QFile::setPermissions(updaterBinary, (QFileDevice::Permission) 0x7755); QFile::setPermissions(updaterBinary, (QFileDevice::Permission)0x7755);
if(!QProcess::startDetached(updaterBinary, args)) if (!QProcess::startDetached(updaterBinary, args))
{ {
QLOG_ERROR() << "Failed to start the updater process!"; QLOG_ERROR() << "Failed to start the updater process!";
return; return;
@ -555,8 +554,8 @@ bool MultiMC::openJsonEditor(const QString &filename)
} }
else else
{ {
return QProcess::startDetached(m_settings->get("JsonEditor").toString(), return QProcess::startDetached(m_settings->get("JsonEditor").toString(), QStringList()
QStringList() << file); << file);
} }
} }

View File

@ -5,44 +5,27 @@ find_package(Qt5Core REQUIRED)
# Include Qt headers. # Include Qt headers.
include_directories(${Qt5Base_INCLUDE_DIRS}) include_directories(${Qt5Base_INCLUDE_DIRS})
include_directories(${Qt5Network_INCLUDE_DIRS})
SET(LIBSETTINGS_HEADERS
include/libsettings_config.h
include/inifile.h
include/settingsobject.h
include/setting.h
include/overridesetting.h
include/basicsettingsobject.h
include/inisettingsobject.h
include/keyring.h
)
SET(LIBSETTINGS_HEADERS_PRIVATE
src/stubkeyring.h
)
SET(LIBSETTINGS_SOURCES SET(LIBSETTINGS_SOURCES
src/inifile.cpp libsettings_config.h
src/settingsobject.cpp inifile.h
src/setting.cpp inifile.cpp
src/overridesetting.cpp
src/basicsettingsobject.cpp settingsobject.h
src/inisettingsobject.cpp settingsobject.cpp
inisettingsobject.h
inisettingsobject.cpp
src/keyring.cpp setting.h
src/stubkeyring.cpp setting.cpp
overridesetting.h
overridesetting.cpp
) )
# Set the include dir path. # Set the include dir path.
SET(LIBSETTINGS_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/include" PARENT_SCOPE) SET(LIBSETTINGS_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}" PARENT_SCOPE)
include_directories(${LIBSETTINGS_INCLUDE_DIR})
# Static link! # Static link!
ADD_DEFINITIONS(-DLIBSETTINGS_STATIC) ADD_DEFINITIONS(-DLIBSETTINGS_STATIC)
@ -59,6 +42,6 @@ IF(MultiMC_CODE_COVERAGE)
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -O0 --coverage") SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -O0 --coverage")
ENDIF(MultiMC_CODE_COVERAGE) ENDIF(MultiMC_CODE_COVERAGE)
add_library(libSettings STATIC ${LIBSETTINGS_SOURCES} ${LIBSETTINGS_HEADERS} ${LIBSETTINGS_HEADERS_PRIVATE}) add_library(libSettings STATIC ${LIBSETTINGS_SOURCES})
qt5_use_modules(libSettings Core) qt5_use_modules(libSettings Core)
target_link_libraries(libSettings) target_link_libraries(libSettings)

View File

@ -1,42 +0,0 @@
/* Copyright 2013 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QObject>
#include <QSettings>
#include "settingsobject.h"
#include "libsettings_config.h"
/*!
* \brief A settings object that stores its settings in a QSettings object.
*/
class LIBSETTINGS_EXPORT BasicSettingsObject : public SettingsObject
{
Q_OBJECT
public:
explicit BasicSettingsObject(QObject *parent = 0);
protected
slots:
virtual void changeSetting(const Setting &setting, QVariant value);
protected:
virtual QVariant retrieveValue(const Setting &setting);
QSettings config;
};

View File

@ -1,97 +0,0 @@
/* Copyright 2013 MultiMC Contributors
*
* Authors: Orochimarufan <orochimarufan.x3@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <QString>
#include "libsettings_config.h"
/**
* @file libsettings/include/keyring.h
* Access to System Keyrings
*/
/**
* @brief The Keyring class
* the System Keyring/Keychain/Wallet/Vault/etc
*/
class LIBSETTINGS_EXPORT Keyring
{
public:
/**
* @brief virtual dtor
*/
virtual ~Keyring() {};
/**
* @brief the System Keyring instance
* @return the Keyring instance
*/
static Keyring *instance();
/**
* @brief store a password in the Keyring
* @param service the service name
* @param username the account name
* @param password the password to store
* @return success
*/
virtual bool storePassword(QString service, QString username, QString password) = 0;
/**
* @brief get a password from the Keyring
* @param service the service name
* @param username the account name
* @return the password (success=!isNull())
*/
virtual QString getPassword(QString service, QString username) = 0;
/**
* @brief lookup a password
* @param service the service name
* @param username the account name
* @return wether the password is available
*/
virtual bool hasPassword(QString service, QString username) = 0;
/**
* @brief get a list of all stored accounts.
* @param service the service name
* @return
*/
virtual QStringList getStoredAccounts(QString service) = 0;
/**
* @brief Remove the specified account from storage
* @param service the service name
* @param username the account name
* @return
*/
virtual void removeStoredAccount(QString service, QString username) = 0;
protected:
/// fall back to StubKeyring if false
virtual bool isValid()
{
return false;
}
private:
static Keyring *m_instance;
static void destroy();
};

View File

@ -13,7 +13,7 @@
* limitations under the License. * limitations under the License.
*/ */
#include "include/inifile.h" #include "inifile.h"
#include <QFile> #include <QFile>
#include <QTextStream> #include <QTextStream>

View File

@ -13,8 +13,8 @@
* limitations under the License. * limitations under the License.
*/ */
#include "include/inisettingsobject.h" #include "inisettingsobject.h"
#include "include/setting.h" #include "setting.h"
INISettingsObject::INISettingsObject(const QString &path, QObject *parent) INISettingsObject::INISettingsObject(const QString &path, QObject *parent)
: SettingsObject(parent) : SettingsObject(parent)
@ -32,31 +32,45 @@ void INISettingsObject::changeSetting(const Setting &setting, QVariant value)
{ {
if (contains(setting.id())) if (contains(setting.id()))
{ {
// valid value -> set the main config, remove all the sysnonyms
if (value.isValid()) if (value.isValid())
m_ini.set(setting.configKey(), value); {
auto list = setting.configKeys();
m_ini.set(list.takeFirst(), value);
for(auto iter: list)
m_ini.remove(iter);
}
// invalid -> remove all (just like resetSetting)
else else
m_ini.remove(setting.configKey()); {
for(auto iter: setting.configKeys())
m_ini.remove(iter);
}
m_ini.saveFile(m_filePath); m_ini.saveFile(m_filePath);
} }
} }
void INISettingsObject::resetSetting(const Setting &setting) void INISettingsObject::resetSetting(const Setting &setting)
{ {
// if we have the setting, remove all the synonyms. ALL OF THEM
if (contains(setting.id())) if (contains(setting.id()))
{ {
m_ini.remove(setting.configKey()); for(auto iter: setting.configKeys())
m_ini.remove(iter);
m_ini.saveFile(m_filePath); m_ini.saveFile(m_filePath);
} }
} }
QVariant INISettingsObject::retrieveValue(const Setting &setting) QVariant INISettingsObject::retrieveValue(const Setting &setting)
{ {
// if we have the setting, return value of the first matching synonym
if (contains(setting.id())) if (contains(setting.id()))
{ {
return m_ini.get(setting.configKey(), QVariant()); for(auto iter: setting.configKeys())
} {
else if(m_ini.contains(iter))
{ return m_ini[iter];
return QVariant(); }
} }
return QVariant();
} }

View File

@ -26,3 +26,4 @@
#define LIBSETTINGS_EXPORT Q_DECL_IMPORT #define LIBSETTINGS_EXPORT Q_DECL_IMPORT
#endif #endif
#endif #endif

View File

@ -13,10 +13,10 @@
* limitations under the License. * limitations under the License.
*/ */
#include "include/overridesetting.h" #include "overridesetting.h"
OverrideSetting::OverrideSetting(const QString &name, Setting *other, QObject *parent) OverrideSetting::OverrideSetting(std::shared_ptr<Setting> other)
: Setting(name, QVariant(), parent) : Setting(other->configKeys(), QVariant())
{ {
m_other = other; m_other = other;
} }

View File

@ -16,6 +16,7 @@
#pragma once #pragma once
#include <QObject> #include <QObject>
#include <memory>
#include "setting.h" #include "setting.h"
@ -31,10 +32,10 @@ class LIBSETTINGS_EXPORT OverrideSetting : public Setting
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit OverrideSetting(const QString &name, Setting *other, QObject *parent = 0); explicit OverrideSetting(std::shared_ptr<Setting> other);
virtual QVariant defValue() const; virtual QVariant defValue() const;
protected: protected:
Setting *m_other; std::shared_ptr<Setting> m_other;
}; };

View File

@ -13,17 +13,23 @@
* limitations under the License. * limitations under the License.
*/ */
#include "include/setting.h" #include "setting.h"
#include "include/settingsobject.h" #include "settingsobject.h"
Setting::Setting(QString id, QVariant defVal, QObject *parent) Setting::Setting(QStringList synonyms, QVariant defVal)
: QObject(parent), m_id(id), m_defVal(defVal) : QObject(), m_synonyms(synonyms), m_defVal(defVal)
{ {
} }
Setting::Setting(QString id, QVariant defVal)
: QObject(), m_synonyms({id}), m_defVal(defVal)
{
}
QVariant Setting::get() const QVariant Setting::get() const
{ {
SettingsObject *sbase = qobject_cast<SettingsObject *>(parent()); SettingsObject *sbase = m_storage;
if (!sbase) if (!sbase)
{ {
return defValue(); return defValue();

View File

@ -17,6 +17,8 @@
#include <QObject> #include <QObject>
#include <QVariant> #include <QVariant>
#include <QStringList>
#include <memory>
#include "libsettings_config.h" #include "libsettings_config.h"
@ -33,7 +35,13 @@ public:
* \brief Constructs a new Setting object with the given parent. * \brief Constructs a new Setting object with the given parent.
* \param parent The Setting's parent object. * \param parent The Setting's parent object.
*/ */
explicit Setting(QString id, QVariant defVal = QVariant(), QObject *parent = 0); explicit Setting(QStringList synonyms, QVariant defVal = QVariant());
/*!
* \brief Constructs a new Setting object with the given parent.
* \param parent The Setting's parent object.
*/
explicit Setting(QString id, QVariant defVal = QVariant());
/*! /*!
* \brief Gets this setting's ID. * \brief Gets this setting's ID.
@ -44,7 +52,7 @@ public:
*/ */
virtual QString id() const virtual QString id() const
{ {
return m_id; return m_synonyms.first();
} }
/*! /*!
@ -53,9 +61,9 @@ public:
* the same as the setting's ID, but it can be different. * the same as the setting's ID, but it can be different.
* \return The setting's config file key. * \return The setting's config file key.
*/ */
virtual QString configKey() const virtual QStringList configKeys() const
{ {
return id(); return m_synonyms;
} }
/*! /*!
@ -111,11 +119,12 @@ slots:
* \brief Reset the setting to default * \brief Reset the setting to default
* This is done by emitting the settingReset() signal which will then be * This is done by emitting the settingReset() signal which will then be
* handled by the SettingsObject object and cause the setting to change. * handled by the SettingsObject object and cause the setting to change.
* \param value The new value.
*/ */
virtual void reset(); virtual void reset();
protected: protected:
QString m_id; friend class SettingsObject;
SettingsObject * m_storage;
QStringList m_synonyms;
QVariant m_defVal; QVariant m_defVal;
}; };

View File

@ -13,8 +13,9 @@
* limitations under the License. * limitations under the License.
*/ */
#include "include/settingsobject.h" #include "settingsobject.h"
#include "include/setting.h" #include "setting.h"
#include "overridesetting.h"
#include <QVariant> #include <QVariant>
@ -22,17 +23,49 @@ SettingsObject::SettingsObject(QObject *parent) : QObject(parent)
{ {
} }
SettingsObject::~SettingsObject()
{
m_settings.clear();
}
std::shared_ptr<Setting> SettingsObject::registerOverride(std::shared_ptr<Setting> original)
{
if (contains(original->id()))
{
qDebug(QString("Failed to register setting %1. ID already exists.")
.arg(original->id())
.toUtf8());
return nullptr; // Fail
}
auto override = std::make_shared<OverrideSetting>(original);
override->m_storage = this;
connectSignals(*override);
m_settings.insert(override->id(), override);
return override;
}
std::shared_ptr<Setting> SettingsObject::registerSetting(QStringList synonyms, QVariant defVal)
{
if (synonyms.empty())
return nullptr;
if (contains(synonyms.first()))
{
qDebug(QString("Failed to register setting %1. ID already exists.")
.arg(synonyms.first())
.toUtf8());
return nullptr; // Fail
}
auto setting = std::make_shared<Setting>(synonyms, defVal);
setting->m_storage = this;
connectSignals(*setting);
m_settings.insert(setting->id(), setting);
return setting;
}
/*
bool SettingsObject::registerSetting(Setting *setting) bool SettingsObject::registerSetting(Setting *setting)
{ {
// Check if setting is null or we already have a setting with the same ID.
if (!setting)
{
qDebug(QString("Failed to register setting. Setting is null.")
.arg(setting->id())
.toUtf8());
return false; // Fail
}
if (contains(setting->id())) if (contains(setting->id()))
{ {
qDebug(QString("Failed to register setting %1. ID already exists.") qDebug(QString("Failed to register setting %1. ID already exists.")
@ -50,21 +83,8 @@ bool SettingsObject::registerSetting(Setting *setting)
// qDebug(QString("Registered setting %1.").arg(setting->id()).toUtf8()); // qDebug(QString("Registered setting %1.").arg(setting->id()).toUtf8());
return true; return true;
} }
*/
void SettingsObject::unregisterSetting(Setting *setting) std::shared_ptr<Setting> SettingsObject::getSetting(const QString &id) const
{
if (!setting || !m_settings.contains(setting->id()))
return; // We can't unregister something that's not registered.
m_settings.remove(setting->id());
// Disconnect signals.
disconnectSignals(*setting);
setting->setParent(NULL); // Drop ownership.
}
Setting *SettingsObject::getSetting(const QString &id) const
{ {
// Make sure there is a setting with the given ID. // Make sure there is a setting with the given ID.
if (!m_settings.contains(id)) if (!m_settings.contains(id))
@ -75,13 +95,13 @@ Setting *SettingsObject::getSetting(const QString &id) const
QVariant SettingsObject::get(const QString &id) const QVariant SettingsObject::get(const QString &id) const
{ {
Setting *setting = getSetting(id); auto setting = getSetting(id);
return (setting ? setting->get() : QVariant()); return (setting ? setting->get() : QVariant());
} }
bool SettingsObject::set(const QString &id, QVariant value) bool SettingsObject::set(const QString &id, QVariant value)
{ {
Setting *setting = getSetting(id); auto setting = getSetting(id);
if (!setting) if (!setting)
{ {
qDebug(QString("Error changing setting %1. Setting doesn't exist.").arg(id).toUtf8()); qDebug(QString("Error changing setting %1. Setting doesn't exist.").arg(id).toUtf8());
@ -96,16 +116,11 @@ bool SettingsObject::set(const QString &id, QVariant value)
void SettingsObject::reset(const QString &id) const void SettingsObject::reset(const QString &id) const
{ {
Setting *setting = getSetting(id); auto setting = getSetting(id);
if (setting) if (setting)
setting->reset(); setting->reset();
} }
QList<Setting *> SettingsObject::getSettings()
{
return m_settings.values();
}
bool SettingsObject::contains(const QString &id) bool SettingsObject::contains(const QString &id)
{ {
return m_settings.contains(id); return m_settings.contains(id);
@ -121,16 +136,3 @@ void SettingsObject::connectSignals(const Setting &setting)
connect(&setting, SIGNAL(settingReset(Setting)), SLOT(resetSetting(const Setting &))); connect(&setting, SIGNAL(settingReset(Setting)), SLOT(resetSetting(const Setting &)));
connect(&setting, SIGNAL(settingReset(Setting)), SIGNAL(settingReset(const Setting &))); connect(&setting, SIGNAL(settingReset(Setting)), SIGNAL(settingReset(const Setting &)));
} }
void SettingsObject::disconnectSignals(const Setting &setting)
{
setting.disconnect(SIGNAL(settingChanged(const Setting &, QVariant)), this,
SLOT(changeSetting(const Setting &, QVariant)));
setting.disconnect(SIGNAL(settingChanged(const Setting &, QVariant)), this,
SIGNAL(settingChanged(const Setting &, QVariant)));
setting.disconnect(SIGNAL(settingReset(const Setting &, QVariant)), this,
SLOT(resetSetting(const Setting &, QVariant)));
setting.disconnect(SIGNAL(settingReset(const Setting &, QVariant)), this,
SIGNAL(settingReset(const Setting &, QVariant)));
}

View File

@ -17,6 +17,9 @@
#include <QObject> #include <QObject>
#include <QMap> #include <QMap>
#include <QStringList>
#include <QVariant>
#include <memory>
#include "libsettings_config.h" #include "libsettings_config.h"
@ -39,32 +42,37 @@ class LIBSETTINGS_EXPORT SettingsObject : public QObject
Q_OBJECT Q_OBJECT
public: public:
explicit SettingsObject(QObject *parent = 0); explicit SettingsObject(QObject *parent = 0);
virtual ~SettingsObject();
/*! /*!
* \brief Registers the given setting with this SettingsObject and connects the necessary * Registers an override setting for the given original setting in this settings object
* signals. *
* This will fail if there is already a setting with the same ID as * This will fail if there is already a setting with the same ID as
* the one that is being registered. * the one that is being registered.
* \note Registering a setting object causes the SettingsObject to take ownership * \return A valid Setting shared pointer if successful.
* of the object. This means that setting's parent will be set to the object
* it was registered with. Because the object it was registered with has taken
* ownership, it becomes responsible for managing that setting object's memory.
* \warning Do \b not delete the setting after registering it.
* \param setting A pointer to the setting that will be registered.
* \return True if successful. False if registry failed.
*/ */
virtual bool registerSetting(Setting *setting); std::shared_ptr<Setting> registerOverride(std::shared_ptr<Setting> original);
/*! /*!
* \brief Unregisters the given setting from this SettingsObject and disconnects its * Registers the given setting with this SettingsObject and connects the necessary signals.
* signals. *
* \note This does not delete the setting. Furthermore, when the setting is * This will fail if there is already a setting with the same ID as
* unregistered, the SettingsObject drops ownership of the setting. This means * the one that is being registered.
* that if you unregister a setting, its parent is set to null and you become * \return A valid Setting shared pointer if successful.
* responsible for freeing its memory.
* \param setting The setting to unregister.
*/ */
virtual void unregisterSetting(Setting *setting); std::shared_ptr<Setting> registerSetting(QStringList synonyms,
QVariant defVal = QVariant());
/*!
* Registers the given setting with this SettingsObject and connects the necessary signals.
*
* This will fail if there is already a setting with the same ID as
* the one that is being registered.
* \return A valid Setting shared pointer if successful.
*/
std::shared_ptr<Setting> registerSetting(QString id, QVariant defVal = QVariant())
{
return registerSetting(QStringList(id), defVal);
}
/*! /*!
* \brief Gets the setting with the given ID. * \brief Gets the setting with the given ID.
@ -73,18 +81,7 @@ public:
* Returns null if there is no setting with the given ID. * Returns null if there is no setting with the given ID.
* \sa operator []() * \sa operator []()
*/ */
virtual Setting *getSetting(const QString &id) const; std::shared_ptr<Setting> getSetting(const QString &id) const;
/*!
* \brief Same as getSetting()
* \param id The ID of the setting to get.
* \return A pointer to the setting with the given ID.
* \sa getSetting()
*/
inline Setting *operator[](const QString &id)
{
return getSetting(id);
}
/*! /*!
* \brief Gets the value of the setting with the given ID. * \brief Gets the value of the setting with the given ID.
@ -92,7 +89,7 @@ public:
* \return The setting's value as a QVariant. * \return The setting's value as a QVariant.
* If no setting with the given ID exists, returns an invalid QVariant. * If no setting with the given ID exists, returns an invalid QVariant.
*/ */
virtual QVariant get(const QString &id) const; QVariant get(const QString &id) const;
/*! /*!
* \brief Sets the value of the setting with the given ID. * \brief Sets the value of the setting with the given ID.
@ -101,27 +98,20 @@ public:
* \param value The new value of the setting. * \param value The new value of the setting.
* \return True if successful, false if it failed. * \return True if successful, false if it failed.
*/ */
virtual bool set(const QString &id, QVariant value); bool set(const QString &id, QVariant value);
/*! /*!
* \brief Reverts the setting with the given ID to default. * \brief Reverts the setting with the given ID to default.
* \param id The ID of the setting to reset. * \param id The ID of the setting to reset.
*/ */
virtual void reset(const QString &id) const; void reset(const QString &id) const;
/*!
* \brief Gets a QList with pointers to all of the registered settings.
* The order of the entries in the list is undefined.
* \return A QList with pointers to all registered settings.
*/
virtual QList<Setting *> getSettings();
/*! /*!
* \brief Checks if this SettingsObject contains a setting with the given ID. * \brief Checks if this SettingsObject contains a setting with the given ID.
* \param id The ID to check for. * \param id The ID to check for.
* \return True if the SettingsObject has a setting with the given ID. * \return True if the SettingsObject has a setting with the given ID.
*/ */
virtual bool contains(const QString &id); bool contains(const QString &id);
signals: signals:
/*! /*!
@ -167,13 +157,7 @@ protected:
* \brief Connects the necessary signals to the given Setting. * \brief Connects the necessary signals to the given Setting.
* \param setting The setting to connect. * \param setting The setting to connect.
*/ */
virtual void connectSignals(const Setting &setting); void connectSignals(const Setting &setting);
/*!
* \brief Disconnects signals from the given Setting.
* \param setting The setting to disconnect.
*/
virtual void disconnectSignals(const Setting &setting);
/*! /*!
* \brief Function used by Setting objects to get their values from the SettingsObject. * \brief Function used by Setting objects to get their values from the SettingsObject.
@ -185,5 +169,5 @@ protected:
friend class Setting; friend class Setting;
private: private:
QMap<QString, Setting *> m_settings; QMap<QString, std::shared_ptr<Setting>> m_settings;
}; };

View File

@ -1,44 +0,0 @@
/* Copyright 2013 MultiMC Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "include/basicsettingsobject.h"
#include "include/setting.h"
BasicSettingsObject::BasicSettingsObject(QObject *parent) : SettingsObject(parent)
{
}
void BasicSettingsObject::changeSetting(const Setting &setting, QVariant value)
{
if (contains(setting.id()))
{
if (value.isValid())
config.setValue(setting.configKey(), value);
else
config.remove(setting.configKey());
}
}
QVariant BasicSettingsObject::retrieveValue(const Setting &setting)
{
if (contains(setting.id()))
{
return config.value(setting.configKey());
}
else
{
return QVariant();
}
}

View File

@ -1,63 +0,0 @@
/* Copyright 2013 MultiMC Contributors
*
* Authors: Orochimarufan <orochimarufan.x3@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "include/keyring.h"
#include "osutils.h"
#include "stubkeyring.h"
// system specific keyrings
/*#if defined(OSX)
class OSXKeychain;
#define KEYRING OSXKeychain
#elif defined(LINUX)
class XDGKeyring;
#define KEYRING XDGKeyring
#elif defined(WINDOWS)
class Win32Keystore;
#define KEYRING Win32Keystore
#else
#pragma message Keyrings are not supported on your os. Falling back to the insecure StubKeyring
#endif*/
Keyring *Keyring::instance()
{
if (m_instance == nullptr)
{
#ifdef KEYRING
m_instance = new KEYRING();
if (!m_instance->isValid())
{
qWarning("Could not create SystemKeyring! falling back to StubKeyring.");
m_instance = new StubKeyring();
}
#else
qWarning("Keyrings are not supported on your OS. Fallback StubKeyring is insecure!");
m_instance = new StubKeyring();
#endif
atexit(Keyring::destroy);
}
return m_instance;
}
void Keyring::destroy()
{
delete m_instance;
}
Keyring *Keyring::m_instance;

View File

@ -1,105 +0,0 @@
/* Copyright 2013 MultiMC Contributors
*
* Authors: Orochimarufan <orochimarufan.x3@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stubkeyring.h"
#include <QStringList>
// Scrambling
// this is NOT SAFE, but it's not plain either.
int scrambler = 0x9586309;
QString scramble(QString in_)
{
QByteArray in = in_.toUtf8();
QByteArray out;
for (int i = 0; i < in.length(); i++)
out.append(in.at(i) ^ scrambler);
return QString::fromUtf8(out);
}
inline QString base64(QString in)
{
return QString(in.toUtf8().toBase64());
}
inline QString unbase64(QString in)
{
return QString::fromUtf8(QByteArray::fromBase64(in.toLatin1()));
}
inline QString scramble64(QString in)
{
return base64(scramble(in));
}
inline QString unscramble64(QString in)
{
return scramble(unbase64(in));
}
// StubKeyring implementation
inline QString generateKey(QString service, QString username)
{
return QString("%1/%2").arg(base64(service)).arg(scramble64(username));
}
bool StubKeyring::storePassword(QString service, QString username, QString password)
{
m_settings.setValue(generateKey(service, username), scramble64(password));
return true;
}
QString StubKeyring::getPassword(QString service, QString username)
{
QString key = generateKey(service, username);
if (!m_settings.contains(key))
return QString();
return unscramble64(m_settings.value(key).toString());
}
bool StubKeyring::hasPassword(QString service, QString username)
{
return m_settings.contains(generateKey(service, username));
}
QStringList StubKeyring::getStoredAccounts(QString service)
{
service = base64(service).append('/');
QStringList out;
QStringList in(m_settings.allKeys());
QStringListIterator it(in);
while (it.hasNext())
{
QString c = it.next();
if (c.startsWith(service))
out << unscramble64(c.mid(service.length()));
}
return out;
}
void StubKeyring::removeStoredAccount(QString service, QString username)
{
QString key = generateKey(service, username);
m_settings.remove(key);
}
// FIXME: this needs tweaking/changes for user account level storage
StubKeyring::StubKeyring()
:
// m_settings(QSettings::UserScope, "Orochimarufan", "Keyring")
m_settings("keyring.cfg", QSettings::IniFormat)
{
}

View File

@ -1,47 +0,0 @@
/* Copyright 2013 MultiMC Contributors
*
* Authors: Orochimarufan <orochimarufan.x3@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "include/keyring.h"
#include <QSettings>
class StubKeyring : public Keyring
{
public:
/**
* @brief virtual dtor
*/
virtual ~StubKeyring() {};
virtual bool storePassword(QString service, QString username, QString password);
virtual QString getPassword(QString service, QString username);
virtual bool hasPassword(QString service, QString username);
virtual QStringList getStoredAccounts(QString service);
virtual void removeStoredAccount(QString service, QString username);
private:
friend class Keyring;
explicit StubKeyring();
virtual bool isValid()
{
return true;
}
QSettings m_settings;
};

View File

@ -37,11 +37,11 @@ BaseInstance::BaseInstance(BaseInstancePrivate *d_in, const QString &rootDir,
d->m_settings = settings_obj; d->m_settings = settings_obj;
d->m_rootDir = rootDir; d->m_rootDir = rootDir;
settings().registerSetting(new Setting("name", "Unnamed Instance")); settings().registerSetting("name", "Unnamed Instance");
settings().registerSetting(new Setting("iconKey", "default")); settings().registerSetting("iconKey", "default");
connect(MMC->icons().get(), SIGNAL(iconUpdated(QString)), SLOT(iconUpdated(QString))); connect(MMC->icons().get(), SIGNAL(iconUpdated(QString)), SLOT(iconUpdated(QString)));
settings().registerSetting(new Setting("notes", "")); settings().registerSetting("notes", "");
settings().registerSetting(new Setting("lastLaunchTime", 0)); settings().registerSetting("lastLaunchTime", 0);
/* /*
* custom base jar has no default. it is determined in code... see the accessor methods for * custom base jar has no default. it is determined in code... see the accessor methods for
@ -50,49 +50,37 @@ BaseInstance::BaseInstance(BaseInstancePrivate *d_in, const QString &rootDir,
* for instances that DO NOT have the CustomBaseJar setting (legacy instances), * for instances that DO NOT have the CustomBaseJar setting (legacy instances),
* [.]minecraft/bin/mcbackup.jar is the default base jar * [.]minecraft/bin/mcbackup.jar is the default base jar
*/ */
settings().registerSetting(new Setting("UseCustomBaseJar", true)); settings().registerSetting("UseCustomBaseJar", true);
settings().registerSetting(new Setting("CustomBaseJar", "")); settings().registerSetting("CustomBaseJar", "");
auto globalSettings = MMC->settings(); auto globalSettings = MMC->settings();
// Java Settings // Java Settings
settings().registerSetting(new Setting("OverrideJava", false)); settings().registerSetting("OverrideJava", false);
settings().registerSetting( settings().registerOverride(globalSettings->getSetting("JavaPath"));
new OverrideSetting("JavaPath", globalSettings->getSetting("JavaPath"))); settings().registerOverride(globalSettings->getSetting("JvmArgs"));
settings().registerSetting(
new OverrideSetting("JvmArgs", globalSettings->getSetting("JvmArgs")));
// Custom Commands // Custom Commands
settings().registerSetting(new Setting("OverrideCommands", false)); settings().registerSetting({"OverrideCommands","OverrideLaunchCmd"}, false);
settings().registerSetting(new OverrideSetting( settings().registerOverride(globalSettings->getSetting("PreLaunchCommand"));
"PreLaunchCommand", globalSettings->getSetting("PreLaunchCommand"))); settings().registerOverride(globalSettings->getSetting("PostExitCommand"));
settings().registerSetting(
new OverrideSetting("PostExitCommand", globalSettings->getSetting("PostExitCommand")));
// Window Size // Window Size
settings().registerSetting(new Setting("OverrideWindow", false)); settings().registerSetting("OverrideWindow", false);
settings().registerSetting( settings().registerOverride(globalSettings->getSetting("LaunchMaximized"));
new OverrideSetting("LaunchMaximized", globalSettings->getSetting("LaunchMaximized"))); settings().registerOverride(globalSettings->getSetting("MinecraftWinWidth"));
settings().registerSetting(new OverrideSetting( settings().registerOverride(globalSettings->getSetting("MinecraftWinHeight"));
"MinecraftWinWidth", globalSettings->getSetting("MinecraftWinWidth")));
settings().registerSetting(new OverrideSetting(
"MinecraftWinHeight", globalSettings->getSetting("MinecraftWinHeight")));
// Memory // Memory
settings().registerSetting(new Setting("OverrideMemory", false)); settings().registerSetting("OverrideMemory", false);
settings().registerSetting( settings().registerOverride(globalSettings->getSetting("MinMemAlloc"));
new OverrideSetting("MinMemAlloc", globalSettings->getSetting("MinMemAlloc"))); settings().registerOverride(globalSettings->getSetting("MaxMemAlloc"));
settings().registerSetting( settings().registerOverride(globalSettings->getSetting("PermGen"));
new OverrideSetting("MaxMemAlloc", globalSettings->getSetting("MaxMemAlloc")));
settings().registerSetting(
new OverrideSetting("PermGen", globalSettings->getSetting("PermGen")));
// Console // Console
settings().registerSetting(new Setting("OverrideConsole", false)); settings().registerSetting("OverrideConsole", false);
settings().registerSetting( settings().registerOverride(globalSettings->getSetting("ShowConsole"));
new OverrideSetting("ShowConsole", globalSettings->getSetting("ShowConsole"))); settings().registerOverride(globalSettings->getSetting("AutoCloseConsole"));
settings().registerSetting(new OverrideSetting(
"AutoCloseConsole", globalSettings->getSetting("AutoCloseConsole")));
} }
void BaseInstance::iconUpdated(QString key) void BaseInstance::iconUpdated(QString key)

View File

@ -45,7 +45,7 @@ InstanceFactory::InstLoadError InstanceFactory::loadInstance(BaseInstance *&inst
{ {
auto m_settings = new INISettingsObject(PathCombine(instDir, "instance.cfg")); auto m_settings = new INISettingsObject(PathCombine(instDir, "instance.cfg"));
m_settings->registerSetting(new Setting("InstanceType", "Legacy")); m_settings->registerSetting("InstanceType", "Legacy");
QString inst_type = m_settings->get("InstanceType").toString(); QString inst_type = m_settings->get("InstanceType").toString();
@ -94,7 +94,7 @@ InstanceFactory::InstCreateError InstanceFactory::createInstance(BaseInstance *&
return InstanceFactory::NoSuchVersion; return InstanceFactory::NoSuchVersion;
auto m_settings = new INISettingsObject(PathCombine(instDir, "instance.cfg")); auto m_settings = new INISettingsObject(PathCombine(instDir, "instance.cfg"));
m_settings->registerSetting(new Setting("InstanceType", "Legacy")); m_settings->registerSetting("InstanceType", "Legacy");
if (type == NormalInst) if (type == NormalInst)
{ {
@ -171,7 +171,7 @@ InstanceFactory::InstCreateError InstanceFactory::copyInstance(BaseInstance *&ne
return InstanceFactory::CantCreateDir; return InstanceFactory::CantCreateDir;
} }
auto m_settings = new INISettingsObject(PathCombine(instDir, "instance.cfg")); auto m_settings = new INISettingsObject(PathCombine(instDir, "instance.cfg"));
m_settings->registerSetting(new Setting("InstanceType", "Legacy")); m_settings->registerSetting("InstanceType", "Legacy");
QString inst_type = m_settings->get("InstanceType").toString(); QString inst_type = m_settings->get("InstanceType").toString();
if(inst_type == "OneSixFTB") if(inst_type == "OneSixFTB")

View File

@ -37,11 +37,11 @@ LegacyInstance::LegacyInstance(const QString &rootDir, SettingsObject *settings,
QObject *parent) QObject *parent)
: BaseInstance(new LegacyInstancePrivate(), rootDir, settings, parent) : BaseInstance(new LegacyInstancePrivate(), rootDir, settings, parent)
{ {
settings->registerSetting(new Setting("NeedsRebuild", true)); settings->registerSetting("NeedsRebuild", true);
settings->registerSetting(new Setting("ShouldUpdate", false)); settings->registerSetting("ShouldUpdate", false);
settings->registerSetting(new Setting("JarVersion", "Unknown")); settings->registerSetting("JarVersion", "Unknown");
settings->registerSetting(new Setting("LwjglVersion", "2.9.0")); settings->registerSetting("LwjglVersion", "2.9.0");
settings->registerSetting(new Setting("IntendedJarVersion", "")); settings->registerSetting("IntendedJarVersion", "");
} }
std::shared_ptr<Task> LegacyInstance::doUpdate(bool only_prepare) std::shared_ptr<Task> LegacyInstance::doUpdate(bool only_prepare)

View File

@ -33,8 +33,8 @@ OneSixInstance::OneSixInstance(const QString &rootDir, SettingsObject *setting_o
: BaseInstance(new OneSixInstancePrivate(), rootDir, setting_obj, parent) : BaseInstance(new OneSixInstancePrivate(), rootDir, setting_obj, parent)
{ {
I_D(OneSixInstance); I_D(OneSixInstance);
d->m_settings->registerSetting(new Setting("IntendedVersion", "")); d->m_settings->registerSetting("IntendedVersion", "");
d->m_settings->registerSetting(new Setting("ShouldUpdate", false)); d->m_settings->registerSetting("ShouldUpdate", false);
reloadFullVersion(); reloadFullVersion();
} }

View File

@ -45,7 +45,7 @@ IconList::IconList(QObject *parent) : QAbstractListModel(parent)
auto setting = MMC->settings()->getSetting("IconsDir"); auto setting = MMC->settings()->getSetting("IconsDir");
QString path = setting->get().toString(); QString path = setting->get().toString();
connect(setting, SIGNAL(settingChanged(const Setting &, QVariant)), connect(setting.get(), SIGNAL(settingChanged(const Setting &, QVariant)),
SLOT(settingChanged(const Setting &, QVariant))); SLOT(settingChanged(const Setting &, QVariant)));
directoryChanged(path); directoryChanged(path);
} }
@ -145,7 +145,7 @@ void IconList::fileChanged(const QString &path)
void IconList::settingChanged(const Setting &setting, QVariant value) void IconList::settingChanged(const Setting &setting, QVariant value)
{ {
if(setting.configKey() != "IconsDir") if(setting.id() != "IconsDir")
return; return;
directoryChanged(value.toString()); directoryChanged(value.toString());