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