Providing proper defaults for nick and realname on Mac OS using CoreServices
[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 <signal.h>
24
25 #include <QCoreApplication>
26 #include <QDateTime>
27 #include <QFileInfo>
28 #include <QLibraryInfo>
29 #include <QSettings>
30 #include <QTranslator>
31
32 #include "message.h"
33 #include "identity.h"
34 #include "network.h"
35 #include "bufferinfo.h"
36 #include "types.h"
37 #include "syncableobject.h"
38
39 Quassel::BuildInfo Quassel::_buildInfo;
40 AbstractCliParser *Quassel::_cliParser = 0;
41 Quassel::RunMode Quassel::_runMode;
42 QString Quassel::_configDirPath;
43 QString Quassel::_translationDirPath;
44 QStringList Quassel::_dataDirPaths;
45 bool Quassel::_initialized = false;
46 bool Quassel::DEBUG = false;
47 QString Quassel::_coreDumpFileName;
48
49 Quassel::Quassel() {
50   // We catch SIGTERM and SIGINT (caused by Ctrl+C) to graceful shutdown Quassel.
51   signal(SIGTERM, handleSignal);
52   signal(SIGINT, handleSignal);
53
54   // we have crashhandler for win32 and unix (based on execinfo).
55   // on mac os we use it's integrated backtrace generator
56 #if defined(Q_OS_WIN32) || (defined(HAVE_EXECINFO) && !defined(Q_OS_MAC))
57   signal(SIGABRT, handleSignal);
58   signal(SIGSEGV, handleSignal);
59 #  ifndef Q_OS_WIN32
60   signal(SIGBUS, handleSignal);
61 #  endif
62 #endif
63
64 }
65
66 Quassel::~Quassel() {
67   delete _cliParser;
68 }
69
70 bool Quassel::init() {
71   if(_initialized)
72     return true;  // allow multiple invocations because of MonolithicApplication
73
74   _initialized = true;
75   qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
76
77   registerMetaTypes();
78
79   Network::setDefaultCodecForServer("ISO-8859-1");
80   Network::setDefaultCodecForEncoding("UTF-8");
81   Network::setDefaultCodecForDecoding("ISO-8859-15");
82
83   if(isOptionSet("help")) {
84     cliParser()->usage();
85     return false;
86   }
87
88   DEBUG = isOptionSet("debug");
89   return true;
90 }
91
92 //! Register our custom types with Qt's Meta Object System.
93 /**  This makes them available for QVariant and in signals/slots, among other things.
94 *
95 */
96 void Quassel::registerMetaTypes() {
97   // Complex types
98   qRegisterMetaType<QVariant>("QVariant");
99   qRegisterMetaType<Message>("Message");
100   qRegisterMetaType<BufferInfo>("BufferInfo");
101   qRegisterMetaType<NetworkInfo>("NetworkInfo");
102   qRegisterMetaType<Network::Server>("Network::Server");
103   qRegisterMetaType<Identity>("Identity");
104   qRegisterMetaType<Network::ConnectionState>("Network::ConnectionState");
105
106   qRegisterMetaTypeStreamOperators<QVariant>("QVariant");
107   qRegisterMetaTypeStreamOperators<Message>("Message");
108   qRegisterMetaTypeStreamOperators<BufferInfo>("BufferInfo");
109   qRegisterMetaTypeStreamOperators<NetworkInfo>("NetworkInfo");
110   qRegisterMetaTypeStreamOperators<Network::Server>("Network::Server");
111   qRegisterMetaTypeStreamOperators<Identity>("Identity");
112   qRegisterMetaTypeStreamOperators<qint8>("Network::ConnectionState");
113
114   qRegisterMetaType<IdentityId>("IdentityId");
115   qRegisterMetaType<BufferId>("BufferId");
116   qRegisterMetaType<NetworkId>("NetworkId");
117   qRegisterMetaType<UserId>("UserId");
118   qRegisterMetaType<AccountId>("AccountId");
119   qRegisterMetaType<MsgId>("MsgId");
120
121   qRegisterMetaTypeStreamOperators<IdentityId>("IdentityId");
122   qRegisterMetaTypeStreamOperators<BufferId>("BufferId");
123   qRegisterMetaTypeStreamOperators<NetworkId>("NetworkId");
124   qRegisterMetaTypeStreamOperators<UserId>("UserId");
125   qRegisterMetaTypeStreamOperators<AccountId>("AccountId");
126   qRegisterMetaTypeStreamOperators<MsgId>("MsgId");
127 }
128
129 void Quassel::setupBuildInfo(const QString &generated) {
130   _buildInfo.applicationName = "Quassel IRC";
131   _buildInfo.coreApplicationName = "quasselcore";
132   _buildInfo.clientApplicationName = "quasselclient";
133   _buildInfo.organizationName = "Quassel Project";
134   _buildInfo.organizationDomain = "quassel-irc.org";
135
136   QStringList gen = generated.split(',');
137   Q_ASSERT(gen.count() == 10);
138   _buildInfo.baseVersion = gen[0];
139   _buildInfo.generatedVersion = gen[1];
140   _buildInfo.isSourceDirty = !gen[2].isEmpty();
141   _buildInfo.commitHash = gen[3];
142   _buildInfo.commitDate = gen[4].toUInt();
143   _buildInfo.protocolVersion = gen[5].toUInt();
144   _buildInfo.clientNeedsProtocol = gen[6].toUInt();
145   _buildInfo.coreNeedsProtocol = gen[7].toUInt();
146   _buildInfo.buildDate = QString("%1 %2").arg(gen[8], gen[9]);
147   // create a nice version string
148   if(_buildInfo.generatedVersion.isEmpty()) {
149     if(!_buildInfo.commitHash.isEmpty()) {
150       // dist version
151       _buildInfo.plainVersionString = QString("v%1 (dist-%2)")
152                                         .arg(_buildInfo.baseVersion)
153                                         .arg(_buildInfo.commitHash.left(7));
154                                         _buildInfo.fancyVersionString
155                                            = QString("v%1 (dist-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%3\">%2</a>)")
156                                         .arg(_buildInfo.baseVersion)
157                                         .arg(_buildInfo.commitHash.left(7))
158                                         .arg(_buildInfo.commitHash);
159     } else {
160     // we only have a base version :(
161       _buildInfo.plainVersionString = QString("v%1 (unknown rev)").arg(_buildInfo.baseVersion);
162     }
163   } else {
164     // analyze what we got from git-describe
165     QRegExp rx("(.*)-(\\d+)-g([0-9a-f]+)$");
166     if(rx.exactMatch(_buildInfo.generatedVersion)) {
167       QString distance = rx.cap(2) == "0" ? QString() : QString(" [+%1]").arg(rx.cap(2));
168       _buildInfo.plainVersionString = QString("v%1%2 (git-%3%4)")
169                                         .arg(rx.cap(1), distance, rx.cap(3))
170                                         .arg(_buildInfo.isSourceDirty ? "*" : "");
171       if(!_buildInfo.commitHash.isEmpty()) {
172         _buildInfo.fancyVersionString = QString("v%1%2 (git-<a href=\"http://git.quassel-irc.org/?p=quassel.git;a=commit;h=%5\">%3</a>%4)")
173                                           .arg(rx.cap(1), distance, rx.cap(3))
174                                           .arg(_buildInfo.isSourceDirty ? "*" : "")
175                                           .arg(_buildInfo.commitHash);
176       }
177     } else {
178       _buildInfo.plainVersionString = QString("v%1 (invalid rev)").arg(_buildInfo.baseVersion);
179     }
180   }
181   if(_buildInfo.fancyVersionString.isEmpty())
182     _buildInfo.fancyVersionString = _buildInfo.plainVersionString;
183 }
184
185 //! Signal handler for graceful shutdown.
186 void Quassel::handleSignal(int sig) {
187   switch(sig) {
188   case SIGTERM:
189   case SIGINT:
190     qWarning("%s", qPrintable(QString("Caught signal %1 - exiting.").arg(sig)));
191     QCoreApplication::quit();
192     break;
193   case SIGABRT:
194   case SIGSEGV:
195 #ifndef Q_OS_WIN32
196   case SIGBUS:
197 #endif
198     logBacktrace(coreDumpFileName());
199     exit(EXIT_FAILURE);
200     break;
201   default:
202     break;
203   }
204 }
205
206 void Quassel::logFatalMessage(const char *msg) {
207 #ifdef Q_OS_MAC
208   Q_UNUSED(msg)
209 #else
210   QFile dumpFile(coreDumpFileName());
211   dumpFile.open(QIODevice::Append);
212   QTextStream dumpStream(&dumpFile);
213
214   dumpStream << "Fatal: " << msg << '\n';
215   dumpStream.flush();
216   dumpFile.close();
217 #endif
218 }
219
220 const QString &Quassel::coreDumpFileName() {
221   if(_coreDumpFileName.isEmpty()) {
222     _coreDumpFileName = QString("Quassel-Crash-%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMdd-hhmm"));
223     QFile dumpFile(_coreDumpFileName);
224     dumpFile.open(QIODevice::Append);
225     QTextStream dumpStream(&dumpFile);
226     dumpStream << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash << '\n';
227     qDebug() << "Quassel IRC: " << _buildInfo.baseVersion << ' ' << _buildInfo.commitHash;
228     dumpStream.flush();
229     dumpFile.close();
230   }
231   return _coreDumpFileName;
232 }
233
234 QString Quassel::configDirPath() {
235   if(!_configDirPath.isEmpty())
236     return _configDirPath;
237
238   if(Quassel::isOptionSet("datadir")) {
239     qWarning() << "Obsolete option --datadir used!";
240     _configDirPath = Quassel::optionValue("datadir");
241   } else if(Quassel::isOptionSet("configdir")) {
242     _configDirPath = Quassel::optionValue("configdir");
243   } else {
244
245 #ifdef Q_WS_MAC
246     // On Mac, the path is always the same
247     _configDirPath = QDir::homePath() + "/Library/Application Support/Quassel/";
248 #else
249     // We abuse QSettings to find us a sensible path on the other platforms
250 #  ifdef Q_WS_WIN
251     // don't use the registry
252     QSettings::Format format = QSettings::IniFormat;
253 #  else
254     QSettings::Format format = QSettings::NativeFormat;
255 #  endif
256     QSettings s(format, QSettings::UserScope, QCoreApplication::organizationDomain(), buildInfo().applicationName);
257     QFileInfo fileInfo(s.fileName());
258     _configDirPath = fileInfo.dir().absolutePath();
259 #endif /* Q_WS_MAC */
260   }
261
262   if(!_configDirPath.endsWith(QDir::separator()) && !_configDirPath.endsWith('/'))
263     _configDirPath += QDir::separator();
264
265   QDir qDir(_configDirPath);
266   if(!qDir.exists(_configDirPath)) {
267     if(!qDir.mkpath(_configDirPath)) {
268       qCritical() << "Unable to create Quassel config directory:" << qPrintable(qDir.absolutePath());
269       return QString();
270     }
271   }
272
273   return _configDirPath;
274 }
275
276 QStringList Quassel::dataDirPaths() {
277   return _dataDirPaths;
278 }
279
280 QStringList Quassel::findDataDirPaths() const {
281   QStringList dataDirNames = QString(qgetenv("XDG_DATA_DIRS")).split(':', QString::SkipEmptyParts);
282
283   if(!dataDirNames.isEmpty()) {
284     for(int i = 0; i < dataDirNames.count(); i++)
285       dataDirNames[i].append("/apps/quassel/");
286   } else {
287   // Provide a fallback
288 #ifdef Q_OS_WIN32
289     dataDirNames << qgetenv("APPDATA") + QCoreApplication::organizationDomain() + "/share/apps/quassel/"
290                  << qgetenv("APPDATA") + QCoreApplication::organizationDomain()
291                  << QCoreApplication::applicationDirPath();
292   }
293 #elif defined Q_WS_MAC
294     dataDirNames << QDir::homePath() + "/Library/Application Support/Quassel/"
295                  << QCoreApplication::applicationDirPath();
296   }
297 #else
298     dataDirNames.append("/usr/share/apps/quassel/");
299   }
300   // on UNIX, we always check our install prefix
301   QString appDir = QCoreApplication::applicationDirPath();
302   int binpos = appDir.lastIndexOf("/bin");
303   if(binpos >= 0) {
304     appDir.replace(binpos, 4, "/share");
305     appDir.append("/apps/quassel/");
306     if(!dataDirNames.contains(appDir))
307       dataDirNames.append(appDir);
308   }
309 #endif
310
311   // add resource path and workdir just in case
312   dataDirNames << QCoreApplication::applicationDirPath() + "/data/"
313                << ":/data/";
314
315   // append trailing '/' and check for existence
316   QStringList::Iterator iter = dataDirNames.begin();
317   while(iter != dataDirNames.end()) {
318     if(!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
319       iter->append(QDir::separator());
320     if(!QFile::exists(*iter))
321       iter = dataDirNames.erase(iter);
322     else
323       ++iter;
324   }
325
326   return dataDirNames;
327 }
328
329 QString Quassel::findDataFilePath(const QString &fileName) {
330   QStringList dataDirs = dataDirPaths();
331   foreach(QString dataDir, dataDirs) {
332     QString path = dataDir + fileName;
333     if(QFile::exists(path))
334       return path;
335   }
336   return QString();
337 }
338
339 void Quassel::loadTranslation(const QLocale &locale) {
340   if(_translationDirPath.isEmpty()) {
341     // We support only one translation dir; fallback mechanisms wouldn't work else.
342     // This means that if we have a $data/i18n dir, the internal :/i18n resource won't be considered.
343     foreach(const QString &dir, dataDirPaths()) {
344       if(QFile::exists(dir + "translations/")) {
345         _translationDirPath = dir + "translations/";
346         break;
347       }
348     }
349     if(_translationDirPath.isEmpty())
350       _translationDirPath = ":/i18n/";
351   }
352
353   QTranslator *qtTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QtTr");
354   QTranslator *quasselTranslator = QCoreApplication::instance()->findChild<QTranslator *>("QuasselTr");
355
356   if(!qtTranslator) {
357     qtTranslator = new QTranslator(qApp);
358     qtTranslator->setObjectName("QtTr");
359     qApp->installTranslator(qtTranslator);
360   }
361   if(!quasselTranslator) {
362     quasselTranslator = new QTranslator(qApp);
363     quasselTranslator->setObjectName("QuasselTr");
364     qApp->installTranslator(quasselTranslator);
365   }
366
367   QLocale::setDefault(locale);
368
369   if(locale.language() == QLocale::C)
370     return;
371
372   bool success = qtTranslator->load(QString("qt_%1").arg(locale.name()), _translationDirPath);
373   if(!success)
374     qtTranslator->load(QString("qt_%1").arg(locale.name()), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
375   quasselTranslator->load(QString("quassel_%1").arg(locale.name()), _translationDirPath);
376 }