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;
54 Quassel::LogLevel Quassel::_logLevel = InfoLevel;
55 QFile *Quassel::_logFile = 0;
56 bool Quassel::_logToSyslog = false;
62 // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
63 signal(SIGTERM, handleSignal);
64 signal(SIGINT, handleSignal);
70 logFile()->deleteLater();
75 bool Quassel::init() {
77 return true; // allow multiple invocations because of MonolithicApplication
80 // we have crashhandler for win32 and unix (based on execinfo).
81 #if defined(Q_OS_WIN32) || defined(HAVE_EXECINFO)
83 // we only handle crashes ourselves if coredumps are disabled
84 struct rlimit *limit = (rlimit *) malloc(sizeof(struct rlimit));
85 int rc = getrlimit(RLIMIT_CORE, limit);
87 if(rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
88 # endif /* Q_OS_WIN32 */
89 signal(SIGABRT, handleSignal);
90 signal(SIGSEGV, handleSignal);
92 signal(SIGBUS, handleSignal);
95 # endif /* Q_OS_WIN32 */
96 #endif /* Q_OS_WIN32 || HAVE_EXECINFO */
100 qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
104 Network::setDefaultCodecForServer("ISO-8859-1");
105 Network::setDefaultCodecForEncoding("UTF-8");
106 Network::setDefaultCodecForDecoding("ISO-8859-15");
108 if(isOptionSet("help")) {
109 cliParser()->usage();
113 if(isOptionSet("version")) {
114 std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
118 DEBUG = isOptionSet("debug");
121 if(isOptionSet("loglevel")) {
122 QString level = optionValue("loglevel");
124 if(level == "Debug") _logLevel = DebugLevel;
125 else if(level == "Info") _logLevel = InfoLevel;
126 else if(level == "Warning") _logLevel= WarningLevel;
127 else if(level == "Error") _logLevel = ErrorLevel;
130 QString logfilename = optionValue("logfile");
131 if(!logfilename.isEmpty()) {
132 _logFile = new QFile(logfilename);
133 if(!_logFile->open(QIODevice::Append | QIODevice::Text)) {
134 qWarning() << "Could not open log file" << logfilename << ":" << _logFile->errorString();
135 _logFile->deleteLater();
140 _logToSyslog = isOptionSet("syslog");
145 void Quassel::quit() {
146 QCoreApplication::quit();
149 //! Register our custom types with Qt's Meta Object System.
150 /** This makes them available for QVariant and in signals/slots, among other things.
153 void Quassel::registerMetaTypes() {
155 qRegisterMetaType<Message>("Message");
156 qRegisterMetaType<BufferInfo>("BufferInfo");
157 qRegisterMetaType<NetworkInfo>("NetworkInfo");
158 qRegisterMetaType<Network::Server>("Network::Server");
159 qRegisterMetaType<Identity>("Identity");
160 qRegisterMetaType<Network::ConnectionState>("Network::ConnectionState");
162 qRegisterMetaTypeStreamOperators<Message>("Message");
163 qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
164 qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
165 qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
166 qRegisterMetaTypeStreamOperators<Identity>("Identity");
167 qRegisterMetaTypeStreamOperators<qint8>("Network::ConnectionState");
169 qRegisterMetaType<IdentityId>("IdentityId");
170 qRegisterMetaType<BufferId>("BufferId");
171 qRegisterMetaType<NetworkId>("NetworkId");
172 qRegisterMetaType<UserId>("UserId");
173 qRegisterMetaType<AccountId>("AccountId");
174 qRegisterMetaType<MsgId>("MsgId");
176 qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
177 qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
178 qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
179 qRegisterMetaTypeStreamOperators<UserId>("UserId");
180 qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
181 qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
183 // Versions of Qt prior to 4.7 didn't define QVariant as a meta type
184 if(!QMetaType::type("QVariant")) {
185 qRegisterMetaType<QVariant>("QVariant");
186 qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
190 void Quassel::setupBuildInfo(const QString &generated) {
191 _buildInfo.applicationName = "Quassel IRC";
192 _buildInfo.coreApplicationName = "quasselcore";
193 _buildInfo.clientApplicationName = "quasselclient";
194 _buildInfo.organizationName = "Quassel Project";
195 _buildInfo.organizationDomain = "quassel-irc.org";
197 QStringList gen = generated.split(',');
198 Q_ASSERT(gen.count() == 10);
199 _buildInfo.baseVersion = gen[0];
200 _buildInfo.generatedVersion = gen[1];
201 _buildInfo.isSourceDirty = !gen[2].isEmpty();
202 _buildInfo.commitHash = gen[3];
203 _buildInfo.commitDate = gen[4].toUInt();
204 _buildInfo.protocolVersion = gen[5].toUInt();
205 _buildInfo.clientNeedsProtocol = gen[6].toUInt();
206 _buildInfo.coreNeedsProtocol = gen[7].toUInt();
207 _buildInfo.buildDate = QString("%1 %2").arg(gen[8], gen[9]);
208 // create a nice version string
209 if(_buildInfo.generatedVersion.isEmpty()) {
210 if(!_buildInfo.commitHash.isEmpty()) {
212 _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
213 .arg(_buildInfo.baseVersion)
214 .arg(_buildInfo.commitHash.left(7));
215 _buildInfo.fancyVersionString = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
216 .arg(_buildInfo.baseVersion)
217 .arg(_buildInfo.commitHash.left(7))
218 .arg(_buildInfo.commitHash);
220 // we only have a base version :(
221 _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
224 // analyze what we got from git-describe
225 QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
226 if(rx.exactMatch(_buildInfo.generatedVersion)) {
227 QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2));
228 _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)")
229 .arg(_buildInfo.baseVersion, distance, rx.cap(3))
230 .arg(_buildInfo.isSourceDirty ? "*" : "");
231 if(!_buildInfo.commitHash.isEmpty()) {
232 _buildInfo.fancyVersionString = QString("v%1 (%2git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
233 .arg(_buildInfo.baseVersion, distance, rx.cap(3))
234 .arg(_buildInfo.isSourceDirty ? "*" : "")
235 .arg(_buildInfo.commitHash);
238 _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
241 if(_buildInfo.fancyVersionString.isEmpty())
242 _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
245 //! Signal handler for graceful shutdown.
246 void Quassel::handleSignal(int sig) {
250 qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
254 QCoreApplication::quit();
261 logBacktrace(coreDumpFileName());
269 void Quassel::logFatalMessage(const char *msg) {
273 QFile dumpFile(coreDumpFileName());
274 dumpFile.open(QIODevice::Append);
275 QTextStream dumpStream(&dumpFile);
277 dumpStream << "Fatal: " << msg << '\n';
283 Quassel::Features Quassel::features() {
285 for(int i = 1; i <= NumFeatures; i<<=1)
286 feats |= (Feature) i;
291 const QString &Quassel::coreDumpFileName() {
292 if(_coreDumpFileName.isEmpty()) {
293 QDir configDir(configDirPath());
294 _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
295 QFile dumpFile(_coreDumpFileName);
296 dumpFile.open(QIODevice::Append);
297 QTextStream dumpStream(&dumpFile);
298 dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
299 qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
303 return _coreDumpFileName;
306 QString Quassel::configDirPath() {
307 if(!_configDirPath.isEmpty())
308 return _configDirPath;
310 if(Quassel::isOptionSet("datadir")) {
311 qWarning() << "Obsolete option --datadir used!";
312 _configDirPath = Quassel::optionValue("datadir");
313 } else if(Quassel::isOptionSet("configdir")) {
314 _configDirPath = Quassel::optionValue("configdir");
318 // On Mac, the path is always the same
319 _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
321 // We abuse QSettings to find us a sensible path on the other platforms
323 // don't use the registry
324 QSettings::Format format = QSettings::IniFormat;
326 QSettings::Format format = QSettings::NativeFormat;
328 QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
329 QFileInfo fileInfo(s.fileName());
330 _configDirPath = fileInfo.dir().absolutePath();
331 #endif /* Q_WS_MAC */
334 if(!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
335 _configDirPath += QDir::separator();
337 QDir qDir(_configDirPath);
338 if(!qDir.exists(_configDirPath)) {
339 if(!qDir.mkpath(_configDirPath)) {
340 qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
345 return _configDirPath;
348 QStringList Quassel::dataDirPaths() {
349 return _dataDirPaths;
352 QStringList Quassel::findDataDirPaths() const {
353 QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
355 if(!dataDirNames.isEmpty()) {
356 for(int i = 0; i < dataDirNames.count(); i++)
357 dataDirNames[i].append("/apps/quassel/");
359 // Provide a fallback
361 dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
362 << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
363 << QCoreApplication::applicationDirPath();
365 #elif defined Q_WS_MAC
366 dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
367 << QCoreApplication::applicationDirPath();
370 dataDirNames.append("/usr/share/apps/quassel/");
372 // on UNIX, we always check our install prefix
373 QString appDir = QCoreApplication::applicationDirPath();
374 int binpos = appDir.lastIndexOf("/bin");
376 appDir.replace(binpos, 4, "/share");
377 appDir.append("/apps/quassel/");
378 if(!dataDirNames.contains(appDir))
379 dataDirNames.append(appDir);
383 // add resource path and workdir just in case
384 dataDirNames << QCoreApplication::applicationDirPath() + "/data/"
387 // append trailing '/' and check for existence
388 QStringList::Iterator iter = dataDirNames.begin();
389 while(iter != dataDirNames.end()) {
390 if(!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
391 iter->append(QDir::separator());
392 if(!QFile::exists(*iter))
393 iter = dataDirNames.erase(iter);
401 QString Quassel::findDataFilePath(const QString &fileName) {
402 QStringList dataDirs = dataDirPaths();
403 foreach(QString dataDir, dataDirs) {
404 QString path = dataDir + fileName;
405 if(QFile::exists(path))
411 QStringList Quassel::scriptDirPaths() {
412 QStringList res(configDirPath() + "scripts/");
413 foreach(QString path, dataDirPaths())
414 res << path + "scripts/";
418 QString Quassel::translationDirPath() {
419 if(_translationDirPath.isEmpty()) {
420 // We support only one translation dir; fallback mechanisms wouldn't work else.
421 // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
422 foreach(const QString &dir, dataDirPaths()) {
423 if(QFile::exists(dir + "translations/")) {
424 _translationDirPath = dir + "translations/";
428 if(_translationDirPath.isEmpty())
429 _translationDirPath = ":/i18n/";
431 return _translationDirPath;
434 void Quassel::loadTranslation(const QLocale &locale) {
435 QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
436 QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
439 qApp->removeTranslator(qtTranslator);
440 if(quasselTranslator)
441 qApp->removeTranslator(quasselTranslator);
443 // We use QLocale::C to indicate that we don't want a translation
444 if(locale.language() == QLocale::C)
447 qtTranslator = new QTranslator(qApp);
448 qtTranslator->setObjectName("QtTr");
449 qApp->installTranslator(qtTranslator);
451 quasselTranslator = new QTranslator(qApp);
452 quasselTranslator->setObjectName("QuasselTr");
453 qApp->installTranslator(quasselTranslator);
455 QLocale::setDefault(locale);
457 bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
459 qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
460 quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());