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