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