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