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