Fix typos
[quassel.git] / src / qtui / chatview.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2022 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "chatview.h"
22
23 #include <algorithm>
24
25 #include <QGraphicsTextItem>
26 #include <QKeyEvent>
27 #include <QMenu>
28 #include <QScrollBar>
29
30 #include "bufferwidget.h"
31 #include "chatline.h"
32 #include "chatscene.h"
33 #include "client.h"
34 #include "clientignorelistmanager.h"
35 #include "messagefilter.h"
36 #include "qtui.h"
37 #include "qtuistyle.h"
38 #include "util.h"
39
40 ChatView::ChatView(BufferId bufferId, QWidget* parent)
41     : QGraphicsView(parent)
42     , AbstractChatView()
43 {
44     QList<BufferId> filterList;
45     filterList.append(bufferId);
46     auto* filter = new MessageFilter(Client::messageModel(), filterList, this);
47     init(filter);
48 }
49
50 ChatView::ChatView(MessageFilter* filter, QWidget* parent)
51     : QGraphicsView(parent)
52     , AbstractChatView()
53 {
54     init(filter);
55 }
56
57 void ChatView::init(MessageFilter* filter)
58 {
59     _bufferContainer = nullptr;
60     _currentScaleFactor = 1;
61     _invalidateFilter = false;
62
63     setAttribute(Qt::WA_AcceptTouchEvents);
64     setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
65     setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
66     setAlignment(Qt::AlignLeft | Qt::AlignBottom);
67     setInteractive(true);
68     // setOptimizationFlags(QGraphicsView::DontClipPainter | QGraphicsView::DontAdjustForAntialiasing);
69     // setOptimizationFlags(QGraphicsView::DontAdjustForAntialiasing);
70     setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
71     // setTransformationAnchor(QGraphicsView::NoAnchor);
72     setTransformationAnchor(QGraphicsView::AnchorViewCenter);
73
74     _scrollTimer.setInterval(100);
75     _scrollTimer.setSingleShot(true);
76     connect(&_scrollTimer, &QTimer::timeout, this, &ChatView::scrollTimerTimeout);
77
78     _scene = new ChatScene(filter, filter->idString(), viewport()->width(), this);
79     connect(_scene, &QGraphicsScene::sceneRectChanged, this, &ChatView::adjustSceneRect);
80     connect(_scene, &ChatScene::lastLineChanged, this, &ChatView::lastLineChanged);
81     connect(_scene, &ChatScene::mouseMoveWhileSelecting, this, &ChatView::mouseMoveWhileSelecting);
82     setScene(_scene);
83
84     connect(verticalScrollBar(), &QAbstractSlider::valueChanged, this, &ChatView::verticalScrollbarChanged);
85     _lastScrollbarPos = verticalScrollBar()->maximum();
86
87     // Workaround for the ChatView scrolling up a fair bit when scrollbar becomes visible
88     verticalScrollBar()->installEventFilter(this);
89
90     connect(Client::networkModel(), &NetworkModel::markerLineSet, this, &ChatView::markerLineSet);
91
92     // only connect if client is synched with a core
93     if (Client::isConnected())
94         connect(Client::ignoreListManager(), &ClientIgnoreListManager::ignoreListChanged, this, &ChatView::invalidateFilter);
95 }
96
97 bool ChatView::event(QEvent* event)
98 {
99     if (event->type() == QEvent::KeyPress) {
100         auto* keyEvent = static_cast<QKeyEvent*>(event);
101         switch (keyEvent->key()) {
102         case Qt::Key_Up:
103         case Qt::Key_Down:
104         case Qt::Key_PageUp:
105         case Qt::Key_PageDown:
106             if (requestBacklogForScroll()) {
107                 return true;
108             }
109         default:
110             break;
111         }
112     }
113
114     if (event->type() == QEvent::TouchBegin && ((QTouchEvent*)event)->device()->type() == QTouchDevice::TouchScreen) {
115         // Enable scrolling by dragging, disable selecting/clicking content
116         setDragMode(QGraphicsView::ScrollHandDrag);
117         setInteractive(false);
118         // if scrollbar is not visible we need to request backlog below else we need to accept
119         // the event now (return true) so that we will receive TouchUpdate and TouchEnd/TouchCancel
120         if (verticalScrollBar()->isVisible())
121             return true;
122     }
123
124     if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
125         // End scroll and reset settings to default
126         setDragMode(QGraphicsView::NoDrag);
127         setInteractive(true);
128         _firstTouchUpdateHappened = false;
129         return true;
130     }
131
132     if (event->type() == QEvent::TouchUpdate) {
133         if (!_firstTouchUpdateHappened) {
134             // After the first movement of a Touch-Point, calculate the distance in both axis
135             // and if the point moved more horizontally abort scroll.
136             QTouchEvent::TouchPoint p = ((QTouchEvent*)event)->touchPoints().at(0);
137             double dx = qAbs(p.lastPos().x() - p.pos().x());
138             double dy = qAbs(p.lastPos().y() - p.pos().y());
139             if (dx > dy) {
140                 setDragMode(QGraphicsView::NoDrag);
141                 setInteractive(true);
142             }
143             _firstTouchUpdateHappened = true;
144         }
145         // Applying the movement happens automatically by the drag-mode
146     }
147     if (event->type() == QEvent::Wheel
148         || (event->type() == QEvent::TouchBegin && ((QTouchEvent*)event)->device()->type() == QTouchDevice::TouchScreen)
149         || event->type() == QEvent::TouchUpdate) {
150         if (requestBacklogForScroll()) {
151             return true;
152         }
153     }
154
155     if (event->type() == QEvent::Show) {
156         if (_invalidateFilter)
157             invalidateFilter();
158     }
159
160     return QGraphicsView::event(event);
161 }
162
163 bool ChatView::eventFilter(QObject* watched, QEvent* event)
164 {
165     QAbstractSlider* vbar = verticalScrollBar();
166     Q_ASSERT(vbar);
167
168     if (watched != vbar) {
169         // Ignore and pass through all events not featuring the scrollbar
170         return false;
171     }
172     if (event->type() == QEvent::Show) {
173         // FIXME: Workaround for the ChatView scrolling up a fair bit when transitioning from the
174         // vertical scrollbar not being visible, to becoming visible.  This happens especially
175         // often when no initial backlog is loaded.
176         if (_backlogRequestedBeforeScrollable) {
177             _backlogRequestedBeforeScrollable = false;
178             vbar->setValue(vbar->maximum());
179         }
180     }
181     // Pass through all events
182     return false;
183 }
184
185 void ChatView::resizeEvent(QResizeEvent* event)
186 {
187     // if view is currently scrolled to bottom, we want it that way after resizing
188     bool atBottom = (_lastScrollbarPos == verticalScrollBar()->maximum());
189
190     QGraphicsView::resizeEvent(event);
191
192     // if scrolling to bottom, do it immediately.
193     if (atBottom) {
194         // we can reduce viewport updates if we scroll to the bottom already at the beginning
195         verticalScrollBar()->setValue(verticalScrollBar()->maximum());
196     }
197
198     scene()->updateForViewport(viewport()->width(), viewport()->height());
199     adjustSceneRect();
200
201     if (atBottom) {
202         _lastScrollbarPos = verticalScrollBar()->maximum();
203         verticalScrollBar()->setValue(verticalScrollBar()->maximum());
204     }
205     checkChatLineCaches();
206 }
207
208 void ChatView::adjustSceneRect()
209 {
210     // Workaround for QTBUG-6322
211     // If the viewport's sceneRect() is (almost) as wide as as the viewport itself,
212     // Qt wants to reserve space for scrollbars even if they're turned off, resulting in
213     // an ugly white space at the bottom of the ChatView.
214     // Since the view's scene's width actually doesn't matter at all, we just adjust it
215     // by some hopefully large enough value to avoid this problem.
216
217     setSceneRect(scene()->sceneRect().adjusted(0, 0, -25, 0));
218 }
219
220 void ChatView::mouseMoveWhileSelecting(const QPointF& scenePos)
221 {
222     int y = (int)mapFromScene(scenePos).y();
223     _scrollOffset = 0;
224     if (y < 0)
225         _scrollOffset = y;
226     else if (y > height())
227         _scrollOffset = y - height();
228
229     if (_scrollOffset && !_scrollTimer.isActive())
230         _scrollTimer.start();
231 }
232
233 void ChatView::scrollTimerTimeout()
234 {
235     // scroll view
236     QAbstractSlider* vbar = verticalScrollBar();
237     if (_scrollOffset < 0 && vbar->value() > 0)
238         vbar->setValue(qMax(vbar->value() + _scrollOffset, 0));
239     else if (_scrollOffset > 0 && vbar->value() < vbar->maximum())
240         vbar->setValue(qMin(vbar->value() + _scrollOffset, vbar->maximum()));
241 }
242
243 void ChatView::lastLineChanged(QGraphicsItem* chatLine, qreal offset)
244 {
245     Q_UNUSED(chatLine)
246     // disabled until further testing/discussion
247     // if(!scene()->isScrollingAllowed())
248     //  return;
249
250     QAbstractSlider* vbar = verticalScrollBar();
251     Q_ASSERT(vbar);
252     if (vbar->maximum() - vbar->value() <= (offset + 5) * _currentScaleFactor) {  // 5px grace area
253         vbar->setValue(vbar->maximum());
254     }
255 }
256
257 void ChatView::verticalScrollbarChanged(int newPos)
258 {
259     QAbstractSlider* vbar = verticalScrollBar();
260     Q_ASSERT(vbar);
261
262     // check for backlog request
263     if (newPos < _lastScrollbarPos) {
264         int relativePos = 100;
265         if (vbar->maximum() - vbar->minimum() != 0)
266             relativePos = (newPos - vbar->minimum()) * 100 / (vbar->maximum() - vbar->minimum());
267
268         if (relativePos < 20) {
269             scene()->requestBacklog();
270         }
271     }
272     _lastScrollbarPos = newPos;
273
274     // FIXME: Fugly workaround for the ChatView scrolling up 1px on buffer switch
275     if (vbar->maximum() - newPos <= 2)
276         vbar->setValue(vbar->maximum());
277 }
278
279 MsgId ChatView::lastMsgId() const
280 {
281     if (!scene())
282         return {};
283
284     QAbstractItemModel* model = scene()->model();
285     if (!model || model->rowCount() == 0)
286         return {};
287
288     return model->index(model->rowCount() - 1, 0).data(MessageModel::MsgIdRole).value<MsgId>();
289 }
290
291 MsgId ChatView::lastVisibleMsgId() const
292 {
293     ChatLine* line = lastVisibleChatLine();
294
295     if (line)
296         return line->msgId();
297
298     return {};
299 }
300
301 bool chatLinePtrLessThan(ChatLine* one, ChatLine* other)
302 {
303     return one->row() < other->row();
304 }
305
306 // TODO: figure out if it's cheaper to use a cached list (that we'd need to keep updated)
307 QSet<ChatLine*> ChatView::visibleChatLines(Qt::ItemSelectionMode mode) const
308 {
309     QSet<ChatLine*> result;
310     foreach (QGraphicsItem* item, items(viewport()->rect().adjusted(-1, -1, 1, 1), mode)) {
311         auto* line = qgraphicsitem_cast<ChatLine*>(item);
312         if (line)
313             result.insert(line);
314     }
315     return result;
316 }
317
318 QList<ChatLine*> ChatView::visibleChatLinesSorted(Qt::ItemSelectionMode mode) const
319 {
320     QList<ChatLine*> result = visibleChatLines(mode).values();
321     std::sort(result.begin(), result.end(), chatLinePtrLessThan);
322     return result;
323 }
324
325 ChatLine* ChatView::lastVisibleChatLine(bool ignoreDayChange) const
326 {
327     if (!scene())
328         return nullptr;
329
330     QAbstractItemModel* model = scene()->model();
331     if (!model || model->rowCount() == 0)
332         return nullptr;
333
334     int row = -1;
335
336     QSet<ChatLine*> visibleLines = visibleChatLines(Qt::ContainsItemBoundingRect);
337     foreach (ChatLine* line, visibleLines) {
338         if (line->row() > row && (ignoreDayChange ? line->msgType() != Message::DayChange : true))
339             row = line->row();
340     }
341
342     if (row >= 0)
343         return scene()->chatLine(row);
344
345     return nullptr;
346 }
347
348 void ChatView::setMarkerLineVisible(bool visible)
349 {
350     scene()->setMarkerLineVisible(visible);
351 }
352
353 void ChatView::setMarkerLine(MsgId msgId)
354 {
355     if (!scene()->isSingleBufferScene())
356         return;
357
358     BufferId bufId = scene()->singleBufferId();
359     Client::setMarkerLine(bufId, msgId);
360 }
361
362 void ChatView::markerLineSet(BufferId buffer, MsgId msgId)
363 {
364     if (!scene()->isSingleBufferScene() || scene()->singleBufferId() != buffer)
365         return;
366
367     scene()->setMarkerLine(msgId);
368     scene()->setMarkerLineVisible(true);
369 }
370
371 void ChatView::jumpToMarkerLine(bool requestBacklog)
372 {
373     scene()->jumpToMarkerLine(requestBacklog);
374 }
375
376 void ChatView::addActionsToMenu(QMenu* menu, const QPointF& pos)
377 {
378     // zoom actions
379     auto* bw = qobject_cast<BufferWidget*>(bufferContainer());
380     if (bw) {
381         bw->addActionsToMenu(menu, pos);
382         menu->addSeparator();
383     }
384 }
385
386 void ChatView::zoomIn()
387 {
388     _currentScaleFactor *= 1.2;
389     scale(1.2, 1.2);
390     scene()->setWidth(viewport()->width() / _currentScaleFactor - 2);
391 }
392
393 void ChatView::zoomOut()
394 {
395     _currentScaleFactor /= 1.2;
396     scale(1 / 1.2, 1 / 1.2);
397     scene()->setWidth(viewport()->width() / _currentScaleFactor - 2);
398 }
399
400 void ChatView::zoomOriginal()
401 {
402     scale(1 / _currentScaleFactor, 1 / _currentScaleFactor);
403     _currentScaleFactor = 1;
404     scene()->setWidth(viewport()->width() - 2);
405 }
406
407 void ChatView::invalidateFilter()
408 {
409     // if this is the currently selected chatview
410     // invalidate immediately
411     if (isVisible()) {
412         _scene->filter()->invalidateFilter();
413         _invalidateFilter = false;
414     }
415     // otherwise invalidate whenever the view is shown
416     else {
417         _invalidateFilter = true;
418     }
419 }
420
421 void ChatView::scrollContentsBy(int dx, int dy)
422 {
423     QGraphicsView::scrollContentsBy(dx, dy);
424     checkChatLineCaches();
425 }
426
427 void ChatView::setHasCache(ChatLine* line, bool hasCache)
428 {
429     if (hasCache)
430         _linesWithCache.insert(line);
431     else
432         _linesWithCache.remove(line);
433 }
434
435 bool ChatView::requestBacklogForScroll()
436 {
437     if (!verticalScrollBar()->isVisible()) {
438         // Not able to scroll, fetch backlog
439         //
440         // Future improvement: continue fetching backlog in chunks until the scrollbar is visible,
441         // or the beginning of the buffer has been reached.
442         scene()->requestBacklog();
443         _backlogRequestedBeforeScrollable = true;
444         // Backlog has been requested
445         return true;
446     }
447     else {
448         // Scrollbar already visible, no backlog requested
449         return false;
450     }
451 }
452
453 void ChatView::checkChatLineCaches()
454 {
455     qreal top = mapToScene(viewport()->rect().topLeft()).y() - 10;  // some grace area to avoid premature cleaning
456     qreal bottom = mapToScene(viewport()->rect().bottomRight()).y() + 10;
457     QSet<ChatLine*>::iterator iter = _linesWithCache.begin();
458     while (iter != _linesWithCache.end()) {
459         ChatLine* line = *iter;
460         if (line->pos().y() + line->height() < top || line->pos().y() > bottom) {
461             line->clearCache();
462             iter = _linesWithCache.erase(iter);
463         }
464         else
465             ++iter;
466     }
467 }