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"
45 Quassel::BuildInfo Quassel::_buildInfo;
46 AbstractCliParser *Quassel::_cliParser = 0;
47 Quassel::RunMode Quassel::_runMode;
48 QString Quassel::_configDirPath;
49 QString Quassel::_translationDirPath;
50 QStringList Quassel::_dataDirPaths;
51 bool Quassel::_initialized = false;
52 bool Quassel::DEBUG = false;
53 QString Quassel::_coreDumpFileName;
54 Quassel *Quassel::_instance = 0;
55 bool Quassel::_handleCrashes = true;
56 Quassel::LogLevel Quassel::_logLevel = InfoLevel;
57 QFile *Quassel::_logFile = 0;
58 bool Quassel::_logToSyslog = false;
65 // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
66 signal(SIGTERM, handleSignal);
67 signal(SIGINT, handleSignal);
75 logFile()->deleteLater();
84 return true; // allow multiple invocations because of MonolithicApplication
87 // we have crashhandler for win32 and unix (based on execinfo).
88 #if defined(Q_OS_WIN32) || defined(HAVE_EXECINFO)
90 // we only handle crashes ourselves if coredumps are disabled
91 struct rlimit *limit = (rlimit *)malloc(sizeof(struct rlimit));
92 int rc = getrlimit(RLIMIT_CORE, limit);
94 if (rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
95 # endif /* Q_OS_WIN32 */
96 signal(SIGABRT, handleSignal);
97 signal(SIGSEGV, handleSignal);
99 signal(SIGBUS, handleSignal);
102 # endif /* Q_OS_WIN32 */
103 #endif /* Q_OS_WIN32 || HAVE_EXECINFO */
107 qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
111 Network::setDefaultCodecForServer("ISO-8859-1");
112 Network::setDefaultCodecForEncoding("UTF-8");
113 Network::setDefaultCodecForDecoding("ISO-8859-15");
115 if (isOptionSet("help")) {
116 cliParser()->usage();
120 if (isOptionSet("version")) {
121 std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
125 DEBUG = isOptionSet("debug");
128 if (Quassel::runMode() != Quassel::ClientOnly) {
129 if (isOptionSet("loglevel")) {
130 QString level = optionValue("loglevel");
132 if (level == "Debug") _logLevel = DebugLevel;
133 else if (level == "Info") _logLevel = InfoLevel;
134 else if (level == "Warning") _logLevel = WarningLevel;
135 else if (level == "Error") _logLevel = ErrorLevel;
138 QString logfilename = optionValue("logfile");
139 if (!logfilename.isEmpty()) {
140 _logFile = new QFile(logfilename);
141 if (!_logFile->open(QIODevice::Append | QIODevice::Text)) {
142 qWarning() << "Could not open log file" << logfilename << ":" << _logFile->errorString();
143 _logFile->deleteLater();
148 _logToSyslog = isOptionSet("syslog");
158 QCoreApplication::quit();
162 //! Register our custom types with Qt's Meta Object System.
163 /** This makes them available for QVariant and in signals/slots, among other things.
166 void Quassel::registerMetaTypes()
169 qRegisterMetaType<Message>("Message");
170 qRegisterMetaType<BufferInfo>("BufferInfo");
171 qRegisterMetaType<NetworkInfo>("NetworkInfo");
172 qRegisterMetaType<Network::Server>("Network::Server");
173 qRegisterMetaType<Identity>("Identity");
175 qRegisterMetaTypeStreamOperators<Message>("Message");
176 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
177 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
178 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
179 qRegisterMetaTypeStreamOperators<Identity>("Identity");
181 qRegisterMetaType<IdentityId>("IdentityId");
182 qRegisterMetaType<BufferId>("BufferId");
183 qRegisterMetaType<NetworkId>("NetworkId");
184 qRegisterMetaType<UserId>("UserId");
185 qRegisterMetaType<AccountId>("AccountId");
186 qRegisterMetaType<MsgId>("MsgId");
188 qRegisterMetaType<QHostAddress>("QHostAddress");
190 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
191 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
192 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
193 qRegisterMetaTypeStreamOperators<UserId>("UserId");
194 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
195 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
197 // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
198 if (!QMetaType::type("QVariant")) {
199 qRegisterMetaType<QVariant>("QVariant");
200 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
205 void Quassel::setupBuildInfo(const QString &generated)
207 _buildInfo.applicationName = "Quassel IRC";
208 _buildInfo.coreApplicationName = "quasselcore";
209 _buildInfo.clientApplicationName = "quasselclient";
210 _buildInfo.organizationName = "Quassel Project";
211 _buildInfo.organizationDomain = "quassel-irc.org";
213 QStringList gen = generated.split(',');
214 Q_ASSERT(gen.count() == 10);
215 _buildInfo.baseVersion = gen[0];
216 _buildInfo.generatedVersion = gen[1];
217 _buildInfo.isSourceDirty = !gen[2].isEmpty();
218 _buildInfo.commitHash = gen[3];
219 _buildInfo.commitDate = gen[4].toUInt();
220 _buildInfo.protocolVersion = gen[5].toUInt();
221 _buildInfo.clientNeedsProtocol = gen[6].toUInt();
222 _buildInfo.coreNeedsProtocol = gen[7].toUInt();
223 _buildInfo.buildDate = QString("%1 %2").arg(gen[8], gen[9]);
224 // create a nice version string
225 if (_buildInfo.generatedVersion.isEmpty()) {
226 if (!_buildInfo.commitHash.isEmpty()) {
228 _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
229 .arg(_buildInfo.baseVersion)
230 .arg(_buildInfo.commitHash.left(7));
231 _buildInfo.fancyVersionString = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
232 .arg(_buildInfo.baseVersion)
233 .arg(_buildInfo.commitHash.left(7))
234 .arg(_buildInfo.commitHash);
237 // we only have a base version :(
238 _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
242 // analyze what we got from git-describe
243 QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
244 if (rx.exactMatch(_buildInfo.generatedVersion)) {
245 QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2));
246 _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)")
247 .arg(_buildInfo.baseVersion, distance, rx.cap(3))
248 .arg(_buildInfo.isSourceDirty ? "*" : "");
249 if (!_buildInfo.commitHash.isEmpty()) {
250 _buildInfo.fancyVersionString = QString("v%1 (%2git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
251 .arg(_buildInfo.baseVersion, distance, rx.cap(3))
252 .arg(_buildInfo.isSourceDirty ? "*" : "")
253 .arg(_buildInfo.commitHash);
257 _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
260 if (_buildInfo.fancyVersionString.isEmpty())
261 _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
265 //! Signal handler for graceful shutdown.
266 void Quassel::handleSignal(int sig)
271 qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
275 QCoreApplication::quit();
282 logBacktrace(coreDumpFileName());
291 void Quassel::logFatalMessage(const char *msg)
296 QFile dumpFile(coreDumpFileName());
297 dumpFile.open(QIODevice::Append);
298 QTextStream dumpStream(&dumpFile);
300 dumpStream << "Fatal: " << msg << '\n';
307 Quassel::Features Quassel::features()
310 for (int i = 1; i <= NumFeatures; i <<= 1)
317 const QString &Quassel::coreDumpFileName()
319 if (_coreDumpFileName.isEmpty()) {
320 QDir configDir(configDirPath());
321 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
322 QFile dumpFile(_coreDumpFileName);
323 dumpFile.open(QIODevice::Append);
324 QTextStream dumpStream(&dumpFile);
325 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
326 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
330 return _coreDumpFileName;
334 QString Quassel::configDirPath()
336 if (!_configDirPath.isEmpty())
337 return _configDirPath;
339 if (Quassel::isOptionSet("datadir")) {
340 qWarning() << "Obsolete option --datadir used!";
341 _configDirPath = Quassel::optionValue("datadir");
343 else if (Quassel::isOptionSet("configdir")) {
344 _configDirPath = Quassel::optionValue("configdir");
348 // On Mac, the path is always the same
349 _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
351 // We abuse QSettings to find us a sensible path on the other platforms
353 // don't use the registry
354 QSettings::Format format = QSettings::IniFormat;
356 QSettings::Format format = QSettings::NativeFormat;
358 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
359 QFileInfo fileInfo(s.fileName());
360 _configDirPath = fileInfo.dir().absolutePath();
361 #endif /* Q_WS_MAC */
364 if (!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
365 _configDirPath += QDir::separator();
367 QDir qDir(_configDirPath);
368 if (!qDir.exists(_configDirPath)) {
369 if (!qDir.mkpath(_configDirPath)) {
370 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
375 return _configDirPath;
379 QStringList Quassel::dataDirPaths()
381 return _dataDirPaths;
385 QStringList Quassel::findDataDirPaths() const
387 QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
389 if (!dataDirNames.isEmpty()) {
390 for (int i = 0; i < dataDirNames.count(); i++)
391 dataDirNames[i].append("/apps/quassel/");
394 // Provide a fallback
396 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
397 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
398 << QCoreApplication::applicationDirPath();
400 #elif defined Q_WS_MAC
401 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
402 << QCoreApplication::applicationDirPath();
405 dataDirNames.append("/usr/share/apps/quassel/");
407 // on UNIX, we always check our install prefix
408 QString appDir = QCoreApplication::applicationDirPath();
409 int binpos = appDir.lastIndexOf("/bin");
411 appDir.replace(binpos, 4, "/share");
412 appDir.append("/apps/quassel/");
413 if (!dataDirNames.contains(appDir))
414 dataDirNames.append(appDir);
418 // add resource path and workdir just in case
419 dataDirNames << QCoreApplication::applicationDirPath() + "/data/"
422 // append trailing '/' and check for existence
423 QStringList::Iterator iter = dataDirNames.begin();
424 while (iter != dataDirNames.end()) {
425 if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
426 iter->append(QDir::separator());
427 if (!QFile::exists(*iter))
428 iter = dataDirNames.erase(iter);
437 QString Quassel::findDataFilePath(const QString &fileName)
439 QStringList dataDirs = dataDirPaths();
440 foreach(QString dataDir, dataDirs) {
441 QString path = dataDir + fileName;
442 if (QFile::exists(path))
449 QStringList Quassel::scriptDirPaths()
451 QStringList res(configDirPath() + "scripts/");
452 foreach(QString path, dataDirPaths())
453 res << path + "scripts/";
458 QString Quassel::translationDirPath()
460 if (_translationDirPath.isEmpty()) {
461 // We support only one translation dir; fallback mechanisms wouldn't work else.
462 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
463 foreach(const QString &dir, dataDirPaths()) {
464 if (QFile::exists(dir + "translations/")) {
465 _translationDirPath = dir + "translations/";
469 if (_translationDirPath.isEmpty())
470 _translationDirPath = ":/i18n/";
472 return _translationDirPath;
476 void Quassel::loadTranslation(const QLocale &locale)
478 QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
479 QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
482 qApp->removeTranslator(qtTranslator);
483 if (quasselTranslator)
484 qApp->removeTranslator(quasselTranslator);
486 // We use QLocale::C to indicate that we don't want a translation
487 if (locale.language() == QLocale::C)
490 qtTranslator = new QTranslator(qApp);
491 qtTranslator->setObjectName("QtTr");
492 qApp->installTranslator(qtTranslator);
494 quasselTranslator = new QTranslator(qApp);
495 quasselTranslator->setObjectName("QuasselTr");
496 qApp->installTranslator(quasselTranslator);
498 #if QT_VERSION >= 0x040800
499 bool success = qtTranslator->load(locale, QString("qt_%1"), translationDirPath());
501 qtTranslator->load(locale, QString("qt_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
502 quasselTranslator->load(locale, QString(""), translationDirPath());
504 QString localeName = locale.name();
506 // if the user did not specify a language in the settings, the system locale
507 // is used, but Qt < 4.8 does not respect language settings. This bit is
508 // based on QLocale::uiLanguages() as in Qt 4.8.3
509 if (locale == QLocale::system()) {
510 // FIXME: does it make sense to set the locale to the system locale?
511 QLocale::setDefault(locale);
512 QVariant res = QSystemLocale().query(QSystemLocale::UILanguages, QVariant());
514 QString newName = res.toStringList()[0];
515 if (!newName.isEmpty()) {
516 localeName = newName.replace('-', "_"); // silly Qt.
521 bool success = qtTranslator->load(QString("qt_%1").arg(localeName), translationDirPath());
523 qtTranslator->load(QString("qt_%1").arg(localeName), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
524 quasselTranslator->load(QString("%1").arg(localeName), translationDirPath());