logger: Refactor the logging framework
[quassel.git] / src / qtui / qtuiapplication.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 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 "qtuiapplication.h"
22
23 #include <QDir>
24 #include <QFile>
25 #include <QStringList>
26
27 #ifdef HAVE_KDE4
28 #  include <KStandardDirs>
29 #endif
30
31 #include "chatviewsettings.h"
32 #include "client.h"
33 #include "cliparser.h"
34 #include "mainwin.h"
35 #include "qtui.h"
36 #include "qtuisettings.h"
37
38 QtUiApplication::QtUiApplication(int &argc, char **argv)
39 #ifdef HAVE_KDE4
40     : KApplication()  // KApplication is deprecated in KF5
41 #else
42     : QApplication(argc, argv)
43 #endif
44 {
45 #ifdef HAVE_KDE4
46     Q_UNUSED(argc); Q_UNUSED(argv);
47
48     // Setup KDE's data dirs
49     // Because we can't use KDE stuff in (the class) Quassel directly, we need to do this here...
50     QStringList dataDirs = KGlobal::dirs()->findDirs("data", "");
51
52     // Just in case, also check our install prefix
53     dataDirs << QCoreApplication::applicationDirPath() + "/../share/apps/";
54
55     // Normalize and append our application name
56     for (int i = 0; i < dataDirs.count(); i++)
57         dataDirs[i] = QDir::cleanPath(dataDirs.at(i)) + "/quassel/";
58
59     // Add resource path and just in case.
60     // Workdir should have precedence
61     dataDirs.prepend(QCoreApplication::applicationDirPath() + "/data/");
62     dataDirs.append(":/data/");
63
64     // Append trailing '/' and check for existence
65     auto iter = dataDirs.begin();
66     while (iter != dataDirs.end()) {
67         if (!iter->endsWith(QDir::separator()) && !iter->endsWith('/'))
68             iter->append(QDir::separator());
69         if (!QFile::exists(*iter))
70             iter = dataDirs.erase(iter);
71         else
72             ++iter;
73     }
74
75     dataDirs.removeDuplicates();
76     Quassel::setDataDirPaths(dataDirs);
77
78 #else /* HAVE_KDE4 */
79
80     Quassel::setDataDirPaths(Quassel::findDataDirPaths());
81
82 #endif /* HAVE_KDE4 */
83
84 #if defined(HAVE_KDE4) || defined(Q_OS_MAC)
85     Quassel::disableCrashHandler();
86 #endif /* HAVE_KDE4 || Q_OS_MAC */
87
88     Quassel::setRunMode(Quassel::ClientOnly);
89
90 #if QT_VERSION >= 0x050000
91     connect(this, &QGuiApplication::commitDataRequest, this, &QtUiApplication::commitData, Qt::DirectConnection);
92     connect(this, &QGuiApplication::saveStateRequest, this, &QtUiApplication::saveState, Qt::DirectConnection);
93 #endif
94
95 #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
96     QGuiApplication::setFallbackSessionManagementEnabled(false);
97 #endif
98 }
99
100
101 bool QtUiApplication::init()
102 {
103     if (Quassel::init()) {
104         // Settings upgrade/downgrade handling
105         if (!migrateSettings()) {
106             qCritical() << "Could not load or upgrade client settings, terminating!";
107             return false;
108         }
109
110         Client::init(new QtUi());
111
112         // Init UI only after the event loop has started
113         // TODO Qt5: Make this a lambda
114         QTimer::singleShot(0, this, SLOT(initUi()));
115
116         Quassel::registerQuitHandler([]() {
117             QtUi::mainWindow()->quit();
118         });
119
120         return true;
121     }
122     return false;
123 }
124
125
126 QtUiApplication::~QtUiApplication()
127 {
128     Client::destroy();
129     Quassel::destroy();
130 }
131
132
133 void QtUiApplication::initUi()
134 {
135     QtUi::instance()->init();
136     resumeSessionIfPossible();
137 }
138
139
140 bool QtUiApplication::migrateSettings()
141 {
142     // --------
143     // Check major settings version.  This represents incompatible changes between settings
144     // versions.  So far, we only have 1.
145     QtUiSettings s;
146     uint versionMajor = s.version();
147     if (versionMajor != 1) {
148         qCritical() << qPrintable(QString("Invalid client settings version '%1'")
149                                   .arg(versionMajor));
150         return false;
151     }
152
153     // --------
154     // Check minor settings version, handling upgrades/downgrades as needed
155     // Current minor version
156     //
157     // NOTE:  If you increase the minor version, you MUST ALSO add new version upgrade logic in
158     // applySettingsMigration()!  Otherwise, settings upgrades will fail.
159     const uint VERSION_MINOR_CURRENT = 9;
160     // Stored minor version
161     uint versionMinor = s.versionMinor();
162
163     if (versionMinor == VERSION_MINOR_CURRENT) {
164         // At latest version, no need to migrate defaults or other settings
165         return true;
166     } else if (versionMinor == 0) {
167         // New configuration, store as current version
168         qDebug() << qPrintable(QString("Set up new client settings v%1.%2")
169                                .arg(versionMajor).arg(VERSION_MINOR_CURRENT));
170         s.setVersionMinor(VERSION_MINOR_CURRENT);
171
172         // Update the settings stylesheet for first setup.  We don't know if older content exists,
173         // if the configuration got erased separately, etc.
174         QtUiStyle qtUiStyle;
175         qtUiStyle.generateSettingsQss();
176         return true;
177     } else if (versionMinor < VERSION_MINOR_CURRENT) {
178         // We're upgrading - apply the neccessary upgrades from each interim version
179         // curVersion will never equal VERSION_MINOR_CURRENT, as it represents the version before
180         // the most recent applySettingsMigration() call.
181         for (uint curVersion = versionMinor; curVersion < VERSION_MINOR_CURRENT; curVersion++) {
182             if (!applySettingsMigration(s, curVersion + 1)) {
183                 // Something went wrong, time to bail out
184                 qCritical() << qPrintable(QString("Could not migrate client settings from v%1.%2 "
185                                                   "to v%1.%3")
186                                           .arg(versionMajor).arg(curVersion).arg(curVersion + 1));
187                 // Keep track of the last successful upgrade to avoid repeating it on next start
188                 s.setVersionMinor(curVersion);
189                 return false;
190             }
191         }
192         // Migration successful!
193         qDebug() << qPrintable(QString("Successfully migrated client settings from v%1.%2 to "
194                                        "v%1.%3")
195                                .arg(versionMajor).arg(versionMinor).arg(VERSION_MINOR_CURRENT));
196         // Store the new minor version
197         s.setVersionMinor(VERSION_MINOR_CURRENT);
198         return true;
199     } else {
200         // versionMinor > VERSION_MINOR_CURRENT
201         // The user downgraded to an older version of Quassel.  Let's hope for the best.
202         // Don't change the minorVersion as the newer version's upgrade logic has already run.
203         qWarning() << qPrintable(QString("Client settings v%1.%2 is newer than latest known v%1.%3,"
204                                          " things might not work!")
205                                  .arg(versionMajor).arg(versionMinor).arg(VERSION_MINOR_CURRENT));
206         return true;
207     }
208 }
209
210
211 bool QtUiApplication::applySettingsMigration(QtUiSettings settings, const uint newVersion)
212 {
213     switch (newVersion) {
214     // Version 0 and 1 aren't valid upgrade paths - one represents no version, the other is the
215     // oldest version.  Ignore those, start from 2 and higher.
216     // Each missed version will be called in sequence.  E.g. to upgrade from '1' to '3', this
217     // function will be called with '2', then '3'.
218     // Use explicit scope via { ... } to avoid cross-initialization
219     //
220     // In most cases, the goal is to preserve the older default values for keys that haven't been
221     // saved.  Exceptions will be noted below.
222     // NOTE:  If you add new upgrade logic here, you MUST ALSO increase VERSION_MINOR_CURRENT in
223     // migrateSettings()!  Otherwise, your upgrade logic won't ever be called.
224     case 9:
225     {
226         // New default changes: show highest sender prefix mode, if available
227
228         // --------
229         // ChatView settings
230         ChatViewSettings chatViewSettings;
231         const QString senderPrefixModeId = "SenderPrefixMode";
232         if (!chatViewSettings.valueExists(senderPrefixModeId)) {
233             // New default is HighestMode, preserve previous behavior by setting to NoModes
234             chatViewSettings.setValue(senderPrefixModeId,
235                                       static_cast<int>(UiStyle::SenderPrefixMode::NoModes));
236         }
237         // --------
238
239         // Migration complete!
240         return true;
241     }
242
243     case 8:
244     {
245         // New default changes: RegEx checkbox now toggles Channel regular expressions, too
246         //
247         // This only affects local highlights.  Core-side highlights weren't released in stable when
248         // this change was made, so no need to migrate those.
249
250         // --------
251         // NotificationSettings
252         NotificationSettings notificationSettings;
253
254         // Check each highlight rule for a "Channel" field.  If one exists, convert to RegEx mode.
255         // This might be more efficient with std::transform() or such.  It /is/ only run once...
256         auto highlightList = notificationSettings.highlightList();
257         bool changesMade = false;
258         for (int index = 0; index < highlightList.count(); ++index)
259         {
260             // Load the highlight rule...
261             auto highlightRule = highlightList[index].toMap();
262
263             // Check if "Channel" has anything set and RegEx is disabled
264             if (!highlightRule["Channel"].toString().isEmpty()
265                     && highlightRule["RegEx"].toBool() == false) {
266                 // We have a rule to convert
267
268                 // Mark as a regular expression, allowing the Channel filtering to work the same as
269                 // before the upgrade
270                 highlightRule["RegEx"] = true;
271
272                 // Convert the main rule to regular expression, mirroring the conversion to wildcard
273                 // format from QtUiMessageProcessor::checkForHighlight()
274                 highlightRule["Name"] =
275                         "(^|\\W)" + QRegExp::escape(highlightRule["Name"].toString()) + "(\\W|$)";
276
277                 // Save the rule back
278                 highlightList[index] = highlightRule;
279                 changesMade = true;
280             }
281         }
282
283         // Save the modified rules if any changes were made
284         if (changesMade) {
285             notificationSettings.setHighlightList(highlightList);
286         }
287         // --------
288
289         // Migration complete!
290         return true;
291     }
292     case 7:
293     {
294         // New default changes: UseProxy is no longer used in CoreAccountSettings
295         CoreAccountSettings s;
296         for (auto &&accountId : s.knownAccounts()) {
297             auto map = s.retrieveAccountData(accountId);
298             if (!map.value("UseProxy", false).toBool()) {
299                 map["ProxyType"] = static_cast<int>(QNetworkProxy::ProxyType::NoProxy);
300             }
301             map.remove("UseProxy");
302             s.storeAccountData(accountId, map);
303         }
304
305         // Migration complete!
306         return true;
307     }
308     case 6:
309     {
310         // New default changes: sender colors switched around to Tango-ish theme
311
312         // --------
313         // QtUiStyle settings
314         QtUiStyleSettings settingsUiStyleColors("Colors");
315         // Preserve the old default values for all variants
316         const QColor oldDefaultSenderColorSelf = QColor(0, 0, 0);
317         const QList<QColor> oldDefaultSenderColors = QList<QColor> {
318             QColor(204,  13, 127),  /// Sender00
319             QColor(142,  85, 233),  /// Sender01
320             QColor(179,  14,  14),  /// Sender02
321             QColor( 23, 179,  57),  /// Sender03
322             QColor( 88, 175, 179),  /// Sender04
323             QColor(157,  84, 179),  /// Sender05
324             QColor(179, 151, 117),  /// Sender06
325             QColor( 49, 118, 179),  /// Sender07
326             QColor(233,  13, 127),  /// Sender08
327             QColor(142,  85, 233),  /// Sender09
328             QColor(179,  14,  14),  /// Sender10
329             QColor( 23, 179,  57),  /// Sender11
330             QColor( 88, 175, 179),  /// Sender12
331             QColor(157,  84, 179),  /// Sender13
332             QColor(179, 151, 117),  /// Sender14
333             QColor( 49, 118, 179),  /// Sender15
334         };
335         if (!settingsUiStyleColors.valueExists("SenderSelf")) {
336             // Preserve the old default sender color if none set
337             settingsUiStyleColors.setValue("SenderSelf", oldDefaultSenderColorSelf);
338         }
339         QString senderColorId;
340         for (int i = 0; i < oldDefaultSenderColors.count(); i++) {
341             // Get the sender color ID for each available color
342             QString dez = QString::number(i);
343             if (dez.length() == 1) dez.prepend('0');
344             senderColorId = QString("Sender" + dez);
345             if (!settingsUiStyleColors.valueExists(senderColorId)) {
346                 // Preserve the old default sender color if none set
347                 settingsUiStyleColors.setValue(senderColorId, oldDefaultSenderColors[i]);
348             }
349         }
350
351         // Update the settings stylesheet with old defaults
352         QtUiStyle qtUiStyle;
353         qtUiStyle.generateSettingsQss();
354         // --------
355
356         // Migration complete!
357         return true;
358     }
359     case 5:
360     {
361         // New default changes: sender colors apply to nearly all messages with nicks
362
363         // --------
364         // QtUiStyle settings
365         QtUiStyleSettings settingsUiStyleColors("Colors");
366         const QString useNickGeneralColorsId = "UseNickGeneralColors";
367         if (!settingsUiStyleColors.valueExists(useNickGeneralColorsId)) {
368             // New default is true, preserve previous behavior by setting to false
369             settingsUiStyleColors.setValue(useNickGeneralColorsId, false);
370         }
371
372         // Update the settings stylesheet with old defaults
373         QtUiStyle qtUiStyle;
374         qtUiStyle.generateSettingsQss();
375         // --------
376
377         // Migration complete!
378         return true;
379     }
380     case 4:
381     {
382         // New default changes: system locale used to generate a timestamp format string, deciding
383         // 24-hour or 12-hour timestamp.
384
385         // --------
386         // ChatView settings
387         const QString useCustomTimestampFormatId = "ChatView/__default__/UseCustomTimestampFormat";
388         if (!settings.valueExists(useCustomTimestampFormatId)) {
389             // New default value is false, preserve previous behavior by setting to true
390             settings.setValue(useCustomTimestampFormatId, true);
391         }
392         // --------
393
394         // Migration complete!
395         return true;
396     }
397     case 3:
398     {
399         // New default changes: per-chat history and line wrapping enabled by default.
400
401         // --------
402         // InputWidget settings
403         UiSettings settingsInputWidget("InputWidget");
404         const QString enableInputPerChatId = "EnablePerChatHistory";
405         if (!settingsInputWidget.valueExists(enableInputPerChatId)) {
406             // New default value is true, preserve previous behavior by setting to false
407             settingsInputWidget.setValue(enableInputPerChatId, false);
408         }
409
410         const QString enableInputLinewrap = "EnableLineWrap";
411         if (!settingsInputWidget.valueExists(enableInputLinewrap)) {
412             // New default value is true, preserve previous behavior by setting to false
413             settingsInputWidget.setValue(enableInputLinewrap, false);
414         }
415         // --------
416
417         // Migration complete!
418         return true;
419     }
420     case 2:
421     {
422         // New default changes: sender <nick> brackets disabled, sender colors and sender CTCP
423         // colors enabled.
424
425         // --------
426         // ChatView settings
427         const QString timestampFormatId = "ChatView/__default__/TimestampFormat";
428         if (!settings.valueExists(timestampFormatId)) {
429             // New default value is " hh:mm:ss", preserve old default of "[hh:mm:ss]"
430             settings.setValue(timestampFormatId, "[hh:mm:ss]");
431         }
432
433         const QString showSenderBracketsId = "ChatView/__default__/ShowSenderBrackets";
434         if (!settings.valueExists(showSenderBracketsId)) {
435             // New default is false, preserve previous behavior by setting to true
436             settings.setValue(showSenderBracketsId, true);
437         }
438         // --------
439
440         // --------
441         // QtUiStyle settings
442         QtUiStyleSettings settingsUiStyleColors("Colors");
443         const QString useSenderColorsId = "UseSenderColors";
444         if (!settingsUiStyleColors.valueExists(useSenderColorsId)) {
445             // New default is true, preserve previous behavior by setting to false
446             settingsUiStyleColors.setValue(useSenderColorsId, false);
447         }
448
449         const QString useSenderActionColorsId = "UseSenderActionColors";
450         if (!settingsUiStyleColors.valueExists(useSenderActionColorsId)) {
451             // New default is true, preserve previous behavior by setting to false
452             settingsUiStyleColors.setValue(useSenderActionColorsId, false);
453         }
454
455         // Update the settings stylesheet with old defaults
456         QtUiStyle qtUiStyle;
457         qtUiStyle.generateSettingsQss();
458         // --------
459
460         // Migration complete!
461         return true;
462     }
463     default:
464         // Something unexpected happened
465         return false;
466     }
467 }
468
469
470 void QtUiApplication::commitData(QSessionManager &manager)
471 {
472     Q_UNUSED(manager)
473     _aboutToQuit = true;
474 }
475
476
477 void QtUiApplication::saveState(QSessionManager &manager)
478 {
479     //qDebug() << QString("saving session state to id %1").arg(manager.sessionId());
480     // AccountId activeCore = Client::currentCoreAccount().accountId(); // FIXME store this!
481     SessionSettings s(manager.sessionId());
482     s.setSessionAge(0);
483     QtUi::mainWindow()->saveStateToSettings(s);
484 }
485
486
487 void QtUiApplication::resumeSessionIfPossible()
488 {
489     // load all sessions
490     if (isSessionRestored()) {
491         qDebug() << QString("restoring from session %1").arg(sessionId());
492         SessionSettings s(sessionId());
493         s.sessionAging();
494         s.setSessionAge(0);
495         QtUi::mainWindow()->restoreStateFromSettings(s);
496         s.cleanup();
497     }
498     else {
499         SessionSettings s(QString("1"));
500         s.sessionAging();
501         s.cleanup();
502     }
503 }