Debian Codegraph @

src/MainWindow.cpp

raw symbols SCIP
1 // SPDX-FileCopyrightText: Nheko Contributors
2 //
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
5 #include <QApplication>
6 #include <QMessageBox>
7
8 #include <mtx/events/collections.hpp>
9 #include <mtx/requests.hpp>
10 #include <mtx/responses/login.hpp>
11
12 #include "BlurhashProvider.h"
13 #include "Cache_p.h"
14 #include "ChatPage.h"
15 #include "ColorImageProvider.h"
16 #include "Config.h"
17 #include "JdenticonProvider.h"
18 #include "Logging.h"
19 #include "MainWindow.h"
20 #include "MatrixClient.h"
21 #include "MxcImageProvider.h"
22 #include "TrayIcon.h"
23 #include "UserSettingsPage.h"
24 #include "Utils.h"
25 #include "dock/Dock.h"
26 #include "encryption/DeviceVerificationFlow.h"
27 #include "timeline/RoomlistModel.h"
28 #include "timeline/TimelineModel.h"
29 #include "timeline/TimelineViewManager.h"
30 #include "ui/Theme.h"
31 #include "voip/CallManager.h"
32 #include "voip/WebRTCSession.h"
33
34 #ifdef NHEKO_DBUS_SYS
35 #include "dbus/NhekoDBusApi.h"
36 #endif
37
38 MainWindow *MainWindow::instance_ = nullptr;
39
40 MainWindow::MainWindow(QWindow *parent)
41 : QQuickView(parent)
42 , userSettings_{UserSettings::instance()}
43 {
44 instance_ = this;
45
46 MainWindow::setWindowTitle(0);
47 setObjectName(QStringLiteral("MainWindow"));
48 setResizeMode(QQuickView::SizeRootObjectToView);
49 setMinimumHeight(conf::window::minHeight);
50 setMinimumWidth(conf::window::minWidth);
51 restoreWindowSize();
52
53 chat_page_ = new ChatPage(userSettings_, this);
54 registerQmlTypes();
55
56 setColor(Theme::paletteFromTheme(userSettings_->theme()).window().color());
57 setSource(QUrl(QStringLiteral("qrc:///resources/qml/Root.qml")));
58
59 trayIcon_ = new TrayIcon(QStringLiteral(":/logos/nheko.svg"), this);
60
61 connect(chat_page_, &ChatPage::closing, this, [this] { switchToLoginPage(""); });
62 connect(chat_page_, &ChatPage::unreadMessages, this, &MainWindow::setWindowTitle);
63 connect(chat_page_, &ChatPage::unreadMessages, trayIcon_, &TrayIcon::setUnreadCount);
64 connect(chat_page_, &ChatPage::showLoginPage, this, &MainWindow::switchToLoginPage);
65 connect(chat_page_, &ChatPage::showNotification, this, &MainWindow::showNotification);
66
67 connect(userSettings_.get(), &UserSettings::trayChanged, trayIcon_, &TrayIcon::setVisible);
68 connect(trayIcon_,
69 SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
70 this,
71 SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
72
73 trayIcon_->setVisible(userSettings_->tray());
74 dock_ = new Dock(this);
75 connect(chat_page_, SIGNAL(unreadMessages(int)), dock_, SLOT(setUnreadCount(int)));
76
77 // load cache on event loop
78 QTimer::singleShot(0, this, [this] {
79 if (hasActiveUser()) {
80 QString token = userSettings_->accessToken();
81 QString home_server = userSettings_->homeserver();
82 QString user_id = userSettings_->userId();
83 QString device_id = userSettings_->deviceId();
84
85 http::client()->set_access_token(token.toStdString());
86 http::client()->set_server(home_server.toStdString());
87 http::client()->set_device_id(device_id.toStdString());
88
89 try {
90 using namespace mtx::identifiers;
91 http::client()->set_user(parse<User>(user_id.toStdString()));
92 } catch (const std::invalid_argument &) {
93 nhlog::ui()->critical("bootstrapped with invalid user_id: {}",
94 user_id.toStdString());
95 }
96
97 nhlog::ui()->info("User already signed in, showing chat page");
98 showChatPage();
99 }
100 });
101 }
102
103 void
104 MainWindow::registerQmlTypes()
105 {
106 imgProvider = new MxcImageProvider();
107 engine()->addImageProvider(QStringLiteral("MxcImage"), imgProvider);
108 engine()->addImageProvider(QStringLiteral("colorimage"), new ColorImageProvider());
109 engine()->addImageProvider(QStringLiteral("blurhash"), new BlurhashProvider());
110 if (JdenticonProvider::isAvailable())
111 engine()->addImageProvider(QStringLiteral("jdenticon"), new JdenticonProvider());
112
113 QObject::connect(engine(), &QQmlEngine::quit, &QGuiApplication::quit);
114
115 #ifdef NHEKO_DBUS_SYS
116 if (UserSettings::instance()->exposeDBusApi()) {
117 if (QDBusConnection::sessionBus().isConnected() &&
118 QDBusConnection::sessionBus().registerService(NHEKO_DBUS_SERVICE_NAME)) {
119 nheko::dbus::init();
120 nhlog::ui()->info("Initialized D-Bus");
121 dbusAvailable_ = true;
122 } else
123 nhlog::ui()->warn("Could not connect to D-Bus!");
124 }
125 #endif
126 }
127
128 void
129 MainWindow::setWindowTitle(int notificationCount)
130 {
131 QString name = QStringLiteral("nheko");
132
133 if (!userSettings_.data()->profile().isEmpty())
134 name += " | " + userSettings_.data()->profile();
135 if (notificationCount > 0) {
136 name.append(QString{QStringLiteral(" (%1)")}.arg(notificationCount));
137 }
138 QQuickView::setTitle(name);
139 }
140
141 // HACK: https://bugreports.qt.io/browse/QTBUG-83972, qtwayland cannot auto hide menu
142 void
143 MainWindow::mousePressEvent(QMouseEvent *event)
144 {
145 #if defined(Q_OS_LINUX)
146 if (QGuiApplication::platformName() == "wayland") {
147 emit hideMenu();
148 }
149 #endif
150 return QQuickView::mousePressEvent(event);
151 }
152
153 void
154 MainWindow::restoreWindowSize()
155 {
156 int savedWidth = userSettings_->qsettings()->value(QStringLiteral("window/width")).toInt();
157 int savedheight = userSettings_->qsettings()->value(QStringLiteral("window/height")).toInt();
158
159 nhlog::ui()->info("Restoring window size {}x{}", savedWidth, savedheight);
160
161 if (savedWidth == 0 || savedheight == 0)
162 resize(conf::window::width, conf::window::height);
163 else
164 resize(savedWidth, savedheight);
165 }
166
167 void
168 MainWindow::saveCurrentWindowSize()
169 {
170 auto settings = userSettings_->qsettings();
171 QSize current = size();
172
173 settings->setValue(QStringLiteral("window/width"), current.width());
174 settings->setValue(QStringLiteral("window/height"), current.height());
175 }
176
177 void
178 MainWindow::showChatPage()
179 {
180 auto userid = QString::fromStdString(http::client()->user_id().to_string());
181 auto device_id = QString::fromStdString(http::client()->device_id());
182 auto homeserver = QString::fromStdString(http::client()->server_url());
183 auto token = QString::fromStdString(http::client()->access_token());
184
185 userSettings_.data()->setUserId(userid);
186 userSettings_.data()->setAccessToken(token);
187 userSettings_.data()->setDeviceId(device_id);
188 userSettings_.data()->setHomeserver(homeserver);
189
190 chat_page_->bootstrap(userid, homeserver, token);
191 connect(cache::client(), &Cache::databaseReady, this, &MainWindow::secretsChanged);
192 connect(cache::client(), &Cache::secretChanged, this, &MainWindow::secretsChanged);
193
194 emit reload();
195 nhlog::ui()->info("Switching to chat page");
196 emit switchToChatPage();
197 }
198
199 bool
200 NhekoFixupPaletteEventFilter::eventFilter(QObject *obj, QEvent *event)
201 {
202 // Workaround for the QGuiApplication palette not being applied to toplevel windows for some
203 // reason?!?
204 if (event->type() == QEvent::ChildAdded &&
205 obj->metaObject()->className() == QStringLiteral("QQuickRootItem")) {
206 auto windows = QGuiApplication::topLevelWindows();
207 for (const auto window : std::as_const(windows)) {
208 if (window->property("posted").isValid())
209 continue;
210 QGuiApplication::postEvent(window, new QEvent(QEvent::ApplicationPaletteChange));
211 window->setProperty("posted", true);
212 }
213 }
214 return false;
215 }
216
217 void
218 MainWindow::closeEvent(QCloseEvent *event)
219 {
220 if (WebRTCSession::instance().state() != webrtc::State::DISCONNECTED) {
221 if (QMessageBox::question(
222 nullptr, QStringLiteral("nheko"), QStringLiteral("A call is in progress. Quit?")) !=
223 QMessageBox::Yes) {
224 event->ignore();
225 return;
226 }
227 }
228
229 if (!qApp->isSavingSession() && isVisible() && pageSupportsTray() && userSettings_->tray()) {
230 event->ignore();
231 hide();
232 return;
233 }
234 }
235
236 void
237 MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
238 {
239 switch (reason) {
240 case QSystemTrayIcon::Trigger:
241 if (!isVisible()) {
242 show();
243 } else {
244 hide();
245 }
246 break;
247 default:
248 break;
249 }
250 }
251
252 bool
253 MainWindow::hasActiveUser()
254 {
255 auto settings = userSettings_->qsettings();
256 QString prefix;
257 if (userSettings_->profile() != QLatin1String(""))
258 prefix = "profile/" + userSettings_->profile() + "/";
259
260 return !settings->value(prefix + "auth/access_token").toString().isEmpty() &&
261 !settings->value(prefix + "auth/home_server").toString().isEmpty() &&
262 !settings->value(prefix + "auth/user_id").toString().isEmpty();
263 }
264
265 bool
266 MainWindow::pageSupportsTray() const
267 {
268 return !http::client()->access_token().empty();
269 }
270
271 inline void
272 MainWindow::showDialog(QWidget *dialog)
273 {
274 dialog->setWindowFlags(Qt::WindowType::Dialog | Qt::WindowType::WindowCloseButtonHint |
275 Qt::WindowType::WindowTitleHint);
276 dialog->raise();
277 dialog->show();
278 utils::centerWidget(dialog, this);
279 dialog->window()->windowHandle()->setTransientParent(this);
280 }
281
282 void
283 MainWindow::addPerRoomWindow(const QString &room, QWindow *window)
284 {
285 roomWindows_.insert(room, window);
286 }
287 void
288 MainWindow::removePerRoomWindow(const QString &room, QWindow *window)
289 {
290 roomWindows_.remove(room, window);
291 }
292 QWindow *
293 MainWindow::windowForRoom(const QString &room)
294 {
295 auto currMainWindowRoom = ChatPage::instance()->timelineManager()->rooms()->currentRoom();
296 if ((currMainWindowRoom && currMainWindowRoom->roomId() == room) ||
297 ChatPage::instance()->timelineManager()->rooms()->currentRoomPreview().roomid_ == room)
298 return this;
299 else if (auto res = roomWindows_.find(room); res != roomWindows_.end())
300 return res.value();
301 return nullptr;
302 }
303
304 QString
305 MainWindow::focusedRoom() const
306 {
307 auto focus = QGuiApplication::focusWindow();
308 if (!focus)
309 return {};
310
311 if (focus == this) {
312 auto currMainWindowRoom = ChatPage::instance()->timelineManager()->rooms()->currentRoom();
313 if (currMainWindowRoom)
314 return currMainWindowRoom->roomId();
315 else
316 return ChatPage::instance()->timelineManager()->rooms()->currentRoomPreview().roomid_;
317 }
318
319 auto i = roomWindows_.constBegin();
320 while (i != roomWindows_.constEnd()) {
321 if (i.value() == focus)
322 return i.key();
323 ++i;
324 }
325
326 return nullptr;
327 }
328
329 #include "moc_MainWindow.cpp"