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