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