Replace shared pointers of MatrixClient with a single instance

This commit is contained in:
Konstantinos Sideris 2018-05-08 18:43:56 +03:00
parent ffb43836e4
commit 4c4ea557b3
31 changed files with 196 additions and 269 deletions

View file

@ -4,6 +4,7 @@ if(CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR CMAKE_CXX_COMPILER_ID MATCHES "GNU")
-Wextra \ -Wextra \
-Werror \ -Werror \
-pipe \ -pipe \
-Wno-unused-function \
-pedantic \ -pedantic \
-Wunreachable-code") -Wunreachable-code")

View file

@ -22,7 +22,6 @@
#include <QSharedPointer> #include <QSharedPointer>
#include <functional> #include <functional>
class MatrixClient;
class TimelineItem; class TimelineItem;
class Cache; class Cache;
@ -31,11 +30,7 @@ class AvatarProvider : public QObject
Q_OBJECT Q_OBJECT
public: public:
static void init(QSharedPointer<MatrixClient> client, QSharedPointer<Cache> cache) static void init(QSharedPointer<Cache> cache) { cache_ = cache; }
{
client_ = client;
cache_ = cache;
}
//! The callback is called with the downloaded avatar for the given user //! The callback is called with the downloaded avatar for the given user
//! or the avatar is downloaded first and then saved for re-use. //! or the avatar is downloaded first and then saved for re-use.
static void resolve(const QString &room_id, static void resolve(const QString &room_id,
@ -44,6 +39,5 @@ public:
std::function<void(QImage)> callback); std::function<void(QImage)> callback);
private: private:
static QSharedPointer<MatrixClient> client_;
static QSharedPointer<Cache> cache_; static QSharedPointer<Cache> cache_;
}; };

View file

@ -30,7 +30,6 @@
#include <mtx.hpp> #include <mtx.hpp>
class MatrixClient;
class OverlayModal; class OverlayModal;
class QuickSwitcher; class QuickSwitcher;
class RoomList; class RoomList;
@ -59,9 +58,7 @@ class ChatPage : public QWidget
Q_OBJECT Q_OBJECT
public: public:
ChatPage(QSharedPointer<MatrixClient> client, ChatPage(QSharedPointer<UserSettings> userSettings, QWidget *parent = 0);
QSharedPointer<UserSettings> userSettings,
QWidget *parent = 0);
// Initialize all the components of the UI. // Initialize all the components of the UI.
void bootstrap(QString userid, QString homeserver, QString token); void bootstrap(QString userid, QString homeserver, QString token);
@ -70,14 +67,6 @@ public:
QString currentRoom() const { return current_room_; } QString currentRoom() const { return current_room_; }
static ChatPage *instance() { return instance_; } static ChatPage *instance() { return instance_; }
void readEvent(const QString &room_id, const QString &event_id)
{
client_->readEvent(room_id, event_id);
}
void redactEvent(const QString &room_id, const QString &event_id)
{
client_->redactEvent(room_id, event_id);
}
QSharedPointer<UserSettings> userSettings() { return userSettings_; } QSharedPointer<UserSettings> userSettings() { return userSettings_; }
QSharedPointer<Cache> cache() { return cache_; } QSharedPointer<Cache> cache() { return cache_; }
@ -192,9 +181,6 @@ private:
QSharedPointer<dialogs::ReadReceipts> receiptsDialog_; QSharedPointer<dialogs::ReadReceipts> receiptsDialog_;
QSharedPointer<OverlayModal> receiptsModal_; QSharedPointer<OverlayModal> receiptsModal_;
// Matrix Client API provider.
QSharedPointer<MatrixClient> client_;
// Global user settings. // Global user settings.
QSharedPointer<UserSettings> userSettings_; QSharedPointer<UserSettings> userSettings_;

View file

@ -6,7 +6,6 @@
#include "CommunitiesListItem.h" #include "CommunitiesListItem.h"
#include "Community.h" #include "Community.h"
#include "MatrixClient.h"
#include "ui/Theme.h" #include "ui/Theme.h"
class CommunitiesList : public QWidget class CommunitiesList : public QWidget
@ -14,7 +13,7 @@ class CommunitiesList : public QWidget
Q_OBJECT Q_OBJECT
public: public:
CommunitiesList(QSharedPointer<MatrixClient> client, QWidget *parent = nullptr); CommunitiesList(QWidget *parent = nullptr);
void setCommunities(const std::map<QString, QSharedPointer<Community>> &communities); void setCommunities(const std::map<QString, QSharedPointer<Community>> &communities);
void clear() { communities_.clear(); } void clear() { communities_.clear(); }
@ -44,6 +43,4 @@ private:
QScrollArea *scrollArea_; QScrollArea *scrollArea_;
std::map<QString, QSharedPointer<CommunitiesListItem>> communities_; std::map<QString, QSharedPointer<CommunitiesListItem>> communities_;
QSharedPointer<MatrixClient> client_;
}; };

View file

@ -24,7 +24,6 @@
class FlatButton; class FlatButton;
class LoadingIndicator; class LoadingIndicator;
class MatrixClient;
class OverlayModal; class OverlayModal;
class RaisedButton; class RaisedButton;
class TextField; class TextField;
@ -34,7 +33,7 @@ class LoginPage : public QWidget
Q_OBJECT Q_OBJECT
public: public:
LoginPage(QSharedPointer<MatrixClient> client, QWidget *parent = 0); LoginPage(QWidget *parent = 0);
void reset(); void reset();
@ -97,7 +96,4 @@ private:
TextField *matrixid_input_; TextField *matrixid_input_;
TextField *password_input_; TextField *password_input_;
TextField *serverInput_; TextField *serverInput_;
// Matrix client API provider.
QSharedPointer<MatrixClient> client_;
}; };

View file

@ -31,7 +31,6 @@
class ChatPage; class ChatPage;
class LoadingIndicator; class LoadingIndicator;
class MatrixClient;
class OverlayModal; class OverlayModal;
class SnackBar; class SnackBar;
class TrayIcon; class TrayIcon;
@ -125,8 +124,6 @@ private:
//! Used to hide undefined states between page transitions. //! Used to hide undefined states between page transitions.
QSharedPointer<OverlayModal> progressModal_; QSharedPointer<OverlayModal> progressModal_;
QSharedPointer<LoadingIndicator> spinner_; QSharedPointer<LoadingIndicator> spinner_;
//! Matrix Client API provider.
QSharedPointer<MatrixClient> client_;
//! Tray icon that shows the unread message count. //! Tray icon that shows the unread message count.
TrayIcon *trayIcon_; TrayIcon *trayIcon_;
//! Notifications display. //! Notifications display.

View file

@ -43,7 +43,7 @@ class MatrixClient : public QNetworkAccessManager
{ {
Q_OBJECT Q_OBJECT
public: public:
MatrixClient(QString server, QObject *parent = 0); MatrixClient(QObject *parent = 0);
// Client API. // Client API.
void initialSync() noexcept; void initialSync() noexcept;
@ -211,3 +211,13 @@ private:
//! Filter to be send as filter-param for (initial) /sync requests. //! Filter to be send as filter-param for (initial) /sync requests.
QString filter_; QString filter_;
}; };
namespace http {
//! Initialize the http module
void
init(QObject *parent);
//! Retrieve the client instance.
MatrixClient *
client();
}

View file

@ -23,7 +23,6 @@
#include <memory> #include <memory>
class FlatButton; class FlatButton;
class MatrixClient;
class RaisedButton; class RaisedButton;
class TextField; class TextField;
@ -36,7 +35,7 @@ class RegisterPage : public QWidget
Q_OBJECT Q_OBJECT
public: public:
RegisterPage(QSharedPointer<MatrixClient> client, QWidget *parent = 0); RegisterPage(QWidget *parent = 0);
protected: protected:
void paintEvent(QPaintEvent *event) override; void paintEvent(QPaintEvent *event) override;
@ -75,8 +74,6 @@ private:
TextField *password_confirmation_; TextField *password_confirmation_;
TextField *server_input_; TextField *server_input_;
// Matrix client API provider.
QSharedPointer<MatrixClient> client_;
//! ReCaptcha dialog. //! ReCaptcha dialog.
std::shared_ptr<dialogs::ReCaptcha> captchaDialog_; std::shared_ptr<dialogs::ReCaptcha> captchaDialog_;
}; };

View file

@ -26,7 +26,6 @@
#include <mtx.hpp> #include <mtx.hpp>
class LeaveRoomDialog; class LeaveRoomDialog;
class MatrixClient;
class OverlayModal; class OverlayModal;
class RoomInfoListItem; class RoomInfoListItem;
class Sync; class Sync;
@ -40,9 +39,7 @@ class RoomList : public QWidget
Q_OBJECT Q_OBJECT
public: public:
RoomList(QSharedPointer<MatrixClient> client, RoomList(QSharedPointer<UserSettings> userSettings, QWidget *parent = 0);
QSharedPointer<UserSettings> userSettings,
QWidget *parent = 0);
void setCache(QSharedPointer<Cache> cache) { cache_ = cache; } void setCache(QSharedPointer<Cache> cache) { cache_ = cache; }
void initialize(const QMap<QString, RoomInfo> &info); void initialize(const QMap<QString, RoomInfo> &info);
@ -105,7 +102,6 @@ private:
//! Which rooms to include in the room list. //! Which rooms to include in the room list.
std::vector<QString> roomFilter_; std::vector<QString> roomFilter_;
QSharedPointer<MatrixClient> client_;
QSharedPointer<Cache> cache_; QSharedPointer<Cache> cache_;
QSharedPointer<UserSettings> userSettings_; QSharedPointer<UserSettings> userSettings_;

View file

@ -26,11 +26,11 @@
#include <QStyleOption> #include <QStyleOption>
#include "AvatarProvider.h" #include "AvatarProvider.h"
#include "ChatPage.h"
#include "RoomInfoListItem.h" #include "RoomInfoListItem.h"
#include "Utils.h" #include "Utils.h"
#include "Cache.h" #include "Cache.h"
#include "MatrixClient.h"
class ImageItem; class ImageItem;
class StickerItem; class StickerItem;
@ -121,7 +121,7 @@ public:
void sendReadReceipt() const void sendReadReceipt() const
{ {
if (!event_id_.isEmpty()) if (!event_id_.isEmpty())
ChatPage::instance()->readEvent(room_id_, event_id_); http::client()->readEvent(room_id_, event_id_);
} }
//! Add a user avatar for this event. //! Add a user avatar for this event.

View file

@ -25,6 +25,7 @@
#include <QScrollArea> #include <QScrollArea>
#include <QStyle> #include <QStyle>
#include <QStyleOption> #include <QStyleOption>
#include <QTimer>
#include <mtx/events.hpp> #include <mtx/events.hpp>
#include <mtx/responses/messages.hpp> #include <mtx/responses/messages.hpp>
@ -117,12 +118,9 @@ class TimelineView : public QWidget
public: public:
TimelineView(const mtx::responses::Timeline &timeline, TimelineView(const mtx::responses::Timeline &timeline,
QSharedPointer<MatrixClient> client,
const QString &room_id,
QWidget *parent = 0);
TimelineView(QSharedPointer<MatrixClient> client,
const QString &room_id, const QString &room_id,
QWidget *parent = 0); QWidget *parent = 0);
TimelineView(const QString &room_id, QWidget *parent = 0);
// Add new events at the end of the timeline. // Add new events at the end of the timeline.
void addEvents(const mtx::responses::Timeline &timeline); void addEvents(const mtx::responses::Timeline &timeline);
@ -298,7 +296,6 @@ private:
QMap<QString, TimelineItem *> eventIds_; QMap<QString, TimelineItem *> eventIds_;
QQueue<PendingMessage> pending_msgs_; QQueue<PendingMessage> pending_msgs_;
QList<PendingMessage> pending_sent_msgs_; QList<PendingMessage> pending_sent_msgs_;
QSharedPointer<MatrixClient> client_;
}; };
template<class Widget, mtx::events::MessageType MsgType> template<class Widget, mtx::events::MessageType MsgType>
@ -311,7 +308,7 @@ TimelineView::addUserMessage(const QString &url,
auto with_sender = (lastSender_ != local_user_) || isDateDifference(lastMsgTimestamp_); auto with_sender = (lastSender_ != local_user_) || isDateDifference(lastMsgTimestamp_);
auto trimmed = QFileInfo{filename}.fileName(); // Trim file path. auto trimmed = QFileInfo{filename}.fileName(); // Trim file path.
auto widget = new Widget(client_, url, trimmed, size, this); auto widget = new Widget(url, trimmed, size, this);
TimelineItem *view_item = TimelineItem *view_item =
new TimelineItem(widget, local_user_, with_sender, room_id_, scroll_widget_); new TimelineItem(widget, local_user_, with_sender, room_id_, scroll_widget_);
@ -325,7 +322,7 @@ TimelineView::addUserMessage(const QString &url,
// Keep track of the sender and the timestamp of the current message. // Keep track of the sender and the timestamp of the current message.
saveLastMessageInfo(local_user_, QDateTime::currentDateTime()); saveLastMessageInfo(local_user_, QDateTime::currentDateTime());
int txn_id = client_->incrementTransactionId(); int txn_id = http::client()->incrementTransactionId();
PendingMessage message(MsgType, txn_id, url, trimmed, mime, size, "", view_item); PendingMessage message(MsgType, txn_id, url, trimmed, mime, size, "", view_item);
handleNewUserMessage(message); handleNewUserMessage(message);
@ -343,7 +340,7 @@ template<class Event, class Widget>
TimelineItem * TimelineItem *
TimelineView::createTimelineItem(const Event &event, bool withSender) TimelineView::createTimelineItem(const Event &event, bool withSender)
{ {
auto eventWidget = new Widget(client_, event); auto eventWidget = new Widget(event);
auto item = new TimelineItem(eventWidget, event, withSender, room_id_, scroll_widget_); auto item = new TimelineItem(eventWidget, event, withSender, room_id_, scroll_widget_);
return item; return item;

View file

@ -24,7 +24,6 @@
class QFile; class QFile;
class MatrixClient;
class RoomInfoListItem; class RoomInfoListItem;
class TimelineView; class TimelineView;
struct DescInfo; struct DescInfo;
@ -34,7 +33,7 @@ class TimelineViewManager : public QStackedWidget
Q_OBJECT Q_OBJECT
public: public:
TimelineViewManager(QSharedPointer<MatrixClient> client, QWidget *parent); TimelineViewManager(QWidget *parent);
// Initialize with timeline events. // Initialize with timeline events.
void initialize(const mtx::responses::Rooms &rooms); void initialize(const mtx::responses::Rooms &rooms);
@ -91,5 +90,4 @@ private:
QString active_room_; QString active_room_;
std::map<QString, QSharedPointer<TimelineView>> views_; std::map<QString, QSharedPointer<TimelineView>> views_;
QSharedPointer<MatrixClient> client_;
}; };

View file

@ -24,8 +24,6 @@
#include <QSharedPointer> #include <QSharedPointer>
#include <QWidget> #include <QWidget>
#include "MatrixClient.h"
#include <mtx.hpp> #include <mtx.hpp>
class AudioItem : public QWidget class AudioItem : public QWidget
@ -42,12 +40,10 @@ class AudioItem : public QWidget
durationForegroundColor) durationForegroundColor)
public: public:
AudioItem(QSharedPointer<MatrixClient> client, AudioItem(const mtx::events::RoomEvent<mtx::events::msg::Audio> &event,
const mtx::events::RoomEvent<mtx::events::msg::Audio> &event,
QWidget *parent = nullptr); QWidget *parent = nullptr);
AudioItem(QSharedPointer<MatrixClient> client, AudioItem(const QString &url,
const QString &url,
const QString &filename, const QString &filename,
uint64_t size, uint64_t size,
QWidget *parent = nullptr); QWidget *parent = nullptr);
@ -90,7 +86,6 @@ private:
QString filenameToSave_; QString filenameToSave_;
mtx::events::RoomEvent<mtx::events::msg::Audio> event_; mtx::events::RoomEvent<mtx::events::msg::Audio> event_;
QSharedPointer<MatrixClient> client_;
QMediaPlayer *player_; QMediaPlayer *player_;

View file

@ -25,8 +25,6 @@
#include <mtx.hpp> #include <mtx.hpp>
#include "MatrixClient.h"
class FileItem : public QWidget class FileItem : public QWidget
{ {
Q_OBJECT Q_OBJECT
@ -36,12 +34,10 @@ class FileItem : public QWidget
Q_PROPERTY(QColor backgroundColor WRITE setBackgroundColor READ backgroundColor) Q_PROPERTY(QColor backgroundColor WRITE setBackgroundColor READ backgroundColor)
public: public:
FileItem(QSharedPointer<MatrixClient> client, FileItem(const mtx::events::RoomEvent<mtx::events::msg::File> &event,
const mtx::events::RoomEvent<mtx::events::msg::File> &event,
QWidget *parent = nullptr); QWidget *parent = nullptr);
FileItem(QSharedPointer<MatrixClient> client, FileItem(const QString &url,
const QString &url,
const QString &filename, const QString &filename,
uint64_t size, uint64_t size,
QWidget *parent = nullptr); QWidget *parent = nullptr);
@ -71,7 +67,6 @@ private:
QString filenameToSave_; QString filenameToSave_;
mtx::events::RoomEvent<mtx::events::msg::File> event_; mtx::events::RoomEvent<mtx::events::msg::File> event_;
QSharedPointer<MatrixClient> client_;
QIcon icon_; QIcon icon_;

View file

@ -24,8 +24,6 @@
#include <mtx.hpp> #include <mtx.hpp>
#include "MatrixClient.h"
namespace dialogs { namespace dialogs {
class ImageOverlay; class ImageOverlay;
} }
@ -34,12 +32,10 @@ class ImageItem : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
ImageItem(QSharedPointer<MatrixClient> client, ImageItem(const mtx::events::RoomEvent<mtx::events::msg::Image> &event,
const mtx::events::RoomEvent<mtx::events::msg::Image> &event,
QWidget *parent = nullptr); QWidget *parent = nullptr);
ImageItem(QSharedPointer<MatrixClient> client, ImageItem(const QString &url,
const QString &url,
const QString &filename, const QString &filename,
uint64_t size, uint64_t size,
QWidget *parent = nullptr); QWidget *parent = nullptr);
@ -81,8 +77,6 @@ private:
QRectF imageRegion_; QRectF imageRegion_;
mtx::events::RoomEvent<mtx::events::msg::Image> event_; mtx::events::RoomEvent<mtx::events::msg::Image> event_;
QSharedPointer<MatrixClient> client_;
}; };
class StickerItem : public ImageItem class StickerItem : public ImageItem
@ -90,11 +84,8 @@ class StickerItem : public ImageItem
Q_OBJECT Q_OBJECT
public: public:
StickerItem(QSharedPointer<MatrixClient> client, StickerItem(const mtx::events::Sticker &event, QWidget *parent = nullptr)
const mtx::events::Sticker &event, : ImageItem{QString::fromStdString(event.content.url),
QWidget *parent = nullptr)
: ImageItem{client,
QString::fromStdString(event.content.url),
QString::fromStdString(event.content.body), QString::fromStdString(event.content.body),
event.content.info.size, event.content.info.size,
parent} parent}

View file

@ -20,10 +20,9 @@
#include <QEvent> #include <QEvent>
#include <QLabel> #include <QLabel>
#include <QSharedPointer> #include <QSharedPointer>
#include <QUrl>
#include <QWidget> #include <QWidget>
#include "MatrixClient.h"
#include <mtx.hpp> #include <mtx.hpp>
class VideoItem : public QWidget class VideoItem : public QWidget
@ -31,12 +30,10 @@ class VideoItem : public QWidget
Q_OBJECT Q_OBJECT
public: public:
VideoItem(QSharedPointer<MatrixClient> client, VideoItem(const mtx::events::RoomEvent<mtx::events::msg::Video> &event,
const mtx::events::RoomEvent<mtx::events::msg::Video> &event,
QWidget *parent = nullptr); QWidget *parent = nullptr);
VideoItem(QSharedPointer<MatrixClient> client, VideoItem(const QString &url,
const QString &url,
const QString &filename, const QString &filename,
uint64_t size, uint64_t size,
QWidget *parent = nullptr); QWidget *parent = nullptr);
@ -51,5 +48,4 @@ private:
QLabel *label_; QLabel *label_;
mtx::events::RoomEvent<mtx::events::msg::Video> event_; mtx::events::RoomEvent<mtx::events::msg::Video> event_;
QSharedPointer<MatrixClient> client_;
}; };

View file

@ -22,7 +22,6 @@
#include "Cache.h" #include "Cache.h"
#include "MatrixClient.h" #include "MatrixClient.h"
QSharedPointer<MatrixClient> AvatarProvider::client_;
QSharedPointer<Cache> AvatarProvider::cache_; QSharedPointer<Cache> AvatarProvider::cache_;
void void
@ -46,7 +45,7 @@ AvatarProvider::resolve(const QString &room_id,
return; return;
} }
auto proxy = client_->fetchUserAvatar(avatarUrl); auto proxy = http::client()->fetchUserAvatar(avatarUrl);
if (proxy.isNull()) if (proxy.isNull())
return; return;

View file

@ -48,11 +48,8 @@ constexpr int INITIAL_SYNC_RETRY_TIMEOUT = 240 * 1000;
ChatPage *ChatPage::instance_ = nullptr; ChatPage *ChatPage::instance_ = nullptr;
ChatPage::ChatPage(QSharedPointer<MatrixClient> client, ChatPage::ChatPage(QSharedPointer<UserSettings> userSettings, QWidget *parent)
QSharedPointer<UserSettings> userSettings,
QWidget *parent)
: QWidget(parent) : QWidget(parent)
, client_(client)
, userSettings_{userSettings} , userSettings_{userSettings}
{ {
setObjectName("chatPage"); setObjectName("chatPage");
@ -61,7 +58,7 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
topLayout_->setSpacing(0); topLayout_->setSpacing(0);
topLayout_->setMargin(0); topLayout_->setMargin(0);
communitiesList_ = new CommunitiesList(client, this); communitiesList_ = new CommunitiesList(this);
topLayout_->addWidget(communitiesList_); topLayout_->addWidget(communitiesList_);
auto splitter = new Splitter(this); auto splitter = new Splitter(this);
@ -82,12 +79,12 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
connect( connect(
sidebarActions_, &SideBarActions::showSettings, this, &ChatPage::showUserSettingsPage); sidebarActions_, &SideBarActions::showSettings, this, &ChatPage::showUserSettingsPage);
connect( connect(
sidebarActions_, &SideBarActions::joinRoom, client_.data(), &MatrixClient::joinRoom); sidebarActions_, &SideBarActions::joinRoom, http::client(), &MatrixClient::joinRoom);
connect( connect(
sidebarActions_, &SideBarActions::createRoom, client_.data(), &MatrixClient::createRoom); sidebarActions_, &SideBarActions::createRoom, http::client(), &MatrixClient::createRoom);
user_info_widget_ = new UserInfoWidget(sideBar_); user_info_widget_ = new UserInfoWidget(sideBar_);
room_list_ = new RoomList(client, userSettings_, sideBar_); room_list_ = new RoomList(userSettings_, sideBar_);
sideBarLayout_->addWidget(user_info_widget_); sideBarLayout_->addWidget(user_info_widget_);
sideBarLayout_->addWidget(room_list_); sideBarLayout_->addWidget(room_list_);
@ -105,7 +102,7 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
contentLayout_->setMargin(0); contentLayout_->setMargin(0);
top_bar_ = new TopRoomBar(this); top_bar_ = new TopRoomBar(this);
view_manager_ = new TimelineViewManager(client, this); view_manager_ = new TimelineViewManager(this);
contentLayout_->addWidget(top_bar_); contentLayout_->addWidget(top_bar_);
contentLayout_->addWidget(view_manager_); contentLayout_->addWidget(view_manager_);
@ -124,15 +121,15 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
typingRefresher_->setInterval(TYPING_REFRESH_TIMEOUT); typingRefresher_->setInterval(TYPING_REFRESH_TIMEOUT);
connect(user_info_widget_, &UserInfoWidget::logout, this, [this]() { connect(user_info_widget_, &UserInfoWidget::logout, this, [this]() {
client_->logout(); http::client()->logout();
emit showOverlayProgressBar(); emit showOverlayProgressBar();
}); });
connect(client_.data(), &MatrixClient::loggedOut, this, &ChatPage::logout); connect(http::client(), &MatrixClient::loggedOut, this, &ChatPage::logout);
connect(top_bar_, &TopRoomBar::inviteUsers, this, [this](QStringList users) { connect(top_bar_, &TopRoomBar::inviteUsers, this, [this](QStringList users) {
for (int ii = 0; ii < users.size(); ++ii) { for (int ii = 0; ii < users.size(); ++ii) {
QTimer::singleShot(ii * 1000, this, [this, ii, users]() { QTimer::singleShot(ii * 1000, this, [this, ii, users]() {
client_->inviteUser(current_room_, users.at(ii)); http::client()->inviteUser(current_room_, users.at(ii));
}); });
} }
}); });
@ -158,12 +155,12 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
connect(room_list_, &RoomList::acceptInvite, this, [this](const QString &room_id) { connect(room_list_, &RoomList::acceptInvite, this, [this](const QString &room_id) {
view_manager_->addRoom(room_id); view_manager_->addRoom(room_id);
client_->joinRoom(room_id); http::client()->joinRoom(room_id);
room_list_->removeRoom(room_id, currentRoom() == room_id); room_list_->removeRoom(room_id, currentRoom() == room_id);
}); });
connect(room_list_, &RoomList::declineInvite, this, [this](const QString &room_id) { connect(room_list_, &RoomList::declineInvite, this, [this](const QString &room_id) {
client_->leaveRoom(room_id); http::client()->leaveRoom(room_id);
room_list_->removeRoom(room_id, currentRoom() == room_id); room_list_->removeRoom(room_id, currentRoom() == room_id);
}); });
@ -172,7 +169,7 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
return; return;
typingRefresher_->start(); typingRefresher_->start();
client_->sendTypingNotification(current_room_); http::client()->sendTypingNotification(current_room_);
}); });
connect(text_input_, &TextInputWidget::stoppedTyping, this, [this]() { connect(text_input_, &TextInputWidget::stoppedTyping, this, [this]() {
@ -180,14 +177,14 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
return; return;
typingRefresher_->stop(); typingRefresher_->stop();
client_->removeTypingNotification(current_room_); http::client()->removeTypingNotification(current_room_);
}); });
connect(typingRefresher_, &QTimer::timeout, this, [this]() { connect(typingRefresher_, &QTimer::timeout, this, [this]() {
if (!userSettings_->isTypingNotificationsEnabled()) if (!userSettings_->isTypingNotificationsEnabled())
return; return;
client_->sendTypingNotification(current_room_); http::client()->sendTypingNotification(current_room_);
}); });
connect(view_manager_, connect(view_manager_,
@ -212,45 +209,45 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
connect(text_input_, connect(text_input_,
&TextInputWidget::sendJoinRoomRequest, &TextInputWidget::sendJoinRoomRequest,
client_.data(), http::client(),
&MatrixClient::joinRoom); &MatrixClient::joinRoom);
connect(text_input_, connect(text_input_,
&TextInputWidget::uploadImage, &TextInputWidget::uploadImage,
this, this,
[this](QSharedPointer<QIODevice> data, const QString &fn) { [this](QSharedPointer<QIODevice> data, const QString &fn) {
client_->uploadImage(current_room_, fn, data); http::client()->uploadImage(current_room_, fn, data);
}); });
connect(text_input_, connect(text_input_,
&TextInputWidget::uploadFile, &TextInputWidget::uploadFile,
this, this,
[this](QSharedPointer<QIODevice> data, const QString &fn) { [this](QSharedPointer<QIODevice> data, const QString &fn) {
client_->uploadFile(current_room_, fn, data); http::client()->uploadFile(current_room_, fn, data);
}); });
connect(text_input_, connect(text_input_,
&TextInputWidget::uploadAudio, &TextInputWidget::uploadAudio,
this, this,
[this](QSharedPointer<QIODevice> data, const QString &fn) { [this](QSharedPointer<QIODevice> data, const QString &fn) {
client_->uploadAudio(current_room_, fn, data); http::client()->uploadAudio(current_room_, fn, data);
}); });
connect(text_input_, connect(text_input_,
&TextInputWidget::uploadVideo, &TextInputWidget::uploadVideo,
this, this,
[this](QSharedPointer<QIODevice> data, const QString &fn) { [this](QSharedPointer<QIODevice> data, const QString &fn) {
client_->uploadVideo(current_room_, fn, data); http::client()->uploadVideo(current_room_, fn, data);
}); });
connect( connect(
client_.data(), &MatrixClient::roomCreationFailed, this, &ChatPage::showNotification); http::client(), &MatrixClient::roomCreationFailed, this, &ChatPage::showNotification);
connect(client_.data(), &MatrixClient::joinFailed, this, &ChatPage::showNotification); connect(http::client(), &MatrixClient::joinFailed, this, &ChatPage::showNotification);
connect(client_.data(), &MatrixClient::uploadFailed, this, [this](int, const QString &msg) { connect(http::client(), &MatrixClient::uploadFailed, this, [this](int, const QString &msg) {
text_input_->hideUploadSpinner(); text_input_->hideUploadSpinner();
emit showNotification(msg); emit showNotification(msg);
}); });
connect( connect(
client_.data(), http::client(),
&MatrixClient::imageUploaded, &MatrixClient::imageUploaded,
this, this,
[this](QString roomid, QString filename, QString url, QString mime, uint64_t dsize) { [this](QString roomid, QString filename, QString url, QString mime, uint64_t dsize) {
@ -258,7 +255,7 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
view_manager_->queueImageMessage(roomid, filename, url, mime, dsize); view_manager_->queueImageMessage(roomid, filename, url, mime, dsize);
}); });
connect( connect(
client_.data(), http::client(),
&MatrixClient::fileUploaded, &MatrixClient::fileUploaded,
this, this,
[this](QString roomid, QString filename, QString url, QString mime, uint64_t dsize) { [this](QString roomid, QString filename, QString url, QString mime, uint64_t dsize) {
@ -266,7 +263,7 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
view_manager_->queueFileMessage(roomid, filename, url, mime, dsize); view_manager_->queueFileMessage(roomid, filename, url, mime, dsize);
}); });
connect( connect(
client_.data(), http::client(),
&MatrixClient::audioUploaded, &MatrixClient::audioUploaded,
this, this,
[this](QString roomid, QString filename, QString url, QString mime, uint64_t dsize) { [this](QString roomid, QString filename, QString url, QString mime, uint64_t dsize) {
@ -274,7 +271,7 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
view_manager_->queueAudioMessage(roomid, filename, url, mime, dsize); view_manager_->queueAudioMessage(roomid, filename, url, mime, dsize);
}); });
connect( connect(
client_.data(), http::client(),
&MatrixClient::videoUploaded, &MatrixClient::videoUploaded,
this, this,
[this](QString roomid, QString filename, QString url, QString mime, uint64_t dsize) { [this](QString roomid, QString filename, QString url, QString mime, uint64_t dsize) {
@ -284,28 +281,28 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
connect(room_list_, &RoomList::roomAvatarChanged, this, &ChatPage::updateTopBarAvatar); connect(room_list_, &RoomList::roomAvatarChanged, this, &ChatPage::updateTopBarAvatar);
connect(client_.data(), connect(http::client(),
&MatrixClient::initialSyncCompleted, &MatrixClient::initialSyncCompleted,
this, this,
&ChatPage::initialSyncCompleted); &ChatPage::initialSyncCompleted);
connect( connect(
client_.data(), &MatrixClient::initialSyncFailed, this, &ChatPage::retryInitialSync); http::client(), &MatrixClient::initialSyncFailed, this, &ChatPage::retryInitialSync);
connect(client_.data(), &MatrixClient::syncCompleted, this, &ChatPage::syncCompleted); connect(http::client(), &MatrixClient::syncCompleted, this, &ChatPage::syncCompleted);
connect(client_.data(), connect(http::client(),
&MatrixClient::getOwnProfileResponse, &MatrixClient::getOwnProfileResponse,
this, this,
&ChatPage::updateOwnProfileInfo); &ChatPage::updateOwnProfileInfo);
connect(client_.data(), connect(http::client(),
SIGNAL(getOwnCommunitiesResponse(QList<QString>)), SIGNAL(getOwnCommunitiesResponse(QList<QString>)),
this, this,
SLOT(updateOwnCommunitiesInfo(QList<QString>))); SLOT(updateOwnCommunitiesInfo(QList<QString>)));
connect(client_.data(), connect(http::client(),
&MatrixClient::communityProfileRetrieved, &MatrixClient::communityProfileRetrieved,
this, this,
[this](QString communityId, QJsonObject profile) { [this](QString communityId, QJsonObject profile) {
communities_[communityId]->parseProfile(profile); communities_[communityId]->parseProfile(profile);
}); });
connect(client_.data(), connect(http::client(),
&MatrixClient::communityRoomsRetrieved, &MatrixClient::communityRoomsRetrieved,
this, this,
[this](QString communityId, QJsonObject rooms) { [this](QString communityId, QJsonObject rooms) {
@ -321,7 +318,7 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
} }
}); });
connect(client_.data(), &MatrixClient::joinedRoom, this, [this](const QString &room_id) { connect(http::client(), &MatrixClient::joinedRoom, this, [this](const QString &room_id) {
emit showNotification("You joined the room."); emit showNotification("You joined the room.");
// We remove any invites with the same room_id. // We remove any invites with the same room_id.
@ -332,17 +329,17 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
.arg(QString::fromStdString(e.what()))); .arg(QString::fromStdString(e.what())));
} }
}); });
connect(client_.data(), &MatrixClient::leftRoom, this, &ChatPage::removeRoom); connect(http::client(), &MatrixClient::leftRoom, this, &ChatPage::removeRoom);
connect(client_.data(), &MatrixClient::invitedUser, this, [this](QString, QString user) { connect(http::client(), &MatrixClient::invitedUser, this, [this](QString, QString user) {
emit showNotification(QString("Invited user %1").arg(user)); emit showNotification(QString("Invited user %1").arg(user));
}); });
connect(client_.data(), &MatrixClient::roomCreated, this, [this](QString room_id) { connect(http::client(), &MatrixClient::roomCreated, this, [this](QString room_id) {
emit showNotification(QString("Room %1 created").arg(room_id)); emit showNotification(QString("Room %1 created").arg(room_id));
}); });
connect(client_.data(), &MatrixClient::redactionFailed, this, [this](const QString &error) { connect(http::client(), &MatrixClient::redactionFailed, this, [this](const QString &error) {
emit showNotification(QString("Message redaction failed: %1").arg(error)); emit showNotification(QString("Message redaction failed: %1").arg(error));
}); });
connect(client_.data(), connect(http::client(),
&MatrixClient::notificationsRetrieved, &MatrixClient::notificationsRetrieved,
this, this,
&ChatPage::sendDesktopNotifications); &ChatPage::sendDesktopNotifications);
@ -369,13 +366,13 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
syncTimeoutTimer_ = new QTimer(this); syncTimeoutTimer_ = new QTimer(this);
connect(syncTimeoutTimer_, &QTimer::timeout, this, [this]() { connect(syncTimeoutTimer_, &QTimer::timeout, this, [this]() {
if (client_->getHomeServer().isEmpty()) { if (http::client()->getHomeServer().isEmpty()) {
syncTimeoutTimer_->stop(); syncTimeoutTimer_->stop();
return; return;
} }
qDebug() << "Sync took too long. Retrying..."; qDebug() << "Sync took too long. Retrying...";
client_->sync(); http::client()->sync();
}); });
connect(communitiesList_, connect(communitiesList_,
@ -399,8 +396,8 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
connect(this, &ChatPage::continueSync, this, [this](const QString &next_batch) { connect(this, &ChatPage::continueSync, this, [this](const QString &next_batch) {
syncTimeoutTimer_->start(SYNC_RETRY_TIMEOUT); syncTimeoutTimer_->start(SYNC_RETRY_TIMEOUT);
client_->setNextBatchToken(next_batch); http::client()->setNextBatchToken(next_batch);
client_->sync(); http::client()->sync();
}); });
connect(this, &ChatPage::startConsesusTimer, this, [this]() { connect(this, &ChatPage::startConsesusTimer, this, [this]() {
@ -440,7 +437,7 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client,
} }
if (hasNotifications) if (hasNotifications)
client_->getNotifications(); http::client()->getNotifications();
}); });
connect(this, &ChatPage::syncRoomlist, room_list_, &RoomList::sync); connect(this, &ChatPage::syncRoomlist, room_list_, &RoomList::sync);
@ -489,22 +486,22 @@ ChatPage::deleteConfigs()
cache_->deleteData(); cache_->deleteData();
client_->reset(); http::client()->reset();
} }
void void
ChatPage::bootstrap(QString userid, QString homeserver, QString token) ChatPage::bootstrap(QString userid, QString homeserver, QString token)
{ {
client_->setServer(homeserver); http::client()->setServer(homeserver);
client_->setAccessToken(token); http::client()->setAccessToken(token);
client_->getOwnProfile(); http::client()->getOwnProfile();
client_->getOwnCommunities(); http::client()->getOwnCommunities();
cache_ = QSharedPointer<Cache>(new Cache(userid)); cache_ = QSharedPointer<Cache>(new Cache(userid));
room_list_->setCache(cache_); room_list_->setCache(cache_);
text_input_->setCache(cache_); text_input_->setCache(cache_);
AvatarProvider::init(client_, cache_); AvatarProvider::init(cache_);
try { try {
cache_->setup(); cache_->setup();
@ -525,7 +522,7 @@ ChatPage::bootstrap(QString userid, QString homeserver, QString token)
qInfo() << "Falling back to initial sync ..."; qInfo() << "Falling back to initial sync ...";
} }
client_->initialSync(); http::client()->initialSync();
initialSyncTimer_->start(INITIAL_SYNC_RETRY_TIMEOUT); initialSyncTimer_->start(INITIAL_SYNC_RETRY_TIMEOUT);
} }
@ -602,7 +599,7 @@ ChatPage::updateOwnProfileInfo(const QUrl &avatar_url, const QString &display_na
} }
} }
auto proxy = client_->fetchUserAvatar(avatar_url); auto proxy = http::client()->fetchUserAvatar(avatar_url);
if (proxy.isNull()) if (proxy.isNull())
return; return;
@ -825,7 +822,7 @@ ChatPage::retryInitialSync(int status_code)
{ {
initialSyncTimer_->stop(); initialSyncTimer_->stop();
if (client_->getHomeServer().isEmpty()) { if (http::client()->getHomeServer().isEmpty()) {
deleteConfigs(); deleteConfigs();
resetUI(); resetUI();
emit showLoginPage("Sync error. Please try again."); emit showLoginPage("Sync error. Please try again.");
@ -836,7 +833,7 @@ ChatPage::retryInitialSync(int status_code)
if (status_code == -1 || status_code == 504 || status_code == 502 || status_code == 524) { if (status_code == -1 || status_code == 504 || status_code == 502 || status_code == 524) {
qWarning() << "retrying initial sync"; qWarning() << "retrying initial sync";
client_->initialSync(); http::client()->initialSync();
initialSyncTimer_->start(INITIAL_SYNC_RETRY_TIMEOUT); initialSyncTimer_->start(INITIAL_SYNC_RETRY_TIMEOUT);
} else { } else {
// Drop into the login screen. // Drop into the login screen.

View file

@ -1,10 +1,10 @@
#include "CommunitiesList.h" #include "CommunitiesList.h"
#include "MatrixClient.h"
#include <QLabel> #include <QLabel>
CommunitiesList::CommunitiesList(QSharedPointer<MatrixClient> client, QWidget *parent) CommunitiesList::CommunitiesList(QWidget *parent)
: QWidget(parent) : QWidget(parent)
, client_(client)
{ {
QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0); sizePolicy.setHorizontalStretch(0);
@ -38,14 +38,14 @@ CommunitiesList::CommunitiesList(QSharedPointer<MatrixClient> client, QWidget *p
scrollArea_->setWidget(scrollAreaContents_); scrollArea_->setWidget(scrollAreaContents_);
topLayout_->addWidget(scrollArea_); topLayout_->addWidget(scrollArea_);
connect(client_.data(), connect(http::client(),
&MatrixClient::communityProfileRetrieved, &MatrixClient::communityProfileRetrieved,
this, this,
[this](QString communityId, QJsonObject profile) { [](QString communityId, QJsonObject profile) {
client_->fetchCommunityAvatar(communityId, http::client()->fetchCommunityAvatar(
QUrl(profile["avatar_url"].toString())); communityId, QUrl(profile["avatar_url"].toString()));
}); });
connect(client_.data(), connect(http::client(),
SIGNAL(communityAvatarRetrieved(const QString &, const QPixmap &)), SIGNAL(communityAvatarRetrieved(const QString &, const QPixmap &)),
this, this,
SLOT(updateCommunityAvatar(const QString &, const QPixmap &))); SLOT(updateCommunityAvatar(const QString &, const QPixmap &)));
@ -61,8 +61,8 @@ CommunitiesList::setCommunities(const std::map<QString, QSharedPointer<Community
for (const auto &community : communities) { for (const auto &community : communities) {
addCommunity(community.second, community.first); addCommunity(community.second, community.first);
client_->fetchCommunityProfile(community.first); http::client()->fetchCommunityProfile(community.first);
client_->fetchCommunityRooms(community.first); http::client()->fetchCommunityRooms(community.first);
} }
communities_["world"]->setPressedState(true); communities_["world"]->setPressedState(true);
@ -77,7 +77,7 @@ CommunitiesList::addCommunity(QSharedPointer<Community> community, const QString
communities_.emplace(community_id, QSharedPointer<CommunitiesListItem>(list_item)); communities_.emplace(community_id, QSharedPointer<CommunitiesListItem>(list_item));
client_->fetchCommunityAvatar(community_id, community->getAvatar()); http::client()->fetchCommunityAvatar(community_id, community->getAvatar());
contentsLayout_->insertWidget(contentsLayout_->count() - 1, list_item); contentsLayout_->insertWidget(contentsLayout_->count() - 1, list_item);

View file

@ -30,10 +30,9 @@
using namespace mtx::identifiers; using namespace mtx::identifiers;
LoginPage::LoginPage(QSharedPointer<MatrixClient> client, QWidget *parent) LoginPage::LoginPage(QWidget *parent)
: QWidget(parent) : QWidget(parent)
, inferredServerAddress_() , inferredServerAddress_()
, client_{client}
{ {
top_layout_ = new QVBoxLayout(); top_layout_ = new QVBoxLayout();
@ -143,11 +142,11 @@ LoginPage::LoginPage(QSharedPointer<MatrixClient> client, QWidget *parent)
connect(matrixid_input_, SIGNAL(returnPressed()), login_button_, SLOT(click())); connect(matrixid_input_, SIGNAL(returnPressed()), login_button_, SLOT(click()));
connect(password_input_, SIGNAL(returnPressed()), login_button_, SLOT(click())); connect(password_input_, SIGNAL(returnPressed()), login_button_, SLOT(click()));
connect(serverInput_, SIGNAL(returnPressed()), login_button_, SLOT(click())); connect(serverInput_, SIGNAL(returnPressed()), login_button_, SLOT(click()));
connect(client_.data(), SIGNAL(loginError(QString)), this, SLOT(loginError(QString))); connect(http::client(), SIGNAL(loginError(QString)), this, SLOT(loginError(QString)));
connect(client_.data(), SIGNAL(loginError(QString)), this, SIGNAL(errorOccurred())); connect(http::client(), SIGNAL(loginError(QString)), this, SIGNAL(errorOccurred()));
connect(matrixid_input_, SIGNAL(editingFinished()), this, SLOT(onMatrixIdEntered())); connect(matrixid_input_, SIGNAL(editingFinished()), this, SLOT(onMatrixIdEntered()));
connect(client_.data(), SIGNAL(versionError(QString)), this, SLOT(versionError(QString))); connect(http::client(), SIGNAL(versionError(QString)), this, SLOT(versionError(QString)));
connect(client_.data(), SIGNAL(versionSuccess()), this, SLOT(versionSuccess())); connect(http::client(), SIGNAL(versionSuccess()), this, SLOT(versionSuccess()));
connect(serverInput_, SIGNAL(editingFinished()), this, SLOT(onServerAddressEntered())); connect(serverInput_, SIGNAL(editingFinished()), this, SLOT(onServerAddressEntered()));
} }
@ -181,8 +180,8 @@ LoginPage::onMatrixIdEntered()
inferredServerAddress_ = homeServer; inferredServerAddress_ = homeServer;
serverInput_->setText(homeServer); serverInput_->setText(homeServer);
client_->setServer(homeServer); http::client()->setServer(homeServer);
client_->versions(); http::client()->versions();
} }
} }
@ -190,8 +189,8 @@ void
LoginPage::onServerAddressEntered() LoginPage::onServerAddressEntered()
{ {
error_label_->setText(""); error_label_->setText("");
client_->setServer(serverInput_->text()); http::client()->setServer(serverInput_->text());
client_->versions(); http::client()->versions();
serverLayout_->removeWidget(errorIcon_); serverLayout_->removeWidget(errorIcon_);
errorIcon_->hide(); errorIcon_->hide();
@ -202,7 +201,7 @@ LoginPage::onServerAddressEntered()
void void
LoginPage::versionError(QString error) LoginPage::versionError(QString error)
{ {
QUrl currentServer = client_->getHomeServer(); QUrl currentServer = http::client()->getHomeServer();
QString mxidAddress = matrixid_input_->text().split(":").at(1); QString mxidAddress = matrixid_input_->text().split(":").at(1);
error_label_->setText(error); error_label_->setText(error);
@ -242,8 +241,8 @@ LoginPage::onLoginButtonClicked()
if (password_input_->text().isEmpty()) if (password_input_->text().isEmpty())
return loginError(tr("Empty password")); return loginError(tr("Empty password"));
client_->setServer(serverInput_->text()); http::client()->setServer(serverInput_->text());
client_->login(QString::fromStdString(user.localpart()), password_input_->text()); http::client()->login(QString::fromStdString(user.localpart()), password_input_->text());
emit loggingIn(); emit loggingIn();
} }

View file

@ -54,6 +54,9 @@ MainWindow::MainWindow(QWidget *parent)
setWindowTitle("nheko"); setWindowTitle("nheko");
setObjectName("MainWindow"); setObjectName("MainWindow");
// Initialize the http client.
http::init(this);
restoreWindowSize(); restoreWindowSize();
QFont font("Open Sans"); QFont font("Open Sans");
@ -61,14 +64,13 @@ MainWindow::MainWindow(QWidget *parent)
font.setStyleStrategy(QFont::PreferAntialias); font.setStyleStrategy(QFont::PreferAntialias);
setFont(font); setFont(font);
client_ = QSharedPointer<MatrixClient>(new MatrixClient("matrix.org"));
userSettings_ = QSharedPointer<UserSettings>(new UserSettings); userSettings_ = QSharedPointer<UserSettings>(new UserSettings);
trayIcon_ = new TrayIcon(":/logos/nheko-32.png", this); trayIcon_ = new TrayIcon(":/logos/nheko-32.png", this);
welcome_page_ = new WelcomePage(this); welcome_page_ = new WelcomePage(this);
login_page_ = new LoginPage(client_, this); login_page_ = new LoginPage(this);
register_page_ = new RegisterPage(client_, this); register_page_ = new RegisterPage(this);
chat_page_ = new ChatPage(client_, userSettings_, this); chat_page_ = new ChatPage(userSettings_, this);
userSettingsPage_ = new UserSettingsPage(userSettings_, this); userSettingsPage_ = new UserSettingsPage(userSettings_, this);
// Initialize sliding widget manager. // Initialize sliding widget manager.
@ -122,16 +124,16 @@ MainWindow::MainWindow(QWidget *parent)
connect( connect(
chat_page_, &ChatPage::showUserSettingsPage, this, &MainWindow::showUserSettingsPage); chat_page_, &ChatPage::showUserSettingsPage, this, &MainWindow::showUserSettingsPage);
connect(client_.data(), connect(http::client(),
SIGNAL(loginSuccess(QString, QString, QString)), SIGNAL(loginSuccess(QString, QString, QString)),
this, this,
SLOT(showChatPage(QString, QString, QString))); SLOT(showChatPage(QString, QString, QString)));
connect(client_.data(), connect(http::client(),
SIGNAL(registerSuccess(QString, QString, QString)), SIGNAL(registerSuccess(QString, QString, QString)),
this, this,
SLOT(showChatPage(QString, QString, QString))); SLOT(showChatPage(QString, QString, QString)));
connect(client_.data(), &MatrixClient::invalidToken, this, [this]() { connect(http::client(), &MatrixClient::invalidToken, this, [this]() {
chat_page_->deleteConfigs(); chat_page_->deleteConfigs();
showLoginPage(); showLoginPage();
login_page_->loginError("Invalid token detected. Please try to login again."); login_page_->loginError("Invalid token detected. Please try to login again.");
@ -315,7 +317,7 @@ MainWindow::openLeaveRoomDialog(const QString &room_id)
leaveRoomModal_->hide(); leaveRoomModal_->hide();
if (leaving) if (leaving)
client_->leaveRoom(roomToLeave); http::client()->leaveRoom(roomToLeave);
}); });
leaveRoomModal_ = leaveRoomModal_ =

View file

@ -33,7 +33,27 @@
#include "MatrixClient.h" #include "MatrixClient.h"
MatrixClient::MatrixClient(QString server, QObject *parent) namespace {
MatrixClient *instance_ = nullptr;
}
namespace http {
void
init(QObject *parent)
{
if (!instance_)
instance_ = new MatrixClient(parent);
}
MatrixClient *
client()
{
return instance_;
}
}
MatrixClient::MatrixClient(QObject *parent)
: QNetworkAccessManager(parent) : QNetworkAccessManager(parent)
, clientApiUrl_{"/_matrix/client/r0"} , clientApiUrl_{"/_matrix/client/r0"}
, mediaApiUrl_{"/_matrix/media/r0"} , mediaApiUrl_{"/_matrix/media/r0"}
@ -55,8 +75,6 @@ MatrixClient::MatrixClient(QString server, QObject *parent)
[](QNetworkReply *reply, const QList<QSslError> &) { reply->ignoreSslErrors(); }); [](QNetworkReply *reply, const QList<QSslError> &) { reply->ignoreSslErrors(); });
} }
setServer(server);
QJsonObject default_filter{ QJsonObject default_filter{
{ {
"room", "room",

View file

@ -28,9 +28,8 @@
#include "dialogs/ReCaptcha.hpp" #include "dialogs/ReCaptcha.hpp"
RegisterPage::RegisterPage(QSharedPointer<MatrixClient> client, QWidget *parent) RegisterPage::RegisterPage(QWidget *parent)
: QWidget(parent) : QWidget(parent)
, client_(client)
{ {
top_layout_ = new QVBoxLayout(); top_layout_ = new QVBoxLayout();
@ -126,11 +125,11 @@ RegisterPage::RegisterPage(QSharedPointer<MatrixClient> client, QWidget *parent)
connect(password_input_, SIGNAL(returnPressed()), register_button_, SLOT(click())); connect(password_input_, SIGNAL(returnPressed()), register_button_, SLOT(click()));
connect(password_confirmation_, SIGNAL(returnPressed()), register_button_, SLOT(click())); connect(password_confirmation_, SIGNAL(returnPressed()), register_button_, SLOT(click()));
connect(server_input_, SIGNAL(returnPressed()), register_button_, SLOT(click())); connect(server_input_, SIGNAL(returnPressed()), register_button_, SLOT(click()));
connect(client_.data(), connect(http::client(),
SIGNAL(registerError(const QString &)), SIGNAL(registerError(const QString &)),
this, this,
SLOT(registerError(const QString &))); SLOT(registerError(const QString &)));
connect(client_.data(), connect(http::client(),
&MatrixClient::registrationFlow, &MatrixClient::registrationFlow,
this, this,
[this](const QString &user, [this](const QString &user,
@ -148,7 +147,8 @@ RegisterPage::RegisterPage(QSharedPointer<MatrixClient> client, QWidget *parent)
[this, user, pass, server, session]() { [this, user, pass, server, session]() {
captchaDialog_->close(); captchaDialog_->close();
emit registering(); emit registering();
client_->registerUser(user, pass, server, session); http::client()->registerUser(
user, pass, server, session);
}); });
} }
@ -189,7 +189,7 @@ RegisterPage::onRegisterButtonClicked()
QString password = password_input_->text(); QString password = password_input_->text();
QString server = server_input_->text(); QString server = server_input_->text();
client_->registerUser(username, password, server); http::client()->registerUser(username, password, server);
emit registering(); emit registering();
} }
} }

View file

@ -29,11 +29,8 @@
#include "UserSettingsPage.h" #include "UserSettingsPage.h"
#include "Utils.h" #include "Utils.h"
RoomList::RoomList(QSharedPointer<MatrixClient> client, RoomList::RoomList(QSharedPointer<UserSettings> userSettings, QWidget *parent)
QSharedPointer<UserSettings> userSettings,
QWidget *parent)
: QWidget(parent) : QWidget(parent)
, client_(client)
, userSettings_{userSettings} , userSettings_{userSettings}
{ {
setStyleSheet("border: none;"); setStyleSheet("border: none;");
@ -58,7 +55,7 @@ RoomList::RoomList(QSharedPointer<MatrixClient> client,
scrollArea_->setWidget(scrollAreaContents_); scrollArea_->setWidget(scrollAreaContents_);
topLayout_->addWidget(scrollArea_); topLayout_->addWidget(scrollArea_);
connect(client_.data(), connect(http::client(),
&MatrixClient::roomAvatarRetrieved, &MatrixClient::roomAvatarRetrieved,
this, this,
[this](const QString &room_id, [this](const QString &room_id,
@ -104,7 +101,7 @@ RoomList::updateAvatar(const QString &room_id, const QString &url)
savedImgData = cache_->image(url); savedImgData = cache_->image(url);
if (savedImgData.isEmpty()) { if (savedImgData.isEmpty()) {
client_->fetchRoomAvatar(room_id, url); http::client()->fetchRoomAvatar(room_id, url);
} else { } else {
QPixmap img; QPixmap img;
img.loadFromData(savedImgData); img.loadFromData(savedImgData);
@ -317,7 +314,7 @@ RoomList::closeJoinRoomDialog(bool isJoining, QString roomAlias)
joinRoomModal_->hide(); joinRoomModal_->hide();
if (isJoining) if (isJoining)
client_->joinRoom(roomAlias); http::client()->joinRoom(roomAlias);
} }
void void

View file

@ -19,8 +19,10 @@
#include <QFontDatabase> #include <QFontDatabase>
#include <QMenu> #include <QMenu>
#include <QTextEdit> #include <QTextEdit>
#include <QTimer>
#include "Avatar.h" #include "Avatar.h"
#include "ChatPage.h"
#include "Config.h" #include "Config.h"
#include "timeline/TimelineItem.h" #include "timeline/TimelineItem.h"
@ -63,7 +65,7 @@ TimelineItem::init()
connect(redactMsg_, &QAction::triggered, this, [this]() { connect(redactMsg_, &QAction::triggered, this, [this]() {
if (!event_id_.isEmpty()) if (!event_id_.isEmpty())
ChatPage::instance()->redactEvent(room_id_, event_id_); http::client()->redactEvent(room_id_, event_id_);
}); });
connect(markAsRead_, &QAction::triggered, this, [this]() { sendReadReceipt(); }); connect(markAsRead_, &QAction::triggered, this, [this]() { sendReadReceipt(); });

View file

@ -84,26 +84,21 @@ DateSeparator::paintEvent(QPaintEvent *)
} }
TimelineView::TimelineView(const mtx::responses::Timeline &timeline, TimelineView::TimelineView(const mtx::responses::Timeline &timeline,
QSharedPointer<MatrixClient> client,
const QString &room_id, const QString &room_id,
QWidget *parent) QWidget *parent)
: QWidget(parent) : QWidget(parent)
, room_id_{room_id} , room_id_{room_id}
, client_{client}
{ {
init(); init();
addEvents(timeline); addEvents(timeline);
} }
TimelineView::TimelineView(QSharedPointer<MatrixClient> client, TimelineView::TimelineView(const QString &room_id, QWidget *parent)
const QString &room_id,
QWidget *parent)
: QWidget(parent) : QWidget(parent)
, room_id_{room_id} , room_id_{room_id}
, client_{client}
{ {
init(); init();
client_->messages(room_id_, ""); http::client()->messages(room_id_, "");
} }
void void
@ -143,7 +138,7 @@ TimelineView::fetchHistory()
return; return;
isPaginationInProgress_ = true; isPaginationInProgress_ = true;
client_->messages(room_id_, prev_batch_token_); http::client()->messages(room_id_, prev_batch_token_);
paginationTimer_->start(5000); paginationTimer_->start(5000);
return; return;
@ -194,7 +189,7 @@ TimelineView::sliderMoved(int position)
// FIXME: Maybe move this to TimelineViewManager to remove the // FIXME: Maybe move this to TimelineViewManager to remove the
// extra calls? // extra calls?
client_->messages(room_id_, prev_batch_token_); http::client()->messages(room_id_, prev_batch_token_);
} }
} }
@ -430,7 +425,7 @@ TimelineView::init()
paginationTimer_ = new QTimer(this); paginationTimer_ = new QTimer(this);
connect(paginationTimer_, &QTimer::timeout, this, &TimelineView::fetchHistory); connect(paginationTimer_, &QTimer::timeout, this, &TimelineView::fetchHistory);
connect(client_.data(), connect(http::client(),
&MatrixClient::messagesRetrieved, &MatrixClient::messagesRetrieved,
this, this,
&TimelineView::addBackwardsEvents); &TimelineView::addBackwardsEvents);
@ -551,7 +546,7 @@ TimelineView::addUserMessage(mtx::events::MessageType ty, const QString &body)
saveLastMessageInfo(local_user_, QDateTime::currentDateTime()); saveLastMessageInfo(local_user_, QDateTime::currentDateTime());
int txn_id = client_->incrementTransactionId(); int txn_id = http::client()->incrementTransactionId();
PendingMessage message(ty, txn_id, body, "", "", -1, "", view_item); PendingMessage message(ty, txn_id, body, "", "", -1, "", view_item);
handleNewUserMessage(message); handleNewUserMessage(message);
} }
@ -577,11 +572,12 @@ TimelineView::sendNextPendingMessage()
case mtx::events::MessageType::Video: case mtx::events::MessageType::Video:
case mtx::events::MessageType::File: case mtx::events::MessageType::File:
// FIXME: Improve the API // FIXME: Improve the API
client_->sendRoomMessage( http::client()->sendRoomMessage(
m.ty, m.txn_id, room_id_, m.filename, m.mime, m.media_size, m.body); m.ty, m.txn_id, room_id_, m.filename, m.mime, m.media_size, m.body);
break; break;
default: default:
client_->sendRoomMessage(m.ty, m.txn_id, room_id_, m.body, m.mime, m.media_size); http::client()->sendRoomMessage(
m.ty, m.txn_id, room_id_, m.body, m.mime, m.media_size);
break; break;
} }
} }
@ -675,7 +671,7 @@ TimelineView::readLastEvent() const
const auto eventId = getLastEventId(); const auto eventId = getLastEventId();
if (!eventId.isEmpty()) if (!eventId.isEmpty())
client_->readEvent(room_id_, eventId); http::client()->readEvent(room_id_, eventId);
} }
QString QString

View file

@ -31,21 +31,20 @@
#include "timeline/widgets/ImageItem.h" #include "timeline/widgets/ImageItem.h"
#include "timeline/widgets/VideoItem.h" #include "timeline/widgets/VideoItem.h"
TimelineViewManager::TimelineViewManager(QSharedPointer<MatrixClient> client, QWidget *parent) TimelineViewManager::TimelineViewManager(QWidget *parent)
: QStackedWidget(parent) : QStackedWidget(parent)
, client_(client)
{ {
setStyleSheet("border: none;"); setStyleSheet("border: none;");
connect( connect(
client_.data(), &MatrixClient::messageSent, this, &TimelineViewManager::messageSent); http::client(), &MatrixClient::messageSent, this, &TimelineViewManager::messageSent);
connect(client_.data(), connect(http::client(),
&MatrixClient::messageSendFailed, &MatrixClient::messageSendFailed,
this, this,
&TimelineViewManager::messageSendFailed); &TimelineViewManager::messageSendFailed);
connect(client_.data(), connect(http::client(),
&MatrixClient::redactionCompleted, &MatrixClient::redactionCompleted,
this, this,
[this](const QString &room_id, const QString &event_id) { [this](const QString &room_id, const QString &event_id) {
@ -190,7 +189,7 @@ TimelineViewManager::addRoom(const mtx::responses::JoinedRoom &room, const QStri
return; return;
// Create a history view with the room events. // Create a history view with the room events.
TimelineView *view = new TimelineView(room.timeline, client_, room_id); TimelineView *view = new TimelineView(room.timeline, room_id);
views_.emplace(room_id, QSharedPointer<TimelineView>(view)); views_.emplace(room_id, QSharedPointer<TimelineView>(view));
connect(view, connect(view,
@ -209,7 +208,7 @@ TimelineViewManager::addRoom(const QString &room_id)
return; return;
// Create a history view without any events. // Create a history view without any events.
TimelineView *view = new TimelineView(client_, room_id); TimelineView *view = new TimelineView(room_id);
views_.emplace(room_id, QSharedPointer<TimelineView>(view)); views_.emplace(room_id, QSharedPointer<TimelineView>(view));
connect(view, connect(view,

View file

@ -23,6 +23,7 @@
#include <QPainter> #include <QPainter>
#include <QPixmap> #include <QPixmap>
#include "MatrixClient.h"
#include "Utils.h" #include "Utils.h"
#include "timeline/widgets/AudioItem.h" #include "timeline/widgets/AudioItem.h"
@ -57,7 +58,7 @@ AudioItem::init()
QString media_params = url_parts[1]; QString media_params = url_parts[1];
url_ = QString("%1/_matrix/media/r0/download/%2") url_ = QString("%1/_matrix/media/r0/download/%2")
.arg(client_.data()->getHomeServer().toString(), media_params); .arg(http::client()->getHomeServer().toString(), media_params);
player_ = new QMediaPlayer; player_ = new QMediaPlayer;
player_->setMedia(QUrl(url_)); player_->setMedia(QUrl(url_));
@ -73,29 +74,21 @@ AudioItem::init()
}); });
} }
AudioItem::AudioItem(QSharedPointer<MatrixClient> client, AudioItem::AudioItem(const mtx::events::RoomEvent<mtx::events::msg::Audio> &event, QWidget *parent)
const mtx::events::RoomEvent<mtx::events::msg::Audio> &event,
QWidget *parent)
: QWidget(parent) : QWidget(parent)
, url_{QUrl(QString::fromStdString(event.content.url))} , url_{QUrl(QString::fromStdString(event.content.url))}
, text_{QString::fromStdString(event.content.body)} , text_{QString::fromStdString(event.content.body)}
, event_{event} , event_{event}
, client_{client}
{ {
readableFileSize_ = utils::humanReadableFileSize(event.content.info.size); readableFileSize_ = utils::humanReadableFileSize(event.content.info.size);
init(); init();
} }
AudioItem::AudioItem(QSharedPointer<MatrixClient> client, AudioItem::AudioItem(const QString &url, const QString &filename, uint64_t size, QWidget *parent)
const QString &url,
const QString &filename,
uint64_t size,
QWidget *parent)
: QWidget(parent) : QWidget(parent)
, url_{url} , url_{url}
, text_{filename} , text_{filename}
, client_{client}
{ {
readableFileSize_ = utils::humanReadableFileSize(size); readableFileSize_ = utils::humanReadableFileSize(size);
@ -134,7 +127,7 @@ AudioItem::mousePressEvent(QMouseEvent *event)
if (filenameToSave_.isEmpty()) if (filenameToSave_.isEmpty())
return; return;
auto proxy = client_->downloadFile(url_); auto proxy = http::client()->downloadFile(url_);
connect(proxy.data(), connect(proxy.data(),
&DownloadMediaProxy::fileDownloaded, &DownloadMediaProxy::fileDownloaded,
this, this,

View file

@ -23,6 +23,7 @@
#include <QPainter> #include <QPainter>
#include <QPixmap> #include <QPixmap>
#include "MatrixClient.h"
#include "Utils.h" #include "Utils.h"
#include "timeline/widgets/FileItem.h" #include "timeline/widgets/FileItem.h"
@ -56,32 +57,24 @@ FileItem::init()
QString media_params = url_parts[1]; QString media_params = url_parts[1];
url_ = QString("%1/_matrix/media/r0/download/%2") url_ = QString("%1/_matrix/media/r0/download/%2")
.arg(client_.data()->getHomeServer().toString(), media_params); .arg(http::client()->getHomeServer().toString(), media_params);
} }
FileItem::FileItem(QSharedPointer<MatrixClient> client, FileItem::FileItem(const mtx::events::RoomEvent<mtx::events::msg::File> &event, QWidget *parent)
const mtx::events::RoomEvent<mtx::events::msg::File> &event,
QWidget *parent)
: QWidget(parent) : QWidget(parent)
, url_{QString::fromStdString(event.content.url)} , url_{QString::fromStdString(event.content.url)}
, text_{QString::fromStdString(event.content.body)} , text_{QString::fromStdString(event.content.body)}
, event_{event} , event_{event}
, client_{client}
{ {
readableFileSize_ = utils::humanReadableFileSize(event.content.info.size); readableFileSize_ = utils::humanReadableFileSize(event.content.info.size);
init(); init();
} }
FileItem::FileItem(QSharedPointer<MatrixClient> client, FileItem::FileItem(const QString &url, const QString &filename, uint64_t size, QWidget *parent)
const QString &url,
const QString &filename,
uint64_t size,
QWidget *parent)
: QWidget(parent) : QWidget(parent)
, url_{url} , url_{url}
, text_{filename} , text_{filename}
, client_{client}
{ {
readableFileSize_ = utils::humanReadableFileSize(size); readableFileSize_ = utils::humanReadableFileSize(size);
@ -120,7 +113,7 @@ FileItem::mousePressEvent(QMouseEvent *event)
if (filenameToSave_.isEmpty()) if (filenameToSave_.isEmpty())
return; return;
auto proxy = client_->downloadFile(url_); auto proxy = http::client()->downloadFile(url_);
connect(proxy.data(), connect(proxy.data(),
&DownloadMediaProxy::fileDownloaded, &DownloadMediaProxy::fileDownloaded,
this, this,

View file

@ -25,16 +25,14 @@
#include <QUuid> #include <QUuid>
#include "Config.h" #include "Config.h"
#include "MatrixClient.h"
#include "Utils.h" #include "Utils.h"
#include "dialogs/ImageOverlay.h" #include "dialogs/ImageOverlay.h"
#include "timeline/widgets/ImageItem.h" #include "timeline/widgets/ImageItem.h"
ImageItem::ImageItem(QSharedPointer<MatrixClient> client, ImageItem::ImageItem(const mtx::events::RoomEvent<mtx::events::msg::Image> &event, QWidget *parent)
const mtx::events::RoomEvent<mtx::events::msg::Image> &event,
QWidget *parent)
: QWidget(parent) : QWidget(parent)
, event_{event} , event_{event}
, client_{client}
{ {
setMouseTracking(true); setMouseTracking(true);
setCursor(Qt::PointingHandCursor); setCursor(Qt::PointingHandCursor);
@ -52,9 +50,9 @@ ImageItem::ImageItem(QSharedPointer<MatrixClient> client,
QString media_params = url_parts[1]; QString media_params = url_parts[1];
url_ = QString("%1/_matrix/media/r0/download/%2") url_ = QString("%1/_matrix/media/r0/download/%2")
.arg(client_.data()->getHomeServer().toString(), media_params); .arg(http::client()->getHomeServer().toString(), media_params);
auto proxy = client_.data()->downloadImage(url_); auto proxy = http::client()->downloadImage(url_);
connect(proxy.data(), connect(proxy.data(),
&DownloadMediaProxy::imageDownloaded, &DownloadMediaProxy::imageDownloaded,
@ -65,15 +63,10 @@ ImageItem::ImageItem(QSharedPointer<MatrixClient> client,
}); });
} }
ImageItem::ImageItem(QSharedPointer<MatrixClient> client, ImageItem::ImageItem(const QString &url, const QString &filename, uint64_t size, QWidget *parent)
const QString &url,
const QString &filename,
uint64_t size,
QWidget *parent)
: QWidget(parent) : QWidget(parent)
, url_{url} , url_{url}
, text_{filename} , text_{filename}
, client_{client}
{ {
Q_UNUSED(size); Q_UNUSED(size);
@ -90,9 +83,9 @@ ImageItem::ImageItem(QSharedPointer<MatrixClient> client,
QString media_params = url_parts[1]; QString media_params = url_parts[1];
url_ = QString("%1/_matrix/media/r0/download/%2") url_ = QString("%1/_matrix/media/r0/download/%2")
.arg(client_.data()->getHomeServer().toString(), media_params); .arg(http::client()->getHomeServer().toString(), media_params);
auto proxy = client_.data()->downloadImage(url_); auto proxy = http::client()->downloadImage(url_);
connect(proxy.data(), connect(proxy.data(),
&DownloadMediaProxy::imageDownloaded, &DownloadMediaProxy::imageDownloaded,
@ -238,7 +231,7 @@ ImageItem::saveAs()
if (filename.isEmpty()) if (filename.isEmpty())
return; return;
auto proxy = client_->downloadFile(url_); auto proxy = http::client()->downloadFile(url_);
connect(proxy.data(), connect(proxy.data(),
&DownloadMediaProxy::fileDownloaded, &DownloadMediaProxy::fileDownloaded,
this, this,

View file

@ -20,6 +20,7 @@
#include <QVBoxLayout> #include <QVBoxLayout>
#include "Config.h" #include "Config.h"
#include "MatrixClient.h"
#include "Utils.h" #include "Utils.h"
#include "timeline/widgets/VideoItem.h" #include "timeline/widgets/VideoItem.h"
@ -34,17 +35,14 @@ VideoItem::init()
QString media_params = url_parts[1]; QString media_params = url_parts[1];
url_ = QString("%1/_matrix/media/r0/download/%2") url_ = QString("%1/_matrix/media/r0/download/%2")
.arg(client_.data()->getHomeServer().toString(), media_params); .arg(http::client()->getHomeServer().toString(), media_params);
} }
VideoItem::VideoItem(QSharedPointer<MatrixClient> client, VideoItem::VideoItem(const mtx::events::RoomEvent<mtx::events::msg::Video> &event, QWidget *parent)
const mtx::events::RoomEvent<mtx::events::msg::Video> &event,
QWidget *parent)
: QWidget(parent) : QWidget(parent)
, url_{QString::fromStdString(event.content.url)} , url_{QString::fromStdString(event.content.url)}
, text_{QString::fromStdString(event.content.body)} , text_{QString::fromStdString(event.content.body)}
, event_{event} , event_{event}
, client_{client}
{ {
readableFileSize_ = utils::humanReadableFileSize(event.content.info.size); readableFileSize_ = utils::humanReadableFileSize(event.content.info.size);
@ -65,15 +63,10 @@ VideoItem::VideoItem(QSharedPointer<MatrixClient> client,
layout->addWidget(label_); layout->addWidget(label_);
} }
VideoItem::VideoItem(QSharedPointer<MatrixClient> client, VideoItem::VideoItem(const QString &url, const QString &filename, uint64_t size, QWidget *parent)
const QString &url,
const QString &filename,
uint64_t size,
QWidget *parent)
: QWidget(parent) : QWidget(parent)
, url_{url} , url_{url}
, text_{filename} , text_{filename}
, client_{client}
{ {
readableFileSize_ = utils::humanReadableFileSize(size); readableFileSize_ = utils::humanReadableFileSize(size);