Make the UI actually emit the required signal
[quassel.git] / src / qtui / qtuiapplication.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2016 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     Quassel(),
44     _aboutToQuit(false)
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     setDataDirPaths(dataDirs);
78
79 #else /* HAVE_KDE4 */
80
81     setDataDirPaths(findDataDirPaths());
82
83 #endif /* HAVE_KDE4 */
84
85 #if defined(HAVE_KDE4) || defined(Q_OS_MAC)
86     disableCrashhandler();
87 #endif /* HAVE_KDE4 || Q_OS_MAC */
88     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         // FIXME: MIGRATION 0.3 -> 0.4: Move database and core config to new location
108         // Move settings, note this does not delete the old files
109 #ifdef Q_OS_MAC
110         QSettings newSettings("quassel-irc.org", "quasselclient");
111 #else
112
113 # ifdef Q_OS_WIN
114         QSettings::Format format = QSettings::IniFormat;
115 # else
116         QSettings::Format format = QSettings::NativeFormat;
117 # endif
118
119         QString newFilePath = Quassel::configDirPath() + "quasselclient"
120                               + ((format == QSettings::NativeFormat) ? QLatin1String(".conf") : QLatin1String(".ini"));
121         QSettings newSettings(newFilePath, format);
122 #endif /* Q_OS_MAC */
123
124         if (newSettings.value("Config/Version").toUInt() == 0) {
125 #     ifdef Q_OS_MAC
126             QString org = "quassel-irc.org";
127 #     else
128             QString org = "Quassel Project";
129 #     endif
130             QSettings oldSettings(org, "Quassel Client");
131             if (oldSettings.allKeys().count()) {
132                 qWarning() << "\n\n*** IMPORTANT: Config and data file locations have changed. Attempting to auto-migrate your client settings...";
133                 foreach(QString key, oldSettings.allKeys())
134                 newSettings.setValue(key, oldSettings.value(key));
135                 newSettings.setValue("Config/Version", 1);
136                 qWarning() << "*   Your client settings have been migrated to" << newSettings.fileName();
137                 qWarning() << "*** Migration completed.\n\n";
138             }
139         }
140
141         // MIGRATION end
142
143         // Settings upgrade/downgrade handling
144         if (!migrateSettings()) {
145             qCritical() << "Could not load or upgrade client settings, terminating!";
146             return false;
147         }
148
149         // Checking if settings Icon Theme is valid
150         QString savedIcontheme = QtUiSettings().value("IconTheme", QVariant("")).toString();
151 #ifndef WITH_OXYGEN
152         if (savedIcontheme == "oxygen")
153             QtUiSettings().remove("IconTheme");
154 #endif
155 #ifndef WITH_BREEZE
156         if (savedIcontheme == "breeze")
157             QtUiSettings().remove("IconTheme");
158 #endif
159 #ifndef WITH_BREEZE_DARK
160         if (savedIcontheme == "breezedark")
161             QtUiSettings().remove("IconTheme");
162 #endif
163
164         // Set the icon theme
165         if (Quassel::isOptionSet("icontheme"))
166             QIcon::setThemeName(Quassel::optionValue("icontheme"));
167         else if (QtUiSettings().value("IconTheme", QVariant("")).toString() != "")
168             QIcon::setThemeName(QtUiSettings().value("IconTheme").toString());
169         else if (QIcon::themeName().isEmpty())
170             // Some platforms don't set a default icon theme; chances are we can find our bundled theme though
171             QIcon::setThemeName("breeze");
172
173         // session resume
174         QtUi *gui = new QtUi();
175         Client::init(gui);
176         // init gui only after the event loop has started
177         // QTimer::singleShot(0, gui, SLOT(init()));
178         gui->init();
179         resumeSessionIfPossible();
180         return true;
181     }
182     return false;
183 }
184
185
186 QtUiApplication::~QtUiApplication()
187 {
188     Client::destroy();
189 }
190
191
192 void QtUiApplication::quit()
193 {
194     QtUi::mainWindow()->quit();
195 }
196
197
198 bool QtUiApplication::migrateSettings()
199 {
200     // --------
201     // Check major settings version.  This represents incompatible changes between settings
202     // versions.  So far, we only have 1.
203     QtUiSettings s;
204     uint versionMajor = s.version();
205     if (versionMajor != 1) {
206         qCritical() << qPrintable(QString("Invalid client settings version '%1'")
207                                   .arg(versionMajor));
208         return false;
209     }
210
211     // --------
212     // Check minor settings version, handling upgrades/downgrades as needed
213     // Current minor version
214     //
215     // NOTE:  If you increase the minor version, you MUST ALSO add new version upgrade logic in
216     // applySettingsMigration()!  Otherwise, settings upgrades will fail.
217     const uint VERSION_MINOR_CURRENT = 6;
218     // Stored minor version
219     uint versionMinor = s.versionMinor();
220
221     if (versionMinor == VERSION_MINOR_CURRENT) {
222         // At latest version, no need to migrate defaults or other settings
223         return true;
224     } else if (versionMinor == 0) {
225         // New configuration, store as current version
226         qDebug() << qPrintable(QString("Set up new client settings v%1.%2")
227                                .arg(versionMajor).arg(VERSION_MINOR_CURRENT));
228         s.setVersionMinor(VERSION_MINOR_CURRENT);
229
230         // Update the settings stylesheet for first setup.  We don't know if older content exists,
231         // if the configuration got erased separately, etc.
232         QtUiStyle qtUiStyle;
233         qtUiStyle.generateSettingsQss();
234         return true;
235     } else if (versionMinor < VERSION_MINOR_CURRENT) {
236         // We're upgrading - apply the neccessary upgrades from each interim version
237         // curVersion will never equal VERSION_MINOR_CURRENT, as it represents the version before
238         // the most recent applySettingsMigration() call.
239         for (uint curVersion = versionMinor; curVersion < VERSION_MINOR_CURRENT; curVersion++) {
240             if (!applySettingsMigration(s, curVersion + 1)) {
241                 // Something went wrong, time to bail out
242                 qCritical() << qPrintable(QString("Could not migrate client settings from v%1.%2 "
243                                                   "to v%1.%3")
244                                           .arg(versionMajor).arg(curVersion).arg(curVersion + 1));
245                 // Keep track of the last successful upgrade to avoid repeating it on next start
246                 s.setVersionMinor(curVersion);
247                 return false;
248             }
249         }
250         // Migration successful!
251         qDebug() << qPrintable(QString("Successfully migrated client settings from v%1.%2 to "
252                                        "v%1.%3")
253                                .arg(versionMajor).arg(versionMinor).arg(VERSION_MINOR_CURRENT));
254         // Store the new minor version
255         s.setVersionMinor(VERSION_MINOR_CURRENT);
256         return true;
257     } else {
258         // versionMinor > VERSION_MINOR_CURRENT
259         // The user downgraded to an older version of Quassel.  Let's hope for the best.
260         // Don't change the minorVersion as the newer version's upgrade logic has already run.
261         qWarning() << qPrintable(QString("Client settings v%1.%2 is newer than latest known v%1.%3,"
262                                          " things might not work!")
263                                  .arg(versionMajor).arg(versionMinor).arg(VERSION_MINOR_CURRENT));
264         return true;
265     }
266 }
267
268
269 bool QtUiApplication::applySettingsMigration(QtUiSettings settings, const uint newVersion)
270 {
271     switch (newVersion) {
272     // Version 0 and 1 aren't valid upgrade paths - one represents no version, the other is the
273     // oldest version.  Ignore those, start from 2 and higher.
274     // Each missed version will be called in sequence.  E.g. to upgrade from '1' to '3', this
275     // function will be called with '2', then '3'.
276     // Use explicit scope via { ... } to avoid cross-initialization
277     //
278     // In most cases, the goal is to preserve the older default values for keys that haven't been
279     // saved.  Exceptions will be noted below.
280     // NOTE:  If you add new upgrade logic here, you MUST ALSO increase VERSION_MINOR_CURRENT in
281     // migrateSettings()!  Otherwise, your upgrade logic won't ever be called.
282     case 6:
283     {
284         // New default changes: sender colors switched around to Tango-ish theme
285
286         // --------
287         // QtUiStyle settings
288         QtUiStyleSettings settingsUiStyleColors("Colors");
289         // Preserve the old default values for all variants
290         const QColor oldDefaultSenderColorSelf = QColor(0, 0, 0);
291         const QList<QColor> oldDefaultSenderColors = QList<QColor> {
292             QColor(204,  13, 127),  /// Sender00
293             QColor(142,  85, 233),  /// Sender01
294             QColor(179,  14,  14),  /// Sender02
295             QColor( 23, 179,  57),  /// Sender03
296             QColor( 88, 175, 179),  /// Sender04
297             QColor(157,  84, 179),  /// Sender05
298             QColor(179, 151, 117),  /// Sender06
299             QColor( 49, 118, 179),  /// Sender07
300             QColor(233,  13, 127),  /// Sender08
301             QColor(142,  85, 233),  /// Sender09
302             QColor(179,  14,  14),  /// Sender10
303             QColor( 23, 179,  57),  /// Sender11
304             QColor( 88, 175, 179),  /// Sender12
305             QColor(157,  84, 179),  /// Sender13
306             QColor(179, 151, 117),  /// Sender14
307             QColor( 49, 118, 179),  /// Sender15
308         };
309         if (!settingsUiStyleColors.valueExists("SenderSelf")) {
310             // Preserve the old default sender color if none set
311             settingsUiStyleColors.setValue("SenderSelf", oldDefaultSenderColorSelf);
312         }
313         QString senderColorId;
314         for (int i = 0; i < oldDefaultSenderColors.count(); i++) {
315             // Get the sender color ID for each available color
316             QString dez = QString::number(i);
317             if (dez.length() == 1) dez.prepend('0');
318             senderColorId = QString("Sender" + dez);
319             if (!settingsUiStyleColors.valueExists(senderColorId)) {
320                 // Preserve the old default sender color if none set
321                 settingsUiStyleColors.setValue(senderColorId, oldDefaultSenderColors[i]);
322             }
323         }
324
325         // Update the settings stylesheet with old defaults
326         QtUiStyle qtUiStyle;
327         qtUiStyle.generateSettingsQss();
328         // --------
329
330         // Migration complete!
331         return true;
332     }
333     case 5:
334     {
335         // New default changes: sender colors apply to nearly all messages with nicks
336
337         // --------
338         // QtUiStyle settings
339         QtUiStyleSettings settingsUiStyleColors("Colors");
340         const QString useNickGeneralColorsId = "UseNickGeneralColors";
341         if (!settingsUiStyleColors.valueExists(useNickGeneralColorsId)) {
342             // New default is true, preserve previous behavior by setting to false
343             settingsUiStyleColors.setValue(useNickGeneralColorsId, false);
344         }
345
346         // Update the settings stylesheet with old defaults
347         QtUiStyle qtUiStyle;
348         qtUiStyle.generateSettingsQss();
349         // --------
350
351         // Migration complete!
352         return true;
353     }
354     case 4:
355     {
356         // New default changes: system locale used to generate a timestamp format string, deciding
357         // 24-hour or 12-hour timestamp.
358
359         // --------
360         // ChatView settings
361         const QString useCustomTimestampFormatId = "ChatView/__default__/UseCustomTimestampFormat";
362         if (!settings.valueExists(useCustomTimestampFormatId)) {
363             // New default value is false, preserve previous behavior by setting to true
364             settings.setValue(useCustomTimestampFormatId, true);
365         }
366         // --------
367
368         // Migration complete!
369         return true;
370     }
371     case 3:
372     {
373         // New default changes: per-chat history and line wrapping enabled by default.
374
375         // --------
376         // InputWidget settings
377         UiSettings settingsInputWidget("InputWidget");
378         const QString enableInputPerChatId = "EnablePerChatHistory";
379         if (!settingsInputWidget.valueExists(enableInputPerChatId)) {
380             // New default value is true, preserve previous behavior by setting to false
381             settingsInputWidget.setValue(enableInputPerChatId, false);
382         }
383
384         const QString enableInputLinewrap = "EnableLineWrap";
385         if (!settingsInputWidget.valueExists(enableInputLinewrap)) {
386             // New default value is true, preserve previous behavior by setting to false
387             settingsInputWidget.setValue(enableInputLinewrap, false);
388         }
389         // --------
390
391         // Migration complete!
392         return true;
393     }
394     case 2:
395     {
396         // New default changes: sender <nick> brackets disabled, sender colors and sender CTCP
397         // colors enabled.
398
399         // --------
400         // ChatView settings
401         const QString timestampFormatId = "ChatView/__default__/TimestampFormat";
402         if (!settings.valueExists(timestampFormatId)) {
403             // New default value is " hh:mm:ss", preserve old default of "[hh:mm:ss]"
404             settings.setValue(timestampFormatId, "[hh:mm:ss]");
405         }
406
407         const QString showSenderBracketsId = "ChatView/__default__/ShowSenderBrackets";
408         if (!settings.valueExists(showSenderBracketsId)) {
409             // New default is false, preserve previous behavior by setting to true
410             settings.setValue(showSenderBracketsId, true);
411         }
412         // --------
413
414         // --------
415         // QtUiStyle settings
416         QtUiStyleSettings settingsUiStyleColors("Colors");
417         const QString useSenderColorsId = "UseSenderColors";
418         if (!settingsUiStyleColors.valueExists(useSenderColorsId)) {
419             // New default is true, preserve previous behavior by setting to false
420             settingsUiStyleColors.setValue(useSenderColorsId, false);
421         }
422
423         const QString useSenderActionColorsId = "UseSenderActionColors";
424         if (!settingsUiStyleColors.valueExists(useSenderActionColorsId)) {
425             // New default is true, preserve previous behavior by setting to false
426             settingsUiStyleColors.setValue(useSenderActionColorsId, false);
427         }
428
429         // Update the settings stylesheet with old defaults
430         QtUiStyle qtUiStyle;
431         qtUiStyle.generateSettingsQss();
432         // --------
433
434         // Migration complete!
435         return true;
436     }
437     default:
438         // Something unexpected happened
439         return false;
440     }
441 }
442
443
444 void QtUiApplication::commitData(QSessionManager &manager)
445 {
446     Q_UNUSED(manager)
447     _aboutToQuit = true;
448 }
449
450
451 void QtUiApplication::saveState(QSessionManager &manager)
452 {
453     //qDebug() << QString("saving session state to id %1").arg(manager.sessionId());
454     // AccountId activeCore = Client::currentCoreAccount().accountId(); // FIXME store this!
455     SessionSettings s(manager.sessionId());
456     s.setSessionAge(0);
457     QtUi::mainWindow()->saveStateToSettings(s);
458 }
459
460
461 void QtUiApplication::resumeSessionIfPossible()
462 {
463     // load all sessions
464     if (isSessionRestored()) {
465         qDebug() << QString("restoring from session %1").arg(sessionId());
466         SessionSettings s(sessionId());
467         s.sessionAging();
468         s.setSessionAge(0);
469         QtUi::mainWindow()->restoreStateFromSettings(s);
470         s.cleanup();
471     }
472     else {
473         SessionSettings s(QString("1"));
474         s.sessionAging();
475         s.cleanup();
476     }
477 }