d9e180e7936851c011c2eb79197fe41b79f26c28
[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 <signal.h>
24
25 #include <QCoreApplication>
26 #include <QDateTime>
27 #include <QFileInfo>
28 #include <QMetaType>
29 #include <QObject>
30 #include <QSettings>
31
32 #include "message.h"
33 #include "identity.h"
34 #include "network.h"
35 #include "bufferinfo.h"
36 #include "types.h"
37 #include "syncableobject.h"
38
39 Quassel::BuildInfo Quassel::_buildInfo;
40 AbstractCliParser *Quassel::_cliParser = 0;
41 Quassel::RunMode Quassel::_runMode;
42 QString Quassel::_configDirPath;
43 QStringList Quassel::_dataDirPaths;
44 bool Quassel::_initialized = false;
45 bool Quassel::DEBUG = false;
46 QString Quassel::_coreDumpFileName;
47
48 Quassel::Quassel() {
49   // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
50   signal(SIGTERM, handleSignal);
51   signal(SIGINT, handleSignal);
52
53   // we have crashhandler for win32 and unix (based on execinfo).
54   // on mac os we use it's integrated backtrace generator
55 #if defined(Q_OS_WIN32) || (defined(HAVE_EXECINFO) && !defined(Q_OS_MAC))
56   signal(SIGABRT, handleSignal);
57   signal(SIGSEGV, handleSignal);
58 #  ifndef Q_OS_WIN32
59   signal(SIGBUS, handleSignal);
60 #  endif
61 #endif
62
63 }
64
65 Quassel::~Quassel() {
66   delete _cliParser;
67 }
68
69 bool Quassel::init() {
70   if(_initialized)
71     return true;  // allow multiple invocations because of MonolithicApplication
72
73   _initialized = true;
74   qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
75
76   registerMetaTypes();
77
78   Network::setDefaultCodecForServer("ISO-8859-1");
79   Network::setDefaultCodecForEncoding("UTF-8");
80   Network::setDefaultCodecForDecoding("ISO-8859-15");
81
82   if(isOptionSet("help")) {
83     cliParser()->usage();
84     return false;
85   }
86
87   DEBUG = isOptionSet("debug");
88   return true;
89 }
90
91 //! Register our custom types with Qt's Meta Object System.
92 /**  This makes them available for QVariant and in signals/slots, among other things.
93 *
94 */
95 void Quassel::registerMetaTypes() {
96   // Complex types
97   qRegisterMetaType<QVariant>("QVariant");
98   qRegisterMetaType<Message>("Message");
99   qRegisterMetaType<BufferInfo>("BufferInfo");
100   qRegisterMetaType<NetworkInfo>("NetworkInfo");
101   qRegisterMetaType<Network::Server>("Network::Server");
102   qRegisterMetaType<Identity>("Identity");
103   qRegisterMetaType<Network::ConnectionState>("Network::ConnectionState");
104
105   qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
106   qRegisterMetaTypeStreamOperators<Message>("Message");
107   qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
108   qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
109   qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
110   qRegisterMetaTypeStreamOperators<Identity>("Identity");
111   qRegisterMetaTypeStreamOperators<qint8>("Network::ConnectionState");
112
113   qRegisterMetaType<IdentityId>("IdentityId");
114   qRegisterMetaType<BufferId>("BufferId");
115   qRegisterMetaType<NetworkId>("NetworkId");
116   qRegisterMetaType<UserId>("UserId");
117   qRegisterMetaType<AccountId>("AccountId");
118   qRegisterMetaType<MsgId>("MsgId");
119
120   qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
121   qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
122   qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
123   qRegisterMetaTypeStreamOperators<UserId>("UserId");
124   qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
125   qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
126 }
127
128 void Quassel::setupBuildInfo(const QString &generated) {
129   _buildInfo.applicationName = "Quassel IRC";
130   _buildInfo.coreApplicationName = "quasselcore";
131   _buildInfo.clientApplicationName = "quasselclient";
132   _buildInfo.organizationName = "Quassel Project";
133   _buildInfo.organizationDomain = "quassel-irc.org";
134
135   QStringList gen = generated.split(',');
136   Q_ASSERT(gen.count() == 10);
137   _buildInfo.baseVersion = gen[0];
138   _buildInfo.generatedVersion = gen[1];
139   _buildInfo.isSourceDirty = !gen[2].isEmpty();
140   _buildInfo.commitHash = gen[3];
141   _buildInfo.commitDate = gen[4].toUInt();
142   _buildInfo.protocolVersion = gen[5].toUInt();
143   _buildInfo.clientNeedsProtocol = gen[6].toUInt();
144   _buildInfo.coreNeedsProtocol = gen[7].toUInt();
145   _buildInfo.buildDate = QString("%1 %2").arg(gen[8], gen[9]);
146   // create a nice version string
147   if(_buildInfo.generatedVersion.isEmpty()) {
148     if(!_buildInfo.commitHash.isEmpty()) {
149       // dist version
150       _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
151                                         .arg(_buildInfo.baseVersion)
152                                         .arg(_buildInfo.commitHash.left(7));
153                                         _buildInfo.fancyVersionString
154                                            = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
155                                         .arg(_buildInfo.baseVersion)
156                                         .arg(_buildInfo.commitHash.left(7))
157                                         .arg(_buildInfo.commitHash);
158     } else {
159     // we only have a base version :(
160       _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
161     }
162   } else {
163     // analyze what we got from git-describe
164     QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
165     if(rx.exactMatch(_buildInfo.generatedVersion)) {
166       QString distance = rx.cap(2) == "0" ? QString() : QString(" [+%1]").arg(rx.cap(2));
167       _buildInfo.plainVersionString = QString("v%1%2 (git-%3%4)")
168                                         .arg(rx.cap(1), distance, rx.cap(3))
169                                         .arg(_buildInfo.isSourceDirty ? "*" : "");
170       if(!_buildInfo.commitHash.isEmpty()) {
171         _buildInfo.fancyVersionString = QString("v%1%2 (git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
172                                           .arg(rx.cap(1), distance, rx.cap(3))
173                                           .arg(_buildInfo.isSourceDirty ? "*" : "")
174                                           .arg(_buildInfo.commitHash);
175       }
176     } else {
177       _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
178     }
179   }
180   if(_buildInfo.fancyVersionString.isEmpty())
181     _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
182 }
183
184 //! Signal handler for graceful shutdown.
185 void Quassel::handleSignal(int sig) {
186   switch(sig) {
187   case SIGTERM:
188   case SIGINT:
189     qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
190     QCoreApplication::quit();
191     break;
192   case SIGABRT:
193   case SIGSEGV:
194 #ifndef Q_OS_WIN32
195   case SIGBUS:
196 #endif
197     logBacktrace(coreDumpFileName());
198     exit(EXIT_FAILURE);
199     break;
200   default:
201     break;
202   }
203 }
204
205 void Quassel::logFatalMessage(const char *msg) {
206 #ifdef Q_OS_MAC
207   Q_UNUSED(msg)
208 #else
209   QFile dumpFile(coreDumpFileName());
210   dumpFile.open(QIODevice::Append);
211   QTextStream dumpStream(&dumpFile);
212
213   dumpStream << "Fatal: " << msg << '\n';
214   dumpStream.flush();
215   dumpFile.close();
216 #endif
217 }
218
219 const QString &Quassel::coreDumpFileName() {
220   if(_coreDumpFileName.isEmpty()) {
221     _coreDumpFileName = QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm"));
222     QFile dumpFile(_coreDumpFileName);
223     dumpFile.open(QIODevice::Append);
224     QTextStream dumpStream(&dumpFile);
225     dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
226     qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
227     dumpStream.flush();
228     dumpFile.close();
229   }
230   return _coreDumpFileName;
231 }
232
233 QString Quassel::configDirPath() {
234   if(!_configDirPath.isEmpty())
235     return _configDirPath;
236
237   if(Quassel::isOptionSet("datadir")) {
238     qWarning() << "Obsolete option --datadir used!";
239     _configDirPath = Quassel::optionValue("datadir");
240   } else if(Quassel::isOptionSet("configdir")) {
241     _configDirPath = Quassel::optionValue("configdir");
242   } else {
243
244 #ifdef Q_WS_MAC
245     // On Mac, the path is always the same
246     _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
247 #else
248     // We abuse QSettings to find us a sensible path on the other platforms
249 #  ifdef Q_WS_WIN
250     // don't use the registry
251     QSettings::Format format = QSettings::IniFormat;
252 #  else
253     QSettings::Format format = QSettings::NativeFormat;
254 #  endif
255     QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
256     QFileInfo fileInfo(s.fileName());
257     _configDirPath = fileInfo.dir().absolutePath();
258 #endif /* Q_WS_MAC */
259   }
260
261   if(!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
262     _configDirPath += QDir::separator();
263
264   QDir qDir(_configDirPath);
265   if(!qDir.exists(_configDirPath)) {
266     if(!qDir.mkpath(_configDirPath)) {
267       qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
268       return QString();
269     }
270   }
271
272   return _configDirPath;
273 }
274
275 QStringList Quassel::dataDirPaths() {
276   return _dataDirPaths;
277 }
278
279 QStringList Quassel::findDataDirPaths() const {
280   QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
281
282   if(!dataDirNames.isEmpty()) {
283     for(int i = 0; i < dataDirNames.count(); i++)
284       dataDirNames[i].append("/apps/quassel/");
285   } else {
286   // Provide a fallback
287   // FIXME fix this for win and mac!
288 #ifdef Q_OS_WIN32
289     dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
290                  << QCoreApplication::applicationDirPath();
291 #elif defined Q_WS_MAC
292     dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
293                  << QCoreApplication::applicationDirPath();
294 #else
295     if(dataDirNames.isEmpty())
296       dataDirNames.append("/usr/share/apps/quassel/");
297     // on UNIX, we always check our install prefix
298     QString appDir = QCoreApplication::applicationDirPath();
299     int binpos = appDir.lastIndexOf("/bin");
300     if(binpos >= 0) {
301       appDir.replace(binpos, 4, "/share");
302       appDir.append("/apps/quassel/");
303       if(!dataDirNames.contains(appDir))
304         dataDirNames.append(appDir);
305     }
306 #endif
307   }
308
309   // add resource path and workdir just in case
310   dataDirNames << ":/data/"
311                << QCoreApplication::applicationDirPath() + "/data/"
312                << QCoreApplication::applicationDirPath();
313
314   // append trailing '/' and check for existence
315   QStringList::Iterator iter = dataDirNames.begin();
316   while(iter != dataDirNames.end()) {
317     if(!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
318       iter->append(QDir::separator());
319     if(!QFile::exists(*iter))
320       iter = dataDirNames.erase(iter);
321     else
322       ++iter;
323   }
324
325   return dataDirNames;
326 }
327
328 QString Quassel::findDataFilePath(const QString &fileName) {
329   QStringList dataDirs = dataDirPaths();
330   foreach(QString dataDir, dataDirs) {
331     QString path = dataDir + fileName;
332     if(QFile::exists(path))
333       return path;
334   }
335   return QString();
336 }