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