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