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