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