1 /***************************************************************************
2 * Copyright (C) 2005-2020 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 ***************************************************************************/
25 #include <QGraphicsTextItem>
30 #include "bufferwidget.h"
32 #include "chatscene.h"
34 #include "clientignorelistmanager.h"
35 #include "messagefilter.h"
37 #include "qtuistyle.h"
40 ChatView::ChatView(BufferId bufferId, QWidget* parent)
41 : QGraphicsView(parent)
44 QList<BufferId> filterList;
45 filterList.append(bufferId);
46 auto* filter = new MessageFilter(Client::messageModel(), filterList, this);
50 ChatView::ChatView(MessageFilter* filter, QWidget* parent)
51 : QGraphicsView(parent)
57 void ChatView::init(MessageFilter* filter)
59 _bufferContainer = nullptr;
60 _currentScaleFactor = 1;
61 _invalidateFilter = false;
63 setAttribute(Qt::WA_AcceptTouchEvents);
64 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
65 setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
66 setAlignment(Qt::AlignLeft | Qt::AlignBottom);
68 // setOptimizationFlags(QGraphicsView::DontClipPainter | QGraphicsView::DontAdjustForAntialiasing);
69 // setOptimizationFlags(QGraphicsView::DontAdjustForAntialiasing);
70 setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
71 // setTransformationAnchor(QGraphicsView::NoAnchor);
72 setTransformationAnchor(QGraphicsView::AnchorViewCenter);
74 _scrollTimer.setInterval(100);
75 _scrollTimer.setSingleShot(true);
76 connect(&_scrollTimer, &QTimer::timeout, this, &ChatView::scrollTimerTimeout);
78 _scene = new ChatScene(filter, filter->idString(), viewport()->width(), this);
79 connect(_scene, &QGraphicsScene::sceneRectChanged, this, &ChatView::adjustSceneRect);
80 connect(_scene, &ChatScene::lastLineChanged, this, &ChatView::lastLineChanged);
81 connect(_scene, &ChatScene::mouseMoveWhileSelecting, this, &ChatView::mouseMoveWhileSelecting);
84 connect(verticalScrollBar(), &QAbstractSlider::valueChanged, this, &ChatView::verticalScrollbarChanged);
85 _lastScrollbarPos = verticalScrollBar()->maximum();
87 connect(Client::networkModel(), &NetworkModel::markerLineSet, this, &ChatView::markerLineSet);
89 // only connect if client is synched with a core
90 if (Client::isConnected())
91 connect(Client::ignoreListManager(), &ClientIgnoreListManager::ignoreListChanged, this, &ChatView::invalidateFilter);
94 bool ChatView::event(QEvent* event)
96 if (event->type() == QEvent::KeyPress) {
97 auto* keyEvent = static_cast<QKeyEvent*>(event);
98 switch (keyEvent->key()) {
102 case Qt::Key_PageDown:
103 if (!verticalScrollBar()->isVisible()) {
104 scene()->requestBacklog();
112 if (event->type() == QEvent::TouchBegin && ((QTouchEvent*)event)->device()->type() == QTouchDevice::TouchScreen) {
113 // Enable scrolling by draging, disable selecting/clicking content
114 setDragMode(QGraphicsView::ScrollHandDrag);
115 setInteractive(false);
116 // if scrollbar is not visible we need to request backlog below else we need to accept
117 // the event now (return true) so that we will receive TouchUpdate and TouchEnd/TouchCancel
118 if (verticalScrollBar()->isVisible())
122 if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) {
123 // End scroll and reset settings to default
124 setDragMode(QGraphicsView::NoDrag);
125 setInteractive(true);
126 _firstTouchUpdateHappened = false;
130 if (event->type() == QEvent::TouchUpdate) {
131 if (!_firstTouchUpdateHappened) {
132 // After the first movement of a Touch-Point, calculate the distance in both axis
133 // and if the point moved more horizontally abort scroll.
134 QTouchEvent::TouchPoint p = ((QTouchEvent*)event)->touchPoints().at(0);
135 double dx = qAbs(p.lastPos().x() - p.pos().x());
136 double dy = qAbs(p.lastPos().y() - p.pos().y());
138 setDragMode(QGraphicsView::NoDrag);
139 setInteractive(true);
141 _firstTouchUpdateHappened = true;
143 // Applying the movement happens automatically by the drag-mode
145 if (event->type() == QEvent::Wheel
146 || (event->type() == QEvent::TouchBegin && ((QTouchEvent*)event)->device()->type() == QTouchDevice::TouchScreen)
147 || event->type() == QEvent::TouchUpdate) {
148 if (!verticalScrollBar()->isVisible()) {
149 scene()->requestBacklog();
154 if (event->type() == QEvent::Show) {
155 if (_invalidateFilter)
159 return QGraphicsView::event(event);
162 void ChatView::resizeEvent(QResizeEvent* event)
164 // if view is currently scrolled to bottom, we want it that way after resizing
165 bool atBottom = (_lastScrollbarPos == verticalScrollBar()->maximum());
167 QGraphicsView::resizeEvent(event);
169 // if scrolling to bottom, do it immediately.
171 // we can reduce viewport updates if we scroll to the bottom allready at the beginning
172 verticalScrollBar()->setValue(verticalScrollBar()->maximum());
175 scene()->updateForViewport(viewport()->width(), viewport()->height());
179 _lastScrollbarPos = verticalScrollBar()->maximum();
180 verticalScrollBar()->setValue(verticalScrollBar()->maximum());
182 checkChatLineCaches();
185 void ChatView::adjustSceneRect()
187 // Workaround for QTBUG-6322
188 // If the viewport's sceneRect() is (almost) as wide as as the viewport itself,
189 // Qt wants to reserve space for scrollbars even if they're turned off, resulting in
190 // an ugly white space at the bottom of the ChatView.
191 // Since the view's scene's width actually doesn't matter at all, we just adjust it
192 // by some hopefully large enough value to avoid this problem.
194 setSceneRect(scene()->sceneRect().adjusted(0, 0, -25, 0));
197 void ChatView::mouseMoveWhileSelecting(const QPointF& scenePos)
199 int y = (int)mapFromScene(scenePos).y();
203 else if (y > height())
204 _scrollOffset = y - height();
206 if (_scrollOffset && !_scrollTimer.isActive())
207 _scrollTimer.start();
210 void ChatView::scrollTimerTimeout()
213 QAbstractSlider* vbar = verticalScrollBar();
214 if (_scrollOffset < 0 && vbar->value() > 0)
215 vbar->setValue(qMax(vbar->value() + _scrollOffset, 0));
216 else if (_scrollOffset > 0 && vbar->value() < vbar->maximum())
217 vbar->setValue(qMin(vbar->value() + _scrollOffset, vbar->maximum()));
220 void ChatView::lastLineChanged(QGraphicsItem* chatLine, qreal offset)
223 // disabled until further testing/discussion
224 // if(!scene()->isScrollingAllowed())
227 QAbstractSlider* vbar = verticalScrollBar();
229 if (vbar->maximum() - vbar->value() <= (offset + 5) * _currentScaleFactor) { // 5px grace area
230 vbar->setValue(vbar->maximum());
234 void ChatView::verticalScrollbarChanged(int newPos)
236 QAbstractSlider* vbar = verticalScrollBar();
239 // check for backlog request
240 if (newPos < _lastScrollbarPos) {
241 int relativePos = 100;
242 if (vbar->maximum() - vbar->minimum() != 0)
243 relativePos = (newPos - vbar->minimum()) * 100 / (vbar->maximum() - vbar->minimum());
245 if (relativePos < 20) {
246 scene()->requestBacklog();
249 _lastScrollbarPos = newPos;
251 // FIXME: Fugly workaround for the ChatView scrolling up 1px on buffer switch
252 if (vbar->maximum() - newPos <= 2)
253 vbar->setValue(vbar->maximum());
256 MsgId ChatView::lastMsgId() const
261 QAbstractItemModel* model = scene()->model();
262 if (!model || model->rowCount() == 0)
265 return model->index(model->rowCount() - 1, 0).data(MessageModel::MsgIdRole).value<MsgId>();
268 MsgId ChatView::lastVisibleMsgId() const
270 ChatLine* line = lastVisibleChatLine();
273 return line->msgId();
278 bool chatLinePtrLessThan(ChatLine* one, ChatLine* other)
280 return one->row() < other->row();
283 // TODO: figure out if it's cheaper to use a cached list (that we'd need to keep updated)
284 QSet<ChatLine*> ChatView::visibleChatLines(Qt::ItemSelectionMode mode) const
286 QSet<ChatLine*> result;
287 foreach (QGraphicsItem* item, items(viewport()->rect().adjusted(-1, -1, 1, 1), mode)) {
288 auto* line = qgraphicsitem_cast<ChatLine*>(item);
295 QList<ChatLine*> ChatView::visibleChatLinesSorted(Qt::ItemSelectionMode mode) const
297 QList<ChatLine*> result = visibleChatLines(mode).values();
298 std::sort(result.begin(), result.end(), chatLinePtrLessThan);
302 ChatLine* ChatView::lastVisibleChatLine(bool ignoreDayChange) const
307 QAbstractItemModel* model = scene()->model();
308 if (!model || model->rowCount() == 0)
313 QSet<ChatLine*> visibleLines = visibleChatLines(Qt::ContainsItemBoundingRect);
314 foreach (ChatLine* line, visibleLines) {
315 if (line->row() > row && (ignoreDayChange ? line->msgType() != Message::DayChange : true))
320 return scene()->chatLine(row);
325 void ChatView::setMarkerLineVisible(bool visible)
327 scene()->setMarkerLineVisible(visible);
330 void ChatView::setMarkerLine(MsgId msgId)
332 if (!scene()->isSingleBufferScene())
335 BufferId bufId = scene()->singleBufferId();
336 Client::setMarkerLine(bufId, msgId);
339 void ChatView::markerLineSet(BufferId buffer, MsgId msgId)
341 if (!scene()->isSingleBufferScene() || scene()->singleBufferId() != buffer)
344 scene()->setMarkerLine(msgId);
345 scene()->setMarkerLineVisible(true);
348 void ChatView::jumpToMarkerLine(bool requestBacklog)
350 scene()->jumpToMarkerLine(requestBacklog);
353 void ChatView::addActionsToMenu(QMenu* menu, const QPointF& pos)
356 auto* bw = qobject_cast<BufferWidget*>(bufferContainer());
358 bw->addActionsToMenu(menu, pos);
359 menu->addSeparator();
363 void ChatView::zoomIn()
365 _currentScaleFactor *= 1.2;
367 scene()->setWidth(viewport()->width() / _currentScaleFactor - 2);
370 void ChatView::zoomOut()
372 _currentScaleFactor /= 1.2;
373 scale(1 / 1.2, 1 / 1.2);
374 scene()->setWidth(viewport()->width() / _currentScaleFactor - 2);
377 void ChatView::zoomOriginal()
379 scale(1 / _currentScaleFactor, 1 / _currentScaleFactor);
380 _currentScaleFactor = 1;
381 scene()->setWidth(viewport()->width() - 2);
384 void ChatView::invalidateFilter()
386 // if this is the currently selected chatview
387 // invalidate immediately
389 _scene->filter()->invalidateFilter();
390 _invalidateFilter = false;
392 // otherwise invalidate whenever the view is shown
394 _invalidateFilter = true;
398 void ChatView::scrollContentsBy(int dx, int dy)
400 QGraphicsView::scrollContentsBy(dx, dy);
401 checkChatLineCaches();
404 void ChatView::setHasCache(ChatLine* line, bool hasCache)
407 _linesWithCache.insert(line);
409 _linesWithCache.remove(line);
412 void ChatView::checkChatLineCaches()
414 qreal top = mapToScene(viewport()->rect().topLeft()).y() - 10; // some grace area to avoid premature cleaning
415 qreal bottom = mapToScene(viewport()->rect().bottomRight()).y() + 10;
416 QSet<ChatLine*>::iterator iter = _linesWithCache.begin();
417 while (iter != _linesWithCache.end()) {
418 ChatLine* line = *iter;
419 if (line->pos().y() + line->height() < top || line->pos().y() > bottom) {
421 iter = _linesWithCache.erase(iter);