File: timelinewidget.cpp

package info (click to toggle)
quaternion 0.0.97.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,800 kB
  • sloc: cpp: 8,380; xml: 172; sh: 5; makefile: 2
file content (356 lines) | stat: -rw-r--r-- 12,668 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
#include "timelinewidget.h"

#include "chatroomwidget.h"
#include "logging_categories.h"
#include "models/messageeventmodel.h"

#include <Quotient/events/reactionevent.h>
#include <Quotient/events/roompowerlevelsevent.h>

#include <Quotient/csapi/message_pagination.h>

#include <Quotient/networkaccessmanager.h>
#include <Quotient/settings.h>
#include <Quotient/user.h>

#include <QtQml/QQmlContext>
#include <QtQml/QQmlEngine>
#include <QtWidgets/QApplication>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QMenu>

#include <QtCore/QStringBuilder>
#include <QtGui/QClipboard>
#include <QtGui/QDesktopServices>

using Quotient::operator""_ls;

QNetworkAccessManager* TimelineWidget::NamFactory::create(QObject* parent)
{
    return new Quotient::NetworkAccessManager(parent);
}

TimelineWidget::TimelineWidget(ChatRoomWidget* chatRoomWidget)
    : QQuickWidget(chatRoomWidget)
    , m_messageModel(new MessageEventModel(this))
    , indexToMaybeRead(-1)
    , readMarkerOnScreen(false)
{
    using namespace Quotient;
    qmlRegisterUncreatableType<QuaternionRoom>(
        "Quotient", 1, 0, "Room",
        "Room objects can only be created by libQuotient");
    qmlRegisterAnonymousType<RoomMember>("Quotient", 1);
    qmlRegisterAnonymousType<GetRoomEventsJob>("Quotient", 1);
    qmlRegisterAnonymousType<MessageEventModel>("Quotient", 1);
    qmlRegisterType<Settings>("Quotient", 1, 0, "Settings");

    setResizeMode(SizeRootObjectToView);

    engine()->setNetworkAccessManagerFactory(&namFactory);

    auto* ctxt = rootContext();
    ctxt->setContextProperty("messageModel"_ls, m_messageModel);
    ctxt->setContextProperty("controller"_ls, this);

    setSource(QUrl("qrc:///qml/Timeline.qml"_ls));

    connect(&activityDetector, &ActivityDetector::triggered, this,
            &TimelineWidget::markShownAsRead);
}

TimelineWidget::~TimelineWidget()
{
    // Clean away the view to prevent further requests to the controller
    setSource({});
}

QString TimelineWidget::selectedText() const { return m_selectedText; }

QuaternionRoom* TimelineWidget::currentRoom() const
{
    return m_messageModel->room();
}

ChatRoomWidget* TimelineWidget::roomWidget() const
{
    return static_cast<ChatRoomWidget*>(parent());
}

void TimelineWidget::setRoom(QuaternionRoom* newRoom)
{
    if (currentRoom() == newRoom)
        return;

    if (currentRoom()) {
        currentRoom()->setDisplayed(false);
        currentRoom()->disconnect(this);
    }
    readMarkerOnScreen = false;
    maybeReadTimer.stop();
    indicesOnScreen.clear();
    indexToMaybeRead = -1;

    m_messageModel->changeRoom(newRoom);
    if (newRoom) {
        connect(newRoom, &Quotient::Room::fullyReadMarkerMoved, this, [this] {
            const auto rm = currentRoom()->fullyReadMarker();
            readMarkerOnScreen = rm != currentRoom()->historyEdge()
                                 && std::ranges::lower_bound(indicesOnScreen, rm->index())
                                        != indicesOnScreen.cend();
            reStartShownTimer();
            activityDetector.setEnabled(pendingMarkRead());
        });
        newRoom->setDisplayed(true);
    }
}

void TimelineWidget::focusInput() { roomWidget()->focusInput(); }

void TimelineWidget::spotlightEvent(const QString& eventId)
{
    auto index = m_messageModel->findRow(eventId);
    if (index >= 0) {
        emit viewPositionRequested(index);
        emit animateMessage(index);
    } else
        roomWidget()->setHudHtml("<font color=red>" % tr("Referenced message not found")
                                 % "</font>");
}

void TimelineWidget::saveFileAs(const QString& eventId)
{
    if (!currentRoom()) {
        qCWarning(TIMELINE)
            << "ChatRoomWidget::saveFileAs without an active room ignored";
        return;
    }
    const auto fileName = QFileDialog::getSaveFileName(
        this, tr("Save file as"), currentRoom()->fileNameToDownload(eventId));
    if (!fileName.isEmpty())
        currentRoom()->downloadFile(eventId, QUrl::fromLocalFile(fileName));
}

void TimelineWidget::onMessageShownChanged(int visualIndex, bool shown,
                                           bool hasReadMarker)
{
    const auto* room = currentRoom();
    if (!room || !room->displayed())
        return;

    // A message can be auto-marked as (fully) read if:
    // 0. The (fully) read marker is on the screen
    // 1. The message is shown on the screen now
    // 2. It's been the bottommost message on the screen for the last 1 second
    //    (or whatever UI/maybe_read_timer tells in milliseconds) and the user
    //    is active during that time
    // 3. It's below the read marker after that time

    Q_ASSERT(visualIndex <= room->timelineSize());
    const auto eventIt = room->syncEdge() - visualIndex - 1;
    const auto timelineIndex = eventIt->index();

    if (hasReadMarker) {
        readMarkerOnScreen = shown;
        if (shown) {
            indexToMaybeRead = timelineIndex;
            reStartShownTimer();
        } else
            maybeReadTimer.stop();
    }

    const auto pos = std::ranges::lower_bound(indicesOnScreen, timelineIndex);
    if (shown) {
        if (pos == indicesOnScreen.end() || *pos != timelineIndex) {
            indicesOnScreen.insert(pos, timelineIndex);
            if (timelineIndex == indicesOnScreen.back())
                reStartShownTimer();
        }
    } else {
        if (pos != indicesOnScreen.end() && *pos == timelineIndex)
            if (indicesOnScreen.erase(pos) == indicesOnScreen.end())
                reStartShownTimer();
    }
}

void TimelineWidget::showMenu(int index, const QString& hoveredLink,
                              const QString& selectedText, bool showingDetails)
{
    const auto modelIndex = m_messageModel->index(index, 0);
    const auto eventId =
        modelIndex.data(MessageEventModel::EventIdRole).toString();

    auto menu = new QMenu(this);
    menu->setAttribute(Qt::WA_DeleteOnClose);

    if (currentRoom()->canRedact(eventId))
        menu->addAction(QIcon::fromTheme("edit-delete"), tr("Redact"), this,
                        [this, eventId] { currentRoom()->redactEvent(eventId); });

    if (!selectedText.isEmpty())
        menu->addAction(tr("Copy selected text to clipboard"), this,
                        [selectedText] {
                            QApplication::clipboard()->setText(selectedText);
                        });

    if (!hoveredLink.isEmpty())
        menu->addAction(tr("Copy link to clipboard"), this, [hoveredLink] {
            QApplication::clipboard()->setText(hoveredLink);
        });

    menu->addAction(QIcon::fromTheme("link"), tr("Copy permalink to clipboard"),
                    [this, eventId] {
                        QApplication::clipboard()->setText(
                            "https://matrix.to/#/" + currentRoom()->id() + "/"
                            + QUrl::toPercentEncoding(eventId));
                    });
    menu->addAction(QIcon::fromTheme("format-text-blockquote"),
                    tr("Quote", "a verb (do quote), not a noun (a quote)"),
                    [this, modelIndex] { roomWidget()->quote(modelIndex.data().toString()); });

    auto a = menu->addAction(QIcon::fromTheme("view-list-details"),
                             tr("Show details"),
                             [this, index] { emit showDetails(index); });
    a->setCheckable(true);
    a->setChecked(showingDetails);

    const auto eventType =
        modelIndex.data(MessageEventModel::EventTypeRole).toString();
    if (eventType == "image" || eventType == "file") {
        const auto progressInfo =
            modelIndex.data(MessageEventModel::LongOperationRole).value<Quotient::FileTransferInfo>();
        const bool downloaded = !progressInfo.isUpload
                                && progressInfo.completed();

        menu->addSeparator();
        menu->addAction(QIcon::fromTheme("document-open"), tr("Open externally"),
                        [this, index] { emit openExternally(index); });
        if (downloaded) {
            menu->addAction(QIcon::fromTheme("folder-open"), tr("Open Folder"),
                            [localDir = progressInfo.localDir] {
                                QDesktopServices::openUrl(localDir);
                            });
            if (eventType == "image") {
                menu->addAction(tr("Copy image to clipboard"), this,
                                [imgPath = progressInfo.localPath.path()] {
                                    QApplication::clipboard()->setImage(
                                        QImage(imgPath));
                                });
            }
        } else {
            menu->addAction(QIcon::fromTheme("edit-download"), tr("Download"),
                            [this, eventId] {
                                currentRoom()->downloadFile(eventId);
                            });
        }
        menu->addAction(QIcon::fromTheme("document-save-as"),
                        tr("Save file as..."),
                        [this, eventId] { saveFileAs(eventId); });
    }
    menu->popup(QCursor::pos());
}

void TimelineWidget::reactionButtonClicked(const QString& eventId,
                                           const QString& key)
{
    using namespace Quotient;
    const auto& annotations =
        currentRoom()->relatedEvents(eventId, EventRelation::AnnotationType);

    for (const auto& a: annotations)
        if (auto* e = eventCast<const ReactionEvent>(a);
            e != nullptr && e->key() == key
            && a->senderId() == currentRoom()->localMember().id()) //
        {
            currentRoom()->redactEvent(a->id());
            return;
        }

    currentRoom()->postReaction(eventId, key);
}

void TimelineWidget::setGlobalSelectionBuffer(const QString& text)
{
    if (QApplication::clipboard()->supportsSelection())
        QApplication::clipboard()->setText(text, QClipboard::Selection);

    m_selectedText = text;
}

void TimelineWidget::ensureLastReadEvent()
{
    auto r = currentRoom();
    if (!r)
        return;
    if (!historyRequest.isCanceled()) { // Second click cancels the request
        historyRequest.cancel();
        return;
    }
    // Store the future as is, without continuations, so that it could be cancelled
    historyRequest = r->ensureHistory(r->lastFullyReadEventId());
    historyRequest
        .then([this](auto) {
            qCDebug(TIMELINE,
                    "Loaded enough history to get the last fully read event, now scrolling");
            emit viewPositionRequested(
                m_messageModel->findRow(currentRoom()->lastFullyReadEventId()));
            emit historyRequestChanged();
        })
        .onCanceled([this] { emit historyRequestChanged(); });
}

bool TimelineWidget::isHistoryRequestRunning() const { return historyRequest.isRunning(); }

void TimelineWidget::reStartShownTimer()
{
    if (!readMarkerOnScreen || indicesOnScreen.empty()
        || indexToMaybeRead >= indicesOnScreen.back())
        return;

    static Quotient::Settings settings;
    maybeReadTimer.start(settings.get<int>("UI/maybe_read_timer", 1000), this);
    qCDebug(TIMELINE) << "Scheduled maybe-read message update:"
                      << indexToMaybeRead << "->" << indicesOnScreen.back();
}

void TimelineWidget::timerEvent(QTimerEvent* qte)
{
    if (qte->timerId() != maybeReadTimer.timerId()) {
        QQuickWidget::timerEvent(qte);
        return;
    }
    maybeReadTimer.stop();
    // Only update the maybe-read message if we're tracking it
    if (readMarkerOnScreen && !indicesOnScreen.empty()
        && indexToMaybeRead < indicesOnScreen.back()) //
    {
        qCDebug(TIMELINE) << "Maybe-read message update:" << indexToMaybeRead
                          << "->" << indicesOnScreen.back();
        indexToMaybeRead = indicesOnScreen.back();
        activityDetector.setEnabled(pendingMarkRead());
    }
}

void TimelineWidget::markShownAsRead()
{
    // FIXME: a case when a single message doesn't fit on the screen.
    if (auto room = currentRoom(); room != nullptr && readMarkerOnScreen) {
        const auto iter = room->findInTimeline(indicesOnScreen.back());
        Q_ASSERT(iter != room->historyEdge());
        room->markMessagesAsRead((*iter)->id());
    }
}

bool TimelineWidget::pendingMarkRead() const
{
    if (!readMarkerOnScreen || !currentRoom())
        return false;

    const auto rm = currentRoom()->fullyReadMarker();
    return rm != currentRoom()->historyEdge() && rm->index() < indexToMaybeRead;
}

Qt::KeyboardModifiers TimelineWidget::getModifierKeys() const
{
    return QGuiApplication::keyboardModifiers();
}