fixing speed up aftermath
[quassel.git] / src / qtui / chatscene.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 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 <QApplication>
22 #include <QClipboard>
23 #include <QGraphicsSceneMouseEvent>
24 #include <QPersistentModelIndex>
25
26 #include "chatitem.h"
27 #include "chatline.h"
28 #include "chatlinemodelitem.h"
29 #include "chatscene.h"
30 #include "client.h"
31 #include "clientbacklogmanager.h"
32 #include "columnhandleitem.h"
33 #include "messagefilter.h"
34 #include "qtui.h"
35 #include "qtuistyle.h"
36 #include "chatviewsettings.h"
37
38 const qreal minContentsWidth = 200;
39
40 ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, qreal width, QObject *parent)
41   : QGraphicsScene(0, 0, width, 0, parent),
42     _idString(idString),
43     _model(model),
44     _singleBufferScene(false),
45     _sceneRect(0, 0, width, 0),
46     _viewportHeight(0),
47     _selectingItem(0),
48     _selectionStart(-1),
49     _isSelecting(false),
50     _lastBacklogSize(0)
51 {
52   MessageFilter *filter = qobject_cast<MessageFilter*>(model);
53   if(filter) {
54     _singleBufferScene = filter->isSingleBufferFilter();
55   }
56
57   ChatViewSettings defaultSettings;
58   int defaultFirstColHandlePos = defaultSettings.value("FirstColumnHandlePos", 80).toInt();
59   int defaultSecondColHandlePos = defaultSettings.value("SecondColumnHandlePos", 200).toInt();
60
61   ChatViewSettings viewSettings(this);
62   firstColHandlePos = viewSettings.value("FirstColumnHandlePos", defaultFirstColHandlePos).toInt();
63   secondColHandlePos = viewSettings.value("SecondColumnHandlePos", defaultSecondColHandlePos).toInt();
64
65   firstColHandle = new ColumnHandleItem(QtUi::style()->firstColumnSeparator());
66   addItem(firstColHandle);
67   firstColHandle->setXPos(firstColHandlePos);
68   connect(firstColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
69   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), firstColHandle, SLOT(sceneRectChanged(const QRectF &)));
70
71   secondColHandle = new ColumnHandleItem(QtUi::style()->secondColumnSeparator());
72   addItem(secondColHandle);
73   secondColHandle->setXPos(secondColHandlePos);
74   connect(secondColHandle, SIGNAL(positionChanged(qreal)), this, SLOT(handlePositionChanged(qreal)));
75   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), secondColHandle, SLOT(sceneRectChanged(const QRectF &)));
76
77   setHandleXLimits();
78
79   connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
80           this, SLOT(rowsInserted(const QModelIndex &, int, int)));
81   connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
82           this, SLOT(rowsAboutToBeRemoved(const QModelIndex &, int, int)));
83
84   if(model->rowCount() > 0)
85     rowsInserted(QModelIndex(), 0, model->rowCount() - 1);
86 }
87
88 ChatScene::~ChatScene() {
89 }
90
91 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
92   Q_UNUSED(index);
93   qreal h = 0;
94   qreal y = _sceneRect.y();
95   qreal width = _sceneRect.width();
96   bool atTop = true;
97   bool atBottom = false;
98   bool moveTop = false;
99
100   if(start > 0) {
101     y = _lines.value(start - 1)->y() + _lines.value(start - 1)->height();
102     atTop = false;
103   }
104   if(start == _lines.count())
105     atBottom = true;
106
107   qreal contentsWidth = width - secondColumnHandle()->sceneRight();
108   qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
109   qreal timestampWidth = firstColumnHandle()->sceneLeft();
110   QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
111   QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
112
113
114   for(int i = end; i >= start; i--) {
115     ChatLine *line = new ChatLine(i, model(),
116                                   width,
117                                   timestampWidth, senderWidth, contentsWidth,
118                                   senderPos, contentsPos);
119     if(atTop) {
120       h -= line->height();
121       line->setPos(0, y+h);
122     } else {
123       line->setPos(0, y+h);
124       h += line->height();
125     }
126     _lines.insert(start, line);
127     addItem(line);
128   }
129
130   // update existing items
131   for(int i = end+1; i < _lines.count(); i++) {
132     _lines[i]->setRow(i);
133   }
134
135   // update selection
136   if(_selectionStart >= 0) {
137     int offset = end - start + 1;
138     if(_selectionStart >= start) _selectionStart += offset;
139     if(_selectionEnd >= start) _selectionEnd += offset;
140     if(_firstSelectionRow >= start) _firstSelectionRow += offset;
141     if(_lastSelectionRow >= start) _lastSelectionRow += offset;
142   }
143
144   // neither pre- or append means we have to do dirty work: move items...
145   if(!(atTop || atBottom)) {
146     qreal offset = h;
147     int moveStart = 0;
148     int moveEnd = _lines.count() - 1;
149     ChatLine *line = 0;
150     if(end > _lines.count() - end) {
151       // move top part
152       moveTop = true;
153       offset = -offset;
154       moveEnd = end;
155     } else {
156       // move bottom part
157       moveStart = start;
158     }
159     for(int i = moveStart; i <= moveEnd; i++) {
160       line = _lines.at(i);
161       line->setPos(0, line->pos().y() + offset);
162     }
163   }
164
165   // update sceneRect
166   if(atTop || moveTop) {
167     updateSceneRect(_sceneRect.adjusted(0, h, 0, 0));
168   } else {
169     updateSceneRect(_sceneRect.adjusted(0, 0, 0, h));
170     emit lastLineChanged(_lines.last());
171   }
172
173 }
174
175 void ChatScene::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
176   Q_UNUSED(parent);
177
178   qreal h = 0; // total height of removed items;
179
180   bool atTop = (start == 0);
181   bool atBottom = (end == _lines.count() - 1);
182   bool moveTop = false;
183
184   // remove items from scene
185   QList<ChatLine *>::iterator lineIter = _lines.begin() + start;
186   int lineCount = start;
187   while(lineIter != _lines.end() && lineCount <= end) {
188     h += (*lineIter)->height();
189     delete *lineIter;
190     lineIter = _lines.erase(lineIter);
191     lineCount++;
192   }
193
194   // update rows of remaining chatlines
195   for(int i = start; i < _lines.count(); i++) {
196     _lines.at(i)->setRow(i);
197   }
198
199   // update selection
200   if(_selectionStart >= 0) {
201     int offset = end - start + 1;
202     if(_selectionStart >= start)
203       _selectionStart -= offset;
204     if(_selectionEnd >= start)
205       _selectionEnd -= offset;
206     if(_firstSelectionRow >= start)
207       _firstSelectionRow -= offset;
208     if(_lastSelectionRow >= start)
209       _lastSelectionRow -= offset;
210   }
211
212   // neither removing at bottom or top means we have to move items...
213   if(!(atTop || atBottom)) {
214     qreal offset = h;
215     int moveStart = 0;
216     int moveEnd = _lines.count() - 1;
217     ChatLine *line = 0;
218     if(start > _lines.count() - end) {
219       // move top part
220       moveTop = true;
221       moveEnd = start - 1;
222     } else {
223       // move bottom part
224       moveStart = start;
225       offset = -offset;
226     }
227     for(int i = moveStart; i <= moveEnd; i++) {
228       line = _lines.at(i);
229       line->setPos(0, line->pos().y() + offset);
230     }
231   }
232
233   // update sceneRect
234   if(atTop || moveTop) {
235     updateSceneRect(_sceneRect.adjusted(0, h, 0, 0));
236   } else {
237     updateSceneRect(_sceneRect.adjusted(0, 0, 0, -h));
238   }
239 }
240
241 void ChatScene::updateForViewport(qreal width, qreal height) {
242   _viewportHeight = height;
243   setWidth(width);
244 }
245
246 // setWidth is used for 2 things:
247 //  a) updating the scene to fit the width of the corresponding view
248 //  b) to update the positions of the items if a columhandle has changed it's position
249 // forceReposition is true in the second case
250 // this method features some codeduplication for the sake of performance
251 void ChatScene::setWidth(qreal width, bool forceReposition) {
252   if(width == _sceneRect.width() && !forceReposition)
253     return;
254
255 //   clock_t startT = clock();
256
257   qreal linePos = _sceneRect.y() + _sceneRect.height();
258   qreal yBottom = linePos;
259   QList<ChatLine *>::iterator lineIter = _lines.end();
260   QList<ChatLine *>::iterator lineIterBegin = _lines.begin();
261   ChatLine *line = 0;
262   qreal lineHeight = 0;
263   qreal contentsWidth = width - secondColumnHandle()->sceneRight();
264
265   if(forceReposition) {
266     qreal timestampWidth = firstColumnHandle()->sceneLeft();
267     qreal senderWidth = secondColumnHandle()->sceneLeft() - firstColumnHandle()->sceneRight();
268     QPointF senderPos(firstColumnHandle()->sceneRight(), 0);
269     QPointF contentsPos(secondColumnHandle()->sceneRight(), 0);
270     while(lineIter != lineIterBegin) {
271       lineIter--;
272       line = *lineIter;
273       lineHeight = line->setColumns(timestampWidth, senderWidth, contentsWidth, senderPos, contentsPos);
274       linePos -= lineHeight;
275       line->setPos(0, linePos);
276     }
277   } else {
278     while(lineIter != lineIterBegin) {
279       lineIter--;
280       line = *lineIter;
281       lineHeight = line->setGeometryByWidth(width, contentsWidth);
282       linePos -= lineHeight;
283       line->setPos(0, linePos);
284     }
285   }
286
287   updateSceneRect(QRectF(0, linePos, width, yBottom - linePos));
288   setHandleXLimits();
289
290 //   clock_t endT = clock();
291 //   qDebug() << "resized" << _lines.count() << "in" << (float)(endT - startT) / CLOCKS_PER_SEC << "sec";
292 }
293
294 void ChatScene::handlePositionChanged(qreal xpos) {
295   bool first = (sender() == firstColHandle);
296   qreal oldx;
297   if(first) {
298     oldx = firstColHandlePos;
299     firstColHandlePos = xpos;
300   } else {
301     oldx = secondColHandlePos;
302     secondColHandlePos = xpos;
303   }
304
305   ChatViewSettings viewSettings(this);
306   viewSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
307   viewSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
308
309   ChatViewSettings defaultSettings;
310   defaultSettings.setValue("FirstColumnHandlePos", firstColHandlePos);
311   defaultSettings.setValue("SecondColumnHandlePos", secondColHandlePos);
312
313   setWidth(width(), true);  // readjust all chatlines
314   // we get ugly redraw errors if we don't update this explicitly... :(
315   // width() should be the same for both handles, so just use firstColHandle regardless
316   //update(qMin(oldx, xpos), 0, qMax(oldx, xpos) + firstColHandle->width(), height());
317 }
318
319 void ChatScene::setHandleXLimits() {
320   firstColHandle->setXLimits(0, secondColHandle->sceneLeft());
321   secondColHandle->setXLimits(firstColHandle->sceneRight(), width() - minContentsWidth);
322 }
323
324 void ChatScene::setSelectingItem(ChatItem *item) {
325   if(_selectingItem) _selectingItem->clearSelection();
326   _selectingItem = item;
327 }
328
329 void ChatScene::startGlobalSelection(ChatItem *item, const QPointF &itemPos) {
330   _selectionStart = _selectionEnd = _lastSelectionRow = _firstSelectionRow = item->row();
331   _selectionStartCol = _selectionMinCol = item->column();
332   _isSelecting = true;
333   _lines[_selectionStart]->setSelected(true, (ChatLineModel::ColumnType)_selectionMinCol);
334   updateSelection(item->mapToScene(itemPos));
335 }
336
337 void ChatScene::updateSelection(const QPointF &pos) {
338   // This is somewhat hacky... we look at the contents item that is at the cursor's y position (ignoring x), since
339   // it has the full height. From this item, we can then determine the row index and hence the ChatLine.
340   ChatItem *contentItem = static_cast<ChatItem *>(itemAt(QPointF(secondColHandle->sceneRight() + 1, pos.y())));
341   if(!contentItem) return;
342
343   int curRow = contentItem->row();
344   int curColumn;
345   if(pos.x() > secondColHandle->sceneRight()) curColumn = ChatLineModel::ContentsColumn;
346   else if(pos.x() > firstColHandlePos) curColumn = ChatLineModel::SenderColumn;
347   else curColumn = ChatLineModel::TimestampColumn;
348
349   ChatLineModel::ColumnType minColumn = (ChatLineModel::ColumnType)qMin(curColumn, _selectionStartCol);
350   if(minColumn != _selectionMinCol) {
351     _selectionMinCol = minColumn;
352     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
353       _lines[l]->setSelected(true, minColumn);
354     }
355   }
356   int newstart = qMin(curRow, _firstSelectionRow);
357   int newend = qMax(curRow, _firstSelectionRow);
358   if(newstart < _selectionStart) {
359     for(int l = newstart; l < _selectionStart; l++)
360       _lines[l]->setSelected(true, minColumn);
361   }
362   if(newstart > _selectionStart) {
363     for(int l = _selectionStart; l < newstart; l++)
364       _lines[l]->setSelected(false);
365   }
366   if(newend > _selectionEnd) {
367     for(int l = _selectionEnd+1; l <= newend; l++)
368       _lines[l]->setSelected(true, minColumn);
369   }
370   if(newend < _selectionEnd) {
371     for(int l = newend+1; l <= _selectionEnd; l++)
372       _lines[l]->setSelected(false);
373   }
374
375   _selectionStart = newstart;
376   _selectionEnd = newend;
377   _lastSelectionRow = curRow;
378
379   if(newstart == newend && minColumn == ChatLineModel::ContentsColumn) {
380     if(!_selectingItem) {
381       qWarning() << "WARNING: ChatScene::updateSelection() has a null _selectingItem, this should never happen! Please report.";
382       return;
383     }
384     _lines[curRow]->setSelected(false);
385     _isSelecting = false;
386     _selectingItem->continueSelecting(_selectingItem->mapFromScene(pos));
387   }
388 }
389
390 void ChatScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
391   if(_isSelecting && event->buttons() == Qt::LeftButton) {
392     updateSelection(event->scenePos());
393     event->accept();
394   } else {
395     QGraphicsScene::mouseMoveEvent(event);
396   }
397 }
398
399 void ChatScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
400   if(event->buttons() == Qt::LeftButton && _selectionStart >= 0) {
401     for(int l = qMin(_selectionStart, _selectionEnd); l <= qMax(_selectionStart, _selectionEnd); l++) {
402       _lines[l]->setSelected(false);
403     }
404     _selectionStart = -1;
405     QGraphicsScene::mousePressEvent(event);  // so we can start a new local selection
406   } else {
407     QGraphicsScene::mousePressEvent(event);
408   }
409 }
410
411 void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
412   if(_isSelecting && !event->buttons() & Qt::LeftButton) {
413     putToClipboard(selectionToString());
414     _isSelecting = false;
415     event->accept();
416   } else {
417     QGraphicsScene::mouseReleaseEvent(event);
418   }
419 }
420
421 void ChatScene::putToClipboard(const QString &selection) {
422   // TODO Configure clipboards
423 #   ifdef Q_WS_X11
424   QApplication::clipboard()->setText(selection, QClipboard::Selection);
425 #   endif
426 //# else
427   QApplication::clipboard()->setText(selection);
428 //# endif
429 }
430
431 //!\brief Convert current selection to human-readable string.
432 QString ChatScene::selectionToString() const {
433   //TODO Make selection format configurable!
434   if(!_isSelecting) return QString();
435   int start = qMin(_selectionStart, _selectionEnd);
436   int end = qMax(_selectionStart, _selectionEnd);
437   if(start < 0 || end >= _lines.count()) {
438     qDebug() << "Invalid selection range:" << start << end;
439     return QString();
440   }
441   QString result;
442   for(int l = start; l <= end; l++) {
443     if(_selectionMinCol == ChatLineModel::TimestampColumn)
444       result += _lines[l]->item(ChatLineModel::TimestampColumn).data(MessageModel::DisplayRole).toString() + " ";
445     if(_selectionMinCol <= ChatLineModel::SenderColumn)
446       result += _lines[l]->item(ChatLineModel::SenderColumn).data(MessageModel::DisplayRole).toString() + " ";
447     result += _lines[l]->item(ChatLineModel::ContentsColumn).data(MessageModel::DisplayRole).toString() + "\n";
448   }
449   return result;
450 }
451
452 void ChatScene::requestBacklog() {
453   static const int REQUEST_COUNT = 500;
454   int backlogSize = model()->rowCount();
455   if(isSingleBufferScene() && backlogSize != 0 && _lastBacklogSize + REQUEST_COUNT <= backlogSize) {
456     QModelIndex msgIdx = model()->index(0, 0);
457     MsgId msgId = model()->data(msgIdx, ChatLineModel::MsgIdRole).value<MsgId>();
458     BufferId bufferId = model()->data(msgIdx, ChatLineModel::BufferIdRole).value<BufferId>();
459     _lastBacklogSize = backlogSize;
460     Client::backlogManager()->requestBacklog(bufferId, REQUEST_COUNT, msgId.toInt());
461   }
462 }
463
464 int ChatScene::sectionByScenePos(int x) {
465   if(x < firstColHandle->x())
466     return ChatLineModel::TimestampColumn;
467   if(x < secondColHandle->x())
468     return ChatLineModel::SenderColumn;
469
470   return ChatLineModel::ContentsColumn;
471 }
472
473 void ChatScene::updateSceneRect(const QRectF &rect) {
474   _sceneRect = rect;
475   setSceneRect(rect);
476 }