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