Compare commits

..

42 Commits

Author SHA1 Message Date
l10n daemon script
b901ea6e2a GIT_SILENT Sync po/docbooks with svn 2024-02-21 02:56:16 +00:00
James Graham
8cfd515db2 Add feature flag for reply in thread
Currently the ability to reply in threads was added but not the ability to actually view threads so this doesn't currently make much sense to just have enabled int he main build.

Note: I want to cherrypick this so it's just the flag. I'll add a feature flag page to dev tools for master soon.


(cherry picked from commit 864f9b8f74)
2024-02-20 20:11:01 +00:00
l10n daemon script
3e5181d64e GIT_SILENT Sync po/docbooks with svn 2024-02-20 02:59:05 +00:00
Carl Schwan
ae53bf5df2 Add neochat 24.02 release note
(cherry picked from commit dc5366e924)
2024-02-19 12:33:21 +00:00
l10n daemon script
d2ed304672 GIT_SILENT Sync po/docbooks with svn 2024-02-19 02:58:48 +00:00
l10n daemon script
4924bd05a8 GIT_SILENT Sync po/docbooks with svn 2024-02-18 02:57:59 +00:00
l10n daemon script
9aa7553a1f GIT_SILENT Sync po/docbooks with svn 2024-02-16 03:02:48 +00:00
Heiko Becker
1c910165c1 GIT_SILENT Update Appstream for new release 2024-02-16 00:48:30 +01:00
Heiko Becker
05a84da722 GIT_SILENT Upgrade release service version to 24.02.0. 2024-02-16 00:01:13 +01:00
Carl Schwan
1ab8b85f06 Fix reaction update event when the event is not there anymore
Happens when interacting witht Mjonir quite often


(cherry picked from commit 6d3839dd42)
2024-02-15 20:13:28 +00:00
Carl Schwan
05883bcb71 Fix reaction delegate sizing for text reaction
(cherry picked from commit 755a060e12)
2024-02-15 20:13:01 +00:00
l10n daemon script
20cb6dc864 GIT_SILENT Sync po/docbooks with svn 2024-02-15 02:52:41 +00:00
l10n daemon script
b6cf60acdb GIT_SILENT made messages (after extraction) 2024-02-15 02:21:10 +00:00
Tobias Fella
d4a6a41981 Skip Welcome screen when there's only one connection and it's loaded
If the connection is stuck, we can still log in to a different one that way.

(cherry picked from commit 7150445f8e)
2024-02-14 18:16:07 +01:00
Tobias Fella
8c2682c943 Allow dropping connections from the welcome page
This is the last piece required to make sure that we can recover from broken connections, e.g., when the access token is invalid.

(cherry picked from commit b02bdd22dd)
2024-02-14 18:14:20 +01:00
Heiko Becker
9c56561853 GIT_SILENT Update Appstream for new release
(cherry picked from commit 0cd0a6a672)
2024-02-14 14:39:59 +01:00
l10n daemon script
ab9410cc03 GIT_SILENT Sync po/docbooks with svn 2024-02-14 03:00:27 +00:00
Tobias Fella
43fae7af04 Show custom emoji reactions as per MSC4027
(cherry picked from commit ca57732871)
2024-02-12 16:02:48 +01:00
Tobias Fella
0cf19d21f2 Fix AudioDelegate playback
(cherry picked from commit b909cb2db8)
2024-02-10 23:06:44 +01:00
l10n daemon script
ce448bd027 GIT_SILENT Sync po/docbooks with svn 2024-02-09 03:07:07 +00:00
l10n daemon script
056e91df9f GIT_SILENT Sync po/docbooks with svn 2024-02-05 03:32:35 +00:00
l10n daemon script
258815ca10 GIT_SILENT Sync po/docbooks with svn 2024-02-02 02:54:20 +00:00
l10n daemon script
174373fb15 GIT_SILENT Sync po/docbooks with svn 2024-01-31 03:10:56 +00:00
l10n daemon script
aa0790d7fd GIT_SILENT Sync po/docbooks with svn 2024-01-30 02:58:53 +00:00
l10n daemon script
e6c589c6ac GIT_SILENT Sync po/docbooks with svn 2024-01-29 02:59:49 +00:00
James Graham
4b1805bdaa Fix copying selected text from a message
(cherry picked from commit 48502480df)
2024-01-28 10:06:27 +00:00
l10n daemon script
6055460bff GIT_SILENT Sync po/docbooks with svn 2024-01-28 02:58:51 +00:00
l10n daemon script
0642685874 GIT_SILENT Sync po/docbooks with svn 2024-01-27 02:57:15 +00:00
l10n daemon script
e2b7e6778e GIT_SILENT Sync po/docbooks with svn 2024-01-26 02:59:18 +00:00
l10n daemon script
22bf9b8a59 GIT_SILENT Sync po/docbooks with svn 2024-01-24 02:56:01 +00:00
l10n daemon script
85fc1a1f46 GIT_SILENT Sync po/docbooks with svn 2024-01-23 03:02:41 +00:00
l10n daemon script
624123407c GIT_SILENT Sync po/docbooks with svn 2024-01-22 03:38:56 +00:00
James Graham
7bad41739f Cherrypick 24.02 Clip QuickSwitcher
Clip QuickSwitcher to stop the delegates overlapping the dialog


(cherry picked from commit 8e8105d04d)
2024-01-17 17:19:40 +00:00
l10n daemon script
ee16504aa0 GIT_SILENT Sync po/docbooks with svn 2024-01-17 02:57:22 +00:00
Ingo Klöcker
cf308bcdce Require master of ECM
We need the fix for APK packaging with Android NDK r25


(cherry picked from commit 21d9e69712)
2024-01-16 14:21:07 +00:00
l10n daemon script
6fbfa48c77 GIT_SILENT Sync po/docbooks with svn 2024-01-16 02:57:45 +00:00
l10n daemon script
67d71cb590 GIT_SILENT Sync po/docbooks with svn 2024-01-15 02:56:34 +00:00
l10n daemon script
c5817df2c9 GIT_SILENT Sync po/docbooks with svn 2024-01-14 03:43:35 +00:00
Joshua Goins
b94fcd6858 Make the search message dialog header way prettier, like it is in KCMs
I think I've heard of this before...

(cherry picked from commit 2247a2a7af)
2024-01-13 20:37:48 -05:00
Joshua Goins
8a8874fcb6 Add missing thread roles in SearchModel
This fixes the message search so it works again!

(cherry picked from commit 08a0fbfd6b)
2024-01-13 20:35:25 -05:00
James Graham
b593f7321b Cherrypick 24.02 Readonly Room
Add readonly property to a room and use it to decide whether to show chatbar, replies and edits

BUG: 479590


(cherry picked from commit ec4aa73e37)
2024-01-13 12:06:00 +00:00
Albert Astals Cid
5002258e34 GIT_SILENT Upgrade release service version to 24.01.95. 2024-01-11 20:53:22 +01:00
251 changed files with 29076 additions and 36803 deletions

View File

@@ -8,8 +8,8 @@ cmake_minimum_required(VERSION 3.16)
# KDE Applications version, managed by release script. # KDE Applications version, managed by release script.
set(RELEASE_SERVICE_VERSION_MAJOR "24") set(RELEASE_SERVICE_VERSION_MAJOR "24")
set(RELEASE_SERVICE_VERSION_MINOR "04") set(RELEASE_SERVICE_VERSION_MINOR "02")
set(RELEASE_SERVICE_VERSION_MICRO "70") set(RELEASE_SERVICE_VERSION_MICRO "0")
set(RELEASE_SERVICE_VERSION "${RELEASE_SERVICE_VERSION_MAJOR}.${RELEASE_SERVICE_VERSION_MINOR}.${RELEASE_SERVICE_VERSION_MICRO}") set(RELEASE_SERVICE_VERSION "${RELEASE_SERVICE_VERSION_MAJOR}.${RELEASE_SERVICE_VERSION_MINOR}.${RELEASE_SERVICE_VERSION_MICRO}")
project(NeoChat VERSION ${RELEASE_SERVICE_VERSION}) project(NeoChat VERSION ${RELEASE_SERVICE_VERSION})

View File

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

View File

@@ -239,11 +239,44 @@ to provide a convergent experience across multiple platforms.</p>
<categories> <categories>
<category>Network</category> <category>Network</category>
</categories> </categories>
<developer> <developer_name>The KDE Community</developer_name>
<id>kde.org</id> <developer_name xml:lang="ar">مجتمع كِيدِي</developer_name>
<name>The KDE Community</name> <developer_name xml:lang="az">KDE Cəmiyyəti</developer_name>
<url>https://kde.org</url> <developer_name xml:lang="ca">La comunitat KDE</developer_name>
</developer> <developer_name xml:lang="ca-valencia">La comunitat KDE</developer_name>
<developer_name xml:lang="cs">Komunita KDE</developer_name>
<developer_name xml:lang="de">Die KDE-Gemeinschaft</developer_name>
<developer_name xml:lang="el">Η Κοινότητα του KDE</developer_name>
<developer_name xml:lang="en-GB">The KDE Community</developer_name>
<developer_name xml:lang="eo">La KDE-Komunumo</developer_name>
<developer_name xml:lang="es">La comunidad KDE</developer_name>
<developer_name xml:lang="eu">KDE komunitatea</developer_name>
<developer_name xml:lang="fi">KDE-yhteisö</developer_name>
<developer_name xml:lang="fr">La communauté de KDE</developer_name>
<developer_name xml:lang="gl">A comunidade KDE</developer_name>
<developer_name xml:lang="hu">A KDE Közösség</developer_name>
<developer_name xml:lang="ia">Le communitate de KDE</developer_name>
<developer_name xml:lang="id">Komunitas KDE</developer_name>
<developer_name xml:lang="ie">Li comunité de KDE</developer_name>
<developer_name xml:lang="it">La comunità KDE</developer_name>
<developer_name xml:lang="ka">KDE-ის საზოგადოება</developer_name>
<developer_name xml:lang="ko">KDE 커뮤니티</developer_name>
<developer_name xml:lang="nl">De KDE gemeenschap</developer_name>
<developer_name xml:lang="nn">KDE-fellesskapet</developer_name>
<developer_name xml:lang="pa">ਕੇਡੀਈ ਕਮਿਊਨਟੀ</developer_name>
<developer_name xml:lang="pl">Społeczność KDE</developer_name>
<developer_name xml:lang="pt">A Comunidade do KDE</developer_name>
<developer_name xml:lang="pt-BR">A comunidade KDE</developer_name>
<developer_name xml:lang="ru">Сообщество KDE</developer_name>
<developer_name xml:lang="sk">KDE Komunita</developer_name>
<developer_name xml:lang="sl">Skupnost KDE</developer_name>
<developer_name xml:lang="sv">KDE-gemenskapen</developer_name>
<developer_name xml:lang="ta">கே.டீ.யீ. சமூகம்</developer_name>
<developer_name xml:lang="tr">KDE Topluluğu</developer_name>
<developer_name xml:lang="uk">Спільнота KDE</developer_name>
<developer_name xml:lang="x-test">xxThe KDE Communityxx</developer_name>
<developer_name xml:lang="zh-CN">KDE 社区</developer_name>
<developer_name xml:lang="zh-TW">KDE 社群</developer_name>
<metadata_license>CC0-1.0</metadata_license> <metadata_license>CC0-1.0</metadata_license>
<project_license>GPL-3.0</project_license> <project_license>GPL-3.0</project_license>
<custom> <custom>

View File

@@ -65,7 +65,7 @@ GenericName[ie]=Cliente de Matrix
GenericName[it]=Client Matrix GenericName[it]=Client Matrix
GenericName[ka]=Matrix -ის კლიენტი GenericName[ka]=Matrix -ის კლიენტი
GenericName[ko]=Matrix 클라이언트 GenericName[ko]=Matrix 클라이언트
GenericName[lt]=Matrix kliento programa GenericName[lt]=Matrix kliento programą
GenericName[nl]=Matrix-client GenericName[nl]=Matrix-client
GenericName[nn]=Matrix-klient GenericName[nn]=Matrix-klient
GenericName[pa]=ਮੈਟਰਿਕਸ ਕਲਾਈਂਟ GenericName[pa]=ਮੈਟਰਿਕਸ ਕਲਾਈਂਟ

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> ></term>
<listitem> <listitem>
<para <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> </listitem>
</varlistentry> </varlistentry>
</variablelist> </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

@@ -144,18 +144,6 @@ add_library(neochat STATIC
models/timelinemodel.cpp models/timelinemodel.cpp
models/timelinemodel.h models/timelinemodel.h
enums/pushrule.h enums/pushrule.h
models/itinerarymodel.cpp
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 qt_add_qml_module(neochat URI org.kde.neochat NO_PLUGIN
@@ -173,10 +161,11 @@ qt_add_qml_module(neochat URI org.kde.neochat NO_PLUGIN
qml/UserInfoDesktop.qml qml/UserInfoDesktop.qml
qml/RoomPage.qml qml/RoomPage.qml
qml/RoomWindow.qml qml/RoomWindow.qml
qml/ExploreRoomsPage.qml qml/JoinRoomPage.qml
qml/ManualRoomDialog.qml qml/ManualRoomDialog.qml
qml/ExplorerDelegate.qml qml/ExplorerDelegate.qml
qml/InviteUserPage.qml qml/InviteUserPage.qml
qml/StartChatPage.qml
qml/ImageEditorPage.qml qml/ImageEditorPage.qml
qml/WelcomePage.qml qml/WelcomePage.qml
qml/General.qml qml/General.qml
@@ -201,12 +190,21 @@ qt_add_qml_module(neochat URI org.kde.neochat NO_PLUGIN
qml/TimelineDelegate.qml qml/TimelineDelegate.qml
qml/ReplyComponent.qml qml/ReplyComponent.qml
qml/StateDelegate.qml qml/StateDelegate.qml
qml/RichLabel.qml
qml/MessageDelegate.qml qml/MessageDelegate.qml
qml/Bubble.qml qml/Bubble.qml
qml/SectionDelegate.qml qml/SectionDelegate.qml
qml/VideoDelegate.qml
qml/ReactionDelegate.qml qml/ReactionDelegate.qml
qml/LinkPreviewDelegate.qml
qml/AudioDelegate.qml
qml/FileDelegate.qml
qml/ImageDelegate.qml
qml/EncryptedDelegate.qml
qml/EventDelegate.qml qml/EventDelegate.qml
qml/TextDelegate.qml
qml/ReadMarkerDelegate.qml qml/ReadMarkerDelegate.qml
qml/PollDelegate.qml
qml/MimeComponent.qml qml/MimeComponent.qml
qml/StateComponent.qml qml/StateComponent.qml
qml/MessageEditComponent.qml qml/MessageEditComponent.qml
@@ -269,13 +267,15 @@ qt_add_qml_module(neochat URI org.kde.neochat NO_PLUGIN
qml/EmojiTonesPicker.qml qml/EmojiTonesPicker.qml
qml/EmojiDelegate.qml qml/EmojiDelegate.qml
qml/EmojiGrid.qml qml/EmojiGrid.qml
qml/RoomSearchPage.qml qml/SearchPage.qml
qml/LocationDelegate.qml
qml/LocationChooser.qml qml/LocationChooser.qml
qml/TimelineView.qml qml/TimelineView.qml
qml/InvitationView.qml qml/InvitationView.qml
qml/AvatarTabButton.qml qml/AvatarTabButton.qml
qml/SpaceDrawer.qml qml/SpaceDrawer.qml
qml/OsmLocationPlugin.qml qml/OsmLocationPlugin.qml
qml/LiveLocationDelegate.qml
qml/FullScreenMap.qml qml/FullScreenMap.qml
qml/LocationsPage.qml qml/LocationsPage.qml
qml/LocationMapItem.qml qml/LocationMapItem.qml
@@ -298,30 +298,11 @@ qt_add_qml_module(neochat URI org.kde.neochat NO_PLUGIN
qml/NotificationsView.qml qml/NotificationsView.qml
qml/LoadingDelegate.qml qml/LoadingDelegate.qml
qml/TimelineEndDelegate.qml qml/TimelineEndDelegate.qml
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 RESOURCES
qml/confetti.png qml/confetti.png
qml/glowdot.png qml/glowdot.png
) )
configure_file(config-neochat.h.in ${CMAKE_CURRENT_BINARY_DIR}/config-neochat.h)
if(WIN32) if(WIN32)
set_target_properties(neochat PROPERTIES OUTPUT_NAME "neochatlib") set_target_properties(neochat PROPERTIES OUTPUT_NAME "neochatlib")
endif() endif()
@@ -335,15 +316,6 @@ ecm_qt_declare_logging_category(neochat
EXPORT NEOCHAT EXPORT NEOCHAT
) )
ecm_qt_declare_logging_category(neochat
HEADER "publicroomlist_logging.h"
IDENTIFIER "PublicRoomList"
CATEGORY_NAME "org.kde.neochat.publicroomlistmodel"
DESCRIPTION "Neochat: publicroomlistmodel"
DEFAULT_SEVERITY Info
EXPORT NEOCHAT
)
ecm_qt_declare_logging_category(neochat ecm_qt_declare_logging_category(neochat
HEADER "eventhandler_logging.h" HEADER "eventhandler_logging.h"
IDENTIFIER "EventHandling" IDENTIFIER "EventHandling"

View File

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

View File

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

View File

@@ -1,8 +0,0 @@
/*
SPDX-FileCopyrightText: 2024 Tobias Fella <tobias.fella@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#pragma once
#define CMAKE_INSTALL_FULL_LIBEXECDIR_KF6 "${KDE_INSTALL_FULL_LIBEXECDIR_KF}"

View File

@@ -23,12 +23,12 @@
#include <Quotient/csapi/logout.h> #include <Quotient/csapi/logout.h>
#include <Quotient/csapi/notifications.h> #include <Quotient/csapi/notifications.h>
#include <Quotient/eventstats.h> #include <Quotient/eventstats.h>
#include <Quotient/jobs/downloadfilejob.h>
#include <Quotient/qt_connection_util.h> #include <Quotient/qt_connection_util.h>
#include "neochatconfig.h" #include "neochatconfig.h"
#include "neochatroom.h" #include "neochatroom.h"
#include "notificationsmanager.h" #include "notificationsmanager.h"
#include "proxycontroller.h"
#include "roommanager.h" #include "roommanager.h"
#if defined(Q_OS_WIN) || defined(Q_OS_MAC) #if defined(Q_OS_WIN) || defined(Q_OS_MAC)
@@ -46,7 +46,7 @@ Controller::Controller(QObject *parent)
{ {
Connection::setRoomType<NeoChatRoom>(); Connection::setRoomType<NeoChatRoom>();
ProxyController::instance().setApplicationProxy(); setApplicationProxy();
#ifndef Q_OS_ANDROID #ifndef Q_OS_ANDROID
setQuitOnLastWindowClosed(); setQuitOnLastWindowClosed();
@@ -287,10 +287,28 @@ void Controller::setActiveConnection(NeoChatConnection *connection)
if (connection == m_connection) { if (connection == m_connection) {
return; return;
} }
if (m_connection != nullptr) {
disconnect(m_connection, &NeoChatConnection::syncError, this, nullptr);
disconnect(m_connection, &NeoChatConnection::accountDataChanged, this, nullptr);
}
m_connection = connection; m_connection = connection;
if (connection != nullptr) {
connect(connection, &NeoChatConnection::requestFailed, this, [](BaseJob *job) {
if (dynamic_cast<DownloadFileJob *>(job) && job->jsonData()["errcode"_ls].toString() == "M_TOO_LARGE"_ls) {
RoomManager::instance().warning(i18n("File too large to download."), i18n("Contact your matrix server administrator for support."));
}
});
}
NeoChatConfig::self()->save();
Q_EMIT activeConnectionChanged(); Q_EMIT activeConnectionChanged();
} }
void Controller::forceRefreshTextDocument(QQuickTextDocument *textDocument, QQuickItem *item)
{
// HACK: Workaround bug QTBUG 93281
connect(textDocument->textDocument(), SIGNAL(imagesLoaded()), item, SLOT(updateWholeDocument()));
}
void Controller::listenForNotifications() void Controller::listenForNotifications()
{ {
#ifdef HAVE_KUNIFIEDPUSH #ifdef HAVE_KUNIFIEDPUSH
@@ -312,6 +330,36 @@ void Controller::listenForNotifications()
#endif #endif
} }
void Controller::setApplicationProxy()
{
NeoChatConfig *cfg = NeoChatConfig::self();
QNetworkProxy proxy;
// type match to ProxyType from neochatconfig.kcfg
switch (cfg->proxyType()) {
case 1: // HTTP
proxy.setType(QNetworkProxy::HttpProxy);
proxy.setHostName(cfg->proxyHost());
proxy.setPort(cfg->proxyPort());
proxy.setUser(cfg->proxyUser());
proxy.setPassword(cfg->proxyPassword());
break;
case 2: // SOCKS 5
proxy.setType(QNetworkProxy::Socks5Proxy);
proxy.setHostName(cfg->proxyHost());
proxy.setPort(cfg->proxyPort());
proxy.setUser(cfg->proxyUser());
proxy.setPassword(cfg->proxyPassword());
break;
case 0: // System Default
default:
// do nothing
break;
}
QNetworkProxy::setApplicationProxy(proxy);
}
bool Controller::isFlatpak() const bool Controller::isFlatpak() const
{ {
#ifdef NEOCHAT_FLATPAK #ifdef NEOCHAT_FLATPAK

View File

@@ -84,8 +84,22 @@ public:
[[nodiscard]] bool supportSystemTray() const; [[nodiscard]] bool supportSystemTray() const;
/**
* @brief Sets the QNetworkProxy for the application.
*
* @sa QNetworkProxy::setApplicationProxy
*/
Q_INVOKABLE void setApplicationProxy();
bool isFlatpak() const; bool isFlatpak() const;
/**
* @brief Force a QQuickTextDocument to refresh when images are loaded.
*
* HACK: This is a workaround for QTBUG 93281.
*/
Q_INVOKABLE void forceRefreshTextDocument(QQuickTextDocument *textDocument, QQuickItem *item);
/** /**
* @brief Start listening for notifications in dbus-activated mode. * @brief Start listening for notifications in dbus-activated mode.
* These notifications will quit the application when closed. * These notifications will quit the application when closed.

View File

@@ -6,13 +6,6 @@
#include <QObject> #include <QObject>
#include <QQmlEngine> #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 * @class DelegateType
* *
@@ -33,34 +26,23 @@ public:
* similar to the spec it is not the same. * similar to the spec it is not the same.
*/ */
enum Type { 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. */ Message, /**< A text message. */
Sticker, /**< A message that is a sticker. */
State, /**< A state event in the room. */ State, /**< A state event in the room. */
Encrypted, /**< An encrypted message that cannot be decrypted. */
ReadMarker, /**< The local user read marker. */ 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. */ Loading, /**< A delegate to tell the user more messages are being loaded. */
TimelineEnd, /**< A delegate to inform that all messages are loaded. */ TimelineEnd, /**< A delegate to inform that all messages are loaded. */
Other, /**< Anything that cannot be classified as another type. */ Other, /**< Anything that cannot be classified as another type. */
}; };
Q_ENUM(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/roomavatarevent.h>
#include <Quotient/events/roomcanonicalaliasevent.h> #include <Quotient/events/roomcanonicalaliasevent.h>
#include <Quotient/events/roommemberevent.h> #include <Quotient/events/roommemberevent.h>
#include <Quotient/events/roommessageevent.h>
#include <Quotient/events/roompowerlevelsevent.h> #include <Quotient/events/roompowerlevelsevent.h>
#include <Quotient/events/simplestateevents.h> #include <Quotient/events/simplestateevents.h>
#include <Quotient/events/stickerevent.h> #include <Quotient/events/stickerevent.h>
#include <Quotient/quotient_common.h> #include <Quotient/quotient_common.h>
#include "delegatetype.h"
#include "eventhandler_logging.h" #include "eventhandler_logging.h"
#include "events/locationbeaconevent.h"
#include "events/pollevent.h" #include "events/pollevent.h"
#include "events/serveraclevent.h"
#include "events/widgetevent.h"
#include "linkpreviewer.h" #include "linkpreviewer.h"
#include "messagecomponenttype.h"
#include "models/reactionmodel.h" #include "models/reactionmodel.h"
#include "neochatconfig.h" #include "neochatconfig.h"
#include "neochatroom.h" #include "neochatroom.h"
@@ -35,10 +31,34 @@
using namespace Quotient; using namespace Quotient;
EventHandler::EventHandler(const NeoChatRoom *room, const RoomEvent *event) const NeoChatRoom *EventHandler::getRoom() const
: m_room(room)
, m_event(event)
{ {
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 QString EventHandler::getId() const
@@ -51,14 +71,62 @@ QString EventHandler::getId() const
return !m_event->id().isEmpty() ? m_event->id() : m_event->transactionId(); 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) { if (auto e = eventCast<const RoomMessageEvent>(event)) {
qCWarning(EventHandling) << "messageComponentType called with m_event set to nullptr."; switch (e->msgtype()) {
return MessageComponentType::Other; 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 QVariantMap EventHandler::getAuthor(bool isPending) const
@@ -277,7 +345,8 @@ QString EventHandler::getBody(const Quotient::RoomEvent *event, Qt::TextFormat f
} }
if (prettyPrint) { 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 // The below code assumes senderName output in AuthorRole
@@ -388,22 +457,22 @@ QString EventHandler::getBody(const Quotient::RoomEvent *event, Qt::TextFormat f
[](const RoomPowerLevelsEvent &) { [](const RoomPowerLevelsEvent &) {
return i18nc("'power level' means permission level", "changed the power levels for this room"); 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) { [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()) return e.stateKey().isEmpty() ? i18n("updated %1 state", e.matrixType())
: i18n("updated %1 state for %2", e.matrixType(), prettyPrint ? e.stateKey().toHtmlEscaped() : e.stateKey()); : i18n("updated %1 state for %2", e.matrixType(), prettyPrint ? e.stateKey().toHtmlEscaped() : e.stateKey());
}, },
@@ -557,22 +626,19 @@ QString EventHandler::getGenericBody() const
[](const RoomPowerLevelsEvent &) { [](const RoomPowerLevelsEvent &) {
return i18nc("'power level' means permission level", "changed the power levels for this room"); return i18nc("'power level' means permission level", "changed the power levels for this room");
}, },
[](const LocationBeaconEvent &) { [](const StateEvent &e) {
return i18n("sent a live location beacon"); if (e.matrixType() == QLatin1String("m.room.server_acl")) {
}, return i18n("changed the server access control lists for this room");
[](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");
} }
if (e.contentJson().isEmpty()) { if (e.matrixType() == QLatin1String("im.vector.modular.widgets")) {
return i18n("removed a widget"); 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"); return i18n("updated the state");
}, },
[](const PollStartEvent &e) { [](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(); 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) { if (m_room == nullptr) {
qCWarning(EventHandling) << "replyMessageComponentType called with m_room set to nullptr."; qCWarning(EventHandling) << "getReplyDelegateType called with m_room set to nullptr.";
return MessageComponentType::Other; return DelegateType::Other;
} }
if (m_event == nullptr) { if (m_event == nullptr) {
qCWarning(EventHandling) << "replyMessageComponentType called with m_event set to nullptr."; qCWarning(EventHandling) << "getReplyDelegateType called with m_event set to nullptr.";
return MessageComponentType::Other; return DelegateType::Other;
} }
auto replyEvent = m_room->getReplyForEvent(*m_event); auto replyEvent = m_room->getReplyForEvent(*m_event);
if (replyEvent == nullptr) { if (replyEvent == nullptr) {
return MessageComponentType::Other; return DelegateType::Other;
} }
return MessageComponentType::typeForEvent(*replyEvent); return getDelegateTypeForEvent(replyEvent);
} }
QVariantMap EventHandler::getReplyAuthor() const QVariantMap EventHandler::getReplyAuthor() const

View File

@@ -11,7 +11,7 @@
#include <Quotient/events/roomevent.h> #include <Quotient/events/roomevent.h>
#include <Quotient/events/roommessageevent.h> #include <Quotient/events/roommessageevent.h>
#include "enums/messagecomponenttype.h" #include "enums/delegatetype.h"
class LinkPreviewer; class LinkPreviewer;
class NeoChatRoom; class NeoChatRoom;
@@ -31,12 +31,30 @@ class ReactionModel;
* information. This is to minimize warnings from QML especially during startup * information. This is to minimize warnings from QML especially during startup
* and room changes. * and room changes.
*/ */
class EventHandler class EventHandler : public QObject
{ {
Q_GADGET Q_OBJECT
public: 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. * @brief Return the Matrix ID of the event.
@@ -44,9 +62,13 @@ public:
QString getId() const; 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. * @brief Get the author of the event in context of the room.
@@ -220,9 +242,13 @@ public:
QString getReplyId() const; 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. * @brief Get the author of the event replied to in context of the room.
@@ -378,6 +404,8 @@ private:
KFormat m_format; KFormat m_format;
DelegateType::Type getDelegateTypeForEvent(const Quotient::RoomEvent *event) const;
QString getBody(const Quotient::RoomEvent *event, Qt::TextFormat format, bool stripNewlines) 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; 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; using namespace Quotient;
LinkPreviewer::LinkPreviewer(const NeoChatRoom *room, const Quotient::RoomMessageEvent *event, QObject *parent) LinkPreviewer::LinkPreviewer(const NeoChatRoom *room, const Quotient::RoomMessageEvent *event)
: QObject(parent) : QObject(nullptr)
, m_currentRoom(room) , m_currentRoom(room)
, m_event(event) , m_event(event)
, m_loaded(false) , m_loaded(false)

View File

@@ -60,7 +60,7 @@ class LinkPreviewer : public QObject
Q_PROPERTY(bool empty READ empty NOTIFY emptyChanged) Q_PROPERTY(bool empty READ empty NOTIFY emptyChanged)
public: 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]] QUrl url() const;
[[nodiscard]] bool loaded() 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); auto targetRoom = text.startsWith(QLatin1Char('!')) ? room->connection()->room(text) : room->connection()->roomByAlias(text);
if (targetRoom) { if (targetRoom) {
RoomManager::instance().resolveResource(targetRoom->id()); RoomManager::instance().enterRoom(dynamic_cast<NeoChatRoom *>(targetRoom));
return QString(); return QString();
} }
Q_EMIT room->showMessage(NeoChatRoom::Info, i18nc("Joining room <roomname>.", "Joining room %1.", text)); 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); auto targetRoom = text.startsWith(QLatin1Char('!')) ? room->connection()->room(text) : room->connection()->roomByAlias(text);
if (targetRoom) { if (targetRoom) {
RoomManager::instance().resolveResource(targetRoom->id()); RoomManager::instance().enterRoom(dynamic_cast<NeoChatRoom *>(targetRoom));
return QString(); return QString();
} }
Q_EMIT room->showMessage(NeoChatRoom::Info, i18nc("Knocking room <roomname>.", "Knocking room %1.", text)); Q_EMIT room->showMessage(NeoChatRoom::Info, i18nc("Knocking room <roomname>.", "Knocking room %1.", text));

View File

@@ -1,163 +0,0 @@
// SPDX-FileCopyrightText: 2024 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "itinerarymodel.h"
#include <QProcess>
#include "config-neochat.h"
#ifndef Q_OS_ANDROID
#include <KIO/ApplicationLauncherJob>
#endif
ItineraryModel::ItineraryModel(QObject *parent)
: QAbstractListModel(parent)
{
}
void ItineraryModel::setConnection(NeoChatConnection *connection)
{
if (m_connection == connection) {
return;
}
m_connection = connection;
Q_EMIT connectionChanged();
}
NeoChatConnection *ItineraryModel::connection() const
{
return m_connection;
}
QVariant ItineraryModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return {};
}
auto row = index.row();
auto data = m_data[row];
if (role == NameRole) {
if (data[QStringLiteral("@type")] == QStringLiteral("TrainReservation")) {
return data[QStringLiteral("reservationFor")][QStringLiteral("trainNumber")];
}
if (data[QStringLiteral("@type")] == QStringLiteral("LodgingReservation")) {
return data[QStringLiteral("reservationFor")][QStringLiteral("name")];
}
}
if (role == TypeRole) {
return data[QStringLiteral("@type")];
}
if (role == DepartureStationRole) {
return data[QStringLiteral("reservationFor")][QStringLiteral("departureStation")][QStringLiteral("name")];
}
if (role == ArrivalStationRole) {
return data[QStringLiteral("reservationFor")][QStringLiteral("arrivalStation")][QStringLiteral("name")];
}
if (role == DepartureTimeRole) {
const auto &time = data[QStringLiteral("reservationFor")][QStringLiteral("departureTime")];
auto dateTime = (time.isString() ? time : time[QStringLiteral("@value")]).toVariant().toDateTime();
if (const auto &timeZone = time[QStringLiteral("timezone")].toString(); timeZone.length() > 0) {
dateTime.setTimeZone(QTimeZone(timeZone.toLatin1().data()));
}
return dateTime.toString(QLocale::system().dateTimeFormat(QLocale::ShortFormat));
}
if (role == ArrivalTimeRole) {
const auto &time = data[QStringLiteral("reservationFor")][QStringLiteral("arrivalTime")];
auto dateTime = (time.isString() ? time : time[QStringLiteral("@value")]).toVariant().toDateTime();
if (const auto &timeZone = time[QStringLiteral("timezone")].toString(); timeZone.length() > 0) {
dateTime.setTimeZone(QTimeZone(timeZone.toLatin1().data()));
}
return dateTime.toString(QLocale::system().dateTimeFormat(QLocale::ShortFormat));
}
if (role == AddressRole) {
const auto &addressData = data[QStringLiteral("reservationFor")][QStringLiteral("address")];
return QStringLiteral("%1 - %2 %3 %4")
.arg(addressData[QStringLiteral("streetAddress")].toString(),
addressData[QStringLiteral("postalCode")].toString(),
addressData[QStringLiteral("addressLocality")].toString(),
addressData[QStringLiteral("addressCountry")].toString());
}
if (role == StartTimeRole) {
auto dateTime = data[QStringLiteral("checkinTime")][QStringLiteral("@value")].toVariant().toDateTime();
return dateTime.toString(QLocale::system().dateTimeFormat(QLocale::ShortFormat));
}
if (role == EndTimeRole) {
auto dateTime = data[QStringLiteral("checkoutTime")][QStringLiteral("@value")].toVariant().toDateTime();
return dateTime.toString(QLocale::system().dateTimeFormat(QLocale::ShortFormat));
}
if (role == DeparturePlatformRole) {
return data[QStringLiteral("reservationFor")][QStringLiteral("departurePlatform")];
}
if (role == ArrivalPlatformRole) {
return data[QStringLiteral("reservationFor")][QStringLiteral("arrivalPlatform")];
}
if (role == CoachRole) {
return data[QStringLiteral("reservedTicket")][QStringLiteral("ticketedSeat")][QStringLiteral("seatSection")];
}
if (role == SeatRole) {
return data[QStringLiteral("reservedTicket")][QStringLiteral("ticketedSeat")][QStringLiteral("seatNumber")];
}
return {};
}
int ItineraryModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return m_data.size();
}
QHash<int, QByteArray> ItineraryModel::roleNames() const
{
return {
{NameRole, "name"},
{TypeRole, "type"},
{DepartureStationRole, "departureStation"},
{ArrivalStationRole, "arrivalStation"},
{DepartureTimeRole, "departureTime"},
{ArrivalTimeRole, "arrivalTime"},
{AddressRole, "address"},
{StartTimeRole, "startTime"},
{EndTimeRole, "endTime"},
{DeparturePlatformRole, "departurePlatform"},
{ArrivalPlatformRole, "arrivalPlatform"},
{CoachRole, "coach"},
{SeatRole, "seat"},
};
}
QString ItineraryModel::path() const
{
return m_path;
}
void ItineraryModel::setPath(const QString &path)
{
if (path == m_path) {
return;
}
m_path = path;
Q_EMIT pathChanged();
loadData();
}
void ItineraryModel::loadData()
{
auto process = new QProcess(this);
process->start(QLatin1String(CMAKE_INSTALL_FULL_LIBEXECDIR_KF6) + QLatin1String("/kitinerary-extractor"), {m_path.mid(7)});
connect(process, &QProcess::finished, this, [this, process]() {
auto data = process->readAllStandardOutput();
beginResetModel();
m_data = QJsonDocument::fromJson(data).array();
endResetModel();
});
}
void ItineraryModel::sendToItinerary()
{
#ifndef Q_OS_ANDROID
auto job = new KIO::ApplicationLauncherJob(KService::serviceByDesktopName(QStringLiteral("org.kde.itinerary")));
job->setUrls({QUrl::fromLocalFile(m_path.mid(7))});
job->start();
#endif
}

View File

@@ -1,62 +0,0 @@
// SPDX-FileCopyrightText: 2024 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#pragma once
#include <QAbstractListModel>
#include <QPointer>
#include <QQmlEngine>
#include <QString>
#include "neochatconnection.h"
class ItineraryModel : public QAbstractListModel
{
Q_OBJECT
QML_ELEMENT
Q_PROPERTY(NeoChatConnection *connection READ connection WRITE setConnection NOTIFY connectionChanged)
Q_PROPERTY(QString path READ path WRITE setPath NOTIFY pathChanged)
public:
enum Roles {
NameRole = Qt::DisplayRole,
TypeRole,
DepartureStationRole,
ArrivalStationRole,
DepartureTimeRole,
ArrivalTimeRole,
AddressRole,
StartTimeRole,
EndTimeRole,
DeparturePlatformRole,
ArrivalPlatformRole,
CoachRole,
SeatRole,
};
Q_ENUM(Roles)
explicit ItineraryModel(QObject *parent = nullptr);
void setConnection(NeoChatConnection *connection);
NeoChatConnection *connection() const;
QVariant data(const QModelIndex &index, int role) const override;
int rowCount(const QModelIndex &parent = {}) const override;
QHash<int, QByteArray> roleNames() const override;
QString path() const;
void setPath(const QString &path);
Q_INVOKABLE void sendToItinerary();
Q_SIGNALS:
void connectionChanged();
void pathChanged();
private:
QPointer<NeoChatConnection> m_connection;
QJsonArray m_data;
QString m_path;
void loadData();
};

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 "mediamessagefiltermodel.h"
#include <Quotient/events/roommessageevent.h>
#include <Quotient/room.h> #include <Quotient/room.h>
#include "enums/delegatetype.h"
#include "messageeventmodel.h" #include "messageeventmodel.h"
#include "messagefiltermodel.h" #include "messagefiltermodel.h"
@@ -20,8 +20,8 @@ bool MediaMessageFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex
{ {
const QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); const QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
if (index.data(MessageEventModel::MediaInfoRole).toMap()[QLatin1String("mimeType")].toString().contains(QLatin1String("image")) if (index.data(MessageEventModel::DelegateTypeRole).toInt() == DelegateType::Image
|| index.data(MessageEventModel::MediaInfoRole).toMap()[QLatin1String("mimeType")].toString().contains(QLatin1String("video"))) { || index.data(MessageEventModel::DelegateTypeRole).toInt() == DelegateType::Video) {
return true; return true;
} }
return false; return false;
@@ -30,9 +30,9 @@ bool MediaMessageFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex
QVariant MediaMessageFilterModel::data(const QModelIndex &index, int role) const QVariant MediaMessageFilterModel::data(const QModelIndex &index, int role) const
{ {
if (role == SourceRole) { 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(); 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>(); auto progressInfo = mapToSource(index).data(MessageEventModel::ProgressInfoRole).value<Quotient::FileTransferInfo>();
if (progressInfo.completed()) { 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(); return mapToSource(index).data(MessageEventModel::MediaInfoRole).toMap()[QStringLiteral("tempInfo")].toMap()[QStringLiteral("source")].toUrl();
} }
if (role == TypeRole) { 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; return MediaType::Image;
} else { } else {
return MediaType::Video; 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 // SPDX-License-Identifier: GPL-3.0-only
#include "messageeventmodel.h" #include "messageeventmodel.h"
#include "linkpreviewer.h"
#include "messageeventmodel_logging.h" #include "messageeventmodel_logging.h"
#include "neochatconfig.h" #include "neochatconfig.h"
@@ -9,7 +10,6 @@
#include <Quotient/connection.h> #include <Quotient/connection.h>
#include <Quotient/csapi/rooms.h> #include <Quotient/csapi/rooms.h>
#include <Quotient/events/redactionevent.h> #include <Quotient/events/redactionevent.h>
#include <Quotient/events/roommessageevent.h>
#include <Quotient/events/stickerevent.h> #include <Quotient/events/stickerevent.h>
#include <Quotient/user.h> #include <Quotient/user.h>
@@ -22,8 +22,6 @@
#include "enums/delegatetype.h" #include "enums/delegatetype.h"
#include "eventhandler.h" #include "eventhandler.h"
#include "events/pollevent.h" #include "events/pollevent.h"
#include "linkpreviewer.h"
#include "messagecontentmodel.h"
#include "models/reactionmodel.h" #include "models/reactionmodel.h"
#include "texthandler.h" #include "texthandler.h"
@@ -33,6 +31,7 @@ QHash<int, QByteArray> MessageEventModel::roleNames() const
{ {
QHash<int, QByteArray> roles = QAbstractItemModel::roleNames(); QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();
roles[DelegateTypeRole] = "delegateType"; roles[DelegateTypeRole] = "delegateType";
roles[PlainText] = "plainText";
roles[EventIdRole] = "eventId"; roles[EventIdRole] = "eventId";
roles[TimeRole] = "time"; roles[TimeRole] = "time";
roles[TimeStringRole] = "timeString"; roles[TimeStringRole] = "timeString";
@@ -41,6 +40,15 @@ QHash<int, QByteArray> MessageEventModel::roleNames() const
roles[HighlightRole] = "isHighlighted"; roles[HighlightRole] = "isHighlighted";
roles[SpecialMarksRole] = "marks"; roles[SpecialMarksRole] = "marks";
roles[ProgressInfoRole] = "progressInfo"; 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[IsThreadedRole] = "isThreaded";
roles[ThreadRootRole] = "threadRoot"; roles[ThreadRootRole] = "threadRoot";
roles[ShowAuthorRole] = "showAuthor"; roles[ShowAuthorRole] = "showAuthor";
@@ -56,8 +64,10 @@ QHash<int, QByteArray> MessageEventModel::roleNames() const
roles[IsRedactedRole] = "isRedacted"; roles[IsRedactedRole] = "isRedacted";
roles[GenericDisplayRole] = "genericDisplay"; roles[GenericDisplayRole] = "genericDisplay";
roles[IsPendingRole] = "isPending"; roles[IsPendingRole] = "isPending";
roles[ContentModelRole] = "contentModel"; roles[LatitudeRole] = "latitude";
roles[MediaInfoRole] = "mediaInfo"; roles[LongitudeRole] = "longitude";
roles[AssetRole] = "asset";
roles[PollHandlerRole] = "pollHandler";
return roles; return roles;
} }
@@ -86,6 +96,7 @@ void MessageEventModel::setRoom(NeoChatRoom *room)
beginResetModel(); beginResetModel();
if (m_currentRoom) { if (m_currentRoom) {
m_currentRoom->disconnect(this); m_currentRoom->disconnect(this);
m_linkPreviewers.clear();
m_reactionModels.clear(); m_reactionModels.clear();
} }
@@ -108,6 +119,14 @@ void MessageEventModel::setRoom(NeoChatRoom *room)
room->getPreviousContent(50); room->getPreviousContent(50);
} }
lastReadEventId = room->lastFullyReadEventId(); 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) { connect(m_currentRoom, &Room::aboutToAddNewMessages, this, [this](RoomEventsRange events) {
for (auto &&event : events) { for (auto &&event : events) {
@@ -219,6 +238,7 @@ void MessageEventModel::setRoom(NeoChatRoom *room)
moveReadMarker(toEventId); moveReadMarker(toEventId);
}); });
connect(m_currentRoom, &Room::replacedEvent, this, [this](const RoomEvent *newEvent) { connect(m_currentRoom, &Room::replacedEvent, this, [this](const RoomEvent *newEvent) {
refreshLastUserEvents(refreshEvent(newEvent->id()) - timelineBaseIndex());
const RoomMessageEvent *message = eventCast<const RoomMessageEvent>(newEvent); const RoomMessageEvent *message = eventCast<const RoomMessageEvent>(newEvent);
if (message != nullptr) { if (message != nullptr) {
createEventObjects(message); createEventObjects(message);
@@ -245,6 +265,10 @@ void MessageEventModel::setRoom(NeoChatRoom *room)
refreshEventRoles(event->id(), {ReadMarkersRole, ReadMarkersStringRole, ExcessReadMarkersRole}); 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] { connect(m_currentRoom->connection(), &Connection::ignoredUsersListChanged, this, [this] {
beginResetModel(); beginResetModel();
endResetModel(); 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 QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
{ {
if (!checkIndex(idx, QAbstractItemModel::CheckIndexOption::IndexIsValid)) { 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 pendingIt = m_currentRoom->pendingEvents().crbegin() + std::min(row, timelineBaseIndex());
const auto &evt = isPending ? **pendingIt : **timelineIt; 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 (role == Qt::DisplayRole) {
if (evt.isRedacted()) { if (evt.isRedacted()) {
@@ -466,24 +494,16 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
return eventHandler.getRichBody(); 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) { if (role == GenericDisplayRole) {
return eventHandler.getGenericBody(); return eventHandler.getGenericBody();
} }
if (role == PlainText) {
return eventHandler.getPlainBody();
}
if (role == DelegateTypeRole) { if (role == DelegateTypeRole) {
return DelegateType::typeForEvent(evt); return eventHandler.getDelegateType();
} }
if (role == AuthorRole) { if (role == AuthorRole) {
@@ -541,6 +561,46 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
return eventHandler.getTimeString(true, QLocale::ShortFormat, isPending, lastUpdated); 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) { if (role == IsThreadedRole) {
return eventHandler.isThreaded(); return eventHandler.isThreaded();
} }
@@ -584,6 +644,18 @@ QVariant MessageEventModel::data(const QModelIndex &idx, int role) const
return false; return false;
} }
if (role == LatitudeRole) {
return eventHandler.getLatitude();
}
if (role == LongitudeRole) {
return eventHandler.getLongitude();
}
if (role == AssetRole) {
return eventHandler.getLocationAssetType();
}
if (role == ReadMarkersRole) { if (role == ReadMarkersRole) {
return eventHandler.getReadMarkers(); 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()); return row < static_cast<int>(m_currentRoom->pendingEvents().size());
} }
if (role == MediaInfoRole) { if (role == PollHandlerRole) {
return eventHandler.getMediaInfo(); return QVariant::fromValue<PollHandler *>(m_currentRoom->poll(evt.id()));
} }
return {}; return {};
@@ -654,6 +726,16 @@ void MessageEventModel::createEventObjects(const Quotient::RoomMessageEvent *eve
{ {
auto eventId = event->id(); 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 // ReactionModel handles updates to add and remove reactions, we only need to
// handle adding and removing whole models here. // handle adding and removing whole models here.
if (m_reactionModels.contains(eventId)) { if (m_reactionModels.contains(eventId)) {
@@ -681,7 +763,7 @@ void MessageEventModel::createEventObjects(const Quotient::RoomMessageEvent *eve
bool MessageEventModel::event(QEvent *event) bool MessageEventModel::event(QEvent *event)
{ {
if (event->type() == QEvent::ApplicationPaletteChange) { 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); return QObject::event(event);
} }

View File

@@ -40,6 +40,7 @@ public:
*/ */
enum EventRoles { enum EventRoles {
DelegateTypeRole = Qt::UserRole + 1, /**< The delegate type of the message. */ 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. */ EventIdRole, /**< The matrix event ID of the event. */
TimeRole, /**< The timestamp for when the event was sent (as a QDateTime). */ 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). */ 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. */ SpecialMarksRole, /**< Whether the event is hidden or not. */
ProgressInfoRole, /**< Progress info when downloading files. */ ProgressInfoRole, /**< Progress info when downloading files. */
GenericDisplayRole, /**< A generic string based upon the message type. */ 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. */ 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, IsThreadedRole,
ThreadRootRole, ThreadRootRole,
@@ -70,6 +80,10 @@ public:
AuthorDisplayNameRole, /**< The displayname for the event's sender; for name change events, the old displayname. */ AuthorDisplayNameRole, /**< The displayname for the event's sender; for name change events, the old displayname. */
IsRedactedRole, /**< Whether an event has been deleted. */ IsRedactedRole, /**< Whether an event has been deleted. */
IsPendingRole, /**< Whether an event is waiting to be accepted by the server. */ 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 LastRole, // Keep this last
}; };
Q_ENUM(EventRoles) Q_ENUM(EventRoles)
@@ -121,6 +135,7 @@ private:
bool movingEvent = false; bool movingEvent = false;
KFormat m_format; KFormat m_format;
QMap<QString, QSharedPointer<LinkPreviewer>> m_linkPreviewers;
QMap<QString, QSharedPointer<ReactionModel>> m_reactionModels; QMap<QString, QSharedPointer<ReactionModel>> m_reactionModels;
[[nodiscard]] int timelineBaseIndex() const; [[nodiscard]] int timelineBaseIndex() const;

View File

@@ -127,8 +127,9 @@ QString MessageFilterModel::aggregateEventToString(int sourceRow) const
chunks.removeDuplicates(); chunks.removeDuplicates();
// The author text is either "n users" if > 1 user or the matrix.to link to a single user. // 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()) 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(), .arg(uniqueAuthors[0].toMap()[QStringLiteral("id")].toString(),
uniqueAuthors[0].toMap()[QStringLiteral("color")].toString(),
uniqueAuthors[0].toMap()[QStringLiteral("displayName")].toString().toHtmlEscaped()); uniqueAuthors[0].toMap()[QStringLiteral("displayName")].toString().toHtmlEscaped());
QString chunksText; QString chunksText;

View File

@@ -122,7 +122,9 @@ void NotificationsModel::loadData()
const auto &authorAvatar = avatar.isValid() && avatar.scheme() == QStringLiteral("mxc") ? avatar : QUrl(); const auto &authorAvatar = avatar.isValid() && avatar.scheme() == QStringLiteral("mxc") ? avatar : QUrl();
const auto &roomEvent = eventCast<const RoomEvent>(notification.event.get()); 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()); beginInsertRows({}, m_notifications.length(), m_notifications.length());
m_notifications += Notification{ m_notifications += Notification{
.roomId = notification.roomId, .roomId = notification.roomId,

View File

@@ -5,8 +5,6 @@
#include <Quotient/connection.h> #include <Quotient/connection.h>
#include "publicroomlist_logging.h"
using namespace Quotient; using namespace Quotient;
PublicRoomListModel::PublicRoomListModel(QObject *parent) PublicRoomListModel::PublicRoomListModel(QObject *parent)
@@ -43,7 +41,7 @@ void PublicRoomListModel::setConnection(Connection *conn)
if (job) { if (job) {
job->abandon(); job->abandon();
job = nullptr; job = nullptr;
Q_EMIT searchingChanged(); Q_EMIT loadingChanged();
} }
if (m_connection) { if (m_connection) {
@@ -52,6 +50,7 @@ void PublicRoomListModel::setConnection(Connection *conn)
Q_EMIT connectionChanged(); Q_EMIT connectionChanged();
Q_EMIT serverChanged(); Q_EMIT serverChanged();
Q_EMIT hasMoreChanged();
} }
QString PublicRoomListModel::server() const QString PublicRoomListModel::server() const
@@ -72,13 +71,14 @@ void PublicRoomListModel::setServer(const QString &value)
nextBatch = QString(); nextBatch = QString();
attempted = false; attempted = false;
rooms.clear(); rooms.clear();
Q_EMIT loadingChanged();
endResetModel(); endResetModel();
if (job) { if (job) {
job->abandon(); job->abandon();
job = nullptr; job = nullptr;
Q_EMIT searchingChanged(); Q_EMIT loadingChanged();
} }
if (m_connection) { if (m_connection) {
@@ -86,30 +86,42 @@ void PublicRoomListModel::setServer(const QString &value)
} }
Q_EMIT serverChanged(); Q_EMIT serverChanged();
Q_EMIT hasMoreChanged();
} }
QString PublicRoomListModel::searchText() const QString PublicRoomListModel::keyword() const
{ {
return m_searchText; return m_keyword;
} }
void PublicRoomListModel::setSearchText(const QString &value) void PublicRoomListModel::setKeyword(const QString &value)
{ {
if (m_searchText == value) { if (m_keyword == value) {
return; return;
} }
m_searchText = value; m_keyword = value;
Q_EMIT searchTextChanged();
beginResetModel();
nextBatch = QString(); nextBatch = QString();
attempted = false; attempted = false;
rooms.clear();
endResetModel();
if (job) { if (job) {
job->abandon(); job->abandon();
job = nullptr; job = nullptr;
Q_EMIT searchingChanged(); Q_EMIT loadingChanged();
} }
if (m_connection) {
next();
}
Q_EMIT keywordChanged();
Q_EMIT hasMoreChanged();
} }
bool PublicRoomListModel::showOnlySpaces() const bool PublicRoomListModel::showOnlySpaces() const
@@ -126,28 +138,15 @@ void PublicRoomListModel::setShowOnlySpaces(bool showOnlySpaces)
Q_EMIT showOnlySpacesChanged(); Q_EMIT showOnlySpacesChanged();
} }
void PublicRoomListModel::search(int limit) void PublicRoomListModel::next(int count)
{ {
if (limit < 1 || attempted) { if (count < 1) {
return; return;
} }
if (job) { if (job) {
qCDebug(PublicRoomList) << "Other job running, ignore"; qDebug() << "PublicRoomListModel: Other jobs running, ignore";
return;
}
next(limit);
}
void PublicRoomListModel::next(int limit)
{
if (m_connection == nullptr || limit < 1) {
return;
}
if (job) {
qCDebug(PublicRoomList) << "Other job running, ignore";
return; return;
} }
@@ -155,17 +154,11 @@ void PublicRoomListModel::next(int limit)
if (m_showOnlySpaces) { if (m_showOnlySpaces) {
roomTypes += QLatin1String("m.space"); roomTypes += QLatin1String("m.space");
} }
job = m_connection->callApi<QueryPublicRoomsJob>(m_server, limit, nextBatch, QueryPublicRoomsJob::Filter{m_searchText, roomTypes}); job = m_connection->callApi<QueryPublicRoomsJob>(m_server, count, nextBatch, QueryPublicRoomsJob::Filter{m_keyword, roomTypes});
Q_EMIT searchingChanged(); Q_EMIT loadingChanged();
connect(job, &BaseJob::finished, this, [this] { connect(job, &BaseJob::finished, this, [this] {
if (!attempted) { attempted = true;
beginResetModel();
rooms.clear();
endResetModel();
attempted = true;
}
if (job->status() == BaseJob::Success) { if (job->status() == BaseJob::Success) {
nextBatch = job->nextBatch(); nextBatch = job->nextBatch();
@@ -173,10 +166,14 @@ void PublicRoomListModel::next(int limit)
this->beginInsertRows({}, rooms.count(), rooms.count() + job->chunk().count() - 1); this->beginInsertRows({}, rooms.count(), rooms.count() + job->chunk().count() - 1);
rooms.append(job->chunk()); rooms.append(job->chunk());
this->endInsertRows(); this->endInsertRows();
if (job->nextBatch().isEmpty()) {
Q_EMIT hasMoreChanged();
}
} }
this->job = nullptr; this->job = nullptr;
Q_EMIT searchingChanged(); Q_EMIT loadingChanged();
}); });
} }
@@ -187,7 +184,8 @@ QVariant PublicRoomListModel::data(const QModelIndex &index, int role) const
} }
if (index.row() >= rooms.count()) { if (index.row() >= rooms.count()) {
qCDebug(PublicRoomList) << "something's wrong: index.row() >= rooms.count()"; qDebug() << "PublicRoomListModel, something's wrong: index.row() >= "
"rooms.count()";
return {}; return {};
} }
auto room = rooms.at(index.row()); auto room = rooms.at(index.row());
@@ -273,19 +271,12 @@ int PublicRoomListModel::rowCount(const QModelIndex &parent) const
return rooms.count(); return rooms.count();
} }
bool PublicRoomListModel::canFetchMore(const QModelIndex &parent) const bool PublicRoomListModel::hasMore() const
{ {
Q_UNUSED(parent) return !(attempted && nextBatch.isEmpty());
return !nextBatch.isEmpty();
} }
void PublicRoomListModel::fetchMore(const QModelIndex &parent) bool PublicRoomListModel::loading() const
{
Q_UNUSED(parent)
next();
}
bool PublicRoomListModel::searching() const
{ {
return job != nullptr; return job != nullptr;
} }

View File

@@ -41,9 +41,9 @@ class PublicRoomListModel : public QAbstractListModel
Q_PROPERTY(QString server READ server WRITE setServer NOTIFY serverChanged) Q_PROPERTY(QString server READ server WRITE setServer NOTIFY serverChanged)
/** /**
* @brief The text to search the public room list for. * @brief The filter keyword for the list of public rooms.
*/ */
Q_PROPERTY(QString searchText READ searchText WRITE setSearchText NOTIFY searchTextChanged) Q_PROPERTY(QString keyword READ keyword WRITE setKeyword NOTIFY keywordChanged)
/** /**
* @brief Whether only space rooms should be shown. * @brief Whether only space rooms should be shown.
@@ -51,9 +51,14 @@ class PublicRoomListModel : public QAbstractListModel
Q_PROPERTY(bool showOnlySpaces READ showOnlySpaces WRITE setShowOnlySpaces NOTIFY showOnlySpacesChanged) Q_PROPERTY(bool showOnlySpaces READ showOnlySpaces WRITE setShowOnlySpaces NOTIFY showOnlySpacesChanged)
/** /**
* @brief Whether the model is searching. * @brief Whether the model has more items to load.
*/ */
Q_PROPERTY(bool searching READ searching NOTIFY searchingChanged) Q_PROPERTY(bool hasMore READ hasMore NOTIFY hasMoreChanged)
/**
* @biref Whether the model is still loading.
*/
Q_PROPERTY(bool loading READ loading NOTIFY loadingChanged)
public: public:
/** /**
@@ -100,38 +105,31 @@ public:
[[nodiscard]] QString server() const; [[nodiscard]] QString server() const;
void setServer(const QString &value); void setServer(const QString &value);
[[nodiscard]] QString searchText() const; [[nodiscard]] QString keyword() const;
void setSearchText(const QString &searchText); void setKeyword(const QString &value);
[[nodiscard]] bool showOnlySpaces() const; [[nodiscard]] bool showOnlySpaces() const;
void setShowOnlySpaces(bool showOnlySpaces); void setShowOnlySpaces(bool showOnlySpaces);
[[nodiscard]] bool searching() const; [[nodiscard]] bool hasMore() const;
/** [[nodiscard]] bool loading() const;
* @brief Search the room directory.
*
* @param limit the maximum number of rooms to load.
*/
Q_INVOKABLE void search(int limit = 50);
private:
QPointer<Quotient::Connection> m_connection = nullptr;
QString m_server;
QString m_searchText;
bool m_showOnlySpaces = false;
/** /**
* @brief Load the next set of rooms. * @brief Load the next set of rooms.
* *
* @param limit the maximum number of rooms to load. * @param count the maximum number of rooms to load.
*/ */
void next(int limit = 50); Q_INVOKABLE void next(int count = 50);
bool canFetchMore(const QModelIndex &parent) const override;
void fetchMore(const QModelIndex &parent) override; private:
Quotient::Connection *m_connection = nullptr;
QString m_server;
QString m_keyword;
bool m_showOnlySpaces = false;
bool attempted = false; bool attempted = false;
bool m_searching = false; bool m_loading = false;
QString nextBatch; QString nextBatch;
QList<Quotient::PublicRoomsChunk> rooms; QList<Quotient::PublicRoomsChunk> rooms;
@@ -141,7 +139,8 @@ private:
Q_SIGNALS: Q_SIGNALS:
void connectionChanged(); void connectionChanged();
void serverChanged(); void serverChanged();
void searchTextChanged(); void keywordChanged();
void showOnlySpacesChanged(); void showOnlySpacesChanged();
void searchingChanged(); void hasMoreChanged();
void loadingChanged();
}; };

View File

@@ -298,7 +298,30 @@ QVariant RoomListModel::data(const QModelIndex &index, int role) const
return room->topic(); return room->topic();
} }
if (role == CategoryRole) { 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) { if (role == NotificationCountRole) {
return room->notificationCount(); return room->notificationCount();
@@ -325,7 +348,9 @@ QVariant RoomListModel::data(const QModelIndex &index, int role) const
if (room->lastEvent() == nullptr || room->lastEventIsSpoiler()) { if (room->lastEvent() == nullptr || room->lastEventIsSpoiler()) {
return QString(); return QString();
} }
EventHandler eventHandler(room, room->lastEvent()); EventHandler eventHandler;
eventHandler.setRoom(room);
eventHandler.setEvent(room->lastEvent());
return eventHandler.subtitleText(); return eventHandler.subtitleText();
} }
if (role == AvatarImageRole) { if (role == AvatarImageRole) {
@@ -338,14 +363,11 @@ QVariant RoomListModel::data(const QModelIndex &index, int role) const
return room->isSpace(); return room->isSpace();
} }
if (role == IsChildSpaceRole) { if (role == IsChildSpaceRole) {
return SpaceHierarchyCache::instance().isChild(room->id()); return SpaceHierarchyCache::instance().isChildSpace(room->id());
} }
if (role == ReplacementIdRole) { if (role == ReplacementIdRole) {
return room->successorId(); return room->successorId();
} }
if (role == IsDirectChat) {
return room->isDirectChat();
}
return QVariant(); return QVariant();
} }
@@ -379,30 +401,9 @@ QHash<int, QByteArray> RoomListModel::roleNames() const
roles[IsSpaceRole] = "isSpace"; roles[IsSpaceRole] = "isSpace";
roles[RoomIdRole] = "roomId"; roles[RoomIdRole] = "roomId";
roles[IsChildSpaceRole] = "isChildSpace"; roles[IsChildSpaceRole] = "isChildSpace";
roles[IsDirectChat] = "isDirectChat";
return roles; 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) QString RoomListModel::categoryName(int category)
{ {
switch (category) { switch (category) {
@@ -411,7 +412,7 @@ QString RoomListModel::categoryName(int category)
case NeoChatRoomType::Favorite: case NeoChatRoomType::Favorite:
return i18n("Favorite"); return i18n("Favorite");
case NeoChatRoomType::Direct: case NeoChatRoomType::Direct:
return i18n("Friends"); return i18n("Direct Messages");
case NeoChatRoomType::Normal: case NeoChatRoomType::Normal:
return i18n("Normal"); return i18n("Normal");
case NeoChatRoomType::Deprioritized: case NeoChatRoomType::Deprioritized:

View File

@@ -77,7 +77,6 @@ public:
IsSpaceRole, /**< Whether the room is a space. */ IsSpaceRole, /**< Whether the room is a space. */
IsChildSpaceRole, /**< Whether this space is a child of a different space. */ IsChildSpaceRole, /**< Whether this space is a child of a different space. */
ReplacementIdRole, /**< The room id of the room replacing this one, if any. */ ReplacementIdRole, /**< The room id of the room replacing this one, if any. */
IsDirectChat, /**< Whether this room is a direct chat. */
}; };
Q_ENUM(EventRoles) Q_ENUM(EventRoles)
@@ -116,11 +115,6 @@ public:
*/ */
Q_INVOKABLE [[nodiscard]] NeoChatRoom *roomAt(int row) const; 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. * @brief Return a string to represent the given room category.
*/ */

View File

@@ -3,9 +3,8 @@
#include "searchmodel.h" #include "searchmodel.h"
#include "enums/delegatetype.h"
#include "eventhandler.h" #include "eventhandler.h"
#include "models/messagecontentmodel.h" #include "messageeventmodel.h"
#include "neochatroom.h" #include "neochatroom.h"
#include <QGuiApplication> #include <QGuiApplication>
@@ -37,7 +36,7 @@ void SearchModel::setSearchText(const QString &searchText)
void SearchModel::search() void SearchModel::search()
{ {
Q_ASSERT(m_room); Q_ASSERT(m_connection);
setSearching(true); setSearching(true);
if (m_job) { if (m_job) {
m_job->abandon(); m_job->abandon();
@@ -63,7 +62,7 @@ void SearchModel::search()
}; };
auto job = m_room->connection()->callApi<SearchJob>(SearchJob::Categories{criteria}); auto job = m_connection->callApi<SearchJob>(SearchJob::Categories{criteria});
m_job = job; m_job = job;
connect(job, &BaseJob::finished, this, [this, job] { connect(job, &BaseJob::finished, this, [this, job] {
beginResetModel(); beginResetModel();
@@ -75,14 +74,29 @@ void SearchModel::search()
}); });
} }
Connection *SearchModel::connection() const
{
return m_connection;
}
void SearchModel::setConnection(Connection *connection)
{
m_connection = connection;
Q_EMIT connectionChanged();
}
QVariant SearchModel::data(const QModelIndex &index, int role) const QVariant SearchModel::data(const QModelIndex &index, int role) const
{ {
auto row = index.row(); auto row = index.row();
const auto &event = *m_result->results[row].result; const auto &event = *m_result->results[row].result;
EventHandler eventHandler(m_room, &event); EventHandler eventHandler;
eventHandler.setRoom(m_room);
eventHandler.setEvent(&event);
switch (role) { switch (role) {
case DisplayRole:
return eventHandler.getRichBody();
case ShowAuthorRole: case ShowAuthorRole:
return true; return true;
case AuthorRole: case AuthorRole:
@@ -102,8 +116,22 @@ QVariant SearchModel::data(const QModelIndex &index, int role) const
return false; return false;
case ShowReadMarkersRole: case ShowReadMarkersRole:
return false; 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: case IsPendingRole:
return false; return false;
case ShowLinkPreviewRole:
return false;
case HighlightRole: case HighlightRole:
return eventHandler.isHighlighted(); return eventHandler.isHighlighted();
case EventIdRole: case EventIdRole:
@@ -112,17 +140,6 @@ QVariant SearchModel::data(const QModelIndex &index, int role) const
return eventHandler.isThreaded(); return eventHandler.isThreaded();
case ThreadRootRole: case ThreadRootRole:
return eventHandler.threadRoot(); 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; return DelegateType::Message;
} }
@@ -140,6 +157,7 @@ QHash<int, QByteArray> SearchModel::roleNames() const
{ {
return { return {
{DelegateTypeRole, "delegateType"}, {DelegateTypeRole, "delegateType"},
{DisplayRole, "display"},
{AuthorRole, "author"}, {AuthorRole, "author"},
{ShowSectionRole, "showSection"}, {ShowSectionRole, "showSection"},
{SectionRole, "section"}, {SectionRole, "section"},
@@ -150,15 +168,25 @@ QHash<int, QByteArray> SearchModel::roleNames() const
{ExcessReadMarkersRole, "excessReadMarkers"}, {ExcessReadMarkersRole, "excessReadMarkers"},
{HighlightRole, "isHighlighted"}, {HighlightRole, "isHighlighted"},
{ReadMarkersString, "readMarkersString"}, {ReadMarkersString, "readMarkersString"},
{PlainTextRole, "plainText"},
{VerifiedRole, "verified"}, {VerifiedRole, "verified"},
{ProgressInfoRole, "progressInfo"},
{ShowReactionsRole, "showReactions"}, {ShowReactionsRole, "showReactions"},
{IsReplyRole, "isReply"},
{ReplyAuthorRole, "replyAuthor"},
{ReplyIdRole, "replyId"},
{ReplyDelegateTypeRole, "replyDelegateType"},
{ReplyDisplayRole, "replyDisplay"},
{ReplyMediaInfoRole, "replyMediaInfo"},
{ReactionRole, "reaction"}, {ReactionRole, "reaction"},
{ReadMarkersRole, "readMarkers"}, {ReadMarkersRole, "readMarkers"},
{IsPendingRole, "isPending"}, {IsPendingRole, "isPending"},
{ShowReadMarkersRole, "showReadMarkers"}, {ShowReadMarkersRole, "showReadMarkers"},
{MimeTypeRole, "mimeType"},
{ShowLinkPreviewRole, "showLinkPreview"},
{LinkPreviewRole, "linkPreview"},
{IsThreadedRole, "isThreaded"}, {IsThreadedRole, "isThreaded"},
{ThreadRootRole, "threadRoot"}, {ThreadRootRole, "threadRoot"},
{ContentModelRole, "contentModel"},
}; };
} }
@@ -174,6 +202,19 @@ void SearchModel::setRoom(NeoChatRoom *room)
} }
m_room = room; m_room = room;
Q_EMIT roomChanged(); 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 bool SearchModel::searching() const

View File

@@ -31,6 +31,11 @@ class SearchModel : public QAbstractListModel
*/ */
Q_PROPERTY(QString searchText READ searchText WRITE setSearchText NOTIFY searchTextChanged) Q_PROPERTY(QString searchText READ searchText WRITE setSearchText NOTIFY searchTextChanged)
/**
* @brief The current connection that the model is using to search for messages.
*/
Q_PROPERTY(Quotient::Connection *connection READ connection WRITE setConnection NOTIFY connectionChanged)
/** /**
* @brief The current room that the search is being done from. * @brief The current room that the search is being done from.
*/ */
@@ -51,7 +56,8 @@ public:
* since the same delegates are used. * since the same delegates are used.
*/ */
enum Roles { enum Roles {
DelegateTypeRole = Qt::DisplayRole + 1, DisplayRole = Qt::DisplayRole,
DelegateTypeRole,
ShowAuthorRole, ShowAuthorRole,
AuthorRole, AuthorRole,
ShowSectionRole, ShowSectionRole,
@@ -62,15 +68,25 @@ public:
ExcessReadMarkersRole, ExcessReadMarkersRole,
HighlightRole, HighlightRole,
ReadMarkersString, ReadMarkersString,
PlainTextRole,
VerifiedRole, VerifiedRole,
ProgressInfoRole,
ShowReactionsRole, ShowReactionsRole,
IsReplyRole,
ReplyAuthorRole,
ReplyIdRole,
ReplyDelegateTypeRole,
ReplyDisplayRole,
ReplyMediaInfoRole,
ReactionRole, ReactionRole,
ReadMarkersRole, ReadMarkersRole,
IsPendingRole, IsPendingRole,
ShowReadMarkersRole, ShowReadMarkersRole,
MimeTypeRole,
ShowLinkPreviewRole,
LinkPreviewRole,
IsThreadedRole, IsThreadedRole,
ThreadRootRole, ThreadRootRole,
ContentModelRole,
}; };
Q_ENUM(Roles) Q_ENUM(Roles)
explicit SearchModel(QObject *parent = nullptr); explicit SearchModel(QObject *parent = nullptr);
@@ -78,6 +94,9 @@ public:
QString searchText() const; QString searchText() const;
void setSearchText(const QString &searchText); void setSearchText(const QString &searchText);
Quotient::Connection *connection() const;
void setConnection(Quotient::Connection *connection);
NeoChatRoom *room() const; NeoChatRoom *room() const;
void setRoom(NeoChatRoom *room); void setRoom(NeoChatRoom *room);
@@ -111,6 +130,7 @@ public:
Q_SIGNALS: Q_SIGNALS:
void searchTextChanged(); void searchTextChanged();
void connectionChanged();
void roomChanged(); void roomChanged();
void searchingChanged(); void searchingChanged();
@@ -121,6 +141,7 @@ private:
void setSearching(bool searching); void setSearching(bool searching);
QString m_searchText; QString m_searchText;
Quotient::Connection *m_connection = nullptr;
NeoChatRoom *m_room = nullptr; NeoChatRoom *m_room = nullptr;
Quotient::Omittable<Quotient::SearchJob::ResultRoomEvents> m_result = Quotient::none; Quotient::Omittable<Quotient::SearchJob::ResultRoomEvents> m_result = Quotient::none;
Quotient::SearchJob *m_job = nullptr; Quotient::SearchJob *m_job = nullptr;

View File

@@ -83,21 +83,6 @@ bool SortFilterRoomListModel::filterAcceptsRow(int source_row, const QModelIndex
{ {
Q_UNUSED(source_parent); Q_UNUSED(source_parent);
bool acceptRoom =
sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::DisplayNameRole).toString().contains(m_filterText, Qt::CaseInsensitive)
&& sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::IsSpaceRole).toBool() == false;
bool isDirectChat = sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::IsDirectChat).toBool();
// In `show direct chats` mode we only care about whether or not it's a direct chat or if the filter string matches.'
if (m_mode == DirectChats) {
return isDirectChat && acceptRoom;
}
// When not in `show direct chats` mode, filter them out.
if (isDirectChat && m_mode == Rooms) {
return false;
}
if (sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::JoinStateRole).toString() == QStringLiteral("upgraded") if (sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::JoinStateRole).toString() == QStringLiteral("upgraded")
&& dynamic_cast<RoomListModel *>(sourceModel()) && dynamic_cast<RoomListModel *>(sourceModel())
->connection() ->connection()
@@ -105,11 +90,12 @@ bool SortFilterRoomListModel::filterAcceptsRow(int source_row, const QModelIndex
return false; return false;
} }
bool acceptRoom =
sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::DisplayNameRole).toString().contains(m_filterText, Qt::CaseInsensitive)
&& sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::IsSpaceRole).toBool() == false;
if (m_activeSpaceId.isEmpty()) { if (m_activeSpaceId.isEmpty()) {
if (!SpaceHierarchyCache::instance().isChild(sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::RoomIdRole).toString())) { return acceptRoom;
return acceptRoom;
}
return false;
} else { } else {
const auto &rooms = SpaceHierarchyCache::instance().getRoomListForSpace(m_activeSpaceId, false); 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()) return std::find(rooms.begin(), rooms.end(), sourceModel()->data(sourceModel()->index(source_row, 0), RoomListModel::RoomIdRole).toString())
@@ -130,20 +116,4 @@ void SortFilterRoomListModel::setActiveSpaceId(const QString &spaceId)
invalidate(); invalidate();
} }
SortFilterRoomListModel::Mode SortFilterRoomListModel::mode() const
{
return m_mode;
}
void SortFilterRoomListModel::setMode(SortFilterRoomListModel::Mode mode)
{
if (m_mode == mode) {
return;
}
m_mode = mode;
Q_EMIT modeChanged();
invalidate();
}
#include "moc_sortfilterroomlistmodel.cpp" #include "moc_sortfilterroomlistmodel.cpp"

View File

@@ -47,11 +47,6 @@ class SortFilterRoomListModel : public QSortFilterProxyModel
*/ */
Q_PROPERTY(QString activeSpaceId READ activeSpaceId WRITE setActiveSpaceId NOTIFY activeSpaceIdChanged) Q_PROPERTY(QString activeSpaceId READ activeSpaceId WRITE setActiveSpaceId NOTIFY activeSpaceIdChanged)
/**
* @brief Whether only direct chats should be shown.
*/
Q_PROPERTY(Mode mode READ mode WRITE setMode NOTIFY modeChanged)
public: public:
enum RoomSortOrder { enum RoomSortOrder {
Alphabetical, Alphabetical,
@@ -60,13 +55,6 @@ public:
}; };
Q_ENUM(RoomSortOrder) Q_ENUM(RoomSortOrder)
enum Mode {
Rooms,
DirectChats,
All,
};
Q_ENUM(Mode)
explicit SortFilterRoomListModel(QObject *parent = nullptr); explicit SortFilterRoomListModel(QObject *parent = nullptr);
void setRoomSortOrder(RoomSortOrder sortOrder); void setRoomSortOrder(RoomSortOrder sortOrder);
@@ -78,9 +66,6 @@ public:
QString activeSpaceId() const; QString activeSpaceId() const;
void setActiveSpaceId(const QString &spaceId); void setActiveSpaceId(const QString &spaceId);
Mode mode() const;
void setMode(Mode mode);
protected: protected:
/** /**
* @brief Returns true if the value of source_left is less than source_right. * @brief Returns true if the value of source_left is less than source_right.
@@ -100,11 +85,9 @@ Q_SIGNALS:
void roomSortOrderChanged(); void roomSortOrderChanged();
void filterTextChanged(); void filterTextChanged();
void activeSpaceIdChanged(); void activeSpaceIdChanged();
void modeChanged();
private: private:
RoomSortOrder m_sortOrder = Categories; RoomSortOrder m_sortOrder = Categories;
Mode m_mode = All;
QString m_filterText; QString m_filterText;
QString m_activeSpaceId; QString m_activeSpaceId;
}; };

View File

@@ -244,20 +244,6 @@ QVariant SpaceChildrenModel::data(const QModelIndex &index, int role) const
} }
return QVariant::fromValue(nullptr); 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 {}; return {};
} }
@@ -339,8 +325,6 @@ QHash<int, QByteArray> SpaceChildrenModel::roleNames() const
roles[IsDeclaredParentRole] = "isDeclaredParent"; roles[IsDeclaredParentRole] = "isDeclaredParent";
roles[CanRemove] = "canRemove"; roles[CanRemove] = "canRemove";
roles[ParentRoomRole] = "parentRoom"; roles[ParentRoomRole] = "parentRoom";
roles[OrderRole] = "order";
roles[ChildTimestampRole] = "childTimestamp";
return roles; return roles;
} }

View File

@@ -51,8 +51,6 @@ public:
IsDeclaredParentRole, IsDeclaredParentRole,
CanRemove, CanRemove,
ParentRoomRole, ParentRoomRole,
OrderRole,
ChildTimestampRole,
}; };
explicit SpaceChildrenModel(QObject *parent = nullptr); 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 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::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()) {
return false; return false;
} }
if (!source_left.data(SpaceChildrenModel::OrderRole).toString().isEmpty() && !source_right.data(SpaceChildrenModel::OrderRole).toString().isEmpty()) { return true;
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();
} }
bool SpaceChildSortFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const bool SpaceChildSortFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const

View File

@@ -141,22 +141,6 @@ bool SpaceTreeItem::isSpace() const
return m_isSpace; 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 QJsonObject SpaceTreeItem::childStateContent(const SpaceTreeItem *child) const
{ {
if (child == nullptr) { if (child == nullptr) {

View File

@@ -125,11 +125,6 @@ public:
*/ */
bool isSpace() const; 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. * @brief Return the m.space.child state event content for the given child.
*/ */

View File

@@ -26,6 +26,7 @@ void UserDirectoryListModel::setConnection(Connection *conn)
beginResetModel(); beginResetModel();
m_limited = false;
attempted = false; attempted = false;
users.clear(); users.clear();
@@ -36,50 +37,53 @@ void UserDirectoryListModel::setConnection(Connection *conn)
endResetModel(); endResetModel();
m_connection = conn; m_connection = conn;
if (job) {
job->abandon();
job = nullptr;
}
Q_EMIT connectionChanged(); Q_EMIT connectionChanged();
Q_EMIT limitedChanged();
if (m_job) {
m_job->abandon();
m_job = nullptr;
Q_EMIT searchingChanged();
}
} }
QString UserDirectoryListModel::searchText() const QString UserDirectoryListModel::keyword() const
{ {
return m_searchText; return m_keyword;
} }
void UserDirectoryListModel::setSearchText(const QString &value) void UserDirectoryListModel::setKeyword(const QString &value)
{ {
if (m_searchText == value) { if (m_keyword == value) {
return; return;
} }
m_searchText = value; m_keyword = value;
Q_EMIT searchTextChanged();
if (m_job) {
m_job->abandon();
m_job = nullptr;
Q_EMIT searchingChanged();
}
m_limited = false;
attempted = false; attempted = false;
if (job) {
job->abandon();
job = nullptr;
}
Q_EMIT keywordChanged();
Q_EMIT limitedChanged();
} }
bool UserDirectoryListModel::searching() const bool UserDirectoryListModel::limited() const
{ {
return m_job != nullptr; return m_limited;
} }
void UserDirectoryListModel::search(int limit) void UserDirectoryListModel::search(int count)
{ {
if (limit < 1) { if (count < 1) {
return; return;
} }
if (m_job) { if (job) {
qDebug() << "UserDirectoryListModel: Other jobs running, ignore"; qDebug() << "UserDirectoryListModel: Other jobs running, ignore";
return; return;
@@ -89,22 +93,25 @@ void UserDirectoryListModel::search(int limit)
return; return;
} }
m_job = m_connection->callApi<SearchUserDirectoryJob>(m_searchText, limit); job = m_connection->callApi<SearchUserDirectoryJob>(m_keyword, count);
Q_EMIT searchingChanged();
connect(m_job, &BaseJob::finished, this, [this] { connect(job, &BaseJob::finished, this, [this] {
attempted = true; attempted = true;
if (m_job->status() == BaseJob::Success) { if (job->status() == BaseJob::Success) {
auto users = m_job->results(); auto users = job->results();
this->beginResetModel(); this->beginResetModel();
this->users = users; this->users = users;
this->m_limited = job->limited();
this->endResetModel(); this->endResetModel();
} }
this->m_job = nullptr; this->job = nullptr;
Q_EMIT searchingChanged();
Q_EMIT limitedChanged();
}); });
} }
@@ -120,7 +127,7 @@ QVariant UserDirectoryListModel::data(const QModelIndex &index, int role) const
return {}; return {};
} }
auto user = users.at(index.row()); auto user = users.at(index.row());
if (role == DisplayNameRole) { if (role == NameRole) {
auto displayName = user.displayName; auto displayName = user.displayName;
if (!displayName.isEmpty()) { if (!displayName.isEmpty()) {
return displayName; return displayName;
@@ -135,17 +142,18 @@ QVariant UserDirectoryListModel::data(const QModelIndex &index, int role) const
} }
if (role == AvatarRole) { if (role == AvatarRole) {
auto avatarUrl = user.avatarUrl; auto avatarUrl = user.avatarUrl;
if (avatarUrl.isEmpty() || !m_connection) {
return QUrl(); if (avatarUrl.isEmpty()) {
return QString();
} }
return m_connection->makeMediaUrl(avatarUrl); return avatarUrl.url().remove(0, 6);
} }
if (role == UserIDRole) { if (role == UserIDRole) {
return user.userId; return user.userId;
} }
if (role == DirectChatExistsRole) { if (role == DirectChatsRole) {
if (!m_connection) { if (!m_connection) {
return false; return QStringList();
}; };
auto userObj = m_connection->user(user.userId); auto userObj = m_connection->user(user.userId);
@@ -154,11 +162,11 @@ QVariant UserDirectoryListModel::data(const QModelIndex &index, int role) const
if (userObj && directChats.contains(userObj)) { if (userObj && directChats.contains(userObj)) {
auto directChatsForUser = directChats.values(userObj); auto directChatsForUser = directChats.values(userObj);
if (!directChatsForUser.isEmpty()) { if (!directChatsForUser.isEmpty()) {
return true; return QVariant::fromValue(directChatsForUser);
} }
} }
return false; return QStringList();
} }
return {}; return {};
@@ -168,10 +176,10 @@ QHash<int, QByteArray> UserDirectoryListModel::roleNames() const
{ {
QHash<int, QByteArray> roles; QHash<int, QByteArray> roles;
roles[DisplayNameRole] = "displayName"; roles[NameRole] = "name";
roles[AvatarRole] = "avatarUrl"; roles[AvatarRole] = "avatar";
roles[UserIDRole] = "userId"; roles[UserIDRole] = "userID";
roles[DirectChatExistsRole] = "directChatExists"; roles[DirectChatsRole] = "directChats";
return roles; return roles;
} }

View File

@@ -35,24 +35,24 @@ class UserDirectoryListModel : public QAbstractListModel
Q_PROPERTY(Quotient::Connection *connection READ connection WRITE setConnection NOTIFY connectionChanged) Q_PROPERTY(Quotient::Connection *connection READ connection WRITE setConnection NOTIFY connectionChanged)
/** /**
* @brief The text to search the public room list for. * @brief The keyword to use in the search.
*/ */
Q_PROPERTY(QString searchText READ searchText WRITE setSearchText NOTIFY searchTextChanged) Q_PROPERTY(QString keyword READ keyword WRITE setKeyword NOTIFY keywordChanged)
/** /**
* @brief Whether the model is searching. * @brief Whether the current results have been truncated.
*/ */
Q_PROPERTY(bool searching READ searching NOTIFY searchingChanged) Q_PROPERTY(bool limited READ limited NOTIFY limitedChanged)
public: public:
/** /**
* @brief Defines the model roles. * @brief Defines the model roles.
*/ */
enum EventRoles { enum EventRoles {
DisplayNameRole = Qt::DisplayRole, /**< The user's display name. */ NameRole = Qt::DisplayRole + 1, /**< The user's display name. */
AvatarRole, /**< The source URL for the user's avatar. */ AvatarRole, /**< The source URL for the user's avatar. */
UserIDRole, /**< Matrix ID of the user. */ UserIDRole, /**< Matrix ID of the user. */
DirectChatExistsRole, /**< Whether there is already a direct chat with the user. */ DirectChatsRole, /**< A list of direct chat matrix IDs with the user. */
}; };
explicit UserDirectoryListModel(QObject *parent = nullptr); explicit UserDirectoryListModel(QObject *parent = nullptr);
@@ -60,17 +60,17 @@ public:
[[nodiscard]] Quotient::Connection *connection() const; [[nodiscard]] Quotient::Connection *connection() const;
void setConnection(Quotient::Connection *conn); void setConnection(Quotient::Connection *conn);
[[nodiscard]] QString searchText() const; [[nodiscard]] QString keyword() const;
void setSearchText(const QString &searchText); void setKeyword(const QString &value);
[[nodiscard]] bool searching() const; [[nodiscard]] bool limited() const;
/** /**
* @brief Get the given role value at the given index. * @brief Get the given role value at the given index.
* *
* @sa QAbstractItemModel::data * @sa QAbstractItemModel::data
*/ */
[[nodiscard]] QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; [[nodiscard]] QVariant data(const QModelIndex &index, int role = NameRole) const override;
/** /**
* @brief Number of rows in the model. * @brief Number of rows in the model.
@@ -87,23 +87,23 @@ public:
[[nodiscard]] QHash<int, QByteArray> roleNames() const override; [[nodiscard]] QHash<int, QByteArray> roleNames() const override;
/** /**
* @brief Search the user directory. * @brief Start the user search.
*
* @param limit the maximum number of rooms to load.
*/ */
Q_INVOKABLE void search(int limit = 50); Q_INVOKABLE void search(int count = 50);
Q_SIGNALS: Q_SIGNALS:
void connectionChanged(); void connectionChanged();
void searchTextChanged(); void keywordChanged();
void searchingChanged(); void limitedChanged();
private: private:
Quotient::Connection *m_connection = nullptr; Quotient::Connection *m_connection = nullptr;
QString m_searchText; QString m_keyword;
bool m_limited = false;
bool attempted = false; bool attempted = false;
QList<Quotient::SearchUserDirectoryJob::User> users; QList<Quotient::SearchUserDirectoryJob::User> users;
Quotient::SearchUserDirectoryJob *m_job = nullptr; Quotient::SearchUserDirectoryJob *job = nullptr;
}; };

View File

@@ -188,7 +188,6 @@ Name[ie]=Nov invitation
Name[it]=Nuovo invito Name[it]=Nuovo invito
Name[ka]=ახალი მოსაწვევი Name[ka]=ახალი მოსაწვევი
Name[ko]=새 초대장 Name[ko]=새 초대장
Name[lt]=Naujas pakvietimas
Name[nl]=Nieuwe uitnodiging Name[nl]=Nieuwe uitnodiging
Name[nn]=Ny invitasjon Name[nn]=Ny invitasjon
Name[pa]=ਨਵਾਂ ਸੱਦਾ Name[pa]=ਨਵਾਂ ਸੱਦਾ
@@ -226,7 +225,6 @@ Comment[ie]=Vu have un nov invitation a un chambre
Comment[it]=È presente un nuovo invito a una stanza Comment[it]=È presente un nuovo invito a una stanza
Comment[ka]=გაქვთ ახალი ოთახის მოსაწვევი Comment[ka]=გაქვთ ახალი ოთახის მოსაწვევი
Comment[ko]=새로운 대화방 초대장을 받음 Comment[ko]=새로운 대화방 초대장을 받음
Comment[lt]=Yra naujas pakvietimas į kambarį
Comment[nl]=Er is een nieuwe uitnodiging naar een room Comment[nl]=Er is een nieuwe uitnodiging naar een room
Comment[nn]=Du har ein ny invitasjon til eit rom Comment[nn]=Du har ein ny invitasjon til eit rom
Comment[pa]=ਰੂਮ ਲਈ ਨਵਾਂ ਸੱਦਾ ਹੈ Comment[pa]=ਰੂਮ ਲਈ ਨਵਾਂ ਸੱਦਾ ਹੈ

View File

@@ -22,6 +22,10 @@
<label>Background transparency value</label> <label>Background transparency value</label>
<default>0.3</default> <default>0.3</default>
</entry> </entry>
<entry name="MergeRoomList" type="bool">
<label>Merge Room Lists</label>
<default>false</default>
</entry>
<entry name="AllowQuickEdit" type="bool"> <entry name="AllowQuickEdit" type="bool">
<label>Use s/text/replacement syntax to edit your last message.</label> <label>Use s/text/replacement syntax to edit your last message.</label>
<default>false</default> <default>false</default>
@@ -152,5 +156,11 @@
<default></default> <default></default>
</entry> </entry>
</group> </group>
<group name="FeatureFlags">
<entry name="Threads" type="bool">
<label>Enable threads</label>
<default>false</default>
</entry>
</group>
</kcfg> </kcfg>

View File

@@ -8,12 +8,8 @@
#include "controller.h" #include "controller.h"
#include "jobs/neochatchangepasswordjob.h" #include "jobs/neochatchangepasswordjob.h"
#include "jobs/neochatdeactivateaccountjob.h" #include "jobs/neochatdeactivateaccountjob.h"
#include "neochatroom.h"
#include "roommanager.h" #include "roommanager.h"
#include "spacehierarchycache.h"
#include <Quotient/connection.h>
#include <Quotient/quotient_common.h>
#include <qt6keychain/keychain.h> #include <qt6keychain/keychain.h>
#include <KLocalizedString> #include <KLocalizedString>
@@ -21,9 +17,7 @@
#include <Quotient/csapi/content-repo.h> #include <Quotient/csapi/content-repo.h>
#include <Quotient/csapi/profile.h> #include <Quotient/csapi/profile.h>
#include <Quotient/database.h> #include <Quotient/database.h>
#include <Quotient/jobs/downloadfilejob.h>
#include <Quotient/qt_connection_util.h> #include <Quotient/qt_connection_util.h>
#include <Quotient/room.h>
#include <Quotient/settings.h> #include <Quotient/settings.h>
#include <Quotient/user.h> #include <Quotient/user.h>
@@ -38,17 +32,6 @@ using namespace Qt::StringLiterals;
NeoChatConnection::NeoChatConnection(QObject *parent) NeoChatConnection::NeoChatConnection(QObject *parent)
: Connection(parent) : Connection(parent)
{
connectSignals();
}
NeoChatConnection::NeoChatConnection(const QUrl &server, QObject *parent)
: Connection(server, parent)
{
connectSignals();
}
void NeoChatConnection::connectSignals()
{ {
connect(this, &NeoChatConnection::accountDataChanged, this, [this](const QString &type) { connect(this, &NeoChatConnection::accountDataChanged, this, [this](const QString &type) {
if (type == QLatin1String("org.kde.neochat.account_label")) { if (type == QLatin1String("org.kde.neochat.account_label")) {
@@ -66,54 +49,16 @@ void NeoChatConnection::connectSignals()
Q_EMIT userConsentRequired(job->errorUrl()); Q_EMIT userConsentRequired(job->errorUrl());
} }
}); });
connect(this, &NeoChatConnection::requestFailed, this, [](BaseJob *job) { }
if (dynamic_cast<DownloadFileJob *>(job) && job->jsonData()["errcode"_ls].toString() == "M_TOO_LARGE"_ls) {
RoomManager::instance().warning(i18n("File too large to download."), i18n("Contact your matrix server administrator for support."));
}
});
connect(this, &NeoChatConnection::directChatsListChanged, this, [this](DirectChatsMap additions, DirectChatsMap removals) {
Q_EMIT directChatInvitesChanged();
for (const auto &chatId : additions) {
if (const auto chat = room(chatId)) {
connect(chat, &Room::unreadStatsChanged, this, [this]() {
Q_EMIT directChatNotificationsChanged();
});
}
}
for (const auto &chatId : removals) {
if (const auto chat = room(chatId)) {
disconnect(chat, &Room::unreadStatsChanged, this, nullptr);
}
}
});
connect(this, &NeoChatConnection::joinedRoom, this, [this](Room *room) {
if (room->isDirectChat()) {
connect(room, &Room::unreadStatsChanged, this, [this]() {
Q_EMIT directChatNotificationsChanged();
});
}
});
connect(this, &NeoChatConnection::leftRoom, this, [this](Room *room, Room *prev) {
Q_UNUSED(room)
if (prev && prev->isDirectChat()) {
Q_EMIT directChatInvitesChanged();
}
});
connect(&SpaceHierarchyCache::instance(), &SpaceHierarchyCache::spaceHierarchyChanged, this, [this]() { NeoChatConnection::NeoChatConnection(const QUrl &server, QObject *parent)
Q_EMIT homeNotificationsChanged(); : Connection(server, parent)
{
connect(this, &NeoChatConnection::accountDataChanged, this, [this](const QString &type) {
if (type == QLatin1String("org.kde.neochat.account_label")) {
Q_EMIT labelChanged();
}
}); });
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) void NeoChatConnection::logout(bool serverSideLogout)
@@ -257,7 +202,7 @@ void NeoChatConnection::createRoom(const QString &name, const QString &topic, co
Q_EMIT Controller::instance().errorOccured(i18n("Room creation failed: %1", job->errorString()), {}); Q_EMIT Controller::instance().errorOccured(i18n("Room creation failed: %1", job->errorString()), {});
}); });
connectSingleShot(this, &Connection::newRoom, this, [](Room *room) { connectSingleShot(this, &Connection::newRoom, this, [](Room *room) {
RoomManager::instance().resolveResource(room->id()); RoomManager::instance().enterRoom(dynamic_cast<NeoChatRoom *>(room));
}); });
} }
@@ -289,87 +234,24 @@ void NeoChatConnection::createSpace(const QString &name, const QString &topic, c
Q_EMIT Controller::instance().errorOccured(i18n("Space creation failed: %1", job->errorString()), {}); Q_EMIT Controller::instance().errorOccured(i18n("Space creation failed: %1", job->errorString()), {});
}); });
connectSingleShot(this, &Connection::newRoom, this, [](Room *room) { connectSingleShot(this, &Connection::newRoom, this, [](Room *room) {
RoomManager::instance().resolveResource(room->id()); RoomManager::instance().enterRoom(dynamic_cast<NeoChatRoom *>(room));
}); });
} }
bool NeoChatConnection::directChatExists(Quotient::User *user)
{
return directChats().contains(user);
}
void NeoChatConnection::openOrCreateDirectChat(const QString &userId)
{
if (auto user = this->user(userId)) {
openOrCreateDirectChat(user);
} else {
qWarning() << "openOrCreateDirectChat: Couldn't get user object for ID " << userId << ", unable to open/request direct chat.";
}
}
void NeoChatConnection::openOrCreateDirectChat(User *user) void NeoChatConnection::openOrCreateDirectChat(User *user)
{ {
const auto existing = directChats(); const auto existing = directChats();
if (existing.contains(user)) { 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) { if (room) {
RoomManager::instance().resolveResource(room->id()); RoomManager::instance().enterRoom(room);
return; return;
} }
} }
requestDirectChat(user); requestDirectChat(user);
} }
qsizetype NeoChatConnection::directChatNotifications() const
{
qsizetype notifications = 0;
QStringList added; // The same ID can be in the list multiple times.
for (const auto &chatId : directChats()) {
if (!added.contains(chatId)) {
if (const auto chat = room(chatId)) {
notifications += chat->notificationCount();
added += chatId;
}
}
}
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);
for (const auto inviteRoom : inviteRooms) {
if (inviteRoom->isDirectChat()) {
return true;
}
}
return false;
}
QCoro::Task<void> NeoChatConnection::setupPushNotifications(QString endpoint) QCoro::Task<void> NeoChatConnection::setupPushNotifications(QString endpoint)
{ {
#ifdef HAVE_KUNIFIEDPUSH #ifdef HAVE_KUNIFIEDPUSH

View File

@@ -27,21 +27,6 @@ class NeoChatConnection : public Quotient::Connection
Q_PROPERTY(QString deviceKey READ deviceKey CONSTANT) Q_PROPERTY(QString deviceKey READ deviceKey CONSTANT)
Q_PROPERTY(QString encryptionKey READ encryptionKey CONSTANT) Q_PROPERTY(QString encryptionKey READ encryptionKey CONSTANT)
/**
* @brief The total number of notifications for all direct chats.
*/
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.
*/
Q_PROPERTY(bool directChatInvites READ directChatInvites NOTIFY directChatInvitesChanged)
/** /**
* @brief Whether NeoChat is currently able to connect to the server. * @brief Whether NeoChat is currently able to connect to the server.
*/ */
@@ -95,28 +80,12 @@ public:
Q_INVOKABLE void createSpace(const QString &name, const QString &topic, const QString &parent = {}, bool setChildParent = false); Q_INVOKABLE void createSpace(const QString &name, const QString &topic, const QString &parent = {}, bool setChildParent = false);
/** /**
* @brief Whether a direct chat with the user exists. * @brief Join a direct chat with the given user.
*/
Q_INVOKABLE bool directChatExists(Quotient::User *user);
/**
* @brief Join a direct chat with the given user ID.
*
* If a direct chat with the user doesn't exist one is created and then joined.
*/
Q_INVOKABLE void openOrCreateDirectChat(const QString &userId);
/**
* @brief Join a direct chat with the given user object.
* *
* If a direct chat with the user doesn't exist one is created and then joined. * If a direct chat with the user doesn't exist one is created and then joined.
*/ */
Q_INVOKABLE void openOrCreateDirectChat(Quotient::User *user); Q_INVOKABLE void openOrCreateDirectChat(Quotient::User *user);
qsizetype directChatNotifications() const;
qsizetype homeNotifications() const;
bool directChatInvites() const;
// note: this is intentionally a copied QString because // note: this is intentionally a copied QString because
// the reference could be destroyed before the task is finished // the reference could be destroyed before the task is finished
QCoro::Task<void> setupPushNotifications(QString endpoint); QCoro::Task<void> setupPushNotifications(QString endpoint);
@@ -128,9 +97,6 @@ public:
Q_SIGNALS: Q_SIGNALS:
void labelChanged(); void labelChanged();
void directChatNotificationsChanged();
void homeNotificationsChanged();
void directChatInvitesChanged();
void isOnlineChanged(); void isOnlineChanged();
void passwordStatus(NeoChatConnection::PasswordStatus status); void passwordStatus(NeoChatConnection::PasswordStatus status);
void userConsentRequired(QUrl url); void userConsentRequired(QUrl url);
@@ -138,6 +104,4 @@ Q_SIGNALS:
private: private:
bool m_isOnline = true; bool m_isOnline = true;
void setIsOnline(bool isOnline); void setIsOnline(bool isOnline);
void connectSignals();
}; };

View File

@@ -42,7 +42,6 @@
#include "neochatconfig.h" #include "neochatconfig.h"
#include "notificationsmanager.h" #include "notificationsmanager.h"
#include "roomlastmessageprovider.h" #include "roomlastmessageprovider.h"
#include "spacehierarchycache.h"
#include "texthandler.h" #include "texthandler.h"
#include "urlhelper.h" #include "urlhelper.h"
#include "utils.h" #include "utils.h"
@@ -126,16 +125,6 @@ NeoChatRoom::NeoChatRoom(Connection *connection, QString roomId, JoinState joinS
Q_EMIT urlPreviewEnabledChanged(); 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 bool NeoChatRoom::hasFileUploading() const
@@ -513,7 +502,9 @@ void NeoChatRoom::postHtmlMessage(const QString &text,
} }
if (isThread) { if (isThread) {
EventHandler eventHandler(this, &**replyIt); EventHandler eventHandler;
eventHandler.setRoom(this);
eventHandler.setEvent(&**replyIt);
const bool isFallingBack = !eventHandler.isThreaded(); const bool isFallingBack = !eventHandler.isThreaded();
@@ -560,7 +551,9 @@ void NeoChatRoom::postHtmlMessage(const QString &text,
if (isReply) { if (isReply) {
const auto &replyEvt = **replyIt; const auto &replyEvt = **replyIt;
EventHandler eventHandler(this, &**replyIt); EventHandler eventHandler;
eventHandler.setRoom(this);
eventHandler.setEvent(&**replyIt);
// clang-format off // clang-format off
QJsonObject json{ QJsonObject json{
@@ -1289,14 +1282,6 @@ bool NeoChatRoom::isSpace()
return creationEvent->roomType() == RoomType::Space; 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) void NeoChatRoom::addChild(const QString &childId, bool setChildParent, bool canonical, bool suggested)
{ {
if (!isSpace()) { if (!isSpace()) {
@@ -1841,11 +1826,7 @@ int NeoChatRoom::maxRoomVersion() const
Quotient::User *NeoChatRoom::directChatRemoteUser() const Quotient::User *NeoChatRoom::directChatRemoteUser() const
{ {
auto users = connection()->directChatUsers(this); return connection()->directChatUsers(this)[0];
if (users.isEmpty()) {
return nullptr;
}
return users[0];
} }
void NeoChatRoom::sendLocation(float lat, float lon, const QString &description) void NeoChatRoom::sendLocation(float lat, float lon, const QString &description)

View File

@@ -126,13 +126,6 @@ class NeoChatRoom : public Quotient::Room
*/ */
Q_PROPERTY(bool isSpace READ isSpace CONSTANT) 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. * @brief Whether the local user has an invite to the room.
* *
@@ -533,8 +526,6 @@ public:
[[nodiscard]] bool isSpace(); [[nodiscard]] bool isSpace();
qsizetype childrenNotificationCount();
/** /**
* @brief Add the given room as a child. * @brief Add the given room as a child.
* *
@@ -824,7 +815,6 @@ Q_SIGNALS:
void parentIdsChanged(); void parentIdsChanged();
void canonicalParentChanged(); void canonicalParentChanged();
void lastActiveTimeChanged(); void lastActiveTimeChanged();
void childrenNotificationCountChanged();
void isInviteChanged(); void isInviteChanged();
void readOnlyChanged(); void readOnlyChanged();
void displayNameChanged(); 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())); auto connection = dynamic_cast<NeoChatConnection *>(Controller::instance().accounts().get(room->localUser()->id()));
Controller::instance().setActiveConnection(connection); Controller::instance().setActiveConnection(connection);
RoomManager::instance().setConnection(connection); RoomManager::instance().setConnection(connection);
RoomManager::instance().resolveResource(room->id()); RoomManager::instance().enterRoom(room);
}); });
if (canReply) { if (canReply) {
@@ -251,7 +251,7 @@ void NotificationsManager::postInviteNotification(NeoChatRoom *rawRoom, const QS
} }
WindowController::instance().showAndRaiseWindow(notification->xdgActivationToken()); WindowController::instance().showAndRaiseWindow(notification->xdgActivationToken());
notification->close(); 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")); const auto acceptAction = notification->addAction(i18nc("@action:button The thing being accepted is an invitation to chat", "Accept"));

View File

@@ -63,7 +63,6 @@ Comment[ie]=Trovar chambres in NeoChat
Comment[it]=Trova stanze in NeoChat Comment[it]=Trova stanze in NeoChat
Comment[ka]=იპოვე ოთახები NeoChat-ში Comment[ka]=იპოვე ოთახები NeoChat-ში
Comment[ko]=NeoChat에서 대화방 찾기 Comment[ko]=NeoChat에서 대화방 찾기
Comment[lt]=Rasti kambarius NeoChat
Comment[nl]=Rooms zoeken in NeoChat Comment[nl]=Rooms zoeken in NeoChat
Comment[nn]=Finn rom i NeoChat Comment[nn]=Finn rom i NeoChat
Comment[pl]=Znajdź pokoje w NeoChat Comment[pl]=Znajdź pokoje w NeoChat

View File

@@ -1,35 +0,0 @@
// SPDX-FileCopyrightText: 2024 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#include "proxycontroller.h"
#include <QNetworkProxy>
#include "neochatconfig.h"
void ProxyController::setApplicationProxy()
{
auto cfg = NeoChatConfig::self();
QNetworkProxy proxy;
switch (cfg->proxyType()) {
case 1:
proxy.setType(QNetworkProxy::HttpProxy);
break;
case 2:
proxy.setType(QNetworkProxy::Socks5Proxy);
break;
default:
break;
}
proxy.setHostName(cfg->proxyHost());
proxy.setPort(cfg->proxyPort());
proxy.setUser(cfg->proxyUser());
proxy.setPassword(cfg->proxyPassword());
QNetworkProxy::setApplicationProxy(proxy);
}
ProxyController::ProxyController(QObject *parent)
: QObject(parent)
{
}

View File

@@ -1,36 +0,0 @@
// SPDX-FileCopyrightText: 2024 Tobias Fella <tobias.fella@kde.org>
// SPDX-License-Identifier: LGPL-2.0-or-later
#pragma once
#include <QObject>
#include <QQmlEngine>
class ProxyController : public QObject
{
Q_OBJECT
QML_ELEMENT
QML_SINGLETON
public:
static ProxyController &instance()
{
static ProxyController _instance;
return _instance;
}
static ProxyController *create(QQmlEngine *engine, QJSEngine *)
{
engine->setObjectOwnership(&instance(), QQmlEngine::CppOwnership);
return &instance();
}
/**
* @brief Sets the QNetworkProxy for the application.
*
* @sa QNetworkProxy::setApplicationProxy
*/
Q_INVOKABLE void setApplicationProxy();
private:
explicit ProxyController(QObject *parent = nullptr);
};

View File

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

View File

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

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