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