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