cmake: avoid de-duplication of user's CXXFLAGS
[quassel.git] / src / qtui / chatview.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2020 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 "chatview.h"
22
23 #include <algorithm>
24
25 #include <QGraphicsTextItem>
26 #include <QKeyEvent>
27 #include <QMenu>
28 #include <QScrollBar>
29
30 #include "bufferwidget.h"
31 #include "chatline.h"
32 #include "chatscene.h"
33 #include "client.h"
34 #include "clientignorelistmanager.h"
35 #include "messagefilter.h"
36 #include "qtui.h"
37 #include "qtuistyle.h"
38 #include "util.h"
39
40 ChatView::ChatView(BufferId bufferId, QWidget* parent)
41     : QGraphicsView(parent)
42     , AbstractChatView()
43 {
44     QList<BufferId> filterList;
45     filterList.append(bufferId);
46     auto* filter = new MessageFilter(Client::messageModel(), filterList, this);
47     init(filter);
48 }
49
50 ChatView::ChatView(MessageFilter* filter, QWidget* parent)
51     : QGraphicsView(parent)
52     , AbstractChatView()
53 {
54     init(filter);
55 }
56
57 void ChatView::init(MessageFilter* filter)
58 {
59     _bufferContainer = nullptr;
60     _currentScaleFactor = 1;
61     _invalidateFilter = false;
62
63     setAttribute(Qt::WA_AcceptTouchEvents);
64     setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
65     setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
66     setAlignment(Qt::AlignLeft | Qt::AlignBottom);
67     setInteractive(true);
68     // setOptimizationFlags(QGraphicsView::DontClipPainter | QGraphicsView::DontAdjustForAntialiasing);
69     // setOptimizationFlags(QGraphicsView::DontAdjustForAntialiasing);
70     setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
71     // setTransformationAnchor(QGraphicsView::NoAnchor);
72     setTransformationAnchor(QGraphicsView::AnchorViewCenter);
73
74     _scrollTimer.setInterval(100);
75     _scrollTimer.setSingleShot(true);
76     connect(&_scrollTimer, &QTimer::timeout, this, &ChatView::scrollTimerTimeout);
77
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);
82     setScene(_scene);
83
84     connect(verticalScrollBar(), &QAbstractSlider::valueChanged, this, &ChatView::verticalScrollbarChanged);
85     _lastScrollbarPos = verticalScrollBar()->maximum();
86
87     connect(Client::networkModel(), &NetworkModel::markerLineSet, this, &ChatView::markerLineSet);
88
89     // only connect if client is synched with a core
90     if (Client::isConnected())
91         connect(Client::ignoreListManager(), &ClientIgnoreListManager::ignoreListChanged, this, &ChatView::invalidateFilter);
92 }
93
94 bool ChatView::event(QEvent* event)
95 {
96     if (event->type() == QEvent::KeyPress) {
97         auto* 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 && ((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())
119             return true;
120     }
121
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;
127         return true;
128     }
129
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());
137             if (dx > dy) {
138                 setDragMode(QGraphicsView::NoDrag);
139                 setInteractive(true);
140             }
141             _firstTouchUpdateHappened = true;
142         }
143         // Applying the movement happens automatically by the drag-mode
144     }
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();
150             return true;
151         }
152     }
153
154     if (event->type() == QEvent::Show) {
155         if (_invalidateFilter)
156             invalidateFilter();
157     }
158
159     return QGraphicsView::event(event);
160 }
161
162 void ChatView::resizeEvent(QResizeEvent* event)
163 {
164     // if view is currently scrolled to bottom, we want it that way after resizing
165     bool atBottom = (_lastScrollbarPos == verticalScrollBar()->maximum());
166
167     QGraphicsView::resizeEvent(event);
168
169     // if scrolling to bottom, do it immediately.
170     if (atBottom) {
171         // we can reduce viewport updates if we scroll to the bottom allready at the beginning
172         verticalScrollBar()->setValue(verticalScrollBar()->maximum());
173     }
174
175     scene()->updateForViewport(viewport()->width(), viewport()->height());
176     adjustSceneRect();
177
178     if (atBottom) {
179         _lastScrollbarPos = verticalScrollBar()->maximum();
180         verticalScrollBar()->setValue(verticalScrollBar()->maximum());
181     }
182     checkChatLineCaches();
183 }
184
185 void ChatView::adjustSceneRect()
186 {
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.
193
194     setSceneRect(scene()->sceneRect().adjusted(0, 0, -25, 0));
195 }
196
197 void ChatView::mouseMoveWhileSelecting(const QPointF& scenePos)
198 {
199     int y = (int)mapFromScene(scenePos).y();
200     _scrollOffset = 0;
201     if (y < 0)
202         _scrollOffset = y;
203     else if (y > height())
204         _scrollOffset = y - height();
205
206     if (_scrollOffset && !_scrollTimer.isActive())
207         _scrollTimer.start();
208 }
209
210 void ChatView::scrollTimerTimeout()
211 {
212     // scroll view
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()));
218 }
219
220 void ChatView::lastLineChanged(QGraphicsItem* chatLine, qreal offset)
221 {
222     Q_UNUSED(chatLine)
223     // disabled until further testing/discussion
224     // if(!scene()->isScrollingAllowed())
225     //  return;
226
227     QAbstractSlider* vbar = verticalScrollBar();
228     Q_ASSERT(vbar);
229     if (vbar->maximum() - vbar->value() <= (offset + 5) * _currentScaleFactor) {  // 5px grace area
230         vbar->setValue(vbar->maximum());
231     }
232 }
233
234 void ChatView::verticalScrollbarChanged(int newPos)
235 {
236     QAbstractSlider* vbar = verticalScrollBar();
237     Q_ASSERT(vbar);
238
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());
244
245         if (relativePos < 20) {
246             scene()->requestBacklog();
247         }
248     }
249     _lastScrollbarPos = newPos;
250
251     // FIXME: Fugly workaround for the ChatView scrolling up 1px on buffer switch
252     if (vbar->maximum() - newPos <= 2)
253         vbar->setValue(vbar->maximum());
254 }
255
256 MsgId ChatView::lastMsgId() const
257 {
258     if (!scene())
259         return {};
260
261     QAbstractItemModel* model = scene()->model();
262     if (!model || model->rowCount() == 0)
263         return {};
264
265     return model->index(model->rowCount() - 1, 0).data(MessageModel::MsgIdRole).value<MsgId>();
266 }
267
268 MsgId ChatView::lastVisibleMsgId() const
269 {
270     ChatLine* line = lastVisibleChatLine();
271
272     if (line)
273         return line->msgId();
274
275     return {};
276 }
277
278 bool chatLinePtrLessThan(ChatLine* one, ChatLine* other)
279 {
280     return one->row() < other->row();
281 }
282
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
285 {
286     QSet<ChatLine*> result;
287     foreach (QGraphicsItem* item, items(viewport()->rect().adjusted(-1, -1, 1, 1), mode)) {
288         auto* line = qgraphicsitem_cast<ChatLine*>(item);
289         if (line)
290             result.insert(line);
291     }
292     return result;
293 }
294
295 QList<ChatLine*> ChatView::visibleChatLinesSorted(Qt::ItemSelectionMode mode) const
296 {
297     QList<ChatLine*> result = visibleChatLines(mode).values();
298     std::sort(result.begin(), result.end(), chatLinePtrLessThan);
299     return result;
300 }
301
302 ChatLine* ChatView::lastVisibleChatLine(bool ignoreDayChange) const
303 {
304     if (!scene())
305         return nullptr;
306
307     QAbstractItemModel* model = scene()->model();
308     if (!model || model->rowCount() == 0)
309         return nullptr;
310
311     int row = -1;
312
313     QSet<ChatLine*> visibleLines = visibleChatLines(Qt::ContainsItemBoundingRect);
314     foreach (ChatLine* line, visibleLines) {
315         if (line->row() > row && (ignoreDayChange ? line->msgType() != Message::DayChange : true))
316             row = line->row();
317     }
318
319     if (row >= 0)
320         return scene()->chatLine(row);
321
322     return nullptr;
323 }
324
325 void ChatView::setMarkerLineVisible(bool visible)
326 {
327     scene()->setMarkerLineVisible(visible);
328 }
329
330 void ChatView::setMarkerLine(MsgId msgId)
331 {
332     if (!scene()->isSingleBufferScene())
333         return;
334
335     BufferId bufId = scene()->singleBufferId();
336     Client::setMarkerLine(bufId, msgId);
337 }
338
339 void ChatView::markerLineSet(BufferId buffer, MsgId msgId)
340 {
341     if (!scene()->isSingleBufferScene() || scene()->singleBufferId() != buffer)
342         return;
343
344     scene()->setMarkerLine(msgId);
345     scene()->setMarkerLineVisible(true);
346 }
347
348 void ChatView::jumpToMarkerLine(bool requestBacklog)
349 {
350     scene()->jumpToMarkerLine(requestBacklog);
351 }
352
353 void ChatView::addActionsToMenu(QMenu* menu, const QPointF& pos)
354 {
355     // zoom actions
356     auto* bw = qobject_cast<BufferWidget*>(bufferContainer());
357     if (bw) {
358         bw->addActionsToMenu(menu, pos);
359         menu->addSeparator();
360     }
361 }
362
363 void ChatView::zoomIn()
364 {
365     _currentScaleFactor *= 1.2;
366     scale(1.2, 1.2);
367     scene()->setWidth(viewport()->width() / _currentScaleFactor - 2);
368 }
369
370 void ChatView::zoomOut()
371 {
372     _currentScaleFactor /= 1.2;
373     scale(1 / 1.2, 1 / 1.2);
374     scene()->setWidth(viewport()->width() / _currentScaleFactor - 2);
375 }
376
377 void ChatView::zoomOriginal()
378 {
379     scale(1 / _currentScaleFactor, 1 / _currentScaleFactor);
380     _currentScaleFactor = 1;
381     scene()->setWidth(viewport()->width() - 2);
382 }
383
384 void ChatView::invalidateFilter()
385 {
386     // if this is the currently selected chatview
387     // invalidate immediately
388     if (isVisible()) {
389         _scene->filter()->invalidateFilter();
390         _invalidateFilter = false;
391     }
392     // otherwise invalidate whenever the view is shown
393     else {
394         _invalidateFilter = true;
395     }
396 }
397
398 void ChatView::scrollContentsBy(int dx, int dy)
399 {
400     QGraphicsView::scrollContentsBy(dx, dy);
401     checkChatLineCaches();
402 }
403
404 void ChatView::setHasCache(ChatLine* line, bool hasCache)
405 {
406     if (hasCache)
407         _linesWithCache.insert(line);
408     else
409         _linesWithCache.remove(line);
410 }
411
412 void ChatView::checkChatLineCaches()
413 {
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) {
420             line->clearCache();
421             iter = _linesWithCache.erase(iter);
422         }
423         else
424             ++iter;
425     }
426 }