rename translation files to <2 letter ISO code>.po
[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<QVariant>("QVariant");
126   qRegisterMetaType<Message>("Message");
127   qRegisterMetaType<BufferInfo>("BufferInfo");
128   qRegisterMetaType<NetworkInfo>("NetworkInfo");
129   qRegisterMetaType<Network::Server>("Network::Server");
130   qRegisterMetaType<Identity>("Identity");
131   qRegisterMetaType<Network::ConnectionState>("Network::ConnectionState");
132
133   qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
134   qRegisterMetaTypeStreamOperators<Message>("Message");
135   qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
136   qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
137   qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
138   qRegisterMetaTypeStreamOperators<Identity>("Identity");
139   qRegisterMetaTypeStreamOperators<qint8>("Network::ConnectionState");
140
141   qRegisterMetaType<IdentityId>("IdentityId");
142   qRegisterMetaType<BufferId>("BufferId");
143   qRegisterMetaType<NetworkId>("NetworkId");
144   qRegisterMetaType<UserId>("UserId");
145   qRegisterMetaType<AccountId>("AccountId");
146   qRegisterMetaType<MsgId>("MsgId");
147
148   qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
149   qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
150   qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
151   qRegisterMetaTypeStreamOperators<UserId>("UserId");
152   qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
153   qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
154 }
155
156 void Quassel::setupBuildInfo(const QString &generated) {
157   _buildInfo.applicationName = "Quassel IRC";
158   _buildInfo.coreApplicationName = "quasselcore";
159   _buildInfo.clientApplicationName = "quasselclient";
160   _buildInfo.organizationName = "Quassel Project";
161   _buildInfo.organizationDomain = "quassel-irc.org";
162
163   QStringList gen = generated.split(',');
164   Q_ASSERT(gen.count() == 10);
165   _buildInfo.baseVersion = gen[0];
166   _buildInfo.generatedVersion = gen[1];
167   _buildInfo.isSourceDirty = !gen[2].isEmpty();
168   _buildInfo.commitHash = gen[3];
169   _buildInfo.commitDate = gen[4].toUInt();
170   _buildInfo.protocolVersion = gen[5].toUInt();
171   _buildInfo.clientNeedsProtocol = gen[6].toUInt();
172   _buildInfo.coreNeedsProtocol = gen[7].toUInt();
173   _buildInfo.buildDate = QString("%1 %2").arg(gen[8], gen[9]);
174   // create a nice version string
175   if(_buildInfo.generatedVersion.isEmpty()) {
176     if(!_buildInfo.commitHash.isEmpty()) {
177       // dist version
178       _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
179                                         .arg(_buildInfo.baseVersion)
180                                         .arg(_buildInfo.commitHash.left(7));
181       _buildInfo.fancyVersionString = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
182                                         .arg(_buildInfo.baseVersion)
183                                         .arg(_buildInfo.commitHash.left(7))
184                                         .arg(_buildInfo.commitHash);
185     } else {
186     // we only have a base version :(
187       _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
188     }
189   } else {
190     // analyze what we got from git-describe
191     QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
192     if(rx.exactMatch(_buildInfo.generatedVersion)) {
193       QString distance = rx.cap(2) == "0" ? QString() : QString("%1+%2 ").arg(rx.cap(1), rx.cap(2));
194       _buildInfo.plainVersionString = QString("v%1 (%2git-%3%4)")
195                                         .arg(_buildInfo.baseVersion, distance, rx.cap(3))
196                                         .arg(_buildInfo.isSourceDirty ? "*" : "");
197       if(!_buildInfo.commitHash.isEmpty()) {
198         _buildInfo.fancyVersionString = QString("v%1 (%2git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
199                                           .arg(_buildInfo.baseVersion, distance, rx.cap(3))
200                                           .arg(_buildInfo.isSourceDirty ? "*" : "")
201                                           .arg(_buildInfo.commitHash);
202       }
203     } else {
204       _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
205     }
206   }
207   if(_buildInfo.fancyVersionString.isEmpty())
208     _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
209 }
210
211 //! Signal handler for graceful shutdown.
212 void Quassel::handleSignal(int sig) {
213   switch(sig) {
214   case SIGTERM:
215   case SIGINT:
216     qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
217     if(_instance)
218       _instance->quit();
219     else
220       QCoreApplication::quit();
221     break;
222   case SIGABRT:
223   case SIGSEGV:
224 #ifndef Q_OS_WIN32
225   case SIGBUS:
226 #endif
227     logBacktrace(coreDumpFileName());
228     exit(EXIT_FAILURE);
229     break;
230   default:
231     break;
232   }
233 }
234
235 void Quassel::logFatalMessage(const char *msg) {
236 #ifdef Q_OS_MAC
237   Q_UNUSED(msg)
238 #else
239   QFile dumpFile(coreDumpFileName());
240   dumpFile.open(QIODevice::Append);
241   QTextStream dumpStream(&dumpFile);
242
243   dumpStream << "Fatal: " << msg << '\n';
244   dumpStream.flush();
245   dumpFile.close();
246 #endif
247 }
248
249 Quassel::Features Quassel::features() {
250   Features feats = 0;
251   for(int i = 1; i <= NumFeatures; i<<=1)
252     feats |= (Feature) i;
253
254   return feats;
255 }
256
257 const QString &Quassel::coreDumpFileName() {
258   if(_coreDumpFileName.isEmpty()) {
259     QDir configDir(configDirPath());
260     _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
261     QFile dumpFile(_coreDumpFileName);
262     dumpFile.open(QIODevice::Append);
263     QTextStream dumpStream(&dumpFile);
264     dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
265     qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
266     dumpStream.flush();
267     dumpFile.close();
268   }
269   return _coreDumpFileName;
270 }
271
272 QString Quassel::configDirPath() {
273   if(!_configDirPath.isEmpty())
274     return _configDirPath;
275
276   if(Quassel::isOptionSet("datadir")) {
277     qWarning() << "Obsolete option --datadir used!";
278     _configDirPath = Quassel::optionValue("datadir");
279   } else if(Quassel::isOptionSet("configdir")) {
280     _configDirPath = Quassel::optionValue("configdir");
281   } else {
282
283 #ifdef Q_WS_MAC
284     // On Mac, the path is always the same
285     _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
286 #else
287     // We abuse QSettings to find us a sensible path on the other platforms
288 #  ifdef Q_WS_WIN
289     // don't use the registry
290     QSettings::Format format = QSettings::IniFormat;
291 #  else
292     QSettings::Format format = QSettings::NativeFormat;
293 #  endif
294     QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
295     QFileInfo fileInfo(s.fileName());
296     _configDirPath = fileInfo.dir().absolutePath();
297 #endif /* Q_WS_MAC */
298   }
299
300   if(!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
301     _configDirPath += QDir::separator();
302
303   QDir qDir(_configDirPath);
304   if(!qDir.exists(_configDirPath)) {
305     if(!qDir.mkpath(_configDirPath)) {
306       qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
307       return QString();
308     }
309   }
310
311   return _configDirPath;
312 }
313
314 QStringList Quassel::dataDirPaths() {
315   return _dataDirPaths;
316 }
317
318 QStringList Quassel::findDataDirPaths() const {
319   QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
320
321   if(!dataDirNames.isEmpty()) {
322     for(int i = 0; i < dataDirNames.count(); i++)
323       dataDirNames[i].append("/apps/quassel/");
324   } else {
325   // Provide a fallback
326 #ifdef Q_OS_WIN32
327     dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
328                  << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
329                  << QCoreApplication::applicationDirPath();
330   }
331 #elif defined Q_WS_MAC
332     dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
333                  << QCoreApplication::applicationDirPath();
334   }
335 #else
336     dataDirNames.append("/usr/share/apps/quassel/");
337   }
338   // on UNIX, we always check our install prefix
339   QString appDir = QCoreApplication::applicationDirPath();
340   int binpos = appDir.lastIndexOf("/bin");
341   if(binpos >= 0) {
342     appDir.replace(binpos, 4, "/share");
343     appDir.append("/apps/quassel/");
344     if(!dataDirNames.contains(appDir))
345       dataDirNames.append(appDir);
346   }
347 #endif
348
349   // add resource path and workdir just in case
350   dataDirNames << QCoreApplication::applicationDirPath() + "/data/"
351                << ":/data/";
352
353   // append trailing '/' and check for existence
354   QStringList::Iterator iter = dataDirNames.begin();
355   while(iter != dataDirNames.end()) {
356     if(!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
357       iter->append(QDir::separator());
358     if(!QFile::exists(*iter))
359       iter = dataDirNames.erase(iter);
360     else
361       ++iter;
362   }
363
364   return dataDirNames;
365 }
366
367 QString Quassel::findDataFilePath(const QString &fileName) {
368   QStringList dataDirs = dataDirPaths();
369   foreach(QString dataDir, dataDirs) {
370     QString path = dataDir + fileName;
371     if(QFile::exists(path))
372       return path;
373   }
374   return QString();
375 }
376
377 QStringList Quassel::scriptDirPaths() {
378   QStringList res(configDirPath() + "scripts/");
379   foreach(QString path, dataDirPaths())
380     res << path + "scripts/";
381   return res;
382 }
383
384 QString Quassel::translationDirPath() {
385   if(_translationDirPath.isEmpty()) {
386     // We support only one translation dir; fallback mechanisms wouldn't work else.
387     // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
388     foreach(const QString &dir, dataDirPaths()) {
389       if(QFile::exists(dir + "translations/")) {
390         _translationDirPath = dir + "translations/";
391         break;
392       }
393     }
394     if(_translationDirPath.isEmpty())
395       _translationDirPath = ":/i18n/";
396   }
397   return _translationDirPath;
398 }
399
400 void Quassel::loadTranslation(const QLocale &locale) {
401   QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
402   QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
403
404   if(!qtTranslator) {
405     qtTranslator = new QTranslator(qApp);
406     qtTranslator->setObjectName("QtTr");
407     qApp->installTranslator(qtTranslator);
408   }
409   if(!quasselTranslator) {
410     quasselTranslator = new QTranslator(qApp);
411     quasselTranslator->setObjectName("QuasselTr");
412     qApp->installTranslator(quasselTranslator);
413   }
414
415   QLocale::setDefault(locale);
416
417   if(locale.language() == QLocale::C)
418     return;
419
420   bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
421   if(!success)
422     qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
423   quasselTranslator->load(QString("%1").arg(locale.name()), translationDirPath());
424 }