Automatic back traces on windows.
[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 Quassel::BuildInfo Quassel::_buildInfo;
38 CliParser *Quassel::_cliParser = 0;
39 Quassel::RunMode Quassel::_runMode;
40 bool Quassel::_initialized = false;
41 bool Quassel::DEBUG = false;
42 QString Quassel::_coreDumpFileName;
43
44 Quassel::Quassel() {
45   Q_INIT_RESOURCE(i18n);
46
47   // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
48   signal(SIGTERM, handleSignal);
49   signal(SIGINT, handleSignal);
50
51   // we have crashhandler for win32 and unix (based on execinfo).
52   // on mac os we use it's integrated backtrace generator
53 #if defined(Q_OS_WIN32) || (defined(HAVE_EXECINFO) && !defined(Q_OS_MAC))
54   signal(SIGABRT, handleSignal);
55   signal(SIGSEGV, handleSignal);
56 #  ifndef Q_OS_WIN32
57   signal(SIGBUS, handleSignal);
58 #  endif
59 #endif
60
61   _cliParser = new CliParser();
62
63   // put shared client&core arguments here
64   cliParser()->addSwitch("debug",'d', tr("Enable debug output"));
65   cliParser()->addSwitch("help",'h', tr("Display this help and exit"));
66 }
67
68 Quassel::~Quassel() {
69   delete _cliParser;
70 }
71
72 bool Quassel::init() {
73   if(_initialized)
74     return true;  // allow multiple invocations because of MonolithicApplication
75
76   _initialized = true;
77   qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
78
79   registerMetaTypes();
80   setupTranslations();
81
82   QCoreApplication::setApplicationName(buildInfo().applicationName);
83   QCoreApplication::setOrganizationName(buildInfo().organizationName);
84   QCoreApplication::setOrganizationDomain(buildInfo().organizationDomain);
85
86   Network::setDefaultCodecForServer("ISO-8859-1");
87   Network::setDefaultCodecForEncoding("UTF-8");
88   Network::setDefaultCodecForDecoding("ISO-8859-15");
89
90   if(!cliParser()->parse(QCoreApplication::arguments()) || isOptionSet("help")) {
91     cliParser()->usage();
92     return false;
93   }
94   DEBUG = isOptionSet("debug");
95   return true;
96 }
97
98 //! Register our custom types with Qt's Meta Object System.
99 /**  This makes them available for QVariant and in signals/slots, among other things.
100 *
101 */
102 void Quassel::registerMetaTypes() {
103   // Complex types
104   qRegisterMetaType<QVariant>("QVariant");
105   qRegisterMetaType<Message>("Message");
106   qRegisterMetaType<BufferInfo>("BufferInfo");
107   qRegisterMetaType<NetworkInfo>("NetworkInfo");
108   qRegisterMetaType<Identity>("Identity");
109   qRegisterMetaType<Network::ConnectionState>("Network::ConnectionState");
110
111   qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
112   qRegisterMetaTypeStreamOperators<Message>("Message");
113   qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
114   qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
115   qRegisterMetaTypeStreamOperators<Identity>("Identity");
116   qRegisterMetaTypeStreamOperators<qint8>("Network::ConnectionState");
117
118   qRegisterMetaType<IdentityId>("IdentityId");
119   qRegisterMetaType<BufferId>("BufferId");
120   qRegisterMetaType<NetworkId>("NetworkId");
121   qRegisterMetaType<UserId>("UserId");
122   qRegisterMetaType<AccountId>("AccountId");
123   qRegisterMetaType<MsgId>("MsgId");
124
125   qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
126   qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
127   qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
128   qRegisterMetaTypeStreamOperators<UserId>("UserId");
129   qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
130   qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
131 }
132
133 void Quassel::setupTranslations() {
134   // Set up i18n support
135   QLocale locale = QLocale::system();
136
137   QTranslator *qtTranslator = new QTranslator(qApp);
138   qtTranslator->setObjectName("QtTr");
139   qtTranslator->load(QString(":i18n/qt_%1").arg(locale.name()));
140   qApp->installTranslator(qtTranslator);
141
142   QTranslator *quasselTranslator = new QTranslator(qApp);
143   quasselTranslator->setObjectName("QuasselTr");
144   quasselTranslator->load(QString(":i18n/quassel_%1").arg(locale.name()));
145   qApp->installTranslator(quasselTranslator);
146 }
147
148 void Quassel::setupBuildInfo(const QString &generated) {
149   _buildInfo.applicationName = "Quassel IRC";
150   _buildInfo.coreApplicationName = "Quassel Core";
151   _buildInfo.clientApplicationName = "Quassel Client";
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
174                                            = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
175                                         .arg(_buildInfo.baseVersion)
176                                         .arg(_buildInfo.commitHash.left(7))
177                                         .arg(_buildInfo.commitHash);
178     } else {
179     // we only have a base version :(
180       _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
181     }
182   } else {
183     // analyze what we got from git-describe
184     QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
185     if(rx.exactMatch(_buildInfo.generatedVersion)) {
186       QString distance = rx.cap(2) == "0" ? QString() : QString(" [+%1]").arg(rx.cap(2));
187       _buildInfo.plainVersionString = QString("v%1%2 (git-%3%4)")
188                                         .arg(rx.cap(1), distance, rx.cap(3))
189                                         .arg(_buildInfo.isSourceDirty ? "*" : "");
190       if(!_buildInfo.commitHash.isEmpty()) {
191         _buildInfo.fancyVersionString = QString("v%1%2 (git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
192                                           .arg(rx.cap(1), distance, rx.cap(3))
193                                           .arg(_buildInfo.isSourceDirty ? "*" : "")
194                                           .arg(_buildInfo.commitHash);
195       }
196     } else {
197       _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
198     }
199   }
200   if(_buildInfo.fancyVersionString.isEmpty())
201     _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
202 }
203
204 //! Signal handler for graceful shutdown.
205 void Quassel::handleSignal(int sig) {
206   switch(sig) {
207   case SIGTERM:
208   case SIGINT:
209     qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
210     QCoreApplication::quit();
211     break;
212   case SIGABRT:
213   case SIGSEGV:
214 #ifndef Q_OS_WIN32
215   case SIGBUS:
216 #endif
217     logBacktrace(coreDumpFileName());
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     _coreDumpFileName = QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm"));
241     QFile dumpFile(_coreDumpFileName);
242     dumpFile.open(QIODevice::Append);
243     QTextStream dumpStream(&dumpFile);
244     dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
245     qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
246     dumpStream.flush();
247     dumpFile.close();
248   }
249   return _coreDumpFileName;
250 }