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