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