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