common: Use the Singleton mixin for the Quassel instance
[quassel.git] / src / common / quassel.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "quassel.h"
22
23 #include <algorithm>
24 #include <iostream>
25
26 #include <signal.h>
27 #if !defined Q_OS_WIN && !defined Q_OS_MAC
28 #  include <sys/types.h>
29 #  include <sys/time.h>
30 #  include <sys/resource.h>
31 #endif
32
33 #include <QCoreApplication>
34 #include <QDateTime>
35 #include <QDir>
36 #include <QFileInfo>
37 #include <QHostAddress>
38 #include <QLibraryInfo>
39 #include <QMetaEnum>
40 #include <QSettings>
41 #include <QTranslator>
42 #include <QUuid>
43
44 #include "bufferinfo.h"
45 #include "identity.h"
46 #include "logger.h"
47 #include "logmessage.h"
48 #include "message.h"
49 #include "network.h"
50 #include "peer.h"
51 #include "protocol.h"
52 #include "syncableobject.h"
53 #include "types.h"
54
55 #include "../../version.h"
56
57 Quassel::Quassel()
58     : Singleton<Quassel>{this}
59     , _logger{new Logger{this}}
60 {
61 }
62
63
64 bool Quassel::init()
65 {
66     if (instance()->_initialized)
67         return true;  // allow multiple invocations because of MonolithicApplication
68
69     // Setup signal handling
70     // TODO: Don't use unsafe methods, see handleSignal()
71
72     // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
73     signal(SIGTERM, handleSignal);
74     signal(SIGINT, handleSignal);
75 #ifndef Q_OS_WIN
76     // SIGHUP is used to reload configuration (i.e. SSL certificates)
77     // Windows does not support SIGHUP
78     signal(SIGHUP, handleSignal);
79 #endif
80
81     if (instance()->_handleCrashes) {
82         // we have crashhandler for win32 and unix (based on execinfo).
83 #if defined(Q_OS_WIN) || defined(HAVE_EXECINFO)
84 # ifndef Q_OS_WIN
85         // we only handle crashes ourselves if coredumps are disabled
86         struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit));
87         int rc = getrlimit(RLIMIT_CORE, limit);
88
89         if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
90 # endif /* Q_OS_WIN */
91             signal(SIGABRT, handleSignal);
92             signal(SIGSEGV, handleSignal);
93 # ifndef Q_OS_WIN
94             signal(SIGBUS, handleSignal);
95         }
96         free(limit);
97 # endif /* Q_OS_WIN */
98 #endif /* Q_OS_WIN || HAVE_EXECINFO */
99     }
100
101     instance()->_initialized = true;
102     qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
103
104     instance()->setupEnvironment();
105     instance()->registerMetaTypes();
106
107     Network::setDefaultCodecForServer("UTF-8");
108     Network::setDefaultCodecForEncoding("UTF-8");
109     Network::setDefaultCodecForDecoding("ISO-8859-15");
110
111     if (isOptionSet("help")) {
112         instance()->_cliParser->usage();
113         return false;
114     }
115
116     if (isOptionSet("version")) {
117         std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
118         return false;
119     }
120
121     // Don't keep a debug log on the core
122     return instance()->logger()->setup(runMode() != RunMode::CoreOnly);
123 }
124
125
126 Logger *Quassel::logger() const
127 {
128     return _logger;
129 }
130
131
132 void Quassel::registerQuitHandler(QuitHandler handler)
133 {
134     instance()->_quitHandlers.emplace_back(std::move(handler));
135 }
136
137 void Quassel::quit()
138 {
139     if (_quitHandlers.empty()) {
140         QCoreApplication::quit();
141     }
142     else {
143         for (auto &&handler : _quitHandlers) {
144             handler();
145         }
146     }
147 }
148
149
150 void Quassel::registerReloadHandler(ReloadHandler handler)
151 {
152     instance()->_reloadHandlers.emplace_back(std::move(handler));
153 }
154
155
156 bool Quassel::reloadConfig()
157 {
158     bool result{true};
159     for (auto &&handler : _reloadHandlers) {
160         result = result && handler();
161     }
162     return result;
163 }
164
165
166 //! Register our custom types with Qt's Meta Object System.
167 /**  This makes them available for QVariant and in signals/slots, among other things.
168 *
169 */
170 void Quassel::registerMetaTypes()
171 {
172     // Complex types
173     qRegisterMetaType<Message>("Message");
174     qRegisterMetaType<BufferInfo>("BufferInfo");
175     qRegisterMetaType<NetworkInfo>("NetworkInfo");
176     qRegisterMetaType<Network::Server>("Network::Server");
177     qRegisterMetaType<Identity>("Identity");
178
179     qRegisterMetaTypeStreamOperators<Message>("Message");
180     qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
181     qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
182     qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
183     qRegisterMetaTypeStreamOperators<Identity>("Identity");
184
185     qRegisterMetaType<IdentityId>("IdentityId");
186     qRegisterMetaType<BufferId>("BufferId");
187     qRegisterMetaType<NetworkId>("NetworkId");
188     qRegisterMetaType<UserId>("UserId");
189     qRegisterMetaType<AccountId>("AccountId");
190     qRegisterMetaType<MsgId>("MsgId");
191
192     qRegisterMetaType<QHostAddress>("QHostAddress");
193     qRegisterMetaTypeStreamOperators<QHostAddress>("QHostAddress");
194     qRegisterMetaType<QUuid>("QUuid");
195     qRegisterMetaTypeStreamOperators<QUuid>("QUuid");
196
197     qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
198     qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
199     qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
200     qRegisterMetaTypeStreamOperators<UserId>("UserId");
201     qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
202     qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
203
204     qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
205     qRegisterMetaType<PeerPtr>("PeerPtr");
206     qRegisterMetaTypeStreamOperators<PeerPtr>("PeerPtr");
207
208     // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
209     if (!QMetaType::type("QVariant")) {
210         qRegisterMetaType<QVariant>("QVariant");
211         qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
212     }
213 }
214
215
216 void Quassel::setupEnvironment()
217 {
218     // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This
219     // is, for example, used by Qt for finding icons and other things. In case Quassel is installed in a non-standard
220     // prefix (or run from the build directory), it makes sense to add this to XDG_DATA_DIRS so we don't have to
221     // hack extra search paths into various places.
222 #ifdef Q_OS_UNIX
223     QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
224     if (xdgDataVar.isEmpty())
225         xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
226
227     QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
228
229     // Add our install prefix (if we're not in a bindir, this just adds the current workdir)
230     QString appDir = QCoreApplication::applicationDirPath();
231     int binpos = appDir.lastIndexOf("/bin");
232     if (binpos >= 0) {
233         appDir.replace(binpos, 4, "/share");
234         xdgDirs.append(appDir);
235         // Also append apps/quassel, this is only for QIconLoader to find icons there
236         xdgDirs.append(appDir + "/apps/quassel");
237     } else
238         xdgDirs.append(appDir);  // build directory is always the last fallback
239
240     xdgDirs.removeDuplicates();
241
242     qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
243 #endif
244 }
245
246
247 void Quassel::setupBuildInfo()
248 {
249     BuildInfo buildInfo;
250     buildInfo.applicationName = "quassel";
251     buildInfo.coreApplicationName = "quasselcore";
252     buildInfo.clientApplicationName = "quasselclient";
253     buildInfo.organizationName = "Quassel Project";
254     buildInfo.organizationDomain = "quassel-irc.org";
255
256     buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
257
258     buildInfo.baseVersion = QUASSEL_VERSION_STRING;
259     buildInfo.generatedVersion = GIT_DESCRIBE;
260
261     // Check if we got a commit hash
262     if (!QString(GIT_HEAD).isEmpty()) {
263         buildInfo.commitHash = GIT_HEAD;
264         // Set to Unix epoch, wrapped as a string for backwards-compatibility
265         buildInfo.commitDate = QString::number(GIT_COMMIT_DATE);
266     }
267     else if (!QString(DIST_HASH).contains("Format")) {
268         buildInfo.commitHash = DIST_HASH;
269         // Leave as Unix epoch if set as Unix epoch, but don't force this for
270         // backwards-compatibility with existing packaging/release tools that might set strings.
271         buildInfo.commitDate = QString(DIST_DATE);
272     }
273
274     // create a nice version string
275     if (buildInfo.generatedVersion.isEmpty()) {
276         if (!buildInfo.commitHash.isEmpty()) {
277             // dist version
278             buildInfo.plainVersionString = QString{"v%1 (dist-%2)"}
279                                                .arg(buildInfo.baseVersion)
280                                                .arg(buildInfo.commitHash.left(7));
281             buildInfo.fancyVersionString = QString{"v%1 (dist-<a href=\"https://github.com/quassel/quassel/commit/%3\">%2</a>)"}
282                                                .arg(buildInfo.baseVersion)
283                                                .arg(buildInfo.commitHash.left(7))
284                                                .arg(buildInfo.commitHash);
285         }
286         else {
287             // we only have a base version :(
288             buildInfo.plainVersionString = QString{"v%1 (unknown revision)"}.arg(buildInfo.baseVersion);
289         }
290     }
291     else {
292         // analyze what we got from git-describe
293         static const QRegExp rx{"(.*)-(\\d+)-g([0-9a-f]+)(-dirty)?$"};
294         if (rx.exactMatch(buildInfo.generatedVersion)) {
295             QString distance = rx.cap(2) == "0" ? QString{} : QString{"%1+%2 "}.arg(rx.cap(1), rx.cap(2));
296             buildInfo.plainVersionString = QString{"v%1 (%2git-%3%4)"}.arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4));
297             if (!buildInfo.commitHash.isEmpty()) {
298                 buildInfo.fancyVersionString = QString{"v%1 (%2git-<a href=\"https://github.com/quassel/quassel/commit/%5\">%3</a>%4)"}
299                                                    .arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), buildInfo.commitHash);
300             }
301         }
302         else {
303             buildInfo.plainVersionString = QString{"v%1 (invalid revision)"}.arg(buildInfo.baseVersion);
304         }
305     }
306     if (buildInfo.fancyVersionString.isEmpty()) {
307         buildInfo.fancyVersionString = buildInfo.plainVersionString;
308     }
309
310     instance()->_buildInfo = std::move(buildInfo);
311 }
312
313
314 const Quassel::BuildInfo &Quassel::buildInfo()
315 {
316     return instance()->_buildInfo;
317 }
318
319
320 //! Signal handler for graceful shutdown.
321 //! @todo: Ensure this doesn't use unsafe methods (it does currently)
322 //!        cf. QSocketNotifier, UnixSignalWatcher
323 void Quassel::handleSignal(int sig)
324 {
325     switch (sig) {
326     case SIGTERM:
327     case SIGINT:
328         qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
329         instance()->quit();
330         break;
331 #ifndef Q_OS_WIN
332 // Windows does not support SIGHUP
333     case SIGHUP:
334         // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for
335         // graceful reloading of processes.
336         quInfo() << "Caught signal" << SIGHUP << "- reloading configuration";
337         if (instance()->reloadConfig()) {
338             quInfo() << "Successfully reloaded configuration";
339         }
340         break;
341 #endif
342     case SIGABRT:
343     case SIGSEGV:
344 #ifndef Q_OS_WIN
345     case SIGBUS:
346 #endif
347         instance()->logBacktrace(instance()->coreDumpFileName());
348         exit(EXIT_FAILURE);
349     default:
350         ;
351     }
352 }
353
354
355 void Quassel::disableCrashHandler()
356 {
357     instance()->_handleCrashes = false;
358 }
359
360
361 Quassel::RunMode Quassel::runMode() {
362     return instance()->_runMode;
363 }
364
365
366 void Quassel::setRunMode(RunMode runMode)
367 {
368     instance()->_runMode = runMode;
369 }
370
371
372 void Quassel::setCliParser(std::shared_ptr<AbstractCliParser> parser)
373 {
374     instance()->_cliParser = std::move(parser);
375 }
376
377
378 QString Quassel::optionValue(const QString &key)
379 {
380     return instance()->_cliParser ? instance()->_cliParser->value(key) : QString{};
381 }
382
383
384 bool Quassel::isOptionSet(const QString &key)
385 {
386     return instance()->_cliParser ? instance()->_cliParser->isSet(key) : false;
387 }
388
389
390 const QString &Quassel::coreDumpFileName()
391 {
392     if (_coreDumpFileName.isEmpty()) {
393         QDir configDir(configDirPath());
394         _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
395         QFile dumpFile(_coreDumpFileName);
396         dumpFile.open(QIODevice::Append);
397         QTextStream dumpStream(&dumpFile);
398         dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
399         qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
400         dumpStream.flush();
401         dumpFile.close();
402     }
403     return _coreDumpFileName;
404 }
405
406
407 QString Quassel::configDirPath()
408 {
409     if (!instance()->_configDirPath.isEmpty())
410         return instance()->_configDirPath;
411
412     QString path;
413     if (isOptionSet("datadir")) {
414         qWarning() << "Obsolete option --datadir used!";
415         path = Quassel::optionValue("datadir");
416     }
417     else if (isOptionSet("configdir")) {
418         path = Quassel::optionValue("configdir");
419     }
420     else {
421 #ifdef Q_OS_MAC
422         // On Mac, the path is always the same
423         path = QDir::homePath() + "/Library/Application Support/Quassel/";
424 #else
425         // We abuse QSettings to find us a sensible path on the other platforms
426 #  ifdef Q_OS_WIN
427         // don't use the registry
428         QSettings::Format format = QSettings::IniFormat;
429 #  else
430         QSettings::Format format = QSettings::NativeFormat;
431 #  endif
432         QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
433         QFileInfo fileInfo(s.fileName());
434         path = fileInfo.dir().absolutePath();
435 #endif /* Q_OS_MAC */
436     }
437
438     path = QFileInfo{path}.absoluteFilePath();
439
440     if (!path.endsWith(QDir::separator()) && !path.endsWith('/'))
441         path += QDir::separator();
442
443     QDir qDir{path};
444     if (!qDir.exists(path)) {
445         if (!qDir.mkpath(path)) {
446             qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
447             return {};
448         }
449     }
450
451     instance()->_configDirPath = path;
452     return path;
453 }
454
455
456 void Quassel::setDataDirPaths(const QStringList &paths) {
457     instance()->_dataDirPaths = paths;
458 }
459
460
461 QStringList Quassel::dataDirPaths()
462 {
463     return instance()->_dataDirPaths;
464 }
465
466
467 QStringList Quassel::findDataDirPaths()
468 {
469     // TODO Qt5
470     // We don't use QStandardPaths for now, as we still need to provide fallbacks for Qt4 and
471     // want to stay consistent.
472
473     QStringList dataDirNames;
474 #ifdef Q_OS_WIN
475     dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
476                  << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
477                  << QCoreApplication::applicationDirPath();
478 #elif defined Q_OS_MAC
479     dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
480                  << QCoreApplication::applicationDirPath();
481 #else
482     // Linux et al
483
484     // XDG_DATA_HOME is the location for users to override system-installed files, usually in .local/share
485     // This should thus come first.
486     QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
487     if (xdgDataHome.isEmpty())
488         xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
489     dataDirNames << xdgDataHome;
490
491     // Now whatever is configured through XDG_DATA_DIRS
492     QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
493     if (xdgDataDirs.isEmpty())
494         dataDirNames << "/usr/local/share" << "/usr/share";
495     else
496         dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
497
498     // Just in case, also check our install prefix
499     dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
500
501     // Normalize and append our application name
502     for (int i = 0; i < dataDirNames.count(); i++)
503         dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/";
504
505 #endif
506
507     // Add resource path and workdir just in case.
508     // Workdir should have precedence
509     dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
510     dataDirNames.append(":/data/");
511
512     // Append trailing '/' and check for existence
513     auto iter = dataDirNames.begin();
514     while (iter != dataDirNames.end()) {
515         if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
516             iter->append(QDir::separator());
517         if (!QFile::exists(*iter))
518             iter = dataDirNames.erase(iter);
519         else
520             ++iter;
521     }
522
523     dataDirNames.removeDuplicates();
524
525     return dataDirNames;
526 }
527
528
529 QString Quassel::findDataFilePath(const QString &fileName)
530 {
531     QStringList dataDirs = dataDirPaths();
532     foreach(QString dataDir, dataDirs) {
533         QString path = dataDir + fileName;
534         if (QFile::exists(path))
535             return path;
536     }
537     return QString();
538 }
539
540
541 QStringList Quassel::scriptDirPaths()
542 {
543     QStringList res(configDirPath() + "scripts/");
544     foreach(QString path, dataDirPaths())
545     res << path + "scripts/";
546     return res;
547 }
548
549
550 QString Quassel::translationDirPath()
551 {
552     if (instance()->_translationDirPath.isEmpty()) {
553         // We support only one translation dir; fallback mechanisms wouldn't work else.
554         // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
555         foreach(const QString &dir, dataDirPaths()) {
556             if (QFile::exists(dir + "translations/")) {
557                 instance()->_translationDirPath = dir + "translations/";
558                 break;
559             }
560         }
561         if (instance()->_translationDirPath.isEmpty())
562             instance()->_translationDirPath = ":/i18n/";
563     }
564     return instance()->_translationDirPath;
565 }
566
567
568 void Quassel::loadTranslation(const QLocale &locale)
569 {
570     QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
571     QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
572
573     if (qtTranslator)
574         qApp->removeTranslator(qtTranslator);
575     if (quasselTranslator)
576         qApp->removeTranslator(quasselTranslator);
577
578     // We use QLocale::C to indicate that we don't want a translation
579     if (locale.language() == QLocale::C)
580         return;
581
582     qtTranslator = new QTranslator(qApp);
583     qtTranslator->setObjectName("QtTr");
584     qApp->installTranslator(qtTranslator);
585
586     quasselTranslator = new QTranslator(qApp);
587     quasselTranslator->setObjectName("QuasselTr");
588     qApp->installTranslator(quasselTranslator);
589
590 #if QT_VERSION >= 0x040800 && !defined Q_OS_MAC
591     bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
592     if (!success)
593         qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
594     quasselTranslator->load(locale, QString(""), translationDirPath());
595 #else
596     bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
597     if (!success)
598         qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
599     quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());
600 #endif
601 }
602
603
604 // ---- Quassel::Features ---------------------------------------------------------------------------------------------
605
606 Quassel::Features::Features()
607 {
608     QStringList features;
609
610     // TODO Qt5: Use QMetaEnum::fromType()
611     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
612     _features.resize(featureEnum.keyCount(), true);  // enable all known features to true
613 }
614
615
616 Quassel::Features::Features(const QStringList &features, LegacyFeatures legacyFeatures)
617 {
618     // TODO Qt5: Use QMetaEnum::fromType()
619     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
620     _features.resize(featureEnum.keyCount(), false);
621
622     for (auto &&feature : features) {
623         int i = featureEnum.keyToValue(qPrintable(feature));
624         if (i >= 0) {
625             _features[i] = true;
626         }
627         else {
628             _unknownFeatures << feature;
629         }
630     }
631
632     if (legacyFeatures) {
633         // TODO Qt5: Use QMetaEnum::fromType()
634         auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
635         for (quint32 mask = 0x0001; mask <= 0x8000; mask <<=1) {
636             if (static_cast<quint32>(legacyFeatures) & mask) {
637                 int i = featureEnum.keyToValue(legacyFeatureEnum.valueToKey(mask));
638                 if (i >= 0) {
639                     _features[i] = true;
640                 }
641             }
642         }
643     }
644 }
645
646
647 bool Quassel::Features::isEnabled(Feature feature) const
648 {
649     size_t i = static_cast<size_t>(feature);
650     return i < _features.size() ? _features[i] : false;
651 }
652
653
654 QStringList Quassel::Features::toStringList(bool enabled) const
655 {
656     // Check if any feature is enabled
657     if (!enabled && std::all_of(_features.cbegin(), _features.cend(), [](bool feature) { return !feature; })) {
658         return QStringList{} << "NoFeatures";
659     }
660
661     QStringList result;
662
663     // TODO Qt5: Use QMetaEnum::fromType()
664     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
665     for (quint32 i = 0; i < _features.size(); ++i) {
666         if (_features[i] == enabled) {
667             result << featureEnum.key(i);
668         }
669     }
670     return result;
671 }
672
673
674 Quassel::LegacyFeatures Quassel::Features::toLegacyFeatures() const
675 {
676     // TODO Qt5: Use LegacyFeatures (flag operators for enum classes not supported in Qt4)
677     quint32 result{0};
678     // TODO Qt5: Use QMetaEnum::fromType()
679     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
680     auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
681
682     for (quint32 i = 0; i < _features.size(); ++i) {
683         if (_features[i]) {
684             int v = legacyFeatureEnum.keyToValue(featureEnum.key(i));
685             if (v >= 0) {
686                 result |= v;
687             }
688         }
689     }
690     return static_cast<LegacyFeatures>(result);
691 }
692
693
694 QStringList Quassel::Features::unknownFeatures() const
695 {
696     return _unknownFeatures;
697 }