a9798054f5cc427389b5bc151e678b549365c351
[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 Quassel *Quassel::_instance = 0;
53
54 Quassel::Quassel() {
55   Q_ASSERT(!_instance);
56   _instance = this;
57
58   // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
59   signal(SIGTERM, handleSignal);
60   signal(SIGINT, handleSignal);
61
62   // we have crashhandler for win32 and unix (based on execinfo).
63   // on mac os we use it's integrated backtrace generator
64 #if defined(Q_OS_WIN32) || (defined(HAVE_EXECINFO) && !defined(Q_OS_MAC))
65
66 # ifndef Q_OS_WIN32
67   // we only handle crashes ourselves if coredumps are disabled
68   struct rlimit *limit = (rlimit *) malloc(sizeof(struct rlimit));
69   int rc = getrlimit(RLIMIT_CORE, limit);
70
71   if(rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
72 # endif
73     signal(SIGABRT, handleSignal);
74     signal(SIGSEGV, handleSignal);
75 #   ifndef Q_OS_WIN32
76     signal(SIGBUS, handleSignal);
77   }
78   free(limit);
79 #   endif
80
81 #endif
82 }
83
84 Quassel::~Quassel() {
85   delete _cliParser;
86 }
87
88 bool Quassel::init() {
89   if(_initialized)
90     return true;  // allow multiple invocations because of MonolithicApplication
91
92   _initialized = true;
93   qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
94
95   registerMetaTypes();
96
97   Network::setDefaultCodecForServer("ISO-8859-1");
98   Network::setDefaultCodecForEncoding("UTF-8");
99   Network::setDefaultCodecForDecoding("ISO-8859-15");
100
101   if(isOptionSet("help")) {
102     cliParser()->usage();
103     return false;
104   }
105
106   if(isOptionSet("version")) {
107     std::cout << qPrintable("Quassel IRC: " + Quassel::buildInfo().plainVersionString) << std::endl;
108     return false;
109   }
110
111   DEBUG = isOptionSet("debug");
112   return true;
113 }
114
115 void Quassel::quit() {
116   QCoreApplication::quit();
117 }
118
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.
121 *
122 */
123 void Quassel::registerMetaTypes() {
124   // Complex types
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");
132
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");
140
141   qRegisterMetaType<IdentityId>("IdentityId");
142   qRegisterMetaType<BufferId>("BufferId");
143   qRegisterMetaType<NetworkId>("NetworkId");
144   qRegisterMetaType<UserId>("UserId");
145   qRegisterMetaType<AccountId>("AccountId");
146   qRegisterMetaType<MsgId>("MsgId");
147
148   qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
149   qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
150   qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
151   qRegisterMetaTypeStreamOperators<UserId>("UserId");
152   qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
153   qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
154 }
155
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";
162
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()) {
177       // dist version
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);
185     } else {
186     // we only have a base version :(
187       _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
188     }
189   } else {
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);
202       }
203     } else {
204       _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
205     }
206   }
207   if(_buildInfo.fancyVersionString.isEmpty())
208     _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
209 }
210
211 //! Signal handler for graceful shutdown.
212 void Quassel::handleSignal(int sig) {
213   switch(sig) {
214   case SIGTERM:
215   case SIGINT:
216     qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
217     if(_instance)
218       _instance->quit();
219     else
220       QCoreApplication::quit();
221     break;
222   case SIGABRT:
223   case SIGSEGV:
224 #ifndef Q_OS_WIN32
225   case SIGBUS:
226 #endif
227     logBacktrace(coreDumpFileName());
228     exit(EXIT_FAILURE);
229     break;
230   default:
231     break;
232   }
233 }
234
235 void Quassel::logFatalMessage(const char *msg) {
236 #ifdef Q_OS_MAC
237   Q_UNUSED(msg)
238 #else
239   QFile dumpFile(coreDumpFileName());
240   dumpFile.open(QIODevice::Append);
241   QTextStream dumpStream(&dumpFile);
242
243   dumpStream << "Fatal: " << msg << '\n';
244   dumpStream.flush();
245   dumpFile.close();
246 #endif
247 }
248
249 const QString &Quassel::coreDumpFileName() {
250   if(_coreDumpFileName.isEmpty()) {
251     QDir configDir(configDirPath());
252     _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
253     QFile dumpFile(_coreDumpFileName);
254     dumpFile.open(QIODevice::Append);
255     QTextStream dumpStream(&dumpFile);
256     dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
257     qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
258     dumpStream.flush();
259     dumpFile.close();
260   }
261   return _coreDumpFileName;
262 }
263
264 QString Quassel::configDirPath() {
265   if(!_configDirPath.isEmpty())
266     return _configDirPath;
267
268   if(Quassel::isOptionSet("datadir")) {
269     qWarning() << "Obsolete option --datadir used!";
270     _configDirPath = Quassel::optionValue("datadir");
271   } else if(Quassel::isOptionSet("configdir")) {
272     _configDirPath = Quassel::optionValue("configdir");
273   } else {
274
275 #ifdef Q_WS_MAC
276     // On Mac, the path is always the same
277     _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
278 #else
279     // We abuse QSettings to find us a sensible path on the other platforms
280 #  ifdef Q_WS_WIN
281     // don't use the registry
282     QSettings::Format format = QSettings::IniFormat;
283 #  else
284     QSettings::Format format = QSettings::NativeFormat;
285 #  endif
286     QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
287     QFileInfo fileInfo(s.fileName());
288     _configDirPath = fileInfo.dir().absolutePath();
289 #endif /* Q_WS_MAC */
290   }
291
292   if(!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
293     _configDirPath += QDir::separator();
294
295   QDir qDir(_configDirPath);
296   if(!qDir.exists(_configDirPath)) {
297     if(!qDir.mkpath(_configDirPath)) {
298       qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
299       return QString();
300     }
301   }
302
303   return _configDirPath;
304 }
305
306 QStringList Quassel::dataDirPaths() {
307   return _dataDirPaths;
308 }
309
310 QStringList Quassel::findDataDirPaths() const {
311   QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
312
313   if(!dataDirNames.isEmpty()) {
314     for(int i = 0; i < dataDirNames.count(); i++)
315       dataDirNames[i].append("/apps/quassel/");
316   } else {
317   // Provide a fallback
318 #ifdef Q_OS_WIN32
319     dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
320                  << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
321                  << QCoreApplication::applicationDirPath();
322   }
323 #elif defined Q_WS_MAC
324     dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
325                  << QCoreApplication::applicationDirPath();
326   }
327 #else
328     dataDirNames.append("/usr/share/apps/quassel/");
329   }
330   // on UNIX, we always check our install prefix
331   QString appDir = QCoreApplication::applicationDirPath();
332   int binpos = appDir.lastIndexOf("/bin");
333   if(binpos >= 0) {
334     appDir.replace(binpos, 4, "/share");
335     appDir.append("/apps/quassel/");
336     if(!dataDirNames.contains(appDir))
337       dataDirNames.append(appDir);
338   }
339 #endif
340
341   // add resource path and workdir just in case
342   dataDirNames << QCoreApplication::applicationDirPath() + "/data/"
343                << ":/data/";
344
345   // append trailing '/' and check for existence
346   QStringList::Iterator iter = dataDirNames.begin();
347   while(iter != dataDirNames.end()) {
348     if(!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
349       iter->append(QDir::separator());
350     if(!QFile::exists(*iter))
351       iter = dataDirNames.erase(iter);
352     else
353       ++iter;
354   }
355
356   return dataDirNames;
357 }
358
359 QString Quassel::findDataFilePath(const QString &fileName) {
360   QStringList dataDirs = dataDirPaths();
361   foreach(QString dataDir, dataDirs) {
362     QString path = dataDir + fileName;
363     if(QFile::exists(path))
364       return path;
365   }
366   return QString();
367 }
368
369 QStringList Quassel::scriptDirPaths() {
370   QStringList res(configDirPath() + "scripts/");
371   foreach(QString path, dataDirPaths())
372     res << path + "scripts/";
373   return res;
374 }
375
376 QString Quassel::translationDirPath() {
377   if(_translationDirPath.isEmpty()) {
378     // We support only one translation dir; fallback mechanisms wouldn't work else.
379     // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
380     foreach(const QString &dir, dataDirPaths()) {
381       if(QFile::exists(dir + "translations/")) {
382         _translationDirPath = dir + "translations/";
383         break;
384       }
385     }
386     if(_translationDirPath.isEmpty())
387       _translationDirPath = ":/i18n/";
388   }
389   return _translationDirPath;
390 }
391
392 void Quassel::loadTranslation(const QLocale &locale) {
393   QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
394   QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
395
396   if(!qtTranslator) {
397     qtTranslator = new QTranslator(qApp);
398     qtTranslator->setObjectName("QtTr");
399     qApp->installTranslator(qtTranslator);
400   }
401   if(!quasselTranslator) {
402     quasselTranslator = new QTranslator(qApp);
403     quasselTranslator->setObjectName("QuasselTr");
404     qApp->installTranslator(quasselTranslator);
405   }
406
407   QLocale::setDefault(locale);
408
409   if(locale.language() == QLocale::C)
410     return;
411
412   bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
413   if(!success)
414     qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
415   quasselTranslator->load(QString("quassel_%1").arg(locale.name()), translationDirPath());
416 }