1 /***************************************************************************
2 * Copyright (C) 2005-2013 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/resource.h>
29 #include <QCoreApplication>
32 #include <QLibraryInfo>
34 #include <QTranslator>
35 #include <QHostAddress>
40 #include "bufferinfo.h"
42 #include "syncableobject.h"
44 Quassel::BuildInfo Quassel::_buildInfo;
45 AbstractCliParser *Quassel::_cliParser = 0;
46 Quassel::RunMode Quassel::_runMode;
47 QString Quassel::_configDirPath;
48 QString Quassel::_translationDirPath;
49 QStringList Quassel::_dataDirPaths;
50 bool Quassel::_initialized = false;
51 bool Quassel::DEBUG = false;
52 QString Quassel::_coreDumpFileName;
53 Quassel *Quassel::_instance = 0;
54 bool Quassel::_handleCrashes = true;
55 Quassel::LogLevel Quassel::_logLevel = InfoLevel;
56 QFile *Quassel::_logFile = 0;
57 bool Quassel::_logToSyslog = false;
64 // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
65 signal(SIGTERM, handleSignal);
66 signal(SIGINT, handleSignal);
74 logFile()->deleteLater();
83 return true; // allow multiple invocations because of MonolithicApplication
86 // we have crashhandler for win32 and unix (based on execinfo).
87 #if defined(Q_OS_WIN32) || defined(HAVE_EXECINFO)
89 // we only handle crashes ourselves if coredumps are disabled
90 struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit));
91 int rc = getrlimit(RLIMIT_CORE, limit);
93 if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
94 # endif /* Q_OS_WIN32 */
95 signal(SIGABRT, handleSignal);
96 signal(SIGSEGV, handleSignal);
98 signal(SIGBUS, handleSignal);
101 # endif /* Q_OS_WIN32 */
102 #endif /* Q_OS_WIN32 || HAVE_EXECINFO */
106 qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
110 Network::setDefaultCodecForServer("ISO-8859-1");
111 Network::setDefaultCodecForEncoding("UTF-8");
112 Network::setDefaultCodecForDecoding("ISO-8859-15");
114 if (isOptionSet("help")) {
115 cliParser()->usage();
119 if (isOptionSet("version")) {
120 std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
124 DEBUG = isOptionSet("debug");
127 if (Quassel::runMode() != Quassel::ClientOnly) {
128 if (isOptionSet("loglevel")) {
129 QString level = optionValue("loglevel");
131 if (level == "Debug") _logLevel = DebugLevel;
132 else if (level == "Info") _logLevel = InfoLevel;
133 else if (level == "Warning") _logLevel = WarningLevel;
134 else if (level == "Error") _logLevel = ErrorLevel;
137 QString logfilename = optionValue("logfile");
138 if (!logfilename.isEmpty()) {
139 _logFile = new QFile(logfilename);
140 if (!_logFile->open(QIODevice::Append | QIODevice::Text)) {
141 qWarning() << "Could not open log file" << logfilename << ":" << _logFile->errorString();
142 _logFile->deleteLater();
147 _logToSyslog = isOptionSet("syslog");
157 QCoreApplication::quit();
161 //! Register our custom types with Qt's Meta Object System.
162 /** This makes them available for QVariant and in signals/slots, among other things.
165 void Quassel::registerMetaTypes()
168 qRegisterMetaType<Message>("Message");
169 qRegisterMetaType<BufferInfo>("BufferInfo");
170 qRegisterMetaType<NetworkInfo>("NetworkInfo");
171 qRegisterMetaType<Network::Server>("Network::Server");
172 qRegisterMetaType<Identity>("Identity");
174 qRegisterMetaTypeStreamOperators<Message>("Message");
175 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
176 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
177 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
178 qRegisterMetaTypeStreamOperators<Identity>("Identity");
180 qRegisterMetaType<IdentityId>("IdentityId");
181 qRegisterMetaType<BufferId>("BufferId");
182 qRegisterMetaType<NetworkId>("NetworkId");
183 qRegisterMetaType<UserId>("UserId");
184 qRegisterMetaType<AccountId>("AccountId");
185 qRegisterMetaType<MsgId>("MsgId");
187 qRegisterMetaType<QHostAddress>("QHostAddress");
189 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
190 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
191 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
192 qRegisterMetaTypeStreamOperators<UserId>("UserId");
193 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
194 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
196 // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
197 if (!QMetaType::type("QVariant")) {
198 qRegisterMetaType<QVariant>("QVariant");
199 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
204 void Quassel::setupBuildInfo(const QString &generated)
206 _buildInfo.applicationName = "Quassel IRC";
207 _buildInfo.coreApplicationName = "quasselcore";
208 _buildInfo.clientApplicationName = "quasselclient";
209 _buildInfo.organizationName = "Quassel Project";
210 _buildInfo.organizationDomain = "quassel-irc.org";
212 QStringList gen = generated.split(',');
213 Q_ASSERT(gen.count() == 10);
214 _buildInfo.baseVersion = gen[0];
215 _buildInfo.generatedVersion = gen[1];
216 _buildInfo.isSourceDirty = !gen[2].isEmpty();
217 _buildInfo.commitHash = gen[3];
218 _buildInfo.commitDate = gen[4].toUInt();
219 _buildInfo.protocolVersion = gen[5].toUInt();
220 _buildInfo.clientNeedsProtocol = gen[6].toUInt();
221 _buildInfo.coreNeedsProtocol = gen[7].toUInt();
222 _buildInfo.buildDate = QString("%1 %2").arg(gen[8], gen[9]);
223 // create a nice version string
224 if (_buildInfo.generatedVersion.isEmpty()) {
225 if (!_buildInfo.commitHash.isEmpty()) {
227 _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
228 .arg(_buildInfo.baseVersion)
229 .arg(_buildInfo.commitHash.left(7));
230 _buildInfo.fancyVersionString = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
231 .arg(_buildInfo.baseVersion)
232 .arg(_buildInfo.commitHash.left(7))
233 .arg(_buildInfo.commitHash);
236 // we only have a base version :(
237 _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
241 // analyze what we got from git-describe
242 QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
243 if (rx.exactMatch(_buildInfo.generatedVersion)) {
244 QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2));
245 _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)")
246 .arg(_buildInfo.baseVersion, distance, rx.cap(3))
247 .arg(_buildInfo.isSourceDirty ? "*" : "");
248 if (!_buildInfo.commitHash.isEmpty()) {
249 _buildInfo.fancyVersionString = QString("v%1 (%2git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
250 .arg(_buildInfo.baseVersion, distance, rx.cap(3))
251 .arg(_buildInfo.isSourceDirty ? "*" : "")
252 .arg(_buildInfo.commitHash);
256 _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
259 if (_buildInfo.fancyVersionString.isEmpty())
260 _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
264 //! Signal handler for graceful shutdown.
265 void Quassel::handleSignal(int sig)
270 qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
274 QCoreApplication::quit();
281 logBacktrace(coreDumpFileName());
290 void Quassel::logFatalMessage(const char *msg)
295 QFile dumpFile(coreDumpFileName());
296 dumpFile.open(QIODevice::Append);
297 QTextStream dumpStream(&dumpFile);
299 dumpStream << "Fatal: " << msg << '\n';
306 Quassel::Features Quassel::features()
309 for (int i = 1; i <= NumFeatures; i <<= 1)
316 const QString &Quassel::coreDumpFileName()
318 if (_coreDumpFileName.isEmpty()) {
319 QDir configDir(configDirPath());
320 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
321 QFile dumpFile(_coreDumpFileName);
322 dumpFile.open(QIODevice::Append);
323 QTextStream dumpStream(&dumpFile);
324 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
325 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
329 return _coreDumpFileName;
333 QString Quassel::configDirPath()
335 if (!_configDirPath.isEmpty())
336 return _configDirPath;
338 if (Quassel::isOptionSet("datadir")) {
339 qWarning() << "Obsolete option --datadir used!";
340 _configDirPath = Quassel::optionValue("datadir");
342 else if (Quassel::isOptionSet("configdir")) {
343 _configDirPath = Quassel::optionValue("configdir");
347 // On Mac, the path is always the same
348 _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
350 // We abuse QSettings to find us a sensible path on the other platforms
352 // don't use the registry
353 QSettings::Format format = QSettings::IniFormat;
355 QSettings::Format format = QSettings::NativeFormat;
357 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
358 QFileInfo fileInfo(s.fileName());
359 _configDirPath = fileInfo.dir().absolutePath();
360 #endif /* Q_WS_MAC */
363 if (!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
364 _configDirPath += QDir::separator();
366 QDir qDir(_configDirPath);
367 if (!qDir.exists(_configDirPath)) {
368 if (!qDir.mkpath(_configDirPath)) {
369 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
374 return _configDirPath;
378 QStringList Quassel::dataDirPaths()
380 return _dataDirPaths;
384 QStringList Quassel::findDataDirPaths() const
386 QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
388 if (!dataDirNames.isEmpty()) {
389 for (int i = 0; i < dataDirNames.count(); i++)
390 dataDirNames[i].append("/apps/quassel/");
393 // Provide a fallback
395 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
396 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
397 << QCoreApplication::applicationDirPath();
399 #elif defined Q_WS_MAC
400 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
401 << QCoreApplication::applicationDirPath();
404 dataDirNames.append("/usr/share/apps/quassel/");
406 // on UNIX, we always check our install prefix
407 QString appDir = QCoreApplication::applicationDirPath();
408 int binpos = appDir.lastIndexOf("/bin");
410 appDir.replace(binpos, 4, "/share");
411 appDir.append("/apps/quassel/");
412 if (!dataDirNames.contains(appDir))
413 dataDirNames.append(appDir);
417 // add resource path and workdir just in case
418 dataDirNames << QCoreApplication::applicationDirPath() + "/data/"
421 // append trailing '/' and check for existence
422 QStringList::Iterator iter = dataDirNames.begin();
423 while (iter != dataDirNames.end()) {
424 if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
425 iter->append(QDir::separator());
426 if (!QFile::exists(*iter))
427 iter = dataDirNames.erase(iter);
436 QString Quassel::findDataFilePath(const QString &fileName)
438 QStringList dataDirs = dataDirPaths();
439 foreach(QString dataDir, dataDirs) {
440 QString path = dataDir + fileName;
441 if (QFile::exists(path))
448 QStringList Quassel::scriptDirPaths()
450 QStringList res(configDirPath() + "scripts/");
451 foreach(QString path, dataDirPaths())
452 res << path + "scripts/";
457 QString Quassel::translationDirPath()
459 if (_translationDirPath.isEmpty()) {
460 // We support only one translation dir; fallback mechanisms wouldn't work else.
461 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
462 foreach(const QString &dir, dataDirPaths()) {
463 if (QFile::exists(dir + "translations/")) {
464 _translationDirPath = dir + "translations/";
468 if (_translationDirPath.isEmpty())
469 _translationDirPath = ":/i18n/";
471 return _translationDirPath;
475 void Quassel::loadTranslation(const QLocale &locale)
477 QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
478 QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
481 qApp->removeTranslator(qtTranslator);
482 if (quasselTranslator)
483 qApp->removeTranslator(quasselTranslator);
485 // We use QLocale::C to indicate that we don't want a translation
486 if (locale.language() == QLocale::C)
489 qtTranslator = new QTranslator(qApp);
490 qtTranslator->setObjectName("QtTr");
491 qApp->installTranslator(qtTranslator);
493 quasselTranslator = new QTranslator(qApp);
494 quasselTranslator->setObjectName("QuasselTr");
495 qApp->installTranslator(quasselTranslator);
497 QLocale::setDefault(locale);
499 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
501 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
502 quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());