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