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