Small style change

This commit is contained in:
Konstantinos Sideris 2017-08-20 13:47:22 +03:00
parent 57ac64fb2b
commit 2644e4acca
120 changed files with 2897 additions and 2415 deletions

View file

@ -7,13 +7,12 @@ AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: true AllowAllParametersOfDeclarationOnNextLine: true
AllowShortFunctionsOnASingleLine: None AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: false AllowShortIfStatementsOnASingleLine: false
BasedOnStyle: Google BasedOnStyle: Mozilla
BinPackArguments: false BinPackArguments: false
BinPackParameters: false BinPackParameters: false
BreakBeforeBraces: Linux BreakBeforeBraces: Linux
BreakConstructorInitializersBeforeComma: true BreakConstructorInitializersBeforeComma: true
ColumnLimit: 0 ColumnLimit: 120
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ContinuationIndentWidth: 8 ContinuationIndentWidth: 8
IndentCaseLabels: false IndentCaseLabels: false
IndentWidth: 8 IndentWidth: 8

View file

@ -46,12 +46,14 @@ private:
QString userId_; QString userId_;
}; };
inline void Cache::unmount() inline void
Cache::unmount()
{ {
isMounted_ = false; isMounted_ = false;
} }
inline QString Cache::memberDbName(const QString &roomid) inline QString
Cache::memberDbName(const QString &roomid)
{ {
return QString("m.%1").arg(roomid); return QString("m.%1").arg(roomid);
} }

View file

@ -36,8 +36,8 @@ namespace fonts
static const int heading = 13; static const int heading = 13;
static const int badge = 10; static const int badge = 10;
static const int bubble = 20; static const int bubble = 20;
} // namespace fonts } // namespace fonts
} // namespace roomlist } // namespace roomlist
namespace userInfoWidget namespace userInfoWidget
{ {
@ -45,8 +45,8 @@ namespace fonts
{ {
static const int displayName = 16; static const int displayName = 16;
static const int userid = 14; static const int userid = 14;
} // namespace fonts } // namespace fonts
} // namespace userInfoWidget } // namespace userInfoWidget
namespace topRoomBar namespace topRoomBar
{ {
@ -54,8 +54,8 @@ namespace fonts
{ {
static const int roomName = 15; static const int roomName = 15;
static const int roomDescription = 13; static const int roomDescription = 13;
} // namespace fonts } // namespace fonts
} // namespace topRoomBar } // namespace topRoomBar
namespace timeline namespace timeline
{ {
@ -70,4 +70,4 @@ static const int timestamp = 9;
} }
} }
} // namespace conf } // namespace conf

View file

@ -53,7 +53,8 @@ private:
QLabel *category_; QLabel *category_;
}; };
inline void EmojiCategory::clickIndex(const QModelIndex &index) inline void
EmojiCategory::clickIndex(const QModelIndex &index)
{ {
emit emojiSelected(index.data(Qt::UserRole).toString()); emit emojiSelected(index.data(Qt::UserRole).toString());
} }

View file

@ -37,12 +37,14 @@ private:
QString password_; QString password_;
}; };
inline void LoginRequest::setPassword(QString password) inline void
LoginRequest::setPassword(QString password)
{ {
password_ = password; password_ = password;
} }
inline void LoginRequest::setUser(QString username) inline void
LoginRequest::setUser(QString username)
{ {
user_ = username; user_ = username;
} }
@ -62,17 +64,20 @@ private:
QString user_id_; QString user_id_;
}; };
inline QString LoginResponse::getAccessToken() inline QString
LoginResponse::getAccessToken()
{ {
return access_token_; return access_token_;
} }
inline QString LoginResponse::getHomeServer() inline QString
LoginResponse::getHomeServer()
{ {
return home_server_; return home_server_;
} }
inline QString LoginResponse::getUserId() inline QString
LoginResponse::getUserId()
{ {
return user_id_; return user_id_;
} }

View file

@ -136,32 +136,38 @@ private:
QString next_batch_; QString next_batch_;
}; };
inline QUrl MatrixClient::getHomeServer() inline QUrl
MatrixClient::getHomeServer()
{ {
return server_; return server_;
} }
inline int MatrixClient::transactionId() inline int
MatrixClient::transactionId()
{ {
return txn_id_; return txn_id_;
} }
inline void MatrixClient::setServer(const QString &server) inline void
MatrixClient::setServer(const QString &server)
{ {
server_ = QUrl(QString("https://%1").arg(server)); server_ = QUrl(QString("https://%1").arg(server));
} }
inline void MatrixClient::setAccessToken(const QString &token) inline void
MatrixClient::setAccessToken(const QString &token)
{ {
token_ = token; token_ = token;
} }
inline void MatrixClient::setNextBatchToken(const QString &next_batch) inline void
MatrixClient::setNextBatchToken(const QString &next_batch)
{ {
next_batch_ = next_batch; next_batch_ = next_batch;
} }
inline void MatrixClient::incrementTransactionId() inline void
MatrixClient::incrementTransactionId()
{ {
txn_id_ += 1; txn_id_ += 1;
} }

View file

@ -35,12 +35,14 @@ private:
QString display_name_; QString display_name_;
}; };
inline QUrl ProfileResponse::getAvatarUrl() inline QUrl
ProfileResponse::getAvatarUrl()
{ {
return avatar_url_; return avatar_url_;
} }
inline QString ProfileResponse::getDisplayName() inline QString
ProfileResponse::getDisplayName()
{ {
return display_name_; return display_name_;
} }

View file

@ -37,12 +37,14 @@ private:
QString password_; QString password_;
}; };
inline void RegisterRequest::setPassword(QString password) inline void
RegisterRequest::setPassword(QString password)
{ {
password_ = password; password_ = password;
} }
inline void RegisterRequest::setUser(QString username) inline void
RegisterRequest::setUser(QString username)
{ {
user_ = username; user_ = username;
} }
@ -62,17 +64,20 @@ private:
QString user_id_; QString user_id_;
}; };
inline QString RegisterResponse::getAccessToken() inline QString
RegisterResponse::getAccessToken()
{ {
return access_token_; return access_token_;
} }
inline QString RegisterResponse::getHomeServer() inline QString
RegisterResponse::getHomeServer()
{ {
return home_server_; return home_server_;
} }
inline QString RegisterResponse::getUserId() inline QString
RegisterResponse::getUserId()
{ {
return user_id_; return user_id_;
} }

View file

@ -38,10 +38,7 @@ class RoomInfoListItem : public QWidget
Q_OBJECT Q_OBJECT
public: public:
RoomInfoListItem(QSharedPointer<RoomSettings> settings, RoomInfoListItem(QSharedPointer<RoomSettings> settings, RoomState state, QString room_id, QWidget *parent = 0);
RoomState state,
QString room_id,
QWidget *parent = 0);
~RoomInfoListItem(); ~RoomInfoListItem();
@ -95,28 +92,34 @@ private:
int unreadMsgCount_ = 0; int unreadMsgCount_ = 0;
}; };
inline int RoomInfoListItem::unreadMessageCount() const inline int
RoomInfoListItem::unreadMessageCount() const
{ {
return unreadMsgCount_; return unreadMsgCount_;
} }
inline bool RoomInfoListItem::isPressed() const inline bool
RoomInfoListItem::isPressed() const
{ {
return isPressed_; return isPressed_;
} }
inline RoomState RoomInfoListItem::state() const inline RoomState
RoomInfoListItem::state() const
{ {
return state_; return state_;
} }
inline void RoomInfoListItem::setAvatar(const QImage &img) inline void
RoomInfoListItem::setAvatar(const QImage &img)
{ {
roomAvatar_ = QPixmap::fromImage(img.scaled(IconSize, IconSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); roomAvatar_ =
QPixmap::fromImage(img.scaled(IconSize, IconSize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
update(); update();
} }
inline void RoomInfoListItem::setDescriptionMessage(const DescInfo &info) inline void
RoomInfoListItem::setDescriptionMessage(const DescInfo &info)
{ {
lastMsgInfo_ = info; lastMsgInfo_ = info;
} }

View file

@ -37,17 +37,20 @@ private:
QJsonArray chunk_; QJsonArray chunk_;
}; };
inline QString RoomMessages::start() const inline QString
RoomMessages::start() const
{ {
return start_; return start_;
} }
inline QString RoomMessages::end() const inline QString
RoomMessages::end() const
{ {
return end_; return end_;
} }
inline QJsonArray RoomMessages::chunk() const inline QJsonArray
RoomMessages::chunk() const
{ {
return chunk_; return chunk_;
} }

View file

@ -80,17 +80,20 @@ private:
QString userAvatar_; QString userAvatar_;
}; };
inline QString RoomState::getTopic() const inline QString
RoomState::getTopic() const
{ {
return topic.content().topic().simplified(); return topic.content().topic().simplified();
} }
inline QString RoomState::getName() const inline QString
RoomState::getName() const
{ {
return name_; return name_;
} }
inline QUrl RoomState::getAvatar() const inline QUrl
RoomState::getAvatar() const
{ {
return avatar_; return avatar_;
} }

View file

@ -36,11 +36,7 @@ class SlidingStackWidget : public QStackedWidget
public: public:
// Defines the animation direction. // Defines the animation direction.
enum class AnimationDirection { enum class AnimationDirection { LEFT_TO_RIGHT, RIGHT_TO_LEFT, AUTOMATIC };
LEFT_TO_RIGHT,
RIGHT_TO_LEFT,
AUTOMATIC
};
SlidingStackWidget(QWidget *parent); SlidingStackWidget(QWidget *parent);
~SlidingStackWidget(); ~SlidingStackWidget();

View file

@ -51,37 +51,44 @@ private:
uint64_t origin_server_ts_; uint64_t origin_server_ts_;
}; };
inline QJsonObject Event::content() const inline QJsonObject
Event::content() const
{ {
return content_; return content_;
} }
inline QJsonObject Event::unsigned_content() const inline QJsonObject
Event::unsigned_content() const
{ {
return unsigned_; return unsigned_;
} }
inline QString Event::sender() const inline QString
Event::sender() const
{ {
return sender_; return sender_;
} }
inline QString Event::state_key() const inline QString
Event::state_key() const
{ {
return state_key_; return state_key_;
} }
inline QString Event::type() const inline QString
Event::type() const
{ {
return type_; return type_;
} }
inline QString Event::eventId() const inline QString
Event::eventId() const
{ {
return event_id_; return event_id_;
} }
inline uint64_t Event::timestamp() const inline uint64_t
Event::timestamp() const
{ {
return origin_server_ts_; return origin_server_ts_;
} }
@ -96,7 +103,8 @@ private:
QJsonArray events_; QJsonArray events_;
}; };
inline QJsonArray State::events() const inline QJsonArray
State::events() const
{ {
return events_; return events_;
} }
@ -116,17 +124,20 @@ private:
bool limited_; bool limited_;
}; };
inline QJsonArray Timeline::events() const inline QJsonArray
Timeline::events() const
{ {
return events_; return events_;
} }
inline QString Timeline::previousBatch() const inline QString
Timeline::previousBatch() const
{ {
return prev_batch_; return prev_batch_;
} }
inline bool Timeline::limited() const inline bool
Timeline::limited() const
{ {
return limited_; return limited_;
} }
@ -148,12 +159,14 @@ private:
/* UnreadNotifications unread_notifications_; */ /* UnreadNotifications unread_notifications_; */
}; };
inline State JoinedRoom::state() const inline State
JoinedRoom::state() const
{ {
return state_; return state_;
} }
inline Timeline JoinedRoom::timeline() const inline Timeline
JoinedRoom::timeline() const
{ {
return timeline_; return timeline_;
} }
@ -169,7 +182,8 @@ private:
QMap<QString, JoinedRoom> join_; QMap<QString, JoinedRoom> join_;
}; };
inline QMap<QString, JoinedRoom> Rooms::join() const inline QMap<QString, JoinedRoom>
Rooms::join() const
{ {
return join_; return join_;
} }
@ -186,12 +200,14 @@ private:
Rooms rooms_; Rooms rooms_;
}; };
inline Rooms SyncResponse::rooms() const inline Rooms
SyncResponse::rooms() const
{ {
return rooms_; return rooms_;
} }
inline QString SyncResponse::nextBatch() const inline QString
SyncResponse::nextBatch() const
{ {
return next_batch_; return next_batch_;
} }

View file

@ -66,7 +66,8 @@ private:
EmojiPickButton *emoji_button_; EmojiPickButton *emoji_button_;
}; };
inline void TextInputWidget::focusLineEdit() inline void
TextInputWidget::focusLineEdit()
{ {
input_->setFocus(); input_->setFocus();
} }

View file

@ -38,8 +38,14 @@ class TimelineItem : public QWidget
{ {
Q_OBJECT Q_OBJECT
public: public:
TimelineItem(const events::MessageEvent<msgs::Notice> &e, bool with_sender, const QString &color, QWidget *parent = 0); TimelineItem(const events::MessageEvent<msgs::Notice> &e,
TimelineItem(const events::MessageEvent<msgs::Text> &e, bool with_sender, const QString &color, QWidget *parent = 0); bool with_sender,
const QString &color,
QWidget *parent = 0);
TimelineItem(const events::MessageEvent<msgs::Text> &e,
bool with_sender,
const QString &color,
QWidget *parent = 0);
// For local messages. // For local messages.
TimelineItem(const QString &userid, const QString &color, QString body, QWidget *parent = 0); TimelineItem(const QString &userid, const QString &color, QString body, QWidget *parent = 0);
@ -69,10 +75,10 @@ private:
DescInfo descriptionMsg_; DescInfo descriptionMsg_;
QHBoxLayout *topLayout_; QHBoxLayout *topLayout_;
QVBoxLayout *sideLayout_; // Avatar or Timestamp QVBoxLayout *sideLayout_; // Avatar or Timestamp
QVBoxLayout *mainLayout_; // Header & Message body QVBoxLayout *mainLayout_; // Header & Message body
QHBoxLayout *headerLayout_; // Username (&) Timestamp QHBoxLayout *headerLayout_; // Username (&) Timestamp
Avatar *userAvatar_; Avatar *userAvatar_;
@ -83,7 +89,8 @@ private:
QLabel *body_; QLabel *body_;
}; };
inline DescInfo TimelineItem::descriptionMessage() const inline DescInfo
TimelineItem::descriptionMessage() const
{ {
return descriptionMsg_; return descriptionMsg_;
} }

View file

@ -44,10 +44,10 @@ struct PendingMessage {
TimelineItem *widget; TimelineItem *widget;
PendingMessage(int txn_id, QString body, QString event_id, TimelineItem *widget) PendingMessage(int txn_id, QString body, QString event_id, TimelineItem *widget)
: txn_id(txn_id) : txn_id(txn_id)
, body(body) , body(body)
, event_id(event_id) , event_id(event_id)
, widget(widget) , widget(widget)
{ {
} }
}; };
@ -63,12 +63,21 @@ class TimelineView : public QWidget
Q_OBJECT Q_OBJECT
public: public:
TimelineView(const Timeline &timeline, QSharedPointer<MatrixClient> client, const QString &room_id, QWidget *parent = 0); TimelineView(const Timeline &timeline,
QSharedPointer<MatrixClient> client,
const QString &room_id,
QWidget *parent = 0);
TimelineView(QSharedPointer<MatrixClient> client, const QString &room_id, QWidget *parent = 0); TimelineView(QSharedPointer<MatrixClient> client, const QString &room_id, QWidget *parent = 0);
TimelineItem *createTimelineItem(const events::MessageEvent<msgs::Image> &e, const QString &color, bool with_sender); TimelineItem *createTimelineItem(const events::MessageEvent<msgs::Image> &e,
TimelineItem *createTimelineItem(const events::MessageEvent<msgs::Notice> &e, const QString &color, bool with_sender); const QString &color,
TimelineItem *createTimelineItem(const events::MessageEvent<msgs::Text> &e, const QString &color, bool with_sender); bool with_sender);
TimelineItem *createTimelineItem(const events::MessageEvent<msgs::Notice> &e,
const QString &color,
bool with_sender);
TimelineItem *createTimelineItem(const events::MessageEvent<msgs::Text> &e,
const QString &color,
bool with_sender);
// Add new events at the end of the timeline. // Add new events at the end of the timeline.
int addEvents(const Timeline &timeline); int addEvents(const Timeline &timeline);
@ -137,7 +146,8 @@ private:
QSharedPointer<MatrixClient> client_; QSharedPointer<MatrixClient> client_;
}; };
inline bool TimelineView::isDuplicate(const QString &event_id) inline bool
TimelineView::isDuplicate(const QString &event_id)
{ {
return eventIds_.contains(event_id); return eventIds_.contains(event_id);
} }

View file

@ -70,26 +70,28 @@ private:
int buttonSize_; int buttonSize_;
}; };
inline void TopRoomBar::updateRoomAvatar(const QImage &avatar_image) inline void
TopRoomBar::updateRoomAvatar(const QImage &avatar_image)
{ {
avatar_->setImage(avatar_image); avatar_->setImage(avatar_image);
} }
inline void TopRoomBar::updateRoomAvatar(const QIcon &icon) inline void
TopRoomBar::updateRoomAvatar(const QIcon &icon)
{ {
avatar_->setIcon(icon); avatar_->setIcon(icon);
} }
inline void TopRoomBar::updateRoomName(const QString &name) inline void
TopRoomBar::updateRoomName(const QString &name)
{ {
QString elidedText = QFontMetrics(name_label_->font()) QString elidedText = QFontMetrics(name_label_->font()).elidedText(name, Qt::ElideRight, width() * 0.8);
.elidedText(name, Qt::ElideRight, width() * 0.8);
name_label_->setText(elidedText); name_label_->setText(elidedText);
} }
inline void TopRoomBar::updateRoomTopic(const QString &topic) inline void
TopRoomBar::updateRoomTopic(const QString &topic)
{ {
QString elidedText = QFontMetrics(topic_label_->font()) QString elidedText = QFontMetrics(topic_label_->font()).elidedText(topic, Qt::ElideRight, width() * 0.8);
.elidedText(topic, Qt::ElideRight, width() * 0.8);
topic_label_->setText(elidedText); topic_label_->setText(elidedText);
} }

View file

@ -26,7 +26,9 @@ namespace matrix
{ {
namespace events namespace events
{ {
class AliasesEventContent : public Deserializable, public Serializable class AliasesEventContent
: public Deserializable
, public Serializable
{ {
public: public:
void deserialize(const QJsonValue &data) override; void deserialize(const QJsonValue &data) override;
@ -38,9 +40,10 @@ private:
QList<QString> aliases_; QList<QString> aliases_;
}; };
inline QList<QString> AliasesEventContent::aliases() const inline QList<QString>
AliasesEventContent::aliases() const
{ {
return aliases_; return aliases_;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -30,7 +30,9 @@ namespace events
* A picture that is associated with the room. * A picture that is associated with the room.
*/ */
class AvatarEventContent : public Deserializable, public Serializable class AvatarEventContent
: public Deserializable
, public Serializable
{ {
public: public:
void deserialize(const QJsonValue &data) override; void deserialize(const QJsonValue &data) override;
@ -42,9 +44,10 @@ private:
QUrl url_; QUrl url_;
}; };
inline QUrl AvatarEventContent::url() const inline QUrl
AvatarEventContent::url() const
{ {
return url_; return url_;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -32,7 +32,9 @@ namespace events
* users which alias to use to advertise the room. * users which alias to use to advertise the room.
*/ */
class CanonicalAliasEventContent : public Deserializable, public Serializable class CanonicalAliasEventContent
: public Deserializable
, public Serializable
{ {
public: public:
void deserialize(const QJsonValue &data) override; void deserialize(const QJsonValue &data) override;
@ -44,9 +46,10 @@ private:
QString alias_; QString alias_;
}; };
inline QString CanonicalAliasEventContent::alias() const inline QString
CanonicalAliasEventContent::alias() const
{ {
return alias_; return alias_;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -29,7 +29,9 @@ namespace events
* This is the first event in a room and cannot be changed. It acts as the root of all other events. * This is the first event in a room and cannot be changed. It acts as the root of all other events.
*/ */
class CreateEventContent : public Deserializable, public Serializable class CreateEventContent
: public Deserializable
, public Serializable
{ {
public: public:
void deserialize(const QJsonValue &data) override; void deserialize(const QJsonValue &data) override;
@ -42,9 +44,10 @@ private:
QString creator_; QString creator_;
}; };
inline QString CreateEventContent::creator() const inline QString
CreateEventContent::creator() const
{ {
return creator_; return creator_;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -53,13 +53,18 @@ enum class EventType {
Unsupported, Unsupported,
}; };
EventType extractEventType(const QJsonObject &data); EventType
extractEventType(const QJsonObject &data);
bool isMessageEvent(EventType type); bool
bool isStateEvent(EventType type); isMessageEvent(EventType type);
bool
isStateEvent(EventType type);
template <class Content> template<class Content>
class Event : public Deserializable, public Serializable class Event
: public Deserializable
, public Serializable
{ {
public: public:
inline Content content() const; inline Content content() const;
@ -73,20 +78,23 @@ private:
EventType type_; EventType type_;
}; };
template <class Content> template<class Content>
inline Content Event<Content>::content() const inline Content
Event<Content>::content() const
{ {
return content_; return content_;
} }
template <class Content> template<class Content>
inline EventType Event<Content>::eventType() const inline EventType
Event<Content>::eventType() const
{ {
return type_; return type_;
} }
template <class Content> template<class Content>
void Event<Content>::deserialize(const QJsonValue &data) void
Event<Content>::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("Event is not a JSON object"); throw DeserializationException("Event is not a JSON object");
@ -97,8 +105,9 @@ void Event<Content>::deserialize(const QJsonValue &data)
type_ = extractEventType(object); type_ = extractEventType(object);
} }
template <class Content> template<class Content>
QJsonObject Event<Content>::serialize() const QJsonObject
Event<Content>::serialize() const
{ {
QJsonObject object; QJsonObject object;
@ -145,5 +154,5 @@ QJsonObject Event<Content>::serialize() const
return object; return object;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -32,7 +32,9 @@ enum class HistoryVisibility {
WorldReadable, WorldReadable,
}; };
class HistoryVisibilityEventContent : public Deserializable, public Serializable class HistoryVisibilityEventContent
: public Deserializable
, public Serializable
{ {
public: public:
inline HistoryVisibility historyVisibility() const; inline HistoryVisibility historyVisibility() const;
@ -44,9 +46,10 @@ private:
HistoryVisibility history_visibility_; HistoryVisibility history_visibility_;
}; };
inline HistoryVisibility HistoryVisibilityEventContent::historyVisibility() const inline HistoryVisibility
HistoryVisibilityEventContent::historyVisibility() const
{ {
return history_visibility_; return history_visibility_;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -44,7 +44,9 @@ enum class JoinRule {
* Describes how users are allowed to join the room. * Describes how users are allowed to join the room.
*/ */
class JoinRulesEventContent : public Deserializable, public Serializable class JoinRulesEventContent
: public Deserializable
, public Serializable
{ {
public: public:
void deserialize(const QJsonValue &data) override; void deserialize(const QJsonValue &data) override;
@ -56,9 +58,10 @@ private:
JoinRule join_rule_; JoinRule join_rule_;
}; };
inline JoinRule JoinRulesEventContent::joinRule() const inline JoinRule
JoinRulesEventContent::joinRule() const
{ {
return join_rule_; return join_rule_;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -47,7 +47,9 @@ enum class Membership {
* The current membership state of a user in the room. * The current membership state of a user in the room.
*/ */
class MemberEventContent : public Deserializable, public Serializable class MemberEventContent
: public Deserializable
, public Serializable
{ {
public: public:
void deserialize(const QJsonValue &data) override; void deserialize(const QJsonValue &data) override;
@ -63,19 +65,22 @@ private:
Membership membership_state_; Membership membership_state_;
}; };
inline QUrl MemberEventContent::avatarUrl() const inline QUrl
MemberEventContent::avatarUrl() const
{ {
return avatar_url_; return avatar_url_;
} }
inline QString MemberEventContent::displayName() const inline QString
MemberEventContent::displayName() const
{ {
return display_name_; return display_name_;
} }
inline Membership MemberEventContent::membershipState() const inline Membership
MemberEventContent::membershipState() const
{ {
return membership_state_; return membership_state_;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -24,7 +24,7 @@ namespace matrix
{ {
namespace events namespace events
{ {
template <class MsgContent> template<class MsgContent>
class MessageEvent : public RoomEvent<MessageEventContent> class MessageEvent : public RoomEvent<MessageEventContent>
{ {
public: public:
@ -36,14 +36,16 @@ private:
MsgContent msg_content_; MsgContent msg_content_;
}; };
template <class MsgContent> template<class MsgContent>
inline MsgContent MessageEvent<MsgContent>::msgContent() const inline MsgContent
MessageEvent<MsgContent>::msgContent() const
{ {
return msg_content_; return msg_content_;
} }
template <class MsgContent> template<class MsgContent>
void MessageEvent<MsgContent>::deserialize(const QJsonValue &data) void
MessageEvent<MsgContent>::deserialize(const QJsonValue &data)
{ {
RoomEvent<MessageEventContent>::deserialize(data); RoomEvent<MessageEventContent>::deserialize(data);
@ -59,6 +61,6 @@ struct ThumbnailInfo {
QString mimetype; QString mimetype;
}; };
} // namespace messages } // namespace messages
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -54,9 +54,12 @@ enum class MessageEventType {
Unknown, Unknown,
}; };
MessageEventType extractMessageEventType(const QJsonObject &data); MessageEventType
extractMessageEventType(const QJsonObject &data);
class MessageEventContent : public Deserializable, public Serializable class MessageEventContent
: public Deserializable
, public Serializable
{ {
public: public:
void deserialize(const QJsonValue &data) override; void deserialize(const QJsonValue &data) override;
@ -68,9 +71,10 @@ private:
QString body_; QString body_;
}; };
inline QString MessageEventContent::body() const inline QString
MessageEventContent::body() const
{ {
return body_; return body_;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -29,7 +29,9 @@ namespace events
* A human-friendly room name designed to be displayed to the end-user. * A human-friendly room name designed to be displayed to the end-user.
*/ */
class NameEventContent : public Deserializable, public Serializable class NameEventContent
: public Deserializable
, public Serializable
{ {
public: public:
void deserialize(const QJsonValue &data) override; void deserialize(const QJsonValue &data) override;
@ -41,9 +43,10 @@ private:
QString name_; QString name_;
}; };
inline QString NameEventContent::name() const inline QString
NameEventContent::name() const
{ {
return name_; return name_;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -36,7 +36,9 @@ enum class PowerLevels {
* Defines the power levels (privileges) of users in the room. * Defines the power levels (privileges) of users in the room.
*/ */
class PowerLevelsEventContent : public Deserializable, public Serializable class PowerLevelsEventContent
: public Deserializable
, public Serializable
{ {
public: public:
void deserialize(const QJsonValue &data) override; void deserialize(const QJsonValue &data) override;
@ -68,39 +70,46 @@ private:
QMap<QString, int> users_; QMap<QString, int> users_;
}; };
inline int PowerLevelsEventContent::banLevel() const inline int
PowerLevelsEventContent::banLevel() const
{ {
return ban_; return ban_;
} }
inline int PowerLevelsEventContent::inviteLevel() const inline int
PowerLevelsEventContent::inviteLevel() const
{ {
return invite_; return invite_;
} }
inline int PowerLevelsEventContent::kickLevel() const inline int
PowerLevelsEventContent::kickLevel() const
{ {
return kick_; return kick_;
} }
inline int PowerLevelsEventContent::redactLevel() const inline int
PowerLevelsEventContent::redactLevel() const
{ {
return redact_; return redact_;
} }
inline int PowerLevelsEventContent::eventsDefaultLevel() const inline int
PowerLevelsEventContent::eventsDefaultLevel() const
{ {
return events_default_; return events_default_;
} }
inline int PowerLevelsEventContent::stateDefaultLevel() const inline int
PowerLevelsEventContent::stateDefaultLevel() const
{ {
return state_default_; return state_default_;
} }
inline int PowerLevelsEventContent::usersDefaultLevel() const inline int
PowerLevelsEventContent::usersDefaultLevel() const
{ {
return users_default_; return users_default_;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -26,7 +26,7 @@ namespace matrix
{ {
namespace events namespace events
{ {
template <class Content> template<class Content>
class RoomEvent : public Event<Content> class RoomEvent : public Event<Content>
{ {
public: public:
@ -46,32 +46,37 @@ private:
uint64_t origin_server_ts_; uint64_t origin_server_ts_;
}; };
template <class Content> template<class Content>
inline QString RoomEvent<Content>::eventId() const inline QString
RoomEvent<Content>::eventId() const
{ {
return event_id_; return event_id_;
} }
template <class Content> template<class Content>
inline QString RoomEvent<Content>::roomId() const inline QString
RoomEvent<Content>::roomId() const
{ {
return room_id_; return room_id_;
} }
template <class Content> template<class Content>
inline QString RoomEvent<Content>::sender() const inline QString
RoomEvent<Content>::sender() const
{ {
return sender_; return sender_;
} }
template <class Content> template<class Content>
inline uint64_t RoomEvent<Content>::timestamp() const inline uint64_t
RoomEvent<Content>::timestamp() const
{ {
return origin_server_ts_; return origin_server_ts_;
} }
template <class Content> template<class Content>
void RoomEvent<Content>::deserialize(const QJsonValue &data) void
RoomEvent<Content>::deserialize(const QJsonValue &data)
{ {
Event<Content>::deserialize(data); Event<Content>::deserialize(data);
@ -96,8 +101,9 @@ void RoomEvent<Content>::deserialize(const QJsonValue &data)
origin_server_ts_ = object.value("origin_server_ts").toDouble(); origin_server_ts_ = object.value("origin_server_ts").toDouble();
} }
template <class Content> template<class Content>
QJsonObject RoomEvent<Content>::serialize() const QJsonObject
RoomEvent<Content>::serialize() const
{ {
QJsonObject object = Event<Content>::serialize(); QJsonObject object = Event<Content>::serialize();
@ -108,5 +114,5 @@ QJsonObject RoomEvent<Content>::serialize() const
return object; return object;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -25,7 +25,7 @@ namespace matrix
{ {
namespace events namespace events
{ {
template <class Content> template<class Content>
class StateEvent : public RoomEvent<Content> class StateEvent : public RoomEvent<Content>
{ {
public: public:
@ -40,20 +40,23 @@ private:
Content prev_content_; Content prev_content_;
}; };
template <class Content> template<class Content>
inline QString StateEvent<Content>::stateKey() const inline QString
StateEvent<Content>::stateKey() const
{ {
return state_key_; return state_key_;
} }
template <class Content> template<class Content>
inline Content StateEvent<Content>::previousContent() const inline Content
StateEvent<Content>::previousContent() const
{ {
return prev_content_; return prev_content_;
} }
template <class Content> template<class Content>
void StateEvent<Content>::deserialize(const QJsonValue &data) void
StateEvent<Content>::deserialize(const QJsonValue &data)
{ {
RoomEvent<Content>::deserialize(data); RoomEvent<Content>::deserialize(data);
@ -68,8 +71,9 @@ void StateEvent<Content>::deserialize(const QJsonValue &data)
prev_content_.deserialize(object.value("prev_content")); prev_content_.deserialize(object.value("prev_content"));
} }
template <class Content> template<class Content>
QJsonObject StateEvent<Content>::serialize() const QJsonObject
StateEvent<Content>::serialize() const
{ {
QJsonObject object = RoomEvent<Content>::serialize(); QJsonObject object = RoomEvent<Content>::serialize();
@ -82,5 +86,5 @@ QJsonObject StateEvent<Content>::serialize() const
return object; return object;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -29,7 +29,9 @@ namespace events
* A topic is a short message detailing what is currently being discussed in the room. * A topic is a short message detailing what is currently being discussed in the room.
*/ */
class TopicEventContent : public Deserializable, public Serializable class TopicEventContent
: public Deserializable
, public Serializable
{ {
public: public:
void deserialize(const QJsonValue &data) override; void deserialize(const QJsonValue &data) override;
@ -41,9 +43,10 @@ private:
QString topic_; QString topic_;
}; };
inline QString TopicEventContent::topic() const inline QString
TopicEventContent::topic() const
{ {
return topic_; return topic_;
} }
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -47,16 +47,18 @@ private:
AudioInfo info_; AudioInfo info_;
}; };
inline QString Audio::url() const inline QString
Audio::url() const
{ {
return url_; return url_;
} }
inline AudioInfo Audio::info() const inline AudioInfo
Audio::info() const
{ {
return info_; return info_;
} }
} // namespace messages } // namespace messages
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -32,6 +32,6 @@ class Emote : public Deserializable
public: public:
void deserialize(const QJsonObject &obj) override; void deserialize(const QJsonObject &obj) override;
}; };
} // namespace messages } // namespace messages
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -53,21 +53,24 @@ private:
FileInfo info_; FileInfo info_;
}; };
inline QString File::filename() const inline QString
File::filename() const
{ {
return filename_; return filename_;
} }
inline QString File::url() const inline QString
File::url() const
{ {
return url_; return url_;
} }
inline FileInfo File::info() const inline FileInfo
File::info() const
{ {
return info_; return info_;
} }
} // namespace messages } // namespace messages
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -51,16 +51,18 @@ private:
ImageInfo info_; ImageInfo info_;
}; };
inline QString Image::url() const inline QString
Image::url() const
{ {
return url_; return url_;
} }
inline ImageInfo Image::info() const inline ImageInfo
Image::info() const
{ {
return info_; return info_;
} }
} // namespace messages } // namespace messages
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -47,16 +47,18 @@ private:
LocationInfo info_; LocationInfo info_;
}; };
inline QString Location::geoUri() const inline QString
Location::geoUri() const
{ {
return geo_uri_; return geo_uri_;
} }
inline LocationInfo Location::info() const inline LocationInfo
Location::info() const
{ {
return info_; return info_;
} }
} // namespace messages } // namespace messages
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -32,6 +32,6 @@ class Notice : public Deserializable
public: public:
void deserialize(const QJsonObject &obj) override; void deserialize(const QJsonObject &obj) override;
}; };
} // namespace messages } // namespace messages
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -32,6 +32,6 @@ class Text : public Deserializable
public: public:
void deserialize(const QJsonObject &obj) override; void deserialize(const QJsonObject &obj) override;
}; };
} // namespace messages } // namespace messages
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -52,16 +52,18 @@ private:
VideoInfo info_; VideoInfo info_;
}; };
inline QString Video::url() const inline QString
Video::url() const
{ {
return url_; return url_;
} }
inline VideoInfo Video::info() const inline VideoInfo
Video::info() const
{ {
return info_; return info_;
} }
} // namespace messages } // namespace messages
} // namespace events } // namespace events
} // namespace matrix } // namespace matrix

View file

@ -80,35 +80,41 @@ private:
int angle_; int angle_;
}; };
inline void CircularProgressDelegate::setDashOffset(qreal offset) inline void
CircularProgressDelegate::setDashOffset(qreal offset)
{ {
dash_offset_ = offset; dash_offset_ = offset;
progress_->update(); progress_->update();
} }
inline void CircularProgressDelegate::setDashLength(qreal length) inline void
CircularProgressDelegate::setDashLength(qreal length)
{ {
dash_length_ = length; dash_length_ = length;
progress_->update(); progress_->update();
} }
inline void CircularProgressDelegate::setAngle(int angle) inline void
CircularProgressDelegate::setAngle(int angle)
{ {
angle_ = angle; angle_ = angle;
progress_->update(); progress_->update();
} }
inline qreal CircularProgressDelegate::dashOffset() const inline qreal
CircularProgressDelegate::dashOffset() const
{ {
return dash_offset_; return dash_offset_;
} }
inline qreal CircularProgressDelegate::dashLength() const inline qreal
CircularProgressDelegate::dashLength() const
{ {
return dash_length_; return dash_length_;
} }
inline int CircularProgressDelegate::angle() const inline int
CircularProgressDelegate::angle() const
{ {
return angle_; return angle_;
} }

View file

@ -30,7 +30,8 @@ public:
gradient.setStart(right0); gradient.setStart(right0);
gradient.setFinalStop(right1); gradient.setFinalStop(right1);
painter.setBrush(QBrush(gradient)); painter.setBrush(QBrush(gradient));
painter.drawRoundRect(QRectF(QPointF(width - margin * radius, margin), QPointF(width, height - margin)), 0.0, 0.0); painter.drawRoundRect(
QRectF(QPointF(width - margin * radius, margin), QPointF(width, height - margin)), 0.0, 0.0);
// Left // Left
QPointF left0(margin, height / 2); QPointF left0(margin, height / 2);
@ -54,7 +55,8 @@ public:
gradient.setStart(bottom0); gradient.setStart(bottom0);
gradient.setFinalStop(bottom1); gradient.setFinalStop(bottom1);
painter.setBrush(QBrush(gradient)); painter.setBrush(QBrush(gradient));
painter.drawRoundRect(QRectF(QPointF(margin, height - margin), QPointF(width - margin, height)), 0.0, 0.0); painter.drawRoundRect(
QRectF(QPointF(margin, height - margin), QPointF(width - margin, height)), 0.0, 0.0);
// BottomRight // BottomRight
QPointF bottomright0(width - margin, height - margin); QPointF bottomright0(width - margin, height - margin);
@ -95,6 +97,7 @@ public:
// Widget // Widget
painter.setBrush(QBrush("#FFFFFF")); painter.setBrush(QBrush("#FFFFFF"));
painter.setRenderHint(QPainter::Antialiasing); painter.setRenderHint(QPainter::Antialiasing);
painter.drawRoundRect(QRectF(QPointF(margin, margin), QPointF(width - margin, height - margin)), radius, radius); painter.drawRoundRect(
QRectF(QPointF(margin, margin), QPointF(width - margin, height - margin)), radius, radius);
} }
}; };

View file

@ -63,12 +63,14 @@ private:
bool was_checked_; bool was_checked_;
}; };
inline qreal FlatButtonStateMachine::overlayOpacity() const inline qreal
FlatButtonStateMachine::overlayOpacity() const
{ {
return overlay_opacity_; return overlay_opacity_;
} }
inline qreal FlatButtonStateMachine::checkedOverlayProgress() const inline qreal
FlatButtonStateMachine::checkedOverlayProgress() const
{ {
return checked_overlay_progress_; return checked_overlay_progress_;
} }
@ -86,8 +88,13 @@ class FlatButton : public QPushButton
public: public:
explicit FlatButton(QWidget *parent = 0, ui::ButtonPreset preset = ui::ButtonPreset::FlatPreset); explicit FlatButton(QWidget *parent = 0, ui::ButtonPreset preset = ui::ButtonPreset::FlatPreset);
explicit FlatButton(const QString &text, QWidget *parent = 0, ui::ButtonPreset preset = ui::ButtonPreset::FlatPreset); explicit FlatButton(const QString &text,
FlatButton(const QString &text, ui::Role role, QWidget *parent = 0, ui::ButtonPreset preset = ui::ButtonPreset::FlatPreset); QWidget *parent = 0,
ui::ButtonPreset preset = ui::ButtonPreset::FlatPreset);
FlatButton(const QString &text,
ui::Role role,
QWidget *parent = 0,
ui::ButtonPreset preset = ui::ButtonPreset::FlatPreset);
~FlatButton(); ~FlatButton();
void applyPreset(ui::ButtonPreset preset); void applyPreset(ui::ButtonPreset preset);

View file

@ -8,16 +8,16 @@ class Menu : public QMenu
{ {
public: public:
Menu(QWidget *parent = nullptr) Menu(QWidget *parent = nullptr)
: QMenu(parent) : QMenu(parent)
{ {
QFont font; QFont font;
font.setPixelSize(conf::fontSize); font.setPixelSize(conf::fontSize);
setFont(font); setFont(font);
setStyleSheet( setStyleSheet("QMenu { color: black; background-color: white; margin: 0px;}"
"QMenu { color: black; background-color: white; margin: 0px;}" "QMenu::item { color: black; padding: 7px 20px; border: 1px solid transparent; margin: "
"QMenu::item { color: black; padding: 7px 20px; border: 1px solid transparent; margin: 2px 0px; }" "2px 0px; }"
"QMenu::item:selected { color: black; background: rgba(180, 180, 180, 100); }"); "QMenu::item:selected { color: black; background: rgba(180, 180, 180, 100); }");
}; };
protected: protected:

View file

@ -46,13 +46,15 @@ private:
QPropertyAnimation *animation_; QPropertyAnimation *animation_;
}; };
inline void OverlayModal::setDuration(int duration) inline void
OverlayModal::setDuration(int duration)
{ {
duration_ = duration; duration_ = duration;
animation_->setDuration(duration_); animation_->setDuration(duration_);
} }
inline void OverlayModal::setColor(QColor color) inline void
OverlayModal::setColor(QColor color)
{ {
color_ = color; color_ = color;
} }

View file

@ -66,67 +66,80 @@ private:
QBrush brush_; QBrush brush_;
}; };
inline void Ripple::setOverlay(RippleOverlay *overlay) inline void
Ripple::setOverlay(RippleOverlay *overlay)
{ {
overlay_ = overlay; overlay_ = overlay;
} }
inline qreal Ripple::radius() const inline qreal
Ripple::radius() const
{ {
return radius_; return radius_;
} }
inline qreal Ripple::opacity() const inline qreal
Ripple::opacity() const
{ {
return opacity_; return opacity_;
} }
inline QColor Ripple::color() const inline QColor
Ripple::color() const
{ {
return brush_.color(); return brush_.color();
} }
inline QBrush Ripple::brush() const inline QBrush
Ripple::brush() const
{ {
return brush_; return brush_;
} }
inline QPoint Ripple::center() const inline QPoint
Ripple::center() const
{ {
return center_; return center_;
} }
inline QPropertyAnimation *Ripple::radiusAnimation() const inline QPropertyAnimation *
Ripple::radiusAnimation() const
{ {
return radius_anim_; return radius_anim_;
} }
inline QPropertyAnimation *Ripple::opacityAnimation() const inline QPropertyAnimation *
Ripple::opacityAnimation() const
{ {
return opacity_anim_; return opacity_anim_;
} }
inline void Ripple::setOpacityStartValue(qreal value) inline void
Ripple::setOpacityStartValue(qreal value)
{ {
opacity_anim_->setStartValue(value); opacity_anim_->setStartValue(value);
} }
inline void Ripple::setOpacityEndValue(qreal value) inline void
Ripple::setOpacityEndValue(qreal value)
{ {
opacity_anim_->setEndValue(value); opacity_anim_->setEndValue(value);
} }
inline void Ripple::setRadiusStartValue(qreal value) inline void
Ripple::setRadiusStartValue(qreal value)
{ {
radius_anim_->setStartValue(value); radius_anim_->setStartValue(value);
} }
inline void Ripple::setRadiusEndValue(qreal value) inline void
Ripple::setRadiusEndValue(qreal value)
{ {
radius_anim_->setEndValue(value); radius_anim_->setEndValue(value);
} }
inline void Ripple::setDuration(int msecs) inline void
Ripple::setDuration(int msecs)
{ {
radius_anim_->setDuration(msecs); radius_anim_->setDuration(msecs);
opacity_anim_->setDuration(msecs); opacity_anim_->setDuration(msecs);

View file

@ -37,18 +37,21 @@ private:
bool use_clip_; bool use_clip_;
}; };
inline void RippleOverlay::setClipping(bool enable) inline void
RippleOverlay::setClipping(bool enable)
{ {
use_clip_ = enable; use_clip_ = enable;
update(); update();
} }
inline bool RippleOverlay::hasClipping() const inline bool
RippleOverlay::hasClipping() const
{ {
return use_clip_; return use_clip_;
} }
inline void RippleOverlay::setClipPath(const QPainterPath &path) inline void
RippleOverlay::setClipPath(const QPainterPath &path)
{ {
clip_path_ = path; clip_path_ = path;
update(); update();

View file

@ -92,34 +92,40 @@ private:
qreal y_; qreal y_;
}; };
inline void TextFieldLabel::setColor(const QColor &color) inline void
TextFieldLabel::setColor(const QColor &color)
{ {
color_ = color; color_ = color;
update(); update();
} }
inline void TextFieldLabel::setOffset(const QPointF &pos) inline void
TextFieldLabel::setOffset(const QPointF &pos)
{ {
x_ = pos.x(); x_ = pos.x();
y_ = pos.y(); y_ = pos.y();
update(); update();
} }
inline void TextFieldLabel::setScale(qreal scale) inline void
TextFieldLabel::setScale(qreal scale)
{ {
scale_ = scale; scale_ = scale;
update(); update();
} }
inline QPointF TextFieldLabel::offset() const inline QPointF
TextFieldLabel::offset() const
{ {
return QPointF(x_, y_); return QPointF(x_, y_);
} }
inline qreal TextFieldLabel::scale() const inline qreal
TextFieldLabel::scale() const
{ {
return scale_; return scale_;
} }
inline QColor TextFieldLabel::color() const inline QColor
TextFieldLabel::color() const
{ {
return color_; return color_;
} }
@ -155,13 +161,15 @@ private:
qreal progress_; qreal progress_;
}; };
inline void TextFieldStateMachine::setProgress(qreal progress) inline void
TextFieldStateMachine::setProgress(qreal progress)
{ {
progress_ = progress; progress_ = progress;
text_field_->update(); text_field_->update();
} }
inline qreal TextFieldStateMachine::progress() const inline qreal
TextFieldStateMachine::progress() const
{ {
return progress_; return progress_;
} }

View file

@ -6,11 +6,7 @@
namespace ui namespace ui
{ {
enum class AvatarType { enum class AvatarType { Icon, Image, Letter };
Icon,
Image,
Letter
};
namespace sidebar namespace sidebar
{ {
@ -23,38 +19,17 @@ const int FontSize = 16;
// Default avatar size. Width and height. // Default avatar size. Width and height.
const int AvatarSize = 40; const int AvatarSize = 40;
enum class ButtonPreset { enum class ButtonPreset { FlatPreset, CheckablePreset };
FlatPreset,
CheckablePreset
};
enum class RippleStyle { enum class RippleStyle { CenteredRipple, PositionedRipple, NoRipple };
CenteredRipple,
PositionedRipple,
NoRipple
};
enum class OverlayStyle { enum class OverlayStyle { NoOverlay, TintedOverlay, GrayOverlay };
NoOverlay,
TintedOverlay,
GrayOverlay
};
enum class Role { enum class Role { Default, Primary, Secondary };
Default,
Primary,
Secondary
};
enum class ButtonIconPlacement { enum class ButtonIconPlacement { LeftIcon, RightIcon };
LeftIcon,
RightIcon
};
enum class ProgressType { enum class ProgressType { DeterminateProgress, IndeterminateProgress };
DeterminateProgress,
IndeterminateProgress
};
enum class Color { enum class Color {
Black, Black,
@ -70,7 +45,7 @@ enum class Color {
Transparent Transparent
}; };
} // namespace ui } // namespace ui
class Theme : public QObject class Theme : public QObject
{ {

View file

@ -23,7 +23,8 @@ private:
Theme *theme_; Theme *theme_;
}; };
inline ThemeManager &ThemeManager::instance() inline ThemeManager &
ThemeManager::instance()
{ {
static ThemeManager instance; static ThemeManager instance;
return instance; return instance;

View file

@ -23,14 +23,16 @@ QMap<QString, QImage> AvatarProvider::userAvatars_;
QMap<QString, QUrl> AvatarProvider::avatarUrls_; QMap<QString, QUrl> AvatarProvider::avatarUrls_;
QMap<QString, QList<TimelineItem *>> AvatarProvider::toBeResolved_; QMap<QString, QList<TimelineItem *>> AvatarProvider::toBeResolved_;
void AvatarProvider::init(QSharedPointer<MatrixClient> client) void
AvatarProvider::init(QSharedPointer<MatrixClient> client)
{ {
client_ = client; client_ = client;
connect(client_.data(), &MatrixClient::userAvatarRetrieved, &AvatarProvider::updateAvatar); connect(client_.data(), &MatrixClient::userAvatarRetrieved, &AvatarProvider::updateAvatar);
} }
void AvatarProvider::updateAvatar(const QString &uid, const QImage &img) void
AvatarProvider::updateAvatar(const QString &uid, const QImage &img)
{ {
if (toBeResolved_.contains(uid)) { if (toBeResolved_.contains(uid)) {
auto items = toBeResolved_[uid]; auto items = toBeResolved_[uid];
@ -45,7 +47,8 @@ void AvatarProvider::updateAvatar(const QString &uid, const QImage &img)
userAvatars_.insert(uid, img); userAvatars_.insert(uid, img);
} }
void AvatarProvider::resolve(const QString &userId, TimelineItem *item) void
AvatarProvider::resolve(const QString &userId, TimelineItem *item)
{ {
if (userAvatars_.contains(userId)) { if (userAvatars_.contains(userId)) {
auto img = userAvatars_[userId]; auto img = userAvatars_[userId];
@ -70,12 +73,14 @@ void AvatarProvider::resolve(const QString &userId, TimelineItem *item)
} }
} }
void AvatarProvider::setAvatarUrl(const QString &userId, const QUrl &url) void
AvatarProvider::setAvatarUrl(const QString &userId, const QUrl &url)
{ {
avatarUrls_.insert(userId, url); avatarUrls_.insert(userId, url);
} }
void AvatarProvider::clear() void
AvatarProvider::clear()
{ {
userAvatars_.clear(); userAvatars_.clear();
avatarUrls_.clear(); avatarUrls_.clear();

View file

@ -31,11 +31,11 @@ static const lmdb::val NEXT_BATCH_KEY("next_batch");
static const lmdb::val transactionID("transaction_id"); static const lmdb::val transactionID("transaction_id");
Cache::Cache(const QString &userId) Cache::Cache(const QString &userId)
: env_{nullptr} : env_{ nullptr }
, stateDb_{0} , stateDb_{ 0 }
, roomDb_{0} , roomDb_{ 0 }
, isMounted_{false} , isMounted_{ false }
, userId_{userId} , userId_{ userId }
{ {
auto statePath = QString("%1/%2/state") auto statePath = QString("%1/%2/state")
.arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)) .arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation))
@ -51,7 +51,8 @@ Cache::Cache(const QString &userId)
qDebug() << "[cache] First time initializing LMDB"; qDebug() << "[cache] First time initializing LMDB";
if (!QDir().mkpath(statePath)) { if (!QDir().mkpath(statePath)) {
throw std::runtime_error(("Unable to create state directory:" + statePath).toStdString().c_str()); throw std::runtime_error(
("Unable to create state directory:" + statePath).toStdString().c_str());
} }
} }
@ -83,7 +84,8 @@ Cache::Cache(const QString &userId)
isMounted_ = true; isMounted_ = true;
} }
void Cache::insertRoomState(const QString &roomid, const RoomState &state) void
Cache::insertRoomState(const QString &roomid, const RoomState &state)
{ {
if (!isMounted_) if (!isMounted_)
return; return;
@ -93,11 +95,7 @@ void Cache::insertRoomState(const QString &roomid, const RoomState &state)
auto stateEvents = QJsonDocument(state.serialize()).toBinaryData(); auto stateEvents = QJsonDocument(state.serialize()).toBinaryData();
auto id = roomid.toUtf8(); auto id = roomid.toUtf8();
lmdb::dbi_put( lmdb::dbi_put(txn, roomDb_, lmdb::val(id.data(), id.size()), lmdb::val(stateEvents.data(), stateEvents.size()));
txn,
roomDb_,
lmdb::val(id.data(), id.size()),
lmdb::val(stateEvents.data(), stateEvents.size()));
for (const auto &membership : state.memberships) { for (const auto &membership : state.memberships) {
lmdb::dbi membersDb = lmdb::dbi::open(txn, roomid.toStdString().c_str(), MDB_CREATE); lmdb::dbi membersDb = lmdb::dbi::open(txn, roomid.toStdString().c_str(), MDB_CREATE);
@ -111,21 +109,19 @@ void Cache::insertRoomState(const QString &roomid, const RoomState &state)
// We add or update (e.g invite -> join) a new user to the membership list. // We add or update (e.g invite -> join) a new user to the membership list.
case events::Membership::Invite: case events::Membership::Invite:
case events::Membership::Join: { case events::Membership::Join: {
lmdb::dbi_put( lmdb::dbi_put(txn,
txn, membersDb,
membersDb, lmdb::val(key.data(), key.size()),
lmdb::val(key.data(), key.size()), lmdb::val(memberEvent.data(), memberEvent.size()));
lmdb::val(memberEvent.data(), memberEvent.size()));
break; break;
} }
// We remove the user from the membership list. // We remove the user from the membership list.
case events::Membership::Leave: case events::Membership::Leave:
case events::Membership::Ban: { case events::Membership::Ban: {
lmdb::dbi_del( lmdb::dbi_del(txn,
txn, membersDb,
membersDb, lmdb::val(key.data(), key.size()),
lmdb::val(key.data(), key.size()), lmdb::val(memberEvent.data(), memberEvent.size()));
lmdb::val(memberEvent.data(), memberEvent.size()));
break; break;
} }
case events::Membership::Knock: { case events::Membership::Knock: {
@ -138,7 +134,8 @@ void Cache::insertRoomState(const QString &roomid, const RoomState &state)
txn.commit(); txn.commit();
} }
QMap<QString, RoomState> Cache::states() QMap<QString, RoomState>
Cache::states()
{ {
QMap<QString, RoomState> states; QMap<QString, RoomState> states;
@ -166,7 +163,8 @@ QMap<QString, RoomState> Cache::states()
while (memberCursor.get(memberId, memberContent, MDB_NEXT)) { while (memberCursor.get(memberId, memberContent, MDB_NEXT)) {
auto userid = QString::fromUtf8(memberId.data(), memberId.size()); auto userid = QString::fromUtf8(memberId.data(), memberId.size());
auto data = QJsonDocument::fromBinaryData(QByteArray(memberContent.data(), memberContent.size())); auto data =
QJsonDocument::fromBinaryData(QByteArray(memberContent.data(), memberContent.size()));
try { try {
events::StateEvent<events::MemberEventContent> member; events::StateEvent<events::MemberEventContent> member;
@ -194,7 +192,8 @@ QMap<QString, RoomState> Cache::states()
return states; return states;
} }
void Cache::setNextBatchToken(const QString &token) void
Cache::setNextBatchToken(const QString &token)
{ {
auto txn = lmdb::txn::begin(env_); auto txn = lmdb::txn::begin(env_);
auto value = token.toUtf8(); auto value = token.toUtf8();
@ -204,7 +203,8 @@ void Cache::setNextBatchToken(const QString &token)
txn.commit(); txn.commit();
} }
bool Cache::isInitialized() bool
Cache::isInitialized()
{ {
auto txn = lmdb::txn::begin(env_, nullptr, MDB_RDONLY); auto txn = lmdb::txn::begin(env_, nullptr, MDB_RDONLY);
lmdb::val token; lmdb::val token;
@ -216,7 +216,8 @@ bool Cache::isInitialized()
return res; return res;
} }
QString Cache::nextBatchToken() QString
Cache::nextBatchToken()
{ {
auto txn = lmdb::txn::begin(env_, nullptr, MDB_RDONLY); auto txn = lmdb::txn::begin(env_, nullptr, MDB_RDONLY);
lmdb::val token; lmdb::val token;

View file

@ -43,9 +43,9 @@
namespace events = matrix::events; namespace events = matrix::events;
ChatPage::ChatPage(QSharedPointer<MatrixClient> client, QWidget *parent) ChatPage::ChatPage(QSharedPointer<MatrixClient> client, QWidget *parent)
: QWidget(parent) : QWidget(parent)
, sync_interval_(2000) , sync_interval_(2000)
, client_(client) , client_(client)
{ {
setStyleSheet("background-color: #f8fbfe;"); setStyleSheet("background-color: #f8fbfe;");
@ -168,23 +168,18 @@ ChatPage::ChatPage(QSharedPointer<MatrixClient> client, QWidget *parent)
SIGNAL(syncCompleted(const SyncResponse &)), SIGNAL(syncCompleted(const SyncResponse &)),
this, this,
SLOT(syncCompleted(const SyncResponse &))); SLOT(syncCompleted(const SyncResponse &)));
connect(client_.data(), connect(client_.data(), SIGNAL(syncFailed(const QString &)), this, SLOT(syncFailed(const QString &)));
SIGNAL(syncFailed(const QString &)),
this,
SLOT(syncFailed(const QString &)));
connect(client_.data(), connect(client_.data(),
SIGNAL(getOwnProfileResponse(const QUrl &, const QString &)), SIGNAL(getOwnProfileResponse(const QUrl &, const QString &)),
this, this,
SLOT(updateOwnProfileInfo(const QUrl &, const QString &))); SLOT(updateOwnProfileInfo(const QUrl &, const QString &)));
connect(client_.data(), connect(client_.data(), SIGNAL(ownAvatarRetrieved(const QPixmap &)), this, SLOT(setOwnAvatar(const QPixmap &)));
SIGNAL(ownAvatarRetrieved(const QPixmap &)),
this,
SLOT(setOwnAvatar(const QPixmap &)));
AvatarProvider::init(client); AvatarProvider::init(client);
} }
void ChatPage::logout() void
ChatPage::logout()
{ {
sync_timer_->stop(); sync_timer_->stop();
@ -217,7 +212,8 @@ void ChatPage::logout()
emit close(); emit close();
} }
void ChatPage::bootstrap(QString userid, QString homeserver, QString token) void
ChatPage::bootstrap(QString userid, QString homeserver, QString token)
{ {
client_->setServer(homeserver); client_->setServer(homeserver);
client_->setAccessToken(token); client_->setAccessToken(token);
@ -235,24 +231,28 @@ void ChatPage::bootstrap(QString userid, QString homeserver, QString token)
client_->initialSync(); client_->initialSync();
} }
void ChatPage::startSync() void
ChatPage::startSync()
{ {
client_->sync(); client_->sync();
} }
void ChatPage::setOwnAvatar(const QPixmap &img) void
ChatPage::setOwnAvatar(const QPixmap &img)
{ {
user_info_widget_->setAvatar(img.toImage()); user_info_widget_->setAvatar(img.toImage());
} }
void ChatPage::syncFailed(const QString &msg) void
ChatPage::syncFailed(const QString &msg)
{ {
qWarning() << "Sync error:" << msg; qWarning() << "Sync error:" << msg;
sync_timer_->start(sync_interval_ * 5); sync_timer_->start(sync_interval_ * 5);
} }
// TODO: Should be moved in another class that manages this global list. // TODO: Should be moved in another class that manages this global list.
void ChatPage::updateDisplayNames(const RoomState &state) void
ChatPage::updateDisplayNames(const RoomState &state)
{ {
for (const auto member : state.memberships) { for (const auto member : state.memberships) {
auto displayName = member.content().displayName(); auto displayName = member.content().displayName();
@ -262,7 +262,8 @@ void ChatPage::updateDisplayNames(const RoomState &state)
} }
} }
void ChatPage::syncCompleted(const SyncResponse &response) void
ChatPage::syncCompleted(const SyncResponse &response)
{ {
// TODO: Catch exception // TODO: Catch exception
cache_->setNextBatchToken(response.nextBatch()); cache_->setNextBatchToken(response.nextBatch());
@ -309,7 +310,8 @@ void ChatPage::syncCompleted(const SyncResponse &response)
sync_timer_->start(sync_interval_); sync_timer_->start(sync_interval_);
} }
void ChatPage::initialSyncCompleted(const SyncResponse &response) void
ChatPage::initialSyncCompleted(const SyncResponse &response)
{ {
if (!response.nextBatch().isEmpty()) if (!response.nextBatch().isEmpty())
client_->setNextBatchToken(response.nextBatch()); client_->setNextBatchToken(response.nextBatch());
@ -367,7 +369,8 @@ void ChatPage::initialSyncCompleted(const SyncResponse &response)
emit contentLoaded(); emit contentLoaded();
} }
void ChatPage::updateTopBarAvatar(const QString &roomid, const QPixmap &img) void
ChatPage::updateTopBarAvatar(const QString &roomid, const QPixmap &img)
{ {
room_avatars_.insert(roomid, img); room_avatars_.insert(roomid, img);
@ -377,7 +380,8 @@ void ChatPage::updateTopBarAvatar(const QString &roomid, const QPixmap &img)
top_bar_->updateRoomAvatar(img.toImage()); top_bar_->updateRoomAvatar(img.toImage());
} }
void ChatPage::updateOwnProfileInfo(const QUrl &avatar_url, const QString &display_name) void
ChatPage::updateOwnProfileInfo(const QUrl &avatar_url, const QString &display_name)
{ {
QSettings settings; QSettings settings;
auto userid = settings.value("auth/user_id").toString(); auto userid = settings.value("auth/user_id").toString();
@ -389,7 +393,8 @@ void ChatPage::updateOwnProfileInfo(const QUrl &avatar_url, const QString &displ
client_->fetchOwnAvatar(avatar_url); client_->fetchOwnAvatar(avatar_url);
} }
void ChatPage::changeTopRoomInfo(const QString &room_id) void
ChatPage::changeTopRoomInfo(const QString &room_id)
{ {
if (!state_manager_.contains(room_id)) if (!state_manager_.contains(room_id))
return; return;
@ -408,7 +413,8 @@ void ChatPage::changeTopRoomInfo(const QString &room_id)
current_room_ = room_id; current_room_ = room_id;
} }
void ChatPage::showUnreadMessageNotification(int count) void
ChatPage::showUnreadMessageNotification(int count)
{ {
emit unreadMessages(count); emit unreadMessages(count);
@ -419,7 +425,8 @@ void ChatPage::showUnreadMessageNotification(int count)
emit changeWindowTitle(QString("nheko (%1)").arg(count)); emit changeWindowTitle(QString("nheko (%1)").arg(count));
} }
void ChatPage::updateRoomState(RoomState &room_state, const QJsonArray &events) void
ChatPage::updateRoomState(RoomState &room_state, const QJsonArray &events)
{ {
events::EventType ty; events::EventType ty;
@ -509,7 +516,8 @@ void ChatPage::updateRoomState(RoomState &room_state, const QJsonArray &events)
} }
} }
void ChatPage::loadStateFromCache() void
ChatPage::loadStateFromCache()
{ {
qDebug() << "Restoring state from cache"; qDebug() << "Restoring state from cache";
@ -564,7 +572,8 @@ void ChatPage::loadStateFromCache()
sync_timer_->start(sync_interval_); sync_timer_->start(sync_interval_);
} }
void ChatPage::keyPressEvent(QKeyEvent *event) void
ChatPage::keyPressEvent(QKeyEvent *event)
{ {
if (event->key() == Qt::Key_K) { if (event->key() == Qt::Key_K) {
if (event->modifiers() == Qt::ControlModifier) if (event->modifiers() == Qt::ControlModifier)
@ -572,7 +581,8 @@ void ChatPage::keyPressEvent(QKeyEvent *event)
} }
} }
void ChatPage::showQuickSwitcher() void
ChatPage::showQuickSwitcher()
{ {
if (quickSwitcher_ == nullptr) { if (quickSwitcher_ == nullptr) {
quickSwitcher_ = new QuickSwitcher(this); quickSwitcher_ = new QuickSwitcher(this);

View file

@ -22,11 +22,12 @@
#include "Deserializable.h" #include "Deserializable.h"
DeserializationException::DeserializationException(const std::string &msg) DeserializationException::DeserializationException(const std::string &msg)
: msg_(msg) : msg_(msg)
{ {
} }
const char *DeserializationException::what() const noexcept const char *
DeserializationException::what() const noexcept
{ {
return msg_.c_str(); return msg_.c_str();
} }

View file

@ -22,7 +22,7 @@
#include "EmojiCategory.h" #include "EmojiCategory.h"
EmojiCategory::EmojiCategory(QString category, QList<Emoji> emoji, QWidget *parent) EmojiCategory::EmojiCategory(QString category, QList<Emoji> emoji, QWidget *parent)
: QWidget(parent) : QWidget(parent)
{ {
mainLayout_ = new QVBoxLayout(this); mainLayout_ = new QVBoxLayout(this);
mainLayout_->setMargin(0); mainLayout_->setMargin(0);

View file

@ -21,7 +21,7 @@
#include "EmojiItemDelegate.h" #include "EmojiItemDelegate.h"
EmojiItemDelegate::EmojiItemDelegate(QObject *parent) EmojiItemDelegate::EmojiItemDelegate(QObject *parent)
: QStyledItemDelegate(parent) : QStyledItemDelegate(parent)
{ {
data_ = new Emoji; data_ = new Emoji;
} }
@ -31,7 +31,8 @@ EmojiItemDelegate::~EmojiItemDelegate()
delete data_; delete data_;
} }
void EmojiItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const void
EmojiItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{ {
Q_UNUSED(index); Q_UNUSED(index);

View file

@ -27,19 +27,18 @@
#include "FlatButton.h" #include "FlatButton.h"
EmojiPanel::EmojiPanel(QWidget *parent) EmojiPanel::EmojiPanel(QWidget *parent)
: QWidget(parent) : QWidget(parent)
, shadowMargin_{2} , shadowMargin_{ 2 }
, width_{370} , width_{ 370 }
, height_{350} , height_{ 350 }
, animationDuration_{100} , animationDuration_{ 100 }
, categoryIconSize_{20} , categoryIconSize_{ 20 }
{ {
setStyleSheet( setStyleSheet("QWidget {background: #f8fbfe; color: #e8e8e8; border: none;}"
"QWidget {background: #f8fbfe; color: #e8e8e8; border: none;}" "QScrollBar:vertical { background-color: #f8fbfe; width: 8px; margin: 0px 2px 0 2px; }"
"QScrollBar:vertical { background-color: #f8fbfe; width: 8px; margin: 0px 2px 0 2px; }" "QScrollBar::handle:vertical { background-color: #d6dde3; min-height: 20px; }"
"QScrollBar::handle:vertical { background-color: #d6dde3; min-height: 20px; }" "QScrollBar::add-line:vertical { border: none; background: none; }"
"QScrollBar::add-line:vertical { border: none; background: none; }" "QScrollBar::sub-line:vertical { border: none; background: none; }");
"QScrollBar::sub-line:vertical { border: none; background: none; }");
setAttribute(Qt::WA_TranslucentBackground, true); setAttribute(Qt::WA_TranslucentBackground, true);
setAttribute(Qt::WA_ShowWithoutActivating, true); setAttribute(Qt::WA_ShowWithoutActivating, true);
@ -160,9 +159,7 @@ EmojiPanel::EmojiPanel(QWidget *parent)
animation_->setEndValue(0); animation_->setEndValue(0);
connect(peopleEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected); connect(peopleEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected);
connect(peopleCategory, &QPushButton::clicked, [this, peopleEmoji]() { connect(peopleCategory, &QPushButton::clicked, [this, peopleEmoji]() { this->showEmojiCategory(peopleEmoji); });
this->showEmojiCategory(peopleEmoji);
});
connect(natureEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected); connect(natureEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected);
connect(natureCategory_, &QPushButton::clicked, [this, natureEmoji]() { connect(natureCategory_, &QPushButton::clicked, [this, natureEmoji]() {
@ -170,9 +167,7 @@ EmojiPanel::EmojiPanel(QWidget *parent)
}); });
connect(foodEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected); connect(foodEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected);
connect(foodCategory_, &QPushButton::clicked, [this, foodEmoji]() { connect(foodCategory_, &QPushButton::clicked, [this, foodEmoji]() { this->showEmojiCategory(foodEmoji); });
this->showEmojiCategory(foodEmoji);
});
connect(activityEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected); connect(activityEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected);
connect(activityCategory, &QPushButton::clicked, [this, activityEmoji]() { connect(activityCategory, &QPushButton::clicked, [this, activityEmoji]() {
@ -180,9 +175,7 @@ EmojiPanel::EmojiPanel(QWidget *parent)
}); });
connect(travelEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected); connect(travelEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected);
connect(travelCategory, &QPushButton::clicked, [this, travelEmoji]() { connect(travelCategory, &QPushButton::clicked, [this, travelEmoji]() { this->showEmojiCategory(travelEmoji); });
this->showEmojiCategory(travelEmoji);
});
connect(objectsEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected); connect(objectsEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected);
connect(objectsCategory, &QPushButton::clicked, [this, objectsEmoji]() { connect(objectsCategory, &QPushButton::clicked, [this, objectsEmoji]() {
@ -195,9 +188,7 @@ EmojiPanel::EmojiPanel(QWidget *parent)
}); });
connect(flagsEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected); connect(flagsEmoji, &EmojiCategory::emojiSelected, this, &EmojiPanel::emojiSelected);
connect(flagsCategory, &QPushButton::clicked, [this, flagsEmoji]() { connect(flagsCategory, &QPushButton::clicked, [this, flagsEmoji]() { this->showEmojiCategory(flagsEmoji); });
this->showEmojiCategory(flagsEmoji);
});
connect(animation_, &QAbstractAnimation::finished, [this]() { connect(animation_, &QAbstractAnimation::finished, [this]() {
if (animation_->direction() == QAbstractAnimation::Forward) if (animation_->direction() == QAbstractAnimation::Forward)
@ -205,7 +196,8 @@ EmojiPanel::EmojiPanel(QWidget *parent)
}); });
} }
void EmojiPanel::showEmojiCategory(const EmojiCategory *category) void
EmojiPanel::showEmojiCategory(const EmojiCategory *category)
{ {
auto posToGo = category->mapToParent(QPoint()).y(); auto posToGo = category->mapToParent(QPoint()).y();
auto current = scrollArea_->verticalScrollBar()->value(); auto current = scrollArea_->verticalScrollBar()->value();
@ -225,14 +217,16 @@ void EmojiPanel::showEmojiCategory(const EmojiCategory *category)
this->scrollArea_->ensureVisible(0, posToGo, 0, 0); this->scrollArea_->ensureVisible(0, posToGo, 0, 0);
} }
void EmojiPanel::leaveEvent(QEvent *event) void
EmojiPanel::leaveEvent(QEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
fadeOut(); fadeOut();
} }
void EmojiPanel::paintEvent(QPaintEvent *event) void
EmojiPanel::paintEvent(QPaintEvent *event)
{ {
QPainter p(this); QPainter p(this);
DropShadow::draw(p, DropShadow::draw(p,
@ -249,13 +243,15 @@ void EmojiPanel::paintEvent(QPaintEvent *event)
QWidget::paintEvent(event); QWidget::paintEvent(event);
} }
void EmojiPanel::fadeOut() void
EmojiPanel::fadeOut()
{ {
animation_->setDirection(QAbstractAnimation::Forward); animation_->setDirection(QAbstractAnimation::Forward);
animation_->start(); animation_->start();
} }
void EmojiPanel::fadeIn() void
EmojiPanel::fadeIn()
{ {
animation_->setDirection(QAbstractAnimation::Backward); animation_->setDirection(QAbstractAnimation::Backward);
animation_->start(); animation_->start();

View file

@ -20,12 +20,13 @@
#include "EmojiPickButton.h" #include "EmojiPickButton.h"
EmojiPickButton::EmojiPickButton(QWidget *parent) EmojiPickButton::EmojiPickButton(QWidget *parent)
: FlatButton(parent) : FlatButton(parent)
, panel_{nullptr} , panel_{ nullptr }
{ {
} }
void EmojiPickButton::enterEvent(QEvent *e) void
EmojiPickButton::enterEvent(QEvent *e)
{ {
Q_UNUSED(e); Q_UNUSED(e);
@ -47,7 +48,8 @@ void EmojiPickButton::enterEvent(QEvent *e)
panel_->show(); panel_->show();
} }
void EmojiPickButton::leaveEvent(QEvent *e) void
EmojiPickButton::leaveEvent(QEvent *e)
{ {
Q_UNUSED(e); Q_UNUSED(e);

File diff suppressed because it is too large Load diff

View file

@ -28,10 +28,12 @@
namespace events = matrix::events; namespace events = matrix::events;
namespace msgs = matrix::events::messages; namespace msgs = matrix::events::messages;
ImageItem::ImageItem(QSharedPointer<MatrixClient> client, const events::MessageEvent<msgs::Image> &event, QWidget *parent) ImageItem::ImageItem(QSharedPointer<MatrixClient> client,
: QWidget(parent) const events::MessageEvent<msgs::Image> &event,
, event_{event} QWidget *parent)
, client_{client} : QWidget(parent)
, event_{ event }
, client_{ client }
{ {
setMouseTracking(true); setMouseTracking(true);
setCursor(Qt::PointingHandCursor); setCursor(Qt::PointingHandCursor);
@ -58,7 +60,8 @@ ImageItem::ImageItem(QSharedPointer<MatrixClient> client, const events::MessageE
SLOT(imageDownloaded(const QString &, const QPixmap &))); SLOT(imageDownloaded(const QString &, const QPixmap &)));
} }
void ImageItem::imageDownloaded(const QString &event_id, const QPixmap &img) void
ImageItem::imageDownloaded(const QString &event_id, const QPixmap &img)
{ {
if (event_id != event_.eventId()) if (event_id != event_.eventId())
return; return;
@ -66,7 +69,8 @@ void ImageItem::imageDownloaded(const QString &event_id, const QPixmap &img)
setImage(img); setImage(img);
} }
void ImageItem::openUrl() void
ImageItem::openUrl()
{ {
if (url_.toString().isEmpty()) if (url_.toString().isEmpty())
return; return;
@ -75,7 +79,8 @@ void ImageItem::openUrl()
qWarning() << "Could not open url" << url_.toString(); qWarning() << "Could not open url" << url_.toString();
} }
void ImageItem::scaleImage() void
ImageItem::scaleImage()
{ {
if (image_.isNull()) if (image_.isNull())
return; return;
@ -97,7 +102,8 @@ void ImageItem::scaleImage()
scaled_image_ = image_.scaled(width_, height_, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); scaled_image_ = image_.scaled(width_, height_, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
} }
QSize ImageItem::sizeHint() const QSize
ImageItem::sizeHint() const
{ {
if (image_.isNull()) if (image_.isNull())
return QSize(max_width_, bottom_height_); return QSize(max_width_, bottom_height_);
@ -105,14 +111,16 @@ QSize ImageItem::sizeHint() const
return QSize(width_, height_); return QSize(width_, height_);
} }
void ImageItem::setImage(const QPixmap &image) void
ImageItem::setImage(const QPixmap &image)
{ {
image_ = image; image_ = image;
scaleImage(); scaleImage();
update(); update();
} }
void ImageItem::mousePressEvent(QMouseEvent *event) void
ImageItem::mousePressEvent(QMouseEvent *event)
{ {
if (event->button() != Qt::LeftButton) if (event->button() != Qt::LeftButton)
return; return;
@ -133,14 +141,16 @@ void ImageItem::mousePressEvent(QMouseEvent *event)
} }
} }
void ImageItem::resizeEvent(QResizeEvent *event) void
ImageItem::resizeEvent(QResizeEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
scaleImage(); scaleImage();
} }
void ImageItem::paintEvent(QPaintEvent *event) void
ImageItem::paintEvent(QPaintEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);

View file

@ -25,8 +25,8 @@
#include "ImageOverlayDialog.h" #include "ImageOverlayDialog.h"
ImageOverlayDialog::ImageOverlayDialog(QPixmap image, QWidget *parent) ImageOverlayDialog::ImageOverlayDialog(QPixmap image, QWidget *parent)
: QWidget{parent} : QWidget{ parent }
, originalImage_{image} , originalImage_{ image }
{ {
setMouseTracking(true); setMouseTracking(true);
setParent(0); setParent(0);
@ -49,7 +49,8 @@ ImageOverlayDialog::ImageOverlayDialog(QPixmap image, QWidget *parent)
} }
// TODO: Move this into Utils // TODO: Move this into Utils
void ImageOverlayDialog::scaleImage(int max_width, int max_height) void
ImageOverlayDialog::scaleImage(int max_width, int max_height)
{ {
if (originalImage_.isNull()) if (originalImage_.isNull())
return; return;
@ -73,7 +74,8 @@ void ImageOverlayDialog::scaleImage(int max_width, int max_height)
image_ = originalImage_.scaled(final_width, final_height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); image_ = originalImage_.scaled(final_width, final_height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
} }
void ImageOverlayDialog::paintEvent(QPaintEvent *event) void
ImageOverlayDialog::paintEvent(QPaintEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
@ -115,7 +117,8 @@ void ImageOverlayDialog::paintEvent(QPaintEvent *event)
painter.drawLine(center + QPointF(15, -15), center - QPointF(15, -15)); painter.drawLine(center + QPointF(15, -15), center - QPointF(15, -15));
} }
void ImageOverlayDialog::mousePressEvent(QMouseEvent *event) void
ImageOverlayDialog::mousePressEvent(QMouseEvent *event)
{ {
if (event->button() != Qt::LeftButton) if (event->button() != Qt::LeftButton)
return; return;

View file

@ -27,12 +27,13 @@ LoginRequest::LoginRequest()
} }
LoginRequest::LoginRequest(QString username, QString password) LoginRequest::LoginRequest(QString username, QString password)
: user_(username) : user_(username)
, password_(password) , password_(password)
{ {
} }
QByteArray LoginRequest::serialize() noexcept QByteArray
LoginRequest::serialize() noexcept
{ {
#if defined(Q_OS_MAC) #if defined(Q_OS_MAC)
QString initialDeviceName("nheko on Mac OS"); QString initialDeviceName("nheko on Mac OS");
@ -45,16 +46,17 @@ QByteArray LoginRequest::serialize() noexcept
#endif #endif
QJsonObject body{ QJsonObject body{
{"type", "m.login.password"}, { "type", "m.login.password" },
{"user", user_}, { "user", user_ },
{"password", password_}, { "password", password_ },
{"initial_device_display_name", initialDeviceName}, { "initial_device_display_name", initialDeviceName },
}; };
return QJsonDocument(body).toJson(QJsonDocument::Compact); return QJsonDocument(body).toJson(QJsonDocument::Compact);
} }
void LoginResponse::deserialize(const QJsonDocument &data) void
LoginResponse::deserialize(const QJsonDocument &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("Login response is not a JSON object"); throw DeserializationException("Login response is not a JSON object");

View file

@ -22,9 +22,9 @@
#include "LoginPage.h" #include "LoginPage.h"
LoginPage::LoginPage(QSharedPointer<MatrixClient> client, QWidget *parent) LoginPage::LoginPage(QSharedPointer<MatrixClient> client, QWidget *parent)
: QWidget(parent) : QWidget(parent)
, inferredServerAddress_() , inferredServerAddress_()
, client_{client} , client_{ client }
{ {
setStyleSheet("background-color: #f9f9f9"); setStyleSheet("background-color: #f9f9f9");
@ -159,12 +159,14 @@ LoginPage::LoginPage(QSharedPointer<MatrixClient> client, QWidget *parent)
matrixid_input_->setValidator(&InputValidator::Id); matrixid_input_->setValidator(&InputValidator::Id);
} }
void LoginPage::loginError(QString error) void
LoginPage::loginError(QString error)
{ {
error_label_->setText(error); error_label_->setText(error);
} }
void LoginPage::onMatrixIdEntered() void
LoginPage::onMatrixIdEntered()
{ {
error_label_->setText(""); error_label_->setText("");
@ -197,7 +199,8 @@ void LoginPage::onMatrixIdEntered()
} }
} }
void LoginPage::onServerAddressEntered() void
LoginPage::onServerAddressEntered()
{ {
error_label_->setText(""); error_label_->setText("");
client_->setServer(serverInput_->text()); client_->setServer(serverInput_->text());
@ -209,10 +212,12 @@ void LoginPage::onServerAddressEntered()
spinner_->show(); spinner_->show();
} }
void LoginPage::versionError(QString error) void
LoginPage::versionError(QString error)
{ {
// Matrix homeservers are often kept on a subdomain called 'matrix' // Matrix homeservers are often kept on a subdomain called 'matrix'
// so let's try that next, unless the address was set explicitly or the domain part of the username already points to this subdomain // so let's try that next, unless the address was set explicitly or the domain part of the username already
// points to this subdomain
QUrl currentServer = client_->getHomeServer(); QUrl currentServer = client_->getHomeServer();
QString mxidAddress = matrixid_input_->text().split(":").at(1); QString mxidAddress = matrixid_input_->text().split(":").at(1);
if (currentServer.host() == inferredServerAddress_ && !currentServer.host().startsWith("matrix")) { if (currentServer.host() == inferredServerAddress_ && !currentServer.host().startsWith("matrix")) {
@ -234,7 +239,8 @@ void LoginPage::versionError(QString error)
matrixidLayout_->removeWidget(spinner_); matrixidLayout_->removeWidget(spinner_);
} }
void LoginPage::versionSuccess() void
LoginPage::versionSuccess()
{ {
serverLayout_->removeWidget(spinner_); serverLayout_->removeWidget(spinner_);
matrixidLayout_->removeWidget(spinner_); matrixidLayout_->removeWidget(spinner_);
@ -244,7 +250,8 @@ void LoginPage::versionSuccess()
serverInput_->hide(); serverInput_->hide();
} }
void LoginPage::onLoginButtonClicked() void
LoginPage::onLoginButtonClicked()
{ {
error_label_->setText(""); error_label_->setText("");
@ -260,7 +267,8 @@ void LoginPage::onLoginButtonClicked()
} }
} }
void LoginPage::reset() void
LoginPage::reset()
{ {
matrixid_input_->clear(); matrixid_input_->clear();
password_input_->clear(); password_input_->clear();
@ -275,7 +283,8 @@ void LoginPage::reset()
inferredServerAddress_.clear(); inferredServerAddress_.clear();
} }
void LoginPage::onBackButtonClicked() void
LoginPage::onBackButtonClicked()
{ {
emit backButtonClicked(); emit backButtonClicked();
} }

View file

@ -23,7 +23,7 @@
#include "Theme.h" #include "Theme.h"
LogoutDialog::LogoutDialog(QWidget *parent) LogoutDialog::LogoutDialog(QWidget *parent)
: QFrame(parent) : QFrame(parent)
{ {
setMaximumSize(400, 400); setMaximumSize(400, 400);
setStyleSheet("background-color: #f9f9f9"); setStyleSheet("background-color: #f9f9f9");

View file

@ -15,8 +15,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "Config.h"
#include "MainWindow.h" #include "MainWindow.h"
#include "Config.h"
#include <QLayout> #include <QLayout>
#include <QNetworkReply> #include <QNetworkReply>
@ -26,9 +26,9 @@
MainWindow *MainWindow::instance_ = nullptr; MainWindow *MainWindow::instance_ = nullptr;
MainWindow::MainWindow(QWidget *parent) MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent) : QMainWindow(parent)
, progress_modal_{nullptr} , progress_modal_{ nullptr }
, spinner_{nullptr} , spinner_{ nullptr }
{ {
QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
setSizePolicy(sizePolicy); setSizePolicy(sizePolicy);
@ -94,7 +94,8 @@ MainWindow::MainWindow(QWidget *parent)
} }
} }
void MainWindow::restoreWindowSize() void
MainWindow::restoreWindowSize()
{ {
QSettings settings; QSettings settings;
int savedWidth = settings.value("window/width").toInt(); int savedWidth = settings.value("window/width").toInt();
@ -106,7 +107,8 @@ void MainWindow::restoreWindowSize()
resize(savedWidth, savedheight); resize(savedWidth, savedheight);
} }
void MainWindow::saveCurrentWindowSize() void
MainWindow::saveCurrentWindowSize()
{ {
QSettings settings; QSettings settings;
QSize current = size(); QSize current = size();
@ -115,7 +117,8 @@ void MainWindow::saveCurrentWindowSize()
settings.setValue("window/height", current.height()); settings.setValue("window/height", current.height());
} }
void MainWindow::removeOverlayProgressBar() void
MainWindow::removeOverlayProgressBar()
{ {
QTimer *timer = new QTimer(this); QTimer *timer = new QTimer(this);
timer->setSingleShot(true); timer->setSingleShot(true);
@ -138,7 +141,8 @@ void MainWindow::removeOverlayProgressBar()
timer->start(500); timer->start(500);
} }
void MainWindow::showChatPage(QString userid, QString homeserver, QString token) void
MainWindow::showChatPage(QString userid, QString homeserver, QString token)
{ {
QSettings settings; QSettings settings;
settings.setValue("auth/access_token", token); settings.setValue("auth/access_token", token);
@ -174,7 +178,8 @@ void MainWindow::showChatPage(QString userid, QString homeserver, QString token)
instance_ = this; instance_ = this;
} }
void MainWindow::showWelcomePage() void
MainWindow::showWelcomePage()
{ {
int index = sliding_stack_->getWidgetIndex(welcome_page_); int index = sliding_stack_->getWidgetIndex(welcome_page_);
@ -184,19 +189,22 @@ void MainWindow::showWelcomePage()
sliding_stack_->slideInIndex(index, SlidingStackWidget::AnimationDirection::LEFT_TO_RIGHT); sliding_stack_->slideInIndex(index, SlidingStackWidget::AnimationDirection::LEFT_TO_RIGHT);
} }
void MainWindow::showLoginPage() void
MainWindow::showLoginPage()
{ {
int index = sliding_stack_->getWidgetIndex(login_page_); int index = sliding_stack_->getWidgetIndex(login_page_);
sliding_stack_->slideInIndex(index, SlidingStackWidget::AnimationDirection::LEFT_TO_RIGHT); sliding_stack_->slideInIndex(index, SlidingStackWidget::AnimationDirection::LEFT_TO_RIGHT);
} }
void MainWindow::showRegisterPage() void
MainWindow::showRegisterPage()
{ {
int index = sliding_stack_->getWidgetIndex(register_page_); int index = sliding_stack_->getWidgetIndex(register_page_);
sliding_stack_->slideInIndex(index, SlidingStackWidget::AnimationDirection::RIGHT_TO_LEFT); sliding_stack_->slideInIndex(index, SlidingStackWidget::AnimationDirection::RIGHT_TO_LEFT);
} }
void MainWindow::closeEvent(QCloseEvent *event) void
MainWindow::closeEvent(QCloseEvent *event)
{ {
if (isVisible()) { if (isVisible()) {
event->ignore(); event->ignore();
@ -204,7 +212,8 @@ void MainWindow::closeEvent(QCloseEvent *event)
} }
} }
void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason) void
MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{ {
switch (reason) { switch (reason) {
case QSystemTrayIcon::Trigger: case QSystemTrayIcon::Trigger:
@ -219,16 +228,17 @@ void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
} }
} }
bool MainWindow::hasActiveUser() bool
MainWindow::hasActiveUser()
{ {
QSettings settings; QSettings settings;
return settings.contains("auth/access_token") && return settings.contains("auth/access_token") && settings.contains("auth/home_server") &&
settings.contains("auth/home_server") &&
settings.contains("auth/user_id"); settings.contains("auth/user_id");
} }
MainWindow *MainWindow::instance() MainWindow *
MainWindow::instance()
{ {
return instance_; return instance_;
} }

View file

@ -33,7 +33,7 @@
#include "Versions.h" #include "Versions.h"
MatrixClient::MatrixClient(QString server, QObject *parent) MatrixClient::MatrixClient(QString server, QObject *parent)
: QNetworkAccessManager(parent) : QNetworkAccessManager(parent)
{ {
server_ = "https://" + server; server_ = "https://" + server;
api_url_ = "/_matrix/client/r0"; api_url_ = "/_matrix/client/r0";
@ -45,7 +45,8 @@ MatrixClient::MatrixClient(QString server, QObject *parent)
connect(this, SIGNAL(finished(QNetworkReply *)), this, SLOT(onResponse(QNetworkReply *))); connect(this, SIGNAL(finished(QNetworkReply *)), this, SLOT(onResponse(QNetworkReply *)));
} }
void MatrixClient::reset() noexcept void
MatrixClient::reset() noexcept
{ {
next_batch_ = ""; next_batch_ = "";
server_ = ""; server_ = "";
@ -54,7 +55,8 @@ void MatrixClient::reset() noexcept
txn_id_ = 0; txn_id_ = 0;
} }
void MatrixClient::onVersionsResponse(QNetworkReply *reply) void
MatrixClient::onVersionsResponse(QNetworkReply *reply)
{ {
reply->deleteLater(); reply->deleteLater();
@ -88,7 +90,8 @@ void MatrixClient::onVersionsResponse(QNetworkReply *reply)
} }
} }
void MatrixClient::onLoginResponse(QNetworkReply *reply) void
MatrixClient::onLoginResponse(QNetworkReply *reply)
{ {
reply->deleteLater(); reply->deleteLater();
@ -124,7 +127,8 @@ void MatrixClient::onLoginResponse(QNetworkReply *reply)
} }
} }
void MatrixClient::onLogoutResponse(QNetworkReply *reply) void
MatrixClient::onLogoutResponse(QNetworkReply *reply)
{ {
reply->deleteLater(); reply->deleteLater();
@ -138,7 +142,8 @@ void MatrixClient::onLogoutResponse(QNetworkReply *reply)
emit loggedOut(); emit loggedOut();
} }
void MatrixClient::onRegisterResponse(QNetworkReply *reply) void
MatrixClient::onRegisterResponse(QNetworkReply *reply)
{ {
reply->deleteLater(); reply->deleteLater();
@ -160,16 +165,15 @@ void MatrixClient::onRegisterResponse(QNetworkReply *reply)
try { try {
response.deserialize(json); response.deserialize(json);
emit registerSuccess(response.getUserId(), emit registerSuccess(response.getUserId(), response.getHomeServer(), response.getAccessToken());
response.getHomeServer(),
response.getAccessToken());
} catch (DeserializationException &e) { } catch (DeserializationException &e) {
qWarning() << "Register" << e.what(); qWarning() << "Register" << e.what();
emit registerError("Received malformed response."); emit registerError("Received malformed response.");
} }
} }
void MatrixClient::onGetOwnProfileResponse(QNetworkReply *reply) void
MatrixClient::onGetOwnProfileResponse(QNetworkReply *reply)
{ {
reply->deleteLater(); reply->deleteLater();
@ -193,7 +197,8 @@ void MatrixClient::onGetOwnProfileResponse(QNetworkReply *reply)
} }
} }
void MatrixClient::onInitialSyncResponse(QNetworkReply *reply) void
MatrixClient::onInitialSyncResponse(QNetworkReply *reply)
{ {
reply->deleteLater(); reply->deleteLater();
@ -223,7 +228,8 @@ void MatrixClient::onInitialSyncResponse(QNetworkReply *reply)
emit initialSyncCompleted(response); emit initialSyncCompleted(response);
} }
void MatrixClient::onSyncResponse(QNetworkReply *reply) void
MatrixClient::onSyncResponse(QNetworkReply *reply)
{ {
reply->deleteLater(); reply->deleteLater();
@ -251,7 +257,8 @@ void MatrixClient::onSyncResponse(QNetworkReply *reply)
} }
} }
void MatrixClient::onSendTextMessageResponse(QNetworkReply *reply) void
MatrixClient::onSendTextMessageResponse(QNetworkReply *reply)
{ {
reply->deleteLater(); reply->deleteLater();
@ -286,7 +293,8 @@ void MatrixClient::onSendTextMessageResponse(QNetworkReply *reply)
reply->property("txn_id").toInt()); reply->property("txn_id").toInt());
} }
void MatrixClient::onRoomAvatarResponse(QNetworkReply *reply) void
MatrixClient::onRoomAvatarResponse(QNetworkReply *reply)
{ {
reply->deleteLater(); reply->deleteLater();
@ -310,7 +318,8 @@ void MatrixClient::onRoomAvatarResponse(QNetworkReply *reply)
emit roomAvatarRetrieved(roomid, pixmap); emit roomAvatarRetrieved(roomid, pixmap);
} }
void MatrixClient::onUserAvatarResponse(QNetworkReply *reply) void
MatrixClient::onUserAvatarResponse(QNetworkReply *reply)
{ {
reply->deleteLater(); reply->deleteLater();
@ -333,7 +342,8 @@ void MatrixClient::onUserAvatarResponse(QNetworkReply *reply)
emit userAvatarRetrieved(roomid, img); emit userAvatarRetrieved(roomid, img);
} }
void MatrixClient::onGetOwnAvatarResponse(QNetworkReply *reply) void
MatrixClient::onGetOwnAvatarResponse(QNetworkReply *reply)
{ {
reply->deleteLater(); reply->deleteLater();
@ -355,7 +365,8 @@ void MatrixClient::onGetOwnAvatarResponse(QNetworkReply *reply)
emit ownAvatarRetrieved(pixmap); emit ownAvatarRetrieved(pixmap);
} }
void MatrixClient::onImageResponse(QNetworkReply *reply) void
MatrixClient::onImageResponse(QNetworkReply *reply)
{ {
reply->deleteLater(); reply->deleteLater();
@ -379,7 +390,8 @@ void MatrixClient::onImageResponse(QNetworkReply *reply)
emit imageDownloaded(event_id, pixmap); emit imageDownloaded(event_id, pixmap);
} }
void MatrixClient::onMessagesResponse(QNetworkReply *reply) void
MatrixClient::onMessagesResponse(QNetworkReply *reply)
{ {
reply->deleteLater(); reply->deleteLater();
@ -405,7 +417,8 @@ void MatrixClient::onMessagesResponse(QNetworkReply *reply)
emit messagesRetrieved(room_id, msgs); emit messagesRetrieved(room_id, msgs);
} }
void MatrixClient::onResponse(QNetworkReply *reply) void
MatrixClient::onResponse(QNetworkReply *reply)
{ {
switch (static_cast<Endpoint>(reply->property("endpoint").toInt())) { switch (static_cast<Endpoint>(reply->property("endpoint").toInt())) {
case Endpoint::Versions: case Endpoint::Versions:
@ -452,7 +465,8 @@ void MatrixClient::onResponse(QNetworkReply *reply)
} }
} }
void MatrixClient::login(const QString &username, const QString &password) noexcept void
MatrixClient::login(const QString &username, const QString &password) noexcept
{ {
QUrl endpoint(server_); QUrl endpoint(server_);
endpoint.setPath(api_url_ + "/login"); endpoint.setPath(api_url_ + "/login");
@ -466,7 +480,8 @@ void MatrixClient::login(const QString &username, const QString &password) noexc
reply->setProperty("endpoint", static_cast<int>(Endpoint::Login)); reply->setProperty("endpoint", static_cast<int>(Endpoint::Login));
} }
void MatrixClient::logout() noexcept void
MatrixClient::logout() noexcept
{ {
QUrlQuery query; QUrlQuery query;
query.addQueryItem("access_token", token_); query.addQueryItem("access_token", token_);
@ -483,7 +498,8 @@ void MatrixClient::logout() noexcept
reply->setProperty("endpoint", static_cast<int>(Endpoint::Logout)); reply->setProperty("endpoint", static_cast<int>(Endpoint::Logout));
} }
void MatrixClient::registerUser(const QString &user, const QString &pass, const QString &server) noexcept void
MatrixClient::registerUser(const QString &user, const QString &pass, const QString &server) noexcept
{ {
setServer(server); setServer(server);
@ -503,11 +519,11 @@ void MatrixClient::registerUser(const QString &user, const QString &pass, const
reply->setProperty("endpoint", static_cast<int>(Endpoint::Register)); reply->setProperty("endpoint", static_cast<int>(Endpoint::Register));
} }
void MatrixClient::sync() noexcept void
MatrixClient::sync() noexcept
{ {
QJsonObject filter{{"room", QJsonObject filter{ { "room", QJsonObject{ { "ephemeral", QJsonObject{ { "limit", 0 } } } } },
QJsonObject{{"ephemeral", QJsonObject{{"limit", 0}}}}}, { "presence", QJsonObject{ { "limit", 0 } } } };
{"presence", QJsonObject{{"limit", 0}}}};
QUrlQuery query; QUrlQuery query;
query.addQueryItem("set_presence", "online"); query.addQueryItem("set_presence", "online");
@ -532,7 +548,8 @@ void MatrixClient::sync() noexcept
reply->setProperty("endpoint", static_cast<int>(Endpoint::Sync)); reply->setProperty("endpoint", static_cast<int>(Endpoint::Sync));
} }
void MatrixClient::sendTextMessage(const QString &roomid, const QString &msg) noexcept void
MatrixClient::sendTextMessage(const QString &roomid, const QString &msg) noexcept
{ {
QUrlQuery query; QUrlQuery query;
query.addQueryItem("access_token", token_); query.addQueryItem("access_token", token_);
@ -541,9 +558,7 @@ void MatrixClient::sendTextMessage(const QString &roomid, const QString &msg) no
endpoint.setPath(api_url_ + QString("/rooms/%1/send/m.room.message/%2").arg(roomid).arg(txn_id_)); endpoint.setPath(api_url_ + QString("/rooms/%1/send/m.room.message/%2").arg(roomid).arg(txn_id_));
endpoint.setQuery(query); endpoint.setQuery(query);
QJsonObject body{ QJsonObject body{ { "msgtype", "m.text" }, { "body", msg } };
{"msgtype", "m.text"},
{"body", msg}};
QNetworkRequest request(QString(endpoint.toEncoded())); QNetworkRequest request(QString(endpoint.toEncoded()));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
@ -557,16 +572,17 @@ void MatrixClient::sendTextMessage(const QString &roomid, const QString &msg) no
incrementTransactionId(); incrementTransactionId();
} }
void MatrixClient::initialSync() noexcept void
MatrixClient::initialSync() noexcept
{ {
QJsonArray excluded_presence = { QJsonArray excluded_presence = {
QString("m.presence"), QString("m.presence"),
}; };
QJsonObject filter{{"room", QJsonObject filter{ { "room",
QJsonObject{{"timeline", QJsonObject{{"limit", 20}}}, QJsonObject{ { "timeline", QJsonObject{ { "limit", 20 } } },
{"ephemeral", QJsonObject{{"limit", 0}}}}}, { "ephemeral", QJsonObject{ { "limit", 0 } } } } },
{"presence", QJsonObject{{"not_types", excluded_presence}}}}; { "presence", QJsonObject{ { "not_types", excluded_presence } } } };
QUrlQuery query; QUrlQuery query;
query.addQueryItem("full_state", "true"); query.addQueryItem("full_state", "true");
@ -584,7 +600,8 @@ void MatrixClient::initialSync() noexcept
reply->setProperty("endpoint", static_cast<int>(Endpoint::InitialSync)); reply->setProperty("endpoint", static_cast<int>(Endpoint::InitialSync));
} }
void MatrixClient::versions() noexcept void
MatrixClient::versions() noexcept
{ {
QUrl endpoint(server_); QUrl endpoint(server_);
endpoint.setPath("/_matrix/client/versions"); endpoint.setPath("/_matrix/client/versions");
@ -595,7 +612,8 @@ void MatrixClient::versions() noexcept
reply->setProperty("endpoint", static_cast<int>(Endpoint::Versions)); reply->setProperty("endpoint", static_cast<int>(Endpoint::Versions));
} }
void MatrixClient::getOwnProfile() noexcept void
MatrixClient::getOwnProfile() noexcept
{ {
// FIXME: Remove settings from the matrix client. The class should store the user's matrix ID. // FIXME: Remove settings from the matrix client. The class should store the user's matrix ID.
QSettings settings; QSettings settings;
@ -614,7 +632,8 @@ void MatrixClient::getOwnProfile() noexcept
reply->setProperty("endpoint", static_cast<int>(Endpoint::GetOwnProfile)); reply->setProperty("endpoint", static_cast<int>(Endpoint::GetOwnProfile));
} }
void MatrixClient::fetchRoomAvatar(const QString &roomid, const QUrl &avatar_url) void
MatrixClient::fetchRoomAvatar(const QString &roomid, const QUrl &avatar_url)
{ {
QList<QString> url_parts = avatar_url.toString().split("mxc://"); QList<QString> url_parts = avatar_url.toString().split("mxc://");
@ -640,7 +659,8 @@ void MatrixClient::fetchRoomAvatar(const QString &roomid, const QUrl &avatar_url
reply->setProperty("endpoint", static_cast<int>(Endpoint::RoomAvatar)); reply->setProperty("endpoint", static_cast<int>(Endpoint::RoomAvatar));
} }
void MatrixClient::fetchUserAvatar(const QString &userId, const QUrl &avatarUrl) void
MatrixClient::fetchUserAvatar(const QString &userId, const QUrl &avatarUrl)
{ {
QList<QString> url_parts = avatarUrl.toString().split("mxc://"); QList<QString> url_parts = avatarUrl.toString().split("mxc://");
@ -666,7 +686,8 @@ void MatrixClient::fetchUserAvatar(const QString &userId, const QUrl &avatarUrl)
reply->setProperty("endpoint", static_cast<int>(Endpoint::UserAvatar)); reply->setProperty("endpoint", static_cast<int>(Endpoint::UserAvatar));
} }
void MatrixClient::downloadImage(const QString &event_id, const QUrl &url) void
MatrixClient::downloadImage(const QString &event_id, const QUrl &url)
{ {
QNetworkRequest image_request(url); QNetworkRequest image_request(url);
@ -675,7 +696,8 @@ void MatrixClient::downloadImage(const QString &event_id, const QUrl &url)
reply->setProperty("endpoint", static_cast<int>(Endpoint::Image)); reply->setProperty("endpoint", static_cast<int>(Endpoint::Image));
} }
void MatrixClient::fetchOwnAvatar(const QUrl &avatar_url) void
MatrixClient::fetchOwnAvatar(const QUrl &avatar_url)
{ {
QList<QString> url_parts = avatar_url.toString().split("mxc://"); QList<QString> url_parts = avatar_url.toString().split("mxc://");
@ -700,7 +722,8 @@ void MatrixClient::fetchOwnAvatar(const QUrl &avatar_url)
reply->setProperty("endpoint", static_cast<int>(Endpoint::GetOwnAvatar)); reply->setProperty("endpoint", static_cast<int>(Endpoint::GetOwnAvatar));
} }
void MatrixClient::messages(const QString &room_id, const QString &from_token, int limit) noexcept void
MatrixClient::messages(const QString &room_id, const QString &from_token, int limit) noexcept
{ {
QUrlQuery query; QUrlQuery query;
query.addQueryItem("access_token", token_); query.addQueryItem("access_token", token_);

View file

@ -22,7 +22,8 @@
#include "Deserializable.h" #include "Deserializable.h"
#include "Profile.h" #include "Profile.h"
void ProfileResponse::deserialize(const QJsonDocument &data) void
ProfileResponse::deserialize(const QJsonDocument &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("Response is not a JSON object"); throw DeserializationException("Response is not a JSON object");

View file

@ -23,19 +23,21 @@
#include "QuickSwitcher.h" #include "QuickSwitcher.h"
RoomSearchInput::RoomSearchInput(QWidget* parent) RoomSearchInput::RoomSearchInput(QWidget *parent)
: TextField(parent) : TextField(parent)
{ {
} }
bool RoomSearchInput::focusNextPrevChild(bool next) bool
RoomSearchInput::focusNextPrevChild(bool next)
{ {
Q_UNUSED(next); Q_UNUSED(next);
return false; return false;
} }
void RoomSearchInput::keyPressEvent(QKeyEvent* event) void
RoomSearchInput::keyPressEvent(QKeyEvent *event)
{ {
if (event->key() == Qt::Key_Tab) { if (event->key() == Qt::Key_Tab) {
auto completer = this->completer(); auto completer = this->completer();
@ -55,8 +57,8 @@ void RoomSearchInput::keyPressEvent(QKeyEvent* event)
TextField::keyPressEvent(event); TextField::keyPressEvent(event);
} }
QuickSwitcher::QuickSwitcher(QWidget* parent) QuickSwitcher::QuickSwitcher(QWidget *parent)
: QFrame(parent) : QFrame(parent)
{ {
setMaximumWidth(400); setMaximumWidth(400);
setStyleSheet("background-color: #f9f9f9"); setStyleSheet("background-color: #f9f9f9");
@ -69,7 +71,7 @@ QuickSwitcher::QuickSwitcher(QWidget* parent)
roomSearch_->setPlaceholderText(tr("Find a room...")); roomSearch_->setPlaceholderText(tr("Find a room..."));
QStringList wordList; QStringList wordList;
QCompleter* completer = new QCompleter(wordList, this); QCompleter *completer = new QCompleter(wordList, this);
completer->setCaseSensitivity(Qt::CaseInsensitive); completer->setCaseSensitivity(Qt::CaseInsensitive);
roomSearch_->setCompleter(completer); roomSearch_->setCompleter(completer);
@ -87,7 +89,8 @@ QuickSwitcher::QuickSwitcher(QWidget* parent)
}); });
} }
void QuickSwitcher::setRoomList(const QMap<QString, QString>& rooms) void
QuickSwitcher::setRoomList(const QMap<QString, QString> &rooms)
{ {
rooms_ = rooms; rooms_ = rooms;
@ -99,12 +102,14 @@ void QuickSwitcher::setRoomList(const QMap<QString, QString>& rooms)
roomSearch_->completer()->setModel(new QStringListModel(search_items)); roomSearch_->completer()->setModel(new QStringListModel(search_items));
} }
void QuickSwitcher::showEvent(QShowEvent*) void
QuickSwitcher::showEvent(QShowEvent *)
{ {
roomSearch_->setFocus(); roomSearch_->setFocus();
} }
void QuickSwitcher::keyPressEvent(QKeyEvent* event) void
QuickSwitcher::keyPressEvent(QKeyEvent *event)
{ {
if (event->key() == Qt::Key_Escape) { if (event->key() == Qt::Key_Escape) {
roomSearch_->clear(); roomSearch_->clear();

View file

@ -23,21 +23,21 @@
#include "Register.h" #include "Register.h"
RegisterRequest::RegisterRequest(const QString &username, const QString &password) RegisterRequest::RegisterRequest(const QString &username, const QString &password)
: user_(username) : user_(username)
, password_(password) , password_(password)
{ {
} }
QByteArray RegisterRequest::serialize() noexcept QByteArray
RegisterRequest::serialize() noexcept
{ {
QJsonObject body{ QJsonObject body{ { "username", user_ }, { "password", password_ } };
{"username", user_},
{"password", password_}};
return QJsonDocument(body).toJson(QJsonDocument::Compact); return QJsonDocument(body).toJson(QJsonDocument::Compact);
} }
void RegisterResponse::deserialize(const QJsonDocument &data) void
RegisterResponse::deserialize(const QJsonDocument &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("Response is not a JSON object"); throw DeserializationException("Response is not a JSON object");

View file

@ -23,8 +23,8 @@
#include "RegisterPage.h" #include "RegisterPage.h"
RegisterPage::RegisterPage(QSharedPointer<MatrixClient> client, QWidget *parent) RegisterPage::RegisterPage(QSharedPointer<MatrixClient> client, QWidget *parent)
: QWidget(parent) : QWidget(parent)
, client_(client) , client_(client)
{ {
setStyleSheet("background-color: #f9f9f9"); setStyleSheet("background-color: #f9f9f9");
@ -144,17 +144,20 @@ RegisterPage::RegisterPage(QSharedPointer<MatrixClient> client, QWidget *parent)
setLayout(top_layout_); setLayout(top_layout_);
} }
void RegisterPage::onBackButtonClicked() void
RegisterPage::onBackButtonClicked()
{ {
emit backButtonClicked(); emit backButtonClicked();
} }
void RegisterPage::registerError(const QString &msg) void
RegisterPage::registerError(const QString &msg)
{ {
error_label_->setText(msg); error_label_->setText(msg);
} }
void RegisterPage::onRegisterButtonClicked() void
RegisterPage::onRegisterButtonClicked()
{ {
error_label_->setText(""); error_label_->setText("");

View file

@ -29,13 +29,13 @@ RoomInfoListItem::RoomInfoListItem(QSharedPointer<RoomSettings> settings,
RoomState state, RoomState state,
QString room_id, QString room_id,
QWidget *parent) QWidget *parent)
: QWidget(parent) : QWidget(parent)
, state_(state) , state_(state)
, roomId_(room_id) , roomId_(room_id)
, roomSettings_{settings} , roomSettings_{ settings }
, isPressed_(false) , isPressed_(false)
, maxHeight_(IconSize + 2 * Padding) , maxHeight_(IconSize + 2 * Padding)
, unreadMsgCount_(0) , unreadMsgCount_(0)
{ {
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
setMouseTracking(true); setMouseTracking(true);
@ -54,14 +54,13 @@ RoomInfoListItem::RoomInfoListItem(QSharedPointer<RoomSettings> settings,
toggleNotifications_ = new QAction(notificationText(), this); toggleNotifications_ = new QAction(notificationText(), this);
connect(toggleNotifications_, &QAction::triggered, this, [=]() { connect(toggleNotifications_, &QAction::triggered, this, [=]() { roomSettings_->toggleNotifications(); });
roomSettings_->toggleNotifications();
});
menu_->addAction(toggleNotifications_); menu_->addAction(toggleNotifications_);
} }
QString RoomInfoListItem::notificationText() QString
RoomInfoListItem::notificationText()
{ {
if (roomSettings_.isNull() || roomSettings_->isNotificationsEnabled()) if (roomSettings_.isNull() || roomSettings_->isNotificationsEnabled())
return QString(tr("Disable notifications")); return QString(tr("Disable notifications"));
@ -69,7 +68,8 @@ QString RoomInfoListItem::notificationText()
return tr("Enable notifications"); return tr("Enable notifications");
} }
void RoomInfoListItem::resizeEvent(QResizeEvent *) void
RoomInfoListItem::resizeEvent(QResizeEvent *)
{ {
// Update ripple's clipping path. // Update ripple's clipping path.
QPainterPath path; QPainterPath path;
@ -79,7 +79,8 @@ void RoomInfoListItem::resizeEvent(QResizeEvent *)
ripple_overlay_->setClipping(true); ripple_overlay_->setClipping(true);
} }
void RoomInfoListItem::paintEvent(QPaintEvent *event) void
RoomInfoListItem::paintEvent(QPaintEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
@ -119,7 +120,8 @@ void RoomInfoListItem::paintEvent(QPaintEvent *event)
QFontMetrics fontNameMetrics(font); QFontMetrics fontNameMetrics(font);
int top_y = 2 * Padding + fontNameMetrics.ascent() / 2; int top_y = 2 * Padding + fontNameMetrics.ascent() / 2;
auto name = metrics.elidedText(state_.getName(), Qt::ElideRight, (width() - IconSize - 2 * Padding) * 0.8); auto name =
metrics.elidedText(state_.getName(), Qt::ElideRight, (width() - IconSize - 2 * Padding) * 0.8);
p.drawText(QPoint(2 * Padding + IconSize, top_y), name); p.drawText(QPoint(2 * Padding + IconSize, top_y), name);
if (!isPressed_) { if (!isPressed_) {
@ -226,19 +228,22 @@ void RoomInfoListItem::paintEvent(QPaintEvent *event)
} }
} }
void RoomInfoListItem::updateUnreadMessageCount(int count) void
RoomInfoListItem::updateUnreadMessageCount(int count)
{ {
unreadMsgCount_ += count; unreadMsgCount_ += count;
update(); update();
} }
void RoomInfoListItem::clearUnreadMessageCount() void
RoomInfoListItem::clearUnreadMessageCount()
{ {
unreadMsgCount_ = 0; unreadMsgCount_ = 0;
update(); update();
} }
void RoomInfoListItem::setPressedState(bool state) void
RoomInfoListItem::setPressedState(bool state)
{ {
if (!isPressed_ && state) { if (!isPressed_ && state) {
isPressed_ = state; isPressed_ = state;
@ -249,13 +254,15 @@ void RoomInfoListItem::setPressedState(bool state)
} }
} }
void RoomInfoListItem::setState(const RoomState &new_state) void
RoomInfoListItem::setState(const RoomState &new_state)
{ {
state_ = new_state; state_ = new_state;
update(); update();
} }
void RoomInfoListItem::contextMenuEvent(QContextMenuEvent *event) void
RoomInfoListItem::contextMenuEvent(QContextMenuEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
@ -263,7 +270,8 @@ void RoomInfoListItem::contextMenuEvent(QContextMenuEvent *event)
menu_->popup(event->globalPos()); menu_->popup(event->globalPos());
} }
void RoomInfoListItem::mousePressEvent(QMouseEvent *event) void
RoomInfoListItem::mousePressEvent(QMouseEvent *event)
{ {
if (event->buttons() == Qt::RightButton) { if (event->buttons() == Qt::RightButton) {
QWidget::mousePressEvent(event); QWidget::mousePressEvent(event);

View file

@ -24,8 +24,8 @@
#include "Sync.h" #include "Sync.h"
RoomList::RoomList(QSharedPointer<MatrixClient> client, QWidget *parent) RoomList::RoomList(QSharedPointer<MatrixClient> client, QWidget *parent)
: QWidget(parent) : QWidget(parent)
, client_(client) , client_(client)
{ {
setStyleSheet("QWidget { border: none; }"); setStyleSheet("QWidget { border: none; }");
@ -65,12 +65,14 @@ RoomList::~RoomList()
{ {
} }
void RoomList::clear() void
RoomList::clear()
{ {
rooms_.clear(); rooms_.clear();
} }
void RoomList::updateUnreadMessageCount(const QString &roomid, int count) void
RoomList::updateUnreadMessageCount(const QString &roomid, int count)
{ {
if (!rooms_.contains(roomid)) { if (!rooms_.contains(roomid)) {
qWarning() << "UpdateUnreadMessageCount: Unknown roomid"; qWarning() << "UpdateUnreadMessageCount: Unknown roomid";
@ -82,7 +84,8 @@ void RoomList::updateUnreadMessageCount(const QString &roomid, int count)
calculateUnreadMessageCount(); calculateUnreadMessageCount();
} }
void RoomList::calculateUnreadMessageCount() void
RoomList::calculateUnreadMessageCount()
{ {
int total_unread_msgs = 0; int total_unread_msgs = 0;
@ -92,8 +95,9 @@ void RoomList::calculateUnreadMessageCount()
emit totalUnreadMessageCountUpdated(total_unread_msgs); emit totalUnreadMessageCountUpdated(total_unread_msgs);
} }
void RoomList::setInitialRooms(const QMap<QString, QSharedPointer<RoomSettings>> &settings, void
const QMap<QString, RoomState> &states) RoomList::setInitialRooms(const QMap<QString, QSharedPointer<RoomSettings>> &settings,
const QMap<QString, RoomState> &states)
{ {
rooms_.clear(); rooms_.clear();
@ -128,7 +132,8 @@ void RoomList::setInitialRooms(const QMap<QString, QSharedPointer<RoomSettings>>
emit roomChanged(rooms_.firstKey()); emit roomChanged(rooms_.firstKey());
} }
void RoomList::sync(const QMap<QString, RoomState> &states) void
RoomList::sync(const QMap<QString, RoomState> &states)
{ {
for (auto it = states.constBegin(); it != states.constEnd(); it++) { for (auto it = states.constBegin(); it != states.constEnd(); it++) {
auto room_id = it.key(); auto room_id = it.key();
@ -150,7 +155,8 @@ void RoomList::sync(const QMap<QString, RoomState> &states)
} }
} }
void RoomList::highlightSelectedRoom(const QString &room_id) void
RoomList::highlightSelectedRoom(const QString &room_id)
{ {
emit roomChanged(room_id); emit roomChanged(room_id);
@ -175,7 +181,8 @@ void RoomList::highlightSelectedRoom(const QString &room_id)
} }
} }
void RoomList::updateRoomAvatar(const QString &roomid, const QPixmap &img) void
RoomList::updateRoomAvatar(const QString &roomid, const QPixmap &img)
{ {
if (!rooms_.contains(roomid)) { if (!rooms_.contains(roomid)) {
qWarning() << "Avatar update on non existent room" << roomid; qWarning() << "Avatar update on non existent room" << roomid;
@ -185,7 +192,8 @@ void RoomList::updateRoomAvatar(const QString &roomid, const QPixmap &img)
rooms_.value(roomid)->setAvatar(img.toImage()); rooms_.value(roomid)->setAvatar(img.toImage());
} }
void RoomList::updateRoomDescription(const QString &roomid, const DescInfo &info) void
RoomList::updateRoomDescription(const QString &roomid, const DescInfo &info)
{ {
if (!rooms_.contains(roomid)) { if (!rooms_.contains(roomid)) {
qWarning() << "Description update on non existent room" << roomid << info.body; qWarning() << "Description update on non existent room" << roomid << info.body;

View file

@ -17,7 +17,8 @@
#include "RoomMessages.h" #include "RoomMessages.h"
void RoomMessages::deserialize(const QJsonDocument &data) void
RoomMessages::deserialize(const QJsonDocument &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("response is not a JSON object"); throw DeserializationException("response is not a JSON object");

View file

@ -23,7 +23,8 @@
namespace events = matrix::events; namespace events = matrix::events;
void RoomState::resolveName() void
RoomState::resolveName()
{ {
name_ = "Empty Room"; name_ = "Empty Room";
userAvatar_.clear(); userAvatar_.clear();
@ -69,7 +70,8 @@ void RoomState::resolveName()
name_ = QString("%1 and %2 others").arg(name_).arg(memberships.size()); name_ = QString("%1 and %2 others").arg(name_).arg(memberships.size());
} }
void RoomState::resolveAvatar() void
RoomState::resolveAvatar()
{ {
if (userAvatar_.isEmpty()) { if (userAvatar_.isEmpty()) {
avatar_ = avatar.content().url(); avatar_ = avatar.content().url();
@ -84,7 +86,8 @@ void RoomState::resolveAvatar()
} }
// Should be used only after initial sync. // Should be used only after initial sync.
void RoomState::removeLeaveMemberships() void
RoomState::removeLeaveMemberships()
{ {
for (auto it = memberships.begin(); it != memberships.end();) { for (auto it = memberships.begin(); it != memberships.end();) {
if (it.value().content().membershipState() == events::Membership::Leave) { if (it.value().content().membershipState() == events::Membership::Leave) {
@ -95,7 +98,8 @@ void RoomState::removeLeaveMemberships()
} }
} }
void RoomState::update(const RoomState &state) void
RoomState::update(const RoomState &state)
{ {
bool needsNameCalculation = false; bool needsNameCalculation = false;
bool needsAvatarCalculation = false; bool needsAvatarCalculation = false;
@ -152,7 +156,8 @@ void RoomState::update(const RoomState &state)
resolveAvatar(); resolveAvatar();
} }
QJsonObject RoomState::serialize() const QJsonObject
RoomState::serialize() const
{ {
QJsonObject obj; QJsonObject obj;
@ -186,7 +191,8 @@ QJsonObject RoomState::serialize() const
return obj; return obj;
} }
void RoomState::parse(const QJsonObject &object) void
RoomState::parse(const QJsonObject &object)
{ {
// FIXME: Make this less versbose. // FIXME: Make this less versbose.

View file

@ -18,7 +18,7 @@
#include "SlidingStackWidget.h" #include "SlidingStackWidget.h"
SlidingStackWidget::SlidingStackWidget(QWidget *parent) SlidingStackWidget::SlidingStackWidget(QWidget *parent)
: QStackedWidget(parent) : QStackedWidget(parent)
{ {
window_ = parent; window_ = parent;
@ -39,7 +39,8 @@ SlidingStackWidget::~SlidingStackWidget()
{ {
} }
void SlidingStackWidget::slideInNext() void
SlidingStackWidget::slideInNext()
{ {
int now = currentIndex(); int now = currentIndex();
@ -47,7 +48,8 @@ void SlidingStackWidget::slideInNext()
slideInIndex(now + 1); slideInIndex(now + 1);
} }
void SlidingStackWidget::slideInPrevious() void
SlidingStackWidget::slideInPrevious()
{ {
int now = currentIndex(); int now = currentIndex();
@ -55,7 +57,8 @@ void SlidingStackWidget::slideInPrevious()
slideInIndex(now - 1); slideInIndex(now - 1);
} }
void SlidingStackWidget::slideInIndex(int index, AnimationDirection direction) void
SlidingStackWidget::slideInIndex(int index, AnimationDirection direction)
{ {
// Take into consideration possible index overflow/undeflow. // Take into consideration possible index overflow/undeflow.
if (index > count() - 1) { if (index > count() - 1) {
@ -69,7 +72,8 @@ void SlidingStackWidget::slideInIndex(int index, AnimationDirection direction)
slideInWidget(widget(index), direction); slideInWidget(widget(index), direction);
} }
void SlidingStackWidget::slideInWidget(QWidget *next_widget, AnimationDirection direction) void
SlidingStackWidget::slideInWidget(QWidget *next_widget, AnimationDirection direction)
{ {
// If an animation is currenlty executing we should wait for it to finish before // If an animation is currenlty executing we should wait for it to finish before
// another transition can start. // another transition can start.
@ -132,7 +136,8 @@ void SlidingStackWidget::slideInWidget(QWidget *next_widget, AnimationDirection
animation_group->start(); animation_group->start();
} }
void SlidingStackWidget::onAnimationFinished() void
SlidingStackWidget::onAnimationFinished()
{ {
setCurrentIndex(next_); setCurrentIndex(next_);
@ -145,7 +150,8 @@ void SlidingStackWidget::onAnimationFinished()
emit animationFinished(); emit animationFinished();
} }
int SlidingStackWidget::getWidgetIndex(QWidget *widget) int
SlidingStackWidget::getWidgetIndex(QWidget *widget)
{ {
return indexOf(widget); return indexOf(widget);
} }

View file

@ -21,13 +21,14 @@
#include "Theme.h" #include "Theme.h"
Splitter::Splitter(QWidget *parent) Splitter::Splitter(QWidget *parent)
: QSplitter(parent) : QSplitter(parent)
{ {
connect(this, &QSplitter::splitterMoved, this, &Splitter::onSplitterMoved); connect(this, &QSplitter::splitterMoved, this, &Splitter::onSplitterMoved);
setChildrenCollapsible(false); setChildrenCollapsible(false);
} }
void Splitter::onSplitterMoved(int pos, int index) void
Splitter::onSplitterMoved(int pos, int index)
{ {
Q_UNUSED(pos); Q_UNUSED(pos);
Q_UNUSED(index); Q_UNUSED(index);

View file

@ -24,7 +24,8 @@
#include "Deserializable.h" #include "Deserializable.h"
#include "Sync.h" #include "Sync.h"
void SyncResponse::deserialize(const QJsonDocument &data) void
SyncResponse::deserialize(const QJsonDocument &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("Sync response is not a JSON object"); throw DeserializationException("Sync response is not a JSON object");
@ -41,7 +42,8 @@ void SyncResponse::deserialize(const QJsonDocument &data)
next_batch_ = object.value("next_batch").toString(); next_batch_ = object.value("next_batch").toString();
} }
void Rooms::deserialize(const QJsonValue &data) void
Rooms::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("Rooms value is not a JSON object"); throw DeserializationException("Rooms value is not a JSON object");
@ -81,7 +83,8 @@ void Rooms::deserialize(const QJsonValue &data)
} }
} }
void JoinedRoom::deserialize(const QJsonValue &data) void
JoinedRoom::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("JoinedRoom is not a JSON object"); throw DeserializationException("JoinedRoom is not a JSON object");
@ -112,7 +115,8 @@ void JoinedRoom::deserialize(const QJsonValue &data)
timeline_.deserialize(object.value("timeline")); timeline_.deserialize(object.value("timeline"));
} }
void Event::deserialize(const QJsonValue &data) void
Event::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("Event is not a JSON object"); throw DeserializationException("Event is not a JSON object");
@ -152,7 +156,8 @@ void Event::deserialize(const QJsonValue &data)
origin_server_ts_ = object.value("origin_server_ts").toDouble(); origin_server_ts_ = object.value("origin_server_ts").toDouble();
} }
void State::deserialize(const QJsonValue &data) void
State::deserialize(const QJsonValue &data)
{ {
if (!data.isArray()) if (!data.isArray())
throw DeserializationException("State is not a JSON array"); throw DeserializationException("State is not a JSON array");
@ -160,7 +165,8 @@ void State::deserialize(const QJsonValue &data)
events_ = data.toArray(); events_ = data.toArray();
} }
void Timeline::deserialize(const QJsonValue &data) void
Timeline::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("Timeline is not a JSON object"); throw DeserializationException("Timeline is not a JSON object");

View file

@ -24,12 +24,13 @@
#include "TextInputWidget.h" #include "TextInputWidget.h"
FilteredTextEdit::FilteredTextEdit(QWidget *parent) FilteredTextEdit::FilteredTextEdit(QWidget *parent)
: QTextEdit(parent) : QTextEdit(parent)
{ {
setAcceptRichText(false); setAcceptRichText(false);
} }
void FilteredTextEdit::keyPressEvent(QKeyEvent *event) void
FilteredTextEdit::keyPressEvent(QKeyEvent *event)
{ {
if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
emit enterPressed(); emit enterPressed();
@ -38,7 +39,7 @@ void FilteredTextEdit::keyPressEvent(QKeyEvent *event)
} }
TextInputWidget::TextInputWidget(QWidget *parent) TextInputWidget::TextInputWidget(QWidget *parent)
: QWidget(parent) : QWidget(parent)
{ {
setFont(QFont("Emoji One")); setFont(QFont("Emoji One"));
@ -95,7 +96,8 @@ TextInputWidget::TextInputWidget(QWidget *parent)
connect(emoji_button_, SIGNAL(emojiSelected(const QString &)), this, SLOT(addSelectedEmoji(const QString &))); connect(emoji_button_, SIGNAL(emojiSelected(const QString &)), this, SLOT(addSelectedEmoji(const QString &)));
} }
void TextInputWidget::addSelectedEmoji(const QString &emoji) void
TextInputWidget::addSelectedEmoji(const QString &emoji)
{ {
QTextCursor cursor = input_->textCursor(); QTextCursor cursor = input_->textCursor();
@ -118,7 +120,8 @@ void TextInputWidget::addSelectedEmoji(const QString &emoji)
input_->show(); input_->show();
} }
void TextInputWidget::onSendButtonClicked() void
TextInputWidget::onSendButtonClicked()
{ {
auto msg_text = input_->document()->toPlainText().trimmed(); auto msg_text = input_->document()->toPlainText().trimmed();
@ -130,7 +133,8 @@ void TextInputWidget::onSendButtonClicked()
input_->clear(); input_->clear();
} }
void TextInputWidget::paintEvent(QPaintEvent *event) void
TextInputWidget::paintEvent(QPaintEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);

View file

@ -33,7 +33,8 @@ static const QString URL_HTML = "<a href=\"\\1\" style=\"color: #333333\">\\1</a
namespace events = matrix::events; namespace events = matrix::events;
namespace msgs = matrix::events::messages; namespace msgs = matrix::events::messages;
void TimelineItem::init() void
TimelineItem::init()
{ {
userAvatar_ = nullptr; userAvatar_ = nullptr;
timestamp_ = nullptr; timestamp_ = nullptr;
@ -69,10 +70,10 @@ void TimelineItem::init()
* For messages created locally. The avatar and the username are displayed. * For messages created locally. The avatar and the username are displayed.
*/ */
TimelineItem::TimelineItem(const QString &userid, const QString &color, QString body, QWidget *parent) TimelineItem::TimelineItem(const QString &userid, const QString &color, QString body, QWidget *parent)
: QWidget(parent) : QWidget(parent)
{ {
init(); init();
descriptionMsg_ = {"You: ", userid, body, descriptiveTime(QDateTime::currentDateTime())}; descriptionMsg_ = { "You: ", userid, body, descriptiveTime(QDateTime::currentDateTime()) };
body.replace(URL_REGEX, URL_HTML); body.replace(URL_REGEX, URL_HTML);
auto displayName = TimelineViewManager::displayName(userid); auto displayName = TimelineViewManager::displayName(userid);
@ -92,13 +93,13 @@ TimelineItem::TimelineItem(const QString &userid, const QString &color, QString
* For messages created locally. Only the text is displayed. * For messages created locally. Only the text is displayed.
*/ */
TimelineItem::TimelineItem(QString body, QWidget *parent) TimelineItem::TimelineItem(QString body, QWidget *parent)
: QWidget(parent) : QWidget(parent)
{ {
QSettings settings; QSettings settings;
auto userid = settings.value("auth/user_id").toString(); auto userid = settings.value("auth/user_id").toString();
init(); init();
descriptionMsg_ = {"You: ", userid, body, descriptiveTime(QDateTime::currentDateTime())}; descriptionMsg_ = { "You: ", userid, body, descriptiveTime(QDateTime::currentDateTime()) };
body.replace(URL_REGEX, URL_HTML); body.replace(URL_REGEX, URL_HTML);
@ -117,7 +118,7 @@ TimelineItem::TimelineItem(ImageItem *image,
const events::MessageEvent<msgs::Image> &event, const events::MessageEvent<msgs::Image> &event,
const QString &color, const QString &color,
QWidget *parent) QWidget *parent)
: QWidget(parent) : QWidget(parent)
{ {
init(); init();
@ -125,11 +126,10 @@ TimelineItem::TimelineItem(ImageItem *image,
auto displayName = TimelineViewManager::displayName(event.sender()); auto displayName = TimelineViewManager::displayName(event.sender());
QSettings settings; QSettings settings;
descriptionMsg_ = { descriptionMsg_ = { event.sender() == settings.value("auth/user_id") ? "You" : displayName,
event.sender() == settings.value("auth/user_id") ? "You" : displayName, event.sender(),
event.sender(), " sent an image",
" sent an image", descriptiveTime(QDateTime::fromMSecsSinceEpoch(event.timestamp())) };
descriptiveTime(QDateTime::fromMSecsSinceEpoch(event.timestamp()))};
generateTimestamp(timestamp); generateTimestamp(timestamp);
generateBody(displayName, color, ""); generateBody(displayName, color, "");
@ -150,18 +150,17 @@ TimelineItem::TimelineItem(ImageItem *image,
* Used to display images. Only the image is displayed. * Used to display images. Only the image is displayed.
*/ */
TimelineItem::TimelineItem(ImageItem *image, const events::MessageEvent<msgs::Image> &event, QWidget *parent) TimelineItem::TimelineItem(ImageItem *image, const events::MessageEvent<msgs::Image> &event, QWidget *parent)
: QWidget(parent) : QWidget(parent)
{ {
init(); init();
auto displayName = TimelineViewManager::displayName(event.sender()); auto displayName = TimelineViewManager::displayName(event.sender());
QSettings settings; QSettings settings;
descriptionMsg_ = { descriptionMsg_ = { event.sender() == settings.value("auth/user_id") ? "You" : displayName,
event.sender() == settings.value("auth/user_id") ? "You" : displayName, event.sender(),
event.sender(), " sent an image",
" sent an image", descriptiveTime(QDateTime::fromMSecsSinceEpoch(event.timestamp())) };
descriptiveTime(QDateTime::fromMSecsSinceEpoch(event.timestamp()))};
auto timestamp = QDateTime::fromMSecsSinceEpoch(event.timestamp()); auto timestamp = QDateTime::fromMSecsSinceEpoch(event.timestamp());
generateTimestamp(timestamp); generateTimestamp(timestamp);
@ -179,15 +178,17 @@ TimelineItem::TimelineItem(ImageItem *image, const events::MessageEvent<msgs::Im
/* /*
* Used to display remote notice messages. * Used to display remote notice messages.
*/ */
TimelineItem::TimelineItem(const events::MessageEvent<msgs::Notice> &event, bool with_sender, const QString &color, QWidget *parent) TimelineItem::TimelineItem(const events::MessageEvent<msgs::Notice> &event,
: QWidget(parent) bool with_sender,
const QString &color,
QWidget *parent)
: QWidget(parent)
{ {
init(); init();
descriptionMsg_ = { descriptionMsg_ = { TimelineViewManager::displayName(event.sender()),
TimelineViewManager::displayName(event.sender()), event.sender(),
event.sender(), " sent a notification",
" sent a notification", descriptiveTime(QDateTime::fromMSecsSinceEpoch(event.timestamp())) };
descriptiveTime(QDateTime::fromMSecsSinceEpoch(event.timestamp()))};
auto body = event.content().body().trimmed().toHtmlEscaped(); auto body = event.content().body().trimmed().toHtmlEscaped();
auto timestamp = QDateTime::fromMSecsSinceEpoch(event.timestamp()); auto timestamp = QDateTime::fromMSecsSinceEpoch(event.timestamp());
@ -217,8 +218,11 @@ TimelineItem::TimelineItem(const events::MessageEvent<msgs::Notice> &event, bool
/* /*
* Used to display remote text messages. * Used to display remote text messages.
*/ */
TimelineItem::TimelineItem(const events::MessageEvent<msgs::Text> &event, bool with_sender, const QString &color, QWidget *parent) TimelineItem::TimelineItem(const events::MessageEvent<msgs::Text> &event,
: QWidget(parent) bool with_sender,
const QString &color,
QWidget *parent)
: QWidget(parent)
{ {
init(); init();
@ -227,11 +231,10 @@ TimelineItem::TimelineItem(const events::MessageEvent<msgs::Text> &event, bool w
auto displayName = TimelineViewManager::displayName(event.sender()); auto displayName = TimelineViewManager::displayName(event.sender());
QSettings settings; QSettings settings;
descriptionMsg_ = { descriptionMsg_ = { event.sender() == settings.value("auth/user_id") ? "You" : displayName,
event.sender() == settings.value("auth/user_id") ? "You" : displayName, event.sender(),
event.sender(), QString(": %1").arg(body),
QString(": %1").arg(body), descriptiveTime(QDateTime::fromMSecsSinceEpoch(event.timestamp())) };
descriptiveTime(QDateTime::fromMSecsSinceEpoch(event.timestamp()))};
generateTimestamp(timestamp); generateTimestamp(timestamp);
@ -255,7 +258,8 @@ TimelineItem::TimelineItem(const events::MessageEvent<msgs::Text> &event, bool w
} }
// Only the body is displayed. // Only the body is displayed.
void TimelineItem::generateBody(const QString &body) void
TimelineItem::generateBody(const QString &body)
{ {
QString content("<span style=\"color: black;\"> %1 </span>"); QString content("<span style=\"color: black;\"> %1 </span>");
@ -270,7 +274,8 @@ void TimelineItem::generateBody(const QString &body)
} }
// The username/timestamp is displayed along with the message body. // The username/timestamp is displayed along with the message body.
void TimelineItem::generateBody(const QString &userid, const QString &color, const QString &body) void
TimelineItem::generateBody(const QString &userid, const QString &color, const QString &body)
{ {
auto sender = userid; auto sender = userid;
@ -300,7 +305,8 @@ void TimelineItem::generateBody(const QString &userid, const QString &color, con
body_->setMargin(0); body_->setMargin(0);
} }
void TimelineItem::generateTimestamp(const QDateTime &time) void
TimelineItem::generateTimestamp(const QDateTime &time)
{ {
QString msg("<span style=\"color: #5d6565;\"> %1 </span>"); QString msg("<span style=\"color: #5d6565;\"> %1 </span>");
@ -316,7 +322,8 @@ void TimelineItem::generateTimestamp(const QDateTime &time)
timestamp_->setContentsMargins(0, topMargin, 0, 0); timestamp_->setContentsMargins(0, topMargin, 0, 0);
} }
QString TimelineItem::replaceEmoji(const QString &body) QString
TimelineItem::replaceEmoji(const QString &body)
{ {
QString fmtBody = ""; QString fmtBody = "";
@ -325,9 +332,9 @@ QString TimelineItem::replaceEmoji(const QString &body)
// TODO: Be more precise here. // TODO: Be more precise here.
if (code > 9000) if (code > 9000)
fmtBody += QString("<span style=\"font-family: Emoji One; font-size: %1px\">").arg(conf::emojiSize) + fmtBody += QString("<span style=\"font-family: Emoji One; font-size: %1px\">")
QString(c) + .arg(conf::emojiSize) +
"</span>"; QString(c) + "</span>";
else else
fmtBody += c; fmtBody += c;
} }
@ -335,7 +342,8 @@ QString TimelineItem::replaceEmoji(const QString &body)
return fmtBody; return fmtBody;
} }
void TimelineItem::setupAvatarLayout(const QString &userName) void
TimelineItem::setupAvatarLayout(const QString &userName)
{ {
topLayout_->setContentsMargins(conf::timeline::msgMargin, conf::timeline::msgMargin, 0, 0); topLayout_->setContentsMargins(conf::timeline::msgMargin, conf::timeline::msgMargin, 0, 0);
@ -356,7 +364,8 @@ void TimelineItem::setupAvatarLayout(const QString &userName)
headerLayout_->addWidget(timestamp_, 1); headerLayout_->addWidget(timestamp_, 1);
} }
void TimelineItem::setupSimpleLayout() void
TimelineItem::setupSimpleLayout()
{ {
sideLayout_->addWidget(timestamp_); sideLayout_->addWidget(timestamp_);
@ -378,7 +387,8 @@ void TimelineItem::setupSimpleLayout()
topLayout_->setContentsMargins(conf::timeline::msgMargin, conf::timeline::msgMargin / 3, 0, 0); topLayout_->setContentsMargins(conf::timeline::msgMargin, conf::timeline::msgMargin / 3, 0, 0);
} }
void TimelineItem::setUserAvatar(const QImage &avatar) void
TimelineItem::setUserAvatar(const QImage &avatar)
{ {
if (userAvatar_ == nullptr) if (userAvatar_ == nullptr)
return; return;
@ -386,7 +396,8 @@ void TimelineItem::setUserAvatar(const QImage &avatar)
userAvatar_->setImage(avatar); userAvatar_->setImage(avatar);
} }
QString TimelineItem::descriptiveTime(const QDateTime &then) QString
TimelineItem::descriptiveTime(const QDateTime &then)
{ {
auto now = QDateTime::currentDateTime(); auto now = QDateTime::currentDateTime();

View file

@ -38,9 +38,9 @@ TimelineView::TimelineView(const Timeline &timeline,
QSharedPointer<MatrixClient> client, 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} , client_{ client }
{ {
QSettings settings; QSettings settings;
local_user_ = settings.value("auth/user_id").toString(); local_user_ = settings.value("auth/user_id").toString();
@ -50,9 +50,9 @@ TimelineView::TimelineView(const Timeline &timeline,
} }
TimelineView::TimelineView(QSharedPointer<MatrixClient> client, const QString &room_id, QWidget *parent) TimelineView::TimelineView(QSharedPointer<MatrixClient> client, const QString &room_id, QWidget *parent)
: QWidget(parent) : QWidget(parent)
, room_id_{room_id} , room_id_{ room_id }
, client_{client} , client_{ client }
{ {
QSettings settings; QSettings settings;
local_user_ = settings.value("auth/user_id").toString(); local_user_ = settings.value("auth/user_id").toString();
@ -61,7 +61,8 @@ TimelineView::TimelineView(QSharedPointer<MatrixClient> client, const QString &r
client_->messages(room_id_, ""); client_->messages(room_id_, "");
} }
void TimelineView::sliderRangeChanged(int min, int max) void
TimelineView::sliderRangeChanged(int min, int max)
{ {
Q_UNUSED(min); Q_UNUSED(min);
@ -89,7 +90,8 @@ void TimelineView::sliderRangeChanged(int min, int max)
} }
} }
void TimelineView::fetchHistory() void
TimelineView::fetchHistory()
{ {
bool hasEnoughMessages = scroll_area_->verticalScrollBar()->value() != 0; bool hasEnoughMessages = scroll_area_->verticalScrollBar()->value() != 0;
@ -103,7 +105,8 @@ void TimelineView::fetchHistory()
paginationTimer_->stop(); paginationTimer_->stop();
} }
void TimelineView::scrollDown() void
TimelineView::scrollDown()
{ {
int current = scroll_area_->verticalScrollBar()->value(); int current = scroll_area_->verticalScrollBar()->value();
int max = scroll_area_->verticalScrollBar()->maximum(); int max = scroll_area_->verticalScrollBar()->maximum();
@ -120,7 +123,8 @@ void TimelineView::scrollDown()
scroll_area_->verticalScrollBar()->setValue(max); scroll_area_->verticalScrollBar()->setValue(max);
} }
void TimelineView::sliderMoved(int position) void
TimelineView::sliderMoved(int position)
{ {
if (!scroll_area_->verticalScrollBar()->isVisible()) if (!scroll_area_->verticalScrollBar()->isVisible())
return; return;
@ -142,7 +146,8 @@ void TimelineView::sliderMoved(int position)
} }
} }
void TimelineView::addBackwardsEvents(const QString &room_id, const RoomMessages &msgs) void
TimelineView::addBackwardsEvents(const QString &room_id, const RoomMessages &msgs)
{ {
if (room_id_ != room_id) if (room_id_ != room_id)
return; return;
@ -189,7 +194,8 @@ void TimelineView::addBackwardsEvents(const QString &room_id, const RoomMessages
lastSender_ = items.constFirst()->descriptionMessage().userid; lastSender_ = items.constFirst()->descriptionMessage().userid;
} }
TimelineItem *TimelineView::parseMessageEvent(const QJsonObject &event, TimelineDirection direction) TimelineItem *
TimelineView::parseMessageEvent(const QJsonObject &event, TimelineDirection direction)
{ {
events::EventType ty = events::extractEventType(event); events::EventType ty = events::extractEventType(event);
@ -274,7 +280,8 @@ TimelineItem *TimelineView::parseMessageEvent(const QJsonObject &event, Timeline
return nullptr; return nullptr;
} }
int TimelineView::addEvents(const Timeline &timeline) int
TimelineView::addEvents(const Timeline &timeline)
{ {
int message_count = 0; int message_count = 0;
@ -306,7 +313,8 @@ int TimelineView::addEvents(const Timeline &timeline)
return message_count; return message_count;
} }
void TimelineView::init() void
TimelineView::init()
{ {
top_layout_ = new QVBoxLayout(this); top_layout_ = new QVBoxLayout(this);
top_layout_->setSpacing(0); top_layout_->setSpacing(0);
@ -339,10 +347,14 @@ void TimelineView::init()
connect(client_.data(), &MatrixClient::messagesRetrieved, this, &TimelineView::addBackwardsEvents); connect(client_.data(), &MatrixClient::messagesRetrieved, this, &TimelineView::addBackwardsEvents);
connect(scroll_area_->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(sliderMoved(int))); connect(scroll_area_->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(sliderMoved(int)));
connect(scroll_area_->verticalScrollBar(), SIGNAL(rangeChanged(int, int)), this, SLOT(sliderRangeChanged(int, int))); connect(scroll_area_->verticalScrollBar(),
SIGNAL(rangeChanged(int, int)),
this,
SLOT(sliderRangeChanged(int, int)));
} }
void TimelineView::updateLastSender(const QString &user_id, TimelineDirection direction) void
TimelineView::updateLastSender(const QString &user_id, TimelineDirection direction)
{ {
if (direction == TimelineDirection::Bottom) if (direction == TimelineDirection::Bottom)
lastSender_ = user_id; lastSender_ = user_id;
@ -350,7 +362,8 @@ void TimelineView::updateLastSender(const QString &user_id, TimelineDirection di
firstSender_ = user_id; firstSender_ = user_id;
} }
bool TimelineView::isSenderRendered(const QString &user_id, TimelineDirection direction) bool
TimelineView::isSenderRendered(const QString &user_id, TimelineDirection direction)
{ {
if (direction == TimelineDirection::Bottom) if (direction == TimelineDirection::Bottom)
return lastSender_ != user_id; return lastSender_ != user_id;
@ -358,7 +371,8 @@ bool TimelineView::isSenderRendered(const QString &user_id, TimelineDirection di
return firstSender_ != user_id; return firstSender_ != user_id;
} }
TimelineItem *TimelineView::createTimelineItem(const events::MessageEvent<msgs::Image> &event, const QString &color, bool with_sender) TimelineItem *
TimelineView::createTimelineItem(const events::MessageEvent<msgs::Image> &event, const QString &color, bool with_sender)
{ {
auto image = new ImageItem(client_, event); auto image = new ImageItem(client_, event);
@ -371,19 +385,24 @@ TimelineItem *TimelineView::createTimelineItem(const events::MessageEvent<msgs::
return item; return item;
} }
TimelineItem *TimelineView::createTimelineItem(const events::MessageEvent<msgs::Notice> &event, const QString &color, bool with_sender) TimelineItem *
TimelineView::createTimelineItem(const events::MessageEvent<msgs::Notice> &event,
const QString &color,
bool with_sender)
{ {
TimelineItem *item = new TimelineItem(event, with_sender, color, scroll_widget_); TimelineItem *item = new TimelineItem(event, with_sender, color, scroll_widget_);
return item; return item;
} }
TimelineItem *TimelineView::createTimelineItem(const events::MessageEvent<msgs::Text> &event, const QString &color, bool with_sender) TimelineItem *
TimelineView::createTimelineItem(const events::MessageEvent<msgs::Text> &event, const QString &color, bool with_sender)
{ {
TimelineItem *item = new TimelineItem(event, with_sender, color, scroll_widget_); TimelineItem *item = new TimelineItem(event, with_sender, color, scroll_widget_);
return item; return item;
} }
void TimelineView::addTimelineItem(TimelineItem *item, TimelineDirection direction) void
TimelineView::addTimelineItem(TimelineItem *item, TimelineDirection direction)
{ {
if (direction == TimelineDirection::Bottom) if (direction == TimelineDirection::Bottom)
scroll_layout_->addWidget(item); scroll_layout_->addWidget(item);
@ -391,7 +410,8 @@ void TimelineView::addTimelineItem(TimelineItem *item, TimelineDirection directi
scroll_layout_->insertWidget(1, item); scroll_layout_->insertWidget(1, item);
} }
void TimelineView::updatePendingMessage(int txn_id, QString event_id) void
TimelineView::updatePendingMessage(int txn_id, QString event_id)
{ {
for (auto &msg : pending_msgs_) { for (auto &msg : pending_msgs_) {
if (msg.txn_id == txn_id) { if (msg.txn_id == txn_id) {
@ -401,7 +421,8 @@ void TimelineView::updatePendingMessage(int txn_id, QString event_id)
} }
} }
bool TimelineView::isPendingMessage(const events::MessageEvent<msgs::Text> &e, const QString &local_userid) bool
TimelineView::isPendingMessage(const events::MessageEvent<msgs::Text> &e, const QString &local_userid)
{ {
if (e.sender() != local_userid) if (e.sender() != local_userid)
return false; return false;
@ -414,7 +435,8 @@ bool TimelineView::isPendingMessage(const events::MessageEvent<msgs::Text> &e, c
return false; return false;
} }
void TimelineView::removePendingMessage(const events::MessageEvent<msgs::Text> &e) void
TimelineView::removePendingMessage(const events::MessageEvent<msgs::Text> &e)
{ {
for (auto it = pending_msgs_.begin(); it != pending_msgs_.end(); it++) { for (auto it = pending_msgs_.begin(); it != pending_msgs_.end(); it++) {
int index = std::distance(pending_msgs_.begin(), it); int index = std::distance(pending_msgs_.begin(), it);
@ -426,7 +448,8 @@ void TimelineView::removePendingMessage(const events::MessageEvent<msgs::Text> &
} }
} }
void TimelineView::addUserTextMessage(const QString &body, int txn_id) void
TimelineView::addUserTextMessage(const QString &body, int txn_id)
{ {
QSettings settings; QSettings settings;
auto user_id = settings.value("auth/user_id").toString(); auto user_id = settings.value("auth/user_id").toString();
@ -450,7 +473,8 @@ void TimelineView::addUserTextMessage(const QString &body, int txn_id)
pending_msgs_.push_back(message); pending_msgs_.push_back(message);
} }
void TimelineView::notifyForLastEvent() void
TimelineView::notifyForLastEvent()
{ {
auto lastItem = scroll_layout_->itemAt(scroll_layout_->count() - 1); auto lastItem = scroll_layout_->itemAt(scroll_layout_->count() - 1);
auto *lastTimelineItem = qobject_cast<TimelineItem *>(lastItem->widget()); auto *lastTimelineItem = qobject_cast<TimelineItem *>(lastItem->widget());

View file

@ -27,8 +27,8 @@
#include "TimelineViewManager.h" #include "TimelineViewManager.h"
TimelineViewManager::TimelineViewManager(QSharedPointer<MatrixClient> client, QWidget *parent) TimelineViewManager::TimelineViewManager(QSharedPointer<MatrixClient> client, QWidget *parent)
: QStackedWidget(parent) : QStackedWidget(parent)
, client_(client) , client_(client)
{ {
setStyleSheet("QWidget { background: #f8fbfe; color: #e8e8e8; border: none;}"); setStyleSheet("QWidget { background: #f8fbfe; color: #e8e8e8; border: none;}");
@ -42,7 +42,8 @@ TimelineViewManager::~TimelineViewManager()
{ {
} }
void TimelineViewManager::messageSent(const QString &event_id, const QString &roomid, int txn_id) void
TimelineViewManager::messageSent(const QString &event_id, const QString &roomid, int txn_id)
{ {
// We save the latest valid transaction ID for later use. // We save the latest valid transaction ID for later use.
QSettings settings; QSettings settings;
@ -52,7 +53,8 @@ void TimelineViewManager::messageSent(const QString &event_id, const QString &ro
view->updatePendingMessage(txn_id, event_id); view->updatePendingMessage(txn_id, event_id);
} }
void TimelineViewManager::sendTextMessage(const QString &msg) void
TimelineViewManager::sendTextMessage(const QString &msg)
{ {
auto room_id = active_room_; auto room_id = active_room_;
auto view = views_[room_id]; auto view = views_[room_id];
@ -61,7 +63,8 @@ void TimelineViewManager::sendTextMessage(const QString &msg)
client_->sendTextMessage(room_id, msg); client_->sendTextMessage(room_id, msg);
} }
void TimelineViewManager::clearAll() void
TimelineViewManager::clearAll()
{ {
NICK_COLORS.clear(); NICK_COLORS.clear();
@ -71,7 +74,8 @@ void TimelineViewManager::clearAll()
views_.clear(); views_.clear();
} }
void TimelineViewManager::initialize(const Rooms &rooms) void
TimelineViewManager::initialize(const Rooms &rooms)
{ {
for (auto it = rooms.join().constBegin(); it != rooms.join().constEnd(); it++) { for (auto it = rooms.join().constBegin(); it != rooms.join().constEnd(); it++) {
auto roomid = it.key(); auto roomid = it.key();
@ -90,7 +94,8 @@ void TimelineViewManager::initialize(const Rooms &rooms)
} }
} }
void TimelineViewManager::initialize(const QList<QString> &rooms) void
TimelineViewManager::initialize(const QList<QString> &rooms)
{ {
for (const auto &roomid : rooms) { for (const auto &roomid : rooms) {
// Create a history view without any events. // Create a history view without any events.
@ -107,7 +112,8 @@ void TimelineViewManager::initialize(const QList<QString> &rooms)
} }
} }
void TimelineViewManager::sync(const Rooms &rooms) void
TimelineViewManager::sync(const Rooms &rooms)
{ {
for (auto it = rooms.join().constBegin(); it != rooms.join().constEnd(); it++) { for (auto it = rooms.join().constBegin(); it != rooms.join().constEnd(); it++) {
auto roomid = it.key(); auto roomid = it.key();
@ -132,7 +138,8 @@ void TimelineViewManager::sync(const Rooms &rooms)
} }
} }
void TimelineViewManager::setHistoryView(const QString &room_id) void
TimelineViewManager::setHistoryView(const QString &room_id)
{ {
if (!views_.contains(room_id)) { if (!views_.contains(room_id)) {
qDebug() << "Room ID from RoomList is not present in ViewManager" << room_id; qDebug() << "Room ID from RoomList is not present in ViewManager" << room_id;
@ -151,10 +158,11 @@ void TimelineViewManager::setHistoryView(const QString &room_id)
QMap<QString, QString> TimelineViewManager::NICK_COLORS; QMap<QString, QString> TimelineViewManager::NICK_COLORS;
QMap<QString, QString> TimelineViewManager::DISPLAY_NAMES; QMap<QString, QString> TimelineViewManager::DISPLAY_NAMES;
QString TimelineViewManager::chooseRandomColor() QString
TimelineViewManager::chooseRandomColor()
{ {
std::random_device random_device; std::random_device random_device;
std::mt19937 engine{random_device()}; std::mt19937 engine{ random_device() };
std::uniform_real_distribution<float> dist(0, 1); std::uniform_real_distribution<float> dist(0, 1);
float hue = dist(engine); float hue = dist(engine);
@ -208,7 +216,8 @@ QString TimelineViewManager::chooseRandomColor()
return color.name(); return color.name();
} }
QString TimelineViewManager::getUserColor(const QString &userid) QString
TimelineViewManager::getUserColor(const QString &userid)
{ {
auto color = NICK_COLORS.value(userid); auto color = NICK_COLORS.value(userid);
@ -220,7 +229,8 @@ QString TimelineViewManager::getUserColor(const QString &userid)
return color; return color;
} }
QString TimelineViewManager::displayName(const QString &userid) QString
TimelineViewManager::displayName(const QString &userid)
{ {
if (DISPLAY_NAMES.contains(userid)) if (DISPLAY_NAMES.contains(userid))
return DISPLAY_NAMES.value(userid); return DISPLAY_NAMES.value(userid);

View file

@ -21,8 +21,8 @@
#include "TopRoomBar.h" #include "TopRoomBar.h"
TopRoomBar::TopRoomBar(QWidget *parent) TopRoomBar::TopRoomBar(QWidget *parent)
: QWidget(parent) : QWidget(parent)
, buttonSize_{32} , buttonSize_{ 32 }
{ {
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
setMinimumSize(QSize(0, 65)); setMinimumSize(QSize(0, 65));
@ -75,9 +75,7 @@ TopRoomBar::TopRoomBar(QWidget *parent)
menu_ = new Menu(this); menu_ = new Menu(this);
toggleNotifications_ = new QAction(tr("Disable notifications"), this); toggleNotifications_ = new QAction(tr("Disable notifications"), this);
connect(toggleNotifications_, &QAction::triggered, this, [=]() { connect(toggleNotifications_, &QAction::triggered, this, [=]() { roomSettings_->toggleNotifications(); });
roomSettings_->toggleNotifications();
});
menu_->addAction(toggleNotifications_); menu_->addAction(toggleNotifications_);
@ -88,14 +86,14 @@ TopRoomBar::TopRoomBar(QWidget *parent)
toggleNotifications_->setText(tr("Enable notifications")); toggleNotifications_->setText(tr("Enable notifications"));
auto pos = mapToGlobal(settingsBtn_->pos()); auto pos = mapToGlobal(settingsBtn_->pos());
menu_->popup(QPoint(pos.x() + buttonSize_ - menu_->sizeHint().width(), menu_->popup(QPoint(pos.x() + buttonSize_ - menu_->sizeHint().width(), pos.y() + buttonSize_));
pos.y() + buttonSize_));
}); });
setLayout(top_layout_); setLayout(top_layout_);
} }
void TopRoomBar::updateRoomAvatarFromName(const QString &name) void
TopRoomBar::updateRoomAvatarFromName(const QString &name)
{ {
QChar letter = '?'; QChar letter = '?';
@ -105,14 +103,16 @@ void TopRoomBar::updateRoomAvatarFromName(const QString &name)
avatar_->setLetter(letter); avatar_->setLetter(letter);
} }
void TopRoomBar::reset() void
TopRoomBar::reset()
{ {
name_label_->setText(""); name_label_->setText("");
topic_label_->setText(""); topic_label_->setText("");
avatar_->setLetter(QChar('?')); avatar_->setLetter(QChar('?'));
} }
void TopRoomBar::paintEvent(QPaintEvent *event) void
TopRoomBar::paintEvent(QPaintEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
@ -123,7 +123,8 @@ void TopRoomBar::paintEvent(QPaintEvent *event)
style()->drawPrimitive(QStyle::PE_Widget, &option, &painter, this); style()->drawPrimitive(QStyle::PE_Widget, &option, &painter, this);
} }
void TopRoomBar::setRoomSettings(QSharedPointer<RoomSettings> settings) void
TopRoomBar::setRoomSettings(QSharedPointer<RoomSettings> settings)
{ {
roomSettings_ = settings; roomSettings_ = settings;
} }

View file

@ -25,12 +25,13 @@
#endif #endif
MsgCountComposedIcon::MsgCountComposedIcon(const QString &filename) MsgCountComposedIcon::MsgCountComposedIcon(const QString &filename)
: QIconEngine() : QIconEngine()
{ {
icon_ = QIcon(filename); icon_ = QIcon(filename);
} }
void MsgCountComposedIcon::paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) void
MsgCountComposedIcon::paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state)
{ {
painter->setRenderHint(QPainter::TextAntialiasing); painter->setRenderHint(QPainter::TextAntialiasing);
painter->setRenderHint(QPainter::SmoothPixmapTransform); painter->setRenderHint(QPainter::SmoothPixmapTransform);
@ -52,23 +53,21 @@ void MsgCountComposedIcon::paint(QPainter *painter, const QRect &rect, QIcon::Mo
painter->setPen(Qt::NoPen); painter->setPen(Qt::NoPen);
painter->setFont(QFont("Open Sans", 8, QFont::Black)); painter->setFont(QFont("Open Sans", 8, QFont::Black));
QRectF bubble(rect.width() - BubbleDiameter, QRectF bubble(rect.width() - BubbleDiameter, rect.height() - BubbleDiameter, BubbleDiameter, BubbleDiameter);
rect.height() - BubbleDiameter,
BubbleDiameter,
BubbleDiameter);
painter->drawEllipse(bubble); painter->drawEllipse(bubble);
painter->setPen(QPen(textColor)); painter->setPen(QPen(textColor));
painter->setBrush(Qt::NoBrush); painter->setBrush(Qt::NoBrush);
painter->drawText(bubble, Qt::AlignCenter, QString::number(msgCount)); painter->drawText(bubble, Qt::AlignCenter, QString::number(msgCount));
} }
QIconEngine *MsgCountComposedIcon::clone() const QIconEngine *
MsgCountComposedIcon::clone() const
{ {
return new MsgCountComposedIcon(*this); return new MsgCountComposedIcon(*this);
} }
TrayIcon::TrayIcon(const QString &filename, QWidget *parent) TrayIcon::TrayIcon(const QString &filename, QWidget *parent)
: QSystemTrayIcon(parent) : QSystemTrayIcon(parent)
{ {
#if defined(Q_OS_MAC) || defined(Q_OS_WIN) #if defined(Q_OS_MAC) || defined(Q_OS_WIN)
setIcon(QIcon(filename)); setIcon(QIcon(filename));
@ -82,9 +81,7 @@ TrayIcon::TrayIcon(const QString &filename, QWidget *parent)
quitAction_ = new QAction(tr("Quit"), parent); quitAction_ = new QAction(tr("Quit"), parent);
connect(viewAction_, SIGNAL(triggered()), parent, SLOT(show())); connect(viewAction_, SIGNAL(triggered()), parent, SLOT(show()));
connect(quitAction_, &QAction::triggered, this, [=]() { connect(quitAction_, &QAction::triggered, this, [=]() { QApplication::quit(); });
QApplication::quit();
});
menu->addAction(viewAction_); menu->addAction(viewAction_);
menu->addAction(quitAction_); menu->addAction(quitAction_);
@ -92,12 +89,11 @@ TrayIcon::TrayIcon(const QString &filename, QWidget *parent)
setContextMenu(menu); setContextMenu(menu);
// We wait a little for the icon to load. // We wait a little for the icon to load.
QTimer::singleShot(500, this, [=]() { QTimer::singleShot(500, this, [=]() { show(); });
show();
});
} }
void TrayIcon::setUnreadCount(int count) void
TrayIcon::setUnreadCount(int count)
{ {
// Use the native badge counter in MacOS. // Use the native badge counter in MacOS.
#if defined(Q_OS_MAC) #if defined(Q_OS_MAC)

View file

@ -24,12 +24,12 @@
#include "UserInfoWidget.h" #include "UserInfoWidget.h"
UserInfoWidget::UserInfoWidget(QWidget *parent) UserInfoWidget::UserInfoWidget(QWidget *parent)
: QWidget(parent) : QWidget(parent)
, display_name_("User") , display_name_("User")
, user_id_("@user:homeserver.org") , user_id_("@user:homeserver.org")
, logoutModal_{nullptr} , logoutModal_{ nullptr }
, logoutDialog_{nullptr} , logoutDialog_{ nullptr }
, logoutButtonSize_{32} , logoutButtonSize_{ 32 }
{ {
QSizePolicy sizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); QSizePolicy sizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
setSizePolicy(sizePolicy); setSizePolicy(sizePolicy);
@ -108,15 +108,14 @@ UserInfoWidget::UserInfoWidget(QWidget *parent)
}); });
} }
void UserInfoWidget::closeLogoutDialog(bool isLoggingOut) void
UserInfoWidget::closeLogoutDialog(bool isLoggingOut)
{ {
logoutModal_->fadeOut(); logoutModal_->fadeOut();
if (isLoggingOut) { if (isLoggingOut) {
// Waiting for the modal to fade out. // Waiting for the modal to fade out.
QTimer::singleShot(100, this, [=]() { QTimer::singleShot(100, this, [=]() { emit logout(); });
emit logout();
});
} }
} }
@ -124,7 +123,8 @@ UserInfoWidget::~UserInfoWidget()
{ {
} }
void UserInfoWidget::resizeEvent(QResizeEvent *event) void
UserInfoWidget::resizeEvent(QResizeEvent *event)
{ {
Q_UNUSED(event); Q_UNUSED(event);
@ -142,20 +142,23 @@ void UserInfoWidget::resizeEvent(QResizeEvent *event)
} }
} }
void UserInfoWidget::reset() void
UserInfoWidget::reset()
{ {
displayNameLabel_->setText(""); displayNameLabel_->setText("");
userIdLabel_->setText(""); userIdLabel_->setText("");
userAvatar_->setLetter(QChar('?')); userAvatar_->setLetter(QChar('?'));
} }
void UserInfoWidget::setAvatar(const QImage &img) void
UserInfoWidget::setAvatar(const QImage &img)
{ {
avatar_image_ = img; avatar_image_ = img;
userAvatar_->setImage(img); userAvatar_->setImage(img);
} }
void UserInfoWidget::setDisplayName(const QString &name) void
UserInfoWidget::setDisplayName(const QString &name)
{ {
if (name.isEmpty()) if (name.isEmpty())
display_name_ = user_id_.split(':')[0].split('@')[1]; display_name_ = user_id_.split(':')[0].split('@')[1];
@ -166,7 +169,8 @@ void UserInfoWidget::setDisplayName(const QString &name)
userAvatar_->setLetter(QChar(display_name_[0])); userAvatar_->setLetter(QChar(display_name_[0]));
} }
void UserInfoWidget::setUserId(const QString &userid) void
UserInfoWidget::setUserId(const QString &userid)
{ {
user_id_ = userid; user_id_ = userid;
userIdLabel_->setText(userid); userIdLabel_->setText(userid);

View file

@ -24,7 +24,8 @@
#include "Deserializable.h" #include "Deserializable.h"
#include "Versions.h" #include "Versions.h"
void VersionsResponse::deserialize(const QJsonDocument &data) void
VersionsResponse::deserialize(const QJsonDocument &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("Versions response is not a JSON object"); throw DeserializationException("Versions response is not a JSON object");
@ -51,7 +52,8 @@ void VersionsResponse::deserialize(const QJsonDocument &data)
} }
} }
bool VersionsResponse::isVersionSupported(unsigned int major, unsigned int minor, unsigned int patch) bool
VersionsResponse::isVersionSupported(unsigned int major, unsigned int minor, unsigned int patch)
{ {
for (auto &v : supported_versions_) { for (auto &v : supported_versions_) {
if (v.major_ == major && v.minor_ == minor && v.patch_ >= patch) if (v.major_ == major && v.minor_ == minor && v.patch_ >= patch)

View file

@ -22,7 +22,7 @@
#include "WelcomePage.h" #include "WelcomePage.h"
WelcomePage::WelcomePage(QWidget *parent) WelcomePage::WelcomePage(QWidget *parent)
: QWidget(parent) : QWidget(parent)
{ {
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
@ -86,12 +86,14 @@ WelcomePage::WelcomePage(QWidget *parent)
connect(login_button_, SIGNAL(clicked()), this, SLOT(onLoginButtonClicked())); connect(login_button_, SIGNAL(clicked()), this, SLOT(onLoginButtonClicked()));
} }
void WelcomePage::onLoginButtonClicked() void
WelcomePage::onLoginButtonClicked()
{ {
emit userLogin(); emit userLogin();
} }
void WelcomePage::onRegisterButtonClicked() void
WelcomePage::onRegisterButtonClicked()
{ {
emit userRegister(); emit userRegister();
} }

View file

@ -21,7 +21,8 @@
using namespace matrix::events; using namespace matrix::events;
void AliasesEventContent::deserialize(const QJsonValue &data) void
AliasesEventContent::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("AliasesEventContent is not a JSON object"); throw DeserializationException("AliasesEventContent is not a JSON object");
@ -37,7 +38,8 @@ void AliasesEventContent::deserialize(const QJsonValue &data)
aliases_.push_back(alias.toString()); aliases_.push_back(alias.toString());
} }
QJsonObject AliasesEventContent::serialize() const QJsonObject
AliasesEventContent::serialize() const
{ {
QJsonObject object; QJsonObject object;

View file

@ -21,7 +21,8 @@
using namespace matrix::events; using namespace matrix::events;
void AvatarEventContent::deserialize(const QJsonValue &data) void
AvatarEventContent::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("AvatarEventContent is not a JSON object"); throw DeserializationException("AvatarEventContent is not a JSON object");
@ -37,7 +38,8 @@ void AvatarEventContent::deserialize(const QJsonValue &data)
qWarning() << "Invalid avatar url" << url_; qWarning() << "Invalid avatar url" << url_;
} }
QJsonObject AvatarEventContent::serialize() const QJsonObject
AvatarEventContent::serialize() const
{ {
QJsonObject object; QJsonObject object;

View file

@ -19,7 +19,8 @@
using namespace matrix::events; using namespace matrix::events;
void CanonicalAliasEventContent::deserialize(const QJsonValue &data) void
CanonicalAliasEventContent::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("CanonicalAliasEventContent is not a JSON object"); throw DeserializationException("CanonicalAliasEventContent is not a JSON object");
@ -32,7 +33,8 @@ void CanonicalAliasEventContent::deserialize(const QJsonValue &data)
alias_ = object.value("alias").toString(); alias_ = object.value("alias").toString();
} }
QJsonObject CanonicalAliasEventContent::serialize() const QJsonObject
CanonicalAliasEventContent::serialize() const
{ {
QJsonObject object; QJsonObject object;

View file

@ -19,7 +19,8 @@
using namespace matrix::events; using namespace matrix::events;
void CreateEventContent::deserialize(const QJsonValue &data) void
CreateEventContent::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("CreateEventContent is not a JSON object"); throw DeserializationException("CreateEventContent is not a JSON object");
@ -32,7 +33,8 @@ void CreateEventContent::deserialize(const QJsonValue &data)
creator_ = object.value("creator").toString(); creator_ = object.value("creator").toString();
} }
QJsonObject CreateEventContent::serialize() const QJsonObject
CreateEventContent::serialize() const
{ {
QJsonObject object; QJsonObject object;

View file

@ -29,7 +29,8 @@
#include "PowerLevelsEventContent.h" #include "PowerLevelsEventContent.h"
#include "TopicEventContent.h" #include "TopicEventContent.h"
matrix::events::EventType matrix::events::extractEventType(const QJsonObject &object) matrix::events::EventType
matrix::events::extractEventType(const QJsonObject &object)
{ {
if (!object.contains("type")) if (!object.contains("type"))
throw DeserializationException("Missing event type"); throw DeserializationException("Missing event type");
@ -62,21 +63,18 @@ matrix::events::EventType matrix::events::extractEventType(const QJsonObject &ob
return EventType::Unsupported; return EventType::Unsupported;
} }
bool matrix::events::isStateEvent(EventType type) bool
matrix::events::isStateEvent(EventType type)
{ {
return type == EventType::RoomAliases || return type == EventType::RoomAliases || type == EventType::RoomAvatar ||
type == EventType::RoomAvatar || type == EventType::RoomCanonicalAlias || type == EventType::RoomCreate ||
type == EventType::RoomCanonicalAlias || type == EventType::RoomHistoryVisibility || type == EventType::RoomJoinRules ||
type == EventType::RoomCreate || type == EventType::RoomMember || type == EventType::RoomName || type == EventType::RoomPowerLevels ||
type == EventType::RoomHistoryVisibility ||
type == EventType::RoomJoinRules ||
type == EventType::RoomMember ||
type == EventType::RoomName ||
type == EventType::RoomPowerLevels ||
type == EventType::RoomTopic; type == EventType::RoomTopic;
} }
bool matrix::events::isMessageEvent(EventType type) bool
matrix::events::isMessageEvent(EventType type)
{ {
return type == EventType::RoomMessage; return type == EventType::RoomMessage;
} }

View file

@ -19,7 +19,8 @@
using namespace matrix::events; using namespace matrix::events;
void HistoryVisibilityEventContent::deserialize(const QJsonValue &data) void
HistoryVisibilityEventContent::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("HistoryVisibilityEventContent is not a JSON object"); throw DeserializationException("HistoryVisibilityEventContent is not a JSON object");
@ -40,10 +41,12 @@ void HistoryVisibilityEventContent::deserialize(const QJsonValue &data)
else if (value == "world_readable") else if (value == "world_readable")
history_visibility_ = HistoryVisibility::WorldReadable; history_visibility_ = HistoryVisibility::WorldReadable;
else else
throw DeserializationException(QString("Unknown history_visibility value: %1").arg(value).toUtf8().constData()); throw DeserializationException(
QString("Unknown history_visibility value: %1").arg(value).toUtf8().constData());
} }
QJsonObject HistoryVisibilityEventContent::serialize() const QJsonObject
HistoryVisibilityEventContent::serialize() const
{ {
QJsonObject object; QJsonObject object;

View file

@ -19,7 +19,8 @@
using namespace matrix::events; using namespace matrix::events;
void JoinRulesEventContent::deserialize(const QJsonValue &data) void
JoinRulesEventContent::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("JoinRulesEventContent is not a JSON object"); throw DeserializationException("JoinRulesEventContent is not a JSON object");
@ -43,7 +44,8 @@ void JoinRulesEventContent::deserialize(const QJsonValue &data)
throw DeserializationException(QString("Unknown join_rule value: %1").arg(value).toUtf8().constData()); throw DeserializationException(QString("Unknown join_rule value: %1").arg(value).toUtf8().constData());
} }
QJsonObject JoinRulesEventContent::serialize() const QJsonObject
JoinRulesEventContent::serialize() const
{ {
QJsonObject object; QJsonObject object;

View file

@ -21,7 +21,8 @@
using namespace matrix::events; using namespace matrix::events;
void MemberEventContent::deserialize(const QJsonValue &data) void
MemberEventContent::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("MemberEventContent is not a JSON object"); throw DeserializationException("MemberEventContent is not a JSON object");
@ -56,7 +57,8 @@ void MemberEventContent::deserialize(const QJsonValue &data)
display_name_ = object.value("displayname").toString(); display_name_ = object.value("displayname").toString();
} }
QJsonObject MemberEventContent::serialize() const QJsonObject
MemberEventContent::serialize() const
{ {
QJsonObject object; QJsonObject object;

View file

@ -21,7 +21,8 @@
using namespace matrix::events; using namespace matrix::events;
MessageEventType matrix::events::extractMessageEventType(const QJsonObject &data) MessageEventType
matrix::events::extractMessageEventType(const QJsonObject &data)
{ {
if (!data.contains("content")) if (!data.contains("content"))
return MessageEventType::Unknown; return MessageEventType::Unknown;
@ -49,7 +50,8 @@ MessageEventType matrix::events::extractMessageEventType(const QJsonObject &data
return MessageEventType::Unknown; return MessageEventType::Unknown;
} }
void MessageEventContent::deserialize(const QJsonValue &data) void
MessageEventContent::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("MessageEventContent is not a JSON object"); throw DeserializationException("MessageEventContent is not a JSON object");
@ -62,7 +64,8 @@ void MessageEventContent::deserialize(const QJsonValue &data)
body_ = object.value("body").toString(); body_ = object.value("body").toString();
} }
QJsonObject MessageEventContent::serialize() const QJsonObject
MessageEventContent::serialize() const
{ {
// TODO: Add for all the message contents. // TODO: Add for all the message contents.
QJsonObject object; QJsonObject object;

View file

@ -19,7 +19,8 @@
using namespace matrix::events; using namespace matrix::events;
void NameEventContent::deserialize(const QJsonValue &data) void
NameEventContent::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("NameEventContent is not a JSON object"); throw DeserializationException("NameEventContent is not a JSON object");
@ -32,7 +33,8 @@ void NameEventContent::deserialize(const QJsonValue &data)
name_ = object.value("name").toString(); name_ = object.value("name").toString();
} }
QJsonObject NameEventContent::serialize() const QJsonObject
NameEventContent::serialize() const
{ {
QJsonObject object; QJsonObject object;

View file

@ -22,7 +22,8 @@
using namespace matrix::events; using namespace matrix::events;
void PowerLevelsEventContent::deserialize(const QJsonValue &data) void
PowerLevelsEventContent::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("PowerLevelsEventContent is not a JSON object"); throw DeserializationException("PowerLevelsEventContent is not a JSON object");
@ -65,7 +66,8 @@ void PowerLevelsEventContent::deserialize(const QJsonValue &data)
} }
} }
QJsonObject PowerLevelsEventContent::serialize() const QJsonObject
PowerLevelsEventContent::serialize() const
{ {
QJsonObject object; QJsonObject object;
@ -93,7 +95,8 @@ QJsonObject PowerLevelsEventContent::serialize() const
return object; return object;
} }
int PowerLevelsEventContent::eventLevel(QString event_type) const int
PowerLevelsEventContent::eventLevel(QString event_type) const
{ {
if (events_.contains(event_type)) if (events_.contains(event_type))
return events_[event_type]; return events_[event_type];
@ -101,7 +104,8 @@ int PowerLevelsEventContent::eventLevel(QString event_type) const
return events_default_; return events_default_;
} }
int PowerLevelsEventContent::userLevel(QString userid) const int
PowerLevelsEventContent::userLevel(QString userid) const
{ {
if (users_.contains(userid)) if (users_.contains(userid))
return users_[userid]; return users_[userid];

View file

@ -19,7 +19,8 @@
using namespace matrix::events; using namespace matrix::events;
void TopicEventContent::deserialize(const QJsonValue &data) void
TopicEventContent::deserialize(const QJsonValue &data)
{ {
if (!data.isObject()) if (!data.isObject())
throw DeserializationException("TopicEventContent is not a JSON object"); throw DeserializationException("TopicEventContent is not a JSON object");
@ -32,7 +33,8 @@ void TopicEventContent::deserialize(const QJsonValue &data)
topic_ = object.value("topic").toString(); topic_ = object.value("topic").toString();
} }
QJsonObject TopicEventContent::serialize() const QJsonObject
TopicEventContent::serialize() const
{ {
QJsonObject object; QJsonObject object;

View file

@ -19,7 +19,8 @@
using namespace matrix::events::messages; using namespace matrix::events::messages;
void Audio::deserialize(const QJsonObject &object) void
Audio::deserialize(const QJsonObject &object)
{ {
if (!object.contains("url")) if (!object.contains("url"))
throw DeserializationException("url key is missing"); throw DeserializationException("url key is missing");

View file

@ -19,7 +19,8 @@
using namespace matrix::events::messages; using namespace matrix::events::messages;
void Emote::deserialize(const QJsonObject &object) void
Emote::deserialize(const QJsonObject &object)
{ {
if (object.value("msgtype") != "m.emote") if (object.value("msgtype") != "m.emote")
throw DeserializationException("invalid msgtype for emote"); throw DeserializationException("invalid msgtype for emote");

Some files were not shown because too many files have changed in this diff Show more