icons: Warn on missing icons
[quassel.git] / src / qtui / qtui.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 "qtui.h"
22
23 #include <QApplication>
24 #include <QFile>
25 #include <QFileInfo>
26 #include <QIcon>
27 #include <QStringList>
28
29 #include "abstractnotificationbackend.h"
30 #include "buffermodel.h"
31 #include "chatlinemodel.h"
32 #include "contextmenuactionprovider.h"
33 #include "icon.h"
34 #include "mainwin.h"
35 #include "qtuimessageprocessor.h"
36 #include "qtuisettings.h"
37 #include "qtuistyle.h"
38 #include "systemtray.h"
39 #include "toolbaractionprovider.h"
40 #include "types.h"
41 #include "util.h"
42
43 QtUi *QtUi::_instance = nullptr;
44 MainWin *QtUi::_mainWin = nullptr;
45 QList<AbstractNotificationBackend *> QtUi::_notificationBackends;
46 QList<AbstractNotificationBackend::Notification> QtUi::_notifications;
47
48 QtUi::QtUi()
49     : GraphicalUi()
50     , _systemIconTheme{QIcon::themeName()}
51 {
52     if (_instance != nullptr) {
53         qWarning() << "QtUi has been instantiated again!";
54         return;
55     }
56     _instance = this;
57
58     if (Quassel::isOptionSet("icontheme")) {
59         _systemIconTheme = Quassel::optionValue("icontheme");
60         QIcon::setThemeName(_systemIconTheme);
61     }
62
63     QtUiSettings uiSettings;
64     Quassel::loadTranslation(uiSettings.value("Locale", QLocale::system()).value<QLocale>());
65
66     setupIconTheme();
67
68     QApplication::setWindowIcon(icon::get("quassel"));
69
70     setContextMenuActionProvider(new ContextMenuActionProvider(this));
71     setToolBarActionProvider(new ToolBarActionProvider(this));
72
73     setUiStyle(new QtUiStyle(this));
74     _mainWin = new MainWin();
75
76     setMainWidget(_mainWin);
77
78     connect(_mainWin, SIGNAL(connectToCore(const QVariantMap &)), this, SIGNAL(connectToCore(const QVariantMap &)));
79     connect(_mainWin, SIGNAL(disconnectFromCore()), this, SIGNAL(disconnectFromCore()));
80     connect(Client::instance(), SIGNAL(bufferMarkedAsRead(BufferId)), SLOT(closeNotifications(BufferId)));
81 }
82
83
84 QtUi::~QtUi()
85 {
86     unregisterAllNotificationBackends();
87     delete _mainWin;
88     _mainWin = nullptr;
89     _instance = nullptr;
90 }
91
92
93 void QtUi::init()
94 {
95     _mainWin->init();
96     QtUiSettings uiSettings;
97     uiSettings.initAndNotify("UseSystemTrayIcon", this, SLOT(useSystemTrayChanged(QVariant)), true);
98
99     GraphicalUi::init(); // needs to be called after the mainWin is initialized
100 }
101
102
103 MessageModel *QtUi::createMessageModel(QObject *parent)
104 {
105     return new ChatLineModel(parent);
106 }
107
108
109 AbstractMessageProcessor *QtUi::createMessageProcessor(QObject *parent)
110 {
111     return new QtUiMessageProcessor(parent);
112 }
113
114
115 void QtUi::connectedToCore()
116 {
117     _mainWin->connectedToCore();
118 }
119
120
121 void QtUi::disconnectedFromCore()
122 {
123     _mainWin->disconnectedFromCore();
124     GraphicalUi::disconnectedFromCore();
125 }
126
127
128 void QtUi::useSystemTrayChanged(const QVariant &v)
129 {
130     _useSystemTray = v.toBool();
131     SystemTray *tray = mainWindow()->systemTray();
132     if (_useSystemTray) {
133         if (tray->isSystemTrayAvailable())
134             tray->setVisible(true);
135     }
136     else {
137         if (tray->isSystemTrayAvailable() && mainWindow()->isVisible())
138             tray->setVisible(false);
139     }
140 }
141
142
143 bool QtUi::haveSystemTray()
144 {
145     return mainWindow()->systemTray()->isSystemTrayAvailable() && instance()->_useSystemTray;
146 }
147
148
149 bool QtUi::isHidingMainWidgetAllowed() const
150 {
151     return haveSystemTray();
152 }
153
154
155 void QtUi::minimizeRestore(bool show)
156 {
157     SystemTray *tray = mainWindow()->systemTray();
158     if (show) {
159         if (tray && !_useSystemTray)
160             tray->setVisible(false);
161     }
162     else {
163         if (tray && _useSystemTray)
164             tray->setVisible(true);
165     }
166     GraphicalUi::minimizeRestore(show);
167 }
168
169
170 void QtUi::registerNotificationBackend(AbstractNotificationBackend *backend)
171 {
172     if (!_notificationBackends.contains(backend)) {
173         _notificationBackends.append(backend);
174         instance()->connect(backend, SIGNAL(activated(uint)), SLOT(notificationActivated(uint)));
175     }
176 }
177
178
179 void QtUi::unregisterNotificationBackend(AbstractNotificationBackend *backend)
180 {
181     _notificationBackends.removeAll(backend);
182 }
183
184
185 void QtUi::unregisterAllNotificationBackends()
186 {
187     _notificationBackends.clear();
188 }
189
190
191 const QList<AbstractNotificationBackend *> &QtUi::notificationBackends()
192 {
193     return _notificationBackends;
194 }
195
196
197 uint QtUi::invokeNotification(BufferId bufId, AbstractNotificationBackend::NotificationType type, const QString &sender, const QString &text)
198 {
199     static int notificationId = 0;
200
201     AbstractNotificationBackend::Notification notification(++notificationId, bufId, type, sender, text);
202     _notifications.append(notification);
203     foreach(AbstractNotificationBackend *backend, _notificationBackends)
204     backend->notify(notification);
205     return notificationId;
206 }
207
208
209 void QtUi::closeNotification(uint notificationId)
210 {
211     QList<AbstractNotificationBackend::Notification>::iterator i = _notifications.begin();
212     while (i != _notifications.end()) {
213         if (i->notificationId == notificationId) {
214             foreach(AbstractNotificationBackend *backend, _notificationBackends)
215             backend->close(notificationId);
216             i = _notifications.erase(i);
217         }
218         else ++i;
219     }
220 }
221
222
223 void QtUi::closeNotifications(BufferId bufferId)
224 {
225     QList<AbstractNotificationBackend::Notification>::iterator i = _notifications.begin();
226     while (i != _notifications.end()) {
227         if (!bufferId.isValid() || i->bufferId == bufferId) {
228             foreach(AbstractNotificationBackend *backend, _notificationBackends)
229             backend->close(i->notificationId);
230             i = _notifications.erase(i);
231         }
232         else ++i;
233     }
234 }
235
236
237 const QList<AbstractNotificationBackend::Notification> &QtUi::activeNotifications()
238 {
239     return _notifications;
240 }
241
242
243 void QtUi::notificationActivated(uint notificationId)
244 {
245     if (notificationId != 0) {
246         QList<AbstractNotificationBackend::Notification>::iterator i = _notifications.begin();
247         while (i != _notifications.end()) {
248             if (i->notificationId == notificationId) {
249                 BufferId bufId = i->bufferId;
250                 if (bufId.isValid())
251                     Client::bufferModel()->switchToBuffer(bufId);
252                 break;
253             }
254             ++i;
255         }
256     }
257     closeNotification(notificationId);
258
259     activateMainWidget();
260 }
261
262
263 void QtUi::bufferMarkedAsRead(BufferId bufferId)
264 {
265     if (bufferId.isValid()) {
266         closeNotifications(bufferId);
267     }
268 }
269
270
271 std::vector<std::pair<QString, QString>> QtUi::availableIconThemes() const
272 {
273     //: Supported icon theme names
274     static const std::vector<std::pair<QString, QString>> supported {
275         { "breeze", tr("Breeze") },
276         { "breeze-dark", tr("Breeze Dark") },
277         { "oxygen", tr("Oxygen") }
278     };
279
280     std::vector<std::pair<QString, QString>> result;
281     for (auto &&themePair : supported) {
282         for (auto &&dir : QIcon::themeSearchPaths()) {
283             if (QFileInfo{dir + "/" + themePair.first + "/index.theme"}.exists()) {
284                 result.push_back(themePair);
285                 break;
286             }
287         }
288     }
289
290     return result;
291 }
292
293
294 QString QtUi::systemIconTheme() const
295 {
296     return _systemIconTheme;
297 }
298
299
300 void QtUi::setupIconTheme()
301 {
302     // Add paths to our own icon sets to the theme search paths
303     QStringList themePaths = QIcon::themeSearchPaths();
304     themePaths.removeAll(":/icons");  // this should come last
305     for (auto &&dataDir : Quassel::dataDirPaths()) {
306         QString iconDir{dataDir + "icons"};
307         if (QFileInfo{iconDir}.isDir()) {
308             themePaths << iconDir;
309         }
310     }
311     themePaths << ":/icons";
312     QIcon::setThemeSearchPaths(themePaths);
313
314     refreshIconTheme();
315 }
316
317
318 void QtUi::refreshIconTheme()
319 {
320     // List of available fallback themes
321     QStringList availableThemes;
322     for (auto &&themePair : availableIconThemes()) {
323         availableThemes << themePair.first;
324     }
325
326     if (availableThemes.isEmpty()) {
327         // We could probably introduce a more sophisticated fallback handling, such as putting the "most important" icons into hicolor,
328         // but this just gets complex for no good reason. We really rely on a supported theme to be installed, if not system-wide, then
329         // as part of the Quassel installation (which is enabled by default anyway).
330         qWarning() << tr("No supported icon theme installed, you'll lack icons! Supported are the KDE/Plasma themes Breeze, Breeze Dark and Oxygen.");
331         return;
332     }
333
334     UiStyleSettings s;
335     QString fallbackTheme{s.value("Icons/FallbackTheme").toString()};
336
337     if (fallbackTheme.isEmpty() || !availableThemes.contains(fallbackTheme)) {
338         if (availableThemes.contains(_systemIconTheme)) {
339             fallbackTheme = _systemIconTheme;
340         }
341         else {
342             fallbackTheme = availableThemes.first();
343         }
344     }
345
346     if (_systemIconTheme.isEmpty() || _systemIconTheme == fallbackTheme || s.value("Icons/OverrideSystemTheme", false).toBool()) {
347         // We have a valid fallback theme and want to override the system theme (if it's even defined), so we're basically done
348         QIcon::setThemeName(fallbackTheme);
349         emit iconThemeRefreshed();
350         return;
351     }
352
353 #if QT_VERSION >= 0x050000
354     // At this point, we have a system theme that we don't want to override, but that may not contain all
355     // required icons.
356     // We create a dummy theme that inherits first from the system theme, then from the supported fallback.
357     // This rather ugly hack allows us to inject the fallback into the inheritance chain, so non-standard
358     // icons missing in the system theme will be filled in by the fallback.
359     // Since we can't get notified when the system theme changes, this means that a restart may be required
360     // to apply a theme change... but you can't have everything, I guess.
361     if (!_dummyThemeDir) {
362         _dummyThemeDir.reset(new QTemporaryDir{});
363         if (!_dummyThemeDir->isValid() || !QDir{_dummyThemeDir->path()}.mkpath("icons/quassel-icon-proxy/apps/32")) {
364             qWarning() << "Could not create temporary directory for proxying the system icon theme, using fallback";
365             QIcon::setThemeName(fallbackTheme);
366             emit iconThemeRefreshed();
367             return;
368         }
369         // Add this to XDG_DATA_DIRS, otherwise KIconLoader complains
370         auto xdgDataDirs = qgetenv("XDG_DATA_DIRS");
371         if (!xdgDataDirs.isEmpty())
372             xdgDataDirs += ":";
373         xdgDataDirs += _dummyThemeDir->path();
374         qputenv("XDG_DATA_DIRS", xdgDataDirs);
375
376         QIcon::setThemeSearchPaths(QIcon::themeSearchPaths() << _dummyThemeDir->path() + "/icons");
377     }
378
379     QFile indexFile{_dummyThemeDir->path() + "/icons/quassel-icon-proxy/index.theme"};
380     if (!indexFile.open(QFile::WriteOnly|QFile::Truncate)) {
381         qWarning() << "Could not create index file for proxying the system icon theme, using fallback";
382         QIcon::setThemeName(fallbackTheme);
383         emit iconThemeRefreshed();
384         return;
385     }
386
387     // Write a dummy index file that is sufficient to make QIconLoader happy
388     auto indexContents = QString{
389             "[Icon Theme]\n"
390             "Name=quassel-icon-proxy\n"
391             "Inherits=%1,%2\n"
392             "Directories=apps/32\n"
393             "[apps/32]\nSize=32\nType=Fixed\n"
394     }.arg(_systemIconTheme, fallbackTheme);
395     if (indexFile.write(indexContents.toLatin1()) < 0) {
396         qWarning() << "Could not write index file for proxying the system icon theme, using fallback";
397         QIcon::setThemeName(fallbackTheme);
398         emit iconThemeRefreshed();
399         return;
400     }
401     indexFile.close();
402     QIcon::setThemeName("quassel-icon-proxy");
403 #else
404     // Qt4 doesn't support QTemporaryDir. Since it's deprecated and slated to be removed soon anyway, we don't bother
405     // writing a replacement and simply don't support not overriding the system theme.
406     QIcon::setThemeName(fallbackTheme);
407     emit iconThemeRefreshed();
408 #endif
409 }