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>
39 #include "bufferinfo.h"
41 #include "syncableobject.h"
43 Quassel::BuildInfo Quassel::_buildInfo;
44 AbstractCliParser *Quassel::_cliParser = 0;
45 Quassel::RunMode Quassel::_runMode;
46 QString Quassel::_configDirPath;
47 QString Quassel::_translationDirPath;
48 QStringList Quassel::_dataDirPaths;
49 bool Quassel::_initialized = false;
50 bool Quassel::DEBUG = false;
51 QString Quassel::_coreDumpFileName;
52 Quassel *Quassel::_instance = 0;
53 bool Quassel::_handleCrashes = true;
59 // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
60 signal(SIGTERM, handleSignal);
61 signal(SIGINT, handleSignal);
68 bool Quassel::init() {
70 return true; // allow multiple invocations because of MonolithicApplication
73 // we have crashhandler for win32 and unix (based on execinfo).
74 #if defined(Q_OS_WIN32) || defined(HAVE_EXECINFO)
76 // we only handle crashes ourselves if coredumps are disabled
77 struct rlimit *limit = (rlimit *) malloc(sizeof(struct rlimit));
78 int rc = getrlimit(RLIMIT_CORE, limit);
80 if(rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
81 # endif /* Q_OS_WIN32 */
82 signal(SIGABRT, handleSignal);
83 signal(SIGSEGV, handleSignal);
85 signal(SIGBUS, handleSignal);
88 # endif /* Q_OS_WIN32 */
89 #endif /* Q_OS_WIN32 || HAVE_EXECINFO */
93 qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
97 Network::setDefaultCodecForServer("ISO-8859-1");
98 Network::setDefaultCodecForEncoding("UTF-8");
99 Network::setDefaultCodecForDecoding("ISO-8859-15");
101 if(isOptionSet("help")) {
102 cliParser()->usage();
106 if(isOptionSet("version")) {
107 std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
111 DEBUG = isOptionSet("debug");
115 void Quassel::quit() {
116 QCoreApplication::quit();
119 //! Register our custom types with Qt's Meta Object System.
120 /** This makes them available for QVariant and in signals/slots, among other things.
123 void Quassel::registerMetaTypes() {
125 qRegisterMetaType<QVariant>("QVariant");
126 qRegisterMetaType<Message>("Message");
127 qRegisterMetaType<BufferInfo>("BufferInfo");
128 qRegisterMetaType<NetworkInfo>("NetworkInfo");
129 qRegisterMetaType<Network::Server>("Network::Server");
130 qRegisterMetaType<Identity>("Identity");
131 qRegisterMetaType<Network::ConnectionState>("Network::ConnectionState");
133 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
134 qRegisterMetaTypeStreamOperators<Message>("Message");
135 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
136 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
137 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
138 qRegisterMetaTypeStreamOperators<Identity>("Identity");
139 qRegisterMetaTypeStreamOperators<qint8>("Network::ConnectionState");
141 qRegisterMetaType<IdentityId>("IdentityId");
142 qRegisterMetaType<BufferId>("BufferId");
143 qRegisterMetaType<NetworkId>("NetworkId");
144 qRegisterMetaType<UserId>("UserId");
145 qRegisterMetaType<AccountId>("AccountId");
146 qRegisterMetaType<MsgId>("MsgId");
148 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
149 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
150 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
151 qRegisterMetaTypeStreamOperators<UserId>("UserId");
152 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
153 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
156 void Quassel::setupBuildInfo(const QString &generated) {
157 _buildInfo.applicationName = "Quassel IRC";
158 _buildInfo.coreApplicationName = "quasselcore";
159 _buildInfo.clientApplicationName = "quasselclient";
160 _buildInfo.organizationName = "Quassel Project";
161 _buildInfo.organizationDomain = "quassel-irc.org";
163 QStringList gen = generated.split(',');
164 Q_ASSERT(gen.count() == 10);
165 _buildInfo.baseVersion = gen[0];
166 _buildInfo.generatedVersion = gen[1];
167 _buildInfo.isSourceDirty = !gen[2].isEmpty();
168 _buildInfo.commitHash = gen[3];
169 _buildInfo.commitDate = gen[4].toUInt();
170 _buildInfo.protocolVersion = gen[5].toUInt();
171 _buildInfo.clientNeedsProtocol = gen[6].toUInt();
172 _buildInfo.coreNeedsProtocol = gen[7].toUInt();
173 _buildInfo.buildDate = QString("%1 %2").arg(gen[8], gen[9]);
174 // create a nice version string
175 if(_buildInfo.generatedVersion.isEmpty()) {
176 if(!_buildInfo.commitHash.isEmpty()) {
178 _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
179 .arg(_buildInfo.baseVersion)
180 .arg(_buildInfo.commitHash.left(7));
181 _buildInfo.fancyVersionString = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
182 .arg(_buildInfo.baseVersion)
183 .arg(_buildInfo.commitHash.left(7))
184 .arg(_buildInfo.commitHash);
186 // we only have a base version :(
187 _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
190 // analyze what we got from git-describe
191 QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
192 if(rx.exactMatch(_buildInfo.generatedVersion)) {
193 QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2));
194 _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)")
195 .arg(_buildInfo.baseVersion, distance, rx.cap(3))
196 .arg(_buildInfo.isSourceDirty ? "*" : "");
197 if(!_buildInfo.commitHash.isEmpty()) {
198 _buildInfo.fancyVersionString = QString("v%1 (%2git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
199 .arg(_buildInfo.baseVersion, distance, rx.cap(3))
200 .arg(_buildInfo.isSourceDirty ? "*" : "")
201 .arg(_buildInfo.commitHash);
204 _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
207 if(_buildInfo.fancyVersionString.isEmpty())
208 _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
211 //! Signal handler for graceful shutdown.
212 void Quassel::handleSignal(int sig) {
216 qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
220 QCoreApplication::quit();
227 logBacktrace(coreDumpFileName());
235 void Quassel::logFatalMessage(const char *msg) {
239 QFile dumpFile(coreDumpFileName());
240 dumpFile.open(QIODevice::Append);
241 QTextStream dumpStream(&dumpFile);
243 dumpStream << "Fatal: " << msg << '\n';
249 Quassel::Features Quassel::features() {
251 for(int i = 1; i <= NumFeatures; i<<=1)
252 feats |= (Feature) i;
257 const QString &Quassel::coreDumpFileName() {
258 if(_coreDumpFileName.isEmpty()) {
259 QDir configDir(configDirPath());
260 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
261 QFile dumpFile(_coreDumpFileName);
262 dumpFile.open(QIODevice::Append);
263 QTextStream dumpStream(&dumpFile);
264 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
265 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
269 return _coreDumpFileName;
272 QString Quassel::configDirPath() {
273 if(!_configDirPath.isEmpty())
274 return _configDirPath;
276 if(Quassel::isOptionSet("datadir")) {
277 qWarning() << "Obsolete option --datadir used!";
278 _configDirPath = Quassel::optionValue("datadir");
279 } else if(Quassel::isOptionSet("configdir")) {
280 _configDirPath = Quassel::optionValue("configdir");
284 // On Mac, the path is always the same
285 _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
287 // We abuse QSettings to find us a sensible path on the other platforms
289 // don't use the registry
290 QSettings::Format format = QSettings::IniFormat;
292 QSettings::Format format = QSettings::NativeFormat;
294 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
295 QFileInfo fileInfo(s.fileName());
296 _configDirPath = fileInfo.dir().absolutePath();
297 #endif /* Q_WS_MAC */
300 if(!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
301 _configDirPath += QDir::separator();
303 QDir qDir(_configDirPath);
304 if(!qDir.exists(_configDirPath)) {
305 if(!qDir.mkpath(_configDirPath)) {
306 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
311 return _configDirPath;
314 QStringList Quassel::dataDirPaths() {
315 return _dataDirPaths;
318 QStringList Quassel::findDataDirPaths() const {
319 QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
321 if(!dataDirNames.isEmpty()) {
322 for(int i = 0; i < dataDirNames.count(); i++)
323 dataDirNames[i].append("/apps/quassel/");
325 // Provide a fallback
327 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
328 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
329 << QCoreApplication::applicationDirPath();
331 #elif defined Q_WS_MAC
332 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
333 << QCoreApplication::applicationDirPath();
336 dataDirNames.append("/usr/share/apps/quassel/");
338 // on UNIX, we always check our install prefix
339 QString appDir = QCoreApplication::applicationDirPath();
340 int binpos = appDir.lastIndexOf("/bin");
342 appDir.replace(binpos, 4, "/share");
343 appDir.append("/apps/quassel/");
344 if(!dataDirNames.contains(appDir))
345 dataDirNames.append(appDir);
349 // add resource path and workdir just in case
350 dataDirNames << QCoreApplication::applicationDirPath() + "/data/"
353 // append trailing '/' and check for existence
354 QStringList::Iterator iter = dataDirNames.begin();
355 while(iter != dataDirNames.end()) {
356 if(!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
357 iter->append(QDir::separator());
358 if(!QFile::exists(*iter))
359 iter = dataDirNames.erase(iter);
367 QString Quassel::findDataFilePath(const QString &fileName) {
368 QStringList dataDirs = dataDirPaths();
369 foreach(QString dataDir, dataDirs) {
370 QString path = dataDir + fileName;
371 if(QFile::exists(path))
377 QStringList Quassel::scriptDirPaths() {
378 QStringList res(configDirPath() + "scripts/");
379 foreach(QString path, dataDirPaths())
380 res << path + "scripts/";
384 QString Quassel::translationDirPath() {
385 if(_translationDirPath.isEmpty()) {
386 // We support only one translation dir; fallback mechanisms wouldn't work else.
387 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
388 foreach(const QString &dir, dataDirPaths()) {
389 if(QFile::exists(dir + "translations/")) {
390 _translationDirPath = dir + "translations/";
394 if(_translationDirPath.isEmpty())
395 _translationDirPath = ":/i18n/";
397 return _translationDirPath;
400 void Quassel::loadTranslation(const QLocale &locale) {
401 QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
402 QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
405 qApp->removeTranslator(qtTranslator);
406 if(quasselTranslator)
407 qApp->removeTranslator(quasselTranslator);
409 // We use QLocale::C to indicate that we don't want a translation
410 if(locale.language() == QLocale::C)
413 qtTranslator = new QTranslator(qApp);
414 qtTranslator->setObjectName("QtTr");
415 qApp->installTranslator(qtTranslator);
417 quasselTranslator = new QTranslator(qApp);
418 quasselTranslator->setObjectName("QuasselTr");
419 qApp->installTranslator(quasselTranslator);
421 QLocale::setDefault(locale);
423 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
425 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
426 quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());