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"
47 #include "syncableobject.h"
50 #include "../../version.h"
52 Quassel::BuildInfo Quassel::_buildInfo;
53 AbstractCliParser *Quassel::_cliParser = 0;
54 Quassel::RunMode Quassel::_runMode;
55 QString Quassel::_configDirPath;
56 QString Quassel::_translationDirPath;
57 QStringList Quassel::_dataDirPaths;
58 bool Quassel::_initialized = false;
59 bool Quassel::DEBUG = false;
60 QString Quassel::_coreDumpFileName;
61 Quassel *Quassel::_instance = 0;
62 bool Quassel::_handleCrashes = true;
63 Quassel::LogLevel Quassel::_logLevel = InfoLevel;
64 QFile *Quassel::_logFile = 0;
65 bool Quassel::_logToSyslog = false;
72 // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
73 signal(SIGTERM, handleSignal);
74 signal(SIGINT, handleSignal);
82 logFile()->deleteLater();
91 return true; // allow multiple invocations because of MonolithicApplication
94 // we have crashhandler for win32 and unix (based on execinfo).
95 #if defined(Q_OS_WIN) || defined(HAVE_EXECINFO)
97 // we only handle crashes ourselves if coredumps are disabled
98 struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit));
99 int rc = getrlimit(RLIMIT_CORE, limit);
101 if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
102 # endif /* Q_OS_WIN */
103 signal(SIGABRT, handleSignal);
104 signal(SIGSEGV, handleSignal);
106 signal(SIGBUS, handleSignal);
109 # endif /* Q_OS_WIN */
110 #endif /* Q_OS_WIN || HAVE_EXECINFO */
114 qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
119 Network::setDefaultCodecForServer("ISO-8859-1");
120 Network::setDefaultCodecForEncoding("UTF-8");
121 Network::setDefaultCodecForDecoding("ISO-8859-15");
123 if (isOptionSet("help")) {
124 cliParser()->usage();
128 if (isOptionSet("version")) {
129 std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
133 DEBUG = isOptionSet("debug");
136 if (Quassel::runMode() != Quassel::ClientOnly) {
137 if (isOptionSet("loglevel")) {
138 QString level = optionValue("loglevel");
140 if (level == "Debug") _logLevel = DebugLevel;
141 else if (level == "Info") _logLevel = InfoLevel;
142 else if (level == "Warning") _logLevel = WarningLevel;
143 else if (level == "Error") _logLevel = ErrorLevel;
146 QString logfilename = optionValue("logfile");
147 if (!logfilename.isEmpty()) {
148 _logFile = new QFile(logfilename);
149 if (!_logFile->open(QIODevice::Append | QIODevice::Text)) {
150 qWarning() << "Could not open log file" << logfilename << ":" << _logFile->errorString();
151 _logFile->deleteLater();
156 _logToSyslog = isOptionSet("syslog");
166 QCoreApplication::quit();
170 //! Register our custom types with Qt's Meta Object System.
171 /** This makes them available for QVariant and in signals/slots, among other things.
174 void Quassel::registerMetaTypes()
177 qRegisterMetaType<Message>("Message");
178 qRegisterMetaType<BufferInfo>("BufferInfo");
179 qRegisterMetaType<NetworkInfo>("NetworkInfo");
180 qRegisterMetaType<Network::Server>("Network::Server");
181 qRegisterMetaType<Identity>("Identity");
183 qRegisterMetaTypeStreamOperators<Message>("Message");
184 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
185 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
186 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
187 qRegisterMetaTypeStreamOperators<Identity>("Identity");
189 qRegisterMetaType<IdentityId>("IdentityId");
190 qRegisterMetaType<BufferId>("BufferId");
191 qRegisterMetaType<NetworkId>("NetworkId");
192 qRegisterMetaType<UserId>("UserId");
193 qRegisterMetaType<AccountId>("AccountId");
194 qRegisterMetaType<MsgId>("MsgId");
196 qRegisterMetaType<QHostAddress>("QHostAddress");
197 qRegisterMetaType<QUuid>("QUuid");
199 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
200 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
201 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
202 qRegisterMetaTypeStreamOperators<UserId>("UserId");
203 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
204 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
206 qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
207 qRegisterMetaType<PeerPtr>("PeerPtr");
208 qRegisterMetaTypeStreamOperators<PeerPtr>("PeerPtr");
210 // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
211 if (!QMetaType::type("QVariant")) {
212 qRegisterMetaType<QVariant>("QVariant");
213 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
218 void Quassel::setupEnvironment()
220 // On modern Linux systems, XDG_DATA_DIRS contains a list of directories containing application data. This
221 // is, for example, used by Qt for finding icons and other things. In case Quassel is installed in a non-standard
222 // prefix (or run from the build directory), it makes sense to add this to XDG_DATA_DIRS so we don't have to
223 // hack extra search paths into various places.
225 QString xdgDataVar = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
226 if (xdgDataVar.isEmpty())
227 xdgDataVar = QLatin1String("/usr/local/share:/usr/share"); // sane defaults
229 QStringList xdgDirs = xdgDataVar.split(QLatin1Char(':'), QString::SkipEmptyParts);
231 // Add our install prefix (if we're not in a bindir, this just adds the current workdir)
232 QString appDir = QCoreApplication::applicationDirPath();
233 int binpos = appDir.lastIndexOf("/bin");
235 appDir.replace(binpos, 4, "/share");
236 xdgDirs.append(appDir);
237 // Also append apps/quassel, this is only for QIconLoader to find icons there
238 xdgDirs.append(appDir + "/apps/quassel");
240 xdgDirs.append(appDir); // build directory is always the last fallback
242 xdgDirs.removeDuplicates();
244 qputenv("XDG_DATA_DIRS", QFile::encodeName(xdgDirs.join(":")));
249 void Quassel::setupBuildInfo()
251 _buildInfo.applicationName = "quassel";
252 _buildInfo.coreApplicationName = "quasselcore";
253 _buildInfo.clientApplicationName = "quasselclient";
254 _buildInfo.organizationName = "Quassel Project";
255 _buildInfo.organizationDomain = "quassel-irc.org";
257 _buildInfo.protocolVersion = 10; // FIXME: deprecated, will be removed
259 _buildInfo.baseVersion = QUASSEL_VERSION_STRING;
260 _buildInfo.generatedVersion = GIT_DESCRIBE;
262 // Check if we got a commit hash
263 if (!QString(GIT_HEAD).isEmpty()) {
264 _buildInfo.commitHash = GIT_HEAD;
266 date.setTime_t(GIT_COMMIT_DATE);
267 _buildInfo.commitDate = date.toString();
269 else if (!QString(DIST_HASH).contains("Format")) {
270 _buildInfo.commitHash = DIST_HASH;
271 _buildInfo.commitDate = QString(DIST_DATE);
274 // create a nice version string
275 if (_buildInfo.generatedVersion.isEmpty()) {
276 if (!_buildInfo.commitHash.isEmpty()) {
278 _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
279 .arg(_buildInfo.baseVersion)
280 .arg(_buildInfo.commitHash.left(7));
281 _buildInfo.fancyVersionString = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
282 .arg(_buildInfo.baseVersion)
283 .arg(_buildInfo.commitHash.left(7))
284 .arg(_buildInfo.commitHash);
287 // we only have a base version :(
288 _buildInfo.plainVersionString = QString("v%1 (unknown revision)").arg(_buildInfo.baseVersion);
292 // analyze what we got from git-describe
293 QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)(-dirty)?$");
294 if (rx.exactMatch(_buildInfo.generatedVersion)) {
295 QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2));
296 _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)")
297 .arg(_buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4));
298 if (!_buildInfo.commitHash.isEmpty()) {
299 _buildInfo.fancyVersionString = QString("v%1 (%2git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
300 .arg(_buildInfo.baseVersion, distance, rx.cap(3), rx.cap(4), _buildInfo.commitHash);
304 _buildInfo.plainVersionString = QString("v%1 (invalid revision)").arg(_buildInfo.baseVersion);
307 if (_buildInfo.fancyVersionString.isEmpty())
308 _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
312 //! Signal handler for graceful shutdown.
313 void Quassel::handleSignal(int sig)
318 qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
322 QCoreApplication::quit();
329 logBacktrace(coreDumpFileName());
338 void Quassel::logFatalMessage(const char *msg)
343 QFile dumpFile(coreDumpFileName());
344 dumpFile.open(QIODevice::Append);
345 QTextStream dumpStream(&dumpFile);
347 dumpStream << "Fatal: " << msg << '\n';
354 Quassel::Features Quassel::features()
357 for (int i = 1; i <= NumFeatures; i <<= 1)
364 const QString &Quassel::coreDumpFileName()
366 if (_coreDumpFileName.isEmpty()) {
367 QDir configDir(configDirPath());
368 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
369 QFile dumpFile(_coreDumpFileName);
370 dumpFile.open(QIODevice::Append);
371 QTextStream dumpStream(&dumpFile);
372 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
373 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
377 return _coreDumpFileName;
381 QString Quassel::configDirPath()
383 if (!_configDirPath.isEmpty())
384 return _configDirPath;
386 if (Quassel::isOptionSet("datadir")) {
387 qWarning() << "Obsolete option --datadir used!";
388 _configDirPath = Quassel::optionValue("datadir");
390 else if (Quassel::isOptionSet("configdir")) {
391 _configDirPath = Quassel::optionValue("configdir");
395 // On Mac, the path is always the same
396 _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
398 // We abuse QSettings to find us a sensible path on the other platforms
400 // don't use the registry
401 QSettings::Format format = QSettings::IniFormat;
403 QSettings::Format format = QSettings::NativeFormat;
405 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
406 QFileInfo fileInfo(s.fileName());
407 _configDirPath = fileInfo.dir().absolutePath();
408 #endif /* Q_OS_MAC */
411 if (!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
412 _configDirPath += QDir::separator();
414 QDir qDir(_configDirPath);
415 if (!qDir.exists(_configDirPath)) {
416 if (!qDir.mkpath(_configDirPath)) {
417 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
422 return _configDirPath;
426 QStringList Quassel::dataDirPaths()
428 return _dataDirPaths;
432 QStringList Quassel::findDataDirPaths() const
434 // We don't use QStandardPaths for now, as we still need to provide fallbacks for Qt4 and
435 // want to stay consistent.
437 QStringList dataDirNames;
439 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
440 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
441 << QCoreApplication::applicationDirPath();
442 #elif defined Q_OS_MAC
443 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
444 << QCoreApplication::applicationDirPath();
448 // XDG_DATA_HOME is the location for users to override system-installed files, usually in .local/share
449 // This should thus come first.
450 QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
451 if (xdgDataHome.isEmpty())
452 xdgDataHome = QDir::homePath() + QLatin1String("/.local/share");
453 dataDirNames << xdgDataHome;
455 // Now whatever is configured through XDG_DATA_DIRS
456 QString xdgDataDirs = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
457 if (xdgDataDirs.isEmpty())
458 dataDirNames << "/usr/local/share" << "/usr/share";
460 dataDirNames << xdgDataDirs.split(':', QString::SkipEmptyParts);
462 // Just in case, also check our install prefix
463 dataDirNames << QCoreApplication::applicationDirPath() + "/../share";
465 // Normalize and append our application name
466 for (int i = 0; i < dataDirNames.count(); i++)
467 dataDirNames[i] = QDir::cleanPath(dataDirNames.at(i)) + "/quassel/";
471 // Add resource path and workdir just in case.
472 // Workdir should have precedence
473 dataDirNames.prepend(QCoreApplication::applicationDirPath() + "/data/");
474 dataDirNames.append(":/data/");
476 // Append trailing '/' and check for existence
477 auto iter = dataDirNames.begin();
478 while (iter != dataDirNames.end()) {
479 if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
480 iter->append(QDir::separator());
481 if (!QFile::exists(*iter))
482 iter = dataDirNames.erase(iter);
487 dataDirNames.removeDuplicates();
493 QString Quassel::findDataFilePath(const QString &fileName)
495 QStringList dataDirs = dataDirPaths();
496 foreach(QString dataDir, dataDirs) {
497 QString path = dataDir + fileName;
498 if (QFile::exists(path))
505 QStringList Quassel::scriptDirPaths()
507 QStringList res(configDirPath() + "scripts/");
508 foreach(QString path, dataDirPaths())
509 res << path + "scripts/";
514 QString Quassel::translationDirPath()
516 if (_translationDirPath.isEmpty()) {
517 // We support only one translation dir; fallback mechanisms wouldn't work else.
518 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
519 foreach(const QString &dir, dataDirPaths()) {
520 if (QFile::exists(dir + "translations/")) {
521 _translationDirPath = dir + "translations/";
525 if (_translationDirPath.isEmpty())
526 _translationDirPath = ":/i18n/";
528 return _translationDirPath;
532 void Quassel::loadTranslation(const QLocale &locale)
534 QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
535 QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
538 qApp->removeTranslator(qtTranslator);
539 if (quasselTranslator)
540 qApp->removeTranslator(quasselTranslator);
542 // We use QLocale::C to indicate that we don't want a translation
543 if (locale.language() == QLocale::C)
546 qtTranslator = new QTranslator(qApp);
547 qtTranslator->setObjectName("QtTr");
548 qApp->installTranslator(qtTranslator);
550 quasselTranslator = new QTranslator(qApp);
551 quasselTranslator->setObjectName("QuasselTr");
552 qApp->installTranslator(quasselTranslator);
554 #if QT_VERSION >= 0x040800 && !defined Q_OS_MAC
555 bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
557 qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
558 quasselTranslator->load(locale, QString(""), translationDirPath());
560 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
562 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
563 quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());