Time and date support in messageeventmodel && local echo support.

square-messages
Black Hat 2018-07-30 00:00:41 +08:00
parent a105f344f4
commit 93a303799a
7 changed files with 279 additions and 216 deletions

View File

@ -1,5 +1,6 @@
import QtQuick 2.9 import QtQuick 2.9
import QtQuick.Controls 2.2 import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3
import QtQuick.Controls.Material 2.2 import QtQuick.Controls.Material 2.2
AvatarContainer { AvatarContainer {
@ -10,24 +11,46 @@ AvatarContainer {
Rectangle { Rectangle {
id: messageRect id: messageRect
width: Math.min(messageText.implicitWidth + 24, messageListView.width - (!sentByMe ? 40 + messageRow.spacing : 0)) width: Math.min(Math.max(messageText.implicitWidth, (timeText.visible ? timeText.implicitWidth : 0)) + 24, messageListView.width - (!sentByMe ? 40 + messageRow.spacing : 0))
height: messageText.implicitHeight + 24 height: messageText.implicitHeight + (timeText.visible ? timeText.implicitHeight : 0) + 24
color: isNotice ? "transparent" : !sentByMe ? Material.accent : background color: isNotice ? "transparent" : !sentByMe ? Material.accent : background
border.color: Material.accent border.color: Material.accent
border.width: isNotice ? 2 : 0 border.width: isNotice ? 2 : 0
Label { ColumnLayout {
id: messageText id: messageColumn
text: display
color: isNotice || sentByMe ? Material.foreground : "white"
anchors.fill: parent anchors.fill: parent
anchors.margins: 12 anchors.margins: 12
wrapMode: Label.Wrap spacing: 0
linkColor: isNotice || sentByMe ? Material.accent : "white"
// textFormat: contentType === "text/html" ? Text.RichText : Text.StyledText Label {
textFormat: Text.StyledText id: messageText
onLinkActivated: Qt.openUrlExternally(link) Layout.maximumWidth: parent.width
text: display
color: isNotice || sentByMe ? Material.foreground : "white"
wrapMode: Label.Wrap
linkColor: isNotice || sentByMe ? Material.accent : "white"
// textFormat: contentType === "text/html" ? Text.RichText : Text.StyledText
textFormat: Text.StyledText
onLinkActivated: Qt.openUrlExternally(link)
}
Label {
id: timeText
visible: Math.abs(time - aboveTime) > 600000 || index == 0
Layout.alignment: Qt.AlignRight
text: Qt.formatDateTime(time, "d MMM hh:mm")
color: isNotice || sentByMe ? "grey" : "white"
font.pointSize: 8
// Component.onCompleted: {
// console.log("Difference: " + Math.abs(time - aboveTime))
// console.log("Index: " + index)
// }
}
} }
} }
} }

View File

@ -16,14 +16,6 @@ Item {
anchors.right: !(eventType === "state" || eventType === "emote") && sentByMe ? parent.right : undefined anchors.right: !(eventType === "state" || eventType === "emote") && sentByMe ? parent.right : undefined
anchors.horizontalCenter: (eventType === "state" || eventType === "emote") ? parent.horizontalCenter : undefined anchors.horizontalCenter: (eventType === "state" || eventType === "emote") ? parent.horizontalCenter : undefined
MouseArea {
anchors.fill: parent
ToolTip.visible: pressed
ToolTip.delay: Qt.styleHints.mousePressAndHoldInterval
ToolTip.text: time
}
Loader { Loader {
id: delegateLoader id: delegateLoader

View File

@ -96,6 +96,21 @@ Item {
delegate: MessageDelegate {} delegate: MessageDelegate {}
section.property: "section"
section.criteria: ViewSection.FullString
section.delegate: Label {
text: section
color: "grey"
padding: 16
verticalAlignment: Text.AlignVCenter
anchors.horizontalCenter: parent.horizontalCenter
background: Rectangle {
anchors.fill: parent
anchors.margins: 4
color: Material.theme == Material.Light ? "#dbdbdb" : "#363636"
}
}
onAtYBeginningChanged: atYBeginning && currentRoom ? currentRoom.getPreviousContent(50) : {} onAtYBeginningChanged: atYBeginning && currentRoom ? currentRoom.getPreviousContent(50) : {}
onAtYEndChanged: atYEnd && currentRoom ? currentRoom.markAllMessagesAsRead() : {} onAtYEndChanged: atYEnd && currentRoom ? currentRoom.markAllMessagesAsRead() : {}
@ -180,6 +195,13 @@ Item {
bottomPadding: 0 bottomPadding: 0
selectByMouse: true selectByMouse: true
Keys.onReturnPressed: {
if (inputField.text) {
inputField.postMessage(inputField.text)
inputField.text = ""
}
}
background: Item { background: Item {
Rectangle { Rectangle {
z: 5 z: 5
@ -191,16 +213,6 @@ Item {
Rectangle { anchors.fill: parent; color: Material.theme == Material.Light ? "#eaeaea" : "#242424" } Rectangle { anchors.fill: parent; color: Material.theme == Material.Light ? "#eaeaea" : "#242424" }
} }
Shortcut {
sequence: "Ctrl+Return"
onActivated: {
if (inputField.text) {
inputField.postMessage(inputField.text)
inputField.text = ""
}
}
}
function postMessage(text) { function postMessage(text) {
if (text.trim().length === 0) { return } if (text.trim().length === 0) { return }
if(!currentRoom) { return } if(!currentRoom) { return }

View File

@ -9,20 +9,20 @@
#include <QMimeDatabase> #include <QMimeDatabase>
Controller::Controller(QObject* parent) : QObject(parent) { Controller::Controller(QObject* parent) : QObject(parent) {
connect(m_connection, &QMatrixClient::Connection::connected, this, connect(m_connection, &Connection::connected, this,
&Controller::connected); &Controller::connected);
connect(m_connection, &QMatrixClient::Connection::resolveError, this, connect(m_connection, &Connection::resolveError, this,
&Controller::reconnect); &Controller::reconnect);
connect(m_connection, &QMatrixClient::Connection::syncError, this, connect(m_connection, &Connection::syncError, this,
&Controller::reconnect); &Controller::reconnect);
connect(m_connection, &QMatrixClient::Connection::syncDone, this, connect(m_connection, &Connection::syncDone, this,
&Controller::resync); &Controller::resync);
connect(m_connection, &QMatrixClient::Connection::connected, this, connect(m_connection, &Connection::connected, this,
&Controller::connectionChanged); &Controller::connectionChanged);
connect(m_connection, &QMatrixClient::Connection::connected, connect(m_connection, &Connection::connected,
[=] { setBusy(true); }); [=] { setBusy(true); });
connect(m_connection, &QMatrixClient::Connection::syncDone, connect(m_connection, &Connection::syncDone,
[=] { setBusy(false); }); [=] { setBusy(false); });
} }
@ -76,7 +76,7 @@ void Controller::reconnect() {
m_connection->connectWithToken(userID, token, ""); m_connection->connectWithToken(userID, token, "");
} }
void Controller::postFile(QMatrixClient::Room* room, const QUrl& localFile, void Controller::postFile(Room* room, const QUrl& localFile,
const QUrl& mxcUrl) { const QUrl& mxcUrl) {
const QString mime = getMIME(localFile); const QString mime = getMIME(localFile);
const QString fileName = localFile.toLocalFile(); const QString fileName = localFile.toLocalFile();

View File

@ -6,14 +6,12 @@
#include "roomlistmodel.h" #include "roomlistmodel.h"
#include "user.h" #include "user.h"
namespace QMatrixClient { using namespace QMatrixClient;
class Connection;
}
class Controller : public QObject { class Controller : public QObject {
Q_OBJECT Q_OBJECT
Q_PROPERTY(QMatrixClient::Connection* connection READ getConnection CONSTANT) Q_PROPERTY(Connection* connection READ getConnection CONSTANT)
Q_PROPERTY( Q_PROPERTY(
bool isLogin READ getIsLogin WRITE setIsLogin NOTIFY isLoginChanged) bool isLogin READ getIsLogin WRITE setIsLogin NOTIFY isLoginChanged)
Q_PROPERTY(QString homeserver READ getHomeserver WRITE setHomeserver NOTIFY Q_PROPERTY(QString homeserver READ getHomeserver WRITE setHomeserver NOTIFY
@ -34,8 +32,8 @@ class Controller : public QObject {
// All the non-Q_INVOKABLE functions. // All the non-Q_INVOKABLE functions.
// All the Q_PROPERTYs. // All the Q_PROPERTYs.
QMatrixClient::Connection* m_connection = new QMatrixClient::Connection(); Connection* m_connection = new Connection();
QMatrixClient::Connection* getConnection() { return m_connection; } Connection* getConnection() { return m_connection; }
bool isLogin = false; bool isLogin = false;
bool getIsLogin() { return isLogin; } bool getIsLogin() { return isLogin; }
@ -97,7 +95,7 @@ class Controller : public QObject {
void errorOccured(); void errorOccured();
public slots: public slots:
void postFile(QMatrixClient::Room* room, const QUrl& localFile, void postFile(Room* room, const QUrl& localFile,
const QUrl& mxcUrl); const QUrl& mxcUrl);
QString getMIME(const QUrl& fileUrl) const; QString getMIME(const QUrl& fileUrl) const;
}; };

View File

@ -36,11 +36,13 @@ void MessageEventModel::setRoom(QMatrixClient::Room* room) {
using namespace QMatrixClient; using namespace QMatrixClient;
connect(m_currentRoom, &Room::aboutToAddNewMessages, this, connect(m_currentRoom, &Room::aboutToAddNewMessages, this,
[=](RoomEventsRange events) { [=](RoomEventsRange events) {
beginInsertRows(QModelIndex(), 0, int(events.size()) - 1); const auto pos = m_currentRoom->pendingEvents().size();
beginInsertRows(QModelIndex(), int(pos),
int(pos + events.size() - 1));
}); });
connect(m_currentRoom, &Room::aboutToAddHistoricalMessages, this, connect(m_currentRoom, &Room::aboutToAddHistoricalMessages, this,
[=](RoomEventsRange events) { [=](RoomEventsRange events) {
if (rowCount() > 0) nextNewerRow = rowCount() - 1; if (rowCount() > 0) nextNewerRow = rowCount() - 1; // See #312
beginInsertRows(QModelIndex(), rowCount(), beginInsertRows(QModelIndex(), rowCount(),
rowCount() + int(events.size()) - 1); rowCount() + int(events.size()) - 1);
}); });
@ -52,6 +54,28 @@ void MessageEventModel::setRoom(QMatrixClient::Room* room) {
} }
endInsertRows(); endInsertRows();
}); });
connect(m_currentRoom, &Room::pendingEventAboutToAdd, this,
[this] { beginInsertRows({}, 0, 0); });
connect(m_currentRoom, &Room::pendingEventAdded, this,
&MessageEventModel::endInsertRows);
connect(m_currentRoom, &Room::pendingEventAboutToMerge, this,
[this](RoomEvent*, int i) {
const auto timelineBaseIdx =
int(m_currentRoom->pendingEvents().size());
if (i + 1 == timelineBaseIdx) return; // No need to move anything
mergingEcho = true;
Q_ASSERT(beginMoveRows({}, i, i, {}, timelineBaseIdx));
});
connect(m_currentRoom, &Room::pendingEventMerged, this, [this] {
if (mergingEcho) {
endMoveRows();
mergingEcho = false;
}
refreshEventRoles(int(m_currentRoom->pendingEvents().size()),
{SpecialMarksRole});
});
connect(m_currentRoom, &Room::pendingEventChanged, this,
[this](int i) { refreshEventRoles(i, {SpecialMarksRole}); });
connect(m_currentRoom, &Room::readMarkerMoved, this, [this] { connect(m_currentRoom, &Room::readMarkerMoved, this, [this] {
refreshEventRoles( refreshEventRoles(
std::exchange(lastReadEventId, m_currentRoom->readMarkerEventId()), std::exchange(lastReadEventId, m_currentRoom->readMarkerEventId()),
@ -74,20 +98,23 @@ void MessageEventModel::setRoom(QMatrixClient::Room* room) {
} else } else
lastReadEventId.clear(); lastReadEventId.clear();
endResetModel(); endResetModel();
emit roomChanged();
} }
void MessageEventModel::refreshEvent(const QString& eventId) { void MessageEventModel::refreshEvent(const QString& eventId) {
refreshEventRoles(eventId, {}); refreshEventRoles(eventId, {});
} }
void MessageEventModel::refreshEventRoles(const int row,
const QVector<int>& roles) {
const auto idx = index(row);
emit dataChanged(idx, idx, roles);
}
void MessageEventModel::refreshEventRoles(const QString& eventId, void MessageEventModel::refreshEventRoles(const QString& eventId,
const QVector<int> roles) { const QVector<int>& roles) {
const auto it = m_currentRoom->findInTimeline(eventId); const auto it = m_currentRoom->findInTimeline(eventId);
if (it != m_currentRoom->timelineEdge()) { if (it != m_currentRoom->timelineEdge())
const auto row = it - m_currentRoom->messageEvents().rbegin(); refreshEventRoles(it - m_currentRoom->messageEvents().rbegin(), roles);
emit dataChanged(index(row), index(row), roles);
}
} }
inline bool hasValidTimestamp(const QMatrixClient::TimelineItem& ti) { inline bool hasValidTimestamp(const QMatrixClient::TimelineItem& ti) {
@ -136,225 +163,232 @@ int MessageEventModel::rowCount(const QModelIndex& parent) const {
} }
QVariant MessageEventModel::data(const QModelIndex& index, int role) const { QVariant MessageEventModel::data(const QModelIndex& index, int role) const {
if (!m_currentRoom || index.row() < 0 || const auto row = index.row();
index.row() >= m_currentRoom->timelineSize())
return QVariant();
const auto timelineIt = m_currentRoom->messageEvents().rbegin() + index.row(); if (!m_currentRoom || row < 0 ||
const auto& ti = *timelineIt; row >= int(m_currentRoom->pendingEvents().size()) +
m_currentRoom->timelineSize())
return {};
const auto timelineBaseIdx = int(m_currentRoom->pendingEvents().size());
const auto timelineIt = m_currentRoom->messageEvents().crbegin() +
std::max(-1, row - timelineBaseIdx);
const auto& evt = row < timelineBaseIdx
? *m_currentRoom->pendingEvents()[size_t(row)]
: *timelineIt->event();
using namespace QMatrixClient; using namespace QMatrixClient;
if (role == Qt::DisplayRole) { if (role == Qt::DisplayRole) {
if (ti->isRedacted()) { if (evt.isRedacted()) {
auto reason = ti->redactedBecause()->reason(); auto reason = evt.redactedBecause()->reason();
if (reason.isEmpty()) if (reason.isEmpty()) return tr("Redacted");
return tr("Redacted");
else return tr("Redacted: %1").arg(evt.redactedBecause()->reason());
return tr("Redacted: %1").arg(ti->redactedBecause()->reason());
} }
if (ti->type() == EventType::RoomMessage) { return visit(
using namespace MessageEventContent; evt,
[this](const RoomMessageEvent& e) {
using namespace MessageEventContent;
auto* e = ti.viewAs<RoomMessageEvent>(); if (e.hasTextContent() && e.mimeType().name() != "text/plain")
if (e->hasTextContent() && e->mimeType().name() != "text/plain") return static_cast<const TextContent*>(e.content())->body;
return static_cast<const TextContent*>(e->content())->body; if (e.hasFileContent()) {
if (e->hasFileContent()) { auto fileCaption = e.content()->fileInfo()->originalName;
auto fileCaption = e->content()->fileInfo()->originalName; if (fileCaption.isEmpty())
if (fileCaption.isEmpty()) fileCaption = m_currentRoom->prettyPrint(e.plainBody());
fileCaption = m_currentRoom->prettyPrint(e->plainBody()); if (fileCaption.isEmpty()) return tr("a file");
if (fileCaption.isEmpty()) return tr("a file");
}
return m_currentRoom->prettyPrint(e->plainBody());
}
if (ti->type() == EventType::RoomMember) {
auto* e = ti.viewAs<RoomMemberEvent>();
// FIXME: Rewind to the name that was at the time of this event
QString subjectName = m_currentRoom->roomMembername(e->userId());
// The below code assumes senderName output in AuthorRole
switch (e->membership()) {
case MembershipType::Invite:
if (e->repeatsState())
return tr("reinvited %1 to the room").arg(subjectName);
// [[fallthrough]]
case MembershipType::Join: {
if (e->repeatsState()) return tr("joined the room (repeated)");
if (!e->prev_content() ||
e->membership() != e->prev_content()->membership) {
return e->membership() == MembershipType::Invite
? tr("invited %1 to the room").arg(subjectName)
: tr("joined the room");
} }
QString text{}; return m_currentRoom->prettyPrint(e.plainBody());
if (e->displayName() != e->prev_content()->displayName) { },
if (e->displayName().isEmpty()) [this](const RoomMemberEvent& e) {
text = tr("cleared the display name"); // FIXME: Rewind to the name that was at the time of this event
else QString subjectName = m_currentRoom->roomMembername(e.userId());
text = tr("changed the display name to %1").arg(e->displayName()); // The below code assumes senderName output in AuthorRole
switch (e.membership()) {
case MembershipType::Invite:
if (e.repeatsState())
return tr("reinvited %1 to the room").arg(subjectName);
FALLTHROUGH;
case MembershipType::Join: {
if (e.repeatsState()) return tr("joined the room (repeated)");
if (!e.prevContent() ||
e.membership() != e.prevContent()->membership) {
return e.membership() == MembershipType::Invite
? tr("invited %1 to the room").arg(subjectName)
: tr("joined the room");
}
QString text{};
if (e.displayName() != e.prevContent()->displayName) {
if (e.displayName().isEmpty())
text = tr("cleared the display name");
else
text =
tr("changed the display name to %1").arg(e.displayName());
}
if (e.avatarUrl() != e.prevContent()->avatarUrl) {
if (!text.isEmpty()) text += " and ";
if (e.avatarUrl().isEmpty())
text += tr("cleared the avatar");
else
text += tr("updated the avatar");
}
return text;
}
case MembershipType::Leave:
if (e.prevContent() &&
e.prevContent()->membership == MembershipType::Ban) {
return (e.senderId() != e.userId())
? tr("unbanned %1").arg(subjectName)
: tr("self-unbanned");
}
return (e.senderId() != e.userId())
? tr("has put %1 out of the room").arg(subjectName)
: tr("left the room");
case MembershipType::Ban:
return (e.senderId() != e.userId())
? tr("banned %1 from the room").arg(subjectName)
: tr("self-banned from the room");
case MembershipType::Knock:
return tr("knocked");
default:;
} }
if (e->avatarUrl() != e->prev_content()->avatarUrl) {
if (!text.isEmpty()) text += " and ";
if (e->avatarUrl().isEmpty())
text += tr("cleared the avatar");
else
text += tr("updated the avatar");
}
return text;
}
case MembershipType::Leave:
if (e->prev_content() &&
e->prev_content()->membership == MembershipType::Ban) {
if (e->senderId() != e->userId())
return tr("unbanned %1").arg(subjectName);
else
return tr("self-unbanned");
}
if (e->senderId() != e->userId())
return tr("has put %1 out of the room").arg(subjectName);
else
return tr("left the room");
case MembershipType::Ban:
if (e->senderId() != e->userId())
return tr("banned %1 from the room").arg(subjectName);
else
return tr("self-banned from the room");
case MembershipType::Knock:
return tr("knocked");
case MembershipType::Undefined:
return tr("made something unknown"); return tr("made something unknown");
} },
} [](const RoomAliasesEvent& e) {
if (ti->type() == EventType::RoomAliases) { return tr("set aliases to: %1").arg(e.aliases().join(", "));
auto* e = ti.viewAs<RoomAliasesEvent>(); },
return tr("set aliases to: %1").arg(e->aliases().join(", ")); [](const RoomCanonicalAliasEvent& e) {
} return (e.alias().isEmpty())
if (ti->type() == EventType::RoomCanonicalAlias) { ? tr("cleared the room main alias")
auto* e = ti.viewAs<RoomCanonicalAliasEvent>(); : tr("set the room main alias to: %1").arg(e.alias());
if (e->alias().isEmpty()) },
return tr("cleared the room main alias"); [](const RoomNameEvent& e) {
else return (e.name().isEmpty())
return tr("set the room main alias to: %1").arg(e->alias()); ? tr("cleared the room name")
} : tr("set the room name to: %1").arg(e.name());
if (ti->type() == EventType::RoomName) { },
auto* e = ti.viewAs<RoomNameEvent>(); [](const RoomTopicEvent& e) {
if (e->name().isEmpty()) return (e.topic().isEmpty())
return tr("cleared the room name"); ? tr("cleared the topic")
else : tr("set the topic to: %1").arg(e.topic());
return tr("set the room name to: %1").arg(e->name()); },
} [](const RoomAvatarEvent&) { return tr("changed the room avatar"); },
if (ti->type() == EventType::RoomTopic) { [](const EncryptionEvent&) {
auto* e = ti.viewAs<RoomTopicEvent>(); return tr("activated End-to-End Encryption");
if (e->topic().isEmpty()) },
return tr("cleared the topic"); tr("Unknown Event"));
else
return tr("set the topic to: %1").arg(e->topic());
}
if (ti->type() == EventType::RoomAvatar) {
return tr("changed the room avatar");
}
if (ti->type() == EventType::RoomEncryption) {
return tr("activated End-to-End Encryption");
}
return tr("Unknown Event");
} }
if (role == Qt::ToolTipRole) { if (role == Qt::ToolTipRole) {
return ti->originalJson(); return evt.originalJson();
} }
if (role == EventTypeRole) { if (role == EventTypeRole) {
if (ti->isStateEvent()) return "state"; if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
switch (e->msgtype()) {
if (ti->type() == EventType::RoomMessage) {
switch (ti.viewAs<RoomMessageEvent>()->msgtype()) {
case MessageEventType::Emote: case MessageEventType::Emote:
return "emote"; return "emote";
case MessageEventType::Notice: case MessageEventType::Notice:
return "notice"; return "notice";
case MessageEventType::Image: case MessageEventType::Image:
return "image"; return "image";
case MessageEventType::Audio:
// return "audio";
case MessageEventType::File: case MessageEventType::File:
case MessageEventType::Audio:
case MessageEventType::Video: case MessageEventType::Video:
return "file"; return "file";
default: default:
return "message"; return "message";
} }
} }
if (is<RedactionEvent>(evt)) return "redaction";
if (evt.isStateEvent()) return "state";
return "other"; return "other";
} }
if (role == TimeRole) return makeMessageTimestamp(timelineIt); if (role == EventResolvedTypeRole)
return EventTypeRegistry::getMatrixType(evt.type());
if (role == SectionRole)
return makeDateString(timelineIt); // FIXME: move date rendering to QML
if (role == AuthorRole) { if (role == AuthorRole) {
auto userId = ti->senderId();
// FIXME: It shouldn't be User, it should be its state "as of event" // FIXME: It shouldn't be User, it should be its state "as of event"
return QVariant::fromValue(m_currentRoom->user(userId)); return QVariant::fromValue(row < timelineBaseIdx
? m_currentRoom->localUser()
: m_currentRoom->user(evt.senderId()));
} }
if (role == ContentTypeRole) { if (role == ContentTypeRole) {
if (ti->type() == EventType::RoomMessage) { if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
const auto& contentType = const auto& contentType = e->mimeType().name();
ti.viewAs<RoomMessageEvent>()->mimeType().name(); return contentType == "text/plain" ? QStringLiteral("text/html")
return contentType == "text/plain" ? "text/html" : contentType; : contentType;
} }
return "text/plain"; return QStringLiteral("text/plain");
} }
if (role == ContentRole) { if (role == ContentRole) {
if (ti->isRedacted()) { if (evt.isRedacted()) {
auto reason = ti->redactedBecause()->reason(); auto reason = evt.redactedBecause()->reason();
if (reason.isEmpty()) return (reason.isEmpty())
return tr("Redacted"); ? tr("Redacted")
else : tr("Redacted: %1").arg(evt.redactedBecause()->reason());
return tr("Redacted: %1").arg(ti->redactedBecause()->reason());
} }
if (ti->type() == EventType::RoomMessage) { if (auto e = eventCast<const RoomMessageEvent>(&evt)) {
using namespace MessageEventContent; // Cannot use e.contentJson() here because some
// EventContent classes inject values into the copy of the
auto* e = ti.viewAs<RoomMessageEvent>(); // content JSON stored in EventContent::Base
switch (e->msgtype()) { return e->hasFileContent()
case MessageEventType::Image: ? QVariant::fromValue(e->content()->originalJson)
case MessageEventType::File: : QVariant();
case MessageEventType::Audio: };
case MessageEventType::Video:
return QVariant::fromValue(e->content()->originalJson);
default:;
}
}
} }
if (role == ReadMarkerRole) return ti->id() == lastReadEventId; // HighlightRole is missing. This will be fixed soon.
if (role == ReadMarkerRole) return evt.id() == lastReadEventId;
if (role == SpecialMarksRole) { if (role == SpecialMarksRole) {
if (ti->isStateEvent() && ti.viewAs<StateEventBase>()->repeatsState()) if (row < timelineBaseIdx)
return "hidden"; return evt.id().isEmpty() ? "unsent" : "unsynced";
return ti->isRedacted() ? "redacted" : "";
if (evt.isStateEvent() &&
static_cast<const StateEventBase&>(evt).repeatsState())
return "noop";
return evt.isRedacted() ? "redacted" : "";
} }
if (role == EventIdRole) return ti->id(); if (role == EventIdRole) return evt.id();
if (role == LongOperationRole) { if (role == LongOperationRole) {
if (ti->type() == EventType::RoomMessage && if (auto e = eventCast<const RoomMessageEvent>(&evt))
ti.viewAs<RoomMessageEvent>()->hasFileContent()) { if (e->hasFileContent())
auto info = m_currentRoom->fileTransferInfo(ti->id()); return QVariant::fromValue(m_currentRoom->fileTransferInfo(e->id()));
return QVariant::fromValue(info);
}
} }
auto aboveEventIt = timelineIt + 1; // FIXME: shouldn't be here, because #312 if (row >= timelineBaseIdx - 1) // The timeline and the topmost unsynced
if (aboveEventIt != m_currentRoom->timelineEdge()) { {
if (role == AboveSectionRole) return makeDateString(aboveEventIt); if (role == TimeRole)
return row < timelineBaseIdx ? QDateTime::currentDateTimeUtc()
: makeMessageTimestamp(timelineIt);
if (role == AboveAuthorRole) if (role == SectionRole)
return QVariant::fromValue( return row < timelineBaseIdx
m_currentRoom->user((*aboveEventIt)->senderId())); ? tr("Today")
: makeDateString(
timelineIt); // FIXME: move date rendering to QML
// FIXME: shouldn't be here, because #312
auto aboveEventIt = timelineIt + 1;
if (aboveEventIt != m_currentRoom->timelineEdge()) {
if (role == AboveSectionRole) return makeDateString(aboveEventIt);
if (role == AboveAuthorRole)
return QVariant::fromValue(
m_currentRoom->user((*aboveEventIt)->senderId()));
if (role == AboveTimeRole) return makeMessageTimestamp(aboveEventIt);
}
} }
return QVariant(); return QVariant();
@ -365,6 +399,7 @@ QHash<int, QByteArray> MessageEventModel::roleNames() const {
roles[EventTypeRole] = "eventType"; roles[EventTypeRole] = "eventType";
roles[EventIdRole] = "eventId"; roles[EventIdRole] = "eventId";
roles[TimeRole] = "time"; roles[TimeRole] = "time";
roles[AboveTimeRole] = "aboveTime";
roles[SectionRole] = "section"; roles[SectionRole] = "section";
roles[AboveSectionRole] = "aboveSection"; roles[AboveSectionRole] = "aboveSection";
roles[AuthorRole] = "author"; roles[AuthorRole] = "author";

View File

@ -14,6 +14,7 @@ class MessageEventModel : public QAbstractListModel {
EventTypeRole = Qt::UserRole + 1, EventTypeRole = Qt::UserRole + 1,
EventIdRole, EventIdRole,
TimeRole, TimeRole,
AboveTimeRole,
SectionRole, SectionRole,
AboveSectionRole, AboveSectionRole,
AuthorRole, AuthorRole,
@ -45,11 +46,13 @@ class MessageEventModel : public QAbstractListModel {
private: private:
QMatrixClient::Room* m_currentRoom = nullptr; QMatrixClient::Room* m_currentRoom = nullptr;
QString lastReadEventId; QString lastReadEventId;
bool mergingEcho = 0;
int nextNewerRow = -1; int nextNewerRow = -1;
QDateTime makeMessageTimestamp(QMatrixClient::Room::rev_iter_t baseIt) const; QDateTime makeMessageTimestamp(QMatrixClient::Room::rev_iter_t baseIt) const;
QString makeDateString(QMatrixClient::Room::rev_iter_t baseIt) const; QString makeDateString(QMatrixClient::Room::rev_iter_t baseIt) const;
void refreshEventRoles(const QString& eventId, const QVector<int> roles); void refreshEventRoles(const int row, const QVector<int>& roles);
void refreshEventRoles(const QString& eventId, const QVector<int>& roles);
signals: signals:
void roomChanged(); void roomChanged();