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