Improve debugging for new IRCv3 functionality
[quassel.git] / src / common / quassel.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2019 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             {"ident-listen", tr("The address(es) quasselcore will listen on for ident requests. Same format as --listen."), tr("<address>[,...]"), "::1,127.0.0.1"},
362             {"oidentd", tr("Enable oidentd integration. In most cases you should also enable --strict-ident.")},
363             {"oidentd-conffile", tr("Set path to oidentd configuration file."), tr("file")},
364 #ifdef HAVE_SSL
365             {"require-ssl", tr("Require SSL for remote (non-loopback) client connections.")},
366             {"ssl-cert", tr("Specify the path to the SSL certificate."), tr("path"), "configdir/quasselCert.pem"},
367             {"ssl-key", tr("Specify the path to the SSL key."), tr("path"), "ssl-cert-path"},
368 #endif
369         };
370     }
371
372     // Logging options
373     options += {
374         {{"L", "loglevel"}, tr("Supports one of Debug|Info|Warning|Error; default is Info."), tr("level"), "Info"},
375         {{"l", "logfile"}, tr("Log to a file."), "path"},
376 #ifdef HAVE_SYSLOG
377         {"syslog", tr("Log to syslog.")},
378 #endif
379     };
380
381     // Debug options
382     options += {{"d", "debug"}, tr("Enable debug output.")};
383     if (runMode() != RunMode::CoreOnly) {
384         options += {
385             {"debugbufferswitches", tr("Enables debugging for bufferswitches.")},
386             {"debugmodel", tr("Enables debugging for models.")},
387         };
388     }
389     if (runMode() != RunMode::ClientOnly) {
390         options += {
391             {"debug-irc", tr("Enable logging of all raw IRC messages to debug log, including passwords!  In most cases you should also set --loglevel Debug")},
392             {"debug-irc-id", tr("Limit raw IRC logging to this network ID.  Implies --debug-irc"), tr("database network ID"), "-1"},
393             {"debug-irc-parsed", tr("Enable logging of all parsed IRC messages to debug log, including passwords!  In most cases you should also set --loglevel Debug")},
394             {"debug-irc-parsed-id", tr("Limit parsed IRC logging to this network ID.  Implies --debug-irc-parsed"), tr("database network ID"), "-1"},
395         };
396     }
397
398     _cliParser.addOptions(options);
399     _cliParser.addHelpOption();
400     _cliParser.addVersionOption();
401     _cliParser.setApplicationDescription(tr("Quassel IRC is a modern, distributed IRC client."));
402
403     // This will call ::exit() for --help, --version and in case of errors
404     _cliParser.process(*QCoreApplication::instance());
405 }
406
407 QString Quassel::optionValue(const QString& key)
408 {
409     return instance()->_cliParser.value(key);
410 }
411
412 bool Quassel::isOptionSet(const QString& key)
413 {
414     return instance()->_cliParser.isSet(key);
415 }
416
417 const QString& Quassel::coreDumpFileName()
418 {
419     if (_coreDumpFileName.isEmpty()) {
420         QDir configDir(configDirPath());
421         _coreDumpFileName = configDir.absoluteFilePath(
422             QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
423         QFile dumpFile(_coreDumpFileName);
424         dumpFile.open(QIODevice::Append);
425         QTextStream dumpStream(&dumpFile);
426         dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
427         qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
428         dumpStream.flush();
429         dumpFile.close();
430     }
431     return _coreDumpFileName;
432 }
433
434 QString Quassel::configDirPath()
435 {
436     if (!instance()->_configDirPath.isEmpty())
437         return instance()->_configDirPath;
438
439     QString path;
440     if (isOptionSet("configdir")) {
441         path = Quassel::optionValue("configdir");
442     }
443     else {
444 #ifdef Q_OS_MAC
445         // On Mac, the path is always the same
446         path = QDir::homePath() + "/Library/Application Support/Quassel/";
447 #else
448         // We abuse QSettings to find us a sensible path on the other platforms
449 #    ifdef Q_OS_WIN
450         // don't use the registry
451         QSettings::Format format = QSettings::IniFormat;
452 #    else
453         QSettings::Format format = QSettings::NativeFormat;
454 #    endif
455         QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
456         QFileInfo fileInfo(s.fileName());
457         path = fileInfo.dir().absolutePath();
458 #endif /* Q_OS_MAC */
459     }
460
461     path = QFileInfo{path}.absoluteFilePath();
462
463     if (!path.endsWith(QDir::separator()) && !path.endsWith('/'))
464         path += QDir::separator();
465
466     QDir qDir{path};
467     if (!qDir.exists(path)) {
468         if (!qDir.mkpath(path)) {
469             qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
470             return {};
471         }
472     }
473
474     instance()->_configDirPath = path;
475     return path;
476 }
477
478 QStringList Quassel::dataDirPaths()
479 {
480     if (!instance()->_dataDirPaths.isEmpty())
481         return instance()->_dataDirPaths;
482
483     // TODO: Migrate to QStandardPaths (will require moving of the sqlite database,
484     //       or a fallback for it being in the config dir)
485
486     QStringList dataDirNames;
487 #ifdef Q_OS_WIN
488     dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
489                  << qgetenv("APPDATA") + QCoreApplication::organizationDomain() << QCoreApplication::applicationDirPath();
490 #elif defined Q_OS_MAC
491     dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/" << 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"
506                      << "/usr/share";
507     else
508         dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
509
510     // Just in case, also check our install prefix
511     dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
512
513     // Normalize and append our application name
514     for (int i = 0; i < dataDirNames.count(); i++)
515         dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/";
516
517 #endif
518
519     // Add resource path and workdir just in case.
520     // Workdir should have precedence
521     dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
522     dataDirNames.append(":/data/");
523
524     // Append trailing '/' and check for existence
525     auto iter = dataDirNames.begin();
526     while (iter != dataDirNames.end()) {
527         if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
528             iter->append(QDir::separator());
529         if (!QFile::exists(*iter))
530             iter = dataDirNames.erase(iter);
531         else
532             ++iter;
533     }
534
535     dataDirNames.removeDuplicates();
536
537     instance()->_dataDirPaths = dataDirNames;
538     return dataDirNames;
539 }
540
541 QString Quassel::findDataFilePath(const QString& fileName)
542 {
543     QStringList dataDirs = dataDirPaths();
544     foreach (QString dataDir, dataDirs) {
545         QString path = dataDir + fileName;
546         if (QFile::exists(path))
547             return path;
548     }
549     return QString();
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 QString Quassel::translationDirPath()
561 {
562     if (instance()->_translationDirPath.isEmpty()) {
563         // We support only one translation dir; fallback mechanisms wouldn't work else.
564         // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
565         foreach (const QString& dir, dataDirPaths()) {
566             if (QFile::exists(dir + "translations/")) {
567                 instance()->_translationDirPath = dir + "translations/";
568                 break;
569             }
570         }
571         if (instance()->_translationDirPath.isEmpty())
572             instance()->_translationDirPath = ":/i18n/";
573     }
574     return instance()->_translationDirPath;
575 }
576
577 void Quassel::loadTranslation(const QLocale& locale)
578 {
579     auto* qtTranslator = QCoreApplication::instance()->findChild<QTranslator*>("QtTr");
580     auto* quasselTranslator = QCoreApplication::instance()->findChild<QTranslator*>("QuasselTr");
581
582     if (qtTranslator)
583         qApp->removeTranslator(qtTranslator);
584     if (quasselTranslator)
585         qApp->removeTranslator(quasselTranslator);
586
587     // We use QLocale::C to indicate that we don't want a translation
588     if (locale.language() == QLocale::C)
589         return;
590
591     qtTranslator = new QTranslator(qApp);
592     qtTranslator->setObjectName("QtTr");
593
594     quasselTranslator = new QTranslator(qApp);
595     quasselTranslator->setObjectName("QuasselTr");
596
597 #ifndef Q_OS_MAC
598     bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
599     if (!success)
600         qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
601     quasselTranslator->load(locale, QString(""), translationDirPath());
602 #else
603     bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
604     if (!success)
605         qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
606     quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());
607 #endif
608
609     qApp->installTranslator(quasselTranslator);
610     qApp->installTranslator(qtTranslator);
611 }
612
613 // ---- Quassel::Features ---------------------------------------------------------------------------------------------
614
615 Quassel::Features::Features()
616 {
617     QStringList features;
618
619     // TODO Qt5: Use QMetaEnum::fromType()
620     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
621     _features.resize(featureEnum.keyCount(), true);  // enable all known features to true
622 }
623
624 Quassel::Features::Features(const QStringList& features, LegacyFeatures legacyFeatures)
625 {
626     // TODO Qt5: Use QMetaEnum::fromType()
627     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
628     _features.resize(featureEnum.keyCount(), false);
629
630     for (auto&& feature : features) {
631         int i = featureEnum.keyToValue(qPrintable(feature));
632         if (i >= 0) {
633             _features[i] = true;
634         }
635         else {
636             _unknownFeatures << feature;
637         }
638     }
639
640     if (legacyFeatures) {
641         // TODO Qt5: Use QMetaEnum::fromType()
642         auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
643         for (quint32 mask = 0x0001; mask <= 0x8000; mask <<= 1) {
644             if (static_cast<quint32>(legacyFeatures) & mask) {
645                 int i = featureEnum.keyToValue(legacyFeatureEnum.valueToKey(mask));
646                 if (i >= 0) {
647                     _features[i] = true;
648                 }
649             }
650         }
651     }
652 }
653
654 bool Quassel::Features::isEnabled(Feature feature) const
655 {
656     auto i = static_cast<size_t>(feature);
657     return i < _features.size() ? _features[i] : false;
658 }
659
660 QStringList Quassel::Features::toStringList(bool enabled) const
661 {
662     // Check if any feature is enabled
663     if (!enabled && std::all_of(_features.cbegin(), _features.cend(), [](bool feature) { return !feature; })) {
664         return QStringList{} << "NoFeatures";
665     }
666
667     QStringList result;
668
669     // TODO Qt5: Use QMetaEnum::fromType()
670     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
671     for (quint32 i = 0; i < _features.size(); ++i) {
672         if (_features[i] == enabled) {
673             result << featureEnum.key(i);
674         }
675     }
676     return result;
677 }
678
679 Quassel::LegacyFeatures Quassel::Features::toLegacyFeatures() const
680 {
681     // TODO Qt5: Use LegacyFeatures (flag operators for enum classes not supported in Qt4)
682     quint32 result{0};
683     // TODO Qt5: Use QMetaEnum::fromType()
684     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
685     auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
686
687     for (quint32 i = 0; i < _features.size(); ++i) {
688         if (_features[i]) {
689             int v = legacyFeatureEnum.keyToValue(featureEnum.key(i));
690             if (v >= 0) {
691                 result |= v;
692             }
693         }
694     }
695     return static_cast<LegacyFeatures>(result);
696 }
697
698 QStringList Quassel::Features::unknownFeatures() const
699 {
700     return _unknownFeatures;
701 }