Improve MainWindow state save/restore
[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
54 Quassel::Quassel() {
55   Q_ASSERT(!_instance);
56   _instance = this;
57
58   // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
59   signal(SIGTERM, handleSignal);
60   signal(SIGINT, handleSignal);
61
62   // we have crashhandler for win32 and unix (based on execinfo).
63   // on mac os we use it's integrated backtrace generator
64 #if defined(Q_OS_WIN32) || (defined(HAVE_EXECINFO) && !defined(Q_OS_MAC))
65
66 # ifndef Q_OS_WIN32
67   // we only handle crashes ourselves if coredumps are disabled
68   struct rlimit *limit = (rlimit *) malloc(sizeof(struct rlimit));
69   int rc = getrlimit(RLIMIT_CORE, limit);
70
71   if(rc == -1 || !((long)limit->rlim_cur > 0 || limit->rlim_cur == RLIM_INFINITY)) {
72 # endif
73     signal(SIGABRT, handleSignal);
74     signal(SIGSEGV, handleSignal);
75 #   ifndef Q_OS_WIN32
76     signal(SIGBUS, handleSignal);
77   }
78   free(limit);
79 #   endif
80
81 #endif
82 }
83
84 Quassel::~Quassel() {
85   delete _cliParser;
86 }
87
88 bool Quassel::init() {
89   if(_initialized)
90     return true;  // allow multiple invocations because of MonolithicApplication
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
182                                            = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
183                                         .arg(_buildInfo.baseVersion)
184                                         .arg(_buildInfo.commitHash.left(7))
185                                         .arg(_buildInfo.commitHash);
186     } else {
187     // we only have a base version :(
188       _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
189     }
190   } else {
191     // analyze what we got from git-describe
192     QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
193     if(rx.exactMatch(_buildInfo.generatedVersion)) {
194       QString distance = rx.cap(2) == "0" ? QString() : QString(" [+%1]").arg(rx.cap(2));
195       _buildInfo.plainVersionString = QString("v%1%2 (git-%3%4)")
196                                         .arg(rx.cap(1), distance, rx.cap(3))
197                                         .arg(_buildInfo.isSourceDirty ? "*" : "");
198       if(!_buildInfo.commitHash.isEmpty()) {
199         _buildInfo.fancyVersionString = QString("v%1%2 (git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
200                                           .arg(rx.cap(1), distance, rx.cap(3))
201                                           .arg(_buildInfo.isSourceDirty ? "*" : "")
202                                           .arg(_buildInfo.commitHash);
203       }
204     } else {
205       _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
206     }
207   }
208   if(_buildInfo.fancyVersionString.isEmpty())
209     _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
210 }
211
212 //! Signal handler for graceful shutdown.
213 void Quassel::handleSignal(int sig) {
214   switch(sig) {
215   case SIGTERM:
216   case SIGINT:
217     qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
218     if(_instance)
219       _instance->quit();
220     else
221       QCoreApplication::quit();
222     break;
223   case SIGABRT:
224   case SIGSEGV:
225 #ifndef Q_OS_WIN32
226   case SIGBUS:
227 #endif
228     logBacktrace(coreDumpFileName());
229     exit(EXIT_FAILURE);
230     break;
231   default:
232     break;
233   }
234 }
235
236 void Quassel::logFatalMessage(const char *msg) {
237 #ifdef Q_OS_MAC
238   Q_UNUSED(msg)
239 #else
240   QFile dumpFile(coreDumpFileName());
241   dumpFile.open(QIODevice::Append);
242   QTextStream dumpStream(&dumpFile);
243
244   dumpStream << "Fatal: " << msg << '\n';
245   dumpStream.flush();
246   dumpFile.close();
247 #endif
248 }
249
250 const QString &Quassel::coreDumpFileName() {
251   if(_coreDumpFileName.isEmpty()) {
252     QDir configDir(configDirPath());
253     _coreDumpFileName = configDir.absoluteFilePath(QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm")));
254     QFile dumpFile(_coreDumpFileName);
255     dumpFile.open(QIODevice::Append);
256     QTextStream dumpStream(&dumpFile);
257     dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
258     qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
259     dumpStream.flush();
260     dumpFile.close();
261   }
262   return _coreDumpFileName;
263 }
264
265 QString Quassel::configDirPath() {
266   if(!_configDirPath.isEmpty())
267     return _configDirPath;
268
269   if(Quassel::isOptionSet("datadir")) {
270     qWarning() << "Obsolete option --datadir used!";
271     _configDirPath = Quassel::optionValue("datadir");
272   } else if(Quassel::isOptionSet("configdir")) {
273     _configDirPath = Quassel::optionValue("configdir");
274   } else {
275
276 #ifdef Q_WS_MAC
277     // On Mac, the path is always the same
278     _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
279 #else
280     // We abuse QSettings to find us a sensible path on the other platforms
281 #  ifdef Q_WS_WIN
282     // don't use the registry
283     QSettings::Format format = QSettings::IniFormat;
284 #  else
285     QSettings::Format format = QSettings::NativeFormat;
286 #  endif
287     QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
288     QFileInfo fileInfo(s.fileName());
289     _configDirPath = fileInfo.dir().absolutePath();
290 #endif /* Q_WS_MAC */
291   }
292
293   if(!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
294     _configDirPath += QDir::separator();
295
296   QDir qDir(_configDirPath);
297   if(!qDir.exists(_configDirPath)) {
298     if(!qDir.mkpath(_configDirPath)) {
299       qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
300       return QString();
301     }
302   }
303
304   return _configDirPath;
305 }
306
307 QStringList Quassel::dataDirPaths() {
308   return _dataDirPaths;
309 }
310
311 QStringList Quassel::findDataDirPaths() const {
312   QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
313
314   if(!dataDirNames.isEmpty()) {
315     for(int i = 0; i < dataDirNames.count(); i++)
316       dataDirNames[i].append("/apps/quassel/");
317   } else {
318   // Provide a fallback
319 #ifdef Q_OS_WIN32
320     dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
321                  << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
322                  << QCoreApplication::applicationDirPath();
323   }
324 #elif defined Q_WS_MAC
325     dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
326                  << QCoreApplication::applicationDirPath();
327   }
328 #else
329     dataDirNames.append("/usr/share/apps/quassel/");
330   }
331   // on UNIX, we always check our install prefix
332   QString appDir = QCoreApplication::applicationDirPath();
333   int binpos = appDir.lastIndexOf("/bin");
334   if(binpos >= 0) {
335     appDir.replace(binpos, 4, "/share");
336     appDir.append("/apps/quassel/");
337     if(!dataDirNames.contains(appDir))
338       dataDirNames.append(appDir);
339   }
340 #endif
341
342   // add resource path and workdir just in case
343   dataDirNames << QCoreApplication::applicationDirPath() + "/data/"
344                << ":/data/";
345
346   // append trailing '/' and check for existence
347   QStringList::Iterator iter = dataDirNames.begin();
348   while(iter != dataDirNames.end()) {
349     if(!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
350       iter->append(QDir::separator());
351     if(!QFile::exists(*iter))
352       iter = dataDirNames.erase(iter);
353     else
354       ++iter;
355   }
356
357   return dataDirNames;
358 }
359
360 QString Quassel::findDataFilePath(const QString &fileName) {
361   QStringList dataDirs = dataDirPaths();
362   foreach(QString dataDir, dataDirs) {
363     QString path = dataDir + fileName;
364     if(QFile::exists(path))
365       return path;
366   }
367   return QString();
368 }
369
370 QStringList Quassel::scriptDirPaths() {
371   QStringList res(configDirPath() + "scripts/");
372   foreach(QString path, dataDirPaths())
373     res << path + "scripts/";
374   return res;
375 }
376
377 QString Quassel::translationDirPath() {
378   if(_translationDirPath.isEmpty()) {
379     // We support only one translation dir; fallback mechanisms wouldn't work else.
380     // This means that if we have a $data/translations dir, the internal :/i18n resource won't be considered.
381     foreach(const QString &dir, dataDirPaths()) {
382       if(QFile::exists(dir + "translations/")) {
383         _translationDirPath = dir + "translations/";
384         break;
385       }
386     }
387     if(_translationDirPath.isEmpty())
388       _translationDirPath = ":/i18n/";
389   }
390   return _translationDirPath;
391 }
392
393 void Quassel::loadTranslation(const QLocale &locale) {
394   QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
395   QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
396
397   if(!qtTranslator) {
398     qtTranslator = new QTranslator(qApp);
399     qtTranslator->setObjectName("QtTr");
400     qApp->installTranslator(qtTranslator);
401   }
402   if(!quasselTranslator) {
403     quasselTranslator = new QTranslator(qApp);
404     quasselTranslator->setObjectName("QuasselTr");
405     qApp->installTranslator(quasselTranslator);
406   }
407
408   QLocale::setDefault(locale);
409
410   if(locale.language() == QLocale::C)
411     return;
412
413   bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), translationDirPath());
414   if(!success)
415     qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
416   quasselTranslator->load(QString("quassel_%1").arg(locale.name()), translationDirPath());
417 }