From 23ec80ccba5604aebcd73e9975bf5b743b685a74 Mon Sep 17 00:00:00 2001 From: blue Date: Tue, 15 Aug 2023 12:28:25 -0300 Subject: [PATCH] cleanup some warnings suppression --- CMakeLists.txt | 1 + core/account.cpp | 6 +- core/handlers/messagehandler.cpp | 152 ++++---- core/handlers/omemohandler.cpp | 1 + core/handlers/rosterhandler.cpp | 1 + core/signalcatcher.cpp | 18 +- main/application.cpp | 196 ++++------- shared/CMakeLists.txt | 1 + shared/defines.h | 24 ++ shared/identity.cpp | 4 + shared/shared.h | 1 + ui/models/accounts.cpp | 85 ++--- ui/models/info/emails.cpp | 36 +- ui/models/info/omemo/keys.cpp | 12 +- ui/models/info/phones.cpp | 44 +-- ui/models/roster.cpp | 390 ++++++++------------- ui/utils/comboboxdelegate.cpp | 30 +- ui/utils/resizer.cpp | 13 +- ui/widgets/chat.cpp | 3 + ui/widgets/conversation.cpp | 135 +++---- ui/widgets/conversation.h | 3 +- ui/widgets/messageline/feedview.cpp | 91 ++--- ui/widgets/messageline/messagedelegate.cpp | 152 +++----- ui/widgets/messageline/messagedelegate.h | 2 + ui/widgets/messageline/messagefeed.cpp | 131 +++---- ui/widgets/room.cpp | 22 +- 26 files changed, 630 insertions(+), 924 deletions(-) create mode 100644 shared/defines.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 06c4344..d29bb4f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,6 +2,7 @@ cmake_minimum_required(VERSION 3.5) project(squawk VERSION 0.2.3 LANGUAGES CXX) cmake_policy(SET CMP0076 NEW) +cmake_policy(SET CMP0077 NEW) cmake_policy(SET CMP0079 NEW) set(CMAKE_CXX_STANDARD 17) diff --git a/core/account.cpp b/core/account.cpp index 736d5ae..b06f51b 100644 --- a/core/account.cpp +++ b/core/account.cpp @@ -21,6 +21,8 @@ #include +#include "shared/defines.h" + Core::Account::Account( const QString& p_login, const QString& p_server, @@ -159,7 +161,8 @@ Core::Account::Account( logger->setLoggingType(QXmppLogger::SignalLogging); client.setLogger(logger); - QObject::connect(logger, &QXmppLogger::message, this, [](QXmppLogger::MessageType type, const QString& text){ + QObject::connect(logger, &QXmppLogger::message, this, [](QXmppLogger::MessageType type, const QString& text) { + SHARED_UNUSED(type); qDebug() << text; }); } @@ -511,6 +514,7 @@ void Core::Account::onMamResultsReceived(const QString& queryId, const QXmppResu } void Core::Account::onMamLog(QXmppLogger::MessageType type, const QString& msg) { + SHARED_UNUSED(type); qDebug() << "MAM MESSAGE LOG::"; qDebug() << msg; } diff --git a/core/handlers/messagehandler.cpp b/core/handlers/messagehandler.cpp index 020ab6f..3ed8dec 100644 --- a/core/handlers/messagehandler.cpp +++ b/core/handlers/messagehandler.cpp @@ -24,11 +24,9 @@ Core::MessageHandler::MessageHandler(Core::Account* account): acc(account), pendingStateMessages(), uploadingSlotsQueue() -{ -} +{} -void Core::MessageHandler::onMessageReceived(const QXmppMessage& msg) -{ +void Core::MessageHandler::onMessageReceived(const QXmppMessage& msg) { #if (QXMPP_VERSION) >= QT_VERSION_CHECK(1, 5, 0) #ifdef WITH_OMEMO switch (msg.encryptionMethod()) { @@ -83,9 +81,9 @@ void Core::MessageHandler::onMessageReceived(const QXmppMessage& msg) {"state", static_cast(Shared::Message::State::error)}, {"errorText", msg.error().text()} }; - if (cnt != nullptr) { + if (cnt != nullptr) cnt->changeMessage(id, cData); - } + emit acc->changeMessage(jid, id, cData); handled = true; } else { @@ -97,13 +95,11 @@ void Core::MessageHandler::onMessageReceived(const QXmppMessage& msg) qDebug() << "received a message with type \"Headline\", not sure what to do with it now, skipping"; break; } - if (!handled) { + if (!handled) logMessage(msg); - } } -bool Core::MessageHandler::handleChatMessage(const QXmppMessage& msg, bool outgoing, bool forwarded, bool guessing) -{ +bool Core::MessageHandler::handleChatMessage(const QXmppMessage& msg, bool outgoing, bool forwarded, bool guessing) { if (msg.body().size() != 0 || msg.outOfBandUrl().size() > 0) { Shared::Message sMsg(Shared::Message::chat); initializeMessage(sMsg, msg, outgoing, forwarded, guessing); @@ -138,8 +134,7 @@ bool Core::MessageHandler::handleChatMessage(const QXmppMessage& msg, bool outgo return false; } -bool Core::MessageHandler::handleGroupMessage(const QXmppMessage& msg, bool outgoing, bool forwarded, bool guessing) -{ +bool Core::MessageHandler::handleGroupMessage(const QXmppMessage& msg, bool outgoing, bool forwarded, bool guessing) { const QString& body(msg.body()); if (body.size() != 0) { @@ -182,8 +177,7 @@ bool Core::MessageHandler::handleGroupMessage(const QXmppMessage& msg, bool outg } -void Core::MessageHandler::initializeMessage(Shared::Message& target, const QXmppMessage& source, bool outgoing, bool forwarded, bool guessing) const -{ +void Core::MessageHandler::initializeMessage(Shared::Message& target, const QXmppMessage& source, bool outgoing, bool forwarded, bool guessing) const { const QDateTime& time(source.stamp()); QString id; #if (QXMPP_VERSION) >= QT_VERSION_CHECK(1, 3, 0) @@ -229,8 +223,7 @@ void Core::MessageHandler::initializeMessage(Shared::Message& target, const QXmp target.setOutOfBandUrl(oob); } -void Core::MessageHandler::logMessage(const QXmppMessage& msg, const QString& reason) -{ +void Core::MessageHandler::logMessage(const QXmppMessage& msg, const QString& reason) { qDebug() << reason; qDebug() << "- from: " << msg.from(); qDebug() << "- to: " << msg.to(); @@ -247,19 +240,16 @@ void Core::MessageHandler::logMessage(const QXmppMessage& msg, const QString& re } #if (QXMPP_VERSION) < QT_VERSION_CHECK(1, 5, 0) -void Core::MessageHandler::onCarbonMessageReceived(const QXmppMessage& msg) -{ +void Core::MessageHandler::onCarbonMessageReceived(const QXmppMessage& msg) { handleChatMessage(msg, false, true); } -void Core::MessageHandler::onCarbonMessageSent(const QXmppMessage& msg) -{ +void Core::MessageHandler::onCarbonMessageSent(const QXmppMessage& msg) { handleChatMessage(msg, true, true); } #endif -std::tuple Core::MessageHandler::getOriginalPendingMessageId(const QString& id) -{ +std::tuple Core::MessageHandler::getOriginalPendingMessageId(const QString& id) { std::tuple result({false, "", ""}); std::map::const_iterator itr = pendingStateMessages.find(id); if (itr != pendingStateMessages.end()) { @@ -268,11 +258,11 @@ std::tuple Core::MessageHandler::getOriginalPendingMessa std::map::const_iterator itrC = pendingCorrectionMessages.find(id); if (itrC != pendingCorrectionMessages.end()) { - if (itrC->second.size() > 0) { + if (itrC->second.size() > 0) std::get<1>(result) = itrC->second; - } else { + else std::get<1>(result) = itr->first; - } + pendingCorrectionMessages.erase(itrC); } else { std::get<1>(result) = itr->first; @@ -284,8 +274,8 @@ std::tuple Core::MessageHandler::getOriginalPendingMessa return result; } -void Core::MessageHandler::onReceiptReceived(const QString& jid, const QString& id) -{ +void Core::MessageHandler::onReceiptReceived(const QString& jid, const QString& id) { + SHARED_UNUSED(jid); std::tuple ids = getOriginalPendingMessageId(id); if (std::get<0>(ids)) { QMap cData = {{"state", static_cast(Shared::Message::State::delivered)}}; @@ -298,8 +288,7 @@ void Core::MessageHandler::onReceiptReceived(const QString& jid, const QString& } } -void Core::MessageHandler::sendMessage(const Shared::Message& data, bool newMessage, QString originalId) -{ +void Core::MessageHandler::sendMessage(const Shared::Message& data, bool newMessage, QString originalId) { if (data.getOutOfBandUrl().size() == 0 && data.getAttachPath().size() > 0) { pendingCorrectionMessages.insert(std::make_pair(data.getId(), originalId)); prepareUpload(data, newMessage); @@ -308,19 +297,18 @@ void Core::MessageHandler::sendMessage(const Shared::Message& data, bool newMess } } -void Core::MessageHandler::performSending(Shared::Message data, const QString& originalId, bool newMessage) -{ +void Core::MessageHandler::performSending(Shared::Message data, const QString& originalId, bool newMessage) { QString jid = data.getPenPalJid(); QString id = data.getId(); qDebug() << "Sending message with id:" << id; - if (originalId.size() > 0) { + if (originalId.size() > 0) qDebug() << "To replace one with id:" << originalId; - } + RosterItem* ri = acc->rh->getRosterItem(jid); bool sent = false; - if (newMessage && originalId.size() > 0) { + if (newMessage && originalId.size() > 0) newMessage = false; - } + QDateTime sendTime = QDateTime::currentDateTimeUtc(); if (acc->state == Shared::ConnectionState::connected) { QXmppMessage msg(createPacket(data, sendTime, originalId)); @@ -341,22 +329,21 @@ void Core::MessageHandler::performSending(Shared::Message data, const QString& o QMap changes(getChanges(data, sendTime, newMessage, originalId)); QString realId; - if (originalId.size() > 0) { + if (originalId.size() > 0) realId = originalId; - } else { + else realId = id; - } + if (ri != nullptr) { - if (newMessage) { + if (newMessage) ri->appendMessageToArchive(data); - } else { + else ri->changeMessage(realId, changes); - } + if (sent) { pendingStateMessages.insert(std::make_pair(id, jid)); - if (originalId.size() > 0) { + if (originalId.size() > 0) pendingCorrectionMessages.insert(std::make_pair(id, originalId)); - } } else { pendingStateMessages.erase(id); pendingCorrectionMessages.erase(id); @@ -366,25 +353,24 @@ void Core::MessageHandler::performSending(Shared::Message data, const QString& o emit acc->changeMessage(jid, realId, changes); } -QMap Core::MessageHandler::getChanges(Shared::Message& data, const QDateTime& time, bool newMessage, const QString& originalId) const -{ +QMap Core::MessageHandler::getChanges(Shared::Message& data, const QDateTime& time, bool newMessage, const QString& originalId) const { QMap changes; QString oob = data.getOutOfBandUrl(); Shared::Message::State mstate = data.getState(); changes.insert("state", static_cast(mstate)); - if (mstate == Shared::Message::State::error) { + if (mstate == Shared::Message::State::error) changes.insert("errorText", data.getErrorText()); - } - if (oob.size() > 0) { + + if (oob.size() > 0) changes.insert("outOfBandUrl", oob); - } - if (newMessage) { + + if (newMessage) data.setTime(time); - } - if (originalId.size() > 0) { + + if (originalId.size() > 0) changes.insert("body", data.getBody()); - } + changes.insert("stamp", time); //sometimes (when the image is pasted with ctrl+v) @@ -394,22 +380,20 @@ QMap Core::MessageHandler::getChanges(Shared::Message& data, if (attachPath.size() > 0) { QString squawkified = Shared::squawkifyPath(attachPath); changes.insert("attachPath", squawkified); - if (attachPath != squawkified) { + if (attachPath != squawkified) data.setAttachPath(squawkified); - } } return changes; } -QXmppMessage Core::MessageHandler::createPacket(const Shared::Message& data, const QDateTime& time, const QString& originalId) const -{ +QXmppMessage Core::MessageHandler::createPacket(const Shared::Message& data, const QDateTime& time, const QString& originalId) const { QXmppMessage msg(acc->getFullJid(), data.getTo(), data.getBody(), data.getThread()); QString id(data.getId()); - if (originalId.size() > 0) { + if (originalId.size() > 0) msg.setReplaceId(originalId); - } + #if (QXMPP_VERSION) >= QT_VERSION_CHECK(1, 3, 0) msg.setOriginId(id); @@ -423,8 +407,7 @@ QXmppMessage Core::MessageHandler::createPacket(const Shared::Message& data, con return msg; } -void Core::MessageHandler::prepareUpload(const Shared::Message& data, bool newMessage) -{ +void Core::MessageHandler::prepareUpload(const Shared::Message& data, bool newMessage) { if (acc->state == Shared::ConnectionState::connected) { QString jid = data.getPenPalJid(); QString id = data.getId(); @@ -455,9 +438,8 @@ void Core::MessageHandler::prepareUpload(const Shared::Message& data, bool newMe if (file.exists() && file.isReadable()) { pendingStateMessages.insert(std::make_pair(id, jid)); uploadingSlotsQueue.emplace_back(path, id); - if (uploadingSlotsQueue.size() == 1) { + if (uploadingSlotsQueue.size() == 1) acc->um->requestUploadSlot(file); - } } else { handleUploadError(jid, id, "Uploading file no longer exists or your system user has no permission to read it"); qDebug() << "Requested upload slot in account" << acc->name << "for file" << path << "but the file doesn't exist or is not readable"; @@ -474,8 +456,7 @@ void Core::MessageHandler::prepareUpload(const Shared::Message& data, bool newMe } } -void Core::MessageHandler::onUploadSlotReceived(const QXmppHttpUploadSlotIq& slot) -{ +void Core::MessageHandler::onUploadSlotReceived(const QXmppHttpUploadSlotIq& slot) { if (uploadingSlotsQueue.size() == 0) { qDebug() << "HTTP Upload manager of account" << acc->name << "reports about success requesting upload slot, but none was requested"; } else { @@ -485,14 +466,12 @@ void Core::MessageHandler::onUploadSlotReceived(const QXmppHttpUploadSlotIq& slo acc->network->uploadFile({acc->name, palJid, mId}, pair.first, slot.putUrl(), slot.getUrl(), slot.putHeaders()); uploadingSlotsQueue.pop_front(); - if (uploadingSlotsQueue.size() > 0) { + if (uploadingSlotsQueue.size() > 0) acc->um->requestUploadSlot(uploadingSlotsQueue.front().first); - } } } -void Core::MessageHandler::onUploadSlotRequestFailed(const QXmppHttpUploadRequestIq& request) -{ +void Core::MessageHandler::onUploadSlotRequestFailed(const QXmppHttpUploadRequestIq& request) { QString err(request.error().text()); if (uploadingSlotsQueue.size() == 0) { qDebug() << "HTTP Upload manager of account" << acc->name << "reports about an error requesting upload slot, but none was requested"; @@ -503,14 +482,12 @@ void Core::MessageHandler::onUploadSlotRequestFailed(const QXmppHttpUploadReques handleUploadError(pendingStateMessages.at(pair.second), pair.second, err); uploadingSlotsQueue.pop_front(); - if (uploadingSlotsQueue.size() > 0) { + if (uploadingSlotsQueue.size() > 0) acc->um->requestUploadSlot(uploadingSlotsQueue.front().first); - } } } -void Core::MessageHandler::onDownloadFileComplete(const std::list& msgs, const QString& path) -{ +void Core::MessageHandler::onDownloadFileComplete(const std::list& msgs, const QString& path) { QMap cData = { {"attachPath", path} }; @@ -518,27 +495,24 @@ void Core::MessageHandler::onDownloadFileComplete(const std::listgetName()) { RosterItem* cnt = acc->rh->getRosterItem(info.jid); if (cnt != nullptr) { - if (cnt->changeMessage(info.messageId, cData)) { + bool changed = cnt->changeMessage(info.messageId, cData); + if (changed) emit acc->changeMessage(info.jid, info.messageId, cData); - } } } } } -void Core::MessageHandler::onLoadFileError(const std::list& msgs, const QString& text, bool up) -{ +void Core::MessageHandler::onLoadFileError(const std::list& msgs, const QString& text, bool up) { if (up) { for (const Shared::MessageInfo& info : msgs) { - if (info.account == acc->getName()) { + if (info.account == acc->getName()) handleUploadError(info.jid, info.messageId, text); - } } } } -void Core::MessageHandler::handleUploadError(const QString& jid, const QString& messageId, const QString& errorText) -{ +void Core::MessageHandler::handleUploadError(const QString& jid, const QString& messageId, const QString& errorText) { emit acc->uploadFileError(jid, messageId, "Error requesting slot to upload file: " + errorText); pendingStateMessages.erase(messageId); pendingCorrectionMessages.erase(messageId); @@ -548,8 +522,7 @@ void Core::MessageHandler::handleUploadError(const QString& jid, const QString& }); } -void Core::MessageHandler::onUploadFileComplete(const std::list& msgs, const QString& url, const QString& path) -{ +void Core::MessageHandler::onUploadFileComplete(const std::list& msgs, const QString& url, const QString& path) { for (const Shared::MessageInfo& info : msgs) { if (info.account == acc->getName()) { RosterItem* ri = acc->rh->getRosterItem(info.jid); @@ -564,12 +537,11 @@ void Core::MessageHandler::onUploadFileComplete(const std::list allowedToChangeKeys({ "errorText" }); -void Core::MessageHandler::requestChangeMessage(const QString& jid, const QString& messageId, const QMap& data) -{ +void Core::MessageHandler::requestChangeMessage(const QString& jid, const QString& messageId, const QMap& data) { RosterItem* cnt = acc->rh->getRosterItem(jid); if (cnt != nullptr) { bool allSupported = true; @@ -604,8 +575,7 @@ void Core::MessageHandler::requestChangeMessage(const QString& jid, const QStrin } } -void Core::MessageHandler::resendMessage(const QString& jid, const QString& id) -{ +void Core::MessageHandler::resendMessage(const QString& jid, const QString& id) { RosterItem* cnt = acc->rh->getRosterItem(jid); if (cnt != nullptr) { try { diff --git a/core/handlers/omemohandler.cpp b/core/handlers/omemohandler.cpp index 35bca9e..2f9f70e 100644 --- a/core/handlers/omemohandler.cpp +++ b/core/handlers/omemohandler.cpp @@ -213,6 +213,7 @@ void Core::OmemoHandler::onOwnBundlesReceived() { } void Core::OmemoHandler::onOmemoDeviceAdded(const QString& jid, uint32_t id) { + SHARED_UNUSED(id); qDebug() << "OMEMO device added for" << jid; } diff --git a/core/handlers/rosterhandler.cpp b/core/handlers/rosterhandler.cpp index 2e59971..4ce8939 100644 --- a/core/handlers/rosterhandler.cpp +++ b/core/handlers/rosterhandler.cpp @@ -456,6 +456,7 @@ void Core::RosterHandler::removeRoomRequest(const QString& jid) { } void Core::RosterHandler::addRoomRequest(const QString& jid, const QString& nick, const QString& password, bool autoJoin) { + SHARED_UNUSED(password); QString lcJid = jid.toLower(); std::map::const_iterator cItr = conferences.find(lcJid); if (cItr == conferences.end()) { diff --git a/core/signalcatcher.cpp b/core/signalcatcher.cpp index 046c67e..ef3e14c 100644 --- a/core/signalcatcher.cpp +++ b/core/signalcatcher.cpp @@ -21,6 +21,8 @@ #include #include +#include "shared/defines.h" + int SignalCatcher::sigintFd[2] = {0,0}; SignalCatcher::SignalCatcher(QCoreApplication *p_app, QObject *parent): @@ -28,14 +30,10 @@ SignalCatcher::SignalCatcher(QCoreApplication *p_app, QObject *parent): app(p_app) { if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd)) - { qFatal("Couldn't create INT socketpair"); - } if (setup_unix_signal_handlers() != 0) - { qFatal("Couldn't install unix handlers"); - } snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this); connect(snInt, &QSocketNotifier::activated, this, &SignalCatcher::handleSigInt); @@ -44,25 +42,25 @@ SignalCatcher::SignalCatcher(QCoreApplication *p_app, QObject *parent): SignalCatcher::~SignalCatcher() {} -void SignalCatcher::handleSigInt() -{ +void SignalCatcher::handleSigInt() { snInt->setEnabled(false); char tmp; ssize_t s = ::read(sigintFd[1], &tmp, sizeof(tmp)); + SHARED_UNUSED(s); emit interrupt(); snInt->setEnabled(true); } -void SignalCatcher::intSignalHandler(int unused) -{ +void SignalCatcher::intSignalHandler(int unused) { char a = 1; ssize_t s = ::write(sigintFd[0], &a, sizeof(a)); + SHARED_UNUSED(s); + SHARED_UNUSED(unused); } -int SignalCatcher::setup_unix_signal_handlers() -{ +int SignalCatcher::setup_unix_signal_handlers() { struct sigaction s_int; s_int.sa_handler = SignalCatcher::intSignalHandler; diff --git a/main/application.cpp b/main/application.cpp index edf9fd7..0701a0c 100644 --- a/main/application.cpp +++ b/main/application.cpp @@ -120,8 +120,7 @@ Application::Application(Core::Squawk* p_core): Application::~Application() {} -void Application::quit() -{ +void Application::quit() { if (!nowQuitting) { nowQuitting = true; emit quitting(); @@ -135,32 +134,27 @@ void Application::quit() conversations.clear(); dialogueQueue.quit(); - if (squawk != nullptr) { + if (squawk != nullptr) squawk->close(); - } if (trayIcon != nullptr) { trayIcon->deleteLater(); trayIcon = nullptr; } - if (!destroyingSquawk) { + if (!destroyingSquawk) checkForTheLastWindow(); - } } } -void Application::checkForTheLastWindow() -{ - if (QApplication::topLevelWidgets().size() > 0) { +void Application::checkForTheLastWindow() { + if (QApplication::topLevelWidgets().size() > 0) emit readyToQuit(); - } else { + else connect(qApp, &QApplication::lastWindowClosed, this, &Application::readyToQuit); - } } -void Application::createMainWindow() -{ +void Application::createMainWindow() { if (squawk == nullptr) { squawk = new Squawk(roster); @@ -202,9 +196,8 @@ void Application::createMainWindow() for (const std::list& entry : expandedPaths) { QModelIndex ind = roster.getIndexByPath(entry); - if (ind.isValid()) { + if (ind.isValid()) squawk->expand(ind); - } } connect(squawk, &Squawk::itemExpanded, this, &Application::onItemExpanded); @@ -212,8 +205,7 @@ void Application::createMainWindow() } } -void Application::onSquawkClosing() -{ +void Application::onSquawkClosing() { dialogueQueue.setParentWidnow(nullptr); if (!nowQuitting) { @@ -237,18 +229,15 @@ void Application::onSquawkClosing() void Application::onSquawkDestroyed() { destroyingSquawk = false; - if (nowQuitting) { + if (nowQuitting) checkForTheLastWindow(); - } } -void Application::onChangeTray(bool enabled, bool hide) -{ +void Application::onChangeTray(bool enabled, bool hide) { if (enabled) { if (trayIcon == nullptr) { - if (!hide || squawk == nullptr) { + if (!hide || squawk == nullptr) createTrayIcon(); - } } else { if (hide && squawk != nullptr) { trayIcon->deleteLater(); @@ -261,8 +250,7 @@ void Application::onChangeTray(bool enabled, bool hide) } } -void Application::createTrayIcon() -{ +void Application::createTrayIcon() { trayIcon = new QSystemTrayIcon(); QMenu* trayIconMenu = new QMenu(); @@ -279,8 +267,7 @@ void Application::createTrayIcon() trayIcon->show(); } -void Application::trayClicked(QSystemTrayIcon::ActivationReason reason) -{ +void Application::trayClicked(QSystemTrayIcon::ActivationReason reason) { switch (reason) { case QSystemTrayIcon::Trigger: case QSystemTrayIcon::DoubleClick: @@ -292,8 +279,7 @@ void Application::trayClicked(QSystemTrayIcon::ActivationReason reason) } } -void Application::toggleSquawk() -{ +void Application::toggleSquawk() { QSettings settings; if (squawk == nullptr) { createMainWindow(); @@ -308,34 +294,27 @@ void Application::toggleSquawk() } } -void Application::onItemCollapsed(const QModelIndex& index) -{ +void Application::onItemCollapsed(const QModelIndex& index) { std::list address = roster.getItemPath(index); - if (address.size() > 0) { + if (address.size() > 0) expandedPaths.erase(address); - } } -void Application::onItemExpanded(const QModelIndex& index) -{ +void Application::onItemExpanded(const QModelIndex& index) { std::list address = roster.getItemPath(index); - if (address.size() > 0) { + if (address.size() > 0) expandedPaths.insert(address); - } } -void Application::onAddedElement(const std::list& path) -{ +void Application::onAddedElement(const std::list& path) { if (squawk != nullptr && expandedPaths.count(path) > 0) { QModelIndex index = roster.getIndexByPath(path); - if (index.isValid()) { + if (index.isValid()) squawk->expand(index); - } } } -void Application::notify(const QString& account, const Shared::Message& msg) -{ +void Application::notify(const QString& account, const Shared::Message& msg) { QString jid = msg.getPenPalJid(); QString name = QString(roster.getContactName(account, jid)); QString path = QString(roster.getContactIconPath(account, jid, msg.getPenPalResource())); @@ -344,16 +323,15 @@ void Application::notify(const QString& account, const Shared::Message& msg) uint32_t notificationId = qHash(msg.getId()); args << notificationId; - if (path.size() > 0) { + if (path.size() > 0) args << path; - } else { + else args << QString("mail-message"); //TODO should here better be unknown user icon? - } - if (msg.getType() == Shared::Message::groupChat) { + + if (msg.getType() == Shared::Message::groupChat) args << msg.getFromResource() + tr(" from ") + name; - } else { + else args << name; - } QString body(msg.getBody()); QString oob(msg.getOutOfBandUrl()); @@ -378,13 +356,11 @@ void Application::notify(const QString& account, const Shared::Message& msg) storage.insert(std::make_pair(notificationId, std::make_pair(Models::Roster::ElId(account, name), msg.getId()))); - if (squawk != nullptr) { + if (squawk != nullptr) QApplication::alert(squawk); - } } -void Application::onNotificationClosed(quint32 id, quint32 reason) -{ +void Application::onNotificationClosed(quint32 id, quint32 reason) { Notifications::const_iterator itr = storage.find(id); if (itr != storage.end()) { if (reason == 2) { //dissmissed by user (https://specifications.freedesktop.org/notification-spec/latest/ar01s09.html) @@ -397,21 +373,18 @@ void Application::onNotificationClosed(quint32 id, quint32 reason) } } -void Application::onNotificationInvoked(quint32 id, const QString& action) -{ +void Application::onNotificationInvoked(quint32 id, const QString& action) { qDebug() << "Notification" << id << action << "request"; Notifications::const_iterator itr = storage.find(id); if (itr != storage.end()) { - if (action == "markAsRead") { + if (action == "markAsRead") roster.markMessageAsRead(itr->second.first, itr->second.second); - } else if (action == "openConversation") { + else if (action == "openConversation") focusConversation(itr->second.first, "", itr->second.second); - } } } -void Application::unreadMessagesCountChanged(int count) -{ +void Application::unreadMessagesCountChanged(int count) { QDBusMessage signal = QDBusMessage::createSignal("/", "com.canonical.Unity.LauncherEntry", "Update"); signal << qApp->desktopFileName() + QLatin1String(".desktop"); signal << QVariantMap ({ @@ -421,54 +394,49 @@ void Application::unreadMessagesCountChanged(int count) QDBusConnection::sessionBus().send(signal); } -void Application::focusConversation(const Models::Roster::ElId& id, const QString& resource, const QString& messageId) -{ +void Application::focusConversation(const Models::Roster::ElId& id, const QString& resource, const QString& messageId) { if (squawk != nullptr) { if (squawk->currentConversationId() != id) { QModelIndex index = roster.getContactIndex(id.account, id.name, resource); squawk->select(index); } - if (squawk->isMinimized()) { + if (squawk->isMinimized()) squawk->showNormal(); - } else { + else squawk->show(); - } + squawk->raise(); squawk->activateWindow(); } else { openConversation(id, resource); } + SHARED_UNUSED(messageId); //TODO focus messageId; } -void Application::setState(Shared::Availability p_availability) -{ +void Application::setState(Shared::Availability p_availability) { if (availability != p_availability) { availability = p_availability; emit changeState(availability); } } -void Application::stateChanged(Shared::Availability state) -{ +void Application::stateChanged(Shared::Availability state) { availability = state; - if (squawk != nullptr) { + if (squawk != nullptr) squawk->stateChanged(state); - } } -void Application::readSettings() -{ +void Application::readSettings() { QSettings settings; settings.beginGroup("ui"); int avail; - if (settings.contains("availability")) { + if (settings.contains("availability")) avail = settings.value("availability").toInt(); - } else { + else avail = static_cast(Shared::Availability::online); - } settings.beginGroup("roster"); QStringList entries = settings.allKeys(); @@ -486,13 +454,11 @@ void Application::readSettings() setState(Shared::Global::fromInt(avail)); createMainWindow(); - if (settings.value("tray", false).toBool() && !settings.value("hideTray", false).toBool()) { + if (settings.value("tray", false).toBool() && !settings.value("hideTray", false).toBool()) createTrayIcon(); - } } -void Application::writeSettings() -{ +void Application::writeSettings() { QSettings settings; settings.beginGroup("ui"); settings.setValue("availability", static_cast(availability)); @@ -501,9 +467,9 @@ void Application::writeSettings() settings.beginGroup("roster"); for (const std::list& address : expandedPaths) { QString path = ""; - for (const QString& hop : address) { + for (const QString& hop : address) path += hop + "/"; - } + path += "expanded"; settings.setValue(path, true); } @@ -513,54 +479,49 @@ void Application::writeSettings() } void Application::requestPassword(const QString& account, bool authenticationError) { - if (authenticationError) { + if (authenticationError) dialogueQueue.addAction(account, DialogQueue::askCredentials); - } else { + else dialogueQueue.addAction(account, DialogQueue::askPassword); - } - } -void Application::onConversationClosed() -{ + +void Application::onConversationClosed() { Conversation* conv = static_cast(sender()); Models::Roster::ElId id(conv->getAccount(), conv->getJid()); Conversations::const_iterator itr = conversations.find(id); - if (itr != conversations.end()) { + if (itr != conversations.end()) conversations.erase(itr); - } + if (conv->isMuc) { Room* room = static_cast(conv); - if (!room->autoJoined()) { + if (!room->autoJoined()) emit setRoomJoined(id.account, id.name, false); - } } } -void Application::changeSubscription(const Models::Roster::ElId& id, bool subscribe) -{ +void Application::changeSubscription(const Models::Roster::ElId& id, bool subscribe) { Models::Item::Type type = roster.getContactType(id); switch (type) { case Models::Item::contact: - if (subscribe) { + if (subscribe) emit subscribeContact(id.account, id.name, ""); - } else { + else emit unsubscribeContact(id.account, id.name, ""); - } + break; case Models::Item::room: setRoomAutoJoin(id.account, id.name, subscribe); - if (!isConverstationOpened(id)) { + if (!isConverstationOpened(id)) emit setRoomJoined(id.account, id.name, subscribe); - } + break; default: break; } } -void Application::subscribeConversation(Conversation* conv) -{ +void Application::subscribeConversation(Conversation* conv) { connect(conv, &Conversation::destroyed, this, &Application::onConversationClosed); connect(conv, &Conversation::sendMessage, this, &Application::onConversationMessage); connect(conv, &Conversation::replaceMessage, this, &Application::onConversationReplaceMessage); @@ -568,8 +529,7 @@ void Application::subscribeConversation(Conversation* conv) connect(conv, &Conversation::notifyableMessage, this, &Application::notify); } -void Application::openConversation(const Models::Roster::ElId& id, const QString& resource) -{ +void Application::openConversation(const Models::Roster::ElId& id, const QString& resource) { Conversations::const_iterator itr = conversations.find(id); Models::Account* acc = roster.getAccount(id.account); Conversation* conv = nullptr; @@ -583,9 +543,8 @@ void Application::openConversation(const Models::Roster::ElId& id, const QString created = true; Models::Room* room = static_cast(el); conv = new Room(acc, room); - if (!room->getJoined()) { + if (!room->getJoined()) emit setRoomJoined(id.account, id.name, true); - } } else if (el->type == Models::Item::contact) { created = true; conv = new Chat(acc, static_cast(el)); @@ -604,14 +563,12 @@ void Application::openConversation(const Models::Roster::ElId& id, const QString conv->raise(); conv->activateWindow(); - if (resource.size() > 0) { + if (resource.size() > 0) conv->setPalResource(resource); - } } } -void Application::onConversationMessage(const Shared::Message& msg) -{ +void Application::onConversationMessage(const Shared::Message& msg) { Conversation* conv = static_cast(sender()); QString acc = conv->getAccount(); @@ -619,8 +576,7 @@ void Application::onConversationMessage(const Shared::Message& msg) emit sendMessage(acc, msg); } -void Application::onConversationReplaceMessage(const QString& originalId, const Shared::Message& msg) -{ +void Application::onConversationReplaceMessage(const QString& originalId, const Shared::Message& msg) { Conversation* conv = static_cast(sender()); QString acc = conv->getAccount(); @@ -630,8 +586,7 @@ void Application::onConversationReplaceMessage(const QString& originalId, const emit replaceMessage(acc, originalId, msg); } -void Application::onConversationResend(const QString& id) -{ +void Application::onConversationResend(const QString& id) { Conversation* conv = static_cast(sender()); QString acc = conv->getAccount(); QString jid = conv->getJid(); @@ -649,8 +604,7 @@ void Application::onSquawkOpenedConversation() { } } -void Application::removeAccount(const QString& account) -{ +void Application::removeAccount(const QString& account) { Conversations::const_iterator itr = conversations.begin(); while (itr != conversations.end()) { if (itr->first.account == account) { @@ -665,23 +619,20 @@ void Application::removeAccount(const QString& account) } } - if (squawk != nullptr && squawk->currentConversationId().account == account) { + if (squawk != nullptr && squawk->currentConversationId().account == account) squawk->closeCurrentConversation(); - } roster.removeAccount(account); } -void Application::changeAccount(const QString& account, const QMap& data) -{ +void Application::changeAccount(const QString& account, const QMap& data) { for (QMap::const_iterator itr = data.begin(), end = data.end(); itr != end; ++itr) { QString attr = itr.key(); roster.updateAccount(account, attr, *itr); } } -void Application::addGroup(const QString& account, const QString& name) -{ +void Application::addGroup(const QString& account, const QString& name) { roster.addGroup(account, name); if (squawk != nullptr) { @@ -692,9 +643,8 @@ void Application::addGroup(const QString& account, const QString& name) if (settings.value("expanded", false).toBool()) { QModelIndex ind = roster.getAccountIndex(account); squawk->expand(ind); - if (settings.value(name + "/expanded", false).toBool()) { + if (settings.value(name + "/expanded", false).toBool()) squawk->expand(roster.getGroupIndex(account, name)); - } } settings.endGroup(); settings.endGroup(); diff --git a/shared/CMakeLists.txt b/shared/CMakeLists.txt index 4bcc12f..4ba24ea 100644 --- a/shared/CMakeLists.txt +++ b/shared/CMakeLists.txt @@ -37,6 +37,7 @@ set(HEADER_FILES info.h clientid.h trustsummary.h + defines.h ) target_sources(squawk PRIVATE diff --git a/shared/defines.h b/shared/defines.h new file mode 100644 index 0000000..227a714 --- /dev/null +++ b/shared/defines.h @@ -0,0 +1,24 @@ +/* + * Squawk messenger. + * Copyright (C) 2019 Yury Gubich + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef SHARED_DEFINES_H +#define SHARED_DEFINES_H + +#define SHARED_UNUSED(x) (void)(x) + +#endif diff --git a/shared/identity.cpp b/shared/identity.cpp index a0a4f0a..ef616d8 100644 --- a/shared/identity.cpp +++ b/shared/identity.cpp @@ -121,6 +121,8 @@ QDataStream & Shared::Identity::operator >> (QDataStream& stream) const { stream << type; stream << language; stream << name; + + return stream; } QDataStream & Shared::Identity::operator << (QDataStream& stream) { @@ -128,6 +130,8 @@ QDataStream & Shared::Identity::operator << (QDataStream& stream) { stream >> type; stream >> language; stream >> name; + + return stream; } QDataStream & operator >> (QDataStream& stream, Shared::Identity& identity) { diff --git a/shared/shared.h b/shared/shared.h index 68e5c8d..ba9a2ed 100644 --- a/shared/shared.h +++ b/shared/shared.h @@ -19,6 +19,7 @@ #ifndef SHARED_H #define SHARED_H +#include "defines.h" #include "enums.h" #include "global.h" #include "icons.h" diff --git a/ui/models/accounts.cpp b/ui/models/accounts.cpp index 8a9e5d9..e401b3a 100644 --- a/ui/models/accounts.cpp +++ b/ui/models/accounts.cpp @@ -18,6 +18,7 @@ #include "accounts.h" #include "shared/icons.h" +#include "shared/defines.h" #include #include @@ -26,32 +27,24 @@ std::deque Models::Accounts::columns = {"Name", "Server", "State", "Err Models::Accounts::Accounts(QObject* parent): QAbstractTableModel(parent), - accs() -{ + accs() {} -} +Models::Accounts::~Accounts() {} -Models::Accounts::~Accounts() -{ - -} - -QVariant Models::Accounts::data (const QModelIndex& index, int role) const -{ +QVariant Models::Accounts::data (const QModelIndex& index, int role) const { QVariant answer; switch (role) { case Qt::DisplayRole: answer = accs[index.row()]->data(index.column()); break; case Qt::DecorationRole: - if (index.column() == 2) { + if (index.column() == 2) answer = Shared::connectionStateIcon(accs[index.row()]->getState()); - } break; case Qt::ForegroundRole: - if (!accs[index.row()]->getActive()) { + if (!accs[index.row()]->getActive()) answer = qApp->palette().brush(QPalette::Disabled, QPalette::Text); - } + break; default: break; } @@ -59,53 +52,46 @@ QVariant Models::Accounts::data (const QModelIndex& index, int role) const return answer; } -int Models::Accounts::columnCount ( const QModelIndex& parent ) const -{ +int Models::Accounts::columnCount (const QModelIndex& parent) const { + SHARED_UNUSED(parent); return columns.size(); } -int Models::Accounts::rowCount ( const QModelIndex& parent ) const -{ +int Models::Accounts::rowCount (const QModelIndex& parent) const { + SHARED_UNUSED(parent); return accs.size(); } -unsigned int Models::Accounts::size() const -{ +unsigned int Models::Accounts::size() const { return rowCount(QModelIndex()); } -unsigned int Models::Accounts::activeSize() const -{ +unsigned int Models::Accounts::activeSize() const { unsigned int size = 0; for (const Models::Account* acc : accs) { - if (acc->getActive()) { + if (acc->getActive()) ++size; - } } return size; } -QVariant Models::Accounts::headerData(int section, Qt::Orientation orientation, int role) const -{ - if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { +QVariant Models::Accounts::headerData(int section, Qt::Orientation orientation, int role) const { + if (role == Qt::DisplayRole && orientation == Qt::Horizontal) return tr(columns[section].toLatin1()); - } + return QVariant(); } -void Models::Accounts::addAccount(Account* account) -{ +void Models::Accounts::addAccount(Account* account) { beginInsertRows(QModelIndex(), accs.size(), accs.size()); - int index = 0; std::deque::const_iterator before = accs.begin(); while (before != accs.end()) { Account* bfr = *before; - if (bfr->getDisplayedName() > account->getDisplayedName()) { + if (bfr->getDisplayedName() > account->getDisplayedName()) break; - } - index++; + before++; } @@ -117,25 +103,23 @@ void Models::Accounts::addAccount(Account* account) emit changed(); } -void Models::Accounts::onAccountChanged(Item* item, int row, int col) -{ - if (row < 0) { +void Models::Accounts::onAccountChanged(Item* item, int row, int col) { + if (row < 0) return; - } + if (static_cast::size_type>(row) < accs.size()) { Account* acc = getAccount(row); - if (item != acc) { + if (item != acc) return; //it means the signal is emitted by one of accounts' children, not exactly him, this model has no interest in that - } if (col == 0) { int newRow = 0; std::deque::const_iterator before = accs.begin(); while (before != accs.end()) { Item* bfr = *before; - if (bfr->getDisplayedName() > item->getDisplayedName()) { + if (bfr->getDisplayedName() > item->getDisplayedName()) break; - } + newRow++; before++; } @@ -152,20 +136,18 @@ void Models::Accounts::onAccountChanged(Item* item, int row, int col) } } - if (col < columnCount(QModelIndex())) { + if (col < columnCount(QModelIndex())) emit dataChanged(createIndex(row, col), createIndex(row, col)); - } + emit changed(); } } -Models::Account * Models::Accounts::getAccount(int index) -{ +Models::Account * Models::Accounts::getAccount(int index) { return accs[index]; } -void Models::Accounts::removeAccount(int index) -{ +void Models::Accounts::removeAccount(int index) { Account* account = accs[index]; beginRemoveRows(QModelIndex(), index, index); disconnect(account, &Account::childChanged, this, &Accounts::onAccountChanged); @@ -175,14 +157,13 @@ void Models::Accounts::removeAccount(int index) emit sizeChanged(accs.size()); } -std::deque Models::Accounts::getActiveNames() const -{ +std::deque Models::Accounts::getActiveNames() const { std::deque res; for (const Models::Account* acc : accs) { - if (acc->getActive()) { + if (acc->getActive()) res.push_back(acc->getName()); - } + } return res; diff --git a/ui/models/info/emails.cpp b/ui/models/info/emails.cpp index 4bb8a17..694c0c9 100644 --- a/ui/models/info/emails.cpp +++ b/ui/models/info/emails.cpp @@ -19,6 +19,7 @@ #include "emails.h" #include "shared/icons.h" +#include "shared/defines.h" #include Models::EMails::EMails(bool p_edit, QObject* parent): @@ -27,10 +28,15 @@ Models::EMails::EMails(bool p_edit, QObject* parent): deque() {} int Models::EMails::columnCount(const QModelIndex& parent) const { - return 3;} + SHARED_UNUSED(parent); + return 3; +} int Models::EMails::rowCount(const QModelIndex& parent) const { - return deque.size();} + SHARED_UNUSED(parent); + return deque.size(); + +} void Models::EMails::revertPreferred(quint32 row) { setData(createIndex(row, 2), !isPreferred(row));} @@ -83,9 +89,9 @@ QVariant Models::EMails::data(const QModelIndex& index, int role) const { Qt::ItemFlags Models::EMails::flags(const QModelIndex& index) const { Qt::ItemFlags f = QAbstractTableModel::flags(index); - if (edit && index.column() != 2) { + if (edit && index.column() != 2) f = Qt::ItemIsEditable | f; - } + return f; } @@ -114,9 +120,9 @@ bool Models::EMails::setData(const QModelIndex& index, const QVariant& value, in return true; case 1: { quint8 newRole = value.toUInt(); - if (newRole > Shared::VCard::Email::work) { + if (newRole > Shared::VCard::Email::work) return false; - } + item.role = static_cast(newRole); return true; } @@ -160,19 +166,17 @@ QModelIndex Models::EMails::addNewEmptyLine() { } bool Models::EMails::isPreferred(quint32 row) const { - if (row < deque.size()) { + if (row < deque.size()) return deque[row].prefered; - } else { + else return false; - } } void Models::EMails::removeLines(quint32 index, quint32 count) { if (index < deque.size()) { quint32 maxCount = deque.size() - index; - if (count > maxCount) { + if (count > maxCount) count = maxCount; - } if (count > 0) { beginRemoveRows(QModelIndex(), index, index + count - 1); @@ -185,21 +189,19 @@ void Models::EMails::removeLines(quint32 index, quint32 count) { } void Models::EMails::getEmails(std::deque& emails) const { - for (const Shared::VCard::Email& my : deque) { + for (const Shared::VCard::Email& my : deque) emails.emplace_back(my); - } } void Models::EMails::setEmails(const std::deque& emails) { - if (deque.size() > 0) { + if (deque.size() > 0) removeLines(0, deque.size()); - } if (emails.size() > 0) { beginInsertRows(QModelIndex(), 0, emails.size() - 1); - for (const Shared::VCard::Email& comming : emails) { + for (const Shared::VCard::Email& comming : emails) deque.emplace_back(comming); - } + endInsertRows(); } } diff --git a/ui/models/info/omemo/keys.cpp b/ui/models/info/omemo/keys.cpp index e4dc8d2..5d957b1 100644 --- a/ui/models/info/omemo/keys.cpp +++ b/ui/models/info/omemo/keys.cpp @@ -16,6 +16,8 @@ #include "keys.h" +#include "shared/defines.h" + const QHash Models::Keys::roles = { {Label, "label"}, {FingerPrint, "fingerPrint"}, @@ -28,13 +30,11 @@ Models::Keys::Keys(QObject* parent): modified() {} Models::Keys::~Keys() { - for (Shared::KeyInfo* key : keys) { + for (Shared::KeyInfo* key : keys) delete key; - } - for (std::pair& pair: modified) { + for (std::pair& pair: modified) delete pair.second; - } } std::deque Models::Keys::modifiedKeys() const { @@ -92,15 +92,15 @@ QVariant Models::Keys::data(const QModelIndex& index, int role) const { } int Models::Keys::rowCount(const QModelIndex& parent) const { + SHARED_UNUSED(parent); return keys.size(); } QHash Models::Keys::roleNames() const {return roles;} QModelIndex Models::Keys::index(int row, int column, const QModelIndex& parent) const { - if (!hasIndex(row, column, parent)) { + if (!hasIndex(row, column, parent)) return QModelIndex(); - } return createIndex(row, column, keys[row]); } diff --git a/ui/models/info/phones.cpp b/ui/models/info/phones.cpp index 99c52c2..2b6523a 100644 --- a/ui/models/info/phones.cpp +++ b/ui/models/info/phones.cpp @@ -19,6 +19,7 @@ #include "phones.h" #include "shared/icons.h" +#include "shared/defines.h" #include Models::Phones::Phones(bool p_edit, QObject* parent): @@ -27,10 +28,14 @@ Models::Phones::Phones(bool p_edit, QObject* parent): deque() {} int Models::Phones::columnCount(const QModelIndex& parent) const { - return 4;} + SHARED_UNUSED(parent); + return 4; +} int Models::Phones::rowCount(const QModelIndex& parent) const { - return deque.size();} + SHARED_UNUSED(parent); + return deque.size(); +} void Models::Phones::revertPreferred(quint32 row) { setData(createIndex(row, 3), !isPreferred(row)); @@ -77,9 +82,9 @@ QVariant Models::Phones::data(const QModelIndex& index, int role) const { case Qt::DisplayRole: return QVariant(); case Qt::DecorationRole: - if (deque[index.row()].prefered) { + if (deque[index.row()].prefered) return Shared::icon("favorite", false); - } + return QVariant(); default: return QVariant(); @@ -101,9 +106,9 @@ QModelIndex Models::Phones::addNewEmptyLine() { Qt::ItemFlags Models::Phones::flags(const QModelIndex& index) const { Qt::ItemFlags f = QAbstractTableModel::flags(index); - if (edit && index.column() != 3) { + if (edit && index.column() != 3) f = Qt::ItemIsEditable | f; - } + return f; } @@ -139,25 +144,22 @@ bool Models::Phones::dropPrefered() { } void Models::Phones::getPhones(std::deque& phones) const { - for (const Shared::VCard::Phone& my : deque) { + for (const Shared::VCard::Phone& my : deque) phones.emplace_back(my); - } } bool Models::Phones::isPreferred(quint32 row) const { - if (row < deque.size()) { + if (row < deque.size()) return deque[row].prefered; - } else { + else return false; - } } void Models::Phones::removeLines(quint32 index, quint32 count) { if (index < deque.size()) { quint32 maxCount = deque.size() - index; - if (count > maxCount) { + if (count > maxCount) count = maxCount; - } if (count > 0) { beginRemoveRows(QModelIndex(), index, index + count - 1); @@ -178,17 +180,17 @@ bool Models::Phones::setData(const QModelIndex& index, const QVariant& value, in return true; case 1: { quint8 newRole = value.toUInt(); - if (newRole > Shared::VCard::Phone::work) { + if (newRole > Shared::VCard::Phone::work) return false; - } + item.role = static_cast(newRole); return true; } case 2: { quint8 newType = value.toUInt(); - if (newType > Shared::VCard::Phone::other) { + if (newType > Shared::VCard::Phone::other) return false; - } + item.type = static_cast(newType); return true; } @@ -209,15 +211,15 @@ bool Models::Phones::setData(const QModelIndex& index, const QVariant& value, in } void Models::Phones::setPhones(const std::deque& phones) { - if (deque.size() > 0) { + if (deque.size() > 0) removeLines(0, deque.size()); - } + if (phones.size() > 0) { beginInsertRows(QModelIndex(), 0, phones.size() - 1); - for (const Shared::VCard::Phone& comming : phones) { + for (const Shared::VCard::Phone& comming : phones) deque.emplace_back(comming); - } + endInsertRows(); } } diff --git a/ui/models/roster.cpp b/ui/models/roster.cpp index 43717f8..0f35baa 100644 --- a/ui/models/roster.cpp +++ b/ui/models/roster.cpp @@ -21,6 +21,8 @@ #include #include +#include "shared/defines.h" + Models::Roster::Roster(QObject* parent): QAbstractItemModel(parent), accountsModel(new Accounts()), @@ -39,14 +41,12 @@ Models::Roster::Roster(QObject* parent): connect(root, &Item::childMoved, this, &Roster::onChildMoved); } -Models::Roster::~Roster() -{ +Models::Roster::~Roster() { delete accountsModel; delete root; } -void Models::Roster::addAccount(const QMap& data) -{ +void Models::Roster::addAccount(const QMap& data) { Account* acc = new Account(data); connect(acc, &Account::reconnected, this, &Roster::onAccountReconnected); root->appendChild(acc); @@ -56,24 +56,21 @@ void Models::Roster::addAccount(const QMap& data) emit addedElement({acc->getId()}); } -QVariant Models::Roster::data (const QModelIndex& index, int role) const -{ - if (!index.isValid()) { +QVariant Models::Roster::data (const QModelIndex& index, int role) const { + if (!index.isValid()) return QVariant(); - } QVariant result; Item *item = static_cast(index.internalPointer()); - if (item->type == Item::reference) { + if (item->type == Item::reference) item = static_cast(item)->dereference(); - } + switch (role) { - case Qt::DisplayRole: - { - if (index.column() != 0) { + case Qt::DisplayRole: { + if (index.column() != 0) break; - } + switch (item->type) { case Item::group: { Group* gr = static_cast(item); @@ -81,9 +78,9 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const str += gr->getName(); unsigned int amount = gr->getUnreadMessages(); - if (amount > 0) { + if (amount > 0) str += QString(" (") + tr("New messages") + ")"; - } + result = str; } @@ -104,9 +101,8 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const } else if (col == 1) { QString path = acc->getAvatarPath(); - if (path.size() > 0) { + if (path.size() > 0) result = QIcon(path); - } } } break; @@ -116,16 +112,15 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const if (col == 0) { result = contact->getStatusIcon(false); } else if (col == 1) { - if (contact->getAvatarState() != Shared::Avatar::empty) { + if (contact->getAvatarState() != Shared::Avatar::empty) result = QIcon(contact->getAvatarPath()); - } } } break; case Item::presence: { - if (index.column() != 0) { + if (index.column() != 0) break; - } + Presence* presence = static_cast(item); result = presence->getStatusIcon(false); } @@ -138,9 +133,8 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const } else if (col == 1) { QString path = room->getAvatarPath(); - if (path.size() > 0) { + if (path.size() > 0) result = QIcon(path); - } } } break; @@ -151,14 +145,11 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const result = p->getStatusIcon(false); } else if (col == 1) { QString path = p->getAvatarPath(); - if (path.size() > 0) { + if (path.size() > 0) result = QIcon(path); - } } - if (index.column() != 0) { + if (index.column() != 0) break; - } - } break; default: @@ -194,9 +185,9 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const Contact* contact = static_cast(item); QString str(""); int mc = contact->getMessagesCount(); - if (mc > 0) { + if (mc > 0) str += QString(tr("New messages: ")) + std::to_string(mc).c_str() + "\n"; - } + str += tr("Jabber ID: ") + contact->getJid() + "\n"; Shared::SubscriptionState ss = contact->getState(); if (ss == Shared::SubscriptionState::both || ss == Shared::SubscriptionState::to) { @@ -204,9 +195,8 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const str += tr("Availability: ") + Shared::Global::getName(av); if (av != Shared::Availability::offline) { QString s = contact->getStatus(); - if (s.size() > 0) { + if (s.size() > 0) str += "\n" + tr("Status: ") + s; - } } str += "\n" + tr("Subscription: ") + Shared::Global::getName(ss); } else { @@ -222,9 +212,9 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const Shared::Availability av = contact->getAvailability(); str += tr("Availability: ") + Shared::Global::getName(av); QString s = contact->getStatus(); - if (s.size() > 0) { + if (s.size() > 0) str += "\n" + tr("Status: ") + s; - } + str += "\n" + tr("Client: ") + contact->getClientNode(); result = str; @@ -236,9 +226,8 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const Shared::Availability av = p->getAvailability(); str += tr("Availability: ") + Shared::Global::getName(av) + "\n"; QString s = p->getStatus(); - if (s.size() > 0) { + if (s.size() > 0) str += tr("Status: ") + s + "\n"; - } str += tr("Affiliation: ") + Shared::Global::getName(p->getAffiliation()) + "\n"; str += tr("Role: ") + Shared::Global::getName(p->getRole()) + "\n"; @@ -251,9 +240,9 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const Group* gr = static_cast(item); unsigned int count = gr->getUnreadMessages(); QString str(""); - if (count > 0) { + if (count > 0) str += tr("New messages: ") + std::to_string(count).c_str() + "\n"; - } + str += tr("Online contacts: ") + std::to_string(gr->getOnlineContacts()).c_str() + "\n"; str += tr("Total contacts: ") + std::to_string(gr->childCount()).c_str(); result = str; @@ -263,15 +252,14 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const Room* rm = static_cast(item); unsigned int count = rm->getMessagesCount(); QString str(""); - if (count > 0) { + if (count > 0) str += tr("New messages: ") + std::to_string(count).c_str() + "\n"; - } str += tr("Jabber ID: ") + rm->getJid() + "\n"; str += tr("Subscription: ") + rm->getStatusText(); - if (rm->getJoined()) { + if (rm->getJoined()) str += QString("\n") + tr("Members: ") + std::to_string(rm->childCount()).c_str(); - } + result = str; } break; @@ -284,9 +272,8 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const switch (item->type) { case Item::account: { Account* acc = static_cast(item); - if (!acc->getActive()) { + if (!acc->getActive()) result = qApp->palette().brush(QPalette::Disabled, QPalette::Text); - } } break; default: @@ -299,17 +286,14 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const return result; } -int Models::Roster::columnCount (const QModelIndex& parent) const -{ - if (parent.isValid()) { +int Models::Roster::columnCount (const QModelIndex& parent) const { + if (parent.isValid()) return static_cast(parent.internalPointer())->columnCount(); - } else { + else return root->columnCount(); - } } -void Models::Roster::updateAccount(const QString& account, const QString& field, const QVariant& value) -{ +void Models::Roster::updateAccount(const QString& account, const QString& field, const QVariant& value) { std::map::iterator itr = accounts.find(account); if (itr != accounts.end()) { Account* acc = itr->second; @@ -317,75 +301,63 @@ void Models::Roster::updateAccount(const QString& account, const QString& field, } } - -Qt::ItemFlags Models::Roster::flags(const QModelIndex& index) const -{ - if (!index.isValid()) { +Qt::ItemFlags Models::Roster::flags(const QModelIndex& index) const { + if (!index.isValid()) return Qt::ItemFlags(); - } return QAbstractItemModel::flags(index); } - -int Models::Roster::rowCount (const QModelIndex& parent) const -{ +int Models::Roster::rowCount (const QModelIndex& parent) const{ Item *parentItem; - if (!parent.isValid()) { + if (!parent.isValid()) parentItem = root; - } else { + else parentItem = static_cast(parent.internalPointer()); - } return parentItem->childCount(); } -QVariant Models::Roster::headerData(int section, Qt::Orientation orientation, int role) const -{ +QVariant Models::Roster::headerData(int section, Qt::Orientation orientation, int role) const { + SHARED_UNUSED(section); + SHARED_UNUSED(orientation); + SHARED_UNUSED(role); + return QVariant(); } -QModelIndex Models::Roster::parent (const QModelIndex& child) const -{ - if (!child.isValid()) { +QModelIndex Models::Roster::parent (const QModelIndex& child) const { + if (!child.isValid()) return QModelIndex(); - } Item *childItem = static_cast(child.internalPointer()); - if (childItem == root) { + if (childItem == root) return QModelIndex(); - } Item *parentItem = childItem->parentItem(); - - if (parentItem == root) { + if (parentItem == root) return createIndex(0, 0, parentItem); - } return createIndex(parentItem->row(), 0, parentItem); } -QModelIndex Models::Roster::index (int row, int column, const QModelIndex& parent) const -{ - if (!hasIndex(row, column, parent)) { +QModelIndex Models::Roster::index (int row, int column, const QModelIndex& parent) const { + if (!hasIndex(row, column, parent)) return QModelIndex(); - } Item *parentItem; - if (!parent.isValid()) { + if (!parent.isValid()) parentItem = root; - } else { + else parentItem = static_cast(parent.internalPointer()); - } Item *childItem = parentItem->child(row); - if (childItem) { + if (childItem) return createIndex(row, column, childItem); - } else { + else return QModelIndex(); - } } Models::Roster::ElId::ElId(const QString& p_account, const QString& p_name): @@ -393,27 +365,22 @@ Models::Roster::ElId::ElId(const QString& p_account, const QString& p_name): name(p_name) {} -bool Models::Roster::ElId::operator <(const Models::Roster::ElId& other) const -{ - if (account == other.account) { +bool Models::Roster::ElId::operator <(const Models::Roster::ElId& other) const { + if (account == other.account) return name < other.name; - } else { + else return account < other.account; - } } -bool Models::Roster::ElId::operator!=(const Models::Roster::ElId& other) const -{ +bool Models::Roster::ElId::operator!=(const Models::Roster::ElId& other) const { return !(operator == (other)); } -bool Models::Roster::ElId::operator==(const Models::Roster::ElId& other) const -{ +bool Models::Roster::ElId::operator==(const Models::Roster::ElId& other) const { return (account == other.account) && (name == other.name); } -void Models::Roster::onAccountDataChanged(const QModelIndex& tl, const QModelIndex& br, const QVector& roles) -{ +void Models::Roster::onAccountDataChanged(const QModelIndex& tl, const QModelIndex& br, const QVector& roles) { if (tl.column() == 0) { emit dataChanged(tl, br, roles); } else if (tl.column() == 2) { @@ -423,8 +390,7 @@ void Models::Roster::onAccountDataChanged(const QModelIndex& tl, const QModelInd } } -void Models::Roster::addGroup(const QString& account, const QString& name) -{ +void Models::Roster::addGroup(const QString& account, const QString& name) { ElId id(account, name); std::map::const_iterator gItr = groups.find(id); if (gItr != groups.end()) { @@ -438,15 +404,13 @@ void Models::Roster::addGroup(const QString& account, const QString& name) groups.insert(std::make_pair(id, group)); acc->appendChild(group); - emit addedElement({acc->getId(), group->getId()}); } else { qDebug() << "An attempt to add group " << name << " to non existing account " << account << ", skipping"; } } -void Models::Roster::addContact(const QString& account, const QString& jid, const QString& group, const QMap& data) -{ +void Models::Roster::addContact(const QString& account, const QString& jid, const QString& group, const QMap& data) { Item* parent; Account* acc; Contact* contact; @@ -513,16 +477,15 @@ void Models::Roster::addContact(const QString& account, const QString& jid, cons } path.push_back(contact->getId()); - if (ref == 0) { + if (ref == 0) ref = new Reference(contact); - } + parent->appendChild(ref); emit addedElement(path); } -void Models::Roster::removeGroup(const QString& account, const QString& name) -{ +void Models::Roster::removeGroup(const QString& account, const QString& name) { ElId id(account, name); std::map::const_iterator gItr = groups.find(id); if (gItr == groups.end()) { @@ -541,11 +504,10 @@ void Models::Roster::removeGroup(const QString& account, const QString& name) item->removeChild(0); Contact* cont = static_cast(ref->dereference()); - if (cont->referencesCount() == 1) { + if (cont->referencesCount() == 1) toInsert.push_back(ref); - } else { + else delete ref; - } } if (toInsert.size() > 0) { @@ -559,8 +521,7 @@ void Models::Roster::removeGroup(const QString& account, const QString& name) groups.erase(gItr); } -void Models::Roster::changeContact(const QString& account, const QString& jid, const QMap& data) -{ +void Models::Roster::changeContact(const QString& account, const QString& jid, const QMap& data) { Element* el = getElement(ElId(account, jid)); if (el != nullptr) { for (QMap::const_iterator itr = data.begin(), end = data.end(); itr != end; ++itr) { @@ -569,18 +530,15 @@ void Models::Roster::changeContact(const QString& account, const QString& jid, c } } -void Models::Roster::changeMessage(const QString& account, const QString& jid, const QString& id, const QMap& data) -{ +void Models::Roster::changeMessage(const QString& account, const QString& jid, const QString& id, const QMap& data) { Element* el = getElement(ElId(account, jid)); - if (el != nullptr) { + if (el != nullptr) el->changeMessage(id, data); - } else { + else qDebug() << "A request to change a message of the contact " << jid << " in the account " << account << " but it wasn't found"; - } } -void Models::Roster::removeContact(const QString& account, const QString& jid) -{ +void Models::Roster::removeContact(const QString& account, const QString& jid) { ElId id(account, jid); std::map::iterator itr = contacts.find(id); @@ -592,21 +550,18 @@ void Models::Roster::removeContact(const QString& account, const QString& jid) std::set toRemove; for (std::pair pair : groups) { - if (pair.second->childCount() == 0) { + if (pair.second->childCount() == 0) toRemove.insert(pair.first); - } } - for (const ElId& elId : toRemove) { + for (const ElId& elId : toRemove) removeGroup(elId.account, elId.name); - } } else { qDebug() << "An attempt to remove contact " << jid << " from account " << account <<" which doesn't exist there, skipping"; } } -void Models::Roster::removeContact(const QString& account, const QString& jid, const QString& group) -{ +void Models::Roster::removeContact(const QString& account, const QString& jid, const QString& group) { ElId contactId(account, jid); ElId groupId(account, group); @@ -639,20 +594,18 @@ void Models::Roster::removeContact(const QString& account, const QString& jid, c } else { delete ref; } - if (gr->childCount() == 0) { + if (gr->childCount() == 0) removeGroup(account, group); - } } -void Models::Roster::onChildChanged(Models::Item* item, int row, int col) -{ +void Models::Roster::onChildChanged(Models::Item* item, int row, int col) { + SHARED_UNUSED(col); QModelIndex index = createIndex(row, 0, item); QModelIndex index2 = createIndex(row, 1, item); emit dataChanged(index, index2); } -void Models::Roster::onChildIsAboutToBeInserted(Models::Item* parent, int first, int last) -{ +void Models::Roster::onChildIsAboutToBeInserted(Models::Item* parent, int first, int last) { int row = 0; if (parent != root) { row = parent->row(); @@ -662,45 +615,39 @@ void Models::Roster::onChildIsAboutToBeInserted(Models::Item* parent, int first, } } -void Models::Roster::onChildIsAboutToBeMoved(Models::Item* source, int first, int last, Models::Item* destination, int newIndex) -{ +void Models::Roster::onChildIsAboutToBeMoved(Models::Item* source, int first, int last, Models::Item* destination, int newIndex) { int oldRow = 0; - if (source != root) { + if (source != root) oldRow = source->row(); - } + int newRow = 0; - if (destination != root) { + if (destination != root) newRow = destination->row(); - } + beginMoveRows(createIndex(oldRow, 0, source), first, last, createIndex(newRow, 0, destination), newIndex); } -void Models::Roster::onChildIsAboutToBeRemoved(Models::Item* parent, int first, int last) -{ +void Models::Roster::onChildIsAboutToBeRemoved(Models::Item* parent, int first, int last) { int row = 0; - if (parent != root) { + if (parent != root) row = parent->row(); - } + beginRemoveRows(createIndex(row, 0, parent), first, last); } -void Models::Roster::onChildInserted() -{ +void Models::Roster::onChildInserted() { endInsertRows(); } -void Models::Roster::onChildMoved() -{ +void Models::Roster::onChildMoved() { endMoveRows(); } -void Models::Roster::onChildRemoved() -{ +void Models::Roster::onChildRemoved() { endRemoveRows(); } -void Models::Roster::addPresence(const QString& account, const QString& jid, const QString& name, const QMap& data) -{ +void Models::Roster::addPresence(const QString& account, const QString& jid, const QString& name, const QMap& data) { ElId contactId(account, jid); std::map::iterator itr = contacts.find(contactId); if (itr != contacts.end()) { @@ -709,8 +656,7 @@ void Models::Roster::addPresence(const QString& account, const QString& jid, con } -void Models::Roster::removePresence(const QString& account, const QString& jid, const QString& name) -{ +void Models::Roster::removePresence(const QString& account, const QString& jid, const QString& name) { ElId contactId(account, jid); std::map::iterator itr = contacts.find(contactId); if (itr != contacts.end()) { @@ -718,16 +664,13 @@ void Models::Roster::removePresence(const QString& account, const QString& jid, } } -void Models::Roster::addMessage(const QString& account, const Shared::Message& data) -{ +void Models::Roster::addMessage(const QString& account, const Shared::Message& data) { Element* el = getElement(ElId(account, data.getPenPalJid())); - if (el != nullptr) { + if (el != nullptr) el->addMessage(data); - } } -void Models::Roster::removeAccount(const QString& account) -{ +void Models::Roster::removeAccount(const QString& account) { std::map::const_iterator itr = accounts.find(account); if (itr == accounts.end()) { qDebug() << "An attempt to remove non existing account " << account << ", skipping"; @@ -777,26 +720,23 @@ void Models::Roster::removeAccount(const QString& account) acc->deleteLater(); } -QString Models::Roster::getContactName(const QString& account, const QString& jid) const -{ +QString Models::Roster::getContactName(const QString& account, const QString& jid) const { ElId id(account, jid); std::map::const_iterator cItr = contacts.find(id); QString name = ""; if (cItr == contacts.end()) { std::map::const_iterator rItr = rooms.find(id); - if (rItr == rooms.end()) { + if (rItr == rooms.end()) qDebug() << "An attempt to get a name of non existing contact/room " << account << ":" << jid << ", skipping"; - } else { + else name = rItr->second->getRoomName(); - } } else { name = cItr->second->getContactName(); } return name; } -void Models::Roster::addRoom(const QString& account, const QString jid, const QMap& data) -{ +void Models::Roster::addRoom(const QString& account, const QString jid, const QMap& data) { Account* acc; { std::map::iterator itr = accounts.find(account); @@ -826,8 +766,7 @@ void Models::Roster::addRoom(const QString& account, const QString jid, const QM emit addedElement({acc->getId(), room->getId()}); } -void Models::Roster::changeRoom(const QString& account, const QString jid, const QMap& data) -{ +void Models::Roster::changeRoom(const QString& account, const QString jid, const QMap& data) { ElId id = {account, jid}; std::map::const_iterator itr = rooms.find(id); if (itr == rooms.end()) { @@ -840,8 +779,7 @@ void Models::Roster::changeRoom(const QString& account, const QString jid, const } } -void Models::Roster::removeRoom(const QString& account, const QString jid) -{ +void Models::Roster::removeRoom(const QString& account, const QString jid) { Account* acc; { std::map::iterator itr = accounts.find(account); @@ -865,8 +803,7 @@ void Models::Roster::removeRoom(const QString& account, const QString jid) rooms.erase(itr); } -void Models::Roster::addRoomParticipant(const QString& account, const QString& jid, const QString& name, const QMap& data) -{ +void Models::Roster::addRoomParticipant(const QString& account, const QString& jid, const QString& name, const QMap& data) { ElId id = {account, jid}; std::map::const_iterator itr = rooms.find(id); if (itr == rooms.end()) { @@ -877,8 +814,7 @@ void Models::Roster::addRoomParticipant(const QString& account, const QString& j } } -void Models::Roster::changeRoomParticipant(const QString& account, const QString& jid, const QString& name, const QMap& data) -{ +void Models::Roster::changeRoomParticipant(const QString& account, const QString& jid, const QString& name, const QMap& data) { ElId id = {account, jid}; std::map::const_iterator itr = rooms.find(id); if (itr == rooms.end()) { @@ -889,8 +825,7 @@ void Models::Roster::changeRoomParticipant(const QString& account, const QString } } -void Models::Roster::removeRoomParticipant(const QString& account, const QString& jid, const QString& name) -{ +void Models::Roster::removeRoomParticipant(const QString& account, const QString& jid, const QString& name) { ElId id = {account, jid}; std::map::const_iterator itr = rooms.find(id); if (itr == rooms.end()) { @@ -901,20 +836,17 @@ void Models::Roster::removeRoomParticipant(const QString& account, const QString } } -std::deque Models::Roster::groupList(const QString& account) const -{ +std::deque Models::Roster::groupList(const QString& account) const { std::deque answer; for (std::pair pair : groups) { - if (pair.first.account == account) { + if (pair.first.account == account) answer.push_back(pair.first.name); - } } return answer; } -bool Models::Roster::groupHasContact(const QString& account, const QString& group, const QString& contact) const -{ +bool Models::Roster::groupHasContact(const QString& account, const QString& group, const QString& contact) const { ElId grId({account, group}); std::map::const_iterator gItr = groups.find(grId); if (gItr == groups.end()) { @@ -924,22 +856,19 @@ bool Models::Roster::groupHasContact(const QString& account, const QString& grou } } -QString Models::Roster::getContactIconPath(const QString& account, const QString& jid, const QString& resource) const -{ +QString Models::Roster::getContactIconPath(const QString& account, const QString& jid, const QString& resource) const { ElId id(account, jid); std::map::const_iterator cItr = contacts.find(id); QString path = ""; if (cItr == contacts.end()) { std::map::const_iterator rItr = rooms.find(id); - if (rItr == rooms.end()) { + if (rItr == rooms.end()) qDebug() << "An attempt to get an icon path of non existing contact" << account << ":" << jid << ", returning empty value"; - } else { + else path = rItr->second->getParticipantIconPath(resource); - } } else { - if (cItr->second->getAvatarState() != Shared::Avatar::empty) { + if (cItr->second->getAvatarState() != Shared::Avatar::empty) path = cItr->second->getAvatarPath(); - } } return path; } @@ -950,34 +879,29 @@ Models::Account * Models::Roster::getAccount(const QString& name) { const Models::Account * Models::Roster::getAccountConst(const QString& name) const { return accounts.at(name);} -const Models::Element * Models::Roster::getElementConst(const Models::Roster::ElId& id) const -{ +const Models::Element * Models::Roster::getElementConst(const Models::Roster::ElId& id) const { std::map::const_iterator cItr = contacts.find(id); if (cItr != contacts.end()) { return cItr->second; } else { std::map::const_iterator rItr = rooms.find(id); - if (rItr != rooms.end()) { + if (rItr != rooms.end()) return rItr->second; - } } return nullptr; } -bool Models::Roster::markMessageAsRead(const Models::Roster::ElId& elementId, const QString& messageId) -{ +bool Models::Roster::markMessageAsRead(const Models::Roster::ElId& elementId, const QString& messageId) { const Element* el = getElementConst(elementId); - if (el != nullptr) { + if (el != nullptr) return el->markMessageAsRead(messageId); - } else { + else return false; - } } -QModelIndex Models::Roster::getAccountIndex(const QString& name) const -{ +QModelIndex Models::Roster::getAccountIndex(const QString& name) const { std::map::const_iterator itr = accounts.find(name); if (itr == accounts.end()) { return QModelIndex(); @@ -986,8 +910,7 @@ QModelIndex Models::Roster::getAccountIndex(const QString& name) const } } -QModelIndex Models::Roster::getGroupIndex(const QString& account, const QString& name) const -{ +QModelIndex Models::Roster::getGroupIndex(const QString& account, const QString& name) const { std::map::const_iterator itr = accounts.find(account); if (itr == accounts.end()) { return QModelIndex(); @@ -1002,8 +925,7 @@ QModelIndex Models::Roster::getGroupIndex(const QString& account, const QString& } } -QModelIndex Models::Roster::getContactIndex(const QString& account, const QString& jid, const QString& resource) const -{ +QModelIndex Models::Roster::getContactIndex(const QString& account, const QString& jid, const QString& resource) const { std::map::const_iterator itr = accounts.find(account); if (itr == accounts.end()) { return QModelIndex(); @@ -1017,11 +939,10 @@ QModelIndex Models::Roster::getContactIndex(const QString& account, const QStrin return contactIndex; } else { Presence* pres = cItr->second->getPresence(resource); - if (pres != nullptr) { + if (pres != nullptr) return index(pres->row(), 0, contactIndex); - } else { + else return contactIndex; - } } } else { std::map::const_iterator rItr = rooms.find(ElId(account, jid)); @@ -1031,11 +952,10 @@ QModelIndex Models::Roster::getContactIndex(const QString& account, const QStrin return roomIndex; } else { Participant* part = rItr->second->getParticipant(resource); - if (part != nullptr) { + if (part != nullptr) return index(part->row(), 0, roomIndex); - } else { + else return roomIndex; - } } } else { return QModelIndex(); @@ -1044,93 +964,78 @@ QModelIndex Models::Roster::getContactIndex(const QString& account, const QStrin } } -void Models::Roster::onElementRequestArchive(const QString& before) -{ +void Models::Roster::onElementRequestArchive(const QString& before) { Element* el = static_cast(sender()); emit requestArchive(el->getAccountName(), el->getJid(), before); } -void Models::Roster::responseArchive(const QString& account, const QString& jid, const std::list& list, bool last) -{ +void Models::Roster::responseArchive(const QString& account, const QString& jid, const std::list& list, bool last) { ElId id(account, jid); Element* el = getElement(id); - if (el != nullptr) { + if (el != nullptr) el->responseArchive(list, last); - } } -void Models::Roster::fileProgress(const std::list& msgs, qreal value, bool up) -{ +void Models::Roster::fileProgress(const std::list& msgs, qreal value, bool up) { for (const Shared::MessageInfo& info : msgs) { Element* el = getElement(ElId(info.account, info.jid)); - if (el != nullptr) { + if (el != nullptr) el->fileProgress(info.messageId, value, up); - } } } -void Models::Roster::fileComplete(const std::list& msgs, bool up) -{ +void Models::Roster::fileComplete(const std::list& msgs, bool up) { for (const Shared::MessageInfo& info : msgs) { Element* el = getElement(ElId(info.account, info.jid)); - if (el != nullptr) { + if (el != nullptr) el->fileComplete(info.messageId, up); - } } } -void Models::Roster::fileError(const std::list& msgs, const QString& err, bool up) -{ +void Models::Roster::fileError(const std::list& msgs, const QString& err, bool up) { for (const Shared::MessageInfo& info : msgs) { Element* el = getElement(ElId(info.account, info.jid)); - if (el != nullptr) { + if (el != nullptr) el->fileError(info.messageId, err, up); - } } } -Models::Element * Models::Roster::getElement(const Models::Roster::ElId& id) -{ +Models::Element * Models::Roster::getElement(const Models::Roster::ElId& id) { return const_cast(getElementConst(id)); } -Models::Item::Type Models::Roster::getContactType(const Models::Roster::ElId& id) const -{ +Models::Item::Type Models::Roster::getContactType(const Models::Roster::ElId& id) const { const Models::Element* el = getElementConst(id); - if (el == nullptr) { + if (el == nullptr) return Item::root; - } + return el->type; } -void Models::Roster::onAccountReconnected() -{ +void Models::Roster::onAccountReconnected() { Account* acc = static_cast(sender()); QString accName = acc->getName(); for (const std::pair& pair : contacts) { - if (pair.first.account == accName) { + if (pair.first.account == accName) pair.second->handleRecconnect(); - } } } -void Models::Roster::recalculateUnreadMessages() -{ +void Models::Roster::recalculateUnreadMessages() { int count(0); - for (const std::pair& pair : contacts) { + for (const std::pair& pair : contacts) count += pair.second->getMessagesCount(); - } - for (const std::pair& pair : rooms) { + + for (const std::pair& pair : rooms) count += pair.second->getMessagesCount(); - } + emit unreadMessagesCountChanged(count); } -std::list Models::Roster::getItemPath(const QModelIndex& index) const -{ +std::list Models::Roster::getItemPath(const QModelIndex& index) const { std::list result; if (index.isValid() && index.model() == this) { Item* item = static_cast(index.internalPointer()); @@ -1143,8 +1048,7 @@ std::list Models::Roster::getItemPath(const QModelIndex& index) const return result; } -QModelIndex Models::Roster::getIndexByPath(const std::list& path) const -{ +QModelIndex Models::Roster::getIndexByPath(const std::list& path) const { if (path.empty()) return QModelIndex(); diff --git a/ui/utils/comboboxdelegate.cpp b/ui/utils/comboboxdelegate.cpp index 4c96c79..cbaa1e3 100644 --- a/ui/utils/comboboxdelegate.cpp +++ b/ui/utils/comboboxdelegate.cpp @@ -18,35 +18,30 @@ #include "QTimer" #include "comboboxdelegate.h" +#include "shared/defines.h" ComboboxDelegate::ComboboxDelegate(QObject *parent): QStyledItemDelegate(parent), entries(), ff(new FocusFilter()) -{ -} +{} - -ComboboxDelegate::~ComboboxDelegate() -{ +ComboboxDelegate::~ComboboxDelegate() { delete ff; } - -QWidget* ComboboxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const -{ +QWidget* ComboboxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { + SHARED_UNUSED(option); + SHARED_UNUSED(index); QComboBox *cb = new QComboBox(parent); - - for (const std::pair& pair : entries) { + for (const std::pair& pair : entries) cb->addItem(pair.second, pair.first); - } return cb; } -void ComboboxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const -{ +void ComboboxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QComboBox *cb = static_cast(editor); int currentIndex = index.data(Qt::EditRole).toInt(); if (currentIndex >= 0) { @@ -56,19 +51,16 @@ void ComboboxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) } -void ComboboxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const -{ +void ComboboxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QComboBox *cb = static_cast(editor); model->setData(index, cb->currentIndex(), Qt::EditRole); } -void ComboboxDelegate::addEntry(const QString& title, const QIcon& icon) -{ +void ComboboxDelegate::addEntry(const QString& title, const QIcon& icon) { entries.emplace_back(title, icon); } -bool ComboboxDelegate::FocusFilter::eventFilter(QObject* src, QEvent* evt) -{ +bool ComboboxDelegate::FocusFilter::eventFilter(QObject* src, QEvent* evt) { if (evt->type() == QEvent::FocusIn) { QComboBox* cb = static_cast(src); cb->removeEventFilter(this); diff --git a/ui/utils/resizer.cpp b/ui/utils/resizer.cpp index 8691400..ad62e6d 100644 --- a/ui/utils/resizer.cpp +++ b/ui/utils/resizer.cpp @@ -18,14 +18,13 @@ #include "resizer.h" -Resizer::Resizer(QWidget* parent): -QObject(parent) -{ - -} +#include "shared/defines.h" -bool Resizer::eventFilter(QObject* obj, QEvent* event) -{ +Resizer::Resizer(QWidget* parent): +QObject(parent) {} + +bool Resizer::eventFilter(QObject* obj, QEvent* event) { + SHARED_UNUSED(obj); if (event->type() == QEvent::Resize) { QResizeEvent* ev = static_cast(event); emit resized(ev->oldSize(), ev->size()); diff --git a/ui/widgets/chat.cpp b/ui/widgets/chat.cpp index 301553b..3b9f090 100644 --- a/ui/widgets/chat.cpp +++ b/ui/widgets/chat.cpp @@ -19,6 +19,8 @@ #include "chat.h" #include "ui_conversation.h" +#include "shared/defines.h" + Chat::Chat(Models::Account* acc, Models::Contact* p_contact, QWidget* parent): Conversation(false, acc, p_contact, p_contact->getJid(), "", parent), contact(p_contact) @@ -39,6 +41,7 @@ Chat::~Chat() {} void Chat::onContactChanged(Models::Item* item, int row, int col) { + SHARED_UNUSED(row); if (item == contact) { switch (col) { case 0: diff --git a/ui/widgets/conversation.cpp b/ui/widgets/conversation.cpp index c11449f..e6316c7 100644 --- a/ui/widgets/conversation.cpp +++ b/ui/widgets/conversation.cpp @@ -115,15 +115,14 @@ Conversation::Conversation(bool muc, Models::Account* acc, Models::Element* el, initializeOverlay(); } -Conversation::~Conversation() -{ +Conversation::~Conversation() { delete contextMenu; element->feed->decrementObservers(); } -void Conversation::onAccountChanged(Models::Item* item, int row, int col) -{ +void Conversation::onAccountChanged(Models::Item* item, int row, int col) { + SHARED_UNUSED(row); if (item == account) { if (col == 2 && account->getState() == Shared::ConnectionState::connected) { //to request the history when we're back online after reconnect //if (!requestingHistory) { @@ -136,8 +135,7 @@ void Conversation::onAccountChanged(Models::Item* item, int row, int col) } } -void Conversation::initializeOverlay() -{ +void Conversation::initializeOverlay() { QGridLayout* gr = static_cast(layout()); QLabel* progressLabel = new QLabel(tr("Drop files here to attach them to your message")); gr->addWidget(overlay, 0, 0, 2, 1); @@ -160,26 +158,22 @@ void Conversation::initializeOverlay() overlay->hide(); } -void Conversation::setName(const QString& name) -{ +void Conversation::setName(const QString& name) { m_ui->nameLabel->setText(name); setWindowTitle(name); } -QString Conversation::getAccount() const -{ +QString Conversation::getAccount() const { return account->getName(); } -QString Conversation::getJid() const -{ +QString Conversation::getJid() const { return palJid; } KeyEnterReceiver::KeyEnterReceiver(QObject* parent): QObject(parent), ownEvent(false) {} -bool KeyEnterReceiver::eventFilter(QObject* obj, QEvent* event) -{ +bool KeyEnterReceiver::eventFilter(QObject* obj, QEvent* event) { QEvent::Type type = event->type(); if (type == QEvent::KeyPress) { QKeyEvent* key = static_cast(event); @@ -215,18 +209,15 @@ bool Conversation::checkClipboardImage() { return !QApplication::clipboard()->image().isNull(); } -QString Conversation::getPalResource() const -{ +QString Conversation::getPalResource() const { return activePalResource; } -void Conversation::setPalResource(const QString& res) -{ +void Conversation::setPalResource(const QString& res) { activePalResource = res; } -void Conversation::initiateMessageSending() -{ +void Conversation::initiateMessageSending() { QString body(m_ui->messageEditor->toPlainText()); if (body.size() > 0) { @@ -245,8 +236,7 @@ void Conversation::initiateMessageSending() clear(); } -void Conversation::initiateMessageSending(const Shared::Message& msg) -{ +void Conversation::initiateMessageSending(const Shared::Message& msg) { if (currentAction == CurrentAction::edit) { emit replaceMessage(currentMessageId, msg); currentAction = CurrentAction::none; @@ -255,12 +245,11 @@ void Conversation::initiateMessageSending(const Shared::Message& msg) } } -void Conversation::onImagePasted() -{ +void Conversation::onImagePasted() { QImage image = QApplication::clipboard()->image(); - if (image.isNull()) { + if (image.isNull()) return; - } + QTemporaryFile *tempFile = new QTemporaryFile(QDir::tempPath() + QStringLiteral("/squawk_img_attach_XXXXXX.png"), QApplication::instance()); tempFile->open(); image.save(tempFile, "PNG"); @@ -273,8 +262,7 @@ void Conversation::onImagePasted() // See Core::NetworkAccess::onUploadFinished. } -void Conversation::onAttach() -{ +void Conversation::onAttach() { QFileDialog* d = new QFileDialog(this, tr("Chose a file to send")); d->setFileMode(QFileDialog::ExistingFile); @@ -284,37 +272,31 @@ void Conversation::onAttach() d->show(); } -void Conversation::onFileSelected() -{ +void Conversation::onFileSelected() { QFileDialog* d = static_cast(sender()); - - for (const QString& path : d->selectedFiles()) { + for (const QString& path : d->selectedFiles()) addAttachedFile(path); - } d->deleteLater(); } -void Conversation::setStatus(const QString& status) -{ +void Conversation::setStatus(const QString& status) { statusLabel->setText(Shared::processMessageBody(status)); } -Models::Roster::ElId Conversation::getId() const -{ +Models::Roster::ElId Conversation::getId() const { return {getAccount(), getJid()}; } -void Conversation::addAttachedFile(const QString& path) -{ +void Conversation::addAttachedFile(const QString& path) { QMimeDatabase db; QMimeType type = db.mimeTypeForFile(path); QFileInfo info(path); QIcon fileIcon = QIcon::fromTheme(type.iconName()); - if (fileIcon.isNull()) { + if (fileIcon.isNull()) fileIcon.addFile(QString::fromUtf8(":/images/fallback/dark/big/mail-attachment.svg"), QSize(), QIcon::Normal, QIcon::Off); - } + Badge* badge = new Badge(path, info.fileName(), fileIcon); connect(badge, &Badge::close, this, &Conversation::onBadgeClose); @@ -331,35 +313,31 @@ void Conversation::addAttachedFile(const QString& path) } } -void Conversation::removeAttachedFile(Badge* badge) -{ +void Conversation::removeAttachedFile(Badge* badge) { W::Order::const_iterator itr = filesToAttach.find(badge); if (itr != filesToAttach.end()) { filesToAttach.erase(badge); - if (filesLayout->count() == 1) { + if (filesLayout->count() == 1) filesLayout->setContentsMargins(0, 0, 0, 0); - } + badge->deleteLater(); } } -void Conversation::onBadgeClose() -{ +void Conversation::onBadgeClose() { Badge* badge = static_cast(sender()); removeAttachedFile(badge); } -void Conversation::clearAttachedFiles() -{ - for (Badge* badge : filesToAttach) { +void Conversation::clearAttachedFiles() { + for (Badge* badge : filesToAttach) badge->deleteLater(); - } + filesToAttach.clear(); filesLayout->setContentsMargins(0, 0, 0, 0); } -void Conversation::clear() -{ +void Conversation::clear() { currentMessageId.clear(); currentAction = CurrentAction::none; m_ui->currentActionBadge->setVisible(false); @@ -367,8 +345,7 @@ void Conversation::clear() m_ui->messageEditor->clear(); } -void Conversation::setAvatar(const QString& path) -{ +void Conversation::setAvatar(const QString& path) { QPixmap pixmap; if (path.size() == 0) { pixmap = Shared::icon("user", true).pixmap(avatarSize); @@ -390,13 +367,11 @@ void Conversation::setAvatar(const QString& path) m_ui->avatar->setPixmap(result); } -void Conversation::onTextEditDocSizeChanged(const QSizeF& size) -{ +void Conversation::onTextEditDocSizeChanged(const QSizeF& size) { m_ui->messageEditor->setMaximumHeight(int(size.height())); } -void Conversation::setFeedFrames(bool top, bool right, bool bottom, bool left) -{ +void Conversation::setFeedFrames(bool top, bool right, bool bottom, bool left) { shadow.setFrames(top, right, bottom, left); } @@ -421,13 +396,12 @@ void Conversation::dragEnterEvent(QDragEnterEvent* event) } } -void Conversation::dragLeaveEvent(QDragLeaveEvent* event) -{ +void Conversation::dragLeaveEvent(QDragLeaveEvent* event) { + SHARED_UNUSED(event); overlay->hide(); } -void Conversation::dropEvent(QDropEvent* event) -{ +void Conversation::dropEvent(QDropEvent* event) { bool accept = false; if (event->mimeData()->hasUrls()) { QList list = event->mimeData()->urls(); @@ -441,14 +415,13 @@ void Conversation::dropEvent(QDropEvent* event) } } } - if (accept) { + if (accept) event->acceptProposedAction(); - } + overlay->hide(); } -Shared::Message Conversation::createMessage() const -{ +Shared::Message Conversation::createMessage() const { Shared::Message msg; msg.setOutgoing(true); msg.generateRandomId(); @@ -457,23 +430,20 @@ Shared::Message Conversation::createMessage() const return msg; } -void Conversation::onFeedMessage(const Shared::Message& msg) -{ +void Conversation::onFeedMessage(const Shared::Message& msg) { this->onMessage(msg); } -void Conversation::onMessage(const Shared::Message& msg) -{ +void Conversation::onMessage(const Shared::Message& msg) { if (!msg.getForwarded()) { QApplication::alert(this); - if (window()->windowState().testFlag(Qt::WindowMinimized)) { + if (window()->windowState().testFlag(Qt::WindowMinimized)) emit notifyableMessage(getAccount(), msg); - } + } } -void Conversation::positionShadow() -{ +void Conversation::positionShadow() { int w = width(); int h = feed->height(); @@ -482,8 +452,7 @@ void Conversation::positionShadow() shadow.raise(); } -void Conversation::onFeedContext(const QPoint& pos) -{ +void Conversation::onFeedContext(const QPoint& pos) { QModelIndex index = feed->indexAt(pos); if (index.isValid()) { Shared::Message* item = static_cast(index.internalPointer()); @@ -542,14 +511,12 @@ void Conversation::onFeedContext(const QPoint& pos) connect(edit, &QAction::triggered, this, std::bind(&Conversation::onMessageEditRequested, this, id)); } - if (showMenu) { + if (showMenu) contextMenu->popup(feed->viewport()->mapToGlobal(pos)); - } } } -void Conversation::onMessageEditorContext(const QPoint& pos) -{ +void Conversation::onMessageEditorContext(const QPoint& pos) { pasteImageAction->setEnabled(Conversation::checkClipboardImage()); QMenu *editorMenu = m_ui->messageEditor->createStandardContextMenu(); @@ -559,8 +526,7 @@ void Conversation::onMessageEditorContext(const QPoint& pos) editorMenu->exec(this->m_ui->messageEditor->mapToGlobal(pos)); } -void Conversation::onMessageEditRequested(const QString& id) -{ +void Conversation::onMessageEditRequested(const QString& id) { clear(); try { @@ -582,8 +548,7 @@ void Conversation::onMessageEditRequested(const QString& id) } } -void Conversation::showEvent(QShowEvent* event) -{ +void Conversation::showEvent(QShowEvent* event) { QWidget::showEvent(event); emit shown(); diff --git a/ui/widgets/conversation.h b/ui/widgets/conversation.h index 0c44bd9..80c8c2f 100644 --- a/ui/widgets/conversation.h +++ b/ui/widgets/conversation.h @@ -34,6 +34,7 @@ #include "shared/icons.h" #include "shared/utils.h" #include "shared/pathcheck.h" +#include "shared/defines.h" #include "ui/models/account.h" #include "ui/models/roster.h" @@ -159,8 +160,6 @@ private: static QPainterPath* avatarMask; static QPixmap* avatarPixmap; static QPainter* avatarPainter; - - }; #endif // CONVERSATION_H diff --git a/ui/widgets/messageline/feedview.cpp b/ui/widgets/messageline/feedview.cpp index 9d222ae..43d0218 100644 --- a/ui/widgets/messageline/feedview.cpp +++ b/ui/widgets/messageline/feedview.cpp @@ -79,11 +79,10 @@ QModelIndex FeedView::indexAt(const QPoint& point) const { for (std::deque::size_type i = 0; i < hints.size(); ++i) { const Hint& hint = hints[i]; if (y <= hint.offset + hint.height) { - if (y > hint.offset) { + if (y > hint.offset) return model()->index(i, 0, rootIndex()); - } else { + else break; - } } } @@ -156,13 +155,11 @@ void FeedView::updateGeometries() { vo = 0; } else { int verticalMargin = 0; - if (st->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents)) { + if (st->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents)) frameAroundContents = st->pixelMetric(QStyle::PM_DefaultFrameWidth) * 2; - } - if (verticalScrollBarPolicy() == Qt::ScrollBarAsNeeded) { + if (verticalScrollBarPolicy() == Qt::ScrollBarAsNeeded) verticalMargin = verticalScrollBarExtent + frameAroundContents; - } layoutBounds.rwidth() -= verticalMargin; @@ -176,21 +173,19 @@ void FeedView::updateGeometries() { QModelIndex index = m->index(i, 0, rootIndex()); QDateTime currentDate = index.data(Models::MessageFeed::Date).toDateTime(); if (i > 0) { - if (currentDate.daysTo(lastDate) > 0) { + if (currentDate.daysTo(lastDate) > 0) previousOffset += dividerMetrics.height() + dateDeviderMargin * 2; - } else { + else previousOffset += elementMargin; - } } lastDate = currentDate; QSize messageSize = itemDelegate(index)->sizeHint(option, index); uint32_t offsetX(0); if (specialDelegate) { - if (index.data(Models::MessageFeed::SentByMe).toBool()) { + if (index.data(Models::MessageFeed::SentByMe).toBool()) offsetX = layoutBounds.width() - messageSize.width() - MessageDelegate::avatarHeight - MessageDelegate::margin * 2; - } else { + else offsetX = MessageDelegate::avatarHeight + MessageDelegate::margin * 2; - } } hints.emplace_back(Hint({ @@ -204,9 +199,9 @@ void FeedView::updateGeometries() { } int totalHeight = previousOffset - layoutBounds.height() + dividerMetrics.height() + dateDeviderMargin * 2; - if (modelState != Models::MessageFeed::complete) { + if (modelState != Models::MessageFeed::complete) totalHeight += progressSize; - } + vo = qMax(qMin(vo, totalHeight), 0); bar->setRange(0, totalHeight); bar->setPageStep(layoutBounds.height()); @@ -219,7 +214,6 @@ void FeedView::updateGeometries() { clearWidgetsMode = true; } - QAbstractItemView::updateGeometries(); } @@ -230,26 +224,23 @@ bool FeedView::tryToCalculateGeometriesWithNoScrollbars(const QStyleOptionViewIt QModelIndex index = m->index(i, 0, rootIndex()); QDateTime currentDate = index.data(Models::MessageFeed::Date).toDateTime(); if (i > 0) { - if (currentDate.daysTo(lastDate) > 0) { + if (currentDate.daysTo(lastDate) > 0) previousOffset += dateDeviderMargin * 2 + dividerMetrics.height(); - } else { + else previousOffset += elementMargin; - } } lastDate = currentDate; QSize messageSize = itemDelegate(index)->sizeHint(option, index); - if (previousOffset + messageSize.height() + elementMargin > totalHeight) { + if (previousOffset + messageSize.height() + elementMargin > totalHeight) return false; - } uint32_t offsetX(0); if (specialDelegate) { - if (index.data(Models::MessageFeed::SentByMe).toBool()) { + if (index.data(Models::MessageFeed::SentByMe).toBool()) offsetX = option.rect.width() - messageSize.width() - MessageDelegate::avatarHeight - MessageDelegate::margin * 2; - } else { + else offsetX = MessageDelegate::avatarHeight + MessageDelegate::margin * 2; - } } hints.emplace_back(Hint({ false, @@ -262,9 +253,8 @@ bool FeedView::tryToCalculateGeometriesWithNoScrollbars(const QStyleOptionViewIt } previousOffset += dateDeviderMargin * 2 + dividerMetrics.height(); - if (previousOffset > totalHeight) { + if (previousOffset > totalHeight) return false; - } return true; } @@ -284,13 +274,12 @@ void FeedView::paintEvent(QPaintEvent* event) { const Hint& hint = hints[i]; int32_t relativeY1 = vph - hint.offset - hint.height; if (!inZone) { - if (y2 > relativeY1) { + if (y2 > relativeY1) inZone = true; - } } - if (inZone) { + if (inZone) toRener.emplace_back(m->index(i, 0, rootIndex())); - } + if (y1 > relativeY1) { inZone = false; break; @@ -304,9 +293,8 @@ void FeedView::paintEvent(QPaintEvent* event) { if (specialDelegate) { MessageDelegate* del = static_cast(itemDelegate()); - if (clearWidgetsMode) { + if (clearWidgetsMode) del->beginClearWidgets(); - } } QDateTime lastDate; @@ -319,9 +307,8 @@ void FeedView::paintEvent(QPaintEvent* event) { int ind = index.row() - 1; if (ind > 0) { QDateTime underDate = m->index(ind, 0, rootIndex()).data(Models::MessageFeed::Date).toDateTime(); - if (currentDate.daysTo(underDate) > 0) { + if (currentDate.daysTo(underDate) > 0) drawDateDevider(option.rect.bottom(), underDate, painter); - } } first = false; } @@ -332,14 +319,13 @@ void FeedView::paintEvent(QPaintEvent* event) { option.state.setFlag(QStyle::State_MouseOver, mouseOver); itemDelegate(index)->paint(&painter, option, index); - if (!lastDate.isNull() && currentDate.daysTo(lastDate) > 0) { + if (!lastDate.isNull() && currentDate.daysTo(lastDate) > 0) drawDateDevider(option.rect.bottom(), lastDate, painter); - } + lastDate = currentDate; } - if (!lastDate.isNull() && inZone) { //if after drawing all messages there is still space + if (!lastDate.isNull() && inZone) //if after drawing all messages there is still space drawDateDevider(option.rect.top() - dateDeviderMargin * 2 - dividerMetrics.height(), lastDate, painter); - } if (clearWidgetsMode && specialDelegate) { MessageDelegate* del = static_cast(itemDelegate()); @@ -362,13 +348,11 @@ void FeedView::verticalScrollbarValueChanged(int value) { positionProgress(); - if (specialDelegate) { + if (specialDelegate) clearWidgetsMode = true; - } - if (modelState == Models::MessageFeed::incomplete && value < progressSize) { + if (modelState == Models::MessageFeed::incomplete && value < progressSize) model()->fetchMore(rootIndex()); - } QAbstractItemView::verticalScrollbarValueChanged(vo); } @@ -391,16 +375,14 @@ void FeedView::setAnchorHovered(Shared::Hover type) { } void FeedView::mouseMoveEvent(QMouseEvent* event) { - if (!isVisible()) { + if (!isVisible()) return; - } dragEndPoint = event->localPos().toPoint(); if (mousePressed) { QPoint distance = dragStartPoint - dragEndPoint; - if (distance.manhattanLength() > 5) { + if (distance.manhattanLength() > 5) dragging = true; - } } QAbstractItemView::mouseMoveEvent(event); @@ -423,11 +405,10 @@ void FeedView::mouseMoveEvent(QMouseEvent* event) { QModelIndex index = indexAt(dragEndPoint); if (index.isValid()) { QRect rect = visualRect(index); - if (rect.contains(dragEndPoint)) { + if (rect.contains(dragEndPoint)) setAnchorHovered(del->hoverType(dragEndPoint, index, rect)); - } else { + else setAnchorHovered(Shared::Hover::nothing); - } } else { setAnchorHovered(Shared::Hover::nothing); } @@ -447,9 +428,8 @@ void FeedView::mousePressEvent(QMouseEvent* event) { if (lastSelectedId.size()) { Models::MessageFeed* feed = static_cast(model()); QModelIndex index = feed->modelIndexById(lastSelectedId); - if (index.isValid()) { + if (index.isValid()) setDirtyRegion(visualRect(index)); - } } } } @@ -467,18 +447,16 @@ void FeedView::mouseDoubleClickEvent(QMouseEvent* event) { if (lastSelectedId.size()) { Models::MessageFeed* feed = static_cast(model()); QModelIndex index = feed->modelIndexById(lastSelectedId); - if (index.isValid()) { + if (index.isValid()) setDirtyRegion(visualRect(index)); - } } QModelIndex index = indexAt(dragStartPoint); QRect rect = visualRect(index); if (rect.contains(dragStartPoint)) { selectedText = del->leftDoubleClick(dragStartPoint, index, rect); - if (selectedText.size() > 0) { + if (selectedText.size() > 0) setDirtyRegion(rect); - } } } } @@ -494,9 +472,8 @@ void FeedView::mouseReleaseEvent(QMouseEvent* event) { if (index.isValid()) { QRect rect = visualRect(index); MessageDelegate* del = static_cast(itemDelegate()); - if (rect.contains(point)) { + if (rect.contains(point)) del->leftClick(point, index, rect); - } } } dragging = false; diff --git a/ui/widgets/messageline/messagedelegate.cpp b/ui/widgets/messageline/messagedelegate.cpp index 1830d71..35a73c2 100644 --- a/ui/widgets/messageline/messagedelegate.cpp +++ b/ui/widgets/messageline/messagedelegate.cpp @@ -29,6 +29,8 @@ #include "messagedelegate.h" #include "messagefeed.h" +#include "shared/defines.h" + constexpr int textMargin = 2; constexpr int statusIconSize = 16; @@ -70,27 +72,21 @@ MessageDelegate::MessageDelegate(QObject* parent): barHeight = bar.sizeHint().height(); } -MessageDelegate::~MessageDelegate() -{ - for (const std::pair& pair: *buttons){ +MessageDelegate::~MessageDelegate() { + for (const std::pair& pair: *buttons) delete pair.second; - } - for (const std::pair& pair: *bars){ + for (const std::pair& pair: *bars) delete pair.second; - } - for (const std::pair& pair: *statusIcons){ + for (const std::pair& pair: *statusIcons) delete pair.second; - } - for (const std::pair& pair: *pencilIcons){ + for (const std::pair& pair: *pencilIcons) delete pair.second; - } - for (const std::pair& pair: *previews){ + for (const std::pair& pair: *previews) delete pair.second; - } delete statusIcons; delete pencilIcons; @@ -101,29 +97,26 @@ MessageDelegate::~MessageDelegate() delete bodyRenderer; } -void MessageDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const -{ +void MessageDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QVariant vi = index.data(Models::MessageFeed::Bulk); - if (!vi.isValid()) { + if (!vi.isValid()) return; - } + Models::FeedItem data = qvariant_cast(vi); painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); paintBubble(data, painter, option); bool ntds = needToDrawSender(index, data); - if (ntds || option.rect.y() < 1) { + if (ntds || option.rect.y() < 1) paintAvatar(data, index, option, painter); - } QStyleOptionViewItem opt = option; opt.rect = option.rect.adjusted(bubbleMargin, bubbleMargin, -bubbleMargin, -bubbleMargin / 2); - if (!data.sentByMe) { + if (!data.sentByMe) opt.displayAlignment = Qt::AlignLeft | Qt::AlignTop; - } else { + else opt.displayAlignment = Qt::AlignRight | Qt::AlignTop; - } QRect rect; if (ntds) { @@ -189,11 +182,11 @@ void MessageDelegate::paint(QPainter* painter, const QStyleOptionViewItem& optio QLabel* pencilIcon = getPencilIcon(data); pencilIcon->setParent(vp); - if (data.sentByMe) { + if (data.sentByMe) pencilIcon->move(opt.rect.left() + statusIconSize + margin, currentY); - } else { + else pencilIcon->move(opt.rect.right() - statusIconSize - margin, currentY); - } + pencilIcon->show(); } else { std::map::const_iterator itr = pencilIcons->find(data.id); @@ -205,27 +198,24 @@ void MessageDelegate::paint(QPainter* painter, const QStyleOptionViewItem& optio painter->restore(); - if (clearingWidgets) { + if (clearingWidgets) idsToKeep->insert(data.id); - } } -void MessageDelegate::paintBubble(const Models::FeedItem& data, QPainter* painter, const QStyleOptionViewItem& option) const -{ +void MessageDelegate::paintBubble(const Models::FeedItem& data, QPainter* painter, const QStyleOptionViewItem& option) const { painter->save(); - if (data.sentByMe) { + if (data.sentByMe) painter->setBrush(option.palette.brush(QPalette::Inactive, QPalette::Highlight)); - } else { + else painter->setBrush(option.palette.brush(QPalette::Window)); - } + painter->setPen(Qt::NoPen); painter->drawRoundedRect(option.rect, bubbleBorderRadius, bubbleBorderRadius); painter->restore(); } -void MessageDelegate::paintAvatar(const Models::FeedItem& data, const QModelIndex& index, const QStyleOptionViewItem& option, QPainter* painter) const -{ +void MessageDelegate::paintAvatar(const Models::FeedItem& data, const QModelIndex& index, const QStyleOptionViewItem& option, QPainter* painter) const { int currentRow = index.row(); int y = option.rect.y(); bool firstAttempt = true; @@ -255,11 +245,10 @@ void MessageDelegate::paintAvatar(const Models::FeedItem& data, const QModelInde QPainterPath path; int ax; - if (data.sentByMe) { + if (data.sentByMe) ax = option.rect.x() + option.rect.width() + margin; - } else { + else ax = margin; - } path.addEllipse(ax, y + margin / 2, avatarHeight, avatarHeight); painter->save(); @@ -268,8 +257,7 @@ void MessageDelegate::paintAvatar(const Models::FeedItem& data, const QModelInde painter->restore(); } -bool MessageDelegate::needToDrawAvatar(const QModelIndex& index, const Models::FeedItem& data, const QStyleOptionViewItem& option) const -{ +bool MessageDelegate::needToDrawAvatar(const QModelIndex& index, const Models::FeedItem& data, const QStyleOptionViewItem& option) const { return (option.rect.y() < 1) || needToDrawSender(index, data); } @@ -285,8 +273,7 @@ bool MessageDelegate::needToDrawSender(const QModelIndex& index, const Models::F } } -QSize MessageDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const -{ +QSize MessageDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { QRect messageRect = option.rect.adjusted(bubbleMargin, margin / 2 + bubbleMargin, -(avatarHeight + 3 * margin + bubbleMargin), -(margin + bubbleMargin) / 2); QStyleOptionViewItem opt = option; opt.rect = messageRect; @@ -360,12 +347,10 @@ QSize MessageDelegate::sizeHint(const QStyleOptionViewItem& option, const QModel return messageSize; } -QRect MessageDelegate::getHoveredMessageBodyRect(const QModelIndex& index, const Models::FeedItem& data, const QRect& sizeHint) const -{ +QRect MessageDelegate::getHoveredMessageBodyRect(const QModelIndex& index, const Models::FeedItem& data, const QRect& sizeHint) const { QRect localHint = sizeHint.adjusted(bubbleMargin, bubbleMargin + margin, -bubbleMargin, -bubbleMargin / 2); - if (needToDrawSender(index, data)) { + if (needToDrawSender(index, data)) localHint.adjust(0, nickMetrics.lineSpacing() + textMargin, 0, 0); - } int attachHeight = 0; switch (data.attach.state) { @@ -405,8 +390,7 @@ QRect MessageDelegate::getHoveredMessageBodyRect(const QModelIndex& index, const return localHint; } -QString MessageDelegate::getAnchor(const QPoint& point, const QModelIndex& index, const QRect& sizeHint) const -{ +QString MessageDelegate::getAnchor(const QPoint& point, const QModelIndex& index, const QRect& sizeHint) const { QVariant vi = index.data(Models::MessageFeed::Bulk); Models::FeedItem data = qvariant_cast(vi); if (data.text.size() > 0) { @@ -425,16 +409,13 @@ QString MessageDelegate::getAnchor(const QPoint& point, const QModelIndex& index return QString(); } -void MessageDelegate::leftClick(const QPoint& point, const QModelIndex& index, const QRect& sizeHint) const -{ +void MessageDelegate::leftClick(const QPoint& point, const QModelIndex& index, const QRect& sizeHint) const { QString anchor = getAnchor(point, index, sizeHint); - if (anchor.size() > 0) { + if (anchor.size() > 0) emit openLink(anchor); - } } -QString MessageDelegate::leftDoubleClick(const QPoint& point, const QModelIndex& index, const QRect& sizeHint) -{ +QString MessageDelegate::leftDoubleClick(const QPoint& point, const QModelIndex& index, const QRect& sizeHint) { QVariant vi = index.data(Models::MessageFeed::Bulk); Models::FeedItem data = qvariant_cast(vi); if (data.text.size() > 0) { @@ -466,8 +447,7 @@ QString MessageDelegate::leftDoubleClick(const QPoint& point, const QModelIndex& return ""; } -Shared::Hover MessageDelegate::hoverType(const QPoint& point, const QModelIndex& index, const QRect& sizeHint) const -{ +Shared::Hover MessageDelegate::hoverType(const QPoint& point, const QModelIndex& index, const QRect& sizeHint) const { QVariant vi = index.data(Models::MessageFeed::Bulk); Models::FeedItem data = qvariant_cast(vi); if (data.text.size() > 0) { @@ -486,17 +466,15 @@ Shared::Hover MessageDelegate::hoverType(const QPoint& point, const QModelIndex& return Shared::Hover::anchor; } else { int position = lay->hitTest(translated, Qt::HitTestAccuracy::ExactHit); - if (position != -1) { + if (position != -1) return Shared::Hover::text; - } } } } return Shared::Hover::nothing; } -QString MessageDelegate::mouseDrag(const QPoint& start, const QPoint& end, const QModelIndex& index, const QRect& sizeHint) -{ +QString MessageDelegate::mouseDrag(const QPoint& start, const QPoint& end, const QModelIndex& index, const QRect& sizeHint) { QVariant vi = index.data(Models::MessageFeed::Bulk); Models::FeedItem data = qvariant_cast(vi); if (data.text.size() > 0) { @@ -529,30 +507,24 @@ QString MessageDelegate::mouseDrag(const QPoint& start, const QPoint& end, const return ""; } -QString MessageDelegate::clearSelection() -{ +QString MessageDelegate::clearSelection() { QString lastSelectedId = currentId; currentId = ""; selection = std::pair(0, 0); return lastSelectedId; } -bool MessageDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index) -{ +bool MessageDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index) { //qDebug() << event->type(); - - return QStyledItemDelegate::editorEvent(event, model, option, index); } -int MessageDelegate::paintButton(QPushButton* btn, QPainter* painter, bool sentByMe, QStyleOptionViewItem& option) const -{ +int MessageDelegate::paintButton(QPushButton* btn, QPainter* painter, bool sentByMe, QStyleOptionViewItem& option) const { QPoint start; - if (sentByMe) { + if (sentByMe) start = {option.rect.x() + option.rect.width() - btn->width(), option.rect.top()}; - } else { + else start = option.rect.topLeft(); - } QWidget* vp = static_cast(painter->device()); btn->setParent(vp); @@ -563,8 +535,7 @@ int MessageDelegate::paintButton(QPushButton* btn, QPainter* painter, bool sentB return btn->width(); } -int MessageDelegate::paintComment(const Models::FeedItem& data, QPainter* painter, QStyleOptionViewItem& option) const -{ +int MessageDelegate::paintComment(const Models::FeedItem& data, QPainter* painter, QStyleOptionViewItem& option) const { painter->setFont(dateFont); QColor q = painter->pen().color(); q.setAlpha(180); @@ -576,8 +547,8 @@ int MessageDelegate::paintComment(const Models::FeedItem& data, QPainter* painte return rect.width(); } -int MessageDelegate::paintBar(QProgressBar* bar, QPainter* painter, bool sentByMe, QStyleOptionViewItem& option) const -{ +int MessageDelegate::paintBar(QProgressBar* bar, QPainter* painter, bool sentByMe, QStyleOptionViewItem& option) const { + SHARED_UNUSED(sentByMe); QPoint start = option.rect.topLeft(); bar->resize(option.rect.width(), barHeight); @@ -589,8 +560,7 @@ int MessageDelegate::paintBar(QProgressBar* bar, QPainter* painter, bool sentByM return option.rect.width(); } -int MessageDelegate::paintPreview(const Models::FeedItem& data, QPainter* painter, QStyleOptionViewItem& option) const -{ +int MessageDelegate::paintPreview(const Models::FeedItem& data, QPainter* painter, QStyleOptionViewItem& option) const { Preview* preview = 0; std::map::iterator itr = previews->find(data.id); @@ -605,18 +575,16 @@ int MessageDelegate::paintPreview(const Models::FeedItem& data, QPainter* painte previews->insert(std::make_pair(data.id, preview)); } - if (!preview->isFileReachable()) { //this is the situation when the file preview couldn't be painted because the file was moved + if (!preview->isFileReachable()) //this is the situation when the file preview couldn't be painted because the file was moved emit invalidPath(data.id); //or deleted. This signal notifies the model, and the model notifies the core, preview can - } //handle being invalid for as long as I need and can be even become valid again with a new path - + //handle being invalid for as long as I need and can be even become valid again with a new path QSize pSize(preview->size()); option.rect.adjust(0, pSize.height() + textMargin, 0, 0); return pSize.width(); } -QPushButton * MessageDelegate::getButton(const Models::FeedItem& data) const -{ +QPushButton * MessageDelegate::getButton(const Models::FeedItem& data) const { std::map::const_iterator itr = buttons->find(data.id); FeedButton* result = 0; if (itr != buttons->end()) { @@ -640,8 +608,7 @@ QPushButton * MessageDelegate::getButton(const Models::FeedItem& data) const return result; } -QProgressBar * MessageDelegate::getBar(const Models::FeedItem& data) const -{ +QProgressBar * MessageDelegate::getBar(const Models::FeedItem& data) const { std::map::const_iterator barItr = bars->find(data.id); QProgressBar* result = 0; if (barItr != bars->end()) { @@ -665,8 +632,7 @@ QProgressBar * MessageDelegate::getBar(const Models::FeedItem& data) const return result; } -QLabel * MessageDelegate::getStatusIcon(const Models::FeedItem& data) const -{ +QLabel * MessageDelegate::getStatusIcon(const Models::FeedItem& data) const { std::map::const_iterator itr = statusIcons->find(data.id); QLabel* result = 0; @@ -680,9 +646,8 @@ QLabel * MessageDelegate::getStatusIcon(const Models::FeedItem& data) const QIcon q(Shared::icon(Shared::messageStateThemeIcons[static_cast(data.state)])); QString tt = Shared::Global::getName(data.state); if (data.state == Shared::Message::State::error) { - if (data.error > 0) { + if (data.error > 0) tt += ": " + data.error; - } } if (result->toolTip() != tt) { //If i just assign pixmap every time unconditionally result->setPixmap(q.pixmap(statusIconSize)); //it invokes an infinite cycle of repaint @@ -692,8 +657,7 @@ QLabel * MessageDelegate::getStatusIcon(const Models::FeedItem& data) const return result; } -QLabel * MessageDelegate::getPencilIcon(const Models::FeedItem& data) const -{ +QLabel * MessageDelegate::getPencilIcon(const Models::FeedItem& data) const { std::map::const_iterator itr = pencilIcons->find(data.id); QLabel* result = 0; @@ -755,14 +719,12 @@ int MessageDelegate::paintBody(const Models::FeedItem& data, QPainter* painter, return 0; } -void MessageDelegate::beginClearWidgets() -{ +void MessageDelegate::beginClearWidgets() { idsToKeep->clear(); clearingWidgets = true; } -void MessageDelegate::endClearWidgets() -{ +void MessageDelegate::endClearWidgets() { if (clearingWidgets) { removeElements(buttons, idsToKeep); removeElements(bars, idsToKeep); @@ -775,14 +737,12 @@ void MessageDelegate::endClearWidgets() } } -void MessageDelegate::onButtonPushed() const -{ +void MessageDelegate::onButtonPushed() const { FeedButton* btn = static_cast(sender()); emit buttonPushed(btn->messageId); } -void MessageDelegate::clearHelperWidget(const Models::FeedItem& data) const -{ +void MessageDelegate::clearHelperWidget(const Models::FeedItem& data) const { std::map::const_iterator itr = buttons->find(data.id); if (itr != buttons->end()) { delete itr->second; diff --git a/ui/widgets/messageline/messagedelegate.h b/ui/widgets/messageline/messagedelegate.h index a05b4cd..16e39ff 100644 --- a/ui/widgets/messageline/messagedelegate.h +++ b/ui/widgets/messageline/messagedelegate.h @@ -30,6 +30,8 @@ #include #include #include +#include +#include #include "shared/icons.h" #include "shared/global.h" diff --git a/ui/widgets/messageline/messagefeed.cpp b/ui/widgets/messageline/messagefeed.cpp index af772fd..1eba1fa 100644 --- a/ui/widgets/messageline/messagefeed.cpp +++ b/ui/widgets/messageline/messagefeed.cpp @@ -20,6 +20,7 @@ #include #include +#include #include @@ -228,24 +229,20 @@ std::set Models::MessageFeed::detectChanges(c return roles; } -void Models::MessageFeed::removeMessage(const QString& id) -{ +void Models::MessageFeed::removeMessage(const QString& id) { //todo; } -Shared::Message Models::MessageFeed::getMessage(const QString& id) -{ +Shared::Message Models::MessageFeed::getMessage(const QString& id) { StorageById::iterator itr = indexById.find(id); - if (itr == indexById.end()) { + if (itr == indexById.end()) throw NotFound(id.toStdString(), rosterItem->getJid().toStdString(), rosterItem->getAccountName().toStdString()); - } return **itr; } -QVariant Models::MessageFeed::data(const QModelIndex& index, int role) const -{ +QVariant Models::MessageFeed::data(const QModelIndex& index, int role) const { int i = index.row(); QVariant answer; @@ -266,11 +263,10 @@ QVariant Models::MessageFeed::data(const QModelIndex& index, int role) const if (sentByMe(*msg)) { answer = rosterItem->getAccountName(); } else { - if (rosterItem->isRoom()) { + if (rosterItem->isRoom()) answer = msg->getFromResource(); - } else { + else answer = rosterItem->getDisplayedName(); - } } break; case Date: @@ -290,19 +286,17 @@ QVariant Models::MessageFeed::data(const QModelIndex& index, int role) const if (sentByMe(*msg)) { path = rosterItem->getAccountAvatarPath(); } else if (!rosterItem->isRoom()) { - if (rosterItem->getAvatarState() != Shared::Avatar::empty) { + if (rosterItem->getAvatarState() != Shared::Avatar::empty) path = rosterItem->getAvatarPath(); - } } else { const Room* room = static_cast(rosterItem); path = room->getParticipantIconPath(msg->getFromResource()); } - if (path.size() == 0) { + if (path.size() == 0) answer = Shared::iconPath("user", true); - } else { + else answer = path; - } } break; case Attach: @@ -342,15 +336,14 @@ QVariant Models::MessageFeed::data(const QModelIndex& index, int role) const item.avatar = room->getParticipantIconPath(msg->getFromResource()); } else { item.sender = rosterItem->getDisplayedName(); - if (rosterItem->getAvatarState() != Shared::Avatar::empty) { + if (rosterItem->getAvatarState() != Shared::Avatar::empty) item.avatar = rosterItem->getAvatarPath(); - } } } - if (item.avatar.size() == 0) { + if (item.avatar.size() == 0) item.avatar = Shared::iconPath("user", true); - } + item.attach = fillAttach(*msg); answer.setValue(item); } @@ -363,13 +356,12 @@ QVariant Models::MessageFeed::data(const QModelIndex& index, int role) const return answer; } -int Models::MessageFeed::rowCount(const QModelIndex& parent) const -{ +int Models::MessageFeed::rowCount(const QModelIndex& parent) const { + SHARED_UNUSED(parent); return storage.size(); } -bool Models::MessageFeed::markMessageAsRead(const QString& id) const -{ +bool Models::MessageFeed::markMessageAsRead(const QString& id) const { std::set::const_iterator umi = unreadMessages->find(id); if (umi != unreadMessages->end()) { unreadMessages->erase(umi); @@ -379,32 +371,29 @@ bool Models::MessageFeed::markMessageAsRead(const QString& id) const return false; } -unsigned int Models::MessageFeed::unreadMessagesCount() const -{ +unsigned int Models::MessageFeed::unreadMessagesCount() const { return unreadMessages->size(); } -bool Models::MessageFeed::canFetchMore(const QModelIndex& parent) const -{ +bool Models::MessageFeed::canFetchMore(const QModelIndex& parent) const { + SHARED_UNUSED(parent); return syncState == incomplete; } -void Models::MessageFeed::fetchMore(const QModelIndex& parent) -{ +void Models::MessageFeed::fetchMore(const QModelIndex& parent) { + SHARED_UNUSED(parent); if (syncState == incomplete) { syncState = syncing; emit syncStateChange(syncState); - if (storage.size() == 0) { + if (storage.size() == 0) emit requestArchive(""); - } else { + else emit requestArchive((*indexByTime.rbegin())->getId()); - } } } -void Models::MessageFeed::responseArchive(const std::list list, bool last) -{ +void Models::MessageFeed::responseArchive(const std::list list, bool last) { Storage::size_type size = storage.size(); beginInsertRows(QModelIndex(), size, size + list.size() - 1); @@ -415,21 +404,19 @@ void Models::MessageFeed::responseArchive(const std::list list, endInsertRows(); if (syncState == syncing) { - if (last) { + if (last) syncState = complete; - } else { + else syncState = incomplete; - } + emit syncStateChange(syncState); } } -QModelIndex Models::MessageFeed::index(int row, int column, const QModelIndex& parent) const -{ - if (!hasIndex(row, column, parent)) { +QModelIndex Models::MessageFeed::index(int row, int column, const QModelIndex& parent) const{ + if (!hasIndex(row, column, parent)) return QModelIndex(); - } - + StorageByTime::iterator itr = indexByTime.nth(row); if (itr != indexByTime.end()) { Shared::Message* msg = *itr; @@ -442,8 +429,7 @@ QModelIndex Models::MessageFeed::index(int row, int column, const QModelIndex& p QHash Models::MessageFeed::roleNames() const {return roles;} -bool Models::MessageFeed::sentByMe(const Shared::Message& msg) const -{ +bool Models::MessageFeed::sentByMe(const Shared::Message& msg) const { if (rosterItem->isRoom()) { const Room* room = static_cast(rosterItem); return room->getNick().toLower() == msg.getFromResource().toLower(); @@ -452,8 +438,7 @@ bool Models::MessageFeed::sentByMe(const Shared::Message& msg) const } } -Models::Attachment Models::MessageFeed::fillAttach(const Shared::Message& msg) const -{ +Models::Attachment Models::MessageFeed::fillAttach(const Shared::Message& msg) const { ::Models::Attachment att; QString id = msg.getId(); @@ -501,16 +486,14 @@ Models::Attachment Models::MessageFeed::fillAttach(const Shared::Message& msg) c return att; } -Models::Edition Models::MessageFeed::fillCorrection(const Shared::Message& msg) const -{ +Models::Edition Models::MessageFeed::fillCorrection(const Shared::Message& msg) const { ::Models::Edition ed({msg.getEdited(), msg.getOriginalBody(), msg.getLastModified()}); return ed; } -void Models::MessageFeed::downloadAttachment(const QString& messageId) -{ +void Models::MessageFeed::downloadAttachment(const QString& messageId) { bool notify = false; Err::const_iterator eitr = failedDownloads.find(messageId); if (eitr != failedDownloads.end()) { @@ -532,13 +515,11 @@ void Models::MessageFeed::downloadAttachment(const QString& messageId) qDebug() << "An attempt to download an attachment for the message that doesn't exist. ID:" << messageId; } - if (notify) { + if (notify) emit dataChanged(ind, ind, {MessageRoles::Attach}); - } } -bool Models::MessageFeed::registerUpload(const QString& messageId) -{ +bool Models::MessageFeed::registerUpload(const QString& messageId) { bool success = uploads.insert(std::make_pair(messageId, 0)).second; QVector roles({}); @@ -556,8 +537,7 @@ bool Models::MessageFeed::registerUpload(const QString& messageId) return success; } -void Models::MessageFeed::fileProgress(const QString& messageId, qreal value, bool up) -{ +void Models::MessageFeed::fileProgress(const QString& messageId, qreal value, bool up) { Progress* pr = 0; Err* err = 0; if (up) { @@ -583,13 +563,11 @@ void Models::MessageFeed::fileProgress(const QString& messageId, qreal value, bo } } -void Models::MessageFeed::fileComplete(const QString& messageId, bool up) -{ +void Models::MessageFeed::fileComplete(const QString& messageId, bool up) { fileProgress(messageId, 1, up); } -void Models::MessageFeed::fileError(const QString& messageId, const QString& error, bool up) -{ +void Models::MessageFeed::fileError(const QString& messageId, const QString& error, bool up) { Err* failed; Progress* loads; if (up) { @@ -601,33 +579,28 @@ void Models::MessageFeed::fileError(const QString& messageId, const QString& err } Progress::iterator pitr = loads->find(messageId); - if (pitr != loads->end()) { + if (pitr != loads->end()) loads->erase(pitr); - } std::pair pair = failed->insert(std::make_pair(messageId, error)); - if (!pair.second) { + if (!pair.second) pair.first->second = error; - } + QModelIndex ind = modelIndexById(messageId); - if (ind.isValid()) { + if (ind.isValid()) emit dataChanged(ind, ind, {MessageRoles::Attach}); - } } -void Models::MessageFeed::incrementObservers() -{ +void Models::MessageFeed::incrementObservers() { ++observersAmount; } -void Models::MessageFeed::decrementObservers() -{ +void Models::MessageFeed::decrementObservers() { --observersAmount; } -QModelIndex Models::MessageFeed::modelIndexById(const QString& id) const -{ +QModelIndex Models::MessageFeed::modelIndexById(const QString& id) const { StorageById::const_iterator itr = indexById.find(id); if (itr != indexById.end()) { Shared::Message* msg = *itr; @@ -637,8 +610,7 @@ QModelIndex Models::MessageFeed::modelIndexById(const QString& id) const return QModelIndex(); } -QModelIndex Models::MessageFeed::modelIndexByTime(const QString& id, const QDateTime& time) const -{ +QModelIndex Models::MessageFeed::modelIndexByTime(const QString& id, const QDateTime& time) const { if (indexByTime.size() > 0) { StorageByTime::const_iterator tItr = indexByTime.lower_bound(time); StorageByTime::const_iterator tEnd = indexByTime.upper_bound(time); @@ -660,8 +632,7 @@ QModelIndex Models::MessageFeed::modelIndexByTime(const QString& id, const QDate return QModelIndex(); } -void Models::MessageFeed::reportLocalPathInvalid(const QString& messageId) -{ +void Models::MessageFeed::reportLocalPathInvalid(const QString& messageId) { StorageById::iterator itr = indexById.find(messageId); if (itr == indexById.end()) { qDebug() << "received a command to change a message, but the message couldn't be found, skipping"; @@ -679,13 +650,11 @@ void Models::MessageFeed::reportLocalPathInvalid(const QString& messageId) emit dataChanged(index, index, {MessageRoles::Attach}); } -Models::MessageFeed::SyncState Models::MessageFeed::getSyncState() const -{ +Models::MessageFeed::SyncState Models::MessageFeed::getSyncState() const { return syncState; } -void Models::MessageFeed::requestLatestMessages() -{ +void Models::MessageFeed::requestLatestMessages() { if (syncState != syncing) { syncState = syncing; emit syncStateChange(syncState); diff --git a/ui/widgets/room.cpp b/ui/widgets/room.cpp index 91d7255..3409a86 100644 --- a/ui/widgets/room.cpp +++ b/ui/widgets/room.cpp @@ -31,12 +31,10 @@ Room::Room(Models::Account* acc, Models::Room* p_room, QWidget* parent): connect(room, &Models::Room::participantLeft, this, &Room::onParticipantLeft); } -Room::~Room() -{ +Room::~Room() { } -Shared::Message Room::createMessage() const -{ +Shared::Message Room::createMessage() const { Shared::Message msg = Conversation::createMessage(); msg.setType(Shared::Message::groupChat); msg.setFromJid(room->getJid()); @@ -45,13 +43,12 @@ Shared::Message Room::createMessage() const return msg; } -bool Room::autoJoined() const -{ +bool Room::autoJoined() const { return room->getAutoJoin(); } -void Room::onRoomChanged(Models::Item* item, int row, int col) -{ +void Room::onRoomChanged(Models::Item* item, int row, int col) { + SHARED_UNUSED(row); if (item == room) { switch (col) { case 0: @@ -67,11 +64,10 @@ void Room::onRoomChanged(Models::Item* item, int row, int col) } } -void Room::onParticipantJoined(const Models::Participant& participant) -{ - +void Room::onParticipantJoined(const Models::Participant& participant) { + SHARED_UNUSED(participant); } -void Room::onParticipantLeft(const QString& name) -{ +void Room::onParticipantLeft(const QString& name) { + SHARED_UNUSED(name); }