summary refs log tree commit diff
path: root/src/MainWindow.cpp
blob: 4159006e74e19206247b50b3dd8c55c0cf6fae29 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// SPDX-FileCopyrightText: Nheko Contributors
//
// SPDX-License-Identifier: GPL-3.0-or-later

#include <QApplication>
#include <QMessageBox>

#include <mtx/requests.hpp>
#include <mtx/responses/login.hpp>
#include <mtx/events/collections.hpp>

#include "AliasEditModel.h"
#include "BlurhashProvider.h"
#include "Cache.h"
#include "Cache_p.h"
#include "ChatPage.h"
#include "Clipboard.h"
#include "ColorImageProvider.h"
#include "CombinedImagePackModel.h"
#include "CompletionProxyModel.h"
#include "Config.h"
#include "EventAccessors.h"
#include "GridImagePackModel.h"
#include "ImagePackListModel.h"
#include "InviteesModel.h"
#include "JdenticonProvider.h"
#include "Logging.h"
#include "LoginPage.h"
#include "MainWindow.h"
#include "MatrixClient.h"
#include "MemberList.h"
#include "MxcImageProvider.h"
#include "PowerlevelsEditModels.h"
#include "ReadReceiptsModel.h"
#include "RegisterPage.h"
#include "RoomDirectoryModel.h"
#include "RoomsModel.h"
#include "SingleImagePackModel.h"
#include "TrayIcon.h"
#include "UserDirectoryModel.h"
#include "UserSettingsPage.h"
#include "UsersModel.h"
#include "Utils.h"
#include "dock/Dock.h"
#include "emoji/Provider.h"
#include "encryption/DeviceVerificationFlow.h"
#include "encryption/SelfVerificationStatus.h"
#include "timeline/DelegateChooser.h"
#include "timeline/TimelineFilter.h"
#include "timeline/TimelineViewManager.h"
#include "ui/HiddenEvents.h"
#include "ui/MxcAnimatedImage.h"
#include "ui/MxcMediaProxy.h"
#include "ui/NhekoCursorShape.h"
#include "ui/NhekoDropArea.h"
#include "ui/NhekoEventObserver.h"
#include "ui/NhekoGlobalObject.h"
#include "ui/RoomSummary.h"
#include "ui/UIA.h"
#include "voip/CallManager.h"
#include "voip/WebRTCSession.h"

#ifdef NHEKO_DBUS_SYS
#include "dbus/NhekoDBusApi.h"
#endif

MainWindow *MainWindow::instance_ = nullptr;

MainWindow::MainWindow(QWindow *parent)
  : QQuickView(parent)
  , userSettings_{UserSettings::instance()}
{
    instance_ = this;

    MainWindow::setWindowTitle(0);
    setObjectName(QStringLiteral("MainWindow"));
    setResizeMode(QQuickView::SizeRootObjectToView);
    setMinimumHeight(conf::window::minHeight);
    setMinimumWidth(conf::window::minWidth);
    restoreWindowSize();

    chat_page_ = new ChatPage(userSettings_, this);
    registerQmlTypes();

    setColor(Theme::paletteFromTheme(userSettings_->theme()).window().color());
    setSource(QUrl(QStringLiteral("qrc:///qml/Root.qml")));

    trayIcon_ = new TrayIcon(QStringLiteral(":/logos/nheko.svg"), this);

    connect(chat_page_, &ChatPage::closing, this, [this] { switchToLoginPage(""); });
    connect(chat_page_, &ChatPage::unreadMessages, this, &MainWindow::setWindowTitle);
    connect(chat_page_, SIGNAL(unreadMessages(int)), trayIcon_, SLOT(setUnreadCount(int)));
    connect(chat_page_, &ChatPage::showLoginPage, this, &MainWindow::switchToLoginPage);
    connect(chat_page_, &ChatPage::showNotification, this, &MainWindow::showNotification);

    connect(userSettings_.get(), &UserSettings::trayChanged, trayIcon_, &TrayIcon::setVisible);
    connect(trayIcon_,
            SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this,
            SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));

    trayIcon_->setVisible(userSettings_->tray());
    dock_ = new Dock(this);
    connect(chat_page_, SIGNAL(unreadMessages(int)), dock_, SLOT(setUnreadCount(int)));

    // load cache on event loop
    QTimer::singleShot(0, this, [this] {
        if (hasActiveUser()) {
            QString token       = userSettings_->accessToken();
            QString home_server = userSettings_->homeserver();
            QString user_id     = userSettings_->userId();
            QString device_id   = userSettings_->deviceId();

            http::client()->set_access_token(token.toStdString());
            http::client()->set_server(home_server.toStdString());
            http::client()->set_device_id(device_id.toStdString());

            try {
                using namespace mtx::identifiers;
                http::client()->set_user(parse<User>(user_id.toStdString()));
            } catch (const std::invalid_argument &) {
                nhlog::ui()->critical("bootstrapped with invalid user_id: {}",
                                      user_id.toStdString());
            }

            nhlog::ui()->info("User already signed in, showing chat page");
            showChatPage();
        }
    });
}

void
MainWindow::registerQmlTypes()
{


    qmlRegisterUncreatableMetaObject(qml_mtx_events::staticMetaObject,
                                     "im.nheko",
                                     1,
                                     0,
                                     "MtxEvent",
                                     QStringLiteral("Can't instantiate enum!"));
    qmlRegisterUncreatableMetaObject(
      olm::staticMetaObject, "im.nheko", 1, 0, "Olm", QStringLiteral("Can't instantiate enum!"));
    qmlRegisterUncreatableMetaObject(crypto::staticMetaObject,
                                     "im.nheko",
                                     1,
                                     0,
                                     "Crypto",
                                     QStringLiteral("Can't instantiate enum!"));
    qmlRegisterUncreatableMetaObject(verification::staticMetaObject,
                                     "im.nheko",
                                     1,
                                     0,
                                     "VerificationStatus",
                                     QStringLiteral("Can't instantiate enum!"));

    qmlRegisterType<DelegateChoice>("im.nheko", 1, 0, "DelegateChoice");
    qmlRegisterType<DelegateChooser>("im.nheko", 1, 0, "DelegateChooser");
    qmlRegisterType<NhekoDropArea>("im.nheko", 1, 0, "NhekoDropArea");
    qmlRegisterType<NhekoCursorShape>("im.nheko", 1, 0, "CursorShape");
    qmlRegisterType<NhekoEventObserver>("im.nheko", 1, 0, "EventObserver");
    qmlRegisterType<MxcAnimatedImage>("im.nheko", 1, 0, "MxcAnimatedImage");
    qmlRegisterType<MxcMediaProxy>("im.nheko", 1, 0, "MxcMedia");
    qmlRegisterType<RoomDirectoryModel>("im.nheko", 1, 0, "RoomDirectoryModel");
    qmlRegisterType<UserDirectoryModel>("im.nheko", 1, 0, "UserDirectoryModel");
    qmlRegisterType<LoginPage>("im.nheko", 1, 0, "Login");
    qmlRegisterType<RegisterPage>("im.nheko", 1, 0, "Registration");
    qmlRegisterType<HiddenEvents>("im.nheko", 1, 0, "HiddenEvents");
    qmlRegisterType<TimelineFilter>("im.nheko", 1, 0, "TimelineFilter");
    qmlRegisterUncreatableType<RoomSummary>(
      "im.nheko",
      1,
      0,
      "RoomSummary",
      QStringLiteral("Please use joinRoom to create a room summary."));
    qmlRegisterUncreatableType<AliasEditingModel>(
      "im.nheko",
      1,
      0,
      "AliasEditingModel",
      QStringLiteral("Please use editAliases to create the models"));

    qmlRegisterUncreatableType<PowerlevelEditingModels>(
      "im.nheko",
      1,
      0,
      "PowerlevelEditingModels",
      QStringLiteral("Please use editPowerlevels to create the models"));
    qmlRegisterUncreatableType<DeviceVerificationFlow>(
      "im.nheko",
      1,
      0,
      "DeviceVerificationFlow",
      QStringLiteral("Can't create verification flow from QML!"));
    qmlRegisterUncreatableType<UserProfile>(
      "im.nheko",
      1,
      0,
      "UserProfileModel",
      QStringLiteral("UserProfile needs to be instantiated on the C++ side"));
    qmlRegisterUncreatableType<MemberList>(
      "im.nheko",
      1,
      0,
      "MemberList",
      QStringLiteral("MemberList needs to be instantiated on the C++ side"));
    qmlRegisterUncreatableType<RoomSettings>(
      "im.nheko",
      1,
      0,
      "RoomSettingsModel",
      QStringLiteral("Room Settings needs to be instantiated on the C++ side"));
    qmlRegisterUncreatableType<TimelineModel>(
      "im.nheko", 1, 0, "Room", QStringLiteral("Room needs to be instantiated on the C++ side"));
    qmlRegisterUncreatableType<ImagePackListModel>(
      "im.nheko",
      1,
      0,
      "ImagePackListModel",
      QStringLiteral("ImagePackListModel needs to be instantiated on the C++ side"));
    qmlRegisterUncreatableType<SingleImagePackModel>(
      "im.nheko",
      1,
      0,
      "SingleImagePackModel",
      QStringLiteral("SingleImagePackModel needs to be instantiated on the C++ side"));
    qmlRegisterUncreatableType<InviteesModel>(
      "im.nheko",
      1,
      0,
      "InviteesModel",
      QStringLiteral("InviteesModel needs to be instantiated on the C++ side"));
    qmlRegisterUncreatableType<ReadReceiptsProxy>(
      "im.nheko",
      1,
      0,
      "ReadReceiptsProxy",
      QStringLiteral("ReadReceiptsProxy needs to be instantiated on the C++ side"));

    qmlRegisterSingletonType<Clipboard>(
      "im.nheko", 1, 0, "Clipboard", [](QQmlEngine *, QJSEngine *) -> QObject * {
          return new Clipboard();
      });
    qmlRegisterSingletonType<Nheko>(
      "im.nheko", 1, 0, "Nheko", [](QQmlEngine *, QJSEngine *) -> QObject * {
          return new Nheko();
      });
    qmlRegisterSingletonType<UserSettingsModel>(
      "im.nheko", 1, 0, "UserSettingsModel", [](QQmlEngine *, QJSEngine *) -> QObject * {
          return new UserSettingsModel();
      });

    qmlRegisterSingletonInstance("im.nheko", 1, 0, "Settings", userSettings_.data());


    qmlRegisterUncreatableType<FilteredCommunitiesModel>(
      "im.nheko",
      1,
      0,
      "FilteredCommunitiesModel",
      QStringLiteral("Use Communities.filtered() to create a FilteredCommunitiesModel"));

    qmlRegisterUncreatableType<MediaUpload>(
      "im.nheko", 1, 0, "MediaUpload", QStringLiteral("MediaUploads can not be created in Qml"));
    qmlRegisterUncreatableMetaObject(emoji::staticMetaObject,
                                     "im.nheko.EmojiModel",
                                     1,
                                     0,
                                     "EmojiCategory",
                                     QStringLiteral("Error: Only enums"));

    qmlRegisterType<RoomDirectoryModel>("im.nheko", 1, 0, "RoomDirectoryModel");

    qmlRegisterSingletonType<SelfVerificationStatus>(
      "im.nheko", 1, 0, "SelfVerificationStatus", [](QQmlEngine *, QJSEngine *) -> QObject * {
          auto ptr = new SelfVerificationStatus();
          QObject::connect(ChatPage::instance(),
                           &ChatPage::initializeEmptyViews,
                           ptr,
                           &SelfVerificationStatus::invalidate);
          return ptr;
      });
    qmlRegisterSingletonInstance("im.nheko", 1, 0, "MainWindow", this);
    qmlRegisterSingletonInstance("im.nheko", 1, 0, "UIA", UIA::instance());
    qmlRegisterSingletonInstance(
      "im.nheko", 1, 0, "CallManager", ChatPage::instance()->callManager());

    imgProvider = new MxcImageProvider();
    engine()->addImageProvider(QStringLiteral("MxcImage"), imgProvider);
    engine()->addImageProvider(QStringLiteral("colorimage"), new ColorImageProvider());
    engine()->addImageProvider(QStringLiteral("blurhash"), new BlurhashProvider());
    if (JdenticonProvider::isAvailable())
        engine()->addImageProvider(QStringLiteral("jdenticon"), new JdenticonProvider());

    QObject::connect(engine(), &QQmlEngine::quit, &QGuiApplication::quit);

#ifdef NHEKO_DBUS_SYS
    if (UserSettings::instance()->exposeDBusApi()) {
        if (QDBusConnection::sessionBus().isConnected() &&
            QDBusConnection::sessionBus().registerService(NHEKO_DBUS_SERVICE_NAME)) {
            nheko::dbus::init();
            nhlog::ui()->info("Initialized D-Bus");
            dbusAvailable_ = true;
        } else
            nhlog::ui()->warn("Could not connect to D-Bus!");
    }
#endif
}

void
MainWindow::setWindowTitle(int notificationCount)
{
    QString name = QStringLiteral("nheko");

    if (!userSettings_.data()->profile().isEmpty())
        name += " | " + userSettings_.data()->profile();
    if (notificationCount > 0) {
        name.append(QString{QStringLiteral(" (%1)")}.arg(notificationCount));
    }
    QQuickView::setTitle(name);
}

bool
MainWindow::event(QEvent *event)
{
    auto type = event->type();

    if (type == QEvent::Close) {
        closeEvent(static_cast<QCloseEvent *>(event));
    }

    return QQuickView::event(event);
}

// HACK: https://bugreports.qt.io/browse/QTBUG-83972, qtwayland cannot auto hide menu
void
MainWindow::mousePressEvent(QMouseEvent *event)
{
#if defined(Q_OS_LINUX)
    if (QGuiApplication::platformName() == "wayland") {
        emit hideMenu();
    }
#endif
    return QQuickView::mousePressEvent(event);
}

void
MainWindow::restoreWindowSize()
{
    int savedWidth  = userSettings_->qsettings()->value(QStringLiteral("window/width")).toInt();
    int savedheight = userSettings_->qsettings()->value(QStringLiteral("window/height")).toInt();

    nhlog::ui()->info("Restoring window size {}x{}", savedWidth, savedheight);

    if (savedWidth == 0 || savedheight == 0)
        resize(conf::window::width, conf::window::height);
    else
        resize(savedWidth, savedheight);
}

void
MainWindow::saveCurrentWindowSize()
{
    auto settings = userSettings_->qsettings();
    QSize current = size();

    settings->setValue(QStringLiteral("window/width"), current.width());
    settings->setValue(QStringLiteral("window/height"), current.height());
}

void
MainWindow::showChatPage()
{
    auto userid     = QString::fromStdString(http::client()->user_id().to_string());
    auto device_id  = QString::fromStdString(http::client()->device_id());
    auto homeserver = QString::fromStdString(http::client()->server_url());
    auto token      = QString::fromStdString(http::client()->access_token());

    userSettings_.data()->setUserId(userid);
    userSettings_.data()->setAccessToken(token);
    userSettings_.data()->setDeviceId(device_id);
    userSettings_.data()->setHomeserver(homeserver);

    chat_page_->bootstrap(userid, homeserver, token);
    connect(cache::client(), &Cache::databaseReady, this, &MainWindow::secretsChanged);
    connect(cache::client(), &Cache::secretChanged, this, &MainWindow::secretsChanged);

    emit reload();
    nhlog::ui()->info("Switching to chat page");
    emit switchToChatPage();
}

void
MainWindow::closeEvent(QCloseEvent *event)
{
    if (WebRTCSession::instance().state() != webrtc::State::DISCONNECTED) {
        if (QMessageBox::question(
              nullptr, QStringLiteral("nheko"), QStringLiteral("A call is in progress. Quit?")) !=
            QMessageBox::Yes) {
            event->ignore();
            return;
        }
    }

    if (!qApp->isSavingSession() && isVisible() && pageSupportsTray() && userSettings_->tray()) {
        event->ignore();
        hide();
    }
}

void
MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::Trigger:
        if (!isVisible()) {
            show();
        } else {
            hide();
        }
        break;
    default:
        break;
    }
}

bool
MainWindow::hasActiveUser()
{
    auto settings = userSettings_->qsettings();
    QString prefix;
    if (userSettings_->profile() != QLatin1String(""))
        prefix = "profile/" + userSettings_->profile() + "/";

    return settings->contains(prefix + "auth/access_token") &&
           settings->contains(prefix + "auth/home_server") &&
           settings->contains(prefix + "auth/user_id");
}

bool
MainWindow::pageSupportsTray() const
{
    return !http::client()->access_token().empty();
}

inline void
MainWindow::showDialog(QWidget *dialog)
{
    dialog->setWindowFlags(Qt::WindowType::Dialog | Qt::WindowType::WindowCloseButtonHint |
                           Qt::WindowType::WindowTitleHint);
    dialog->raise();
    dialog->show();
    utils::centerWidget(dialog, this);
    dialog->window()->windowHandle()->setTransientParent(this);
}

void
MainWindow::addPerRoomWindow(const QString &room, QWindow *window)
{
    roomWindows_.insert(room, window);
}
void
MainWindow::removePerRoomWindow(const QString &room, QWindow *window)
{
    roomWindows_.remove(room, window);
}
QWindow *
MainWindow::windowForRoom(const QString &room)
{
    auto currMainWindowRoom = ChatPage::instance()->timelineManager()->rooms()->currentRoom();
    if ((currMainWindowRoom && currMainWindowRoom->roomId() == room) ||
        ChatPage::instance()->timelineManager()->rooms()->currentRoomPreview().roomid_ == room)
        return this;
    else if (auto res = roomWindows_.find(room); res != roomWindows_.end())
        return res.value();
    return nullptr;
}

QString
MainWindow::focusedRoom() const
{
    auto focus = QGuiApplication::focusWindow();
    if (!focus)
        return {};

    if (focus == this) {
        auto currMainWindowRoom = ChatPage::instance()->timelineManager()->rooms()->currentRoom();
        if (currMainWindowRoom)
            return currMainWindowRoom->roomId();
        else
            return ChatPage::instance()->timelineManager()->rooms()->currentRoomPreview().roomid_;
    }

    auto i = roomWindows_.constBegin();
    while (i != roomWindows_.constEnd()) {
        if (i.value() == focus)
            return i.key();
        ++i;
    }

    return nullptr;
}