From 19dc6cadea0168f72daff7c0ed679ccdac71a7d5 Mon Sep 17 00:00:00 2001 From: Nicolas Werner Date: Wed, 29 Dec 2021 06:01:38 +0100 Subject: [PATCH] Reserve size of some containers we are filling --- src/Cache.cpp | 12 +- src/ChatPage.cpp | 3 +- src/CombinedImagePackModel.cpp | 3 +- src/EventAccessors.cpp | 4 +- src/ImagePackListModel.cpp | 1 + src/InviteesModel.cpp | 9 +- src/InviteesModel.h | 9 +- src/MainWindow.cpp | 3 +- src/MxcImageProvider.cpp | 6 +- src/ReadReceiptsModel.cpp | 5 +- src/RegisterPage.cpp | 5 +- src/SingleImagePackModel.cpp | 1 + src/UserSettingsPage.cpp | 173 +++++++++++++++------------ src/UserSettingsPage.h | 9 +- src/Utils.cpp | 12 +- src/encryption/Olm.cpp | 1 + src/main.cpp | 14 ++- src/notifications/ManagerLinux.cpp | 9 +- src/timeline/CommunitiesModel.cpp | 1 + src/timeline/EventStore.cpp | 1 + src/timeline/InputBar.cpp | 12 +- src/timeline/RoomlistModel.cpp | 11 +- src/timeline/RoomlistModel.h | 3 +- src/timeline/TimelineModel.cpp | 87 +++++++------- src/timeline/TimelineModel.h | 1 + src/timeline/TimelineViewManager.cpp | 72 +++++++---- src/ui/NhekoGlobalObject.cpp | 4 +- src/ui/RoomSettings.cpp | 6 +- src/ui/UserProfile.cpp | 19 +-- src/voip/CallManager.cpp | 14 ++- src/voip/WebRTCSession.cpp | 16 ++- 31 files changed, 317 insertions(+), 209 deletions(-) diff --git a/src/Cache.cpp b/src/Cache.cpp index 3a21f83e..b197353e 100644 --- a/src/Cache.cpp +++ b/src/Cache.cpp @@ -224,13 +224,13 @@ Cache::setup() // Previous location of the cache directory auto oldCache = QStringLiteral("%1/%2%3").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation), - QString::fromUtf8(localUserId_.toUtf8().toHex()), - QString::fromUtf8(settings->profile().toUtf8().toHex())); + QString::fromUtf8(localUserId_.toUtf8().toHex()), + QString::fromUtf8(settings->profile().toUtf8().toHex())); - cacheDirectory_ = - QStringLiteral("%1/%2%3").arg(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), - QString::fromUtf8(localUserId_.toUtf8().toHex()), - QString::fromUtf8(settings->profile().toUtf8().toHex())); + cacheDirectory_ = QStringLiteral("%1/%2%3").arg( + QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), + QString::fromUtf8(localUserId_.toUtf8().toHex()), + QString::fromUtf8(settings->profile().toUtf8().toHex())); bool isInitial = !QFile::exists(cacheDirectory_); diff --git a/src/ChatPage.cpp b/src/ChatPage.cpp index 71cfadd8..46c8a9f9 100644 --- a/src/ChatPage.cpp +++ b/src/ChatPage.cpp @@ -1325,7 +1325,8 @@ ChatPage::handleMatrixUri(QString uri) if (item.startsWith(QLatin1String("action="))) { action = item.remove(QStringLiteral("action=")); } else if (item.startsWith(QLatin1String("via="))) { - vias.push_back(QUrl::fromPercentEncoding(item.remove(QStringLiteral("via=")).toUtf8()).toStdString()); + vias.push_back(QUrl::fromPercentEncoding(item.remove(QStringLiteral("via=")).toUtf8()) + .toStdString()); } } diff --git a/src/CombinedImagePackModel.cpp b/src/CombinedImagePackModel.cpp index abc49dd5..d9d047a1 100644 --- a/src/CombinedImagePackModel.cpp +++ b/src/CombinedImagePackModel.cpp @@ -56,7 +56,8 @@ CombinedImagePackModel::data(const QModelIndex &index, int role) const if (hasIndex(index.row(), index.column(), index.parent())) { switch (role) { case CompletionModel::CompletionRole: - return QStringLiteral("\"%2\"") + return QStringLiteral( + "\"%2\"") .arg(QString::fromStdString(images[index.row()].image.url).toHtmlEscaped(), QString::fromStdString(images[index.row()].image.body)); case Roles::Url: diff --git a/src/EventAccessors.cpp b/src/EventAccessors.cpp index 4d8b7b8f..f77c41e7 100644 --- a/src/EventAccessors.cpp +++ b/src/EventAccessors.cpp @@ -396,7 +396,9 @@ mtx::accessors::formattedBodyWithFallback(const mtx::events::collections::Timeli if (!formatted.empty()) return QString::fromStdString(formatted); else - return QString::fromStdString(body(event)).toHtmlEscaped().replace(QLatin1String("\n"), QLatin1String("
")); + return QString::fromStdString(body(event)) + .toHtmlEscaped() + .replace(QLatin1String("\n"), QLatin1String("
")); } std::optional diff --git a/src/ImagePackListModel.cpp b/src/ImagePackListModel.cpp index 39e46f01..a8ac99c8 100644 --- a/src/ImagePackListModel.cpp +++ b/src/ImagePackListModel.cpp @@ -15,6 +15,7 @@ ImagePackListModel::ImagePackListModel(const std::string &roomId, QObject *paren { auto packs_ = cache::client()->getImagePacks(room_id, std::nullopt); + packs.reserve(packs_.size()); for (const auto &pack : packs_) { packs.push_back(QSharedPointer(new SingleImagePackModel(pack))); } diff --git a/src/InviteesModel.cpp b/src/InviteesModel.cpp index ced58389..b7e495ce 100644 --- a/src/InviteesModel.cpp +++ b/src/InviteesModel.cpp @@ -76,14 +76,15 @@ QStringList InviteesModel::mxids() { QStringList mxidList; - for (int i = 0; i < invitees_.length(); ++i) - mxidList.push_back(invitees_[i]->mxid_); + mxidList.reserve(invitees_.size()); + for (auto &invitee : qAsConst(invitees_)) + mxidList.push_back(invitee->mxid_); return mxidList; } -Invitee::Invitee(const QString &mxid, QObject *parent) +Invitee::Invitee(QString mxid, QObject *parent) : QObject{parent} - , mxid_{mxid} + , mxid_{std::move(mxid)} { http::client()->get_profile( mxid_.toStdString(), [this](const mtx::responses::Profile &res, mtx::http::RequestErr err) { diff --git a/src/InviteesModel.h b/src/InviteesModel.h index 65fb78d6..c5473177 100644 --- a/src/InviteesModel.h +++ b/src/InviteesModel.h @@ -13,7 +13,7 @@ class Invitee : public QObject Q_OBJECT public: - Invitee(const QString &mxid, QObject *parent = nullptr); + Invitee(QString mxid, QObject *parent = nullptr); signals: void userInfoLoaded(); @@ -45,12 +45,13 @@ public: Q_INVOKABLE void addUser(QString mxid); Q_INVOKABLE void removeUser(QString mxid); - QHash roleNames() const override; - int rowCount(const QModelIndex & = QModelIndex()) const override + [[nodiscard]] QHash roleNames() const override; + [[nodiscard]] int rowCount(const QModelIndex & = QModelIndex()) const override { return (int)invitees_.size(); } - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + [[nodiscard]] QVariant + data(const QModelIndex &index, int role = Qt::DisplayRole) const override; QStringList mxids(); signals: diff --git a/src/MainWindow.cpp b/src/MainWindow.cpp index 0c8273f7..bc830f23 100644 --- a/src/MainWindow.cpp +++ b/src/MainWindow.cpp @@ -261,7 +261,8 @@ void MainWindow::closeEvent(QCloseEvent *event) { if (WebRTCSession::instance().state() != webrtc::State::DISCONNECTED) { - if (QMessageBox::question(this, QStringLiteral("nheko"), QStringLiteral("A call is in progress. Quit?")) != + if (QMessageBox::question( + this, QStringLiteral("nheko"), QStringLiteral("A call is in progress. Quit?")) != QMessageBox::Yes) { event->ignore(); return; diff --git a/src/MxcImageProvider.cpp b/src/MxcImageProvider.cpp index 192cedbe..2405d413 100644 --- a/src/MxcImageProvider.cpp +++ b/src/MxcImageProvider.cpp @@ -255,7 +255,8 @@ MxcImageProvider::download(const QString &id, image = clipRadius(std::move(image), radius); } - image.setText(QStringLiteral("original filename"), QString::fromStdString(originalFilename)); + image.setText(QStringLiteral("original filename"), + QString::fromStdString(originalFilename)); image.setText(QStringLiteral("mxc url"), "mxc://" + id); then(id, requestedSize, image, fileInfo.absoluteFilePath()); return; @@ -266,7 +267,8 @@ MxcImageProvider::download(const QString &id, image = clipRadius(std::move(image), radius); } - image.setText(QStringLiteral("original filename"), QString::fromStdString(originalFilename)); + image.setText(QStringLiteral("original filename"), + QString::fromStdString(originalFilename)); image.setText(QStringLiteral("mxc url"), "mxc://" + id); then(id, requestedSize, image, fileInfo.absoluteFilePath()); }); diff --git a/src/ReadReceiptsModel.cpp b/src/ReadReceiptsModel.cpp index ed28ce48..15ac83e1 100644 --- a/src/ReadReceiptsModel.cpp +++ b/src/ReadReceiptsModel.cpp @@ -112,8 +112,9 @@ ReadReceiptsModel::dateFormat(const QDateTime &then) const else if (days < 7) //: %1 is the name of the current day, %2 is the time the read receipt was read. The //: result may look like this: Monday, 7:15 - return QStringLiteral("%1, %2").arg(then.toString(QStringLiteral("dddd")), - QLocale::system().toString(then.time(), QLocale::ShortFormat)); + return QStringLiteral("%1, %2").arg( + then.toString(QStringLiteral("dddd")), + QLocale::system().toString(then.time(), QLocale::ShortFormat)); return QLocale::system().toString(then.time(), QLocale::ShortFormat); } diff --git a/src/RegisterPage.cpp b/src/RegisterPage.cpp index 351f1e5d..3958a0b4 100644 --- a/src/RegisterPage.cpp +++ b/src/RegisterPage.cpp @@ -364,7 +364,10 @@ RegisterPage::doRegistration() disconnect(UIA::instance(), &UIA::error, this, nullptr); }); http::client()->registration( - username, password, ::UIA::instance()->genericHandler(QStringLiteral("Registration")), registrationCb()); + username, + password, + ::UIA::instance()->genericHandler(QStringLiteral("Registration")), + registrationCb()); } } diff --git a/src/SingleImagePackModel.cpp b/src/SingleImagePackModel.cpp index 3eb5f031..c2363337 100644 --- a/src/SingleImagePackModel.cpp +++ b/src/SingleImagePackModel.cpp @@ -29,6 +29,7 @@ SingleImagePackModel::SingleImagePackModel(ImagePackInfo pack_, QObject *parent) if (!pack.pack) pack.pack = mtx::events::msc2545::ImagePack::PackDescription{}; + shortcodes.reserve(pack.images.size()); for (const auto &e : pack.images) shortcodes.push_back(e.first); diff --git a/src/UserSettingsPage.cpp b/src/UserSettingsPage.cpp index ce501681..63563f3f 100644 --- a/src/UserSettingsPage.cpp +++ b/src/UserSettingsPage.cpp @@ -63,55 +63,70 @@ UserSettings::load(std::optional profile) tray_ = settings.value(QStringLiteral("user/window/tray"), false).toBool(); startInTray_ = settings.value(QStringLiteral("user/window/start_in_tray"), false).toBool(); - roomListWidth_ = settings.value(QStringLiteral("user/sidebar/room_list_width"), -1).toInt(); - communityListWidth_ = settings.value(QStringLiteral("user/sidebar/community_list_width"), -1).toInt(); + roomListWidth_ = settings.value(QStringLiteral("user/sidebar/room_list_width"), -1).toInt(); + communityListWidth_ = + settings.value(QStringLiteral("user/sidebar/community_list_width"), -1).toInt(); - hasDesktopNotifications_ = settings.value(QStringLiteral("user/desktop_notifications"), true).toBool(); - hasAlertOnNotification_ = settings.value(QStringLiteral("user/alert_on_notification"), false).toBool(); - groupView_ = settings.value(QStringLiteral("user/group_view"), true).toBool(); - buttonsInTimeline_ = settings.value(QStringLiteral("user/timeline/buttons"), true).toBool(); - timelineMaxWidth_ = settings.value(QStringLiteral("user/timeline/max_width"), 0).toInt(); + hasDesktopNotifications_ = + settings.value(QStringLiteral("user/desktop_notifications"), true).toBool(); + hasAlertOnNotification_ = + settings.value(QStringLiteral("user/alert_on_notification"), false).toBool(); + groupView_ = settings.value(QStringLiteral("user/group_view"), true).toBool(); + buttonsInTimeline_ = settings.value(QStringLiteral("user/timeline/buttons"), true).toBool(); + timelineMaxWidth_ = settings.value(QStringLiteral("user/timeline/max_width"), 0).toInt(); messageHoverHighlight_ = settings.value(QStringLiteral("user/timeline/message_hover_highlight"), false).toBool(); enlargeEmojiOnlyMessages_ = settings.value(QStringLiteral("user/timeline/enlarge_emoji_only_msg"), false).toBool(); - markdown_ = settings.value(QStringLiteral("user/markdown_enabled"), true).toBool(); - animateImagesOnHover_ = settings.value(QStringLiteral("user/animate_images_on_hover"), false).toBool(); - typingNotifications_ = settings.value(QStringLiteral("user/typing_notifications"), true).toBool(); - sortByImportance_ = settings.value(QStringLiteral("user/sort_by_unread"), true).toBool(); - readReceipts_ = settings.value(QStringLiteral("user/read_receipts"), true).toBool(); - theme_ = settings.value(QStringLiteral("user/theme"), defaultTheme_).toString(); - font_ = settings.value(QStringLiteral("user/font_family"), "default").toString(); - avatarCircles_ = settings.value(QStringLiteral("user/avatar_circles"), true).toBool(); - useIdenticon_ = settings.value(QStringLiteral("user/use_identicon"), true).toBool(); - decryptSidebar_ = settings.value(QStringLiteral("user/decrypt_sidebar"), true).toBool(); - privacyScreen_ = settings.value(QStringLiteral("user/privacy_screen"), false).toBool(); - privacyScreenTimeout_ = settings.value(QStringLiteral("user/privacy_screen_timeout"), 0).toInt(); - mobileMode_ = settings.value(QStringLiteral("user/mobile_mode"), false).toBool(); - emojiFont_ = settings.value(QStringLiteral("user/emoji_font_family"), "default").toString(); - baseFontSize_ = settings.value(QStringLiteral("user/font_size"), QFont().pointSizeF()).toDouble(); - auto tempPresence = settings.value(QStringLiteral("user/presence"), "").toString().toStdString(); - auto presenceValue = QMetaEnum::fromType().keyToValue(tempPresence.c_str()); + markdown_ = settings.value(QStringLiteral("user/markdown_enabled"), true).toBool(); + animateImagesOnHover_ = + settings.value(QStringLiteral("user/animate_images_on_hover"), false).toBool(); + typingNotifications_ = + settings.value(QStringLiteral("user/typing_notifications"), true).toBool(); + sortByImportance_ = settings.value(QStringLiteral("user/sort_by_unread"), true).toBool(); + readReceipts_ = settings.value(QStringLiteral("user/read_receipts"), true).toBool(); + theme_ = settings.value(QStringLiteral("user/theme"), defaultTheme_).toString(); + font_ = settings.value(QStringLiteral("user/font_family"), "default").toString(); + avatarCircles_ = settings.value(QStringLiteral("user/avatar_circles"), true).toBool(); + useIdenticon_ = settings.value(QStringLiteral("user/use_identicon"), true).toBool(); + decryptSidebar_ = settings.value(QStringLiteral("user/decrypt_sidebar"), true).toBool(); + privacyScreen_ = settings.value(QStringLiteral("user/privacy_screen"), false).toBool(); + privacyScreenTimeout_ = + settings.value(QStringLiteral("user/privacy_screen_timeout"), 0).toInt(); + mobileMode_ = settings.value(QStringLiteral("user/mobile_mode"), false).toBool(); + emojiFont_ = settings.value(QStringLiteral("user/emoji_font_family"), "default").toString(); + baseFontSize_ = + settings.value(QStringLiteral("user/font_size"), QFont().pointSizeF()).toDouble(); + auto tempPresence = + settings.value(QStringLiteral("user/presence"), "").toString().toStdString(); + auto presenceValue = QMetaEnum::fromType().keyToValue(tempPresence.c_str()); if (presenceValue < 0) presenceValue = 0; - presence_ = static_cast(presenceValue); - ringtone_ = settings.value(QStringLiteral("user/ringtone"), "Default").toString(); - microphone_ = settings.value(QStringLiteral("user/microphone"), QString()).toString(); - camera_ = settings.value(QStringLiteral("user/camera"), QString()).toString(); - cameraResolution_ = settings.value(QStringLiteral("user/camera_resolution"), QString()).toString(); - cameraFrameRate_ = settings.value(QStringLiteral("user/camera_frame_rate"), QString()).toString(); - screenShareFrameRate_ = settings.value(QStringLiteral("user/screen_share_frame_rate"), 5).toInt(); - screenSharePiP_ = settings.value(QStringLiteral("user/screen_share_pip"), true).toBool(); - screenShareRemoteVideo_ = settings.value(QStringLiteral("user/screen_share_remote_video"), false).toBool(); - screenShareHideCursor_ = settings.value(QStringLiteral("user/screen_share_hide_cursor"), false).toBool(); - useStunServer_ = settings.value(QStringLiteral("user/use_stun_server"), false).toBool(); + presence_ = static_cast(presenceValue); + ringtone_ = settings.value(QStringLiteral("user/ringtone"), "Default").toString(); + microphone_ = settings.value(QStringLiteral("user/microphone"), QString()).toString(); + camera_ = settings.value(QStringLiteral("user/camera"), QString()).toString(); + cameraResolution_ = + settings.value(QStringLiteral("user/camera_resolution"), QString()).toString(); + cameraFrameRate_ = + settings.value(QStringLiteral("user/camera_frame_rate"), QString()).toString(); + screenShareFrameRate_ = + settings.value(QStringLiteral("user/screen_share_frame_rate"), 5).toInt(); + screenSharePiP_ = settings.value(QStringLiteral("user/screen_share_pip"), true).toBool(); + screenShareRemoteVideo_ = + settings.value(QStringLiteral("user/screen_share_remote_video"), false).toBool(); + screenShareHideCursor_ = + settings.value(QStringLiteral("user/screen_share_hide_cursor"), false).toBool(); + useStunServer_ = settings.value(QStringLiteral("user/use_stun_server"), false).toBool(); if (profile) // set to "" if it's the default to maintain compatibility profile_ = (*profile == QLatin1String("default")) ? QLatin1String("") : *profile; else profile_ = settings.value(QStringLiteral("user/currentProfile"), "").toString(); - QString prefix = (profile_ != QLatin1String("") && profile_ != QLatin1String("default")) ? "profile/" + profile_ + "/" : QLatin1String(""); + QString prefix = (profile_ != QLatin1String("") && profile_ != QLatin1String("default")) + ? "profile/" + profile_ + "/" + : QLatin1String(""); accessToken_ = settings.value(prefix + "auth/access_token", "").toString(); homeserver_ = settings.value(prefix + "auth/home_server", "").toString(); userId_ = settings.value(prefix + "auth/user_id", "").toString(); @@ -714,7 +729,9 @@ UserSettings::save() settings.endGroup(); // user - QString prefix = (profile_ != QLatin1String("") && profile_ != QLatin1String("default")) ? "profile/" + profile_ + "/" : QLatin1String(""); + QString prefix = (profile_ != QLatin1String("") && profile_ != QLatin1String("default")) + ? "profile/" + profile_ + "/" + : QLatin1String(""); settings.setValue(prefix + "auth/access_token", accessToken_); settings.setValue(prefix + "auth/home_server", homeserver_); settings.setValue(prefix + "auth/user_id", userId_); @@ -730,11 +747,13 @@ UserSettings::save() settings.setValue(prefix + "user/recent_reactions", recentReactions_); QVariantList v; + v.reserve(collapsedSpaces_.size()); for (const auto &e : qAsConst(collapsedSpaces_)) v.push_back(e); settings.setValue(prefix + "user/collapsed_spaces", v); - settings.setValue(QStringLiteral("disable_certificate_validation"), disableCertificateValidation_); + settings.setValue(QStringLiteral("disable_certificate_validation"), + disableCertificateValidation_); settings.sync(); } @@ -959,20 +978,21 @@ UserSettingsPage::UserSettingsPage(QSharedPointer settings, QWidge crossSigningKeysLayout->addWidget(crossSigningRequestBtn, 0, Qt::AlignRight); crossSigningKeysLayout->addWidget(crossSigningDownloadBtn, 0, Qt::AlignRight); - auto boxWrap = [this, &font](QString labelText, QWidget *field, QString tooltipText = QLatin1String("")) { - auto label = new QLabel{labelText, this}; - label->setFont(font); - label->setMargin(OptionMargin); + auto boxWrap = + [this, &font](QString labelText, QWidget *field, QString tooltipText = QLatin1String("")) { + auto label = new QLabel{labelText, this}; + label->setFont(font); + label->setMargin(OptionMargin); - if (!tooltipText.isEmpty()) { - label->setToolTip(tooltipText); - } + if (!tooltipText.isEmpty()) { + label->setToolTip(tooltipText); + } - auto layout = new QHBoxLayout; - layout->addWidget(field, 0, Qt::AlignRight); + auto layout = new QHBoxLayout; + layout->addWidget(field, 0, Qt::AlignRight); - formLayout_->addRow(label, layout); - }; + formLayout_->addRow(label, layout); + }; formLayout_->addRow(general_); formLayout_->addRow(new HorizontalLine{this}); @@ -1087,7 +1107,8 @@ UserSettingsPage::UserSettingsPage(QSharedPointer settings, QWidge ringtoneCombo_->addItem(QStringLiteral("Default")); ringtoneCombo_->addItem(QStringLiteral("Other...")); const QString &ringtone = settings_->ringtone(); - if (!ringtone.isEmpty() && ringtone != QLatin1String("Mute") && ringtone != QLatin1String("Default")) + if (!ringtone.isEmpty() && ringtone != QLatin1String("Mute") && + ringtone != QLatin1String("Default")) ringtoneCombo_->addItem(ringtone); microphoneCombo_->setSizeAdjustPolicy(QComboBox::AdjustToContents); cameraCombo_->setSizeAdjustPolicy(QComboBox::AdjustToContents); @@ -1186,32 +1207,32 @@ UserSettingsPage::UserSettingsPage(QSharedPointer settings, QWidge this, [this](const QString &family) { settings_->setEmojiFontFamily(family.trimmed()); }); - connect(ringtoneCombo_, - static_cast(&QComboBox::currentTextChanged), - this, - [this](const QString &ringtone) { - if (ringtone == QLatin1String("Other...")) { - QString homeFolder = - QStandardPaths::writableLocation(QStandardPaths::HomeLocation); - auto filepath = QFileDialog::getOpenFileName( - this, tr("Select a file"), homeFolder, tr("All Files (*)")); - if (!filepath.isEmpty()) { - const auto &oldSetting = settings_->ringtone(); - if (oldSetting != QLatin1String("Mute") && oldSetting != QLatin1String("Default")) - ringtoneCombo_->removeItem(ringtoneCombo_->findText(oldSetting)); - settings_->setRingtone(filepath); - ringtoneCombo_->addItem(filepath); - ringtoneCombo_->setCurrentText(filepath); - } else { - ringtoneCombo_->setCurrentText(settings_->ringtone()); - } - } else if (ringtone == QLatin1String("Mute") || ringtone == QLatin1String("Default")) { - const auto &oldSetting = settings_->ringtone(); - if (oldSetting != QLatin1String("Mute") && oldSetting != QLatin1String("Default")) - ringtoneCombo_->removeItem(ringtoneCombo_->findText(oldSetting)); - settings_->setRingtone(ringtone); - } - }); + connect( + ringtoneCombo_, + static_cast(&QComboBox::currentTextChanged), + this, + [this](const QString &ringtone) { + if (ringtone == QLatin1String("Other...")) { + QString homeFolder = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); + auto filepath = QFileDialog::getOpenFileName( + this, tr("Select a file"), homeFolder, tr("All Files (*)")); + if (!filepath.isEmpty()) { + const auto &oldSetting = settings_->ringtone(); + if (oldSetting != QLatin1String("Mute") && oldSetting != QLatin1String("Default")) + ringtoneCombo_->removeItem(ringtoneCombo_->findText(oldSetting)); + settings_->setRingtone(filepath); + ringtoneCombo_->addItem(filepath); + ringtoneCombo_->setCurrentText(filepath); + } else { + ringtoneCombo_->setCurrentText(settings_->ringtone()); + } + } else if (ringtone == QLatin1String("Mute") || ringtone == QLatin1String("Default")) { + const auto &oldSetting = settings_->ringtone(); + if (oldSetting != QLatin1String("Mute") && oldSetting != QLatin1String("Default")) + ringtoneCombo_->removeItem(ringtoneCombo_->findText(oldSetting)); + settings_->setRingtone(ringtone); + } + }); connect(microphoneCombo_, static_cast(&QComboBox::currentTextChanged), diff --git a/src/UserSettingsPage.h b/src/UserSettingsPage.h index 0b2dc4fb..bbedb11e 100644 --- a/src/UserSettingsPage.h +++ b/src/UserSettingsPage.h @@ -291,10 +291,11 @@ signals: private: // Default to system theme if QT_QPA_PLATFORMTHEME var is set. - QString defaultTheme_ = - QProcessEnvironment::systemEnvironment().value(QStringLiteral("QT_QPA_PLATFORMTHEME"), QLatin1String("")).isEmpty() - ? "light" - : "system"; + QString defaultTheme_ = QProcessEnvironment::systemEnvironment() + .value(QStringLiteral("QT_QPA_PLATFORMTHEME"), QLatin1String("")) + .isEmpty() + ? "light" + : "system"; QString theme_; bool messageHoverHighlight_; bool enlargeEmojiOnlyMessages_; diff --git a/src/Utils.cpp b/src/Utils.cpp index 15557d56..6fba079c 100644 --- a/src/Utils.cpp +++ b/src/Utils.cpp @@ -237,8 +237,8 @@ utils::getMessageDescription(const TimelineEvent &event, DescInfo info; info.userid = sender; - info.body = - QStringLiteral(" %1").arg(messageDescription(username, QLatin1String(""), sender == localUser)); + info.body = QStringLiteral(" %1").arg( + messageDescription(username, QLatin1String(""), sender == localUser)); info.timestamp = msg->origin_server_ts; info.descriptiveTime = utils::descriptiveTime(ts); info.event_id = QString::fromStdString(msg->event_id); @@ -402,8 +402,9 @@ utils::linkifyMessage(const QString &body) // Convert to valid XML. auto doc = body; doc.replace(conf::strings::url_regex, conf::strings::url_html); - doc.replace(QRegularExpression(QStringLiteral("\\b(?(matrix:[\\S]{5,}))(?![\"'])\\b")), - conf::strings::url_html); + doc.replace( + QRegularExpression(QStringLiteral("\\b(?(matrix:[\\S]{5,}))(?![\"'])\\b")), + conf::strings::url_html); return doc; } @@ -555,7 +556,8 @@ utils::markdownToHtml(const QString &text, bool rainbowify) auto result = linkifyMessage(escapeBlacklistedHtml(QString::fromStdString(html))).trimmed(); - if (result.count(QStringLiteral("

")) == 1 && result.startsWith(QLatin1String("

")) && result.endsWith(QLatin1String("

"))) { + if (result.count(QStringLiteral("

")) == 1 && result.startsWith(QLatin1String("

")) && + result.endsWith(QLatin1String("

"))) { result = result.mid(3, result.size() - 3 - 4); } diff --git a/src/encryption/Olm.cpp b/src/encryption/Olm.cpp index 0004a40c..38b38476 100644 --- a/src/encryption/Olm.cpp +++ b/src/encryption/Olm.cpp @@ -1220,6 +1220,7 @@ send_encrypted_to_device_messages(const std::mapdevice_keys.size()); for (const auto &[device, keys] : deviceKeys->device_keys) { (void)keys; deviceTargets.push_back(device); diff --git a/src/main.cpp b/src/main.cpp index d98ef029..cae97158 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -185,8 +185,7 @@ main(int argc, char *argv[]) // name is set. It only exists to keep Qt from complaining about the --profile/-p // option and thereby crashing the app. QCommandLineOption configName( - QStringList() << QStringLiteral("p") - << QStringLiteral("profile"), + QStringList() << QStringLiteral("p") << QStringLiteral("profile"), QCoreApplication::tr("Create a unique profile, which allows you to log into several " "accounts at the same time and start multiple instances of nheko."), QCoreApplication::tr("profile"), @@ -252,11 +251,15 @@ main(int argc, char *argv[]) QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedKingdom)); QTranslator qtTranslator; - qtTranslator.load(QLocale(), QStringLiteral("qt"), QStringLiteral("_"), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); + qtTranslator.load(QLocale(), + QStringLiteral("qt"), + QStringLiteral("_"), + QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&qtTranslator); QTranslator appTranslator; - appTranslator.load(QLocale(), QStringLiteral("nheko"), QStringLiteral("_"), QStringLiteral(":/translations")); + appTranslator.load( + QLocale(), QStringLiteral("nheko"), QStringLiteral("_"), QStringLiteral(":/translations")); app.installTranslator(&appTranslator); MainWindow w; @@ -304,7 +307,8 @@ main(int argc, char *argv[]) QObject::disconnect(uriConnection); }); } - QDesktopServices::setUrlHandler(QStringLiteral("matrix"), ChatPage::instance(), "handleMatrixUri"); + QDesktopServices::setUrlHandler( + QStringLiteral("matrix"), ChatPage::instance(), "handleMatrixUri"); #if defined(Q_OS_MAC) // Temporary solution for the emoji picker until diff --git a/src/notifications/ManagerLinux.cpp b/src/notifications/ManagerLinux.cpp index 3f7a6b5d..ea46f5d7 100644 --- a/src/notifications/ManagerLinux.cpp +++ b/src/notifications/ManagerLinux.cpp @@ -108,7 +108,8 @@ NotificationsManager::postNotification(const mtx::responses::Notification ¬if if (hasImages_ && mtx::accessors::msg_type(notification.event) == mtx::events::MessageType::Image) { MxcImageProvider::download( - QString::fromStdString(mtx::accessors::url(notification.event)).remove(QStringLiteral("mxc://")), + QString::fromStdString(mtx::accessors::url(notification.event)) + .remove(QStringLiteral("mxc://")), QSize(200, 80), [postNotif, notification, template_](QString, QSize, QImage, QString imgPath) { if (imgPath.isEmpty()) @@ -184,9 +185,9 @@ NotificationsManager::systemPostNotification(const QString &room_id, // TODO(Nico): Look into what to actually put there. argumentList << (QStringList(QStringLiteral("default")) << QLatin1String("") << QStringLiteral("inline-reply") - << QLatin1String("")); // actions - argumentList << hints; // hints - argumentList << (int)-1; // timeout in ms + << QLatin1String("")); // actions + argumentList << hints; // hints + argumentList << (int)-1; // timeout in ms QDBusPendingCall call = dbus.asyncCallWithArgumentList(QStringLiteral("Notify"), argumentList); auto watcher = new QDBusPendingCallWatcher{call, this}; diff --git a/src/timeline/CommunitiesModel.cpp b/src/timeline/CommunitiesModel.cpp index fec08d60..520a0372 100644 --- a/src/timeline/CommunitiesModel.cpp +++ b/src/timeline/CommunitiesModel.cpp @@ -293,6 +293,7 @@ CommunitiesModel::FlatTree::storeCollapsed() int depth = -1; QStringList current; + elements.reserve(static_cast(tree.size())); for (const auto &e : tree) { if (e.depth > depth) { diff --git a/src/timeline/EventStore.cpp b/src/timeline/EventStore.cpp index 0a19483d..209464b7 100644 --- a/src/timeline/EventStore.cpp +++ b/src/timeline/EventStore.cpp @@ -527,6 +527,7 @@ EventStore::reactions(const std::string &event_id) } QVariantList temp; + temp.reserve(static_cast(reactions.size())); for (auto &reaction : reactions) { const auto &agg = aggregation[reaction.key_.toStdString()]; reaction.count_ = agg.count; diff --git a/src/timeline/InputBar.cpp b/src/timeline/InputBar.cpp index 832016e2..767dccc3 100644 --- a/src/timeline/InputBar.cpp +++ b/src/timeline/InputBar.cpp @@ -56,7 +56,8 @@ InputBar::insertMimeData(const QMimeData *md) if (!md) return; - nhlog::ui()->debug("Got mime formats: {}", md->formats().join(QStringLiteral(", ")).toStdString()); + nhlog::ui()->debug("Got mime formats: {}", + md->formats().join(QStringLiteral(", ")).toStdString()); const auto formats = md->formats().filter(QStringLiteral("/")); const auto image = formats.filter(QStringLiteral("image/"), Qt::CaseInsensitive); const auto audio = formats.filter(QStringLiteral("audio/"), Qt::CaseInsensitive); @@ -140,7 +141,8 @@ InputBar::updateAtRoom(const QString &t) auto start = finder.position(); finder.toNextBoundary(); auto end = finder.position(); - if (start > 0 && end - start >= 4 && t.mid(start, end - start) == QLatin1String("room") && + if (start > 0 && end - start >= 4 && + t.mid(start, end - start) == QLatin1String("room") && t.at(start - 1) == QChar('@')) { roomMention = true; break; @@ -660,13 +662,15 @@ InputBar::showPreview(const QMimeData &source, const QString &path, const QStrin previewDialog_->setAttribute(Qt::WA_DeleteOnClose); // Force SVG to _not_ be handled as an image, but as raw data - if (source.hasImage() && (formats.empty() || formats.front() != QLatin1String("image/svg+xml"))) { + if (source.hasImage() && + (formats.empty() || formats.front() != QLatin1String("image/svg+xml"))) { if (!formats.empty() && formats.front().startsWith(QLatin1String("image/"))) { // known format, keep as-is previewDialog_->setPreview(qvariant_cast(source.imageData()), formats.front()); } else { // unknown image format, default to image/png - previewDialog_->setPreview(qvariant_cast(source.imageData()), QStringLiteral("image/png")); + previewDialog_->setPreview(qvariant_cast(source.imageData()), + QStringLiteral("image/png")); } } else if (!path.isEmpty()) previewDialog_->setPreview(path); diff --git a/src/timeline/RoomlistModel.cpp b/src/timeline/RoomlistModel.cpp index 0757d27e..2dfe5d6f 100644 --- a/src/timeline/RoomlistModel.cpp +++ b/src/timeline/RoomlistModel.cpp @@ -90,6 +90,7 @@ RoomlistModel::data(const QModelIndex &index, int role) const if (role == Roles::ParentSpaces) { auto parents = cache::client()->getParentRoomIds(roomid.toStdString()); QStringList list; + list.reserve(static_cast(parents.size())); for (const auto &t : parents) list.push_back(QString::fromStdString(t)); return list; @@ -98,7 +99,8 @@ RoomlistModel::data(const QModelIndex &index, int role) const } else if (role == Roles::IsDirect) { return directChatToUser.count(roomid) > 0; } else if (role == Roles::DirectChatOtherUserId) { - return directChatToUser.count(roomid) ? directChatToUser.at(roomid).front() : QLatin1String(""); + return directChatToUser.count(roomid) ? directChatToUser.at(roomid).front() + : QLatin1String(""); } if (models.contains(roomid)) { @@ -113,7 +115,7 @@ RoomlistModel::data(const QModelIndex &index, int role) const case Roles::Time: return room->lastMessage().descriptiveTime; case Roles::Timestamp: - return QVariant(static_cast(room->lastMessage().timestamp)); + return QVariant{static_cast(room->lastMessage().timestamp)}; case Roles::HasUnreadMessages: return this->roomReadStatus.count(roomid) && this->roomReadStatus.at(roomid); case Roles::HasLoudNotification: @@ -129,6 +131,7 @@ RoomlistModel::data(const QModelIndex &index, int role) const case Roles::Tags: { auto info = cache::singleRoomInfo(roomid.toStdString()); QStringList list; + list.reserve(static_cast(info.tags.size())); for (const auto &t : info.tags) list.push_back(QString::fromStdString(t)); return list; @@ -148,7 +151,7 @@ RoomlistModel::data(const QModelIndex &index, int role) const case Roles::Time: return QString(); case Roles::Timestamp: - return QVariant(static_cast(0)); + return QVariant{static_cast(0)}; case Roles::HasUnreadMessages: case Roles::HasLoudNotification: return false; @@ -177,7 +180,7 @@ RoomlistModel::data(const QModelIndex &index, int role) const case Roles::Time: return QString(); case Roles::Timestamp: - return QVariant(static_cast(0)); + return QVariant{static_cast(0)}; case Roles::HasUnreadMessages: case Roles::HasLoudNotification: return false; diff --git a/src/timeline/RoomlistModel.h b/src/timeline/RoomlistModel.h index 8bffccc9..459b8788 100644 --- a/src/timeline/RoomlistModel.h +++ b/src/timeline/RoomlistModel.h @@ -159,7 +159,8 @@ public slots: } void joinPreview(QString roomid) { - roomlistmodel->joinPreview(roomid, filterType == FilterBy::Space ? filterStr : QLatin1String("")); + roomlistmodel->joinPreview(roomid, + filterType == FilterBy::Space ? filterStr : QLatin1String("")); } void acceptInvite(QString roomid) { roomlistmodel->acceptInvite(roomid); } void declineInvite(QString roomid) { roomlistmodel->declineInvite(roomid); } diff --git a/src/timeline/TimelineModel.cpp b/src/timeline/TimelineModel.cpp index ae3094ab..a95339cc 100644 --- a/src/timeline/TimelineModel.cpp +++ b/src/timeline/TimelineModel.cpp @@ -503,7 +503,7 @@ TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int r switch (role) { case IsSender: - return QVariant(acc::sender(event) == http::client()->user_id().to_string()); + return {acc::sender(event) == http::client()->user_id().to_string()}; case UserId: return QVariant(QString::fromStdString(acc::sender(event))); case UserName: @@ -512,12 +512,12 @@ TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int r case Day: { QDateTime prevDate = origin_server_ts(event); prevDate.setTime(QTime()); - return QVariant(prevDate.toMSecsSinceEpoch()); + return {prevDate.toMSecsSinceEpoch()}; } case Timestamp: return QVariant(origin_server_ts(event)); case Type: - return QVariant(toRoomEventType(event)); + return {toRoomEventType(event)}; case TypeString: return QVariant(toRoomEventTypeString(event)); case IsOnlyEmoji: { @@ -530,17 +530,18 @@ TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int r if (utils::codepointIsEmoji(code)) { emojiCount++; } else { - return QVariant(0); + return {0}; } } - return QVariant(emojiCount); + return {emojiCount}; } case Body: return QVariant(utils::replaceEmoji(QString::fromStdString(body(event)).toHtmlEscaped())); case FormattedBody: { const static QRegularExpression replyFallback( - QStringLiteral(".*"), QRegularExpression::DotMatchesEverythingOption); + QStringLiteral(".*"), + QRegularExpression::DotMatchesEverythingOption); auto ascent = QFontMetrics(UserSettings::instance()->font()).ascent(); @@ -574,7 +575,8 @@ TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int r // Construct image parameters later used by MxcImageProvider. QString imgParams; if (curImg.contains(QLatin1String("height"))) { - const static QRegularExpression matchImgHeight(QStringLiteral("height=([\"\']?)(\\d+)([\"\']?)")); + const static QRegularExpression matchImgHeight( + QStringLiteral("height=([\"\']?)(\\d+)([\"\']?)")); // Make emoticons twice as high as the font. if (curImg.contains(QLatin1String("data-mx-emoticon"))) { imgReplacement = @@ -587,11 +589,11 @@ TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int r // Replace src in current . const static QRegularExpression matchImgUri(QStringLiteral("src=\"mxc://([^\"]*)\"")); imgReplacement.replace(matchImgUri, - QString("src=\"image://mxcImage/\\1%1\"").arg(imgParams)); + QStringLiteral(R"(src="image://mxcImage/\1%1")").arg(imgParams)); // Same regex but for single quotes around the src const static QRegularExpression matchImgUri2(QStringLiteral("src=\'mxc://([^\']*)\'")); imgReplacement.replace(matchImgUri2, - QString("src=\'image://mxcImage/\\1%1\'").arg(imgParams)); + QStringLiteral("src=\'image://mxcImage/\\1%1\'").arg(imgParams)); // Replace in formattedBody_ with our new . formattedBody_.replace(curImg, imgReplacement); @@ -623,7 +625,7 @@ TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int r double prop = media_height(event) / (double)w; - return QVariant(prop > 0 ? prop : 1.); + return {prop > 0 ? prop : 1.}; } case EventId: { if (auto replaces = relations(event).replaces()) @@ -651,10 +653,10 @@ TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int r return qml_mtx_events::Received; } case IsEdited: - return QVariant(relations(event).replaces().has_value()); + return {relations(event).replaces().has_value()}; case IsEditable: - return QVariant(!is_state_event(event) && - mtx::accessors::sender(event) == http::client()->user_id().to_string()); + return {!is_state_event(event) && + mtx::accessors::sender(event) == http::client()->user_id().to_string()}; case IsEncrypted: { auto id = event_id(event); auto encrypted_event = events.get(id, "", false); @@ -693,8 +695,10 @@ TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int r return QVariant( utils::replaceEmoji(QString::fromStdString(room_name(event)).toHtmlEscaped())); case RoomTopic: - return QVariant(utils::replaceEmoji(utils::linkifyMessage( - QString::fromStdString(room_topic(event)).toHtmlEscaped().replace(QLatin1String("\n"), QLatin1String("
"))))); + return QVariant(utils::replaceEmoji( + utils::linkifyMessage(QString::fromStdString(room_topic(event)) + .toHtmlEscaped() + .replace(QLatin1String("\n"), QLatin1String("
"))))); case CallType: return QVariant(QString::fromStdString(call_type(event))); case Dump: { @@ -736,7 +740,7 @@ TimelineModel::data(const mtx::events::collections::TimelineEvents &event, int r case RelatedEventCacheBuster: return relatedEventCacheBuster; default: - return QVariant(); + return {}; } } @@ -746,7 +750,7 @@ TimelineModel::data(const QModelIndex &index, int role) const using namespace mtx::accessors; namespace acc = mtx::accessors; if (index.row() < 0 && index.row() >= rowCount()) - return QVariant(); + return {}; // HACK(Nico): fetchMore likes to break with dynamically sized delegates and reuseItems if (index.row() + 1 == rowCount() && !m_paginationInProgress) @@ -760,10 +764,10 @@ TimelineModel::data(const QModelIndex &index, int role) const if (role == PreviousMessageDay || role == PreviousMessageUserId) { int prevIdx = rowCount() - index.row() - 2; if (prevIdx < 0) - return QVariant(); + return {}; auto tempEv = events.get(prevIdx); if (!tempEv) - return QVariant(); + return {}; if (role == PreviousMessageUserId) return data(*tempEv, UserId); else @@ -778,7 +782,7 @@ TimelineModel::dataById(const QString &id, int role, const QString &relatedTo) { if (auto event = events.get(id.toStdString(), relatedTo.toStdString())) return data(*event, role); - return QVariant(); + return {}; } bool @@ -1623,7 +1627,7 @@ TimelineModel::cacheMedia(const QString &eventId, void TimelineModel::cacheMedia(const QString &eventId) { - cacheMedia(eventId, NULL); + cacheMedia(eventId, nullptr); } void @@ -1739,7 +1743,7 @@ TimelineModel::formatTypingUsers(const std::vector &users, const QColor (int)users.size()); if (users.empty()) { - return QString(); + return {}; } QStringList uidWithoutLast; @@ -1774,6 +1778,7 @@ TimelineModel::formatTypingUsers(const std::vector &users, const QColor return coloredUsername; }; + uidWithoutLast.reserve(static_cast(users.size())); for (size_t i = 0; i + 1 < users.size(); i++) { uidWithoutLast.append(formatUser(users[i])); } @@ -1786,11 +1791,11 @@ TimelineModel::formatJoinRuleEvent(const QString &id) { mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), ""); if (!e) - return QString(); + return {}; auto event = std::get_if>(e); if (!event) - return QString(); + return {}; QString user = QString::fromStdString(event->sender); QString name = utils::replaceEmoji(displayName(user)); @@ -1814,7 +1819,7 @@ TimelineModel::formatJoinRuleEvent(const QString &id) } default: // Currently, knock and private are reserved keywords and not implemented in Matrix. - return QString(); + return {}; } } @@ -1823,11 +1828,11 @@ TimelineModel::formatGuestAccessEvent(const QString &id) { mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), ""); if (!e) - return QString(); + return {}; auto event = std::get_if>(e); if (!event) - return QString(); + return {}; QString user = QString::fromStdString(event->sender); QString name = utils::replaceEmoji(displayName(user)); @@ -1838,7 +1843,7 @@ TimelineModel::formatGuestAccessEvent(const QString &id) case mtx::events::state::AccessState::Forbidden: return tr("%1 has closed the room to guest access.").arg(name); default: - return QString(); + return {}; } } @@ -1847,12 +1852,12 @@ TimelineModel::formatHistoryVisibilityEvent(const QString &id) { mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), ""); if (!e) - return QString(); + return {}; auto event = std::get_if>(e); if (!event) - return QString(); + return {}; QString user = QString::fromStdString(event->sender); QString name = utils::replaceEmoji(displayName(user)); @@ -1870,7 +1875,7 @@ TimelineModel::formatHistoryVisibilityEvent(const QString &id) return tr("%1 set the room history visible to members since they joined the room.") .arg(name); default: - return QString(); + return {}; } } @@ -1879,7 +1884,7 @@ TimelineModel::formatPowerLevelEvent(const QString &id) { mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), ""); if (!e) - return QString(); + return {}; auto event = std::get_if>(e); if (!event) @@ -1924,7 +1929,7 @@ TimelineModel::formatRedactedEvent(const QString &id) } else { pair[QStringLiteral("first")] = tr("Removed by %1 because: %2").arg(redactedName, reason); pair[QStringLiteral("second")] = tr("%1 (%2) removed this message at %3\nReason: %4") - .arg(redactedName, redactedUser, dateTime, reason); + .arg(redactedName, redactedUser, dateTime, reason); } return pair; @@ -1980,11 +1985,11 @@ TimelineModel::formatMemberEvent(const QString &id) { mtx::events::collections::TimelineEvents *e = events.get(id.toStdString(), ""); if (!e) - return QString(); + return {}; auto event = std::get_if>(e); if (!event) - return QString(); + return {}; mtx::events::StateEvent *prevEvent = nullptr; if (!event->unsigned_data.replaces_state.empty()) { @@ -2038,7 +2043,7 @@ TimelineModel::formatMemberEvent(const QString &id) break; case Membership::Leave: if (!prevEvent) // Should only ever happen temporarily - return QString(); + return {}; if (prevEvent->content.membership == Membership::Invite) { if (event->state_key == event->sender) @@ -2163,7 +2168,7 @@ TimelineModel::roomName() const auto info = cache::getRoomInfo({room_id_.toStdString()}); if (!info.count(room_id_)) - return QString(); + return {}; else return utils::replaceEmoji(QString::fromStdString(info[room_id_].name).toHtmlEscaped()); } @@ -2174,7 +2179,7 @@ TimelineModel::plainRoomName() const auto info = cache::getRoomInfo({room_id_.toStdString()}); if (!info.count(room_id_)) - return QString(); + return {}; else return QString::fromStdString(info[room_id_].name); } @@ -2185,7 +2190,7 @@ TimelineModel::roomAvatarUrl() const auto info = cache::getRoomInfo({room_id_.toStdString()}); if (!info.count(room_id_)) - return QString(); + return {}; else return QString::fromStdString(info[room_id_].avatar_url); } @@ -2196,7 +2201,7 @@ TimelineModel::roomTopic() const auto info = cache::getRoomInfo({room_id_.toStdString()}); if (!info.count(room_id_)) - return QString(); + return {}; else return utils::replaceEmoji( utils::linkifyMessage(QString::fromStdString(info[room_id_].topic).toHtmlEscaped())); @@ -2244,5 +2249,5 @@ TimelineModel::directChatOtherUserId() const id = member.user_id; return id; } else - return QString(); + return {}; } diff --git a/src/timeline/TimelineModel.h b/src/timeline/TimelineModel.h index afb712da..b14c7a18 100644 --- a/src/timeline/TimelineModel.h +++ b/src/timeline/TimelineModel.h @@ -286,6 +286,7 @@ public: { auto list = events.reactions(event_id); std::vector<::Reaction> vec; + vec.reserve(list.size()); for (const auto &r : list) vec.push_back(r.value()); return vec; diff --git a/src/timeline/TimelineViewManager.cpp b/src/timeline/TimelineViewManager.cpp index 6928b95b..8e94989b 100644 --- a/src/timeline/TimelineViewManager.cpp +++ b/src/timeline/TimelineViewManager.cpp @@ -103,10 +103,12 @@ TimelineViewManager::updateColorPalette() if (ChatPage::instance()->userSettings()->theme() == QLatin1String("light")) { view->rootContext()->setContextProperty(QStringLiteral("currentActivePalette"), QPalette()); - view->rootContext()->setContextProperty(QStringLiteral("currentInactivePalette"), QPalette()); + view->rootContext()->setContextProperty(QStringLiteral("currentInactivePalette"), + QPalette()); } else if (ChatPage::instance()->userSettings()->theme() == QLatin1String("dark")) { view->rootContext()->setContextProperty(QStringLiteral("currentActivePalette"), QPalette()); - view->rootContext()->setContextProperty(QStringLiteral("currentInactivePalette"), QPalette()); + view->rootContext()->setContextProperty(QStringLiteral("currentInactivePalette"), + QPalette()); } else { view->rootContext()->setContextProperty(QStringLiteral("currentActivePalette"), QPalette()); view->rootContext()->setContextProperty(QStringLiteral("currentInactivePalette"), nullptr); @@ -161,12 +163,20 @@ TimelineViewManager::TimelineViewManager(CallManager *callManager, ChatPage *par qRegisterMetaType>(); - qmlRegisterUncreatableMetaObject( - qml_mtx_events::staticMetaObject, "im.nheko", 1, 0, "MtxEvent", QStringLiteral("Can't instantiate enum!")); + qmlRegisterUncreatableMetaObject(qml_mtx_events::staticMetaObject, + "im.nheko", + 1, + 0, + "MtxEvent", + QStringLiteral("Can't instantiate enum!")); qmlRegisterUncreatableMetaObject( olm::staticMetaObject, "im.nheko", 1, 0, "Olm", QStringLiteral("Can't instantiate enum!")); - qmlRegisterUncreatableMetaObject( - crypto::staticMetaObject, "im.nheko", 1, 0, "Crypto", QStringLiteral("Can't instantiate enum!")); + qmlRegisterUncreatableMetaObject(crypto::staticMetaObject, + "im.nheko", + 1, + 0, + "Crypto", + QStringLiteral("Can't instantiate enum!")); qmlRegisterUncreatableMetaObject(verification::staticMetaObject, "im.nheko", 1, @@ -181,11 +191,23 @@ TimelineViewManager::TimelineViewManager(CallManager *callManager, ChatPage *par qmlRegisterType("im.nheko", 1, 0, "MxcAnimatedImage"); qmlRegisterType("im.nheko", 1, 0, "MxcMedia"); qmlRegisterUncreatableType( - "im.nheko", 1, 0, "DeviceVerificationFlow", QStringLiteral("Can't create verification flow from QML!")); + "im.nheko", + 1, + 0, + "DeviceVerificationFlow", + QStringLiteral("Can't create verification flow from QML!")); qmlRegisterUncreatableType( - "im.nheko", 1, 0, "UserProfileModel", QStringLiteral("UserProfile needs to be instantiated on the C++ side")); + "im.nheko", + 1, + 0, + "UserProfileModel", + QStringLiteral("UserProfile needs to be instantiated on the C++ side")); qmlRegisterUncreatableType( - "im.nheko", 1, 0, "MemberList", QStringLiteral("MemberList needs to be instantiated on the C++ side")); + "im.nheko", + 1, + 0, + "MemberList", + QStringLiteral("MemberList needs to be instantiated on the C++ side")); qmlRegisterUncreatableType( "im.nheko", 1, @@ -207,7 +229,11 @@ TimelineViewManager::TimelineViewManager(CallManager *callManager, ChatPage *par "SingleImagePackModel", QStringLiteral("SingleImagePackModel needs to be instantiated on the C++ side")); qmlRegisterUncreatableType( - "im.nheko", 1, 0, "InviteesModel", QStringLiteral("InviteesModel needs to be instantiated on the C++ side")); + "im.nheko", + 1, + 0, + "InviteesModel", + QStringLiteral("InviteesModel needs to be instantiated on the C++ side")); qmlRegisterUncreatableType( "im.nheko", 1, @@ -270,8 +296,12 @@ TimelineViewManager::TimelineViewManager(CallManager *callManager, ChatPage *par qmlRegisterType("im.nheko.EmojiModel", 1, 0, "EmojiModel"); qmlRegisterUncreatableType( "im.nheko.EmojiModel", 1, 0, "Emoji", QStringLiteral("Used by emoji models")); - qmlRegisterUncreatableMetaObject( - emoji::staticMetaObject, "im.nheko.EmojiModel", 1, 0, "EmojiCategory", QStringLiteral("Error: Only enums")); + qmlRegisterUncreatableMetaObject(emoji::staticMetaObject, + "im.nheko.EmojiModel", + 1, + 0, + "EmojiCategory", + QStringLiteral("Error: Only enums")); qmlRegisterType("im.nheko", 1, 0, "RoomDirectoryModel"); @@ -404,15 +434,17 @@ TimelineViewManager::openImageOverlay(QString mxcUrl, QString eventId) return; } - MxcImageProvider::download( - mxcUrl.remove(QStringLiteral("mxc://")), QSize(), [this, eventId](QString, QSize, QImage img, QString) { - if (img.isNull()) { - nhlog::ui()->error("Error when retrieving image for overlay."); - return; - } + MxcImageProvider::download(mxcUrl.remove(QStringLiteral("mxc://")), + QSize(), + [this, eventId](QString, QSize, QImage img, QString) { + if (img.isNull()) { + nhlog::ui()->error( + "Error when retrieving image for overlay."); + return; + } - emit openImageOverlayInternalCb(eventId, std::move(img)); - }); + emit openImageOverlayInternalCb(eventId, std::move(img)); + }); } void diff --git a/src/ui/NhekoGlobalObject.cpp b/src/ui/NhekoGlobalObject.cpp index b6122ac9..56c0d9f0 100644 --- a/src/ui/NhekoGlobalObject.cpp +++ b/src/ui/NhekoGlobalObject.cpp @@ -28,8 +28,8 @@ void Nheko::updateUserProfile() { if (cache::client() && cache::client()->isInitialized()) - currentUser_.reset( - new UserProfile(QLatin1String(""), utils::localUser(), ChatPage::instance()->timelineManager())); + currentUser_.reset(new UserProfile( + QLatin1String(""), utils::localUser(), ChatPage::instance()->timelineManager())); else currentUser_.reset(); emit profileChanged(); diff --git a/src/ui/RoomSettings.cpp b/src/ui/RoomSettings.cpp index 038c2e89..b9042524 100644 --- a/src/ui/RoomSettings.cpp +++ b/src/ui/RoomSettings.cpp @@ -234,8 +234,10 @@ RoomSettings::roomName() const QString RoomSettings::roomTopic() const { - return utils::replaceEmoji(utils::linkifyMessage( - QString::fromStdString(info_.topic).toHtmlEscaped().replace(QLatin1String("\n"), QLatin1String("
")))); + return utils::replaceEmoji( + utils::linkifyMessage(QString::fromStdString(info_.topic) + .toHtmlEscaped() + .replace(QLatin1String("\n"), QLatin1String("
")))); } QString diff --git a/src/ui/UserProfile.cpp b/src/ui/UserProfile.cpp index cd9e170d..19bbb007 100644 --- a/src/ui/UserProfile.cpp +++ b/src/ui/UserProfile.cpp @@ -232,6 +232,7 @@ UserProfile::updateVerificationStatus() this->isUserVerified = verificationStatus.user_verified; emit userStatusChanged(); + deviceInfo.reserve(devices.size()); for (const auto &d : devices) { auto device = d.second; verification::Status verified = @@ -244,9 +245,9 @@ UserProfile::updateVerificationStatus() if (isSelf() && device.device_id == ::http::client()->device_id()) verified = verification::Status::SELF; - deviceInfo.push_back({QString::fromStdString(d.first), - QString::fromStdString(device.unsigned_info.device_display_name), - verified}); + deviceInfo.emplace_back(QString::fromStdString(d.first), + QString::fromStdString(device.unsigned_info.device_display_name), + verified); } // For self, also query devices without keys @@ -270,17 +271,17 @@ UserProfile::updateVerificationStatus() found = true; // Gottem! Let's fill in the blanks e.lastIp = QString::fromStdString(d.last_seen_ip); - e.lastTs = d.last_seen_ts; + e.lastTs = static_cast(d.last_seen_ts); break; } } // No entry? Let's add one. if (!found) { - deviceInfo.push_back({QString::fromStdString(d.device_id), - QString::fromStdString(d.display_name), - verification::NOT_APPLICABLE, - QString::fromStdString(d.last_seen_ip), - d.last_seen_ts}); + deviceInfo.emplace_back(QString::fromStdString(d.device_id), + QString::fromStdString(d.display_name), + verification::NOT_APPLICABLE, + QString::fromStdString(d.last_seen_ip), + d.last_seen_ts); } } diff --git a/src/voip/CallManager.cpp b/src/voip/CallManager.cpp index 70ea326d..8ea0c638 100644 --- a/src/voip/CallManager.cpp +++ b/src/voip/CallManager.cpp @@ -70,7 +70,8 @@ CallManager::CallManager(QObject *parent) QTimer::singleShot(timeoutms_, this, [this, callid]() { if (session_.state() == webrtc::State::OFFERSENT && callid == callid_) { hangUp(CallHangUp::Reason::InviteTimeOut); - emit ChatPage::instance()->showNotification(QStringLiteral("The remote side failed to pick up.")); + emit ChatPage::instance()->showNotification( + QStringLiteral("The remote side failed to pick up.")); } }); }); @@ -177,7 +178,8 @@ CallManager::sendInvite(const QString &roomid, CallType callType, unsigned int w auto roomInfo = cache::singleRoomInfo(roomid.toStdString()); if (roomInfo.member_count != 2) { - emit ChatPage::instance()->showNotification(QStringLiteral("Calls are limited to 1:1 rooms.")); + emit ChatPage::instance()->showNotification( + QStringLiteral("Calls are limited to 1:1 rooms.")); return; } @@ -291,8 +293,9 @@ CallManager::handleEvent(const RoomEvent &callInviteEvent) const QString &ringtone = ChatPage::instance()->userSettings()->ringtone(); if (ringtone != QLatin1String("Mute")) - playRingtone(ringtone == QLatin1String("Default") ? QUrl(QStringLiteral("qrc:/media/media/ring.ogg")) - : QUrl::fromLocalFile(ringtone), + playRingtone(ringtone == QLatin1String("Default") + ? QUrl(QStringLiteral("qrc:/media/media/ring.ogg")) + : QUrl::fromLocalFile(ringtone), true); roomid_ = QString::fromStdString(callInviteEvent.room_id); callid_ = callInviteEvent.content.call_id; @@ -370,7 +373,8 @@ CallManager::handleEvent(const RoomEvent &callAnswerEvent) if (callAnswerEvent.sender == utils::localUser().toStdString() && callid_ == callAnswerEvent.content.call_id) { if (!isOnCall()) { - emit ChatPage::instance()->showNotification(QStringLiteral("Call answered on another device.")); + emit ChatPage::instance()->showNotification( + QStringLiteral("Call answered on another device.")); stopRingtone(); haveCallInvite_ = false; emit newInviteState(); diff --git a/src/voip/WebRTCSession.cpp b/src/voip/WebRTCSession.cpp index 6dc5e9ae..b93bbb5c 100644 --- a/src/voip/WebRTCSession.cpp +++ b/src/voip/WebRTCSession.cpp @@ -44,12 +44,20 @@ WebRTCSession::WebRTCSession() : devices_(CallDevices::instance()) { qRegisterMetaType(); - qmlRegisterUncreatableMetaObject( - webrtc::staticMetaObject, "im.nheko", 1, 0, "CallType", QStringLiteral("Can't instantiate enum")); + qmlRegisterUncreatableMetaObject(webrtc::staticMetaObject, + "im.nheko", + 1, + 0, + "CallType", + QStringLiteral("Can't instantiate enum")); qRegisterMetaType(); - qmlRegisterUncreatableMetaObject( - webrtc::staticMetaObject, "im.nheko", 1, 0, "WebRTCState", QStringLiteral("Can't instantiate enum")); + qmlRegisterUncreatableMetaObject(webrtc::staticMetaObject, + "im.nheko", + 1, + 0, + "WebRTCState", + QStringLiteral("Can't instantiate enum")); connect(this, &WebRTCSession::stateChanged, this, &WebRTCSession::setState); init();