1 /***************************************************************************
2 * Copyright (C) 2005-2015 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
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>
31 #include <QCoreApplication>
34 #include <QHostAddress>
35 #include <QLibraryInfo>
37 #include <QTranslator>
40 #include "bufferinfo.h"
46 #include "syncableobject.h"
49 #include "../../version.h"
51 Quassel::BuildInfo Quassel::_buildInfo;
52 AbstractCliParser *Quassel::_cliParser = 0;
53 Quassel::RunMode Quassel::_runMode;
54 QString Quassel::_configDirPath;
55 QString Quassel::_translationDirPath;
56 QStringList Quassel::_dataDirPaths;
57 bool Quassel::_initialized = false;
58 bool Quassel::DEBUG = false;
59 QString Quassel::_coreDumpFileName;
60 Quassel *Quassel::_instance = 0;
61 bool Quassel::_handleCrashes = true;
62 Quassel::LogLevel Quassel::_logLevel = InfoLevel;
63 QFile *Quassel::_logFile = 0;
64 bool Quassel::_logToSyslog = false;
71 // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
72 signal(SIGTERM, handleSignal);
73 signal(SIGINT, handleSignal);
81 logFile()->deleteLater();
90 return true; // allow multiple invocations because of MonolithicApplication
93 // we have crashhandler for win32 and unix (based on execinfo).
94 #if defined(Q_OS_WIN) || defined(HAVE_EXECINFO)
96 // we only handle crashes ourselves if coredumps are disabled
97 struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit));
98 int rc = getrlimit(RLIMIT_CORE, limit);
100 if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
101 # endif /* Q_OS_WIN */
102 signal(SIGABRT, handleSignal);
103 signal(SIGSEGV, handleSignal);
105 signal(SIGBUS, handleSignal);
108 # endif /* Q_OS_WIN */
109 #endif /* Q_OS_WIN || HAVE_EXECINFO */
113 qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
118 Network::setDefaultCodecForServer("ISO-8859-1");
119 Network::setDefaultCodecForEncoding("UTF-8");
120 Network::setDefaultCodecForDecoding("ISO-8859-15");
122 if (isOptionSet("help")) {
123 cliParser()->usage();
127 if (isOptionSet("version")) {
128 std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
132 DEBUG = isOptionSet("debug");
135 if (Quassel::runMode() != Quassel::ClientOnly) {
136 if (isOptionSet("loglevel")) {
137 QString level = optionValue("loglevel");
139 if (level == "Debug") _logLevel = DebugLevel;
140 else if (level == "Info") _logLevel = InfoLevel;
141 else if (level == "Warning") _logLevel = WarningLevel;
142 else if (level == "Error") _logLevel = ErrorLevel;
145 QString logfilename = optionValue("logfile");
146 if (!logfilename.isEmpty()) {
147 _logFile = new QFile(logfilename);
148 if (!_logFile->open(QIODevice::Append | QIODevice::Text)) {
149 qWarning() << "Could not open log file" << logfilename << ":" << _logFile->errorString();
150 _logFile->deleteLater();
155 _logToSyslog = isOptionSet("syslog");
165 QCoreApplication::quit();
169 //! Register our custom types with Qt's Meta Object System.
170 /** This makes them available for QVariant and in signals/slots, among other things.
173 void Quassel::registerMetaTypes()
176 qRegisterMetaType<Message>("Message");
177 qRegisterMetaType<BufferInfo>("BufferInfo");
178 qRegisterMetaType<NetworkInfo>("NetworkInfo");
179 qRegisterMetaType<Network::Server>("Network::Server");
180 qRegisterMetaType<Identity>("Identity");
182 qRegisterMetaTypeStreamOperators<Message>("Message");
183 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
184 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
185 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
186 qRegisterMetaTypeStreamOperators<Identity>("Identity");
188 qRegisterMetaType<IdentityId>("IdentityId");
189 qRegisterMetaType<BufferId>("BufferId");
190 qRegisterMetaType<NetworkId>("NetworkId");
191 qRegisterMetaType<UserId>("UserId");
192 qRegisterMetaType<AccountId>("AccountId");
193 qRegisterMetaType<MsgId>("MsgId");
195 qRegisterMetaType<QHostAddress>("QHostAddress");
196 qRegisterMetaType<QUuid>("QUuid");
198 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
199 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
200 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
201 qRegisterMetaTypeStreamOperators<UserId>("UserId");
202 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
203 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
205 qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
207 // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
208 if (!QMetaType::type("QVariant")) {
209 qRegisterMetaType<QVariant>("QVariant");
210 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
215 void Quassel::setupEnvironment()
217 // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This
218 // is, for example, used by Qt for finding icons and other things. In case Quassel is installed in a non-standard
219 // prefix (or run from the build directory), it makes sense to add this to XDG_DATA_DIRS so we don't have to
220 // hack extra search paths into various places.
222 QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
223 if (xdgDataVar.isEmpty())
224 xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
226 QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
228 // Add our install prefix (if we're not in a bindir, this just adds the current workdir)
229 QString appDir = QCoreApplication::applicationDirPath();
230 int binpos = appDir.lastIndexOf("/bin");
232 appDir.replace(binpos, 4, "/share");
233 xdgDirs.append(appDir);
234 // Also append apps/quassel, this is only for QIconLoader to find icons there
235 xdgDirs.append(appDir + "/apps/quassel");
237 xdgDirs.append(appDir); // build directory is always the last fallback
239 xdgDirs.removeDuplicates();
241 qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
246 void Quassel::setupBuildInfo()
248 _buildInfo.applicationName = "quassel";
249 _buildInfo.coreApplicationName = "quasselcore";
250 _buildInfo.clientApplicationName = "quasselclient";
251 _buildInfo.organizationName = "Quassel Project";
252 _buildInfo.organizationDomain = "quassel-irc.org";
254 _buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
256 _buildInfo.baseVersion = QUASSEL_VERSION_STRING;
257 _buildInfo.generatedVersion = GIT_DESCRIBE;
259 // This will be imprecise for incremental builds not touching this file, but we really don't want to always recompile
260 _buildInfo.buildDate = QString("%1 %2").arg(__DATE__, __TIME__);
262 // Check if we got a commit hash
263 if (!QString(GIT_HEAD).isEmpty())
264 _buildInfo.commitHash = GIT_HEAD;
265 else if (!QString(DIST_HASH).contains("Format")) {
266 _buildInfo.commitHash = DIST_HASH;
267 _buildInfo.commitDate = QString(DIST_DATE).toUInt();
270 // create a nice version string
271 if (_buildInfo.generatedVersion.isEmpty()) {
272 if (!_buildInfo.commitHash.isEmpty()) {
274 _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
275 .arg(_buildInfo.baseVersion)
276 .arg(_buildInfo.commitHash.left(7));
277 _buildInfo.fancyVersionString = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
278 .arg(_buildInfo.baseVersion)
279 .arg(_buildInfo.commitHash.left(7))
280 .arg(_buildInfo.commitHash);
283 // we only have a base version :(
284 _buildInfo.plainVersionString = QString("v%1 (unknown revision)").arg(_buildInfo.baseVersion);
288 // analyze what we got from git-describe
289 QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)(-dirty)?$");
290 if (rx.exactMatch(_buildInfo.generatedVersion)) {
291 QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2));
292 _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)")
293 .arg(_buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4));
294 if (!_buildInfo.commitHash.isEmpty()) {
295 _buildInfo.fancyVersionString = QString("v%1 (%2git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
296 .arg(_buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), _buildInfo.commitHash);
300 _buildInfo.plainVersionString = QString("v%1 (invalid revision)").arg(_buildInfo.baseVersion);
303 if (_buildInfo.fancyVersionString.isEmpty())
304 _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
308 //! Signal handler for graceful shutdown.
309 void Quassel::handleSignal(int sig)
314 qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
318 QCoreApplication::quit();
325 logBacktrace(coreDumpFileName());
334 void Quassel::logFatalMessage(const char *msg)
339 QFile dumpFile(coreDumpFileName());
340 dumpFile.open(QIODevice::Append);
341 QTextStream dumpStream(&dumpFile);
343 dumpStream << "Fatal: " << msg << '\n';
350 Quassel::Features Quassel::features()
353 for (int i = 1; i <= NumFeatures; i <<= 1)
360 const QString &Quassel::coreDumpFileName()
362 if (_coreDumpFileName.isEmpty()) {
363 QDir configDir(configDirPath());
364 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
365 QFile dumpFile(_coreDumpFileName);
366 dumpFile.open(QIODevice::Append);
367 QTextStream dumpStream(&dumpFile);
368 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
369 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
373 return _coreDumpFileName;
377 QString Quassel::configDirPath()
379 if (!_configDirPath.isEmpty())
380 return _configDirPath;
382 if (Quassel::isOptionSet("datadir")) {
383 qWarning() << "Obsolete option --datadir used!";
384 _configDirPath = Quassel::optionValue("datadir");
386 else if (Quassel::isOptionSet("configdir")) {
387 _configDirPath = Quassel::optionValue("configdir");
391 // On Mac, the path is always the same
392 _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
394 // We abuse QSettings to find us a sensible path on the other platforms
396 // don't use the registry
397 QSettings::Format format = QSettings::IniFormat;
399 QSettings::Format format = QSettings::NativeFormat;
401 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
402 QFileInfo fileInfo(s.fileName());
403 _configDirPath = fileInfo.dir().absolutePath();
404 #endif /* Q_OS_MAC */
407 if (!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
408 _configDirPath += QDir::separator();
410 QDir qDir(_configDirPath);
411 if (!qDir.exists(_configDirPath)) {
412 if (!qDir.mkpath(_configDirPath)) {
413 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
418 return _configDirPath;
422 QStringList Quassel::dataDirPaths()
424 return _dataDirPaths;
428 QStringList Quassel::findDataDirPaths() const
430 // We don't use QStandardPaths for now, as we still need to provide fallbacks for Qt4 and
431 // want to stay consistent.
433 QStringList dataDirNames;
435 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
436 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
437 << QCoreApplication::applicationDirPath();
438 #elif defined Q_OS_MAC
439 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
440 << QCoreApplication::applicationDirPath();
444 // XDG_DATA_HOME is the location for users to override system-installed files, usually in .local/share
445 // This should thus come first.
446 QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
447 if (xdgDataHome.isEmpty())
448 xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
449 dataDirNames << xdgDataHome;
451 // Now whatever is configured through XDG_DATA_DIRS
452 QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
453 if (xdgDataDirs.isEmpty())
454 dataDirNames << "/usr/local/share" << "/usr/share";
456 dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
458 // Just in case, also check our install prefix
459 dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
461 // Normalize and append our application name
462 for (int i = 0; i < dataDirNames.count(); i++)
463 dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/";
467 // Add resource path and workdir just in case.
468 // Workdir should have precedence
469 dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
470 dataDirNames.append(":/data/");
472 // Append trailing '/' and check for existence
473 auto iter = dataDirNames.begin();
474 while (iter != dataDirNames.end()) {
475 if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
476 iter->append(QDir::separator());
477 if (!QFile::exists(*iter))
478 iter = dataDirNames.erase(iter);
483 dataDirNames.removeDuplicates();
489 QString Quassel::findDataFilePath(const QString &fileName)
491 QStringList dataDirs = dataDirPaths();
492 foreach(QString dataDir, dataDirs) {
493 QString path = dataDir + fileName;
494 if (QFile::exists(path))
501 QStringList Quassel::scriptDirPaths()
503 QStringList res(configDirPath() + "scripts/");
504 foreach(QString path, dataDirPaths())
505 res << path + "scripts/";
510 QString Quassel::translationDirPath()
512 if (_translationDirPath.isEmpty()) {
513 // We support only one translation dir; fallback mechanisms wouldn't work else.
514 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
515 foreach(const QString &dir, dataDirPaths()) {
516 if (QFile::exists(dir + "translations/")) {
517 _translationDirPath = dir + "translations/";
521 if (_translationDirPath.isEmpty())
522 _translationDirPath = ":/i18n/";
524 return _translationDirPath;
528 void Quassel::loadTranslation(const QLocale &locale)
530 QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
531 QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
534 qApp->removeTranslator(qtTranslator);
535 if (quasselTranslator)
536 qApp->removeTranslator(quasselTranslator);
538 // We use QLocale::C to indicate that we don't want a translation
539 if (locale.language() == QLocale::C)
542 qtTranslator = new QTranslator(qApp);
543 qtTranslator->setObjectName("QtTr");
544 qApp->installTranslator(qtTranslator);
546 quasselTranslator = new QTranslator(qApp);
547 quasselTranslator->setObjectName("QuasselTr");
548 qApp->installTranslator(quasselTranslator);
550 #if QT_VERSION >= 0x040800 && !defined Q_OS_MAC
551 bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
553 qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
554 quasselTranslator->load(locale, QString(""), translationDirPath());
556 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
558 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
559 quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());