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