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