f890740d2e4aba4ad3d50f8f6dae3c383657dd40
[quassel.git] / src / common / quassel.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-09 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include "quassel.h"
22
23 #include <iostream>
24 #include <signal.h>
25 #if !defined Q_OS_WIN32 && !defined Q_OS_MAC
26 #  include <sys/resource.h>
27 #endif
28
29 #include <QCoreApplication>
30 #include <QDateTime>
31 #include <QFileInfo>
32 #include <QLibraryInfo>
33 #include <QSettings>
34 #include <QTranslator>
35
36 #include "message.h"
37 #include "identity.h"
38 #include "network.h"
39 #include "bufferinfo.h"
40 #include "types.h"
41 #include "syncableobject.h"
42
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
53 Quassel::Quassel() {
54   // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
55   signal(SIGTERM, handleSignal);
56   signal(SIGINT, handleSignal);
57
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))
61
62 # ifndef Q_OS_WIN32
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);
66
67   if(rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
68 # endif
69     signal(SIGABRT, handleSignal);
70     signal(SIGSEGV, handleSignal);
71 #   ifndef Q_OS_WIN32
72     signal(SIGBUS, handleSignal);
73   }
74   free(limit);
75 #   endif
76
77 #endif
78 }
79
80 Quassel::~Quassel() {
81   delete _cliParser;
82 }
83
84 bool Quassel::init() {
85   if(_initialized)
86     return true;  // allow multiple invocations because of MonolithicApplication
87
88   _initialized = true;
89   qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
90
91   registerMetaTypes();
92
93   Network::setDefaultCodecForServer("ISO-8859-1");
94   Network::setDefaultCodecForEncoding("UTF-8");
95   Network::setDefaultCodecForDecoding("ISO-8859-15");
96
97   if(isOptionSet("help")) {
98     cliParser()->usage();
99     return false;
100   }
101
102   if(isOptionSet("version")) {
103     std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
104     return false;
105   }
106
107   DEBUG = isOptionSet("debug");
108   return true;
109 }
110
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.
113 *
114 */
115 void Quassel::registerMetaTypes() {
116   // Complex types
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");
124
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");
132
133   qRegisterMetaType<IdentityId>("IdentityId");
134   qRegisterMetaType<BufferId>("BufferId");
135   qRegisterMetaType<NetworkId>("NetworkId");
136   qRegisterMetaType<UserId>("UserId");
137   qRegisterMetaType<AccountId>("AccountId");
138   qRegisterMetaType<MsgId>("MsgId");
139
140   qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
141   qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
142   qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
143   qRegisterMetaTypeStreamOperators<UserId>("UserId");
144   qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
145   qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
146 }
147
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";
154
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()) {
169       // dist version
170       _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
171                                         .arg(_buildInfo.baseVersion)
172                                         .arg(_buildInfo.commitHash.left(7));
173       _buildInfo.fancyVersionString = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
174                                         .arg(_buildInfo.baseVersion)
175                                         .arg(_buildInfo.commitHash.left(7))
176                                         .arg(_buildInfo.commitHash);
177     } else {
178     // we only have a base version :(
179       _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
180     }
181   } else {
182     // analyze what we got from git-describe
183     QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
184     if(rx.exactMatch(_buildInfo.generatedVersion)) {
185       QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2));
186       _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)")
187                                         .arg(_buildInfo.baseVersion, distance, rx.cap(3))
188                                         .arg(_buildInfo.isSourceDirty ? "*" : "");
189       if(!_buildInfo.commitHash.isEmpty()) {
190         _buildInfo.fancyVersionString = QString("v%1 (%2git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
191                                           .arg(_buildInfo.baseVersion, distance, rx.cap(3))
192                                           .arg(_buildInfo.isSourceDirty ? "*" : "")
193                                           .arg(_buildInfo.commitHash);
194       }
195     } else {
196       _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
197     }
198   }
199   if(_buildInfo.fancyVersionString.isEmpty())
200     _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
201 }
202
203 //! Signal handler for graceful shutdown.
204 void Quassel::handleSignal(int sig) {
205   switch(sig) {
206   case SIGTERM:
207   case SIGINT:
208     qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
209     QCoreApplication::quit();
210     break;
211   case SIGABRT:
212   case SIGSEGV:
213 #ifndef Q_OS_WIN32
214   case SIGBUS:
215 #endif
216     logBacktrace(coreDumpFileName());
217     exit(EXIT_FAILURE);
218     break;
219   default:
220     break;
221   }
222 }
223
224 void Quassel::logFatalMessage(const char *msg) {
225 #ifdef Q_OS_MAC
226   Q_UNUSED(msg)
227 #else
228   QFile dumpFile(coreDumpFileName());
229   dumpFile.open(QIODevice::Append);
230   QTextStream dumpStream(&dumpFile);
231
232   dumpStream << "Fatal: " << msg << '\n';
233   dumpStream.flush();
234   dumpFile.close();
235 #endif
236 }
237
238 const QString &Quassel::coreDumpFileName() {
239   if(_coreDumpFileName.isEmpty()) {
240     QDir configDir(configDirPath());
241     _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
242     QFile dumpFile(_coreDumpFileName);
243     dumpFile.open(QIODevice::Append);
244     QTextStream dumpStream(&dumpFile);
245     dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
246     qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
247     dumpStream.flush();
248     dumpFile.close();
249   }
250   return _coreDumpFileName;
251 }
252
253 QString Quassel::configDirPath() {
254   if(!_configDirPath.isEmpty())
255     return _configDirPath;
256
257   if(Quassel::isOptionSet("datadir")) {
258     qWarning() << "Obsolete option --datadir used!";
259     _configDirPath = Quassel::optionValue("datadir");
260   } else if(Quassel::isOptionSet("configdir")) {
261     _configDirPath = Quassel::optionValue("configdir");
262   } else {
263
264 #ifdef Q_WS_MAC
265     // On Mac, the path is always the same
266     _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
267 #else
268     // We abuse QSettings to find us a sensible path on the other platforms
269 #  ifdef Q_WS_WIN
270     // don't use the registry
271     QSettings::Format format = QSettings::IniFormat;
272 #  else
273     QSettings::Format format = QSettings::NativeFormat;
274 #  endif
275     QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
276     QFileInfo fileInfo(s.fileName());
277     _configDirPath = fileInfo.dir().absolutePath();
278 #endif /* Q_WS_MAC */
279   }
280
281   if(!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
282     _configDirPath += QDir::separator();
283
284   QDir qDir(_configDirPath);
285   if(!qDir.exists(_configDirPath)) {
286     if(!qDir.mkpath(_configDirPath)) {
287       qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
288       return QString();
289     }
290   }
291
292   return _configDirPath;
293 }
294
295 QStringList Quassel::dataDirPaths() {
296   return _dataDirPaths;
297 }
298
299 QStringList Quassel::findDataDirPaths() const {
300   QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
301
302   if(!dataDirNames.isEmpty()) {
303     for(int i = 0; i < dataDirNames.count(); i++)
304       dataDirNames[i].append("/apps/quassel/");
305   } else {
306   // Provide a fallback
307 #ifdef Q_OS_WIN32
308     dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
309                  << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
310                  << QCoreApplication::applicationDirPath();
311   }
312 #elif defined Q_WS_MAC
313     dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
314                  << QCoreApplication::applicationDirPath();
315   }
316 #else
317     dataDirNames.append("/usr/share/apps/quassel/");
318   }
319   // on UNIX, we always check our install prefix
320   QString appDir = QCoreApplication::applicationDirPath();
321   int binpos = appDir.lastIndexOf("/bin");
322   if(binpos >= 0) {
323     appDir.replace(binpos, 4, "/share");
324     appDir.append("/apps/quassel/");
325     if(!dataDirNames.contains(appDir))
326       dataDirNames.append(appDir);
327   }
328 #endif
329
330   // add resource path and workdir just in case
331   dataDirNames << QCoreApplication::applicationDirPath() + "/data/"
332                << ":/data/";
333
334   // append trailing '/' and check for existence
335   QStringList::Iterator iter = dataDirNames.begin();
336   while(iter != dataDirNames.end()) {
337     if(!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
338       iter->append(QDir::separator());
339     if(!QFile::exists(*iter))
340       iter = dataDirNames.erase(iter);
341     else
342       ++iter;
343   }
344
345   return dataDirNames;
346 }
347
348 QString Quassel::findDataFilePath(const QString &fileName) {
349   QStringList dataDirs = dataDirPaths();
350   foreach(QString dataDir, dataDirs) {
351     QString path = dataDir + fileName;
352     if(QFile::exists(path))
353       return path;
354   }
355   return QString();
356 }
357
358 QString Quassel::translationDirPath() {
359   if(_translationDirPath.isEmpty()) {
360     // We support only one translation dir; fallback mechanisms wouldn't work else.
361     // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
362     foreach(const QString &dir, dataDirPaths()) {
363       if(QFile::exists(dir + "translations/")) {
364         _translationDirPath = dir + "translations/";
365         break;
366       }
367     }
368     if(_translationDirPath.isEmpty())
369       _translationDirPath = ":/i18n/";
370   }
371   return _translationDirPath;
372 }
373
374 void Quassel::loadTranslation(const QLocale &locale) {
375   QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
376   QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
377
378   if(!qtTranslator) {
379     qtTranslator = new QTranslator(qApp);
380     qtTranslator->setObjectName("QtTr");
381     qApp->installTranslator(qtTranslator);
382   }
383   if(!quasselTranslator) {
384     quasselTranslator = new QTranslator(qApp);
385     quasselTranslator->setObjectName("QuasselTr");
386     qApp->installTranslator(quasselTranslator);
387   }
388
389   QLocale::setDefault(locale);
390
391   if(locale.language() == QLocale::C)
392     return;
393
394   bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
395   if(!success)
396     qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
397   quasselTranslator->load(QString("quassel_%1").arg(locale.name()), translationDirPath());
398 }