Compare commits

..

1 Commits

Author SHA1 Message Date
James Graham
e8b269869c Some people don't want friends so fix 2024-01-24 16:41:13 +00:00
235 changed files with 23675 additions and 27748 deletions

View File

@@ -12,6 +12,7 @@
#include <Quotient/quotient_common.h>
#include <Quotient/syncdata.h>
#include "enums/delegatetype.h"
#include "linkpreviewer.h"
#include "models/reactionmodel.h"
#include "neochatroom.h"
@@ -28,14 +29,19 @@ class EventHandlerTest : public QObject
private:
Connection *connection = nullptr;
TestUtils::TestRoom *room = nullptr;
EventHandler emptyHandler = EventHandler(nullptr, nullptr);
EventHandler eventHandler;
EventHandler emptyHandler;
EventHandler noEventHandler;
private Q_SLOTS:
void initTestCase();
void nullSetEvent();
void eventId();
void nullEventId();
void delegateType_data();
void delegateType();
void nullDelegateType();
void author();
void nullAuthor();
void authorDisplayName();
@@ -63,6 +69,8 @@ private Q_SLOTS:
void nullHasReply();
void replyId();
void nullReplyId();
void replyDelegateType();
void nullReplyDelegateType();
void replyAuthor();
void nullReplyAuthor();
void replyBody();
@@ -75,32 +83,72 @@ private Q_SLOTS:
void nullLocation();
void readMarkers();
void nullReadMarkers();
void cleanup();
};
void EventHandlerTest::initTestCase()
{
connection = Connection::makeMockConnection(QStringLiteral("@bob:kde.org"));
room = new TestUtils::TestRoom(connection, QStringLiteral("#myroom:kde.org"), QLatin1String("test-eventhandler-sync.json"));
eventHandler.setRoom(room);
noEventHandler.setRoom(room);
}
void EventHandlerTest::nullSetEvent()
{
QTest::ignoreMessage(QtWarningMsg, "cannot setEvent when m_room is set to nullptr.");
emptyHandler.setEvent(room->messageEvents().at(0).get());
}
void EventHandlerTest::eventId()
{
EventHandler eventHandler(room, room->messageEvents().at(0).get());
eventHandler.setEvent(room->messageEvents().at(0).get());
QCOMPARE(eventHandler.getId(), QStringLiteral("$153456789:example.org"));
}
void EventHandlerTest::nullEventId()
{
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "getId called with m_event set to nullptr.");
QCOMPARE(noEventHandler.getId(), QString());
}
void EventHandlerTest::delegateType_data()
{
QTest::addColumn<int>("eventNum");
QTest::addColumn<DelegateType::Type>("delegateType");
QTest::newRow("message") << 0 << DelegateType::Message;
QTest::newRow("state") << 1 << DelegateType::State;
QTest::newRow("message 2") << 2 << DelegateType::Message;
QTest::newRow("reaction") << 3 << DelegateType::Other;
QTest::newRow("video") << 4 << DelegateType::Video;
QTest::newRow("location") << 7 << DelegateType::Location;
}
void EventHandlerTest::delegateType()
{
QFETCH(int, eventNum);
QFETCH(DelegateType::Type, delegateType);
eventHandler.setEvent(room->messageEvents().at(eventNum).get());
QCOMPARE(eventHandler.getDelegateType(), delegateType);
}
void EventHandlerTest::nullDelegateType()
{
QTest::ignoreMessage(QtWarningMsg, "getDelegateType called with m_event set to nullptr.");
QCOMPARE(noEventHandler.getDelegateType(), DelegateType::Other);
}
void EventHandlerTest::author()
{
auto event = room->messageEvents().at(0).get();
auto author = room->user(event->senderId());
EventHandler eventHandler(room, event);
eventHandler.setEvent(event);
auto eventHandlerAuthor = eventHandler.getAuthor();
@@ -118,14 +166,15 @@ void EventHandlerTest::nullAuthor()
QTest::ignoreMessage(QtWarningMsg, "getAuthor called with m_room set to nullptr.");
QCOMPARE(emptyHandler.getAuthor(), QVariantMap());
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "getAuthor called with m_event set to nullptr. Returning empty user.");
QCOMPARE(noEventHandler.getAuthor(), room->getUser(nullptr));
}
void EventHandlerTest::authorDisplayName()
{
EventHandler eventHandler(room, room->messageEvents().at(1).get());
auto event = room->messageEvents().at(1).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.getAuthorDisplayName(), QStringLiteral("before"));
}
@@ -134,14 +183,15 @@ void EventHandlerTest::nullAuthorDisplayName()
QTest::ignoreMessage(QtWarningMsg, "getAuthorDisplayName called with m_room set to nullptr.");
QCOMPARE(emptyHandler.getAuthorDisplayName(), QString());
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "getAuthorDisplayName called with m_event set to nullptr.");
QCOMPARE(noEventHandler.getAuthorDisplayName(), QString());
}
void EventHandlerTest::singleLineSidplayName()
{
EventHandler eventHandler(room, room->messageEvents().at(11).get());
auto event = room->messageEvents().at(11).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.singleLineAuthorDisplayname(), QStringLiteral("Look at me I put newlines in my display name"));
}
@@ -150,14 +200,14 @@ void EventHandlerTest::nullSingleLineDisplayName()
QTest::ignoreMessage(QtWarningMsg, "getAuthorDisplayName called with m_room set to nullptr.");
QCOMPARE(emptyHandler.singleLineAuthorDisplayname(), QString());
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "getAuthorDisplayName called with m_event set to nullptr.");
QCOMPARE(noEventHandler.singleLineAuthorDisplayname(), QString());
}
void EventHandlerTest::time()
{
EventHandler eventHandler(room, room->messageEvents().at(0).get());
auto event = room->messageEvents().at(0).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.getTime(), QDateTime::fromMSecsSinceEpoch(1432735824654, Qt::UTC));
QCOMPARE(eventHandler.getTime(true, QDateTime::fromMSecsSinceEpoch(1234, Qt::UTC)), QDateTime::fromMSecsSinceEpoch(1234, Qt::UTC));
@@ -165,18 +215,18 @@ void EventHandlerTest::time()
void EventHandlerTest::nullTime()
{
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "getTime called with m_event set to nullptr.");
QCOMPARE(noEventHandler.getTime(), QDateTime());
EventHandler eventHandler(room, room->messageEvents().at(0).get());
eventHandler.setEvent(room->messageEvents().at(0).get());
QTest::ignoreMessage(QtWarningMsg, "a value must be provided for lastUpdated for a pending event.");
QCOMPARE(eventHandler.getTime(true), QDateTime());
}
void EventHandlerTest::timeString()
{
EventHandler eventHandler(room, room->messageEvents().at(0).get());
auto event = room->messageEvents().at(0).get();
eventHandler.setEvent(event);
KFormat format;
@@ -196,22 +246,25 @@ void EventHandlerTest::timeString()
void EventHandlerTest::nullTimeString()
{
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "getTimeString called with m_event set to nullptr.");
QCOMPARE(noEventHandler.getTimeString(false), QString());
EventHandler eventHandler(room, room->messageEvents().at(0).get());
eventHandler.setEvent(room->messageEvents().at(0).get());
QTest::ignoreMessage(QtWarningMsg, "a value must be provided for lastUpdated for a pending event.");
QCOMPARE(eventHandler.getTimeString(false, QLocale::ShortFormat, true), QString());
}
void EventHandlerTest::highlighted()
{
EventHandler eventHandlerHighlight(room, room->messageEvents().at(2).get());
QCOMPARE(eventHandlerHighlight.isHighlighted(), true);
auto event = room->messageEvents().at(2).get();
eventHandler.setEvent(event);
EventHandler eventHandlerNoHighlight(room, room->messageEvents().at(0).get());
QCOMPARE(eventHandlerNoHighlight.isHighlighted(), false);
QCOMPARE(eventHandler.isHighlighted(), true);
event = room->messageEvents().at(0).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.isHighlighted(), false);
}
void EventHandlerTest::nullHighlighted()
@@ -219,18 +272,21 @@ void EventHandlerTest::nullHighlighted()
QTest::ignoreMessage(QtWarningMsg, "isHighlighted called with m_room set to nullptr.");
QCOMPARE(emptyHandler.isHighlighted(), false);
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "isHighlighted called with m_event set to nullptr.");
QCOMPARE(noEventHandler.isHighlighted(), false);
}
void EventHandlerTest::hidden()
{
EventHandler eventHandlerHidden(room, room->messageEvents().at(3).get());
QCOMPARE(eventHandlerHidden.isHidden(), true);
auto event = room->messageEvents().at(3).get();
eventHandler.setEvent(event);
EventHandler eventHandlerNoHidden(room, room->messageEvents().at(0).get());
QCOMPARE(eventHandlerNoHidden.isHidden(), false);
QCOMPARE(eventHandler.isHidden(), true);
event = room->messageEvents().at(0).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.isHidden(), false);
}
void EventHandlerTest::nullHidden()
@@ -238,14 +294,14 @@ void EventHandlerTest::nullHidden()
QTest::ignoreMessage(QtWarningMsg, "isHidden called with m_room set to nullptr.");
QCOMPARE(emptyHandler.isHidden(), false);
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "isHidden called with m_event set to nullptr.");
QCOMPARE(noEventHandler.isHidden(), false);
}
void EventHandlerTest::body()
{
EventHandler eventHandler(room, room->messageEvents().at(0).get());
auto event = room->messageEvents().at(0).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.getRichBody(), QStringLiteral("<b>This is an example<br>text message</b>"));
QCOMPARE(eventHandler.getRichBody(true), QStringLiteral("<b>This is an example text message</b>"));
@@ -255,8 +311,6 @@ void EventHandlerTest::body()
void EventHandlerTest::nullBody()
{
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "getRichBody called with m_event set to nullptr.");
QCOMPARE(noEventHandler.getRichBody(), QString());
@@ -281,30 +335,32 @@ void EventHandlerTest::genericBody()
QFETCH(int, eventNum);
QFETCH(QString, output);
EventHandler eventHandler(room, room->messageEvents().at(eventNum).get());
eventHandler.setEvent(room->messageEvents().at(eventNum).get());
QCOMPARE(eventHandler.getGenericBody(), output);
}
void EventHandlerTest::nullGenericBody()
{
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "getGenericBody called with m_event set to nullptr.");
QCOMPARE(noEventHandler.getGenericBody(), QString());
}
void EventHandlerTest::subtitle()
{
EventHandler eventHandler(room, room->messageEvents().at(0).get());
auto event = room->messageEvents().at(0).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.subtitleText(), QStringLiteral("after: This is an example text message"));
EventHandler eventHandler2(room, room->messageEvents().at(2).get());
QCOMPARE(eventHandler2.subtitleText(), QStringLiteral("after: This is a highlight @bob:kde.org and this is a link https://kde.org"));
event = room->messageEvents().at(2).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.subtitleText(), QStringLiteral("after: This is a highlight @bob:kde.org and this is a link https://kde.org"));
}
void EventHandlerTest::nullSubtitle()
{
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "subtitleText called with m_event set to nullptr.");
QCOMPARE(noEventHandler.subtitleText(), QString());
}
@@ -312,7 +368,7 @@ void EventHandlerTest::nullSubtitle()
void EventHandlerTest::mediaInfo()
{
auto event = room->messageEvents().at(4).get();
EventHandler eventHandler(room, event);
eventHandler.setEvent(event);
auto mediaInfo = eventHandler.getMediaInfo();
auto thumbnailInfo = mediaInfo["tempInfo"_ls].toMap();
@@ -337,48 +393,76 @@ void EventHandlerTest::nullMediaInfo()
QTest::ignoreMessage(QtWarningMsg, "getMediaInfo called with m_room set to nullptr.");
QCOMPARE(emptyHandler.getMediaInfo(), QVariantMap());
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "getMediaInfo called with m_event set to nullptr.");
QCOMPARE(noEventHandler.getMediaInfo(), QVariantMap());
}
void EventHandlerTest::hasReply()
{
EventHandler eventHandlerReply(room, room->messageEvents().at(5).get());
QCOMPARE(eventHandlerReply.hasReply(), true);
auto event = room->messageEvents().at(5).get();
eventHandler.setEvent(event);
EventHandler eventHandlerNoReply(room, room->messageEvents().at(0).get());
QCOMPARE(eventHandlerNoReply.hasReply(), false);
QCOMPARE(eventHandler.hasReply(), true);
event = room->messageEvents().at(0).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.hasReply(), false);
}
void EventHandlerTest::nullHasReply()
{
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "hasReply called with m_event set to nullptr.");
QCOMPARE(noEventHandler.hasReply(), false);
}
void EventHandlerTest::replyId()
{
EventHandler eventHandlerReply(room, room->messageEvents().at(5).get());
QCOMPARE(eventHandlerReply.getReplyId(), QStringLiteral("$153456789:example.org"));
auto event = room->messageEvents().at(5).get();
eventHandler.setEvent(event);
EventHandler eventHandlerNoReply(room, room->messageEvents().at(0).get());
QCOMPARE(eventHandlerNoReply.getReplyId(), QStringLiteral(""));
QCOMPARE(eventHandler.getReplyId(), QStringLiteral("$153456789:example.org"));
event = room->messageEvents().at(0).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.getReplyId(), QStringLiteral(""));
}
void EventHandlerTest::nullReplyId()
{
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "getReplyId called with m_event set to nullptr.");
QCOMPARE(noEventHandler.getReplyId(), QString());
}
void EventHandlerTest::replyDelegateType()
{
auto event = room->messageEvents().at(5).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.getReplyDelegateType(), DelegateType::Message);
event = room->messageEvents().at(0).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.getReplyDelegateType(), DelegateType::Other);
}
void EventHandlerTest::nullReplyDelegateType()
{
QTest::ignoreMessage(QtWarningMsg, "getReplyDelegateType called with m_room set to nullptr.");
QCOMPARE(emptyHandler.getReplyDelegateType(), DelegateType::Other);
QTest::ignoreMessage(QtWarningMsg, "getReplyDelegateType called with m_event set to nullptr.");
QCOMPARE(noEventHandler.getReplyDelegateType(), DelegateType::Other);
}
void EventHandlerTest::replyAuthor()
{
auto event = room->messageEvents().at(5).get();
auto replyEvent = room->messageEvents().at(0).get();
auto replyAuthor = room->user(replyEvent->senderId());
EventHandler eventHandler(room, room->messageEvents().at(5).get());
eventHandler.setEvent(event);
auto eventHandlerReplyAuthor = eventHandler.getReplyAuthor();
@@ -390,8 +474,10 @@ void EventHandlerTest::replyAuthor()
QCOMPARE(eventHandlerReplyAuthor["color"_ls], Utils::getUserColor(replyAuthor->hueF()));
QCOMPARE(eventHandlerReplyAuthor["object"_ls], QVariant::fromValue(replyAuthor));
EventHandler eventHandlerNoAuthor(room, room->messageEvents().at(0).get());
QCOMPARE(eventHandlerNoAuthor.getReplyAuthor(), room->getUser(nullptr));
event = room->messageEvents().at(0).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.getReplyAuthor(), room->getUser(nullptr));
}
void EventHandlerTest::nullReplyAuthor()
@@ -399,14 +485,14 @@ void EventHandlerTest::nullReplyAuthor()
QTest::ignoreMessage(QtWarningMsg, "getReplyAuthor called with m_room set to nullptr.");
QCOMPARE(emptyHandler.getReplyAuthor(), QVariantMap());
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "getReplyAuthor called with m_event set to nullptr. Returning empty user.");
QCOMPARE(noEventHandler.getReplyAuthor(), room->getUser(nullptr));
}
void EventHandlerTest::replyBody()
{
EventHandler eventHandler(room, room->messageEvents().at(5).get());
auto event = room->messageEvents().at(5).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.getReplyRichBody(), QStringLiteral("<b>This is an example<br>text message</b>"));
QCOMPARE(eventHandler.getReplyRichBody(true), QStringLiteral("<b>This is an example text message</b>"));
@@ -416,8 +502,6 @@ void EventHandlerTest::replyBody()
void EventHandlerTest::nullReplyBody()
{
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "getReplyRichBody called with m_event set to nullptr.");
QCOMPARE(noEventHandler.getReplyRichBody(), QString());
@@ -429,7 +513,7 @@ void EventHandlerTest::replyMediaInfo()
{
auto event = room->messageEvents().at(6).get();
auto replyEvent = room->messageEvents().at(4).get();
EventHandler eventHandler(room, event);
eventHandler.setEvent(event);
auto mediaInfo = eventHandler.getReplyMediaInfo();
auto thumbnailInfo = mediaInfo["tempInfo"_ls].toMap();
@@ -454,26 +538,31 @@ void EventHandlerTest::nullReplyMediaInfo()
QTest::ignoreMessage(QtWarningMsg, "getReplyMediaInfo called with m_room set to nullptr.");
QCOMPARE(emptyHandler.getReplyMediaInfo(), QVariantMap());
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "getReplyMediaInfo called with m_event set to nullptr.");
QCOMPARE(noEventHandler.getReplyMediaInfo(), QVariantMap());
}
void EventHandlerTest::thread()
{
EventHandler eventHandlerNoThread(room, room->messageEvents().at(0).get());
QCOMPARE(eventHandlerNoThread.isThreaded(), false);
QCOMPARE(eventHandlerNoThread.threadRoot(), QString());
auto event = room->messageEvents().at(0).get();
eventHandler.setEvent(event);
EventHandler eventHandlerThreadRoot(room, room->messageEvents().at(9).get());
QCOMPARE(eventHandlerThreadRoot.isThreaded(), true);
QCOMPARE(eventHandlerThreadRoot.threadRoot(), QStringLiteral("$threadroot:example.org"));
QCOMPARE(eventHandlerThreadRoot.getReplyId(), QStringLiteral("$threadroot:example.org"));
QCOMPARE(eventHandler.isThreaded(), false);
QCOMPARE(eventHandler.threadRoot(), QString());
EventHandler eventHandlerThreadReply(room, room->messageEvents().at(10).get());
QCOMPARE(eventHandlerThreadReply.isThreaded(), true);
QCOMPARE(eventHandlerThreadReply.threadRoot(), QStringLiteral("$threadroot:example.org"));
QCOMPARE(eventHandlerThreadReply.getReplyId(), QStringLiteral("$threadmessage1:example.org"));
event = room->messageEvents().at(9).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.isThreaded(), true);
QCOMPARE(eventHandler.threadRoot(), QStringLiteral("$threadroot:example.org"));
QCOMPARE(eventHandler.getReplyId(), QStringLiteral("$threadroot:example.org"));
event = room->messageEvents().at(10).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.isThreaded(), true);
QCOMPARE(eventHandler.threadRoot(), QStringLiteral("$threadroot:example.org"));
QCOMPARE(eventHandler.getReplyId(), QStringLiteral("$threadmessage1:example.org"));
}
void EventHandlerTest::nullThread()
@@ -481,14 +570,14 @@ void EventHandlerTest::nullThread()
QTest::ignoreMessage(QtWarningMsg, "isThreaded called with m_event set to nullptr.");
QCOMPARE(emptyHandler.isThreaded(), false);
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "threadRoot called with m_event set to nullptr.");
QCOMPARE(noEventHandler.threadRoot(), QString());
}
void EventHandlerTest::location()
{
EventHandler eventHandler(room, room->messageEvents().at(7).get());
auto event = room->messageEvents().at(7).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.getLatitude(), QStringLiteral("51.7035").toFloat());
QCOMPARE(eventHandler.getLongitude(), QStringLiteral("-1.14394").toFloat());
@@ -509,7 +598,9 @@ void EventHandlerTest::nullLocation()
void EventHandlerTest::readMarkers()
{
EventHandler eventHandler(room, room->messageEvents().at(0).get());
auto event = room->messageEvents().at(0).get();
eventHandler.setEvent(event);
QCOMPARE(eventHandler.hasReadMarkers(), true);
auto readMarkers = eventHandler.getReadMarkers();
@@ -520,16 +611,18 @@ void EventHandlerTest::readMarkers()
QCOMPARE(eventHandler.getNumberExcessReadMarkers(), QString());
QCOMPARE(eventHandler.getReadMarkersString(), QStringLiteral("1 user: @alice:matrix.org"));
EventHandler eventHandler2(room, room->messageEvents().at(2).get());
QCOMPARE(eventHandler2.hasReadMarkers(), true);
event = room->messageEvents().at(2).get();
eventHandler.setEvent(event);
readMarkers = eventHandler2.getReadMarkers();
QCOMPARE(eventHandler.hasReadMarkers(), true);
readMarkers = eventHandler.getReadMarkers();
QCOMPARE(readMarkers.size(), 5);
QCOMPARE(eventHandler2.getNumberExcessReadMarkers(), QStringLiteral("+ 1"));
QCOMPARE(eventHandler.getNumberExcessReadMarkers(), QStringLiteral("+ 1"));
// There are no guarantees on the order of the users it will be different every time so don't match the whole string.
QCOMPARE(eventHandler2.getReadMarkersString().startsWith(QStringLiteral("6 users:")), true);
QCOMPARE(eventHandler.getReadMarkersString().startsWith(QStringLiteral("6 users:")), true);
}
void EventHandlerTest::nullReadMarkers()
@@ -546,8 +639,6 @@ void EventHandlerTest::nullReadMarkers()
QTest::ignoreMessage(QtWarningMsg, "getReadMarkersString called with m_room set to nullptr.");
QCOMPARE(emptyHandler.getReadMarkersString(), QString());
EventHandler noEventHandler(room, nullptr);
QTest::ignoreMessage(QtWarningMsg, "hasReadMarkers called with m_event set to nullptr.");
QCOMPARE(noEventHandler.hasReadMarkers(), false);
@@ -561,5 +652,10 @@ void EventHandlerTest::nullReadMarkers()
QCOMPARE(noEventHandler.getReadMarkersString(), QString());
}
void EventHandlerTest::cleanup()
{
eventHandler.setEvent(nullptr);
}
QTEST_MAIN(EventHandlerTest)
#include "eventhandlertest.moc"

View File

@@ -103,6 +103,7 @@ void MessageEventModelTest::simpleTimeline()
QCOMPARE(model->data(model->index(1)), QStringLiteral("<b>This is an example<br>text message</b>"));
QCOMPARE(model->data(model->index(1), MessageEventModel::DelegateTypeRole), DelegateType::Message);
QCOMPARE(model->data(model->index(1), MessageEventModel::PlainText), QStringLiteral("This is an example\ntext message"));
QCOMPARE(model->data(model->index(1), MessageEventModel::EventIdRole), QStringLiteral("$153456789:example.org"));
QTest::ignoreMessage(QtWarningMsg, "Index QModelIndex(-1,-1,0x0,QObject(0x0)) is not valid (expected valid)");

View File

@@ -87,7 +87,6 @@ to provide a convergent experience across multiple platforms.</p>
<p xml:lang="fi">NeoChat on asiakassovellus Matrixille, hajautetulle pikaviestinyhteyskäytännölle. Sillä voi lähettää teksti-, video- ja ääniviestejä perheelle, tutuille ja ystäville. Se käyttää KDE-kehystä ja erityisesti Kirigamia tuottaakseen mukautuvan monialustaisen käyttökokemuksen.</p>
<p xml:lang="fr">NeoChat est un client pour le protocole Matrix, un protocole décentralisé de communications pour messagerie instantané. Il vous permet d'envoyer des messages de texte, des vidéos et des fichiers audio à votre famille, vos collègues et vos amis. Il utilise les environnements de développement et plus précisément Kirigami pour fournir une expérience convergente sur plusieurs plate-formes. </p>
<p xml:lang="gl">NeoChat é un cliente para Matrix, o protocolo de comunicación descentralizada para mensaxaría instantánea. Podes enviar mensaxes de texto, vídeos e ficheiros de son á túa familia, colegas e amizades. Usas infraestruturas de KDE e principalmente Kirigami para proporcionar unha experiencia de uso converxente para varias plataformas.</p>
<p xml:lang="hu">A NeoChat egy kliens a Matrixhoz, az azonnali üzenetküldés decentralizált komunikációs protokolljához.. Szöveges üzeneteket, videókat és hangfájlokat küldhet családjának, kollégáinak és barátainak. A KDE keretrendszert használja, a Kirigaminak köszönhetően konvergens élményt nyújt több platformon is.</p>
<p xml:lang="ia">NeoChat es un cliente per Matrix, le protocollo de communication decentralisate per messager instantanee. Illo te permitte inviar messager de texto, files de video e audio a tu familia, collegas e amicos usante. Illo usa KDE frameworks e super toto Kirigamii forni un experientia convergente trans platteforme multiple.</p>
<p xml:lang="it">NeoChat è un client per Matrix, il protocollo di comunicazione decentralizzato per la messaggistica istantanea. Ti consente di inviare messaggi di testo, video e file audio a familiari, colleghi e amici. Utilizza i framework KDE e in particolare Kirigami per fornire un'esperienza convergente su più piattaforme.</p>
<p xml:lang="ka">NeoChat არის Matrix კლიენტი. ის საშუალებას გაძლევთ გაგზავნოთ ტექსტური შეტყობინებები, ვიდეოები და აუდიო ფაილები თქვენს ოჯახს, კოლეგებსა და მეგობრებს მატრიქსის პროტოკოლის გამოყენებით.</p>
@@ -325,24 +324,6 @@ to provide a convergent experience across multiple platforms.</p>
<content_attribute id="social-chat">intense</content_attribute>
</content_rating>
<releases>
<release version="24.02.0" date="2024-02-28">
<url>https://kde.org/announcements/megarelease/6/#neochat</url>
<description>
<p>In the newest version, when launching the app, you will get a welcome page that lets you choose which account you want to use and lets you log in to other accounts. The welcome screen will also warn you when NeoChat cannot load an account.</p>
<p>NeoChat will also let you register a new account directly from the app itself. Deactivating your Matrix account is also possible from within NeoChat.</p>
<p>Spaces are a relatively new feature of Matrix that let you group chat channels together. This is used to improve the discoverability of rooms, manage large communities, or just tidy all the channels you are in. You can now do all this without leaving NeoChat.</p>
<p>NeoChat won't let you miss any new notifications anymore. We added a new page that includes all your recent notifications and when NeoChat is closed, you will still be able to receive push notifications. The main timeline will let you know when more messages are loading and when you reach the end of it.</p>
<p>More NeoChat Goodies</p>
<ul>
<li>QR Codes to share contacts</li>
<li>Improved room upgrades</li>
<li>Added button to reject invitation and ignore user</li>
<li>Display device security details</li>
<li>Added room security settings</li>
</ul>
</description>
</release>
<release version="23.08.5" date="2024-02-15"/>
<release version="23.08.4" date="2023-12-07"/>
<release version="23.08.3" date="2023-11-09"/>
<release version="23.08.2" date="2023-10-12"/>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -77,7 +77,7 @@ SPDX-License-Identifier: CC-BY-SA-4.0
></term>
<listitem>
<para
>Bir kullanıcı veya oda için matrix URIsi; örneğin, matrix:u/kullanıcı:örnek.org ve matrix:r/kök:örnek.org. Bu, NeoChatin verilen odayı veya konuşmayı açmayı denemesini sağlar. </para>
>Bir kullanıcı veya oda için matrix URI'si; örneğin, matrix:u/kullanıcı:örnek.org ve matrix:r/kök:örnek.org. Bu, NeoChat'in verilen odayı veya konuşmayı açmayı denemesini sağlar. </para>
</listitem>
</varlistentry>
</variablelist>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -148,14 +148,6 @@ add_library(neochat STATIC
models/itinerarymodel.h
proxycontroller.cpp
proxycontroller.h
models/linemodel.cpp
models/linemodel.h
events/locationbeaconevent.h
events/serveraclevent.h
events/widgetevent.h
enums/messagecomponenttype.h
models/messagecontentmodel.cpp
models/messagecontentmodel.h
)
qt_add_qml_module(neochat URI org.kde.neochat NO_PLUGIN
@@ -201,12 +193,21 @@ qt_add_qml_module(neochat URI org.kde.neochat NO_PLUGIN
qml/TimelineDelegate.qml
qml/ReplyComponent.qml
qml/StateDelegate.qml
qml/RichLabel.qml
qml/MessageDelegate.qml
qml/Bubble.qml
qml/SectionDelegate.qml
qml/VideoDelegate.qml
qml/ReactionDelegate.qml
qml/LinkPreviewDelegate.qml
qml/AudioDelegate.qml
qml/FileDelegate.qml
qml/ImageDelegate.qml
qml/EncryptedDelegate.qml
qml/EventDelegate.qml
qml/TextDelegate.qml
qml/ReadMarkerDelegate.qml
qml/PollDelegate.qml
qml/MimeComponent.qml
qml/StateComponent.qml
qml/MessageEditComponent.qml
@@ -270,12 +271,14 @@ qt_add_qml_module(neochat URI org.kde.neochat NO_PLUGIN
qml/EmojiDelegate.qml
qml/EmojiGrid.qml
qml/RoomSearchPage.qml
qml/LocationDelegate.qml
qml/LocationChooser.qml
qml/TimelineView.qml
qml/InvitationView.qml
qml/AvatarTabButton.qml
qml/SpaceDrawer.qml
qml/OsmLocationPlugin.qml
qml/LiveLocationDelegate.qml
qml/FullScreenMap.qml
qml/LocationsPage.qml
qml/LocationMapItem.qml
@@ -301,20 +304,6 @@ qt_add_qml_module(neochat URI org.kde.neochat NO_PLUGIN
qml/SearchPage.qml
qml/ServerComboBox.qml
qml/UserSearchPage.qml
qml/ManualUserDialog.qml
qml/MessageComponentChooser.qml
qml/TextComponent.qml
qml/ImageComponent.qml
qml/VideoComponent.qml
qml/AudioComponent.qml
qml/EncryptedComponent.qml
qml/FileComponent.qml
qml/LocationComponent.qml
qml/LiveLocationComponent.qml
qml/PollComponent.qml
qml/LinkPreviewComponent.qml
qml/LoadComponent.qml
qml/RecommendedSpaceDialog.qml
RESOURCES
qml/confetti.png
qml/glowdot.png

View File

@@ -43,14 +43,14 @@ void ChatBarCache::setReplyId(const QString &replyId)
if (m_relationType == Reply && m_relationId == replyId) {
return;
}
const auto oldEventId = std::exchange(m_relationId, replyId);
m_relationId = replyId;
if (m_relationId.isEmpty()) {
m_relationType = None;
} else {
m_relationType = Reply;
}
m_attachmentPath = QString();
Q_EMIT relationIdChanged(oldEventId, m_relationId);
Q_EMIT relationIdChanged();
Q_EMIT attachmentPathChanged();
}
@@ -72,14 +72,14 @@ void ChatBarCache::setEditId(const QString &editId)
if (m_relationType == Edit && m_relationId == editId) {
return;
}
const auto oldEventId = std::exchange(m_relationId, editId);
m_relationId = editId;
if (m_relationId.isEmpty()) {
m_relationType = None;
} else {
m_relationType = Edit;
}
m_attachmentPath = QString();
Q_EMIT relationIdChanged(oldEventId, m_relationId);
Q_EMIT relationIdChanged();
Q_EMIT attachmentPathChanged();
}
@@ -114,9 +114,10 @@ QString ChatBarCache::relationMessage() const
qWarning() << "ChatBarCache created with incorrect parent, a NeoChatRoom must be set as the parent on creation.";
return {};
}
EventHandler eventhandler;
eventhandler.setRoom(room);
if (auto event = room->findInTimeline(m_relationId); event != room->historyEdge()) {
EventHandler eventhandler(room, &**event);
eventhandler.setEvent(&**event);
return eventhandler.getPlainBody();
}
return {};
@@ -153,9 +154,9 @@ void ChatBarCache::setAttachmentPath(const QString &attachmentPath)
}
m_attachmentPath = attachmentPath;
m_relationType = None;
const auto oldEventId = std::exchange(m_relationId, QString());
m_relationId = QString();
Q_EMIT attachmentPathChanged();
Q_EMIT relationIdChanged(oldEventId, m_relationId);
Q_EMIT relationIdChanged();
}
QList<Mention> *ChatBarCache::mentions()

View File

@@ -186,7 +186,7 @@ public:
Q_SIGNALS:
void textChanged();
void relationIdChanged(const QString &oldEventId, const QString &newEventId);
void relationIdChanged();
void threadIdChanged();
void attachmentPathChanged();

View File

@@ -178,12 +178,10 @@ void Controller::invokeLogin()
}
auto connection = new NeoChatConnection(account.homeserver());
m_connectionsLoading[accountId] = connection;
connect(connection, &NeoChatConnection::connected, this, [this, connection, accountId] {
connect(connection, &NeoChatConnection::connected, this, [this, connection] {
connection->loadState();
addConnection(connection);
m_accountsLoading.removeAll(connection->userId());
m_connectionsLoading.remove(accountId);
Q_EMIT accountsLoadingChanged();
});
connect(connection, &NeoChatConnection::networkError, this, [this](const QString &error, const QString &, int, int) {
@@ -332,13 +330,3 @@ void Controller::setTestMode(bool test)
{
testMode = test;
}
void Controller::removeConnection(const QString &userId)
{
if (m_connectionsLoading.contains(userId) && m_connectionsLoading[userId]) {
auto connection = m_connectionsLoading[userId];
m_accountsLoading.removeAll(userId);
Q_EMIT accountsLoadingChanged();
SettingsGroup("Accounts"_ls).remove(userId);
}
}

View File

@@ -96,8 +96,6 @@ public:
static void setTestMode(bool testMode);
Q_INVOKABLE void removeConnection(const QString &userId);
private:
explicit Controller(QObject *parent = nullptr);
@@ -111,7 +109,6 @@ private:
Quotient::AccountRegistry m_accountRegistry;
QStringList m_accountsLoading;
QMap<QString, QPointer<Quotient::Connection>> m_connectionsLoading;
QString m_endpoint;
private Q_SLOTS:

View File

@@ -6,13 +6,6 @@
#include <QObject>
#include <QQmlEngine>
#include <Quotient/events/encryptedevent.h>
#include <Quotient/events/roomevent.h>
#include <Quotient/events/roommessageevent.h>
#include <Quotient/events/stickerevent.h>
#include "events/pollevent.h"
/**
* @class DelegateType
*
@@ -33,34 +26,23 @@ public:
* similar to the spec it is not the same.
*/
enum Type {
Emote, /**< A message that begins with /me. */
Notice, /**< A notice event. */
Image, /**< A message that is an image. */
Audio, /**< A message that is an audio recording. */
Video, /**< A message that is a video. */
File, /**< A message that is a file. */
Message, /**< A text message. */
Sticker, /**< A message that is a sticker. */
State, /**< A state event in the room. */
Encrypted, /**< An encrypted message that cannot be decrypted. */
ReadMarker, /**< The local user read marker. */
Poll, /**< The initial event for a poll. */
Location, /**< A location event. */
LiveLocation, /**< The initial event of a shared live location (i.e., the place where this is supposed to be shown in the timeline). */
Loading, /**< A delegate to tell the user more messages are being loaded. */
TimelineEnd, /**< A delegate to inform that all messages are loaded. */
Other, /**< Anything that cannot be classified as another type. */
};
Q_ENUM(Type);
/**
* @brief Return the delegate type for the given event.
*
* @param event the event to return a type for.
*
* @sa Type
*/
static Type typeForEvent(const Quotient::RoomEvent &event)
{
if (event.is<Quotient::RoomMessageEvent>() || event.is<Quotient::StickerEvent>() || event.is<Quotient::EncryptedEvent>()
|| event.is<Quotient::PollStartEvent>()) {
return Message;
}
if (event.isStateEvent()) {
if (event.matrixType() == QStringLiteral("org.matrix.msc3672.beacon_info")) {
return Message;
}
return State;
}
return Other;
}
};

View File

@@ -1,107 +0,0 @@
// SPDX-FileCopyrightText: 2024 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
#pragma once
#include <QObject>
#include <QQmlEngine>
#include <Quotient/events/encryptedevent.h>
#include <Quotient/events/roomevent.h>
#include <Quotient/events/roommessageevent.h>
#include <Quotient/events/stickerevent.h>
#include "events/pollevent.h"
/**
* @class MessageComponentType
*
* This class is designed to define the MessageComponentType enumeration.
*/
class MessageComponentType : public QObject
{
Q_OBJECT
QML_ELEMENT
QML_UNCREATABLE("")
public:
/**
* @brief The type of component that is needed for an event.
*
* @note While similar this is not the matrix event or message type. This is
* to tell a QML Bubble what component to use to visualise all or part of
* a room message.
*/
enum Type {
Text, /**< A text message. */
Image, /**< A message that is an image. */
Audio, /**< A message that is an audio recording. */
Video, /**< A message that is a video. */
File, /**< A message that is a file. */
Poll, /**< The initial event for a poll. */
Location, /**< A location event. */
LiveLocation, /**< The initial event of a shared live location (i.e., the place where this is supposed to be shown in the timeline). */
Encrypted, /**< An encrypted message that cannot be decrypted. */
Reply, /**< A component to show a replied-to message. */
ReplyLoad, /**< A loading dialog for a reply. */
LinkPreview, /**< A preview of a URL in the message. */
LinkPreviewLoad, /**< A loading dialog for a link preview. */
Edit, /**< A text edit for editing a message. */
Other, /**< Anything that cannot be classified as another type. */
};
Q_ENUM(Type);
/**
* @brief Return the delegate type for the given event.
*
* @param event the event to return a type for.
*
* @sa Type
*/
static Type typeForEvent(const Quotient::RoomEvent &event)
{
using namespace Quotient;
if (const auto e = eventCast<const RoomMessageEvent>(&event)) {
switch (e->msgtype()) {
case MessageEventType::Emote:
return MessageComponentType::Text;
case MessageEventType::Notice:
return MessageComponentType::Text;
case MessageEventType::Image:
return MessageComponentType::Image;
case MessageEventType::Audio:
return MessageComponentType::Audio;
case MessageEventType::Video:
return MessageComponentType::Video;
case MessageEventType::Location:
return MessageComponentType::Location;
case MessageEventType::File:
return MessageComponentType::File;
default:
return MessageComponentType::Text;
}
}
if (is<const StickerEvent>(event)) {
return MessageComponentType::Image;
}
if (event.isStateEvent()) {
if (event.matrixType() == QStringLiteral("org.matrix.msc3672.beacon_info")) {
return MessageComponentType::LiveLocation;
}
return MessageComponentType::Other;
}
if (is<const EncryptedEvent>(event)) {
return MessageComponentType::Encrypted;
}
if (is<PollStartEvent>(event)) {
const auto pollEvent = eventCast<const PollStartEvent>(&event);
if (pollEvent->isRedacted()) {
return MessageComponentType::Text;
}
return MessageComponentType::Poll;
}
return MessageComponentType::Other;
}
};

View File

@@ -14,19 +14,15 @@
#include <Quotient/events/roomavatarevent.h>
#include <Quotient/events/roomcanonicalaliasevent.h>
#include <Quotient/events/roommemberevent.h>
#include <Quotient/events/roommessageevent.h>
#include <Quotient/events/roompowerlevelsevent.h>
#include <Quotient/events/simplestateevents.h>
#include <Quotient/events/stickerevent.h>
#include <Quotient/quotient_common.h>
#include "delegatetype.h"
#include "eventhandler_logging.h"
#include "events/locationbeaconevent.h"
#include "events/pollevent.h"
#include "events/serveraclevent.h"
#include "events/widgetevent.h"
#include "linkpreviewer.h"
#include "messagecomponenttype.h"
#include "models/reactionmodel.h"
#include "neochatconfig.h"
#include "neochatroom.h"
@@ -35,10 +31,34 @@
using namespace Quotient;
EventHandler::EventHandler(const NeoChatRoom *room, const RoomEvent *event)
: m_room(room)
, m_event(event)
const NeoChatRoom *EventHandler::getRoom() const
{
return m_room;
}
void EventHandler::setRoom(const NeoChatRoom *room)
{
if (room == m_room) {
return;
}
m_room = room;
}
const Quotient::Event *EventHandler::getEvent() const
{
return m_event;
}
void EventHandler::setEvent(const Quotient::RoomEvent *event)
{
if (m_room == nullptr) {
qCWarning(EventHandling) << "cannot setEvent when m_room is set to nullptr.";
return;
}
if (event == m_event) {
return;
}
m_event = event;
}
QString EventHandler::getId() const
@@ -51,14 +71,62 @@ QString EventHandler::getId() const
return !m_event->id().isEmpty() ? m_event->id() : m_event->transactionId();
}
MessageComponentType::Type EventHandler::messageComponentType() const
DelegateType::Type EventHandler::getDelegateTypeForEvent(const Quotient::RoomEvent *event) const
{
if (m_event == nullptr) {
qCWarning(EventHandling) << "messageComponentType called with m_event set to nullptr.";
return MessageComponentType::Other;
if (auto e = eventCast<const RoomMessageEvent>(event)) {
switch (e->msgtype()) {
case MessageEventType::Emote:
return DelegateType::Emote;
case MessageEventType::Notice:
return DelegateType::Notice;
case MessageEventType::Image:
return DelegateType::Image;
case MessageEventType::Audio:
return DelegateType::Audio;
case MessageEventType::Video:
return DelegateType::Video;
case MessageEventType::Location:
return DelegateType::Location;
default:
break;
}
if (e->hasFileContent()) {
return DelegateType::File;
}
return DelegateType::Message;
}
if (is<const StickerEvent>(*event)) {
return DelegateType::Sticker;
}
if (event->isStateEvent()) {
if (event->matrixType() == QStringLiteral("org.matrix.msc3672.beacon_info")) {
return DelegateType::LiveLocation;
}
return DelegateType::State;
}
if (is<const EncryptedEvent>(*event)) {
return DelegateType::Encrypted;
}
if (is<PollStartEvent>(*event)) {
const auto pollEvent = eventCast<const PollStartEvent>(event);
if (pollEvent->isRedacted()) {
return DelegateType::Message;
}
return DelegateType::Poll;
}
return MessageComponentType::typeForEvent(*m_event);
return DelegateType::Other;
}
DelegateType::Type EventHandler::getDelegateType() const
{
if (m_event == nullptr) {
qCWarning(EventHandling) << "getDelegateType called with m_event set to nullptr.";
return DelegateType::Other;
}
return getDelegateTypeForEvent(m_event);
}
QVariantMap EventHandler::getAuthor(bool isPending) const
@@ -277,7 +345,8 @@ QString EventHandler::getBody(const Quotient::RoomEvent *event, Qt::TextFormat f
}
if (prettyPrint) {
subjectName = QStringLiteral("<a href=\"https://matrix.to/#/%1\">%2</a>").arg(e.userId(), subjectName);
subjectName = QStringLiteral("<a href=\"https://matrix.to/#/%1\" style=\"color: %2\">%3</a>")
.arg(e.userId(), Utils::getUserColor(m_room->user(e.userId())->hueF()).name(), subjectName);
}
// The below code assumes senderName output in AuthorRole
@@ -388,22 +457,22 @@ QString EventHandler::getBody(const Quotient::RoomEvent *event, Qt::TextFormat f
[](const RoomPowerLevelsEvent &) {
return i18nc("'power level' means permission level", "changed the power levels for this room");
},
[](const LocationBeaconEvent &e) {
return e.contentJson()["description"_ls].toString();
},
[](const ServerAclEvent &) {
return i18n("changed the server access control lists for this room");
},
[](const WidgetEvent &e) {
if (e.fullJson()["unsigned"_ls]["prev_content"_ls].toObject().isEmpty()) {
return i18nc("[User] added <name> widget", "added %1 widget", e.contentJson()["name"_ls].toString());
}
if (e.contentJson().isEmpty()) {
return i18nc("[User] removed <name> widget", "removed %1 widget", e.fullJson()["unsigned"_ls]["prev_content"_ls]["name"_ls].toString());
}
return i18nc("[User] configured <name> widget", "configured %1 widget", e.contentJson()["name"_ls].toString());
},
[prettyPrint](const StateEvent &e) {
if (e.matrixType() == QLatin1String("m.room.server_acl")) {
return i18n("changed the server access control lists for this room");
}
if (e.matrixType() == QLatin1String("im.vector.modular.widgets")) {
if (e.fullJson()["unsigned"_ls]["prev_content"_ls].toObject().isEmpty()) {
return i18nc("[User] added <name> widget", "added %1 widget", e.contentJson()["name"_ls].toString());
}
if (e.contentJson().isEmpty()) {
return i18nc("[User] removed <name> widget", "removed %1 widget", e.fullJson()["unsigned"_ls]["prev_content"_ls]["name"_ls].toString());
}
return i18nc("[User] configured <name> widget", "configured %1 widget", e.contentJson()["name"_ls].toString());
}
if (e.matrixType() == "org.matrix.msc3672.beacon_info"_ls) {
return e.contentJson()["description"_ls].toString();
}
return e.stateKey().isEmpty() ? i18n("updated %1 state", e.matrixType())
: i18n("updated %1 state for %2", e.matrixType(), prettyPrint ? e.stateKey().toHtmlEscaped() : e.stateKey());
},
@@ -557,22 +626,19 @@ QString EventHandler::getGenericBody() const
[](const RoomPowerLevelsEvent &) {
return i18nc("'power level' means permission level", "changed the power levels for this room");
},
[](const LocationBeaconEvent &) {
return i18n("sent a live location beacon");
},
[](const ServerAclEvent &) {
return i18n("changed the server access control lists for this room");
},
[](const WidgetEvent &e) {
if (e.fullJson()["unsigned"_ls]["prev_content"_ls].toObject().isEmpty()) {
return i18n("added a widget");
[](const StateEvent &e) {
if (e.matrixType() == QLatin1String("m.room.server_acl")) {
return i18n("changed the server access control lists for this room");
}
if (e.contentJson().isEmpty()) {
return i18n("removed a widget");
if (e.matrixType() == QLatin1String("im.vector.modular.widgets")) {
if (e.fullJson()["unsigned"_ls]["prev_content"_ls].toObject().isEmpty()) {
return i18n("added a widget");
}
if (e.contentJson().isEmpty()) {
return i18n("removed a widget");
}
return i18n("configured a widget");
}
return i18n("configured a widget");
},
[](const StateEvent &) {
return i18n("updated the state");
},
[](const PollStartEvent &e) {
@@ -729,22 +795,22 @@ QString EventHandler::getReplyId() const
return m_event->contentJson()["m.relates_to"_ls].toObject()["m.in_reply_to"_ls].toObject()["event_id"_ls].toString();
}
MessageComponentType::Type EventHandler::replyMessageComponentType() const
DelegateType::Type EventHandler::getReplyDelegateType() const
{
if (m_room == nullptr) {
qCWarning(EventHandling) << "replyMessageComponentType called with m_room set to nullptr.";
return MessageComponentType::Other;
qCWarning(EventHandling) << "getReplyDelegateType called with m_room set to nullptr.";
return DelegateType::Other;
}
if (m_event == nullptr) {
qCWarning(EventHandling) << "replyMessageComponentType called with m_event set to nullptr.";
return MessageComponentType::Other;
qCWarning(EventHandling) << "getReplyDelegateType called with m_event set to nullptr.";
return DelegateType::Other;
}
auto replyEvent = m_room->getReplyForEvent(*m_event);
if (replyEvent == nullptr) {
return MessageComponentType::Other;
return DelegateType::Other;
}
return MessageComponentType::typeForEvent(*replyEvent);
return getDelegateTypeForEvent(replyEvent);
}
QVariantMap EventHandler::getReplyAuthor() const

View File

@@ -11,7 +11,7 @@
#include <Quotient/events/roomevent.h>
#include <Quotient/events/roommessageevent.h>
#include "enums/messagecomponenttype.h"
#include "enums/delegatetype.h"
class LinkPreviewer;
class NeoChatRoom;
@@ -31,12 +31,30 @@ class ReactionModel;
* information. This is to minimize warnings from QML especially during startup
* and room changes.
*/
class EventHandler
class EventHandler : public QObject
{
Q_GADGET
Q_OBJECT
public:
EventHandler(const NeoChatRoom *room, const Quotient::RoomEvent *event);
/**
* @brief Return the current room the EventHandler is using.
*/
const NeoChatRoom *getRoom() const;
/**
* @brief Set the current room the EventHandler to using.
*/
void setRoom(const NeoChatRoom *room);
/**
* @brief Return the current event the EventHandler is using.
*/
const Quotient::Event *getEvent() const;
/**
* @brief Set the current event the EventHandler to using.
*/
void setEvent(const Quotient::RoomEvent *event);
/**
* @brief Return the Matrix ID of the event.
@@ -44,9 +62,13 @@ public:
QString getId() const;
/**
* @brief The MessageComponentType to use to visualise the main event content.
* @brief Return the DelegateType of the event.
*
* @note While similar this is not the matrix event or message type. This is
* to tell a QML ListView what delegate to show for each event. So while
* similar to the spec it is not the same.
*/
MessageComponentType::Type messageComponentType() const;
DelegateType::Type getDelegateType() const;
/**
* @brief Get the author of the event in context of the room.
@@ -220,9 +242,13 @@ public:
QString getReplyId() const;
/**
* @brief The MessageComponentType to use to visualise the reply content.
* @brief Return the DelegateType of the event replied to.
*
* @note While similar this is not the matrix event or message type. This is
* to tell a QML ListView what delegate to show for each event. So while
* similar to the spec it is not the same.
*/
MessageComponentType::Type replyMessageComponentType() const;
DelegateType::Type getReplyDelegateType() const;
/**
* @brief Get the author of the event replied to in context of the room.
@@ -378,6 +404,8 @@ private:
KFormat m_format;
DelegateType::Type getDelegateTypeForEvent(const Quotient::RoomEvent *event) const;
QString getBody(const Quotient::RoomEvent *event, Qt::TextFormat format, bool stripNewlines) const;
QString getMessageBody(const Quotient::RoomMessageEvent &event, Qt::TextFormat format, bool stripNewlines) const;

View File

@@ -1,14 +0,0 @@
// SPDX-FileCopyrightText: 2024 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
#pragma once
#include <Quotient/events/simplestateevents.h>
namespace Quotient
{
// Defined so we can directly switch on type.
DEFINE_SIMPLE_STATE_EVENT(LocationBeaconEvent, "org.matrix.msc3672.beacon_info", QString, body, "body")
} // namespace Quotient

View File

@@ -1,14 +0,0 @@
// SPDX-FileCopyrightText: 2024 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
#pragma once
#include <Quotient/events/simplestateevents.h>
namespace Quotient
{
// Defined so we can directly switch on type.
DEFINE_SIMPLE_STATE_EVENT(ServerAclEvent, "m.room.server_acl", bool, allow_ip_literals, "allow_ip_literals")
} // namespace Quotient

View File

@@ -1,14 +0,0 @@
// SPDX-FileCopyrightText: 2024 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
#pragma once
#include <Quotient/events/simplestateevents.h>
namespace Quotient
{
// Defined so we can directly switch on type.
DEFINE_SIMPLE_STATE_EVENT(WidgetEvent, "im.vector.modular.widgets", QString, name, "name")
} // namespace Quotient

View File

@@ -13,8 +13,8 @@
using namespace Quotient;
LinkPreviewer::LinkPreviewer(const NeoChatRoom *room, const Quotient::RoomMessageEvent *event, QObject *parent)
: QObject(parent)
LinkPreviewer::LinkPreviewer(const NeoChatRoom *room, const Quotient::RoomMessageEvent *event)
: QObject(nullptr)
, m_currentRoom(room)
, m_event(event)
, m_loaded(false)

View File

@@ -60,7 +60,7 @@ class LinkPreviewer : public QObject
Q_PROPERTY(bool empty READ empty NOTIFY emptyChanged)
public:
explicit LinkPreviewer(const NeoChatRoom *room = nullptr, const Quotient::RoomMessageEvent *event = nullptr, QObject *parent = nullptr);
explicit LinkPreviewer(const NeoChatRoom *room = nullptr, const Quotient::RoomMessageEvent *event = nullptr);
[[nodiscard]] QUrl url() const;
[[nodiscard]] bool loaded() const;

View File

@@ -230,7 +230,7 @@ QList<ActionsModel::Action> actions{
}
auto targetRoom = text.startsWith(QLatin1Char('!')) ? room->connection()->room(text) : room->connection()->roomByAlias(text);
if (targetRoom) {
RoomManager::instance().resolveResource(targetRoom->id());
RoomManager::instance().enterRoom(dynamic_cast<NeoChatRoom *>(targetRoom));
return QString();
}
Q_EMIT room->showMessage(NeoChatRoom::Info, i18nc("Joining room <roomname>.", "Joining room %1.", text));
@@ -256,7 +256,7 @@ QList<ActionsModel::Action> actions{
}
auto targetRoom = text.startsWith(QLatin1Char('!')) ? room->connection()->room(text) : room->connection()->roomByAlias(text);
if (targetRoom) {
RoomManager::instance().resolveResource(targetRoom->id());
RoomManager::instance().enterRoom(dynamic_cast<NeoChatRoom *>(targetRoom));
return QString();
}
Q_EMIT room->showMessage(NeoChatRoom::Info, i18nc("Knocking room <roomname>.", "Knocking room %1.", text));

View File

@@ -1,64 +0,0 @@
// SPDX-FileCopyrightText: 2024 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
#include "linemodel.h"
LineModel::LineModel(QObject *parent)
: QAbstractListModel(parent)
{
}
QQuickTextDocument *LineModel::document() const
{
return m_document;
}
void LineModel::setDocument(QQuickTextDocument *document)
{
if (document == m_document) {
return;
}
m_document = document;
Q_EMIT documentChanged();
resetModel();
}
QVariant LineModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return {};
}
const auto &row = index.row();
if (row < 0 || row > rowCount()) {
return {};
}
if (role == LineHeightRole) {
auto textDoc = m_document->textDocument();
return int(textDoc->documentLayout()->blockBoundingRect(textDoc->findBlockByNumber(row)).height());
}
return {};
}
int LineModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
if (m_document == nullptr) {
return 0;
}
return m_document->textDocument()->blockCount();
}
QHash<int, QByteArray> LineModel::roleNames() const
{
return {{LineHeightRole, "docLineHeight"}};
}
void LineModel::resetModel()
{
beginResetModel();
endResetModel();
}

View File

@@ -1,80 +0,0 @@
// SPDX-FileCopyrightText: 2024 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
#pragma once
#include <QAbstractListModel>
#include <QAbstractTextDocumentLayout>
#include <QQmlEngine>
#include <QQuickTextDocument>
#include <QTextBlock>
#include <qtmetamacros.h>
/**
* @class LineModel
*
* A model to provide line info for a QQuickTextDocument.
*
* @sa QQuickTextDocument
*/
class LineModel : public QAbstractListModel
{
Q_OBJECT
QML_ELEMENT
/**
* @brief The QQuickTextDocument that is being handled.
*/
Q_PROPERTY(QQuickTextDocument *document READ document WRITE setDocument NOTIFY documentChanged)
public:
/**
* @brief Defines the model roles.
*/
enum Roles {
LineHeightRole = Qt::UserRole + 1, /**< The delegate type of the message. */
};
Q_ENUM(Roles)
explicit LineModel(QObject *parent = nullptr);
[[nodiscard]] QQuickTextDocument *document() const;
void setDocument(QQuickTextDocument *document);
/**
* @brief Get the given role value at the given index.
*
* @sa QAbstractItemModel::data
*/
[[nodiscard]] QVariant data(const QModelIndex &index, int role) const override;
/**
* @brief Number of rows in the model.
*
* @sa QAbstractItemModel::rowCount
*/
[[nodiscard]] int rowCount(const QModelIndex &parent = QModelIndex()) const override;
/**
* @brief Returns a mapping from Role enum values to role names.
*
* @sa Roles, QAbstractItemModel::roleNames()
*/
[[nodiscard]] QHash<int, QByteArray> roleNames() const override;
/**
* @brief Reset the model.
*
* This needs to be called when the QQuickTextDocument container changes width
* or height as this may change line heights due to wrapping.
*
* @sa QQuickTextDocument
*/
Q_INVOKABLE void resetModel();
Q_SIGNALS:
void documentChanged();
private:
QPointer<QQuickTextDocument> m_document = nullptr;
};

View File

@@ -3,9 +3,9 @@
#include "mediamessagefiltermodel.h"
#include <Quotient/events/roommessageevent.h>
#include <Quotient/room.h>
#include "enums/delegatetype.h"
#include "messageeventmodel.h"
#include "messagefiltermodel.h"
@@ -20,8 +20,8 @@ bool MediaMessageFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex
{
const QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
if (index.data(MessageEventModel::MediaInfoRole).toMap()[QLatin1String("mimeType")].toString().contains(QLatin1String("image"))
|| index.data(MessageEventModel::MediaInfoRole).toMap()[QLatin1String("mimeType")].toString().contains(QLatin1String("video"))) {
if (index.data(MessageEventModel::DelegateTypeRole).toInt() == DelegateType::Image
|| index.data(MessageEventModel::DelegateTypeRole).toInt() == DelegateType::Video) {
return true;
}
return false;
@@ -30,9 +30,9 @@ bool MediaMessageFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex
QVariant MediaMessageFilterModel::data(const QModelIndex &index, int role) const
{
if (role == SourceRole) {
if (mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()[QLatin1String("mimeType")].toString().contains(QLatin1String("image"))) {
if (mapToSource(index).data(MessageEventModel::DelegateTypeRole).toInt() == DelegateType::Image) {
return mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()[QStringLiteral("source")].toUrl();
} else if (mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()[QLatin1String("mimeType")].toString().contains(QLatin1String("video"))) {
} else if (mapToSource(index).data(MessageEventModel::DelegateTypeRole).toInt() == DelegateType::Video) {
auto progressInfo = mapToSource(index).data(MessageEventModel::ProgressInfoRole).value<Quotient::FileTransferInfo>();
if (progressInfo.completed()) {
@@ -48,7 +48,7 @@ QVariant MediaMessageFilterModel::data(const QModelIndex &index, int role) const
return mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()[QStringLiteral("tempInfo")].toMap()[QStringLiteral("source")].toUrl();
}
if (role == TypeRole) {
if (mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()[QLatin1String("mimeType")].toString().contains(QLatin1String("image"))) {
if (mapToSource(index).data(MessageEventModel::DelegateTypeRole).toInt() == DelegateType::Image) {
return MediaType::Image;
} else {
return MediaType::Video;

View File

@@ -1,245 +0,0 @@
// SPDX-FileCopyrightText: 2024 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
#include "messagecontentmodel.h"
#include <Quotient/events/redactionevent.h>
#include <Quotient/events/stickerevent.h>
#include <KLocalizedString>
#include "chatbarcache.h"
#include "enums/messagecomponenttype.h"
#include "eventhandler.h"
#include "linkpreviewer.h"
#include "neochatroom.h"
MessageContentModel::MessageContentModel(const Quotient::RoomEvent *event, NeoChatRoom *room)
: QAbstractListModel(nullptr)
, m_room(room)
, m_event(event)
{
if (m_room != nullptr) {
connect(m_room, &NeoChatRoom::pendingEventAboutToMerge, this, [this](Quotient::RoomEvent *serverEvent) {
if (m_room != nullptr && m_event != nullptr) {
if (m_event->id() == serverEvent->id()) {
beginResetModel();
m_event = serverEvent;
endResetModel();
}
}
});
connect(m_room, &NeoChatRoom::replacedEvent, this, [this](const Quotient::RoomEvent *newEvent) {
if (m_room != nullptr && m_event != nullptr) {
if (m_event->id() == newEvent->id()) {
beginResetModel();
m_event = newEvent;
endResetModel();
}
}
});
connect(m_room, &NeoChatRoom::replyLoaded, this, [this](const QString &eventId, const QString &replyId) {
Q_UNUSED(eventId)
if (m_event != nullptr && m_event != nullptr) {
const auto eventHandler = EventHandler(m_room, m_event);
if (replyId == eventHandler.getReplyId()) {
// HACK: Because DelegateChooser can't switch the delegate on dataChanged it has to think there is a new delegate.
beginResetModel();
m_components[0] = MessageComponentType::Reply;
endResetModel();
}
}
});
connect(m_room, &NeoChatRoom::newFileTransfer, this, [this](const QString &eventId) {
if (m_event != nullptr && m_event != nullptr && eventId == m_event->id()) {
Q_EMIT dataChanged(index(0), index(rowCount() - 1), {FileTransferInfoRole});
}
});
connect(m_room, &NeoChatRoom::fileTransferProgress, this, [this](const QString &eventId) {
if (m_event != nullptr && m_event != nullptr && eventId == m_event->id()) {
Q_EMIT dataChanged(index(0), index(rowCount() - 1), {FileTransferInfoRole});
}
});
connect(m_room, &NeoChatRoom::fileTransferCompleted, this, [this](const QString &eventId) {
if (m_event != nullptr && m_event != nullptr && eventId == m_event->id()) {
Q_EMIT dataChanged(index(0), index(rowCount() - 1), {FileTransferInfoRole});
}
});
connect(m_room, &NeoChatRoom::fileTransferFailed, this, [this](const QString &eventId) {
if (m_event != nullptr && m_event != nullptr && eventId == m_event->id()) {
Q_EMIT dataChanged(index(0), index(rowCount() - 1), {FileTransferInfoRole});
}
});
connect(m_room->editCache(), &ChatBarCache::relationIdChanged, this, [this](const QString &oldEventId, const QString &newEventId) {
if (m_event != nullptr && (oldEventId == m_event->id() || newEventId == m_event->id())) {
// HACK: Because DelegateChooser can't switch the delegate on dataChanged it has to think there is a new delegate.
beginResetModel();
endResetModel();
}
});
}
if (const auto event = eventCast<const Quotient::RoomMessageEvent>(m_event)) {
if (LinkPreviewer::hasPreviewableLinks(event)) {
m_linkPreviewer = new LinkPreviewer(m_room, event, this);
connect(m_linkPreviewer, &LinkPreviewer::loadedChanged, [this]() {
if (m_linkPreviewer->loaded()) {
// HACK: Because DelegateChooser can't switch the delegate on dataChanged it has to think there is a new delegate.
beginResetModel();
m_components[m_components.size() - 1] = MessageComponentType::LinkPreview;
endResetModel();
}
});
}
}
updateComponents();
}
static LinkPreviewer *emptyLinkPreview = new LinkPreviewer;
QVariant MessageContentModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return {};
}
if (index.row() >= rowCount()) {
qDebug() << "MessageContentModel, something's wrong: index.row() >= rowCount()";
return {};
}
EventHandler eventHandler(m_room, m_event);
if (role == DisplayRole) {
if (m_event->isRedacted()) {
auto reason = m_event->redactedBecause()->reason();
return (reason.isEmpty()) ? i18n("<i>[This message was deleted]</i>")
: i18n("<i>[This message was deleted: %1]</i>", m_event->redactedBecause()->reason());
}
return eventHandler.getRichBody();
}
if (role == ComponentTypeRole) {
const auto component = m_components[index.row()];
if (component == MessageComponentType::Text && !m_event->id().isEmpty() && m_room->editCache()->editId() == m_event->id()) {
return MessageComponentType::Edit;
}
return component;
}
if (role == EventIdRole) {
return eventHandler.getId();
}
if (role == AuthorRole) {
return eventHandler.getAuthor(false);
}
if (role == MediaInfoRole) {
return eventHandler.getMediaInfo();
}
if (role == FileTransferInfoRole) {
if (auto event = eventCast<const Quotient::RoomMessageEvent>(m_event)) {
if (event->hasFileContent()) {
return QVariant::fromValue(m_room->fileTransferInfo(event->id()));
}
}
if (auto event = eventCast<const Quotient::StickerEvent>(m_event)) {
return QVariant::fromValue(m_room->fileTransferInfo(event->id()));
}
}
if (role == LatitudeRole) {
return eventHandler.getLatitude();
}
if (role == LongitudeRole) {
return eventHandler.getLongitude();
}
if (role == AssetRole) {
return eventHandler.getLocationAssetType();
}
if (role == PollHandlerRole) {
return QVariant::fromValue<PollHandler *>(m_room->poll(m_event->id()));
}
if (role == IsReplyRole) {
return eventHandler.hasReply();
}
if (role == ReplyComponentType) {
return eventHandler.replyMessageComponentType();
}
if (role == ReplyEventIdRole) {
return eventHandler.getReplyId();
}
if (role == ReplyAuthorRole) {
return eventHandler.getReplyAuthor();
}
if (role == ReplyDisplayRole) {
return eventHandler.getReplyRichBody();
}
if (role == ReplyMediaInfoRole) {
return eventHandler.getReplyMediaInfo();
}
if (role == LinkPreviewerRole) {
if (m_linkPreviewer != nullptr) {
return QVariant::fromValue<LinkPreviewer *>(m_linkPreviewer);
} else {
return QVariant::fromValue<LinkPreviewer *>(emptyLinkPreview);
}
}
return {};
}
int MessageContentModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return m_components.size();
}
QHash<int, QByteArray> MessageContentModel::roleNames() const
{
QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();
roles[DisplayRole] = "display";
roles[ComponentTypeRole] = "componentType";
roles[EventIdRole] = "eventId";
roles[AuthorRole] = "author";
roles[MediaInfoRole] = "mediaInfo";
roles[FileTransferInfoRole] = "fileTransferInfo";
roles[LatitudeRole] = "latitude";
roles[LongitudeRole] = "longitude";
roles[AssetRole] = "asset";
roles[PollHandlerRole] = "pollHandler";
roles[IsReplyRole] = "isReply";
roles[ReplyComponentType] = "replyComponentType";
roles[ReplyEventIdRole] = "replyEventId";
roles[ReplyAuthorRole] = "replyAuthor";
roles[ReplyDisplayRole] = "replyDisplay";
roles[ReplyMediaInfoRole] = "replyMediaInfo";
roles[LinkPreviewerRole] = "linkPreviewer";
return roles;
}
void MessageContentModel::updateComponents()
{
beginResetModel();
m_components.clear();
EventHandler eventHandler(m_room, m_event);
if (eventHandler.hasReply()) {
if (m_room->findInTimeline(eventHandler.getReplyId()) == m_room->historyEdge()) {
m_components += MessageComponentType::ReplyLoad;
m_room->loadReply(m_event->id(), eventHandler.getReplyId());
} else {
m_components += MessageComponentType::Reply;
}
}
m_components += eventHandler.messageComponentType();
if (m_linkPreviewer != nullptr) {
if (m_linkPreviewer->loaded()) {
m_components += MessageComponentType::LinkPreview;
} else {
m_components += MessageComponentType::LinkPreviewLoad;
}
}
endResetModel();
}

View File

@@ -1,83 +0,0 @@
// SPDX-FileCopyrightText: 2024 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
#pragma once
#include <QAbstractListModel>
#include <QQmlEngine>
#include "eventhandler.h"
#include "linkpreviewer.h"
#include "messagecomponenttype.h"
#include "neochatroom.h"
/**
* @class MessageContentModel
*
* A model to visualise the components of a single RoomMessageEvent.
*/
class MessageContentModel : public QAbstractListModel
{
Q_OBJECT
QML_ELEMENT
QML_UNCREATABLE("")
public:
/**
* @brief Defines the model roles.
*/
enum Roles {
DisplayRole = Qt::DisplayRole, /**< The display text for the message. */
ComponentTypeRole, /**< The type of component to visualise the message. */
EventIdRole, /**< The matrix event ID of the event. */
AuthorRole, /**< The author of the event. */
MediaInfoRole, /**< The media info for the event. */
FileTransferInfoRole, /**< FileTransferInfo for any downloading files. */
LatitudeRole, /**< Latitude for a location event. */
LongitudeRole, /**< Longitude for a location event. */
AssetRole, /**< Type of location event, e.g. self pin of the user location. */
PollHandlerRole, /**< The PollHandler for the event, if any. */
IsReplyRole, /**< Is the message a reply to another event. */
ReplyComponentType, /**< The type of component to visualise the reply message. */
ReplyEventIdRole, /**< The matrix ID of the message that was replied to. */
ReplyAuthorRole, /**< The author of the event that was replied to. */
ReplyDisplayRole, /**< The body of the message that was replied to. */
ReplyMediaInfoRole, /**< The media info of the message that was replied to. */
LinkPreviewerRole, /**< The link preview details. */
};
Q_ENUM(Roles)
explicit MessageContentModel(const Quotient::RoomEvent *event, NeoChatRoom *room);
/**
* @brief Get the given role value at the given index.
*
* @sa QAbstractItemModel::data
*/
[[nodiscard]] QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
/**
* @brief Number of rows in the model.
*
* @sa QAbstractItemModel::rowCount
*/
[[nodiscard]] int rowCount(const QModelIndex &parent = QModelIndex()) const override;
/**
* @brief Returns a mapping from Role enum values to role names.
*
* @sa Roles, QAbstractItemModel::roleNames()
*/
[[nodiscard]] QHash<int, QByteArray> roleNames() const override;
private:
NeoChatRoom *m_room = nullptr;
const Quotient::RoomEvent *m_event = nullptr;
QVector<MessageComponentType::Type> m_components;
void updateComponents();
LinkPreviewer *m_linkPreviewer = nullptr;
};

View File

@@ -2,6 +2,7 @@
// SPDX-License-Identifier: GPL-3.0-only
#include "messageeventmodel.h"
#include "linkpreviewer.h"
#include "messageeventmodel_logging.h"
#include "neochatconfig.h"
@@ -9,7 +10,6 @@
#include <Quotient/connection.h>
#include <Quotient/csapi/rooms.h>
#include <Quotient/events/redactionevent.h>
#include <Quotient/events/roommessageevent.h>
#include <Quotient/events/stickerevent.h>
#include <Quotient/user.h>
@@ -22,8 +22,6 @@
#include "enums/delegatetype.h"
#include "eventhandler.h"
#include "events/pollevent.h"
#include "linkpreviewer.h"
#include "messagecontentmodel.h"
#include "models/reactionmodel.h"
#include "texthandler.h"
@@ -33,6 +31,7 @@ QHash<int, QByteArray> MessageEventModel::roleNames() const
{
QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();
roles[DelegateTypeRole] = "delegateType";
roles[PlainText] = "plainText";
roles[EventIdRole] = "eventId";
roles[TimeRole] = "time";
roles[TimeStringRole] = "timeString";
@@ -41,6 +40,15 @@ QHash<int, QByteArray> MessageEventModel::roleNames() const
roles[HighlightRole] = "isHighlighted";
roles[SpecialMarksRole] = "marks";
roles[ProgressInfoRole] = "progressInfo";
roles[ShowLinkPreviewRole] = "showLinkPreview";
roles[LinkPreviewRole] = "linkPreview";
roles[MediaInfoRole] = "mediaInfo";
roles[IsReplyRole] = "isReply";
roles[ReplyAuthor] = "replyAuthor";
roles[ReplyIdRole] = "replyId";
roles[ReplyDelegateTypeRole] = "replyDelegateType";
roles[ReplyDisplayRole] = "replyDisplay";
roles[ReplyMediaInfoRole] = "replyMediaInfo";
roles[IsThreadedRole] = "isThreaded";
roles[ThreadRootRole] = "threadRoot";
roles[ShowAuthorRole] = "showAuthor";
@@ -56,8 +64,10 @@ QHash<int, QByteArray> MessageEventModel::roleNames() const
roles[IsRedactedRole] = "isRedacted";
roles[GenericDisplayRole] = "genericDisplay";
roles[IsPendingRole] = "isPending";
roles[ContentModelRole] = "contentModel";
roles[MediaInfoRole] = "mediaInfo";
roles[LatitudeRole] = "latitude";
roles[LongitudeRole] = "longitude";
roles[AssetRole] = "asset";
roles[PollHandlerRole] = "pollHandler";
return roles;
}
@@ -86,6 +96,7 @@ void MessageEventModel::setRoom(NeoChatRoom *room)
beginResetModel();
if (m_currentRoom) {
m_currentRoom->disconnect(this);
m_linkPreviewers.clear();
m_reactionModels.clear();
}
@@ -108,6 +119,14 @@ void MessageEventModel::setRoom(NeoChatRoom *room)
room->getPreviousContent(50);
}
lastReadEventId = room->lastFullyReadEventId();
connect(m_currentRoom, &NeoChatRoom::replyLoaded, this, [this](const auto &eventId, const auto &replyId) {
Q_UNUSED(replyId);
auto row = eventIdToRow(eventId);
if (row == -1) {
return;
}
Q_EMIT dataChanged(index(row, 0), index(row, 0), {ReplyDelegateTypeRole, ReplyDisplayRole, ReplyMediaInfoRole, ReplyAuthor});
});
connect(m_currentRoom, &Room::aboutToAddNewMessages, this, [this](RoomEventsRange events) {
for (auto &&event : events) {
@@ -219,6 +238,7 @@ void MessageEventModel::setRoom(NeoChatRoom *room)
moveReadMarker(toEventId);
});
connect(m_currentRoom, &Room::replacedEvent, this, [this](const RoomEvent *newEvent) {
refreshLastUserEvents(refreshEvent(newEvent->id()) - timelineBaseIndex());
const RoomMessageEvent *message = eventCast<const RoomMessageEvent>(newEvent);
if (message != nullptr) {
createEventObjects(message);
@@ -245,6 +265,10 @@ void MessageEventModel::setRoom(NeoChatRoom *room)
refreshEventRoles(event->id(), {ReadMarkersRole, ReadMarkersStringRole, ExcessReadMarkersRole});
}
});
connect(m_currentRoom, &Room::newFileTransfer, this, &MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::fileTransferProgress, this, &MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::fileTransferCompleted, this, &MessageEventModel::refreshEvent);
connect(m_currentRoom, &Room::fileTransferFailed, this, &MessageEventModel::refreshEvent);
connect(m_currentRoom->connection(), &Connection::ignoredUsersListChanged, this, [this] {
beginResetModel();
endResetModel();
@@ -415,6 +439,8 @@ void MessageEventModel::fetchMore(const QModelIndex &parent)
}
}
static LinkPreviewer *emptyLinkPreview = new LinkPreviewer;
QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
{
if (!checkIndex(idx, QAbstractItemModel::CheckIndexOption::IndexIsValid)) {
@@ -455,7 +481,9 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
const auto pendingIt = m_currentRoom->pendingEvents().crbegin() + std::min(row, timelineBaseIndex());
const auto &evt = isPending ? **pendingIt : **timelineIt;
EventHandler eventHandler(m_currentRoom, &evt);
EventHandler eventHandler;
eventHandler.setRoom(m_currentRoom);
eventHandler.setEvent(&evt);
if (role == Qt::DisplayRole) {
if (evt.isRedacted()) {
@@ -466,24 +494,16 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
return eventHandler.getRichBody();
}
if (role == ContentModelRole) {
if (!evt.isStateEvent()) {
return QVariant::fromValue<MessageContentModel *>(new MessageContentModel(&evt, m_currentRoom));
}
if (evt.isStateEvent()) {
if (evt.matrixType() == QStringLiteral("org.matrix.msc3672.beacon_info")) {
return QVariant::fromValue<MessageContentModel *>(new MessageContentModel(&evt, m_currentRoom));
}
}
return {};
}
if (role == GenericDisplayRole) {
return eventHandler.getGenericBody();
}
if (role == PlainText) {
return eventHandler.getPlainBody();
}
if (role == DelegateTypeRole) {
return DelegateType::typeForEvent(evt);
return eventHandler.getDelegateType();
}
if (role == AuthorRole) {
@@ -541,6 +561,46 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
return eventHandler.getTimeString(true, QLocale::ShortFormat, isPending, lastUpdated);
}
if (role == ShowLinkPreviewRole) {
return m_linkPreviewers.contains(evt.id());
}
if (role == LinkPreviewRole) {
if (m_linkPreviewers.contains(evt.id())) {
return QVariant::fromValue<LinkPreviewer *>(m_linkPreviewers[evt.id()].data());
} else {
return QVariant::fromValue<LinkPreviewer *>(emptyLinkPreview);
}
}
if (role == MediaInfoRole) {
return eventHandler.getMediaInfo();
}
if (role == IsReplyRole) {
return eventHandler.hasReply();
}
if (role == ReplyIdRole) {
return eventHandler.getReplyId();
}
if (role == ReplyDelegateTypeRole) {
return eventHandler.getReplyDelegateType();
}
if (role == ReplyAuthor) {
return eventHandler.getReplyAuthor();
}
if (role == ReplyDisplayRole) {
return eventHandler.getReplyRichBody();
}
if (role == ReplyMediaInfoRole) {
return eventHandler.getReplyMediaInfo();
}
if (role == IsThreadedRole) {
return eventHandler.isThreaded();
}
@@ -584,6 +644,18 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
return false;
}
if (role == LatitudeRole) {
return eventHandler.getLatitude();
}
if (role == LongitudeRole) {
return eventHandler.getLongitude();
}
if (role == AssetRole) {
return eventHandler.getLocationAssetType();
}
if (role == ReadMarkersRole) {
return eventHandler.getReadMarkers();
}
@@ -633,8 +705,8 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
return row < static_cast<int>(m_currentRoom->pendingEvents().size());
}
if (role == MediaInfoRole) {
return eventHandler.getMediaInfo();
if (role == PollHandlerRole) {
return QVariant::fromValue<PollHandler *>(m_currentRoom->poll(evt.id()));
}
return {};
@@ -654,6 +726,16 @@ void MessageEventModel::createEventObjects(const Quotient::RoomMessageEvent *eve
{
auto eventId = event->id();
if (m_linkPreviewers.contains(eventId)) {
if (!LinkPreviewer::hasPreviewableLinks(event)) {
m_linkPreviewers.remove(eventId);
}
} else {
if (LinkPreviewer::hasPreviewableLinks(event)) {
m_linkPreviewers[eventId] = QSharedPointer<LinkPreviewer>(new LinkPreviewer(m_currentRoom, event));
}
}
// ReactionModel handles updates to add and remove reactions, we only need to
// handle adding and removing whole models here.
if (m_reactionModels.contains(eventId)) {
@@ -681,7 +763,7 @@ void MessageEventModel::createEventObjects(const Quotient::RoomMessageEvent *eve
bool MessageEventModel::event(QEvent *event)
{
if (event->type() == QEvent::ApplicationPaletteChange) {
Q_EMIT dataChanged(index(0, 0), index(rowCount() - 1, 0), {AuthorRole, ReadMarkersRole});
Q_EMIT dataChanged(index(0, 0), index(rowCount() - 1, 0), {AuthorRole, ReplyAuthor, ReadMarkersRole});
}
return QObject::event(event);
}

View File

@@ -40,6 +40,7 @@ public:
*/
enum EventRoles {
DelegateTypeRole = Qt::UserRole + 1, /**< The delegate type of the message. */
PlainText, /**< Plain text representation of the message. */
EventIdRole, /**< The matrix event ID of the event. */
TimeRole, /**< The timestamp for when the event was sent (as a QDateTime). */
TimeStringRole, /**< The timestamp for when the event was sent as a string (in QLocale::ShortFormat). */
@@ -49,9 +50,18 @@ public:
SpecialMarksRole, /**< Whether the event is hidden or not. */
ProgressInfoRole, /**< Progress info when downloading files. */
GenericDisplayRole, /**< A generic string based upon the message type. */
ShowLinkPreviewRole, /**< Whether a link preview should be shown. */
LinkPreviewRole, /**< The link preview details. */
MediaInfoRole, /**< The media info for the event. */
ContentModelRole, /**< The MessageContentModel for the event. */
IsReplyRole, /**< Is the message a reply to another event. */
ReplyAuthor, /**< The author of the event that was replied to. */
ReplyIdRole, /**< The matrix ID of the message that was replied to. */
ReplyDelegateTypeRole, /**< The delegate type of the message that was replied to. */
ReplyDisplayRole, /**< The body of the message that was replied to. */
ReplyMediaInfoRole, /**< The media info of the message that was replied to. */
IsThreadedRole,
ThreadRootRole,
@@ -70,6 +80,10 @@ public:
AuthorDisplayNameRole, /**< The displayname for the event's sender; for name change events, the old displayname. */
IsRedactedRole, /**< Whether an event has been deleted. */
IsPendingRole, /**< Whether an event is waiting to be accepted by the server. */
LatitudeRole, /**< Latitude for a location event. */
LongitudeRole, /**< Longitude for a location event. */
AssetRole, /**< Type of location event, e.g. self pin of the user location. */
PollHandlerRole, /**< The PollHandler for the event, if any. */
LastRole, // Keep this last
};
Q_ENUM(EventRoles)
@@ -121,6 +135,7 @@ private:
bool movingEvent = false;
KFormat m_format;
QMap<QString, QSharedPointer<LinkPreviewer>> m_linkPreviewers;
QMap<QString, QSharedPointer<ReactionModel>> m_reactionModels;
[[nodiscard]] int timelineBaseIndex() const;

View File

@@ -127,8 +127,9 @@ QString MessageFilterModel::aggregateEventToString(int sourceRow) const
chunks.removeDuplicates();
// The author text is either "n users" if > 1 user or the matrix.to link to a single user.
QString userText = uniqueAuthors.length() > 1 ? i18ncp("n users", " %1 user ", " %1 users ", uniqueAuthors.length())
: QStringLiteral("<a href=\"https://matrix.to/#/%1\">%3</a> ")
: QStringLiteral("<a href=\"https://matrix.to/#/%1\" style=\"color: %2\">%3</a> ")
.arg(uniqueAuthors[0].toMap()[QStringLiteral("id")].toString(),
uniqueAuthors[0].toMap()[QStringLiteral("color")].toString(),
uniqueAuthors[0].toMap()[QStringLiteral("displayName")].toString().toHtmlEscaped());
QString chunksText;

View File

@@ -122,7 +122,9 @@ void NotificationsModel::loadData()
const auto &authorAvatar = avatar.isValid() && avatar.scheme() == QStringLiteral("mxc") ? avatar : QUrl();
const auto &roomEvent = eventCast<const RoomEvent>(notification.event.get());
EventHandler eventHandler(dynamic_cast<NeoChatRoom *>(room), roomEvent);
EventHandler eventHandler;
eventHandler.setRoom(dynamic_cast<NeoChatRoom *>(room));
eventHandler.setEvent(roomEvent);
beginInsertRows({}, m_notifications.length(), m_notifications.length());
m_notifications += Notification{
.roomId = notification.roomId,

View File

@@ -23,7 +23,7 @@ ReactionModel::ReactionModel(const Quotient::RoomMessageEvent *event, const NeoC
{
if (m_event != nullptr && m_room != nullptr) {
connect(m_room, &NeoChatRoom::updatedEvent, this, [this](const QString &eventId) {
if (m_event && m_event->id() == eventId) {
if (m_event->id() == eventId) {
updateReactions();
}
});
@@ -80,7 +80,7 @@ QVariant ReactionModel::data(const QModelIndex &index, int role) const
"%2 reacted with %3",
reaction.authors.count(),
text,
m_shortcodes.contains(reaction.reaction) ? m_shortcodes[reaction.reaction] : reactionText(reaction.reaction));
reactionText(reaction.reaction));
return text;
}
@@ -111,7 +111,6 @@ void ReactionModel::updateReactions()
beginResetModel();
m_reactions.clear();
m_shortcodes.clear();
const auto &annotations = m_room->relatedEvents(*m_event, Quotient::EventRelation::AnnotationType);
if (annotations.isEmpty()) {
@@ -126,9 +125,6 @@ void ReactionModel::updateReactions()
}
if (const auto &e = eventCast<const Quotient::ReactionEvent>(a)) {
reactions[e->key()].append(m_room->user(e->senderId()));
if (e->contentJson()[QStringLiteral("shortcode")].toString().length()) {
m_shortcodes[e->key()] = e->contentJson()[QStringLiteral("shortcode")].toString().toHtmlEscaped();
}
}
}
@@ -162,18 +158,8 @@ QHash<int, QByteArray> ReactionModel::roleNames() const
};
}
QString ReactionModel::reactionText(QString text) const
QString ReactionModel::reactionText(const QString &text)
{
text = text.toHtmlEscaped();
if (text.startsWith(QStringLiteral("mxc://"))) {
static QFont font;
static int size = font.pixelSize();
if (size == -1) {
size = font.pointSizeF() * 1.333;
}
return QStringLiteral("<img src=\"%1\" width=\"%2\" height=\"%2\">")
.arg(m_room->connection()->makeMediaUrl(QUrl(text)).toString(), QString::number(size));
}
const auto isEmoji = [](const QString &text) {
#ifdef HAVE_ICU
QTextBoundaryFinder finder(QTextBoundaryFinder::Grapheme, text);

View File

@@ -71,9 +71,8 @@ private:
const NeoChatRoom *m_room;
const Quotient::RoomMessageEvent *m_event;
QList<Reaction> m_reactions;
QMap<QString, QString> m_shortcodes;
void updateReactions();
QString reactionText(QString text) const;
static QString reactionText(const QString &text);
};
Q_DECLARE_METATYPE(ReactionModel *)

View File

@@ -298,7 +298,30 @@ QVariant RoomListModel::data(const QModelIndex &index, int role) const
return room->topic();
}
if (role == CategoryRole) {
return category(room);
if (room->joinState() == JoinState::Invite) {
return NeoChatRoomType::Invited;
}
if (room->isFavourite()) {
return NeoChatRoomType::Favorite;
}
if (room->isLowPriority()) {
return NeoChatRoomType::Deprioritized;
}
if (room->isDirectChat()) {
return NeoChatRoomType::Direct;
}
const RoomCreateEvent *creationEvent = room->creation();
if (!creationEvent) {
return NeoChatRoomType::Normal;
}
QJsonObject contentJson = creationEvent->contentJson();
QJsonObject::const_iterator typeIter = contentJson.find("type"_ls);
if (typeIter != contentJson.end()) {
if (typeIter.value().toString() == "m.space"_ls) {
return NeoChatRoomType::Space;
}
}
return NeoChatRoomType::Normal;
}
if (role == NotificationCountRole) {
return room->notificationCount();
@@ -325,7 +348,9 @@ QVariant RoomListModel::data(const QModelIndex &index, int role) const
if (room->lastEvent() == nullptr || room->lastEventIsSpoiler()) {
return QString();
}
EventHandler eventHandler(room, room->lastEvent());
EventHandler eventHandler;
eventHandler.setRoom(room);
eventHandler.setEvent(room->lastEvent());
return eventHandler.subtitleText();
}
if (role == AvatarImageRole) {
@@ -338,7 +363,7 @@ QVariant RoomListModel::data(const QModelIndex &index, int role) const
return room->isSpace();
}
if (role == IsChildSpaceRole) {
return SpaceHierarchyCache::instance().isChild(room->id());
return SpaceHierarchyCache::instance().isChildSpace(room->id());
}
if (role == ReplacementIdRole) {
return room->successorId();
@@ -383,26 +408,6 @@ QHash<int, QByteArray> RoomListModel::roleNames() const
return roles;
}
NeoChatRoomType::Types RoomListModel::category(NeoChatRoom *room)
{
if (room->isSpace()) {
return NeoChatRoomType::Space;
}
if (room->joinState() == JoinState::Invite) {
return NeoChatRoomType::Invited;
}
if (room->isFavourite()) {
return NeoChatRoomType::Favorite;
}
if (room->isLowPriority()) {
return NeoChatRoomType::Deprioritized;
}
if (room->isDirectChat()) {
return NeoChatRoomType::Direct;
}
return NeoChatRoomType::Normal;
}
QString RoomListModel::categoryName(int category)
{
switch (category) {

View File

@@ -116,11 +116,6 @@ public:
*/
Q_INVOKABLE [[nodiscard]] NeoChatRoom *roomAt(int row) const;
/**
* @brief The category for the given room.
*/
static NeoChatRoomType::Types category(NeoChatRoom *room);
/**
* @brief Return a string to represent the given room category.
*/

View File

@@ -3,9 +3,8 @@
#include "searchmodel.h"
#include "enums/delegatetype.h"
#include "eventhandler.h"
#include "models/messagecontentmodel.h"
#include "messageeventmodel.h"
#include "neochatroom.h"
#include <QGuiApplication>
@@ -80,9 +79,13 @@ QVariant SearchModel::data(const QModelIndex &index, int role) const
auto row = index.row();
const auto &event = *m_result->results[row].result;
EventHandler eventHandler(m_room, &event);
EventHandler eventHandler;
eventHandler.setRoom(m_room);
eventHandler.setEvent(&event);
switch (role) {
case DisplayRole:
return eventHandler.getRichBody();
case ShowAuthorRole:
return true;
case AuthorRole:
@@ -102,8 +105,22 @@ QVariant SearchModel::data(const QModelIndex &index, int role) const
return false;
case ShowReadMarkersRole:
return false;
case IsReplyRole:
return eventHandler.hasReply();
case ReplyIdRole:
return eventHandler.hasReply();
case ReplyAuthorRole:
return eventHandler.getReplyAuthor();
case ReplyDelegateTypeRole:
return eventHandler.getReplyDelegateType();
case ReplyDisplayRole:
return eventHandler.getReplyRichBody();
case ReplyMediaInfoRole:
return eventHandler.getReplyMediaInfo();
case IsPendingRole:
return false;
case ShowLinkPreviewRole:
return false;
case HighlightRole:
return eventHandler.isHighlighted();
case EventIdRole:
@@ -112,17 +129,6 @@ QVariant SearchModel::data(const QModelIndex &index, int role) const
return eventHandler.isThreaded();
case ThreadRootRole:
return eventHandler.threadRoot();
case ContentModelRole: {
if (!event.isStateEvent()) {
return QVariant::fromValue<MessageContentModel *>(new MessageContentModel(&event, m_room));
}
if (event.isStateEvent()) {
if (event.matrixType() == QStringLiteral("org.matrix.msc3672.beacon_info")) {
return QVariant::fromValue<MessageContentModel *>(new MessageContentModel(&event, m_room));
}
}
return {};
}
}
return DelegateType::Message;
}
@@ -140,6 +146,7 @@ QHash<int, QByteArray> SearchModel::roleNames() const
{
return {
{DelegateTypeRole, "delegateType"},
{DisplayRole, "display"},
{AuthorRole, "author"},
{ShowSectionRole, "showSection"},
{SectionRole, "section"},
@@ -150,15 +157,25 @@ QHash<int, QByteArray> SearchModel::roleNames() const
{ExcessReadMarkersRole, "excessReadMarkers"},
{HighlightRole, "isHighlighted"},
{ReadMarkersString, "readMarkersString"},
{PlainTextRole, "plainText"},
{VerifiedRole, "verified"},
{ProgressInfoRole, "progressInfo"},
{ShowReactionsRole, "showReactions"},
{IsReplyRole, "isReply"},
{ReplyAuthorRole, "replyAuthor"},
{ReplyIdRole, "replyId"},
{ReplyDelegateTypeRole, "replyDelegateType"},
{ReplyDisplayRole, "replyDisplay"},
{ReplyMediaInfoRole, "replyMediaInfo"},
{ReactionRole, "reaction"},
{ReadMarkersRole, "readMarkers"},
{IsPendingRole, "isPending"},
{ShowReadMarkersRole, "showReadMarkers"},
{MimeTypeRole, "mimeType"},
{ShowLinkPreviewRole, "showLinkPreview"},
{LinkPreviewRole, "linkPreview"},
{IsThreadedRole, "isThreaded"},
{ThreadRootRole, "threadRoot"},
{ContentModelRole, "contentModel"},
};
}
@@ -174,6 +191,19 @@ void SearchModel::setRoom(NeoChatRoom *room)
}
m_room = room;
Q_EMIT roomChanged();
connect(m_room, &NeoChatRoom::replyLoaded, this, [this](const auto &eventId, const auto &replyId) {
Q_UNUSED(replyId);
const auto &results = m_result->results;
auto it = std::find_if(results.begin(), results.end(), [eventId](const auto &event) {
return event.result->id() == eventId;
});
if (it == results.end()) {
return;
}
auto row = it - results.begin();
Q_EMIT dataChanged(index(row, 0), index(row, 0), {ReplyDelegateTypeRole, ReplyDisplayRole, ReplyMediaInfoRole, ReplyAuthorRole});
});
}
bool SearchModel::searching() const

View File

@@ -51,7 +51,8 @@ public:
* since the same delegates are used.
*/
enum Roles {
DelegateTypeRole = Qt::DisplayRole + 1,
DisplayRole = Qt::DisplayRole,
DelegateTypeRole,
ShowAuthorRole,
AuthorRole,
ShowSectionRole,
@@ -62,15 +63,25 @@ public:
ExcessReadMarkersRole,
HighlightRole,
ReadMarkersString,
PlainTextRole,
VerifiedRole,
ProgressInfoRole,
ShowReactionsRole,
IsReplyRole,
ReplyAuthorRole,
ReplyIdRole,
ReplyDelegateTypeRole,
ReplyDisplayRole,
ReplyMediaInfoRole,
ReactionRole,
ReadMarkersRole,
IsPendingRole,
ShowReadMarkersRole,
MimeTypeRole,
ShowLinkPreviewRole,
LinkPreviewRole,
IsThreadedRole,
ThreadRootRole,
ContentModelRole,
};
Q_ENUM(Roles)
explicit SearchModel(QObject *parent = nullptr);

View File

@@ -106,10 +106,7 @@ bool SortFilterRoomListModel::filterAcceptsRow(int source_row, const QModelIndex
}
if (m_activeSpaceId.isEmpty()) {
if (!SpaceHierarchyCache::instance().isChild(sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::RoomIdRole).toString())) {
return acceptRoom;
}
return false;
return acceptRoom;
} else {
const auto &rooms = SpaceHierarchyCache::instance().getRoomListForSpace(m_activeSpaceId, false);
return std::find(rooms.begin(), rooms.end(), sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::RoomIdRole).toString())

View File

@@ -244,20 +244,6 @@ QVariant SpaceChildrenModel::data(const QModelIndex &index, int role) const
}
return QVariant::fromValue(nullptr);
}
if (role == OrderRole) {
if (child->parentItem() == nullptr) {
return QString();
}
const auto childState = child->parentItem()->childStateContent(child);
return childState[QLatin1String("order")].toString();
}
if (role == ChildTimestampRole) {
if (child->parentItem() == nullptr) {
return QString();
}
const auto childState = child->parentItem()->childState(child);
return childState[QLatin1String("origin_server_ts")].toString();
}
return {};
}
@@ -339,8 +325,6 @@ QHash<int, QByteArray> SpaceChildrenModel::roleNames() const
roles[IsDeclaredParentRole] = "isDeclaredParent";
roles[CanRemove] = "canRemove";
roles[ParentRoomRole] = "parentRoom";
roles[OrderRole] = "order";
roles[ChildTimestampRole] = "childTimestamp";
return roles;
}

View File

@@ -51,8 +51,6 @@ public:
IsDeclaredParentRole,
CanRemove,
ParentRoomRole,
OrderRole,
ChildTimestampRole,
};
explicit SpaceChildrenModel(QObject *parent = nullptr);

View File

@@ -26,27 +26,10 @@ QString SpaceChildSortFilterModel::filterText() const
bool SpaceChildSortFilterModel::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const
{
if (source_left.data(SpaceChildrenModel::IsSpaceRole).toBool() && source_right.data(SpaceChildrenModel::IsSpaceRole).toBool()) {
if (!source_left.data(SpaceChildrenModel::OrderRole).toString().isEmpty() && !source_right.data(SpaceChildrenModel::OrderRole).toString().isEmpty()) {
return QString::compare(source_left.data(SpaceChildrenModel::OrderRole).toString(), source_right.data(SpaceChildrenModel::OrderRole).toString())
< 0;
}
return source_left.data(SpaceChildrenModel::ChildTimestampRole).toDateTime() > source_right.data(SpaceChildrenModel::ChildTimestampRole).toDateTime();
}
if (source_left.data(SpaceChildrenModel::IsSpaceRole).toBool()) {
return true;
} else if (source_right.data(SpaceChildrenModel::IsSpaceRole).toBool()) {
if (!source_left.data(SpaceChildrenModel::IsSpaceRole).toBool() && source_right.data(SpaceChildrenModel::IsSpaceRole).toBool()) {
return false;
}
if (!source_left.data(SpaceChildrenModel::OrderRole).toString().isEmpty() && !source_right.data(SpaceChildrenModel::OrderRole).toString().isEmpty()) {
return QString::compare(source_left.data(SpaceChildrenModel::OrderRole).toString(), source_right.data(SpaceChildrenModel::OrderRole).toString()) < 0;
}
if (!source_left.data(SpaceChildrenModel::OrderRole).toString().isEmpty()) {
return true;
} else if (!source_right.data(SpaceChildrenModel::OrderRole).toString().isEmpty()) {
return false;
}
return source_left.data(SpaceChildrenModel::ChildTimestampRole).toDateTime() > source_right.data(SpaceChildrenModel::ChildTimestampRole).toDateTime();
return true;
}
bool SpaceChildSortFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const

View File

@@ -141,22 +141,6 @@ bool SpaceTreeItem::isSpace() const
return m_isSpace;
}
QJsonObject SpaceTreeItem::childState(const SpaceTreeItem *child) const
{
if (child == nullptr) {
return {};
}
if (child->parentItem() != this) {
return {};
}
for (const auto &childState : m_childStates) {
if (childState->stateKey() == child->id()) {
return childState->fullJson();
}
}
return {};
}
QJsonObject SpaceTreeItem::childStateContent(const SpaceTreeItem *child) const
{
if (child == nullptr) {

View File

@@ -125,11 +125,6 @@ public:
*/
bool isSpace() const;
/**
* @brief Return the m.space.child stripped state Json for the given child.
*/
QJsonObject childState(const SpaceTreeItem *child) const;
/**
* @brief Return the m.space.child state event content for the given child.
*/

View File

@@ -8,9 +8,7 @@
#include "controller.h"
#include "jobs/neochatchangepasswordjob.h"
#include "jobs/neochatdeactivateaccountjob.h"
#include "neochatroom.h"
#include "roommanager.h"
#include "spacehierarchycache.h"
#include <Quotient/connection.h>
#include <Quotient/quotient_common.h>
@@ -99,21 +97,6 @@ void NeoChatConnection::connectSignals()
Q_EMIT directChatInvitesChanged();
}
});
connect(&SpaceHierarchyCache::instance(), &SpaceHierarchyCache::spaceHierarchyChanged, this, [this]() {
Q_EMIT homeNotificationsChanged();
});
for (const auto room : allRooms()) {
connect(room, &NeoChatRoom::unreadStatsChanged, this, [this, room]() {
if (room != nullptr) {
auto category = RoomListModel::category(static_cast<NeoChatRoom *>(room));
if (!SpaceHierarchyCache::instance().isChild(room->id()) && (category == NeoChatRoomType::Normal || category == NeoChatRoomType::Favorite)
&& room->successorId().isEmpty()) {
Q_EMIT homeNotificationsChanged();
}
}
});
}
}
void NeoChatConnection::logout(bool serverSideLogout)
@@ -257,7 +240,7 @@ void NeoChatConnection::createRoom(const QString &name, const QString &topic, co
Q_EMIT Controller::instance().errorOccured(i18n("Room creation failed: %1", job->errorString()), {});
});
connectSingleShot(this, &Connection::newRoom, this, [](Room *room) {
RoomManager::instance().resolveResource(room->id());
RoomManager::instance().enterRoom(dynamic_cast<NeoChatRoom *>(room));
});
}
@@ -289,7 +272,7 @@ void NeoChatConnection::createSpace(const QString &name, const QString &topic, c
Q_EMIT Controller::instance().errorOccured(i18n("Space creation failed: %1", job->errorString()), {});
});
connectSingleShot(this, &Connection::newRoom, this, [](Room *room) {
RoomManager::instance().resolveResource(room->id());
RoomManager::instance().enterRoom(dynamic_cast<NeoChatRoom *>(room));
});
}
@@ -312,9 +295,9 @@ void NeoChatConnection::openOrCreateDirectChat(User *user)
const auto existing = directChats();
if (existing.contains(user)) {
const auto room = this->room(existing.value(user));
const auto room = static_cast<NeoChatRoom *>(this->room(existing.value(user)));
if (room) {
RoomManager::instance().resolveResource(room->id());
RoomManager::instance().enterRoom(room);
return;
}
}
@@ -336,29 +319,6 @@ qsizetype NeoChatConnection::directChatNotifications() const
return notifications;
}
qsizetype NeoChatConnection::homeNotifications() const
{
qsizetype notifications = 0;
QStringList added;
const auto &spaceHierarchyCache = SpaceHierarchyCache::instance();
for (const auto &room : allRooms()) {
auto category = RoomListModel::category(static_cast<NeoChatRoom *>(room));
if (!added.contains(room->id()) && room->joinState() == JoinState::Join && !room->isDirectChat() && !spaceHierarchyCache.isChild(room->id())
&& room->successorId().isEmpty()) {
switch (category) {
case NeoChatRoomType::Normal:
case NeoChatRoomType::Favorite:
notifications += room->notificationCount();
break;
default:
notifications += room->highlightCount();
}
added += room->id();
}
}
return notifications;
}
bool NeoChatConnection::directChatInvites() const
{
auto inviteRooms = rooms(JoinState::Invite);

View File

@@ -32,11 +32,6 @@ class NeoChatConnection : public Quotient::Connection
*/
Q_PROPERTY(qsizetype directChatNotifications READ directChatNotifications NOTIFY directChatNotificationsChanged)
/**
* @brief The total number of notifications for all rooms in the home tab.
*/
Q_PROPERTY(qsizetype homeNotifications READ homeNotifications NOTIFY homeNotificationsChanged)
/**
* @brief Whether there is at least one invite to a direct chat.
*/
@@ -114,7 +109,6 @@ public:
Q_INVOKABLE void openOrCreateDirectChat(Quotient::User *user);
qsizetype directChatNotifications() const;
qsizetype homeNotifications() const;
bool directChatInvites() const;
// note: this is intentionally a copied QString because
@@ -129,7 +123,6 @@ public:
Q_SIGNALS:
void labelChanged();
void directChatNotificationsChanged();
void homeNotificationsChanged();
void directChatInvitesChanged();
void isOnlineChanged();
void passwordStatus(NeoChatConnection::PasswordStatus status);

View File

@@ -42,7 +42,6 @@
#include "neochatconfig.h"
#include "notificationsmanager.h"
#include "roomlastmessageprovider.h"
#include "spacehierarchycache.h"
#include "texthandler.h"
#include "urlhelper.h"
#include "utils.h"
@@ -126,16 +125,6 @@ NeoChatRoom::NeoChatRoom(Connection *connection, QString roomId, JoinState joinS
Q_EMIT urlPreviewEnabledChanged();
}
});
connect(&SpaceHierarchyCache::instance(), &SpaceHierarchyCache::spaceHierarchyChanged, this, [this]() {
if (isSpace()) {
Q_EMIT childrenNotificationCountChanged();
}
});
connect(&SpaceHierarchyCache::instance(), &SpaceHierarchyCache::spaceNotifcationCountChanged, this, [this](const QStringList &spaces) {
if (spaces.contains(id())) {
Q_EMIT childrenNotificationCountChanged();
}
});
}
bool NeoChatRoom::hasFileUploading() const
@@ -513,7 +502,9 @@ void NeoChatRoom::postHtmlMessage(const QString &text,
}
if (isThread) {
EventHandler eventHandler(this, &**replyIt);
EventHandler eventHandler;
eventHandler.setRoom(this);
eventHandler.setEvent(&**replyIt);
const bool isFallingBack = !eventHandler.isThreaded();
@@ -560,7 +551,9 @@ void NeoChatRoom::postHtmlMessage(const QString &text,
if (isReply) {
const auto &replyEvt = **replyIt;
EventHandler eventHandler(this, &**replyIt);
EventHandler eventHandler;
eventHandler.setRoom(this);
eventHandler.setEvent(&**replyIt);
// clang-format off
QJsonObject json{
@@ -1289,14 +1282,6 @@ bool NeoChatRoom::isSpace()
return creationEvent->roomType() == RoomType::Space;
}
qsizetype NeoChatRoom::childrenNotificationCount()
{
if (!isSpace()) {
return 0;
}
return SpaceHierarchyCache::instance().notificationCountForSpace(id());
}
void NeoChatRoom::addChild(const QString &childId, bool setChildParent, bool canonical, bool suggested)
{
if (!isSpace()) {

View File

@@ -126,13 +126,6 @@ class NeoChatRoom : public Quotient::Room
*/
Q_PROPERTY(bool isSpace READ isSpace CONSTANT)
/**
* @brief The number of notifications in this room's children.
*
* Will always return 0 if this is not a space.
*/
Q_PROPERTY(qsizetype childrenNotificationCount READ childrenNotificationCount NOTIFY childrenNotificationCountChanged)
/**
* @brief Whether the local user has an invite to the room.
*
@@ -533,8 +526,6 @@ public:
[[nodiscard]] bool isSpace();
qsizetype childrenNotificationCount();
/**
* @brief Add the given room as a child.
*
@@ -824,7 +815,6 @@ Q_SIGNALS:
void parentIdsChanged();
void canonicalParentChanged();
void lastActiveTimeChanged();
void childrenNotificationCountChanged();
void isInviteChanged();
void readOnlyChanged();
void displayNameChanged();

View File

@@ -216,7 +216,7 @@ void NotificationsManager::postNotification(NeoChatRoom *room,
auto connection = dynamic_cast<NeoChatConnection *>(Controller::instance().accounts().get(room->localUser()->id()));
Controller::instance().setActiveConnection(connection);
RoomManager::instance().setConnection(connection);
RoomManager::instance().resolveResource(room->id());
RoomManager::instance().enterRoom(room);
});
if (canReply) {
@@ -251,7 +251,7 @@ void NotificationsManager::postInviteNotification(NeoChatRoom *rawRoom, const QS
}
WindowController::instance().showAndRaiseWindow(notification->xdgActivationToken());
notification->close();
RoomManager::instance().resolveResource(room->id());
RoomManager::instance().enterRoom(room);
});
const auto acceptAction = notification->addAction(i18nc("@action:button The thing being accepted is an invitation to chat", "Accept"));

View File

@@ -40,8 +40,9 @@ FormCard.FormCardPage {
if (fileDialog) {
return;
}
fileDialog = openFileDialog.createObject(this);
fileDialog.chosen.connect(receivedSource => {
fileDialog.chosen.connect((receivedSource) => {
if (!receivedSource) {
return;
}
@@ -136,9 +137,7 @@ FormCard.FormCardPage {
visible: root.connection !== undefined && root.connection.canChangePassword === false
text: i18n("Your server doesn't support changing your password")
}
FormCard.FormDelegateSeparator {
visible: root.connection !== undefined && root.connection.canChangePassword === false
}
FormCard.FormDelegateSeparator { visible: root.connection !== undefined && root.connection.canChangePassword === false }
FormCard.FormTextFieldDelegate {
id: currentPassword
label: i18n("Current Password:")
@@ -213,11 +212,7 @@ FormCard.FormCardPage {
FormCard.FormButtonDelegate {
id: deactivateAccountButton
text: i18n("Deactivate Account")
onClicked: pageStack.pushDialogLayer("qrc:/org/kde/neochat/qml/ConfirmDeactivateAccountDialog.qml", {
connection: root.connection
}, {
title: i18nc("@title", "Confirm Deactivating Account")
})
onClicked: pageStack.pushDialogLayer("qrc:/org/kde/neochat/qml/ConfirmDeactivateAccountDialog.qml", {connection: root.connection}, {title: i18nc("@title", "Confirm Deactivating Account")})
}
}

View File

@@ -24,30 +24,26 @@ QQC2.Menu {
connection: root.connection
}, {
title: i18n("Account editor")
})
});
}
QQC2.MenuItem {
text: i18n("Notification settings")
icon.name: "notifications"
onTriggered: pageStack.pushDialogLayer("qrc:/org/kde/neochat/qml/SettingsPage.qml", {
defaultPage: "notifications",
connection: root.connection
connection: root.connection,
}, {
title: i18n("Configure"),
width: Kirigami.Units.gridUnit * 50,
height: Kirigami.Units.gridUnit * 42
})
title: i18n("Configure")
});
}
QQC2.MenuItem {
text: i18n("Devices")
icon.name: "computer-symbolic"
onTriggered: pageStack.pushDialogLayer("qrc:/org/kde/neochat/qml/SettingsPage.qml", {
defaultPage: "devices",
connection: root.connection
connection: root.connection,
}, {
title: i18n("Configure"),
width: Kirigami.Units.gridUnit * 50,
height: Kirigami.Units.gridUnit * 42
title: i18n("Configure")
})
}
QQC2.MenuItem {

View File

@@ -80,7 +80,7 @@ FormCard.FormCardPage {
connection: accountDelegate.connection
onAccepted: {
if (AccountRegistry.accountCount === 1) {
root.Window.window.close();
root.Window.window.close()
}
}
}
@@ -93,9 +93,7 @@ FormCard.FormCardPage {
}
}
}
FormCard.FormDelegateSeparator {
below: addAccountDelegate
}
FormCard.FormDelegateSeparator { below: addAccountDelegate }
FormCard.FormButtonDelegate {
id: addAccountDelegate
@@ -109,7 +107,7 @@ FormCard.FormCardPage {
target: Controller
function onConnectionAdded() {
if (pageStack.layers.depth > 2) {
pageStack.layers.pop();
pageStack.layers.pop()
}
}
}

View File

@@ -31,9 +31,7 @@ FormCard.FormCardPage {
Item {
Layout.fillWidth: true
}
QQC2.ButtonGroup {
id: themeGroup
}
QQC2.ButtonGroup { id: themeGroup }
ThemeRadioButton {
thin: timelineModeSetting.width < Kirigami.Units.gridUnit * 22
innerObject: [
@@ -198,9 +196,7 @@ FormCard.FormCardPage {
}
}
FormCard.FormDelegateSeparator {
below: compactRoomListDelegate
}
FormCard.FormDelegateSeparator { below: compactRoomListDelegate }
FormCard.FormCheckDelegate {
id: compactRoomListDelegate
@@ -212,11 +208,7 @@ FormCard.FormCardPage {
}
}
FormCard.FormDelegateSeparator {
above: compactRoomListDelegate
below: colorSchemeDelegate.item
visible: colorSchemeDelegate.visible
}
FormCard.FormDelegateSeparator { above: compactRoomListDelegate ; below: colorSchemeDelegate.item ; visible: colorSchemeDelegate.visible }
Loader {
id: colorSchemeDelegate
@@ -239,10 +231,7 @@ FormCard.FormCardPage {
}
}
FormCard.FormDelegateSeparator {
above: showFancyEffectsDelegate
below: hasWindowSystemDelegate
}
FormCard.FormDelegateSeparator { above: showFancyEffectsDelegate ; below: hasWindowSystemDelegate }
FormCard.FormCheckDelegate {
id: hasWindowSystemDelegate
@@ -256,10 +245,7 @@ FormCard.FormCardPage {
}
}
FormCard.FormDelegateSeparator {
above: hasWindowSystemDelegate
below: transparencyDelegate
}
FormCard.FormDelegateSeparator { above: hasWindowSystemDelegate; below: transparencyDelegate }
FormCard.AbstractFormDelegate {
id: transparencyDelegate
@@ -283,9 +269,7 @@ FormCard.FormCardPage {
}
Layout.fillWidth: true
HoverHandler {
id: sliderHover
}
HoverHandler { id: sliderHover }
QQC2.ToolTip.visible: sliderHover.hovered && !enabled
QQC2.ToolTip.text: i18n("Only enabled if the transparent chat page is enabled.")
}
@@ -296,11 +280,7 @@ FormCard.FormCardPage {
}
}
FormCard.FormDelegateSeparator {
above: transparencyDelegate
below: showLocalMessagesOnRightDelegate
visible: transparencyDelegate.visible
}
FormCard.FormDelegateSeparator { above: transparencyDelegate; below: showLocalMessagesOnRightDelegate; visible: transparencyDelegate.visible }
FormCard.FormCheckDelegate {
id: showLocalMessagesOnRightDelegate
@@ -308,27 +288,25 @@ FormCard.FormCardPage {
checked: Config.showLocalMessagesOnRight
enabled: !Config.isShowLocalMessagesOnRightImmutable && !Config.compactLayout
onToggled: {
Config.showLocalMessagesOnRight = checked;
Config.save();
Config.showLocalMessagesOnRight = checked
Config.save()
}
}
FormCard.FormDelegateSeparator {
above: showLocalMessagesOnRightDelegate
below: showLinkPreviewDelegate
}
FormCard.FormDelegateSeparator { above: showLocalMessagesOnRightDelegate; below: showLinkPreviewDelegate }
FormCard.FormCheckDelegate {
id: showLinkPreviewDelegate
text: i18n("Show links preview in the chat messages")
checked: Config.showLinkPreview
onToggled: {
Config.showLinkPreview = checked;
Config.save();
Config.showLinkPreview = checked
Config.save()
}
}
}
FormCard.FormHeader {
title: i18n("Show Avatar")
}
@@ -337,8 +315,8 @@ FormCard.FormCardPage {
text: i18n("In chat")
checked: Config.showAvatarInTimeline
onToggled: {
Config.showAvatarInTimeline = checked;
Config.save();
Config.showAvatarInTimeline = checked
Config.save()
}
enabled: !Config.isShowAvatarInTimelineImmutable
}
@@ -348,8 +326,8 @@ FormCard.FormCardPage {
checked: Config.showAvatarInRoomDrawer
enabled: !Config.isShowAvatarInRoomDrawerImmutable
onToggled: {
Config.showAvatarInRoomDrawer = checked;
Config.save();
Config.showAvatarInRoomDrawer = checked
Config.save()
}
}
}

View File

@@ -27,10 +27,11 @@ QQC2.Popup {
text: i18n("Choose local file")
onClicked: {
root.close();
var fileDialog = openFileDialog.createObject(QQC2.ApplicationWindow.overlay);
fileDialog.chosen.connect(path => root.chosen(path));
fileDialog.open();
root.close()
var fileDialog = openFileDialog.createObject(QQC2.ApplicationWindow.overlay)
fileDialog.chosen.connect(path => root.chosen(path))
fileDialog.open()
}
}
@@ -45,11 +46,11 @@ QQC2.Popup {
icon.name: 'insert-image'
text: i18n("Clipboard image")
onClicked: {
const path = StandardPaths.standardLocations(StandardPaths.CacheLocation)[0] + "/screenshots/" + (new Date()).getTime() + ".png";
const path = StandardPaths.standardLocations(StandardPaths.CacheLocation)[0] + "/screenshots/" + (new Date()).getTime() + ".png"
if (!Clipboard.saveImage(path)) {
return;
}
root.chosen(path);
root.chosen(path)
root.close();
}
}

View File

@@ -13,7 +13,7 @@ import org.kde.neochat
ColumnLayout {
id: root
signal attachmentCancelled
signal attachmentCancelled()
property string attachmentPath
@@ -47,7 +47,7 @@ ColumnLayout {
onClicked: {
let imageEditor = applicationWindow().pageStack.layers.push(imageEditorPage);
imageEditor.newPathChanged.connect(function (newPath) {
imageEditor.newPathChanged.connect(function(newPath) {
applicationWindow().pageStack.layers.pop();
root.attachmentPath = newPath;
});
@@ -61,7 +61,7 @@ ColumnLayout {
action: Kirigami.Action {
text: i18n("Cancel sending attachment")
icon.name: "dialog-close"
onTriggered: attachmentCancelled()
onTriggered: attachmentCancelled();
shortcut: "Escape"
}
QQC2.ToolTip.text: text
@@ -81,14 +81,14 @@ ColumnLayout {
onSourceChanged: {
// Reset source size height, which affect implicitHeight
sourceSize.height = -1;
sourceSize.height = -1
}
onSourceSizeChanged: {
if (implicitHeight > Kirigami.Units.gridUnit * 8) {
// This can save a lot of RAM when loading large images.
// It also improves visual quality for large images.
sourceSize.height = Kirigami.Units.gridUnit * 8;
sourceSize.height = Kirigami.Units.gridUnit * 8
}
}

View File

@@ -1,168 +0,0 @@
// SPDX-FileCopyrightText: 2022 Tobias Fella <tobias.fella@kde.org>
// SPDX-FileCopyrightText: 2024 James Graham <james.h.graham@protonmail.com>
// SPDX-License-Identifier: GPL-2.0-or-later
import QtQuick
import QtQuick.Controls as QQC2
import QtQuick.Layouts
import QtMultimedia
import org.kde.coreaddons
import org.kde.kirigami as Kirigami
import org.kde.neochat
/**
* @brief A component to show audio from a message.
*/
ColumnLayout {
id: root
/**
* @brief The NeoChatRoom the delegate is being displayed in.
*/
required property NeoChatRoom room
/**
* @brief The matrix ID of the message event.
*/
required property string eventId
/**
* @brief The display text of the message.
*/
required property string display
/**
* @brief The media info for the event.
*
* This should consist of the following:
* - source - The mxc URL for the media.
* - mimeType - The MIME type of the media (should be image/xxx for this delegate).
* - mimeIcon - The MIME icon name (should be image-xxx).
* - size - The file size in bytes.
* - width - The width in pixels of the audio media.
* - height - The height in pixels of the audio media.
* - tempInfo - mediaInfo (with the same properties as this except no tempInfo) for a temporary image while the file downloads.
*/
required property var mediaInfo
/**
* @brief FileTransferInfo for any downloading files.
*/
required property var fileTransferInfo
/**
* @brief Whether the media has been downloaded.
*/
readonly property bool downloaded: root.fileTransferInfo && root.fileTransferInfo.completed
onDownloadedChanged: if (downloaded) {
audio.play()
}
/**
* @brief The maximum width that the bubble's content can be.
*/
property real maxContentWidth: -1
MediaPlayer {
id: audio
onErrorOccurred: (error, errorString) => console.warn("Audio playback error:" + error + errorString)
audioOutput: AudioOutput {}
}
states: [
State {
name: "notDownloaded"
when: !root.fileTransferInfo.completed && !root.fileTransferInfo.active
PropertyChanges {
target: playButton
icon.name: "media-playback-start"
onClicked: root.room.downloadFile(root.eventId)
}
},
State {
name: "downloading"
when: root.fileTransferInfo.active && !root.fileTransferInfo.completed
PropertyChanges {
target: downloadBar
visible: true
}
PropertyChanges {
target: playButton
icon.name: "media-playback-stop"
onClicked: {
root.room.cancelFileTransfer(root.eventId)
}
}
},
State {
name: "paused"
when: root.fileTransferInfo.completed && (audio.playbackState === MediaPlayer.StoppedState || audio.playbackState === MediaPlayer.PausedState)
PropertyChanges {
target: playButton
icon.name: "media-playback-start"
onClicked: {
audio.source = root.fileTransferInfo.localPath;
audio.play()
}
}
},
State {
name: "playing"
when: root.fileTransferInfo.completed && audio.playbackState === MediaPlayer.PlayingState
PropertyChanges {
target: playButton
icon.name: "media-playback-pause"
onClicked: audio.pause()
}
}
]
RowLayout {
QQC2.ToolButton {
id: playButton
}
QQC2.Label {
text: root.display
wrapMode: Text.Wrap
Layout.fillWidth: true
}
}
QQC2.ProgressBar {
id: downloadBar
visible: false
Layout.fillWidth: true
from: 0
to: root.mediaInfo.size
value: root.fileTransferInfo.progress
}
RowLayout {
visible: audio.hasAudio
QQC2.Slider {
Layout.fillWidth: true
from: 0
to: audio.duration
value: audio.position
onMoved: audio.seek(value)
}
QQC2.Label {
visible: root.maxContentWidth > Kirigami.Units.gridUnit * 12
text: Format.formatDuration(audio.position) + "/" + Format.formatDuration(audio.duration)
}
}
QQC2.Label {
Layout.alignment: Qt.AlignRight
Layout.rightMargin: Kirigami.Units.smallSpacing
visible: audio.hasAudio && root.maxContentWidth < Kirigami.Units.gridUnit * 12
text: Format.formatDuration(audio.position) + "/" + Format.formatDuration(audio.duration)
}
}

142
src/qml/AudioDelegate.qml Normal file
View File

@@ -0,0 +1,142 @@
// SPDX-FileCopyrightText: 2022 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: GPL-2.0-or-later
import QtQuick
import QtQuick.Controls as QQC2
import QtQuick.Layouts
import QtMultimedia
import org.kde.coreaddons
import org.kde.kirigami as Kirigami
import org.kde.neochat
/**
* @brief A timeline delegate for an audio message.
*
* @inherit MessageDelegate
*/
MessageDelegate {
id: root
/**
* @brief The media info for the event.
*
* This should consist of the following:
* - source - The mxc URL for the media.
* - mimeType - The MIME type of the media (should be audio/xxx for this delegate).
* - mimeIcon - The MIME icon name (should be audio-xxx).
* - size - The file size in bytes.
* - duration - The length in seconds of the audio media.
*/
required property var mediaInfo
/**
* @brief Whether the media has been downloaded.
*/
readonly property bool downloaded: root.progressInfo && root.progressInfo.completed
onDownloadedChanged: audio.play()
onOpenContextMenu: RoomManager.viewEventMenu(eventId, author, delegateType, plainText, "", "", mediaInfo.mimeType, progressInfo)
bubbleContent: ColumnLayout {
MediaPlayer {
id: audio
source: root.progressInfo.localPath
}
states: [
State {
name: "notDownloaded"
when: !root.progressInfo.completed && !root.progressInfo.active
PropertyChanges {
target: playButton
icon.name: "media-playback-start"
onClicked: root.room.downloadFile(root.eventId)
}
},
State {
name: "downloading"
when: root.progressInfo.active && !root.progressInfo.completed
PropertyChanges {
target: downloadBar
visible: true
}
PropertyChanges {
target: playButton
icon.name: "media-playback-stop"
onClicked: {
root.room.cancelFileTransfer(root.eventId)
}
}
},
State {
name: "paused"
when: root.progressInfo.completed && (audio.playbackState === Audio.StoppedState || audio.playbackState === Audio.PausedState)
PropertyChanges {
target: playButton
icon.name: "media-playback-start"
onClicked: {
audio.play()
}
}
},
State {
name: "playing"
when: root.progressInfo.completed && audio.playbackState === Audio.PlayingState
PropertyChanges {
target: playButton
icon.name: "media-playback-pause"
onClicked: audio.pause()
}
}
]
RowLayout {
QQC2.ToolButton {
id: playButton
}
QQC2.Label {
text: root.display
wrapMode: Text.Wrap
Layout.fillWidth: true
}
}
QQC2.ProgressBar {
id: downloadBar
visible: false
Layout.fillWidth: true
from: 0
to: root.mediaInfo.size
value: root.progressInfo.progress
}
RowLayout {
visible: audio.hasAudio
QQC2.Slider {
Layout.fillWidth: true
from: 0
to: audio.duration
value: audio.position
onMoved: audio.seek(value)
}
QQC2.Label {
visible: root.contentMaxWidth > Kirigami.Units.gridUnit * 12
text: Format.formatDuration(audio.position) + "/" + Format.formatDuration(audio.duration)
}
}
QQC2.Label {
Layout.alignment: Qt.AlignRight
Layout.rightMargin: Kirigami.Units.smallSpacing
visible: audio.hasAudio && root.contentMaxWidth < Kirigami.Units.gridUnit * 12
text: Format.formatDuration(audio.position) + "/" + Format.formatDuration(audio.duration)
}
}
}

View File

@@ -15,8 +15,8 @@ Delegates.RoundedItemDelegate {
property url source
signal contextMenuRequested
signal selected
signal contextMenuRequested()
signal selected()
padding: Kirigami.Units.largeSpacing
@@ -24,9 +24,9 @@ Delegates.RoundedItemDelegate {
QQC2.ToolTip.text: text
QQC2.ToolTip.delay: Kirigami.Units.toolTipDelay
Accessible.onPressAction: selected()
Keys.onSpacePressed: selected()
Keys.onEnterPressed: selected()
Accessible.onPressAction: selected();
Keys.onSpacePressed: selected();
Keys.onEnterPressed: selected();
onPressAndHold: root.contextMenuRequested()

View File

@@ -44,8 +44,8 @@ Kirigami.Page {
icon.name: "im-ban-user"
QQC2.DialogButtonBox.buttonRole: QQC2.DialogButtonBox.AcceptRole
onClicked: {
root.room.ban(root.userId, reason.text);
root.closeDialog();
root.room.ban(root.userId, reason.text)
root.closeDialog()
}
}
QQC2.Button {

View File

@@ -22,11 +22,6 @@ import org.kde.neochat
QQC2.Control {
id: root
/**
* @brief The NeoChatRoom the delegate is being displayed in.
*/
required property NeoChatRoom room
/**
* @brief The message author.
*
@@ -66,28 +61,70 @@ QQC2.Control {
property bool showHighlight: false
/**
* @brief The model to visualise the content of the message.
* @brief The main delegate content item to show in the bubble.
*/
required property MessageContentModel contentModel
property Item content
/**
* @brief The ActionsHandler object to use.
*
* This is expected to have the correct room set otherwise messages will be sent
* to the wrong room.
* @brief Whether this message is replying to another.
*/
property ActionsHandler actionsHandler
property bool isReply: false
/**
* @brief The matrix ID of the reply event.
*/
required property var replyId
/**
* @brief The reply author.
*
* This should consist of the following:
* - id - The matrix ID of the reply author.
* - isLocalUser - Whether the reply author is the local user.
* - avatarSource - The mxc URL for the reply author's avatar in the current room.
* - avatarMediaId - The media ID of the reply author's avatar.
* - avatarUrl - The mxc URL for the reply author's avatar.
* - displayName - The display name of the reply author.
* - display - The name of the reply author.
* - color - The color for the reply author.
* - object - The Quotient::User object for the reply author.
*
* @sa Quotient::User
*/
required property var replyAuthor
/**
* @brief The delegate type of the message replied to.
*/
required property int replyDelegateType
/**
* @brief The display text of the message replied to.
*/
required property string replyDisplay
/**
* @brief The media info for the reply event.
*
* This could be an image, audio, video or file.
*
* This should consist of the following:
* - source - The mxc URL for the media.
* - mimeType - The MIME type of the media.
* - mimeIcon - The MIME icon name.
* - size - The file size in bytes.
* - duration - The length in seconds of the audio media (audio/video only).
* - width - The width in pixels of the audio media (image/video only).
* - height - The height in pixels of the audio media (image/video only).
* - tempInfo - mediaInfo (with the same properties as this except no tempInfo) for a temporary image while the file downloads (image/video only).
*/
required property var replyMediaInfo
/**
* @brief Whether the bubble background should be shown.
*/
property alias showBackground: bubbleBackground.visible
/**
* @brief The timeline ListView this component is being used in.
*/
required property ListView timeline
/**
* @brief The maximum width that the bubble's content can be.
*/
@@ -98,26 +135,11 @@ QQC2.Control {
*/
signal replyClicked(string eventID)
/**
* @brief The user selected text has changed.
*/
signal selectedTextChanged(string selectedText)
/**
* @brief Request a context menu be show for the message.
*/
signal showMessageMenu()
contentItem: ColumnLayout {
id: contentColumn
spacing: Kirigami.Units.smallSpacing
RowLayout {
id: headerRow
Layout.maximumWidth: root.maxContentWidth
implicitHeight: Math.max(nameButton.implicitHeight, timeLabel.implicitHeight)
visible: root.showAuthor
QQC2.AbstractButton {
id: nameButton
Layout.fillWidth: true
contentItem: QQC2.Label {
text: root.author.displayName
@@ -130,7 +152,6 @@ QQC2.Control {
onClicked: RoomManager.resolveResource(root.author.id, "mention")
}
QQC2.Label {
id: timeLabel
text: root.timeString
horizontalAlignment: Text.AlignRight
color: Kirigami.Theme.disabledTextColor
@@ -143,19 +164,35 @@ QQC2.Control {
}
}
}
Repeater {
id: contentRepeater
model: root.contentModel
delegate: MessageComponentChooser {
room: root.room
actionsHandler: root.actionsHandler
timeline: root.timeline
maxContentWidth: root.maxContentWidth
Loader {
id: replyLoader
Layout.fillWidth: true
Layout.maximumWidth: root.maxContentWidth
onReplyClicked: (eventId) => {root.replyClicked(eventId)}
onSelectedTextChanged: (selectedText) => {root.selectedTextChanged(selectedText);}
onShowMessageMenu: root.showMessageMenu()
active: root.isReply && root.replyDelegateType !== DelegateType.Other
visible: active
sourceComponent: ReplyComponent {
author: root.replyAuthor
type: root.replyDelegateType
display: root.replyDisplay
mediaInfo: root.replyMediaInfo
contentMaxWidth: root.maxContentWidth
}
Connections {
target: replyLoader.item
function onReplyClicked() {
replyClicked(root.replyId)
}
}
}
Item {
id: contentParent
Layout.fillWidth: true
Layout.maximumWidth: root.maxContentWidth
implicitWidth: root.content ? root.content.implicitWidth : 0
implicitHeight: root.content ? root.content.implicitHeight : 0
}
}
@@ -165,22 +202,28 @@ QQC2.Control {
Kirigami.Theme.colorSet: Kirigami.Theme.View
Kirigami.Theme.inherit: false
color: if (root.author.isLocalUser) {
return Kirigami.ColorUtils.tintWithAlpha(Kirigami.Theme.backgroundColor, Kirigami.Theme.highlightColor, 0.15);
return Kirigami.ColorUtils.tintWithAlpha(Kirigami.Theme.backgroundColor, Kirigami.Theme.highlightColor, 0.15)
} else if (root.showHighlight) {
return Kirigami.Theme.positiveBackgroundColor;
return Kirigami.Theme.positiveBackgroundColor
} else {
return Kirigami.Theme.backgroundColor;
return Kirigami.Theme.backgroundColor
}
radius: Kirigami.Units.smallSpacing
shadow {
size: Kirigami.Units.smallSpacing
size: Kirigami.Units.smallSpacing
color: root.showHighlight ? Qt.rgba(0.0, 0.0, 0.0, 0.10) : Qt.rgba(Kirigami.Theme.textColor.r, Kirigami.Theme.textColor.g, Kirigami.Theme.textColor.b, 0.10)
}
Behavior on color {
ColorAnimation {
duration: Kirigami.Units.shortDuration
}
ColorAnimation { duration: Kirigami.Units.shortDuration }
}
}
onContentChanged: {
if (!root.content) {
return;
}
root.content.parent = contentParent;
root.content.anchors.fill = contentParent;
}
}

View File

@@ -20,7 +20,7 @@ LoginStep {
url: "http://localhost:20847"
implicitHeight: 500
onLoadingChanged: {
webview.runJavaScript("document.body.style.background = '" + Kirigami.Theme.backgroundColor + "'");
webview.runJavaScript("document.body.style.background = '" + Kirigami.Theme.backgroundColor + "'")
}
Timer {
@@ -29,15 +29,15 @@ LoginStep {
running: true
interval: 300
onTriggered: {
if (!webview.visible) {
return;
if(!webview.visible) {
return
}
webview.runJavaScript("!!grecaptcha ? grecaptcha.getResponse() : \"\"", function (response) {
if (!webview.visible || !response)
return;
webview.runJavaScript("!!grecaptcha ? grecaptcha.getResponse() : \"\"", function(response){
if(!webview.visible || !response)
return
timer.running = false;
Registration.recaptchaResponse = response;
});
})
}
}
}

View File

@@ -25,7 +25,7 @@ KirigamiSettings.CategorizedSettings {
return {
room: root.room,
connection: root.connection
};
}
}
},
KirigamiSettings.SettingAction {
@@ -36,7 +36,7 @@ KirigamiSettings.CategorizedSettings {
initialProperties: {
return {
room: root.room
};
}
}
},
KirigamiSettings.SettingAction {
@@ -47,7 +47,7 @@ KirigamiSettings.CategorizedSettings {
initialProperties: {
return {
room: root.room
};
}
}
},
KirigamiSettings.SettingAction {
@@ -58,7 +58,7 @@ KirigamiSettings.CategorizedSettings {
initialProperties: {
return {
room: root.room
};
}
}
}
]

View File

@@ -57,15 +57,15 @@ QQC2.Control {
property bool isBusy: root.currentRoom && root.currentRoom.hasFileUploading
// Matrix does not allow sending attachments in replies
visible: _private.chatBarCache.replyId.length === 0 && _private.chatBarCache.attachmentPath.length === 0
visible: _private.chatBarCache.replyId.length === 0 && _private.chatBarCache.attachmentPath.length === 0
icon.name: "mail-attachment"
text: i18n("Attach an image or file")
displayHint: Kirigami.DisplayHint.IconOnly
onTriggered: {
let dialog = (Clipboard.hasImage ? attachDialog : openFileDialog).createObject(applicationWindow().overlay);
dialog.chosen.connect(path => _private.chatBarCache.attachmentPath = path);
dialog.open();
let dialog = (Clipboard.hasImage ? attachDialog : openFileDialog).createObject(applicationWindow().overlay)
dialog.chosen.connect(path => _private.chatBarCache.attachmentPath = path)
dialog.open()
}
tooltip: text
@@ -83,9 +83,9 @@ QQC2.Control {
onTriggered: {
if (emojiDialog.visible) {
emojiDialog.close();
emojiDialog.close()
} else {
emojiDialog.open();
emojiDialog.open()
}
}
tooltip: text
@@ -98,9 +98,7 @@ QQC2.Control {
displayHint: QQC2.AbstractButton.IconOnly
onTriggered: {
locationChooser.createObject(QQC2.ApplicationWindow.overlay, {
room: root.currentRoom
}).open();
locationChooser.createObject(QQC2.ApplicationWindow.overlay, {room: root.currentRoom}).open()
}
tooltip: text
},
@@ -115,7 +113,7 @@ QQC2.Control {
checkable: true
onTriggered: {
_private.postMessage();
_private.postMessage()
}
tooltip: text
@@ -125,7 +123,7 @@ QQC2.Control {
/**
* @brief A message has been sent from the chat bar.
*/
signal messageSent
signal messageSent()
spacing: 0
@@ -136,7 +134,7 @@ QQC2.Control {
color: Kirigami.Theme.backgroundColor
Kirigami.Separator {
anchors.left: parent.left
anchors.right: parent.right
anchors.right:parent.right
anchors.top: parent.top
}
}
@@ -148,8 +146,7 @@ QQC2.Control {
contentItem: ColumnLayout {
spacing: 0
Item {
// Required to adjust for the top separator
Item { // Required to adjust for the top separator
Layout.preferredHeight: 1
Layout.fillWidth: true
}
@@ -203,17 +200,17 @@ QQC2.Control {
onTextChanged: {
if (!repeatTimer.running && Config.typingNotifications) {
var textExists = text.length > 0;
root.currentRoom.sendTypingNotification(textExists);
textExists ? repeatTimer.start() : repeatTimer.stop();
var textExists = text.length > 0
root.currentRoom.sendTypingNotification(textExists)
textExists ? repeatTimer.start() : repeatTimer.stop()
}
_private.chatBarCache.text = text;
_private.chatBarCache.text = text
}
onSelectedTextChanged: {
if (selectedText.length > 0) {
quickFormatBar.selectionStart = selectionStart;
quickFormatBar.selectionEnd = selectionEnd;
quickFormatBar.open();
quickFormatBar.selectionStart = selectionStart
quickFormatBar.selectionEnd = selectionEnd
quickFormatBar.open()
}
}
@@ -228,42 +225,42 @@ QQC2.Control {
Keys.onDeletePressed: {
if (selectedText.length > 0) {
remove(selectionStart, selectionEnd);
remove(selectionStart, selectionEnd)
} else {
remove(cursorPosition, cursorPosition + 1);
remove(cursorPosition, cursorPosition + 1)
}
if (textField.text == selectedText || textField.text.length <= 1) {
root.currentRoom.sendTypingNotification(false);
repeatTimer.stop();
root.currentRoom.sendTypingNotification(false)
repeatTimer.stop()
}
if (quickFormatBar.visible) {
quickFormatBar.close();
quickFormatBar.close()
}
}
Keys.onEnterPressed: event => {
if (completionMenu.visible) {
completionMenu.complete();
completionMenu.complete()
} else if (event.modifiers & Qt.ShiftModifier || Kirigami.Settings.isMobile) {
textField.insert(cursorPosition, "\n");
textField.insert(cursorPosition, "\n")
} else {
_private.postMessage();
}
}
Keys.onReturnPressed: event => {
if (completionMenu.visible) {
completionMenu.complete();
completionMenu.complete()
} else if (event.modifiers & Qt.ShiftModifier || Kirigami.Settings.isMobile) {
textField.insert(cursorPosition, "\n");
textField.insert(cursorPosition, "\n")
} else {
_private.postMessage();
}
}
Keys.onTabPressed: {
if (completionMenu.visible) {
completionMenu.complete();
completionMenu.complete()
}
}
Keys.onPressed: event => {
Keys.onPressed: (event) => {
if (event.key === Qt.Key_V && event.modifiers & Qt.ControlModifier) {
event.accepted = _private.pasteImage();
} else if (event.key === Qt.Key_Up && event.modifiers & Qt.ControlModifier) {
@@ -271,26 +268,26 @@ QQC2.Control {
} else if (event.key === Qt.Key_Up && textField.text.length === 0) {
root.currentRoom.editLastMessage();
} else if (event.key === Qt.Key_Up && completionMenu.visible) {
completionMenu.decrementIndex();
completionMenu.decrementIndex()
} else if (event.key === Qt.Key_Down && completionMenu.visible) {
completionMenu.incrementIndex();
completionMenu.incrementIndex()
} else if (event.key === Qt.Key_Backspace) {
if (textField.text == selectedText || textField.text.length <= 1) {
root.currentRoom.sendTypingNotification(false);
repeatTimer.stop();
root.currentRoom.sendTypingNotification(false)
repeatTimer.stop()
}
if (quickFormatBar.visible && selectedText.length > 0) {
quickFormatBar.close();
quickFormatBar.close()
}
}
}
Keys.onShortcutOverride: event => {
if (completionMenu.visible) {
completionMenu.close();
completionMenu.close()
} else if ((_private.chatBarCache.isReplying || _private.chatBarCache.attachmentPath.length > 0) && event.key === Qt.Key_Escape) {
_private.chatBarCache.attachmentPath = "";
_private.chatBarCache.replyId = "";
_private.chatBarCache.threadId = "";
_private.chatBarCache.attachmentPath = ""
_private.chatBarCache.replyId = ""
_private.chatBarCache.threadId = ""
event.accepted = true;
}
}
@@ -361,7 +358,7 @@ QQC2.Control {
onAttachmentCancelled: {
_private.chatBarCache.attachmentPath = "";
root.forceActiveFocus();
root.forceActiveFocus()
}
}
}
@@ -373,11 +370,11 @@ QQC2.Control {
function postMessage() {
root.actionsHandler.handleMessageEvent(_private.chatBarCache);
repeatTimer.stop();
repeatTimer.stop()
root.currentRoom.markAllMessagesAsRead();
textField.clear();
_private.chatBarCache.replyId = "";
messageSent();
messageSent()
}
function formatText(format, selectionStart, selectionEnd) {
@@ -389,19 +386,21 @@ QQC2.Control {
*/
let innerText = textField.text.substr(selectionStart, selectionEnd - selectionStart);
if (innerText.charAt(innerText.length - 1) === " ") {
let trimmedRightString = innerText.replace(/\s*$/, "");
let trimmedRightString = innerText.replace(/\s*$/,"");
let trimDifference = innerText.length - trimmedRightString.length;
selectionEnd -= trimDifference;
}
if (innerText.charAt(0) === " ") {
let trimmedLeftString = innerText.replace(/^\s*/, "");
let trimmedLeftString = innerText.replace(/^\s*/,"");
let trimDifference = innerText.length - trimmedLeftString.length;
selectionStart = selectionStart + trimDifference;
}
let startText = textField.text.substr(0, selectionStart);
// Needs updating with the new selectionStart and selectionEnd with white space trimmed.
innerText = textField.text.substr(selectionStart, selectionEnd - selectionStart);
let endText = textField.text.substr(selectionEnd);
textField.text = "";
textField.text = startText + format.start + innerText + format.end + format.extra + endText;
@@ -496,14 +495,13 @@ QQC2.Control {
currentRoom: root.currentRoom
onChosen: emoji => insertText(emoji)
onClosed: if (emojiAction.checked) {
emojiAction.checked = false;
}
onClosed: if (emojiAction.checked) emojiAction.checked = false
}
function insertText(text) {
let initialCursorPosition = textField.cursorPosition;
textField.text = textField.text.substr(0, initialCursorPosition) + text + textField.text.substr(initialCursorPosition);
textField.cursorPosition = initialCursorPosition + text.length;
textField.text = textField.text.substr(0, initialCursorPosition) + text + textField.text.substr(initialCursorPosition)
textField.cursorPosition = initialCursorPosition + text.length
}
}

View File

@@ -32,7 +32,7 @@ Kirigami.ScrollablePage {
id: roomDelegate
filterText: ""
onSelected: {
root.chosen(roomDelegate.currentRoom.id);
root.chosen(roomDelegate.currentRoom.id)
}
connection: root.connection
}

Some files were not shown because too many files have changed in this diff Show More