Settings upgrade logic, classic for old installs
[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         // Set the icon theme
149         if (Quassel::isOptionSet("icontheme"))
150             QIcon::setThemeName(Quassel::optionValue("icontheme"));
151         else if (QIcon::themeName().isEmpty())
152             // Some platforms don't set a default icon theme; chances are we can find our bundled Oxygen theme though
153             QIcon::setThemeName("oxygen");
154
155         // session resume
156         QtUi *gui = new QtUi();
157         Client::init(gui);
158         // init gui only after the event loop has started
159         // QTimer::singleShot(0, gui, SLOT(init()));
160         gui->init();
161         resumeSessionIfPossible();
162         return true;
163     }
164     return false;
165 }
166
167
168 QtUiApplication::~QtUiApplication()
169 {
170     Client::destroy();
171 }
172
173
174 void QtUiApplication::quit()
175 {
176     QtUi::mainWindow()->quit();
177 }
178
179
180 bool QtUiApplication::migrateSettings()
181 {
182     // --------
183     // Check major settings version.  This represents incompatible changes between settings
184     // versions.  So far, we only have 1.
185     QtUiSettings s;
186     uint versionMajor = s.version();
187     if (versionMajor != 1) {
188         qCritical() << qPrintable(QString("Invalid client settings version '%1'")
189                                   .arg(versionMajor));
190         return false;
191     }
192
193     // --------
194     // Check minor settings version, handling upgrades/downgrades as needed
195     // Current minor version
196     const uint VERSION_MINOR_CURRENT = 2;
197     // Stored minor version
198     uint versionMinor = s.versionMinor();
199
200     if (versionMinor == VERSION_MINOR_CURRENT) {
201         // At latest version, no need to migrate defaults or other settings
202         return true;
203     } else if (versionMinor == 0) {
204         // New configuration, store as current version
205         qDebug() << qPrintable(QString("Set up new client settings v%1.%2")
206                                .arg(versionMajor).arg(VERSION_MINOR_CURRENT));
207         s.setVersionMinor(VERSION_MINOR_CURRENT);
208
209         // Update the settings stylesheet for first setup.  We don't know if older content exists,
210         // if the configuration got erased separately, etc.
211         QtUiStyle qtUiStyle;
212         qtUiStyle.generateSettingsQss();
213         return true;
214     } else if (versionMinor < VERSION_MINOR_CURRENT) {
215         // We're upgrading - apply the neccessary upgrades from each interim version
216         // curVersion will never equal VERSION_MINOR_CURRENT, as it represents the version before
217         // the most recent applySettingsMigration() call.
218         for (uint curVersion = versionMinor; curVersion < VERSION_MINOR_CURRENT; curVersion++) {
219             if (!applySettingsMigration(s, curVersion + 1)) {
220                 // Something went wrong, time to bail out
221                 qCritical() << qPrintable(QString("Could not migrate client settings from v%1.%2 "
222                                                   "to v%1.%3")
223                                           .arg(versionMajor).arg(curVersion).arg(curVersion + 1));
224                 // Keep track of the last successful upgrade to avoid repeating it on next start
225                 s.setVersionMinor(curVersion);
226                 return false;
227             }
228         }
229         // Migration successful!
230         qDebug() << qPrintable(QString("Successfully migrated client settings from v%1.%2 to "
231                                        "v%1.%3")
232                                .arg(versionMajor).arg(versionMinor).arg(VERSION_MINOR_CURRENT));
233         // Store the new minor version
234         s.setVersionMinor(VERSION_MINOR_CURRENT);
235         return true;
236     } else {
237         // versionMinor > VERSION_MINOR_CURRENT
238         // The user downgraded to an older version of Quassel.  Let's hope for the best.
239         // Don't change the minorVersion as the newer version's upgrade logic has already run.
240         qWarning() << qPrintable(QString("Client settings v%1.%2 is newer than latest known v%1.%3,"
241                                          " things might not work!")
242                                  .arg(versionMajor).arg(versionMinor).arg(VERSION_MINOR_CURRENT));
243         return true;
244     }
245 }
246
247
248 bool QtUiApplication::applySettingsMigration(QtUiSettings settings, const uint newVersion)
249 {
250     switch (newVersion) {
251     // Version 0 and 1 aren't valid upgrade paths - one represents no version, the other is the
252     // oldest version.  Ignore those, start from 2 and higher.
253     // Each missed version will be called in sequence.  E.g. to upgrade from '1' to '3', this
254     // function will be called with '2', then '3'.
255     case 2:
256     {
257         // Use explicit scope via { ... } to avoid cross-initialization
258
259         // New default changes: sender <nick> brackets disabled, sender colors and sender CTCP
260         // colors enabled.  Preserve the older default values for keys that haven't been saved.
261
262         // --------
263         // ChatView settings
264         const QString timestampFormatId = "ChatView/__default__/TimestampFormat";
265         if (!settings.valueExists(timestampFormatId)) {
266             // New default value is " hh:mm:ss", preserve old default of "[hh:mm:ss]"
267             settings.setValue(timestampFormatId, "[hh:mm:ss]");
268         }
269
270         const QString showSenderBracketsId = "ChatView/__default__/ShowSenderBrackets";
271         if (!settings.valueExists(showSenderBracketsId)) {
272             // New default is false, preserve previous behavior by setting to true
273             settings.setValue(showSenderBracketsId, true);
274         }
275         // --------
276
277         // --------
278         // QtUiStyle settings
279         QtUiStyleSettings settingsUiStyleColors("Colors");
280         const QString useSenderColorsId = "UseSenderColors";
281         if (!settingsUiStyleColors.valueExists(useSenderColorsId)) {
282             // New default is true, preserve previous behavior by setting to false
283             settingsUiStyleColors.setValue(useSenderColorsId, false);
284         }
285
286         const QString useSenderActionColorsId = "UseSenderActionColors";
287         if (!settingsUiStyleColors.valueExists(useSenderActionColorsId)) {
288             // New default is true, preserve previous behavior by setting to false
289             settingsUiStyleColors.setValue(useSenderActionColorsId, false);
290         }
291
292         // Update the settings stylesheet with old defaults
293         QtUiStyle qtUiStyle;
294         qtUiStyle.generateSettingsQss();
295         // --------
296
297         // Migration complete!
298         return true;
299     }
300     default:
301         // Something unexpected happened
302         return false;
303     }
304 }
305
306
307 void QtUiApplication::commitData(QSessionManager &manager)
308 {
309     Q_UNUSED(manager)
310     _aboutToQuit = true;
311 }
312
313
314 void QtUiApplication::saveState(QSessionManager &manager)
315 {
316     //qDebug() << QString("saving session state to id %1").arg(manager.sessionId());
317     // AccountId activeCore = Client::currentCoreAccount().accountId(); // FIXME store this!
318     SessionSettings s(manager.sessionId());
319     s.setSessionAge(0);
320     QtUi::mainWindow()->saveStateToSettings(s);
321 }
322
323
324 void QtUiApplication::resumeSessionIfPossible()
325 {
326     // load all sessions
327     if (isSessionRestored()) {
328         qDebug() << QString("restoring from session %1").arg(sessionId());
329         SessionSettings s(sessionId());
330         s.sessionAging();
331         s.setSessionAge(0);
332         QtUi::mainWindow()->restoreStateFromSettings(s);
333         s.cleanup();
334     }
335     else {
336         SessionSettings s(QString("1"));
337         s.sessionAging();
338         s.cleanup();
339     }
340 }