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