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