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