fixing BR #297 and #309 improved default aliases
[quassel.git] / src / common / quassel.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel IRC Team                         *
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 <signal.h>
24
25 #include <QCoreApplication>
26 #include <QDateTime>
27 #include <QObject>
28 #include <QMetaType>
29
30 #include "message.h"
31 #include "identity.h"
32 #include "network.h"
33 #include "bufferinfo.h"
34 #include "types.h"
35 #include "syncableobject.h"
36
37 #if defined(HAVE_EXECINFO) and not defined(Q_OS_MAC)
38 #  define BUILD_CRASHHANDLER
39 #  include <execinfo.h>
40 #  include <dlfcn.h>
41 #  include <cxxabi.h>
42 #endif
43
44 Quassel::BuildInfo Quassel::_buildInfo;
45 CliParser *Quassel::_cliParser = 0;
46 Quassel::RunMode Quassel::_runMode;
47 bool Quassel::_initialized = false;
48 bool Quassel::DEBUG = false;
49 QString Quassel::_coreDumpFileName;
50
51 Quassel::Quassel() {
52   Q_INIT_RESOURCE(i18n);
53
54   // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
55   signal(SIGTERM, handleSignal);
56   signal(SIGINT, handleSignal);
57
58 #ifdef BUILD_CRASHHANDLER
59   signal(SIGABRT, handleSignal);
60   signal(SIGBUS, handleSignal);
61   signal(SIGSEGV, handleSignal);
62 #endif // #if defined(HAVE_EXECINFO) and not defined(Q_OS_MAC)
63
64   _cliParser = new CliParser();
65
66   // put shared client&core arguments here
67   cliParser()->addSwitch("debug",'d', tr("Enable debug output"));
68   cliParser()->addSwitch("help",'h', tr("Display this help and exit"));
69 }
70
71 Quassel::~Quassel() {
72   delete _cliParser;
73 }
74
75 bool Quassel::init() {
76   if(_initialized)
77     return true;  // allow multiple invocations because of MonolithicApplication
78
79   _initialized = true;
80   qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
81
82   registerMetaTypes();
83   setupTranslations();
84
85   QCoreApplication::setApplicationName(buildInfo().applicationName);
86   QCoreApplication::setOrganizationName(buildInfo().organizationName);
87   QCoreApplication::setOrganizationDomain(buildInfo().organizationDomain);
88
89   Network::setDefaultCodecForServer("ISO-8859-1");
90   Network::setDefaultCodecForEncoding("UTF-8");
91   Network::setDefaultCodecForDecoding("ISO-8859-15");
92
93   if(!cliParser()->parse(QCoreApplication::arguments()) || isOptionSet("help")) {
94     cliParser()->usage();
95     return false;
96   }
97   DEBUG = isOptionSet("debug");
98   return true;
99 }
100
101 //! Register our custom types with Qt's Meta Object System.
102 /**  This makes them available for QVariant and in signals/slots, among other things.
103 *
104 */
105 void Quassel::registerMetaTypes() {
106   // Complex types
107   qRegisterMetaType<QVariant>("QVariant");
108   qRegisterMetaType<Message>("Message");
109   qRegisterMetaType<BufferInfo>("BufferInfo");
110   qRegisterMetaType<NetworkInfo>("NetworkInfo");
111   qRegisterMetaType<Identity>("Identity");
112   qRegisterMetaType<Network::ConnectionState>("Network::ConnectionState");
113
114   qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
115   qRegisterMetaTypeStreamOperators<Message>("Message");
116   qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
117   qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
118   qRegisterMetaTypeStreamOperators<Identity>("Identity");
119   qRegisterMetaTypeStreamOperators<qint8>("Network::ConnectionState");
120
121   qRegisterMetaType<IdentityId>("IdentityId");
122   qRegisterMetaType<BufferId>("BufferId");
123   qRegisterMetaType<NetworkId>("NetworkId");
124   qRegisterMetaType<UserId>("UserId");
125   qRegisterMetaType<AccountId>("AccountId");
126   qRegisterMetaType<MsgId>("MsgId");
127
128   qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
129   qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
130   qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
131   qRegisterMetaTypeStreamOperators<UserId>("UserId");
132   qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
133   qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
134 }
135
136 void Quassel::setupTranslations() {
137   // Set up i18n support
138   QLocale locale = QLocale::system();
139
140   QTranslator *qtTranslator = new QTranslator(qApp);
141   qtTranslator->setObjectName("QtTr");
142   qtTranslator->load(QString(":i18n/qt_%1").arg(locale.name()));
143   qApp->installTranslator(qtTranslator);
144
145   QTranslator *quasselTranslator = new QTranslator(qApp);
146   quasselTranslator->setObjectName("QuasselTr");
147   quasselTranslator->load(QString(":i18n/quassel_%1").arg(locale.name()));
148   qApp->installTranslator(quasselTranslator);
149 }
150
151 void Quassel::setupBuildInfo(const QString &generated) {
152   _buildInfo.applicationName = "Quassel IRC";
153   _buildInfo.coreApplicationName = "Quassel Core";
154   _buildInfo.clientApplicationName = "Quassel Client";
155   _buildInfo.organizationName = "Quassel Project";
156   _buildInfo.organizationDomain = "quassel-irc.org";
157
158   QStringList gen = generated.split(',');
159   Q_ASSERT(gen.count() == 10);
160   _buildInfo.baseVersion = gen[0];
161   _buildInfo.generatedVersion = gen[1];
162   _buildInfo.isSourceDirty = !gen[2].isEmpty();
163   _buildInfo.commitHash = gen[3];
164   _buildInfo.commitDate = gen[4].toUInt();
165   _buildInfo.protocolVersion = gen[5].toUInt();
166   _buildInfo.clientNeedsProtocol = gen[6].toUInt();
167   _buildInfo.coreNeedsProtocol = gen[7].toUInt();
168   _buildInfo.buildDate = QString("%1 %2").arg(gen[8], gen[9]);
169   // create a nice version string
170   if(_buildInfo.generatedVersion.isEmpty()) {
171     if(!_buildInfo.commitHash.isEmpty()) {
172       // dist version
173       _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
174                                         .arg(_buildInfo.baseVersion)
175                                         .arg(_buildInfo.commitHash.left(7));
176                                         _buildInfo.fancyVersionString
177                                            = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
178                                         .arg(_buildInfo.baseVersion)
179                                         .arg(_buildInfo.commitHash.left(7))
180                                         .arg(_buildInfo.commitHash);
181     } else {
182     // we only have a base version :(
183       _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
184     }
185   } else {
186     // analyze what we got from git-describe
187     QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
188     if(rx.exactMatch(_buildInfo.generatedVersion)) {
189       QString distance = rx.cap(2) == "0" ? QString() : QString(" [+%1]").arg(rx.cap(2));
190       _buildInfo.plainVersionString = QString("v%1%2 (git-%3%4)")
191                                         .arg(rx.cap(1), distance, rx.cap(3))
192                                         .arg(_buildInfo.isSourceDirty ? "*" : "");
193       if(!_buildInfo.commitHash.isEmpty()) {
194         _buildInfo.fancyVersionString = QString("v%1%2 (git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
195                                           .arg(rx.cap(1), distance, rx.cap(3))
196                                           .arg(_buildInfo.isSourceDirty ? "*" : "")
197                                           .arg(_buildInfo.commitHash);
198       }
199     } else {
200       _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
201     }
202   }
203   if(_buildInfo.fancyVersionString.isEmpty())
204     _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
205 }
206
207 //! Signal handler for graceful shutdown.
208 void Quassel::handleSignal(int sig) {
209   switch(sig) {
210     case SIGTERM:
211     case SIGINT:
212       qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
213       QCoreApplication::quit();
214       break;
215
216 #ifdef BUILD_CRASHHANDLER
217     case SIGABRT:
218     case SIGBUS:
219     case SIGSEGV:
220       handleCrash();
221 #endif
222       break;
223     default:
224       break;
225   }
226 }
227
228 void Quassel::logFatalMessage(const char *msg) {
229 #ifndef Q_OS_MAC
230   QFile dumpFile(coreDumpFileName());
231   dumpFile.open(QIODevice::WriteOnly);
232   QTextStream dumpStream(&dumpFile);
233 #else
234   QTextStream dumpStream(stderr);
235 #endif
236   
237   dumpStream << "Fatal: " << msg << '\n';
238   dumpStream.flush();
239
240   qInstallMsgHandler(0);
241   abort();
242 }
243
244 void Quassel::handleCrash() {
245 #ifdef BUILD_CRASHHANDLER
246   void* callstack[128];
247   int i, frames = backtrace(callstack, 128);
248
249   QFile dumpFile(coreDumpFileName());
250   dumpFile.open(QIODevice::Append);
251   QTextStream dumpStream(&dumpFile);
252
253   dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
254     
255   for (i = 0; i < frames; ++i) {
256     Dl_info info;
257     dladdr (callstack[i], &info);
258     // as a reference:
259     //     typedef struct
260     //     {
261       //       __const char *dli_fname;   /* File name of defining object.  */
262     //       void *dli_fbase;           /* Load address of that object.  */
263     //       __const char *dli_sname;   /* Name of nearest symbol.  */
264     //       void *dli_saddr;           /* Exact value of nearest symbol.  */
265     //     } Dl_info;
266
267     #if __LP64__
268     int addrSize = 16;
269     #else
270     int addrSize = 8;
271     #endif
272
273     QString funcName;
274     if(info.dli_sname) {
275       char *func = abi::__cxa_demangle(info.dli_sname, 0, 0, 0);
276       if(func) {
277         funcName = QString(func);
278         free(func);
279       } else {
280         funcName = QString(info.dli_sname);
281       }
282     } else {
283       funcName = QString("0x%1").arg((long)info.dli_saddr, addrSize, QLatin1Char('0'));
284     }
285
286     // prettificating the filename
287     QString fileName("???");
288     if(info.dli_fname) {
289       fileName = QString(info.dli_fname);
290       int slashPos = fileName.lastIndexOf('/');
291       if(slashPos != -1)
292         fileName = fileName.mid(slashPos + 1);
293       if(fileName.count() < 20)
294         fileName += QString(20 - fileName.count(), ' ');
295     }
296
297     QString debugLine = QString("#%1 %2 0x%3 %4").arg(i, 3, 10)
298     .arg(fileName)
299     .arg((long)(callstack[i]), addrSize, 16, QLatin1Char('0'))
300     .arg(funcName);
301
302     dumpStream << debugLine << "\n";
303     qDebug() << qPrintable(debugLine);
304   }
305   dumpFile.close();
306   exit(27);
307 #endif /* BUILD_CRASHHANDLER */
308 }
309
310 const QString &Quassel::coreDumpFileName() {
311   if(_coreDumpFileName.isEmpty())
312     _coreDumpFileName = QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm"));
313
314   return _coreDumpFileName;
315 }