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