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