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