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