common: Make CommitDate Unix epoch, handle legacy
[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 <signal.h>
27 #if !defined Q_OS_WIN && !defined Q_OS_MAC
28 #  include <sys/types.h>
29 #  include <sys/time.h>
30 #  include <sys/resource.h>
31 #endif
32
33 #include <QCoreApplication>
34 #include <QDateTime>
35 #include <QDir>
36 #include <QFileInfo>
37 #include <QHostAddress>
38 #include <QLibraryInfo>
39 #include <QMetaEnum>
40 #include <QSettings>
41 #include <QTranslator>
42 #include <QUuid>
43
44 #include "bufferinfo.h"
45 #include "identity.h"
46 #include "logger.h"
47 #include "message.h"
48 #include "network.h"
49 #include "peer.h"
50 #include "protocol.h"
51 #include "syncableobject.h"
52 #include "types.h"
53
54 #include "../../version.h"
55
56 Quassel *Quassel::instance()
57 {
58     static Quassel instance;
59     return &instance;
60 }
61
62
63 Quassel::Quassel()
64 {
65     // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
66     signal(SIGTERM, handleSignal);
67     signal(SIGINT, handleSignal);
68 #ifndef Q_OS_WIN
69     // SIGHUP is used to reload configuration (i.e. SSL certificates)
70     // Windows does not support SIGHUP
71     signal(SIGHUP, handleSignal);
72 #endif
73 }
74
75
76 bool Quassel::init()
77 {
78     if (instance()->_initialized)
79         return true;  // allow multiple invocations because of MonolithicApplication
80
81     if (instance()->_handleCrashes) {
82         // we have crashhandler for win32 and unix (based on execinfo).
83 #if defined(Q_OS_WIN) || defined(HAVE_EXECINFO)
84 # ifndef Q_OS_WIN
85         // we only handle crashes ourselves if coredumps are disabled
86         struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit));
87         int rc = getrlimit(RLIMIT_CORE, limit);
88
89         if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
90 # endif /* Q_OS_WIN */
91         signal(SIGABRT, handleSignal);
92         signal(SIGSEGV, handleSignal);
93 # ifndef Q_OS_WIN
94         signal(SIGBUS, handleSignal);
95     }
96     free(limit);
97 # endif /* Q_OS_WIN */
98 #endif /* Q_OS_WIN || HAVE_EXECINFO */
99     }
100
101     instance()->_initialized = true;
102     qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
103
104     instance()->setupEnvironment();
105     instance()->registerMetaTypes();
106
107     Network::setDefaultCodecForServer("UTF-8");
108     Network::setDefaultCodecForEncoding("UTF-8");
109     Network::setDefaultCodecForDecoding("ISO-8859-15");
110
111     if (isOptionSet("help")) {
112         instance()->_cliParser->usage();
113         return false;
114     }
115
116     if (isOptionSet("version")) {
117         std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
118         return false;
119     }
120
121     // Set up logging
122     if (isOptionSet("loglevel")) {
123         QString level = optionValue("loglevel").toLower();
124
125         if (level == "debug")
126             setLogLevel(DebugLevel);
127         else if (level == "info")
128             setLogLevel(InfoLevel);
129         else if (level == "warning")
130             setLogLevel(WarningLevel);
131         else if (level == "error")
132             setLogLevel(ErrorLevel);
133         else {
134             qWarning() << qPrintable(tr("Invalid log level %1; supported are Debug|Info|Warning|Error").arg(level));
135             return false;
136         }
137     }
138
139     QString logfilename = optionValue("logfile");
140     if (!logfilename.isEmpty()) {
141         instance()->_logFile.reset(new QFile{logfilename});
142         if (!logFile()->open(QIODevice::Append | QIODevice::Text)) {
143             qWarning() << qPrintable(tr("Could not open log file \"%1\": %2").arg(logfilename, logFile()->errorString()));
144             instance()->_logFile.reset();
145         }
146     }
147 #ifdef HAVE_SYSLOG
148     instance()->_logToSyslog = isOptionSet("syslog");
149 #endif
150
151 #if QT_VERSION < 0x050000
152     qInstallMsgHandler(Logger::logMessage);
153 #else
154     qInstallMessageHandler(Logger::logMessage);
155 #endif
156
157     return true;
158 }
159
160
161 void Quassel::destroy()
162 {
163     if (logFile()) {
164         logFile()->close();
165         instance()->_logFile.reset();
166     }
167 }
168
169
170 void Quassel::registerQuitHandler(QuitHandler handler)
171 {
172     instance()->_quitHandlers.emplace_back(std::move(handler));
173 }
174
175 void Quassel::quit()
176 {
177     if (_quitHandlers.empty()) {
178         QCoreApplication::quit();
179     }
180     else {
181         for (auto &&handler : _quitHandlers) {
182             handler();
183         }
184     }
185 }
186
187
188 void Quassel::registerReloadHandler(ReloadHandler handler)
189 {
190     instance()->_reloadHandlers.emplace_back(std::move(handler));
191 }
192
193
194 bool Quassel::reloadConfig()
195 {
196     bool result{true};
197     for (auto &&handler : _reloadHandlers) {
198         result = result && handler();
199     }
200     return result;
201 }
202
203
204 //! Register our custom types with Qt's Meta Object System.
205 /**  This makes them available for QVariant and in signals/slots, among other things.
206 *
207 */
208 void Quassel::registerMetaTypes()
209 {
210     // Complex types
211     qRegisterMetaType<Message>("Message");
212     qRegisterMetaType<BufferInfo>("BufferInfo");
213     qRegisterMetaType<NetworkInfo>("NetworkInfo");
214     qRegisterMetaType<Network::Server>("Network::Server");
215     qRegisterMetaType<Identity>("Identity");
216
217     qRegisterMetaTypeStreamOperators<Message>("Message");
218     qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
219     qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
220     qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
221     qRegisterMetaTypeStreamOperators<Identity>("Identity");
222
223     qRegisterMetaType<IdentityId>("IdentityId");
224     qRegisterMetaType<BufferId>("BufferId");
225     qRegisterMetaType<NetworkId>("NetworkId");
226     qRegisterMetaType<UserId>("UserId");
227     qRegisterMetaType<AccountId>("AccountId");
228     qRegisterMetaType<MsgId>("MsgId");
229
230     qRegisterMetaType<QHostAddress>("QHostAddress");
231     qRegisterMetaTypeStreamOperators<QHostAddress>("QHostAddress");
232     qRegisterMetaType<QUuid>("QUuid");
233     qRegisterMetaTypeStreamOperators<QUuid>("QUuid");
234
235     qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
236     qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
237     qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
238     qRegisterMetaTypeStreamOperators<UserId>("UserId");
239     qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
240     qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
241
242     qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
243     qRegisterMetaType<PeerPtr>("PeerPtr");
244     qRegisterMetaTypeStreamOperators<PeerPtr>("PeerPtr");
245
246     // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
247     if (!QMetaType::type("QVariant")) {
248         qRegisterMetaType<QVariant>("QVariant");
249         qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
250     }
251 }
252
253
254 void Quassel::setupEnvironment()
255 {
256     // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This
257     // is, for example, used by Qt for finding icons and other things. In case Quassel is installed in a non-standard
258     // prefix (or run from the build directory), it makes sense to add this to XDG_DATA_DIRS so we don't have to
259     // hack extra search paths into various places.
260 #ifdef Q_OS_UNIX
261     QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
262     if (xdgDataVar.isEmpty())
263         xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
264
265     QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
266
267     // Add our install prefix (if we're not in a bindir, this just adds the current workdir)
268     QString appDir = QCoreApplication::applicationDirPath();
269     int binpos = appDir.lastIndexOf("/bin");
270     if (binpos >= 0) {
271         appDir.replace(binpos, 4, "/share");
272         xdgDirs.append(appDir);
273         // Also append apps/quassel, this is only for QIconLoader to find icons there
274         xdgDirs.append(appDir + "/apps/quassel");
275     } else
276         xdgDirs.append(appDir);  // build directory is always the last fallback
277
278     xdgDirs.removeDuplicates();
279
280     qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
281 #endif
282 }
283
284
285 void Quassel::setupBuildInfo()
286 {
287     BuildInfo buildInfo;
288     buildInfo.applicationName = "quassel";
289     buildInfo.coreApplicationName = "quasselcore";
290     buildInfo.clientApplicationName = "quasselclient";
291     buildInfo.organizationName = "Quassel Project";
292     buildInfo.organizationDomain = "quassel-irc.org";
293
294     buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
295
296     buildInfo.baseVersion = QUASSEL_VERSION_STRING;
297     buildInfo.generatedVersion = GIT_DESCRIBE;
298
299     // Check if we got a commit hash
300     if (!QString(GIT_HEAD).isEmpty()) {
301         buildInfo.commitHash = GIT_HEAD;
302         // Set to Unix epoch, wrapped as a string for backwards-compatibility
303         buildInfo.commitDate = QString::number(GIT_COMMIT_DATE);
304     }
305     else if (!QString(DIST_HASH).contains("Format")) {
306         buildInfo.commitHash = DIST_HASH;
307         // Leave as Unix epoch if set as Unix epoch, but don't force this for
308         // backwards-compatibility with existing packaging/release tools that might set strings.
309         buildInfo.commitDate = QString(DIST_DATE);
310     }
311
312     // create a nice version string
313     if (buildInfo.generatedVersion.isEmpty()) {
314         if (!buildInfo.commitHash.isEmpty()) {
315             // dist version
316             buildInfo.plainVersionString = QString{"v%1 (dist-%2)"}
317                                                .arg(buildInfo.baseVersion)
318                                                .arg(buildInfo.commitHash.left(7));
319             buildInfo.fancyVersionString = QString{"v%1 (dist-<a href=\"https://github.com/quassel/quassel/commit/%3\">%2</a>)"}
320                                                .arg(buildInfo.baseVersion)
321                                                .arg(buildInfo.commitHash.left(7))
322                                                .arg(buildInfo.commitHash);
323         }
324         else {
325             // we only have a base version :(
326             buildInfo.plainVersionString = QString{"v%1 (unknown revision)"}.arg(buildInfo.baseVersion);
327         }
328     }
329     else {
330         // analyze what we got from git-describe
331         static const QRegExp rx{"(.*)-(\\d+)-g([0-9a-f]+)(-dirty)?$"};
332         if (rx.exactMatch(buildInfo.generatedVersion)) {
333             QString distance = rx.cap(2) == "0" ? QString{} : QString{"%1+%2 "}.arg(rx.cap(1), rx.cap(2));
334             buildInfo.plainVersionString = QString{"v%1 (%2git-%3%4)"}.arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4));
335             if (!buildInfo.commitHash.isEmpty()) {
336                 buildInfo.fancyVersionString = QString{"v%1 (%2git-<a href=\"https://github.com/quassel/quassel/commit/%5\">%3</a>%4)"}
337                                                    .arg(buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), buildInfo.commitHash);
338             }
339         }
340         else {
341             buildInfo.plainVersionString = QString{"v%1 (invalid revision)"}.arg(buildInfo.baseVersion);
342         }
343     }
344     if (buildInfo.fancyVersionString.isEmpty()) {
345         buildInfo.fancyVersionString = buildInfo.plainVersionString;
346     }
347
348     instance()->_buildInfo = std::move(buildInfo);
349 }
350
351
352 const Quassel::BuildInfo &Quassel::buildInfo()
353 {
354     return instance()->_buildInfo;
355 }
356
357
358 //! Signal handler for graceful shutdown.
359 void Quassel::handleSignal(int sig)
360 {
361     switch (sig) {
362     case SIGTERM:
363     case SIGINT:
364         qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
365         instance()->quit();
366         break;
367 #ifndef Q_OS_WIN
368 // Windows does not support SIGHUP
369     case SIGHUP:
370         // Most applications use this as the 'configuration reload' command, e.g. nginx uses it for
371         // graceful reloading of processes.
372         quInfo() << "Caught signal" << SIGHUP << "- reloading configuration";
373         if (instance()->reloadConfig()) {
374             quInfo() << "Successfully reloaded configuration";
375         }
376         break;
377 #endif
378     case SIGABRT:
379     case SIGSEGV:
380 #ifndef Q_OS_WIN
381     case SIGBUS:
382 #endif
383         instance()->logBacktrace(instance()->coreDumpFileName());
384         exit(EXIT_FAILURE);
385     default:
386         ;
387     }
388 }
389
390
391 void Quassel::disableCrashHandler()
392 {
393     instance()->_handleCrashes = false;
394 }
395
396
397 Quassel::RunMode Quassel::runMode() {
398     return instance()->_runMode;
399 }
400
401
402 void Quassel::setRunMode(RunMode runMode)
403 {
404     instance()->_runMode = runMode;
405 }
406
407
408 void Quassel::setCliParser(std::shared_ptr<AbstractCliParser> parser)
409 {
410     instance()->_cliParser = std::move(parser);
411 }
412
413
414 QString Quassel::optionValue(const QString &key)
415 {
416     return instance()->_cliParser ? instance()->_cliParser->value(key) : QString{};
417 }
418
419
420 bool Quassel::isOptionSet(const QString &key)
421 {
422     return instance()->_cliParser ? instance()->_cliParser->isSet(key) : false;
423 }
424
425
426 Quassel::LogLevel Quassel::logLevel()
427 {
428     return instance()->_logLevel;
429 }
430
431
432 void Quassel::setLogLevel(LogLevel logLevel)
433 {
434     instance()->_logLevel = logLevel;
435 }
436
437
438 QFile *Quassel::logFile() {
439     return instance()->_logFile.get();
440 }
441
442
443 bool Quassel::logToSyslog()
444 {
445     return instance()->_logToSyslog;
446 }
447
448
449 void Quassel::logFatalMessage(const char *msg)
450 {
451 #ifdef Q_OS_MAC
452     Q_UNUSED(msg)
453 #else
454     QFile dumpFile(instance()->coreDumpFileName());
455     dumpFile.open(QIODevice::Append);
456     QTextStream dumpStream(&dumpFile);
457
458     dumpStream << "Fatal: " << msg << '\n';
459     dumpStream.flush();
460     dumpFile.close();
461 #endif
462 }
463
464
465 const QString &Quassel::coreDumpFileName()
466 {
467     if (_coreDumpFileName.isEmpty()) {
468         QDir configDir(configDirPath());
469         _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
470         QFile dumpFile(_coreDumpFileName);
471         dumpFile.open(QIODevice::Append);
472         QTextStream dumpStream(&dumpFile);
473         dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
474         qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
475         dumpStream.flush();
476         dumpFile.close();
477     }
478     return _coreDumpFileName;
479 }
480
481
482 QString Quassel::configDirPath()
483 {
484     if (!instance()->_configDirPath.isEmpty())
485         return instance()->_configDirPath;
486
487     QString path;
488     if (isOptionSet("datadir")) {
489         qWarning() << "Obsolete option --datadir used!";
490         path = Quassel::optionValue("datadir");
491     }
492     else if (isOptionSet("configdir")) {
493         path = Quassel::optionValue("configdir");
494     }
495     else {
496 #ifdef Q_OS_MAC
497         // On Mac, the path is always the same
498         path = QDir::homePath() + "/Library/Application Support/Quassel/";
499 #else
500         // We abuse QSettings to find us a sensible path on the other platforms
501 #  ifdef Q_OS_WIN
502         // don't use the registry
503         QSettings::Format format = QSettings::IniFormat;
504 #  else
505         QSettings::Format format = QSettings::NativeFormat;
506 #  endif
507         QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
508         QFileInfo fileInfo(s.fileName());
509         path = fileInfo.dir().absolutePath();
510 #endif /* Q_OS_MAC */
511     }
512
513     path = QFileInfo{path}.absoluteFilePath();
514
515     if (!path.endsWith(QDir::separator()) && !path.endsWith('/'))
516         path += QDir::separator();
517
518     QDir qDir{path};
519     if (!qDir.exists(path)) {
520         if (!qDir.mkpath(path)) {
521             qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
522             return {};
523         }
524     }
525
526     instance()->_configDirPath = path;
527     return path;
528 }
529
530
531 void Quassel::setDataDirPaths(const QStringList &paths) {
532     instance()->_dataDirPaths = paths;
533 }
534
535
536 QStringList Quassel::dataDirPaths()
537 {
538     return instance()->_dataDirPaths;
539 }
540
541
542 QStringList Quassel::findDataDirPaths()
543 {
544     // TODO Qt5
545     // We don't use QStandardPaths for now, as we still need to provide fallbacks for Qt4 and
546     // want to stay consistent.
547
548     QStringList dataDirNames;
549 #ifdef Q_OS_WIN
550     dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
551                  << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
552                  << QCoreApplication::applicationDirPath();
553 #elif defined Q_OS_MAC
554     dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
555                  << QCoreApplication::applicationDirPath();
556 #else
557     // Linux et al
558
559     // XDG_DATA_HOME is the location for users to override system-installed files, usually in .local/share
560     // This should thus come first.
561     QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
562     if (xdgDataHome.isEmpty())
563         xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
564     dataDirNames << xdgDataHome;
565
566     // Now whatever is configured through XDG_DATA_DIRS
567     QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
568     if (xdgDataDirs.isEmpty())
569         dataDirNames << "/usr/local/share" << "/usr/share";
570     else
571         dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
572
573     // Just in case, also check our install prefix
574     dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
575
576     // Normalize and append our application name
577     for (int i = 0; i < dataDirNames.count(); i++)
578         dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/";
579
580 #endif
581
582     // Add resource path and workdir just in case.
583     // Workdir should have precedence
584     dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
585     dataDirNames.append(":/data/");
586
587     // Append trailing '/' and check for existence
588     auto iter = dataDirNames.begin();
589     while (iter != dataDirNames.end()) {
590         if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
591             iter->append(QDir::separator());
592         if (!QFile::exists(*iter))
593             iter = dataDirNames.erase(iter);
594         else
595             ++iter;
596     }
597
598     dataDirNames.removeDuplicates();
599
600     return dataDirNames;
601 }
602
603
604 QString Quassel::findDataFilePath(const QString &fileName)
605 {
606     QStringList dataDirs = dataDirPaths();
607     foreach(QString dataDir, dataDirs) {
608         QString path = dataDir + fileName;
609         if (QFile::exists(path))
610             return path;
611     }
612     return QString();
613 }
614
615
616 QStringList Quassel::scriptDirPaths()
617 {
618     QStringList res(configDirPath() + "scripts/");
619     foreach(QString path, dataDirPaths())
620     res << path + "scripts/";
621     return res;
622 }
623
624
625 QString Quassel::translationDirPath()
626 {
627     if (instance()->_translationDirPath.isEmpty()) {
628         // We support only one translation dir; fallback mechanisms wouldn't work else.
629         // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
630         foreach(const QString &dir, dataDirPaths()) {
631             if (QFile::exists(dir + "translations/")) {
632                 instance()->_translationDirPath = dir + "translations/";
633                 break;
634             }
635         }
636         if (instance()->_translationDirPath.isEmpty())
637             instance()->_translationDirPath = ":/i18n/";
638     }
639     return instance()->_translationDirPath;
640 }
641
642
643 void Quassel::loadTranslation(const QLocale &locale)
644 {
645     QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
646     QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
647
648     if (qtTranslator)
649         qApp->removeTranslator(qtTranslator);
650     if (quasselTranslator)
651         qApp->removeTranslator(quasselTranslator);
652
653     // We use QLocale::C to indicate that we don't want a translation
654     if (locale.language() == QLocale::C)
655         return;
656
657     qtTranslator = new QTranslator(qApp);
658     qtTranslator->setObjectName("QtTr");
659     qApp->installTranslator(qtTranslator);
660
661     quasselTranslator = new QTranslator(qApp);
662     quasselTranslator->setObjectName("QuasselTr");
663     qApp->installTranslator(quasselTranslator);
664
665 #if QT_VERSION >= 0x040800 && !defined Q_OS_MAC
666     bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
667     if (!success)
668         qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
669     quasselTranslator->load(locale, QString(""), translationDirPath());
670 #else
671     bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
672     if (!success)
673         qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
674     quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());
675 #endif
676 }
677
678
679 // ---- Quassel::Features ---------------------------------------------------------------------------------------------
680
681 Quassel::Features::Features()
682 {
683     QStringList features;
684
685     // TODO Qt5: Use QMetaEnum::fromType()
686     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
687     _features.resize(featureEnum.keyCount(), true);  // enable all known features to true
688 }
689
690
691 Quassel::Features::Features(const QStringList &features, LegacyFeatures legacyFeatures)
692 {
693     // TODO Qt5: Use QMetaEnum::fromType()
694     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
695     _features.resize(featureEnum.keyCount(), false);
696
697     for (auto &&feature : features) {
698         int i = featureEnum.keyToValue(qPrintable(feature));
699         if (i >= 0) {
700             _features[i] = true;
701         }
702         else {
703             _unknownFeatures << feature;
704         }
705     }
706
707     if (legacyFeatures) {
708         // TODO Qt5: Use QMetaEnum::fromType()
709         auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
710         for (quint32 mask = 0x0001; mask <= 0x8000; mask <<=1) {
711             if (static_cast<quint32>(legacyFeatures) & mask) {
712                 int i = featureEnum.keyToValue(legacyFeatureEnum.valueToKey(mask));
713                 if (i >= 0) {
714                     _features[i] = true;
715                 }
716             }
717         }
718     }
719 }
720
721
722 bool Quassel::Features::isEnabled(Feature feature) const
723 {
724     size_t i = static_cast<size_t>(feature);
725     return i < _features.size() ? _features[i] : false;
726 }
727
728
729 QStringList Quassel::Features::toStringList(bool enabled) const
730 {
731     // Check if any feature is enabled
732     if (!enabled && std::all_of(_features.cbegin(), _features.cend(), [](bool feature) { return !feature; })) {
733         return QStringList{} << "NoFeatures";
734     }
735
736     QStringList result;
737
738     // TODO Qt5: Use QMetaEnum::fromType()
739     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
740     for (quint32 i = 0; i < _features.size(); ++i) {
741         if (_features[i] == enabled) {
742             result << featureEnum.key(i);
743         }
744     }
745     return result;
746 }
747
748
749 Quassel::LegacyFeatures Quassel::Features::toLegacyFeatures() const
750 {
751     // TODO Qt5: Use LegacyFeatures (flag operators for enum classes not supported in Qt4)
752     quint32 result{0};
753     // TODO Qt5: Use QMetaEnum::fromType()
754     auto featureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("Feature"));
755     auto legacyFeatureEnum = Quassel::staticMetaObject.enumerator(Quassel::staticMetaObject.indexOfEnumerator("LegacyFeature"));
756
757     for (quint32 i = 0; i < _features.size(); ++i) {
758         if (_features[i]) {
759             int v = legacyFeatureEnum.keyToValue(featureEnum.key(i));
760             if (v >= 0) {
761                 result |= v;
762             }
763         }
764     }
765     return static_cast<LegacyFeatures>(result);
766 }
767
768
769 QStringList Quassel::Features::unknownFeatures() const
770 {
771     return _unknownFeatures;
772 }