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