sigproxy: Modernize RPC calls (remote signals)
[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 <QCoreApplication>
27 #include <QDateTime>
28 #include <QDir>
29 #include <QFileInfo>
30 #include <QHostAddress>
31 #include <QLibraryInfo>
32 #include <QMetaEnum>
33 #include <QSettings>
34 #include <QTranslator>
35 #include <QUuid>
36
37 #include "bufferinfo.h"
38 #include "identity.h"
39 #include "logger.h"
40 #include "message.h"
41 #include "network.h"
42 #include "peer.h"
43 #include "protocol.h"
44 #include "syncableobject.h"
45 #include "types.h"
46 #include "version.h"
47
48 #ifndef Q_OS_WIN
49 #    include "posixsignalwatcher.h"
50 #else
51 #    include "windowssignalwatcher.h"
52 #endif
53
54 Quassel::Quassel()
55     : Singleton<Quassel>{this}
56     , _logger{new Logger{this}}
57 {
58 #ifdef EMBED_DATA
59     Q_INIT_RESOURCE(i18n);
60 #endif
61 }
62
63 void Quassel::init(RunMode runMode)
64 {
65     _runMode = runMode;
66
67     qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
68
69     setupSignalHandling();
70     setupEnvironment();
71     registerMetaTypes();
72
73     // Initial translation (may be overridden in UI settings)
74     loadTranslation(QLocale::system());
75
76     setupCliParser();
77
78     // Don't keep a debug log on the core
79     logger()->setup(runMode != RunMode::CoreOnly);
80
81     Network::setDefaultCodecForServer("UTF-8");
82     Network::setDefaultCodecForEncoding("UTF-8");
83     Network::setDefaultCodecForDecoding("ISO-8859-15");
84 }
85
86 Logger* Quassel::logger() const
87 {
88     return _logger;
89 }
90
91 void Quassel::registerQuitHandler(QuitHandler handler)
92 {
93     instance()->_quitHandlers.emplace_back(std::move(handler));
94 }
95
96 void Quassel::quit()
97 {
98     // Protect against multiple invocations (e.g. triggered by MainWin::closeEvent())
99     if (!_quitting) {
100         _quitting = true;
101         qInfo() << "Quitting...";
102         if (_quitHandlers.empty()) {
103             QCoreApplication::quit();
104         }
105         else {
106             // Note: We expect one of the registered handlers to call QCoreApplication::quit()
107             for (auto&& handler : _quitHandlers) {
108                 handler();
109             }
110         }
111     }
112 }
113
114 void Quassel::registerReloadHandler(ReloadHandler handler)
115 {
116     instance()->_reloadHandlers.emplace_back(std::move(handler));
117 }
118
119 bool Quassel::reloadConfig()
120 {
121     bool result{true};
122     for (auto&& handler : _reloadHandlers) {
123         result = result && handler();
124     }
125     return result;
126 }
127
128 //! Register our custom types with Qt's Meta Object System.
129 /**  This makes them available for QVariant and in signals/slots, among other things.
130  *
131  */
132 void Quassel::registerMetaTypes()
133 {
134     // Complex types
135     qRegisterMetaType<Message>("Message");
136     qRegisterMetaType<BufferInfo>("BufferInfo");
137     qRegisterMetaType<NetworkInfo>("NetworkInfo");
138     qRegisterMetaType<Network::Server>("Network::Server");
139     qRegisterMetaType<Identity>("Identity");
140
141     qRegisterMetaTypeStreamOperators<Message>("Message");
142     qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
143     qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
144     qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
145     qRegisterMetaTypeStreamOperators<Identity>("Identity");
146
147     qRegisterMetaType<IdentityId>("IdentityId");
148     qRegisterMetaType<BufferId>("BufferId");
149     qRegisterMetaType<NetworkId>("NetworkId");
150     qRegisterMetaType<UserId>("UserId");
151     qRegisterMetaType<AccountId>("AccountId");
152     qRegisterMetaType<MsgId>("MsgId");
153
154     qRegisterMetaType<QHostAddress>("QHostAddress");
155     qRegisterMetaTypeStreamOperators<QHostAddress>("QHostAddress");
156     qRegisterMetaType<QUuid>("QUuid");
157     qRegisterMetaTypeStreamOperators<QUuid>("QUuid");
158
159     qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
160     qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
161     qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
162     qRegisterMetaTypeStreamOperators<UserId>("UserId");
163     qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
164     qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
165
166     qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
167     qRegisterMetaType<PeerPtr>("PeerPtr");
168     qRegisterMetaTypeStreamOperators<PeerPtr>("PeerPtr");
169
170     // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
171     if (!QMetaType::type("QVariant")) {
172         qRegisterMetaType<QVariant>("QVariant");
173         qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
174     }
175 }
176
177 void Quassel::setupEnvironment()
178 {
179     // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This
180     // is, for example, used by Qt for finding icons and other things. In case Quassel is installed in a non-standard
181     // prefix (or run from the build directory), it makes sense to add this to XDG_DATA_DIRS so we don't have to
182     // hack extra search paths into various places.
183 #ifdef Q_OS_UNIX
184     QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
185     if (xdgDataVar.isEmpty())
186         xdgDataVar = QLatin1String("/usr/local/share:/usr/share");  // sane defaults
187
188     QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
189
190     // Add our install prefix (if we're not in a bindir, this just adds the current workdir)
191     QString appDir = QCoreApplication::applicationDirPath();
192     int binpos = appDir.lastIndexOf("/bin");
193     if (binpos >= 0) {
194         appDir.replace(binpos, 4, "/share");
195         xdgDirs.append(appDir);
196         // Also append apps/quassel, this is only for QIconLoader to find icons there
197         xdgDirs.append(appDir + "/apps/quassel");
198     }
199     else
200         xdgDirs.append(appDir);  // build directory is always the last fallback
201
202     xdgDirs.removeDuplicates();
203
204     qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
205 #endif
206 }
207
208 void Quassel::setupBuildInfo()
209 {
210     BuildInfo buildInfo;
211     buildInfo.applicationName = "quassel";
212     buildInfo.coreApplicationName = "quasselcore";
213     buildInfo.clientApplicationName = "quasselclient";
214     buildInfo.organizationName = "Quassel Project";
215     buildInfo.organizationDomain = "quassel-irc.org";
216
217     buildInfo.protocolVersion = 10;  // FIXME: deprecated, will be removed
218
219     buildInfo.baseVersion = QUASSEL_VERSION_STRING;
220     buildInfo.generatedVersion = GIT_DESCRIBE;
221
222     // Check if we got a commit hash
223     if (!QString(GIT_HEAD).isEmpty()) {
224         buildInfo.commitHash = GIT_HEAD;
225         // Set to Unix epoch, wrapped as a string for backwards-compatibility
226         buildInfo.commitDate = QString::number(GIT_COMMIT_DATE);
227     }
228     else if (!QString(DIST_HASH).contains("Format")) {
229         buildInfo.commitHash = DIST_HASH;
230         // Leave as Unix epoch if set as Unix epoch, but don't force this for
231         // backwards-compatibility with existing packaging/release tools that might set strings.
232         buildInfo.commitDate = QString(DIST_DATE);
233     }
234
235     // create a nice version string
236     if (buildInfo.generatedVersion.isEmpty()) {
237         if (!buildInfo.commitHash.isEmpty()) {
238             // dist version
239             buildInfo.plainVersionString = QString{"v%1 (dist-%2)"}.arg(buildInfo.baseVersion).arg(buildInfo.commitHash.left(7));
240             buildInfo.fancyVersionString = QString{"v%1 (dist-<a href=\"https://github.com/quassel/quassel/commit/%3\">%2</a>)"}
241                                                .arg(buildInfo.baseVersion)
242                                                .arg(buildInfo.commitHash.left(7))
243                                                .arg(buildInfo.commitHash);
244         }
245         else {
246             // we only have a base version :(
247             buildInfo.plainVersionString = QString{"v%1 (unknown revision)"}.arg(buildInfo.baseVersion);
248         }
249     }
250     else {
251         // analyze what we got from git-describe
252         static const QRegExp rx{"(.*)-(\\d+)-g([0-9a-f]+)(-dirty)?$"};
253         if (rx.exactMatch(buildInfo.generatedVersion)) {
254             QString distance = rx.cap(2) == "0" ? QString{} : QString{"%1+%2 "}.arg(rx.cap(1), rx.cap(2));
255             buildInfo.plainVersionString = QString{"v%1 (%2git-%3%4)"}.arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4));
256             if (!buildInfo.commitHash.isEmpty()) {
257                 buildInfo.fancyVersionString = QString{"v%1 (%2git-<a href=\"https://github.com/quassel/quassel/commit/%5\">%3</a>%4)"}
258                                                    .arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), buildInfo.commitHash);
259             }
260         }
261         else {
262             buildInfo.plainVersionString = QString{"v%1 (invalid revision)"}.arg(buildInfo.baseVersion);
263         }
264     }
265     if (buildInfo.fancyVersionString.isEmpty()) {
266         buildInfo.fancyVersionString = buildInfo.plainVersionString;
267     }
268
269     instance()->_buildInfo = std::move(buildInfo);
270 }
271
272 const Quassel::BuildInfo& Quassel::buildInfo()
273 {
274     return instance()->_buildInfo;
275 }
276
277 void Quassel::setupSignalHandling()
278 {
279 #ifndef Q_OS_WIN
280     _signalWatcher = new PosixSignalWatcher(this);
281 #else
282     _signalWatcher = new WindowsSignalWatcher(this);
283 #endif
284     connect(_signalWatcher, &AbstractSignalWatcher::handleSignal, this, &Quassel::handleSignal);
285 }
286
287 void Quassel::handleSignal(AbstractSignalWatcher::Action action)
288 {
289     switch (action) {
290     case AbstractSignalWatcher::Action::Reload:
291         // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for graceful reloading of processes.
292         if (!_reloadHandlers.empty()) {
293             qInfo() << "Reloading configuration";
294             if (reloadConfig()) {
295                 qInfo() << "Successfully reloaded configuration";
296             }
297         }
298         break;
299     case AbstractSignalWatcher::Action::Terminate:
300         if (!_quitting) {
301             quit();
302         }
303         else {
304             qInfo() << "Already shutting down, ignoring signal";
305         }
306         break;
307     case AbstractSignalWatcher::Action::HandleCrash:
308         logBacktrace(instance()->coreDumpFileName());
309         exit(EXIT_FAILURE);
310     }
311 }
312
313 Quassel::RunMode Quassel::runMode()
314 {
315     return instance()->_runMode;
316 }
317
318 void Quassel::setupCliParser()
319 {
320     QList<QCommandLineOption> options;
321
322     // General options
323     /// @todo Bring back --datadir to specify the database location independent of config
324     if (runMode() == RunMode::ClientOnly) {
325         options += {{"c", "configdir"}, tr("Specify the directory holding the client configuration."), tr("path")};
326     }
327     else {
328         options += {{"c", "configdir"},
329                     tr("Specify the directory holding configuration files, the SQlite database and the SSL certificate."),
330                     tr("path")};
331     }
332
333     // Client options
334     if (runMode() != RunMode::CoreOnly) {
335         options += {
336             {"icontheme", tr("Override the system icon theme ('breeze' is recommended)."), tr("theme")},
337             {"qss", tr("Load a custom application stylesheet."), tr("file.qss")},
338             {"hidewindow", tr("Start the client minimized to the system tray.")},
339         };
340     }
341
342     // Core options
343     if (runMode() != RunMode::ClientOnly) {
344         options += {
345             {"listen", tr("The address(es) quasselcore will listen on."), tr("<address>[,<address>[,...]]"), "::,0.0.0.0"},
346             {{"p", "port"}, tr("The port quasselcore will listen at."), tr("port"), "4242"},
347             {{"n", "norestore"}, tr("Don't restore last core's state.")},
348             {"config-from-environment", tr("Load configuration from environment variables.")},
349             {"select-backend", tr("Switch storage backend (migrating data if possible)."), tr("backendidentifier")},
350             {"select-authenticator", tr("Select authentication backend."), tr("authidentifier")},
351             {"add-user", tr("Starts an interactive session to add a new core user.")},
352             {"change-userpass",
353              tr("Starts an interactive session to change the password of the user identified by <username>."),
354              tr("username")},
355             {"strict-ident", tr("Use users' quasselcore username as ident reply. Ignores each user's configured ident setting.")},
356             {"ident-daemon", tr("Enable internal ident daemon.")},
357             {"ident-port",
358              tr("The port quasselcore will listen at for ident requests. Only meaningful with --ident-daemon."),
359              tr("port"),
360              "10113"},
361             {"oidentd", tr("Enable oidentd integration. In most cases you should also enable --strict-ident.")},
362             {"oidentd-conffile", tr("Set path to oidentd configuration file."), tr("file")},
363 #ifdef HAVE_SSL
364             {"require-ssl", tr("Require SSL for remote (non-loopback) client connections.")},
365             {"ssl-cert", tr("Specify the path to the SSL certificate."), tr("path"), "configdir/quasselCert.pem"},
366             {"ssl-key", tr("Specify the path to the SSL key."), tr("path"), "ssl-cert-path"},
367 #endif
368         };
369     }
370
371     // Logging options
372     options += {
373         {{"L", "loglevel"}, tr("Supports one of Debug|Info|Warning|Error; default is Info."), tr("level"), "Info"},
374         {{"l", "logfile"}, tr("Log to a file."), "path"},
375 #ifdef HAVE_SYSLOG
376         {"syslog", tr("Log to syslog.")},
377 #endif
378     };
379
380     // Debug options
381     options += {{"d", "debug"}, tr("Enable debug output.")};
382     if (runMode() != RunMode::CoreOnly) {
383         options += {
384             {"debugbufferswitches", tr("Enables debugging for bufferswitches.")},
385             {"debugmodel", tr("Enables debugging for models.")},
386         };
387     }
388     if (runMode() != RunMode::ClientOnly) {
389         options += {
390             {"debug-irc", tr("Enable logging of all raw IRC messages to debug log, including passwords!  In most cases you should also set --loglevel Debug")},
391             {"debug-irc-id", tr("Limit raw IRC logging to this network ID.  Implies --debug-irc"), tr("database network ID"), "-1"},
392         };
393     }
394
395     _cliParser.addOptions(options);
396     _cliParser.addHelpOption();
397     _cliParser.addVersionOption();
398     _cliParser.setApplicationDescription(tr("Quassel IRC is a modern, distributed IRC client."));
399
400     // This will call ::exit() for --help, --version and in case of errors
401     _cliParser.process(*QCoreApplication::instance());
402 }
403
404 QString Quassel::optionValue(const QString& key)
405 {
406     return instance()->_cliParser.value(key);
407 }
408
409 bool Quassel::isOptionSet(const QString& key)
410 {
411     return instance()->_cliParser.isSet(key);
412 }
413
414 const QString& Quassel::coreDumpFileName()
415 {
416     if (_coreDumpFileName.isEmpty()) {
417         QDir configDir(configDirPath());
418         _coreDumpFileName = configDir.absoluteFilePath(
419             QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
420         QFile dumpFile(_coreDumpFileName);
421         dumpFile.open(QIODevice::Append);
422         QTextStream dumpStream(&dumpFile);
423         dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
424         qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
425         dumpStream.flush();
426         dumpFile.close();
427     }
428     return _coreDumpFileName;
429 }
430
431 QString Quassel::configDirPath()
432 {
433     if (!instance()->_configDirPath.isEmpty())
434         return instance()->_configDirPath;
435
436     QString path;
437     if (isOptionSet("configdir")) {
438         path = Quassel::optionValue("configdir");
439     }
440     else {
441 #ifdef Q_OS_MAC
442         // On Mac, the path is always the same
443         path = QDir::homePath() + "/Library/Application Support/Quassel/";
444 #else
445         // We abuse QSettings to find us a sensible path on the other platforms
446 #    ifdef Q_OS_WIN
447         // don't use the registry
448         QSettings::Format format = QSettings::IniFormat;
449 #    else
450         QSettings::Format format = QSettings::NativeFormat;
451 #    endif
452         QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
453         QFileInfo fileInfo(s.fileName());
454         path = fileInfo.dir().absolutePath();
455 #endif /* Q_OS_MAC */
456     }
457
458     path = QFileInfo{path}.absoluteFilePath();
459
460     if (!path.endsWith(QDir::separator()) && !path.endsWith('/'))
461         path += QDir::separator();
462
463     QDir qDir{path};
464     if (!qDir.exists(path)) {
465         if (!qDir.mkpath(path)) {
466             qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
467             return {};
468         }
469     }
470
471     instance()->_configDirPath = path;
472     return path;
473 }
474
475 QStringList Quassel::dataDirPaths()
476 {
477     if (!instance()->_dataDirPaths.isEmpty())
478         return instance()->_dataDirPaths;
479
480     // TODO: Migrate to QStandardPaths (will require moving of the sqlite database,
481     //       or a fallback for it being in the config dir)
482
483     QStringList dataDirNames;
484 #ifdef Q_OS_WIN
485     dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
486                  << qgetenv("APPDATA") + QCoreApplication::organizationDomain() << QCoreApplication::applicationDirPath();
487 #elif defined Q_OS_MAC
488     dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/" << QCoreApplication::applicationDirPath();
489 #else
490     // Linux et al
491
492     // XDG_DATA_HOME is the location for users to override system-installed files, usually in .local/share
493     // This should thus come first.
494     QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
495     if (xdgDataHome.isEmpty())
496         xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
497     dataDirNames << xdgDataHome;
498
499     // Now whatever is configured through XDG_DATA_DIRS
500     QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
501     if (xdgDataDirs.isEmpty())
502         dataDirNames << "/usr/local/share"
503                      << "/usr/share";
504     else
505         dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
506
507     // Just in case, also check our install prefix
508     dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
509
510     // Normalize and append our application name
511     for (int i = 0; i < dataDirNames.count(); i++)
512         dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/";
513
514 #endif
515
516     // Add resource path and workdir just in case.
517     // Workdir should have precedence
518     dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
519     dataDirNames.append(":/data/");
520
521     // Append trailing '/' and check for existence
522     auto iter = dataDirNames.begin();
523     while (iter != dataDirNames.end()) {
524         if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
525             iter->append(QDir::separator());
526         if (!QFile::exists(*iter))
527             iter = dataDirNames.erase(iter);
528         else
529             ++iter;
530     }
531
532     dataDirNames.removeDuplicates();
533
534     instance()->_dataDirPaths = dataDirNames;
535     return dataDirNames;
536 }
537
538 QString Quassel::findDataFilePath(const QString& fileName)
539 {
540     QStringList dataDirs = dataDirPaths();
541     foreach (QString dataDir, dataDirs) {
542         QString path = dataDir + fileName;
543         if (QFile::exists(path))
544             return path;
545     }
546     return QString();
547 }
548
549 QStringList Quassel::scriptDirPaths()
550 {
551     QStringList res(configDirPath() + "scripts/");
552     foreach (QString path, dataDirPaths())
553         res << path + "scripts/";
554     return res;
555 }
556
557 QString Quassel::translationDirPath()
558 {
559     if (instance()->_translationDirPath.isEmpty()) {
560         // We support only one translation dir; fallback mechanisms wouldn't work else.
561         // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
562         foreach (const QString& dir, dataDirPaths()) {
563             if (QFile::exists(dir + "translations/")) {
564                 instance()->_translationDirPath = dir + "translations/";
565                 break;
566             }
567         }
568         if (instance()->_translationDirPath.isEmpty())
569             instance()->_translationDirPath = ":/i18n/";
570     }
571     return instance()->_translationDirPath;
572 }
573
574 void Quassel::loadTranslation(const QLocale& locale)
575 {
576     auto* qtTranslator = QCoreApplication::instance()->findChild<QTranslator*>("QtTr");
577     auto* quasselTranslator = QCoreApplication::instance()->findChild<QTranslator*>("QuasselTr");
578
579     if (qtTranslator)
580         qApp->removeTranslator(qtTranslator);
581     if (quasselTranslator)
582         qApp->removeTranslator(quasselTranslator);
583
584     // We use QLocale::C to indicate that we don't want a translation
585     if (locale.language() == QLocale::C)
586         return;
587
588     qtTranslator = new QTranslator(qApp);
589     qtTranslator->setObjectName("QtTr");
590
591     quasselTranslator = new QTranslator(qApp);
592     quasselTranslator->setObjectName("QuasselTr");
593
594 #ifndef Q_OS_MAC
595     bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
596     if (!success)
597         qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
598     quasselTranslator->load(locale, QString(""), translationDirPath());
599 #else
600     bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
601     if (!success)
602         qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
603     quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());
604 #endif
605
606     qApp->installTranslator(quasselTranslator);
607     qApp->installTranslator(qtTranslator);
608 }
609
610 // ---- Quassel::Features ---------------------------------------------------------------------------------------------
611
612 Quassel::Features::Features()
613 {
614     QStringList features;
615
616     // TODO Qt5: Use QMetaEnum::fromType()
617     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
618     _features.resize(featureEnum.keyCount(), true);  // enable all known features to true
619 }
620
621 Quassel::Features::Features(const QStringList& features, LegacyFeatures legacyFeatures)
622 {
623     // TODO Qt5: Use QMetaEnum::fromType()
624     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
625     _features.resize(featureEnum.keyCount(), false);
626
627     for (auto&& feature : features) {
628         int i = featureEnum.keyToValue(qPrintable(feature));
629         if (i >= 0) {
630             _features[i] = true;
631         }
632         else {
633             _unknownFeatures << feature;
634         }
635     }
636
637     if (legacyFeatures) {
638         // TODO Qt5: Use QMetaEnum::fromType()
639         auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
640         for (quint32 mask = 0x0001; mask <= 0x8000; mask <<= 1) {
641             if (static_cast<quint32>(legacyFeatures) & mask) {
642                 int i = featureEnum.keyToValue(legacyFeatureEnum.valueToKey(mask));
643                 if (i >= 0) {
644                     _features[i] = true;
645                 }
646             }
647         }
648     }
649 }
650
651 bool Quassel::Features::isEnabled(Feature feature) const
652 {
653     auto i = static_cast<size_t>(feature);
654     return i < _features.size() ? _features[i] : false;
655 }
656
657 QStringList Quassel::Features::toStringList(bool enabled) const
658 {
659     // Check if any feature is enabled
660     if (!enabled && std::all_of(_features.cbegin(), _features.cend(), [](bool feature) { return !feature; })) {
661         return QStringList{} << "NoFeatures";
662     }
663
664     QStringList result;
665
666     // TODO Qt5: Use QMetaEnum::fromType()
667     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
668     for (quint32 i = 0; i < _features.size(); ++i) {
669         if (_features[i] == enabled) {
670             result << featureEnum.key(i);
671         }
672     }
673     return result;
674 }
675
676 Quassel::LegacyFeatures Quassel::Features::toLegacyFeatures() const
677 {
678     // TODO Qt5: Use LegacyFeatures (flag operators for enum classes not supported in Qt4)
679     quint32 result{0};
680     // TODO Qt5: Use QMetaEnum::fromType()
681     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
682     auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
683
684     for (quint32 i = 0; i < _features.size(); ++i) {
685         if (_features[i]) {
686             int v = legacyFeatureEnum.keyToValue(featureEnum.key(i));
687             if (v >= 0) {
688                 result |= v;
689             }
690         }
691     }
692     return static_cast<LegacyFeatures>(result);
693 }
694
695 QStringList Quassel::Features::unknownFeatures() const
696 {
697     return _unknownFeatures;
698 }