X-Git-Url: https://git.quassel-irc.org/?p=quassel.git;a=blobdiff_plain;f=src%2Fcommon%2Fquassel.cpp;h=7ee7915e905a52608483faad752d02de1c0cb3b5;hp=62b8b3a8a4a19beb49309ff3aeeeec8b5bf704a9;hb=f9e037ea6a0b946c84db62d324996d8f878c1efb;hpb=12fbdede1ac2d35359eab076ccecb203c04139c4 diff --git a/src/common/quassel.cpp b/src/common/quassel.cpp index 62b8b3a8..7ee7915e 100644 --- a/src/common/quassel.cpp +++ b/src/common/quassel.cpp @@ -1,5 +1,5 @@ /*************************************************************************** - * Copyright (C) 2005-2013 by the Quassel Project * + * Copyright (C) 2005-2018 by the Quassel Project * * devel@quassel-irc.org * * * * This program is free software; you can redistribute it and/or modify * @@ -20,100 +20,96 @@ #include "quassel.h" +#include #include + #include -#if !defined Q_OS_WIN32 && !defined Q_OS_MAC +#if !defined Q_OS_WIN && !defined Q_OS_MAC +# include +# include # include #endif #include #include +#include #include +#include #include +#include #include #include -#include +#include -#include "message.h" +#include "bufferinfo.h" #include "identity.h" +#include "logger.h" +#include "message.h" #include "network.h" -#include "bufferinfo.h" -#include "types.h" +#include "peer.h" +#include "protocol.h" #include "syncableobject.h" -#include "logger.h" +#include "types.h" -Quassel::BuildInfo Quassel::_buildInfo; -AbstractCliParser *Quassel::_cliParser = 0; -Quassel::RunMode Quassel::_runMode; -QString Quassel::_configDirPath; -QString Quassel::_translationDirPath; -QStringList Quassel::_dataDirPaths; -bool Quassel::_initialized = false; -bool Quassel::DEBUG = false; -QString Quassel::_coreDumpFileName; -Quassel *Quassel::_instance = 0; -bool Quassel::_handleCrashes = true; -Quassel::LogLevel Quassel::_logLevel = InfoLevel; -QFile *Quassel::_logFile = 0; -bool Quassel::_logToSyslog = false; +#include "../../version.h" -Quassel::Quassel() +Quassel *Quassel::instance() { - Q_ASSERT(!_instance); - _instance = this; - - // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel. - signal(SIGTERM, handleSignal); - signal(SIGINT, handleSignal); + static Quassel instance; + return &instance; } -Quassel::~Quassel() +Quassel::Quassel() { - if (logFile()) { - logFile()->close(); - logFile()->deleteLater(); - } - delete _cliParser; + // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel. + signal(SIGTERM, handleSignal); + signal(SIGINT, handleSignal); +#ifndef Q_OS_WIN + // SIGHUP is used to reload configuration (i.e. SSL certificates) + // Windows does not support SIGHUP + signal(SIGHUP, handleSignal); +#endif } bool Quassel::init() { - if (_initialized) + if (instance()->_initialized) return true; // allow multiple invocations because of MonolithicApplication - if (_handleCrashes) { + if (instance()->_handleCrashes) { // we have crashhandler for win32 and unix (based on execinfo). -#if defined(Q_OS_WIN32) || defined(HAVE_EXECINFO) -# ifndef Q_OS_WIN32 +#if defined(Q_OS_WIN) || defined(HAVE_EXECINFO) +# ifndef Q_OS_WIN // we only handle crashes ourselves if coredumps are disabled struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit)); int rc = getrlimit(RLIMIT_CORE, limit); if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) { -# endif /* Q_OS_WIN32 */ +# endif /* Q_OS_WIN */ signal(SIGABRT, handleSignal); signal(SIGSEGV, handleSignal); -# ifndef Q_OS_WIN32 +# ifndef Q_OS_WIN signal(SIGBUS, handleSignal); } free(limit); -# endif /* Q_OS_WIN32 */ -#endif /* Q_OS_WIN32 || HAVE_EXECINFO */ +# endif /* Q_OS_WIN */ +#endif /* Q_OS_WIN || HAVE_EXECINFO */ } - _initialized = true; + instance()->_initialized = true; qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime())); - registerMetaTypes(); + instance()->setupEnvironment(); + instance()->registerMetaTypes(); Network::setDefaultCodecForServer("ISO-8859-1"); Network::setDefaultCodecForEncoding("UTF-8"); Network::setDefaultCodecForDecoding("ISO-8859-15"); if (isOptionSet("help")) { - cliParser()->usage(); + instance()->_cliParser->usage(); return false; } @@ -122,40 +118,86 @@ bool Quassel::init() return false; } - DEBUG = isOptionSet("debug"); - - // set up logging - if (Quassel::runMode() != Quassel::ClientOnly) { - if (isOptionSet("loglevel")) { - QString level = optionValue("loglevel"); - - if (level == "Debug") _logLevel = DebugLevel; - else if (level == "Info") _logLevel = InfoLevel; - else if (level == "Warning") _logLevel = WarningLevel; - else if (level == "Error") _logLevel = ErrorLevel; + // Set up logging + if (isOptionSet("loglevel")) { + QString level = optionValue("loglevel").toLower(); + + if (level == "debug") + setLogLevel(DebugLevel); + else if (level == "info") + setLogLevel(InfoLevel); + else if (level == "warning") + setLogLevel(WarningLevel); + else if (level == "error") + setLogLevel(ErrorLevel); + else { + qWarning() << qPrintable(tr("Invalid log level %1; supported are Debug|Info|Warning|Error").arg(level)); + return false; } + } - QString logfilename = optionValue("logfile"); - if (!logfilename.isEmpty()) { - _logFile = new QFile(logfilename); - if (!_logFile->open(QIODevice::Append | QIODevice::Text)) { - qWarning() << "Could not open log file" << logfilename << ":" << _logFile->errorString(); - _logFile->deleteLater(); - _logFile = 0; - } + QString logfilename = optionValue("logfile"); + if (!logfilename.isEmpty()) { + instance()->_logFile.reset(new QFile{logfilename}); + if (!logFile()->open(QIODevice::Append | QIODevice::Text)) { + qWarning() << qPrintable(tr("Could not open log file \"%1\": %2").arg(logfilename, logFile()->errorString())); + instance()->_logFile.reset(); } + } #ifdef HAVE_SYSLOG - _logToSyslog = isOptionSet("syslog"); + instance()->_logToSyslog = isOptionSet("syslog"); +#endif + +#if QT_VERSION < 0x050000 + qInstallMsgHandler(Logger::logMessage); +#else + qInstallMessageHandler(Logger::logMessage); #endif - } return true; } +void Quassel::destroy() +{ + if (logFile()) { + logFile()->close(); + instance()->_logFile.reset(); + } +} + + +void Quassel::registerQuitHandler(QuitHandler handler) +{ + instance()->_quitHandlers.emplace_back(std::move(handler)); +} + void Quassel::quit() { - QCoreApplication::quit(); + if (_quitHandlers.empty()) { + QCoreApplication::quit(); + } + else { + for (auto &&handler : _quitHandlers) { + handler(); + } + } +} + + +void Quassel::registerReloadHandler(ReloadHandler handler) +{ + instance()->_reloadHandlers.emplace_back(std::move(handler)); +} + + +bool Quassel::reloadConfig() +{ + bool result{true}; + for (auto &&handler : _reloadHandlers) { + result = result && handler(); + } + return result; } @@ -186,6 +228,9 @@ void Quassel::registerMetaTypes() qRegisterMetaType("MsgId"); qRegisterMetaType("QHostAddress"); + qRegisterMetaTypeStreamOperators("QHostAddress"); + qRegisterMetaType("QUuid"); + qRegisterMetaTypeStreamOperators("QUuid"); qRegisterMetaTypeStreamOperators("IdentityId"); qRegisterMetaTypeStreamOperators("BufferId"); @@ -194,6 +239,10 @@ void Quassel::registerMetaTypes() qRegisterMetaTypeStreamOperators("AccountId"); qRegisterMetaTypeStreamOperators("MsgId"); + qRegisterMetaType("Protocol::SessionState"); + qRegisterMetaType("PeerPtr"); + qRegisterMetaTypeStreamOperators("PeerPtr"); + // Versions of Qt prior to 4.7 didn't define QVariant as a meta type if (!QMetaType::type("QVariant")) { qRegisterMetaType("QVariant"); @@ -202,63 +251,113 @@ void Quassel::registerMetaTypes() } -void Quassel::setupBuildInfo(const QString &generated) +void Quassel::setupEnvironment() +{ + // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This + // is, for example, used by Qt for finding icons and other things. In case Quassel is installed in a non-standard + // prefix (or run from the build directory), it makes sense to add this to XDG_DATA_DIRS so we don't have to + // hack extra search paths into various places. +#ifdef Q_OS_UNIX + QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS")); + if (xdgDataVar.isEmpty()) + xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults + + QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts); + + // Add our install prefix (if we're not in a bindir, this just adds the current workdir) + QString appDir = QCoreApplication::applicationDirPath(); + int binpos = appDir.lastIndexOf("/bin"); + if (binpos >= 0) { + appDir.replace(binpos, 4, "/share"); + xdgDirs.append(appDir); + // Also append apps/quassel, this is only for QIconLoader to find icons there + xdgDirs.append(appDir + "/apps/quassel"); + } else + xdgDirs.append(appDir); // build directory is always the last fallback + + xdgDirs.removeDuplicates(); + + qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":"))); +#endif +} + + +void Quassel::setupBuildInfo() { - _buildInfo.applicationName = "Quassel IRC"; - _buildInfo.coreApplicationName = "quasselcore"; - _buildInfo.clientApplicationName = "quasselclient"; - _buildInfo.organizationName = "Quassel Project"; - _buildInfo.organizationDomain = "quassel-irc.org"; + BuildInfo buildInfo; + buildInfo.applicationName = "quassel"; + buildInfo.coreApplicationName = "quasselcore"; + buildInfo.clientApplicationName = "quasselclient"; + buildInfo.organizationName = "Quassel Project"; + buildInfo.organizationDomain = "quassel-irc.org"; + + buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed + + buildInfo.baseVersion = QUASSEL_VERSION_STRING; + buildInfo.generatedVersion = GIT_DESCRIBE; + + // Check if we got a commit hash + if (!QString(GIT_HEAD).isEmpty()) { + buildInfo.commitHash = GIT_HEAD; + QDateTime date; +#if QT_VERSION >= 0x050800 + date.setSecsSinceEpoch(GIT_COMMIT_DATE); +#else + // toSecsSinceEpoch() was added in Qt 5.8. Manually downconvert to seconds for now. + // See https://doc.qt.io/qt-5/qdatetime.html#toMSecsSinceEpoch + // Warning generated if not converting the 1000 to a qint64 first. + date.setMSecsSinceEpoch(GIT_COMMIT_DATE * (qint64)1000); +#endif + buildInfo.commitDate = date.toString(); + } + else if (!QString(DIST_HASH).contains("Format")) { + buildInfo.commitHash = DIST_HASH; + buildInfo.commitDate = QString(DIST_DATE); + } - QStringList gen = generated.split(','); - Q_ASSERT(gen.count() == 10); - _buildInfo.baseVersion = gen[0]; - _buildInfo.generatedVersion = gen[1]; - _buildInfo.isSourceDirty = !gen[2].isEmpty(); - _buildInfo.commitHash = gen[3]; - _buildInfo.commitDate = gen[4].toUInt(); - _buildInfo.protocolVersion = gen[5].toUInt(); - _buildInfo.clientNeedsProtocol = gen[6].toUInt(); - _buildInfo.coreNeedsProtocol = gen[7].toUInt(); - _buildInfo.buildDate = QString("%1 %2").arg(gen[8], gen[9]); // create a nice version string - if (_buildInfo.generatedVersion.isEmpty()) { - if (!_buildInfo.commitHash.isEmpty()) { + if (buildInfo.generatedVersion.isEmpty()) { + if (!buildInfo.commitHash.isEmpty()) { // dist version - _buildInfo.plainVersionString = QString("v%1 (dist-%2)") - .arg(_buildInfo.baseVersion) - .arg(_buildInfo.commitHash.left(7)); - _buildInfo.fancyVersionString = QString("v%1 (dist-%2)") - .arg(_buildInfo.baseVersion) - .arg(_buildInfo.commitHash.left(7)) - .arg(_buildInfo.commitHash); + buildInfo.plainVersionString = QString{"v%1 (dist-%2)"} + .arg(buildInfo.baseVersion) + .arg(buildInfo.commitHash.left(7)); + buildInfo.fancyVersionString = QString{"v%1 (dist-%2)"} + .arg(buildInfo.baseVersion) + .arg(buildInfo.commitHash.left(7)) + .arg(buildInfo.commitHash); } else { // we only have a base version :( - _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion); + buildInfo.plainVersionString = QString{"v%1 (unknown revision)"}.arg(buildInfo.baseVersion); } } else { // analyze what we got from git-describe - QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$"); - if (rx.exactMatch(_buildInfo.generatedVersion)) { - QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2)); - _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)") - .arg(_buildInfo.baseVersion, distance, rx.cap(3)) - .arg(_buildInfo.isSourceDirty ? "*" : ""); - if (!_buildInfo.commitHash.isEmpty()) { - _buildInfo.fancyVersionString = QString("v%1 (%2git-%3%4)") - .arg(_buildInfo.baseVersion, distance, rx.cap(3)) - .arg(_buildInfo.isSourceDirty ? "*" : "") - .arg(_buildInfo.commitHash); + static const QRegExp rx{"(.*)-(\\d+)-g([0-9a-f]+)(-dirty)?$"}; + if (rx.exactMatch(buildInfo.generatedVersion)) { + QString distance = rx.cap(2) == "0" ? QString{} : QString{"%1+%2 "}.arg(rx.cap(1), rx.cap(2)); + buildInfo.plainVersionString = QString{"v%1 (%2git-%3%4)"}.arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4)); + if (!buildInfo.commitHash.isEmpty()) { + buildInfo.fancyVersionString = QString{"v%1 (%2git-%3%4)"} + .arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), buildInfo.commitHash); } } else { - _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion); + buildInfo.plainVersionString = QString{"v%1 (invalid revision)"}.arg(buildInfo.baseVersion); } } - if (_buildInfo.fancyVersionString.isEmpty()) - _buildInfo.fancyVersionString = _buildInfo.plainVersionString; + if (buildInfo.fancyVersionString.isEmpty()) { + buildInfo.fancyVersionString = buildInfo.plainVersionString; + } + + instance()->_buildInfo = std::move(buildInfo); +} + + +const Quassel::BuildInfo &Quassel::buildInfo() +{ + return instance()->_buildInfo; } @@ -269,31 +368,96 @@ void Quassel::handleSignal(int sig) case SIGTERM: case SIGINT: qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig))); - if (_instance) - _instance->quit(); - else - QCoreApplication::quit(); + instance()->quit(); + break; +#ifndef Q_OS_WIN +// Windows does not support SIGHUP + case SIGHUP: + // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for + // graceful reloading of processes. + quInfo() << "Caught signal" << SIGHUP << "- reloading configuration"; + if (instance()->reloadConfig()) { + quInfo() << "Successfully reloaded configuration"; + } break; +#endif case SIGABRT: case SIGSEGV: -#ifndef Q_OS_WIN32 +#ifndef Q_OS_WIN case SIGBUS: #endif - logBacktrace(coreDumpFileName()); + instance()->logBacktrace(instance()->coreDumpFileName()); exit(EXIT_FAILURE); - break; default: - break; + ; } } +void Quassel::disableCrashHandler() +{ + instance()->_handleCrashes = false; +} + + +Quassel::RunMode Quassel::runMode() { + return instance()->_runMode; +} + + +void Quassel::setRunMode(RunMode runMode) +{ + instance()->_runMode = runMode; +} + + +void Quassel::setCliParser(std::shared_ptr parser) +{ + instance()->_cliParser = std::move(parser); +} + + +QString Quassel::optionValue(const QString &key) +{ + return instance()->_cliParser ? instance()->_cliParser->value(key) : QString{}; +} + + +bool Quassel::isOptionSet(const QString &key) +{ + return instance()->_cliParser ? instance()->_cliParser->isSet(key) : false; +} + + +Quassel::LogLevel Quassel::logLevel() +{ + return instance()->_logLevel; +} + + +void Quassel::setLogLevel(LogLevel logLevel) +{ + instance()->_logLevel = logLevel; +} + + +QFile *Quassel::logFile() { + return instance()->_logFile.get(); +} + + +bool Quassel::logToSyslog() +{ + return instance()->_logToSyslog; +} + + void Quassel::logFatalMessage(const char *msg) { #ifdef Q_OS_MAC Q_UNUSED(msg) #else - QFile dumpFile(coreDumpFileName()); + QFile dumpFile(instance()->coreDumpFileName()); dumpFile.open(QIODevice::Append); QTextStream dumpStream(&dumpFile); @@ -304,16 +468,6 @@ void Quassel::logFatalMessage(const char *msg) } -Quassel::Features Quassel::features() -{ - Features feats = 0; - for (int i = 1; i <= NumFeatures; i <<= 1) - feats |= (Feature)i; - - return feats; -} - - const QString &Quassel::coreDumpFileName() { if (_coreDumpFileName.isEmpty()) { @@ -333,23 +487,24 @@ const QString &Quassel::coreDumpFileName() QString Quassel::configDirPath() { - if (!_configDirPath.isEmpty()) - return _configDirPath; + if (!instance()->_configDirPath.isEmpty()) + return instance()->_configDirPath; - if (Quassel::isOptionSet("datadir")) { + QString path; + if (isOptionSet("datadir")) { qWarning() << "Obsolete option --datadir used!"; - _configDirPath = Quassel::optionValue("datadir"); + path = Quassel::optionValue("datadir"); } - else if (Quassel::isOptionSet("configdir")) { - _configDirPath = Quassel::optionValue("configdir"); + else if (isOptionSet("configdir")) { + path = Quassel::optionValue("configdir"); } else { -#ifdef Q_WS_MAC +#ifdef Q_OS_MAC // On Mac, the path is always the same - _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/"; + path = QDir::homePath() + "/Library/Application Support/Quassel/"; #else // We abuse QSettings to find us a sensible path on the other platforms -# ifdef Q_WS_WIN +# ifdef Q_OS_WIN // don't use the registry QSettings::Format format = QSettings::IniFormat; # else @@ -357,70 +512,85 @@ QString Quassel::configDirPath() # endif QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName); QFileInfo fileInfo(s.fileName()); - _configDirPath = fileInfo.dir().absolutePath(); -#endif /* Q_WS_MAC */ + path = fileInfo.dir().absolutePath(); +#endif /* Q_OS_MAC */ } - if (!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/')) - _configDirPath += QDir::separator(); + if (!path.endsWith(QDir::separator()) && !path.endsWith('/')) + path += QDir::separator(); - QDir qDir(_configDirPath); - if (!qDir.exists(_configDirPath)) { - if (!qDir.mkpath(_configDirPath)) { + QDir qDir{path}; + if (!qDir.exists(path)) { + if (!qDir.mkpath(path)) { qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath()); - return QString(); + return {}; } } - return _configDirPath; + instance()->_configDirPath = path; + + return path; +} + + +void Quassel::setDataDirPaths(const QStringList &paths) { + instance()->_dataDirPaths = paths; } QStringList Quassel::dataDirPaths() { - return _dataDirPaths; + return instance()->_dataDirPaths; } -QStringList Quassel::findDataDirPaths() const +QStringList Quassel::findDataDirPaths() { - QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts); - - if (!dataDirNames.isEmpty()) { - for (int i = 0; i < dataDirNames.count(); i++) - dataDirNames[i].append("/apps/quassel/"); - } - else { - // Provide a fallback -#ifdef Q_OS_WIN32 - dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/" - << qgetenv("APPDATA") + QCoreApplication::organizationDomain() - << QCoreApplication::applicationDirPath(); - } -#elif defined Q_WS_MAC - dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/" - << QCoreApplication::applicationDirPath(); - } + // TODO Qt5 + // We don't use QStandardPaths for now, as we still need to provide fallbacks for Qt4 and + // want to stay consistent. + + QStringList dataDirNames; +#ifdef Q_OS_WIN + dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/" + << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + << QCoreApplication::applicationDirPath(); +#elif defined Q_OS_MAC + dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/" + << QCoreApplication::applicationDirPath(); #else - dataDirNames.append("/usr/share/apps/quassel/"); - } - // on UNIX, we always check our install prefix - QString appDir = QCoreApplication::applicationDirPath(); - int binpos = appDir.lastIndexOf("/bin"); - if (binpos >= 0) { - appDir.replace(binpos, 4, "/share"); - appDir.append("/apps/quassel/"); - if (!dataDirNames.contains(appDir)) - dataDirNames.append(appDir); - } + // Linux et al + + // XDG_DATA_HOME is the location for users to override system-installed files, usually in .local/share + // This should thus come first. + QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME")); + if (xdgDataHome.isEmpty()) + xdgDataHome = QDir::homePath() + QLatin1String("/.local/share"); + dataDirNames << xdgDataHome; + + // Now whatever is configured through XDG_DATA_DIRS + QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS")); + if (xdgDataDirs.isEmpty()) + dataDirNames << "/usr/local/share" << "/usr/share"; + else + dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts); + + // Just in case, also check our install prefix + dataDirNames << QCoreApplication::applicationDirPath() + "/../share"; + + // Normalize and append our application name + for (int i = 0; i < dataDirNames.count(); i++) + dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/"; + #endif - // add resource path and workdir just in case - dataDirNames << QCoreApplication::applicationDirPath() + "/data/" - << ":/data/"; + // Add resource path and workdir just in case. + // Workdir should have precedence + dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/"); + dataDirNames.append(":/data/"); - // append trailing '/' and check for existence - QStringList::Iterator iter = dataDirNames.begin(); + // Append trailing '/' and check for existence + auto iter = dataDirNames.begin(); while (iter != dataDirNames.end()) { if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/')) iter->append(QDir::separator()); @@ -430,6 +600,8 @@ QStringList Quassel::findDataDirPaths() const ++iter; } + dataDirNames.removeDuplicates(); + return dataDirNames; } @@ -457,19 +629,19 @@ QStringList Quassel::scriptDirPaths() QString Quassel::translationDirPath() { - if (_translationDirPath.isEmpty()) { + if (instance()->_translationDirPath.isEmpty()) { // We support only one translation dir; fallback mechanisms wouldn't work else. // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered. foreach(const QString &dir, dataDirPaths()) { if (QFile::exists(dir + "translations/")) { - _translationDirPath = dir + "translations/"; + instance()->_translationDirPath = dir + "translations/"; break; } } - if (_translationDirPath.isEmpty()) - _translationDirPath = ":/i18n/"; + if (instance()->_translationDirPath.isEmpty()) + instance()->_translationDirPath = ":/i18n/"; } - return _translationDirPath; + return instance()->_translationDirPath; } @@ -495,7 +667,7 @@ void Quassel::loadTranslation(const QLocale &locale) quasselTranslator->setObjectName("QuasselTr"); qApp->installTranslator(quasselTranslator); -#if QT_VERSION >= 0x040800 +#if QT_VERSION >= 0x040800 && !defined Q_OS_MAC bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath()); if (!success) qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); @@ -507,3 +679,99 @@ void Quassel::loadTranslation(const QLocale &locale) quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath()); #endif } + + +// ---- Quassel::Features --------------------------------------------------------------------------------------------- + +Quassel::Features::Features() +{ + QStringList features; + + // TODO Qt5: Use QMetaEnum::fromType() + auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature")); + _features.resize(featureEnum.keyCount(), true); // enable all known features to true +} + + +Quassel::Features::Features(const QStringList &features, LegacyFeatures legacyFeatures) +{ + // TODO Qt5: Use QMetaEnum::fromType() + auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature")); + _features.resize(featureEnum.keyCount(), false); + + for (auto &&feature : features) { + int i = featureEnum.keyToValue(qPrintable(feature)); + if (i >= 0) { + _features[i] = true; + } + else { + _unknownFeatures << feature; + } + } + + if (legacyFeatures) { + // TODO Qt5: Use QMetaEnum::fromType() + auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature")); + for (quint32 mask = 0x0001; mask <= 0x8000; mask <<=1) { + if (static_cast(legacyFeatures) & mask) { + int i = featureEnum.keyToValue(legacyFeatureEnum.valueToKey(mask)); + if (i >= 0) { + _features[i] = true; + } + } + } + } +} + + +bool Quassel::Features::isEnabled(Feature feature) const +{ + size_t i = static_cast(feature); + return i < _features.size() ? _features[i] : false; +} + + +QStringList Quassel::Features::toStringList(bool enabled) const +{ + // Check if any feature is enabled + if (!enabled && std::all_of(_features.cbegin(), _features.cend(), [](bool feature) { return !feature; })) { + return QStringList{} << "NoFeatures"; + } + + QStringList result; + + // TODO Qt5: Use QMetaEnum::fromType() + auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature")); + for (quint32 i = 0; i < _features.size(); ++i) { + if (_features[i] == enabled) { + result << featureEnum.key(i); + } + } + return result; +} + + +Quassel::LegacyFeatures Quassel::Features::toLegacyFeatures() const +{ + // TODO Qt5: Use LegacyFeatures (flag operators for enum classes not supported in Qt4) + quint32 result{0}; + // TODO Qt5: Use QMetaEnum::fromType() + auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature")); + auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature")); + + for (quint32 i = 0; i < _features.size(); ++i) { + if (_features[i]) { + int v = legacyFeatureEnum.keyToValue(featureEnum.key(i)); + if (v >= 0) { + result |= v; + } + } + } + return static_cast(result); +} + + +QStringList Quassel::Features::unknownFeatures() const +{ + return _unknownFeatures; +}