1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include "qtuiapplication.h"
25 #include <QStringList>
28 # include <KStandardDirs>
31 #include "chatviewsettings.h"
32 #include "cliparser.h"
35 #include "qtuisettings.h"
38 QtUiApplication::QtUiApplication(int &argc, char **argv)
40 : KApplication() // KApplication is deprecated in KF5
42 : QApplication(argc, argv)
46 Q_UNUSED(argc); Q_UNUSED(argv);
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", "");
52 // Just in case, also check our install prefix
53 dataDirs << QCoreApplication::applicationDirPath() + "/../share/apps/";
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/";
59 // Add resource path and just in case.
60 // Workdir should have precedence
61 dataDirs.prepend(QCoreApplication::applicationDirPath() + "/data/");
62 dataDirs.append(":/data/");
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);
75 dataDirs.removeDuplicates();
76 Quassel::setDataDirPaths(dataDirs);
80 Quassel::setDataDirPaths(Quassel::findDataDirPaths());
82 #endif /* HAVE_KDE4 */
84 #if defined(HAVE_KDE4) || defined(Q_OS_MAC)
85 Quassel::disableCrashHandler();
86 #endif /* HAVE_KDE4 || Q_OS_MAC */
88 Quassel::setRunMode(Quassel::ClientOnly);
90 #if QT_VERSION >= 0x050000
91 connect(this, &QGuiApplication::commitDataRequest, this, &QtUiApplication::commitData, Qt::DirectConnection);
92 connect(this, &QGuiApplication::saveStateRequest, this, &QtUiApplication::saveState, Qt::DirectConnection);
95 #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
96 QGuiApplication::setFallbackSessionManagementEnabled(false);
101 void QtUiApplication::init()
103 if (!Quassel::init()) {
104 throw ExitException{EXIT_FAILURE, tr("Could not initialize Quassel!")};
107 // Settings upgrade/downgrade handling
108 if (!migrateSettings()) {
109 throw ExitException{EXIT_FAILURE, tr("Could not load or upgrade client settings!")};
112 _client.reset(new Client(std::unique_ptr<QtUi>(new QtUi()))); // TODO C++14: std::make_unique
114 // Init UI only after the event loop has started
115 // TODO Qt5: Make this a lambda
116 QTimer::singleShot(0, this, SLOT(initUi()));
120 void QtUiApplication::initUi()
122 QtUi::instance()->init();
124 // Needs to happen after UI init, so the MainWin quit handler is registered first
125 Quassel::registerQuitHandler(quitHandler());
127 resumeSessionIfPossible();
131 Quassel::QuitHandler QtUiApplication::quitHandler()
133 // Wait until the Client instance is destroyed before quitting the event loop
135 connect(_client.get(), SIGNAL(destroyed()), QCoreApplication::instance(), SLOT(quit()));
136 _client.release()->deleteLater();
141 bool QtUiApplication::migrateSettings()
144 // Check major settings version. This represents incompatible changes between settings
145 // versions. So far, we only have 1.
147 uint versionMajor = s.version();
148 if (versionMajor != 1) {
149 qCritical() << qPrintable(QString("Invalid client settings version '%1'")
155 // Check minor settings version, handling upgrades/downgrades as needed
156 // Current minor version
158 // NOTE: If you increase the minor version, you MUST ALSO add new version upgrade logic in
159 // applySettingsMigration()! Otherwise, settings upgrades will fail.
160 const uint VERSION_MINOR_CURRENT = 9;
161 // Stored minor version
162 uint versionMinor = s.versionMinor();
164 if (versionMinor == VERSION_MINOR_CURRENT) {
165 // At latest version, no need to migrate defaults or other settings
167 } else if (versionMinor == 0) {
168 // New configuration, store as current version
169 qDebug() << qPrintable(QString("Set up new client settings v%1.%2")
170 .arg(versionMajor).arg(VERSION_MINOR_CURRENT));
171 s.setVersionMinor(VERSION_MINOR_CURRENT);
173 // Update the settings stylesheet for first setup. We don't know if older content exists,
174 // if the configuration got erased separately, etc.
176 qtUiStyle.generateSettingsQss();
178 } else if (versionMinor < VERSION_MINOR_CURRENT) {
179 // We're upgrading - apply the neccessary upgrades from each interim version
180 // curVersion will never equal VERSION_MINOR_CURRENT, as it represents the version before
181 // the most recent applySettingsMigration() call.
182 for (uint curVersion = versionMinor; curVersion < VERSION_MINOR_CURRENT; curVersion++) {
183 if (!applySettingsMigration(s, curVersion + 1)) {
184 // Something went wrong, time to bail out
185 qCritical() << qPrintable(QString("Could not migrate client settings from v%1.%2 "
187 .arg(versionMajor).arg(curVersion).arg(curVersion + 1));
188 // Keep track of the last successful upgrade to avoid repeating it on next start
189 s.setVersionMinor(curVersion);
193 // Migration successful!
194 qDebug() << qPrintable(QString("Successfully migrated client settings from v%1.%2 to "
196 .arg(versionMajor).arg(versionMinor).arg(VERSION_MINOR_CURRENT));
197 // Store the new minor version
198 s.setVersionMinor(VERSION_MINOR_CURRENT);
201 // versionMinor > VERSION_MINOR_CURRENT
202 // The user downgraded to an older version of Quassel. Let's hope for the best.
203 // Don't change the minorVersion as the newer version's upgrade logic has already run.
204 qWarning() << qPrintable(QString("Client settings v%1.%2 is newer than latest known v%1.%3,"
205 " things might not work!")
206 .arg(versionMajor).arg(versionMinor).arg(VERSION_MINOR_CURRENT));
212 bool QtUiApplication::applySettingsMigration(QtUiSettings settings, const uint newVersion)
214 switch (newVersion) {
215 // Version 0 and 1 aren't valid upgrade paths - one represents no version, the other is the
216 // oldest version. Ignore those, start from 2 and higher.
217 // Each missed version will be called in sequence. E.g. to upgrade from '1' to '3', this
218 // function will be called with '2', then '3'.
219 // Use explicit scope via { ... } to avoid cross-initialization
221 // In most cases, the goal is to preserve the older default values for keys that haven't been
222 // saved. Exceptions will be noted below.
223 // NOTE: If you add new upgrade logic here, you MUST ALSO increase VERSION_MINOR_CURRENT in
224 // migrateSettings()! Otherwise, your upgrade logic won't ever be called.
227 // New default changes: show highest sender prefix mode, if available
231 ChatViewSettings chatViewSettings;
232 const QString senderPrefixModeId = "SenderPrefixMode";
233 if (!chatViewSettings.valueExists(senderPrefixModeId)) {
234 // New default is HighestMode, preserve previous behavior by setting to NoModes
235 chatViewSettings.setValue(senderPrefixModeId,
236 static_cast<int>(UiStyle::SenderPrefixMode::NoModes));
240 // Migration complete!
246 // New default changes: RegEx checkbox now toggles Channel regular expressions, too
248 // This only affects local highlights. Core-side highlights weren't released in stable when
249 // this change was made, so no need to migrate those.
252 // NotificationSettings
253 NotificationSettings notificationSettings;
255 // Check each highlight rule for a "Channel" field. If one exists, convert to RegEx mode.
256 // This might be more efficient with std::transform() or such. It /is/ only run once...
257 auto highlightList = notificationSettings.highlightList();
258 bool changesMade = false;
259 for (int index = 0; index < highlightList.count(); ++index)
261 // Load the highlight rule...
262 auto highlightRule = highlightList[index].toMap();
264 // Check if "Channel" has anything set and RegEx is disabled
265 if (!highlightRule["Channel"].toString().isEmpty()
266 && highlightRule["RegEx"].toBool() == false) {
267 // We have a rule to convert
269 // Mark as a regular expression, allowing the Channel filtering to work the same as
270 // before the upgrade
271 highlightRule["RegEx"] = true;
273 // Convert the main rule to regular expression, mirroring the conversion to wildcard
274 // format from QtUiMessageProcessor::checkForHighlight()
275 highlightRule["Name"] =
276 "(^|\\W)" + QRegExp::escape(highlightRule["Name"].toString()) + "(\\W|$)";
278 // Save the rule back
279 highlightList[index] = highlightRule;
284 // Save the modified rules if any changes were made
286 notificationSettings.setHighlightList(highlightList);
290 // Migration complete!
295 // New default changes: UseProxy is no longer used in CoreAccountSettings
296 CoreAccountSettings s;
297 for (auto &&accountId : s.knownAccounts()) {
298 auto map = s.retrieveAccountData(accountId);
299 if (!map.value("UseProxy", false).toBool()) {
300 map["ProxyType"] = static_cast<int>(QNetworkProxy::ProxyType::NoProxy);
302 map.remove("UseProxy");
303 s.storeAccountData(accountId, map);
306 // Migration complete!
311 // New default changes: sender colors switched around to Tango-ish theme
314 // QtUiStyle settings
315 QtUiStyleSettings settingsUiStyleColors("Colors");
316 // Preserve the old default values for all variants
317 const QColor oldDefaultSenderColorSelf = QColor(0, 0, 0);
318 const QList<QColor> oldDefaultSenderColors = QList<QColor> {
319 QColor(204, 13, 127), /// Sender00
320 QColor(142, 85, 233), /// Sender01
321 QColor(179, 14, 14), /// Sender02
322 QColor( 23, 179, 57), /// Sender03
323 QColor( 88, 175, 179), /// Sender04
324 QColor(157, 84, 179), /// Sender05
325 QColor(179, 151, 117), /// Sender06
326 QColor( 49, 118, 179), /// Sender07
327 QColor(233, 13, 127), /// Sender08
328 QColor(142, 85, 233), /// Sender09
329 QColor(179, 14, 14), /// Sender10
330 QColor( 23, 179, 57), /// Sender11
331 QColor( 88, 175, 179), /// Sender12
332 QColor(157, 84, 179), /// Sender13
333 QColor(179, 151, 117), /// Sender14
334 QColor( 49, 118, 179), /// Sender15
336 if (!settingsUiStyleColors.valueExists("SenderSelf")) {
337 // Preserve the old default sender color if none set
338 settingsUiStyleColors.setValue("SenderSelf", oldDefaultSenderColorSelf);
340 QString senderColorId;
341 for (int i = 0; i < oldDefaultSenderColors.count(); i++) {
342 // Get the sender color ID for each available color
343 QString dez = QString::number(i);
344 if (dez.length() == 1) dez.prepend('0');
345 senderColorId = QString("Sender" + dez);
346 if (!settingsUiStyleColors.valueExists(senderColorId)) {
347 // Preserve the old default sender color if none set
348 settingsUiStyleColors.setValue(senderColorId, oldDefaultSenderColors[i]);
352 // Update the settings stylesheet with old defaults
354 qtUiStyle.generateSettingsQss();
357 // Migration complete!
362 // New default changes: sender colors apply to nearly all messages with nicks
365 // QtUiStyle settings
366 QtUiStyleSettings settingsUiStyleColors("Colors");
367 const QString useNickGeneralColorsId = "UseNickGeneralColors";
368 if (!settingsUiStyleColors.valueExists(useNickGeneralColorsId)) {
369 // New default is true, preserve previous behavior by setting to false
370 settingsUiStyleColors.setValue(useNickGeneralColorsId, false);
373 // Update the settings stylesheet with old defaults
375 qtUiStyle.generateSettingsQss();
378 // Migration complete!
383 // New default changes: system locale used to generate a timestamp format string, deciding
384 // 24-hour or 12-hour timestamp.
388 const QString useCustomTimestampFormatId = "ChatView/__default__/UseCustomTimestampFormat";
389 if (!settings.valueExists(useCustomTimestampFormatId)) {
390 // New default value is false, preserve previous behavior by setting to true
391 settings.setValue(useCustomTimestampFormatId, true);
395 // Migration complete!
400 // New default changes: per-chat history and line wrapping enabled by default.
403 // InputWidget settings
404 UiSettings settingsInputWidget("InputWidget");
405 const QString enableInputPerChatId = "EnablePerChatHistory";
406 if (!settingsInputWidget.valueExists(enableInputPerChatId)) {
407 // New default value is true, preserve previous behavior by setting to false
408 settingsInputWidget.setValue(enableInputPerChatId, false);
411 const QString enableInputLinewrap = "EnableLineWrap";
412 if (!settingsInputWidget.valueExists(enableInputLinewrap)) {
413 // New default value is true, preserve previous behavior by setting to false
414 settingsInputWidget.setValue(enableInputLinewrap, false);
418 // Migration complete!
423 // New default changes: sender <nick> brackets disabled, sender colors and sender CTCP
428 const QString timestampFormatId = "ChatView/__default__/TimestampFormat";
429 if (!settings.valueExists(timestampFormatId)) {
430 // New default value is " hh:mm:ss", preserve old default of "[hh:mm:ss]"
431 settings.setValue(timestampFormatId, "[hh:mm:ss]");
434 const QString showSenderBracketsId = "ChatView/__default__/ShowSenderBrackets";
435 if (!settings.valueExists(showSenderBracketsId)) {
436 // New default is false, preserve previous behavior by setting to true
437 settings.setValue(showSenderBracketsId, true);
442 // QtUiStyle settings
443 QtUiStyleSettings settingsUiStyleColors("Colors");
444 const QString useSenderColorsId = "UseSenderColors";
445 if (!settingsUiStyleColors.valueExists(useSenderColorsId)) {
446 // New default is true, preserve previous behavior by setting to false
447 settingsUiStyleColors.setValue(useSenderColorsId, false);
450 const QString useSenderActionColorsId = "UseSenderActionColors";
451 if (!settingsUiStyleColors.valueExists(useSenderActionColorsId)) {
452 // New default is true, preserve previous behavior by setting to false
453 settingsUiStyleColors.setValue(useSenderActionColorsId, false);
456 // Update the settings stylesheet with old defaults
458 qtUiStyle.generateSettingsQss();
461 // Migration complete!
465 // Something unexpected happened
471 void QtUiApplication::commitData(QSessionManager &manager)
478 void QtUiApplication::saveState(QSessionManager &manager)
480 //qDebug() << QString("saving session state to id %1").arg(manager.sessionId());
481 // AccountId activeCore = Client::currentCoreAccount().accountId(); // FIXME store this!
482 SessionSettings s(manager.sessionId());
484 QtUi::mainWindow()->saveStateToSettings(s);
488 void QtUiApplication::resumeSessionIfPossible()
491 if (isSessionRestored()) {
492 qDebug() << QString("restoring from session %1").arg(sessionId());
493 SessionSettings s(sessionId());
496 QtUi::mainWindow()->restoreStateFromSettings(s);
500 SessionSettings s(QString("1"));