1 /***************************************************************************
2 * Copyright (C) 2005-2018 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
23 #include <QGraphicsTextItem>
28 #include "bufferwidget.h"
30 #include "chatscene.h"
32 #include "clientignorelistmanager.h"
33 #include "messagefilter.h"
35 #include "qtuistyle.h"
37 ChatView::ChatView(BufferId bufferId, QWidget* parent)
38 : QGraphicsView(parent)
41 QList<BufferId> filterList;
42 filterList.append(bufferId);
43 auto* filter = new MessageFilter(Client::messageModel(), filterList, this);
47 ChatView::ChatView(MessageFilter* filter, QWidget* parent)
48 : QGraphicsView(parent)
54 void ChatView::init(MessageFilter* filter)
56 _bufferContainer = nullptr;
57 _currentScaleFactor = 1;
58 _invalidateFilter = false;
60 setAttribute(Qt::WA_AcceptTouchEvents);
61 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
62 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
63 setAlignment(Qt::AlignLeft | Qt::AlignBottom);
65 // setOptimizationFlags(QGraphicsView::DontClipPainter | QGraphicsView::DontAdjustForAntialiasing);
66 // setOptimizationFlags(QGraphicsView::DontAdjustForAntialiasing);
67 setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
68 // setTransformationAnchor(QGraphicsView::NoAnchor);
69 setTransformationAnchor(QGraphicsView::AnchorViewCenter);
71 _scrollTimer.setInterval(100);
72 _scrollTimer.setSingleShot(true);
73 connect(&_scrollTimer, &QTimer::timeout, this, &ChatView::scrollTimerTimeout);
75 _scene = new ChatScene(filter, filter->idString(), viewport()->width(), this);
76 connect(_scene, &QGraphicsScene::sceneRectChanged, this, &ChatView::adjustSceneRect);
77 connect(_scene, &ChatScene::lastLineChanged, this, &ChatView::lastLineChanged);
78 connect(_scene, &ChatScene::mouseMoveWhileSelecting, this, &ChatView::mouseMoveWhileSelecting);
81 connect(verticalScrollBar(), &QAbstractSlider::valueChanged, this, &ChatView::verticalScrollbarChanged);
82 _lastScrollbarPos = verticalScrollBar()->maximum();
84 connect(Client::networkModel(), &NetworkModel::markerLineSet, this, &ChatView::markerLineSet);
86 // only connect if client is synched with a core
87 if (Client::isConnected())
88 connect(Client::ignoreListManager(), &ClientIgnoreListManager::ignoreListChanged, this, &ChatView::invalidateFilter);
91 bool ChatView::event(QEvent* event)
93 if (event->type() == QEvent::KeyPress) {
94 auto* keyEvent = static_cast<QKeyEvent*>(event);
95 switch (keyEvent->key()) {
99 case Qt::Key_PageDown:
100 if (!verticalScrollBar()->isVisible()) {
101 scene()->requestBacklog();
109 if (event->type() == QEvent::TouchBegin && ((QTouchEvent*)event)->device()->type() == QTouchDevice::TouchScreen) {
110 // Enable scrolling by draging, disable selecting/clicking content
111 setDragMode(QGraphicsView::ScrollHandDrag);
112 setInteractive(false);
113 // if scrollbar is not visible we need to request backlog below else we need to accept
114 // the event now (return true) so that we will receive TouchUpdate and TouchEnd/TouchCancel
115 if (verticalScrollBar()->isVisible())
119 if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
120 // End scroll and reset settings to default
121 setDragMode(QGraphicsView::NoDrag);
122 setInteractive(true);
123 _firstTouchUpdateHappened = false;
127 if (event->type() == QEvent::TouchUpdate) {
128 if (!_firstTouchUpdateHappened) {
129 // After the first movement of a Touch-Point, calculate the distance in both axis
130 // and if the point moved more horizontally abort scroll.
131 QTouchEvent::TouchPoint p = ((QTouchEvent*)event)->touchPoints().at(0);
132 double dx = qAbs(p.lastPos().x() - p.pos().x());
133 double dy = qAbs(p.lastPos().y() - p.pos().y());
135 setDragMode(QGraphicsView::NoDrag);
136 setInteractive(true);
138 _firstTouchUpdateHappened = true;
140 // Applying the movement happens automatically by the drag-mode
142 if (event->type() == QEvent::Wheel
143 || (event->type() == QEvent::TouchBegin && ((QTouchEvent*)event)->device()->type() == QTouchDevice::TouchScreen)
144 || event->type() == QEvent::TouchUpdate) {
145 if (!verticalScrollBar()->isVisible()) {
146 scene()->requestBacklog();
151 if (event->type() == QEvent::Show) {
152 if (_invalidateFilter)
156 return QGraphicsView::event(event);
159 void ChatView::resizeEvent(QResizeEvent* event)
161 // if view is currently scrolled to bottom, we want it that way after resizing
162 bool atBottom = (_lastScrollbarPos == verticalScrollBar()->maximum());
164 QGraphicsView::resizeEvent(event);
166 // if scrolling to bottom, do it immediately.
168 // we can reduce viewport updates if we scroll to the bottom allready at the beginning
169 verticalScrollBar()->setValue(verticalScrollBar()->maximum());
172 scene()->updateForViewport(viewport()->width(), viewport()->height());
176 _lastScrollbarPos = verticalScrollBar()->maximum();
177 verticalScrollBar()->setValue(verticalScrollBar()->maximum());
179 checkChatLineCaches();
182 void ChatView::adjustSceneRect()
184 // Workaround for QTBUG-6322
185 // If the viewport's sceneRect() is (almost) as wide as as the viewport itself,
186 // Qt wants to reserve space for scrollbars even if they're turned off, resulting in
187 // an ugly white space at the bottom of the ChatView.
188 // Since the view's scene's width actually doesn't matter at all, we just adjust it
189 // by some hopefully large enough value to avoid this problem.
191 setSceneRect(scene()->sceneRect().adjusted(0, 0, -25, 0));
194 void ChatView::mouseMoveWhileSelecting(const QPointF& scenePos)
196 int y = (int)mapFromScene(scenePos).y();
200 else if (y > height())
201 _scrollOffset = y - height();
203 if (_scrollOffset && !_scrollTimer.isActive())
204 _scrollTimer.start();
207 void ChatView::scrollTimerTimeout()
210 QAbstractSlider* vbar = verticalScrollBar();
211 if (_scrollOffset < 0 && vbar->value() > 0)
212 vbar->setValue(qMax(vbar->value() + _scrollOffset, 0));
213 else if (_scrollOffset > 0 && vbar->value() < vbar->maximum())
214 vbar->setValue(qMin(vbar->value() + _scrollOffset, vbar->maximum()));
217 void ChatView::lastLineChanged(QGraphicsItem* chatLine, qreal offset)
220 // disabled until further testing/discussion
221 // if(!scene()->isScrollingAllowed())
224 QAbstractSlider* vbar = verticalScrollBar();
226 if (vbar->maximum() - vbar->value() <= (offset + 5) * _currentScaleFactor) { // 5px grace area
227 vbar->setValue(vbar->maximum());
231 void ChatView::verticalScrollbarChanged(int newPos)
233 QAbstractSlider* vbar = verticalScrollBar();
236 // check for backlog request
237 if (newPos < _lastScrollbarPos) {
238 int relativePos = 100;
239 if (vbar->maximum() - vbar->minimum() != 0)
240 relativePos = (newPos - vbar->minimum()) * 100 / (vbar->maximum() - vbar->minimum());
242 if (relativePos < 20) {
243 scene()->requestBacklog();
246 _lastScrollbarPos = newPos;
248 // FIXME: Fugly workaround for the ChatView scrolling up 1px on buffer switch
249 if (vbar->maximum() - newPos <= 2)
250 vbar->setValue(vbar->maximum());
253 MsgId ChatView::lastMsgId() const
258 QAbstractItemModel* model = scene()->model();
259 if (!model || model->rowCount() == 0)
262 return model->index(model->rowCount() - 1, 0).data(MessageModel::MsgIdRole).value<MsgId>();
265 MsgId ChatView::lastVisibleMsgId() const
267 ChatLine* line = lastVisibleChatLine();
270 return line->msgId();
275 bool chatLinePtrLessThan(ChatLine* one, ChatLine* other)
277 return one->row() < other->row();
280 // TODO: figure out if it's cheaper to use a cached list (that we'd need to keep updated)
281 QSet<ChatLine*> ChatView::visibleChatLines(Qt::ItemSelectionMode mode) const
283 QSet<ChatLine*> result;
284 foreach (QGraphicsItem* item, items(viewport()->rect().adjusted(-1, -1, 1, 1), mode)) {
285 auto* line = qgraphicsitem_cast<ChatLine*>(item);
292 QList<ChatLine*> ChatView::visibleChatLinesSorted(Qt::ItemSelectionMode mode) const
294 QList<ChatLine*> result = visibleChatLines(mode).toList();
295 qSort(result.begin(), result.end(), chatLinePtrLessThan);
299 ChatLine* ChatView::lastVisibleChatLine(bool ignoreDayChange) const
304 QAbstractItemModel* model = scene()->model();
305 if (!model || model->rowCount() == 0)
310 QSet<ChatLine*> visibleLines = visibleChatLines(Qt::ContainsItemBoundingRect);
311 foreach (ChatLine* line, visibleLines) {
312 if (line->row() > row && (ignoreDayChange ? line->msgType() != Message::DayChange : true))
317 return scene()->chatLine(row);
322 void ChatView::setMarkerLineVisible(bool visible)
324 scene()->setMarkerLineVisible(visible);
327 void ChatView::setMarkerLine(MsgId msgId)
329 if (!scene()->isSingleBufferScene())
332 BufferId bufId = scene()->singleBufferId();
333 Client::setMarkerLine(bufId, msgId);
336 void ChatView::markerLineSet(BufferId buffer, MsgId msgId)
338 if (!scene()->isSingleBufferScene() || scene()->singleBufferId() != buffer)
341 scene()->setMarkerLine(msgId);
342 scene()->setMarkerLineVisible(true);
345 void ChatView::jumpToMarkerLine(bool requestBacklog)
347 scene()->jumpToMarkerLine(requestBacklog);
350 void ChatView::addActionsToMenu(QMenu* menu, const QPointF& pos)
353 auto* bw = qobject_cast<BufferWidget*>(bufferContainer());
355 bw->addActionsToMenu(menu, pos);
356 menu->addSeparator();
360 void ChatView::zoomIn()
362 _currentScaleFactor *= 1.2;
364 scene()->setWidth(viewport()->width() / _currentScaleFactor - 2);
367 void ChatView::zoomOut()
369 _currentScaleFactor /= 1.2;
370 scale(1 / 1.2, 1 / 1.2);
371 scene()->setWidth(viewport()->width() / _currentScaleFactor - 2);
374 void ChatView::zoomOriginal()
376 scale(1 / _currentScaleFactor, 1 / _currentScaleFactor);
377 _currentScaleFactor = 1;
378 scene()->setWidth(viewport()->width() - 2);
381 void ChatView::invalidateFilter()
383 // if this is the currently selected chatview
384 // invalidate immediately
386 _scene->filter()->invalidateFilter();
387 _invalidateFilter = false;
389 // otherwise invalidate whenever the view is shown
391 _invalidateFilter = true;
395 void ChatView::scrollContentsBy(int dx, int dy)
397 QGraphicsView::scrollContentsBy(dx, dy);
398 checkChatLineCaches();
401 void ChatView::setHasCache(ChatLine* line, bool hasCache)
404 _linesWithCache.insert(line);
406 _linesWithCache.remove(line);
409 void ChatView::checkChatLineCaches()
411 qreal top = mapToScene(viewport()->rect().topLeft()).y() - 10; // some grace area to avoid premature cleaning
412 qreal bottom = mapToScene(viewport()->rect().bottomRight()).y() + 10;
413 QSet<ChatLine*>::iterator iter = _linesWithCache.begin();
414 while (iter != _linesWithCache.end()) {
415 ChatLine* line = *iter;
416 if (line->pos().y() + line->height() < top || line->pos().y() > bottom) {
418 iter = _linesWithCache.erase(iter);