1 /***************************************************************************
2 * Copyright (C) 2005-2014 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_WIN32 && !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 Quassel::BuildInfo Quassel::_buildInfo;
50 AbstractCliParser *Quassel::_cliParser = 0;
51 Quassel::RunMode Quassel::_runMode;
52 QString Quassel::_configDirPath;
53 QString Quassel::_translationDirPath;
54 QStringList Quassel::_dataDirPaths;
55 bool Quassel::_initialized = false;
56 bool Quassel::DEBUG = false;
57 QString Quassel::_coreDumpFileName;
58 Quassel *Quassel::_instance = 0;
59 bool Quassel::_handleCrashes = true;
60 Quassel::LogLevel Quassel::_logLevel = InfoLevel;
61 QFile *Quassel::_logFile = 0;
62 bool Quassel::_logToSyslog = false;
69 // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
70 signal(SIGTERM, handleSignal);
71 signal(SIGINT, handleSignal);
79 logFile()->deleteLater();
88 return true; // allow multiple invocations because of MonolithicApplication
91 // we have crashhandler for win32 and unix (based on execinfo).
92 #if defined(Q_OS_WIN32) || defined(HAVE_EXECINFO)
94 // we only handle crashes ourselves if coredumps are disabled
95 struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit));
96 int rc = getrlimit(RLIMIT_CORE, limit);
98 if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
99 # endif /* Q_OS_WIN32 */
100 signal(SIGABRT, handleSignal);
101 signal(SIGSEGV, handleSignal);
103 signal(SIGBUS, handleSignal);
106 # endif /* Q_OS_WIN32 */
107 #endif /* Q_OS_WIN32 || HAVE_EXECINFO */
111 qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
115 Network::setDefaultCodecForServer("ISO-8859-1");
116 Network::setDefaultCodecForEncoding("UTF-8");
117 Network::setDefaultCodecForDecoding("ISO-8859-15");
119 if (isOptionSet("help")) {
120 cliParser()->usage();
124 if (isOptionSet("version")) {
125 std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
129 DEBUG = isOptionSet("debug");
132 if (Quassel::runMode() != Quassel::ClientOnly) {
133 if (isOptionSet("loglevel")) {
134 QString level = optionValue("loglevel");
136 if (level == "Debug") _logLevel = DebugLevel;
137 else if (level == "Info") _logLevel = InfoLevel;
138 else if (level == "Warning") _logLevel = WarningLevel;
139 else if (level == "Error") _logLevel = ErrorLevel;
142 QString logfilename = optionValue("logfile");
143 if (!logfilename.isEmpty()) {
144 _logFile = new QFile(logfilename);
145 if (!_logFile->open(QIODevice::Append | QIODevice::Text)) {
146 qWarning() << "Could not open log file" << logfilename << ":" << _logFile->errorString();
147 _logFile->deleteLater();
152 _logToSyslog = isOptionSet("syslog");
162 QCoreApplication::quit();
166 //! Register our custom types with Qt's Meta Object System.
167 /** This makes them available for QVariant and in signals/slots, among other things.
170 void Quassel::registerMetaTypes()
173 qRegisterMetaType<Message>("Message");
174 qRegisterMetaType<BufferInfo>("BufferInfo");
175 qRegisterMetaType<NetworkInfo>("NetworkInfo");
176 qRegisterMetaType<Network::Server>("Network::Server");
177 qRegisterMetaType<Identity>("Identity");
179 qRegisterMetaTypeStreamOperators<Message>("Message");
180 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
181 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
182 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
183 qRegisterMetaTypeStreamOperators<Identity>("Identity");
185 qRegisterMetaType<IdentityId>("IdentityId");
186 qRegisterMetaType<BufferId>("BufferId");
187 qRegisterMetaType<NetworkId>("NetworkId");
188 qRegisterMetaType<UserId>("UserId");
189 qRegisterMetaType<AccountId>("AccountId");
190 qRegisterMetaType<MsgId>("MsgId");
192 qRegisterMetaType<QHostAddress>("QHostAddress");
193 qRegisterMetaType<QUuid>("QUuid");
195 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
196 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
197 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
198 qRegisterMetaTypeStreamOperators<UserId>("UserId");
199 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
200 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
202 qRegisterMetaType<Protocol::SessionState>("Protocol::SessionState");
204 // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
205 if (!QMetaType::type("QVariant")) {
206 qRegisterMetaType<QVariant>("QVariant");
207 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
212 void Quassel::setupBuildInfo(const QString &generated)
214 _buildInfo.applicationName = "Quassel IRC";
215 _buildInfo.coreApplicationName = "quasselcore";
216 _buildInfo.clientApplicationName = "quasselclient";
217 _buildInfo.organizationName = "Quassel Project";
218 _buildInfo.organizationDomain = "quassel-irc.org";
220 QStringList gen = generated.split(',');
221 Q_ASSERT(gen.count() == 10);
222 _buildInfo.baseVersion = gen[0];
223 _buildInfo.generatedVersion = gen[1];
224 _buildInfo.isSourceDirty = !gen[2].isEmpty();
225 _buildInfo.commitHash = gen[3];
226 _buildInfo.commitDate = gen[4].toUInt();
227 _buildInfo.protocolVersion = gen[5].toUInt();
228 _buildInfo.clientNeedsProtocol = gen[6].toUInt();
229 _buildInfo.coreNeedsProtocol = gen[7].toUInt();
230 _buildInfo.buildDate = QString("%1 %2").arg(gen[8], gen[9]);
231 // create a nice version string
232 if (_buildInfo.generatedVersion.isEmpty()) {
233 if (!_buildInfo.commitHash.isEmpty()) {
235 _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
236 .arg(_buildInfo.baseVersion)
237 .arg(_buildInfo.commitHash.left(7));
238 _buildInfo.fancyVersionString = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
239 .arg(_buildInfo.baseVersion)
240 .arg(_buildInfo.commitHash.left(7))
241 .arg(_buildInfo.commitHash);
244 // we only have a base version :(
245 _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
249 // analyze what we got from git-describe
250 QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
251 if (rx.exactMatch(_buildInfo.generatedVersion)) {
252 QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2));
253 _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)")
254 .arg(_buildInfo.baseVersion, distance, rx.cap(3))
255 .arg(_buildInfo.isSourceDirty ? "*" : "");
256 if (!_buildInfo.commitHash.isEmpty()) {
257 _buildInfo.fancyVersionString = QString("v%1 (%2git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
258 .arg(_buildInfo.baseVersion, distance, rx.cap(3))
259 .arg(_buildInfo.isSourceDirty ? "*" : "")
260 .arg(_buildInfo.commitHash);
264 _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
267 if (_buildInfo.fancyVersionString.isEmpty())
268 _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
272 //! Signal handler for graceful shutdown.
273 void Quassel::handleSignal(int sig)
278 qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
282 QCoreApplication::quit();
289 logBacktrace(coreDumpFileName());
298 void Quassel::logFatalMessage(const char *msg)
303 QFile dumpFile(coreDumpFileName());
304 dumpFile.open(QIODevice::Append);
305 QTextStream dumpStream(&dumpFile);
307 dumpStream << "Fatal: " << msg << '\n';
314 Quassel::Features Quassel::features()
317 for (int i = 1; i <= NumFeatures; i <<= 1)
324 const QString &Quassel::coreDumpFileName()
326 if (_coreDumpFileName.isEmpty()) {
327 QDir configDir(configDirPath());
328 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
329 QFile dumpFile(_coreDumpFileName);
330 dumpFile.open(QIODevice::Append);
331 QTextStream dumpStream(&dumpFile);
332 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
333 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
337 return _coreDumpFileName;
341 QString Quassel::configDirPath()
343 if (!_configDirPath.isEmpty())
344 return _configDirPath;
346 if (Quassel::isOptionSet("datadir")) {
347 qWarning() << "Obsolete option --datadir used!";
348 _configDirPath = Quassel::optionValue("datadir");
350 else if (Quassel::isOptionSet("configdir")) {
351 _configDirPath = Quassel::optionValue("configdir");
355 // On Mac, the path is always the same
356 _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
358 // We abuse QSettings to find us a sensible path on the other platforms
360 // don't use the registry
361 QSettings::Format format = QSettings::IniFormat;
363 QSettings::Format format = QSettings::NativeFormat;
365 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
366 QFileInfo fileInfo(s.fileName());
367 _configDirPath = fileInfo.dir().absolutePath();
368 #endif /* Q_WS_MAC */
371 if (!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
372 _configDirPath += QDir::separator();
374 QDir qDir(_configDirPath);
375 if (!qDir.exists(_configDirPath)) {
376 if (!qDir.mkpath(_configDirPath)) {
377 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
382 return _configDirPath;
386 QStringList Quassel::dataDirPaths()
388 return _dataDirPaths;
392 QStringList Quassel::findDataDirPaths() const
394 QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
396 if (!dataDirNames.isEmpty()) {
397 for (int i = 0; i < dataDirNames.count(); i++)
398 dataDirNames[i].append("/apps/quassel/");
401 // Provide a fallback
403 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
404 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
405 << QCoreApplication::applicationDirPath();
407 #elif defined Q_WS_MAC
408 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
409 << QCoreApplication::applicationDirPath();
412 dataDirNames.append("/usr/share/apps/quassel/");
414 // on UNIX, we always check our install prefix
415 QString appDir = QCoreApplication::applicationDirPath();
416 int binpos = appDir.lastIndexOf("/bin");
418 appDir.replace(binpos, 4, "/share");
419 appDir.append("/apps/quassel/");
420 if (!dataDirNames.contains(appDir))
421 dataDirNames.append(appDir);
425 // add resource path and workdir just in case
426 dataDirNames << QCoreApplication::applicationDirPath() + "/data/"
429 // append trailing '/' and check for existence
430 QStringList::Iterator iter = dataDirNames.begin();
431 while (iter != dataDirNames.end()) {
432 if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
433 iter->append(QDir::separator());
434 if (!QFile::exists(*iter))
435 iter = dataDirNames.erase(iter);
444 QString Quassel::findDataFilePath(const QString &fileName)
446 QStringList dataDirs = dataDirPaths();
447 foreach(QString dataDir, dataDirs) {
448 QString path = dataDir + fileName;
449 if (QFile::exists(path))
456 QStringList Quassel::scriptDirPaths()
458 QStringList res(configDirPath() + "scripts/");
459 foreach(QString path, dataDirPaths())
460 res << path + "scripts/";
465 QString Quassel::translationDirPath()
467 if (_translationDirPath.isEmpty()) {
468 // We support only one translation dir; fallback mechanisms wouldn't work else.
469 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
470 foreach(const QString &dir, dataDirPaths()) {
471 if (QFile::exists(dir + "translations/")) {
472 _translationDirPath = dir + "translations/";
476 if (_translationDirPath.isEmpty())
477 _translationDirPath = ":/i18n/";
479 return _translationDirPath;
483 void Quassel::loadTranslation(const QLocale &locale)
485 QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
486 QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
489 qApp->removeTranslator(qtTranslator);
490 if (quasselTranslator)
491 qApp->removeTranslator(quasselTranslator);
493 // We use QLocale::C to indicate that we don't want a translation
494 if (locale.language() == QLocale::C)
497 qtTranslator = new QTranslator(qApp);
498 qtTranslator->setObjectName("QtTr");
499 qApp->installTranslator(qtTranslator);
501 quasselTranslator = new QTranslator(qApp);
502 quasselTranslator->setObjectName("QuasselTr");
503 qApp->installTranslator(quasselTranslator);
505 #if QT_VERSION >= 0x040800 && !defined Q_OS_MAC
506 bool success = qtTranslator->load(locale, QString("qt_"), translationDirPath());
508 qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
509 quasselTranslator->load(locale, QString(""), translationDirPath());
511 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
513 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
514 quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());