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