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