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