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