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