1 /***************************************************************************
2 * Copyright (C) 2005-09 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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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;
63 // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
64 signal(SIGTERM, handleSignal);
65 signal(SIGINT, handleSignal);
71 logFile()->deleteLater();
76 bool Quassel::init() {
78 return true; // allow multiple invocations because of MonolithicApplication
81 // we have crashhandler for win32 and unix (based on execinfo).
82 #if defined(Q_OS_WIN32) || defined(HAVE_EXECINFO)
84 // we only handle crashes ourselves if coredumps are disabled
85 struct rlimit *limit = (rlimit *) malloc(sizeof(struct rlimit));
86 int rc = getrlimit(RLIMIT_CORE, limit);
88 if(rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
89 # endif /* Q_OS_WIN32 */
90 signal(SIGABRT, handleSignal);
91 signal(SIGSEGV, handleSignal);
93 signal(SIGBUS, handleSignal);
96 # endif /* Q_OS_WIN32 */
97 #endif /* Q_OS_WIN32 || HAVE_EXECINFO */
101 qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
105 Network::setDefaultCodecForServer("ISO-8859-1");
106 Network::setDefaultCodecForEncoding("UTF-8");
107 Network::setDefaultCodecForDecoding("ISO-8859-15");
109 if(isOptionSet("help")) {
110 cliParser()->usage();
114 if(isOptionSet("version")) {
115 std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
119 DEBUG = isOptionSet("debug");
122 if(Quassel::runMode() != Quassel::ClientOnly) {
123 if(isOptionSet("loglevel")) {
124 QString level = optionValue("loglevel");
126 if(level == "Debug") _logLevel = DebugLevel;
127 else if(level == "Info") _logLevel = InfoLevel;
128 else if(level == "Warning") _logLevel= WarningLevel;
129 else if(level == "Error") _logLevel = ErrorLevel;
132 QString logfilename = optionValue("logfile");
133 if(!logfilename.isEmpty()) {
134 _logFile = new QFile(logfilename);
135 if(!_logFile->open(QIODevice::Append | QIODevice::Text)) {
136 qWarning() << "Could not open log file" << logfilename << ":" << _logFile->errorString();
137 _logFile->deleteLater();
142 _logToSyslog = isOptionSet("syslog");
149 void Quassel::quit() {
150 QCoreApplication::quit();
153 //! Register our custom types with Qt's Meta Object System.
154 /** This makes them available for QVariant and in signals/slots, among other things.
157 void Quassel::registerMetaTypes() {
159 qRegisterMetaType<Message>("Message");
160 qRegisterMetaType<BufferInfo>("BufferInfo");
161 qRegisterMetaType<NetworkInfo>("NetworkInfo");
162 qRegisterMetaType<Network::Server>("Network::Server");
163 qRegisterMetaType<Identity>("Identity");
164 qRegisterMetaType<Network::ConnectionState>("Network::ConnectionState");
166 qRegisterMetaTypeStreamOperators<Message>("Message");
167 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
168 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
169 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
170 qRegisterMetaTypeStreamOperators<Identity>("Identity");
171 qRegisterMetaTypeStreamOperators<qint8>("Network::ConnectionState");
173 qRegisterMetaType<IdentityId>("IdentityId");
174 qRegisterMetaType<BufferId>("BufferId");
175 qRegisterMetaType<NetworkId>("NetworkId");
176 qRegisterMetaType<UserId>("UserId");
177 qRegisterMetaType<AccountId>("AccountId");
178 qRegisterMetaType<MsgId>("MsgId");
180 qRegisterMetaType<QHostAddress>("QHostAddress");
182 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
183 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
184 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
185 qRegisterMetaTypeStreamOperators<UserId>("UserId");
186 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
187 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
189 // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
190 if(!QMetaType::type("QVariant")) {
191 qRegisterMetaType<QVariant>("QVariant");
192 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
196 void Quassel::setupBuildInfo(const QString &generated) {
197 _buildInfo.applicationName = "Quassel IRC";
198 _buildInfo.coreApplicationName = "quasselcore";
199 _buildInfo.clientApplicationName = "quasselclient";
200 _buildInfo.organizationName = "Quassel Project";
201 _buildInfo.organizationDomain = "quassel-irc.org";
203 QStringList gen = generated.split(',');
204 Q_ASSERT(gen.count() == 10);
205 _buildInfo.baseVersion = gen[0];
206 _buildInfo.generatedVersion = gen[1];
207 _buildInfo.isSourceDirty = !gen[2].isEmpty();
208 _buildInfo.commitHash = gen[3];
209 _buildInfo.commitDate = gen[4].toUInt();
210 _buildInfo.protocolVersion = gen[5].toUInt();
211 _buildInfo.clientNeedsProtocol = gen[6].toUInt();
212 _buildInfo.coreNeedsProtocol = gen[7].toUInt();
213 _buildInfo.buildDate = QString("%1 %2").arg(gen[8], gen[9]);
214 // create a nice version string
215 if(_buildInfo.generatedVersion.isEmpty()) {
216 if(!_buildInfo.commitHash.isEmpty()) {
218 _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
219 .arg(_buildInfo.baseVersion)
220 .arg(_buildInfo.commitHash.left(7));
221 _buildInfo.fancyVersionString = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
222 .arg(_buildInfo.baseVersion)
223 .arg(_buildInfo.commitHash.left(7))
224 .arg(_buildInfo.commitHash);
226 // we only have a base version :(
227 _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
230 // analyze what we got from git-describe
231 QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
232 if(rx.exactMatch(_buildInfo.generatedVersion)) {
233 QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2));
234 _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)")
235 .arg(_buildInfo.baseVersion, distance, rx.cap(3))
236 .arg(_buildInfo.isSourceDirty ? "*" : "");
237 if(!_buildInfo.commitHash.isEmpty()) {
238 _buildInfo.fancyVersionString = QString("v%1 (%2git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
239 .arg(_buildInfo.baseVersion, distance, rx.cap(3))
240 .arg(_buildInfo.isSourceDirty ? "*" : "")
241 .arg(_buildInfo.commitHash);
244 _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
247 if(_buildInfo.fancyVersionString.isEmpty())
248 _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
251 //! Signal handler for graceful shutdown.
252 void Quassel::handleSignal(int sig) {
256 qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
260 QCoreApplication::quit();
267 logBacktrace(coreDumpFileName());
275 void Quassel::logFatalMessage(const char *msg) {
279 QFile dumpFile(coreDumpFileName());
280 dumpFile.open(QIODevice::Append);
281 QTextStream dumpStream(&dumpFile);
283 dumpStream << "Fatal: " << msg << '\n';
289 Quassel::Features Quassel::features() {
291 for(int i = 1; i <= NumFeatures; i<<=1)
292 feats |= (Feature) i;
297 const QString &Quassel::coreDumpFileName() {
298 if(_coreDumpFileName.isEmpty()) {
299 QDir configDir(configDirPath());
300 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
301 QFile dumpFile(_coreDumpFileName);
302 dumpFile.open(QIODevice::Append);
303 QTextStream dumpStream(&dumpFile);
304 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
305 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
309 return _coreDumpFileName;
312 QString Quassel::configDirPath() {
313 if(!_configDirPath.isEmpty())
314 return _configDirPath;
316 if(Quassel::isOptionSet("datadir")) {
317 qWarning() << "Obsolete option --datadir used!";
318 _configDirPath = Quassel::optionValue("datadir");
319 } else if(Quassel::isOptionSet("configdir")) {
320 _configDirPath = Quassel::optionValue("configdir");
324 // On Mac, the path is always the same
325 _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
327 // We abuse QSettings to find us a sensible path on the other platforms
329 // don't use the registry
330 QSettings::Format format = QSettings::IniFormat;
332 QSettings::Format format = QSettings::NativeFormat;
334 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
335 QFileInfo fileInfo(s.fileName());
336 _configDirPath = fileInfo.dir().absolutePath();
337 #endif /* Q_WS_MAC */
340 if(!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
341 _configDirPath += QDir::separator();
343 QDir qDir(_configDirPath);
344 if(!qDir.exists(_configDirPath)) {
345 if(!qDir.mkpath(_configDirPath)) {
346 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
351 return _configDirPath;
354 QStringList Quassel::dataDirPaths() {
355 return _dataDirPaths;
358 QStringList Quassel::findDataDirPaths() const {
359 QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
361 if(!dataDirNames.isEmpty()) {
362 for(int i = 0; i < dataDirNames.count(); i++)
363 dataDirNames[i].append("/apps/quassel/");
365 // Provide a fallback
367 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
368 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
369 << QCoreApplication::applicationDirPath();
371 #elif defined Q_WS_MAC
372 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
373 << QCoreApplication::applicationDirPath();
376 dataDirNames.append("/usr/share/apps/quassel/");
378 // on UNIX, we always check our install prefix
379 QString appDir = QCoreApplication::applicationDirPath();
380 int binpos = appDir.lastIndexOf("/bin");
382 appDir.replace(binpos, 4, "/share");
383 appDir.append("/apps/quassel/");
384 if(!dataDirNames.contains(appDir))
385 dataDirNames.append(appDir);
389 // add resource path and workdir just in case
390 dataDirNames << QCoreApplication::applicationDirPath() + "/data/"
393 // append trailing '/' and check for existence
394 QStringList::Iterator iter = dataDirNames.begin();
395 while(iter != dataDirNames.end()) {
396 if(!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
397 iter->append(QDir::separator());
398 if(!QFile::exists(*iter))
399 iter = dataDirNames.erase(iter);
407 QString Quassel::findDataFilePath(const QString &fileName) {
408 QStringList dataDirs = dataDirPaths();
409 foreach(QString dataDir, dataDirs) {
410 QString path = dataDir + fileName;
411 if(QFile::exists(path))
417 QStringList Quassel::scriptDirPaths() {
418 QStringList res(configDirPath() + "scripts/");
419 foreach(QString path, dataDirPaths())
420 res << path + "scripts/";
424 QString Quassel::translationDirPath() {
425 if(_translationDirPath.isEmpty()) {
426 // We support only one translation dir; fallback mechanisms wouldn't work else.
427 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
428 foreach(const QString &dir, dataDirPaths()) {
429 if(QFile::exists(dir + "translations/")) {
430 _translationDirPath = dir + "translations/";
434 if(_translationDirPath.isEmpty())
435 _translationDirPath = ":/i18n/";
437 return _translationDirPath;
440 void Quassel::loadTranslation(const QLocale &locale) {
441 QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
442 QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
445 qApp->removeTranslator(qtTranslator);
446 if(quasselTranslator)
447 qApp->removeTranslator(quasselTranslator);
449 // We use QLocale::C to indicate that we don't want a translation
450 if(locale.language() == QLocale::C)
453 qtTranslator = new QTranslator(qApp);
454 qtTranslator->setObjectName("QtTr");
455 qApp->installTranslator(qtTranslator);
457 quasselTranslator = new QTranslator(qApp);
458 quasselTranslator->setObjectName("QuasselTr");
459 qApp->installTranslator(quasselTranslator);
461 QLocale::setDefault(locale);
463 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
465 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
466 quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());