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;
54 // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
55 signal(SIGTERM, handleSignal);
56 signal(SIGINT, handleSignal);
58 // we have crashhandler for win32 and unix (based on execinfo).
59 // on mac os we use it's integrated backtrace generator
60 #if defined(Q_OS_WIN32) || (defined(HAVE_EXECINFO) && !defined(Q_OS_MAC))
63 // we only handle crashes ourselves if coredumps are disabled
64 struct rlimit *limit = (rlimit *) malloc(sizeof(struct rlimit));
65 int rc = getrlimit(RLIMIT_CORE, limit);
67 if(rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
69 signal(SIGABRT, handleSignal);
70 signal(SIGSEGV, handleSignal);
72 signal(SIGBUS, handleSignal);
84 bool Quassel::init() {
86 return true; // allow multiple invocations because of MonolithicApplication
89 qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
93 Network::setDefaultCodecForServer("ISO-8859-1");
94 Network::setDefaultCodecForEncoding("UTF-8");
95 Network::setDefaultCodecForDecoding("ISO-8859-15");
97 if(isOptionSet("help")) {
102 if(isOptionSet("version")) {
103 std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
107 DEBUG = isOptionSet("debug");
111 //! Register our custom types with Qt's Meta Object System.
112 /** This makes them available for QVariant and in signals/slots, among other things.
115 void Quassel::registerMetaTypes() {
117 qRegisterMetaType<QVariant>("QVariant");
118 qRegisterMetaType<Message>("Message");
119 qRegisterMetaType<BufferInfo>("BufferInfo");
120 qRegisterMetaType<NetworkInfo>("NetworkInfo");
121 qRegisterMetaType<Network::Server>("Network::Server");
122 qRegisterMetaType<Identity>("Identity");
123 qRegisterMetaType<Network::ConnectionState>("Network::ConnectionState");
125 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
126 qRegisterMetaTypeStreamOperators<Message>("Message");
127 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
128 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
129 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
130 qRegisterMetaTypeStreamOperators<Identity>("Identity");
131 qRegisterMetaTypeStreamOperators<qint8>("Network::ConnectionState");
133 qRegisterMetaType<IdentityId>("IdentityId");
134 qRegisterMetaType<BufferId>("BufferId");
135 qRegisterMetaType<NetworkId>("NetworkId");
136 qRegisterMetaType<UserId>("UserId");
137 qRegisterMetaType<AccountId>("AccountId");
138 qRegisterMetaType<MsgId>("MsgId");
140 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
141 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
142 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
143 qRegisterMetaTypeStreamOperators<UserId>("UserId");
144 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
145 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
148 void Quassel::setupBuildInfo(const QString &generated) {
149 _buildInfo.applicationName = "Quassel IRC";
150 _buildInfo.coreApplicationName = "quasselcore";
151 _buildInfo.clientApplicationName = "quasselclient";
152 _buildInfo.organizationName = "Quassel Project";
153 _buildInfo.organizationDomain = "quassel-irc.org";
155 QStringList gen = generated.split(',');
156 Q_ASSERT(gen.count() == 10);
157 _buildInfo.baseVersion = gen[0];
158 _buildInfo.generatedVersion = gen[1];
159 _buildInfo.isSourceDirty = !gen[2].isEmpty();
160 _buildInfo.commitHash = gen[3];
161 _buildInfo.commitDate = gen[4].toUInt();
162 _buildInfo.protocolVersion = gen[5].toUInt();
163 _buildInfo.clientNeedsProtocol = gen[6].toUInt();
164 _buildInfo.coreNeedsProtocol = gen[7].toUInt();
165 _buildInfo.buildDate = QString("%1 %2").arg(gen[8], gen[9]);
166 // create a nice version string
167 if(_buildInfo.generatedVersion.isEmpty()) {
168 if(!_buildInfo.commitHash.isEmpty()) {
170 _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
171 .arg(_buildInfo.baseVersion)
172 .arg(_buildInfo.commitHash.left(7));
173 _buildInfo.fancyVersionString
174 = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
175 .arg(_buildInfo.baseVersion)
176 .arg(_buildInfo.commitHash.left(7))
177 .arg(_buildInfo.commitHash);
179 // we only have a base version :(
180 _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
183 // analyze what we got from git-describe
184 QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
185 if(rx.exactMatch(_buildInfo.generatedVersion)) {
186 QString distance = rx.cap(2) == "0" ? QString() : QString(" [+%1]").arg(rx.cap(2));
187 _buildInfo.plainVersionString = QString("v%1%2 (git-%3%4)")
188 .arg(rx.cap(1), distance, rx.cap(3))
189 .arg(_buildInfo.isSourceDirty ? "*" : "");
190 if(!_buildInfo.commitHash.isEmpty()) {
191 _buildInfo.fancyVersionString = QString("v%1%2 (git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
192 .arg(rx.cap(1), distance, rx.cap(3))
193 .arg(_buildInfo.isSourceDirty ? "*" : "")
194 .arg(_buildInfo.commitHash);
197 _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
200 if(_buildInfo.fancyVersionString.isEmpty())
201 _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
204 //! Signal handler for graceful shutdown.
205 void Quassel::handleSignal(int sig) {
209 qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
210 QCoreApplication::quit();
217 logBacktrace(coreDumpFileName());
225 void Quassel::logFatalMessage(const char *msg) {
229 QFile dumpFile(coreDumpFileName());
230 dumpFile.open(QIODevice::Append);
231 QTextStream dumpStream(&dumpFile);
233 dumpStream << "Fatal: " << msg << '\n';
239 const QString &Quassel::coreDumpFileName() {
240 if(_coreDumpFileName.isEmpty()) {
241 QDir configDir(configDirPath());
242 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
243 QFile dumpFile(_coreDumpFileName);
244 dumpFile.open(QIODevice::Append);
245 QTextStream dumpStream(&dumpFile);
246 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
247 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
251 return _coreDumpFileName;
254 QString Quassel::configDirPath() {
255 if(!_configDirPath.isEmpty())
256 return _configDirPath;
258 if(Quassel::isOptionSet("datadir")) {
259 qWarning() << "Obsolete option --datadir used!";
260 _configDirPath = Quassel::optionValue("datadir");
261 } else if(Quassel::isOptionSet("configdir")) {
262 _configDirPath = Quassel::optionValue("configdir");
266 // On Mac, the path is always the same
267 _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
269 // We abuse QSettings to find us a sensible path on the other platforms
271 // don't use the registry
272 QSettings::Format format = QSettings::IniFormat;
274 QSettings::Format format = QSettings::NativeFormat;
276 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
277 QFileInfo fileInfo(s.fileName());
278 _configDirPath = fileInfo.dir().absolutePath();
279 #endif /* Q_WS_MAC */
282 if(!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
283 _configDirPath += QDir::separator();
285 QDir qDir(_configDirPath);
286 if(!qDir.exists(_configDirPath)) {
287 if(!qDir.mkpath(_configDirPath)) {
288 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
293 return _configDirPath;
296 QStringList Quassel::dataDirPaths() {
297 return _dataDirPaths;
300 QStringList Quassel::findDataDirPaths() const {
301 QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
303 if(!dataDirNames.isEmpty()) {
304 for(int i = 0; i < dataDirNames.count(); i++)
305 dataDirNames[i].append("/apps/quassel/");
307 // Provide a fallback
309 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
310 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
311 << QCoreApplication::applicationDirPath();
313 #elif defined Q_WS_MAC
314 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
315 << QCoreApplication::applicationDirPath();
318 dataDirNames.append("/usr/share/apps/quassel/");
320 // on UNIX, we always check our install prefix
321 QString appDir = QCoreApplication::applicationDirPath();
322 int binpos = appDir.lastIndexOf("/bin");
324 appDir.replace(binpos, 4, "/share");
325 appDir.append("/apps/quassel/");
326 if(!dataDirNames.contains(appDir))
327 dataDirNames.append(appDir);
331 // add resource path and workdir just in case
332 dataDirNames << QCoreApplication::applicationDirPath() + "/data/"
335 // append trailing '/' and check for existence
336 QStringList::Iterator iter = dataDirNames.begin();
337 while(iter != dataDirNames.end()) {
338 if(!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
339 iter->append(QDir::separator());
340 if(!QFile::exists(*iter))
341 iter = dataDirNames.erase(iter);
349 QString Quassel::findDataFilePath(const QString &fileName) {
350 QStringList dataDirs = dataDirPaths();
351 foreach(QString dataDir, dataDirs) {
352 QString path = dataDir + fileName;
353 if(QFile::exists(path))
359 QStringList Quassel::scriptDirPaths() {
360 QStringList res(configDirPath() + "scripts/");
361 foreach(QString path, dataDirPaths())
362 res << path + "scripts/";
366 QString Quassel::translationDirPath() {
367 if(_translationDirPath.isEmpty()) {
368 // We support only one translation dir; fallback mechanisms wouldn't work else.
369 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
370 foreach(const QString &dir, dataDirPaths()) {
371 if(QFile::exists(dir + "translations/")) {
372 _translationDirPath = dir + "translations/";
376 if(_translationDirPath.isEmpty())
377 _translationDirPath = ":/i18n/";
379 return _translationDirPath;
382 void Quassel::loadTranslation(const QLocale &locale) {
383 QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
384 QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
387 qtTranslator = new QTranslator(qApp);
388 qtTranslator->setObjectName("QtTr");
389 qApp->installTranslator(qtTranslator);
391 if(!quasselTranslator) {
392 quasselTranslator = new QTranslator(qApp);
393 quasselTranslator->setObjectName("QuasselTr");
394 qApp->installTranslator(quasselTranslator);
397 QLocale::setDefault(locale);
399 if(locale.language() == QLocale::C)
402 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
404 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
405 quasselTranslator->load(QString("quassel_%1").arg(locale.name()), translationDirPath());