From aacc4bcb4a487871daae6717f77605aaba444341 Mon Sep 17 00:00:00 2001 From: Marc Deop Date: Sat, 2 Mar 2019 12:26:57 +0100 Subject: style: apply .clang-format to all .cpp and .h files --- lib/room.cpp | 1734 +++++++++++++++++++++++++++------------------------------- 1 file changed, 798 insertions(+), 936 deletions(-) (limited to 'lib/room.cpp') diff --git a/lib/room.cpp b/lib/room.cpp index 5da9373e..c7c94fe5 100644 --- a/lib/room.cpp +++ b/lib/room.cpp @@ -13,55 +13,55 @@ * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "room.h" -#include "csapi/kicking.h" -#include "csapi/inviting.h" +#include "avatar.h" +#include "connection.h" +#include "converters.h" +#include "csapi/account-data.h" #include "csapi/banning.h" +#include "csapi/inviting.h" +#include "csapi/kicking.h" #include "csapi/leaving.h" #include "csapi/receipts.h" #include "csapi/redaction.h" -#include "csapi/account-data.h" -#include "csapi/room_state.h" #include "csapi/room_send.h" +#include "csapi/room_state.h" +#include "csapi/room_upgrades.h" #include "csapi/rooms.h" #include "csapi/tags.h" -#include "csapi/room_upgrades.h" -#include "events/simplestateevents.h" -#include "events/roomcreateevent.h" -#include "events/roomtombstoneevent.h" -#include "events/roomavatarevent.h" -#include "events/roommemberevent.h" -#include "events/typingevent.h" -#include "events/receiptevent.h" -#include "events/callinviteevent.h" -#include "events/callcandidatesevent.h" #include "events/callanswerevent.h" +#include "events/callcandidatesevent.h" #include "events/callhangupevent.h" +#include "events/callinviteevent.h" +#include "events/receiptevent.h" #include "events/redactionevent.h" -#include "jobs/mediathumbnailjob.h" +#include "events/roomavatarevent.h" +#include "events/roomcreateevent.h" +#include "events/roommemberevent.h" +#include "events/roomtombstoneevent.h" +#include "events/simplestateevents.h" +#include "events/typingevent.h" #include "jobs/downloadfilejob.h" +#include "jobs/mediathumbnailjob.h" #include "jobs/postreadmarkersjob.h" -#include "avatar.h" -#include "connection.h" -#include "user.h" -#include "converters.h" #include "syncdata.h" +#include "user.h" +#include #include -#include // for efficient string concats (operator%) +#include #include -#include -#include #include -#include +#include // for efficient string concats (operator%) +#include #include -#include #include +#include using namespace QMatrixClient; using namespace std::placeholders; @@ -75,239 +75,235 @@ enum EventsPlacement : int { Older = -1, Newer = 1 }; class Room::Private { public: - /** Map of user names to users. User names potentially duplicate, hence a multi-hashmap. */ - using members_map_t = QMultiHash; - - Private(Connection* c, QString id_, JoinState initialJoinState) - : q(nullptr), connection(c), id(move(id_)) - , joinState(initialJoinState) - { } - - Room* q; - - Connection* connection; - QString id; - JoinState joinState; - RoomSummary summary = { none, 0, none }; - /// The state of the room at timeline position before-0 - /// \sa timelineBase - std::unordered_map baseState; - /// The state of the room at timeline position after-maxTimelineIndex() - /// \sa Room::syncEdge - QHash currentState; - Timeline timeline; - PendingEvents unsyncedEvents; - QHash eventsIndex; - QString displayname; - Avatar avatar; - int highlightCount = 0; - int notificationCount = 0; - members_map_t membersMap; - QList usersTyping; - QMultiHash eventIdReadUsers; - QList membersLeft; - int unreadMessages = 0; - bool displayed = false; - QString firstDisplayedEventId; - QString lastDisplayedEventId; - QHash lastReadEventIds; - QString serverReadMarker; - TagsMap tags; - std::unordered_map accountData; - QString prevBatch; - QPointer eventsHistoryJob; - QPointer allMembersJob; - - struct FileTransferPrivateInfo + /** Map of user names to users. User names potentially duplicate, hence a + * multi-hashmap. */ + using members_map_t = QMultiHash; + + Private(Connection* c, QString id_, JoinState initialJoinState) + : q(nullptr), connection(c), id(move(id_)), joinState(initialJoinState) + { + } + + Room* q; + + Connection* connection; + QString id; + JoinState joinState; + RoomSummary summary = { none, 0, none }; + /// The state of the room at timeline position before-0 + /// \sa timelineBase + std::unordered_map baseState; + /// The state of the room at timeline position after-maxTimelineIndex() + /// \sa Room::syncEdge + QHash currentState; + Timeline timeline; + PendingEvents unsyncedEvents; + QHash eventsIndex; + QString displayname; + Avatar avatar; + int highlightCount = 0; + int notificationCount = 0; + members_map_t membersMap; + QList usersTyping; + QMultiHash eventIdReadUsers; + QList membersLeft; + int unreadMessages = 0; + bool displayed = false; + QString firstDisplayedEventId; + QString lastDisplayedEventId; + QHash lastReadEventIds; + QString serverReadMarker; + TagsMap tags; + std::unordered_map accountData; + QString prevBatch; + QPointer eventsHistoryJob; + QPointer allMembersJob; + + struct FileTransferPrivateInfo { + FileTransferPrivateInfo() = default; + FileTransferPrivateInfo(BaseJob* j, const QString& fileName, + bool isUploading = false) + : status(FileTransferInfo::Started), + job(j), + localFileInfo(fileName), + isUpload(isUploading) { - FileTransferPrivateInfo() = default; - FileTransferPrivateInfo(BaseJob* j, const QString& fileName, - bool isUploading = false) - : status(FileTransferInfo::Started), job(j) - , localFileInfo(fileName), isUpload(isUploading) - { } - - FileTransferInfo::Status status = FileTransferInfo::None; - QPointer job = nullptr; - QFileInfo localFileInfo { }; - bool isUpload = false; - qint64 progress = 0; - qint64 total = -1; - - void update(qint64 p, qint64 t) - { - if (t == 0) - { - t = -1; - if (p == 0) - p = -1; - } - if (p != -1) - qCDebug(PROFILER) << "Transfer progress:" << p << "/" << t - << "=" << llround(double(p) / t * 100) << "%"; - progress = p; total = t; - } - }; - void failedTransfer(const QString& tid, const QString& errorMessage = {}) + } + + FileTransferInfo::Status status = FileTransferInfo::None; + QPointer job = nullptr; + QFileInfo localFileInfo {}; + bool isUpload = false; + qint64 progress = 0; + qint64 total = -1; + + void update(qint64 p, qint64 t) { - qCWarning(MAIN) << "File transfer failed for id" << tid; - if (!errorMessage.isEmpty()) - qCWarning(MAIN) << "Message:" << errorMessage; - fileTransfers[tid].status = FileTransferInfo::Failed; - emit q->fileTransferFailed(tid, errorMessage); + if (t == 0) { + t = -1; + if (p == 0) + p = -1; + } + if (p != -1) + qCDebug(PROFILER) << "Transfer progress:" << p << "/" << t + << "=" << llround(double(p) / t * 100) << "%"; + progress = p; + total = t; } - /// A map from event/txn ids to information about the long operation; - /// used for both download and upload operations - QHash fileTransfers; + }; + void failedTransfer(const QString& tid, const QString& errorMessage = {}) + { + qCWarning(MAIN) << "File transfer failed for id" << tid; + if (!errorMessage.isEmpty()) + qCWarning(MAIN) << "Message:" << errorMessage; + fileTransfers[tid].status = FileTransferInfo::Failed; + emit q->fileTransferFailed(tid, errorMessage); + } + /// A map from event/txn ids to information about the long operation; + /// used for both download and upload operations + QHash fileTransfers; - const RoomMessageEvent* getEventWithFile(const QString& eventId) const; - QString fileNameToDownload(const RoomMessageEvent* event) const; + const RoomMessageEvent* getEventWithFile(const QString& eventId) const; + QString fileNameToDownload(const RoomMessageEvent* event) const; - Changes setSummary(RoomSummary&& newSummary); + Changes setSummary(RoomSummary&& newSummary); - //void inviteUser(User* u); // We might get it at some point in time. - void insertMemberIntoMap(User* u); - void renameMember(User* u, QString oldName); - void removeMemberFromMap(const QString& username, User* u); + // void inviteUser(User* u); // We might get it at some point in time. + void insertMemberIntoMap(User* u); + void renameMember(User* u, QString oldName); + void removeMemberFromMap(const QString& username, User* u); - // This updates the room displayname field (which is the way a room - // should be shown in the room list); called whenever the list of - // members, the room name (m.room.name) or canonical alias change. - void updateDisplayname(); - // This is used by updateDisplayname() but only calculates the new name - // without any updates. - QString calculateDisplayname() const; + // This updates the room displayname field (which is the way a room + // should be shown in the room list); called whenever the list of + // members, the room name (m.room.name) or canonical alias change. + void updateDisplayname(); + // This is used by updateDisplayname() but only calculates the new name + // without any updates. + QString calculateDisplayname() const; - /// A point in the timeline corresponding to baseState - rev_iter_t timelineBase() const { return q->findInTimeline(-1); } + /// A point in the timeline corresponding to baseState + rev_iter_t timelineBase() const { return q->findInTimeline(-1); } - void getPreviousContent(int limit = 10); + void getPreviousContent(int limit = 10); - template - const EventT* getCurrentState(QString stateKey = {}) const - { - static const EventT empty; - const auto* evt = - currentState.value({EventT::matrixTypeId(), stateKey}, &empty); - Q_ASSERT(evt->type() == EventT::typeId() && - evt->matrixType() == EventT::matrixTypeId()); - return static_cast(evt); - } + template + const EventT* getCurrentState(QString stateKey = {}) const + { + static const EventT empty; + const auto* evt = currentState.value( + { EventT::matrixTypeId(), stateKey }, &empty); + Q_ASSERT(evt->type() == EventT::typeId() + && evt->matrixType() == EventT::matrixTypeId()); + return static_cast(evt); + } - bool isEventNotable(const TimelineItem& ti) const - { - return !ti->isRedacted() && - ti->senderId() != connection->userId() && - is(*ti); - } + bool isEventNotable(const TimelineItem& ti) const + { + return !ti->isRedacted() && ti->senderId() != connection->userId() + && is(*ti); + } - template - Changes updateStateFrom(EventArrayT&& events) - { - Changes changes = NoChange; - if (!events.empty()) - { - QElapsedTimer et; et.start(); - for (auto&& eptr: events) - { - const auto& evt = *eptr; - Q_ASSERT(evt.isStateEvent()); - // Update baseState afterwards to make sure that the old state - // is valid and usable inside processStateEvent - changes |= q->processStateEvent(evt); - baseState[{evt.matrixType(),evt.stateKey()}] = move(eptr); - } - if (events.size() > 9 || et.nsecsElapsed() >= profilerMinNsecs()) - qCDebug(PROFILER) << "*** Room::Private::updateStateFrom():" - << events.size() << "event(s)," << et; + template + Changes updateStateFrom(EventArrayT&& events) + { + Changes changes = NoChange; + if (!events.empty()) { + QElapsedTimer et; + et.start(); + for (auto&& eptr : events) { + const auto& evt = *eptr; + Q_ASSERT(evt.isStateEvent()); + // Update baseState afterwards to make sure that the old state + // is valid and usable inside processStateEvent + changes |= q->processStateEvent(evt); + baseState[{ evt.matrixType(), evt.stateKey() }] = move(eptr); } - return changes; - } - Changes addNewMessageEvents(RoomEvents&& events); - void addHistoricalMessageEvents(RoomEvents&& events); - - /** Move events into the timeline - * - * Insert events into the timeline, either new or historical. - * Pointers in the original container become empty, the ownership - * is passed to the timeline container. - * @param events - the range of events to be inserted - * @param placement - position and direction of insertion: Older for - * historical messages, Newer for new ones - */ - Timeline::difference_type moveEventsToTimeline(RoomEventsRange events, - EventsPlacement placement); - - /** - * Remove events from the passed container that are already in the timeline - */ - void dropDuplicateEvents(RoomEvents& events) const; - - Changes setLastReadEvent(User* u, QString eventId); - void updateUnreadCount(rev_iter_t from, rev_iter_t to); - Changes promoteReadMarker(User* u, rev_iter_t newMarker, - bool force = false); - - Changes markMessagesAsRead(rev_iter_t upToMarker); - - void getAllMembers(); - - QString sendEvent(RoomEventPtr&& event); - - template - QString sendEvent(ArgTs&&... eventArgs) - { - return sendEvent(makeEvent(std::forward(eventArgs)...)); + if (events.size() > 9 || et.nsecsElapsed() >= profilerMinNsecs()) + qCDebug(PROFILER) << "*** Room::Private::updateStateFrom():" + << events.size() << "event(s)," << et; } + return changes; + } + Changes addNewMessageEvents(RoomEvents&& events); + void addHistoricalMessageEvents(RoomEvents&& events); + + /** Move events into the timeline + * + * Insert events into the timeline, either new or historical. + * Pointers in the original container become empty, the ownership + * is passed to the timeline container. + * @param events - the range of events to be inserted + * @param placement - position and direction of insertion: Older for + * historical messages, Newer for new ones + */ + Timeline::difference_type moveEventsToTimeline(RoomEventsRange events, + EventsPlacement placement); + + /** + * Remove events from the passed container that are already in the timeline + */ + void dropDuplicateEvents(RoomEvents& events) const; + + Changes setLastReadEvent(User* u, QString eventId); + void updateUnreadCount(rev_iter_t from, rev_iter_t to); + Changes promoteReadMarker(User* u, rev_iter_t newMarker, + bool force = false); + + Changes markMessagesAsRead(rev_iter_t upToMarker); + + void getAllMembers(); + + QString sendEvent(RoomEventPtr&& event); + + template + QString sendEvent(ArgTs&&... eventArgs) + { + return sendEvent(makeEvent(std::forward(eventArgs)...)); + } - RoomEvent* addAsPending(RoomEventPtr&& event); + RoomEvent* addAsPending(RoomEventPtr&& event); - QString doSendEvent(const RoomEvent* pEvent); - void onEventSendingFailure(const QString& txnId, BaseJob* call = nullptr); + QString doSendEvent(const RoomEvent* pEvent); + void onEventSendingFailure(const QString& txnId, BaseJob* call = nullptr); - template - SetRoomStateWithKeyJob* requestSetState(const QString& stateKey, - const EvT& event) - { - if (q->successorId().isEmpty()) - { - // TODO: Queue up state events sending (see #133). - return connection->callApi( - id, EvT::matrixTypeId(), stateKey, event.contentJson()); - } - qCWarning(MAIN) << q << "has been upgraded, state won't be set"; - return nullptr; + template + SetRoomStateWithKeyJob* requestSetState(const QString& stateKey, + const EvT& event) + { + if (q->successorId().isEmpty()) { + // TODO: Queue up state events sending (see #133). + return connection->callApi( + id, EvT::matrixTypeId(), stateKey, event.contentJson()); } + qCWarning(MAIN) << q << "has been upgraded, state won't be set"; + return nullptr; + } - template - auto requestSetState(const EvT& event) - { - return connection->callApi( - id, EvT::matrixTypeId(), event.contentJson()); - } + template auto requestSetState(const EvT& event) + { + return connection->callApi(id, EvT::matrixTypeId(), + event.contentJson()); + } - /** - * @brief Apply redaction to the timeline - * - * Tries to find an event in the timeline and redact it; deletes the - * redaction event whether the redacted event was found or not. - */ - bool processRedaction(const RedactionEvent& redaction); + /** + * @brief Apply redaction to the timeline + * + * Tries to find an event in the timeline and redact it; deletes the + * redaction event whether the redacted event was found or not. + */ + bool processRedaction(const RedactionEvent& redaction); - void setTags(TagsMap newTags); + void setTags(TagsMap newTags); - QJsonObject toJson() const; + QJsonObject toJson() const; private: - using users_shortlist_t = std::array; - template - users_shortlist_t buildShortlist(const ContT& users) const; - users_shortlist_t buildShortlist(const QStringList& userIds) const; + using users_shortlist_t = std::array; + template + users_shortlist_t buildShortlist(const ContT& users) const; + users_shortlist_t buildShortlist(const QStringList& userIds) const; - bool isLocalUser(const User* u) const - { - return u == q->localUser(); - } + bool isLocalUser(const User* u) const { return u == q->localUser(); } }; Room::Room(Connection* connection, QString id, JoinState initialJoinState) @@ -318,24 +314,18 @@ Room::Room(Connection* connection, QString id, JoinState initialJoinState) // https://marcmutz.wordpress.com/translated-articles/pimp-my-pimpl-%E2%80%94-reloaded/ d->q = this; d->displayname = d->calculateDisplayname(); // Set initial "Empty room" name - connectUntil(connection, &Connection::loadedRoomState, this, - [this] (Room* r) { - if (this == r) - emit baseStateLoaded(); - return this == r; // loadedRoomState fires only once per room - }); + connectUntil( + connection, &Connection::loadedRoomState, this, [this](Room* r) { + if (this == r) + emit baseStateLoaded(); + return this == r; // loadedRoomState fires only once per room + }); qCDebug(MAIN) << "New" << toCString(initialJoinState) << "Room:" << id; } -Room::~Room() -{ - delete d; -} +Room::~Room() { delete d; } -const QString& Room::id() const -{ - return d->id; -} +const QString& Room::id() const { return d->id; } QString Room::version() const { @@ -345,8 +335,8 @@ QString Room::version() const bool Room::isUnstable() const { - return !connection()->loadingCapabilities() && - !connection()->stableRoomVersions().contains(version()); + return !connection()->loadingCapabilities() + && !connection()->stableRoomVersions().contains(version()); } QString Room::predecessorId() const @@ -359,10 +349,7 @@ QString Room::successorId() const return d->getCurrentState()->successorRoomId(); } -const Room::Timeline& Room::messageEvents() const -{ - return d->timeline; -} +const Room::Timeline& Room::messageEvents() const { return d->timeline; } const Room::PendingEvents& Room::pendingEvents() const { @@ -384,35 +371,20 @@ QString Room::canonicalAlias() const return d->getCurrentState()->alias(); } -QString Room::displayName() const -{ - return d->displayname; -} +QString Room::displayName() const { return d->displayname; } QString Room::topic() const { return d->getCurrentState()->topic(); } -QString Room::avatarMediaId() const -{ - return d->avatar.mediaId(); -} +QString Room::avatarMediaId() const { return d->avatar.mediaId(); } -QUrl Room::avatarUrl() const -{ - return d->avatar.url(); -} +QUrl Room::avatarUrl() const { return d->avatar.url(); } -const Avatar& Room::avatarObject() const -{ - return d->avatar; -} +const Avatar& Room::avatarObject() const { return d->avatar; } -QImage Room::avatar(int dimension) -{ - return avatar(dimension, dimension); -} +QImage Room::avatar(int dimension) { return avatar(dimension, dimension); } QImage Room::avatar(int width, int height) { @@ -422,9 +394,10 @@ QImage Room::avatar(int width, int height) // Use the first (excluding self) user's avatar for direct chats const auto dcUsers = directChatUsers(); - for (auto* u: dcUsers) + for (auto* u : dcUsers) if (u != localUser()) - return u->avatar(width, height, this, [=] { emit avatarChanged(); }); + return u->avatar(width, height, this, + [=] { emit avatarChanged(); }); return {}; } @@ -436,24 +409,20 @@ User* Room::user(const QString& userId) const JoinState Room::memberJoinState(User* user) const { - return - d->membersMap.contains(user->name(this), user) ? JoinState::Join : - JoinState::Leave; + return d->membersMap.contains(user->name(this), user) ? JoinState::Join + : JoinState::Leave; } -JoinState Room::joinState() const -{ - return d->joinState; -} +JoinState Room::joinState() const { return d->joinState; } void Room::setJoinState(JoinState state) { JoinState oldState = d->joinState; - if( state == oldState ) + if (state == oldState) return; d->joinState = state; - qCDebug(MAIN) << "Room" << id() << "changed state: " - << int(oldState) << "->" << int(state); + qCDebug(MAIN) << "Room" << id() << "changed state: " << int(oldState) + << "->" << int(state); emit changed(Change::JoinStateChange); emit joinStateChanged(oldState, state); } @@ -468,8 +437,7 @@ Room::Changes Room::Private::setLastReadEvent(User* u, QString eventId) swap(storedId, eventId); emit q->lastReadEventChanged(u); emit q->readMarkerForUserMoved(u, eventId, storedId); - if (isLocalUser(u)) - { + if (isLocalUser(u)) { if (storedId != serverReadMarker) connection->callApi(id, storedId); emit q->readMarkerMoved(eventId, storedId); @@ -488,32 +456,33 @@ void Room::Private::updateUnreadCount(rev_iter_t from, rev_iter_t to) // unreadMessages and might need to promote the read marker further // over local-origin messages. const auto readMarker = q->readMarker(); - if (readMarker >= from && readMarker < to) - { + if (readMarker >= from && readMarker < to) { promoteReadMarker(q->localUser(), readMarker, true); return; } Q_ASSERT(to <= readMarker); - QElapsedTimer et; et.start(); - const auto newUnreadMessages = count_if(from, to, - std::bind(&Room::Private::isEventNotable, this, _1)); + QElapsedTimer et; + et.start(); + const auto newUnreadMessages = count_if( + from, to, std::bind(&Room::Private::isEventNotable, this, _1)); if (et.nsecsElapsed() > profilerMinNsecs() / 10) qCDebug(PROFILER) << "Counting gained unread messages took" << et; - if(newUnreadMessages > 0) - { - // See https://github.com/QMatrixClient/libqmatrixclient/wiki/unread_count + if (newUnreadMessages > 0) { + // See + // https://github.com/QMatrixClient/libqmatrixclient/wiki/unread_count if (unreadMessages < 0) unreadMessages = 0; unreadMessages += newUnreadMessages; qCDebug(MAIN) << "Room" << q->objectName() << "has gained" - << newUnreadMessages << "unread message(s)," - << (q->readMarker() == timeline.crend() ? - "in total at least" : "in total") - << unreadMessages << "unread message(s)"; + << newUnreadMessages << "unread message(s)," + << (q->readMarker() == timeline.crend() + ? "in total at least" + : "in total") + << unreadMessages << "unread message(s)"; emit q->unreadMessagesChanged(q); } } @@ -525,34 +494,36 @@ Room::Changes Room::Private::promoteReadMarker(User* u, rev_iter_t newMarker, Q_ASSERT(newMarker >= timeline.crbegin() && newMarker <= timeline.crend()); const auto prevMarker = q->readMarker(u); - if (!force && prevMarker <= newMarker) // Remember, we deal with reverse iterators + if (!force + && prevMarker <= newMarker) // Remember, we deal with reverse iterators return Change::NoChange; Q_ASSERT(newMarker < timeline.crend()); // Try to auto-promote the read marker over the user's own messages // (switch to direct iterators for that). - auto eagerMarker = find_if(newMarker.base(), timeline.cend(), - [=](const TimelineItem& ti) { return ti->senderId() != u->id(); }); + auto eagerMarker = find_if( + newMarker.base(), timeline.cend(), + [=](const TimelineItem& ti) { return ti->senderId() != u->id(); }); auto changes = setLastReadEvent(u, (*(eagerMarker - 1))->id()); - if (isLocalUser(u)) - { + if (isLocalUser(u)) { const auto oldUnreadCount = unreadMessages; - QElapsedTimer et; et.start(); - unreadMessages = count_if(eagerMarker, timeline.cend(), - std::bind(&Room::Private::isEventNotable, this, _1)); + QElapsedTimer et; + et.start(); + unreadMessages = + count_if(eagerMarker, timeline.cend(), + std::bind(&Room::Private::isEventNotable, this, _1)); if (et.nsecsElapsed() > profilerMinNsecs() / 10) qCDebug(PROFILER) << "Recounting unread messages took" << et; - // See https://github.com/QMatrixClient/libqmatrixclient/wiki/unread_count + // See + // https://github.com/QMatrixClient/libqmatrixclient/wiki/unread_count if (unreadMessages == 0) unreadMessages = -1; - if (force || unreadMessages != oldUnreadCount) - { - if (unreadMessages == -1) - { + if (force || unreadMessages != oldUnreadCount) { + if (unreadMessages == -1) { qCDebug(MAIN) << "Room" << displayname << "has no more unread messages"; } else @@ -575,10 +546,8 @@ Room::Changes Room::Private::markMessagesAsRead(rev_iter_t upToMarker) // We shouldn't send read receipts for the local user's own messages - so // search earlier messages for the latest message not from the local user // until the previous last-read message, whichever comes first. - for (; upToMarker < prevMarker; ++upToMarker) - { - if ((*upToMarker)->senderId() != q->localUser()->id()) - { + for (; upToMarker < prevMarker; ++upToMarker) { + if ((*upToMarker)->senderId() != q->localUser()->id()) { connection->callApi(id, "m.read", (*upToMarker)->id()); break; @@ -601,47 +570,36 @@ void Room::markAllMessagesAsRead() bool Room::canSwitchVersions() const { // TODO, #276: m.room.power_levels - const auto* plEvt = - d->currentState.value({"m.room.power_levels", ""}); + const auto* plEvt = d->currentState.value({ "m.room.power_levels", "" }); if (!plEvt) return true; const auto plJson = plEvt->contentJson(); const auto currentUserLevel = - plJson.value("users"_ls).toObject() - .value(localUser()->id()).toInt( - plJson.value("users_default"_ls).toInt()); + plJson.value("users"_ls) + .toObject() + .value(localUser()->id()) + .toInt(plJson.value("users_default"_ls).toInt()); const auto tombstonePowerLevel = - plJson.value("events").toObject() - .value("m.room.tombstone"_ls).toInt( - plJson.value("state_default"_ls).toInt()); + plJson.value("events") + .toObject() + .value("m.room.tombstone"_ls) + .toInt(plJson.value("state_default"_ls).toInt()); return currentUserLevel >= tombstonePowerLevel; } -bool Room::hasUnreadMessages() const -{ - return unreadCount() >= 0; -} +bool Room::hasUnreadMessages() const { return unreadCount() >= 0; } -int Room::unreadCount() const -{ - return d->unreadMessages; -} +int Room::unreadCount() const { return d->unreadMessages; } -Room::rev_iter_t Room::historyEdge() const -{ - return d->timeline.crend(); -} +Room::rev_iter_t Room::historyEdge() const { return d->timeline.crend(); } Room::Timeline::const_iterator Room::syncEdge() const { return d->timeline.cend(); } -Room::rev_iter_t Room::timelineEdge() const -{ - return historyEdge(); -} +Room::rev_iter_t Room::timelineEdge() const { return historyEdge(); } TimelineItem::index_t Room::minTimelineIndex() const { @@ -655,21 +613,19 @@ TimelineItem::index_t Room::maxTimelineIndex() const bool Room::isValidIndex(TimelineItem::index_t timelineIndex) const { - return !d->timeline.empty() && - timelineIndex >= minTimelineIndex() && - timelineIndex <= maxTimelineIndex(); + return !d->timeline.empty() && timelineIndex >= minTimelineIndex() + && timelineIndex <= maxTimelineIndex(); } Room::rev_iter_t Room::findInTimeline(TimelineItem::index_t index) const { - return timelineEdge() - - (isValidIndex(index) ? index - minTimelineIndex() + 1 : 0); + return timelineEdge() + - (isValidIndex(index) ? index - minTimelineIndex() + 1 : 0); } Room::rev_iter_t Room::findInTimeline(const QString& evtId) const { - if (!d->timeline.empty() && d->eventsIndex.contains(evtId)) - { + if (!d->timeline.empty() && d->eventsIndex.contains(evtId)) { auto it = findInTimeline(d->eventsIndex.value(evtId)); Q_ASSERT((*it)->id() == evtId); return it; @@ -680,14 +636,18 @@ Room::rev_iter_t Room::findInTimeline(const QString& evtId) const Room::PendingEvents::iterator Room::findPendingEvent(const QString& txnId) { return std::find_if(d->unsyncedEvents.begin(), d->unsyncedEvents.end(), - [txnId] (const auto& item) { return item->transactionId() == txnId; }); + [txnId](const auto& item) { + return item->transactionId() == txnId; + }); } Room::PendingEvents::const_iterator Room::findPendingEvent(const QString& txnId) const { return std::find_if(d->unsyncedEvents.cbegin(), d->unsyncedEvents.cend(), - [txnId] (const auto& item) { return item->transactionId() == txnId; }); + [txnId](const auto& item) { + return item->transactionId() == txnId; + }); } void Room::Private::getAllMembers() @@ -697,28 +657,25 @@ void Room::Private::getAllMembers() return; allMembersJob = connection->callApi( - id, connection->nextBatchToken(), "join"); + id, connection->nextBatchToken(), "join"); auto nextIndex = timeline.empty() ? 0 : timeline.back().index() + 1; - connect( allMembersJob, &BaseJob::success, q, [=] { + connect(allMembersJob, &BaseJob::success, q, [=] { Q_ASSERT(timeline.empty() || nextIndex <= q->maxTimelineIndex() + 1); auto roomChanges = updateStateFrom(allMembersJob->chunk()); // Replay member events that arrived after the point for which // the full members list was requested. - if (!timeline.empty() ) + if (!timeline.empty()) for (auto it = q->findInTimeline(nextIndex).base(); it != timeline.cend(); ++it) if (is(**it)) roomChanges |= q->processStateEvent(**it); - if (roomChanges&MembersChange) + if (roomChanges & MembersChange) emit q->memberListChanged(); emit q->allMembersLoaded(); }); } -bool Room::displayed() const -{ - return d->displayed; -} +bool Room::displayed() const { return d->displayed; } void Room::setDisplayed(bool displayed) { @@ -727,18 +684,14 @@ void Room::setDisplayed(bool displayed) d->displayed = displayed; emit displayedChanged(displayed); - if( displayed ) - { + if (displayed) { resetHighlightCount(); resetNotificationCount(); d->getAllMembers(); } } -QString Room::firstDisplayedEventId() const -{ - return d->firstDisplayedEventId; -} +QString Room::firstDisplayedEventId() const { return d->firstDisplayedEventId; } Room::rev_iter_t Room::firstDisplayedMarker() const { @@ -760,10 +713,7 @@ void Room::setFirstDisplayedEvent(TimelineItem::index_t index) setFirstDisplayedEventId(findInTimeline(index)->event()->id()); } -QString Room::lastDisplayedEventId() const -{ - return d->lastDisplayedEventId; -} +QString Room::lastDisplayedEventId() const { return d->lastDisplayedEventId; } Room::rev_iter_t Room::lastDisplayedMarker() const { @@ -791,41 +741,33 @@ Room::rev_iter_t Room::readMarker(const User* user) const return findInTimeline(d->lastReadEventIds.value(user)); } -Room::rev_iter_t Room::readMarker() const -{ - return readMarker(localUser()); -} +Room::rev_iter_t Room::readMarker() const { return readMarker(localUser()); } QString Room::readMarkerEventId() const { return d->lastReadEventIds.value(localUser()); } -QList Room::usersAtEventId(const QString& eventId) { +QList Room::usersAtEventId(const QString& eventId) +{ return d->eventIdReadUsers.values(eventId); } -int Room::notificationCount() const -{ - return d->notificationCount; -} +int Room::notificationCount() const { return d->notificationCount; } void Room::resetNotificationCount() { - if( d->notificationCount == 0 ) + if (d->notificationCount == 0) return; d->notificationCount = 0; emit notificationCountChanged(this); } -int Room::highlightCount() const -{ - return d->highlightCount; -} +int Room::highlightCount() const { return d->highlightCount; } void Room::resetHighlightCount() { - if( d->highlightCount == 0 ) + if (d->highlightCount == 0) return; d->highlightCount = 0; emit highlightCountChanged(this); @@ -834,9 +776,8 @@ void Room::resetHighlightCount() void Room::switchVersion(QString newVersion) { auto* job = connection()->callApi(id(), newVersion); - connect(job, &BaseJob::failure, this, [this,job] { - emit upgradeFailed(job->errorString()); - }); + connect(job, &BaseJob::failure, this, + [this, job] { emit upgradeFailed(job->errorString()); }); } bool Room::hasAccountData(const QString& type) const @@ -851,20 +792,11 @@ const EventPtr& Room::accountData(const QString& type) const return it != d->accountData.end() ? it->second : NoEventPtr; } -QStringList Room::tagNames() const -{ - return d->tags.keys(); -} +QStringList Room::tagNames() const { return d->tags.keys(); } -TagsMap Room::tags() const -{ - return d->tags; -} +TagsMap Room::tags() const { return d->tags; } -TagRecord Room::tag(const QString& name) const -{ - return d->tags.value(name); -} +TagRecord Room::tag(const QString& name) const { return d->tags.value(name); } std::pair validatedTag(QString name) { @@ -882,8 +814,8 @@ std::pair validatedTag(QString name) void Room::addTag(const QString& name, const TagRecord& record) { const auto& checkRes = validatedTag(name); - if (d->tags.contains(name) || - (checkRes.first && d->tags.contains(checkRes.second))) + if (d->tags.contains(name) + || (checkRes.first && d->tags.contains(checkRes.second))) return; emit tagsAboutToChange(); @@ -895,13 +827,12 @@ void Room::addTag(const QString& name, const TagRecord& record) void Room::addTag(const QString& name, float order) { - addTag(name, TagRecord{order}); + addTag(name, TagRecord { order }); } void Room::removeTag(const QString& name) { - if (d->tags.contains(name)) - { + if (d->tags.contains(name)) { emit tagsAboutToChange(); d->tags.remove(name); emit tagsChanged(); @@ -918,18 +849,16 @@ void Room::setTags(TagsMap newTags) d->setTags(move(newTags)); connection()->callApi( localUser()->id(), id(), TagEvent::matrixTypeId(), - TagEvent(d->tags).contentJson()); + TagEvent(d->tags).contentJson()); } void Room::Private::setTags(TagsMap newTags) { emit q->tagsAboutToChange(); const auto keys = newTags.keys(); - for (const auto& k: keys) - { + for (const auto& k : keys) { const auto& checkRes = validatedTag(k); - if (checkRes.first) - { + if (checkRes.first) { if (newTags.contains(checkRes.second)) newTags.remove(k); else @@ -942,20 +871,11 @@ void Room::Private::setTags(TagsMap newTags) emit q->tagsChanged(); } -bool Room::isFavourite() const -{ - return d->tags.contains(FavouriteTag); -} +bool Room::isFavourite() const { return d->tags.contains(FavouriteTag); } -bool Room::isLowPriority() const -{ - return d->tags.contains(LowPriorityTag); -} +bool Room::isLowPriority() const { return d->tags.contains(LowPriorityTag); } -bool Room::isDirectChat() const -{ - return connection()->isDirectChat(id()); -} +bool Room::isDirectChat() const { return connection()->isDirectChat(id()); } QList Room::directChatUsers() const { @@ -966,8 +886,7 @@ const RoomMessageEvent* Room::Private::getEventWithFile(const QString& eventId) const { auto evtIt = q->findInTimeline(eventId); - if (evtIt != timeline.rend() && is(**evtIt)) - { + if (evtIt != timeline.rend() && is(**evtIt)) { auto* event = evtIt->viewAs(); if (event->hasFileContent()) return event; @@ -981,12 +900,9 @@ QString Room::Private::fileNameToDownload(const RoomMessageEvent* event) const Q_ASSERT(event->hasFileContent()); const auto* fileInfo = event->content()->fileInfo(); QString fileName; - if (!fileInfo->originalName.isEmpty()) - { + if (!fileInfo->originalName.isEmpty()) { fileName = QFileInfo(fileInfo->originalName).fileName(); - } - else if (!event->plainBody().isEmpty()) - { + } else if (!event->plainBody().isEmpty()) { // Having no better options, assume that the body has // the original file URL or at least the file name. QUrl u { event->plainBody() }; @@ -997,13 +913,13 @@ QString Room::Private::fileNameToDownload(const RoomMessageEvent* event) const if (fileName.isEmpty() || !QTemporaryFile(fileName).open()) return "file." % fileInfo->mimeType.preferredSuffix(); - if (QSysInfo::productType() == "windows") - { + if (QSysInfo::productType() == "windows") { const auto& suffixes = fileInfo->mimeType.suffixes(); - if (!suffixes.isEmpty() && - std::none_of(suffixes.begin(), suffixes.end(), - [&fileName] (const QString& s) { - return fileName.endsWith(s); })) + if (!suffixes.isEmpty() + && std::none_of(suffixes.begin(), suffixes.end(), + [&fileName](const QString& s) { + return fileName.endsWith(s); + })) return fileName % '.' % fileInfo->mimeType.preferredSuffix(); } return fileName; @@ -1012,12 +928,12 @@ QString Room::Private::fileNameToDownload(const RoomMessageEvent* event) const QUrl Room::urlToThumbnail(const QString& eventId) const { if (auto* event = d->getEventWithFile(eventId)) - if (event->hasThumbnail()) - { + if (event->hasThumbnail()) { auto* thumbnail = event->content()->thumbnailInfo(); Q_ASSERT(thumbnail != nullptr); return MediaThumbnailJob::makeRequestUrl(connection()->homeserver(), - thumbnail->url, thumbnail->imageSize); + thumbnail->url, + thumbnail->imageSize); } qDebug() << "Event" << eventId << "has no thumbnail"; return {}; @@ -1025,8 +941,7 @@ QUrl Room::urlToThumbnail(const QString& eventId) const QUrl Room::urlToDownload(const QString& eventId) const { - if (auto* event = d->getEventWithFile(eventId)) - { + if (auto* event = d->getEventWithFile(eventId)) { auto* fileInfo = event->content()->fileInfo(); Q_ASSERT(fileInfo != nullptr); return DownloadFileJob::makeRequestUrl(connection()->homeserver(), @@ -1053,8 +968,7 @@ FileTransferInfo Room::fileTransferInfo(const QString& id) const qint64 progress = infoIt->progress; qint64 total = infoIt->total; - if (total > INT_MAX) - { + if (total > INT_MAX) { // JavaScript doesn't deal with 64-bit integers; scale down if necessary progress = llround(double(progress) / total * INT_MAX); total = INT_MAX; @@ -1066,13 +980,16 @@ FileTransferInfo Room::fileTransferInfo(const QString& id) const fti.progress = int(progress); fti.total = int(total); fti.localDir = QUrl::fromLocalFile(infoIt->localFileInfo.absolutePath()); - fti.localPath = QUrl::fromLocalFile(infoIt->localFileInfo.absoluteFilePath()); + fti.localPath = + QUrl::fromLocalFile(infoIt->localFileInfo.absoluteFilePath()); return fti; #else - return { infoIt->status, infoIt->isUpload, int(progress), int(total), - QUrl::fromLocalFile(infoIt->localFileInfo.absolutePath()), - QUrl::fromLocalFile(infoIt->localFileInfo.absoluteFilePath()) - }; + return { infoIt->status, + infoIt->isUpload, + int(progress), + int(total), + QUrl::fromLocalFile(infoIt->localFileInfo.absolutePath()), + QUrl::fromLocalFile(infoIt->localFileInfo.absoluteFilePath()) }; #endif } @@ -1096,39 +1013,24 @@ QString Room::prettyPrint(const QString& plainText) const return QMatrixClient::prettyPrint(plainText); } -QList< User* > Room::usersTyping() const -{ - return d->usersTyping; -} +QList Room::usersTyping() const { return d->usersTyping; } -QList< User* > Room::membersLeft() const -{ - return d->membersLeft; -} +QList Room::membersLeft() const { return d->membersLeft; } -QList< User* > Room::users() const -{ - return d->membersMap.values(); -} +QList Room::users() const { return d->membersMap.values(); } QStringList Room::memberNames() const { QStringList res; for (auto u : qAsConst(d->membersMap)) - res.append( roomMembername(u) ); + res.append(roomMembername(u)); return res; } -int Room::memberCount() const -{ - return d->membersMap.size(); -} +int Room::memberCount() const { return d->membersMap.size(); } -int Room::timelineSize() const -{ - return int(d->timeline.size()); -} +int Room::timelineSize() const { return int(d->timeline.size()); } bool Room::usesEncryption() const { @@ -1149,31 +1051,25 @@ int Room::invitedCount() const return d->summary.invitedMemberCount.value(); } -int Room::totalMemberCount() const -{ - return joinedCount() + invitedCount(); -} +int Room::totalMemberCount() const { return joinedCount() + invitedCount(); } -GetRoomEventsJob* Room::eventsHistoryJob() const -{ - return d->eventsHistoryJob; -} +GetRoomEventsJob* Room::eventsHistoryJob() const { return d->eventsHistoryJob; } Room::Changes Room::Private::setSummary(RoomSummary&& newSummary) { if (!summary.merge(newSummary)) return Change::NoChange; - qCDebug(MAIN).nospace().noquote() - << "Updated room summary for " << q->objectName() << ": " << summary; + qCDebug(MAIN).nospace().noquote() << "Updated room summary for " + << q->objectName() << ": " << summary; emit q->memberListChanged(); return Change::SummaryChange; } -void Room::Private::insertMemberIntoMap(User *u) +void Room::Private::insertMemberIntoMap(User* u) { const auto userName = u->name(q); - // If there is exactly one namesake of the added user, signal member renaming - // for that other one because the two should be disambiguated now. + // If there is exactly one namesake of the added user, signal member + // renaming for that other one because the two should be disambiguated now. auto namesakes = membersMap.values(userName); if (namesakes.size() == 1) emit q->memberAboutToRename(namesakes.front(), @@ -1185,14 +1081,11 @@ void Room::Private::insertMemberIntoMap(User *u) void Room::Private::renameMember(User* u, QString oldName) { - if (u->name(q) == oldName) - { + if (u->name(q) == oldName) { qCWarning(MAIN) << "Room::Private::renameMember(): the user " << u->fullName(q) << "is already known in the room under a new name."; - } - else if (membersMap.contains(oldName, u)) - { + } else if (membersMap.contains(oldName, u)) { removeMemberFromMap(oldName, u); insertMemberIntoMap(u); } @@ -1203,15 +1096,15 @@ void Room::Private::removeMemberFromMap(const QString& username, User* u) { User* namesake = nullptr; auto namesakes = membersMap.values(username); - if (namesakes.size() == 2) - { - namesake = namesakes.front() == u ? namesakes.back() : namesakes.front(); + if (namesakes.size() == 2) { + namesake = + namesakes.front() == u ? namesakes.back() : namesakes.front(); Q_ASSERT_X(namesake != u, __FUNCTION__, "Room members list is broken"); emit q->memberAboutToRename(namesake, username); } membersMap.remove(username, u); - // If there was one namesake besides the removed user, signal member renaming - // for it because it doesn't need to be disambiguated anymore. + // If there was one namesake besides the removed user, signal member + // renaming for it because it doesn't need to be disambiguated anymore. // TODO: Think about left users. if (namesake) emit q->memberRenamed(namesake); @@ -1222,27 +1115,31 @@ inline auto makeErrorStr(const Event& e, QByteArray msg) return msg.append("; event dump follows:\n").append(e.originalJson()); } -Room::Timeline::difference_type Room::Private::moveEventsToTimeline( - RoomEventsRange events, EventsPlacement placement) +Room::Timeline::difference_type +Room::Private::moveEventsToTimeline(RoomEventsRange events, + EventsPlacement placement) { Q_ASSERT(!events.empty()); // Historical messages arrive in newest-to-oldest order, so the process for // them is almost symmetric to the one for new messages. New messages get // appended from index 0; old messages go backwards from index -1. - auto index = timeline.empty() ? -((placement+1)/2) /* 1 -> -1; -1 -> 0 */ : - placement == Older ? timeline.front().index() : - timeline.back().index(); + auto index = timeline.empty() + ? -((placement + 1) / 2) /* 1 -> -1; -1 -> 0 */ + : placement == Older ? timeline.front().index() + : timeline.back().index(); auto baseIndex = index; - for (auto&& e: events) - { + for (auto&& e : events) { const auto eId = e->id(); Q_ASSERT_X(e, __FUNCTION__, "Attempt to add nullptr to timeline"); - Q_ASSERT_X(!eId.isEmpty(), __FUNCTION__, - makeErrorStr(*e, - "Event with empty id cannot be in the timeline")); - Q_ASSERT_X(!eventsIndex.contains(eId), __FUNCTION__, - makeErrorStr(*e, "Event is already in the timeline; " - "incoming events were not properly deduplicated")); + Q_ASSERT_X( + !eId.isEmpty(), __FUNCTION__, + makeErrorStr(*e, + "Event with empty id cannot be in the timeline")); + Q_ASSERT_X( + !eventsIndex.contains(eId), __FUNCTION__, + makeErrorStr(*e, + "Event is already in the timeline; " + "incoming events were not properly deduplicated")); if (placement == Older) timeline.emplace_front(move(e), --index); else @@ -1279,8 +1176,7 @@ QString Room::roomMembername(const User* u) const // (extension to the spec) QVector bridges; for (; namesakesIt != d->membersMap.cend() && namesakesIt.key() == username; - ++namesakesIt) - { + ++namesakesIt) { const auto bridgeName = (*namesakesIt)->bridged(); if (bridges.contains(bridgeName)) // Two accounts on the same bridge return u->fullName(this); // Disambiguate fully @@ -1298,60 +1194,56 @@ QString Room::roomMembername(const QString& userId) const void Room::updateData(SyncRoomData&& data, bool fromCache) { - if( d->prevBatch.isEmpty() ) + if (d->prevBatch.isEmpty()) d->prevBatch = data.timelinePrevBatch; setJoinState(data.joinState); Changes roomChanges = Change::NoChange; - QElapsedTimer et; et.start(); - for (auto&& event: data.accountData) + QElapsedTimer et; + et.start(); + for (auto&& event : data.accountData) roomChanges |= processAccountDataEvent(move(event)); roomChanges |= d->updateStateFrom(data.state); - if (!data.timeline.empty()) - { + if (!data.timeline.empty()) { et.restart(); roomChanges |= d->addNewMessageEvents(move(data.timeline)); if (data.timeline.size() > 9 || et.nsecsElapsed() >= profilerMinNsecs()) qCDebug(PROFILER) << "*** Room::addNewMessageEvents():" << data.timeline.size() << "event(s)," << et; } - if (roomChanges&TopicChange) + if (roomChanges & TopicChange) emit topicChanged(); - if (roomChanges&NameChange) + if (roomChanges & NameChange) emit namesChanged(this); - if (roomChanges&MembersChange) + if (roomChanges & MembersChange) emit memberListChanged(); roomChanges |= d->setSummary(move(data.summary)); d->updateDisplayname(); - for( auto&& ephemeralEvent: data.ephemeral ) + for (auto&& ephemeralEvent : data.ephemeral) roomChanges |= processEphemeralEvent(move(ephemeralEvent)); // See https://github.com/QMatrixClient/libqmatrixclient/wiki/unread_count - if (data.unreadCount != -2 && data.unreadCount != d->unreadMessages) - { + if (data.unreadCount != -2 && data.unreadCount != d->unreadMessages) { qCDebug(MAIN) << "Setting unread_count to" << data.unreadCount; d->unreadMessages = data.unreadCount; emit unreadMessagesChanged(this); } - if( data.highlightCount != d->highlightCount ) - { + if (data.highlightCount != d->highlightCount) { d->highlightCount = data.highlightCount; emit highlightCountChanged(this); } - if( data.notificationCount != d->notificationCount ) - { + if (data.notificationCount != d->notificationCount) { d->notificationCount = data.notificationCount; emit notificationCountChanged(this); } - if (roomChanges != Change::NoChange) - { + if (roomChanges != Change::NoChange) { emit changed(roomChanges); if (!fromCache) connection()->saveRoomState(this); @@ -1382,37 +1274,34 @@ QString Room::Private::doSendEvent(const RoomEvent* pEvent) { const auto txnId = pEvent->transactionId(); // TODO, #133: Enqueue the job rather than immediately trigger it. - if (auto call = connection->callApi(BackgroundRequest, - id, pEvent->matrixType(), txnId, pEvent->contentJson())) - { - Room::connect(call, &BaseJob::started, q, - [this,txnId] { - auto it = q->findPendingEvent(txnId); - if (it == unsyncedEvents.end()) - { - qWarning(EVENTS) << "Pending event for transaction" << txnId - << "not found - got synced so soon?"; - return; - } - it->setDeparted(); - emit q->pendingEventChanged(it - unsyncedEvents.begin()); - }); + if (auto call = connection->callApi( + BackgroundRequest, id, pEvent->matrixType(), txnId, + pEvent->contentJson())) { + Room::connect(call, &BaseJob::started, q, [this, txnId] { + auto it = q->findPendingEvent(txnId); + if (it == unsyncedEvents.end()) { + qWarning(EVENTS) << "Pending event for transaction" << txnId + << "not found - got synced so soon?"; + return; + } + it->setDeparted(); + emit q->pendingEventChanged(it - unsyncedEvents.begin()); + }); Room::connect(call, &BaseJob::failure, q, - std::bind(&Room::Private::onEventSendingFailure, this, txnId, call)); - Room::connect(call, &BaseJob::success, q, - [this,call,txnId] { - emit q->messageSent(txnId, call->eventId()); - auto it = q->findPendingEvent(txnId); - if (it == unsyncedEvents.end()) - { - qDebug(EVENTS) << "Pending event for transaction" << txnId - << "already merged"; - return; - } + std::bind(&Room::Private::onEventSendingFailure, this, + txnId, call)); + Room::connect(call, &BaseJob::success, q, [this, call, txnId] { + emit q->messageSent(txnId, call->eventId()); + auto it = q->findPendingEvent(txnId); + if (it == unsyncedEvents.end()) { + qDebug(EVENTS) << "Pending event for transaction" << txnId + << "already merged"; + return; + } - it->setReachedServer(call->eventId()); - emit q->pendingEventChanged(it - unsyncedEvents.begin()); - }); + it->setReachedServer(call->eventId()); + emit q->pendingEventChanged(it - unsyncedEvents.begin()); + }); } else onEventSendingFailure(txnId); return txnId; @@ -1421,15 +1310,14 @@ QString Room::Private::doSendEvent(const RoomEvent* pEvent) void Room::Private::onEventSendingFailure(const QString& txnId, BaseJob* call) { auto it = q->findPendingEvent(txnId); - if (it == unsyncedEvents.end()) - { + if (it == unsyncedEvents.end()) { qCritical(EVENTS) << "Pending event for transaction" << txnId << "could not be sent"; return; } - it->setSendingFailed(call - ? call->statusCaption() % ": " % call->errorString() - : tr("The call could not be started")); + it->setSendingFailed(call ? call->statusCaption() % ": " + % call->errorString() + : tr("The call could not be started")); emit q->pendingEventChanged(it - unsyncedEvents.begin()); } @@ -1439,30 +1327,29 @@ QString Room::retryMessage(const QString& txnId) Q_ASSERT(it != d->unsyncedEvents.end()); qDebug(EVENTS) << "Retrying transaction" << txnId; const auto& transferIt = d->fileTransfers.find(txnId); - if (transferIt != d->fileTransfers.end()) - { + if (transferIt != d->fileTransfers.end()) { Q_ASSERT(transferIt->isUpload); - if (transferIt->status == FileTransferInfo::Completed) - { + if (transferIt->status == FileTransferInfo::Completed) { qCDebug(MAIN) << "File for transaction" << txnId << "has already been uploaded, bypassing re-upload"; } else { - if (isJobRunning(transferIt->job)) - { + if (isJobRunning(transferIt->job)) { qCDebug(MAIN) << "Abandoning the upload job for transaction" << txnId << "and starting again"; transferIt->job->abandon(); - emit fileTransferFailed(txnId, tr("File upload will be retried")); + emit fileTransferFailed(txnId, + tr("File upload will be retried")); } uploadFile(txnId, - QUrl::fromLocalFile(transferIt->localFileInfo.absoluteFilePath())); + QUrl::fromLocalFile( + transferIt->localFileInfo.absoluteFilePath())); // FIXME: Content type is no more passed here but it should } } - if (it->deliveryStatus() == EventStatus::ReachedServer) - { - qCWarning(MAIN) << "The previous attempt has reached the server; two" - " events are likely to be in the timeline after retry"; + if (it->deliveryStatus() == EventStatus::ReachedServer) { + qCWarning(MAIN) + << "The previous attempt has reached the server; two" + " events are likely to be in the timeline after retry"; } it->resetStatus(); return d->doSendEvent(it->event()); @@ -1470,23 +1357,22 @@ QString Room::retryMessage(const QString& txnId) void Room::discardMessage(const QString& txnId) { - auto it = std::find_if(d->unsyncedEvents.begin(), d->unsyncedEvents.end(), - [txnId] (const auto& evt) { return evt->transactionId() == txnId; }); + auto it = std::find_if( + d->unsyncedEvents.begin(), d->unsyncedEvents.end(), + [txnId](const auto& evt) { return evt->transactionId() == txnId; }); Q_ASSERT(it != d->unsyncedEvents.end()); qDebug(EVENTS) << "Discarding transaction" << txnId; const auto& transferIt = d->fileTransfers.find(txnId); - if (transferIt != d->fileTransfers.end()) - { + if (transferIt != d->fileTransfers.end()) { Q_ASSERT(transferIt->isUpload); - if (isJobRunning(transferIt->job)) - { + if (isJobRunning(transferIt->job)) { transferIt->status = FileTransferInfo::Cancelled; transferIt->job->abandon(); emit fileTransferFailed(txnId, tr("File upload cancelled")); - } else if (transferIt->status == FileTransferInfo::Completed) - { - qCWarning(MAIN) << "File for transaction" << txnId - << "has been uploaded but the message was discarded"; + } else if (transferIt->status == FileTransferInfo::Completed) { + qCWarning(MAIN) + << "File for transaction" << txnId + << "has been uploaded but the message was discarded"; } } emit pendingEventAboutToDiscard(int(it - d->unsyncedEvents.begin())); @@ -1507,8 +1393,9 @@ QString Room::postPlainText(const QString& plainText) QString Room::postHtmlMessage(const QString& plainText, const QString& html, MessageEventType type) { - return d->sendEvent(plainText, type, - new EventContent::TextContent(html, QStringLiteral("text/html"))); + return d->sendEvent( + plainText, type, + new EventContent::TextContent(html, QStringLiteral("text/html"))); } QString Room::postHtmlText(const QString& plainText, const QString& html) @@ -1523,58 +1410,58 @@ QString Room::postFile(const QString& plainText, const QUrl& localPath, Q_ASSERT(localFile.isFile()); // Remote URL will only be known after upload; fill in the local path // to enable the preview while the event is pending. - const auto txnId = d->addAsPending(makeEvent( - plainText, localFile, asGenericFile) - )->transactionId(); + const auto txnId = + d->addAsPending(makeEvent(plainText, localFile, + asGenericFile)) + ->transactionId(); uploadFile(txnId, localPath); auto* context = new QObject(this); connect(this, &Room::fileTransferCompleted, context, - [context,this,txnId] (const QString& id, QUrl, const QUrl& mxcUri) { - if (id == txnId) - { - auto it = findPendingEvent(txnId); - if (it != d->unsyncedEvents.end()) - { - it->setFileUploaded(mxcUri); - emit pendingEventChanged( + [context, this, txnId](const QString& id, QUrl, + const QUrl& mxcUri) { + if (id == txnId) { + auto it = findPendingEvent(txnId); + if (it != d->unsyncedEvents.end()) { + it->setFileUploaded(mxcUri); + emit pendingEventChanged( int(it - d->unsyncedEvents.begin())); - d->doSendEvent(it->get()); - } else { - // Normally in this situation we should instruct - // the media server to delete the file; alas, there's no - // API specced for that. - qCWarning(MAIN) << "File uploaded to" << mxcUri - << "but the event referring to it was cancelled"; + d->doSendEvent(it->get()); + } else { + // Normally in this situation we should instruct + // the media server to delete the file; alas, there's no + // API specced for that. + qCWarning(MAIN) << "File uploaded to" << mxcUri + << "but the event referring to it was " + "cancelled"; + } + context->deleteLater(); } - context->deleteLater(); - } - }); + }); connect(this, &Room::fileTransferCancelled, this, - [context,this,txnId] (const QString& id) { - if (id == txnId) - { - auto it = findPendingEvent(txnId); - if (it != d->unsyncedEvents.end()) - { - const auto idx = int(it - d->unsyncedEvents.begin()); - emit pendingEventAboutToDiscard(idx); - // See #286 on why iterator may not be valid here. - d->unsyncedEvents.erase(d->unsyncedEvents.begin() + idx); - emit pendingEventDiscarded(); + [context, this, txnId](const QString& id) { + if (id == txnId) { + auto it = findPendingEvent(txnId); + if (it != d->unsyncedEvents.end()) { + const auto idx = int(it - d->unsyncedEvents.begin()); + emit pendingEventAboutToDiscard(idx); + // See #286 on why iterator may not be valid here. + d->unsyncedEvents.erase(d->unsyncedEvents.begin() + + idx); + emit pendingEventDiscarded(); + } + context->deleteLater(); } - context->deleteLater(); - } - }); + }); return txnId; } QString Room::postEvent(RoomEvent* event) { - if (usesEncryption()) - { + if (usesEncryption()) { qCCritical(MAIN) << "Room" << displayName() - << "enforces encryption; sending encrypted messages is not supported yet"; + << "enforces encryption; sending encrypted messages " + "is not supported yet"; } return d->sendEvent(RoomEventPtr(event)); } @@ -1582,7 +1469,8 @@ QString Room::postEvent(RoomEvent* event) QString Room::postJson(const QString& matrixType, const QJsonObject& eventContent) { - return d->sendEvent(loadEvent(basicEventJson(matrixType, eventContent))); + return d->sendEvent( + loadEvent(basicEventJson(matrixType, eventContent))); } void Room::setName(const QString& newName) @@ -1625,10 +1513,7 @@ bool isEchoEvent(const RoomEventPtr& le, const PendingEventItem& re) return le->contentJson() == re->contentJson(); } -bool Room::supportsCalls() const -{ - return joinedCount() == 2; -} +bool Room::supportsCalls() const { return joinedCount() == 2; } void Room::checkVersion() { @@ -1638,8 +1523,7 @@ void Room::checkVersion() // This method is only called after the base state has been loaded // or the server capabilities have been loaded. emit stabilityUpdated(defaultVersion, stableVersions); - if (!stableVersions.contains(version())) - { + if (!stableVersions.contains(version())) { qCDebug(MAIN) << this << "version is" << version() << "which the server doesn't count as stable"; if (canSwitchVersions()) @@ -1680,25 +1564,22 @@ void Room::hangupCall(const QString& callId) postEvent(new CallHangupEvent(callId)); } -void Room::getPreviousContent(int limit) -{ - d->getPreviousContent(limit); -} +void Room::getPreviousContent(int limit) { d->getPreviousContent(limit); } void Room::Private::getPreviousContent(int limit) { if (isJobRunning(eventsHistoryJob)) return; - eventsHistoryJob = - connection->callApi(id, prevBatch, "b", "", limit); + eventsHistoryJob = connection->callApi(id, prevBatch, "b", + "", limit); emit q->eventsHistoryJobChanged(); - connect( eventsHistoryJob, &BaseJob::success, q, [=] { + connect(eventsHistoryJob, &BaseJob::success, q, [=] { prevBatch = eventsHistoryJob->end(); addHistoricalMessageEvents(eventsHistoryJob->chunk()); }); - connect( eventsHistoryJob, &QObject::destroyed, - q, &Room::eventsHistoryJobChanged); + connect(eventsHistoryJob, &QObject::destroyed, q, + &Room::eventsHistoryJobChanged); } void Room::inviteToRoom(const QString& memberId) @@ -1712,7 +1593,8 @@ LeaveRoomJob* Room::leaveRoom() return connection()->leaveRoom(this); } -SetRoomStateWithKeyJob*Room::setMemberState(const QString& memberId, const RoomMemberEvent& event) const +SetRoomStateWithKeyJob* Room::setMemberState(const QString& memberId, + const RoomMemberEvent& event) const { return d->requestSetState(memberId, event); } @@ -1735,7 +1617,7 @@ void Room::unban(const QString& userId) void Room::redactEvent(const QString& eventId, const QString& reason) { connection()->callApi( - id(), eventId, connection()->generateTxnId(), reason); + id(), eventId, connection()->generateTxnId(), reason); } void Room::uploadFile(const QString& id, const QUrl& localFilename, @@ -1745,18 +1627,17 @@ void Room::uploadFile(const QString& id, const QUrl& localFilename, "localFilename should point at a local file"); auto fileName = localFilename.toLocalFile(); auto job = connection()->uploadFile(fileName, overrideContentType); - if (isJobRunning(job)) - { + if (isJobRunning(job)) { d->fileTransfers.insert(id, { job, fileName, true }); connect(job, &BaseJob::uploadProgress, this, - [this,id] (qint64 sent, qint64 total) { + [this, id](qint64 sent, qint64 total) { d->fileTransfers[id].update(sent, total); emit fileTransferProgress(id, sent, total); }); - connect(job, &BaseJob::success, this, [this,id,localFilename,job] { - d->fileTransfers[id].status = FileTransferInfo::Completed; - emit fileTransferCompleted(id, localFilename, job->contentUri()); - }); + connect(job, &BaseJob::success, this, [this, id, localFilename, job] { + d->fileTransfers[id].status = FileTransferInfo::Completed; + emit fileTransferCompleted(id, localFilename, job->contentUri()); + }); connect(job, &BaseJob::failure, this, std::bind(&Private::failedTransfer, d, id, job->errorString())); emit newFileTransfer(id, localFilename); @@ -1767,9 +1648,8 @@ void Room::uploadFile(const QString& id, const QUrl& localFilename, void Room::downloadFile(const QString& eventId, const QUrl& localFilename) { auto ongoingTransfer = d->fileTransfers.find(eventId); - if (ongoingTransfer != d->fileTransfers.end() && - ongoingTransfer->status == FileTransferInfo::Started) - { + if (ongoingTransfer != d->fileTransfers.end() + && ongoingTransfer->status == FileTransferInfo::Started) { qCWarning(MAIN) << "Transfer for" << eventId << "is ongoing; download won't start"; return; @@ -1778,42 +1658,41 @@ void Room::downloadFile(const QString& eventId, const QUrl& localFilename) Q_ASSERT_X(localFilename.isEmpty() || localFilename.isLocalFile(), __FUNCTION__, "localFilename should point at a local file"); const auto* event = d->getEventWithFile(eventId); - if (!event) - { + if (!event) { qCCritical(MAIN) - << eventId << "is not in the local timeline or has no file content"; + << eventId + << "is not in the local timeline or has no file content"; Q_ASSERT(false); return; } const auto fileUrl = event->content()->fileInfo()->url; auto filePath = localFilename.toLocalFile(); - if (filePath.isEmpty()) - { + if (filePath.isEmpty()) { // Build our own file path, starting with temp directory and eventId. filePath = eventId; - filePath = QDir::tempPath() % '/' % - filePath.replace(QRegularExpression("[/\\<>|\"*?:]"), "_") % - '#' % d->fileNameToDownload(event); + filePath = QDir::tempPath() % '/' + % filePath.replace(QRegularExpression("[/\\<>|\"*?:]"), "_") + % '#' % d->fileNameToDownload(event); } auto job = connection()->downloadFile(fileUrl, filePath); - if (isJobRunning(job)) - { + if (isJobRunning(job)) { // If there was a previous transfer (completed or failed), remove it. d->fileTransfers.remove(eventId); d->fileTransfers.insert(eventId, { job, job->targetFileName() }); connect(job, &BaseJob::downloadProgress, this, - [this,eventId] (qint64 received, qint64 total) { - d->fileTransfers[eventId].update(received, total); - emit fileTransferProgress(eventId, received, total); - }); - connect(job, &BaseJob::success, this, [this,eventId,fileUrl,job] { - d->fileTransfers[eventId].status = FileTransferInfo::Completed; - emit fileTransferCompleted(eventId, fileUrl, - QUrl::fromLocalFile(job->targetFileName())); - }); + [this, eventId](qint64 received, qint64 total) { + d->fileTransfers[eventId].update(received, total); + emit fileTransferProgress(eventId, received, total); + }); + connect(job, &BaseJob::success, this, [this, eventId, fileUrl, job] { + d->fileTransfers[eventId].status = FileTransferInfo::Completed; + emit fileTransferCompleted( + eventId, fileUrl, + QUrl::fromLocalFile(job->targetFileName())); + }); connect(job, &BaseJob::failure, this, - std::bind(&Private::failedTransfer, d, - eventId, job->errorString())); + std::bind(&Private::failedTransfer, d, eventId, + job->errorString())); } else d->failedTransfer(eventId); } @@ -1821,10 +1700,9 @@ void Room::downloadFile(const QString& eventId, const QUrl& localFilename) void Room::cancelFileTransfer(const QString& id) { auto it = d->fileTransfers.find(id); - if (it == d->fileTransfers.end()) - { - qCWarning(MAIN) << "No information on file transfer" << id - << "in room" << d->id; + if (it == d->fileTransfers.end()) { + qCWarning(MAIN) << "No information on file transfer" << id << "in room" + << d->id; return; } if (isJobRunning(it->job)) @@ -1840,15 +1718,16 @@ void Room::Private::dropDuplicateEvents(RoomEvents& events) const // Multiple-remove (by different criteria), single-erase // 1. Check for duplicates against the timeline. - auto dupsBegin = remove_if(events.begin(), events.end(), - [&] (const RoomEventPtr& e) - { return eventsIndex.contains(e->id()); }); + auto dupsBegin = + remove_if(events.begin(), events.end(), [&](const RoomEventPtr& e) { + return eventsIndex.contains(e->id()); + }); // 2. Check for duplicates within the batch if there are still events. for (auto eIt = events.begin(); distance(eIt, dupsBegin) > 1; ++eIt) - dupsBegin = remove_if(eIt + 1, dupsBegin, - [&] (const RoomEventPtr& e) - { return e->id() == (*eIt)->id(); }); + dupsBegin = remove_if(eIt + 1, dupsBegin, [&](const RoomEventPtr& e) { + return e->id() == (*eIt)->id(); + }); if (dupsBegin == events.end()) return; @@ -1867,48 +1746,54 @@ RoomEventPtr makeRedacted(const RoomEvent& target, const RedactionEvent& redaction) { auto originalJson = target.originalJsonObject(); - static const QStringList keepKeys { - EventIdKey, TypeKey, QStringLiteral("room_id"), - QStringLiteral("sender"), QStringLiteral("state_key"), - QStringLiteral("prev_content"), ContentKey, - QStringLiteral("hashes"), QStringLiteral("signatures"), - QStringLiteral("depth"), QStringLiteral("prev_events"), - QStringLiteral("prev_state"), QStringLiteral("auth_events"), - QStringLiteral("origin"), QStringLiteral("origin_server_ts"), - QStringLiteral("membership") + static const QStringList keepKeys { EventIdKey, + TypeKey, + QStringLiteral("room_id"), + QStringLiteral("sender"), + QStringLiteral("state_key"), + QStringLiteral("prev_content"), + ContentKey, + QStringLiteral("hashes"), + QStringLiteral("signatures"), + QStringLiteral("depth"), + QStringLiteral("prev_events"), + QStringLiteral("prev_state"), + QStringLiteral("auth_events"), + QStringLiteral("origin"), + QStringLiteral("origin_server_ts"), + QStringLiteral("membership") }; + + std::vector> keepContentKeysMap { + { RoomMemberEvent::typeId(), { QStringLiteral("membership") } }, + { RoomCreateEvent::typeId(), { QStringLiteral("creator") } } + // , { RoomJoinRules::typeId(), { QStringLiteral("join_rule") } } + // , { RoomPowerLevels::typeId(), + // { QStringLiteral("ban"), QStringLiteral("events"), + // QStringLiteral("events_default"), + // QStringLiteral("kick"), QStringLiteral("redact"), + // QStringLiteral("state_default"), + // QStringLiteral("users"), QStringLiteral("users_default") + // } } + , + { RoomAliasesEvent::typeId(), { QStringLiteral("aliases") } } + // , { RoomHistoryVisibility::typeId(), + // { QStringLiteral("history_visibility") } } }; - - std::vector> keepContentKeysMap - { { RoomMemberEvent::typeId(), { QStringLiteral("membership") } } - , { RoomCreateEvent::typeId(), { QStringLiteral("creator") } } -// , { RoomJoinRules::typeId(), { QStringLiteral("join_rule") } } -// , { RoomPowerLevels::typeId(), -// { QStringLiteral("ban"), QStringLiteral("events"), -// QStringLiteral("events_default"), QStringLiteral("kick"), -// QStringLiteral("redact"), QStringLiteral("state_default"), -// QStringLiteral("users"), QStringLiteral("users_default") } } - , { RoomAliasesEvent::typeId(), { QStringLiteral("aliases") } } -// , { RoomHistoryVisibility::typeId(), -// { QStringLiteral("history_visibility") } } - }; - for (auto it = originalJson.begin(); it != originalJson.end();) - { + for (auto it = originalJson.begin(); it != originalJson.end();) { if (!keepKeys.contains(it.key())) it = originalJson.erase(it); // TODO: shred the value else ++it; } - auto keepContentKeys = - find_if(keepContentKeysMap.begin(), keepContentKeysMap.end(), - [&target](const auto& t) { return target.type() == t.first; } ); - if (keepContentKeys == keepContentKeysMap.end()) - { + auto keepContentKeys = find_if( + keepContentKeysMap.begin(), keepContentKeysMap.end(), + [&target](const auto& t) { return target.type() == t.first; }); + if (keepContentKeys == keepContentKeysMap.end()) { originalJson.remove(ContentKeyL); originalJson.remove(PrevContentKeyL); } else { auto content = originalJson.take(ContentKeyL).toObject(); - for (auto it = content.begin(); it != content.end(); ) - { + for (auto it = content.begin(); it != content.end();) { if (!keepContentKeys->second.contains(it.key())) it = content.erase(it); else @@ -1934,10 +1819,9 @@ bool Room::Private::processRedaction(const RedactionEvent& redaction) Q_ASSERT(q->isValidIndex(*pIdx)); auto& ti = timeline[Timeline::size_type(*pIdx - q->minTimelineIndex())]; - if (ti->isRedacted() && ti->redactedBecause()->id() == redaction.id()) - { - qCDebug(MAIN) << "Redaction" << redaction.id() - << "of event" << ti->id() << "already done, skipping"; + if (ti->isRedacted() && ti->redactedBecause()->id() == redaction.id()) { + qCDebug(MAIN) << "Redaction" << redaction.id() << "of event" << ti->id() + << "already done, skipping"; return true; } @@ -1945,15 +1829,16 @@ bool Room::Private::processRedaction(const RedactionEvent& redaction) // instead of the redacted one. oldEvent will be deleted on return. auto oldEvent = ti.replaceEvent(makeRedacted(*ti, redaction)); qCDebug(MAIN) << "Redacted" << oldEvent->id() << "with" << redaction.id(); - if (oldEvent->isStateEvent()) - { - const StateEventKey evtKey { oldEvent->matrixType(), oldEvent->stateKey() }; + if (oldEvent->isStateEvent()) { + const StateEventKey evtKey { oldEvent->matrixType(), + oldEvent->stateKey() }; Q_ASSERT(currentState.contains(evtKey)); - if (currentState[evtKey] == oldEvent.get()) - { - Q_ASSERT(ti.index() >= 0); // Historical states can't be in currentState - qCDebug(MAIN).nospace() << "Reverting state " - << oldEvent->matrixType() << "/" << oldEvent->stateKey(); + if (currentState[evtKey] == oldEvent.get()) { + Q_ASSERT(ti.index() + >= 0); // Historical states can't be in currentState + qCDebug(MAIN).nospace() + << "Reverting state " << oldEvent->matrixType() << "/" + << oldEvent->stateKey(); // Retarget the current state to the newly made event. if (q->processStateEvent(*ti)) emit q->namesChanged(q); @@ -1971,10 +1856,7 @@ Connection* Room::connection() const return d->connection; } -User* Room::localUser() const -{ - return connection()->user(); -} +User* Room::localUser() const { return connection()->user(); } inline bool isRedaction(const RoomEventPtr& ep) { @@ -1992,22 +1874,22 @@ Room::Changes Room::Private::addNewMessageEvents(RoomEvents&& events) // batch landed in the timeline already redacted. // NB: We have to store redaction events to the timeline too - see #220. auto redactionIt = std::find_if(events.begin(), events.end(), isRedaction); - for(const auto& eptr: RoomEventsRange(redactionIt, events.end())) - if (auto* r = eventCast(eptr)) - { + for (const auto& eptr : RoomEventsRange(redactionIt, events.end())) + if (auto* r = eventCast(eptr)) { // Try to find the target in the timeline, then in the batch. if (processRedaction(*r)) continue; - auto targetIt = std::find_if(events.begin(), redactionIt, - [id=r->redactedEvent()] (const RoomEventPtr& ep) { - return ep->id() == id; - }); + auto targetIt = std::find_if( + events.begin(), redactionIt, + [id = r->redactedEvent()](const RoomEventPtr& ep) { + return ep->id() == id; + }); if (targetIt != redactionIt) *targetIt = makeRedacted(**targetIt, *r); else - qCDebug(MAIN) << "Redaction" << r->id() - << "ignored: target event" << r->redactedEvent() - << "is not found"; + qCDebug(MAIN) + << "Redaction" << r->id() << "ignored: target event" + << r->redactedEvent() << "is not found"; // If the target event comes later, it comes already redacted. } @@ -2017,26 +1899,26 @@ Room::Changes Room::Private::addNewMessageEvents(RoomEvents&& events) // postulate that the current state is only current between syncs but not // within a sync. Changes roomChanges = Change::NoChange; - for (const auto& eptr: events) + for (const auto& eptr : events) roomChanges |= q->processStateEvent(*eptr); auto timelineSize = timeline.size(); auto totalInserted = 0; - for (auto it = events.begin(); it != events.end();) - { - auto nextPendingPair = findFirstOf(it, events.end(), - unsyncedEvents.begin(), unsyncedEvents.end(), isEchoEvent); + for (auto it = events.begin(); it != events.end();) { + auto nextPendingPair = + findFirstOf(it, events.end(), unsyncedEvents.begin(), + unsyncedEvents.end(), isEchoEvent); auto nextPending = nextPendingPair.first; - if (it != nextPending) - { + if (it != nextPending) { RoomEventsRange eventsSpan { it, nextPending }; emit q->aboutToAddNewMessages(eventsSpan); auto insertedSize = moveEventsToTimeline(eventsSpan, Newer); totalInserted += insertedSize; auto firstInserted = timeline.cend() - insertedSize; q->onAddNewTimelineEvents(firstInserted); - emit q->addedMessages(firstInserted->index(), timeline.back().index()); + emit q->addedMessages(firstInserted->index(), + timeline.back().index()); } if (nextPending == events.end()) break; @@ -2058,8 +1940,8 @@ Room::Changes Room::Private::addNewMessageEvents(RoomEvents&& events) // unsyncedEvents (see #286). Fortunately, unsyncedEvents only grows at // its back so we can rely on the index staying valid at least. unsyncedEvents.erase(unsyncedEvents.begin() + pendingEvtIdx); - if (auto insertedSize = moveEventsToTimeline({nextPending, it}, Newer)) - { + if (auto insertedSize = + moveEventsToTimeline({ nextPending, it }, Newer)) { totalInserted += insertedSize; q->onAddNewTimelineEvents(timeline.cend() - insertedSize); } @@ -2073,11 +1955,10 @@ Room::Changes Room::Private::addNewMessageEvents(RoomEvents&& events) if (auto* evt = it->viewAs()) emit q->callEvent(q, evt); - if (totalInserted > 0) - { - qCDebug(MAIN) - << "Room" << q->objectName() << "received" << totalInserted - << "new events; the last event is now" << timeline.back(); + if (totalInserted > 0) { + qCDebug(MAIN) << "Room" << q->objectName() << "received" + << totalInserted << "new events; the last event is now" + << timeline.back(); // The first event in the just-added batch (referred to by `from`) // defines whose read marker can possibly be promoted any further over @@ -2086,11 +1967,11 @@ Room::Changes Room::Private::addNewMessageEvents(RoomEvents&& events) // markMessagesAsRead() invocation) to promote their read markers over // the new message events. auto firstWriter = q->user((*from)->senderId()); - if (q->readMarker(firstWriter) != timeline.crend()) - { + if (q->readMarker(firstWriter) != timeline.crend()) { roomChanges |= promoteReadMarker(firstWriter, rev_iter_t(from) - 1); - qCDebug(MAIN) << "Auto-promoted read marker for" << firstWriter->id() - << "to" << *q->readMarker(firstWriter); + qCDebug(MAIN) << "Auto-promoted read marker for" + << firstWriter->id() << "to" + << *q->readMarker(firstWriter); } updateUnreadCount(timeline.crbegin(), rev_iter_t(from)); @@ -2103,7 +1984,8 @@ Room::Changes Room::Private::addNewMessageEvents(RoomEvents&& events) void Room::Private::addHistoricalMessageEvents(RoomEvents&& events) { - QElapsedTimer et; et.start(); + QElapsedTimer et; + et.start(); const auto timelineSize = timeline.size(); dropDuplicateEvents(events); @@ -2114,12 +1996,10 @@ void Room::Private::addHistoricalMessageEvents(RoomEvents&& events) // messages. Also, the cache doesn't store events with empty content; // so when such events show up in the timeline they should be properly // incorporated. - for (const auto& eptr: events) - { + for (const auto& eptr : events) { const auto& e = *eptr; - if (e.isStateEvent() && - !currentState.contains({e.matrixType(), e.stateKey()})) - { + if (e.isStateEvent() + && !currentState.contains({ e.matrixType(), e.stateKey() })) { q->processStateEvent(e); } } @@ -2147,167 +2027,157 @@ Room::Changes Room::processStateEvent(const RoomEvent& e) if (!e.isStateEvent()) return Change::NoChange; - const auto* oldStateEvent = std::exchange( - d->currentState[{e.matrixType(),e.stateKey()}], - static_cast(&e)); - Q_ASSERT(!oldStateEvent || - (oldStateEvent->matrixType() == e.matrixType() && - oldStateEvent->stateKey() == e.stateKey())); + const auto* oldStateEvent = + std::exchange(d->currentState[{ e.matrixType(), e.stateKey() }], + static_cast(&e)); + Q_ASSERT(!oldStateEvent + || (oldStateEvent->matrixType() == e.matrixType() + && oldStateEvent->stateKey() == e.stateKey())); if (!is(e)) qCDebug(EVENTS) << "Room state event:" << e; - return visit(e - , [] (const RoomNameEvent&) { - return NameChange; - } - , [this,oldStateEvent] (const RoomAliasesEvent& ae) { - const auto previousAliases = oldStateEvent - ? static_cast(oldStateEvent)->aliases() - : QStringList(); - connection()->updateRoomAliases(id(), previousAliases, ae.aliases()); - return OtherChange; - } - , [this] (const RoomCanonicalAliasEvent& evt) { - setObjectName(evt.alias().isEmpty() ? d->id : evt.alias()); - return CanonicalAliasChange; - } - , [] (const RoomTopicEvent&) { - return TopicChange; - } - , [this] (const RoomAvatarEvent& evt) { - if (d->avatar.updateUrl(evt.url())) - emit avatarChanged(); - return AvatarChange; - } - , [this] (const RoomMemberEvent& evt) { - auto* u = user(evt.userId()); - u->processEvent(evt, this); - if (u == localUser() && memberJoinState(u) == JoinState::Invite + return visit( + e, [](const RoomNameEvent&) { return NameChange; }, + [this, oldStateEvent](const RoomAliasesEvent& ae) { + const auto previousAliases = oldStateEvent + ? static_cast(oldStateEvent) + ->aliases() + : QStringList(); + connection()->updateRoomAliases(id(), previousAliases, + ae.aliases()); + return OtherChange; + }, + [this](const RoomCanonicalAliasEvent& evt) { + setObjectName(evt.alias().isEmpty() ? d->id : evt.alias()); + return CanonicalAliasChange; + }, + [](const RoomTopicEvent&) { return TopicChange; }, + [this](const RoomAvatarEvent& evt) { + if (d->avatar.updateUrl(evt.url())) + emit avatarChanged(); + return AvatarChange; + }, + [this](const RoomMemberEvent& evt) { + auto* u = user(evt.userId()); + u->processEvent(evt, this); + if (u == localUser() && memberJoinState(u) == JoinState::Invite && evt.isDirect()) - connection()->addToDirectChats(this, user(evt.senderId())); - - if( evt.membership() == MembershipType::Join ) - { - if (memberJoinState(u) != JoinState::Join) - { - d->insertMemberIntoMap(u); - connect(u, &User::nameAboutToChange, this, - [=] (QString newName, QString, const Room* context) { - if (context == this) - emit memberAboutToRename(u, newName); - }); - connect(u, &User::nameChanged, this, - [=] (QString, QString oldName, const Room* context) { - if (context == this) - d->renameMember(u, oldName); - }); - emit userAdded(u); - } - } - else if( evt.membership() != MembershipType::Join ) - { - if (memberJoinState(u) == JoinState::Join) - { - if (evt.membership() == MembershipType::Invite) - qCWarning(MAIN) << "Invalid membership change:" << evt; - if (!d->membersLeft.contains(u)) - d->membersLeft.append(u); - d->removeMemberFromMap(u->name(this), u); - emit userRemoved(u); + connection()->addToDirectChats(this, user(evt.senderId())); + + if (evt.membership() == MembershipType::Join) { + if (memberJoinState(u) != JoinState::Join) { + d->insertMemberIntoMap(u); + connect(u, &User::nameAboutToChange, this, + [=](QString newName, QString, + const Room* context) { + if (context == this) + emit memberAboutToRename(u, newName); + }); + connect(u, &User::nameChanged, this, + [=](QString, QString oldName, + const Room* context) { + if (context == this) + d->renameMember(u, oldName); + }); + emit userAdded(u); + } + } else if (evt.membership() != MembershipType::Join) { + if (memberJoinState(u) == JoinState::Join) { + if (evt.membership() == MembershipType::Invite) + qCWarning(MAIN) + << "Invalid membership change:" << evt; + if (!d->membersLeft.contains(u)) + d->membersLeft.append(u); + d->removeMemberFromMap(u->name(this), u); + emit userRemoved(u); + } } - } - return MembersChange; - } - , [this] (const EncryptionEvent&) { - emit encryption(); // It can only be done once, so emit it here. - return OtherChange; - } - , [this] (const RoomTombstoneEvent& evt) { - const auto successorId = evt.successorRoomId(); - if (auto* successor = connection()->room(successorId)) - emit upgraded(evt.serverMessage(), successor); - else - connectUntil(connection(), &Connection::loadedRoomState, this, - [this,successorId,serverMsg=evt.serverMessage()] - (Room* newRoom) { - if (newRoom->id() != successorId) - return false; - emit upgraded(serverMsg, newRoom); - return true; - }); - - return OtherChange; - } - ); + return MembersChange; + }, + [this](const EncryptionEvent&) { + emit encryption(); // It can only be done once, so emit it here. + return OtherChange; + }, + [this](const RoomTombstoneEvent& evt) { + const auto successorId = evt.successorRoomId(); + if (auto* successor = connection()->room(successorId)) + emit upgraded(evt.serverMessage(), successor); + else + connectUntil( + connection(), &Connection::loadedRoomState, this, + [this, successorId, + serverMsg = evt.serverMessage()](Room* newRoom) { + if (newRoom->id() != successorId) + return false; + emit upgraded(serverMsg, newRoom); + return true; + }); + + return OtherChange; + }); } Room::Changes Room::processEphemeralEvent(EventPtr&& event) { Changes changes = NoChange; - QElapsedTimer et; et.start(); - if (auto* evt = eventCast(event)) - { + QElapsedTimer et; + et.start(); + if (auto* evt = eventCast(event)) { d->usersTyping.clear(); - for( const QString& userId: qAsConst(evt->users()) ) - { + for (const QString& userId : qAsConst(evt->users())) { auto u = user(userId); if (memberJoinState(u) == JoinState::Join) d->usersTyping.append(u); } if (evt->users().size() > 3 || et.nsecsElapsed() >= profilerMinNsecs()) qCDebug(PROFILER) << "*** Room::processEphemeralEvent(typing):" - << evt->users().size() << "users," << et; + << evt->users().size() << "users," << et; emit typingChanged(); } - if (auto* evt = eventCast(event)) - { + if (auto* evt = eventCast(event)) { int totalReceipts = 0; - for( const auto &p: qAsConst(evt->eventsWithReceipts()) ) - { + for (const auto& p : qAsConst(evt->eventsWithReceipts())) { totalReceipts += p.receipts.size(); { if (p.receipts.size() == 1) - qCDebug(EPHEMERAL) << "Marking" << p.evtId - << "as read for" << p.receipts[0].userId; + qCDebug(EPHEMERAL) << "Marking" << p.evtId << "as read for" + << p.receipts[0].userId; else - qCDebug(EPHEMERAL) << "Marking" << p.evtId - << "as read for" << p.receipts.size() << "users"; + qCDebug(EPHEMERAL) << "Marking" << p.evtId << "as read for" + << p.receipts.size() << "users"; } const auto newMarker = findInTimeline(p.evtId); - if (newMarker != timelineEdge()) - { - for( const Receipt& r: p.receipts ) - { + if (newMarker != timelineEdge()) { + for (const Receipt& r : p.receipts) { if (r.userId == connection()->userId()) continue; // FIXME, #185 auto u = user(r.userId); if (memberJoinState(u) == JoinState::Join) changes |= d->promoteReadMarker(u, newMarker); } - } else - { + } else { qCDebug(EPHEMERAL) << "Event" << p.evtId - << "not found; saving read receipts anyway"; + << "not found; saving read receipts anyway"; // If the event is not found (most likely, because it's too old // and hasn't been fetched from the server yet), but there is // a previous marker for a user, keep the previous marker. // Otherwise, blindly store the event id for this user. - for( const Receipt& r: p.receipts ) - { + for (const Receipt& r : p.receipts) { if (r.userId == connection()->userId()) continue; // FIXME, #185 auto u = user(r.userId); - if (memberJoinState(u) == JoinState::Join && - readMarker(u) == timelineEdge()) + if (memberJoinState(u) == JoinState::Join + && readMarker(u) == timelineEdge()) changes |= d->setLastReadEvent(u, p.evtId); } } } - if (evt->eventsWithReceipts().size() > 3 || totalReceipts > 10 || - et.nsecsElapsed() >= profilerMinNsecs()) - qCDebug(PROFILER) << "*** Room::processEphemeralEvent(receipts):" - << evt->eventsWithReceipts().size() - << "event(s) with" << totalReceipts << "receipt(s)," << et; + if (evt->eventsWithReceipts().size() > 3 || totalReceipts > 10 + || et.nsecsElapsed() >= profilerMinNsecs()) + qCDebug(PROFILER) + << "*** Room::processEphemeralEvent(receipts):" + << evt->eventsWithReceipts().size() << "event(s) with" + << totalReceipts << "receipt(s)," << et; } return changes; } @@ -2315,28 +2185,25 @@ Room::Changes Room::processEphemeralEvent(EventPtr&& event) Room::Changes Room::processAccountDataEvent(EventPtr&& event) { Changes changes = NoChange; - if (auto* evt = eventCast(event)) - { + if (auto* evt = eventCast(event)) { d->setTags(evt->tags()); changes |= Change::TagsChange; } - if (auto* evt = eventCast(event)) - { + if (auto* evt = eventCast(event)) { auto readEventId = evt->event_id(); qCDebug(MAIN) << "Server-side read marker at" << readEventId; d->serverReadMarker = readEventId; const auto newMarker = findInTimeline(readEventId); changes |= newMarker != timelineEdge() - ? d->markMessagesAsRead(newMarker) - : d->setLastReadEvent(localUser(), readEventId); + ? d->markMessagesAsRead(newMarker) + : d->setLastReadEvent(localUser(), readEventId); } // For all account data events auto& currentData = d->accountData[event->matrixType()]; // A polymorphic event-specific comparison might be a bit more // efficient; maaybe do it another day - if (!currentData || currentData->contentJson() != event->contentJson()) - { + if (!currentData || currentData->contentJson() != event->contentJson()) { emit accountDataAboutToChange(event->matrixType()); currentData = move(event); qCDebug(MAIN) << "Updated account data of type" @@ -2356,15 +2223,14 @@ Room::Private::buildShortlist(const ContT& users) const // display names of two topmost users excluding the current one to render // the name of the room. The below code selects 3 topmost users, // slightly extending the spec. - users_shortlist_t shortlist { }; // Prefill with nullptrs + users_shortlist_t shortlist {}; // Prefill with nullptrs std::partial_sort_copy( - users.begin(), users.end(), - shortlist.begin(), shortlist.end(), - [this] (const User* u1, const User* u2) { - // localUser(), if it's in the list, is sorted below all others - return isLocalUser(u2) || (!isLocalUser(u1) && u1->id() < u2->id()); - } - ); + users.begin(), users.end(), shortlist.begin(), shortlist.end(), + [this](const User* u1, const User* u2) { + // localUser(), if it's in the list, is sorted below all others + return isLocalUser(u2) + || (!isLocalUser(u1) && u1->id() < u2->id()); + }); return shortlist; } @@ -2373,7 +2239,7 @@ Room::Private::buildShortlist(const QStringList& userIds) const { QList users; users.reserve(userIds.size()); - for (const auto& h: userIds) + for (const auto& h : userIds) users.push_back(q->user(h)); return buildShortlist(users); } @@ -2395,23 +2261,22 @@ QString Room::Private::calculateDisplayname() const return dispName; // Using m.room.aliases in naming is explicitly discouraged by the spec - //if (!q->aliases().empty() && !q->aliases().at(0).isEmpty()) + // if (!q->aliases().empty() && !q->aliases().at(0).isEmpty()) // return q->aliases().at(0); // Supplementary code for 3 and 4: build the shortlist of users whose names // will be used to construct the room name. Takes into account MSC688's // "heroes" if available. - const bool emptyRoom = membersMap.isEmpty() || - (membersMap.size() == 1 && isLocalUser(*membersMap.begin())); - const auto shortlist = - !summary.heroes.omitted() ? buildShortlist(summary.heroes.value()) : - !emptyRoom ? buildShortlist(membersMap) : - buildShortlist(membersLeft); + const bool emptyRoom = membersMap.isEmpty() + || (membersMap.size() == 1 && isLocalUser(*membersMap.begin())); + const auto shortlist = !summary.heroes.omitted() + ? buildShortlist(summary.heroes.value()) + : !emptyRoom ? buildShortlist(membersMap) + : buildShortlist(membersLeft); QStringList names; - for (auto u: shortlist) - { + for (auto u : shortlist) { if (u == nullptr || isLocalUser(u)) break; names.push_back(q->roomMembername(u)); @@ -2421,10 +2286,10 @@ QString Room::Private::calculateDisplayname() const ? membersLeft.size() - int(joinState == JoinState::Leave) : q->joinedCount() - int(joinState == JoinState::Join); if (usersCountExceptLocal > int(shortlist.size())) - names << - tr("%Ln other(s)", - "Used to make a room name from user names: A, B and _N others_", - usersCountExceptLocal); + names << tr( + "%Ln other(s)", + "Used to make a room name from user names: A, B and _N others_", + usersCountExceptLocal); auto namesList = QLocale().createSeparatedList(names); // 3. Room members @@ -2442,8 +2307,7 @@ QString Room::Private::calculateDisplayname() const void Room::Private::updateDisplayname() { auto swappedName = calculateDisplayname(); - if (swappedName != displayname) - { + if (swappedName != displayname) { emit q->displaynameAboutToChange(q); swap(displayname, swappedName); qDebug(MAIN) << q->objectName() << "has changed display name from" @@ -2454,17 +2318,17 @@ void Room::Private::updateDisplayname() QJsonObject Room::Private::toJson() const { - QElapsedTimer et; et.start(); + QElapsedTimer et; + et.start(); QJsonObject result; addParam(result, QStringLiteral("summary"), summary); { QJsonArray stateEvents; - for (const auto* evt: currentState) - { + for (const auto* evt : currentState) { Q_ASSERT(evt->isStateEvent()); - if ((evt->isRedacted() && !is(*evt)) || - evt->contentJson().isEmpty()) + if ((evt->isRedacted() && !is(*evt)) + || evt->contentJson().isEmpty()) continue; auto json = evt->fullJson(); @@ -2474,56 +2338,54 @@ QJsonObject Room::Private::toJson() const stateEvents.append(json); } - const auto stateObjName = joinState == JoinState::Invite ? - QStringLiteral("invite_state") : QStringLiteral("state"); - result.insert(stateObjName, - QJsonObject {{ QStringLiteral("events"), stateEvents }}); + const auto stateObjName = joinState == JoinState::Invite + ? QStringLiteral("invite_state") + : QStringLiteral("state"); + result.insert( + stateObjName, + QJsonObject { { QStringLiteral("events"), stateEvents } }); } - if (!accountData.empty()) - { + if (!accountData.empty()) { QJsonArray accountDataEvents; - for (const auto& e: accountData) - { + for (const auto& e : accountData) { if (!e.second->contentJson().isEmpty()) accountDataEvents.append(e.second->fullJson()); } result.insert(QStringLiteral("account_data"), - QJsonObject {{ QStringLiteral("events"), accountDataEvents }}); + QJsonObject { { QStringLiteral("events"), + accountDataEvents } }); } - QJsonObject unreadNotifObj - { { SyncRoomData::UnreadCountKey, unreadMessages } }; + QJsonObject unreadNotifObj { { SyncRoomData::UnreadCountKey, + unreadMessages } }; if (highlightCount > 0) - unreadNotifObj.insert(QStringLiteral("highlight_count"), highlightCount); + unreadNotifObj.insert(QStringLiteral("highlight_count"), + highlightCount); if (notificationCount > 0) - unreadNotifObj.insert(QStringLiteral("notification_count"), notificationCount); + unreadNotifObj.insert(QStringLiteral("notification_count"), + notificationCount); result.insert(QStringLiteral("unread_notifications"), unreadNotifObj); if (et.elapsed() > 30) - qCDebug(PROFILER) << "Room::toJson() for" << displayname << "took" << et; + qCDebug(PROFILER) << "Room::toJson() for" << displayname << "took" + << et; return result; } -QJsonObject Room::toJson() const -{ - return d->toJson(); -} +QJsonObject Room::toJson() const { return d->toJson(); } -MemberSorter Room::memberSorter() const -{ - return MemberSorter(this); -} +MemberSorter Room::memberSorter() const { return MemberSorter(this); } -bool MemberSorter::operator()(User *u1, User *u2) const +bool MemberSorter::operator()(User* u1, User* u2) const { return operator()(u1, room->roomMembername(u2)); } -bool MemberSorter::operator ()(User* u1, const QString& u2name) const +bool MemberSorter::operator()(User* u1, const QString& u2name) const { auto n1 = room->roomMembername(u1); if (n1.startsWith('@')) -- cgit v1.2.3 From c05ade838f0fce81f2bbe80a3295618a8a26ff52 Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Fri, 2 Aug 2019 19:59:40 +0900 Subject: Apply the new brace wrapping to source files --- examples/qmc-example.cpp | 7 +-- lib/avatar.cpp | 15 ++----- lib/avatar.h | 6 +-- lib/connection.cpp | 79 ++++++++++++++++---------------- lib/connection.h | 21 +++------ lib/connectiondata.cpp | 7 +-- lib/connectiondata.h | 6 +-- lib/converters.h | 97 ++++++++++++++-------------------------- lib/e2ee.h | 3 +- lib/encryptionmanager.cpp | 3 +- lib/encryptionmanager.h | 9 ++-- lib/eventitem.h | 24 ++++------ lib/events/accountdataevents.h | 50 +++++++++------------ lib/events/callanswerevent.h | 6 +-- lib/events/callcandidatesevent.h | 6 +-- lib/events/callhangupevent.h | 6 +-- lib/events/callinviteevent.h | 6 +-- lib/events/directchatevent.h | 10 ++--- lib/events/encryptedevent.h | 6 +-- lib/events/encryptionevent.cpp | 6 +-- lib/events/encryptionevent.h | 15 ++----- lib/events/event.cpp | 4 +- lib/events/event.h | 24 ++++------ lib/events/eventcontent.cpp | 3 +- lib/events/eventcontent.h | 46 ++++++------------- lib/events/eventloader.h | 9 ++-- lib/events/reactionevent.h | 16 +++---- lib/events/receiptevent.cpp | 3 +- lib/events/receiptevent.h | 12 ++--- lib/events/redactionevent.h | 9 ++-- lib/events/roomavatarevent.h | 9 ++-- lib/events/roomcreateevent.h | 13 ++---- lib/events/roomevent.cpp | 3 +- lib/events/roomevent.h | 9 ++-- lib/events/roommemberevent.cpp | 6 +-- lib/events/roommemberevent.h | 22 +++------ lib/events/roommessageevent.cpp | 12 ++--- lib/events/roommessageevent.h | 24 ++++------ lib/events/roomtombstoneevent.h | 10 ++--- lib/events/simplestateevents.h | 25 ++++------- lib/events/stateevent.h | 21 +++------ lib/events/typingevent.cpp | 3 +- lib/events/typingevent.h | 6 +-- lib/jobs/basejob.cpp | 6 +-- lib/jobs/basejob.h | 35 ++++----------- lib/jobs/downloadfilejob.cpp | 7 +-- lib/jobs/downloadfilejob.h | 11 ++--- lib/jobs/mediathumbnailjob.h | 6 +-- lib/jobs/postreadmarkersjob.h | 3 +- lib/jobs/requestdata.cpp | 12 ++--- lib/jobs/requestdata.h | 9 ++-- lib/jobs/syncjob.h | 6 +-- lib/joinstate.h | 6 +-- lib/logging.h | 3 +- lib/networkaccessmanager.cpp | 6 +-- lib/networkaccessmanager.h | 6 +-- lib/networksettings.h | 6 +-- lib/qt_connection_util.h | 12 ++--- lib/room.cpp | 35 ++++++--------- lib/room.h | 28 +++--------- lib/settings.h | 16 +++---- lib/syncdata.h | 15 +++---- lib/user.cpp | 6 +-- lib/user.h | 6 +-- lib/util.cpp | 18 +++----- lib/util.h | 64 ++++++++------------------ 66 files changed, 335 insertions(+), 664 deletions(-) (limited to 'lib/room.cpp') diff --git a/examples/qmc-example.cpp b/examples/qmc-example.cpp index d6cba76a..f4067009 100644 --- a/examples/qmc-example.cpp +++ b/examples/qmc-example.cpp @@ -24,8 +24,7 @@ using std::cout; using std::endl; using namespace std::placeholders; -class QMCTest : public QObject -{ +class QMCTest : public QObject { public: QMCTest(Connection* conn, QString testRoomName, QString source); @@ -92,9 +91,7 @@ bool QMCTest::validatePendingEvent(const QString& txnId) } QMCTest::QMCTest(Connection* conn, QString testRoomName, QString source) - : c(conn) - , origin(std::move(source)) - , targetRoomName(std::move(testRoomName)) + : c(conn), origin(std::move(source)), targetRoomName(std::move(testRoomName)) { if (!origin.isEmpty()) cout << "Origin for the test message: " << origin.toStdString() << endl; diff --git a/lib/avatar.cpp b/lib/avatar.cpp index 0e58a1ce..614f008d 100644 --- a/lib/avatar.cpp +++ b/lib/avatar.cpp @@ -32,12 +32,9 @@ using namespace QMatrixClient; using std::move; -class Avatar::Private -{ +class Avatar::Private { public: - explicit Private(QUrl url = {}) - : _url(move(url)) - {} + explicit Private(QUrl url = {}) : _url(move(url)) {} ~Private() { if (isJobRunning(_thumbnailRequest)) @@ -65,13 +62,9 @@ public: mutable std::vector callbacks; }; -Avatar::Avatar() - : d(std::make_unique()) -{} +Avatar::Avatar() : d(std::make_unique()) {} -Avatar::Avatar(QUrl url) - : d(std::make_unique(std::move(url))) -{} +Avatar::Avatar(QUrl url) : d(std::make_unique(std::move(url))) {} Avatar::Avatar(Avatar&&) = default; diff --git a/lib/avatar.h b/lib/avatar.h index 37991192..c33e1982 100644 --- a/lib/avatar.h +++ b/lib/avatar.h @@ -24,12 +24,10 @@ #include #include -namespace QMatrixClient -{ +namespace QMatrixClient { class Connection; -class Avatar -{ +class Avatar { public: explicit Avatar(); explicit Avatar(QUrl url); diff --git a/lib/connection.cpp b/lib/connection.cpp index 6ebe05dc..6cd6ad0b 100644 --- a/lib/connection.cpp +++ b/lib/connection.cpp @@ -70,8 +70,7 @@ HashT erase_if(HashT& hashMap, Pred pred) return removals; } -class Connection::Private -{ +class Connection::Private { public: explicit Private(std::unique_ptr&& connection) : data(move(connection)) @@ -151,15 +150,12 @@ public: }; Connection::Connection(const QUrl& server, QObject* parent) - : QObject(parent) - , d(new Private(std::make_unique(server))) + : QObject(parent), d(new Private(std::make_unique(server))) { d->q = this; // All d initialization should occur before this line } -Connection::Connection(QObject* parent) - : Connection({}, parent) -{} +Connection::Connection(QObject* parent) : Connection({}, parent) {} Connection::~Connection() { @@ -183,45 +179,47 @@ void Connection::resolveServer(const QString& mxid) qCDebug(MAIN) << "Finding the server" << domain; auto getWellKnownJob = callApi(); - connect(getWellKnownJob, &BaseJob::finished, - [this, getWellKnownJob, maybeBaseUrl] { - if (getWellKnownJob->status() == BaseJob::NotFoundError) { - qCDebug(MAIN) << "No .well-known file, IGNORE"; - } else if (getWellKnownJob->status() != BaseJob::Success) { + connect( + getWellKnownJob, &BaseJob::finished, + [this, getWellKnownJob, maybeBaseUrl] { + if (getWellKnownJob->status() == BaseJob::NotFoundError) + qCDebug(MAIN) << "No .well-known file, IGNORE"; + else { + if (getWellKnownJob->status() != BaseJob::Success) { qCDebug(MAIN) << "Fetching .well-known file failed, FAIL_PROMPT"; emit resolveError(tr("Fetching .well-known file failed")); return; - } else if (getWellKnownJob->data().homeserver.baseUrl.isEmpty()) { + } + QUrl baseUrl(getWellKnownJob->data().homeserver.baseUrl); + if (baseUrl.isEmpty()) { qCDebug(MAIN) << "base_url not provided, FAIL_PROMPT"; emit resolveError(tr("base_url not provided")); return; - } else if (!QUrl(getWellKnownJob->data().homeserver.baseUrl) - .isValid()) { + } + if (!baseUrl.isValid()) { qCDebug(MAIN) << "base_url invalid, FAIL_ERROR"; emit resolveError(tr("base_url invalid")); return; - } else { - QUrl baseUrl(getWellKnownJob->data().homeserver.baseUrl); - - qCDebug(MAIN) << ".well-known for" << maybeBaseUrl.host() - << "is" << baseUrl.toString(); - setHomeserver(baseUrl); } - auto getVersionsJob = callApi(); - - connect(getVersionsJob, &BaseJob::finished, - [this, getVersionsJob] { - if (getVersionsJob->status() == BaseJob::Success) { - qCDebug(MAIN) << "homeserver url is valid"; - emit resolved(); - } else { - qCDebug(MAIN) << "homeserver url invalid"; - emit resolveError(tr("homeserver url invalid")); - } - }); + qCDebug(MAIN) << ".well-known for" << maybeBaseUrl.host() + << "is" << baseUrl.toString(); + setHomeserver(baseUrl); + } + + auto getVersionsJob = callApi(); + + connect(getVersionsJob, &BaseJob::finished, [this, getVersionsJob] { + if (getVersionsJob->status() == BaseJob::Success) { + qCDebug(MAIN) << "homeserver url is valid"; + emit resolved(); + } else { + qCDebug(MAIN) << "homeserver url invalid"; + emit resolveError(tr("homeserver url invalid")); + } }); + }); } void Connection::connectToServer(const QString& user, const QString& password, @@ -372,8 +370,8 @@ void Connection::sync(int timeout) connect(job, &SyncJob::failure, this, [this, job] { d->syncJob = nullptr; if (job->error() == BaseJob::ContentAccessError) { - qCWarning(SYNCJOB) - << "Sync job failed with ContentAccessError - login expired?"; + qCWarning(SYNCJOB) << "Sync job failed with ContentAccessError - " + "login expired?"; emit loginError(job->errorString(), job->rawDataSample()); } else emit syncError(job->errorString(), job->rawDataSample()); @@ -437,7 +435,6 @@ void Connection::onSyncSuccess(SyncData&& data, bool fromCache) visit( *eventPtr, [this](const DirectChatEvent& dce) { - // See // https://github.com/QMatrixClient/libqmatrixclient/wiki/Handling-direct-chat-events const auto& usersToDCs = dce.usersToDirectChats(); DirectChatsMap remoteRemovals = @@ -492,8 +489,8 @@ void Connection::onSyncSuccess(SyncData&& data, bool fromCache) << QStringList::fromSet(ignoredUsers()).join(','); auto& currentData = d->accountData[accountEvent.matrixType()]; - // A polymorphic event-specific comparison might be a bit more - // efficient; maaybe do it another day + // A polymorphic event-specific comparison might be a bit + // more efficient; maaybe do it another day if (!currentData || currentData->contentJson() != accountEvent.contentJson()) { currentData = std::move(eventPtr); @@ -678,9 +675,9 @@ void Connection::requestDirectChat(const QString& userId) if (auto* u = user(userId)) requestDirectChat(u); else - qCCritical(MAIN) - << "Connection::requestDirectChat: Couldn't get a user object for" - << userId; + qCCritical(MAIN) << "Connection::requestDirectChat: Couldn't get a " + "user object for" + << userId; } void Connection::requestDirectChat(User* u) diff --git a/lib/connection.h b/lib/connection.h index 8d65f0e7..b89c0c65 100644 --- a/lib/connection.h +++ b/lib/connection.h @@ -32,13 +32,11 @@ #include -namespace QtOlm -{ +namespace QtOlm { class Account; } -namespace QMatrixClient -{ +namespace QMatrixClient { class Room; class User; class ConnectionData; @@ -93,14 +91,9 @@ static inline user_factory_t defaultUserFactory() * * \sa Connection::callApi */ -enum RunningPolicy -{ - ForegroundRequest = 0x0, - BackgroundRequest = 0x1 -}; +enum RunningPolicy { ForegroundRequest = 0x0, BackgroundRequest = 0x1 }; -class Connection : public QObject -{ +class Connection : public QObject { Q_OBJECT Q_PROPERTY(User* localUser READ user NOTIFY stateChanged) @@ -129,8 +122,7 @@ public: using UsersToDevicesToEvents = std::unordered_map>; - enum RoomVisibility - { + enum RoomVisibility { PublishRoom, UnpublishRoom }; // FIXME: Should go inside CreateRoomJob @@ -285,8 +277,7 @@ public: Q_INVOKABLE void getTurnServers(); - struct SupportedRoomVersion - { + struct SupportedRoomVersion { QString id; QString status; diff --git a/lib/connectiondata.cpp b/lib/connectiondata.cpp index c157565f..df4cece2 100644 --- a/lib/connectiondata.cpp +++ b/lib/connectiondata.cpp @@ -23,11 +23,8 @@ using namespace QMatrixClient; -struct ConnectionData::Private -{ - explicit Private(QUrl url) - : baseUrl(std::move(url)) - {} +struct ConnectionData::Private { + explicit Private(QUrl url) : baseUrl(std::move(url)) {} QUrl baseUrl; QByteArray accessToken; diff --git a/lib/connectiondata.h b/lib/connectiondata.h index 6f9f090c..9b579b1c 100644 --- a/lib/connectiondata.h +++ b/lib/connectiondata.h @@ -24,10 +24,8 @@ class QNetworkAccessManager; -namespace QMatrixClient -{ -class ConnectionData -{ +namespace QMatrixClient { +class ConnectionData { public: explicit ConnectionData(QUrl baseUrl); virtual ~ConnectionData(); diff --git a/lib/converters.h b/lib/converters.h index aa07261d..0085fa4b 100644 --- a/lib/converters.h +++ b/lib/converters.h @@ -38,11 +38,9 @@ using optional = std::experimental::optional; #endif // Enable std::unordered_map -namespace std -{ +namespace std { template <> -struct hash -{ +struct hash { size_t operator()(const QString& s) const Q_DECL_NOEXCEPT { return qHash(s @@ -57,18 +55,15 @@ struct hash class QVariant; -namespace QMatrixClient -{ +namespace QMatrixClient { template -struct JsonObjectConverter -{ +struct JsonObjectConverter { static void dumpTo(QJsonObject& jo, const T& pod) { jo = pod.toJson(); } static void fillFrom(const QJsonObject& jo, T& pod) { pod = T(jo); } }; template -struct JsonConverter -{ +struct JsonConverter { static QJsonObject dump(const T& pod) { QJsonObject jo; @@ -139,52 +134,44 @@ inline void fillFromJson(const QJsonValue& jv, T& pod) // JsonConverter<> specialisations template -struct TrivialJsonDumper -{ +struct TrivialJsonDumper { // Works for: QJsonValue (and all things it can consume), // QJsonObject, QJsonArray static auto dump(const T& val) { return val; } }; template <> -struct JsonConverter : public TrivialJsonDumper -{ +struct JsonConverter : public TrivialJsonDumper { static auto load(const QJsonValue& jv) { return jv.toBool(); } }; template <> -struct JsonConverter : public TrivialJsonDumper -{ +struct JsonConverter : public TrivialJsonDumper { static auto load(const QJsonValue& jv) { return jv.toInt(); } }; template <> -struct JsonConverter : public TrivialJsonDumper -{ +struct JsonConverter : public TrivialJsonDumper { static auto load(const QJsonValue& jv) { return jv.toDouble(); } }; template <> -struct JsonConverter : public TrivialJsonDumper -{ +struct JsonConverter : public TrivialJsonDumper { static auto load(const QJsonValue& jv) { return float(jv.toDouble()); } }; template <> -struct JsonConverter : public TrivialJsonDumper -{ +struct JsonConverter : public TrivialJsonDumper { static auto load(const QJsonValue& jv) { return qint64(jv.toDouble()); } }; template <> -struct JsonConverter : public TrivialJsonDumper -{ +struct JsonConverter : public TrivialJsonDumper { static auto load(const QJsonValue& jv) { return jv.toString(); } }; template <> -struct JsonConverter -{ +struct JsonConverter { static auto dump(const QDateTime& val) = delete; // not provided yet static auto load(const QJsonValue& jv) { @@ -193,8 +180,7 @@ struct JsonConverter }; template <> -struct JsonConverter -{ +struct JsonConverter { static auto dump(const QDate& val) = delete; // not provided yet static auto load(const QJsonValue& jv) { @@ -203,14 +189,12 @@ struct JsonConverter }; template <> -struct JsonConverter : public TrivialJsonDumper -{ +struct JsonConverter : public TrivialJsonDumper { static auto load(const QJsonValue& jv) { return jv.toArray(); } }; template <> -struct JsonConverter -{ +struct JsonConverter { static QString dump(const QByteArray& ba) { return ba.constData(); } static auto load(const QJsonValue& jv) { @@ -219,15 +203,13 @@ struct JsonConverter }; template <> -struct JsonConverter -{ +struct JsonConverter { static QJsonValue dump(const QVariant& v); static QVariant load(const QJsonValue& jv); }; template -struct JsonConverter> -{ +struct JsonConverter> { static QJsonValue dump(const Omittable& from) { return from.omitted() ? QJsonValue() : toJson(from.value()); @@ -241,8 +223,7 @@ struct JsonConverter> }; template -struct JsonArrayConverter -{ +struct JsonArrayConverter { static void dumpTo(QJsonArray& ar, const VectorT& vals) { for (const auto& v : vals) @@ -267,20 +248,17 @@ struct JsonArrayConverter }; template -struct JsonConverter> : public JsonArrayConverter> -{}; +struct JsonConverter> + : public JsonArrayConverter> {}; template -struct JsonConverter> : public JsonArrayConverter> -{}; +struct JsonConverter> : public JsonArrayConverter> {}; template -struct JsonConverter> : public JsonArrayConverter> -{}; +struct JsonConverter> : public JsonArrayConverter> {}; template <> -struct JsonConverter : public JsonConverter> -{ +struct JsonConverter : public JsonConverter> { static auto dump(const QStringList& sl) { return QJsonArray::fromStringList(sl); @@ -288,8 +266,7 @@ struct JsonConverter : public JsonConverter> }; template <> -struct JsonObjectConverter> -{ +struct JsonObjectConverter> { static void dumpTo(QJsonObject& json, const QSet& s) { for (const auto& e : s) @@ -305,8 +282,7 @@ struct JsonObjectConverter> }; template -struct HashMapFromJson -{ +struct HashMapFromJson { static void dumpTo(QJsonObject& json, const HashMapT& hashMap) { for (auto it = hashMap.begin(); it != hashMap.end(); ++it) @@ -322,13 +298,11 @@ struct HashMapFromJson template struct JsonObjectConverter> - : public HashMapFromJson> -{}; + : public HashMapFromJson> {}; template struct JsonObjectConverter> - : public HashMapFromJson> -{}; + : public HashMapFromJson> {}; // We could use std::conditional<> below but QT_VERSION* macros in C++ code // cause (kinda valid but useless and noisy) compiler warnings about @@ -340,16 +314,14 @@ using variant_map_t = QVariantMap; #endif template <> -struct JsonConverter -{ +struct JsonConverter { static QJsonObject dump(const variant_map_t& vh); static QVariantHash load(const QJsonValue& jv); }; // Conditional insertion into a QJsonObject -namespace _impl -{ +namespace _impl { template inline void addTo(QJsonObject& o, const QString& k, ValT&& v) { @@ -384,8 +356,7 @@ namespace _impl // This one is for types that don't have isEmpty() and for all types // when Force is true template - struct AddNode - { + struct AddNode { template static void impl(ContT& container, const QString& key, ForwardedT&& value) @@ -396,8 +367,7 @@ namespace _impl // This one is for types that have isEmpty() when Force is false template - struct AddNode().isEmpty())> - { + struct AddNode().isEmpty())> { template static void impl(ContT& container, const QString& key, ForwardedT&& value) @@ -409,8 +379,7 @@ namespace _impl // This one unfolds Omittable<> (also only when Force is false) template - struct AddNode, false> - { + struct AddNode, false> { template static void impl(ContT& container, const QString& key, const OmittableT& value) diff --git a/lib/e2ee.h b/lib/e2ee.h index d3329def..c85211be 100644 --- a/lib/e2ee.h +++ b/lib/e2ee.h @@ -4,8 +4,7 @@ #include -namespace QMatrixClient -{ +namespace QMatrixClient { static const auto CiphertextKeyL = "ciphertext"_ls; static const auto SenderKeyKeyL = "sender_key"_ls; static const auto DeviceIdKeyL = "device_id"_ls; diff --git a/lib/encryptionmanager.cpp b/lib/encryptionmanager.cpp index 46d937b8..15723688 100644 --- a/lib/encryptionmanager.cpp +++ b/lib/encryptionmanager.cpp @@ -16,8 +16,7 @@ using namespace QMatrixClient; using namespace QtOlm; using std::move; -class EncryptionManager::Private -{ +class EncryptionManager::Private { public: explicit Private(const QByteArray& encryptionAccountPickle, float signedKeysProportion, float oneTimeKeyThreshold) diff --git a/lib/encryptionmanager.h b/lib/encryptionmanager.h index 02bb882f..79c25a00 100644 --- a/lib/encryptionmanager.h +++ b/lib/encryptionmanager.h @@ -5,17 +5,14 @@ #include #include -namespace QtOlm -{ +namespace QtOlm { class Account; } -namespace QMatrixClient -{ +namespace QMatrixClient { class Connection; -class EncryptionManager : public QObject -{ +class EncryptionManager : public QObject { Q_OBJECT public: diff --git a/lib/eventitem.h b/lib/eventitem.h index 58f5479c..68d1ae06 100644 --- a/lib/eventitem.h +++ b/lib/eventitem.h @@ -22,12 +22,10 @@ #include -namespace QMatrixClient -{ +namespace QMatrixClient { class StateEventBase; -class EventStatus -{ +class EventStatus { Q_GADGET public: /** Special marks an event can assume @@ -35,8 +33,7 @@ public: * This is used to hint at a special status of some events in UI. * All values except Redacted and Hidden are mutually exclusive. */ - enum Code - { + enum Code { Normal = 0x0, //< No special designation Submitted = 0x01, //< The event has just been submitted for sending FileUploaded = 0x02, //< The file attached to the event has been @@ -51,11 +48,9 @@ public: Q_FLAG(Status) }; -class EventItemBase -{ +class EventItemBase { public: - explicit EventItemBase(RoomEventPtr&& e) - : evt(std::move(e)) + explicit EventItemBase(RoomEventPtr&& e) : evt(std::move(e)) { Q_ASSERT(evt); } @@ -87,16 +82,14 @@ private: RoomEventPtr evt; }; -class TimelineItem : public EventItemBase -{ +class TimelineItem : public EventItemBase { public: // For compatibility with Qt containers, even though we use // a std:: container now for the room timeline using index_t = int; TimelineItem(RoomEventPtr&& e, index_t number) - : EventItemBase(std::move(e)) - , idx(number) + : EventItemBase(std::move(e)), idx(number) {} index_t index() const { return idx; } @@ -118,8 +111,7 @@ inline const CallEventBase* EventItemBase::viewAs() const return evt->isCallEvent() ? weakPtrCast(evt) : nullptr; } -class PendingEventItem : public EventItemBase -{ +class PendingEventItem : public EventItemBase { Q_GADGET public: using EventItemBase::EventItemBase; diff --git a/lib/events/accountdataevents.h b/lib/events/accountdataevents.h index abab9867..3f519668 100644 --- a/lib/events/accountdataevents.h +++ b/lib/events/accountdataevents.h @@ -24,20 +24,16 @@ #include "event.h" #include "eventcontent.h" -namespace QMatrixClient -{ +namespace QMatrixClient { constexpr const char* FavouriteTag = "m.favourite"; constexpr const char* LowPriorityTag = "m.lowpriority"; -struct TagRecord -{ +struct TagRecord { using order_type = Omittable; order_type order; - TagRecord(order_type order = none) - : order(order) - {} + TagRecord(order_type order = none) : order(order) {} bool operator<(const TagRecord& other) const { @@ -48,8 +44,7 @@ struct TagRecord }; template <> -struct JsonObjectConverter -{ +struct JsonObjectConverter { static void fillFrom(const QJsonObject& jo, TagRecord& rec) { // Parse a float both from JSON double and JSON string because @@ -72,26 +67,23 @@ struct JsonObjectConverter using TagsMap = QHash; -#define DEFINE_SIMPLE_EVENT(_Name, _TypeId, _ContentType, _ContentKey) \ - class _Name : public Event \ - { \ - public: \ - using content_type = _ContentType; \ - DEFINE_EVENT_TYPEID(_TypeId, _Name) \ - explicit _Name(QJsonObject obj) \ - : Event(typeId(), std::move(obj)) \ - {} \ - explicit _Name(_ContentType content) \ - : Event(typeId(), matrixTypeId(), \ - QJsonObject { { QStringLiteral(#_ContentKey), \ - toJson(std::move(content)) } }) \ - {} \ - auto _ContentKey() const \ - { \ - return content(#_ContentKey##_ls); \ - } \ - }; \ - REGISTER_EVENT_TYPE(_Name) \ +#define DEFINE_SIMPLE_EVENT(_Name, _TypeId, _ContentType, _ContentKey) \ + class _Name : public Event { \ + public: \ + using content_type = _ContentType; \ + DEFINE_EVENT_TYPEID(_TypeId, _Name) \ + explicit _Name(QJsonObject obj) : Event(typeId(), std::move(obj)) {} \ + explicit _Name(_ContentType content) \ + : Event(typeId(), matrixTypeId(), \ + QJsonObject { { QStringLiteral(#_ContentKey), \ + toJson(std::move(content)) } }) \ + {} \ + auto _ContentKey() const \ + { \ + return content(#_ContentKey##_ls); \ + } \ + }; \ + REGISTER_EVENT_TYPE(_Name) \ // End of macro DEFINE_SIMPLE_EVENT(TagEvent, "m.tag", TagsMap, tags) diff --git a/lib/events/callanswerevent.h b/lib/events/callanswerevent.h index 69662eb9..052f732d 100644 --- a/lib/events/callanswerevent.h +++ b/lib/events/callanswerevent.h @@ -20,10 +20,8 @@ #include "roomevent.h" -namespace QMatrixClient -{ -class CallAnswerEvent : public CallEventBase -{ +namespace QMatrixClient { +class CallAnswerEvent : public CallEventBase { public: DEFINE_EVENT_TYPEID("m.call.answer", CallAnswerEvent) diff --git a/lib/events/callcandidatesevent.h b/lib/events/callcandidatesevent.h index 1c12b800..2a915a43 100644 --- a/lib/events/callcandidatesevent.h +++ b/lib/events/callcandidatesevent.h @@ -20,10 +20,8 @@ #include "roomevent.h" -namespace QMatrixClient -{ -class CallCandidatesEvent : public CallEventBase -{ +namespace QMatrixClient { +class CallCandidatesEvent : public CallEventBase { public: DEFINE_EVENT_TYPEID("m.call.candidates", CallCandidatesEvent) diff --git a/lib/events/callhangupevent.h b/lib/events/callhangupevent.h index 0a5a3283..97fa2f52 100644 --- a/lib/events/callhangupevent.h +++ b/lib/events/callhangupevent.h @@ -20,10 +20,8 @@ #include "roomevent.h" -namespace QMatrixClient -{ -class CallHangupEvent : public CallEventBase -{ +namespace QMatrixClient { +class CallHangupEvent : public CallEventBase { public: DEFINE_EVENT_TYPEID("m.call.hangup", CallHangupEvent) diff --git a/lib/events/callinviteevent.h b/lib/events/callinviteevent.h index 4334ca5b..9b9d0ae5 100644 --- a/lib/events/callinviteevent.h +++ b/lib/events/callinviteevent.h @@ -20,10 +20,8 @@ #include "roomevent.h" -namespace QMatrixClient -{ -class CallInviteEvent : public CallEventBase -{ +namespace QMatrixClient { +class CallInviteEvent : public CallEventBase { public: DEFINE_EVENT_TYPEID("m.call.invite", CallInviteEvent) diff --git a/lib/events/directchatevent.h b/lib/events/directchatevent.h index 6b4a08ee..94857a93 100644 --- a/lib/events/directchatevent.h +++ b/lib/events/directchatevent.h @@ -20,16 +20,12 @@ #include "event.h" -namespace QMatrixClient -{ -class DirectChatEvent : public Event -{ +namespace QMatrixClient { +class DirectChatEvent : public Event { public: DEFINE_EVENT_TYPEID("m.direct", DirectChatEvent) - explicit DirectChatEvent(const QJsonObject& obj) - : Event(typeId(), obj) - {} + explicit DirectChatEvent(const QJsonObject& obj) : Event(typeId(), obj) {} QMultiHash usersToDirectChats() const; }; diff --git a/lib/events/encryptedevent.h b/lib/events/encryptedevent.h index 0dbce25c..67298a27 100644 --- a/lib/events/encryptedevent.h +++ b/lib/events/encryptedevent.h @@ -3,8 +3,7 @@ #include "e2ee.h" #include "roomevent.h" -namespace QMatrixClient -{ +namespace QMatrixClient { class Room; /* * While the specification states: @@ -24,8 +23,7 @@ class Room; * in general. It's possible, because RoomEvent interface is similar to Event's * one and doesn't add new restrictions, just provides additional features. */ -class EncryptedEvent : public RoomEvent -{ +class EncryptedEvent : public RoomEvent { Q_GADGET public: DEFINE_EVENT_TYPEID("m.room.encrypted", EncryptedEvent) diff --git a/lib/events/encryptionevent.cpp b/lib/events/encryptionevent.cpp index 995c8dad..0c732a51 100644 --- a/lib/events/encryptionevent.cpp +++ b/lib/events/encryptionevent.cpp @@ -15,11 +15,9 @@ static const std::array encryptionStrings = { { QMatrixClient::MegolmV1AesSha2AlgoKey } }; -namespace QMatrixClient -{ +namespace QMatrixClient { template <> -struct JsonConverter -{ +struct JsonConverter { static EncryptionType load(const QJsonValue& jv) { const auto& encryptionString = jv.toString(); diff --git a/lib/events/encryptionevent.h b/lib/events/encryptionevent.h index 97119c8d..debabcae 100644 --- a/lib/events/encryptionevent.h +++ b/lib/events/encryptionevent.h @@ -21,16 +21,10 @@ #include "eventcontent.h" #include "stateevent.h" -namespace QMatrixClient -{ -class EncryptionEventContent : public EventContent::Base -{ +namespace QMatrixClient { +class EncryptionEventContent : public EventContent::Base { public: - enum EncryptionType : size_t - { - MegolmV1AesSha2 = 0, - Undefined - }; + enum EncryptionType : size_t { MegolmV1AesSha2 = 0, Undefined }; explicit EncryptionEventContent(EncryptionType et = Undefined) : encryption(et) @@ -48,8 +42,7 @@ protected: using EncryptionType = EncryptionEventContent::EncryptionType; -class EncryptionEvent : public StateEvent -{ +class EncryptionEvent : public StateEvent { Q_GADGET public: DEFINE_EVENT_TYPEID("m.room.encryption", EncryptionEvent) diff --git a/lib/events/event.cpp b/lib/events/event.cpp index 718a6602..694254fe 100644 --- a/lib/events/event.cpp +++ b/lib/events/event.cpp @@ -42,9 +42,7 @@ QString EventTypeRegistry::getMatrixType(event_type_t typeId) : QString(); } -Event::Event(Type type, const QJsonObject& json) - : _type(type) - , _json(json) +Event::Event(Type type, const QJsonObject& json) : _type(type), _json(json) { if (!json.contains(ContentKeyL) && !json.value(UnsignedKeyL).toObject().contains(RedactedCauseKeyL)) { diff --git a/lib/events/event.h b/lib/events/event.h index d6525281..686bd8e0 100644 --- a/lib/events/event.h +++ b/lib/events/event.h @@ -25,8 +25,7 @@ # define USE_EVENTTYPE_ALIAS 1 #endif -namespace QMatrixClient -{ +namespace QMatrixClient { // === event_ptr_tt<> and type casting facilities === template @@ -85,8 +84,7 @@ inline QJsonObject basicEventJson(StrT matrixType, const QJsonObject& content) using event_type_t = size_t; using event_mtype_t = const char*; -class EventTypeRegistry -{ +class EventTypeRegistry { public: ~EventTypeRegistry() = default; @@ -121,8 +119,7 @@ inline event_type_t EventTypeRegistry::initializeTypeId() } template -struct EventTypeTraits -{ +struct EventTypeTraits { static event_type_t id() { static const auto id = EventTypeRegistry::initializeTypeId(); @@ -148,8 +145,7 @@ inline event_ptr_tt makeEvent(ArgTs&&... args) } template -class EventFactory -{ +class EventFactory { public: template static auto addMethod(FnT&& method) @@ -223,8 +219,7 @@ inline auto registerEventType() // === Event === -class Event -{ +class Event { Q_GADGET Q_PROPERTY(Type type READ type CONSTANT) Q_PROPERTY(QJsonObject contentJson READ contentJson CONSTANT) @@ -304,16 +299,14 @@ using Events = EventsArray; // to enable its deserialisation from a /sync and other // polymorphic event arrays #define REGISTER_EVENT_TYPE(_Type) \ - namespace \ - { \ + namespace { \ [[gnu::unused]] static const auto _factoryAdded##_Type = \ registerEventType<_Type>(); \ } \ // End of macro #ifdef USE_EVENTTYPE_ALIAS -namespace EventType -{ +namespace EventType { inline event_type_t logEventType(event_type_t id, const char* idName) { qDebug(EVENTS) << "Using id" << id << "for" << idName; @@ -324,8 +317,7 @@ namespace EventType // This macro provides constants in EventType:: namespace for // back-compatibility with libQMatrixClient 0.3 event type system. # define DEFINE_EVENTTYPE_ALIAS(_Id, _Type) \ - namespace EventType \ - { \ + namespace EventType { \ [[deprecated("Use is<>(), eventCast<>() or " \ "visit<>()")]] static const auto _Id = \ logEventType(typeId<_Type>(), #_Id); \ diff --git a/lib/events/eventcontent.cpp b/lib/events/eventcontent.cpp index 2b84c2b7..814f2787 100644 --- a/lib/events/eventcontent.cpp +++ b/lib/events/eventcontent.cpp @@ -70,8 +70,7 @@ void FileInfo::fillInfoJson(QJsonObject* infoJson) const ImageInfo::ImageInfo(const QUrl& u, qint64 fileSize, QMimeType mimeType, const QSize& imageSize, const QString& originalFilename) - : FileInfo(u, fileSize, mimeType, originalFilename) - , imageSize(imageSize) + : FileInfo(u, fileSize, mimeType, originalFilename), imageSize(imageSize) {} ImageInfo::ImageInfo(const QUrl& u, const QJsonObject& infoJson, diff --git a/lib/events/eventcontent.h b/lib/events/eventcontent.h index 7a3db1fc..5c0f92d1 100644 --- a/lib/events/eventcontent.h +++ b/lib/events/eventcontent.h @@ -26,10 +26,8 @@ #include #include -namespace QMatrixClient -{ -namespace EventContent -{ +namespace QMatrixClient { +namespace EventContent { /** * A base class for all content types that can be stored * in a RoomMessageEvent @@ -40,12 +38,9 @@ namespace EventContent * assumed but not required that a content object can also be created * from plain data. */ - class Base - { + class Base { public: - explicit Base(QJsonObject o = {}) - : originalJson(std::move(o)) - {} + explicit Base(QJsonObject o = {}) : originalJson(std::move(o)) {} virtual ~Base() = default; // FIXME: make toJson() from converters.* work on base classes @@ -90,8 +85,7 @@ namespace EventContent * * This class is not polymorphic. */ - class FileInfo - { + class FileInfo { public: explicit FileInfo(const QUrl& u, qint64 payloadSize = -1, const QMimeType& mimeType = {}, @@ -131,8 +125,7 @@ namespace EventContent /** * A content info class for image content types: image, thumbnail, video */ - class ImageInfo : public FileInfo - { + class ImageInfo : public FileInfo { public: explicit ImageInfo(const QUrl& u, qint64 fileSize = -1, QMimeType mimeType = {}, const QSize& imageSize = {}, @@ -153,16 +146,11 @@ namespace EventContent * the JSON representation of event content; namely, * "info/thumbnail_url" and "info/thumbnail_info" fields are used. */ - class Thumbnail : public ImageInfo - { + class Thumbnail : public ImageInfo { public: - Thumbnail() - : ImageInfo(QUrl()) - {} // To allow empty thumbnails + Thumbnail() : ImageInfo(QUrl()) {} // To allow empty thumbnails Thumbnail(const QJsonObject& infoJson); - Thumbnail(const ImageInfo& info) - : ImageInfo(info) - {} + Thumbnail(const ImageInfo& info) : ImageInfo(info) {} using ImageInfo::ImageInfo; /** @@ -172,12 +160,9 @@ namespace EventContent void fillInfoJson(QJsonObject* infoJson) const; }; - class TypedBase : public Base - { + class TypedBase : public Base { public: - explicit TypedBase(QJsonObject o = {}) - : Base(std::move(o)) - {} + explicit TypedBase(QJsonObject o = {}) : Base(std::move(o)) {} virtual QMimeType type() const = 0; virtual const FileInfo* fileInfo() const { return nullptr; } virtual FileInfo* fileInfo() { return nullptr; } @@ -198,8 +183,7 @@ namespace EventContent * \tparam InfoT base info class */ template - class UrlBasedContent : public TypedBase, public InfoT - { + class UrlBasedContent : public TypedBase, public InfoT { public: using InfoT::InfoT; explicit UrlBasedContent(const QJsonObject& json) @@ -227,13 +211,11 @@ namespace EventContent }; template - class UrlWithThumbnailContent : public UrlBasedContent - { + class UrlWithThumbnailContent : public UrlBasedContent { public: using UrlBasedContent::UrlBasedContent; explicit UrlWithThumbnailContent(const QJsonObject& json) - : UrlBasedContent(json) - , thumbnail(InfoT::originalInfoJson) + : UrlBasedContent(json), thumbnail(InfoT::originalInfoJson) { // Another small hack, to simplify making a thumbnail link UrlBasedContent::originalJson.insert("thumbnailMediaId", diff --git a/lib/events/eventloader.h b/lib/events/eventloader.h index a203eaa3..9e8bb410 100644 --- a/lib/events/eventloader.h +++ b/lib/events/eventloader.h @@ -20,10 +20,8 @@ #include "stateevent.h" -namespace QMatrixClient -{ -namespace _impl -{ +namespace QMatrixClient { +namespace _impl { template static inline auto loadEvent(const QJsonObject& json, const QString& matrixType) @@ -75,8 +73,7 @@ inline StateEventPtr loadStateEvent(const QString& matrixType, } template -struct JsonConverter> -{ +struct JsonConverter> { static auto load(const QJsonValue& jv) { return loadEvent(jv.toObject()); diff --git a/lib/events/reactionevent.h b/lib/events/reactionevent.h index d524b549..b1e04561 100644 --- a/lib/events/reactionevent.h +++ b/lib/events/reactionevent.h @@ -20,11 +20,9 @@ #include "roomevent.h" -namespace QMatrixClient -{ +namespace QMatrixClient { -struct EventRelation -{ +struct EventRelation { using reltypeid_t = const char*; static constexpr reltypeid_t Reply() { return "m.in_reply_to"; } static constexpr reltypeid_t Annotation() { return "m.annotation"; } @@ -48,14 +46,12 @@ struct EventRelation } }; template <> -struct JsonObjectConverter -{ +struct JsonObjectConverter { static void dumpTo(QJsonObject& jo, const EventRelation& pod); static void fillFrom(const QJsonObject& jo, EventRelation& pod); }; -class ReactionEvent : public RoomEvent -{ +class ReactionEvent : public RoomEvent { public: DEFINE_EVENT_TYPEID("m.reaction", ReactionEvent) @@ -63,9 +59,7 @@ public: : RoomEvent(typeId(), matrixTypeId(), { { QStringLiteral("m.relates_to"), toJson(value) } }) {} - explicit ReactionEvent(const QJsonObject& obj) - : RoomEvent(typeId(), obj) - {} + explicit ReactionEvent(const QJsonObject& obj) : RoomEvent(typeId(), obj) {} EventRelation relation() const { return content(QStringLiteral("m.relates_to")); diff --git a/lib/events/receiptevent.cpp b/lib/events/receiptevent.cpp index fcb8431b..4a54b744 100644 --- a/lib/events/receiptevent.cpp +++ b/lib/events/receiptevent.cpp @@ -40,8 +40,7 @@ Example of a Receipt Event: using namespace QMatrixClient; -ReceiptEvent::ReceiptEvent(const QJsonObject& obj) - : Event(typeId(), obj) +ReceiptEvent::ReceiptEvent(const QJsonObject& obj) : Event(typeId(), obj) { const auto& contents = contentJson(); _eventsWithReceipts.reserve(contents.size()); diff --git a/lib/events/receiptevent.h b/lib/events/receiptevent.h index e8396670..c32e0543 100644 --- a/lib/events/receiptevent.h +++ b/lib/events/receiptevent.h @@ -23,22 +23,18 @@ #include #include -namespace QMatrixClient -{ -struct Receipt -{ +namespace QMatrixClient { +struct Receipt { QString userId; QDateTime timestamp; }; -struct ReceiptsForEvent -{ +struct ReceiptsForEvent { QString evtId; QVector receipts; }; using EventsWithReceipts = QVector; -class ReceiptEvent : public Event -{ +class ReceiptEvent : public Event { public: DEFINE_EVENT_TYPEID("m.receipt", ReceiptEvent) explicit ReceiptEvent(const QJsonObject& obj); diff --git a/lib/events/redactionevent.h b/lib/events/redactionevent.h index a7dd9705..3628fb33 100644 --- a/lib/events/redactionevent.h +++ b/lib/events/redactionevent.h @@ -20,15 +20,12 @@ #include "roomevent.h" -namespace QMatrixClient -{ -class RedactionEvent : public RoomEvent -{ +namespace QMatrixClient { +class RedactionEvent : public RoomEvent { public: DEFINE_EVENT_TYPEID("m.room.redaction", RedactionEvent) - explicit RedactionEvent(const QJsonObject& obj) - : RoomEvent(typeId(), obj) + explicit RedactionEvent(const QJsonObject& obj) : RoomEvent(typeId(), obj) {} QString redactedEvent() const diff --git a/lib/events/roomavatarevent.h b/lib/events/roomavatarevent.h index ee460339..16aeb070 100644 --- a/lib/events/roomavatarevent.h +++ b/lib/events/roomavatarevent.h @@ -21,18 +21,15 @@ #include "eventcontent.h" #include "stateevent.h" -namespace QMatrixClient -{ -class RoomAvatarEvent : public StateEvent -{ +namespace QMatrixClient { +class RoomAvatarEvent : public StateEvent { // It's a bit of an overkill to use a full-fledged ImageContent // because in reality m.room.avatar usually only has a single URL, // without a thumbnail. But The Spec says there be thumbnails, and // we follow The Spec. public: DEFINE_EVENT_TYPEID("m.room.avatar", RoomAvatarEvent) - explicit RoomAvatarEvent(const QJsonObject& obj) - : StateEvent(typeId(), obj) + explicit RoomAvatarEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) {} QUrl url() const { return content().url; } }; diff --git a/lib/events/roomcreateevent.h b/lib/events/roomcreateevent.h index 17b86388..c8ba8c40 100644 --- a/lib/events/roomcreateevent.h +++ b/lib/events/roomcreateevent.h @@ -20,22 +20,17 @@ #include "stateevent.h" -namespace QMatrixClient -{ -class RoomCreateEvent : public StateEventBase -{ +namespace QMatrixClient { +class RoomCreateEvent : public StateEventBase { public: DEFINE_EVENT_TYPEID("m.room.create", RoomCreateEvent) - explicit RoomCreateEvent() - : StateEventBase(typeId(), matrixTypeId()) - {} + explicit RoomCreateEvent() : StateEventBase(typeId(), matrixTypeId()) {} explicit RoomCreateEvent(const QJsonObject& obj) : StateEventBase(typeId(), obj) {} - struct Predecessor - { + struct Predecessor { QString roomId; QString eventId; }; diff --git a/lib/events/roomevent.cpp b/lib/events/roomevent.cpp index fb715473..543640ca 100644 --- a/lib/events/roomevent.cpp +++ b/lib/events/roomevent.cpp @@ -32,8 +32,7 @@ RoomEvent::RoomEvent(Type type, event_mtype_t matrixType, : Event(type, matrixType, contentJson) {} -RoomEvent::RoomEvent(Type type, const QJsonObject& json) - : Event(type, json) +RoomEvent::RoomEvent(Type type, const QJsonObject& json) : Event(type, json) { const auto unsignedData = json[UnsignedKeyL].toObject(); const auto redaction = unsignedData[RedactedCauseKeyL]; diff --git a/lib/events/roomevent.h b/lib/events/roomevent.h index 8edb397c..155d4600 100644 --- a/lib/events/roomevent.h +++ b/lib/events/roomevent.h @@ -22,13 +22,11 @@ #include -namespace QMatrixClient -{ +namespace QMatrixClient { class RedactionEvent; /** This class corresponds to m.room.* events */ -class RoomEvent : public Event -{ +class RoomEvent : public Event { Q_GADGET Q_PROPERTY(QString id READ id) Q_PROPERTY(QDateTime timestamp READ timestamp CONSTANT) @@ -93,8 +91,7 @@ using RoomEventPtr = event_ptr_tt; using RoomEvents = EventsArray; using RoomEventsRange = Range; -class CallEventBase : public RoomEvent -{ +class CallEventBase : public RoomEvent { public: CallEventBase(Type type, event_mtype_t matrixType, const QString& callId, int version, const QJsonObject& contentJson = {}); diff --git a/lib/events/roommemberevent.cpp b/lib/events/roommemberevent.cpp index e6292b73..3cbf6685 100644 --- a/lib/events/roommemberevent.cpp +++ b/lib/events/roommemberevent.cpp @@ -28,11 +28,9 @@ static const std::array membershipStrings = { QStringLiteral("leave"), QStringLiteral("ban") } }; -namespace QMatrixClient -{ +namespace QMatrixClient { template <> -struct JsonConverter -{ +struct JsonConverter { static MembershipType load(const QJsonValue& jv) { const auto& membershipString = jv.toString(); diff --git a/lib/events/roommemberevent.h b/lib/events/roommemberevent.h index c1015df2..59d59e3a 100644 --- a/lib/events/roommemberevent.h +++ b/lib/events/roommemberevent.h @@ -21,13 +21,10 @@ #include "eventcontent.h" #include "stateevent.h" -namespace QMatrixClient -{ -class MemberEventContent : public EventContent::Base -{ +namespace QMatrixClient { +class MemberEventContent : public EventContent::Base { public: - enum MembershipType : size_t - { + enum MembershipType : size_t { Invite = 0, Join, Knock, @@ -36,9 +33,7 @@ public: Undefined }; - explicit MemberEventContent(MembershipType mt = Join) - : membership(mt) - {} + explicit MemberEventContent(MembershipType mt = Join) : membership(mt) {} explicit MemberEventContent(const QJsonObject& json); MembershipType membership; @@ -52,16 +47,14 @@ protected: using MembershipType = MemberEventContent::MembershipType; -class RoomMemberEvent : public StateEvent -{ +class RoomMemberEvent : public StateEvent { Q_GADGET public: DEFINE_EVENT_TYPEID("m.room.member", RoomMemberEvent) using MembershipType = MemberEventContent::MembershipType; - explicit RoomMemberEvent(const QJsonObject& obj) - : StateEvent(typeId(), obj) + explicit RoomMemberEvent(const QJsonObject& obj) : StateEvent(typeId(), obj) {} [[deprecated("Use RoomMemberEvent(userId, contentArgs) " "instead")]] RoomMemberEvent(MemberEventContent&& c) @@ -103,8 +96,7 @@ private: }; template <> -class EventFactory -{ +class EventFactory { public: static event_ptr_tt make(const QJsonObject& json, const QString&) diff --git a/lib/events/roommessageevent.cpp b/lib/events/roommessageevent.cpp index da8d59ca..991931de 100644 --- a/lib/events/roommessageevent.cpp +++ b/lib/events/roommessageevent.cpp @@ -54,8 +54,7 @@ TypedBase* make(const QJsonObject& json) : nullptr; } -struct MsgTypeDesc -{ +struct MsgTypeDesc { QString matrixType; MsgType enumType; TypedBase* (*maker)(const QJsonObject&); @@ -174,8 +173,7 @@ RoomMessageEvent::RoomMessageEvent(const QString& plainBody, {} RoomMessageEvent::RoomMessageEvent(const QJsonObject& obj) - : RoomEvent(typeId(), obj) - , _content(nullptr) + : RoomEvent(typeId(), obj), _content(nullptr) { if (isRedacted()) return; @@ -281,8 +279,7 @@ TextContent::TextContent(const QString& text, const QString& contentType, mimeType = QMimeDatabase().mimeTypeForName("text/html"); } -namespace QMatrixClient -{ +namespace QMatrixClient { // Overload the default fromJson<> logic that defined in converters.h // as we want template <> @@ -350,8 +347,7 @@ void TextContent::fillJson(QJsonObject* json) const LocationContent::LocationContent(const QString& geoUri, const Thumbnail& thumbnail) - : geoUri(geoUri) - , thumbnail(thumbnail) + : geoUri(geoUri), thumbnail(thumbnail) {} LocationContent::LocationContent(const QJsonObject& json) diff --git a/lib/events/roommessageevent.h b/lib/events/roommessageevent.h index 1f1fde41..c7a5cb47 100644 --- a/lib/events/roommessageevent.h +++ b/lib/events/roommessageevent.h @@ -23,15 +23,13 @@ class QFileInfo; -namespace QMatrixClient -{ +namespace QMatrixClient { namespace MessageEventContent = EventContent; // Back-compatibility /** * The event class corresponding to m.room.message events */ -class RoomMessageEvent : public RoomEvent -{ +class RoomMessageEvent : public RoomEvent { Q_GADGET Q_PROPERTY(QString msgType READ rawMsgtype CONSTANT) Q_PROPERTY(QString plainBody READ plainBody CONSTANT) @@ -40,8 +38,7 @@ class RoomMessageEvent : public RoomEvent public: DEFINE_EVENT_TYPEID("m.room.message", RoomMessageEvent) - enum class MsgType - { + enum class MsgType { Text, Emote, Notice, @@ -96,12 +93,10 @@ REGISTER_EVENT_TYPE(RoomMessageEvent) DEFINE_EVENTTYPE_ALIAS(RoomMessage, RoomMessageEvent) using MessageEventType = RoomMessageEvent::MsgType; -namespace EventContent -{ +namespace EventContent { // Additional event content types - struct RelatesTo - { + struct RelatesTo { static constexpr const char* ReplyTypeId() { return "m.in_reply_to"; } static constexpr const char* ReplacementTypeId() { return "m.replace"; } QString type; // The only supported relation so far @@ -118,8 +113,7 @@ namespace EventContent * Available fields: mimeType, body. The body can be either rich text * or plain text, depending on what mimeType specifies. */ - class TextContent : public TypedBase - { + class TextContent : public TypedBase { public: TextContent(const QString& text, const QString& contentType, Omittable relatesTo = none); @@ -148,8 +142,7 @@ namespace EventContent * - thumbnail.mimeType * - thumbnail.imageSize */ - class LocationContent : public TypedBase - { + class LocationContent : public TypedBase { public: LocationContent(const QString& geoUri, const Thumbnail& thumbnail = {}); explicit LocationContent(const QJsonObject& json); @@ -168,8 +161,7 @@ namespace EventContent * A base class for info types that include duration: audio and video */ template - class PlayableContent : public ContentT - { + class PlayableContent : public ContentT { public: using ContentT::ContentT; PlayableContent(const QJsonObject& json) diff --git a/lib/events/roomtombstoneevent.h b/lib/events/roomtombstoneevent.h index aa9cb766..95fed998 100644 --- a/lib/events/roomtombstoneevent.h +++ b/lib/events/roomtombstoneevent.h @@ -20,16 +20,12 @@ #include "stateevent.h" -namespace QMatrixClient -{ -class RoomTombstoneEvent : public StateEventBase -{ +namespace QMatrixClient { +class RoomTombstoneEvent : public StateEventBase { public: DEFINE_EVENT_TYPEID("m.room.tombstone", RoomTombstoneEvent) - explicit RoomTombstoneEvent() - : StateEventBase(typeId(), matrixTypeId()) - {} + explicit RoomTombstoneEvent() : StateEventBase(typeId(), matrixTypeId()) {} explicit RoomTombstoneEvent(const QJsonObject& obj) : StateEventBase(typeId(), obj) {} diff --git a/lib/events/simplestateevents.h b/lib/events/simplestateevents.h index 0078c44d..6dad8020 100644 --- a/lib/events/simplestateevents.h +++ b/lib/events/simplestateevents.h @@ -20,25 +20,20 @@ #include "stateevent.h" -namespace QMatrixClient -{ -namespace EventContent -{ +namespace QMatrixClient { +namespace EventContent { template - class SimpleContent - { + class SimpleContent { public: using value_type = T; // The constructor is templated to enable perfect forwarding template SimpleContent(QString keyName, TT&& value) - : value(std::forward(value)) - , key(std::move(keyName)) + : value(std::forward(value)), key(std::move(keyName)) {} SimpleContent(const QJsonObject& json, QString keyName) - : value(fromJson(json[keyName])) - , key(std::move(keyName)) + : value(fromJson(json[keyName])), key(std::move(keyName)) {} QJsonObject toJson() const { @@ -54,14 +49,11 @@ namespace EventContent } // namespace EventContent #define DEFINE_SIMPLE_STATE_EVENT(_Name, _TypeId, _ValueType, _ContentKey) \ - class _Name : public StateEvent> \ - { \ + class _Name : public StateEvent> { \ public: \ using value_type = content_type::value_type; \ DEFINE_EVENT_TYPEID(_TypeId, _Name) \ - explicit _Name() \ - : _Name(value_type()) \ - {} \ + explicit _Name() : _Name(value_type()) {} \ template \ explicit _Name(T&& value) \ : StateEvent(typeId(), matrixTypeId(), QString(), \ @@ -86,8 +78,7 @@ DEFINE_EVENTTYPE_ALIAS(RoomTopic, RoomTopicEvent) DEFINE_EVENTTYPE_ALIAS(RoomEncryption, EncryptionEvent) class RoomAliasesEvent - : public StateEvent> -{ + : public StateEvent> { public: DEFINE_EVENT_TYPEID("m.room.aliases", RoomAliasesEvent) explicit RoomAliasesEvent(const QJsonObject& obj) diff --git a/lib/events/stateevent.h b/lib/events/stateevent.h index d1b742ba..757c94ee 100644 --- a/lib/events/stateevent.h +++ b/lib/events/stateevent.h @@ -20,8 +20,7 @@ #include "roomevent.h" -namespace QMatrixClient -{ +namespace QMatrixClient { /// Make a minimal correct Matrix state event JSON template @@ -34,13 +33,11 @@ inline QJsonObject basicStateEventJson(StrT matrixType, { ContentKey, content } }; } -class StateEventBase : public RoomEvent -{ +class StateEventBase : public RoomEvent { public: using factory_t = EventFactory; - StateEventBase(Type type, const QJsonObject& json) - : RoomEvent(type, json) + StateEventBase(Type type, const QJsonObject& json) : RoomEvent(type, json) {} StateEventBase(Type type, event_mtype_t matrixType, const QString& stateKey = {}, @@ -71,8 +68,7 @@ inline bool is(const Event& e) using StateEventKey = QPair; template -struct Prev -{ +struct Prev { template explicit Prev(const QJsonObject& unsignedJson, ContentParamTs&&... contentParams) @@ -86,8 +82,7 @@ struct Prev }; template -class StateEvent : public StateEventBase -{ +class StateEvent : public StateEventBase { public: using content_type = ContentT; @@ -135,11 +130,9 @@ private: }; } // namespace QMatrixClient -namespace std -{ +namespace std { template <> -struct hash -{ +struct hash { size_t operator()(const QMatrixClient::StateEventKey& k) const Q_DECL_NOEXCEPT { return qHash(k); diff --git a/lib/events/typingevent.cpp b/lib/events/typingevent.cpp index 128a206a..ee3d6b67 100644 --- a/lib/events/typingevent.cpp +++ b/lib/events/typingevent.cpp @@ -22,8 +22,7 @@ using namespace QMatrixClient; -TypingEvent::TypingEvent(const QJsonObject& obj) - : Event(typeId(), obj) +TypingEvent::TypingEvent(const QJsonObject& obj) : Event(typeId(), obj) { const auto& array = contentJson()["user_ids"_ls].toArray(); for (const auto& user : array) diff --git a/lib/events/typingevent.h b/lib/events/typingevent.h index 241359b4..c8170865 100644 --- a/lib/events/typingevent.h +++ b/lib/events/typingevent.h @@ -20,10 +20,8 @@ #include "event.h" -namespace QMatrixClient -{ -class TypingEvent : public Event -{ +namespace QMatrixClient { +class TypingEvent : public Event { public: DEFINE_EVENT_TYPEID("m.typing", TypingEvent) diff --git a/lib/jobs/basejob.cpp b/lib/jobs/basejob.cpp index e4a74954..a6471ece 100644 --- a/lib/jobs/basejob.cpp +++ b/lib/jobs/basejob.cpp @@ -32,8 +32,7 @@ using namespace QMatrixClient; -struct NetworkReplyDeleter : public QScopedPointerDeleteLater -{ +struct NetworkReplyDeleter : public QScopedPointerDeleteLater { static inline void cleanup(QNetworkReply* reply) { if (reply && reply->isRunning()) @@ -42,8 +41,7 @@ struct NetworkReplyDeleter : public QScopedPointerDeleteLater } }; -class BaseJob::Private -{ +class BaseJob::Private { public: // Using an idiom from clang-tidy: // http://clang.llvm.org/extra/clang-tidy/checks/modernize-pass-by-value.html diff --git a/lib/jobs/basejob.h b/lib/jobs/basejob.h index f445d087..c85d2d90 100644 --- a/lib/jobs/basejob.h +++ b/lib/jobs/basejob.h @@ -28,32 +28,22 @@ class QNetworkReply; class QSslError; -namespace QMatrixClient -{ +namespace QMatrixClient { class ConnectionData; -enum class HttpVerb -{ - Get, - Put, - Post, - Delete -}; +enum class HttpVerb { Get, Put, Post, Delete }; -struct JobTimeoutConfig -{ +struct JobTimeoutConfig { int jobTimeout; int nextRetryInterval; }; -class BaseJob : public QObject -{ +class BaseJob : public QObject { Q_OBJECT Q_PROPERTY(QUrl requestUrl READ requestUrl CONSTANT) Q_PROPERTY(int maxRetries READ maxRetries WRITE setMaxRetries) public: - enum StatusCode - { + enum StatusCode { NoError = 0 // To be compatible with Qt conventions , Success = 0, @@ -93,8 +83,7 @@ public: * A simple wrapper around QUrlQuery that allows its creation from * a list of string pairs */ - class Query : public QUrlQuery - { + class Query : public QUrlQuery { public: using QUrlQuery::QUrlQuery; Query() = default; @@ -115,16 +104,10 @@ public: * along the lines of StatusCode, with additional values * starting at UserDefinedError */ - class Status - { + class Status { public: - Status(StatusCode c) - : code(c) - {} - Status(int c, QString m) - : code(c) - , message(std::move(m)) - {} + Status(StatusCode c) : code(c) {} + Status(int c, QString m) : code(c), message(std::move(m)) {} bool good() const { return code < ErrorLevel; } friend QDebug operator<<(QDebug dbg, const Status& s) diff --git a/lib/jobs/downloadfilejob.cpp b/lib/jobs/downloadfilejob.cpp index 3dff5a68..9722186c 100644 --- a/lib/jobs/downloadfilejob.cpp +++ b/lib/jobs/downloadfilejob.cpp @@ -6,12 +6,9 @@ using namespace QMatrixClient; -class DownloadFileJob::Private -{ +class DownloadFileJob::Private { public: - Private() - : tempFile(new QTemporaryFile()) - {} + Private() : tempFile(new QTemporaryFile()) {} explicit Private(const QString& localFilename) : targetFile(new QFile(localFilename)) diff --git a/lib/jobs/downloadfilejob.h b/lib/jobs/downloadfilejob.h index 58858448..ebfe5a0d 100644 --- a/lib/jobs/downloadfilejob.h +++ b/lib/jobs/downloadfilejob.h @@ -2,15 +2,10 @@ #include "csapi/content-repo.h" -namespace QMatrixClient -{ -class DownloadFileJob : public GetContentJob -{ +namespace QMatrixClient { +class DownloadFileJob : public GetContentJob { public: - enum - { - FileError = BaseJob::UserDefinedError + 1 - }; + enum { FileError = BaseJob::UserDefinedError + 1 }; using GetContentJob::makeRequestUrl; static QUrl makeRequestUrl(QUrl baseUrl, const QUrl& mxcUri); diff --git a/lib/jobs/mediathumbnailjob.h b/lib/jobs/mediathumbnailjob.h index eeabe7a9..df0a7f31 100644 --- a/lib/jobs/mediathumbnailjob.h +++ b/lib/jobs/mediathumbnailjob.h @@ -22,10 +22,8 @@ #include -namespace QMatrixClient -{ -class MediaThumbnailJob : public GetContentThumbnailJob -{ +namespace QMatrixClient { +class MediaThumbnailJob : public GetContentThumbnailJob { public: using GetContentThumbnailJob::makeRequestUrl; static QUrl makeRequestUrl(QUrl baseUrl, const QUrl& mxcUri, diff --git a/lib/jobs/postreadmarkersjob.h b/lib/jobs/postreadmarkersjob.h index d53ae66c..cf482a9a 100644 --- a/lib/jobs/postreadmarkersjob.h +++ b/lib/jobs/postreadmarkersjob.h @@ -24,8 +24,7 @@ using namespace QMatrixClient; -class PostReadMarkersJob : public BaseJob -{ +class PostReadMarkersJob : public BaseJob { public: explicit PostReadMarkersJob(const QString& roomId, const QString& readUpToEventId) diff --git a/lib/jobs/requestdata.cpp b/lib/jobs/requestdata.cpp index 8248d6b1..6ad7c007 100644 --- a/lib/jobs/requestdata.cpp +++ b/lib/jobs/requestdata.cpp @@ -23,16 +23,10 @@ inline auto fromJson(const JsonDataT& jdata) return fromData(QJsonDocument(jdata).toJson(QJsonDocument::Compact)); } -RequestData::RequestData(const QByteArray& a) - : _source(fromData(a)) -{} +RequestData::RequestData(const QByteArray& a) : _source(fromData(a)) {} -RequestData::RequestData(const QJsonObject& jo) - : _source(fromJson(jo)) -{} +RequestData::RequestData(const QJsonObject& jo) : _source(fromJson(jo)) {} -RequestData::RequestData(const QJsonArray& ja) - : _source(fromJson(ja)) -{} +RequestData::RequestData(const QJsonArray& ja) : _source(fromJson(ja)) {} RequestData::~RequestData() = default; diff --git a/lib/jobs/requestdata.h b/lib/jobs/requestdata.h index 974a9ddf..55987a3b 100644 --- a/lib/jobs/requestdata.h +++ b/lib/jobs/requestdata.h @@ -26,23 +26,20 @@ class QJsonArray; class QJsonDocument; class QIODevice; -namespace QMatrixClient -{ +namespace QMatrixClient { /** * A simple wrapper that represents the request body. * Provides a unified interface to dump an unstructured byte stream * as well as JSON (and possibly other structures in the future) to * a QByteArray consumed by QNetworkAccessManager request methods. */ -class RequestData -{ +class RequestData { public: RequestData() = default; RequestData(const QByteArray& a); RequestData(const QJsonObject& jo); RequestData(const QJsonArray& ja); - RequestData(QIODevice* source) - : _source(std::unique_ptr(source)) + RequestData(QIODevice* source) : _source(std::unique_ptr(source)) {} RequestData(const RequestData&) = delete; RequestData& operator=(const RequestData&) = delete; diff --git a/lib/jobs/syncjob.h b/lib/jobs/syncjob.h index e2cec8f7..8f925414 100644 --- a/lib/jobs/syncjob.h +++ b/lib/jobs/syncjob.h @@ -22,10 +22,8 @@ #include "../syncdata.h" #include "basejob.h" -namespace QMatrixClient -{ -class SyncJob : public BaseJob -{ +namespace QMatrixClient { +class SyncJob : public BaseJob { public: explicit SyncJob(const QString& since = {}, const QString& filter = {}, int timeout = -1, const QString& presence = {}); diff --git a/lib/joinstate.h b/lib/joinstate.h index e4dc679a..fcf840ae 100644 --- a/lib/joinstate.h +++ b/lib/joinstate.h @@ -22,10 +22,8 @@ #include -namespace QMatrixClient -{ -enum class JoinState : unsigned int -{ +namespace QMatrixClient { +enum class JoinState : unsigned int { Join = 0x1, Invite = 0x2, Leave = 0x4, diff --git a/lib/logging.h b/lib/logging.h index a50c1795..24799752 100644 --- a/lib/logging.h +++ b/lib/logging.h @@ -28,8 +28,7 @@ Q_DECLARE_LOGGING_CATEGORY(EPHEMERAL) Q_DECLARE_LOGGING_CATEGORY(JOBS) Q_DECLARE_LOGGING_CATEGORY(SYNCJOB) -namespace QMatrixClient -{ +namespace QMatrixClient { // QDebug manipulators using QDebugManip = QDebug (*)(QDebug); diff --git a/lib/networkaccessmanager.cpp b/lib/networkaccessmanager.cpp index 9ac589b8..7bff654c 100644 --- a/lib/networkaccessmanager.cpp +++ b/lib/networkaccessmanager.cpp @@ -23,15 +23,13 @@ using namespace QMatrixClient; -class NetworkAccessManager::Private -{ +class NetworkAccessManager::Private { public: QList ignoredSslErrors; }; NetworkAccessManager::NetworkAccessManager(QObject* parent) - : QNetworkAccessManager(parent) - , d(std::make_unique()) + : QNetworkAccessManager(parent), d(std::make_unique()) {} QList NetworkAccessManager::ignoredSslErrors() const diff --git a/lib/networkaccessmanager.h b/lib/networkaccessmanager.h index bf8f0cbc..dfa388f0 100644 --- a/lib/networkaccessmanager.h +++ b/lib/networkaccessmanager.h @@ -22,10 +22,8 @@ #include -namespace QMatrixClient -{ -class NetworkAccessManager : public QNetworkAccessManager -{ +namespace QMatrixClient { +class NetworkAccessManager : public QNetworkAccessManager { Q_OBJECT public: NetworkAccessManager(QObject* parent = nullptr); diff --git a/lib/networksettings.h b/lib/networksettings.h index 0c21a9fe..75bf726d 100644 --- a/lib/networksettings.h +++ b/lib/networksettings.h @@ -24,10 +24,8 @@ Q_DECLARE_METATYPE(QNetworkProxy::ProxyType) -namespace QMatrixClient -{ -class NetworkSettings : public SettingsGroup -{ +namespace QMatrixClient { +class NetworkSettings : public SettingsGroup { Q_OBJECT QMC_DECLARE_SETTING(QNetworkProxy::ProxyType, proxyType, setProxyType) QMC_DECLARE_SETTING(QString, proxyHostName, setProxyHostName) diff --git a/lib/qt_connection_util.h b/lib/qt_connection_util.h index 1b3229d4..94c1ec60 100644 --- a/lib/qt_connection_util.h +++ b/lib/qt_connection_util.h @@ -22,10 +22,8 @@ #include -namespace QMatrixClient -{ -namespace _impl -{ +namespace QMatrixClient { +namespace _impl { template inline QMetaObject::Connection connectUntil(SenderT* sender, SignalT signal, ContextT* context, @@ -86,12 +84,10 @@ inline auto connectSingleShot(SenderT* sender, SignalT signal, * destruction. */ template -class ConnectionsGuard : public QPointer -{ +class ConnectionsGuard : public QPointer { public: ConnectionsGuard(T* publisher, QObject* subscriber) - : QPointer(publisher) - , subscriber(subscriber) + : QPointer(publisher), subscriber(subscriber) {} ~ConnectionsGuard() { diff --git a/lib/room.cpp b/lib/room.cpp index cf58f3c0..b32d3492 100644 --- a/lib/room.cpp +++ b/lib/room.cpp @@ -78,24 +78,16 @@ using std::move; using std::llround; #endif -enum EventsPlacement : int -{ - Older = -1, - Newer = 1 -}; +enum EventsPlacement : int { Older = -1, Newer = 1 }; -class Room::Private -{ +class Room::Private { public: /// Map of user names to users /** User names potentially duplicate, hence QMultiHash. */ using members_map_t = QMultiHash; Private(Connection* c, QString id_, JoinState initialJoinState) - : q(nullptr) - , connection(c) - , id(move(id_)) - , joinState(initialJoinState) + : q(nullptr), connection(c), id(move(id_)), joinState(initialJoinState) {} Room* q; @@ -144,8 +136,7 @@ public: QPointer eventsHistoryJob; QPointer allMembersJob; - struct FileTransferPrivateInfo - { + struct FileTransferPrivateInfo { FileTransferPrivateInfo() = default; FileTransferPrivateInfo(BaseJob* j, const QString& fileName, bool isUploading = false) @@ -354,8 +345,7 @@ private: decltype(Room::Private::baseState) Room::Private::stubbedState {}; Room::Room(Connection* connection, QString id, JoinState initialJoinState) - : QObject(connection) - , d(new Private(connection, id, initialJoinState)) + : QObject(connection), d(new Private(connection, id, initialJoinState)) { setObjectName(id); // See "Accessing the Public Class" section in @@ -1617,9 +1607,9 @@ QString Room::postFile(const QString& plainText, const QUrl& localPath, // Normally in this situation we should instruct // the media server to delete the file; alas, there's no // API specced for that. - qCWarning(MAIN) - << "File uploaded to" << mxcUri - << "but the event referring to it was cancelled"; + qCWarning(MAIN) << "File uploaded to" << mxcUri + << "but the event referring to it was " + "cancelled"; } context->deleteLater(); } @@ -2382,9 +2372,9 @@ Room::Changes Room::processStateEvent(const RoomEvent& e) break; case MembershipType::Join: if (evt.membership() == MembershipType::Invite) - qCWarning(MAIN) - << "Invalid membership change from Join to Invite:" - << evt; + qCWarning(MAIN) << "Invalid membership change from " + "Join to Invite:" + << evt; if (evt.membership() != prevMembership) { disconnect(u, &User::nameAboutToChange, this, nullptr); disconnect(u, &User::nameChanged, this, nullptr); @@ -2564,7 +2554,8 @@ Room::Private::buildShortlist(const ContT& users) const std::partial_sort_copy( users.begin(), users.end(), shortlist.begin(), shortlist.end(), [this](const User* u1, const User* u2) { - // localUser(), if it's in the list, is sorted below all others + // localUser(), if it's in the list, is sorted + // below all others return isLocalUser(u2) || (!isLocalUser(u1) && u1->id() < u2->id()); }); return shortlist; diff --git a/lib/room.h b/lib/room.h index f5433fb6..d6fb8a61 100644 --- a/lib/room.h +++ b/lib/room.h @@ -35,8 +35,7 @@ #include #include -namespace QMatrixClient -{ +namespace QMatrixClient { class Event; class Avatar; class SyncRoomData; @@ -52,8 +51,7 @@ class RedactEventJob; * This is specifically tuned to work with QML exposing all traits as * Q_PROPERTY values. */ -class FileTransferInfo -{ +class FileTransferInfo { Q_GADGET Q_PROPERTY(bool isUpload MEMBER isUpload CONSTANT) Q_PROPERTY(bool active READ active CONSTANT) @@ -65,14 +63,7 @@ class FileTransferInfo Q_PROPERTY(QUrl localDir MEMBER localDir CONSTANT) Q_PROPERTY(QUrl localPath MEMBER localPath CONSTANT) public: - enum Status - { - None, - Started, - Completed, - Failed, - Cancelled - }; + enum Status { None, Started, Completed, Failed, Cancelled }; Status status = None; bool isUpload = false; int progress = 0; @@ -86,8 +77,7 @@ public: bool failed() const { return status == Failed; } }; -class Room : public QObject -{ +class Room : public QObject { Q_OBJECT Q_PROPERTY(Connection* connection READ connection CONSTANT) Q_PROPERTY(User* localUser READ localUser CONSTANT) @@ -146,8 +136,7 @@ public: using rev_iter_t = Timeline::const_reverse_iterator; using timeline_iter_t = Timeline::const_iterator; - enum Change : uint - { + enum Change : uint { NoChange = 0x0, NameChange = 0x1, CanonicalAliasChange = 0x2, @@ -663,12 +652,9 @@ private: void setJoinState(JoinState state); }; -class MemberSorter -{ +class MemberSorter { public: - explicit MemberSorter(const Room* r) - : room(r) - {} + explicit MemberSorter(const Room* r) : room(r) {} bool operator()(User* u1, User* u2) const; bool operator()(User* u1, const QString& u2name) const; diff --git a/lib/settings.h b/lib/settings.h index e1ca0866..6747631e 100644 --- a/lib/settings.h +++ b/lib/settings.h @@ -24,10 +24,8 @@ class QVariant; -namespace QMatrixClient -{ -class Settings : public QSettings -{ +namespace QMatrixClient { +class Settings : public QSettings { Q_OBJECT public: /** @@ -42,9 +40,7 @@ public: #if defined(_MSC_VER) && _MSC_VER < 1900 // VS 2013 (and probably older) aren't friends with 'using' statements // that involve private constructors - explicit Settings(QObject* parent = 0) - : QSettings(parent) - {} + explicit Settings(QObject* parent = 0) : QSettings(parent) {} #else using QSettings::QSettings; #endif @@ -71,8 +67,7 @@ protected: QSettings legacySettings { legacyOrganizationName, legacyApplicationName }; }; -class SettingsGroup : public Settings -{ +class SettingsGroup : public Settings { public: template explicit SettingsGroup(QString path, ArgTs&&... qsettingsArgs) @@ -121,8 +116,7 @@ private: setValue(QStringLiteral(qsettingname), std::move(newValue)); \ } -class AccountSettings : public SettingsGroup -{ +class AccountSettings : public SettingsGroup { Q_OBJECT Q_PROPERTY(QString userId READ userId CONSTANT) QMC_DECLARE_SETTING(QString, deviceId, setDeviceId) diff --git a/lib/syncdata.h b/lib/syncdata.h index 6932878d..ad9902e4 100644 --- a/lib/syncdata.h +++ b/lib/syncdata.h @@ -22,8 +22,7 @@ #include "events/stateevent.h" -namespace QMatrixClient -{ +namespace QMatrixClient { /// Room summary, as defined in MSC688 /** * Every member of this structure is an Omittable; as per the MSC, only @@ -32,8 +31,7 @@ namespace QMatrixClient * means that nothing has come from the server; heroes.value().isEmpty() * means a peculiar case of a room with the only member - the current user. */ -struct RoomSummary -{ +struct RoomSummary { Omittable joinedMemberCount; Omittable invitedMemberCount; Omittable heroes; //< mxids of users to take part in the room @@ -48,14 +46,12 @@ struct RoomSummary }; template <> -struct JsonObjectConverter -{ +struct JsonObjectConverter { static void dumpTo(QJsonObject& jo, const RoomSummary& rs); static void fillFrom(const QJsonObject& jo, RoomSummary& rs); }; -class SyncRoomData -{ +class SyncRoomData { public: QString roomId; JoinState joinState; @@ -82,8 +78,7 @@ public: // QVector cannot work with non-copiable objects, std::vector can. using SyncDataList = std::vector; -class SyncData -{ +class SyncData { public: SyncData() = default; explicit SyncData(const QString& cacheFileName); diff --git a/lib/user.cpp b/lib/user.cpp index f0216454..0705aee7 100644 --- a/lib/user.cpp +++ b/lib/user.cpp @@ -41,8 +41,7 @@ using namespace QMatrixClient; using namespace std::placeholders; using std::move; -class User::Private -{ +class User::Private { public: static Avatar makeAvatar(QUrl url) { return Avatar(move(url)); } @@ -184,8 +183,7 @@ void User::Private::setAvatarForRoom(const Room* r, const QUrl& newUrl, } User::User(QString userId, Connection* connection) - : QObject(connection) - , d(new Private(move(userId), connection)) + : QObject(connection), d(new Private(move(userId), connection)) { setObjectName(userId); } diff --git a/lib/user.h b/lib/user.h index f4d7cff3..779efb34 100644 --- a/lib/user.h +++ b/lib/user.h @@ -23,14 +23,12 @@ #include #include -namespace QMatrixClient -{ +namespace QMatrixClient { class Connection; class Room; class RoomMemberEvent; -class User : public QObject -{ +class User : public QObject { Q_OBJECT Q_PROPERTY(QString id READ id CONSTANT) Q_PROPERTY(bool isGuest READ isGuest CONSTANT) diff --git a/lib/util.cpp b/lib/util.cpp index 9e0807c6..1919e811 100644 --- a/lib/util.cpp +++ b/lib/util.cpp @@ -124,7 +124,8 @@ QString QMatrixClient::serverPart(const QString& mxId) % ServerPartRegEx % ")$"; static QRegularExpression parser( re, - QRegularExpression::UseUnicodePropertiesOption); // Because Asian digits + QRegularExpression::UseUnicodePropertiesOption); // Because Asian + // digits return parser.match(mxId).captured(1); } @@ -148,16 +149,14 @@ void f2(int, QString); static_assert(std::is_same, QString>::value, "Test fn_arg_t<>"); -struct S -{ +struct S { int mf(); }; static_assert(is_callable_v, "Test member function"); static_assert(returns(), "Test returns<> with member function"); -struct Fo -{ +struct Fo { int operator()(); }; static_assert(is_callable_v, "Test is_callable<> with function object"); @@ -165,8 +164,7 @@ static_assert(function_traits::arg_number == 0, "Test function object"); static_assert(std::is_same, int>::value, "Test return type of function object"); -struct Fo1 -{ +struct Fo1 { void operator()(int); }; static_assert(function_traits::arg_number == 1, "Test function object 1"); @@ -182,13 +180,11 @@ static_assert(std::is_same, int>::value, #endif template -struct fn_object -{ +struct fn_object { static int smf(double) { return 0; } }; template <> -struct fn_object -{ +struct fn_object { void operator()(QString); }; static_assert(is_callable_v>, "Test function object"); diff --git a/lib/util.h b/lib/util.h index a29f6253..d055fa46 100644 --- a/lib/util.h +++ b/lib/util.h @@ -63,8 +63,7 @@ static void qAsConst(const T&&) Q_DECL_EQ_DELETE; # define BROKEN_INITIALIZER_LISTS #endif -namespace QMatrixClient -{ +namespace QMatrixClient { // The below enables pretty-printing of enums in logs #if (QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)) # define REGISTER_ENUM(EnumName) Q_ENUM(EnumName) @@ -88,8 +87,7 @@ inline auto unique_ptr_cast(PtrT2&& p) return std::unique_ptr(static_cast(p.release())); } -struct NoneTag -{}; +struct NoneTag {}; constexpr NoneTag none {}; /** A crude substitute for `optional` while we're not C++17 @@ -97,27 +95,17 @@ constexpr NoneTag none {}; * Only works with default-constructible types. */ template -class Omittable -{ +class Omittable { static_assert(!std::is_reference::value, "You cannot make an Omittable<> with a reference type"); public: using value_type = std::decay_t; - explicit Omittable() - : Omittable(none) - {} - Omittable(NoneTag) - : _value(value_type()) - , _omitted(true) - {} - Omittable(const value_type& val) - : _value(val) - {} - Omittable(value_type&& val) - : _value(std::move(val)) - {} + explicit Omittable() : Omittable(none) {} + Omittable(NoneTag) : _value(value_type()), _omitted(true) {} + Omittable(const value_type& val) : _value(val) {} + Omittable(value_type&& val) : _value(std::move(val)) {} Omittable& operator=(const value_type& val) { _value = val; @@ -192,8 +180,7 @@ private: bool _omitted = false; }; -namespace _impl -{ +namespace _impl { template struct fn_traits; } @@ -205,13 +192,11 @@ namespace _impl * https://stackoverflow.com/questions/7943525/is-it-possible-to-figure-out-the-parameter-type-and-return-type-of-a-lambda#7943765 */ template -struct function_traits : public _impl::fn_traits -{}; +struct function_traits : public _impl::fn_traits {}; // Specialisation for a function template -struct function_traits -{ +struct function_traits { static constexpr auto is_callable = true; using return_type = ReturnT; using arg_types = std::tuple; @@ -219,30 +204,26 @@ struct function_traits static constexpr auto arg_number = std::tuple_size::value; }; -namespace _impl -{ +namespace _impl { template - struct fn_traits - { + struct fn_traits { static constexpr auto is_callable = false; }; template struct fn_traits - : public fn_traits - {}; // A generic function object that has (non-overloaded) operator() + : public fn_traits { + }; // A generic function object that has (non-overloaded) operator() // Specialisation for a member function template struct fn_traits - : function_traits - {}; + : function_traits {}; // Specialisation for a const member function template struct fn_traits - : function_traits - {}; + : function_traits {}; } // namespace _impl template @@ -272,22 +253,15 @@ inline auto operator"" _ls(const char* s, std::size_t size) * are at least ForwardIterators. Inspired by Ranges TS. */ template -class Range -{ +class Range { // Looking forward for Ranges TS to produce something (in C++23?..) using iterator = typename ArrayT::iterator; using const_iterator = typename ArrayT::const_iterator; using size_type = typename ArrayT::size_type; public: - Range(ArrayT& arr) - : from(std::begin(arr)) - , to(std::end(arr)) - {} - Range(iterator from, iterator to) - : from(from) - , to(to) - {} + Range(ArrayT& arr) : from(std::begin(arr)), to(std::end(arr)) {} + Range(iterator from, iterator to) : from(from), to(to) {} size_type size() const { -- cgit v1.2.3