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