cleanup some warnings suppression

This commit is contained in:
Blue 2023-08-15 12:28:25 -03:00
parent 5fbb03fc46
commit 23ec80ccba
Signed by untrusted user: blue
GPG Key ID: 9B203B252A63EE38
26 changed files with 630 additions and 924 deletions

View File

@ -2,6 +2,7 @@ cmake_minimum_required(VERSION 3.5)
project(squawk VERSION 0.2.3 LANGUAGES CXX) project(squawk VERSION 0.2.3 LANGUAGES CXX)
cmake_policy(SET CMP0076 NEW) cmake_policy(SET CMP0076 NEW)
cmake_policy(SET CMP0077 NEW)
cmake_policy(SET CMP0079 NEW) cmake_policy(SET CMP0079 NEW)
set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD 17)

View File

@ -21,6 +21,8 @@
#include <QDateTime> #include <QDateTime>
#include "shared/defines.h"
Core::Account::Account( Core::Account::Account(
const QString& p_login, const QString& p_login,
const QString& p_server, const QString& p_server,
@ -159,7 +161,8 @@ Core::Account::Account(
logger->setLoggingType(QXmppLogger::SignalLogging); logger->setLoggingType(QXmppLogger::SignalLogging);
client.setLogger(logger); 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; 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) { void Core::Account::onMamLog(QXmppLogger::MessageType type, const QString& msg) {
SHARED_UNUSED(type);
qDebug() << "MAM MESSAGE LOG::"; qDebug() << "MAM MESSAGE LOG::";
qDebug() << msg; qDebug() << msg;
} }

View File

@ -24,11 +24,9 @@ Core::MessageHandler::MessageHandler(Core::Account* account):
acc(account), acc(account),
pendingStateMessages(), pendingStateMessages(),
uploadingSlotsQueue() uploadingSlotsQueue()
{ {}
}
void Core::MessageHandler::onMessageReceived(const QXmppMessage& msg) void Core::MessageHandler::onMessageReceived(const QXmppMessage& msg) {
{
#if (QXMPP_VERSION) >= QT_VERSION_CHECK(1, 5, 0) #if (QXMPP_VERSION) >= QT_VERSION_CHECK(1, 5, 0)
#ifdef WITH_OMEMO #ifdef WITH_OMEMO
switch (msg.encryptionMethod()) { switch (msg.encryptionMethod()) {
@ -83,9 +81,9 @@ void Core::MessageHandler::onMessageReceived(const QXmppMessage& msg)
{"state", static_cast<uint>(Shared::Message::State::error)}, {"state", static_cast<uint>(Shared::Message::State::error)},
{"errorText", msg.error().text()} {"errorText", msg.error().text()}
}; };
if (cnt != nullptr) { if (cnt != nullptr)
cnt->changeMessage(id, cData); cnt->changeMessage(id, cData);
}
emit acc->changeMessage(jid, id, cData); emit acc->changeMessage(jid, id, cData);
handled = true; handled = true;
} else { } 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"; qDebug() << "received a message with type \"Headline\", not sure what to do with it now, skipping";
break; break;
} }
if (!handled) { if (!handled)
logMessage(msg); 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) { if (msg.body().size() != 0 || msg.outOfBandUrl().size() > 0) {
Shared::Message sMsg(Shared::Message::chat); Shared::Message sMsg(Shared::Message::chat);
initializeMessage(sMsg, msg, outgoing, forwarded, guessing); initializeMessage(sMsg, msg, outgoing, forwarded, guessing);
@ -138,8 +134,7 @@ bool Core::MessageHandler::handleChatMessage(const QXmppMessage& msg, bool outgo
return false; 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()); const QString& body(msg.body());
if (body.size() != 0) { 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()); const QDateTime& time(source.stamp());
QString id; QString id;
#if (QXMPP_VERSION) >= QT_VERSION_CHECK(1, 3, 0) #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); 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() << reason;
qDebug() << "- from: " << msg.from(); qDebug() << "- from: " << msg.from();
qDebug() << "- to: " << msg.to(); 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) #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); handleChatMessage(msg, false, true);
} }
void Core::MessageHandler::onCarbonMessageSent(const QXmppMessage& msg) void Core::MessageHandler::onCarbonMessageSent(const QXmppMessage& msg) {
{
handleChatMessage(msg, true, true); handleChatMessage(msg, true, true);
} }
#endif #endif
std::tuple<bool, QString, QString> Core::MessageHandler::getOriginalPendingMessageId(const QString& id) std::tuple<bool, QString, QString> Core::MessageHandler::getOriginalPendingMessageId(const QString& id) {
{
std::tuple<bool, QString, QString> result({false, "", ""}); std::tuple<bool, QString, QString> result({false, "", ""});
std::map<QString, QString>::const_iterator itr = pendingStateMessages.find(id); std::map<QString, QString>::const_iterator itr = pendingStateMessages.find(id);
if (itr != pendingStateMessages.end()) { if (itr != pendingStateMessages.end()) {
@ -268,11 +258,11 @@ std::tuple<bool, QString, QString> Core::MessageHandler::getOriginalPendingMessa
std::map<QString, QString>::const_iterator itrC = pendingCorrectionMessages.find(id); std::map<QString, QString>::const_iterator itrC = pendingCorrectionMessages.find(id);
if (itrC != pendingCorrectionMessages.end()) { if (itrC != pendingCorrectionMessages.end()) {
if (itrC->second.size() > 0) { if (itrC->second.size() > 0)
std::get<1>(result) = itrC->second; std::get<1>(result) = itrC->second;
} else { else
std::get<1>(result) = itr->first; std::get<1>(result) = itr->first;
}
pendingCorrectionMessages.erase(itrC); pendingCorrectionMessages.erase(itrC);
} else { } else {
std::get<1>(result) = itr->first; std::get<1>(result) = itr->first;
@ -284,8 +274,8 @@ std::tuple<bool, QString, QString> Core::MessageHandler::getOriginalPendingMessa
return result; 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<bool, QString, QString> ids = getOriginalPendingMessageId(id); std::tuple<bool, QString, QString> ids = getOriginalPendingMessageId(id);
if (std::get<0>(ids)) { if (std::get<0>(ids)) {
QMap<QString, QVariant> cData = {{"state", static_cast<uint>(Shared::Message::State::delivered)}}; QMap<QString, QVariant> cData = {{"state", static_cast<uint>(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) { if (data.getOutOfBandUrl().size() == 0 && data.getAttachPath().size() > 0) {
pendingCorrectionMessages.insert(std::make_pair(data.getId(), originalId)); pendingCorrectionMessages.insert(std::make_pair(data.getId(), originalId));
prepareUpload(data, newMessage); 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 jid = data.getPenPalJid();
QString id = data.getId(); QString id = data.getId();
qDebug() << "Sending message with id:" << id; qDebug() << "Sending message with id:" << id;
if (originalId.size() > 0) { if (originalId.size() > 0)
qDebug() << "To replace one with id:" << originalId; qDebug() << "To replace one with id:" << originalId;
}
RosterItem* ri = acc->rh->getRosterItem(jid); RosterItem* ri = acc->rh->getRosterItem(jid);
bool sent = false; bool sent = false;
if (newMessage && originalId.size() > 0) { if (newMessage && originalId.size() > 0)
newMessage = false; newMessage = false;
}
QDateTime sendTime = QDateTime::currentDateTimeUtc(); QDateTime sendTime = QDateTime::currentDateTimeUtc();
if (acc->state == Shared::ConnectionState::connected) { if (acc->state == Shared::ConnectionState::connected) {
QXmppMessage msg(createPacket(data, sendTime, originalId)); QXmppMessage msg(createPacket(data, sendTime, originalId));
@ -341,22 +329,21 @@ void Core::MessageHandler::performSending(Shared::Message data, const QString& o
QMap<QString, QVariant> changes(getChanges(data, sendTime, newMessage, originalId)); QMap<QString, QVariant> changes(getChanges(data, sendTime, newMessage, originalId));
QString realId; QString realId;
if (originalId.size() > 0) { if (originalId.size() > 0)
realId = originalId; realId = originalId;
} else { else
realId = id; realId = id;
}
if (ri != nullptr) { if (ri != nullptr) {
if (newMessage) { if (newMessage)
ri->appendMessageToArchive(data); ri->appendMessageToArchive(data);
} else { else
ri->changeMessage(realId, changes); ri->changeMessage(realId, changes);
}
if (sent) { if (sent) {
pendingStateMessages.insert(std::make_pair(id, jid)); pendingStateMessages.insert(std::make_pair(id, jid));
if (originalId.size() > 0) { if (originalId.size() > 0)
pendingCorrectionMessages.insert(std::make_pair(id, originalId)); pendingCorrectionMessages.insert(std::make_pair(id, originalId));
}
} else { } else {
pendingStateMessages.erase(id); pendingStateMessages.erase(id);
pendingCorrectionMessages.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); emit acc->changeMessage(jid, realId, changes);
} }
QMap<QString, QVariant> Core::MessageHandler::getChanges(Shared::Message& data, const QDateTime& time, bool newMessage, const QString& originalId) const QMap<QString, QVariant> Core::MessageHandler::getChanges(Shared::Message& data, const QDateTime& time, bool newMessage, const QString& originalId) const {
{
QMap<QString, QVariant> changes; QMap<QString, QVariant> changes;
QString oob = data.getOutOfBandUrl(); QString oob = data.getOutOfBandUrl();
Shared::Message::State mstate = data.getState(); Shared::Message::State mstate = data.getState();
changes.insert("state", static_cast<uint>(mstate)); changes.insert("state", static_cast<uint>(mstate));
if (mstate == Shared::Message::State::error) { if (mstate == Shared::Message::State::error)
changes.insert("errorText", data.getErrorText()); changes.insert("errorText", data.getErrorText());
}
if (oob.size() > 0) { if (oob.size() > 0)
changes.insert("outOfBandUrl", oob); changes.insert("outOfBandUrl", oob);
}
if (newMessage) { if (newMessage)
data.setTime(time); data.setTime(time);
}
if (originalId.size() > 0) { if (originalId.size() > 0)
changes.insert("body", data.getBody()); changes.insert("body", data.getBody());
}
changes.insert("stamp", time); changes.insert("stamp", time);
//sometimes (when the image is pasted with ctrl+v) //sometimes (when the image is pasted with ctrl+v)
@ -394,22 +380,20 @@ QMap<QString, QVariant> Core::MessageHandler::getChanges(Shared::Message& data,
if (attachPath.size() > 0) { if (attachPath.size() > 0) {
QString squawkified = Shared::squawkifyPath(attachPath); QString squawkified = Shared::squawkifyPath(attachPath);
changes.insert("attachPath", squawkified); changes.insert("attachPath", squawkified);
if (attachPath != squawkified) { if (attachPath != squawkified)
data.setAttachPath(squawkified); data.setAttachPath(squawkified);
} }
}
return changes; 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()); QXmppMessage msg(acc->getFullJid(), data.getTo(), data.getBody(), data.getThread());
QString id(data.getId()); QString id(data.getId());
if (originalId.size() > 0) { if (originalId.size() > 0)
msg.setReplaceId(originalId); msg.setReplaceId(originalId);
}
#if (QXMPP_VERSION) >= QT_VERSION_CHECK(1, 3, 0) #if (QXMPP_VERSION) >= QT_VERSION_CHECK(1, 3, 0)
msg.setOriginId(id); msg.setOriginId(id);
@ -423,8 +407,7 @@ QXmppMessage Core::MessageHandler::createPacket(const Shared::Message& data, con
return msg; 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) { if (acc->state == Shared::ConnectionState::connected) {
QString jid = data.getPenPalJid(); QString jid = data.getPenPalJid();
QString id = data.getId(); QString id = data.getId();
@ -455,9 +438,8 @@ void Core::MessageHandler::prepareUpload(const Shared::Message& data, bool newMe
if (file.exists() && file.isReadable()) { if (file.exists() && file.isReadable()) {
pendingStateMessages.insert(std::make_pair(id, jid)); pendingStateMessages.insert(std::make_pair(id, jid));
uploadingSlotsQueue.emplace_back(path, id); uploadingSlotsQueue.emplace_back(path, id);
if (uploadingSlotsQueue.size() == 1) { if (uploadingSlotsQueue.size() == 1)
acc->um->requestUploadSlot(file); acc->um->requestUploadSlot(file);
}
} else { } else {
handleUploadError(jid, id, "Uploading file no longer exists or your system user has no permission to read it"); 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"; 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) { if (uploadingSlotsQueue.size() == 0) {
qDebug() << "HTTP Upload manager of account" << acc->name << "reports about success requesting upload slot, but none was requested"; qDebug() << "HTTP Upload manager of account" << acc->name << "reports about success requesting upload slot, but none was requested";
} else { } 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()); acc->network->uploadFile({acc->name, palJid, mId}, pair.first, slot.putUrl(), slot.getUrl(), slot.putHeaders());
uploadingSlotsQueue.pop_front(); uploadingSlotsQueue.pop_front();
if (uploadingSlotsQueue.size() > 0) { if (uploadingSlotsQueue.size() > 0)
acc->um->requestUploadSlot(uploadingSlotsQueue.front().first); 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()); QString err(request.error().text());
if (uploadingSlotsQueue.size() == 0) { if (uploadingSlotsQueue.size() == 0) {
qDebug() << "HTTP Upload manager of account" << acc->name << "reports about an error requesting upload slot, but none was requested"; 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); handleUploadError(pendingStateMessages.at(pair.second), pair.second, err);
uploadingSlotsQueue.pop_front(); uploadingSlotsQueue.pop_front();
if (uploadingSlotsQueue.size() > 0) { if (uploadingSlotsQueue.size() > 0)
acc->um->requestUploadSlot(uploadingSlotsQueue.front().first); acc->um->requestUploadSlot(uploadingSlotsQueue.front().first);
} }
}
} }
void Core::MessageHandler::onDownloadFileComplete(const std::list<Shared::MessageInfo>& msgs, const QString& path) void Core::MessageHandler::onDownloadFileComplete(const std::list<Shared::MessageInfo>& msgs, const QString& path) {
{
QMap<QString, QVariant> cData = { QMap<QString, QVariant> cData = {
{"attachPath", path} {"attachPath", path}
}; };
@ -518,27 +495,24 @@ void Core::MessageHandler::onDownloadFileComplete(const std::list<Shared::Messag
if (info.account == acc->getName()) { if (info.account == acc->getName()) {
RosterItem* cnt = acc->rh->getRosterItem(info.jid); RosterItem* cnt = acc->rh->getRosterItem(info.jid);
if (cnt != nullptr) { 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); emit acc->changeMessage(info.jid, info.messageId, cData);
} }
} }
} }
}
} }
void Core::MessageHandler::onLoadFileError(const std::list<Shared::MessageInfo>& msgs, const QString& text, bool up) void Core::MessageHandler::onLoadFileError(const std::list<Shared::MessageInfo>& msgs, const QString& text, bool up) {
{
if (up) { if (up) {
for (const Shared::MessageInfo& info : msgs) { for (const Shared::MessageInfo& info : msgs) {
if (info.account == acc->getName()) { if (info.account == acc->getName())
handleUploadError(info.jid, info.messageId, text); 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); emit acc->uploadFileError(jid, messageId, "Error requesting slot to upload file: " + errorText);
pendingStateMessages.erase(messageId); pendingStateMessages.erase(messageId);
pendingCorrectionMessages.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<Shared::MessageInfo>& msgs, const QString& url, const QString& path) void Core::MessageHandler::onUploadFileComplete(const std::list<Shared::MessageInfo>& msgs, const QString& url, const QString& path) {
{
for (const Shared::MessageInfo& info : msgs) { for (const Shared::MessageInfo& info : msgs) {
if (info.account == acc->getName()) { if (info.account == acc->getName()) {
RosterItem* ri = acc->rh->getRosterItem(info.jid); RosterItem* ri = acc->rh->getRosterItem(info.jid);
@ -564,12 +537,11 @@ void Core::MessageHandler::onUploadFileComplete(const std::list<Shared::MessageI
} }
} }
void Core::MessageHandler::sendMessageWithLocalUploadedFile(Shared::Message msg, const QString& url, bool newMessage) void Core::MessageHandler::sendMessageWithLocalUploadedFile(Shared::Message msg, const QString& url, bool newMessage) {
{
msg.setOutOfBandUrl(url); msg.setOutOfBandUrl(url);
if (msg.getBody().size() == 0) { //not sure why, but most messages do that if (msg.getBody().size() == 0) //not sure why, but most messages do that
msg.setBody(url); //they duplicate oob in body, some of them wouldn't even show an attachment if you don't do that msg.setBody(url); //they duplicate oob in body, some of them wouldn't even show an attachment if you don't do that
}
performSending(msg, pendingCorrectionMessages.at(msg.getId()), newMessage); performSending(msg, pendingCorrectionMessages.at(msg.getId()), newMessage);
//TODO removal/progress update //TODO removal/progress update
} }
@ -581,8 +553,7 @@ static const std::set<QString> allowedToChangeKeys({
"errorText" "errorText"
}); });
void Core::MessageHandler::requestChangeMessage(const QString& jid, const QString& messageId, const QMap<QString, QVariant>& data) void Core::MessageHandler::requestChangeMessage(const QString& jid, const QString& messageId, const QMap<QString, QVariant>& data) {
{
RosterItem* cnt = acc->rh->getRosterItem(jid); RosterItem* cnt = acc->rh->getRosterItem(jid);
if (cnt != nullptr) { if (cnt != nullptr) {
bool allSupported = true; 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); RosterItem* cnt = acc->rh->getRosterItem(jid);
if (cnt != nullptr) { if (cnt != nullptr) {
try { try {

View File

@ -213,6 +213,7 @@ void Core::OmemoHandler::onOwnBundlesReceived() {
} }
void Core::OmemoHandler::onOmemoDeviceAdded(const QString& jid, uint32_t id) { void Core::OmemoHandler::onOmemoDeviceAdded(const QString& jid, uint32_t id) {
SHARED_UNUSED(id);
qDebug() << "OMEMO device added for" << jid; qDebug() << "OMEMO device added for" << jid;
} }

View File

@ -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) { void Core::RosterHandler::addRoomRequest(const QString& jid, const QString& nick, const QString& password, bool autoJoin) {
SHARED_UNUSED(password);
QString lcJid = jid.toLower(); QString lcJid = jid.toLower();
std::map<QString, Conference*>::const_iterator cItr = conferences.find(lcJid); std::map<QString, Conference*>::const_iterator cItr = conferences.find(lcJid);
if (cItr == conferences.end()) { if (cItr == conferences.end()) {

View File

@ -21,6 +21,8 @@
#include <sys/socket.h> #include <sys/socket.h>
#include <unistd.h> #include <unistd.h>
#include "shared/defines.h"
int SignalCatcher::sigintFd[2] = {0,0}; int SignalCatcher::sigintFd[2] = {0,0};
SignalCatcher::SignalCatcher(QCoreApplication *p_app, QObject *parent): SignalCatcher::SignalCatcher(QCoreApplication *p_app, QObject *parent):
@ -28,14 +30,10 @@ SignalCatcher::SignalCatcher(QCoreApplication *p_app, QObject *parent):
app(p_app) app(p_app)
{ {
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd)) if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd))
{
qFatal("Couldn't create INT socketpair"); qFatal("Couldn't create INT socketpair");
}
if (setup_unix_signal_handlers() != 0) if (setup_unix_signal_handlers() != 0)
{
qFatal("Couldn't install unix handlers"); qFatal("Couldn't install unix handlers");
}
snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this); snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);
connect(snInt, &QSocketNotifier::activated, this, &SignalCatcher::handleSigInt); connect(snInt, &QSocketNotifier::activated, this, &SignalCatcher::handleSigInt);
@ -44,25 +42,25 @@ SignalCatcher::SignalCatcher(QCoreApplication *p_app, QObject *parent):
SignalCatcher::~SignalCatcher() SignalCatcher::~SignalCatcher()
{} {}
void SignalCatcher::handleSigInt() void SignalCatcher::handleSigInt() {
{
snInt->setEnabled(false); snInt->setEnabled(false);
char tmp; char tmp;
ssize_t s = ::read(sigintFd[1], &tmp, sizeof(tmp)); ssize_t s = ::read(sigintFd[1], &tmp, sizeof(tmp));
SHARED_UNUSED(s);
emit interrupt(); emit interrupt();
snInt->setEnabled(true); snInt->setEnabled(true);
} }
void SignalCatcher::intSignalHandler(int unused) void SignalCatcher::intSignalHandler(int unused) {
{
char a = 1; char a = 1;
ssize_t s = ::write(sigintFd[0], &a, sizeof(a)); 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; struct sigaction s_int;
s_int.sa_handler = SignalCatcher::intSignalHandler; s_int.sa_handler = SignalCatcher::intSignalHandler;

View File

@ -120,8 +120,7 @@ Application::Application(Core::Squawk* p_core):
Application::~Application() {} Application::~Application() {}
void Application::quit() void Application::quit() {
{
if (!nowQuitting) { if (!nowQuitting) {
nowQuitting = true; nowQuitting = true;
emit quitting(); emit quitting();
@ -135,32 +134,27 @@ void Application::quit()
conversations.clear(); conversations.clear();
dialogueQueue.quit(); dialogueQueue.quit();
if (squawk != nullptr) { if (squawk != nullptr)
squawk->close(); squawk->close();
}
if (trayIcon != nullptr) { if (trayIcon != nullptr) {
trayIcon->deleteLater(); trayIcon->deleteLater();
trayIcon = nullptr; trayIcon = nullptr;
} }
if (!destroyingSquawk) { if (!destroyingSquawk)
checkForTheLastWindow(); checkForTheLastWindow();
} }
}
} }
void Application::checkForTheLastWindow() void Application::checkForTheLastWindow() {
{ if (QApplication::topLevelWidgets().size() > 0)
if (QApplication::topLevelWidgets().size() > 0) {
emit readyToQuit(); emit readyToQuit();
} else { else
connect(qApp, &QApplication::lastWindowClosed, this, &Application::readyToQuit); connect(qApp, &QApplication::lastWindowClosed, this, &Application::readyToQuit);
}
} }
void Application::createMainWindow() void Application::createMainWindow() {
{
if (squawk == nullptr) { if (squawk == nullptr) {
squawk = new Squawk(roster); squawk = new Squawk(roster);
@ -202,18 +196,16 @@ void Application::createMainWindow()
for (const std::list<QString>& entry : expandedPaths) { for (const std::list<QString>& entry : expandedPaths) {
QModelIndex ind = roster.getIndexByPath(entry); QModelIndex ind = roster.getIndexByPath(entry);
if (ind.isValid()) { if (ind.isValid())
squawk->expand(ind); squawk->expand(ind);
} }
}
connect(squawk, &Squawk::itemExpanded, this, &Application::onItemExpanded); connect(squawk, &Squawk::itemExpanded, this, &Application::onItemExpanded);
connect(squawk, &Squawk::itemCollapsed, this, &Application::onItemCollapsed); connect(squawk, &Squawk::itemCollapsed, this, &Application::onItemCollapsed);
} }
} }
void Application::onSquawkClosing() void Application::onSquawkClosing() {
{
dialogueQueue.setParentWidnow(nullptr); dialogueQueue.setParentWidnow(nullptr);
if (!nowQuitting) { if (!nowQuitting) {
@ -237,18 +229,15 @@ void Application::onSquawkClosing()
void Application::onSquawkDestroyed() { void Application::onSquawkDestroyed() {
destroyingSquawk = false; destroyingSquawk = false;
if (nowQuitting) { if (nowQuitting)
checkForTheLastWindow(); checkForTheLastWindow();
}
} }
void Application::onChangeTray(bool enabled, bool hide) void Application::onChangeTray(bool enabled, bool hide) {
{
if (enabled) { if (enabled) {
if (trayIcon == nullptr) { if (trayIcon == nullptr) {
if (!hide || squawk == nullptr) { if (!hide || squawk == nullptr)
createTrayIcon(); createTrayIcon();
}
} else { } else {
if (hide && squawk != nullptr) { if (hide && squawk != nullptr) {
trayIcon->deleteLater(); trayIcon->deleteLater();
@ -261,8 +250,7 @@ void Application::onChangeTray(bool enabled, bool hide)
} }
} }
void Application::createTrayIcon() void Application::createTrayIcon() {
{
trayIcon = new QSystemTrayIcon(); trayIcon = new QSystemTrayIcon();
QMenu* trayIconMenu = new QMenu(); QMenu* trayIconMenu = new QMenu();
@ -279,8 +267,7 @@ void Application::createTrayIcon()
trayIcon->show(); trayIcon->show();
} }
void Application::trayClicked(QSystemTrayIcon::ActivationReason reason) void Application::trayClicked(QSystemTrayIcon::ActivationReason reason) {
{
switch (reason) { switch (reason) {
case QSystemTrayIcon::Trigger: case QSystemTrayIcon::Trigger:
case QSystemTrayIcon::DoubleClick: case QSystemTrayIcon::DoubleClick:
@ -292,8 +279,7 @@ void Application::trayClicked(QSystemTrayIcon::ActivationReason reason)
} }
} }
void Application::toggleSquawk() void Application::toggleSquawk() {
{
QSettings settings; QSettings settings;
if (squawk == nullptr) { if (squawk == nullptr) {
createMainWindow(); createMainWindow();
@ -308,34 +294,27 @@ void Application::toggleSquawk()
} }
} }
void Application::onItemCollapsed(const QModelIndex& index) void Application::onItemCollapsed(const QModelIndex& index) {
{
std::list<QString> address = roster.getItemPath(index); std::list<QString> address = roster.getItemPath(index);
if (address.size() > 0) { if (address.size() > 0)
expandedPaths.erase(address); expandedPaths.erase(address);
}
} }
void Application::onItemExpanded(const QModelIndex& index) void Application::onItemExpanded(const QModelIndex& index) {
{
std::list<QString> address = roster.getItemPath(index); std::list<QString> address = roster.getItemPath(index);
if (address.size() > 0) { if (address.size() > 0)
expandedPaths.insert(address); expandedPaths.insert(address);
}
} }
void Application::onAddedElement(const std::list<QString>& path) void Application::onAddedElement(const std::list<QString>& path) {
{
if (squawk != nullptr && expandedPaths.count(path) > 0) { if (squawk != nullptr && expandedPaths.count(path) > 0) {
QModelIndex index = roster.getIndexByPath(path); QModelIndex index = roster.getIndexByPath(path);
if (index.isValid()) { if (index.isValid())
squawk->expand(index); 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 jid = msg.getPenPalJid();
QString name = QString(roster.getContactName(account, jid)); QString name = QString(roster.getContactName(account, jid));
QString path = QString(roster.getContactIconPath(account, jid, msg.getPenPalResource())); 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()); uint32_t notificationId = qHash(msg.getId());
args << notificationId; args << notificationId;
if (path.size() > 0) { if (path.size() > 0)
args << path; args << path;
} else { else
args << QString("mail-message"); //TODO should here better be unknown user icon? 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; args << msg.getFromResource() + tr(" from ") + name;
} else { else
args << name; args << name;
}
QString body(msg.getBody()); QString body(msg.getBody());
QString oob(msg.getOutOfBandUrl()); 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()))); 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); QApplication::alert(squawk);
}
} }
void Application::onNotificationClosed(quint32 id, quint32 reason) void Application::onNotificationClosed(quint32 id, quint32 reason) {
{
Notifications::const_iterator itr = storage.find(id); Notifications::const_iterator itr = storage.find(id);
if (itr != storage.end()) { if (itr != storage.end()) {
if (reason == 2) { //dissmissed by user (https://specifications.freedesktop.org/notification-spec/latest/ar01s09.html) 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"; qDebug() << "Notification" << id << action << "request";
Notifications::const_iterator itr = storage.find(id); Notifications::const_iterator itr = storage.find(id);
if (itr != storage.end()) { if (itr != storage.end()) {
if (action == "markAsRead") { if (action == "markAsRead")
roster.markMessageAsRead(itr->second.first, itr->second.second); roster.markMessageAsRead(itr->second.first, itr->second.second);
} else if (action == "openConversation") { else if (action == "openConversation")
focusConversation(itr->second.first, "", itr->second.second); 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"); QDBusMessage signal = QDBusMessage::createSignal("/", "com.canonical.Unity.LauncherEntry", "Update");
signal << qApp->desktopFileName() + QLatin1String(".desktop"); signal << qApp->desktopFileName() + QLatin1String(".desktop");
signal << QVariantMap ({ signal << QVariantMap ({
@ -421,54 +394,49 @@ void Application::unreadMessagesCountChanged(int count)
QDBusConnection::sessionBus().send(signal); 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 != nullptr) {
if (squawk->currentConversationId() != id) { if (squawk->currentConversationId() != id) {
QModelIndex index = roster.getContactIndex(id.account, id.name, resource); QModelIndex index = roster.getContactIndex(id.account, id.name, resource);
squawk->select(index); squawk->select(index);
} }
if (squawk->isMinimized()) { if (squawk->isMinimized())
squawk->showNormal(); squawk->showNormal();
} else { else
squawk->show(); squawk->show();
}
squawk->raise(); squawk->raise();
squawk->activateWindow(); squawk->activateWindow();
} else { } else {
openConversation(id, resource); openConversation(id, resource);
} }
SHARED_UNUSED(messageId);
//TODO focus messageId; //TODO focus messageId;
} }
void Application::setState(Shared::Availability p_availability) void Application::setState(Shared::Availability p_availability) {
{
if (availability != p_availability) { if (availability != p_availability) {
availability = p_availability; availability = p_availability;
emit changeState(availability); emit changeState(availability);
} }
} }
void Application::stateChanged(Shared::Availability state) void Application::stateChanged(Shared::Availability state) {
{
availability = state; availability = state;
if (squawk != nullptr) { if (squawk != nullptr)
squawk->stateChanged(state); squawk->stateChanged(state);
}
} }
void Application::readSettings() void Application::readSettings() {
{
QSettings settings; QSettings settings;
settings.beginGroup("ui"); settings.beginGroup("ui");
int avail; int avail;
if (settings.contains("availability")) { if (settings.contains("availability"))
avail = settings.value("availability").toInt(); avail = settings.value("availability").toInt();
} else { else
avail = static_cast<int>(Shared::Availability::online); avail = static_cast<int>(Shared::Availability::online);
}
settings.beginGroup("roster"); settings.beginGroup("roster");
QStringList entries = settings.allKeys(); QStringList entries = settings.allKeys();
@ -486,13 +454,11 @@ void Application::readSettings()
setState(Shared::Global::fromInt<Shared::Availability>(avail)); setState(Shared::Global::fromInt<Shared::Availability>(avail));
createMainWindow(); createMainWindow();
if (settings.value("tray", false).toBool() && !settings.value("hideTray", false).toBool()) { if (settings.value("tray", false).toBool() && !settings.value("hideTray", false).toBool())
createTrayIcon(); createTrayIcon();
}
} }
void Application::writeSettings() void Application::writeSettings() {
{
QSettings settings; QSettings settings;
settings.beginGroup("ui"); settings.beginGroup("ui");
settings.setValue("availability", static_cast<int>(availability)); settings.setValue("availability", static_cast<int>(availability));
@ -501,9 +467,9 @@ void Application::writeSettings()
settings.beginGroup("roster"); settings.beginGroup("roster");
for (const std::list<QString>& address : expandedPaths) { for (const std::list<QString>& address : expandedPaths) {
QString path = ""; QString path = "";
for (const QString& hop : address) { for (const QString& hop : address)
path += hop + "/"; path += hop + "/";
}
path += "expanded"; path += "expanded";
settings.setValue(path, true); settings.setValue(path, true);
} }
@ -513,54 +479,49 @@ void Application::writeSettings()
} }
void Application::requestPassword(const QString& account, bool authenticationError) { void Application::requestPassword(const QString& account, bool authenticationError) {
if (authenticationError) { if (authenticationError)
dialogueQueue.addAction(account, DialogQueue::askCredentials); dialogueQueue.addAction(account, DialogQueue::askCredentials);
} else { else
dialogueQueue.addAction(account, DialogQueue::askPassword); dialogueQueue.addAction(account, DialogQueue::askPassword);
}
} }
void Application::onConversationClosed()
{ void Application::onConversationClosed() {
Conversation* conv = static_cast<Conversation*>(sender()); Conversation* conv = static_cast<Conversation*>(sender());
Models::Roster::ElId id(conv->getAccount(), conv->getJid()); Models::Roster::ElId id(conv->getAccount(), conv->getJid());
Conversations::const_iterator itr = conversations.find(id); Conversations::const_iterator itr = conversations.find(id);
if (itr != conversations.end()) { if (itr != conversations.end())
conversations.erase(itr); conversations.erase(itr);
}
if (conv->isMuc) { if (conv->isMuc) {
Room* room = static_cast<Room*>(conv); Room* room = static_cast<Room*>(conv);
if (!room->autoJoined()) { if (!room->autoJoined())
emit setRoomJoined(id.account, id.name, false); 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); Models::Item::Type type = roster.getContactType(id);
switch (type) { switch (type) {
case Models::Item::contact: case Models::Item::contact:
if (subscribe) { if (subscribe)
emit subscribeContact(id.account, id.name, ""); emit subscribeContact(id.account, id.name, "");
} else { else
emit unsubscribeContact(id.account, id.name, ""); emit unsubscribeContact(id.account, id.name, "");
}
break; break;
case Models::Item::room: case Models::Item::room:
setRoomAutoJoin(id.account, id.name, subscribe); setRoomAutoJoin(id.account, id.name, subscribe);
if (!isConverstationOpened(id)) { if (!isConverstationOpened(id))
emit setRoomJoined(id.account, id.name, subscribe); emit setRoomJoined(id.account, id.name, subscribe);
}
break; break;
default: default:
break; break;
} }
} }
void Application::subscribeConversation(Conversation* conv) void Application::subscribeConversation(Conversation* conv) {
{
connect(conv, &Conversation::destroyed, this, &Application::onConversationClosed); connect(conv, &Conversation::destroyed, this, &Application::onConversationClosed);
connect(conv, &Conversation::sendMessage, this, &Application::onConversationMessage); connect(conv, &Conversation::sendMessage, this, &Application::onConversationMessage);
connect(conv, &Conversation::replaceMessage, this, &Application::onConversationReplaceMessage); connect(conv, &Conversation::replaceMessage, this, &Application::onConversationReplaceMessage);
@ -568,8 +529,7 @@ void Application::subscribeConversation(Conversation* conv)
connect(conv, &Conversation::notifyableMessage, this, &Application::notify); 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); Conversations::const_iterator itr = conversations.find(id);
Models::Account* acc = roster.getAccount(id.account); Models::Account* acc = roster.getAccount(id.account);
Conversation* conv = nullptr; Conversation* conv = nullptr;
@ -583,9 +543,8 @@ void Application::openConversation(const Models::Roster::ElId& id, const QString
created = true; created = true;
Models::Room* room = static_cast<Models::Room*>(el); Models::Room* room = static_cast<Models::Room*>(el);
conv = new Room(acc, room); conv = new Room(acc, room);
if (!room->getJoined()) { if (!room->getJoined())
emit setRoomJoined(id.account, id.name, true); emit setRoomJoined(id.account, id.name, true);
}
} else if (el->type == Models::Item::contact) { } else if (el->type == Models::Item::contact) {
created = true; created = true;
conv = new Chat(acc, static_cast<Models::Contact*>(el)); conv = new Chat(acc, static_cast<Models::Contact*>(el));
@ -604,14 +563,12 @@ void Application::openConversation(const Models::Roster::ElId& id, const QString
conv->raise(); conv->raise();
conv->activateWindow(); conv->activateWindow();
if (resource.size() > 0) { if (resource.size() > 0)
conv->setPalResource(resource); conv->setPalResource(resource);
} }
}
} }
void Application::onConversationMessage(const Shared::Message& msg) void Application::onConversationMessage(const Shared::Message& msg) {
{
Conversation* conv = static_cast<Conversation*>(sender()); Conversation* conv = static_cast<Conversation*>(sender());
QString acc = conv->getAccount(); QString acc = conv->getAccount();
@ -619,8 +576,7 @@ void Application::onConversationMessage(const Shared::Message& msg)
emit sendMessage(acc, 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<Conversation*>(sender()); Conversation* conv = static_cast<Conversation*>(sender());
QString acc = conv->getAccount(); QString acc = conv->getAccount();
@ -630,8 +586,7 @@ void Application::onConversationReplaceMessage(const QString& originalId, const
emit replaceMessage(acc, originalId, msg); emit replaceMessage(acc, originalId, msg);
} }
void Application::onConversationResend(const QString& id) void Application::onConversationResend(const QString& id) {
{
Conversation* conv = static_cast<Conversation*>(sender()); Conversation* conv = static_cast<Conversation*>(sender());
QString acc = conv->getAccount(); QString acc = conv->getAccount();
QString jid = conv->getJid(); 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(); Conversations::const_iterator itr = conversations.begin();
while (itr != conversations.end()) { while (itr != conversations.end()) {
if (itr->first.account == account) { 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(); squawk->closeCurrentConversation();
}
roster.removeAccount(account); roster.removeAccount(account);
} }
void Application::changeAccount(const QString& account, const QMap<QString, QVariant>& data) void Application::changeAccount(const QString& account, const QMap<QString, QVariant>& data) {
{
for (QMap<QString, QVariant>::const_iterator itr = data.begin(), end = data.end(); itr != end; ++itr) { for (QMap<QString, QVariant>::const_iterator itr = data.begin(), end = data.end(); itr != end; ++itr) {
QString attr = itr.key(); QString attr = itr.key();
roster.updateAccount(account, attr, *itr); 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); roster.addGroup(account, name);
if (squawk != nullptr) { if (squawk != nullptr) {
@ -692,10 +643,9 @@ void Application::addGroup(const QString& account, const QString& name)
if (settings.value("expanded", false).toBool()) { if (settings.value("expanded", false).toBool()) {
QModelIndex ind = roster.getAccountIndex(account); QModelIndex ind = roster.getAccountIndex(account);
squawk->expand(ind); squawk->expand(ind);
if (settings.value(name + "/expanded", false).toBool()) { if (settings.value(name + "/expanded", false).toBool())
squawk->expand(roster.getGroupIndex(account, name)); squawk->expand(roster.getGroupIndex(account, name));
} }
}
settings.endGroup(); settings.endGroup();
settings.endGroup(); settings.endGroup();
settings.endGroup(); settings.endGroup();

View File

@ -37,6 +37,7 @@ set(HEADER_FILES
info.h info.h
clientid.h clientid.h
trustsummary.h trustsummary.h
defines.h
) )
target_sources(squawk PRIVATE target_sources(squawk PRIVATE

24
shared/defines.h Normal file
View File

@ -0,0 +1,24 @@
/*
* Squawk messenger.
* Copyright (C) 2019 Yury Gubich <blue@macaw.me>
*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef SHARED_DEFINES_H
#define SHARED_DEFINES_H
#define SHARED_UNUSED(x) (void)(x)
#endif

View File

@ -121,6 +121,8 @@ QDataStream & Shared::Identity::operator >> (QDataStream& stream) const {
stream << type; stream << type;
stream << language; stream << language;
stream << name; stream << name;
return stream;
} }
QDataStream & Shared::Identity::operator << (QDataStream& stream) { QDataStream & Shared::Identity::operator << (QDataStream& stream) {
@ -128,6 +130,8 @@ QDataStream & Shared::Identity::operator << (QDataStream& stream) {
stream >> type; stream >> type;
stream >> language; stream >> language;
stream >> name; stream >> name;
return stream;
} }
QDataStream & operator >> (QDataStream& stream, Shared::Identity& identity) { QDataStream & operator >> (QDataStream& stream, Shared::Identity& identity) {

View File

@ -19,6 +19,7 @@
#ifndef SHARED_H #ifndef SHARED_H
#define SHARED_H #define SHARED_H
#include "defines.h"
#include "enums.h" #include "enums.h"
#include "global.h" #include "global.h"
#include "icons.h" #include "icons.h"

View File

@ -18,6 +18,7 @@
#include "accounts.h" #include "accounts.h"
#include "shared/icons.h" #include "shared/icons.h"
#include "shared/defines.h"
#include <QIcon> #include <QIcon>
#include <QDebug> #include <QDebug>
@ -26,32 +27,24 @@ std::deque<QString> Models::Accounts::columns = {"Name", "Server", "State", "Err
Models::Accounts::Accounts(QObject* parent): Models::Accounts::Accounts(QObject* parent):
QAbstractTableModel(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; QVariant answer;
switch (role) { switch (role) {
case Qt::DisplayRole: case Qt::DisplayRole:
answer = accs[index.row()]->data(index.column()); answer = accs[index.row()]->data(index.column());
break; break;
case Qt::DecorationRole: case Qt::DecorationRole:
if (index.column() == 2) { if (index.column() == 2)
answer = Shared::connectionStateIcon(accs[index.row()]->getState()); answer = Shared::connectionStateIcon(accs[index.row()]->getState());
}
break; break;
case Qt::ForegroundRole: case Qt::ForegroundRole:
if (!accs[index.row()]->getActive()) { if (!accs[index.row()]->getActive())
answer = qApp->palette().brush(QPalette::Disabled, QPalette::Text); answer = qApp->palette().brush(QPalette::Disabled, QPalette::Text);
} break;
default: default:
break; break;
} }
@ -59,53 +52,46 @@ QVariant Models::Accounts::data (const QModelIndex& index, int role) const
return answer; return answer;
} }
int Models::Accounts::columnCount ( const QModelIndex& parent ) const int Models::Accounts::columnCount (const QModelIndex& parent) const {
{ SHARED_UNUSED(parent);
return columns.size(); 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(); return accs.size();
} }
unsigned int Models::Accounts::size() const unsigned int Models::Accounts::size() const {
{
return rowCount(QModelIndex()); return rowCount(QModelIndex());
} }
unsigned int Models::Accounts::activeSize() const unsigned int Models::Accounts::activeSize() const {
{
unsigned int size = 0; unsigned int size = 0;
for (const Models::Account* acc : accs) { for (const Models::Account* acc : accs) {
if (acc->getActive()) { if (acc->getActive())
++size; ++size;
} }
}
return size; return size;
} }
QVariant Models::Accounts::headerData(int section, Qt::Orientation orientation, int role) const QVariant Models::Accounts::headerData(int section, Qt::Orientation orientation, int role) const {
{ if (role == Qt::DisplayRole && orientation == Qt::Horizontal)
if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
return tr(columns[section].toLatin1()); return tr(columns[section].toLatin1());
}
return QVariant(); return QVariant();
} }
void Models::Accounts::addAccount(Account* account) void Models::Accounts::addAccount(Account* account) {
{
beginInsertRows(QModelIndex(), accs.size(), accs.size()); beginInsertRows(QModelIndex(), accs.size(), accs.size());
int index = 0;
std::deque<Account*>::const_iterator before = accs.begin(); std::deque<Account*>::const_iterator before = accs.begin();
while (before != accs.end()) { while (before != accs.end()) {
Account* bfr = *before; Account* bfr = *before;
if (bfr->getDisplayedName() > account->getDisplayedName()) { if (bfr->getDisplayedName() > account->getDisplayedName())
break; break;
}
index++;
before++; before++;
} }
@ -117,25 +103,23 @@ void Models::Accounts::addAccount(Account* account)
emit changed(); emit changed();
} }
void Models::Accounts::onAccountChanged(Item* item, int row, int col) void Models::Accounts::onAccountChanged(Item* item, int row, int col) {
{ if (row < 0)
if (row < 0) {
return; return;
}
if (static_cast<std::deque<Models::Account*>::size_type>(row) < accs.size()) { if (static_cast<std::deque<Models::Account*>::size_type>(row) < accs.size()) {
Account* acc = getAccount(row); 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 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) { if (col == 0) {
int newRow = 0; int newRow = 0;
std::deque<Account*>::const_iterator before = accs.begin(); std::deque<Account*>::const_iterator before = accs.begin();
while (before != accs.end()) { while (before != accs.end()) {
Item* bfr = *before; Item* bfr = *before;
if (bfr->getDisplayedName() > item->getDisplayedName()) { if (bfr->getDisplayedName() > item->getDisplayedName())
break; break;
}
newRow++; newRow++;
before++; 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 dataChanged(createIndex(row, col), createIndex(row, col));
}
emit changed(); emit changed();
} }
} }
Models::Account * Models::Accounts::getAccount(int index) Models::Account * Models::Accounts::getAccount(int index) {
{
return accs[index]; return accs[index];
} }
void Models::Accounts::removeAccount(int index) void Models::Accounts::removeAccount(int index) {
{
Account* account = accs[index]; Account* account = accs[index];
beginRemoveRows(QModelIndex(), index, index); beginRemoveRows(QModelIndex(), index, index);
disconnect(account, &Account::childChanged, this, &Accounts::onAccountChanged); disconnect(account, &Account::childChanged, this, &Accounts::onAccountChanged);
@ -175,14 +157,13 @@ void Models::Accounts::removeAccount(int index)
emit sizeChanged(accs.size()); emit sizeChanged(accs.size());
} }
std::deque<QString> Models::Accounts::getActiveNames() const std::deque<QString> Models::Accounts::getActiveNames() const {
{
std::deque<QString> res; std::deque<QString> res;
for (const Models::Account* acc : accs) { for (const Models::Account* acc : accs) {
if (acc->getActive()) { if (acc->getActive())
res.push_back(acc->getName()); res.push_back(acc->getName());
}
} }
return res; return res;

View File

@ -19,6 +19,7 @@
#include "emails.h" #include "emails.h"
#include "shared/icons.h" #include "shared/icons.h"
#include "shared/defines.h"
#include <QCoreApplication> #include <QCoreApplication>
Models::EMails::EMails(bool p_edit, QObject* parent): Models::EMails::EMails(bool p_edit, QObject* parent):
@ -27,10 +28,15 @@ Models::EMails::EMails(bool p_edit, QObject* parent):
deque() {} deque() {}
int Models::EMails::columnCount(const QModelIndex& parent) const { int Models::EMails::columnCount(const QModelIndex& parent) const {
return 3;} SHARED_UNUSED(parent);
return 3;
}
int Models::EMails::rowCount(const QModelIndex& parent) const { int Models::EMails::rowCount(const QModelIndex& parent) const {
return deque.size();} SHARED_UNUSED(parent);
return deque.size();
}
void Models::EMails::revertPreferred(quint32 row) { void Models::EMails::revertPreferred(quint32 row) {
setData(createIndex(row, 2), !isPreferred(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 Models::EMails::flags(const QModelIndex& index) const {
Qt::ItemFlags f = QAbstractTableModel::flags(index); Qt::ItemFlags f = QAbstractTableModel::flags(index);
if (edit && index.column() != 2) { if (edit && index.column() != 2)
f = Qt::ItemIsEditable | f; f = Qt::ItemIsEditable | f;
}
return f; return f;
} }
@ -114,9 +120,9 @@ bool Models::EMails::setData(const QModelIndex& index, const QVariant& value, in
return true; return true;
case 1: { case 1: {
quint8 newRole = value.toUInt(); quint8 newRole = value.toUInt();
if (newRole > Shared::VCard::Email::work) { if (newRole > Shared::VCard::Email::work)
return false; return false;
}
item.role = static_cast<Shared::VCard::Email::Role>(newRole); item.role = static_cast<Shared::VCard::Email::Role>(newRole);
return true; return true;
} }
@ -160,19 +166,17 @@ QModelIndex Models::EMails::addNewEmptyLine() {
} }
bool Models::EMails::isPreferred(quint32 row) const { bool Models::EMails::isPreferred(quint32 row) const {
if (row < deque.size()) { if (row < deque.size())
return deque[row].prefered; return deque[row].prefered;
} else { else
return false; return false;
}
} }
void Models::EMails::removeLines(quint32 index, quint32 count) { void Models::EMails::removeLines(quint32 index, quint32 count) {
if (index < deque.size()) { if (index < deque.size()) {
quint32 maxCount = deque.size() - index; quint32 maxCount = deque.size() - index;
if (count > maxCount) { if (count > maxCount)
count = maxCount; count = maxCount;
}
if (count > 0) { if (count > 0) {
beginRemoveRows(QModelIndex(), index, index + count - 1); beginRemoveRows(QModelIndex(), index, index + count - 1);
@ -185,21 +189,19 @@ void Models::EMails::removeLines(quint32 index, quint32 count) {
} }
void Models::EMails::getEmails(std::deque<Shared::VCard::Email>& emails) const { void Models::EMails::getEmails(std::deque<Shared::VCard::Email>& emails) const {
for (const Shared::VCard::Email& my : deque) { for (const Shared::VCard::Email& my : deque)
emails.emplace_back(my); emails.emplace_back(my);
}
} }
void Models::EMails::setEmails(const std::deque<Shared::VCard::Email>& emails) { void Models::EMails::setEmails(const std::deque<Shared::VCard::Email>& emails) {
if (deque.size() > 0) { if (deque.size() > 0)
removeLines(0, deque.size()); removeLines(0, deque.size());
}
if (emails.size() > 0) { if (emails.size() > 0) {
beginInsertRows(QModelIndex(), 0, emails.size() - 1); beginInsertRows(QModelIndex(), 0, emails.size() - 1);
for (const Shared::VCard::Email& comming : emails) { for (const Shared::VCard::Email& comming : emails)
deque.emplace_back(comming); deque.emplace_back(comming);
}
endInsertRows(); endInsertRows();
} }
} }

View File

@ -16,6 +16,8 @@
#include "keys.h" #include "keys.h"
#include "shared/defines.h"
const QHash<int, QByteArray> Models::Keys::roles = { const QHash<int, QByteArray> Models::Keys::roles = {
{Label, "label"}, {Label, "label"},
{FingerPrint, "fingerPrint"}, {FingerPrint, "fingerPrint"},
@ -28,13 +30,11 @@ Models::Keys::Keys(QObject* parent):
modified() {} modified() {}
Models::Keys::~Keys() { Models::Keys::~Keys() {
for (Shared::KeyInfo* key : keys) { for (Shared::KeyInfo* key : keys)
delete key; delete key;
}
for (std::pair<const int, Shared::KeyInfo*>& pair: modified) { for (std::pair<const int, Shared::KeyInfo*>& pair: modified)
delete pair.second; delete pair.second;
}
} }
std::deque<Shared::KeyInfo> Models::Keys::modifiedKeys() const { std::deque<Shared::KeyInfo> 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 { int Models::Keys::rowCount(const QModelIndex& parent) const {
SHARED_UNUSED(parent);
return keys.size(); return keys.size();
} }
QHash<int, QByteArray> Models::Keys::roleNames() const {return roles;} QHash<int, QByteArray> Models::Keys::roleNames() const {return roles;}
QModelIndex Models::Keys::index(int row, int column, const QModelIndex& parent) const { 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 QModelIndex();
}
return createIndex(row, column, keys[row]); return createIndex(row, column, keys[row]);
} }

View File

@ -19,6 +19,7 @@
#include "phones.h" #include "phones.h"
#include "shared/icons.h" #include "shared/icons.h"
#include "shared/defines.h"
#include <QCoreApplication> #include <QCoreApplication>
Models::Phones::Phones(bool p_edit, QObject* parent): Models::Phones::Phones(bool p_edit, QObject* parent):
@ -27,10 +28,14 @@ Models::Phones::Phones(bool p_edit, QObject* parent):
deque() {} deque() {}
int Models::Phones::columnCount(const QModelIndex& parent) const { int Models::Phones::columnCount(const QModelIndex& parent) const {
return 4;} SHARED_UNUSED(parent);
return 4;
}
int Models::Phones::rowCount(const QModelIndex& parent) const { int Models::Phones::rowCount(const QModelIndex& parent) const {
return deque.size();} SHARED_UNUSED(parent);
return deque.size();
}
void Models::Phones::revertPreferred(quint32 row) { void Models::Phones::revertPreferred(quint32 row) {
setData(createIndex(row, 3), !isPreferred(row)); setData(createIndex(row, 3), !isPreferred(row));
@ -77,9 +82,9 @@ QVariant Models::Phones::data(const QModelIndex& index, int role) const {
case Qt::DisplayRole: case Qt::DisplayRole:
return QVariant(); return QVariant();
case Qt::DecorationRole: case Qt::DecorationRole:
if (deque[index.row()].prefered) { if (deque[index.row()].prefered)
return Shared::icon("favorite", false); return Shared::icon("favorite", false);
}
return QVariant(); return QVariant();
default: default:
return QVariant(); return QVariant();
@ -101,9 +106,9 @@ QModelIndex Models::Phones::addNewEmptyLine() {
Qt::ItemFlags Models::Phones::flags(const QModelIndex& index) const { Qt::ItemFlags Models::Phones::flags(const QModelIndex& index) const {
Qt::ItemFlags f = QAbstractTableModel::flags(index); Qt::ItemFlags f = QAbstractTableModel::flags(index);
if (edit && index.column() != 3) { if (edit && index.column() != 3)
f = Qt::ItemIsEditable | f; f = Qt::ItemIsEditable | f;
}
return f; return f;
} }
@ -139,25 +144,22 @@ bool Models::Phones::dropPrefered() {
} }
void Models::Phones::getPhones(std::deque<Shared::VCard::Phone>& phones) const { void Models::Phones::getPhones(std::deque<Shared::VCard::Phone>& phones) const {
for (const Shared::VCard::Phone& my : deque) { for (const Shared::VCard::Phone& my : deque)
phones.emplace_back(my); phones.emplace_back(my);
}
} }
bool Models::Phones::isPreferred(quint32 row) const { bool Models::Phones::isPreferred(quint32 row) const {
if (row < deque.size()) { if (row < deque.size())
return deque[row].prefered; return deque[row].prefered;
} else { else
return false; return false;
}
} }
void Models::Phones::removeLines(quint32 index, quint32 count) { void Models::Phones::removeLines(quint32 index, quint32 count) {
if (index < deque.size()) { if (index < deque.size()) {
quint32 maxCount = deque.size() - index; quint32 maxCount = deque.size() - index;
if (count > maxCount) { if (count > maxCount)
count = maxCount; count = maxCount;
}
if (count > 0) { if (count > 0) {
beginRemoveRows(QModelIndex(), index, index + count - 1); beginRemoveRows(QModelIndex(), index, index + count - 1);
@ -178,17 +180,17 @@ bool Models::Phones::setData(const QModelIndex& index, const QVariant& value, in
return true; return true;
case 1: { case 1: {
quint8 newRole = value.toUInt(); quint8 newRole = value.toUInt();
if (newRole > Shared::VCard::Phone::work) { if (newRole > Shared::VCard::Phone::work)
return false; return false;
}
item.role = static_cast<Shared::VCard::Phone::Role>(newRole); item.role = static_cast<Shared::VCard::Phone::Role>(newRole);
return true; return true;
} }
case 2: { case 2: {
quint8 newType = value.toUInt(); quint8 newType = value.toUInt();
if (newType > Shared::VCard::Phone::other) { if (newType > Shared::VCard::Phone::other)
return false; return false;
}
item.type = static_cast<Shared::VCard::Phone::Type>(newType); item.type = static_cast<Shared::VCard::Phone::Type>(newType);
return true; return true;
} }
@ -209,15 +211,15 @@ bool Models::Phones::setData(const QModelIndex& index, const QVariant& value, in
} }
void Models::Phones::setPhones(const std::deque<Shared::VCard::Phone>& phones) { void Models::Phones::setPhones(const std::deque<Shared::VCard::Phone>& phones) {
if (deque.size() > 0) { if (deque.size() > 0)
removeLines(0, deque.size()); removeLines(0, deque.size());
}
if (phones.size() > 0) { if (phones.size() > 0) {
beginInsertRows(QModelIndex(), 0, phones.size() - 1); beginInsertRows(QModelIndex(), 0, phones.size() - 1);
for (const Shared::VCard::Phone& comming : phones) { for (const Shared::VCard::Phone& comming : phones)
deque.emplace_back(comming); deque.emplace_back(comming);
}
endInsertRows(); endInsertRows();
} }
} }

View File

@ -21,6 +21,8 @@
#include <QIcon> #include <QIcon>
#include <QFont> #include <QFont>
#include "shared/defines.h"
Models::Roster::Roster(QObject* parent): Models::Roster::Roster(QObject* parent):
QAbstractItemModel(parent), QAbstractItemModel(parent),
accountsModel(new Accounts()), accountsModel(new Accounts()),
@ -39,14 +41,12 @@ Models::Roster::Roster(QObject* parent):
connect(root, &Item::childMoved, this, &Roster::onChildMoved); connect(root, &Item::childMoved, this, &Roster::onChildMoved);
} }
Models::Roster::~Roster() Models::Roster::~Roster() {
{
delete accountsModel; delete accountsModel;
delete root; delete root;
} }
void Models::Roster::addAccount(const QMap<QString, QVariant>& data) void Models::Roster::addAccount(const QMap<QString, QVariant>& data) {
{
Account* acc = new Account(data); Account* acc = new Account(data);
connect(acc, &Account::reconnected, this, &Roster::onAccountReconnected); connect(acc, &Account::reconnected, this, &Roster::onAccountReconnected);
root->appendChild(acc); root->appendChild(acc);
@ -56,24 +56,21 @@ void Models::Roster::addAccount(const QMap<QString, QVariant>& data)
emit addedElement({acc->getId()}); emit addedElement({acc->getId()});
} }
QVariant Models::Roster::data (const QModelIndex& index, int role) const QVariant Models::Roster::data (const QModelIndex& index, int role) const {
{ if (!index.isValid())
if (!index.isValid()) {
return QVariant(); return QVariant();
}
QVariant result; QVariant result;
Item *item = static_cast<Item*>(index.internalPointer()); Item *item = static_cast<Item*>(index.internalPointer());
if (item->type == Item::reference) { if (item->type == Item::reference)
item = static_cast<Reference*>(item)->dereference(); item = static_cast<Reference*>(item)->dereference();
}
switch (role) { switch (role) {
case Qt::DisplayRole: case Qt::DisplayRole: {
{ if (index.column() != 0)
if (index.column() != 0) {
break; break;
}
switch (item->type) { switch (item->type) {
case Item::group: { case Item::group: {
Group* gr = static_cast<Group*>(item); Group* gr = static_cast<Group*>(item);
@ -81,9 +78,9 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const
str += gr->getName(); str += gr->getName();
unsigned int amount = gr->getUnreadMessages(); unsigned int amount = gr->getUnreadMessages();
if (amount > 0) { if (amount > 0)
str += QString(" (") + tr("New messages") + ")"; str += QString(" (") + tr("New messages") + ")";
}
result = str; result = str;
} }
@ -104,11 +101,10 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const
} else if (col == 1) { } else if (col == 1) {
QString path = acc->getAvatarPath(); QString path = acc->getAvatarPath();
if (path.size() > 0) { if (path.size() > 0)
result = QIcon(path); result = QIcon(path);
} }
} }
}
break; break;
case Item::contact: { case Item::contact: {
Contact* contact = static_cast<Contact*>(item); Contact* contact = static_cast<Contact*>(item);
@ -116,16 +112,15 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const
if (col == 0) { if (col == 0) {
result = contact->getStatusIcon(false); result = contact->getStatusIcon(false);
} else if (col == 1) { } else if (col == 1) {
if (contact->getAvatarState() != Shared::Avatar::empty) { if (contact->getAvatarState() != Shared::Avatar::empty)
result = QIcon(contact->getAvatarPath()); result = QIcon(contact->getAvatarPath());
} }
} }
}
break; break;
case Item::presence: { case Item::presence: {
if (index.column() != 0) { if (index.column() != 0)
break; break;
}
Presence* presence = static_cast<Presence*>(item); Presence* presence = static_cast<Presence*>(item);
result = presence->getStatusIcon(false); result = presence->getStatusIcon(false);
} }
@ -138,11 +133,10 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const
} else if (col == 1) { } else if (col == 1) {
QString path = room->getAvatarPath(); QString path = room->getAvatarPath();
if (path.size() > 0) { if (path.size() > 0)
result = QIcon(path); result = QIcon(path);
} }
} }
}
break; break;
case Item::participant: { case Item::participant: {
quint8 col = index.column(); quint8 col = index.column();
@ -151,15 +145,12 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const
result = p->getStatusIcon(false); result = p->getStatusIcon(false);
} else if (col == 1) { } else if (col == 1) {
QString path = p->getAvatarPath(); QString path = p->getAvatarPath();
if (path.size() > 0) { if (path.size() > 0)
result = QIcon(path); result = QIcon(path);
} }
} if (index.column() != 0)
if (index.column() != 0) {
break; break;
} }
}
break; break;
default: default:
break; break;
@ -194,9 +185,9 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const
Contact* contact = static_cast<Contact*>(item); Contact* contact = static_cast<Contact*>(item);
QString str(""); QString str("");
int mc = contact->getMessagesCount(); int mc = contact->getMessagesCount();
if (mc > 0) { if (mc > 0)
str += QString(tr("New messages: ")) + std::to_string(mc).c_str() + "\n"; str += QString(tr("New messages: ")) + std::to_string(mc).c_str() + "\n";
}
str += tr("Jabber ID: ") + contact->getJid() + "\n"; str += tr("Jabber ID: ") + contact->getJid() + "\n";
Shared::SubscriptionState ss = contact->getState(); Shared::SubscriptionState ss = contact->getState();
if (ss == Shared::SubscriptionState::both || ss == Shared::SubscriptionState::to) { if (ss == Shared::SubscriptionState::both || ss == Shared::SubscriptionState::to) {
@ -204,10 +195,9 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const
str += tr("Availability: ") + Shared::Global::getName(av); str += tr("Availability: ") + Shared::Global::getName(av);
if (av != Shared::Availability::offline) { if (av != Shared::Availability::offline) {
QString s = contact->getStatus(); QString s = contact->getStatus();
if (s.size() > 0) { if (s.size() > 0)
str += "\n" + tr("Status: ") + s; str += "\n" + tr("Status: ") + s;
} }
}
str += "\n" + tr("Subscription: ") + Shared::Global::getName(ss); str += "\n" + tr("Subscription: ") + Shared::Global::getName(ss);
} else { } else {
str += tr("Subscription: ") + Shared::Global::getName(ss); str += tr("Subscription: ") + Shared::Global::getName(ss);
@ -222,9 +212,9 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const
Shared::Availability av = contact->getAvailability(); Shared::Availability av = contact->getAvailability();
str += tr("Availability: ") + Shared::Global::getName(av); str += tr("Availability: ") + Shared::Global::getName(av);
QString s = contact->getStatus(); QString s = contact->getStatus();
if (s.size() > 0) { if (s.size() > 0)
str += "\n" + tr("Status: ") + s; str += "\n" + tr("Status: ") + s;
}
str += "\n" + tr("Client: ") + contact->getClientNode(); str += "\n" + tr("Client: ") + contact->getClientNode();
result = str; result = str;
@ -236,9 +226,8 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const
Shared::Availability av = p->getAvailability(); Shared::Availability av = p->getAvailability();
str += tr("Availability: ") + Shared::Global::getName(av) + "\n"; str += tr("Availability: ") + Shared::Global::getName(av) + "\n";
QString s = p->getStatus(); QString s = p->getStatus();
if (s.size() > 0) { if (s.size() > 0)
str += tr("Status: ") + s + "\n"; str += tr("Status: ") + s + "\n";
}
str += tr("Affiliation: ") + Shared::Global::getName(p->getAffiliation()) + "\n"; str += tr("Affiliation: ") + Shared::Global::getName(p->getAffiliation()) + "\n";
str += tr("Role: ") + Shared::Global::getName(p->getRole()) + "\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<Group*>(item); Group* gr = static_cast<Group*>(item);
unsigned int count = gr->getUnreadMessages(); unsigned int count = gr->getUnreadMessages();
QString str(""); QString str("");
if (count > 0) { if (count > 0)
str += tr("New messages: ") + std::to_string(count).c_str() + "\n"; 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("Online contacts: ") + std::to_string(gr->getOnlineContacts()).c_str() + "\n";
str += tr("Total contacts: ") + std::to_string(gr->childCount()).c_str(); str += tr("Total contacts: ") + std::to_string(gr->childCount()).c_str();
result = str; result = str;
@ -263,15 +252,14 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const
Room* rm = static_cast<Room*>(item); Room* rm = static_cast<Room*>(item);
unsigned int count = rm->getMessagesCount(); unsigned int count = rm->getMessagesCount();
QString str(""); QString str("");
if (count > 0) { if (count > 0)
str += tr("New messages: ") + std::to_string(count).c_str() + "\n"; str += tr("New messages: ") + std::to_string(count).c_str() + "\n";
}
str += tr("Jabber ID: ") + rm->getJid() + "\n"; str += tr("Jabber ID: ") + rm->getJid() + "\n";
str += tr("Subscription: ") + rm->getStatusText(); str += tr("Subscription: ") + rm->getStatusText();
if (rm->getJoined()) { if (rm->getJoined())
str += QString("\n") + tr("Members: ") + std::to_string(rm->childCount()).c_str(); str += QString("\n") + tr("Members: ") + std::to_string(rm->childCount()).c_str();
}
result = str; result = str;
} }
break; break;
@ -284,10 +272,9 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const
switch (item->type) { switch (item->type) {
case Item::account: { case Item::account: {
Account* acc = static_cast<Account*>(item); Account* acc = static_cast<Account*>(item);
if (!acc->getActive()) { if (!acc->getActive())
result = qApp->palette().brush(QPalette::Disabled, QPalette::Text); result = qApp->palette().brush(QPalette::Disabled, QPalette::Text);
} }
}
break; break;
default: default:
break; break;
@ -299,17 +286,14 @@ QVariant Models::Roster::data (const QModelIndex& index, int role) const
return result; return result;
} }
int Models::Roster::columnCount (const QModelIndex& parent) const int Models::Roster::columnCount (const QModelIndex& parent) const {
{ if (parent.isValid())
if (parent.isValid()) {
return static_cast<Item*>(parent.internalPointer())->columnCount(); return static_cast<Item*>(parent.internalPointer())->columnCount();
} else { else
return root->columnCount(); 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<QString, Account*>::iterator itr = accounts.find(account); std::map<QString, Account*>::iterator itr = accounts.find(account);
if (itr != accounts.end()) { if (itr != accounts.end()) {
Account* acc = itr->second; 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 {
Qt::ItemFlags Models::Roster::flags(const QModelIndex& index) const if (!index.isValid())
{
if (!index.isValid()) {
return Qt::ItemFlags(); return Qt::ItemFlags();
}
return QAbstractItemModel::flags(index); return QAbstractItemModel::flags(index);
} }
int Models::Roster::rowCount (const QModelIndex& parent) const{
int Models::Roster::rowCount (const QModelIndex& parent) const
{
Item *parentItem; Item *parentItem;
if (!parent.isValid()) { if (!parent.isValid())
parentItem = root; parentItem = root;
} else { else
parentItem = static_cast<Item*>(parent.internalPointer()); parentItem = static_cast<Item*>(parent.internalPointer());
}
return parentItem->childCount(); 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(); return QVariant();
} }
QModelIndex Models::Roster::parent (const QModelIndex& child) const QModelIndex Models::Roster::parent (const QModelIndex& child) const {
{ if (!child.isValid())
if (!child.isValid()) {
return QModelIndex(); return QModelIndex();
}
Item *childItem = static_cast<Item*>(child.internalPointer()); Item *childItem = static_cast<Item*>(child.internalPointer());
if (childItem == root) { if (childItem == root)
return QModelIndex(); return QModelIndex();
}
Item *parentItem = childItem->parentItem(); Item *parentItem = childItem->parentItem();
if (parentItem == root)
if (parentItem == root) {
return createIndex(0, 0, parentItem); return createIndex(0, 0, parentItem);
}
return createIndex(parentItem->row(), 0, parentItem); return createIndex(parentItem->row(), 0, parentItem);
} }
QModelIndex Models::Roster::index (int row, int column, const QModelIndex& parent) const QModelIndex Models::Roster::index (int row, int column, const QModelIndex& parent) const {
{ if (!hasIndex(row, column, parent))
if (!hasIndex(row, column, parent)) {
return QModelIndex(); return QModelIndex();
}
Item *parentItem; Item *parentItem;
if (!parent.isValid()) { if (!parent.isValid())
parentItem = root; parentItem = root;
} else { else
parentItem = static_cast<Item*>(parent.internalPointer()); parentItem = static_cast<Item*>(parent.internalPointer());
}
Item *childItem = parentItem->child(row); Item *childItem = parentItem->child(row);
if (childItem) { if (childItem)
return createIndex(row, column, childItem); return createIndex(row, column, childItem);
} else { else
return QModelIndex(); return QModelIndex();
}
} }
Models::Roster::ElId::ElId(const QString& p_account, const QString& p_name): 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) name(p_name)
{} {}
bool Models::Roster::ElId::operator <(const Models::Roster::ElId& other) const bool Models::Roster::ElId::operator <(const Models::Roster::ElId& other) const {
{ if (account == other.account)
if (account == other.account) {
return name < other.name; return name < other.name;
} else { else
return account < other.account; 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)); 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); return (account == other.account) && (name == other.name);
} }
void Models::Roster::onAccountDataChanged(const QModelIndex& tl, const QModelIndex& br, const QVector<int>& roles) void Models::Roster::onAccountDataChanged(const QModelIndex& tl, const QModelIndex& br, const QVector<int>& roles) {
{
if (tl.column() == 0) { if (tl.column() == 0) {
emit dataChanged(tl, br, roles); emit dataChanged(tl, br, roles);
} else if (tl.column() == 2) { } 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); ElId id(account, name);
std::map<ElId, Group*>::const_iterator gItr = groups.find(id); std::map<ElId, Group*>::const_iterator gItr = groups.find(id);
if (gItr != groups.end()) { 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)); groups.insert(std::make_pair(id, group));
acc->appendChild(group); acc->appendChild(group);
emit addedElement({acc->getId(), group->getId()}); emit addedElement({acc->getId(), group->getId()});
} else { } else {
qDebug() << "An attempt to add group " << name << " to non existing account " << account << ", skipping"; 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<QString, QVariant>& data) void Models::Roster::addContact(const QString& account, const QString& jid, const QString& group, const QMap<QString, QVariant>& data) {
{
Item* parent; Item* parent;
Account* acc; Account* acc;
Contact* contact; Contact* contact;
@ -513,16 +477,15 @@ void Models::Roster::addContact(const QString& account, const QString& jid, cons
} }
path.push_back(contact->getId()); path.push_back(contact->getId());
if (ref == 0) { if (ref == 0)
ref = new Reference(contact); ref = new Reference(contact);
}
parent->appendChild(ref); parent->appendChild(ref);
emit addedElement(path); 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); ElId id(account, name);
std::map<ElId, Group*>::const_iterator gItr = groups.find(id); std::map<ElId, Group*>::const_iterator gItr = groups.find(id);
if (gItr == groups.end()) { if (gItr == groups.end()) {
@ -541,12 +504,11 @@ void Models::Roster::removeGroup(const QString& account, const QString& name)
item->removeChild(0); item->removeChild(0);
Contact* cont = static_cast<Contact*>(ref->dereference()); Contact* cont = static_cast<Contact*>(ref->dereference());
if (cont->referencesCount() == 1) { if (cont->referencesCount() == 1)
toInsert.push_back(ref); toInsert.push_back(ref);
} else { else
delete ref; delete ref;
} }
}
if (toInsert.size() > 0) { if (toInsert.size() > 0) {
Account* acc = accounts.find("account")->second; Account* acc = accounts.find("account")->second;
@ -559,8 +521,7 @@ void Models::Roster::removeGroup(const QString& account, const QString& name)
groups.erase(gItr); groups.erase(gItr);
} }
void Models::Roster::changeContact(const QString& account, const QString& jid, const QMap<QString, QVariant>& data) void Models::Roster::changeContact(const QString& account, const QString& jid, const QMap<QString, QVariant>& data) {
{
Element* el = getElement(ElId(account, jid)); Element* el = getElement(ElId(account, jid));
if (el != nullptr) { if (el != nullptr) {
for (QMap<QString, QVariant>::const_iterator itr = data.begin(), end = data.end(); itr != end; ++itr) { for (QMap<QString, QVariant>::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<QString, QVariant>& data) void Models::Roster::changeMessage(const QString& account, const QString& jid, const QString& id, const QMap<QString, QVariant>& data) {
{
Element* el = getElement(ElId(account, jid)); Element* el = getElement(ElId(account, jid));
if (el != nullptr) { if (el != nullptr)
el->changeMessage(id, data); 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"; 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); ElId id(account, jid);
std::map<ElId, Contact*>::iterator itr = contacts.find(id); std::map<ElId, Contact*>::iterator itr = contacts.find(id);
@ -592,21 +550,18 @@ void Models::Roster::removeContact(const QString& account, const QString& jid)
std::set<ElId> toRemove; std::set<ElId> toRemove;
for (std::pair<ElId, Group*> pair : groups) { for (std::pair<ElId, Group*> pair : groups) {
if (pair.second->childCount() == 0) { if (pair.second->childCount() == 0)
toRemove.insert(pair.first); toRemove.insert(pair.first);
} }
}
for (const ElId& elId : toRemove) { for (const ElId& elId : toRemove)
removeGroup(elId.account, elId.name); removeGroup(elId.account, elId.name);
}
} else { } else {
qDebug() << "An attempt to remove contact " << jid << " from account " << account <<" which doesn't exist there, skipping"; 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 contactId(account, jid);
ElId groupId(account, group); ElId groupId(account, group);
@ -639,20 +594,18 @@ void Models::Roster::removeContact(const QString& account, const QString& jid, c
} else { } else {
delete ref; delete ref;
} }
if (gr->childCount() == 0) { if (gr->childCount() == 0)
removeGroup(account, group); 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 index = createIndex(row, 0, item);
QModelIndex index2 = createIndex(row, 1, item); QModelIndex index2 = createIndex(row, 1, item);
emit dataChanged(index, index2); 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; int row = 0;
if (parent != root) { if (parent != root) {
row = parent->row(); 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; int oldRow = 0;
if (source != root) { if (source != root)
oldRow = source->row(); oldRow = source->row();
}
int newRow = 0; int newRow = 0;
if (destination != root) { if (destination != root)
newRow = destination->row(); newRow = destination->row();
}
beginMoveRows(createIndex(oldRow, 0, source), first, last, createIndex(newRow, 0, destination), newIndex); 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; int row = 0;
if (parent != root) { if (parent != root)
row = parent->row(); row = parent->row();
}
beginRemoveRows(createIndex(row, 0, parent), first, last); beginRemoveRows(createIndex(row, 0, parent), first, last);
} }
void Models::Roster::onChildInserted() void Models::Roster::onChildInserted() {
{
endInsertRows(); endInsertRows();
} }
void Models::Roster::onChildMoved() void Models::Roster::onChildMoved() {
{
endMoveRows(); endMoveRows();
} }
void Models::Roster::onChildRemoved() void Models::Roster::onChildRemoved() {
{
endRemoveRows(); endRemoveRows();
} }
void Models::Roster::addPresence(const QString& account, const QString& jid, const QString& name, const QMap<QString, QVariant>& data) void Models::Roster::addPresence(const QString& account, const QString& jid, const QString& name, const QMap<QString, QVariant>& data) {
{
ElId contactId(account, jid); ElId contactId(account, jid);
std::map<ElId, Contact*>::iterator itr = contacts.find(contactId); std::map<ElId, Contact*>::iterator itr = contacts.find(contactId);
if (itr != contacts.end()) { 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); ElId contactId(account, jid);
std::map<ElId, Contact*>::iterator itr = contacts.find(contactId); std::map<ElId, Contact*>::iterator itr = contacts.find(contactId);
if (itr != contacts.end()) { 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())); Element* el = getElement(ElId(account, data.getPenPalJid()));
if (el != nullptr) { if (el != nullptr)
el->addMessage(data); el->addMessage(data);
}
} }
void Models::Roster::removeAccount(const QString& account) void Models::Roster::removeAccount(const QString& account) {
{
std::map<QString, Account*>::const_iterator itr = accounts.find(account); std::map<QString, Account*>::const_iterator itr = accounts.find(account);
if (itr == accounts.end()) { if (itr == accounts.end()) {
qDebug() << "An attempt to remove non existing account " << account << ", skipping"; qDebug() << "An attempt to remove non existing account " << account << ", skipping";
@ -777,26 +720,23 @@ void Models::Roster::removeAccount(const QString& account)
acc->deleteLater(); 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); ElId id(account, jid);
std::map<ElId, Contact*>::const_iterator cItr = contacts.find(id); std::map<ElId, Contact*>::const_iterator cItr = contacts.find(id);
QString name = ""; QString name = "";
if (cItr == contacts.end()) { if (cItr == contacts.end()) {
std::map<ElId, Room*>::const_iterator rItr = rooms.find(id); std::map<ElId, Room*>::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"; qDebug() << "An attempt to get a name of non existing contact/room " << account << ":" << jid << ", skipping";
} else { else
name = rItr->second->getRoomName(); name = rItr->second->getRoomName();
}
} else { } else {
name = cItr->second->getContactName(); name = cItr->second->getContactName();
} }
return name; return name;
} }
void Models::Roster::addRoom(const QString& account, const QString jid, const QMap<QString, QVariant>& data) void Models::Roster::addRoom(const QString& account, const QString jid, const QMap<QString, QVariant>& data) {
{
Account* acc; Account* acc;
{ {
std::map<QString, Account*>::iterator itr = accounts.find(account); std::map<QString, Account*>::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()}); emit addedElement({acc->getId(), room->getId()});
} }
void Models::Roster::changeRoom(const QString& account, const QString jid, const QMap<QString, QVariant>& data) void Models::Roster::changeRoom(const QString& account, const QString jid, const QMap<QString, QVariant>& data) {
{
ElId id = {account, jid}; ElId id = {account, jid};
std::map<ElId, Room*>::const_iterator itr = rooms.find(id); std::map<ElId, Room*>::const_iterator itr = rooms.find(id);
if (itr == rooms.end()) { 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; Account* acc;
{ {
std::map<QString, Account*>::iterator itr = accounts.find(account); std::map<QString, Account*>::iterator itr = accounts.find(account);
@ -865,8 +803,7 @@ void Models::Roster::removeRoom(const QString& account, const QString jid)
rooms.erase(itr); rooms.erase(itr);
} }
void Models::Roster::addRoomParticipant(const QString& account, const QString& jid, const QString& name, const QMap<QString, QVariant>& data) void Models::Roster::addRoomParticipant(const QString& account, const QString& jid, const QString& name, const QMap<QString, QVariant>& data) {
{
ElId id = {account, jid}; ElId id = {account, jid};
std::map<ElId, Room*>::const_iterator itr = rooms.find(id); std::map<ElId, Room*>::const_iterator itr = rooms.find(id);
if (itr == rooms.end()) { 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<QString, QVariant>& data) void Models::Roster::changeRoomParticipant(const QString& account, const QString& jid, const QString& name, const QMap<QString, QVariant>& data) {
{
ElId id = {account, jid}; ElId id = {account, jid};
std::map<ElId, Room*>::const_iterator itr = rooms.find(id); std::map<ElId, Room*>::const_iterator itr = rooms.find(id);
if (itr == rooms.end()) { 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}; ElId id = {account, jid};
std::map<ElId, Room*>::const_iterator itr = rooms.find(id); std::map<ElId, Room*>::const_iterator itr = rooms.find(id);
if (itr == rooms.end()) { if (itr == rooms.end()) {
@ -901,20 +836,17 @@ void Models::Roster::removeRoomParticipant(const QString& account, const QString
} }
} }
std::deque<QString> Models::Roster::groupList(const QString& account) const std::deque<QString> Models::Roster::groupList(const QString& account) const {
{
std::deque<QString> answer; std::deque<QString> answer;
for (std::pair<ElId, Group*> pair : groups) { for (std::pair<ElId, Group*> pair : groups) {
if (pair.first.account == account) { if (pair.first.account == account)
answer.push_back(pair.first.name); answer.push_back(pair.first.name);
} }
}
return answer; 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}); ElId grId({account, group});
std::map<ElId, Group*>::const_iterator gItr = groups.find(grId); std::map<ElId, Group*>::const_iterator gItr = groups.find(grId);
if (gItr == groups.end()) { if (gItr == groups.end()) {
@ -924,23 +856,20 @@ 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); ElId id(account, jid);
std::map<ElId, Contact*>::const_iterator cItr = contacts.find(id); std::map<ElId, Contact*>::const_iterator cItr = contacts.find(id);
QString path = ""; QString path = "";
if (cItr == contacts.end()) { if (cItr == contacts.end()) {
std::map<ElId, Room*>::const_iterator rItr = rooms.find(id); std::map<ElId, Room*>::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"; qDebug() << "An attempt to get an icon path of non existing contact" << account << ":" << jid << ", returning empty value";
} else { else
path = rItr->second->getParticipantIconPath(resource); path = rItr->second->getParticipantIconPath(resource);
}
} else { } else {
if (cItr->second->getAvatarState() != Shared::Avatar::empty) { if (cItr->second->getAvatarState() != Shared::Avatar::empty)
path = cItr->second->getAvatarPath(); path = cItr->second->getAvatarPath();
} }
}
return path; return path;
} }
@ -950,34 +879,29 @@ Models::Account * Models::Roster::getAccount(const QString& name) {
const Models::Account * Models::Roster::getAccountConst(const QString& name) const { const Models::Account * Models::Roster::getAccountConst(const QString& name) const {
return accounts.at(name);} 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<ElId, Contact*>::const_iterator cItr = contacts.find(id); std::map<ElId, Contact*>::const_iterator cItr = contacts.find(id);
if (cItr != contacts.end()) { if (cItr != contacts.end()) {
return cItr->second; return cItr->second;
} else { } else {
std::map<ElId, Room*>::const_iterator rItr = rooms.find(id); std::map<ElId, Room*>::const_iterator rItr = rooms.find(id);
if (rItr != rooms.end()) { if (rItr != rooms.end())
return rItr->second; return rItr->second;
} }
}
return nullptr; 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); const Element* el = getElementConst(elementId);
if (el != nullptr) { if (el != nullptr)
return el->markMessageAsRead(messageId); return el->markMessageAsRead(messageId);
} else { else
return false; return false;
}
} }
QModelIndex Models::Roster::getAccountIndex(const QString& name) const QModelIndex Models::Roster::getAccountIndex(const QString& name) const {
{
std::map<QString, Account*>::const_iterator itr = accounts.find(name); std::map<QString, Account*>::const_iterator itr = accounts.find(name);
if (itr == accounts.end()) { if (itr == accounts.end()) {
return QModelIndex(); 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<QString, Account*>::const_iterator itr = accounts.find(account); std::map<QString, Account*>::const_iterator itr = accounts.find(account);
if (itr == accounts.end()) { if (itr == accounts.end()) {
return QModelIndex(); 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<QString, Account*>::const_iterator itr = accounts.find(account); std::map<QString, Account*>::const_iterator itr = accounts.find(account);
if (itr == accounts.end()) { if (itr == accounts.end()) {
return QModelIndex(); return QModelIndex();
@ -1017,12 +939,11 @@ QModelIndex Models::Roster::getContactIndex(const QString& account, const QStrin
return contactIndex; return contactIndex;
} else { } else {
Presence* pres = cItr->second->getPresence(resource); Presence* pres = cItr->second->getPresence(resource);
if (pres != nullptr) { if (pres != nullptr)
return index(pres->row(), 0, contactIndex); return index(pres->row(), 0, contactIndex);
} else { else
return contactIndex; return contactIndex;
} }
}
} else { } else {
std::map<ElId, Room*>::const_iterator rItr = rooms.find(ElId(account, jid)); std::map<ElId, Room*>::const_iterator rItr = rooms.find(ElId(account, jid));
if (rItr != rooms.end()) { if (rItr != rooms.end()) {
@ -1031,12 +952,11 @@ QModelIndex Models::Roster::getContactIndex(const QString& account, const QStrin
return roomIndex; return roomIndex;
} else { } else {
Participant* part = rItr->second->getParticipant(resource); Participant* part = rItr->second->getParticipant(resource);
if (part != nullptr) { if (part != nullptr)
return index(part->row(), 0, roomIndex); return index(part->row(), 0, roomIndex);
} else { else
return roomIndex; return roomIndex;
} }
}
} else { } else {
return QModelIndex(); 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<Element*>(sender()); Element* el = static_cast<Element*>(sender());
emit requestArchive(el->getAccountName(), el->getJid(), before); emit requestArchive(el->getAccountName(), el->getJid(), before);
} }
void Models::Roster::responseArchive(const QString& account, const QString& jid, const std::list<Shared::Message>& list, bool last) void Models::Roster::responseArchive(const QString& account, const QString& jid, const std::list<Shared::Message>& list, bool last) {
{
ElId id(account, jid); ElId id(account, jid);
Element* el = getElement(id); Element* el = getElement(id);
if (el != nullptr) { if (el != nullptr)
el->responseArchive(list, last); el->responseArchive(list, last);
}
} }
void Models::Roster::fileProgress(const std::list<Shared::MessageInfo>& msgs, qreal value, bool up) void Models::Roster::fileProgress(const std::list<Shared::MessageInfo>& msgs, qreal value, bool up) {
{
for (const Shared::MessageInfo& info : msgs) { for (const Shared::MessageInfo& info : msgs) {
Element* el = getElement(ElId(info.account, info.jid)); Element* el = getElement(ElId(info.account, info.jid));
if (el != nullptr) { if (el != nullptr)
el->fileProgress(info.messageId, value, up); el->fileProgress(info.messageId, value, up);
} }
}
} }
void Models::Roster::fileComplete(const std::list<Shared::MessageInfo>& msgs, bool up) void Models::Roster::fileComplete(const std::list<Shared::MessageInfo>& msgs, bool up) {
{
for (const Shared::MessageInfo& info : msgs) { for (const Shared::MessageInfo& info : msgs) {
Element* el = getElement(ElId(info.account, info.jid)); Element* el = getElement(ElId(info.account, info.jid));
if (el != nullptr) { if (el != nullptr)
el->fileComplete(info.messageId, up); el->fileComplete(info.messageId, up);
} }
}
} }
void Models::Roster::fileError(const std::list<Shared::MessageInfo>& msgs, const QString& err, bool up) void Models::Roster::fileError(const std::list<Shared::MessageInfo>& msgs, const QString& err, bool up) {
{
for (const Shared::MessageInfo& info : msgs) { for (const Shared::MessageInfo& info : msgs) {
Element* el = getElement(ElId(info.account, info.jid)); Element* el = getElement(ElId(info.account, info.jid));
if (el != nullptr) { if (el != nullptr)
el->fileError(info.messageId, err, up); 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<Models::Element*>(getElementConst(id)); return const_cast<Models::Element*>(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); const Models::Element* el = getElementConst(id);
if (el == nullptr) { if (el == nullptr)
return Item::root; return Item::root;
}
return el->type; return el->type;
} }
void Models::Roster::onAccountReconnected() void Models::Roster::onAccountReconnected() {
{
Account* acc = static_cast<Account*>(sender()); Account* acc = static_cast<Account*>(sender());
QString accName = acc->getName(); QString accName = acc->getName();
for (const std::pair<const ElId, Contact*>& pair : contacts) { for (const std::pair<const ElId, Contact*>& pair : contacts) {
if (pair.first.account == accName) { if (pair.first.account == accName)
pair.second->handleRecconnect(); pair.second->handleRecconnect();
} }
}
} }
void Models::Roster::recalculateUnreadMessages() void Models::Roster::recalculateUnreadMessages() {
{
int count(0); int count(0);
for (const std::pair<const ElId, Contact*>& pair : contacts) { for (const std::pair<const ElId, Contact*>& pair : contacts)
count += pair.second->getMessagesCount(); count += pair.second->getMessagesCount();
}
for (const std::pair<const ElId, Room*>& pair : rooms) { for (const std::pair<const ElId, Room*>& pair : rooms)
count += pair.second->getMessagesCount(); count += pair.second->getMessagesCount();
}
emit unreadMessagesCountChanged(count); emit unreadMessagesCountChanged(count);
} }
std::list<QString> Models::Roster::getItemPath(const QModelIndex& index) const std::list<QString> Models::Roster::getItemPath(const QModelIndex& index) const {
{
std::list<QString> result; std::list<QString> result;
if (index.isValid() && index.model() == this) { if (index.isValid() && index.model() == this) {
Item* item = static_cast<Item*>(index.internalPointer()); Item* item = static_cast<Item*>(index.internalPointer());
@ -1143,8 +1048,7 @@ std::list<QString> Models::Roster::getItemPath(const QModelIndex& index) const
return result; return result;
} }
QModelIndex Models::Roster::getIndexByPath(const std::list<QString>& path) const QModelIndex Models::Roster::getIndexByPath(const std::list<QString>& path) const {
{
if (path.empty()) if (path.empty())
return QModelIndex(); return QModelIndex();

View File

@ -18,35 +18,30 @@
#include "QTimer" #include "QTimer"
#include "comboboxdelegate.h" #include "comboboxdelegate.h"
#include "shared/defines.h"
ComboboxDelegate::ComboboxDelegate(QObject *parent): ComboboxDelegate::ComboboxDelegate(QObject *parent):
QStyledItemDelegate(parent), QStyledItemDelegate(parent),
entries(), entries(),
ff(new FocusFilter()) ff(new FocusFilter())
{ {}
}
ComboboxDelegate::~ComboboxDelegate() {
ComboboxDelegate::~ComboboxDelegate()
{
delete ff; 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); QComboBox *cb = new QComboBox(parent);
for (const std::pair<QString, QIcon>& pair : entries)
for (const std::pair<QString, QIcon>& pair : entries) {
cb->addItem(pair.second, pair.first); cb->addItem(pair.second, pair.first);
}
return cb; return cb;
} }
void ComboboxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const void ComboboxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const {
{
QComboBox *cb = static_cast<QComboBox*>(editor); QComboBox *cb = static_cast<QComboBox*>(editor);
int currentIndex = index.data(Qt::EditRole).toInt(); int currentIndex = index.data(Qt::EditRole).toInt();
if (currentIndex >= 0) { 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<QComboBox *>(editor); QComboBox *cb = static_cast<QComboBox *>(editor);
model->setData(index, cb->currentIndex(), Qt::EditRole); 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); 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) { if (evt->type() == QEvent::FocusIn) {
QComboBox* cb = static_cast<QComboBox*>(src); QComboBox* cb = static_cast<QComboBox*>(src);
cb->removeEventFilter(this); cb->removeEventFilter(this);

View File

@ -18,14 +18,13 @@
#include "resizer.h" #include "resizer.h"
#include "shared/defines.h"
Resizer::Resizer(QWidget* parent): Resizer::Resizer(QWidget* parent):
QObject(parent) QObject(parent) {}
{
} bool Resizer::eventFilter(QObject* obj, QEvent* event) {
SHARED_UNUSED(obj);
bool Resizer::eventFilter(QObject* obj, QEvent* event)
{
if (event->type() == QEvent::Resize) { if (event->type() == QEvent::Resize) {
QResizeEvent* ev = static_cast<QResizeEvent*>(event); QResizeEvent* ev = static_cast<QResizeEvent*>(event);
emit resized(ev->oldSize(), ev->size()); emit resized(ev->oldSize(), ev->size());

View File

@ -19,6 +19,8 @@
#include "chat.h" #include "chat.h"
#include "ui_conversation.h" #include "ui_conversation.h"
#include "shared/defines.h"
Chat::Chat(Models::Account* acc, Models::Contact* p_contact, QWidget* parent): Chat::Chat(Models::Account* acc, Models::Contact* p_contact, QWidget* parent):
Conversation(false, acc, p_contact, p_contact->getJid(), "", parent), Conversation(false, acc, p_contact, p_contact->getJid(), "", parent),
contact(p_contact) contact(p_contact)
@ -39,6 +41,7 @@ Chat::~Chat()
{} {}
void Chat::onContactChanged(Models::Item* item, int row, int col) { void Chat::onContactChanged(Models::Item* item, int row, int col) {
SHARED_UNUSED(row);
if (item == contact) { if (item == contact) {
switch (col) { switch (col) {
case 0: case 0:

View File

@ -115,15 +115,14 @@ Conversation::Conversation(bool muc, Models::Account* acc, Models::Element* el,
initializeOverlay(); initializeOverlay();
} }
Conversation::~Conversation() Conversation::~Conversation() {
{
delete contextMenu; delete contextMenu;
element->feed->decrementObservers(); 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 (item == account) {
if (col == 2 && account->getState() == Shared::ConnectionState::connected) { //to request the history when we're back online after reconnect if (col == 2 && account->getState() == Shared::ConnectionState::connected) { //to request the history when we're back online after reconnect
//if (!requestingHistory) { //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<QGridLayout*>(layout()); QGridLayout* gr = static_cast<QGridLayout*>(layout());
QLabel* progressLabel = new QLabel(tr("Drop files here to attach them to your message")); QLabel* progressLabel = new QLabel(tr("Drop files here to attach them to your message"));
gr->addWidget(overlay, 0, 0, 2, 1); gr->addWidget(overlay, 0, 0, 2, 1);
@ -160,26 +158,22 @@ void Conversation::initializeOverlay()
overlay->hide(); overlay->hide();
} }
void Conversation::setName(const QString& name) void Conversation::setName(const QString& name) {
{
m_ui->nameLabel->setText(name); m_ui->nameLabel->setText(name);
setWindowTitle(name); setWindowTitle(name);
} }
QString Conversation::getAccount() const QString Conversation::getAccount() const {
{
return account->getName(); return account->getName();
} }
QString Conversation::getJid() const QString Conversation::getJid() const {
{
return palJid; return palJid;
} }
KeyEnterReceiver::KeyEnterReceiver(QObject* parent): QObject(parent), ownEvent(false) {} 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(); QEvent::Type type = event->type();
if (type == QEvent::KeyPress) { if (type == QEvent::KeyPress) {
QKeyEvent* key = static_cast<QKeyEvent*>(event); QKeyEvent* key = static_cast<QKeyEvent*>(event);
@ -215,18 +209,15 @@ bool Conversation::checkClipboardImage() {
return !QApplication::clipboard()->image().isNull(); return !QApplication::clipboard()->image().isNull();
} }
QString Conversation::getPalResource() const QString Conversation::getPalResource() const {
{
return activePalResource; return activePalResource;
} }
void Conversation::setPalResource(const QString& res) void Conversation::setPalResource(const QString& res) {
{
activePalResource = res; activePalResource = res;
} }
void Conversation::initiateMessageSending() void Conversation::initiateMessageSending() {
{
QString body(m_ui->messageEditor->toPlainText()); QString body(m_ui->messageEditor->toPlainText());
if (body.size() > 0) { if (body.size() > 0) {
@ -245,8 +236,7 @@ void Conversation::initiateMessageSending()
clear(); clear();
} }
void Conversation::initiateMessageSending(const Shared::Message& msg) void Conversation::initiateMessageSending(const Shared::Message& msg) {
{
if (currentAction == CurrentAction::edit) { if (currentAction == CurrentAction::edit) {
emit replaceMessage(currentMessageId, msg); emit replaceMessage(currentMessageId, msg);
currentAction = CurrentAction::none; 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(); QImage image = QApplication::clipboard()->image();
if (image.isNull()) { if (image.isNull())
return; return;
}
QTemporaryFile *tempFile = new QTemporaryFile(QDir::tempPath() + QStringLiteral("/squawk_img_attach_XXXXXX.png"), QApplication::instance()); QTemporaryFile *tempFile = new QTemporaryFile(QDir::tempPath() + QStringLiteral("/squawk_img_attach_XXXXXX.png"), QApplication::instance());
tempFile->open(); tempFile->open();
image.save(tempFile, "PNG"); image.save(tempFile, "PNG");
@ -273,8 +262,7 @@ void Conversation::onImagePasted()
// See Core::NetworkAccess::onUploadFinished. // See Core::NetworkAccess::onUploadFinished.
} }
void Conversation::onAttach() void Conversation::onAttach() {
{
QFileDialog* d = new QFileDialog(this, tr("Chose a file to send")); QFileDialog* d = new QFileDialog(this, tr("Chose a file to send"));
d->setFileMode(QFileDialog::ExistingFile); d->setFileMode(QFileDialog::ExistingFile);
@ -284,37 +272,31 @@ void Conversation::onAttach()
d->show(); d->show();
} }
void Conversation::onFileSelected() void Conversation::onFileSelected() {
{
QFileDialog* d = static_cast<QFileDialog*>(sender()); QFileDialog* d = static_cast<QFileDialog*>(sender());
for (const QString& path : d->selectedFiles())
for (const QString& path : d->selectedFiles()) {
addAttachedFile(path); addAttachedFile(path);
}
d->deleteLater(); d->deleteLater();
} }
void Conversation::setStatus(const QString& status) void Conversation::setStatus(const QString& status) {
{
statusLabel->setText(Shared::processMessageBody(status)); statusLabel->setText(Shared::processMessageBody(status));
} }
Models::Roster::ElId Conversation::getId() const Models::Roster::ElId Conversation::getId() const {
{
return {getAccount(), getJid()}; return {getAccount(), getJid()};
} }
void Conversation::addAttachedFile(const QString& path) void Conversation::addAttachedFile(const QString& path) {
{
QMimeDatabase db; QMimeDatabase db;
QMimeType type = db.mimeTypeForFile(path); QMimeType type = db.mimeTypeForFile(path);
QFileInfo info(path); QFileInfo info(path);
QIcon fileIcon = QIcon::fromTheme(type.iconName()); 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); fileIcon.addFile(QString::fromUtf8(":/images/fallback/dark/big/mail-attachment.svg"), QSize(), QIcon::Normal, QIcon::Off);
}
Badge* badge = new Badge(path, info.fileName(), fileIcon); Badge* badge = new Badge(path, info.fileName(), fileIcon);
connect(badge, &Badge::close, this, &Conversation::onBadgeClose); 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<Badge*, Badge::Comparator>::const_iterator itr = filesToAttach.find(badge); W::Order<Badge*, Badge::Comparator>::const_iterator itr = filesToAttach.find(badge);
if (itr != filesToAttach.end()) { if (itr != filesToAttach.end()) {
filesToAttach.erase(badge); filesToAttach.erase(badge);
if (filesLayout->count() == 1) { if (filesLayout->count() == 1)
filesLayout->setContentsMargins(0, 0, 0, 0); filesLayout->setContentsMargins(0, 0, 0, 0);
}
badge->deleteLater(); badge->deleteLater();
} }
} }
void Conversation::onBadgeClose() void Conversation::onBadgeClose() {
{
Badge* badge = static_cast<Badge*>(sender()); Badge* badge = static_cast<Badge*>(sender());
removeAttachedFile(badge); removeAttachedFile(badge);
} }
void Conversation::clearAttachedFiles() void Conversation::clearAttachedFiles() {
{ for (Badge* badge : filesToAttach)
for (Badge* badge : filesToAttach) {
badge->deleteLater(); badge->deleteLater();
}
filesToAttach.clear(); filesToAttach.clear();
filesLayout->setContentsMargins(0, 0, 0, 0); filesLayout->setContentsMargins(0, 0, 0, 0);
} }
void Conversation::clear() void Conversation::clear() {
{
currentMessageId.clear(); currentMessageId.clear();
currentAction = CurrentAction::none; currentAction = CurrentAction::none;
m_ui->currentActionBadge->setVisible(false); m_ui->currentActionBadge->setVisible(false);
@ -367,8 +345,7 @@ void Conversation::clear()
m_ui->messageEditor->clear(); m_ui->messageEditor->clear();
} }
void Conversation::setAvatar(const QString& path) void Conversation::setAvatar(const QString& path) {
{
QPixmap pixmap; QPixmap pixmap;
if (path.size() == 0) { if (path.size() == 0) {
pixmap = Shared::icon("user", true).pixmap(avatarSize); pixmap = Shared::icon("user", true).pixmap(avatarSize);
@ -390,13 +367,11 @@ void Conversation::setAvatar(const QString& path)
m_ui->avatar->setPixmap(result); m_ui->avatar->setPixmap(result);
} }
void Conversation::onTextEditDocSizeChanged(const QSizeF& size) void Conversation::onTextEditDocSizeChanged(const QSizeF& size) {
{
m_ui->messageEditor->setMaximumHeight(int(size.height())); 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); 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(); overlay->hide();
} }
void Conversation::dropEvent(QDropEvent* event) void Conversation::dropEvent(QDropEvent* event) {
{
bool accept = false; bool accept = false;
if (event->mimeData()->hasUrls()) { if (event->mimeData()->hasUrls()) {
QList<QUrl> list = event->mimeData()->urls(); QList<QUrl> list = event->mimeData()->urls();
@ -441,14 +415,13 @@ void Conversation::dropEvent(QDropEvent* event)
} }
} }
} }
if (accept) { if (accept)
event->acceptProposedAction(); event->acceptProposedAction();
}
overlay->hide(); overlay->hide();
} }
Shared::Message Conversation::createMessage() const Shared::Message Conversation::createMessage() const {
{
Shared::Message msg; Shared::Message msg;
msg.setOutgoing(true); msg.setOutgoing(true);
msg.generateRandomId(); msg.generateRandomId();
@ -457,23 +430,20 @@ Shared::Message Conversation::createMessage() const
return msg; return msg;
} }
void Conversation::onFeedMessage(const Shared::Message& msg) void Conversation::onFeedMessage(const Shared::Message& msg) {
{
this->onMessage(msg); this->onMessage(msg);
} }
void Conversation::onMessage(const Shared::Message& msg) void Conversation::onMessage(const Shared::Message& msg) {
{
if (!msg.getForwarded()) { if (!msg.getForwarded()) {
QApplication::alert(this); QApplication::alert(this);
if (window()->windowState().testFlag(Qt::WindowMinimized)) { if (window()->windowState().testFlag(Qt::WindowMinimized))
emit notifyableMessage(getAccount(), msg); emit notifyableMessage(getAccount(), msg);
}
} }
} }
void Conversation::positionShadow() void Conversation::positionShadow() {
{
int w = width(); int w = width();
int h = feed->height(); int h = feed->height();
@ -482,8 +452,7 @@ void Conversation::positionShadow()
shadow.raise(); shadow.raise();
} }
void Conversation::onFeedContext(const QPoint& pos) void Conversation::onFeedContext(const QPoint& pos) {
{
QModelIndex index = feed->indexAt(pos); QModelIndex index = feed->indexAt(pos);
if (index.isValid()) { if (index.isValid()) {
Shared::Message* item = static_cast<Shared::Message*>(index.internalPointer()); Shared::Message* item = static_cast<Shared::Message*>(index.internalPointer());
@ -542,14 +511,12 @@ void Conversation::onFeedContext(const QPoint& pos)
connect(edit, &QAction::triggered, this, std::bind(&Conversation::onMessageEditRequested, this, id)); connect(edit, &QAction::triggered, this, std::bind(&Conversation::onMessageEditRequested, this, id));
} }
if (showMenu) { if (showMenu)
contextMenu->popup(feed->viewport()->mapToGlobal(pos)); contextMenu->popup(feed->viewport()->mapToGlobal(pos));
} }
}
} }
void Conversation::onMessageEditorContext(const QPoint& pos) void Conversation::onMessageEditorContext(const QPoint& pos) {
{
pasteImageAction->setEnabled(Conversation::checkClipboardImage()); pasteImageAction->setEnabled(Conversation::checkClipboardImage());
QMenu *editorMenu = m_ui->messageEditor->createStandardContextMenu(); QMenu *editorMenu = m_ui->messageEditor->createStandardContextMenu();
@ -559,8 +526,7 @@ void Conversation::onMessageEditorContext(const QPoint& pos)
editorMenu->exec(this->m_ui->messageEditor->mapToGlobal(pos)); editorMenu->exec(this->m_ui->messageEditor->mapToGlobal(pos));
} }
void Conversation::onMessageEditRequested(const QString& id) void Conversation::onMessageEditRequested(const QString& id) {
{
clear(); clear();
try { try {
@ -582,8 +548,7 @@ void Conversation::onMessageEditRequested(const QString& id)
} }
} }
void Conversation::showEvent(QShowEvent* event) void Conversation::showEvent(QShowEvent* event) {
{
QWidget::showEvent(event); QWidget::showEvent(event);
emit shown(); emit shown();

View File

@ -34,6 +34,7 @@
#include "shared/icons.h" #include "shared/icons.h"
#include "shared/utils.h" #include "shared/utils.h"
#include "shared/pathcheck.h" #include "shared/pathcheck.h"
#include "shared/defines.h"
#include "ui/models/account.h" #include "ui/models/account.h"
#include "ui/models/roster.h" #include "ui/models/roster.h"
@ -159,8 +160,6 @@ private:
static QPainterPath* avatarMask; static QPainterPath* avatarMask;
static QPixmap* avatarPixmap; static QPixmap* avatarPixmap;
static QPainter* avatarPainter; static QPainter* avatarPainter;
}; };
#endif // CONVERSATION_H #endif // CONVERSATION_H

View File

@ -79,13 +79,12 @@ QModelIndex FeedView::indexAt(const QPoint& point) const {
for (std::deque<Hint>::size_type i = 0; i < hints.size(); ++i) { for (std::deque<Hint>::size_type i = 0; i < hints.size(); ++i) {
const Hint& hint = hints[i]; const Hint& hint = hints[i];
if (y <= hint.offset + hint.height) { if (y <= hint.offset + hint.height) {
if (y > hint.offset) { if (y > hint.offset)
return model()->index(i, 0, rootIndex()); return model()->index(i, 0, rootIndex());
} else { else
break; break;
} }
} }
}
return QModelIndex(); return QModelIndex();
} }
@ -156,13 +155,11 @@ void FeedView::updateGeometries() {
vo = 0; vo = 0;
} else { } else {
int verticalMargin = 0; int verticalMargin = 0;
if (st->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents)) { if (st->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents))
frameAroundContents = st->pixelMetric(QStyle::PM_DefaultFrameWidth) * 2; frameAroundContents = st->pixelMetric(QStyle::PM_DefaultFrameWidth) * 2;
}
if (verticalScrollBarPolicy() == Qt::ScrollBarAsNeeded) { if (verticalScrollBarPolicy() == Qt::ScrollBarAsNeeded)
verticalMargin = verticalScrollBarExtent + frameAroundContents; verticalMargin = verticalScrollBarExtent + frameAroundContents;
}
layoutBounds.rwidth() -= verticalMargin; layoutBounds.rwidth() -= verticalMargin;
@ -176,22 +173,20 @@ void FeedView::updateGeometries() {
QModelIndex index = m->index(i, 0, rootIndex()); QModelIndex index = m->index(i, 0, rootIndex());
QDateTime currentDate = index.data(Models::MessageFeed::Date).toDateTime(); QDateTime currentDate = index.data(Models::MessageFeed::Date).toDateTime();
if (i > 0) { if (i > 0) {
if (currentDate.daysTo(lastDate) > 0) { if (currentDate.daysTo(lastDate) > 0)
previousOffset += dividerMetrics.height() + dateDeviderMargin * 2; previousOffset += dividerMetrics.height() + dateDeviderMargin * 2;
} else { else
previousOffset += elementMargin; previousOffset += elementMargin;
} }
}
lastDate = currentDate; lastDate = currentDate;
QSize messageSize = itemDelegate(index)->sizeHint(option, index); QSize messageSize = itemDelegate(index)->sizeHint(option, index);
uint32_t offsetX(0); uint32_t offsetX(0);
if (specialDelegate) { 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; offsetX = layoutBounds.width() - messageSize.width() - MessageDelegate::avatarHeight - MessageDelegate::margin * 2;
} else { else
offsetX = MessageDelegate::avatarHeight + MessageDelegate::margin * 2; offsetX = MessageDelegate::avatarHeight + MessageDelegate::margin * 2;
} }
}
hints.emplace_back(Hint({ hints.emplace_back(Hint({
false, false,
@ -204,9 +199,9 @@ void FeedView::updateGeometries() {
} }
int totalHeight = previousOffset - layoutBounds.height() + dividerMetrics.height() + dateDeviderMargin * 2; int totalHeight = previousOffset - layoutBounds.height() + dividerMetrics.height() + dateDeviderMargin * 2;
if (modelState != Models::MessageFeed::complete) { if (modelState != Models::MessageFeed::complete)
totalHeight += progressSize; totalHeight += progressSize;
}
vo = qMax(qMin(vo, totalHeight), 0); vo = qMax(qMin(vo, totalHeight), 0);
bar->setRange(0, totalHeight); bar->setRange(0, totalHeight);
bar->setPageStep(layoutBounds.height()); bar->setPageStep(layoutBounds.height());
@ -219,7 +214,6 @@ void FeedView::updateGeometries() {
clearWidgetsMode = true; clearWidgetsMode = true;
} }
QAbstractItemView::updateGeometries(); QAbstractItemView::updateGeometries();
} }
@ -230,27 +224,24 @@ bool FeedView::tryToCalculateGeometriesWithNoScrollbars(const QStyleOptionViewIt
QModelIndex index = m->index(i, 0, rootIndex()); QModelIndex index = m->index(i, 0, rootIndex());
QDateTime currentDate = index.data(Models::MessageFeed::Date).toDateTime(); QDateTime currentDate = index.data(Models::MessageFeed::Date).toDateTime();
if (i > 0) { if (i > 0) {
if (currentDate.daysTo(lastDate) > 0) { if (currentDate.daysTo(lastDate) > 0)
previousOffset += dateDeviderMargin * 2 + dividerMetrics.height(); previousOffset += dateDeviderMargin * 2 + dividerMetrics.height();
} else { else
previousOffset += elementMargin; previousOffset += elementMargin;
} }
}
lastDate = currentDate; lastDate = currentDate;
QSize messageSize = itemDelegate(index)->sizeHint(option, index); QSize messageSize = itemDelegate(index)->sizeHint(option, index);
if (previousOffset + messageSize.height() + elementMargin > totalHeight) { if (previousOffset + messageSize.height() + elementMargin > totalHeight)
return false; return false;
}
uint32_t offsetX(0); uint32_t offsetX(0);
if (specialDelegate) { 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; offsetX = option.rect.width() - messageSize.width() - MessageDelegate::avatarHeight - MessageDelegate::margin * 2;
} else { else
offsetX = MessageDelegate::avatarHeight + MessageDelegate::margin * 2; offsetX = MessageDelegate::avatarHeight + MessageDelegate::margin * 2;
} }
}
hints.emplace_back(Hint({ hints.emplace_back(Hint({
false, false,
previousOffset, previousOffset,
@ -262,9 +253,8 @@ bool FeedView::tryToCalculateGeometriesWithNoScrollbars(const QStyleOptionViewIt
} }
previousOffset += dateDeviderMargin * 2 + dividerMetrics.height(); previousOffset += dateDeviderMargin * 2 + dividerMetrics.height();
if (previousOffset > totalHeight) { if (previousOffset > totalHeight)
return false; return false;
}
return true; return true;
} }
@ -284,13 +274,12 @@ void FeedView::paintEvent(QPaintEvent* event) {
const Hint& hint = hints[i]; const Hint& hint = hints[i];
int32_t relativeY1 = vph - hint.offset - hint.height; int32_t relativeY1 = vph - hint.offset - hint.height;
if (!inZone) { if (!inZone) {
if (y2 > relativeY1) { if (y2 > relativeY1)
inZone = true; inZone = true;
} }
} if (inZone)
if (inZone) {
toRener.emplace_back(m->index(i, 0, rootIndex())); toRener.emplace_back(m->index(i, 0, rootIndex()));
}
if (y1 > relativeY1) { if (y1 > relativeY1) {
inZone = false; inZone = false;
break; break;
@ -304,10 +293,9 @@ void FeedView::paintEvent(QPaintEvent* event) {
if (specialDelegate) { if (specialDelegate) {
MessageDelegate* del = static_cast<MessageDelegate*>(itemDelegate()); MessageDelegate* del = static_cast<MessageDelegate*>(itemDelegate());
if (clearWidgetsMode) { if (clearWidgetsMode)
del->beginClearWidgets(); del->beginClearWidgets();
} }
}
QDateTime lastDate; QDateTime lastDate;
bool first = true; bool first = true;
@ -319,10 +307,9 @@ void FeedView::paintEvent(QPaintEvent* event) {
int ind = index.row() - 1; int ind = index.row() - 1;
if (ind > 0) { if (ind > 0) {
QDateTime underDate = m->index(ind, 0, rootIndex()).data(Models::MessageFeed::Date).toDateTime(); 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); drawDateDevider(option.rect.bottom(), underDate, painter);
} }
}
first = false; first = false;
} }
QRect stripe = option.rect; QRect stripe = option.rect;
@ -332,14 +319,13 @@ void FeedView::paintEvent(QPaintEvent* event) {
option.state.setFlag(QStyle::State_MouseOver, mouseOver); option.state.setFlag(QStyle::State_MouseOver, mouseOver);
itemDelegate(index)->paint(&painter, option, index); 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); drawDateDevider(option.rect.bottom(), lastDate, painter);
}
lastDate = currentDate; 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); drawDateDevider(option.rect.top() - dateDeviderMargin * 2 - dividerMetrics.height(), lastDate, painter);
}
if (clearWidgetsMode && specialDelegate) { if (clearWidgetsMode && specialDelegate) {
MessageDelegate* del = static_cast<MessageDelegate*>(itemDelegate()); MessageDelegate* del = static_cast<MessageDelegate*>(itemDelegate());
@ -362,13 +348,11 @@ void FeedView::verticalScrollbarValueChanged(int value) {
positionProgress(); positionProgress();
if (specialDelegate) { if (specialDelegate)
clearWidgetsMode = true; clearWidgetsMode = true;
}
if (modelState == Models::MessageFeed::incomplete && value < progressSize) { if (modelState == Models::MessageFeed::incomplete && value < progressSize)
model()->fetchMore(rootIndex()); model()->fetchMore(rootIndex());
}
QAbstractItemView::verticalScrollbarValueChanged(vo); QAbstractItemView::verticalScrollbarValueChanged(vo);
} }
@ -391,17 +375,15 @@ void FeedView::setAnchorHovered(Shared::Hover type) {
} }
void FeedView::mouseMoveEvent(QMouseEvent* event) { void FeedView::mouseMoveEvent(QMouseEvent* event) {
if (!isVisible()) { if (!isVisible())
return; return;
}
dragEndPoint = event->localPos().toPoint(); dragEndPoint = event->localPos().toPoint();
if (mousePressed) { if (mousePressed) {
QPoint distance = dragStartPoint - dragEndPoint; QPoint distance = dragStartPoint - dragEndPoint;
if (distance.manhattanLength() > 5) { if (distance.manhattanLength() > 5)
dragging = true; dragging = true;
} }
}
QAbstractItemView::mouseMoveEvent(event); QAbstractItemView::mouseMoveEvent(event);
@ -423,11 +405,10 @@ void FeedView::mouseMoveEvent(QMouseEvent* event) {
QModelIndex index = indexAt(dragEndPoint); QModelIndex index = indexAt(dragEndPoint);
if (index.isValid()) { if (index.isValid()) {
QRect rect = visualRect(index); QRect rect = visualRect(index);
if (rect.contains(dragEndPoint)) { if (rect.contains(dragEndPoint))
setAnchorHovered(del->hoverType(dragEndPoint, index, rect)); setAnchorHovered(del->hoverType(dragEndPoint, index, rect));
} else { else
setAnchorHovered(Shared::Hover::nothing); setAnchorHovered(Shared::Hover::nothing);
}
} else { } else {
setAnchorHovered(Shared::Hover::nothing); setAnchorHovered(Shared::Hover::nothing);
} }
@ -447,12 +428,11 @@ void FeedView::mousePressEvent(QMouseEvent* event) {
if (lastSelectedId.size()) { if (lastSelectedId.size()) {
Models::MessageFeed* feed = static_cast<Models::MessageFeed*>(model()); Models::MessageFeed* feed = static_cast<Models::MessageFeed*>(model());
QModelIndex index = feed->modelIndexById(lastSelectedId); QModelIndex index = feed->modelIndexById(lastSelectedId);
if (index.isValid()) { if (index.isValid())
setDirtyRegion(visualRect(index)); setDirtyRegion(visualRect(index));
} }
} }
} }
}
} }
void FeedView::mouseDoubleClickEvent(QMouseEvent* event) { void FeedView::mouseDoubleClickEvent(QMouseEvent* event) {
@ -467,21 +447,19 @@ void FeedView::mouseDoubleClickEvent(QMouseEvent* event) {
if (lastSelectedId.size()) { if (lastSelectedId.size()) {
Models::MessageFeed* feed = static_cast<Models::MessageFeed*>(model()); Models::MessageFeed* feed = static_cast<Models::MessageFeed*>(model());
QModelIndex index = feed->modelIndexById(lastSelectedId); QModelIndex index = feed->modelIndexById(lastSelectedId);
if (index.isValid()) { if (index.isValid())
setDirtyRegion(visualRect(index)); setDirtyRegion(visualRect(index));
} }
}
QModelIndex index = indexAt(dragStartPoint); QModelIndex index = indexAt(dragStartPoint);
QRect rect = visualRect(index); QRect rect = visualRect(index);
if (rect.contains(dragStartPoint)) { if (rect.contains(dragStartPoint)) {
selectedText = del->leftDoubleClick(dragStartPoint, index, rect); selectedText = del->leftDoubleClick(dragStartPoint, index, rect);
if (selectedText.size() > 0) { if (selectedText.size() > 0)
setDirtyRegion(rect); setDirtyRegion(rect);
} }
} }
} }
}
} }
void FeedView::mouseReleaseEvent(QMouseEvent* event) { void FeedView::mouseReleaseEvent(QMouseEvent* event) {
@ -494,11 +472,10 @@ void FeedView::mouseReleaseEvent(QMouseEvent* event) {
if (index.isValid()) { if (index.isValid()) {
QRect rect = visualRect(index); QRect rect = visualRect(index);
MessageDelegate* del = static_cast<MessageDelegate*>(itemDelegate()); MessageDelegate* del = static_cast<MessageDelegate*>(itemDelegate());
if (rect.contains(point)) { if (rect.contains(point))
del->leftClick(point, index, rect); del->leftClick(point, index, rect);
} }
} }
}
dragging = false; dragging = false;
mousePressed = false; mousePressed = false;
} }

View File

@ -29,6 +29,8 @@
#include "messagedelegate.h" #include "messagedelegate.h"
#include "messagefeed.h" #include "messagefeed.h"
#include "shared/defines.h"
constexpr int textMargin = 2; constexpr int textMargin = 2;
constexpr int statusIconSize = 16; constexpr int statusIconSize = 16;
@ -70,27 +72,21 @@ MessageDelegate::MessageDelegate(QObject* parent):
barHeight = bar.sizeHint().height(); barHeight = bar.sizeHint().height();
} }
MessageDelegate::~MessageDelegate() MessageDelegate::~MessageDelegate() {
{ for (const std::pair<const QString, FeedButton*>& pair: *buttons)
for (const std::pair<const QString, FeedButton*>& pair: *buttons){
delete pair.second; delete pair.second;
}
for (const std::pair<const QString, QProgressBar*>& pair: *bars){ for (const std::pair<const QString, QProgressBar*>& pair: *bars)
delete pair.second; delete pair.second;
}
for (const std::pair<const QString, QLabel*>& pair: *statusIcons){ for (const std::pair<const QString, QLabel*>& pair: *statusIcons)
delete pair.second; delete pair.second;
}
for (const std::pair<const QString, QLabel*>& pair: *pencilIcons){ for (const std::pair<const QString, QLabel*>& pair: *pencilIcons)
delete pair.second; delete pair.second;
}
for (const std::pair<const QString, Preview*>& pair: *previews){ for (const std::pair<const QString, Preview*>& pair: *previews)
delete pair.second; delete pair.second;
}
delete statusIcons; delete statusIcons;
delete pencilIcons; delete pencilIcons;
@ -101,29 +97,26 @@ MessageDelegate::~MessageDelegate()
delete bodyRenderer; 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); QVariant vi = index.data(Models::MessageFeed::Bulk);
if (!vi.isValid()) { if (!vi.isValid())
return; return;
}
Models::FeedItem data = qvariant_cast<Models::FeedItem>(vi); Models::FeedItem data = qvariant_cast<Models::FeedItem>(vi);
painter->save(); painter->save();
painter->setRenderHint(QPainter::Antialiasing, true); painter->setRenderHint(QPainter::Antialiasing, true);
paintBubble(data, painter, option); paintBubble(data, painter, option);
bool ntds = needToDrawSender(index, data); bool ntds = needToDrawSender(index, data);
if (ntds || option.rect.y() < 1) { if (ntds || option.rect.y() < 1)
paintAvatar(data, index, option, painter); paintAvatar(data, index, option, painter);
}
QStyleOptionViewItem opt = option; QStyleOptionViewItem opt = option;
opt.rect = option.rect.adjusted(bubbleMargin, bubbleMargin, -bubbleMargin, -bubbleMargin / 2); opt.rect = option.rect.adjusted(bubbleMargin, bubbleMargin, -bubbleMargin, -bubbleMargin / 2);
if (!data.sentByMe) { if (!data.sentByMe)
opt.displayAlignment = Qt::AlignLeft | Qt::AlignTop; opt.displayAlignment = Qt::AlignLeft | Qt::AlignTop;
} else { else
opt.displayAlignment = Qt::AlignRight | Qt::AlignTop; opt.displayAlignment = Qt::AlignRight | Qt::AlignTop;
}
QRect rect; QRect rect;
if (ntds) { if (ntds) {
@ -189,11 +182,11 @@ void MessageDelegate::paint(QPainter* painter, const QStyleOptionViewItem& optio
QLabel* pencilIcon = getPencilIcon(data); QLabel* pencilIcon = getPencilIcon(data);
pencilIcon->setParent(vp); pencilIcon->setParent(vp);
if (data.sentByMe) { if (data.sentByMe)
pencilIcon->move(opt.rect.left() + statusIconSize + margin, currentY); pencilIcon->move(opt.rect.left() + statusIconSize + margin, currentY);
} else { else
pencilIcon->move(opt.rect.right() - statusIconSize - margin, currentY); pencilIcon->move(opt.rect.right() - statusIconSize - margin, currentY);
}
pencilIcon->show(); pencilIcon->show();
} else { } else {
std::map<QString, QLabel*>::const_iterator itr = pencilIcons->find(data.id); std::map<QString, QLabel*>::const_iterator itr = pencilIcons->find(data.id);
@ -205,27 +198,24 @@ void MessageDelegate::paint(QPainter* painter, const QStyleOptionViewItem& optio
painter->restore(); painter->restore();
if (clearingWidgets) { if (clearingWidgets)
idsToKeep->insert(data.id); 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(); painter->save();
if (data.sentByMe) { if (data.sentByMe)
painter->setBrush(option.palette.brush(QPalette::Inactive, QPalette::Highlight)); painter->setBrush(option.palette.brush(QPalette::Inactive, QPalette::Highlight));
} else { else
painter->setBrush(option.palette.brush(QPalette::Window)); painter->setBrush(option.palette.brush(QPalette::Window));
}
painter->setPen(Qt::NoPen); painter->setPen(Qt::NoPen);
painter->drawRoundedRect(option.rect, bubbleBorderRadius, bubbleBorderRadius); painter->drawRoundedRect(option.rect, bubbleBorderRadius, bubbleBorderRadius);
painter->restore(); 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 currentRow = index.row();
int y = option.rect.y(); int y = option.rect.y();
bool firstAttempt = true; bool firstAttempt = true;
@ -255,11 +245,10 @@ void MessageDelegate::paintAvatar(const Models::FeedItem& data, const QModelInde
QPainterPath path; QPainterPath path;
int ax; int ax;
if (data.sentByMe) { if (data.sentByMe)
ax = option.rect.x() + option.rect.width() + margin; ax = option.rect.x() + option.rect.width() + margin;
} else { else
ax = margin; ax = margin;
}
path.addEllipse(ax, y + margin / 2, avatarHeight, avatarHeight); path.addEllipse(ax, y + margin / 2, avatarHeight, avatarHeight);
painter->save(); painter->save();
@ -268,8 +257,7 @@ void MessageDelegate::paintAvatar(const Models::FeedItem& data, const QModelInde
painter->restore(); 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); 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); QRect messageRect = option.rect.adjusted(bubbleMargin, margin / 2 + bubbleMargin, -(avatarHeight + 3 * margin + bubbleMargin), -(margin + bubbleMargin) / 2);
QStyleOptionViewItem opt = option; QStyleOptionViewItem opt = option;
opt.rect = messageRect; opt.rect = messageRect;
@ -360,12 +347,10 @@ QSize MessageDelegate::sizeHint(const QStyleOptionViewItem& option, const QModel
return messageSize; 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); 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); localHint.adjust(0, nickMetrics.lineSpacing() + textMargin, 0, 0);
}
int attachHeight = 0; int attachHeight = 0;
switch (data.attach.state) { switch (data.attach.state) {
@ -405,8 +390,7 @@ QRect MessageDelegate::getHoveredMessageBodyRect(const QModelIndex& index, const
return localHint; 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); QVariant vi = index.data(Models::MessageFeed::Bulk);
Models::FeedItem data = qvariant_cast<Models::FeedItem>(vi); Models::FeedItem data = qvariant_cast<Models::FeedItem>(vi);
if (data.text.size() > 0) { if (data.text.size() > 0) {
@ -425,16 +409,13 @@ QString MessageDelegate::getAnchor(const QPoint& point, const QModelIndex& index
return QString(); 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); QString anchor = getAnchor(point, index, sizeHint);
if (anchor.size() > 0) { if (anchor.size() > 0)
emit openLink(anchor); 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); QVariant vi = index.data(Models::MessageFeed::Bulk);
Models::FeedItem data = qvariant_cast<Models::FeedItem>(vi); Models::FeedItem data = qvariant_cast<Models::FeedItem>(vi);
if (data.text.size() > 0) { if (data.text.size() > 0) {
@ -466,8 +447,7 @@ QString MessageDelegate::leftDoubleClick(const QPoint& point, const QModelIndex&
return ""; 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); QVariant vi = index.data(Models::MessageFeed::Bulk);
Models::FeedItem data = qvariant_cast<Models::FeedItem>(vi); Models::FeedItem data = qvariant_cast<Models::FeedItem>(vi);
if (data.text.size() > 0) { if (data.text.size() > 0) {
@ -486,17 +466,15 @@ Shared::Hover MessageDelegate::hoverType(const QPoint& point, const QModelIndex&
return Shared::Hover::anchor; return Shared::Hover::anchor;
} else { } else {
int position = lay->hitTest(translated, Qt::HitTestAccuracy::ExactHit); int position = lay->hitTest(translated, Qt::HitTestAccuracy::ExactHit);
if (position != -1) { if (position != -1)
return Shared::Hover::text; return Shared::Hover::text;
} }
} }
} }
}
return Shared::Hover::nothing; 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); QVariant vi = index.data(Models::MessageFeed::Bulk);
Models::FeedItem data = qvariant_cast<Models::FeedItem>(vi); Models::FeedItem data = qvariant_cast<Models::FeedItem>(vi);
if (data.text.size() > 0) { if (data.text.size() > 0) {
@ -529,30 +507,24 @@ QString MessageDelegate::mouseDrag(const QPoint& start, const QPoint& end, const
return ""; return "";
} }
QString MessageDelegate::clearSelection() QString MessageDelegate::clearSelection() {
{
QString lastSelectedId = currentId; QString lastSelectedId = currentId;
currentId = ""; currentId = "";
selection = std::pair(0, 0); selection = std::pair(0, 0);
return lastSelectedId; 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(); //qDebug() << event->type();
return QStyledItemDelegate::editorEvent(event, model, option, index); 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; QPoint start;
if (sentByMe) { if (sentByMe)
start = {option.rect.x() + option.rect.width() - btn->width(), option.rect.top()}; start = {option.rect.x() + option.rect.width() - btn->width(), option.rect.top()};
} else { else
start = option.rect.topLeft(); start = option.rect.topLeft();
}
QWidget* vp = static_cast<QWidget*>(painter->device()); QWidget* vp = static_cast<QWidget*>(painter->device());
btn->setParent(vp); btn->setParent(vp);
@ -563,8 +535,7 @@ int MessageDelegate::paintButton(QPushButton* btn, QPainter* painter, bool sentB
return btn->width(); 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); painter->setFont(dateFont);
QColor q = painter->pen().color(); QColor q = painter->pen().color();
q.setAlpha(180); q.setAlpha(180);
@ -576,8 +547,8 @@ int MessageDelegate::paintComment(const Models::FeedItem& data, QPainter* painte
return rect.width(); 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(); QPoint start = option.rect.topLeft();
bar->resize(option.rect.width(), barHeight); bar->resize(option.rect.width(), barHeight);
@ -589,8 +560,7 @@ int MessageDelegate::paintBar(QProgressBar* bar, QPainter* painter, bool sentByM
return option.rect.width(); 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; Preview* preview = 0;
std::map<QString, Preview*>::iterator itr = previews->find(data.id); std::map<QString, Preview*>::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)); 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 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()); QSize pSize(preview->size());
option.rect.adjust(0, pSize.height() + textMargin, 0, 0); option.rect.adjust(0, pSize.height() + textMargin, 0, 0);
return pSize.width(); return pSize.width();
} }
QPushButton * MessageDelegate::getButton(const Models::FeedItem& data) const QPushButton * MessageDelegate::getButton(const Models::FeedItem& data) const {
{
std::map<QString, FeedButton*>::const_iterator itr = buttons->find(data.id); std::map<QString, FeedButton*>::const_iterator itr = buttons->find(data.id);
FeedButton* result = 0; FeedButton* result = 0;
if (itr != buttons->end()) { if (itr != buttons->end()) {
@ -640,8 +608,7 @@ QPushButton * MessageDelegate::getButton(const Models::FeedItem& data) const
return result; return result;
} }
QProgressBar * MessageDelegate::getBar(const Models::FeedItem& data) const QProgressBar * MessageDelegate::getBar(const Models::FeedItem& data) const {
{
std::map<QString, QProgressBar*>::const_iterator barItr = bars->find(data.id); std::map<QString, QProgressBar*>::const_iterator barItr = bars->find(data.id);
QProgressBar* result = 0; QProgressBar* result = 0;
if (barItr != bars->end()) { if (barItr != bars->end()) {
@ -665,8 +632,7 @@ QProgressBar * MessageDelegate::getBar(const Models::FeedItem& data) const
return result; return result;
} }
QLabel * MessageDelegate::getStatusIcon(const Models::FeedItem& data) const QLabel * MessageDelegate::getStatusIcon(const Models::FeedItem& data) const {
{
std::map<QString, QLabel*>::const_iterator itr = statusIcons->find(data.id); std::map<QString, QLabel*>::const_iterator itr = statusIcons->find(data.id);
QLabel* result = 0; QLabel* result = 0;
@ -680,10 +646,9 @@ QLabel * MessageDelegate::getStatusIcon(const Models::FeedItem& data) const
QIcon q(Shared::icon(Shared::messageStateThemeIcons[static_cast<uint8_t>(data.state)])); QIcon q(Shared::icon(Shared::messageStateThemeIcons[static_cast<uint8_t>(data.state)]));
QString tt = Shared::Global::getName(data.state); QString tt = Shared::Global::getName(data.state);
if (data.state == Shared::Message::State::error) { if (data.state == Shared::Message::State::error) {
if (data.error > 0) { if (data.error > 0)
tt += ": " + data.error; tt += ": " + data.error;
} }
}
if (result->toolTip() != tt) { //If i just assign pixmap every time unconditionally if (result->toolTip() != tt) { //If i just assign pixmap every time unconditionally
result->setPixmap(q.pixmap(statusIconSize)); //it invokes an infinite cycle of repaint result->setPixmap(q.pixmap(statusIconSize)); //it invokes an infinite cycle of repaint
result->setToolTip(tt); //may be it's better to subclass and store last condition in int? result->setToolTip(tt); //may be it's better to subclass and store last condition in int?
@ -692,8 +657,7 @@ QLabel * MessageDelegate::getStatusIcon(const Models::FeedItem& data) const
return result; return result;
} }
QLabel * MessageDelegate::getPencilIcon(const Models::FeedItem& data) const QLabel * MessageDelegate::getPencilIcon(const Models::FeedItem& data) const {
{
std::map<QString, QLabel*>::const_iterator itr = pencilIcons->find(data.id); std::map<QString, QLabel*>::const_iterator itr = pencilIcons->find(data.id);
QLabel* result = 0; QLabel* result = 0;
@ -755,14 +719,12 @@ int MessageDelegate::paintBody(const Models::FeedItem& data, QPainter* painter,
return 0; return 0;
} }
void MessageDelegate::beginClearWidgets() void MessageDelegate::beginClearWidgets() {
{
idsToKeep->clear(); idsToKeep->clear();
clearingWidgets = true; clearingWidgets = true;
} }
void MessageDelegate::endClearWidgets() void MessageDelegate::endClearWidgets() {
{
if (clearingWidgets) { if (clearingWidgets) {
removeElements(buttons, idsToKeep); removeElements(buttons, idsToKeep);
removeElements(bars, idsToKeep); removeElements(bars, idsToKeep);
@ -775,14 +737,12 @@ void MessageDelegate::endClearWidgets()
} }
} }
void MessageDelegate::onButtonPushed() const void MessageDelegate::onButtonPushed() const {
{
FeedButton* btn = static_cast<FeedButton*>(sender()); FeedButton* btn = static_cast<FeedButton*>(sender());
emit buttonPushed(btn->messageId); emit buttonPushed(btn->messageId);
} }
void MessageDelegate::clearHelperWidget(const Models::FeedItem& data) const void MessageDelegate::clearHelperWidget(const Models::FeedItem& data) const {
{
std::map<QString, FeedButton*>::const_iterator itr = buttons->find(data.id); std::map<QString, FeedButton*>::const_iterator itr = buttons->find(data.id);
if (itr != buttons->end()) { if (itr != buttons->end()) {
delete itr->second; delete itr->second;

View File

@ -30,6 +30,8 @@
#include <QProgressBar> #include <QProgressBar>
#include <QLabel> #include <QLabel>
#include <QTextDocument> #include <QTextDocument>
#include <QString>
#include <QPainter>
#include "shared/icons.h" #include "shared/icons.h"
#include "shared/global.h" #include "shared/global.h"

View File

@ -20,6 +20,7 @@
#include <ui/models/element.h> #include <ui/models/element.h>
#include <ui/models/room.h> #include <ui/models/room.h>
#include <shared/defines.h>
#include <QDebug> #include <QDebug>
@ -228,24 +229,20 @@ std::set<Models::MessageFeed::MessageRoles> Models::MessageFeed::detectChanges(c
return roles; return roles;
} }
void Models::MessageFeed::removeMessage(const QString& id) void Models::MessageFeed::removeMessage(const QString& id) {
{
//todo; //todo;
} }
Shared::Message Models::MessageFeed::getMessage(const QString& id) Shared::Message Models::MessageFeed::getMessage(const QString& id) {
{
StorageById::iterator itr = indexById.find(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()); throw NotFound(id.toStdString(), rosterItem->getJid().toStdString(), rosterItem->getAccountName().toStdString());
}
return **itr; 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(); int i = index.row();
QVariant answer; QVariant answer;
@ -266,12 +263,11 @@ QVariant Models::MessageFeed::data(const QModelIndex& index, int role) const
if (sentByMe(*msg)) { if (sentByMe(*msg)) {
answer = rosterItem->getAccountName(); answer = rosterItem->getAccountName();
} else { } else {
if (rosterItem->isRoom()) { if (rosterItem->isRoom())
answer = msg->getFromResource(); answer = msg->getFromResource();
} else { else
answer = rosterItem->getDisplayedName(); answer = rosterItem->getDisplayedName();
} }
}
break; break;
case Date: case Date:
answer = msg->getTime(); answer = msg->getTime();
@ -290,20 +286,18 @@ QVariant Models::MessageFeed::data(const QModelIndex& index, int role) const
if (sentByMe(*msg)) { if (sentByMe(*msg)) {
path = rosterItem->getAccountAvatarPath(); path = rosterItem->getAccountAvatarPath();
} else if (!rosterItem->isRoom()) { } else if (!rosterItem->isRoom()) {
if (rosterItem->getAvatarState() != Shared::Avatar::empty) { if (rosterItem->getAvatarState() != Shared::Avatar::empty)
path = rosterItem->getAvatarPath(); path = rosterItem->getAvatarPath();
}
} else { } else {
const Room* room = static_cast<const Room*>(rosterItem); const Room* room = static_cast<const Room*>(rosterItem);
path = room->getParticipantIconPath(msg->getFromResource()); path = room->getParticipantIconPath(msg->getFromResource());
} }
if (path.size() == 0) { if (path.size() == 0)
answer = Shared::iconPath("user", true); answer = Shared::iconPath("user", true);
} else { else
answer = path; answer = path;
} }
}
break; break;
case Attach: case Attach:
answer.setValue(fillAttach(*msg)); answer.setValue(fillAttach(*msg));
@ -342,15 +336,14 @@ QVariant Models::MessageFeed::data(const QModelIndex& index, int role) const
item.avatar = room->getParticipantIconPath(msg->getFromResource()); item.avatar = room->getParticipantIconPath(msg->getFromResource());
} else { } else {
item.sender = rosterItem->getDisplayedName(); item.sender = rosterItem->getDisplayedName();
if (rosterItem->getAvatarState() != Shared::Avatar::empty) { if (rosterItem->getAvatarState() != Shared::Avatar::empty)
item.avatar = rosterItem->getAvatarPath(); item.avatar = rosterItem->getAvatarPath();
} }
} }
}
if (item.avatar.size() == 0) { if (item.avatar.size() == 0)
item.avatar = Shared::iconPath("user", true); item.avatar = Shared::iconPath("user", true);
}
item.attach = fillAttach(*msg); item.attach = fillAttach(*msg);
answer.setValue(item); answer.setValue(item);
} }
@ -363,13 +356,12 @@ QVariant Models::MessageFeed::data(const QModelIndex& index, int role) const
return answer; return answer;
} }
int Models::MessageFeed::rowCount(const QModelIndex& parent) const int Models::MessageFeed::rowCount(const QModelIndex& parent) const {
{ SHARED_UNUSED(parent);
return storage.size(); return storage.size();
} }
bool Models::MessageFeed::markMessageAsRead(const QString& id) const bool Models::MessageFeed::markMessageAsRead(const QString& id) const {
{
std::set<QString>::const_iterator umi = unreadMessages->find(id); std::set<QString>::const_iterator umi = unreadMessages->find(id);
if (umi != unreadMessages->end()) { if (umi != unreadMessages->end()) {
unreadMessages->erase(umi); unreadMessages->erase(umi);
@ -379,32 +371,29 @@ bool Models::MessageFeed::markMessageAsRead(const QString& id) const
return false; return false;
} }
unsigned int Models::MessageFeed::unreadMessagesCount() const unsigned int Models::MessageFeed::unreadMessagesCount() const {
{
return unreadMessages->size(); 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; return syncState == incomplete;
} }
void Models::MessageFeed::fetchMore(const QModelIndex& parent) void Models::MessageFeed::fetchMore(const QModelIndex& parent) {
{ SHARED_UNUSED(parent);
if (syncState == incomplete) { if (syncState == incomplete) {
syncState = syncing; syncState = syncing;
emit syncStateChange(syncState); emit syncStateChange(syncState);
if (storage.size() == 0) { if (storage.size() == 0)
emit requestArchive(""); emit requestArchive("");
} else { else
emit requestArchive((*indexByTime.rbegin())->getId()); emit requestArchive((*indexByTime.rbegin())->getId());
} }
}
} }
void Models::MessageFeed::responseArchive(const std::list<Shared::Message> list, bool last) void Models::MessageFeed::responseArchive(const std::list<Shared::Message> list, bool last) {
{
Storage::size_type size = storage.size(); Storage::size_type size = storage.size();
beginInsertRows(QModelIndex(), size, size + list.size() - 1); beginInsertRows(QModelIndex(), size, size + list.size() - 1);
@ -415,20 +404,18 @@ void Models::MessageFeed::responseArchive(const std::list<Shared::Message> list,
endInsertRows(); endInsertRows();
if (syncState == syncing) { if (syncState == syncing) {
if (last) { if (last)
syncState = complete; syncState = complete;
} else { else
syncState = incomplete; syncState = incomplete;
}
emit syncStateChange(syncState); emit syncStateChange(syncState);
} }
} }
QModelIndex Models::MessageFeed::index(int row, int column, const QModelIndex& parent) const QModelIndex Models::MessageFeed::index(int row, int column, const QModelIndex& parent) const{
{ if (!hasIndex(row, column, parent))
if (!hasIndex(row, column, parent)) {
return QModelIndex(); return QModelIndex();
}
StorageByTime::iterator itr = indexByTime.nth(row); StorageByTime::iterator itr = indexByTime.nth(row);
if (itr != indexByTime.end()) { if (itr != indexByTime.end()) {
@ -442,8 +429,7 @@ QModelIndex Models::MessageFeed::index(int row, int column, const QModelIndex& p
QHash<int, QByteArray> Models::MessageFeed::roleNames() const {return roles;} QHash<int, QByteArray> 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()) { if (rosterItem->isRoom()) {
const Room* room = static_cast<const Room*>(rosterItem); const Room* room = static_cast<const Room*>(rosterItem);
return room->getNick().toLower() == msg.getFromResource().toLower(); 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; ::Models::Attachment att;
QString id = msg.getId(); QString id = msg.getId();
@ -501,16 +486,14 @@ Models::Attachment Models::MessageFeed::fillAttach(const Shared::Message& msg) c
return att; 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()}); ::Models::Edition ed({msg.getEdited(), msg.getOriginalBody(), msg.getLastModified()});
return ed; return ed;
} }
void Models::MessageFeed::downloadAttachment(const QString& messageId) void Models::MessageFeed::downloadAttachment(const QString& messageId) {
{
bool notify = false; bool notify = false;
Err::const_iterator eitr = failedDownloads.find(messageId); Err::const_iterator eitr = failedDownloads.find(messageId);
if (eitr != failedDownloads.end()) { 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; 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}); 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; bool success = uploads.insert(std::make_pair(messageId, 0)).second;
QVector<int> roles({}); QVector<int> roles({});
@ -556,8 +537,7 @@ bool Models::MessageFeed::registerUpload(const QString& messageId)
return success; 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; Progress* pr = 0;
Err* err = 0; Err* err = 0;
if (up) { 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); 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; Err* failed;
Progress* loads; Progress* loads;
if (up) { if (up) {
@ -601,33 +579,28 @@ void Models::MessageFeed::fileError(const QString& messageId, const QString& err
} }
Progress::iterator pitr = loads->find(messageId); Progress::iterator pitr = loads->find(messageId);
if (pitr != loads->end()) { if (pitr != loads->end())
loads->erase(pitr); loads->erase(pitr);
}
std::pair<Err::iterator, bool> pair = failed->insert(std::make_pair(messageId, error)); std::pair<Err::iterator, bool> pair = failed->insert(std::make_pair(messageId, error));
if (!pair.second) { if (!pair.second)
pair.first->second = error; pair.first->second = error;
}
QModelIndex ind = modelIndexById(messageId); QModelIndex ind = modelIndexById(messageId);
if (ind.isValid()) { if (ind.isValid())
emit dataChanged(ind, ind, {MessageRoles::Attach}); emit dataChanged(ind, ind, {MessageRoles::Attach});
}
} }
void Models::MessageFeed::incrementObservers() void Models::MessageFeed::incrementObservers() {
{
++observersAmount; ++observersAmount;
} }
void Models::MessageFeed::decrementObservers() void Models::MessageFeed::decrementObservers() {
{
--observersAmount; --observersAmount;
} }
QModelIndex Models::MessageFeed::modelIndexById(const QString& id) const QModelIndex Models::MessageFeed::modelIndexById(const QString& id) const {
{
StorageById::const_iterator itr = indexById.find(id); StorageById::const_iterator itr = indexById.find(id);
if (itr != indexById.end()) { if (itr != indexById.end()) {
Shared::Message* msg = *itr; Shared::Message* msg = *itr;
@ -637,8 +610,7 @@ QModelIndex Models::MessageFeed::modelIndexById(const QString& id) const
return QModelIndex(); 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) { if (indexByTime.size() > 0) {
StorageByTime::const_iterator tItr = indexByTime.lower_bound(time); StorageByTime::const_iterator tItr = indexByTime.lower_bound(time);
StorageByTime::const_iterator tEnd = indexByTime.upper_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(); return QModelIndex();
} }
void Models::MessageFeed::reportLocalPathInvalid(const QString& messageId) void Models::MessageFeed::reportLocalPathInvalid(const QString& messageId) {
{
StorageById::iterator itr = indexById.find(messageId); StorageById::iterator itr = indexById.find(messageId);
if (itr == indexById.end()) { if (itr == indexById.end()) {
qDebug() << "received a command to change a message, but the message couldn't be found, skipping"; 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}); emit dataChanged(index, index, {MessageRoles::Attach});
} }
Models::MessageFeed::SyncState Models::MessageFeed::getSyncState() const Models::MessageFeed::SyncState Models::MessageFeed::getSyncState() const {
{
return syncState; return syncState;
} }
void Models::MessageFeed::requestLatestMessages() void Models::MessageFeed::requestLatestMessages() {
{
if (syncState != syncing) { if (syncState != syncing) {
syncState = syncing; syncState = syncing;
emit syncStateChange(syncState); emit syncStateChange(syncState);

View File

@ -31,12 +31,10 @@ Room::Room(Models::Account* acc, Models::Room* p_room, QWidget* parent):
connect(room, &Models::Room::participantLeft, this, &Room::onParticipantLeft); 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(); Shared::Message msg = Conversation::createMessage();
msg.setType(Shared::Message::groupChat); msg.setType(Shared::Message::groupChat);
msg.setFromJid(room->getJid()); msg.setFromJid(room->getJid());
@ -45,13 +43,12 @@ Shared::Message Room::createMessage() const
return msg; return msg;
} }
bool Room::autoJoined() const bool Room::autoJoined() const {
{
return room->getAutoJoin(); 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) { if (item == room) {
switch (col) { switch (col) {
case 0: 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);
} }