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