client: Default to AsNeeded backlog fetching
[quassel.git] / src / qtui / chatview.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2020 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     connect(Client::networkModel(), &NetworkModel::markerLineSet, this, &ChatView::markerLineSet);
88
89     // only connect if client is synched with a core
90     if (Client::isConnected())
91         connect(Client::ignoreListManager(), &ClientIgnoreListManager::ignoreListChanged, this, &ChatView::invalidateFilter);
92 }
93
94 bool ChatView::event(QEvent* event)
95 {
96     if (event->type() == QEvent::KeyPress) {
97         auto* keyEvent = static_cast<QKeyEvent*>(event);
98         switch (keyEvent->key()) {
99         case Qt::Key_Up:
100         case Qt::Key_Down:
101         case Qt::Key_PageUp:
102         case Qt::Key_PageDown:
103             if (requestBacklogForScroll()) {
104                 return true;
105             }
106         default:
107             break;
108         }
109     }
110
111     if (event->type() == QEvent::TouchBegin && ((QTouchEvent*)event)->device()->type() == QTouchDevice::TouchScreen) {
112         // Enable scrolling by draging, disable selecting/clicking content
113         setDragMode(QGraphicsView::ScrollHandDrag);
114         setInteractive(false);
115         // if scrollbar is not visible we need to request backlog below else we need to accept
116         // the event now (return true) so that we will receive TouchUpdate and TouchEnd/TouchCancel
117         if (verticalScrollBar()->isVisible())
118             return true;
119     }
120
121     if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
122         // End scroll and reset settings to default
123         setDragMode(QGraphicsView::NoDrag);
124         setInteractive(true);
125         _firstTouchUpdateHappened = false;
126         return true;
127     }
128
129     if (event->type() == QEvent::TouchUpdate) {
130         if (!_firstTouchUpdateHappened) {
131             // After the first movement of a Touch-Point, calculate the distance in both axis
132             // and if the point moved more horizontally abort scroll.
133             QTouchEvent::TouchPoint p = ((QTouchEvent*)event)->touchPoints().at(0);
134             double dx = qAbs(p.lastPos().x() - p.pos().x());
135             double dy = qAbs(p.lastPos().y() - p.pos().y());
136             if (dx > dy) {
137                 setDragMode(QGraphicsView::NoDrag);
138                 setInteractive(true);
139             }
140             _firstTouchUpdateHappened = true;
141         }
142         // Applying the movement happens automatically by the drag-mode
143     }
144     if (event->type() == QEvent::Wheel
145         || (event->type() == QEvent::TouchBegin && ((QTouchEvent*)event)->device()->type() == QTouchDevice::TouchScreen)
146         || event->type() == QEvent::TouchUpdate) {
147         if (requestBacklogForScroll()) {
148             return true;
149         }
150     }
151
152     if (event->type() == QEvent::Show) {
153         if (_invalidateFilter)
154             invalidateFilter();
155     }
156
157     return QGraphicsView::event(event);
158 }
159
160 void ChatView::resizeEvent(QResizeEvent* event)
161 {
162     // if view is currently scrolled to bottom, we want it that way after resizing
163     bool atBottom = (_lastScrollbarPos == verticalScrollBar()->maximum());
164
165     QGraphicsView::resizeEvent(event);
166
167     // if scrolling to bottom, do it immediately.
168     if (atBottom) {
169         // we can reduce viewport updates if we scroll to the bottom allready at the beginning
170         verticalScrollBar()->setValue(verticalScrollBar()->maximum());
171     }
172
173     scene()->updateForViewport(viewport()->width(), viewport()->height());
174     adjustSceneRect();
175
176     if (atBottom) {
177         _lastScrollbarPos = verticalScrollBar()->maximum();
178         verticalScrollBar()->setValue(verticalScrollBar()->maximum());
179     }
180     checkChatLineCaches();
181 }
182
183 void ChatView::adjustSceneRect()
184 {
185     // Workaround for QTBUG-6322
186     // If the viewport's sceneRect() is (almost) as wide as as the viewport itself,
187     // Qt wants to reserve space for scrollbars even if they're turned off, resulting in
188     // an ugly white space at the bottom of the ChatView.
189     // Since the view's scene's width actually doesn't matter at all, we just adjust it
190     // by some hopefully large enough value to avoid this problem.
191
192     setSceneRect(scene()->sceneRect().adjusted(0, 0, -25, 0));
193 }
194
195 void ChatView::mouseMoveWhileSelecting(const QPointF& scenePos)
196 {
197     int y = (int)mapFromScene(scenePos).y();
198     _scrollOffset = 0;
199     if (y < 0)
200         _scrollOffset = y;
201     else if (y > height())
202         _scrollOffset = y - height();
203
204     if (_scrollOffset && !_scrollTimer.isActive())
205         _scrollTimer.start();
206 }
207
208 void ChatView::scrollTimerTimeout()
209 {
210     // scroll view
211     QAbstractSlider* vbar = verticalScrollBar();
212     if (_scrollOffset < 0 && vbar->value() > 0)
213         vbar->setValue(qMax(vbar->value() + _scrollOffset, 0));
214     else if (_scrollOffset > 0 && vbar->value() < vbar->maximum())
215         vbar->setValue(qMin(vbar->value() + _scrollOffset, vbar->maximum()));
216 }
217
218 void ChatView::lastLineChanged(QGraphicsItem* chatLine, qreal offset)
219 {
220     Q_UNUSED(chatLine)
221     // disabled until further testing/discussion
222     // if(!scene()->isScrollingAllowed())
223     //  return;
224
225     QAbstractSlider* vbar = verticalScrollBar();
226     Q_ASSERT(vbar);
227     if (vbar->maximum() - vbar->value() <= (offset + 5) * _currentScaleFactor) {  // 5px grace area
228         vbar->setValue(vbar->maximum());
229     }
230 }
231
232 void ChatView::verticalScrollbarChanged(int newPos)
233 {
234     QAbstractSlider* vbar = verticalScrollBar();
235     Q_ASSERT(vbar);
236
237     // check for backlog request
238     if (newPos < _lastScrollbarPos) {
239         int relativePos = 100;
240         if (vbar->maximum() - vbar->minimum() != 0)
241             relativePos = (newPos - vbar->minimum()) * 100 / (vbar->maximum() - vbar->minimum());
242
243         if (relativePos < 20) {
244             scene()->requestBacklog();
245         }
246     }
247     _lastScrollbarPos = newPos;
248
249     // FIXME: Fugly workaround for the ChatView scrolling up 1px on buffer switch
250     if (vbar->maximum() - newPos <= 2)
251         vbar->setValue(vbar->maximum());
252 }
253
254 MsgId ChatView::lastMsgId() const
255 {
256     if (!scene())
257         return {};
258
259     QAbstractItemModel* model = scene()->model();
260     if (!model || model->rowCount() == 0)
261         return {};
262
263     return model->index(model->rowCount() - 1, 0).data(MessageModel::MsgIdRole).value<MsgId>();
264 }
265
266 MsgId ChatView::lastVisibleMsgId() const
267 {
268     ChatLine* line = lastVisibleChatLine();
269
270     if (line)
271         return line->msgId();
272
273     return {};
274 }
275
276 bool chatLinePtrLessThan(ChatLine* one, ChatLine* other)
277 {
278     return one->row() < other->row();
279 }
280
281 // TODO: figure out if it's cheaper to use a cached list (that we'd need to keep updated)
282 QSet<ChatLine*> ChatView::visibleChatLines(Qt::ItemSelectionMode mode) const
283 {
284     QSet<ChatLine*> result;
285     foreach (QGraphicsItem* item, items(viewport()->rect().adjusted(-1, -1, 1, 1), mode)) {
286         auto* line = qgraphicsitem_cast<ChatLine*>(item);
287         if (line)
288             result.insert(line);
289     }
290     return result;
291 }
292
293 QList<ChatLine*> ChatView::visibleChatLinesSorted(Qt::ItemSelectionMode mode) const
294 {
295     QList<ChatLine*> result = visibleChatLines(mode).values();
296     std::sort(result.begin(), result.end(), chatLinePtrLessThan);
297     return result;
298 }
299
300 ChatLine* ChatView::lastVisibleChatLine(bool ignoreDayChange) const
301 {
302     if (!scene())
303         return nullptr;
304
305     QAbstractItemModel* model = scene()->model();
306     if (!model || model->rowCount() == 0)
307         return nullptr;
308
309     int row = -1;
310
311     QSet<ChatLine*> visibleLines = visibleChatLines(Qt::ContainsItemBoundingRect);
312     foreach (ChatLine* line, visibleLines) {
313         if (line->row() > row && (ignoreDayChange ? line->msgType() != Message::DayChange : true))
314             row = line->row();
315     }
316
317     if (row >= 0)
318         return scene()->chatLine(row);
319
320     return nullptr;
321 }
322
323 void ChatView::setMarkerLineVisible(bool visible)
324 {
325     scene()->setMarkerLineVisible(visible);
326 }
327
328 void ChatView::setMarkerLine(MsgId msgId)
329 {
330     if (!scene()->isSingleBufferScene())
331         return;
332
333     BufferId bufId = scene()->singleBufferId();
334     Client::setMarkerLine(bufId, msgId);
335 }
336
337 void ChatView::markerLineSet(BufferId buffer, MsgId msgId)
338 {
339     if (!scene()->isSingleBufferScene() || scene()->singleBufferId() != buffer)
340         return;
341
342     scene()->setMarkerLine(msgId);
343     scene()->setMarkerLineVisible(true);
344 }
345
346 void ChatView::jumpToMarkerLine(bool requestBacklog)
347 {
348     scene()->jumpToMarkerLine(requestBacklog);
349 }
350
351 void ChatView::addActionsToMenu(QMenu* menu, const QPointF& pos)
352 {
353     // zoom actions
354     auto* bw = qobject_cast<BufferWidget*>(bufferContainer());
355     if (bw) {
356         bw->addActionsToMenu(menu, pos);
357         menu->addSeparator();
358     }
359 }
360
361 void ChatView::zoomIn()
362 {
363     _currentScaleFactor *= 1.2;
364     scale(1.2, 1.2);
365     scene()->setWidth(viewport()->width() / _currentScaleFactor - 2);
366 }
367
368 void ChatView::zoomOut()
369 {
370     _currentScaleFactor /= 1.2;
371     scale(1 / 1.2, 1 / 1.2);
372     scene()->setWidth(viewport()->width() / _currentScaleFactor - 2);
373 }
374
375 void ChatView::zoomOriginal()
376 {
377     scale(1 / _currentScaleFactor, 1 / _currentScaleFactor);
378     _currentScaleFactor = 1;
379     scene()->setWidth(viewport()->width() - 2);
380 }
381
382 void ChatView::invalidateFilter()
383 {
384     // if this is the currently selected chatview
385     // invalidate immediately
386     if (isVisible()) {
387         _scene->filter()->invalidateFilter();
388         _invalidateFilter = false;
389     }
390     // otherwise invalidate whenever the view is shown
391     else {
392         _invalidateFilter = true;
393     }
394 }
395
396 void ChatView::scrollContentsBy(int dx, int dy)
397 {
398     QGraphicsView::scrollContentsBy(dx, dy);
399     checkChatLineCaches();
400 }
401
402 void ChatView::setHasCache(ChatLine* line, bool hasCache)
403 {
404     if (hasCache)
405         _linesWithCache.insert(line);
406     else
407         _linesWithCache.remove(line);
408 }
409
410 bool ChatView::requestBacklogForScroll()
411 {
412     if (!verticalScrollBar()->isVisible()) {
413         // Not able to scroll, fetch backlog
414         //
415         // Future improvement: continue fetching backlog in chunks until the scrollbar is visible,
416         // or the beginning of the buffer has been reached.
417         scene()->requestBacklog();
418         // Backlog has been requested
419         return true;
420     }
421     else {
422         // Scrollbar already visible, no backlog requested
423         return false;
424     }
425 }
426
427 void ChatView::checkChatLineCaches()
428 {
429     qreal top = mapToScene(viewport()->rect().topLeft()).y() - 10;  // some grace area to avoid premature cleaning
430     qreal bottom = mapToScene(viewport()->rect().bottomRight()).y() + 10;
431     QSet<ChatLine*>::iterator iter = _linesWithCache.begin();
432     while (iter != _linesWithCache.end()) {
433         ChatLine* line = *iter;
434         if (line->pos().y() + line->height() < top || line->pos().y() > bottom) {
435             line->clearCache();
436             iter = _linesWithCache.erase(iter);
437         }
438         else
439             ++iter;
440     }
441 }