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