From 1fad9398fce58a8d7bf96bdaa2629a80b336b14c Mon Sep 17 00:00:00 2001 From: Konstantinos Sideris Date: Wed, 24 Jan 2018 20:46:37 +0200 Subject: [PATCH] Use more stl containers & minor refactorings --- include/AvatarProvider.h | 4 +- include/Cache.h | 5 +- include/ChatPage.h | 14 +- include/CommunitiesList.h | 25 ++-- include/Community.h | 42 +----- include/QuickSwitcher.h | 4 +- include/RoomList.h | 26 ++-- include/timeline/TimelineViewManager.h | 12 +- src/AvatarProvider.cc | 24 ++-- src/Cache.cc | 10 +- src/ChatPage.cc | 170 +++++++++++++------------ src/CommunitiesList.cc | 50 +++----- src/Community.cc | 25 ++-- src/QuickSwitcher.cc | 9 +- src/RoomList.cc | 162 +++++++++++------------ src/timeline/TimelineViewManager.cc | 40 +++--- 16 files changed, 293 insertions(+), 329 deletions(-) diff --git a/include/AvatarProvider.h b/include/AvatarProvider.h index 77f9ebb..f344129 100644 --- a/include/AvatarProvider.h +++ b/include/AvatarProvider.h @@ -48,6 +48,6 @@ private: static QSharedPointer client_; using UserID = QString; - static QMap avatars_; - static QMap>> toBeResolved_; + static std::map avatars_; + static std::map>> toBeResolved_; }; diff --git a/include/Cache.h b/include/Cache.h index e8d797d..93668b8 100644 --- a/include/Cache.h +++ b/include/Cache.h @@ -18,7 +18,6 @@ #pragma once #include -#include #include #include #include @@ -53,7 +52,7 @@ public: Cache(const QString &userId, QObject *parent = nullptr); void setState(const QString &nextBatchToken, - const QMap> &states); + const std::map> &states); bool isInitialized() const; QString nextBatchToken() const; @@ -90,7 +89,7 @@ public: void saveImage(const QString &url, const QByteArray &data); signals: - void statesLoaded(QMap states); + void statesLoaded(std::map states); private: void setNextBatchToken(lmdb::txn &txn, const QString &token); diff --git a/include/ChatPage.h b/include/ChatPage.h index 3da84b3..3cc6e6c 100644 --- a/include/ChatPage.h +++ b/include/ChatPage.h @@ -95,7 +95,7 @@ private: static ChatPage *instance_; using UserID = QString; - using RoomStates = QMap>; + using RoomStates = std::map>; using Membership = mtx::events::StateEvent; using Memberships = std::map; @@ -105,7 +105,7 @@ private: void removeLeftRooms(const LeftRooms &rooms); void updateJoinedRooms(const JoinedRooms &rooms); - QMap> generateMembershipDifference( + std::map> generateMembershipDifference( const JoinedRooms &rooms, const RoomStates &states) const; @@ -160,18 +160,18 @@ private: QString current_room_; QString current_community_; - QMap room_avatars_; - QMap community_avatars_; + std::map roomAvatars_; + std::map community_avatars_; UserInfoWidget *user_info_widget_; RoomStates roomStates_; - QMap> roomSettings_; + std::map> roomSettings_; - QMap> communityManager_; + std::map> communities_; // Keeps track of the users currently typing on each room. - QMap> typingUsers_; + std::map> typingUsers_; QTimer *typingRefresher_; QSharedPointer quickSwitcher_; diff --git a/include/CommunitiesList.h b/include/CommunitiesList.h index 5371536..8bb6aaa 100644 --- a/include/CommunitiesList.h +++ b/include/CommunitiesList.h @@ -3,7 +3,6 @@ #include #include #include -#include #include "CommunitiesListItem.h" #include "Community.h" @@ -16,27 +15,33 @@ class CommunitiesList : public QWidget public: CommunitiesList(QSharedPointer client, QWidget *parent = nullptr); - ~CommunitiesList(); - void setCommunities(const QMap> &communities); - void clear(); + void setCommunities(const std::map> &communities); + void clear() { communities_.clear(); } + + void addCommunity(QSharedPointer community, const QString &id); + void removeCommunity(const QString &id); - void addCommunity(QSharedPointer community, const QString &community_id); - void removeCommunity(const QString &community_id); signals: - void communityChanged(const QString &community_id); + void communityChanged(const QString &id); public slots: - void updateCommunityAvatar(const QString &community_id, const QPixmap &img); - void highlightSelectedCommunity(const QString &community_id); + void updateCommunityAvatar(const QString &id, const QPixmap &img); + void highlightSelectedCommunity(const QString &id); private: + //! Check whether or not a community id is currently managed. + bool communityExists(const QString &id) + { + return communities_.find(id) != communities_.end(); + } + QVBoxLayout *topLayout_; QVBoxLayout *contentsLayout_; QWidget *scrollAreaContents_; QScrollArea *scrollArea_; - QMap> communities_; + std::map> communities_; QSharedPointer client_; }; diff --git a/include/Community.h b/include/Community.h index 5f3adba..5b759e5 100644 --- a/include/Community.h +++ b/include/Community.h @@ -13,11 +13,11 @@ public: void parseProfile(const QJsonObject &profile); void parseRooms(const QJsonObject &rooms); - inline QUrl getAvatar() const; - inline QString getName() const; - inline QString getShortDescription() const; - inline QString getLongDescription() const; - inline const QList getRoomList() const; + QUrl getAvatar() const { return avatar_; } + QString getName() const { return name_; } + QString getShortDescription() const { return short_description_; } + QString getLongDescription() const { return long_description_; } + std::vector getRoomList() const { return rooms_; } private: QUrl avatar_; @@ -25,35 +25,5 @@ private: QString short_description_; QString long_description_; - QList rooms_; + std::vector rooms_; }; - -inline QUrl -Community::getAvatar() const -{ - return avatar_; -} - -inline QString -Community::getName() const -{ - return name_; -} - -inline QString -Community::getShortDescription() const -{ - return short_description_; -} - -inline QString -Community::getLongDescription() const -{ - return long_description_; -} - -inline const QList -Community::getRoomList() const -{ - return rooms_; -} diff --git a/include/QuickSwitcher.h b/include/QuickSwitcher.h index 5cbd0f1..115161a 100644 --- a/include/QuickSwitcher.h +++ b/include/QuickSwitcher.h @@ -47,7 +47,7 @@ class QuickSwitcher : public QFrame public: explicit QuickSwitcher(QWidget *parent = nullptr); - void setRoomList(const QMap &rooms); + void setRoomList(const std::map &rooms); signals: void closing(); @@ -65,5 +65,5 @@ private: RoomSearchInput *roomSearch_; QCompleter *completer_; - QMap rooms_; + std::map rooms_; }; diff --git a/include/RoomList.h b/include/RoomList.h index 43b95f1..ed93f17 100644 --- a/include/RoomList.h +++ b/include/RoomList.h @@ -17,7 +17,6 @@ #pragma once -#include #include #include #include @@ -50,22 +49,22 @@ public: ~RoomList(); void setCache(QSharedPointer cache) { cache_ = cache; } - void setInitialRooms(const QMap> &settings, - const QMap> &states); - void sync(const QMap> &states, - const QMap> &settings); + void setInitialRooms(const std::map> &settings, + const std::map> &states); + void sync(const std::map> &states, + const std::map> &settings); void syncInvites(const std::map &rooms); void clear(); void updateAvatar(const QString &room_id, const QString &url); - void addRoom(const QMap> &settings, + void addRoom(const QSharedPointer &settings, const QSharedPointer &state, const QString &room_id); void addInvitedRoom(const QString &room_id, const mtx::responses::InvitedRoom &room); void removeRoom(const QString &room_id, bool reset); void setFilterRooms(bool filterRooms); - void setRoomFilter(QList room_ids); + void setRoomFilter(std::vector room_ids); signals: void roomChanged(const QString &room_id); @@ -92,7 +91,14 @@ private slots: void sortRoomsByLastMessage(); private: + //! Return the first non-null room. + std::pair> firstRoom() const; void calculateUnreadMessageCount(); + bool roomExists(const QString &room_id) { return rooms_.find(room_id) != rooms_.end(); } + bool filterItemExists(const QString &id) + { + return std::find(roomFilter_.begin(), roomFilter_.end(), id) != roomFilter_.end(); + } QVBoxLayout *topLayout_; QVBoxLayout *contentsLayout_; @@ -106,11 +112,11 @@ private: QSharedPointer leaveRoomModal_; QSharedPointer leaveRoomDialog_; - QMap> rooms_; + std::map> rooms_; QString selectedRoom_; - bool filterRooms_ = false; - QList roomFilter_ = QList(); // which rooms to include in the room list + //! Which rooms to include in the room list. + std::vector roomFilter_; QSharedPointer client_; QSharedPointer cache_; diff --git a/include/timeline/TimelineViewManager.h b/include/timeline/TimelineViewManager.h index c19031c..81fedfb 100644 --- a/include/timeline/TimelineViewManager.h +++ b/include/timeline/TimelineViewManager.h @@ -17,7 +17,6 @@ #pragma once -#include #include #include @@ -41,13 +40,13 @@ public: // Initialize with timeline events. void initialize(const mtx::responses::Rooms &rooms); // Empty initialization. - void initialize(const QList &rooms); + void initialize(const std::vector &rooms); void addRoom(const mtx::responses::JoinedRoom &room, const QString &room_id); void addRoom(const QString &room_id); void sync(const mtx::responses::Rooms &rooms); - void clearAll(); + void clearAll() { views_.clear(); } // Check if all the timelines have been loaded. bool hasLoaded() const; @@ -55,7 +54,7 @@ public: static QString chooseRandomColor(); static QString displayName(const QString &userid); - static QMap DISPLAY_NAMES; + static std::map DISPLAY_NAMES; signals: void clearRoomMessageCount(QString roomid); @@ -78,7 +77,10 @@ private slots: void messageSendFailed(const QString &roomid, int txnid); private: + //! Check if the given room id is managed by a TimelineView. + bool timelineViewExists(const QString &id) { return views_.find(id) != views_.end(); } + QString active_room_; - QMap> views_; + std::map> views_; QSharedPointer client_; }; diff --git a/src/AvatarProvider.cc b/src/AvatarProvider.cc index 881ef2d..f39d987 100644 --- a/src/AvatarProvider.cc +++ b/src/AvatarProvider.cc @@ -20,8 +20,8 @@ QSharedPointer AvatarProvider::client_; -QMap AvatarProvider::avatars_; -QMap>> AvatarProvider::toBeResolved_; +std::map AvatarProvider::avatars_; +std::map>> AvatarProvider::toBeResolved_; void AvatarProvider::init(QSharedPointer client) @@ -32,26 +32,26 @@ AvatarProvider::init(QSharedPointer client) void AvatarProvider::updateAvatar(const QString &uid, const QImage &img) { - if (toBeResolved_.contains(uid)) { + if (toBeResolved_.find(uid) != toBeResolved_.end()) { auto callbacks = toBeResolved_[uid]; // Update all the timeline items with the resolved avatar. for (const auto callback : callbacks) callback(img); - toBeResolved_.remove(uid); + toBeResolved_.erase(toBeResolved_.find(uid)); } auto avatarData = avatars_[uid]; avatarData.img = img; - avatars_.insert(uid, avatarData); + avatars_.emplace(uid, avatarData); } void AvatarProvider::resolve(const QString &userId, std::function callback) { - if (!avatars_.contains(userId)) + if (avatars_.find(userId) == avatars_.end()) return; auto img = avatars_[userId].img; @@ -62,7 +62,7 @@ AvatarProvider::resolve(const QString &userId, std::function callb } // Add the current timeline item to the waiting list for this avatar. - if (!toBeResolved_.contains(userId)) { + if (toBeResolved_.find(userId) == toBeResolved_.end()) { client_->fetchUserAvatar(avatars_[userId].url, [userId](QImage image) { updateAvatar(userId, image); }, [userId](QString error) { @@ -71,12 +71,12 @@ AvatarProvider::resolve(const QString &userId, std::function callb << userId; }); - QList> items; - items.push_back(callback); + std::vector> items; + items.emplace_back(callback); - toBeResolved_.insert(userId, items); + toBeResolved_.emplace(userId, items); } else { - toBeResolved_[userId].push_back(callback); + toBeResolved_[userId].emplace_back(callback); } } @@ -86,7 +86,7 @@ AvatarProvider::setAvatarUrl(const QString &userId, const QUrl &url) AvatarData data; data.url = url; - avatars_.insert(userId, data); + avatars_.emplace(userId, data); } void diff --git a/src/Cache.cc b/src/Cache.cc index 3217636..d889f73 100644 --- a/src/Cache.cc +++ b/src/Cache.cc @@ -155,7 +155,7 @@ Cache::image(const QString &url) const void Cache::setState(const QString &nextBatchToken, - const QMap> &states) + const std::map> &states) { if (!isMounted_) return; @@ -165,8 +165,8 @@ Cache::setState(const QString &nextBatchToken, setNextBatchToken(txn, nextBatchToken); - for (auto it = states.constBegin(); it != states.constEnd(); ++it) - insertRoomState(txn, it.key(), it.value()); + for (auto const &state : states) + insertRoomState(txn, state.first, state.second); txn.commit(); } catch (const lmdb::error &e) { @@ -252,7 +252,7 @@ Cache::removeInvite(const QString &room_id) void Cache::states() { - QMap states; + std::map states; auto txn = lmdb::txn::begin(env_, nullptr, MDB_RDONLY); auto cursor = lmdb::cursor::open(txn, roomDb_); @@ -293,7 +293,7 @@ Cache::states() qDebug() << members.size() << "members for" << roomid; state.memberships = members; - states.insert(roomid, state); + states.emplace(roomid, std::move(state)); } qDebug() << "Retrieved" << states.size() << "rooms"; diff --git a/src/ChatPage.cc b/src/ChatPage.cc index 225434e..6d9c87f 100644 --- a/src/ChatPage.cc +++ b/src/ChatPage.cc @@ -161,7 +161,7 @@ ChatPage::ChatPage(QSharedPointer client, return; } - if (typingUsers_.contains(roomid)) + if (typingUsers_.find(roomid) != typingUsers_.end()) users = typingUsers_[roomid]; typingDisplay_->setUsers(users); @@ -185,7 +185,7 @@ ChatPage::ChatPage(QSharedPointer client, &TimelineViewManager::unreadMessages, this, [=](const QString &roomid, int count) { - if (!roomSettings_.contains(roomid)) { + if (roomSettings_.find(roomid) == roomSettings_.end()) { qWarning() << "RoomId does not have settings" << roomid; room_list_->updateUnreadMessageCount(roomid, count); return; @@ -331,20 +331,20 @@ ChatPage::ChatPage(QSharedPointer client, &MatrixClient::communityProfileRetrieved, this, [=](QString communityId, QJsonObject profile) { - communityManager_[communityId]->parseProfile(profile); + communities_[communityId]->parseProfile(profile); }); connect(client_.data(), &MatrixClient::communityRoomsRetrieved, this, [=](QString communityId, QJsonObject rooms) { - communityManager_[communityId]->parseRooms(rooms); + communities_[communityId]->parseRooms(rooms); if (communityId == current_community_) { if (communityId == "world") { room_list_->setFilterRooms(false); } else { room_list_->setRoomFilter( - communityManager_[communityId]->getRoomList()); + communities_[communityId]->getRoomList()); } } }); @@ -394,12 +394,11 @@ ChatPage::ChatPage(QSharedPointer client, this, [=](const QString &communityId) { current_community_ = communityId; - if (communityId == "world") { + + if (communityId == "world") room_list_->setFilterRooms(false); - } else { - room_list_->setRoomFilter( - communityManager_[communityId]->getRoomList()); - } + else + room_list_->setRoomFilter(communities_[communityId]->getRoomList()); }); setGroupViewState(userSettings_->isGroupViewEnabled()); @@ -427,7 +426,7 @@ ChatPage::logout() void ChatPage::resetUI() { - room_avatars_.clear(); + roomAvatars_.clear(); room_list_->clear(); roomSettings_.clear(); roomStates_.clear(); @@ -538,9 +537,9 @@ ChatPage::initialSyncCompleted(const mtx::responses::Sync &response) const auto room_id = QString::fromStdString(it->first); - roomStates_.insert(room_id, roomState); - roomSettings_.insert(room_id, - QSharedPointer(new RoomSettings(room_id))); + roomStates_.emplace(room_id, roomState); + roomSettings_.emplace(room_id, + QSharedPointer(new RoomSettings(room_id))); for (const auto membership : roomState->memberships) { updateUserDisplayName(membership.second); @@ -572,7 +571,7 @@ ChatPage::initialSyncCompleted(const mtx::responses::Sync &response) void ChatPage::updateTopBarAvatar(const QString &roomid, const QPixmap &img) { - room_avatars_.insert(roomid, img); + roomAvatars_.emplace(roomid, img); if (current_room_ != roomid) return; @@ -602,16 +601,16 @@ ChatPage::updateOwnCommunitiesInfo(const QList &own_communities) for (int i = 0; i < own_communities.size(); i++) { QSharedPointer community = QSharedPointer(new Community()); - communityManager_[own_communities[i]] = community; + communities_[own_communities[i]] = community; } - communitiesList_->setCommunities(communityManager_); + communitiesList_->setCommunities(communities_); } void ChatPage::changeTopRoomInfo(const QString &room_id) { - if (!roomStates_.contains(room_id)) + if (roomStates_.find(room_id) == roomStates_.end()) return; auto state = roomStates_[room_id]; @@ -620,8 +619,8 @@ ChatPage::changeTopRoomInfo(const QString &room_id) top_bar_->updateRoomTopic(state->getTopic()); top_bar_->setRoomSettings(roomSettings_[room_id]); - if (room_avatars_.contains(room_id)) - top_bar_->updateRoomAvatar(room_avatars_.value(room_id).toImage()); + if (roomAvatars_.find(room_id) != roomAvatars_.end()) + top_bar_->updateRoomAvatar(roomAvatars_[room_id].toImage()); else top_bar_->updateRoomAvatarFromName(state->getName()); @@ -648,51 +647,56 @@ ChatPage::loadStateFromCache() qDebug() << "Restored nextBatchToken" << cache_->nextBatchToken(); client_->setNextBatchToken(cache_->nextBatchToken()); - qRegisterMetaType>(); + qRegisterMetaType>(); QtConcurrent::run(cache_.data(), &Cache::states); - connect(cache_.data(), &Cache::statesLoaded, this, [this](QMap rooms) { - qDebug() << "Cache data loaded"; + connect( + cache_.data(), &Cache::statesLoaded, this, [this](std::map rooms) { + qDebug() << "Cache data loaded"; - for (auto it = rooms.constBegin(); it != rooms.constEnd(); ++it) { - auto roomState = QSharedPointer(new RoomState(it.value())); + std::vector roomKeys; - // Clean up and prepare state for use. - roomState->removeLeaveMemberships(); - roomState->resolveName(); - roomState->resolveAvatar(); + for (auto const &room : rooms) { + auto roomState = QSharedPointer(new RoomState(room.second)); - // Save the current room state. - roomStates_.insert(it.key(), roomState); + // Clean up and prepare state for use. + roomState->removeLeaveMemberships(); + roomState->resolveName(); + roomState->resolveAvatar(); - // Create or restore the settings for this room. - roomSettings_.insert( - it.key(), QSharedPointer(new RoomSettings(it.key()))); + // Save the current room state. + roomStates_.emplace(room.first, roomState); - // Resolve user avatars. - for (const auto membership : roomState->memberships) { - updateUserDisplayName(membership.second); - updateUserAvatarUrl(membership.second); - } - } + // Create or restore the settings for this room. + roomSettings_.emplace( + room.first, QSharedPointer(new RoomSettings(room.first))); - // Initializing empty timelines. - view_manager_->initialize(rooms.keys()); + // Resolve user avatars. + for (auto const &membership : roomState->memberships) { + updateUserDisplayName(membership.second); + updateUserAvatarUrl(membership.second); + } - // Initialize room list from the restored state and settings. - room_list_->setInitialRooms(roomSettings_, roomStates_); - room_list_->syncInvites(cache_->invites()); + roomKeys.emplace_back(room.first); + } - // Check periodically if the timelines have been loaded. - consensusTimer_->start(CONSENSUS_TIMEOUT); + // Initializing empty timelines. + view_manager_->initialize(roomKeys); - // Show the content if consensus can't be achieved. - showContentTimer_->start(SHOW_CONTENT_TIMEOUT); + // Initialize room list from the restored state and settings. + room_list_->setInitialRooms(roomSettings_, roomStates_); + room_list_->syncInvites(cache_->invites()); - // Start receiving events. - client_->sync(); - }); + // Check periodically if the timelines have been loaded. + consensusTimer_->start(CONSENSUS_TIMEOUT); + + // Show the content if consensus can't be achieved. + showContentTimer_->start(SHOW_CONTENT_TIMEOUT); + + // Start receiving events. + client_->sync(); + }); } void @@ -723,14 +727,14 @@ ChatPage::showQuickSwitcher() quickSwitcherModal_->setColor(QColor(30, 30, 30, 170)); } - QMap rooms; + std::map rooms; - for (auto it = roomStates_.constBegin(); it != roomStates_.constEnd(); ++it) { + for (auto const &state : roomStates_) { QString deambiguator = - QString::fromStdString(it.value()->canonical_alias.content.alias); + QString::fromStdString(state.second->canonical_alias.content.alias); if (deambiguator == "") - deambiguator = it.key(); - rooms.insert(it.value()->getName() + " (" + deambiguator + ")", it.key()); + deambiguator = state.first; + rooms.emplace(state.second->getName() + " (" + deambiguator + ")", state.first); } quickSwitcher_->setRoomList(rooms); @@ -740,14 +744,14 @@ ChatPage::showQuickSwitcher() void ChatPage::addRoom(const QString &room_id) { - if (!roomStates_.contains(room_id)) { + if (roomStates_.find(room_id) == roomStates_.end()) { auto room_state = QSharedPointer(new RoomState); - roomStates_.insert(room_id, room_state); - roomSettings_.insert(room_id, - QSharedPointer(new RoomSettings(room_id))); + roomStates_.emplace(room_id, room_state); + roomSettings_.emplace(room_id, + QSharedPointer(new RoomSettings(room_id))); - room_list_->addRoom(roomSettings_, roomStates_[room_id], room_id); + room_list_->addRoom(roomSettings_[room_id], roomStates_[room_id], room_id); room_list_->highlightSelectedRoom(room_id); changeTopRoomInfo(room_id); @@ -757,8 +761,8 @@ ChatPage::addRoom(const QString &room_id) void ChatPage::removeRoom(const QString &room_id) { - roomStates_.remove(room_id); - roomSettings_.remove(room_id); + roomStates_.erase(roomStates_.find(room_id)); + roomSettings_.erase(roomSettings_.find(room_id)); try { cache_->removeRoom(room_id); cache_->removeInvite(room_id); @@ -812,7 +816,7 @@ ChatPage::updateTypingUsers(const QString &roomid, const std::vectorsetUsers(users); } - typingUsers_.insert(roomid, users); + typingUsers_.emplace(roomid, users); } void @@ -833,7 +837,7 @@ ChatPage::updateUserDisplayName( auto stateKey = QString::fromStdString(membership.state_key); if (!displayName.isEmpty()) - TimelineViewManager::DISPLAY_NAMES.insert(stateKey, displayName); + TimelineViewManager::DISPLAY_NAMES.emplace(stateKey, displayName); } void @@ -842,7 +846,7 @@ ChatPage::removeLeftRooms(const std::map for (auto it = rooms.cbegin(); it != rooms.cend(); ++it) { const auto room_id = QString::fromStdString(it->first); - if (roomStates_.contains(room_id)) + if (roomStates_.find(room_id) != roomStates_.end()) removeRoom(room_id); } } @@ -865,7 +869,7 @@ ChatPage::updateJoinedRooms(const std::mapsecond.timeline; // Merge the new updates for rooms that we are tracking. - if (roomStates_.contains(roomid)) { + if (roomStates_.find(roomid) != roomStates_.end()) { auto oldState = roomStates_[roomid]; oldState->updateFromEvents(newStateEvents.events); oldState->updateFromEvents(newTimelineEvents.events); @@ -881,9 +885,9 @@ ChatPage::updateJoinedRooms(const std::mapresolveName(); roomState->resolveAvatar(); - roomStates_.insert(roomid, roomState); + roomStates_.emplace(roomid, roomState); - roomSettings_.insert( + roomSettings_.emplace( roomid, QSharedPointer(new RoomSettings(roomid))); view_manager_->addRoom(it->second, roomid); @@ -899,17 +903,17 @@ ChatPage::updateJoinedRooms(const std::map> +std::map> ChatPage::generateMembershipDifference( const std::map &rooms, - const QMap> &states) const + const std::map> &states) const { - QMap> stateDiff; + std::map> stateDiff; for (auto it = rooms.cbegin(); it != rooms.cend(); ++it) { const auto room_id = QString::fromStdString(it->first); - if (!states.contains(room_id)) + if (states.find(room_id) == states.end()) continue; auto all_memberships = getMemberships(it->second.state.events); @@ -920,17 +924,17 @@ ChatPage::generateMembershipDifference( all_memberships.emplace(mm->first, mm->second); auto local = QSharedPointer(new RoomState); - local->aliases = states[room_id]->aliases; - local->avatar = states[room_id]->avatar; - local->canonical_alias = states[room_id]->canonical_alias; - local->history_visibility = states[room_id]->history_visibility; - local->join_rules = states[room_id]->join_rules; - local->name = states[room_id]->name; - local->power_levels = states[room_id]->power_levels; - local->topic = states[room_id]->topic; + local->aliases = states.at(room_id)->aliases; + local->avatar = states.at(room_id)->avatar; + local->canonical_alias = states.at(room_id)->canonical_alias; + local->history_visibility = states.at(room_id)->history_visibility; + local->join_rules = states.at(room_id)->join_rules; + local->name = states.at(room_id)->name; + local->power_levels = states.at(room_id)->power_levels; + local->topic = states.at(room_id)->topic; local->memberships = all_memberships; - stateDiff.insert(room_id, local); + stateDiff.emplace(room_id, local); } return stateDiff; diff --git a/src/CommunitiesList.cc b/src/CommunitiesList.cc index c40155e..1469dd8 100644 --- a/src/CommunitiesList.cc +++ b/src/CommunitiesList.cc @@ -34,7 +34,7 @@ CommunitiesList::CommunitiesList(QSharedPointer client, QWidget *p WorldCommunityListItem *world_list_item = new WorldCommunityListItem(); contentsLayout_->addWidget(world_list_item); - communities_.insert("world", QSharedPointer(world_list_item)); + communities_.emplace("world", QSharedPointer(world_list_item)); connect(world_list_item, &WorldCommunityListItem::clicked, this, @@ -57,49 +57,38 @@ CommunitiesList::CommunitiesList(QSharedPointer client, QWidget *p SLOT(updateCommunityAvatar(const QString &, const QPixmap &))); } -CommunitiesList::~CommunitiesList() {} - void -CommunitiesList::setCommunities(const QMap> &communities) +CommunitiesList::setCommunities(const std::map> &communities) { communities_.clear(); // TODO: still not sure how to handle the "world" special-case WorldCommunityListItem *world_list_item = new WorldCommunityListItem(); - communities_.insert("world", QSharedPointer(world_list_item)); + communities_.emplace("world", QSharedPointer(world_list_item)); connect(world_list_item, &WorldCommunityListItem::clicked, this, &CommunitiesList::highlightSelectedCommunity); contentsLayout_->insertWidget(0, world_list_item); - for (auto it = communities.constBegin(); it != communities.constEnd(); it++) { - const auto community_id = it.key(); - const auto community = it.value(); - - addCommunity(community, community_id); + for (const auto &community : communities) { + addCommunity(community.second, community.first); - client_->fetchCommunityProfile(community_id); - client_->fetchCommunityRooms(community_id); + client_->fetchCommunityProfile(community.first); + client_->fetchCommunityRooms(community.first); } world_list_item->setPressedState(true); emit communityChanged("world"); } -void -CommunitiesList::clear() -{ - communities_.clear(); -} - void CommunitiesList::addCommunity(QSharedPointer community, const QString &community_id) { CommunitiesListItem *list_item = new CommunitiesListItem(community, community_id, scrollArea_); - communities_.insert(community_id, QSharedPointer(list_item)); + communities_.emplace(community_id, QSharedPointer(list_item)); client_->fetchCommunityAvatar(community_id, community->getAvatar()); @@ -114,37 +103,36 @@ CommunitiesList::addCommunity(QSharedPointer community, const QString void CommunitiesList::removeCommunity(const QString &community_id) { - communities_.remove(community_id); + communities_.erase(communities_.find(community_id)); } void CommunitiesList::updateCommunityAvatar(const QString &community_id, const QPixmap &img) { - if (!communities_.contains(community_id)) { + if (!communityExists(community_id)) { qWarning() << "Avatar update on nonexistent community" << community_id; return; } - communities_.value(community_id)->setAvatar(img.toImage()); + communities_.find(community_id)->second->setAvatar(img.toImage()); } void CommunitiesList::highlightSelectedCommunity(const QString &community_id) { - emit communityChanged(community_id); - - if (!communities_.contains(community_id)) { + if (!communityExists(community_id)) { qDebug() << "CommunitiesList: clicked unknown community"; return; } - for (auto it = communities_.constBegin(); it != communities_.constEnd(); it++) { - if (it.key() != community_id) { - it.value()->setPressedState(false); + emit communityChanged(community_id); + + for (const auto &community : communities_) { + if (community.first != community_id) { + community.second->setPressedState(false); } else { - it.value()->setPressedState(true); - scrollArea_->ensureWidgetVisible( - qobject_cast(it.value().data())); + community.second->setPressedState(true); + scrollArea_->ensureWidgetVisible(community.second.data()); } } } diff --git a/src/Community.cc b/src/Community.cc index a68f2b1..d563c15 100644 --- a/src/Community.cc +++ b/src/Community.cc @@ -6,29 +6,19 @@ void Community::parseProfile(const QJsonObject &profile) { - if (profile["name"].type() == QJsonValue::Type::String) { + if (profile["name"].type() == QJsonValue::Type::String) name_ = profile["name"].toString(); - } else { + else name_ = "Unnamed Community"; // TODO: what is correct here? - } - if (profile["avatar_url"].type() == QJsonValue::Type::String) { + if (profile["avatar_url"].type() == QJsonValue::Type::String) avatar_ = QUrl(profile["avatar_url"].toString()); - } else { - avatar_ = QUrl(); - } - if (profile["short_description"].type() == QJsonValue::Type::String) { + if (profile["short_description"].type() == QJsonValue::Type::String) short_description_ = profile["short_description"].toString(); - } else { - short_description_ = ""; - } - if (profile["long_description"].type() == QJsonValue::Type::String) { + if (profile["long_description"].type() == QJsonValue::Type::String) long_description_ = profile["long_description"].toString(); - } else { - long_description_ = ""; - } } void @@ -36,7 +26,8 @@ Community::parseRooms(const QJsonObject &rooms) { rooms_.clear(); - for (auto i = 0; i < rooms["chunk"].toArray().size(); i++) { - rooms_.append(rooms["chunk"].toArray()[i].toObject()["room_id"].toString()); + for (auto const &room : rooms["chunk"].toArray()) { + if (room.toObject().contains("room_id")) + rooms_.emplace_back(room.toObject()["room_id"].toString()); } } diff --git a/src/QuickSwitcher.cc b/src/QuickSwitcher.cc index 2be636a..6cc8250 100644 --- a/src/QuickSwitcher.cc +++ b/src/QuickSwitcher.cc @@ -138,10 +138,13 @@ QuickSwitcher::QuickSwitcher(QWidget *parent) } void -QuickSwitcher::setRoomList(const QMap &rooms) +QuickSwitcher::setRoomList(const std::map &rooms) { - rooms_ = rooms; - QStringList items = rooms.keys(); + rooms_ = rooms; + + QStringList items; + for (const auto &room : rooms) + items << room.first; completer_->setModel(new QStringListModel(items)); } diff --git a/src/RoomList.cc b/src/RoomList.cc index 61acfb8..fefd8da 100644 --- a/src/RoomList.cc +++ b/src/RoomList.cc @@ -82,16 +82,15 @@ RoomList::clear() } void -RoomList::addRoom(const QMap> &settings, +RoomList::addRoom(const QSharedPointer &settings, const QSharedPointer &state, const QString &room_id) { - RoomInfoListItem *room_item = - new RoomInfoListItem(settings[room_id], state, room_id, scrollArea_); + auto room_item = new RoomInfoListItem(settings, state, room_id, scrollArea_); connect(room_item, &RoomInfoListItem::clicked, this, &RoomList::highlightSelectedRoom); connect(room_item, &RoomInfoListItem::leaveRoom, this, &RoomList::openLeaveRoomDialog); - rooms_.insert(room_id, QSharedPointer(room_item)); + rooms_.emplace(room_id, QSharedPointer(room_item)); if (!state->getAvatar().toString().isEmpty()) updateAvatar(room_id, state->getAvatar().toString()); @@ -124,21 +123,24 @@ RoomList::updateAvatar(const QString &room_id, const QString &url) void RoomList::removeRoom(const QString &room_id, bool reset) { - rooms_.remove(room_id); + rooms_.erase(rooms_.find(room_id)); - if (rooms_.isEmpty() || !reset) + if (rooms_.empty() || !reset) return; - auto first_room = rooms_.first(); - first_room->setPressedState(true); + auto room = firstRoom(); - emit roomChanged(rooms_.firstKey()); + if (room.second.isNull()) + return; + + room.second->setPressedState(true); + emit roomChanged(room.first); } void RoomList::updateUnreadMessageCount(const QString &roomid, int count) { - if (!rooms_.contains(roomid)) { + if (!roomExists(roomid)) { qWarning() << "UpdateUnreadMessageCount: Unknown roomid"; return; } @@ -153,15 +155,17 @@ RoomList::calculateUnreadMessageCount() { int total_unread_msgs = 0; - for (const auto &room : rooms_) - total_unread_msgs += room->unreadMessageCount(); + for (const auto &room : rooms_) { + if (!room.second.isNull()) + total_unread_msgs += room.second->unreadMessageCount(); + } emit totalUnreadMessageCountUpdated(total_unread_msgs); } void -RoomList::setInitialRooms(const QMap> &settings, - const QMap> &states) +RoomList::setInitialRooms(const std::map> &settings, + const std::map> &states) { rooms_.clear(); @@ -171,22 +175,18 @@ RoomList::setInitialRooms(const QMap> &set return; } - for (auto it = states.constBegin(); it != states.constEnd(); ++it) { - const auto room_id = it.key(); - const auto state = it.value(); + for (auto const &state : states) + addRoom(settings.at(state.first), state.second, state.first); - addRoom(settings, state, room_id); - } - - if (rooms_.isEmpty()) + if (rooms_.empty()) return; - setFilterRooms(filterRooms_); - - auto first_room = rooms_.first(); - first_room->setPressedState(true); + auto room = firstRoom(); + if (room.second.isNull()) + return; - emit roomChanged(rooms_.firstKey()); + room.second->setPressedState(true); + emit roomChanged(room.first); } void @@ -212,33 +212,30 @@ RoomList::openLeaveRoomDialog(const QString &room_id) } void -RoomList::sync(const QMap> &states, - const QMap> &settings) +RoomList::sync(const std::map> &states, + const std::map> &settings) { - for (auto it = states.constBegin(); it != states.constEnd(); ++it) { - auto room_id = it.key(); - auto state = it.value(); + for (auto const &state : states) { + if (!roomExists(state.first)) + addRoom(settings.at(state.first), state.second, state.first); - if (!rooms_.contains(room_id)) - addRoom(settings, state, room_id); - - auto room = rooms_[room_id]; + auto room = rooms_[state.first]; auto current_avatar = room->state()->getAvatar(); - auto new_avatar = state->getAvatar(); + auto new_avatar = state.second->getAvatar(); if (current_avatar != new_avatar && !new_avatar.toString().isEmpty()) - updateAvatar(room_id, new_avatar.toString()); + updateAvatar(state.first, new_avatar.toString()); - room->setState(state); + room->setState(state.second); } } void RoomList::clearRoomMessageCount(const QString &room_id) { - if (!rooms_.contains(room_id)) + if (!roomExists(room_id)) return; auto room = rooms_[room_id]; @@ -252,7 +249,7 @@ RoomList::highlightSelectedRoom(const QString &room_id) { emit roomChanged(room_id); - if (!rooms_.contains(room_id)) { + if (!roomExists(room_id)) { qDebug() << "RoomList: clicked unknown roomid"; return; } @@ -261,13 +258,15 @@ RoomList::highlightSelectedRoom(const QString &room_id) calculateUnreadMessageCount(); - for (auto it = rooms_.constBegin(); it != rooms_.constEnd(); ++it) { - if (it.key() != room_id) { - it.value()->setPressedState(false); + for (auto const &room : rooms_) { + if (room.second.isNull()) + continue; + + if (room.first != room_id) { + room.second->setPressedState(false); } else { - it.value()->setPressedState(true); - scrollArea_->ensureWidgetVisible( - qobject_cast(it.value().data())); + room.second->setPressedState(true); + scrollArea_->ensureWidgetVisible(room.second.data()); } } @@ -277,12 +276,12 @@ RoomList::highlightSelectedRoom(const QString &room_id) void RoomList::updateRoomAvatar(const QString &roomid, const QPixmap &img) { - if (!rooms_.contains(roomid)) { + if (!roomExists(roomid)) { qWarning() << "Avatar update on non existent room" << roomid; return; } - rooms_.value(roomid)->setAvatar(img.toImage()); + rooms_[roomid]->setAvatar(img.toImage()); // Used to inform other widgets for the new image data. emit roomAvatarChanged(roomid, img); @@ -291,12 +290,12 @@ RoomList::updateRoomAvatar(const QString &roomid, const QPixmap &img) void RoomList::updateRoomDescription(const QString &roomid, const DescInfo &info) { - if (!rooms_.contains(roomid)) { + if (!roomExists(roomid)) { qWarning() << "Description update on non existent room" << roomid << info.body; return; } - rooms_.value(roomid)->setDescriptionMessage(info); + rooms_[roomid]->setDescriptionMessage(info); if (underMouse()) { // When the user hover out of the roomlist a sort will be triggered. @@ -359,9 +358,8 @@ RoomList::closeJoinRoomDialog(bool isJoining, QString roomAlias) { joinRoomModal_->fadeOut(); - if (isJoining) { + if (isJoining) client_->joinRoom(roomAlias); - } } void @@ -369,48 +367,44 @@ RoomList::closeLeaveRoomDialog(bool leaving, const QString &room_id) { leaveRoomModal_->fadeOut(); - if (leaving) { + if (leaving) client_->leaveRoom(room_id); - } } void -RoomList::setFilterRooms(bool filterRooms) +RoomList::setFilterRooms(bool isFilteringEnabled) { - filterRooms_ = filterRooms; - for (int i = 0; i < contentsLayout_->count(); i++) { // If roomFilter_ contains the room for the current RoomInfoListItem, // show the list item, otherwise hide it - RoomInfoListItem *listitem = - (RoomInfoListItem *)contentsLayout_->itemAt(i)->widget(); - - if (listitem != nullptr) { - if (!filterRooms) { - contentsLayout_->itemAt(i)->widget()->show(); - } else if (roomFilter_.contains(listitem->roomId())) { - contentsLayout_->itemAt(i)->widget()->show(); - } else { - contentsLayout_->itemAt(i)->widget()->hide(); - } - } + auto listitem = + qobject_cast(contentsLayout_->itemAt(i)->widget()); + + if (!listitem) + continue; + + if (!isFilteringEnabled || filterItemExists(listitem->roomId())) + listitem->show(); + else + listitem->hide(); } - if (filterRooms_ && !roomFilter_.contains(selectedRoom_)) { + if (isFilteringEnabled && !filterItemExists(selectedRoom_)) { RoomInfoListItem *firstVisibleRoom = nullptr; + for (int i = 0; i < contentsLayout_->count(); i++) { QWidget *item = contentsLayout_->itemAt(i)->widget(); + if (item != nullptr && item->isVisible()) { - firstVisibleRoom = (RoomInfoListItem *)item; + firstVisibleRoom = qobject_cast(item); break; } } - if (firstVisibleRoom != nullptr) { + + if (firstVisibleRoom != nullptr) highlightSelectedRoom(firstVisibleRoom->roomId()); - } } else { - scrollArea_->ensureWidgetVisible( - qobject_cast(rooms_.value(selectedRoom_).data())); + scrollArea_->ensureWidgetVisible(rooms_[selectedRoom_].data()); } } @@ -429,13 +423,13 @@ RoomList::syncInvites(const std::map & for (auto it = rooms.cbegin(); it != rooms.cend(); ++it) { const auto room_id = QString::fromStdString(it->first); - if (!rooms_.contains(room_id)) + if (!roomExists(room_id)) addInvitedRoom(room_id, it->second); } } void -RoomList::setRoomFilter(QList room_ids) +RoomList::setRoomFilter(std::vector room_ids) { roomFilter_ = room_ids; setFilterRooms(true); @@ -448,10 +442,22 @@ RoomList::addInvitedRoom(const QString &room_id, const mtx::responses::InvitedRo connect(room_item, &RoomInfoListItem::acceptInvite, this, &RoomList::acceptInvite); connect(room_item, &RoomInfoListItem::declineInvite, this, &RoomList::declineInvite); - rooms_.insert(room_id, QSharedPointer(room_item)); + rooms_.emplace(room_id, QSharedPointer(room_item)); updateAvatar(room_id, QString::fromStdString(room.avatar())); int pos = contentsLayout_->count() - 1; contentsLayout_->insertWidget(pos, room_item); } + +std::pair> +RoomList::firstRoom() const +{ + auto firstRoom = rooms_.begin(); + + while (firstRoom->second.isNull() && firstRoom != rooms_.end()) + firstRoom++; + + return std::pair>(firstRoom->first, + firstRoom->second); +} diff --git a/src/timeline/TimelineViewManager.cc b/src/timeline/TimelineViewManager.cc index 4214581..0a81b06 100644 --- a/src/timeline/TimelineViewManager.cc +++ b/src/timeline/TimelineViewManager.cc @@ -89,7 +89,7 @@ TimelineViewManager::queueImageMessage(const QString &roomid, const QString &filename, const QString &url) { - if (!views_.contains(roomid)) { + if (!timelineViewExists(roomid)) { qDebug() << "Cannot send m.image message to a non-managed view"; return; } @@ -104,7 +104,7 @@ TimelineViewManager::queueFileMessage(const QString &roomid, const QString &filename, const QString &url) { - if (!views_.contains(roomid)) { + if (!timelineViewExists(roomid)) { qDebug() << "Cannot send m.file message to a non-managed view"; return; } @@ -119,7 +119,7 @@ TimelineViewManager::queueAudioMessage(const QString &roomid, const QString &filename, const QString &url) { - if (!views_.contains(roomid)) { + if (!timelineViewExists(roomid)) { qDebug() << "Cannot send m.audio message to a non-managed view"; return; } @@ -129,15 +129,6 @@ TimelineViewManager::queueAudioMessage(const QString &roomid, view->addUserMessage(url, filename); } -void -TimelineViewManager::clearAll() -{ - for (auto view : views_) - removeWidget(view.data()); - - views_.clear(); -} - void TimelineViewManager::initialize(const mtx::responses::Rooms &rooms) { @@ -147,11 +138,10 @@ TimelineViewManager::initialize(const mtx::responses::Rooms &rooms) } void -TimelineViewManager::initialize(const QList &rooms) +TimelineViewManager::initialize(const std::vector &rooms) { - for (const auto &roomid : rooms) { + for (const auto &roomid : rooms) addRoom(roomid); - } } void @@ -159,7 +149,7 @@ TimelineViewManager::addRoom(const mtx::responses::JoinedRoom &room, const QStri { // Create a history view with the room events. TimelineView *view = new TimelineView(room.timeline, client_, room_id); - views_.insert(room_id, QSharedPointer(view)); + views_.emplace(room_id, QSharedPointer(view)); connect(view, &TimelineView::updateLastTimelineMessage, @@ -179,7 +169,7 @@ TimelineViewManager::addRoom(const QString &room_id) { // Create a history view without any events. TimelineView *view = new TimelineView(client_, room_id); - views_.insert(room_id, QSharedPointer(view)); + views_.emplace(room_id, QSharedPointer(view)); connect(view, &TimelineView::updateLastTimelineMessage, @@ -200,12 +190,12 @@ TimelineViewManager::sync(const mtx::responses::Rooms &rooms) for (auto it = rooms.join.cbegin(); it != rooms.join.cend(); ++it) { auto roomid = QString::fromStdString(it->first); - if (!views_.contains(roomid)) { + if (!timelineViewExists(roomid)) { qDebug() << "Ignoring event from unknown room" << roomid; continue; } - auto view = views_.value(roomid); + auto view = views_.at(roomid); int msgs_added = view->addEvents(it->second.timeline); @@ -223,13 +213,13 @@ TimelineViewManager::sync(const mtx::responses::Rooms &rooms) void TimelineViewManager::setHistoryView(const QString &room_id) { - if (!views_.contains(room_id)) { + if (!timelineViewExists(room_id)) { qDebug() << "Room ID from RoomList is not present in ViewManager" << room_id; return; } active_room_ = room_id; - auto view = views_.value(room_id); + auto view = views_.at(room_id); setCurrentWidget(view.data()); @@ -237,7 +227,7 @@ TimelineViewManager::setHistoryView(const QString &room_id) view->scrollDown(); } -QMap TimelineViewManager::DISPLAY_NAMES; +std::map TimelineViewManager::DISPLAY_NAMES; QString TimelineViewManager::chooseRandomColor() @@ -300,8 +290,8 @@ TimelineViewManager::chooseRandomColor() QString TimelineViewManager::displayName(const QString &userid) { - if (DISPLAY_NAMES.contains(userid)) - return DISPLAY_NAMES.value(userid); + if (DISPLAY_NAMES.find(userid) != DISPLAY_NAMES.end()) + return DISPLAY_NAMES.at(userid); return userid; } @@ -310,7 +300,7 @@ bool TimelineViewManager::hasLoaded() const { for (const auto &view : views_) - if (!view->hasLoaded()) + if (!view.second->hasLoaded()) return false; return true;