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