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