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